diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 71eb71905..5c25411c7 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -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,70 @@ 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_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 +173,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 +196,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 +252,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,9 +263,11 @@ 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 \ @@ -245,10 +278,13 @@ jobs: 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,7 +293,9 @@ 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 \ @@ -267,39 +305,69 @@ jobs: 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_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 +375,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 +400,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 diff --git a/AGENTS.md b/AGENTS.md index 89516ec2a..3ab597306 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -167,12 +167,25 @@ 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_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 +204,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 +263,26 @@ 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/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 +296,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 5a367699d..8d9886fdf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -102,6 +102,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 +245,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 +266,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 @@ -551,11 +562,11 @@ 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). +# 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 +587,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 +626,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 +746,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) @@ -836,6 +875,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) @@ -941,6 +993,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 +1111,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) @@ -1195,6 +1269,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 +1294,8 @@ 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_slot67_indirect.cpp tests/desktop_gpu.cpp) add_executable(startup_stream_depth tests/startup_stream_depth.cpp $) target_compile_features(startup_stream_depth PRIVATE cxx_std_17) @@ -1371,6 +1458,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 +1514,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 +1528,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 +1548,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 +1581,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 +1606,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) @@ -1508,11 +1644,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) @@ -1809,6 +1946,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 +2057,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 +2109,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 +2162,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) 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 +2267,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) @@ -2942,6 +3161,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} @@ -3106,6 +3332,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 +3351,10 @@ 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_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 +3398,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 +3429,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 +3503,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 +3538,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 +3559,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 +3587,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 +3633,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 +3648,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,6 +3723,12 @@ 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: 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 a 2D texture (CalculateLevelOfDetail / Unclamped). add_test(NAME startup_gfx2hlsl_image_get_lod_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_image_get_lod_check.py") @@ -3392,6 +3766,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 +3782,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 +3869,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 +3921,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 +3946,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 +3981,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 +4003,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 +4032,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 +4091,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 +4117,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 +4148,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 +4167,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 +4176,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 +4188,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 +4220,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 +4238,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 +4299,10 @@ 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 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 +4312,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 + 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 +4323,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 +4381,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 +4416,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 +4463,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 +4512,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 +4533,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 @@ -3967,11 +4612,45 @@ 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}) + 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} + 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 +4698,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 +4787,14 @@ 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_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 +4807,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 +4830,10 @@ 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. + foreach(gate IN ITEMS gate gate-ring gate-ring-reuse) 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 +4864,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 +4905,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). @@ -4219,6 +4933,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 +4957,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 +5001,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 +5041,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 +5215,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 +6035,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 +6422,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 +7118,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 +7152,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 +7290,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 +7340,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 +7539,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 +7713,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 +7807,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 +7884,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}" @@ -7466,9 +8453,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 +8546,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 +9851,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 +9881,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 +9896,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 +9977,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 +10172,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 +10301,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 +10328,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 +10439,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 +10494,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 +10552,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}) @@ -9721,6 +10788,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 +11057,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 +11198,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 +11268,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 +11295,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 +11312,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 +11339,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 +11354,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 +11424,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 1327cb617..19a646b00 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -42,7 +42,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": "^(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)$" } } }, diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f960f92a1..c3a2bba76 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,7 +27,9 @@ 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. diff --git a/README.md b/README.md index 39a74b438..9b94df39f 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,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 +149,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 +170,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,15 +215,15 @@ 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) | | 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) | @@ -242,7 +246,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 +300,7 @@ 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) | | 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 c84ebab6c..56de8eec6 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -1,5 +1,7 @@ # 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. + ## Desktop culling and front-face winding `raster_winding_warp` and `raster_winding_hardware` draw two mirrored triangles @@ -81,11 +83,35 @@ 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. + +`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 +120,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 +136,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 @@ -189,7 +223,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 +299,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 +430,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 +452,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: @@ -3852,7 +3904,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 +4424,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 +4626,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 @@ -4838,6 +4928,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 +5642,88 @@ 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` adds the negated value); +- `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 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. + +```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 +6073,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 +6099,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 +6416,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 +6482,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 +6540,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 +6594,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 +6755,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 +6794,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 +6816,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 +6984,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 +7053,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. Exactly one must match all 320 words; anything else fails the test. 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 +7922,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 +8169,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 +8409,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 +8776,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) @@ -8675,6 +9176,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 +9697,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 +10161,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 +10193,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 +10266,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 +10297,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 +10319,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 +10547,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. | @@ -13988,6 +14803,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 +14972,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 @@ -14202,11 +15041,28 @@ For binary32 arithmetic and compare sources, the translator reads the inline int `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) +## 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, 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. -`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 @@ -14334,6 +15190,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 +15257,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 +15273,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 +15285,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 +15434,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 +15473,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 +15481,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 +15551,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 @@ -14725,6 +15648,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 +15677,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 +15687,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 +15793,20 @@ 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. + ### Startup compute formatted buffer reads The offline compute translator lowers `buffer_load_format_x`, `_xy`, `_xyz` and `_xyzw` using @@ -14904,6 +15875,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 +15941,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 +15961,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 +16025,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 +16056,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 +16090,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 +16111,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 +16188,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 +16353,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 @@ -15470,11 +16566,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 +16683,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 +16764,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 +16789,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 +16816,43 @@ 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. +### 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 +16861,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 +16894,108 @@ 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. + +The log line `x2w-render compute dispatches: translated , refused , no translation , not modelled ` follows the render totals; "not modelled" 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. + +Measured on three fixture programs. 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 both guard words, 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 +``` + +### 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. A comparison sampler (`smpc`) and the run-time sampler heap table (`smpheap`) are still refused, as "a comparison sampler" and "a sampler from the sampler heap". 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 `smpc` and `smpheap` lines refuse with their reasons and leave 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 +17016,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 +17051,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 +17060,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 +17101,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 +17109,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 +17234,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 +17301,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 +17321,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 +17408,155 @@ 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. diff --git a/docs/experiments/README.md b/docs/experiments/README.md new file mode 100644 index 000000000..5b903b6c2 --- /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/hardware-gtx1080ti.md b/docs/experiments/hardware-gtx1080ti.md new file mode 100644 index 000000000..7db9c0540 --- /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/startup-compute-array-uav.md b/docs/experiments/startup-compute-array-uav.md new file mode 100644 index 000000000..dfd17b2d3 --- /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-gfx2hlsl-pixel-first-lane.md b/docs/experiments/startup-gfx2hlsl-pixel-first-lane.md new file mode 100644 index 000000000..a286b66c9 --- /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-wave-reduce.md b/docs/experiments/startup-gfx2hlsl-wave-reduce.md new file mode 100644 index 000000000..552d3bd60 --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-wave-reduce.md @@ -0,0 +1,91 @@ +# 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 only in a straight-line 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). + +## 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 program with branches, a vertex stage, `s_wqm` before the chain, and `vP` + (which holds the other row) read after the restore before a VALU rewrites 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) and every refusal by name. The same +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 and for the +interleaved pair; 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, signed for unsigned, the lane's own value and the first +lane's value for each operation; 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-mesh57-dead-block-scalar.md b/docs/experiments/startup-mesh57-dead-block-scalar.md new file mode 100644 index 000000000..60491fd08 --- /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 000000000..61ca9cdeb --- /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/non-windows-hosts.md b/docs/non-windows-hosts.md index cf71bc2ca..e868b1f2d 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 1353b96e3..ab8dbd25b 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -118,7 +118,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 +208,22 @@ 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-28` and `x2w-startup-shader-28cs`. +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 +287,67 @@ 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 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 +362,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 @@ -434,8 +557,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. @@ -674,6 +798,8 @@ are not copied. Keep using the package root as `-DataDir`, then run the staged e ``` `run.ps1` copies the stand-ins next to the executable 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`. @@ -1105,7 +1231,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 +1239,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 +1273,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 (` 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 /capture -B `; that project fetches its own dependencies), start `capture -o run.tracy -a 127.0.0.1 -s ` and then the instrumented run. Open the file with the Tracy profiler, or export zone statistics with `csvexport`. @@ -1274,11 +1401,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 @@ -1338,28 +1465,35 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `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_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_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_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{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_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` 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\\x64`, else `PATH`. When none exists it writes `.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_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_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_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_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=` | 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=` | 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 (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=` | 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=`, `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=`, `X2W_DRAW_DUMP_DIR`, `X2W_DRAW_DUMP_PIXEL=,` | 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=` | 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 detached= released=` 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_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=` | 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_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 | @@ -1386,6 +1520,42 @@ 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 [--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=` 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 ` 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 @@ -1425,32 +1595,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 +1632,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 +1713,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 of slot 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__` 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 `, +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_` 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` @@ -1731,6 +2024,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 +2155,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 @@ -1872,7 +2181,7 @@ These are measured on one executable; treat them as hypotheses for others. `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,6 +2197,42 @@ 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 straight-line pixel stage (`s_or_saveexec_b32 sS, -1`, + the identity fill `v_cndmask_b32_e64 vT, , 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. 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) - **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 @@ -1992,14 +2337,43 @@ 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` at its own `u` register, under the lane's exec bit, and the manifest becomes version 2 with a - `uav tex2d table ` 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 tex2d table
` line. The same full mask on `dim:SQ_RSRC_IMG_2D_ARRAY` + uses three address registers, a `RWTexture2DArray` 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`. +- **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. @@ -2511,14 +2885,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 @@ -2613,11 +2991,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 @@ -2823,6 +3203,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 @@ -2961,10 +3355,33 @@ layouts"): ## 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. +`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. diff --git a/src/mesh_shader_pipeline.cpp b/src/mesh_shader_pipeline.cpp new file mode 100644 index 000000000..67cc6993c --- /dev/null +++ b/src/mesh_shader_pipeline.cpp @@ -0,0 +1,385 @@ +#include "mesh_shader_pipeline.h" + +#include +#include +#include +#include +#include + +#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(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 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 +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 serialize_and_create_root( + ID3D12Device* device, + const D3D12_ROOT_SIGNATURE_DESC& desc, + const char* label) { + ComPtr blob; + ComPtr 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(error_blob->GetBufferPointer()), error_blob->GetBufferSize()); + } + throw_if_failed(ser_hr, msg.c_str()); + } + ComPtr root; + throw_if_failed(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)), + label); + return root; +} + +ComPtr upload_typed_buffer( + ID3D12Device* device, + const void* data, + std::size_t byte_size, + const char* label) { + const UINT64 alloc_size = std::max(4, static_cast(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 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 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 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(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(vb_bytes); + res.vbv.StrideInBytes = sizeof(MeshletVertex); + + res.ibv.BufferLocation = res.indices->GetGPUVirtualAddress(); + res.ibv.SizeInBytes = static_cast(ib_bytes); + res.ibv.Format = DXGI_FORMAT_R32_UINT; + + res.meshlet_count = static_cast(data.meshlets.size()); + res.index_count = static_cast(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 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 000000000..984ae323b --- /dev/null +++ b/src/mesh_shader_pipeline.h @@ -0,0 +1,132 @@ +#pragma once + +#include "meshlet_builder.h" + +#include +#include + +#include + +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 +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 root_signature; + PipelineSubobject as; + PipelineSubobject ms; + PipelineSubobject ps; + PipelineSubobject blend; + PipelineSubobject sample_mask; + PipelineSubobject rasterizer; + PipelineSubobject depth_stencil; + PipelineSubobject rtv_formats; + PipelineSubobject dsv_format; + PipelineSubobject sample_desc; + PipelineSubobject topology; +}; + +// Variant without AS subobject (an empty AS subobject is invalid in D3D12). +struct MeshOnlyPipelineStream { + PipelineSubobject root_signature; + PipelineSubobject ms; + PipelineSubobject ps; + PipelineSubobject blend; + PipelineSubobject sample_mask; + PipelineSubobject rasterizer; + PipelineSubobject depth_stencil; + PipelineSubobject rtv_formats; + PipelineSubobject dsv_format; + PipelineSubobject sample_desc; + PipelineSubobject 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 vertices; + Microsoft::WRL::ComPtr indices; + Microsoft::WRL::ComPtr meshlets; + Microsoft::WRL::ComPtr bounds; + Microsoft::WRL::ComPtr unique_vertex_indices; + Microsoft::WRL::ComPtr 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 root_signature_; + Microsoft::WRL::ComPtr pipeline_state_; +}; + +} // namespace x2w::meshlet diff --git a/src/meshlet_builder.cpp b/src/meshlet_builder.cpp new file mode 100644 index 000000000..35c3f271e --- /dev/null +++ b/src/meshlet_builder.cpp @@ -0,0 +1,309 @@ +#include "meshlet_builder.h" + +#include +#include +#include +#include +#include +#include + +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& 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 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& vertices, + std::vector& indices, + float x0, float y0, + float x1, float y1, + float z, + bool front_facing_cw, + const std::array& color) { + const std::uint32_t base = static_cast(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& vertices, + const std::vector& 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 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(out.unique_vertex_indices.size()); + current_primitive_offset = static_cast(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 vertices; + std::vector 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 000000000..fd8870664 --- /dev/null +++ b/src/meshlet_builder.h @@ -0,0 +1,62 @@ +#pragma once + +#include +#include + +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 vertices; + std::vector source_indices; + std::vector meshlets; + std::vector bounds; + std::vector unique_vertex_indices; + std::vector 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& vertices, + const std::vector& 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/shaders/meshlet_pipeline.hlsl b/src/shaders/meshlet_pipeline.hlsl new file mode 100644 index 000000000..d4f969af6 --- /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 g_vertices : register(t0); +StructuredBuffer g_meshlets : register(t1); +StructuredBuffer g_bounds : register(t2); +StructuredBuffer g_unique_vertex_indices : register(t3); +StructuredBuffer g_packed_primitives : register(t4); +RWStructuredBuffer 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 c6c25a4fe..9f3bdaa93 100644 --- a/src/startup_stubs/acphal.cpp +++ b/src/startup_stubs/acphal.cpp @@ -18,12 +18,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 +46,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(virtual_address); + const auto base_addr = reinterpret_cast(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(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 +82,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(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(zero_bytes)); // fresh pages are zero @@ -98,10 +131,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(decommit_end - decommit_begin), MEM_DECOMMIT); } done = true; } @@ -154,8 +196,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(0x80070057); // E_INVALIDARG + } else if (memory) { heap_bytes = bytes; heap_reset(); heap_base = static_cast(memory); @@ -210,7 +256,10 @@ extern "C" __declspec(noinline) long AcpHalAllocateShapeContexts(u64 rcx, u64 rd rollback(); return static_cast(0x8007000E); } - const u64 offset = static_cast(memory - heap_base); + unsigned char* base = nullptr; + u64 total_bytes = 0; + heap_snapshot(base, total_bytes); + const u64 offset = static_cast(memory - base); if (offset > 0xFFFFFFFFull) { heap_give(memory); rollback(); @@ -230,13 +279,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(&hal_connect); - table[2] = reinterpret_cast(&hal_submit); - ready = true; - } + static const auto table = [] { + auto slots = hal_table(std::make_index_sequence<48>{}); + slots[0] = reinterpret_cast(&hal_connect); + slots[2] = reinterpret_cast(&hal_submit); + return slots; + }(); static void* const* const object = table.data(); if (!rcx || !x2w_local::writable(reinterpret_cast(rcx), sizeof(void*))) return static_cast(0x80004003); *reinterpret_cast(rcx) = &object; @@ -247,7 +295,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 +307,33 @@ extern "C" __declspec(noinline) long ApuAlloc(void** virtual_address, std::uint3 const u64 bytes = static_cast(size); u64 align = static_cast(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(!virtual_address ? 0x80004003 : valid ? 0x8007000E : 0x80070057); - if (virtual_address) *virtual_address = memory; - if (memory && apu_address) *apu_address = static_cast(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(0x80004003); // E_POINTER + } else if (!bytes) { + hr = static_cast(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(memory - base); + if (offset > 0xFFFFFFFFull) { + heap_give(memory); + memory = nullptr; + hr = static_cast(0x8007000E); // E_OUTOFMEMORY + } + } else { + hr = static_cast(0x8007000E); // E_OUTOFMEMORY + } + } + if (virtual_ok) *virtual_address = memory; + if (memory && apu_address) *apu_address = static_cast(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, @@ -292,8 +364,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(virtual_address), 0, 0, 0, _ReturnAddress()); - auto* p = static_cast(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 +375,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(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,9 +390,8 @@ 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(virtual_address), 0, 0, 0, _ReturnAddress()); - auto* p = static_cast(virtual_address); - const std::uint32_t result = heap_base && p >= heap_base && p < heap_base + heap_bytes - ? static_cast(p - heap_base) : 0; + u64 offset = 0; + const std::uint32_t result = in_apu_range(virtual_address, offset) ? static_cast(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; diff --git a/src/startup_stubs/buffer_format_word3.h b/src/startup_stubs/buffer_format_word3.h index 771ec1dd8..072ae1aed 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/console_mode.h b/src/startup_stubs/console_mode.h new file mode 100644 index 000000000..7bc01ac3f --- /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= (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 +#include + +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(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(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(data), bytes); +} + +} // namespace x2w_console_mode diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 6f92733f0..ff63b03c3 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -61,6 +61,45 @@ std::vector& view_materialized() { static std::vector& view_ids() { static std::unordered_map 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(view_records().size()), static_cast(view_records().capacity()), + static_cast(view_ids().size()), static_cast(view_ids().bucket_count()), + c.grows_records, c.grows_ids, c.missed); + return n < 0 ? 0 : (std::min)(static_cast(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 +120,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(resource)); + if (slot == 19 && counter) retire_add_view_ref(reinterpret_cast(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(resource)); + if (slot == 19 && counter) retire_release_view_ref(reinterpret_cast(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(resource), why); + if (slot == 19 && counter) retire_leave_class(reinterpret_cast(counter), why); +} + constexpr std::uint32_t view_token_magic = 0x56573258; // "X2WV" bool title_backed(u64 title_handle, u64 bytes) @@ -92,6 +163,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(title_handle), 32)) + return live; + std::uint32_t words[8]; + std::memcpy(words, reinterpret_cast(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, @@ -277,6 +368,62 @@ void note_heap(Wrapper* w, UINT type, UINT count, UINT logical_count, UINT incre static_cast(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 +void reserve_one_view_entry(std::vector& 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(record.dest_title), token_bytes)) + std::memset(reinterpret_cast(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 +453,53 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ record.id = found->second; } else { record.id = static_cast(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(view_ids().size() + 1) / static_cast(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(resource)); - if (prev && prev - 1 < view_records().size() && view_records()[prev - 1].slot == 18 && view_materialized()[prev - 1]) - retire_release_view_ref(reinterpret_cast(view_records()[prev - 1].resource)); + if (materialized) view_refs_add(static_cast(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(resource), RetireLeft::view); + } else if (view_slot_names_resource(static_cast(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(slot), resource, counter, RetireLeft::view); } ReleaseSRWLockExclusive(¬e_lock); const std::size_t token_bytes = slot == 22 ? x2w_startup::title_sampler_stride : 32u; @@ -340,34 +519,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(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(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(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(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 000000000..7115c2850 --- /dev/null +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -0,0 +1,517 @@ +// 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 .txt (`stage cs`) and +// .cs.cso. Bound from the compute tables recorded by slot 35: raw buffers (`srv buf table ` +// inputs, `uav table ` outputs) named by hardware buffer descriptors, and 2D textures +// (`srv tex2d table ` inputs, `uav tex2d/tex2da float table channels 4` outputs) named +// by the token of a view the title created (device slots 18 and 19). `smp` 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). + +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; + bool array = false; + }; + u64 key = 0; + int state = 0; // 0 not loaded, 1 ready, 2 unavailable + ULONGLONG retry_manifest_at = 0; // only an absent manifest can become ready later + std::vector uds, srvs, uavs; + x2w_startup::TranslatedSamplers samplers; // static ones only + x2w_startup::ComPtr root; + x2w_startup::ComPtr pipeline; + const char* unmodelled = nullptr; // why a manifest that exists cannot be used + 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 + 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(); + } + } +}; + +// Formats a `float` typed output may be viewed with: the program stores float4. +bool float_output_format(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_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_B8G8R8A8_UNORM: + return true; + default: + return false; + } +} +std::unordered_map& compute_translations() { static std::unordered_map m; return m; } +LONG compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled; + +// 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; + wchar_t path[MAX_PATH]; + std::string manifest; + if (!cache_path(path, L"", tr.key, L".txt") || !read_text(path, manifest)) { + tr.retry_manifest_at = GetTickCount64() + 1000; + return nullptr; + } + tr.retry_manifest_at = 0; + 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; + } + 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(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(s + 1); + return ComputeTranslation::root_constant; + }; + 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 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 tex2d float table %d %d channels 4%n", &i, &a, &b, &used) == 3 && whole() && + i == tr.uavs.size()) + tr.uavs.push_back({a, b, true}); + else if (std::sscanf(line.c_str(), "uav %u tex2da float table %d %d channels 4%n", &i, &a, &b, &used) == 3 && whole() && + i == tr.uavs.size()) { + tr.uavs.push_back({a, b, true}); + tr.uavs.back().array = true; + } + else if (std::sscanf(line.c_str(), "srv %u tex2d table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) + tr.srvs.push_back({a, b, true}); + // A static sampler, plain (smp) or with the descriptor's LOD clamp (smpl), decoded as the draw path does. + // Not modelled here: comparison samplers (smpc) and the run-time sampler heap table (smpheap). + else if (line.rfind("smpc", 0) == 0) return "a comparison sampler"; + 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) && 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 2D texture" + : line.rfind("uav", 0) == 0 ? "an output that is not a raw table buffer or a 2D/2D-array float texture" + : 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(ud.a) >= slots.size() || slots[ud.a].texture)) + return "an entry value names a descriptor that is not a buffer input or output"; + } + x2w_startup::ComPtr code; + if (!cache_path(path, L"", tr.key, L".cs.cso") || FAILED(D3DReadFileToBlob(path, &code))) return "no compiled program"; + // 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(tr.uds.empty() ? 1 : tr.uds.size()), + static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size())))) + return "root signature creation failed"; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = tr.root.Get(); + desc.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (FAILED(device_of(the_device)->CreateComputePipelineState(&desc, IID_PPV_ARGS(&tr.pipeline)))) + return "pipeline creation failed"; + tr.state = 1; + 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; +} + +// 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; + unsigned char desc[40]; // a texture view's description, as the title gave it with a desktop format + Wrapper* wrapper; + std::uint32_t words[4]; // a buffer's descriptor words as it was bound from, and its stride + UINT stride; + } views[40]{}; + static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == 40 && sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == 40); + 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->retry_manifest_at && GetTickCount64() >= tr->retry_manifest_at)) { + 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(); + 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)) { + 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 (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(slot.word_byte), 16); + if (!table_entry || !x2w_local::readable(reinterpret_cast(table_entry), 16)) { + reason = "a table descriptor is not bound"; + break; + } + std::memcpy(words, reinterpret_cast(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(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 ? 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(slot.b), slot.texture ? 32 : 16); + const std::size_t entry_bytes = slot.texture ? 32 : 16; + if (!entry || !x2w_local::readable(reinterpret_cast(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(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(record.resource)) : nullptr; + ID3D12Resource* const texture = !wrapper || wrapper->own().kind != resource_kind ? nullptr + : output ? static_cast(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 >= sizeof(desc); + if (described) std::memcpy(&desc, record.desc, sizeof(desc)); + if (desc.Format) desc.Format = desktop_format(desc.Format); + words[3] = static_cast(desc.Format ? desc.Format : resource.Format) | static_cast(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 (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}; + std::memcpy(views[i].desc, &desc, sizeof(desc)); + views[i].wrapper = wrapper; + continue; + } + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + const bool described = record.desc_bytes >= sizeof(desc); + if (described) std::memcpy(&desc, record.desc, sizeof(desc)); + if (desc.Format) desc.Format = desktop_format(desc.Format); + const DXGI_FORMAT format = desc.Format ? desc.Format : resource.Format; + words[3] = static_cast(format) | static_cast(desc.ViewDimension) << 16; + if (!known || record.slot != 19) reason = "an output texture entry is not the token of an unordered access view"; + 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.array) { + // 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 && !float_output_format(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}; + std::memcpy(views[i].desc, &desc, sizeof(desc)); + views[i].wrapper = wrapper; + continue; + } + if (!output) { + // Each condition of a complete GPU-backed buffer range has its own reason. + 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) // 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; + } + // An output is written by the GPU: only a placed buffer that aliases the title's memory shows the result + // to the title. shortcut: view tokens and copied placements are refused, add them with their first user. + const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); + const UINT stride = (words[1] >> 16) & 0x3fff; + const u64 bytes = u64{stride ? stride : 1} * words[2]; + const auto placed = words[0] == view_token_magic || !bytes || bytes % 4 || bytes > (16u << 20) + ? PlacedVertexView{} : placed_buffer_range(self->own().list_device, address, bytes); + const ResourceInfo* info = placed.alias ? resource_info(placed.owner) : nullptr; + const u64 offset = placed.alias ? address - reinterpret_cast(placed.owner->own().title_memory) : 0; + if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON || offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT || + !(placed.alias->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + reason = "an output is not an aliased placed buffer range with 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"; + views[i] = {placed.alias, offset, bytes, true}; + std::memcpy(views[i].words, words, sizeof(views[i].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(count); + UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(n))) % draw_heap_size; + if (first + n > draw_heap_size) { + first = 0; + InterlockedExchange(&draw_heap_cursor, static_cast(n)); + } + D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + std::size_t{first} * draw_heap_increment}; + for (std::size_t i = 0; i < count; ++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 ? reinterpret_cast(view.desc) : nullptr, dest); + continue; + } + if (i < inputs) { + if (view.transition) require_state(self, view.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + buffer_view(dest, view.resource, view.offset, static_cast(view.bytes)); + continue; + } + require_state(self, view.resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (view.texture) { + device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, + view.described ? reinterpret_cast(view.desc) : 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(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(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 reasons; + std::vector 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(); } diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 16aa47bd0..7fbce0caf 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -9,6 +9,146 @@ // 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 or RWTexture2DArray at u, whose descriptor is at byte O of the title's +// root table P. Only that form is read; 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 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 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(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] == "raw" || w[2] == "table") return "buffer view (raw uav) is not bound"; + if (w[2] != "tex2d" && w[2] != "tex2da") return "only tex2d and tex2da views are bound"; + out.array = w[2] == "tex2da"; + 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; + return nullptr; +} + +// Formats a RWTexture2D 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 enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; @@ -16,6 +156,7 @@ struct Translation { int state = 0; // 1 ready, 2 unavailable ULONGLONG retry_manifest_at = 0; // Only an absent manifest can become ready on a later draw. std::vector srvs; + std::vector uavs; // manifest 'uav N tex2d table P O' (#1996 F): u0.. after the SRVs std::vector uds; x2w_startup::TranslatedSamplers samplers; x2w_startup::ExportWriteMasks write_masks; // manifest 'wmask': channels each export leaves unwritten (#1674) @@ -168,14 +309,11 @@ 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.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; @@ -203,11 +341,17 @@ 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; @@ -226,7 +370,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) 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(tr.uds.size()), - static_cast(tr.srvs.size()), tr.samplers, &tr.root); + static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size())); if (FAILED(hr)) { log("x2w-draw root signature for %016llx failed 0x%08lx", tr.key, static_cast(hr)); return; @@ -234,8 +378,8 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) tr.state = 1; 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 textures, %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); } // draw_lock held. Both pipeline forms use the same request writer and shader cache. @@ -244,7 +388,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* { // 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"; + constexpr char revision[] = "x2w-startup-shader-28"; const u64 seed = fnv_bytes(revision, sizeof(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. @@ -314,10 +458,11 @@ LONG pointer_like_qwords(const std::vector& blob) SRWLOCK compute_request_lock = SRWLOCK_INIT; std::unordered_set& compute_keys_seen() { static std::unordered_set s; return s; } -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 +501,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,7 +509,7 @@ void publish_compute_request(const void* desc) std::vector 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 + constexpr char compute_revision[] = "x2w-startup-shader-28cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); @@ -392,6 +537,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. @@ -427,7 +573,7 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo 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"; + constexpr char revision[] = "x2w-startup-mesh-57-3"; 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 written; @@ -451,7 +597,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"; @@ -936,8 +1088,7 @@ std::unordered_map& 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. @@ -1089,14 +1240,14 @@ bool prepare_draw_sampler_heap(Pass& pass, ID3D12GraphicsCommandList* list, bool // 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 content; }; std::unordered_map& frame_copies() { static std::unordered_map 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 +1258,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 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; } @@ -1292,19 +1454,20 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) 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(bytes), &offset); - if (!rows) { + rows = reserve_upload_ring(self, static_cast(bytes), &offset, &chunk); + if (!rows || !chunk) { state.done = false; return false; } std::memset(rows, 0, static_cast(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); + plan.upload(list, texture, owned.cpu ? owned.resource.Get() : chunk, mips, slices, slice, i, offset); } } if (dedicated) { @@ -1317,36 +1480,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(bytes), &offset); - if (!rows) { + ID3D12Resource* chunk = nullptr; + auto* rows = reserve_upload_ring(self, static_cast(bytes), &offset, &chunk); + if (!rows || !chunk) { state.done = false; return true; } std::memset(rows, 0, static_cast(bytes)); chain.copy(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(bytes), &offset); - if (!rows) { + ID3D12Resource* chunk = nullptr; + auto* rows = reserve_upload_ring(self, static_cast(bytes), &offset, &chunk); + if (!rows || !chunk) { state.done = false; return true; } std::memset(rows, 0, static_cast(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(bytes), &offset); - if (!rows) { + auto* const rows = reserve_upload_ring(self, static_cast(bytes), &offset, &chunk); + if (!rows || !chunk) { state.done = false; return true; } @@ -1354,11 +1520,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(level.row_bytes)); - } else if (!ring_copy(reinterpret_cast(memory) + stride * s + fp.Offset, static_cast(bytes), &offset)) { + } else if (!ring_copy(self, reinterpret_cast(memory) + stride * s + fp.Offset, static_cast(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 +1555,48 @@ LONG draw_dump_frame() }(); return frame; } +struct DrawDumpPixel { + bool enabled{}; + UINT x{}, y{}; +}; +// X2W_DRAW_DUMP_PIXEL=,: 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(); + const DrawDumpPixel pixel = draw_dump_pixel(); if (!wanted || frame_number < wanted || frame_number > wanted + 1 || !pass.target0 || draw_dumps().full()) 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,13 +1617,22 @@ 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() @@ -1437,6 +1642,30 @@ void draw_dump_flush() if (completed.empty()) return; char folder[MAX_PATH] = "."; GetEnvironmentVariableA("X2W_DRAW_DUMP_DIR", folder, sizeof(folder)); + if (draw_dump_pixel().enabled) { + static std::vector 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(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(dump.index); @@ -1574,6 +1803,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 +1954,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(); } @@ -1744,12 +1967,20 @@ struct IndirectBufferView { // 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) { - 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 +1996,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor std::memcpy(&view, record.desc, 40); owner = as_wrapper(reinterpret_cast(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,57 +2004,81 @@ 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(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(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 {}; + 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; 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(owner->own().real); offset = address - reinterpret_cast(owner->own().title_memory); - if (!placed.alias && (!native || !list_copied_gpu_range(self, native, offset, bytes))) return {}; + if (!placed.alias && (!native || !list_copied_gpu_range(self, native, offset, bytes))) + return refuse("an input is in a placed buffer that does not alias title memory"); + } else if (own_memory) { + native = static_cast(owner->own().real); } else if (owner && !owner->own().title_memory) { native = static_cast(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 % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) return refuse("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 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 {}; + offset > desc.Width || bytes > desc.Width - offset) return refuse("an input range is outside its desktop buffer"); return {native, offset, bytes, stride, upload}; } @@ -1832,6 +2087,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,26 +2132,89 @@ bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedB if (!entry || !x2w_local::readable(reinterpret_cast(entry), sizeof(descriptor.words))) return refuse(ud.a, "missing hardware descriptor"); std::memcpy(descriptor.words, reinterpret_cast(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 textures 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]; + 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(entry), 32)) return refuse(i, "table entry unreadable", entry); + std::memcpy(words, reinterpret_cast(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(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(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 = 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(desc.DepthOrArraySize), static_cast(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(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 > 4 || 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(srv.b), 32); + std::uint32_t srv_words[8] = {}; + if (!srv_entry || !x2w_local::readable(reinterpret_cast(srv_entry), 32)) continue; + std::memcpy(srv_words, reinterpret_cast(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; } @@ -1917,6 +2258,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,6 +2286,14 @@ 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; if (indirect && indexed_rect && !pipeline) { @@ -1952,23 +2307,63 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + PixelUavBinding uav_bindings[pixel_uav_limit]; + if (!resolve_pixel_uavs(*tr, pass, uav_bindings)) { + ReleaseSRWLockExclusive(&draw_lock); + return false; + } const UINT n = static_cast(tr->srvs.size()); - UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(n))) % draw_heap_size; - if (first + n > draw_heap_size) { + const UINT views = n + static_cast(tr->uavs.size()); // the SRVs, then the UAVs, in one table + UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(views))) % draw_heap_size; + if (first + views > draw_heap_size) { first = 0; - InterlockedExchange(&draw_heap_cursor, static_cast(n)); + InterlockedExchange(&draw_heap_cursor, static_cast(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; + 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(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(placed.alias))) { + live_indices = {gpu + offset, static_cast(index_total), pass.ib.Format}; + live_index_resource = placed.alias; + } + } + } INT vertex_first = indexed ? 0 : static_cast(start); UINT vertex_count = indexed ? 0 : count; - if (indices_ok) { + if (indices_ok && !live_index_resource) { std::uint32_t low = ~0u, high = 0; for (UINT k = 0; k < count; ++k) { const std::uint32_t value = index_bytes == 2 ? reinterpret_cast(index_address)[k] @@ -2000,6 +2395,9 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI address += skip; bytes = static_cast(wanted < bytes - skip ? wanted : bytes - skip); } + if (live_index_resource && placed.alias) { + retain_with_recording(self, x2w_startup::ComPtr(placed.alias)); + } } else if (srv.source == 2 && srv.a < 16) { address = pass.root_address[srv.a]; bytes = readable_window(address, 0x10000); @@ -2058,7 +2456,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); @@ -2204,12 +2608,13 @@ 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; + auto* target = readable_window(address, bytes) >= bytes ? reserve_upload_ring(self, padded, &offset, &chunk) : nullptr; if (target) { std::memcpy(target, reinterpret_cast(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,7 +2623,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI buffer_view(dest, placed.alias, address - reinterpret_cast(placed.owner->own().title_memory), bytes); continue; } - bool have = address && bytes && readable_window(address, bytes) >= bytes && frame_copy(address, bytes, &offset); + ID3D12Resource* chunk = nullptr; + bool have = address && bytes && readable_window(address, bytes) >= bytes && frame_copy(self, address, bytes, &offset, &chunk); // 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. @@ -2236,9 +2642,9 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI for (int k = 0; k < 64; ++k) identity[k] = (k % 16) % 5 == 0 ? 1.0f : 0.0f; address = reinterpret_cast(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 +2654,22 @@ 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); + 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(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(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] = {}; @@ -2303,8 +2725,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI pass.bound_sampler_heap = samplers; } list->SetGraphicsRoot32BitConstants(0, static_cast(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,11 +2743,15 @@ 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(bytes), - index_bytes == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; + ID3D12Resource* index_chunk = nullptr; + auto view = live_indices; + if (live_index_resource) { + require_state(self, live_index_resource, D3D12_RESOURCE_STATE_INDEX_BUFFER); + } else if (indices_ok && frame_copy(self, index_address, index_total, &offset, &index_chunk) && index_chunk) { + view = {index_chunk->GetGPUVirtualAddress() + offset, static_cast(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); @@ -2381,19 +2807,24 @@ 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; + x2w_startup::ViewTable heap_records; + x2w_startup::ViewHeapSelection view_heaps; 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(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(heaps[i]) && + heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + heap_records = x2w_startup::resolve_view_table(heap.desktop_gpu, heap.title_cpu, heap.logical_count, + heap.increment, heap.desktop_gpu); if (heap.wrapper == reinterpret_cast(heaps[i]) && heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER && heap.desktop_gpu) source = {static_cast(heap.title_sampler_cpu), heap.count}; @@ -2402,13 +2833,13 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* 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.title_view_heap = heap_records; } // 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 +2877,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 +2903,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(((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 673084c38..1252190e8 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -258,7 +258,8 @@ 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; @@ -350,7 +351,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 +412,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(page_start); D3D12_RESOURCE_DESC rdesc{}; rdesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; @@ -538,6 +540,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(address); resource->own().tiled_address_srv = true; note_resource(resource, &desc, bytes); diff --git a/src/startup_stubs/d3d12_present.inl b/src/startup_stubs/d3d12_present.inl index 58bec8cf4..40ff3f6a5 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 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(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(p.width), static_cast(p.height), 0, 1}; - const D3D12_RECT scissor{0, 0, static_cast(p.width), static_cast(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 278f27580..31bbee990 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 detached= released= +// 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= disables the detach of cache (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 + +#include +#include + 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(sizeof(line)) ? length : static_cast(sizeof(line)) - 1; + WriteFile(GetStdHandle(STD_ERROR_HANDLE), line, static_cast(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 f92272d09..56d453557 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -21,6 +21,7 @@ #include "startup_stubs/overlay_window.h" #include "startup_stubs/draw_bmp.h" #include "startup_stubs/draw_dump_tracking.h" +#include "startup_stubs/pixel_history.h" #include "startup_stubs/translated_sampler_bindings.h" #include "startup_stubs/export_write_mask.h" #include "startup_stubs/depth_state_apply.h" @@ -29,11 +30,13 @@ #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/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 #include "startup_stubs/derived_blend.h" #include "startup_stubs/placement_publish.h" @@ -48,13 +51,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 #include "command_list_slot_names.h" @@ -63,6 +70,7 @@ #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" @@ -163,14 +171,13 @@ 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 chunks referenced by this recording, including while closed. bool list_close_failed; // Desktop Reset repeats a failed Close result indefinitely. 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. @@ -182,6 +189,10 @@ struct alignas(16) WrapperOwn { 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,10 +468,22 @@ u64 unwrap(u64 value) return w ? reinterpret_cast(w->own().real) : value; } +volatile LONG wraps_to_fail; // fixture-only, set by x2w_d3d12_fail_wraps +constexpr u64 out_of_memory = static_cast(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(_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(block + sizeof(WrapperOwn)); w->vtable = tables[kind]; @@ -469,7 +492,13 @@ Wrapper* wrap(IUnknown* real, Kind kind) w->own().kind = kind; if (kind == fence_kind && real) w->own().completed = static_cast(static_cast(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 +829,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 +906,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(*out), requested_format); Wrapper* child = wrap(static_cast(*out), kind); + if (!child) { + static_cast(*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(args[0]), @@ -985,6 +1024,7 @@ 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_upload_recording(Wrapper* list); void retire_discard_holds(Wrapper* list); void retire_note_submission(ID3D12CommandQueue* queue, const std::vector& lists); void drain_retired_resources(); @@ -1008,6 +1048,7 @@ ULONG __stdcall release(Wrapper* self) linear_buffers().retire(static_cast(self->own().real)); } if (self->own().kind == list_kind && self->own().real) { + release_upload_recording(self); discard_mesh_lease_recording(static_cast(self->own().real)); retire_drop_recording(self); } @@ -1043,6 +1084,10 @@ HRESULT __stdcall device_create_command_queue(Wrapper* self, const D3D12_COMMAND desc->Priority, desc->Flags, desc->NodeMask, text, static_cast(hr)); if (FAILED(hr)) return hr; *out = wrap(queue, queue_kind); + if (!*out) { + queue->Release(); + return E_OUTOFMEMORY; + } register_retire_queue(static_cast(*out)); return S_OK; } @@ -1067,6 +1112,10 @@ HRESULT __stdcall device_create_command_queue_x(Wrapper* self, const D3D12_COMMA desc->Type, desc->Priority, desc->Flags, desc->NodeMask, text, static_cast(hr)); if (FAILED(hr)) return hr; *out = wrap(queue, queue_kind); + if (!*out) { + queue->Release(); + return E_OUTOFMEMORY; + } register_retire_queue(static_cast(*out)); return S_OK; } @@ -1163,7 +1212,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(self, reinterpret_cast(desc), root, iid, out, 0, 0, 0, 0); if (SUCCEEDED(static_cast(result)) && out && desc && root && desc->NumArgumentDescs > 1) { @@ -1216,7 +1265,7 @@ u64 __stdcall device_create_command_signature(Wrapper* self, const D3D12_COMMAND for (UINT i = 0; i < desc->NumArgumentDescs; ++i) { if (static_cast(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; } } } @@ -1408,9 +1457,18 @@ struct TitleAllocator { SRWLOCK allocator_lock = SRWLOCK_INIT; std::unordered_map title_allocators; std::unordered_map list_recordings; // list -> allocator holding its recording -std::unordered_map> queue_submits; +std::unordered_map> queue_submits; +std::vector upload_chunks; // allocator_lock also protects recording holds and queue fence values + LONG allocator_swaps, allocator_creates; +void release_upload_recording(Wrapper* list) +{ + AcquireSRWLockExclusive(&allocator_lock); + discard_upload_chunks(list->own().upload_chunks, upload_chunks.data()); + ReleaseSRWLockExclusive(&allocator_lock); +} + // allocator_lock held. TitleAllocator& title_allocator(Wrapper* allocator) { @@ -1482,6 +1540,39 @@ 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 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: 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(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) { @@ -1571,7 +1662,9 @@ bool submit_fence_fails() // signalled, the work is on the GPU all the same: the allocators are marked untracked instead. void note_submits(ID3D12CommandQueue* queue, const std::vector& 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 +1672,12 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector& 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 bool signaled = fence && SUCCEEDED(queue->Signal(fence, value + 1)); + if (signaled) ++value; + submit.submitted(chunks, signaled); + if (signaled) { for (Wrapper* list : lists) { const auto found = list_recordings.find(list); if (found == list_recordings.end()) continue; @@ -1713,6 +1810,7 @@ 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()); state.list_uploads = nullptr; state.list_scratch = nullptr; state.list_ready = false; @@ -1754,6 +1852,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()); if (const auto found = list_recordings.find(self); found != list_recordings.end() && found->second) found->second->close_failed = true; } @@ -1808,8 +1907,22 @@ 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) -{ +// 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 `; 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); + }; static ID3D12CommandAllocator* allocator; static ID3D12GraphicsCommandList* list; static ID3D12Fence* fence; @@ -1825,7 +1938,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 +1969,8 @@ 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(hr)); + std::snprintf(failure, sizeof(failure), "readback setup failed 0x%08lx", static_cast(hr)); + report_failure(); return; } transition(list, surface, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); @@ -1873,32 +1988,36 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) queue->Signal(fence, ++fence_value); fence->SetEventOnCompletion(fence_value, event); if (WaitForSingleObject(event, 3000) != WAIT_OBJECT_0) { - std::snprintf(shown_note, sizeof(shown_note), "readback timed out"); + std::snprintf(failure, sizeof(failure), "readback timed out"); + report_failure(); return; } void* mapped = nullptr; const D3D12_RANGE range{0, static_cast(total)}; if (FAILED(readback->Map(0, &range, &mapped))) return; - AcquireSRWLockExclusive(&shown_lock); - shown_pixels.resize(shown_width * shown_height); - std::uint64_t sum = 0; + 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(mapped) + footprint.Offset + static_cast(y) * desc.Height / shown_height * footprint.Footprint.RowPitch; for (int x = 0; x < shown_width; ++x) { const unsigned char* texel = row + static_cast(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=: 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(desc.Width), height = desc.Height; std::vector file(54 + std::size_t{width} * height * 4); const std::uint32_t header[] = {static_cast(file.size()), 0, 54, 40, width, static_cast(-static_cast(height)), @@ -1921,6 +2040,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 +2113,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 parameters; UINT heap_flags = 0; @@ -1994,8 +2126,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(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,7 +2255,7 @@ 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, + bool& compute, IndirectGraphicsPipeline& graphics, ID3D12RootSignature*& pipeline_root, ID3D12RootSignature* cached_root = nullptr) { const bool cached_mesh = cached_root != nullptr; @@ -2283,6 +2417,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(root->own().real); if (pipeline && (vertex || mesh) && (pixel || cached_mesh)) { graphics = {cached_mesh ? cached_root : static_cast(root->own().real), targets.RTFormats[0], mesh, cached_mesh}; @@ -2297,29 +2433,44 @@ 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) +// 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. + +UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) { - 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) { + constexpr u64 max_alloc_bytes = max_upload_ring_bytes / 4; + UploadReservation reservation; + if (bytes == 0 || bytes > max_alloc_bytes) return reservation; + const u64 rounded = (static_cast(bytes) + 511) & ~u64{511}; + + auto& chunks = upload_chunks; + static unsigned active = 0; + static u64 total_bytes = 0; + + AcquireSRWLockExclusive(&allocator_lock); + const auto finish = [&](unsigned index) { + active = index; + chunks[index].hold(list->own().upload_chunks, index); + ReleaseSRWLockExclusive(&allocator_lock); + return reservation; + }; + if (!chunks.empty()) { + reservation = reserve_upload_chunk(chunks[active], rounded); + if (reservation.mapped) return finish(active); + } + + const u64 remaining = total_bytes < max_upload_ring_bytes ? max_upload_ring_bytes - total_bytes : 0; + if (rounded <= remaining) { + u64 chunk_bytes = chunks.empty() ? 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 +2478,71 @@ 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(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(base), chunk_bytes, 0}); + total_bytes += chunk_bytes; + reservation = reserve_upload_chunk(chunks.back(), rounded); + return finish(static_cast(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(InterlockedExchangeAdd64(&cursor, static_cast(rounded))) % ring_bytes; - if (start + rounded > ring_bytes) start = static_cast(InterlockedExchangeAdd64(&cursor, static_cast(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) return finish(index); + } + + for (unsigned index = 0; index < chunks.size(); ++index) { + reservation = reuse_upload_chunk(chunks[index], index, rounded, queue_submits); + if (reservation.mapped) return finish(index); + } + + ReleaseSRWLockExclusive(&allocator_lock); + static LONG refused; + if (first_calls(refused, 8)) + log("x2w-draw upload ring reservation refused: no unused capacity"); + return reservation; +} + +unsigned char* reserve_upload_ring(Wrapper* list, std::size_t bytes, u64* offset, ID3D12Resource** resource) +{ + if (resource) *resource = nullptr; + if (offset) *offset = 0; + const UploadReservation reservation = reserve_upload_ring(list, bytes); + if (!reservation.mapped) return nullptr; + if (offset) *offset = reservation.offset; + if (resource) *resource = reservation.resource; + return reservation.mapped; } -bool ring_copy(u64 title_address, std::size_t bytes, u64* offset) +bool ring_copy(Wrapper* list, u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** resource = nullptr) { - auto* dest = reserve_upload_ring(bytes, offset); + auto* dest = reserve_upload_ring(list, bytes, offset, resource); if (!dest) return false; std::memcpy(dest, reinterpret_cast(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 +2569,13 @@ struct Pass { ID3D12RootSignature* compute_root = nullptr; // latest guest root if it was forwarded x2w_startup::ComPtr desktop_compute_root; // last root actually set on this recording std::array 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 desktop_compute_root_uavs{}; const std::vector* compute_params = nullptr; std::unique_ptr 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; @@ -2405,9 +2596,12 @@ struct Pass { x2w_startup::ViewTable view_tables[16]{}; x2w_startup::ComputeTables compute_tables; // slot 35, read by a Dispatch handler u64 source_view_heap = 0; + x2w_startup::ViewTable title_view_heap; // slot 32: the title memory of the list's view heap (heap records) 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) + 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,6 +2614,8 @@ 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; std::unique_ptr sampler_snapshot; @@ -2560,6 +2756,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(w->own().real)); @@ -2599,28 +2796,93 @@ 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_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(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(); 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); } } +// 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, 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 @@ -2761,6 +3023,13 @@ 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); namespace indirect_other_refusal_code { @@ -2796,6 +3065,7 @@ 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"; @@ -2803,6 +3073,13 @@ constexpr const char* count_not_common_state = "count_not_common_state"; 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. void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, void* count_buffer, u64 count_offset) @@ -2855,6 +3132,7 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, const bool graphics = indexed || mesh || command == IndirectCommand::draw; Pass& pass = pass_of(self); refusal_pipeline = pass.pipeline; + 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; @@ -2902,6 +3180,17 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, 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 +3207,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 +3241,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(buffer->own().real); + if (translated_compute) { + const TranslatedDispatch dispatch{{}, static_cast(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(kind)]); + return; + } IndirectIndexView index_view; if (indexed) { auto view = pass.ib; @@ -3032,8 +3330,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 @@ -3063,6 +3360,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 +3381,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(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(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(pass.pipeline->own().real)); + restore_compute_root(pass, list); + const auto first = x2w_startup::SplitIndirectDispatch::rewritten_offset(count, stride); + auto* command = static_cast(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(kind)]); + return; } if (!leased_arguments && !rect_list) { require_state(self, resource, argument_state); @@ -3392,6 +3722,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 +3817,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; @@ -3534,9 +3868,11 @@ void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 add 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; } } @@ -3560,7 +3896,7 @@ void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) 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]; @@ -3589,6 +3925,34 @@ 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); + if (list && pass.pipeline && pass.pipeline->own().compute_request_key) { + record_translated_dispatch(self, {{x, y, z}}); + 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(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); // List slot 12, DrawInstanced. @@ -3642,6 +4006,7 @@ std::unordered_map& 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" @@ -3977,18 +4342,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 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(a) = value; - return reinterpret_cast(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(result) = value; + return reinterpret_cast(result); + } std::uint64_t bits = 0; static_assert(sizeof(T) <= sizeof(bits)); std::memcpy(&bits, &value, sizeof(T)); @@ -4067,6 +4433,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 +4445,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(title_memory), 0, MEM_RELEASE); + heap->Release(); + return E_OUTOFMEMORY; + } if (title_memory) { w->own().title_cpu = title_memory; AcquireSRWLockExclusive(&descriptor_lock); @@ -4095,6 +4467,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(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 +4510,26 @@ template __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(a), RetireLeft::view); - if constexpr (N == 19) retire_leave_class(reinterpret_cast(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(a), RetireLeft::view); + if constexpr (N == 19) retire_leave_class(reinterpret_cast(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(a), RetireLeft::view); return 0; @@ -4124,16 +4542,72 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) described_bytes, title_dest, args[D], materialized); }; const char* skip = nullptr; + bool default_view = false; + bool uav_denied = false; // a UAV of a resource without unordered access: recorded as not created, as before #2649 if (N == 17) skip = "constant buffer view (title GPU address)"; if (N >= 18 && N <= 21 && args[0]) { const UINT flags = reinterpret_cast(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"; + uav_denied = 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(described), 8)) { + std::memcpy(&view_dimension, reinterpret_cast(described) + 4, sizeof(view_dimension)); + const D3D12_RESOURCE_DESC resource_desc = reinterpret_cast(args[0])->GetDesc(); + const auto dimension = static_cast(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(resource_desc.Format), mode)) + default_view = true; + else if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast(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(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); + } + } } + // 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(args[1]), 8)) + std::memcpy(&requested, reinterpret_cast(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(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 (uav_denied && !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 +4629,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 +4657,8 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) *reinterpret_cast(b), null_rtv)) args[1] = reinterpret_cast(&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 +4675,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(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(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(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(rd.Width), rd.Height, rd.DepthOrArraySize, rd.MipLevels, rd.Format, + rd.SampleDesc.Count, static_cast(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, @@ -4321,6 +4810,10 @@ HRESULT __stdcall device_create_command_list_x(Wrapper* self, const void* desc, allocator, pso, text, static_cast(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 +4853,70 @@ struct ExistingHeap { }; std::vector> 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 resource; + }; + using iterator = std::array::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 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 +4940,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 resource; }; - static std::array 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 +4970,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(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 +5045,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 +5060,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(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 +5076,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS ? static_cast(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(address) - static_cast(base); + UINT64 offset = static_cast(address) - static_cast(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 +5113,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(address) - static_cast(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 +5149,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)) { @@ -4684,8 +5274,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(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 +5451,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 +5460,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 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; - 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 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(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(h.desktop_cpu + u64{i} * h.increment)}); - h.shadow[i] = 0; - retire_release_view_ref(reinterpret_cast(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(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(token), 32)) continue; - std::uint32_t words[2]; - std::memcpy(words, reinterpret_cast(token), sizeof(words)); - if (words[0] == view_token_magic && words[1] == slot.id) - InterlockedCompareExchange(reinterpret_cast(token), 0, static_cast(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 +5494,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 +5559,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 +5754,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(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(r->own().real); - AcquireSRWLockExclusive(&draw_lock); - out->cache_entries += static_cast(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(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(InterlockedCompareExchange(&r->own().retire_view_refs, 0, 0)); + if (auto* real = static_cast(r->own().real)) { + AcquireSRWLockExclusive(&draw_lock); + out->cache_entries += static_cast(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(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(pass_of(l).states.size()); @@ -5323,16 +5846,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 +5875,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 allocator; - x2w_startup::ComPtr 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 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 allocator; + x2w_startup::ComPtr 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 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(device), static_cast(wrapper), static_cast(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 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(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 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(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 staging; + x2w_startup::ComPtr 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(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(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. @@ -5554,6 +6205,7 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper*, const D3D12_COMPUTE static_cast(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(*out); note_pipeline(pipeline, 62, nullptr, desc, sizeof(*desc)); note_compute_binding_pipeline(pipeline, *desc); @@ -5587,13 +6239,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 +6258,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(*out)->own().compute_pipeline = real_pipeline && compute; + static_cast(*out)->own().pipeline_root = pipeline_root; static_cast(*out)->own().indirect_graphics = graphics; static_cast(*out)->own().mesh86_key = mesh86_key; note_pipeline(static_cast(*out), 86, nullptr, desc->pPipelineStateSubobjectStream, desc->SizeInBytes < 0x2000 ? desc->SizeInBytes : 0x2000, @@ -5660,8 +6318,15 @@ 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_cast(*out)->own().compute_request_key = key; + static_cast(*out)->own().compute_request_root = as_wrapper(*static_cast(desc)); + } + } note_pipeline(static_cast(*out), N, nullptr, desc, 0x300); return S_OK; } @@ -5689,6 +6354,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(*out), 55, base, desc, bytes_in_patches); return S_OK; } @@ -5700,10 +6366,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 +6378,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(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 +6396,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(clear), clear && !cleared ? "(dropped)" : "", session, castable_count, castable, text, static_cast(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 +6420,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. @@ -5935,6 +6629,74 @@ void report_budget(ID3D12CommandQueue* queue) log("x2w-budget local=%s nonlocal=%s%s unmeasured=%llu", local, nonlocal, text, counts.unmeasured); } +// 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= (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(wanted) < planes ? static_cast(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(resource)) : nullptr; + if (!surface || surface->own().kind != resource_kind || !surface->own().real) continue; + auto* const real = static_cast(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(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(resource)); + continue; + } + const D3D12_RESOURCE_DESC desc = static_cast(surface->own().real)->GetDesc(); + log("x2w-present frame %ld plane %u/%u: %llux%u format %d flags=0x%x", frame, i, planes, + static_cast(desc.Width), desc.Height, desc.Format, static_cast(desc.Flags)); + } +} + // Queue slot 32 (Xbox order): (plane count, plane parameters*, present parameters*) -> HRESULT, the // console present. Nothing is shown yet; frames are counted and a heartbeat is logged. HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_parameters, const void* present_parameters) @@ -5970,7 +6732,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(plane_parameters); if (planes && words && x2w_local::readable(words, 0x18) && words[1] >= 1 && x2w_local::readable(reinterpret_cast(words[2]), 8)) @@ -5978,9 +6746,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(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(self->own().real), static_cast(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(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 +6780,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(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(self->own().real), raw_surface, static_cast(raw_plane)); } if (shown_in_window) { if (frame % 30 == 0) { @@ -6037,6 +6816,11 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa heap_root_refusals[static_cast(x2w_startup::RealRootDecision::both_heaps_missing)], heap_root_refusals[static_cast(x2w_startup::RealRootDecision::state_not_restorable)], indirect_first_lookups, compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words); + if (render_mode() && frame % 300 == 0) { + log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld, not modelled %ld", + compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled); + 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 +6854,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(heap_infos().size()), static_cast(placed_buffer_calls), static_cast(placed_buffer_region_info), static_cast(placed_buffer_queries)); + { + char line[640]; + if (view_census_line(line, sizeof(line))) log("%s", line); + } { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); @@ -6195,6 +6983,7 @@ void build_tables() tables[device_kind][48] = reinterpret_cast(&device_create_command_queue_x); tables[device_kind][70] = reinterpret_cast(&device_memory_srv); tables[device_kind][73] = reinterpret_cast(&device_create_command_list_x); + tables[device_kind][76] = reinterpret_cast(&device_create_committed); tables[device_kind][78] = reinterpret_cast(&device_frame_interval); tables[device_kind][79] = reinterpret_cast(&device_frame_event); tables[device_kind][80] = reinterpret_cast(&device_wait_frame_event); @@ -6230,6 +7019,7 @@ void build_tables() list_typed[139] = reinterpret_cast(&list_reset); list_typed[148] = reinterpret_cast(&list_allocate_upload); list_typed[12] = reinterpret_cast(&list_draw); + list_typed[14] = reinterpret_cast(&list_dispatch); list_typed[16] = reinterpret_cast(&list_copy_texture); list_typed[20] = reinterpret_cast(&list_topology); list_typed[21] = reinterpret_cast(&list_viewports); @@ -6248,6 +7038,8 @@ void build_tables() list_typed[13] = reinterpret_cast(&list_draw_indexed); list_typed[35] = reinterpret_cast(&list_compute_table); list_typed[36] = reinterpret_cast(&list_table); + list_typed[37] = reinterpret_cast(&list_compute_constant); + list_typed[39] = reinterpret_cast(&list_compute_constants); list_typed[40] = reinterpret_cast(&list_root_constants); list_typed[47] = reinterpret_cast(&list_index_buffer); list_typed[48] = reinterpret_cast(&list_vertex_buffers); @@ -6311,9 +7103,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 +7193,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(adapter), block, text, static_cast(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 cbbbbae61..e2ecdc624 100644 --- a/src/startup_stubs/draw_dump_tracking.h +++ b/src/startup_stubs/draw_dump_tracking.h @@ -3,6 +3,8 @@ #include #include +#include "startup_stubs/d3d12_teardown.h" + #include #include #include @@ -19,6 +21,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 @@ -51,6 +59,34 @@ class DrawReadbacks { return true; } + // 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 buffer, Microsoft::WRL::ComPtr fence) + { + std::lock_guard 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 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; + } + void discard(ID3D12CommandList* list) { std::lock_guard lock(mutex_); @@ -101,5 +137,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/formatted_buffer.h b/src/startup_stubs/formatted_buffer.h index 2a216abb0..76ad650eb 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/input_script.h b/src/startup_stubs/input_script.h index 0e16ce8ca..b34c4450b 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 929a7eca8..207469413 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" @@ -318,22 +319,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(static_cast(address) - static_cast(range.base)); + PlacedBufferRange local_range = range; + UINT64 offset = static_cast(static_cast(address) - static_cast(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(static_cast(address) - static_cast(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 +875,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 6e5d89c46..a47b3477d 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_dispatch.h b/src/startup_stubs/list_dispatch.h new file mode 100644 index 000000000..102446d71 --- /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 + +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/memory_srv_buffer.h b/src/startup_stubs/memory_srv_buffer.h index 4031efe12..b24be40d5 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; diff --git a/src/startup_stubs/memory_srv_census.h b/src/startup_stubs/memory_srv_census.h index 9a6a725ec..240dbb8f3 100644 --- a/src/startup_stubs/memory_srv_census.h +++ b/src/startup_stubs/memory_srv_census.h @@ -29,8 +29,10 @@ 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 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) @@ -47,10 +49,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/mesh86_cache.inl b/src/startup_stubs/mesh86_cache.inl index 175671c9b..0c2fe5b3e 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(request.root->own().real)); if (result) graphics.cached_srv_root = srv_root; static LONG loaded; diff --git a/src/startup_stubs/pixel_history.h b/src/startup_stubs/pixel_history.h new file mode 100644 index 000000000..4f64586d1 --- /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 + +#include +#include +#include + +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(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(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(sample.draw), sample.frame, sample.x, sample.y, + static_cast(sample.key), sample.count, static_cast(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 456cdfe6b..115983e17 100644 --- a/src/startup_stubs/placed_buffer_range.h +++ b/src/startup_stubs/placed_buffer_range.h @@ -58,6 +58,18 @@ inline QueryRegion query_region() } } // namespace placed_detail +// 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; +} + // 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. @@ -107,4 +119,28 @@ inline bool measure_placed_buffer(const void* address, std::uint64_t width, Plac return true; } +// 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(address); + const auto base = reinterpret_cast(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 a8967cbe4..c64520a24 100644 --- a/src/startup_stubs/placed_build.h +++ b/src/startup_stubs/placed_build.h @@ -3,7 +3,8 @@ #include 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 000000000..b41cd5895 --- /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 + +#include +#include + +#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 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(width), static_cast(height), 0, 1}; + const D3D12_RECT scissor{0, 0, static_cast(width), static_cast(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 000000000..0c71c7ac1 --- /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 +#include +#include + +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 +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(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(resources), 8)) return 0; + std::memcpy(&first, reinterpret_cast(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/profile_zone.h b/src/startup_stubs/profile_zone.h index 4981dc672..e94d7e2f6 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 #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/registry_console_mode.inl b/src/startup_stubs/registry_console_mode.inl new file mode 100644 index 000000000..7af9b49ae --- /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 , , 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 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(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(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(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(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(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(status)); +} + +template +Fn real_reg(RegistryImport which) noexcept +{ + return reinterpret_cast(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(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(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(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(type), data, reinterpret_cast(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(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(type), data, reinterpret_cast(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(reg_close_key); + untrack_oem(key); + return real ? real(key) : ERROR_PROC_NOT_FOUND; +} + +void* const registry_hooks[registry_imports] = { + reinterpret_cast(&hooked_reg_open_key_ex_w), reinterpret_cast(&hooked_reg_open_key_w), + reinterpret_cast(&hooked_reg_query_value_ex_w), reinterpret_cast(&hooked_reg_get_value_w), + reinterpret_cast(&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(real))) return nullptr; + return reinterpret_cast(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(base + hit.first_thunk_rva); + if (*slot == reinterpret_cast(registry_hooks[which])) return; + if (!remember_registry(which, reinterpret_cast(*slot))) return; + DWORD old = 0; + if (!VirtualProtect(slot, 8, PAGE_READWRITE, &old)) return; + *slot = reinterpret_cast(registry_hooks[which]); + VirtualProtect(slot, 8, old, &old); + ++patched; + }); + return patched; +} diff --git a/src/startup_stubs/root_constant_store.h b/src/startup_stubs/root_constant_store.h new file mode 100644 index 000000000..45b991400 --- /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 +#include + +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(((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(parameter_count) && offset >= 0 && + offset < static_cast(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 e5b23da82..b9dd8a4d0 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 +template 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 -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 +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(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(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(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 +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 7c9a17046..bf117e9e8 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(name) > 0xffff) { static LONG logged; if (x2w_local::first_calls(logged, 40)) x2w_local::logf("x2w-runtime GetProcAddress(%p, \"%s\") -> %p", static_cast(module), name, static_cast(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(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(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(args[3]); - if (size > x2w_save::max_blob_bytes || (size && x2w_local::probe_readable(static_cast(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(args[2]); - if (size) action.data.assign(bytes, bytes + size); + if (!action.remove) { + const std::size_t size = static_cast(args[3]); + if (size > x2w_save::max_blob_bytes || (size && x2w_local::probe_readable(static_cast(args[2]), size) != size)) { + *result = e_invalidarg; + return true; + } + const auto* bytes = reinterpret_cast(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(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 9887644fe..2237dd77b 100644 --- a/src/startup_stubs/save_store.h +++ b/src/startup_stubs/save_store.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -56,12 +57,21 @@ inline bool valid_name(std::string_view name) noexcept same = std::tolower(static_cast(tail[i])) == suffix[i]; if (same) return false; } - std::string stem(name.substr(0, name.find('.'))); - for (char& c : stem) c = static_cast(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(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 000000000..f7f2de091 --- /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 +#include +#include + +#include +#include +#include + +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 make_scratch(ID3D12Device* device, UINT max_count, UINT stride) + { + Microsoft::WRL::ComPtr 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 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(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 root; + Microsoft::WRL::ComPtr 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 guard(lock_); + for (auto& known : entries_) + if (known->device == device) return known->pipeline ? known.get() : nullptr; + auto entry = std::make_unique(); + 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 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 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> 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 000000000..046ea0d03 --- /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 +#include +#include + +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(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 a4aca72dd..10149b3c1 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -110,20 +110,25 @@ inline std::vector 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.. right after them. inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT srvs, - const TranslatedSamplers& samplers, ID3D12RootSignature** out) + const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 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. + const D3D12_DESCRIPTOR_RANGE view_ranges[2]{{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, uavs, 0, 0, srvs}}; parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - parameters[1].DescriptorTable = {1, &srv_range}; + // A range of no descriptors does not serialize: a program without resources starts the table at its outputs. + parameters[1].DescriptorTable = {(srvs ? 1u : 0u) + (uavs ? 1u : 0u), srvs ? view_ranges : view_ranges + 1}; 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); if (samplers.heap) { parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; parameters[count].DescriptorTable = {1, &sampler_range}; diff --git a/src/startup_stubs/typed_uav_load.h b/src/startup_stubs/typed_uav_load.h new file mode 100644 index 000000000..c3bab6bc7 --- /dev/null +++ b/src/startup_stubs/typed_uav_load.h @@ -0,0 +1,14 @@ +#pragma once +#include + +// 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 000000000..57bf321a5 --- /dev/null +++ b/src/startup_stubs/upload_reservation.h @@ -0,0 +1,89 @@ +#pragma once + +#include +#include + +struct ID3D12Resource; + +inline constexpr std::uint64_t initial_upload_chunk_bytes = 16ull << 20; +inline constexpr std::uint64_t max_upload_ring_bytes = 256ull << 20; +// Each allocation except possibly the final remainder is at least the initial size. +inline constexpr unsigned max_upload_chunks = max_upload_ring_bytes / initial_upload_chunk_bytes; +using UploadChunkMask = std::uint32_t; +static_assert(max_upload_chunks <= 32); + +template +struct UploadQueue { + Fence* fence = nullptr; + std::uint64_t value = 0; + std::array 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; + } + } +}; + +inline void discard_upload_chunks(UploadChunkMask& recording, UploadRingChunk* chunks) +{ + for (unsigned i = 0; recording; ++i, recording >>= 1) + if (recording & 1) --chunks[i].recordings; +} + +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 +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 000000000..4c5408536 --- /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/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 50d543a16..a71155197 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -75,6 +75,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 +109,7 @@ struct Entry { std::unique_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 +134,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 @@ -152,9 +175,33 @@ static bool has_zlib_header(const unsigned char* bytes, std::size_t size) return true; } +// 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. +static bool resident_read_write(std::uintptr_t start, std::uintptr_t end) +{ + 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(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(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; +} + // 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 VirtualQuery walk, 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). static bool destination_writable(const void* destination, std::size_t bytes) { if (bytes == 0) return true; @@ -162,6 +209,7 @@ static bool destination_writable(const void* destination, std::size_t bytes) 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; + if (resident_read_write(cursor, end)) return true; while (cursor < end) { MEMORY_BASIC_INFORMATION info{}; if (!VirtualQuery(reinterpret_cast(cursor), &info, sizeof(info)) || info.State != MEM_COMMIT) @@ -279,15 +327,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(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(InterlockedDecrement(&self->refs)); - if (refs == 0 && self->kind == queue) { - auto& object = *static_cast(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 +358,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(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(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) { @@ -950,6 +1050,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 +1061,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 +1088,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 +1099,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 +1160,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 +1175,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 +1240,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 +1276,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 +1294,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 +1423,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 +1516,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(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(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(request + 0x08); const unsigned destination_size = *reinterpret_cast(request + 0x18); @@ -1355,6 +1559,7 @@ void __stdcall queue_enqueue_status(Object* self, Object* array, unsigned index) InterlockedExchange(&array->results[index], static_cast(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 +1726,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(count); + return total; + } + if (kind != factory && kind != file && kind != status && kind != queue) return 0; + return static_cast(live_by_kind[kind / 0x20 - 1]); +} + +extern "C" __declspec(dllexport) unsigned long x2w_xcrdapi_live_workers() +{ + return static_cast(live_workers); +} + extern "C" long __stdcall DStorageGetFactory(const GUID* riid, void** out) { char id[48]; diff --git a/src/startup_stubs/xcrdapi.def b/src/startup_stubs/xcrdapi.def index 1d2bae195..55b3df7ff 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/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 756741898..c21277296 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -71,7 +72,7 @@ struct PhysicalMemory { for (const auto& run : runs) UnmapViewOfFile(reinterpret_cast(run.first)); for (const HANDLE slab : slots.slabs()) - CloseHandle(slab); + if (slab) CloseHandle(slab); } }; @@ -100,12 +101,26 @@ const Backing* mirrored_backing(ULONG_PTR page) } // Caller holds memory.mutex. -void unpin_slot(const Slot& slot) +void collect_empty_slabs(std::vector& 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* closed = nullptr) { const auto found = memory.pins.find(slot); 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 @@ -862,6 +877,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 committed; + X2W_PLOT("XMemVirtualAlloc commits (bytes, cumulative)", static_cast(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(bytes), static_cast(type), @@ -1051,26 +1073,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(pages)); - if (status == era_physical::Status::ok) { + std::vector 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(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 @@ -1452,11 +1480,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 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; } @@ -1472,8 +1504,8 @@ extern "C" BOOL WINAPI x2w_xmem_page_stats(ULONGLONG* live_sections) } // 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; @@ -1628,7 +1660,10 @@ const bool lazy_commit_installed = [] { // 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 +1676,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 +1813,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 +1828,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 a5b43f0f1..50272449c 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 @@ -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); diff --git a/src/xmem_slab_slots.h b/src/xmem_slab_slots.h index 1b9095cc7..5f060196b 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 #include #include @@ -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 + 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& 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 slabs_; + std::vector 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> free_; // (slab index, offset) }; diff --git a/tests/adapter_name_filter.h b/tests/adapter_name_filter.h new file mode 100644 index 000000000..a82ebbe02 --- /dev/null +++ b/tests/adapter_name_filter.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include +#include + +// Hardware fixtures match XBOX2WINDOWS_ADAPTER against the DXGI description. +class AdapterNameFilter { +public: + bool read() + { + length = GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(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/bink_descriptors_aot_cli_check.py b/tests/bink_descriptors_aot_cli_check.py new file mode 100644 index 000000000..fd72ae78c --- /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(" 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 000000000..f49bbe9a0 --- /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 \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 000000000..49bc5af44 --- /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 \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 000000000..cb606b759 --- /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(" 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(" 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 000000000..fc370f1e2 --- /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 000000000..3c1493c48 --- /dev/null +++ b/tests/checks/pixel-binary/README.md @@ -0,0 +1,10 @@ +# pixel-binary check lists + +Put one `.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 000000000..a7b359904 --- /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 000000000..ed54c3ec8 --- /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 000000000..3b2f6c652 --- /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_pixel_first_lane.txt b/tests/checks/pixel-binary/startup_gfx2hlsl_pixel_first_lane.txt new file mode 100644 index 000000000..f15e3caaa --- /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 000000000..b44566ab2 --- /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/python-linux/mesh_bitcmp.txt b/tests/checks/python-linux/mesh_bitcmp.txt new file mode 100644 index 000000000..b0b6ee930 --- /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 000000000..3befbb80e --- /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/pixel_image_store.txt b/tests/checks/python-linux/pixel_image_store.txt new file mode 100644 index 000000000..2e7a8b422 --- /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 000000000..1d836f9de --- /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/startup_gfx2hlsl_pixel_first_lane.txt b/tests/checks/python-linux/startup_gfx2hlsl_pixel_first_lane.txt new file mode 100644 index 000000000..3807cfccb --- /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_wave_reduce.txt b/tests/checks/python-linux/startup_gfx2hlsl_wave_reduce.txt new file mode 100644 index 000000000..61056353c --- /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/cmake/README.md b/tests/cmake/README.md new file mode 100644 index 000000000..4800fd947 --- /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/.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/mesh_bitcmp.cmake b/tests/cmake/mesh_bitcmp.cmake new file mode 100644 index 000000000..88ba3ecbf --- /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}" + "$" ${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 000000000..184128bd4 --- /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}" + "$" ${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/startup_compute_dispatch_array.cmake b/tests/cmake/startup_compute_dispatch_array.cmake new file mode 100644 index 000000000..ad9b4f92b --- /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" "$" + "${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" "$" + "${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_debug_launch_args.cmake b/tests/cmake/startup_debug_launch_args.cmake new file mode 100644 index 000000000..7484ae950 --- /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_gfx2hlsl_pixel_first_lane.cmake b/tests/cmake/startup_gfx2hlsl_pixel_first_lane.cmake new file mode 100644 index 000000000..982ab7e6b --- /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}" + "$" ${adapter} $<$:${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_wave_reduce.cmake b/tests/cmake/startup_gfx2hlsl_wave_reduce.cmake new file mode 100644 index 000000000..376fba248 --- /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}" + "$" ${adapter} $<$:${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_pixel_history_draw.cmake b/tests/cmake/startup_pixel_history_draw.cmake new file mode 100644 index 000000000..7f7de1742 --- /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" + "$" "${backend}") + set_tests_properties(startup_pixel_history_draw_${backend} PROPERTIES TIMEOUT 90 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 000000000..c47f3f01b --- /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_view_alloc.cmake b/tests/cmake/startup_view_alloc.cmake new file mode 100644 index 000000000..46e6da25b --- /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/compute_alu_bfm_check.py b/tests/compute_alu_bfm_check.py new file mode 100644 index 000000000..5745b2f5f --- /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 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 000000000..ebb3d72c4 --- /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 " + " | binary ") + 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 000000000..ab9853eb0 --- /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 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 ") diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index 4b6ada2a5..ee4fb50d1 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -250,8 +250,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* 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 +272,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 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 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 +280,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 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 heap; if (tables) { // An image-load case binds its output at u0 and the source texture at t0; the table @@ -346,21 +351,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 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 +371,86 @@ void check_compute_file(ID3D12Device* device, const char* path, bool conversion_ file.seekg(0); if (!file.read(bytes.data(), static_cast(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(&store.groups), sizeof(store.groups)); - file.read(reinterpret_cast(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(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(&store.groups), sizeof(store.groups)); + file.read(reinterpret_cast(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(store.initial.data()), sizeof(store.initial)); + if (!file) + throw std::runtime_error("Invalid compute store initial words"); + } + if (file.peek() != std::char_traits::eof()) { + file.read(reinterpret_cast(store.root_constants.data()), sizeof(store.root_constants)); + if (!file) + throw std::runtime_error("Invalid compute store constants"); if (file.peek() != std::char_traits::eof()) { - file.read(reinterpret_cast(store.root_constants.data()), sizeof(store.root_constants)); - if (!file) - throw std::runtime_error("Invalid compute store constants"); - if (file.peek() != std::char_traits::eof()) { - file.read(reinterpret_cast(store.source.data()), sizeof(store.source)); - if (!file || file.peek() != std::char_traits::eof()) - throw std::runtime_error("Invalid compute store source words"); - store.has_source = true; - } + file.read(reinterpret_cast(store.source.data()), sizeof(store.source)); + if (!file || file.peek() != std::char_traits::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 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 bytes(static_cast(size)); - file.seekg(0); - if (!file.read(bytes.data(), static_cast(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); @@ -458,7 +476,8 @@ void check_compute_texture_file(ID3D12Device* device, const char* path, const ch 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, + const auto program = create_compute_program(device, shader, {compute_tables, sizeof(compute_tables)}); + run_compute(device, true, program, false, &store, &texels, format, nullptr, false, false, view_mip1 ? 1 : 0); } @@ -540,12 +559,12 @@ bool check_compute_texture_msaa_file(ID3D12Device* device, const char* path, con source.read(reinterpret_cast(store.expected.data()), sizeof(store.expected)); if (!source || source.peek() != std::char_traits::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 +669,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 signature; check(device->CreateRootSignature(0, compute_tables, sizeof(compute_tables), IID_PPV_ARGS(&signature)), "Create image store root signature"); @@ -761,6 +780,7 @@ 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"); } diff --git a/tests/compute_heap_store_check.py b/tests/compute_heap_store_check.py index 21e8906b7..a95a87913 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 6555ec680..68156df83 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 aee7656f7..da7fca6a1 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 bdaa9eca3..576b9cf1a 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 " - "| draw ") + "| draw | draw-d16 ") diff --git a/tests/compute_salu_bitset_check.py b/tests/compute_salu_bitset_check.py new file mode 100644 index 000000000..cfc415dbe --- /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 ") + 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 964b2447f..404f259e7 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -3739,6 +3739,32 @@ 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. They differ at word 0, the + cancellation 4097 * 4097 - 16785408 (1.0 fused, +0 unfused). Exactly one model must match all 320 words; + a compile, dispatch or readback failure, or any other readback, fails the test. + """ + matches = {} + for name, model in (("fused", mac_f32_words(fused=True)), ("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 + 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}") + + 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 +3805,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 +5143,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 +5455,231 @@ 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 + assert "(0u - tid.x)" in 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 + for mutated, mismatched_word in shared_mutants(name, lines, binding): + src.write_text(aot.lower(mutated, 64, **binding), 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 +6350,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 = (" 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 +6602,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 +6632,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 +8242,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 +9950,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 +9991,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 000000000..149ad4628 --- /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/aes_pclmul_aot.asm b/tests/cpu/aes_pclmul_aot.asm new file mode 100644 index 000000000..c9497881d --- /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 000000000..1df0227d2 --- /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 000000000..64267bec9 --- /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(" 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("" 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/avx_cmp_aot.asm b/tests/cpu/avx_cmp_aot.asm new file mode 100644 index 000000000..fb7295d95 --- /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 000000000..f92943cb9 --- /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 000000000..83a14fbd6 --- /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(" float: + if daz and _is_subnormal_f64(bits): + bits &= 0x8000000000000000 + return struct.unpack(" 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(" bytes: + xa = list(struct.unpack("<2Q", a[:16])) + xb0 = struct.unpack(" 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 "" 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(" 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 000000000..7678a4a82 --- /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 000000000..b0a2748a6 --- /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 000000000..bbfa86d5d --- /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(" 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 c683c53ab..3a0d0d098 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 07ae0dc61..f69a5589e 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 000000000..6a4404912 --- /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 000000000..3935ba5a4 --- /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 000000000..e1d10328a --- /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 000000000..fd13c6902 --- /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 000000000..8bde8d32f --- /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 000000000..3ca4e0750 --- /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(" 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(" 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(" 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 000000000..a8e7c1060 --- /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 000000000..cf2f0ae67 --- /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(" 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("> 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(" 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 000000000..4dc37d6e8 --- /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 000000000..d62d31edc --- /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(bswap16(load_always((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((r8 + 0x10ull), bswap32(static_cast((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(bswap64(load_always((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(" 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(" 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(" 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 "" not in source_cpp and "" 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(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(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(" 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 698468125..3cc7310b6 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 98ae594df..0d2a120ad 100644 --- a/tests/cpu/x87_fprem.py +++ b/tests/cpu/x87_fprem.py @@ -5,6 +5,8 @@ python tests/cpu/x87_fprem.py emit [control] translate (and optionally mutate) the fixture python tests/cpu/x87_fprem.py check [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 5120b5f7f..57d186485 100644 --- a/tests/cpu/x87_scale.py +++ b/tests/cpu/x87_scale.py @@ -5,6 +5,8 @@ python tests/cpu/x87_scale.py emit [control] translate (and optionally mutate) the fixture python tests/cpu/x87_scale.py check [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 87739375d..ba09c13aa 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/desktop_gpu.h b/tests/desktop_gpu.h index 84ff8c3f5..a49d48dd8 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -30,11 +30,14 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const 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,12 @@ 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); +struct ComputeReadbackProgram { + Microsoft::WRL::ComPtr signature; + Microsoft::WRL::ComPtr 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 +81,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 +90,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 +106,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 8ec04d0de..f867c0c7d 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_compile_time_cli_check.py b/tests/dxc_compile_time_cli_check.py index 0f7e89415..5e4e05754 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/f16_packed_model.py b/tests/f16_packed_model.py new file mode 100644 index 000000000..f788b40af --- /dev/null +++ b/tests/f16_packed_model.py @@ -0,0 +1,127 @@ +"""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('> 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_op(op, a, b, c=0): + """One binary16 lane: op is 'mul', 'add' or 'fma' (a * b + c).""" + 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__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_working_set_delta_cli_check.py b/tests/ffx_working_set_delta_cli_check.py new file mode 100644 index 000000000..d076e34ea --- /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 \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 000000000..fb8c4c4f2 --- /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 + +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_reference_cli_check.py b/tests/form_reference_cli_check.py new file mode 100644 index 000000000..9ae521fac --- /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 000000000..4f26ca185 --- /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/gpu_case_recorder_check.py b/tests/gpu_case_recorder_check.py new file mode 100644 index 000000000..f5f076879 --- /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/hardware_adapter_filter_check.py b/tests/hardware_adapter_filter_check.py new file mode 100644 index 000000000..2196c24f1 --- /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 1727eb5cc..baabffa4d 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 000000000..5ec465586 --- /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/intake_exe_cli_check.py b/tests/intake_exe_cli_check.py new file mode 100644 index 000000000..0f97c248d --- /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(" 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/mesh_bitcmp_check.py b/tests/mesh_bitcmp_check.py new file mode 100644 index 000000000..cd3a8b7de --- /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(" 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 | draw ]") + + +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 000000000..cb2f65b0c --- /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 reassemble wave64 mesh and wave32 pixel fixtures with llvm-mc + draw 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(" 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("> 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 000000000..66efe49b5 --- /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 +#include +#include +#include +#include +#include + +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 rgba; + std::array 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& vertices, const std::vector& 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 vertices(kMaxMeshletVertices + 1, scene.vertices.front()); + std::vector 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 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 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(kSide), static_cast(kSide), 0.0f, 1.0f}; + const D3D12_RECT scissor{0, 0, static_cast(kSide), static_cast(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(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(readback_bytes)}; + check(pixel_readback->Map(0, &pixel_range, &mapped), "Map rendered pixels"); + const auto* base = static_cast(mapped); + for (UINT y = 0; y < kSide; ++y) { + std::memcpy(&result.rgba[static_cast(y) * kSide * 4], + base + footprint.Offset + static_cast(y) * footprint.Footprint.RowPitch, + kSide * 4); + } + pixel_readback->Unmap(0, &empty); + return result; +} + +void verify_rendered_image(const std::vector& rgba, const char* label) { + auto pixel_at = [&](UINT x, UINT y) -> std::array { + const std::size_t idx = (static_cast(y) * kSide + x) * 4; + return {rgba[idx + 0], rgba[idx + 1], rgba[idx + 2], rgba[idx + 3]}; + }; + const std::array green{0, 255, 0, 255}; + const std::array blue{0, 0, 255, 255}; + const std::array 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(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(auto_result.caps.mesh_shader_tier), + static_cast(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{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 000000000..1dd1e83ce --- /dev/null +++ b/tests/meshlet_builder_check.cpp @@ -0,0 +1,280 @@ +#include "meshlet_builder.h" + +#include +#include +#include +#include +#include +#include + +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 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 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 verts; + std::vector indices; + for (int y = 0; y <= grid; ++y) { + for (int x = 0; x <= grid; ++x) { + verts.push_back(make_vertex(static_cast(x), static_cast(y), 0.0f)); + } + } + for (int y = 0; y < grid; ++y) { + for (int x = 0; x < grid; ++x) { + const std::uint32_t v0 = static_cast(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> 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 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 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 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 tilted_pair(float half_angle) { + const float c = std::cos(half_angle); + const float s = std::sin(half_angle); + std::vector 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 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 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 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 indices; + for (int y = 0; y < grid; ++y) { + for (int x = 0; x < grid; ++x) { + const std::uint32_t v0 = static_cast(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 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 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/offscreen_check.cpp b/tests/offscreen_check.cpp index d3973cdd1..08ec3e41c 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 -OperationResult run_pixel_batch(const OperationContext& ctx, AfterDraw after_draw) +template +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])); @@ -1285,8 +1332,10 @@ OperationResult run_startup_sampler_heap(const OperationContext& ctx) // mip levels whose cells all differ (tests/startup_image_3d.cpp). 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; float z = 0.0f; if (two_dimensional && ctx.argv[5][0] == '0' && (ctx.argv[5][1] == 'x' || ctx.argv[5][1] == 'X')) { @@ -1303,8 +1352,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); std::uint32_t bits[4]; std::memcpy(bits, color, sizeof(bits)); if (std::memcmp(bits, expected, sizeof(bits)) != 0) { @@ -1367,20 +1416,31 @@ OperationResult run_startup_image_load_d16(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } -// --startup-image-store : 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 [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 +1532,39 @@ OperationResult run_startup_pixel_words(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +// --startup-pixel-dump : 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 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(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 : 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]); @@ -1620,8 +1703,8 @@ constexpr CapabilityGate kGateSm66MinLod{ // Scenario-dependent capability checks (such as DXR tier, mesh tier, or existing-heap support) // remain inside the handlers and report OutcomeKind::skip. 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}, + {"--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 +1712,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 +1726,22 @@ 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-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-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}, // : 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 +1775,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 +1797,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}, diff --git a/tests/paged_resource_check.py b/tests/paged_resource_check.py new file mode 100644 index 000000000..45ea58216 --- /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/pe_package_preflight_cli_check.py b/tests/pe_package_preflight_cli_check.py new file mode 100644 index 000000000..18f488a2c --- /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(" 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/pixel_aot_check.py b/tests/pixel_aot_check.py index 2c1098356..1de2b7a63 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -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(" (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( @@ -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) @@ -18904,9 +18911,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|"), @@ -24162,7 +24169,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) diff --git a/tests/pixel_compare_grad_check.py b/tests/pixel_compare_grad_check.py new file mode 100644 index 000000000..4858ebabf --- /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(" 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 000000000..604f8a15d --- /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 ba0e719a6..5d82a5cca 100644 --- a/tests/pixel_compare_render.cpp +++ b/tests/pixel_compare_render.cpp @@ -20,7 +20,7 @@ struct CompareCase { std::vector> 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(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(c.depths.data()), std::streamsize(c.depths.size() * sizeof(float))); c.expected.resize(size_t(c.width) * c.height); file.read(reinterpret_cast(c.expected.data()), std::streamsize(c.expected.size() * 16)); @@ -61,9 +65,10 @@ ComPtr 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 ps{std::istreambuf_iterator(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(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 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 staged(static_cast(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 000000000..4a6763e41 --- /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 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 7564a71be..2d7085759 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/rdna2_tools_check.py b/tests/rdna2_tools_check.py index 1b197796d..b1c5060a2 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 000000000..8194c9f35 --- /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/run_checks_fragments_check.py b/tests/run_checks_fragments_check.py new file mode 100644 index 000000000..43e00d48a --- /dev/null +++ b/tests/run_checks_fragments_check.py @@ -0,0 +1,120 @@ +"""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. + 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 + 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 2d04e5cbb..16beed43a 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 diff --git a/tests/script_state_probe_cli_check.py b/tests/script_state_probe_cli_check.py new file mode 100644 index 000000000..b0e3a75bf --- /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(" 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( + " 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("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 000000000..903bbb7cb --- /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(" 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(" 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 000000000..d02e8fbd4 --- /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(" 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 000000000..035bc91fd --- /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("> 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 000000000..cf3e9905e --- /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 000000000..6ef84046a --- /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 49119430c..50a2c4c01 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 fd2782d60..08ee595e3 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 960ff5fbe..a17ea821d 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 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN @@ -8,6 +9,7 @@ #define NOMINMAX #endif #include +#include #include #include @@ -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(ro); + auto* ro_apu = static_cast(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(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(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(sentinel); check(take(&out, usable + 16, 16, &apu) == no_memory && !out && apu == 0xDEADBEEF, "larger than the heap"); out = const_cast(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 go{false}; std::atomic 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 go{false}; + std::atomic bad{0}; + void* objects[callers] = {}; + std::vector 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(hal); auto connect = reinterpret_cast(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(GetProcAddress(module, "ApuAlloc")); + free_fn = reinterpret_cast(GetProcAddress(module, "ApuFree")); + map_apu_fn = reinterpret_cast(GetProcAddress(module, "ApuMapApuAddress")); + auto create = reinterpret_cast(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(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(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(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(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(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(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(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 \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_address_buffer_srv_check.py b/tests/startup_address_buffer_srv_check.py index 44c6304f0..31a2f6283 100644 --- a/tests/startup_address_buffer_srv_check.py +++ b/tests/startup_address_buffer_srv_check.py @@ -11,12 +11,16 @@ 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\} " @@ -50,13 +54,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, 17, 77) 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 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 a3b628699..41ba62e26 100644 --- a/tests/startup_address_console_check.py +++ b/tests/startup_address_console_check.py @@ -5,8 +5,10 @@ and one texture whose address is announced as XG rows after it was published gate the upload lifetime control described at check_gate - gate-ring the same draws with X2W_TEST_ADDRESS_UPLOAD_RING=1, which must show the - first payload overwritten + 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 + gate-ring-reuse after completion, a new ring upload draws payload 18 over the right half 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 @@ -216,7 +218,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 +229,21 @@ 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 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" + 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 +254,10 @@ 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) wrong = {"left": 0, "right": 0} seen = set() for y in range(TARGET_H): @@ -260,12 +271,14 @@ def check_gate(directory, consumer, backend, ring): released = f"x2w-draw by-address uploads: {GATE_PAYLOADS} submits completed and released" half = TARGET_W * TARGET_H // 2 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") @@ -278,12 +291,12 @@ def check_gate(directory, consumer, backend, ring): 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 [gate | gate-ring]\n" + if len(sys.argv) not in (3, 4) or (len(sys.argv) == 4 and sys.argv[3] not in ("gate", "gate-ring", "gate-ring-reuse")): + usage = "usage: startup_address_console_check.py [gate | gate-ring | gate-ring-reuse]\n" sys.exit(usage + "\n\n".join(__doc__.split("\n\n")[: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) diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index d2a72fc2d..183f25d0a 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -12,6 +12,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 Word ptr(T* value) { return reinterpret_cast(value); } struct ViewAt { @@ -21,12 +22,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(cpu); + std::array 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(invoke(guest, 14, ptr(&heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&heap))))) return false; cpu = invoke(heap, 9); @@ -58,7 +70,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 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 +90,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(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); @@ -450,6 +485,101 @@ int draw_formatted_view(void* guest, void* list) 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 storage{}; + auto* records = reinterpret_cast((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(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 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(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 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(view.address)[288 / sizeof(std::uint32_t)] = values[i]; + if (FAILED(static_cast(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 raw_buf0{}; @@ -500,6 +630,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); @@ -533,6 +664,16 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(5); draw(6); + + // 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( + 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(7); return 0; } @@ -581,7 +722,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 diff --git a/tests/startup_address_srv_check.py b/tests/startup_address_srv_check.py index a5a6cc5c3..0fbfe7f73 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")) @@ -27,12 +27,17 @@ def prepare_draw_cache(directory, consumer, hlsl, modes, binding): 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: diff --git a/tests/startup_buffer_format_word3_check.cpp b/tests/startup_buffer_format_word3_check.cpp index 8df22b7b4..5e245ecd9 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 c89621218..9099c99dc 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_committed_slot76_check.cpp b/tests/startup_committed_slot76_check.cpp new file mode 100644 index 000000000..284d472b2 --- /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 +#include + +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((*reinterpret_cast(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(desc.Width), clear ? " with clear value" : "", static_cast(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(hr), + created, static_cast(removed)); + if (created) static_cast(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_compute_dispatch_array_check.py b/tests/startup_compute_dispatch_array_check.py new file mode 100644 index 000000000..343640ad8 --- /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 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 000000000..bc1ee0577 --- /dev/null +++ b/tests/startup_compute_dispatch_check.py @@ -0,0 +1,139 @@ +"""A translated compute program dispatched through the stand-in's command list (list slot 14). + +usage: startup_compute_dispatch_check.py + +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. Four 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 one logged reason, 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). +Exit 77 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_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): + 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('<%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) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch') + 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 + + 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 is not an aliased placed buffer range with unordered access": 1 keys, 1 dispatches') \ + and '[00000000 00000000 ' not in census[2], census + assert len(refused) == 1 and 'an output is not an aliased placed buffer range with 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:]}' + print(f'startup_compute_dispatch: PASS on {adapter} (all {C.WORDS} words match after translation and with the ' + 'same root set again; untouched before translation, without a Dispatch and for 6 refusals)') + + +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 000000000..1098908b2 --- /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 + +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('> 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 000000000..c5addfad7 --- /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 + +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 000000000..4ddb8ad31 --- /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 + +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 000000000..57b9e8839 --- /dev/null +++ b/tests/startup_compute_dispatch_input_check.py @@ -0,0 +1,95 @@ +"""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 + +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.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] + 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_texture_check.py b/tests/startup_compute_dispatch_texture_check.py new file mode 100644 index 000000000..fd09c48de --- /dev/null +++ b/tests/startup_compute_dispatch_texture_check.py @@ -0,0 +1,280 @@ +"""Translated compute programs with 2D texture views, dispatched through the stand-in's command list (slot 14). + +usage: startup_compute_dispatch_texture_check.py + +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. + +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); `smpc` and `smpheap` lines are refused with their reasons. +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 +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}') + + +# 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(' reassemble every fixture source and compare machine words + decode disassemble GLOBAL test words with LLVM 15 and compare strings + dispatch 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('> 1) & 0x3f) + w1 = ((soffset & 0x7f) << 25) | (imm & 0x1fffff) + return struct.pack(' +# 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(' 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_image_store_check.py b/tests/startup_compute_image_store_check.py index e3833dbea..1623afee8 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 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)) @@ -61,6 +156,12 @@ def encoded(line, hex_words): instruction = encoded(asm, code) refused(reason, lambda: pipeline(instruction)) + # 1D, 3D and cube keep the same refusal with the address count their form would take. + for dim, address in (('SQ_RSRC_IMG_1D', 'v8'), ('SQ_RSRC_IMG_3D', 'v[8:10]'), + ('SQ_RSRC_IMG_CUBE', 'v[8:10]')): + refused('only 2D images', + lambda: pipe.cs.op_image_store(['v[14:17]', address, 's[24:31]'], ['dmask:0xf', 'dim:' + dim])) + 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 +186,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 +204,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 +239,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 a16a78d0c..9c7fd5516 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 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) @@ -74,6 +119,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 312c2529a..220764ee4 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 17b4fdd1f..84dadc0c3 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 000000000..40adb04d6 --- /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 ') + for publish in (True, False): + with tempfile.TemporaryDirectory() as tmp: + run(Path(tmp), *sys.argv[1:], publish) diff --git a/tests/startup_compute_readfirstlane_check.py b/tests/startup_compute_readfirstlane_check.py index c229be9e2..ae1d1177f 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(' + translate, compile with DXC cs_6_0, dispatch and compare all 320 words + control + 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(' 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(' 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 + +#include +#include +#include +#include +#include +#include +#include + +#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(0x5100); +HKEY const fake_other = reinterpret_cast(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 +Fn hook(const char* name, Fn fake) +{ + return reinterpret_cast(registry_hook_for(GetModuleHandleW(nullptr), name, reinterpret_cast(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(&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(&fake_close))); + check("a hook is never kept as the real function", !registry_hook_for(exe, "RegCloseKey", reinterpret_cast(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 imports; +}; + +// Synthetic PE32+ image with one regular import descriptor per entry, each slot already bound. +std::vector build_image(const std::vector& dlls, std::vector>* slots) +{ + namespace patch = x2w_runtime_patch; + std::vector image(0x1000, 0); + auto* dos = reinterpret_cast(image.data()); + dos->e_magic = 0x5A4D; + dos->e_lfanew = 0x80; + auto* nt = image.data() + 0x80; + *reinterpret_cast(nt) = 0x00004550; + *reinterpret_cast(nt + 24) = 0x20B; + auto* dirs = reinterpret_cast(nt + 24 + 112); + dirs[1].virtual_address = 0x200; + dirs[1].size = static_cast(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((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(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(image.data() + imp->original_first_thunk)[i].value = hint; + reinterpret_cast(image.data() + imp->first_thunk)[i].value = + reinterpret_cast(dlls[d].imports[i].bound); + slots->back().push_back(imp->first_thunk + static_cast(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(GetProcAddress(decoy, "decoy_calls")); + void* const decoy_open = reinterpret_cast(GetProcAddress(decoy, "RegOpenKeyExW")); + void* const decoy_query = reinterpret_cast(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(resolve(decoy, "RegOpenKeyExW")); + const auto query_fn = reinterpret_cast(resolve(decoy, "RegQueryValueExW")); + say("GetProcAddress(decoy, RegOpenKeyExW) is the decoy's export", reinterpret_cast(open_fn) == decoy_open); + say("GetProcAddress(decoy, RegQueryValueExW) is the decoy's export", reinterpret_cast(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(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> 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(&fake_query)}, + {"RegCloseKey", reinterpret_cast(&fake_close)}}}}, + &slots); + const auto slot = [&](std::size_t d, std::size_t i) { return *reinterpret_cast(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(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(&fake_query)); + before = seen(); + const int real_before = real_queries; + query(reinterpret_cast(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(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 000000000..d0fa5f677 --- /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 + +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(static_cast(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 000000000..8e0e44b36 --- /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 000000000..2db2d8ced --- /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_debug_launch_args_check.py b/tests/startup_debug_launch_args_check.py new file mode 100644 index 000000000..119203fe7 --- /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_direct_index_late_write_check.py b/tests/startup_direct_index_late_write_check.py new file mode 100644 index 000000000..b7bc1d821 --- /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_destination_check.cpp b/tests/startup_dstorage_destination_check.cpp index 6e456b9b8..1c05da696 100644 --- a/tests/startup_dstorage_destination_check.cpp +++ b/tests/startup_dstorage_destination_check.cpp @@ -12,6 +12,7 @@ #define NOMINMAX #endif #include +#include #include #include @@ -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(status_pointer); queue = static_cast(queue_pointer); for (unsigned i = 0; i < bytes; ++i) source[i] = static_cast(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(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(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(MapViewOfFile(shared_mapping, FILE_MAP_WRITE, 0, 0, 2 * page)) : nullptr; + auto* cow_pair = shared_mapping ? static_cast(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(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)); const long end_of_file = static_cast(HRESULT_FROM_WIN32(ERROR_HANDLE_EOF)); diff --git a/tests/startup_flat_param.cpp b/tests/startup_flat_param.cpp index 2fc2ae247..7c92eb02b 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 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(width), static_cast(height), 0, 1}; const D3D12_RECT scissor{0, 0, static_cast(width), static_cast(height)}; list->RSSetViewports(1, &viewport); diff --git a/tests/startup_gameinput_script_syntax.cpp b/tests/startup_gameinput_script_syntax.cpp index 45abfa578..226cfe9cb 100644 --- a/tests/startup_gameinput_script_syntax.cpp +++ b/tests/startup_gameinput_script_syntax.cpp @@ -192,6 +192,9 @@ void check_rejections() {"ly=0.5", 0, 1, "missing @"}, {"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_gamesave_submit.cpp b/tests/startup_gamesave_submit.cpp index 09f83f42a..687b361a3 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 +#include #include +#include +#include + +static std::atomic 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 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(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_gfx2hlsl_add_sub_co_check.py b/tests/startup_gfx2hlsl_add_sub_co_check.py index 7fa75429f..0a80e6ea1 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 000000000..b7185e6e1 --- /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 [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('>|<=|>=|==|!=|\|\||&=|[-+*&|^~!<>?:(),.=])') +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 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('> 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 75f4e5e2a..be2399c57 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 dd4e6a179..8a84bbe2d 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 28', 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-28'))))) if failures: print('FAILED: ' + ', '.join(failures)) 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 000000000..a800179f3 --- /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 [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(' 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('> 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 000000000..4d4b31002 --- /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 [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(' `((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(' reassemble the fixture sources and compare them with the words below dispatch translate, compile with DXC cs_6_0, dispatch and compare every word - control + control 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,103 @@ 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') + + 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 +494,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 +551,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 +712,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 +731,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 +759,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 +774,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 +787,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 +806,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 +888,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 +919,32 @@ 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-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 +957,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 +975,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 +1006,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 +1029,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 @@ -674,6 +1095,40 @@ 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()) + # Remove just the latch or just the guard to isolate the control-flow diagnostic. + refused('s_cbranch_scc0 inside a block s_cbranch_execz skips per lane: branch out of the block', + lambda: translate('O', code=patch(LOOP_BREAK_WORDS, 'f4ff84bf', '000080bf')).hlsl_cs()) + translate('O', code=patch(LOOP_BREAK_WORDS, '060088bf', '000080bf')).hlsl_cs() + + def check_mbcnt(): for _, words, reason in MBCNT_REFUSALS: refused(reason, lambda: translate('D', code=bytes.fromhex(words + '000081bf'))) @@ -692,13 +1147,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 +1380,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 +1413,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 +1440,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() @@ -870,7 +1563,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 +1668,26 @@ 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_loop_break() + 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 +1717,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 +1726,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 +1739,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 +1792,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 +1981,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 +2015,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 +2149,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 +2203,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 +2265,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 +2278,7 @@ def assemble(llvm_mc, source): def check_binary(llvm_mc): + assert assemble(llvm_mc, LOOP_BREAK_SOURCE) == LOOP_BREAK_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 +2294,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 +2310,25 @@ 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 '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 +2336,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 +2378,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 +2400,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 000000000..d1d6f02de --- /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 assemble the fixture sources (gfx1013) and compare with the words here + dispatch + translate, compile with DXC cs_6_0, dispatch and compare every word + control + 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(' assemble the fixture sources (gfx1013) and compare with the words here + dispatch + translate, compile with DXC cs_6_0, dispatch and compare every word + control + 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(' 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('` 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 000000000..ca1601f90 --- /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 [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 db9e81b77..9c726fc01 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 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(' 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 000000000..27377b320 --- /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 assemble the fixture sources with LLVM (gfx1013) and compare with the words here + draw [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_f16_alu_check.py b/tests/startup_gfx2hlsl_f16_alu_check.py index 98a93969f..7cd26001b 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 49a5e674c..cff464b12 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 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 ` 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 25fc58b0b..9677acb9e 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_float_alu_check.py b/tests/startup_gfx2hlsl_float_alu_check.py new file mode 100644 index 000000000..e3bff9bca --- /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 reassemble the pixel bodies and compare them with the recorded words + draw [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(' reassemble the pixel bodies and compare them with the recorded words + draw [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(' reassemble the pixel bodies and compare them with the recorded words + draw [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('> 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 de05a5e1f..8d9c2de35 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-28, after the precise v_fma_mix lowering', + bool(seed and seed.group(1) == 'x2w-startup-shader-28'), 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 000000000..39fb577bb --- /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 ] + +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('] + +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 000000000..d24436c81 --- /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 ] + +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('> level) * 3 // 4 + rgba = ((1 + x + 32 * level) / 128, x, 0, 0.75 if x else 0.5) + return ','.join(f'{struct.unpack(" 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 e9443d9ca..f0508e5ad 100644 --- a/tests/startup_gfx2hlsl_image_get_lod_check.py +++ b/tests/startup_gfx2hlsl_image_get_lod_check.py @@ -1,17 +1,20 @@ -"""image_get_lod on a 2D texture in tools/startup/gfx2hlsl.py. +"""image_get_lod on a 2D texture 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. 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). +Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits. A uniform join +before the read is accepted. Controls (refused): dmask 0x4, a 2D array, s_cbranch_vccz/execz 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 [fxc]: also compile the dmask 0x3 stage with dxc ps_6_0 (and fxc ps_5_1). """ import struct @@ -34,7 +37,11 @@ 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(' 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_ +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 +92,18 @@ 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') + _, 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,8 +112,9 @@ 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; uniform join/branch before ' + 'the read accepted, also after a cleared EXEC; dmask 0x4, a 2D array, vcc/exec branches, a sampler bias and a ' + 'sampler without mipmapping refused; refused without the handler') return pipe diff --git a/tests/startup_gfx2hlsl_int3_alu_check.py b/tests/startup_gfx2hlsl_int3_alu_check.py new file mode 100644 index 000000000..f5c3906dc --- /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 reassemble the pixel bodies and compare them with the recorded words + draw [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 000000000..093ae49ed --- /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 reassemble the pixel bodies and compare them with the recorded words + draw [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 a6944cdfe..d15365bd1 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(' 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_mad64_check.py b/tests/startup_gfx2hlsl_mad64_check.py new file mode 100644 index 000000000..f19d83219 --- /dev/null +++ b/tests/startup_gfx2hlsl_mad64_check.py @@ -0,0 +1,287 @@ +"""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 reassemble the pixel fixtures and compare them with the words below + draw [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)) + + +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 000000000..98ca9a61c --- /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 reassemble the fixture sources and compare them with the encoded words + draw [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 000000000..bb13ffc4e --- /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('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 reassemble the fixture sources and compare them with the words below + draw [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(' 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 000000000..071eddee7 --- /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_pixel_first_lane_check.py b/tests/startup_gfx2hlsl_pixel_first_lane_check.py new file mode 100644 index 000000000..afdad8dbf --- /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 assemble every fixture with LLVM (gfx1013) and compare with the words here + draw [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('> 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_readfirstlane_load_recompute_check.py b/tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py new file mode 100644 index 000000000..b79e184e3 --- /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 538adf789..9cfb81f77 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 b1fb5ee6f..fbdf616ca 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,206 @@ 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 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), + ('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 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, '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 +476,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 31413e53d..a32c5dbb1 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 000000000..306731689 --- /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 + +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(' [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) & 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('> 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(' 1: + if sys.argv[1] != 'draw': + raise SystemExit(__doc__) + draw_check(*sys.argv[2:]) +print('PASS') diff --git a/tests/startup_gfx2hlsl_s_bitset_check.py b/tests/startup_gfx2hlsl_s_bitset_check.py new file mode 100644 index 000000000..baa873e0c --- /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(' + +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(' + +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(' 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 000000000..ff92fa5ae --- /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('> (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 000000000..b1c80d6f7 --- /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 + +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('> (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 f89588c73..09d63fe62 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 000000000..bf9ec1f1e --- /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'(? reassemble every fixture and instruction spelling and compare with recorded words + decode disassemble the canonical encodings with LLVM's C API and compare with disasm_rdna2.py + draw [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('> 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(' 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('> (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 7a2d86ebc..f33cff0f5 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 419946c63..a1c9ae945 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 000000000..82209cb5f --- /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 assemble the fixture with LLVM 15 (-mcpu=gfx1013) and require its words + draw [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('> 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 5f4d8ef9d..4d831c5f0 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 71a51c295..83f6882f2 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 000000000..c6abbcb27 --- /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_ 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(' the draw fixtures assemble to their words + draw [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 000000000..11e79a1fa --- /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 assemble the fixture sources with LLVM (gfx1013) and compare with the words here + draw [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 000000000..fe69f50d9 --- /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 + +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(' 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 000000000..5dc0417c2 --- /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 ] + +`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(' 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 000000000..1f9fbae09 --- /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(';` 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_vcc_hi_check.py b/tests/startup_gfx2hlsl_vcc_hi_check.py new file mode 100644 index 000000000..51de51d2a --- /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 assemble the fixture sources with LLVM (gfx1013) and compare with the words here + draw [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 99e552a10..946900b02 100644 --- a/tests/startup_gfx2hlsl_watch_check.py +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -107,9 +107,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') diff --git a/tests/startup_gfx2hlsl_wave_reduce_check.py b/tests/startup_gfx2hlsl_wave_reduce_check.py new file mode 100644 index 000000000..1fa29e4b6 --- /dev/null +++ b/tests/startup_gfx2hlsl_wave_reduce_check.py @@ -0,0 +1,799 @@ +"""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 assemble every fixture with LLVM (gfx1013) and compare with the words here + draw [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. + +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, signed for unsigned, the lane's own value, the first lane's value; +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(', 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('= 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)] + 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 ('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')]) + # 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')))] + + +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 + if label in OPS: + hows = [(how, (lambda t, f=f: f(t, label))) 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 label == 'v_or_b32' and how == 'signed for unsigned': + continue # v_or_b32 has no signedness + 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(' max_levels || (levels > 1 && !array && !two_dimensional)) + 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)) throw std::runtime_error("2D mip window exceeds the resource"); diff --git a/tests/startup_image_gather_lz_check.py b/tests/startup_image_gather_lz_check.py index 7282c36bc..b10961de1 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 000000000..00be477e5 --- /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 reassemble every fixture source and compare it with the recorded words + draw [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_sample_b_check.py b/tests/startup_image_sample_b_check.py index f72cc4242..552a3aa7c 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 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 @@ -386,9 +390,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 +404,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 +428,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(' +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_ 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 +471,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 r0'), @@ -453,7 +530,7 @@ def controls(): refused('gather', 'image_gather4_b') refused('cube', 'image dimension SQ_RSRC_IMG_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') @@ -588,6 +665,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 000000000..b51aea26b --- /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 reassemble every fixture source and compare it with the recorded words + draw [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 000000000..d684232c5 --- /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 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 000000000..409aeca02 --- /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 [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('> 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 000000000..215504951 --- /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_ s_cbranch_vccz / vccnz / execz / execnz before it -> SampleLevel 0 (as before) + back_ a divergent back edge over the sample -> SampleLevel 0 (as before) + exit_ a divergent forward exit, loop closed by s_branch -> SampleLevel 0 (as before) + + (no arguments) translation controls, pure Python + draw [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('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 d406e77dc..72d4a0fff 100644 --- a/tests/startup_image_sample_l_check.py +++ b/tests/startup_image_sample_l_check.py @@ -251,11 +251,15 @@ 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' 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('refused: offset, compare, gather, cube, 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_store.cpp b/tests/startup_image_store.cpp index a428055be..d6e7ff9f5 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, 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 #include @@ -54,8 +56,9 @@ ComPtr 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(coverage), 1, 0, 1}; + const D3D12_RECT scissor{0, 0, static_cast(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(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(DXGI_FORMAT_R11G11B10_FLOAT)); + return "typed_uav_load_refused"; + } + return nullptr; +} diff --git a/tests/startup_indirect_dispatch.cpp b/tests/startup_indirect_dispatch.cpp index 99d28e7bb..aab481fd3 100644 --- a/tests/startup_indirect_dispatch.cpp +++ b/tests/startup_indirect_dispatch.cpp @@ -4,7 +4,8 @@ #include #include -#include "desktop_gpu.h" +#include "adapter_name_filter.h" +#include "startup_indirect_writer.h" #include #include @@ -15,6 +16,8 @@ #include 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; 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((*reinterpret_cast(object))[index]); } -template -ComPtr 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 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 result; - check(stored.As(&result), "query underlying object"); - return result; -} - ComPtr 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(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(guest, 133)(guest, static_cast(memory_backing.get()) + 4, &argument_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), reinterpret_cast(guest_arguments.GetAddressOf())), "place guest argument buffer"); - const auto arguments = native_object(device, guest, guest_arguments.Get()); + const auto arguments = indirect_native_object(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(guest_list.GetAddressOf())), "create guest command list"); using Reset = HRESULT (WINAPI*)(IUnknown*, IUnknown*, void*, void*); check(slot(guest_list.Get(), 139)(guest_list.Get(), allocator.Get(), nullptr, nullptr), "reset guest command list"); - const auto native_list = native_object(device, guest, guest_list.Get()); + const auto native_list = indirect_native_object(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(guest_list.Get(), 25)(guest_list.Get(), consumer); slot(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(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 queue; ComPtr 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 guest_queue; + check(guest->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), + reinterpret_cast(guest_queue.GetAddressOf())), "create guest queue"); + const auto queue = indirect_native_object(device, guest, guest_queue.Get()); + ComPtr 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(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(reset), held); + if (FAILED(reset) || held != scratches) { + std::fprintf(stderr, "split scratch was released before its submission retired\n"); + return false; + } + } else { + ComPtr 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((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"); @@ -396,20 +443,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 234eb8c3b..1641191bd 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -106,6 +106,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 +219,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 +302,18 @@ ComPtr create_root(ID3D12Device* device, const D3D12_ROOT_S return root; } +enum class TableSample { texture, buffer, buffer_tail }; + ComPtr 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-28"; 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(sample)]; std::uint64_t key = 1469598103934665603ull; const auto add = [&key](const void* data, std::size_t bytes) { const auto* p = static_cast(data); @@ -321,14 +335,15 @@ ComPtr 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(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 desc{ reinterpret_cast(root), 0, 0, 0, 0, @@ -602,19 +617,20 @@ ComPtr 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(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 +657,8 @@ struct TranslatedDrawFixture { srv.Buffer.FirstElement = replay ? 0 : 1; srv.Buffer.NumElements = replay ? static_cast(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; @@ -1337,6 +1355,207 @@ 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 TranslatedDrawFixture alias_binding(guest, red, nullptr, false, false, false, true); + enum class Mode { mrt_two, color_and_dsv, depth_only, no_attachments, alias_rtv1 }; + const auto run_mode = [&](Mode mode, const char* label) -> bool { + const auto& binding = mode == Mode::alias_rtv1 ? alias_binding : red_binding; + PlacedBuffer arguments(device, guest, static_cast(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 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 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(dsv_heap.Get(), 9)(dsv_heap.Get(), nullptr)}; + const D3D12_CPU_DESCRIPTOR_HANDLE native_dsv = + native_object(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 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(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(wrapped, 52)(wrapped, rtvs[0].ptr, clear, 0, nullptr); + if (mode == Mode::mrt_two) slot(wrapped, 52)(wrapped, rtvs[1].ptr, clear, 0, nullptr); + if (mode == Mode::mrt_two || mode == Mode::alias_rtv1) + slot(wrapped, 50)(wrapped, 2, rtvs, FALSE, nullptr); + else if (mode == Mode::color_and_dsv) { + slot(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(wrapped, 50)(wrapped, 0, nullptr, FALSE, &guest_dsv); + list->ClearDepthStencilView(native_dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + } else { + slot(wrapped, 50)(wrapped, 0, nullptr, FALSE, nullptr); + } + + ComPtr query_heap; + ComPtr 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); + } + + const D3D12_VIEWPORT viewport{0, 0, width, height, 0, 1}; + const D3D12_RECT scissor{0, 0, width, height}; + slot(wrapped, 25)(wrapped, pso); + slot(wrapped, 34)(wrapped, title_root); + ID3D12DescriptorHeap* heaps[]{binding.heap.Get()}; + slot(wrapped, 32)(wrapped, 1, heaps); + slot
(wrapped, 36)(wrapped, 0, binding.gpu); + slot(wrapped, 20)(wrapped, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + slot(wrapped, 21)(wrapped, 1, &viewport); + slot(wrapped, 22)(wrapped, 1, &scissor); + if (mode == Mode::depth_only) list->BeginQuery(query_heap.Get(), D3D12_QUERY_TYPE_OCCLUSION, 0); + slot(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(wrapped, 9)(wrapped), "close targets list"); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + ComPtr guest_queue; + check(guest->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), reinterpret_cast(guest_queue.GetAddressOf())), + "create targets queue"); + IUnknown* lists[]{wrapped}; + slot(guest_queue.Get(), 10)(guest_queue.Get(), 1, lists); + const auto native_queue = native_object(device, guest, guest_queue.Get()); + ComPtr 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(width) * height; + if (samples != expected_samples) { + std::fprintf(stderr, "%s: expected %llu rasterized samples, got %llu\n", + label, static_cast(expected_samples), + static_cast(samples)); + return false; + } + } + + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + device->GetCopyableFootprints(&color_desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + const auto read_pixels = [&](ID3D12Resource* target, std::uint32_t expected_colour, const char* which) -> bool { + 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(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; + std::memcpy(&actual, static_cast(memory) + y * footprint.Footprint.RowPitch + x * sizeof(actual), sizeof(actual)); + if (actual != expected_colour) { + std::fprintf(stderr, "%s (%s) pixel (%u,%u): got 0x%08x, expected 0x%08x\n", + label, which, x, y, actual, expected_colour); + ok = false; + } + } + readback->Unmap(0, &untouched); + return ok; + }; + const bool expect_draw = mode == Mode::mrt_two || mode == Mode::color_and_dsv; + 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; + std::printf("%s: OK\n", label); + return true; + }; + 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 +1627,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 + @@ -1526,6 +1745,7 @@ 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 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 +1753,7 @@ 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 || 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; @@ -1910,7 +2130,7 @@ int main(int argc, char** argv) try ComPtr 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"); @@ -1974,7 +2194,7 @@ int main(int argc, char** argv) try } const auto pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), false); 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 +2228,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 storage(bytes); + auto* msg = reinterpret_cast(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(msg->ID), static_cast(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 +2291,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 000000000..b853427d3 --- /dev/null +++ b/tests/startup_indirect_writer.h @@ -0,0 +1,26 @@ +#pragma once +#include "desktop_gpu.h" + +template +Microsoft::WRL::ComPtr 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 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 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 f73fe79b2..c0c700320 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 000000000..0dfdcb74e --- /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 to reassemble every source. +The draw arguments are . +""" +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(' 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_list_dispatch_check.cpp b/tests/startup_list_dispatch_check.cpp new file mode 100644 index 000000000..17abf3648 --- /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 +#include + +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 000000000..25586fde2 --- /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: " 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 +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +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(hr)); + throw std::runtime_error(stage); + } +} + +template +Method slot(IUnknown* object, unsigned index) +{ + return reinterpret_cast((*reinterpret_cast(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 +ComPtr 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 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 result; + check(stored.As(&result), "query underlying object"); + return result; +} + +ComPtr guest_root(ID3D12Device* guest, const D3D12_ROOT_SIGNATURE_DESC& desc, const char* name) +{ + ComPtr serialized, errors; + check(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, &errors), name); + ComPtr 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 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 result; + check(slot(guest, 86)(guest, &desc, __uuidof(ID3D12PipelineState), reinterpret_cast(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 new_dispatch_lines() +{ + std::vector 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 fresh; + if (all.size() > lines_seen) fresh.assign(all.begin() + static_cast(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 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(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(guest, 73)(guest, list_desc, allocator_.Get(), nullptr, __uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(list_.GetAddressOf())), "create guest command list"); + native_ = native_object(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(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(&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(&foreign_)); + srv(upload_); + }); + if (!ok) return false; + resolve(11); + check(slot(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(list_.Get(), 9)(list_.Get()), "close third recording"); + return execute(0, 2); + } + +private: + static constexpr UINT max_queries = 16; + + void reset() + { + check(slot(list_.Get(), 139)(list_.Get(), allocator_.Get(), nullptr, nullptr), "reset guest command list"); + upload_ = reinterpret_cast(slot(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(list_.Get(), 25)(list_.Get(), pipeline); + root(root_signature); + } + void root(IUnknown* root_signature) { slot(list_.Get(), 33)(list_.Get(), root_signature); } + void srv(UINT64 address) { slot
(list_.Get(), 43)(list_.Get(), 0, address); } + + template + bool expect(const Case& c, Setup setup) + { + setup(); + if (c.query >= 0) native_->BeginQuery(queries_.Get(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, c.query); + slot(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 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(got), static_cast(expected_[i].invocations)); + if (got != expected_[i].invocations) { + std::fprintf(stderr, "%s: CSInvocations %llu, expected %llu\n", expected_[i].label, + static_cast(got), static_cast(expected_[i].invocations)); + ok = false; + } + } + return ok; + } + + struct Expected { + const char* label; + UINT64 invocations; + }; + ID3D12Device* device_; + ID3D12Device* guest_; + bool skip_srv_; + ComPtr code_; + ComPtr root_a_, root_b_, root_table_, root_sampler_; + ComPtr pso_a_, pso_b_, pso_table_, pso_sampler_; + ComPtr queries_; + ComPtr readback_; + ComPtr queue_; + ComPtr fence_; + UINT64 fence_value_ = 0; + ComPtr allocator_; + ComPtr list_; + ComPtr native_; + UINT64 upload_ = 0; + std::uint32_t foreign_ = 0; + std::vector 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 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 factory; + check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "create DXGI factory"); + ComPtr 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 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 parameters{}; + ComPtr 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 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 storage(bytes); + auto* message = reinterpret_cast(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(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_memory_srv_buffer_check.cpp b/tests/startup_memory_srv_buffer_check.cpp index abc4c7005..cced3c949 100644 --- a/tests/startup_memory_srv_buffer_check.cpp +++ b/tests/startup_memory_srv_buffer_check.cpp @@ -5,6 +5,7 @@ // --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. // Each mutated run is a negative control and must fail. #include "startup_stubs/memory_srv_buffer.h" @@ -84,10 +85,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)) { 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]\n"); return 2; } const auto buf = buffer_desc(1024); @@ -301,6 +303,15 @@ 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)); + // 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 c8f4b0ec2..839017443 100644 --- a/tests/startup_memory_srv_census_check.cpp +++ b/tests/startup_memory_srv_census_check.cpp @@ -2,6 +2,7 @@ // 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 @@ -41,6 +42,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(AsSrvRefusal::none) + 1;; ++r) { + const char* name = as_srv_refusal_name(static_cast(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 +80,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, 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 539e9cb62..10753fbe5 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, 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 000000000..7ca3c62ab --- /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 000000000..66091ef85 --- /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 + startup_mesh57_lane_spill_check.py draw + +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(' 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 000000000..3537b099a --- /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 000000000..10aab1927 --- /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 + startup_mesh57_loop_check.py draw + +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(' 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(' + +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(' startup_mesh57_skeleton_check.py draw + startup_mesh57_skeleton_check.py depth + startup_mesh57_skeleton_check.py killexit startup_mesh57_skeleton_check.py formatted startup_mesh57_skeleton_check.py shift startup_mesh57_skeleton_check.py exchange @@ -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(' 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(' 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(' %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(' 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_packed_position_provenance_check.py b/tests/startup_packed_position_provenance_check.py new file mode 100644 index 000000000..b68fa1c55 --- /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 [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_.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 (.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('.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-28'))))) + 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 000000000..025cb23fc --- /dev/null +++ b/tests/startup_pixel_history.cpp @@ -0,0 +1,284 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#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 compile(const char* source, const char* entry, const char* target) +{ + ComPtr 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(errors->GetBufferPointer())); + check(hr, "compile shader"); + } + return code; +} + +ComPtr 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 blob, errors; + check(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &errors), "serialize root signature"); + ComPtr root; + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)), + "create root signature"); + return root; +} + +ComPtr 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 vs = compile(vertex, "main", "vs_5_1"); + const ComPtr 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 pipeline; + check(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)), "create pipeline"); + return pipeline; +} + +struct Target { + ComPtr device; + ComPtr texture, readback; + ComPtr 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; +} + +// A fresh target keeps the control independent of the first history: the clear value is the resource's +// initial content, so no extra clear command is needed. +void renew_texture(Target& target) +{ + target.texture.Reset(); + 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)), "renew target"); + target.device->CreateRenderTargetView(target.texture.Get(), nullptr, target.rtv); +} + +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(width), static_cast(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& 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 factory; + ComPtr adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + if (hardware) { + ComPtr factory6; + if (FAILED(factory.As(&factory6))) return 3; + for (UINT i = 0;; ++i) { + ComPtr 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"); + + // 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(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 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 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. + renew_texture(target); + std::vector 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 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 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 000000000..c26e09f79 --- /dev/null +++ b/tests/startup_pixel_history_draw_check.py @@ -0,0 +1,110 @@ +"""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") + 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 7c1c0c4ac..d505024ba 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, : VOP1 opcode 0x01, vdst=2, inline integer 0..64 (0x80 + n).""" + return struct.pack(', 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 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 000000000..92b887f80 --- /dev/null +++ b/tests/startup_pixel_uav.cpp @@ -0,0 +1,433 @@ +// X2W_TEST_PIXEL_UAV= (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 .uav, and the debug layer's +// errors are counted when it is on. +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +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 Word ptr(T* value) { return reinterpret_cast(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; + void* resources[textures]{}; + ComPtr natives[textures]; + void* array_resources[3]{}; + ComPtr array_natives[3]; +} fixture; + +ComPtr 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(invoke(guest, 5, ptr(&key), ptr(wrapped))))) return nullptr; + ComPtr stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = fixture.desktop->GetPrivateData(key, &bytes, stored.GetAddressOf()); + invoke(guest, 5, ptr(&key), 0); + ComPtr 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 queue; + ComPtr allocator; + ComPtr list; + ComPtr 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 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 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* 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(&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(&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* 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(&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(&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; +} + +ID3D12InfoQueue* debug_messages() +{ + static ComPtr 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.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((*static_cast(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(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(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((*static_cast(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(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(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((*static_cast(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(invoke(guest, 14, ptr(&rtv_heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&rtv_heap))))) + return 73; + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast(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 .uav; then the debug layer's error count. +int report_pixel_uavs(const char* pixels) +{ + std::vector words; + const bool copied = 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(words.data()), static_cast(words.size() * 4)); + if (!out) return 76; + } + const HRESULT removed = fixture.desktop->GetDeviceRemovedReason(); + std::printf("device removed reason: 0x%08lx\n", static_cast(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 storage(size); + auto* message = reinterpret_cast(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(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 000000000..8fd0594b5 --- /dev/null +++ b/tests/startup_pixel_uav_check.py @@ -0,0 +1,368 @@ +"""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= +(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 buffer +line, a 'channels' field and a view index out of order are refused when the manifest is loaded. +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 and tex2da views are bound)'), + ('a.buffer-line', 'uav 0 raw table 0 0', None, 'uav line refused (buffer view (raw uav) is not bound)'), + ('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, = self.cache.glob('*.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 2b395c945..b5806b6cf 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(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 000000000..e7e054724 --- /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 + +#include "startup_stubs/plane_compositor.h" +#include "startup_stubs/present_planes.h" + +#include +#include + +#include +#include +#include +#include +#include + +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(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(value), + static_cast(completed), static_cast(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(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(surfaces[i]); + const std::uint64_t pointer = reinterpret_cast(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 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(address); + const auto* lo = reinterpret_cast(&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(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 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(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(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& 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& 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(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(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(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 000000000..88473d3c6 --- /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 +#include + +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(address); + const auto* b = static_cast(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(first_plane)); + put(records + 0x48, 7); + put(records + 0x50, 2); + put(records + 0x58, reinterpret_cast(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(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_ps_input_scan_check.py b/tests/startup_ps_input_scan_check.py index fe2c44463..eaba71a97 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_resource_retire.cpp b/tests/startup_resource_retire.cpp index 2787867a0..d97928eb5 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 fa6fbaf4c..ce21bc438 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 @@ -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(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 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 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; @@ -371,7 +407,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-28"; // d3d12_draw.inl cached_translation constexpr char draw_vertex_shader[] = R"( struct Varying { float4 position : SV_Position; }; @@ -973,6 +1009,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(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 rtv_heap = c.make_descriptor_heap("rtv heap", D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1); + const UINT64 rtv0 = invoke(rtv_heap.Get(), 9); + invoke(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(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(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 rtv_copy = c.make_descriptor_heap("rtv copy heap", D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1); + const UINT64 rtv_copy0 = invoke(rtv_copy.Get(), 9); + invoke(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(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 desktop_heap; + if (!require(c.device->CreateDescriptorHeap(&desktop_heap_desc, IID_PPV_ARGS(&desktop_heap)), "untracked rtv heap")) + return false; + invoke(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 dsv_heap = c.make_descriptor_heap("dsv heap", D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1); + const UINT64 dsv0 = invoke(dsv_heap.Get(), 9); + invoke(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(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 uav_heap = c.make_descriptor_heap("uav heap", D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1); + const UINT64 uav0 = invoke(uav_heap.Get(), 9); + invoke(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(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(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 counter_heap = c.make_descriptor_heap("counter uav heap", D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1); + const UINT64 counter0 = invoke(counter_heap.Get(), 9); + invoke(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(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(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 tracked_heap = c.make_descriptor_heap("fallback rtv heap", D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1); + invoke(c.guest, 20, tracked.guest.Get(), &rtv, invoke(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 desktop_heap; + if (!require(c.device->CreateDescriptorHeap(&desktop_heap_desc, IID_PPV_ARGS(&desktop_heap)), "fallback rtv heap")) + return false; + invoke(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 heap = c.make_descriptor_heap("abi heap", D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1); + ComPtr other = c.make_descriptor_heap("abi second heap", D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1); + const UINT64 want = invoke(heap.Get(), 9, static_cast(nullptr)); + const UINT64 got = invoke(heap.Get(), 9, static_cast(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(got), static_cast(want), + static_cast(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((*reinterpret_cast(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(returned), static_cast(&buffer), + static_cast(buffer.ptr), static_cast(want)); + return false; + } + const UINT64 again = invoke(heap.Get(), 9, static_cast(nullptr)); + if (again != want) { + std::printf("FAIL: heap start changed after the calls above: got %#llx, expected %#llx\n", + static_cast(again), static_cast(want)); + return false; + } + return true; +} + } // namespace int main(int argc, char** argv) @@ -1023,10 +1263,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 +1309,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 6db82d289..263dd96dc 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 [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 @@ -417,75 +402,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(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(c.guest, 18, static_cast(nullptr), &srv, heap.cpu + c.increment * static_cast(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(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(c.guest, 18, T.guest.Get(), &srv, visible.cpu + c.increment); + invoke(c.guest, 18, texture.guest.Get(), &srv, visible.cpu + c.increment); invoke(c.guest, 24, 1u, staging.cpu, visible.cpu + c.increment, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); ComPtr 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(c.guest, 18, T3.guest.Get(), &srv, visible.cpu + 2 * c.increment); invoke(c.guest, 18, T4.guest.Get(), &srv, visible.cpu + 3 * c.increment); @@ -494,30 +478,31 @@ bool case3_list_holds(Context& c, bool on, GuestHeap& visible) invoke(submitted.list.Get(), 17, D3.guest.Get(), T3.guest.Get()); invoke(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 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 +558,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 +622,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 +636,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 000000000..a07bb3acf --- /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 +#include + +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_run_ps1_check.py b/tests/startup_run_ps1_check.py index 8d9c55a68..2f90f43b4 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -14,6 +14,7 @@ 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" @@ -92,6 +93,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: ". @@ -122,7 +136,7 @@ def alive(pid): 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): """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. @@ -136,9 +150,10 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), (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") (startup / "gfx2hlsl.py").write_text(WATCH_STUB.format(early_exit=early_exit), encoding="utf-8") - (root / "bld").mkdir() + 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"") + (build / f"{dll}.dll").write_bytes(b"") exe, data, log = root / "run" / "t.exe", root / "data", root / "log" exe.parent.mkdir() exe.write_bytes(b"") @@ -156,8 +171,12 @@ 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", "") + 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", + "-Exe", str(exe), "-DataDir", str(data), "-LogDir", str(log), + "-BuildDir", build_arg, "-Seconds", "9", "-MemoryGiB", "3", "-ContinueAsserts", "4", *switches] if translate: command += ["-Render", "-Translate", "-ShaderCache", "cache"] @@ -175,11 +194,15 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), printed = [line.strip() for line in stdout if line.strip()] error_text = stderr.read().strip() 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] 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})") @@ -218,6 +241,9 @@ 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) + 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: @@ -295,6 +321,59 @@ 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: + 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 +388,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_runtime_proxy_scope/decoy.cpp b/tests/startup_runtime_proxy_scope/decoy.cpp index ddba2565e..86f8aefe3 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 223c116b5..9da19864b 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 ec4221b3e..516e65269 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(GetProcAddress(xgr, "query_calls")) : nullptr; const auto decoy_seen = decoy ? reinterpret_cast(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(GetProcAddress(decoy, "registry_query_calls")) : nullptr; + DWORD type = 0, bytes = 0; + const LONG expect_real = advapi_reg ? reinterpret_cast(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(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(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(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_shader_cache_key_check.py b/tests/startup_shader_cache_key_check.py index 7a7d7218a..e4b0733b6 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-28 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) == 0xe4791179bf7096b3 + assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0xf6cb7f56c2985cfb 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 fc9a5ffa1..978639b90 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 c8bee38eb..39a3f850a 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_slot133_heap_cap_check.cpp b/tests/startup_slot133_heap_cap_check.cpp new file mode 100644 index 000000000..dce82648f --- /dev/null +++ b/tests/startup_slot133_heap_cap_check.cpp @@ -0,0 +1,818 @@ +// 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 [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 +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +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 +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +template +ComPtr desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast(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(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((index * 131 + seed * 37 + 19) & 0xff); +} + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(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(xmem), static_cast(d3d), GetLastError()); + return false; + } + g_xmem_virtual_alloc = reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")); + g_create_xbox_device = reinterpret_cast(GetProcAddress(d3d, "D3D12XboxCreateDevice")); + g_budget_snapshot = reinterpret_cast(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 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(rb_bytes)}; + if (!require(rb->Map(0, &range, &mapped), "readback map")) return false; + const auto* got = static_cast(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 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(bytes)}; + if (!require(rb->Map(0, &range, &mapped), "buffer readback map")) return false; + const auto* got = static_cast(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( + 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 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(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(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(D3D12_COMMAND_LIST_TYPE_DIRECT), 2, 1, 0}; + ComPtr 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(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 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(page)}; + if (!require(late_readback->Map(0, &prime_range, &primed), "late-write readback prime map")) return 4; + std::memset(primed, 0x6d, static_cast(page)); + late_readback->Unmap(0, nullptr); + + // Slot 15 takes the raw desktop readback pointer as its destination (copy_endpoint). + invoke(late_list.Get(), 15, reinterpret_cast(late_readback.Get()), UINT64{0}, + reinterpret_cast(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(page)); + + IUnknown* late_lists[] = {late_list.Get()}; + invoke(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(page)}; + if (!require(late_readback->Map(0, &late_read_range, &late_mapped), "late-write readback map")) return 4; + const auto* late_got = static_cast(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(late_stale), static_cast(page), + static_cast(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 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(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 own_queue; + ComPtr own_alloc; + ComPtr own_list; + ComPtr 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( + VirtualAlloc(nullptr, small_block_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!check(small_block != nullptr, "VirtualAlloc 4 MiB block")) return 4; + ComPtr 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(guest, device, small_a.Get()); + const auto small_b_real = desktop_object(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( + 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 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(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 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(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( + 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 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(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(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(D3D12_COMMAND_LIST_TYPE_DIRECT), 2, 1, 0}; + ComPtr 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(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& backing, + ComPtr& src, ComPtr& 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 small_mem, small2_mem, big_mem, small3_mem; + ComPtr 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(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(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(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(guest, device, small_dst.Get()); + const auto small2_dst_real = desktop_object(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(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(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(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(guest, device, big_dst.Get()); + const auto small3_dst_real = desktop_object(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) +{ + 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 [cap]"); + return 2; + } + const bool warp = std::strcmp(argv[1], "warp") == 0; + const bool cap = argc == 3; + if (!load_shims(cap)) return 3; + + ComPtr 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 debug_iface; + if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug_iface)))) return 77; + } + + ComPtr guest; + ComPtr device; + std::array parameters{}; + if (!require(g_create_xbox_device(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf())), + "Xbox device") || + !require(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)), "desktop device")) + return 3; + + ComPtr 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(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(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 000000000..f3389e2a1 --- /dev/null +++ b/tests/startup_slot67_indirect.cpp @@ -0,0 +1,93 @@ +#include "startup_slot67_indirect.h" +#include "startup_indirect_writer.h" +#include "startup_stream_setup.h" +#include +#include +#include +#include + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +using Microsoft::WRL::ComPtr; + +namespace { +using Record = std::array; +constexpr Record initial{0xa5a5a5a5, 0, 0, 0, 0x5a5a5a5a}; +constexpr UINT offset = sizeof(UINT); // guards on either side of the three-DWORD 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(value); } +} + +void Slot67Indirect::prepare(IDXGIAdapter* adapter, void* guest_device, void* guest_list, void* backing, UINT groups) +{ + auto* guest = static_cast(guest_device); + ComPtr device; + check(D3D12XboxCreateDevice(adapter, nullptr, IID_PPV_ARGS(&device)), "open producer's desktop device"); + auto list = indirect_native_object(device.Get(), guest, static_cast(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(invoke(guest, 133, word(backing), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(placed.GetAddressOf()))), "place indirect arguments"); + auto args = indirect_native_object(device.Get(), guest, placed.Get()); + 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) { + 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 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); +} + +bool Slot67Indirect::check_record(UINT groups) const +{ + const D3D12_RANGE range{0, sizeof(initial)}, empty{0, 0}; + void* mapped = nullptr; + check(readback->Map(0, &range, &mapped), "map GPU argument readback after consumer fence"); + Record actual{}; + std::memcpy(actual.data(), mapped, sizeof(actual)); + readback->Unmap(0, &empty); + const Record expected{initial.front(), groups, groups ? 1u : 0u, groups ? 1u : 0u, initial.back()}; + std::printf("GPU argument record: %08x [%u,%u,%u] %08x\n", actual[0], actual[1], actual[2], actual[3], actual[4]); + std::fflush(stdout); + return actual == expected; +} diff --git a/tests/startup_slot67_indirect.h b/tests/startup_slot67_indirect.h new file mode 100644 index 000000000..7aaba4a6a --- /dev/null +++ b/tests/startup_slot67_indirect.h @@ -0,0 +1,16 @@ +#pragma once +#include +#include +#include + +// Keeps the producer, argument resource and signature alive until the consumer's queue fence. +struct Slot67Indirect { + Microsoft::WRL::ComPtr root; + Microsoft::WRL::ComPtr writer; + Microsoft::WRL::ComPtr placed, upload, readback; + Microsoft::WRL::ComPtr signature; + + void prepare(IDXGIAdapter* adapter, void* guest_device, void* guest_list, void* backing, UINT groups); + void execute(void* guest_list, UINT commands, bool count_buffer, bool outside) const; + bool check_record(UINT groups) const; +}; diff --git a/tests/startup_slot67_indirect_dispatch_check.py b/tests/startup_slot67_indirect_dispatch_check.py new file mode 100644 index 000000000..c6f1db049 --- /dev/null +++ b/tests/startup_slot67_indirect_dispatch_check.py @@ -0,0 +1,167 @@ +"""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. +""" +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_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 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] + 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, 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 | ' + 'binary | mutation') diff --git a/tests/startup_smem_address_check.py b/tests/startup_smem_address_check.py index e2d53f0f3..ba169a9e8 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 fdc7cfeae..a3ca4a7d1 100644 --- a/tests/startup_stage_package_check.py +++ b/tests/startup_stage_package_check.py @@ -12,7 +12,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 +22,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 +85,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") diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index e7dcab0a2..eddf880ff 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -15,9 +15,11 @@ #include "startup_stream_draw.h" #include "startup_stream_setup.h" +#include "startup_slot67_indirect.h" 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 +163,353 @@ 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-sampled, dispatch-sampled-unbound, dispatch-sampled-2x1, dispatch-heap, +// dispatch-heap-outside, dispatch-heap-word*, dispatch-input-*: one creation, then dispatch_slot67 below +// texture-store, texture-store-none, texture-store-denied, texture-store-occupied, texture-store-copied: 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((*static_cast(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-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-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-token writes the token of a texture view where the input descriptor was. +// 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. +static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::string& mode) +{ + constexpr UINT words = 320; + const bool indirect = mode.rfind("dispatch-indirect-", 0) == 0; + const UINT groups = mode == "dispatch-indirect-zero" ? 0u : mode == "dispatch-indirect-2" ? 2u : 5u; + auto* memory = static_cast(VirtualAlloc(nullptr, indirect ? 0x30000 : 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!memory) return 70; + UINT* const buffers[2] = {memory, memory + 0x10000 / sizeof(UINT)}; + for (UINT i = 0; i < words; ++i) { + buffers[0][i] = 0x8b02a7f1u + i * 0x413b1u; + buffers[1][i] = 0xc5c5c5c5u; + } + UINT fields[2][3] = {{4, 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(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)); + const auto word = [](const void* value) { return reinterpret_cast(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}; + if (FAILED(static_cast(invoke(device, 133, word(buffers[i]), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(&placed[i]))))) return 71; + const UINT64 address = reinterpret_cast(buffers[mode == "dispatch-same-buffer" ? 1 : i]); + const UINT view[4] = {static_cast(address), static_cast(address >> 32) | fields[i][0] << 16, fields[i][1], fields[i][2]}; + std::memcpy(descriptors[mode == "dispatch-swapped" ? 1 - i : i], view, sizeof(view)); + } + const UINT64 between = reinterpret_cast(memory) + 0x8000; + if (mode == "dispatch-input-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}; + void* copied = nullptr; + if (FAILED(static_cast(invoke(device, 133, word(reinterpret_cast(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-past") { + descriptors[0][2] = words + 4; + } else if (mode == "dispatch-input-unplaced" || mode == "dispatch-input-copied") { + descriptors[0][0] = static_cast(between); + descriptors[0][1] = static_cast(between >> 32) | 4u << 16; + } + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, 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(list_type), 2, 1, 0}; + if (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&heap)))) || + FAILED(static_cast(invoke(device, 8, word(&queue_desc), word(&__uuidof(ID3D12CommandQueue)), word(&queue)))) || + FAILED(static_cast(invoke(device, 9, list_type, word(&__uuidof(ID3D12CommandAllocator)), word(&allocator)))) || + FAILED(static_cast(invoke(device, 73, word(list_desc), word(allocator), 0, word(&__uuidof(ID3D12GraphicsCommandList)), word(&list)))) || + FAILED(static_cast(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(memory) + 0x20000; + const UINT alias[4] = {static_cast(address), static_cast(address >> 32) | (4u << 16), 5, 0}; + std::memcpy(descriptors[1], alias, sizeof(alias)); + } + std::memcpy(reinterpret_cast(cpu), descriptors, sizeof(descriptors)); + const bool heap_record = mode.rfind("dispatch-heap", 0) == 0; + if (heap_record) + for (const UINT at : {0u, 32u, 64u}) + std::memcpy(reinterpret_cast(cpu + at), descriptors[at != 64], sizeof(descriptors[0])); + const bool heap_word = mode.rfind("dispatch-heap-word", 0) == 0; + const UINT constants[3] = {0x01234567, 0x9e3779b9, 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(invoke(list, 139, word(allocator))))) return 74; + Slot67Indirect record; + if (indirect) record.prepare(adapter, device, list, memory + 0x20000 / sizeof(UINT), groups); + bind(); + if (mode.rfind("dispatch-sampled", 0) == 0 || mode == "dispatch-input-token") { + const UINT width = mode == "dispatch-sampled-2x1" ? 2 : 1; + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {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(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; + std::memcpy(texel, rgba, sizeof(rgba)); + invoke(upload, 9, 0, 0); + D3D12_TEXTURE_COPY_LOCATION image{static_cast(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION source{static_cast(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + source.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, width, 1, 1, 256}}; + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + D3D12_SHADER_RESOURCE_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM, 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)); + } + 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(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(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(cpu + sizeof(descriptors[0])), descriptors[1], sizeof(descriptors[1])); + std::memcpy(unplaced + 4, buffers[0], words * sizeof(UINT)); + } + 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(invoke(list, 9))) || FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + bind(); + } + if (heap_record) 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(reinterpret_cast(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(mode == "dispatch-heap-word-placed" ? buffers[0] : index); + const UINT view[4] = {static_cast(address), static_cast(address >> 32), + mode == "dispatch-heap-word-past" ? at : mode == "dispatch-heap-word-placed" ? words * 4 : bytes, 0}; + std::memcpy(reinterpret_cast(cpu + 96), view, sizeof(view)); + } + invoke(list, 35, 1, gpu); + if (indirect) record.execute(list, mode == "dispatch-indirect-multi" ? 2 : 1, + mode == "dispatch-indirect-counted", mode == "dispatch-indirect-outside"); + 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") invoke(list, 14, 3, 2, 2); + if (FAILED(static_cast(invoke(list, 9)))) return 75; + invoke(queue, 10, 1, word(&list)); + if (FAILED(static_cast(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); + } + if (indirect && !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 + 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(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. +static int texture_slot67(void* device, const std::string& mode) +{ + constexpr UINT width = 32, height = 8; + const bool fp32 = mode == "texture-array" || mode == "texture-array-2d"; + const UINT layers = mode == "texture-array" || mode == "texture-array-d16" ? 6 : 1; + const UINT pitch = width * (fp32 ? 16 : 8), slice_bytes = pitch * height, bytes = slice_bytes * layers; + const auto word = [](const void* value) { return reinterpret_cast(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 = fp32 ? DXGI_FORMAT_R32G32B32A32_FLOAT : + mode == "texture-store-uint" ? DXGI_FORMAT_R16G16B16A16_UINT : DXGI_FORMAT_R16G16B16A16_FLOAT; + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, static_cast(layers), 1, 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(invoke(upload, 8, 0, 0, word(&memory)))) || !memory) return 71; + if (fp32) { + for (UINT layer = 0; layer < layers; ++layer) + for (UINT i = 0; i < slice_bytes / 4; ++i) + static_cast(memory)[layer * slice_bytes / 4 + i] = 0xbf000000u | (layer << 12) | i; + } else { + for (UINT i = 0; i < bytes / 2; ++i) static_cast(memory)[i] = static_cast(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, 4, 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(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&heap)))) || + FAILED(static_cast(invoke(device, 8, word(&queue_desc), word(&__uuidof(ID3D12CommandQueue)), word(&queue)))) || + FAILED(static_cast(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&__uuidof(ID3D12CommandAllocator)), word(&allocator)))) || + FAILED(static_cast(invoke(device, 73, word(list_desc), word(allocator), 0, word(&__uuidof(ID3D12GraphicsCommandList)), word(&list)))) || + FAILED(static_cast(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 (layers > 1) { + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + view.Texture2DArray = {0, 1, 4, 0}; // four selected slices, with untouched neighbors on both sides + } + 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(cpu + 64), reinterpret_cast(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); + } + 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); + D3D12_TEXTURE_COPY_LOCATION image{static_cast(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION source{static_cast(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + source.PlacedFootprint = {0, {format, width, height, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION result = source; + result.pResource = static_cast(readback); + const UINT constants[3] = {1, 2, 3}; + if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + invoke(list, 32, 1, word(&heap)); + for (UINT layer = 0; layer < layers; ++layer) { + image.SubresourceIndex = layer; + source.PlacedFootprint.Offset = UINT64{layer} * slice_bytes; + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + } + 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); + for (UINT layer = 0; layer < layers; ++layer) { + image.SubresourceIndex = layer; + result.PlacedFootprint.Offset = UINT64{layer} * slice_bytes; + invoke(list, 16, word(&result), 0, 0, 0, word(&image), 0); + } + if (FAILED(static_cast(invoke(list, 9)))) return 75; + invoke(queue, 10, 1, word(&list)); + if (FAILED(static_cast(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(invoke(readback, 8, 0, 0, word(&memory)))) || !memory) return 2; + std::ofstream(path, std::ios::binary).write(static_cast(memory), bytes); + invoke(readback, 9, 0, 0); + return 0; +} + 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 +518,7 @@ static bool create_slot67(void* device, const char* code_path, const char* data_ std::vector state{std::istreambuf_iterator(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 +567,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((*static_cast(device))[67])(device, d, __uuidof(ID3D12PipelineState), &pipeline)) && + const bool created = SUCCEEDED(reinterpret_cast((*static_cast(device))[67])(device, d, __uuidof(ID3D12PipelineState), &pipeline)) && pipeline; + slot67_pipeline = pipeline; + slot67_root = root; + return created; }; if (m == "order") { if (!create(desc)) return false; @@ -258,13 +610,29 @@ int main(int argc, char** argv) ComPtr 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; // slot67 [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(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 34a837861..26b37f639 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -192,6 +192,114 @@ 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(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(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(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(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(invoke(guest, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue)))) || + FAILED(static_cast(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator)))) || + FAILED(static_cast(invoke(guest, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) || + FAILED(static_cast(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(target)}; + const std::uint64_t token = 7, count_one = 1, resources_ptr = reinterpret_cast(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(invoke(allocator, 8))) || + FAILED(static_cast(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(width), static_cast(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(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(invoke(allocator, 8))) || + FAILED(static_cast(invoke(list, 139, arg(allocator))))) return 35; + D3D12_TEXTURE_COPY_LOCATION to{static_cast(readback), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION from{static_cast(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(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(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); @@ -293,6 +401,8 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* const UINT height = bc_chain ? 32 : bc7 ? bc7->height : bc ? 128 : single ? 1 : 4; ComPtr 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 +417,69 @@ 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; + 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(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(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(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(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(index_memory); + for (UINT i = 0; i < 3; ++i) words[i] = static_cast(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(width), static_cast(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*); @@ -323,7 +495,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 +507,12 @@ 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_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 +525,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 @@ -403,8 +584,9 @@ 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. + // 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(invoke(list, 9))) || !next_recording()) return 35; @@ -420,7 +602,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(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 +610,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(invoke(queue, 14, arg(fence), payloads + 1))) || !reached(payloads + 1)) return 25; @@ -492,6 +677,12 @@ 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 (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; diff --git a/tests/startup_stream_fetch_check.py b/tests/startup_stream_fetch_check.py index 94fc6499f..c7b253041 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 bc3c55c84..2f094c361 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 09a1ad6c0..929f4d3e2 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -12,6 +12,7 @@ #include #include +#include "adapter_name_filter.h" #include "startup_stream_setup.h" using Microsoft::WRL::ComPtr; @@ -79,32 +80,20 @@ int pick_stream_adapter(bool hardware, ComPtr& 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 factory6; if (FAILED(factory.As(&factory6))) return 77; for (UINT n = 0;; ++n) { ComPtr 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; @@ -141,16 +130,18 @@ 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; + const D3D12_DESCRIPTOR_RANGE srv{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 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}; @@ -198,7 +189,10 @@ 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[8] = L""; + GetEnvironmentVariableW(L"X2W_TEST_INPUT_LAYOUT", layout_mode, 8); + const bool empty_layout = std::wcscmp(layout_mode, L"empty") == 0; // declared layout with zero elements + LayoutStream with_layout{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, {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()}}}}; diff --git a/tests/startup_teardown_unload.cpp b/tests/startup_teardown_unload.cpp index 44cc0297d..af71c53d3 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 // // 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 detached= released= +// +// 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= +// 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 #include @@ -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& factory, ComPtr(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(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(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(GetProcAddress(module, "D3D12XboxCreateDevice")); probe = reinterpret_cast(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(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(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(probe), reinterpret_cast(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& 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 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 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(before), static_cast(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(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(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(before), static_cast(warm)); + FreeLibrary(shim); + return 6; + } } if (!FreeLibrary(shim)) { std::fprintf(stderr, "%s: FreeLibrary failed: %lu\n", cache.name, static_cast(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(held[slot]), + static_cast(after), static_cast(held[slot] - 1)); + release_placed(heap, objects); + return 9; + } + std::printf("unload %s: slot %u reference %lu -> %lu\n", cache.name, slot, + static_cast(held[slot]), static_cast(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(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(last)); + return 16; + } + std::printf("unload %s: heap released last, %lu -> 0\n", cache.name, static_cast(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 factory; + ComPtr 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 device; - HRESULT hr = create(adapter, nullptr, __uuidof(ID3D12Device), + HRESULT hr = create(adapter.Get(), nullptr, __uuidof(ID3D12Device), reinterpret_cast(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(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(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(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(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 \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(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(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 c2fcba5db..75337d70f 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -203,6 +203,9 @@ 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", "partial_tile_xg_rows"), @@ -224,6 +227,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: diff --git a/tests/startup_triage_run_cli_check.py b/tests/startup_triage_run_cli_check.py new file mode 100644 index 000000000..346be0e1b --- /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_vertex_fetch_formats_check.py b/tests/startup_vertex_fetch_formats_check.py index 187fa7b56..0dcdc6480 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 000000000..84dd71acb --- /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 [control] +// (X2W_D3D12_BUDGET=1 X2W_D3D12_RELEASE_RETIRED=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_RENDER=1 X2W_TRAP_LOG=) +// "control" never arms the failure, so the armed expectations must fail and the fixture must print FAIL. +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +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 +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +int failures; + +void expect(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(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(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 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 guest, heap; + std::array parameters{}; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(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(heap.Get(), 9); + const UINT stride = invoke(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 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(nullptr), &iid, + reinterpret_cast(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(guest.Get(), 18, static_cast(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(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 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(nullptr), &iid, + reinterpret_cast(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(guest.Get(), 19, static_cast(buffers[index].Get()), + static_cast(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 000000000..d11b99cfd --- /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 [off|vary] +// (X2W_D3D12_BUDGET=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_RENDER=1 X2W_D3D12_VIEW_CENSUS=1 X2W_TRAP_LOG=) +// "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 + +#include +#include +#include +#include + +#include +#include +#include +#include + +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 +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(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(hr)); + return SUCCEEDED(hr); +} + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(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(&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(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(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(guest, 18, static_cast(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(index) / 16.0f; + desc.MaxAnisotropy = 1; + desc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; + desc.MaxLOD = D3D12_FLOAT32_MAX; + invoke(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(after_repeated - before_repeated), + static_cast(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 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 guest, views, samplers; + std::array parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(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(views.Get(), 9), invoke(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(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 000000000..319d88ffd --- /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 +#include + +#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 000000000..823b6c7c7 --- /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 [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 +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +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 +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +template +ComPtr desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast(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(hr)); + return SUCCEEDED(hr); +} + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(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 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 queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + UINT64 value = 0; + HANDLE event = nullptr; + ComPtr upload, readback, probe_out; + ComPtr root; + ComPtr pso; + ComPtr heap; + ComPtr 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 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 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(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(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 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 guest; + ComPtr device; + std::array parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(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 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(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(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(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(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(c.guest, 18, texture_b.Get(), &valid, c.slot(2)); + invoke(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(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(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(c.guest, 19, uav_texture.Get(), static_cast(nullptr), &uav, uav_slot); + if (!c.device_ok()) return 5; + std::array before{}, after{}; + std::memcpy(before.data(), reinterpret_cast(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(c.guest, 19, uav_texture.Get(), static_cast(nullptr), &uav, uav_slot); + std::memcpy(after.data(), reinterpret_cast(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_wrap_allocation.cpp b/tests/startup_wrap_allocation.cpp new file mode 100644 index 000000000..c2d0b02ec --- /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 + +#include +#include +#include + +#include +#include +#include +#include + +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 +HRESULT invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = HRESULT (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(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 +void check(const char* name, Create create) +{ + ComPtr 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(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(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 factory; + ComPtr adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) + return 77; + std::array parameters{}; + + // Device creation itself: the desktop device reference is released and the output stays null. + ComPtr device; + check("D3D12XboxCreateDevice", [&](IUnknown** out) { + return D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), reinterpret_cast(out)); + }); + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(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(nullptr), 0u, static_cast(nullptr), + &__uuidof(ID3D12PipelineState), reinterpret_cast(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(out)); + }); + + // A failed device creation must leave the previously published device visible to its children. + if (!control) { + ComPtr existing_queue; + HRESULT hr = invoke(device.Get(), 8, &queue, &__uuidof(ID3D12CommandQueue), + reinterpret_cast(existing_queue.GetAddressOf())); + if (FAILED(hr) || !existing_queue) return 3; + + ComPtr second_device; + arm(); + hr = D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(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 parent; + hr = existing_queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast(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 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(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(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(out)); + }); + + // Slot 73, command list on that allocator: a desktop list is created before the 64 KiB list wrapper. + ComPtr allocator; + if (FAILED(invoke(device.Get(), 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), + reinterpret_cast(allocator.GetAddressOf())))) + return 3; + const std::array list_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + check("Device::slot73 command list", [&](IUnknown** out) { + return invoke(device.Get(), 73, static_cast(list_desc.data()), static_cast(allocator.Get()), + static_cast(nullptr), &__uuidof(ID3D12GraphicsCommandList), reinterpret_cast(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(nullptr), + static_cast(nullptr), 0u, static_cast(nullptr), &__uuidof(ID3D12Resource), + reinterpret_cast(out)); + }); + + const auto free_backing = [](void* ptr) { VirtualFree(ptr, 0, MEM_RELEASE); }; + const std::unique_ptr 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(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(D3D12_RESOURCE_STATE_COMMON), + static_cast(nullptr), &__uuidof(ID3D12Resource), reinterpret_cast(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_xcrdapi_lifetime.cpp b/tests/startup_xcrdapi_lifetime.cpp new file mode 100644 index 000000000..8df0308ce --- /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 + +#include +#include +#include +#include + +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(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(self); + reinterpret_cast(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 payload(piece); + for (unsigned i = 0; i < piece; ++i) payload[i] = static_cast((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(GetProcAddress(library, "DStorageGetFactory")) : nullptr; + auto* live_objects = library ? reinterpret_cast(GetProcAddress(library, "x2w_xcrdapi_live_objects")) : nullptr; + auto* live_workers = library ? reinterpret_cast(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(factory_ptr); + unsigned char description[0x28] = {}; + *reinterpret_cast(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(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(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(static_cast(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(static_cast(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(factory->vtable[4])(factory, data_path, nullptr, &file1) != 0 || !file1) return 2; + if (reinterpret_cast(factory->vtable[5])(factory, 4, "Pending", nullptr, &status1) != 0 || !status1) return 2; + if (reinterpret_cast(factory->vtable[10])(factory, description, nullptr, &queue1) != 0 || !queue1) return 2; + auto* queue = static_cast(queue1); + auto* status = static_cast(status1); + void* fence_vtable[11] = {}; + fence_vtable[10] = reinterpret_cast(&Fence::signal); + Fence first{}, barrier{}; + first.vtable = fence_vtable; + barrier.vtable = fence_vtable; + + std::vector destination(piece, 0xA5); + alignas(8) unsigned char request[0x48] = {}; + *reinterpret_cast(request + 0x08) = destination.data(); + *reinterpret_cast(request + 0x18) = piece; + *reinterpret_cast(request + 0x20) = file1; + *reinterpret_cast(request + 0x30) = piece; + reinterpret_cast(queue->vtable[3])(queue, request); + reinterpret_cast(queue->vtable[4])(queue, status, 0); + reinterpret_cast(queue->vtable[5])(queue, &first, 0x100); + // A barrier behind the request: when it runs, the request's entry has released its references. + reinterpret_cast(queue->vtable[5])(queue, &barrier, 0x101); + + // The guest drops the file while the request is pending. + reinterpret_cast(static_cast(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(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(status->vtable[3])(status, 0), "the status entry did not complete") && ok; + ok = expect(reinterpret_cast(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(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(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(factory->vtable[4])(factory, data_path, nullptr, &file2) != 0 || !file2) return 2; + if (reinterpret_cast(factory->vtable[5])(factory, 4, "Unsubmitted", nullptr, &status2) != 0 || !status2) return 2; + if (reinterpret_cast(factory->vtable[10])(factory, description, nullptr, &queue2) != 0 || !queue2) return 2; + auto* queue_2 = static_cast(queue2); + alignas(8) unsigned char request2[0x48] = {}; + *reinterpret_cast(request2 + 0x08) = destination.data(); + *reinterpret_cast(request2 + 0x18) = piece; + *reinterpret_cast(request2 + 0x20) = file2; + *reinterpret_cast(request2 + 0x30) = piece; + reinterpret_cast(queue_2->vtable[3])(queue_2, request2); + reinterpret_cast(queue_2->vtable[4])(queue_2, static_cast(status2), 1); + reinterpret_cast(static_cast(file2)->vtable[2])(file2); + reinterpret_cast(static_cast(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(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(factory->vtable[4])(factory, data_path, nullptr, &file3) != 0 || !file3) return 2; + if (reinterpret_cast(factory->vtable[5])(factory, 4, "WorkerRelease", nullptr, &status3) != 0 || !status3) return 2; + if (reinterpret_cast(factory->vtable[10])(factory, description, nullptr, &queue3) != 0 || !queue3) return 2; + auto* queue_3 = static_cast(queue3); + auto* status_3 = static_cast(status3); + void* release_vtable[11] = {}; + release_vtable[10] = reinterpret_cast(&ReleasingFence::signal); + ReleasingFence releasing{}; + releasing.vtable = release_vtable; + releasing.queue = queue_3; + alignas(8) unsigned char request3[0x48] = {}; + *reinterpret_cast(request3 + 0x08) = destination.data(); + *reinterpret_cast(request3 + 0x18) = piece; + *reinterpret_cast(request3 + 0x20) = file3; + *reinterpret_cast(request3 + 0x30) = piece; + reinterpret_cast(queue_3->vtable[3])(queue_3, request3); + reinterpret_cast(queue_3->vtable[4])(queue_3, status_3, 0); + reinterpret_cast(queue_3->vtable[5])(queue_3, &releasing, 0x200); + reinterpret_cast(static_cast(file3)->vtable[2])(file3); + reinterpret_cast(status_3->vtable[2])(status3); + reinterpret_cast(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(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/texture_descriptors_cli_check.py b/tests/texture_descriptors_cli_check.py new file mode 100644 index 000000000..daac72a8b --- /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(" 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 000000000..83cad82e1 --- /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 +#include +#include + +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(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/unified_buffer_paths_check.cpp b/tests/unified_buffer_paths_check.cpp index fe8d868a3..1a0b74089 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 000000000..9b84a3b4d --- /dev/null +++ b/tests/upload_reservation_check.cpp @@ -0,0 +1,116 @@ +#include "startup_stubs/upload_reservation.h" + +#include +#include +#include +#include +#include +#include + +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 storage(new unsigned char[max_upload_ring_bytes]); + std::array 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> 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"); +} + +} // namespace + +int main() +{ + unsigned char storage_a[4 * kAlign]; + unsigned char storage_b[8 * kAlign]; + std::vector 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(); + std::puts("upload_reservation_check: all checks passed"); + return 0; +} diff --git a/tests/xmem_lazy_startup_check.py b/tests/xmem_lazy_startup_check.py index e98f519e3..48171e9af 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_page_stats_check.py b/tests/xmem_page_stats_check.py index 85a2d2601..73c46271f 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 000000000..b02284dd6 --- /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 +Each case runs in a process of its own (--child ), 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_slab_slots_check.cpp b/tests/xmem_slab_slots_check.cpp index e2dc7157a..023789fc0 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 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 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/tools/bink_descriptors_aot.py b/tools/bink_descriptors_aot.py index f6638f4db..da1f62f8e 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 9b72bb297..8ccef7594 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 430f39223..49455a304 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 5261d880e..0d8a2865d 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 a76f40afd..2ed0625df 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_ 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,141 @@ "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_(?Pwrite|read)_b(?P32|64|128) (?Pv\d+|v\[\d+:\d+\]), (?Pv\d+|v\[\d+:\d+\])" + r"(?: offset:(?P\d+))?", + r"ds_(?Pwrite2|write2st64)_b(?P32|64) (?Pv\d+), (?Pv\d+|v\[\d+:\d+\]), (?Pv\d+|v\[\d+:\d+\])" + r"(?: offset0:(?P\d+))?(?: offset1:(?P\d+))?", + r"ds_(?Pread2|read2st64)_b(?P32|64) (?Pv\[\d+:\d+\]), (?Pv\d+)" + r"(?: offset0:(?P\d+))?(?: offset1:(?P\d+))?", + rf"ds_(?P{'|'.join(LDS_SHARED_ATOMICS)}) (?Pv\d+), (?Pv\d+)(?: offset:(?P\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) + if op == "sub_u32": + value = f"(0u - {value})" + method = LDS_SHARED_ATOMICS[op] + 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 +485,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 +758,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 +787,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 +831,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 +869,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 +880,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 +927,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 +1010,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 +1022,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 +1069,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 +1137,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 +1205,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 +1424,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 +1759,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 +1780,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 +2330,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 +2454,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 +2466,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 +2615,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 +2692,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 +2760,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 +3026,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N r"s\[(?P\d+):(?P\d+)\], 0" r"(?P idxen)?(?P offen)?(?: offset:(?P\d+))?(?P 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 +3047,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 +3078,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 +3103,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 +3138,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[234]))?|(?Pbyte|short)(?P_d16_hi)?)|" r"(?Pt)?buffer_store_format_(?P(?:d16_)?(?:x|xy|xyz|xyzw))) " @@ -3106,6 +3375,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 +3467,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 cf3dbeb55..e90a51e0f 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) + "", 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_aes_pclmul_aot.py b/tools/cpu_aes_pclmul_aot.py new file mode 100644 index 000000000..50c09626a --- /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_(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 ). + +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 +#include +#include +#if defined(_MSC_VER) +#include +#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(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(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(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(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(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(aes_gf_mul(2u, a0) ^ aes_gf_mul(3u, a1) ^ a2 ^ a3); + out[c * 4u + 1u] = static_cast(a0 ^ aes_gf_mul(2u, a1) ^ aes_gf_mul(3u, a2) ^ a3); + out[c * 4u + 2u] = static_cast(a0 ^ a1 ^ aes_gf_mul(2u, a2) ^ aes_gf_mul(3u, a3)); + out[c * 4u + 3u] = static_cast(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(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(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(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(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(AES_SBOX[w & 0xFFu]) + | (static_cast(AES_SBOX[(w >> 8) & 0xFFu]) << 8) + | (static_cast(AES_SBOX[(w >> 16) & 0xFFu]) << 16) + | (static_cast(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(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_avx_cmp_aot.py b/tools/cpu_avx_cmp_aot.py new file mode 100644 index 000000000..1e9bbf03a --- /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_(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 +#include +#include +#include +#if defined(_MSC_VER) +#include +#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(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(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(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(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(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(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(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(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(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(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(va))); + const __m128 y = _mm_castsi128_ps(_mm_cvtsi32_si128(static_cast(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(_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(va))); + const __m128d y = _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast(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(_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 000000000..e84bfbbcc --- /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_(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 +#include +#include +#include +#if defined(_MSC_VER) +#include +#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(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(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(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(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 +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 0e67cda33..7f1d4b03b 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 @@ -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(static_cast(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(static_cast(s8(u))) + : static_cast(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(static_cast(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(static_cast(s8(u))) + : static_cast(u)); + } return out; } -static Vec256 op_vpmovsxbq(const Vec256& a) { - return {{static_cast(static_cast(s8(lane8(a, 0u)))), - static_cast(static_cast(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(static_cast(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(static_cast(s8(u))) + : static_cast(u); + } return out; } -static Vec256 op_vpmovsxwq(const Vec256& a) { - return {{static_cast(static_cast(s16(lane16(a, 0u)))), - static_cast(static_cast(s16(lane16(a, 1u)))), 0ull, 0ull}}; -} - -static Vec256 op_vpmovsxdq(const Vec256& a) { - return {{static_cast(static_cast(s32(lane32(a, 0u)))), - static_cast(static_cast(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(static_cast(s16(u))) + : static_cast(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(static_cast(s16(u))) + : static_cast(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(static_cast(s32(u))) + : static_cast(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 000000000..72dfa2199 --- /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_(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 +#include +#include +#if defined(_MSC_VER) +#include +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + T v{}; + std::memcpy(&v, reinterpret_cast(address), sizeof(T)); + const volatile T observed = v; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +template +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(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(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(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(cur); + if (c == 0u) return static_cast(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(r)); + return static_cast(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(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(src1_w); + const std::uint32_t s2 = static_cast(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(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(src1_w); + const unsigned start = static_cast(src2_w & 0xFFull); + const unsigned len = static_cast((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(d); +} + +static inline word op_bextr64(word s1, word s2, Flags& flags) { + const unsigned start = static_cast(s2 & 0xFFull); + const unsigned len = static_cast((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(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(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(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(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({addr}, static_cast(({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 000000000..b953edfad --- /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_(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 +#include +#include +#if defined(_MSC_VER) +#include +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + T v{}; + std::memcpy(&v, reinterpret_cast(address), sizeof(T)); + const volatile T observed = v; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +template +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(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(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(lhs_w); + const std::uint32_t b = static_cast(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(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(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(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(src_w); + const unsigned idx = static_cast(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(d); +} + +static inline word op_bzhi64(word s, word idx_w, Flags& flags) { + const unsigned idx = static_cast(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(static_cast(src1_w)) + * static_cast(static_cast(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(src1) * static_cast(src2); + lo = static_cast(prod); + hi = static_cast(prod >> 64); +#endif +} + +static inline word op_pdep32(word src_w, word mask_w) { + std::uint32_t s = static_cast(src_w); + std::uint32_t m = static_cast(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(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(src_w); + std::uint32_t m = static_cast(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(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(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(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({addr}, static_cast(({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_movbe_aot.py b/tools/cpu_movbe_aot.py new file mode 100644 index 000000000..d439ee29d --- /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_(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 +#include +#include +#if defined(_MSC_VER) +#include +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + T v{}; + std::memcpy(&v, reinterpret_cast(address), sizeof(T)); + const volatile T observed = v; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +template +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(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((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(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(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(cur); + if (c == 0u) return static_cast(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(r)); + return static_cast(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(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(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(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({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({addr}, static_cast(({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_sse41_fp_aot.py b/tools/cpu_sse41_fp_aot.py new file mode 100644 index 000000000..e5c1ca2d1 --- /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_(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 +#include +#include +#include +#if defined(_MSC_VER) +#include +#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(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(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(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(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(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(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(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(val) << shift); +} + +static inline std::uint32_t round_mode(std::uint8_t imm8) { + if ((imm8 & 4u) == 0u) { + return static_cast(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(val); + const double tf = static_cast(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(f), round_mode(imm8)); + if (n == 0) { + return sign_bit; + } + const float out_f = static_cast(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(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(vb))); +} + +static inline std::uint32_t bits_from_sse_ss(__m128 v) { + return static_cast(_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(vb))); +} + +static inline std::uint64_t bits_from_sse_sd(__m128d v) { + return static_cast(_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(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(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(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({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(static_cast({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_compile_time.py b/tools/dxc_compile_time.py index 9bf68e758..3d9011cfc 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 7a00cc1b2..000e16d99 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_version_query.py b/tools/ffx_version_query.py index e5cd253ed..713619abd 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 #include #include @@ -3086,15 +3091,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 6ed27189a..cf9184fc4 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 9ca34952d..206036022 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 +Usage: out/pe-env/Scripts/python.exe tools/form_reference.py [--out-dir 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 "groupform". """ +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 36823e02e..99a49f06a 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/gpu-check/README.md b/tools/gpu-check/README.md index 95286748f..8e4e26e44 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 03af93bee..914203981 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 732cba8cb..f52ff82d0 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/intake_exe.py b/tools/intake_exe.py index 6216ab76e..df99d3623 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 836c607bd..03def0a8f 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 7da3427ee..b382779b5 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 000000000..596c883c0 --- /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 42eef6353..53697514f 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 c80271e45..4d1ee1c26 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/pe_package_preflight.py b/tools/pe_package_preflight.py index 4af2e57a5..89c3dd462 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/pixel_aot.py b/tools/pixel_aot.py index 20d01a27e..bb30bdf3c 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" @@ -315,6 +316,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 +455,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 +537,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 +576,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 +768,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 +778,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 @@ -1237,14 +1252,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 +1477,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 = { @@ -3536,10 +3546,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 +3586,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 +3696,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 +5033,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 +5047,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 +5104,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(" 255 for reg in (dst, *address)): raise ValueError("Comparison sample VGPR out of range") @@ -5222,10 +5276,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 +5334,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 +5667,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});") @@ -7211,7 +7312,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})"): @@ -7864,6 +7965,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 +7985,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 +7997,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 +8042,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/rdna_cvt_pk_u8.py b/tools/rdna_cvt_pk_u8.py index d7dccdc75..09a533e23 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 000000000..5ff1c888b --- /dev/null +++ b/tools/record_gpu_cases.py @@ -0,0 +1,67 @@ +"""Record the compiled gfx2hlsl compute cases for the GPU check package. + + python -B tools/record_gpu_cases.py + +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 --compute-store-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 compiler expect mismatch + id gfx2hlsl_compute/ or gfx2hlsl_compute/control-; the files are .cso and .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 record(dxc, output, cases=None, controls=None): + """Write the cases and the manifest into `output`; return the manifest rows.""" + output = Path(output) + 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, dxc, 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 '')) + with open(output / 'manifest.tsv', 'w', newline='\n', encoding='ascii') as manifest: + for row in rows: + manifest.write('\t'.join(row) + '\n') + return rows + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('dxc') + parser.add_argument('output') + args = parser.parse_args() + rows = record(args.dxc, args.output) + 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__': + sys.exit(main()) diff --git a/tools/run_checks_parallel.py b/tools/run_checks_parallel.py index c6703aa63..45a71459d 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