From 87a6003fcc38661683f6936a614acfa90e420c83 Mon Sep 17 00:00:00 2001 From: denn0x <55638248+denn0x@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:11:10 +0000 Subject: [PATCH] Integrate Xbox2Windows shader translation and D3D12 rendering --- .github/workflows/windows.yml | 5 + AGENTS.md | 9 + CMakeLists.txt | 893 +- docs/experiments.md | 91 +- docs/startup-runtime.md | 48 +- src/era_heap.cpp | 5 +- src/era_query.cpp | 9 +- src/shader_db/archive_scan.cpp | 152 + src/shader_db/archive_scan.h | 28 + src/shader_db/gpu_export.cpp | 282 + src/shader_db/gpu_export.h | 31 + src/shader_db/shader_db.cpp | 257 + src/shader_db/shader_db.h | 108 + src/shader_db/shader_db_writer.cpp | 162 + src/shader_db/shader_db_writer.h | 41 + src/shader_db/x2w_shaders.cpp | 460 + src/shader_db/x2w_shaders_no_translator.cpp | 9 + src/shader_db/x2w_shaders_translate.h | 24 + src/shader_db/x2w_shaders_vs.cpp | 70 + src/startup_stubs/LICENSE-GPL-3.0.txt | 674 ++ src/startup_stubs/THIRD_PARTY_NOTICES.md | 13 + src/startup_stubs/bc_bind_trace.inl | 109 + src/startup_stubs/bcpack_bc6h.h | 318 + src/startup_stubs/bcpack_decoder.h | 28 + src/startup_stubs/blake3/LICENSE_A2 | 202 + src/startup_stubs/blake3/LICENSE_A2LLVM | 219 + src/startup_stubs/blake3/LICENSE_CC0 | 121 + src/startup_stubs/blake3/blake3.c | 651 ++ src/startup_stubs/blake3/blake3.h | 86 + src/startup_stubs/blake3/blake3_dispatch.c | 332 + src/startup_stubs/blake3/blake3_impl.h | 333 + src/startup_stubs/blake3/blake3_portable.c | 160 + src/startup_stubs/buffer_address_index.h | 76 + src/startup_stubs/chad.cpp | 29 +- src/startup_stubs/cull_input_capture.inl | 624 ++ src/startup_stubs/cx_input_dump.inl | 426 + src/startup_stubs/d3d12_capture.inl | 29 +- src/startup_stubs/d3d12_cold_texture.inl | 70 + src/startup_stubs/d3d12_compute.inl | 1662 ++++ .../d3d12_compute_binding_trace.inl | 2 +- src/startup_stubs/d3d12_copy_buffer.inl | 91 + src/startup_stubs/d3d12_draw.inl | 3233 ++++++- src/startup_stubs/d3d12_gpu_time.inl | 365 + src/startup_stubs/d3d12_heap_raw.inl | 896 ++ src/startup_stubs/d3d12_indirect.inl | 791 ++ src/startup_stubs/d3d12_mem_counters.h | 55 + src/startup_stubs/d3d12_mem_counters.inl | 271 + src/startup_stubs/d3d12_memcut_alias.inl | 48 + src/startup_stubs/d3d12_memcut_release.inl | 361 + src/startup_stubs/d3d12_memory_srv.inl | 963 ++- src/startup_stubs/d3d12_mesh.inl | 1272 +++ src/startup_stubs/d3d12_present.inl | 202 +- src/startup_stubs/d3d12_range_alias.inl | 125 + src/startup_stubs/d3d12_rawaddr.inl | 311 + src/startup_stubs/d3d12_record_trace.inl | 714 ++ src/startup_stubs/d3d12_regblob.inl | 520 ++ src/startup_stubs/d3d12_upload_ring.inl | 469 + src/startup_stubs/d3d12_vdesc.inl | 70 + src/startup_stubs/d3d12_xs_device.cpp | 3277 ++++++- src/startup_stubs/d3d12_xs_traps.cpp | 7 + src/startup_stubs/derived_blend.h | 19 +- src/startup_stubs/draw_bmp.h | 64 +- src/startup_stubs/draw_input_dump.inl | 693 ++ src/startup_stubs/dstorage_status_stats.h | 220 + src/startup_stubs/frame_rgb_report.inl | 50 + src/startup_stubs/frame_rgb_sample.h | 45 + src/startup_stubs/gfx10_layout_equations.inc | 62 + src/startup_stubs/gfx10_layout_local.h | 244 + src/startup_stubs/gfx10_raw_vdesc.h | 67 + src/startup_stubs/gfx10_view_words.h | 324 + src/startup_stubs/gpu_abi.h | 394 + src/startup_stubs/gpu_ambient.h | 154 + src/startup_stubs/gpu_ambient_kernels.h | 185 + src/startup_stubs/gpu_as_address.h | 22 + src/startup_stubs/gpu_bind.inl | 1768 ++++ src/startup_stubs/gpu_build_queue.h | 173 + src/startup_stubs/gpu_compute_trace.h | 208 + src/startup_stubs/gpu_compute_trace.inl | 462 + src/startup_stubs/gpu_db.cpp | 241 + src/startup_stubs/gpu_db.h | 22 + src/startup_stubs/gpu_depth_twins.h | 121 + src/startup_stubs/gpu_find.h | 78 + src/startup_stubs/gpu_heap.h | 502 ++ src/startup_stubs/gpu_heap.inl | 2132 +++++ src/startup_stubs/gpu_hooks.h | 163 + src/startup_stubs/gpu_hooks.inl | 542 ++ src/startup_stubs/gpu_indirect.inl | 434 + src/startup_stubs/gpu_indirect_capture.h | 65 + src/startup_stubs/gpu_indirect_clamp.h | 482 ++ src/startup_stubs/gpu_late_texture.h | 161 + src/startup_stubs/gpu_list_states.h | 84 + src/startup_stubs/gpu_material_fields.h | 62 + src/startup_stubs/gpu_material_trace.h | 116 + src/startup_stubs/gpu_memory.h | 328 + src/startup_stubs/gpu_memory_arena.h | 207 + src/startup_stubs/gpu_memory_store.inl | 251 + src/startup_stubs/gpu_packed_light.h | 136 + src/startup_stubs/gpu_pipeline.inl | 783 ++ src/startup_stubs/gpu_pipeline_build.h | 570 ++ src/startup_stubs/gpu_pipeline_pending.h | 150 + src/startup_stubs/gpu_pipeline_record.h | 29 + src/startup_stubs/gpu_pipeline_state.h | 467 + src/startup_stubs/gpu_read_states.h | 17 + src/startup_stubs/gpu_rect.cpp | 19 + src/startup_stubs/gpu_rect.h | 10 + src/startup_stubs/gpu_reference_library.h | 95 + src/startup_stubs/gpu_resident_mips.h | 114 + src/startup_stubs/gpu_roots.h | 545 ++ src/startup_stubs/gpu_srgb.h | 83 + src/startup_stubs/gpu_table_constants.h | 60 + src/startup_stubs/gpu_trace_request.h | 93 + src/startup_stubs/gpu_transition.h | 18 + src/startup_stubs/gpu_view_trace.h | 98 + src/startup_stubs/gpu_views.inl | 747 ++ src/startup_stubs/gpu_warm_bad.h | 58 + src/startup_stubs/heap_raw_prelude.hlsli | 120 + src/startup_stubs/list_copy.inl | 7 + src/startup_stubs/list_copy_texture.h | 4 +- src/startup_stubs/list_copy_texture.inl | 277 +- src/startup_stubs/local_log.h | 182 +- src/startup_stubs/log_cap.h | 33 + src/startup_stubs/mesh_xmem_handoff.inl | 8 +- src/startup_stubs/overlay_window.h | 13 + src/startup_stubs/pipeline_state_decode.h | 316 +- src/startup_stubs/placed_buffer_range.h | 15 + src/startup_stubs/placed_pool.h | 98 + src/startup_stubs/rawaddr_table.h | 167 + src/startup_stubs/red_producer_diagnostic.inl | 109 +- src/startup_stubs/resource_address_index.h | 9 + src/startup_stubs/runtime_proxy.cpp | 128 +- src/startup_stubs/slice_footprints.h | 2 + src/startup_stubs/small_texture_heap.h | 83 + src/startup_stubs/state_block_blend.h | 59 +- src/startup_stubs/title_composition.h | 48 + src/startup_stubs/title_heap_memory.h | 9 +- src/startup_stubs/title_texture_readback.inl | 114 + .../translated_sampler_bindings.h | 78 +- src/startup_stubs/trap.h | 40 + src/startup_stubs/xapu.cpp | 12 +- src/startup_stubs/xcrdapi.cpp | 536 +- src/x2w_shader/bvh.cpp | 265 + src/x2w_shader/bvh.h | 125 + src/x2w_shader/dxbc.cpp | 110 + src/x2w_shader/dxbc.h | 93 + src/x2w_shader/dxil.cpp | 93 + src/x2w_shader/dxil.h | 80 + src/x2w_shader/emit/CMakeLists.txt | 80 + src/x2w_shader/emit/bitcode.cpp | 876 ++ src/x2w_shader/emit/bitcode.h | 452 + src/x2w_shader/emit/census.cpp | 174 + src/x2w_shader/emit/census.h | 45 + src/x2w_shader/emit/cmake/dxil.cmake | 17 + src/x2w_shader/emit/cmake/host.cmake | 21 + src/x2w_shader/emit/cmake/lower.cmake | 30 + src/x2w_shader/emit/cmake/opt.cmake | 6 + src/x2w_shader/emit/cmake/wave.cmake | 50 + src/x2w_shader/emit/cmake/x_translate.cmake | 23 + src/x2w_shader/emit/cmake/y_tool.cmake | 34 + src/x2w_shader/emit/cmake/z_difftests.cmake | 12 + src/x2w_shader/emit/cmake/z_modtests.cmake | 15 + src/x2w_shader/emit/container.cpp | 392 + src/x2w_shader/emit/container.h | 110 + src/x2w_shader/emit/emit.h | 118 + src/x2w_shader/emit/fingerprint.cmake | 29 + src/x2w_shader/emit/host.cpp | 1006 +++ src/x2w_shader/emit/host.h | 256 + src/x2w_shader/emit/lower.h | 163 + src/x2w_shader/emit/lower_buffer_exit.cpp | 1158 +++ src/x2w_shader/emit/lower_core.cpp | 1026 +++ src/x2w_shader/emit/lower_desc.cpp | 769 ++ src/x2w_shader/emit/lower_ds_sop.cpp | 1353 +++ src/x2w_shader/emit/lower_free.cpp | 1269 +++ src/x2w_shader/emit/lower_image.cpp | 811 ++ src/x2w_shader/emit/lower_impl.h | 585 ++ src/x2w_shader/emit/lower_input_mem.cpp | 1174 +++ src/x2w_shader/emit/lower_int_cmp_interp.cpp | 997 +++ src/x2w_shader/emit/lower_intersect.cpp | 601 ++ src/x2w_shader/emit/lower_ops_lanes.cpp | 1316 +++ src/x2w_shader/emit/lower_smem.cpp | 866 ++ src/x2w_shader/emit/lower_valu.cpp | 1230 +++ src/x2w_shader/emit/lower_valu16.cpp | 876 ++ src/x2w_shader/emit/mod.cpp | 484 ++ src/x2w_shader/emit/mod_signature.cpp | 136 + src/x2w_shader/emit/opt.cpp | 1276 +++ src/x2w_shader/emit/opt.h | 73 + src/x2w_shader/emit/own_bits.cpp | 811 ++ src/x2w_shader/emit/own_bits.h | 27 + src/x2w_shader/emit/rect.cpp | 250 + src/x2w_shader/emit/rect.h | 26 + src/x2w_shader/emit/sampler.cpp | 59 + src/x2w_shader/emit/sampler.h | 40 + src/x2w_shader/emit/settings.cpp | 131 + src/x2w_shader/emit/settings.h | 55 + src/x2w_shader/emit/shader.cpp | 579 ++ src/x2w_shader/emit/shader.h | 209 + src/x2w_shader/emit/signature.h | 22 + src/x2w_shader/emit/threading.cpp | 174 + src/x2w_shader/emit/threading.h | 24 + src/x2w_shader/emit/validator.cpp | 141 + src/x2w_shader/emit/validator.h | 47 + src/x2w_shader/emit/wave.cpp | 715 ++ src/x2w_shader/emit/wave.h | 174 + src/x2w_shader/error.h | 65 + src/x2w_shader/front/CMakeLists.txt | 76 + src/x2w_shader/front_hash.h | 38 + src/x2w_shader/gfx10/fields.cpp | 576 ++ src/x2w_shader/gfx10/fields.h | 263 + src/x2w_shader/gfx10/mod.cpp | 283 + src/x2w_shader/gfx10/mod.h | 118 + src/x2w_shader/gfx10/opcodes.cpp | 1344 +++ src/x2w_shader/gfx10/opcodes.h | 39 + src/x2w_shader/gfx10/sp3.cpp | 567 ++ src/x2w_shader/gfx10/sp3.h | 13 + src/x2w_shader/io.cpp | 431 + src/x2w_shader/io.h | 215 + src/x2w_shader/ir.cpp | 1476 ++++ src/x2w_shader/ir.h | 224 + src/x2w_shader/lib.cpp | 99 + src/x2w_shader/lib.h | 38 + src/x2w_shader/native.cpp | 519 ++ src/x2w_shader/native.h | 324 + src/x2w_shader/resource.cpp | 2164 +++++ src/x2w_shader/resource.h | 220 + src/x2w_shader/spill.cpp | 267 + src/x2w_shader/spill.h | 49 + src/x2w_shader/structure.cpp | 1201 +++ src/x2w_shader/structure.h | 248 + src/xmem_census.cpp | 491 ++ src/xmem_census.h | 26 + src/xmem_gpu_pool.cpp | 78 + src/xmem_gpu_pool.h | 11 + src/xmem_low.h | 48 + src/xmem_mapped_pages.cpp | 1008 ++- src/xmem_shim.cpp | 3 +- src/xmem_shim.def | 22 +- tests/bcpack_bc6h_test.cpp | 127 + tests/bcpack_bc6h_vectors.inl | 193 + tests/bcpack_bcn_check.py | 267 + tests/bcpack_bcn_decode_test.cpp | 94 + tests/buffer_address_index_check.cpp | 117 + tests/desktop_gpu.h | 2 +- tests/gfx10_layout_check.cpp | 659 ++ tests/gfx10_layout_golden.txt | 40 + tests/gpu_bind.cmake | 36 + tests/gpu_heap_tests.cmake | 69 + tests/mesh_clip_distance_check.py | 112 + tests/mesh_loop_state_check.py | 168 + tests/mesh_pc_table_check.py | 41 + tests/mesh_perlane_loop_check.py | 109 + tests/mesh_waterfall_check.py | 177 + tests/offscreen_check.cpp | 6 +- tests/section_window_ops_check.cpp | 295 + tests/shader_db_check.cpp | 233 + tests/startup_address_srv.cpp | 112 + tests/startup_bc_writer_srv.inl | 98 + tests/startup_bfm_absdiff_check.py | 60 + tests/startup_buffer_address_check.py | 11 +- tests/startup_buffer_heap_index_check.py | 100 + tests/startup_buffer_store_check.py | 136 + tests/startup_carry_dst_check.py | 38 + tests/startup_class_f16_sdwa_check.py | 95 + tests/startup_class_sdwa_check.py | 81 + tests/startup_clear_depth_stencil.cpp | 41 +- tests/startup_clip_distance_check.py | 58 + tests/startup_counted_search_check.py | 36 + tests/startup_cselect_vcc_lo_check.py | 52 + tests/startup_cx_async.cpp | 850 ++ tests/startup_cx_async.hlsl | 29 + tests/startup_cx_heap_raw.hlsl | 56 + tests/startup_cx_heap_words.hlsl | 23 + tests/startup_cx_pso_time.cpp | 88 + tests/startup_detile_draw.ps1 | 40 + tests/startup_draw_async_check.py | 90 + tests/startup_draw_bmp.cpp | 45 + tests/startup_draw_dump_inputs_check.py | 164 + tests/startup_draw_fma_check.py | 110 + tests/startup_draw_heap_check.py | 83 + tests/startup_draw_heapwords_check.py | 142 + tests/startup_draw_lock_split_check.py | 151 + tests/startup_draw_lock_times.cpp | 87 + tests/startup_draw_srv_limit_check.py | 63 + tests/startup_draw_state.cpp | 296 + tests/startup_draw_state_check.py | 112 + tests/startup_draw_uav.cpp | 335 + tests/startup_draw_uav_check.py | 393 + tests/startup_dstorage_destination_check.cpp | 19 +- tests/startup_dstorage_status_stats_check.cpp | 98 + tests/startup_execz_join_check.py | 65 + tests/startup_fma_exact_fxc_check.py | 226 + tests/startup_fmt_load_table_check.py | 169 + tests/startup_format_load_check.py | 111 + tests/startup_format_store_check.py | 105 + tests/startup_frame_copy.cpp | 125 +- tests/startup_frame_copy_check.py | 101 +- tests/startup_frame_rgb_sample.cpp | 70 + tests/startup_front_face_check.py | 126 + tests/startup_gfx10_view_words_check.cpp | 233 + tests/startup_gfx2hlsl_bit_alu_check.py | 22 + tests/startup_gfx2hlsl_coverage_check.py | 687 ++ tests/startup_gfx2hlsl_draw_descnum_check.py | 126 + tests/startup_gfx2hlsl_draw_descword_check.py | 114 + .../startup_gfx2hlsl_exec_lane_facts_check.py | 162 + tests/startup_gfx2hlsl_f16_arith_check.py | 735 ++ tests/startup_gfx2hlsl_f32_lg_local_check.py | 747 ++ tests/startup_gfx2hlsl_ldexp_check.py | 136 + tests/startup_gfx2hlsl_mix_fma_check.py | 115 + .../startup_gfx2hlsl_mul_hi_mad_half_check.py | 62 + tests/startup_gfx2hlsl_root_local_check.py | 85 + ...tartup_gfx2hlsl_scalar_named_dest_check.py | 31 + tests/startup_gfx2hlsl_scc_carry_check.py | 172 + .../startup_gfx2hlsl_shift64_literal_check.py | 57 + tests/startup_gfx2hlsl_wave_union_check.py | 357 + tests/startup_gpu_abi_heap_start_check.cpp | 131 + tests/startup_gpu_abi_off_check.cpp | 228 + tests/startup_gpu_ambient.inl | 106 + tests/startup_gpu_bind.hlsl | 35 + tests/startup_gpu_bind_check.cpp | 440 + tests/startup_gpu_build_queue.cpp | 84 + tests/startup_gpu_compute_trace.inl | 430 + tests/startup_gpu_db_check.cpp | 83 + tests/startup_gpu_depth_twins.cpp | 128 + tests/startup_gpu_heap.cpp | 1181 +++ tests/startup_gpu_heap.hlsl | 53 + tests/startup_gpu_heap_fit_check.cpp | 334 + tests/startup_gpu_heap_layout_check.cpp | 377 + tests/startup_gpu_heap_shim.cpp | 188 + tests/startup_gpu_indirect.cpp | 845 ++ tests/startup_gpu_indirect.hlsl | 24 + tests/startup_gpu_list_states.inl | 61 + tests/startup_gpu_memory.hlsl | 17 + tests/startup_gpu_memory_store.hlsl | 24 + tests/startup_gpu_memory_store.inl | 131 + tests/startup_gpu_pipeline.cpp | 728 ++ tests/startup_gpu_pipeline.hlsl | 66 + tests/startup_gpu_pipeline_state_check.cpp | 312 + tests/startup_gpu_reference_library.cpp | 69 + tests/startup_gpu_resident_mips.inl | 206 + tests/startup_gpu_roots_check.cpp | 141 + tests/startup_gpu_small_texture_heap.inl | 86 + tests/startup_gpu_trace_request.cpp | 30 + tests/startup_gpu_user_data_check.cpp | 270 + tests/startup_gpu_warm_bad.cpp | 62 + tests/startup_heap_texture_check.py | 91 + tests/startup_image_3d_check.py | 9 +- tests/startup_image_d16_check.py | 87 + tests/startup_image_get_lod_check.py | 116 + tests/startup_image_invariant_check.py | 99 + tests/startup_image_sample_b_local_check.py | 82 + tests/startup_image_sample_d_check.py | 78 + ...startup_image_sample_implicit_lod_check.py | 69 + tests/startup_image_sample_l_check.py | 9 +- tests/startup_indirect_dispatch.hlsl | 19 + tests/startup_indirect_dispatch_local.cpp | 353 + tests/startup_int_three_operand_check.py | 68 + tests/startup_interp_f16_check.py | 193 + tests/startup_lane_invariant_check.py | 165 + tests/startup_list_copy_texture_warp.cpp | 174 + tests/startup_lit64_check.py | 47 + tests/startup_literal_halves_check.py | 67 + tests/startup_local_log_check.cpp | 28 +- tests/startup_log_cap_check.cpp | 71 + tests/startup_loop_carried_check.py | 117 + tests/startup_loop_regions_check.py | 184 + tests/startup_memory_srv_announced_check.py | 111 + tests/startup_memory_srv_detile.ps1 | 118 + tests/startup_mesh_barrier_ranges_check.py | 105 + tests/startup_mesh_desc_numeric_check.py | 20 + tests/startup_mesh_descword_check.py | 106 + tests/startup_mesh_dispatch.cpp | 1401 +++ tests/startup_mesh_dispatch.hlsl | 127 + tests/startup_mesh_exec_lineage_check.py | 111 + tests/startup_mesh_exec_off_check.py | 292 + tests/startup_mesh_exec_restore_check.py | 282 + tests/startup_mesh_exec_walk_check.py | 126 + tests/startup_mesh_first_lane_check.py | 98 + tests/startup_mesh_heap_copy_check.py | 26 + tests/startup_mesh_heap_sampler_check.py | 187 + tests/startup_mesh_lane_scc_check.py | 434 + tests/startup_mesh_literal_flow_check.py | 99 + tests/startup_mesh_loop_tail_check.py | 40 + tests/startup_mesh_output_budget_check.py | 24 + tests/startup_mesh_padded_barriers_check.py | 52 + tests/startup_mesh_restored_scalar_check.py | 104 + tests/startup_mesh_rtv_variant_check.py | 188 + tests/startup_mesh_salu_check.py | 145 + tests/startup_mesh_spi_input_check.py | 116 + tests/startup_mesh_spill_check.py | 167 + tests/startup_mesh_vcc_data_check.py | 169 + tests/startup_mesh_vcc_vote_check.py | 30 + tests/startup_mrt_wide_int_check.py | 59 + tests/startup_pack_f16_check.py | 87 + tests/startup_packed_position_check.py | 10 +- tests/startup_pipeline_state_local_check.cpp | 351 + tests/startup_placed_buffer_range_check.cpp | 9 + tests/startup_placed_fast.cpp | 128 + tests/startup_present_producer.cpp | 22 + tests/startup_present_producer_check.py | 6 + tests/startup_probe_cache.cpp | 184 + tests/startup_profile_check.py | 76 + tests/startup_profile_probe.cpp | 73 + tests/startup_quad_divergent_check.py | 86 + tests/startup_quad_dpp_check.py | 178 + tests/startup_quad_uniform_check.py | 105 + tests/startup_readfirstlane_chain_check.py | 145 + tests/startup_readfirstlane_exec_check.py | 124 + .../startup_resource_address_index_check.cpp | 10 +- tests/startup_resource_retire_title.cpp | 99 +- tests/startup_rgba8_dmode.ps1 | 61 + tests/startup_root_cbv.cpp | 2 + tests/startup_root_srv_lazy_check.py | 46 + tests/startup_round_mode_check.py | 395 + tests/startup_rtv_bind_local.cpp | 247 + tests/startup_run_ps1_check.py | 4 +- tests/startup_sample_c_border_check.py | 80 + tests/startup_sample_c_preclamp_check.py | 66 + tests/startup_sampler_comparison_check.cpp | 25 + tests/startup_sampler_x.cpp | 20 +- tests/startup_saveexec_same_reg_check.py | 67 + tests/startup_scalar_bits_check.py | 155 + tests/startup_scalar_complement_mask_check.py | 90 + tests/startup_scalar_const_fold_check.py | 73 + tests/startup_scalar_ff_check.py | 44 + tests/startup_scalar_nand_check.py | 70 + tests/startup_scalar_pack_hh_check.py | 110 + tests/startup_scmp_u64_check.py | 115 + tests/startup_sdwa_cvt_check.py | 68 + tests/startup_sdwa_mov_check.py | 122 + tests/startup_shader_trace_misses_check.py | 43 + tests/startup_smem_overlap_mask_check.py | 85 + tests/startup_sopk_sign_check.py | 39 + tests/startup_spi_input_check.py | 96 + tests/startup_stream_check.py | 20 +- tests/startup_stream_consumer.cpp | 72 +- tests/startup_stream_draw.cpp | 41 +- tests/startup_stream_interface_check.py | 65 +- tests/startup_stream_pc_table_check.py | 241 + tests/startup_stream_ps_inputs_check.py | 138 + tests/startup_stream_setup.cpp | 2 +- tests/startup_stream_vertex_exit_check.py | 100 + tests/startup_tbuffer_uint_snorm_check.py | 136 + tests/startup_translator_check.py | 2 +- tests/startup_vopc_dpp_check.py | 65 + tests/startup_vs_heap_check.py | 91 + tests/startup_vs_instance_id_check.py | 62 + tests/startup_vsregs_state_check.py | 87 + tests/startup_vswap_check.py | 99 + tests/startup_waterfall_check.py | 304 + tests/tile_mapping_shared_heap_check.cpp | 205 + tests/x2w_shader/archive_decode_check.cpp | 355 + tests/x2w_shader/core_tests.cpp | 811 ++ tests/x2w_shader/emit/atomic_test.cpp | 122 + tests/x2w_shader/emit/barycentric_test.cpp | 594 ++ tests/x2w_shader/emit/bitcode_test.cpp | 218 + tests/x2w_shader/emit/container_test.cpp | 156 + tests/x2w_shader/emit/diff_test.cpp | 1238 +++ tests/x2w_shader/emit/host_test.cpp | 272 + tests/x2w_shader/emit/intersect_test.cpp | 722 ++ tests/x2w_shader/emit/lower_card_util.h | 423 + tests/x2w_shader/emit/lower_cube_lod_test.cpp | 125 + tests/x2w_shader/emit/lower_permlane_test.cpp | 189 + tests/x2w_shader/emit/lower_probe_test.cpp | 103 + tests/x2w_shader/emit/lower_size_test.cpp | 356 + tests/x2w_shader/emit/lower_test.cpp | 685 ++ tests/x2w_shader/emit/lower_valu_test.cpp | 1952 +++++ .../x2w_shader/emit/lower_waterfall_test.cpp | 261 + tests/x2w_shader/emit/lower_wave64_test.cpp | 640 ++ tests/x2w_shader/emit/mod_test.cpp | 1266 +++ tests/x2w_shader/emit/opt_test.cpp | 1148 +++ tests/x2w_shader/emit/own_bits_test.cpp | 167 + tests/x2w_shader/emit/rect_test.cpp | 238 + tests/x2w_shader/emit/ref/README.txt | 28 + tests/x2w_shader/emit/ref/out/build.bin | Bin 0 -> 108 bytes tests/x2w_shader/emit/ref/out/cs_basic.bin | Bin 0 -> 2812 bytes tests/x2w_shader/emit/ref/out/hashes.bin | Bin 0 -> 3216 bytes tests/x2w_shader/emit/ref/out/ps_basic.bin | Bin 0 -> 3222 bytes tests/x2w_shader/emit/ref/out/psv_cs.bin | Bin 0 -> 120 bytes tests/x2w_shader/emit/ref/out/psv_gs.bin | Bin 0 -> 216 bytes tests/x2w_shader/emit/ref/out/psv_ms.bin | Bin 0 -> 184 bytes tests/x2w_shader/emit/ref/out/psv_ps.bin | Bin 0 -> 400 bytes tests/x2w_shader/emit/ref/out/rect_plain.bin | Bin 0 -> 4928 bytes tests/x2w_shader/emit/ref/out/rect_prim.bin | Bin 0 -> 5255 bytes tests/x2w_shader/emit/ref/out/sig_in.bin | Bin 0 -> 266 bytes tests/x2w_shader/emit/ref/out/sig_out.bin | Bin 0 -> 123 bytes tests/x2w_shader/emit/ref/out_opt0/build.bin | Bin 0 -> 108 bytes .../x2w_shader/emit/ref/out_opt0/cs_basic.bin | Bin 0 -> 2836 bytes tests/x2w_shader/emit/ref/out_opt0/hashes.bin | Bin 0 -> 3216 bytes .../x2w_shader/emit/ref/out_opt0/ps_basic.bin | Bin 0 -> 3214 bytes tests/x2w_shader/emit/ref/out_opt0/psv_cs.bin | Bin 0 -> 120 bytes tests/x2w_shader/emit/ref/out_opt0/psv_gs.bin | Bin 0 -> 216 bytes tests/x2w_shader/emit/ref/out_opt0/psv_ms.bin | Bin 0 -> 184 bytes tests/x2w_shader/emit/ref/out_opt0/psv_ps.bin | Bin 0 -> 400 bytes .../emit/ref/out_opt0/rect_plain.bin | Bin 0 -> 4960 bytes .../emit/ref/out_opt0/rect_prim.bin | Bin 0 -> 5287 bytes tests/x2w_shader/emit/ref/out_opt0/sig_in.bin | Bin 0 -> 266 bytes .../x2w_shader/emit/ref/out_opt0/sig_out.bin | Bin 0 -> 123 bytes tests/x2w_shader/emit/ref/ref_dump.rs | 254 + tests/x2w_shader/emit/ref_test.cpp | 272 + tests/x2w_shader/emit/ref_validate_test.cpp | 43 + tests/x2w_shader/emit/sampler_test.cpp | 87 + tests/x2w_shader/emit/test_util.h | 48 + tests/x2w_shader/emit/threading_test.cpp | 79 + tests/x2w_shader/emit/validator_test.cpp | 148 + tests/x2w_shader/emit/wave_test.cpp | 399 + tests/x2w_shader/resource_fixtures.h | 570 ++ tests/x2w_shader/vs_bvh_test.cpp | 295 + tests/x2w_shader/vs_front_test.h | 91 + tests/x2w_shader/vs_io_test.cpp | 254 + tests/x2w_shader/vs_native_test.cpp | 450 + tests/x2w_shader/vs_resource_test.cpp | 1066 +++ tests/x2w_shader/vs_spill_test.cpp | 98 + tests/x2w_shader/vs_structure_test.cpp | 454 + tests/x2w_tool/blake3_test.cpp | 99 + tests/x2w_tool/scan_test.cpp | 353 + tests/x2w_tool/sgd5_test.cpp | 217 + tests/xmem_linear_placement.cpp | 180 + tests/xmem_scatter_refusal_check.py | 296 + tools/bcpack_bcn.py | 235 + tools/disasm_rdna2.py | 51 +- tools/pixel_aot.py | 10 +- tools/shader_material_fields.mjs | 65 + tools/startup/compute_harness.cpp | 401 + tools/startup/debug_launch.py | 789 +- tools/startup/gfx2hlsl.py | 7691 +++++++++++------ tools/startup/gpu_slab_pool.py | 140 + tools/startup/mesh2hlsl.py | 4018 +++++++++ tools/startup/mesh_harness.cpp | 560 ++ tools/startup/run.ps1 | 30 +- tools/startup/sample_profile.py | 429 + tools/startup/shader_cache_rekey.py | 5 + tools/startup/shader_trace_misses.cpp | 64 + tools/startup/window_status.py | 96 + tools/x2w/blake3.cpp | 176 + tools/x2w/blake3.h | 45 + tools/x2w/main.cpp | 39 + tools/x2w/scan.cpp | 424 + tools/x2w/scan.h | 141 + tools/x2w/sgd5.cpp | 115 + tools/x2w/sgd5.h | 46 + tools/x2w/shaders_dump.cpp | 497 ++ tools/x2w/shaders_dump.h | 81 + 540 files changed, 138920 insertions(+), 3501 deletions(-) create mode 100644 src/shader_db/archive_scan.cpp create mode 100644 src/shader_db/archive_scan.h create mode 100644 src/shader_db/gpu_export.cpp create mode 100644 src/shader_db/gpu_export.h create mode 100644 src/shader_db/shader_db.cpp create mode 100644 src/shader_db/shader_db.h create mode 100644 src/shader_db/shader_db_writer.cpp create mode 100644 src/shader_db/shader_db_writer.h create mode 100644 src/shader_db/x2w_shaders.cpp create mode 100644 src/shader_db/x2w_shaders_no_translator.cpp create mode 100644 src/shader_db/x2w_shaders_translate.h create mode 100644 src/shader_db/x2w_shaders_vs.cpp create mode 100644 src/startup_stubs/LICENSE-GPL-3.0.txt create mode 100644 src/startup_stubs/bc_bind_trace.inl create mode 100644 src/startup_stubs/bcpack_bc6h.h create mode 100644 src/startup_stubs/blake3/LICENSE_A2 create mode 100644 src/startup_stubs/blake3/LICENSE_A2LLVM create mode 100644 src/startup_stubs/blake3/LICENSE_CC0 create mode 100644 src/startup_stubs/blake3/blake3.c create mode 100644 src/startup_stubs/blake3/blake3.h create mode 100644 src/startup_stubs/blake3/blake3_dispatch.c create mode 100644 src/startup_stubs/blake3/blake3_impl.h create mode 100644 src/startup_stubs/blake3/blake3_portable.c create mode 100644 src/startup_stubs/buffer_address_index.h create mode 100644 src/startup_stubs/cull_input_capture.inl create mode 100644 src/startup_stubs/cx_input_dump.inl create mode 100644 src/startup_stubs/d3d12_cold_texture.inl create mode 100644 src/startup_stubs/d3d12_compute.inl create mode 100644 src/startup_stubs/d3d12_copy_buffer.inl create mode 100644 src/startup_stubs/d3d12_gpu_time.inl create mode 100644 src/startup_stubs/d3d12_heap_raw.inl create mode 100644 src/startup_stubs/d3d12_indirect.inl create mode 100644 src/startup_stubs/d3d12_mem_counters.h create mode 100644 src/startup_stubs/d3d12_mem_counters.inl create mode 100644 src/startup_stubs/d3d12_memcut_alias.inl create mode 100644 src/startup_stubs/d3d12_memcut_release.inl create mode 100644 src/startup_stubs/d3d12_mesh.inl create mode 100644 src/startup_stubs/d3d12_range_alias.inl create mode 100644 src/startup_stubs/d3d12_rawaddr.inl create mode 100644 src/startup_stubs/d3d12_record_trace.inl create mode 100644 src/startup_stubs/d3d12_regblob.inl create mode 100644 src/startup_stubs/d3d12_upload_ring.inl create mode 100644 src/startup_stubs/d3d12_vdesc.inl create mode 100644 src/startup_stubs/d3d12_xs_traps.cpp create mode 100644 src/startup_stubs/draw_input_dump.inl create mode 100644 src/startup_stubs/dstorage_status_stats.h create mode 100644 src/startup_stubs/frame_rgb_report.inl create mode 100644 src/startup_stubs/frame_rgb_sample.h create mode 100644 src/startup_stubs/gfx10_layout_equations.inc create mode 100644 src/startup_stubs/gfx10_layout_local.h create mode 100644 src/startup_stubs/gfx10_raw_vdesc.h create mode 100644 src/startup_stubs/gfx10_view_words.h create mode 100644 src/startup_stubs/gpu_abi.h create mode 100644 src/startup_stubs/gpu_ambient.h create mode 100644 src/startup_stubs/gpu_ambient_kernels.h create mode 100644 src/startup_stubs/gpu_as_address.h create mode 100644 src/startup_stubs/gpu_bind.inl create mode 100644 src/startup_stubs/gpu_build_queue.h create mode 100644 src/startup_stubs/gpu_compute_trace.h create mode 100644 src/startup_stubs/gpu_compute_trace.inl create mode 100644 src/startup_stubs/gpu_db.cpp create mode 100644 src/startup_stubs/gpu_db.h create mode 100644 src/startup_stubs/gpu_depth_twins.h create mode 100644 src/startup_stubs/gpu_find.h create mode 100644 src/startup_stubs/gpu_heap.h create mode 100644 src/startup_stubs/gpu_heap.inl create mode 100644 src/startup_stubs/gpu_hooks.h create mode 100644 src/startup_stubs/gpu_hooks.inl create mode 100644 src/startup_stubs/gpu_indirect.inl create mode 100644 src/startup_stubs/gpu_indirect_capture.h create mode 100644 src/startup_stubs/gpu_indirect_clamp.h create mode 100644 src/startup_stubs/gpu_late_texture.h create mode 100644 src/startup_stubs/gpu_list_states.h create mode 100644 src/startup_stubs/gpu_material_fields.h create mode 100644 src/startup_stubs/gpu_material_trace.h create mode 100644 src/startup_stubs/gpu_memory.h create mode 100644 src/startup_stubs/gpu_memory_arena.h create mode 100644 src/startup_stubs/gpu_memory_store.inl create mode 100644 src/startup_stubs/gpu_packed_light.h create mode 100644 src/startup_stubs/gpu_pipeline.inl create mode 100644 src/startup_stubs/gpu_pipeline_build.h create mode 100644 src/startup_stubs/gpu_pipeline_pending.h create mode 100644 src/startup_stubs/gpu_pipeline_record.h create mode 100644 src/startup_stubs/gpu_pipeline_state.h create mode 100644 src/startup_stubs/gpu_read_states.h create mode 100644 src/startup_stubs/gpu_rect.cpp create mode 100644 src/startup_stubs/gpu_rect.h create mode 100644 src/startup_stubs/gpu_reference_library.h create mode 100644 src/startup_stubs/gpu_resident_mips.h create mode 100644 src/startup_stubs/gpu_roots.h create mode 100644 src/startup_stubs/gpu_srgb.h create mode 100644 src/startup_stubs/gpu_table_constants.h create mode 100644 src/startup_stubs/gpu_trace_request.h create mode 100644 src/startup_stubs/gpu_transition.h create mode 100644 src/startup_stubs/gpu_view_trace.h create mode 100644 src/startup_stubs/gpu_views.inl create mode 100644 src/startup_stubs/gpu_warm_bad.h create mode 100644 src/startup_stubs/heap_raw_prelude.hlsli create mode 100644 src/startup_stubs/log_cap.h create mode 100644 src/startup_stubs/placed_pool.h create mode 100644 src/startup_stubs/rawaddr_table.h create mode 100644 src/startup_stubs/small_texture_heap.h create mode 100644 src/startup_stubs/title_composition.h create mode 100644 src/startup_stubs/title_texture_readback.inl create mode 100644 src/x2w_shader/bvh.cpp create mode 100644 src/x2w_shader/bvh.h create mode 100644 src/x2w_shader/dxbc.cpp create mode 100644 src/x2w_shader/dxbc.h create mode 100644 src/x2w_shader/dxil.cpp create mode 100644 src/x2w_shader/dxil.h create mode 100644 src/x2w_shader/emit/CMakeLists.txt create mode 100644 src/x2w_shader/emit/bitcode.cpp create mode 100644 src/x2w_shader/emit/bitcode.h create mode 100644 src/x2w_shader/emit/census.cpp create mode 100644 src/x2w_shader/emit/census.h create mode 100644 src/x2w_shader/emit/cmake/dxil.cmake create mode 100644 src/x2w_shader/emit/cmake/host.cmake create mode 100644 src/x2w_shader/emit/cmake/lower.cmake create mode 100644 src/x2w_shader/emit/cmake/opt.cmake create mode 100644 src/x2w_shader/emit/cmake/wave.cmake create mode 100644 src/x2w_shader/emit/cmake/x_translate.cmake create mode 100644 src/x2w_shader/emit/cmake/y_tool.cmake create mode 100644 src/x2w_shader/emit/cmake/z_difftests.cmake create mode 100644 src/x2w_shader/emit/cmake/z_modtests.cmake create mode 100644 src/x2w_shader/emit/container.cpp create mode 100644 src/x2w_shader/emit/container.h create mode 100644 src/x2w_shader/emit/emit.h create mode 100644 src/x2w_shader/emit/fingerprint.cmake create mode 100644 src/x2w_shader/emit/host.cpp create mode 100644 src/x2w_shader/emit/host.h create mode 100644 src/x2w_shader/emit/lower.h create mode 100644 src/x2w_shader/emit/lower_buffer_exit.cpp create mode 100644 src/x2w_shader/emit/lower_core.cpp create mode 100644 src/x2w_shader/emit/lower_desc.cpp create mode 100644 src/x2w_shader/emit/lower_ds_sop.cpp create mode 100644 src/x2w_shader/emit/lower_free.cpp create mode 100644 src/x2w_shader/emit/lower_image.cpp create mode 100644 src/x2w_shader/emit/lower_impl.h create mode 100644 src/x2w_shader/emit/lower_input_mem.cpp create mode 100644 src/x2w_shader/emit/lower_int_cmp_interp.cpp create mode 100644 src/x2w_shader/emit/lower_intersect.cpp create mode 100644 src/x2w_shader/emit/lower_ops_lanes.cpp create mode 100644 src/x2w_shader/emit/lower_smem.cpp create mode 100644 src/x2w_shader/emit/lower_valu.cpp create mode 100644 src/x2w_shader/emit/lower_valu16.cpp create mode 100644 src/x2w_shader/emit/mod.cpp create mode 100644 src/x2w_shader/emit/mod_signature.cpp create mode 100644 src/x2w_shader/emit/opt.cpp create mode 100644 src/x2w_shader/emit/opt.h create mode 100644 src/x2w_shader/emit/own_bits.cpp create mode 100644 src/x2w_shader/emit/own_bits.h create mode 100644 src/x2w_shader/emit/rect.cpp create mode 100644 src/x2w_shader/emit/rect.h create mode 100644 src/x2w_shader/emit/sampler.cpp create mode 100644 src/x2w_shader/emit/sampler.h create mode 100644 src/x2w_shader/emit/settings.cpp create mode 100644 src/x2w_shader/emit/settings.h create mode 100644 src/x2w_shader/emit/shader.cpp create mode 100644 src/x2w_shader/emit/shader.h create mode 100644 src/x2w_shader/emit/signature.h create mode 100644 src/x2w_shader/emit/threading.cpp create mode 100644 src/x2w_shader/emit/threading.h create mode 100644 src/x2w_shader/emit/validator.cpp create mode 100644 src/x2w_shader/emit/validator.h create mode 100644 src/x2w_shader/emit/wave.cpp create mode 100644 src/x2w_shader/emit/wave.h create mode 100644 src/x2w_shader/error.h create mode 100644 src/x2w_shader/front/CMakeLists.txt create mode 100644 src/x2w_shader/front_hash.h create mode 100644 src/x2w_shader/gfx10/fields.cpp create mode 100644 src/x2w_shader/gfx10/fields.h create mode 100644 src/x2w_shader/gfx10/mod.cpp create mode 100644 src/x2w_shader/gfx10/mod.h create mode 100644 src/x2w_shader/gfx10/opcodes.cpp create mode 100644 src/x2w_shader/gfx10/opcodes.h create mode 100644 src/x2w_shader/gfx10/sp3.cpp create mode 100644 src/x2w_shader/gfx10/sp3.h create mode 100644 src/x2w_shader/io.cpp create mode 100644 src/x2w_shader/io.h create mode 100644 src/x2w_shader/ir.cpp create mode 100644 src/x2w_shader/ir.h create mode 100644 src/x2w_shader/lib.cpp create mode 100644 src/x2w_shader/lib.h create mode 100644 src/x2w_shader/native.cpp create mode 100644 src/x2w_shader/native.h create mode 100644 src/x2w_shader/resource.cpp create mode 100644 src/x2w_shader/resource.h create mode 100644 src/x2w_shader/spill.cpp create mode 100644 src/x2w_shader/spill.h create mode 100644 src/x2w_shader/structure.cpp create mode 100644 src/x2w_shader/structure.h create mode 100644 src/xmem_census.cpp create mode 100644 src/xmem_census.h create mode 100644 src/xmem_gpu_pool.cpp create mode 100644 src/xmem_gpu_pool.h create mode 100644 src/xmem_low.h create mode 100644 tests/bcpack_bc6h_test.cpp create mode 100644 tests/bcpack_bc6h_vectors.inl create mode 100644 tests/bcpack_bcn_check.py create mode 100644 tests/bcpack_bcn_decode_test.cpp create mode 100644 tests/buffer_address_index_check.cpp create mode 100644 tests/gfx10_layout_check.cpp create mode 100644 tests/gfx10_layout_golden.txt create mode 100644 tests/gpu_bind.cmake create mode 100644 tests/gpu_heap_tests.cmake create mode 100644 tests/mesh_clip_distance_check.py create mode 100644 tests/mesh_loop_state_check.py create mode 100644 tests/mesh_pc_table_check.py create mode 100644 tests/mesh_perlane_loop_check.py create mode 100644 tests/mesh_waterfall_check.py create mode 100644 tests/section_window_ops_check.cpp create mode 100644 tests/shader_db_check.cpp create mode 100644 tests/startup_bc_writer_srv.inl create mode 100644 tests/startup_bfm_absdiff_check.py create mode 100644 tests/startup_buffer_heap_index_check.py create mode 100644 tests/startup_buffer_store_check.py create mode 100644 tests/startup_carry_dst_check.py create mode 100644 tests/startup_class_f16_sdwa_check.py create mode 100644 tests/startup_class_sdwa_check.py create mode 100644 tests/startup_clip_distance_check.py create mode 100644 tests/startup_counted_search_check.py create mode 100644 tests/startup_cselect_vcc_lo_check.py create mode 100644 tests/startup_cx_async.cpp create mode 100644 tests/startup_cx_async.hlsl create mode 100644 tests/startup_cx_heap_raw.hlsl create mode 100644 tests/startup_cx_heap_words.hlsl create mode 100644 tests/startup_cx_pso_time.cpp create mode 100644 tests/startup_detile_draw.ps1 create mode 100644 tests/startup_draw_async_check.py create mode 100644 tests/startup_draw_dump_inputs_check.py create mode 100644 tests/startup_draw_fma_check.py create mode 100644 tests/startup_draw_heap_check.py create mode 100644 tests/startup_draw_heapwords_check.py create mode 100644 tests/startup_draw_lock_split_check.py create mode 100644 tests/startup_draw_lock_times.cpp create mode 100644 tests/startup_draw_srv_limit_check.py create mode 100644 tests/startup_draw_state.cpp create mode 100644 tests/startup_draw_state_check.py create mode 100644 tests/startup_draw_uav.cpp create mode 100644 tests/startup_draw_uav_check.py create mode 100644 tests/startup_dstorage_status_stats_check.cpp create mode 100644 tests/startup_execz_join_check.py create mode 100644 tests/startup_fma_exact_fxc_check.py create mode 100644 tests/startup_fmt_load_table_check.py create mode 100644 tests/startup_format_load_check.py create mode 100644 tests/startup_format_store_check.py create mode 100644 tests/startup_frame_rgb_sample.cpp create mode 100644 tests/startup_front_face_check.py create mode 100644 tests/startup_gfx10_view_words_check.cpp create mode 100644 tests/startup_gfx2hlsl_coverage_check.py create mode 100644 tests/startup_gfx2hlsl_draw_descnum_check.py create mode 100644 tests/startup_gfx2hlsl_draw_descword_check.py create mode 100644 tests/startup_gfx2hlsl_exec_lane_facts_check.py create mode 100644 tests/startup_gfx2hlsl_f16_arith_check.py create mode 100644 tests/startup_gfx2hlsl_f32_lg_local_check.py create mode 100644 tests/startup_gfx2hlsl_ldexp_check.py create mode 100644 tests/startup_gfx2hlsl_mix_fma_check.py create mode 100644 tests/startup_gfx2hlsl_mul_hi_mad_half_check.py create mode 100644 tests/startup_gfx2hlsl_root_local_check.py create mode 100644 tests/startup_gfx2hlsl_scalar_named_dest_check.py create mode 100644 tests/startup_gfx2hlsl_scc_carry_check.py create mode 100644 tests/startup_gfx2hlsl_shift64_literal_check.py create mode 100644 tests/startup_gfx2hlsl_wave_union_check.py create mode 100644 tests/startup_gpu_abi_heap_start_check.cpp create mode 100644 tests/startup_gpu_abi_off_check.cpp create mode 100644 tests/startup_gpu_ambient.inl create mode 100644 tests/startup_gpu_bind.hlsl create mode 100644 tests/startup_gpu_bind_check.cpp create mode 100644 tests/startup_gpu_build_queue.cpp create mode 100644 tests/startup_gpu_compute_trace.inl create mode 100644 tests/startup_gpu_db_check.cpp create mode 100644 tests/startup_gpu_depth_twins.cpp create mode 100644 tests/startup_gpu_heap.cpp create mode 100644 tests/startup_gpu_heap.hlsl create mode 100644 tests/startup_gpu_heap_fit_check.cpp create mode 100644 tests/startup_gpu_heap_layout_check.cpp create mode 100644 tests/startup_gpu_heap_shim.cpp create mode 100644 tests/startup_gpu_indirect.cpp create mode 100644 tests/startup_gpu_indirect.hlsl create mode 100644 tests/startup_gpu_list_states.inl create mode 100644 tests/startup_gpu_memory.hlsl create mode 100644 tests/startup_gpu_memory_store.hlsl create mode 100644 tests/startup_gpu_memory_store.inl create mode 100644 tests/startup_gpu_pipeline.cpp create mode 100644 tests/startup_gpu_pipeline.hlsl create mode 100644 tests/startup_gpu_pipeline_state_check.cpp create mode 100644 tests/startup_gpu_reference_library.cpp create mode 100644 tests/startup_gpu_resident_mips.inl create mode 100644 tests/startup_gpu_roots_check.cpp create mode 100644 tests/startup_gpu_small_texture_heap.inl create mode 100644 tests/startup_gpu_trace_request.cpp create mode 100644 tests/startup_gpu_user_data_check.cpp create mode 100644 tests/startup_gpu_warm_bad.cpp create mode 100644 tests/startup_heap_texture_check.py create mode 100644 tests/startup_image_d16_check.py create mode 100644 tests/startup_image_get_lod_check.py create mode 100644 tests/startup_image_invariant_check.py create mode 100644 tests/startup_image_sample_b_local_check.py create mode 100644 tests/startup_image_sample_d_check.py create mode 100644 tests/startup_image_sample_implicit_lod_check.py create mode 100644 tests/startup_indirect_dispatch.hlsl create mode 100644 tests/startup_indirect_dispatch_local.cpp create mode 100644 tests/startup_int_three_operand_check.py create mode 100644 tests/startup_interp_f16_check.py create mode 100644 tests/startup_lane_invariant_check.py create mode 100644 tests/startup_lit64_check.py create mode 100644 tests/startup_literal_halves_check.py create mode 100644 tests/startup_log_cap_check.cpp create mode 100644 tests/startup_loop_carried_check.py create mode 100644 tests/startup_loop_regions_check.py create mode 100644 tests/startup_memory_srv_announced_check.py create mode 100644 tests/startup_memory_srv_detile.ps1 create mode 100644 tests/startup_mesh_barrier_ranges_check.py create mode 100644 tests/startup_mesh_desc_numeric_check.py create mode 100644 tests/startup_mesh_descword_check.py create mode 100644 tests/startup_mesh_dispatch.cpp create mode 100644 tests/startup_mesh_dispatch.hlsl create mode 100644 tests/startup_mesh_exec_lineage_check.py create mode 100644 tests/startup_mesh_exec_off_check.py create mode 100644 tests/startup_mesh_exec_restore_check.py create mode 100644 tests/startup_mesh_exec_walk_check.py create mode 100644 tests/startup_mesh_first_lane_check.py create mode 100644 tests/startup_mesh_heap_copy_check.py create mode 100644 tests/startup_mesh_heap_sampler_check.py create mode 100644 tests/startup_mesh_lane_scc_check.py create mode 100644 tests/startup_mesh_literal_flow_check.py create mode 100644 tests/startup_mesh_loop_tail_check.py create mode 100644 tests/startup_mesh_output_budget_check.py create mode 100644 tests/startup_mesh_padded_barriers_check.py create mode 100644 tests/startup_mesh_restored_scalar_check.py create mode 100644 tests/startup_mesh_rtv_variant_check.py create mode 100644 tests/startup_mesh_salu_check.py create mode 100644 tests/startup_mesh_spi_input_check.py create mode 100644 tests/startup_mesh_spill_check.py create mode 100644 tests/startup_mesh_vcc_data_check.py create mode 100644 tests/startup_mesh_vcc_vote_check.py create mode 100644 tests/startup_mrt_wide_int_check.py create mode 100644 tests/startup_pack_f16_check.py create mode 100644 tests/startup_pipeline_state_local_check.cpp create mode 100644 tests/startup_placed_fast.cpp create mode 100644 tests/startup_probe_cache.cpp create mode 100644 tests/startup_profile_check.py create mode 100644 tests/startup_profile_probe.cpp create mode 100644 tests/startup_quad_divergent_check.py create mode 100644 tests/startup_quad_dpp_check.py create mode 100644 tests/startup_quad_uniform_check.py create mode 100644 tests/startup_readfirstlane_chain_check.py create mode 100644 tests/startup_readfirstlane_exec_check.py create mode 100644 tests/startup_rgba8_dmode.ps1 create mode 100644 tests/startup_root_srv_lazy_check.py create mode 100644 tests/startup_round_mode_check.py create mode 100644 tests/startup_rtv_bind_local.cpp create mode 100644 tests/startup_sample_c_border_check.py create mode 100644 tests/startup_sample_c_preclamp_check.py create mode 100644 tests/startup_saveexec_same_reg_check.py create mode 100644 tests/startup_scalar_bits_check.py create mode 100644 tests/startup_scalar_complement_mask_check.py create mode 100644 tests/startup_scalar_const_fold_check.py create mode 100644 tests/startup_scalar_ff_check.py create mode 100644 tests/startup_scalar_nand_check.py create mode 100644 tests/startup_scalar_pack_hh_check.py create mode 100644 tests/startup_scmp_u64_check.py create mode 100644 tests/startup_sdwa_cvt_check.py create mode 100644 tests/startup_sdwa_mov_check.py create mode 100644 tests/startup_shader_trace_misses_check.py create mode 100644 tests/startup_smem_overlap_mask_check.py create mode 100644 tests/startup_sopk_sign_check.py create mode 100644 tests/startup_spi_input_check.py create mode 100644 tests/startup_stream_pc_table_check.py create mode 100644 tests/startup_stream_ps_inputs_check.py create mode 100644 tests/startup_stream_vertex_exit_check.py create mode 100644 tests/startup_tbuffer_uint_snorm_check.py create mode 100644 tests/startup_vopc_dpp_check.py create mode 100644 tests/startup_vs_heap_check.py create mode 100644 tests/startup_vs_instance_id_check.py create mode 100644 tests/startup_vsregs_state_check.py create mode 100644 tests/startup_vswap_check.py create mode 100644 tests/startup_waterfall_check.py create mode 100644 tests/tile_mapping_shared_heap_check.cpp create mode 100644 tests/x2w_shader/archive_decode_check.cpp create mode 100644 tests/x2w_shader/core_tests.cpp create mode 100644 tests/x2w_shader/emit/atomic_test.cpp create mode 100644 tests/x2w_shader/emit/barycentric_test.cpp create mode 100644 tests/x2w_shader/emit/bitcode_test.cpp create mode 100644 tests/x2w_shader/emit/container_test.cpp create mode 100644 tests/x2w_shader/emit/diff_test.cpp create mode 100644 tests/x2w_shader/emit/host_test.cpp create mode 100644 tests/x2w_shader/emit/intersect_test.cpp create mode 100644 tests/x2w_shader/emit/lower_card_util.h create mode 100644 tests/x2w_shader/emit/lower_cube_lod_test.cpp create mode 100644 tests/x2w_shader/emit/lower_permlane_test.cpp create mode 100644 tests/x2w_shader/emit/lower_probe_test.cpp create mode 100644 tests/x2w_shader/emit/lower_size_test.cpp create mode 100644 tests/x2w_shader/emit/lower_test.cpp create mode 100644 tests/x2w_shader/emit/lower_valu_test.cpp create mode 100644 tests/x2w_shader/emit/lower_waterfall_test.cpp create mode 100644 tests/x2w_shader/emit/lower_wave64_test.cpp create mode 100644 tests/x2w_shader/emit/mod_test.cpp create mode 100644 tests/x2w_shader/emit/opt_test.cpp create mode 100644 tests/x2w_shader/emit/own_bits_test.cpp create mode 100644 tests/x2w_shader/emit/rect_test.cpp create mode 100644 tests/x2w_shader/emit/ref/README.txt create mode 100644 tests/x2w_shader/emit/ref/out/build.bin create mode 100644 tests/x2w_shader/emit/ref/out/cs_basic.bin create mode 100644 tests/x2w_shader/emit/ref/out/hashes.bin create mode 100644 tests/x2w_shader/emit/ref/out/ps_basic.bin create mode 100644 tests/x2w_shader/emit/ref/out/psv_cs.bin create mode 100644 tests/x2w_shader/emit/ref/out/psv_gs.bin create mode 100644 tests/x2w_shader/emit/ref/out/psv_ms.bin create mode 100644 tests/x2w_shader/emit/ref/out/psv_ps.bin create mode 100644 tests/x2w_shader/emit/ref/out/rect_plain.bin create mode 100644 tests/x2w_shader/emit/ref/out/rect_prim.bin create mode 100644 tests/x2w_shader/emit/ref/out/sig_in.bin create mode 100644 tests/x2w_shader/emit/ref/out/sig_out.bin create mode 100644 tests/x2w_shader/emit/ref/out_opt0/build.bin create mode 100644 tests/x2w_shader/emit/ref/out_opt0/cs_basic.bin create mode 100644 tests/x2w_shader/emit/ref/out_opt0/hashes.bin create mode 100644 tests/x2w_shader/emit/ref/out_opt0/ps_basic.bin create mode 100644 tests/x2w_shader/emit/ref/out_opt0/psv_cs.bin create mode 100644 tests/x2w_shader/emit/ref/out_opt0/psv_gs.bin create mode 100644 tests/x2w_shader/emit/ref/out_opt0/psv_ms.bin create mode 100644 tests/x2w_shader/emit/ref/out_opt0/psv_ps.bin create mode 100644 tests/x2w_shader/emit/ref/out_opt0/rect_plain.bin create mode 100644 tests/x2w_shader/emit/ref/out_opt0/rect_prim.bin create mode 100644 tests/x2w_shader/emit/ref/out_opt0/sig_in.bin create mode 100644 tests/x2w_shader/emit/ref/out_opt0/sig_out.bin create mode 100644 tests/x2w_shader/emit/ref/ref_dump.rs create mode 100644 tests/x2w_shader/emit/ref_test.cpp create mode 100644 tests/x2w_shader/emit/ref_validate_test.cpp create mode 100644 tests/x2w_shader/emit/sampler_test.cpp create mode 100644 tests/x2w_shader/emit/test_util.h create mode 100644 tests/x2w_shader/emit/threading_test.cpp create mode 100644 tests/x2w_shader/emit/validator_test.cpp create mode 100644 tests/x2w_shader/emit/wave_test.cpp create mode 100644 tests/x2w_shader/resource_fixtures.h create mode 100644 tests/x2w_shader/vs_bvh_test.cpp create mode 100644 tests/x2w_shader/vs_front_test.h create mode 100644 tests/x2w_shader/vs_io_test.cpp create mode 100644 tests/x2w_shader/vs_native_test.cpp create mode 100644 tests/x2w_shader/vs_resource_test.cpp create mode 100644 tests/x2w_shader/vs_spill_test.cpp create mode 100644 tests/x2w_shader/vs_structure_test.cpp create mode 100644 tests/x2w_tool/blake3_test.cpp create mode 100644 tests/x2w_tool/scan_test.cpp create mode 100644 tests/x2w_tool/sgd5_test.cpp create mode 100644 tests/xmem_linear_placement.cpp create mode 100644 tests/xmem_scatter_refusal_check.py create mode 100644 tools/bcpack_bcn.py create mode 100644 tools/shader_material_fields.mjs create mode 100644 tools/startup/compute_harness.cpp create mode 100644 tools/startup/gpu_slab_pool.py create mode 100644 tools/startup/mesh2hlsl.py create mode 100644 tools/startup/mesh_harness.cpp create mode 100644 tools/startup/sample_profile.py create mode 100644 tools/startup/shader_trace_misses.cpp create mode 100644 tools/startup/window_status.py create mode 100644 tools/x2w/blake3.cpp create mode 100644 tools/x2w/blake3.h create mode 100644 tools/x2w/main.cpp create mode 100644 tools/x2w/scan.cpp create mode 100644 tools/x2w/scan.h create mode 100644 tools/x2w/sgd5.cpp create mode 100644 tools/x2w/sgd5.h create mode 100644 tools/x2w/shaders_dump.cpp create mode 100644 tools/x2w/shaders_dump.h diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 4a225bda8e..b8a7765210 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -308,6 +308,11 @@ jobs: tests/startup_smem_address_check.py \ tests/startup_stream_fetch_check.py \ tests/startup_stream_interface_check.py \ + tests/startup_waterfall_check.py \ + tests/startup_gfx2hlsl_scc_carry_check.py \ + tests/startup_vs_instance_id_check.py \ + tests/startup_gfx2hlsl_draw_descword_check.py \ + tests/startup_gfx2hlsl_draw_descnum_check.py \ tests/compute_alu_cmp_ne_check.py \ tests/compute_entry_layout_check.py \ tests/compute_buffer_atomics_check.py \ diff --git a/AGENTS.md b/AGENTS.md index d7c8b49ab0..6970655b3c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -180,6 +180,14 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_live_telemetry_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_capture_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_watch_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_ldexp_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_shift64_literal_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mix_fma_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_named_dest_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f16_arith_check.py +./out/pe-env/bin/python -B tests/startup_image_sample_implicit_lod_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_exec_lane_facts_check.py +./out/pe-env/bin/python -B tests/startup_fma_exact_fxc_check.py ./out/pe-env/bin/python -B tests/startup_translator_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_smem_offset_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sload_const_offset_check.py @@ -245,6 +253,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_vopc_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_lg_local_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 diff --git a/CMakeLists.txt b/CMakeLists.txt index bd107f2a78..a3c3e63702 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,6 +3,14 @@ project(Xbox2Windows LANGUAGES CXX) enable_testing() +add_executable(shader_trace_misses tools/startup/shader_trace_misses.cpp) +target_compile_features(shader_trace_misses PRIVATE cxx_std_17) + +add_executable(startup_frame_rgb_sample tests/startup_frame_rgb_sample.cpp) +target_include_directories(startup_frame_rgb_sample PRIVATE src) +target_compile_features(startup_frame_rgb_sample PRIVATE cxx_std_17) +add_test(NAME startup_frame_rgb_sample COMMAND startup_frame_rgb_sample) + # Python never caches the bytecode of the script it is started with, so every start of a big # tests/.py recompiled it. tests/pyc_main.py runs that file through the import system, # which reuses a valid .pyc. The add_test calls below keep naming the script; this wrapper swaps in @@ -24,6 +32,8 @@ endfunction() set(INTAKE_PYTHON "${CMAKE_SOURCE_DIR}/out/pe-env/Scripts/python.exe" CACHE FILEPATH "Native x64 Python with pefile for static intake tests") if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_shader_trace_misses COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_shader_trace_misses_check.py" $) add_test(NAME pyc_main_entry COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pyc_main_check.py") set_tests_properties(pyc_main_entry PROPERTIES TIMEOUT 60) @@ -167,7 +177,8 @@ set_tests_properties(era_physical_owns_last_page_control PROPERTIES PASS_REGULAR # Desktop xmem.dll for native and mapped callers. add_library(xmem_shim SHARED src/xmem_shim.cpp src/xmem_shim.def src/xmem_gpu_usage.cpp src/adapter_identity.cpp src/era_heap.cpp src/era_query.cpp src/era_physical.cpp - src/era_title_gpu.cpp src/era_gpu_alias.cpp src/era_title_va.cpp src/xmem_mapped_pages.cpp) + src/era_title_gpu.cpp src/era_gpu_alias.cpp src/era_title_va.cpp src/xmem_mapped_pages.cpp src/xmem_census.cpp + src/xmem_gpu_pool.cpp) set_target_properties(xmem_shim PROPERTIES OUTPUT_NAME xmem) # LINK uses explicit export ordinals in the generated import library. Keep # those ordinals in the DLL and build the consumer library with names. @@ -376,9 +387,22 @@ add_dependencies(x2w_build_rev x2w_build_rev_generate) target_include_directories(x2w_build_rev PRIVATE src) target_compile_options(x2w_build_rev PRIVATE /Zl) +# The BLAKE3 reference C code (src/startup_stubs/blake3, from the official repository's c/ directory, version 1.8.7, +# CC0 / Apache-2.0), portable implementation only: the shader database key (gpu_db.h, PLAN.md contract C1). +enable_language(C) +# Every target that compiles d3d12_xs_device.cpp also compiles X2W_GPU_SOURCES (each with its own CRT); +# x2w_blake3 is the same code as a static library for fixtures and the shader database tools. +set(X2W_BLAKE3_SOURCES src/startup_stubs/blake3/blake3.c src/startup_stubs/blake3/blake3_dispatch.c + src/startup_stubs/blake3/blake3_portable.c) +set_source_files_properties(${X2W_BLAKE3_SOURCES} PROPERTIES + COMPILE_DEFINITIONS "BLAKE3_NO_SSE2;BLAKE3_NO_SSE41;BLAKE3_NO_AVX2;BLAKE3_NO_AVX512;BLAKE3_USE_NEON=0") +set(X2W_GPU_SOURCES src/startup_stubs/gpu_db.cpp src/shader_db/shader_db.cpp ${X2W_BLAKE3_SOURCES}) +add_library(x2w_blake3 STATIC ${X2W_BLAKE3_SOURCES}) +set_target_properties(x2w_blake3 PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") # Desktop d3d12_xs.dll for the package DLLs' two named d3d12_xs root-signature imports. add_library(d3d12_xs_shim SHARED src/d3d12_xs_shim.cpp src/d3d12x_device_slots.cpp - src/d3d12_xs_iids.cpp src/d3d12_xs_shim.def src/startup_stubs/d3d12_xs_device.cpp) + src/d3d12_xs_iids.cpp src/d3d12_xs_shim.def src/startup_stubs/d3d12_xs_traps.cpp src/startup_stubs/d3d12_xs_device.cpp + ${X2W_GPU_SOURCES}) set_target_properties(d3d12_xs_shim PROPERTIES OUTPUT_NAME d3d12_xs) target_include_directories(d3d12_xs_shim PRIVATE src) target_compile_features(d3d12_xs_shim PRIVATE cxx_std_17) @@ -542,7 +566,7 @@ endif() # The DirectStorage heartbeat reports this process's peak commit (#1199). target_link_libraries(startup_stub_xcrdapi PRIVATE psapi) target_sources(startup_stub_gameinput PRIVATE src/startup_stubs/runtime_proxy.cpp) -target_link_libraries(d3d12_xs_shim PRIVATE user32 gdi32 d3dcompiler dxgi x2w_build_rev) +target_link_libraries(d3d12_xs_shim PRIVATE user32 gdi32 dcomp d3dcompiler dxgi x2w_build_rev) 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>") @@ -591,6 +615,44 @@ endforeach() set_tests_properties(startup_descriptor_increment_hardware PROPERTIES SKIP_RETURN_CODE 77) set_tests_properties(startup_descriptor_increment_hardware startup_descriptor_increment_warp PROPERTIES TIMEOUT 60 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=1") +# The shader binding ABI switch (src/startup_stubs/gpu_abi.h, gpu_hooks.inl, PLAN.md WP0) on WARP: unset, device slots +# 15, 14, 57, 62 and 86 answer as before and no hook counter moves; X2W_GPU_ABI=1, slot 15 answers 32/16, 57 +# refuses, 62/86 log their blake3 keys and reach the stubs. The mutated run flips the switch and is the negative control. +add_executable(startup_gpu_abi_off_check tests/startup_gpu_abi_off_check.cpp) +target_include_directories(startup_gpu_abi_off_check PRIVATE src) +target_compile_features(startup_gpu_abi_off_check PRIVATE cxx_std_17) +target_link_libraries(startup_gpu_abi_off_check PRIVATE d3d12_xs_shim x2w_blake3 d3d12 dxgi) +set_target_properties(startup_gpu_abi_off_check PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +add_test(NAME startup_gpu_abi_off COMMAND startup_gpu_abi_off_check off) +add_test(NAME startup_gpu_abi_on COMMAND startup_gpu_abi_off_check on) +add_test(NAME startup_gpu_abi_off_mutate_control COMMAND startup_gpu_abi_off_check off --mutate) +set_tests_properties(startup_gpu_abi_off_mutate_control PROPERTIES WILL_FAIL TRUE) +set_tests_properties(startup_gpu_abi_off startup_gpu_abi_on startup_gpu_abi_off_mutate_control PROPERTIES TIMEOUT 60 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1") +# WP3 vbind (gpu_roots.h, gpu_bind.inl): the header checks and the WARP binding checks. +include(tests/gpu_bind.cmake) +# WP5 rawtwins (gpu_heap.h, gpu_heap.inl, gpu_views.inl): the layout check, the device and shim tests. +include(tests/gpu_heap_tests.cmake) +add_executable(startup_gpu_abi_heap_start_check tests/startup_gpu_abi_heap_start_check.cpp) +target_compile_features(startup_gpu_abi_heap_start_check PRIVATE cxx_std_17) +target_link_libraries(startup_gpu_abi_heap_start_check PRIVATE d3d12_xs_shim d3d12 dxgi) +set_target_properties(startup_gpu_abi_heap_start_check PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +add_test(NAME startup_gpu_abi_heap_start COMMAND startup_gpu_abi_heap_start_check) +set_tests_properties(startup_gpu_abi_heap_start PROPERTIES TIMEOUT 60 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1") +add_executable(startup_gpu_heap_fit_check tests/startup_gpu_heap_fit_check.cpp) +target_include_directories(startup_gpu_heap_fit_check PRIVATE src) +target_compile_features(startup_gpu_heap_fit_check PRIVATE cxx_std_17) +target_link_libraries(startup_gpu_heap_fit_check PRIVATE d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_gpu_read_states_${backend} COMMAND startup_gpu_heap_fit_check ${backend} --read-states) + set_tests_properties(startup_gpu_read_states_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME startup_gpu_heap_fit_${backend} COMMAND startup_gpu_heap_fit_check ${backend}) + add_test(NAME startup_gpu_heap_fit_${backend}_mutate COMMAND startup_gpu_heap_fit_check ${backend} --mutate) + set_tests_properties(startup_gpu_heap_fit_${backend} startup_gpu_heap_fit_${backend}_mutate PROPERTIES TIMEOUT 60 + SKIP_RETURN_CODE 77) + set_tests_properties(startup_gpu_heap_fit_${backend}_mutate PROPERTIES WILL_FAIL TRUE) +endforeach() # Which heap type values slot 15 forwards to desktop (src/startup_stubs/descriptor_heap_type.h), without a # device. The mutated runs are the negative controls. add_executable(startup_descriptor_heap_type_check tests/startup_descriptor_heap_type_check.cpp) @@ -636,6 +698,10 @@ foreach(adapter IN ITEMS hardware warp) set_tests_properties(startup_view_heap_${adapter} PROPERTIES SKIP_RETURN_CODE 77) endforeach() add_executable(startup_stub_consumer tests/startup_stub_consumer.cpp) +# BCPack BC6H rebuild and its dictionary fallback on synthetic lane symbols (bcpack_bc6h.h). +add_executable(bcpack_bc6h_test tests/bcpack_bc6h_test.cpp) +target_compile_features(bcpack_bc6h_test PRIVATE cxx_std_17) +add_test(NAME bcpack_bc6h COMMAND bcpack_bc6h_test) add_executable(startup_gameinput_keys tests/startup_gameinput_keys.cpp) target_compile_features(startup_gameinput_keys PRIVATE cxx_std_17) add_test(NAME startup_gameinput_keys COMMAND startup_gameinput_keys "$") @@ -676,7 +742,10 @@ set_tests_properties(startup_present_signature_unheld_source_control_warp PROPER if(EXISTS "${INTAKE_PYTHON}") add_executable(startup_present_producer tests/startup_present_producer.cpp) target_compile_features(startup_present_producer PRIVATE cxx_std_17) - target_link_libraries(startup_present_producer PRIVATE d3d12_xs_shim d3d12 dxgi) + target_link_libraries(startup_present_producer PRIVATE d3d12_xs_shim d3d12 dxgi user32) + add_test(NAME startup_present_original_window_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_present_producer_check.py" warp "$" title-window) + set_tests_properties(startup_present_original_window_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) foreach(backend IN ITEMS warp hardware) add_test(NAME startup_present_producer_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_present_producer_check.py" "${backend}" "$") @@ -690,6 +759,20 @@ add_executable(startup_placement_alloc tests/startup_placement_alloc.cpp) target_compile_features(startup_placement_alloc PRIVATE cxx_std_17) target_include_directories(startup_placement_alloc PRIVATE src) add_test(NAME startup_placement_alloc COMMAND startup_placement_alloc) +# Log caps that never wrap (src/startup_stubs/log_cap.h); the old wrapping pattern is the negative control. +add_executable(startup_log_cap_check tests/startup_log_cap_check.cpp) +target_compile_features(startup_log_cap_check PRIVATE cxx_std_17) +target_include_directories(startup_log_cap_check PRIVATE src) +add_test(NAME startup_log_cap COMMAND startup_log_cap_check) +add_test(NAME startup_log_cap_wrap_control COMMAND startup_log_cap_check --mutate wrap) +set_tests_properties(startup_log_cap_wrap_control PROPERTIES WILL_FAIL TRUE) +# Status wait diagnostics of the DirectStorage stand-in (src/startup_stubs/dstorage_status_stats.h). +add_executable(startup_dstorage_status_stats_check tests/startup_dstorage_status_stats_check.cpp) +target_compile_features(startup_dstorage_status_stats_check PRIVATE cxx_std_17) +target_include_directories(startup_dstorage_status_stats_check PRIVATE src) +add_test(NAME startup_dstorage_status_stats COMMAND startup_dstorage_status_stats_check) +add_test(NAME startup_dstorage_status_stats_stale_control COMMAND startup_dstorage_status_stats_check --mutate no-stale) +set_tests_properties(startup_dstorage_status_stats_stale_control PROPERTIES WILL_FAIL TRUE) # The same registration under the lock held exclusively, and max_width kept at the widest record # (src/startup_stubs/placement_publish.h). The mutated run is the negative control. add_executable(startup_placement_publish_check tests/startup_placement_publish_check.cpp) @@ -736,9 +819,9 @@ set_tests_properties(startup_list_copy_texture_slice_control PROPERTIES WILL_FAI # The same call through the wrapped command list: two array slices round-trip, and an out-of-range subresource # or a format mismatch is refused before any desktop copy. -add_executable(startup_list_copy_texture_warp tests/startup_list_copy_texture_warp.cpp) +add_executable(startup_list_copy_texture_warp tests/startup_list_copy_texture_warp.cpp tests/desktop_gpu.cpp) target_compile_features(startup_list_copy_texture_warp PRIVATE cxx_std_17) -target_link_libraries(startup_list_copy_texture_warp PRIVATE d3d12_xs_shim d3d12 dxgi) +target_link_libraries(startup_list_copy_texture_warp PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) foreach(backend IN ITEMS warp hardware) add_test(NAME startup_list_copy_texture_${backend} COMMAND startup_list_copy_texture_warp ${backend}) set_tests_properties(startup_list_copy_texture_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 @@ -883,9 +966,12 @@ endforeach() # The test compiles the stand-in's source into itself so it can redirect CreateThread and operator new. add_executable(startup_dstorage_destination_check tests/startup_dstorage_destination_check.cpp) target_compile_features(startup_dstorage_destination_check PRIVATE cxx_std_17) -add_dependencies(startup_dstorage_destination_check startup_stub_xcrdapi) +add_dependencies(startup_dstorage_destination_check startup_stub_xcrdapi xmem_shim) add_test(NAME startup_dstorage_destination COMMAND startup_dstorage_destination_check "$") set_tests_properties(startup_dstorage_destination PROPERTIES TIMEOUT 60) +add_test(NAME startup_dstorage_destination_xmem COMMAND startup_dstorage_destination_check + "$" "$") +set_tests_properties(startup_dstorage_destination_xmem PROPERTIES TIMEOUT 60 ENVIRONMENT "X2W_DSTORAGE_DEST_WAIT_MS=0") add_executable(startup_storage_worker_start tests/startup_storage_worker_start.cpp) target_compile_features(startup_storage_worker_start PRIVATE cxx_std_17) target_include_directories(startup_storage_worker_start PRIVATE src) @@ -1095,6 +1181,17 @@ endif() add_executable(startup_host_cpu_probe tests/startup_host_cpu_probe.cpp) target_compile_features(startup_host_cpu_probe PRIVATE cxx_std_17) # Placed buffers at the boundary between two views of physical pages (src/xmem_mapped_pages.cpp). +add_executable(xmem_linear_placement_check tests/xmem_linear_placement.cpp tests/desktop_gpu.cpp) +target_include_directories(xmem_linear_placement_check PRIVATE src) +target_compile_features(xmem_linear_placement_check PRIVATE cxx_std_17) +target_link_libraries(xmem_linear_placement_check PRIVATE xmem_shim d3d12_xs_shim d3d12 dxgi onecore) +foreach(mode IN ITEMS linear baseline) + add_test(NAME xmem_linear_placement_${mode}_warp COMMAND xmem_linear_placement_check ${mode}) +endforeach() + +add_test(NAME xmem_linear_placement_linear_hardware COMMAND xmem_linear_placement_check linear hardware) +set_tests_properties(xmem_linear_placement_linear_hardware PROPERTIES SKIP_RETURN_CODE 77) + add_executable(xmem_page_runs_device_check tests/xmem_page_runs_device_check.cpp) target_compile_features(xmem_page_runs_device_check PRIVATE cxx_std_17) target_link_libraries(xmem_page_runs_device_check PRIVATE xmem_shim d3d12_xs_shim d3d12 dxgi) @@ -1108,6 +1205,11 @@ target_compile_features(startup_launch_probe PRIVATE cxx_std_17) # Input for the startup debugger's diagnostics check (tests/startup_debug_check.py). add_executable(startup_debug_probe tests/startup_debug_probe.cpp) target_compile_features(startup_debug_probe PRIVATE cxx_std_17) +# Input for the sampling-profiler check (tests/startup_profile_check.py); with a pdb so frames get names. +add_executable(startup_profile_probe tests/startup_profile_probe.cpp) +target_compile_features(startup_profile_probe PRIVATE cxx_std_17) +target_compile_options(startup_profile_probe PRIVATE /Zi) +target_link_options(startup_profile_probe PRIVATE /DEBUG) # The DLL the probe calls for the debugger's call-hook case (--trace-calls). add_library(startup_debug_calls SHARED tests/startup_debug_calls.cpp) add_dependencies(startup_debug_probe startup_debug_calls) @@ -1198,7 +1300,8 @@ add_test(NAME startup_typed_buffer_view COMMAND startup_typed_buffer_view) add_library(startup_stream_setup_obj OBJECT tests/startup_stream_setup.cpp) target_compile_features(startup_stream_setup_obj PRIVATE cxx_std_17) add_executable(startup_stream_consumer tests/startup_stream_consumer.cpp $ tests/startup_stream_draw.cpp - tests/startup_address_srv.cpp tests/startup_root_cbv.cpp tests/startup_root_heap.cpp) + tests/startup_address_srv.cpp tests/startup_root_cbv.cpp tests/startup_root_heap.cpp + tests/startup_draw_uav.cpp) target_compile_features(startup_stream_consumer PRIVATE cxx_std_17) target_link_libraries(startup_stream_consumer PRIVATE d3d12_xs_shim startup_stub_xg_xs d3d12 dxgi d3dcompiler) target_sources(startup_stream_consumer PRIVATE tests/startup_frame_copy.cpp) @@ -1218,6 +1321,10 @@ add_executable(startup_draw_depth_target tests/startup_draw_depth_target.cpp $) +target_compile_features(startup_draw_state PRIVATE cxx_std_17) +target_link_libraries(startup_draw_state PRIVATE d3d12_xs_shim d3d12 dxgi) add_executable(startup_stream_rasterizer tests/startup_stream_rasterizer.cpp $) target_compile_features(startup_stream_rasterizer PRIVATE cxx_std_17) target_link_libraries(startup_stream_rasterizer PRIVATE d3d12_xs_shim d3d12 dxgi) @@ -1240,10 +1347,11 @@ target_link_libraries(startup_queue_page_batch PRIVATE d3d12_xs_shim dxgi OneCor add_dependencies(startup_queue_page_batch xmem_shim) add_test(NAME startup_queue_page_batch_warp COMMAND startup_queue_page_batch "$") add_test(NAME startup_queue_page_batch_runs_warp COMMAND startup_queue_page_batch "$" runs) +# LOCAL: queue slot 31 runs upstream's page batch only with X2W_UPSTREAM_QUEUE_PAGE_BATCH=1. set_tests_properties(startup_queue_page_batch_warp PROPERTIES RUN_SERIAL TRUE TIMEOUT 90 - ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=0") + ENVIRONMENT "X2W_UPSTREAM_QUEUE_PAGE_BATCH=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=0") set_tests_properties(startup_queue_page_batch_runs_warp PROPERTIES RUN_SERIAL TRUE TIMEOUT 90 SKIP_RETURN_CODE 77 - ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=1") + ENVIRONMENT "X2W_UPSTREAM_QUEUE_PAGE_BATCH=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=1") # Closed lists stay submittable, also after their allocator's Reset (#1352). add_executable(startup_list_resubmit tests/startup_list_resubmit.cpp) @@ -1266,6 +1374,16 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_TEST_SUBMIT_FENCE_FAIL=1") endforeach() +# LOCAL: OMSetRenderTargets with a single descriptor range and handles that hold no view, through the outcome +# counters (the local check, moved from tests/startup_rtv_bind.cpp at the upstream merge). +add_executable(startup_rtv_bind_local tests/startup_rtv_bind_local.cpp) +target_compile_features(startup_rtv_bind_local PRIVATE cxx_std_17) +target_link_libraries(startup_rtv_bind_local PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_rtv_bind_local_${backend} COMMAND startup_rtv_bind_local ${backend}) + set_tests_properties(startup_rtv_bind_local_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") +endforeach() add_executable(startup_upload_arena tests/startup_upload_arena.cpp) target_compile_features(startup_upload_arena PRIVATE cxx_std_17) target_include_directories(startup_upload_arena PRIVATE src) @@ -1384,6 +1502,13 @@ 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). +add_test(NAME startup_cold_texture_priority_off_warp COMMAND startup_resource_retire_title warp cold-off) +set_tests_properties(startup_cold_texture_priority_off_warp PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_COLD_TEXTURE_PRIORITY=0;X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1") +add_test(NAME startup_cold_texture_priority_warp COMMAND startup_resource_retire_title warp cold) +set_tests_properties(startup_cold_texture_priority_warp PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_COLD_TEXTURE_PRIORITY=1;X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1") + 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) @@ -1416,7 +1541,10 @@ 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) + # LOCAL merge: upstream's ExecuteIndirect (list slot 61) and compute root handlers are behind switches here + # (docs/experiments.md, "Local runtime switches for upstream paths"); this upstream test exercises that path. + set_tests_properties(startup_indirect_dispatch_${backend} startup_indirect_root_constants_${backend} startup_indirect_count_${backend} PROPERTIES TIMEOUT 30 + ENVIRONMENT "X2W_UPSTREAM_EXECUTE_INDIRECT=1;X2W_UPSTREAM_COMPUTE_ROOT=1") endforeach() set_tests_properties(startup_indirect_dispatch_hardware startup_indirect_root_constants_hardware startup_indirect_count_hardware PROPERTIES SKIP_RETURN_CODE 77) @@ -1529,6 +1657,25 @@ foreach(backend IN ITEMS warp hardware) set_tests_properties(startup_rtv_bind_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") endforeach() +# LOCAL merge: these upstream tests exercise upstream paths that overlap local ones and are behind switches here +# (docs/experiments.md, "Local runtime switches for upstream paths"): list slots 61, 33/43 and 148. +set(x2w_upstream_list_paths "X2W_UPSTREAM_EXECUTE_INDIRECT=set:1;X2W_UPSTREAM_COMPUTE_ROOT=set:1;X2W_LIST_UPLOAD_PAGES=set:1;X2W_UPSTREAM_MESH86_CACHE=set:1") +foreach(backend IN ITEMS warp hardware) + set(x2w_upstream_list_tests startup_slot148_acceptance_${backend} startup_slot148_acceptance_nodebug_${backend} + startup_resource_budget_${backend}_debug0 startup_resource_budget_${backend}_debug0_inline_control + startup_resource_budget_${backend}_debug1 startup_resource_budget_${backend}_debug1_inline_control + startup_indirect_mesh_request_${backend} startup_rtv_bind_${backend} + startup_slot148_acceptance_serialized_${backend} startup_slot148_acceptance_serialized_nodebug_${backend}) + foreach(mode IN ITEMS draw_indexed draw translated_draw copy_provenance copy_provenance_off translated_indexed + translated_indexed_upload translated_indexed_rect mesh mesh_console mesh_amplified + mesh_xmem_arguments mesh_xmem_arguments_skip_wait rectlist translated_refusal_census + other_refusal_census translated_indexed_alias translated_indexed_alias_off) + list(APPEND x2w_upstream_list_tests startup_indirect_${mode}_${backend}) + endforeach() + set_tests_properties(${x2w_upstream_list_tests} PROPERTIES ENVIRONMENT_MODIFICATION "${x2w_upstream_list_paths}") +endforeach() +set_tests_properties(startup_indirect_counts_control_warp startup_indirect_translated_refusal_census_control_warp + startup_indirect_other_refusal_census_control_warp PROPERTIES ENVIRONMENT_MODIFICATION "${x2w_upstream_list_paths}") # CopyResource, ResolveSubresource and CopyBufferRegion on a recording list (slots 17, 19 and 15). add_executable(startup_list_copy tests/startup_list_copy.cpp) @@ -1606,6 +1753,9 @@ add_test(NAME startup_slice_footprints COMMAND startup_slice_footprints_check) add_test(NAME startup_slice_footprints_padded_control COMMAND startup_slice_footprints_check --mutate padded-last-row) set_tests_properties(startup_slice_footprints_padded_control PROPERTIES WILL_FAIL TRUE) +# LOCAL (local/startup-v2, never pushed): trap-by-default desktop DLLs for startup imports without a +# public ABI yet (src/startup_stubs/trap.h), plus opt-in permissive paths for local startup runs. + find_program(DXC_EXECUTABLE dxc REQUIRED) foreach(stage mesh vertex pixel) if(stage STREQUAL mesh) @@ -1633,24 +1783,29 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$" warp "$" dual-trace-disabled) - set_tests_properties(startup_indirect_mesh_lease_warp_dual-trace-disabled PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + set_tests_properties(startup_indirect_mesh_lease_warp_dual-trace-disabled PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT_MODIFICATION "${x2w_upstream_list_paths}") foreach(backend IN ITEMS warp hardware) add_test(NAME startup_indirect_mesh_lease_${backend}_dual-trace COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$" ${backend} "$" dual-trace) - set_tests_properties(startup_indirect_mesh_lease_${backend}_dual-trace PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + set_tests_properties(startup_indirect_mesh_lease_${backend}_dual-trace PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT_MODIFICATION "${x2w_upstream_list_paths}") add_test(NAME startup_indirect_mesh_cache_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$" ${backend}) - set_tests_properties(startup_indirect_mesh_cache_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + # LOCAL merge: the slot-86 mesh stage cache runs only with X2W_UPSTREAM_MESH86_CACHE=1 here. + set_tests_properties(startup_indirect_mesh_cache_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT_MODIFICATION "${x2w_upstream_list_paths}") foreach(mode IN ITEMS ordered_control skip-wait dual dual-skip-srv dual-skip-argument dual-init-only loose-root) set(test_name startup_indirect_mesh_lease_${backend}_${mode}) add_test(NAME ${test_name} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$" ${backend} "$" ${mode}) - set_tests_properties(${test_name} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + set_tests_properties(${test_name} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT_MODIFICATION "${x2w_upstream_list_paths}") endforeach() endforeach() endif() @@ -1676,6 +1831,239 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_MESH86_FIXTURE_XMEM=$") endforeach() get_filename_component(DXC_BIN_DIR "${DXC_EXECUTABLE}" DIRECTORY) +find_program(STARTUP_FXC fxc HINTS "${DXC_BIN_DIR}") +find_program(STARTUP_POWERSHELL NAMES powershell pwsh REQUIRED) +if(STARTUP_FXC) + foreach(backend IN ITEMS warp hardware) + # LOCAL (textures): X2W_MEMORY_SRV_DETILE; surfaces at addrlib's addresses when gfx10_layout_check has addrlib. + add_test(NAME startup_memory_srv_detile_${backend} COMMAND "${STARTUP_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass + -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_memory_srv_detile.ps1" + "$" "${backend}" "${STARTUP_FXC}" "$") + set_tests_properties(startup_memory_srv_detile_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + add_test(NAME startup_rgba8_dmode_${backend} COMMAND "${STARTUP_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass + -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_rgba8_dmode.ps1" + "$" "${backend}" "${STARTUP_FXC}") + set_tests_properties(startup_rgba8_dmode_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() +endif() + +# LOCAL: ExecuteIndirect (list slot 61) with Dispatch arguments a compute writer stored in title memory. +# The local check, moved from tests/startup_indirect_dispatch.cpp at the upstream merge (upstream has its own). +set(startup_indirect_headers) +foreach(entry IN ITEMS Writer Counter) + string(TOLOWER "${entry}" entry_lower) + set(header "${CMAKE_CURRENT_BINARY_DIR}/startup_indirect_${entry_lower}.h") + add_custom_command(OUTPUT "${header}" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E ${entry} -Vn startup_indirect_${entry_lower} -Fh "${header}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_dispatch.hlsl" + DEPENDS tests/startup_indirect_dispatch.hlsl VERBATIM) + list(APPEND startup_indirect_headers "${header}") +endforeach() +add_executable(startup_indirect_dispatch_local tests/startup_indirect_dispatch_local.cpp ${startup_indirect_headers}) +target_include_directories(startup_indirect_dispatch_local PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") +target_compile_features(startup_indirect_dispatch_local PRIVATE cxx_std_17) +target_link_libraries(startup_indirect_dispatch_local PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + # wrap / wrap-legacy / wrap-cap (LOCAL memcut): the argument ring chain, its legacy control and its cap. + foreach(mode IN ITEMS gpu no-writer zero off huge huge-product wrap wrap-legacy wrap-cap) + add_test(NAME startup_indirect_dispatch_${mode}_${backend} COMMAND startup_indirect_dispatch_local ${backend} ${mode}) + set(indirect_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") + if(mode STREQUAL "off") + set(indirect_env "${indirect_env};X2W_INDIRECT_OFF=1") + endif() + set_tests_properties(startup_indirect_dispatch_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${indirect_env}") + endforeach() + # gpu mode with the read-back copies recorded (X2W_INDIRECT_READBACK) under the debug layer. + add_test(NAME startup_indirect_dispatch_gpu-readback_${backend} COMMAND startup_indirect_dispatch_local ${backend} gpu) + set_tests_properties(startup_indirect_dispatch_gpu-readback_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_INDIRECT_READBACK=8") + # LOCAL (scene): X2W_MESH_RECORD_TRACE in a traced frame (reset pass, raise pass, record at record / at end, writers); + # rectrace-off is the control without the switch (no such line). + foreach(mode IN ITEMS rectrace rectrace-off) + add_test(NAME startup_indirect_dispatch_${mode}_${backend} COMMAND startup_indirect_dispatch_local ${backend} ${mode}) + set(rectrace_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_D3D12_TRACE_ALL=1") + if(mode STREQUAL "rectrace") + set(rectrace_env "${rectrace_env};X2W_MESH_RECORD_TRACE=1") + endif() + set_tests_properties(startup_indirect_dispatch_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${rectrace_env}") + endforeach() +endforeach() + +# LOCAL meshrt: DispatchMesh ExecuteIndirect through a translated mesh pipeline (d3d12_mesh.inl, X2W_MESH=1). +set(startup_mesh_headers) +foreach(entry IN ITEMS "MeshMain;ms_6_5;ms" "MeshHeap;ms_6_5;heap_ms" "MeshDescword;ms_6_5;descword_ms" "PixelMain;ps_6_5;ps" "PixelSampler;ps_6_5;smp_ps" "PixelUint;ps_6_5;uint_ps" "PixelStore;ps_6_5;store_ps" "Writer;cs_6_0;writer") + list(GET entry 0 entry_name) + list(GET entry 1 entry_profile) + list(GET entry 2 entry_short) + set(header "${CMAKE_CURRENT_BINARY_DIR}/startup_mesh_${entry_short}.h") + add_custom_command(OUTPUT "${header}" + COMMAND "${DXC_EXECUTABLE}" -T ${entry_profile} -E ${entry_name} -Vn startup_mesh_${entry_short} -Fh "${header}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh_dispatch.hlsl" + DEPENDS tests/startup_mesh_dispatch.hlsl VERBATIM) + list(APPEND startup_mesh_headers "${header}") +endforeach() +add_executable(startup_mesh_dispatch tests/startup_mesh_dispatch.cpp ${startup_mesh_headers}) +target_include_directories(startup_mesh_dispatch PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") +target_compile_features(startup_mesh_dispatch PRIVATE cxx_std_17) +target_link_libraries(startup_mesh_dispatch PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS gpu derived zero huge off missing depth words16 words32 wordsraw fmaprecise fmabad notargets rtvuint smpheap smpheapswap + statez statezge statezoff statecull stateculloff statedepth statecullflip statecullnone statezrepeat statezuncleared statezlateclear async asyncone rtvvariant uavtex uavtexnoflag rtvnops wordsoob stateclip stateclipon stateclipkeep + descword descwordoff srvwide srvwidecopy srvwideshort) + add_test(NAME startup_mesh_dispatch_${mode}_${backend} COMMAND startup_mesh_dispatch ${backend} ${mode}) + set(mesh_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") + if(NOT mode STREQUAL "off") + set(mesh_env "${mesh_env};X2W_MESH=1") + endif() + set_tests_properties(startup_mesh_dispatch_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${mesh_env}") + endforeach() + # LOCAL meshrt: the same calls in a traced frame (x2w-frame mesh lines, targets noted for the read-back with + # snapshots); the runs above are the controls (no line, nothing noted). + # LOCAL (scene): rectrace / rectraceapart set X2W_MESH_RECORD_TRACE=1 themselves (d3d12_record_trace.inl images, + # heap reads, mesh reads against skipped dispatch ranges). + foreach(mode IN ITEMS statez notargets zero statecull stateculloff rectrace rectraceapart) + add_test(NAME startup_mesh_dispatch_trace_${mode}_${backend} COMMAND startup_mesh_dispatch ${backend} ${mode}) + set_tests_properties(startup_mesh_dispatch_trace_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_MESH=1;X2W_D3D12_TRACE_ALL=1;X2W_D3D12_TRACE_TARGETS=1") + endforeach() + # LOCAL meshrt: NOT traced. dump_*: X2W_MESH_DUMP_INPUTS lists the key (statez: dumped; zero: X = 0, not dumped). + # framestats_*: X2W_MESH_STATS_FRAMES=1 (gpu: the frame counts, one target-set line; zero: not counted). + foreach(mode IN ITEMS statez zero) + add_test(NAME startup_mesh_dispatch_dump_${mode}_${backend} COMMAND startup_mesh_dispatch ${backend} ${mode}) + set_tests_properties(startup_mesh_dispatch_dump_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_MESH=1;X2W_TEST_MESH_DUMP=1") + endforeach() + foreach(mode IN ITEMS gpu zero) + add_test(NAME startup_mesh_dispatch_framestats_${mode}_${backend} COMMAND startup_mesh_dispatch ${backend} ${mode}) + set_tests_properties(startup_mesh_dispatch_framestats_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_MESH=1;X2W_MESH_STATS_FRAMES=1") + # framestatsmulti_*: X2W_MESH_STATS_FRAMES=2 through presents only (23 frames, slot wrap, 20 frames not counted). + add_test(NAME startup_mesh_dispatch_framestatsmulti_${mode}_${backend} COMMAND startup_mesh_dispatch ${backend} ${mode}) + set_tests_properties(startup_mesh_dispatch_framestatsmulti_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_MESH=1;X2W_MESH_STATS_FRAMES=2;X2W_TEST_FS_MULTI=1") + endforeach() +endforeach() + +# LOCAL stall: device slot 133 without the allocation walk once the heap is open (X2W_PLACED_FAST; walk = control). +add_executable(startup_placed_fast tests/startup_placed_fast.cpp) +target_compile_features(startup_placed_fast PRIVATE cxx_std_17) +target_link_libraries(startup_placed_fast PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS fast walk) + add_test(NAME startup_placed_fast_${mode}_${backend} COMMAND startup_placed_fast ${backend} ${mode}) + set(placed_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1") + if(mode STREQUAL "fast") + set(placed_env "${placed_env};X2W_PLACED_FAST=1") + endif() + set_tests_properties(startup_placed_fast_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "${placed_env}") + endforeach() +endforeach() + +# LOCAL stall: probe_readable's unreadable-range cache (local_log.h, X2W_PROBE_CACHE; nocache = control). No GPU. +add_executable(startup_probe_cache tests/startup_probe_cache.cpp) +target_include_directories(startup_probe_cache PRIVATE src) +target_compile_features(startup_probe_cache PRIVATE cxx_std_17) +add_test(NAME startup_probe_cache_cache COMMAND startup_probe_cache cache) +set_tests_properties(startup_probe_cache_cache PROPERTIES TIMEOUT 60 ENVIRONMENT "X2W_PROBE_CACHE=1;X2W_PROBE_CACHE_MS=100") +add_test(NAME startup_probe_cache_query COMMAND startup_probe_cache query) +set_tests_properties(startup_probe_cache_query PROPERTIES ENVIRONMENT "X2W_PROBE_CACHE=1;X2W_PROBE_QUERY_FIRST=1") +add_test(NAME startup_probe_cache_lazy COMMAND startup_probe_cache lazy) +set_tests_properties(startup_probe_cache_lazy PROPERTIES ENVIRONMENT "X2W_PROBE_CACHE=1;X2W_PROBE_QUERY_FIRST=1;X2W_XMEM_LAZY_COMMIT=1") +add_test(NAME startup_probe_cache_nocache COMMAND startup_probe_cache nocache) +set_tests_properties(startup_probe_cache_nocache PROPERTIES TIMEOUT 60) + +# LOCAL stall: draw_lock hold / wait time by site (d3d12_draw.inl, X2W_DRAW_LOCK_TIMES; off = control). No GPU. +add_executable(startup_draw_lock_times tests/startup_draw_lock_times.cpp) +target_compile_features(startup_draw_lock_times PRIVATE cxx_std_17) +add_dependencies(startup_draw_lock_times d3d12_xs_shim) +foreach(mode IN ITEMS on off) + add_test(NAME startup_draw_lock_times_${mode} COMMAND startup_draw_lock_times ${mode}) + set(lock_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1") + if(mode STREQUAL "on") + set(lock_env "${lock_env};X2W_DRAW_LOCK_TIMES=1") + endif() + set_tests_properties(startup_draw_lock_times_${mode} PROPERTIES TIMEOUT 60 ENVIRONMENT "${lock_env}") +endforeach() + +# LOCAL stall: a translated slot-67 dispatch while its pipeline is held back (d3d12_compute.inl, X2W_CX_ASYNC). +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_async_cs.h" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E CountMain -Vn startup_cx_async_cs -Fh "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_async_cs.h" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_cx_async.hlsl" + DEPENDS tests/startup_cx_async.hlsl VERBATIM) +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_cs.h" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E HeapMain -Vn startup_cx_heap_cs -Fh "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_cs.h" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_cx_async.hlsl" + DEPENDS tests/startup_cx_async.hlsl VERBATIM) +# LOCAL: modes rawheap / rawheap-off, `heapraw 1` (d3d12_heap_raw.inl); the heap prelude the translator emits. +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_raw_cs.h" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_6 -E RawHeapMain -Vn startup_cx_heap_raw_cs -I "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs" + -Fh "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_raw_cs.h" "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_cx_heap_raw.hlsl" + DEPENDS tests/startup_cx_heap_raw.hlsl src/startup_stubs/heap_raw_prelude.hlsli VERBATIM) +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_bench_cs.h" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_6 -E RawBenchMain -Vn startup_cx_heap_bench_cs -I "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs" + -Fh "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_bench_cs.h" "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_cx_heap_raw.hlsl" + DEPENDS tests/startup_cx_heap_raw.hlsl src/startup_stubs/heap_raw_prelude.hlsli VERBATIM) +# LOCAL isa-gaps: mode heapwords, `heapwords 1` (heap descriptor words as numbers; the helper the translator emits). +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_words_cs.h" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_6 -E WordsMain -Vn startup_cx_heap_words_cs + -Fh "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_words_cs.h" "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_cx_heap_words.hlsl" + DEPENDS tests/startup_cx_heap_words.hlsl VERBATIM) +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_sampler_cs.h" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E SamplerMain -Vn startup_cx_sampler_cs -Fh "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_sampler_cs.h" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_cx_async.hlsl" + DEPENDS tests/startup_cx_async.hlsl VERBATIM) +add_executable(startup_cx_async tests/startup_cx_async.cpp "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_async_cs.h" + "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_cs.h" "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_sampler_cs.h" + "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_raw_cs.h" "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_bench_cs.h" + "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_words_cs.h") +target_include_directories(startup_cx_async PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") +target_compile_features(startup_cx_async PRIVATE cxx_std_17) +target_link_libraries(startup_cx_async PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS async sync known seen heap sampler rawheap rawheap-off rawheap-reset rawheap-late rawheap-bench slow slow-off heapwords heapwords-raw) + add_test(NAME startup_cx_async_${mode}_${backend} COMMAND startup_cx_async ${backend} ${mode}) + set(cx_async_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") + if(mode STREQUAL "async") + set(cx_async_env "${cx_async_env};X2W_CX_ASYNC=1") + elseif(mode STREQUAL "rawheap-bench") + set(cx_async_env "${cx_async_env};X2W_HEAP_RAW_CHECK=1") + elseif(mode STREQUAL "known" OR mode STREQUAL "seen") + set(cx_async_env "${cx_async_env};X2W_CX_ASYNC=1;X2W_CX_PREWARM_ALL=1") + elseif(mode STREQUAL "slow") + set(cx_async_env "${cx_async_env};X2W_CX_ASYNC=1;X2W_CX_PREWARM_ALL=1;X2W_CX_PREWARM_THREADS=1;X2W_CX_SLOW_LOG_MS=500;X2W_CX_SLOW_MS=1500") + elseif(mode STREQUAL "slow-off") + set(cx_async_env "${cx_async_env};X2W_CX_ASYNC=1;X2W_CX_PREWARM_ALL=1;X2W_CX_PREWARM_THREADS=1;X2W_CX_SLOW_LOG_MS=500;X2W_CX_SLOW_MS=100000;X2W_CX_DEMAND_LANE=0") + endif() + set_tests_properties(startup_cx_async_${mode}_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77 + ENVIRONMENT "${cx_async_env}") + endforeach() +endforeach() + +add_executable(startup_cx_pso_time tests/startup_cx_pso_time.cpp) +target_compile_features(startup_cx_pso_time PRIVATE cxx_std_17) +target_link_libraries(startup_cx_pso_time PRIVATE d3d12_xs_shim d3d12 dxgi) + +# LOCAL indirect: reserved-buffer tiles onto CreateHeap heaps (exact) and onto opened file-mapping heaps (refused by +# the runtime, device removed: the X2W_RANGE_ALIAS gate in d3d12_range_alias.inl relies on it). +add_executable(tile_mapping_shared_heap_check tests/tile_mapping_shared_heap_check.cpp) +target_compile_features(tile_mapping_shared_heap_check PRIVATE cxx_std_17) +target_link_libraries(tile_mapping_shared_heap_check PRIVATE d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS plain shared) + add_test(NAME tile_mapping_${mode}_heap_${backend} COMMAND tile_mapping_shared_heap_check ${backend} ${mode}) + add_test(NAME tile_mapping_${mode}_heap_nodebug_${backend} COMMAND tile_mapping_shared_heap_check ${backend} ${mode} nodebug) + set_tests_properties(tile_mapping_${mode}_heap_${backend} tile_mapping_${mode}_heap_nodebug_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() +endforeach() + +# Which uses of a section_va chunk window (a buffer on a heap opened over a pagefile file mapping) the runtime takes. +add_executable(section_window_ops_check tests/section_window_ops_check.cpp) +target_compile_features(section_window_ops_check PRIVATE cxx_std_17) +target_link_libraries(section_window_ops_check PRIVATE d3d12 dxgi d3dcompiler) + target_compile_definitions(root_probe PRIVATE SDK_DXC_DIR=L"${DXC_BIN_DIR}/") add_executable(offscreen_check tests/offscreen_check.cpp tests/compute_check.cpp tests/dxr_check.cpp tests/buffer_ops.cpp tests/descriptor_heap_paging.cpp) @@ -1722,14 +2110,14 @@ set(OFFSCREEN_AGILITY_620_DIR "" CACHE PATH "Agility SDK 1.620.2 x64 DLL directo # With OFFSCREEN_AGILITY_620_DIR the fixture compiles against the Agility headers instead: it keeps its # own copy below and the provider keeps its own. d3d12_xs_shim uses the static CRT and is not shared. if(NOT OFFSCREEN_AGILITY_620_DIR) - add_library(d3d12_xs_device_obj OBJECT src/startup_stubs/d3d12_xs_device.cpp) + add_library(d3d12_xs_device_obj OBJECT src/startup_stubs/d3d12_xs_device.cpp ${X2W_GPU_SOURCES}) target_include_directories(d3d12_xs_device_obj PRIVATE src) target_compile_features(d3d12_xs_device_obj PRIVATE cxx_std_17) target_sources(offscreen_check PRIVATE $) else() - target_sources(offscreen_check PRIVATE src/startup_stubs/d3d12_xs_device.cpp) + target_sources(offscreen_check PRIVATE src/startup_stubs/d3d12_xs_device.cpp ${X2W_GPU_SOURCES}) endif() -target_link_libraries(offscreen_check PRIVATE d3d12 dxgi dxguid d3dcompiler user32 gdi32 x2w_build_rev) +target_link_libraries(offscreen_check PRIVATE d3d12 dxgi dxguid d3dcompiler user32 gdi32 dcomp x2w_build_rev) target_include_directories(offscreen_check PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") if(OFFSCREEN_AGILITY_620_DIR) if(EXISTS "${OFFSCREEN_AGILITY_620_DIR}/sdk.nupkg") @@ -1923,6 +2311,16 @@ add_executable(startup_sampler_comparison_check tests/startup_sampler_comparison target_include_directories(startup_sampler_comparison_check PRIVATE src) target_compile_features(startup_sampler_comparison_check PRIVATE cxx_std_17) add_test(NAME startup_sampler_comparison COMMAND startup_sampler_comparison_check) +# LOCAL: console view facts for translated compute programs (src/startup_stubs/gfx10_view_words.h): typed buffer +# view layout, GFX10_FORMAT codes, synthesized V#/T# words, integer UAV format. Mutated runs are negative controls. +add_executable(startup_gfx10_view_words_check tests/startup_gfx10_view_words_check.cpp) +target_include_directories(startup_gfx10_view_words_check PRIVATE src) +target_compile_features(startup_gfx10_view_words_check PRIVATE cxx_std_17) +add_test(NAME startup_gfx10_view_words COMMAND startup_gfx10_view_words_check) +foreach(mutation IN ITEMS legacy width order uint) + add_test(NAME startup_gfx10_view_words_${mutation}_control COMMAND startup_gfx10_view_words_check --mutate ${mutation}) + set_tests_properties(startup_gfx10_view_words_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() # Diagnostic line for a refused device slot 70 call (src/startup_stubs/memory_srv_report.h). add_executable(startup_memory_srv_report_check tests/startup_memory_srv_report_check.cpp) target_include_directories(startup_memory_srv_report_check PRIVATE src) @@ -2108,6 +2506,18 @@ target_compile_features(startup_depth_state_check PRIVATE cxx_std_17) add_test(NAME startup_depth_state COMMAND startup_depth_state_check) add_test(NAME startup_depth_state_switch_control COMMAND startup_depth_state_check --mutate switch) set_tests_properties(startup_depth_state_switch_control PROPERTIES WILL_FAIL TRUE) +# LOCAL: the local decoder check (moved from tests/startup_pipeline_state_check.cpp at the upstream merge). +# Fixed-function state of slot 57 / 55 pipelines (src/startup_stubs/pipeline_state_decode.h): depth-stencil, +# rasterizer and blend write masks from hand-built register words, both state block layouts, derived +# records, depth-target adjustments and the X2W_DRAW_STATE_* switches. The mutated runs (front-face +# convention inverted, mesh fields unshifted) are the negative controls. +add_executable(startup_pipeline_state_local_check tests/startup_pipeline_state_local_check.cpp) +target_include_directories(startup_pipeline_state_local_check PRIVATE src) +target_compile_features(startup_pipeline_state_local_check PRIVATE cxx_std_17) +add_test(NAME startup_pipeline_state_local COMMAND startup_pipeline_state_local_check) +add_test(NAME startup_pipeline_state_local_winding_control COMMAND startup_pipeline_state_local_check --mutate winding) +add_test(NAME startup_pipeline_state_local_mesh_shift_control COMMAND startup_pipeline_state_local_check --mutate mesh-shift) +set_tests_properties(startup_pipeline_state_local_winding_control startup_pipeline_state_local_mesh_shift_control PROPERTIES WILL_FAIL TRUE) # Root table handles resolved against a logical view heap, and the records a translated draw reads # from the window (src/startup_stubs/logical_view_table.h). add_executable(startup_logical_view_table_check tests/startup_logical_view_table_check.cpp) @@ -2125,6 +2535,8 @@ add_executable(startup_local_log_check tests/startup_local_log_check.cpp) target_include_directories(startup_local_log_check PRIVATE src) target_compile_features(startup_local_log_check PRIVATE cxx_std_17) add_test(NAME startup_local_log COMMAND startup_local_log_check) +add_test(NAME startup_local_log_query_first COMMAND startup_local_log_check --probe-only) +set_tests_properties(startup_local_log_query_first PROPERTIES ENVIRONMENT "X2W_PROBE_QUERY_FIRST=1") add_test(NAME startup_local_log_guard_drop_control COMMAND startup_local_log_check --mutate guard-drop) set_tests_properties(startup_local_log_guard_drop_control PROPERTIES WILL_FAIL TRUE) add_test(NAME startup_local_log_reopen_control COMMAND startup_local_log_check --mutate reopen) @@ -2704,6 +3116,31 @@ if(XBOX2WINDOWS_ADDRLIB_DIR) else() message(STATUS "xg_swizzle_select: addrlib not configured, the test will skip (77)") endif() +# LOCAL (textures): the GFX10 layout of console-swizzled memory views (src/startup_stubs/gfx10_layout.h). The golden +# check runs in every build (addrlib-recorded hashes); the addrlib check compares every element address with addrlib +# itself and skips (77) without it. The two mutated runs are the negative controls. +add_executable(gfx10_layout_check tests/gfx10_layout_check.cpp) +target_compile_features(gfx10_layout_check PRIVATE cxx_std_17) +target_include_directories(gfx10_layout_check PRIVATE src) +if(XBOX2WINDOWS_ADDRLIB_DIR) + target_link_libraries(gfx10_layout_check PRIVATE xbw_addrlib) + target_compile_definitions(gfx10_layout_check PRIVATE XBOX2WINDOWS_HAVE_ADDRLIB) +endif() +set(_gfx10_golden "${CMAKE_CURRENT_SOURCE_DIR}/tests/gfx10_layout_golden.txt") +add_test(NAME gfx10_layout_golden COMMAND gfx10_layout_check "${_gfx10_golden}") +add_test(NAME gfx10_layout_floor_control COMMAND gfx10_layout_check "${_gfx10_golden}" --mutate floor) +add_test(NAME gfx10_layout_tail_control COMMAND gfx10_layout_check "${_gfx10_golden}" --mutate tail) +set_tests_properties(gfx10_layout_floor_control gfx10_layout_tail_control PROPERTIES WILL_FAIL TRUE) +add_test(NAME gfx10_layout_addrlib COMMAND gfx10_layout_check --addrlib) +set_tests_properties(gfx10_layout_addrlib PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) +# LOCAL (textures): the address index of memory buffer lookups (src/startup_stubs/buffer_address_index.h) against a +# brute-force walk; the mutated window is the negative control. +add_executable(buffer_address_index_check tests/buffer_address_index_check.cpp) +target_compile_features(buffer_address_index_check PRIVATE cxx_std_17) +target_include_directories(buffer_address_index_check PRIVATE src) +add_test(NAME buffer_address_index COMMAND buffer_address_index_check) +add_test(NAME buffer_address_index_control COMMAND buffer_address_index_check --mutate) +set_tests_properties(buffer_address_index_control PROPERTIES WILL_FAIL TRUE) add_test(NAME xg_bc64_tiling_reference COMMAND xg_swizzle_select_check --bc64-tiling) set_tests_properties(xg_bc64_tiling_reference PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) # 4 KiB allocation answers for small 2D textures (src/startup_stubs/small_texture_4k.h): literal sizes and @@ -2912,6 +3349,13 @@ foreach(adapter IN ITEMS hardware warp) PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) set_tests_properties(startup_sampler_x_swapped_${adapter} PROPERTIES FAIL_REGULAR_EXPRESSION "startup_sampler_x swapped=0") + # LOCAL (textures): the same probes with the samplers translated from S# words (the X2W_SAMPLER_LOD fields); the + # control drops the LOD and border fields and must mismatch. + add_test(NAME startup_sampler_lod_words_${adapter} COMMAND offscreen_check ${adapter} --startup-sampler-x-words) + add_test(NAME startup_sampler_lod_words_dropped_${adapter} COMMAND offscreen_check ${adapter} --startup-sampler-x-words-dropped) + set_tests_properties(startup_sampler_lod_words_${adapter} startup_sampler_lod_words_dropped_${adapter} + PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) + set_tests_properties(startup_sampler_lod_words_dropped_${adapter} PROPERTIES WILL_FAIL TRUE) # The dropped control resets the decoded LOD limits and must read the wrong mip for both entries. add_test(NAME startup_sampler_lod_${adapter} COMMAND offscreen_check ${adapter} --startup-sampler-lod) add_test(NAME startup_sampler_lod_dropped_${adapter} COMMAND offscreen_check ${adapter} --startup-sampler-lod-dropped) @@ -3073,6 +3517,12 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_buffer_atomics_check.py") add_test(NAME startup_image_sample_c COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_c_check.py") + # Pixel-stage lowerings of mesh pairs (gfx2hlsl): translation checks with negative controls. + foreach(check IN ITEMS scalar_pack_hh quad_dpp spi_input mesh_spi_input image_sample_b image_sample_d interp_f16 round_mode front_face quad_divergent scalar_const_fold sample_c_preclamp sample_c_border vopc_dpp image_get_lod) + add_test(NAME startup_${check} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_${check}_check.py") + set_tests_properties(startup_${check} PROPERTIES TIMEOUT 120) + endforeach() add_test(NAME startup_image_gather_c_lz COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_gather_c_lz_check.py") # image_sample_b (#1996): translation controls, then a desktop draw whose mip level the bias selects. @@ -3130,6 +3580,30 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_gfx2hlsl_watch COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_watch_check.py") set_tests_properties(startup_gfx2hlsl_watch PROPERTIES TIMEOUT 120) + # v_ldexp_f32 through x2w_ldexp (f32 denormals flushed), against an exact reference. + add_test(NAME startup_gfx2hlsl_ldexp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_ldexp_check.py") + add_test(NAME startup_gfx2hlsl_shift64_literal COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_shift64_literal_check.py") + # X2W_DRAW_FEATURES=mixfma: v_fma_mix_f32 through x2w_fma_exact (x2w_mad_precise for a signed-zero addend). + add_test(NAME startup_gfx2hlsl_mix_fma COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_mix_fma_check.py") + # X2W_PS_WAVE_UNION=1: wave64 reduction chains over the host wave (translation controls; the draw mode needs a + # two-target dump tool and is run by hand). + add_test(NAME startup_gfx2hlsl_wave_union COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_wave_union_check.py") + add_test(NAME startup_gfx2hlsl_scalar_named_dest COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_named_dest_check.py") + add_test(NAME startup_gfx2hlsl_f16_arith COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_f16_arith_check.py") + add_test(NAME startup_image_sample_implicit_lod COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_implicit_lod_check.py") + # Draw-stage conflict registers fixed by the exec bit, back-edge loop heads and vcc descriptor copies. + add_test(NAME startup_gfx2hlsl_exec_lane_facts COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_exec_lane_facts_check.py") + # Draw-stage x2w_fma_exact keeps fxc double immediates out (device-free part). + add_test(NAME startup_fma_exact_fxc COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_fma_exact_fxc_check.py") add_test(NAME startup_gfx2hlsl_handler_arity COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_handler_arity_check.py") # gfx2hlsl names why s_getpc_b64 is refused instead of reporting the mnemonic alone. @@ -3142,6 +3616,19 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl lowers v_fma_mix_f32 and selects binary16 source halves on all three mixed-precision FMAs. add_test(NAME startup_gfx2hlsl_fma_mix COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_fma_mix_check.py") + # The mesh-stage translator checks (tools/startup/mesh2hlsl.py): hand-assembled gfx1013 NGG programs, each + # with its negative controls; pure Python, no arguments (the optional --write keeps the programs). + file(GLOB startup_mesh_python_checks CONFIGURE_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh_*_check.py") + foreach(check ${startup_mesh_python_checks}) + get_filename_component(check_name "${check}" NAME_WE) + string(REGEX REPLACE "_check$" "" check_name "${check_name}") + # (startup_mesh_spi_input is registered with the pixel-stage lowerings above) + if(NOT TEST ${check_name}) + add_test(NAME ${check_name} COMMAND "${INTAKE_PYTHON}" -B "${check}") + set_tests_properties(${check_name} PROPERTIES TIMEOUT 300) + endif() + endforeach() # VOP1/VOP2 sub-dword addressing (SDWA) in the translator (#1141), checked against the pixel AOT # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B @@ -3243,7 +3730,7 @@ if(EXISTS "${INTAKE_PYTHON}") endforeach() # gfx2hlsl run-time sampler heap indexing (#1143): translation controls, then a desktop draw with # DXC ps_6_0 and, when the Windows SDK's FXC is found, the ps_5_1 the startup tools compile with. - find_program(STARTUP_FXC fxc HINTS "${DXC_BIN_DIR}") + if(STARTUP_FXC) # The v_fma_mix* translations from startup_gfx2hlsl_fma_mix, compiled for ps_5_1. add_test(NAME startup_gfx2hlsl_fma_mix_fxc COMMAND "${INTAKE_PYTHON}" -B @@ -3487,6 +3974,21 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_flat_param_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_flat_param_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + # binary16 interpolation (v_interp_p2_f16) on the same one-pixel renderer + add_test(NAME startup_interp_f16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_interp_f16_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_interp_f16_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + # s_round_mode 0xc: binary16 results rounded toward zero, on the same renderer + add_test(NAME startup_round_mode_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_round_mode_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_round_mode_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + # FRONT_FACE as SV_IsFrontFace (+1.0 / -1.0), on the same renderer + add_test(NAME startup_front_face_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_front_face_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_front_face_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME raster_winding_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/raster_winding_reference.py" "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -3803,7 +4305,10 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_launch_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_launch_cli_check.py") set_tests_properties(startup_launch_cli_check PROPERTIES TIMEOUT 30) - find_program(STARTUP_POWERSHELL NAMES powershell pwsh REQUIRED) + + add_test(NAME startup_profile COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_profile_check.py" "$") + set_tests_properties(startup_profile PROPERTIES TIMEOUT 120) add_test(NAME startup_stage_package COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stage_package_check.py" "${STARTUP_POWERSHELL}") set_tests_properties(startup_stage_package PROPERTIES TIMEOUT 120) @@ -3827,7 +4332,9 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_compute_binding_trace_warp COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_binding_trace_check.py" "$") - set_tests_properties(startup_compute_binding_trace_warp PROPERTIES TIMEOUT 30) + # LOCAL merge: upstream test of its compute root and upload-page paths (switched here). + set_tests_properties(startup_compute_binding_trace_warp PROPERTIES TIMEOUT 30 + ENVIRONMENT "X2W_UPSTREAM_COMPUTE_ROOT=1;X2W_LIST_UPLOAD_PAGES=1") add_test(NAME startup_compute_request_warp COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_request_check.py" "$") add_test(NAME startup_compute_request_disabled_control COMMAND "${INTAKE_PYTHON}" -B @@ -3859,6 +4366,20 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_draw_check.py" "$" "${backend}") set_tests_properties(startup_stream_draw_${backend} PROPERTIES TIMEOUT 90) + # LOCAL stall: a draw while its desktop pipeline compile is held back (X2W_DRAW_ASYNC; sync = control) + foreach(mode IN ITEMS async sync) + add_test(NAME startup_draw_async_${mode}_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_async_check.py" + "$" "${backend}" "${mode}") + set_tests_properties(startup_draw_async_${mode}_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() + # LOCAL stall: two threads draw with a buffer srv at once (X2W_DRAW_LOCK_SPLIT; locked = control) + foreach(mode IN ITEMS split copy below locked) + add_test(NAME startup_draw_lock_split_${mode}_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_lock_split_check.py" + "$" "${backend}" "${mode}") + set_tests_properties(startup_draw_lock_split_${mode}_${backend} PROPERTIES TIMEOUT 150 SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_stream_viewport_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_viewport_check.py" "$" "${backend}") @@ -3866,15 +4387,34 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_stream_fetch_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_fetch_check.py" "$" "${backend}") - set_tests_properties(startup_stream_fetch_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + set_tests_properties(startup_stream_fetch_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_UPSTREAM_STREAM_LAYOUT=1") add_test(NAME startup_stream_interface_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_interface_check.py" "$" "${backend}") set_tests_properties(startup_stream_interface_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_stream_pc_table_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_pc_table_check.py" + "$" "${backend}") + set_tests_properties(startup_stream_pc_table_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_stream_ps_inputs_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_ps_inputs_check.py" + "$" "${backend}") + set_tests_properties(startup_stream_ps_inputs_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_draw_dump_inputs_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_dump_inputs_check.py" + "$" "${backend}") + set_tests_properties(startup_draw_dump_inputs_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_stream_depth_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_depth_check.py" "$" "${backend}") - set_tests_properties(startup_stream_depth_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + # LOCAL merge: list slot 24 (OMSetStencilRef) is installed here only on request (X2W_UPSTREAM_STENCIL_REF). + set_tests_properties(startup_stream_depth_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_UPSTREAM_STENCIL_REF=1") + add_test(NAME startup_draw_state_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_state_check.py" + "$" "${backend}") + set_tests_properties(startup_draw_state_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_stream_rasterizer_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" "$" "${backend}") @@ -3928,6 +4468,12 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_requests_check.py" "$" "${backend}") set_tests_properties(startup_indirect_requests_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + if(backend STREQUAL "warp") + add_test(NAME startup_draw_srv_limit_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_srv_limit_check.py" + "$" "${STARTUP_FXC}") + set_tests_properties(startup_draw_srv_limit_warp PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endif() add_test(NAME startup_formatted_view_draw_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_formatted_view_draw_check.py" "$" "${backend}" "${STARTUP_FXC}") @@ -3948,14 +4494,25 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_root_cbv_check.py" "$" ${backend}) set_tests_properties(startup_root_cbv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + # LOCAL stall: X2W_ROOT_SRV_LAZY (list slot 44 copies nothing at record time; control without the switch) + add_test(NAME startup_root_srv_lazy_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_root_srv_lazy_check.py" + "$" ${backend}) + set_tests_properties(startup_root_srv_lazy_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_root_heap_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_root_heap_check.py" "$" ${backend}) - set_tests_properties(startup_root_heap_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + # LOCAL merge: upstream's deferred descriptor-heap root arguments run with X2W_DEFER_HEAP_ROOTS=1 here. + set_tests_properties(startup_root_heap_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_DEFER_HEAP_ROOTS=1") add_test(NAME startup_address_srv_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_srv_check.py" "$" "${backend}") set_tests_properties(startup_address_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_memory_srv_announced_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_memory_srv_announced_check.py" + "$" "${backend}") + set_tests_properties(startup_memory_srv_announced_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) if(backend STREQUAL "warp") # Negative control for X2W_RESOURCE_INDEX_CHECK: mode 2 skips the index inserts, so the check must # report the first live resource it does not find (the run passes only on that report). @@ -3981,7 +4538,9 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_address_single_element_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_single_element_srv_check.py" "$" "${backend}") - set_tests_properties(startup_address_single_element_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + # LOCAL merge: upstream's single-element and console-layout memory SRVs run with X2W_UPSTREAM_CONSOLE_SRV=1. + set_tests_properties(startup_address_single_element_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_UPSTREAM_CONSOLE_SRV=1") add_test(NAME startup_address_buffer_srv_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_buffer_srv_check.py" "$" "${backend}") @@ -4002,6 +4561,19 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_frame_copy_check.py" "$" ${backend}) set_tests_properties(startup_frame_copy_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_draw_uav_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_uav_check.py" + "$" "${backend}") + set_tests_properties(startup_draw_uav_${backend} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + # LOCAL (textures): X2W_HEAP_TEXTURE_UPLOAD; heap draws need 32-byte view slots (77 elsewhere, e.g. WARP). + add_test(NAME startup_heap_texture_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_heap_texture_check.py" + "$" "${backend}" "$") + set_tests_properties(startup_heap_texture_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_buffer_heap_index_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_buffer_heap_index_check.py" + "$" "${backend}") + set_tests_properties(startup_buffer_heap_index_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_placed_vertex_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_placed_vertex_check.py" "$" "${backend}") @@ -4013,7 +4585,8 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_address_console_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_console_check.py" "$" "${backend}") - set_tests_properties(startup_address_console_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + set_tests_properties(startup_address_console_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_UPSTREAM_CONSOLE_SRV=1") # 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) @@ -4021,7 +4594,13 @@ if(EXISTS "${INTAKE_PYTHON}") 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" "$" "${backend}" "${gate}") - set_tests_properties(startup_address_console_${gate_name}_${backend} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + set_tests_properties(startup_address_console_${gate_name}_${backend} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_UPSTREAM_CONSOLE_SRV=1") + # LOCAL merge: the local upload ring (d3d12_upload_ring.inl, X2W_UPLOAD_RING=chain default) never reuses + # unexecuted space, so the ring control needs the old wrapping 256 MiB ring it was written against. + if(gate STREQUAL "gate-ring") + set_tests_properties(startup_address_console_${gate_name}_${backend} PROPERTIES ENVIRONMENT "X2W_UPSTREAM_CONSOLE_SRV=1;X2W_UPLOAD_RING=legacy") + endif() endforeach() add_test(NAME startup_xg_bc_chain_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_xg_bc_chain_check.py" @@ -4041,6 +4620,33 @@ if(EXISTS "${INTAKE_PYTHON}") # Stream stage interface by semantic: the translator-only cases (draws: startup_stream_interface_). add_test(NAME startup_stream_interface_translate COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_interface_check.py") + # A stream vertex shader with data after its single reachable exit (a PC-relative table) is bounded there. + add_test(NAME startup_stream_vertex_exit COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_vertex_exit_check.py") + # The s_getpc_b64 table pointer of such a shader: the translator-only cases (draws: startup_stream_pc_table_). + add_test(NAME startup_stream_pc_table_translate COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_pc_table_check.py") + # Resource-heap descriptors at a run-time offset in a vertex stage (X2W_DRAW_FEATURES=heap), CPU reference. + add_test(NAME startup_vs_heap COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_vs_heap_check.py") + # A stream pixel stage's SPI input layout from its FSSM header: the translator-only cases. + add_test(NAME startup_stream_ps_inputs_translate COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_ps_inputs_check.py") + # Startup shader translator: vertex-stage entry v3 as SV_InstanceID; entry v1 / v2 refused. + add_test(NAME startup_vs_instance_id COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_vs_instance_id_check.py") + # Startup shader translator: a draw stage's numeric read of a table descriptor word (X2W_DRAW_FEATURES=descword). + add_test(NAME startup_gfx2hlsl_draw_descword COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_draw_descword_check.py") + # Startup shader translator: a draw stage's scalar arithmetic over table descriptor words (descword). + add_test(NAME startup_gfx2hlsl_draw_descnum COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_draw_descnum_check.py") + # Startup shader translator: the SCC carry chain of s_add_u32 / s_addc_u32 and s_sub_u32 / s_subb_u32. + add_test(NAME startup_gfx2hlsl_scc_carry COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_scc_carry_check.py") + # Startup shader translator: waterfall loops (wave32/wave64, scc1 or execnz back edge) and s_nor_b32 of masks. + add_test(NAME startup_waterfall COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_waterfall_check.py") # Startup shader translator: descriptor offsets inside wide scalar loads (no game data). add_test(NAME startup_translator COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_translator_check.py") @@ -4088,8 +4694,10 @@ if(EXISTS "${INTAKE_PYTHON}") # Offline re-key of saved shader requests under the current cache revision (pure Python). add_test(NAME startup_shader_cache_rekey COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_shader_cache_rekey_check.py") + set_tests_properties(startup_shader_cache_rekey PROPERTIES ENVIRONMENT "X2W_UPSTREAM_SHADER_CACHE_REKEY=1") add_test(NAME runtime_shader_cache_rekey_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_shader_cache_rekey_cli_check.py") + set_tests_properties(runtime_shader_cache_rekey_cli_check PROPERTIES ENVIRONMENT "X2W_UPSTREAM_SHADER_CACHE_REKEY=1") # Partial colour exports carry their channel mask to the manifest; compressed exports of whole pairs lower (#1674). add_test(NAME startup_gfx2hlsl_export_mask COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_export_mask_check.py") @@ -7958,7 +8566,7 @@ if(EXISTS "${INTAKE_PYTHON}") if(TARGET d3d12_xs_device_obj) target_sources(cpu_placed_dxr_provider PRIVATE $) else() - target_sources(cpu_placed_dxr_provider PRIVATE src/startup_stubs/d3d12_xs_device.cpp) + target_sources(cpu_placed_dxr_provider PRIVATE src/startup_stubs/d3d12_xs_device.cpp ${X2W_GPU_SOURCES}) endif() target_include_directories(cpu_placed_dxr_provider PRIVATE tests src "${CMAKE_CURRENT_BINARY_DIR}") target_link_libraries(cpu_placed_dxr_provider PRIVATE d3d12 dxgi dxguid d3dcompiler user32 gdi32 x2w_build_rev) @@ -10216,3 +10824,232 @@ foreach(i RANGE 0 ${X2W_SLOW_TEST_COSTS_LAST} 2) set_tests_properties(${slow_name} PROPERTIES COST ${slow_cost}) endif() endforeach() + +# ---- x2w_shader: C++ port of the upstream Rust shader crate (namespace x2w::vs) ---- +# vs-core: lib, dxbc, dxil, ir, gfx10 decoder. The other port packages add their sources with +# target_sources(x2w_shader PRIVATE ...) in blocks of their own below. +add_library(x2w_shader STATIC + src/x2w_shader/lib.cpp + src/x2w_shader/dxbc.cpp + src/x2w_shader/dxil.cpp + src/x2w_shader/ir.cpp + src/x2w_shader/gfx10/mod.cpp + src/x2w_shader/gfx10/fields.cpp + src/x2w_shader/gfx10/opcodes.cpp + src/x2w_shader/gfx10/sp3.cpp) +target_include_directories(x2w_shader PUBLIC src) +target_compile_features(x2w_shader PUBLIC cxx_std_20) + +# Unit tests ported from the #[cfg(test)] blocks of those modules, one ctest per Rust test. +add_executable(x2w_shader_core_tests tests/x2w_shader/core_tests.cpp) +target_link_libraries(x2w_shader_core_tests PRIVATE x2w_shader) +foreach(x2w_vs_core_test IN ITEMS + dxbc_round_trips_parts dxbc_rejects_bad_input + dxil_parses_standard_layout dxil_detects_xbox_layout dxil_rejects_missing_bitcode_magic + gfx10_flat_offsets_ignore_bit_eleven gfx10_tables_are_sorted gfx10_lengths_and_names + gfx10_follows_branches_and_skips_data gfx10_follows_far_jumps gfx10_follows_far_jumps_backward + gfx10_rejects_bad_code opcodes_s_ttracedata_imm_is_sopp_0x28 + sp3_scalar sp3_atc_probe_immediate_is_not_a_register sp3_lane_masks_follow_the_wave_size + sp3_vector_modifiers sp3_memory_and_export sp3_one_sided_packed_negation_is_printed + sp3_fields_the_instruction_lacks_are_not_printed sp3_image_d16_data_is_packed + ir_a_skip_is_left_out_when_the_scalars_it_changes_come_back_or_are_not_read + ir_joins_get_phis_only_where_values_differ ir_in_place_scalar_ops_read_their_destination + ir_loops_carry_values_through_phis ir_drops_scheduling_and_follows_far_jumps + ir_reports_what_it_cannot_express ir_relative_vgpr_access_spans_up_to_the_vgpr_count + ir_reverse_order_diamond_chain_eliminates_trivial_phis + ir_remove_trivial_phis_compresses_reverse_chain_in_bounded_steps + ir_non_trivial_phis_preserve_compressed_representatives) + add_test(NAME x2w_shader_core_${x2w_vs_core_test} COMMAND x2w_shader_core_tests ${x2w_vs_core_test}) +endforeach() + +# vs-front: native, io, resource, spill, structure, bvh (src/x2w_shader/front/CMakeLists.txt builds +# them standalone too). +target_sources(x2w_shader PRIVATE + src/x2w_shader/bvh.cpp + src/x2w_shader/native.cpp + src/x2w_shader/structure.cpp + src/x2w_shader/spill.cpp + src/x2w_shader/io.cpp + src/x2w_shader/resource.cpp) +foreach(x2w_vs_front_test IN ITEMS vs_bvh_test vs_native_test vs_structure_test vs_spill_test vs_io_test + vs_resource_test) + add_executable(x2w_${x2w_vs_front_test} tests/x2w_shader/${x2w_vs_front_test}.cpp) + target_link_libraries(x2w_${x2w_vs_front_test} PRIVATE x2w_shader) + target_include_directories(x2w_${x2w_vs_front_test} PRIVATE tests/x2w_shader) + add_test(NAME x2w_${x2w_vs_front_test} COMMAND x2w_${x2w_vs_front_test}) +endforeach() + +# Real-program check: every native program of an archive decoded and built into SSA, compared hash +# for hash with the upstream Rust implementation (reference lines from a helper outside the repo). Skipped +# (77) unless X2W_VS_CORE_ARCHIVE and X2W_VS_CORE_REFERENCE are set: a sweep takes the machine lock. +add_executable(x2w_shader_archive_decode_check tests/x2w_shader/archive_decode_check.cpp) +target_link_libraries(x2w_shader_archive_decode_check PRIVATE x2w_shader) +add_test(NAME x2w_shader_core_archive_decode COMMAND x2w_shader_archive_decode_check) +set_tests_properties(x2w_shader_core_archive_decode PROPERTIES SKIP_RETURN_CODE 77) + +# vs-emit: the DXIL writer and the translator's entry points (src/x2w_shader/emit, port of the upstream Rust emit/ module; vs-lower's +# lowering is a fragment of it), their ctests, and `x2w shaders --out ` (tools/x2w), X2W's own shader +# dump. src/x2w_shader/emit/CMakeLists.txt also builds standalone. +add_subdirectory(src/x2w_shader/emit ${CMAKE_BINARY_DIR}/x2w_shader_emit) +# LOCAL (vexport): X2W's shader database (src/shader_db): the reader the runtime maps, its writer, the archive +# scan and x2w_shaders, the shader dump tool and its --compare option for a reference export. +add_library(x2w_shader_db STATIC + src/shader_db/shader_db.cpp src/shader_db/shader_db_writer.cpp src/shader_db/archive_scan.cpp + src/shader_db/gpu_export.cpp) +target_compile_features(x2w_shader_db PUBLIC cxx_std_17) +target_include_directories(x2w_shader_db PUBLIC src src/shader_db) +target_link_libraries(x2w_shader_db PUBLIC x2w_blake3) +# The static CRT, as x2w_blake3 and the shim (which compiles shader_db.cpp itself, through X2W_GPU_SOURCES). +set_target_properties(x2w_shader_db PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +if(TARGET x2w_shader AND EXISTS "${CMAKE_SOURCE_DIR}/src/shader_db/x2w_shaders_vs.cpp") + add_executable(x2w_shaders src/shader_db/x2w_shaders.cpp src/shader_db/x2w_shaders_vs.cpp) + target_link_libraries(x2w_shaders PRIVATE x2w_shader_db x2w_shader) +else() + add_executable(x2w_shaders src/shader_db/x2w_shaders.cpp src/shader_db/x2w_shaders_no_translator.cpp) + target_link_libraries(x2w_shaders PRIVATE x2w_shader_db) +endif() +target_compile_definitions(x2w_shaders PRIVATE SDK_DXC_DIR=L"${DXC_BIN_DIR}/" UNICODE _UNICODE) +add_executable(shader_db_check tests/shader_db_check.cpp) +target_link_libraries(shader_db_check PRIVATE x2w_shader_db) +add_test(NAME shader_db_check COMMAND shader_db_check) +add_test(NAME shader_db_check_control COMMAND shader_db_check --mutate) +set_tests_properties(shader_db_check_control PROPERTIES WILL_FAIL TRUE) +add_executable(startup_gpu_db_check tests/startup_gpu_db_check.cpp src/startup_stubs/gpu_db.cpp) +target_link_libraries(startup_gpu_db_check PRIVATE x2w_shader_db) +set_target_properties(x2w_shaders shader_db_check startup_gpu_db_check PROPERTIES + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +add_test(NAME startup_gpu_db_check COMMAND startup_gpu_db_check) +add_test(NAME startup_gpu_db_check_control COMMAND startup_gpu_db_check --mutate) +set_tests_properties(startup_gpu_db_check_control PROPERTIES WILL_FAIL TRUE) + +# LOCAL vpipe (WP2, PLAN.md): ABI pipelines and root signatures. The stream walk and graphics state +# (src/startup_stubs/gpu_pipeline_state.h) without a device; the mutated runs are the negative controls. +add_executable(startup_gpu_reference_library tests/startup_gpu_reference_library.cpp src/startup_stubs/gpu_db.cpp) +add_test(NAME startup_gpu_reference_entry_locks COMMAND startup_gpu_reference_library --entry-locks) +target_link_libraries(startup_gpu_reference_library PRIVATE x2w_shader_db d3d12 dxgi) +set_target_properties(startup_gpu_reference_library PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + +add_executable(startup_gpu_warm_bad tests/startup_gpu_warm_bad.cpp) +target_include_directories(startup_gpu_warm_bad PRIVATE src) +target_compile_features(startup_gpu_warm_bad PRIVATE cxx_std_17) +target_link_libraries(startup_gpu_warm_bad PRIVATE x2w_blake3) +add_test(NAME startup_gpu_warm_bad COMMAND startup_gpu_warm_bad) + +add_executable(startup_gpu_build_queue tests/startup_gpu_build_queue.cpp) +target_include_directories(startup_gpu_build_queue PRIVATE src) +target_compile_features(startup_gpu_build_queue PRIVATE cxx_std_17) +add_test(NAME startup_gpu_build_queue COMMAND startup_gpu_build_queue) +set_tests_properties(startup_gpu_build_queue PROPERTIES TIMEOUT 10) + +add_executable(startup_gpu_pipeline_state_check tests/startup_gpu_pipeline_state_check.cpp) +target_include_directories(startup_gpu_pipeline_state_check PRIVATE src) +target_compile_features(startup_gpu_pipeline_state_check PRIVATE cxx_std_17) +add_test(NAME startup_gpu_pipeline_state COMMAND startup_gpu_pipeline_state_check) +add_test(NAME startup_gpu_pipeline_state_desktop_numbering_control COMMAND startup_gpu_pipeline_state_check --mutate desktop-numbering) +add_test(NAME startup_gpu_pipeline_state_blend_kept_control COMMAND startup_gpu_pipeline_state_check --mutate blend-kept) +set_tests_properties(startup_gpu_pipeline_state_desktop_numbering_control startup_gpu_pipeline_state_blend_kept_control + PROPERTIES WILL_FAIL TRUE) +# The host roots and pipelines (gpu_pipeline_build.h, gpu_pipeline_pending.h) from synthetic records over our own +# HLSL written to the ABI (tests/startup_gpu_pipeline.hlsl, SM 6.6), on WARP and hardware: root layout, a compute +# dispatch, a graphics draw from a console stream, a mesh draw (MS = 24). --mutate no-heap-flags drops the +# DIRECTLY_INDEXED flags and must fail; the debug runs fail on any debug-layer error. +set(startup_gpu_pipeline_headers) +foreach(entry IN ITEMS "CsMain;cs_6_6;cs" "VsMain;vs_6_6;vs" "PsMain;ps_6_6;ps" "MsMain;ms_6_6;ms") + list(GET entry 0 entry_name) + list(GET entry 1 entry_profile) + list(GET entry 2 entry_short) + set(header "${CMAKE_CURRENT_BINARY_DIR}/startup_gpu_pipeline_${entry_short}.h") + add_custom_command(OUTPUT "${header}" + COMMAND "${DXC_EXECUTABLE}" -nologo -T ${entry_profile} -E ${entry_name} -Vn startup_gpu_pipeline_${entry_short} -Fh "${header}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gpu_pipeline.hlsl" + DEPENDS tests/startup_gpu_pipeline.hlsl VERBATIM) + list(APPEND startup_gpu_pipeline_headers "${header}") +endforeach() +add_executable(startup_gpu_pipeline tests/startup_gpu_pipeline.cpp ${startup_gpu_pipeline_headers}) +target_include_directories(startup_gpu_pipeline PRIVATE src "${CMAKE_CURRENT_BINARY_DIR}") +target_compile_features(startup_gpu_pipeline PRIVATE cxx_std_17) +target_link_libraries(startup_gpu_pipeline PRIVATE d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_gpu_reference_miss_${backend} COMMAND startup_gpu_pipeline ${backend} compute --reference-miss) + set_tests_properties(startup_gpu_reference_miss_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 90) + foreach(mode IN ITEMS root compute graphics mesh rectangles) + add_test(NAME startup_gpu_pipeline_${mode}_${backend} COMMAND startup_gpu_pipeline ${backend} ${mode}) + add_test(NAME startup_gpu_pipeline_${mode}_${backend}_debug COMMAND startup_gpu_pipeline ${backend} ${mode} --debug) + add_test(NAME startup_gpu_pipeline_${mode}_${backend}_no_heap_flags_control + COMMAND startup_gpu_pipeline ${backend} ${mode} --mutate no-heap-flags) + set_tests_properties(startup_gpu_pipeline_${mode}_${backend} startup_gpu_pipeline_${mode}_${backend}_debug + PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + set_tests_properties(startup_gpu_pipeline_${mode}_${backend}_no_heap_flags_control PROPERTIES TIMEOUT 60 WILL_FAIL TRUE) + endforeach() +endforeach() + +# WP4 (vindirect): the indirect execution core (src/startup_stubs/gpu_indirect_clamp.h) on a desktop +# device: the argument clamp with the upstream test vectors, the per-list budget pool, 0x69 run as a dispatch, +# mesh records run as DispatchMesh(x, 1, 1). Controls: --mutate (clamp bound removed) and restart-nozero must fail. +set(startup_gpu_indirect_ms_header "${CMAKE_CURRENT_BINARY_DIR}/startup_gpu_indirect_ms.h") +add_custom_command(OUTPUT "${startup_gpu_indirect_ms_header}" + COMMAND "${DXC_EXECUTABLE}" -T ms_6_5 -E MeshMain -Vn startup_gpu_indirect_ms -Fh "${startup_gpu_indirect_ms_header}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gpu_indirect.hlsl" + DEPENDS tests/startup_gpu_indirect.hlsl VERBATIM) +add_executable(startup_gpu_indirect tests/startup_gpu_indirect.cpp "${startup_gpu_indirect_ms_header}") +target_include_directories(startup_gpu_indirect PRIVATE src/startup_stubs "${CMAKE_CURRENT_BINARY_DIR}") +target_compile_features(startup_gpu_indirect PRIVATE cxx_std_17) +target_link_libraries(startup_gpu_indirect PRIVATE d3d12 dxgi d3dcompiler) +add_test(NAME startup_gpu_indirect_layout COMMAND startup_gpu_indirect warp layout) +foreach(adapter IN ITEMS warp hardware) + foreach(case IN ITEMS count window budget lanes restart pool dispatch69 mesh wide capture) + add_test(NAME startup_gpu_indirect_${case}_${adapter} COMMAND startup_gpu_indirect ${adapter} ${case}) + set_tests_properties(startup_gpu_indirect_${case}_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endforeach() + add_test(NAME startup_gpu_indirect_mutate_${adapter} COMMAND startup_gpu_indirect ${adapter} count --mutate) + add_test(NAME startup_gpu_indirect_restart_nozero_${adapter} COMMAND startup_gpu_indirect ${adapter} restart-nozero) + set_tests_properties(startup_gpu_indirect_mutate_${adapter} startup_gpu_indirect_restart_nozero_${adapter} + PROPERTIES WILL_FAIL TRUE SKIP_RETURN_CODE 77 TIMEOUT 120) +endforeach() + +# vexport's x2w_shaders (src/shader_db) with this translator (src/shader_db/x2w_shaders_vs.cpp, which needs the dump's +# per-container step and the repository root on the include path). x2w_shaders is built with the static CRT (/MT), the +# translator's libraries with the DLL one, so it links a static-CRT copy of them (x2w_vs_translator_mt: the same +# sources, compiled once more) in place of x2w_shader. +if(TARGET x2w_shaders AND TARGET x2w_tool_dump) + set(x2w_vs_mt_sources "") + foreach(t IN ITEMS x2w_shader x2w_vs_emit_base x2w_vs_emit_opt x2w_vs_emit_dxil x2w_vs_emit_wave x2w_vs_emit_lower + x2w_vs_emit x2w_tool_base x2w_tool_dump) + get_target_property(dir ${t} SOURCE_DIR) + get_target_property(list ${t} SOURCES) + foreach(f IN LISTS list) + if(NOT IS_ABSOLUTE "${f}") + set(f "${dir}/${f}") + endif() + list(APPEND x2w_vs_mt_sources "${f}") + endforeach() + endforeach() + list(REMOVE_DUPLICATES x2w_vs_mt_sources) + add_library(x2w_vs_translator_mt STATIC ${x2w_vs_mt_sources}) + target_include_directories(x2w_vs_translator_mt PUBLIC src ${CMAKE_SOURCE_DIR} tools/x2w + PRIVATE "$") + target_compile_features(x2w_vs_translator_mt PUBLIC cxx_std_20) + target_compile_options(x2w_vs_translator_mt PRIVATE /permissive- /utf-8 /EHsc /bigobj) + target_compile_definitions(x2w_vs_translator_mt PRIVATE _CRT_SECURE_NO_WARNINGS NOMINMAX X2W_VS_FINGERPRINT_HEADER + "X2W_TOOL_SOURCE_DIR=\"${CMAKE_SOURCE_DIR}\"") + add_dependencies(x2w_vs_translator_mt x2w_vs_fingerprint) + target_link_libraries(x2w_vs_translator_mt PUBLIC d3d12 dxgi) + set_target_properties(x2w_vs_translator_mt PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + get_target_property(x2w_vs_shaders_links x2w_shaders LINK_LIBRARIES) + list(REMOVE_ITEM x2w_vs_shaders_links x2w_shader) + set_property(TARGET x2w_shaders PROPERTY LINK_LIBRARIES ${x2w_vs_shaders_links} x2w_vs_translator_mt) + + # Only the adapter to the C++20 shader emitter needs its language standard. Each + # consumer links the adapter with its own CRT, including the standalone device fixtures. + add_library(gpu_rect_mt STATIC src/startup_stubs/gpu_rect.cpp) + target_link_libraries(gpu_rect_mt PRIVATE x2w_vs_translator_mt) + set_target_properties(gpu_rect_mt PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + target_link_libraries(d3d12_xs_shim PRIVATE gpu_rect_mt) + add_library(gpu_rect STATIC src/startup_stubs/gpu_rect.cpp) + target_link_libraries(gpu_rect PRIVATE x2w_vs_emit_dxil) + target_link_libraries(startup_gpu_pipeline PRIVATE gpu_rect) + target_link_libraries(offscreen_check PRIVATE gpu_rect) + if(TARGET cpu_placed_dxr_provider) + target_link_libraries(cpu_placed_dxr_provider PRIVATE gpu_rect) + endif() +endif() diff --git a/docs/experiments.md b/docs/experiments.md index 667e7799f7..f2208c2067 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -609,8 +609,8 @@ python -B tests/host_commit_check.py -v This is independently written from public Windows PSAPI behavior and the reported Windows commit-limit failure mode in -[VIctory's README at `ffe310e`](https://github.com/Marvisak/VIctory/blob/ffe310eb2098e52169f4c44db5ffdabf43a72622/README.md). -No VIctory (GPL-3.0-or-later) source code is copied into this MIT project. +the upstream `README.md` at commit `ffe310eb2098e52169f4c44db5ffdabf43a72622`. +The commit-headroom check uses the Windows API directly. Its implementation contains no code from that GPL-3.0-or-later project. The source-built Linux tests mock the Windows API and check limits, underflow, API errors, low-commit failure **before** package inspection, and preservation of the prior JSON output when the option is absent. The native Windows test @@ -7741,6 +7741,60 @@ modifier the emitted text is unchanged. `op_sel` and source modifiers are still rather than silently ignored, and a uint-result conversion such as `v_cvt_f16_f32` keeps refusing output modifiers. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_vcvt_omod$' -V`. +**f32 lg and nlg compares with a NaN source (#1920).** `V_CMP_LG_F32` is less or greater: ordered and not equal, +false when either source is NaN, and `V_CMP_NLG_F32` is its negation. `compare()` lowered them as `a != b` and +`!(a != b)`, and HLSL `!=` is unordered, so both gave the opposite result on every NaN pair. They now read +`(ORDERED && (a < b || a > b))` and its negation, where ORDERED tests both source words for NaN on their bits +(`(w & 0x7fffffff) <= 0x7f800000`, before the neg/abs modifiers). The bit test is needed on hardware: DXC without +`-Gis` marks the float compares `fast`, and on an RX 9070 XT (driver 32.0.31044.16) the DXC build of the plain +less-or-greater in the `cmp` fixture below returned 1 for both lg and nlg on all 156 NaN pairs (its `v_cmpx` +fixtures matched); FXC on both backends and DXC on WARP gave the ordered result. +`startup_gfx2hlsl_f32_lg` decodes every f32 condition of the table (v_cmp and v_cmpx, e32 and e64 under every +neg/abs combination, 510 forms), translates it and evaluates the HLSL over all 256 pairs of +-0, +-min denormal, ++-1.0, +-max finite, +-inf, +-quiet, signalling and payload NaN against a reference built from the ISA +definitions on the bit patterns; the old `!=` text fails all 68 lg/nlg forms, and the f32 SDWA forms stay refused. +The draws `startup_gfx2hlsl_f32_lg_{warp,hardware}` build one of those words from the pixel's x and one from its +y, so 16 x 16 pixels cover every pair, and write `v_cmp_lg_f32_e32`, `v_cmp_nlg_f32_e64`, `v_cmp_lg_f32_e64` and +`v_cmp_nlg_f32_e32` results or keep a pixel through `v_cmpx_lg/nlg_f32_e32/e64`, compiled with FXC `ps_5_1` and +DXC `ps_6_0`. Every pixel matched on WARP and on the RX 9070 XT with both compilers: lg is 1 on unequal pairs and +0 on equal and NaN pairs, nlg the opposite. Both backends flushed denormal compare sources to signed zero, which +D3D allows; the draw accepts the image with denormals kept or flushed, the same choice for every fixture, and +reports which. The old `!=` text fails each draw against both images (156 pixels differ against the flushed one) +and matches its own image. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_f32_lg' -V`; +`tests/startup_gfx2hlsl_f32_lg_check.py binary ` and `decode ` round-trip the forms and the +fixtures through LLVM 15. + +**f32 nlt, nle, ngt, nge, o and u under compilers without `-Gis` (#1936).** The startup cache compiles every +`gfx2hlsl` pair with FXC and no flags, and neither compiler keeps float compares IEEE-strict unless asked. FXC +compiled `!(a < b)` to `ge a, b` (and likewise for `<=`, `>`, `>=`), so nlt, nle, ngt and nge gave 0 on every NaN +pair where the ISA gives 1; DXC folded `a != a` and `a == a`, so u was constant 0 and o constant 1. WARP and an +RX 9070 XT (driver 32.0.31044.16) agreed in every case, and `/Gis` or `-Gis` restored the ISA result, so the +bytecode decides it. The n-forms now read `!(ORDERED && a OP b)` and o and u read ORDERED and `!ORDERED`, with +ORDERED the bit test of both source words that lg uses; neq is unchanged, as both compilers keep `!(a == b)` true +on NaN. `startup_gfx2hlsl_f32_nan` evaluates the HLSL of all 510 f32 forms over the 256 source pairs under IEEE +compares and under models of the two rewrites (a negation pushed into the opposite relation; reflexive float +relations folded, and less-or-greater read as unordered not-equal, #1920); each equals the ISA reference, and the +text before #1936 fails all 204 forms of the six conditions under the model of the compiler that broke it. The +draws `startup_gfx2hlsl_f32_nan_{warp,hardware}` write four results of each of the 13 conditions other than lg +and nlg (e32, and e64 with `(-a, |b|)`, `(-|a|, -b)`, `(|a|, b)`) and keep pixels through `v_cmpx_*_e64` for the +six, compiled with FXC `ps_5_1` and DXC `ps_6_0`. Every pixel matched on WARP and the RX 9070 XT with both +compilers (denormal sources flushed where they matter). The text before #1936 fails each draw on the compiler that +rewrote it (156 NaN pixels against the flushed image) and matches that rewrite's image; on the other compiler it +is recorded, and it matched. Also recorded, not checked: with `/Gis` and `-Gis` the old and the new text of the six +both matched every pixel. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_f32_nan' -V`; +`tests/startup_gfx2hlsl_f32_nan_check.py binary ` and `decode ` round-trip the fixtures through +LLVM 15. +The SDWA forms of those conversions read the same table: after the split, `sdwa()` still looked only at the +uint-result table, so every `v_cvt_f32_*_sdwa` was refused until it was pointed at both (#1727). The +restored path keeps the source selection, the `dst_sel`/`dst_unused` write and the `U(...)` wrapper, and a +conversion's output modifier inside an SDWA form is still refused rather than dropped. + +**An `op_sel` the lowering does not model is refused.** `set_vf()` used to accept an `op_sel` modifier and emit +the same text as without it. `op_sel` selects which half of a packed source the operation reads, so dropping +it silently changes the operand; the float path now refuses it (#1754). The same test pins the exact shift, +mask and conversion expressions of the byte-extracting conversions, whose shift amounts escaped mutation +checks before. +Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_opsel$' -V`. The SDWA forms of those conversions read the same table: after the split, `sdwa()` still looked only at the uint-result table, so every `v_cvt_f32_*_sdwa` was refused until it was pointed at both (#1727). `sdwa()` now also applies output modifiers (`clamp`, `mul:2`, `mul:4` and `div:2`) on `VEC_U_TO_F` conversions before `U(...)` @@ -15545,6 +15599,39 @@ 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. +## Local runtime switches for upstream paths (local merge) + +Where the local runtime and upstream implement the same device or list slot, the local path stays the default and the upstream one is kept behind its own switch. Each is off unless set to `1`. + +| Switch | Upstream behaviour it enables | +|---|---| +| `X2W_DEFER_HEAP_ROOTS` | Deferred descriptor-heap root arguments in `list_graphics_root` (`root_heap_flags`); real draws that need them are refused. | +| `X2W_UPSTREAM_EXECUTE_INDIRECT` | The upstream list slot 61 handler (`list_execute_indirect_upstream`) in place of the local `d3d12_indirect.inl` one. Its Dispatch forwarding also needs `X2W_UPSTREAM_COMPUTE_ROOT`, because the local slot 33 handler does not record the desktop compute root. | +| `X2W_UPSTREAM_COMPUTE_ROOT` | The upstream compute root signature and upload SRV handlers on list slots 33 and 43 (`list_compute_root_desktop`, `list_compute_upload_srv`). | +| `X2W_LIST_UPLOAD_PAGES` | The upstream upload-page allocator on list slot 148 (`list_allocate_upload_pages`); without it `list_upload_gpu` finds no pages and its callers fall through to the local paths. | +| `X2W_UPSTREAM_CONSOLE_SRV` | The upstream by-address memory SRV forms on device slot 70: textures in a console layout of `gfx10_layout.h` (`console_layout_srv`) and single-element textures (`single_element_srv.h`). Without it slot 70 refuses those calls as the local runtime did; `X2W_MEMORY_SRV_DETILE` and `X2W_MEMORY_SRV_ANNOUNCED` keep their own forms. | +| `X2W_UPSTREAM_STENCIL_REF` | List slot 24 (`OMSetStencilRef` forwarding) alone, without the depth group. | +| `X2W_UPSTREAM_STREAM_LAYOUT` | A stream pipeline's `INPUT_LAYOUT` subobject read into the draw request: it is published as `req_.ia` and folded into the key, so `gfx2hlsl.py` can translate a vertex shader that calls the fetch routine. Without it the request carries no layout and the key is the one the stream pipeline had before the merge. | +| `X2W_UPSTREAM_MESH86_CACHE` | The upstream slot-86 mesh stage cache (`try_cached_mesh86`, `req_.m86`, key revision `x2w-startup-mesh-86-1`). It takes mesh streams before `stream_translation`, so without it slot 86 keeps the local mesh path. | + +Slot 24 (depth state) is registered when the local depth switch, upstream `X2W_DEPTH_STATE` or `X2W_UPSTREAM_STENCIL_REF` is set. The upstream tests of these paths set the switch in their CTest `ENVIRONMENT`. These rows describe switch wiring only; no title run has measured the upstream paths in this tree. + +### Shader cache revision (local merge) + +The draw and mesh key revision stays `x2w-startup-shader-3` (`pipeline_key` in `src/startup_stubs/d3d12_draw.inl` and `tools/startup/gfx2hlsl.py`), the value before the merge, so the published shader cache keeps resolving. Upstream advanced it to drop its own older translator output: + +| Revision | Upstream commit | Reason | Runtime contract of an existing entry | +|---|---|---|---| +| 4 | f7b7297d | non-fused multiply-add rounding | translator output only | +| 5 | 56bd3bd1 | A16 coordinates of image loads | translator output only | +| 6 | c3c3ab3c, 7f502437 | A16 `image_sample`/`_lz`; slot-86 pixel attributes linked to vertex parameters by semantic | translator output only | +| 7 | 27f32934 | partial export masks (`wmask` manifest lines) | unchanged: a manifest without `wmask` lines keeps the full write mask, as before | +| 8 | 5b4b1070 | moves past 7 because of the slot-86 linking | translator output only | +| `8cs` | f8cfa76b (#2195) | slot 67 compute requests `req_.c67` | a separate key space; this tree uses `x2w-startup-shader-3cs` (the graphics revision plus `cs`, as `tests/startup_compute_request_check.py` requires). No `.c67` file existed in the cache. The local `req_c67_` key has no revision and is unchanged | + +Merge 2 (origin/main b976e8bc) takes upstream for every conflict outside the shader translator, the mesh path, the shader and manifest loading path and the cache keys, which keep the local side. Upstream moved the revision on to 14 (9 #2299, 10 #2305, 11 #2292, 12 #2308, 13 #2319, 14 #2059); this tree stays at 3 and `3cs`, and its translator keeps the local lowerings where both sides changed the same lines, so `buffer_store_dwordx3` is still refused. Retranslating 60 cached draw requests and 10 RTV variants gives the same manifests as before the merge; the HLSL differs only by two unused helper functions (`bfe32`, `bfe64`, upstream #2088) in every preamble. Upstream's early refusal of `uav` manifest lines is not taken, because the local cache's version-1 manifests carry them. + +The upstream stream input layout key (a8f581c4) changes a stream request's key without a revision; it is behind `X2W_UPSTREAM_STREAM_LAYOUT` above. Entries written before the merge were translated by the pre-merge translator and keep that output; a key the merged translator writes for the first time gets the merged lowerings. No switch selects another revision, because both use the one merged translator. ## 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 diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index c4fd9a0e07..bcdb513da8 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -37,8 +37,8 @@ Render-mode slot 26 forwards unflagged UAV barriers on an open direct or compute resource orders UAV accesses across resources. A named resource must be a wrapper around a local desktop resource with UAV access. Transition and aliasing records are skipped because desktop resource states and heap aliases are managed by the shim. The slot returns zero console actions. -The console slot and record layout are also documented by the -[ztrx command-list implementation](https://github.com/Zettrox/ztrx/blob/90b529f878a470fec9bf07b7be316bc769a12232/crates/victory-gpu/src/list.rs). +The upstream command-list implementation documents the console slot and record layout in +`src/list.rs` at commit `90b529f878a470fec9bf07b7be316bc769a12232`. Build `startup_present_producer` and run `ctest --preset release --no-tests=error -R '^startup_list_uav_barriers_(warp|hardware)$' -V`. @@ -255,6 +255,11 @@ windows, build `startup_overlay_window` and run `ctest --preset release --no-tests=error -R '^startup_overlay_window$' -V`. The same run raises each of two guests in turn and checks that the raised one is selected. +The launcher defaults to `X2W_PRESENT_IN_TITLE_WINDOW=1` in render mode. DirectComposition +attaches the GPU swap chain to the executable's existing client area and scales the picture +on resize. The original window opens with a 1280 ? 720 client area and handles input. The launcher appends the runtime name, frame number, and recent frame rate to its caption. Setting the switch +to `0` selects the separate output window. + With `X2W_HIDE_TITLE_WINDOW=1` (exactly `1`), a 500 ms timer on the output window's thread hides the title's own visible, unowned windows while presents reach the output window, and hides them again when the title shows them. The hide is asynchronous (`ShowWindowAsync`), so a busy title thread does not @@ -1410,6 +1415,18 @@ those lifetimes intact. `unmeasured` counts tracking failures. DXGI usage can also include allocations outside these categories, such as swap chain and descriptor heap backing. +With `X2W_D3D12_COLD_TEXTURE_PRIORITY=1`, the runtime asks Windows for low residency +priority when the guest releases its last reference to a committed slot 133 sampled +2D texture with title memory, one sample and no resource flags. A guest AddRef, +direct view or copy, or translated sample that resolves the wrapper restores normal +priority. The texture then keeps normal priority for the rest of the process. +Already-recorded commands and persistent shader-visible descriptors can still +access a low-priority texture without another CPU-side lookup. Windows controls +physical placement. The hint preserves resource contents and committed allocation +size. The memory heartbeat reports the bytes and count currently at low priority, +the cumulative restored bytes and count, and failed priority changes. The hint +is disabled when `X2W_D3D12_RELEASE_RETIRED` or `X2W_MEMCUT_RELEASE` is enabled. + `X2W_D3D12_RELEASE_RETIRED=1` ends the retained lifetime for committed 2D textures that have one sample, no render-target, depth-stencil or unordered-access flag, and live in a default heap without heap flags: @@ -3059,3 +3076,30 @@ before any desktop copy, leaving a sentinel-filled readback buffer unchanged. On list refuses boxes with an unaligned right or bottom edge, copies the aligned 4x4 block, and reads back all eight block bytes with the next byte unchanged. Reproduce the portable and wrapped-list checks with `ctest --preset dev --no-tests=error -R '^startup_list_copy_texture' -V`. + +### Compare a compute output with its presented frame + +With busy-frame tracing and `X2W_CX_TRACE_UAV=<16-hex-key>,` enabled, set +`X2W_CX_TRACE_PAIR=1` to sample the selected compute output and the final +presented surface. The producer command must be recorded and submitted in the +same frame on the presenting queue. Look for matching submit frame numbers in +`x2w-frame-pair` lines. A busy presentation readback can skip the second +sample. A frame with only one image is an incomplete comparison. + +The runtime writes 96-by-54 RGB PFM images beside `X2W_TRAP_LOG`. Lighting +values retain their half-float numeric values. Presentation bytes are normalized +to [0,1] in the surface's encoding. Compare spatial features and zero regions; +a tone-mapping pass can change magnitudes. Six horizontal bands in the log +report sample counts with finite nonzero RGB, alpha alone, and nonfinite values. + +### Local shader profiles + +Set these options before starting the process. Leave a selector unset to disable its match. + +| Setting | Local input | +| --- | --- | +| X2W_MATERIAL_FIELDS_PROFILE | Path to the text output of the shader_material_fields.mjs tool. Each row holds a shader key, two DXBC checksum halves and a field mask in hexadecimal. | +| X2W_EXPOSURE_RESET_KEY | Lowercase 16-digit hexadecimal pixel shader key for resetting exposure history. | +| X2W_LIGHT_RESOLVE_MARKER, X2W_LIGHT_RADIANCE_MARKER, X2W_LIGHT_AIR_MARKER | Case-sensitive strings in compute containers that identify each lighting role. | +| X2W_CULL_HEAP_PROBE_KEY | 16-digit hexadecimal compute shader key for the optional X2W_CULL_HEAP_PROBE diagnostic. | +| X2W_CULL_INPUT_CAPTURE | Comma-separated key:occurrence selections. Keys are 16 hexadecimal digits. Occurrences start at zero. An asterisk selects every occurrence. | diff --git a/src/era_heap.cpp b/src/era_heap.cpp index 25520fc730..3662d8b130 100644 --- a/src/era_heap.cpp +++ b/src/era_heap.cpp @@ -13,6 +13,7 @@ #define NOMINMAX #endif #include +#include "xmem_low.h" namespace era_heap { namespace { @@ -52,7 +53,7 @@ void* allocate_pages(std::size_t bytes, std::size_t alignment) noexcept const auto page = geometry().page; const auto committed = (bytes + page - 1) & ~(page - 1); for (int attempt = 0; attempt < 8; ++attempt) { - auto* probe = VirtualAlloc(nullptr, committed + alignment, MEM_RESERVE, PAGE_NOACCESS); + auto* probe = x2w_low::alloc(committed + alignment, MEM_RESERVE, PAGE_NOACCESS); if (!probe) { return nullptr; } @@ -117,7 +118,7 @@ void* allocate(std::size_t bytes, std::uint64_t attributes) noexcept return nullptr; } // Committed pages are zero-filled by the system. - return VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + return x2w_low::alloc(bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); } // Physical memory types need title physical pages, which this experiment does not model. diff --git a/src/era_query.cpp b/src/era_query.cpp index 703bcefe3a..b0fee639ed 100644 --- a/src/era_query.cpp +++ b/src/era_query.cpp @@ -80,7 +80,14 @@ std::size_t query(void* process, const void* address, void* buffer, std::size_t // Desktop policy, not a Scarlett field: mark addresses in registered GPU-intended regions. const bool registered = is_current_process(process) && is_registered(reinterpret_cast(address)); - static_cast(buffer)[tail_offset] = registered ? tail_registered : 0; + // LOCAL EXPERIMENT (X2W_XMEM_QUERY_READABLE): the BVH callers may read bits 0-1 as "CPU readable"; + // mark every committed readable region. Behavioural reference: ivall/xcl@91f9a5e (kernelx.rs). + static const bool readable_policy = GetEnvironmentVariableA("X2W_XMEM_QUERY_READABLE", nullptr, 0) != 0; + const DWORD readable = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | + PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; + const bool cpu_readable = readable_policy && info.State == MEM_COMMIT && (info.Protect & readable) && + !(info.Protect & (PAGE_GUARD | PAGE_NOACCESS)); + static_cast(buffer)[tail_offset] = registered || cpu_readable ? tail_registered : 0; } return sizeof(info); } diff --git a/src/shader_db/archive_scan.cpp b/src/shader_db/archive_scan.cpp new file mode 100644 index 0000000000..6088730b38 --- /dev/null +++ b/src/shader_db/archive_scan.cpp @@ -0,0 +1,152 @@ +// See archive_scan.h. +#include "archive_scan.h" + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include +#include + +#include "../startup_stubs/inflate.h" + +namespace shader_db { +namespace { + +uint32_t u32(const uint8_t* p) +{ + uint32_t v; + std::memcpy(&v, p, 4); + return v; +} + +const uint8_t* find(const uint8_t* from, const uint8_t* end, const char (&needle)[5]) +{ + const uint8_t* at = std::search(from, end, needle, needle + 4); + return at == end ? nullptr : at; +} + +const uint8_t* find(const uint8_t* from, const uint8_t* end, const uint8_t (&needle)[4]) +{ + const uint8_t* at = std::search(from, end, needle, needle + 4); + return at == end ? nullptr : at; +} + +constexpr std::size_t max_unpacked = 64u << 20; + +// The length-prefixed printable name ends at the NUL before the record. +std::string name_before(const uint8_t* file, std::size_t nul) +{ + std::size_t run = nul; + while (run > 0 && file[run - 1] >= 0x21 && file[run - 1] <= 0x7e) --run; + for (std::size_t l = run ? run - 1 : 0; l < nul; ++l) + if (static_cast(file[l]) == nul - l) return std::string(reinterpret_cast(file + l + 1), nul - l - 1); + return {}; +} + +// The stream must end exactly at the declared unpacked size. +bool unpack(const uint8_t* packed, std::size_t packed_bytes, std::size_t unpacked_bytes, std::vector& out) +{ + out.assign(unpacked_bytes + 1, 0); // one spare byte: a stream that runs longer must not fit + x2w_inflate::Stream s{packed, packed_bytes, 0, out.data(), out.size()}; + if (!x2w_inflate::inflate_raw(s) || s.out_pos != unpacked_bytes) return false; + out.resize(unpacked_bytes); + return true; +} + +} // namespace + +std::size_t dxbc_size(const uint8_t* data, std::size_t available) +{ + if (available < 32 || std::memcmp(data, "DXBC", 4)) return 0; + const std::size_t total = u32(data + 24), count = u32(data + 28); + if (total < 32 || total > available || count > 256 || 32 + 4 * count > total) return 0; + for (std::size_t i = 0; i < count; ++i) { + const std::size_t offset = u32(data + 32 + 4 * i); + if (offset > total || total - offset < 8) return 0; + const std::size_t size = u32(data + offset + 4); + if (size > total - offset - 8) return 0; + } + return total; +} + +std::size_t scan_bytes(const uint8_t* data, std::size_t n, const ContainerSink& sink) +{ + const uint8_t* end = data + n; + std::size_t corrupt = 0; + char label[64]; + if (find(data, end, "SGD5")) { + static const uint8_t marker[4] = {0xe7, 0xdc, 0x0d, 0x00}; + std::vector unpacked; + for (const uint8_t* at = find(data, end, marker); at; at = find(at + 1, end, marker)) { + const std::size_t o = static_cast(at - data); + if (o < 6 || n - o < 12) continue; + const std::size_t size = u32(at - 4), unpacked_bytes = u32(at + 8); + if (u32(at + 4) != size || size < 12 || unpacked_bytes > max_unpacked || size > n - o) continue; + const std::string name = data[o - 6] == 0 ? name_before(data, o - 6) : std::string(); + if (!unpack(at + 12, size - 12, unpacked_bytes, unpacked)) { + ++corrupt; + continue; + } + std::snprintf(label, sizeof(label), "@0x%zx ", o); + // Limit a container embedded in the unpacked record to its declared size. + const std::size_t bounded = dxbc_size(unpacked.data(), unpacked.size()); + sink(unpacked.data(), bounded ? bounded : unpacked.size(), label + (name.empty() ? std::string("?") : name)); + } + } + for (const uint8_t* at = find(data, end, "DXBC"); at; at = find(at + 1, end, "DXBC")) { + const std::size_t size = dxbc_size(at, static_cast(end - at)); + if (!size) continue; + std::snprintf(label, sizeof(label), "@0x%zx", static_cast(at - data)); + sink(at, size, label); + } + return corrupt; +} + +namespace { + +void walk(const std::wstring& path, uint64_t max_file, const std::function& file_sink, + const ContainerSink& sink) +{ + const DWORD attributes = GetFileAttributesW(path.c_str()); + if (attributes == INVALID_FILE_ATTRIBUTES) return; + if (attributes & FILE_ATTRIBUTE_DIRECTORY) { + WIN32_FIND_DATAW found; + std::vector names; + HANDLE h = FindFirstFileW((path + L"\\*").c_str(), &found); + if (h == INVALID_HANDLE_VALUE) return; + do { + if (std::wcscmp(found.cFileName, L".") && std::wcscmp(found.cFileName, L"..")) names.push_back(found.cFileName); + } while (FindNextFileW(h, &found)); + FindClose(h); + std::sort(names.begin(), names.end()); // a fixed order, so the first source of a container is stable + for (const auto& name : names) walk(path + L"\\" + name, max_file, file_sink, sink); + return; + } + HANDLE file = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return; + LARGE_INTEGER size{}; + if (GetFileSizeEx(file, &size) && size.QuadPart > 0 && static_cast(size.QuadPart) <= max_file) { + HANDLE mapping = CreateFileMappingW(file, nullptr, PAGE_READONLY, 0, 0, nullptr); + const void* view = mapping ? MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0) : nullptr; + if (view) { + file_sink(path); + scan_bytes(static_cast(view), static_cast(size.QuadPart), sink); + UnmapViewOfFile(view); + } + if (mapping) CloseHandle(mapping); + } + CloseHandle(file); +} + +} // namespace + +void scan_paths(const std::vector& paths, uint64_t max_file, const std::function& file_sink, + const ContainerSink& sink) +{ + for (const auto& p : paths) walk(p, max_file, file_sink, sink); +} + +} // namespace shader_db diff --git a/src/shader_db/archive_scan.h b/src/shader_db/archive_scan.h new file mode 100644 index 0000000000..4171ec1882 --- /dev/null +++ b/src/shader_db/archive_scan.h @@ -0,0 +1,28 @@ +// Finds DXBC containers in standalone files, executables, DLLs and SGD5 archives. Each SGD5 +// record has a preceding name, marker 0x000ddce7, packed and unpacked sizes, and a raw deflate stream. Validate +// each container's parts and take only its declared size so the bytes match the title's pipeline creation request. +#pragma once + +#include +#include +#include +#include +#include + +namespace shader_db { + +// `label`: "@0x" for a container as is, "@0x " for a packed record. +using ContainerSink = std::function; + +// The bytes of a well-formed DXBC container at the start of `data`, cut to its header's size; 0 if there is none. +std::size_t dxbc_size(const uint8_t* data, std::size_t available); + +// Every container in one file's bytes. Returns the number of packed records that did not unpack. +std::size_t scan_bytes(const uint8_t* data, std::size_t n, const ContainerSink& sink); + +// Every regular file under `paths` (files or folders, recursively) up to `max_file` bytes, mapped read-only. +// `file_sink` is told each file before its containers. +void scan_paths(const std::vector& paths, uint64_t max_file, const std::function& file_sink, + const ContainerSink& sink); + +} // namespace shader_db diff --git a/src/shader_db/gpu_export.cpp b/src/shader_db/gpu_export.cpp new file mode 100644 index 0000000000..2ddbd456c1 --- /dev/null +++ b/src/shader_db/gpu_export.cpp @@ -0,0 +1,282 @@ +// See gpu_export.h. A small JSON reader for the export's own files (objects, arrays, strings without +// escapes beyond \" \\ \uXXXX, numbers, true, false, null). +#include "gpu_export.h" + +#include +#include +#include +#include +#include + +namespace shader_db { +namespace { + +struct Value { + enum Kind { null, boolean, number, string, array, object } kind = null; + bool b = false; + double n = 0; + std::string s; + std::vector items; + std::vector> fields; + const Value* get(const char* name) const + { + for (const auto& f : fields) + if (f.first == name) return &f.second; + return nullptr; + } +}; + +struct Parser { + const char* p; + const char* end; + bool ok = true; + void space() + { + while (p < end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) ++p; + } + bool eat(char c) + { + space(); + if (p < end && *p == c) { + ++p; + return true; + } + return false; + } + std::string text() + { + std::string out; + if (!eat('"')) { + ok = false; + return out; + } + while (p < end && *p != '"') { + if (*p == '\\' && p + 1 < end) { + ++p; + if (*p == 'u' && end - p >= 5) { + out.push_back(static_cast(std::strtoul(std::string(p + 1, p + 5).c_str(), nullptr, 16))); + p += 5; + continue; + } + } + out.push_back(*p++); + } + ok = ok && p < end; + ++p; + return out; + } + Value value(int depth = 0) + { + Value v; + space(); + if (p >= end || depth > 32) { + ok = false; + return v; + } + if (*p == '{') { + ++p; + v.kind = Value::object; + if (eat('}')) return v; + do { + std::string name = text(); + if (!eat(':')) ok = false; + v.fields.emplace_back(std::move(name), value(depth + 1)); + } while (ok && eat(',')); + if (!eat('}')) ok = false; + } else if (*p == '[') { + ++p; + v.kind = Value::array; + if (eat(']')) return v; + do v.items.push_back(value(depth + 1)); + while (ok && eat(',')); + if (!eat(']')) ok = false; + } else if (*p == '"') { + v.kind = Value::string; + v.s = text(); + } else if (!std::strncmp(p, "true", 4) || !std::strncmp(p, "false", 5)) { + v.kind = Value::boolean; + v.b = *p == 't'; + p += v.b ? 4 : 5; + } else if (!std::strncmp(p, "null", 4)) { + p += 4; + } else { + char* stop = nullptr; + v.kind = Value::number; + v.n = std::strtod(p, &stop); + if (stop == p) ok = false; + p = stop; + } + return v; + } +}; + +struct Reader { + const Value& root; + std::string why; + const Value* field(const Value& v, const char* name, Value::Kind kind) + { + const Value* f = v.get(name); + if (!f || f->kind != kind) { + if (why.empty()) why = std::string("field ") + name; + return nullptr; + } + return f; + } + uint32_t u(const Value& v, const char* name) + { + const Value* f = field(v, name, Value::number); + return f ? static_cast(f->n) : 0; + } + float f(const Value& v, const char* name) + { + const Value* x = field(v, name, Value::number); + return x ? static_cast(x->n) : 0.0f; + } + bool b(const Value& v, const char* name) + { + const Value* x = field(v, name, Value::boolean); + return x && x->b; + } + const std::vector& list(const Value& v, const char* name) + { + static const std::vector none; + const Value* x = field(v, name, Value::array); + return x ? x->items : none; + } +}; + +uint32_t kind_code(const std::string& name, const char* const* names, uint32_t count, std::string& why) +{ + for (uint32_t i = 0; i < count; ++i) + if (name == names[i]) return i; + if (name.rfind("Other(", 0) == 0) return count + static_cast(std::strtoul(name.c_str() + 6, nullptr, 10)); + why = "kind " + name; + return 0; +} + +const char* const root_names[] = {"Constants", "Descriptor", "Table", "ImmediateSampler", "ResourceHeap", "SamplerHeap"}; +const char* const resource_names[] = {"Srv", "Sampler", "Cbv", "Uav"}; +const char* const stage_names[] = {"Ls", "Hs", "Es", "Gs", "Vs", "Ps", "Ms", "Cs"}; + +bool read_file(const std::wstring& path, std::string& out) +{ + std::ifstream f(path, std::ios::binary); + if (!f) return false; + std::ostringstream s; + s << f.rdbuf(); + out = s.str(); + return true; +} + +} // namespace + +bool record_from_json(const std::string& json, std::vector dxil, ShaderRecord& out, std::string& why) +{ + Parser parser{json.data(), json.data() + json.size()}; + const Value root = parser.value(); + if (!parser.ok || root.kind != Value::object) { + why = "not JSON"; + return false; + } + Reader r{root, {}}; + ShaderRecord s; + const Value* key = r.field(root, "key", Value::string); + const Value* fnv = r.field(root, "container_fnv64", Value::string); + const Value* stage = r.field(root, "stage", Value::string); + if (key) s.key = std::strtoull(key->s.c_str(), nullptr, 16); + if (fnv) s.fnv64 = std::strtoull(fnv->s.c_str(), nullptr, 16); + if (stage) s.stage = static_cast(kind_code(stage->s, stage_names, 8, r.why)); + if (stage && static_cast(s.stage) > 7 && r.why.empty()) r.why = "stage"; + s.container_bytes = r.u(root, "container_bytes"); + if (r.u(root, "dxil_bytes") != dxil.size() && r.why.empty()) r.why = "dxil_bytes disagrees with the .dxil file"; + s.dxil = std::move(dxil); + s.user_data_dwords = r.u(root, "user_data_dwords"); + for (const Value& u : r.list(root, "user_data")) { + const Value* root_kind = r.field(u, "root", Value::string); + s.user_data.push_back({r.u(u, "index"), r.u(u, "slot"), root_kind ? kind_code(root_kind->s, root_names, 6, r.why) : 0, r.u(u, "dword")}); + } + for (const Value& w : r.list(root, "samplers")) { + std::array words{}; + if (w.items.size() != 4 && r.why.empty()) r.why = "sampler words"; + for (std::size_t i = 0; i < 4 && i < w.items.size(); ++i) words[i] = static_cast(w.items[i].n); + s.samplers.push_back(words); + } + for (const Value& t : r.list(root, "static_samplers")) { + VxStaticSampler x{}; + x.filter = r.u(t, "filter"); + const auto& address = r.list(t, "address"); + for (std::size_t i = 0; i < 3 && i < address.size(); ++i) x.address[i] = static_cast(address[i].n); + x.mip_lod_bias = r.f(t, "mip_lod_bias"); + x.max_anisotropy = r.u(t, "max_anisotropy"); + x.comparison = r.u(t, "comparison"); + x.border = r.u(t, "border"); + x.min_lod = r.f(t, "min_lod"); + x.max_lod = r.f(t, "max_lod"); + s.static_samplers.push_back(x); + } + for (const Value& v : r.list(root, "root_cbvs")) s.root_cbvs.push_back(static_cast(v.n)); + for (const Value& v : r.list(root, "root_srvs")) s.root_srvs.push_back(static_cast(v.n)); + for (const Value& v : r.list(root, "root_uavs")) s.root_uavs.push_back(static_cast(v.n)); + for (const Value& v : r.list(root, "root_indexed_views")) + s.root_indexed_views.push_back({r.u(v, "table_slot"), r.u(v, "constant_slot"), r.u(v, "constant_dword"), r.u(v, "byte_offset"), r.u(v, "shift")}); + for (const Value& u : r.list(root, "used")) { + const Value* kind = r.field(u, "kind", Value::string); + const Value* root_kind = r.field(u, "root", Value::string); + s.used.push_back({kind ? kind_code(kind->s, resource_names, 4, r.why) : 0, root_kind ? kind_code(root_kind->s, root_names, 6, r.why) : 0, + r.u(u, "table_offset_dwords"), r.u(u, "lower_bound"), r.u(u, "stride"), r.u(u, "dwords"), r.u(u, "user_data"), + r.u(u, "slot")}); + } + const Value* threads = root.get("threads"); + if (threads && threads->kind == Value::array && threads->items.size() == 3) { + s.has_threads = true; + for (int i = 0; i < 3; ++i) s.threads[i] = static_cast(threads->items[i].n); + } + s.stores = r.b(root, "stores"); + s.stores_by_address = r.b(root, "stores_by_address"); + s.builder = r.b(root, "builder"); + if (const Value* native = root.get("derived_native"); native && native->kind == Value::object) { + s.wave_size = r.u(*native, "wave_size"); + s.vgprs = r.u(*native, "vgprs"); + } + if (!r.why.empty()) { + why = r.why; + return false; + } + out = std::move(s); + return true; +} + +bool read_gpu_export(const std::wstring& dir, GpuExport& out, std::size_t limit) +{ + std::string index; + if (!read_file(dir + L"\\index.tsv", index) || !read_file(dir + L"\\manifest.txt", out.manifest)) return false; + std::istringstream lines(index); + std::string line; + std::getline(lines, line); // header + while (std::getline(lines, line) && (!limit || out.rows.size() < limit)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + std::vector cols; + for (std::size_t at = 0;;) { + const std::size_t tab = line.find('\t', at); + cols.push_back(line.substr(at, tab == std::string::npos ? std::string::npos : tab - at)); + if (tab == std::string::npos) break; + at = tab + 1; + } + if (cols.size() < 2) continue; + const std::wstring stem = dir + L"\\" + std::wstring(cols[0].begin(), cols[0].end()); + std::string json, dxil; + std::string why; + ExportRow row; + if (!read_file(stem + L".json", json) || !read_file(stem + L".dxil", dxil)) why = "missing file"; + else if (record_from_json(json, std::vector(dxil.begin(), dxil.end()), row.record, why)) { + row.first_source = cols.back(); + const uint64_t key = row.record.key; + out.rows.emplace(key, std::move(row)); + continue; + } + out.errors.push_back(cols[0] + ": " + why); + } + return true; +} + +} // namespace shader_db diff --git a/src/shader_db/gpu_export.h b/src/shader_db/gpu_export.h new file mode 100644 index 0000000000..7ef0c87e9e --- /dev/null +++ b/src/shader_db/gpu_export.h @@ -0,0 +1,31 @@ +// Reads an exported shader directory containing index.tsv, manifest.txt, and a JSON record and DXIL file for each +// key. +#pragma once + +#include +#include +#include +#include + +#include "shader_db_writer.h" + +namespace shader_db { + +struct ExportRow { + ShaderRecord record; + std::string first_source; // first file containing the shader container +}; + +struct GpuExport { + std::map rows; // by key + std::string manifest; // manifest.txt as written + std::vector errors; // records that did not read +}; + +// Reads every record index.tsv names (`limit` records at most; 0 for all). +bool read_gpu_export(const std::wstring& dir, GpuExport& out, std::size_t limit = 0); + +// One record from its JSON text and DXIL bytes; false with `why` if a field is missing or of the wrong kind. +bool record_from_json(const std::string& json, std::vector dxil, ShaderRecord& out, std::string& why); + +} // namespace shader_db diff --git a/src/shader_db/shader_db.cpp b/src/shader_db/shader_db.cpp new file mode 100644 index 0000000000..766c5df608 --- /dev/null +++ b/src/shader_db/shader_db.cpp @@ -0,0 +1,257 @@ +// See shader_db.h. +#include "shader_db.h" + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "startup_stubs/blake3/blake3.h" + +namespace shader_db { +namespace { + +struct Db { + std::mutex lock; // open/close and the miss set; lookups after open read only + std::wstring path; + HANDLE file = INVALID_HANDLE_VALUE, mapping = nullptr; + const unsigned char* base = nullptr; + uint64_t bytes = 0; + const VxIndex* index = nullptr; + uint32_t count = 0; + std::vector shaders; // in index order + Manifest manifest{}; + MissLog log = nullptr; + std::unordered_set missed; +}; + +Db& db() +{ + static Db instance; + return instance; +} + +void say(MissLog log, const char* format, ...) +{ + char line[512]; + va_list args; + va_start(args, format); + std::vsnprintf(line, sizeof(line), format, args); + va_end(args); + if (log) log(line); +} + +bool in_file(uint64_t offset, uint64_t bytes, uint64_t total) { return offset <= total && bytes <= total - offset; } + +void unmap(Db& d) +{ + if (d.base) UnmapViewOfFile(d.base); + if (d.mapping) CloseHandle(d.mapping); + if (d.file != INVALID_HANDLE_VALUE) CloseHandle(d.file); + d.base = nullptr; + d.mapping = nullptr; + d.file = INVALID_HANDLE_VALUE; + d.index = nullptr; + d.count = 0; + d.shaders.clear(); + d.missed.clear(); + d.path.clear(); +} + +uint32_t number(const std::string& text, const char* name) +{ + const std::string key = std::string("\n") + name + " "; + const std::size_t at = ("\n" + text).find(key); + if (at == std::string::npos) return 0; + return static_cast(std::strtoul(text.c_str() + at + key.size() - 1, nullptr, 0)); +} + +void word(const std::string& text, const char* name, char* out, std::size_t capacity) +{ + out[0] = 0; + const std::string key = std::string("\n") + name + " "; + const std::size_t at = ("\n" + text).find(key); + if (at == std::string::npos) return; + std::size_t from = at + key.size() - 1, to = text.find('\n', from); + if (to == std::string::npos) to = text.size(); + const std::size_t n = std::min(to - from, capacity - 1); + std::memcpy(out, text.data() + from, n); + out[n] = 0; +} + +// Resolves one record; false if any array lies outside the file. +bool resolve(const unsigned char* base, uint64_t total, uint64_t offset, GpuShader& s) +{ + if (!in_file(offset, sizeof(VxRecord), total)) return false; + VxRecord r; + std::memcpy(&r, base + offset, sizeof(r)); + const auto array = [&](uint64_t at, uint64_t count, uint64_t size) { return in_file(at, count * size, total); }; + if (!array(r.dxil_offset, r.dxil_bytes, 1) || !array(r.user_data_offset, r.user_data_count, sizeof(VxUserData)) || + !array(r.samplers_offset, r.sampler_count, 16) || !array(r.static_samplers_offset, r.static_sampler_count, sizeof(VxStaticSampler)) || + !array(r.root_cbvs_offset, r.root_cbv_count, 1) || !array(r.root_srvs_offset, r.root_srv_count, 1) || + !array(r.root_uavs_offset, r.root_uav_count, 1) || + !array(r.root_indexed_views_offset, r.root_indexed_view_count, sizeof(VxRootIndexedView)) || + !array(r.used_offset, r.used_count, sizeof(VxUsed)) || r.stage > static_cast(Stage::cs)) + return false; + s.key = r.key; + s.fnv64 = r.fnv64; + s.stage = static_cast(r.stage); + s.container_bytes = r.container_bytes; + s.dxil = base + r.dxil_offset; + s.dxil_bytes = r.dxil_bytes; + s.user_data_dwords = r.user_data_dwords; + s.user_data = reinterpret_cast(base + r.user_data_offset); + s.user_data_count = r.user_data_count; + s.samplers = reinterpret_cast(base + r.samplers_offset); + s.sampler_count = r.sampler_count; + s.static_samplers = reinterpret_cast(base + r.static_samplers_offset); + s.static_sampler_count = r.static_sampler_count; + s.root_cbvs = base + r.root_cbvs_offset; + s.root_cbv_count = r.root_cbv_count; + s.root_srvs = base + r.root_srvs_offset; + s.root_srv_count = r.root_srv_count; + s.root_uavs = base + r.root_uavs_offset; + s.root_uav_count = r.root_uav_count; + s.root_indexed_views = reinterpret_cast(base + r.root_indexed_views_offset); + s.root_indexed_view_count = r.root_indexed_view_count; + s.used = reinterpret_cast(base + r.used_offset); + s.used_count = r.used_count; + s.has_threads = (r.flags & flag_threads) != 0; + std::memcpy(s.threads, r.threads, sizeof(s.threads)); + s.stores = (r.flags & flag_stores) != 0; + s.stores_by_address = (r.flags & flag_stores_by_address) != 0; + s.builder = (r.flags & flag_builder) != 0; + s.wave_size = r.wave_size; + s.vgprs = r.vgprs; + return true; +} + +} // namespace + +bool gpu_db_open(const wchar_t* path, uint32_t expected_view_heap_limit, uint32_t expected_raw_views, MissLog log) +{ + Db& d = db(); + std::lock_guard hold(d.lock); + if (d.base && d.path == path) return true; + unmap(d); + d.log = log; + d.file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + LARGE_INTEGER size{}; + if (d.file == INVALID_HANDLE_VALUE || !GetFileSizeEx(d.file, &size) || size.QuadPart < static_cast(sizeof(VxHeader))) { + say(log, "gpu-db: cannot open the database (error %lu)", GetLastError()); + unmap(d); + return false; + } + d.mapping = CreateFileMappingW(d.file, nullptr, PAGE_READONLY, 0, 0, nullptr); + d.base = d.mapping ? static_cast(MapViewOfFile(d.mapping, FILE_MAP_READ, 0, 0, 0)) : nullptr; + if (!d.base) { + say(log, "gpu-db: cannot map the database (error %lu)", GetLastError()); + unmap(d); + return false; + } + d.bytes = static_cast(size.QuadPart); + VxHeader h; + std::memcpy(&h, d.base, sizeof(h)); + if (std::memcmp(h.magic, "VXDB0001", 8) || h.version != 1 || h.file_bytes != d.bytes || + !in_file(h.index_offset, uint64_t(h.record_count) * sizeof(VxIndex), d.bytes) || + !in_file(h.manifest_offset, h.manifest_bytes, d.bytes)) { + say(log, "gpu-db: not a database of format 1, or truncated"); + unmap(d); + return false; + } + const std::string manifest(reinterpret_cast(d.base + h.manifest_offset), h.manifest_bytes); + Manifest& m = d.manifest; + m.max_wave = number(manifest, "max_wave"); + m.view_heap_limit = number(manifest, "view_heap_limit"); + m.raw_views = number(manifest, "raw_views"); + m.host_rdna = number(manifest, "host_rdna"); + m.loop_limit = number(manifest, "loop_limit"); + m.group_sync = number(manifest, "group_sync"); + m.shader_opt = number(manifest, "shader_opt"); + word(manifest, "build", m.build, sizeof(m.build)); + word(manifest, "commit", m.commit, sizeof(m.commit)); + word(manifest, "producer", m.producer, sizeof(m.producer)); + word(manifest, "X2W_SHADERCFG_HELPER_OWN", m.helper_own, sizeof(m.helper_own)); + word(manifest, "X2W_SHADERCFG_BVH_FENCES", m.bvh_fences, sizeof(m.bvh_fences)); + word(manifest, "X2W_SHADERCFG_BVH_BOUNDS", m.bvh_bounds, sizeof(m.bvh_bounds)); + if ((expected_view_heap_limit && m.view_heap_limit != expected_view_heap_limit) || + (expected_raw_views && m.raw_views != expected_raw_views)) { + say(log, "gpu-db: refused: made for view_heap_limit %u raw_views %u, this heap has %u and %u", m.view_heap_limit, + m.raw_views, expected_view_heap_limit, expected_raw_views); + unmap(d); + return false; + } + d.index = reinterpret_cast(d.base + h.index_offset); + d.count = h.record_count; + d.shaders.resize(d.count); + for (uint32_t i = 0; i < d.count; ++i) { + if ((i && d.index[i - 1].key >= d.index[i].key) || !resolve(d.base, d.bytes, d.index[i].record_offset, d.shaders[i]) || + d.shaders[i].key != d.index[i].key) { + say(log, "gpu-db: record %u is damaged or out of order", i); + unmap(d); + return false; + } + } + d.path = path; + say(log, "gpu-db: %u shaders, build %.16s, commit %.12s, view_heap_limit %u raw_views %u max_wave %u", d.count, m.build, + m.commit, m.view_heap_limit, m.raw_views, m.max_wave); + return true; +} + +void gpu_db_close() +{ + Db& d = db(); + std::lock_guard hold(d.lock); + unmap(d); +} + +const Manifest* gpu_db_manifest() { return db().base ? &db().manifest : nullptr; } +std::size_t gpu_db_count() { return db().count; } +const GpuShader* gpu_db_at(std::size_t i) { return i < db().count ? &db().shaders[i] : nullptr; } + +uint64_t gpu_key(const void* bytes, std::size_t n) +{ + blake3_hasher hasher; + blake3_hasher_init(&hasher); + blake3_hasher_update(&hasher, bytes, n); + uint8_t out[8]; + blake3_hasher_finalize(&hasher, out, sizeof(out)); + uint64_t key = 0; + for (uint8_t b : out) key = key << 8 | b; + return key; +} + +const GpuShader* gpu_shader_by_key(uint64_t key) +{ + const Db& d = db(); + if (!d.base) return nullptr; + const VxIndex* end = d.index + d.count; + const VxIndex* at = std::lower_bound(d.index, end, key, [](const VxIndex& e, uint64_t k) { return e.key < k; }); + return at != end && at->key == key ? &d.shaders[static_cast(at - d.index)] : nullptr; +} + +const GpuShader* gpu_shader(const void* bytes, std::size_t n, Stage stage) +{ + if (!bytes || !n) return nullptr; + const uint64_t key = gpu_key(bytes, n); + const GpuShader* found = gpu_shader_by_key(key); + if (found && (stage == Stage::any || found->stage == stage)) return found; + Db& d = db(); + std::lock_guard hold(d.lock); + if (d.missed.insert(key).second) + say(d.log, "gpu-db: miss key=%016llx bytes=%zu stage=%u%s", static_cast(key), n, + static_cast(stage), found ? " (recorded with another stage)" : ""); + return nullptr; +} + +} // namespace shader_db diff --git a/src/shader_db/shader_db.h b/src/shader_db/shader_db.h new file mode 100644 index 0000000000..d6d5c7dbcd --- /dev/null +++ b/src/shader_db/shader_db.h @@ -0,0 +1,108 @@ +// Precompiled shader database. Each record is keyed by the stage and the first eight bytes of BLAKE3 over the exact +// D3D12_SHADER_BYTECODE passed at pipeline creation, read as a big-endian u64. The FNV hash links the record to +// request files. +// +// The little-endian file contains a 64-byte VxHeader, VxIndex entries sorted by key, VxRecord entries, element +// arrays, DXIL containers and manifest text. Offsets are relative to the start of the file. Each record includes +// the translated shader and its thread dimensions, resource use and store flags. The reader rejects incompatible +// manifest settings, supports concurrent lookups after opening, and logs each missing key once. +#pragma once + +#include +#include + +namespace shader_db { + +// Hardware stage order in the serialized shader cache. +enum class Stage : uint32_t { ls = 0, hs = 1, es = 2, gs = 3, vs = 4, ps = 5, ms = 6, cs = 7, any = 0xffffffffu }; + +// Serialized root kinds: 0 Constants, 1 Descriptor, 2 Table, 3 ImmediateSampler, 4 ResourceHeap, 5 SamplerHeap, 6 + +// x Other(x). +enum RootKind : uint32_t { root_constants = 0, root_descriptor = 1, root_table = 2, root_immediate_sampler = 3, + root_resource_heap = 4, root_sampler_heap = 5, root_other_base = 6 }; +// Resource kinds of `used`: 0 Srv, 1 Sampler, 2 Cbv, 3 Uav, 4 + x Other(x). +enum ResourceKind : uint32_t { resource_srv = 0, resource_sampler = 1, resource_cbv = 2, resource_uav = 3, resource_other_base = 4 }; + +#pragma pack(push, 1) +struct VxHeader { + char magic[8]; // "VXDB0001" + uint32_t version, record_count; + uint64_t index_offset, manifest_offset; + uint32_t manifest_bytes, reserved; + uint64_t file_bytes; + uint8_t pad[16]; +}; +struct VxIndex { uint64_t key, record_offset; }; +struct VxUserData { uint32_t index, slot, root, dword; }; // dword `index` of b0 holds root parameter `slot`'s dword +struct VxStaticSampler { + uint32_t filter, address[3]; + float mip_lod_bias; + uint32_t max_anisotropy, comparison, border; + float min_lod, max_lod; +}; +struct VxRootIndexedView { uint32_t table_slot, constant_slot, constant_dword, byte_offset, shift; }; +struct VxUsed { uint32_t kind, root, table_offset_dwords, lower_bound, stride, dwords, user_data, slot; }; +enum : uint32_t { flag_stores = 1, flag_stores_by_address = 2, flag_builder = 4, flag_threads = 8 }; +struct VxRecord { + uint64_t key, fnv64; + uint32_t stage, container_bytes; + uint64_t dxil_offset; + uint32_t dxil_bytes, user_data_dwords; + uint32_t user_data_count, sampler_count, static_sampler_count, root_cbv_count; + uint32_t root_srv_count, root_uav_count, root_indexed_view_count, used_count; + uint64_t user_data_offset, samplers_offset, static_samplers_offset, root_cbvs_offset; + uint64_t root_srvs_offset, root_uavs_offset, root_indexed_views_offset, used_offset; + uint32_t threads[3], flags, wave_size, vgprs; +}; +#pragma pack(pop) +static_assert(sizeof(VxHeader) == 64, "header layout"); +static_assert(sizeof(VxRecord) == 160, "record layout"); +static_assert(sizeof(VxStaticSampler) == 40, "static sampler layout"); + +// A record with its arrays resolved (pointers into the mapped file; valid until gpu_db_close). +struct GpuShader { + uint64_t key, fnv64; + Stage stage; + uint32_t container_bytes; + const void* dxil; + std::size_t dxil_bytes; + uint32_t user_data_dwords; // root constants of the stage must cover this many dwords (b0, space 0) + const VxUserData* user_data; uint32_t user_data_count; + const uint32_t (*samplers)[4]; uint32_t sampler_count; // immediate samplers s, console words + const VxStaticSampler* static_samplers; uint32_t static_sampler_count; // the same decoded, s space 0 + const uint8_t* root_cbvs; uint32_t root_cbv_count; // root parameter indices, b in ROOT_CBV_SPACE + const uint8_t* root_srvs; uint32_t root_srv_count; // t in ROOT_CBV_SPACE (raw buffers) + const uint8_t* root_uavs; uint32_t root_uav_count; // u in ROOT_CBV_SPACE (raw buffers) + const VxRootIndexedView* root_indexed_views; uint32_t root_indexed_view_count; + const VxUsed* used; uint32_t used_count; + bool has_threads; uint32_t threads[3]; + bool stores, stores_by_address, builder; + uint32_t wave_size, vgprs; // of the console program (derived) +}; + +// The settings the export was made for (manifest.txt), as numbers; 0 when absent. +struct Manifest { + uint32_t max_wave, view_heap_limit, raw_views, host_rdna, loop_limit, group_sync, shader_opt; + // The X2W_SHADERCFG_* switches in the translation's key, as the export saw them (empty: unset). + char helper_own[16], bvh_fences[16], bvh_bounds[16]; + char build[65], commit[64], producer[32]; +}; + +using MissLog = void (*)(const char* line); + +// Maps `path`. Refuses (returns false, logs why) a file that is not a database, or whose manifest's view_heap_limit +// or raw_views differ from the expected values (pass 0 to skip a check). Idempotent for one path. +bool gpu_db_open(const wchar_t* path, uint32_t expected_view_heap_limit, uint32_t expected_raw_views, MissLog log); +void gpu_db_close(); +const Manifest* gpu_db_manifest(); +std::size_t gpu_db_count(); + +// C1 key of the bytes (BLAKE3, first 8 bytes big-endian). +uint64_t gpu_key(const void* bytes, std::size_t n); +// C5: the record for these bytes, or null (C6: the key is logged once). Stage::any skips the stage check. +const GpuShader* gpu_shader(const void* bytes, std::size_t n, Stage stage); +const GpuShader* gpu_shader_by_key(uint64_t key); +// Record i in key order, i < gpu_db_count(). +const GpuShader* gpu_db_at(std::size_t i); + +} // namespace shader_db diff --git a/src/shader_db/shader_db_writer.cpp b/src/shader_db/shader_db_writer.cpp new file mode 100644 index 0000000000..2731298b65 --- /dev/null +++ b/src/shader_db/shader_db_writer.cpp @@ -0,0 +1,162 @@ +// See shader_db_writer.h. +#include "shader_db_writer.h" + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include +#include + +namespace shader_db { + +uint64_t fnv64(const void* bytes, std::size_t n) +{ + uint64_t h = 1469598103934665603ull; + for (std::size_t i = 0; i < n; ++i) h = (h ^ static_cast(bytes)[i]) * 1099511628211ull; + return h; +} + +ShaderRecord copy_record(const GpuShader& s) +{ + ShaderRecord r; + r.key = s.key; + r.fnv64 = s.fnv64; + r.stage = s.stage; + r.container_bytes = s.container_bytes; + const auto* dxil = static_cast(s.dxil); + r.dxil.assign(dxil, dxil + s.dxil_bytes); + r.user_data_dwords = s.user_data_dwords; + r.user_data.assign(s.user_data, s.user_data + s.user_data_count); + for (uint32_t i = 0; i < s.sampler_count; ++i) r.samplers.push_back({s.samplers[i][0], s.samplers[i][1], s.samplers[i][2], s.samplers[i][3]}); + r.static_samplers.assign(s.static_samplers, s.static_samplers + s.static_sampler_count); + r.root_cbvs.assign(s.root_cbvs, s.root_cbvs + s.root_cbv_count); + r.root_srvs.assign(s.root_srvs, s.root_srvs + s.root_srv_count); + r.root_uavs.assign(s.root_uavs, s.root_uavs + s.root_uav_count); + r.root_indexed_views.assign(s.root_indexed_views, s.root_indexed_views + s.root_indexed_view_count); + r.used.assign(s.used, s.used + s.used_count); + r.has_threads = s.has_threads; + std::memcpy(r.threads, s.threads, sizeof(r.threads)); + r.stores = s.stores; + r.stores_by_address = s.stores_by_address; + r.builder = s.builder; + r.wave_size = s.wave_size; + r.vgprs = s.vgprs; + return r; +} + +namespace { + +struct Out { + std::vector bytes; + void align(std::size_t a) + { + while (bytes.size() % a) bytes.push_back(0); + } + uint64_t put(const void* data, std::size_t n, std::size_t a) + { + align(a); + const uint64_t at = bytes.size(); + const auto* p = static_cast(data); + bytes.insert(bytes.end(), p, p + n); + return at; + } + template + uint64_t put(const std::vector& v, std::size_t a = 8) + { + return put(v.data(), v.size() * sizeof(T), a); + } +}; + +} // namespace + +bool write_db(const std::wstring& path, std::vector records, const std::string& manifest, std::string& error) +{ + std::sort(records.begin(), records.end(), [](const ShaderRecord& a, const ShaderRecord& b) { return a.key < b.key; }); + for (std::size_t i = 1; i < records.size(); ++i) + if (records[i - 1].key == records[i].key) { + char text[64]; + std::snprintf(text, sizeof(text), "key %016llx twice", static_cast(records[i].key)); + error = text; + return false; + } + Out out; + out.bytes.resize(sizeof(VxHeader) + records.size() * sizeof(VxIndex)); + std::vector index(records.size()); + for (std::size_t i = 0; i < records.size(); ++i) { + const ShaderRecord& s = records[i]; + if (s.dxil.size() > 0xffffffffu) { + error = "a DXIL container over 4 GiB"; + return false; + } + out.align(8); + const uint64_t at = out.bytes.size(); + out.bytes.resize(at + sizeof(VxRecord)); + VxRecord r{}; + r.key = s.key; + r.fnv64 = s.fnv64; + r.stage = static_cast(s.stage); + r.container_bytes = s.container_bytes; + r.dxil_offset = out.put(s.dxil, 4); + r.dxil_bytes = static_cast(s.dxil.size()); + r.user_data_dwords = s.user_data_dwords; + r.user_data_count = static_cast(s.user_data.size()); + r.sampler_count = static_cast(s.samplers.size()); + r.static_sampler_count = static_cast(s.static_samplers.size()); + r.root_cbv_count = static_cast(s.root_cbvs.size()); + r.root_srv_count = static_cast(s.root_srvs.size()); + r.root_uav_count = static_cast(s.root_uavs.size()); + r.root_indexed_view_count = static_cast(s.root_indexed_views.size()); + r.used_count = static_cast(s.used.size()); + r.user_data_offset = out.put(s.user_data); + r.samplers_offset = out.put(s.samplers); + r.static_samplers_offset = out.put(s.static_samplers); + r.root_cbvs_offset = out.put(s.root_cbvs, 1); + r.root_srvs_offset = out.put(s.root_srvs, 1); + r.root_uavs_offset = out.put(s.root_uavs, 1); + r.root_indexed_views_offset = out.put(s.root_indexed_views); + r.used_offset = out.put(s.used); + std::memcpy(r.threads, s.threads, sizeof(r.threads)); + r.flags = (s.stores ? flag_stores : 0) | (s.stores_by_address ? flag_stores_by_address : 0) | (s.builder ? flag_builder : 0) | + (s.has_threads ? flag_threads : 0); + r.wave_size = s.wave_size; + r.vgprs = s.vgprs; + std::memcpy(out.bytes.data() + at, &r, sizeof(r)); + index[i] = {s.key, at}; + } + VxHeader h{}; + std::memcpy(h.magic, "VXDB0001", 8); + h.version = 1; + h.record_count = static_cast(records.size()); + h.index_offset = sizeof(VxHeader); + h.manifest_offset = out.put(manifest.data(), manifest.size(), 1); + h.manifest_bytes = static_cast(manifest.size()); + h.file_bytes = out.bytes.size(); + std::memcpy(out.bytes.data(), &h, sizeof(h)); + if (!index.empty()) std::memcpy(out.bytes.data() + sizeof(VxHeader), index.data(), index.size() * sizeof(VxIndex)); + + const std::wstring temporary = path + L".partial"; + HANDLE file = CreateFileW(temporary.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) { + error = "cannot create the database file"; + return false; + } + bool ok = true; + for (std::size_t done = 0; ok && done < out.bytes.size();) { + const DWORD chunk = static_cast(std::min(out.bytes.size() - done, 1u << 30)); + DWORD written = 0; + ok = WriteFile(file, out.bytes.data() + done, chunk, &written, nullptr) && written == chunk; + done += chunk; + } + ok = CloseHandle(file) && ok; + if (!ok || !MoveFileExW(temporary.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING)) { + DeleteFileW(temporary.c_str()); + error = "cannot write the database file"; + return false; + } + return true; +} + +} // namespace shader_db diff --git a/src/shader_db/shader_db_writer.h b/src/shader_db/shader_db_writer.h new file mode 100644 index 0000000000..e1a3311939 --- /dev/null +++ b/src/shader_db/shader_db_writer.h @@ -0,0 +1,41 @@ +// Writes X2W's shader database (shader_db.h layout): the records a translator made, one per container. +#pragma once + +#include +#include +#include +#include + +#include "shader_db.h" + +namespace shader_db { + +// One record with its arrays owned (what the writer takes and gpu_shader() can be copied back into). +struct ShaderRecord { + uint64_t key = 0, fnv64 = 0; + Stage stage = Stage::vs; + uint32_t container_bytes = 0; + std::vector dxil; + uint32_t user_data_dwords = 0; + std::vector user_data; + std::vector> samplers; + std::vector static_samplers; + std::vector root_cbvs, root_srvs, root_uavs; + std::vector root_indexed_views; + std::vector used; + bool has_threads = false; + uint32_t threads[3] = {0, 0, 0}; + bool stores = false, stores_by_address = false, builder = false; + uint32_t wave_size = 0, vgprs = 0; +}; + +ShaderRecord copy_record(const GpuShader& s); + +// Writes `records` (sorted by key here; a repeated key is an error) and `manifest` to `path`, through a temporary +// file renamed over it, so a reader never maps a partial database. +bool write_db(const std::wstring& path, std::vector records, const std::string& manifest, std::string& error); + +// X2W's fnv_bytes (d3d12_draw.inl: the FNV-1a prime, basis 1469598103934665603), kept in each record beside the key. +uint64_t fnv64(const void* bytes, std::size_t n); + +} // namespace shader_db diff --git a/src/shader_db/x2w_shaders.cpp b/src/shader_db/x2w_shaders.cpp new file mode 100644 index 0000000000..5533baa238 --- /dev/null +++ b/src/shader_db/x2w_shaders.cpp @@ -0,0 +1,460 @@ +// x2w_shaders --out [--jobs N] [--payload ] [--max-file BYTES] +// Finds shader containers, deduplicates by key, and translates each or reads its record from the supplied export. +// Writes x2w_shaders.vxdb, manifest.txt, index.tsv, sources.tsv and misses.tsv in the cache directory. +// +// x2w_shaders --compare [--limit N] [--list] +// Compares DXIL bytes and binding metadata. Reports the first differing disassembled function or container part, +// with counts by outcome, source module and function. Exit code 0 means all records match. +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "archive_scan.h" +#include "startup_stubs/blake3/blake3.h" +#include "shader_db_writer.h" +#include "shader_db.h" +#include "gpu_export.h" +#include "x2w_shaders_translate.h" + +#ifndef SDK_DXC_DIR +#define SDK_DXC_DIR L"" +#endif + +using namespace shader_db; +using Microsoft::WRL::ComPtr; + +namespace { + +std::wstring widen(const char* s) +{ + const int n = MultiByteToWideChar(CP_UTF8, 0, s, -1, nullptr, 0); + std::wstring out(n > 0 ? n - 1 : 0, L'\0'); + if (n > 1) MultiByteToWideChar(CP_UTF8, 0, s, -1, out.data(), n); + return out; +} + +std::string narrow(const std::wstring& s) +{ + const int n = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, nullptr, 0, nullptr, nullptr); + std::string out(n > 0 ? n - 1 : 0, '\0'); + if (n > 1) WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, out.data(), n, nullptr, nullptr); + return out; +} + +bool write_text(const std::wstring& path, const std::string& text) +{ + FILE* f = _wfopen(path.c_str(), L"wb"); + if (!f) return false; + const bool ok = std::fwrite(text.data(), 1, text.size(), f) == text.size(); + return std::fclose(f) == 0 && ok; +} + +std::string hex16(uint64_t v) +{ + char text[17]; + std::snprintf(text, sizeof(text), "%016llx", static_cast(v)); + return text; +} + +const char* stage_name(Stage s) +{ + static const char* names[] = {"Ls", "Hs", "Es", "Gs", "Vs", "Ps", "Ms", "Cs"}; + return static_cast(s) < 8 ? names[static_cast(s)] : "?"; +} + +// --------------------------------------------------------------------------------------------------------------- +// Dump + +struct Job { + uint64_t key; + std::vector bytes; +}; + +int dump(const std::vector& paths, const std::wstring& out_dir, unsigned jobs, const std::wstring& payload_dir, + uint64_t max_file) +{ + const Translator* translator = payload_dir.empty() ? builtin_translator() : nullptr; + GpuExport payload; + if (!payload_dir.empty()) { + if (!read_gpu_export(payload_dir, payload)) { + std::fprintf(stderr, "x2w_shaders: cannot read the export %s\n", narrow(payload_dir).c_str()); + return 2; + } + std::printf("payload: %zu records from the reference export (%zu unreadable)\n", payload.rows.size(), payload.errors.size()); + } else if (!translator) { + std::fprintf(stderr, "x2w_shaders: built without the translator (x2w_shader); pass --payload \n"); + return 2; + } + CreateDirectoryW(out_dir.c_str(), nullptr); + + std::mutex lock; + std::condition_variable wake; + std::deque queue; + bool done_scanning = false; + std::unordered_set seen; // deduplicate by full BLAKE3 + std::vector records; + std::vector sources, misses, index; + std::atomic translated{0}, failed{0}; + std::string file; + + const auto finish = [&](uint64_t key, const std::vector& bytes) { + ShaderRecord r; + std::string why; + bool ok = false; + if (translator) { + ok = translator->translate(bytes.data(), bytes.size(), r, why); + } else { + const auto found = payload.rows.find(key); + ok = found != payload.rows.end(); + if (ok) r = found->second.record; + else why = "not in the payload"; + } + r.key = key; + r.fnv64 = fnv64(bytes.data(), bytes.size()); + r.container_bytes = static_cast(bytes.size()); + std::lock_guard hold(lock); + if (!ok) { + for (char& c : why) + if (c == '\t' || c == '\n' || c == '\r') c = ' '; + misses.push_back(hex16(key) + "\t" + hex16(r.fnv64) + "\t" + std::to_string(bytes.size()) + "\t" + why); + ++failed; + return; + } + index.push_back(hex16(key) + "\t" + stage_name(r.stage) + "\t" + hex16(r.fnv64) + "\t" + std::to_string(bytes.size()) + "\t" + + std::to_string(r.dxil.size())); + records.push_back(std::move(r)); + ++translated; + }; + + std::vector workers; + for (unsigned i = 0; i < jobs; ++i) + workers.emplace_back([&] { + for (;;) { + Job job; + { + std::unique_lock hold(lock); + wake.wait(hold, [&] { return !queue.empty() || done_scanning; }); + if (queue.empty()) return; + job = std::move(queue.front()); + queue.pop_front(); + } + wake.notify_all(); + finish(job.key, job.bytes); + } + }); + + std::size_t containers = 0; + scan_paths( + paths, max_file, [&](const std::wstring& path) { file = narrow(path); }, + [&](const uint8_t* bytes, std::size_t n, const std::string& label) { + uint8_t full[32]; + blake3_hasher h; + blake3_hasher_init(&h); + blake3_hasher_update(&h, bytes, n); + blake3_hasher_finalize(&h, full, sizeof(full)); + uint64_t key = 0; + for (int i = 0; i < 8; ++i) key = key << 8 | full[i]; + std::unique_lock hold(lock); + sources.push_back(hex16(key) + "\t" + file + "\t" + label); + if (!seen.insert(std::string(reinterpret_cast(full), sizeof(full))).second) return; + ++containers; + wake.wait(hold, [&] { return queue.size() < 256; }); + queue.push_back({key, std::vector(bytes, bytes + n)}); + wake.notify_all(); + }); + { + std::lock_guard hold(lock); + done_scanning = true; + } + wake.notify_all(); + for (auto& w : workers) w.join(); + + // Two containers with the same 64-bit key: keep the first, report the rest as misses. + std::sort(records.begin(), records.end(), [](const ShaderRecord& a, const ShaderRecord& b) { return a.key < b.key; }); + for (std::size_t i = 1; i < records.size();) + if (records[i].key == records[i - 1].key) { + misses.push_back(hex16(records[i].key) + "\t" + hex16(records[i].fnv64) + "\t" + std::to_string(records[i].container_bytes) + + "\tkey collision"); + records.erase(records.begin() + static_cast(i)); + } else { + ++i; + } + + std::string manifest = "format gpu-x2w-1\nkey blake3-16 of the D3D12_SHADER_BYTECODE bytes\n"; + if (translator) { + manifest += std::string("producer ") + translator->name + "\n" + translator->settings(); + } else { + manifest += "producer gpu-export\n"; + // The settings the payload's translations were made with. + std::size_t at = 0; + while (at < payload.manifest.size()) { + std::size_t end = payload.manifest.find('\n', at); + if (end == std::string::npos) end = payload.manifest.size(); + const std::string line = payload.manifest.substr(at, end - at); + if (line.rfind("format ", 0) && line.rfind("key ", 0) && line.rfind("records ", 0) && !line.empty()) manifest += line + "\n"; + at = end + 1; + } + } + manifest += "records " + std::to_string(records.size()) + "\n"; + + std::string error; + const std::size_t written = records.size(); + if (!write_db(out_dir + L"\\x2w_shaders.vxdb", std::move(records), manifest, error)) { + std::fprintf(stderr, "x2w_shaders: %s\n", error.c_str()); + return 3; + } + const auto table = [](const char* header, std::vector lines) { + std::sort(lines.begin(), lines.end()); + std::string text = std::string(header) + "\n"; + for (const auto& l : lines) text += l + "\n"; + return text; + }; + write_text(out_dir + L"\\manifest.txt", manifest); + write_text(out_dir + L"\\index.tsv", table("key\tstage\tcontainer_fnv64\tcontainer_bytes\tdxil_bytes", index)); + write_text(out_dir + L"\\sources.tsv", table("key\tfile\tlabel", sources)); + write_text(out_dir + L"\\misses.tsv", table("key\tcontainer_fnv64\tcontainer_bytes\treason", misses)); + std::printf("%zu containers, %zu records written, %zu without a translation\n", containers, written, failed.load()); + return 0; +} + +// --------------------------------------------------------------------------------------------------------------- +// Compare + +struct Disassembler { + ComPtr compiler; + Disassembler() + { + HMODULE dll = LoadLibraryExW(SDK_DXC_DIR L"dxcompiler.dll", nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); + // X2W_DXC_DIR= when the build's SDK folder is not on this machine. + if (!dll) { + wchar_t dir[MAX_PATH]; + const DWORD n = GetEnvironmentVariableW(L"X2W_DXC_DIR", dir, MAX_PATH); + if (n && n < MAX_PATH) + dll = LoadLibraryExW((std::wstring(dir) + L"/dxcompiler.dll").c_str(), nullptr, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); + } + if (!dll) dll = LoadLibraryW(L"dxcompiler.dll"); + auto create = dll ? reinterpret_cast(GetProcAddress(dll, "DxcCreateInstance")) : nullptr; + if (create) create(CLSID_DxcCompiler, IID_PPV_ARGS(&compiler)); + } + bool text(const std::vector& dxil, std::string& out) const + { + if (!compiler) return false; + ComPtr result; + ComPtr blob; + DxcBuffer input{dxil.data(), dxil.size(), 0}; + HRESULT status = E_FAIL; + if (FAILED(compiler->Disassemble(&input, IID_PPV_ARGS(&result))) || FAILED(result->GetStatus(&status)) || FAILED(status) || + FAILED(result->GetOutput(DXC_OUT_DISASSEMBLY, IID_PPV_ARGS(&blob), nullptr)) || !blob) + return false; + out.assign(blob->GetStringPointer(), blob->GetStringLength()); + return true; + } +}; + +// The disassembly cut into named pieces: "define @name" bodies, and everything else as "module". +std::vector> pieces(const std::string& text) +{ + std::vector> out; + std::string module; + std::size_t at = 0; + while (at < text.size()) { + std::size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + const std::string line = text.substr(at, end - at); + if (line.rfind("define ", 0) == 0) { + const std::size_t name = line.find('@'), paren = line.find('(', name); + std::string body = line + "\n"; + at = end + 1; + while (at < text.size()) { + std::size_t e = text.find('\n', at); + if (e == std::string::npos) e = text.size(); + const std::string l = text.substr(at, e - at); + body += l + "\n"; + at = e + 1; + if (l == "}") break; + } + out.emplace_back(name == std::string::npos ? "?" : line.substr(name, paren - name), body); + continue; + } + // The disassembler prints the container's hash; it differs whenever anything does. + if (line.find("; shader hash:") == std::string::npos) module += line + "\n"; + at = end + 1; + } + out.emplace_back("module", module); + return out; +} + +// The first part (fourcc) of two DXBC containers that differs, or "container". +std::string first_part(const std::vector& a, const std::vector& b) +{ + const auto parts = [](const std::vector& c) { + std::map> out; + if (!dxbc_size(c.data(), c.size())) return out; + uint32_t count; + std::memcpy(&count, c.data() + 28, 4); + for (uint32_t i = 0; i < count; ++i) { + uint32_t offset, size; + std::memcpy(&offset, c.data() + 32 + 4 * i, 4); + std::memcpy(&size, c.data() + offset + 4, 4); + out[std::string(reinterpret_cast(c.data() + offset), 4)].assign(c.begin() + offset + 8, c.begin() + offset + 8 + size); + } + return out; + }; + const auto pa = parts(a), pb = parts(b); + for (const auto& [name, data] : pa) { + if (name == "HASH") continue; + const auto other = pb.find(name); + if (other == pb.end() || other->second != data) return "part " + name; + } + for (const auto& [name, data] : pb) + if (!pa.count(name)) return "part " + name; + return "container"; +} + +std::string metadata_difference(const ShaderRecord& a, const ShaderRecord& b) +{ + const auto bytes_equal = [](const auto& x, const auto& y) { + return x.size() == y.size() && (x.empty() || !std::memcmp(x.data(), y.data(), x.size() * sizeof(x[0]))); + }; + if (a.stage != b.stage) return "stage"; + if (a.user_data_dwords != b.user_data_dwords || !bytes_equal(a.user_data, b.user_data)) return "user_data"; + if (!bytes_equal(a.samplers, b.samplers)) return "samplers"; + if (!bytes_equal(a.static_samplers, b.static_samplers)) return "static_samplers"; + if (!bytes_equal(a.root_cbvs, b.root_cbvs)) return "root_cbvs"; + if (!bytes_equal(a.root_srvs, b.root_srvs)) return "root_srvs"; + if (!bytes_equal(a.root_uavs, b.root_uavs)) return "root_uavs"; + if (!bytes_equal(a.root_indexed_views, b.root_indexed_views)) return "root_indexed_views"; + if (!bytes_equal(a.used, b.used)) return "used"; + if (a.has_threads != b.has_threads || std::memcmp(a.threads, b.threads, sizeof(a.threads))) return "threads"; + if (a.stores != b.stores || a.stores_by_address != b.stores_by_address) return "stores"; + return {}; +} + +std::string module_of(const std::string& path) +{ + const std::size_t slash = path.find_last_of("\\/"); + return slash == std::string::npos ? path : path.substr(slash + 1); +} + +int compare(const std::wstring& export_dir, std::wstring ours, std::size_t limit, bool list) +{ + GpuExport oracle; + if (!read_gpu_export(export_dir, oracle, limit)) { + std::fprintf(stderr, "x2w_shaders: cannot read the export %s\n", narrow(export_dir).c_str()); + return 2; + } + if (GetFileAttributesW(ours.c_str()) & FILE_ATTRIBUTE_DIRECTORY) ours += L"\\x2w_shaders.vxdb"; + if (!gpu_db_open(ours.c_str(), 0, 0, [](const char* line) { std::fprintf(stderr, "%s\n", line); })) return 2; + const Disassembler dis; + if (!dis.compiler) std::fprintf(stderr, "x2w_shaders: no dxcompiler.dll; DXIL differences are named by container part only\n"); + std::map outcomes, functions; + std::map> modules; + std::size_t mismatches = 0; + for (const auto& [key, row] : oracle.rows) { + const GpuShader* found = gpu_shader_by_key(key); + std::string outcome, detail; + if (!found) { + outcome = "missing"; + } else { + const ShaderRecord mine = copy_record(*found); + if (mine.dxil != row.record.dxil) { + outcome = "dxil differs"; + std::string a, b; + if (dis.text(row.record.dxil, a) && dis.text(mine.dxil, b)) { + const auto pa = pieces(a), pb = pieces(b); + for (std::size_t i = 0; i < std::max(pa.size(), pb.size()) && detail.empty(); ++i) + if (i >= pa.size() || i >= pb.size() || pa[i] != pb[i]) detail = i < pa.size() ? pa[i].first : pb[i].first; + if (detail.empty()) detail = first_part(row.record.dxil, mine.dxil); + } else { + detail = first_part(row.record.dxil, mine.dxil); + } + ++functions[detail]; + } else if (const std::string field = metadata_difference(row.record, mine); !field.empty()) { + outcome = "metadata differs"; + detail = field; + } else { + outcome = "identical"; + } + } + ++outcomes[outcome]; + ++modules[module_of(row.first_source)][outcome]; + if (outcome != "identical") { + ++mismatches; + if (list) std::printf("%s\t%s\t%s\t%s\n", hex16(key).c_str(), outcome.c_str(), detail.c_str(), module_of(row.first_source).c_str()); + } + } + std::printf("compared %zu reference records (%zu unreadable) with %zu of ours\n", oracle.rows.size(), oracle.errors.size(), gpu_db_count()); + for (const auto& [name, n] : outcomes) std::printf(" %-18s %zu\n", name.c_str(), n); + std::printf("by module:\n"); + for (const auto& [module, counts] : modules) { + std::printf(" %s:", module.c_str()); + for (const auto& [name, n] : counts) std::printf(" %s %zu;", name.c_str(), n); + std::printf("\n"); + } + if (!functions.empty()) { + std::printf("first differing function or part:\n"); + std::vector> sorted; + for (const auto& [name, n] : functions) sorted.emplace_back(n, name); + std::sort(sorted.rbegin(), sorted.rend()); + for (const auto& [n, name] : sorted) std::printf(" %6zu %s\n", n, name.c_str()); + } + gpu_db_close(); + return mismatches ? 1 : 0; +} + +int usage() +{ + std::fprintf(stderr, + "usage: x2w_shaders --out [--jobs N] [--payload ] [--max-file BYTES]\n" + " x2w_shaders --compare [--limit N] [--list]\n"); + return 2; +} + +} // namespace + +int wmain(int argc, wchar_t** argv) +{ + std::vector paths; + std::wstring out, payload, oracle, ours; + unsigned jobs = std::max(1u, std::thread::hardware_concurrency()); + uint64_t max_file = 2ull << 30; // default maximum input size + std::size_t limit = 0; + bool list = false; + for (int i = 1; i < argc; ++i) { + const std::wstring a = argv[i]; + const bool more = i + 1 < argc; + if (a == L"--out" && more) out = argv[++i]; + else if (a == L"--payload" && more) payload = argv[++i]; + else if (a == L"--jobs" && more) jobs = std::max(1, _wtoi(argv[++i])); + else if (a == L"--max-file" && more) max_file = _wcstoui64(argv[++i], nullptr, 0); + else if (a == L"--limit" && more) limit = static_cast(_wtoi64(argv[++i])); + else if (a == L"--list") list = true; + else if (a == L"--compare" && i + 2 < argc) { + oracle = argv[++i]; + ours = argv[++i]; + } else if (a.rfind(L"--", 0) == 0) return usage(); + else paths.push_back(a); + } + if (!oracle.empty()) return compare(oracle, ours, limit, list); + if (paths.empty() || out.empty()) return usage(); + return dump(paths, out, jobs, payload, max_file); +} diff --git a/src/shader_db/x2w_shaders_no_translator.cpp b/src/shader_db/x2w_shaders_no_translator.cpp new file mode 100644 index 0000000000..f5849d6c2b --- /dev/null +++ b/src/shader_db/x2w_shaders_no_translator.cpp @@ -0,0 +1,9 @@ +// x2w_shaders without the C++ translator port: builtin_translator() is null. When library x2w_shader exists, +// CMake builds x2w_shaders_vs.cpp in place of this file, which adapts x2w::vs::translate to Translator. +#include "x2w_shaders_translate.h" + +namespace shader_db { + +const Translator* builtin_translator() { return nullptr; } + +} // namespace shader_db diff --git a/src/shader_db/x2w_shaders_translate.h b/src/shader_db/x2w_shaders_translate.h new file mode 100644 index 0000000000..0bd1782f5d --- /dev/null +++ b/src/shader_db/x2w_shaders_translate.h @@ -0,0 +1,24 @@ +// When linked, x2w_shader supplies the per-container translator. Otherwise the tool reads translated records from +// the supplied export. +#pragma once + +#include +#include +#include + +#include "shader_db_writer.h" + +namespace shader_db { + +struct Translator { + const char* name; // written to the manifest as `producer` + // Fills every field of `out` but key, fnv64 and container_bytes (the caller's), or returns false with `why`. + bool (*translate)(const uint8_t* container, std::size_t n, ShaderRecord& out, std::string& why); + // Manifest lines (name value\n) for the settings the translations depend on. + std::string (*settings)(); +}; + +// The built-in translator, or null when the tool was built without x2w_shader. +const Translator* builtin_translator(); + +} // namespace shader_db diff --git a/src/shader_db/x2w_shaders_vs.cpp b/src/shader_db/x2w_shaders_vs.cpp new file mode 100644 index 0000000000..09f1b18372 --- /dev/null +++ b/src/shader_db/x2w_shaders_vs.cpp @@ -0,0 +1,70 @@ +// Adapts x2w::vs::translate to shader_db::Translator. Each container uses the same translation and JSON encoding as +// the shader dump command, then record_from_json reads its metadata. Probe the host before translating because wave +// sizes, RDNA capabilities and view-heap layout affect output. +#include +#include +#include +#include + +#include "tools/x2w/scan.h" +#include "tools/x2w/shaders_dump.h" +#include "gpu_export.h" +#include "x2w_shaders_translate.h" + +namespace shader_db { +namespace { + +std::once_flag probed; + +void probe() { + std::call_once(probed, [] { x2w::tool::probe_host(); }); +} + +bool translate(const uint8_t* container, std::size_t n, ShaderRecord& out, std::string& why) { + probe(); + x2w::tool::Found f; + f.bytes = x2w::tool::bounded(x2w::tool::Bytes(container, n)); + f.full = x2w::tool::blake3(f.bytes); + f.key = x2w::tool::key_of(f.full); + f.name = x2w::tool::hex16(f.key); + f.fnv = x2w::tool::fnv64(f.bytes); + x2w::tool::Made m; + try { + m = x2w::tool::make(f); + } catch (const std::exception& e) { + // Keep translating the remaining containers if this one fails. + why = std::string("panic: ") + e.what(); + return false; + } + if (m.failed) { + why = *m.failed; + return false; + } + return record_from_json(m.json, std::move(m.dxil), out, why); +} + +// The manifest lines of `x2w shaders` that name the translator and the host settings. +std::string settings() { + probe(); + const std::string all = x2w::tool::manifest(0); + std::string out; + std::size_t at = 0; + while (at < all.size()) { + std::size_t end = all.find('\n', at); + if (end == std::string::npos) end = all.size(); + const std::string line = all.substr(at, end - at); + if (!line.empty() && line.rfind("format ", 0) && line.rfind("key ", 0) && line.rfind("records ", 0) && + line.rfind("producer ", 0) && line.rfind("cache ", 0)) + out += line + "\n"; + at = end + 1; + } + return out; +} + +const Translator x2w_vs{"x2w-shader-port", translate, settings}; + +} // namespace + +const Translator* builtin_translator() { return &x2w_vs; } + +} // namespace shader_db diff --git a/src/startup_stubs/LICENSE-GPL-3.0.txt b/src/startup_stubs/LICENSE-GPL-3.0.txt new file mode 100644 index 0000000000..f288702d2f --- /dev/null +++ b/src/startup_stubs/LICENSE-GPL-3.0.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/src/startup_stubs/THIRD_PARTY_NOTICES.md b/src/startup_stubs/THIRD_PARTY_NOTICES.md index def6537e70..01a015bfb5 100644 --- a/src/startup_stubs/THIRD_PARTY_NOTICES.md +++ b/src/startup_stubs/THIRD_PARTY_NOTICES.md @@ -54,3 +54,16 @@ https://datatracker.ietf.org/ipr/1914/ Broadcom Corporation: https://datatracker.ietf.org/ipr/1526/ ``` + +## Shader translator and GPU runtime + +Portions of the shader translator, GPU runtime, and corresponding tests use code +from the upstream shader and GPU crates. The upstream workspace at revision +`e9f435f9821ee8e03316367766c1551438aafec5` identifies its license as +`GPL-3.0-or-later`. See [the license text](LICENSE-GPL-3.0.txt). +File-specific notices, including the Valve notice in the GFX10 opcode table, +also apply. + +The screen-probe light replacement and depth-based crease shading are credited +to beloooo (06031237, 4f45ab88, cd9f78ce). Revisions 82ca134, 7da523a, and +81ebb7b document the radiance estimate, air-light bounds, and probe filtering. diff --git a/src/startup_stubs/bc_bind_trace.inl b/src/startup_stubs/bc_bind_trace.inl new file mode 100644 index 0000000000..5010d8ac31 --- /dev/null +++ b/src/startup_stubs/bc_bind_trace.inl @@ -0,0 +1,109 @@ +// Correlate recorded BC copy destinations with SRVs the binding path actually uses. +// Store identities only. The trace never holds a resource alive or selects a descriptor. +namespace bc_bind_trace { +bool enabled() +{ + static const bool on = x2w_local::env_on("X2W_GPU_BC_BIND_TRACE"); + return on; +} + +struct Writer { + ID3D12Resource* host{}; + const Wrapper* wrapper{}; + const Wrapper* list{}; + u64 address{}, span{}; + D3D12_RESOURCE_DESC desc{}; + UINT sub{}; + LONG frame{}; + bool submitted{}; +}; +struct Match { + ID3D12Resource* writer{}; + ID3D12Resource* reader{}; + u64 write_address{}, read_address{}; + bool submitted{}; + bool operator==(const Match& other) const { + return writer == other.writer && reader == other.reader && write_address == other.write_address && + read_address == other.read_address && submitted == other.submitted; + } +}; + +std::mutex mutex; +std::vector writers; +std::vector same, different; +std::vector> pending; +std::atomic generation{1}; +constexpr size_t limit = 128; + +void copied(Wrapper* list, Wrapper* wrapper, ID3D12Resource* host, UINT sub) +{ + const auto* info = resource_info(wrapper); + if (!info) return; + const auto address = reinterpret_cast(wrapper->own().title_memory); + const auto& d = info->console; + const auto layout = detile_layout(d); + // An exact base still matches when the title layout has no known footprint. + const auto span = layout.valid ? layout.size : 1; + std::lock_guard guard(mutex); + size_t index = 0; + while (index < writers.size() && !(writers[index].host == host && writers[index].address == address && + writers[index].wrapper == wrapper)) ++index; + if (index == limit) return; + if ((index == writers.size() || !writers[index].submitted) && pending.size() < 4 * limit) { + const auto key = std::make_pair(static_cast(list), index); + if (std::find(pending.begin(), pending.end(), key) == pending.end()) pending.push_back(key); + } + if (index < writers.size()) return; + + writers.push_back({host, wrapper, list, address, span, d, sub, frame_number, false}); + generation.fetch_add(1, std::memory_order_release); + log("x2w-bc copied frame=%ld list=%p title=0x%llx host=%p wrapper=%p span=%llu sub=%u " + "size=%llux%ux%u mips=%u fmt=%u layout=0x%x flags=0x%x", + frame_number, list, address, host, wrapper, span, sub, d.Width, d.Height, d.DepthOrArraySize, + d.MipLevels, unsigned(d.Format), unsigned(d.Layout), unsigned(d.Flags)); +} + +void close_recording(const Wrapper* list, bool submitted) +{ + std::lock_guard guard(mutex); + pending.erase(std::remove_if(pending.begin(), pending.end(), [&](const auto& record) { + if (record.first != list) return false; + auto& w = writers[record.second]; + if (submitted && !w.submitted) { + w.submitted = true; + generation.fetch_add(1, std::memory_order_release); + log("x2w-bc submitted frame=%ld list=%p title=0x%llx host=%p", frame_number, list, w.address, w.host); + } + return true; + }), pending.end()); +} +void read(const Wrapper* list, const Wrapper* resource, ID3D12Resource* host, const D3D12_RESOURCE_DESC& rd) +{ + if (!resource || resource->own().kind != resource_kind) return; + const auto address = reinterpret_cast(resource->own().title_memory); + struct Recent { u64 generation{}, address{}; ID3D12Resource* host{}; }; + static thread_local std::array recent{}; + auto& entry = recent[((address >> 16) ^ (reinterpret_cast(host) >> 4)) % recent.size()]; + const auto epoch = generation.load(std::memory_order_acquire); + if (entry.generation == epoch && entry.host == host && entry.address == address) return; + entry = {epoch, address, host}; + std::lock_guard guard(mutex); + for (const auto& w : writers) { + const bool identical = w.host == host; + if (!identical && (!w.address || address < w.address || address - w.address >= w.span)) continue; + auto& seen = identical ? same : different; + const Match match{w.host, host, w.address, address, w.submitted}; + if (seen.size() == limit || std::find(seen.begin(), seen.end(), match) != seen.end()) continue; + seen.push_back(match); + const auto* info = resource_info(resource); + const auto& d = info ? info->console : rd; + log("x2w-bc bound frame=%ld list=%p same_host=%u submitted=%u copied_frame=%ld write_title=0x%llx " + "write_host=%p read_title=0x%llx read_host=%p wrapper=%p size=%llux%ux%u mips=%u fmt=%u layout=0x%x " + "flags=0x%x proxy=%u detiled=%u partial=%u", + frame_number, list, unsigned(identical), unsigned(w.submitted), w.frame, w.address, w.host, address, host, + resource, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels, unsigned(d.Format), unsigned(d.Layout), + unsigned(d.Flags), unsigned(resource->own().linear_memory_srv), unsigned(resource->own().detiled_memory_srv), + unsigned(resource->own().partial_mip_srv)); + } +} +} // namespace bc_bind_trace diff --git a/src/startup_stubs/bcpack_bc6h.h b/src/startup_stubs/bcpack_bc6h.h new file mode 100644 index 0000000000..efa39fcfcf --- /dev/null +++ b/src/startup_stubs/bcpack_bc6h.h @@ -0,0 +1,318 @@ +#pragma once + +#include +#include +#include + +#include "bcpack_decoder.h" + +namespace x2w_bcpack { +namespace bc6h { + +struct Mode { + uint8_t code, code_bits, base_bits, delta_bits[3]; + bool transformed, two_regions; +}; + +// Spec modes 1..14, in the order lane 15 (E) numbers them. +inline constexpr Mode MODES[14] = { + { 0x00, 2, 10, { 5, 5, 5 }, true, true }, + { 0x01, 2, 7, { 6, 6, 6 }, true, true }, + { 0x02, 5, 11, { 5, 4, 4 }, true, true }, + { 0x06, 5, 11, { 4, 5, 4 }, true, true }, + { 0x0a, 5, 11, { 4, 4, 5 }, true, true }, + { 0x0e, 5, 9, { 5, 5, 5 }, true, true }, + { 0x12, 5, 8, { 6, 5, 5 }, true, true }, + { 0x16, 5, 8, { 5, 6, 5 }, true, true }, + { 0x1a, 5, 8, { 5, 5, 6 }, true, true }, + { 0x1e, 5, 6, { 6, 6, 6 }, false, true }, + { 0x03, 5, 10, { 10, 10, 10 }, false, false }, + { 0x07, 5, 11, { 9, 9, 9 }, true, false }, + { 0x0b, 5, 12, { 8, 8, 8 }, true, false }, + { 0x0f, 5, 16, { 4, 4, 4 }, true, false }, +}; + +// Endpoint bits after the mode bits, low to high: (endpoint << 6) | (channel << 4) | bit, endpoints +// w x y z = 0..3, channels R G B = 0..2. From the BC6H block layout; checked (UF16) against an +// independent decoder on random blocks of every mode. +inline constexpr uint8_t LAYOUT_BITS[14] = { 75, 75, 72, 72, 72, 72, 72, 72, 72, 72, 60, 60, 60, 60 }; +inline constexpr uint8_t LAYOUT[14][75] = { + { 0x94, 0xa4, 0xe4, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, + 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x40, 0x41, 0x42, 0x43, 0x44, 0xd4, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, + 0xe0, 0xd0, 0xd1, 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0xe1, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, + 0x81, 0x82, 0x83, 0x84, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xe3 }, + { 0x95, 0xd4, 0xd5, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xe0, 0xe1, 0xa4, 0x10, 0x11, 0x12, + 0x13, 0x14, 0x15, 0x16, 0xa5, 0xe2, 0x94, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0xe3, 0xe5, + 0xe4, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, + 0x55, 0xd0, 0xd1, 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, + 0x81, 0x82, 0x83, 0x84, 0x85, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x0a, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x1a, 0xe0, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x2a, 0xe1, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0x84, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xe3 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x0a, 0xd4, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, 0x1a, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x2a, 0xe1, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0xe0, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0x94, 0xe3 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x0a, 0xa4, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x1a, 0xe0, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0x2a, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0xe1, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0xe4, 0xe3 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0xa4, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x94, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0xe4, 0x40, 0x41, + 0x42, 0x43, 0x44, 0xd4, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, 0xe0, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0xe1, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0x84, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xe3 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xd4, 0xa4, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0xe2, 0x94, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0xe3, 0xe4, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x45, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, 0xe0, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0xe1, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0x84, 0x85, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xe0, 0xa4, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x95, 0x94, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0xd5, 0xe4, 0x40, 0x41, + 0x42, 0x43, 0x44, 0xd4, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0xe1, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0x84, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xe3 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xe1, 0xa4, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0xa5, 0x94, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0xe5, 0xe4, 0x40, 0x41, + 0x42, 0x43, 0x44, 0xd4, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, 0xe0, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0x84, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xe3 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0xd4, 0xe0, 0xe1, 0xa4, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x95, 0xa5, 0xe2, 0x94, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0xd5, 0xe3, 0xe5, 0xe4, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x45, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0x84, 0x85, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x58, 0x59, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x0a, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x58, 0x1a, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x2a }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x0b, 0x0a, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x1b, 0x1a, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x2b, 0x2a }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x50, 0x51, 0x52, 0x53, 0x1f, 0x1e, 0x1d, 0x1c, + 0x1b, 0x1a, 0x60, 0x61, 0x62, 0x63, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a }, +}; + +// Second anchor of the 32 two-region partitions (the first 32 of BC7's ANCHOR_2). +inline uint8_t anchor2(uint8_t part) { return ANCHOR_2[part & 31]; } + +struct Fields { + uint8_t mode = 0, part = 0; + uint16_t ep[4][3] = {}; // field values as the BC6H spec numbers their bits (LAYOUT places them) + uint8_t idx[16] = {}; +}; + +inline uint8_t field_bits(const Mode& m, int e, int c) { + return (e == 0 || !m.transformed) ? m.base_bits : m.delta_bits[c]; +} + +inline void pack(const Fields& f, uint8_t* out) { + const Mode& m = MODES[f.mode]; + BitWriter128 w; + w.put(m.code, m.code_bits); + for (int k = 0; k < LAYOUT_BITS[f.mode]; ++k) { + const uint8_t t = LAYOUT[f.mode][k]; + w.put((f.ep[t >> 6][(t >> 4) & 3] >> (t & 15)) & 1u, 1); + } + if (m.two_regions) { + w.put(f.part & 31u, 5); + const uint8_t a2 = anchor2(f.part); + for (int p = 0; p < 16; ++p) w.put(f.idx[p], (p == 0 || p == a2) ? 2 : 3); + } else { + for (int p = 0; p < 16; ++p) w.put(f.idx[p], p == 0 ? 3 : 4); + } + w.write_to(out); +} + +struct State { + uint16_t ep[4][3]; + uint8_t ix[16]; +}; + +// Optional dictionary (255 slots; slot = reference - block - 1 for a reference past the stream +// start). A null pointer or a false *_known entry means unknown. None ships in the tree. +struct Dictionary { + const uint16_t (*ep)[4][3] = nullptr; + const bool* ep_known = nullptr; + const uint8_t (*ix)[16] = nullptr; + const bool* ix_known = nullptr; +}; + +struct Stats { + size_t blocks = 0; + size_t exact = 0; // both chains known + size_t endpoints_only = 0; // endpoints known, flat indices + size_t copied = 0; // endpoints from the nearest known block, flat indices + size_t constant = 0; // stream without any known endpoints +}; + +inline uint32_t il8(uint16_t e, uint16_t o) { + uint32_t v = 0; + for (int k = 0; k < 8; ++k) v |= ((e >> k) & 1u) << (2 * k) | ((o >> k) & 1u) << (2 * k + 1); + return v; +} + +inline uint32_t rev_hi(uint32_t v, uint32_t bits) { + if (bits <= 11) return v; + const uint32_t k = bits - 10, hi = (v >> 10) & ((1u << k) - 1); + uint32_t r = 0; + for (uint32_t j = 0; j < k; ++j) r |= ((hi >> j) & 1u) << (k - 1 - j); + return (v & 1023u) | (r << 10); +} + +inline uint32_t wrap(int32_t v, uint32_t bits) { return static_cast(v) & ((1u << bits) - 1); } + +// UF16 half 0x2000 (2^-7) as a mode-13 base; the same bits read as SF16 give 2.0. +inline constexpr uint16_t DEFAULT_FILL_BASE = 16913; + +// fill_base: mode-13 base value for the constant block (0 = zero block). copy_known = false sends every +// unknown-endpoint block to the constant block instead of copying a known block's endpoints. +// Returns false only on a malformed symbol stream (a mode code outside 0..13). +inline bool decode_blocks(const std::vector& symbols, size_t nb, uint8_t* out, size_t cap, + Stats* stats, const Dictionary* dict = nullptr, uint16_t fill_base = DEFAULT_FILL_BASE, + bool copy_known = true) { + if (cap < nb * 16) return false; + const size_t t = nb * 2; + auto sym = [&](int lane, size_t i, int h) -> uint16_t { return symbols[lane * t + 2 * i + h]; }; + std::vector st(nb); + std::vector fl(nb); + std::vector kep(nb), kix(nb); + static constexpr State HALF = { { { 0x8000, 0x8000, 0x8000 }, { 0x8000, 0x8000, 0x8000 }, + { 0x8000, 0x8000, 0x8000 }, { 0x8000, 0x8000, 0x8000 } }, + { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 } }; + for (size_t i = 0; i < nb; ++i) { + const size_t x = interleave(sym(1, i, 0), sym(1, i, 1)); + const size_t er = static_cast((static_cast(x) + unzigzag(interleave(sym(0, i, 0), sym(0, i, 1)))) & 0xFF); + const size_t xr = x; + const uint16_t (*pe)[3] = HALF.ep; + const uint8_t* pq = HALF.ix; + bool ke = true, kx = true; + if (er != 0 && er <= i) { pe = st[i - er].ep; ke = kep[i - er]; } + else if (er > i) { + const size_t s = er - i - 1; + if (dict && dict->ep && dict->ep_known && dict->ep_known[s]) pe = dict->ep[s]; + else ke = false; + } + if (xr != 0 && xr <= i) { pq = st[i - xr].ix; kx = kix[i - xr]; } + else if (xr > i) { + const size_t s = xr - i - 1; + if (dict && dict->ix && dict->ix_known && dict->ix_known[s]) pq = dict->ix[s]; + else kx = false; + } + const uint16_t mode = sym(15, i, 0); + if (mode >= 14) return false; + const Mode& m = MODES[mode]; + Fields& f = fl[i]; + State& s = st[i]; + std::memcpy(s.ep, pe, sizeof s.ep); + f.mode = static_cast(mode); + f.part = m.two_regions ? static_cast(sym(15, i, 1) & 31) : 0; + const int ne = m.two_regions ? 4 : 2; + for (int e = 0; e < ne; ++e) { + for (int c = 0; c < 3; ++c) { + const uint32_t w = field_bits(m, e, c); + const uint32_t raw = e < 2 ? il8(sym(2 + 3 * e + c, i, 0), sym(2 + 3 * e + c, i, 1)) + : sym(8 + c, i, e - 2); + const uint32_t v = wrap(static_cast(pe[e][c] >> (16 - w)) + unzigzag(static_cast(raw)), w); + s.ep[e][c] = static_cast(v << (16 - w)); + f.ep[e][c] = static_cast(e == 0 ? rev_hi(v, m.base_bits) : v); + } + } + if (!m.two_regions) { + for (int c = 0; c < 3; ++c) { + s.ep[2][c] = m.transformed + ? static_cast(((static_cast(s.ep[0][c] >> (16 - m.base_bits)) << (16 - m.delta_bits[c])) & 0xFFFF) ^ 0x8000) + : s.ep[0][c]; + s.ep[3][c] = s.ep[1][c]; + } + } + const uint32_t ib = m.two_regions ? 3 : 4; + for (int k = 0; k < 4; ++k) { + for (int h = 0; h < 2; ++h) { + const uint16_t sv = sym(11 + k, i, h); + uint32_t ev = 0, od = 0; + for (uint32_t j = 0; j < ib; ++j) { + ev |= ((sv >> (2 * j)) & 1u) << j; + od |= ((sv >> (2 * j + 1)) & 1u) << j; + } + const uint32_t left = k < 3 ? od : ev, right = k < 3 ? ev : od; + const int p0 = 4 * k + 2 * h; + const uint32_t d[2] = { left, right }; + for (int q = 0; q < 2; ++q) { + const uint32_t v = wrap(static_cast(pq[p0 + q] >> (4 - ib)) + unzigzag(static_cast(d[q])), ib); + s.ix[p0 + q] = static_cast(v << (4 - ib)); + f.idx[p0 + q] = static_cast(v); + } + } + } + kep[i] = ke; + kix[i] = kx; + } + + Stats local; + local.blocks = nb; + auto flat = [](Fields& f) { + const uint8_t v = MODES[f.mode].two_regions ? 3 : 7; // anchors stay legal + std::memset(f.idx, v, sizeof f.idx); + }; + // nearest endpoint-known block in stream order (a tie takes the earlier one) + std::vector nearest(nb, -1); + int64_t last = -1; + for (size_t i = 0; i < nb; ++i) { if (kep[i]) last = static_cast(i); nearest[i] = last; } + last = -1; + for (size_t i = nb; i-- > 0;) { + if (kep[i]) last = static_cast(i); + const int64_t at = static_cast(i); + if (last >= 0 && (nearest[i] < 0 || last - at < at - nearest[i])) nearest[i] = last; + } + for (size_t i = 0; i < nb; ++i) { + Fields f = fl[i]; + if (kep[i] && kix[i]) { + ++local.exact; + } else if (kep[i]) { + flat(f); + ++local.endpoints_only; + } else if (copy_known && nearest[i] >= 0) { + f = fl[static_cast(nearest[i])]; + flat(f); + ++local.copied; + } else { + f = Fields{}; + f.mode = 13; + for (int c = 0; c < 3; ++c) f.ep[0][c] = fill_base; // x = 0: both endpoints equal + ++local.constant; + } + pack(f, out + i * 16); + } + if (stats) *stats = local; + return true; +} + +// The whole BCPack BC6H stream: lanes, then rebuild. False when the lanes do not decode. +inline bool decode_stream(const unsigned char* input, size_t input_size, unsigned char* output, size_t output_size, + size_t* produced, Stats* stats, const Dictionary* dict = nullptr, + uint16_t fill_base = DEFAULT_FILL_BASE, bool copy_known = true) { + if (!input || !output || !produced || input_size == 0 || output_size == 0 || output_size % 16) return false; + const size_t nb = output_size / 16; + static constexpr uint8_t ab[16] = { 3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4 }; + std::vector symbols; + if (!decode_lanes(input, input_size, ab, 16, nb * 2, symbols)) return false; + if (!decode_blocks(symbols, nb, output, output_size, stats, dict, fill_base, copy_known)) return false; + *produced = output_size; + return true; +} + +} // namespace bc6h +} // namespace x2w_bcpack diff --git a/src/startup_stubs/bcpack_decoder.h b/src/startup_stubs/bcpack_decoder.h index e255040f50..7cf130629a 100644 --- a/src/startup_stubs/bcpack_decoder.h +++ b/src/startup_stubs/bcpack_decoder.h @@ -19,6 +19,8 @@ namespace x2w_bcpack { +// (The BC3/BC4/BC5 rank tables and dictionaries come from bcpack_tables.h, which includes bcpack_tables_bcn.inl.) + inline void model_forward(uint8_t eab, uint8_t q, uint16_t sym, uint32_t& f, uint32_t& cf) { uint32_t s = sym; unsigned long seg = 0; @@ -1161,6 +1163,32 @@ inline bool decode_bc1_blocks(const std::vector& symbols, size_t targe return true; } +// BC3, BC4 and BC5 (formats 3, 4, 5), from Xbox2Windows upstream PR 1390, which adapts the +// bcpack-rs rules and tables (revision c55c5fad, MIT OR Apache-2.0). +// Lane layouts (alphabet bits; symbols per lane per block), each checked locally against every +// BC3/BC4/BC5 archive interval (35/77/333): exact logical size, every compressed byte consumed, +// legal final states. +// BC4 12 lanes {7,7,7,7,5x8}, 1/block: d, x, e0, e1, 8 pair lanes (texels 2k, 2k+1). +// BC5 12 lanes {3,3,7,7,5x8}, 2/block: d and x nibbles, R e0/e1, G e0/e1, 4 R + 4 G pair lanes. +// BC3 12 lanes {3,3,7,5,5,5,5,4,5,4,7,7}, 2/block: d, x, alpha e0/e1, 4 alpha pair lanes, +// R/G/B 565 endpoints (E = colour 0, O = colour 1), 2 colour quadrant lanes (TL TR, BL BR). +// UNVERIFIED: the pair/quadrant rank tables and the pre-history dictionaries are fitted by +// bcpack-rs, which itself reports only partial byte agreement. Locally, decoded pictures are +// coherent, and each format's own pair table gives smoother texels than the other formats' tables +// on every sampled interval, but there is no ground truth. 87% of BC5 blocks have an endpoint +// reference chain that starts in the dictionary, so a wrong dictionary entry shifts them all. +// +// BC6H (format 6): lane layout only, not decoded. 16 lanes {3,3,7,7,7,4,4,4,5,5,5,7,7,7,7,4}, +// 2 symbols per lane per block, verified on all 268 local BC6H intervals as above. Measured on +// real data: lane 15 E = BC6H mode (0..13), lane 15 O = partition (0..31, 0 for one-region modes); +// lanes 8..10 (E, O) carry two full-width delta fields per channel in two-region modes and are +// zero in one-region modes; lanes 2..4 and 5..7 carry the base and first delta fields split into +// ceil/floor halves across E and O; lanes 11..14 carry index pairs (8 bits one-region, 6 bits +// two-region). Missing: the prediction domain for endpoints across modes, the use of the index +// reference x (non-zero in BC6H data, unlike BC3/4/5), and a dictionary for pre-history refs: +// 93.5% of BC6H blocks have an endpoint reference chain, and 70% an index chain, that starts +// before the first block, so no field mapping alone can give correct blocks. + inline constexpr uint8_t ALPHA_CODE[8] = { 0, 2, 3, 4, 5, 6, 7, 1 }; inline constexpr uint8_t COLOUR_CODE[4] = { 0, 2, 3, 1 }; diff --git a/src/startup_stubs/blake3/LICENSE_A2 b/src/startup_stubs/blake3/LICENSE_A2 new file mode 100644 index 0000000000..d512ca94d0 --- /dev/null +++ b/src/startup_stubs/blake3/LICENSE_A2 @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2019 Jack O'Connor and Samuel Neves + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/startup_stubs/blake3/LICENSE_A2LLVM b/src/startup_stubs/blake3/LICENSE_A2LLVM new file mode 100644 index 0000000000..8d11bec0e8 --- /dev/null +++ b/src/startup_stubs/blake3/LICENSE_A2LLVM @@ -0,0 +1,219 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2019 Jack O'Connor and Samuel Neves + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + diff --git a/src/startup_stubs/blake3/LICENSE_CC0 b/src/startup_stubs/blake3/LICENSE_CC0 new file mode 100644 index 0000000000..0e259d42c9 --- /dev/null +++ b/src/startup_stubs/blake3/LICENSE_CC0 @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/src/startup_stubs/blake3/blake3.c b/src/startup_stubs/blake3/blake3.c new file mode 100644 index 0000000000..00f91f4449 --- /dev/null +++ b/src/startup_stubs/blake3/blake3.c @@ -0,0 +1,651 @@ +#include +#include +#include +#include + +#include "blake3.h" +#include "blake3_impl.h" + +const char *blake3_version(void) { return BLAKE3_VERSION_STRING; } + +INLINE void chunk_state_init(blake3_chunk_state *self, const uint32_t key[8], + uint8_t flags) { + memcpy(self->cv, key, BLAKE3_KEY_LEN); + self->chunk_counter = 0; + memset(self->buf, 0, BLAKE3_BLOCK_LEN); + self->buf_len = 0; + self->blocks_compressed = 0; + self->flags = flags; +} + +INLINE void chunk_state_reset(blake3_chunk_state *self, const uint32_t key[8], + uint64_t chunk_counter) { + memcpy(self->cv, key, BLAKE3_KEY_LEN); + self->chunk_counter = chunk_counter; + self->blocks_compressed = 0; + memset(self->buf, 0, BLAKE3_BLOCK_LEN); + self->buf_len = 0; +} + +INLINE size_t chunk_state_len(const blake3_chunk_state *self) { + return (BLAKE3_BLOCK_LEN * (size_t)self->blocks_compressed) + + ((size_t)self->buf_len); +} + +INLINE size_t chunk_state_fill_buf(blake3_chunk_state *self, + const uint8_t *input, size_t input_len) { + size_t take = BLAKE3_BLOCK_LEN - ((size_t)self->buf_len); + if (take > input_len) { + take = input_len; + } + uint8_t *dest = self->buf + ((size_t)self->buf_len); + memcpy(dest, input, take); + self->buf_len += (uint8_t)take; + return take; +} + +INLINE uint8_t chunk_state_maybe_start_flag(const blake3_chunk_state *self) { + if (self->blocks_compressed == 0) { + return CHUNK_START; + } else { + return 0; + } +} + +typedef struct { + uint32_t input_cv[8]; + uint64_t counter; + uint8_t block[BLAKE3_BLOCK_LEN]; + uint8_t block_len; + uint8_t flags; +} output_t; + +INLINE output_t make_output(const uint32_t input_cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags) { + output_t ret; + memcpy(ret.input_cv, input_cv, 32); + memcpy(ret.block, block, BLAKE3_BLOCK_LEN); + ret.block_len = block_len; + ret.counter = counter; + ret.flags = flags; + return ret; +} + +// Chaining values within a given chunk (specifically the compress_in_place +// interface) are represented as words. This avoids unnecessary bytes<->words +// conversion overhead in the portable implementation. However, the hash_many +// interface handles both user input and parent node blocks, so it accepts +// bytes. For that reason, chaining values in the CV stack are represented as +// bytes. +INLINE void output_chaining_value(const output_t *self, uint8_t cv[32]) { + uint32_t cv_words[8]; + memcpy(cv_words, self->input_cv, 32); + blake3_compress_in_place(cv_words, self->block, self->block_len, + self->counter, self->flags); + store_cv_words(cv, cv_words); +} + +INLINE void output_root_bytes(const output_t *self, uint64_t seek, uint8_t *out, + size_t out_len) { + if (out_len == 0) { + return; + } + uint64_t output_block_counter = seek / 64; + size_t offset_within_block = seek % 64; + uint8_t wide_buf[64]; + if(offset_within_block) { + blake3_compress_xof(self->input_cv, self->block, self->block_len, output_block_counter, self->flags | ROOT, wide_buf); + const size_t available_bytes = 64 - offset_within_block; + const size_t bytes = out_len > available_bytes ? available_bytes : out_len; + memcpy(out, wide_buf + offset_within_block, bytes); + out += bytes; + out_len -= bytes; + output_block_counter += 1; + } + if(out_len / 64) { + blake3_xof_many(self->input_cv, self->block, self->block_len, output_block_counter, self->flags | ROOT, out, out_len / 64); + } + output_block_counter += out_len / 64; + out += out_len & -64; + out_len -= out_len & -64; + if(out_len) { + blake3_compress_xof(self->input_cv, self->block, self->block_len, output_block_counter, self->flags | ROOT, wide_buf); + memcpy(out, wide_buf, out_len); + } +} + +INLINE void chunk_state_update(blake3_chunk_state *self, const uint8_t *input, + size_t input_len) { + if (self->buf_len > 0) { + size_t take = chunk_state_fill_buf(self, input, input_len); + input += take; + input_len -= take; + if (input_len > 0) { + blake3_compress_in_place( + self->cv, self->buf, BLAKE3_BLOCK_LEN, self->chunk_counter, + self->flags | chunk_state_maybe_start_flag(self)); + self->blocks_compressed += 1; + self->buf_len = 0; + memset(self->buf, 0, BLAKE3_BLOCK_LEN); + } + } + + while (input_len > BLAKE3_BLOCK_LEN) { + blake3_compress_in_place(self->cv, input, BLAKE3_BLOCK_LEN, + self->chunk_counter, + self->flags | chunk_state_maybe_start_flag(self)); + self->blocks_compressed += 1; + input += BLAKE3_BLOCK_LEN; + input_len -= BLAKE3_BLOCK_LEN; + } + + chunk_state_fill_buf(self, input, input_len); +} + +INLINE output_t chunk_state_output(const blake3_chunk_state *self) { + uint8_t block_flags = + self->flags | chunk_state_maybe_start_flag(self) | CHUNK_END; + return make_output(self->cv, self->buf, self->buf_len, self->chunk_counter, + block_flags); +} + +INLINE output_t parent_output(const uint8_t block[BLAKE3_BLOCK_LEN], + const uint32_t key[8], uint8_t flags) { + return make_output(key, block, BLAKE3_BLOCK_LEN, 0, flags | PARENT); +} + +// Given some input larger than one chunk, return the number of bytes that +// should go in the left subtree. This is the largest power-of-2 number of +// chunks that leaves at least 1 byte for the right subtree. +INLINE size_t left_subtree_len(size_t input_len) { + // Subtract 1 to reserve at least one byte for the right side. input_len + // should always be greater than BLAKE3_CHUNK_LEN. + size_t full_chunks = (input_len - 1) / BLAKE3_CHUNK_LEN; + return round_down_to_power_of_2(full_chunks) * BLAKE3_CHUNK_LEN; +} + +// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE chunks at the same time +// on a single thread. Write out the chunk chaining values and return the +// number of chunks hashed. These chunks are never the root and never empty; +// those cases use a different codepath. +INLINE size_t compress_chunks_parallel(const uint8_t *input, size_t input_len, + const uint32_t key[8], + uint64_t chunk_counter, uint8_t flags, + uint8_t *out) { +#if defined(BLAKE3_TESTING) + assert(0 < input_len); + assert(input_len <= MAX_SIMD_DEGREE * BLAKE3_CHUNK_LEN); +#endif + + const uint8_t *chunks_array[MAX_SIMD_DEGREE]; + size_t input_position = 0; + size_t chunks_array_len = 0; + while (input_len - input_position >= BLAKE3_CHUNK_LEN) { + chunks_array[chunks_array_len] = &input[input_position]; + input_position += BLAKE3_CHUNK_LEN; + chunks_array_len += 1; + } + + blake3_hash_many(chunks_array, chunks_array_len, + BLAKE3_CHUNK_LEN / BLAKE3_BLOCK_LEN, key, chunk_counter, + true, flags, CHUNK_START, CHUNK_END, out); + + // Hash the remaining partial chunk, if there is one. Note that the empty + // chunk (meaning the empty message) is a different codepath. + if (input_len > input_position) { + uint64_t counter = chunk_counter + (uint64_t)chunks_array_len; + blake3_chunk_state chunk_state; + chunk_state_init(&chunk_state, key, flags); + chunk_state.chunk_counter = counter; + chunk_state_update(&chunk_state, &input[input_position], + input_len - input_position); + output_t output = chunk_state_output(&chunk_state); + output_chaining_value(&output, &out[chunks_array_len * BLAKE3_OUT_LEN]); + return chunks_array_len + 1; + } else { + return chunks_array_len; + } +} + +// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE parents at the same time +// on a single thread. Write out the parent chaining values and return the +// number of parents hashed. (If there's an odd input chaining value left over, +// return it as an additional output.) These parents are never the root and +// never empty; those cases use a different codepath. +INLINE size_t compress_parents_parallel(const uint8_t *child_chaining_values, + size_t num_chaining_values, + const uint32_t key[8], uint8_t flags, + uint8_t *out) { +#if defined(BLAKE3_TESTING) + assert(2 <= num_chaining_values); + assert(num_chaining_values <= 2 * MAX_SIMD_DEGREE_OR_2); +#endif + + const uint8_t *parents_array[MAX_SIMD_DEGREE_OR_2]; + size_t parents_array_len = 0; + while (num_chaining_values - (2 * parents_array_len) >= 2) { + parents_array[parents_array_len] = + &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN]; + parents_array_len += 1; + } + + blake3_hash_many(parents_array, parents_array_len, 1, key, + 0, // Parents always use counter 0. + false, flags | PARENT, + 0, // Parents have no start flags. + 0, // Parents have no end flags. + out); + + // If there's an odd child left over, it becomes an output. + if (num_chaining_values > 2 * parents_array_len) { + memcpy(&out[parents_array_len * BLAKE3_OUT_LEN], + &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN], + BLAKE3_OUT_LEN); + return parents_array_len + 1; + } else { + return parents_array_len; + } +} + +// The wide helper function returns (writes out) an array of chaining values +// and returns the length of that array. The number of chaining values returned +// is the dynamically detected SIMD degree, at most MAX_SIMD_DEGREE. Or fewer, +// if the input is shorter than that many chunks. The reason for maintaining a +// wide array of chaining values going back up the tree, is to allow the +// implementation to hash as many parents in parallel as possible. +// +// As a special case when the SIMD degree is 1, this function will still return +// at least 2 outputs. This guarantees that this function doesn't perform the +// root compression. (If it did, it would use the wrong flags, and also we +// wouldn't be able to implement extendable output.) Note that this function is +// not used when the whole input is only 1 chunk long; that's a different +// codepath. +// +// Why not just have the caller split the input on the first update(), instead +// of implementing this special rule? Because we don't want to limit SIMD or +// multi-threading parallelism for that update(). +size_t blake3_compress_subtree_wide(const uint8_t *input, size_t input_len, + const uint32_t key[8], + uint64_t chunk_counter, uint8_t flags, + uint8_t *out, bool use_tbb) { + // Note that the single chunk case does *not* bump the SIMD degree up to 2 + // when it is 1. If this implementation adds multi-threading in the future, + // this gives us the option of multi-threading even the 2-chunk case, which + // can help performance on smaller platforms. + if (input_len <= blake3_simd_degree() * BLAKE3_CHUNK_LEN) { + return compress_chunks_parallel(input, input_len, key, chunk_counter, flags, + out); + } + + // With more than simd_degree chunks, we need to recurse. Start by dividing + // the input into left and right subtrees. (Note that this is only optimal + // as long as the SIMD degree is a power of 2. If we ever get a SIMD degree + // of 3 or something, we'll need a more complicated strategy.) + size_t left_input_len = left_subtree_len(input_len); + size_t right_input_len = input_len - left_input_len; + const uint8_t *right_input = &input[left_input_len]; + uint64_t right_chunk_counter = + chunk_counter + (uint64_t)(left_input_len / BLAKE3_CHUNK_LEN); + + // Make space for the child outputs. Here we use MAX_SIMD_DEGREE_OR_2 to + // account for the special case of returning 2 outputs when the SIMD degree + // is 1. + uint8_t cv_array[2 * MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN]; + size_t degree = blake3_simd_degree(); + if (left_input_len > BLAKE3_CHUNK_LEN && degree == 1) { + // The special case: We always use a degree of at least two, to make + // sure there are two outputs. Except, as noted above, at the chunk + // level, where we allow degree=1. (Note that the 1-chunk-input case is + // a different codepath.) + degree = 2; + } + uint8_t *right_cvs = &cv_array[degree * BLAKE3_OUT_LEN]; + + // Recurse! + size_t left_n = SIZE_MAX; + size_t right_n = SIZE_MAX; + +#if defined(BLAKE3_USE_TBB) + blake3_compress_subtree_wide_join_tbb( + key, flags, use_tbb, + // left-hand side + input, left_input_len, chunk_counter, cv_array, &left_n, + // right-hand side + right_input, right_input_len, right_chunk_counter, right_cvs, &right_n); +#else + left_n = blake3_compress_subtree_wide( + input, left_input_len, key, chunk_counter, flags, cv_array, use_tbb); + right_n = blake3_compress_subtree_wide(right_input, right_input_len, key, + right_chunk_counter, flags, right_cvs, + use_tbb); +#endif // BLAKE3_USE_TBB + + // The special case again. If simd_degree=1, then we'll have left_n=1 and + // right_n=1. Rather than compressing them into a single output, return + // them directly, to make sure we always have at least two outputs. + if (left_n == 1) { + memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN); + return 2; + } + + // Otherwise, do one layer of parent node compression. + size_t num_chaining_values = left_n + right_n; + return compress_parents_parallel(cv_array, num_chaining_values, key, flags, + out); +} + +// Hash a subtree with compress_subtree_wide(), and then condense the resulting +// list of chaining values down to a single parent node. Don't compress that +// last parent node, however. Instead, return its message bytes (the +// concatenated chaining values of its children). This is necessary when the +// first call to update() supplies a complete subtree, because the topmost +// parent node of that subtree could end up being the root. It's also necessary +// for extended output in the general case. +// +// As with compress_subtree_wide(), this function is not used on inputs of 1 +// chunk or less. That's a different codepath. +INLINE void +compress_subtree_to_parent_node(const uint8_t *input, size_t input_len, + const uint32_t key[8], uint64_t chunk_counter, + uint8_t flags, uint8_t out[2 * BLAKE3_OUT_LEN], + bool use_tbb) { +#if defined(BLAKE3_TESTING) + assert(input_len > BLAKE3_CHUNK_LEN); +#endif + + uint8_t cv_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN]; + size_t num_cvs = blake3_compress_subtree_wide(input, input_len, key, + chunk_counter, flags, cv_array, use_tbb); + assert(num_cvs <= MAX_SIMD_DEGREE_OR_2); + // The following loop never executes when MAX_SIMD_DEGREE_OR_2 is 2, because + // as we just asserted, num_cvs will always be <=2 in that case. But GCC + // (particularly GCC 8.5) can't tell that it never executes, and if NDEBUG is + // set then it emits incorrect warnings here. We tried a few different + // hacks to silence these, but in the end our hacks just produced different + // warnings (see https://github.com/BLAKE3-team/BLAKE3/pull/380). Out of + // desperation, we ifdef out this entire loop when we know it's not needed. +#if MAX_SIMD_DEGREE_OR_2 > 2 + // If MAX_SIMD_DEGREE_OR_2 is greater than 2 and there's enough input, + // compress_subtree_wide() returns more than 2 chaining values. Condense + // them into 2 by forming parent nodes repeatedly. + uint8_t out_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN / 2]; + while (num_cvs > 2) { + num_cvs = + compress_parents_parallel(cv_array, num_cvs, key, flags, out_array); + memcpy(cv_array, out_array, num_cvs * BLAKE3_OUT_LEN); + } +#endif + memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN); +} + +INLINE void hasher_init_base(blake3_hasher *self, const uint32_t key[8], + uint8_t flags) { + memcpy(self->key, key, BLAKE3_KEY_LEN); + chunk_state_init(&self->chunk, key, flags); + self->cv_stack_len = 0; +} + +void blake3_hasher_init(blake3_hasher *self) { hasher_init_base(self, IV, 0); } + +void blake3_hasher_init_keyed(blake3_hasher *self, + const uint8_t key[BLAKE3_KEY_LEN]) { + uint32_t key_words[8]; + load_key_words(key, key_words); + hasher_init_base(self, key_words, KEYED_HASH); +} + +void blake3_hasher_init_derive_key_raw(blake3_hasher *self, const void *context, + size_t context_len) { + blake3_hasher context_hasher; + hasher_init_base(&context_hasher, IV, DERIVE_KEY_CONTEXT); + blake3_hasher_update(&context_hasher, context, context_len); + uint8_t context_key[BLAKE3_KEY_LEN]; + blake3_hasher_finalize(&context_hasher, context_key, BLAKE3_KEY_LEN); + uint32_t context_key_words[8]; + load_key_words(context_key, context_key_words); + hasher_init_base(self, context_key_words, DERIVE_KEY_MATERIAL); +} + +void blake3_hasher_init_derive_key(blake3_hasher *self, const char *context) { + blake3_hasher_init_derive_key_raw(self, context, strlen(context)); +} + +// As described in hasher_push_cv() below, we do "lazy merging", delaying +// merges until right before the next CV is about to be added. This is +// different from the reference implementation. Another difference is that we +// aren't always merging 1 chunk at a time. Instead, each CV might represent +// any power-of-two number of chunks, as long as the smaller-above-larger stack +// order is maintained. Instead of the "count the trailing 0-bits" algorithm +// described in the spec, we use a "count the total number of 1-bits" variant +// that doesn't require us to retain the subtree size of the CV on top of the +// stack. The principle is the same: each CV that should remain in the stack is +// represented by a 1-bit in the total number of chunks (or bytes) so far. +INLINE void hasher_merge_cv_stack(blake3_hasher *self, uint64_t total_len) { + size_t post_merge_stack_len = (size_t)popcnt(total_len); + while (self->cv_stack_len > post_merge_stack_len) { + uint8_t *parent_node = + &self->cv_stack[(self->cv_stack_len - 2) * BLAKE3_OUT_LEN]; + output_t output = parent_output(parent_node, self->key, self->chunk.flags); + output_chaining_value(&output, parent_node); + self->cv_stack_len -= 1; + } +} + +// In reference_impl.rs, we merge the new CV with existing CVs from the stack +// before pushing it. We can do that because we know more input is coming, so +// we know none of the merges are root. +// +// This setting is different. We want to feed as much input as possible to +// compress_subtree_wide(), without setting aside anything for the chunk_state. +// If the user gives us 64 KiB, we want to parallelize over all 64 KiB at once +// as a single subtree, if at all possible. +// +// This leads to two problems: +// 1) This 64 KiB input might be the only call that ever gets made to update. +// In this case, the root node of the 64 KiB subtree would be the root node +// of the whole tree, and it would need to be ROOT finalized. We can't +// compress it until we know. +// 2) This 64 KiB input might complete a larger tree, whose root node is +// similarly going to be the root of the whole tree. For example, maybe +// we have 196 KiB (that is, 128 + 64) hashed so far. We can't compress the +// node at the root of the 256 KiB subtree until we know how to finalize it. +// +// The second problem is solved with "lazy merging". That is, when we're about +// to add a CV to the stack, we don't merge it with anything first, as the +// reference impl does. Instead we do merges using the *previous* CV that was +// added, which is sitting on top of the stack, and we put the new CV +// (unmerged) on top of the stack afterwards. This guarantees that we never +// merge the root node until finalize(). +// +// Solving the first problem requires an additional tool, +// compress_subtree_to_parent_node(). That function always returns the top +// *two* chaining values of the subtree it's compressing. We then do lazy +// merging with each of them separately, so that the second CV will always +// remain unmerged. (That also helps us support extendable output when we're +// hashing an input all-at-once.) +INLINE void hasher_push_cv(blake3_hasher *self, uint8_t new_cv[BLAKE3_OUT_LEN], + uint64_t chunk_counter) { + hasher_merge_cv_stack(self, chunk_counter); + memcpy(&self->cv_stack[self->cv_stack_len * BLAKE3_OUT_LEN], new_cv, + BLAKE3_OUT_LEN); + self->cv_stack_len += 1; +} + +INLINE void blake3_hasher_update_base(blake3_hasher *self, const void *input, + size_t input_len, bool use_tbb) { + // Explicitly checking for zero avoids causing UB by passing a null pointer + // to memcpy. This comes up in practice with things like: + // std::vector v; + // blake3_hasher_update(&hasher, v.data(), v.size()); + if (input_len == 0) { + return; + } + + const uint8_t *input_bytes = (const uint8_t *)input; + + // If we have some partial chunk bytes in the internal chunk_state, we need + // to finish that chunk first. + if (chunk_state_len(&self->chunk) > 0) { + size_t take = BLAKE3_CHUNK_LEN - chunk_state_len(&self->chunk); + if (take > input_len) { + take = input_len; + } + chunk_state_update(&self->chunk, input_bytes, take); + input_bytes += take; + input_len -= take; + // If we've filled the current chunk and there's more coming, finalize this + // chunk and proceed. In this case we know it's not the root. + if (input_len > 0) { + output_t output = chunk_state_output(&self->chunk); + uint8_t chunk_cv[32]; + output_chaining_value(&output, chunk_cv); + hasher_push_cv(self, chunk_cv, self->chunk.chunk_counter); + chunk_state_reset(&self->chunk, self->key, self->chunk.chunk_counter + 1); + } else { + return; + } + } + + // Now the chunk_state is clear, and we have more input. If there's more than + // a single chunk (so, definitely not the root chunk), hash the largest whole + // subtree we can, with the full benefits of SIMD (and maybe in the future, + // multi-threading) parallelism. Two restrictions: + // - The subtree has to be a power-of-2 number of chunks. Only subtrees along + // the right edge can be incomplete, and we don't know where the right edge + // is going to be until we get to finalize(). + // - The subtree must evenly divide the total number of chunks up until this + // point (if total is not 0). If the current incomplete subtree is only + // waiting for 1 more chunk, we can't hash a subtree of 4 chunks. We have + // to complete the current subtree first. + // Because we might need to break up the input to form powers of 2, or to + // evenly divide what we already have, this part runs in a loop. + while (input_len > BLAKE3_CHUNK_LEN) { + size_t subtree_len = round_down_to_power_of_2(input_len); + uint64_t count_so_far = self->chunk.chunk_counter * BLAKE3_CHUNK_LEN; + // Shrink the subtree_len until it evenly divides the count so far. We know + // that subtree_len itself is a power of 2, so we can use a bitmasking + // trick instead of an actual remainder operation. (Note that if the caller + // consistently passes power-of-2 inputs of the same size, as is hopefully + // typical, this loop condition will always fail, and subtree_len will + // always be the full length of the input.) + // + // An aside: We don't have to shrink subtree_len quite this much. For + // example, if count_so_far is 1, we could pass 2 chunks to + // compress_subtree_to_parent_node. Since we'll get 2 CVs back, we'll still + // get the right answer in the end, and we might get to use 2-way SIMD + // parallelism. The problem with this optimization, is that it gets us + // stuck always hashing 2 chunks. The total number of chunks will remain + // odd, and we'll never graduate to higher degrees of parallelism. See + // https://github.com/BLAKE3-team/BLAKE3/issues/69. + while ((((uint64_t)(subtree_len - 1)) & count_so_far) != 0) { + subtree_len /= 2; + } + // The shrunken subtree_len might now be 1 chunk long. If so, hash that one + // chunk by itself. Otherwise, compress the subtree into a pair of CVs. + uint64_t subtree_chunks = subtree_len / BLAKE3_CHUNK_LEN; + if (subtree_len <= BLAKE3_CHUNK_LEN) { + blake3_chunk_state chunk_state; + chunk_state_init(&chunk_state, self->key, self->chunk.flags); + chunk_state.chunk_counter = self->chunk.chunk_counter; + chunk_state_update(&chunk_state, input_bytes, subtree_len); + output_t output = chunk_state_output(&chunk_state); + uint8_t cv[BLAKE3_OUT_LEN]; + output_chaining_value(&output, cv); + hasher_push_cv(self, cv, chunk_state.chunk_counter); + } else { + // This is the high-performance happy path, though getting here depends + // on the caller giving us a long enough input. + uint8_t cv_pair[2 * BLAKE3_OUT_LEN]; + compress_subtree_to_parent_node(input_bytes, subtree_len, self->key, + self->chunk.chunk_counter, + self->chunk.flags, cv_pair, use_tbb); + hasher_push_cv(self, cv_pair, self->chunk.chunk_counter); + hasher_push_cv(self, &cv_pair[BLAKE3_OUT_LEN], + self->chunk.chunk_counter + (subtree_chunks / 2)); + } + self->chunk.chunk_counter += subtree_chunks; + input_bytes += subtree_len; + input_len -= subtree_len; + } + + // If there's any remaining input less than a full chunk, add it to the chunk + // state. In that case, also do a final merge loop to make sure the subtree + // stack doesn't contain any unmerged pairs. The remaining input means we + // know these merges are non-root. This merge loop isn't strictly necessary + // here, because hasher_push_chunk_cv already does its own merge loop, but it + // simplifies blake3_hasher_finalize below. + if (input_len > 0) { + chunk_state_update(&self->chunk, input_bytes, input_len); + hasher_merge_cv_stack(self, self->chunk.chunk_counter); + } +} + +void blake3_hasher_update(blake3_hasher *self, const void *input, + size_t input_len) { + bool use_tbb = false; + blake3_hasher_update_base(self, input, input_len, use_tbb); +} + +#if defined(BLAKE3_USE_TBB) +void blake3_hasher_update_tbb(blake3_hasher *self, const void *input, + size_t input_len) { + bool use_tbb = true; + blake3_hasher_update_base(self, input, input_len, use_tbb); +} +#endif // BLAKE3_USE_TBB + +void blake3_hasher_finalize(const blake3_hasher *self, uint8_t *out, + size_t out_len) { + blake3_hasher_finalize_seek(self, 0, out, out_len); +} + +void blake3_hasher_finalize_seek(const blake3_hasher *self, uint64_t seek, + uint8_t *out, size_t out_len) { + // Explicitly checking for zero avoids causing UB by passing a null pointer + // to memcpy. This comes up in practice with things like: + // std::vector v; + // blake3_hasher_finalize(&hasher, v.data(), v.size()); + if (out_len == 0) { + return; + } + + // If the subtree stack is empty, then the current chunk is the root. + if (self->cv_stack_len == 0) { + output_t output = chunk_state_output(&self->chunk); + output_root_bytes(&output, seek, out, out_len); + return; + } + // If there are any bytes in the chunk state, finalize that chunk and do a + // roll-up merge between that chunk hash and every subtree in the stack. In + // this case, the extra merge loop at the end of blake3_hasher_update + // guarantees that none of the subtrees in the stack need to be merged with + // each other first. Otherwise, if there are no bytes in the chunk state, + // then the top of the stack is a chunk hash, and we start the merge from + // that. + output_t output; + size_t cvs_remaining; + if (chunk_state_len(&self->chunk) > 0) { + cvs_remaining = self->cv_stack_len; + output = chunk_state_output(&self->chunk); + } else { + // There are always at least 2 CVs in the stack in this case. + cvs_remaining = self->cv_stack_len - 2; + output = parent_output(&self->cv_stack[cvs_remaining * 32], self->key, + self->chunk.flags); + } + while (cvs_remaining > 0) { + cvs_remaining -= 1; + uint8_t parent_block[BLAKE3_BLOCK_LEN]; + memcpy(parent_block, &self->cv_stack[cvs_remaining * 32], 32); + output_chaining_value(&output, &parent_block[32]); + output = parent_output(parent_block, self->key, self->chunk.flags); + } + output_root_bytes(&output, seek, out, out_len); +} + +void blake3_hasher_reset(blake3_hasher *self) { + chunk_state_reset(&self->chunk, self->key, 0); + self->cv_stack_len = 0; +} diff --git a/src/startup_stubs/blake3/blake3.h b/src/startup_stubs/blake3/blake3.h new file mode 100644 index 0000000000..c5b799870a --- /dev/null +++ b/src/startup_stubs/blake3/blake3.h @@ -0,0 +1,86 @@ +#ifndef BLAKE3_H +#define BLAKE3_H + +#include +#include + +#if !defined(BLAKE3_API) +# if defined(_WIN32) || defined(__CYGWIN__) +# if defined(BLAKE3_DLL) +# if defined(BLAKE3_DLL_EXPORTS) +# define BLAKE3_API __declspec(dllexport) +# else +# define BLAKE3_API __declspec(dllimport) +# endif +# define BLAKE3_PRIVATE +# else +# define BLAKE3_API +# define BLAKE3_PRIVATE +# endif +# elif __GNUC__ >= 4 +# define BLAKE3_API __attribute__((visibility("default"))) +# define BLAKE3_PRIVATE __attribute__((visibility("hidden"))) +# else +# define BLAKE3_API +# define BLAKE3_PRIVATE +# endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define BLAKE3_VERSION_STRING "1.8.7" +#define BLAKE3_KEY_LEN 32 +#define BLAKE3_OUT_LEN 32 +#define BLAKE3_BLOCK_LEN 64 +#define BLAKE3_CHUNK_LEN 1024 +#define BLAKE3_MAX_DEPTH 54 + +// This struct is a private implementation detail. It has to be here because +// it's part of the blake3_hasher structure defined below. +typedef struct { + uint32_t cv[8]; + uint64_t chunk_counter; + uint8_t buf[BLAKE3_BLOCK_LEN]; + uint8_t buf_len; + uint8_t blocks_compressed; + uint8_t flags; +} blake3_chunk_state; + +typedef struct { + uint32_t key[8]; + blake3_chunk_state chunk; + uint8_t cv_stack_len; + // The stack size is MAX_DEPTH + 1 because we do lazy merging. For example, + // with 7 chunks, we have 3 entries in the stack. Adding an 8th chunk + // requires a 4th entry, rather than merging everything down to 1, because we + // don't know whether more input is coming. This is different from how the + // reference implementation does things. + uint8_t cv_stack[(BLAKE3_MAX_DEPTH + 1) * BLAKE3_OUT_LEN]; +} blake3_hasher; + +BLAKE3_API const char *blake3_version(void); +BLAKE3_API void blake3_hasher_init(blake3_hasher *self); +BLAKE3_API void blake3_hasher_init_keyed(blake3_hasher *self, + const uint8_t key[BLAKE3_KEY_LEN]); +BLAKE3_API void blake3_hasher_init_derive_key(blake3_hasher *self, const char *context); +BLAKE3_API void blake3_hasher_init_derive_key_raw(blake3_hasher *self, const void *context, + size_t context_len); +BLAKE3_API void blake3_hasher_update(blake3_hasher *self, const void *input, + size_t input_len); +#if defined(BLAKE3_USE_TBB) +BLAKE3_API void blake3_hasher_update_tbb(blake3_hasher *self, const void *input, + size_t input_len); +#endif // BLAKE3_USE_TBB +BLAKE3_API void blake3_hasher_finalize(const blake3_hasher *self, uint8_t *out, + size_t out_len); +BLAKE3_API void blake3_hasher_finalize_seek(const blake3_hasher *self, uint64_t seek, + uint8_t *out, size_t out_len); +BLAKE3_API void blake3_hasher_reset(blake3_hasher *self); + +#ifdef __cplusplus +} +#endif + +#endif /* BLAKE3_H */ diff --git a/src/startup_stubs/blake3/blake3_dispatch.c b/src/startup_stubs/blake3/blake3_dispatch.c new file mode 100644 index 0000000000..14dfbbe0c8 --- /dev/null +++ b/src/startup_stubs/blake3/blake3_dispatch.c @@ -0,0 +1,332 @@ +#include +#include +#include + +#include "blake3_impl.h" + +#if defined(_MSC_VER) +#include +#endif + +#if defined(IS_X86) +#if defined(_MSC_VER) +#include +#elif defined(__GNUC__) +#include +#else +#undef IS_X86 /* Unimplemented! */ +#endif +#endif + +#if !defined(BLAKE3_ATOMICS) +#if defined(__has_include) +#if __has_include() && !defined(_MSC_VER) +#define BLAKE3_ATOMICS 1 +#else +#define BLAKE3_ATOMICS 0 +#endif /* __has_include() && !defined(_MSC_VER) */ +#else +#define BLAKE3_ATOMICS 0 +#endif /* defined(__has_include) */ +#endif /* BLAKE3_ATOMICS */ + +#if BLAKE3_ATOMICS +#define ATOMIC_INT _Atomic int +#define ATOMIC_LOAD(x) x +#define ATOMIC_STORE(x, y) x = y +#elif defined(_MSC_VER) +#define ATOMIC_INT LONG +#define ATOMIC_LOAD(x) InterlockedOr(&x, 0) +#define ATOMIC_STORE(x, y) InterlockedExchange(&x, y) +#else +#define ATOMIC_INT int +#define ATOMIC_LOAD(x) x +#define ATOMIC_STORE(x, y) x = y +#endif + +#define MAYBE_UNUSED(x) (void)((x)) + +#if defined(IS_X86) +static uint64_t xgetbv(void) { +#if defined(_MSC_VER) + return _xgetbv(0); +#else + uint32_t eax = 0, edx = 0; + __asm__ __volatile__("xgetbv\n" : "=a"(eax), "=d"(edx) : "c"(0)); + return ((uint64_t)edx << 32) | eax; +#endif +} + +static void cpuid(uint32_t out[4], uint32_t id) { +#if defined(_MSC_VER) + __cpuid((int *)out, id); +#elif defined(__i386__) || defined(_M_IX86) + __asm__ __volatile__("movl %%ebx, %1\n" + "cpuid\n" + "xchgl %1, %%ebx\n" + : "=a"(out[0]), "=r"(out[1]), "=c"(out[2]), "=d"(out[3]) + : "a"(id)); +#else + __asm__ __volatile__("cpuid\n" + : "=a"(out[0]), "=b"(out[1]), "=c"(out[2]), "=d"(out[3]) + : "a"(id)); +#endif +} + +static void cpuidex(uint32_t out[4], uint32_t id, uint32_t sid) { +#if defined(_MSC_VER) + __cpuidex((int *)out, id, sid); +#elif defined(__i386__) || defined(_M_IX86) + __asm__ __volatile__("movl %%ebx, %1\n" + "cpuid\n" + "xchgl %1, %%ebx\n" + : "=a"(out[0]), "=r"(out[1]), "=c"(out[2]), "=d"(out[3]) + : "a"(id), "c"(sid)); +#else + __asm__ __volatile__("cpuid\n" + : "=a"(out[0]), "=b"(out[1]), "=c"(out[2]), "=d"(out[3]) + : "a"(id), "c"(sid)); +#endif +} + + +enum cpu_feature { + SSE2 = 1 << 0, + SSSE3 = 1 << 1, + SSE41 = 1 << 2, + AVX = 1 << 3, + AVX2 = 1 << 4, + AVX512F = 1 << 5, + AVX512VL = 1 << 6, + /* ... */ + UNDEFINED = 1 << 30 +}; + +#if !defined(BLAKE3_TESTING) +static /* Allow the variable to be controlled manually for testing */ +#endif + ATOMIC_INT g_cpu_features = UNDEFINED; + +#if !defined(BLAKE3_TESTING) +static +#endif + enum cpu_feature + get_cpu_features(void) { + + /* If TSAN detects a data race here, try compiling with -DBLAKE3_ATOMICS=1 */ + enum cpu_feature features = ATOMIC_LOAD(g_cpu_features); + if (features != UNDEFINED) { + return features; + } else { +#if defined(IS_X86) + uint32_t regs[4] = {0}; + uint32_t *eax = ®s[0], *ebx = ®s[1], *ecx = ®s[2], *edx = ®s[3]; + (void)edx; + features = 0; + cpuid(regs, 0); + const int max_id = *eax; + cpuid(regs, 1); +#if defined(__amd64__) || defined(_M_X64) + features |= SSE2; +#else + if (*edx & (1UL << 26)) + features |= SSE2; +#endif + if (*ecx & (1UL << 9)) + features |= SSSE3; + if (*ecx & (1UL << 19)) + features |= SSE41; + + if (*ecx & (1UL << 27)) { // OSXSAVE + const uint64_t mask = xgetbv(); + if ((mask & 6) == 6) { // SSE and AVX states + if (*ecx & (1UL << 28)) + features |= AVX; + if (max_id >= 7) { + cpuidex(regs, 7, 0); + if (*ebx & (1UL << 5)) + features |= AVX2; + if ((mask & 224) == 224) { // Opmask, ZMM_Hi256, Hi16_Zmm + if (*ebx & (1UL << 31)) + features |= AVX512VL; + if (*ebx & (1UL << 16)) + features |= AVX512F; + } + } + } + } + ATOMIC_STORE(g_cpu_features, features); + return features; +#else + /* How to detect NEON? */ + return 0; +#endif + } +} +#endif + +void blake3_compress_in_place(uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags) { +#if defined(IS_X86) + const enum cpu_feature features = get_cpu_features(); + MAYBE_UNUSED(features); +#if !defined(BLAKE3_NO_AVX512) + if (features & AVX512VL) { + blake3_compress_in_place_avx512(cv, block, block_len, counter, flags); + return; + } +#endif +#if !defined(BLAKE3_NO_SSE41) + if (features & SSE41) { + blake3_compress_in_place_sse41(cv, block, block_len, counter, flags); + return; + } +#endif +#if !defined(BLAKE3_NO_SSE2) + if (features & SSE2) { + blake3_compress_in_place_sse2(cv, block, block_len, counter, flags); + return; + } +#endif +#endif + blake3_compress_in_place_portable(cv, block, block_len, counter, flags); +} + +void blake3_compress_xof(const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, uint8_t flags, + uint8_t out[64]) { +#if defined(IS_X86) + const enum cpu_feature features = get_cpu_features(); + MAYBE_UNUSED(features); +#if !defined(BLAKE3_NO_AVX512) + if (features & AVX512VL) { + blake3_compress_xof_avx512(cv, block, block_len, counter, flags, out); + return; + } +#endif +#if !defined(BLAKE3_NO_SSE41) + if (features & SSE41) { + blake3_compress_xof_sse41(cv, block, block_len, counter, flags, out); + return; + } +#endif +#if !defined(BLAKE3_NO_SSE2) + if (features & SSE2) { + blake3_compress_xof_sse2(cv, block, block_len, counter, flags, out); + return; + } +#endif +#endif + blake3_compress_xof_portable(cv, block, block_len, counter, flags, out); +} + + +void blake3_xof_many(const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, uint8_t flags, + uint8_t out[64], size_t outblocks) { + if (outblocks == 0) { + // The current assembly implementation always outputs at least 1 block. + return; + } +#if defined(IS_X86) + const enum cpu_feature features = get_cpu_features(); + MAYBE_UNUSED(features); +#if !defined(_WIN32) && !defined(__CYGWIN__) && !defined(BLAKE3_NO_AVX512) + if (features & AVX512VL) { + blake3_xof_many_avx512(cv, block, block_len, counter, flags, out, outblocks); + return; + } +#endif +#endif + for(size_t i = 0; i < outblocks; ++i) { + blake3_compress_xof(cv, block, block_len, counter + i, flags, out + 64*i); + } +} + +void blake3_hash_many(const uint8_t *const *inputs, size_t num_inputs, + size_t blocks, const uint32_t key[8], uint64_t counter, + bool increment_counter, uint8_t flags, + uint8_t flags_start, uint8_t flags_end, uint8_t *out) { +#if defined(IS_X86) + const enum cpu_feature features = get_cpu_features(); + MAYBE_UNUSED(features); +#if !defined(BLAKE3_NO_AVX512) + if ((features & (AVX512F|AVX512VL)) == (AVX512F|AVX512VL)) { + blake3_hash_many_avx512(inputs, num_inputs, blocks, key, counter, + increment_counter, flags, flags_start, flags_end, + out); + return; + } +#endif +#if !defined(BLAKE3_NO_AVX2) + if (features & AVX2) { + blake3_hash_many_avx2(inputs, num_inputs, blocks, key, counter, + increment_counter, flags, flags_start, flags_end, + out); + return; + } +#endif +#if !defined(BLAKE3_NO_SSE41) + if (features & SSE41) { + blake3_hash_many_sse41(inputs, num_inputs, blocks, key, counter, + increment_counter, flags, flags_start, flags_end, + out); + return; + } +#endif +#if !defined(BLAKE3_NO_SSE2) + if (features & SSE2) { + blake3_hash_many_sse2(inputs, num_inputs, blocks, key, counter, + increment_counter, flags, flags_start, flags_end, + out); + return; + } +#endif +#endif + +#if BLAKE3_USE_NEON == 1 + blake3_hash_many_neon(inputs, num_inputs, blocks, key, counter, + increment_counter, flags, flags_start, flags_end, out); + return; +#endif + + blake3_hash_many_portable(inputs, num_inputs, blocks, key, counter, + increment_counter, flags, flags_start, flags_end, + out); +} + +// The dynamically detected SIMD degree of the current platform. +size_t blake3_simd_degree(void) { +#if defined(IS_X86) + const enum cpu_feature features = get_cpu_features(); + MAYBE_UNUSED(features); +#if !defined(BLAKE3_NO_AVX512) + if ((features & (AVX512F|AVX512VL)) == (AVX512F|AVX512VL)) { + return 16; + } +#endif +#if !defined(BLAKE3_NO_AVX2) + if (features & AVX2) { + return 8; + } +#endif +#if !defined(BLAKE3_NO_SSE41) + if (features & SSE41) { + return 4; + } +#endif +#if !defined(BLAKE3_NO_SSE2) + if (features & SSE2) { + return 4; + } +#endif +#endif +#if BLAKE3_USE_NEON == 1 + return 4; +#endif + return 1; +} diff --git a/src/startup_stubs/blake3/blake3_impl.h b/src/startup_stubs/blake3/blake3_impl.h new file mode 100644 index 0000000000..88e71e41e9 --- /dev/null +++ b/src/startup_stubs/blake3/blake3_impl.h @@ -0,0 +1,333 @@ +#ifndef BLAKE3_IMPL_H +#define BLAKE3_IMPL_H + +#include +#include +#include +#include +#include + +#include "blake3.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// internal flags +enum blake3_flags { + CHUNK_START = 1 << 0, + CHUNK_END = 1 << 1, + PARENT = 1 << 2, + ROOT = 1 << 3, + KEYED_HASH = 1 << 4, + DERIVE_KEY_CONTEXT = 1 << 5, + DERIVE_KEY_MATERIAL = 1 << 6, +}; + +// This C implementation tries to support recent versions of GCC, Clang, and +// MSVC. +#if defined(_MSC_VER) +#define INLINE static __forceinline +#else +#define INLINE static inline __attribute__((always_inline)) +#endif + +#ifdef __cplusplus +#define NOEXCEPT noexcept +#else +#define NOEXCEPT +#endif + +#if (defined(__x86_64__) || defined(_M_X64)) && !defined(_M_ARM64EC) +#define IS_X86 +#define IS_X86_64 +#endif + +#if defined(__i386__) || defined(_M_IX86) +#define IS_X86 +#define IS_X86_32 +#endif + +#if defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC) +#define IS_AARCH64 +#endif + +#if defined(IS_X86) +#if defined(_MSC_VER) +#include +#endif +#endif + +#if !defined(BLAKE3_USE_NEON) + // If BLAKE3_USE_NEON not manually set, autodetect based on AArch64ness + #if defined(IS_AARCH64) + #if defined(__ARM_BIG_ENDIAN) + #define BLAKE3_USE_NEON 0 + #else + #define BLAKE3_USE_NEON 1 + #endif + #else + #define BLAKE3_USE_NEON 0 + #endif +#endif + +#if defined(IS_X86) +#define MAX_SIMD_DEGREE 16 +#elif BLAKE3_USE_NEON == 1 +#define MAX_SIMD_DEGREE 4 +#else +#define MAX_SIMD_DEGREE 1 +#endif + +// There are some places where we want a static size that's equal to the +// MAX_SIMD_DEGREE, but also at least 2. +#define MAX_SIMD_DEGREE_OR_2 (MAX_SIMD_DEGREE > 2 ? MAX_SIMD_DEGREE : 2) + +static const uint32_t IV[8] = {0x6A09E667UL, 0xBB67AE85UL, 0x3C6EF372UL, + 0xA54FF53AUL, 0x510E527FUL, 0x9B05688CUL, + 0x1F83D9ABUL, 0x5BE0CD19UL}; + +static const uint8_t MSG_SCHEDULE[7][16] = { + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + {2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8}, + {3, 4, 10, 12, 13, 2, 7, 14, 6, 5, 9, 0, 11, 15, 8, 1}, + {10, 7, 12, 9, 14, 3, 13, 15, 4, 0, 11, 2, 5, 8, 1, 6}, + {12, 13, 9, 11, 15, 10, 14, 8, 7, 2, 5, 3, 0, 1, 6, 4}, + {9, 14, 11, 5, 8, 12, 15, 1, 13, 3, 0, 10, 2, 6, 4, 7}, + {11, 15, 5, 0, 1, 9, 8, 6, 14, 10, 2, 12, 3, 4, 7, 13}, +}; + +/* Find index of the highest set bit */ +/* x is assumed to be nonzero. */ +static unsigned int highest_one(uint64_t x) { +#if defined(__GNUC__) || defined(__clang__) + return 63 ^ (unsigned int)__builtin_clzll(x); +#elif defined(_MSC_VER) && defined(IS_X86_64) + unsigned long index; + _BitScanReverse64(&index, x); + return index; +#elif defined(_MSC_VER) && defined(IS_X86_32) + if(x >> 32) { + unsigned long index; + _BitScanReverse(&index, (unsigned long)(x >> 32)); + return 32 + index; + } else { + unsigned long index; + _BitScanReverse(&index, (unsigned long)x); + return index; + } +#else + unsigned int c = 0; + if(x & 0xffffffff00000000ULL) { x >>= 32; c += 32; } + if(x & 0x00000000ffff0000ULL) { x >>= 16; c += 16; } + if(x & 0x000000000000ff00ULL) { x >>= 8; c += 8; } + if(x & 0x00000000000000f0ULL) { x >>= 4; c += 4; } + if(x & 0x000000000000000cULL) { x >>= 2; c += 2; } + if(x & 0x0000000000000002ULL) { c += 1; } + return c; +#endif +} + +// Count the number of 1 bits. +INLINE unsigned int popcnt(uint64_t x) { +#if defined(__GNUC__) || defined(__clang__) + return (unsigned int)__builtin_popcountll(x); +#else + unsigned int count = 0; + while (x != 0) { + count += 1; + x &= x - 1; + } + return count; +#endif +} + +// Largest power of two less than or equal to x. As a special case, returns 1 +// when x is 0. +INLINE uint64_t round_down_to_power_of_2(uint64_t x) { + return 1ULL << highest_one(x | 1); +} + +INLINE uint32_t counter_low(uint64_t counter) { return (uint32_t)counter; } + +INLINE uint32_t counter_high(uint64_t counter) { + return (uint32_t)(counter >> 32); +} + +INLINE uint32_t load32(const void *src) { + const uint8_t *p = (const uint8_t *)src; + return ((uint32_t)(p[0]) << 0) | ((uint32_t)(p[1]) << 8) | + ((uint32_t)(p[2]) << 16) | ((uint32_t)(p[3]) << 24); +} + +INLINE void load_key_words(const uint8_t key[BLAKE3_KEY_LEN], + uint32_t key_words[8]) { + key_words[0] = load32(&key[0 * 4]); + key_words[1] = load32(&key[1 * 4]); + key_words[2] = load32(&key[2 * 4]); + key_words[3] = load32(&key[3 * 4]); + key_words[4] = load32(&key[4 * 4]); + key_words[5] = load32(&key[5 * 4]); + key_words[6] = load32(&key[6 * 4]); + key_words[7] = load32(&key[7 * 4]); +} + +INLINE void load_block_words(const uint8_t block[BLAKE3_BLOCK_LEN], + uint32_t block_words[16]) { + for (size_t i = 0; i < 16; i++) { + block_words[i] = load32(&block[i * 4]); + } +} + +INLINE void store32(void *dst, uint32_t w) { + uint8_t *p = (uint8_t *)dst; + p[0] = (uint8_t)(w >> 0); + p[1] = (uint8_t)(w >> 8); + p[2] = (uint8_t)(w >> 16); + p[3] = (uint8_t)(w >> 24); +} + +INLINE void store_cv_words(uint8_t bytes_out[32], uint32_t cv_words[8]) { + store32(&bytes_out[0 * 4], cv_words[0]); + store32(&bytes_out[1 * 4], cv_words[1]); + store32(&bytes_out[2 * 4], cv_words[2]); + store32(&bytes_out[3 * 4], cv_words[3]); + store32(&bytes_out[4 * 4], cv_words[4]); + store32(&bytes_out[5 * 4], cv_words[5]); + store32(&bytes_out[6 * 4], cv_words[6]); + store32(&bytes_out[7 * 4], cv_words[7]); +} + +void blake3_compress_in_place(uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags); + +void blake3_compress_xof(const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, uint8_t flags, + uint8_t out[64]); + +void blake3_xof_many(const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, uint8_t flags, + uint8_t out[64], size_t outblocks); + +void blake3_hash_many(const uint8_t *const *inputs, size_t num_inputs, + size_t blocks, const uint32_t key[8], uint64_t counter, + bool increment_counter, uint8_t flags, + uint8_t flags_start, uint8_t flags_end, uint8_t *out); + +size_t blake3_simd_degree(void); + +BLAKE3_PRIVATE size_t blake3_compress_subtree_wide(const uint8_t *input, size_t input_len, + const uint32_t key[8], + uint64_t chunk_counter, uint8_t flags, + uint8_t *out, bool use_tbb); + +#if defined(BLAKE3_USE_TBB) +BLAKE3_PRIVATE void blake3_compress_subtree_wide_join_tbb( + // shared params + const uint32_t key[8], uint8_t flags, bool use_tbb, + // left-hand side params + const uint8_t *l_input, size_t l_input_len, uint64_t l_chunk_counter, + uint8_t *l_cvs, size_t *l_n, + // right-hand side params + const uint8_t *r_input, size_t r_input_len, uint64_t r_chunk_counter, + uint8_t *r_cvs, size_t *r_n) NOEXCEPT; +#endif + +// Declarations for implementation-specific functions. +void blake3_compress_in_place_portable(uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags); + +void blake3_compress_xof_portable(const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags, uint8_t out[64]); + +void blake3_hash_many_portable(const uint8_t *const *inputs, size_t num_inputs, + size_t blocks, const uint32_t key[8], + uint64_t counter, bool increment_counter, + uint8_t flags, uint8_t flags_start, + uint8_t flags_end, uint8_t *out); + +#if defined(IS_X86) +#if !defined(BLAKE3_NO_SSE2) +void blake3_compress_in_place_sse2(uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags); +void blake3_compress_xof_sse2(const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags, uint8_t out[64]); +void blake3_hash_many_sse2(const uint8_t *const *inputs, size_t num_inputs, + size_t blocks, const uint32_t key[8], + uint64_t counter, bool increment_counter, + uint8_t flags, uint8_t flags_start, + uint8_t flags_end, uint8_t *out); +#endif +#if !defined(BLAKE3_NO_SSE41) +void blake3_compress_in_place_sse41(uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags); +void blake3_compress_xof_sse41(const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags, uint8_t out[64]); +void blake3_hash_many_sse41(const uint8_t *const *inputs, size_t num_inputs, + size_t blocks, const uint32_t key[8], + uint64_t counter, bool increment_counter, + uint8_t flags, uint8_t flags_start, + uint8_t flags_end, uint8_t *out); +#endif +#if !defined(BLAKE3_NO_AVX2) +void blake3_hash_many_avx2(const uint8_t *const *inputs, size_t num_inputs, + size_t blocks, const uint32_t key[8], + uint64_t counter, bool increment_counter, + uint8_t flags, uint8_t flags_start, + uint8_t flags_end, uint8_t *out); +#endif +#if !defined(BLAKE3_NO_AVX512) +void blake3_compress_in_place_avx512(uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags); + +void blake3_compress_xof_avx512(const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags, uint8_t out[64]); + +void blake3_hash_many_avx512(const uint8_t *const *inputs, size_t num_inputs, + size_t blocks, const uint32_t key[8], + uint64_t counter, bool increment_counter, + uint8_t flags, uint8_t flags_start, + uint8_t flags_end, uint8_t *out); + +#if !defined(_WIN32) && !defined(__CYGWIN__) +void blake3_xof_many_avx512(const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, uint8_t flags, + uint8_t* out, size_t outblocks); +#endif +#endif +#endif + +#if BLAKE3_USE_NEON == 1 +void blake3_hash_many_neon(const uint8_t *const *inputs, size_t num_inputs, + size_t blocks, const uint32_t key[8], + uint64_t counter, bool increment_counter, + uint8_t flags, uint8_t flags_start, + uint8_t flags_end, uint8_t *out); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* BLAKE3_IMPL_H */ diff --git a/src/startup_stubs/blake3/blake3_portable.c b/src/startup_stubs/blake3/blake3_portable.c new file mode 100644 index 0000000000..062dd1b47f --- /dev/null +++ b/src/startup_stubs/blake3/blake3_portable.c @@ -0,0 +1,160 @@ +#include "blake3_impl.h" +#include + +INLINE uint32_t rotr32(uint32_t w, uint32_t c) { + return (w >> c) | (w << (32 - c)); +} + +INLINE void g(uint32_t *state, size_t a, size_t b, size_t c, size_t d, + uint32_t x, uint32_t y) { + state[a] = state[a] + state[b] + x; + state[d] = rotr32(state[d] ^ state[a], 16); + state[c] = state[c] + state[d]; + state[b] = rotr32(state[b] ^ state[c], 12); + state[a] = state[a] + state[b] + y; + state[d] = rotr32(state[d] ^ state[a], 8); + state[c] = state[c] + state[d]; + state[b] = rotr32(state[b] ^ state[c], 7); +} + +INLINE void round_fn(uint32_t state[16], const uint32_t *msg, size_t round) { + // Select the message schedule based on the round. + const uint8_t *schedule = MSG_SCHEDULE[round]; + + // Mix the columns. + g(state, 0, 4, 8, 12, msg[schedule[0]], msg[schedule[1]]); + g(state, 1, 5, 9, 13, msg[schedule[2]], msg[schedule[3]]); + g(state, 2, 6, 10, 14, msg[schedule[4]], msg[schedule[5]]); + g(state, 3, 7, 11, 15, msg[schedule[6]], msg[schedule[7]]); + + // Mix the rows. + g(state, 0, 5, 10, 15, msg[schedule[8]], msg[schedule[9]]); + g(state, 1, 6, 11, 12, msg[schedule[10]], msg[schedule[11]]); + g(state, 2, 7, 8, 13, msg[schedule[12]], msg[schedule[13]]); + g(state, 3, 4, 9, 14, msg[schedule[14]], msg[schedule[15]]); +} + +INLINE void compress_pre(uint32_t state[16], const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, uint8_t flags) { + uint32_t block_words[16]; + block_words[0] = load32(block + 4 * 0); + block_words[1] = load32(block + 4 * 1); + block_words[2] = load32(block + 4 * 2); + block_words[3] = load32(block + 4 * 3); + block_words[4] = load32(block + 4 * 4); + block_words[5] = load32(block + 4 * 5); + block_words[6] = load32(block + 4 * 6); + block_words[7] = load32(block + 4 * 7); + block_words[8] = load32(block + 4 * 8); + block_words[9] = load32(block + 4 * 9); + block_words[10] = load32(block + 4 * 10); + block_words[11] = load32(block + 4 * 11); + block_words[12] = load32(block + 4 * 12); + block_words[13] = load32(block + 4 * 13); + block_words[14] = load32(block + 4 * 14); + block_words[15] = load32(block + 4 * 15); + + state[0] = cv[0]; + state[1] = cv[1]; + state[2] = cv[2]; + state[3] = cv[3]; + state[4] = cv[4]; + state[5] = cv[5]; + state[6] = cv[6]; + state[7] = cv[7]; + state[8] = IV[0]; + state[9] = IV[1]; + state[10] = IV[2]; + state[11] = IV[3]; + state[12] = counter_low(counter); + state[13] = counter_high(counter); + state[14] = (uint32_t)block_len; + state[15] = (uint32_t)flags; + + round_fn(state, &block_words[0], 0); + round_fn(state, &block_words[0], 1); + round_fn(state, &block_words[0], 2); + round_fn(state, &block_words[0], 3); + round_fn(state, &block_words[0], 4); + round_fn(state, &block_words[0], 5); + round_fn(state, &block_words[0], 6); +} + +void blake3_compress_in_place_portable(uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags) { + uint32_t state[16]; + compress_pre(state, cv, block, block_len, counter, flags); + cv[0] = state[0] ^ state[8]; + cv[1] = state[1] ^ state[9]; + cv[2] = state[2] ^ state[10]; + cv[3] = state[3] ^ state[11]; + cv[4] = state[4] ^ state[12]; + cv[5] = state[5] ^ state[13]; + cv[6] = state[6] ^ state[14]; + cv[7] = state[7] ^ state[15]; +} + +void blake3_compress_xof_portable(const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, uint64_t counter, + uint8_t flags, uint8_t out[64]) { + uint32_t state[16]; + compress_pre(state, cv, block, block_len, counter, flags); + + store32(&out[0 * 4], state[0] ^ state[8]); + store32(&out[1 * 4], state[1] ^ state[9]); + store32(&out[2 * 4], state[2] ^ state[10]); + store32(&out[3 * 4], state[3] ^ state[11]); + store32(&out[4 * 4], state[4] ^ state[12]); + store32(&out[5 * 4], state[5] ^ state[13]); + store32(&out[6 * 4], state[6] ^ state[14]); + store32(&out[7 * 4], state[7] ^ state[15]); + store32(&out[8 * 4], state[8] ^ cv[0]); + store32(&out[9 * 4], state[9] ^ cv[1]); + store32(&out[10 * 4], state[10] ^ cv[2]); + store32(&out[11 * 4], state[11] ^ cv[3]); + store32(&out[12 * 4], state[12] ^ cv[4]); + store32(&out[13 * 4], state[13] ^ cv[5]); + store32(&out[14 * 4], state[14] ^ cv[6]); + store32(&out[15 * 4], state[15] ^ cv[7]); +} + +INLINE void hash_one_portable(const uint8_t *input, size_t blocks, + const uint32_t key[8], uint64_t counter, + uint8_t flags, uint8_t flags_start, + uint8_t flags_end, uint8_t out[BLAKE3_OUT_LEN]) { + uint32_t cv[8]; + memcpy(cv, key, BLAKE3_KEY_LEN); + uint8_t block_flags = flags | flags_start; + while (blocks > 0) { + if (blocks == 1) { + block_flags |= flags_end; + } + blake3_compress_in_place_portable(cv, input, BLAKE3_BLOCK_LEN, counter, + block_flags); + input = &input[BLAKE3_BLOCK_LEN]; + blocks -= 1; + block_flags = flags; + } + store_cv_words(out, cv); +} + +void blake3_hash_many_portable(const uint8_t *const *inputs, size_t num_inputs, + size_t blocks, const uint32_t key[8], + uint64_t counter, bool increment_counter, + uint8_t flags, uint8_t flags_start, + uint8_t flags_end, uint8_t *out) { + while (num_inputs > 0) { + hash_one_portable(inputs[0], blocks, key, counter, flags, flags_start, + flags_end, out); + if (increment_counter) { + counter += 1; + } + inputs += 1; + num_inputs -= 1; + out = &out[BLAKE3_OUT_LEN]; + } +} diff --git a/src/startup_stubs/buffer_address_index.h b/src/startup_stubs/buffer_address_index.h new file mode 100644 index 0000000000..71d8344924 --- /dev/null +++ b/src/startup_stubs/buffer_address_index.h @@ -0,0 +1,76 @@ +#pragma once +#include +#include +#include +#include +#include + +namespace x2w_startup { + +template class BufferAddressIndex { +public: + enum class Mutation { none, exact_start }; // exact_start: the test's negative control (ignores the window) + explicit BufferAddressIndex(Mutation m = Mutation::none) : mutation_(m) {} + + void insert(Key key, std::uint64_t base, std::uint64_t width) + { + erase(key); + if (!width || width > ~std::uint64_t{} - base) return; + Group& g = groups_[class_of(width)]; + g.by_start.emplace(base, Entry{key, width}); + if (width > g.max_width) g.max_width = width; + where_[key] = {base, width}; + } + bool erase(Key key) + { + const auto found = where_.find(key); + if (found == where_.end()) return false; + const auto [base, width] = found->second; + Group& g = groups_[class_of(width)]; + const auto [first, last] = g.by_start.equal_range(base); + for (auto it = first; it != last; ++it) + if (it->second.key == key) { + g.by_start.erase(it); + break; + } + where_.erase(found); + return true; + } + // visit(key, base, width) for every range that contains [address, address + bytes) (bytes >= 1); visit returns + // false to stop. Order: by class, then by start. + template void containing(std::uint64_t address, std::uint64_t bytes, Visit&& visit) const + { + if (!bytes || bytes > ~std::uint64_t{} - address) return; + for (const Group& g : groups_) { + if (g.by_start.empty()) continue; + const std::uint64_t earliest = mutation_ == Mutation::exact_start ? address + : address >= g.max_width ? address - g.max_width + 1 : 0; + for (auto it = g.by_start.lower_bound(earliest); it != g.by_start.end() && it->first <= address; ++it) { + const std::uint64_t base = it->first, width = it->second.width; + if (address - base >= width || bytes > width - (address - base)) continue; + if (!visit(it->second.key, base, width)) return; + } + } + } + std::size_t size() const { return where_.size(); } + +private: + struct Entry { + Key key; + std::uint64_t width; + }; + struct Group { + std::multimap by_start; + std::uint64_t max_width = 0; + }; + static std::size_t class_of(std::uint64_t width) + { + return width <= (std::uint64_t{1} << 16) ? 0 : width <= (std::uint64_t{1} << 20) ? 1 : width <= (std::uint64_t{1} << 24) ? 2 + : width <= (std::uint64_t{1} << 28) ? 3 : 4; + } + std::array groups_; + std::unordered_map> where_; + Mutation mutation_; +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/chad.cpp b/src/startup_stubs/chad.cpp index 93149cce43..6b62592c71 100644 --- a/src/startup_stubs/chad.cpp +++ b/src/startup_stubs/chad.cpp @@ -47,27 +47,22 @@ long release_handle(const char* name, unsigned index, u64 rcx, u64 rdx, u64 r8, } } // namespace +// XDspActivate(connection, parameters, &state, &handle): the caller keeps both outputs next to each +// other in its effect object and later reads the state block (+0x4 compared with its own counter, +// +0xc tested for zero). Each activation gets its own zeroed 256-byte state block and a handle. extern "C" __declspec(noinline) long XDspActivate(u64 rcx, u64 rdx, u64 r8, u64 r9) { static LONG calls; - accept("XDspActivate", 0, rcx, rdx, r8, r9, _ReturnAddress(), calls); - // XDspActivate(client, params, XDspStatus** status, XDspStreamHandle* stream). No XDSP device exists - // under this stand-in, so the call fails the way the documented code says instead of returning success - // with both outputs untouched: validate them, clear them, then report the failure. - auto** status_out = reinterpret_cast(static_cast(r8)); - auto** stream_out = reinterpret_cast(static_cast(r9)); - if (!status_out || !x2w_local::writable(status_out, sizeof(void*)) || - !stream_out || !x2w_local::writable(stream_out, sizeof(void*))) { - x2w_local::logf("x2w-audio XDspActivate status_out=%p stream_out=%p -> E_POINTER", - static_cast(status_out), static_cast(stream_out)); - return hr_pointer; + const long result = accept("XDspActivate", 0, rcx, rdx, r8, r9, _ReturnAddress(), calls); + static unsigned char* blocks = static_cast(VirtualAlloc(nullptr, 1u << 20, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + static LONG used; + const LONG index = InterlockedIncrement(&used) - 1; + if (blocks && index < 4096) { + void* state = blocks + static_cast(index) * 256; + if (r8 && x2w_local::writable(reinterpret_cast(r8), sizeof(void*))) *reinterpret_cast(r8) = state; + if (r9 && x2w_local::writable(reinterpret_cast(r9), sizeof(u64))) *reinterpret_cast(r9) = 0x58325344ull << 32 | (index + 1); } - *status_out = nullptr; - *stream_out = nullptr; - x2w_local::logf("x2w-audio XDspActivate status_out=%p stream_out=%p -> 0x8AC810A2 " - "(XDSP_E_NO_DEVICE_RESOURCES)", - static_cast(status_out), static_cast(stream_out)); - return hr_no_device_resources; + return result; } extern "C" __declspec(noinline) long XDspConnectWithMaximumStreamLimit(u64 rcx, u64 rdx, u64 r8, u64 r9, u64 flag, void** handle) diff --git a/src/startup_stubs/cull_input_capture.inl b/src/startup_stubs/cull_input_capture.inl new file mode 100644 index 0000000000..68706d38aa --- /dev/null +++ b/src/startup_stubs/cull_input_capture.inl @@ -0,0 +1,624 @@ +// LOCAL (diagnostic): X2W_CULL_INPUT_CAPTURE. In the traced frame (X2W_D3D12_TRACE_FRAME), for selected translated +// compute dispatches (key and occurrence), copy what the dispatch reads, as the GPU sees it at that point of the list, +// into read-back buffers, and write them with an index next to the trap log (/cullcap/). Nothing is written +// back to the title or changes what the dispatch does; the copies only add barriers and copies around it. +// +// X2W_CULL_INPUT_CAPTURE=:[,...] the n-th (0-based) translated dispatch of in the traced frame, +// in recording order over all threads; :* = every one (max 8) +// X2W_CULL_CAPTURE_MAX_MB= cap per buffer copy (default 256) +// X2W_CULL_CAPTURE_FRAMES= frames to capture (default 1: the first traced frame with a selection) +// X2W_CULL_CAPTURE_TOTAL_MB= cap on all copies of one frame (default 1024; logged when hit) +// X2W_CULL_CAPTURE_EXTRA=:[,...] more title ranges (hex address, decimal or 0x bytes) copied before +// every selected dispatch (for reads the replay reports as unmapped) +// +// Before the dispatch: every bound table buffer (manifest resource; title address, bytes, stride, V# word 3), every +// bound texture (all mips of the resource), the indirect record the dispatch consumes, and the EXTRA ranges. For a +// heap shader (SM 6.6 heap): the heapmem view the shader reads (GPU copy of its window range), the vinfo words, and +// for every entry constant of kind 3 that names a heap slot holding a view token, the buffer the raw view installed +// for that token addresses (copied from the install's own window and offset: exactly what the shader reads), with +// the install's state. SRV and heap buffers above 1 MiB are copied once per frame per range (later dispatches get a +// "dup" line naming the earlier file: ASSUMED unchanged in between); UAV buffers are copied for every dispatch. +// CPU side, at record time: the root constants, the title view heap's bytes, the root tables and every view record +// (id -> address, bytes, descriptor words). +// After the dispatch (behind the UAV barrier): every bound UAV buffer up to 4 MiB (the X records, the list). +// Index: cullcap/index.tsv, one line per blob: frame, key, occ, phase, kind, label, title address, bytes, file, extra. +namespace cull_capture { + +using Microsoft::WRL::ComPtr; + +struct Want { u64 key; int occ; }; // occ -1: every occurrence (at most 8) + +struct Blob { + ComPtr readback; + ID3D12GraphicsCommandList* list = nullptr; + std::string name, extra; // file name, index columns after the file + std::string head; // index columns before the file + u64 bytes = 0; // bytes to write + // texture mip: rows are copied with a pitch; written tight + UINT rows = 0; + u64 row_bytes = 0, row_pitch = 0, offset = 0; + ComPtr fence; + bool submitted = false, live = true; +}; + +struct State { + std::mutex lock; + std::vector wants; + std::vector> extra; + u64 max_bytes = 256ull << 20; + u64 total_max = 1024ull << 20, frame_bytes = 0; + bool total_logged = false; + int frames_max = 1, frames_done = 0; + bool frame_had = false; + LONG frame = -1; + std::vector> seen; // key -> occurrences counted in `frame` + struct Large { u64 address, bytes; std::string name; }; + std::vector large; // > 1 MiB SRV / heap copies made in `frame` + std::vector blobs; + std::wstring dir; + bool views_written_frame = false; + unsigned captured = 0; +}; + +inline u64 parse_number(const char* s, char** end) +{ + if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) return std::strtoull(s + 2, end, 16); + return std::strtoull(s, end, 10); +} + +State* cc_state() +{ + static State* const s = [] () -> State* { + char value[1024]{}; + const DWORD n = GetEnvironmentVariableA("X2W_CULL_INPUT_CAPTURE", value, sizeof(value)); + if (!n || n >= sizeof(value) || std::strcmp(value, "0") == 0) return nullptr; + auto* st = new State; + const std::string spec(value); + for (std::size_t at = 0; at < spec.size();) { + const std::size_t end = (std::min)(spec.find(',', at), spec.size()); + const std::string item = spec.substr(at, end - at); + const std::size_t colon = item.find(':'); + if (colon == 16) { + const u64 key = std::strtoull(item.substr(0, 16).c_str(), nullptr, 16); + const std::string occ = item.substr(17); + st->wants.push_back({key, occ == "*" ? -1 : std::atoi(occ.c_str())}); + } else { + log("x2w-cullcap: ignored selection '%s' (want <16 hex key>:)", item.c_str()); + } + at = end + 1; + } + if (GetEnvironmentVariableA("X2W_CULL_CAPTURE_MAX_MB", value, sizeof(value))) + st->max_bytes = (std::max)(1, std::strtoull(value, nullptr, 10)) << 20; + if (GetEnvironmentVariableA("X2W_CULL_CAPTURE_FRAMES", value, sizeof(value))) + st->frames_max = (std::max)(1, std::atoi(value)); + if (GetEnvironmentVariableA("X2W_CULL_CAPTURE_TOTAL_MB", value, sizeof(value))) + st->total_max = (std::max)(1, std::strtoull(value, nullptr, 10)) << 20; + if (const DWORD m = GetEnvironmentVariableA("X2W_CULL_CAPTURE_EXTRA", value, sizeof(value)); m && m < sizeof(value)) { + char* p = value; + while (*p) { + char* e = nullptr; + const u64 address = std::strtoull(p, &e, 16); + if (e == p || *e != ':') break; + const u64 bytes = parse_number(e + 1, &e); + if (address && bytes) st->extra.emplace_back(address, bytes); + if (*e != ',') break; + p = e + 1; + } + } + wchar_t trap[MAX_PATH]{}; + const DWORD length = GetEnvironmentVariableW(L"X2W_TRAP_LOG", trap, MAX_PATH); + if (length && length < MAX_PATH) { + st->dir.assign(trap, length); + st->dir.resize(st->dir.find_last_of(L"/\\") + 1); + } + st->dir += L"cullcap\\"; + CreateDirectoryW(st->dir.c_str(), nullptr); + std::string keys; + for (const Want& w : st->wants) { + char t[40]; + std::snprintf(t, sizeof(t), "%s%016llx:%s", keys.empty() ? "" : ",", w.key, w.occ < 0 ? "*" : std::to_string(w.occ).c_str()); + keys += t; + } + log("x2w-cullcap: armed for the traced frame: %s; max %llu MiB per buffer; %zu extra ranges", keys.c_str(), + st->max_bytes >> 20, st->extra.size()); + return st; + }(); + return s; +} + +// The occurrence of `key` this dispatch is (>= 0) when it is selected, else -1. Counts every translated dispatch of a +// wanted key in the traced frame, selected or not. +int pick(u64 key) +{ + State* st = cc_state(); + if (!st || !trace_frame_active) return -1; + std::lock_guard guard(st->lock); + if (st->frame != frame_number) { + st->frame = frame_number; + st->seen.clear(); + st->large.clear(); + st->views_written_frame = false; + st->frame_bytes = 0; + st->total_logged = false; + if (st->frame_had) ++st->frames_done; + st->frame_had = false; + } + bool wanted = false; + for (const Want& w : st->wants) wanted |= w.key == key; + if (!wanted) return -1; + int occ = 0; + bool found = false; + for (auto& s : st->seen) + if (s.first == key) { occ = s.second++; found = true; } + if (!found) st->seen.emplace_back(key, 1); + if (st->frames_done >= st->frames_max) return -1; + for (const Want& w : st->wants) + if (w.key == key && (w.occ == occ || (w.occ < 0 && occ < 8))) { + st->frame_had = true; + return occ; + } + return -1; +} + +std::string hex(u64 v) +{ + char t[24]; + std::snprintf(t, sizeof(t), "0x%llx", v); + return t; +} + +ComPtr readback_buffer(u64 bytes) +{ + ComPtr r; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = bytes ? bytes : 16; + d.Height = d.DepthOrArraySize = d.MipLevels = d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + auto* device = device_of(the_device); + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&r)))) + return nullptr; + x2w_budget::committed(device, r.Get(), D3D12_HEAP_TYPE_READBACK); + return r; +} + +struct Ctx { + State* st; + ID3D12GraphicsCommandList* list; + u64 key; + int occ; + const char* phase; + std::string prefix; // file name prefix + std::string head; // index columns frame..phase +}; + +void index_line(State* st, const std::string& line); + +// GPU copy of [at, at + bytes) of desktop buffer `window` (in UNORDERED_ACCESS on the list, as every window the +// translated paths bind), which holds title range [address, address + bytes). +void copy_window(Ctx& c, const std::string& label, ID3D12Resource* window, u64 at, u64 bytes, u64 address, const std::string& extra, bool once_large) +{ + if (!window || !bytes) return; + bool clipped = false; + if (bytes > c.st->max_bytes) bytes = c.st->max_bytes, clipped = true; + const std::string name = c.prefix + "-" + label + ".bin"; + if (once_large && bytes > (1u << 20)) { + for (const auto& l : c.st->large) + if (l.address == address && l.bytes == bytes) { + index_line(c.st, c.head + "\tdup\t" + label + "\t" + hex(address) + "\t" + std::to_string(bytes) + "\t" + l.name + "\t" + extra + + ";copied earlier in this frame (ASSUMED unchanged since)"); + return; + } + c.st->large.push_back({address, bytes, name}); + } + if (c.st->frame_bytes + bytes > c.st->total_max) { + if (!c.st->total_logged) log("x2w-cullcap: X2W_CULL_CAPTURE_TOTAL_MB reached (%llu MiB); later copies of this frame skipped", c.st->total_max >> 20); + c.st->total_logged = true; + index_line(c.st, c.head + "\tskipped\t" + label + "\t" + hex(address) + "\t" + std::to_string(bytes) + "\t-\t" + extra + ";total cap"); + return; + } + c.st->frame_bytes += bytes; + Blob b; + b.readback = readback_buffer(bytes); + if (!b.readback) { + log("x2w-cullcap %016llx occ %d %s %s: read-back allocation of %llu bytes failed", c.key, c.occ, c.phase, label.c_str(), bytes); + return; + } + D3D12_RESOURCE_BARRIER t{}; + t.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + t.Transition.pResource = window; + t.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + t.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; // as indirect_stage: windows rest in COMMON / UAV + t.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + c.list->ResourceBarrier(1, &t); + c.list->CopyBufferRegion(b.readback.Get(), 0, window, at, bytes); + std::swap(t.Transition.StateBefore, t.Transition.StateAfter); + c.list->ResourceBarrier(1, &t); + b.list = c.list; + b.bytes = bytes; + b.name = name; + b.head = c.head + "\tbuf\t" + label + "\t" + hex(address) + "\t" + std::to_string(bytes); + b.extra = extra + (clipped ? ";clipped" : ""); + c.st->blobs.push_back(std::move(b)); +} + +// GPU copy of title range [address, address + bytes) through its desktop window (desktop_range: the window the +// table binding path binds). +void copy_range(Ctx& c, const std::string& label, u64 address, u64 bytes, const std::string& extra, bool once_large) +{ + if (!address || !bytes) return; + if (bytes > c.st->max_bytes) bytes = c.st->max_bytes; + ID3D12Resource* window = nullptr; + u64 at = 0; + if (!desktop_range(address, bytes, &window, &at)) { + index_line(c.st, c.head + "\tmissing\t" + label + "\t" + hex(address) + "\t" + std::to_string(bytes) + "\t-\t" + extra + ";no desktop window"); + return; + } + copy_window(c, label, window, at, bytes, address, extra, once_large); +} + +void copy_texture(Wrapper* self, Ctx& c, const char* label, ID3D12Resource* texture, bool uav, const std::string& extra) +{ + const D3D12_RESOURCE_DESC desc = texture->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.DepthOrArraySize != 1 || desc.SampleDesc.Count != 1) { + log("x2w-cullcap %016llx occ %d %s %s: texture not a single 2D (dimension %d array %u)", c.key, c.occ, c.phase, label, + desc.Dimension, desc.DepthOrArraySize); + return; + } + auto* device = device_of(the_device); + require_state(self, texture, D3D12_RESOURCE_STATE_COPY_SOURCE); + for (UINT mip = 0; mip < desc.MipLevels; ++mip) { + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; + UINT rows = 0; + UINT64 row_bytes = 0, total = 0; + device->GetCopyableFootprints(&desc, mip, 1, 0, &fp, &rows, &row_bytes, &total); + if (!total || total > c.st->max_bytes) continue; + Blob b; + b.readback = readback_buffer(total); + if (!b.readback) continue; + const D3D12_TEXTURE_COPY_LOCATION from{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {mip}}; + D3D12_TEXTURE_COPY_LOCATION to{b.readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = fp; + c.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + b.list = c.list; + b.rows = rows; + b.row_bytes = row_bytes; + b.row_pitch = fp.Footprint.RowPitch; + b.offset = fp.Offset; + b.bytes = u64{rows} * row_bytes; + b.name = c.prefix + "-" + label + "-mip" + std::to_string(mip) + ".bin"; + b.head = c.head + "\ttex\t" + label + "\t0\t" + std::to_string(b.bytes); + b.extra = extra + ";mip=" + std::to_string(mip) + ";width=" + std::to_string(fp.Footprint.Width) + ";height=" + + std::to_string(fp.Footprint.Height) + ";mips=" + std::to_string(desc.MipLevels) + ";dxgi=" + std::to_string(desc.Format) + + ";row_bytes=" + std::to_string(row_bytes); + c.st->blobs.push_back(std::move(b)); + } + require_state(self, texture, uav ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS : D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); +} + +bool write_file(const std::wstring& path, const void* data, std::size_t bytes) +{ + FILE* f = nullptr; + if (_wfopen_s(&f, path.c_str(), L"wb") || !f) return false; + const bool ok = !bytes || std::fwrite(data, 1, bytes, f) == bytes; + return std::fclose(f) == 0 && ok; +} + +void index_line(State* st, const std::string& line) +{ + FILE* f = nullptr; + if (_wfopen_s(&f, (st->dir + L"index.tsv").c_str(), L"ab") || !f) return; + std::fprintf(f, "%s\n", line.c_str()); + std::fclose(f); +} + +std::wstring wide(const std::string& s) { return std::wstring(s.begin(), s.end()); } + +// CPU-side blob, written now (title memory as the CPU holds it at record time). +void cpu_blob(Ctx& c, const char* label, u64 address, const void* data, std::size_t bytes, const std::string& extra) +{ + const std::string name = c.prefix + "-" + label + ".bin"; + const bool ok = write_file(c.st->dir + wide(name), data, bytes); + index_line(c.st, c.head + "\tcpu\t" + label + "\t" + hex(address) + "\t" + std::to_string(bytes) + "\t" + (ok ? name : "WRITE-FAILED") + "\t" + extra); +} + +// Every view record the runtime knows: id, slot, image (T#), title address, bytes, descriptor dwords 0..7 as the +// translated shaders see them (view_record_words; a buffer's address is filled in here from the record). +void write_view_records(Ctx& c) +{ + if (c.st->views_written_frame) return; + c.st->views_written_frame = true; + std::string out = "id\tslot\timage\taddress\tbytes\tw0\tw1\tw2\tw3\tw4\tw5\tw6\tw7\n"; + AcquireSRWLockShared(¬e_lock); + const std::vector records = view_records(); // processed outside note_lock (as fill_views does) + ReleaseSRWLockShared(¬e_lock); + for (std::size_t id = 0; id < records.size(); ++id) { + const ViewRecord& record = records[id]; + std::uint32_t v[8]{}; + bool image = false, unmapped = false; + if (!view_record_words(record, v, &image, &unmapped)) continue; + u64 address = 0, bytes = 0; + const Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + const u64 base = resource && resource->own().title_memory ? reinterpret_cast(resource->own().title_memory) : 0; + if (record.slot == 17 && record.desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(&address, record.desc, 8); + std::memcpy(&size, record.desc + 8, 4); + bytes = size; + } else if (!image) { + x2w_startup::BufferViewLayout l; + if (base && x2w_startup::buffer_view_layout_from_desc(record.slot == 19, record.desc, record.desc_bytes, l, typed_views_off())) + address = base + l.offset, bytes = l.bytes; + } else { + address = base; // the T# base stays 0 (the replay places the image itself) + } + if (!image) { + v[0] = static_cast(address); + v[1] = (v[1] & ~0xffffu) | (static_cast(address >> 32) & 0xffff); + } + char line[260]; + std::snprintf(line, sizeof(line), "%zu\t%u\t%d\t0x%llx\t%llu\t%08x\t%08x\t%08x\t%08x\t%08x\t%08x\t%08x\t%08x\n", static_cast(record.id), record.slot, + image ? 1 : 0, address, bytes, v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]); + out += line; + } + const std::string name = "f" + std::to_string(c.st->frame + 1) + "-view-records.tsv"; + const bool ok = write_file(c.st->dir + wide(name), out.data(), out.size()); + index_line(c.st, c.head + "\tcpu\tview-records\t0\t" + std::to_string(out.size()) + "\t" + (ok ? name : "WRITE-FAILED") + "\tid = word 1 of the heap view token (X2WV)"); +} + +} // namespace cull_capture + +// Called by execute_dispatch (d3d12_compute.inl) right before the dispatch is issued (pipeline, root and views bound; +// an indirect record already staged), with the manifest's resources as bound. +void cull_capture_before(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, int occ, const ComputeTranslation& tr, + const u64* res_address, const std::size_t* res_bytes, const std::uint32_t* strides, const std::uint32_t* word3, + Microsoft::WRL::ComPtr* textures, const std::uint32_t* values, UINT value_count, + const TitleHeapView* heap_view, u64 heap_address, UINT x, UINT y, UINT z) +{ + using namespace cull_capture; + State* st = cc_state(); + if (!st || occ < 0) return; + // the heap slots the kind-3 entry constants name, and their raw view installs, read before st->lock: draw_lock + // (which guards raw_srv_installs) is held around submissions, where st->lock is taken too + struct HeapUse { std::size_t ud; std::uint32_t index, id; RawSrvInstall install; }; + std::vector heap_uses; + if (tr.heap && heap_view && heap_view->window) { + for (std::size_t i = 0; i < tr.uds.size() && i < value_count; ++i) { + if (tr.uds[i].kind != 3) continue; + const std::uint32_t index = values[i]; + const u64 byte_index = u64{index} << 5; + if (byte_index + 8 > heap_view->bytes) continue; + UINT words[2]{}; + const auto* at = reinterpret_cast(heap_address + byte_index); + if (!x2w_local::readable(at, sizeof(words))) continue; + std::memcpy(words, at, sizeof(words)); + if (words[0] != view_token_magic || words[1] >= view_ids_max) continue; // not a view token: not a heap index + heap_uses.push_back({i, index, words[1], {}}); + } + AcquireSRWLockExclusive(&draw_lock); + for (HeapUse& u : heap_uses) + if (u.id < raw_srv_installs.size()) u.install = raw_srv_installs[u.id]; + ReleaseSRWLockExclusive(&draw_lock); + } + std::lock_guard guard(st->lock); + const Pass& pass = pass_of(self); + char prefix[96]; + std::snprintf(prefix, sizeof(prefix), "f%ld-%016llx-o%d", frame_number + 1, key, occ); + Ctx c{st, list, key, occ, "before", prefix, ""}; + c.head = std::to_string(frame_number + 1) + "\t" + [&] { char k[20]; std::snprintf(k, sizeof(k), "%016llx", key); return std::string(k); }() + + "\t" + std::to_string(occ) + "\tbefore"; + // dispatch facts + std::string facts = "list=" + hex(reinterpret_cast(list)) + ";xyz=" + std::to_string(x) + "," + std::to_string(y) + "," + std::to_string(z) + ";trace_seq_before=" + std::to_string(dispatch_trace_seq) + + ";heap_address=" + hex(heap_address) + ";numthreads=" + std::to_string(tr.threads[0]) + "x" + std::to_string(tr.threads[1]) + "x" + std::to_string(tr.threads[2]); + for (int p = 0; p < 16; ++p) { + if (pass.compute_kind[p] == 1) { + facts += ";p" + std::to_string(p) + "_constants="; + for (UINT w = 0; w < pass.compute_count[p] && w < 16; ++w) facts += (w ? "," : "") + hex(pass.compute_constants[p][w]); + } else if (pass.compute_kind[p]) { + facts += ";p" + std::to_string(p) + "_kind" + std::to_string(pass.compute_kind[p]) + "=" + hex(pass.compute_address[p]); + } + } + facts += ";entry="; + for (UINT i = 0; i < value_count && i < 64; ++i) facts += (i ? "," : "") + hex(values[i]); + if (IndirectPending* p = indirect_current; p && p->args_window) { + // the indirect record this dispatch consumes (copied from the window as the ring copy read it) + Blob b; + b.readback = readback_buffer(16); + if (b.readback) { + D3D12_RESOURCE_BARRIER t{}; + t.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + t.Transition.pResource = p->args_window; + t.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + t.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + t.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &t); + list->CopyBufferRegion(b.readback.Get(), 0, p->args_window, p->args_at, 12); + std::swap(t.Transition.StateBefore, t.Transition.StateAfter); + list->ResourceBarrier(1, &t); + b.list = list; + b.bytes = 12; + b.name = std::string(prefix) + "-dispatch-args.bin"; + b.head = c.head + "\tbuf\tdispatch-args\t0\t12"; + b.extra = "stride=" + std::to_string(p->stride) + ";max_count=" + std::to_string(p->max_count); + st->blobs.push_back(std::move(b)); + } + facts += ";indirect=1"; + } + index_line(st, c.head + "\tdispatch\tfacts\t0\t0\t-\t" + facts); + log("x2w-cullcap %016llx occ %d frame %ld list %p: capturing (%s)", key, occ, frame_number + 1, list, facts.c_str()); + // table resources + for (std::size_t i = 0; i < tr.res.size() && i < 64; ++i) { + const auto& r = tr.res[i]; + char label[32]; + std::snprintf(label, sizeof(label), "%s%zu", r.uav ? "u" : "t", i); + const std::string extra = "res=" + std::to_string(i) + ";uav=" + std::to_string(r.uav) + ";kind=" + std::to_string(r.kind) + + ";source=" + std::to_string(r.source) + ";param=" + std::to_string(r.a) + ";offset=" + std::to_string(r.b) + + ";stride=" + std::to_string(strides[i]) + ";word3=" + hex(word3[i]); + if (r.kind == 0) copy_range(c, label, res_address[i], res_bytes[i], extra, !r.uav); + else if (textures[i]) copy_texture(self, c, label, textures[i].Get(), r.uav, extra); + else index_line(st, c.head + "\tmissing\t" + label + "\t0\t0\t-\t" + extra + ";not bound or not traced"); + } + // heap shader: the heapmem view as the GPU reads it, the vinfo words, and the buffers behind the entry constants + if (tr.heap && heap_view && heap_view->window) { + copy_window(c, "heapmem", heap_view->window, heap_view->offset, heap_view->bytes, heap_address, + "title_heap_bytes=" + std::to_string(heap_view->heap_bytes) + ";view_bytes=" + std::to_string(heap_view->bytes), true); + if (vinfo_words) cpu_blob(c, "vinfo", 0, vinfo_words, std::size_t{view_ids_max} * 16, "16 bytes per view id: stride, format code, 0, 0"); + for (const HeapUse& u : heap_uses) { + const std::size_t i = u.ud; + const std::uint32_t index = u.index; + const std::uint32_t words[2] = {view_token_magic, u.id}; + const RawSrvInstall& install = u.install; + const std::string label = "heap" + std::to_string(index); + const std::string extra = "ud=" + std::to_string(i) + ";param=" + std::to_string(tr.uds[i].a) + ";word=" + std::to_string(tr.uds[i].b) + + ";index=" + std::to_string(index) + ";view_id=" + std::to_string(words[1]) + ";install=" + install.state + + ";install_address=" + hex(install.address) + ";install_bytes=" + std::to_string(install.bytes) + + ";gpuva=" + hex(install.gpuva) + ";window_offset=" + hex(install.offset); + if (install.window) copy_window(c, label, install.window, install.offset, install.bytes, install.address, extra, true); + else index_line(st, c.head + "\tmissing\t" + label + "\t" + hex(install.address) + "\t" + std::to_string(install.bytes) + "\t-\t" + extra + + ";no raw view installed (the shader reads a null view: zeros)"); + } + } + const TraceHeap heap = record_trace_heap(pass); + if (heap.base && heap.bytes && x2w_local::readable(reinterpret_cast(heap.base), static_cast(heap.bytes))) + cpu_blob(c, "title-heap", heap.base, reinterpret_cast(heap.base), static_cast(heap.bytes), + "count=" + std::to_string(heap.count) + ";increment=" + std::to_string(heap.increment)); + for (int p = 0; p < 16; ++p) { + if (pass.compute_kind[p] != 5 || !pass.compute_address[p]) continue; + const u64 table = pass.compute_address[p]; + std::size_t bytes = 0; // the bytes the manifest reads from this table (entries are 32 bytes) + for (const auto& r : tr.res) + if (r.source == 0 && r.a == p) bytes = (std::max)(bytes, static_cast(r.b) + 32); + for (const auto& u : tr.uds) + if (u.kind == 7 && u.a == p) bytes = (std::max)(bytes, static_cast(u.b) + 4); + bytes = bytes ? (bytes + 31) & ~std::size_t{31} : 0x200; + if (x2w_local::readable(reinterpret_cast(table), bytes)) { + char label[24]; + std::snprintf(label, sizeof(label), "table-p%d", p); + cpu_blob(c, label, table, reinterpret_cast(table), bytes, "param=" + std::to_string(p)); + } + } + write_view_records(c); + for (std::size_t i = 0; i < st->extra.size(); ++i) { + char label[24]; + std::snprintf(label, sizeof(label), "extra%zu", i); + copy_range(c, label, st->extra[i].first, st->extra[i].second, "", true); + } +} + +// After the dispatch's UAV barrier: the bound UAV buffers up to 4 MiB. +void cull_capture_after(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, int occ, const ComputeTranslation& tr, + const u64* res_address, const std::size_t* res_bytes) +{ + using namespace cull_capture; + State* st = cc_state(); + if (!st || occ < 0) return; + std::lock_guard guard(st->lock); + char prefix[96]; + std::snprintf(prefix, sizeof(prefix), "f%ld-%016llx-o%d-after", frame_number + 1, key, occ); + char k[20]; + std::snprintf(k, sizeof(k), "%016llx", key); + Ctx c{st, list, key, occ, "after", prefix, std::to_string(frame_number + 1) + "\t" + k + "\t" + std::to_string(occ) + "\tafter"}; + for (std::size_t i = 0; i < tr.res.size() && i < 64; ++i) { + const auto& r = tr.res[i]; + if (!r.uav || r.kind != 0 || res_bytes[i] > (4u << 20)) continue; + char label[32]; + std::snprintf(label, sizeof(label), "u%zu", i); + copy_range(c, label, res_address[i], res_bytes[i], "res=" + std::to_string(i), false); + } + ++st->captured; + (void)self; +} + +bool cull_capture_armed(u64 key) +{ + using namespace cull_capture; + const State* st = cc_state(); + if (!st || !trace_frame_active) return false; + for (const Want& w : st->wants) + if (w.key == key) return true; + return false; +} +int cull_capture_pick(u64 key) { return cull_capture::pick(key); } +bool cull_capture_on() { return cull_capture::cc_state() != nullptr; } + +// After ExecuteCommandLists: a fence for the blobs recorded on these lists. +void cull_capture_submitted(ID3D12CommandQueue* queue, ID3D12CommandList* const* lists, UINT count) +{ + using namespace cull_capture; + State* st = cc_state(); + if (!st) return; + std::lock_guard guard(st->lock); + ComPtr fence; + for (Blob& b : st->blobs) { + if (b.submitted || !b.live || std::find(lists, lists + count, static_cast(b.list)) == lists + count) continue; + if (!fence) { + if (FAILED(device_of(the_device)->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))) || FAILED(queue->Signal(fence.Get(), 1))) { + log("x2w-cullcap: fence failed; blobs of this submission dropped"); + fence.Reset(); + return; + } + } + b.fence = fence; + b.submitted = true; + } +} + +// A list reset before it was submitted: its blobs will never be filled. +void cull_capture_discard(ID3D12GraphicsCommandList* list) +{ + using namespace cull_capture; + State* st = cc_state(); + if (!st) return; + std::lock_guard guard(st->lock); + for (Blob& b : st->blobs) + if (b.list == list && !b.submitted) b.live = false; +} + +// At present: write the blobs whose fence passed. +void cull_capture_flush() +{ + using namespace cull_capture; + State* st = cc_state(); + if (!st) return; + std::lock_guard guard(st->lock); + std::vector keep; + for (Blob& b : st->blobs) { + if (!b.live) { + index_line(st, b.head + "\tDISCARDED\t" + b.extra + ";list reset before submission"); + continue; + } + if (!b.submitted || b.fence->GetCompletedValue() < 1) { + keep.push_back(std::move(b)); + continue; + } + void* memory = nullptr; + const D3D12_RANGE none{}; + bool ok = false; + if (SUCCEEDED(b.readback->Map(0, nullptr, &memory))) { + const auto* base = static_cast(memory); + if (b.rows) { + std::vector tight(static_cast(b.bytes)); + for (UINT y = 0; y < b.rows; ++y) + std::memcpy(tight.data() + y * b.row_bytes, base + b.offset + y * b.row_pitch, static_cast(b.row_bytes)); + ok = write_file(st->dir + wide(b.name), tight.data(), tight.size()); + } else { + ok = write_file(st->dir + wide(b.name), base, static_cast(b.bytes)); + } + b.readback->Unmap(0, &none); + } + index_line(st, b.head + "\t" + (ok ? b.name : "WRITE-FAILED") + "\t" + b.extra); + if (b.name.find("dispatch-args") != std::string::npos && ok) { + std::uint32_t xyz[3]{}; + void* m = nullptr; + if (SUCCEEDED(b.readback->Map(0, nullptr, &m))) { + std::memcpy(xyz, m, 12); + b.readback->Unmap(0, &none); + } + log("x2w-cullcap %s: dispatch args %u %u %u", b.name.c_str(), xyz[0], xyz[1], xyz[2]); + } + } + const std::size_t written = st->blobs.size() - keep.size(); + st->blobs.swap(keep); + if (written) log("x2w-cullcap: wrote %zu blobs (%zu pending) to cullcap\\index.tsv", written, st->blobs.size()); +} diff --git a/src/startup_stubs/cx_input_dump.inl b/src/startup_stubs/cx_input_dump.inl new file mode 100644 index 0000000000..a1f55c7edc --- /dev/null +++ b/src/startup_stubs/cx_input_dump.inl @@ -0,0 +1,426 @@ +// LOCAL (lt-lead probe, opt-in; nothing changes while the switches are unset). +// +// X2W_CX_TRACE_CLEARS=1: in a traced frame (X2W_D3D12_TRACE_BUSY / X2W_D3D12_TRACE_FRAME), one line per +// ClearRenderTargetView, ClearDepthStencilView and ClearUnorderedAccessView* call: +// x2w-frame clear rtv|dsv|uav-float|uav-uint view=0x target <desktop resource> <w>x<h> fmt <n> +// [title 0x<address>] values ... rects <n> [dropped: <reason>] +// The desktop resource pointer is the "desktop" field of the trace's cx-img lines, so a clear joins those lines. +// +// X2W_CX_DUMP_INPUTS=<key hex>[,<occurrence>]: the occurrence-th dispatch (default 1) of that compute key in a traced +// frame. Only one dispatch per run is dumped. For it, the runtime writes: +// - every bound buffer: the title bytes the CPU sees when the dispatch is recorded (the GPU reads the same pages in +// place when the list runs; a later title or GPU write is not seen); at most 64 KiB per buffer; +// - every bound texture (SRV and UAV): a GPU copy of mip 0 / slice 0 taken just BEFORE the dispatch ("pre"), and +// for UAV textures a second copy just AFTER it ("post"). Each copy is the whole subresource when that is at most +// X2W_CX_DUMP_FULL_MIB MiB (default 1), else the box X2W_CX_DUMP_BOX=x,y,w,h (default 64x64 at the centre, +// aligned to 4). Depth/stencil resources can only be copied whole (D3D12), one file per plane, or are skipped +// above X2W_CX_DUMP_DEPTH_MIB (default 32). +// Files go to X2W_CX_DUMP_DIR, else the folder of X2W_TRAP_LOG, else the current folder: +// cxdump_<key>_f<frame>.txt index: one line per buffer / texture copy (see the board/ready note) +// cxdump_<key>_f<frame>_buf<slot>.bin, cxdump_<key>_f<frame>_<pre|post>_<slot>[_p<plane>].bin +// Texture files hold tightly packed rows (row pitch removed). The copies are read back at a later present, after a +// marker copied at the end of the same command list has arrived plus two more presents. +namespace cx_dump { + +inline bool clears_on() +{ + static const bool on = x2w_local::env_on("X2W_CX_TRACE_CLEARS"); + return on; +} + +inline u64 title_of(u64 title_resource) +{ + if (!title_resource) return 0; + Wrapper* w = as_wrapper(reinterpret_cast<const void*>(title_resource)); + return w && w->own().kind == resource_kind ? reinterpret_cast<u64>(w->own().title_memory) : 0; +} + +// kind: "rtv", "dsv", "uav-float", "uav-uint". values: 4 floats / uints (rtv, uav) or null (dsv: depth, stencil). +inline void note_clear(const char* kind, u64 handle, ID3D12Resource* target, u64 title_resource, const void* values, bool floats, + float depth, unsigned stencil, unsigned flags, UINT rects, const char* dropped) +{ + if (!clears_on() || !trace_frame_active) return; + char text[512]; + int n = std::snprintf(text, sizeof(text), "x2w-frame clear %s view=0x%llx target %p", kind, static_cast<unsigned long long>(handle), + static_cast<void*>(target)); + if (target) { + const D3D12_RESOURCE_DESC d = target->GetDesc(); + n += std::snprintf(text + n, sizeof(text) - n, " %llux%u fmt %d", static_cast<unsigned long long>(d.Width), d.Height, static_cast<int>(d.Format)); + } + if (const u64 title = title_of(title_resource)) n += std::snprintf(text + n, sizeof(text) - n, " title 0x%llx", static_cast<unsigned long long>(title)); + if (values && x2w_local::readable(values, 16)) { + if (floats) { + const float* v = static_cast<const float*>(values); + n += std::snprintf(text + n, sizeof(text) - n, " colour %.9g %.9g %.9g %.9g", v[0], v[1], v[2], v[3]); + } else { + const UINT* v = static_cast<const UINT*>(values); + n += std::snprintf(text + n, sizeof(text) - n, " values %08x %08x %08x %08x", v[0], v[1], v[2], v[3]); + } + } else if (!std::strcmp(kind, "dsv")) { + n += std::snprintf(text + n, sizeof(text) - n, " flags 0x%x depth %.9g stencil %u", flags, depth, stencil); + } else { + n += std::snprintf(text + n, sizeof(text) - n, " values unreadable"); + } + n += std::snprintf(text + n, sizeof(text) - n, " rects %u", rects); + if (dropped) std::snprintf(text + n, sizeof(text) - n, " dropped: %s", dropped); + log("%s", text); +} + +struct Selection { + u64 key = 0; + LONG occurrence = 1; +}; +inline const Selection& selection() +{ + static const Selection s = [] { + Selection out; + char value[64]{}; + const DWORD n = GetEnvironmentVariableA("X2W_CX_DUMP_INPUTS", value, sizeof(value)); + if (!n || n >= sizeof(value)) return out; + char* end = nullptr; + out.key = std::strtoull(value, &end, 16); + if (end && *end == ',') out.occurrence = std::atol(end + 1); + if (out.occurrence < 1) out.occurrence = 1; + log("x2w-cxdump X2W_CX_DUMP_INPUTS: key %016llx occurrence %ld in a traced frame", static_cast<unsigned long long>(out.key), out.occurrence); + return out; + }(); + return s; +} +inline unsigned env_number(const char* name, unsigned fallback) +{ + char value[32]{}; + return GetEnvironmentVariableA(name, value, sizeof(value)) ? static_cast<unsigned>(std::strtoul(value, nullptr, 10)) : fallback; +} +inline std::string out_dir() +{ + char path[MAX_PATH]{}; + DWORD n = GetEnvironmentVariableA("X2W_CX_DUMP_DIR", path, MAX_PATH); + if (n && n < MAX_PATH) return std::string(path, n); + n = GetEnvironmentVariableA("X2W_TRAP_LOG", path, MAX_PATH); + if (n && n < MAX_PATH) { + std::string s(path, n); + const auto cut = s.find_last_of("\\/"); + return cut == std::string::npos ? std::string(".") : s.substr(0, cut); + } + return "."; +} + +struct Copy { + std::string name; // file name + std::string line; // index line + Microsoft::WRL::ComPtr<ID3D12Resource> readback; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT rows = 0; + UINT64 row_bytes = 0; +}; +struct Pending { + u64 key = 0; + LONG frame = 0; + std::vector<Copy> copies; + std::vector<std::pair<std::string, std::string>> buffers; // name, line (bytes written at record time) + Microsoft::WRL::ComPtr<ID3D12Resource> marker_upload, marker_readback; + std::uint32_t magic[4]{}; + int seen = -1; // presents since the marker arrived (-1: not yet) + int waited = 0; + bool active = false; +}; +inline std::mutex& lock() +{ + static std::mutex m; + return m; +} +inline Pending& pending() +{ + static Pending p; + return p; +} +inline LONG& seen_in_frame() +{ + static LONG count = 0; + return count; +} +inline LONG& counted_frame() +{ + static LONG frame = 0; + return frame; +} +inline bool& done() +{ + static bool d = false; + return d; +} + +inline Microsoft::WRL::ComPtr<ID3D12Resource> buffer(D3D12_HEAP_TYPE type, UINT64 bytes) +{ + Microsoft::WRL::ComPtr<ID3D12Resource> out; + const D3D12_HEAP_PROPERTIES heap{type}; + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = bytes ? bytes : 1; + d.Height = d.DepthOrArraySize = d.MipLevels = d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + auto* device = device_of(the_device); + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, + type == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&out)))) + out.Reset(); + else + x2w_budget::committed(device, out.Get(), type); + return out; +} + +// One selected dispatch, from the binding loop to the end of recording. Inactive (and free) for every other dispatch. +class Dispatch { +public: + Dispatch(u64 key, UINT x, UINT y, UINT z) : key_(key) + { + const Selection& s = selection(); + if (!s.key || s.key != key || !trace_frame_active) return; + std::lock_guard<std::mutex> guard(lock()); + if (done() || pending().active) return; + if (counted_frame() != frame_number) counted_frame() = frame_number, seen_in_frame() = 0; + if (++seen_in_frame() != s.occurrence) return; + active_ = true; + frame_ = frame_number + 1; // the frame being recorded (presented next) + std::snprintf(stem_, sizeof(stem_), "cxdump_%016llx_f%ld", static_cast<unsigned long long>(key), frame_); + log("x2w-cxdump %016llx dispatch (%u, %u, %u): occurrence %ld of frame %ld selected", static_cast<unsigned long long>(key), x, y, z, + s.occurrence, frame_); + } + ~Dispatch() + { + if (active_ && !finished_) { + std::lock_guard<std::mutex> guard(lock()); + seen_in_frame() -= 1; // the dispatch did not run: the next one of this key takes its place + log("x2w-cxdump %016llx: selected dispatch did not run; re-armed", static_cast<unsigned long long>(key_)); + } + } + explicit operator bool() const { return active_; } + + // From the binding loop: slot i as bound. title_resource is the view record's resource (textures), address/bytes + // the bound buffer range. + void slot(UINT i, bool uav, int kind, bool bound, u64 title_resource, u64 address, std::size_t bytes) + { + if (!active_) return; + Slot s{i, uav, kind, bound, nullptr, title_of(title_resource), address, bytes}; + if (kind && bound) { + Wrapper* w = title_resource ? as_wrapper(reinterpret_cast<const void*>(title_resource)) : nullptr; + if (w && w->own().kind == resource_kind) s.texture = static_cast<ID3D12Resource*>(w->own().real); + } + slots_.push_back(s); + } + + // Buffers (CPU bytes, now) and texture copies recorded into `list`. phase "pre": every texture; "post": UAV textures. + void copy(Wrapper* self, ID3D12GraphicsCommandList* list, const char* phase) + { + if (!active_) return; + const bool pre = !std::strcmp(phase, "pre"); + if (pre) write_buffers(); + for (const Slot& s : slots_) { + if (!s.texture || (!pre && !s.uav)) continue; + copy_texture(self, list, s, phase); + } + } + + // Marker copy, then hand the copies to poll(). Called once after the dispatch was recorded. + void finish(ID3D12GraphicsCommandList* list) + { + if (!active_) return; + finished_ = true; + std::lock_guard<std::mutex> guard(lock()); + Pending& p = pending(); + p = Pending{}; + p.key = key_; + p.frame = frame_; + p.copies = std::move(copies_); + p.buffers = std::move(buffers_); + p.marker_upload = buffer(D3D12_HEAP_TYPE_UPLOAD, 16); + p.marker_readback = buffer(D3D12_HEAP_TYPE_READBACK, 16); + p.magic[0] = 0x504d4443; // "CDMP" + p.magic[1] = static_cast<std::uint32_t>(key_); + p.magic[2] = static_cast<std::uint32_t>(frame_); + p.magic[3] = static_cast<std::uint32_t>(GetTickCount()); + void* memory = nullptr; + if (!p.marker_upload || !p.marker_readback || FAILED(p.marker_upload->Map(0, nullptr, &memory))) { + log("x2w-cxdump %016llx: marker buffers failed; nothing is read back", static_cast<unsigned long long>(key_)); + p = Pending{}; + done() = true; + return; + } + std::memcpy(memory, p.magic, 16); + p.marker_upload->Unmap(0, nullptr); + list->CopyBufferRegion(p.marker_readback.Get(), 0, p.marker_upload.Get(), 0, 16); + p.active = true; + done() = true; + log("x2w-cxdump %016llx: %zu texture copies and %zu buffers recorded; read back at a later present", static_cast<unsigned long long>(key_), + p.copies.size(), p.buffers.size()); + } + +private: + struct Slot { + UINT index; + bool uav; + int kind; + bool bound; + ID3D12Resource* texture; + u64 title; + u64 address; + std::size_t bytes; + }; + + void write_buffers() + { + const std::string dir = out_dir(); + for (const Slot& s : slots_) { + if (s.kind) continue; + char name[96], line[256]; + if (!s.address || !s.bytes) { + std::snprintf(line, sizeof(line), "buf %u %s unbound", s.index, s.uav ? "uav" : "srv"); + buffers_.emplace_back(std::string(), line); + continue; + } + const std::size_t bytes = s.bytes < (64u << 10) ? s.bytes : (64u << 10); + std::snprintf(name, sizeof(name), "%s_buf%u.bin", stem_, s.index); + const bool readable = x2w_local::readable(reinterpret_cast<const void*>(s.address), bytes); + if (readable) { + if (std::FILE* f = std::fopen((dir + "\\" + name).c_str(), "wb")) { + std::fwrite(reinterpret_cast<const void*>(s.address), 1, bytes, f); + std::fclose(f); + } + } + std::snprintf(line, sizeof(line), "buf %u %s title 0x%llx bytes %zu written %zu file %s", s.index, s.uav ? "uav" : "srv", + static_cast<unsigned long long>(s.address), s.bytes, readable ? bytes : 0, readable ? name : "-"); + buffers_.emplace_back(name, line); + } + } + + void copy_texture(Wrapper* self, ID3D12GraphicsCommandList* list, const Slot& s, const char* phase) + { + auto* device = device_of(the_device); + const D3D12_RESOURCE_DESC rd = s.texture->GetDesc(); + if (rd.SampleDesc.Count != 1) return note_skip(s, phase, "multisampled"); + const bool depth = (rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) != 0; + D3D12_FEATURE_DATA_FORMAT_INFO info{rd.Format, 1}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, &info, sizeof(info)))) info.PlaneCount = 1; + const UINT per_plane = rd.MipLevels * (rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1u : rd.DepthOrArraySize); + const UINT64 full_limit = UINT64{env_number(depth ? "X2W_CX_DUMP_DEPTH_MIB" : "X2W_CX_DUMP_FULL_MIB", depth ? 32u : 1u)} << 20; + for (UINT plane = 0; plane < (info.PlaneCount ? info.PlaneCount : 1u); ++plane) { + const UINT sub = plane * per_plane; + Copy c; + UINT64 total = 0; + device->GetCopyableFootprints(&rd, sub, 1, 0, &c.footprint, &c.rows, &c.row_bytes, &total); + D3D12_BOX box{0, 0, 0, static_cast<UINT>(rd.Width), rd.Height, c.footprint.Footprint.Depth}; + const bool whole = total <= full_limit; + if (!whole) { + if (depth) return note_skip(s, phase, "depth resource above X2W_CX_DUMP_DEPTH_MIB (D3D12 copies depth only whole)"); + unsigned bx = 0, by = 0, bw = 64, bh = 64; + char value[64]{}; + const bool given = GetEnvironmentVariableA("X2W_CX_DUMP_BOX", value, sizeof(value)) && + std::sscanf(value, "%u,%u,%u,%u", &bx, &by, &bw, &bh) == 4; + const UINT w = static_cast<UINT>(rd.Width), h = rd.Height; + if (!given) bx = w > 64 ? (w / 2 - 32) : 0, by = h > 64 ? (h / 2 - 32) : 0; + bx &= ~3u, by &= ~3u, bw = (bw + 3) & ~3u, bh = (bh + 3) & ~3u; + if (bx >= w || by >= h) return note_skip(s, phase, "box outside the texture"); + if (bx + bw > w) bw = w - bx; + if (by + bh > h) bh = h - by; + D3D12_RESOURCE_DESC part = rd; + part.Width = bw, part.Height = bh, part.MipLevels = 1, part.DepthOrArraySize = 1; + device->GetCopyableFootprints(&part, 0, 1, 0, &c.footprint, &c.rows, &c.row_bytes, &total); + box = D3D12_BOX{bx, by, 0, bx + bw, by + bh, 1}; + } + c.readback = buffer(D3D12_HEAP_TYPE_READBACK, total); + if (!c.readback) return note_skip(s, phase, "readback allocation failed"); + char name[112], line[384]; + if (info.PlaneCount > 1) std::snprintf(name, sizeof(name), "%s_%s_%u_p%u.bin", stem_, phase, s.index, plane); + else std::snprintf(name, sizeof(name), "%s_%s_%u.bin", stem_, phase, s.index); + std::snprintf(line, sizeof(line), + "tex %u %s %s desktop %p title 0x%llx %llux%ux%u mips %u fmt %d flags 0x%x plane %u box %u,%u %ux%u row_bytes %llu rows %u file %s", + s.index, s.uav ? "uav" : "srv", phase, static_cast<void*>(s.texture), static_cast<unsigned long long>(s.title), + static_cast<unsigned long long>(rd.Width), rd.Height, rd.DepthOrArraySize, rd.MipLevels, static_cast<int>(rd.Format), + static_cast<unsigned>(rd.Flags), plane, box.left, box.top, box.right - box.left, box.bottom - box.top, + static_cast<unsigned long long>(c.row_bytes), c.rows, name); + c.name = name; + c.line = line; + // The state this list holds the texture in now (set by the binding), restored after the copy. + D3D12_RESOURCE_STATES before = D3D12_RESOURCE_STATE_COMMON; + if (const auto* entry = pass_of(self).states.find(s.texture)) before = entry->depth; + require_state(self, s.texture, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION to{c.readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = c.footprint; + const D3D12_TEXTURE_COPY_LOCATION from{s.texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {sub}}; + list->CopyTextureRegion(&to, 0, 0, 0, &from, whole ? nullptr : &box); + require_state(self, s.texture, before); + copies_.push_back(std::move(c)); + } + } + + void note_skip(const Slot& s, const char* phase, const char* why) + { + char line[256]; + std::snprintf(line, sizeof(line), "tex %u %s %s desktop %p title 0x%llx skipped: %s", s.index, s.uav ? "uav" : "srv", phase, + static_cast<void*>(s.texture), static_cast<unsigned long long>(s.title), why); + buffers_.emplace_back(std::string(), line); + } + + u64 key_; + bool active_ = false, finished_ = false; + LONG frame_ = 0; + char stem_[64]{}; + std::vector<Slot> slots_; + std::vector<Copy> copies_; + std::vector<std::pair<std::string, std::string>> buffers_; +}; + +// Each present: read the copies back once the marker has arrived and two more presents have passed. +inline void poll() +{ + if (!selection().key) return; + std::lock_guard<std::mutex> guard(lock()); + Pending& p = pending(); + if (!p.active) return; + if (p.seen < 0) { + void* memory = nullptr; + const D3D12_RANGE read{0, 16}, none{}; + if (SUCCEEDED(p.marker_readback->Map(0, &read, &memory))) { + if (!std::memcmp(memory, p.magic, 16)) p.seen = 0; + p.marker_readback->Unmap(0, &none); + } + if (p.seen < 0 && ++p.waited > 600) { + log("x2w-cxdump %016llx: marker never arrived (list not executed?); dump dropped", static_cast<unsigned long long>(p.key)); + p = Pending{}; + } + return; + } + if (++p.seen < 2) return; + const std::string dir = out_dir(); + char stem[64]; + std::snprintf(stem, sizeof(stem), "cxdump_%016llx_f%ld", static_cast<unsigned long long>(p.key), p.frame); + std::FILE* index = std::fopen((dir + "\\" + stem + ".txt").c_str(), "w"); + if (index) std::fprintf(index, "x2w-cxdump 1 key %016llx frame %ld\n", static_cast<unsigned long long>(p.key), p.frame); + for (const auto& b : p.buffers) + if (index) std::fprintf(index, "%s\n", b.second.c_str()); + for (Copy& c : p.copies) { + void* memory = nullptr; + // The last row ends at row_bytes, not at a full pitch (the buffer is sized by GetCopyableFootprints). + const UINT64 lines = UINT64{c.rows} * c.footprint.Footprint.Depth; + const D3D12_RANGE read{0, static_cast<SIZE_T>(c.footprint.Offset + (lines ? (lines - 1) * c.footprint.Footprint.RowPitch : 0) + c.row_bytes)}, + none{}; + bool ok = false; + if (SUCCEEDED(c.readback->Map(0, &read, &memory))) { + if (std::FILE* f = std::fopen((dir + "\\" + c.name).c_str(), "wb")) { + const auto* base = static_cast<const unsigned char*>(memory) + c.footprint.Offset; + for (UINT zslice = 0; zslice < c.footprint.Footprint.Depth; ++zslice) + for (UINT y = 0; y < c.rows; ++y) + std::fwrite(base + (UINT64{zslice} * c.rows + y) * c.footprint.Footprint.RowPitch, 1, static_cast<std::size_t>(c.row_bytes), f); + ok = std::fclose(f) == 0; + } + c.readback->Unmap(0, &none); + } + if (index) std::fprintf(index, "%s%s\n", c.line.c_str(), ok ? "" : " (write failed)"); + } + if (index) std::fclose(index); + log("x2w-cxdump %016llx frame %ld: %zu buffers and %zu texture copies written to %s\\%s.*", static_cast<unsigned long long>(p.key), p.frame, + p.buffers.size(), p.copies.size(), dir.c_str(), stem); + p = Pending{}; +} + +} // namespace cx_dump diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 6f92733f06..998bd5b75b 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -176,6 +176,23 @@ PlacementIndex& placement_group(u64 width) return placement_index[width > D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT]; } +// LOCAL (textures): every buffer record that is not a placement (note_resource, or retire_placement turning one into +// a plain record), by title-memory range. existing_memory_buffer queries it under note_lock shared instead of walking +// resource_infos() when X2W_BUFFER_ADDRESS_INDEX=1. It is maintained whether or not the switch is on (one map +// insert per buffer creation, under the exclusive lock already held), so the switch only picks the reader. +x2w_startup::BufferAddressIndex<const Wrapper*>& buffer_address_index() +{ + static x2w_startup::BufferAddressIndex<const Wrapper*> index; + return index; +} +void index_buffer_record(const Wrapper* w, const ResourceInfo& info) // note_lock exclusive held +{ + const u64 base = reinterpret_cast<u64>(w->own().title_memory); + if (info.placement == Placement::none && info.console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && base) + buffer_address_index().insert(w, base, info.console.Width); + else + buffer_address_index().erase(w); +} // Resources by the title memory they start at (note_lock held), for the memory SRV lookups. An entry stays // as long as the resource's record in resource_infos does (never pruned); every lookup applies its own // live-reference filter, so a released resource is skipped there and found again if it is referenced again. @@ -211,6 +228,7 @@ void note_resource(Wrapper* w, const D3D12_RESOURCE_DESC* console, u64 bytes) // Record and index change together or not at all (store_indexed); mode 2 leaves the index out. x2w_startup::store_indexed(resource_address_index(), resource_infos(), static_cast<const Wrapper*>(w), resource_index_check_mode() == 2 ? 0 : reinterpret_cast<u64>(w->own().title_memory), resource_index_extent(info), info); + index_buffer_record(w, resource_infos().at(w)); // LOCAL (textures): X2W_BUFFER_ADDRESS_INDEX } void retire_placement(Wrapper* w) { @@ -227,6 +245,7 @@ void retire_placement(Wrapper* w) } } found->second.placement = Placement::none; + index_buffer_record(w, found->second); // LOCAL (textures): now a plain record, as the walk sees it } ReleaseSRWLockExclusive(¬e_lock); } @@ -282,6 +301,7 @@ void note_heap(Wrapper* w, UINT type, UINT count, UINT logical_count, UINT incre void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_t desc_bytes, u64 dest_title, u64 dest_desktop, bool materialized = true) { + if (const Wrapper* r = as_wrapper(reinterpret_cast<const void*>(resource)); r && r->own().refs <= 0) x2w_memcut::note_after_release(false); // LOCAL memcut ViewRecord record{}; record.slot = static_cast<std::uint32_t>(slot); record.resource = resource; @@ -302,7 +322,8 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ AcquireSRWLockExclusive(¬e_lock); ++views_noted; const auto found = view_ids().find(hash); - if (found != view_ids().end()) { + const bool distinct = found == view_ids().end(); + if (!distinct) { record.id = found->second; } else { record.id = static_cast<std::uint32_t>(view_records().size()); @@ -323,6 +344,12 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ retire_leave_class(reinterpret_cast<const void*>(resource), RetireLeft::view); } ReleaseSRWLockExclusive(¬e_lock); + static const bool trace_views = x2w_local::env_on("X2W_GPU_DROP_TRACE"); + if (trace_views && distinct && record.id < 256 && !resource && (slot == 18 || slot == 19) && record.desc_bytes >= 8) { + UINT fields[2]; + std::memcpy(fields, record.desc, sizeof(fields)); + log("x2w-gpu captured null view: id=%x slot=%d created=%d format=%u dimension=%u", record.id, slot, int(created), fields[0], fields[1]); + } const std::size_t token_bytes = slot == 22 ? x2w_startup::title_sampler_stride : 32u; if (dest_title != dest_desktop && title_backed(dest_title, token_bytes) && x2w_local::writable(reinterpret_cast<void*>(dest_title), token_bytes)) { diff --git a/src/startup_stubs/d3d12_cold_texture.inl b/src/startup_stubs/d3d12_cold_texture.inl new file mode 100644 index 0000000000..420423dc76 --- /dev/null +++ b/src/startup_stubs/d3d12_cold_texture.inl @@ -0,0 +1,70 @@ +// Residency hints only. The committed object and its descriptors keep their normal lifetime. +// A title that samples a persistent descriptor without a shim call can still use a low-priority texture. +enum { priority_untracked, priority_normal, priority_low }; +SRWLOCK cold_texture_lock = SRWLOCK_INIT; +unsigned long long cold_texture_count, cold_texture_bytes, warmed_texture_count, warmed_texture_bytes, cold_texture_failures; + +bool cold_textures_enabled() +{ + static const bool on = x2w_local::env_on("X2W_D3D12_COLD_TEXTURE_PRIORITY") && + !x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED") && !x2w_local::env_on("X2W_MEMCUT_RELEASE"); + return on; +} + +void update_texture_priority(Wrapper* wrapper, bool cool) +{ + AcquireSRWLockExclusive(&cold_texture_lock); + auto& w = wrapper->own(); + const LONG previous = cool ? priority_normal : priority_low; + const LONG state = ReadNoFence(&w.cold_texture_state); + if (!cool && state == priority_normal) { + // A bind at zero guest refs, or the AddRef from zero, reached this lock before the final + // Release could lower the priority. Keep the resource warm when that Release arrives. + InterlockedExchange(&w.cold_texture_state, priority_untracked); + } else if (state == previous && + (!cool || InterlockedCompareExchange(&w.refs, 0, 0) == 0)) { + auto* resource = static_cast<ID3D12Resource*>(w.real); + ID3D12Device1* device = nullptr; + HRESULT hr = resource->GetDevice(IID_PPV_ARGS(&device)); + unsigned long long bytes = 0; + if (SUCCEEDED(hr)) { + const auto desc = resource->GetDesc(); + bytes = device->GetResourceAllocationInfo(0, 1, &desc).SizeInBytes; + const auto priority = cool ? D3D12_RESIDENCY_PRIORITY_LOW : D3D12_RESIDENCY_PRIORITY_NORMAL; + ID3D12Pageable* object = resource; + hr = device->SetResidencyPriority(1, &object, &priority); + device->Release(); + } + if (SUCCEEDED(hr)) { + // Keep a texture warm permanently once we see its reuse, including a bind at zero guest refs. + InterlockedExchange(&w.cold_texture_state, cool ? priority_low : priority_untracked); + if (cool) { + ++cold_texture_count; + cold_texture_bytes += bytes; + } else { + ++warmed_texture_count; + warmed_texture_bytes += bytes; + } + } else { + ++cold_texture_failures; + if (cool) InterlockedExchange(&w.cold_texture_state, priority_untracked); + if (cold_texture_failures <= 3) log("x2w-cold texture: %s failed 0x%08lx", cool ? "lowering priority" : "restoring priority", hr); + } + } + ReleaseSRWLockExclusive(&cold_texture_lock); +} + +void warm_texture(Wrapper* wrapper, bool reacquired = false) +{ + if (!wrapper) return; + const auto& w = wrapper->own(); + const LONG state = ReadNoFence(&w.cold_texture_state); + if (state == priority_low || (state == priority_normal && (reacquired || !ReadNoFence(&w.refs)))) + update_texture_priority(wrapper, false); +} + +void cool_texture(Wrapper* wrapper) +{ + if (ReadNoFence(&wrapper->own().cold_texture_state) == priority_normal) + update_texture_priority(wrapper, true); +} diff --git a/src/startup_stubs/d3d12_compute.inl b/src/startup_stubs/d3d12_compute.inl new file mode 100644 index 0000000000..38c21c1e4f --- /dev/null +++ b/src/startup_stubs/d3d12_compute.inl @@ -0,0 +1,1662 @@ + +struct WindowSpan { D3D12_GPU_VIRTUAL_ADDRESS va; u64 size; ID3D12Resource* buffer; }; +SRWLOCK window_span_lock = SRWLOCK_INIT; +std::vector<WindowSpan>& window_spans() +{ + static std::vector<WindowSpan> spans; + return spans; +} +void note_window(ID3D12Resource* buffer) +{ + if (!buffer) return; + AcquireSRWLockExclusive(&window_span_lock); + window_spans().push_back({buffer->GetGPUVirtualAddress(), buffer->GetDesc().Width, buffer}); + ReleaseSRWLockExclusive(&window_span_lock); +} + +LONG range_split, range_unmapped, range_ok; +// LOCAL indirect: X2W_RANGE_ALIAS (d3d12_range_alias.inl): split chunk-page ranges are described and counted there. +bool range_alias_on(); +bool range_alias_split(u64 address, u64 bytes); +void range_alias_repeat(); +// The desktop window buffer and byte offset that address [address, address + bytes) of title memory, +// when the range is contiguous in one window. Cache entries last for one frame and mapping generation. +struct DesktopRangeHit { ID3D12Resource* buffer; u64 offset; bool chunk_split = false; }; +DesktopRangeHit resolve_desktop_range(u64 address, u64 bytes) +{ + DesktopRangeHit hit{nullptr, 0}; + const D3D12_GPU_VIRTUAL_ADDRESS va = desktop_va(address); + if (!va) { + InterlockedIncrement(&range_unmapped); + } else { + AcquireSRWLockShared(&window_span_lock); + for (const WindowSpan& s : window_spans()) + if (va >= s.va && va - s.va < s.size && bytes <= s.size - (va - s.va)) { + hit = {s.buffer, va - s.va}; + break; + } + ReleaseSRWLockShared(&window_span_lock); + MEMORY_BASIC_INFORMATION info{}; + u64 known_base = 0, known_end = 0; + if (hit.buffer && known_private(address, &known_base, &known_end)) { + // A private allocation opened as a heap: the range is one allocation when it ends inside it. + if (address + bytes > known_end) hit.buffer = nullptr; + if (!hit.buffer) InterlockedIncrement(&range_split); + } else if (hit.buffer && timed_query(reinterpret_cast<const void*>(address), &info) == sizeof(info)) { + if (info.Type == MEM_MAPPED) { + // Chunk pages: each 64 KiB page of the range must sit at the matching section offset. + // LOCAL: asked of xmem directly (one lookup per page) instead of desktop_va, which + // queried the page's memory and walked the windows for every page. + using Location = BOOL(WINAPI*)(const void*, HANDLE*, ULONG64*); + static const Location location = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast<Location>(GetProcAddress(xmem, "x2w_xmem_gpu_location")) : nullptr; + }(); + HANDLE first_section = nullptr; + ULONG64 first_at = 0; + if (!location || !location(reinterpret_cast<const void*>(address), &first_section, &first_at)) { + for (u64 at = (address | 0xffff) + 1; at < address + bytes; at += 0x10000) + if (desktop_va(at) != va + (at - address)) { + hit.buffer = nullptr; + break; + } + } else { + for (u64 at = (address | 0xffff) + 1; at < address + bytes; at += 0x10000) { + HANDLE section = nullptr; + ULONG64 where = 0; + if (!location(reinterpret_cast<const void*>(at), §ion, &where) || section != first_section || + where != first_at + (at - address)) { + hit.buffer = nullptr; + break; + } + } + if (!hit.buffer && range_alias_on()) { + range_alias_split(address, bytes); // never an alias today: described, counted, NULL + hit.chunk_split = true; + } + } + } else { + MEMORY_BASIC_INFORMATION last{}; + if (timed_query(reinterpret_cast<const void*>(address + bytes - 1), &last) != sizeof(last) || + last.AllocationBase != info.AllocationBase) + hit.buffer = nullptr; + } + if (!hit.buffer) InterlockedIncrement(&range_split); + } + } + return hit; +} + +u64 gpu_mapping_generation() +{ + using Read = ULONG64 (WINAPI*)(); + static std::atomic<Read> reader{}; + auto read = reader.load(std::memory_order_acquire); + if (!read) { + const HMODULE module = GetModuleHandleW(L"xmem.dll"); + if (!module) return 0; + read = reinterpret_cast<Read>(GetProcAddress(module, "x2w_xmem_gpu_mapping_generation")); + if (!read) return 0; + HMODULE pinned{}; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast<LPCWSTR>(read), &pinned)) return 0; + reader.store(read, std::memory_order_release); + } + return read(); +} + +bool desktop_range(u64 address, u64 bytes, ID3D12Resource** buffer, u64* offset) +{ + Timed timed(time_cx_desktop_range); + using Hit = DesktopRangeHit; + struct Key { + u64 address, bytes; + bool operator==(const Key& other) const { return address == other.address && bytes == other.bytes; } + }; + struct Hash { + size_t operator()(const Key& key) const { + const u64 mix = (key.address * 1099511628211ull ^ key.bytes) * 0x9e3779b97f4a7c15ull; + return static_cast<size_t>(mix ^ (mix >> 32)); + } + }; + struct Recent { Key key{}; Hit hit{}; LONG frame = -1; u64 generation{}; }; + static thread_local std::array<Recent, 256> recent{}; + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_map<Key, Hit, Hash> cache; + static LONG cache_frame = -1; + static u64 cache_generation{}; + if (!address || !bytes || bytes > UINT64_MAX - address) return false; + const Key key{address, bytes}; + for (;;) { + const LONG frame = frame_number; + const auto generation = gpu_mapping_generation(); + auto& slot = recent[Hash{}(key) % recent.size()]; + const auto reuse = [&](const Hit& hit) { + *buffer = hit.buffer; + *offset = hit.offset; + if (hit.chunk_split) range_alias_repeat(); + return hit.buffer != nullptr; + }; + if (slot.frame == frame && slot.generation == generation && slot.key == key) return reuse(slot.hit); + AcquireSRWLockShared(&lock); + if (cache_frame == frame && cache_generation == generation) { + if (const auto found = cache.find(key); found != cache.end()) { + slot = {key, found->second, frame, generation}; + ReleaseSRWLockShared(&lock); + return reuse(slot.hit); + } + } + ReleaseSRWLockShared(&lock); + auto hit = resolve_desktop_range(address, bytes); + if (gpu_mapping_generation() != generation) continue; + if (hit.buffer) InterlockedIncrement(&range_ok); + AcquireSRWLockExclusive(&lock); + if (frame == frame_number) { + if (cache_frame != frame || cache_generation != generation) { + cache.clear(); + cache_frame = frame; + cache_generation = generation; + } + cache[key] = hit; + } + ReleaseSRWLockExclusive(&lock); + slot = {key, hit, frame, generation}; + *buffer = hit.buffer; + *offset = hit.offset; + return hit.buffer != nullptr; + } +} + +struct ComputeTranslation { + struct Res { bool uav; int kind, source, a, b; bool integer = false; }; // kind 0 buffer, 1 2D, 2 2D array, 3 3D, 4 1D; source 0 table(param a, byte b), 2 root a + // integer: R32_UINT texture UAV (manifest kinds tex2du, tex3du) + struct Ud { int kind, a, b; }; // 3 root constant(param a, word b), 4 stride of res a, 5 word 3 of res a, 6 base of res a, + // 7 descriptor dword at byte b of table param a (descword) + int state = 0; // 1 ready, 2 unavailable + std::vector<Res> res; + std::vector<Ud> uds; + std::vector<std::array<std::uint32_t, 4>> samplers; + std::uint32_t compare_samplers = 0; + std::vector<UINT> heap_samplers; + UINT sampler_parameter = 0; + ID3D12RootSignature* root = nullptr; + ID3D12PipelineState* pso = nullptr; + UINT threads[3] = {}; + bool heap = false; // indexes the title's resource heap (SM 6.6 ResourceDescriptorHeap) + bool heapraw = false; // LOCAL: `heapraw 1` (needs `heap 1`): raw V#s in heap slots, table at t2 space1 (d3d12_heap_raw.inl) + bool heapwords = false; // LOCAL isa-gaps: `heapwords 1` (needs `heap 1`): heap descriptor words as numbers, vdesc at t3 space1 + bool heap_views_logged = false; // LOCAL meshrt: the "bounded heap views" line (once per key) + LONG logged = 0; + LONG entry_logged = 0; // X2W_CX_ENTRY_LOG lines written +}; +std::unordered_map<u64, ComputeTranslation>& compute_translations() { static std::unordered_map<u64, ComputeTranslation> m; return m; } +LONG cx_ready, cx_missing, cx_dispatched, cx_null_res, cx_bad_uav; +volatile LONG64 cx_compile_ms; // LOCAL stall: driver compile time of every translation loaded this run + +bool heap_raw_on(); // LOCAL: d3d12_heap_raw.inl (X2W_HEAP_RAW) +void load_compute(u64 key, ComputeTranslation& tr) +{ + tr.state = 2; + // LOCAL stall, fixtures only: X2W_CX_TEST_HOLD_EVENT (d3d12_draw.inl test_hold), so a test can issue a + // dispatch while its pipeline is deliberately not ready. + test_hold("x2w-cx", key); + wchar_t path[MAX_PATH]; + std::string manifest; + if (!cache_path(path, L"", key, L".cs.txt") || !read_text(path, manifest)) { + InterlockedIncrement(&cx_missing); + return; + } + for (std::size_t at = 0; at < manifest.size();) { + std::size_t end = manifest.find('\n', at); + if (end == std::string::npos) end = manifest.size(); + const std::string line = manifest.substr(at, end - at); + at = end + 1; + int i = 0, x = 0, y = 0, z = 0; + char kind[16] = "", source[16] = "", view[8] = ""; + unsigned w[4] = {}; + if (std::sscanf(line.c_str(), "cs %d %d %d", &x, &y, &z) == 3) { + tr.threads[0] = x, tr.threads[1] = y, tr.threads[2] = z; + } else if (line.rfind("cssampler", 0) == 0) { + char trailing; + if (std::sscanf(line.c_str(), "cssampler %d %c", &i, &trailing) != 1 || i < 0 || + i >= static_cast<int>(x2w_startup::translated_sampler_count) || + std::find(tr.heap_samplers.begin(), tr.heap_samplers.end(), static_cast<UINT>(i)) != tr.heap_samplers.end()) return; + tr.heap_samplers.push_back(static_cast<UINT>(i)); + } else if (line.rfind("heapraw 1", 0) == 0) { + tr.heapraw = true; // LOCAL: d3d12_heap_raw.inl + } else if (line.rfind("heapwords 1", 0) == 0) { + tr.heapwords = true; + } else if (line.rfind("heap 1", 0) == 0) { + tr.heap = true; + } else if (std::sscanf(line.c_str(), "udsrc %d %15s %d %d", &i, source, &x, &y) >= 2) { + ComputeTranslation::Ud ud{-1, x, y}; + if (!std::strcmp(source, "rootconst")) ud.kind = 3; + else if (!std::strcmp(source, "stride")) ud.kind = 4; + else if (!std::strcmp(source, "bufword3")) ud.kind = 5; + else if (!std::strcmp(source, "bufbase")) ud.kind = 6; + else if (!std::strcmp(source, "descword")) ud.kind = 7; + if (ud.kind < 0 || static_cast<std::size_t>(i) != tr.uds.size()) { + log("x2w-cx %016llx: entry value %d from %s not supported", key, i, source); + return; + } + tr.uds.push_back(ud); + } else if (std::sscanf(line.c_str(), "%7s %d %15s %15s %d %d", view, &i, kind, source, &x, &y) >= 5 && + (!std::strcmp(view, "srv") || !std::strcmp(view, "uav"))) { + ComputeTranslation::Res r{view[0] == 'u', !std::strcmp(kind, "tex2d") ? 1 : !std::strcmp(kind, "tex2da") ? 2 : !std::strcmp(kind, "tex3d") ? 3 : !std::strcmp(kind, "tex1d") ? 4 : 0, + !std::strcmp(source, "root") ? 2 : 0, x, y}; + if (!std::strcmp(kind, "tex2du") || !std::strcmp(kind, "tex3du")) { + r.kind = kind[3] == '2' ? 1 : 3; + r.integer = true; + if (!r.uav) { + log("x2w-cx %016llx: integer texture kind %s only as a uav", key, kind); + return; + } + } + if (static_cast<std::size_t>(i) != tr.res.size()) return; + tr.res.push_back(r); + } else if (std::sscanf(line.c_str(), "smp %d %x %x %x %x", &i, &w[0], &w[1], &w[2], &w[3]) == 5) { + tr.samplers.push_back({w[0], w[1], w[2], w[3]}); + } else if (std::sscanf(line.c_str(), "smpcmp %d", &i) == 1 && i >= 0 && i < 32) { + tr.compare_samplers |= 1u << i; + } + } + if (tr.uds.size() > 60 || tr.res.size() > 64) return; + if (tr.heapraw && !tr.heap) { // LOCAL: the table is a heap binding (d3d12_heap_raw.inl) + log("x2w-cx %016llx: `heapraw 1` without `heap 1`: translation refused", key); + return; + } + if (tr.heapwords && !tr.heap) { // LOCAL isa-gaps: the words are read through heapmem's view tokens + log("x2w-cx %016llx: `heapwords 1` without `heap 1`: translation refused", key); + return; + } + if (tr.heapwords) log("x2w-cx %016llx: heapwords 1: view descriptor words (vdesc) at t3 space1", key); // LOCAL isa-gaps + if (tr.heapraw) log("x2w-cx %016llx: heapraw 1: raw V# table at t2 space1%s", key, heap_raw_on() ? "" : " (X2W_HEAP_RAW=0: a null view)"); + ID3DBlob* code = nullptr; + if (!cache_path(path, L"", key, L".cs.cso") || FAILED(D3DReadFileToBlob(path, &code))) return; + const UINT n = static_cast<UINT>(tr.res.size()); + D3D12_ROOT_PARAMETER parameters[3]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameters[0].Constants.Num32BitValues = tr.uds.empty() ? 1u : static_cast<UINT>(tr.uds.size()); + D3D12_DESCRIPTOR_RANGE ranges[2] = {{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, n, 0, 0, 0}, {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, n, 0, 0, n}}; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[1].DescriptorTable = {2, ranges}; + std::vector<D3D12_STATIC_SAMPLER_DESC> samplers; + for (std::size_t i = 0; i < tr.samplers.size(); ++i) samplers.push_back(x2w_startup::decode_sampler(tr.samplers[i], static_cast<UINT>(i), (tr.compare_samplers >> i) & 1)); + ID3DBlob* blob = nullptr; + ID3DBlob* errors = nullptr; + HRESULT hr = E_FAIL; + if (!tr.heap) { + UINT parameters_used = n ? 2u : 1u; + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, x2w_startup::translated_sampler_count, 0, + x2w_startup::translated_sampler_space, 0}; + if (!tr.heap_samplers.empty()) { + tr.sampler_parameter = parameters_used++; + parameters[tr.sampler_parameter].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[tr.sampler_parameter].DescriptorTable = {1, &range}; + } + D3D12_ROOT_SIGNATURE_DESC desc{parameters_used, parameters, static_cast<UINT>(samplers.size()), samplers.data(), D3D12_ROOT_SIGNATURE_FLAG_NONE}; + hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, &errors); + } else { + // [0] constants, [1] t0 space1 = the title heap's memory, [2] t1 space1 = per-view info, [3] the table + D3D12_DESCRIPTOR_RANGE1 ranges1[2] = {{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, n, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, n, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, n}}; + const D3D12_DESCRIPTOR_RANGE1 bounded1[2] = { + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 1, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, tr.heapwords ? 3u : tr.heapraw ? 2u : 1u, 1, 1, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, 0}}; + D3D12_ROOT_PARAMETER1 p1[5]{}; + p1[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + p1[0].Constants.Num32BitValues = parameters[0].Constants.Num32BitValues; + p1[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + p1[1].DescriptorTable = {1, &bounded1[0]}; + p1[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + p1[2].DescriptorTable = {1, &bounded1[1]}; + p1[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + p1[3].DescriptorTable = {2, ranges1}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC vd{}; + vd.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + UINT parameters_used = n ? 4u : 3u; + D3D12_DESCRIPTOR_RANGE1 range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, x2w_startup::translated_sampler_count, 0, + x2w_startup::translated_sampler_space, D3D12_DESCRIPTOR_RANGE_FLAG_NONE, 0}; + if (!tr.heap_samplers.empty()) { + tr.sampler_parameter = parameters_used++; + p1[tr.sampler_parameter].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + p1[tr.sampler_parameter].DescriptorTable = {1, &range}; + } + vd.Desc_1_1 = {parameters_used, p1, static_cast<UINT>(samplers.size()), samplers.data(), D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED}; + hr = D3D12SerializeVersionedRootSignature(&vd, &blob, &errors); + if (FAILED(hr) && errors) log("x2w-cx %016llx root signature: %.300s", key, static_cast<const char*>(errors->GetBufferPointer())); + } + if (SUCCEEDED(hr)) hr = device_of(the_device)->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&tr.root)); + if (blob) blob->Release(); + if (errors) errors->Release(); + LARGE_INTEGER compile_start{}, compile_end{}, frequency{}; + QueryPerformanceCounter(&compile_start); + if (SUCCEEDED(hr)) { + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = tr.root; + pd.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + hr = device_of(the_device)->CreateComputePipelineState(&pd, IID_PPV_ARGS(&tr.pso)); + char slow[48] = ""; + const DWORD sn = GetEnvironmentVariableA("X2W_CX_TEST_SLOW_KEY", slow, sizeof slow); + if (sn && sn < sizeof slow && std::strtoull(slow, nullptr, 16) == key) + if (const char* colon = std::strchr(slow, ':')) Sleep(static_cast<DWORD>(std::strtoul(colon + 1, nullptr, 10))); + } + QueryPerformanceCounter(&compile_end); + QueryPerformanceFrequency(&frequency); + const SIZE_T code_bytes = code->GetBufferSize(); + code->Release(); + InterlockedAdd64(&cx_compile_ms, (compile_end.QuadPart - compile_start.QuadPart) * 1000 / frequency.QuadPart); + // LOCAL: the driver compile time and DXIL size, so a run shows which first uses are slow + log("x2w-cx %016llx translated: %zu entry values, %u resources, %zu samplers, group %ux%ux%u -> 0x%08lx (%zu bytes, compiled in %lld ms)", + key, tr.uds.size(), n, tr.samplers.size(), tr.threads[0], tr.threads[1], tr.threads[2], static_cast<unsigned long>(hr), code_bytes, + static_cast<long long>((compile_end.QuadPart - compile_start.QuadPart) * 1000 / frequency.QuadPart)); + if (FAILED(hr)) return; + tr.state = 1; + InterlockedIncrement(&cx_ready); +} + +DXGI_FORMAT typeless_to_float(DXGI_FORMAT f) +{ + switch (f) { + case DXGI_FORMAT_R8G8B8A8_TYPELESS: return DXGI_FORMAT_R8G8B8A8_UNORM; + case DXGI_FORMAT_B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_UNORM; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: return DXGI_FORMAT_R16G16B16A16_FLOAT; + case DXGI_FORMAT_R32G32B32A32_TYPELESS: return DXGI_FORMAT_R32G32B32A32_FLOAT; + case DXGI_FORMAT_R16G16_TYPELESS: return DXGI_FORMAT_R16G16_FLOAT; + case DXGI_FORMAT_R32G32_TYPELESS: return DXGI_FORMAT_R32G32_FLOAT; + case DXGI_FORMAT_R16_TYPELESS: return DXGI_FORMAT_R16_FLOAT; + case DXGI_FORMAT_R32_TYPELESS: return DXGI_FORMAT_R32_FLOAT; + case DXGI_FORMAT_R8_TYPELESS: return DXGI_FORMAT_R8_UNORM; + case DXGI_FORMAT_R8G8_TYPELESS: return DXGI_FORMAT_R8G8_UNORM; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: return DXGI_FORMAT_R10G10B10A2_UNORM; + case DXGI_FORMAT_R24G8_TYPELESS: return DXGI_FORMAT_R24_UNORM_X8_TYPELESS; + case DXGI_FORMAT_R32G8X24_TYPELESS: return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; + default: return f; + } +} +bool float_format(DXGI_FORMAT f) +{ + switch (f) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R11G11B10_FLOAT: + case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R8_UNORM: + return true; + default: + return false; + } +} + +// Writes a null view of the right shape for resource r. +void null_view(const ComputeTranslation::Res& r, D3D12_CPU_DESCRIPTOR_HANDLE dest, bool uav) +{ + InterlockedIncrement(&cx_null_res); + if (uav) { + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = r.integer ? DXGI_FORMAT_R32_UINT : r.kind ? DXGI_FORMAT_R8G8B8A8_UNORM : DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = r.kind == 1 ? D3D12_UAV_DIMENSION_TEXTURE2D : r.kind == 2 ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY + : r.kind == 3 ? D3D12_UAV_DIMENSION_TEXTURE3D : r.kind == 4 ? D3D12_UAV_DIMENSION_TEXTURE1D : D3D12_UAV_DIMENSION_BUFFER; + if (!r.kind) { + d.Buffer.NumElements = 1; + d.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + } + if (r.kind == 2) d.Texture2DArray.ArraySize = 1; + if (r.kind == 3) d.Texture3D.WSize = 1; + device_of(the_device)->CreateUnorderedAccessView(nullptr, nullptr, &d, dest); + } else { + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = r.kind ? DXGI_FORMAT_R8G8B8A8_UNORM : DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = r.kind == 1 ? D3D12_SRV_DIMENSION_TEXTURE2D : r.kind == 2 ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY + : r.kind == 3 ? D3D12_SRV_DIMENSION_TEXTURE3D : r.kind == 4 ? D3D12_SRV_DIMENSION_TEXTURE1D : D3D12_SRV_DIMENSION_BUFFER; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (!r.kind) { + d.Buffer.NumElements = 1; + d.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + } else { + d.Texture2D.MipLevels = 1; + if (r.kind == 2) d.Texture2DArray.ArraySize = 1; + } + device_of(the_device)->CreateShaderResourceView(nullptr, &d, dest); + } +} + +// LOCAL: integer texture UAVs (tex2du/tex3du) bound and refused, for the 300-frame report. +LONG cxu_bound, cxu_refused; +void note_integer_uav(bool bound, DXGI_FORMAT resource_format, UINT flags) +{ + InterlockedIncrement(bound ? &cxu_bound : &cxu_refused); + static LONG logged_bound, logged_refused; + if (bound ? first_calls(logged_bound, 1) : first_calls(logged_refused, 6)) + log("x2w-cx integer texture uav %s: resource format %u flags 0x%x%s", bound ? "bound as R32_UINT" : "REFUSED (null R32_UINT view)", + resource_format, flags, bound ? "" : " (needs ALLOW_UNORDERED_ACCESS and an R32_TYPELESS or R32_UINT resource)"); +} + +// Binds a texture behind a view record as SRV or UAV (true when a real view was written). +// prepare: also upload a plain texture and move it to the view's state (false for the bulk heap fill). +bool texture_view(Wrapper* self, const ComputeTranslation::Res& r, const ViewRecord& record, D3D12_CPU_DESCRIPTOR_HANDLE dest, + bool prepare = true, Microsoft::WRL::ComPtr<ID3D12Resource>* traced = nullptr) +{ + Timed timed(time_cx_texture); + Wrapper* resource = as_wrapper(reinterpret_cast<const void*>(record.resource)); + if (prepare) warm_texture(resource); + if (prepare && resource && resource->own().kind == resource_kind) memcut_revive(resource); // LOCAL memcut: X2W_MEMCUT_RELEASE + ID3D12Resource* texture = resource && resource->own().kind == resource_kind ? static_cast<ID3D12Resource*>(resource->own().real) : nullptr; + if (!texture || record.desc_bytes < 24) return false; + if (resource->own().refs <= 0) x2w_memcut::note_after_release(true); // LOCAL memcut + const D3D12_RESOURCE_DESC rd = texture->GetDesc(); + const int dim = rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 3 : rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D ? 4 + : rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D ? (rd.DepthOrArraySize > 1 ? 2 : 1) : 0; + if (!dim || (dim != r.kind && !(dim == 2 && r.kind == 1) && !(dim == 1 && r.kind == 2))) return false; + // The view's format and first mip / slice from the title's view description. + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + UINT mip = 0, slice = 0; + std::memcpy(&format, record.desc, 4); + format = typeless_to_float(desktop_format(format ? format : rd.Format)); + if (record.slot == 19) { + std::memcpy(&mip, record.desc + 8, 4); + if (r.kind == 2 || r.kind == 3) std::memcpy(&slice, record.desc + 12, 4); + } else if (record.slot == 18) { + std::memcpy(&mip, record.desc + 16, 4); // MostDetailedMip + } + if (mip >= rd.MipLevels) mip = 0; + if (r.uav) { + if (r.integer) format = x2w_startup::integer_uav_format(rd.Format); + if (!(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) || (r.integer ? format == DXGI_FORMAT_UNKNOWN : !float_format(format))) { + InterlockedIncrement(&cx_bad_uav); + if (r.integer) note_integer_uav(false, rd.Format, rd.Flags); + return false; + } + if (r.integer) note_integer_uav(true, rd.Format, rd.Flags); + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = format; + if (r.kind == 1) { d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; d.Texture2D.MipSlice = mip; } + else if (r.kind == 2) { d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; d.Texture2DArray = {mip, slice < rd.DepthOrArraySize ? slice : 0, rd.DepthOrArraySize - (slice < rd.DepthOrArraySize ? slice : 0), 0}; } + else if (r.kind == 3) { d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; d.Texture3D = {mip, 0, UINT(-1)}; } + else { d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; d.Texture1D.MipSlice = mip; } + if (prepare) require_state(self, texture, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + device_of(the_device)->CreateUnorderedAccessView(texture, nullptr, &d, dest); + if (traced && r.kind == 1 && !mip) *traced = texture; + return true; + } + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = format; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (r.kind == 1) { d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; d.Texture2D.MostDetailedMip = mip; d.Texture2D.MipLevels = UINT(-1); } + else if (r.kind == 2) { d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; d.Texture2DArray.MostDetailedMip = mip; d.Texture2DArray.MipLevels = UINT(-1); d.Texture2DArray.ArraySize = rd.DepthOrArraySize; } + else if (r.kind == 3) { d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; d.Texture3D.MostDetailedMip = mip; d.Texture3D.MipLevels = UINT(-1); } + else { d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; d.Texture1D.MostDetailedMip = mip; d.Texture1D.MipLevels = UINT(-1); } + if (prepare && record.slot != 19 && !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && + !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) + upload_texture(self, resource, texture); + if (prepare) require_state(self, texture, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + fix_srv(d, texture); + device_of(the_device)->CreateShaderResourceView(texture, &d, dest); + if (traced) *traced = texture; // LOCAL: X2W_CULL_INPUT_CAPTURE (red_producers().after_uav ignores a texture not in UAV state) + return true; +} + +// The view-id region of the shader-visible heap: 8 views per title view id i at +// draw_heap_size + 8 + 8 * i (0 Texture2D, 1 Texture2DArray, 2 Texture3D, 3 Texture1D, 4 raw buffer SRV, +// 5 RWTexture2D, 6 RWTexture2DArray, 7 raw buffer UAV), empty views of each kind at draw_heap_size. +// vinfo (an upload buffer, 16 bytes per id): word 0 the index stride in bytes (structured: the structure stride, +// typed: the element size, raw: 0), word 1 the GFX10_FORMAT code of a typed view (0: raw, structured or unmapped). +// Filled up to the newest record. +constexpr UINT view_ids_max = 90000; +UINT views_filled; +ID3D12Resource* vinfo_buffer; +std::uint32_t* vinfo_words; +LONG views_bound, views_null; +// LOCAL: typed buffer views (FirstElement x element size, index stride = element size). X2W_CX_TYPED_OFF=1 restores +// the old layout (element 4 bytes, stride 0, no format) for heap views, table views and bufword3. +bool typed_views_off() +{ + static const bool off = x2w_local::env_on("X2W_CX_TYPED_OFF"); + return off; +} +LONG cxv_typed_heap, cxv_typed_table, cxv_misaligned, cxv_word3; // heap: views filled; table: bindings +LONG cxd_image, cxd_buffer, cxd_title, cxd_null, cxd_unmapped; // descword values by source +LONG cxe_rootconst, cxe_descword, cxe_null_res; // entry values: unset root constant, unbound descword table, of a null resource +// LOCAL: X2W_CX_ENTRY_LOG=1 (every key) or <key>[,<key>...] (hex): the entry values of the first 4 dispatches per key. +bool cx_entry_log(u64 key) +{ + static bool all = false; + static const std::vector<u64> keys = [] { + std::vector<u64> out; + char value[2048]{}; + const DWORD n = GetEnvironmentVariableA("X2W_CX_ENTRY_LOG", value, sizeof(value)); + if (!n || n >= sizeof(value)) return out; + if (!std::strcmp(value, "1")) { + all = true; + log("x2w-cx X2W_CX_ENTRY_LOG: every key, first 4 dispatches each"); + return out; + } + for (const char* p = value; *p;) { + char* end = nullptr; + const u64 k = std::strtoull(p, &end, 16); + if (end == p) { + ++p; + continue; + } + out.push_back(k); + p = end; + } + log("x2w-cx X2W_CX_ENTRY_LOG: %zu keys, first 4 dispatches each", out.size()); + return out; + }(); + return all || (!keys.empty() && std::find(keys.begin(), keys.end(), key) != keys.end()); +} +void note_typed_view(const x2w_startup::BufferViewLayout& l, const ViewRecord& record, bool heap) +{ + if (l.kind != x2w_startup::BufferViewKind::typed) return; + InterlockedIncrement(heap ? &cxv_typed_heap : &cxv_typed_table); + static LONG logged; + if (first_calls(logged, 6)) { + std::uint32_t format = 0; + std::memcpy(&format, record.desc, 4); + log("x2w-cx typed buffer view %u (%s): format %u -> gfx10 format %u, %u-byte elements from byte %llu, %llu bytes%s", record.id, heap ? "heap" : "table", format, + l.format.code, l.index_stride, static_cast<unsigned long long>(l.offset), static_cast<unsigned long long>(l.bytes), + typed_views_off() ? " (X2W_CX_TYPED_OFF)" : ""); + } +} +// Called every 300 frames (render mode): view facts handed to translated programs since the last report. +void report_cx_views() +{ + log("x2w-cx view facts (300 frames): typed buffer views heap %ld table %ld (heap misaligned %ld), bufword3 synthesized %ld%s; " + "descword values image %ld buffer %ld title %ld null %ld (unmapped format %ld); integer texture uavs bound %ld refused %ld", + InterlockedExchange(&cxv_typed_heap, 0), InterlockedExchange(&cxv_typed_table, 0), InterlockedExchange(&cxv_misaligned, 0), + InterlockedExchange(&cxv_word3, 0), typed_views_off() ? " (X2W_CX_TYPED_OFF)" : "", InterlockedExchange(&cxd_image, 0), + InterlockedExchange(&cxd_buffer, 0), InterlockedExchange(&cxd_title, 0), InterlockedExchange(&cxd_null, 0), InterlockedExchange(&cxd_unmapped, 0), + InterlockedExchange(&cxu_bound, 0), InterlockedExchange(&cxu_refused, 0)); + log("x2w-cx entry values (300 frames): root constant not set %ld, descword table not bound %ld (these dispatches %s), " + "of a null resource %ld (run); SetComputeRootSignature same %ld changed %ld%s", + InterlockedExchange(&cxe_rootconst, 0), InterlockedExchange(&cxe_descword, 0), + x2w_local::env_on("X2W_CX_UNRESOLVED_RUN") ? "run, X2W_CX_UNRESOLVED_RUN" : "skipped", InterlockedExchange(&cxe_null_res, 0), + InterlockedExchange(&compute_root_same, 0), InterlockedExchange(&compute_root_changed, 0), + x2w_local::env_on("X2W_CX_ROOT_RESET") ? " (X2W_CX_ROOT_RESET: both clear)" : ""); +} +bool heap_raw_drain(u64 heap, u64 heap_bytes); // LOCAL: d3d12_heap_raw.inl (`heapraw 1`) +void heap_raw_bind(bool table, D3D12_CPU_DESCRIPTOR_HANDLE dest); +void vdesc_fill(const ViewRecord& record); // LOCAL meshrt: d3d12_vdesc.inl (`heapwords 1`; inert until a manifest asks) +// Opt-in evidence for the cull shader whose H0 is indexed by entry constant ud1. +u64 cull_heap_probe_key() +{ + static const u64 key = []() -> u64 { + const char* text = std::getenv("X2W_CULL_HEAP_PROBE_KEY"); + if (!text || std::strlen(text) != 16 || std::strspn(text, "0123456789abcdefABCDEF") != 16) return 0; + return std::strtoull(text, nullptr, 16); + }(); + return key; +} +bool cull_heap_probe() +{ + static const bool enabled = x2w_local::env_on("X2W_CULL_HEAP_PROBE"); + return enabled && cull_heap_probe_key() != 0; +} +// LOCAL (diagnostic): X2W_CULL_INPUT_CAPTURE (cull_input_capture.inl). +bool cull_capture_on(); +bool cull_capture_armed(u64 key); +int cull_capture_pick(u64 key); +void cull_capture_before(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, int occ, const ComputeTranslation& tr, + const u64* res_address, const std::size_t* res_bytes, const std::uint32_t* strides, const std::uint32_t* word3, + Microsoft::WRL::ComPtr<ID3D12Resource>* textures, const std::uint32_t* values, UINT value_count, + const TitleHeapView* heap_view, u64 heap_address, UINT x, UINT y, UINT z); +void cull_capture_after(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, int occ, const ComputeTranslation& tr, + const u64* res_address, const std::size_t* res_bytes); +struct RawSrvInstall { + const char* state = "untouched"; + u64 address = 0, bytes = 0, gpuva = 0, offset = 0; + ID3D12Resource* window = nullptr; // LOCAL: the window the raw views address (X2W_CULL_INPUT_CAPTURE copies from it) +}; +std::vector<RawSrvInstall> raw_srv_installs; // populated only when enabled, draw_lock held +void trace_cull_heap_entry(Wrapper* list, u64 heap, const TitleHeapView& view, UINT slot) +{ + const UINT byte_index = slot << 5; // same 32-bit arithmetic as h0 in the shader + const bool inside = u64{byte_index} + 8 <= view.bytes; + const u64 address = heap + byte_index; + UINT words[2]{}; + const bool readable = inside && x2w_local::readable(reinterpret_cast<const void*>(address), sizeof(words)); + if (readable) std::memcpy(words, reinterpret_cast<const void*>(address), sizeof(words)); + const bool token = readable && words[0] == view_token_magic; + const bool valid = token && words[1] < view_ids_max; + const auto install = valid && words[1] < raw_srv_installs.size() ? raw_srv_installs[words[1]] : RawSrvInstall{}; + log("x2w-cull-heap frame %ld list %p key %016llx H0 slot %u heap 0x%llx window %p+0x%llx entry 0x%llx " + "CPU %s %08x %08x shader kind4 index %u install %s title 0x%llx bytes %llu backing GPUVA 0x%llx+0x%llx", + frame_number, list, cull_heap_probe_key(), slot, heap, view.window, view.offset, address, + !inside ? "outside" : !readable ? "unreadable" : token ? "token" : "raw", words[0], words[1], + valid ? draw_heap_size + 8 + words[1] * 8 + 4 : draw_heap_size + 4, + valid ? install.state : readable || !inside ? "fallback-null" : "unknown", + install.address, install.bytes, install.gpuva, install.offset); +} +void fill_view_kinds(Wrapper* self, UINT base, const ViewRecord* record) +{ + if (record) vdesc_fill(*record); // LOCAL meshrt + const SIZE_T inc = draw_heap_increment; + auto at = [&](UINT k) { return D3D12_CPU_DESCRIPTOR_HANDLE{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{base + k} * inc}; }; + static const ComputeTranslation::Res kinds[8] = {{false, 1, 0, 0, 0}, {false, 2, 0, 0, 0}, {false, 3, 0, 0, 0}, {false, 4, 0, 0, 0}, + {false, 0, 0, 0, 0}, {true, 1, 0, 0, 0}, {true, 2, 0, 0, 0}, {true, 0, 0, 0, 0}}; + bool done[8] = {}; + RawSrvInstall* raw = nullptr; + if ((cull_heap_probe() || cull_capture_on()) && record && base >= draw_heap_size + 8) { + const UINT id = (base - draw_heap_size - 8) / 8; + if (raw_srv_installs.size() <= id) raw_srv_installs.resize(id + 1); + raw = &raw_srv_installs[id]; + *raw = {}; + raw->state = "NULL"; + } + if (record) { + Wrapper* resource = as_wrapper(reinterpret_cast<const void*>(record->resource)); + ID3D12Resource* real = resource && resource->own().kind == resource_kind ? static_cast<ID3D12Resource*>(resource->own().real) : nullptr; + const bool buffer_view = record->slot == 17 || (real && real->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER); + if (!buffer_view && real) { + for (UINT k : {0u, 1u, 2u, 3u, 5u, 6u}) done[k] = texture_view(self, kinds[k], *record, at(k), false); + } else if (buffer_view) { + u64 address = 0; + std::size_t bytes = 0; + std::uint32_t stride = 0, format_code = 0; + bool typed = false; + if (record->slot == 17 && record->desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(&address, record->desc, 8); + std::memcpy(&size, record->desc + 8, 4); + bytes = size; + } else if ((record->slot == 18 || record->slot == 19) && record->desc_bytes >= 24 && resource && resource->own().title_memory) { + x2w_startup::BufferViewLayout l; + if (x2w_startup::buffer_view_layout_from_desc(record->slot == 19, record->desc, record->desc_bytes, l, typed_views_off())) { + address = reinterpret_cast<u64>(resource->own().title_memory) + l.offset; + bytes = static_cast<std::size_t>(l.bytes); + stride = l.index_stride; + format_code = l.format.code; + note_typed_view(l, *record, true); + typed = l.kind == x2w_startup::BufferViewKind::typed; + } + } + if (bytes > (256u << 20)) bytes = 256u << 20; + ID3D12Resource* window = nullptr; + u64 offset = 0; + const bool in_window = address && bytes && desktop_range(address, bytes, &window, &offset); + if (raw) { + raw->address = address; + raw->bytes = bytes; + raw->state = !bytes || !address ? "NULL-empty" : !in_window ? "NULL-range" : (offset & 15) ? "NULL-alignment" : "NULL"; + if (in_window) { + raw->gpuva = window->GetGPUVirtualAddress(); + raw->offset = offset; + raw->window = window; + } + } + if (in_window && (offset & 15) && typed) InterlockedIncrement(&cxv_misaligned); // raw views must start 16-aligned + if (in_window && (offset & 15) == 0) { + D3D12_SHADER_RESOURCE_VIEW_DESC sd{}; + sd.Format = DXGI_FORMAT_R32_TYPELESS; + sd.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + sd.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + sd.Buffer.FirstElement = offset / 4; + sd.Buffer.NumElements = static_cast<UINT>((bytes + 3) / 4); + sd.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device_of(the_device)->CreateShaderResourceView(window, &sd, at(4)); + D3D12_UNORDERED_ACCESS_VIEW_DESC ud{}; + ud.Format = DXGI_FORMAT_R32_TYPELESS; + ud.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + ud.Buffer.FirstElement = offset / 4; + ud.Buffer.NumElements = sd.Buffer.NumElements; + ud.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device_of(the_device)->CreateUnorderedAccessView(window, nullptr, &ud, at(7)); + done[4] = done[7] = true; + if (raw) raw->state = "bound"; + } + if (vinfo_words && record->id < view_ids_max) { + vinfo_words[record->id * 4] = stride; + vinfo_words[record->id * 4 + 1] = format_code; + } + } + } + for (UINT k = 0; k < 8; ++k) { + if (done[k]) { + InterlockedIncrement(&views_bound); + continue; + } + null_view(kinds[k], at(k), kinds[k].uav); + InterlockedDecrement(&cx_null_res); + if (record) InterlockedIncrement(&views_null); + } +} +// draw_lock held. +void fill_views(Wrapper* self) +{ + Timed timed(time_cx_fill_views); + if (!vinfo_buffer) { + D3D12_HEAP_PROPERTIES up{D3D12_HEAP_TYPE_UPLOAD}; + D3D12_RESOURCE_DESC rd{}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rd.Width = u64{view_ids_max} * 16; + rd.Height = rd.DepthOrArraySize = rd.MipLevels = 1; + rd.SampleDesc.Count = 1; + rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (FAILED(device_of(the_device)->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&vinfo_buffer)))) + return; + vinfo_buffer->Map(0, nullptr, reinterpret_cast<void**>(&vinfo_words)); + std::memset(vinfo_words, 0, u64{view_ids_max} * 16); + fill_view_kinds(self, draw_heap_size, nullptr); // the empty views + } + AcquireSRWLockShared(¬e_lock); + const UINT count = static_cast<UINT>(view_records().size() < view_ids_max ? view_records().size() : view_ids_max); + ReleaseSRWLockShared(¬e_lock); + const UINT from = views_filled; + for (UINT i = views_filled; i < count; ++i) { + AcquireSRWLockShared(¬e_lock); + const ViewRecord record = view_records()[i]; + ReleaseSRWLockShared(¬e_lock); + fill_view_kinds(self, draw_heap_size + 8 + 8 * i, &record); + note_heap_texture(record); // LOCAL textures: X2W_HEAP_TEXTURE_UPLOAD (d3d12_draw.inl) + } + views_filled = count; + if (count != from) { + static LONG logged; + if (first_calls(logged, 12)) log("x2w-cx views %u..%u filled; bound %ld, empty %ld", from, count, views_bound, views_null); + } +} + +// The title heap behind the bound compute tables (else the newest shader-visible view heap). +bool title_view_heap(const Pass& pass, u64* address, u64* bytes) +{ + AcquireSRWLockShared(¬e_lock); + const HeapInfo* best = nullptr; + for (const HeapInfo& h : heap_infos()) { + if (h.type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || !h.title_cpu || !h.desktop_gpu) continue; + for (UINT i = 0; i < 16; ++i) + if (pass.compute_kind[i] == 5 && pass.compute_address[i] >= h.title_cpu && pass.compute_address[i] < h.title_cpu + u64{h.count} * h.increment) + best = &h; + if (!best) best = &h; + } + if (best) { + *address = best->title_cpu; + *bytes = u64{best->logical_count} * best->increment; // LOCAL meshrt: the title's heap (count may be driver-clamped) + } + ReleaseSRWLockShared(¬e_lock); + return best != nullptr; +} + +// The 8 gfx10 descriptor words the console would hold for a view the title created (gfx10_view_words.h): a CBV +// or buffer view gives the V# (raw for a CBV), a texture view the T# from the view and its resource. False: no +// words (unknown slot, unreadable desc, texture view of an unknown resource). Used by descword and vdesc +// (meshrt, `heapwords 1`); no counters here. +bool view_record_words(const ViewRecord& record, std::uint32_t out[8], bool* image, bool* unmapped) +{ + std::memset(out, 0, 32); + *image = *unmapped = false; + Wrapper* resource = as_wrapper(reinterpret_cast<const void*>(record.resource)); + ID3D12Resource* real = resource && resource->own().kind == resource_kind ? static_cast<ID3D12Resource*>(resource->own().real) : nullptr; + x2w_startup::BufferViewLayout l; + if (record.slot == 17 && record.desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(&size, record.desc + 8, 4); + l = x2w_startup::buffer_view_layout(DXGI_FORMAT_R32_TYPELESS, 0, size / 4, 0, 1); // a CBV reads as a raw buffer + } else if ((record.slot == 18 || record.slot == 19) && + x2w_startup::buffer_view_layout_from_desc(record.slot == 19, record.desc, record.desc_bytes, l, typed_views_off())) { + } else if (real && (record.slot == 18 || record.slot == 19)) { + x2w_startup::ImageViewFacts v; + if (!x2w_startup::image_view_from_desc(record.slot == 19, record.desc, record.desc_bytes, v)) return false; + const D3D12_RESOURCE_DESC rd = real->GetDesc(); + v.dimension = rd.Dimension; + v.width = rd.Width; + v.height = rd.Height; + v.depth_or_array = rd.DepthOrArraySize; + v.mip_levels = rd.MipLevels; + v.format = typeless_to_float(desktop_format(v.format ? v.format : rd.Format)); + return *image = x2w_startup::gfx10_image_words(v, out, unmapped); + } else { + return false; + } + x2w_startup::gfx10_buffer_words(l, out); + return true; +} + +// LOCAL: `udsrc <i> descword <param> <byte offset>`: the dword at <byte offset> of the descriptor table bound at root +// parameter <param>, as the console would hold it. Entries are 32 bytes: entry = offset & ~31, word = (offset & 31) / 4. +// A view token becomes the synthesized gfx10 T# (texture view) or V# (buffer view, CBV) word (gfx10_view_words.h); +// any other readable entry gives the title's own dword; null, unreadable or unknown views give 0. +// resolved: false when the table is not bound or its entry is not readable (the value 0 is then not the title's). +std::uint32_t descword_value(const Pass& pass, int param, int offset, u64 key, bool* resolved = nullptr) +{ + if (resolved) *resolved = false; + if (param < 0 || param >= 16 || offset < 0 || pass.compute_kind[param] != 5 || !pass.compute_address[param]) { + static LONG logged; + if (first_calls(logged, 4)) + log("x2w-cx %016llx descword %d %d: root parameter is not a bound descriptor table (kind %d): value 0", key, param, offset, + param >= 0 && param < 16 ? pass.compute_kind[param] : -1); + InterlockedIncrement(&cxd_null); + return 0; + } + const u64 entry = pass.compute_address[param] + (static_cast<u64>(offset) & ~31ull); + const int word = (offset & 31) / 4; + std::uint32_t words[8] = {}; + if (!x2w_local::readable(reinterpret_cast<const void*>(entry), 32)) { + InterlockedIncrement(&cxd_null); + return 0; + } + std::memcpy(words, reinterpret_cast<const void*>(entry), 32); + if (resolved) *resolved = true; + if (words[0] != view_token_magic) { + InterlockedIncrement(words[word] ? &cxd_title : &cxd_null); + return words[word]; + } + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + std::uint32_t out[8] = {}; + bool image = false, unmapped = false; + const bool made = known && view_record_words(record, out, &image, &unmapped); + if (made && unmapped) { + InterlockedIncrement(&cxd_unmapped); + static LONG logged; + if (first_calls(logged, 8)) log("x2w-cx descword: view %u has no gfx10 format here: FORMAT 0 (word 1 may then read as a null view)", record.id); + } + if (!made) { + InterlockedIncrement(&cxd_null); + return 0; + } + InterlockedIncrement(image ? &cxd_image : &cxd_buffer); + static LONG logged_image, logged_buffer; + if (first_calls(image ? logged_image : logged_buffer, 1)) + log("%s", image ? "x2w-cx descword: image views give T# FORMAT, WIDTH, HEIGHT, DST_SEL, BASE_LEVEL, LAST_LEVEL, TYPE, DEPTH, BASE_ARRAY, " + "ARRAY_PITCH, MAX_MIP; left 0: base address, MIN_LOD, RESOURCE_LEVEL, SW_MODE, BC_SWIZZLE, PERF_MOD, words 6-7" + : "x2w-cx descword: buffer views give V# STRIDE, NUM_RECORDS, DST_SEL, FORMAT, OOB_SELECT; left 0: base address, " + "SWIZZLE_ENABLE, CACHE_SWIZZLE, INDEX_STRIDE, ADD_TID_ENABLE, RESOURCE_LEVEL, words 4-7"); + static LONG logged_value; + if (first_calls(logged_value, 8)) + log("x2w-cx %016llx descword %d %d: view %u slot %u %s word %d = %08x", key, param, offset, record.id, record.slot, image ? "T#" : "V#", word, out[word]); + return out[word]; +} + +SRWLOCK compute_load_lock = SRWLOCK_INIT; +CONDITION_VARIABLE compute_loaded = CONDITION_VARIABLE_INIT; +ComputeTranslation& loaded_compute(u64 key) +{ + AcquireSRWLockExclusive(&compute_load_lock); + ComputeTranslation& tr = compute_translations()[key]; // element references survive rehashing + while (tr.state == 3) SleepConditionVariableSRW(&compute_loaded, &compute_load_lock, INFINITE, 0); + if (tr.state != 0) { + ReleaseSRWLockExclusive(&compute_load_lock); + return tr; + } + tr.state = 3; + ReleaseSRWLockExclusive(&compute_load_lock); + ComputeTranslation loaded; + load_compute(key, loaded); + AcquireSRWLockExclusive(&compute_load_lock); + tr = loaded; // final state (1 ready, 2 unavailable) and the objects; nobody reads tr while it is 3 + ReleaseSRWLockExclusive(&compute_load_lock); + WakeAllConditionVariable(&compute_loaded); + return tr; +} + +// LOCAL stall: the translation of a slot 67 pipeline is loaded (and its desktop pipeline compiled by the +// driver) when the title creates the pipeline, on two below-normal background threads, so the first +// dispatch usually finds it ready instead of compiling on a recording thread inside the frame. A +// dispatch of a key still queued compiles it itself; one of a key being compiled waits for that key +// only (loaded_compute). X2W_CX_PREWARM_OFF=1 (or X2W_CX_COMPILE_LOCKED=1) turns this off; +// X2W_CX_PREWARM_THREADS=<1..4> sets the thread count. +SRWLOCK prewarm_lock = SRWLOCK_INIT; +CONDITION_VARIABLE prewarm_wanted = CONDITION_VARIABLE_INIT; +std::deque<u64>& prewarm_queue() +{ + static std::deque<u64> q; + return q; +} +std::unordered_set<u64>& prewarm_keys() // every key ever queued (prewarm_lock): each is queued once +{ + static std::unordered_set<u64> s; + return s; +} +LONG cx_prewarm_queued, cx_prewarm_done; +std::deque<u64>& demand_queue() // prewarm_lock +{ + static std::deque<u64> q; + return q; +} +struct PrewarmLoad { // one per worker that is loading (prewarm_lock) + u64 key = 0; + ULONGLONG start = 0; // GetTickCount64 + int lane = 0; // 0 background (demanded keys first), 1 demanded keys only + bool logged = false; // the "load running" line written + bool slow = false; // marked slow; a replacement worker of its lane was started (when `replaced`) + bool replaced = false; +}; +std::vector<PrewarmLoad*>& prewarm_loads() // prewarm_lock +{ + static std::vector<PrewarmLoad*> v; + return v; +} +LONG prewarm_live[2], prewarm_target[2]; // workers per lane, running and wanted (prewarm_lock) +LONG cx_slow_extra, cx_slow_keys; // replacement workers running for slow loads; keys marked slow this run +constexpr LONG cx_slow_extra_max = 4; +DWORD cx_env_ms(const char* name, DWORD fallback) +{ + char value[16]{}; + const DWORD n = GetEnvironmentVariableA(name, value, sizeof(value)); + return n && n < sizeof(value) && value[0] ? static_cast<DWORD>(std::strtoul(value, nullptr, 10)) : fallback; +} +DWORD WINAPI prewarm_thread(void* lane); +void prewarm_spawn(int lane) // prewarm_lock held: one more worker of `lane` +{ + ++prewarm_live[lane]; + if (const HANDLE t = CreateThread(nullptr, 0, prewarm_thread, reinterpret_cast<void*>(static_cast<std::intptr_t>(lane)), 0, nullptr)) + CloseHandle(t); + else + --prewarm_live[lane]; +} +struct CxAsync { + LONG skipped = 0; // since the run started + LONG since_report = 0; // since the last report_cx_async + ULONGLONG first_skip = 0; // GetTickCount64 of the first skip +}; +std::unordered_map<u64, CxAsync>& cx_async_keys() +{ + static std::unordered_map<u64, CxAsync> m; + return m; +} +bool cx_async() +{ + static const bool on = x2w_local::env_on("X2W_CX_ASYNC") && !x2w_local::env_on("X2W_CX_COMPILE_LOCKED"); + return on; +} +// LOCAL stall: X2W_CX_PREWARM_ALL=1 (prewarm_known_start, below) queues the known keys when the device is made. +// known_keys is filled before any of them is queued and not changed after, so the workers read it unlocked. +std::unordered_set<u64>& known_keys() +{ + static std::unordered_set<u64> s; + return s; +} +LONG cx_known_done; +ULONGLONG cx_known_started; +// The prewarm workers (lane 0: demanded keys first, then the background queue; lane 1: demanded keys only). A key +// with skipped dispatches logs when it is ready. +DWORD WINAPI prewarm_thread(void* lane_arg) +{ + const int lane = static_cast<int>(reinterpret_cast<std::intptr_t>(lane_arg)); + // A demanded key holds back a dispatch now: the lane-1 worker runs at normal priority. + SetThreadPriority(GetCurrentThread(), lane ? THREAD_PRIORITY_NORMAL : THREAD_PRIORITY_BELOW_NORMAL); + for (;;) { + AcquireSRWLockExclusive(&prewarm_lock); + for (;;) { + if (prewarm_live[lane] > prewarm_target[lane]) { // a slow load of this lane ended: one worker too many + --prewarm_live[lane]; + ReleaseSRWLockExclusive(&prewarm_lock); + return 0; + } + if (!demand_queue().empty() || (lane == 0 && !prewarm_queue().empty())) break; + SleepConditionVariableSRW(&prewarm_wanted, &prewarm_lock, INFINITE, 0); + } + std::deque<u64>& from = !demand_queue().empty() ? demand_queue() : prewarm_queue(); + const bool demanded = &from == &demand_queue(); + const u64 key = from.front(); + from.pop_front(); + PrewarmLoad load; + load.key = key; + load.start = GetTickCount64(); + load.lane = lane; + prewarm_loads().push_back(&load); + ReleaseSRWLockExclusive(&prewarm_lock); + const int state = loaded_compute(key).state; + AcquireSRWLockExclusive(&prewarm_lock); + prewarm_loads().erase(std::find(prewarm_loads().begin(), prewarm_loads().end(), &load)); + if (load.replaced) { // its replacement keeps running: this lane now has one worker too many + --prewarm_target[lane]; + --cx_slow_extra; + } + ReleaseSRWLockExclusive(&prewarm_lock); + if (load.slow) + log("x2w-cx %016llx: slow load ended after %llu ms (%s, lane %d%s)", key, static_cast<unsigned long long>(GetTickCount64() - load.start), + state == 1 ? "ready" : "unavailable", lane, demanded ? ", demanded" : ""); + const LONG n = InterlockedIncrement(&cx_prewarm_done); + if (n <= 4 || n % 200 == 0) log("x2w-cx prewarm %ld of %ld queued pipelines loaded (latest %016llx)", n, cx_prewarm_queued, key); + if (known_keys().count(key)) { + const LONG done = InterlockedIncrement(&cx_known_done); + if (done == static_cast<LONG>(known_keys().size())) + log("x2w-cx prewarm: all %ld known pipelines loaded %.1f s after the device was made (X2W_CX_PREWARM_ALL); " + "driver compile time of all translations so far %.1f s", done, (GetTickCount64() - cx_known_started) / 1000.0, + static_cast<double>(cx_compile_ms) / 1000.0); + } + if (cx_async()) { + AcquireSRWLockExclusive(&compute_load_lock); + const auto found = cx_async_keys().find(key); + const CxAsync seen = found != cx_async_keys().end() ? found->second : CxAsync{}; + ReleaseSRWLockExclusive(&compute_load_lock); + if (seen.skipped) + log("x2w-cx %016llx %s (X2W_CX_ASYNC) %llu ms after its first skipped dispatch; %ld dispatches skipped while compiling", + key, state == 1 ? "ready" : "unavailable", static_cast<unsigned long long>(GetTickCount64() - seen.first_skip), seen.skipped); + } + } +} +// The watch of running loads (see demand_queue): every 250 ms. +DWORD WINAPI prewarm_watch(void*) +{ + const DWORD log_ms = cx_env_ms("X2W_CX_SLOW_LOG_MS", 10000), slow_ms = cx_env_ms("X2W_CX_SLOW_MS", 60000); + log("x2w-cx prewarm watch: a load running %lu ms is logged, one running %lu ms marks its key slow and starts a replacement worker " + "(at most %ld at once)", log_ms, slow_ms, cx_slow_extra_max); + for (;;) { + Sleep(250); + struct Note { u64 key; ULONGLONG ms; int lane; bool slow, replaced; LONG waiting; }; + std::vector<Note> notes; + AcquireSRWLockExclusive(&prewarm_lock); + const ULONGLONG now = GetTickCount64(); + const LONG waiting = static_cast<LONG>(prewarm_queue().size() + demand_queue().size()); + for (PrewarmLoad* load : prewarm_loads()) { + const ULONGLONG ms = now - load->start; + if (ms >= log_ms && !load->logged) { + load->logged = true; + notes.push_back({load->key, ms, load->lane, false, false, waiting}); + } + if (ms >= slow_ms && !load->slow) { + load->slow = true; + ++cx_slow_keys; + if (cx_slow_extra < cx_slow_extra_max) { + load->replaced = true; + ++cx_slow_extra; + ++prewarm_target[load->lane]; + prewarm_spawn(load->lane); + } + notes.push_back({load->key, ms, load->lane, true, load->replaced, waiting}); + } + } + ReleaseSRWLockExclusive(&prewarm_lock); + for (const Note& n : notes) + if (!n.slow) + log("x2w-cx %016llx: load running for %llu ms (driver compile; lane %d; %ld keys waiting)", n.key, n.ms, n.lane, n.waiting); + else + log("x2w-cx %016llx: marked slow after %llu ms (lane %d): %s; %ld keys waiting", n.key, n.ms, n.lane, + n.replaced ? "a replacement worker started" : "no replacement (cap reached)", n.waiting); + } +} +bool prewarm_enabled() +{ + static const bool off = x2w_local::env_on("X2W_CX_PREWARM_OFF") || x2w_local::env_on("X2W_CX_COMPILE_LOCKED") || + x2w_local::env_on("X2W_CX_OFF") || x2w_local::env_on("X2W_COMPUTE_OFF"); + return !off; +} +// Queues `key` for the workers once. `front`: a dispatch needs it now (X2W_CX_ASYNC); a key still waiting in the +// queue moves to the front. With X2W_CX_ASYNC the workers run even under X2W_CX_PREWARM_OFF (then only demanded +// keys are queued). False: the key cannot be queued (prewarm off, or not a loadable slot-67 key). +bool prewarm_compute(u64 key, bool front) +{ + if ((!prewarm_enabled() && !(front && cx_async())) || (key >> 56) != 0x67 || !(key & 0x00ffffffffffffffull)) return false; + static const int threads = [] { + char value[4]{}; + const DWORD n = GetEnvironmentVariableA("X2W_CX_PREWARM_THREADS", value, sizeof(value)); + int count = n && n < sizeof(value) ? std::atoi(value) : x2w_local::env_on("X2W_CX_PREWARM_ALL") ? 3 : 2; + count = count < 1 ? 1 : count > 4 ? 4 : count; + const bool lane = cx_async() && !(GetEnvironmentVariableA("X2W_CX_DEMAND_LANE", value, sizeof(value)) && value[0] == '0'); + AcquireSRWLockExclusive(&prewarm_lock); + prewarm_target[0] = count; + prewarm_target[1] = lane ? 1 : 0; + for (int i = 0; i < count; ++i) prewarm_spawn(0); + if (lane) prewarm_spawn(1); + ReleaseSRWLockExclusive(&prewarm_lock); + if (const HANDLE t = CreateThread(nullptr, 0, prewarm_watch, nullptr, 0, nullptr)) CloseHandle(t); + log("x2w-cx prewarm: %d background threads%s%s", count, + cx_async() ? "; X2W_CX_ASYNC=1: a dispatch of a pipeline not loaded yet is skipped, never compiled or waited for on its thread" : "", + lane ? "; plus 1 demand-lane thread (demanded keys only)" : cx_async() ? "; no demand-lane thread (X2W_CX_DEMAND_LANE=0)" : ""); + return count; + }(); + (void)threads; + AcquireSRWLockExclusive(&prewarm_lock); + const bool fresh = prewarm_keys().insert(key).second; + bool wake = fresh; + if (fresh) { + ++cx_prewarm_queued; + if (front) demand_queue().push_back(key); + else prewarm_queue().push_back(key); + } else if (front) { + std::deque<u64>& q = prewarm_queue(); + for (auto it = q.begin(); it != q.end(); ++it) + if (*it == key) { + q.erase(it); + demand_queue().push_back(key); + wake = true; + break; + } // not in the queue: demanded already, or a worker is loading it or has loaded it + } + ReleaseSRWLockExclusive(&prewarm_lock); + // All: a lane-1 worker woken for a background key would sleep again and leave the key to nobody. + if (wake) WakeAllConditionVariable(&prewarm_wanted); + return true; +} +// X2W_CX_ASYNC: the translation of `key` if its load has finished (state 1 ready or 2 unavailable), else nullptr +// after counting the skip and queueing the key at the front. A key the workers cannot take is loaded here as before. +ComputeTranslation* ready_compute(u64 key) +{ + AcquireSRWLockExclusive(&compute_load_lock); + ComputeTranslation& tr = compute_translations()[key]; + if (tr.state == 1 || tr.state == 2) { + ReleaseSRWLockExclusive(&compute_load_lock); + return &tr; + } + CxAsync& a = cx_async_keys()[key]; + const bool first = !a.skipped; + if (first) a.first_skip = GetTickCount64(); + ++a.skipped; + ++a.since_report; + ReleaseSRWLockExclusive(&compute_load_lock); + if (!prewarm_compute(key, true)) { + AcquireSRWLockExclusive(&compute_load_lock); + --a.skipped, --a.since_report; // element references survive rehashing + ReleaseSRWLockExclusive(&compute_load_lock); + return &loaded_compute(key); + } + static LONG logged; + if (first && first_calls(logged, 32)) + log("x2w-cx %016llx: pipeline not loaded yet, dispatch skipped and the key queued first for the prewarm workers (X2W_CX_ASYNC)", key); + return nullptr; +} +// Heartbeat (every 5 s): the dispatches skipped while compiling since the last report, per key. +void report_cx_async() +{ + if (!cx_async()) return; + std::vector<std::pair<u64, LONG>> keys; + LONG total = 0, all_time = 0; + AcquireSRWLockExclusive(&compute_load_lock); + for (auto& entry : cx_async_keys()) { + all_time += entry.second.skipped; + if (!entry.second.since_report) continue; + keys.push_back({entry.first, entry.second.since_report}); + total += entry.second.since_report; + entry.second.since_report = 0; + } + ReleaseSRWLockExclusive(&compute_load_lock); + AcquireSRWLockShared(&prewarm_lock); + const std::size_t waiting = prewarm_queue().size(), demanded = demand_queue().size(), loading = prewarm_loads().size(); + const LONG slow = cx_slow_keys; + ReleaseSRWLockShared(&prewarm_lock); + if (!total) return; + std::sort(keys.begin(), keys.end(), [](const auto& a, const auto& b) { return a.second > b.second; }); + char line[1400]; + int n = std::snprintf(line, sizeof(line), "x2w-cx dispatches skipped while compiling since the last report (X2W_CX_ASYNC): %ld over %zu keys " + "(%ld this run; %zu keys waiting in the prewarm queue; %zu demanded waiting, %zu loading, %ld slow this run):", + total, keys.size(), all_time, waiting, demanded, loading, slow); + for (const auto& k : keys) { + if (n > static_cast<int>(sizeof(line)) - 40) { + n += std::snprintf(line + n, sizeof(line) - n, " ..."); + break; + } + n += std::snprintf(line + n, sizeof(line) - n, " %016llx=%ld", k.first, k.second); + } + log("%s", line); +} + +// LOCAL stall: X2W_CX_PREWARM_ALL=1. When the device is made, every slot-67 key that has a translation in the +// cache (<key>.cs.cso) and is in the keys-seen file goes to the prewarm workers (3 by default), smallest .cso +// first; without a keys-seen file, every cached translation does. The keys-seen file (X2W_CX_KEYS_SEEN, default +// <X2W_SHADER_CACHE>\cx_keys_seen.lst: one key per line; not .txt, so the manifest watcher ignores it) holds the +// keys of earlier runs plus every key dispatched in this one; it is rewritten every 10 s when it changed (a +// temporary file and a rename), since a run usually ends without a clean exit. +bool prewarm_all() +{ + static const bool on = x2w_local::env_on("X2W_CX_PREWARM_ALL") && prewarm_enabled(); + return on; +} +SRWLOCK keys_seen_lock = SRWLOCK_INIT; +std::unordered_set<u64>& keys_seen() // keys_seen_lock: the file's keys and the keys dispatched this run +{ + static std::unordered_set<u64> s; + return s; +} +LONG keys_seen_changed; +bool keys_seen_path(wchar_t* out) +{ + DWORD n = GetEnvironmentVariableW(L"X2W_CX_KEYS_SEEN", out, MAX_PATH); + if (n && n < MAX_PATH) return true; + wchar_t dir[MAX_PATH]; + n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); + if (!n || n >= MAX_PATH) return false; + swprintf(out, MAX_PATH, L"%s\\cx_keys_seen.lst", dir); + return true; +} +// execute_translated: the key was dispatched (every dispatch; a shared lookup once the key is known). +void note_key_seen(u64 key) +{ + if (!prewarm_all()) return; + AcquireSRWLockShared(&keys_seen_lock); + const bool known = keys_seen().count(key) != 0; + ReleaseSRWLockShared(&keys_seen_lock); + if (known) return; + AcquireSRWLockExclusive(&keys_seen_lock); + if (keys_seen().insert(key).second) InterlockedIncrement(&keys_seen_changed); + ReleaseSRWLockExclusive(&keys_seen_lock); +} +DWORD WINAPI keys_seen_writer(void*) +{ + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + wchar_t path[MAX_PATH], temp[MAX_PATH]; + if (!keys_seen_path(path)) return 0; + swprintf(temp, MAX_PATH, L"%s.%lu.tmp", path, GetCurrentProcessId()); + for (;;) { + Sleep(10000); + if (!InterlockedExchange(&keys_seen_changed, 0)) continue; + std::string text; + AcquireSRWLockShared(&keys_seen_lock); + std::vector<u64> keys(keys_seen().begin(), keys_seen().end()); + ReleaseSRWLockShared(&keys_seen_lock); + std::sort(keys.begin(), keys.end()); + for (const u64 key : keys) { + char line[24]; + std::snprintf(line, sizeof(line), "%016llx\n", key); + text += line; + } + const HANDLE file = CreateFileW(temp, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) continue; + DWORD written = 0; + const bool ok = WriteFile(file, text.data(), static_cast<DWORD>(text.size()), &written, nullptr) && written == text.size(); + CloseHandle(file); + const bool moved = ok && MoveFileExW(temp, path, MOVEFILE_REPLACE_EXISTING); + if (!moved) DeleteFileW(temp); + static LONG logged; + if (first_calls(logged, 4) || !moved) log("x2w-cx keys seen: %zu keys written to %ls%s", keys.size(), path, moved ? "" : " FAILED"); + } +} +// attach_device, after the_device is set. +void prewarm_known_start() +{ + if (!prewarm_all()) return; + cx_known_started = GetTickCount64(); + wchar_t path[MAX_PATH], dir[MAX_PATH]; + const DWORD dn = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); + if (!dn || dn >= MAX_PATH) return; + std::string text; + const bool have_file = keys_seen_path(path) && read_text(path, text); + std::size_t file_keys = 0; + AcquireSRWLockExclusive(&keys_seen_lock); + for (std::size_t at = 0; have_file && at < text.size();) { + std::size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + const u64 key = std::strtoull(text.substr(at, end - at).c_str(), nullptr, 16); + if ((key >> 56) == 0x67 && keys_seen().insert(key).second) ++file_keys; + at = end + 1; + } + ReleaseSRWLockExclusive(&keys_seen_lock); + // The cached translations, smallest first. + std::vector<std::pair<u64, u64>> cached; // (size, key) + wchar_t pattern[MAX_PATH]; + swprintf(pattern, MAX_PATH, L"%s\\67*.cs.cso", dir); + WIN32_FIND_DATAW found{}; + const HANDLE find = FindFirstFileW(pattern, &found); + if (find != INVALID_HANDLE_VALUE) { + do { + wchar_t* tail = nullptr; + const u64 key = std::wcstoull(found.cFileName, &tail, 16); + if (!tail || tail - found.cFileName != 16 || _wcsicmp(tail, L".cs.cso") != 0) continue; + if (have_file && !keys_seen().count(key)) continue; // keys_seen is not written by another thread yet + cached.push_back({(static_cast<u64>(found.nFileSizeHigh) << 32) | found.nFileSizeLow, key}); + } while (FindNextFileW(find, &found)); + FindClose(find); + } + std::sort(cached.begin(), cached.end()); + for (const auto& c : cached) known_keys().insert(c.second); + if (have_file) + log("x2w-cx prewarm: %zu known pipelines queued (X2W_CX_PREWARM_ALL; keys seen file %ls: %zu keys, %zu with a translation), smallest first", + cached.size(), path, file_keys, cached.size()); + else + log("x2w-cx prewarm: %zu known pipelines queued (X2W_CX_PREWARM_ALL; no keys seen file: every cached translation), smallest first", + cached.size()); + for (const auto& c : cached) prewarm_compute(c.second); + if (const HANDLE t = CreateThread(nullptr, 0, keys_seen_writer, nullptr, 0, nullptr)) CloseHandle(t); +} +// Heartbeat, and the first translated dispatch: how many of the known pipelines are loaded. +void report_prewarm_known(const char* when) +{ + static LONG complete_logged; + if (!prewarm_all() || known_keys().empty() || complete_logged) return; + const LONG done = cx_known_done; + if (done == static_cast<LONG>(known_keys().size())) InterlockedExchange(&complete_logged, 1); + log("x2w-cx prewarm: %ld of %zu pipelines ready %s, %.1f s after the device was made; driver compile time so far %.1f s", + done, known_keys().size(), when, (GetTickCount64() - cx_known_started) / 1000.0, static_cast<double>(cx_compile_ms) / 1000.0); +} + +// Runs a dispatch through the translation of compute key `key`. False: not translated (or no list). +bool execute_translated(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, UINT x, UINT y, UINT z) +{ + static const bool enabled = !x2w_local::env_on("X2W_CX_OFF"); + if (!enabled || !list || (key >> 56) != 0x67) { + dispatch_outcome = !enabled ? co_c67_off : list ? co_c67_other_key : co_not_run; + return false; + } + Timed timed(time_cx_execute); + Pass& pass = pass_of(self); + // LOCAL: X2W_CX_COMPILE_LOCKED=1 restores the old order (compile while holding draw_lock), for comparison. + static const bool compile_locked = x2w_local::env_on("X2W_CX_COMPILE_LOCKED"); + note_key_seen(key); // LOCAL stall: X2W_CX_PREWARM_ALL keys-seen file + static LONG first_dispatch; + if (!first_dispatch && !InterlockedExchange(&first_dispatch, 1)) report_prewarm_known("at the first translated dispatch"); + // LOCAL stall: X2W_CX_ASYNC=1 skips a dispatch whose pipeline is not loaded yet (ready_compute). + ComputeTranslation* ready = compile_locked ? nullptr : cx_async() ? ready_compute(key) : &loaded_compute(key); + if (!compile_locked && !ready) { + dispatch_outcome = co_c67_compiling; + return false; + } + lock_draw(200000 + __LINE__); + if (!ready) { + ready = &compute_translations()[key]; + if (!ready->state) load_compute(key, *ready); + } + ComputeTranslation& tr = *ready; + if (tr.state != 1 || !ensure_draw_heap(the_device)) { + dispatch_outcome = tr.state != 1 ? co_c67_untranslated : co_c67_heap; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + TitleHeapView heap_view; // LOCAL meshrt: the bounded heapmem view (d3d12_draw.inl bounded_title_heap) + u64 heap_address = 0; + bool heap_raw_table = false; // LOCAL `heapraw 1`: the raw V# table is bound (d3d12_heap_raw.inl) + if (tr.heap) { + u64 heap_bytes = 0; + static LONG logged_heap; + const char* why = draw_heap_increment != 32 ? "increment not 32" + : !title_view_heap(pass, &heap_address, &heap_bytes) ? "title view heap not reachable" + : bounded_title_heap(heap_address, heap_bytes, heap_view); + if (why) { + if (first_calls(logged_heap, 4)) log("x2w-cx %016llx: heap dispatch skipped: %s (increment %u)", key, why, draw_heap_increment); + dispatch_outcome = co_c67_heap; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + fill_views(self); + upload_heap_textures(self); // LOCAL textures: X2W_HEAP_TEXTURE_UPLOAD (d3d12_draw.inl) + if (tr.heapraw) heap_raw_table = heap_raw_drain(heap_address, heap_view.bytes); // LOCAL: d3d12_heap_raw.inl + if (tr.heapwords && !ensure_vdesc()) { // LOCAL isa-gaps: no descriptor-word buffer, the dispatch is skipped + static LONG logged_vdesc; + if (first_calls(logged_vdesc, 8)) log("x2w-cx %016llx: heapwords: no view descriptor (vdesc) buffer, dispatch skipped", key); + dispatch_outcome = co_c67_heap; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + if (!vinfo_buffer) { + dispatch_outcome = co_c67_heap; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + } + const UINT n = static_cast<UINT>(tr.res.size()); + // LOCAL meshrt: heapmem / vinfo (/ raw table) views after the res table; LOCAL isa-gaps: (/ raw table or null, vdesc) + const UINT hv = tr.heap ? (tr.heapwords ? 4u : tr.heapraw ? 3u : 2u) : 0u; + UINT first = static_cast<UINT>(InterlockedExchangeAdd(&draw_heap_cursor, static_cast<LONG>(2 * n + hv))) % draw_heap_size; + if (first + 2 * n + hv > draw_heap_size) { + first = 0; + InterlockedExchange(&draw_heap_cursor, static_cast<LONG>(2 * n + hv)); + } + std::uint32_t strides[64] = {}, word3[64] = {}, bases[64] = {}; + bool bound_res[64] = {}; + const LONG probe_frame = trace_uav_busy_frame; + const int probe_slot = probe_frame ? red_producers().uav_slot(key) : -1; + Microsoft::WRL::ComPtr<ID3D12Resource> probe_texture; + const bool capture_armed = cull_capture_armed(key); // LOCAL: X2W_CULL_INPUT_CAPTURE keeps every bound texture + Microsoft::WRL::ComPtr<ID3D12Resource> capture_textures[64]; + u64 res_address[64] = {}; // title address of a bound buffer (X2W_CX_ENTRY_LOG) + std::size_t res_bytes[64] = {}; + const bool show = x2w_local::first_calls(tr.logged, 2); + cx_dump::Dispatch dump(key, x, y, z); // LOCAL lt-lead probe: X2W_CX_DUMP_INPUTS (inactive otherwise) + for (UINT i = 0; i < n; ++i) { + const ComputeTranslation::Res& r = tr.res[i]; + const SIZE_T inc = draw_heap_increment; + const D3D12_CPU_DESCRIPTOR_HANDLE srv{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + i} * inc}; + const D3D12_CPU_DESCRIPTOR_HANDLE uav{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + n + i} * inc}; + // the unused half of each pair stays null + null_view(r, r.uav ? srv : uav, !r.uav); + InterlockedDecrement(&cx_null_res); + const D3D12_CPU_DESCRIPTOR_HANDLE dest = r.uav ? uav : srv; + u64 entry = 0, address = 0; + std::size_t bytes = 0; + if (r.source == 0 && r.a < 16 && pass.compute_kind[r.a] == 5 && pass.compute_address[r.a]) entry = pass.compute_address[r.a] + static_cast<u64>(r.b); + if (r.source == 2 && r.a < 16 && pass.compute_kind[r.a] >= 2 && pass.compute_kind[r.a] <= 4) { + address = pass.compute_address[r.a]; + bytes = readable_window(address, 1u << 20); + } + std::uint32_t words[8] = {}; + if (entry && x2w_local::readable(reinterpret_cast<const void*>(entry), 32)) std::memcpy(words, reinterpret_cast<const void*>(entry), 32); + ViewRecord record{}; + bool known = false; + if (words[0] == view_token_magic) { + AcquireSRWLockShared(¬e_lock); + known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + } else if (entry) { + word3[i] = words[3]; + } + bool bound = false; + if (r.kind) { + bound = known && texture_view(self, r, record, dest, true, static_cast<int>(i) == probe_slot ? std::addressof(probe_texture) + : capture_armed && i < 64 ? std::addressof(capture_textures[i]) : nullptr); + if (capture_armed && i < 64 && static_cast<int>(i) == probe_slot) capture_textures[i] = probe_texture; + } else { + if (known && record.slot == 17 && record.desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(&address, record.desc, 8); + std::memcpy(&size, record.desc + 8, 4); + bytes = size; + } else if (known && (record.slot == 18 || record.slot == 19) && record.desc_bytes >= 24) { + Wrapper* resource = as_wrapper(reinterpret_cast<const void*>(record.resource)); + D3D12_SRV_DIMENSION dim{}; + std::memcpy(&dim, record.desc + 4, 4); + x2w_startup::BufferViewLayout l; + if (dim == 1 /* BUFFER in both SRV and UAV enums */ && resource && resource->own().title_memory && + x2w_startup::buffer_view_layout_from_desc(record.slot == 19, record.desc, record.desc_bytes, l, typed_views_off())) { + address = reinterpret_cast<u64>(resource->own().title_memory) + l.offset; + bytes = static_cast<std::size_t>(l.bytes); + strides[i] = l.index_stride; + note_typed_view(l, record, false); + if (!typed_views_off() && l.kind == x2w_startup::BufferViewKind::typed) { + // word 3 of the V# the console holds for this typed view (format, swizzle), for bufword3 entry + // values; raw and structured views keep 0 (the translator's raw-words fallback) + std::uint32_t v[8]; + x2w_startup::gfx10_buffer_words(l, v); + word3[i] = v[3]; + InterlockedIncrement(&cxv_word3); + } + } + } else if (entry && words[0] != view_token_magic) { + address = words[0] | (static_cast<u64>(words[1] & 0xffff) << 32); + strides[i] = (words[1] >> 16) & 0x3fff; + bytes = static_cast<std::size_t>(strides[i] ? strides[i] : 1) * words[2]; + } + if (bytes > (256u << 20)) bytes = 256u << 20; + ID3D12Resource* window = nullptr; + u64 offset = 0; + if (address && bytes && desktop_range(address, bytes, &window, &offset)) { + const u64 aligned = offset & ~15ull; + bases[i] = static_cast<std::uint32_t>(offset - aligned); + const UINT elements = static_cast<UINT>((bytes + bases[i] + 3) / 4); + if (r.uav) { + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d.Buffer.FirstElement = aligned / 4; + d.Buffer.NumElements = elements; + d.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device_of(the_device)->CreateUnorderedAccessView(window, nullptr, &d, dest); + } else { + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + d.Buffer.FirstElement = aligned / 4; + d.Buffer.NumElements = elements; + d.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device_of(the_device)->CreateShaderResourceView(window, &d, dest); + } + bound = true; + res_address[i] = address; + res_bytes[i] = bytes; + // LOCAL (video): X2W_CX_UAV_WRITTEN=1 registers a translated compute buffer UAV as GPU-written, as draw UAVs and + // GPU copies are, so translated draws read the range in place instead of from a record-time copy. Ranges above + // 1 MiB are not registered (counted), so a wide UAV does not turn every buffer in its window into an in-place read. + static const bool uav_written = x2w_local::env_on("X2W_CX_UAV_WRITTEN"); + if (r.uav && uav_written) { + static LONG registered, too_wide; + const bool wide = bytes > (1u << 20); + if (!wide) note_gpu_written(address, bytes); + const LONG n = InterlockedIncrement(wide ? &too_wide : ®istered); + if ((n & (n - 1)) == 0) + log("x2w-cx X2W_CX_UAV_WRITTEN: %s %ld (latest %016llx uav %u 0x%llx, %zu bytes)", wide ? "not registered (> 1 MiB)" : "registered", + n, key, i, address, bytes); + } + } + if (const int rw = range_watch_hit(address, bytes); rw >= 0) { + if (range_watch_line(rw)) + log("x2w-watch 0x%llx: compute %016llx %s %u 0x%llx (%zu bytes) frame %ld: %s", range_watch_address(rw), key, r.uav ? "uav" : "srv", + i, address, bytes, frame_number, bound ? "bound" : "NULL"); + range_watch_sample("compute-bind", key); + } + } + if (!bound) null_view(r, dest, r.uav); + bound_res[i] = bound; + if (dump) dump.slot(i, r.uav, r.kind, bound, record.resource, res_address[i], res_bytes[i]); + if (show) + log("x2w-cx %016llx %s %u kind %d source %d(%d,%d): entry 0x%llx words %08x %08x %08x %08x -> address 0x%llx %zu bytes stride %u: %s", + key, r.uav ? "uav" : "srv", i, r.kind, r.source, r.a, r.b, entry, words[0], words[1], words[2], words[3], address, bytes, + strides[i], bound ? "bound" : "NULL"); + } + std::uint32_t values[64] = {}; + // LOCAL: whether each entry value is the title's. A root constant word the title has not set since the root + // signature changed (or set as another kind of root argument), or a descword whose table is not bound, would + // be a stale value or 0; such a dispatch is skipped ("entry value unresolved"; X2W_CX_UNRESOLVED_RUN=1 runs it). + // A stride / word 3 / base of a resource that is not bound only addresses that null resource: counted, run. + char state[64] = {}; // 0 resolved, 'u' unresolved (skips), 'n' of a null resource + int unresolved = -1; + for (std::size_t i = 0; i < tr.uds.size(); ++i) { + const ComputeTranslation::Ud& ud = tr.uds[i]; + const bool in = ud.a >= 0 && ud.a < 64; + values[i] = ud.kind == 3 ? ((ud.a < 16 && ud.b < 16) ? pass.compute_constants[ud.a][ud.b] : 0) + : ud.kind == 4 ? (in ? strides[ud.a] : 0) : ud.kind == 5 ? (in ? word3[ud.a] : 0) : (in ? bases[ud.a] : 0); + if (ud.kind == 3) { + const bool set = ud.a >= 0 && ud.a < 16 && ud.b >= 0 && ud.b < 16 && pass.compute_kind[ud.a] == 1 && + ((pass.compute_set[ud.a] >> ud.b) & 1); + if (!set) state[i] = 'u'; + } else if (ud.kind == 7) { + bool resolved = false; + values[i] = descword_value(pass, ud.a, ud.b, key, &resolved); + if (!resolved) state[i] = 'u'; + } else if (!in || static_cast<std::size_t>(ud.a) >= n || !bound_res[ud.a]) { + state[i] = 'n'; + } + if (state[i] == 'u' && unresolved < 0) unresolved = static_cast<int>(i); + if (state[i]) InterlockedIncrement(state[i] == 'u' ? (ud.kind == 3 ? &cxe_rootconst : &cxe_descword) : &cxe_null_res); + } + static const bool run_unresolved = x2w_local::env_on("X2W_CX_UNRESOLVED_RUN"); + if (cx_entry_log(key) && x2w_local::first_calls(tr.entry_logged, 4)) { + char text[1600]; + int used = std::snprintf(text, sizeof(text), "x2w-cx entry %016llx dispatch (%u, %u, %u):", key, x, y, z); + for (std::size_t i = 0; i < tr.uds.size() && used < static_cast<int>(sizeof(text)) - 80; ++i) { + const ComputeTranslation::Ud& ud = tr.uds[i]; + static const char* const names[] = {"?", "?", "?", "rootconst", "stride", "bufword3", "bufbase", "descword"}; + const char* name = ud.kind >= 0 && ud.kind <= 7 ? names[ud.kind] : "?"; + used += std::snprintf(text + used, sizeof(text) - used, " ud%zu=%08x %s(%d,%d)%s", i, values[i], name, ud.a, ud.b, + state[i] == 'u' ? " UNRESOLVED" : state[i] == 'n' ? " null-res" : ""); + } + log("%s", text); + // The first words of each small bound buffer, as the CPU sees the title's memory now. The GPU reads the same + // pages in place (desktop_range) when the list executes, so a later title write can still change them. + for (UINT i = 0; i < n; ++i) { + if (!res_address[i] || !res_bytes[i] || res_bytes[i] > 256) continue; + std::uint32_t w[8] = {}; + const std::size_t count = res_bytes[i] / 4 < 8 ? res_bytes[i] / 4 : 8; + if (!count || !x2w_local::readable(reinterpret_cast<const void*>(res_address[i]), count * 4)) continue; + std::memcpy(w, reinterpret_cast<const void*>(res_address[i]), count * 4); + log("x2w-cx entry %016llx res %u at 0x%llx (%zu bytes): %08x %08x %08x %08x %08x %08x %08x %08x", key, i, res_address[i], + res_bytes[i], w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]); + } + } + if (unresolved >= 0) { + const ComputeTranslation::Ud& ud = tr.uds[unresolved]; + static LONG logged; + if (first_calls(logged, 12)) + log("x2w-cx %016llx: entry value %d (%s %d %d) unresolved: kind %d, words set %04x%s", key, unresolved, + ud.kind == 3 ? "rootconst" : "descword", ud.a, ud.b, ud.a >= 0 && ud.a < 16 ? pass.compute_kind[ud.a] : -1, + ud.a >= 0 && ud.a < 16 ? pass.compute_set[ud.a] : 0, run_unresolved ? "; run anyway (X2W_CX_UNRESOLVED_RUN)" : "; dispatch skipped"); + if (!run_unresolved) { + dispatch_outcome = co_c67_unresolved; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + } + ID3D12DescriptorHeap* sampler_heap = nullptr; + if (!tr.heap_samplers.empty()) { + if (!prepare_draw_sampler_heap(pass, list, false)) { + dispatch_outcome = co_c67_heap; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + for (UINT slot : tr.heap_samplers) { + D3D12_SAMPLER_DESC sampler{}; + const auto& words = pass.sampler_snapshot->words[slot]; + if (!pass.sampler_snapshot->readable.test(slot) || + (words[0] != view_token_magic && (!x2w_startup::sampler_lod_fields_on() || (words[3] >> 30) == 3)) || + !resolve_draw_sampler(words, sampler)) { + dispatch_outcome = co_c67_heap; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + } + sampler_heap = pass.sampler_heap.Get(); + } + list->SetPipelineState(tr.pso); + if (!pass.heap_set || (sampler_heap && pass.bound_sampler_heap != sampler_heap)) { + x2w_startup::bind_translated_heaps(list, draw_heap, sampler_heap); + pass.heap_set = true; + pass.bound_sampler_heap = sampler_heap; + } + if (cull_heap_probe() && trace_frame_active && key == cull_heap_probe_key() && tr.heap) + trace_cull_heap_entry(self, heap_address, heap_view, values[1]); + list->SetComputeRootSignature(tr.root); + if (sampler_heap) list->SetComputeRootDescriptorTable(tr.sampler_parameter, sampler_heap->GetGPUDescriptorHandleForHeapStart()); + list->SetComputeRoot32BitConstants(0, tr.uds.empty() ? 1u : static_cast<UINT>(tr.uds.size()), values, 0); + if (tr.heap) { + const UINT h0 = first + 2 * n; + const SIZE_T cpu0 = draw_heap->GetCPUDescriptorHandleForHeapStart().ptr; + const u64 gpu0 = draw_heap->GetGPUDescriptorHandleForHeapStart().ptr; + const u64 vinfo_bytes = vinfo_buffer->GetDesc().Width; + bounded_raw_srv(heap_view.window, heap_view.offset, heap_view.bytes, D3D12_CPU_DESCRIPTOR_HANDLE{cpu0 + SIZE_T{h0} * draw_heap_increment}); + bounded_raw_srv(vinfo_buffer, 0, vinfo_bytes, D3D12_CPU_DESCRIPTOR_HANDLE{cpu0 + SIZE_T{h0 + 1} * draw_heap_increment}); + if (tr.heapraw) heap_raw_bind(heap_raw_table, D3D12_CPU_DESCRIPTOR_HANDLE{cpu0 + SIZE_T{h0 + 2} * draw_heap_increment}); + else if (tr.heapwords) bounded_raw_srv(nullptr, 0, 4, D3D12_CPU_DESCRIPTOR_HANDLE{cpu0 + SIZE_T{h0 + 2} * draw_heap_increment}); + if (tr.heapwords) // LOCAL isa-gaps: bounded, so an id past view_ids_max reads 0 (a missing descriptor) + bounded_raw_srv(vdesc_buffer, 0, vdesc_buffer->GetDesc().Width, D3D12_CPU_DESCRIPTOR_HANDLE{cpu0 + SIZE_T{h0 + 3} * draw_heap_increment}); + list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu0 + u64{h0} * draw_heap_increment}); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu0 + u64{h0 + 1} * draw_heap_increment}); + if (!tr.heap_views_logged) { + tr.heap_views_logged = true; // once per key (draw_lock held) + static LONG shown; + if (first_calls(shown, 256)) + log("x2w-cx %016llx: bounded heap views: heapmem %llu bytes (title heap %llu), vinfo %llu", key, heap_view.bytes, heap_view.heap_bytes, + vinfo_bytes); + } + if (n) list->SetComputeRootDescriptorTable(3, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + } else if (n) { + list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + } + ReleaseSRWLockExclusive(&draw_lock); + const int capture_occ = capture_armed ? cull_capture_pick(key) : -1; // LOCAL: X2W_CULL_INPUT_CAPTURE + if (capture_occ >= 0) + cull_capture_before(self, list, key, capture_occ, tr, res_address, res_bytes, strides, word3, capture_textures, values, + static_cast<UINT>(tr.uds.size()), tr.heap ? &heap_view : nullptr, heap_address, x, y, z); + if (dump) dump.copy(self, list, "pre"); + gpu_time::dispatch(self, list, key, false); // LOCAL: X2W_CX_GPU_TIME (d3d12_gpu_time.inl) + indirect_dispatch(self, list, x, y, z); // LOCAL: Dispatch, or the pending ExecuteIndirect (d3d12_indirect.inl) + gpu_time::dispatch(self, list, key, true); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + if (capture_occ >= 0) cull_capture_after(self, list, key, capture_occ, tr, res_address, res_bytes); + if (probe_texture) red_producers().after_uav(self, list, probe_texture.Get(), probe_frame, key, probe_slot); + if (dump) { + dump.copy(self, list, "post"); + dump.finish(list); + } + const LONG done = InterlockedIncrement(&cx_dispatched); + dispatch_outcome = co_c67_run; + if (x2w_local::first_of(done, 8) || done % 5000 == 0) + log("x2w-cx dispatch %ld: %016llx (%u, %u, %u); ready %ld missing %ld null %ld bad-uav %ld; ranges ok %ld split %ld unmapped %ld", done, key, x, y, z, + cx_ready, cx_missing, cx_null_res, cx_bad_uav, range_ok, range_split, range_unmapped); + if ((done & 63) == 1) check_device("translated dispatch", 0); + return true; +} diff --git a/src/startup_stubs/d3d12_compute_binding_trace.inl b/src/startup_stubs/d3d12_compute_binding_trace.inl index f40e41078c..7231499ea1 100644 --- a/src/startup_stubs/d3d12_compute_binding_trace.inl +++ b/src/startup_stubs/d3d12_compute_binding_trace.inl @@ -74,7 +74,7 @@ void trace_compute_dispatch(Wrapper* list, const Pass& pass, UINT x, UINT y, UIN bindings += item; } x2w_local::logf("x2w-compute-bindings key=%016llx Dispatch=%ux%ux%u root=%s desktop-root=%u desktop-pso=%u params=%zu%s", - pipeline.compute_trace_key, x, y, z, root_match, pass.compute_root != nullptr, pass.compute_pipeline, + pipeline.compute_trace_key, x, y, z, root_match, pass.compute_root_desktop != nullptr, pass.compute_pipeline, params ? params->size() : 0, bindings.c_str()); } diff --git a/src/startup_stubs/d3d12_copy_buffer.inl b/src/startup_stubs/d3d12_copy_buffer.inl new file mode 100644 index 0000000000..310cf3c169 --- /dev/null +++ b/src/startup_stubs/d3d12_copy_buffer.inl @@ -0,0 +1,91 @@ +// LOCAL (video): command-list slot 15, CopyBufferRegion(dest, dest offset, source, source offset, bytes). +// Included inside d3d12_xs_device.cpp's anonymous namespace, before the slot tables are filled. +// +// Skipping an upload-to-placed copy leaves stale data in constant buffers consumed by later draws. +// +// X2W_D3D12_COPY_BUFFER: unset or 0 = the old no-op; "log" = no-op, but the first copies are +// logged with their title addresses; 1 = copy title memory to title memory at record time (the +// copy completes before later draws in the same frame take their record-time copies), and log. +// LOCAL SHORTCUT: the copy happens when the title records it, not when the GPU would run it; a +// copy from a buffer that GPU work fills in the same submission copies the older contents, and +// a draw that already took its frame copy of the destination this frame keeps that copy. + +LONG buffer_copies_done, buffer_copies_skipped; + +int copy_buffer_mode() +{ + static const int mode = [] { + char value[8]{}; + const DWORD saved = GetLastError(); + const DWORD length = GetEnvironmentVariableA("X2W_D3D12_COPY_BUFFER", value, sizeof(value)); + SetLastError(saved); + if (!length || value[0] == '0') return 0; + return value[0] == '1' ? 2 : (value[0] == 'l' || value[0] == 'L') ? 1 : (value[0] == 'g' || value[0] == 'G') ? 3 : 0; // 3: LOCAL draw-rt + }(); + return mode; +} + +bool copy_title_bytes(unsigned char* dest, const unsigned char* source, std::size_t bytes) noexcept +{ + __try { + std::memmove(dest, source, bytes); + return true; + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } +} + +void __stdcall list_copy_buffer(Wrapper* self, Wrapper* dest, u64 dest_offset, Wrapper* source, u64 source_offset, u64 bytes) +{ + (void)self; + const int mode = copy_buffer_mode(); + auto* const to = dest && dest->own().kind == resource_kind ? static_cast<unsigned char*>(dest->own().title_memory) : nullptr; + auto* const from = source && source->own().kind == resource_kind ? static_cast<const unsigned char*>(source->own().title_memory) : nullptr; + const char* outcome = "copied"; + bool done = false; + if (!to || !from) { + outcome = !to ? "skipped: destination has no title memory" : "skipped: source has no title memory"; + } else if (!bytes || bytes > (u64{256} << 20) || dest_offset > (u64{1} << 40) || source_offset > (u64{1} << 40)) { + outcome = "skipped: size or offset out of range"; + } else if (!x2w_local::readable(from + source_offset, static_cast<std::size_t>(bytes))) { + outcome = "skipped: source unreadable"; + } else if (mode < 2) { + outcome = "not copied (X2W_D3D12_COPY_BUFFER=log)"; + } else if (!copy_title_bytes(to + dest_offset, from + source_offset, static_cast<std::size_t>(bytes))) { + outcome = "skipped: destination not writable"; + } else { + done = true; + } + InterlockedIncrement(done ? &buffer_copies_done : &buffer_copies_skipped); + copy_watch_note("record-time", to ? reinterpret_cast<u64>(to) + dest_offset : 0, from ? reinterpret_cast<u64>(from) + source_offset : 0, + bytes, outcome); + static SRWLOCK seen_lock = SRWLOCK_INIT; + static std::unordered_set<u64>* seen = new std::unordered_set<u64>; + const u64 where = to ? reinterpret_cast<u64>(to) + dest_offset : reinterpret_cast<u64>(dest) ^ (dest_offset << 1); + AcquireSRWLockExclusive(&seen_lock); + const bool fresh = seen->size() < 4096 && seen->insert(where).second; + ReleaseSRWLockExclusive(&seen_lock); + static LONG shown_small, shown_long; + if (fresh && first_calls(bytes && bytes <= 0x100 ? shown_small : shown_long, 256)) { + const std::size_t dumped = bytes && bytes <= 0x100 ? static_cast<std::size_t>(bytes) : 16; + char head[3 * 0x100 + 1] = ""; + if (from && x2w_local::readable(from + source_offset, dumped)) hex_text(from + source_offset, dumped, head, sizeof(head)); + log("x2w-copy CopyBufferRegion dest %p+0x%llx (title %p) source %p+0x%llx (title %p) bytes 0x%llx: %s; source [%s]", + static_cast<void*>(dest), dest_offset, to ? static_cast<void*>(to + dest_offset) : nullptr, static_cast<void*>(source), + source_offset, from ? static_cast<const void*>(from + source_offset) : nullptr, bytes, outcome, head); + } + static LONG reports; + const LONG total = buffer_copies_done + buffer_copies_skipped; + if (total % 1000 == 0 && first_calls(reports, 40)) + log("x2w-copy CopyBufferRegion totals: copied %ld, skipped %ld", buffer_copies_done, buffer_copies_skipped); +} + +// Installs slot 15 when the switch asks for it; one line says which mode is in effect. +void install_copy_buffer(ListTyped* typed) +{ + const int mode = copy_buffer_mode(); + if (!mode) return; + typed[15] = mode == 3 ? reinterpret_cast<ListTyped>(&list_copy_buffer_gpu) : reinterpret_cast<ListTyped>(&list_copy_buffer); // LOCAL draw-rt + log("x2w-copy X2W_D3D12_COPY_BUFFER=%s: command-list slot 15 (CopyBufferRegion) %s", mode == 3 ? "gpu" : mode == 2 ? "1" : "log", + mode == 3 ? "runs on the GPU in list order (record-time copy as fallback)" : mode == 2 ? "copies title memory at record time" : "is logged only"); +} diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 16aa47bd07..6ac3ec4d95 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -9,19 +9,37 @@ // buffers named by the hardware descriptors in its tables, textures behind view tokens) into an // upload ring / a private descriptor heap. +constexpr int draw_srv_limit = 64; + +enum UavKind { uav_raw, uav_float, uav_rgb, uav_min, uav_max64, uav_or, uav_buf16x4 }; + 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 }; + // desc_word (LOCAL ind-meshps, X2W_MESH_DESCWORD=1): `udsrc <i> descword <param> <byte>`, the dword at <byte> of the + // descriptor table bound at root parameter <param> (draw_descword_value) + enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, buf_word3, uav_word3, uav_base, uav_stride, d16_unorm16, desc_word3, desc_word }; struct Ud { int kind, a, b; }; + // LOCAL draw-rt: kind 0 raw buffer (RWByteAddressBuffer), 1 2D texture (RWTexture2D<float4>), 2 2D texture stored as float3 + // (`tex2d3`: bound only to a view of at most 3 channels); source 0 table(param a, byte b), 2 root parameter a + struct Uav { int kind, source, a, b; }; int state = 0; // 1 ready, 2 unavailable ULONGLONG retry_manifest_at = 0; // Only an absent manifest can become ready on a later draw. std::vector<Srv> srvs; std::vector<Ud> uds; + std::vector<Uav> uavs; // u0.. in their own table (root parameter uav_parameter) + unsigned uav_base_wanted = 0; // bit per uav that has a `udsrc uavbase` value: a misaligned view may start below it + UINT uav_parameter = 0; + bool heap = false; // `heap 1`: heapmem, vinfo and the view-id region (root parameters heap_parameter..+2) + UINT heap_parameter = 0; + bool heap_views_logged = false; // LOCAL meshrt: the "bounded heap views" line (once per key) + bool heapwords = false; // LOCAL meshrt `heapwords 1` (needs `heap 1`): vdesc, root SRV t2 space1 (d3d12_vdesc.inl) + UINT vdesc_parameter = 0; x2w_startup::TranslatedSamplers samplers; x2w_startup::ExportWriteMasks write_masks; // manifest 'wmask': channels each export leaves unwritten (#1674) x2w_startup::D16ImageSrvs d16_srvs; // manifest 'd16srv': texture views that must match proven D16 formats (#2023) ID3DBlob* vs = nullptr; ID3DBlob* ps = nullptr; + ID3DBlob* ms = nullptr; // LOCAL meshrt: `stage mesh` manifest (d3d12_mesh.inl): vs is null, ps optional ID3D12RootSignature* root = nullptr; std::optional<bool> independent_indirect_entry; std::optional<bool> indexed_indirect_entry; @@ -49,8 +67,73 @@ struct BoundPipeline { D3D12_RASTERIZER_DESC rasterizer{}; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; std::unordered_map<u64, ID3D12PipelineState*> pipelines; // by target formats + // LOCAL (renderstate): fixed-function state decoded from the slot 57 base's state block A (vertex or + // mesh layout, pipeline_state_decode.h) and the nearest slot 55 parts; used only under X2W_DRAW_STATE_*. + bool has_words = false; // state block A read (ds / rs / masked_blend valid where .ok) + bool mesh_layout = false; // A+0x004 == 6: the fields sit 0x54 later (read_words handled it) + bool blend_overridden = false; // a slot 55 blend patch or a stream blend subobject replaces the register words + bool derived_ds = false, derived_rs = false; // a slot 55 depth-stencil / rasterizer part replaces A's + x2w_pipeline_state::DepthStencil ds; + x2w_pipeline_state::Raster rs; + x2w_pipeline_state::Blend masked_blend; + D3D12_DEPTH_STENCIL_DESC patch_ds{}; + D3D12_RASTERIZER_DESC patch_rs{}; + // LOCAL meshrt: the title's raw rasterizer words rs was decoded from (traced-frame mesh lines). + std::uint32_t raw_mode = 0, raw_clip = 0; }; +// LOCAL (renderstate): counters for the decoded fixed-function state, reported every 300 frames. +namespace draw_state { +enum Counter { + decoded, decoded_mesh, class_depth_off, class_depth_read, class_depth_write, class_stencil, class_cull, class_blend, class_masked, + class_dual, refused_depth, refused_raster, refused_blend, derived_ds, derived_rs, derived_invalid, depth_bounds_ignored, + stencil_masks_differ, clip_split, bias_rounded, conservative_dropped, pso_new, pso_failed_fallback, pso_failed_both, + draws_depth_no_target, draws_stencil_no_plane, draws_read_only, draws_rect_cull_off, dual_multi_target, draws_depth_uncleared, count +}; +LONG n[count]; +void add(Counter c) { InterlockedIncrement(&n[c]); } +const x2w_pipeline_state::Switches& switches() +{ + static const x2w_pipeline_state::Switches s = [] { + const auto v = x2w_pipeline_state::switches_from_env(); + log("x2w-draw-state switches: depth %d cull %d (flip %d) blend masks %d depth clears %d depth clip %d (X2W_DRAW_STATE_DEPTH / " + "_CULL / _CULL_FLIP / _BLEND / _DEPTH_CLEAR / _DEPTHCLIP, X2W_DRAW_STATE=0 all off)", v.depth, v.cull, v.flip, v.blend, + v.depth_clear, v.depthclip); + return v; + }(); + return s; +} +} // namespace draw_state + +// One line per 300 frames (counters reset here). +void report_draw_state() +{ + using namespace draw_state; + LONG v[count]; + for (int i = 0; i < count; ++i) v[i] = InterlockedExchange(&n[i], 0); + const auto& s = switches(); + log("x2w-draw-state 300 frames (depth %d cull %d flip %d masks %d): pipelines decoded %ld (mesh layout %ld) [depth off %ld, read %ld, " + "write %ld, stencil %ld, cull %ld, blend %ld, masked %ld, dual-source %ld]; refused depth %ld raster %ld blend %ld; derived parts " + "depth-stencil %ld rasterizer %ld invalid %ld; flagged: depth bounds ignored %ld, stencil back masks differ %ld, one zclip " + "%ld, bias rounded %ld, conservative dropped %ld; PSOs new-state %ld, failed->old state %ld, failed both %ld; draws: depth/" + "stencil test without depth target %ld, stencil without plane %ld, read-only target writes off %ld, rect list cull off %ld, " + "dual-source with >1 target %ld, depth/stencil test on a never-cleared depth target off %ld", + s.depth, s.cull, s.flip, s.blend, v[decoded], v[decoded_mesh], v[class_depth_off], v[class_depth_read], v[class_depth_write], + v[class_stencil], v[class_cull], v[class_blend], v[class_masked], v[class_dual], v[refused_depth], v[refused_raster], + v[refused_blend], v[derived_ds], v[derived_rs], v[derived_invalid], v[depth_bounds_ignored], v[stencil_masks_differ], + v[clip_split], v[bias_rounded], v[conservative_dropped], v[pso_new], v[pso_failed_fallback], v[pso_failed_both], + v[draws_depth_no_target], v[draws_stencil_no_plane], v[draws_read_only], v[draws_rect_cull_off], v[dual_multi_target], + v[draws_depth_uncleared]); + if (s.depth_clear) + log("x2w-draw-state 300 frames: depth clears (slot 51) forwarded %ld; dropped: list not open %ld, not a depth view %ld, depth " + "outside [0, 1] %ld, nothing to clear %ld", InterlockedExchange(&depth_clears[0], 0), InterlockedExchange(&depth_clears[1], 0), + InterlockedExchange(&depth_clears[2], 0), InterlockedExchange(&depth_clears[3], 0), InterlockedExchange(&depth_clears[4], 0)); +} +// LOCAL meshrt (d3d12_mesh.inl): mesh pipelines through draw_translated. +int load_mesh_stages(Translation& tr, const std::string& manifest); +bool mesh_issue_active(Wrapper* self); +ID3D12PipelineState* mesh_pso_for(const Translation& tr); + // Looks for a desktop-layout D3D12_BLEND_DESC inside a state block: two flags, then eight render // target entries whose fields are all inside their enumerations. bool find_blend(const std::vector<unsigned char>& block, D3D12_BLEND_DESC* out, std::size_t* where) @@ -76,11 +159,365 @@ bool find_blend(const std::vector<unsigned char>& block, D3D12_BLEND_DESC* out, } SRWLOCK draw_lock = SRWLOCK_INIT; +// LOCAL: who took draw_lock last (line, thread, time), and a monitor that logs when the lock has +// been held for 10 s or more (title threads waiting on it trip the title's own hang watchdog). +// Logs another thread's stack (module+offset per frame), unwound through the unwind tables while +// the thread is suspended; nothing is allocated or logged until it runs again. +void log_thread_stack(DWORD thread_id, const char* what) +{ + HANDLE thread = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, thread_id); + if (!thread) return; + DWORD64 frames[40] = {}; + int depth = 0; + if (SuspendThread(thread) != static_cast<DWORD>(-1)) { + CONTEXT context{}; + context.ContextFlags = CONTEXT_FULL; + if (GetThreadContext(thread, &context)) { + for (; depth < 40 && context.Rip; ++depth) { + frames[depth] = context.Rip; + DWORD64 image = 0; + PRUNTIME_FUNCTION function = RtlLookupFunctionEntry(context.Rip, &image, nullptr); + if (!function) { + // A leaf function: the return address is at rsp. + if (IsBadReadPtr(reinterpret_cast<void*>(context.Rsp), 8)) break; + context.Rip = *reinterpret_cast<DWORD64*>(context.Rsp); + context.Rsp += 8; + continue; + } + void* handler_data = nullptr; + DWORD64 establisher = 0; + RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, context.Rip, function, &context, &handler_data, &establisher, nullptr); + } + } + ResumeThread(thread); + } + CloseHandle(thread); + char text[2400]; + int at = 0; + for (int i = 0; i < depth && at < static_cast<int>(sizeof(text)) - 80; ++i) { + HMODULE module = nullptr; + char name[MAX_PATH] = "?"; + if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast<LPCSTR>(frames[i]), &module) && module) { + GetModuleFileNameA(module, name, MAX_PATH); + const char* slash = std::strrchr(name, '\\'); + at += std::snprintf(text + at, sizeof(text) - at, " %s+0x%llx", slash ? slash + 1 : name, + static_cast<unsigned long long>(frames[i] - reinterpret_cast<DWORD64>(module))); + } else { + at += std::snprintf(text + at, sizeof(text) - at, " 0x%llx", static_cast<unsigned long long>(frames[i])); + } + } + log("x2w-draw %s thread %lu stack:%s", what, thread_id, text); +} +volatile LONG draw_lock_line, draw_lock_thread; +volatile LONG64 draw_lock_since; +void draw_lock_taken(int line) +{ + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + draw_lock_line = line; + draw_lock_thread = static_cast<LONG>(GetCurrentThreadId()); + draw_lock_since = now.QuadPart; + static const HANDLE monitor = CreateThread(nullptr, 0, [](void*) -> DWORD { + LARGE_INTEGER frequency; + QueryPerformanceFrequency(&frequency); + LONG64 reported = 0; + for (;;) { + Sleep(5000); + if (TryAcquireSRWLockExclusive(&draw_lock)) { + ReleaseSRWLockExclusive(&draw_lock); + continue; + } + const LONG64 since = draw_lock_since; + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + const double held = static_cast<double>(now.QuadPart - since) / static_cast<double>(frequency.QuadPart); + // Two more looks 5 s apart show whether the holder is moving. + static int looks; + if (held >= 10.0 && since == reported && looks < 2) { + ++looks; + log_thread_stack(static_cast<DWORD>(draw_lock_thread), "draw_lock holder (again)"); + } + if (held >= 10.0 && since != reported) { + looks = 0; + reported = since; + log("x2w-draw draw_lock held %.1f s by thread %ld (taken at line %ld)", held, draw_lock_thread, draw_lock_line); + log_thread_stack(static_cast<DWORD>(draw_lock_thread), "draw_lock holder"); + } + } + }, nullptr, 0, nullptr); + (void)monitor; +} +// LOCAL: takes draw_lock; time spent blocked behind another holder is reported as "draw-lock-wait" +// in the time-inside line (calls = acquisitions that had to wait), which the 10 s monitor cannot show. +// LOCAL stall: X2W_DRAW_LOCK_TIMES=1 (default off): hold and wait time of draw_lock by the site that took it (the +// `line` id passed to lock_draw: d3d12_xs_device.cpp line, 100000 + d3d12_draw.inl line, 200000 + d3d12_compute.inl, +// 300000 + d3d12_mesh.inl, 400000 + d3d12_rawaddr.inl, 900000 + d3d12_memcut_release.inl). One "x2w-draw lock times" +// line every 300 frames (queue_present), counters reset there. The hold ends at ReleaseSRWLockExclusive(&draw_lock): +// the macro below routes every exclusive SRW release after this point through release_exclusive_timed, which only +// does the accounting for draw_lock released by the thread that took it. Off: one static bool test per release. +namespace draw_lock_times { +struct Site { + volatile LONG id; + volatile LONG64 holds, hold_ticks, hold_max, waits, wait_ticks, wait_max; +}; +constexpr int site_count = 128; +Site sites[site_count]; +volatile LONG overflow; // acquisitions whose site found no free slot +volatile LONG hold_open; // written by the holder only: draw_lock_taken ran and the release has not been counted +bool on() +{ + static const bool value = x2w_local::env_on("X2W_DRAW_LOCK_TIMES"); + return value; +} +Site* site(LONG id) +{ + const unsigned start = static_cast<unsigned>(id) * 2654435761u; + for (int i = 0; i < site_count; ++i) { + Site& s = sites[(start + static_cast<unsigned>(i)) % site_count]; + LONG seen = s.id; + if (seen == id) return &s; + if (seen == 0) { + seen = InterlockedCompareExchange(&s.id, id, 0); + if (seen == 0 || seen == id) return &s; + } + } + InterlockedIncrement(&overflow); + return nullptr; +} +void raise_max(volatile LONG64& max, LONG64 value) +{ + for (LONG64 seen = max; value > seen;) { + const LONG64 before = InterlockedCompareExchange64(&max, value, seen); + if (before == seen) break; + seen = before; + } +} +void note_wait(LONG id, LONG64 ticks) +{ + if (Site* s = site(id)) { + InterlockedIncrement64(&s->waits); + InterlockedAdd64(&s->wait_ticks, ticks); + raise_max(s->wait_max, ticks); + } +} +const char* file_of(LONG id) +{ + switch (id / 100000) { + case 0: return "xs_device"; + case 1: return "draw"; + case 2: return "compute"; + case 3: return "mesh"; + case 4: return "rawaddr"; + case 9: return id >= 999000 ? "fixture" : "memcut_release"; + default: return "?"; + } +} +// Every 300 frames (queue_present) and from the fixture export: sites by hold time, then reset. +void report(const char* when) +{ + if (!on()) return; + static LONG64 frequency = [] { + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + return f.QuadPart; + }(); + struct Row { LONG id; LONG64 holds, hold_ticks, hold_max, waits, wait_ticks, wait_max; }; + Row rows[site_count]; + int count = 0; + for (Site& s : sites) { + if (!s.id) continue; + rows[count++] = {s.id, InterlockedExchange64(&s.holds, 0), InterlockedExchange64(&s.hold_ticks, 0), InterlockedExchange64(&s.hold_max, 0), + InterlockedExchange64(&s.waits, 0), InterlockedExchange64(&s.wait_ticks, 0), InterlockedExchange64(&s.wait_max, 0)}; + if (!rows[count - 1].holds && !rows[count - 1].waits) --count; + } + std::sort(rows, rows + count, [](const Row& a, const Row& b) { return a.hold_ticks > b.hold_ticks; }); + const auto ms = [](LONG64 ticks) { return static_cast<double>(ticks) * 1000.0 / static_cast<double>(frequency); }; + LONG64 hold_total = 0, wait_total = 0; + for (int i = 0; i < count; ++i) hold_total += rows[i].hold_ticks, wait_total += rows[i].wait_ticks; + char line[3072]; + int n = std::snprintf(line, sizeof(line), "x2w-draw lock times (%s, X2W_DRAW_LOCK_TIMES): held %.1f ms, waited %.1f ms over %d sites%s; " + "site id file holds/total ms/max ms, waits/total ms/max ms:", when, ms(hold_total), ms(wait_total), count, + overflow ? " (site table full: some not counted)" : ""); + for (int i = 0; i < count && n < static_cast<int>(sizeof(line)) - 160; ++i) { + const Row& r = rows[i]; + n += std::snprintf(line + n, sizeof(line) - n, " %ld %s %lld/%.1f/%.2f, %lld/%.1f/%.2f;", r.id, file_of(r.id), r.holds, ms(r.hold_ticks), + ms(r.hold_max), r.waits, ms(r.wait_ticks), ms(r.wait_max)); + } + log("%s", line); +} +} // namespace draw_lock_times +void lock_draw(int line) +{ + if (!TryAcquireSRWLockExclusive(&draw_lock)) { + Timed waited(time_draw_lock_wait); + if (draw_lock_times::on()) { + LARGE_INTEGER before, after; + QueryPerformanceCounter(&before); + AcquireSRWLockExclusive(&draw_lock); + QueryPerformanceCounter(&after); + draw_lock_times::note_wait(line, after.QuadPart - before.QuadPart); + } else { + AcquireSRWLockExclusive(&draw_lock); + } + } + draw_lock_taken(line); + if (draw_lock_times::on()) draw_lock_times::hold_open = 1; +} +void release_exclusive_timed(PSRWLOCK lock) +{ + if (lock == &draw_lock && draw_lock_times::on() && draw_lock_times::hold_open && + draw_lock_thread == static_cast<LONG>(GetCurrentThreadId())) { + draw_lock_times::hold_open = 0; + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + const LONG64 ticks = now.QuadPart - draw_lock_since; + if (draw_lock_times::Site* s = draw_lock_times::site(draw_lock_line)) { + InterlockedIncrement64(&s->holds); + InterlockedAdd64(&s->hold_ticks, ticks); + draw_lock_times::raise_max(s->hold_max, ticks); + } + } + ReleaseSRWLockExclusive(lock); +} +#define ReleaseSRWLockExclusive(lock) release_exclusive_timed(lock) +// LOCAL stall: X2W_DRAW_LOCK_SPLIT=1 (default off). draw_translated holds draw_lock for the lookups, the PSO, the +// sampler heap, the heap-view fill and the uav binding as before, then releases it for the srv loop and takes it +// again only around the calls that touch process-wide state (texture binds, null-binding counters, gpu_written, +// frame_copy, range watch, mesh dumps, the device check) and for the recording tail (SetPipelineState .. Draw). +// What runs unlocked: the index range scan, readable_window probes, entry reads, view_records (note_lock), +// buffer view creation into this call's own ring slots, desktop_range (own lock), placed-stream copies +// (reserve_upload_ring has its own lock), require_state / window_read_state (this list's own states), log lines. +bool draw_lock_split() +{ + static const bool on = x2w_local::env_on("X2W_DRAW_LOCK_SPLIT"); + return on; +} +// Takes draw_lock for its scope when `split` (the lock is not held then); nothing otherwise (it is held). +struct SplitRelock { + bool split; + SplitRelock(bool s, int line) : split(s) { if (split) lock_draw(line); } + ~SplitRelock() { if (split) ReleaseSRWLockExclusive(&draw_lock); } + SplitRelock(const SplitRelock&) = delete; + SplitRelock& operator=(const SplitRelock&) = delete; +}; +// Fixture hook (startup_draw_lock_times): op 0 takes draw_lock at site 999000 + b, holds it a microseconds (spin) +// and releases it; op 1 writes the report now ("fixture"). +extern "C" __declspec(dllexport) u64 WINAPI x2w_draw_lock_times_test(int op, u64 a, u64 b) +{ + if (op == 1) { + draw_lock_times::report("fixture"); + return draw_lock_times::on() ? 1 : 0; + } + if (op != 0) return 0; + lock_draw(999000 + static_cast<int>(b)); + LARGE_INTEGER start, now, frequency; + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&start); + do QueryPerformanceCounter(&now); + while (static_cast<u64>(now.QuadPart - start.QuadPart) * 1000000ull < a * static_cast<u64>(frequency.QuadPart)); + ReleaseSRWLockExclusive(&draw_lock); + return 1; +} std::unordered_map<const Wrapper*, BoundPipeline*>& translation_by_pipeline() { static std::unordered_map<const Wrapper*, BoundPipeline*> m; return m; } std::unordered_map<u64, Translation*>& translation_by_key() { static std::unordered_map<u64, Translation*> m; return m; } LONG translated_draws, untranslated_draws, translation_ready, translation_missing, null_bindings; LONG formatted_draws_refused; // draws whose formatted buffer load had no resolved descriptor word 3 (also untranslated) LONG null_by_cause[x2w_local::null_cause_count]; // null_bindings split by cause; the parts add up to it +// LOCAL draw-rt: counters of the manifest features the pipeline translator asks for (RUNTIME_NEEDS 2-5). +// Reported every 300 frames as "x2w-draw-rt totals:" once any translation using them was loaded. +LONG rt_loaded_word3, rt_loaded_uav, rt_loaded_heap; +LONG rt_word3_set, rt_word3_zero; +LONG rt_uav_draws, rt_uav_buf_bound, rt_uav_buf_unresolved, rt_uav_buf_misaligned, rt_srv_in_place, rt_srv_stale_copy; +LONG rt_heap_draws, rt_heap_skipped; +LONG rt_uav_tex[9]; +LONG rt_written_evicted; // GPU-written ranges dropped (registry full) +// GPU-ordered CopyBufferRegion (slot 15, X2W_D3D12_COPY_BUFFER=gpu): copies run on the GPU, and record-time +// fallbacks by reason (the record-time copy of d3d12_copy_buffer.inl). +enum CopyFallback { cf_no_list, cf_no_title_memory, cf_range, cf_unaligned, cf_overlap, cf_dest_unresolved, cf_source_unresolved, + cf_no_pipeline, cf_copy_list_same, cf_reasons }; +const char* const copy_fallback_names[cf_reasons] = {"list not recording", "no title memory", "size or offset out of range", + "offset or size not a multiple of 4", "overlapping ranges in one window", "destination not in one window", + "source not in one window", "copy pipeline unavailable", "copy-type list, source and destination in one window"}; +LONG cg_gpu, cg_same_window, cg_copy_list, cg_record_too, cg_fallback[cf_reasons]; +LONG64 cg_bytes; +std::size_t gpu_written_count(); // draw_lock held +LONG rt_report_frame = -1; +void report_texture_census(); +void report_draw_rt() // draw_lock held +{ + report_texture_census(); + if (frame_number % 300 || frame_number == rt_report_frame) return; + LONG fallbacks = 0; + for (LONG f : cg_fallback) fallbacks += f; + if (cg_gpu || fallbacks) { + rt_report_frame = frame_number; + log("x2w-copy-gpu totals: frame %ld; on the GPU %ld (same window %ld, copy-type lists %ld, %lld KiB; also copied at record time %ld); " + "record-time fallback %ld (list %ld, title memory %ld, range %ld, unaligned %ld, overlap %ld, dest unresolved %ld, source unresolved %ld, " + "pipeline %ld, copy list same window %ld); gpu-written ranges %zu evicted %ld", + frame_number, cg_gpu, cg_same_window, cg_copy_list, cg_bytes >> 10, cg_record_too, fallbacks, cg_fallback[0], cg_fallback[1], + cg_fallback[2], cg_fallback[3], cg_fallback[4], cg_fallback[5], cg_fallback[6], cg_fallback[7], cg_fallback[8], gpu_written_count(), + rt_written_evicted); + } + if (!(rt_loaded_word3 | rt_loaded_uav | rt_loaded_heap)) return; + rt_report_frame = frame_number; + log("x2w-draw-rt totals: frame %ld; loaded bufword3 %ld uav %ld heap %ld; bufword3 values set %ld zero %ld; " + "uav draws %ld, buffer uavs bound %ld null (unresolved %ld misaligned %ld); srvs in place %ld stale copy %ld; " + "texture uavs bound %ld, draws skipped (unresolved %ld flag %ld shape %ld format %ld store %ld channels %ld atomic format %ld atomic support %ld); heap draws %ld skipped %ld", + frame_number, rt_loaded_word3, rt_loaded_uav, rt_loaded_heap, rt_word3_set, rt_word3_zero, + rt_uav_draws, rt_uav_buf_bound, rt_uav_buf_unresolved, rt_uav_buf_misaligned, rt_srv_in_place, rt_srv_stale_copy, + rt_uav_tex[0], rt_uav_tex[1], rt_uav_tex[2], rt_uav_tex[3], rt_uav_tex[4], rt_uav_tex[5], rt_uav_tex[6], rt_uav_tex[7], rt_uav_tex[8], rt_heap_draws, rt_heap_skipped); +} + +// LOCAL (textures): X2W_TEXTURE_CENSUS=1 (d3d12_memory_srv.inl). Table texture srvs of translated draws, counted +// by outcome: bound to a real texture (by where the texture came from, and by desktop format) or null (by cause). +// One "x2w-texcensus draw textures" line every 300 frames (with the slot-70 lines), cumulative; with +// X2W_TEXTURE_CENSUS_EVERY=1 also after every counted binding. +bool texture_census_on(); +bool census_every_event(); +void report_memory_srv_census(long frame); +enum TextureSource { ts_linear_srv, ts_tiled_address, ts_other, ts_detiled, ts_count }; +LONG64 census_real[ts_count], census_null[x2w_local::null_cause_count], census_real_format[128]; +LONG census_report_frame = -1; +void log_texture_census(const char* when); +void census_texture_binding(Wrapper* resource, ID3D12Resource* texture, x2w_local::NullCause cause) +{ + if (!texture_census_on()) return; + if (!texture) { + InterlockedIncrement64(&census_null[static_cast<int>(cause)]); + } else { + const int source = resource && resource->own().detiled_memory_srv ? ts_detiled + : resource && resource->own().linear_memory_srv ? ts_linear_srv + : resource && resource->own().tiled_address_srv ? ts_tiled_address : ts_other; + InterlockedIncrement64(&census_real[source]); + InterlockedIncrement64(&census_real_format[static_cast<UINT>(texture->GetDesc().Format) & 127]); + } + if (census_every_event()) log_texture_census("binding"); +} +void report_texture_census() // draw_lock held +{ + if (!texture_census_on() || frame_number % 300 || frame_number == census_report_frame) return; + census_report_frame = frame_number; + char when[32]; + std::snprintf(when, sizeof(when), "frame %ld", frame_number); + log_texture_census(when); + report_memory_srv_census(frame_number); +} +void log_texture_census(const char* when) +{ + char formats[512] = ""; + int used = 0; + for (int f = 0; f < 128 && used < 480; ++f) + if (census_real_format[f]) used += std::snprintf(formats + used, sizeof(formats) - used, " %d:%lld", f, census_real_format[f]); + char nulls[256] = ""; + used = 0; + for (int c = 0; c < x2w_local::null_cause_count && used < 230; ++c) + if (census_null[c]) used += std::snprintf(nulls + used, sizeof(nulls) - used, " cause%d:%lld", c, census_null[c]); + log("x2w-texcensus draw textures %s (cumulative): real %lld (linear memory srv %lld, tiled address %lld, other %lld, detiled %lld), " + "null%s; real by format%s", + when, census_real[0] + census_real[1] + census_real[2] + census_real[3], census_real[0], census_real[1], census_real[2], + census_real[3], nulls, formats); +} void count_null_binding(x2w_local::NullCause cause) { @@ -88,8 +525,316 @@ void count_null_binding(x2w_local::NullCause cause) InterlockedIncrement(&null_bindings); InterlockedIncrement(&null_by_cause[static_cast<int>(cause)]); } +// LOCAL (video): descriptor slots a null texture was copied from while free (X2W_DRAW_NULL_TEXTURE_LOG=1). +// note_descriptor_watch (each present) logs the first change of each: "written later" or "never". +struct WatchedSlot { u64 at, key, slot; UINT srv; std::uint32_t words[8]; LONG since; bool reported; }; +SRWLOCK watch_lock = SRWLOCK_INIT; +std::vector<WatchedSlot>& watched_slots() { static std::vector<WatchedSlot> v; return v; } +extern LONG frame_number; +void watch_descriptor(u64 at, const std::uint32_t* words, u64 key, UINT srv, u64 slot) +{ + AcquireSRWLockExclusive(&watch_lock); + if (watched_slots().size() < 64) { + WatchedSlot w{at, key, slot, srv, {}, frame_number, false}; + std::memcpy(w.words, words, sizeof(w.words)); + watched_slots().push_back(w); + } + ReleaseSRWLockExclusive(&watch_lock); +} +void note_descriptor_watch(LONG frame) +{ + AcquireSRWLockExclusive(&watch_lock); + for (WatchedSlot& w : watched_slots()) { + if (w.reported) continue; + std::uint32_t now[8]{}; + if (!x2w_local::readable(reinterpret_cast<const void*>(w.at), sizeof(now))) continue; + std::memcpy(now, reinterpret_cast<const void*>(w.at), sizeof(now)); + if (!std::memcmp(now, w.words, sizeof(now))) continue; + w.reported = true; + log("x2w-draw watched slot 0x%llx (for %016llx srv %u, watched since frame %ld) changed at frame %ld: %08x %08x %08x %08x %08x %08x %08x %08x", + w.slot, w.key, w.srv, w.since, frame, now[0], now[1], now[2], now[3], now[4], now[5], now[6], now[7]); + } + ReleaseSRWLockExclusive(&watch_lock); +} + +// LOCAL (video): X2W_DRAW_NULL_TEXTURE_LOG=1 logs the first null texture binding of each pipeline key +// and srv (at most 96 lines) with the 8 descriptor words, to find which draws lose their texture +// and whether the title wrote a hardware descriptor there instead of a view the wrapper made. +bool refused_marker_description(const std::uint32_t* w, char* out, std::size_t size); // below +void note_null_texture(u64 key, UINT srv, u64 entry, const std::uint32_t* words, x2w_local::NullCause cause) +{ + static const bool on = [] { + const bool value = x2w_local::env_on("X2W_DRAW_NULL_TEXTURE_LOG"); + if (value) log("x2w-draw X2W_DRAW_NULL_TEXTURE_LOG=1: null texture bindings are logged per pipeline key and srv"); + return value; + }(); + if (!on || cause == x2w_local::NullCause::none) return; + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_set<u64>* seen = new std::unordered_set<u64>; + static LONG lines; + AcquireSRWLockExclusive(&lock); + const bool fresh = seen->insert(key * 31 + srv).second; + ReleaseSRWLockExclusive(&lock); + if (!fresh || !first_calls(lines, 96)) return; + log("x2w-draw null texture %016llx srv %u cause %s frame %ld: entry 0x%llx words %08x %08x %08x %08x %08x %08x %08x %08x", key, srv, + x2w_local::null_cause_names[static_cast<int>(cause)], frame_number, entry, words[0], words[1], words[2], words[3], words[4], + words[5], words[6], words[7]); + // LOCAL (textures): X2W_BUFFER_HEAP_INDEX's refused-view marker, with the description of the refused call. + if (char marker[256]; refused_marker_description(words, marker, sizeof marker)) { + log("x2w-draw null texture %016llx srv %u: %s", key, srv, marker); + return; + } + bool rest_zero = true; + for (int i = 1; i < 8; ++i) rest_zero = rest_zero && words[i] == 0; + const bool link = words[0] && words[0] != view_token_magic && rest_zero; + // A token whose first word the title replaced (a freed slot that still names a view). + const bool clobbered = words[0] != view_token_magic && words[2] >= 17 && words[2] <= 22 && (words[4] || words[5]); + if (!link && !clobbered) return; + AcquireSRWLockShared(¬e_lock); + const std::vector<HeapInfo> heaps = heap_infos(); + ViewRecord named{}; + const bool named_known = clobbered && words[1] < view_records().size(); + if (named_known) named = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + if (clobbered) + log("x2w-draw null texture %016llx srv %u: looks like a freed token: first word 0x%x, view id %u slot %u resource 0x%08x%08x; view %s%s", + key, srv, words[0], words[1], words[2], words[5], words[4], named_known ? "known" : "UNKNOWN", + named_known && named.resource == (u64{words[5]} << 32 | words[4]) ? ", resource matches" : named_known ? ", resource DIFFERS" : ""); + bool in_heap = false; + for (std::size_t h = 0; h < heaps.size(); ++h) { + const HeapInfo& heap = heaps[h]; + if (!heap.title_cpu) continue; + const UINT stride = title_descriptor_stride(heap.title_cpu, heap.increment); + if (entry < heap.title_cpu || entry >= heap.title_cpu + u64{heap.count} * stride) continue; + in_heap = true; + const u64 index = (entry - heap.title_cpu) / stride; + log("x2w-draw null texture %016llx srv %u: entry 0x%llx is index 0x%llx of heap %zu (type %u, count %u, title 0x%llx, stride %u); shadow id %u", + key, srv, entry, index, h, heap.type, heap.count, heap.title_cpu, stride, heap.shadow ? heap.shadow[index] : 0u); + if (!link) break; + for (int d = -1; d <= 0; ++d) { + const u64 slot = u64{words[0]} + d; + if (slot >= heap.count) continue; + const u64 at = heap.title_cpu + slot * stride; + std::uint32_t there[8]{}; + const bool readable = x2w_local::readable(reinterpret_cast<const void*>(at), sizeof(there)); + if (readable) std::memcpy(there, reinterpret_cast<const void*>(at), sizeof(there)); + const std::uint32_t shadow = heap.shadow ? heap.shadow[slot] : 0; + log("x2w-draw null texture %016llx srv %u: heap %zu slot 0x%llx (N%s): %s words %08x %08x %08x %08x %08x %08x; shadow id %u%s", + key, srv, h, slot, d ? "-1" : "", readable ? (there[0] == view_token_magic ? "token" : "no token") : "unreadable", there[0], there[1], + there[2], there[3], there[4], there[5], shadow, shadow ? "" : " (no view ever created there)"); + if (d == -1 && readable) watch_descriptor(at, there, key, srv, slot); + } + break; + } + if (!in_heap) log("x2w-draw null texture %016llx srv %u: entry 0x%llx is in no title descriptor heap", key, srv, entry); +} LONG frame_number; +LONG heap_index_checks, heap_index_restored, heap_index_slot_token, heap_index_shadow, heap_index_unresolved; +void resolve_heap_index(u64 key, UINT srv, u64 entry, std::uint32_t* words) +{ + static const bool on = [] { + const bool value = x2w_local::env_on("X2W_DRAW_TEXTURE_HEAP_INDEX"); + if (value) log("x2w-draw X2W_DRAW_TEXTURE_HEAP_INDEX=1: freed or free-slot texture descriptors are resolved (slot N-1 / view id)"); + return value; + }(); + if (!on || words[0] == view_token_magic) return; + bool rest_zero = true; + for (int i = 1; i < 8; ++i) rest_zero = rest_zero && words[i] == 0; + const bool link = words[0] && rest_zero; + const bool clobbered = words[2] >= 17 && words[2] <= 22 && (words[4] || words[5]); + if (!link && !clobbered) return; + const LONG checks = InterlockedIncrement(&heap_index_checks); + std::uint32_t out[8]{}; + const char* how = nullptr; + AcquireSRWLockShared(¬e_lock); + if (clobbered) { + if (words[1] < view_records().size() && view_records()[words[1]].resource == (u64{words[5]} << 32 | words[4])) { + std::memcpy(out, words, sizeof(out)); + out[0] = view_token_magic; + how = "restored token"; + } + } else { + for (const HeapInfo& heap : heap_infos()) { + if (!heap.title_cpu || words[0] > heap.count) continue; + const UINT stride = title_descriptor_stride(heap.title_cpu, heap.increment); + if (entry < heap.title_cpu || entry >= heap.title_cpu + u64{heap.count} * stride) continue; + const u64 slot = u64{words[0]} - 1; + const u64 at = heap.title_cpu + slot * stride; + if (x2w_local::readable(reinterpret_cast<const void*>(at), sizeof(out))) { + std::memcpy(out, reinterpret_cast<const void*>(at), sizeof(out)); + if (out[0] == view_token_magic && out[1] < view_records().size()) how = "slot N-1 token"; + } + const std::uint32_t shadow = heap.shadow ? heap.shadow[slot] : 0; + if (!how && shadow && shadow - 1 < view_records().size()) { + const ViewRecord& r = view_records()[shadow - 1]; + const std::uint32_t token[8] = {view_token_magic, shadow - 1, r.slot, 0, static_cast<std::uint32_t>(r.resource), + static_cast<std::uint32_t>(r.resource >> 32), 0, 0}; + std::memcpy(out, token, sizeof(out)); + how = "slot N-1 shadow id"; + } + break; + } + } + ReleaseSRWLockShared(¬e_lock); + InterlockedIncrement(!how ? &heap_index_unresolved : how[0] == 'r' ? &heap_index_restored : how[9] == 't' ? &heap_index_slot_token + : &heap_index_shadow); + static LONG reports; + if ((checks & 4095) == 0 && first_calls(reports, 40)) + log("x2w-draw texture heap index totals: checks %ld, restored tokens %ld, slot N-1 tokens %ld, slot N-1 shadow ids %ld, unresolved %ld", checks, + heap_index_restored, heap_index_slot_token, heap_index_shadow, heap_index_unresolved); + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_set<u64>* seen = new std::unordered_set<u64>; + AcquireSRWLockExclusive(&lock); + const bool fresh = seen->size() < 4096 && seen->insert(key * 31 + srv).second; + ReleaseSRWLockExclusive(&lock); + static LONG lines; + if (fresh && first_calls(lines, 48)) + log("x2w-draw texture heap index %016llx srv %u frame %ld: entry 0x%llx words %08x %08x %08x -> %s%s (view id %u slot %u)", key, srv, + frame_number, entry, words[0], words[1], words[2], how ? how : "unresolved", how ? "" : ", left null", how ? out[1] : 0u, how ? out[2] : 0u); + if (how) std::memcpy(words, out, sizeof(out)); +} + +bool buffer_heap_index_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_BUFFER_HEAP_INDEX"); + if (v) log("x2w-draw X2W_BUFFER_HEAP_INDEX=1: slot-70 buffers without a resource get a stand-in; free-list buffer entries bind null"); + return v; + }(); + return on; +} +LONG buffer_links, buffer_links_nulled, buffer_refused_views; +// With the switch, a slot-70 call that is refused writes this marker and its reason's code into its destination +// (mark_refused_destination, d3d12_memory_srv.inl), so an entry copied from it names the refusal instead of a link. +constexpr std::uint32_t refused_view_magic = 0x52463258; // "X2FR" +SRWLOCK refusal_names_lock = SRWLOCK_INIT; +const char* refusal_names[64]; +std::uint32_t refusal_code(const char* reason) +{ + AcquireSRWLockExclusive(&refusal_names_lock); + std::uint32_t code = 0; + while (code < 63 && refusal_names[code] && std::strcmp(refusal_names[code], reason)) ++code; + if (!refusal_names[code]) refusal_names[code] = reason; // reasons are string literals + ReleaseSRWLockExclusive(&refusal_names_lock); + return code; +} +const char* refusal_name(std::uint32_t code) +{ + AcquireSRWLockShared(&refusal_names_lock); + const char* name = code < 64 && refusal_names[code] ? refusal_names[code] : "unknown"; + ReleaseSRWLockShared(&refusal_names_lock); + return name; +} +// Why X2W_MEMORY_SRV_DETILE did not take a refused texture call (d3d12_memory_srv.inl detile_decline); 0 = not asked +// (switch off, or not a texture description). +const char* const detile_declines[] = {"-", "not console-swizzled", "a tiled path's form", "announced", "view form", + "layout or element size", "(6: bc mip chain, retired)", "over 1 GiB", "unreadable", "destination", "publish failed", "would detile"}; +// The marker's description words (mark_refused_destination): word 2 = bit 31 | format | layout << 8 | dimension << 17 | +// min(mips, 15) << 20 | detile decline << 24, word 3 = width, word 4 = height, word 5 = depth or array size | first 256 +// bytes readable << 16 | nonzero << 17, words 6/7 = the address. Bit 31 keeps word 2 out of the token slot range. +void describe_marker(const std::uint32_t* w, char* out, std::size_t size) +{ + if (!(w[2] >> 31)) { + std::snprintf(out, size, "no description"); + return; + } + const unsigned decline = (w[2] >> 24) & 15; + std::snprintf(out, size, "fmt %u layout 0x%x dim %u mips %u %ux%ux%u address 0x%llx %s, detile: %s", w[2] & 0xff, (w[2] >> 8) & 0x1ff, + (w[2] >> 17) & 7, (w[2] >> 20) & 15, w[3], w[4], w[5] & 0xffff, u64{w[7]} << 32 | w[6], + !((w[5] >> 16) & 1) ? "unreadable" : (w[5] >> 17) & 1 ? "nonzero" : "zero", + decline < std::size(detile_declines) ? detile_declines[decline] : "?"); +} +bool refused_marker_description(const std::uint32_t* w, char* out, std::size_t size) +{ + if (w[0] != refused_view_magic) return false; + char d[160]; + describe_marker(w, d, sizeof d); + std::snprintf(out, size, "refused: %s; %s", refusal_name(w[1]), d); + return true; +} +// LOCAL (textures): X2W_MARKER_REWRITE_LOG=1 (default off; meaningful with X2W_BUFFER_HEAP_INDEX, which writes the +// markers). Does the title patch a descriptor it created in place, e.g. the T# base of a view created with a null +// address once a streamed texture is placed? A refused-view marker whose word 0 is no longer the magic but whose +// description words are intact says so. Counted ("x2w-draw rewritten refused-view markers N" at powers of two, and in +// the totals line) and the first 8 logged with their words, the decoded description and the base the rewritten words +// would hold as a T# (words 0/1 bits 0-7, << 8) and as a V# (words 0/1 bits 0-15). Read in the draw srv loops only. +LONG marker_rewrites; +bool marker_rewrite_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_MARKER_REWRITE_LOG"); + if (v) log("x2w-draw X2W_MARKER_REWRITE_LOG=1: table entries holding a refused-view marker whose first word was rewritten are counted and logged"); + return v; + }(); + return on; +} +// The description's fixed shape (describe_marker): bit 31 set, bits 28-30 clear, a decline in range, a dimension +// 1-4, a nonzero width, word 5 bits 18-31 clear; and word 0 neither the marker nor a token. +bool rewritten_marker_words(const std::uint32_t* w) +{ + const unsigned dim = (w[2] >> 17) & 7; + return w[0] != refused_view_magic && w[0] != view_token_magic && (w[2] >> 31) && !((w[2] >> 28) & 7) && + ((w[2] >> 24) & 15) < std::size(detile_declines) && dim >= 1 && dim <= 4 && w[3] && !(w[5] >> 18); +} +void note_rewritten_marker(u64 key, UINT srv, u64 entry, const std::uint32_t* w) +{ + if (!marker_rewrite_on() || !rewritten_marker_words(w)) return; + const LONG n = InterlockedIncrement(&marker_rewrites); + if ((n & (n - 1)) == 0) log("x2w-draw rewritten refused-view markers %ld", n); + static LONG shown; + if (!first_calls(shown, 8)) return; + char d[160]; + describe_marker(w, d, sizeof d); + log("x2w-draw rewritten refused-view marker %016llx srv %u frame %ld: entry 0x%llx words %08x %08x %08x %08x %08x %08x %08x %08x; " + "described as %s; reason code %u if word 1 is intact; base as a T# 0x%llx, as a V# 0x%llx", key, srv, frame_number, entry, w[0], w[1], w[2], + w[3], w[4], w[5], w[6], w[7], d, w[1], (u64{w[0]} | u64{w[1] & 0xff} << 32) << 8, u64{w[0]} | u64{w[1] & 0xffff} << 32); +} +bool free_link_words(const std::uint32_t* w) +{ + if (w[0] == refused_view_magic) return true; + if (!w[0] || w[0] == view_token_magic || w[3]) return false; + return (!w[1] && !w[2]) || (w[2] >= 17 && w[2] <= 22); +} +void log_buffer_link(u64 key, UINT srv, u64 entry, const std::uint32_t* words) +{ + AcquireSRWLockShared(¬e_lock); + const std::vector<HeapInfo> heaps = heap_infos(); + ReleaseSRWLockShared(¬e_lock); + char where[96] = "in no title descriptor heap"; + char slots[2][160] = {"", ""}; + for (std::size_t h = 0; h < heaps.size(); ++h) { + const HeapInfo& heap = heaps[h]; + if (!heap.title_cpu) continue; + const UINT stride = title_descriptor_stride(heap.title_cpu, heap.increment); + if (entry < heap.title_cpu || entry >= heap.title_cpu + u64{heap.count} * stride) continue; + std::snprintf(where, sizeof where, "index 0x%llx of heap %zu (count %u)", (entry - heap.title_cpu) / stride, h, heap.count); + for (int d = -1; d <= 0; ++d) { + const u64 slot = u64{words[0]} + d; + if (slot >= heap.count) continue; + const u64 at = heap.title_cpu + slot * stride; + std::uint32_t there[6]{}; + const bool readable = x2w_local::readable(reinterpret_cast<const void*>(at), sizeof(there)); + if (readable) std::memcpy(there, reinterpret_cast<const void*>(at), sizeof(there)); + std::snprintf(slots[d + 1], sizeof slots[0], "slot %s 0x%llx %s %08x %08x %08x %08x %08x %08x shadow %u", d ? "N-1" : "N", slot, + readable ? (there[0] == view_token_magic ? "token" : "words") : "unreadable", there[0], there[1], there[2], there[3], + there[4], there[5], heap.shadow ? heap.shadow[slot] : 0u); + } + break; + } + char kind[80], described[192] = ""; + if (words[0] == refused_view_magic) { + std::snprintf(kind, sizeof kind, "refused: %s", refusal_name(words[1])); + char d[160]; + describe_marker(words, d, sizeof d); + std::snprintf(described, sizeof described, "; refused view: %s", d); + } else { + std::snprintf(kind, sizeof kind, "%s", words[1] || words[2] ? "freed token" : "free link"); + } + log("x2w-frame srv-heapbuf %016llx %u frame %ld: entry 0x%llx words %08x %08x %08x %08x (%s) is %s; %s; %s; bound null%s", key, srv, frame_number, + entry, words[0], words[1], words[2], words[3], kind, where, slots[0], slots[1], described); +} + u64 fnv_bytes(const void* data, std::size_t bytes, u64 hash = 1469598103934665603ull) { for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ static_cast<const unsigned char*>(data)[i]) * 1099511628211ull; @@ -134,6 +879,191 @@ bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std:: return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; } +// LOCAL draw-rt: the translated root signature. Without uav lines (or `heap 1`) it is exactly the shared +// create_translated_root one. Otherwise the extra parameters follow the srv and sampler tables: +// a table of the uavs (u0.., space0); for `heap 1` the title heap memory (t0 space1), the per-view info (t1 +// space1), each a one-descriptor table of a bounded raw view (LOCAL meshrt), and one table over the view-id region with an unbounded SRV range per kind at +// offset 0: t0 in space 2 (Texture2D), 3 (Texture2DArray), 4 (Texture3D), 5 (Texture1D), 6 (raw buffer). +HRESULT create_draw_root(Translation& tr) +{ + const UINT n = static_cast<UINT>(tr.srvs.size()), m = static_cast<UINT>(tr.uavs.size()); + if (!m && !tr.heap) + return x2w_startup::create_translated_root(device_of(the_device), static_cast<UINT>(tr.uds.size()), n, tr.samplers, &tr.root); + // At most 9: constants, srv table, sampler table (smpheap), uav table, heapmem, vinfo, region table, vdesc + // (heapwords) = 2 + 1 + 1 + 3 + 1; root cost <= 32 + 7 tables = 39 of 64 DWORDs (heapmem / vinfo / vdesc are + // one-descriptor tables of bounded views, LOCAL meshrt). + D3D12_ROOT_PARAMETER parameters[9]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameters[0].Constants.Num32BitValues = static_cast<UINT>(tr.uds.size()); + const D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, n, 0, 0, 0}; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[1].DescriptorTable = {1, &srv_range}; + const D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, x2w_startup::translated_sampler_count, 0, + x2w_startup::translated_sampler_space, 0}; + UINT count = x2w_startup::sampler_root_parameter(n); + if (tr.samplers.heap) { + parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[count].DescriptorTable = {1, &sampler_range}; + ++count; + } + const D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, m, 0, 0, 0}; + if (m) { + tr.uav_parameter = count; + parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[count].DescriptorTable = {1, &uav_range}; + ++count; + } + D3D12_DESCRIPTOR_RANGE heap_ranges[5]{}; + // LOCAL meshrt (meshhar 010400): heapmem t0 / vinfo t1 / vdesc t2 in space1 are one-descriptor tables of BOUNDED + // raw views (draw_translated writes them per draw), no longer root SRVs: D3D range-checks a view, not a root SRV. + const D3D12_DESCRIPTOR_RANGE bounded_ranges[3] = {{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 1, 0}, {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 1, 1, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 2, 1, 0}}; + if (tr.heap) { + tr.heap_parameter = count; + parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[count].DescriptorTable = {1, &bounded_ranges[0]}; + parameters[count + 1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[count + 1].DescriptorTable = {1, &bounded_ranges[1]}; + for (UINT k = 0; k < 5; ++k) heap_ranges[k] = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, UINT_MAX, 0, 2 + k, 0}; + parameters[count + 2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[count + 2].DescriptorTable = {5, heap_ranges}; + count += 3; + } + if (tr.heap && tr.heapwords) { // LOCAL meshrt: vdesc, t2 space1 (d3d12_vdesc.inl), a bounded view as above + tr.vdesc_parameter = count; + parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[count++].DescriptorTable = {1, &bounded_ranges[2]}; + } + const auto statics = x2w_startup::decode_statics(tr.samplers); + const D3D12_ROOT_SIGNATURE_DESC desc{count, parameters, static_cast<UINT>(statics.size()), statics.data(), D3D12_ROOT_SIGNATURE_FLAG_NONE}; + x2w_startup::ComPtr<ID3DBlob> blob, errors; + HRESULT hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, &errors); + if (FAILED(hr) && errors) log("x2w-draw-rt %016llx root signature: %.300s", tr.key, static_cast<const char*>(errors->GetBufferPointer())); + if (SUCCEEDED(hr)) hr = device_of(the_device)->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&tr.root)); + return hr; +} + +struct ManifestWatch { + SRWLOCK lock = SRWLOCK_INIT; + std::vector<std::pair<Translation*, std::string>> missing; // translation, its rtv request +}; +ManifestWatch& manifest_watch() { static ManifestWatch w; return w; } +std::unordered_map<const Translation*, volatile LONG>& manifest_seen() { static std::unordered_map<const Translation*, volatile LONG> m; return m; } +bool manifest_poll() { static const bool on = x2w_local::env_on("X2W_MANIFEST_POLL"); return on; } + +void manifest_check(const wchar_t* dir, const wchar_t* name) +{ + std::vector<std::pair<Translation*, std::string>> look; + AcquireSRWLockShared(&manifest_watch().lock); + look = manifest_watch().missing; + ReleaseSRWLockShared(&manifest_watch().lock); + if (look.empty() || (!name && !dir[0])) return; + std::unordered_set<std::wstring> present; + if (!name) { + std::wstring pattern = std::wstring(dir) + L"\\*.txt"; + WIN32_FIND_DATAW found{}; + const HANDLE find = FindFirstFileExW(pattern.c_str(), FindExInfoBasic, &found, FindExSearchNameMatch, nullptr, + FIND_FIRST_EX_LARGE_FETCH); + if (find == INVALID_HANDLE_VALUE) return; + do { + std::wstring file(found.cFileName); + for (wchar_t& c : file) c = static_cast<wchar_t>(towlower(c)); + present.insert(std::move(file)); + } while (FindNextFileW(find, &found)); + FindClose(find); + } + for (const auto& [tr, request] : look) { + wchar_t path[MAX_PATH]; + if (!cache_path(path, L"", tr->key, L".txt")) continue; + const wchar_t* slash = std::wcsrchr(path, L'\\'); + std::wstring file(slash ? slash + 1 : path); + for (wchar_t& c : file) c = static_cast<wchar_t>(towlower(c)); + if (name ? _wcsicmp(file.c_str(), name) != 0 : !present.count(file)) continue; + AcquireSRWLockExclusive(&manifest_watch().lock); + auto& m = manifest_watch().missing; + m.erase(std::remove_if(m.begin(), m.end(), [&](const auto& e) { return e.first == tr; }), m.end()); + InterlockedExchange(&manifest_seen()[tr], 1); + ReleaseSRWLockExclusive(&manifest_watch().lock); + log("x2w-draw manifest for %016llx appeared: reloaded at its next draw", tr->key); + } +} + +DWORD WINAPI manifest_watcher(void*) +{ + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + wchar_t dir[MAX_PATH] = L""; + HANDLE handle = INVALID_HANDLE_VALUE; + if (cache_path(dir, L"", 0, L".txt")) { + if (wchar_t* slash = std::wcsrchr(dir, L'\\')) *slash = 0; + handle = CreateFileW(dir, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, nullptr); + } + log("x2w-draw manifest watcher: %s", handle != INVALID_HANDLE_VALUE ? "directory change records" : "30 s rescans"); + alignas(DWORD) static unsigned char buffer[64 * 1024]; + OVERLAPPED overlapped{}; + overlapped.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); + bool pending = false; + bool scan = true; // first pass: a manifest published before the watch started + for (;;) { + // File names only: the stand-in itself writes req_* files here; a manifest is published by rename + // or creation, both name changes, and the record names the file, so no query is needed. The read + // is armed before any scan, so a file named during the scan is still recorded. + if (!pending && handle != INVALID_HANDLE_VALUE && overlapped.hEvent) { + ResetEvent(overlapped.hEvent); + pending = ReadDirectoryChangesW(handle, buffer, sizeof(buffer), FALSE, FILE_NOTIFY_CHANGE_FILE_NAME, nullptr, + &overlapped, nullptr) != FALSE; + } + if (scan) manifest_check(dir, nullptr); + scan = true; + // 30 s rescan: a manifest published between a failed open and its registration has no record. + if (!pending) { + Sleep(30000); + continue; + } + if (WaitForSingleObject(overlapped.hEvent, 30000) != WAIT_OBJECT_0) continue; + pending = false; + DWORD bytes = 0; + if (!GetOverlappedResult(handle, &overlapped, &bytes, FALSE) || bytes == 0) continue; // overflow: names lost + scan = false; + for (DWORD at = 0;;) { + const auto* record = reinterpret_cast<const FILE_NOTIFY_INFORMATION*>(buffer + at); + if (record->Action == FILE_ACTION_ADDED || record->Action == FILE_ACTION_RENAMED_NEW_NAME) { + wchar_t name[MAX_PATH]; + const std::size_t chars = record->FileNameLength / sizeof(wchar_t); + if (chars < MAX_PATH) { + std::wmemcpy(name, record->FileName, chars); + name[chars] = 0; + if (chars > 4 && _wcsicmp(name + chars - 4, L".txt") == 0) manifest_check(dir, name); + } + } + if (!record->NextEntryOffset) break; + at += record->NextEntryOffset; + } + } +} + +void watch_missing_manifest(Translation& tr, const std::string& request) +{ + static const HANDLE thread = CreateThread(nullptr, 0, manifest_watcher, nullptr, 0, nullptr); + (void)thread; + AcquireSRWLockExclusive(&manifest_watch().lock); + manifest_watch().missing.emplace_back(&tr, request); + manifest_seen()[&tr] = 0; + ReleaseSRWLockExclusive(&manifest_watch().lock); +} + +// draw_lock held: true when the translation's absent manifest should be read again now. +bool manifest_retry_due(Translation& tr) +{ + if (!tr.retry_manifest_at) return false; + if (manifest_poll()) return GetTickCount64() >= tr.retry_manifest_at; + AcquireSRWLockShared(&manifest_watch().lock); + const auto found = manifest_seen().find(&tr); + const bool seen = found != manifest_seen().end() && InterlockedExchange(&found->second, 0) != 0; + ReleaseSRWLockShared(&manifest_watch().lock); + return seen; +} + void load_translation(Translation& tr, const std::string& rtv_request = {}) { tr.state = 2; @@ -148,6 +1078,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) log("x2w-draw no translation for pipeline %016llx", tr.key); } tr.retry_manifest_at = GetTickCount64() + 1000; + if (!manifest_poll()) watch_missing_manifest(tr, rtv_request); return; } // The writer publishes this marker last. A malformed published result stays rejected. @@ -173,9 +1104,8 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) // so it must not draw a translation whose stores it would silently skip (#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; + // LOCAL merge: upstream's early refusal of `uav ` lines (#2059) is not taken. Version-1 manifests in + // the local cache carry `uav` lines that the local parser below binds. } 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; @@ -186,12 +1116,49 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) else if (!std::strcmp(source, "d16unorm16") && x >= 0 && x < 32) ud.kind = Translation::d16_unorm16; else if (!std::strcmp(source, "descword3")) ud.kind = Translation::desc_word3; else if (!std::strcmp(source, "mrtbits") && !rtv_request.empty()) ud.kind = Translation::mrt_bits; + else if (!std::strcmp(source, "bufword3")) ud.kind = Translation::buf_word3; // word 3 of srv a's descriptor + else if (!std::strcmp(source, "uavword3")) ud.kind = Translation::uav_word3; // word 3 of uav a's descriptor + else if (!std::strcmp(source, "uavstride") && x >= 0 && x < 8) ud.kind = Translation::uav_stride; // LOCAL pstrans: uav a's record stride + else if (!std::strcmp(source, "uavbase") && x >= 0 && x < 8) { + ud.kind = Translation::uav_base; + tr.uav_base_wanted |= 1u << x; + } else if (!std::strcmp(source, "descword")) { + // LOCAL ind-meshps: a table descriptor word read as a number (mesh2hlsl X2W_MESH_FEATURES=descword). Off unless + // X2W_MESH_DESCWORD=1: the translation is then refused (its shader reads an entry value nobody would set). + static const bool descword_on = x2w_local::env_on("X2W_MESH_DESCWORD"); + if (!descword_on || x < 0 || x >= 16 || y < 0) { + static LONG logged; + if (first_calls(logged, 8)) + log("x2w-draw %016llx: `udsrc %d descword %d %d` %s: translation refused", tr.key, i, x, y, + descword_on ? "out of range" : "needs X2W_MESH_DESCWORD=1"); + return; + } + ud.kind = Translation::desc_word; + } if (static_cast<std::size_t>(i) == tr.uds.size() && ud.kind >= 0) tr.uds.push_back(ud); + } else if (std::sscanf(line.c_str(), "uav %d %15s %15s %d %d", &i, kind, source, &x, &y) >= 4) { + // LOCAL draw-rt: an unsupported uav line rejects the translation (its shader would not match the root signature). + int uav_kind = -1; + constexpr const char* kinds[] = {"buf", "tex2d", "tex2d3", "tex2dumin", "tex2dmax64", "tex2dor", "buf16x4"}; + for (int k = 0; k < static_cast<int>(std::size(kinds)); ++k) + if (!std::strcmp(kind, kinds[k]) && (k == uav_raw || !std::strcmp(source, "table"))) uav_kind = k; + const int uav_source = !std::strcmp(source, "table") ? 0 : !std::strcmp(source, "root") ? 2 : -1; + if (uav_kind >= 2 && (x < 0 || x >= 16 || y < 0 || y % 32 != 0 || + std::sscanf(line.c_str(), "uav %d %15s %15s %d %d", &i, kind, source, &x, &y) != 5)) return; + if (uav_kind < 0 || uav_source < 0 || static_cast<std::size_t>(i) != tr.uavs.size() || tr.uavs.size() >= 8) { + log("x2w-draw-rt %016llx: unsupported manifest line \"%s\"", tr.key, line.c_str()); + return; + } + tr.uavs.push_back({uav_kind, uav_source, x, y}); } else if (std::sscanf(line.c_str(), "srv %d %15s %15s %d %d", &i, kind, source, &x, &y) >= 4) { const int texture_kind = !std::strcmp(kind, "tex2d") ? 1 : !std::strcmp(kind, "tex2da") ? 2 : !std::strcmp(kind, "tex3d") ? 3 : !std::strcmp(kind, "tex1d") ? 4 : 0; Translation::Srv srv{texture_kind, !std::strcmp(source, "vb") ? 1 : !std::strcmp(source, "root") ? 2 : 0, x, y}; if (static_cast<std::size_t>(i) == tr.srvs.size()) tr.srvs.push_back(srv); + } else if (line == "heap 1") { + tr.heap = true; // LOCAL draw-rt: resource-heap (bindless) descriptors + } else if (line == "heapwords 1") { + tr.heapwords = true; // LOCAL meshrt: the heap descriptors' gfx10 words (vdesc, d3d12_vdesc.inl) } else if (line.compare(0, 6, "wmask ") == 0) { if (!tr.write_masks.read_manifest_line(line)) { log("x2w-draw invalid write mask manifest line for %016llx: %s", tr.key, line.c_str()); @@ -217,36 +1184,67 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) log("x2w-draw RTV manifest missing for %016llx", tr.key); return; } - if (tr.uds.empty() || tr.uds.size() > 32 || tr.srvs.size() > 32 || !tr.d16_srvs.valid_for_srvs(tr.srvs)) return; + if (tr.uds.empty() || tr.uds.size() > 32 || tr.srvs.size() > draw_srv_limit || !tr.d16_srvs.valid_for_srvs(tr.srvs)) return; for (const Translation::Ud& ud : tr.uds) { if (ud.kind == Translation::d16_unorm16 && (ud.a < 0 || static_cast<std::size_t>(ud.a) >= tr.srvs.size() || !tr.d16_srvs.requires_exact(static_cast<unsigned>(ud.a)))) return; } - if (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs))) return; - if (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps))) return; - const HRESULT hr = x2w_startup::create_translated_root(device_of(the_device), static_cast<UINT>(tr.uds.size()), - static_cast<UINT>(tr.srvs.size()), tr.samplers, &tr.root); + if (tr.heapwords && !tr.heap) return log("x2w-vdesc %016llx: `heapwords 1` without `heap 1`: translation refused", tr.key); // LOCAL meshrt + // LOCAL draw-rt off switch (X2W_DRAW_RT_OFF=1): translations that use these features stay unavailable. + static const bool rt_off = x2w_local::env_on("X2W_DRAW_RT_OFF"); + if (rt_off && (!tr.uavs.empty() || tr.heap || std::any_of(tr.uds.begin(), tr.uds.end(), [](const Translation::Ud& ud) { + return ud.kind == Translation::buf_word3 || ud.kind == Translation::uav_word3 || ud.kind == Translation::uav_base || + ud.kind == Translation::uav_stride; }))) { + log("x2w-draw-rt %016llx: not used (X2W_DRAW_RT_OFF)", tr.key); + return; + } + const int mesh_stage = load_mesh_stages(tr, manifest); // LOCAL meshrt: 1 `stage mesh` (.ms.cso, optional .ps.cso), -1 failed, 0 not mesh + if (mesh_stage < 0 || (!mesh_stage && (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs))))) return; + if (!mesh_stage && (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps)))) return; + const HRESULT hr = create_draw_root(tr); if (FAILED(hr)) { log("x2w-draw root signature for %016llx failed 0x%08lx", tr.key, static_cast<unsigned long>(hr)); return; } tr.state = 1; + if (std::any_of(tr.uds.begin(), tr.uds.end(), [](const Translation::Ud& ud) { return ud.kind == Translation::buf_word3; })) + InterlockedIncrement(&rt_loaded_word3); + if (!tr.uavs.empty()) { + InterlockedIncrement(&rt_loaded_uav); + log("x2w-draw-rt pipeline %016llx: %zu uavs in root parameter %u", tr.key, tr.uavs.size(), tr.uav_parameter); + } + if (tr.heap) { + InterlockedIncrement(&rt_loaded_heap); + log("x2w-draw-rt pipeline %016llx: heap 1 in root parameters %u..%u", tr.key, tr.heap_parameter, tr.heap_parameter + 2); + if (tr.heapwords) log("x2w-vdesc pipeline %016llx: heapwords 1, vdesc in root parameter %u", tr.key, tr.vdesc_parameter); // LOCAL meshrt + } 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); } -// draw_lock held. Both pipeline forms use the same request writer and shader cache. -Translation* cached_translation(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes, - const std::vector<unsigned char>& root_blob, const std::string& layout = {}) +u64 pipeline_key(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes, + const std::vector<unsigned char>& root_blob) { // 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"; + // LOCAL (local merge): the revision stays x2w-startup-shader-3, the value before the upstream merge, so the + // published shader cache keeps resolving. Upstream moved it to 4..8 to drop its own older translator output + // (FMA rounding, A16 coordinates, slot-86 attribute linking, export write masks). None of those changes the + // root layout, bindings or manifest lines an existing entry is loaded with: a manifest without 'wmask' lines + // keeps the full write mask, as before. docs/experiments.md "Shader cache revision (local merge)". + constexpr char revision[] = "x2w-startup-shader-3"; 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))); + return fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); +} + +// draw_lock held. Both pipeline forms use the same request writer and shader cache. +Translation* cached_translation(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes, + const std::vector<unsigned char>& root_blob, const std::string& layout = {}) +{ + u64 key = pipeline_key(a, a_bytes, b, b_bytes, root_blob); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. if (!layout.empty()) key = fnv_bytes(layout.data(), layout.size(), key); auto& entry = translation_by_key()[key]; @@ -364,7 +1362,7 @@ void publish_compute_request(const void* desc) std::vector<unsigned char> fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-17cs"; // tools/startup/gfx2hlsl.py compute_key + constexpr char compute_revision[] = "x2w-startup-shader-3cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector<unsigned char>* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); @@ -427,7 +1425,7 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector<RootParameter>* 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-1"; const u64 key = fnv_part(root_blob, fnv_part(pixel, fnv_part(mesh, fnv_bytes(revision, sizeof(revision) - 1)))); static SRWLOCK request_lock = SRWLOCK_INIT; static std::unordered_set<u64> written; @@ -541,8 +1539,13 @@ Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3 if (bounds) return nullptr; } } else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT) { + // LOCAL (local merge): upstream folds a non-empty layout into the request key and publishes it as .ia. + // That changes the key of an existing stream request, so it waits behind X2W_UPSTREAM_STREAM_LAYOUT; + // without it the request carries no layout, as before the merge, and gfx2hlsl refuses a vertex shader + // that calls the fetch routine. + static const bool upstream_layout = x2w_local::env_on("X2W_UPSTREAM_STREAM_LAYOUT"); // Unreadable: translate without it; gfx2hlsl refuses a vertex shader that needs it. - if (!stream_input_layout(stream + at, layout)) { + if (upstream_layout && !stream_input_layout(stream + at, layout)) { layout.clear(); log("x2w-draw stream input layout unreadable; requesting the translation without it"); } @@ -576,13 +1579,64 @@ Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3 if (found != root_blobs().end()) root_blob = found->second; ReleaseSRWLockShared(¬e_lock); if (root_blob.empty()) return nullptr; - AcquireSRWLockExclusive(&draw_lock); + lock_draw(100000 + __LINE__); auto* result = cached_translation(stages[0].pShaderBytecode, stages[0].BytecodeLength, stages[1].pShaderBytecode, stages[1].BytecodeLength, root_blob, layout); ReleaseSRWLockExclusive(&draw_lock); return result; } +// LOCAL (renderstate): fixed-function state of the slot 57 base (pipeline_state_decode.h), decoded once +// per title pipeline; read_words picks the vertex or the mesh layout (A+0x004 == 6) itself. Counted and, +// for the first 16, logged; applied only by apply_draw_state under the switches. +void decode_draw_state(BoundPipeline& bound, Wrapper* pipeline, const PipelineInfo* info) +{ + using namespace x2w_pipeline_state; + Words words; + if (!info || info->path != 57 || !read_words(info->state_a.data(), info->state_a.size(), words)) return; + bound.has_words = true; + bound.mesh_layout = words.mesh; + bound.ds = decode_depth_stencil(words.depth, words.stencil, words.refmask, words.refmask_bf); + bound.rs = decode_rasterizer(words.mode, words.clip, words.bias_clamp, words.bias_scale, words.bias_offset, draw_state::switches().flip); + bound.raw_mode = words.mode; // LOCAL meshrt + bound.raw_clip = words.clip; + bound.masked_blend = decode_blend(words.blend, words.target_mask, words.shader_mask, true, false); + const D3D12_DEPTH_STENCIL_DESC& d = bound.derived_ds ? bound.patch_ds : bound.ds.desc; + const bool ds_known = bound.derived_ds || bound.ds.ok; + draw_state::add(draw_state::decoded); + if (words.mesh) draw_state::add(draw_state::decoded_mesh); + if (ds_known) + draw_state::add(!d.DepthEnable ? draw_state::class_depth_off : d.DepthWriteMask ? draw_state::class_depth_write : draw_state::class_depth_read); + if (ds_known && d.StencilEnable) draw_state::add(draw_state::class_stencil); + if (bound.rs.ok && bound.rs.desc.CullMode != D3D12_CULL_MODE_NONE) draw_state::add(draw_state::class_cull); + if (bound.masked_blend.ok && bound.masked_blend.desc.RenderTarget[0].BlendEnable) draw_state::add(draw_state::class_blend); + if (bound.masked_blend.masked_targets) draw_state::add(draw_state::class_masked); + if (bound.masked_blend.dual_source) draw_state::add(draw_state::class_dual); + if (!bound.ds.ok) draw_state::add(draw_state::refused_depth); + if (!bound.rs.ok) draw_state::add(draw_state::refused_raster); + if (!bound.masked_blend.ok) draw_state::add(draw_state::refused_blend); + if (bound.ds.depth_bounds) draw_state::add(draw_state::depth_bounds_ignored); + if (bound.ds.masks_differ) draw_state::add(draw_state::stencil_masks_differ); + if (bound.rs.clip_split) draw_state::add(draw_state::clip_split); + if (bound.rs.bias_rounded) draw_state::add(draw_state::bias_rounded); + static LONG logged_state; + if (first_calls(logged_state, 16)) { + const auto& r = bound.rs.desc; + char derived_rs[96] = ""; + if (bound.derived_rs) // the slot 55 rasterizer part replaces the register state under _CULL + std::snprintf(derived_rs, sizeof(derived_rs), " (derived part wins: fill %d cull %d ccw %d clip %d)", bound.patch_rs.FillMode, + bound.patch_rs.CullMode, bound.patch_rs.FrontCounterClockwise, bound.patch_rs.DepthClipEnable); + log("x2w-draw-state pipeline %p%s: DB_DEPTH_CONTROL %08x STENCIL %08x REFMASK %08x/%08x -> %s depth %d write %d func %d " + "stencil %d%s; MODE %08x CLIP %08x bias %g/%g/%g -> %s cull %d ccw %d bias %d/%g/%g clip %d%s; masks %08x & %08x -> " + "rt0 0x%x%s%s", static_cast<void*>(pipeline), words.mesh ? " (mesh layout)" : "", words.depth, words.stencil, words.refmask, + words.refmask_bf, bound.ds.ok ? "ok" : bound.ds.reason, d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, + bound.derived_ds ? " (derived part)" : "", words.mode, words.clip, words.bias_clamp, words.bias_scale, words.bias_offset, + bound.rs.ok ? "ok" : bound.rs.reason, r.CullMode, r.FrontCounterClockwise, r.DepthBias, r.DepthBiasClamp, r.SlopeScaledDepthBias, + r.DepthClipEnable, derived_rs, words.target_mask, words.shader_mask, bound.masked_blend.desc.RenderTarget[0].RenderTargetWriteMask, + bound.masked_blend.dual_source ? " dual-source" : "", bound.masked_blend.ok ? "" : " (blend refused)"); + } +} + // draw_lock held. BoundPipeline* translation_for(Wrapper* pipeline) { @@ -604,8 +1658,21 @@ BoundPipeline* translation_for(Wrapper* pipeline) from = "derived blend patch"; bound->has_blend = true; } + // LOCAL (renderstate): the nearest derivation's depth-stencil / rasterizer part wins, as for blend. + using namespace x2w_pipeline_state; + const unsigned char* records = info->desc.data(); + const std::size_t record_bytes = info->desc.size(); + if (!bound->derived_ds && last_part(records, record_bytes, part_depth_stencil) != SIZE_MAX) { + bound->derived_ds = derived_depth_stencil(records, record_bytes, bound->patch_ds); + draw_state::add(bound->derived_ds ? draw_state::derived_ds : draw_state::derived_invalid); + } + if (!bound->derived_rs && last_part(records, record_bytes, part_rasterizer) != SIZE_MAX) { + bound->derived_rs = derived_rasterizer(records, record_bytes, bound->patch_rs); + draw_state::add(bound->derived_rs ? draw_state::derived_rs : draw_state::derived_invalid); + } info = pipeline_info(info->base); } + bound->blend_overridden = bound->has_blend || (info && info->has_stream_blend); if (!bound->has_blend && info && info->has_stream_blend) { from = "stream blend subobject"; bound->blend = info->stream_blend; @@ -617,6 +1684,7 @@ BoundPipeline* translation_for(Wrapper* pipeline) } else if (!bound->has_blend && info && find_blend(info->state_a, &bound->blend, &where)) from = "state block A"; else if (!bound->has_blend && info && find_blend(info->state_b, &bound->blend, &where)) from = "state block B"; bound->has_blend = from[0] != 'n'; + decode_draw_state(*bound, pipeline, info); // LOCAL (renderstate) static LONG logged; if (first_calls(logged, 24)) { const auto& t = bound->blend.RenderTarget[0]; @@ -760,8 +1828,10 @@ bool needs_rtv_variant(DXGI_FORMAT format) Translation* translation_for_targets(Translation* base, const Pass& pass) { if (!base) return nullptr; - if (std::none_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant)) { - if (base->retry_manifest_at && GetTickCount64() >= base->retry_manifest_at) + // LOCAL meshrt: a depth-only mesh pipeline (no pixel stage) writes no target, so any target format takes the base. + const bool no_pixel_output = base->state == 1 && base->ms && !base->ps; + if (no_pixel_output || std::none_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant)) { + if (manifest_retry_due(*base)) load_translation(*base); return base; } @@ -778,20 +1848,299 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) publish_shader_request(key, L".rtv", request.data(), request.size()); log("x2w-draw no RTV translation for %016llx (%s)", key, request.c_str()); } - } else if (entry->retry_manifest_at && GetTickCount64() >= entry->retry_manifest_at) { + } else if (manifest_retry_due(*entry)) { load_translation(*entry, request); } return entry; } +// LOCAL (renderstate): the X2W_DRAW_STATE_* groups over the state a caller built before them (its +// BlendState / DepthStencilState / RasterizerState; desc.DSVFormat must already be the draw's format). +// All groups off (the default) leaves desc untouched and returns false. Returns whether anything +// changed; per-draw adjustments are counted on every call. Also for mesh PSOs (d3d12_mesh.inl): +// BoundPipeline's decode already read the mesh layout of state block A. s: which groups apply; the +// vertex draw path passes draw_state::switches(), a mesh caller may pass its own. +bool apply_draw_state(const BoundPipeline& bound, const Pass& pass, D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, + const x2w_pipeline_state::Switches& s) +{ + using namespace x2w_pipeline_state; + const DXGI_FORMAT dsv_format = desc.DSVFormat; + bool changed = false; + if (s.blend && bound.has_words && !bound.blend_overridden && bound.masked_blend.ok) { + desc.BlendState = bound.masked_blend.desc; + if (bound.masked_blend.dual_source) { + // D3D12 blends two colours only into target 0; the words are the same for every target then. + desc.BlendState.IndependentBlendEnable = FALSE; + if (pass.target_count > 1) draw_state::add(draw_state::dual_multi_target); + } + changed = true; + } + if (s.depth && !bound.has_depth_stencil && (bound.derived_ds || (bound.has_words && bound.ds.ok))) { + D3D12_DEPTH_STENCIL_DESC d = bound.derived_ds ? bound.patch_ds : bound.ds.desc; + // A depth target no forwarded slot 51 clear has initialised holds undefined depth: no test against it + // (unless X2W_DRAW_STATE_DEPTH_UNCLEARED=1); the draw keeps depth and stencil off, as before. + const bool target = dsv_format != DXGI_FORMAT_UNKNOWN; + const bool uncleared = target && !s.uncleared && !depth_target_cleared(pass.dsv_resource); + if (uncleared && (d.DepthEnable || d.StencilEnable)) draw_state::add(draw_state::draws_depth_uncleared); + const unsigned adjusted = adjust_for_target(d, target && !uncleared, format_has_stencil(dsv_format), pass.dsv_read_only); + if (pass.read_depth_plane) d.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + if (pass.read_stencil_plane) d.StencilWriteMask = 0; + if ((adjusted & adjust_no_target) && !uncleared) draw_state::add(draw_state::draws_depth_no_target); + if (adjusted & adjust_no_stencil) draw_state::add(draw_state::draws_stencil_no_plane); + if (adjusted & adjust_read_only) draw_state::add(draw_state::draws_read_only); + desc.DepthStencilState = d; + changed = true; + } + if (s.cull && (bound.derived_rs || (bound.has_words && bound.rs.ok))) { + D3D12_RASTERIZER_DESC r = bound.derived_rs ? bound.patch_rs : bound.rs.desc; + if (bound.derived_rs && s.flip) r.FrontCounterClockwise = !r.FrontCounterClockwise; + if (r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF) { + r.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; // tier not checked + draw_state::add(draw_state::conservative_dropped); + } + r.MultisampleEnable = FALSE; // single-sample targets only (desc.SampleDesc.Count = 1) + r.ForcedSampleCount = 0; + // A rectangle list is drawn as two triangles per rectangle; the console rasterizes it as a + // rectangle, which is taken as never culled (assumed). + if (pass.topology == 0x11 && r.CullMode != D3D12_CULL_MODE_NONE) { + r.CullMode = D3D12_CULL_MODE_NONE; + draw_state::add(draw_state::draws_rect_cull_off); + } + desc.RasterizerState = r; + changed = true; + } else if (s.depthclip && (bound.derived_rs || (bound.has_words && bound.rs.ok))) { + // LOCAL meshrt X2W_DRAW_STATE_DEPTHCLIP=1: only the decoded depth clip (shadow passes turn it off), the rest + // of the rasterizer stays as it was. + const BOOL clip = (bound.derived_rs ? bound.patch_rs : bound.rs.desc).DepthClipEnable ? TRUE : FALSE; + if (desc.RasterizerState.DepthClipEnable != clip) { + desc.RasterizerState.DepthClipEnable = clip; + changed = true; + } + } + return changed; +} + +// LOCAL (renderstate): creation of a desc with decoded state failed (first): create the state of before +// instead, count and log. Returns the final result; pipeline is the created one or null. +HRESULT draw_state_fallback(u64 translation, HRESULT first, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& decoded, + const D3D12_GRAPHICS_PIPELINE_STATE_DESC& fallback, ID3D12PipelineState*& pipeline) +{ + if (SUCCEEDED(first)) { + draw_state::add(draw_state::pso_new); + return first; + } + pipeline = nullptr; + const HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&fallback, IID_PPV_ARGS(&pipeline)); + draw_state::add(SUCCEEDED(hr) ? draw_state::pso_failed_fallback : draw_state::pso_failed_both); + static LONG logged_failure; + if (first_calls(logged_failure, 16)) { + const auto& b = decoded.BlendState.RenderTarget[0]; + const auto& d = decoded.DepthStencilState; + const auto& r = decoded.RasterizerState; + log("x2w-draw-state decoded state refused for %016llx (0x%08lx): blend rt0 %d/%d/%d mask 0x%x independent %d, depth %d write %d " + "func %d stencil %d, cull %d ccw %d bias %d/%g/%g clip %d; old state -> 0x%08lx", translation, static_cast<unsigned long>(first), + b.BlendEnable, b.SrcBlend, b.DestBlend, b.RenderTargetWriteMask, decoded.BlendState.IndependentBlendEnable, d.DepthEnable, + d.DepthWriteMask, d.DepthFunc, d.StencilEnable, r.CullMode, r.FrontCounterClockwise, r.DepthBias, r.DepthBiasClamp, + r.SlopeScaledDepthBias, r.DepthClipEnable, static_cast<unsigned long>(hr)); + } + return hr; +} + +// LOCAL stall: a desktop graphics pipeline compiled outside draw_lock. CreateGraphicsPipelineState runs +// the driver's shader compiler (seconds for a large shader on a cold driver cache); under draw_lock it +// stalled every recording thread behind one compile. On a miss pipeline_for fills a PsoBuild and returns +// nullptr; draw_translated drops draw_lock, build_pipeline compiles (one compile per (pipeline, key), +// other threads wanting the same one wait for it), then draw_translated takes draw_lock again and +// pipeline_for installs the result. X2W_DRAW_PSO_LOCKED=1 restores the compile under draw_lock. +struct PsoBuild { + BoundPipeline* bound = nullptr; // never freed (translation_by_pipeline keeps them) + u64 key = 0; // pipeline_for's key in bound->pipelines + u64 translation = 0; // for the log + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; // points at the translation's blobs and root signature, which are never freed + // LOCAL (renderstate): desc carries decoded X2W_DRAW_STATE_* state; when its creation fails, fallback + // (the state of before) is created instead. + bool has_fallback = false; + D3D12_GRAPHICS_PIPELINE_STATE_DESC fallback{}; +}; +struct PsoSlot { + int state = 0; // 1 compiling, 2 done, 3 queued for an X2W_DRAW_ASYNC worker + ID3D12PipelineState* pipeline = nullptr; +}; +SRWLOCK pso_build_lock = SRWLOCK_INIT; // inside draw_lock when both are held +CONDITION_VARIABLE pso_built = CONDITION_VARIABLE_INIT; +// Slots are never erased: a thread that missed before another installed the pipeline finds it done. +std::map<std::pair<const BoundPipeline*, u64>, PsoSlot>& pso_slots() +{ + static std::map<std::pair<const BoundPipeline*, u64>, PsoSlot> m; + return m; +} + +// LOCAL stall, fixtures only: X2W_CX_TEST_HOLD_EVENT=<name> holds every translated compute load and every +// translated draw pipeline compile until the named event is set (at most 20 s). +void test_hold(const char* what, u64 key) +{ + wchar_t hold[128]; + const DWORD n = GetEnvironmentVariableW(L"X2W_CX_TEST_HOLD_EVENT", hold, 128); + if (!n || n >= 128) return; + if (const HANDLE event = OpenEventW(SYNCHRONIZE, FALSE, hold)) { + const DWORD waited = WaitForSingleObject(event, 20000); + CloseHandle(event); + log("%s %016llx: load held by X2W_CX_TEST_HOLD_EVENT (%s)", what, key, waited == WAIT_OBJECT_0 ? "released" : "timed out"); + } +} + +// LOCAL stall: X2W_DRAW_ASYNC=1 (also on with X2W_CX_ASYNC=1 unless X2W_DRAW_ASYNC_OFF=1). A draw whose desktop +// pipeline is not built yet queues the build for two below-normal workers and is skipped ("pipeline compiling"), +// so the recording thread never compiles and never waits for a compile. A skipped draw is dropped, not replayed. +// Slot state 3 = queued for a worker; a thread without the switch that finds it claims it and compiles itself. +bool draw_async() +{ + static const bool on = !x2w_local::env_on("X2W_DRAW_PSO_LOCKED") && + (x2w_local::env_on("X2W_DRAW_ASYNC") || (x2w_local::env_on("X2W_CX_ASYNC") && !x2w_local::env_on("X2W_DRAW_ASYNC_OFF"))); + return on; +} +struct DrawAsync { + LONG skipped = 0, since_report = 0; +}; +std::unordered_map<u64, DrawAsync>& draw_async_keys() // pso_build_lock; by translation key +{ + static std::unordered_map<u64, DrawAsync> m; + return m; +} // The depth format a translated draw uses: the pass's own view, else the one the pipeline was created with. inline DXGI_FORMAT pass_dsv_format(const BoundPipeline& bound, const Pass& pass) { return pass.dsv_format != DXGI_FORMAT_UNKNOWN ? pass.dsv_format : bound.dsv_format; } -ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const Pass& pass, bool indexed_rect) +std::deque<PsoBuild>& pso_queue() // pso_build_lock +{ + static std::deque<PsoBuild> q; + return q; +} +CONDITION_VARIABLE pso_wanted = CONDITION_VARIABLE_INIT; + +void compile_pso(const PsoBuild& build, PsoSlot& slot); +DWORD WINAPI pso_thread(void*) +{ + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + for (;;) { + AcquireSRWLockExclusive(&pso_build_lock); + while (pso_queue().empty()) SleepConditionVariableSRW(&pso_wanted, &pso_build_lock, INFINITE, 0); + const PsoBuild build = pso_queue().front(); + pso_queue().pop_front(); + PsoSlot& slot = pso_slots()[{build.bound, build.key}]; + const bool mine = slot.state == 3; // else another thread claimed it + if (mine) slot.state = 1; + ReleaseSRWLockExclusive(&pso_build_lock); + if (mine) compile_pso(build, slot); + } +} +// draw_translated without draw_lock: queues `build` unless it is queued, compiling or built; counts the skip. +void queue_pso_build(const PsoBuild& build) +{ + static const bool started = [] { + for (int i = 0; i < 2; ++i) + if (const HANDLE t = CreateThread(nullptr, 0, pso_thread, nullptr, 0, nullptr)) CloseHandle(t); + log("x2w-draw X2W_DRAW_ASYNC: 2 pipeline build threads; a draw whose desktop pipeline is not built yet is skipped"); + return true; + }(); + (void)started; + AcquireSRWLockExclusive(&pso_build_lock); + PsoSlot& slot = pso_slots()[{build.bound, build.key}]; + const bool queue = slot.state == 0; + if (queue) { + slot.state = 3; + pso_queue().push_back(build); + } + DrawAsync& a = draw_async_keys()[build.translation]; + const bool first = !a.skipped; + ++a.skipped, ++a.since_report; + ReleaseSRWLockExclusive(&pso_build_lock); + if (queue) WakeConditionVariable(&pso_wanted); + static LONG logged; + if (first && first_calls(logged, 32)) + log("x2w-draw %016llx: desktop pipeline not built yet, draw skipped and the build queued (X2W_DRAW_ASYNC)", build.translation); +} +// Heartbeat: draws skipped while their pipeline compiled, since the last report, per translation key. +void report_draw_async() +{ + if (!draw_async()) return; + std::vector<std::pair<u64, LONG>> keys; + LONG total = 0, all_time = 0; + AcquireSRWLockExclusive(&pso_build_lock); + for (auto& entry : draw_async_keys()) { + all_time += entry.second.skipped; + if (!entry.second.since_report) continue; + keys.push_back({entry.first, entry.second.since_report}); + total += entry.second.since_report; + entry.second.since_report = 0; + } + const std::size_t waiting = pso_queue().size(); + ReleaseSRWLockExclusive(&pso_build_lock); + if (!total) return; + std::sort(keys.begin(), keys.end(), [](const auto& a, const auto& b) { return a.second > b.second; }); + char line[1400]; + int n = std::snprintf(line, sizeof(line), "x2w-draw draws skipped while compiling since the last report (X2W_DRAW_ASYNC): %ld over %zu keys " + "(%ld this run; %zu builds waiting):", total, keys.size(), all_time, waiting); + for (const auto& k : keys) { + if (n > static_cast<int>(sizeof(line)) - 40) { + n += std::snprintf(line + n, sizeof(line) - n, " ..."); + break; + } + n += std::snprintf(line + n, sizeof(line) - n, " %016llx=%ld", k.first, k.second); + } + log("%s", line); +} + +void build_pipeline(const PsoBuild& build) +{ + AcquireSRWLockExclusive(&pso_build_lock); + PsoSlot& slot = pso_slots()[{build.bound, build.key}]; // std::map references stay valid + while (slot.state == 1) SleepConditionVariableSRW(&pso_built, &pso_build_lock, INFINITE, 0); + if (slot.state == 2) { + ReleaseSRWLockExclusive(&pso_build_lock); + return; + } + slot.state = 1; // from 0, or 3 (queued for a worker: claimed here) + ReleaseSRWLockExclusive(&pso_build_lock); + compile_pso(build, slot); +} +void compile_pso(const PsoBuild& build, PsoSlot& slot) +{ + test_hold("x2w-draw", build.translation); + LARGE_INTEGER start, end, frequency; + QueryPerformanceCounter(&start); + ID3D12PipelineState* pipeline = nullptr; + HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&build.desc, IID_PPV_ARGS(&pipeline)); + if (build.has_fallback) hr = draw_state_fallback(build.translation, hr, build.desc, build.fallback, pipeline); + QueryPerformanceCounter(&end); + QueryPerformanceFrequency(&frequency); + log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d%s), compiled in %lld ms outside draw_lock", + build.translation, build.desc.NumRenderTargets, build.desc.NumRenderTargets ? build.desc.RTVFormats[0] : 0, + static_cast<unsigned long>(hr), static_cast<int>(build.desc.DSVFormat), build.desc.DepthStencilState.DepthEnable ? 1 : 0, + build.has_fallback ? ", decoded state" : "", static_cast<long long>((end.QuadPart - start.QuadPart) * 1000 / frequency.QuadPart)); + check_device("translated CreateGraphicsPipelineState", 0); + AcquireSRWLockExclusive(&pso_build_lock); + slot.pipeline = pipeline; + slot.state = 2; + LONG skipped = 0; + if (draw_async()) + if (const auto found = draw_async_keys().find(build.translation); found != draw_async_keys().end()) skipped = found->second.skipped; + ReleaseSRWLockExclusive(&pso_build_lock); + WakeAllConditionVariable(&pso_built); + if (skipped) log("x2w-draw %016llx ready (X2W_DRAW_ASYNC); %ld draws skipped while compiling", build.translation, skipped); +} + +bool pipeline_desc(const BoundPipeline& bound, Translation& tr, const Pass& pass, DXGI_FORMAT dsv_format, + D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, bool indexed_rect = false); + +// draw_lock held. With `deferred`, a pipeline not built yet is described there and nullptr is returned. +// indexed_rect (upstream #2259): the draw is an indexed rectangle list, expanded by a geometry stage. +ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const Pass& pass, PsoBuild* deferred = nullptr, + bool indexed_rect = false) { + if (tr.ms) return mesh_pso_for(tr); // LOCAL meshrt: built off draw_lock by mesh_prepare; null outside a mesh call const DXGI_FORMAT dsv_format = pass_dsv_format(bound, pass); u64 key = pass.target_count; for (UINT i = 0; i < pass.target_count; ++i) key = key * 131 + static_cast<u64>(pass.target_formats[i]); @@ -801,9 +2150,68 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P if (use_depth_stencil) key = fnv_bytes(&bound.depth_stencil, sizeof(bound.depth_stencil), key); if (bound.has_rasterizer) key = fnv_bytes(&bound.rasterizer, sizeof(bound.rasterizer), key); key = fnv_bytes(&indexed_rect, sizeof(indexed_rect), key); + // LOCAL (renderstate): with an X2W_DRAW_STATE_* group on, the decoded state depends on the draw + // (depth target, topology), so the key also covers the three final state descriptions. With every + // group off, key and desc are what they were before. + D3D12_GRAPHICS_PIPELINE_STATE_DESC decoded{}; + bool changed = false; + const auto& state_switches = draw_state::switches(); + if (state_switches.depth || state_switches.cull || state_switches.blend || state_switches.depthclip) { + if (!pipeline_desc(bound, tr, pass, dsv_format, decoded, indexed_rect)) { + bound.pipelines[key] = nullptr; + return nullptr; + } + changed = apply_draw_state(bound, pass, decoded, state_switches); + if (changed) { + key = fnv_bytes(&decoded.BlendState, sizeof(decoded.BlendState), key); + key = fnv_bytes(&decoded.DepthStencilState, sizeof(decoded.DepthStencilState), key); + key = fnv_bytes(&decoded.RasterizerState, sizeof(decoded.RasterizerState), key); + } + } const auto found = bound.pipelines.find(key); if (found != bound.pipelines.end()) return found->second; + { + AcquireSRWLockShared(&pso_build_lock); + const auto built = pso_slots().find({&bound, key}); + const bool done = built != pso_slots().end() && built->second.state == 2; + ID3D12PipelineState* const ready = done ? built->second.pipeline : nullptr; + ReleaseSRWLockShared(&pso_build_lock); + if (done) { + bound.pipelines[key] = ready; + return ready; + } + } D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + if (!pipeline_desc(bound, tr, pass, dsv_format, desc, indexed_rect)) { + bound.pipelines[key] = nullptr; + return nullptr; + } + if (deferred) { + deferred->bound = &bound; + deferred->key = key; + deferred->translation = tr.key; + deferred->desc = changed ? decoded : desc; + deferred->has_fallback = changed; + if (changed) deferred->fallback = desc; + return nullptr; + } + ID3D12PipelineState* pipeline = nullptr; + HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(changed ? &decoded : &desc, IID_PPV_ARGS(&pipeline)); + if (changed) hr = draw_state_fallback(tr.key, hr, decoded, desc, pipeline); + log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d%s)", tr.key, + pass.target_count, pass.target_count ? pass.target_formats[0] : 0, static_cast<unsigned long>(hr), + static_cast<int>(dsv_format), (changed ? decoded : desc).DepthStencilState.DepthEnable ? 1 : 0, changed ? ", decoded state" : ""); + check_device("translated CreateGraphicsPipelineState", 0); + bound.pipelines[key] = pipeline; + return pipeline; +} + +// The desktop PSO description of a translated (vertex) draw with the state of before: blend found in the +// state block, depth-stencil from a stream PSO, no culling. +bool pipeline_desc(const BoundPipeline& bound, Translation& tr, const Pass& pass, DXGI_FORMAT dsv_format, + D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, bool indexed_rect) +{ + desc = {}; desc.pRootSignature = tr.root; desc.VS = {tr.vs->GetBufferPointer(), tr.vs->GetBufferSize()}; desc.PS = {tr.ps->GetBufferPointer(), tr.ps->GetBufferSize()}; @@ -816,7 +2224,7 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P log("x2w-draw %016llx: indexed rectangle geometry unavailable (0x%08lx) %s", tr.key, static_cast<unsigned long>(hr), errors ? static_cast<const char*>(errors->GetBufferPointer()) : ""); } - if (!tr.indexed_rect_geometry) return nullptr; + if (!tr.indexed_rect_geometry) return false; desc.GS = {tr.indexed_rect_geometry->GetBufferPointer(), tr.indexed_rect_geometry->GetBufferSize()}; } // Blend state as found in the pipeline's state block, else opaque. Depth-stencil state and @@ -826,12 +2234,21 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P target = {FALSE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; if (bound.has_blend) desc.BlendState = bound.blend; + // LOCAL EXPERIMENT (X2W_DRAW_DEFAULT_BLEND=1): when no blend description was found, blend + // source alpha over the target. Draws that output alpha 1 look the same; coverage-alpha draws + // (atlas glyphs) need it. The real fix decodes the console blend registers. + static const bool default_blend = x2w_local::env_on("X2W_DRAW_DEFAULT_BLEND"); + if (!bound.has_blend && default_blend) + for (auto& target : desc.BlendState.RenderTarget) + target = {TRUE, FALSE, D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, + D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; // Channels the translated exports leave unwritten stay out of the write mask (#1674). if (!x2w_startup::apply_export_write_masks(desc.BlendState, tr.write_masks, pass.target_count)) { log("x2w-draw export write masks incompatible with shared logic op for %016llx", tr.key); - bound.pipelines[key] = nullptr; - return nullptr; + return false; } + // A state decoded from registers needs a depth view to act on; with none bound the pass keeps the desktop default. + const bool use_depth_stencil = bound.has_depth_stencil && (!bound.depth_from_registers || dsv_format != DXGI_FORMAT_UNKNOWN); if (use_depth_stencil) desc.DepthStencilState = bound.depth_stencil; desc.SampleMask = ~0u; if (bound.has_rasterizer) { @@ -846,15 +2263,7 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P for (UINT i = 0; i < pass.target_count; ++i) desc.RTVFormats[i] = pass.target_formats[i]; desc.DSVFormat = dsv_format; desc.SampleDesc.Count = 1; - ID3D12PipelineState* pipeline = nullptr; - X2W_ZONE("desktop pipeline creation"); - const HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); - log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d)", tr.key, - pass.target_count, pass.target_count ? pass.target_formats[0] : 0, static_cast<unsigned long>(hr), - static_cast<int>(dsv_format), desc.DepthStencilState.DepthEnable ? 1 : 0); - check_device("translated CreateGraphicsPipelineState", 0); - bound.pipelines[key] = pipeline; - return pipeline; + return true; } // Private shader-visible heap for the translated draws' tables, used as a ring. @@ -870,7 +2279,12 @@ bool ensure_draw_heap(Wrapper* device) // startup render device. A list from another device cannot use this heap. if (!device || device != the_device) return false; if (draw_heap) return device == draw_heap_device; - const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, draw_heap_size, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + // LOCAL: the ring is [0, draw_heap_size); after it, the view-id region of translated compute (d3d12_compute.inl), then + // the raw-window views of `heapraw 1` and its page-record view (d3d12_heap_raw.inl; gfx10_raw_vdesc.h). + static_assert(x2w_startup::heap_raw_window_first == draw_heap_size + 8 + 8 * 90000); + static_assert(x2w_startup::heap_raw_pages_view == x2w_startup::heap_raw_window_first + x2w_startup::heap_raw_windows_max); + const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, x2w_startup::heap_raw_pages_view + 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; if (FAILED(device_of(the_device)->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&draw_heap)))) return false; draw_heap_device = device; draw_heap_increment = device_of(the_device)->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); @@ -889,7 +2303,7 @@ std::vector<SubmittedDrawSamplerHeaps> submitted_draw_sampler_heaps; void discard_draw_sampler_heaps(ID3D12CommandList* list) { - AcquireSRWLockExclusive(&draw_lock); + lock_draw(100000 + __LINE__); recorded_draw_sampler_heaps.erase(list); ReleaseSRWLockExclusive(&draw_lock); } @@ -924,6 +2338,7 @@ void retire_draw_sampler_heaps(ID3D12CommandQueue* queue, const std::vector<ID3D } struct TextureUpload { + UINT resident_first = UINT_MAX; u64 hash = 0, generation = ~0ull; LONG checked_frame = -1000; bool done = false, tiled = false; @@ -1090,13 +2505,102 @@ bool prepare_draw_sampler_heap(Pass& pass, ID3D12GraphicsCommandList* list, bool struct FrameCopy { u64 address = 0; u64 offset = 0; - std::vector<unsigned char> content; + ID3D12Resource* buffer = nullptr; // LOCAL memcut: the upload ring chunk, valid while ring_touch(tag) says so + RingTag tag; + // LOCAL stall: shared so that X2W_DRAW_LOCK_SPLIT's frame_copy_unlocked can compare against it after draw_lock + // is released (a later clear or insert_or_assign drops the map's reference, not the comparing thread's). + std::shared_ptr<const std::vector<unsigned char>> content; }; std::unordered_map<u64, FrameCopy>& frame_copies() { static std::unordered_map<u64, FrameCopy> m; return m; } LONG frame_copies_frame = -1; +// LOCAL stall: what draw_translated's buffer srvs cost, per class (0 other callers, 1 plain draw srv, 2 mesh srv): +// bytes memcmp'd on a frame_copy hit, bytes copied on a miss (twice: snapshot + ring), bytes bound in place by +// X2W_DRAW_SRV_IN_PLACE. Reported every 5 s when X2W_DRAW_SRV_STATS=1 or X2W_DRAW_SRV_IN_PLACE is set. +enum { srvc_compared, srvc_copied, srvc_in_place, srvc_kinds }; +volatile LONG64 srvc_bytes[4][srvc_kinds], srvc_calls[4][srvc_kinds]; // LOCAL (textures): class 3 = a table entry holding a V# (title-written or X2W_BUFFER_HEAP_INDEX) +// Over the threshold but copied as before: [class][0] no single desktop window (desktop_range), [1] not 16-aligned. +volatile LONG64 srvc_in_place_missed[4][2]; +thread_local int frame_copy_class; +void srvc_note(int cls, int kind, std::size_t bytes) +{ + InterlockedAdd64(&srvc_bytes[cls][kind], static_cast<LONG64>(bytes)); + InterlockedIncrement64(&srvc_calls[cls][kind]); +} +// X2W_DRAW_SRV_IN_PLACE=<min bytes> (off by default; 0 or unset = off). +std::size_t srv_in_place_min() +{ + static const std::size_t min = [] { + char value[24]{}; + const DWORD n = GetEnvironmentVariableA("X2W_DRAW_SRV_IN_PLACE", value, sizeof(value)); + return n && n < sizeof(value) ? static_cast<std::size_t>(std::strtoull(value, nullptr, 0)) : std::size_t{0}; + }(); + return min; +} +// Positive byte threshold for comparing direct-draw snapshots outside draw_lock (opt-in). +std::size_t draw_copy_split_min() +{ + static const std::size_t min = [] { + char mode[16]{}; + GetEnvironmentVariableA("X2W_UPLOAD_RING", mode, sizeof(mode)); + if (!std::strcmp(mode, "legacy") || ring_env("X2W_UPLOAD_RING_TEST_NO_REPIN", 0)) return std::size_t{0}; + char value[24]{}; + const DWORD n = GetEnvironmentVariableA("X2W_DRAW_COPY_SPLIT_MIN", value, sizeof(value)); + return n && n < sizeof(value) ? static_cast<std::size_t>(std::strtoull(value, nullptr, 0)) : std::size_t{0}; + }(); + return min; +} +bool srv_in_place_all() +{ + static const bool all = x2w_local::env_on("X2W_DRAW_SRV_IN_PLACE_ALL"); + return all; +} +void report_srv_copies() // the 5 s report (d3d12_xs_device.cpp) +{ + static const bool on = srv_in_place_min() || x2w_local::env_on("X2W_DRAW_SRV_STATS"); + if (!on) return; + char text[960]; + int used = 0; + static const char* const names[4] = {"other", "draw", "mesh", "table V#"}; + for (int c = 0; c < 4; ++c) { + LONG64 b[srvc_kinds], n[srvc_kinds]; + for (int k = 0; k < srvc_kinds; ++k) b[k] = InterlockedExchange64(&srvc_bytes[c][k], 0), n[k] = InterlockedExchange64(&srvc_calls[c][k], 0); + const LONG64 no_window = InterlockedExchange64(&srvc_in_place_missed[c][0], 0), unaligned = InterlockedExchange64(&srvc_in_place_missed[c][1], 0); + used += std::snprintf(text + used, sizeof(text) - used, + "%s%s: compared %lld MiB/%lld, copied %lld MiB/%lld, in place %lld MiB/%lld, in-place misses no window %lld unaligned %lld", + c ? "; " : "", names[c], b[srvc_compared] >> 20, n[srvc_compared], b[srvc_copied] >> 20, n[srvc_copied], + b[srvc_in_place] >> 20, n[srvc_in_place], no_window, unaligned); + if (used >= static_cast<int>(sizeof(text))) used = static_cast<int>(sizeof(text)) - 1; + } + log("x2w-draw srv copies since the last report (X2W_DRAW_SRV_IN_PLACE=%zu%s): %s", srv_in_place_min(), + srv_in_place_all() ? ", _ALL: plain draws too" : ", mesh calls only", text); +} + +bool compare_draw_copy(u64 address, std::size_t bytes, u64* offset, ID3D12Resource** buffer) +{ + if (frame_copies_frame != frame_number) return false; + const u64 key = address * 1099511628211ull ^ bytes; + FrameCopy seen; + { + const auto found = frame_copies().find(key); + if (found == frame_copies().end() || found->second.address != address || !found->second.content || + found->second.content->size() != bytes) return false; + seen = found->second; + } + const LONG frame = frame_number; + ReleaseSRWLockExclusive(&draw_lock); + const bool equal = std::memcmp(seen.content->data(), reinterpret_cast<const void*>(address), bytes) == 0; + lock_draw(100000 + __LINE__); + if (!equal || frame != frame_number) return false; + const auto current = frame_copies().find(key); + if (current == frame_copies().end() || current->second.content != seen.content || !ring_touch(seen.tag)) return false; + srvc_note(frame_copy_class, srvc_compared, bytes); + *offset = seen.offset; + *buffer = seen.buffer; + return true; +} // 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(u64 address, std::size_t bytes, u64* offset, ID3D12Resource** buffer) { if (frame_copies_frame != frame_number) { frame_copies().clear(); @@ -1105,31 +2609,110 @@ bool frame_copy(u64 address, std::size_t bytes, u64* offset) const u64 key = address * 1099511628211ull ^ bytes; const auto* title = reinterpret_cast<const unsigned char*>(address); 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) { + const bool known = found != frame_copies().end() && found->second.address == address && found->second.content && + found->second.content->size() == bytes; + if (known && std::memcmp(found->second.content->data(), title, bytes) == 0 && ring_touch(found->second.tag)) { + srvc_note(frame_copy_class, srvc_compared, bytes); // LOCAL stall *offset = found->second.offset; + *buffer = found->second.buffer; return true; } u64 fresh = 0; - auto* ring = reserve_upload_ring(bytes, &fresh); + ID3D12Resource* chunk = nullptr; + RingTag tag; + auto* ring = reserve_upload_ring(bytes, &fresh, &chunk, &tag); if (!ring) return false; + srvc_note(frame_copy_class, srvc_copied, bytes); // LOCAL stall (a refreshed hit also compared its bytes first) // Cache insertion and snapshot allocation are optional. Fill the ring directly if they fail. const unsigned char* source = title; try { - std::vector<unsigned char> content(title, title + bytes); + auto content = std::make_shared<const std::vector<unsigned char>>(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)}); - source = entry.first->second.content.data(); + auto entry = frame_copies().insert_or_assign(key, FrameCopy{address, fresh, chunk, tag, 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); + x2w_memcut::note_copy(frame_number, bytes); // LOCAL memcut 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; + *buffer = chunk; + return true; +} +// LOCAL stall: X2W_DRAW_LOCK_SPLIT: frame_copy for a caller that does NOT hold draw_lock (draw_translated's srv +// loop). draw_lock is taken for the map lookup (site lookup_line) and, after a miss, for the map update +// (commit_line); the memcmp of a hit, the snapshot copy and the ring fill run without it. +// - A hit compares the snapshot it holds a reference to with the title memory now. Equal: that snapshot's ring slice +// holds the same bytes, so it is bound if ring_touch (the ring's own lock) says its chunk was not recycled, whether +// or not another thread replaced the map entry meanwhile. +// - A miss reserves ring space (the ring's own lock; the slice is held by this open list), copies the snapshot and +// the ring unlocked, then stores the entry if the frame has not changed meanwhile (else it is dropped: the map was +// cleared for the new frame). +// Two threads missing on one range both copy; the later insert wins, and each binds its own slice. +bool frame_copy_unlocked(u64 address, std::size_t bytes, u64* offset, ID3D12Resource** buffer, int lookup_line, int commit_line) +{ + const u64 key = address * 1099511628211ull ^ bytes; + const auto* title = reinterpret_cast<const unsigned char*>(address); + std::shared_ptr<const std::vector<unsigned char>> seen; + u64 seen_offset = 0; + ID3D12Resource* seen_buffer = nullptr; + RingTag seen_tag; + lock_draw(lookup_line); + if (frame_copies_frame != frame_number) { + frame_copies().clear(); + frame_copies_frame = frame_number; + } + const LONG frame = frame_copies_frame; + if (const auto found = frame_copies().find(key); found != frame_copies().end() && found->second.address == address && + found->second.content && found->second.content->size() == bytes) { + seen = found->second.content; + seen_offset = found->second.offset; + seen_buffer = found->second.buffer; + seen_tag = found->second.tag; + } + ReleaseSRWLockExclusive(&draw_lock); + if (seen && std::memcmp(seen->data(), title, bytes) == 0 && ring_touch(seen_tag)) { + srvc_note(frame_copy_class, srvc_compared, bytes); + *offset = seen_offset; + *buffer = seen_buffer; + return true; + } + u64 fresh = 0; + ID3D12Resource* chunk = nullptr; + RingTag tag; + auto* ring = reserve_upload_ring(bytes, &fresh, &chunk, &tag); + if (!ring) return false; + srvc_note(frame_copy_class, srvc_copied, bytes); + std::shared_ptr<const std::vector<unsigned char>> content; + try { + content = std::make_shared<const std::vector<unsigned char>>(title, title + bytes); + } catch (const std::bad_alloc&) { + // The ring slice is already reserved: fill it from the title memory and keep no entry. + } + std::memcpy(ring, content ? content->data() : title, bytes); + x2w_memcut::note_copy(frame_number, bytes); // LOCAL memcut + if (content) { + lock_draw(commit_line); + if (frame_copies_frame == frame) { + try { + frame_copies().insert_or_assign(key, FrameCopy{address, fresh, chunk, tag, std::move(content)}); + } catch (const std::bad_alloc&) { + } + } + ReleaseSRWLockExclusive(&draw_lock); + } + if (seen) { + 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; + *buffer = chunk; return true; } @@ -1161,10 +2744,98 @@ u64 hash_memory(const unsigned char* data, std::size_t bytes) for (std::size_t i = words * 8; i < bytes; ++i) h = (h ^ data[i]) * 0x100000001b3ull; return h; } +x2w_startup::gfx10_local::Layout detile_layout(const D3D12_RESOURCE_DESC& r); // d3d12_memory_srv.inl (X2W_MEMORY_SRV_DETILE) +bool readable_texture_backing(u64 address, std::size_t bytes) +{ + Timed timed(time_cx_readable); + return x2w_local::descriptor_memory_readable(address, bytes); +} +// Record all available mips as one owned upload. Read each resident prefix into CPU-owned memory +// before touching the command list: title page mapping can change between the probe and the copy. +bool upload_partial_mips(Wrapper* self, ID3D12Resource* texture, const D3D12_RESOURCE_DESC& console, + u64 address, const x2w_startup::SliceFootprints& plan, TextureUpload& state, + u64 generation, bool* entered_copy_dest) +{ + const auto layout = detile_layout(console); + const UINT base = console.MipLevels - texture->GetDesc().MipLevels; + if (!layout.valid || base >= layout.mips) return false; + const auto suffix = base ? x2w_resident_mips::Suffix{base, x2w_resident_mips::prefix_bytes(layout, base)} + : x2w_resident_mips::find(layout, address, readable_texture_backing); + if (base && !readable_texture_backing(address, SIZE_T(suffix.prefix))) return false; + if (!suffix.prefix) return false; + auto* list = recording(self); + const auto desc = texture->GetDesc(); + if (plan.count != layout.mips - base || desc.DepthOrArraySize != layout.slices) return false; + const bool reusable = state.done && (!state.pending_list || state.pending_list == list) && + state.resident_first == suffix.first; + const auto total = layout.slices * suffix.prefix; + if (reusable && state.generation == generation && + !x2w_startup::recheck_cpu_texture(desc, total, UINT(frame_number) - UINT(state.checked_frame))) return true; + + std::vector<unsigned char> snapshot; + try { snapshot.resize(static_cast<std::size_t>(total)); } + catch (const std::bad_alloc&) { return false; } + for (UINT s = 0; s < layout.slices; ++s) { + SIZE_T read = 0; + if (!ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<const void*>(address + s * layout.slice_size), + snapshot.data() + s * suffix.prefix, SIZE_T(suffix.prefix), &read) || read != suffix.prefix) + return false; + } + const auto hash = hash_memory(snapshot.data(), snapshot.size()); + if (reusable && state.hash == hash) { + state.checked_frame = frame_number; + state.generation = generation; + return true; + } + const UINT element = 1u << layout.elem_log2; + const auto aligned = [](u64 bytes) { return (bytes + 511) & ~511ull; }; + u64 slice_bytes = 0; + for (UINT mip = suffix.first - base; mip < plan.count; ++mip) { + if (!plan.bytes(mip) || plan.placed[mip].Footprint.Depth != 1 || plan.row_bytes[mip] % element) return false; + slice_bytes += aligned(plan.bytes(mip)); + } + x2w_upload::Page page; + if (FAILED(x2w_upload::make_page(device_of(the_device), slice_bytes * layout.slices, page))) return false; + for (UINT s = 0; s < layout.slices; ++s) { + const auto* source = snapshot.data() + s * suffix.prefix; + for (UINT mip = suffix.first - base; mip < plan.count; ++mip) { + if (!x2w_resident_mips::stage_rows(layout, suffix, base + mip, source, page.cpu + page.cursor, + static_cast<UINT>(plan.row_bytes[mip] / element), plan.rows[mip], plan.placed[mip].Footprint.RowPitch)) return false; + page.cursor += aligned(plan.bytes(mip)); + } + } + try { recorded_address_uploads[list].push_back({page.resource, texture, ++address_upload_revision}); } + catch (const std::bad_alloc&) { return false; } + require_state(self, texture, D3D12_RESOURCE_STATE_COPY_DEST); + if (entered_copy_dest) *entered_copy_dest = true; + u64 offset = 0; + for (UINT s = 0; s < layout.slices; ++s) { + for (UINT mip = suffix.first - base; mip < plan.count; ++mip) { + plan.upload(list, texture, page.resource.Get(), plan.count, layout.slices, s, mip, offset); + offset += aligned(plan.bytes(mip)); + } + } + state.pending_list = list; + state.revision = address_upload_revision; + state.resident_first = suffix.first; + state.hash = hash; + state.generation = generation; + state.checked_frame = frame_number; + state.done = state.staged = true; + InterlockedIncrement(&textures_uploaded); + InterlockedExchangeAdd(&texture_bytes_uploaded, static_cast<LONG>(total >> 10)); + static LONG reports; + if (first_calls(reports, 16)) + log("x2w-gpu resident mips recorded at 0x%llx: %u..%u, %u slices, %llu source bytes", + address, suffix.first, layout.mips - 1, layout.slices, total); + return true; +} bool list_wrote(Wrapper* list, ID3D12Resource* resource); // list_copy.inl -bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) +bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture, bool* entered_copy_dest = nullptr) { + if (entered_copy_dest) *entered_copy_dest = false; auto* const memory = static_cast<const unsigned char*>(resource->own().title_memory); + if (InterlockedCompareExchange(&resource->own().refs, 0, 0) <= 0) x2w_memcut::note_after_release(true); // LOCAL memcut auto* list = recording(self); const D3D12_RESOURCE_DESC desc = texture->GetDesc(); const auto* original = resource_info(resource); @@ -1173,9 +2844,14 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) const bool dedicated = console && !address_uploads_from_ring(); // An address-only single-element texture (2D or 3D) uploads its one texel through the footprint path. const bool single = resource->own().tiled_address_srv && x2w_startup::single_element_bytes(desc) != 0; + // LOCAL (video): linear memory-SRV textures (X2W_MEMORY_SRV_LINEAR) are written by the XG stand-in in + // desktop footprint order for every dimension (a volume as one slice), so 1D arrays upload too. Upstream + // uploads every Texture3D with its depth in Footprint.Depth. + const bool linear_srv = resource->own().linear_memory_srv; + const bool volume = linear_srv && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool uploadable = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D || single || - (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc.DepthOrArraySize == 1 && desc.Height == 1); + (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc.Height == 1 && (desc.DepthOrArraySize == 1 || linear_srv)); { static LONG reasons; if ((!memory || (desc.Flags & 0x7) || !uploadable) && !texture_uploads().count(texture) && @@ -1210,11 +2886,19 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) if (const auto found = written_textures().find(reinterpret_cast<u64>(memory)); found != written_textures().end()) written = found->second; ReleaseSRWLockShared(&written_lock); + if (resource->own().partial_mip_srv && original) + return upload_partial_mips(self, texture, original->console, reinterpret_cast<u64>(memory), plan, state, + written.generation, entered_copy_dest); const bool tiled_chain = original && x2w_startup::bc64::supports(original->console); // Any other texture slot 70 publishes holds its texels in the console layout its description names // (gfx10_layout.h, address_texture.h). const bool tiled_bc7 = !tiled_chain && !tiled_address && written.bc7_width != 0; const bool tiled = tiled_bc7 || tiled_address || tiled_chain; + // LOCAL (textures): X2W_MEMORY_SRV_DETILE textures: the title memory holds the console layout of the console + // description (gfx10_layout.h); the readable window, the hash and the change check cover that whole surface. + const bool detiled = resource->own().detiled_memory_srv && original; + const x2w_startup::gfx10_local::Layout console_layout_local = detiled ? detile_layout(original->console) : x2w_startup::gfx10_local::Layout(~0u, false, 0, 0, 0, 0, 0); + if (resource->own().detiled_memory_srv && !console_layout_local.valid) return !console; std::optional<x2w_startup::gfx10::Layout> console_layout; if (console) console_layout.emplace(original->console); const auto generation = written.generation; @@ -1246,7 +2930,8 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) rows_match = compact.level[i].rows == plan.rows[i] && compact.level[i].row_bytes == plan.row_bytes[i]; if (!rows_match) return true; } - const u64 total = tiled_chain ? x2w_startup::bc64::Chain(original->console).bytes() : console ? console_layout->bytes() + const u64 total = detiled ? console_layout_local.size + : tiled_chain ? x2w_startup::bc64::Chain(original->console).bytes() : console ? console_layout->bytes() : tiled && !single ? surface.size() : is_compact ? compact.bytes : stride * (slices - 1) + slice_total; const bool announced = state.generation != generation; const UINT elapsed = static_cast<UINT>(frame_number) - static_cast<UINT>(state.checked_frame); @@ -1255,7 +2940,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) : x2w_startup::recheck_cpu_texture(desc, total, elapsed)); const bool reusable = state.done && (!state.pending_list || state.pending_list == list); if (reusable && !announced && !recheck) return true; - if (readable_window(reinterpret_cast<u64>(memory), static_cast<std::size_t>(total)) < total) { + if (!readable_texture_backing(reinterpret_cast<u64>(memory), static_cast<std::size_t>(total))) { if (!state.done) InterlockedIncrement(&textures_unreadable); if (console) return false; state.done = true; @@ -1287,16 +2972,45 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) } state.staged = false; require_state(self, texture, D3D12_RESOURCE_STATE_COPY_DEST); - if (console) { + if (entered_copy_dest) *entered_copy_dest = true; + if (detiled) { + // Each element of each level, array slice or volume depth from its console address into the desktop + // footprint. Element extents are the desktop ones (rows and row bytes of the footprint), which addrlib's + // ceiling level extents contain. + const UINT eb = 1u << console_layout_local.elem_log2; + for (UINT s = 0; s < slices; ++s) + for (UINT i = 0; i < mips; ++i) { + const auto& fp = plan.placed[i]; + const u64 bytes = plan.bytes(i); + u64 offset = 0; + ID3D12Resource* chunk = nullptr; + // One reservation per level and slice (at most one ring chunk, 64 MiB; a larger level is refused + // by the ring, and the texture is retried later). + auto* rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset, &chunk, nullptr); + if (!rows) { + state.done = false; + return !console; + } + const UINT columns = static_cast<UINT>(plan.row_bytes[i] / eb), depth = fp.Footprint.Depth ? fp.Footprint.Depth : 1; + for (UINT z = 0; z < depth; ++z) + for (UINT y = 0; y < plan.rows[i]; ++y) { + auto* row = rows + (u64{z} * plan.rows[i] + y) * fp.Footprint.RowPitch; + for (UINT x = 0; x < columns; ++x) + std::memcpy(row + u64{x} * eb, memory + console_layout_local.address(i, x, y, volume ? z : s), eb); + } + plan.upload(list, texture, chunk, mips, slices, s, i, offset); + } + } else if (console) { for (UINT slice = 0; slice < slices; ++slice) { for (UINT i = 0; i < mips; ++i) { const u64 bytes = plan.bytes(i); u64 offset = owned.cursor; + ID3D12Resource* chunk = nullptr; // LOCAL memcut: the ring chunk the rows are in unsigned char* rows = owned.cpu ? owned.cpu + offset : nullptr; if (owned.cpu) { owned.cursor += (bytes + placement - 1) & ~(placement - 1); } else { - rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset); + rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset, &chunk, nullptr); if (!rows) { state.done = false; return false; @@ -1304,7 +3018,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) std::memset(rows, 0, static_cast<std::size_t>(bytes)); } console_layout->detile(i, slice, memory, rows, plan.placed[i].Footprint.RowPitch); - plan.upload(list, texture, owned.cpu ? owned.resource.Get() : upload_ring, mips, slices, slice, i, offset); + plan.upload(list, texture, owned.cpu ? owned.resource.Get() : chunk, mips, slices, slice, i, offset); } } if (dedicated) { @@ -1317,35 +3031,38 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) for (UINT i = 0; i < mips; ++i) { const u64 bytes = plan.bytes(i); u64 offset = 0; - auto* rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset); + ID3D12Resource* chunk = nullptr; + auto* rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset, &chunk, nullptr); if (!rows) { state.done = false; return true; } std::memset(rows, 0, static_cast<std::size_t>(bytes)); chain.copy<false>(i, slice, rows, memory, plan.placed[i].Footprint.RowPitch); - plan.upload(list, texture, upload_ring, mips, slices, slice, i, offset); + plan.upload(list, texture, chunk, mips, slices, slice, i, offset); } } } else if (tiled && !single) { u64 offset = 0; + ID3D12Resource* chunk = nullptr; const auto bytes = plan.bytes(0); - auto* rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset); + auto* rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset, &chunk, nullptr); if (!rows) { state.done = false; return true; } std::memset(rows, 0, static_cast<std::size_t>(bytes)); surface.detile(memory, rows, plan.placed[0].Footprint.RowPitch); - plan.upload(list, texture, upload_ring, 1, 1, 0, 0, offset); + plan.upload(list, texture, chunk, 1, 1, 0, 0, offset); } else { for (UINT s = 0; s < slices; ++s) for (UINT i = 0; i < plan.count; ++i) { const auto& fp = plan.placed[i]; const u64 bytes = plan.bytes(i); u64 offset = 0; + ID3D12Resource* chunk = nullptr; if (is_compact) { - auto* const rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset); + auto* const rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset, &chunk, nullptr); if (!rows) { state.done = false; return true; @@ -1354,11 +3071,11 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) for (u64 y = 0; y < level.rows; ++y) std::memcpy(rows + y * fp.Footprint.RowPitch, memory + level.offset + y * level.row_bytes, static_cast<std::size_t>(level.row_bytes)); - } else if (!ring_copy(reinterpret_cast<u64>(memory) + stride * s + fp.Offset, static_cast<std::size_t>(bytes), &offset)) { + } else if (!ring_copy(reinterpret_cast<u64>(memory) + stride * s + fp.Offset, static_cast<std::size_t>(bytes), &offset, &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; @@ -1377,17 +3094,99 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) return true; } +// LOCAL (textures): X2W_HEAP_TEXTURE_UPLOAD=1. Heap (bindless) draws read the view-id region that fill_views +// (d3d12_compute.inl) fills with texture_view(..., prepare = false), so a texture that only the heap references was +// never uploaded nor moved to a shader-resource state. note_heap_texture (fill_views, each new SRV record) lists the +// plain textures; upload_heap_textures (each heap draw, after fill_views) visits the list round-robin, once a frame, +// with upload_texture (which skips unchanged textures itself), until X2W_HEAP_TEXTURE_BUDGET_KIB were uploaded +// (default 65536), X2W_HEAP_TEXTURE_BUDGET_US passed (default 2000) or 512 textures were visited, and moves each texture it uploaded to ALL_SHADER_RESOURCE (pixel and +// non-pixel stages: plain and mesh heap draws, meshrt 012000). The others stay as they are (COMMON between lists, +// promoted on first read). No new copies: each upload fills the desktop texture the title texture already has. +// draw_lock held for both. +bool heap_texture_upload_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_HEAP_TEXTURE_UPLOAD"); + if (v) log("x2w-draw X2W_HEAP_TEXTURE_UPLOAD=1: textures referenced by heap views are uploaded (budgeted, once a frame)"); + return v; + }(); + return on; +} +std::vector<Wrapper*> heap_textures; +std::unordered_set<Wrapper*> heap_texture_set; +std::size_t heap_texture_cursor; +LONG heap_texture_frame = -1; +LONG heap_textures_uploaded; +void note_heap_texture(const ViewRecord& record) +{ + if (!heap_texture_upload_on() || record.slot != 18) return; + Wrapper* resource = as_wrapper(reinterpret_cast<const void*>(record.resource)); + if (!resource || resource->own().kind != resource_kind || !resource->own().real || !resource->own().title_memory) return; + const D3D12_RESOURCE_DESC desc = static_cast<ID3D12Resource*>(resource->own().real)->GetDesc(); + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) return; + if (heap_texture_set.insert(resource).second) heap_textures.push_back(resource); +} +void upload_heap_textures(Wrapper* self) +{ + if (!heap_texture_upload_on() || heap_textures.empty() || heap_texture_frame == frame_number || !recording(self)) return; + heap_texture_frame = frame_number; + static const LONG budget_kib = [] { + char value[16]{}; + const LONG v = GetEnvironmentVariableA("X2W_HEAP_TEXTURE_BUDGET_KIB", value, sizeof value) ? std::atol(value) : 0L; + return v > 0 ? v : 65536L; + }(); + // Time as well as bytes: upload_texture also rehashes unchanged CPU-backed textures on its recheck schedule + // (up to 32 MiB each), which the byte budget does not see. X2W_HEAP_TEXTURE_BUDGET_US (default 2000) bounds the + // whole visit under draw_lock; the first texture is always visited. + static const LONG budget_us = [] { + char value[16]{}; + const LONG v = GetEnvironmentVariableA("X2W_HEAP_TEXTURE_BUDGET_US", value, sizeof value) ? std::atol(value) : 0L; + return v > 0 ? v : 2000L; + }(); + LARGE_INTEGER frequency{}, begin{}, now{}; + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&begin); + const LONG start_kib = texture_bytes_uploaded; + UINT uploaded = 0; + std::size_t visited = 0; + for (; visited < heap_textures.size() && visited < 512 && texture_bytes_uploaded - start_kib < budget_kib; ++visited) { + if (visited) { + QueryPerformanceCounter(&now); + if ((now.QuadPart - begin.QuadPart) * 1000000 / frequency.QuadPart >= budget_us) break; + } + Wrapper* resource = heap_textures[heap_texture_cursor++ % heap_textures.size()]; + // Revalidated each visit (wrappers are never freed today; this keeps it safe if that changes). + if (as_wrapper(resource) != resource || !resource->own().real) continue; + if (InterlockedCompareExchange(&resource->own().refs, 0, 0) <= 0) continue; // released: left alone + auto* texture = static_cast<ID3D12Resource*>(resource->own().real); + const LONG before = textures_uploaded; + upload_texture(self, resource, texture); + if (textures_uploaded == before) continue; + require_state(self, texture, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE); + ++uploaded; + } + if (!uploaded) return; + const LONG n = InterlockedExchangeAdd(&heap_textures_uploaded, static_cast<LONG>(uploaded)) + static_cast<LONG>(uploaded); + static LONG shown; + if (first_calls(shown, 8)) + log("x2w-draw heap textures: frame %ld uploaded %u (%ld KiB), visited %zu of %zu listed; %ld uploaded so far", frame_number, + uploaded, texture_bytes_uploaded - start_kib, visited, heap_textures.size(), n); +} + // Per-draw dumps (X2W_DRAW_DUMP_FRAME=<frame>, X2W_DRAW_DUMP_DIR=<folder>): during that frame, render // target 0 is copied to a readback buffer after each translated draw (at most 48). // Poll the fence of the queue that actually executed the recording before writing its image. using x2w_startup::DrawDump; +// LOCAL (video): set once by X2W_D3D12_TRACE_QUIET (d3d12_present.inl) when no X2W_DRAW_DUMP_FRAME is given. +LONG quiet_dump_frame; LONG draw_dump_frame() { static const LONG frame = [] { char value[16]{}; return GetEnvironmentVariableA("X2W_DRAW_DUMP_FRAME", value, sizeof(value)) ? std::atol(value) : 0L; }(); - return frame; + return frame ? frame : quiet_dump_frame; } void draw_dump_after(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, UINT count) { @@ -1457,6 +3256,516 @@ void draw_dump_flush() log("x2w-draw per-draw dump: %d of %zu completed target copies written to %s", written, completed.size(), folder); } +// LOCAL draw-rt: UAV stores from translated draws (RUNTIME_NEEDS 3 and 5). +// A buffer UAV is a raw view IN PLACE on the desktop window over the title's own memory (desktop_range, +// d3d12_compute.inl), never a copy: the stores reach the title's pages, where its CPU, translated compute +// and later draws read them. Windows rest in COMMON (implicit buffer promotion, as compute uses them); +// a null UAV barrier follows each draw that has UAVs. +// d3d12_compute.inl is included after this file. +D3D12_GPU_VIRTUAL_ADDRESS desktop_va(u64 address); +bool desktop_range(u64 address, u64 bytes, ID3D12Resource** buffer, u64* offset); +void fill_views(Wrapper* self); +bool title_view_heap(const Pass& pass, u64* address, u64* bytes); +extern ID3D12Resource* vinfo_buffer; +extern UINT views_filled; +extern ID3D12Resource* vdesc_buffer; // LOCAL meshrt: d3d12_vdesc.inl +bool ensure_vdesc(); + +// LOCAL draw-rt (`heap 1`): the title view heap a draw indexes: the shader-visible view heap the list set +// (SetDescriptorHeaps), else compute's choice. LOCAL meshrt (meshhar 010400): heapmem is a BOUNDED raw view (a +// table SRV, NumElements = bytes / 4: a Load past the end reads 0) over [base, base + count x increment), clamped to +// the end of the desktop window that holds the base. Resolved once per frame and heap; draw_lock held. Returns the +// reason the draw is skipped, or nullptr. +struct TitleHeapView { + D3D12_GPU_VIRTUAL_ADDRESS va = 0; // the base's desktop address (log only) + ID3D12Resource* window = nullptr; // the view: window + offset, bytes + u64 offset = 0, bytes = 0, heap_bytes = 0; +}; +LONG rt_heap_clamped; // views shortened to the end of the base's window (counted once per frame and heap) +const char* bounded_title_heap(u64 address, u64 bytes, TitleHeapView& out); +const char* draw_title_heap(const Pass& pass, TitleHeapView& out) +{ + u64 address = 0, bytes = 0; + if (pass.source_view_heap) { + AcquireSRWLockShared(¬e_lock); + for (const HeapInfo& h : heap_infos()) + if (h.wrapper == pass.source_view_heap && h.title_cpu) { + address = h.title_cpu; + bytes = u64{h.logical_count} * h.increment; // the title's count (count may be the driver-clamped one) + } + ReleaseSRWLockShared(¬e_lock); + } + if (!address && !title_view_heap(pass, &address, &bytes)) return "title view heap not reachable"; + return bounded_title_heap(address, bytes, out); +} + +// The bounded view over the title heap [address, address + bytes), for draws and translated dispatches +// (d3d12_compute.inl). Cached per frame and heap; draw_lock held. +const char* bounded_title_heap(u64 address, u64 bytes, TitleHeapView& out) +{ + static u64 last_address, last_bytes; + static TitleHeapView last; + static const char* last_why; + static LONG last_frame = -1; + if (address != last_address || bytes != last_bytes || last_frame != frame_number) { + last_address = address; + last_bytes = bytes; + last_frame = frame_number; + last = {}; + last.heap_bytes = bytes; + last.va = desktop_va(address); + last_why = nullptr; + ID3D12Resource* window = nullptr; + u64 offset = 0, view_bytes = bytes; + if (!last.va) { + last_why = "title view heap not reachable"; + } else if (!bytes) { + last_why = "title view heap size unknown"; + } else if (!desktop_range(address, bytes, &window, &offset)) { + // The heap runs past the window that holds its base: the view ends at that window's end. + window = nullptr; + if (desktop_range(address, 16, &window, &offset)) { + const u64 width = window->GetDesc().Width; + view_bytes = width > offset ? width - offset : 0; + InterlockedIncrement(&rt_heap_clamped); + static LONG shown; + if (first_calls(shown, 4)) + log("x2w-draw-rt title heap 0x%llx (%llu bytes) runs past its window: view clamped to %llu bytes", address, bytes, view_bytes); + } else { + window = nullptr; + } + } + if (!last_why && (!window || view_bytes < 4)) last_why = "title view heap not in a desktop window"; + else if (!last_why && (offset & 15)) last_why = "title view heap base not 16-byte aligned (bounded raw view)"; + if (!last_why) { + last.window = window; + last.offset = offset; + last.bytes = view_bytes & ~u64{3}; + } + } + out = last; + return last_why; +} + +// LOCAL meshrt: a bounded raw SRV (ByteAddressBuffer, NumElements = bytes / 4) at dest. offset 16-byte aligned. +void bounded_raw_srv(ID3D12Resource* buffer, u64 offset, u64 bytes, D3D12_CPU_DESCRIPTOR_HANDLE dest) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + d.Buffer.FirstElement = offset / 4; + d.Buffer.NumElements = static_cast<UINT>(bytes / 4 < UINT_MAX ? bytes / 4 : UINT_MAX); + d.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device_of(the_device)->CreateShaderResourceView(buffer, &d, dest); +} + +// gfx10 SQ_BUF_RSRC_WORD3 for a buffer view the title created (udsrc bufword3 / uavword3 of a view token): the +// word gfx10_view_words.h synthesizes, the same value compute hands to compute programs (d3d12_compute.inl): typed +// views only (FORMAT, DST_SEL, OOB_SELECT); raw, structured, constant-buffer and unmapped views: 0. +bool typed_views_off(); +std::uint32_t view_buffer_word3(const ViewRecord& record) +{ + if ((record.slot != 18 && record.slot != 19) || typed_views_off()) return 0; + x2w_startup::BufferViewLayout l; + if (!x2w_startup::buffer_view_layout_from_desc(record.slot == 19, record.desc, record.desc_bytes, l) || + l.kind != x2w_startup::BufferViewKind::typed) + return 0; + std::uint32_t v[8]; + x2w_startup::gfx10_buffer_words(l, v); + return v[3]; +} + +// Title ranges the GPU writes: translated-draw UAVs and GPU-ordered CopyBufferRegion destinations (slot 15, +// X2W_D3D12_COPY_BUFFER=gpu). Raw srvs overlapping one are bound in place instead of copied at record time, so a +// later draw reads what the GPU stored. Disjoint merged ranges, begin -> end; at most gpu_written_max, the lowest +// other range is dropped beyond that (counted: rt_written_evicted). draw_lock held. +std::map<u64, u64>& gpu_written() { static std::map<u64, u64> m; return m; } +// LOCAL stall: the map has its own lock (exclusive to note, shared to look up), so draw_translated's srv loop can ask +// without draw_lock under X2W_DRAW_LOCK_SPLIT. Order: draw_lock (when held) before gpu_written_lock; nothing else is +// taken while gpu_written_lock is held. +SRWLOCK gpu_written_lock = SRWLOCK_INIT; +constexpr std::size_t gpu_written_max = 16384; +void note_gpu_written_locked(u64 address, u64 bytes); +void note_gpu_written(u64 address, u64 bytes) +{ + AcquireSRWLockExclusive(&gpu_written_lock); + note_gpu_written_locked(address, bytes); + ReleaseSRWLockExclusive(&gpu_written_lock); +} +void note_gpu_written_locked(u64 address, u64 bytes) +{ + auto& m = gpu_written(); + u64 begin = address, end = address + bytes; + auto it = m.upper_bound(begin); + if (it != m.begin()) { + const auto before = std::prev(it); + if (before->second >= begin) { + begin = before->first; + if (before->second > end) end = before->second; + it = m.erase(before); + } + } + while (it != m.end() && it->first <= end) { + if (it->second > end) end = it->second; + it = m.erase(it); + } + if (m.size() >= gpu_written_max) { + m.erase(m.begin()); + InterlockedIncrement(&rt_written_evicted); + } + m.emplace(begin, end); +} +bool gpu_written_overlaps(u64 address, u64 bytes) +{ + AcquireSRWLockShared(&gpu_written_lock); + const auto& m = gpu_written(); + auto it = m.lower_bound(address + bytes); + const bool overlaps = it != m.begin() && (--it)->second > address; + ReleaseSRWLockShared(&gpu_written_lock); + return overlaps; +} +std::size_t gpu_written_count() +{ + AcquireSRWLockShared(&gpu_written_lock); + const std::size_t n = gpu_written().size(); + ReleaseSRWLockShared(&gpu_written_lock); + return n; +} +// An in-place srv on a window: shader-resource state in this list's tracked states, except when this list already +// holds the window as UAV (the same 256 MiB window often carries the draw's own uav: one state cannot be both; +// it stays UAV, as before this tracking existed). +void window_read_state(Wrapper* self, ID3D12Resource* window) +{ + if (pass_of(self).states.state(window) == D3D12_RESOURCE_STATE_UNORDERED_ACCESS) return; + require_state(self, window, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); +} + +void null_uav(D3D12_CPU_DESCRIPTOR_HANDLE dest, int kind) +{ + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + if (kind == 1) { + d.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + } else { + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d.Buffer.NumElements = 1; + d.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + } + device_of(the_device)->CreateUnorderedAccessView(nullptr, nullptr, &d, dest); +} + +// The 32-byte title descriptor table entry uav j was read from (0: none). words gets its contents. +u64 uav_entry(const Pass& pass, const Translation::Uav& uav, std::uint32_t (&words)[8]) +{ + const u64 entry = uav.source == 0 && uav.a >= 0 && uav.a < 16 && uav.b >= 0 ? pass.view_tables[uav.a].record(static_cast<u64>(uav.b), 32) : 0; + if (!entry || !x2w_local::readable(reinterpret_cast<const void*>(entry), 32)) return 0; + std::memcpy(words, reinterpret_cast<const void*>(entry), 32); + return entry; +} + +// Binds buffer uav j at dest. word3 / base / stride: the entry values `uavword3`, `uavbase` and `uavstride` (LOCAL +// pstrans: the record stride a translated idxen store multiplies the index by; 0 where none is known). draw_lock held. +void bind_uav_buffer(const Pass& pass, const Translation& tr, UINT j, D3D12_CPU_DESCRIPTOR_HANDLE dest, std::uint32_t* word3, std::uint32_t* base, + ID3D12Resource** bound_window, std::uint32_t* record_stride) +{ + const Translation::Uav& uav = tr.uavs[j]; + std::uint32_t words[8] = {}; + const u64 entry = uav_entry(pass, uav, words); + u64 address = 0; + std::size_t bytes = 0; + const char* from = "none"; + if (uav.source == 2 && uav.a >= 0 && uav.a < 16) { + address = pass.root_address[uav.a]; + bytes = address ? readable_window(address, 1u << 20) : 0; + from = "root"; + } else if (entry && words[0] == view_token_magic) { + // A view the title created: a CBV names its memory, a buffer SRV / UAV a range of its resource's title memory. + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + from = "view"; + if (known) *word3 = view_buffer_word3(record); + if (known && record.slot == 17 && record.desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(&address, record.desc, 8); + std::memcpy(&size, record.desc + 8, 4); + bytes = size; + } else if (known && (record.slot == 18 || record.slot == 19) && record.desc_bytes >= 36) { + DXGI_FORMAT format{}; + std::uint32_t dimension = 0, count = 0, stride = 0, flags = 0; + u64 first_element = 0; + const std::size_t at = record.slot == 18 ? 16 : 8; // Buffer member of the SRV / UAV description + std::memcpy(&format, record.desc, 4); + std::memcpy(&dimension, record.desc + 4, 4); + std::memcpy(&first_element, record.desc + at, 8); + std::memcpy(&count, record.desc + at + 8, 4); + std::memcpy(&stride, record.desc + at + 12, 4); + std::memcpy(&flags, record.desc + 32, 4); // Flags: +32 in both descriptions + Wrapper* resource = as_wrapper(reinterpret_cast<const void*>(record.resource)); + const bool raw = (flags & 1) || format == DXGI_FORMAT_R32_TYPELESS; + const UINT element = stride ? stride : raw || format == DXGI_FORMAT_UNKNOWN ? 4 : x2w_startup::typed_buffer_format_bytes(format); + // A structured view's stride, or a typed view's element size; a raw view has no record stride. + *record_stride = stride ? stride : raw || format == DXGI_FORMAT_UNKNOWN ? 0 : element; + if (dimension == 1 && element && resource && resource->own().title_memory) { + address = reinterpret_cast<u64>(resource->own().title_memory) + first_element * element; + bytes = std::size_t{count} * element; + } + } + } else if (entry) { + // A hardware buffer descriptor the title wrote itself: base address, stride and record count. + address = words[0] | (static_cast<u64>(words[1] & 0xffff) << 32); + const std::uint32_t stride = (words[1] >> 16) & 0x3fff; + bytes = static_cast<std::size_t>(stride ? stride : 1) * words[2]; + *word3 = words[3]; + *record_stride = stride; + from = "descriptor"; + } + if (bytes > (256u << 20)) bytes = 256u << 20; + ID3D12Resource* window = nullptr; + u64 offset = 0; + bool found = address && bytes && desktop_range(address, bytes, &window, &offset); + // A root UAV has no size: shrink the readable guess until it sits in one window. + for (std::size_t smaller = bytes; !found && uav.source == 2 && address && smaller > 4096;) { + smaller = smaller > (64u << 10) ? (64u << 10) : 4096; + if ((found = desktop_range(address, smaller, &window, &offset))) bytes = smaller; + } + const u64 aligned = offset & ~u64{15}; + const char* result = "bound"; + if (!found) { + result = "NULL (no desktop window)"; + InterlockedIncrement(&rt_uav_buf_unresolved); + null_uav(dest, 0); + } else if (aligned != offset && !(tr.uav_base_wanted & (1u << j))) { + result = "NULL (not 16-byte aligned, no uavbase)"; + InterlockedIncrement(&rt_uav_buf_misaligned); + null_uav(dest, 0); + } else { + *base = static_cast<std::uint32_t>(offset - aligned); + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d.Buffer.FirstElement = aligned / 4; + d.Buffer.NumElements = static_cast<UINT>((bytes + *base + 3) / 4); + d.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device_of(the_device)->CreateUnorderedAccessView(window, nullptr, &d, dest); + *bound_window = window; + note_gpu_written(address, bytes); + InterlockedIncrement(&rt_uav_buf_bound); + } + static LONG shown; + if (first_calls(shown, 8)) + log("x2w-draw-rt %016llx uav %u buffer source %d(%d,%d) from %s: entry 0x%llx words %08x %08x %08x %08x -> address 0x%llx, %zu bytes, " + "window %p +0x%llx: %s", tr.key, j, uav.source, uav.a, uav.b, from, entry, words[0], words[1], words[2], words[3], address, bytes, + static_cast<void*>(window), offset, result); +} + +// Texture uav j (`uav <i> tex2d`): a typed Texture2D UAV in the format and at the mip of the view the title +// created. The draw is skipped, not bound to a mismatched view, when any check fails. draw_lock held. +DXGI_FORMAT typeless_to_float(DXGI_FORMAT f); +bool float_format(DXGI_FORMAT f); +enum UavTextureSkip { tex_ok, tex_unresolved, tex_no_uav_flag, tex_shape, tex_format, tex_typed_store, tex_channels, tex_atomic_format, tex_atomic_support, tex_skip_count }; +const char* const uav_texture_skip_names[tex_skip_count] = {"bound", "unresolved view", "texture without ALLOW_UNORDERED_ACCESS", + "not a single-slice 2D texture at a valid mip", "format not a float/unorm format of the texture", "no typed UAV store for the format", + "4-channel format for a 3-channel (tex2d3) store", "incompatible integer atomic UAV format", "requested integer UAV atomic unsupported"}; +static_assert(tex_skip_count == std::size(rt_uav_tex), "one counter per texture uav outcome"); + +// Channels of the float_format formats (d3d12_compute.inl). +int x2w_startup_format_channels(DXGI_FORMAT f) +{ + switch (f) { + case DXGI_FORMAT_R11G11B10_FLOAT: return 3; + case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R8G8_UNORM: return 2; + case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R8_UNORM: return 1; + default: return 4; + } +} + +bool typed_store_supported(DXGI_FORMAT format) +{ + static signed char known[256]; // 0 not asked, 1 supported, -1 not + const auto i = static_cast<unsigned>(format); + if (i >= 256) return false; + if (!known[i]) { + D3D12_FEATURE_DATA_FORMAT_SUPPORT query{format}; + const bool yes = SUCCEEDED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &query, sizeof(query))) && + (query.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) && (query.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE); + known[i] = yes ? 1 : -1; + log("x2w-draw-rt format %d: typed UAV store %s", static_cast<int>(format), yes ? "supported" : "NOT supported"); + } + return known[i] > 0; +} + +UavTextureSkip bind_uav_texture(const Pass& pass, const Translation& tr, UINT j, D3D12_CPU_DESCRIPTOR_HANDLE dest, ID3D12Resource** out) +{ + std::uint32_t words[8] = {}; + const u64 entry = uav_entry(pass, tr.uavs[j], words); + ViewRecord record{}; + bool known = false; + if (entry && words[0] == view_token_magic) { + AcquireSRWLockShared(¬e_lock); + known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + } + Wrapper* resource = known ? as_wrapper(reinterpret_cast<const void*>(record.resource)) : nullptr; + ID3D12Resource* texture = resource && resource->own().kind == resource_kind ? static_cast<ID3D12Resource*>(resource->own().real) : nullptr; + if (tr.uavs[j].kind == uav_buf16x4) { + if (!texture || record.slot != 19 || record.desc_bytes < sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC)) return tex_unresolved; + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + std::memcpy(&d, record.desc, sizeof(d)); + const auto rd = texture->GetDesc(); + if (rd.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || d.ViewDimension != D3D12_UAV_DIMENSION_BUFFER || + !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) || d.Buffer.Flags || d.Buffer.StructureByteStride || + d.Buffer.CounterOffsetInBytes || d.Buffer.FirstElement > rd.Width / 8 || + d.Buffer.NumElements > rd.Width / 8 - d.Buffer.FirstElement) return tex_shape; + if (desktop_format(d.Format) != DXGI_FORMAT_R16G16B16A16_UINT && desktop_format(d.Format) != DXGI_FORMAT_R16G16B16A16_SINT) + return tex_format; + d.Format = DXGI_FORMAT_R16G16B16A16_UINT; + if (!typed_store_supported(d.Format)) return tex_typed_store; + device_of(the_device)->CreateUnorderedAccessView(texture, nullptr, &d, dest); + *out = texture; + if (resource->own().title_memory) note_gpu_written(reinterpret_cast<u64>(resource->own().title_memory) + 8 * d.Buffer.FirstElement, 8ull * d.Buffer.NumElements); + return tex_ok; + } + if (!texture || (record.slot != 18 && record.slot != 19) || record.desc_bytes < 24) return tex_unresolved; + const D3D12_RESOURCE_DESC rd = texture->GetDesc(); + if (!(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return tex_no_uav_flag; + DXGI_FORMAT format{}; + std::uint32_t dimension = 0, mip = 0; + std::memcpy(&format, record.desc, 4); + std::memcpy(&dimension, record.desc + 4, 4); + std::memcpy(&mip, record.desc + (record.slot == 19 ? 8 : 16), 4); // UAV MipSlice / SRV MostDetailedMip + // TEXTURE2D is 4 in both the SRV and the UAV dimension enumerations. + if (rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || rd.DepthOrArraySize != 1 || rd.SampleDesc.Count != 1 || dimension != 4 || + mip >= rd.MipLevels) return tex_shape; + if (tr.uavs[j].kind == uav_min || tr.uavs[j].kind == uav_max64 || tr.uavs[j].kind == uav_or) { + const int kind = tr.uavs[j].kind; + const auto typed = kind == uav_max64 ? DXGI_FORMAT_R32G32_UINT : DXGI_FORMAT_R32_UINT; + const auto typeless = kind == uav_max64 ? DXGI_FORMAT_R32G32_TYPELESS : DXGI_FORMAT_R32_TYPELESS; + if (record.slot != 19 || desktop_format(format ? format : rd.Format) != typed || + (rd.Format != typed && rd.Format != typeless)) return tex_atomic_format; + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{typed}; + if (FAILED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) || + !(support.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)) return tex_atomic_support; + if (kind == uav_max64) { + D3D12_FEATURE_DATA_D3D12_OPTIONS9 opts{}; + if (FAILED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS9, &opts, sizeof(opts))) || + !opts.AtomicInt64OnTypedResourceSupported) return tex_atomic_support; + } else if (!(support.Support2 & (kind == uav_min ? D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_UNSIGNED_MIN_OR_MAX : + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_BITWISE_OPS))) return tex_atomic_support; + format = typed; + } else { + format = typeless_to_float(desktop_format(format ? format : rd.Format)); + if (!float_format(format) || (format != rd.Format && format != typeless_to_float(rd.Format))) return tex_format; + if (!typed_store_supported(format)) return tex_typed_store; + if (tr.uavs[j].kind == uav_rgb && x2w_startup_format_channels(format) > 3) return tex_channels; + } + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = format; + d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + d.Texture2D.MipSlice = mip; + device_of(the_device)->CreateUnorderedAccessView(texture, nullptr, &d, dest); + *out = texture; + static LONG shown; + if (first_calls(shown, 4)) + log("x2w-draw-rt %016llx uav %u texture: entry 0x%llx view %u -> %p %llux%u format %d mip %u: bound", tr.key, j, entry, words[1], + static_cast<void*>(texture), rd.Width, rd.Height, static_cast<int>(format), mip); + return tex_ok; +} + +// LOCAL meshrt: X2W_MESH_DUMP_INPUTS=<key hex>: the inputs of the FIRST traced mesh call of that key go to files in +// <folder of X2W_TRAP_LOG>\mesh_dump_<key>\ (local only): srv<i>.bin = the srv's title range read at record time (the +// bytes a record-time copy uploads; an in-place binding is read by the GPU later), entry.bin = the entry constants as +// set (u32 each), record.bin = the indirect record (d3d12_mesh.inl), index.txt = one line per file. Traced frame only. +// The value is a comma (or space / semicolon) separated list of up to 16 keys; each key is dumped once. +struct MeshDumpKeys { + u64 keys[16] = {}; + unsigned count = 0; +}; +const MeshDumpKeys& mesh_dump_keys() +{ + static const MeshDumpKeys list = [] { + MeshDumpKeys out; + char value[16 * 20 + 16]{}; + if (!GetEnvironmentVariableA("X2W_MESH_DUMP_INPUTS", value, sizeof(value))) return out; + for (char* p = value; *p && out.count < 16;) { + while (*p == ',' || *p == ' ' || *p == ';') ++p; + char* end = nullptr; + const u64 key = _strtoui64(p, &end, 16); + if (end == p) break; + if (key) out.keys[out.count++] = key; + p = end; + } + log("x2w-mesh X2W_MESH_DUMP_INPUTS: %u key(s)", out.count); + return out; + }(); + return list; +} +u64 mesh_dump_key() { return mesh_dump_keys().count ? mesh_dump_keys().keys[0] : 0; } // non-zero: any key wanted +LONG mesh_dump_claimed[16]; // one dump per listed key +LONG mesh_dump_done; // keys dumped +// Any listed key not dumped yet (then the indirect stage reads each mesh call's record, in any frame). +bool mesh_dump_pending() { return mesh_dump_keys().count && mesh_dump_done < static_cast<LONG>(mesh_dump_keys().count); } +// X2W_MESH_DUMP_FROM_FRAME=<n> (default 0): no dump before present n (to skip the start-up pages if needed). +LONG mesh_dump_from_frame() +{ + static const LONG n = [] { + char v[16]{}; + return GetEnvironmentVariableA("X2W_MESH_DUMP_FROM_FRAME", v, sizeof(v)) ? std::atol(v) : 0L; + }(); + return n; +} +thread_local std::string mesh_dump_dir; // non-empty: this call is being dumped (folder with trailing backslash) +bool mesh_dump_record_groups(std::uint32_t (&xyz)[3]); +bool mesh_dump_begin(u64 key) +{ + mesh_dump_dir.clear(); + const MeshDumpKeys& list = mesh_dump_keys(); + unsigned at = 0; + while (at < list.count && list.keys[at] != key) ++at; + if (!key || at == list.count || mesh_dump_claimed[at] || frame_number < mesh_dump_from_frame()) return false; + std::uint32_t xyz[3] = {}; + if (!mesh_dump_record_groups(xyz) || !xyz[0] || !xyz[1] || !xyz[2]) return false; + if (InterlockedCompareExchange(&mesh_dump_claimed[at], 1, 0) != 0) return false; + InterlockedIncrement(&mesh_dump_done); + char log_path[MAX_PATH]{}; + std::string dir; + if (GetEnvironmentVariableA("X2W_TRAP_LOG", log_path, sizeof(log_path))) { + dir = log_path; + const std::size_t slash = dir.find_last_of("\\/"); + dir = slash == std::string::npos ? std::string() : dir.substr(0, slash + 1); + } + char name[48]; + std::snprintf(name, sizeof(name), "mesh_dump_%016llx\\", static_cast<unsigned long long>(key)); + dir += name; + CreateDirectoryA(dir.c_str(), nullptr); + mesh_dump_dir = dir; + log("x2w-mesh dump %016llx: inputs of the first call with groups (record %u %u %u, frame %ld%s) to %s", static_cast<unsigned long long>(key), + xyz[0], xyz[1], xyz[2], frame_number, trace_frame_active ? ", traced" : "", dir.c_str()); + return true; +} +void mesh_dump_file(const char* file, const void* data, std::size_t bytes, const char* note) +{ + if (mesh_dump_dir.empty()) return; + const std::string path = mesh_dump_dir + file; + bool written = false; + if (FILE* f = std::fopen(path.c_str(), "wb")) { + written = (!bytes || !data || std::fwrite(data, 1, bytes, f) == bytes); + std::fclose(f); + } + if (FILE* index = std::fopen((mesh_dump_dir + "index.txt").c_str(), "ab")) { + std::fprintf(index, "%s %zu bytes%s: %s\n", file, bytes, written ? "" : " (WRITE FAILED)", note); + std::fclose(index); + } +} + +// LOCAL (scene): the key and refusal of the latest draw on this thread, for the traced-frame draw lines. +thread_local u64 last_draw_key; +thread_local const char* last_draw_why; bool d16_srvs_ready(const Translation& tr, const Pass& pass, std::uint32_t (&d16_unorm16)[32]) { if (!tr.d16_srvs.any()) return true; @@ -1695,9 +4004,7 @@ ID3D12Resource* validate_indexed_arguments(Wrapper* self, ID3D12GraphicsCommandL auto* indices = draw.indices.resource; const auto before = [&](ID3D12Resource* resource) { - for (const auto& state : pass_of(self).states) - if (state.first == resource) return state.second; - return D3D12_RESOURCE_STATE_COMMON; + return pass_of(self).states.state(resource); }; const auto argument_previous = before(draw.argument); const auto index_previous = before(indices); @@ -1832,7 +4139,7 @@ struct FormattedBufferDescriptor { std::uint32_t words[8] = {}; }; -bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedBufferDescriptor (&descriptors)[32]) +bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedBufferDescriptor (&descriptors)[draw_srv_limit]) { const auto refuse = [&](int slot, const char* reason, std::uint32_t detail = 0) { InterlockedIncrement(&formatted_draws_refused); @@ -1843,7 +4150,7 @@ bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedB }; for (const auto& ud : tr.uds) { if (ud.kind != Translation::desc_word3) continue; - if (ud.a < 0 || ud.a >= 32 || static_cast<std::size_t>(ud.a) >= tr.srvs.size()) + if (ud.a < 0 || ud.a >= draw_srv_limit || static_cast<std::size_t>(ud.a) >= tr.srvs.size()) return refuse(ud.a, "invalid SRV index"); auto& descriptor = descriptors[ud.a]; if (descriptor.entry) continue; @@ -1878,29 +4185,114 @@ bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedB return true; } +bool view_record_words(const ViewRecord& record, std::uint32_t out[8], bool* image, bool* unmapped); // d3d12_compute.inl + +// LOCAL ind-meshps: `udsrc <i> descword <param> <byte>` of a draw or mesh call (X2W_MESH_DESCWORD=1): the dword at <byte> +// of the descriptor table the title bound at graphics root parameter <param>, in its 32-byte console entries +// (entry = byte & ~31, word = (byte & 31) / 4), by the rule of compute's descword_value (d3d12_compute.inl): a view +// token gives the synthesized T# / V# word of its view (view_record_words), any other readable entry its own dword, +// an unbound table, an unreadable entry, an unknown view or a refused-view marker (draw-path only) 0. Free-list link +// entries (free_link_words) are read as the title's dwords, as compute does (not checked against a console). +LONG rt_descword_title, rt_descword_view, rt_descword_null; +std::uint32_t draw_descword_value(const Pass& pass, int param, int offset, u64 key) +{ + const u64 entry = param >= 0 && param < 16 && offset >= 0 ? pass.view_tables[param].record(static_cast<u64>(offset) & ~31ull, 32) : 0; + const int word = (offset & 31) / 4; + std::uint32_t words[8] = {}, value = 0; + const char* what = "table not bound or entry out of range"; + if (entry && x2w_local::readable(reinterpret_cast<const void*>(entry), 32)) { + std::memcpy(words, reinterpret_cast<const void*>(entry), 32); + if (words[0] == refused_view_magic) { + what = "refused-view marker: 0"; // the stand-in's marker words are not the console's descriptor + } else if (words[0] != view_token_magic) { + value = words[word]; + what = "title word"; + } else { + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + std::uint32_t out[8] = {}; + bool image = false, unmapped = false; + if (known && view_record_words(record, out, &image, &unmapped)) { + value = out[word]; + what = image ? (unmapped ? "T# word (no gfx10 format: FORMAT 0)" : "T# word") : "V# word"; + } else { + what = "unknown view: 0"; + } + } + } else if (entry) { + what = "entry unreadable: 0"; + } + InterlockedIncrement(what[0] == 't' && what[1] == 'i' ? &rt_descword_title : what[1] == '#' ? &rt_descword_view : &rt_descword_null); + static LONG shown; + if (first_calls(shown, 4)) + log("x2w-draw-rt %016llx descword %d %d: entry 0x%llx %s = 0x%08x", key, param, offset, entry, what, value); + return value; +} + +#include "startup_stubs/draw_input_dump.inl" // LOCAL lt-lead probe: X2W_DRAW_DUMP_INPUTS (inactive otherwise) + bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance, TranslatedIndirectDraw* indirect) { auto* list = recording(self); Pass& pass = pass_of(self); - const bool rect = pass.topology == 0x11; + const u64 ring_refusals_at_start = ring_cap_refusals; // LOCAL memcut: upload ring refusals during this draw + const bool mesh = mesh_issue_active(self); // LOCAL meshrt: a DispatchMesh call (d3d12_mesh.inl); no topology, rect entry value 0 + const bool rect = !mesh && pass.topology == 0x11; + // Upstream #2259: an indexed rectangle list is drawn only through an indirect draw (geometry-stage expansion). const bool indexed_rect = rect && indexed && indirect; - if (!list || !pass.pipeline || !pass.targets_bound || !(rect || pass.topology == 4 || pass.topology == 5) || - (rect && indexed && !indexed_rect)) return false; - AcquireSRWLockExclusive(&draw_lock); - BoundPipeline* bound = translation_for(pass.pipeline); - Translation* tr = bound ? translation_for_targets(bound->translation, pass) : nullptr; + last_draw_key = 0; + last_draw_why = nullptr; + if (list && pass.pipeline && !pass.targets_bound) InterlockedIncrement(&draws_without_targets); + if (!list || !pass.pipeline || !pass.targets_bound || !(mesh || rect || pass.topology == 4 || pass.topology == 5) || (rect && indexed && !indexed_rect)) { + last_draw_why = !list ? "not recording" : !pass.pipeline ? "no pipeline" : !pass.targets_bound ? "no targets" + : (rect && indexed && !indexed_rect) ? "indexed rectangle list" : "topology"; + return false; + } + lock_draw(100000 + __LINE__); + report_draw_rt(); + static const bool pso_locked = x2w_local::env_on("X2W_DRAW_PSO_LOCKED"); + BoundPipeline* bound = nullptr; + Translation* tr = nullptr; + ID3D12PipelineState* pipeline = nullptr; + for (int attempt = 0;; ++attempt) { + // A second attempt finds the pipeline build_pipeline made (pipeline_for installs it). + bound = translation_for(pass.pipeline); + tr = bound ? translation_for_targets(bound->translation, pass) : nullptr; + PsoBuild build; + pipeline = tr && tr->state == 1 && ensure_draw_heap(self->own().list_device) + ? pipeline_for(*bound, *tr, pass, pso_locked || attempt ? nullptr : &build, indexed_rect) : nullptr; + if (pipeline || !build.bound) break; + ReleaseSRWLockExclusive(&draw_lock); + if (draw_async()) { // LOCAL stall: never compile or wait here; the draw is skipped + queue_pso_build(build); + last_draw_key = tr->key; + last_draw_why = "desktop pipeline compiling (X2W_DRAW_ASYNC)"; + return false; + } + build_pipeline(build); + lock_draw(100000 + __LINE__); + } + if (bound && bound->translation) last_draw_key = bound->translation->key; + // Upstream indirect draws (#2232 .. #2262): reached only through draw_translated(..., indirect), the + // X2W_TRANSLATED_INDIRECT path in d3d12_xs_device.cpp. A plain draw passes nullptr and skips all of it. if (indirect && tr) indirect->shader_key = tr->key; std::uint32_t d16_unorm16[32] = {}; - FormattedBufferDescriptor formatted_buffers[32] = {}; - const bool translation_ok = tr && tr->state == 1; - const bool d16_ok = translation_ok && d16_srvs_ready(*tr, pass, d16_unorm16); - const bool formatted_ok = d16_ok && formatted_buffers_ready(*tr, pass, formatted_buffers); - if (!formatted_ok) { - if (indirect && tr) - indirect->refusal_code = !translation_ok ? indirect_refusal_code::translation_not_ready - : !d16_ok ? indirect_refusal_code::d16_srv_not_ready - : indirect_refusal_code::formatted_buffer_not_ready; + if (tr && tr->state == 1 && !d16_srvs_ready(*tr, pass, d16_unorm16)) { + last_draw_why = "d16 exact srv refused"; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + FormattedBufferDescriptor formatted_buffers[draw_srv_limit] = {}; // upstream #2138 (udsrc descword3) + if (tr && tr->state == 1 && !formatted_buffers_ready(*tr, pass, formatted_buffers)) { + last_draw_why = "formatted buffer refused"; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + if (indirect && (!bound || !tr || tr->state != 1)) { ReleaseSRWLockExclusive(&draw_lock); return false; } @@ -1940,25 +4332,77 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return false; } } - ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass, indexed_rect) : nullptr; - if (indirect && indexed_rect && !pipeline) { - indirect->set_refusal("translated indexed rectangle geometry unavailable", - indirect_refusal_code::indexed_rect_unavailable); - } + if (indexed_rect && !pipeline) indirect->refusal = "translated indexed rectangle geometry unavailable"; if (!pipeline || (tr->samplers.heap && !prepare_draw_sampler_heap(pass, list, tr->samplers.reserved_fallback))) { - if (indirect && !(indexed_rect && !pipeline)) - indirect->refusal_code = !pipeline ? indirect_refusal_code::pipeline_unavailable - : indirect_refusal_code::sampler_heap_unavailable; + last_draw_why = !bound || !bound->translation ? "no translation record" + : !tr ? "no translation for the bound targets (rtv variant)" + : tr->state != 1 ? "no translation" : !pipeline ? "no desktop pipeline" : "sampler heap"; ReleaseSRWLockExclusive(&draw_lock); return false; } + TitleHeapView heap_view; + if (tr->heap) { + // LOCAL draw-rt: the title heap in place, and the view-id region filled up to the newest view. + const char* reason = draw_heap_increment != 32 ? "descriptor increment is not 32" : draw_title_heap(pass, heap_view); + if (!reason) { + fill_views(self); + upload_heap_textures(self); // LOCAL textures: X2W_HEAP_TEXTURE_UPLOAD + if (!vinfo_buffer) reason = "no per-view info buffer"; + else if (tr->heapwords && !ensure_vdesc()) reason = "no view descriptor (vdesc) buffer"; // LOCAL meshrt + } + if (reason) { + InterlockedIncrement(&rt_heap_skipped); + static LONG shown; + if (first_calls(shown, 4)) log("x2w-draw-rt %016llx: heap draw skipped: %s", tr->key, reason); + last_draw_why = reason; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + } const UINT n = static_cast<UINT>(tr->srvs.size()); - UINT first = static_cast<UINT>(InterlockedExchangeAdd(&draw_heap_cursor, static_cast<LONG>(n))) % draw_heap_size; - if (first + n > draw_heap_size) { + const UINT m = static_cast<UINT>(tr->uavs.size()); // LOCAL draw-rt: the uav table follows the srvs in the ring + // LOCAL meshrt: then the bounded heap views (heapmem, vinfo, vdesc with `heapwords 1`), one table each. + const UINT hv = tr->heap ? (tr->heapwords ? 3u : 2u) : 0u; + UINT first = static_cast<UINT>(InterlockedExchangeAdd(&draw_heap_cursor, static_cast<LONG>(n + m + hv))) % draw_heap_size; + if (first + n + m + hv > draw_heap_size) { first = 0; - InterlockedExchange(&draw_heap_cursor, static_cast<LONG>(n)); + InterlockedExchange(&draw_heap_cursor, static_cast<LONG>(n + m + hv)); + } + // LOCAL lt-lead probe: X2W_DRAW_DUMP_INPUTS (inactive and free unless this draw is selected; mesh calls never). + dd_dump::Draw ddump(self, mesh ? 0 : tr->key, indirect != nullptr || indirect_pending(self), indexed, count, instances, start, base_vertex, + start_instance); + std::uint32_t uav_word3[8] = {}, uav_bases[8] = {}, uav_strides[8] = {}; + ID3D12Resource* uav_textures[8] = {}; + ID3D12Resource* uav_windows[8] = {}; + UavTextureSkip skip = tex_ok; + for (UINT j = 0; j < m && skip == tex_ok; ++j) { + const D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + n + j} * draw_heap_increment}; + if (tr->uavs[j].kind == uav_raw) { + bind_uav_buffer(pass, *tr, j, dest, &uav_word3[j], &uav_bases[j], &uav_windows[j], &uav_strides[j]); + ddump.uav_buffer(j, uav_bases[j], uav_strides[j], uav_word3[j]); + } else { + const auto result = bind_uav_texture(pass, *tr, j, dest, &uav_textures[j]); + InterlockedIncrement(&rt_uav_tex[result]); + if (result != tex_ok) skip = result; + ddump.uav_texture(j, uav_textures[j]); + } + } + // Windows bound as UAV are tracked in this list's states (moved back to COMMON at Close), so a GPU copy or an + // in-place srv after this draw names the right before-state. + if (skip == tex_ok) + for (ID3D12Resource* w : uav_windows) + if (w) require_state(self, w, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (skip != tex_ok) { + static LONG shown[tex_skip_count]; + if (first_calls(shown[skip], 2)) log("x2w-draw-rt %016llx: draw skipped: texture uav: %s", tr->key, uav_texture_skip_names[skip]); + last_draw_why = uav_texture_skip_names[skip]; + ReleaseSRWLockExclusive(&draw_lock); + return false; } - std::uint32_t strides[32] = {}; + // LOCAL stall: X2W_DRAW_LOCK_SPLIT. Never for an upstream indirect draw: its refusals in the view loop release draw_lock. + const bool split = draw_lock_split() && !indirect; + if (split) ReleaseSRWLockExclusive(&draw_lock); + std::uint32_t strides[draw_srv_limit] = {}, word3[draw_srv_limit] = {}; // 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. @@ -1982,6 +4426,12 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } } if (vertex_first < 0) vertex_first = 0; + ddump.geometry(vertex_first, vertex_count, indexed, index_address, index_total, index_bytes, indices_ok, pass.topology, pass); + bool dumping = false; + if (mesh && mesh_dump_pending()) { // any frame (the first call with groups of each listed key) + SplitRelock relock(split, 100000 + __LINE__); + dumping = mesh_dump_begin(tr->key); // LOCAL meshrt + } UINT indexed_vertices = UINT_MAX; for (UINT i = 0; i < n; ++i) { const Translation::Srv& srv = tr->srvs[i]; @@ -2009,14 +4459,17 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI (srv.source == 0 && srv.a >= 0 && srv.a < 16 && srv.b >= 0 ? pass.view_tables[srv.a].record(static_cast<u64>(srv.b), 32) : 0); std::uint32_t words[8] = {}; - const bool entry_ok = formatted.entry || - (entry && x2w_local::readable(reinterpret_cast<const void*>(entry), 32)); - if (entry_ok) std::memcpy(words, formatted.entry ? formatted.words : reinterpret_cast<const void*>(entry), 32); + const bool entry_ok = entry && x2w_local::readable(reinterpret_cast<const void*>(entry), 32); + if (entry_ok) std::memcpy(words, reinterpret_cast<const void*>(entry), 32); + if (entry_ok && words[0] != view_token_magic) word3[i] = words[3]; // run-time buffer format (udsrc bufword3) bool buffer_token_known = false; if (srv.kind >= 1 && srv.kind <= 4) { const auto dimension = srv.kind == 1 ? D3D12_SRV_DIMENSION_TEXTURE2D : srv.kind == 2 ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : srv.kind == 4 ? D3D12_SRV_DIMENSION_TEXTURE1D : D3D12_SRV_DIMENSION_TEXTURE3D; + if (entry_ok) note_rewritten_marker(tr->key, i, entry, words); + SplitRelock relock(split, 100000 + __LINE__); // the rest of the texture bind (memcut revive, uploads, counters) + if (entry_ok && words[0] != view_token_magic) resolve_heap_index(tr->key, i, entry, words); // A texture: the title's descriptor memory carries the id of the view it created there. ViewRecord record{}; bool known = false; @@ -2066,7 +4519,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } if (texture && !upload_texture(self, resource, texture)) texture = nullptr; if (texture) { - require_state(self, texture, sampled_state(self, texture)); + require_sampled(self, texture, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); if (resource && !resource->own().tiled_address_srv) retire_hold(self, resource); } const bool had_texture = texture != nullptr; @@ -2075,6 +4528,13 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (first_calls(shown, 6)) log("x2w-draw %016llx srv %u texture: table entry 0x%llx words %08x %08x -> view %s, resource %p, desc %u bytes format %d", tr->key, i, entry, words[0], words[1], known ? "known" : "UNKNOWN", static_cast<void*>(texture), record.desc_bytes, desc.Format); + // LOCAL (scene): in a traced frame, every texture a draw samples, by resource, so a pass's inputs can be + // matched against the "x2w-frame draw ... target <ptr>" lines of the passes that wrote them. + if (trace_frame_active) { + const D3D12_RESOURCE_DESC td = texture ? texture->GetDesc() : D3D12_RESOURCE_DESC{}; + log("x2w-frame srv %016llx %u texture %p %llux%u fmt %d (view fmt %d)", tr->key, i, static_cast<void*>(texture), + static_cast<unsigned long long>(td.Width), td.Height, td.Format, desc.Format); + } const bool wrong_1d_resource = texture && srv.kind == 4 && (texture->GetDesc().Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D || texture->GetDesc().DepthOrArraySize != 1); if (texture && ((record.desc_bytes >= 40 && desc.ViewDimension != dimension) || wrong_1d_resource)) { @@ -2108,9 +4568,32 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI x2w_startup::report_token_entry(line, sizeof(line), tr->key, i, entry, words); log("%s", line); } - device_of(the_device)->CreateShaderResourceView(texture, texture && record.desc_bytes < 40 ? nullptr : &desc, dest); + census_texture_binding(resource, texture, x2w_local::classify_null_binding(facts)); + note_null_texture(tr->key, i, entry, words, x2w_local::classify_null_binding(facts)); + D3D12_SHADER_RESOURCE_VIEW_DESC depth_default{}; + const bool no_desc = texture && record.desc_bytes < 40; + const bool depth_desc = no_desc && default_depth_srv(texture, depth_default); + if (texture && !no_desc) fix_srv(desc, texture); + device_of(the_device)->CreateShaderResourceView(texture, depth_desc ? &depth_default : no_desc ? nullptr : &desc, dest); + ddump.srv_texture(i, srv.kind, entry, words, texture, desc.Format, texture ? "bound" : mismatched ? "null (dimension mismatch)" : "null"); continue; } + // LOCAL (textures): X2W_BUFFER_HEAP_INDEX (buffer_heap_index_on): a free-list buffer entry binds null. + if (srv.source == 0 && entry_ok) note_rewritten_marker(tr->key, i, entry, words); // LOCAL (textures): X2W_MARKER_REWRITE_LOG + const bool buffer_link = srv.source == 0 && entry_ok && free_link_words(words); + if (buffer_link) { + InterlockedIncrement(words[0] == refused_view_magic ? &buffer_refused_views : &buffer_links); + if (buffer_heap_index_on()) { + static LONG link_lines; + if (trace_frame_active || first_calls(link_lines, 32)) { + SplitRelock relock(split, 100000 + __LINE__); // reads heap shadow arrays outside note_lock + log_buffer_link(tr->key, i, entry, words); + } + InterlockedIncrement(&buffer_links_nulled); + std::memset(words, 0, sizeof(words)); + word3[i] = 0; + } + } if (indirect) { IndirectBufferView view{}; if (srv.source == 1 && indexed) { @@ -2148,6 +4631,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI buffer_token_known = words[1] < view_records().size(); if (buffer_token_known) record = view_records()[words[1]]; ReleaseSRWLockShared(¬e_lock); + if (buffer_token_known) word3[i] = view_buffer_word3(record); // LOCAL draw-rt: synthesized V# word 3 if (record.slot == 17 && record.desc_bytes >= 12) { std::uint32_t size = 0; std::memcpy(&address, record.desc, 8); @@ -2173,18 +4657,49 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI strides[i] = (words[1] >> 16) & 0x3fff; bytes = static_cast<std::size_t>(strides[i] ? strides[i] : 1) * words[2]; } - if (bytes > (16u << 20)) { - bytes = 16u << 20; - // Formatted loads past the copy would read zeros on the desktop; refuse the draw instead. - if (formatted.entry) { - InterlockedIncrement(&formatted_draws_refused); - static LONG refused; - if (first_calls(refused, 6)) - log("x2w-draw %016llx srv %u: formatted buffer refused (buffer larger than the 16 MiB draw copy)", tr->key, i); - ReleaseSRWLockExclusive(&draw_lock); - return false; + const std::size_t full_bytes = bytes; // LOCAL meshrt: the dump writes the whole range (up to 256 MiB) + ddump.srv_buffer(i, srv.source, srv.a, srv.b, entry, words, address, bytes, strides[i]); // LOCAL lt-lead probe + if (mesh && trace_frame_active) record_trace_mesh_read(tr->key, i, srv.source, srv.a, srv.b, address, full_bytes); // LOCAL (scene) + constexpr std::size_t copy_limit = 16u << 20; + constexpr std::size_t max_raw_view = std::size_t{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP; + const bool in_place = address && srv_in_place_min() && bytes >= srv_in_place_min() && (mesh || srv_in_place_all()); + ID3D12Resource* full_window = nullptr; + u64 full_offset = 0; + if (bytes > copy_limit) { + // A validated in-place table view does not consume upload-ring space. + if (!(in_place && srv.source == 0 && bytes <= max_raw_view && bytes % 4 == 0 && + desktop_range(address, bytes, &full_window, &full_offset) && + full_offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT == 0)) { + bytes = copy_limit; + full_window = nullptr; } } + if (dumping) { // LOCAL meshrt: X2W_MESH_DUMP_INPUTS + char file[16], note[240]; + std::snprintf(file, sizeof(file), "srv%u.bin", i); + // A root srv has no size (the binding takes up to 64 KiB): the dump takes the readable window up to 16 MiB. + // Any range is cut to its readable part (the note says so) instead of dropped. + const std::size_t wanted = srv.source == 2 ? (16u << 20) : full_bytes > (256u << 20) ? (256u << 20) : full_bytes; + const std::size_t dump_bytes = address && wanted ? static_cast<std::size_t>(readable_window(address, wanted)) : 0; + const bool readable_range = dump_bytes != 0; + std::snprintf(note, sizeof(note), "srv %u source %d(%d,%d) entry 0x%llx words %08x %08x %08x %08x address 0x%llx stride %u bound %zu%s%s%s", i, + srv.source, srv.a, srv.b, static_cast<unsigned long long>(entry), words[0], words[1], words[2], words[3], + static_cast<unsigned long long>(address), strides[i], bytes, readable_range ? "" : " (range not readable: no bytes)", + placed.reject ? " (placed: rejected, bound null)" : "", + srv.source == 2 ? " (root srv: readable window up to 16 MiB)" + : dump_bytes && dump_bytes < wanted ? " (cut to the readable part)" + : dump_bytes != bytes ? " (binding clamped to 16 MiB; dump has the full range up to 256 MiB)" : ""); + SplitRelock relock(split, 100000 + __LINE__); + mesh_dump_file(file, readable_range ? reinterpret_cast<const void*>(address) : nullptr, readable_range ? dump_bytes : 0, note); + } + if (const int r = range_watch_hit(address, bytes); r >= 0) { + SplitRelock relock(split, 100000 + __LINE__); + static LONG shown; + if (first_calls(shown, 16) && range_watch_line(r)) + log("x2w-watch 0x%llx: draw %016llx srv %u reads 0x%llx (%zu bytes) frame %ld", range_watch_address(r), tr->key, i, address, bytes, + frame_number); + range_watch_sample("draw-bind", tr->key); + } // A buffer binding that ends up without a readable range counts as a null binding with its cause. const auto count_buffer = [&](bool bound) { x2w_local::BindingFacts buffer_facts; @@ -2193,32 +4708,94 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI buffer_facts.token_magic = entry_ok && words[0] == view_token_magic; buffer_facts.token_known = buffer_token_known; buffer_facts.bound = bound; - count_null_binding(x2w_local::classify_null_binding(buffer_facts)); + count_null_binding(x2w_local::classify_null_binding(buffer_facts)); // interlocked counters: no draw_lock needed }; if (placed.reject || (placed.owner && !InterlockedCompareExchange(&placed.owner->own().refs, 0, 0))) { buffer_view(dest, nullptr, 0, 0); count_buffer(false); + ddump.bound(i, "null (placed vertex view rejected or released)", 0); continue; } if (placed.owner && bytes % 4 != 0) { // 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(padded, &offset, &chunk, nullptr) : nullptr; if (target) { std::memcpy(target, reinterpret_cast<const void*>(address), bytes); std::memset(target + bytes, 0, padded - bytes); } - buffer_view(dest, target ? upload_ring : nullptr, offset, padded); + buffer_view(dest, target ? chunk : nullptr, offset, padded); count_buffer(target != nullptr); + ddump.bound(i, target ? "copied (padded to a dword)" : "null (padded copy failed)", target ? padded : 0); continue; } if (placed.alias && address % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT == 0 && bytes) { require_state(self, placed.alias, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); buffer_view(dest, placed.alias, address - reinterpret_cast<u64>(placed.owner->own().title_memory), bytes); + ddump.bound(i, "in place (placed vertex alias)", bytes); continue; } - bool have = address && bytes && readable_window(address, bytes) >= bytes && frame_copy(address, bytes, &offset); + if (in_place && bytes >= srv_in_place_min()) { + // LOCAL stall: X2W_DRAW_SRV_IN_PLACE: a large buffer srv reads the title memory in place (the GPU sees it at + // execution time, as on the console) instead of a record-time copy compared or made on every call. + ID3D12Resource* window = full_window; + u64 at = full_offset; + const bool in_window = window || desktop_range(address, bytes, &window, &at); + if (in_window && at % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT == 0) { + // States: only a window this list already tracks is transitioned (window_read_state). An untracked window + // gets no barrier, as translated compute binds windows in place (implicit buffer promotion): the indirect + // stage and compute may have it promoted to UNORDERED_ACCESS, which a COMMON-based barrier would contradict. + if (pass.states.find(window)) window_read_state(self, window); + buffer_view(dest, window, at, bytes); + count_buffer(true); + ddump.bound(i, "in place (X2W_DRAW_SRV_IN_PLACE; the GPU reads it when the list runs)", bytes); + srvc_note(mesh ? 2 : 1, srvc_in_place, bytes); + static LONG shown; + if (first_calls(shown, 4)) + log("x2w-draw %016llx srv %u: 0x%llx (%zu bytes) bound in place at window %p +0x%llx (X2W_DRAW_SRV_IN_PLACE)", tr->key, i, + address, bytes, static_cast<void*>(window), at); + continue; + } + InterlockedIncrement64(&srvc_in_place_missed[mesh ? 2 : 1][in_window ? 1 : 0]); + static LONG missed_shown; + if (first_calls(missed_shown, 8)) + log("x2w-draw %016llx srv %u: 0x%llx (%zu bytes) not bound in place: %s; copied as before", tr->key, i, address, bytes, + in_window ? "window offset not 16-aligned" : "no single desktop window (desktop_range)"); + } + const bool gpu_written_range = address && bytes && gpu_written_overlaps(address, bytes); // its own lock + if (gpu_written_range) { + // LOCAL draw-rt: a translated draw or a GPU copy stores into this range: read it in place, not from a record-time copy. + ID3D12Resource* window = nullptr; + u64 at = 0; + if (desktop_range(address, bytes, &window, &at) && at % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT == 0) { + window_read_state(self, window); + buffer_view(dest, window, at, bytes); + count_buffer(true); + ddump.bound(i, "in place (GPU-written range; the GPU reads it when the list runs)", bytes); + InterlockedIncrement(&rt_srv_in_place); + static LONG shown; + if (first_calls(shown, 4)) + log("x2w-draw-rt %016llx srv %u: 0x%llx (%zu bytes) is written on the GPU (draw uav or copy); bound in place at window %p +0x%llx", + tr->key, i, address, bytes, static_cast<void*>(window), at); + continue; + } + InterlockedIncrement(&rt_srv_stale_copy); + } + frame_copy_class = srv.source == 0 && entry && words[0] && words[0] != view_token_magic ? 3 : mesh ? 2 : 1; + ID3D12Resource* chunk = nullptr; // LOCAL memcut: the upload ring chunk of the copy + bool have = false; + if (address && bytes && readable_window(address, bytes) >= bytes) { + const std::size_t min_bytes = draw_copy_split_min(); + const bool split_copy = !split && min_bytes && bytes >= min_bytes && !mesh && !indirect && !indirect_pending(self); + if (split) { + have = frame_copy_unlocked(address, bytes, &offset, &chunk, 100000 + __LINE__, 100001 + __LINE__); + } else { + have = (split_copy && compare_draw_copy(address, bytes, &offset, &chunk)) || frame_copy(address, bytes, &offset, &chunk); + } + } + frame_copy_class = 0; // thread_local: no lock needed // 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. @@ -2232,24 +4809,40 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return false; } if (!have && identity_for_null) { + SplitRelock relock(split, 100000 + __LINE__); // the shared identity array is rewritten here static float identity[64]; for (int k = 0; k < 64; ++k) identity[k] = (k % 16) % 5 == 0 ? 1.0f : 0.0f; address = reinterpret_cast<u64>(identity); bytes = sizeof(identity); - have = frame_copy(address, bytes, &offset); + have = frame_copy(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)) { + ddump.bound(i, have ? "copied at record time" : "null", have ? bytes : 0); + // LOCAL (video): a traced frame (X2W_D3D12_TRACE_FRAME/BUSY/QUIET) logs every draw's bindings. + if (x2w_local::first_calls(tr->logged_bindings, 8) || trace_frame_active) { char head[3 * 48 + 1] = ""; if (have) hex_text(reinterpret_cast<const void*>(address), bytes < 48 ? bytes : 48, head, sizeof(head)); log("x2w-draw %016llx srv %u buffer source %d(%d,%d): entry 0x%llx words %08x %08x %08x %08x -> address 0x%llx, %zu bytes, stride %u: %s [%s]", tr->key, i, srv.source, srv.a, srv.b, entry, words[0], words[1], words[2], words[3], address, bytes, strides[i], have ? "bound" : "NULL", head); } + // LOCAL (scene): in a traced frame, the whole constant block (up to 512 bytes), so a draw's world and + // view-projection matrices can be read. Same bytes as bound: copied at record time. + if (trace_frame_active && have && bytes > 48) { + for (std::size_t at = 0; at < bytes && at < 512; at += 256) { // 256 bytes per line (log lines hold 1.5 KiB) + char part[3 * 256 + 4] = ""; + const std::size_t n = bytes - at < 256 ? bytes - at : 256; + hex_text(reinterpret_cast<const void*>(address + at), n, part, sizeof(part)); + log("x2w-frame srv-bytes %016llx %u +%zu of %zu: %s", tr->key, i, at, bytes, part); + } + } } static LONG checks; - if ((InterlockedIncrement(&checks) & 63) == 1) check_device("translated draw views", 0); + if ((InterlockedIncrement(&checks) & 63) == 1) { + SplitRelock relock(split, 100000 + __LINE__); + check_device("translated draw views", 0); + } std::uint32_t values[32] = {}; for (std::size_t i = 0; i < tr->uds.size(); ++i) { const Translation::Ud& ud = tr->uds[i]; @@ -2257,9 +4850,117 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI : ud.kind == Translation::base_vertex ? static_cast<std::uint32_t>((indexed ? base_vertex : static_cast<INT>(start)) - vertex_first) : ud.kind == Translation::start_instance ? start_instance : ud.kind == Translation::root_constant ? ((ud.a >= 0 && ud.a < 16 && ud.b >= 0 && ud.b < 8) ? pass.constants[ud.a][ud.b] : 0) - : ud.kind == Translation::stride && ud.a >= 0 && ud.a < 32 ? strides[ud.a] + : ud.kind == Translation::stride && ud.a >= 0 && ud.a < draw_srv_limit ? strides[ud.a] + : ud.kind == Translation::buf_word3 && ud.a >= 0 && ud.a < draw_srv_limit ? word3[ud.a] + : ud.kind == Translation::uav_word3 && ud.a >= 0 && ud.a < 8 ? uav_word3[ud.a] + : ud.kind == Translation::uav_base && ud.a >= 0 && ud.a < 8 ? uav_bases[ud.a] + : ud.kind == Translation::uav_stride && ud.a >= 0 && ud.a < 8 ? uav_strides[ud.a] : ud.kind == Translation::d16_unorm16 && ud.a >= 0 && ud.a < 32 ? d16_unorm16[ud.a] - : ud.kind == Translation::desc_word3 ? formatted_buffers[ud.a].words[3] : 0; + : ud.kind == Translation::desc_word3 && ud.a >= 0 && ud.a < draw_srv_limit ? formatted_buffers[ud.a].words[3] + : ud.kind == Translation::desc_word ? draw_descword_value(pass, ud.a, ud.b, tr->key) : 0; + if (ud.kind == Translation::buf_word3) { + InterlockedIncrement(values[i] ? &rt_word3_set : &rt_word3_zero); + static LONG shown; + if (first_calls(shown, 1)) + log("x2w-draw-rt bufword3 first use: pipeline %016llx entry value %zu = word 3 of srv %d = 0x%08x", tr->key, i, ud.a, values[i]); + } + } + if (mesh && trace_frame_active) record_trace_mesh_heap(self, *tr); // LOCAL (scene): X2W_MESH_RECORD_TRACE heap reads + ddump.values(*tr, values, pass); // LOCAL lt-lead probe: X2W_DRAW_DUMP_INPUTS + if (tr->heap) ddump.heap(pass); + if (dumping) { // LOCAL meshrt: X2W_MESH_DUMP_INPUTS: the entry constants as set, their kinds, and the raw root constants + SplitRelock relock(split, 100000 + __LINE__); + char note[600]; + int used = std::snprintf(note, sizeof(note), "entry constants (root parameter 0), kind(a,b) per value:"); + for (std::size_t i = 0; i < tr->uds.size() && used > 0 && used < static_cast<int>(sizeof(note)) - 24; ++i) + used += std::snprintf(note + used, sizeof(note) - used, " %d(%d,%d)", static_cast<int>(tr->uds[i].kind), tr->uds[i].a, tr->uds[i].b); + mesh_dump_file("entry.bin", values, tr->uds.size() * sizeof(values[0]), note); + mesh_dump_file("root_constants.bin", pass.constants, sizeof(pass.constants), + "the list's 32-bit root constants as set by the title, [parameter 0-15][word 0-7] u32"); + // The heap buffers a key reads through a root constant (mesh 063500: bit 28 set = the meshlet index comes from + // a heap buffer whose descriptor index is bits 0-9). Each root constant the translation reads (a `udsrc .. + // rootconst p w` entry) with bit 28 set is taken as such a reference (ASSUMED; a word that is really something + // else gives one extra file); other root-constant words are not scanned (floats near 1 have bit 28 set). + // heap<index>_desc.bin is the 32-byte title descriptor, heap<index>.bin the buffer it names (its readable + // part, up to 256 MiB). + u64 heap_address = 0, heap_bytes = 0; + if (pass.source_view_heap) { + AcquireSRWLockShared(¬e_lock); + for (const HeapInfo& h : heap_infos()) + if (h.wrapper == pass.source_view_heap && h.title_cpu) heap_address = h.title_cpu, heap_bytes = u64{h.logical_count} * h.increment; + ReleaseSRWLockShared(¬e_lock); + } + if (!heap_address) title_view_heap(pass, &heap_address, &heap_bytes); + std::uint32_t done_index[16]; + unsigned done = 0; + for (std::size_t u = 0; u < tr->uds.size() && done < 16; ++u) { + const Translation::Ud& ud = tr->uds[u]; + if (ud.kind != Translation::root_constant || ud.a < 0 || ud.a >= 16 || ud.b < 0 || ud.b >= 8) continue; + const int p = ud.a, w = ud.b; + const std::uint32_t c = pass.constants[p][w]; + if (!(c & (1u << 28))) continue; + const std::uint32_t index = c & 0x3ff; + bool again = false; + for (unsigned k = 0; k < done; ++k) again |= done_index[k] == index; + if (again) continue; + done_index[done++] = index; + char file[32], note[300]; + const u64 slot = heap_address + u64{index} * 32; + const bool slot_ok = heap_address && u64{index} * 32 + 32 <= heap_bytes && readable_window(slot, 32) >= 32; + std::uint32_t d[8] = {}; + if (slot_ok) std::memcpy(d, reinterpret_cast<const void*>(slot), sizeof(d)); + std::snprintf(file, sizeof(file), "heap%u_desc.bin", index); + std::snprintf(note, sizeof(note), "title heap descriptor %u (root constant [%d][%d] = 0x%08x) at 0x%llx, heap 0x%llx %llu bytes%s", index, + p, w, c, static_cast<unsigned long long>(slot), static_cast<unsigned long long>(heap_address), + static_cast<unsigned long long>(heap_bytes), slot_ok ? "" : " (not readable: no bytes)"); + mesh_dump_file(file, slot_ok ? d : nullptr, slot_ok ? sizeof(d) : 0, note); + if (!slot_ok) continue; + u64 at = 0; + std::size_t n = 0; + UINT stride = 0; + const char* how = "hardware buffer descriptor"; + if (d[0] == view_token_magic) { // a view the title created (as the srv table path resolves it) + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = d[1] < view_records().size(); + if (known) record = view_records()[d[1]]; + ReleaseSRWLockShared(¬e_lock); + how = known ? "view token" : "view token, unknown view"; + if (known && record.slot == 17 && record.desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(&at, record.desc, 8); + std::memcpy(&size, record.desc + 8, 4); + n = size; + how = "view token: constant buffer view"; + } else if (known && record.slot == 18 && record.desc_bytes >= 40) { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + std::memcpy(&view, record.desc, 40); + Wrapper* resource = as_wrapper(reinterpret_cast<const void*>(record.resource)); + if (view.ViewDimension == D3D12_SRV_DIMENSION_BUFFER && resource && resource->own().title_memory) { + const bool typed_view = !view.Buffer.StructureByteStride && view.Format != DXGI_FORMAT_R32_TYPELESS; + const UINT element = view.Buffer.StructureByteStride ? view.Buffer.StructureByteStride + : typed_view ? x2w_startup::typed_buffer_format_bytes(view.Format) : 4; + at = reinterpret_cast<u64>(resource->own().title_memory) + view.Buffer.FirstElement * element; + n = std::size_t{view.Buffer.NumElements} * element; + stride = element; + how = typed_view ? "view token: typed buffer view" : "view token: buffer view"; + } else { + how = "view token: not a buffer view of title memory"; + } + } + } else { + at = d[0] | (static_cast<u64>(d[1] & 0xffff) << 32); + stride = (d[1] >> 16) & 0x3fff; + n = static_cast<std::size_t>(stride ? stride : 1) * d[2]; + } + if (n > (256u << 20)) n = 256u << 20; + if (at && n) n = static_cast<std::size_t>(readable_window(at, n)); // the readable part + const bool range_ok = at && n; + std::snprintf(file, sizeof(file), "heap%u.bin", index); + std::snprintf(note, sizeof(note), "buffer of title heap descriptor %u (%s): words %08x %08x %08x %08x, address 0x%llx stride %u%s", index, + how, d[0], d[1], d[2], d[3], static_cast<unsigned long long>(at), stride, range_ok ? "" : " (range not readable: no bytes)"); + mesh_dump_file(file, range_ok ? reinterpret_cast<const void*>(at) : nullptr, range_ok ? n : 0, note); + } } // A desktop list with no viewport or scissor draws nothing: cover the first render target unless the title set its own. if (pass.target0 && (!pass.viewport_set || !pass.scissor_set)) { @@ -2278,6 +4979,11 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI pass.default_scissor_h = target.Height; } } + // LOCAL stall: X2W_DRAW_LOCK_SPLIT: the recording tail is under draw_lock again (released below as before). + if (split) lock_draw(100000 + __LINE__); + // LOCAL draw-rt: after the srvs, which may have moved the same texture to a shader-resource state. + for (UINT j = 0; j < m; ++j) + if (uav_textures[j]) require_state(self, uav_textures[j], D3D12_RESOURCE_STATE_UNORDERED_ACCESS); ID3D12Resource* validated = nullptr; if (indirect && indexed) { validated = validate_indexed_arguments(self, list, *tr, *indirect, indexed_vertices); @@ -2288,6 +4994,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return false; } } + ddump.before(list, pass); // LOCAL lt-lead probe: X2W_DRAW_DUMP_INPUTS (GPU copies before the draw) list->SetPipelineState(pipeline); // X2W_DEPTH_STATE: the reference of the decoded stencil test is list state in D3D12. It replaces the one a // preceding OMSetStencilRef set, for draws of this pipeline only when a depth view is bound. @@ -2295,19 +5002,53 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI pass_dsv_format(*bound, pass) != DXGI_FORMAT_UNKNOWN && bound->stencil_ref != pass.stencil_reference; if (scoped_stencil_ref) list->OMSetStencilRef(bound->stencil_ref); - list->SetGraphicsRootSignature(tr->root); + // Heaps before the root signature: a directly-indexed root signature set with no heap bound is an + // error on the desktop (#1419). ID3D12DescriptorHeap* samplers = tr->samplers.heap ? pass.sampler_heap.Get() : nullptr; if (!pass.heap_set || pass.bound_sampler_heap != samplers) { x2w_startup::bind_translated_heaps(list, draw_heap, samplers); pass.heap_set = true; pass.bound_sampler_heap = samplers; } + list->SetGraphicsRootSignature(tr->root); list->SetGraphicsRoot32BitConstants(0, static_cast<UINT>(tr->uds.size()), values, 0); if (n) list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); if (samplers) list->SetGraphicsRootDescriptorTable(x2w_startup::sampler_root_parameter(n), samplers->GetGPUDescriptorHandleForHeapStart()); + if (m) list->SetGraphicsRootDescriptorTable(tr->uav_parameter, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first + n} * draw_heap_increment}); + if (tr->heap) { + // LOCAL meshrt: bounded raw views (reads past the end give 0), written per draw in this draw's ring slots. + const UINT h0 = first + n + m; + const auto cpu = [&](UINT k) { return D3D12_CPU_DESCRIPTOR_HANDLE{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{h0 + k} * draw_heap_increment}; }; + const auto gpu = [&](UINT k) { return D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{h0 + k} * draw_heap_increment}; }; + const u64 vinfo_bytes = vinfo_buffer->GetDesc().Width; + const u64 vdesc_bytes = tr->heapwords ? vdesc_buffer->GetDesc().Width : 0; + bounded_raw_srv(heap_view.window, heap_view.offset, heap_view.bytes, cpu(0)); + bounded_raw_srv(vinfo_buffer, 0, vinfo_bytes, cpu(1)); + if (tr->heapwords) bounded_raw_srv(vdesc_buffer, 0, vdesc_bytes, cpu(2)); + list->SetGraphicsRootDescriptorTable(tr->heap_parameter, gpu(0)); + list->SetGraphicsRootDescriptorTable(tr->heap_parameter + 1, gpu(1)); + if (tr->heapwords) list->SetGraphicsRootDescriptorTable(tr->vdesc_parameter, gpu(2)); + if (!tr->heap_views_logged) { + tr->heap_views_logged = true; // once per key (draw_lock held) + static LONG shown; + if (first_calls(shown, 256)) + log("x2w-draw-rt %016llx: bounded heap views: heapmem %llu bytes (title heap %llu), vinfo %llu, vdesc %llu", tr->key, + heap_view.bytes, heap_view.heap_bytes, vinfo_bytes, vdesc_bytes); + } + // The region starts at the 8 empty views before id 0 (d3d12_compute.inl fill_views). + list->SetGraphicsRootDescriptorTable(tr->heap_parameter + 2, + D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{draw_heap_size} * draw_heap_increment}); + if (InterlockedIncrement(&rt_heap_draws) == 1) + log("x2w-draw-rt first heap draw: pipeline %016llx, title heap at desktop 0x%llx, views filled %u", tr->key, heap_view.va, views_filled); + } list->IASetPrimitiveTopology(pass.topology == 5 ? D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP : D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); bool drawn = false; - if (indirect) { + gpu_time::mark(self, list, gpu_time::c_draw, tr->key, false); // LOCAL: X2W_GPU_TIME_CLASSES + if (ring_cap_refusals != ring_refusals_at_start) { + // LOCAL memcut: a copy of this draw was refused because the upload ring chain is at its cap: the draw is not + // issued (it would read zeros where its data should be). Counted in the x2w-upload ring line. + ring_draw_refused(tr->key); + } else if (indirect) { // upstream translated indirect draw (see the head of this function) if (validated) { list->IASetIndexBuffer(&indirect->indices.view); list->ExecuteIndirect(tr->indexed_signature.Get(), 1, validated, 4, validated, 0); @@ -2319,12 +5060,13 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (pass.graphics_root) list->SetGraphicsRootSignature(pass.graphics_root); pass.srv_bound = 0; drawn = true; - } else if (indexed) { + } else if (indirect_pending(self)) { drawn = indirect_draw_issue(self, list, indexed); } else if (indexed) { // LOCAL: d3d12_indirect.inl u64 offset = 0; const u64 address = index_address; const std::size_t bytes = index_total; - if (indices_ok && frame_copy(address, bytes, &offset)) { - const D3D12_INDEX_BUFFER_VIEW view{upload_ring->GetGPUVirtualAddress() + offset, static_cast<UINT>(bytes), + ID3D12Resource* chunk = nullptr; + if (indices_ok && frame_copy(address, bytes, &offset, &chunk)) { + const D3D12_INDEX_BUFFER_VIEW view{chunk->GetGPUVirtualAddress() + offset, static_cast<UINT>(bytes), index_bytes == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; list->IASetIndexBuffer(&view); const auto red_samples = red_producer_draw_before(self, list, "translated-draw", tr->key); @@ -2338,11 +5080,27 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI red_producer_draw_after(self, red_samples); drawn = true; } + gpu_time::mark(self, list, gpu_time::c_draw, tr->key, true, !drawn); + if (drawn && m) { + // LOCAL draw-rt: the stores complete before later work reads or writes the same memory. + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + if (InterlockedIncrement(&rt_uav_draws) == 1) + log("x2w-draw-rt first draw with uavs: pipeline %016llx, %u uavs, %u srvs", tr->key, m, n); + } if (scoped_stencil_ref) list->OMSetStencilRef(pass.stencil_reference); if (drawn && !indirect) draw_dump_after(self, list, tr->key, count); + if (drawn) ddump.after(list, pass); // LOCAL lt-lead probe: X2W_DRAW_DUMP_INPUTS + else ddump.not_issued(ring_cap_refusals != ring_refusals_at_start ? "upload ring at its cap" : "index data not readable"); ReleaseSRWLockExclusive(&draw_lock); if (indirect) return drawn; - if (first_calls(tr->logged_draws, 10) || (count > 100 && first_calls(tr->logged_large, 12))) { + if (trace_frame_active && pass.target0) { + const D3D12_RESOURCE_DESC target = pass.target0->GetDesc(); + log("x2w-frame translated draw %016llx count %u: target0 %p %llux%u format %d, %u targets", tr->key, count, + static_cast<void*>(pass.target0), target.Width, target.Height, target.Format, pass.target_count); + } + if (x2w_local::first_calls(tr->logged_draws, 10) || trace_frame_active || (count > 100 && x2w_local::first_calls(tr->logged_large, 12))) { char indices[3 * 24 + 1] = ""; if (indexed && pass.ib.BufferLocation) hex_text(reinterpret_cast<const void*>(pass.ib.BufferLocation + u64{start} * 2), 24, indices, sizeof(indices)); log("x2w-draw %s(%u, %u, start %u, base %d) pipeline %016llx topology 0x%x -> %s; entry [%x %x %x %x %x %x]; ib 0x%llx+%u fmt %d [%s]; " @@ -2351,12 +5109,15 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI pass.ib.SizeInBytes, pass.ib.Format, indices, pass.vb[0].BufferLocation, pass.vb[0].SizeInBytes, pass.vb[0].StrideInBytes, pass.target_count); } + if (!drawn) last_draw_why = "skipped (index data)"; return drawn; } bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance) { - return draw_translated(self, indexed, count, instances, start, base_vertex, start_instance, nullptr); + const bool done = draw_translated(self, indexed, count, instances, start, base_vertex, start_instance, nullptr); + if (!done) draw_dump_note_not_drawn(last_draw_key, last_draw_why); // LOCAL lt-lead probe: X2W_DRAW_DUMP_INPUTS + return done; } const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* signature, ID3D12Resource* argument, u64 offset, @@ -2437,7 +5198,7 @@ void __stdcall list_table(Wrapper* self, UINT parameter, u64 gpu_handle) } // List slot 35 (desktop 31 + 4), SetComputeRootDescriptorTable(parameter, GPU handle). Recorded only for a later // Dispatch; slot 33 keeps the desktop compute root bind. -void __stdcall list_compute_table(Wrapper* self, UINT parameter, u64 gpu_handle) +void __stdcall list_compute_table_desktop(Wrapper* self, UINT parameter, u64 gpu_handle) { static LONG dropped; if (!self->own().list_open) return; @@ -2461,6 +5222,12 @@ void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, co count <= 8 - offset && offset + count <= (*pass.root)[parameter].constants_count) pass.constant_words_bound[parameter] |= static_cast<unsigned char>(((1u << count) - 1) << offset); } +// LOCAL draw-rt: list slot 46 (desktop 42 + 4), SetGraphicsRootUnorderedAccessView(parameter, title GPU address), +// kept for `uav <i> buf root <parameter> 0`. Nothing else used this slot (it was a no-op). +void __stdcall list_root_uav(Wrapper* self, UINT parameter, u64 address) +{ + if (parameter < 16) pass_of(self).root_address[parameter] = address; +} // List slot 47 (desktop 43 + 4), IASetIndexBuffer(view). void __stdcall list_index_buffer(Wrapper* self, const D3D12_INDEX_BUFFER_VIEW* view) { @@ -2480,5 +5247,221 @@ void __stdcall list_vertex_buffers(Wrapper* self, UINT start, UINT count, const // List slot 13, DrawIndexedInstanced(index count, instances, start index, base vertex, start instance). void __stdcall list_draw_indexed(Wrapper* self, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance) { - InterlockedIncrement(draw_translated(self, true, count, instances, start, base_vertex, start_instance) ? &translated_draws : &untranslated_draws); + const bool done = draw_translated(self, true, count, instances, start, base_vertex, start_instance); + InterlockedIncrement(done ? &translated_draws : &untranslated_draws); + // LOCAL (scene): restored from f5e0f425 (lost in a merge): in a traced frame, note the target for the + // X2W_D3D12_TRACE_TARGETS read-back and log every draw, also the ones not drawn, with key and reason. + if (trace_frame_active) { + const Pass& pass = pass_of(self); + note_traced_target(self, pass.target0, done); + const D3D12_RESOURCE_DESC rd = pass.target0 ? pass.target0->GetDesc() : D3D12_RESOURCE_DESC{}; + log("x2w-frame draw-indexed %u %s target %p %llux%u fmt %d key %016llx %s", count, done ? "drawn" : "NOT drawn", + static_cast<void*>(pass.target0), static_cast<unsigned long long>(rd.Width), rd.Height, rd.Format, last_draw_key, + done ? "" : (last_draw_why ? last_draw_why : "draw failed")); + } +} + +// LOCAL draw-rt: command-list slot 15, CopyBufferRegion, on the GPU at its place in the list +// (X2W_D3D12_COPY_BUFFER=gpu; installed by d3d12_copy_buffer.inl, which keeps the record-time copy as fallback). +// Source and destination are resolved to the in-place windows (desktop_range), so the copy reads what earlier GPU +// work in the submission stored and later GPU work sees the copied bytes in the title's own pages. The copy is a +// small compute pass with both windows as raw root UAVs on direct/compute lists, not CopyBufferRegion: +// - compute and indirect use windows as (implicitly promoted) UAVs; UAV is the state that agrees with them; +// - source and destination often sit in the same 256 MiB window, which cannot be COPY_SOURCE and COPY_DEST at once. +// The windows' states are tracked in the list's Pass states (require_state; back to COMMON at Close), as are the +// windows of draw UAVs and in-place srvs, so copy -> draw (in-place read) -> copy -> draw names correct +// before-states. Order: null UAV barrier, copy, null UAV barrier. On a copy-type list: a real CopyBufferRegion with +// the windows in COPY_SOURCE / COPY_DEST (one window for both: fallback). +// The destination range is registered as GPU-written: translated draws read it in place from then on, not from +// a record-time snapshot (which is stale by construction). +void __stdcall list_copy_buffer(Wrapper* self, Wrapper* dest, u64 dest_offset, Wrapper* source, u64 source_offset, u64 bytes); + +// LOCAL (video): X2W_D3D12_COPY_WATCH=<hex title address>[,<hex>...] (up to 4): every CopyBufferRegion +// whose destination range overlaps [address, address + 0x100) is logged with its outcome (at most 64 +// lines per address), whatever the copy-log budget says. +void copy_watch_note(const char* path, u64 to, u64 from, u64 bytes, const char* outcome) +{ + static u64 watched[4]; + static int count = [] { + char text[128]{}; + int n = 0; + if (GetEnvironmentVariableA("X2W_D3D12_COPY_WATCH", text, sizeof(text))) { + for (char* at = text; *at && n < 4;) { + char* end = nullptr; + const u64 value = std::strtoull(at, &end, 16); + if (end == at) break; + if (value) watched[n++] = value; + at = *end == ',' ? end + 1 : end; + } + log("x2w-copy X2W_D3D12_COPY_WATCH: %d address(es) watched (%s)", n, text); + } + return n; + }(); + static LONG lines[4]; + for (int i = 0; i < count; ++i) + if (to && bytes && to < watched[i] + 0x100 && watched[i] < to + bytes && first_calls(lines[i], 64)) { + unsigned char head[32]{}; + char text[3 * 32 + 1] = ""; + if (from && x2w_local::readable(reinterpret_cast<const void*>(from), bytes < 32 ? bytes : 32)) { + std::memcpy(head, reinterpret_cast<const void*>(from), bytes < 32 ? bytes : 32); + hex_text(head, bytes < 32 ? bytes : 32, text, sizeof(text)); + } + log("x2w-copy watch 0x%llx: %s copy to 0x%llx from 0x%llx bytes 0x%llx frame %ld: %s; source [%s]", watched[i], path, to, from, + bytes, frame_number, outcome, text); + } +} +bool copy_title_bytes(unsigned char* dest, const unsigned char* source, std::size_t bytes) noexcept; // d3d12_copy_buffer.inl +void note_issued_dispatch(ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z, bool indirect); // d3d12_xs_device.cpp (DRED report) +extern thread_local u64 cx_issue_key; +extern thread_local char cx_issue_path; +constexpr char copy_gpu_source[] = R"( +RWByteAddressBuffer from : register(u0); +RWByteAddressBuffer to : register(u1); +cbuffer c : register(b0) { uint from_at; uint to_at; uint words; uint step; }; +[numthreads(64, 1, 1)] void cs(uint3 id : SV_DispatchThreadID) +{ + for (uint i = id.x; i < words; i += step) to.Store(to_at + i * 4, from.Load(from_at + i * 4)); +} +)"; +ID3D12RootSignature* copy_gpu_root; +ID3D12PipelineState* copy_gpu_pso; +bool ensure_copy_gpu() +{ + static SRWLOCK lock = SRWLOCK_INIT; + static bool failed; + if (copy_gpu_pso) return true; + AcquireSRWLockExclusive(&lock); + if (!copy_gpu_pso && !failed) { + ID3D12Device* device = device_of(the_device); + ID3DBlob *code = nullptr, *errors = nullptr, *serialized = nullptr; + HRESULT hr = D3DCompile(copy_gpu_source, sizeof(copy_gpu_source) - 1, "copy_gpu", nullptr, nullptr, "cs", "cs_5_0", + D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, &code, &errors); + if (FAILED(hr) && errors) log("x2w-copy-gpu compile: %.400s", static_cast<const char*>(errors->GetBufferPointer())); + D3D12_ROOT_PARAMETER params[3]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[0].Descriptor.ShaderRegister = 0; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor.ShaderRegister = 1; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[2].Constants.Num32BitValues = 4; + for (auto& p : params) p.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC root_desc{3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + if (SUCCEEDED(hr)) hr = D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, nullptr); + ID3D12RootSignature* root = nullptr; + if (SUCCEEDED(hr)) hr = device->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), IID_PPV_ARGS(&root)); + ID3D12PipelineState* pso = nullptr; + if (SUCCEEDED(hr)) { + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root; + desc.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + hr = device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso)); + } + if (code) code->Release(); + if (errors) errors->Release(); + if (serialized) serialized->Release(); + if (SUCCEEDED(hr)) { + copy_gpu_root = root; + copy_gpu_pso = pso; + } else { + if (root) root->Release(); + failed = true; + } + log("x2w-copy-gpu copy pipeline: 0x%08lx", static_cast<unsigned long>(hr)); + } + ReleaseSRWLockExclusive(&lock); + return copy_gpu_pso != nullptr; +} + +void __stdcall list_copy_buffer_gpu(Wrapper* self, Wrapper* dest, u64 dest_offset, Wrapper* source, u64 source_offset, u64 bytes) +{ + auto* const to = dest && dest->own().kind == resource_kind ? static_cast<unsigned char*>(dest->own().title_memory) : nullptr; + auto* const from = source && source->own().kind == resource_kind ? static_cast<const unsigned char*>(source->own().title_memory) : nullptr; + ID3D12GraphicsCommandList* list = recording(self); + const u64 to_address = to ? reinterpret_cast<u64>(to) + dest_offset : 0; + const u64 from_address = from ? reinterpret_cast<u64>(from) + source_offset : 0; + ID3D12Resource *to_window = nullptr, *from_window = nullptr; + u64 to_at = 0, from_at = 0; + int reason = -1; + if (!list) reason = cf_no_list; + else if (!to || !from) reason = cf_no_title_memory; + else if (!bytes || bytes > (u64{256} << 20) || dest_offset > (u64{1} << 40) || source_offset > (u64{1} << 40)) reason = cf_range; + else if ((to_address | from_address | bytes) & 3) reason = cf_unaligned; + else if (!desktop_range(to_address, bytes, &to_window, &to_at)) reason = cf_dest_unresolved; + else if (!desktop_range(from_address, bytes, &from_window, &from_at)) reason = cf_source_unresolved; + else if (to_window == from_window && to_at < from_at + bytes && from_at < to_at + bytes) reason = cf_overlap; + const bool copy_list = list && list->GetType() == D3D12_COMMAND_LIST_TYPE_COPY; + if (reason < 0 && copy_list && to_window == from_window) reason = cf_copy_list_same; + else if (reason < 0 && !copy_list && !ensure_copy_gpu()) reason = cf_no_pipeline; + static LONG shown; + if (reason >= 0) { + InterlockedIncrement(&cg_fallback[reason]); + if (first_calls(shown, 16)) + log("x2w-copy-gpu CopyBufferRegion title %p <- %p bytes 0x%llx: record-time fallback: %s", static_cast<void*>(to ? to + dest_offset : nullptr), + static_cast<const void*>(from ? from + source_offset : nullptr), bytes, copy_fallback_names[reason]); + list_copy_buffer(self, dest, dest_offset, source, source_offset, bytes); + return; + } + // A source the GPU never wrote (CPU-filled upload memory) is also copied at record time, so the paths that read + // the destination's title memory when the title records (vertex/index ring copies, misaligned srvs, texture + // uploads) see what X2W_D3D12_COPY_BUFFER=1 gave them; the GPU copy then writes the same bytes in list order. + lock_draw(100000 + __LINE__); + const bool source_gpu_written = gpu_written_overlaps(from_address, bytes); + ReleaseSRWLockExclusive(&draw_lock); + copy_watch_note("gpu", to_address, from_address, bytes, source_gpu_written ? "GPU copy (source GPU-written)" : "GPU copy + record-time copy"); + if (!source_gpu_written && x2w_local::readable(from + source_offset, static_cast<std::size_t>(bytes)) && + copy_title_bytes(to + dest_offset, from + source_offset, static_cast<std::size_t>(bytes))) + InterlockedIncrement(&cg_record_too); + if (copy_list) { + // A copy-type list holds no compute or draw work: windows there are only ever moved by these copies, so the + // tracked states are exact (back to COMMON at Close). + require_state(self, from_window, D3D12_RESOURCE_STATE_COPY_SOURCE); + require_state(self, to_window, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(to_window, to_at, from_window, from_at, bytes); + InterlockedIncrement(&cg_copy_list); + } else { + // Both windows in UNORDERED_ACCESS in this list's tracked states (from whatever this list's draws and copies + // left them in; moved back to COMMON at Close). + require_state(self, from_window, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + require_state(self, to_window, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + // Root UAVs at 256-byte steps inside the windows; the remainder goes to the shader as byte offsets. + const u64 to_base = to_at & ~u64{255}, from_base = from_at & ~u64{255}; + const std::uint32_t words = static_cast<std::uint32_t>(bytes / 4); + const UINT groups = words / 64 + 1 > 4096 ? 4096 : words / 64 + 1; + const std::uint32_t values[4] = {static_cast<std::uint32_t>(from_at - from_base), static_cast<std::uint32_t>(to_at - to_base), words, groups * 64}; + D3D12_RESOURCE_BARRIER uav{}; + uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &uav); + list->SetPipelineState(copy_gpu_pso); + list->SetComputeRootSignature(copy_gpu_root); + list->SetComputeRootUnorderedAccessView(0, from_window->GetGPUVirtualAddress() + from_base); + list->SetComputeRootUnorderedAccessView(1, to_window->GetGPUVirtualAddress() + to_base); + list->SetComputeRoot32BitConstants(2, 4, values, 0); + // The copy pass is a Dispatch op in DRED too; record it (path 'b', key 0) so the report's Dispatch op count matches. + const u64 issue_key = cx_issue_key; + const char issue_path = cx_issue_path; + cx_issue_key = 0; + cx_issue_path = 'b'; + note_issued_dispatch(list, groups, 1, 1, false); + cx_issue_key = issue_key; + cx_issue_path = issue_path; + gpu_time::mark(self, list, gpu_time::c_copy, bytes, false); // LOCAL: X2W_GPU_TIME_CLASSES (key: byte count) + list->Dispatch(groups, 1, 1); + gpu_time::mark(self, list, gpu_time::c_copy, bytes, true); + list->ResourceBarrier(1, &uav); + // Graphics work after this point: a title pipeline with a desktop pipeline expects its state back (translated + // draws and compute set theirs on every call). + const Pass& pass = pass_of(self); + if (pass.pipeline_real && pass.pipeline) list->SetPipelineState(static_cast<ID3D12PipelineState*>(pass.pipeline->own().real)); + } + lock_draw(100000 + __LINE__); + note_gpu_written(to_address, bytes); + report_draw_rt(); + ReleaseSRWLockExclusive(&draw_lock); + InterlockedIncrement(&cg_gpu); + if (to_window == from_window) InterlockedIncrement(&cg_same_window); + InterlockedAdd64(&cg_bytes, static_cast<LONG64>(bytes)); + if (first_calls(shown, 16)) + log("x2w-copy-gpu CopyBufferRegion title %p <- %p bytes 0x%llx: on the GPU, window %p +0x%llx <- window %p +0x%llx", + static_cast<void*>(to + dest_offset), static_cast<const void*>(from + source_offset), bytes, static_cast<void*>(to_window), to_at, + static_cast<void*>(from_window), from_at); } diff --git a/src/startup_stubs/d3d12_gpu_time.inl b/src/startup_stubs/d3d12_gpu_time.inl new file mode 100644 index 0000000000..c9f5a31f54 --- /dev/null +++ b/src/startup_stubs/d3d12_gpu_time.inl @@ -0,0 +1,365 @@ +// LOCAL: X2W_CX_GPU_TIME=1, GPU time of translated compute dispatches, per compute key. +// +// Each list that records a timed item gets a timestamp query heap (2 queries per item, up to cap() items per +// recording) and two readback buffers. EndQuery brackets each item. At Close the queries are resolved into the +// readback buffer of this recording (the two alternate, so a list resubmitted once before its result is read +// does not overwrite it). After ExecuteCommandLists, one Signal on a fence of that queue (one fence per queue, +// so completed values only grow) marks the submission. The results are read once the fence passes: at a later +// submit or list Reset, never with a CPU wait. Every 300 frames, the ten keys with the most GPU time are logged. +// +// LOCAL stall: X2W_GPU_TIME_CLASSES=1 (implies X2W_CX_GPU_TIME) also times translated draws (by pipeline key), +// slot-62 desktop compute dispatches (by compute key), GPU buffer copies (X2W_D3D12_COPY_BUFFER=gpu) and each +// whole recording of a direct or compute list (from Reset to Close, keyed by list type). Per recording, the +// list span minus the items inside it is "untimed": barriers, state changes and work of the title's own +// desktop pipelines that is not bracketed. Extra lines "x2w-gpu time ..." per 300 frames; the X2W_CX_GPU_TIME +// lines keep their format. +// +// What a value means: the time between the timestamp before and after the item on the GPU timeline. Each +// translated dispatch ends in a UAV barrier, so dispatches of one list run one after another. Draws are not +// separated by barriers: their intervals overlap and their sum can exceed the list span. Work of other lists +// or queues can still overlap any item and is then counted too, so a per-key total is an upper bound. + +namespace gpu_time { +// enum Class (c_cx, c_draw, c_c62, c_copy, c_list, c_count) is declared with the forward declarations in d3d12_xs_device.cpp +const char* const class_names[c_count] = {"cx", "draw", "c62", "copy", "list"}; +struct Item { u64 key; int cls; }; +struct ListState { + ID3D12QueryHeap* heap = nullptr; + ID3D12Resource* readback[2] = {}; + std::vector<Item> items; // this recording, in query order (item i: queries 2i, 2i + 1) + int open = -1; // the item whose end is still missing (cx, draw, c62, copy) + int open_list = -1; // the recording span whose end is still missing + int slot = 0; // readback buffer of this recording + int type = 0; // desktop list type (direct 0, compute 2) + bool resolved = false; // resolved at Close, not yet submitted + struct Pending { + std::vector<Item> items; + ID3D12Fence* fence = nullptr; + UINT64 value = 0, frequency = 0; + int slot = 0; + int type = 0; + }; + Pending pending[2]; // per readback buffer + bool has_pending[2] = {}; + bool failed = false; +}; +struct QueueFence { ID3D12Fence* fence = nullptr; UINT64 value = 0; }; +struct KeyTime { double total_ms = 0, max_ms = 0; LONG64 calls = 0, over_1ms = 0; }; + +SRWLOCK lock = SRWLOCK_INIT; +std::unordered_map<Wrapper*, ListState>& lists() { static std::unordered_map<Wrapper*, ListState> m; return m; } +std::unordered_map<ID3D12CommandQueue*, QueueFence>& fences() { static std::unordered_map<ID3D12CommandQueue*, QueueFence> m; return m; } +std::unordered_map<u64, KeyTime>& times(int cls) { static std::unordered_map<u64, KeyTime> m[c_count]; return m[cls]; } +double untimed_ms[4], span_ms[4], cx_ms[4]; // by list type (direct 0, bundle 1, compute 2, copy 3) +LONG64 spans[4], cx_calls[4]; +LONG timed, over_cap, overwritten, harvested, failures; + +bool classes() +{ + static const bool enabled = [] { + const bool e = x2w_local::env_on("X2W_GPU_TIME_CLASSES"); + if (e) log("x2w-gpu time X2W_GPU_TIME_CLASSES: also timing translated draws, slot-62 dispatches, GPU copies and list spans"); + return e; + }(); + return enabled; +} +bool on() +{ + static const bool enabled = [] { + const bool e = x2w_local::env_on("X2W_CX_GPU_TIME") || classes(); + if (e) log("x2w-cx X2W_CX_GPU_TIME: timestamps around translated dispatches, read back after the queue's fence passes"); + return e; + }(); + return enabled; +} +UINT cap() { return classes() ? 4096 : 2048; } // items per recording + +bool ensure(ListState& s, ID3D12GraphicsCommandList* list) +{ + if (s.heap) return true; + if (s.failed) return false; + const D3D12_COMMAND_LIST_TYPE type = list->GetType(); + ID3D12Device* device = device_of(the_device); + D3D12_QUERY_HEAP_DESC qd{D3D12_QUERY_HEAP_TYPE_TIMESTAMP, 2 * cap(), 0}; + HRESULT hr = (type == D3D12_COMMAND_LIST_TYPE_DIRECT || type == D3D12_COMMAND_LIST_TYPE_COMPUTE) + ? device->CreateQueryHeap(&qd, IID_PPV_ARGS(&s.heap)) : E_NOTIMPL; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = u64{2} * cap() * 8; + buffer.Height = 1; + buffer.DepthOrArraySize = 1; + buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + for (int i = 0; i < 2 && SUCCEEDED(hr); ++i) + hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&s.readback[i])); + if (SUCCEEDED(hr)) { + s.type = static_cast<int>(type) & 3; + return true; + } + if (s.heap) s.heap->Release(), s.heap = nullptr; + for (auto*& r : s.readback) + if (r) r->Release(), r = nullptr; + s.failed = true; + InterlockedIncrement(&failures); + static LONG logged; + if (first_calls(logged, 4)) log("x2w-cx gpu time: query heap or readback for a list type %d failed 0x%08lx", static_cast<int>(type), static_cast<unsigned long>(hr)); + return false; +} + +void add(int cls, u64 key, double ms) +{ + KeyTime& t = times(cls)[key]; + t.total_ms += ms; + ++t.calls; + if (ms > 1.0) ++t.over_1ms; + if (ms > t.max_ms) t.max_ms = ms; +} + +// Reads every pending result whose fence has passed (lock held). +void harvest_locked() +{ + for (auto& entry : lists()) { + ListState& s = entry.second; + for (int b = 0; b < 2; ++b) { + if (!s.has_pending[b]) continue; + ListState::Pending& p = s.pending[b]; + if (p.fence->GetCompletedValue() < p.value) continue; + s.has_pending[b] = false; + const std::size_t n = p.items.size(); + const D3D12_RANGE range{0, n * 16}; + void* mapped = nullptr; + if (n && p.frequency && SUCCEEDED(s.readback[b]->Map(0, &range, &mapped))) { + const auto* ticks = static_cast<const UINT64*>(mapped); + double inside = 0, span = -1; + int type = 0; + for (std::size_t i = 0; i < n; ++i) { + if (ticks[2 * i + 1] < ticks[2 * i]) continue; // not written or wrapped + const double ms = static_cast<double>(ticks[2 * i + 1] - ticks[2 * i]) * 1000.0 / static_cast<double>(p.frequency); + add(p.items[i].cls, p.items[i].key, ms); + if (p.items[i].cls == c_list) span = ms, type = static_cast<int>(p.items[i].key & 3); + else inside += ms; + if (p.items[i].cls == c_cx) cx_ms[p.type] += ms, ++cx_calls[p.type]; + } + if (span >= 0) { + span_ms[type] += span; + untimed_ms[type] += span > inside ? span - inside : 0; + ++spans[type]; + } + const D3D12_RANGE none{0, 0}; + s.readback[b]->Unmap(0, &none); + InterlockedIncrement(&harvested); + } + } + } +} + +// Opens (after == false) or closes the item of class `cls`; `drop` on the close forgets the item (nothing was +// recorded between the two marks). +void mark(Wrapper* self, ID3D12GraphicsCommandList* list, int cls, u64 key, bool after, bool drop) +{ + if (!on() || (cls != c_cx && !classes()) || !list) return; + AcquireSRWLockExclusive(&lock); + ListState& s = lists()[self]; + if (!after) { + if (s.open >= 0) { + // an item without its end (should not happen): forget it + if (s.open == static_cast<int>(s.items.size()) - 1) s.items.pop_back(); + s.open = -1; + } + if (s.items.size() >= cap()) { + InterlockedIncrement(&over_cap); + } else if (ensure(s, list)) { + list->EndQuery(s.heap, D3D12_QUERY_TYPE_TIMESTAMP, static_cast<UINT>(2 * s.items.size())); + s.open = static_cast<int>(s.items.size()); + s.items.push_back({key, cls}); + } + } else if (s.open >= 0 && s.items[s.open].cls == cls) { + if (drop && s.open == static_cast<int>(s.items.size()) - 1) { + s.items.pop_back(); // its begin query index is reused by the next item + } else { + list->EndQuery(s.heap, D3D12_QUERY_TYPE_TIMESTAMP, static_cast<UINT>(2 * s.open + 1)); + InterlockedIncrement(&timed); + } + s.open = -1; + } + ReleaseSRWLockExclusive(&lock); +} + +// Around the Dispatch of execute_translated (d3d12_compute.inl). +void dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, bool after) { mark(self, list, c_cx, key, after, false); } + +// list_reset, after the desktop Reset: the recording span begins (X2W_GPU_TIME_CLASSES). +void list_begin(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + if (!on() || !classes() || !list) return; + const D3D12_COMMAND_LIST_TYPE type = list->GetType(); + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_COMPUTE) return; + AcquireSRWLockExclusive(&lock); + ListState& s = lists()[self]; + if (s.items.empty() && ensure(s, list)) { + list->EndQuery(s.heap, D3D12_QUERY_TYPE_TIMESTAMP, 0); + s.open_list = 0; + s.items.push_back({static_cast<u64>(type), c_list}); + } + ReleaseSRWLockExclusive(&lock); +} + +// list_close, before the desktop Close. +void close(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + if (!on()) return; + AcquireSRWLockExclusive(&lock); + const auto found = lists().find(self); + if (found != lists().end() && found->second.heap) { + ListState& s = found->second; + if (s.open >= 0) { // a begin without its end + if (s.open == static_cast<int>(s.items.size()) - 1) s.items.pop_back(); + s.open = -1; + } + if (s.open_list >= 0) { + list->EndQuery(s.heap, D3D12_QUERY_TYPE_TIMESTAMP, static_cast<UINT>(2 * s.open_list + 1)); + s.open_list = -1; + } + if (!s.items.empty()) { + s.slot = s.has_pending[0] && !s.has_pending[1] ? 1 : 0; + list->ResolveQueryData(s.heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, static_cast<UINT>(2 * s.items.size()), s.readback[s.slot], 0); + s.resolved = true; + } + } + ReleaseSRWLockExclusive(&lock); +} + +// queue_execute, after the desktop ExecuteCommandLists. +void submitted(ID3D12CommandQueue* queue, const std::vector<Wrapper*>& wrappers) +{ + if (!on()) return; + AcquireSRWLockExclusive(&lock); + std::vector<ListState*> marked; + for (Wrapper* w : wrappers) { + const auto found = lists().find(w); + if (found != lists().end() && found->second.resolved && !found->second.items.empty()) marked.push_back(&found->second); + } + if (!marked.empty()) { + QueueFence& f = fences()[queue]; + if (!f.fence && FAILED(device_of(the_device)->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&f.fence)))) f.fence = nullptr; + UINT64 frequency = 0; + if (f.fence && SUCCEEDED(queue->GetTimestampFrequency(&frequency)) && SUCCEEDED(queue->Signal(f.fence, ++f.value))) { + for (ListState* s : marked) { + const int b = s->slot; + if (s->has_pending[b]) InterlockedIncrement(&overwritten); + s->pending[b] = {s->items, f.fence, f.value, frequency, b, s->type}; + s->has_pending[b] = true; + } + } else { + InterlockedIncrement(&failures); + } + } + harvest_locked(); + ReleaseSRWLockExclusive(&lock); + // Test knob (off by default): X2W_GPU_TIME_REPORT_SUBMITS=<n> also writes the report every n submissions, for + // fixtures that never present. It first waits (at most 5 s) for this queue's timing fence so the report holds + // this submission's results; that wait is why the knob is for fixtures only. + static const LONG every = [] { + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_GPU_TIME_REPORT_SUBMITS", value, sizeof(value)); + return n && n < sizeof(value) ? static_cast<LONG>(std::atoi(value)) : 0L; + }(); + static LONG submits; + if (every > 0 && InterlockedIncrement(&submits) % every == 0) { + AcquireSRWLockExclusive(&lock); + const auto found = fences().find(queue); + ID3D12Fence* fence = found != fences().end() ? found->second.fence : nullptr; + const UINT64 value = fence ? found->second.value : 0; + ReleaseSRWLockExclusive(&lock); + if (fence && fence->GetCompletedValue() < value) { + if (HANDLE done = CreateEventA(nullptr, FALSE, FALSE, nullptr)) { + if (SUCCEEDED(fence->SetEventOnCompletion(value, done))) WaitForSingleObject(done, 5000); + CloseHandle(done); + } + } + report(); + } +} + +// list_reset: a new recording. +void reset(Wrapper* self) +{ + if (!on()) return; + AcquireSRWLockExclusive(&lock); + harvest_locked(); + const auto found = lists().find(self); + if (found != lists().end()) { + found->second.items.clear(); + found->second.open = found->second.open_list = -1; + found->second.resolved = false; + } + ReleaseSRWLockExclusive(&lock); +} + +std::vector<std::pair<u64, KeyTime>> sorted(std::unordered_map<u64, KeyTime>& m) +{ + std::vector<std::pair<u64, KeyTime>> all(m.begin(), m.end()); + m.clear(); + std::sort(all.begin(), all.end(), [](const auto& a, const auto& b) { return a.second.total_ms > b.second.total_ms; }); + return all; +} + +// Every 300 frames. +void report() +{ + if (!on()) return; + std::vector<std::pair<u64, KeyTime>> all[c_count]; + double untimed[4], span[4], cx_by_type[4]; + LONG64 span_count[4], cx_count_by_type[4]; + AcquireSRWLockExclusive(&lock); + harvest_locked(); + for (int c = 0; c < c_count; ++c) all[c] = sorted(times(c)); + for (int t = 0; t < 4; ++t) { + untimed[t] = untimed_ms[t], span[t] = span_ms[t], span_count[t] = spans[t], untimed_ms[t] = span_ms[t] = 0, spans[t] = 0; + cx_by_type[t] = cx_ms[t], cx_count_by_type[t] = cx_calls[t], cx_ms[t] = 0, cx_calls[t] = 0; + } + ReleaseSRWLockExclusive(&lock); + double total = 0; + LONG64 calls = 0; + for (const auto& entry : all[c_cx]) total += entry.second.total_ms, calls += entry.second.calls; + char line[2048]; + int n = std::snprintf(line, sizeof(line), "x2w-cx gpu time (300 frames): %.1f ms in %lld timed dispatches of %zu keys; top:", total, calls, + all[c_cx].size()); + for (std::size_t i = 0; i < all[c_cx].size() && i < 10; ++i) + n += std::snprintf(line + n, sizeof(line) - n, " %016llx %.2f ms/%lld (max %.3f)", all[c_cx][i].first, all[c_cx][i].second.total_ms, + all[c_cx][i].second.calls, all[c_cx][i].second.max_ms); + log("%s", line); + log("x2w-cx gpu time counters: timed %ld, over %u per list %ld, results read %ld, overwritten before read %ld, failures %ld", + InterlockedExchange(&timed, 0), cap(), InterlockedExchange(&over_cap, 0), InterlockedExchange(&harvested, 0), + InterlockedExchange(&overwritten, 0), InterlockedExchange(&failures, 0)); + // LOCAL stall: which queue type the timed dispatches ran on (a compute-queue dispatch shares the GPU with the + // direct queue's work, which its interval can absorb) + log("x2w-cx gpu time by list type: direct %.1f ms/%lld, compute %.1f ms/%lld", cx_by_type[0], cx_count_by_type[0], cx_by_type[2], + cx_count_by_type[2]); + if (!classes()) return; + n = std::snprintf(line, sizeof(line), "x2w-gpu time (300 frames) by class:"); + for (int c = 0; c < c_list; ++c) { + double t = 0, over = 0; + LONG64 k = 0; + for (const auto& entry : all[c]) t += entry.second.total_ms, k += entry.second.calls, over += static_cast<double>(entry.second.over_1ms); + n += std::snprintf(line + n, sizeof(line) - n, " %s %.1f ms/%lld (%.0f over 1 ms, %zu keys);", class_names[c], t, k, over, all[c].size()); + } + static const char* const type_names[4] = {"direct", "bundle", "compute", "copy"}; + for (int t = 0; t < 4; ++t) + if (span_count[t]) + n += std::snprintf(line + n, sizeof(line) - n, " %s lists %.1f ms/%lld spans, untimed inside %.1f ms;", type_names[t], span[t], span_count[t], + untimed[t]); + log("%s", line); + for (int c = 0; c < c_list; ++c) { + if (all[c].empty()) continue; + n = std::snprintf(line, sizeof(line), "x2w-gpu time %s top (ms/calls, max, over 1 ms):", class_names[c]); + for (std::size_t i = 0; i < all[c].size() && i < 10; ++i) + n += std::snprintf(line + n, sizeof(line) - n, " %016llx %.2f/%lld (max %.3f, %lld)", all[c][i].first, all[c][i].second.total_ms, + all[c][i].second.calls, all[c][i].second.max_ms, all[c][i].second.over_1ms); + log("%s", line); + } +} +} // namespace gpu_time diff --git a/src/startup_stubs/d3d12_heap_raw.inl b/src/startup_stubs/d3d12_heap_raw.inl new file mode 100644 index 0000000000..fe3bfe6fcb --- /dev/null +++ b/src/startup_stubs/d3d12_heap_raw.inl @@ -0,0 +1,896 @@ + +bool heap_raw_on() +{ + static const bool on = [] { + char v[8] = ""; + const DWORD n = GetEnvironmentVariableA("X2W_HEAP_RAW", v, sizeof v); + const bool off = n && n < sizeof v && v[0] == '0'; + log("x2w-heapraw X2W_HEAP_RAW=%s: raw V#s in the title heap %s for `heapraw 1` compute translations", off ? "0" : "1 (default)", + off ? "bind the empty view (off)" : "resolve through the table of the runtime's own V#s"); + return !off; + }(); + return on; +} + +struct HeapRawPending { u64 base; std::uint32_t bytes; }; +SRWLOCK heap_raw_pending_lock = SRWLOCK_INIT; +std::vector<HeapRawPending> heap_raw_pending; +LONG64 heap_raw_noted, heap_raw_dropped; +constexpr std::size_t heap_raw_pending_max = 1u << 20; +volatile LONG heap_raw_rescan; + +// The table size: heap_raw_map_entries, or (tests) X2W_HEAP_RAW_TEST_ENTRIES, a power of two from 4 to 2^20. +std::uint32_t heap_raw_entries() +{ + static const std::uint32_t n = [] { + char v[16] = ""; + const DWORD got = GetEnvironmentVariableA("X2W_HEAP_RAW_TEST_ENTRIES", v, sizeof v); + const unsigned long t = got && got < sizeof v ? std::strtoul(v, nullptr, 10) : 0; + if (t >= 4 && t <= (1u << 20) && !(t & (t - 1))) { + log("x2w-heapraw X2W_HEAP_RAW_TEST_ENTRIES=%lu: a test-size table", t); + return static_cast<std::uint32_t>(t); + } + return x2w_startup::heap_raw_map_entries; + }(); + return n; +} + +// write_buffer_descriptor (d3d12_memory_srv.inl), for the V# words it wrote. +void heap_raw_note(const std::uint32_t* words) +{ + if (!heap_raw_on()) return; + x2w_startup::RawBufferWords v; + if (!x2w_startup::raw_buffer_words(words, v)) return; + AcquireSRWLockExclusive(&heap_raw_pending_lock); + const bool room = heap_raw_pending.size() < heap_raw_pending_max; + if (room) heap_raw_pending.push_back({v.base, v.bytes}); + else heap_raw_rescan = 1; // the next drain reads the whole heap (under this lock: the drain clears it with the swap) + ReleaseSRWLockExclusive(&heap_raw_pending_lock); + InterlockedIncrement64(room ? &heap_raw_noted : &heap_raw_dropped); +} + +ID3D12Resource* heap_raw_map; +std::uint32_t* heap_raw_words; // the GPU copy, heap_raw_entries() x 4 (write only) +struct HeapRawSlot { + std::uint32_t lo = 0, hi_window = 0, bytes = 0, offset = 0; // the GPU entry's words + std::uint32_t seen = 0; // sweep pass of the last sighting + LONG tried = 0; // frame of the last resolution attempt + std::uint32_t batch = 0; // heap_raw_batch_id when queued for the GPU copy + std::uint32_t checked = 0; // sweep pass of the last resolution or revalidation + UINT window() const { return hi_window >> 16; } + u64 base() const { return u64{lo} | (u64{hi_window & 0xffff} << 32); } +}; +std::vector<HeapRawSlot> heap_raw_shadow; +constexpr UINT heap_raw_tombstone = 0xffff, heap_raw_refused = 0xfffe; // both a miss for the program (window < 256) +std::uint32_t heap_raw_live, heap_raw_refused_live; // occupied entries (resolved + refused), and the refused among them +std::uint32_t heap_raw_pass = 2; // the sweep pass in progress +// The last complete sweep pass (heap_raw_bits_pass): one bit per table entry the pass found in the heap. An entry's +// sighting is max(seen, that pass) when its bit is set (heap_raw_seen). +std::vector<std::uint64_t> heap_raw_bits; +std::uint32_t heap_raw_bits_pass = 0; +std::uint32_t heap_raw_seen(std::uint32_t slot) +{ + const std::uint32_t s = heap_raw_shadow[slot].seen; + const bool bit = !heap_raw_bits.empty() && (heap_raw_bits[slot >> 6] >> (slot & 63)) & 1; + return bit && heap_raw_bits_pass > s ? heap_raw_bits_pass : s; +} +std::vector<HeapRawPending> heap_raw_backlog; // heap-sweep finds past the per-drain budget +constexpr std::size_t heap_raw_backlog_max = 1u << 19; +std::vector<ID3D12Resource*> heap_raw_windows; // index = window view - heap_raw_window_first +LONG64 heap_raw_paged, heap_raw_paged_full, heap_raw_unaligned_resolved; // paged and unaligned ranges resolved; paged refused (no records left) +LONG64 heap_raw_resolved, heap_raw_unaligned, heap_raw_unmapped, heap_raw_past_view, heap_raw_no_window, heap_raw_displaced, + heap_raw_displaced_recent, heap_raw_evicted, heap_raw_scans, heap_raw_deferred, heap_raw_check_mismatch, heap_raw_passes; +// Heartbeat counters (report_heap_raw, every 5 s), reset at each report. +LONG64 heap_raw_hb_drains, heap_raw_hb_ticks, heap_raw_hb_max_ticks, heap_raw_hb_resolved, heap_raw_hb_evicted, heap_raw_hb_sweep_ticks, + heap_raw_hb_sweep_max_ticks, heap_raw_hb_displaced; +double heap_raw_ms(LONG64 ticks) +{ + static const double per_ms = [] { + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + return static_cast<double>(f.QuadPart) / 1000.0; + }(); + return static_cast<double>(ticks) / per_ms; +} +bool heap_raw_env(const char* name) +{ + char v[4] = ""; + const DWORD n = GetEnvironmentVariableA(name, v, sizeof v); + return n && n < sizeof v && v[0] == '1'; +} +// X2W_HEAP_RAW_TIMES=1 (benchmarks, tests/startup_cx_async.cpp rawheap-bench): one log line per drain with work. +bool heap_raw_times() +{ + static const bool on = heap_raw_env("X2W_HEAP_RAW_TIMES"); + return on; +} +// X2W_HEAP_RAW_CHECK=1 (tests, watched runs): every page-cache resolution of a new range is compared with +// desktop_range(base, bytes) (not the revalidations: their page budget would not bound those calls). +bool heap_raw_revalidating; +bool heap_raw_check() +{ + static const bool on = heap_raw_env("X2W_HEAP_RAW_CHECK"); + return on; +} + +// The index of the window's raw SRV, made on first sight. UINT_MAX: no room (heap_raw_windows_max). +std::vector<u64> heap_raw_window_views; // each window's view bytes +UINT heap_raw_window(ID3D12Resource* window, u64* view_bytes) +{ + for (UINT i = 0; i < heap_raw_windows.size(); ++i) + if (heap_raw_windows[i] == window) { + *view_bytes = heap_raw_window_views[i]; + return i; + } + const u64 width = window->GetDesc().Width; + *view_bytes = (width < x2w_startup::heap_raw_window_view_bytes ? width : x2w_startup::heap_raw_window_view_bytes) & ~3ull; + if (heap_raw_windows.size() >= x2w_startup::heap_raw_windows_max) return UINT_MAX; + const UINT i = static_cast<UINT>(heap_raw_windows.size()); + bounded_raw_srv(window, 0, *view_bytes, + D3D12_CPU_DESCRIPTOR_HANDLE{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + + SIZE_T{x2w_startup::heap_raw_window_first + i} * draw_heap_increment}); + heap_raw_windows.push_back(window); + heap_raw_window_views.push_back(*view_bytes); + log("x2w-heapraw window %u: desktop va 0x%llx, %llu bytes (view %llu)", i, window->GetGPUVirtualAddress(), width, *view_bytes); + return i; +} + +// Writes entry `slot` in the shadow now and in the GPU copy at the next heap_raw_flush (an upload heap: +// write-combined memory, so the order the GPU may see is fenced with _mm_sfence, three fences per flush instead of +// two per entry). A slot that was free on the GPU (z == 0): x, y, w, fence, then z. A slot in use or a tombstone +// (z != 0, which keeps the probe chains through it intact): the window is set to heap_raw_tombstone first (a value +// the program never accepts), fence, x, z, w, fence, then the window. A slot written twice in one batch flushes the +// batch first. +struct HeapRawGpuWrite { std::uint32_t slot; bool was_free; }; +std::vector<HeapRawGpuWrite> heap_raw_batch; +std::uint32_t heap_raw_batch_id = 1; +void heap_raw_flush() +{ + if (heap_raw_batch.empty()) return; + volatile std::uint32_t* const words = heap_raw_words; + for (const HeapRawGpuWrite& w : heap_raw_batch) + if (!w.was_free) words[u64{w.slot} * 4 + 1] = (heap_raw_shadow[w.slot].hi_window & 0xffff) | (heap_raw_tombstone << 16); + _mm_sfence(); + for (const HeapRawGpuWrite& w : heap_raw_batch) { + const HeapRawSlot& e = heap_raw_shadow[w.slot]; + volatile std::uint32_t* g = words + u64{w.slot} * 4; + g[0] = e.lo; + g[3] = e.offset; + if (w.was_free) g[1] = e.hi_window; + else g[2] = e.bytes; + } + _mm_sfence(); + for (const HeapRawGpuWrite& w : heap_raw_batch) { + const HeapRawSlot& e = heap_raw_shadow[w.slot]; + if (w.was_free) words[u64{w.slot} * 4 + 2] = e.bytes; + else words[u64{w.slot} * 4 + 1] = e.hi_window; + } + _mm_sfence(); + heap_raw_batch.clear(); + ++heap_raw_batch_id; +} +void heap_raw_write(std::uint32_t slot, u64 base, std::uint32_t bytes, UINT window, std::uint32_t offset) +{ + HeapRawSlot& s = heap_raw_shadow[slot]; + if (s.batch == heap_raw_batch_id) heap_raw_flush(); + s.batch = heap_raw_batch_id; + heap_raw_batch.push_back({slot, s.bytes == 0}); + s.lo = static_cast<std::uint32_t>(base); + s.hi_window = static_cast<std::uint32_t>((base >> 32) & 0xffff) | (window << 16); + s.bytes = bytes; + s.offset = offset; +} +// Only the window changes (a tombstone): one store, fenced by the caller. +void heap_raw_set_window(std::uint32_t slot, UINT window) +{ + HeapRawSlot& s = heap_raw_shadow[slot]; + if (s.batch == heap_raw_batch_id) heap_raw_flush(); + s.hi_window = (s.hi_window & 0xffff) | (window << 16); + heap_raw_words[u64{slot} * 4 + 1] = s.hi_window; +} + +bool heap_raw_ensure() +{ + if (heap_raw_map) return true; + static bool failed; + if (failed) return false; + D3D12_HEAP_PROPERTIES up{D3D12_HEAP_TYPE_UPLOAD}; + D3D12_RESOURCE_DESC rd{}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rd.Width = u64{heap_raw_entries()} * 16; + rd.Height = rd.DepthOrArraySize = rd.MipLevels = 1; + rd.SampleDesc.Count = 1; + rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (FAILED(device_of(the_device)->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&heap_raw_map))) || + FAILED(heap_raw_map->Map(0, nullptr, reinterpret_cast<void**>(&heap_raw_words)))) { + if (heap_raw_map) heap_raw_map->Release(); + heap_raw_map = nullptr; + failed = true; + log("x2w-heapraw table not created: raw V#s bind the empty view"); + return false; + } + std::memset(heap_raw_words, 0, static_cast<std::size_t>(rd.Width)); + heap_raw_shadow.assign(heap_raw_entries(), HeapRawSlot{}); + log("x2w-heapraw table: %u entries (%llu bytes), %u probes, sweep of the heap in %u frames, %u heap finds resolved per drain; windows " + "from draw heap view %u", + heap_raw_entries(), rd.Width, x2w_startup::heap_raw_probes, x2w_startup::heap_raw_sweep_frames, x2w_startup::heap_raw_resolve_budget, + x2w_startup::heap_raw_window_first); + return true; +} + +void heap_raw_counters() +{ + log("x2w-heapraw ranges: noted %lld (past a full pending list %lld, read again by a rescan); resolved %lld " + "(base not 4-aligned %lld, paged %lld); not resolved: base not 4-aligned %lld, not in windows %lld, past the window view %lld, no " + "window view left %lld, page records full %lld; displaced %lld (recent %lld), evicted %lld; %u entries (%u refused), " + "%zu windows, %zu waiting (deferred %lld), sweep passes %lld, heap reads %lld, check mismatches %lld", + heap_raw_noted, heap_raw_dropped, heap_raw_resolved, heap_raw_unaligned_resolved, heap_raw_paged, heap_raw_unaligned, + heap_raw_unmapped, heap_raw_past_view, heap_raw_no_window, heap_raw_paged_full, + heap_raw_displaced, heap_raw_displaced_recent, heap_raw_evicted, heap_raw_live, heap_raw_refused_live, heap_raw_windows.size(), + heap_raw_backlog.size(), heap_raw_deferred, heap_raw_passes, heap_raw_scans, heap_raw_check_mismatch); +} + +// The table entry of (base, bytes), or UINT_MAX. `place` gets where an insert goes: the first free or tombstone slot +// on the chain, else the occupied slot seen least recently (UINT_MAX only for an empty probe range, never). +std::uint32_t heap_raw_find(u64 base, std::uint32_t bytes, std::uint32_t* place) +{ + const std::uint32_t mask = heap_raw_entries() - 1, lo = static_cast<std::uint32_t>(base), hi = static_cast<std::uint32_t>((base >> 32) & 0xffff); + const std::uint32_t h = x2w_startup::raw_map_hash(lo, hi, bytes); + std::uint32_t free = UINT_MAX, oldest = UINT_MAX; + for (std::uint32_t i = 0; i < x2w_startup::heap_raw_probes; ++i) { + const std::uint32_t at = (h + i) & mask; + const HeapRawSlot& s = heap_raw_shadow[at]; + if (!s.bytes) { // the end of the chain (the program stops here too) + if (free == UINT_MAX) free = at; + break; + } + if (s.window() == heap_raw_tombstone) { + if (free == UINT_MAX) free = at; + continue; + } + if (s.lo == lo && (s.hi_window & 0xffff) == hi && s.bytes == bytes) return at; + if (oldest == UINT_MAX || heap_raw_seen(at) < heap_raw_seen(oldest)) oldest = at; + } + if (place) *place = free != UINT_MAX ? free : oldest; + return UINT_MAX; +} + +// Per-frame 64 KiB page cache for resolution: the window and the window offset of each page's start. +struct HeapRawPage { + u64 page = 0; + LONG frame = -1; + ID3D12Resource* window = nullptr; // nullptr: the page is not in one window + u64 offset = 0; +}; +std::vector<HeapRawPage> heap_raw_pages; +LONG64 heap_raw_page_lookups; // desktop_range calls the page cache made +const HeapRawPage& heap_raw_page(u64 page) +{ + if (heap_raw_pages.empty()) heap_raw_pages.resize(1u << 15); + const std::size_t mask = heap_raw_pages.size() - 1; + std::size_t at = static_cast<std::size_t>((page * 0x9e3779b97f4a7c15ull) >> 40) & mask; + for (std::size_t i = 0; i < 8; ++i, at = (at + 1) & mask) { // linear probes; a stale or full run reuses the first + HeapRawPage& p = heap_raw_pages[at]; + if (p.frame == frame_number && p.page == page) return p; + if (p.frame != frame_number) break; + } + HeapRawPage& p = heap_raw_pages[at]; + p.page = page; + p.frame = frame_number; + p.window = nullptr; + p.offset = 0; + ++heap_raw_page_lookups; + if (!desktop_range(page << 16, 4, &p.window, &p.offset)) p.window = nullptr; + return p; +} + +ID3D12Resource* heap_raw_pages_map; +volatile std::uint32_t* heap_raw_page_words; +std::vector<std::uint32_t> heap_raw_page_shadow; +std::uint32_t heap_raw_page_top; +std::multimap<std::uint32_t, std::uint32_t> heap_raw_page_free; // count -> first +struct HeapRawFreed { LONG frame; std::uint32_t first, count; }; +std::vector<HeapRawFreed> heap_raw_page_freed; +constexpr LONG heap_raw_page_quarantine = 8; +std::uint32_t heap_raw_page_count(u64 base, std::uint32_t bytes) { return static_cast<std::uint32_t>(((base & 0xffff) + bytes - 1) >> 16) + 1; } +std::uint32_t heap_raw_page_alloc(std::uint32_t count) +{ + if (!heap_raw_pages_map) { + static bool failed; + if (failed) return UINT_MAX; + LARGE_INTEGER c0, c1; + QueryPerformanceCounter(&c0); + D3D12_HEAP_PROPERTIES up{D3D12_HEAP_TYPE_UPLOAD}; + D3D12_RESOURCE_DESC rd{}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rd.Width = u64{x2w_startup::heap_raw_page_records} * 8; + rd.Height = rd.DepthOrArraySize = rd.MipLevels = 1; + rd.SampleDesc.Count = 1; + rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + void* words = nullptr; + if (FAILED(device_of(the_device)->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&heap_raw_pages_map))) || + FAILED(heap_raw_pages_map->Map(0, nullptr, &words))) { + if (heap_raw_pages_map) heap_raw_pages_map->Release(); + heap_raw_pages_map = nullptr; + failed = true; + log("x2w-heapraw page records not created: ranges over several windows stay refused"); + return UINT_MAX; + } + heap_raw_page_words = static_cast<std::uint32_t*>(words); + heap_raw_page_shadow.assign(std::size_t{x2w_startup::heap_raw_page_records} * 2, 0); + bounded_raw_srv(heap_raw_pages_map, 0, rd.Width, + D3D12_CPU_DESCRIPTOR_HANDLE{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + + SIZE_T{x2w_startup::heap_raw_pages_view} * draw_heap_increment}); + QueryPerformanceCounter(&c1); + log("x2w-heapraw page records: %u (%llu bytes) at draw heap view %u, made in %.3f ms", x2w_startup::heap_raw_page_records, rd.Width, + x2w_startup::heap_raw_pages_view, heap_raw_ms(c1.QuadPart - c0.QuadPart)); + } + for (std::size_t i = 0; i < heap_raw_page_freed.size();) // runs past their quarantine are free again + if (frame_number - heap_raw_page_freed[i].frame >= heap_raw_page_quarantine) { + heap_raw_page_free.emplace(heap_raw_page_freed[i].count, heap_raw_page_freed[i].first); + heap_raw_page_freed[i] = heap_raw_page_freed.back(); + heap_raw_page_freed.pop_back(); + } else { + ++i; + } + if (const auto run = heap_raw_page_free.lower_bound(count); run != heap_raw_page_free.end()) { + const std::uint32_t first = run->second, left = run->first - count; + heap_raw_page_free.erase(run); + if (left) heap_raw_page_free.emplace(left, first + count); + return first; + } + if (x2w_startup::heap_raw_page_records - heap_raw_page_top < count) return UINT_MAX; + heap_raw_page_top += count; + return heap_raw_page_top - count; +} +void heap_raw_page_release(std::uint32_t first, std::uint32_t count) { heap_raw_page_freed.push_back({frame_number, first, count}); } +// Writes records [first, first + records.size() / 2) (shadow and GPU copy, fenced: the entry that names them is +// written after). +void heap_raw_page_store(std::uint32_t first, const std::vector<std::uint32_t>& records) +{ + for (std::size_t i = 0; i < records.size(); ++i) { + heap_raw_page_shadow[std::size_t{first} * 2 + i] = records[i]; + heap_raw_page_words[std::size_t{first} * 2 + i] = records[i]; + } + _mm_sfence(); +} +// The page records of [base, base + bytes): every 64 KiB page in a window, with room in its view for the range's +// bytes in that page. nullptr, or the counter of why not. +LONG64* heap_raw_page_runs(u64 base, std::uint32_t bytes, std::vector<std::uint32_t>& records) +{ + records.clear(); + const std::uint32_t count = heap_raw_page_count(base, bytes); + if (count > x2w_startup::heap_raw_paged_max_pages) return &heap_raw_unmapped; + const u64 first = base >> 16, end = base + bytes; + for (std::uint32_t i = 0; i < count; ++i) { + const HeapRawPage& p = heap_raw_page(first + i); + if (!p.window) return &heap_raw_unmapped; + u64 view_bytes = 0; + const UINT index = heap_raw_window(p.window, &view_bytes); + if (index == UINT_MAX) return &heap_raw_no_window; + const u64 page_start = (first + i) << 16, used = (std::min)(end, page_start + 0x10000) - page_start; + if (p.offset + used > view_bytes || (p.offset & 3) || p.offset > 0xffffffffull) return &heap_raw_past_view; + records.push_back(index); + records.push_back(static_cast<std::uint32_t>(p.offset)); + } + return nullptr; +} + +// Resolves a range: its window field and offset, or the counter of why not. One window: the window (with +// heap_raw_window_unaligned for a base that is not 4-aligned; the hardware reads such raw buffers byte-exact, and so +// does the program, two dwords per load). Else, every page in some window: a paged entry (new page records). +LONG64* heap_raw_locate_window(u64 base, std::uint32_t bytes, UINT* index, u64* offset); +LONG64* heap_raw_locate(u64 base, std::uint32_t bytes, UINT* index, u64* offset) +{ + LONG64* why = heap_raw_locate_window(base, bytes, index, offset); + if (why != &heap_raw_unmapped) return why; + static std::vector<std::uint32_t> records; + if (LONG64* not_paged = heap_raw_page_runs(base, bytes, records)) return not_paged; + const std::uint32_t first = heap_raw_page_alloc(static_cast<std::uint32_t>(records.size() / 2)); + if (first == UINT_MAX) return &heap_raw_paged_full; + heap_raw_page_store(first, records); + *index = x2w_startup::heap_raw_window_paged; + *offset = first; + if (!heap_raw_revalidating) ++heap_raw_paged; + static LONG shown; + if (first_calls(shown, 8)) + log("x2w-heapraw paged range: base 0x%llx bytes %u, %zu pages, records %u.. (first page window %u offset 0x%x)", base, bytes, + records.size() / 2, first, records[0], records[1]); + return nullptr; +} + +// The one-window part of heap_raw_locate. +LONG64* heap_raw_locate_window(u64 base, std::uint32_t bytes, UINT* index, u64* offset) +{ + const u64 first = base >> 16, last = (base + bytes - 1) >> 16; + const HeapRawPage p0 = heap_raw_page(first); + ID3D12Resource* window = p0.window; + for (u64 page = first + 1; window && page <= last; ++page) { + const HeapRawPage& p = heap_raw_page(page); + if (p.window != window || p.offset != p0.offset + ((page - first) << 16)) window = nullptr; + } + *offset = p0.offset + (base & 0xffff); + if (!window && !desktop_range(base, bytes, &window, offset)) window = nullptr; // the page path refused: ask for the range itself + else if (window && heap_raw_check() && !heap_raw_revalidating) { + ID3D12Resource* w2 = nullptr; + u64 o2 = 0; + const bool ok2 = desktop_range(base, bytes, &w2, &o2); + if (ok2 != (window != nullptr) || (ok2 && (w2 != window || o2 != *offset))) { + static LONG shown; + if (first_calls(shown, 8)) + log("x2w-heapraw check: base 0x%llx bytes %u: pages %p+0x%llx, desktop_range %d %p+0x%llx", base, bytes, static_cast<void*>(window), + *offset, ok2, static_cast<void*>(w2), o2); + ++heap_raw_check_mismatch; + } + } + if (!window) return &heap_raw_unmapped; + u64 view_bytes = 0; + if ((*index = heap_raw_window(window, &view_bytes)) == UINT_MAX) return &heap_raw_no_window; + if (*offset + bytes > view_bytes || (*offset & 3) != (base & 3) || *offset > 0xffffffffull) return &heap_raw_past_view; + if (base & 3) { + *index |= x2w_startup::heap_raw_window_unaligned; + if (!heap_raw_revalidating) ++heap_raw_unaligned_resolved; + } + return nullptr; +} + +// One sighting of (base, bytes): refreshed if in the table (a refused one retried when due), else resolved and +// inserted. True when it needed a resolution attempt. +bool heap_raw_take(u64 base, std::uint32_t bytes) +{ + std::uint32_t place = UINT_MAX; + std::uint32_t at = heap_raw_find(base, bytes, &place); + if (at != UINT_MAX) { + HeapRawSlot& s = heap_raw_shadow[at]; + s.seen = heap_raw_pass; + if (s.window() != heap_raw_refused || frame_number - s.tried < static_cast<LONG>(x2w_startup::heap_raw_retry_frames)) return false; + } + UINT index = heap_raw_refused; + u64 offset = 0; + LONG64* refused = heap_raw_locate(base, bytes, &index, &offset); + if (refused) { + ++*refused; // draw_lock held (as every counter here but noted / dropped) + index = heap_raw_refused; + offset = 0; + } else { + ++heap_raw_resolved; + ++heap_raw_hb_resolved; + static LONG shown; + if (first_calls(shown, 8)) + log("x2w-heapraw resolved V# base 0x%llx bytes %u -> window %u offset 0x%llx", base, bytes, index, offset); + } + if (at != UINT_MAX) { // a refused range, tried again + if (!refused) { + heap_raw_write(at, base, bytes, index, static_cast<std::uint32_t>(offset)); + heap_raw_shadow[at].checked = heap_raw_pass; + --heap_raw_refused_live; + } + heap_raw_shadow[at].tried = frame_number; + return true; + } + HeapRawSlot& old = heap_raw_shadow[place]; + if (old.bytes && old.window() != heap_raw_tombstone) { // every probe occupied: the least recently seen goes + ++heap_raw_displaced; + ++heap_raw_hb_displaced; + if (heap_raw_seen(place) + 1 >= heap_raw_pass) ++heap_raw_displaced_recent; + if (old.window() == x2w_startup::heap_raw_window_paged) heap_raw_page_release(old.offset, heap_raw_page_count(old.base(), old.bytes)); + if (old.window() == heap_raw_refused) --heap_raw_refused_live; + --heap_raw_live; + } + heap_raw_write(place, base, bytes, index, static_cast<std::uint32_t>(offset)); + heap_raw_shadow[place].seen = heap_raw_pass; + heap_raw_shadow[place].checked = heap_raw_pass; + heap_raw_shadow[place].tried = frame_number; + if (!heap_raw_bits.empty()) heap_raw_bits[place >> 6] &= ~(1ull << (place & 63)); // the bit was the old entry's + ++heap_raw_live; + if (refused) ++heap_raw_refused_live; + return true; +} + +// Reads the whole title heap (draw_lock held; the first drain and a rescan): every V# of the runtime's shape goes in +// `out`. Returns the V#s found; a heap the CPU cannot read is skipped (logged). +std::size_t heap_raw_read_all(u64 heap, u64 slots, std::vector<HeapRawPending>& out) +{ + if (!x2w_local::readable(reinterpret_cast<const void*>(heap), static_cast<std::size_t>(slots * 32))) { + log("x2w-heapraw heap 0x%llx (%llu slots) not readable, skipped", heap, slots); + return 0; + } + std::size_t found = 0; + u64 last_base = 0; + std::uint32_t last_bytes = 0; + for (u64 i = 0; i < slots; ++i) { + std::uint32_t w[8]; + std::memcpy(w, reinterpret_cast<const void*>(heap + i * 32), sizeof w); + x2w_startup::RawBufferWords v; + if (!x2w_startup::runtime_vdesc_shape(w) || !x2w_startup::raw_buffer_words(w, v)) continue; + ++found; + if (v.base == last_base && v.bytes == last_bytes) continue; // the slot before held the same range + last_base = v.base; + last_bytes = v.bytes; + out.push_back({v.base, v.bytes}); + } + return found; +} + +bool heap_raw_sweep_sync() +{ + static const bool on = heap_raw_env("X2W_HEAP_RAW_SWEEP_SYNC"); + return on; +} +struct HeapRawSweep { + u64 heap = 0, from = 0, to = 0, slots = 0; // the part asked for + std::uint32_t pass = 0; + std::vector<std::uint64_t> building, done; // bits of the pass being read, and of the last one read to the end + std::uint32_t done_pass = 0; + bool pass_done = false; // `done` is new + std::vector<HeapRawPending> unknown; + std::size_t found = 0; // V#s in the part + LONG64 ticks = 0; // the part's time on the thread + LONG64 faults = 0; // 256-slot blocks that faulted (unmapped while read), skipped +}; +// Copies title memory on the sweep thread: false when a page faults (the heap unmapped under the read). +// Page by page: a guard page's fault clears its guard bit, which is set again (as x2w_local::readable does). +bool heap_raw_copy(void* to, const void* from, std::size_t bytes) +{ + const auto start = reinterpret_cast<std::uintptr_t>(from); + for (std::uintptr_t at = start; at < start + bytes;) { + const std::uintptr_t next = (std::min)((at | 0xFFF) + 1, start + bytes); + DWORD code = 0; + __try { + std::memcpy(static_cast<unsigned char*>(to) + (at - start), reinterpret_cast<const void*>(at), next - at); + } __except (code = GetExceptionCode(), EXCEPTION_EXECUTE_HANDLER) { + if (code == 0x80000001u) { // STATUS_GUARD_PAGE_VIOLATION + MEMORY_BASIC_INFORMATION info{}; + DWORD old = 0; + if (VirtualQuery(reinterpret_cast<const void*>(at), &info, sizeof(info)) && info.State == MEM_COMMIT) + VirtualProtect(reinterpret_cast<void*>(at & ~std::uintptr_t{0xFFF}), 0x1000, info.Protect | PAGE_GUARD, &old); + } + return false; + } + at = next; + } + return true; +} +HeapRawSweep heap_raw_sweep; +volatile LONG heap_raw_sweep_busy; +HANDLE heap_raw_sweep_go, heap_raw_sweep_done; +LONG64 heap_raw_sweep_behind, heap_raw_sweep_parts, heap_raw_hb_thread_ticks; + +// heap_raw_find without a lock and without an insert place (the sweep thread). +std::uint32_t heap_raw_peek(u64 base, std::uint32_t bytes) +{ + const std::uint32_t mask = heap_raw_entries() - 1, lo = static_cast<std::uint32_t>(base), hi = static_cast<std::uint32_t>((base >> 32) & 0xffff); + const std::uint32_t h = x2w_startup::raw_map_hash(lo, hi, bytes); + const volatile HeapRawSlot* shadow = heap_raw_shadow.data(); + for (std::uint32_t i = 0; i < x2w_startup::heap_raw_probes; ++i) { + const volatile HeapRawSlot& e = shadow[(h + i) & mask]; + const std::uint32_t z = e.bytes, y = e.hi_window, x = e.lo; + if (!z) break; + if ((y >> 16) == heap_raw_tombstone) continue; + if (x == lo && (y & 0xffff) == hi && z == bytes) return (h + i) & mask; + } + return UINT_MAX; +} + +DWORD WINAPI heap_raw_sweep_thread(void*) +{ + for (;;) { + WaitForSingleObject(heap_raw_sweep_go, INFINITE); + HeapRawSweep& w = heap_raw_sweep; + LARGE_INTEGER t0, t1; + QueryPerformanceCounter(&t0); + if (w.from == 0) std::fill(w.building.begin(), w.building.end(), 0); + w.found = 0; + u64 last_base = 0; + std::uint32_t last_bytes = 0, last_at = UINT_MAX; + static std::uint32_t block[256 * 8]; // 256 slots, copied at once (a fault skips the block) + for (u64 b = w.from; b < w.to; b += 256) { + const u64 n = (std::min<u64>)(256, w.to - b); + if (!heap_raw_copy(block, reinterpret_cast<const void*>(w.heap + b * 32), static_cast<std::size_t>(n * 32))) { + ++w.faults; + continue; + } + for (u64 i = 0; i < n; ++i) { + const std::uint32_t* words = block + i * 8; + x2w_startup::RawBufferWords v; + if (!x2w_startup::runtime_vdesc_shape(words) || !x2w_startup::raw_buffer_words(words, v)) continue; + ++w.found; + if (v.base == last_base && v.bytes == last_bytes && last_at != UINT_MAX) continue; + last_base = v.base; + last_bytes = v.bytes; + last_at = heap_raw_peek(v.base, v.bytes); + if (last_at != UINT_MAX) w.building[last_at >> 6] |= 1ull << (last_at & 63); + else if (w.unknown.size() < heap_raw_backlog_max) w.unknown.push_back({v.base, v.bytes}); + } + } + if (w.to >= w.slots) { + w.done.swap(w.building); + std::fill(w.building.begin(), w.building.end(), 0); // the next pass starts with no sightings + w.done_pass = w.pass; + w.pass_done = true; + } + QueryPerformanceCounter(&t1); + w.ticks = t1.QuadPart - t0.QuadPart; + InterlockedExchange(&heap_raw_sweep_busy, 0); + SetEvent(heap_raw_sweep_done); + } +} + +// The thread's results, when it is idle (draw_lock held). +void heap_raw_sweep_take() +{ + if (InterlockedCompareExchange(&heap_raw_sweep_busy, 0, 0)) return; + HeapRawSweep& w = heap_raw_sweep; + for (const HeapRawPending& p : w.unknown) + if (heap_raw_backlog.size() < heap_raw_backlog_max) heap_raw_backlog.push_back(p); + w.unknown.clear(); + heap_raw_hb_thread_ticks += w.ticks; + w.ticks = 0; + if (w.pass_done) { + w.pass_done = false; + heap_raw_bits.swap(w.done); // the thread's old `done` comes back as the next one to fill + heap_raw_bits_pass = w.done_pass; + heap_raw_pass = w.done_pass + 1; + ++heap_raw_passes; + } +} + +// Once per frame: take the sweep's results, ask for the next part, then the eviction clock hand (with revalidation). +u64 heap_raw_sweep_heap, heap_raw_sweep_at; +std::uint32_t heap_raw_hand; +LONG heap_raw_swept_frame = -1; +LONG64 heap_raw_revalidated, heap_raw_revalidate_changed; +std::uint32_t heap_raw_revalidate_passes() +{ + static const std::uint32_t n = [] { + char v[8] = ""; + const DWORD got = GetEnvironmentVariableA("X2W_HEAP_RAW_REVALIDATE_PASSES", v, sizeof v); + const unsigned long t = got && got < sizeof v ? std::strtoul(v, nullptr, 10) : 0; + return t >= 1 && t <= 1000 ? static_cast<std::uint32_t>(t) : x2w_startup::heap_raw_revalidate_passes; + }(); + return n; +} +void heap_raw_sweep_ask(u64 heap, u64 slots, std::uint32_t cap); +void heap_raw_hand_work(std::uint32_t cap, LONG64* evicted_out); +void heap_raw_frame_work(u64 heap, u64 heap_bytes) +{ + if (heap_raw_swept_frame == frame_number) return; + heap_raw_swept_frame = frame_number; + LARGE_INTEGER t0, t1; + QueryPerformanceCounter(&t0); + const u64 slots = heap_bytes / 32; + const std::uint32_t cap = heap_raw_entries(); + if (!heap_raw_sweep_go) { + heap_raw_sweep_go = CreateEventW(nullptr, FALSE, FALSE, nullptr); + heap_raw_sweep_done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + heap_raw_sweep.building.assign(cap / 64 + 1, 0); + heap_raw_sweep.done.assign(cap / 64 + 1, 0); + heap_raw_bits.assign(cap / 64 + 1, 0); + HANDLE t = CreateThread(nullptr, 0, heap_raw_sweep_thread, nullptr, 0, nullptr); + if (t) CloseHandle(t); + log("x2w-heapraw sweep thread %s%s", t ? "started" : "NOT started (no sweep)", heap_raw_sweep_sync() ? " (X2W_HEAP_RAW_SWEEP_SYNC=1)" : ""); + if (!t) heap_raw_sweep_busy = 1; // never idle: no parts are asked for + } + // The order: take the thread's results; then (thread idle) the clock hand, which also counts the sightings of the + // pass in progress (heap_raw_sweep.building); then ask for the next part. An entry found by a part already read + // is never evicted on the last complete pass alone (a late staging copy of an entry that pass missed). + // X2W_HEAP_RAW_SWEEP_SYNC=1 asks and waits before the hand instead. + heap_raw_sweep_take(); + const bool sync = heap_raw_sweep_sync(); + if (sync) heap_raw_sweep_ask(heap, slots, cap); + const bool idle = !InterlockedCompareExchange(&heap_raw_sweep_busy, 0, 0); + if (!idle) ++heap_raw_sweep_behind; + LONG64 evicted = 0; + if (idle && heap_raw_live) heap_raw_hand_work(cap, &evicted); + if (!sync && idle) heap_raw_sweep_ask(heap, slots, cap); + heap_raw_evicted += evicted; + heap_raw_hb_evicted += evicted; + QueryPerformanceCounter(&t1); + heap_raw_hb_sweep_ticks += t1.QuadPart - t0.QuadPart; + heap_raw_hb_sweep_max_ticks = (std::max)(heap_raw_hb_sweep_max_ticks, t1.QuadPart - t0.QuadPart); + if (heap_raw_times()) + log("x2w-heapraw frame work: %.3f ms, sweep at %llu of %llu slots, pass %u, %lld evicted, %u entries, revalidated %lld (changed %lld), " + "sweep behind %lld, thread %.3f ms", + heap_raw_ms(t1.QuadPart - t0.QuadPart), heap_raw_sweep_at, slots, heap_raw_pass, evicted, heap_raw_live, heap_raw_revalidated, + heap_raw_revalidate_changed, heap_raw_sweep_behind, heap_raw_ms(heap_raw_sweep.ticks)); +} + +// The next part of the heap for the sweep thread (idle). Sync: waited for and taken. +void heap_raw_sweep_ask(u64 heap, u64 slots, std::uint32_t cap) +{ + if (InterlockedCompareExchange(&heap_raw_sweep_busy, 0, 0)) return; + if (slots) { + if (heap != heap_raw_sweep_heap) { // a new heap: the sweep starts again (the pass does not end early) + if (heap_raw_sweep_heap) log("x2w-heapraw sweep: heap 0x%llx -> 0x%llx (%llu slots)", heap_raw_sweep_heap, heap, slots); + heap_raw_sweep_heap = heap; + heap_raw_sweep_at = 0; + } + const u64 frames = heap_raw_live > cap / 2 ? 4 : x2w_startup::heap_raw_sweep_frames; + const u64 chunk = (std::max<u64>)(4096, (slots + frames - 1) / frames); + HeapRawSweep& w = heap_raw_sweep; + w.heap = heap; + w.slots = slots; + w.from = heap_raw_sweep_at; + w.to = (std::min)(slots, heap_raw_sweep_at + chunk); + w.pass = heap_raw_pass; + heap_raw_sweep_at = w.to >= slots ? 0 : w.to; + ++heap_raw_sweep_parts; + InterlockedExchange(&heap_raw_sweep_busy, 1); + SetEvent(heap_raw_sweep_go); + if (heap_raw_sweep_sync()) { + WaitForSingleObject(heap_raw_sweep_done, 2000); + heap_raw_sweep_take(); + } + } +} + +constexpr LONG64 heap_raw_revalidate_pages = 256; +void heap_raw_hand_work(std::uint32_t cap, LONG64* evicted_out) +{ + LONG64 evicted = 0; + std::uint32_t revalidate = 1024; // re-resolutions per frame at most + const LONG64 lookups_end = heap_raw_page_lookups + heap_raw_revalidate_pages; + const std::uint32_t every = heap_raw_revalidate_passes(); + const std::vector<std::uint64_t>& now = heap_raw_sweep.building; // the pass in progress, so far + heap_raw_revalidating = true; + { + // 1/16 of the table per frame, 1/4 when past half full (the sweep is 4x faster then too), at least 4096 entries + const bool evict = heap_raw_live > cap / 4; + for (std::uint32_t n = (std::max)((std::min)(cap, 4096u), heap_raw_live > cap / 2 ? cap / 4 : cap / 16); n; --n, heap_raw_hand = (heap_raw_hand + 1) & (cap - 1)) { + HeapRawSlot& e = heap_raw_shadow[heap_raw_hand]; + if (!e.bytes || e.window() == heap_raw_tombstone) continue; + const bool seen_now = (now[heap_raw_hand >> 6] >> (heap_raw_hand & 63)) & 1; + if (evict && !seen_now && heap_raw_seen(heap_raw_hand) + 2 <= heap_raw_pass) { + if (e.window() == heap_raw_refused) --heap_raw_refused_live; + if (e.window() == x2w_startup::heap_raw_window_paged) heap_raw_page_release(e.offset, heap_raw_page_count(e.base(), e.bytes)); + heap_raw_set_window(heap_raw_hand, heap_raw_tombstone); + --heap_raw_live; + ++evicted; + continue; + } + // Remap healing: a resolved entry is resolved again every `every` passes (the window and offset of its + // pages now); a changed one is rewritten in place, one that no longer resolves becomes refused. + if (revalidate && heap_raw_page_lookups < lookups_end && e.window() != heap_raw_refused && e.checked + every <= heap_raw_pass) { + --revalidate; + ++heap_raw_revalidated; + e.checked = heap_raw_pass; + UINT index = heap_raw_refused; + u64 offset = 0; + const u64 base = e.base(); + const std::uint32_t bytes = e.bytes; + if (e.window() == x2w_startup::heap_raw_window_paged) { // its page records again, rewritten in place when changed + static std::vector<std::uint32_t> records; + const std::uint32_t first = e.offset; + if (LONG64* refused = heap_raw_page_runs(base, bytes, records)) { + ++*refused; + ++heap_raw_revalidate_changed; + heap_raw_page_release(first, heap_raw_page_count(base, bytes)); + heap_raw_write(heap_raw_hand, base, bytes, heap_raw_refused, 0); + e.tried = frame_number; + ++heap_raw_refused_live; + } else if (!std::equal(records.begin(), records.end(), heap_raw_page_shadow.begin() + std::size_t{first} * 2)) { + ++heap_raw_revalidate_changed; + heap_raw_page_store(first, records); + } + continue; + } + if (LONG64* refused = heap_raw_locate(base, bytes, &index, &offset)) { + ++*refused; + ++heap_raw_revalidate_changed; + heap_raw_write(heap_raw_hand, base, bytes, heap_raw_refused, 0); + e.tried = frame_number; + ++heap_raw_refused_live; + } else if (index != e.window() || offset != e.offset) { + ++heap_raw_revalidate_changed; + heap_raw_write(heap_raw_hand, base, bytes, index, static_cast<std::uint32_t>(offset)); + } + } + } + heap_raw_flush(); + _mm_sfence(); + } + heap_raw_revalidating = false; + *evicted_out = evicted; +} + +// A `heapraw 1` dispatch, draw_lock held. Every range noted since the last drain is looked up, and the new ones are +// resolved now (this frame's dispatches may read them). The first drain reads the whole heap into the backlog; the +// sweep (once per frame) adds what it finds; at most heap_raw_resolve_budget backlog ranges are resolved per drain. +// False: no table. +bool heap_raw_drain(u64 heap, u64 heap_bytes) +{ + if (!heap_raw_on() || !heap_raw_ensure()) return false; + LARGE_INTEGER t0, t1; + QueryPerformanceCounter(&t0); + std::vector<HeapRawPending> pending; + AcquireSRWLockExclusive(&heap_raw_pending_lock); + pending.swap(heap_raw_pending); + const bool rescan = heap_raw_rescan != 0; + heap_raw_rescan = 0; + ReleaseSRWLockExclusive(&heap_raw_pending_lock); + if ((!heap_raw_scans || rescan) && heap && heap_bytes >= 32) { + // The whole heap, resolved now with the noted ranges (no budget): every V# it holds is in the table before + // this dispatch reads it. + ++heap_raw_scans; + const std::size_t noted = pending.size(); + const std::size_t found = heap_raw_read_all(heap, heap_bytes / 32, pending); + log("x2w-heapraw heap read %lld (%s): %llu slots of heap 0x%llx, %zu V#s of the runtime's shape, %zu ranges with %zu noted, all resolved " + "now", heap_raw_scans, rescan ? "rescan, the pending list was full" : "first drain", heap_bytes / 32, heap, found, pending.size(), noted); + } + const LONG64 before = heap_raw_resolved + heap_raw_unaligned + heap_raw_unmapped + heap_raw_past_view + heap_raw_no_window + heap_raw_paged_full; + const std::uint32_t mask = heap_raw_entries() - 1; + for (std::size_t i = 0; i < pending.size(); ++i) { + if (i + 8 < pending.size()) { // the shadow line of a range 8 ahead (a cache miss each otherwise) + const HeapRawPending& q = pending[i + 8]; + const std::uint32_t h = x2w_startup::raw_map_hash(static_cast<std::uint32_t>(q.base), static_cast<std::uint32_t>((q.base >> 32) & 0xffff), q.bytes); + _mm_prefetch(reinterpret_cast<const char*>(&heap_raw_shadow[h & mask]), _MM_HINT_T0); + } + heap_raw_take(pending[i].base, pending[i].bytes); + } + heap_raw_flush(); + heap_raw_frame_work(heap, heap_bytes); + if (!heap_raw_backlog.empty()) { + std::uint32_t budget = x2w_startup::heap_raw_resolve_budget; + std::size_t i = 0; + for (; i < heap_raw_backlog.size() && budget; ++i) budget -= heap_raw_take(heap_raw_backlog[i].base, heap_raw_backlog[i].bytes) ? 1 : 0; + heap_raw_deferred += heap_raw_backlog.size() - i; + heap_raw_backlog.erase(heap_raw_backlog.begin(), heap_raw_backlog.begin() + i); + heap_raw_flush(); + } + QueryPerformanceCounter(&t1); + const LONG64 after = heap_raw_resolved + heap_raw_unaligned + heap_raw_unmapped + heap_raw_past_view + heap_raw_no_window + heap_raw_paged_full; + if (pending.empty() && after == before) return true; // no work + ++heap_raw_hb_drains; + heap_raw_hb_ticks += t1.QuadPart - t0.QuadPart; + heap_raw_hb_max_ticks = (std::max)(heap_raw_hb_max_ticks, t1.QuadPart - t0.QuadPart); + if (heap_raw_times()) + log("x2w-heapraw drain time: %.3f ms, %zu noted, %lld outcomes, %zu waiting, %lld page lookups, %u entries, evicted %lld, displaced %lld " + "(recent %lld), check mismatches %lld", + heap_raw_ms(t1.QuadPart - t0.QuadPart), pending.size(), after - before, heap_raw_backlog.size(), heap_raw_page_lookups, heap_raw_live, + heap_raw_evicted, heap_raw_displaced, heap_raw_displaced_recent, heap_raw_check_mismatch); + LONG64 power = 1; // a counter line when the outcomes total crosses a power of two + while (power * 2 <= after) power *= 2; + if (after && power > before) heap_raw_counters(); + return true; +} + +// The heartbeat (every 5 s, d3d12_xs_device.cpp), for the frame-time gate of a watched run. There is no whole-table +// reset any more; "table half full: reset" counts the entries evicted and displaced instead. +// Called from Present outside draw_lock (the heartbeat block runs after the lock_draw section above it is released). +void report_heap_raw() +{ + if (!heap_raw_on() || (!heap_raw_map && !heap_raw_dropped)) return; + AcquireSRWLockExclusive(&draw_lock); + const LONG64 drains = heap_raw_hb_drains, ticks = heap_raw_hb_ticks, max_ticks = heap_raw_hb_max_ticks, resolved = heap_raw_hb_resolved, + evicted = heap_raw_hb_evicted, sweep = heap_raw_hb_sweep_ticks, sweep_max = heap_raw_hb_sweep_max_ticks, + displaced = heap_raw_hb_displaced; + heap_raw_hb_drains = heap_raw_hb_ticks = heap_raw_hb_max_ticks = heap_raw_hb_resolved = heap_raw_hb_evicted = heap_raw_hb_sweep_ticks = + heap_raw_hb_sweep_max_ticks = heap_raw_hb_displaced = 0; + const std::size_t waiting = heap_raw_backlog.size(); + static LONG64 dropped_reported; + const LONG64 dropped = heap_raw_dropped - dropped_reported; + dropped_reported = heap_raw_dropped; + const std::uint32_t live = heap_raw_live, refused = heap_raw_refused_live; + const LONG64 passes = heap_raw_passes, thread = heap_raw_hb_thread_ticks, behind = heap_raw_sweep_behind, faults = heap_raw_sweep.faults; + heap_raw_hb_thread_ticks = 0; + ReleaseSRWLockExclusive(&draw_lock); + // Drain times include the sweep and eviction work that ran inside them. + log("x2w-heapraw drains with work: %lld, %.3f ms each, max %.3f ms (last 5 s, draw_lock held); table half full: reset 0 (evicted %lld, " + "displaced %lld); resolved %lld new ranges, %zu waiting, %lld notes dropped (pending full); %u of %u entries (%u refused); sweep " + "max %.3f ms per frame (%.3f ms in all), %lld passes; sweep thread %.3f ms (off draw_lock), behind %lld, faulted blocks %lld", + drains, drains ? heap_raw_ms(ticks) / static_cast<double>(drains) : 0.0, heap_raw_ms(max_ticks), evicted, displaced, resolved, waiting, + dropped, live, heap_raw_entries(), refused, heap_raw_ms(sweep_max), heap_raw_ms(sweep), passes, + heap_raw_ms(thread), behind, faults); +} + +// The table's view (t2 space1) at `dest`: a raw SRV of the table, or a null raw view (switch off / no table). +void heap_raw_bind(bool table, D3D12_CPU_DESCRIPTOR_HANDLE dest) +{ + if (table && heap_raw_map) { + bounded_raw_srv(heap_raw_map, 0, u64{heap_raw_entries()} * 16, dest); + return; + } + bounded_raw_srv(nullptr, 0, 4, dest); // a null view: GetDimensions reads 0 +} diff --git a/src/startup_stubs/d3d12_indirect.inl b/src/startup_stubs/d3d12_indirect.inl new file mode 100644 index 0000000000..35b1c7717a --- /dev/null +++ b/src/startup_stubs/d3d12_indirect.inl @@ -0,0 +1,791 @@ + +// Signature type index for counters: 0 Draw, 1 DrawIndexed, 2 Dispatch, 3 DispatchMesh, 4 other. +enum IndirectType { itype_draw, itype_indexed, itype_dispatch, itype_mesh, itype_other, itype_types }; +constexpr const char* indirect_type_names[itype_types] = {"draw", "indexed", "dispatch", "mesh", "other"}; +int indirect_type_of(UINT argument_type) +{ + switch (argument_type) { + case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: return itype_draw; + case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: return itype_indexed; + case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: return itype_dispatch; + case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH: return itype_mesh; + default: return itype_other; + } +} + +// Why a call was not executed. "not-implemented": no execution path exists yet for the type. +enum IndirectSkip { + skip_not_recording, // the list is not recording a desktop list (not render mode, or closed) + skip_unknown_signature, // the signature was not created through device slot 41 + skip_not_implemented, // no execution path for this type (yet) + skip_switched_off, // the type's env switch is off + skip_no_pipeline, // the bound pipeline has no desktop translation (or the path refused the call) + skip_unresolved_buffer, // argument or count buffer has no in-place desktop window (or no index data) + skip_zero_count, // max count 0 + skip_topology, // a draw with a console-only topology (rect list) + skip_no_ring, // the private argument ring could not be created or the record is too large + skip_no_guard, // the argument guard pass could not be created (calls are never executed unguarded) + skip_reasons +}; +constexpr const char* indirect_skip_names[skip_reasons] = {"not-recording", "unknown-signature", "not-implemented", "off", + "no-pipeline", "unresolved-buffer", "zero-count", "unsupported-topology", + "no-ring", "no-guard"}; + +struct IndirectCounters { + LONG calls[itype_types]; + LONG executed[itype_types]; + LONG skipped[skip_reasons][itype_types]; + LONG with_count_buffer; // calls that pass a count resource + LONG max_count_above_one; // calls with max count > 1 + LONG max_count_max; // largest max count seen +}; +IndirectCounters indirect_counts; + +void indirect_skip(int type, IndirectSkip why) { InterlockedIncrement(&indirect_counts.skipped[why][type]); } + +// The signature's stride and last argument type, through a one-entry per-thread cache in front of the +// shared signature table (about 5000 calls a frame use five signatures). +bool indirect_signature(const void* signature, UINT* stride, UINT* argument_type) +{ + thread_local const void* last = nullptr; + thread_local UINT last_stride = 0, last_type = 0; + if (signature && signature == last) { + *stride = last_stride; + *argument_type = last_type; + return true; + } + bool found = false; + AcquireSRWLockShared(&signature_lock); + const auto it = signature_infos().find(signature); + if (it != signature_infos().end() && !it->second.args.empty()) { + *stride = it->second.stride; + *argument_type = static_cast<UINT>(it->second.args.back().Type); + found = true; + } + ReleaseSRWLockShared(&signature_lock); + if (found) { + last = signature; + last_stride = *stride; + last_type = *argument_type; + } + return found; +} + +void max_count_seen(UINT max_count) +{ + if (max_count > 1) InterlockedIncrement(&indirect_counts.max_count_above_one); + LONG seen = indirect_counts.max_count_max; + while (static_cast<LONG>(max_count) > seen) { + const LONG previous = InterlockedCompareExchange(&indirect_counts.max_count_max, static_cast<LONG>(max_count), seen); + if (previous == seen) break; + seen = previous; + } +} + +// ---- Execution ------------------------------------------------------------------------------- +// +// Per call: the argument record (and count dword) is copied from the window over the title's memory +// into a private argument ring, and ExecuteIndirect reads the ring (DESIGN.md section 3): +// window UAV -> COPY_SOURCE, ring COMMON -> COPY_DEST; copy; window -> UAV, ring -> INDIRECT_ARGUMENT; +// ExecuteIndirect; [read-back copy]; ring -> COMMON. +// A window rests in COMMON or UAV-promoted (compute binds it as UAV); UAV is a valid BeforeState for both. + +// X2W_INDIRECT_OFF=1: nothing executed. X2W_INDIRECT_DISPATCH=0 / X2W_INDIRECT_MESH=0: per type (default on). +// Draw/DrawIndexed: default OFF until a test or run has exercised it; X2W_INDIRECT_DRAW=1 turns it on. +// X2W_INDIRECT_READBACK=<n>: read back the first n executed records per report. +bool indirect_env_zero(const char* name) +{ + char value[8]{}; + return GetEnvironmentVariableA(name, value, sizeof(value)) && value[0] == '0'; +} +bool indirect_type_enabled(int type) +{ + static const bool off = x2w_local::env_on("X2W_INDIRECT_OFF"); + static const bool dispatch = !indirect_env_zero("X2W_INDIRECT_DISPATCH"); + static const bool draw = x2w_local::env_on("X2W_INDIRECT_DRAW"); + static const bool mesh = !indirect_env_zero("X2W_INDIRECT_MESH"); + if (off) return false; + return type == itype_dispatch ? dispatch : type == itype_draw || type == itype_indexed ? draw : type == itype_mesh ? mesh : false; +} +LONG indirect_readback_wanted() +{ + static const LONG wanted = [] { + char value[16]{}; + const LONG n = GetEnvironmentVariableA("X2W_INDIRECT_READBACK", value, sizeof(value)) ? std::atol(value) : 0L; + return n < 0 ? 0L : n > 4096 ? 4096L : n; + }(); + return wanted; +} + +// Mesh pipelines (agent mesh): binds the translated mesh pipeline and root state on list `self`, then +// calls indirect_issue(self, list) and returns true when it issued. Null until mesh provides one. +using IndirectMeshHook = bool (*)(Wrapper* self, ID3D12GraphicsCommandList* list); +IndirectMeshHook indirect_mesh_hook = nullptr; +// LOCAL meshrt (d3d12_mesh.inl): a DispatchMesh call that cannot be issued is refused before it is staged. +bool mesh_prepare(Wrapper* self, ID3D12GraphicsCommandList* list); +void mesh_trace_call(Wrapper* self, bool drawn, const Translation* tr, const char* why); // LOCAL meshrt: traced frame only + +// The private argument ring: default heap, rests in COMMON between calls. LOCAL memcut: a chain of chunks recycled +// only after the lists that used them executed and their fences passed (d3d12_upload_ring.inl, indirect instance; +// X2W_INDIRECT_RING=legacy = the old 16 MiB ring). The chunk is per call: IndirectPending::ring. +constexpr u64 indirect_ring_max_take = u64{1} << 20; // one call's record + count, as before (a sixteenth of 16 MiB) +// The chunk holding `bytes` (whole 256-byte slots) at *offset, or nullptr when refused (too large, or the cap). +ID3D12Resource* indirect_ring_take(u64 bytes, u64* offset) +{ + return bytes && bytes <= indirect_ring_max_take ? reserve_indirect_ring(bytes, offset) : nullptr; +} + +// ---- Argument guard ---------------------------------------------------------------------------- +// +// GPU-written records may be garbage while the shaders that produce them are wrong or untranslated, and +// a Dispatch with huge group counts hangs the GPU (device removed). Every record copied into the ring is +// checked ON THE GPU by one tiny compute pass before ExecuteIndirect reads it; a record over the bounds +// is zeroed (a zero-group dispatch / zero-count draw does nothing) and counted in a CPU-visible counter +// that report_indirect reads once per report. No CPU read-back per call. +// Dispatch / DispatchMesh {x, y, z}: each <= X2W_INDIRECT_MAX_GROUPS (default 65535, the desktop limit) +// and x*y*z <= X2W_INDIRECT_MAX_GROUP_PRODUCT (default 2^24; DispatchMesh also <= 2^22, the desktop limit). +// Draw {vertices, instances, ..} / DrawIndexed {indices, instances, ..}: count <= X2W_INDIRECT_MAX_VERTICES +// (default 2^24), instances <= X2W_INDIRECT_MAX_INSTANCES (default 2^16), count*instances <= +// X2W_INDIRECT_MAX_DRAW_PRODUCT (default 2^26). +// X2W_INDIRECT_GUARD=0 executes unguarded (debugging only). When the guard cannot be created, calls are +// skipped ("no-guard"), never executed unguarded. +// Not covered: a record within the bounds can still make a shader loop or fault (wrong root data, +// out-of-range addresses); start offsets (StartIndex, BaseVertex, StartInstance) are not checked +// (index fetches are bounds-checked by the desktop); the count dword is not checked (ExecuteIndirect +// already takes min(count, max count)). +UINT indirect_env_u32(const char* name, UINT fallback) +{ + char value[16]{}; + if (!GetEnvironmentVariableA(name, value, sizeof(value)) || !value[0]) return fallback; + const unsigned long long n = std::strtoull(value, nullptr, 0); + return n && n <= 0xffffffffull ? static_cast<UINT>(n) : fallback; +} +struct IndirectBounds { + UINT groups, group_product, mesh_product, vertices, instances, draw_product; +}; +const IndirectBounds& indirect_bounds() +{ + static const IndirectBounds b = [] { + IndirectBounds v{}; + v.groups = indirect_env_u32("X2W_INDIRECT_MAX_GROUPS", 65535); + v.group_product = indirect_env_u32("X2W_INDIRECT_MAX_GROUP_PRODUCT", 1u << 24); + v.mesh_product = v.group_product < (1u << 22) ? v.group_product : (1u << 22); + v.vertices = indirect_env_u32("X2W_INDIRECT_MAX_VERTICES", 1u << 24); + v.instances = indirect_env_u32("X2W_INDIRECT_MAX_INSTANCES", 1u << 16); + v.draw_product = indirect_env_u32("X2W_INDIRECT_MAX_DRAW_PRODUCT", 1u << 26); + return v; + }(); + return b; +} +bool indirect_guard_wanted() +{ + static const bool wanted = !indirect_env_zero("X2W_INDIRECT_GUARD"); + return wanted; +} + +constexpr char indirect_guard_source[] = R"( +RWByteAddressBuffer ring : register(u0); +RWByteAddressBuffer zeroed : register(u1); +cbuffer Bounds : register(b0) { uint stride; uint records; uint kind; uint counter; uint each; uint product; uint each2; uint unused; }; +[numthreads(64, 1, 1)] +void cs(uint3 id : SV_DispatchThreadID) +{ + if (id.x >= records) return; + const uint at = id.x * stride; + bool bad = false; + if (kind == 0) { + const uint3 g = ring.Load3(at); + bad = g.x > each || g.y > each || g.z > each; + if (!bad && g.x != 0 && g.y > product / g.x) bad = true; + const uint xy = g.x * g.y; + if (!bad && xy != 0 && g.z > product / xy) bad = true; + if (bad) ring.Store3(at, uint3(0, 0, 0)); + } else { + const uint2 d = ring.Load2(at); + bad = d.x > each || d.y > each2 || (d.x != 0 && d.y > product / d.x); + if (bad) ring.Store2(at, uint2(0, 0)); + } + if (bad) { + uint previous; + zeroed.InterlockedAdd(counter * 4, 1, previous); + } +} +)"; +ID3D12RootSignature* indirect_guard_root; +ID3D12PipelineState* indirect_guard_pso; +ID3D12Resource* indirect_guard_counter; // 8 dwords: records zeroed, by counter type +const volatile std::uint32_t* indirect_guard_words; // mapped (CPU-visible custom heap), or null +std::uint32_t indirect_guard_reported[itype_types]; +bool ensure_indirect_guard() +{ + static SRWLOCK lock = SRWLOCK_INIT; + static bool failed; + if (indirect_guard_pso) return true; + AcquireSRWLockExclusive(&lock); + if (!indirect_guard_pso && !failed) { + ID3D12Device* device = device_of(the_device); + ID3DBlob *code = nullptr, *errors = nullptr, *serialized = nullptr; + HRESULT hr = D3DCompile(indirect_guard_source, sizeof(indirect_guard_source) - 1, "indirect_guard", nullptr, nullptr, "cs", + "cs_5_0", D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, &code, &errors); + if (FAILED(hr) && errors) log("x2w-indirect guard compile: %.400s", static_cast<const char*>(errors->GetBufferPointer())); + D3D12_ROOT_PARAMETER params[3]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[0].Descriptor.ShaderRegister = 0; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor.ShaderRegister = 1; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[2].Constants.Num32BitValues = 8; + for (auto& p : params) p.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC root_desc{3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + if (SUCCEEDED(hr)) hr = D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, nullptr); + ID3D12RootSignature* root = nullptr; + if (SUCCEEDED(hr)) + hr = device->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), IID_PPV_ARGS(&root)); + ID3D12PipelineState* pso = nullptr; + if (SUCCEEDED(hr)) { + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root; + desc.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + hr = device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso)); + } + // The counter: a CPU-visible custom heap (write-back, system memory) so a report reads it without a + // copy; if the adapter refuses, a default-heap counter (the guard still runs, counts are not shown). + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 64; + 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; + ID3D12Resource* counter = nullptr; + void* mapped = nullptr; + HRESULT counter_hr = E_FAIL; + if (SUCCEEDED(hr)) { + const D3D12_HEAP_PROPERTIES visible{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0}; + counter_hr = device->CreateCommittedResource(&visible, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&counter)); + if (SUCCEEDED(counter_hr) && SUCCEEDED(counter->Map(0, nullptr, &mapped))) { + std::memset(mapped, 0, 64); + } else { + mapped = nullptr; + if (counter) counter->Release(), counter = nullptr; + const D3D12_HEAP_PROPERTIES local{D3D12_HEAP_TYPE_DEFAULT}; + hr = device->CreateCommittedResource(&local, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&counter)); + } + } + const IndirectBounds& b = indirect_bounds(); + log("x2w-indirect argument guard -> 0x%08lx (counter %s 0x%08lx): groups <= %u each, product <= %u (mesh %u); draws count <= %u, " + "instances <= %u, product <= %u", + static_cast<unsigned long>(hr), mapped ? "visible" : "not visible", static_cast<unsigned long>(counter_hr), b.groups, + b.group_product, b.mesh_product, b.vertices, b.instances, b.draw_product); + if (code) code->Release(); + if (errors) errors->Release(); + if (serialized) serialized->Release(); + if (SUCCEEDED(hr) && pso && root && counter) { + indirect_guard_root = root; + indirect_guard_counter = counter; + indirect_guard_words = static_cast<const volatile std::uint32_t*>(mapped); + indirect_guard_pso = pso; + } else { + if (pso) pso->Release(); + if (root) root->Release(); + if (counter) counter->Release(); + failed = true; + } + } + ReleaseSRWLockExclusive(&lock); + return indirect_guard_pso != nullptr; +} +// Records the guard pass over `records` records at ring offset `slot` (ring in UNORDERED_ACCESS). +void indirect_guard(ID3D12GraphicsCommandList* list, ID3D12Resource* ring, int type, u64 slot, UINT stride, UINT records) +{ + const IndirectBounds& b = indirect_bounds(); + const bool groups = type == itype_dispatch || type == itype_mesh; + const UINT constants[8] = {stride, records, groups ? 0u : 1u, static_cast<UINT>(type), + groups ? b.groups : b.vertices, groups ? (type == itype_mesh ? b.mesh_product : b.group_product) : b.draw_product, + b.instances, 0}; + list->SetPipelineState(indirect_guard_pso); + list->SetComputeRootSignature(indirect_guard_root); + list->SetComputeRootUnorderedAccessView(0, ring->GetGPUVirtualAddress() + slot); + list->SetComputeRootUnorderedAccessView(1, indirect_guard_counter->GetGPUVirtualAddress()); + list->SetComputeRoot32BitConstants(2, 8, constants, 0); + // LOCAL: the guard pass is a Dispatch op in DRED too; record it so the report's Dispatch op count matches. + const u64 issue_key = cx_issue_key; + const char issue_path = cx_issue_path; + cx_issue_key = 0; + cx_issue_path = 'g'; + note_issued_dispatch(list, (records + 63) / 64, 1, 1, false); + cx_issue_key = issue_key; + cx_issue_path = issue_path; + list->Dispatch((records + 63) / 64, 1, 1); +} + +// Read-back of executed records (X2W_INDIRECT_READBACK): 32-byte slots, [0] marker copied from the upload +// ring after the record, [1..7] the first 28 bytes of the record as ExecuteIndirect read it. +constexpr UINT indirect_readback_slots = 4096; +ID3D12Resource* indirect_readback; +const std::uint32_t* indirect_readback_words; +volatile LONG indirect_readback_used; +LONG indirect_readback_generation = 1; +unsigned char indirect_readback_type[indirect_readback_slots]; +struct CullReadback { + LONG frame; + u64 list, source_gpuva, source_at; + UINT max_count; + bool has_count; +}; +CullReadback cull_readback[indirect_readback_slots]; +bool ensure_indirect_readback() +{ + static SRWLOCK lock = SRWLOCK_INIT; + static bool failed; + if (indirect_readback_words) return true; + AcquireSRWLockExclusive(&lock); + if (!indirect_readback_words && !failed) { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = u64{indirect_readback_slots} * 32; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ID3D12Resource* created = nullptr; + void* mapped = nullptr; + HRESULT hr = device_of(the_device)->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&created)); + if (SUCCEEDED(hr)) hr = created->Map(0, nullptr, &mapped); + log("x2w-indirect read-back buffer (%u records) -> 0x%08lx", indirect_readback_slots, static_cast<unsigned long>(hr)); + if (SUCCEEDED(hr)) { + indirect_readback = created; + indirect_readback_words = static_cast<const std::uint32_t*>(mapped); + } else { + failed = true; + } + } + ReleaseSRWLockExclusive(&lock); + return indirect_readback_words != nullptr; +} + +// The window and window offset of [offset, offset + bytes) of a buffer wrapper's title memory. The +// lookup is keyed on the wrapper's whole range (cached per frame by desktop_range), so the thousands +// of records a frame do not each miss the cache. +bool indirect_window(Wrapper* resource, u64 offset, u64 bytes, ID3D12Resource** window, u64* at) +{ + if (!resource || resource->own().kind != resource_kind || !resource->own().title_memory) return false; + const u64 base = reinterpret_cast<u64>(resource->own().title_memory); + u64 width = 0; + if (auto* real = static_cast<ID3D12Resource*>(resource->own().real)) { + const D3D12_RESOURCE_DESC desc = real->GetDesc(); + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) width = desc.Width; + } + if (width && offset <= width && bytes <= width - offset && desktop_range(base, width, window, at)) { + *at += offset; + return true; + } + return desktop_range(base + offset, bytes, window, at); +} + +// The call being executed on this thread, handed to the dispatch / draw / mesh path, which binds the +// pipeline and then calls indirect_issue instead of its direct Dispatch / Draw. +struct IndirectPending { + Wrapper* list; + int type; + ID3D12CommandSignature* signature; + UINT stride, max_count; + ID3D12Resource* args_window; + u64 args_at; + ID3D12Resource* count_window; // null: no count buffer + u64 count_at; + bool issued; + bool cull_sample; + IndirectSkip refused; // set by an issue path that refused the call + // Set by indirect_stage: the record (and count) sit in the ring at `slot`, checked by the guard; the + // ring is in `ring_state` on this list until indirect_issue / indirect_unstage returns it to COMMON. + bool staged; + ID3D12Resource* ring; // LOCAL memcut: the argument ring chunk holding the record + u64 slot, ring_count_at; + D3D12_RESOURCE_STATES ring_state; +}; +thread_local IndirectPending* indirect_current; +// LOCAL meshrt: in a traced frame, the DispatchMesh call's record in title memory (CPU view at record time) for the +// x2w-frame mesh line (d3d12_mesh.inl mesh_trace_call); null otherwise. +thread_local const unsigned char* mesh_trace_record; +thread_local UINT mesh_trace_stride, mesh_trace_max; +// Also outside the traced frame while an X2W_MESH_DUMP_INPUTS key is not dumped yet or X2W_MESH_STATS_FRAMES collects +// (d3d12_mesh.inl): both select by the record's group counts. +bool mesh_fs_collecting(); +bool mesh_record_wanted() { return trace_frame_active || mesh_dump_pending() || mesh_fs_collecting(); } + +bool indirect_pending(Wrapper* self) { return indirect_current && !indirect_current->issued && indirect_current->list == self; } + +void indirect_transition(D3D12_RESOURCE_BARRIER& b, ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) +{ + 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; +} + +// Records, BEFORE the dispatch / draw / mesh path binds its pipeline and root state (the guard pass binds +// its own compute pipeline): the copy of the record into the ring, the guard pass over it and the +// barriers that leave the ring readable as indirect arguments. A forwarded title pipeline (pipeline_real) +// is bound again afterwards. Returns false (p->refused set) when nothing was recorded. +bool indirect_stage(Wrapper* self, ID3D12GraphicsCommandList* list, IndirectPending* p) +{ + const bool guard = indirect_guard_wanted(); + if (guard && !ensure_indirect_guard()) { + p->refused = skip_no_guard; + return false; + } + const u64 record_bytes = u64{p->stride} * p->max_count; + const u64 count_at = (record_bytes + 15) & ~u64{15}; + u64 slot = 0; + ID3D12Resource* const indirect_ring = indirect_ring_take(count_at + (p->count_window ? 16 : 0), &slot); + if (!indirect_ring) { + p->refused = skip_no_ring; + return false; + } + const bool readback = (!cull_heap_probe() || p->cull_sample) && + indirect_readback_wanted() && indirect_readback_used < indirect_readback_wanted() && ensure_indirect_readback(); + D3D12_RESOURCE_BARRIER b[3]; + UINT n = 0; + indirect_transition(b[n++], p->args_window, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + if (p->count_window && p->count_window != p->args_window) + indirect_transition(b[n++], p->count_window, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + indirect_transition(b[n++], indirect_ring, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->ResourceBarrier(n, b); + list->CopyBufferRegion(indirect_ring, slot, p->args_window, p->args_at, record_bytes); + if (p->count_window) list->CopyBufferRegion(indirect_ring, slot + count_at, p->count_window, p->count_at, 4); + const D3D12_RESOURCE_STATES ring_state = readback ? D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_COPY_SOURCE + : D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + for (UINT i = 0; i < n; ++i) std::swap(b[i].Transition.StateBefore, b[i].Transition.StateAfter); + b[n - 1].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; + b[n - 1].Transition.StateAfter = guard ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS : ring_state; + list->ResourceBarrier(n, b); + if (guard) { + indirect_guard(list, indirect_ring, p->type, slot, p->stride, p->max_count); + D3D12_RESOURCE_BARRIER after; + indirect_transition(after, indirect_ring, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, ring_state); + list->ResourceBarrier(1, &after); + const Pass& pass = pass_of(self); + if (pass.pipeline_real && pass.pipeline) list->SetPipelineState(static_cast<ID3D12PipelineState*>(pass.pipeline->own().real)); + } + p->staged = true; + p->ring = indirect_ring; + p->slot = slot; + p->ring_count_at = count_at; + p->ring_state = ring_state; + return true; +} +// A staged call that no path issued: the ring goes back to COMMON on this list. +void indirect_unstage(ID3D12GraphicsCommandList* list, IndirectPending* p) +{ + if (!p->staged) return; + D3D12_RESOURCE_BARRIER b; + indirect_transition(b, p->ring, p->ring_state, D3D12_RESOURCE_STATE_COMMON); + list->ResourceBarrier(1, &b); + p->staged = false; +} + +// Records the ExecuteIndirect for the pending (staged) call. The pipeline and root state must already be +// bound on `list`. +bool indirect_issue(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + IndirectPending* p = indirect_current; + if (!p || p->issued || !p->staged || p->list != self || !list) return false; + const u64 record_bytes = u64{p->stride} * p->max_count; + const u64 slot = p->slot, count_at = p->ring_count_at; + ID3D12Resource* const indirect_ring = p->ring; + const D3D12_RESOURCE_STATES ring_state = p->ring_state; + const bool readback = (ring_state & D3D12_RESOURCE_STATE_COPY_SOURCE) != 0; + list->ExecuteIndirect(p->signature, p->max_count, indirect_ring, slot, p->count_window ? indirect_ring : nullptr, + p->count_window ? slot + count_at : 0); + if (readback) { + const LONG index = InterlockedIncrement(&indirect_readback_used) - 1; + u64 marker_at = 0; + ID3D12Resource* marker_chunk = nullptr; + auto* marker = index < indirect_readback_wanted() ? reserve_upload_ring(4, &marker_at, &marker_chunk, nullptr) : nullptr; + if (marker) { + const std::uint32_t value = 0x1d000000u | (static_cast<std::uint32_t>(indirect_readback_generation & 0xff) << 16) | + static_cast<std::uint32_t>(index); + std::memcpy(marker, &value, 4); + indirect_readback_type[index] = static_cast<unsigned char>(p->type); + const u64 dest = u64{static_cast<UINT>(index)} * 32; + if (p->cull_sample) { + cull_readback[index] = {frame_number, reinterpret_cast<u64>(self), p->args_window->GetGPUVirtualAddress(), + p->args_at, p->max_count, p->count_window != nullptr}; + list->CopyBufferRegion(indirect_readback, dest + 4, indirect_ring, slot, 12); + if (p->count_window) list->CopyBufferRegion(indirect_readback, dest + 16, indirect_ring, slot + count_at, 4); + } else { + list->CopyBufferRegion(indirect_readback, dest + 4, indirect_ring, slot, record_bytes < 28 ? record_bytes : 28); + } + list->CopyBufferRegion(indirect_readback, dest, marker_chunk, marker_at, 4); + } + } + D3D12_RESOURCE_BARRIER rest; + indirect_transition(rest, indirect_ring, ring_state, D3D12_RESOURCE_STATE_COMMON); + list->ResourceBarrier(1, &rest); + p->staged = false; + p->issued = true; + return true; +} + +// Hook for the final Dispatch of both dispatch paths (d3d12_compute.inl execute_translated, +// d3d12_xs_device.cpp execute_dispatch): the indirect call when one is pending on this list. +void indirect_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z) +{ + if (indirect_pending(self)) { + note_issued_dispatch(list, x, y, z, true); // LOCAL: for the DRED report (d3d12_xs_device.cpp) + indirect_issue(self, list); + return; + } + note_issued_dispatch(list, x, y, z, false); + list->Dispatch(x, y, z); +} + +// Hook for the issue point of draw_translated (d3d12_draw.inl): the whole index buffer view goes to +// the upload ring (as the direct path copies its index range), then the indirect call. +bool indirect_draw_issue(Wrapper* self, ID3D12GraphicsCommandList* list, bool indexed) +{ + if (!indirect_pending(self)) return false; + if (indexed) { + const Pass& pass = pass_of(self); + const std::size_t bytes = pass.ib.SizeInBytes < (16u << 20) ? pass.ib.SizeInBytes : (16u << 20); + u64 offset = 0; + ID3D12Resource* chunk = nullptr; + if (!pass.ib.BufferLocation || !bytes || readable_window(pass.ib.BufferLocation, bytes) < bytes || + !frame_copy(pass.ib.BufferLocation, bytes, &offset, &chunk)) { + indirect_current->refused = skip_unresolved_buffer; + return false; + } + const D3D12_INDEX_BUFFER_VIEW view{chunk->GetGPUVirtualAddress() + offset, static_cast<UINT>(bytes), + pass.ib.Format == DXGI_FORMAT_R16_UINT ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; + list->IASetIndexBuffer(&view); + } + return indirect_issue(self, list); +} + +u64 compute_key_of(Wrapper* self); +bool execute_dispatch(Wrapper* self, UINT x, UINT y, UINT z, u64 key); + +void indirect_announce() +{ + static LONG once; + if (InterlockedExchange(&once, 1)) return; + D3D12_FEATURE_DATA_D3D12_OPTIONS7 options7{}; + const HRESULT hr = device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &options7, sizeof(options7)); + log("x2w-indirect execution: dispatch %s, draw %s, mesh %s (hook %s), guard %s, read-back %ld records per report; MeshShaderTier %d (0x%08lx)", + indirect_type_enabled(itype_dispatch) ? "on" : "off", indirect_type_enabled(itype_draw) ? "on" : "off", + indirect_type_enabled(itype_mesh) ? "on" : "off", indirect_mesh_hook ? "set" : "absent", + indirect_guard_wanted() ? "on" : "OFF (X2W_INDIRECT_GUARD=0)", indirect_readback_wanted(), + SUCCEEDED(hr) ? static_cast<int>(options7.MeshShaderTier) : -1, static_cast<unsigned long>(hr)); +} + +// Read-back of a call that is NOT executed (no path or no pipeline): the record as the GPU sees it at +// that point of the list, copied straight from the window. Slot type = counter type | 0x80. +void indirect_probe(ID3D12GraphicsCommandList* list, int type, ID3D12Resource* window, u64 at, u64 bytes) +{ + if (cull_heap_probe() || !indirect_readback_wanted() || indirect_readback_used >= indirect_readback_wanted() || !ensure_indirect_readback()) return; + const LONG index = InterlockedIncrement(&indirect_readback_used) - 1; + u64 marker_at = 0; + ID3D12Resource* marker_chunk = nullptr; + auto* marker = index < indirect_readback_wanted() ? reserve_upload_ring(4, &marker_at, &marker_chunk, nullptr) : nullptr; + if (!marker) return; + const std::uint32_t value = 0x1d000000u | (static_cast<std::uint32_t>(indirect_readback_generation & 0xff) << 16) | + static_cast<std::uint32_t>(index); + std::memcpy(marker, &value, 4); + indirect_readback_type[index] = static_cast<unsigned char>(type | 0x80); + const u64 dest = u64{static_cast<UINT>(index)} * 32; + D3D12_RESOURCE_BARRIER b; + indirect_transition(b, window, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &b); + list->CopyBufferRegion(indirect_readback, dest + 4, window, at, bytes < 28 ? bytes : 28); + std::swap(b.Transition.StateBefore, b.Transition.StateAfter); + list->ResourceBarrier(1, &b); + list->CopyBufferRegion(indirect_readback, dest, marker_chunk, marker_at, 4); +} + +void indirect_run(Wrapper* self, ID3D12GraphicsCommandList* list, int type, Wrapper* signature, UINT stride, UINT max_count, + Wrapper* arguments, u64 offset, Wrapper* count_resource, u64 count_offset) +{ + indirect_announce(); + if (type == itype_other || (type == itype_mesh && !indirect_mesh_hook)) { + ID3D12Resource* window = nullptr; + u64 at = 0; + if (indirect_readback_wanted() && indirect_window(arguments, offset, u64{stride} * max_count, &window, &at)) + indirect_probe(list, type, window, at, u64{stride} * max_count); + return indirect_skip(type, skip_not_implemented); + } + if (!indirect_type_enabled(type)) return indirect_skip(type, skip_switched_off); + auto* desktop_signature = static_cast<ID3D12CommandSignature*>(signature->own().real); + if (!desktop_signature) return indirect_skip(type, skip_unknown_signature); + if (type == itype_draw || type == itype_indexed) { + if (pass_of(self).topology == 0x11) return indirect_skip(type, skip_topology); + } + IndirectPending p{}; + p.list = self; + p.type = type; + p.signature = desktop_signature; + p.stride = stride; + p.max_count = max_count; + p.refused = skip_no_pipeline; + p.cull_sample = cull_heap_probe() && trace_frame_active && type == itype_dispatch && compute_key_of(self) == cull_heap_probe_key(); + if (!indirect_window(arguments, offset, u64{stride} * max_count, &p.args_window, &p.args_at) || + (count_resource && !indirect_window(count_resource, count_offset, 4, &p.count_window, &p.count_at))) + return indirect_skip(type, skip_unresolved_buffer); + mesh_trace_record = nullptr; + if (type == itype_mesh && mesh_record_wanted()) { // LOCAL meshrt: traced frame, pending dump, frame statistics + mesh_trace_record = arguments->own().kind == resource_kind && arguments->own().title_memory + ? static_cast<const unsigned char*>(arguments->own().title_memory) + offset : nullptr; + mesh_trace_stride = stride; + mesh_trace_max = max_count; + } + if (type == itype_mesh && !mesh_prepare(self, list)) return indirect_skip(type, skip_no_pipeline); // LOCAL meshrt: before staging + if (!indirect_stage(self, list, &p)) { + if (type == itype_mesh && trace_frame_active) mesh_trace_call(self, false, nullptr, indirect_skip_names[p.refused]); // LOCAL meshrt + return indirect_skip(type, p.refused); + } + indirect_current = &p; + if (type == itype_dispatch) execute_dispatch(self, 0, 0, 0, compute_key_of(self)); + else if (type == itype_mesh) indirect_mesh_hook(self, list); + else draw_translated(self, type == itype_indexed, 0, 0, 0, 0, 0); + indirect_current = nullptr; + indirect_unstage(list, &p); + if (p.issued) { + InterlockedIncrement(&indirect_counts.executed[type]); + } else { + indirect_probe(list, type, p.args_window, p.args_at, u64{stride} * max_count); + indirect_skip(type, p.refused); + } +} + +// List slot 61 (called from list_execute_indirect before its frame trace). +void indirect_execute(Wrapper* self, void* signature, UINT max_count, Wrapper* arguments, u64 offset, Wrapper* count_resource, + u64 count_offset) +{ + UINT stride = 0, argument_type = ~0u; + const bool known = indirect_signature(signature, &stride, &argument_type); + const int type = known ? indirect_type_of(argument_type) : itype_other; + InterlockedIncrement(&indirect_counts.calls[type]); + if (count_resource) InterlockedIncrement(&indirect_counts.with_count_buffer); + max_count_seen(max_count); + static LONG described; + if (first_calls(described, 16)) { + const void* args_memory = arguments && arguments->own().kind == resource_kind ? arguments->own().title_memory : nullptr; + const void* count_memory = count_resource && count_resource->own().kind == resource_kind ? count_resource->own().title_memory : nullptr; + log("x2w-indirect call: signature %p type %u stride %u, max count %u, arguments %p (title %p) + 0x%llx, count %p (title %p) + 0x%llx", + signature, argument_type, stride, max_count, static_cast<void*>(arguments), args_memory, offset, + static_cast<void*>(count_resource), count_memory, count_offset); + } + auto* list = recording(self); + if (!list) return indirect_skip(type, skip_not_recording); + if (!known) return indirect_skip(type, skip_unknown_signature); + if (!max_count) return indirect_skip(type, skip_zero_count); + indirect_run(self, list, type, static_cast<Wrapper*>(signature), stride, max_count, arguments, offset, count_resource, count_offset); +} + +// The records read back since the last report: how many the GPU copied (marker present), how many were +// non-zero, how many break the v1 draw assumption (entry values 0: indexed BaseVertex and StartInstance, +// draw StartInstance), and up to 6 samples. Then a new generation starts. +void report_indirect_readback() +{ + if (!indirect_readback_wanted() || !indirect_readback_words) return; + const LONG used = InterlockedExchange(&indirect_readback_used, indirect_readback_wanted()); // no new copies while reading + const LONG count = used < indirect_readback_wanted() ? used : indirect_readback_wanted(); + // [0] executed calls (record as ExecuteIndirect read it), [1] calls not executed (record at that point of the list) + LONG arrived[2] = {}, records[2][itype_types] = {}, nonzero[2][itype_types] = {}, broken = 0; + char samples[640] = ""; + int at = 0, shown = 0; + for (LONG i = 0; i < count; ++i) { + const std::uint32_t* w = indirect_readback_words + u64{static_cast<UINT>(i)} * 8; + const std::uint32_t expected = 0x1d000000u | (static_cast<std::uint32_t>(indirect_readback_generation & 0xff) << 16) | + static_cast<std::uint32_t>(i); + if (w[0] != expected) continue; + if (cull_heap_probe()) { + const CullReadback& sample = cull_readback[i]; + log("x2w-cull-heap frame %ld list 0x%llx key %016llx GPU post-guard first indirect XYZ %u %u %u " + "max-count %u count-buffer %s effective-count %u source GPUVA 0x%llx+0x%llx marker %08x", + sample.frame, sample.list, cull_heap_probe_key(), w[1], w[2], w[3], sample.max_count, + sample.has_count ? "yes" : "no", sample.has_count && w[4] < sample.max_count ? w[4] : sample.max_count, + sample.source_gpuva, sample.source_at, expected); + } + const int probed = indirect_readback_type[i] & 0x80 ? 1 : 0; + const int type = (indirect_readback_type[i] & 0x7f) < itype_types ? (indirect_readback_type[i] & 0x7f) : itype_other; + ++arrived[probed]; + ++records[probed][type]; + const bool any = w[1] | w[2] | w[3] | w[4] | w[5]; + if (any) ++nonzero[probed][type]; + if (!probed && ((type == itype_indexed && (w[4] || w[5])) || (type == itype_draw && w[4]))) ++broken; + if (any && shown < 8 && at < static_cast<int>(sizeof(samples)) - 80) { + at += std::snprintf(samples + at, sizeof(samples) - at, "%s%s%s %u %u %u %u %u", shown ? "; " : "", indirect_type_names[type], + probed ? "(not run)" : "", w[1], w[2], w[3], w[4], w[5]); + ++shown; + } + } + const auto sum = [](const LONG* v) { return v[0] + v[1] + v[2] + v[3] + v[4]; }; + log("x2w-indirect read-back: %ld slots; executed: %ld arrived, non-zero %ld (draw %ld/%ld, indexed %ld/%ld, dispatch %ld/%ld, mesh %ld/%ld, " + "other %ld/%ld); not executed: %ld arrived, non-zero %ld (draw %ld/%ld, indexed %ld/%ld, dispatch %ld/%ld, mesh %ld/%ld, other %ld/%ld); " + "executed draws with base vertex / start instance not 0: %ld; samples: %s", + count, arrived[0], sum(nonzero[0]), nonzero[0][0], records[0][0], nonzero[0][1], records[0][1], nonzero[0][2], records[0][2], + nonzero[0][3], records[0][3], nonzero[0][4], records[0][4], arrived[1], sum(nonzero[1]), nonzero[1][0], records[1][0], + nonzero[1][1], records[1][1], nonzero[1][2], records[1][2], nonzero[1][3], records[1][3], nonzero[1][4], records[1][4], broken, + shown ? samples : "none"); + ++indirect_readback_generation; + InterlockedExchange(&indirect_readback_used, 0); +} + +// Every 300 frames (queue_present): one line with the calls by type, the executed calls and the +// skipped calls by reason (each reason with its non-zero types). Counters restart after each line. +void report_indirect(LONG frames) +{ + IndirectCounters c{}; + for (int t = 0; t < itype_types; ++t) { + c.calls[t] = InterlockedExchange(&indirect_counts.calls[t], 0); + c.executed[t] = InterlockedExchange(&indirect_counts.executed[t], 0); + for (int r = 0; r < skip_reasons; ++r) c.skipped[r][t] = InterlockedExchange(&indirect_counts.skipped[r][t], 0); + } + c.with_count_buffer = InterlockedExchange(&indirect_counts.with_count_buffer, 0); + c.max_count_above_one = InterlockedExchange(&indirect_counts.max_count_above_one, 0); + c.max_count_max = InterlockedExchange(&indirect_counts.max_count_max, 0); + LONG calls = 0, executed = 0; + for (int t = 0; t < itype_types; ++t) calls += c.calls[t], executed += c.executed[t]; + char skipped[768] = ""; + int at = 0; + for (int r = 0; r < skip_reasons; ++r) { + LONG total = 0; + for (int t = 0; t < itype_types; ++t) total += c.skipped[r][t]; + if (!total || at >= static_cast<int>(sizeof(skipped)) - 96) continue; + at += std::snprintf(skipped + at, sizeof(skipped) - at, "%s%s %ld [", at ? ", " : "", indirect_skip_names[r], total); + bool first = true; + for (int t = 0; t < itype_types; ++t) + if (c.skipped[r][t]) { + at += std::snprintf(skipped + at, sizeof(skipped) - at, "%s%s %ld", first ? "" : " ", indirect_type_names[t], c.skipped[r][t]); + first = false; + } + at += std::snprintf(skipped + at, sizeof(skipped) - at, "]"); + } + log("x2w-indirect %ld frames: calls %ld by type (draw %ld, indexed %ld, dispatch %ld, mesh %ld, other %ld); executed %ld " + "(draw %ld, indexed %ld, dispatch %ld, mesh %ld, other %ld); skipped by reason (%s); count buffer %ld, max count > 1 %ld, largest %ld", + frames, calls, c.calls[0], c.calls[1], c.calls[2], c.calls[3], c.calls[4], executed, c.executed[0], c.executed[1], c.executed[2], + c.executed[3], c.executed[4], at ? skipped : "none", c.with_count_buffer, c.max_count_above_one, c.max_count_max); + // Records the guard zeroed since the last report (the GPU adds to the counter; values of lists still in + // flight arrive in a later report). + if (indirect_guard_pso && executed) { + if (indirect_guard_words) { + std::uint32_t zeroed[itype_types]; + for (int t = 0; t < itype_types; ++t) { + const std::uint32_t now = indirect_guard_words[t]; + zeroed[t] = now - indirect_guard_reported[t]; + indirect_guard_reported[t] = now; + } + log("x2w-indirect guard: zeroed %u records over the bounds (draw %u, indexed %u, dispatch %u, mesh %u)", + zeroed[0] + zeroed[1] + zeroed[2] + zeroed[3], zeroed[0], zeroed[1], zeroed[2], zeroed[3]); + } else { + log("x2w-indirect guard: active, zeroed count not visible (default-heap counter)"); + } + } + report_indirect_readback(); +} diff --git a/src/startup_stubs/d3d12_mem_counters.h b/src/startup_stubs/d3d12_mem_counters.h new file mode 100644 index 0000000000..d0c332e388 --- /dev/null +++ b/src/startup_stubs/d3d12_mem_counters.h @@ -0,0 +1,55 @@ +#pragma once +#include <windows.h> +#include <psapi.h> +#include <cstdint> + +namespace x2w_memcut { +struct Counters { + volatile LONG64 ring_bytes; // upload-ring bytes reserved since the start (rounded to 512) + volatile LONG64 ring_frame_bytes; // ... in the frame being recorded + volatile LONG64 ring_frame_peak; // ... largest finished frame so far + volatile LONG ring_frame; + volatile LONG64 ring_refused; // requests over the per-copy cap (ring / 4) or without a ring + volatile LONG64 copy_frame_bytes; // frame_copy snapshots (CPU heap) in the frame being recorded + volatile LONG64 copy_frame_peak; + volatile LONG copy_frame; + volatile LONG64 bound_after_release; // textures bound for a draw after the title released them + volatile LONG64 viewed_after_release; // views created on a resource the title had released +}; +inline Counters& counters() +{ + static Counters c; + return c; +} +// Adds bytes to the current frame's sum; the first note of a new frame folds the old sum into peak. +// Approximate under races (a statistic, never used for a decision). +inline void per_frame(volatile LONG64& now, volatile LONG64& peak, volatile LONG& frame, LONG current, LONG64 bytes) +{ + if (InterlockedExchange(&frame, current) != current) { + const LONG64 last = InterlockedExchange64(&now, 0); + LONG64 seen = peak; + while (last > seen) { + const LONG64 previous = InterlockedCompareExchange64(&peak, last, seen); + if (previous == seen) break; + seen = previous; + } + } + InterlockedAdd64(&now, bytes); +} +inline void note_ring(LONG frame, std::uint64_t bytes) +{ + Counters& c = counters(); + InterlockedAdd64(&c.ring_bytes, static_cast<LONG64>(bytes)); + per_frame(c.ring_frame_bytes, c.ring_frame_peak, c.ring_frame, frame, static_cast<LONG64>(bytes)); +} +inline void note_ring_refused() { InterlockedIncrement64(&counters().ring_refused); } +inline void note_copy(LONG frame, std::uint64_t bytes) +{ + Counters& c = counters(); + per_frame(c.copy_frame_bytes, c.copy_frame_peak, c.copy_frame, frame, static_cast<LONG64>(bytes)); +} +inline void note_after_release(bool bound) +{ + InterlockedIncrement64(bound ? &counters().bound_after_release : &counters().viewed_after_release); +} +} // namespace x2w_memcut diff --git a/src/startup_stubs/d3d12_mem_counters.inl b/src/startup_stubs/d3d12_mem_counters.inl new file mode 100644 index 0000000000..dcc75feaf5 --- /dev/null +++ b/src/startup_stubs/d3d12_mem_counters.inl @@ -0,0 +1,271 @@ +namespace { +enum MemcutClass : int { mc_tex_target, mc_tex_uav, mc_tex, mc_buf_copied, mc_buf_aliased, mc_buf, mc_tiled, mc_heap, mc_count }; +const char* const memcut_class_names[mc_count] = {"tex-target", "tex-uav", "tex", "buf-copied", "buf-aliased", "buf", "tiled-srv", "heap"}; +struct MemcutEntry { + const void* real; // the desktop object classified (reclassify if the wrapper now holds another) + u64 bytes; + u64 title; // the title address the resource stands for, or 0 + int cls; + bool system; // not a default (video-memory) heap + bool placement_known; + signed char mapped; // title address in MEM_MAPPED memory: -1 not asked yet, 0 no, 1 yes + DXGI_FORMAT format; + bool reserved; // a reserved resource (no memory of its own): counted with 0 bytes, not as unsized +}; +struct MemcutTotals { + u64 bytes[mc_count][2][2]{}; // [class][system][dead] + u64 count[mc_count][2][2]{}; + u64 tex_size_bytes[4]{}, tex_size_count[4]{}; // live local textures: <1, <16, <64, >=64 MiB + std::unordered_map<int, u64> format_bytes; // live local textures by desktop format + std::vector<std::pair<u64, u64>> spans; // live local textures: [title, title + bytes) + u64 span_mapped = 0; + u64 wrappers = 0, unsized = 0; +}; +std::mutex memcut_mutex; +std::unordered_map<const void*, MemcutEntry>& memcut_cache() +{ + static std::unordered_map<const void*, MemcutEntry> m; + return m; +} + +bool memcut_system_heap(ID3D12Resource* resource) +{ + D3D12_HEAP_PROPERTIES props{}; + D3D12_HEAP_FLAGS flags{}; + if (FAILED(resource->GetHeapProperties(&props, &flags))) return false; // reserved: no own memory + if (props.Type == D3D12_HEAP_TYPE_DEFAULT) return false; + if (props.Type == D3D12_HEAP_TYPE_CUSTOM) return props.MemoryPoolPreference != D3D12_MEMORY_POOL_L1; + return true; +} + +MemcutEntry memcut_classify(ID3D12Resource* resource, void* title) +{ + MemcutEntry e{}; + e.real = resource; + e.mapped = -1; + const D3D12_RESOURCE_DESC desc = resource->GetDesc(); + const D3D12_RESOURCE_ALLOCATION_INFO info = device_of(the_device)->GetResourceAllocationInfo(0, 1, &desc); + e.bytes = info.SizeInBytes == ~0ull ? 0 : info.SizeInBytes; + D3D12_HEAP_PROPERTIES props{}; + D3D12_HEAP_FLAGS flags{}; + e.reserved = FAILED(resource->GetHeapProperties(&props, &flags)); // reserved (X2W_MEMCUT_RELEASE placeholder): no memory + if (e.reserved) e.bytes = 0; + e.system = memcut_system_heap(resource); + e.format = desc.Format; + e.title = reinterpret_cast<u64>(title); + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { + e.cls = mc_buf; // refined after the registry lock (memcut_placements) + } else { + e.placement_known = true; + e.cls = desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) ? mc_tex_target + : desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS ? mc_tex_uav : mc_tex; + } + return e; +} + +MemcutEntry memcut_heap(ID3D12Heap* heap) +{ + MemcutEntry e{}; + e.real = heap; + e.mapped = 0; + e.placement_known = true; + const D3D12_HEAP_DESC desc = heap->GetDesc(); + e.bytes = desc.SizeInBytes; + e.cls = mc_heap; + e.system = desc.Properties.Type == D3D12_HEAP_TYPE_UPLOAD || desc.Properties.Type == D3D12_HEAP_TYPE_READBACK || + (desc.Properties.Type == D3D12_HEAP_TYPE_CUSTOM && desc.Properties.MemoryPoolPreference != D3D12_MEMORY_POOL_L1); + return e; +} + +bool memcut_texture(int cls) { return cls == mc_tex || cls == mc_tex_target || cls == mc_tex_uav || cls == mc_tiled; } + +void memcut_add(MemcutTotals& t, const MemcutEntry& e, bool dead) +{ + if (!e.bytes && !e.reserved) ++t.unsized; + t.bytes[e.cls][e.system][dead] += e.bytes; + ++t.count[e.cls][e.system][dead]; + if (!dead && !e.system && memcut_texture(e.cls)) { + const u64 m = e.bytes >> 20; + const int s = m < 1 ? 0 : m < 16 ? 1 : m < 64 ? 2 : 3; + t.tex_size_bytes[s] += e.bytes; + ++t.tex_size_count[s]; + t.format_bytes[static_cast<int>(e.format)] += e.bytes; + if (e.title) { + t.spans.emplace_back(e.title, e.title + e.bytes); + if (e.mapped == 1) t.span_mapped += e.bytes; + } + } +} + +// Buffer placements (note lock) and title-memory kinds (VirtualQuery, slow here) for new entries, +// outside the registry lock. Keys are only looked up, never dereferenced. +void memcut_refine(const std::vector<const void*>& fresh) +{ + auto& cache = memcut_cache(); + for (const void* p : fresh) { + MemcutEntry& e = cache.at(p); + if (!e.placement_known) { + Placement placement = Placement::none; + AcquireSRWLockShared(¬e_lock); + if (const auto found = resource_infos().find(static_cast<const Wrapper*>(p)); found != resource_infos().end()) + placement = found->second.placement; + ReleaseSRWLockShared(¬e_lock); + // A placement retired before this first look reads as none: such a buffer counts as "buf". + e.cls = placement == Placement::aliased_buffer ? mc_buf_aliased : placement == Placement::copied_buffer ? mc_buf_copied : mc_buf; + e.placement_known = true; + } + if (e.mapped < 0 && e.title && memcut_texture(e.cls)) { + u64 base = 0, end = 0; + MEMORY_BASIC_INFORMATION info{}; + if (known_private(e.title, &base, &end)) e.mapped = 0; + else e.mapped = timed_query(reinterpret_cast<const void*>(e.title), &info) == sizeof(info) && info.Type == MEM_MAPPED; + } + } +} + +void memcut_collect(MemcutTotals& t) +{ + std::lock_guard guard(memcut_mutex); + auto& cache = memcut_cache(); + std::vector<std::pair<const void*, LONG>> seen; + std::vector<const void*> fresh; + AcquireSRWLockShared(®istry_lock); + t.wrappers = registry().size(); + for (const void* p : registry()) { + auto* w = const_cast<Wrapper*>(static_cast<const Wrapper*>(p)); + const Kind kind = w->own().kind; + IUnknown* const real = w->own().real; + if (!real || (kind != resource_kind && kind != heap_kind)) continue; + auto found = cache.find(p); + if (found == cache.end() || found->second.real != real) { + const MemcutEntry e = kind == heap_kind ? memcut_heap(static_cast<ID3D12Heap*>(static_cast<void*>(real))) + : memcut_classify(static_cast<ID3D12Resource*>(static_cast<void*>(real)), w->own().title_memory); + found = cache.insert_or_assign(p, e).first; + fresh.push_back(p); + } + seen.emplace_back(p, InterlockedCompareExchange(&w->own().refs, 0, 0)); + } + ReleaseSRWLockShared(®istry_lock); + memcut_refine(fresh); + for (const auto& [p, refs] : seen) memcut_add(t, cache.at(p), refs <= 0); + + struct Tiled { Wrapper* wrapper; ID3D12Resource* desktop; LONG refs; }; + std::vector<Tiled> tiled; + { + std::lock_guard lock(tiled_srv_mutex); // entries are never erased; desktop textures never released + for (auto& [wrapper, texture] : tiled_srv_textures) + if (texture.desktop) tiled.push_back({wrapper, texture.desktop.Get(), InterlockedCompareExchange(&wrapper->own().refs, 0, 0)}); + } + for (const Tiled& x : tiled) { + auto found = cache.find(x.desktop); + if (found == cache.end()) { + MemcutEntry e = memcut_classify(x.desktop, x.wrapper->own().title_memory); + e.cls = mc_tiled; + e.placement_known = true; + found = cache.emplace(x.desktop, e).first; + memcut_refine({x.desktop}); + } + memcut_add(t, found->second, x.refs <= 0); + } +} + +u64 memcut_union(std::vector<std::pair<u64, u64>>& spans) +{ + std::sort(spans.begin(), spans.end()); + u64 total = 0, start = 0, end = 0; + for (const auto& [a, b] : spans) { + if (a > end) { + total += end - start; + start = a; + end = b; + } else if (b > end) { + end = b; + } + } + return total + (end - start); +} + +int memcut_text(char* text, int capacity) +{ + if (!the_device || !text || capacity < 64) return 0; + const ULONGLONG began = GetTickCount64(); + MemcutTotals t; + memcut_collect(t); + const ULONGLONG took = GetTickCount64() - began; + constexpr u64 mib = 1ull << 20; + u64 local = 0, system = 0, dead_bytes = 0, dead_count = 0; + for (int c = 0; c < mc_count; ++c) { + local += t.bytes[c][0][0] + t.bytes[c][0][1]; + system += t.bytes[c][1][0] + t.bytes[c][1][1]; + dead_bytes += t.bytes[c][0][1] + t.bytes[c][1][1]; + dead_count += t.count[c][0][1] + t.count[c][1][1]; + } + PROCESS_MEMORY_COUNTERS_EX process{}; + process.cb = sizeof(process); + GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&process), sizeof(process)); + PERFORMANCE_INFORMATION perf{}; + perf.cb = sizeof(perf); + GetPerformanceInfo(&perf, sizeof(perf)); + const auto& k = x2w_memcut::counters(); + auto live = [&](int c) { return (t.bytes[c][0][0] + t.bytes[c][1][0]) / mib; }; + auto live_n = [&](int c) { return t.count[c][0][0] + t.count[c][1][0]; }; + int n = std::snprintf(text, static_cast<std::size_t>(capacity), + "memcut MiB/count: local %llu system %llu; tex %llu/%llu target %llu/%llu uav %llu/%llu tiled-srv %llu/%llu " + "buf-copied %llu/%llu buf-aliased %llu/%llu buf %llu/%llu heap %llu/%llu; released-held %llu/%llu; ring %llu " + "peak %llu refused %lld; copy peak %llu; used-after-release bound %lld viewed %lld; ws %llu avail-phys %llu", + local / mib, system / mib, live(mc_tex), live_n(mc_tex), live(mc_tex_target), live_n(mc_tex_target), + live(mc_tex_uav), live_n(mc_tex_uav), live(mc_tiled), live_n(mc_tiled), live(mc_buf_copied), live_n(mc_buf_copied), + live(mc_buf_aliased), live_n(mc_buf_aliased), live(mc_buf), live_n(mc_buf), live(mc_heap), live_n(mc_heap), + dead_bytes / mib, dead_count, + static_cast<u64>(k.ring_bytes) / mib, static_cast<u64>(k.ring_frame_peak) / mib, k.ring_refused, + static_cast<u64>(k.copy_frame_peak) / mib, k.bound_after_release, k.viewed_after_release, + static_cast<u64>(process.WorkingSetSize) / mib, static_cast<u64>(perf.PhysicalAvailable) * perf.PageSize / mib); + if (n < 0) return 0; + if (n >= capacity) n = capacity - 1; + if (cold_textures_enabled() && n < capacity - 1) { + AcquireSRWLockShared(&cold_texture_lock); + const int added = std::snprintf(text + n, static_cast<std::size_t>(capacity - n), + "; cold-priority bytes/count %llu/%llu, restored %llu/%llu, failures %llu", + cold_texture_bytes - warmed_texture_bytes, cold_texture_count - warmed_texture_count, + warmed_texture_bytes, warmed_texture_count, cold_texture_failures); + ReleaseSRWLockShared(&cold_texture_lock); + if (added > 0) n += (std::min)(added, capacity - 1 - n); + } + static ULONGLONG last_detail; + if (began - last_detail >= 10000) { + last_detail = began; + u64 span_sum = 0; + for (const auto& [a, b] : t.spans) span_sum += b - a; + const u64 span_union = memcut_union(t.spans); + char line[1400]; + int at = std::snprintf(line, sizeof(line), "x2w-memcut detail (%llu wrappers, %llu ms, %llu unsized): live local textures by size " + "<1M %llu/%llu <16M %llu/%llu <64M %llu/%llu >=64M %llu/%llu MiB/count; their title spans sum %llu union %llu " + "in mapped %llu MiB;", + t.wrappers, took, t.unsized, t.tex_size_bytes[0] / mib, t.tex_size_count[0], t.tex_size_bytes[1] / mib, + t.tex_size_count[1], t.tex_size_bytes[2] / mib, t.tex_size_count[2], t.tex_size_bytes[3] / mib, + t.tex_size_count[3], span_sum / mib, span_union / mib, t.span_mapped / mib); + std::vector<std::pair<u64, int>> formats; + for (const auto& [format, bytes] : t.format_bytes) formats.emplace_back(bytes, format); + std::sort(formats.rbegin(), formats.rend()); + if (at > 0 && at < static_cast<int>(sizeof(line))) at += std::snprintf(line + at, sizeof(line) - at, " top formats"); + for (std::size_t i = 0; i < formats.size() && i < 8 && at > 0 && at < static_cast<int>(sizeof(line)); ++i) + at += std::snprintf(line + at, sizeof(line) - at, " %d:%llu", formats[i].second, formats[i].first / mib); + for (int c = 0; c < mc_count && at > 0 && at < static_cast<int>(sizeof(line)); ++c) + at += std::snprintf(line + at, sizeof(line) - at, "; %s local %llu/%llu system %llu/%llu released local %llu/%llu system %llu/%llu", + memcut_class_names[c], t.bytes[c][0][0] / mib, t.count[c][0][0], t.bytes[c][1][0] / mib, t.count[c][1][0], + t.bytes[c][0][1] / mib, t.count[c][0][1], t.bytes[c][1][1] / mib, t.count[c][1][1]); + log("%s", line); + } + return n; +} +} // namespace + +// xmem_census.h: "name=<MiB> ..." text for the x2w-mem line. +extern "C" __declspec(dllexport) int WINAPI x2w_memory_counters(char* text, int capacity) +{ + try { + return memcut_text(text, capacity); + } catch (...) { + return 0; // out of memory while counting: no text this time + } +} diff --git a/src/startup_stubs/d3d12_memcut_alias.inl b/src/startup_stubs/d3d12_memcut_alias.inl new file mode 100644 index 0000000000..d148bf57f1 --- /dev/null +++ b/src/startup_stubs/d3d12_memcut_alias.inl @@ -0,0 +1,48 @@ +namespace { +bool memcut_alias_slabs() +{ + static const bool on = x2w_local::env_on("X2W_MEMCUT_ALIAS_SLABS"); + return on; +} +LONG memcut_alias_done, memcut_alias_refused; +LONG64 memcut_alias_bytes, memcut_alias_refused_bytes; + +ID3D12Heap* memcut_slab_heap(void* address, UINT64 bytes, UINT64* offset) +{ + if (!memcut_alias_slabs() || !bytes) return nullptr; + using PoolRun = BOOL(WINAPI*)(const void*, SIZE_T, HANDLE*, ULONG64*); + static const PoolRun run = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + const auto f = xmem ? reinterpret_cast<PoolRun>(GetProcAddress(xmem, "x2w_xmem_pool_run")) : nullptr; + log("x2w-memcut alias slabs: X2W_MEMCUT_ALIAS_SLABS=1, xmem x2w_xmem_pool_run %s", f ? "found" : "MISSING (off)"); + return f; + }(); + HANDLE section = nullptr; + ULONG64 at = 0; + ID3D12Heap* heap = nullptr; + if (run && run(address, static_cast<SIZE_T>(bytes), §ion, &at)) heap = section_heap(section); + if (heap && at + bytes > heap->GetDesc().SizeInBytes) heap = nullptr; + const LONG n = heap ? InterlockedIncrement(&memcut_alias_done) : InterlockedIncrement(&memcut_alias_refused); + InterlockedAdd64(heap ? &memcut_alias_bytes : &memcut_alias_refused_bytes, static_cast<LONG64>(bytes)); + if (x2w_local::first_of(n, 8) || n % 256 == 0) + log("x2w-memcut alias slabs: buffer %p width 0x%llx %s (aliased %ld = %lld MiB, refused %ld = %lld MiB)", address, bytes, + heap ? "placed on its pool section" : "not one pool section run: copied as before", memcut_alias_done, memcut_alias_bytes >> 20, + memcut_alias_refused, memcut_alias_refused_bytes >> 20); + if (heap) *offset = at; + return heap; +} + +// Slot 133: CreatePlacedResource on the slab heap failed (the buffer falls back to a copy). Moves it from the aliased +// count to the refused one, so the counters say what was placed. +void memcut_slab_failed(void* address, UINT64 bytes, HRESULT hr) +{ + InterlockedDecrement(&memcut_alias_done); + InterlockedAdd64(&memcut_alias_bytes, -static_cast<LONG64>(bytes)); + const LONG n = InterlockedIncrement(&memcut_alias_refused); + InterlockedAdd64(&memcut_alias_refused_bytes, static_cast<LONG64>(bytes)); + static LONG shown; + if (x2w_local::first_of(InterlockedIncrement(&shown), 8) || n % 256 == 0) + log("x2w-memcut alias slabs: buffer %p width 0x%llx: placing on the pool section failed 0x%08lx, copied as before", address, bytes, + static_cast<unsigned long>(hr)); +} +} // namespace diff --git a/src/startup_stubs/d3d12_memcut_release.inl b/src/startup_stubs/d3d12_memcut_release.inl new file mode 100644 index 0000000000..60100236f0 --- /dev/null +++ b/src/startup_stubs/d3d12_memcut_release.inl @@ -0,0 +1,361 @@ +#include <unordered_set> + +namespace { +struct MemcutHollow { + D3D12_RESOURCE_DESC desc; + D3D12_HEAP_PROPERTIES props; + D3D12_HEAP_FLAGS flags; + DXGI_FORMAT packed; // packed_stand_in_tag of the original, or UNKNOWN + u64 bytes; +}; +struct MemcutRetiring { + ID3D12Resource* object; + u64 epoch; + u64 bytes; + bool snapped; + std::vector<std::pair<ID3D12Fence*, UINT64>> waits; +}; +struct MemcutRelease { + SRWLOCK lock = SRWLOCK_INIT; + std::unordered_map<Wrapper*, LONG> pending; // wrapper -> frame of its release or last bind + std::unordered_map<Wrapper*, MemcutHollow> hollow; // wrappers whose real is a placeholder now + std::unordered_map<Wrapper*, u64> list_epochs; // list -> epoch at its last Reset + std::unordered_set<Wrapper*> refused; // no placeholder could be made, or revived once: never again + std::vector<MemcutRetiring> retiring; + std::vector<std::pair<ID3D12Fence*, UINT64>> test_waits; // fixtures: extra fences, as note_submits would add + volatile LONG64 epoch = 0; + volatile LONG active = 0; // anything pending or hollow: the bind hook's fast path + LONG last_hollow_frame = -1, last_report_frame = 0, lowest_frame = -1; + u64 lowest = 0; // lowest list Reset epoch, computed at lowest_frame + u64 hollowed = 0, freed = 0, freed_bytes = 0, revived = 0, refused_count = 0, blocked = 0; + u64 reported_freed = 0, window_us = 0, window_max_us = 0; // report bookkeeping, reaper cost since the last line +}; +MemcutRelease& memcut_release_state() +{ + static MemcutRelease s; + return s; +} +bool memcut_release_on() +{ + static const bool on = x2w_local::env_on("X2W_MEMCUT_RELEASE"); + return on; +} +LONG memcut_release_frames() +{ + static const LONG frames = [] { + char v[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_MEMCUT_RELEASE_FRAMES", v, sizeof(v)); + const long f = n && n < sizeof(v) ? std::atol(v) : 8; + return static_cast<LONG>(f >= 1 ? f : 1); + }(); + return frames; +} +bool memcut_release_immediate() +{ + static const bool on = x2w_local::env_on("X2W_MEMCUT_RELEASE_TEST_IMMEDIATE"); + return on; +} +// Reads of unmapped tiles of a reserved resource return 0 from tier 2 on; below that the placeholder +// would not be safe, so the cut stays off. +bool memcut_tiles_safe() +{ + static const bool ok = [] { + D3D12_FEATURE_DATA_D3D12_OPTIONS o{}; + const bool got = the_device && SUCCEEDED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &o, sizeof(o))); + log("x2w-memcut release: X2W_MEMCUT_RELEASE=1, tiled resources tier %d%s, grace %ld frames%s", got ? static_cast<int>(o.TiledResourcesTier) : -1, + got && o.TiledResourcesTier >= D3D12_TILED_RESOURCES_TIER_2 ? "" : " (below 2: OFF)", memcut_release_frames(), + memcut_release_immediate() ? ", TEST IMMEDIATE (no fence wait)" : ""); + return got && o.TiledResourcesTier >= D3D12_TILED_RESOURCES_TIER_2; + }(); + return ok; +} +DXGI_FORMAT memcut_packed_of(ID3D12Resource* r) { return x2w_startup::packed_stand_in_of(r); } +void memcut_copy_packed(ID3D12Resource* to, DXGI_FORMAT packed) +{ + if (to && packed != DXGI_FORMAT_UNKNOWN) to->SetPrivateData(x2w_startup::packed_stand_in_tag, sizeof(packed), &packed); +} + +// Writes the persistent view-id descriptors (translated compute) of every record that names one of these +// wrappers again, from its current desktop object: one pass over the records. draw_lock held. +void memcut_refill_views(const std::vector<Wrapper*>& wrappers) +{ + if (!draw_heap || wrappers.empty()) return; + std::unordered_set<u64> names; + for (Wrapper* w : wrappers) names.insert(reinterpret_cast<u64>(w)); + std::vector<std::pair<UINT, ViewRecord>> found; + AcquireSRWLockShared(¬e_lock); + const UINT filled = views_filled < view_records().size() ? views_filled : static_cast<UINT>(view_records().size()); + for (UINT i = 0; i < filled; ++i) + if (view_records()[i].resource && names.count(view_records()[i].resource)) found.emplace_back(i, view_records()[i]); + ReleaseSRWLockShared(¬e_lock); + for (const auto& [i, record] : found) fill_view_kinds(nullptr, draw_heap_size + 8 + 8 * i, &record); +} + +void memcut_swap_real(Wrapper* w, ID3D12Resource* to) +{ + AcquireSRWLockExclusive(®istry_lock); + w->own().real = to; + ReleaseSRWLockExclusive(®istry_lock); +} + +// Release hook: refs just reached 0. +void memcut_released(Wrapper* self) +{ + if (!memcut_release_on() || self->own().kind != resource_kind || !self->own().title_memory || self->own().tiled_address_srv || + self->own().linear_memory_srv) + return; + auto* real = static_cast<ID3D12Resource*>(self->own().real); + if (!real) return; + const D3D12_RESOURCE_DESC desc = real->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1 || + (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | + D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS))) + return; + D3D12_HEAP_PROPERTIES props{}; + D3D12_HEAP_FLAGS flags{}; + if (FAILED(real->GetHeapProperties(&props, &flags)) || props.Type != D3D12_HEAP_TYPE_DEFAULT) return; + MemcutRelease& s = memcut_release_state(); + AcquireSRWLockExclusive(&s.lock); + if (!s.refused.count(self) && !s.hollow.count(self)) { + s.pending[self] = frame_number; + InterlockedExchange(&s.active, 1); + } + ReleaseSRWLockExclusive(&s.lock); +} + +// List Reset hook (after a successful Reset). +void memcut_list_reset(Wrapper* list) +{ + if (!memcut_release_on()) return; + MemcutRelease& s = memcut_release_state(); + AcquireSRWLockExclusive(&s.lock); + s.list_epochs[list] = static_cast<u64>(InterlockedCompareExchange64(&s.epoch, 0, 0)); + ReleaseSRWLockExclusive(&s.lock); +} + +// Bind hook (draw_lock held): a hollow texture is made again; a pending one counts as used now. +void memcut_revive(Wrapper* w) +{ + if (!w || !memcut_release_on()) return; + MemcutRelease& s = memcut_release_state(); + if (!InterlockedCompareExchange(&s.active, 0, 0)) return; + AcquireSRWLockExclusive(&s.lock); + if (auto p = s.pending.find(w); p != s.pending.end()) { + p->second = frame_number; + ReleaseSRWLockExclusive(&s.lock); + return; + } + const auto h = s.hollow.find(w); + if (h == s.hollow.end()) { + ReleaseSRWLockExclusive(&s.lock); + return; + } + const MemcutHollow hollow = h->second; + ID3D12Resource* created = nullptr; + const HRESULT hr = device_of(the_device)->CreateCommittedResource(&hollow.props, hollow.flags, &hollow.desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&created)); + if (FAILED(hr)) { + ReleaseSRWLockExclusive(&s.lock); + static LONG failures; + if (first_calls(failures, 6)) log("x2w-memcut release: revive of %p failed 0x%08lx (it stays a placeholder: reads zero)", static_cast<void*>(w), hr); + return; + } + memcut_copy_packed(created, hollow.packed); + auto* placeholder = static_cast<ID3D12Resource*>(w->own().real); + memcut_swap_real(w, created); + texture_uploads().erase(placeholder); + s.hollow.erase(h); + const u64 e = static_cast<u64>(InterlockedIncrement64(&s.epoch)); + s.lowest_frame = -1; // as in memcut_reap: the next list check comes after this swap + s.retiring.push_back({placeholder, e, 0, false, {}}); + // A texture bound after it was freed is one the title still draws: never hollow it again (no hollow/revive + // cycle, each of which would be a re-upload under draw_lock). + s.refused.insert(w); + ++s.revived; + ReleaseSRWLockExclusive(&s.lock); + memcut_refill_views({w}); + static LONG shown; + if (first_calls(shown, 8)) + log("x2w-memcut release: revived %p (%llux%u fmt %d, %llu KiB): bound after it was freed; uploaded again from title memory", + static_cast<void*>(w), hollow.desc.Width, hollow.desc.Height, hollow.desc.Format, hollow.bytes >> 10); +} + +// s.lock held. The lowest Reset epoch over the live command lists (0 for a list never Reset). +u64 memcut_min_list_epoch(MemcutRelease& s, u64* live) +{ + u64 lowest = ~0ull; + *live = 0; + AcquireSRWLockShared(®istry_lock); + for (const void* p : registry()) { + auto* w = const_cast<Wrapper*>(static_cast<const Wrapper*>(p)); + if (w->own().kind != list_kind || InterlockedCompareExchange(&w->own().refs, 0, 0) <= 0) continue; + ++*live; + const auto found = s.list_epochs.find(w); + const u64 e = found == s.list_epochs.end() ? 0 : found->second; + if (e < lowest) lowest = e; + } + ReleaseSRWLockShared(®istry_lock); + return lowest; +} + +// At a submit (draw_lock held), after note_submits. +void memcut_reap() +{ + if (!memcut_release_on()) return; + MemcutRelease& s = memcut_release_state(); + if (!InterlockedCompareExchange(&s.active, 0, 0) && s.retiring.empty()) return; + if (!memcut_tiles_safe()) return; + LARGE_INTEGER started{}; + QueryPerformanceCounter(&started); + AcquireSRWLockExclusive(&s.lock); + const LONG frame = frame_number; + // 2. Hollow, once per frame. + if (frame != s.last_hollow_frame && !s.pending.empty()) { + s.last_hollow_frame = frame; + std::vector<Wrapper*> due; + for (auto it = s.pending.begin(); it != s.pending.end();) { + if (InterlockedCompareExchange(&it->first->own().refs, 0, 0) > 0) { it = s.pending.erase(it); continue; } + if (frame - it->second >= memcut_release_frames() && due.size() < 256) due.push_back(it->first); + ++it; + } + const u64 e = due.empty() ? 0 : static_cast<u64>(InterlockedIncrement64(&s.epoch)); + if (!due.empty()) s.lowest_frame = -1; // the list check for epoch e must look at the lists after this hollow + for (Wrapper* w : due) { + s.pending.erase(w); + auto* old = static_cast<ID3D12Resource*>(w->own().real); + // As device slot 133 / 127 create them: a default heap, no heap flags (the implicit heap's own flags, + // e.g. DENY_BUFFERS, are refused by CreateCommittedResource). + MemcutHollow h{old->GetDesc(), D3D12_HEAP_PROPERTIES{D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, memcut_packed_of(old), 0}; + const D3D12_RESOURCE_ALLOCATION_INFO info = device_of(the_device)->GetResourceAllocationInfo(0, 1, &h.desc); + h.bytes = info.SizeInBytes == ~0ull ? 0 : info.SizeInBytes; + D3D12_RESOURCE_DESC reserved = h.desc; + reserved.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; + reserved.Alignment = 0; + ID3D12Resource* placeholder = nullptr; + if (FAILED(device_of(the_device)->CreateReservedResource(&reserved, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&placeholder)))) { + s.refused.insert(w); + ++s.refused_count; + static LONG failures; + if (first_calls(failures, 6)) + log("x2w-memcut release: no placeholder for %p (%llux%u mips %u fmt %d): kept", static_cast<void*>(w), h.desc.Width, h.desc.Height, + h.desc.MipLevels, h.desc.Format); + continue; + } + memcut_copy_packed(placeholder, h.packed); + memcut_swap_real(w, placeholder); + texture_uploads().erase(old); + s.hollow[w] = h; + ++s.hollowed; + if (memcut_release_immediate()) { // fixtures only: the negative control + old->Release(); + ++s.freed; + s.freed_bytes += h.bytes; + } else { + s.retiring.push_back({old, e, h.bytes, false, {}}); + } + } + ReleaseSRWLockExclusive(&s.lock); + memcut_refill_views(due); // a refused one rewrites its own views: harmless + AcquireSRWLockExclusive(&s.lock); + } + // 3. Free what no list and no queue can still reach. + if (!s.retiring.empty()) { + bool unsnapped = false; + for (const MemcutRetiring& r : s.retiring) unsnapped |= !r.snapped; + if (unsnapped && frame != s.lowest_frame) { + u64 live = 0; + s.lowest = memcut_min_list_epoch(s, &live); + s.lowest_frame = frame; + } + const u64 lowest = s.lowest; + std::vector<std::pair<ID3D12Fence*, UINT64>> now; + bool now_taken = false; + u64 blocked = 0; + for (auto it = s.retiring.begin(); it != s.retiring.end();) { + MemcutRetiring& r = *it; + if (!r.snapped) { + if (lowest < r.epoch) { ++blocked; ++it; continue; } + if (!now_taken) { + AcquireSRWLockShared(&allocator_lock); + for (const auto& [queue, submit] : queue_submits) + if (submit.first) now.push_back(submit); + ReleaseSRWLockShared(&allocator_lock); + now.insert(now.end(), s.test_waits.begin(), s.test_waits.end()); + now_taken = true; + } + r.waits = now; + r.snapped = true; + } + bool passed = true; + for (const auto& [fence, value] : r.waits) + if (fence->GetCompletedValue() < value) passed = false; + if (!passed) { ++it; continue; } + r.object->Release(); + ++s.freed; + s.freed_bytes += r.bytes; + it = s.retiring.erase(it); + } + s.blocked = blocked; + } + if (s.pending.empty() && s.hollow.empty()) InterlockedExchange(&s.active, 0); + else InterlockedExchange(&s.active, 1); + // Cost under draw_lock (this call, including the lock wait): max and total since the last report. + LARGE_INTEGER ended{}, hz{}; + QueryPerformanceCounter(&ended); + QueryPerformanceFrequency(&hz); + const u64 us = static_cast<u64>((ended.QuadPart - started.QuadPart) * 1000000 / (hz.QuadPart ? hz.QuadPart : 1)); + s.window_us += us; + if (us > s.window_max_us) s.window_max_us = us; + // Every 300 frames, and at each of the first 4 frees (once per new free, not at every submit). + const bool early = s.freed && s.freed <= 4 && s.freed != s.reported_freed; + const bool report = frame - s.last_report_frame >= 300 || early; + const u64 window_us = s.window_us, window_max_us = s.window_max_us; + if (report) s.last_report_frame = frame, s.reported_freed = s.freed, s.window_us = 0, s.window_max_us = 0; + const u64 pending = s.pending.size(), hollow = s.hollow.size(), retiring = s.retiring.size(); + const u64 hollowed = s.hollowed, freed = s.freed, freed_mib = s.freed_bytes >> 20, revived = s.revived, refused = s.refused_count, blocked = s.blocked; + ReleaseSRWLockExclusive(&s.lock); + static LONG reports; + if (report && first_calls(reports, 400)) + log("x2w-memcut release (frame %ld): pending %llu, hollow %llu, retiring %llu (%llu waiting for a list Reset), hollowed %llu, freed %llu = %llu MiB, " + "revived %llu, refused %llu; reaper under draw_lock since the last line: total %llu.%03llu ms, max %llu.%03llu ms", + frame, pending, hollow, retiring, blocked, hollowed, freed, freed_mib, revived, refused, window_us / 1000, window_us % 1000, + window_max_us / 1000, window_max_us % 1000); +} +} // namespace + +// Fixtures (memcut_release_check): op 0 the wrapper's desktop object; 1 add fence (a, value b) to the waits a +// snapshot takes; 2 advance frame_number by b and run the reaper as a submit would; 3 bind wrapper a (revive); +// 4 state of wrapper a: 0 none, 1 pending, 2 hollow, 3 refused; 5 freed count; 6 Reset epoch hook for list a. +extern "C" __declspec(dllexport) u64 WINAPI x2w_memcut_release_test(int op, void* a, u64 b) +{ + MemcutRelease& s = memcut_release_state(); + Wrapper* w = as_wrapper(a); + switch (op) { + case 0: return w ? reinterpret_cast<u64>(w->own().real) : 0; + case 1: + AcquireSRWLockExclusive(&s.lock); + s.test_waits.emplace_back(static_cast<ID3D12Fence*>(a), b); + ReleaseSRWLockExclusive(&s.lock); + return 1; + case 2: + lock_draw(900000 + __LINE__); + frame_number += static_cast<LONG>(b); + memcut_reap(); + ReleaseSRWLockExclusive(&draw_lock); + return 1; + case 3: + lock_draw(900000 + __LINE__); + memcut_revive(w); + ReleaseSRWLockExclusive(&draw_lock); + return w ? reinterpret_cast<u64>(w->own().real) : 0; + case 4: { + AcquireSRWLockShared(&s.lock); + const u64 state = s.pending.count(w) ? 1 : s.hollow.count(w) ? 2 : s.refused.count(w) ? 3 : 0; + ReleaseSRWLockShared(&s.lock); + return state; + } + case 5: return s.freed; + case 6: memcut_list_reset(w); return 1; + default: return 0; + } +} diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 673084c388..7df975967f 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -13,8 +13,32 @@ bool same_texture_description(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE a.SampleDesc.Quality == b.SampleDesc.Quality && a.Layout == b.Layout && a.Flags == b.Flags; } +bool tiled_any_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_MEMORY_SRV_TILED_ANY"); + if (v) log("x2w-memsrv X2W_MEMORY_SRV_TILED_ANY=1: single-mip tiled memory SRVs of any 16-byte BC format and size"); + return v; + }(); + return on; +} +bool bc16_format(DXGI_FORMAT f) +{ + switch (f) { + case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: + return true; + default: + return false; + } +} bool tiled_bc_srv(const D3D12_RESOURCE_DESC& r) { + if (tiled_any_on() && bc16_format(r.Format) && static_cast<UINT>(r.Layout) == 0x105 && r.Alignment == 0 && + (r.Flags == D3D12_RESOURCE_FLAG_NONE || static_cast<UINT>(r.Flags) == 0x300000) && r.Width && r.Height && + r.Width <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && r.Height <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) + return true; return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && r.DepthOrArraySize == 1 && r.MipLevels == 1 && r.SampleDesc.Count == 1 && r.SampleDesc.Quality == 0 && (r.Format == DXGI_FORMAT_BC3_UNORM || r.Format == DXGI_FORMAT_BC7_UNORM) && @@ -60,6 +84,14 @@ u64 xg_reported_bytes(Wrapper* device, const D3D12_RESOURCE_DESC& desc) } bool supports_placed_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v); +// LOCAL merge: upstream's by-address texture forms (a texture in a console layout of gfx10_layout.h, the +// single-element texture) are new default-on memory SRV paths upstream; here they run only with +// X2W_UPSTREAM_CONSOLE_SRV=1, so slot 70 refuses those calls as before unless asked (docs/experiments.md). +bool upstream_console_srv_on() +{ + static const bool on = x2w_local::env_on("X2W_UPSTREAM_CONSOLE_SRV"); + return on; +} // The shapes slot 70 took before address_texture.h, or a texture in a console layout gfx10_layout.h // addresses with a view that stays inside it. bool supports_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) @@ -128,8 +160,9 @@ bool memory_srv_destination(u64 handle) for (const auto& heap : heap_infos()) { if (heap.type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || !heap.increment) continue; const u64 base = heap.title_cpu ? heap.title_cpu : heap.desktop_cpu; - if (handle >= base && (handle - base) % heap.increment == 0 && - (handle - base) / heap.increment < heap.count) { + const UINT step = heap.title_cpu && x2w_gpu::gpu_abi_on() ? x2w_gpu::abi::view_increment : heap.increment; + const UINT count = heap.title_cpu ? heap.logical_count : heap.count; + if (handle >= base && (handle - base) % step == 0 && (handle - base) / step < count) { valid = true; break; } @@ -159,7 +192,7 @@ void check_resource_address_index() ExitProcess(3); } -Wrapper* existing_memory_texture(u64 address, const D3D12_RESOURCE_DESC& desc) +Wrapper* existing_memory_texture(u64 address, const D3D12_RESOURCE_DESC& desc, bool native_only = false) { X2W_ZONE("srv existing_memory_texture scan"); Wrapper* match = nullptr; @@ -168,7 +201,8 @@ Wrapper* existing_memory_texture(u64 address, const D3D12_RESOURCE_DESC& desc) resource_address_index().for_each_reaching(address, 1, [&](const Wrapper* wrapper) { const auto& info = resource_infos().at(wrapper); if (reinterpret_cast<u64>(wrapper->own().title_memory) != address || - wrapper->own().tiled_address_srv || + wrapper->own().tiled_address_srv || wrapper->own().partial_mip_srv || + (native_only && (wrapper->own().linear_memory_srv || !wrapper->own().real)) || InterlockedCompareExchange(&wrapper->own().refs, 0, 0) <= 0 || !same_texture_description(desc, info.console)) return false; if (match) { @@ -182,6 +216,57 @@ Wrapper* existing_memory_texture(u64 address, const D3D12_RESOURCE_DESC& desc) return match; } +Wrapper* native_tiled_bc_texture(u64 address, const D3D12_RESOURCE_DESC& desc, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv) +{ + if (!tiled_bc_srv(desc) && !x2w_startup::bc64::supports(desc)) return nullptr; + auto* candidate = existing_memory_texture(address, desc, true); + if (!candidate) return nullptr; + const auto host = static_cast<ID3D12Resource*>(candidate->own().real)->GetDesc(); + if ((host.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || !x2w_startup::address_view_fits(host, srv)) return nullptr; + return candidate; +} + +bool packed_light_enabled() +{ + static const bool on = x2w_gpu::gpu_abi_on() && x2w_local::env_on("X2W_GPU_ALIAS_COPY"); + return on; +} + +// Resolve bitwise aliases between single-plane color formats. +// Resolve the current writer at each read; never choose between overlapping writers. +Microsoft::WRL::ComPtr<ID3D12Resource> packed_light_source(u64 address, const D3D12_RESOURCE_DESC& reader) +{ + Microsoft::WRL::ComPtr<ID3D12Resource> result; + if (!packed_light_enabled() || !address || !x2w_packed_light::color_bytes(reader.Format) || + (reader.Flags & (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))) return result; + AcquireSRWLockShared(¬e_lock); + const auto live_target = [](const Wrapper* w, const ResourceInfo& info) { + return w->own().real && InterlockedCompareExchange(&w->own().refs, 0, 0) > 0 && + info.console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && (info.console.Flags & 7); + }; + const Wrapper* owner = nullptr; + u64 span = 1; + resource_address_index().for_each_at(address, [&](const Wrapper* w) { + const auto& info = resource_infos().at(w); + if (!live_target(w, info) || !x2w_packed_light::compatible(info.console, reader)) return false; + auto* host = static_cast<ID3D12Resource*>(w->own().real); + const auto actual = host->GetDesc(); + if (actual.Format != info.console.Format || !x2w_packed_light::compatible(actual, reader)) return false; + result = host; + owner = w; + span = info.bytes ? info.bytes : x2w_packed_light::minimum_span(actual); + return true; + }); + if (owner) resource_address_index().for_each_reaching(address, span, [&](const Wrapper* w) { + if (w == owner || !live_target(w, resource_infos().at(w))) return false; + result.Reset(); + return true; + }); + ReleaseSRWLockShared(¬e_lock); + return result; +} + // An unmatched or interior view must not reinterpret bytes owned by a live resource. bool address_resource_overlap(u64 address, u64 span) { @@ -233,10 +318,51 @@ Wrapper* existing_memory_buffer(Wrapper* device, u64 address, u64 bytes) return nullptr; return const_cast<Wrapper*>(placed.owner); } + // LOCAL (textures): X2W_BUFFER_ADDRESS_INDEX=1 answers from buffer_address_index (d3d12_capture.inl) instead of the + // walk below; =check runs both and counts disagreements (logged at powers of two, first 8 with both answers). + static const int index_mode = [] { + char v[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_BUFFER_ADDRESS_INDEX", v, sizeof(v)); + const int mode = n && n < sizeof(v) ? (std::strcmp(v, "1") == 0 ? 1 : std::strcmp(v, "check") == 0 ? 2 : 0) : 0; + if (mode) log("x2w-memsrv X2W_BUFFER_ADDRESS_INDEX=%s: memory buffer lookups use the address index%s", v, + mode == 2 ? ", checked against the walk on every call" : ""); + return mode; + }(); + // The walk's filters, applied to each candidate either way. + const auto eligible = [](const Wrapper* wrapper, const ResourceInfo& info) { + return !(!wrapper->own().real && info.console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) && + info.placement == Placement::none && info.console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && + !(info.console.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && + InterlockedCompareExchange(&const_cast<Wrapper*>(wrapper)->own().refs, 0, 0) > 0; + }; + Wrapper* indexed = nullptr; + if (index_mode) { + AcquireSRWLockShared(¬e_lock); + bool ambiguous = false; + buffer_address_index().containing(address, bytes, [&](const Wrapper* wrapper, u64 base, u64) { + const auto found = resource_infos().find(wrapper); + if (found == resource_infos().end() || !eligible(wrapper, found->second)) return true; + // As the walk: the record's current base and width decide (the index holds them as noted). + const u64 now = reinterpret_cast<u64>(wrapper->own().title_memory), width = found->second.console.Width; + if (now != base || address < now || address - now >= width || bytes > width - (address - now)) return true; + if (indexed) { + ambiguous = true; + return false; + } + indexed = const_cast<Wrapper*>(wrapper); + return true; + }); + ReleaseSRWLockShared(¬e_lock); + if (ambiguous) indexed = nullptr; + if (index_mode == 1) return indexed; + } Wrapper* match = nullptr; AcquireSRWLockShared(¬e_lock); resource_address_index().for_each_reaching(address, 1, [&](const Wrapper* wrapper) { const auto& info = resource_infos().at(wrapper); + // LOCAL: stand-in buffers (standin_memory_buffer, X2W_MEMORY_SRV_BUFFER: no desktop resource) are found through + // their own map, by address; here they would make real buffers they overlap ambiguous. + if (!wrapper->own().real && info.console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return false; if (info.placement != Placement::none || info.console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (info.console.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || @@ -254,6 +380,17 @@ Wrapper* existing_memory_buffer(Wrapper* device, u64 address, u64 bytes) return false; }); ReleaseSRWLockShared(¬e_lock); + if (index_mode == 2) { + static LONG64 checked, differed; + const LONG64 n = InterlockedIncrement64(&checked); + const bool same = indexed == match; + const LONG64 d = same ? differed : InterlockedIncrement64(&differed); + static LONG shown; + if (!same && first_calls(shown, 8)) + log("x2w-memsrv buffer address index DIFFERS at 0x%llx (%llu bytes): index %p, walk %p", address, bytes, static_cast<void*>(indexed), + static_cast<void*>(match)); + if ((n & (n - 1)) == 0) log("x2w-memsrv buffer address index checked %lld lookups against the walk: %lld differ", n, d); + } return match; } @@ -350,7 +487,7 @@ Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, co break; } } - if (!heap) { + if (!heap && x2w_startup::private_heap_importable(memory.base)) { ID3D12Device3* device3 = nullptr; if (SUCCEEDED(desktop->QueryInterface(IID_PPV_ARGS(&device3)))) { if (SUCCEEDED(device3->OpenExistingHeapFromAddress(memory.base, IID_PPV_ARGS(&heap)))) { @@ -467,7 +604,7 @@ bool latest_texture_write_is_rows(u64 address) // (the single texel, the 0x105 BC3/BC7 surface and the 0x109 BC chains keep their own paths). bool console_layout_srv(const D3D12_RESOURCE_DESC& desc) { - return x2w_startup::console_address_texture(desc) && !x2w_startup::single_element_bytes(desc) && + return upstream_console_srv_on() && x2w_startup::console_address_texture(desc) && !x2w_startup::single_element_bytes(desc) && !tiled_bc_srv(desc) && !x2w_startup::bc64::supports(desc); } @@ -525,7 +662,7 @@ Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURC { const auto bytes = address_texture_bytes(device, desc); // The transient upload ring accepts individual copies up to 64 MiB. - if (bytes > (64ull << 20) || !x2w_local::readable(reinterpret_cast<const void*>(address), bytes)) return nullptr; + if (bytes > (64ull << 20) || !x2w_local::descriptor_memory_readable(address, bytes)) return nullptr; std::lock_guard lock(tiled_srv_mutex); const auto [first, last] = tiled_srv_addresses.equal_range(address); for (auto it = first; it != last; ++it) { @@ -549,6 +686,8 @@ Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURC ID3D12Resource* sampled_address_texture(Wrapper* resource) { if (!resource || resource->own().kind != resource_kind) return nullptr; + warm_texture(resource); + memcut_revive(resource); // LOCAL memcut: X2W_MEMCUT_RELEASE (a freed texture is made again; no-op otherwise) if (!resource->own().tiled_address_srv) return static_cast<ID3D12Resource*>(resource->own().real); std::lock_guard lock(tiled_srv_mutex); auto& sampled = tiled_srv_textures.at(resource); @@ -572,6 +711,534 @@ ID3D12Resource* sampled_address_texture(Wrapper* resource) return sampled.desktop.Get(); } +bool memory_srv_linear_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_MEMORY_SRV_LINEAR"); + if (v) log("x2w-memsrv X2W_MEMORY_SRV_LINEAR=1: plain 2D memory SRVs get a desktop texture uploaded from the view address"); + return v; + }(); + return on; +} +// view_slot does not check mip, array or plane ranges, and desktop removes the device on a view it +// rejects, so the range is checked here (MipLevels ~0u means "all from the most detailed mip"). +bool linear_view_in_range(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) +{ + const UINT mips = r.MipLevels, slices = r.DepthOrArraySize; + const auto mip_range = [&](UINT most, UINT count, float clamp) { + return most < mips && (count == ~0u || (count > 0 && count <= mips - most)) && clamp >= 0.0f && clamp <= static_cast<float>(mips); + }; + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D) + return mip_range(v.Texture2D.MostDetailedMip, v.Texture2D.MipLevels, v.Texture2D.ResourceMinLODClamp) && v.Texture2D.PlaneSlice == 0; + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY) { + const auto& a = v.Texture2DArray; + return mip_range(a.MostDetailedMip, a.MipLevels, a.ResourceMinLODClamp) && a.PlaneSlice == 0 && a.FirstArraySlice < slices && + a.ArraySize > 0 && a.ArraySize <= slices - a.FirstArraySlice; + } + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBE) + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && r.Width == r.Height && slices == 6 && + mip_range(v.TextureCube.MostDetailedMip, v.TextureCube.MipLevels, v.TextureCube.ResourceMinLODClamp); + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBEARRAY) { + const auto& c = v.TextureCubeArray; + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && r.Width == r.Height && slices % 6 == 0 && c.NumCubes > 0 && + c.First2DArrayFace < slices && u64{c.NumCubes} * 6 <= u64{slices} - c.First2DArrayFace && + mip_range(c.MostDetailedMip, c.MipLevels, c.ResourceMinLODClamp); + } + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE1D) + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && + mip_range(v.Texture1D.MostDetailedMip, v.Texture1D.MipLevels, v.Texture1D.ResourceMinLODClamp); + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE1DARRAY) { + const auto& a = v.Texture1DArray; + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && mip_range(a.MostDetailedMip, a.MipLevels, a.ResourceMinLODClamp) && + a.FirstArraySlice < slices && a.ArraySize > 0 && a.ArraySize <= slices - a.FirstArraySlice; + } + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE3D) + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && + mip_range(v.Texture3D.MostDetailedMip, v.Texture3D.MipLevels, v.Texture3D.ResourceMinLODClamp); + return false; +} +// Which description forms the linear and stand-in paths wrote, one counter each. +enum LinearForm { lf_2d, lf_2d_array, lf_cube, lf_cube_array, lf_1d, lf_1d_array, lf_3d, lf_buffer_srv, lf_buffer_uav, lf_count }; +const char* const linear_form_names[lf_count] = {"2d", "2d-array", "cube", "cube-array", "1d", "1d-array", "3d", "buffer-srv", "buffer-uav"}; +LONG64 linear_forms[lf_count]; +int linear_form(D3D12_SRV_DIMENSION d) +{ + switch (d) { + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: return lf_2d_array; + case D3D12_SRV_DIMENSION_TEXTURECUBE: return lf_cube; + case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: return lf_cube_array; + case D3D12_SRV_DIMENSION_TEXTURE1D: return lf_1d; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: return lf_1d_array; + case D3D12_SRV_DIMENSION_TEXTURE3D: return lf_3d; + default: return lf_2d; + } +} +void note_linear_form(int form, u64 destination) +{ + const LONG64 n = InterlockedIncrement64(&linear_forms[form]); + if ((n & (n - 1)) == 0) + log("x2w-memsrv form %s: %lld views written (latest destination 0x%llx)", linear_form_names[form], n, destination); +} +bool linear_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) +{ + const bool sized = r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + ? r.Width <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && r.Height <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION + : r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D + ? r.Width <= D3D12_REQ_TEXTURE1D_U_DIMENSION && r.Height == 1 && r.DepthOrArraySize <= D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION + : r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && + r.Width <= D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION && r.Height <= D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION && + r.DepthOrArraySize <= D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION; + return sized && r.Width && r.Height && + r.DepthOrArraySize >= 1 && r.MipLevels >= 1 && r.MipLevels <= 15 && r.SampleDesc.Count == 1 && + static_cast<UINT>(r.Layout) == 0 && !tiled_bc_srv(r) && !x2w_startup::bc64::supports(r) && + !(r.Flags & (D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE | D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) && + v.Format == r.Format && linear_view_in_range(r, v); +} +bool memory_srv_announced_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_MEMORY_SRV_ANNOUNCED"); + if (v) log("x2w-memsrv X2W_MEMORY_SRV_ANNOUNCED=1: console-swizzled memory SRVs at XG-announced addresses take the linear path"); + return v; + }(); + return on; +} +bool xg_announced(u64 address) +{ + AcquireSRWLockShared(&written_lock); + const auto found = written_textures().find(address); + const bool announced = found != written_textures().end() && !found->second.bc7_width; + ReleaseSRWLockShared(&written_lock); + return announced; +} +bool console_swizzle(const D3D12_RESOURCE_DESC& r) +{ + const UINT layout = static_cast<UINT>(r.Layout); + return layout >= 0x100 && layout <= 0x1ff; +} +bool announced_linear_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v, u64 address) +{ + if (!console_swizzle(r) || tiled_bc_srv(r) || x2w_startup::bc64::supports(r) || !xg_announced(address)) return false; + D3D12_RESOURCE_DESC as_linear = r; + as_linear.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + return linear_memory_srv(as_linear, v); +} +std::mutex linear_srv_mutex; +std::unordered_multimap<u64, std::pair<D3D12_RESOURCE_DESC, Wrapper*>> linear_srv_textures; +thread_local u64 thread_linear_allocations; +u64 linear_srv_bytes; // desktop allocation size of the textures above (GetResourceAllocationInfo) +// detiled: the memory is console-swizzled (X2W_MEMORY_SRV_DETILE); a separate texture from a linear one with the +// same description, so one desktop copy per (address, description, form). +Wrapper* publish_linear_texture(Wrapper* device, u64 address, const D3D12_RESOURCE_DESC& desc, bool detiled = false, + bool partial = false, UINT base = 0, bool allow_create = true) +{ + std::lock_guard lock(linear_srv_mutex); + const auto [first, last] = linear_srv_textures.equal_range(address); + Wrapper* best = nullptr; + UINT best_base = UINT_MAX; + for (auto it = first; it != last; ++it) { + auto* candidate = it->second.second; + if (!same_texture_description(it->second.first, desc) || candidate->own().detiled_memory_srv != detiled || + candidate->own().partial_mip_srv != partial) continue; + if (!partial) return candidate; + auto* native = static_cast<ID3D12Resource*>(candidate->own().real); + const UINT existing = desc.MipLevels - native->GetDesc().MipLevels; + if (existing <= base && existing < best_base) { best = candidate; best_base = existing; } + } + if (best || !allow_create) return best; + const auto texture = x2w_resident_mips::host_desc(sanitized(desc), base); + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + ID3D12Resource* created = nullptr; + auto* desktop = device_of(device); + const auto standard = desktop->GetResourceAllocationInfo(0, 1, &texture).SizeInBytes; + static x2w_startup::SmallTextureHeap pool; + const auto reserved_before = pool.reserved; + const bool placed = pool.place(desktop, texture, standard, &created); + const HRESULT hr = placed ? S_OK : desktop->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &texture, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&created)); + static LONG shown, failures; + if (first_calls(shown, 16) || (FAILED(hr) && first_calls(failures, 16))) + log("x2w-memsrv linear texture at 0x%llx: %llux%ux%u mips %u fmt %d flags 0x%x -> 0x%08lx (%zu so far)", address, desc.Width, + desc.Height, desc.DepthOrArraySize, desc.MipLevels, desc.Format, static_cast<unsigned>(desc.Flags), + static_cast<unsigned long>(hr), linear_srv_textures.size() + 1); + if (FAILED(hr)) return nullptr; + x2w_startup::mark_packed_stand_in(created, desktop_format(desc.Format)); + Wrapper* w = wrap(created, resource_kind); + w->own().title_memory = reinterpret_cast<void*>(address); + w->own().linear_memory_srv = true; + w->own().detiled_memory_srv = detiled; + w->own().partial_mip_srv = partial; + note_resource(w, &desc, 0); + const auto charge = placed ? pool.reserved - reserved_before : standard; + linear_srv_bytes += charge; + thread_linear_allocations += charge; + if (placed && !(pool.count & (pool.count - 1))) + log("x2w-gpu small texture placements=%llu baseline_bytes=%llu heap_bytes=%llu occupied_bytes=%llu latest=%llux%u fmt=%u", + pool.count, pool.committed_equivalent, pool.reserved, pool.occupied, texture.Width, texture.Height, texture.Format); + if (base) { + static u64 compact_count, saved_bytes; + const auto full = sanitized(desc); + const auto whole = device_of(device)->GetResourceAllocationInfo(0, 1, &full).SizeInBytes; + if (whole != UINT64_MAX && whole >= standard) saved_bytes += whole - standard; + ++compact_count; + if ((compact_count & (compact_count - 1)) == 0) + log("x2w-gpu held mip allocations=%llu saved_bytes=%llu latest_base=%u actual_bytes=%llu whole_bytes=%llu", + compact_count, saved_bytes, base, standard, whole); + } + linear_srv_textures.emplace(address, std::make_pair(desc, w)); + return w; +} + +bool memory_srv_detile_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_MEMORY_SRV_DETILE"); + if (v) log("x2w-memsrv X2W_MEMORY_SRV_DETILE=1: unannounced console-swizzled memory SRVs are detiled (GFX10 layout)"); + return v; + }(); + return on; +} +// Bytes per element (per 4x4 block for BC); 0 when the format is not detiled (not a power of two, depth, video). +UINT detile_element_bytes(DXGI_FORMAT f, bool& bc) +{ + bc = true; + switch (f) { + case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB: + case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM: + return 8; + case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_TYPELESS: case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_TYPELESS: case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: + return 16; + default: + break; + } + bc = false; + switch (f) { + case DXGI_FORMAT_R32G32B32A32_TYPELESS: return 16; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: case DXGI_FORMAT_R32G32_TYPELESS: return 8; + case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8A8_TYPELESS: + case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R16G16_TYPELESS: case DXGI_FORMAT_R32_TYPELESS: + case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: + return 4; + case DXGI_FORMAT_R8G8_TYPELESS: case DXGI_FORMAT_R16_TYPELESS: case DXGI_FORMAT_B5G6R5_UNORM: + case DXGI_FORMAT_B5G5R5A1_UNORM: case DXGI_FORMAT_B4G4R4A4_UNORM: + return 2; + case DXGI_FORMAT_R8_TYPELESS: case DXGI_FORMAT_A8_UNORM: return 1; + default: { + const UINT n = x2w_startup::typed_buffer_format_bytes(f); + return n == 12 ? 0 : n; + } + } +} +x2w_startup::gfx10_local::Layout detile_layout(const D3D12_RESOURCE_DESC& r) +{ + bool bc = false; + const UINT bytes = detile_element_bytes(r.Format, bc); + const UINT layout = static_cast<UINT>(r.Layout); + const bool d_mode = layout == 0x106 || layout == 0x10a; + const bool known = layout == 0x100 || layout == 0x105 || layout == 0x109 || d_mode; + const bool row = r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && layout == 0x100 && !bc && + r.Height == 1 && r.DepthOrArraySize == 1 && r.MipLevels == 1; + const bool dim = row || r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D || r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + if (!bytes || !known || !dim || r.Width > 0xffffffffull) + return x2w_startup::gfx10_local::Layout(~0u, false, 0, 0, 0, 0, 0); // invalid + const UINT w = static_cast<UINT>(r.Width), h = r.Height; + x2w_startup::gfx10_local::Layout result(layout - 0x100, r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D, bytes, + bc ? (w + 3) / 4 : w, bc ? (h + 3) / 4 : h, r.DepthOrArraySize, r.MipLevels ? r.MipLevels : 1, + x2w_startup::gfx10_local::Layout::none, true); + if (row && result.valid) result.size = result.slice_size = r.Width * bytes; + return result; +} +// Why detile_srv does not take the call, as an index into detile_declines (d3d12_draw.inl); 0 when it does. +// check_memory false (a null address): the description alone, 11 ("would detile") when it passes. +unsigned detile_decline(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v, u64 address, bool check_memory = true) +{ + if (!console_swizzle(r)) return 1; + if (supports_placed_memory_srv(r, v)) return 2; // (not upstream's console-layout form: detile keeps those, local) + if (check_memory && xg_announced(address)) return 3; + D3D12_RESOURCE_DESC as_linear = r; + as_linear.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // (tiled_bc_srv / bc64 need a console layout: false here) + if (!linear_memory_srv(as_linear, v)) return 4; + const auto l = detile_layout(r); + if (!l.valid) return 5; + if (l.size > (1ull << 30)) return 7; + if (!check_memory) return 11; + if (!x2w_local::descriptor_memory_readable(address, static_cast<std::size_t>(l.size))) return 8; + return 0; +} + +// Only a deferred descriptor can upgrade its mip clamp in place as title pages arrive. +UINT deferred_host_base(const D3D12_RESOURCE_DESC& desc, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv) +{ + if (srv.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D || !srv.Texture2D.MostDetailedMip || + desc.DepthOrArraySize != 1) return 0; + bool compressed = false; + detile_element_bytes(desc.Format, compressed); + return x2w_resident_mips::host_base(desc, srv, detile_layout(desc), compressed); +} + +Wrapper* partial_mip_texture(const D3D12_RESOURCE_DESC& desc, D3D12_SHADER_RESOURCE_VIEW_DESC& srv, u64 address, + bool& pending, bool allow_create) +{ + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.MipLevels < 2 || !x2w_local::descriptor_memory_readable(address, 1) || xg_announced(address) || + detile_decline(desc, srv, address, false) != 11) return nullptr; + const auto layout = detile_layout(desc); + const auto suffix = x2w_resident_mips::find(layout, address, [](u64 at, u64 bytes) { + return x2w_local::descriptor_memory_readable(at, static_cast<std::size_t>(bytes)); + }); + auto selected = srv; + if (!suffix.prefix || !x2w_resident_mips::limit_view(selected, desc.MipLevels, suffix.first)) return nullptr; + const auto base = deferred_host_base(desc, srv); + auto* texture = publish_linear_texture(the_device, address, desc, true, true, base, allow_create); + if (!texture) return nullptr; + if (base && suffix.first <= base) pending = false; + srv = selected; + return texture; +} +bool memory_srv_buffer_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_MEMORY_SRV_BUFFER"); + if (v) log("x2w-memsrv X2W_MEMORY_SRV_BUFFER=1: memory buffer SRVs/UAVs without a buffer resource get a stand-in at the address"); + return v; + }(); + return on; +} +std::mutex standin_buffer_mutex; +std::unordered_map<u64, std::pair<u64, Wrapper*>> standin_buffers; // address -> (bytes, wrapper) +Wrapper* standin_memory_buffer(u64 address, const D3D12_RESOURCE_DESC& desc, u64 span) +{ + if (!address || !span || span > (u64{256} << 20) || desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || + !x2w_local::descriptor_memory_readable(address, 1)) + return nullptr; + const u64 bytes = desc.Width > span ? desc.Width : span; + std::lock_guard lock(standin_buffer_mutex); + if (const auto found = standin_buffers.find(address); found != standin_buffers.end() && found->second.first >= bytes) + return found->second.second; + D3D12_RESOURCE_DESC console = desc; + console.Width = bytes; + Wrapper* w = wrap(nullptr, resource_kind); + w->own().title_memory = reinterpret_cast<void*>(address); + note_resource(w, &console, bytes); + standin_buffers[address] = {bytes, w}; + static LONG shown; + const std::size_t count = standin_buffers.size(); + if (first_calls(shown, 16) || (count & (count - 1)) == 0) + log("x2w-memsrv stand-in buffer at 0x%llx: %llu bytes (%zu stand-ins)", address, bytes, count); + return w; +} + +struct MemoryUnorderedAccessView { + D3D12_UNORDERED_ACCESS_VIEW_DESC view; + u64 address; +}; +static_assert(offsetof(MemoryUnorderedAccessView, address) == 0x28); +void __stdcall device_memory_uav(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const MemoryUnorderedAccessView* input, u64 destination) +{ + static LONG refused; + const char* reason = nullptr; + if (!destination) reason = "null_destination"; + else if (!x2w_local::readable(resource, sizeof(*resource))) reason = "unreadable_resource"; + else if (!x2w_local::readable(input, sizeof(*input))) reason = "unreadable_view"; + else if (!input->address) reason = "null_address"; + else if (resource->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || input->view.ViewDimension != D3D12_UAV_DIMENSION_BUFFER) + reason = "not_a_buffer"; + else if (!memory_srv_destination(destination)) reason = "destination_outside_view_heaps"; + u64 span = 0; + if (!reason) { + const auto& b = input->view.Buffer; + const bool raw = (b.Flags & D3D12_BUFFER_UAV_FLAG_RAW) != 0; + const UINT element = b.StructureByteStride ? b.StructureByteStride : raw ? 4 : x2w_startup::typed_buffer_format_bytes(input->view.Format); + if (b.CounterOffsetInBytes) reason = "counter"; + else if (raw && (input->view.Format != DXGI_FORMAT_R32_TYPELESS || b.StructureByteStride)) reason = "bad_raw_view"; + else if (b.StructureByteStride && input->view.Format != DXGI_FORMAT_UNKNOWN) reason = "bad_structured_view"; + else if (!element || !b.NumElements) reason = "bad_element"; + else if ((span = (b.FirstElement + b.NumElements) * element) > resource->Width) reason = "view_past_resource"; + } + Wrapper* standin = reason ? nullptr : standin_memory_buffer(input->address, *resource, span); + if (!reason && !standin) reason = "no_stand_in"; + if (reason) { + if (first_calls(refused, noop_census_enabled() ? 512 : 8)) + log("x2w-memsrv Device::slot71 memory UAV refused: reason=%s res{dim=%d width=%llu} view{dim=%d fmt=%d} dest=0x%llx", reason, + x2w_local::readable(resource, sizeof(*resource)) ? resource->Dimension : -1, + x2w_local::readable(resource, sizeof(*resource)) ? resource->Width : 0ull, + x2w_local::readable(input, sizeof(*input)) ? input->view.ViewDimension : -1, + x2w_local::readable(input, sizeof(*input)) ? input->view.Format : -1, destination); + return; + } + note_linear_form(lf_buffer_uav, destination); + view_slot<19, 3>(self, reinterpret_cast<u64>(standin), 0, reinterpret_cast<u64>(&input->view), destination); +} + +// LOCAL (textures): X2W_TEXTURE_CENSUS=1 counts every slot-70 outcome, and every refusal by its class (reason, +// resource dimension, layout, format, mip chain or not, XG-announced address or not, first 256 bytes non-zero or +// not), past the 2048-line refusal cap (these lines have no cap of their own). Lines, all cumulative: +// "x2w-texcensus slot70 calls N (...)" and "x2w-texcensus slot70 refusals N (...), top classes:" (up to 24 classes) +// with every 300-frame draw census line, and also at powers of two (calls from 1024, refusals from 256). +enum MemorySrvOutcome { mso_linear, mso_announced, mso_tiled, mso_buffer, mso_standin, mso_refused, mso_detiled, mso_descriptor, mso_count }; +const char* const memory_srv_outcome_names[mso_count] = {"linear", "announced-linear", "tiled/bc64", "buffer", "stand-in buffer", "refused", "detiled", "buffer descriptor"}; +LONG64 memory_srv_outcomes[mso_count]; +std::mutex refusal_census_mutex; +std::unordered_map<u64, LONG64> refusal_census; +LONG64 refusal_census_total; +const char* const census_reasons[] = {"null_destination", "unreadable_resource", "unreadable_view", "null_address", + "unsupported_description", "destination_outside_view_heaps", "buffer_unavailable", "texture_unavailable"}; +bool census_every_event(); +bool texture_census_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_TEXTURE_CENSUS"); + if (v) log("x2w-texcensus X2W_TEXTURE_CENSUS=1: slot-70 outcomes and refusal classes, draw texture bindings real/null; " + "all cumulative, every 300 frames%s", census_every_event() ? " and after every event (X2W_TEXTURE_CENSUS_EVERY=1)" : ""); + return v; + }(); + return on; +} +// X2W_TEXTURE_CENSUS_EVERY=1 (tests): the cumulative lines after every counted event instead of at the thresholds. +bool census_every_event() +{ + static const bool on = x2w_local::env_on("X2W_TEXTURE_CENSUS_EVERY"); + return on; +} +void log_memory_srv_outcomes(const char* when) +{ + LONG64 total = 0; + for (LONG64 n : memory_srv_outcomes) total += n; + log("x2w-texcensus slot70 calls %lld (%s, cumulative): linear %lld, announced-linear %lld, tiled/bc64 %lld, buffer %lld, stand-in buffer %lld, " + "detiled %lld, refused %lld, buffer descriptor %lld", total, when, memory_srv_outcomes[0], memory_srv_outcomes[1], memory_srv_outcomes[2], memory_srv_outcomes[3], + memory_srv_outcomes[4], memory_srv_outcomes[6], memory_srv_outcomes[5], memory_srv_outcomes[7]); +} +void log_refusal_classes(const char* when) // refusal_census_mutex held +{ + std::vector<std::pair<LONG64, u64>> sorted; + for (const auto& [k, n] : refusal_census) sorted.emplace_back(n, k); + std::sort(sorted.begin(), sorted.end(), std::greater<>()); + log("x2w-texcensus slot70 refusals %lld (%s, cumulative), %zu classes, top classes:", refusal_census_total, when, sorted.size()); + for (std::size_t i = 0; i < sorted.size() && i < 24; ++i) { + const u64 k = sorted[i].second; + const u64 decline = (k >> 31) & 15; + char why[48] = ""; + if (decline) std::snprintf(why, sizeof why, " detile: %s", decline < std::size(detile_declines) ? detile_declines[decline] : "?"); + log("x2w-texcensus %lld x %s dim %llu layout 0x%llx fmt %llu %s %s %s%s", sorted[i].first, + (k & 15) < std::size(census_reasons) ? census_reasons[k & 15] : "other", (k >> 4) & 15, (k >> 8) & 0x1ff, (k >> 20) & 0xff, + (k >> 28) & 1 ? "mips>1" : "mips=1", (k >> 29) & 1 ? "announced" : "not-announced", + !((k >> 35) & 1) ? "unreadable" : (k >> 30) & 1 ? "nonzero" : "zero", why); + } +} +// Called with the 300-frame draw census line (d3d12_draw.inl), so a title run's scene window is the difference of +// two reports. +void report_memory_srv_census(long frame) +{ + if (!texture_census_on()) return; + char when[32]; + std::snprintf(when, sizeof(when), "frame %ld", frame); + log_memory_srv_outcomes(when); + std::lock_guard lock(refusal_census_mutex); + log_refusal_classes(when); +} +void census_memory_srv_outcome(int outcome) +{ + if (!texture_census_on()) return; + InterlockedIncrement64(&memory_srv_outcomes[outcome]); + LONG64 total = 0; + for (LONG64 n : memory_srv_outcomes) total += n; + if (census_every_event() || (total >= 1024 && (total & (total - 1)) == 0)) log_memory_srv_outcomes("threshold"); +} +// The memory at a refused call's address: its first 256 bytes readable, and any of them nonzero. +struct RefusedMemory { + bool readable = false, nonzero = false; +}; +RefusedMemory refused_memory(u64 address) +{ + RefusedMemory m; + if (address && x2w_local::descriptor_memory_readable(address, 256)) { + m.readable = true; + const auto* bytes = reinterpret_cast<const unsigned char*>(address); + for (int i = 0; i < 256 && !m.nonzero; ++i) m.nonzero = bytes[i] != 0; + } + return m; +} +LONG64 detile_decline_counts[std::size(detile_declines)]; +// decline: detile_decline's verdict (detile_declines, d3d12_draw.inl; 0 = not asked). Key bits: reason 0-3, dimension +// 4-7, layout 8-16, format 20-27, mips > 1 28, announced 29, nonzero 30, decline 31-34, first 256 bytes readable 35. +// The memory of a refused call, read once for the census and the marker (and not at all when both are off). +RefusedMemory refused_call_memory(const MemoryShaderResourceView* input) +{ + if (!texture_census_on() && !buffer_heap_index_on()) return {}; + return x2w_local::readable(input, sizeof(*input)) ? refused_memory(input->address) : RefusedMemory{}; +} +void census_refusal(const char* reason, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, unsigned decline, + const RefusedMemory& memory) +{ + if (!texture_census_on()) return; + census_memory_srv_outcome(mso_refused); + u64 r = 0; + while (r < std::size(census_reasons) && std::strcmp(census_reasons[r], reason) != 0) ++r; + const bool resource_ok = x2w_local::readable(resource, sizeof(*resource)); + const bool input_ok = x2w_local::readable(input, sizeof(*input)); + const u64 address = input_ok ? input->address : 0; + if (decline >= std::size(detile_declines)) decline = 0; + const u64 dim = resource_ok && resource->Dimension >= 0 && resource->Dimension <= 4 ? resource->Dimension : 7; + const u64 layout = resource_ok ? (static_cast<UINT>(resource->Layout) & 0x1ff) : 0x1ff; + const u64 format = resource_ok ? (static_cast<UINT>(resource->Format) & 0xff) : 0xff; + const u64 chain = resource_ok && resource->MipLevels > 1; + const u64 key = r | dim << 4 | layout << 8 | format << 20 | chain << 28 | u64{address && xg_announced(address)} << 29 | + u64{memory.nonzero} << 30 | u64{decline} << 31 | u64{memory.readable} << 35; + if (decline) { + InterlockedIncrement64(&detile_decline_counts[decline]); + LONG64 n = 0; + for (LONG64 c : detile_decline_counts) n += c; + if (census_every_event() || (n & (n - 1)) == 0) { + char parts[512]; + int used = 0; + for (std::size_t i = 1; i < std::size(detile_declines); ++i) + used += std::snprintf(parts + used, sizeof(parts) - used, "%s%s %lld", i > 1 ? ", " : "", detile_declines[i], detile_decline_counts[i]); + log("x2w-texcensus detile declines of refused texture calls %lld (X2W_MEMORY_SRV_DETILE): %s", n, parts); + } + } + std::lock_guard lock(refusal_census_mutex); + const bool fresh = ++refusal_census[key] == 1; + const LONG64 total = ++refusal_census_total; + // The first call of each class (at most 96 classes): every field, the layout's size and how much of it is readable. + static LONG described_classes; + if (fresh && resource_ok && input_ok && first_calls(described_classes, 96)) { + char resource_text[224], view_text[256]; + x2w_startup::report_resource(resource_text, sizeof(resource_text), resource); + x2w_startup::report_view(view_text, sizeof(view_text), &input->view); + const auto l = detile_layout(*resource); + const std::size_t want = l.valid ? static_cast<std::size_t>((std::min)(l.size, u64{1} << 30)) : 0; + log("x2w-texcensus new refusal class: %s res{%s} view{%s} address 0x%llx; detile: %s; memory %s; console layout %llu bytes, %zu " + "readable from the address", reason, resource_text, view_text, address, detile_declines[decline], + !memory.readable ? "unreadable" : memory.nonzero ? "nonzero" : "zero", l.valid ? l.size : 0ull, + want && address ? x2w_local::probe_descriptor_address(address, want) : 0); + } + if (census_every_event() || (total >= 256 && (total & (total - 1)) == 0)) log_refusal_classes("threshold"); +} + +u64 __stdcall device_slot61_census(Wrapper* self, u64 rdx, u64 r8, u64 r9) +{ + if (noop_census_enabled()) { // what the no-op it replaces still reports + const u64 args[8] = {reinterpret_cast<u64>(self), rdx, r8, r9, 0, 0, 0, 0}; + noop_census_note(device_kind, 61, args, reinterpret_cast<u64>(_ReturnAddress()) - reinterpret_cast<u64>(GetModuleHandleW(nullptr))); + } + static LONG calls; + if (first_calls(calls, 16)) { + char hex[200] = "unreadable"; + if (x2w_local::readable(reinterpret_cast<const void*>(rdx), 64)) { + const auto* w = reinterpret_cast<const std::uint32_t*>(rdx); + int used = 0; + for (int i = 0; i < 16; ++i) used += std::snprintf(hex + used, sizeof(hex) - used, "%08x ", w[i]); + } + log("x2w-texcensus Device::slot61 (sampler?) rdx=0x%llx r8=0x%llx r9=0x%llx words %s", rdx, r8, r9, hex); + } + return 0; +} + // The first check that refuses a call, in the order the checks run; null when every check passes. const char* memory_srv_refusal(const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { @@ -601,17 +1268,122 @@ void log_refused_memory_srv(const char* what, const char* reason, const D3D12_RE const u64 address = input_ok ? input->address : 0; char line[640]; x2w_startup::report_refused_memory_srv(line, sizeof(line), what, reason, resource_ok ? resource : nullptr, - input_ok ? &input->view : nullptr, address, address && x2w_local::readable(reinterpret_cast<const void*>(address), 1), + input_ok ? &input->view : nullptr, address, address && x2w_local::descriptor_memory_readable(address, 1), destination, destination && memory_srv_destination(destination)); log("%s", line); } +// LOCAL (textures): X2W_BUFFER_HEAP_INDEX=1. A refused call writes {refused_view_magic, reason code, description} +// into its title destination (describe_marker, d3d12_draw.inl, has the word layout) and clears the slot's shadow id. +// That is what the slot would otherwise keep: the title's free-list link, or a stale token, which copies spread into +// draw tables. The description travels with the title's copies, so a draw's null entry names the refused call. +void mark_refused_destination(u64 destination, const char* reason, const D3D12_RESOURCE_DESC* resource, + const MemoryShaderResourceView* input, unsigned decline, const RefusedMemory& memory) +{ + if (!buffer_heap_index_on() || !destination || !title_backed(destination, 32) || !x2w_local::writable(reinterpret_cast<void*>(destination), 32)) + return; + std::uint32_t marker[8] = {refused_view_magic, refusal_code(reason), 1u << 31, 0, 0, 0, 0, 0}; + if (x2w_local::readable(resource, sizeof(*resource))) { + const auto& r = *resource; + marker[2] |= (static_cast<UINT>(r.Format) & 0xff) | (static_cast<UINT>(r.Layout) & 0x1ff) << 8 | + (static_cast<UINT>(r.Dimension) & 7) << 17 | (r.MipLevels < 15 ? r.MipLevels : 15u) << 20 | (decline & 15) << 24; + marker[3] = r.Width > 0xffffffffull ? 0xffffffffu : static_cast<std::uint32_t>(r.Width); + marker[4] = r.Height; + marker[5] = r.DepthOrArraySize; + } + if (x2w_local::readable(input, sizeof(*input))) { + marker[5] |= std::uint32_t{memory.readable} << 16 | std::uint32_t{memory.nonzero} << 17; + marker[6] = static_cast<std::uint32_t>(input->address); + marker[7] = static_cast<std::uint32_t>(input->address >> 32); + } + // Preserve an otherwise valid placed SRV while DirectStorage pages are still absent. The descriptor mirror resolves + // these words at use time, including copies of this slot. + static const bool retry = x2w_gpu::gpu_abi_on() && x2w_local::env_on("X2W_GPU_LATE_TEXTURES"); + if (retry && decline == 8 && resource && input && x2w_late_texture::encode(*resource, input->view, input->address, marker)) { + static LONG deferred; + const LONG n = InterlockedIncrement(&deferred); + if ((n & (n - 1)) == 0) log("x2w-gpu deferred texture descriptors written %ld", n); + } + std::memcpy(reinterpret_cast<void*>(destination), marker, sizeof(marker)); + if (const u64 desktop = desktop_cpu_handle(destination)) { + AcquireSRWLockExclusive(¬e_lock); + if (std::uint32_t* slot = shadow_slot(desktop)) *slot = 0; + ReleaseSRWLockExclusive(¬e_lock); + } +} +LONG64 vdesc_no_buffer, vdesc_unaligned, vdesc_no_destination, vdesc_layout, vdesc_ticks[3], vdesc_lock_taken; +void heap_raw_note(const std::uint32_t* words); // LOCAL: d3d12_heap_raw.inl (`heapraw 1` compute: the V# by content) +LONG64 qpc_now() +{ + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return t.QuadPart; +} +bool write_buffer_descriptor(u64 destination, const MemoryShaderResourceView* input, bool found_buffer, LONG64 lookup_ticks) +{ + if (!buffer_heap_index_on()) return false; + const auto counted = [](LONG64& which) { + InterlockedIncrement64(&which); + const LONG64 n = vdesc_no_buffer + vdesc_unaligned + vdesc_no_destination + vdesc_layout; + if ((n & (n - 1)) == 0) { + static const double us_per_tick = [] { + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + return 1e6 / static_cast<double>(f.QuadPart); + }(); + const double written = static_cast<double>((std::max)(1ll, vdesc_no_buffer + vdesc_unaligned)); + log("x2w-memsrv buffer descriptors: written %lld (no buffer %lld, buffer at an offset the view cannot name %lld), not written: " + "destination not title memory %lld, view not encodable %lld; per written call: buffer lookup %.2f us, destination checks " + "%.2f us, shadow clear %.2f us (lock taken %lld)", vdesc_no_buffer + vdesc_unaligned, vdesc_no_buffer, vdesc_unaligned, + vdesc_no_destination, vdesc_layout, vdesc_ticks[0] * us_per_tick / written, vdesc_ticks[1] * us_per_tick / written, + vdesc_ticks[2] * us_per_tick / written, vdesc_lock_taken); + } + }; + const LONG64 t0 = qpc_now(); + if (!destination || !title_backed(destination, 32) || !x2w_local::writable(reinterpret_cast<void*>(destination), 32)) { + counted(vdesc_no_destination); + return false; + } + const LONG64 t1 = qpc_now(); + x2w_startup::BufferViewLayout l; + if (!x2w_startup::buffer_view_layout_from_desc(false, reinterpret_cast<const unsigned char*>(&input->view), 40, l) || + l.kind == x2w_startup::BufferViewKind::unknown || !l.num_records || ((input->address + l.offset) >> 48)) { + counted(vdesc_layout); + return false; + } + std::uint32_t words[8]; + x2w_startup::gfx10_buffer_words(l, words); + const u64 base = input->address + l.offset; + words[0] = static_cast<std::uint32_t>(base); + words[1] |= static_cast<std::uint32_t>(base >> 32) & 0xffff; + std::memcpy(reinterpret_cast<void*>(destination), words, sizeof(words)); + heap_raw_note(words); // LOCAL: translated `heapraw 1` compute reads this V# wherever the title copies it + if (const u64 desktop = desktop_cpu_handle(destination)) { + // Most slots hold no id (the title rewrites the same slots with V#s): look under the shared lock first. + if (shadow_id(desktop)) { + InterlockedIncrement64(&vdesc_lock_taken); + AcquireSRWLockExclusive(¬e_lock); + if (std::uint32_t* slot = shadow_slot(desktop)) *slot = 0; + ReleaseSRWLockExclusive(¬e_lock); + } + } + const LONG64 t2 = qpc_now(); + InterlockedAdd64(&vdesc_ticks[0], lookup_ticks); + InterlockedAdd64(&vdesc_ticks[1], t1 - t0); + InterlockedAdd64(&vdesc_ticks[2], t2 - t1); + counted(found_buffer ? vdesc_unaligned : vdesc_no_buffer); + static LONG shown; + if (first_calls(shown, 8)) + log("x2w-memsrv buffer descriptor written at 0x%llx (X2W_BUFFER_HEAP_INDEX): base 0x%llx, stride %u, records %u, word 3 0x%08x%s", destination, + base, l.index_stride, l.num_records, words[3], found_buffer ? " (a buffer is there, at an offset the view cannot name)" : ""); + return true; +} // Counts a refusal (memory_srv_census) and logs its line while the first 8 refusals last, and also for // the first refusal of each of the first few distinct shapes (MemorySrvCensus::detail_shapes). void refuse_memory_srv(LONG& refused, const char* what, const char* reason, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { - const bool within_limit = first_calls(refused, 8); + const bool within_limit = first_calls(refused, noop_census_enabled() ? 2048 : 8); // LOCAL: the census limit const bool new_shape = memory_srv_census.note(reason, x2w_local::readable(resource, sizeof(*resource)) ? resource : nullptr); if (within_limit || new_shape) log_refused_memory_srv(what, reason, resource, input, destination); } @@ -658,26 +1430,170 @@ void publish_as_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const Me const u64 location = x2w_startup::as_srv_location(input->view, input->address); D3D12_SHADER_RESOURCE_VIEW_DESC resolved{}; const auto refusal = x2w_startup::resolve_as_srv_desc(location, placed_as_buffer(self, location), input->view, resolved); + const u64 desktop = desktop_cpu_handle(destination); + const bool logical = x2w_gpu::gpu_abi_on() && desktop && desktop != destination && title_backed(destination, 32) && + x2w_local::writable(reinterpret_cast<void*>(destination), 32); if (refusal != x2w_startup::AsSrvRefusal::none) { + if (logical) { + auto desc = input->view; + desc.RaytracingAccelerationStructure.Location = location; + note_view(18, 0, 0, &desc, sizeof(desc), destination, desktop, false); + } refuse_memory_srv(refused, "unavailable acceleration structure at the supplied address", x2w_startup::as_srv_refusal_name(refusal), resource, input, destination); return; } view_slot<18, 2>(self, 0, reinterpret_cast<u64>(&resolved), destination, 0); + if (logical) + x2w_as_address::annotate(reinterpret_cast<std::uint32_t*>(destination), location); } +namespace gpu_detail_heap { +u64 late_texture(const std::uint32_t* words, D3D12_SHADER_RESOURCE_VIEW_DESC& srv, bool& pending, bool allow_create = true); +} + +void copy_lazy_native_srv(Wrapper* self, u64 source, u64 destination) +{ + static const bool enabled = x2w_local::env_on("X2W_GPU_LAZY_DETILE") && x2w_local::env_on("X2W_GPU_LATE_TEXTURES"); + if (!enabled) return; + std::uint32_t words[8]; + std::memcpy(words, reinterpret_cast<const void*>(source), sizeof(words)); + if (words[0] != x2w_late_texture::lazy) return; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + bool pending = false; + if (const u64 wrapper = gpu_detail_heap::late_texture(words, srv, pending)) + view_slot<18, 2>(self, wrapper, reinterpret_cast<u64>(&srv), destination, 0); +} +bool lazy_detiled_srv(Wrapper* self, const D3D12_RESOURCE_DESC& resource, const MemoryShaderResourceView& input, u64 destination) +{ + static const bool enabled = x2w_gpu::gpu_abi_on() && x2w_local::env_on("X2W_GPU_LATE_TEXTURES") && + x2w_local::env_on("X2W_GPU_LAZY_DETILE"); + if (!enabled) return false; + std::uint32_t words[8]{}; + if (!x2w_late_texture::encode(resource, input.view, input.address, words) || !title_backed(destination, sizeof(words)) || + !x2w_local::writable(reinterpret_cast<void*>(destination), sizeof(words))) return false; + + words[0] = x2w_late_texture::lazy; + auto desc = input.view; + desc.Format = desktop_format(desc.Format); + if (desc.Format == DXGI_FORMAT_UNKNOWN) desc.Format = desktop_format(resource.Format); + // A CPU descriptor copied through D3D12 must be initialized even before the mirror has a texture. + view_slot<18, 2>(self, 0, reinterpret_cast<u64>(&desc), destination, 0); + std::memcpy(reinterpret_cast<void*>(destination), words, sizeof(words)); + static LONG64 staged; + const auto n = InterlockedIncrement64(&staged); + if ((n & (n - 1)) == 0) log("x2w-gpu detiled texture descriptors staged %lld", n); + return true; +} void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { X2W_ZONE("device_memory_srv"); static LONG refused; check_resource_address_index(); + if (noop_census_enabled()) { // LOCAL (video): is the handler reached at all, and where does it write? + static LONG64 calls; + const LONG64 n = InterlockedIncrement64(&calls); + CensusHeap h{}; + const bool in_heap = noop_census_heap_index(destination, &h); + if (n <= 8 || (n & (n - 1)) == 0) + log("x2w-noop-census memory SRV call %lld: destination 0x%llx = %s index 0x%llx of the heap at 0x%llx", n, destination, + in_heap ? (h.desktop ? "DESKTOP" : "title") : "no heap", h.index, h.base); + } + const bool described = destination && x2w_local::readable(resource, sizeof(*resource)) && + x2w_local::readable(input, sizeof(*input)) && input->address; + if (described && !x2w_startup::is_as_srv(input->view) && + (resource->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D || resource->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) && + !x2w_late_texture::valid_shape(*resource, true)) { + constexpr auto reason = "unsupported_description"; + refuse_memory_srv(refused, "invalid texture shape", reason, resource, input, destination); + const auto memory = refused_call_memory(input); + census_refusal(reason, resource, input, 0, memory); + mark_refused_destination(destination, reason, resource, input, 0, memory); + return; + } + if (described && x2w_packed_light::color_bytes(resource->Format) && input->view.Format == resource->Format && + linear_view_in_range(*resource, input->view) && + packed_light_source(input->address, *resource) && memory_srv_destination(destination)) { + if (auto* proxy = publish_linear_texture(self, input->address, *resource, true)) { + view_slot<18, 2>(self, reinterpret_cast<u64>(proxy), reinterpret_cast<u64>(&input->view), destination, 0); + return; + } + } + // An encoded block copy writes the native texture. A CPU-derived proxy at + // the same base still contains the original title bytes. + if (described) { + if (auto* native = native_tiled_bc_texture(input->address, *resource, input->view); native && memory_srv_destination(destination)) { + view_slot<18, 2>(self, reinterpret_cast<u64>(native), reinterpret_cast<u64>(&input->view), destination, 0); + census_memory_srv_outcome(mso_tiled); + note_memory_srv_write(resource, input, destination); + return; + } + } + const bool plain = described && memory_srv_linear_on() && linear_memory_srv(*resource, input->view); + if ((plain || (described && memory_srv_announced_on() && announced_linear_srv(*resource, input->view, input->address))) && + memory_srv_destination(destination)) { + Wrapper* texture = existing_memory_texture(input->address, *resource); + if (!texture) texture = publish_linear_texture(self, input->address, *resource); + if (texture) { + static LONG64 linear_views; + const LONG64 n = InterlockedIncrement64(&linear_views); + if ((n & (n - 1)) == 0) { + std::size_t textures; + u64 bytes; + { + std::lock_guard lock(linear_srv_mutex); + textures = linear_srv_textures.size(); + bytes = linear_srv_bytes; + } + log("x2w-memsrv linear memory SRVs written: %lld, %zu textures, %llu KiB (latest destination 0x%llx)", n, textures, + bytes >> 10, destination); + } + note_linear_form(linear_form(input->view.ViewDimension), destination); + census_memory_srv_outcome(plain ? mso_linear : mso_announced); + view_slot<18, 2>(self, reinterpret_cast<u64>(texture), reinterpret_cast<u64>(&input->view), destination, 0); + return; + } + } + // LOCAL (textures): X2W_MEMORY_SRV_DETILE (detile_srv above); after the linear and announced forms, before the + // refusal checks, so every path that took a call before still takes it. + // decline: why it did not, for the refusal logs (detile_declines); 0 when not asked (switch off, a buffer). + unsigned decline = 0; + if (memory_srv_detile_on() && destination && x2w_local::readable(resource, sizeof(*resource)) && + x2w_local::readable(input, sizeof(*input)) && resource->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { + decline = detile_decline(*resource, input->view, input->address, input->address != 0); + if (!decline && !memory_srv_destination(destination)) decline = 9; + } + if (described && memory_srv_detile_on() && resource->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && !decline) { + if (lazy_detiled_srv(self, *resource, *input, destination)) { + note_linear_form(linear_form(input->view.ViewDimension), destination); + census_memory_srv_outcome(mso_detiled); + return; + } + Wrapper* texture = existing_memory_texture(input->address, *resource); + if (!texture) texture = publish_linear_texture(self, input->address, *resource, true); + if (!texture) decline = 10; + if (texture) { + static LONG shown; + if (first_calls(shown, 16)) + log("x2w-memsrv detiled memory SRV at 0x%llx: %llux%ux%u mips %u fmt %d layout 0x%x dim %d", input->address, + resource->Width, resource->Height, resource->DepthOrArraySize, resource->MipLevels, resource->Format, + static_cast<unsigned>(resource->Layout), resource->Dimension); + note_linear_form(linear_form(input->view.ViewDimension), destination); + census_memory_srv_outcome(mso_detiled); + view_slot<18, 2>(self, reinterpret_cast<u64>(texture), reinterpret_cast<u64>(&input->view), destination, 0); + return; + } + } if (const char* reason = memory_srv_refusal(resource, input, destination)) { refuse_memory_srv(refused, "unsupported memory SRV arguments", reason, resource, input, destination); + const RefusedMemory memory = refused_call_memory(input); + census_refusal(reason, resource, input, decline, memory); + mark_refused_destination(destination, reason, resource, input, decline, memory); return; } // A single-element texture is published by address like a tiled view: its texel is read at offset 0. - if (x2w_startup::supports_single_element_srv(*resource, input->view)) { + if (upstream_console_srv_on() && x2w_startup::supports_single_element_srv(*resource, input->view)) { if (gpu_written_overlap(input->address, x2w_startup::single_element_bytes(*resource))) { refuse_memory_srv(refused, "GPU-written resource at the supplied address", "gpu_written_resource", resource, input, destination); @@ -697,19 +1613,36 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou if (resource->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { const u64 elem_bytes = x2w_startup::buffer_srv_element_bytes(input->view); const u64 span_bytes = (input->view.Buffer.FirstElement + input->view.Buffer.NumElements) * elem_bytes; + const LONG64 lookup_start = buffer_heap_index_on() ? qpc_now() : 0; Wrapper* buffer = existing_memory_buffer(self, input->address, span_bytes); - if (!buffer) { - buffer = unplaced_memory_buffer(self, input->address, span_bytes, *resource); - } + const LONG64 lookup_ticks = buffer_heap_index_on() ? qpc_now() - lookup_start : 0; const ResourceInfo* info = buffer ? resource_info(buffer) : nullptr; D3D12_SHADER_RESOURCE_VIEW_DESC adjusted{}; + if ((!buffer || !info) && memory_srv_buffer_on()) { + // LOCAL (video): no buffer resource covers the address; a stand-in whose title memory starts there. + if (Wrapper* standin = standin_memory_buffer(input->address, *resource, span_bytes)) { + note_linear_form(lf_buffer_srv, destination); + census_memory_srv_outcome(mso_standin); + view_slot<18, 2>(self, reinterpret_cast<u64>(standin), reinterpret_cast<u64>(&input->view), destination, 0); + return; + } + } if (!buffer || !info || !x2w_startup::resolve_buffer_srv_desc(reinterpret_cast<u64>(buffer->own().title_memory), info->console.Width, input->address, input->view, adjusted)) { + // LOCAL (textures): X2W_BUFFER_HEAP_INDEX=1: the console V# instead (write_buffer_descriptor). + if (write_buffer_descriptor(destination, input, buffer && info, lookup_ticks)) { + census_memory_srv_outcome(mso_descriptor); + return; + } refuse_memory_srv(refused, "unavailable buffer at the supplied address", "buffer_unavailable", resource, input, destination); + const RefusedMemory memory = refused_call_memory(input); + census_refusal("buffer_unavailable", resource, input, 0, memory); + mark_refused_destination(destination, "buffer_unavailable", resource, input, 0, memory); return; } + census_memory_srv_outcome(mso_buffer); view_slot<18, 2>(self, reinterpret_cast<u64>(buffer), reinterpret_cast<u64>(&adjusted), destination, 0); note_memory_srv_write(resource, input, destination); return; @@ -751,8 +1684,12 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou if (!texture) { refuse_memory_srv(refused, "unavailable texture at the supplied base and layout", held ? held : "texture_unavailable", resource, input, destination); + const RefusedMemory memory = refused_call_memory(input); + census_refusal("texture_unavailable", resource, input, decline, memory); + mark_refused_destination(destination, "texture_unavailable", resource, input, decline, memory); return; } + census_memory_srv_outcome(mso_tiled); view_slot<18, 2>(self, reinterpret_cast<u64>(texture), reinterpret_cast<u64>(&input->view), destination, 0); note_memory_srv_write(resource, input, destination); } diff --git a/src/startup_stubs/d3d12_mesh.inl b/src/startup_stubs/d3d12_mesh.inl new file mode 100644 index 0000000000..f5af68c967 --- /dev/null +++ b/src/startup_stubs/d3d12_mesh.inl @@ -0,0 +1,1272 @@ +// Local experiment (never upstream): translated MESH pipelines issued through ExecuteIndirect (agent meshrt). +// Included inside d3d12_xs_device.cpp's anonymous namespace, after d3d12_indirect.inl. +// +// Off unless X2W_MESH=1. When on, indirect_mesh_hook is set and every DispatchMesh ExecuteIndirect call goes: +// indirect_run -> mesh_prepare (this file, before the record is staged; no draw_lock): +// the bound pipeline's mesh key (computed at slot-57 creation by mesh_note57; slot 55: its base's key), +// the translation <key>.txt / .ms.cso / [.ps.cso] (loaded once per key, off draw_lock), +// the desktop PSO (ID3D12Device2::CreatePipelineState stream, once per key and target/state set, off draw_lock); +// a call without all three is skipped BEFORE indirect stages its copy and guard pass; +// -> indirect_stage (copy + guard) -> mesh_hook -> draw_translated (d3d12_draw.inl) with the mesh translation: +// the same binding code as a translated draw (entry constants, srv / uav / sampler tables, heap, default +// viewport and scissor), pipeline_for returns the pre-built mesh PSO, and the issue point +// (indirect_pending -> indirect_draw_issue(self, list, false)) records the ExecuteIndirect. +// +// Key rule (board/msgs/195600_meshrt_mesh-key-rule.md, mesh's 183500 proposal): a slot-57 record without vertex +// code at [9]/[10] and with mesh code at [13]/[14] has the key pipeline_key(a = [5]/[6] bytes or empty, b = [13]/[14] +// bytes, root blob). Slot-55 pipelines take their slot-57 base's key. +// +// Cache files (mesh_work/RUNTIME_NEEDS.md): <key>.txt (draw manifest + `stage mesh` + `ms <threads> <verts> <prims>`, +// published last), <key>.ms.cso (DXIL ms_6_5, required), <key>.ps.cso (optional: none = depth-only pipeline). +// Requests req_<key>.{b,root,a} are written by regblob at creation (not here). +// +// Per 300 frames: "x2w-mesh N frames: calls X issued Y; skipped: ..." (report_mesh), then the bound keys with their +// call counts (report_mesh_keys, top 64). Per key: "x2w-mesh key K first bound frame F (cache: ok|fail|missing)" +// (first 4096 keys), "no translation" / "translation failed (...)" once, "call refused (no targets | rtv variant | +// no PSO | bind refused ...)" once per reason, "first call issued" once. Manifest `fma exact|precise` (RUNTIME_NEEDS 8): +// exact or unstated needs DoublePrecisionFloatShaderOps; a cache mixing rules is logged once, not refused. +// Fixed-function state: the default state (opaque blend; depth-stencil only from a stream pipeline, else off; cull +// none). The decoded mesh state (+0x54 from the vertex-record offsets) replaces mesh_state_desc's body. + +bool mesh_enabled() +{ + static const bool on = x2w_local::env_on("X2W_MESH"); + return on; +} + +enum MeshSkip { mesh_no_translation, mesh_failed, mesh_no_pso, mesh_no_targets, mesh_tier, mesh_no_record, mesh_rtv_variant, mesh_bind, mesh_compiling, mesh_skips }; +LONG mesh_calls, mesh_issued, mesh_skipped[mesh_skips]; +thread_local int mesh_last_skip = -1; // LOCAL meshrt: this thread's last skip reason (traced-frame mesh lines) +void mesh_skip(MeshSkip why) { InterlockedIncrement(&mesh_skipped[why]); mesh_last_skip = why; } +constexpr const char* mesh_skip_names[mesh_skips] = {"no translation", "translation failed", "no PSO", "no targets", "tier", + "no mesh record", "rtv variant", "bind refused", "PSO compiling"}; + +// ---- Keys, at slot-57 creation -------------------------------------------------------------------------------- + +struct MeshRecordKey { + u64 key = 0; + bool keyed = false; // false: a mesh record without a key (no root blob, unreadable pixel code) +}; +SRWLOCK mesh_key_lock = SRWLOCK_INIT; +std::unordered_map<const Wrapper*, MeshRecordKey>& mesh_record_keys() { static std::unordered_map<const Wrapper*, MeshRecordKey> m; return m; } +LONG mesh_records_keyed, mesh_records_unkeyed; + +// Device slot 57, after note_pipeline (X2W_MESH=1 only). The code blobs are hashed while the title still holds them. +void mesh_note57(const void* desc, const Wrapper* self) +{ + if (!mesh_enabled() || !desc || !self || readable_window(reinterpret_cast<u64>(desc), 0x80) < 0x80) return; + u64 w[16]; + std::memcpy(w, desc, sizeof(w)); + if (w[9] && w[10]) return; // vertex code: the draw key (translation_for) + const auto* b = reinterpret_cast<const void*>(w[13]); + const std::size_t b_bytes = static_cast<std::size_t>(w[14]); + if (!b || !b_bytes || b_bytes > (1u << 20) || !x2w_local::readable(b, b_bytes)) return; + MeshRecordKey k; + std::vector<unsigned char> root_blob; + if (Wrapper* root = as_wrapper(reinterpret_cast<const void*>(w[0]))) { + AcquireSRWLockShared(¬e_lock); + const auto found = root_blobs().find(root); + if (found != root_blobs().end()) root_blob = found->second; + ReleaseSRWLockShared(¬e_lock); + } + const auto* a = reinterpret_cast<const void*>(w[5]); + std::size_t a_bytes = static_cast<std::size_t>(w[6]); + bool a_ok = true; + if (!a || !a_bytes) a = nullptr, a_bytes = 0; // depth-only: empty a + else a_ok = a_bytes <= (1u << 20) && x2w_local::readable(a, a_bytes); + if (!root_blob.empty() && a_ok) { + k.key = pipeline_key(a, a_bytes, b, b_bytes, root_blob); + k.keyed = true; + } + InterlockedIncrement(k.keyed ? &mesh_records_keyed : &mesh_records_unkeyed); + static LONG shown; + if (first_calls(shown, 4)) + log("x2w-mesh slot 57 pipeline %p: mesh record, pixel code %zu bytes, mesh code %zu bytes, root %zu bytes -> %s %016llx", + static_cast<const void*>(self), a_bytes, b_bytes, root_blob.size(), k.keyed ? "key" : "NO KEY", k.key); + AcquireSRWLockExclusive(&mesh_key_lock); + mesh_record_keys()[self] = k; + ReleaseSRWLockExclusive(&mesh_key_lock); +} + +// The mesh key of a bound pipeline: its own slot-57 record, else the base chain of slot-55 pipelines (depth 8). +bool mesh_key_of(const Wrapper* pipeline, MeshRecordKey* out) +{ + for (int depth = 0; pipeline && depth < 8; ++depth) { + bool found = false; + AcquireSRWLockShared(&mesh_key_lock); + const auto it = mesh_record_keys().find(pipeline); + if (it != mesh_record_keys().end()) *out = it->second, found = true; + ReleaseSRWLockShared(&mesh_key_lock); + if (found) return true; + const PipelineInfo* info = pipeline_info(pipeline); + pipeline = info && info->path == 55 ? info->base : nullptr; + } + return false; +} + +// ---- Translations, per key (off draw_lock) ------------------------------------------------------------------ + +// The multiply-add rule a mesh translation was built with (mesh_work/RUNTIME_NEEDS.md 8): manifest `fma exact` (fused +// console ops as binary64 fma: needs DoublePrecisionFloatShaderOps) or `fma precise` (float only). No line: unstated, +// treated as exact (the translator's default). A cache that mixes rules is logged once, never refused. +enum MeshFma { mesh_fma_exact, mesh_fma_precise, mesh_fma_unstated, mesh_fma_rules }; +LONG mesh_fma_loaded[mesh_fma_rules]; +const char* const mesh_fma_names[mesh_fma_rules] = {"exact", "precise", "unstated"}; + +bool mesh_double_ops() +{ + static const bool ok = [] { + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + const HRESULT hr = device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)); + const bool doubles = SUCCEEDED(hr) && options.DoublePrecisionFloatShaderOps; + log("x2w-mesh DoublePrecisionFloatShaderOps %d (0x%08lx): `fma exact` translations %s", doubles ? 1 : 0, static_cast<unsigned long>(hr), + doubles ? "allowed" : "refused"); + return doubles; + }(); + return ok; +} + +// load_translation's stage hook (d3d12_draw.inl): 0 not a mesh manifest, 1 `stage mesh` with .ms.cso (and the +// optional .ps.cso) loaded, -1 a mesh manifest whose stage files cannot be read or whose fma rule cannot run here. +int load_mesh_stages(Translation& tr, const std::string& manifest) +{ + bool mesh = false; + unsigned threads = 0, vertices = 0, primitives = 0; + int fma = mesh_fma_unstated; + std::string fma_text; + for (std::size_t at = 0; at < manifest.size();) { + std::size_t end = manifest.find('\n', at); + if (end == std::string::npos) end = manifest.size(); + std::string line = manifest.substr(at, end - at); + if (!line.empty() && line.back() == '\r') line.pop_back(); + at = end + 1; + if (line == "stage mesh") mesh = true; + else if (line.compare(0, 4, "fma ") == 0) fma_text = line.substr(4), fma = fma_text == "exact" ? mesh_fma_exact : fma_text == "precise" ? mesh_fma_precise : -1; + else std::sscanf(line.c_str(), "ms %u %u %u", &threads, &vertices, &primitives); + } + if (!mesh) return 0; + if (fma < 0) { + log("x2w-mesh pipeline %016llx: translation failed (unknown fma rule \"%s\")", tr.key, fma_text.c_str()); + return -1; + } + if (fma != mesh_fma_precise && !mesh_double_ops()) { + log("x2w-mesh pipeline %016llx: translation failed (fma %s needs DoublePrecisionFloatShaderOps)", tr.key, mesh_fma_names[fma]); + return -1; + } + wchar_t path[MAX_PATH]; + if (!cache_path(path, L"", tr.key, L".ms.cso") || FAILED(D3DReadFileToBlob(path, &tr.ms))) { + log("x2w-mesh pipeline %016llx: translation failed (no readable .ms.cso)", tr.key); + return -1; + } + if (cache_path(path, L"", tr.key, L".ps.cso") && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES && FAILED(D3DReadFileToBlob(path, &tr.ps))) { + log("x2w-mesh pipeline %016llx: translation failed (.ps.cso present but unreadable)", tr.key); + return -1; + } + log("x2w-mesh pipeline %016llx: mesh stage %zu bytes (ms %u threads, %u vertices, %u primitives), pixel stage %s, fma %s", tr.key, + tr.ms->GetBufferSize(), threads, vertices, primitives, tr.ps ? "yes" : "none (depth-only)", mesh_fma_names[fma]); + InterlockedIncrement(&mesh_fma_loaded[fma]); + int rules = 0; + for (LONG& n : mesh_fma_loaded) rules += InterlockedCompareExchange(&n, 0, 0) != 0; + static LONG mixed; + if (rules > 1 && InterlockedExchange(&mixed, 1) == 0) + log("x2w-mesh shader cache mixes fma rules (from %016llx): exact %ld, precise %ld, unstated %ld loaded so far; positions may differ " + "between pipelines (not refused)", tr.key, mesh_fma_loaded[mesh_fma_exact], mesh_fma_loaded[mesh_fma_precise], mesh_fma_loaded[mesh_fma_unstated]); + return 1; +} + +struct MeshPso { + int state = 0; // 0 new, 3 compiling, 1 ready, 2 failed (never retried) + ID3D12PipelineState* pso = nullptr; +}; +struct MeshEntry { + volatile int state = 0; // 0 new, 3 loading, 1 ready, 2 failed (never retried), 4 no manifest (checked again after 5 s) + volatile ULONGLONG retry_at = 0; + Translation* tr = nullptr; + std::unordered_map<u64, MeshPso> psos; // by target formats, DSV format and fixed-function state + bool issued_once = false; + unsigned refusals_logged = 0; // bit per MeshSkip: its "call refused" line was written (mesh_lock) + volatile LONG uses = 0; // keyed calls since the last report (report_mesh_keys), counted without a lock + volatile LONG seen = 0; // 1 once the "first bound" line was written +}; +SRWLOCK mesh_lock = SRWLOCK_INIT; +CONDITION_VARIABLE mesh_loaded = CONDITION_VARIABLE_INIT; +std::unordered_map<u64, MeshEntry>& mesh_entries() { static std::unordered_map<u64, MeshEntry> m; return m; } // node-based: references stay valid + +// The entry of `key` in its final state for now (1, 2 or 4). One thread loads a key; others wait for that key only. +MeshEntry& loaded_mesh(u64 key) +{ + AcquireSRWLockExclusive(&mesh_lock); + MeshEntry& e = mesh_entries()[key]; + while (e.state == 3) SleepConditionVariableSRW(&mesh_loaded, &mesh_lock, INFINITE, 0); + if (e.state == 1 || e.state == 2 || (e.state == 4 && GetTickCount64() < e.retry_at)) { + ReleaseSRWLockExclusive(&mesh_lock); + return e; + } + const bool first = e.state == 0; + e.state = 3; + ReleaseSRWLockExclusive(&mesh_lock); + int state = 4; + Translation* tr = nullptr; + wchar_t path[MAX_PATH]; + if (cache_path(path, L"", key, L".txt") && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) { + tr = new Translation; + tr->key = key; + load_translation(*tr); + if (tr->state == 1 && tr->ms) { + state = 1; + } else { + log("x2w-mesh pipeline %016llx: translation failed (%s)", key, + tr->state == 1 ? "manifest has no `stage mesh`" : "manifest, stage files or root signature rejected"); + state = 2; + } + } else { + static LONG shown; + if (first && first_calls(shown, 1024)) log("x2w-mesh pipeline %016llx: no translation", key); + } + AcquireSRWLockExclusive(&mesh_lock); + // tr and retry_at before state: mesh_prepare reads a kept entry's state without mesh_lock. + e.tr = state == 1 ? tr : nullptr; + e.retry_at = state == 4 ? GetTickCount64() + 5000 : 0; + MemoryBarrier(); + e.state = state; + ReleaseSRWLockExclusive(&mesh_lock); + WakeAllConditionVariable(&mesh_loaded); + return e; // a failed Translation is kept (leaked) like draw translations: never retried +} + +// Once per key and reason (first 4096 lines PER REASON, so keys refused for one reason cannot use up the lines of +// another): "x2w-mesh pipeline K: call refused (<why>)", for the refusals that have no per-key line of their own +// (no targets, rtv variant, no PSO, translation taken, bind refused). "no translation" and "translation failed (...)" +// are written once per key by loaded_mesh / load_mesh_stages. +// A refused call of a key whose line is out pays no lock (a racy read of the bit: at worst the lock is taken once more). +bool mesh_refusal_logged(const MeshEntry& e, MeshSkip why) { return (e.refusals_logged & (1u << why)) != 0; } +void mesh_refusal_line(MeshEntry& e, u64 key, MeshSkip why, const char* detail) +{ + if (mesh_refusal_logged(e, why)) return; + AcquireSRWLockExclusive(&mesh_lock); + const bool first = (e.refusals_logged & (1u << why)) == 0; + e.refusals_logged |= 1u << why; + ReleaseSRWLockExclusive(&mesh_lock); + static LONG shown[mesh_skips]; + if (first && first_calls(shown[why], 4096)) log("x2w-mesh pipeline %016llx: call refused (%s)", key, detail); +} + +// ---- Coverage: which mesh keys are bound (board/msgs/210900_mesh) ---------------------------------------------- + +// Every mesh call with a keyed record, after its translation lookup (state: 1 ok, 2 fail, 4 missing). Counted in the +// key's entry without a lock (the entry map is node-based; report_mesh_keys collects the counts). +void mesh_note_use(MeshEntry& e, u64 key) +{ + InterlockedIncrement(&e.uses); + if (e.seen || InterlockedExchange(&e.seen, 1)) return; + static LONG shown; + if (first_calls(shown, 4096)) + log("x2w-mesh key %016llx first bound frame %ld (cache: %s)", key, frame_number, e.state == 1 ? "ok" : e.state == 2 ? "fail" : "missing"); +} + +// "x2w-mesh N frames: keys n distinct, calls c; top: key:calls ..." (up to 64 keys, 32 per line; log lines are 1536 bytes). +void report_mesh_keys(LONG frames) +{ + std::vector<std::pair<u64, LONG>> uses; + std::size_t seen = 0; + AcquireSRWLockShared(&mesh_lock); + for (auto& [key, e] : mesh_entries()) { + if (const LONG n = InterlockedExchange(&e.uses, 0)) uses.emplace_back(key, n); + if (e.seen) ++seen; + } + ReleaseSRWLockShared(&mesh_lock); + LONG calls = 0; + for (const auto& u : uses) calls += u.second; + std::sort(uses.begin(), uses.end(), [](const auto& x, const auto& y) { return x.second != y.second ? x.second > y.second : x.first < y.first; }); + const std::size_t top = uses.size() < 64 ? uses.size() : 64; + if (top <= 32) { + char line[1100]; + int n = 0; + for (std::size_t i = 0; i < top; ++i) n += std::snprintf(line + n, sizeof(line) - n, " %016llx:%ld", uses[i].first, uses[i].second); + log("x2w-mesh %ld frames: keys %zu distinct, calls %ld; top:%s (keys seen since start %zu)", frames, uses.size(), calls, top ? line : " none", seen); + return; + } + log("x2w-mesh %ld frames: keys %zu distinct, calls %ld; top: 64 keys on the next 2 lines (keys seen since start %zu)", frames, uses.size(), calls, seen); + for (std::size_t from = 0; from < top; from += 32) { + const std::size_t to = top < from + 32 ? top : from + 32; + char line[1100]; + int n = 0; + for (std::size_t i = from; i < to; ++i) n += std::snprintf(line + n, sizeof(line) - n, " %016llx:%ld", uses[i].first, uses[i].second); + log("x2w-mesh %ld frames top %zu-%zu:%s", frames, from + 1, to, line); + } +} + +// ---- Desktop pipeline --------------------------------------------------------------------------------------- + +// The fixed-function state of the mesh PSO: the default state (lead, 2026-11-24). Opaque blend, all channels +// written: translation_for's blend decode (bound.blend) reads slot-57 state at the vertex-record offsets, and mesh +// records keep their state 0x54 bytes later, so it is NOT used here. Depth-stencil only from a stream pipeline +// (never a slot-57 record), else off; cull none. The key covers all of it. +// LOCAL meshrt: X2W_MESH_STATE=1 puts the pipeline's own decoded state over that default: depth-stencil, rasterizer +// and masked blend from state block A in the mesh layout (renderstate's decode_draw_state / apply_draw_state, +// pipeline_state_decode.h) or the nearest slot 55 part. Unset (default): the default state as before, same PSO key. +// The state is per title pipeline (BoundPipeline), so two pipelines of one key with different state get two PSOs. +// *fallback (when not null) receives the default desc if the decoded state changed it, for a failed creation. +// LOCAL meshrt (X2W_MESH_DUMP_INPUTS, declared in d3d12_draw.inl): the first record's X, Y, Z in title memory, as +// the traced-frame mesh line reads it (d3d12_indirect.inl sets mesh_trace_record for this call). +bool mesh_dump_record_groups(std::uint32_t (&xyz)[3]) +{ + if (!mesh_trace_record || mesh_trace_stride < 12 || !x2w_local::readable(mesh_trace_record, 12)) return false; + std::memcpy(xyz, mesh_trace_record, 12); + return true; +} +bool mesh_cull_flip() +{ + static const bool flip = x2w_local::env_on("X2W_MESH_STATE_CULL_FLIP"); + return flip; +} +const x2w_pipeline_state::Switches& mesh_switches() +{ + static const x2w_pipeline_state::Switches s = [] { + x2w_pipeline_state::Switches v; + if (x2w_local::env_on("X2W_MESH_STATE")) v.depth = v.cull = v.blend = true; + // Without a rebuild: X2W_MESH_STATE_NOCULL=1 keeps the default rasterizer (cull none); + // X2W_MESH_STATE_CULL_FLIP=1 inverts the decoded front face (apply_draw_state's flip covers slot-55 patches only). + if (v.cull && x2w_local::env_on("X2W_MESH_STATE_NOCULL")) v.cull = false; + // X2W_DRAW_STATE_DEPTHCLIP=1: the decoded depth clip alone (also without X2W_MESH_STATE); cull includes it. + v.depthclip = draw_state::switches().depthclip; // parsed with the others: X2W_DRAW_STATE=0 turns it off too + if (v.depthclip) log("x2w-mesh X2W_DRAW_STATE_DEPTHCLIP=1: mesh PSOs take depth clip from the pipeline's rasterizer state"); + if (v.depth) + log("x2w-mesh X2W_MESH_STATE=1: mesh PSOs take depth-stencil, %sblend from the pipeline's state block%s", v.cull ? "rasterizer and " : "", + !v.cull ? " (X2W_MESH_STATE_NOCULL: rasterizer default)" : mesh_cull_flip() ? " (X2W_MESH_STATE_CULL_FLIP: front face inverted)" : ""); + return v; + }(); + return s; +} +LONG mesh_state_changed, mesh_state_fallback; // PSOs whose decoded state differs from the default; created with the default after a failure +void mesh_state_desc(const BoundPipeline& bound, const Pass& pass, D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, u64& key, + bool* decoded = nullptr, D3D12_GRAPHICS_PIPELINE_STATE_DESC* fallback = nullptr) +{ + const DXGI_FORMAT dsv_format = pass.dsv_format != DXGI_FORMAT_UNKNOWN ? pass.dsv_format : bound.dsv_format; + desc = {}; + for (auto& target : desc.BlendState.RenderTarget) + target = {FALSE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, + D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; + static const bool default_blend = x2w_local::env_on("X2W_DRAW_DEFAULT_BLEND"); + if (default_blend) + for (auto& target : desc.BlendState.RenderTarget) + target = {TRUE, FALSE, D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, + D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; + if (bound.has_depth_stencil) desc.DepthStencilState = bound.depth_stencil; + desc.SampleMask = ~0u; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.NumRenderTargets = pass.target_count; + for (UINT i = 0; i < pass.target_count; ++i) desc.RTVFormats[i] = pass.target_formats[i]; + desc.DSVFormat = dsv_format; + desc.SampleDesc.Count = 1; + const auto& s = mesh_switches(); + if (s.depth || s.cull || s.blend || s.depthclip) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC before = desc; + const bool changed = apply_draw_state(bound, pass, desc, s); + if (s.cull && mesh_cull_flip() && std::memcmp(&before.RasterizerState, &desc.RasterizerState, sizeof(desc.RasterizerState)) != 0) + desc.RasterizerState.FrontCounterClockwise = !desc.RasterizerState.FrontCounterClockwise; + if (decoded) *decoded = changed; + if (changed && fallback) *fallback = before; + } + key = pass.target_count; + for (UINT i = 0; i < pass.target_count; ++i) key = key * 131 + static_cast<u64>(pass.target_formats[i]); + key = fnv_bytes(&dsv_format, sizeof(dsv_format), key); + // Field by field: D3D12_DEPTH_STENCIL_DESC and D3D12_RENDER_TARGET_BLEND_DESC have padding after their UINT8 masks, + // and a struct copied from apply_draw_state's locals carries whatever was there, so hashing the bytes gave a new key + // for the same state. + const auto mix = [&key](u64 v) { key = fnv_bytes(&v, sizeof(v), key); }; + const auto& b = desc.BlendState; + mix(b.AlphaToCoverageEnable), mix(b.IndependentBlendEnable); + for (const auto& t : b.RenderTarget) { + mix(t.BlendEnable), mix(t.LogicOpEnable), mix(t.SrcBlend), mix(t.DestBlend), mix(t.BlendOp), mix(t.SrcBlendAlpha); + mix(t.DestBlendAlpha), mix(t.BlendOpAlpha), mix(t.LogicOp), mix(t.RenderTargetWriteMask); + } + const auto& d = desc.DepthStencilState; + mix(d.DepthEnable), mix(d.DepthWriteMask), mix(d.DepthFunc), mix(d.StencilEnable), mix(d.StencilReadMask), mix(d.StencilWriteMask); + for (const auto* f : {&d.FrontFace, &d.BackFace}) + mix(f->StencilFailOp), mix(f->StencilDepthFailOp), mix(f->StencilPassOp), mix(f->StencilFunc); + const auto& r = desc.RasterizerState; + mix(r.FillMode), mix(r.CullMode), mix(r.FrontCounterClockwise), mix(static_cast<u64>(static_cast<std::int64_t>(r.DepthBias))); + std::uint32_t bits; + std::memcpy(&bits, &r.DepthBiasClamp, 4), mix(bits); + std::memcpy(&bits, &r.SlopeScaledDepthBias, 4), mix(bits); + mix(r.DepthClipEnable), mix(r.MultisampleEnable), mix(r.AntialiasedLineEnable), mix(r.ForcedSampleCount), mix(r.ConservativeRaster); +} + +template <D3D12_PIPELINE_STATE_SUBOBJECT_TYPE Type, class Value> +struct alignas(void*) MeshSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = Type; + Value value{}; +}; +struct MeshStream { + MeshSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, ID3D12RootSignature*> root; + MeshSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE> ms; + MeshSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE> ps; + MeshSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, D3D12_BLEND_DESC> blend; + MeshSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, UINT> sample_mask; + MeshSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, D3D12_RASTERIZER_DESC> rasterizer; + MeshSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_DEPTH_STENCIL_DESC> depth_stencil; + MeshSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT> dsv_format; + MeshSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, D3D12_RT_FORMAT_ARRAY> rtv_formats; + MeshSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC> sample; +}; + +ID3D12PipelineState* create_mesh_pso(const Translation& tr, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& d, HRESULT* result) +{ + static ID3D12Device2* device2 = [] { + ID3D12Device2* d2 = nullptr; + device_of(the_device)->QueryInterface(IID_PPV_ARGS(&d2)); + return d2; + }(); + *result = E_NOINTERFACE; + if (!device2) return nullptr; + MeshStream s; + s.root.value = tr.root; + s.ms.value = {tr.ms->GetBufferPointer(), tr.ms->GetBufferSize()}; + if (tr.ps) s.ps.value = {tr.ps->GetBufferPointer(), tr.ps->GetBufferSize()}; + s.blend.value = d.BlendState; + s.sample_mask.value = d.SampleMask; + s.rasterizer.value = d.RasterizerState; + s.depth_stencil.value = d.DepthStencilState; + s.dsv_format.value = d.DSVFormat; + s.rtv_formats.value.NumRenderTargets = d.NumRenderTargets; + for (UINT i = 0; i < 8; ++i) s.rtv_formats.value.RTFormats[i] = d.RTVFormats[i]; + s.sample.value = d.SampleDesc; + const D3D12_PIPELINE_STATE_STREAM_DESC stream{sizeof(s), &s}; + ID3D12PipelineState* pso = nullptr; + *result = device2->CreatePipelineState(&stream, IID_PPV_ARGS(&pso)); + return SUCCEEDED(*result) ? pso : nullptr; +} + +void mesh_pso_compile(const Translation& tr, MeshPso& slot, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, + const D3D12_GRAPHICS_PIPELINE_STATE_DESC& fallback, bool decoded, UINT target_count, DXGI_FORMAT format0, bool async) +{ + LARGE_INTEGER t0, t1, f; + QueryPerformanceCounter(&t0); + HRESULT hr = E_FAIL; + ID3D12PipelineState* pso = create_mesh_pso(tr, desc, &hr); + QueryPerformanceCounter(&t1); + QueryPerformanceFrequency(&f); + const auto& d = desc.DepthStencilState; + const auto& ms = mesh_switches(); + log("x2w-mesh desktop pipeline for %016llx: %u targets (format %d), dsv %d, depth %d, pixel stage %s -> 0x%08lx; state %s: depth func %d " + "write %d stencil %d, cull %d ccw %d depthclip %d, blend rt0 %d mask 0x%x; compiled in %lld ms%s", tr.key, target_count, static_cast<int>(format0), + static_cast<int>(desc.DSVFormat), d.DepthEnable ? 1 : 0, tr.ps ? "yes" : "none", static_cast<unsigned long>(hr), + !decoded ? "default" : (ms.depth || ms.cull || ms.blend) ? "decoded (X2W_MESH_STATE)" : "default + depth clip decoded (X2W_DRAW_STATE_DEPTHCLIP)", + d.DepthFunc, d.DepthWriteMask, d.StencilEnable, desc.RasterizerState.CullMode, desc.RasterizerState.FrontCounterClockwise, + desc.RasterizerState.DepthClipEnable, desc.BlendState.RenderTarget[0].BlendEnable, desc.BlendState.RenderTarget[0].RenderTargetWriteMask, + static_cast<long long>((t1.QuadPart - t0.QuadPart) * 1000 / f.QuadPart), async ? " (X2W_MESH_ASYNC worker)" : ""); + if (decoded) InterlockedIncrement(&mesh_state_changed); + if (!pso && decoded) { + // The decoded state was refused by the runtime: the default state instead (NOT exercised by a test). + pso = create_mesh_pso(tr, fallback, &hr); + InterlockedIncrement(&mesh_state_fallback); + log("x2w-mesh desktop pipeline for %016llx: decoded state refused, default state -> 0x%08lx", tr.key, static_cast<unsigned long>(hr)); + } + check_device("translated mesh CreatePipelineState", 0); + AcquireSRWLockExclusive(&mesh_lock); + slot.pso = pso; + slot.state = pso ? 1 : 2; + ReleaseSRWLockExclusive(&mesh_lock); + WakeAllConditionVariable(&mesh_loaded); +} + +// X2W_MESH_ASYNC=1: a call whose PSO is not compiled yet hands the compile to a thread-pool worker and is skipped +// ("compiling"); the recording thread never compiles and never waits for a compile. Default off: compile in the call. +bool mesh_async() +{ + static const bool on = [] { + // Also on with stall's X2W_CX_ASYNC=1 (compute and draws), unless X2W_MESH_ASYNC_OFF=1. + const bool v = x2w_local::env_on("X2W_MESH_ASYNC") || (x2w_local::env_on("X2W_CX_ASYNC") && !x2w_local::env_on("X2W_MESH_ASYNC_OFF")); + if (v) log("x2w-mesh X2W_MESH_ASYNC=1: mesh PSOs compile on a worker; calls are skipped until their PSO is ready"); + return v; + }(); + return on; +} +struct MeshPsoJob { + const Translation* tr; + MeshPso* slot; + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc, fallback; + bool decoded; + UINT target_count; + DXGI_FORMAT format0; +}; +DWORD WINAPI mesh_pso_worker(void* p) +{ + MeshPsoJob* job = static_cast<MeshPsoJob*>(p); + mesh_pso_compile(*job->tr, *job->slot, job->desc, job->fallback, job->decoded, job->target_count, job->format0, true); + delete job; + return 0; +} + +// The PSO for (entry, translation, state of this call), compiled once per key without draw_lock (failures are kept). +// tr is the entry's translation or its RTV variant (translation_for_targets). With X2W_MESH_ASYNC, null + *compiling +// while a worker compiles it. +ID3D12PipelineState* mesh_pso(MeshEntry& e, const Translation& tr, const BoundPipeline& bound, const Pass& pass, bool* compiling = nullptr) +{ + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc, fallback; + u64 key = 0; + bool decoded = false; + mesh_state_desc(bound, pass, desc, key, &decoded, &fallback); + key = fnv_bytes(&tr.key, sizeof(tr.key), key); // a variant's PSOs never share a slot with the base's + const bool async = mesh_async(); + AcquireSRWLockExclusive(&mesh_lock); + MeshPso& slot = e.psos[key]; + if (async && slot.state == 3) { + ReleaseSRWLockExclusive(&mesh_lock); + if (compiling) *compiling = true; + return nullptr; + } + while (slot.state == 3) SleepConditionVariableSRW(&mesh_loaded, &mesh_lock, INFINITE, 0); + if (slot.state == 1 || slot.state == 2) { + ID3D12PipelineState* pso = slot.pso; + ReleaseSRWLockExclusive(&mesh_lock); + return pso; + } + slot.state = 3; + ReleaseSRWLockExclusive(&mesh_lock); + const DXGI_FORMAT format0 = pass.target_count ? pass.target_formats[0] : DXGI_FORMAT_UNKNOWN; + if (async) { + auto* job = new MeshPsoJob{&tr, &slot, desc, fallback, decoded, pass.target_count, format0}; + if (QueueUserWorkItem(mesh_pso_worker, job, WT_EXECUTELONGFUNCTION)) { + if (compiling) *compiling = true; + return nullptr; + } + delete job; // no worker: compile here + } + mesh_pso_compile(tr, slot, desc, fallback, decoded, pass.target_count, format0, false); + AcquireSRWLockShared(&mesh_lock); + ID3D12PipelineState* pso = slot.pso; + ReleaseSRWLockShared(&mesh_lock); + return pso; +} + +// ---- Per call -------------------------------------------------------------------------------------------------- + +// Bound title pipeline -> its BoundPipeline (translation_for) with the mesh translation attached. +struct MeshBinding { + MeshRecordKey key; + bool mesh = false; + BoundPipeline* bound = nullptr; + Translation* attached = nullptr; + MeshEntry* entry = nullptr; // the key's entry once it is final (ready or failed): no loaded_mesh per call + u64 pso_signature = 0; // mesh_pass_signature of the pass pso was made for + ID3D12PipelineState* pso = nullptr; // the last PSO of this pipeline: no state desc, hash or mesh_lock per call + Translation* pso_tr = nullptr; // the translation pso was made from (the entry's, or its RTV variant) + u64 variant_wait_signature = 0; // RTV variant not ready for this pass signature: no draw_lock lookup ... + ULONGLONG variant_wait_until = 0; // ... until this tick (1 s) +}; + +// Everything of the pass that mesh_state_desc / apply_draw_state read: targets, DSV format, read-only DSV, rect +// topology. Equal signatures give the same PSO key for the same title pipeline (its BoundPipeline state is fixed). +u64 mesh_pass_signature(const Pass& pass) +{ + u64 s = 0x9e3779b97f4a7c15ull ^ pass.target_count; + for (UINT i = 0; i < pass.target_count; ++i) s = s * 1099511628211ull + static_cast<u64>(pass.target_formats[i]); + s = s * 1099511628211ull + static_cast<u64>(pass.dsv_format); + s = s * 1099511628211ull + (pass.read_depth_plane ? 1u : 0u) + (pass.read_stencil_plane ? 4u : 0u) + (pass.topology == 0x11 ? 2u : 0u); + // renderstate 7c0d4cae: apply_draw_state keeps depth / stencil off on a depth target no forwarded slot 51 clear + // has initialised, so whether the bound target is cleared is part of the PSO (one shared-lock lookup, X2W_MESH_STATE only). + if (mesh_switches().depth && pass.dsv_resource && depth_target_cleared(pass.dsv_resource)) s = s * 1099511628211ull + 4u; + return s | 1; // never 0 (0 = no PSO cached) +} + +// LOCAL meshrt: stand-in CPU per mesh call (report_mesh): mesh_prepare and the bind through draw_translated (which +// includes its draw_lock wait), QueryPerformanceCounter ticks. +volatile LONG64 mesh_prepare_ticks, mesh_bind_ticks, mesh_bind_calls; +LONG64 mesh_now() +{ + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return t.QuadPart; +} +std::unordered_map<const Wrapper*, MeshBinding>& mesh_bindings() { static std::unordered_map<const Wrapper*, MeshBinding> m; return m; } + +bool mesh_tier_ok() +{ + static const bool ok = [] { + D3D12_FEATURE_DATA_D3D12_OPTIONS7 options7{}; + const HRESULT hr7 = device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &options7, sizeof(options7)); + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_5}; + const HRESULT hrm = device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model)); + const bool tier = SUCCEEDED(hr7) && options7.MeshShaderTier >= D3D12_MESH_SHADER_TIER_1; + const bool sm = SUCCEEDED(hrm) && model.HighestShaderModel >= D3D_SHADER_MODEL_6_5; + log("x2w-mesh X2W_MESH=1: MeshShaderTier %d (0x%08lx), highest shader model 0x%x (0x%08lx) -> mesh path %s", + SUCCEEDED(hr7) ? static_cast<int>(options7.MeshShaderTier) : -1, static_cast<unsigned long>(hr7), + SUCCEEDED(hrm) ? static_cast<unsigned>(model.HighestShaderModel) : 0u, static_cast<unsigned long>(hrm), + tier && sm ? "ON" : "OFF (needs tier 1 and shader model 6.5)"); + return tier && sm; + }(); + return ok; +} + +// What mesh_prepare found for the call indirect is about to stage on this thread. +struct MeshReady { + Wrapper* list = nullptr; + Translation* tr = nullptr; + ID3D12PipelineState* pso = nullptr; + MeshEntry* entry = nullptr; +}; +thread_local MeshReady mesh_ready; +thread_local bool mesh_binding_now; // inside draw_translated for the mesh call + +// LOCAL meshrt: in a traced frame (trace_frame_active), every mesh call takes part like an ordinary draw: its render +// targets and depth target are noted for the end-of-frame read-back (X2W_D3D12_TRACE_TARGETS snapshots) and one +// "x2w-frame mesh" line gives key, every target with size and format, depth target, the list's first viewport and +// scissor, the decoded depth state of the PSO, the indirect record's first words in title memory at record time (the +// GPU may write them later) and, when not drawn, the skip reason. Nothing of this runs outside a traced frame. +thread_local u64 mesh_trace_key; // the binding's key for this call (0: none yet) +thread_local const BoundPipeline* mesh_trace_bound; +thread_local LONG mesh_trace_query = -1; // this call's pipeline statistics slot, or -1 + +// LOCAL meshrt: pipeline statistics of the traced frame's issued mesh calls. One query per call (BeginQuery before the +// ExecuteIndirect, EndQuery + ResolveQueryData into a readback buffer after it), PIPELINE_STATISTICS1 when the device +// reports MeshShaderPipelineStatsSupported (MS invocations / primitives), else PIPELINE_STATISTICS (no MS counts). The +// results are read 8 presents after the traced frame ends (no GPU wait; mesh_stats_present), or by the fixture export. +// "x2w-frame mesh stats #slot key K: ..." per slot. Capacity 4096 calls per traced frame; later calls get no query. +struct MeshStats { + ID3D12QueryHeap* heap = nullptr; + ID3D12Resource* readback = nullptr; + bool v1 = false; // PIPELINE_STATISTICS1 + bool failed = false; + UINT capacity = 0; +}; +SRWLOCK mesh_stats_lock = SRWLOCK_INIT; +MeshStats mesh_stats; +LONG mesh_stats_next; // slots handed out since the last report +LONG mesh_stats_due; // frame at which to report (0: none pending) +u64 mesh_stats_keys[4096]; +bool mesh_stats_ready() +{ + AcquireSRWLockShared(&mesh_stats_lock); + const bool ready = mesh_stats.heap != nullptr, failed = mesh_stats.failed; + ReleaseSRWLockShared(&mesh_stats_lock); + if (ready || failed) return ready; + AcquireSRWLockExclusive(&mesh_stats_lock); + if (!mesh_stats.heap && !mesh_stats.failed) { + ID3D12Device* device = device_of(the_device); + D3D12_FEATURE_DATA_D3D12_OPTIONS9 options9{}; + mesh_stats.v1 = SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS9, &options9, sizeof(options9))) && + options9.MeshShaderPipelineStatsSupported; + mesh_stats.capacity = 4096; + const D3D12_QUERY_HEAP_DESC desc{mesh_stats.v1 ? D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS1 : D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, + mesh_stats.capacity, 0}; + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, u64{mesh_stats.capacity} * sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS1), + 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + const HRESULT hq = device->CreateQueryHeap(&desc, IID_PPV_ARGS(&mesh_stats.heap)); + const HRESULT hb = SUCCEEDED(hq) ? device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&mesh_stats.readback)) : hq; + if (FAILED(hb)) { + if (mesh_stats.heap) mesh_stats.heap->Release(); + mesh_stats.heap = nullptr; + mesh_stats.failed = true; + } + log("x2w-mesh pipeline statistics for traced mesh calls: %s (MeshShaderPipelineStatsSupported %d) -> 0x%08lx / 0x%08lx", + mesh_stats.failed ? "unavailable" : mesh_stats.v1 ? "PIPELINE_STATISTICS1" : "PIPELINE_STATISTICS (no MS counts)", mesh_stats.v1 ? 1 : 0, + static_cast<unsigned long>(hq), static_cast<unsigned long>(hb)); + } + const bool made = mesh_stats.heap != nullptr; + ReleaseSRWLockExclusive(&mesh_stats_lock); + return made; +} +D3D12_QUERY_TYPE mesh_stats_type() { return mesh_stats.v1 ? D3D12_QUERY_TYPE_PIPELINE_STATISTICS1 : D3D12_QUERY_TYPE_PIPELINE_STATISTICS; } +UINT mesh_stats_size() { return mesh_stats.v1 ? sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS1) : sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS); } +// Prints every slot's numbers and frees the slots. The GPU work of those calls must be complete. +void mesh_stats_report() +{ + const LONG used = InterlockedExchange(&mesh_stats_next, 0); + InterlockedExchange(&mesh_stats_due, 0); + if (!mesh_stats.readback || used <= 0) return; + const LONG count = used < static_cast<LONG>(mesh_stats.capacity) ? used : static_cast<LONG>(mesh_stats.capacity); + void* mapped = nullptr; + const D3D12_RANGE range{0, static_cast<SIZE_T>(count) * mesh_stats_size()}; + if (FAILED(mesh_stats.readback->Map(0, &range, &mapped))) return; + std::uint64_t sums[5] = {}, zero_ps = 0, zero_clip = 0; + for (LONG i = 0; i < count; ++i) { + D3D12_QUERY_DATA_PIPELINE_STATISTICS1 s{}; + std::memcpy(&s, static_cast<const unsigned char*>(mapped) + std::size_t(i) * mesh_stats_size(), mesh_stats_size()); + if (mesh_stats.v1) + log("x2w-frame mesh stats #%ld key %016llx: MS invocations %llu primitives %llu, clipper invocations %llu primitives %llu, PS invocations %llu", + i, static_cast<unsigned long long>(mesh_stats_keys[i]), s.MSInvocations, s.MSPrimitives, s.CInvocations, s.CPrimitives, s.PSInvocations); + else + log("x2w-frame mesh stats #%ld key %016llx: (no MS counts) clipper invocations %llu primitives %llu, PS invocations %llu", + i, static_cast<unsigned long long>(mesh_stats_keys[i]), s.CInvocations, s.CPrimitives, s.PSInvocations); + const std::uint64_t v[5] = {s.MSInvocations, s.MSPrimitives, s.CInvocations, s.CPrimitives, s.PSInvocations}; + for (int k = 0; k < 5; ++k) sums[k] += v[k]; + zero_clip += s.CPrimitives == 0; + zero_ps += s.PSInvocations == 0; + } + const D3D12_RANGE none{0, 0}; + mesh_stats.readback->Unmap(0, &none); + log("x2w-frame mesh stats total over %ld calls (%ld asked): MS invocations %llu primitives %llu, clipper invocations %llu primitives %llu, " + "PS invocations %llu; calls with 0 clipper primitives %llu, with 0 PS invocations %llu", count, used, sums[0], sums[1], sums[2], sums[3], + sums[4], zero_clip, zero_ps); +} +// queue_present, every present: the traced frame has ended (trace_frame_active 0) -> report 8 presents later. +void mesh_stats_present(LONG frame) +{ + if (trace_frame_active || !mesh_stats_next) return; + const LONG due = mesh_stats_due; + if (!due) InterlockedCompareExchange(&mesh_stats_due, frame + 8, 0); + else if (frame >= due) mesh_stats_report(); +} +extern "C" __declspec(dllexport) void x2w_d3d12_mesh_stats_report() { mesh_stats_report(); } // fixtures, after their fence + +// LOCAL meshrt: X2W_MESH_STATS_FRAMES=<n> (default 0: off). Outside the traced frame, every issued mesh call gets a +// pipeline statistics query (its own query heap, 16 frame slots of 2048 calls) until n frames have been COUNTED: a frame +// counts when at least one of its mesh calls had a record with X > 0 in title memory at record time ("with groups" on +// the lines: X, Y, Z all > 0). 8 presents +// after a frame ends its results are read (no GPU wait); a counted frame prints one line per target set (render target +// formats / sizes + depth format / size; the resources at the end of the line) with the call count, the calls with +// groups and the summed statistics, then a frame line; a frame that does not count prints one "not counted" line (the +// first 8 only). The traced frame keeps its per-call queries (mesh_stats) and is not part of this. +struct MeshFrameSlot { + LONG frame = -1; // the frame id collected in this slot (-1: free) + LONG used = 0; // calls handed a query + LONG groups = 0; // calls with a record with groups (X, Y, Z > 0 at record time) + LONG xpos = 0; // calls with a record with X > 0 at record time: the frame counts when > 0 + LONG due = 0; // present count at which to read + bool closed = false; // the frame has ended (due is set) +}; +constexpr UINT mesh_fs_slots = 16, mesh_fs_calls = 2048; +struct MeshFrameCall { + u64 set = 0; // target-set hash + bool groups = false; // the record had X, Y, Z > 0 at record time +}; +SRWLOCK mesh_fs_lock = SRWLOCK_INIT; +ID3D12QueryHeap* mesh_fs_heap; +ID3D12Resource* mesh_fs_readback; +bool mesh_fs_failed; +MeshFrameSlot mesh_fs_slot[mesh_fs_slots]; +std::vector<MeshFrameCall>& mesh_fs_calls_of() { static std::vector<MeshFrameCall> v(mesh_fs_slots * mesh_fs_calls); return v; } +std::map<u64, std::string>& mesh_fs_sets() { static std::map<u64, std::string> m; return m; } // under mesh_fs_lock +LONG mesh_fs_current; // the frame id being collected +LONG mesh_fs_presents; // presents seen +LONG mesh_fs_counted; // frames counted so far +LONG mesh_fs_reported; // counted frames reported +LONG mesh_fs_skipped_lines; +LONG mesh_fs_wanted() +{ + static const LONG n = [] { + char v[16]{}; + const LONG k = GetEnvironmentVariableA("X2W_MESH_STATS_FRAMES", v, sizeof(v)) ? std::atol(v) : 0; + if (k > 0) log("x2w-mesh X2W_MESH_STATS_FRAMES=%ld: mesh calls carry statistics queries until %ld frames with groups are counted", k, k); + return k > 0 ? k : 0; + }(); + return n; +} +bool mesh_fs_collecting() { return mesh_fs_wanted() && mesh_fs_counted < mesh_fs_wanted() && !mesh_fs_failed; } +bool mesh_fs_ready() +{ + if (!mesh_stats_ready()) return false; // the query type (v1 or not) is chosen there + AcquireSRWLockExclusive(&mesh_fs_lock); + if (!mesh_fs_heap && !mesh_fs_failed) { + ID3D12Device* device = device_of(the_device); + const UINT count = mesh_fs_slots * mesh_fs_calls; + const D3D12_QUERY_HEAP_DESC desc{mesh_stats.v1 ? D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS1 : D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, count, 0}; + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, u64{count} * sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS1), 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + const HRESULT hq = device->CreateQueryHeap(&desc, IID_PPV_ARGS(&mesh_fs_heap)); + const HRESULT hb = SUCCEEDED(hq) ? device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&mesh_fs_readback)) : hq; + if (FAILED(hb)) { + if (mesh_fs_heap) mesh_fs_heap->Release(); + mesh_fs_heap = nullptr; + mesh_fs_failed = true; + } + mesh_fs_calls_of(); + mesh_fs_slot[0].frame = mesh_fs_current; + log("x2w-mesh X2W_MESH_STATS_FRAMES query heap (%u queries) -> 0x%08lx / 0x%08lx", count, static_cast<unsigned long>(hq), + static_cast<unsigned long>(hb)); + } + const bool made = mesh_fs_heap != nullptr; + ReleaseSRWLockExclusive(&mesh_fs_lock); + return made; +} +// The target set of this call: hash, and its text the first time it is seen. +u64 mesh_fs_set(const Pass& pass) +{ + u64 h = fnv_bytes(&pass.target_count, sizeof(pass.target_count), 1469598103934665603ull); + for (UINT i = 0; i < pass.target_count; ++i) h = fnv_bytes(&pass.targets[i], sizeof(pass.targets[i]), h); + h = fnv_bytes(&pass.dsv_resource, sizeof(pass.dsv_resource), h); + AcquireSRWLockShared(&mesh_fs_lock); + const bool known = mesh_fs_sets().count(h) != 0; + ReleaseSRWLockShared(&mesh_fs_lock); + if (known) return h; + char text[600]; + int n = std::snprintf(text, sizeof(text), "targets %u", pass.target_count); + std::string res = "; resources"; + char part[64]; + for (UINT i = 0; i < pass.target_count && n > 0 && n < 480; ++i) { + const D3D12_RESOURCE_DESC rd = pass.targets[i] ? pass.targets[i]->GetDesc() : D3D12_RESOURCE_DESC{}; + n += std::snprintf(text + n, sizeof(text) - n, " [fmt %d %llux%u]", static_cast<int>(pass.target_formats[i]), + static_cast<unsigned long long>(rd.Width), rd.Height); + std::snprintf(part, sizeof(part), " rt%u %p", i, static_cast<void*>(pass.targets[i])); + res += part; + } + if (pass.dsv_resource && n > 0 && n < 540) { + const D3D12_RESOURCE_DESC dd = pass.dsv_resource->GetDesc(); + std::snprintf(text + n, sizeof(text) - n, " dsv fmt %d %llux%u", static_cast<int>(pass.dsv_format), static_cast<unsigned long long>(dd.Width), + dd.Height); + std::snprintf(part, sizeof(part), " dsv %p", static_cast<void*>(pass.dsv_resource)); + res += part; + } else if (n > 0 && n < 540) { + std::snprintf(text + n, sizeof(text) - n, " dsv none"); + } + AcquireSRWLockExclusive(&mesh_fs_lock); + mesh_fs_sets().emplace(h, std::string(text) + '\x1f' + res); + ReleaseSRWLockExclusive(&mesh_fs_lock); + return h; +} +// mesh_hook: a query index for this call, or -1. The current frame's slot. The claim holds mesh_fs_lock shared, so +// it cannot straddle a present's close (exclusive) or a slot's release; the counters are interlocked for concurrent +// recording threads. +LONG mesh_fs_begin(const Pass& pass, bool groups, bool xpos) +{ + if (!mesh_fs_collecting() || !mesh_fs_ready()) return -1; + const u64 set = mesh_fs_set(pass); // takes mesh_fs_lock itself: before the claim + AcquireSRWLockShared(&mesh_fs_lock); + const LONG frame = mesh_fs_current; + const UINT s = static_cast<UINT>(frame) % mesh_fs_slots; + MeshFrameSlot& slot = mesh_fs_slot[s]; + LONG i = -1; + if (slot.frame == frame && !slot.closed) { // else: the slot is still being read, or collection has stopped + i = InterlockedIncrement(&slot.used) - 1; + if (i < static_cast<LONG>(mesh_fs_calls)) { + if (groups) InterlockedIncrement(&slot.groups); + if (xpos) InterlockedIncrement(&slot.xpos); + MeshFrameCall& call = mesh_fs_calls_of()[s * mesh_fs_calls + static_cast<UINT>(i)]; + call.set = set; + call.groups = groups; + } else { + i = -1; + } + } + ReleaseSRWLockShared(&mesh_fs_lock); + return i < 0 ? -1 : static_cast<LONG>(s * mesh_fs_calls) + i; +} +void mesh_fs_read(UINT s) +{ + MeshFrameSlot& slot = mesh_fs_slot[s]; + const LONG used = slot.used < static_cast<LONG>(mesh_fs_calls) ? slot.used : static_cast<LONG>(mesh_fs_calls); + const bool counted = slot.xpos > 0; + if (counted && used > 0 && mesh_fs_readback) { + struct Sum { + LONG calls = 0, groups = 0; + std::uint64_t v[5] = {}; + }; + std::map<u64, Sum> sums; + Sum all; + void* mapped = nullptr; + const SIZE_T base = SIZE_T{s} * mesh_fs_calls * mesh_stats_size(); + const D3D12_RANGE range{base, base + static_cast<SIZE_T>(used) * mesh_stats_size()}; + if (SUCCEEDED(mesh_fs_readback->Map(0, &range, &mapped))) { + for (LONG i = 0; i < used; ++i) { + D3D12_QUERY_DATA_PIPELINE_STATISTICS1 q{}; + std::memcpy(&q, static_cast<const unsigned char*>(mapped) + base + std::size_t(i) * mesh_stats_size(), mesh_stats_size()); + const MeshFrameCall& call = mesh_fs_calls_of()[s * mesh_fs_calls + static_cast<UINT>(i)]; + const std::uint64_t v[5] = {q.MSInvocations, q.MSPrimitives, q.CInvocations, q.CPrimitives, q.PSInvocations}; + for (Sum* sum : {&sums[call.set], &all}) { + ++sum->calls; + sum->groups += call.groups; + for (int k = 0; k < 5; ++k) sum->v[k] += v[k]; + } + } + const D3D12_RANGE none{0, 0}; + mesh_fs_readback->Unmap(0, &none); + } + const LONG number = InterlockedIncrement(&mesh_fs_reported); + for (const auto& [set, sum] : sums) { + AcquireSRWLockShared(&mesh_fs_lock); + const auto found = mesh_fs_sets().find(set); + const std::string text = found == mesh_fs_sets().end() ? std::string("?\x1f") : found->second; + ReleaseSRWLockShared(&mesh_fs_lock); + const std::size_t cut = text.find('\x1f'); + if (mesh_stats.v1) + log("x2w-mesh stats frame %ld set %s: calls %ld (%ld with groups), MS invocations %llu primitives %llu, clipper invocations %llu " + "primitives %llu, PS invocations %llu%s", slot.frame, text.substr(0, cut).c_str(), sum.calls, sum.groups, sum.v[0], sum.v[1], + sum.v[2], sum.v[3], sum.v[4], text.substr(cut + 1).c_str()); + else + log("x2w-mesh stats frame %ld set %s: calls %ld (%ld with groups), (no MS counts) clipper invocations %llu primitives %llu, PS " + "invocations %llu%s", slot.frame, text.substr(0, cut).c_str(), sum.calls, sum.groups, sum.v[2], sum.v[3], sum.v[4], + text.substr(cut + 1).c_str()); + } + log("x2w-mesh stats frames total %ld of %ld frames (frame %ld): %zu target sets, calls %ld (%ld with groups%s), MS invocations %llu " + "primitives %llu, clipper invocations %llu primitives %llu, PS invocations %llu", number, mesh_fs_wanted(), slot.frame, sums.size(), + all.calls, all.groups, slot.used > static_cast<LONG>(mesh_fs_calls) ? "; calls past 2048 had no query" : "", all.v[0], all.v[1], all.v[2], + all.v[3], all.v[4]); + } else if (first_calls(mesh_fs_skipped_lines, 8)) { + log("x2w-mesh stats frame %ld not counted (no record with X > 0 at record time; %ld mesh calls)", slot.frame, slot.used); + } + AcquireSRWLockExclusive(&mesh_fs_lock); // the release: mesh_fs_close may reuse the slot for a later frame + slot.used = slot.groups = slot.xpos = 0; + slot.due = 0; + slot.closed = false; + slot.frame = -1; + ReleaseSRWLockExclusive(&mesh_fs_lock); +} +// Ends the frame being collected: it counts if a call had a record with X > 0; its results are read `delay` presents +// later. +void mesh_fs_close(LONG delay) +{ + AcquireSRWLockExclusive(&mesh_fs_lock); + const LONG frame = mesh_fs_current; + MeshFrameSlot& slot = mesh_fs_slot[static_cast<UINT>(frame) % mesh_fs_slots]; + if (slot.frame == frame) { + if (slot.xpos > 0) ++mesh_fs_counted; + slot.due = mesh_fs_presents + delay; + slot.closed = true; + } + mesh_fs_current = frame + 1; + MeshFrameSlot& next = mesh_fs_slot[static_cast<UINT>(frame + 1) % mesh_fs_slots]; + if (next.frame == -1 && mesh_fs_counted < mesh_fs_wanted()) next.frame = frame + 1; + ReleaseSRWLockExclusive(&mesh_fs_lock); +} +void mesh_fs_present() +{ + if (!mesh_fs_wanted() || !mesh_fs_heap) return; + const LONG now = InterlockedIncrement(&mesh_fs_presents); + mesh_fs_close(8); + for (UINT s = 0; s < mesh_fs_slots; ++s) + if (mesh_fs_slot[s].frame >= 0 && mesh_fs_slot[s].closed && now >= mesh_fs_slot[s].due) mesh_fs_read(s); +} +// Fixtures (after their fence): ends the current frame and reads every closed slot now. +extern "C" __declspec(dllexport) void x2w_d3d12_mesh_frame_stats_report() +{ + if (!mesh_fs_heap) return; + mesh_fs_close(0); + for (UINT s = 0; s < mesh_fs_slots; ++s) + if (mesh_fs_slot[s].frame >= 0 && mesh_fs_slot[s].closed) mesh_fs_read(s); +} +// Fixtures: what queue_present does for X2W_MESH_STATS_FRAMES (the fixture has no swap chain present). +extern "C" __declspec(dllexport) void x2w_d3d12_mesh_frame_stats_present() { mesh_fs_present(); } +void mesh_trace_call(Wrapper* self, bool drawn, const Translation* tr, const char* why) +{ + const Pass& pass = pass_of(self); + for (UINT i = 0; i < pass.target_count; ++i) note_traced_target(self, pass.targets[i], drawn); + if (pass.dsv_resource) + note_traced_target(self, pass.dsv_resource, drawn && !pass.dsv_read_only, + pass.dsv_read_only ? D3D12_RESOURCE_STATE_DEPTH_READ : D3D12_RESOURCE_STATE_DEPTH_WRITE); + char text[900]; + int n = 0; + const auto add = [&](const char* format, auto... args) { + if (n >= 0 && n < static_cast<int>(sizeof(text))) n += std::snprintf(text + n, sizeof(text) - n, format, args...); + }; + add("x2w-frame mesh %s key %016llx", drawn ? "drawn" : "NOT drawn", static_cast<unsigned long long>(mesh_trace_key)); + if (tr && tr->key != mesh_trace_key) add(" variant %016llx", static_cast<unsigned long long>(tr->key)); + add(" targets %u", pass.target_count); + for (UINT i = 0; i < pass.target_count; ++i) { + const D3D12_RESOURCE_DESC rd = pass.targets[i] ? pass.targets[i]->GetDesc() : D3D12_RESOURCE_DESC{}; + add(" [%u %p %llux%u fmt %d]", i, static_cast<void*>(pass.targets[i]), static_cast<unsigned long long>(rd.Width), rd.Height, + static_cast<int>(pass.target_formats[i])); + } + add(" dsv %p fmt %d%s", static_cast<void*>(pass.dsv_resource), static_cast<int>(pass.dsv_format), pass.dsv_read_only ? " read-only" : ""); + if (pass.dsv_resource) { + DepthClearValue clear; + const D3D12_RESOURCE_DESC dd = pass.dsv_resource->GetDesc(); + add(" (%llux%u res fmt %d", static_cast<unsigned long long>(dd.Width), dd.Height, static_cast<int>(dd.Format)); + if (last_depth_clear(pass.dsv_resource, &clear)) + add(", last clear depth %g stencil %u flags 0x%x frame %ld)", clear.depth, clear.stencil, clear.flags, clear.frame); + else + add(", no forwarded clear)"); + } + if (mesh_trace_query >= 0) add(" query #%ld", mesh_trace_query); + if (pass.viewport_set) + add(" viewport %.1f %.1f %.1f %.1f depth %.2f-%.2f", pass.viewport0.TopLeftX, pass.viewport0.TopLeftY, pass.viewport0.Width, + pass.viewport0.Height, pass.viewport0.MinDepth, pass.viewport0.MaxDepth); + else + add(" viewport none"); + if (pass.scissor_set) + add(" scissor %ld %ld %ld %ld", pass.scissor0.left, pass.scissor0.top, pass.scissor0.right, pass.scissor0.bottom); + else + add(" scissor none"); + if (mesh_trace_bound) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc; + u64 key = 0; + bool decoded = false; + mesh_state_desc(*mesh_trace_bound, pass, desc, key, &decoded); + const auto& d = desc.DepthStencilState; + add(" depth %d func %d write %d stencil %d", d.DepthEnable, static_cast<int>(d.DepthFunc), d.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ALL, + d.StencilEnable); + // The PSO's rasterizer (the desc mesh_pso creates; a failed creation falls back to the default state, see the + // desktop-pipeline line) and the title's words it is decoded from. D3D12 cull: 1 none, 2 front, 3 back. + const auto& r = desc.RasterizerState; + const BoundPipeline& b = *mesh_trace_bound; + const bool title_rs = b.derived_rs || (b.has_words && b.rs.ok); + add(" raster cull %d ccw %d depthclip %d bias %d/%g/%g fill %d (%s", static_cast<int>(r.CullMode), r.FrontCounterClockwise, r.DepthClipEnable, + r.DepthBias, r.DepthBiasClamp, r.SlopeScaledDepthBias, static_cast<int>(r.FillMode), + mesh_switches().cull ? (title_rs ? "from the title" : "default: title rasterizer not decoded") + : mesh_switches().depthclip && title_rs ? "default, depth clip from the title (X2W_DRAW_STATE_DEPTHCLIP)" + : "default: X2W_MESH_STATE off or NOCULL"); + (void)decoded; + if (b.derived_rs) + add("; title: slot 55 rasterizer part"); + else if (b.has_words) + add("; title PA_SU_SC_MODE_CNTL %08x PA_CL_CLIP_CNTL %08x%s%s%s", b.raw_mode, b.raw_clip, b.mesh_layout ? " mesh layout" : " vertex layout", + b.rs.ok ? "" : ", refused: ", b.rs.ok ? "" : (b.rs.reason ? b.rs.reason : "?")); + else + add("; no title state words"); + if (title_rs) { // what the title's words decode to, whether applied or not (FACE 0 = counter-clockwise front) + const D3D12_RASTERIZER_DESC& t = b.derived_rs ? b.patch_rs : b.rs.desc; + add(" -> decoded cull %d ccw %d depthclip %d bias %d", static_cast<int>(t.CullMode), t.FrontCounterClockwise, t.DepthClipEnable, t.DepthBias); + } + add("%s)", mesh_cull_flip() ? "; X2W_MESH_STATE_CULL_FLIP" : ""); + } + if (mesh_trace_record) { + const UINT words = mesh_trace_stride / 4 < 8 ? mesh_trace_stride / 4 : 8; + if (words && x2w_local::readable(mesh_trace_record, words * 4)) { + add(" record (max count %u, stride %u):", mesh_trace_max, mesh_trace_stride); + for (UINT i = 0; i < words; ++i) { + std::uint32_t w; + std::memcpy(&w, mesh_trace_record + 4 * i, 4); + add(" %08x", w); + } + } else { + add(" record unreadable"); + } + } + if (!drawn) add(": %s", why ? why : "not issued"); + log("%s", text); +} + +// indirect_run (d3d12_indirect.inl), type DispatchMesh, before the record is staged. False: skip the call (counted +// here by reason; indirect counts it as no-pipeline). No draw_lock held on entry. +bool mesh_prepare_body(Wrapper* self, ID3D12GraphicsCommandList* list); +bool mesh_prepare(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + const LONG64 t0 = mesh_now(); + if (trace_frame_active) mesh_trace_key = 0, mesh_trace_bound = nullptr, mesh_last_skip = -1; + const bool ok = mesh_prepare_body(self, list); + InterlockedAdd64(&mesh_prepare_ticks, mesh_now() - t0); + if (!ok && trace_frame_active) mesh_trace_call(self, false, nullptr, mesh_last_skip >= 0 ? mesh_skip_names[mesh_last_skip] : "refused"); + return ok; +} +bool mesh_prepare_body(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + mesh_ready = {}; + InterlockedIncrement(&mesh_calls); + if (!list || !mesh_tier_ok()) return mesh_skip(mesh_tier), false; + Pass& pass = pass_of(self); + if (!pass.pipeline) return mesh_skip(mesh_no_record), false; + AcquireSRWLockShared(&mesh_key_lock); + const auto found = mesh_bindings().find(pass.pipeline); + MeshBinding binding = found != mesh_bindings().end() ? found->second : MeshBinding{}; + const bool known = found != mesh_bindings().end(); + ReleaseSRWLockShared(&mesh_key_lock); + if (!known) { + binding.mesh = mesh_key_of(pass.pipeline, &binding.key); + lock_draw(300000 + __LINE__); + binding.bound = translation_for(pass.pipeline); + ReleaseSRWLockExclusive(&draw_lock); + AcquireSRWLockExclusive(&mesh_key_lock); + mesh_bindings()[pass.pipeline] = binding; + ReleaseSRWLockExclusive(&mesh_key_lock); + } + if (!binding.mesh || !binding.key.keyed || !binding.bound) return mesh_skip(mesh_no_record), false; + if (trace_frame_active) mesh_trace_key = binding.key.key, mesh_trace_bound = binding.bound; + // The key's entry is kept with the binding (map nodes do not move): loaded_mesh (mesh_lock + lookup) only for the + // first call and, for a key without a translation, when its 5 s retry is due (racy reads of state / retry_at: at + // worst one extra loaded_mesh). + MeshEntry* entry = binding.entry; + if (!entry || (entry->state != 1 && entry->state != 2 && GetTickCount64() >= entry->retry_at)) { + entry = &loaded_mesh(binding.key.key); + if (!binding.entry) { + AcquireSRWLockExclusive(&mesh_key_lock); + mesh_bindings()[pass.pipeline].entry = entry; + ReleaseSRWLockExclusive(&mesh_key_lock); + } + } + MeshEntry& e = *entry; + mesh_note_use(e, binding.key.key); // every keyed call, whatever is refused below (coverage) + if (!pass.targets_bound) { + mesh_refusal_line(e, binding.key.key, mesh_no_targets, "no targets: no render target or depth view bound by the list"); + return mesh_skip(mesh_no_targets), false; + } + // A depth-only pipeline (no pixel stage) needs no variant (translation_for_targets takes the base for it). + const bool rtv_variant = e.tr && e.tr->ps && std::any_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant); + if (e.state == 4) return mesh_skip(mesh_no_translation), false; + if (e.state != 1) return mesh_skip(mesh_failed), false; + if (binding.attached != e.tr) { + // The mesh translation becomes this pipeline's translation, so draw_translated finds it (translation_for leaves + // it null for a record without vertex code). Only a ready translation is attached. + lock_draw(300000 + __LINE__); + const bool free = !binding.bound->translation || binding.bound->translation == e.tr; + if (free) binding.bound->translation = e.tr; + ReleaseSRWLockExclusive(&draw_lock); + if (!free) { + mesh_refusal_line(e, binding.key.key, mesh_failed, "translation taken: the bound pipeline already has another translation"); + return mesh_skip(mesh_failed), false; + } + AcquireSRWLockExclusive(&mesh_key_lock); + mesh_bindings()[pass.pipeline].attached = e.tr; + ReleaseSRWLockExclusive(&mesh_key_lock); + } + const u64 signature = mesh_pass_signature(pass); + ID3D12PipelineState* pso = binding.pso && binding.pso_signature == signature ? binding.pso : nullptr; + Translation* tr = pso ? binding.pso_tr : e.tr; + if (!pso && rtv_variant) { + // Integer / 32-bit float targets: the pixel stage's RTV variant, the same contract as ordinary draws + // (translation_for_targets: key fnv("rtv1 <base key> <formats>"), request req_<variant>.rtv, manifest with the + // rtv1 line). draw_translated resolves the same variant entry for this call. A variant that is not ready is + // looked up again (under draw_lock) at most once a second per binding and pass signature. + if (binding.variant_wait_signature == signature && GetTickCount64() < binding.variant_wait_until) return mesh_skip(mesh_rtv_variant), false; + lock_draw(300000 + __LINE__); + tr = translation_for_targets(e.tr, pass); + const bool ready = tr && tr->state == 1 && tr->ms; + ReleaseSRWLockExclusive(&draw_lock); + if (!ready) { + AcquireSRWLockExclusive(&mesh_key_lock); + MeshBinding& kept = mesh_bindings()[pass.pipeline]; + kept.variant_wait_signature = signature; + kept.variant_wait_until = GetTickCount64() + 1000; + ReleaseSRWLockExclusive(&mesh_key_lock); + if (!mesh_refusal_logged(e, mesh_rtv_variant)) { + char detail[200]; + int n = std::snprintf(detail, sizeof(detail), "rtv variant: target formats"); + for (UINT i = 0; i < pass.target_count && n < 120; ++i) + n += std::snprintf(detail + n, sizeof(detail) - n, " %d", static_cast<int>(pass.target_formats[i])); + std::snprintf(detail + n, sizeof(detail) - n, "; variant %016llx %s", tr ? static_cast<unsigned long long>(tr->key) : 0ull, + tr && tr->state == 1 ? "has no mesh stage" : "not translated yet (req_<variant>.rtv published)"); + mesh_refusal_line(e, binding.key.key, mesh_rtv_variant, detail); + } + return mesh_skip(mesh_rtv_variant), false; + } + static LONG variants_logged; + if (first_calls(variants_logged, 256)) + log("x2w-mesh pipeline %016llx: RTV variant %016llx for target formats %d%s (pixel stage %s)", static_cast<unsigned long long>(binding.key.key), + static_cast<unsigned long long>(tr->key), static_cast<int>(pass.target_formats[0]), pass.target_count > 1 ? " ..." : "", tr->ps ? "yes" : "none"); + } + static volatile LONG reuse_logged; // once per process: the first call served by the PSO kept with the binding + if (pso && !reuse_logged && InterlockedExchange(&reuse_logged, 1) == 0) + log("x2w-mesh pipeline %016llx: PSO kept with the binding reused (no state desc, hash or mesh_lock for this call; logged once)", + static_cast<unsigned long long>(binding.key.key)); + if (!pso) { + bool compiling = false; + pso = mesh_pso(e, *tr, *binding.bound, pass, &compiling); + if (compiling) return mesh_skip(mesh_compiling), false; + if (pso) { + AcquireSRWLockExclusive(&mesh_key_lock); + MeshBinding& kept = mesh_bindings()[pass.pipeline]; + kept.pso = pso; + kept.pso_tr = tr; + kept.pso_signature = signature; + ReleaseSRWLockExclusive(&mesh_key_lock); + } + } + if (!pso) { + mesh_refusal_line(e, binding.key.key, mesh_no_pso, "no PSO: CreatePipelineState failed, see its desktop pipeline line"); + return mesh_skip(mesh_no_pso), false; + } + mesh_ready = {self, tr, pso, &e}; + return true; +} + +// indirect_mesh_hook: the call is staged (copy + guard). Binds through draw_translated, whose issue point calls +// indirect_issue. True only when the ExecuteIndirect was recorded. +bool mesh_hook(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + if (mesh_ready.list != self || !mesh_ready.pso || !list) return false; + mesh_binding_now = true; + const LONG64 t0 = mesh_now(); + // LOCAL meshrt: traced frame: a pipeline statistics query around the call (mesh_stats_ready). + mesh_trace_query = -1; + if (trace_frame_active && mesh_stats_ready()) { + const LONG slot = InterlockedIncrement(&mesh_stats_next) - 1; + if (slot < static_cast<LONG>(mesh_stats.capacity)) { + mesh_trace_query = slot; + mesh_stats_keys[slot] = mesh_trace_key; + list->BeginQuery(mesh_stats.heap, mesh_stats_type(), static_cast<UINT>(slot)); + } + } + // LOCAL meshrt: X2W_MESH_STATS_FRAMES: outside the traced frame, a query from the frame slots (mesh_fs_begin). + LONG fs_query = -1; + if (!trace_frame_active && mesh_fs_collecting()) { + std::uint32_t xyz[3] = {}; + const bool readable = mesh_dump_record_groups(xyz); + const bool groups = readable && xyz[0] && xyz[1] && xyz[2]; // "with groups" on the lines + const bool xpos = readable && xyz[0]; // the frame counts (the request: X > 0) + fs_query = mesh_fs_begin(pass_of(self), groups, xpos); + if (fs_query >= 0) list->BeginQuery(mesh_fs_heap, mesh_stats_type(), static_cast<UINT>(fs_query)); + } + const bool issued = draw_translated(self, false, 0, 0, 0, 0, 0); + if (fs_query >= 0) { + list->EndQuery(mesh_fs_heap, mesh_stats_type(), static_cast<UINT>(fs_query)); + list->ResolveQueryData(mesh_fs_heap, mesh_stats_type(), static_cast<UINT>(fs_query), 1, mesh_fs_readback, + u64{static_cast<UINT>(fs_query)} * mesh_stats_size()); + } + if (mesh_trace_query >= 0) { + list->EndQuery(mesh_stats.heap, mesh_stats_type(), static_cast<UINT>(mesh_trace_query)); + list->ResolveQueryData(mesh_stats.heap, mesh_stats_type(), static_cast<UINT>(mesh_trace_query), 1, mesh_stats.readback, + u64{static_cast<UINT>(mesh_trace_query)} * mesh_stats_size()); + } + InterlockedAdd64(&mesh_bind_ticks, mesh_now() - t0); + InterlockedIncrement64(&mesh_bind_calls); + mesh_binding_now = false; + if (trace_frame_active) mesh_trace_call(self, issued, mesh_ready.tr, "bind refused by draw_translated"); + if (!mesh_dump_dir.empty()) { // LOCAL meshrt: X2W_MESH_DUMP_INPUTS: the record of the dumped call, then done + const UINT bytes = mesh_trace_stride * (mesh_trace_max ? mesh_trace_max : 1); + const bool readable_record = mesh_trace_record && bytes && bytes <= 65536 && x2w_local::readable(mesh_trace_record, bytes); + char note[160]; + std::snprintf(note, sizeof(note), "indirect record(s) in title memory at record time: max count %u, stride %u; call %s", mesh_trace_max, + mesh_trace_stride, issued ? "issued" : "NOT issued (bind refused)"); + mesh_dump_file("record.bin", readable_record ? mesh_trace_record : nullptr, readable_record ? bytes : 0, note); + mesh_dump_dir.clear(); + } + MeshEntry* e = mesh_ready.entry; + mesh_ready = {}; + if (!issued) { + if (e) mesh_refusal_line(*e, e->tr->key, mesh_bind, "bind refused by draw_translated; heap / vinfo / vdesc refusals also have an x2w-draw-rt line, others none"); + return mesh_skip(mesh_bind), false; + } + InterlockedIncrement(&mesh_issued); + if (e && !e->issued_once) { + e->issued_once = true; // a benign race: at worst two lines + static LONG shown; + if (first_calls(shown, 1024)) log("x2w-mesh pipeline %016llx: first call issued", e->tr->key); + } + return true; +} + +// d3d12_draw.inl hooks: draw_translated binds a mesh call (topology gate off, no rect entry value) ... +bool mesh_issue_active(Wrapper* self) { return mesh_binding_now && mesh_ready.list == self && indirect_pending(self); } +// ... and pipeline_for returns the pre-built mesh PSO for a mesh translation (null outside a mesh call: a plain +// draw with a mesh pipeline bound draws nothing). +ID3D12PipelineState* mesh_pso_for(const Translation& tr) { return mesh_binding_now && mesh_ready.tr == &tr ? mesh_ready.pso : nullptr; } + +const bool mesh_hook_installed = [] { + if (mesh_enabled()) indirect_mesh_hook = &mesh_hook; + return mesh_enabled(); +}(); + +// Every 300 frames (queue_present), X2W_MESH=1 only. Counters restart after each line. +void report_mesh(LONG frames) +{ + if (!mesh_enabled()) return; + LONG s[mesh_skips]; + for (int i = 0; i < mesh_skips; ++i) s[i] = InterlockedExchange(&mesh_skipped[i], 0); + const LONG calls = InterlockedExchange(&mesh_calls, 0), issued = InterlockedExchange(&mesh_issued, 0); + LONG accounted = issued; + for (LONG v : s) accounted += v; + log("x2w-mesh %ld frames: calls %ld issued %ld; skipped: no translation %ld, translation failed %ld, no PSO %ld, no targets %ld, " + "tier %ld; also no mesh record %ld, rtv variant %ld, bind refused %ld, refused by indirect after prepare %ld, PSO compiling " + "(X2W_MESH_ASYNC) %ld; records keyed %ld unkeyed %ld (total)", + frames, calls, issued, s[mesh_no_translation], s[mesh_failed], s[mesh_no_pso], s[mesh_no_targets], s[mesh_tier], s[mesh_no_record], + s[mesh_rtv_variant], s[mesh_bind], calls - accounted, s[mesh_compiling], mesh_records_keyed, mesh_records_unkeyed); + // LOCAL meshrt: stand-in CPU per call (QueryPerformanceCounter around mesh_prepare and the bind). + static const double us_per_tick = [] { + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + return 1e6 / static_cast<double>(f.QuadPart); + }(); + const LONG64 prepare = InterlockedExchange64(&mesh_prepare_ticks, 0), bind = InterlockedExchange64(&mesh_bind_ticks, 0); + const LONG64 binds = InterlockedExchange64(&mesh_bind_calls, 0); + log("x2w-mesh %ld frames cpu: prepare %.1f us/call over %ld calls (%.0f ms), bind %.1f us/call over %lld binds (%.0f ms; draw_translated " + "including its draw_lock wait); PSOs with decoded state %ld, of them on the default state after a refusal %ld (total)", frames, + calls ? prepare * us_per_tick / calls : 0.0, calls, prepare * us_per_tick / 1000.0, binds ? bind * us_per_tick / binds : 0.0, + static_cast<long long>(binds), bind * us_per_tick / 1000.0, mesh_state_changed, mesh_state_fallback); + report_mesh_keys(frames); +} diff --git a/src/startup_stubs/d3d12_present.inl b/src/startup_stubs/d3d12_present.inl index 58bec8cf4b..8557a64756 100644 --- a/src/startup_stubs/d3d12_present.inl +++ b/src/startup_stubs/d3d12_present.inl @@ -11,8 +11,13 @@ struct WindowPresenter { ID3D12DescriptorHeap* targets = nullptr; ID3D12DescriptorHeap* textures = nullptr; ID3D12Resource* buffers[2] = {}; - ID3D12CommandAllocator* allocator = nullptr; - ID3D12GraphicsCommandList* list = nullptr; + // LOCAL stall: two copy slots (allocator, list, view), each reused only once the fence value of its + // last copy has passed; a present whose slot is still busy skips the window copy instead of waiting. + ID3D12CommandAllocator* allocators[2] = {}; + ID3D12GraphicsCommandList* lists[2] = {}; + UINT64 slot_values[2] = {}; + UINT next_slot = 0; + LONG skipped = 0; ID3D12RootSignature* root = nullptr; ID3D12PipelineState* pipeline = nullptr; ID3D12Fence* fence = nullptr; @@ -22,6 +27,12 @@ struct WindowPresenter { bool failed = false; }; WindowPresenter window_presenter; +x2w_startup::TitleComposition title_composition; +bool present_in_title_window() +{ + static const bool enabled = x2w_local::env_on("X2W_PRESENT_IN_TITLE_WINDOW"); + return enabled; +} LONG window_presents; // The output window belongs to this layer and has its own thread and message loop; the title's @@ -117,14 +128,21 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; desc.BufferCount = 2; desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; - hr = factory->CreateSwapChainForHwnd(queue, window, &desc, nullptr, nullptr, &chain1); - if (SUCCEEDED(hr)) factory->MakeWindowAssociation(window, DXGI_MWA_NO_ALT_ENTER); + if (present_in_title_window()) { + desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; + desc.Scaling = DXGI_SCALING_STRETCH; + desc.AlphaMode = DXGI_ALPHA_MODE_IGNORE; + hr = factory->CreateSwapChainForComposition(queue, &desc, nullptr, &chain1); + } else { + hr = factory->CreateSwapChainForHwnd(queue, window, &desc, nullptr, nullptr, &chain1); + if (SUCCEEDED(hr)) factory->MakeWindowAssociation(window, DXGI_MWA_NO_ALT_ENTER); + } } if (SUCCEEDED(hr)) hr = chain1->QueryInterface(IID_PPV_ARGS(&p.chain)); 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}; + const D3D12_DESCRIPTOR_HEAP_DESC texture_heap{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; // one view per copy slot 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); @@ -133,9 +151,11 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) if (SUCCEEDED(hr)) device->CreateRenderTargetView(p.buffers[i], nullptr, D3D12_CPU_DESCRIPTOR_HANDLE{p.targets->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{i} * step}); } - if (SUCCEEDED(hr)) hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&p.allocator)); - if (SUCCEEDED(hr)) hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, p.allocator, nullptr, IID_PPV_ARGS(&p.list)); - if (SUCCEEDED(hr)) hr = p.list->Close(); + for (int i = 0; i < 2; ++i) { + if (SUCCEEDED(hr)) hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&p.allocators[i])); + if (SUCCEEDED(hr)) hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, p.allocators[i], nullptr, IID_PPV_ARGS(&p.lists[i])); + if (SUCCEEDED(hr)) hr = p.lists[i]->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[] = @@ -186,6 +206,99 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) return SUCCEEDED(hr); } +void note_present_planes(LONG frame, UINT planes, const void* plane_parameters, const void* present_parameters) +{ + static const bool on = [] { + const bool value = x2w_local::env_on("X2W_PRESENT_PLANES_LOG"); + if (value) log("x2w-present X2W_PRESENT_PLANES_LOG=1: plane changes and one line per 300 frames are logged"); + return value; + }(); + if (!on) return; + static UINT last_planes = ~0u; + static u64 last_count = ~0ull, last_shape = ~0ull; + static u64 known[8]; + static UINT known_count, flips_since, extra_planes_since; + static u64 last_surface; + static LONG lines, summaries; + const auto* words = static_cast<const u64*>(plane_parameters); + const bool header = planes && words && x2w_local::readable(words, 0x18); + const u64 count = header ? words[1] : 0; + u64 surface = 0, shape = 0; + if (header && count >= 1 && x2w_local::readable(reinterpret_cast<const void*>(words[2]), 8)) { + surface = *reinterpret_cast<const u64*>(words[2]); + Wrapper* wrapper = as_wrapper(reinterpret_cast<const void*>(surface)); + if (wrapper && wrapper->own().kind == resource_kind && wrapper->own().real) { + const D3D12_RESOURCE_DESC desc = static_cast<ID3D12Resource*>(wrapper->own().real)->GetDesc(); + shape = (desc.Width & 0xFFFFF) | (u64{desc.Height & 0xFFFFF} << 20) | (u64{static_cast<UINT>(desc.Format) & 0xFFF} << 40); + } + } + // Called from queue_present only, one thread at a time per queue; the statics are diagnostics. + if (surface != last_surface) ++flips_since; + last_surface = surface; + if (planes > 1 || count > 1) ++extra_planes_since; + bool fresh = false; + if (surface) { + UINT i = 0; + while (i < known_count && known[i] != surface) ++i; + if (i == known_count && known_count < 8) { + known[known_count++] = surface; + fresh = true; + } + } + if (frame % 300 == 0 && first_calls(summaries, 200)) { + log("x2w-present planes summary frame %ld: planes=%u resources=%llu %llux%llu format %llu; surfaces seen %u; surface changes %u and " + "presents with more than one plane or resource %u in the last 300 frames", + frame, planes, count, shape & 0xFFFFF, (shape >> 20) & 0xFFFFF, (shape >> 40) & 0xFFF, known_count, flips_since, extra_planes_since); + flips_since = extra_planes_since = 0; + } + if (planes == last_planes && count == last_count && shape == last_shape && !fresh) return; + last_planes = planes; + last_count = count; + last_shape = shape; + if (!first_calls(lines, 32)) return; + char a[3 * 0x60 + 1] = "", b[3 * 0x40 + 1] = ""; + if (plane_parameters && x2w_local::readable(plane_parameters, 0x60)) hex_text(plane_parameters, 0x60, a, sizeof(a)); + if (present_parameters && x2w_local::readable(present_parameters, 0x40)) hex_text(present_parameters, 0x40, b, sizeof(b)); + log("x2w-present planes frame %ld: planes=%u resources=%llu surface=0x%llx %llux%llu format %llu; plane=[%s] present=[%s]", frame, planes, + count, surface, shape & 0xFFFFF, (shape >> 20) & 0xFFFFF, (shape >> 40) & 0xFFF, a, b); +} + +void note_quiet_frame(LONG frame) +{ + static const LONG wanted = [] { + char value[16]{}; + const LONG n = GetEnvironmentVariableA("X2W_D3D12_TRACE_QUIET", value, sizeof(value)) ? std::atol(value) : 0L; + if (n > 0) log("x2w-frame X2W_D3D12_TRACE_QUIET=%ld: one frame is traced after %ld quiet frames (1-8 translated draws) past a busy one", n, n); + return n > 0 ? n : 0L; + }(); + if (!wanted) return; + static const bool dump_dir = GetEnvironmentVariableA("X2W_DRAW_DUMP_DIR", nullptr, 0) != 0; + static LONG last_total, quiet_run, end_frame, next_allowed, traces; + static bool armed; + const LONG total = translated_draws; + const LONG drawn = total - last_total; + last_total = total; + if (end_frame && frame == end_frame) { + InterlockedExchange(&trace_frame_active, 0); + log("x2w-frame ---- end quiet frame %ld (%ld translated draws)", frame, drawn); + summarise_indirect_calls(); + end_frame = 0; + return; + } + static LONG busy_frames; + if (drawn >= 20 && ++busy_frames >= 300) armed = true; + quiet_run = armed && drawn >= 1 && drawn <= 8 ? quiet_run + 1 : 0; + if (end_frame || quiet_run < wanted || frame < next_allowed || traces >= 3) return; + ++traces; + quiet_run = 0; + next_allowed = frame + 3000; + end_frame = frame + 1; + if (dump_dir && !draw_dump_frame()) InterlockedExchange(&quiet_dump_frame, frame); + log("x2w-frame ---- begin quiet frame %ld (previous frame: %ld translated draws, %ld quiet frames)%s", frame + 1, drawn, wanted, + quiet_dump_frame == frame ? "; per-draw target dumps on" : ""); + InterlockedExchange(&trace_frame_active, 1); +} + // Draws `surface` (resting in COMMON) into the window and flips. Returns false if not shown. bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) { @@ -200,12 +313,29 @@ bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) desc.Dimension, desc.SampleDesc.Count, desc.Flags, desc.Format); return false; } - HWND window = output_window(); + HWND window = present_in_title_window() ? title_composition.window : output_window(); + if (present_in_title_window() && !IsWindow(window)) window = x2w_startup::title_picture_window(); if (!window) return false; if (!p.chain && !create_window_presenter(queue, window)) { p.failed = true; return false; } + if (present_in_title_window()) { + const HRESULT attached = title_composition.show(window, p.chain, p.width, p.height); + if (attached != S_OK) { + static LONG failures; + if (FAILED(attached) && first_calls(failures, 3)) + log("x2w-present title composition failed: 0x%08lx", static_cast<unsigned long>(attached)); + return false; + } + } + static const bool wait_each = x2w_local::env_on("X2W_PRESENT_WAIT"); + const UINT slot = wait_each ? 0 : p.next_slot; + if (!wait_each && p.fence->GetCompletedValue() < p.slot_values[slot]) { + const LONG n = InterlockedIncrement(&p.skipped); + if (n <= 4 || n % 500 == 0) log("x2w-present window copy skipped %ld times (previous copies still queued)", n); + return true; // the window keeps its last picture + } ID3D12Device* device = device_of(the_device); const DXGI_FORMAT view_format = x2w_startup::present_view_format(desc.Format); D3D12_SHADER_RESOURCE_VIEW_DESC view{}; @@ -213,36 +343,48 @@ bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) 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 view_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + device->CreateShaderResourceView(surface, &view, D3D12_CPU_DESCRIPTOR_HANDLE{p.textures->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{slot} * view_step}); 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); - transition(p.list, p.buffers[index], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); + ID3D12GraphicsCommandList* list = p.lists[slot]; + if (FAILED(p.allocators[slot]->Reset()) || FAILED(list->Reset(p.allocators[slot], p.pipeline))) return false; + transition(list, surface, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + transition(list, p.buffers[index], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(p.width), static_cast<float>(p.height), 0, 1}; const D3D12_RECT scissor{0, 0, static_cast<LONG>(p.width), static_cast<LONG>(p.height)}; - p.list->SetGraphicsRootSignature(p.root); - p.list->SetDescriptorHeaps(1, &p.textures); - p.list->SetGraphicsRootDescriptorTable(0, p.textures->GetGPUDescriptorHandleForHeapStart()); - p.list->RSSetViewports(1, &viewport); - p.list->RSSetScissorRects(1, &scissor); - p.list->OMSetRenderTargets(1, &target, FALSE, nullptr); - p.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - p.list->DrawInstanced(3, 1, 0, 0); - 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 (FAILED(p.list->Close())) { + list->SetGraphicsRootSignature(p.root); + list->SetDescriptorHeaps(1, &p.textures); + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{p.textures->GetGPUDescriptorHandleForHeapStart().ptr + UINT64{slot} * view_step}); + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &target, FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + transition(list, p.buffers[index], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); + transition(list, surface, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + if (FAILED(list->Close())) { p.failed = true; return false; } - ID3D12CommandList* lists[] = {p.list}; + ID3D12CommandList* lists[] = {list}; queue->ExecuteCommandLists(1, lists); - const HRESULT hr = p.chain->Present(0, 0); - // The allocator is reused next frame: wait until this frame's commands are done. - if (SUCCEEDED(queue->Signal(p.fence, ++p.fence_value)) && p.fence->GetCompletedValue() < p.fence_value && - SUCCEEDED(p.fence->SetEventOnCompletion(p.fence_value, p.reached))) - WaitForSingleObject(p.reached, 2000); + // Without the wait, DO_NOT_WAIT: a full flip queue drops this window frame instead of blocking. + HRESULT hr = p.chain->Present(0, wait_each ? 0 : DXGI_PRESENT_DO_NOT_WAIT); + if (hr == S_OK && present_in_title_window()) { + static LONG reports; + if (first_calls(reports, 1)) log("x2w-present first flip on the original window"); + } + if (hr == DXGI_ERROR_WAS_STILL_DRAWING) { + const LONG n = InterlockedIncrement(&p.skipped); + if (n <= 4 || n % 500 == 0) log("x2w-present window flip skipped %ld times (flip queue full)", n); + hr = S_OK; + } + if (SUCCEEDED(queue->Signal(p.fence, ++p.fence_value))) p.slot_values[slot] = p.fence_value; + p.next_slot = (slot + 1) % 2; + if (wait_each && p.fence->GetCompletedValue() < p.fence_value && SUCCEEDED(p.fence->SetEventOnCompletion(p.fence_value, p.reached))) + WaitForSingleObject(p.reached, 2000); // the allocator is reused next frame static LONG failures; if (FAILED(hr) && first_calls(failures, 4)) log("x2w-present Present failed 0x%08lx", static_cast<unsigned long>(hr)); check_device("window present", 0); diff --git a/src/startup_stubs/d3d12_range_alias.inl b/src/startup_stubs/d3d12_range_alias.inl new file mode 100644 index 0000000000..90fd69183d --- /dev/null +++ b/src/startup_stubs/d3d12_range_alias.inl @@ -0,0 +1,125 @@ +bool range_alias_on() +{ + static const bool on = x2w_local::env_on("X2W_RANGE_ALIAS"); + return on; +} + +LONG range_alias_built, range_alias_reused, range_alias_failed, range_alias_ranges; + +namespace range_alias { +using Location = BOOL(WINAPI*)(const void*, HANDLE*, ULONG64*); +Location location() +{ + static const Location f = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast<Location>(GetProcAddress(xmem, "x2w_xmem_gpu_location")) : nullptr; + }(); + return f; +} + +// The gate, checked once (on the first split range). The reason text goes on every refusal line. +const char* refusal(HANDLE first_section) +{ + static const char* reason = nullptr; + static SRWLOCK lock = SRWLOCK_INIT; + AcquireSRWLockExclusive(&lock); + if (!reason) { + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + const HRESULT got = device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)); + ID3D12Heap* heap = first_section ? section_heap(first_section) : nullptr; + const D3D12_HEAP_FLAGS flags = heap ? heap->GetDesc().Flags : D3D12_HEAP_FLAG_NONE; + if (FAILED(got) || options.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_1) + reason = "no tiled resources (tier below 1)"; + else if (!heap) + reason = "the section has no desktop heap"; + else if (flags & D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER) + reason = "section heaps are cross-adapter shared: UpdateTileMappings onto them removes the device " + "(tests/tile_mapping_shared_heap_check)"; + else + reason = "section heap is not cross-adapter, but this build has no alias builder"; + log("x2w-range-alias: X2W_RANGE_ALIAS=1; tiled resources tier %d (0x%08lx), section heap %p flags 0x%x; xmem location %s: " + "REFUSED (%s). Split ranges stay NULL, as without the switch.", + SUCCEEDED(got) ? static_cast<int>(options.TiledResourcesTier) : -1, static_cast<unsigned long>(got), static_cast<void*>(heap), + static_cast<unsigned>(flags), location() ? "found" : "MISSING", reason); + } + ReleaseSRWLockExclusive(&lock); + return reason; +} + +void summary() +{ + log("x2w-range-alias: built %ld, reused %ld, failed %ld bindings over %ld distinct ranges (frame %ld)", range_alias_built, range_alias_reused, + range_alias_failed, range_alias_ranges, static_cast<long>(frame_number)); +} + +void note_failed() +{ + const LONG n = InterlockedIncrement(&range_alias_failed); + if ((n & (n - 1)) == 0 && n >= 64) summary(); // 64, 128, 256, ... +} +} // namespace range_alias + +// desktop_range: a binding of a frame-cached split range (counted, no line). +void range_alias_repeat() +{ + range_alias::note_failed(); +} + +// desktop_range: [address, address + bytes) is chunk pages whose base has a window and which failed the per-page +// check. Describes the range (first sighting, capped), refuses, counts. Always returns false (no alias). +bool range_alias_split(u64 address, u64 bytes) +{ + const range_alias::Location location = range_alias::location(); + HANDLE first_section = nullptr; + ULONG64 first_at = 0; + if (location) location(reinterpret_cast<const void*>(address), &first_section, &first_at); + const char* reason = range_alias::refusal(first_section); + range_alias::note_failed(); + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_set<u64> seen; + const u64 key = address * 1099511628211ull ^ bytes; + AcquireSRWLockExclusive(&lock); + const bool fresh = seen.size() < 4096 && seen.insert(key).second; + ReleaseSRWLockExclusive(&lock); + if (!fresh) return false; + const LONG distinct = InterlockedIncrement(&range_alias_ranges); + if (!x2w_local::first_of(distinct, 48) || !location) return false; + // The page walk: one location per 64 KiB page (as desktop_range's check), from the range's first page. + const u64 first_page = address & ~0xffffull, end = address + bytes; + std::vector<HANDLE> sections; + unsigned long pages = 0, runs = 0, missing = 0; + long first_break = -1; + const char* break_kind = ""; + long long jump = 0; + HANDLE previous = nullptr; + ULONG64 previous_at = 0; + for (u64 at = first_page; at < end; at += 0x10000, ++pages) { + HANDLE section = nullptr; + ULONG64 where = 0; + if (!location(reinterpret_cast<const void*>(at), §ion, &where)) { + ++missing; + previous = nullptr; + continue; + } + where &= ~0xffffull; + const bool linear = previous && section == previous && where == previous_at + 0x10000; + if (!linear) { + ++runs; + if (previous && first_break < 0) { + first_break = static_cast<long>(pages); + break_kind = section != previous ? "section change" : "offset jump"; + jump = static_cast<long long>(where) - static_cast<long long>(previous_at + 0x10000); + } + } + if (std::find(sections.begin(), sections.end(), section) == sections.end()) sections.push_back(section); + previous = section; + previous_at = where; + } + char where_broken[96] = "none"; + if (first_break >= 0) + std::snprintf(where_broken, sizeof(where_broken), "page %ld, %s %s0x%llx", first_break, break_kind, jump < 0 ? "-" : "+", + static_cast<unsigned long long>(jump < 0 ? -jump : jump)); + log("x2w-range-alias range 0x%llx %llu bytes (frame %ld): %lu pages, %lu linear runs, %zu sections, %lu unmapped; first break: %s: NULL (%s)", + address, static_cast<unsigned long long>(bytes), static_cast<long>(frame_number), pages, runs, sections.size(), missing, where_broken, reason); + return false; +} diff --git a/src/startup_stubs/d3d12_rawaddr.inl b/src/startup_stubs/d3d12_rawaddr.inl new file mode 100644 index 0000000000..e59775ca56 --- /dev/null +++ b/src/startup_stubs/d3d12_rawaddr.inl @@ -0,0 +1,311 @@ + +namespace ra = x2w_startup::rawaddr; + +struct RawKey { + u64 key = 0; + std::vector<ra::Seed> seeds; + std::vector<u64> learned; // addresses missed by earlier dispatches (page start), at most 4 + UINT slot = 0; // statistics slot in rawaddr_stats + LONG dispatches = 0, resolved = 0, unresolved = 0, overflow = 0, skipped = 0, shown = 0; + LONG reported_dispatches = 0; + std::uint32_t seen_misses = 0; +}; +struct RawPipeline { + RawKey* key; + ID3D12RootSignature* root; + ID3D12PipelineState* pso; + UINT first_extra; +}; +SRWLOCK rawaddr_lock = SRWLOCK_INIT; +std::unordered_map<u64, RawKey*>& rawaddr_keys() { static std::unordered_map<u64, RawKey*> m; return m; } +std::unordered_map<Wrapper*, RawPipeline>& rawaddr_pipelines() { static std::unordered_map<Wrapper*, RawPipeline> m; return m; } +constexpr UINT rawaddr_stats_slots = 256; +ID3D12Resource* rawaddr_stats; +volatile std::uint32_t* rawaddr_stats_words; // CPU view of the custom-heap statistics buffer +LONG rawaddr_stats_failed; + +// Opt-in: the raw-address shaders have not run on title data yet, so a published sidecar stays inert +// unless X2W_RAWADDR=1 (X2W_RAWADDR_OFF=1 still wins). +bool rawaddr_enabled() +{ + static const bool enabled = x2w_local::env_on("X2W_RAWADDR") && !x2w_local::env_on("X2W_RAWADDR_OFF"); + return enabled; +} + +// One CPU-readable buffer (custom heap, write-back, L0) with a 128-byte statistics slot per key. +void rawaddr_ensure_stats() +{ + if (rawaddr_stats || rawaddr_stats_failed) return; + D3D12_HEAP_PROPERTIES hp{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0}; + D3D12_RESOURCE_DESC rd{}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rd.Width = u64{rawaddr_stats_slots} * ra::kStatsBytes; + rd.Height = rd.DepthOrArraySize = rd.MipLevels = 1; + rd.SampleDesc.Count = 1; + rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + HRESULT hr = device_of(the_device)->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&rawaddr_stats)); + void* words = nullptr; + if (SUCCEEDED(hr)) hr = rawaddr_stats->Map(0, nullptr, &words); + if (FAILED(hr)) { + rawaddr_stats_failed = 1; + if (rawaddr_stats) rawaddr_stats->Release(); + rawaddr_stats = nullptr; + log("x2w-rawaddr statistics buffer failed 0x%08lx: GPU misses are not counted", static_cast<unsigned long>(hr)); + return; + } + std::memset(words, 0, static_cast<std::size_t>(rd.Width)); + rawaddr_stats_words = static_cast<volatile std::uint32_t*>(words); +} + +// Device slot 62 hook: builds the raw-address pipeline for key when its sidecar exists. True when the +// key has a sidecar (whether or not the pipeline could be built): the plain .cs.dxbc path is then skipped. +bool rawaddr_pipeline(u64 key, Wrapper* root, Wrapper* pipeline) +{ + if (!key || !pipeline) return false; + wchar_t path[MAX_PATH]; + std::string sidecar; + if (!cache_path(path, L"", key, L".rawaddr.txt") || !read_text(path, sidecar)) return false; + if (!rawaddr_enabled()) { + static LONG logged; + if (first_calls(logged, 4)) log("x2w-rawaddr %016llx: sidecar present, path off (needs X2W_RAWADDR=1, no X2W_RAWADDR_OFF): no pipeline", key); + return true; + } + std::vector<ra::Seed> seeds; + if (!ra::parse_sidecar(sidecar, seeds)) { + log("x2w-rawaddr %016llx: sidecar not understood (version / table shape): no pipeline", key); + return true; + } + std::vector<unsigned char> blob; + AcquireSRWLockShared(¬e_lock); + if (const auto found = root_blobs().find(root); found != root_blobs().end()) blob = found->second; + ReleaseSRWLockShared(¬e_lock); + ID3DBlob* code = nullptr; + const char* error = nullptr; + UINT first = 0; + ID3DBlob* augmented = blob.empty() ? nullptr : ra::augmented_root(blob.data(), blob.size(), &first, &error); + ID3D12RootSignature* signature = nullptr; + ID3D12PipelineState* pso = nullptr; + HRESULT hr = augmented ? S_OK : E_FAIL; + if (blob.empty()) error = "no title root blob"; + if (SUCCEEDED(hr)) hr = device_of(the_device)->CreateRootSignature(0, augmented->GetBufferPointer(), augmented->GetBufferSize(), IID_PPV_ARGS(&signature)); + if (augmented) augmented->Release(); + if (SUCCEEDED(hr) && (!cache_path(path, L"", key, L".rawaddr.dxbc") || FAILED(D3DReadFileToBlob(path, &code)))) { + hr = E_FAIL; + error = "no .rawaddr.dxbc"; + } + if (SUCCEEDED(hr)) { + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = signature; + pd.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + hr = device_of(the_device)->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pso)); + if (FAILED(hr)) error = "CreateComputePipelineState"; + } + if (code) code->Release(); + log("x2w-rawaddr %016llx pipeline: title root params %u + 2, %zu seeds -> 0x%08lx%s%s", key, first, seeds.size(), + static_cast<unsigned long>(hr), error ? " " : "", error ? error : ""); + if (FAILED(hr)) { + if (signature) signature->Release(); + return true; + } + AcquireSRWLockExclusive(&rawaddr_lock); + RawKey*& k = rawaddr_keys()[key]; + if (!k) { + k = new RawKey; + k->key = key; + k->seeds = seeds; + k->slot = static_cast<UINT>(rawaddr_keys().size() - 1) % rawaddr_stats_slots; + } + rawaddr_pipelines()[pipeline] = {k, signature, pso, first}; + ReleaseSRWLockExclusive(&rawaddr_lock); + return true; +} + +// The largest span [address, address + span) contiguous in one desktop window, up to X2W_RAWADDR_SPAN_MIB +// (default 16 MiB), to 64 KiB granularity: the cap, then quarters until one fits, then a binary search +// between that span and the failing one above it. At least the 4 KiB page, else unresolved. +bool rawaddr_region(u64 address, ra::Region* region, ID3D12Resource** window) +{ + static const u64 cap = [] { + char text[16] = ""; + const DWORD n = GetEnvironmentVariableA("X2W_RAWADDR_SPAN_MIB", text, sizeof(text)); + const unsigned long mib = n && n < sizeof(text) ? std::strtoul(text, nullptr, 10) : 0; + return u64{mib >= 1 && mib <= 192 ? mib : 16} << 20; + }(); + u64 offset = 0, good = 0, bad = 0; + ID3D12Resource* w = nullptr; + for (u64 span = cap; span >= 0x10000; span >>= 2) { + if (desktop_range(address, span, &w, &offset)) { + good = span; + break; + } + bad = span; + } + if (!good) { + if (!desktop_range(address, 0x1000, &w, &offset)) return false; // at least the page + *window = w; + *region = ra::make_region(address, 0x1000, offset); + return true; + } + u64 good_offset = offset; + ID3D12Resource* good_window = w; + while (bad && bad - good > 0x10000) { + const u64 mid = (good + (bad - good) / 2) & ~0xffffull; + if (mid <= good) break; + if (desktop_range(address, mid, &w, &offset)) { + good = mid; + good_offset = offset; + good_window = w; + } else { + bad = mid; + } + } + *window = good_window; + *region = ra::make_region(address, good, good_offset); + return true; +} + +// execute_dispatch hook: runs the dispatch when the bound pipeline is a raw-address pipeline. False when +// it is not one (or a title argument cannot be bound: the dispatch is then skipped by the caller). +bool rawaddr_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z) +{ + Pass& pass = pass_of(self); + AcquireSRWLockShared(&rawaddr_lock); + const auto found = rawaddr_pipelines().find(pass.pipeline); + const RawPipeline rp = found != rawaddr_pipelines().end() ? found->second : RawPipeline{}; + ReleaseSRWLockShared(&rawaddr_lock); + if (!rp.pso || !pass.compute_root) return false; + RawKey& key = *rp.key; + // the title's own parameters, replayed as execute_dispatch does + D3D12_GPU_VIRTUAL_ADDRESS addresses[16] = {}; + for (UINT i = 0; i < 16; ++i) { + const int kind = pass.compute_kind[i]; + if (kind == 5 || (kind >= 2 && kind <= 4 && pass.compute_address[i] && !(addresses[i] = desktop_va(pass.compute_address[i])))) { + if (x2w_local::first_of(InterlockedIncrement(&key.skipped), 4)) log("x2w-rawaddr %016llx: title parameter %u (kind %d) not bindable: dispatch skipped", key.key, i, kind); + return false; + } + } + // learned seeds: addresses this key missed before (statistics slot, written by the GPU) + AcquireSRWLockExclusive(&rawaddr_lock); + rawaddr_ensure_stats(); // lists record on several threads: created under the lock + if (rawaddr_stats_words) { + const volatile std::uint32_t* s = rawaddr_stats_words + key.slot * (ra::kStatsBytes / 4); + const std::uint32_t misses = s[0]; + if (misses != key.seen_misses) { + for (UINT i = 0; i < ra::kStatsRing && i < misses - key.seen_misses && key.learned.size() < 4; ++i) { + const u64 a = (s[4 + 2 * i] | (u64{s[5 + 2 * i]} << 32)) & ~0xffffull; + if (a && std::find(key.learned.begin(), key.learned.end(), a) == key.learned.end()) key.learned.push_back(a); + } + key.seen_misses = misses; + } + } + std::vector<u64> learned = key.learned; + ReleaseSRWLockExclusive(&rawaddr_lock); + // seeds -> regions: root constants first, then learned, then root descriptors + ra::Region regions[ra::kRegions]{}; + ID3D12Resource* windows[ra::kRegions] = {}; + UINT count = 0, resolved = 0, unresolved = 0, overflow = 0; + std::vector<u64> forget; // learned addresses that do not resolve: dropped so they free their place + const bool show = x2w_local::first_calls(key.shown, 2); + auto add = [&](u64 address, const char* what) { + if (!address) return; + for (UINT k = 0; k < count; ++k) + if (ra::region_contains(regions[k], address)) return; + if (count >= ra::kRegions) { + ++overflow; + if (show) log("x2w-rawaddr %016llx seed %s 0x%llx -> DROPPED (table full)", key.key, what, address); + return; + } + if (rawaddr_region(address, ®ions[count], &windows[count])) { + ++resolved; + if (show) log("x2w-rawaddr %016llx seed %s 0x%llx -> region %u, %u bytes", key.key, what, address, count, regions[count].size); + ++count; + } else { + ++unresolved; + if (what[0] == 'l') forget.push_back(address); + if (show) log("x2w-rawaddr %016llx seed %s 0x%llx -> UNRESOLVED", key.key, what, address); + } + }; + for (const ra::Seed& s : key.seeds) + if (s.kind != ra::SeedKind::rootdesc) add(ra::seed_address(s, pass.compute_kind, pass.compute_constants, pass.compute_address), "rootconst"); + for (u64 a : learned) add(a, "learned"); + for (const ra::Seed& s : key.seeds) + if (s.kind == ra::SeedKind::rootdesc) add(ra::seed_address(s, pass.compute_kind, pass.compute_constants, pass.compute_address), "rootdesc"); + InterlockedExchangeAdd(&key.resolved, static_cast<LONG>(resolved)); + InterlockedExchangeAdd(&key.unresolved, static_cast<LONG>(unresolved)); + InterlockedExchangeAdd(&key.overflow, static_cast<LONG>(overflow)); + if (!forget.empty()) { + AcquireSRWLockExclusive(&rawaddr_lock); + for (u64 a : forget) key.learned.erase(std::remove(key.learned.begin(), key.learned.end(), a), key.learned.end()); + ReleaseSRWLockExclusive(&rawaddr_lock); + } + std::uint32_t table[ra::kTableDwords]; + ra::fill_table(regions, count, table); + + lock_draw(400000 + __LINE__); + if (!ensure_draw_heap(the_device)) { + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + UINT first = static_cast<UINT>(InterlockedExchangeAdd(&draw_heap_cursor, static_cast<LONG>(ra::kSlots))) % draw_heap_size; + if (first + ra::kSlots > draw_heap_size) { + first = 0; + InterlockedExchange(&draw_heap_cursor, static_cast<LONG>(ra::kSlots)); + } + auto raw_uav = [&](ID3D12Resource* buffer, u64 offset, UINT bytes, UINT slot) { + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d.Buffer.FirstElement = offset / 4; + d.Buffer.NumElements = buffer ? (bytes + 3) / 4 : 1; + d.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + const D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + slot} * draw_heap_increment}; + device_of(the_device)->CreateUnorderedAccessView(buffer, nullptr, &d, dest); + }; + for (UINT k = 0; k < ra::kRegions; ++k) raw_uav(k < count ? windows[k] : nullptr, regions[k].view_offset, regions[k].size, k); + raw_uav(nullptr, 0, 0, ra::kNullSlot); + raw_uav(rawaddr_stats, u64{key.slot} * ra::kStatsBytes, ra::kStatsBytes, ra::kStatsSlot); + list->SetPipelineState(rp.pso); + if (!pass.heap_set) { + list->SetDescriptorHeaps(1, &draw_heap); + pass.heap_set = true; + pass.bound_sampler_heap = nullptr; // this call unbinds any sampler heap a draw bound + } + list->SetComputeRootSignature(rp.root); + for (UINT i = 0; i < 16 && i < rp.first_extra; ++i) { + switch (pass.compute_kind[i]) { + case 1: list->SetComputeRoot32BitConstants(i, pass.compute_count[i], pass.compute_constants[i], 0); break; + case 2: list->SetComputeRootConstantBufferView(i, addresses[i]); break; + case 3: list->SetComputeRootShaderResourceView(i, addresses[i]); break; + case 4: list->SetComputeRootUnorderedAccessView(i, addresses[i]); break; + default: break; + } + } + list->SetComputeRoot32BitConstants(rp.first_extra, ra::kTableDwords, table, 0); + list->SetComputeRootDescriptorTable(rp.first_extra + 1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + ReleaseSRWLockExclusive(&draw_lock); + indirect_dispatch(self, list, x, y, z); // LOCAL: Dispatch, or the pending ExecuteIndirect (d3d12_indirect.inl) + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + const LONG done = InterlockedIncrement(&key.dispatches); + if (x2w_local::first_of(done, 2)) log("x2w-rawaddr %016llx dispatch %ld (%u, %u, %u): regions %u, seeds resolved %u unresolved %u", key.key, done, x, y, z, count, resolved, unresolved); + if ((done & 63) == 1) check_device("raw-address dispatch", 0); + return true; +} + +// Heartbeat: one line per key dispatched since the last report. +void rawaddr_report() +{ + AcquireSRWLockShared(&rawaddr_lock); + for (const auto& [id, k] : rawaddr_keys()) { + const LONG d = k->dispatches; + if (d == k->reported_dispatches) continue; + const std::uint32_t misses = rawaddr_stats_words ? rawaddr_stats_words[k->slot * (ra::kStatsBytes / 4)] : 0; + log("x2w-rawaddr %016llx: dispatches %ld (+%ld), seeds resolved %ld unresolved %ld dropped %ld, gpu misses %u%s, learned %zu, skipped %ld", + id, d, d - k->reported_dispatches, k->resolved, k->unresolved, k->overflow, misses, rawaddr_stats_words ? "" : " (not counted)", + k->learned.size(), k->skipped); + k->reported_dispatches = d; + } + ReleaseSRWLockShared(&rawaddr_lock); +} diff --git a/src/startup_stubs/d3d12_record_trace.inl b/src/startup_stubs/d3d12_record_trace.inl new file mode 100644 index 0000000000..a8cec2f0c6 --- /dev/null +++ b/src/startup_stubs/d3d12_record_trace.inl @@ -0,0 +1,714 @@ + +bool record_trace_on() +{ + static const bool on = x2w_local::env_on("X2W_MESH_RECORD_TRACE"); + return on; +} + +struct TracedRecord { + LONG seq = 0; + UINT type = 0; // D3D12_INDIRECT_ARGUMENT_TYPE of the signature's last argument (10 = DispatchMesh) + UINT stride = 0, max_count = 0; + u64 key = 0; + const void* list = nullptr; + const void* dsv = nullptr; + const void* wrapper = nullptr; + const unsigned char* base = nullptr; // title memory of the argument buffer + u64 offset = 0; + UINT words = 0; + std::uint32_t at_record[4] = {}; +}; +struct TracedRange { + LONG seq = 0; // the dispatch's number in the traced frame + u64 key = 0; + const void* pipeline = nullptr; + char label = '?'; + int param = 0, offset = 0; + u64 lo = 0, hi = 0; + const char* state = ""; + LONG order = 0; // record order shared with the mesh reads + bool executed = false; +}; +// (f) one buffer a traced mesh call reads: kind 'S' srv i (source a b), 'H' heap descriptor `slot` (root constant p w). +struct TracedMeshRead { + u64 key = 0; + char kind = 'S'; + int slot = 0, source = 0, a = 0, b = 0; + u64 lo = 0, hi = 0; + LONG order = 0; +}; +SRWLOCK record_trace_lock = SRWLOCK_INIT; +std::vector<TracedRecord>& traced_records() { static std::vector<TracedRecord> v; return v; } +std::vector<TracedRange>& traced_ranges() { static std::vector<TracedRange> v; return v; } +std::vector<TracedMeshRead>& traced_mesh_reads() { static std::vector<TracedMeshRead> v; return v; } +// (d) texture UAVs bound by this frame's dispatches so far: title wrapper -> "key K #n state". +std::map<const void*, std::string>& traced_image_writers() { static std::map<const void*, std::string> m; return m; } +// (d) raw T# base -> (first resource starting there, how many): one resource walk per base per traced frame. +std::map<u64, std::pair<Wrapper*, int>>& traced_tsharp_bases() { static std::map<u64, std::pair<Wrapper*, int>> m; return m; } +LONG record_trace_seq, dispatch_trace_seq, record_trace_order; +thread_local bool record_trace_dispatch_noted; // set by record_trace_dispatch inside an indirect call + +const char* record_trace_outcome(int outcome) +{ + static const char* const names[] = {"run (c62)", "skipped: c62 table argument", "skipped: c62 unmapped", "run", + "skipped: X2W_CX_OFF", "skipped: not a slot-67 key", "skipped: no translation", + "skipped: heap", "skipped: not run", "skipped: X2W_CX_SKIP", "run (rawaddr)", + "skipped: entry value unresolved", "skipped: compiling (X2W_CX_ASYNC)"}; + static_assert(sizeof(names) / sizeof(names[0]) == co_count, "one name per ComputeOutcome"); + return outcome >= 0 && outcome < co_count ? names[outcome] : "skipped: ?"; +} + +// A 32-byte table entry as a buffer range: a runtime view token (slot 17 CBV, 18/19 buffer SRV / UAV) or a raw V#. +// False for empty entries, refused-view markers, image descriptors and anything else. +bool record_trace_entry(const std::uint32_t* w, u64* address, u64* bytes) +{ + *address = 0, *bytes = 0; + if (w[0] == view_token_magic) { + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = w[1] < view_records().size(); + if (known) record = view_records()[w[1]]; + ReleaseSRWLockShared(¬e_lock); + if (!known) return false; + if (record.slot == 17 && record.desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(address, record.desc, 8); + std::memcpy(&size, record.desc + 8, 4); + *bytes = size; + } else if ((record.slot == 18 || record.slot == 19) && record.desc_bytes >= 24) { + Wrapper* resource = as_wrapper(reinterpret_cast<const void*>(record.resource)); + x2w_startup::BufferViewLayout l; + if (!resource || !resource->own().title_memory || + !x2w_startup::buffer_view_layout_from_desc(record.slot == 19, record.desc, record.desc_bytes, l, typed_views_off())) + return false; + *address = reinterpret_cast<u64>(resource->own().title_memory) + l.offset; + *bytes = l.bytes; + } + } else if (w[0] != 0x52463258u /* refused-view marker */ && (w[3] >> 30) == 0) { + *address = w[0] | (static_cast<u64>(w[1] & 0xffff) << 32); + const std::uint32_t stride = (w[1] >> 16) & 0x3fff; + *bytes = u64{stride ? stride : 1u} * w[2]; + } + if (*bytes > (256ull << 20)) *bytes = 256ull << 20; + return *address && *bytes; +} + +// (d) The resource half of an image line: wrapper, title memory, desktop resource and what this frame did to it. +// No side effects (no memcut revive, no tiled stand-in made): a released resource says so. +void record_trace_resource_text(Wrapper* resource, char* text, std::size_t room) +{ + if (!resource || resource->own().kind != resource_kind) { + std::snprintf(text, room, "resource unknown"); + return; + } + const bool live = InterlockedCompareExchange(&resource->own().refs, 0, 0) > 0; + auto* desktop = static_cast<ID3D12Resource*>(resource->own().real); + int n = std::snprintf(text, room, "res %p title 0x%llx desktop %p%s", static_cast<void*>(resource), + static_cast<unsigned long long>(reinterpret_cast<u64>(resource->own().title_memory)), static_cast<void*>(desktop), + resource->own().tiled_address_srv ? " (tiled address srv: sampled through a stand-in)" : ""); + if (desktop && live) { + const D3D12_RESOURCE_DESC d = desktop->GetDesc(); + n += std::snprintf(text + n, room - n, " %llux%ux%u mips %u fmt %d flags 0x%x", static_cast<unsigned long long>(d.Width), d.Height, + d.DepthOrArraySize, d.MipLevels, static_cast<int>(d.Format), static_cast<unsigned>(d.Flags)); + } else { + n += std::snprintf(text + n, room - n, " (%s)", live ? "no desktop resource" : "released"); + } + // Content: this frame's writers before now. + int drawn = -1; + if (desktop) { + AcquireSRWLockShared(&traced_lock); + for (const auto& t : traced_targets()) + if (t.first == desktop) drawn = t.second; + ReleaseSRWLockShared(&traced_lock); + } + std::string uav; + AcquireSRWLockShared(&record_trace_lock); + const auto found = traced_image_writers().find(resource); + if (found != traced_image_writers().end()) uav = found->second; + ReleaseSRWLockShared(&record_trace_lock); + if (drawn < 0 && uav.empty()) { + std::snprintf(text + n, room - n, "; content: no writer seen in this frame before this dispatch%s", + desktop && live && !(desktop->GetDesc().Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + ? " (no GPU-write flags: uploaded from title memory)" : ""); + return; + } + n += std::snprintf(text + n, room - n, "; content:"); + if (drawn >= 0) n += std::snprintf(text + n, room - n, " render/depth target of this frame, %d drawn draws so far;", drawn); + if (!uav.empty()) std::snprintf(text + n, room - n, " texture uav of %s", uav.c_str()); +} + +// (d) A 32-byte entry as an image: a view token of a texture view, or a raw gfx10 T#. Fills `text` and returns the +// title wrapper (or null); *uav: a UAV view (slot 19). False: not an image entry. +bool record_trace_image(const std::uint32_t* w, char* text, std::size_t room, Wrapper** wrapper_out, bool* uav) +{ + *wrapper_out = nullptr, *uav = false; + char res[400]; + if (w[0] == view_token_magic) { + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = w[1] < view_records().size(); + if (known) record = view_records()[w[1]]; + ReleaseSRWLockShared(¬e_lock); + if (!known || (record.slot != 18 && record.slot != 19) || record.desc_bytes < 12) return false; + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + UINT dimension = 0, mip = 0; + std::memcpy(&format, record.desc, 4); + std::memcpy(&dimension, record.desc + 4, 4); + // SRV: ViewDimension 1 = buffer; UAV: 1 = buffer. Both: the first mip at +16 (SRV MostDetailedMip) / +8 (UAV MipSlice). + if (dimension == 1 || dimension == 0) return false; + if (record.slot == 18 && record.desc_bytes >= 20) std::memcpy(&mip, record.desc + 16, 4); + if (record.slot == 19 && record.desc_bytes >= 12) std::memcpy(&mip, record.desc + 8, 4); + Wrapper* resource = as_wrapper(reinterpret_cast<const void*>(record.resource)); + record_trace_resource_text(resource, res, sizeof(res)); + std::snprintf(text, room, "view %u (%s) dim %u fmt %d mip %u; %s", w[1], record.slot == 19 ? "uav" : "srv", dimension, + static_cast<int>(format), mip, res); + *wrapper_out = resource; + *uav = record.slot == 19; + return true; + } + const std::uint32_t type = w[3] >> 28; + if (w[0] == 0x52463258u || type < 8 || type > 13) return false; + const u64 address = (static_cast<u64>(w[0]) | (static_cast<u64>(w[1] & 0xff) << 32)) << 8; + const std::uint32_t width = (((w[1] >> 30) & 3) | ((w[2] & 0xfff) << 2)) + 1, height = ((w[2] >> 14) & 0x3fff) + 1; + // The resource whose title memory starts at the T# base (a texture; several: the first, counted). + // One walk of the resources per distinct base in the traced frame (the cache is emptied at the report). + Wrapper* resource = nullptr; + int matches = 0; + bool cached = false; + AcquireSRWLockShared(&record_trace_lock); + if (const auto hit = traced_tsharp_bases().find(address); hit != traced_tsharp_bases().end()) + cached = true, resource = hit->second.first, matches = hit->second.second; + ReleaseSRWLockShared(&record_trace_lock); + if (address && !cached) { + AcquireSRWLockShared(¬e_lock); + for (const auto& [wrapper, info] : resource_infos()) + if (reinterpret_cast<u64>(wrapper->own().title_memory) == address && info.console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && + InterlockedCompareExchange(&wrapper->own().refs, 0, 0) > 0) { + if (!resource) resource = const_cast<Wrapper*>(wrapper); + ++matches; + } + ReleaseSRWLockShared(¬e_lock); + AcquireSRWLockExclusive(&record_trace_lock); + traced_tsharp_bases()[address] = {resource, matches}; + ReleaseSRWLockExclusive(&record_trace_lock); + } + if (resource) record_trace_resource_text(resource, res, sizeof(res)); + else std::snprintf(res, sizeof(res), "no resource starts at the base"); + std::snprintf(text, room, "T# 0x%llx %ux%u depth %u fmt %u levels %u-%u type %u sw %u; %s%s", static_cast<unsigned long long>(address), width, + height, (w[4] & 0x1fff) + 1, (w[1] >> 20) & 0x1ff, (w[3] >> 12) & 15, (w[3] >> 16) & 15, type, (w[3] >> 20) & 0x1f, res, + matches > 1 ? " (several resources start there: the first)" : ""); + *wrapper_out = resource; + return true; +} + +// (e) The title CBV_SRV_UAV heap of a list: the bound one (SetDescriptorHeaps), else the one holding a bound compute +// table, else the newest (title_view_heap's rule). +struct TraceHeap { + u64 base = 0, bytes = 0; + UINT increment = 32, count = 0; +}; +TraceHeap record_trace_heap(const Pass& pass) +{ + TraceHeap out; + AcquireSRWLockShared(¬e_lock); + const HeapInfo* best = nullptr; + for (const HeapInfo& h : heap_infos()) { + if (h.type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || !h.title_cpu || !h.increment) continue; + if (pass.source_view_heap && h.wrapper == pass.source_view_heap) { + best = &h; + break; + } + for (UINT i = 0; i < 16; ++i) + if (pass.compute_kind[i] == 5 && pass.compute_address[i] >= h.title_cpu && pass.compute_address[i] < h.title_cpu + u64{h.count} * h.increment) + best = &h; + if (!best) best = &h; + } + if (best) out.base = best->title_cpu, out.increment = best->increment, out.count = best->logical_count ? best->logical_count : best->count, + out.bytes = u64{out.count} * best->increment; + ReleaseSRWLockShared(¬e_lock); + return out; +} +// (e) The descriptor at heap index `index`: a buffer range (true, *address / *bytes) or text for anything else. +bool record_trace_heap_slot(const TraceHeap& heap, std::uint32_t index, u64* address, u64* bytes, char* text, std::size_t room, Wrapper** image) +{ + *address = 0, *bytes = 0, *image = nullptr; + text[0] = 0; + const u64 slot = heap.base + u64{index} * heap.increment; + std::uint32_t w[8] = {}; + if (!heap.base || index >= heap.count || !x2w_local::readable(reinterpret_cast<const void*>(slot), 32)) { + std::snprintf(text, room, "slot 0x%llx not readable", static_cast<unsigned long long>(slot)); + return false; + } + std::memcpy(w, reinterpret_cast<const void*>(slot), 32); + if (record_trace_entry(w, address, bytes)) return true; + bool uav = false; + char image_text[700]; + if (record_trace_image(w, image_text, sizeof(image_text), image, &uav)) { + std::snprintf(text, room, "image: %s", image_text); + return false; + } + std::snprintf(text, room, "other: words %08x %08x %08x %08x", w[0], w[1], w[2], w[3]); + return false; +} + +// (c) execute_dispatch, every dispatch on this thread (direct, and indirect through indirect_run). +void record_trace_dispatch(Wrapper* self, u64 key, UINT x, UINT y, UINT z, bool executed, int outcome) +{ + if (!trace_frame_active || !record_trace_on()) return; + const bool indirect = indirect_current != nullptr; + if (indirect) record_trace_dispatch_noted = true; + const LONG seq = InterlockedIncrement(&dispatch_trace_seq); + const char* state = executed ? "run" : record_trace_outcome(outcome); + const Pass& pass = pass_of(self); + // The manifest's buffer resources, when the key is translated (state 1). + struct Res { bool uav; int kind, source, a, b; }; + std::vector<Res> manifest; + bool have_manifest = false; + if ((key >> 56) == 0x67) { + bool locked = false; + for (int i = 0; i < 200 && !(locked = TryAcquireSRWLockExclusive(&draw_lock)); ++i) Sleep(0); + if (locked) { + const auto found = compute_translations().find(key); + if (found != compute_translations().end() && found->second.state == 1) { + have_manifest = true; + for (const auto& r : found->second.res) manifest.push_back({r.uav, r.kind, r.source, r.a, r.b}); + } + ReleaseSRWLockExclusive(&draw_lock); + } + } + const LONG order = InterlockedIncrement(&record_trace_order); + std::vector<TracedRange> ranges; + const auto add = [&](char label, int param, int offset, u64 address, u64 bytes) { + TracedRange r; + r.seq = seq, r.key = key, r.pipeline = pass.pipeline, r.label = label, r.param = param, r.offset = offset, r.lo = address, r.hi = address + bytes, r.state = state; + r.order = order, r.executed = executed; + ranges.push_back(r); + }; + // (d) image entries: logged after the cx-uav line; texture UAVs become writers once this dispatch is logged. + std::vector<std::string> image_lines; + std::vector<const void*> uav_images; + const auto image_at = [&](char label, int param, int offset, const std::uint32_t* w) { + if (image_lines.size() >= 16) return; + Wrapper* resource = nullptr; + bool uav_view = false; + char text[900]; + if (!record_trace_image(w, text, sizeof(text), &resource, &uav_view)) { + // Neither buffer nor image (refused-view marker, a view token without a usable desc, an "integer + 7 zero + // words" heap-index entry, a sampler, a neighbouring table's bytes): the raw words, so no entry is silent. + bool any = false; + for (int k = 0; k < 8; ++k) any |= w[k] != 0; + if (!any) return; + int n = std::snprintf(text, sizeof(text), "other: words %08x %08x %08x %08x %08x %08x %08x %08x", w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]); + if (w[0] == view_token_magic) { + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = w[1] < view_records().size(); + if (known) record = view_records()[w[1]]; + ReleaseSRWLockShared(¬e_lock); + if (known) std::snprintf(text + n, sizeof(text) - n, " (view token: slot %u, desc %u bytes, resource 0x%llx)", record.slot, record.desc_bytes, + static_cast<unsigned long long>(record.resource)); + else std::snprintf(text + n, sizeof(text) - n, " (view token: unknown view)"); + } else if (w[0] == 0x52463258u) { + std::snprintf(text + n, sizeof(text) - n, " (refused-view marker)"); + } else if (w[0] && !(w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7])) { + std::snprintf(text + n, sizeof(text) - n, " (integer + 7 zero words: a heap index?)"); + } + } + const bool uav = uav_view || label == 'U'; + char line[1100]; + std::snprintf(line, sizeof(line), "x2w-frame cx-img #%ld key %016llx %c p%d+0x%x%s: %s", seq, static_cast<unsigned long long>(key), label, param, + offset, uav ? " (uav)" : "", text); + image_lines.push_back(line); + if (uav && resource) uav_images.push_back(resource); + }; + for (int p = 0; p < 16; ++p) { + const int kind = pass.compute_kind[p]; + const u64 address = pass.compute_address[p]; + if ((kind == 3 || kind == 4) && address) { + add('R', p, 0, address, readable_window(address, 1u << 20)); + } else if (kind == 5 && address) { + const auto entry_at = [&](char label, int offset) { + const u64 entry = address + static_cast<u64>(offset); + std::uint32_t w[8]; + if (!x2w_local::readable(reinterpret_cast<const void*>(entry), 32)) return false; + std::memcpy(w, reinterpret_cast<const void*>(entry), 32); + u64 at = 0, bytes = 0; + if (record_trace_entry(w, &at, &bytes)) add(label, p, offset, at, bytes); + else image_at(label == 'S' ? 'T' : label, p, offset, w); // (d) + return true; + }; + if (have_manifest) { // translated: exactly the manifest's buffers (and, d, images) in this table + for (const Res& r : manifest) + if (r.source == 0 && r.a == p && r.b >= 0) entry_at(r.uav ? 'U' : 'S', r.b); + } else { // not translated: every buffer-shaped (and image) entry of the first 64 + for (int e = 0; e < 64 && entry_at('?', e * 32); ++e) { + } + } + } + } + // (e) heap descriptors named by root constants (ASSUMED rule, see the head of this file). + std::vector<std::string> heap_lines; + { + const TraceHeap heap = record_trace_heap(pass); + // Skipped dispatches: the raw root arguments and the heap used, so the index / base mapping can be checked + // offline (a constant equal to the heap's low 32 bits, or to a table's, is marked). + if (!executed) { + char line[1400]; + int n = std::snprintf(line, sizeof(line), "x2w-frame cx-root #%ld key %016llx: heap 0x%llx (low 0x%08x) count %u increment %u;", seq, + static_cast<unsigned long long>(key), static_cast<unsigned long long>(heap.base), static_cast<std::uint32_t>(heap.base), + heap.count, heap.increment); + for (int p = 0; p < 16 && n < static_cast<int>(sizeof(line)) - 160; ++p) { + const int kind = pass.compute_kind[p]; + if (!kind) continue; + if (kind != 1) { + n += std::snprintf(line + n, sizeof(line) - n, " p%d kind %d 0x%llx (low 0x%08x);", p, kind, + static_cast<unsigned long long>(pass.compute_address[p]), static_cast<std::uint32_t>(pass.compute_address[p])); + continue; + } + n += std::snprintf(line + n, sizeof(line) - n, " p%d constants %u:", p, pass.compute_count[p]); + for (UINT w = 0; w < pass.compute_count[p] && w < 16 && n < static_cast<int>(sizeof(line)) - 40; ++w) { + const std::uint32_t c = pass.compute_constants[p][w]; + bool table_low = false; + for (int q = 0; q < 16; ++q) table_low |= pass.compute_kind[q] == 5 && c && c == static_cast<std::uint32_t>(pass.compute_address[q]); + n += std::snprintf(line + n, sizeof(line) - n, " %08x%s", c, + heap.base && c == static_cast<std::uint32_t>(heap.base) ? "(=heap low)" : table_low ? "(=table low)" : ""); + } + n += std::snprintf(line + n, sizeof(line) - n, ";"); + } + heap_lines.push_back(line); + } + unsigned looked = 0; + std::uint32_t seen[8]; + for (int p = 0; p < 16 && heap.base && looked < 8; ++p) { + if (pass.compute_kind[p] != 1) continue; + for (UINT w = 0; w < pass.compute_count[p] && w < 16 && looked < 8; ++w) { + const std::uint32_t c = pass.compute_constants[p][w]; + const std::uint32_t index = c < heap.count ? c : (c & (1u << 28)) && (c & 0x3ff) < heap.count ? (c & 0x3ff) : 0xffffffffu; + if (index == 0xffffffffu) continue; + bool again = false; + for (unsigned k = 0; k < looked; ++k) again |= seen[k] == index; + if (again) continue; + seen[looked++] = index; + u64 at = 0, bytes = 0; + Wrapper* image = nullptr; + char text[800]; + const bool buffer = record_trace_heap_slot(heap, index, &at, &bytes, text, sizeof(text), &image); + if (buffer) { + add('H', p, static_cast<int>(w * 4), at, bytes); + std::snprintf(text, sizeof(text), "buffer 0x%llx %llu bytes", static_cast<unsigned long long>(at), static_cast<unsigned long long>(bytes)); + } + char line[1100]; + std::snprintf(line, sizeof(line), "x2w-frame cx-heap #%ld key %016llx root constant p%d w%u = 0x%08x -> heap 0x%llx index %u (count %u, increment %u): %s", + seq, static_cast<unsigned long long>(key), p, w, c, static_cast<unsigned long long>(heap.base), index, heap.count, + heap.increment, text); + heap_lines.push_back(line); + } + } + } + char text[1400]; + int n = std::snprintf(text, sizeof(text), "x2w-frame cx-uav #%ld key %016llx ", seq, static_cast<unsigned long long>(key)); + if (indirect) n += std::snprintf(text + n, sizeof(text) - n, "indirect"); + else n += std::snprintf(text + n, sizeof(text) - n, "(%u, %u, %u)", x, y, z); + n += std::snprintf(text + n, sizeof(text) - n, " pipeline %p: %s%s:", static_cast<void*>(pass.pipeline), state, have_manifest || (key >> 56) != 0x67 ? "" : ", no manifest"); + if (ranges.empty()) n += std::snprintf(text + n, sizeof(text) - n, " no buffer bound"); + for (const TracedRange& r : ranges) { + if (n > static_cast<int>(sizeof(text)) - 64) { + log("%s ...", text); + n = std::snprintf(text, sizeof(text), "x2w-frame cx-uav #%ld (cont.):", seq); + } + n += std::snprintf(text + n, sizeof(text) - n, " %c p%d+0x%x 0x%llx %llu;", r.label, r.param, r.offset, + static_cast<unsigned long long>(r.lo), static_cast<unsigned long long>(r.hi - r.lo)); + } + log("%s", text); + for (const std::string& line : image_lines) log("%s", line.c_str()); + for (const std::string& line : heap_lines) log("%s", line.c_str()); + char writer[96]; + std::snprintf(writer, sizeof(writer), "key %016llx #%ld (%s)", static_cast<unsigned long long>(key), seq, state); + AcquireSRWLockExclusive(&record_trace_lock); + traced_ranges().insert(traced_ranges().end(), ranges.begin(), ranges.end()); + for (const void* image : uav_images) traced_image_writers()[image] = writer; + ReleaseSRWLockExclusive(&record_trace_lock); +} + +// (f) d3d12_draw.inl draw_translated, a traced mesh call: one buffer srv it binds (title address and full size). +void record_trace_mesh_read(u64 key, UINT srv, int source, int a, int b, u64 address, u64 bytes) +{ + if (!record_trace_on() || !address || !bytes) return; + TracedMeshRead r; + r.key = key, r.kind = 'S', r.slot = static_cast<int>(srv), r.source = source, r.a = a, r.b = b, r.lo = address, r.hi = address + bytes; + r.order = InterlockedIncrement(&record_trace_order); + AcquireSRWLockExclusive(&record_trace_lock); + traced_mesh_reads().push_back(r); + ReleaseSRWLockExclusive(&record_trace_lock); +} +// (f) the heap buffers a traced mesh call names through root constants the translation reads with bit 28 set +// (index in bits 0-9: the X2W_MESH_DUMP_INPUTS rule, ASSUMED). +void record_trace_mesh_heap(Wrapper* self, const Translation& tr) +{ + if (!record_trace_on()) return; + const Pass& pass = pass_of(self); + const TraceHeap heap = record_trace_heap(pass); + if (!heap.base) return; + std::vector<TracedMeshRead> reads; + for (const Translation::Ud& ud : tr.uds) { + if (ud.kind != Translation::root_constant || ud.a < 0 || ud.a >= 16 || ud.b < 0 || ud.b >= 8) continue; + const std::uint32_t c = pass.constants[ud.a][ud.b]; + if (!(c & (1u << 28)) || (c & 0x3ff) >= heap.count) continue; + u64 at = 0, bytes = 0; + Wrapper* image = nullptr; + char text[800]; + if (!record_trace_heap_slot(heap, c & 0x3ff, &at, &bytes, text, sizeof(text), &image)) continue; + bool again = false; + for (const TracedMeshRead& r : reads) again |= r.lo == at && r.hi == at + bytes; + if (again) continue; + TracedMeshRead r; + r.key = tr.key, r.kind = 'H', r.slot = static_cast<int>(c & 0x3ff), r.a = ud.a, r.b = ud.b, r.lo = at, r.hi = at + bytes; + r.order = InterlockedIncrement(&record_trace_order); + reads.push_back(r); + } + if (reads.empty()) return; + AcquireSRWLockExclusive(&record_trace_lock); + traced_mesh_reads().insert(traced_mesh_reads().end(), reads.begin(), reads.end()); + ReleaseSRWLockExclusive(&record_trace_lock); +} + +// (a) list_execute_indirect, after indirect_execute: the call's record at record time. +void record_trace_indirect(Wrapper* self, UINT type, UINT stride, UINT max_count, Wrapper* arguments, u64 offset) +{ + if (!trace_frame_active || !record_trace_on()) return; + const bool dispatch_noted = record_trace_dispatch_noted; + record_trace_dispatch_noted = false; + TracedRecord t; + t.seq = InterlockedIncrement(&record_trace_seq); + t.type = type, t.stride = stride, t.max_count = max_count, t.list = self, t.wrapper = arguments, t.offset = offset; + const Pass& pass = pass_of(self); + t.dsv = pass.dsv_resource; + t.key = type == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH ? mesh_trace_key + : type == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH ? compute_key_of(self) + : 0; + t.base = arguments && arguments->own().kind == resource_kind ? static_cast<const unsigned char*>(arguments->own().title_memory) : nullptr; + const UINT words = stride / 4 < 4 ? stride / 4 : 4; + if (t.base && words && x2w_local::readable(t.base + offset, words * 4)) { + t.words = words; + std::memcpy(t.at_record, t.base + offset, words * 4); + } + // An indirect Dispatch that never reached execute_dispatch (refused before staging) still gets its cx-uav line. + if (type == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH && !dispatch_noted) { + IndirectPending* const saved = indirect_current; + IndirectPending marker{}; + indirect_current = ▮ // only read as "indirect" by record_trace_dispatch + record_trace_dispatch(self, t.key, 0, 0, 0, false, co_not_run); + record_trace_dispatch_noted = false; + indirect_current = saved; + } + AcquireSRWLockExclusive(&record_trace_lock); + traced_records().push_back(t); + ReleaseSRWLockExclusive(&record_trace_lock); +} + +// (b) + writers. queue: wait for its work first (the busy-frame end); null: read at once (no GPU wait). +void record_trace_report(ID3D12CommandQueue* queue) +{ + if (!record_trace_on()) return; + AcquireSRWLockExclusive(&record_trace_lock); + std::vector<TracedRecord> records; + std::vector<TracedRange> ranges; + std::vector<TracedMeshRead> mesh_reads; + records.swap(traced_records()); + ranges.swap(traced_ranges()); + mesh_reads.swap(traced_mesh_reads()); + traced_image_writers().clear(); + traced_tsharp_bases().clear(); + ReleaseSRWLockExclusive(&record_trace_lock); + InterlockedExchange(&record_trace_seq, 0); + InterlockedExchange(&dispatch_trace_seq, 0); + InterlockedExchange(&record_trace_order, 0); + if (records.empty() && ranges.empty() && mesh_reads.empty()) return; + const char* when = "no GPU wait"; + if (queue && the_device) { + ID3D12Fence* fence = nullptr; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (event && SUCCEEDED(device_of(the_device)->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))) && + SUCCEEDED(queue->Signal(fence, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, event))) + when = WaitForSingleObject(event, 5000) == WAIT_OBJECT_0 ? "after GPU wait on the presenting queue" : "GPU wait timed out"; + if (fence) fence->Release(); + if (event) CloseHandle(event); + } + struct Total { LONG calls = 0, x_record = 0, x_end = 0, unreadable = 0; }; + std::map<std::pair<UINT, const void*>, Total> totals; + std::map<const unsigned char*, std::vector<std::size_t>> by_buffer; + std::vector<std::uint32_t> end_x(records.size()); + for (std::size_t i = 0; i < records.size(); ++i) { + const TracedRecord& t = records[i]; + std::uint32_t at_end[4] = {}; + const bool readable = t.words && x2w_local::readable(t.base + t.offset, t.words * 4); + if (readable) std::memcpy(at_end, t.base + t.offset, t.words * 4); + end_x[i] = at_end[0]; + Total& total = totals[{t.type, t.dsv}]; + ++total.calls; + if (!readable) ++total.unreadable; + if (readable && t.at_record[0]) ++total.x_record; + if (readable && at_end[0]) ++total.x_end; + if (t.base) by_buffer[t.base].push_back(i); + log("x2w-frame record #%ld type %u key %016llx list %p dsv %p args %p+0x%llx (wrapper %p, stride %u, max %u): at record %08x %08x %08x %08x, " + "at end %08x %08x %08x %08x%s", + t.seq, t.type, static_cast<unsigned long long>(t.key), t.list, t.dsv, static_cast<const void*>(t.base), + static_cast<unsigned long long>(t.offset), t.wrapper, t.stride, t.max_count, t.at_record[0], t.at_record[1], t.at_record[2], + t.at_record[3], at_end[0], at_end[1], at_end[2], at_end[3], readable ? "" : " (unreadable)"); + } + for (const auto& [k, total] : totals) + log("x2w-frame record totals type %u dsv %p: calls %ld, X > 0 at record %ld, at end %ld, unreadable %ld (end read %s)", k.first, k.second, + total.calls, total.x_record, total.x_end, total.unreadable, when); + // Writers: per argument buffer, the dispatch ranges that cover at least one of its records. + for (const auto& [base, indices] : by_buffer) { + struct Writer { u64 key; const void* pipeline; char label; int param, offset; u64 lo, hi; const char* state; LONG dispatches = 0, first = 0; std::size_t covered = 0; }; + std::vector<Writer> writers; + for (const TracedRange& r : ranges) { + std::size_t covered = 0; + for (const std::size_t i : indices) { + const u64 at = reinterpret_cast<u64>(base) + records[i].offset; + if (at >= r.lo && at + 4 <= r.hi) ++covered; + } + if (!covered) continue; + Writer* w = nullptr; + for (Writer& existing : writers) + if (existing.key == r.key && existing.pipeline == r.pipeline && existing.label == r.label && existing.param == r.param && existing.offset == r.offset && + existing.lo == r.lo && existing.hi == r.hi && std::strcmp(existing.state, r.state) == 0) + w = &existing; + if (!w) { + writers.push_back({r.key, r.pipeline, r.label, r.param, r.offset, r.lo, r.hi, r.state, 0, r.seq, 0}); + w = &writers.back(); + } + ++w->dispatches; + if (covered > w->covered) w->covered = covered; + } + std::size_t x_end = 0; + for (const std::size_t i : indices) x_end += end_x[i] != 0; + log("x2w-frame record writers args %p: %zu records (X > 0 at end %zu), %zu covering dispatch ranges%s", static_cast<const void*>(base), + indices.size(), x_end, writers.size(), writers.empty() ? " (none of this frame's dispatches binds it)" : ""); + for (std::size_t n = 0; n < writers.size() && n < 32; ++n) { + const Writer& w = writers[n]; + log("x2w-frame record writers args %p: key %016llx pipeline %p %c p%d+0x%x 0x%llx %llu bytes, %s, %ld dispatches (first #%ld), covers %zu records", + static_cast<const void*>(base), static_cast<unsigned long long>(w.key), w.pipeline, w.label, w.param, w.offset, + static_cast<unsigned long long>(w.lo), static_cast<unsigned long long>(w.hi - w.lo), w.state, w.dispatches, w.first, w.covered); + } + if (writers.size() > 32) log("x2w-frame record writers args %p: %zu more not shown", static_cast<const void*>(base), writers.size() - 32); + } + // (f) mesh reads: per distinct (key, kind, slot, range), the dispatch ranges of the frame that overlap it. + struct Read { TracedMeshRead r; LONG calls = 0, first_order = 0; }; + std::vector<Read> distinct; + std::map<std::tuple<u64, char, int, u64, u64>, std::size_t> read_ids; + for (const TracedMeshRead& m : mesh_reads) { + const auto [it, added] = read_ids.try_emplace({m.key, m.kind, m.slot, m.lo, m.hi}, distinct.size()); + if (added) distinct.push_back({m, 0, m.order}); + ++distinct[it->second].calls; + } + struct ByRange { const TracedRange* r; LONG dispatches = 0; std::size_t reads = 0; LONG calls = 0; u64 keys[4] = {}; unsigned nkeys = 0; u64 overlap = 0; }; + struct Hit { const TracedRange* r; LONG dispatches = 0, earliest = 0; ByRange reverse; }; + std::vector<Hit> grouped; + std::map<std::tuple<u64, char, int, int, u64, u64, bool>, std::size_t> range_ids; + for (const TracedRange& r : ranges) { + const auto [it, added] = range_ids.try_emplace({r.key, r.label, r.param, r.offset, r.lo, r.hi, r.executed}, grouped.size()); + if (added) grouped.push_back({&r, 0, r.order, {&r}}); + Hit& h = grouped[it->second]; + ++h.dispatches; + h.earliest = (std::min)(h.earliest, r.order); + } + std::vector<std::size_t> sorted; + for (std::size_t i = 0; i < grouped.size(); ++i) sorted.push_back(i); + std::sort(sorted.begin(), sorted.end(), [&](auto a, auto b) { return grouped[a].r->lo < grouped[b].r->lo; }); + std::size_t leaves = 1; + while (leaves < sorted.size()) leaves *= 2; + std::vector<u64> max_end(2 * leaves); + for (std::size_t i = 0; i < sorted.size(); ++i) max_end[leaves + i] = grouped[sorted[i]].r->hi; + for (std::size_t i = leaves - 1; i; --i) max_end[i] = (std::max)(max_end[2*i], max_end[2*i+1]); + std::size_t in_skipped = 0, in_run_only = 0, in_none = 0, shown = 0, in_skipped_entry = 0; + std::vector<std::string> later; + for (const Read& d : distinct) { + std::vector<std::size_t> hits; + bool skipped = false, entry_hit = false; + // The leftmost start and largest end bound all ranges in this subtree. + auto overlaps = [&](auto&& visit, std::size_t node, std::size_t left, std::size_t right) -> void { + if (left >= sorted.size() || max_end[node] <= d.r.lo || grouped[sorted[left]].r->lo >= d.r.hi) return; + if (right - left > 1) { + const auto mid = left + (right - left) / 2; + visit(visit, node * 2, left, mid); + visit(visit, node * 2 + 1, mid, right); + return; + } + const auto id = sorted[left]; + hits.push_back(id); + Hit& h = grouped[id]; + if (h.r->executed) return; + skipped = true; + entry_hit |= h.r->label != 'R'; + ByRange& b = h.reverse; + ++b.reads; + b.calls += d.calls; + b.overlap += (std::min)(h.r->hi, d.r.hi) - (std::max)(h.r->lo, d.r.lo); + if (b.nkeys < 4 && std::find(b.keys, b.keys + b.nkeys, d.r.key) == b.keys + b.nkeys) + b.keys[b.nkeys++] = d.r.key; + }; + overlaps(overlaps, 1, 0, leaves); + in_skipped_entry += entry_hit; + const auto displayed = (std::min)(hits.size(), std::size_t{6}); + std::partial_sort(hits.begin(), hits.begin() + displayed, hits.end(), [&](auto a, auto b) { + if (grouped[a].r->executed != grouped[b].r->executed) return !grouped[a].r->executed; + return a < b; + }); + if (skipped) ++in_skipped; + else if (!hits.empty()) ++in_run_only; + else ++in_none; + char text[1400]; + int n = std::snprintf(text, sizeof(text), "x2w-frame mesh-read key %016llx %c%d", static_cast<unsigned long long>(d.r.key), d.r.kind, d.r.slot); + if (d.r.kind == 'S') n += std::snprintf(text + n, sizeof(text) - n, " (source %d %d+0x%x)", d.r.source, d.r.a, d.r.b); + else n += std::snprintf(text + n, sizeof(text) - n, " (heap index %d, root constant p%d w%d)", d.r.slot, d.r.a, d.r.b); + n += std::snprintf(text + n, sizeof(text) - n, " 0x%llx %llu bytes, %ld calls: %s", static_cast<unsigned long long>(d.r.lo), + static_cast<unsigned long long>(d.r.hi - d.r.lo), d.calls, + skipped ? "INSIDE a skipped dispatch's range" : hits.empty() ? "no dispatch of this frame binds it" : "run dispatches only"); + for (std::size_t k = 0; k < hits.size() && k < 6 && n < static_cast<int>(sizeof(text)) - 200; ++k) { + const Hit& hit = grouped[hits[k]]; + const TracedRange& r = *hit.r; + const u64 lo = r.lo > d.r.lo ? r.lo : d.r.lo, hi = r.hi < d.r.hi ? r.hi : d.r.hi; + n += std::snprintf(text + n, sizeof(text) - n, "; key %016llx %c p%d+0x%x 0x%llx %llu bytes, %s, %ld dispatches (first #%ld)%s, overlap %llu bytes", + static_cast<unsigned long long>(r.key), r.label, r.param, r.offset, static_cast<unsigned long long>(r.lo), + static_cast<unsigned long long>(r.hi - r.lo), r.state, hit.dispatches, r.seq, + hit.earliest < d.first_order ? " recorded before the first read" : " recorded after the first read", + static_cast<unsigned long long>(hi - lo)); + } + if (hits.size() > 6) std::snprintf(text + n, sizeof(text) - n, "; %zu more", hits.size() - 6); + if (skipped && shown < 64) { + log("%s", text); + ++shown; + } else if (!skipped && later.size() < 64) { + later.push_back(text); + } + } + for (std::size_t k = 0; k < later.size() && shown < 64; ++k, ++shown) log("%s", later[k].c_str()); + std::vector<ByRange> by_range; + for (Hit& h : grouped) { + if (!h.reverse.reads) continue; + h.reverse.dispatches = h.dispatches; + by_range.push_back(h.reverse); + } + std::stable_partition(by_range.begin(), by_range.end(), [](const ByRange& b) { return b.r->label != 'R'; }); + // The reverse view, table / heap entries first, then root windows (R: a readable window, not a size). + for (std::size_t k = 0; k < by_range.size() && k < 256; ++k) { + const ByRange& b = by_range[k]; + char keys[96] = ""; + int n = 0; + for (unsigned j = 0; j < b.nkeys; ++j) n += std::snprintf(keys + n, sizeof(keys) - n, "%s%016llx", j ? " " : "", static_cast<unsigned long long>(b.keys[j])); + log("x2w-frame mesh-read by-range key %016llx %c p%d+0x%x 0x%llx %llu bytes, %s, %ld dispatches (first #%ld)%s: %zu distinct mesh reads, %ld calls, " + "overlap %llu bytes, mesh keys %s%s", + static_cast<unsigned long long>(b.r->key), b.r->label, b.r->param, b.r->offset, static_cast<unsigned long long>(b.r->lo), + static_cast<unsigned long long>(b.r->hi - b.r->lo), b.r->state, b.dispatches, b.r->seq, b.r->label == 'R' ? " (root window)" : "", b.reads, + b.calls, static_cast<unsigned long long>(b.overlap), keys, b.nkeys == 4 ? " ..." : ""); + } + if (by_range.size() > 256) log("x2w-frame mesh-read by-range: %zu more not shown", by_range.size() - 256); + if (!mesh_reads.empty()) + log("x2w-frame mesh-read totals: %zu reads, %zu distinct ranges: %zu inside a skipped dispatch's range (%zu inside a skipped table / heap entry, " + "%zu only inside a skipped root window), %zu run dispatches only, %zu bound by no dispatch of this frame (%zu lines shown, %zu skipped ranges hit)", + mesh_reads.size(), distinct.size(), in_skipped, in_skipped_entry, in_skipped - in_skipped_entry, in_run_only, in_none, shown, by_range.size()); +} +extern "C" __declspec(dllexport) void x2w_d3d12_record_trace_report() { record_trace_report(nullptr); } // fixtures, after their fence diff --git a/src/startup_stubs/d3d12_regblob.inl b/src/startup_stubs/d3d12_regblob.inl new file mode 100644 index 0000000000..9cda0da28c --- /dev/null +++ b/src/startup_stubs/d3d12_regblob.inl @@ -0,0 +1,520 @@ + +namespace regblob { +constexpr std::size_t record_bytes = 0x160, desc_bytes = 0x300; +constexpr int record_words = static_cast<int>(record_bytes / 8); +constexpr std::size_t blob_cap = 1u << 20; +constexpr std::uint32_t states_magic = 0x53573258; // "X2WS" +constexpr std::size_t table_cap = 1u << 18; + +struct Pair { + int word; + const unsigned char* data; + std::size_t bytes; +}; +struct Blob { + int word; + std::vector<unsigned char> bytes; +}; +enum class Kind { set, generic_set, states, derived }; +struct Job { + Kind kind; + u64 key; + std::uint32_t hash = 0; // states: state hash + std::vector<Blob> blobs; // set: every pair except code; generic: every pair; states: 1, 3, 7, 11 + std::vector<unsigned char> record, desc, a, b, root; // sets; derived: record = raw patches + std::vector<std::uint32_t> patch_hashes; // derived + bool generic_base = false; // derived: the base key is a g57 key + std::size_t bytes() const + { + std::size_t n = record.size() + desc.size() + a.size() + b.size() + root.size(); + for (const Blob& blob : blobs) n += blob.bytes.size(); + return n; + } +}; + +SRWLOCK queue_lock = SRWLOCK_INIT; +CONDITION_VARIABLE queue_ready = CONDITION_VARIABLE_INIT; +std::vector<Job>& queue() { static std::vector<Job> q; return q; } +LONG64 bytes_queued, bytes_pending; +LONG sets_written, generic_written, requests_written, states_appended, derived_lines, patch_files, failures; +LONG dropped_backlog, dropped_total, sets_dropped, table_full, queued_jobs; + +// A pointer/length pair at odd word i: pointer 4-aligned in the user range, length 4..cap, readable. +bool pair_at(const u64* w, int i, Pair& out) +{ + const u64 p = w[i], bytes = w[i + 1]; + if (p < 0x10000 || p > 0x00007FFFFFFEFFFFull || (p & 3) || bytes < 4 || bytes > blob_cap) return false; + if (readable_window(p, static_cast<std::size_t>(bytes)) < bytes) return false; + out = {i, reinterpret_cast<const unsigned char*>(p), static_cast<std::size_t>(bytes)}; + return true; +} + +std::vector<unsigned char> bytes_of(const void* data, std::size_t bytes) +{ + const auto* p = static_cast<const unsigned char*>(data); + return std::vector<unsigned char>(p, p + bytes); +} + +// <cache>\regblob\<name> +bool sub_path(wchar_t* out, const wchar_t* name) +{ + wchar_t dir[MAX_PATH]; + const DWORD n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); + if (!n || n >= MAX_PATH - 64) return false; + return swprintf(out, MAX_PATH, L"%s\\regblob\\%s", dir, name) > 0; +} + +bool exists(const wchar_t* path) { return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; } + +bool write_whole(const wchar_t* path, const void* data, std::size_t bytes) +{ + wchar_t temporary[MAX_PATH]; + if (swprintf(temporary, MAX_PATH, L"%s.%lu.%lu.tmp", path, GetCurrentProcessId(), GetCurrentThreadId()) < 0) return false; + HANDLE file = CreateFileW(temporary, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + DWORD written = 0; + const bool complete = WriteFile(file, data, static_cast<DWORD>(bytes), &written, nullptr) && written == bytes; + CloseHandle(file); + if (complete && MoveFileExW(temporary, path, MOVEFILE_REPLACE_EXISTING)) return true; + DeleteFileW(temporary); + return false; +} + +// An appended file: read it whole (for its existing entries), cut it back to valid_end(bytes) once, then +// append. Only the worker thread calls these. +std::vector<unsigned char> read_all(const wchar_t* path) +{ + std::vector<unsigned char> out; + HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) return out; + LARGE_INTEGER size{}; + if (GetFileSizeEx(file, &size) && size.QuadPart > 0 && size.QuadPart < (LONGLONG{64} << 20)) { + out.resize(static_cast<std::size_t>(size.QuadPart)); + DWORD got = 0; + if (!ReadFile(file, out.data(), static_cast<DWORD>(out.size()), &got, nullptr) || got != out.size()) out.clear(); + } + CloseHandle(file); + return out; +} +void cut_to(const wchar_t* path, std::size_t bytes) +{ + HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) return; + LARGE_INTEGER at{}; + at.QuadPart = static_cast<LONGLONG>(bytes); + if (SetFilePointerEx(file, at, nullptr, FILE_BEGIN)) SetEndOfFile(file); + CloseHandle(file); +} +bool append(const wchar_t* path, const void* data, std::size_t bytes) +{ + HANDLE file = CreateFileW(path, FILE_APPEND_DATA, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + DWORD written = 0; + const bool complete = WriteFile(file, data, static_cast<DWORD>(bytes), &written, nullptr) && written == bytes; + CloseHandle(file); + return complete; +} + +void put_u32(std::vector<unsigned char>& out, std::uint32_t v) +{ + out.insert(out.end(), reinterpret_cast<const unsigned char*>(&v), reinterpret_cast<const unsigned char*>(&v) + 4); +} + +const wchar_t* blob_name(int word, wchar_t* out, std::size_t size) +{ + if (word == 1) return L"vsregs"; + if (word == 3) return L"psregs"; + if (word == 7) return L"r78"; + swprintf(out, size, L"p%d", word); + return out; +} + +void write_set(const Job& job) +{ + wchar_t path[MAX_PATH], name[64], part[16]; + bool ok = true; + const bool generic = job.kind == Kind::generic_set; + if (generic) { + swprintf(name, std::size(name), L"g57_%016llx.rec", job.key); + if (!sub_path(path, name)) return; + if (exists(path)) { + swprintf(name, std::size(name), L"g57_%016llx.root", job.key); + if (sub_path(path, name) && !exists(path) && !write_whole(path, job.root.data(), job.root.size())) + InterlockedIncrement(&failures); + return; + } + } else if (!cache_path(path, L"req_", job.key, L".rec")) { + return; + } + const bool blobs = generic || !exists(path); + if (blobs) { + swprintf(name, std::size(name), L"%ls%016llx.desc", generic ? L"g57_" : L"", job.key); + ok = sub_path(path, name) && write_whole(path, job.desc.data(), job.desc.size()) && ok; + for (const Blob& blob : job.blobs) { + const wchar_t* ext = blob_name(blob.word, part, std::size(part)); + const bool in_cache = !generic && (blob.word == 1 || blob.word == 3 || blob.word == 7); + if (in_cache) { + swprintf(name, std::size(name), L".%ls", ext); + ok = cache_path(path, L"req_", job.key, name) && write_whole(path, blob.bytes.data(), blob.bytes.size()) && ok; + } else { + swprintf(name, std::size(name), L"%ls%016llx.%ls", generic ? L"g57_" : L"", job.key, ext); + ok = sub_path(path, name) && write_whole(path, blob.bytes.data(), blob.bytes.size()) && ok; + } + } + if (generic) { + // The root blob hashed into ck: mesh pipelines (code at [13]) need it to be translated. + swprintf(name, std::size(name), L"g57_%016llx.root", job.key); + ok = sub_path(path, name) && write_whole(path, job.root.data(), job.root.size()) && ok; + swprintf(name, std::size(name), L"g57_%016llx.rec", job.key); + ok = ok && sub_path(path, name) && write_whole(path, job.record.data(), job.record.size()); + } else { + ok = ok && cache_path(path, L"req_", job.key, L".rec") && write_whole(path, job.record.data(), job.record.size()); + } + if (ok) InterlockedIncrement(generic ? &generic_written : &sets_written); + } + // The request, in cached_translation's order (.a last); never replaced. Not after a failed set. + if (!generic && ok && !job.a.empty()) { + const struct { const wchar_t* ext; const std::vector<unsigned char>* bytes; } parts[] = { + {L".b", &job.b}, {L".root", &job.root}, {L".a", &job.a}}; + for (const auto& p : parts) { + if (!cache_path(path, L"req_", job.key, p.ext)) { ok = false; break; } + if (exists(path)) continue; + if (!write_whole(path, p.bytes->data(), p.bytes->size())) { ok = false; break; } + if (p.ext[1] == L'a') InterlockedIncrement(&requests_written); + } + } + if (!ok) InterlockedIncrement(&failures); + static LONG logged; + if (blobs && ok && first_calls(logged, 8)) + log("x2w-regblob wrote %ls%016llx (%zu blobs)", generic ? L"regblob\\g57_" : L"req_", job.key, job.blobs.size()); +} + +// Valid prefix of a .states file; collects the state hashes in it. +std::size_t states_valid(const std::vector<unsigned char>& f, std::unordered_set<std::uint32_t>& seen) +{ + std::size_t at = 0; + while (at + 16 <= f.size()) { + std::uint32_t magic, bytes, hash; + std::memcpy(&magic, &f[at], 4); + std::memcpy(&bytes, &f[at + 4], 4); + std::memcpy(&hash, &f[at + 8], 4); + if (magic != states_magic || bytes < 8 || bytes > f.size() - at - 8) break; + seen.insert(hash); + at += 8 + bytes; + } + return at; +} + +void append_states(const Job& job) +{ + static std::unordered_map<u64, std::unordered_set<std::uint32_t>> known; // worker thread only + wchar_t path[MAX_PATH], name[64]; + swprintf(name, std::size(name), L"%016llx.states", job.key); + if (!sub_path(path, name)) return; + auto found = known.find(job.key); + if (found == known.end()) { + found = known.emplace(job.key, std::unordered_set<std::uint32_t>{}).first; + const std::vector<unsigned char> f = read_all(path); + const std::size_t valid = states_valid(f, found->second); + if (valid < f.size()) cut_to(path, valid); + } + if (!found->second.insert(job.hash).second) return; + std::vector<unsigned char> out; + put_u32(out, states_magic); + put_u32(out, 0); + put_u32(out, job.hash); + put_u32(out, static_cast<std::uint32_t>(job.blobs.size())); + for (const Blob& blob : job.blobs) { + put_u32(out, static_cast<std::uint32_t>(blob.word)); + put_u32(out, static_cast<std::uint32_t>(blob.bytes.size())); + out.insert(out.end(), blob.bytes.begin(), blob.bytes.end()); + } + const std::uint32_t after = static_cast<std::uint32_t>(out.size() - 8); + std::memcpy(&out[4], &after, 4); + if (append(path, out.data(), out.size())) InterlockedIncrement(&states_appended); + else InterlockedIncrement(&failures); +} + +void append_derived(const Job& job) +{ + static bool loaded = false; // worker thread only + static std::unordered_set<std::string> lines; + static std::unordered_set<std::uint32_t> records; + wchar_t path[MAX_PATH], name[64]; + if (!sub_path(path, L"d55.txt")) return; + if (!loaded) { + loaded = true; + const std::vector<unsigned char> f = read_all(path); + std::size_t start = 0, valid = 0; + for (std::size_t i = 0; i < f.size(); ++i) + if (f[i] == '\n') { + lines.emplace(reinterpret_cast<const char*>(f.data()) + start, i - start); + start = valid = i + 1; + } + if (valid < f.size()) cut_to(path, valid); + } + char line[64 + 9 * 64]; + int n = std::snprintf(line, sizeof(line), "%s%016llx %zu", job.generic_base ? "g57_" : "", job.key, job.patch_hashes.size()); + for (std::size_t i = 0; i < job.patch_hashes.size() && n < static_cast<int>(sizeof(line)) - 12; ++i) + n += std::snprintf(line + n, sizeof(line) - n, " %08x", job.patch_hashes[i]); + if (!lines.emplace(line, static_cast<std::size_t>(n)).second) return; + constexpr std::size_t record = x2w_derived_blend::record_size; + bool ok = true; + for (std::size_t i = 0; i < job.patch_hashes.size() && (i + 1) * record <= job.record.size(); ++i) { + if (records.count(job.patch_hashes[i])) continue; + swprintf(name, std::size(name), L"d55_%08x.bin", job.patch_hashes[i]); + wchar_t file[MAX_PATH]; + if (!sub_path(file, name)) { ok = false; break; } + if (!exists(file)) { + if (!write_whole(file, job.record.data() + i * record, record)) { ok = false; break; } + InterlockedIncrement(&patch_files); + } + records.insert(job.patch_hashes[i]); + } + line[n++] = '\n'; + // One handle for the run: thousands of lines, and every open is a traced file call under the debugger. + static HANDLE out = INVALID_HANDLE_VALUE; + if (out == INVALID_HANDLE_VALUE) + out = CreateFileW(path, FILE_APPEND_DATA, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + DWORD written = 0; + if (ok && out != INVALID_HANDLE_VALUE && WriteFile(out, line, static_cast<DWORD>(n), &written, nullptr) && + written == static_cast<DWORD>(n)) + InterlockedIncrement(&derived_lines); + else + InterlockedIncrement(&failures); +} + +DWORD __stdcall worker(void*) +{ + wchar_t dir[MAX_PATH]; + if (sub_path(dir, L"")) CreateDirectoryW(dir, nullptr); + std::vector<Job> batch; + for (;;) { + AcquireSRWLockExclusive(&queue_lock); + while (queue().empty()) SleepConditionVariableSRW(&queue_ready, &queue_lock, INFINITE, 0); + batch.swap(queue()); + ReleaseSRWLockExclusive(&queue_lock); + for (const Job& job : batch) { + switch (job.kind) { + case Kind::set: case Kind::generic_set: write_set(job); break; + case Kind::states: append_states(job); break; + case Kind::derived: append_derived(job); break; + } + InterlockedAdd64(&bytes_pending, -static_cast<LONG64>(job.bytes())); + } + batch.clear(); + } +} + +void push(Job&& job) +{ + static const LONG64 cap = [] { + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_REGBLOB_MAX_MB", value, sizeof(value)); + const long mb = n && n < sizeof(value) ? std::strtol(value, nullptr, 10) : 512; + return LONG64{mb > 0 ? mb : 512} << 20; + }(); + const bool set = job.kind == Kind::set || job.kind == Kind::generic_set; + const LONG64 bytes = static_cast<LONG64>(job.bytes()); + // Only state and patch records drop while the writer is behind; a key's first set waits its turn. + if (InterlockedAdd64(&bytes_pending, bytes) > (LONG64{16} << 20) && !set) { + InterlockedAdd64(&bytes_pending, -bytes); + InterlockedIncrement(&dropped_backlog); + return; + } + if (InterlockedAdd64(&bytes_queued, bytes) > cap) { + InterlockedAdd64(&bytes_queued, -bytes); + InterlockedAdd64(&bytes_pending, -bytes); + InterlockedIncrement(&dropped_total); + if (set) InterlockedIncrement(&sets_dropped); + return; + } + static const bool started = [] { + HANDLE thread = CreateThread(nullptr, 0, worker, nullptr, 0, nullptr); + if (thread) CloseHandle(thread); + return thread != nullptr; + }(); + if (!started) { + InterlockedAdd64(&bytes_pending, -bytes); + return; + } + InterlockedIncrement(&queued_jobs); + AcquireSRWLockExclusive(&queue_lock); + queue().push_back(std::move(job)); + ReleaseSRWLockExclusive(&queue_lock); + WakeConditionVariable(&queue_ready); +} + +SRWLOCK key_lock = SRWLOCK_INIT; +// Slot-57 pipeline wrapper -> its key and whether it is a g57 key, for the derived pipelines built on it. +std::unordered_map<const Wrapper*, std::pair<u64, bool>>& keys_of() { static std::unordered_map<const Wrapper*, std::pair<u64, bool>> m; return m; } + +// Device slot 57, after note_pipeline. Returns the key (request key, or the g57 content key). +u64 dump57(const void* desc, const Wrapper* self) +{ + static const bool on = !x2w_local::env_on("X2W_REGBLOB_OFF"); + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_set<u64> keys, states; // handled this run + wchar_t probe[MAX_PATH]; + if (!on || !desc || !cache_path(probe, L"req_", 0, L"") || + readable_window(reinterpret_cast<u64>(desc), record_bytes) < record_bytes) return 0; + u64 w[record_words]; + std::memcpy(w, desc, sizeof(w)); + std::vector<unsigned char> root_blob; + if (Wrapper* root = as_wrapper(reinterpret_cast<const void*>(w[0]))) { + AcquireSRWLockShared(¬e_lock); + const auto found = root_blobs().find(root); + if (found != root_blobs().end()) root_blob = found->second; + ReleaseSRWLockShared(¬e_lock); + } + // The same conditions as translation_for, so the key is the request key. + const auto* a = reinterpret_cast<const void*>(w[5]); + const auto* b = reinterpret_cast<const void*>(w[9]); + const std::size_t a_bytes = static_cast<std::size_t>(w[6]), b_bytes = static_cast<std::size_t>(w[10]); + const bool keyed = !root_blob.empty() && a_bytes && b_bytes && a_bytes <= (1u << 20) && b_bytes <= (1u << 20) && + x2w_local::readable(a, a_bytes) && x2w_local::readable(b, b_bytes); + u64 key = 0, state = 1469598103934665603ull; + if (keyed) { + key = pipeline_key(a, a_bytes, b, b_bytes, root_blob); + for (int i : {1, 3, 7, 11}) { + Pair p; + if (!pair_at(w, i, p)) continue; + state = fnv_bytes(&i, sizeof(i), state); + state = fnv_bytes(p.data, p.bytes, state); + } + } else { + constexpr char seed[] = "x2w-regblob-g57-1"; + key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(seed, sizeof(seed) - 1)); + int pairs = 0; + for (int i = 1; i + 1 < record_words; i += 2) { + Pair p; + if (!pair_at(w, i, p)) continue; + ++pairs; + key = fnv_bytes(&i, sizeof(i), key); + key = fnv_bytes(p.data, p.bytes, key); + } + if (!pairs) return 0; + } + const u64 state_id = fnv_bytes(&state, sizeof(state), key); + AcquireSRWLockExclusive(&lock); + const bool plain = keys.insert(keyed ? key : ~key).second; + bool variant = false; + if (keyed && states.size() < table_cap) variant = states.insert(state_id).second; + else if (keyed && !states.count(state_id)) InterlockedIncrement(&table_full); + ReleaseSRWLockExclusive(&lock); + AcquireSRWLockExclusive(&key_lock); + keys_of()[self] = {key, !keyed}; + ReleaseSRWLockExclusive(&key_lock); + if (plain) { + Job job{keyed ? Kind::set : Kind::generic_set, key}; + job.record = bytes_of(desc, record_bytes); + job.desc = bytes_of(desc, readable_window(reinterpret_cast<u64>(desc), desc_bytes)); + for (int i = 1; i + 1 < record_words; i += 2) { + Pair p; + if ((keyed && (i == 5 || i == 9)) || !pair_at(w, i, p)) continue; + job.blobs.push_back({i, bytes_of(p.data, p.bytes)}); + } + static const bool requests = !x2w_local::env_on("X2W_REGBLOB_REQUESTS_OFF"); + if (keyed && requests) { + job.a = bytes_of(a, a_bytes); + job.b = bytes_of(b, b_bytes); + job.root = root_blob; + } + if (!keyed) job.root = root_blob; // regblob\g57_<ck>.root + push(std::move(job)); + } + if (variant) { + Job job{Kind::states, key}; + job.hash = static_cast<std::uint32_t>(state ^ (state >> 32)); + for (int i : {1, 3, 7, 11}) { + Pair p; + if (pair_at(w, i, p)) job.blobs.push_back({i, bytes_of(p.data, p.bytes)}); + } + push(std::move(job)); + } + return key; +} + +// Hash of one patch record without the bytes the title leaves as garbage: the padding after each blend +// target's write mask, and everything after the desc of a depth-stencil or rasterizer record. +std::uint32_t patch_hash(const unsigned char* record) +{ + constexpr std::size_t size = x2w_derived_blend::record_size; + unsigned char canonical[size]; + std::memcpy(canonical, record, size); + std::uint32_t kind; + std::memcpy(&kind, canonical, sizeof(kind)); + unsigned char* body = canonical + sizeof(kind); + if (kind == 2) { + for (int t = 0; t < 8; ++t) + std::memset(body + offsetof(D3D12_BLEND_DESC, RenderTarget) + t * sizeof(D3D12_RENDER_TARGET_BLEND_DESC) + + offsetof(D3D12_RENDER_TARGET_BLEND_DESC, RenderTargetWriteMask) + 1, 0, 3); + } else if (kind == 0 || kind == 1) { + const std::size_t used = kind == 0 ? sizeof(D3D12_DEPTH_STENCIL_DESC) : sizeof(D3D12_RASTERIZER_DESC); + std::memset(body + used, 0, size - sizeof(kind) - used); + if (kind == 0) std::memset(body + offsetof(D3D12_DEPTH_STENCIL_DESC, StencilWriteMask) + 1, 0, 2); + } + static_assert(sizeof(D3D12_RENDER_TARGET_BLEND_DESC) == offsetof(D3D12_RENDER_TARGET_BLEND_DESC, RenderTargetWriteMask) + 4); + static_assert(offsetof(D3D12_DEPTH_STENCIL_DESC, FrontFace) == offsetof(D3D12_DEPTH_STENCIL_DESC, StencilWriteMask) + 3); + static_assert(sizeof(D3D12_DEPTH_STENCIL_DESC) + sizeof(std::uint32_t) <= size); + static_assert(sizeof(D3D12_RASTERIZER_DESC) + sizeof(std::uint32_t) <= size); + const u64 h = fnv_bytes(canonical, size); + return static_cast<std::uint32_t>(h ^ (h >> 32)); +} + +// Device slot 55 (CreateDerivedPipelineStateX), after note_pipeline: one d55.txt line per distinct +// (base key, patch set). The base is found through the slot-55 base chain (depth 8), as translation_for does. +void dump55(const void* base, const void* patches, std::size_t bytes) +{ + static const bool on = !x2w_local::env_on("X2W_REGBLOB_OFF"); + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_set<u64> seen; + constexpr std::size_t record = x2w_derived_blend::record_size; + wchar_t probe[MAX_PATH]; + if (!on || !patches || !bytes || bytes > 64 * record || bytes % record || !cache_path(probe, L"req_", 0, L"")) return; + const Wrapper* w = as_wrapper(base); + std::pair<u64, bool> found{0, false}; + bool have = false; + for (int depth = 0; w && depth < 8 && !have; ++depth) { + AcquireSRWLockShared(&key_lock); + const auto it = keys_of().find(w); + if (it != keys_of().end()) found = it->second, have = true; + ReleaseSRWLockShared(&key_lock); + if (have) break; + const PipelineInfo* info = pipeline_info(w); + w = info && info->path == 55 ? info->base : nullptr; + } + if (!have) return; + Job job{Kind::derived, found.first}; + job.generic_base = found.second; + const auto* p = static_cast<const unsigned char*>(patches); + u64 set = fnv_bytes(&found, sizeof(found.first)); + for (std::size_t at = 0; at < bytes; at += record) { + job.patch_hashes.push_back(patch_hash(p + at)); + set = fnv_bytes(&job.patch_hashes.back(), 4, set); + } + AcquireSRWLockExclusive(&lock); + bool fresh = false; + if (seen.size() < table_cap) fresh = seen.insert(set).second; + else if (!seen.count(set)) InterlockedIncrement(&table_full); + ReleaseSRWLockExclusive(&lock); + if (!fresh) return; + job.record = bytes_of(patches, bytes); + push(std::move(job)); +} + +// Every 300 frames in render mode (frame heartbeat). +void report() +{ + static const bool on = !x2w_local::env_on("X2W_REGBLOB_OFF"); + if (!on || !queued_jobs) return; + AcquireSRWLockShared(&queue_lock); + const std::size_t pending = queue().size(); + ReleaseSRWLockShared(&queue_lock); + log("x2w-regblob totals: queued %ld (%lld KiB), pending %zu (%lld KiB), sets %ld, unclassified %ld, requests %ld, " + "states %ld, derived lines %ld (patch files %ld), failed %ld; dropped: writer behind %ld, over %s cap %ld " + "(first sets %ld), table full %ld", queued_jobs, bytes_queued >> 10, pending, bytes_pending >> 10, sets_written, + generic_written, requests_written, states_appended, derived_lines, patch_files, failures, dropped_backlog, + "X2W_REGBLOB_MAX_MB", dropped_total, sets_dropped, table_full); +} +} // namespace regblob diff --git a/src/startup_stubs/d3d12_upload_ring.inl b/src/startup_stubs/d3d12_upload_ring.inl new file mode 100644 index 0000000000..b366603092 --- /dev/null +++ b/src/startup_stubs/d3d12_upload_ring.inl @@ -0,0 +1,469 @@ +namespace { +struct RingTag { + UINT chunk = ~0u; + u64 generation = 0; +}; +struct RingChunk { + ID3D12Resource* buffer = nullptr; + unsigned char* mapped = nullptr; + u64 base = 0; // offset of this chunk inside buffer (legacy segments share one buffer) + u64 bytes = 0, used = 0; + u64 first_use = 0, last_use = 0; // sequence numbers + u64 generation = 1; + enum State { free_, in_use, fenced } state = free_; + bool unsafe = false; // legacy: reused before it was free + std::vector<std::pair<ID3D12Fence*, UINT64>> waits; + LONG idle_since = 0; +}; +struct RingList { + u64 reset = 0, close = 0, executed = 0; +}; +struct UploadRing { + SRWLOCK lock = SRWLOCK_INIT; + // 0: the upload ring (mapped upload heap). 1: the indirect argument ring (d3d12_indirect.inl): default heap with + // unordered access, never mapped, written by GPU copies recorded on the list that reads it. + int which = 0; + u64 old_ring = 0; // size of the ring this replaces (would-have-wrapped) + bool ready = false, legacy = false; + u64 chunk_bytes = 0, cap_bytes = 0; + std::vector<RingChunk> chunks; + UINT current = ~0u; + u64 seq = 0; + std::unordered_map<Wrapper*, RingList> lists; + // Counters (since the start; the report line also gives the change since the last line). + u64 reserved = 0, refused_cap = 0, refused_cap_bytes = 0, refused_size = 0, overwritten = 0, overwritten_uses = 0, + would_wrap = 0, reexecuted = 0, made = 0, released = 0, peak_in_use = 0, cache_stale = 0, draws_refused = 0, unfenced = 0, repinned = 0; + u64 last_reserved = 0; + LONG last_report_frame = 0; +}; +UploadRing& upload_ring_state() +{ + static UploadRing r; + return r; +} +UploadRing& indirect_ring_state() +{ + static UploadRing r = [] { + UploadRing made; + made.which = 1; + return made; + }(); + return r; +} +const char* ring_name(const UploadRing& r) { return r.which ? "indirect" : "upload"; } +// Cap refusals on this thread: draw_translated compares it before and after its copies and does not issue a draw +// whose copy was refused. +thread_local u64 ring_cap_refusals; +u64 ring_env(const char* name, u64 fallback) +{ + char value[24]{}; + const DWORD n = GetEnvironmentVariableA(name, value, sizeof(value)); + return n && n < sizeof(value) ? std::strtoull(value, nullptr, 0) : fallback; +} + +// r.lock held. Upload ring: a mapped upload buffer. Indirect ring (gpu): a default-heap buffer with unordered access +// (the argument guard rewrites records in place), resting in COMMON, not mapped. +bool ring_make_buffer(u64 bytes, bool gpu, ID3D12Resource** buffer, unsigned char** mapped) +{ + const D3D12_HEAP_PROPERTIES heap{gpu ? D3D12_HEAP_TYPE_DEFAULT : D3D12_HEAP_TYPE_UPLOAD}; + 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; + if (gpu) desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + ID3D12Resource* created = nullptr; + void* base = nullptr; + if (FAILED(device_of(the_device)->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, + gpu ? D3D12_RESOURCE_STATE_COMMON : D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&created)))) + return false; + if (!gpu && FAILED(created->Map(0, nullptr, &base))) { + created->Release(); + return false; + } + *buffer = created; + *mapped = static_cast<unsigned char*>(base); + return true; +} + +// r.lock held. Upload ring: X2W_UPLOAD_RING[=legacy], _CHUNK_MIB (64), _CAP_MIB (2048), old ring 256 MiB. +// Indirect ring: X2W_INDIRECT_RING[=legacy], _CHUNK_MIB (4), _CAP_MIB (256), old ring 16 MiB. +// Fixtures: X2W_<ring>_RING_TEST_KIB (the old ring / a chunk in KiB), X2W_<ring>_RING_TEST_CAP_CHUNKS. +void ring_setup(UploadRing& r) +{ + r.ready = true; + const bool gpu = r.which == 1; + const auto env = [&](const char* upload_name, const char* indirect_name, u64 fallback) { + return ring_env(gpu ? indirect_name : upload_name, fallback); + }; + char mode[16]{}; + GetEnvironmentVariableA(gpu ? "X2W_INDIRECT_RING" : "X2W_UPLOAD_RING", mode, sizeof(mode)); + r.legacy = !std::strcmp(mode, "legacy"); + const u64 test_kib = env("X2W_UPLOAD_RING_TEST_KIB", "X2W_INDIRECT_RING_TEST_KIB", 0); + r.old_ring = test_kib ? test_kib << 10 : (gpu ? u64{16} : u64{256}) << 20; + if (r.legacy) { + const u64 ring = r.old_ring; + ID3D12Resource* buffer = nullptr; + unsigned char* mapped = nullptr; + if (ring_make_buffer(ring, gpu, &buffer, &mapped)) { + for (UINT i = 0; i < 4; ++i) { + RingChunk c; + c.buffer = buffer; + c.mapped = mapped ? mapped + i * (ring / 4) : nullptr; + c.base = i * (ring / 4); + c.bytes = ring / 4; + r.chunks.push_back(c); + } + r.chunk_bytes = ring / 4; + } + r.cap_bytes = ring; + } else { + r.chunk_bytes = test_kib ? test_kib << 10 : env("X2W_UPLOAD_RING_CHUNK_MIB", "X2W_INDIRECT_RING_CHUNK_MIB", gpu ? 4 : 64) << 20; + r.cap_bytes = env("X2W_UPLOAD_RING_CAP_MIB", "X2W_INDIRECT_RING_CAP_MIB", gpu ? 256 : 2048) << 20; + if (const u64 cap_chunks = env("X2W_UPLOAD_RING_TEST_CAP_CHUNKS", "X2W_INDIRECT_RING_TEST_CAP_CHUNKS", 0)) + r.cap_bytes = cap_chunks * r.chunk_bytes; + if (r.cap_bytes < r.chunk_bytes) r.cap_bytes = r.chunk_bytes; + } + log("x2w-%s ring: %s, %llu KiB chunks, cap %llu MiB%s", ring_name(r), + r.legacy ? "legacy (one ring, wraps without a fence check; tracked as 4 segments)" + : "chain (a chunk is reused only after its lists executed and their fences passed)", + r.chunk_bytes >> 10, r.cap_bytes >> 20, r.legacy && r.chunks.empty() ? ": ring buffer FAILED" : ""); +} + +// r.lock held. Does a live list's current recording still hold chunk c (overlapped its use, not executed yet)? +bool ring_held_by_lists(const UploadRing& r, const RingChunk& c) +{ + for (const auto& [list, l] : r.lists) { + if (!l.reset || l.reset > c.last_use) continue; // never recorded, or re-recorded after the last use + if (l.close && l.close < c.first_use) continue; // closed before the chunk was first used + if (l.close && l.executed > l.close) continue; // that recording was executed + return true; + } + return false; +} + +// r.lock held. Moves chunks along in_use -> fenced -> free. +void ring_poll(UploadRing& r) +{ + std::vector<std::pair<ID3D12Fence*, UINT64>> now; + bool now_taken = false, unfenced = false; + for (UINT i = 0; i < r.chunks.size(); ++i) { + RingChunk& c = r.chunks[i]; + if (c.state == RingChunk::in_use && i != r.current && !ring_held_by_lists(r, c)) { + if (!now_taken) { + AcquireSRWLockShared(&allocator_lock); + for (const auto& [queue, submit] : queue_submits) { + if (submit.first) now.push_back(submit); + else unfenced = true; // note_submits could not make this queue's fence: nothing to wait on + } + ReleaseSRWLockShared(&allocator_lock); + now_taken = true; + } + if (unfenced) { + ++r.unfenced; // kept in use: a queue without a submit fence cannot prove the GPU is done + continue; + } + c.waits = now; + c.state = RingChunk::fenced; + } + if (c.state == RingChunk::fenced) { + bool passed = true; + for (const auto& [fence, value] : c.waits) passed &= fence->GetCompletedValue() >= value; + if (passed) { + c.state = RingChunk::free_; + ++c.generation; // cached frame copies in it are gone + c.idle_since = frame_number; + } + } + } + // Chain: keep at most 4 free chunks (256 MiB at the default size); release the rest after 300 idle frames. + if (!r.legacy) { + UINT free_count = 0; + for (UINT i = 0; i < r.chunks.size(); ++i) { + RingChunk& c = r.chunks[i]; + if (c.state != RingChunk::free_ || !c.buffer) continue; + if (++free_count > 4 && frame_number - c.idle_since > 300) { + c.buffer->Release(); + c.buffer = nullptr; + c.mapped = nullptr; + ++r.released; + } + } + } +} + +// r.lock held. Bytes in chunks that are not free (in use or waiting for fences). +u64 ring_in_use(const UploadRing& r) +{ + u64 bytes = 0; + for (const RingChunk& c : r.chunks) + if (c.buffer && c.state != RingChunk::free_) bytes += c.bytes; + return bytes; +} + +// r.lock held. A chunk to write into next, or ~0u (chain at its cap). +UINT ring_next_chunk(UploadRing& r) +{ + if (r.legacy) { + if (r.chunks.empty()) return ~0u; + const UINT next = r.current == ~0u ? 0 : (r.current + 1) % 4; + RingChunk& c = r.chunks[next]; + if (c.state != RingChunk::free_) ring_poll(r); + c.unsafe = c.state != RingChunk::free_; // the old ring reuses it anyway: count what it overwrites + ++c.generation; + return next; + } + ring_poll(r); + for (UINT i = 0; i < r.chunks.size(); ++i) + if (r.chunks[i].state == RingChunk::free_ && r.chunks[i].buffer && i != r.current) return i; + u64 live = 0; + for (const RingChunk& c : r.chunks) live += c.buffer ? c.bytes : 0; + if (live + r.chunk_bytes > r.cap_bytes) return ~0u; + RingChunk c; + c.bytes = r.chunk_bytes; + if (!ring_make_buffer(c.bytes, r.which == 1, &c.buffer, &c.mapped)) return ~0u; + ++r.made; + for (UINT i = 0; i < r.chunks.size(); ++i) + if (!r.chunks[i].buffer) { // reuse a released slot (keeps its generation counting up) + c.generation = r.chunks[i].generation + 1; + r.chunks[i] = c; + return i; + } + r.chunks.push_back(c); + return static_cast<UINT>(r.chunks.size() - 1); +} +} // namespace + +// A slice of `bytes` for copies the GPU reads from a list recorded now. Returns its CPU address and sets the +// buffer and offset to bind (and the tag frame_copy keeps), or nullptr when refused. +// Both rings: a slice of `bytes` rounded to `align`. Returns false when refused (size, or the cap: counted, logged). +bool ring_reserve(UploadRing& r, std::size_t bytes, u64 align, u64* offset, ID3D12Resource** buffer, unsigned char** cpu_out, RingTag* tag) +{ + const bool upload = r.which == 0; + AcquireSRWLockExclusive(&r.lock); + if (!r.ready) ring_setup(r); + const u64 rounded = (bytes + align - 1) & ~(align - 1); + if (!bytes || rounded > r.chunk_bytes || (r.legacy && r.chunks.empty())) { + ++r.refused_size; + ReleaseSRWLockExclusive(&r.lock); + if (upload) x2w_memcut::note_ring_refused(); + return false; + } + if (r.current == ~0u || r.chunks[r.current].used + rounded > r.chunks[r.current].bytes) { + const UINT next = ring_next_chunk(r); + if (next == ~0u) { + if (upload) ++ring_cap_refusals; // draw_translated: the draw is not issued + ++r.refused_cap; + r.refused_cap_bytes += rounded; + const u64 refused = r.refused_cap; + ReleaseSRWLockExclusive(&r.lock); + if (upload) x2w_memcut::note_ring_refused(); + if (refused <= 8 || refused % 4096 == 0) + log("x2w-%s ring: refused %zu bytes at frame %ld: the chain is at its cap (X2W_%s_RING_CAP_MIB) and no chunk is free " + "yet; %s (refusal %llu)", ring_name(r), bytes, frame_number, upload ? "UPLOAD" : "INDIRECT", + upload ? "the copy fails" : "the indirect call is skipped (no-ring)", refused); + return false; + } + r.current = next; + RingChunk& c = r.chunks[next]; + c.state = RingChunk::in_use; + c.used = 0; + c.first_use = ++r.seq; + c.waits.clear(); + } + RingChunk& c = r.chunks[r.current]; + const u64 at = c.used; + c.used += rounded; + c.last_use = ++r.seq; + r.reserved += rounded; + const bool first_overwrite = c.unsafe && !r.overwritten_uses; + if (c.unsafe) r.overwritten += rounded, ++r.overwritten_uses; + const u64 in_use = ring_in_use(r); + if (in_use > r.peak_in_use) r.peak_in_use = in_use; + // The old ring (its size, or the test size) would have handed out unread / unexecuted space here. + const bool first_wrap = !r.legacy && in_use > r.old_ring && !r.would_wrap; + if (!r.legacy && in_use > r.old_ring) r.would_wrap += rounded; + *offset = c.base + at; + *buffer = c.buffer; + if (tag) *tag = RingTag{r.current, c.generation}; + if (cpu_out) *cpu_out = c.mapped ? c.mapped + at : nullptr; + ReleaseSRWLockExclusive(&r.lock); + if (upload) x2w_memcut::note_ring(frame_number, rounded); // LOCAL memcut + if (first_overwrite) + log(upload ? "x2w-upload ring (legacy): first copy written over ring data the GPU had not read yet (frame %ld, %zu bytes)" + : "x2w-indirect ring (legacy): first slot reused while a list holding it had not executed or its fence had not passed " + "(frame %ld, %zu bytes)", + frame_number, bytes); + if (first_wrap) + log("x2w-%s ring (chain): first %s past the old ring's size while all of it is still unread (frame %ld): the old ring " + "would have reused unread space here", ring_name(r), upload ? "copy" : "record", frame_number); + return true; +} + +unsigned char* reserve_upload_ring(std::size_t bytes, u64* offset, ID3D12Resource** buffer, RingTag* tag) +{ + unsigned char* cpu = nullptr; + // 512: texture footprints are placed in the ring too + return ring_reserve(upload_ring_state(), bytes, 512, offset, buffer, &cpu, tag) ? cpu : nullptr; +} + +// d3d12_indirect.inl: ring space for one call's record (+ count), in 256-byte slots. The chunk to copy into and to +// read the arguments from, or nullptr when refused (the call is skipped as no-ring). +ID3D12Resource* reserve_indirect_ring(u64 bytes, u64* offset) +{ + ID3D12Resource* buffer = nullptr; + return ring_reserve(indirect_ring_state(), static_cast<std::size_t>(bytes), 256, offset, &buffer, nullptr, nullptr) ? buffer : nullptr; +} + +// frame_copy cache hit: the slice may be bound again only while its chunk was not recycled. Marks the use. +bool ring_touch(const RingTag& tag) +{ + UploadRing& r = upload_ring_state(); + AcquireSRWLockExclusive(&r.lock); + RingChunk* c = tag.chunk < r.chunks.size() ? &r.chunks[tag.chunk] : nullptr; + // Same generation = not recycled since the copy was made; a recycled chunk is free or in use again. + const bool same = c && c->buffer && c->generation == tag.generation && c->state != RingChunk::free_; + if (!same) ++r.cache_stale; + // Fixtures only: X2W_UPLOAD_RING_TEST_NO_REPIN=1 skips the re-pin (the negative control of the reuse case). + static const bool no_repin = ring_env("X2W_UPLOAD_RING_TEST_NO_REPIN", 0) != 0; + bool first_repin = false; + if (same) { + c->last_use = ++r.seq; + // A chunk waiting for its fences is pinned again: the list binding it now may not have executed yet, and the + // fence snapshot was taken before this use. The next poll checks it against the lists again. + if (c->state == RingChunk::fenced && !no_repin) { + c->state = RingChunk::in_use; + c->waits.clear(); + first_repin = !r.repinned++; + } + } + ReleaseSRWLockExclusive(&r.lock); + if (first_repin) + log("x2w-upload ring: first cached copy bound again from a chunk waiting for its fences (frame %ld): the chunk is in use " + "again until the list binding it has executed", frame_number); + return same || r.legacy; // legacy: as before, the cache trusts its offset (stale hits are only counted) +} + +// draw_translated: a draw not issued because one of its copies was refused at the cap. +void ring_draw_refused(u64 key) +{ + UploadRing& r = upload_ring_state(); + AcquireSRWLockExclusive(&r.lock); + const u64 n = ++r.draws_refused; + ReleaseSRWLockExclusive(&r.lock); + if (n <= 8 || n % 4096 == 0) + log("x2w-upload ring: draw %016llx not issued at frame %ld: a copy it needs was refused (chain at its cap); refused draws %llu", + key, frame_number, n); +} + +// Hooks: list Reset / Close succeeded, lists executed (draw_lock held, after note_submits), list destroyed. +// Each hook updates both rings (the upload ring and the indirect argument ring). +void ring_list_reset(Wrapper* list) +{ + for (UploadRing* r : {&upload_ring_state(), &indirect_ring_state()}) { + AcquireSRWLockExclusive(&r->lock); + RingList& l = r->lists[list]; + l.reset = ++r->seq; + l.close = 0; + ReleaseSRWLockExclusive(&r->lock); + } +} +void ring_list_close(Wrapper* list) +{ + for (UploadRing* r : {&upload_ring_state(), &indirect_ring_state()}) { + AcquireSRWLockExclusive(&r->lock); + if (const auto l = r->lists.find(list); l != r->lists.end()) l->second.close = ++r->seq; + ReleaseSRWLockExclusive(&r->lock); + } +} +void ring_list_gone(Wrapper* list) +{ + for (UploadRing* r : {&upload_ring_state(), &indirect_ring_state()}) { + AcquireSRWLockExclusive(&r->lock); + r->lists.erase(list); + ReleaseSRWLockExclusive(&r->lock); + } +} +void ring_submitted_one(UploadRing& r, const std::vector<Wrapper*>& lists); +void ring_submitted(const std::vector<Wrapper*>& lists) +{ + ring_submitted_one(upload_ring_state(), lists); + ring_submitted_one(indirect_ring_state(), lists); +} +void ring_submitted_one(UploadRing& r, const std::vector<Wrapper*>& lists) +{ + AcquireSRWLockExclusive(&r.lock); + for (Wrapper* w : lists) + if (const auto l = r.lists.find(w); l != r.lists.end()) { + if (l->second.executed > l->second.close && l->second.close) ++r.reexecuted; // the same recording again + l->second.executed = ++r.seq; + } + if (r.ready) ring_poll(r); + const LONG frame = frame_number; + const bool report = r.ready && frame - r.last_report_frame >= 300; + char line[1024]; + if (report) { + r.last_report_frame = frame; + UINT total = 0, in_use = 0, fenced = 0, free_count = 0; + u64 held = 0; + for (const RingChunk& c : r.chunks) { + if (!c.buffer) continue; + ++total; + in_use += c.state == RingChunk::in_use; + fenced += c.state == RingChunk::fenced; + free_count += c.state == RingChunk::free_; + held += c.state == RingChunk::in_use && ring_held_by_lists(r, c); + } + // Upload ring in MiB; the indirect ring (256-byte records) in KiB. + const int shift = r.which ? 10 : 20; + const char* unit = r.which ? "KiB" : "MiB"; + const u64 total_bytes = r.legacy ? (r.chunks.empty() ? 0 : 4 * r.chunk_bytes) : total * r.chunk_bytes; + std::snprintf(line, sizeof(line), + "x2w-%s ring (frame %ld, %s): chunks %u (%llu %s: in use %u, %llu of them held by unexecuted lists, waiting for " + "fences %u, free %u), peak in use %llu %s, reserved %llu %s since the last line (%llu %s total), refused at " + "the cap %llu (%llu %s, draws not issued %llu), refused over the chunk size %llu, %s %llu %s in %llu " + "uses, would have wrapped in the old ring %llu %s, re-executed recordings %llu, stale cache hits %llu, chunks " + "made %llu released %llu, lists %zu, kept for a queue without a fence %llu", + ring_name(r), frame, r.legacy ? "legacy" : "chain", total, total_bytes >> shift, unit, in_use, held, fenced, free_count, + r.peak_in_use >> shift, unit, (r.reserved - r.last_reserved) >> shift, unit, r.reserved >> shift, unit, r.refused_cap, + r.refused_cap_bytes >> shift, unit, r.draws_refused, r.refused_size, + r.which ? "slots reused while a list holding them had not executed" : "written over data the GPU had not read", + r.overwritten >> shift, unit, r.overwritten_uses, r.would_wrap >> shift, unit, r.reexecuted, r.cache_stale, r.made, + r.released, r.lists.size(), r.unfenced); + r.last_reserved = r.reserved; + } + ReleaseSRWLockExclusive(&r.lock); + static LONG reports[2]; + if (report && first_calls(reports[r.which], 400)) log("%s", line); +} + +// Fixtures (export x2w_upload_ring_test, after the file's namespace): counters by index (0 reserved, 1 refused at +// the cap, 2 overwritten bytes, 3 would-wrap bytes, 4 chunks with a buffer, 5 stale cache hits, 6 legacy, 7 draws +// not issued, 8 chunks made, 9 fenced chunks re-pinned by a cache hit). 100 + index: the same for the indirect ring +// (2 = slot bytes reused while a list holding them had not executed, in legacy mode). +unsigned long long upload_ring_counter(int what) +{ + UploadRing& r = what >= 100 ? indirect_ring_state() : upload_ring_state(); + if (what >= 100) what -= 100; + AcquireSRWLockShared(&r.lock); + u64 v = 0; + switch (what) { + case 0: v = r.reserved; break; + case 1: v = r.refused_cap; break; + case 2: v = r.overwritten; break; + case 3: v = r.would_wrap; break; + case 4: for (const RingChunk& c : r.chunks) v += c.buffer != nullptr; break; + case 5: v = r.cache_stale; break; + case 6: v = r.legacy; break; + case 7: v = r.draws_refused; break; + case 8: v = r.made; break; + case 9: v = r.repinned; break; + default: break; + } + ReleaseSRWLockShared(&r.lock); + return v; +} diff --git a/src/startup_stubs/d3d12_vdesc.inl b/src/startup_stubs/d3d12_vdesc.inl new file mode 100644 index 0000000000..83eb6b488d --- /dev/null +++ b/src/startup_stubs/d3d12_vdesc.inl @@ -0,0 +1,70 @@ +// Local experiment (never upstream): vdesc, the gfx10 descriptor words of heap views (agent meshrt). +// Included inside d3d12_xs_device.cpp's anonymous namespace, right after d3d12_compute.inl. +// +// A translated program that reads the WORDS of a resource-heap descriptor as numbers (manifest `heapwords 1`, +// mesh_work/RUNTIME_NEEDS.md 6.3): word 3 of a buffer V# (format, swizzle) for typed buffer loads through a heap +// descriptor, T# words 1-3 (width, height, mips) for image programs. The heap slots hold view tokens (X2WV + id), +// so the words come from a buffer indexed by the same view id as vinfo: 32 bytes per id (8 dwords, the words +// gfx10_view_words.h synthesises; view_record_words in d3d12_compute.inl, shared with `udsrc descword`), zeros +// for ids without words. Bound as root SRV t2 space1 (create_draw_root, after heapmem t0 and vinfo t1). +// +// Inert unless a manifest asks: the buffer (view_ids_max x 32 bytes = 2.9 MB, upload heap) is created by the +// first bound `heapwords 1` translation and then filled for every view fill_view_kinds fills (draw_lock held). + +ID3D12Resource* vdesc_buffer; +std::uint32_t* vdesc_words; +LONG vdesc_image, vdesc_buffer_views, vdesc_none; // ids filled, by kind (totals) + +// fill_view_kinds (d3d12_compute.inl), for every view record it fills; draw_lock held. +void vdesc_fill(const ViewRecord& record) +{ + if (!vdesc_words || record.id >= view_ids_max) return; + std::uint32_t out[8]; + bool image = false, unmapped = false; + const bool made = view_record_words(record, out, &image, &unmapped); // out is zero when !made + // RUNTIME_NEEDS 6.3.3: programs treat word 1 == 0 as a null view, so a live image view never has it: set + // MIN_LOD bit 8 (no program reads it). Only here; descword keeps the plain words. + if (made && image && out[1] == 0) out[1] = 1u << 8; + std::memcpy(vdesc_words + u64{record.id} * 8, out, 32); + InterlockedIncrement(!made ? &vdesc_none : image ? &vdesc_image : &vdesc_buffer_views); + static LONG shown; + if (made && first_calls(shown, 4)) + log("x2w-vdesc view %u (slot %u): %s words %08x %08x %08x %08x %08x %08x %08x %08x%s", record.id, record.slot, image ? "T#" : "V#", + out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7], unmapped ? " (format has no gfx10 code: FORMAT 0)" : ""); +} + +// draw_translated (d3d12_draw.inl), a `heapwords 1` translation, after fill_views; draw_lock held. Creates the +// buffer on first use and fills the views filled so far. False: no buffer (the draw / mesh call is skipped). +bool ensure_vdesc() +{ + static bool failed; + if (vdesc_words || failed) return vdesc_words != nullptr; + D3D12_HEAP_PROPERTIES up{D3D12_HEAP_TYPE_UPLOAD}; + D3D12_RESOURCE_DESC rd{}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rd.Width = u64{view_ids_max} * 32; + rd.Height = rd.DepthOrArraySize = rd.MipLevels = 1; + rd.SampleDesc.Count = 1; + rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + const HRESULT hr = device_of(the_device)->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&vdesc_buffer)); + std::uint32_t* words = nullptr; + if (SUCCEEDED(hr) && FAILED(vdesc_buffer->Map(0, nullptr, reinterpret_cast<void**>(&words)))) words = nullptr; + if (!words) { + failed = true; + log("x2w-vdesc buffer (%llu bytes) -> 0x%08lx: heapwords translations are skipped", static_cast<unsigned long long>(rd.Width), + static_cast<unsigned long>(hr)); + return false; + } + std::memset(words, 0, static_cast<std::size_t>(rd.Width)); + vdesc_words = words; + for (UINT i = 0; i < views_filled; ++i) { + AcquireSRWLockShared(¬e_lock); + const ViewRecord record = view_records()[i]; + ReleaseSRWLockShared(¬e_lock); + vdesc_fill(record); + } + log("x2w-vdesc buffer %u ids x 32 bytes at desktop 0x%llx; %u views filled so far (T# %ld, V# %ld, none %ld)", view_ids_max, + static_cast<unsigned long long>(vdesc_buffer->GetGPUVirtualAddress()), views_filled, vdesc_image, vdesc_buffer_views, vdesc_none); + return true; +} diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 292937af1c..29d827c00b 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -16,9 +16,20 @@ #include "x2w_build_rev.h" #include "xmem_page_batch.h" #include "startup_stubs/local_log.h" +#include "xmem_low.h" +#include "startup_stubs/frame_rgb_sample.h" + +#include <algorithm> +#include <deque> +#include <map> +#include <tuple> +#include <d3d12.h> #include "startup_stubs/logical_view_table.h" #include "startup_stubs/list_compute_root.h" +#include "startup_stubs/placed_pool.h" +#include "startup_stubs/small_texture_heap.h" #include "startup_stubs/overlay_window.h" +#include "startup_stubs/title_composition.h" #include "startup_stubs/draw_bmp.h" #include "startup_stubs/draw_dump_tracking.h" #include "startup_stubs/translated_sampler_bindings.h" @@ -31,6 +42,9 @@ #include "startup_stubs/indexed_rect_geometry.h" #include "startup_stubs/bc7_4k_s.h" #include "startup_stubs/bc64_chain.h" +#include "startup_stubs/gpu_resident_mips.h" +#include "startup_stubs/gfx10_layout_local.h" // LOCAL (textures): X2W_MEMORY_SRV_DETILE (x2w_startup::gfx10_local) +#include "startup_stubs/buffer_address_index.h" // LOCAL (textures): existing_memory_buffer's address index #include "startup_stubs/address_texture.h" #include "startup_stubs/list_upload_pages.h" #include "startup_stubs/resource_budget.h" @@ -64,10 +78,36 @@ #include "null_binding_cause.h" #include "null_texture_view.h" #include "packed_target_format.h" +#include "gpu_srgb.h" +#include "gpu_read_states.h" +#include "gpu_build_queue.h" +#include "gpu_warm_bad.h" +#include "gpu_pipeline_record.h" +#include "gpu_reference_library.h" +#include "startup_stubs/gpu_trace_request.h" +#include "startup_stubs/gpu_transition.h" +#include <filesystem> +#include <fstream> #include "present_view_format.h" #include "state_block_blend.h" #include "title_heap_memory.h" +#include "gfx10_view_words.h" +#include "gfx10_raw_vdesc.h" +#include <xmmintrin.h> // _mm_sfence (d3d12_heap_raw.inl: the upload-heap table) +#include "startup_stubs/rawaddr_table.h" // LOCAL raw-address shaders (d3d12_rawaddr.inl) +#include "startup_stubs/d3d12_mem_counters.h" // LOCAL memcut counters +#include "xmem_section_lease.h" #include "startup_stubs/xmem_section_buffer.h" +// Translated shader ABI (X2W_GPU_ABI=1, PLAN.md WP0-WP5): the standalone headers; the hook prototypes follow +// struct Wrapper. +#include "startup_stubs/gpu_abi.h" +#include "startup_stubs/gpu_view_trace.h" +#include "startup_stubs/gpu_db.h" +#include "startup_stubs/gpu_roots.h" +#include "startup_stubs/gpu_list_states.h" +#include "startup_stubs/gpu_pipeline_state.h" +#include "startup_stubs/gpu_heap.h" +#include "startup_stubs/gpu_indirect_clamp.h" #include <d3d12sdklayers.h> #include <d3d12shader.h> #include <d3dcompiler.h> @@ -151,6 +191,7 @@ enum class RetireLeft : std::uint8_t { none, view, view_copy, residency, present struct alignas(16) WrapperOwn { IUnknown* real; LONG refs; + LONG cold_texture_state; // See d3d12_cold_texture.inl; zero unless the opt-in owns this committed texture. Kind kind; x2w_budget::Ticket* budget; x2w_budget::Ticket* backing_budget; @@ -162,8 +203,15 @@ 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. + ID3D12Resource* plane_copy_scratch; // Owned by this recording's desktop allocator. bool list_close_failed; // Desktop Reset repeats a failed Close result indefinitely. + unsigned char srgb_uav_format; // Original typed format of a typeless sRGB/UAV backing texture. bool tiled_address_srv; // Resource backed by 4 KiB tiled guest memory for translated draws. + bool linear_memory_srv : 1; // LOCAL (video): texture made by X2W_MEMORY_SRV_LINEAR; 1D/3D ones are uploaded too. + bool partial_mip_srv : 1; // detiled late descriptor, possibly only a coarse suffix is resident + bool detiled_memory_srv : 1; // LOCAL (textures): with linear_memory_srv, its title memory is console-swizzled + // (X2W_MEMORY_SRV_DETILE, gfx10_layout.h) and upload_texture detiles it. A bit + // field next to linear_memory_srv keeps WrapperOwn's size. 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 @@ -192,6 +240,9 @@ struct alignas(16) WrapperOwn { u64 mesh86_key{}; UINT list_node_mask; D3D12_QUERY_HEAP_DESC query_heap; // QueryHeap: the desc it was created with (device slot 39) + // Translated shader ABI (gpu_hooks.h): [0] pipeline WP2 / descriptor heap WP5 / command list WP3, [1] command + // list WP4. + void* gpu[2]; }; static_assert(sizeof(WrapperOwn) % 16 == 0, "the title-visible object must stay 16-byte aligned"); struct Wrapper { @@ -199,6 +250,7 @@ struct Wrapper { std::uint64_t console_fields[0x7f]; // +0x08..+0x400 (more for command lists), zero until the title writes WrapperOwn& own() const { return const_cast<WrapperOwn*>(reinterpret_cast<const WrapperOwn*>(this))[-1]; } }; +#include "startup_stubs/gpu_hooks.h" // Translated shader ABI hook prototypes (inside this anonymous namespace) void fence_reached(Wrapper* fence, std::uint64_t value) noexcept { @@ -228,6 +280,212 @@ struct DescriptorRange { SRWLOCK descriptor_lock = SRWLOCK_INIT; std::vector<DescriptorRange> descriptor_ranges; +// LOCAL (video): X2W_NOOP_CENSUS=1 counts the calls of every unimplemented (no-op) slot per object +// kind, and logs the first calls whose register or stack arguments (or the first 64 bytes they point +// to, for the first 64 calls of each slot) hold a descriptor handle inside a title or desktop heap +// range. A console "create view" or "write descriptors" entry point would show up here with handles +// into the main heap. At most 6 hits per slot and 240 in all; stack words are marked "weak" (stale +// caller stack often holds old pointers). Totals at 1024, 2048, 4096, ... no-op calls, one line per kind. +// The same switch logs views that view_slot drops because their destination does not translate. +LONG64 noop_census[16][512]; +LONG noop_census_hits[16][512]; +LONG64 noop_census_total; +bool noop_census_on() +{ + static const bool on = [] { + char value[4]{}; + return GetEnvironmentVariableA("X2W_NOOP_CENSUS", value, sizeof(value)) && value[0] == '1'; + }(); + return on; +} +void log(const char* format, ...); +bool first_calls(LONG& counter, LONG limit); +int range_watch_count(); // X2W_RANGE_WATCH, below +int range_watch_hit(std::uint64_t address, std::uint64_t bytes); +bool range_watch_line(int i); +std::uint64_t range_watch_address(int i); +extern LONG frame_number; +bool noop_census_enabled() +{ + static const bool on = [] { + if (noop_census_on()) log("x2w-noop-census on: counting no-op slot calls and descriptor handles in their arguments"); + return noop_census_on(); + }(); + return on; +} +struct CensusHeap { + std::uint64_t base, index, count; + bool desktop; +}; +bool noop_census_heap_index(std::uint64_t value, CensusHeap* out) +{ + if (value < 0x10000) return false; + bool found = false; + AcquireSRWLockShared(&descriptor_lock); + for (const auto& r : descriptor_ranges) { + if (r.title >= 0x10000 && r.title_stride && value >= r.title && value < r.title + r.bytes) { + *out = {r.title, (value - r.title) / r.title_stride, r.bytes / r.title_stride, false}; + found = true; + break; + } + if (r.desktop >= 0x10000 && r.desktop_stride && value >= r.desktop && value < r.desktop + r.desktop_descriptors * r.desktop_stride) { + *out = {r.desktop, (value - r.desktop) / r.desktop_stride, r.desktop_descriptors, true}; + found = true; + break; + } + } + ReleaseSRWLockShared(&descriptor_lock); + return found; +} +bool noop_census_hit(int kind, int slot) +{ + static LONG hits; + return hits < 240 && InterlockedIncrement(&noop_census_hits[kind & 15][slot & 511]) <= 6 && first_calls(hits, 240); +} +void noop_census_note(int kind, int slot, const std::uint64_t* args, std::uint64_t ret) +{ + const LONG64 calls = InterlockedIncrement64(&noop_census[kind & 15][slot & 511]); + const LONG64 total = InterlockedIncrement64(&noop_census_total); + static const char* const names[8] = {"rcx", "rdx", "r8", "r9", "s0", "s1", "s2", "s3"}; + for (int i = 1; i < 8 && range_watch_count(); ++i) { + const int r = range_watch_hit(args[i], 1); + if (r >= 0 && range_watch_line(r)) + log("x2w-watch 0x%llx: no-op %s::slot%d call %lld %s=0x%llx frame %ld; ret=+0x%llx", range_watch_address(r), kind_names[kind], + slot, calls, names[i], args[i], frame_number, ret); + std::uint64_t words[8]{}; + SIZE_T got = 0; + if (args[i] < 0x10000 || r >= 0 || + !ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<const void*>(args[i]), words, sizeof(words), &got) || got != sizeof(words)) + continue; + for (int w = 0; w < 8; ++w) { + const int rw = range_watch_hit(words[w], 1); + if (rw >= 0 && range_watch_line(rw)) + log("x2w-watch 0x%llx: no-op %s::slot%d call %lld [%s+0x%x]=0x%llx frame %ld; ret=+0x%llx", range_watch_address(rw), + kind_names[kind], slot, calls, names[i], w * 8, words[w], frame_number, ret); + } + } + for (int i = 1; i < 8 && noop_census_hits[kind & 15][slot & 511] < 6; ++i) { + CensusHeap h{}; + const char* weak = i >= 4 ? " (stack word: weak)" : ""; + if (noop_census_heap_index(args[i], &h) && noop_census_hit(kind, slot)) + log("x2w-noop-census %s::slot%d call %lld: %s=0x%llx is %s index 0x%llx of the heap at 0x%llx (%llu descriptors)%s; ret=+0x%llx", + kind_names[kind], slot, calls, names[i], args[i], h.desktop ? "DESKTOP" : "title", h.index, h.base, h.count, weak, ret); + if (calls > 64 || args[i] < 0x10000) continue; + std::uint64_t words[8]{}; + SIZE_T got = 0; + if (!ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<const void*>(args[i]), words, sizeof(words), &got) || got != sizeof(words)) continue; + for (int w = 0; w < 8; ++w) + if (noop_census_heap_index(words[w], &h) && noop_census_hit(kind, slot)) + log("x2w-noop-census %s::slot%d call %lld: [%s+0x%x]=0x%llx is %s index 0x%llx of the heap at 0x%llx (%llu descriptors)%s; ret=+0x%llx", + kind_names[kind], slot, calls, names[i], w * 8, words[w], h.desktop ? "DESKTOP" : "title", h.index, h.base, h.count, weak, ret); + } + if (total >= 1024 && (total & (total - 1)) == 0) { + for (int k = 0; k < kind_count; ++k) { + char text[1536]; + int at = std::snprintf(text, sizeof(text), "x2w-noop-census after %lld no-op calls, %s:", total, kind_names[k]); + bool any = false; + for (int s = 0; s < 512 && at < static_cast<int>(sizeof(text)) - 32; ++s) + if (noop_census[k][s]) { + at += std::snprintf(text + at, sizeof(text) - at, " %d=%lld", s, noop_census[k][s]); + any = true; + } + if (any) log("%s", text); + } + } +} +// Views view_slot drops because the destination is in no known heap (desktop_cpu_handle gives 0). +void noop_census_dropped_view(int slot, std::uint64_t title_dest) +{ + static LONG64 dropped; + static LONG logged; + const LONG64 n = InterlockedIncrement64(&dropped); + if (first_calls(logged, 32) || (n & (n - 1)) == 0) + log("x2w-noop-census view slot %d dropped (destination 0x%llx is in no known heap); %lld dropped so far", slot, title_dest, n); +} + +// LOCAL (video): X2W_RANGE_WATCH=<hex title address>[,<hex>...] (up to 4) watches [address, address + 0x100): +// - its bytes at slot-133 creation of a placed buffer that overlaps it; +// - its bytes at every queue submit, frame and draw/compute bind, logged only when they changed since the last +// sample (site, frame, first 48 bytes, hash of all 0x100); +// - every translated compute binding and every no-op census argument (or one word it points to) in the range. +// At most 64 lines per watched address. +extern LONG frame_number; +constexpr std::uint64_t range_watch_span = 0x100; +struct RangeWatch { + std::uint64_t address; + std::uint64_t hash; + bool sampled; + LONG lines; +}; +RangeWatch range_watches[4]; +int range_watch_count() +{ + static const int count = [] { + char text[128]{}; + int n = 0; + if (GetEnvironmentVariableA("X2W_RANGE_WATCH", text, sizeof(text))) { + for (char* at = text; *at && n < 4;) { + char* end = nullptr; + const std::uint64_t value = std::strtoull(at, &end, 16); + if (end == at) break; + if (value) range_watches[n++].address = value; + at = *end == ',' ? end + 1 : end; + } + log("x2w-watch X2W_RANGE_WATCH: %d range(s) of 0x%llx bytes watched (%s)", n, range_watch_span, text); + } + return n; + }(); + return count; +} +// Index of the first watched range that [address, address + bytes) overlaps, else -1. +int range_watch_hit(std::uint64_t address, std::uint64_t bytes) +{ + if (!range_watch_count() || !address) return -1; + if (!bytes) bytes = 1; + for (int i = 0; i < range_watch_count(); ++i) { + const std::uint64_t a = range_watches[i].address; + if (address < a + range_watch_span && address + bytes > a) return i; + } + return -1; +} +bool range_watch_line(int i) { return InterlockedIncrement(&range_watches[i].lines) <= 64; } +std::uint64_t range_watch_address(int i) { return range_watches[i].address; } +// Reads the watched range without faulting; false if it is not readable. +bool range_watch_read(int i, unsigned char (&bytes)[range_watch_span], std::uint64_t* hash) +{ + SIZE_T got = 0; + if (!ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<const void*>(range_watches[i].address), bytes, sizeof(bytes), &got) || + got != sizeof(bytes)) + return false; + std::uint64_t h = 14695981039346656037ull; + for (unsigned char b : bytes) h = (h ^ b) * 1099511628211ull; + *hash = h; + return true; +} +void range_watch_text(const unsigned char* bytes, char (&text)[3 * 48 + 1]) +{ + for (int k = 0; k < 48; ++k) std::snprintf(text + 3 * k, 4, "%02x ", bytes[k]); +} +// Samples every watched range; logs the ones whose bytes changed since the last sample (or the first sample). +void range_watch_sample(const char* site, std::uint64_t key = 0) +{ + for (int i = 0; i < range_watch_count(); ++i) { + unsigned char bytes[range_watch_span]; + std::uint64_t hash = 0; + if (!range_watch_read(i, bytes, &hash)) continue; + RangeWatch& w = range_watches[i]; + if (w.sampled && w.hash == hash) continue; + const bool first = !w.sampled; + w.sampled = true; + w.hash = hash; + if (!range_watch_line(i)) continue; + char text[3 * 48 + 1]; + range_watch_text(bytes, text); + log("x2w-watch 0x%llx %s at %s %016llx frame %ld: hash %016llx [%s]", w.address, first ? "first sample" : "CHANGED", site, key, + frame_number, hash, text); + } +} + // Desktop rejects a shader-visible CBV/SRV/UAV heap above a driver-specific descriptor count: the // API documents 1,048,576, but a driver may accept fewer (1,000,000 on the GTX 1660 SUPER here), so // the accepted maximum is measured once and cached rather than assumed. @@ -342,27 +600,101 @@ Wrapper* the_device; // Time spent inside the stand-in per entry-point family, reported with the heartbeat. enum { time_list, time_device_noop, time_forward, time_create, time_view, time_queue, time_present, time_wait, - time_pipeline, time_heap, time_copy, time_count }; + time_pipeline, time_heap, time_copy, time_cx_fill_views, time_cx_desktop_range, time_cx_readable, time_cx_texture, + time_cx_execute, time_vquery, time_placed, time_placed_query, time_placed_create, time_placed_log, time_placed_gap, + time_draw_lock_wait, time_log, time_log_in_draw_lock, time_count }; +// LOCAL (perf_work/STARTUP.md): "placed" is all of Device slot 133 (CreatePlacedResourceX); its parts are +// the memory queries, the desktop heap/resource creation and the log line; "placed-gap" is the time on +// the same thread from the end of one slot 133 call to the start of the next (the title's own work +// between two calls; gaps over 1 s are not counted). const char* const time_names[time_count] = {"list", "device-noop", "forward", "create", "view", "queue", "present", "wait", - "pipeline", "heap", "copy"}; + "pipeline", "heap", "copy", "cx-fill-views", "cx-desktop-range", "cx-readable", + "cx-texture-view", "cx-execute", "vquery", "placed", "placed-query", + "placed-create", "placed-log", "placed-gap", "draw-lock-wait", "log", + "log-in-draw-lock"}; volatile LONG64 time_ticks[time_count], time_calls[time_count]; +struct Timed; +SIZE_T timed_query(const void* address, MEMORY_BASIC_INFORMATION* info); // VirtualQuery, timed as "vquery" volatile LONG64 list_slot_ticks[256], list_slot_calls[256]; // per command-list slot volatile LONG64 list_slot_census[256]; // per command-list slot, reported with the render totals +// LOCAL stall: per-thread time inside timed stand-in calls (the outermost Timed scope only, so nested +// categories are not counted twice), for the present split line (present_split). +struct ThreadInside { + volatile LONG tid; + volatile LONG64 ticks; +}; +constexpr LONG thread_inside_max = 256; +ThreadInside thread_inside[thread_inside_max]; +volatile LONG thread_inside_count; +thread_local ThreadInside* thread_inside_mine; +thread_local int timed_depth; +ThreadInside* inside_slot() +{ + if (!thread_inside_mine) { + static ThreadInside overflow; + const LONG i = InterlockedIncrement(&thread_inside_count) - 1; + thread_inside_mine = i < thread_inside_max ? &thread_inside[i] : &overflow; + thread_inside_mine->tid = static_cast<LONG>(GetCurrentThreadId()); + } + return thread_inside_mine; +} struct Timed { int category; LARGE_INTEGER start; - explicit Timed(int c) : category(c) { QueryPerformanceCounter(&start); } + explicit Timed(int c) : category(c) + { + ++timed_depth; + QueryPerformanceCounter(&start); + } ~Timed() { LARGE_INTEGER end; QueryPerformanceCounter(&end); InterlockedAdd64(&time_ticks[category], end.QuadPart - start.QuadPart); InterlockedIncrement64(&time_calls[category]); + if (--timed_depth == 0) InterlockedAdd64(&inside_slot()->ticks, end.QuadPart - start.QuadPart); } }; +// LOCAL: a part of a call timed into one category (Timed covers a whole scope). +struct TimedPart { + int category; + LARGE_INTEGER start; + explicit TimedPart(int c) : category(c) { QueryPerformanceCounter(&start); } + void stop() + { + if (category < 0) return; + LARGE_INTEGER end; + QueryPerformanceCounter(&end); + InterlockedAdd64(&time_ticks[category], end.QuadPart - start.QuadPart); + InterlockedIncrement64(&time_calls[category]); + category = -1; + } + ~TimedPart() { stop(); } +}; +// Slot 133 totals since the start, never reset (the per-report times above are). +volatile LONG64 placed_calls_total, placed_ticks_total; + +SIZE_T timed_query(const void* address, MEMORY_BASIC_INFORMATION* info) +{ + Timed timed(time_vquery); + return VirtualQuery(address, info, sizeof(*info)); +} + +extern SRWLOCK draw_lock; // d3d12_draw.inl +extern volatile LONG draw_lock_thread; // the thread that took draw_lock last +// LOCAL stall: all of log() is timed as "log"; lines written while this thread holds draw_lock also +// as "log-in-draw-lock" (owner check: the last taker is this thread and the lock is not free). void log(const char* format, ...) { + Timed timed(time_log); + TimedPart locked(time_log_in_draw_lock); + if (draw_lock_thread != static_cast<LONG>(GetCurrentThreadId())) + locked.category = -1; + else if (TryAcquireSRWLockShared(&draw_lock)) { + ReleaseSRWLockShared(&draw_lock); + locked.category = -1; + } char line[1536]; va_list args; va_start(args, format); @@ -373,7 +705,7 @@ void log(const char* format, ...) line[n++] = '\r'; line[n++] = '\n'; x2w_trap::write_all(GetStdHandle(STD_ERROR_HANDLE), line, static_cast<DWORD>(n)); - x2w_trap::append_log(line, static_cast<DWORD>(n), false); + x2w_trap::append_trap_log(line, static_cast<DWORD>(n)); // one open handle per module (trap.h) } void guid_text(const GUID* g, char* out, std::size_t size) @@ -405,24 +737,64 @@ ID3D12Device* removal_device; LONG removal_reported, debug_lines; SRWLOCK debug_lock = SRWLOCK_INIT; +void report_dred_dispatches(const D3D12_AUTO_BREADCRUMB_NODE* node, UINT done); // LOCAL, by execute_dispatch +// LOCAL: logs DRED breadcrumbs (the operations around the last completed one, per list) and the page fault. +void report_dred(ID3D12Device* device) +{ + ID3D12DeviceRemovedExtendedData* dred = nullptr; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&dred)))) { + log("x2w-dred not available"); + return; + } + D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT crumbs{}; + if (SUCCEEDED(dred->GetAutoBreadcrumbsOutput(&crumbs))) { + int lists = 0; + for (const D3D12_AUTO_BREADCRUMB_NODE* node = crumbs.pHeadAutoBreadcrumbNode; node && lists < 24; node = node->pNext) { + const UINT done = node->pLastBreadcrumbValue ? *node->pLastBreadcrumbValue : 0; + if (done >= node->BreadcrumbCount) continue; // completed list + ++lists; + log("x2w-dred list %p: %u of %u operations completed", static_cast<const void*>(node->pCommandList), done, node->BreadcrumbCount); + const UINT from = done > 6 ? done - 6 : 0, to = done + 4 < node->BreadcrumbCount ? done + 4 : node->BreadcrumbCount; + for (UINT i = from; i < to; ++i) + log("x2w-dred %s op %u: %d", i == done ? ">>" : " ", i, static_cast<int>(node->pCommandHistory[i])); + report_dred_dispatches(node, done); + } + if (!lists) log("x2w-dred no incomplete list in the breadcrumbs"); + } + D3D12_DRED_PAGE_FAULT_OUTPUT fault{}; + if (SUCCEEDED(dred->GetPageFaultAllocationOutput(&fault))) { + log("x2w-dred page fault va 0x%llx", static_cast<unsigned long long>(fault.PageFaultVA)); + int n = 0; + for (const D3D12_DRED_ALLOCATION_NODE* a = fault.pHeadExistingAllocationNode; a && n < 8; a = a->pNext, ++n) + log("x2w-dred existing allocation type %d", static_cast<int>(a->AllocationType)); + n = 0; + for (const D3D12_DRED_ALLOCATION_NODE* a = fault.pHeadRecentFreedAllocationNode; a && n < 8; a = a->pNext, ++n) + log("x2w-dred recently freed allocation type %d", static_cast<int>(a->AllocationType)); + } + dred->Release(); +} + void check_device(const char* context, int slot) { if (removal_device && !removal_reported) { const HRESULT reason = removal_device->GetDeviceRemovedReason(); - if (reason != S_OK && InterlockedExchange(&removal_reported, 1) == 0) + if (reason != S_OK && InterlockedExchange(&removal_reported, 1) == 0) { log("x2w-d3d12 DEVICE REMOVED, reason 0x%08lx, first noticed after %s %d", static_cast<unsigned long>(reason), context, slot); + report_dred(removal_device); + } } if (!info_queue) return; AcquireSRWLockExclusive(&debug_lock); const UINT64 count = info_queue->GetNumStoredMessages(); - for (UINT64 i = 0; i < count && debug_lines < 400; ++i) { + static std::unordered_map<int, int> per_id; // LOCAL: at most 4 lines per message id + for (UINT64 i = 0; i < count && debug_lines < 4000; ++i) { SIZE_T size = 0; info_queue->GetMessage(i, nullptr, &size); if (!size || size > 8192) continue; alignas(16) char storage[8192]; auto* message = reinterpret_cast<D3D12_MESSAGE*>(storage); - if (SUCCEEDED(info_queue->GetMessage(i, message, &size))) { + if (SUCCEEDED(info_queue->GetMessage(i, message, &size)) && ++per_id[message->ID] <= 4) { ++debug_lines; log("x2w-d3d12-debug [%s %d] sev=%d id=%d %.900s", context, slot, message->Severity, message->ID, message->pDescription); @@ -450,9 +822,12 @@ Wrapper* as_wrapper(const void* p) return known ? const_cast<Wrapper*>(static_cast<const Wrapper*>(p)) : nullptr; } +#include "startup_stubs/d3d12_cold_texture.inl" + u64 unwrap(u64 value) { Wrapper* w = as_wrapper(reinterpret_cast<const void*>(value)); + warm_texture(w); return w ? reinterpret_cast<u64>(w->own().real) : value; } @@ -556,8 +931,98 @@ bool list_noop() extern LONG draw_calls_seen; // X2W_D3D12_TRACE_FRAME=<n>: every command-list call of presented frame n is logged ("x2w-frame") // with its slot, the kinds of any wrapped objects among its arguments, and stack arguments. -LONG trace_frame_active; +// LOCAL (scene): X2W_D3D12_TRACE_ALL=1 traces from the start (fixtures that never present). +LONG trace_requested_frame() +{ + static const LONG wanted = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_D3D12_TRACE_FRAME", value, sizeof(value)) ? std::atol(value) : 0L; + }(); + return wanted; +} +LONG trace_frame_active = x2w_local::env_on("X2W_D3D12_TRACE_ALL") || trace_requested_frame() == 1 ? 1 : 0; +volatile LONG gpu_trace_frame = trace_requested_frame() == 1 ? 1 : 0; +volatile LONG gpu_trace_commands; +volatile LONG gpu_trace_per_kind[2]; // graphics and compute each have a trace budget +volatile LONG gpu_trace_bindings; +volatile LONG gpu_trace_request_id; +using TraceStageKey = std::shared_ptr<const std::string>; +TraceStageKey gpu_scene_stage_override; +TraceStageKey gpu_scene_second_override; +TraceStageKey gpu_trace_stage_key() +{ + if (auto active = std::atomic_load(&gpu_scene_stage_override)) return active; + static const TraceStageKey key = []() -> TraceStageKey { + char value[32]{}; + const DWORD n = GetEnvironmentVariableA("X2W_TRACE_STAGE_KEY", value, sizeof(value)); + if (!n) return {}; + if (n == 16 && std::strspn(value, "0123456789abcdefABCDEF") == 16) return std::make_shared<const std::string>(value); + log("x2w-frame X2W_TRACE_STAGE_KEY requires a 16-digit hexadecimal shader key"); + return std::make_shared<const std::string>("invalid"); // An invalid filter selects no shaders. + }(); + return key; +} +void reset_gpu_trace_commands() +{ + InterlockedExchange(&gpu_trace_commands, 0); + InterlockedExchange(&gpu_trace_bindings, 0); + for (auto& count : gpu_trace_per_kind) InterlockedExchange(&count, 0); +} + +// A scene trace begins on an issued deferred draw. Presentation polls the +// optional request file and closes each capture on its next Present. +struct GpuSceneTrace { + std::mutex lock; + std::atomic<bool> waiting{false}; + LONG mrt = 0, after = 0, first = 0, accepted = 0, pending = 0, active_frame = 0, active_id = 0; + std::atomic<ULONGLONG> next_poll{0}; + std::wstring request_file; + TraceStageKey pending_key; + TraceStageKey second_key; + x2w_gpu::CapturePoint pending_point; + + GpuSceneTrace() + { + char text[32]{}; + const auto bytes = GetEnvironmentVariableA("X2W_TRACE_SCENE_MRT", text, sizeof(text)); + if (bytes && bytes < sizeof(text)) mrt = std::clamp(std::atol(text), 0L, 8L); + const auto delay = GetEnvironmentVariableA("X2W_D3D12_TRACE_BUSY_AFTER", text, sizeof(text)); + if (delay && delay < sizeof(text)) after = (std::max)(0L, std::atol(text)); + wchar_t name[MAX_PATH]{}; + const auto length = GetEnvironmentVariableW(L"X2W_TRACE_REQUEST_FILE", name, MAX_PATH); + if (length && length < MAX_PATH) request_file.assign(name, length); + waiting.store(mrt != 0); + } + + void poll() + { + if (request_file.empty()) return; + const auto now = GetTickCount64(); + auto due = next_poll.load(std::memory_order_relaxed); + if (now < due || !next_poll.compare_exchange_strong(due, now + 250, std::memory_order_relaxed)) return; + FILE* f = nullptr; + if (_wfopen_s(&f, request_file.c_str(), L"rb") != 0) return; + char text[64]{}; + const auto n = std::fread(text, 1, sizeof(text) - 1, f); + std::fclose(f); + if (!n || n == sizeof(text) - 1) return; + const auto request = x2w_gpu::parse_scene_request({text, n}); + if (!request) return; + const auto id = request->id; + std::lock_guard<std::mutex> held(lock); + if (id <= accepted || pending || active_frame) return; + pending_point = request->point; + pending_key = request->stage_key.empty() ? nullptr : std::make_shared<const std::string>(request->stage_key); + second_key = request->second_key.empty() ? nullptr : std::make_shared<const std::string>(request->second_key); + accepted = pending = id; + waiting.store(true, std::memory_order_release); + log("x2w-frame scene request %ld armed for the next qualifying draw, stage=%s%s%s", id, + pending_key ? pending_key->c_str() : "default", second_key ? "," : "", second_key ? second_key->c_str() : ""); + } +}; +GpuSceneTrace& gpu_scene_trace() { static GpuSceneTrace trace; return trace; } extern LONG capture_active; +extern LONG frame_number; // Command-list methods with a real implementation (render mode). Every list call enters through // noop_slot, which times, captures and traces it, then hands over to the entry here if there is one. using ListTyped = u64(__stdcall*)(u64, u64, u64, u64, u64, u64, u64, u64); @@ -604,11 +1069,15 @@ __declspec(noinline) u64 noop_slot(u64 rcx, u64 rdx, u64 r8, u64 r9, u64 s0, u64 if (compute_binding_trace_enabled()) trace_compute_binding(reinterpret_cast<Wrapper*>(rcx), N, rdx, r8, r9, s0); } if (K == list_kind && list_typed[N]) return list_typed[N](rcx, rdx, r8, r9, s0, s1, s2, s3); + if (noop_census_enabled()) { + const u64 args[8] = {rcx, rdx, r8, r9, s0, s1, s2, s3}; + noop_census_note(K, N, args, reinterpret_cast<u64>(_ReturnAddress()) - reinterpret_cast<u64>(GetModuleHandleW(nullptr))); + } // Register arguments only: stale caller stack words often still point at an IID. The probe // costs over a millisecond per call in this process (memory queries), so only the first calls // of each slot are checked. static LONG shape_checks; - if (shape_checks < 32 && InterlockedIncrement(&shape_checks) <= 32 && create_shaped(rdx, r8, r9, 0, 0, 0, 0)) { + if (shape_checks < 32 && x2w_local::first_calls(shape_checks, 32) && create_shaped(rdx, r8, r9, 0, 0, 0, 0)) { char name[64]; std::snprintf(name, sizeof(name), "%s::slot%d(passes an IID)", kind_names[K], N); x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, name, N & 0xFF, rcx, rdx, r8, r9, _ReturnAddress()); @@ -637,8 +1106,12 @@ template <int N> __declspec(noinline) u64 device_noop_slot(u64 rcx, u64 rdx, u64 r8, u64 r9, u64 s0, u64 s1, u64 s2, u64 s3) { Timed timed(time_device_noop); + if (noop_census_enabled()) { + const u64 args[8] = {rcx, rdx, r8, r9, s0, s1, s2, s3}; + noop_census_note(device_kind, N, args, reinterpret_cast<u64>(_ReturnAddress()) - reinterpret_cast<u64>(GetModuleHandleW(nullptr))); + } static LONG shape_checks; - if (shape_checks < 32 && InterlockedIncrement(&shape_checks) <= 32 && create_shaped(rdx, r8, r9, s0, s1, s2, s3)) { + if (shape_checks < 32 && x2w_local::first_calls(shape_checks, 32) && create_shaped(rdx, r8, r9, s0, s1, s2, s3)) { char name[64]; std::snprintf(name, sizeof(name), "Device::slot%d(passes an IID)", N); char first[3 * 64 + 1]; @@ -739,6 +1212,147 @@ DXGI_FORMAT desktop_format(DXGI_FORMAT format) return mapped; } +// Depth-stencil formats are planar on desktop: a stencil view format reads plane 1, a depth one +// plane 0. A view with the wrong plane removes the device (DXGI_ERROR_INVALID_CALL). +void fix_srv_plane(D3D12_SHADER_RESOURCE_VIEW_DESC& d) +{ + const bool stencil = d.Format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT || d.Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT; + const bool depth = d.Format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS || d.Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || + d.Format == DXGI_FORMAT_R32_FLOAT || d.Format == DXGI_FORMAT_R16_UNORM; + if (!stencil && !depth) return; + const UINT plane = stencil ? 1 : 0; + if (d.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D) d.Texture2D.PlaneSlice = plane; + else if (d.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY) d.Texture2DArray.PlaneSlice = plane; +} + +// LOCAL: a view of a multisampled resource must use a multisample dimension; the desktop removes the +// device (DXGI_ERROR_INVALID_CALL) for a TEXTURE2D/ARRAY view of one. The title's descriptions name +// the plain dimensions. +void fix_srv_samples(D3D12_SHADER_RESOURCE_VIEW_DESC& d, ID3D12Resource* resource) +{ + if (!resource) return; + const D3D12_RESOURCE_DESC rd = resource->GetDesc(); + if (rd.SampleDesc.Count <= 1) return; + if (d.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D) { + d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS; + d.Texture2DMS = {}; + } else if (d.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY) { + const UINT first = d.Texture2DArray.FirstArraySlice, size = d.Texture2DArray.ArraySize; + d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; + d.Texture2DMSArray = {}; + d.Texture2DMSArray.FirstArraySlice = first; + d.Texture2DMSArray.ArraySize = size ? size : rd.DepthOrArraySize; + } +} + +// LOCAL: depth textures are created typeless on the desktop (typeless_depth_family), so a view has to +// name a format of that family. The console views its 16-bit depth with stencil (created here as +// R24G8) as R16_UNORM / R8_UINT and a 32-bit depth with stencil as R32_FLOAT; the desktop removes +// the device (DXGI_ERROR_INVALID_CALL) for those. Depth-named views read the depth plane, stencil- +// named views the stencil plane. Only the format changes; the bit layout of a 16-bit console depth +// view is not reproduced (it reads 24-bit depth as UNORM). +DXGI_FORMAT depth_view_format(DXGI_FORMAT resource, DXGI_FORMAT view) +{ + const bool stencil = view == DXGI_FORMAT_R8_UINT || view == DXGI_FORMAT_X24_TYPELESS_G8_UINT || + view == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT; + switch (resource) { + case DXGI_FORMAT_R24G8_TYPELESS: + return stencil ? DXGI_FORMAT_X24_TYPELESS_G8_UINT : DXGI_FORMAT_R24_UNORM_X8_TYPELESS; + case DXGI_FORMAT_R32G8X24_TYPELESS: + return stencil ? DXGI_FORMAT_X32_TYPELESS_G8X24_UINT : DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; + case DXGI_FORMAT_R32_TYPELESS: + return view == DXGI_FORMAT_D32_FLOAT || view == DXGI_FORMAT_UNKNOWN ? DXGI_FORMAT_R32_FLOAT : view; + case DXGI_FORMAT_R16_TYPELESS: + return view == DXGI_FORMAT_D16_UNORM || view == DXGI_FORMAT_UNKNOWN ? DXGI_FORMAT_R16_UNORM : view; + default: + return view; + } +} + +// The depth-stencil view format of a typeless depth family (DSVs need the D format). +DXGI_FORMAT depth_target_format(DXGI_FORMAT resource) +{ + switch (resource) { + case DXGI_FORMAT_R24G8_TYPELESS: return DXGI_FORMAT_D24_UNORM_S8_UINT; + case DXGI_FORMAT_R32G8X24_TYPELESS: return DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + case DXGI_FORMAT_R32_TYPELESS: return DXGI_FORMAT_D32_FLOAT; + case DXGI_FORMAT_R16_TYPELESS: return DXGI_FORMAT_D16_UNORM; + default: return DXGI_FORMAT_UNKNOWN; + } +} + +// A typed depth format of a texture that may be sampled -> its typeless family, so that shader +// resource views of it can exist on the desktop. Typed D formats allow no SRV at all. +DXGI_FORMAT typeless_depth_family(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_D24_UNORM_S8_UINT: return DXGI_FORMAT_R24G8_TYPELESS; + case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return DXGI_FORMAT_R32G8X24_TYPELESS; + case DXGI_FORMAT_D32_FLOAT: return DXGI_FORMAT_R32_TYPELESS; + case DXGI_FORMAT_D16_UNORM: return DXGI_FORMAT_R16_TYPELESS; + default: return format; + } +} + +// All shader-resource-view repairs for a view of `resource`: depth family format, plane, samples. +void fix_srv(D3D12_SHADER_RESOURCE_VIEW_DESC& d, ID3D12Resource* resource) +{ + if (!resource) return; + const D3D12_RESOURCE_DESC rd = resource->GetDesc(); + if (depth_target_format(rd.Format) != DXGI_FORMAT_UNKNOWN) { + const DXGI_FORMAT before = d.Format; + d.Format = depth_view_format(rd.Format, d.Format); + if (d.Format != before) { + static LONG calls; + if (first_calls(calls, 6)) log("x2w-d3d12 SRV of depth format %d: view format %d -> %d", rd.Format, before, d.Format); + } + fix_srv_plane(d); + } + fix_srv_samples(d, resource); +} + +// A default shader resource view description for a typeless depth resource (a null description is +// refused for typeless resources). +bool default_depth_srv(ID3D12Resource* resource, D3D12_SHADER_RESOURCE_VIEW_DESC& d) +{ + if (!resource) return false; + const D3D12_RESOURCE_DESC rd = resource->GetDesc(); + if (depth_target_format(rd.Format) == DXGI_FORMAT_UNKNOWN || rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return false; + d = {}; + d.Format = depth_view_format(rd.Format, DXGI_FORMAT_UNKNOWN); + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (rd.DepthOrArraySize > 1) { + d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + d.Texture2DArray.MipLevels = UINT(-1); + d.Texture2DArray.ArraySize = rd.DepthOrArraySize; + } else { + d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + d.Texture2D.MipLevels = UINT(-1); + } + fix_srv_samples(d, resource); + return true; +} + +// A default depth-stencil view description for a typeless depth resource. +bool default_depth_dsv(ID3D12Resource* resource, D3D12_DEPTH_STENCIL_VIEW_DESC& d) +{ + if (!resource) return false; + const D3D12_RESOURCE_DESC rd = resource->GetDesc(); + const DXGI_FORMAT format = depth_target_format(rd.Format); + if (format == DXGI_FORMAT_UNKNOWN || rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return false; + d = {}; + d.Format = format; + const bool ms = rd.SampleDesc.Count > 1; + if (rd.DepthOrArraySize > 1) { + d.ViewDimension = ms ? D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY : D3D12_DSV_DIMENSION_TEXTURE2DARRAY; + if (ms) d.Texture2DMSArray.ArraySize = rd.DepthOrArraySize; + else d.Texture2DArray.ArraySize = rd.DepthOrArraySize; + } else { + d.ViewDimension = ms ? D3D12_DSV_DIMENSION_TEXTURE2DMS : D3D12_DSV_DIMENSION_TEXTURE2D; + } + return true; +} + constexpr UINT desktop_resource_flags = 0x3f; D3D12_RESOURCE_DESC sanitized(const D3D12_RESOURCE_DESC& desc) { @@ -767,6 +1381,13 @@ D3D12_RESOURCE_DESC sanitized(const D3D12_RESOURCE_DESC& desc) } if (desc.Alignment != 0 && desc.Alignment != 0x10000 && desc.Alignment != 0x400000) copy.Alignment = 0; copy.Format = desktop_format(desc.Format); + if (x2w_gpu::gpu_abi_on()) copy.Format = x2w_srgb::backing_format(copy); + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && (copy.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && + !(copy.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && typeless_depth_family(copy.Format) != copy.Format) { + static LONG depths; + if (first_calls(depths, 4)) log("x2w-d3d12 depth texture format %d created typeless (%d) so it can be sampled", copy.Format, typeless_depth_family(copy.Format)); + copy.Format = typeless_depth_family(copy.Format); + } // A packed target the adapter cannot render to or write as a UAV: packed_target_format.h. if (the_device && x2w_startup::packed_target_format(copy.Format)) { ID3D12Device* const device = static_cast<ID3D12Device*>(the_device->own().real); @@ -871,6 +1492,10 @@ __declspec(noinline) u64 create_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d, if (Desc >= 0 && kind == resource_kind && requested_format != DXGI_FORMAT_UNKNOWN) x2w_startup::mark_packed_stand_in(static_cast<ID3D12Resource*>(*out), requested_format); Wrapper* child = wrap(static_cast<IUnknown*>(*out), kind); + if constexpr (Desc >= 0) { + if (kind == resource_kind && requested_format != desc_copy.Format && x2w_srgb::family(requested_format) == desc_copy.Format) + child->own().srgb_uav_format = static_cast<unsigned char>(requested_format); + } if constexpr (K == device_kind && N == 27) { if (kind == resource_kind && args[0]) retire_set_class(child, *reinterpret_cast<const D3D12_HEAP_PROPERTIES*>(args[0]), @@ -956,18 +1581,36 @@ HRESULT __stdcall query_interface(Wrapper* self, const GUID* iid, void** out) *out = nullptr; HRESULT hr = E_NOINTERFACE; if (is_base_iid(*iid) || kind_for(*iid) == self->own().kind) { - InterlockedIncrement(&self->own().refs); + const LONG refs = InterlockedIncrement(&self->own().refs); + warm_texture(self, refs == 1); *out = self; hr = S_OK; } log("x2w-d3d12 %s::QueryInterface riid=%s -> 0x%08lx", kind_names[self->own().kind], text, static_cast<unsigned long>(hr)); return hr; } -ULONG __stdcall add_ref(Wrapper* self) { return static_cast<ULONG>(InterlockedIncrement(&self->own().refs)); } +ULONG __stdcall add_ref(Wrapper* self) +{ + const LONG refs = InterlockedIncrement(&self->own().refs); + warm_texture(self, refs == 1); + return static_cast<ULONG>(refs); +} // The wrappers and their desktop objects stay alive for the process (experiment scope). The one exception is // X2W_D3D12_RELEASE_RETIRED=1: the desktop object of a resource of the retire class is freed once nothing refers to it. // The wrapper stays. void retire_placement(Wrapper* w); +// LOCAL memcut: X2W_MEMCUT_RELEASE (d3d12_memcut_release.inl). +void memcut_released(Wrapper* self); +void memcut_list_reset(Wrapper* list); +void memcut_reap(); +// LOCAL memcut: upload ring chunk lifetimes (d3d12_upload_ring.inl). +void ring_list_reset(Wrapper* list); +void ring_list_close(Wrapper* list); +void ring_list_gone(Wrapper* list); +void ring_submitted(const std::vector<Wrapper*>& lists); +void memcut_revive(Wrapper* w); +ID3D12Heap* memcut_slab_heap(void* address, UINT64 bytes, UINT64* offset); // X2W_MEMCUT_ALIAS_SLABS +void memcut_slab_failed(void* address, UINT64 bytes, HRESULT hr); void register_retire_queue(Wrapper* queue); void retire_resource(Wrapper* w); void retire_leave_class(const void* object, RetireLeft why); @@ -989,6 +1632,7 @@ ULONG __stdcall release(Wrapper* self) { const auto refs = InterlockedDecrement(&self->own().refs); if (!refs) { + cool_texture(self); if (self->own().budget) self->own().budget->end_use(); if (self->own().backing_budget) self->own().backing_budget->end_use(); if (self->own().kind == descriptor_heap_kind) retire_drop_heap_views(self); @@ -1006,6 +1650,10 @@ ULONG __stdcall release(Wrapper* self) if (self->own().kind == device_kind) clear_unplaced_buffers(self); } + if (!refs && self->own().kind == resource_kind) memcut_released(self); // LOCAL memcut + if (!refs && self->own().kind == list_kind) ring_list_gone(self); // LOCAL memcut (upload ring) + if (!refs && x2w_gpu::gpu_abi_on() && (self->own().kind == resource_kind || self->own().gpu[0] || self->own().gpu[1])) + gpu_released(self); return static_cast<ULONG>(refs); } @@ -1131,31 +1779,33 @@ void __stdcall device_copyable_footprints(Wrapper* self, const D3D12_RESOURCE_DE device_of(self)->GetCopyableFootprints(©, first, count, base, layouts, rows, row_bytes, total); } +// LOCAL: command signatures by wrapper: stride and the argument descriptors, for ExecuteIndirect. +struct SignatureInfo { + UINT stride = 0; + std::vector<D3D12_INDIRECT_ARGUMENT_DESC> args; +}; +SRWLOCK signature_lock = SRWLOCK_INIT; +std::unordered_map<const void*, SignatureInfo>& signature_infos() +{ + static std::unordered_map<const void*, SignatureInfo> infos; + return infos; +} // Device slot 41, desktop CreateCommandSignature(desc, root, riid, ppv); on failure the descriptor and // its argument descriptors are logged. The observed console-only type 0x69 gets a placeholder before // desktop validation. Other types still reach the desktop even when they postdate DISPATCH_MESH. u64 __stdcall device_create_command_signature(Wrapper* self, const D3D12_COMMAND_SIGNATURE_DESC* desc, u64 root, u64 iid, u64 out) { + // Argument types outside the desktop enumeration (0x69 seen, stride 12) cannot be created on + // desktop and are not passed to it (the debug layer reports CREATECOMMANDSIGNATURE_INVALID). + bool console_type = false; + for (UINT i = 0; desc && i < desc->NumArgumentDescs; ++i) + console_type |= static_cast<UINT>(desc->pArgumentDescs[i].Type) > D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + const u64 result = console_type ? static_cast<u64>(static_cast<UINT>(E_INVALIDARG)) + : create_slot<device_kind, 41, 2>(self, reinterpret_cast<u64>(desc), root, iid, out, 0, 0, 0, 0); void** output = reinterpret_cast<void**>(out); const bool readable_args = x2w_local::readable(desc, sizeof(*desc)) && x2w_local::readable(desc->pArgumentDescs, std::size_t{desc->NumArgumentDescs} * sizeof(*desc->pArgumentDescs)); - if (output && readable_args && x2w_startup::has_console_indirect_arg_type(desc->pArgumentDescs, desc->NumArgumentDescs) && - x2w_local::writable(output, sizeof(*output))) { - static LONG placeholders; - if (first_calls(placeholders, 8)) { - log("x2w-d3d12 CreateCommandSignature: console argument type -> placeholder (stride=%u args=%u)", - desc->ByteStride, desc->NumArgumentDescs); - for (UINT i = 0; i < desc->NumArgumentDescs && i < 8; ++i) { - char bytes[3 * 16 + 1]; - hex_text(&desc->pArgumentDescs[i], sizeof(D3D12_INDIRECT_ARGUMENT_DESC), bytes, sizeof(bytes)); - log("x2w-d3d12 arg[%u]=[%s]", i, bytes); - } - } - *output = wrap(nullptr, command_signature_kind); - return S_OK; - } - const u64 result = create_slot<device_kind, 41, 2>(self, reinterpret_cast<u64>(desc), root, iid, out, 0, 0, 0, 0); if (SUCCEEDED(static_cast<HRESULT>(result)) && out && desc && root && desc->NumArgumentDescs > 1) { // A Dispatch preceded by root constants for the signature's root (#1759 part 2). Other root argument // types (root views, vertex and index buffer views) and graphics commands remain unsupported here. @@ -1201,15 +1851,31 @@ u64 __stdcall device_create_command_signature(Wrapper* self, const D3D12_COMMAND log("x2w-d3d12 arg[%u]=[%s]", i, bytes); } } - // Preserve the existing fallback for unknown types only after desktop has refused the real request. - if (FAILED(static_cast<HRESULT>(result)) && readable_args && output && x2w_local::writable(output, sizeof(*output))) { - for (UINT i = 0; i < desc->NumArgumentDescs; ++i) { - if (static_cast<UINT>(desc->pArgumentDescs[i].Type) > D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH) { - *output = wrap(nullptr, command_signature_kind); - return S_OK; - } + // The title gets a placeholder CommandSignature for those (command lists are not executed). + if (FAILED(static_cast<HRESULT>(result)) && console_type && out) { + log("x2w-d3d12 CreateCommandSignature: console argument type -> placeholder"); + *reinterpret_cast<void**>(out) = wrap(nullptr, command_signature_kind); + } + if (out && desc && x2w_local::readable(desc, sizeof(*desc)) && *reinterpret_cast<void**>(out) && + (SUCCEEDED(static_cast<HRESULT>(result)) || console_type)) { + SignatureInfo info; + info.stride = desc->ByteStride; + if (desc->NumArgumentDescs <= 16 && x2w_local::readable(desc->pArgumentDescs, desc->NumArgumentDescs * sizeof(D3D12_INDIRECT_ARGUMENT_DESC))) + info.args.assign(desc->pArgumentDescs, desc->pArgumentDescs + desc->NumArgumentDescs); + static LONG logged; + if (first_calls(logged, 40)) { + char text[256] = ""; + int at = 0; + for (const auto& a : info.args) + at += std::snprintf(text + at, sizeof(text) - at > 0 ? sizeof(text) - at : 0, " %u(%u,%u)", static_cast<UINT>(a.Type), + a.Constant.RootParameterIndex, a.Constant.Num32BitValuesToSet); + log("x2w-d3d12 command signature %p: stride %u, args%s", *reinterpret_cast<void**>(out), info.stride, text); } + AcquireSRWLockExclusive(&signature_lock); + signature_infos()[*reinterpret_cast<void**>(out)] = std::move(info); + ReleaseSRWLockExclusive(&signature_lock); } + if (FAILED(static_cast<HRESULT>(result)) && console_type && out) return S_OK; return result; } @@ -1302,6 +1968,7 @@ void reset_list_dynamic_state(Wrapper* self); void discard_list_gpu_writes(Wrapper* self); void commit_list_gpu_writes(Wrapper* self); void discard_draw_sampler_heaps(ID3D12CommandList* list); +void discard_texture_readbacks(ID3D12CommandList* list); void discard_address_uploads(ID3D12CommandList* list); void use_as_target(Wrapper* self, ID3D12Resource* resource); bool is_container(const void* p); @@ -1345,17 +2012,60 @@ ID3D12Resource* view_target(u64 handle, int slot = 0) 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); + x2w_gpu::transition_all(list, resource, from, to); } +// List slot 148 (Xbox order): AllocateUploadMemory(size, alignment) -> a pointer the CPU writes and +// the GPU reads at the same address (console unified memory), released when the list's allocator is +// reset. Used by the ray-tracing builder, which fails ("Failed to allocate upload buffer") on null. +// LOCAL SHORTCUT: a bump arena of 64 MiB blocks below 1 TiB (x2w_low); blocks are never released. +LONG upload_allocations; +std::mutex builder_upload_lock; +std::map<u64, u64> builder_upload_spans; +std::vector<u64> builder_upload_blocks; +bool builder_memory_on() +{ + static const bool on = x2w_local::env_on("X2W_GPU_MEMORY_STORES"); + return on; +} +u64 __stdcall list_allocate_upload(Wrapper*, u64 size, u64 alignment) +{ + static std::mutex arena_lock; + static unsigned char *cursor = nullptr, *limit = nullptr; + constexpr std::size_t block = std::size_t{64} << 20; + if (!size) size = 16; + if (alignment < 16) alignment = 16; + if ((alignment & (alignment - 1)) || size > block / 2) return 0; + const std::lock_guard guard(arena_lock); + auto aligned = [&] { return reinterpret_cast<unsigned char*>((reinterpret_cast<u64>(cursor) + alignment - 1) & ~(alignment - 1)); }; + if (!cursor || aligned() + size > limit) { + auto* fresh = static_cast<unsigned char*>(x2w_low::alloc(block, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!fresh) return 0; + cursor = fresh; + limit = fresh + block; + static const bool cpu_pages = x2w_local::env_on("X2W_GPU_MEMORY_CPU_PAGES"); + if (builder_memory_on() || cpu_pages) { + std::lock_guard<std::mutex> lock(builder_upload_lock); + builder_upload_blocks.push_back(reinterpret_cast<u64>(fresh)); + } + log("x2w-d3d12 upload arena block %p (64 MiB)", static_cast<void*>(fresh)); + } + unsigned char* result = aligned(); + cursor = result + size; + if (builder_memory_on()) { + std::lock_guard<std::mutex> lock(builder_upload_lock); + builder_upload_spans.emplace(reinterpret_cast<u64>(result), size); + } + if (x2w_local::first_calls(upload_allocations, 4)) + log("x2w-d3d12 CommandList::slot148(AllocateUploadMemory) size=0x%llx align=0x%llx -> %p", size, alignment, + static_cast<void*>(result)); + return reinterpret_cast<u64>(result); +} LONG draw_dump_frame(); void discard_red_producer(ID3D12GraphicsCommandList* list); +void cull_capture_discard(ID3D12GraphicsCommandList* list); // LOCAL: X2W_CULL_INPUT_CAPTURE (cull_input_capture.inl) +void cull_capture_submitted(ID3D12CommandQueue* queue, ID3D12CommandList* const* lists, UINT count); +void cull_capture_flush(); x2w_startup::DrawReadbacks& draw_dumps() { static x2w_startup::DrawReadbacks tracker; @@ -1422,7 +2132,7 @@ bool allocator_idle(const DesktopAllocator* allocator) } // List slot 148 (Xbox order), allocate CPU-writable upload memory for this recording. -void* __stdcall list_allocate_upload(Wrapper* self, UINT64 bytes, UINT64 alignment) +void* __stdcall list_allocate_upload_pages(Wrapper* self, UINT64 bytes, UINT64 alignment) { if (!bytes || !alignment || (alignment & (alignment - 1)) || bytes > UINT64_MAX - (std::max)(alignment, UINT64{16})) return nullptr; @@ -1607,6 +2317,18 @@ extern "C" __declspec(dllexport) unsigned x2w_d3d12_allocator_pool_size(void* al return size; } +void forget_list_dispatches(ID3D12GraphicsCommandList* list); // LOCAL, by execute_dispatch +namespace gpu_time { // LOCAL: X2W_CX_GPU_TIME (d3d12_gpu_time.inl) +void dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, bool after); +void close(Wrapper* self, ID3D12GraphicsCommandList* list); +void submitted(ID3D12CommandQueue* queue, const std::vector<Wrapper*>& wrappers); +void reset(Wrapper* self); +void report(); +// LOCAL stall: X2W_GPU_TIME_CLASSES=1, more classes and the recording span +enum Class { c_cx = 0, c_draw, c_c62, c_copy, c_list, c_count }; +void mark(Wrapper* self, ID3D12GraphicsCommandList* list, int cls, u64 key, bool after, bool drop = false); +void list_begin(Wrapper* self, ID3D12GraphicsCommandList* list); +} // namespace gpu_time // List slot 139 (Xbox order): (allocator, 0, 0), the per-frame reset. HRESULT __stdcall list_reset(Wrapper* self, void* allocator) { @@ -1671,20 +2393,29 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) ++on->lists; state.list_uploads = nullptr; state.list_scratch = nullptr; + state.plane_copy_scratch = nullptr; state.list_ready = false; state.list_open = true; } } ReleaseSRWLockExclusive(&allocator_lock); if (SUCCEEDED(hr)) { - reset_list_dynamic_state(self); + memcut_list_reset(self); // LOCAL memcut + ring_list_reset(self); // LOCAL memcut (upload ring) + forget_list_dispatches(static_cast<ID3D12GraphicsCommandList*>(self->own().real)); + gpu_time::reset(self); + gpu_time::list_begin(self, static_cast<ID3D12GraphicsCommandList*>(self->own().real)); // LOCAL: X2W_GPU_TIME_CLASSES + self->own().list_ready = false; + reset_list_dynamic_state(self); // upstream superset of the local reset_viewport_state discard_list_gpu_writes(self); discard_draw_sampler_heaps(previous); discard_address_uploads(previous); + discard_texture_readbacks(previous); discard_mesh_lease_recording(previous); retire_drop_recording(self); if (draw_dump_frame()) draw_dumps().discard(previous); discard_red_producer(previous); + cull_capture_discard(previous); } InterlockedIncrement(SUCCEEDED(hr) ? &render_resets : &render_reset_failures); static LONG failures; @@ -1705,6 +2436,7 @@ HRESULT __stdcall list_close(Wrapper* self) auto* list = static_cast<ID3D12GraphicsCommandList*>(state.real); end_open_queries(self, list); release_targets(self); + gpu_time::close(self, list); // LOCAL: X2W_CX_GPU_TIME const HRESULT hr = list->Close(); state.list_open = false; state.list_ready = SUCCEEDED(hr); @@ -1714,40 +2446,183 @@ HRESULT __stdcall list_close(Wrapper* self) found->second->close_failed = true; } ReleaseSRWLockExclusive(&allocator_lock); + // LOCAL memcut (upload ring): a failed Close is never executed; it holds its chunks until a Reset. Outside + // allocator_lock: the ring takes it (shared) under its own lock. + ring_list_close(self); InterlockedIncrement(&render_closes); if (FAILED(hr)) { discard_list_gpu_writes(self); discard_draw_sampler_heaps(list); discard_address_uploads(list); + discard_texture_readbacks(list); discard_mesh_lease_recording(list); retire_drop_recording(self); if (draw_dump_frame()) draw_dumps().discard(list); discard_red_producer(list); + cull_capture_discard(list); static LONG failures; if (first_calls(failures, 6)) log("x2w-render list Close failed 0x%08lx", static_cast<unsigned long>(hr)); } return hr; } +// LOCAL stall (X2W_FENCE_TIMES=1, off by default): for every queue Signal that completes through +// complete_when_reached, the time from our Signal to the desktop fence reaching the value (t1: a +// time-critical probe thread waits on the same value with its own event, in signal order) and from +// there to our store of the completed value that the title mwaits on (t2: the threadpool callback). +// Reported with the present split. The probe works through the signals in order, so a later value of a +// faster queue can be timed late ("probe behind": store before probe; counted, not in the means). +namespace fence_times { +struct Entry { + ID3D12Fence* fence; + Wrapper* wrapper; + UINT64 value; + LONG64 t0, t1, t2; + volatile LONG stage; +}; +bool timing() +{ + static const bool value = x2w_local::env_on("X2W_FENCE_TIMES"); + return value; +} +// X2W_FENCE_STORE=probe: the probe thread also stores the completed value as soon as its wait returns +// (the threadpool callback still stores it too; fence_reached only ever raises the value). +bool store_early() +{ + static const bool value = [] { + char text[16]{}; + return GetEnvironmentVariableA("X2W_FENCE_STORE", text, sizeof(text)) && std::strcmp(text, "probe") == 0; + }(); + return value; +} +bool on() { return timing() || store_early(); } +SRWLOCK lock = SRWLOCK_INIT; +std::deque<Entry*> entries; +HANDLE wake; +volatile LONG64 count, gpu_sum, gpu_max, store_sum, store_max, total_max, behind, timeouts; +LONG64 now() +{ + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return t.QuadPart; +} +void raise(volatile LONG64& slot, LONG64 value) +{ + for (LONG64 seen = slot; value > seen;) { + const LONG64 previous = InterlockedCompareExchange64(&slot, value, seen); + if (previous == seen) break; + seen = previous; + } +} +void finish(Entry* e) +{ + if (InterlockedIncrement(&e->stage) != 2) return; + if (e->t1 <= e->t2) { + InterlockedIncrement64(&count); + InterlockedAdd64(&gpu_sum, e->t1 - e->t0); + InterlockedAdd64(&store_sum, e->t2 - e->t1); + raise(gpu_max, e->t1 - e->t0); + raise(store_max, e->t2 - e->t1); + } else { + InterlockedIncrement64(&behind); + } + raise(total_max, e->t2 - e->t0); + e->fence->Release(); + delete e; +} +DWORD WINAPI probe(void*) +{ + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); + SetThreadDescription(GetCurrentThread(), L"x2w fence probe"); + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + for (;;) { + Entry* e = nullptr; + AcquireSRWLockExclusive(&lock); + if (!entries.empty()) { + e = entries.front(); + entries.pop_front(); + } + ReleaseSRWLockExclusive(&lock); + if (!e) { + WaitForSingleObject(wake, 100); + continue; + } + if (e->fence->GetCompletedValue() < e->value && SUCCEEDED(e->fence->SetEventOnCompletion(e->value, event)) && + WaitForSingleObject(event, 5000) != WAIT_OBJECT_0) + InterlockedIncrement64(&timeouts); + else if (store_early()) + fence_reached(e->wrapper, e->value); + e->t1 = now(); + finish(e); + } +} +Entry* start(Wrapper* wrapper, UINT64 value) +{ + if (!on()) return nullptr; + auto* fence = static_cast<ID3D12Fence*>(wrapper->own().real); + static const bool started = [] { + wake = CreateEventW(nullptr, FALSE, FALSE, nullptr); + CloseHandle(CreateThread(nullptr, 0, probe, nullptr, 0, nullptr)); + return true; + }(); + (void)started; + fence->AddRef(); + auto* e = new Entry{fence, wrapper, value, now(), 0, 0, 0}; + AcquireSRWLockExclusive(&lock); + entries.push_back(e); + ReleaseSRWLockExclusive(&lock); + SetEvent(wake); + return e; +} +void stored(Entry* e) +{ + if (!e) return; + e->t2 = now(); + finish(e); +} +// One line per present split window; the counters restart. +void report() +{ + if (!timing()) return; + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + const auto ms = [&](LONG64 t) { return static_cast<double>(t) * 1000.0 / static_cast<double>(f.QuadPart); }; + const LONG64 n = InterlockedExchange64(&count, 0), gs = InterlockedExchange64(&gpu_sum, 0), ss = InterlockedExchange64(&store_sum, 0); + const LONG64 gm = InterlockedExchange64(&gpu_max, 0), sm = InterlockedExchange64(&store_max, 0), tm = InterlockedExchange64(&total_max, 0); + const LONG64 late = InterlockedExchange64(&behind, 0), lost = InterlockedExchange64(&timeouts, 0); + AcquireSRWLockShared(&lock); + const std::size_t queued = entries.size(); + ReleaseSRWLockShared(&lock); + log("x2w-fence times: %lld signals; our Signal -> desktop fence reached mean %.2f ms max %.2f; reached -> completed " + "value stored (what the title mwaits on) mean %.3f ms max %.2f; Signal -> stored max %.2f ms; probe behind %lld, " + "probe timeouts %lld, queued %zu", static_cast<long long>(n), n ? ms(gs) / n : 0.0, ms(gm), n ? ms(ss) / n : 0.0, ms(sm), + ms(tm), static_cast<long long>(late), static_cast<long long>(lost), queued); +} +} // namespace fence_times + // A fence signalled on a queue completes when the desktop GPU reaches it. struct PendingSignal { Wrapper* fence; UINT64 value; HANDLE event; + fence_times::Entry* timing; }; void CALLBACK signal_reached(PTP_CALLBACK_INSTANCE, void* context, PTP_WAIT wait, TP_WAIT_RESULT) { auto* pending = static_cast<PendingSignal*>(context); fence_reached(pending->fence, pending->value); + fence_times::stored(pending->timing); CloseHandle(pending->event); delete pending; CloseThreadpoolWait(wait); } void complete_when_reached(Wrapper* fence, UINT64 value) { - auto* pending = new PendingSignal{fence, value, CreateEventW(nullptr, FALSE, FALSE, nullptr)}; + auto* pending = new PendingSignal{fence, value, CreateEventW(nullptr, FALSE, FALSE, nullptr), + fence_times::start(fence, value)}; if (FAILED(static_cast<ID3D12Fence*>(fence->own().real)->SetEventOnCompletion(value, pending->event))) { fence_reached(fence, value); + fence_times::stored(pending->timing); CloseHandle(pending->event); delete pending; return; @@ -1764,7 +2639,17 @@ 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) +#include "startup_stubs/frame_rgb_report.inl" + +void reduce_presented(const D3D12_RESOURCE_DESC& desc, const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& footprint, bool rgba, UINT64 total, + ID3D12Resource* readback, LONG paired_frame, ID3D12Resource* surface); + +// LOCAL stall: the read-back copy is issued here (issue) and picked up by a later call once its fence +// has passed, instead of waiting for it (up to 3 s, on the presenting thread, every 6th frame). Present +// calls this with issue false on every frame, so a copy is picked up at the first present after the GPU +// finished it. While a copy is in flight no new one is issued (its allocator is still in use). +// X2W_READBACK_WAIT=1 restores the wait after each copy. +void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface, bool issue = true, LONG paired_frame = 0) { static ID3D12CommandAllocator* allocator; static ID3D12GraphicsCommandList* list; @@ -1772,6 +2657,27 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) static ID3D12Resource* readback; static UINT64 readback_bytes, fence_value; static HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + static const bool wait_for_copy = x2w_local::env_on("X2W_READBACK_WAIT"); + struct InFlight { + ID3D12Resource* surface = nullptr; // held until the copy is done + D3D12_RESOURCE_DESC desc{}; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + bool rgba = false; + UINT64 total = 0; + LONG paired_frame = 0; + }; + static InFlight in_flight; + if (in_flight.surface) { + if (fence->GetCompletedValue() < fence_value) { + if (paired_frame) log("x2w-frame-pair present submit_frame=%ld skipped: readback in flight", paired_frame); + if (issue) std::snprintf(shown_note, sizeof(shown_note), "readback still in flight"); + return; + } + reduce_presented(in_flight.desc, in_flight.footprint, in_flight.rgba, in_flight.total, readback, in_flight.paired_frame, in_flight.surface); + in_flight.surface->Release(); + in_flight.surface = nullptr; + } + if (!issue || !queue || !surface) return; ID3D12Device* device = device_of(the_device); const D3D12_RESOURCE_DESC desc = surface->GetDesc(); D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; @@ -1827,14 +2733,26 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) ID3D12CommandList* lists[] = {list}; queue->ExecuteCommandLists(1, lists); queue->Signal(fence, ++fence_value); + surface->AddRef(); + in_flight = {surface, desc, footprint, rgba, total, paired_frame}; + if (!wait_for_copy) return; fence->SetEventOnCompletion(fence_value, event); if (WaitForSingleObject(event, 3000) != WAIT_OBJECT_0) { std::snprintf(shown_note, sizeof(shown_note), "readback timed out"); - return; + return; // picked up by a later call once the fence passes } + reduce_presented(desc, footprint, rgba, total, readback, paired_frame, surface); + in_flight.surface->Release(); + in_flight.surface = nullptr; +} + +void reduce_presented(const D3D12_RESOURCE_DESC& desc, const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& footprint, bool rgba, UINT64 total, + ID3D12Resource* readback, LONG paired_frame, ID3D12Resource* surface) +{ void* mapped = nullptr; const D3D12_RANGE range{0, static_cast<SIZE_T>(total)}; if (FAILED(readback->Map(0, &range, &mapped))) return; + if (paired_frame) report_frame_rgb("present", paired_frame, surface, mapped, desc, footprint); AcquireSRWLockExclusive(&shown_lock); shown_pixels.resize(shown_width * shown_height); std::uint64_t sum = 0; @@ -1854,8 +2772,12 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) { 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) { - const UINT width = static_cast<UINT>(desc.Width), height = desc.Height; + // A path containing %ld gets the read-back number and a picture reduced to at most 960 pixels + // wide, written at every read-back (about every 2 s), so a run keeps a series of shots. + static const bool numbered = dump && std::wcsstr(dump_path, L"%ld") != nullptr; + if (dump && (numbered || (shown_frames % 4) == 3) && desc.Width <= 8192 && desc.Height <= 8192) { + const UINT step = numbered && desc.Width > 960 ? static_cast<UINT>((desc.Width + 959) / 960) : 1; + const UINT width = static_cast<UINT>(desc.Width) / step, height = desc.Height / step; std::vector<unsigned char> file(54 + std::size_t{width} * height * 4); const std::uint32_t header[] = {static_cast<std::uint32_t>(file.size()), 0, 54, 40, width, static_cast<std::uint32_t>(-static_cast<int>(height)), 1 | (32u << 16), 0, width * height * 4, 2835, 2835, 0, 0}; @@ -1863,16 +2785,23 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) file[1] = 'M'; std::memcpy(file.data() + 2, header, sizeof(header)); for (UINT y = 0; y < height; ++y) { - const auto* row = static_cast<const unsigned char*>(mapped) + footprint.Offset + UINT64{y} * footprint.Footprint.RowPitch; + const auto* row = static_cast<const unsigned char*>(mapped) + footprint.Offset + UINT64{y} * step * footprint.Footprint.RowPitch; unsigned char* out = file.data() + 54 + std::size_t{y} * width * 4; for (UINT x = 0; x < width; ++x) { - out[x * 4 + 0] = rgba ? row[x * 4 + 2] : row[x * 4 + 0]; - out[x * 4 + 1] = row[x * 4 + 1]; - out[x * 4 + 2] = rgba ? row[x * 4 + 0] : row[x * 4 + 2]; + const unsigned char* texel = row + std::size_t{x} * step * 4; + out[x * 4 + 0] = rgba ? texel[2] : texel[0]; + out[x * 4 + 1] = texel[1]; + out[x * 4 + 2] = rgba ? texel[0] : texel[2]; out[x * 4 + 3] = 255; } } - write_file(dump_path, file.data(), file.size()); + if (numbered) { + wchar_t path[MAX_PATH]; + swprintf(path, MAX_PATH, dump_path, static_cast<long>(shown_frames)); + write_file(path, file.data(), file.size()); + } else { + write_file(dump_path, file.data(), file.size()); + } } } const D3D12_RANGE none{0, 0}; @@ -1880,7 +2809,265 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) 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)); - if ((count > 0 && count <= 3) || count % 40 == 0) log("x2w-render presented %s", shown_note); + if (x2w_local::first_of(count, 3) || count % 5 == 0) log("x2w-render presented %s (frame %ld)", shown_note, frame_number); +} + +// LOCAL: render targets drawn into during a traced frame, in first-use order. At the end of the +// traced frame each is copied back on the presenting queue (after the title's work) and summarised: +// the share of texels that are not all zero and the mean byte value, to find the first empty pass. +SRWLOCK traced_lock = SRWLOCK_INIT; +struct TracedTarget { + ID3D12Resource* first; // the target + int second; // drawn draws + ID3D12Resource* snap; // copy taken right after its last drawn draw (COPY_DEST), or null + bool copied = false; + LONG command = 0; + UINT slot = 0; + DXGI_FORMAT view = DXGI_FORMAT_UNKNOWN; // format of the RTV that produced this snapshot +}; +std::vector<TracedTarget>& traced_targets() +{ + static std::vector<TracedTarget> targets; + return targets; +} +struct PlaneStates { + D3D12_RESOURCE_STATES depth, stencil; +}; +PlaneStates current_planes(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_STATES fallback); +void require_planes(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_STATES depth, D3D12_RESOURCE_STATES stencil); +void require_state(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_STATES state); +// `after`: the state the target goes back to after a snapshot copy (LOCAL meshrt: DEPTH_WRITE for a depth target). +void note_traced_target(Wrapper* self, ID3D12Resource* target, bool drawn, + D3D12_RESOURCE_STATES after = D3D12_RESOURCE_STATE_RENDER_TARGET, bool bounded = false, + DXGI_FORMAT view = DXGI_FORMAT_UNKNOWN, LONG command = 0, UINT slot = 0) +{ + if (!target || (!command && gpu_trace_stage_key())) return; + AcquireSRWLockExclusive(&traced_lock); + auto& all = traced_targets(); + auto found = std::find_if(all.begin(), all.end(), [&](const auto& e) { return e.first == target; }); + if (found == all.end()) { + if (bounded) { + const auto desc = target->GetDesc(); + // Up to eight single-sample color snapshots at up to 64 MiB each per selected frame. + if (all.size() >= 8 || desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1 || + device_of(the_device)->GetResourceAllocationInfo(0, 1, &desc).SizeInBytes > (64ull << 20)) { + ReleaseSRWLockExclusive(&traced_lock); + return; + } + } + target->AddRef(); + all.push_back({target, 0, nullptr}); + found = all.end() - 1; + } + static const bool snapshots = x2w_local::env_on("X2W_D3D12_TRACE_TARGETS"); + if (drawn) ++found->second; + if (drawn && snapshots) { + found->view = view; + D3D12_RESOURCE_DESC desc = target->GetDesc(); + if (!found->snap && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1) { + desc.Flags &= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; // LOCAL meshrt: a depth target's copy keeps its depth format legal + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + if (FAILED(device_of(the_device)->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&found->snap)))) + found->snap = nullptr; + } + if (found->snap && self->own().list_open) { + auto* list = static_cast<ID3D12GraphicsCommandList*>(self->own().real); + const auto before = current_planes(self, target, after); + require_state(self, target, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyResource(found->snap, target); + found->copied = true; + found->command = command; + found->slot = slot; + require_planes(self, target, before.depth, before.stencil); + } + } + ReleaseSRWLockExclusive(&traced_lock); +} +// LOCAL meshrt, fixtures: the targets noted in traced frames so far, first-use order, 4 words each (width, height, +// format, drawn draws); returns how many are noted. +extern "C" __declspec(dllexport) unsigned x2w_d3d12_traced_targets(unsigned* out, unsigned capacity) +{ + AcquireSRWLockShared(&traced_lock); + const auto& all = traced_targets(); + for (unsigned i = 0; out && i < capacity && i < all.size(); ++i) { + const D3D12_RESOURCE_DESC desc = all[i].first->GetDesc(); + out[4 * i] = static_cast<unsigned>(desc.Width); + out[4 * i + 1] = desc.Height; + out[4 * i + 2] = static_cast<unsigned>(desc.Format); + out[4 * i + 3] = static_cast<unsigned>(all[i].second); + } + const unsigned count = static_cast<unsigned>(all.size()); + ReleaseSRWLockShared(&traced_lock); + return count; +} +void summarise_traced_targets(ID3D12CommandQueue* queue, LONG request_id = 0); +// LOCAL meshrt, fixtures that never present: the end-of-frame read-back (x2w-frame target lines) on a queue of its own; +// empties the noted list as at a present. +extern "C" __declspec(dllexport) int x2w_d3d12_summarise_traced_targets() +{ + if (!the_device) return 0; + ID3D12CommandQueue* queue = nullptr; + const D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(device_of(the_device)->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue)))) return 0; + summarise_traced_targets(queue); + queue->Release(); + return 1; +} +void report_texture_pixels(const char* label, const char* grid_label, const void* mapped, const D3D12_RESOURCE_DESC& desc, + const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& footprint, UINT rows, UINT64 row_bytes) +{ + const UINT texel = desc.Width ? static_cast<UINT>(row_bytes / desc.Width) : 0; + std::uint64_t nonzero = 0, sum = 0, texels = 0; + for (UINT y = 0; y < rows; y += 2) { + const auto* row = static_cast<const unsigned char*>(mapped) + footprint.Offset + UINT64{y} * footprint.Footprint.RowPitch; + for (UINT64 x = 0; x < desc.Width && texel; x += 2) { + bool any = false; + for (UINT b = 0; b < texel; ++b) { + any |= row[x * texel + b] != 0; + sum += row[x * texel + b]; + } + nonzero += any; + ++texels; + } + } + log("%s: non-zero texels %.4f, mean byte %.2f", label, + texels ? double(nonzero) / texels : 0.0, texels && texel ? double(sum) / (texels * texel) : 0.0); + // LOCAL (scene): raw texels on a 3x3 grid (at 1/6, 3/6, 5/6 of width and height), so a flat colour + // and where it sits can be read per target without an image dump. + if (texel && texel <= 16 && rows) { + char text[9 * 36 + 1]{}; + std::size_t used = 0; + for (UINT gy = 1; gy < 6; gy += 2) + for (UINT gx = 1; gx < 6; gx += 2) { + const UINT y = static_cast<UINT>(UINT64{rows} * gy / 6); + const UINT64 x = desc.Width * gx / 6; + const auto* at = static_cast<const unsigned char*>(mapped) + footprint.Offset + UINT64{y} * footprint.Footprint.RowPitch + x * texel; + if (used + 2 * texel + 2 < sizeof(text)) { + for (UINT b = 0; b < texel; ++b) used += std::snprintf(text + used, sizeof(text) - used, "%02x", at[b]); + used += std::snprintf(text + used, sizeof(text) - used, " "); + } + } + log("%s texels 3x3 (rows top to bottom, raw bytes): %s", grid_label, text); + } +} +void summarise_traced_targets(ID3D12CommandQueue* queue, LONG request_id) +{ + wchar_t directory[MAX_PATH]{}; + const auto length = GetEnvironmentVariableW(L"X2W_TRACE_TARGET_DIR", directory, MAX_PATH); + std::filesystem::path output_dir; + if (length && length < MAX_PATH) { + output_dir = directory; + if (request_id) { + output_dir /= L"request-" + std::to_wstring(request_id); + std::error_code error; + if (!std::filesystem::create_directory(output_dir, error)) { + log("x2w-frame scene request %ld needs a fresh output directory (error %d)", request_id, error.value()); + output_dir.clear(); + } + } + } + AcquireSRWLockExclusive(&traced_lock); + std::vector<TracedTarget> all; + all.swap(traced_targets()); + ReleaseSRWLockExclusive(&traced_lock); + ID3D12Device* device = device_of(the_device); + ID3D12CommandAllocator* allocator = nullptr; + ID3D12GraphicsCommandList* list = nullptr; + ID3D12Fence* fence = nullptr; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + HRESULT hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)); + if (SUCCEEDED(hr)) hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, nullptr, IID_PPV_ARGS(&list)); + if (SUCCEEDED(hr)) hr = list->Close(); + if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); + UINT64 fence_value = 0; + for (std::size_t n = 0; n < all.size() && SUCCEEDED(hr); ++n) { + ID3D12Resource* target = all[n].copied ? all[n].snap : all[n].first; + const D3D12_RESOURCE_STATES rest = all[n].copied ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COMMON; + const D3D12_RESOURCE_DESC desc = target->GetDesc(); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT rows = 0; + UINT64 row_bytes = 0, total = 0; + device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, &rows, &row_bytes, &total); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || total == 0 || total == ~0ull || total > (512ull << 20)) { + log("x2w-frame target %zu %p fmt %d: not summarised", n, static_cast<void*>(target), desc.Format); + continue; + } + ID3D12Resource* readback = nullptr; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = total; + buffer.Height = 1; + buffer.DepthOrArraySize = 1; + buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback)))) continue; + allocator->Reset(); + list->Reset(allocator, nullptr); + transition(list, target, rest, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION from{}, to{}; + from.pResource = target; + from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + to.pResource = readback; + to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + to.PlacedFootprint = footprint; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + transition(list, target, D3D12_RESOURCE_STATE_COPY_SOURCE, rest); + list->Close(); + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + queue->Signal(fence, ++fence_value); + fence->SetEventOnCompletion(fence_value, event); + if (WaitForSingleObject(event, 5000) != WAIT_OBJECT_0) { + log("x2w-frame target %zu: read-back timed out", n); + readback->Release(); + break; + } + void* mapped = nullptr; + const D3D12_RANGE range{0, static_cast<SIZE_T>(total)}; + if (SUCCEEDED(readback->Map(0, &range, &mapped))) { + char label[160], grid_label[48]; + std::snprintf(grid_label, sizeof(grid_label), "x2w-frame target %zu", n); + std::snprintf(label, sizeof(label), "%s %s %p %llux%u fmt %d draws %d", grid_label, all[n].copied ? "snapshot" : "end", + static_cast<void*>(all[n].first), desc.Width, desc.Height, desc.Format, all[n].second); + if (all[n].command) + log("x2w-frame target %zu last recorded copy after command #%ld RTV[%u] resource=%p view_fmt=%u", + n, all[n].command, all[n].slot, static_cast<void*>(all[n].first), UINT(all[n].view)); + report_texture_pixels(label, grid_label, mapped, desc, footprint, rows, row_bytes); + const auto preview = all[n].view != DXGI_FORMAT_UNKNOWN ? all[n].view : desc.Format; + if (!output_dir.empty() && x2w_draw_bmp::trace_supported(preview)) { + const auto path = output_dir / (L"target-" + std::to_wstring(n) + L".bmp"); + FILE* file = nullptr; + if (_wfopen_s(&file, path.c_str(), L"wbx") == 0) { + const auto* pixels = static_cast<const unsigned char*>(mapped) + footprint.Offset; + const bool written = x2w_draw_bmp::write(file, pixels, footprint.Footprint.Width, rows, + footprint.Footprint.RowPitch, preview); + const bool closed = std::fclose(file) == 0; + if (!written || !closed) { + DeleteFileW(path.c_str()); + log("x2w-frame target %zu: image write failed", n); + } else log("x2w-frame target %zu BMP view fmt %d%s", n, preview, + preview == DXGI_FORMAT_R16G16_FLOAT ? " signed RG, zero at 128" : ""); + } else { + log("x2w-frame target %zu: could not open image output", n); + } + } + const D3D12_RANGE none{0, 0}; + readback->Unmap(0, &none); + } + readback->Release(); + } + for (auto& e : all) { + e.first->Release(); + if (e.snap) e.snap->Release(); + } + if (list) list->Release(); + if (allocator) allocator->Release(); + if (fence) fence->Release(); + CloseHandle(event); } // --------------------------------------------------------------------------------------------- @@ -1932,8 +3119,35 @@ HRESULT __stdcall device_create_root_signature(Wrapper* self, UINT node, const v if (!out || !iid) return E_POINTER; *out = nullptr; ID3D12RootSignature* root = nullptr; + // LOCAL: the title's root signatures carry CBV_SRV_UAV/SAMPLER_HEAP_DIRECTLY_INDEXED. The title's + // SetDescriptorHeaps is not forwarded (translated draws bind their own heaps), so setting such a + // root on a desktop list is an error (#1419). No title shader runs against these roots on the + // desktop, so the two flags are cleared there; the title's blob is kept for translation keys. + ID3DBlob* stripped = nullptr; + { + ID3D12VersionedRootSignatureDeserializer* reader = nullptr; + if (blob && SUCCEEDED(D3D12CreateVersionedRootSignatureDeserializer(blob, size, IID_PPV_ARGS(&reader)))) { + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc = nullptr; + constexpr UINT indexed = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | + D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + if (SUCCEEDED(reader->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &desc)) && desc && + (static_cast<UINT>(desc->Desc_1_1.Flags) & indexed)) { + D3D12_VERSIONED_ROOT_SIGNATURE_DESC copy = *desc; + copy.Desc_1_1.Flags = static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(static_cast<UINT>(copy.Desc_1_1.Flags) & ~indexed); + if (FAILED(D3D12SerializeVersionedRootSignature(©, &stripped, nullptr))) stripped = nullptr; + static LONG strips; + if (first_calls(strips, 4)) + log("x2w-d3d12 Device::CreateRootSignature flags 0x%x: heap-directly-indexed bits cleared for the desktop (%s)", + static_cast<UINT>(desc->Desc_1_1.Flags), stripped ? "ok" : "serialize failed, kept"); + } + reader->Release(); + } + } const HRESULT hr = kind_for(*iid) == root_signature_kind - ? device_of(self)->CreateRootSignature(node, blob, size, IID_PPV_ARGS(&root)) : E_NOINTERFACE; + ? device_of(self)->CreateRootSignature(node, stripped ? stripped->GetBufferPointer() : blob, + stripped ? stripped->GetBufferSize() : size, IID_PPV_ARGS(&root)) + : E_NOINTERFACE; + if (stripped) stripped->Release(); static LONG calls; const bool log_it = first_calls(calls, 6); if (FAILED(hr)) { @@ -2255,67 +3469,26 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES // Transient data the title addresses by GPU address (fetch tables, vertices, constants) is copied // from its memory into a desktop upload buffer; the copy's GPU address is bound instead. -ID3D12Resource* upload_ring; -bool ring_copy(u64 title_address, std::size_t bytes, u64* offset); -D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(u64 title_address, std::size_t bytes) -{ - u64 offset = 0; - return ring_copy(title_address, bytes, &offset) ? upload_ring->GetGPUVirtualAddress() + offset : 0; -} -unsigned char* reserve_upload_ring(std::size_t bytes, u64* offset) -{ - constexpr u64 ring_bytes = u64{256} << 20; - ID3D12Resource*& ring = upload_ring; - static unsigned char* mapped; - static volatile LONG64 cursor; - static SRWLOCK lock = SRWLOCK_INIT; - if (!ring) { - AcquireSRWLockExclusive(&lock); - if (!ring) { - const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_UPLOAD}; - D3D12_RESOURCE_DESC buffer{}; - buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - buffer.Width = ring_bytes; - buffer.Height = 1; - buffer.DepthOrArraySize = 1; - buffer.MipLevels = 1; - buffer.SampleDesc.Count = 1; - buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - ID3D12Resource* created = nullptr; - void* base = nullptr; - auto* device = device_of(the_device); - if (SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&created)))) { - auto* budget = x2w_budget::committed(device, created, D3D12_HEAP_TYPE_UPLOAD); - if (SUCCEEDED(created->Map(0, nullptr, &base))) { - mapped = static_cast<unsigned char*>(base); - ring = created; - } else if (budget) { - budget->end_use(); // The failed Map leaves the existing desktop reference held. - } - } - } - ReleaseSRWLockExclusive(&lock); - } - if (!ring || bytes == 0 || bytes > ring_bytes / 4) return nullptr; - const u64 rounded = (bytes + 511) & ~u64{511}; // 512: texture footprints are placed in the ring too - u64 start = static_cast<u64>(InterlockedExchangeAdd64(&cursor, static_cast<LONG64>(rounded))) % ring_bytes; - if (start + rounded > ring_bytes) start = static_cast<u64>(InterlockedExchangeAdd64(&cursor, static_cast<LONG64>(rounded) + (ring_bytes - start))) % ring_bytes, start = 0; - *offset = start; - return mapped + start; -} - -bool ring_copy(u64 title_address, std::size_t bytes, u64* offset) +// LOCAL memcut: the buffer is a chunk of the upload ring (d3d12_upload_ring.inl), returned with the offset. +#include "startup_stubs/d3d12_upload_ring.inl" +bool ring_copy(u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** buffer) { - auto* dest = reserve_upload_ring(bytes, offset); + auto* dest = reserve_upload_ring(bytes, offset, buffer, nullptr); if (!dest) return false; std::memcpy(dest, reinterpret_cast<const void*>(title_address), bytes); return true; } +D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(u64 title_address, std::size_t bytes) +{ + u64 offset = 0; + ID3D12Resource* buffer = nullptr; + return ring_copy(title_address, bytes, &offset, &buffer) ? buffer->GetGPUVirtualAddress() + offset : 0; +} // Number of contiguous readable bytes at address, up to wanted. std::size_t readable_window(u64 address, std::size_t wanted) { + Timed timed(time_cx_readable); return x2w_local::probe_readable(static_cast<std::uintptr_t>(address), wanted); } @@ -2336,22 +3509,24 @@ struct Pass { std::vector<CopyRange> copied_gpu_ranges; // exact CopyBufferRegion destinations on this recording bool pipeline_real = false; // the bound pipeline has a desktop pipeline bool compute_pipeline = false; - ID3D12RootSignature* compute_root = nullptr; // latest guest root if it was forwarded - x2w_startup::ComPtr<ID3D12RootSignature> desktop_compute_root; // last root actually set on this recording - std::array<D3D12_GPU_VIRTUAL_ADDRESS, 64> desktop_compute_upload_srvs{}; + ID3D12RootSignature* compute_root_desktop = nullptr; // upstream: desktop compute root set by its slot 33 (local: compute_root below) + x2w_startup::ComPtr<ID3D12RootSignature> desktop_compute_root; // upstream: last root its slot 33 set on this recording + std::array<D3D12_GPU_VIRTUAL_ADDRESS, 64> desktop_compute_upload_srvs{}; // upstream slot 43 (X2W_UPSTREAM_COMPUTE_ROOT) const std::vector<RootParameter>* compute_params = nullptr; std::unique_ptr<ComputeBindingTrace> compute_trace; IndirectGraphicsPipeline indirect_graphics; ID3D12RootSignature* graphics_root = nullptr; bool targets_bound = false; + bool targets_refused = false; // reset/explicitly empty OM is valid for UAV-only graphics bool topology_ok = false; unsigned srv_bound = 0; // bit per root parameter with a desktop address bound + unsigned srv_pending = 0; // LOCAL stall: X2W_ROOT_SRV_LAZY, root SRVs set but not copied yet const std::vector<RootParameter>* root = nullptr; // Heap-indexing flags of the title root signature last set by slot 34. While nonzero, that root signature is // deferred: it is not set on the desktop list, root SRVs are not forwarded, and real draws go through decide_real_root. UINT root_heap_flags = 0; ID3D12RootSignature* deferred_root = nullptr; - std::vector<std::pair<ID3D12Resource*, D3D12_RESOURCE_STATES>> states; // resources this list moved out of COMMON + x2w_gpu::ListStates states; // What the title bound, kept for draws through translated pipelines: Wrapper* pipeline = nullptr; Wrapper* requested_pipeline = nullptr; // last pipeline slot 61 asked a translation for; repeats skip draw_lock @@ -2369,11 +3544,19 @@ struct Pass { D3D12_INDEX_BUFFER_VIEW ib = {}; DXGI_FORMAT target_formats[8] = {}; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; + bool read_depth_plane = false, read_stencil_plane = false; + bool dsv_read_only = false; // LOCAL (renderstate): the bound depth target is a read-only view (d3d12_draw.inl drops depth writes) + ID3D12Resource* dsv_resource = nullptr; // LOCAL (renderstate): desktop resource of the bound depth target bool targets_single_sample = false; bool depth_view_writable = false; UINT stencil_reference = 0; // last guest OMSetStencilRef on this recording UINT target_count = 0; ID3D12Resource* target0 = nullptr; // desktop resource of render target 0 (for per-draw dumps) + // LOCAL meshrt: every bound target's desktop resource and the first viewport / scissor the list set, for the + // traced-frame mesh lines (d3d12_mesh.inl mesh_trace_call). Valid for i < target_count. + ID3D12Resource* targets[8] = {}; + D3D12_VIEWPORT viewport0 = {}; + D3D12_RECT scissor0 = {}; ID3D12Resource* trace_targets[8]{}; ID3D12Resource* trace_depth = nullptr; bool heap_set = false; @@ -2381,6 +3564,13 @@ struct Pass { std::unique_ptr<x2w_startup::SamplerSnapshot> sampler_snapshot; x2w_startup::ComPtr<ID3D12DescriptorHeap> sampler_heap; ID3D12DescriptorHeap* bound_sampler_heap = nullptr; + // LOCAL: compute root state (kind 1 constants, 2 CBV, 3 SRV, 4 UAV, 5 table) + Wrapper* compute_root = nullptr; + int compute_kind[16] = {}; + u64 compute_address[16] = {}; + std::uint32_t compute_constants[16][16] = {}; + UINT compute_count[16] = {}; + std::uint16_t compute_set[16] = {}; // LOCAL: constant words set since the root signature changed (entry value checks) // Whether the title set a viewport / scissor on this list; without them a desktop list draws no pixel. bool viewport_set = false; bool scissor_set = false; @@ -2439,40 +3629,44 @@ void note_copy_gpu_range(Wrapper* self, ID3D12Resource* resource, u64 offset, u6 } } // Desktop resources rest in COMMON between lists; a list moves them as it needs and back at Close. +PlaneStates current_planes(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_STATES fallback) +{ + if (const auto* entry = pass_of(self).states.find(resource)) return {entry->depth, entry->stencil}; + return {fallback, fallback}; +} +void require_planes(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_STATES depth, D3D12_RESOURCE_STATES stencil) +{ + pass_of(self).states.require(static_cast<ID3D12GraphicsCommandList*>(self->own().real), resource, depth, stencil); +} void require_state(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_STATES state) { - Pass& pass = pass_of(self); - auto* list = static_cast<ID3D12GraphicsCommandList*>(self->own().real); - for (auto& known : pass.states) { - if (known.first != resource) continue; - if (known.second != state) { - transition(list, resource, known.second, state); - known.second = state; - } - return; - } - transition(list, resource, D3D12_RESOURCE_STATE_COMMON, state); - pass.states.emplace_back(resource, state); + require_planes(self, resource, state, state); +} +void require_bound_depth(Wrapper* self, D3D12_RESOURCE_STATES shader_reads = D3D12_RESOURCE_STATE_COMMON) +{ + const auto& pass = pass_of(self); + const auto read = D3D12_RESOURCE_STATE_DEPTH_READ | shader_reads; + require_planes(self, pass.dsv_resource, pass.read_depth_plane ? read : D3D12_RESOURCE_STATE_DEPTH_WRITE, + pass.read_stencil_plane ? read : D3D12_RESOURCE_STATE_DEPTH_WRITE); } -// State for a draw that samples `resource`: a depth texture also bound as a read-only DSV keeps DEPTH_READ. -D3D12_RESOURCE_STATES sampled_state(Wrapper* self, ID3D12Resource* resource) +void require_sampled(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_STATES reads) { - for (const auto& known : pass_of(self).states) - if (known.first == resource && (known.second & D3D12_RESOURCE_STATE_DEPTH_READ)) - return D3D12_RESOURCE_STATE_DEPTH_READ | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + const auto& pass = pass_of(self); + if (pass.dsv_resource == resource && (pass.read_depth_plane || pass.read_stencil_plane)) require_bound_depth(self, reads); + else require_state(self, resource, reads); } void use_as_target(Wrapper* self, ID3D12Resource* resource) { require_state(self, resource, D3D12_RESOURCE_STATE_RENDER_TARGET); } #include "startup_stubs/mesh_xmem_handoff.inl" +volatile LONG trace_uav_busy_frame; #include "startup_stubs/red_producer_diagnostic.inl" +#include "startup_stubs/cx_input_dump.inl" // LOCAL lt-lead probe: X2W_CX_TRACE_CLEARS, X2W_CX_DUMP_INPUTS void discard_red_producer(ID3D12GraphicsCommandList* list) { red_producers().discard(list); } void release_targets(Wrapper* self) { Pass& pass = pass_of(self); - for (const auto& known : pass.states) - transition(static_cast<ID3D12GraphicsCommandList*>(self->own().real), known.first, known.second, D3D12_RESOURCE_STATE_COMMON); + pass.states.close(static_cast<ID3D12GraphicsCommandList*>(self->own().real)); pass = Pass{}; } @@ -2540,9 +3734,12 @@ UINT __stdcall list_resource_barriers(Wrapper* self, UINT count, const D3D12_RES Wrapper* resource = as_wrapper(barrier.UAV.pResource); if (!resource || resource->own().kind != resource_kind || !resource->own().real) continue; auto* real = static_cast<ID3D12Resource*>(resource->own().real); - if (!(real->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) continue; Microsoft::WRL::ComPtr<ID3D12Device> owner; if (FAILED(real->GetDevice(IID_PPV_ARGS(&owner))) || owner.Get() != device_of(self->own().list_device)) continue; + if (!(real->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + if (x2w_gpu::gpu_abi_on() && gpu_depth_barrier(self, resource)) ++forwarded; + continue; + } barrier.UAV.pResource = real; } list->ResourceBarrier(1, &barrier); @@ -2555,25 +3752,25 @@ 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 } -void __stdcall list_compute_root(Wrapper* self, void* root) +void __stdcall list_compute_root_desktop(Wrapper* self, void* root) { auto* list = recording(self); if (!list) return; Wrapper* w = as_wrapper(root); Pass& pass = pass_of(self); const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); - pass.compute_root = real ? static_cast<ID3D12RootSignature*>(w->own().real) : nullptr; + pass.compute_root_desktop = real ? static_cast<ID3D12RootSignature*>(w->own().real) : nullptr; pass.compute_tables.set_signature(w ? root_info(w) : nullptr); // a different signature leaves no table bound pass.compute_params = real ? root_info(w) : nullptr; if (compute_binding_trace_enabled() && (!pass.compute_trace || pass.compute_trace->root != w)) { pass.compute_trace = std::make_unique<ComputeBindingTrace>(); pass.compute_trace->root = w; } - if (pass.compute_root) { - if (pass.desktop_compute_root.Get() != pass.compute_root) + if (pass.compute_root_desktop) { + if (pass.desktop_compute_root.Get() != pass.compute_root_desktop) pass.desktop_compute_upload_srvs.fill(0); - pass.desktop_compute_root = pass.compute_root; - list->SetComputeRootSignature(pass.compute_root); + pass.desktop_compute_root = pass.compute_root_desktop; + list->SetComputeRootSignature(pass.compute_root_desktop); } } @@ -2760,7 +3957,7 @@ constexpr const char* unknown = "unknown"; } // namespace indirect_other_refusal_code // 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 __stdcall list_execute_indirect_upstream(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, void* count_buffer, u64 count_offset) { // Every refusal is counted under the signature's kind, including those before the signature is checked. @@ -2879,9 +4076,9 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, 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 (!pass.compute_pipeline || !pass.compute_root) { + } else if (!pass.compute_pipeline || !pass.compute_root_desktop) { 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) { + } else if (sig->own().signature_root && sig->own().signature_root != pass.compute_root_desktop) { return refuse("signature root constants require the bound compute root", indirect_other, indirect_other_refusal_code::compute_root_mismatch); } else if (sig->own().signature_root && (count != 1 || count_buffer)) { // Batched and count-buffer Dispatch is supported for rootless signatures only in this slice. @@ -3065,8 +4262,12 @@ void __stdcall list_graphics_root(Wrapper* self, void* root) } pass.root = params; pass.srv_bound = 0; + pass.srv_pending = 0; + // LOCAL: a root signature with heap-indexing flags is set on the desktop list as before. Upstream defers it + // (not set; real draws on it refused) only with X2W_DEFER_HEAP_ROOTS=1. + static const bool defer_heap_roots = x2w_local::env_on("X2W_DEFER_HEAP_ROOTS"); const bool real = w && w->own().kind == root_signature_kind && w->own().real; - pass.root_heap_flags = real ? root_heap_flags(w) : 0; + pass.root_heap_flags = real && defer_heap_roots ? root_heap_flags(w) : 0; pass.deferred_root = pass.root_heap_flags ? static_cast<ID3D12RootSignature*>(w->own().real) : nullptr; pass.graphics_root = nullptr; auto* list = recording(self); @@ -3202,36 +4403,33 @@ void __stdcall list_clear_depth_stencil(Wrapper* self, u64 handle, D3D12_CLEAR_F return; } auto* list = static_cast<ID3D12GraphicsCommandList*>(self->own().real); + const auto before = current_planes(self, target, D3D12_RESOURCE_STATE_DEPTH_WRITE); require_state(self, target, D3D12_RESOURCE_STATE_DEPTH_WRITE); + cx_dump::note_clear("dsv", handle, target, 0, nullptr, false, depth, stencil, static_cast<unsigned>(flags), rect_count, nullptr); const auto red_sample = red_producers().before(self, list, target, "clear-dsv", 0, 0); list->ClearDepthStencilView(D3D12_CPU_DESCRIPTOR_HANDLE{static_cast<SIZE_T>(desktop)}, flags, depth, stencil, rect_count, rect_count ? rects : nullptr); red_producers().after(self, red_sample); + if (pass_of(self).dsv_resource == target) require_planes(self, target, before.depth, before.stencil); InterlockedIncrement(&render_clears); } // List slot 52 (desktop 48 + 4), ClearRenderTargetView(view, colour, rect count, rects). Desktop -// resources rest in COMMON here, so the target is moved to RENDER_TARGET around the clear. The view is -// read from its shadow record, as OMSetRenderTargets does, so a descriptor the title copied clears the -// resource it now holds; a handle with no record falls back to the creation-time map. +// resources rest in COMMON here, so the target is moved to RENDER_TARGET around the clear. +LONG clears_dropped[2]; // slot 52 dropped: [0] list not open or no colour, [1] view resolves to no target void __stdcall list_clear_target(Wrapper* self, u64 handle, const float* colour, UINT rect_count, const D3D12_RECT* rects) { - if (!self->own().list_open || !colour) return; + if (!self->own().list_open || !colour) { + cx_dump::note_clear("rtv", handle, nullptr, 0, colour, true, 0, 0, 0, rect_count, !colour ? "no colour" : "list not open"); + return (void)InterlockedIncrement(&clears_dropped[0]); + } const u64 desktop = desktop_cpu_handle(handle); - const ResolvedView view = resolve_view(desktop, 20); - ID3D12Resource* target = view.resource; + ID3D12Resource* target = view_target(desktop); + cx_dump::note_clear("rtv", handle, target, 0, colour, true, 0, 0, 0, rect_count, target ? nullptr : "view resolves to no target"); static LONG logged; if (first_calls(logged, 4)) log("x2w-render ClearRenderTargetView view=0x%llx target=%p colour=%.3f %.3f %.3f %.3f rects=%u", handle, static_cast<void*>(target), colour[0], colour[1], colour[2], colour[3], rect_count); - if (!target) { - InterlockedIncrement(&render_target_unresolved); - static LONG refused; - if (first_calls(refused, 6)) - log("x2w-d3d12 ClearRenderTargetView skipped: view 0x%llx is %s", handle, - view.wrong_kind ? "not a render target view" - : view.skipped ? "a skipped render target view" : "not a known render target view"); - return; - } + if (!target) return (void)InterlockedIncrement(&clears_dropped[1]); auto* list = static_cast<ID3D12GraphicsCommandList*>(self->own().real); use_as_target(self, target); const auto red_sample = red_producers().before(self, list, target, "clear-rtv", 0, 0); @@ -3240,6 +4438,17 @@ void __stdcall list_clear_target(Wrapper* self, u64 handle, const float* colour, red_producers().after(self, red_sample); InterlockedIncrement(&render_clears); } + +// Outcome of every slot 50 call (exactly one each), reported and reset every 300 presented frames. +enum TargetBind { + bind_bound, bind_single_range_bound, bind_not_recording, bind_count_over_8, bind_handles_unreadable, + bind_range_past_heap, bind_wrong_kind, bind_unresolved, bind_empty, bind_depth_wrong_kind, bind_depth_unknown, + bind_outcomes +}; +LONG bound_mixed_depth, target_binds[bind_outcomes], target_unresolved_at[8]; +LONG target_depth_unreadable, target_depth_unmapped; // bound without the depth the title passed +LONG draws_without_targets; // translated draws refused because no bind succeeded on the list (d3d12_draw.inl) +LONG state_dropped[3]; // while recording: viewports, scissors (count 0, over 16 or unreadable), blend factor unreadable // The desktop shader-visible CBV/SRV/UAV heap that owns the GPU handle's descriptor, or null. ID3D12DescriptorHeap* owning_view_heap(u64 gpu) { @@ -3288,6 +4497,7 @@ void __stdcall list_clear_uav(Wrapper* self, u64 gpu_handle, u64 cpu_handle, u64 else if (!(view_heap = owning_view_heap(gpu_handle))) why = "GPU handle is on no known descriptor heap"; else if (!(target->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) why = "resource lacks unordered access"; else if (!tracked_from_common(title_resource)) why = "resource does not use COMMON state tracking"; + cx_dump::note_clear(Float ? "uav-float" : "uav-uint", cpu_handle, target, title_resource, values, Float, 0, 0, 0, rect_count, why); if (why) { InterlockedIncrement(&render_target_unresolved); if (first_calls(refused, 6)) log("x2w-d3d12 %s skipped: %s (view 0x%llx)", name, why, cpu_handle); @@ -3334,10 +4544,12 @@ void __stdcall list_discard(Wrapper* self, u64 title_resource, const D3D12_DISCA if (first_calls(logged, 4)) log("x2w-render DiscardResource resource=%p rects=%u", static_cast<void*>(resource), region ? safe.NumRects : 0); } // List slot 50 (desktop 46 + 4), OMSetRenderTargets(count, handles, single range, depth). -// With single_range the title passes the first handle only and the rest follow it at the title's own -// descriptor stride (also for one target). A descriptor of the wrong kind, a handle that holds no view, a -// DSV with only one plane read-only (needs per-plane states), or a depth view that resolves to nothing -// refuses the whole bind: nothing is set and draws are skipped. Each refusal is logged and counted. +// With single_range the title passes only the first handle; target i is at handle + i * the title's RTV +// stride (title_descriptor_stride: for RTV heaps the same desktop increment the title reads from the +// forwarded GetDescriptorHandleIncrementSize), and each is mapped to its desktop descriptor on its own. +// A descriptor of the wrong kind, a colour handle that holds no view, +// or a depth view that resolves to nothing refuses the whole bind: +// desktop targets are unbound and subsequent graphics work is skipped until the next valid bind. void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* handles, BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* depth) { @@ -3349,47 +4561,53 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO pass.target_count = 0; pass.target0 = nullptr; pass.dsv_format = DXGI_FORMAT_UNKNOWN; - if (!list) return; + pass.read_depth_plane = pass.read_stencil_plane = false; + pass.dsv_read_only = false; + pass.dsv_resource = nullptr; + std::fill_n(pass.trace_targets, 8, nullptr); + pass.trace_depth = nullptr; static LONG refused, unresolved_logged; + const auto refuse = [&](TargetBind why) { + pass.targets_refused = true; + if (list) list->OMSetRenderTargets(0, nullptr, FALSE, nullptr); + InterlockedIncrement(&target_binds[why]); + }; + if (!list) return refuse(bind_not_recording); if (count > 8) { - InterlockedIncrement(&render_target_unresolved); if (first_calls(refused, 6)) log("x2w-d3d12 OMSetRenderTargets refused: %u render targets (at most 8)", count); - return; + return refuse(bind_count_over_8); } const UINT listed = single_range ? (count ? 1 : 0) : count; - if (listed && !x2w_local::readable(handles, listed * sizeof(*handles))) return; - UINT stride = 0; + if (listed && !x2w_local::readable(handles, listed * sizeof(*handles))) return refuse(bind_handles_unreadable); + u64 stride = 0; if (single_range && count) { - const UINT increment = the_device ? device_of(the_device)->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) : 0; - stride = increment ? title_descriptor_stride(handles[0].ptr, increment) : 0; - if (!stride) { - InterlockedIncrement(&render_target_unresolved); - return; + const UINT increment = the_device ? device_of(the_device)->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) : 0; + stride = title_descriptor_stride(handles[0].ptr, increment); + UINT available = 0; + desktop_cpu_handle(handles[0].ptr, nullptr, &available); + if (!stride || available < count) { + if (first_calls(refused, 6)) + log("x2w-d3d12 OMSetRenderTargets refused: single range of %u at 0x%llx has %u descriptors left in its heap", + count, static_cast<unsigned long long>(handles[0].ptr), available); + return refuse(bind_range_past_heap); } } D3D12_CPU_DESCRIPTOR_HANDLE desktop[8]; ID3D12Resource* targets[8]{}; DXGI_FORMAT formats[8]{}; for (UINT i = 0; i < count; ++i) { - const u64 step = u64{i} * stride; - if (single_range && handles[0].ptr > (~u64{0}) - step) { - InterlockedIncrement(&render_target_unresolved); - if (first_calls(unresolved_logged, 6)) - log("x2w-d3d12 OMSetRenderTargets refused: render target %u handle overflow (0x%llx + %llu)", i, - static_cast<unsigned long long>(handles[0].ptr), static_cast<unsigned long long>(step)); - return; - } - const u64 title = single_range ? handles[0].ptr + step : handles[i].ptr; + const u64 title = single_range ? handles[0].ptr + i * stride : handles[i].ptr; desktop[i].ptr = static_cast<SIZE_T>(desktop_cpu_handle(title)); const ResolvedView view = resolve_view(desktop[i].ptr, 20); if (view.wrong_kind && first_calls(refused, 6)) log("x2w-d3d12 OMSetRenderTargets refused: render target %u is not a render target view", i); targets[i] = view.resource; if (!targets[i]) { - InterlockedIncrement(&render_target_unresolved); - if (!view.wrong_kind && first_calls(unresolved_logged, 6)) - log("x2w-d3d12 OMSetRenderTargets refused: render target %u (0x%llx) %s", i, static_cast<unsigned long long>(title), - view.skipped ? "holds a skipped view" : "holds no view"); - return; + if (view.wrong_kind) return refuse(bind_wrong_kind); + if (first_calls(refused, 6)) + log("x2w-d3d12 OMSetRenderTargets refused: render target %u of %u (title 0x%llx, %s) holds no known view", i, count, + static_cast<unsigned long long>(title), single_range ? "single range" : "array"); + InterlockedIncrement(&target_unresolved_at[i]); + return refuse(bind_unresolved); } formats[i] = view_format_of(desktop[i].ptr, targets[i]); } @@ -3397,39 +4615,44 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO const D3D12_CPU_DESCRIPTOR_HANDLE* dsv_ptr = nullptr; ID3D12Resource* dsv_target = nullptr; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; - D3D12_RESOURCE_STATES dsv_state = D3D12_RESOURCE_STATE_DEPTH_WRITE; + + if (depth && !x2w_local::readable(depth, sizeof(*depth))) InterlockedIncrement(&target_depth_unreadable); if (depth && x2w_local::readable(depth, sizeof(*depth))) { const u64 resolved = desktop_cpu_handle(depth->ptr); + if (!resolved && depth->ptr) InterlockedIncrement(&target_depth_unmapped); if (!resolved) { // The handle maps to no desktop descriptor: no depth is bound although the pipeline may expect one. InterlockedIncrement(&render_target_unresolved); if (first_calls(unresolved_logged, 6)) log("x2w-d3d12 OMSetRenderTargets: depth handle 0x%llx maps to no descriptor; binding no depth", static_cast<unsigned long long>(depth->ptr)); - } else { + } + if (resolved) { const ResolvedView view = resolve_view(resolved, 21); dsv_target = view.resource; if (!dsv_target) { InterlockedIncrement(&render_target_unresolved); if (first_calls(refused, 6)) - log("x2w-d3d12 OMSetRenderTargets refused: depth handle is %s", - view.wrong_kind ? "not a depth stencil view" - : view.skipped ? "a skipped depth stencil view" : "not a known depth stencil view"); - return; + log("x2w-d3d12 OMSetRenderTargets refused: depth handle is %s", view.wrong_kind ? "not a depth stencil view" : "not a known depth stencil view"); + return refuse(view.wrong_kind ? bind_depth_wrong_kind : bind_depth_unknown); } dsv_format = view_format_of(resolved, dsv_target); const bool read_depth = (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_DEPTH) != 0; // A format without a stencil plane has no second plane to disagree with. const bool read_stencil = !format_has_stencil(dsv_format) ? read_depth : (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_STENCIL) != 0; - if (read_depth != read_stencil) { - if (first_calls(refused, 6)) log("x2w-d3d12 OMSetRenderTargets refused: depth stencil view with one read-only plane (flags 0x%x)", view.dsv_flags); - return; - } - if (read_depth) dsv_state = D3D12_RESOURCE_STATE_DEPTH_READ; + if (read_depth != read_stencil) InterlockedIncrement(&bound_mixed_depth); + pass.read_depth_plane = read_depth; + pass.read_stencil_plane = read_stencil; desktop_dsv.ptr = static_cast<SIZE_T>(resolved); dsv_ptr = &desktop_dsv; } } - if (!count && !dsv_ptr) return; + if (!count && !dsv_ptr) { + if (depth && (!x2w_local::readable(depth, sizeof(*depth)) || depth->ptr)) return refuse(bind_depth_unknown); + list->OMSetRenderTargets(0, nullptr, FALSE, nullptr); + pass.targets_refused = false; + InterlockedIncrement(&target_binds[bind_empty]); + return; + } if (red_producers().enabled()) { std::copy_n(targets, 8, pass.trace_targets); pass.trace_depth = dsv_target; @@ -3437,21 +4660,54 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO for (UINT i = 0; i < count; ++i) { use_as_target(self, targets[i]); pass.target_formats[i] = formats[i]; + pass.targets[i] = targets[i]; if (i == 0) pass.target0 = targets[i]; } - if (dsv_target) require_state(self, dsv_target, dsv_state); + pass.dsv_resource = dsv_target; + if (dsv_target) require_bound_depth(self); pass.target_count = count; pass.dsv_format = dsv_format; + pass.dsv_read_only = pass.read_depth_plane && pass.read_stencil_plane; const auto single_sample = [](ID3D12Resource* resource) { const auto samples = resource->GetDesc().SampleDesc; return samples.Count == 1 && !samples.Quality; }; pass.targets_single_sample = std::all_of(targets, targets + count, single_sample) && (!dsv_target || single_sample(dsv_target)); - pass.depth_view_writable = dsv_target && dsv_state == D3D12_RESOURCE_STATE_DEPTH_WRITE; + pass.depth_view_writable = dsv_target && !pass.read_depth_plane; list->OMSetRenderTargets(count, count ? desktop : nullptr, FALSE, dsv_ptr); pass.targets_bound = true; + pass.targets_refused = false; InterlockedIncrement(&render_target_binds); + InterlockedIncrement(&target_binds[single_range ? bind_single_range_bound : bind_bound]); +} +// One line per 300 presented frames: slot 50 outcomes since the last line (counters reset here). +void report_target_binds() +{ + LONG n[bind_outcomes], at[8]; + LONG calls = 0; + for (int i = 0; i < bind_outcomes; ++i) calls += n[i] = InterlockedExchange(&target_binds[i], 0); + for (int i = 0; i < 8; ++i) at[i] = InterlockedExchange(&target_unresolved_at[i], 0); + log("x2w-targets 300 frames: binds %ld bound %ld single-range %ld outcomes (not recording %ld, count over 8 %ld, " + "handles unreadable %ld, range past heap %ld, wrong kind %ld, unresolved target %ld [at %ld %ld %ld %ld %ld %ld %ld %ld], " + "empty %ld, depth wrong kind %ld, depth unknown %ld, mixed depth/stencil bound %ld), bound without depth (unreadable %ld, " + "unmapped %ld), draws without targets %ld; also dropped: clears (list closed or no colour %ld, no target %ld), " + "viewports %ld, scissors %ld, blend factor %ld", + calls, n[bind_bound] + n[bind_single_range_bound], n[bind_single_range_bound], n[bind_not_recording], + n[bind_count_over_8], n[bind_handles_unreadable], n[bind_range_past_heap], n[bind_wrong_kind], n[bind_unresolved], + at[0], at[1], at[2], at[3], at[4], at[5], at[6], at[7], n[bind_empty], n[bind_depth_wrong_kind], + n[bind_depth_unknown], InterlockedExchange(&bound_mixed_depth, 0), InterlockedExchange(&target_depth_unreadable, 0), + InterlockedExchange(&target_depth_unmapped, 0), InterlockedExchange(&draws_without_targets, 0), + InterlockedExchange(&clears_dropped[0], 0), InterlockedExchange(&clears_dropped[1], 0), InterlockedExchange(&state_dropped[0], 0), + InterlockedExchange(&state_dropped[1], 0), InterlockedExchange(&state_dropped[2], 0)); +} +// Fixtures: slot 50 outcome counts since the last report, in TargetBind order (bound, single-range bound, +// then the refusal reasons). Returns how many outcomes exist. +extern "C" __declspec(dllexport) unsigned x2w_d3d12_target_bind_stats(unsigned* counts, unsigned capacity) +{ + for (unsigned i = 0; counts && i < capacity && i < bind_outcomes; ++i) + counts[i] = static_cast<unsigned>(InterlockedCompareExchange(&target_binds[i], 0, 0)); + return bind_outcomes; } // List slots 21 / 22 / 23, RSSetViewports / RSSetScissorRects / OMSetBlendFactor. void __stdcall list_viewports(Wrapper* self, UINT count, const D3D12_VIEWPORT* viewports) @@ -3460,27 +4716,121 @@ void __stdcall list_viewports(Wrapper* self, UINT count, const D3D12_VIEWPORT* v if (auto* list = recording(self); list && count && count <= 16 && x2w_local::readable(viewports, count * sizeof(*viewports))) { list->RSSetViewports(count, viewports); pass_of(self).viewport_set = true; - } + pass_of(self).viewport0 = viewports[0]; + // LOCAL (video): a traced frame shows each viewport (letterbox questions). + if (trace_frame_active) + log("x2w-frame viewport list=%p count %u: x %.1f y %.1f w %.1f h %.1f", static_cast<void*>(self), count, viewports[0].TopLeftX, + viewports[0].TopLeftY, viewports[0].Width, viewports[0].Height); + } else if (list) InterlockedIncrement(&state_dropped[0]); } void __stdcall list_scissors(Wrapper* self, UINT count, const D3D12_RECT* rects) { if (auto* list = recording(self); list && count && count <= 16 && x2w_local::readable(rects, count * sizeof(*rects))) { list->RSSetScissorRects(count, rects); pass_of(self).scissor_set = true; - } + pass_of(self).scissor0 = rects[0]; + if (trace_frame_active) + log("x2w-frame scissor list=%p count %u: %ld %ld %ld %ld", static_cast<void*>(self), count, rects[0].left, rects[0].top, rects[0].right, + rects[0].bottom); + } else if (list) InterlockedIncrement(&state_dropped[1]); } void __stdcall list_blend_factor(Wrapper* self, const float* factor) { if (auto* list = recording(self); list && x2w_local::readable(factor, 16)) list->OMSetBlendFactor(factor); + else if (list) InterlockedIncrement(&state_dropped[2]); } -// List slot 24, OMSetStencilRef(reference): list state that the stencil test of the next draws compares against. void __stdcall list_stencil_ref(Wrapper* self, UINT reference) { if (auto* list = recording(self)) { - pass_of(self).stencil_reference = reference; - list->OMSetStencilRef(reference); + pass_of(self).stencil_reference = reference; // upstream X2W_DEPTH_STATE (#2169): list state the scoped reference restores + list->OMSetStencilRef(reference & 0xFF); } } +SRWLOCK cleared_depth_lock = SRWLOCK_INIT; +std::unordered_set<const ID3D12Resource*>& cleared_depth_targets() +{ + static std::unordered_set<const ID3D12Resource*> s; + return s; +} +bool depth_target_cleared(const ID3D12Resource* resource) +{ + if (!resource) return false; + AcquireSRWLockShared(&cleared_depth_lock); + const bool found = cleared_depth_targets().count(resource) != 0; + ReleaseSRWLockShared(&cleared_depth_lock); + return found; +} +// LOCAL meshrt: the last forwarded clear of each depth resource (record time), for the traced-frame mesh lines. +struct DepthClearValue { + float depth = 0; + UINT stencil = 0, flags = 0; + LONG frame = 0; +}; +std::unordered_map<const ID3D12Resource*, DepthClearValue>& depth_clear_values() +{ + static std::unordered_map<const ID3D12Resource*, DepthClearValue> m; + return m; +} +bool last_depth_clear(const ID3D12Resource* resource, DepthClearValue* out) +{ + if (!resource) return false; + AcquireSRWLockShared(&cleared_depth_lock); + const auto found = depth_clear_values().find(resource); + const bool known = found != depth_clear_values().end(); + if (known) *out = found->second; + ReleaseSRWLockShared(&cleared_depth_lock); + return known; +} +LONG depth_clears[5]; // [0] forwarded, [1] list not open, [2] view not a known depth view, [3] depth value outside [0, 1], [4] nothing left to clear +void __stdcall list_clear_depth(Wrapper* self, u64 handle, UINT flags, float depth, UINT stencil, UINT rect_count, const D3D12_RECT* rects) +{ + InterlockedIncrement64(&list_slot_calls[51]); + InterlockedIncrement64(&list_slot_census[51]); + InterlockedIncrement(&draw_calls_seen); + static LONG logged; + const bool log_this = first_calls(logged, 8); + auto* list = recording(self); + if (!list) return (void)InterlockedIncrement(&depth_clears[1]); + const u64 resolved = desktop_cpu_handle(handle); + const ResolvedView view = resolved ? resolve_view(resolved, 21) : ResolvedView{}; + ID3D12Resource* target = view.resource; + const DXGI_FORMAT format = target ? view_format_of(resolved, target) : DXGI_FORMAT_UNKNOWN; + UINT clear = flags & (D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL); + if (!format_has_stencil(format)) clear &= ~D3D12_CLEAR_FLAG_STENCIL; + if (log_this) + log("x2w-render ClearDepthStencilView view=0x%llx target=%p format %d flags 0x%x depth %g stencil %u rects %u", handle, + static_cast<void*>(target), static_cast<int>(format), flags, depth, stencil & 0xFF, rect_count); + if (!target) return (void)InterlockedIncrement(&depth_clears[2]); + if ((clear & D3D12_CLEAR_FLAG_DEPTH) && !(depth >= 0.0f && depth <= 1.0f)) return (void)InterlockedIncrement(&depth_clears[3]); + if (!clear) return (void)InterlockedIncrement(&depth_clears[4]); + if (rect_count && !x2w_local::readable(rects, rect_count * sizeof(*rects))) return (void)InterlockedIncrement(&depth_clears[2]); + const auto* tracked = pass_of(self).states.find(target); + const bool known = tracked != nullptr; + const auto before = known ? tracked->depth : D3D12_RESOURCE_STATE_COMMON; + const auto before_stencil = known ? tracked->stencil : before; + require_state(self, target, D3D12_RESOURCE_STATE_DEPTH_WRITE); + list->ClearDepthStencilView(D3D12_CPU_DESCRIPTOR_HANDLE{static_cast<SIZE_T>(resolved)}, static_cast<D3D12_CLEAR_FLAGS>(clear), depth, + static_cast<UINT8>(stencil & 0xFF), rect_count, rect_count ? rects : nullptr); + if (known) require_planes(self, target, before, before_stencil); + // Only a depth clear initialises the depth plane; marked at record time, never unmarked (a freed and reused address stays marked). + if (clear & D3D12_CLEAR_FLAG_DEPTH) { + AcquireSRWLockExclusive(&cleared_depth_lock); + cleared_depth_targets().insert(target); + ReleaseSRWLockExclusive(&cleared_depth_lock); + } + { // LOCAL meshrt: the value, for the traced-frame mesh lines (one map store per forwarded clear) + AcquireSRWLockExclusive(&cleared_depth_lock); + DepthClearValue& v = depth_clear_values()[target]; + if (clear & D3D12_CLEAR_FLAG_DEPTH) v.depth = depth; + if (clear & D3D12_CLEAR_FLAG_STENCIL) v.stencil = stencil & 0xFF; + v.flags = clear; + v.frame = frame_number; + ReleaseSRWLockExclusive(&cleared_depth_lock); + } + InterlockedIncrement(&depth_clears[0]); +} +// List slot 24 (upstream's OMSetStencilRef handler is merged into the local one above: it records the reference +// for X2W_DEPTH_STATE's scoped stencil reference in d3d12_draw.inl). // List slot 43 (desktop 39 + 4), set a compute root SRV backed by this recording's upload pages. void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 address) { @@ -3497,11 +4847,18 @@ void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 add } // List slot 44 (desktop 40 + 4), SetGraphicsRootShaderResourceView(parameter, title GPU address). +bool root_srv_lazy() +{ + static const bool on = x2w_local::env_on("X2W_ROOT_SRV_LAZY"); + return on; +} +LONG root_srv_deferred, root_srv_lazy_bound; +void bind_root_srv(Wrapper* self, ID3D12GraphicsCommandList* list, UINT parameter, u64 address); void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) { auto* list = recording(self); Pass& pass = pass_of(self); - if (parameter < 32) pass.srv_bound &= ~(1u << parameter); + if (parameter < 32) pass.srv_bound &= ~(1u << parameter), pass.srv_pending &= ~(1u << parameter); if (parameter < 16) pass.root_address[parameter] = address; // Under a deferred heap-indexed root the desktop list holds another root signature; only the title address is kept. if (!list || !pass.root || pass.root_heap_flags || parameter >= pass.root->size() || parameter >= 32 || @@ -3515,6 +4872,34 @@ void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) pass.srv_bound |= 1u << parameter; return; } + if (root_srv_lazy() && parameter < 16) { + pass.srv_pending |= 1u << parameter; + const LONG n = InterlockedIncrement(&root_srv_deferred); + if (n == 1) log("x2w-render X2W_ROOT_SRV_LAZY=1: root SRVs are copied at a real-pipeline draw only"); + return; + } + bind_root_srv(self, list, parameter, address); +} +// X2W_ROOT_SRV_LAZY: before a draw on a real desktop pipeline, the root SRVs set since the root signature +// was bound and not copied yet. +void bind_lazy_root_srvs(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + if (!root_srv_lazy()) return; + Pass& pass = pass_of(self); + if (!pass.root) return; + for (UINT p = 0; p < 16 && p < pass.root->size(); ++p) + if ((pass.srv_pending & (1u << p)) && (*pass.root)[p].type == D3D12_ROOT_PARAMETER_TYPE_SRV && pass.root_address[p]) { + pass.srv_pending &= ~(1u << p); + bind_root_srv(self, list, p, pass.root_address[p]); + const LONG n = InterlockedIncrement(&root_srv_lazy_bound); + if (x2w_local::first_of(n, 3)) + log("x2w-render X2W_ROOT_SRV_LAZY: root SRV %u copied at a real-pipeline draw (%ld so far; %ld calls deferred)", p, n, + root_srv_deferred); + } +} +void bind_root_srv(Wrapper* self, ID3D12GraphicsCommandList* list, UINT parameter, u64 address) +{ + Pass& pass = pass_of(self); const std::size_t bytes = readable_window(address, 0x10000); const D3D12_GPU_VIRTUAL_ADDRESS desktop = bytes ? upload_from_title(address, bytes) : 0; static LONG logged; @@ -3527,6 +4912,104 @@ void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) list->SetGraphicsRootShaderResourceView(parameter, desktop); pass.srv_bound |= 1u << parameter; } +// LOCAL: list slot 61, ExecuteIndirect(signature, max count, argument resource, offset, count resource, +// count offset). Not executed yet. During a traced frame every call is recorded (signature, the bound +// pipeline's creation path, argument address) with whether its record was non-zero when the list was +// recorded; at the end of the frame the records are read again and summarised per group. Words that +// only the console GPU would write stay as they were, so "non-zero at end" means the CPU wrote them. +LONG indirect_calls_local; // LOCAL trace (upstream has indirect_calls[][] by outcome) +struct IndirectCall { + const void* signature; + int path; + const void* base; + const unsigned char* record; + UINT stride; + UINT type; + bool nonzero_at_record; +}; +SRWLOCK indirect_lock = SRWLOCK_INIT; +std::vector<IndirectCall>& indirect_trace() +{ + static std::vector<IndirectCall> calls; + return calls; +} +void indirect_execute(Wrapper* self, void* signature, UINT max_count, Wrapper* arguments, u64 offset, Wrapper* count_resource, u64 count_offset); +// LOCAL (scene): X2W_MESH_RECORD_TRACE (d3d12_record_trace.inl), traced frame only. +void record_trace_indirect(Wrapper* self, UINT type, UINT stride, UINT max_count, Wrapper* arguments, u64 offset); +void record_trace_dispatch(Wrapper* self, u64 key, UINT x, UINT y, UINT z, bool executed, int outcome); +void record_trace_report(ID3D12CommandQueue* queue); +void record_trace_mesh_read(u64 key, UINT srv, int source, int a, int b, u64 address, u64 bytes); // d3d12_draw.inl, mesh calls +void record_trace_mesh_heap(Wrapper* self, const Translation& tr); +void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT max_count, Wrapper* arguments, u64 offset, + Wrapper* count_resource, u64 count_offset) +{ + InterlockedIncrement(&indirect_calls_local); + indirect_execute(self, signature, max_count, arguments, offset, count_resource, count_offset); // LOCAL: d3d12_indirect.inl + if (!trace_frame_active) return; + SignatureInfo info; + AcquireSRWLockShared(&signature_lock); + const auto found = signature_infos().find(signature); + if (found != signature_infos().end()) info = found->second; + ReleaseSRWLockShared(&signature_lock); + IndirectCall call{}; + call.signature = signature; + call.stride = info.stride; + call.type = info.args.empty() ? ~0u : static_cast<UINT>(info.args.back().Type); + const PipelineInfo* pipeline = pass_of(self).pipeline ? pipeline_info(pass_of(self).pipeline) : nullptr; + call.path = pipeline ? pipeline->path : -1; + call.base = arguments && arguments->own().kind == resource_kind ? arguments->own().title_memory : nullptr; + call.record = call.base ? static_cast<const unsigned char*>(call.base) + offset : nullptr; + const UINT bytes = info.stride && info.stride <= 64 ? info.stride : 12; + if (call.record && x2w_local::readable(call.record, bytes)) + for (UINT i = 0; i < bytes; ++i) call.nonzero_at_record |= call.record[i] != 0; + else + call.record = nullptr; + (void)max_count; + (void)count_resource; + (void)count_offset; + AcquireSRWLockExclusive(&indirect_lock); + indirect_trace().push_back(call); + ReleaseSRWLockExclusive(&indirect_lock); + record_trace_indirect(self, call.type, info.stride, max_count, arguments, offset); // LOCAL (scene) +} +void summarise_indirect_calls() +{ + record_trace_report(nullptr); // LOCAL (scene): no-op when the busy-frame end already reported + AcquireSRWLockExclusive(&indirect_lock); + std::vector<IndirectCall> calls; + calls.swap(indirect_trace()); + ReleaseSRWLockExclusive(&indirect_lock); + struct Group { + int calls = 0, unreadable = 0, nonzero_at_record = 0, nonzero_at_end = 0; + UINT stride = 0, type = 0; + std::uint32_t sample[4] = {}; + }; + std::map<std::tuple<const void*, int, const void*>, Group> groups; + for (const auto& c : calls) { + Group& g = groups[{c.signature, c.path, c.base}]; + ++g.calls; + g.stride = c.stride; + g.type = c.type; + if (!c.record) { + ++g.unreadable; + continue; + } + const UINT bytes = c.stride && c.stride <= 64 ? c.stride : 12; + bool nonzero = false; + if (x2w_local::readable(c.record, bytes)) + for (UINT i = 0; i < bytes; ++i) nonzero |= c.record[i] != 0; + g.nonzero_at_record += c.nonzero_at_record; + if (nonzero) { + if (!g.nonzero_at_end) std::memcpy(g.sample, c.record, bytes < 16 ? bytes : 16); + ++g.nonzero_at_end; + } + } + log("x2w-frame indirect summary: %zu calls, %zu groups (signature, pipeline creation path, argument resource)", calls.size(), groups.size()); + for (const auto& [key, g] : groups) + log("x2w-frame indirect group sig %p type %u stride %u path %d args %p: calls %d, unreadable %d, non-zero at record %d, at end %d, sample %08x %08x %08x %08x", + std::get<0>(key), g.type, g.stride, std::get<1>(key), std::get<2>(key), g.calls, g.unreadable, g.nonzero_at_record, + g.nonzero_at_end, g.sample[0], g.sample[1], g.sample[2], g.sample[3]); +} // List slot 42 (desktop 38 + 4), SetGraphicsRootConstantBufferView(parameter, title GPU address). // A translated shader reads a root CBV through the same pointer source as a root SRV (root_address). Nothing // is forwarded to the desktop list and srv_bound is left alone: bit 0 means a vertex-fetch SRV is bound. @@ -3546,15 +5029,32 @@ void __stdcall list_root_cbv(Wrapper* self, UINT parameter, u64 address) pass.root_address[parameter] = (address && readable_window(address, 1)) ? address : 0; } extern LONG translated_draws, untranslated_draws, frame_number; +// LOCAL: d3d12_indirect.inl, the indirect call at the issue points of the dispatch and draw paths. +bool indirect_pending(Wrapper* self); +bool indirect_draw_issue(Wrapper* self, ID3D12GraphicsCommandList* list, bool indexed); +void indirect_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z); +void mesh_note57(const void* desc, const Wrapper* self); // LOCAL meshrt: d3d12_mesh.inl bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance); +extern thread_local u64 last_draw_key; // LOCAL (scene): defined in d3d12_draw.inl, for the traced-frame draw lines +extern thread_local const char* last_draw_why; +extern thread_local u64 last_draw_key; +extern thread_local const char* last_draw_why; // List slot 12, DrawInstanced. void __stdcall list_draw(Wrapper* self, UINT vertices, UINT instances, UINT first_vertex, UINT first_instance) { auto* list = recording(self); Pass& pass = pass_of(self); if (list && !pass.pipeline_real) { - InterlockedIncrement(draw_translated(self, false, vertices, instances, first_vertex, 0, first_instance) ? &translated_draws - : &untranslated_draws); + const bool done = draw_translated(self, false, vertices, instances, first_vertex, 0, first_instance); + InterlockedIncrement(done ? &translated_draws : &untranslated_draws); + // LOCAL (scene): restored from f5e0f425 (lost in a merge), as in list_draw_indexed. + if (trace_frame_active) { + note_traced_target(self, pass.target0, done); + const D3D12_RESOURCE_DESC rd = pass.target0 ? pass.target0->GetDesc() : D3D12_RESOURCE_DESC{}; + log("x2w-frame draw %u %s target %p %llux%u fmt %d topology 0x%x key %016llx %s", vertices, done ? "drawn" : "NOT drawn", + static_cast<void*>(pass.target0), static_cast<unsigned long long>(rd.Width), rd.Height, rd.Format, pass.topology, + last_draw_key, done ? "" : (last_draw_why ? last_draw_why : "draw failed")); + } return; } if (list && pass.root_heap_flags) { @@ -3577,15 +5077,25 @@ void __stdcall list_draw(Wrapper* self, UINT vertices, UINT instances, UINT firs list->SetGraphicsRootSignature(pass.deferred_root); } // The translated vertex shaders read their fetch table through root parameter 0. - if (list && pass.pipeline_real && pass.targets_bound && pass.topology_ok && pass.topology != 0x11 && (pass.srv_bound & 1)) { + if (list && pass.pipeline_real) bind_lazy_root_srvs(self, list); // LOCAL stall: X2W_ROOT_SRV_LAZY + const bool real_drawn = list && pass.pipeline_real && pass.targets_bound && pass.topology_ok && pass.topology != 0x11 && (pass.srv_bound & 1); + if (real_drawn) { const auto red_samples = red_producer_draw_before(self, list, "native-draw", 0); list->DrawInstanced(vertices, instances, first_vertex, first_instance); red_producer_draw_after(self, red_samples); const LONG n = InterlockedIncrement(&render_draws); - if (n > 0 && n <= 3) log("x2w-render DrawInstanced(%u, %u, %u, %u) recorded", vertices, instances, first_vertex, first_instance); + if (x2w_local::first_of(n, 3)) log("x2w-render DrawInstanced(%u, %u, %u, %u) recorded", vertices, instances, first_vertex, first_instance); } else { InterlockedIncrement(&render_draws_skipped); } + // LOCAL (scene): the desktop-pipeline path in a traced frame, so no draw of the frame goes unlogged. + if (trace_frame_active) { + note_traced_target(self, pass.target0, real_drawn); + const D3D12_RESOURCE_DESC rd = pass.target0 ? pass.target0->GetDesc() : D3D12_RESOURCE_DESC{}; + log("x2w-frame draw %u %s target %p %llux%u fmt %d topology 0x%x desktop pipeline%s", vertices, real_drawn ? "drawn" : "NOT drawn", + static_cast<void*>(pass.target0), static_cast<unsigned long long>(rd.Width), rd.Height, rd.Format, pass.topology, + real_drawn ? "" : !list ? ": not recording" : !pass.pipeline_real ? ": no pipeline" : ": state (targets/topology/srv 0)"); + } } extern SRWLOCK written_lock; @@ -3598,6 +5108,451 @@ std::unordered_map<u64, TextureWrite>& written_textures(); ID3D12Resource* sampled_address_texture(Wrapper* resource); bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); #include "startup_stubs/d3d12_draw.inl" +#include "startup_stubs/d3d12_regblob.inl" + + +LONG frame_dispatches; // dispatches since the last present (LOCAL instrumentation) +// LOCAL: slot 67 register blobs ([1]/[2] and [3]/[4] of the description), copied at creation because the +// title frees them; written next to the code as req_c67_<key>.regs (length-prefixed pair). +std::unordered_map<Wrapper*, std::vector<unsigned char>>& compute_regs() { static std::unordered_map<Wrapper*, std::vector<unsigned char>> m; return m; } +// LOCAL: compute pipeline wrapper -> req_cs key, and dispatch counts per key (instrumentation). +SRWLOCK compute_lock = SRWLOCK_INIT; +std::unordered_map<Wrapper*, u64>& compute_keys() { static std::unordered_map<Wrapper*, u64> m; return m; } +// LOCAL: compute root state the title sets (list slots = desktop + 4), replayed on a real dispatch. +D3D12_GPU_VIRTUAL_ADDRESS desktop_va(u64 address); +void note_window(ID3D12Resource* buffer); +bool execute_translated(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, UINT x, UINT y, UINT z); +bool rawaddr_pipeline(u64 key, Wrapper* root, Wrapper* pipeline); // d3d12_rawaddr.inl +bool rawaddr_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z); // d3d12_rawaddr.inl +SRWLOCK compute_pso_lock = SRWLOCK_INIT; +std::unordered_map<Wrapper*, ID3D12PipelineState*>& compute_psos() +{ + static std::unordered_map<Wrapper*, ID3D12PipelineState*> m; + return m; +} +LONG compute_executed, compute_skipped_args; +// LOCAL: dispatch outcomes since the last 300-frame report, by path and reason (report_dispatches). +enum ComputeOutcome { co_c62_run, co_c62_table_arg, co_c62_unmapped, co_c67_run, co_c67_off, co_c67_other_key, co_c67_untranslated, + co_c67_heap, co_not_run, co_cx_skip, co_rawaddr_run, co_c67_unresolved, co_c67_compiling /* X2W_CX_ASYNC */, co_count }; +LONG compute_outcomes[co_count]; // compute_lock; counted with the per-key count by execute_dispatch +thread_local int dispatch_outcome; // set on this thread by the path that handled the dispatch + +// LOCAL: the dispatches issued on each desktop list (Dispatch or ExecuteIndirect, through indirect_dispatch), in +// order, since its last Reset, plus the recording before that one (a list can be reset while its previous +// submission still runs). The DRED report maps the in-progress Dispatch op to one of them. +struct IssuedDispatch { u64 key; UINT x, y, z; char path; bool indirect; }; +struct IssuedList { std::vector<IssuedDispatch> current, previous; }; +thread_local u64 cx_issue_key; // set by execute_dispatch for indirect_dispatch +thread_local char cx_issue_path; // 'c' slot-62 desktop pipeline, 't' translated, 'r' raw-address +SRWLOCK issued_lock = SRWLOCK_INIT; +constexpr std::size_t issued_cap = 16384; // per recording +std::unordered_map<const void*, IssuedList>& issued_lists() { static std::unordered_map<const void*, IssuedList> m; return m; } +const void* issued_id(ID3D12GraphicsCommandList* list) { return static_cast<const void*>(static_cast<ID3D12CommandList*>(list)); } +void note_issued_dispatch(ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z, bool indirect) +{ + AcquireSRWLockExclusive(&issued_lock); + std::vector<IssuedDispatch>& v = issued_lists()[issued_id(list)].current; + if (v.size() < issued_cap) v.push_back({cx_issue_key, x, y, z, cx_issue_path, indirect}); + ReleaseSRWLockExclusive(&issued_lock); +} +void forget_list_dispatches(ID3D12GraphicsCommandList* list) +{ + AcquireSRWLockExclusive(&issued_lock); + const auto found = issued_lists().find(issued_id(list)); + if (found != issued_lists().end()) { + found->second.previous.swap(found->second.current); + found->second.current.clear(); + } + ReleaseSRWLockExclusive(&issued_lock); +} +const char* issued_path_name(char path) +{ + return path == 'c' ? "slot-62" : path == 't' ? "translated" : path == 'r' ? "raw-address" : path == 'g' ? "indirect guard pass" : path == 'b' ? "GPU buffer copy (draw-rt)" : "?"; +} +// For one incomplete DRED list: the dispatch at op `done` (the Dispatch ops before it are counted from the op +// types, so the barriers between dispatches need no fixed stride) and the five before and after it. +void report_dred_dispatches(const D3D12_AUTO_BREADCRUMB_NODE* node, UINT done) +{ + if (!node->pCommandList || !node->pCommandHistory) return; + UINT before = 0, total = 0; // Dispatch ops before op `done`, and in the whole list + for (UINT i = 0; i < node->BreadcrumbCount; ++i) + if (node->pCommandHistory[i] == D3D12_AUTO_BREADCRUMB_OP_DISPATCH) { + if (i < done) ++before; + ++total; + } + const bool at_dispatch = done < node->BreadcrumbCount && node->pCommandHistory[done] == D3D12_AUTO_BREADCRUMB_OP_DISPATCH; + std::vector<IssuedDispatch> current, previous; + AcquireSRWLockShared(&issued_lock); + const auto found = issued_lists().find(issued_id(node->pCommandList)); + if (found != issued_lists().end()) current = found->second.current, previous = found->second.previous; + ReleaseSRWLockShared(&issued_lock); + const auto direct_of = [](const std::vector<IssuedDispatch>& v) { + std::vector<IssuedDispatch> out; + for (const IssuedDispatch& d : v) + if (!d.indirect) out.push_back(d); + return out; + }; + std::vector<IssuedDispatch> direct = direct_of(current); + const char* which = "current recording"; + if (direct.size() != total) { + std::vector<IssuedDispatch> older = direct_of(previous); + if (older.size() == total) direct.swap(older), which = "previous recording"; + } + const bool match = direct.size() == total; + log("x2w-dred dispatches list %p: op %u is %s; %u Dispatch ops before it, %u in the list; %zu direct dispatches in the %s " + "(%zu recorded now, %zu before the last Reset)%s", + static_cast<const void*>(node->pCommandList), done, at_dispatch ? "a Dispatch" : "not a Dispatch", before, total, direct.size(), + which, current.size(), previous.size(), match ? "" : "; COUNT MISMATCH, the mapping below is not reliable"); + if (direct.empty()) return; + const std::size_t at = before < direct.size() ? before : direct.size() - 1; + const std::size_t from = at > 5 ? at - 5 : 0, to = at + 6 < direct.size() ? at + 6 : direct.size(); + for (std::size_t i = from; i < to; ++i) + log("x2w-dred %s dispatch %zu: key %016llx (%u, %u, %u) %s", i == at && at_dispatch ? ">>" : " ", i, direct[i].key, + direct[i].x, direct[i].y, direct[i].z, issued_path_name(direct[i].path)); +} + +// LOCAL: X2W_CX_SKIP=<key>[,<key>...] (hex): dispatches of these keys are skipped (outcome "X2W_CX_SKIP"). +bool cx_skip_key(u64 key) +{ + static const std::vector<u64> keys = [] { + std::vector<u64> out; + char value[2048]{}; + const DWORD n = GetEnvironmentVariableA("X2W_CX_SKIP", value, sizeof(value)); + if (!n || n >= sizeof(value)) return out; + for (const char* p = value; *p;) { + char* end = nullptr; + const u64 k = std::strtoull(p, &end, 16); + if (end == p) { + ++p; + continue; + } + out.push_back(k); + p = end; + } + log("x2w-cx X2W_CX_SKIP: %zu keys", out.size()); + for (const u64 k : out) log("x2w-cx X2W_CX_SKIP key %016llx", k); + return out; + }(); + if (keys.empty()) return false; + return std::find(keys.begin(), keys.end(), key) != keys.end(); +} +// slot 33, SetComputeRootSignature(root) +// LOCAL: as in D3D12, setting the root signature already bound keeps the root arguments; another one clears them +// (X2W_CX_ROOT_RESET=1: every call clears them, as before). +LONG compute_root_same, compute_root_changed; +void __stdcall list_compute_root(Wrapper* self, Wrapper* root) +{ + static const bool always_reset = x2w_local::env_on("X2W_CX_ROOT_RESET"); // the old behaviour + Pass& pass = pass_of(self); + if (root && root == pass.compute_root && !always_reset) { + InterlockedIncrement(&compute_root_same); + return; + } + InterlockedIncrement(&compute_root_changed); + pass.compute_root = root; + for (auto& k : pass.compute_kind) k = 0; + for (auto& s : pass.compute_set) s = 0; +} +// slot 35, SetComputeRootDescriptorTable(parameter, handle): not replayed (the executed shaders use none). +void __stdcall list_compute_table(Wrapper* self, UINT parameter, u64 gpu_handle) +{ + if (parameter >= 16) return; + u64 address = 0; // the table's address in the title's descriptor memory (as list_table) + AcquireSRWLockShared(¬e_lock); + for (const HeapInfo& heap : heap_infos()) + if (heap.desktop_gpu && heap.title_cpu && gpu_handle >= heap.desktop_gpu && gpu_handle < heap.desktop_gpu + u64{heap.count} * heap.increment) + address = heap.title_cpu + (gpu_handle - heap.desktop_gpu); + ReleaseSRWLockShared(¬e_lock); + pass_of(self).compute_kind[parameter] = 5; + pass_of(self).compute_address[parameter] = address; + pass_of(self).compute_set[parameter] = 0; +} +// slot 37, SetComputeRoot32BitConstant(parameter, value, offset) +void __stdcall list_compute_constant(Wrapper* self, UINT parameter, UINT value, UINT offset) +{ + Pass& pass = pass_of(self); + if (parameter >= 16 || offset >= 16) return; + if (pass.compute_kind[parameter] != 1) pass.compute_set[parameter] = 0; + pass.compute_kind[parameter] = 1; + pass.compute_constants[parameter][offset] = value; + pass.compute_set[parameter] |= static_cast<std::uint16_t>(1u << offset); + if (offset + 1 > pass.compute_count[parameter]) pass.compute_count[parameter] = offset + 1; +} +// slot 39, SetComputeRoot32BitConstants(parameter, count, data, offset) +void __stdcall list_compute_constants(Wrapper* self, UINT parameter, UINT count, const void* data, UINT offset) +{ + Pass& pass = pass_of(self); + if (parameter >= 16 || offset >= 16 || !data || !x2w_local::readable(data, std::size_t{count} * 4)) return; + if (offset + count > 16) count = 16 - offset; + if (pass.compute_kind[parameter] != 1) pass.compute_set[parameter] = 0; + pass.compute_kind[parameter] = 1; + std::memcpy(&pass.compute_constants[parameter][offset], data, std::size_t{count} * 4); + for (UINT i = 0; i < count; ++i) pass.compute_set[parameter] |= static_cast<std::uint16_t>(1u << (offset + i)); + if (offset + count > pass.compute_count[parameter]) pass.compute_count[parameter] = offset + count; +} +void compute_root_descriptor(Wrapper* self, UINT parameter, u64 address, int kind) +{ + Pass& pass = pass_of(self); + if (parameter >= 16) return; + pass.compute_kind[parameter] = kind; + pass.compute_address[parameter] = address; + pass.compute_set[parameter] = 0; +} +void __stdcall list_compute_cbv(Wrapper* self, UINT parameter, u64 address) { compute_root_descriptor(self, parameter, address, 2); } +void __stdcall list_compute_srv(Wrapper* self, UINT parameter, u64 address) { compute_root_descriptor(self, parameter, address, 3); } +void __stdcall list_compute_uav(Wrapper* self, UINT parameter, u64 address) { compute_root_descriptor(self, parameter, address, 4); } + +// Runs a dispatch through a desktop compute pipeline when one exists for the bound pipeline. +bool execute_dispatch_inner(Wrapper* self, UINT x, UINT y, UINT z, u64 key) +{ + static const bool enabled = !x2w_local::env_on("X2W_COMPUTE_OFF"); + if (cx_skip_key(key)) { + dispatch_outcome = co_cx_skip; + static LONG logged; + if (first_calls(logged, 8)) log("x2w-cx dispatch of key %016llx skipped (X2W_CX_SKIP)", key); + return false; + } + auto* list = recording(self); + Pass& pass = pass_of(self); + if (!enabled || !list || !pass.pipeline) { + dispatch_outcome = co_not_run; + return false; + } + cx_issue_key = key; + cx_issue_path = 'r'; + if (rawaddr_dispatch(self, list, x, y, z)) { // LOCAL raw-address shaders (d3d12_rawaddr.inl) + dispatch_outcome = co_rawaddr_run; + return true; + } + cx_issue_path = 't'; + if (!pass.compute_root || !pass.compute_root->own().real) return execute_translated(self, list, key, x, y, z); + AcquireSRWLockShared(&compute_pso_lock); + const auto found = compute_psos().find(pass.pipeline); + ID3D12PipelineState* pso = found != compute_psos().end() ? found->second : nullptr; + ReleaseSRWLockShared(&compute_pso_lock); + if (!pso) return execute_translated(self, list, key, x, y, z); + cx_issue_path = 'c'; + D3D12_GPU_VIRTUAL_ADDRESS addresses[16] = {}; + for (UINT i = 0; i < 16; ++i) { + const int kind = pass.compute_kind[i]; + if (kind == 5) { + InterlockedIncrement(&compute_skipped_args); + dispatch_outcome = co_c62_table_arg; + return false; + } + if (kind >= 2 && kind <= 4) { + addresses[i] = desktop_va(pass.compute_address[i]); + if (!addresses[i] && pass.compute_address[i]) { + InterlockedIncrement(&compute_skipped_args); + dispatch_outcome = co_c62_unmapped; + return false; + } + } + } + list->SetPipelineState(pso); + list->SetComputeRootSignature(static_cast<ID3D12RootSignature*>(pass.compute_root->own().real)); + for (UINT i = 0; i < 16; ++i) { + switch (pass.compute_kind[i]) { + case 1: list->SetComputeRoot32BitConstants(i, pass.compute_count[i], pass.compute_constants[i], 0); break; + case 2: list->SetComputeRootConstantBufferView(i, addresses[i]); break; + case 3: list->SetComputeRootShaderResourceView(i, addresses[i]); break; + case 4: list->SetComputeRootUnorderedAccessView(i, addresses[i]); break; + default: break; + } + } + gpu_time::mark(self, list, gpu_time::c_c62, key, false); // LOCAL: X2W_GPU_TIME_CLASSES + indirect_dispatch(self, list, x, y, z); // LOCAL: Dispatch, or the pending ExecuteIndirect (d3d12_indirect.inl) + gpu_time::mark(self, list, gpu_time::c_c62, key, true); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + const LONG n = InterlockedIncrement(&compute_executed); + dispatch_outcome = co_c62_run; + if (x2w_local::first_of(n, 4) || n % 5000 == 0) log("x2w-compute dispatch %ld executed (%u, %u, %u)", n, x, y, z); + return true; +} +struct DispatchCount { LONG64 calls = 0; LONG64 groups = 0; UINT x = 0, y = 0, z = 0; }; +std::unordered_map<u64, DispatchCount>& dispatch_counts() { static std::unordered_map<u64, DispatchCount> m; return m; } +// LOCAL: every dispatch (list slot 14 and an ExecuteIndirect dispatch) is counted per key and by outcome in one +// compute_lock hold, so the per-key list and the outcome line of one 300-frame report cover the same dispatches. +// An indirect dispatch passes (0, 0, 0): it adds a call but keeps the key's last direct group counts. +bool execute_dispatch(Wrapper* self, UINT x, UINT y, UINT z, u64 key) +{ + dispatch_outcome = co_not_run; + const bool executed = execute_dispatch_inner(self, x, y, z, key); + const int outcome = dispatch_outcome >= 0 && dispatch_outcome < co_count ? dispatch_outcome : co_not_run; + if (trace_frame_active) record_trace_dispatch(self, key, x, y, z, executed, outcome); // LOCAL (scene) + AcquireSRWLockExclusive(&compute_lock); + DispatchCount& count = dispatch_counts()[key]; + ++count.calls; + count.groups += LONG64{x} * y * z; + if (x | y | z) count.x = x, count.y = y, count.z = z; + ++compute_outcomes[outcome]; + ReleaseSRWLockExclusive(&compute_lock); + return executed; +} +// LOCAL: slot-67 request files req_c67_<key>.{cs,meta,root,desc,regs}, then the marker .done. Once per key per run +// (when the key is first computed for a pipeline, not per dispatch): a key with .done costs one GetFileAttributesW, +// as the old .cs check did. Otherwise each part is checked; a part that is absent or has another size than its data +// (a write cut off by an exit) is written through <name>.<pid>.<tid>.tmp and a rename (regblob::write_whole), and .done +// is written last only when all five parts are on disk. A set started by an older build (no .regs) or cut off +// mid-write (only .cs and .meta) is so completed by the next run that creates the key. +LONG c67_checked, c67_sets_done, c67_parts_written, c67_incomplete, c67_failed; // this run +void complete_c67_request(u64 key, Wrapper* pipeline, const PipelineInfo* info, const void* code, u64 code_bytes, const void* meta, + u64 meta_bytes, const std::vector<unsigned char>& root_blob) +{ + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_set<u64> keys; // handled this run + wchar_t path[MAX_PATH]; + if (!cache_path(path, L"req_c67_", key, L".done")) return; + AcquireSRWLockExclusive(&lock); + const bool fresh = keys.insert(key).second; + ReleaseSRWLockExclusive(&lock); + if (!fresh || GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) return; + InterlockedIncrement(&c67_checked); + std::vector<unsigned char> regs; + AcquireSRWLockShared(&compute_lock); + if (const auto found = compute_regs().find(pipeline); found != compute_regs().end()) regs = found->second; + ReleaseSRWLockShared(&compute_lock); + const bool have_meta = meta_bytes && meta_bytes <= 0x10000 && x2w_local::readable(meta, meta_bytes); + struct Part { const wchar_t* ext; const void* data; std::size_t bytes; bool available; }; + const Part parts[] = { + {L".cs", code, static_cast<std::size_t>(code_bytes), true}, + {L".meta", meta, have_meta ? static_cast<std::size_t>(meta_bytes) : 0, have_meta}, + {L".root", root_blob.data(), root_blob.size(), true}, + {L".desc", info->desc.data(), info->desc.size(), true}, + {L".regs", regs.data(), regs.size(), !regs.empty()}, + }; + int present = 0, written = 0; + bool failed = false; + for (const Part& part : parts) { + WIN32_FILE_ATTRIBUTE_DATA a{}; + if (!cache_path(path, L"req_c67_", key, part.ext)) return; + const bool on_disk = GetFileAttributesExW(path, GetFileExInfoStandard, &a); + const u64 size = (u64{a.nFileSizeHigh} << 32) | a.nFileSizeLow; + if (on_disk && (!part.available || size == part.bytes)) { + ++present; + continue; + } + if (!part.available) continue; + if (regblob::write_whole(path, part.data, part.bytes)) ++present, ++written; + else failed = true; + } + InterlockedAdd(&c67_parts_written, written); + const bool whole = present == static_cast<int>(std::size(parts)); + static const char marker[] = "ok\n"; + if (whole && cache_path(path, L"req_c67_", key, L".done") && regblob::write_whole(path, marker, 3)) InterlockedIncrement(&c67_sets_done); + else InterlockedIncrement(failed ? &c67_failed : &c67_incomplete); // retried by the next run + static LONG logged; + if ((written || !whole) && first_calls(logged, 6)) + log("x2w-cx request %016llx: %d of 5 parts on disk, %d written now%s", key, present, written, + whole ? ", .done written" : failed ? ", a write failed (no .done)" : ", no .regs or .meta yet (no .done)"); +} +// The compute key of the pipeline bound on list self (also used by indirect dispatches). +u64 compute_key_for(Wrapper* pipeline); +bool prewarm_enabled(); // d3d12_compute.inl +bool prewarm_compute(u64 key, bool front = false); +u64 compute_key_of(Wrapper* self) +{ + Pass& pass = pass_of(self); + u64 key = ~0ull; // no compute pipeline bound + AcquireSRWLockExclusive(&compute_lock); + if (pass.pipeline) { + const auto found = compute_keys().find(pass.pipeline); + key = found != compute_keys().end() ? found->second : ~1ull; // ~1: no compute key known for it + } + ReleaseSRWLockExclusive(&compute_lock); + return key == ~1ull ? compute_key_for(pass.pipeline) : key; +} +// The compute key of a pipeline, derived from its creation description and remembered in compute_keys() +// (also at creation, for the background prewarm in d3d12_compute.inl). +u64 compute_key_for(Wrapper* pipeline) +{ + u64 key = ~1ull; + { + // Device slot 67: a console compute pipeline. Its description has the layout of slot 57: + // [0] root signature, [5]/[6] machine code address and length, [7]/[8] the stage's metadata. + // The key is fnv(root blob, fnv(code)), tagged with 0x67 in the top byte; the code, metadata + // and root blob are written to the shader cache as req_c67_<key>.{cs,meta,root,desc,regs}, then .done + // (complete_c67_request). + const PipelineInfo* info = pipeline_info(pipeline); + if (info && info->path == 67 && info->desc.size() >= 0x48) { + u64 words[9]; + std::memcpy(words, info->desc.data(), sizeof(words)); + std::vector<unsigned char> root_blob; + if (Wrapper* root = as_wrapper(reinterpret_cast<const void*>(words[0]))) { + AcquireSRWLockShared(¬e_lock); + const auto found = root_blobs().find(root); + if (found != root_blobs().end()) root_blob = found->second; + ReleaseSRWLockShared(¬e_lock); + } + const auto* code = reinterpret_cast<const void*>(words[5]); + const auto* meta = reinterpret_cast<const void*>(words[7]); + if (words[6] && words[6] <= (1u << 20) && x2w_local::readable(code, words[6])) { + key = (fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(code, words[6])) & 0x00ffffffffffffffull) | (0x67ull << 56); + complete_c67_request(key, pipeline, info, code, words[6], meta, words[8], root_blob); + } else { + key = 0x67ull << 56; // code unreadable + } + } else if (info) { + key = (0xeeull << 56) | static_cast<u64>(info->path); // another creation path + } + AcquireSRWLockExclusive(&compute_lock); + compute_keys()[pipeline] = key; + ReleaseSRWLockExclusive(&compute_lock); + } + return key; +} +// List slot 14, Dispatch(x, y, z). LOCAL instrumentation: counts dispatches per compute pipeline key. +void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) +{ + const u64 key = compute_key_of(self); + InterlockedIncrement(&frame_dispatches); + const bool executed = execute_dispatch(self, x, y, z, key); + if (trace_frame_active) log("x2w-frame dispatch %016llx (%u, %u, %u)%s", key, x, y, z, executed ? " executed" : ""); +} +void report_dispatches() +{ + std::vector<std::pair<u64, DispatchCount>> all; + AcquireSRWLockExclusive(&compute_lock); + LONG o[co_count]; + for (const auto& entry : dispatch_counts()) all.push_back(entry); + dispatch_counts().clear(); + for (int i = 0; i < co_count; ++i) o[i] = compute_outcomes[i], compute_outcomes[i] = 0; // the keys' window + ReleaseSRWLockExclusive(&compute_lock); + std::sort(all.begin(), all.end(), [](const auto& a, const auto& b) { return a.second.calls > b.second.calls; }); + // LOCAL: every key is listed; a full line continues on another line with the same prefix, and a closing + // line gives the key and line counts so a reader can tell the list is complete. + static const char prefix[] = "x2w-render dispatches per compute key (300 frames):"; + // log() cuts a line at 1533 characters (its 1536-byte buffer): stay below it, or the tail keys are lost. + char line[1400]; + int n = std::snprintf(line, sizeof(line), "%s", prefix), lines = 0; + for (const auto& entry : all) { + if (n > static_cast<int>(sizeof(line)) - 80) { + log("%s", line); + ++lines; + n = std::snprintf(line, sizeof(line), "%s", prefix); + } + wchar_t path[MAX_PATH]; + const bool signed_ready = cache_path(path, L"", entry.first, L".cs.dxbc") && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; + n += std::snprintf(line + n, sizeof(line) - n, " %016llx%s:%lld(%u,%u,%u)", entry.first, signed_ready ? "*" : "", + entry.second.calls, entry.second.x, entry.second.y, entry.second.z); + } + log("%s", line); + ++lines; + log("x2w-render dispatch keys (300 frames): %zu keys in %d lines", all.size(), lines); + log("x2w-compute dispatches (300 frames): executed %ld skipped %ld; slot-62 desktop pipeline executed %ld skipped %ld " + "(table argument %ld, unmapped root address %ld); translated executed %ld skipped %ld (X2W_CX_OFF %ld, not a slot-67 key %ld, " + "no translation %ld, heap or vinfo %ld); not run %ld (no list or pipeline, or X2W_COMPUTE_OFF); X2W_CX_SKIP skipped %ld; raw-address executed %ld; translated skipped, entry value unresolved %ld; translated skipped while compiling (X2W_CX_ASYNC) %ld", + o[co_c62_run] + o[co_c67_run] + o[co_rawaddr_run], o[co_c62_table_arg] + o[co_c62_unmapped] + o[co_c67_off] + o[co_c67_other_key] + o[co_c67_untranslated] + o[co_c67_heap] + o[co_cx_skip] + o[co_c67_unresolved] + o[co_c67_compiling], + o[co_c62_run], o[co_c62_table_arg] + o[co_c62_unmapped], o[co_c62_table_arg], o[co_c62_unmapped], o[co_c67_run], + o[co_c67_off] + o[co_c67_other_key] + o[co_c67_untranslated] + o[co_c67_heap], o[co_c67_off], o[co_c67_other_key], o[co_c67_untranslated], + o[co_c67_heap], o[co_not_run], o[co_cx_skip], o[co_rawaddr_run], o[co_c67_unresolved], o[co_c67_compiling]); + if (c67_checked) + log("x2w-cx requests (this run): %ld keys without .done checked, %ld sets completed (.done written), %ld parts written, " + "%ld incomplete (no .meta or .regs at creation), %ld with a failed write; incomplete ones are retried next run", + c67_checked, c67_sets_done, c67_parts_written, c67_incomplete, c67_failed); +} #include "startup_stubs/mesh86_cache.inl" #include "startup_stubs/d3d12_compute_binding_trace.inl" #include "startup_stubs/list_copy_texture.inl" @@ -3613,7 +5568,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) std::vector<ID3D12CommandList*> ready; std::vector<Wrapper*> submitted; // Pin the closed recording and its allocator through submission bookkeeping. - AcquireSRWLockExclusive(&draw_lock); + lock_draw(0 + __LINE__); // LOCAL stall: X2W_DRAW_LOCK_TIMES AcquireSRWLockExclusive(&allocator_lock); for (UINT i = 0; i < count; ++i) { Wrapper* w = as_wrapper(lists[i]); @@ -3626,7 +5581,10 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) bool split = false; const auto submit = [&](const auto& native_lists, const auto& wrappers) { const UINT ready_count = static_cast<UINT>(native_lists.size()); + if (range_watch_count()) range_watch_sample("submit"); // LOCAL + auto title_reads = prepare_texture_readbacks(queue, native_lists); red_producers().execute(queue, native_lists, [&] { + if (x2w_gpu::gpu_abi_on()) gpu_list_submit(queue, ready_count, wrappers.data()); if (draw_dump_frame()) { const HRESULT hr = draw_dumps().execute(queue, ready_count, native_lists.data()); if (FAILED(hr)) log("x2w-draw readback fence failed 0x%08lx", static_cast<unsigned long>(hr)); @@ -3634,6 +5592,9 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) queue->ExecuteCommandLists(ready_count, native_lists.data()); } }); + submit_texture_readbacks(queue, std::move(title_reads)); + cull_capture_submitted(queue, native_lists.data(), ready_count); // LOCAL: X2W_CULL_INPUT_CAPTURE + if (x2w_gpu::gpu_abi_on()) gpu_list_submitted(queue, ready_count, wrappers.data()); retire_address_uploads(queue, native_lists); retire_draw_sampler_heaps(queue, native_lists); note_submits(queue, wrappers); @@ -3661,6 +5622,15 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) submit(ready, submitted); } ReleaseSRWLockExclusive(&allocator_lock); + if (!ready.empty()) { + // LOCAL: still under draw_lock as before, but after allocator_lock: the memcut reaper and the upload + // ring take it (shared) themselves. + memcut_reap(); // LOCAL memcut (X2W_MEMCUT_RELEASE) + ring_submitted(submitted); // LOCAL memcut (upload ring) + gpu_time::submitted(static_cast<ID3D12CommandQueue*>(self->own().real), submitted); // LOCAL: X2W_CX_GPU_TIME + static const bool srv_report_submits = x2w_local::env_on("X2W_DRAW_SRV_STATS_SUBMITS"); // LOCAL stall: fixtures only + if (srv_report_submits) report_srv_copies(); + } ReleaseSRWLockExclusive(&draw_lock); check_device("CommandQueue execute", 35); return; @@ -3715,9 +5685,11 @@ HRESULT WINAPI queue_page_mappings(Wrapper*, UINT count, const X2WPageBatch* bat HMODULE xmem = nullptr; if (!GetModuleHandleExW(0, L"xmem.dll", &xmem)) return HRESULT_FROM_WIN32(GetLastError()); const auto map = reinterpret_cast<decltype(&X2WMapPageBatch)>(GetProcAddress(xmem, "X2WMapPageBatch")); - const HRESULT hr = map ? map(count, batches, pool, pool_pages, flags, nullptr) + X2WPageBatchStats stats{}; + const HRESULT hr = map ? map(count, batches, pool, pool_pages, flags, &stats) : HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND); FreeLibrary(xmem); + if (SUCCEEDED(hr) && stats.pagesChanged) x2w_local::invalidate_probe_cache(); if (FAILED(hr)) { static LONG failures; if (first_calls(failures, 2)) @@ -3770,6 +5742,10 @@ __declspec(noinline) u64 queue_dynamic(Wrapper* self, u64 rdx, u64 r8, u64 r9) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, name, N & 0xFF, reinterpret_cast<u64>(self), rdx, r8, r9, _ReturnAddress()); } + if (noop_census_enabled()) { + const u64 args[8] = {reinterpret_cast<u64>(self), rdx, r8, r9, 0, 0, 0, 0}; + noop_census_note(queue_kind, N, args, reinterpret_cast<u64>(_ReturnAddress()) - reinterpret_cast<u64>(GetModuleHandleW(nullptr))); + } if (log_it) { char name[64]; std::snprintf(name, sizeof(name), "CommandQueue::slot%d", N); @@ -3882,16 +5858,17 @@ 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. template <class T, class Get> std::uint64_t small_result(void* a, void* b, const char* method, Get get) { - if (Wrapper* w = as_wrapper(b)) { - const T value = get(w); - *static_cast<T*>(a) = value; - return reinterpret_cast<std::uint64_t>(a); - } Wrapper* w = as_wrapper(a); + if (!w && a) { + if (Wrapper* object = as_wrapper(b)) { + const T value = get(object); + *static_cast<T*>(a) = value; + return reinterpret_cast<std::uint64_t>(a); + } + } if (!w) fail(method, a, b); const T value = get(w); std::uint64_t bits = 0; @@ -3967,18 +5944,22 @@ HRESULT __stdcall device_create_descriptor_heap(Wrapper* self, const D3D12_DESCR const UINT desktop_stride = device_of(self)->GetDescriptorHandleIncrementSize(desc->Type); const bool raw_samplers = desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER && extra[1] == u64{desc->NumDescriptors} * x2w_startup::title_sampler_stride; - const UINT title_stride = raw_samplers ? x2w_startup::title_sampler_stride : desktop_stride; + // Translated shader ABI: the title's views are 32 and its samplers 16 bytes apart (its slot 15 answers), whatever + // the desktop increments are (WARP: 64 and 64). + const bool gpu_views = x2w_gpu::gpu_abi_on() && desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + const bool gpu_samplers = x2w_gpu::gpu_abi_on() && desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; + const UINT title_stride = raw_samplers || gpu_samplers ? x2w_startup::title_sampler_stride + : gpu_views ? x2w_gpu::abi::view_increment : desktop_stride; const u64 bytes = u64{desc->NumDescriptors} * title_stride; // 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; - // 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 - // of another type gets the same when its desktop start is not an address (title_heap_memory.h). + // The title copies descriptors directly between heaps. Allocate CPU-visible backing when a heap lacks an + // addressable desktop start so the view IDs written by note_view survive byte copies. The desktop heap is still + // populated. Unplaced sampler heaps, including CPU-only staging heaps, use 16-byte title records. if (!x2w_startup::ensure_title_heap_memory(desc->Type, desktop, bytes, title_memory, [](u64 size) { return reinterpret_cast<u64>(VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); - })) { + }, gpu_samplers)) { heap->Release(); return E_OUTOFMEMORY; } @@ -4018,14 +5999,16 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) const u64 title_dest = args[D]; args[D] = desktop_cpu_handle(args[D]); if (!args[D]) { + if (noop_census_enabled()) noop_census_dropped_view(N, title_dest); if constexpr (N == 18) retire_leave_class(reinterpret_cast<const void*>(a), RetireLeft::view); return 0; } + const void* adapted_record = nullptr; const auto record_view = [&](bool materialized) { const u64 raw[4] = {a, b, c, d}; const int described = N == 19 ? 2 : (N == 17 || N == 22) ? 0 : 1; - const std::size_t described_bytes = N == 17 ? 16 : N == 22 ? 52 : N == 18 ? 40 : N == 19 ? 40 : N == 20 ? 20 : 16; - note_view(N, (N >= 18 && N <= 21) ? raw[0] : 0, N == 19 ? raw[1] : 0, reinterpret_cast<const void*>(raw[described]), + const std::size_t described_bytes = N == 17 ? 16 : N == 22 ? 52 : N == 18 ? 40 : N == 19 ? sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) : N == 20 ? 20 : 16; + note_view(N, (N >= 18 && N <= 21) ? raw[0] : 0, N == 19 ? raw[1] : 0, adapted_record ? adapted_record : reinterpret_cast<const void*>(raw[described]), described_bytes, title_dest, args[D], materialized); }; const char* skip = nullptr; @@ -4049,8 +6032,30 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) constexpr std::size_t view_bytes = N == 18 ? sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) : N == 19 ? sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) : N == 20 ? sizeof(D3D12_RENDER_TARGET_VIEW_DESC) : sizeof(D3D12_DEPTH_STENCIL_VIEW_DESC); + if constexpr (N >= 18 && N <= 20) { + const auto* owner = as_wrapper(reinterpret_cast<const void*>(a)); + if (owner && owner->own().srgb_uav_format) { + const auto original = static_cast<DXGI_FORMAT>(owner->own().srgb_uav_format); + const auto rd = reinterpret_cast<ID3D12Resource*>(args[0])->GetDesc(); + if (!args[desc_index]) { + if constexpr (N == 18) { const auto v = x2w_srgb::srv(rd, original); std::memcpy(desc_copy, &v, sizeof(v)); } + if constexpr (N == 19) { const auto v = x2w_srgb::uav(rd, original); std::memcpy(desc_copy, &v, sizeof(v)); } + if constexpr (N == 20) { const auto v = x2w_srgb::rtv(rd, original); std::memcpy(desc_copy, &v, sizeof(v)); } + adapted_record = desc_copy; + } else if (x2w_local::readable(reinterpret_cast<const void*>(args[desc_index]), view_bytes)) { + std::memcpy(desc_copy, reinterpret_cast<const void*>(args[desc_index]), view_bytes); + DXGI_FORMAT format; + std::memcpy(&format, desc_copy, sizeof(format)); + if (format == DXGI_FORMAT_UNKNOWN) format = original; + if constexpr (N == 19) format = x2w_srgb::linear(format); + std::memcpy(desc_copy, &format, sizeof(format)); + adapted_record = desc_copy; + } + if (adapted_record) args[desc_index] = reinterpret_cast<u64>(adapted_record); + } + } if (N >= 18 && N <= 21 && args[desc_index] && x2w_local::readable(reinterpret_cast<const void*>(args[desc_index]), view_bytes)) { - std::memcpy(desc_copy, reinterpret_cast<const void*>(args[desc_index]), view_bytes); + if (!adapted_record) std::memcpy(desc_copy, reinterpret_cast<const void*>(args[desc_index]), view_bytes); DXGI_FORMAT format; std::memcpy(&format, desc_copy, sizeof(format)); DXGI_FORMAT mapped = desktop_format(format); @@ -4073,7 +6078,26 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) std::memcpy(desc_copy, &mapped, sizeof(mapped)); args[desc_index] = reinterpret_cast<u64>(desc_copy); } + if (N == 18) { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + std::memcpy(&view, desc_copy, sizeof(view)); + const D3D12_SHADER_RESOURCE_VIEW_DESC before = view; + fix_srv(view, reinterpret_cast<ID3D12Resource*>(args[0])); + if (std::memcmp(&view, &before, sizeof(view)) != 0) { + std::memcpy(desc_copy, &view, sizeof(view)); + args[desc_index] = reinterpret_cast<u64>(desc_copy); + static LONG planes; + if (first_calls(planes, 4)) log("x2w-d3d12 Device::slot18 view format %d: plane slice set for the depth-stencil plane", view.Format); + } + } } + // A typeless depth texture (typeless_depth_family) needs a description; the title passed none. + D3D12_SHADER_RESOURCE_VIEW_DESC default_srv{}; + D3D12_DEPTH_STENCIL_VIEW_DESC default_dsv{}; + if (N == 18 && args[0] && !args[1] && default_depth_srv(reinterpret_cast<ID3D12Resource*>(args[0]), default_srv)) + args[1] = reinterpret_cast<u64>(&default_srv); + if (N == 21 && args[0] && !args[1] && default_depth_dsv(reinterpret_cast<ID3D12Resource*>(args[0]), default_dsv)) + args[1] = reinterpret_cast<u64>(&default_dsv); D3D12_UNORDERED_ACCESS_VIEW_DESC null_uav{}; D3D12_RENDER_TARGET_VIEW_DESC null_rtv{}; if constexpr (N == 19) { @@ -4088,12 +6112,22 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) *reinterpret_cast<const D3D12_RENDER_TARGET_VIEW_DESC*>(b), null_rtv)) args[1] = reinterpret_cast<u64>(&null_rtv); } + bool trace_uav = false; + if constexpr (N == 19) trace_uav = gpu_view_trace::watching(removal_device); 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 // reference and adds none. const HRESULT removed = removal_device ? removal_device->GetDeviceRemovedReason() : S_OK; + if constexpr (N == 19) { + if (trace_uav) gpu_view_trace::after("Device::slot19", "original UAV", removed, + reinterpret_cast<ID3D12Resource*>(args[0]), reinterpret_cast<ID3D12Resource*>(args[1]), + reinterpret_cast<const D3D12_UNORDERED_ACCESS_VIEW_DESC*>(args[2]), {static_cast<SIZE_T>(args[D])}); + } const bool created = SUCCEEDED(removed); + if constexpr (N == 18 || N == 19) { + if (!a) adapted_record = reinterpret_cast<const void*>(args[desc_index]); + } record_view(created); if (!created) { static LONG failed; @@ -4111,6 +6145,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) return result; } +void copy_lazy_native_srv(Wrapper*, u64 source, u64 destination); // Copy through actual desktop heaps. A logical range may straddle the last // shader-visible descriptor and the first CPU-only descriptor. void copy_descriptor_run(Wrapper* self, UINT count, u64 dest, u64 src, D3D12_DESCRIPTOR_HEAP_TYPE type) @@ -4126,6 +6161,10 @@ void copy_descriptor_run(Wrapper* self, UINT count, u64 dest, u64 src, D3D12_DES const UINT chunk = (std::min)(count, (std::min)(dest_room, src_room)); device_of(self)->CopyDescriptorsSimple(chunk, {static_cast<SIZE_T>(d)}, {static_cast<SIZE_T>(s)}, type); note_copy(dest, src, d, s, chunk, increment); + if (type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && dest == d && src != s && + x2w_gpu::gpu_abi_on() && title_backed(src, u64{chunk} * src_stride)) { + for (UINT i = 0; i < chunk; ++i) copy_lazy_native_srv(self, src + u64{i} * src_stride, dest + u64{i} * dest_stride); + } dest += u64{chunk} * dest_stride; src += u64{chunk} * src_stride; count -= chunk; @@ -4310,10 +6349,248 @@ IndirectAddressAlias indirect_address_alias(Wrapper* device, u64 address, u64 by return {it->resource.Get(), offset}; } volatile LONG64 placed_buffer_calls, placed_buffer_region_info, placed_buffer_queries; // five-second totals +// LOCAL: the address ranges of the private allocations opened as desktop heaps. A memory query +// costs over a millisecond in this process (very many mapped sections); desktop_va and +// desktop_range ask this table first and query the kernel only for addresses outside it. +struct PrivateRange { u64 base, end; }; +SRWLOCK private_range_lock = SRWLOCK_INIT; +std::vector<PrivateRange> private_ranges; +void note_private_range(void* base, ID3D12Heap* heap) +{ + if (!base || !heap) return; + const u64 size = heap->GetDesc().SizeInBytes; + AcquireSRWLockExclusive(&private_range_lock); + private_ranges.push_back({reinterpret_cast<u64>(base), reinterpret_cast<u64>(base) + size}); + ReleaseSRWLockExclusive(&private_range_lock); +} +// The allocation base and end of a private allocation opened as a heap that contains address. +bool known_private(u64 address, u64* base, u64* end) +{ + bool found = false; + AcquireSRWLockShared(&private_range_lock); + for (const PrivateRange& r : private_ranges) + if (address >= r.base && address < r.end) { + *base = r.base; + *end = r.end; + found = true; + break; + } + ReleaseSRWLockShared(&private_range_lock); + return found; +} +ID3D12Heap* existing_heap(void* base) +{ + std::lock_guard lock(placed_mutex); + for (auto& [known, h] : existing_heaps) + if (known == base) return h.real; + if (!x2w_startup::private_heap_importable(base)) return nullptr; + ID3D12Device3* device3 = nullptr; + ID3D12Heap* heap = nullptr; + HRESULT hr = device_of(the_device)->QueryInterface(IID_PPV_ARGS(&device3)); + if (SUCCEEDED(hr)) { + hr = device3->OpenExistingHeapFromAddress(base, IID_PPV_ARGS(&heap)); + device3->Release(); + } + if (FAILED(hr)) { + log("x2w-va OpenExistingHeapFromAddress(%p) -> 0x%08lx", base, static_cast<unsigned long>(hr)); + return nullptr; + } + existing_heaps.emplace_back(base, ExistingHeap{heap, nullptr}); // LOCAL desktop_va path: no budget ticket + note_private_range(base, heap); + return heap; +} +// LOCAL: title GPU address -> desktop GPU address. Title GPU memory is the title's own (CPU) memory. +// A private (VirtualAlloc) allocation can be opened as a desktop heap; buffers placed on that heap +// in 256 MiB steps, each 512 MiB long (or up to the heap's end), let any range below 256 MiB be +// addressed by one buffer. The desktop GPU then reads and writes the same pages as the title's CPU. +struct VaWindow { + void* base; + UINT64 start; + ID3D12Resource* buffer; + UINT64 width; +}; +SRWLOCK va_lock = SRWLOCK_INIT; +std::vector<VaWindow>& va_windows() +{ + static std::vector<VaWindow> windows; + return windows; +} +LONG va_mapped, va_failed; +ID3D12Heap* existing_heap(void* base); // opens (once) the desktop heap over a private allocation +// A chunk section opened once as a desktop heap (nullptr when it cannot be); shared by section_va and, with +// X2W_MEMCUT_ALIAS_SLABS, by placed buffers over pool slabs (device slot 133). +ID3D12Heap* section_heap(HANDLE section) +{ + static SRWLOCK lock = SRWLOCK_INIT; + static std::vector<std::pair<HANDLE, ID3D12Heap*>> heaps; + AcquireSRWLockExclusive(&lock); + for (const auto& [h, hp] : heaps) + if (h == section) { + ReleaseSRWLockExclusive(&lock); + return hp; + } + ID3D12Heap* heap = nullptr; + ID3D12Device3* device3 = nullptr; + HRESULT hr = device_of(the_device)->QueryInterface(IID_PPV_ARGS(&device3)); + if (SUCCEEDED(hr)) { + hr = device3->OpenExistingHeapFromFileMapping(section, IID_PPV_ARGS(&heap)); + device3->Release(); + } + log("x2w-va heap over chunk section %p -> 0x%08lx size 0x%llx", section, static_cast<unsigned long>(hr), + SUCCEEDED(hr) ? heap->GetDesc().SizeInBytes : 0ull); + if (FAILED(hr)) heap = nullptr; + heaps.emplace_back(section, heap); + ReleaseSRWLockExclusive(&lock); + return heap; +} +// A chunk section opened once as a desktop heap; buffers placed on it in 256 MiB steps (512 MiB long). +D3D12_GPU_VIRTUAL_ADDRESS section_va(HANDLE section, ULONG64 offset) +{ + static SRWLOCK lock = SRWLOCK_INIT; + static std::vector<std::tuple<HANDLE, ULONG64, ID3D12Resource*>> windows; + const ULONG64 start = offset & ~((1ull << 28) - 1); + AcquireSRWLockExclusive(&lock); + for (const auto& [h, s, b] : windows) + if (h == section && s == start) { + const D3D12_GPU_VIRTUAL_ADDRESS va = b ? b->GetGPUVirtualAddress() + (offset - start) : 0; + ReleaseSRWLockExclusive(&lock); + return va; + } + ID3D12Heap* heap = section_heap(section); + HRESULT hr = S_OK; + ID3D12Resource* buffer = nullptr; + if (heap) { + const UINT64 size = heap->GetDesc().SizeInBytes; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size - start < (2ull << 28) ? size - start : (2ull << 28); + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + hr = device_of(the_device)->CreatePlacedResource(heap, start, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&buffer)); + if (FAILED(hr)) buffer = nullptr; + log("x2w-va chunk window %p+0x%llx -> 0x%08lx va 0x%llx", section, start, static_cast<unsigned long>(hr), + buffer ? buffer->GetGPUVirtualAddress() : 0ull); + } + windows.emplace_back(section, start, buffer); + ReleaseSRWLockExclusive(&lock); + note_window(buffer); + return buffer ? buffer->GetGPUVirtualAddress() + (offset - start) : 0; +} +D3D12_GPU_VIRTUAL_ADDRESS desktop_va(u64 address) +{ + if (!address) return 0; + MEMORY_BASIC_INFORMATION info{}; + u64 known_base = 0, known_end = 0; + const bool known = known_private(address, &known_base, &known_end); + if (known) { + info.AllocationBase = reinterpret_cast<void*>(known_base); + info.Type = MEM_PRIVATE; + info.State = MEM_COMMIT; + } else if (timed_query(reinterpret_cast<const void*>(address), &info) != sizeof(info)) { + info = {}; + } + if (info.Type == MEM_MAPPED) { + // Physical pages in 1 GiB chunk sections (xmem X2W_XMEM_CHUNKS=1): a heap over the chunk. + using Location = BOOL(WINAPI*)(const void*, HANDLE*, ULONG64*); + static const Location location = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast<Location>(GetProcAddress(xmem, "x2w_xmem_gpu_location")) : nullptr; + }(); + HANDLE section = nullptr; + ULONG64 at = 0; + if (location && location(reinterpret_cast<const void*>(address), §ion, &at)) + return section_va(section, at); + if (x2w_local::first_of(InterlockedIncrement(&va_failed), 8)) log("x2w-va 0x%llx: mapped page without a chunk location", address); + return 0; + } + if (info.Type != MEM_PRIVATE || info.State != MEM_COMMIT) { + if (x2w_local::first_of(InterlockedIncrement(&va_failed), 8)) + log("x2w-va 0x%llx: not a committed private allocation (type 0x%lx state 0x%lx)", address, info.Type, info.State); + return 0; + } + void* base = info.AllocationBase; + const UINT64 offset = address - reinterpret_cast<u64>(base); + const UINT64 start = offset & ~((1ull << 28) - 1); + const auto lookup = [&]() -> D3D12_GPU_VIRTUAL_ADDRESS { + for (const auto& w : va_windows()) + if (w.base == base && w.start == start && offset - start < w.width) + return w.buffer->GetGPUVirtualAddress() + (offset - start); + return 0; + }; + AcquireSRWLockShared(&va_lock); + const auto cached = lookup(); + ReleaseSRWLockShared(&va_lock); + if (cached) return cached; + ID3D12Heap* heap = existing_heap(base); + if (!heap) return 0; + const auto size = heap->GetDesc().SizeInBytes; + if (offset >= size) return 0; + AcquireSRWLockExclusive(&va_lock); + const auto concurrent = lookup(); + if (concurrent) { + ReleaseSRWLockExclusive(&va_lock); + return concurrent; + } + ID3D12Resource* buffer = nullptr; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = (std::min<UINT64>)(size - start, 2ull << 28); + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + const HRESULT hr = device_of(the_device)->CreatePlacedResource(heap, start, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&buffer)); + if (SUCCEEDED(hr)) { + note_window(buffer); + va_windows().push_back({base, start, buffer, desc.Width}); + } + ReleaseSRWLockExclusive(&va_lock); + const LONG n = SUCCEEDED(hr) ? InterlockedIncrement(&va_mapped) : InterlockedIncrement(&va_failed); + if (x2w_local::first_of(n, 16)) + log("x2w-va window base=%p start=0x%llx heap=%p -> 0x%08lx desktop va 0x%llx", base, start, static_cast<void*>(heap), + static_cast<unsigned long>(hr), SUCCEEDED(hr) ? buffer->GetGPUVirtualAddress() : 0ull); + return SUCCEEDED(hr) ? buffer->GetGPUVirtualAddress() + (offset - start) : 0; +} + HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3D12_RESOURCE_DESC* desc, UINT state, const void* clear, const GUID* iid, void** out) { + // LOCAL timers: the whole call ("placed") and the gap since this thread's previous call ("placed-gap"). + static thread_local LONG64 placed_last_end = 0; + struct PlacedEnd { + LARGE_INTEGER start; + LONG64* last_end; + ~PlacedEnd() + { + LARGE_INTEGER end; + QueryPerformanceCounter(&end); + InterlockedAdd64(&time_ticks[time_placed], end.QuadPart - start.QuadPart); + InterlockedIncrement64(&time_calls[time_placed]); + InterlockedAdd64(&placed_ticks_total, end.QuadPart - start.QuadPart); + InterlockedIncrement64(&placed_calls_total); + *last_end = end.QuadPart; + } + } placed_end{{}, &placed_last_end}; + QueryPerformanceCounter(&placed_end.start); + { + static const LONG64 frequency = [] { + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + return f.QuadPart; + }(); + const LONG64 gap = placed_end.start.QuadPart - placed_last_end; + if (placed_last_end && gap >= 0 && gap < frequency) { + InterlockedAdd64(&time_ticks[time_placed_gap], gap); + InterlockedIncrement64(&time_calls[time_placed_gap]); + } + } char text[48]; guid_text(iid, text, sizeof(text)); if (!out || !desc || !iid) return E_POINTER; @@ -4331,8 +6608,11 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 texture.Height = surface.rows * x2w_startup::Bc16Surface::block_texels; } const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + // LOCAL merge: the clear format is mapped to its desktop format first (local), then upstream's packed stand-in. + D3D12_CLEAR_VALUE mapped_clear{}; + if (clear) { mapped_clear = *static_cast<const D3D12_CLEAR_VALUE*>(clear); mapped_clear.Format = desktop_format(mapped_clear.Format); } D3D12_CLEAR_VALUE clear_copy{}; - const auto* clear_value = packed_clear_value(static_cast<const D3D12_CLEAR_VALUE*>(clear), + const auto* clear_value = packed_clear_value(clear ? &mapped_clear : nullptr, desktop_format(desc->Format), texture.Format, clear_copy); ID3D12Resource* created = nullptr; HRESULT texture_hr = device_of(self)->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &texture, @@ -4354,8 +6634,13 @@ 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 (texture.Format != desc->Format && texture.Format == x2w_srgb::family(desc->Format)) + w->own().srgb_uav_format = static_cast<unsigned char>(desc->Format); w->own().budget = x2w_budget::committed(device_of(self), created, props.Type); w->own().title_memory = address; + if (cold_textures_enabled() && address && texture.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + texture.SampleDesc.Count == 1 && texture.Flags == D3D12_RESOURCE_FLAG_NONE) + InterlockedExchange(&w->own().cold_texture_state, priority_normal); note_resource(w, desc, 0); retire_set_class(w, props, D3D12_HEAP_FLAG_NONE, texture, address, /*allow_title_memory=*/true); *out = w; @@ -4368,16 +6653,15 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 // block (X2W_XMEM_LAZY_STARTUP) is committed whole, as the heap opened on it is reused for the block. x2w_local::commit_lazy(address, static_cast<std::size_t>(desc->Width)); x2w_local::commit_lazy_block(address); - x2w_startup::PlacedBufferRange range; - const bool committed = x2w_startup::measure_placed_buffer(address, desc->Width, range); - InterlockedIncrement64(&placed_buffer_calls); - if (range.region_info) InterlockedIncrement64(&placed_buffer_region_info); - InterlockedAdd64(&placed_buffer_queries, range.queries); - if (!committed) { + InterlockedIncrement64(&placed_buffer_calls); // LOCAL walk below (no measure_placed_buffer) + TimedPart query_time(time_placed_query); + MEMORY_BASIC_INFORMATION info{}; + if (!address || VirtualQuery(address, &info, sizeof(info)) != sizeof(info) || info.State != MEM_COMMIT) { + query_time.stop(); log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) address=%p not committed -> E_INVALIDARG", address); return E_INVALIDARG; } - void* base = range.base; + void* base = info.AllocationBase; // LOCAL walk (upstream: measure_placed_buffer range.base) const auto initial_state = state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE || state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS ? static_cast<D3D12_RESOURCE_STATES>(state) : D3D12_RESOURCE_STATE_COMMON; if (initial_state != D3D12_RESOURCE_STATE_COMMON && !(desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) @@ -4389,9 +6673,51 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 // 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. - if ((offset & 0xFFFF) || !range.covered || range.type != MEM_PRIVATE || - initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE) hr = E_INVALIDARG; - if (SUCCEEDED(hr)) { + // LOCAL (perf_work/STARTUP.md): the allocation walk below queries every region from the allocation + // base; one query on a large touched region costs about 1.8 ms per GiB (scratch bench), and the + // start-up loop places ~2,800 small buffers at unaligned offsets in a 2.2 GiB block, where the walk + // result is never used. The checks that need no walk come first; the result is the same. + // X2W_D3D12_PLACED_WALK=1 walks for every call, as before. + static const bool always_walk = x2w_local::env_on("X2W_D3D12_PLACED_WALK"); + const bool rejected = (offset & 0xFFFF) || info.Type != MEM_PRIVATE || + initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE; + MEMORY_BASIC_INFORMATION region{}; + SIZE_T allocation_bytes = 0; + static const bool placed_fast = x2w_local::env_on("X2W_PLACED_FAST"); + bool fast = false; + if (placed_fast && !rejected && !always_walk) { + const auto* region_end = static_cast<const char*>(info.BaseAddress) + info.RegionSize; + if (static_cast<const char*>(address) + desc->Width <= region_end) { + UINT64 heap_bytes = 0; + { + std::lock_guard lock(placed_mutex); + for (auto& [known, h] : existing_heaps) + if (known == base) heap_bytes = h.real->GetDesc().SizeInBytes; + } + if (heap_bytes && offset <= heap_bytes && desc->Width <= heap_bytes - offset) { + fast = true; + allocation_bytes = static_cast<SIZE_T>(heap_bytes); + static LONG fast_calls; + const LONG n = InterlockedIncrement(&fast_calls); + if (x2w_local::first_of(n, 3) || n % 10000 == 0) + log("x2w-d3d12 slot133 X2W_PLACED_FAST: %ld calls placed without the allocation walk (heap %llu bytes)", n, heap_bytes); + } + } + } + if ((!rejected || always_walk) && !fast) + for (auto* cursor = static_cast<char*>(base); + VirtualQuery(cursor, ®ion, sizeof(region)) && region.AllocationBase == base && region.State == MEM_COMMIT; + cursor += region.RegionSize) + allocation_bytes += region.RegionSize; + // LOCAL memcut: X2W_MEMCUT_ALIAS_SLABS=1 places a buffer over pool-slab pages on the slab's section heap. + UINT64 slab_offset = 0; + ID3D12Heap* const slab_heap = info.Type == MEM_MAPPED && initial_state != D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE + ? memcut_slab_heap(address, desc->Width, &slab_offset) : nullptr; + if (!slab_heap && (rejected || offset > allocation_bytes || desc->Width > allocation_bytes - offset)) hr = E_INVALIDARG; + query_time.stop(); + TimedPart create_time(time_placed_create); + if (slab_heap) heap = slab_heap; + else if (SUCCEEDED(hr)) { std::lock_guard lock(placed_mutex); for (const auto& [known, h] : existing_heaps) { if (known == base) { @@ -4399,7 +6725,8 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 backing_budget = h.budget; } } - if (!heap) { + if (!heap && !x2w_startup::private_heap_importable(base)) hr = E_INVALIDARG; + if (!heap && SUCCEEDED(hr)) { ID3D12Device3* device3 = nullptr; hr = device_of(self)->QueryInterface(IID_PPV_ARGS(&device3)); if (SUCCEEDED(hr)) { @@ -4409,6 +6736,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 if (SUCCEEDED(hr)) { backing_budget = x2w_budget::backing_heap(heap, 0); existing_heaps.emplace_back(base, ExistingHeap{heap, backing_budget}); + note_private_range(base, heap); } } } @@ -4417,22 +6745,35 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER); ID3D12Resource* resource = nullptr; if (SUCCEEDED(hr)) - hr = device_of(self)->CreatePlacedResource(heap, offset, ©, initial_state, nullptr, + hr = device_of(self)->CreatePlacedResource(heap, slab_heap ? slab_offset : offset, ©, initial_state, nullptr, IID_PPV_ARGS(&resource)); // A buffer that spans several allocations (adjacent placeholder pieces) cannot be placed on one // existing heap. Fallback: a committed default-heap buffer, not aliased with the title memory. const bool aliased = SUCCEEDED(hr); - const char* placement = "aliased"; + const char* placement = slab_heap && aliased ? "aliased slab" : "aliased"; // LOCAL memcut: "aliased slab" + if (slab_heap && !aliased) memcut_slab_failed(address, desc->Width, hr); if (FAILED(hr)) { const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; copy.Flags = static_cast<D3D12_RESOURCE_FLAGS>(desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); - hr = device_of(self)->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, ©, initial_state, - nullptr, IID_PPV_ARGS(&resource)); - placement = "not aliased"; + static x2w_startup::PlacedPool pool; // LOCAL: X2W_D3D12_PLACED_POOL=1 (placed_pool.h) + hr = pool.create(device_of(self), copy, initial_state, &resource); + placement = "not aliased pooled"; + if (FAILED(hr)) { + hr = device_of(self)->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, ©, initial_state, + nullptr, IID_PPV_ARGS(&resource)); + placement = "not aliased"; + } } + create_time.stop(); + TimedPart log_time(time_placed_log); log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) address=%p base=%p offset=0x%llx width=0x%llx flags=0x%x " "state=0x%x clear=%p riid=%s -> 0x%08lx %s gpuva=0x%llx", address, base, offset, desc->Width, desc->Flags, state, clear, text, static_cast<unsigned long>(hr), placement, resource ? resource->GetGPUVirtualAddress() : 0ull); + if (const int r = range_watch_hit(reinterpret_cast<u64>(address), desc->Width); r >= 0 && range_watch_line(r)) + log("x2w-watch 0x%llx: slot133 placed buffer at %p width 0x%llx flags 0x%x -> 0x%08lx %s frame %ld", range_watch_address(r), address, + desc->Width, desc->Flags, static_cast<unsigned long>(hr), placement, frame_number); + if (range_watch_count()) range_watch_sample("slot133-create"); + log_time.stop(); if (FAILED(hr)) return hr; Wrapper* w = wrap(resource, resource_kind); if (release_retired_enabled()) w->own().retire_never = static_cast<std::uint8_t>(RetireNever::buffer); @@ -4596,6 +6937,7 @@ void retire_note_title_release(Wrapper* w) // held. Assumption, not proven: the guest has no raw pointer to the desktop object of a class member. void retire_hold(Wrapper* list, Wrapper* resource) { + warm_texture(resource); // Copies and resolves can bind wrappers directly. if (!resource || !resource->own().retire_when_idle) return; bool held = false; AcquireSRWLockExclusive(&retire_lock); @@ -5312,7 +7654,7 @@ void dump_pipeline(const char* what, int slot, const void* desc, std::size_t byt return GetEnvironmentVariableA("X2W_D3D12_DUMP_PSO", value, sizeof(value)) && value[0] == '1'; }(); static LONG dumped[512]; - if (!enabled || !desc || !first_calls(dumped[slot & 511], 4)) return; + if (!enabled || !desc || !x2w_local::first_calls(dumped[slot & 511], 4)) return; if (!x2w_local::readable(desc, bytes)) return; const auto* words = static_cast<const u64*>(desc); log("x2w-pso %s slot %d desc %p, %llu bytes", what, slot, desc, static_cast<unsigned long long>(bytes)); @@ -5415,11 +7757,55 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper*, const D3D12_COMPUTE log("x2w-d3d12 Device::slot62(CreateComputePipelineState?) root=%p cs=%p len=0x%llx node=0x%x flags=0x%x extra=0x%llx,0x%llx " "riid=%s -> placeholder [%s]", static_cast<void*>(desc->pRootSignature), desc->CS.pShaderBytecode, static_cast<unsigned long long>(desc->CS.BytecodeLength), desc->NodeMask, desc->Flags, extra0, extra1, text, bytes); + // LOCAL: write the compute code and its root signature to the shader cache as req_cs_<key>.{cs,root} + // for the offline compute translator (nothing executes dispatches yet). + u64 compute_key = 0; + if (Wrapper* root = as_wrapper(desc->pRootSignature); root && desc->CS.BytecodeLength && + desc->CS.BytecodeLength <= (1u << 20) && x2w_local::readable(desc->CS.pShaderBytecode, desc->CS.BytecodeLength)) { + std::vector<unsigned char> root_blob; + AcquireSRWLockShared(¬e_lock); + const auto found = root_blobs().find(root); + if (found != root_blobs().end()) root_blob = found->second; + ReleaseSRWLockShared(¬e_lock); + const u64 key = fnv_bytes(root_blob.data(), root_blob.size(), + fnv_bytes(desc->CS.pShaderBytecode, desc->CS.BytecodeLength)); + if (!root_blob.empty()) compute_key = key; + wchar_t path[MAX_PATH]; + if (!root_blob.empty() && cache_path(path, L"req_cs_", key, L".cs") && GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES) { + write_file(path, desc->CS.pShaderBytecode, desc->CS.BytecodeLength); + cache_path(path, L"req_cs_", key, L".root"); + write_file(path, root_blob.data(), root_blob.size()); + } + } if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE; *out = wrap(nullptr, pipeline_kind); auto* pipeline = static_cast<Wrapper*>(*out); note_pipeline(pipeline, 62, nullptr, desc, sizeof(*desc)); note_compute_binding_pipeline(pipeline, *desc); + // LOCAL: a retargeted and signed container <key>.cs.dxbc becomes a desktop compute pipeline. + if (compute_key) { + wchar_t path[MAX_PATH]; + ID3DBlob* code = nullptr; + Wrapper* root = as_wrapper(desc->pRootSignature); + if (!rawaddr_pipeline(compute_key, root, static_cast<Wrapper*>(*out)) && // LOCAL: a sidecar key skips the plain path + root && root->own().real && cache_path(path, L"", compute_key, L".cs.dxbc") && SUCCEEDED(D3DReadFileToBlob(path, &code))) { + D3D12_COMPUTE_PIPELINE_STATE_DESC real{}; + real.pRootSignature = static_cast<ID3D12RootSignature*>(root->own().real); + real.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + ID3D12PipelineState* pso = nullptr; + const HRESULT hr = device_of(the_device)->CreateComputePipelineState(&real, IID_PPV_ARGS(&pso)); + log("x2w-compute pipeline %016llx from signed container -> 0x%08lx", compute_key, static_cast<unsigned long>(hr)); + if (SUCCEEDED(hr)) { + AcquireSRWLockExclusive(&compute_pso_lock); + compute_psos()[static_cast<Wrapper*>(*out)] = pso; + ReleaseSRWLockExclusive(&compute_pso_lock); + } + code->Release(); + } + } + AcquireSRWLockExclusive(&compute_lock); + compute_keys()[static_cast<Wrapper*>(*out)] = compute_key; + ReleaseSRWLockExclusive(&compute_lock); return S_OK; } @@ -5458,7 +7844,11 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE // guest cache creates a pending translation for any DXBC container. real_pipeline = build_stream_pipeline(desc, why, sizeof(why), compute, graphics); bool mesh_cache_request = false; - if (!real_pipeline) + // LOCAL merge: upstream's slot-86 mesh stage cache (#2270, req_<key>.m86) takes mesh streams before + // stream_translation, which the local mesh path (X2W_MESH*) translates; it runs only with + // X2W_UPSTREAM_MESH86_CACHE=1 so the local mesh path stays as before the merge. + static const bool upstream_mesh86_cache = x2w_local::env_on("X2W_UPSTREAM_MESH86_CACHE"); + if (!real_pipeline && upstream_mesh86_cache) real_pipeline = try_cached_mesh86(*desc, why, sizeof(why), graphics, mesh_cache_request, mesh86_key); if (!mesh_cache_request && (!real_pipeline || graphics.root)) translation = stream_translation(*desc, blend, has_blend, depth_stencil, has_depth_stencil, dsv_format, @@ -5526,6 +7916,24 @@ HRESULT __stdcall device_create_pipeline_placeholder(Wrapper*, const void* desc, if constexpr (N == 67) publish_compute_request(desc); *out = wrap(nullptr, pipeline_kind); note_pipeline(static_cast<Wrapper*>(*out), N, nullptr, desc, 0x300); + if (N == 57) regblob::dump57(desc, static_cast<Wrapper*>(*out)); + if (N == 57) mesh_note57(desc, static_cast<Wrapper*>(*out)); // LOCAL meshrt: mesh key at creation (X2W_MESH=1) + if (N == 67 &&x2w_local::readable(desc, 0x28)) { + u64 words[5]; + std::memcpy(words, desc, sizeof(words)); + std::vector<unsigned char> regs; + for (int i : {1, 3}) { + const std::uint32_t bytes = words[i + 1] <= 0x1000 && x2w_local::readable(reinterpret_cast<const void*>(words[i]), words[i + 1]) + ? static_cast<std::uint32_t>(words[i + 1]) : 0u; + regs.insert(regs.end(), reinterpret_cast<const unsigned char*>(&bytes), reinterpret_cast<const unsigned char*>(&bytes) + 4); + if (bytes) regs.insert(regs.end(), reinterpret_cast<const unsigned char*>(words[i]), reinterpret_cast<const unsigned char*>(words[i]) + bytes); + } + AcquireSRWLockExclusive(&compute_lock); + compute_regs()[static_cast<Wrapper*>(*out)] = std::move(regs); + ReleaseSRWLockExclusive(&compute_lock); + // LOCAL stall: key it now and load its translation in the background (d3d12_compute.inl). + if (prewarm_enabled()) prewarm_compute(compute_key_for(static_cast<Wrapper*>(*out))); + } return S_OK; } @@ -5553,6 +7961,7 @@ HRESULT __stdcall device_create_derived_pipeline(Wrapper*, void* base, UINT coun } *out = wrap(nullptr, pipeline_kind); note_pipeline(static_cast<Wrapper*>(*out), 55, base, desc, bytes_in_patches); + regblob::dump55(base, desc, bytes_in_patches); return S_OK; } @@ -5577,6 +7986,8 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP const D3D12_RESOURCE_ALLOCATION_INFO info = device_of(self)->GetResourceAllocationInfo(0, 1, ©); check_device("Device before slot", 127); void* const title_memory = info.SizeInBytes != ~0ull ? title_resource_memory(info.SizeInBytes, info.Alignment) : nullptr; + D3D12_CLEAR_VALUE mapped_clear{}; + if (clear) { mapped_clear = *clear; mapped_clear.Format = desktop_format(mapped_clear.Format); clear = &mapped_clear; } ID3D12Resource* resource = nullptr; const D3D12_RESOURCE_STATES initial = props->Type == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ : props->Type == D3D12_HEAP_TYPE_READBACK ? D3D12_RESOURCE_STATE_COPY_DEST @@ -5600,6 +8011,8 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP if (FAILED(hr)) return hr; x2w_startup::mark_packed_stand_in(resource, desktop_format(desc->Format)); Wrapper* w = wrap(resource, resource_kind); + if (copy.Format != desc->Format && copy.Format == x2w_srgb::family(desc->Format)) + w->own().srgb_uav_format = static_cast<unsigned char>(desc->Format); 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); @@ -5627,7 +8040,14 @@ HRESULT __stdcall device_wait_frame_event(Wrapper*, UINT type, UINT timeout, voi QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&origin); } - const LONGLONG interval = frequency.QuadPart * (frame_interval_us ? frame_interval_us : 33333) / 1000000; + // LOCAL: X2W_FRAME_US overrides the title's interval (for example 8333 for 120 Hz, 1 for no pacing) + // so boot, menus and loading run faster in test runs. + static const UINT override_us = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_FRAME_US", value, sizeof(value)) ? static_cast<UINT>(std::atol(value)) : 0u; + }(); + const UINT interval_us = override_us ? override_us : frame_interval_us ? frame_interval_us : 33333; + const LONGLONG interval = frequency.QuadPart * interval_us / 1000000; LARGE_INTEGER now; QueryPerformanceCounter(&now); LONGLONG target; @@ -5636,7 +8056,8 @@ HRESULT __stdcall device_wait_frame_event(Wrapper*, UINT type, UINT timeout, voi if (target < now.QuadPart) target = now.QuadPart; // running late: start a new timeline here origin.QuadPart = target; } else { - target = origin.QuadPart + frequency.QuadPart * frame_event_offset_us[type < 4 ? type : 3] / 1000000; + const UINT offset_us = frame_event_offset_us[type < 4 ? type : 3]; + target = origin.QuadPart + frequency.QuadPart * (override_us && offset_us > override_us ? override_us : offset_us) / 1000000; } const LONGLONG wait_ticks = target > now.QuadPart ? target - now.QuadPart : 0; ReleaseSRWLockExclusive(&lock); @@ -5711,7 +8132,92 @@ void draw_overlay(LONG frame, double seconds) ReleaseDC(window, dc); } +#include "startup_stubs/d3d12_compute.inl" +#include "startup_stubs/d3d12_heap_raw.inl" // LOCAL: `heapraw 1`, raw V#s in the title heap +#include "startup_stubs/d3d12_range_alias.inl" // LOCAL indirect: X2W_RANGE_ALIAS +// Translated shader ABI (X2W_GPU_ABI=1): the owners' bodies (gpu_hooks.h), then WP0's installed handlers. +#include "startup_stubs/gpu_pipeline.inl" // WP2 vpipe +#include "startup_stubs/gpu_heap.inl" // WP5 rawtwins +#include "startup_stubs/gpu_views.inl" // WP5 rawtwins +#include "startup_stubs/gpu_find.h" // WP3 vbind +#include "startup_stubs/gpu_bind.inl" // WP3 vbind +#include "startup_stubs/gpu_indirect.inl" // WP4 vindirect +#include "startup_stubs/gpu_hooks.inl" // WP0 vhooks +#include "startup_stubs/d3d12_vdesc.inl" // LOCAL meshrt: `heapwords 1` +#include "startup_stubs/d3d12_gpu_time.inl" +#include "startup_stubs/d3d12_indirect.inl" +#include "startup_stubs/d3d12_mesh.inl" // LOCAL meshrt +#include "startup_stubs/d3d12_record_trace.inl" // LOCAL (scene): X2W_MESH_RECORD_TRACE +#include "startup_stubs/cull_input_capture.inl" // LOCAL (diagnostic): X2W_CULL_INPUT_CAPTURE +#include "startup_stubs/d3d12_rawaddr.inl" #include "startup_stubs/d3d12_present.inl" +#include "startup_stubs/d3d12_copy_buffer.inl" + +// LOCAL stall: every 300 presents (or 10 s), one line: the wall time between them on the presenting thread, split +// into time inside timed stand-in calls and outside, the thread's own CPU time in the same window (wall +// minus CPU is time it was blocked or not scheduled), and the threads with the most stand-in time in the +// window. Says whether the frame period is the presenting thread's own work or a wait on something else. +// X2W_PRESENT_SPLIT=<frames>: another period (default 300); 0: off. +LONG present_split_period() +{ + static const LONG period = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_PRESENT_SPLIT", value, sizeof(value)) ? std::atol(value) : 300L; + }(); + return period; +} + +void present_split(LONG frame) +{ + static LARGE_INTEGER frequency, last; + static LONG last_frame; + static LONG64 last_inside, last_ticks[thread_inside_max]; + static ULONG64 last_cpu; + static DWORD last_tid; + if (!frequency.QuadPart) QueryPerformanceFrequency(&frequency); + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + FILETIME created, exited, kernel, user; + GetThreadTimes(GetCurrentThread(), &created, &exited, &kernel, &user); + const auto u64_of = [](const FILETIME& t) { return (static_cast<ULONG64>(t.dwHighDateTime) << 32) | t.dwLowDateTime; }; + const ULONG64 cpu = u64_of(kernel) + u64_of(user); // 100 ns units + const DWORD tid = GetCurrentThreadId(); + const LONG64 inside = inside_slot()->ticks; + const LONG count = thread_inside_count < thread_inside_max ? thread_inside_count : thread_inside_max; + const auto ms = [](LONG64 ticks) { return static_cast<double>(ticks) * 1000.0 / static_cast<double>(frequency.QuadPart); }; + if (last.QuadPart && tid == last_tid && frame > last_frame) { + const double wall = ms(now.QuadPart - last.QuadPart), in = ms(inside - last_inside); + const double cpu_ms = static_cast<double>(cpu - last_cpu) / 1e4; + struct Top { LONG tid; LONG64 ticks; } top[4]{}; + for (LONG i = 0; i < count; ++i) { + const LONG64 delta = thread_inside[i].ticks - last_ticks[i]; + for (int j = 0; j < 4; ++j) { + if (delta <= top[j].ticks) continue; + for (int m = 3; m > j; --m) top[m] = top[m - 1]; + top[j] = {thread_inside[i].tid, delta}; + break; + } + } + char text[160]; + int used = 0; + text[0] = 0; + for (const Top& t : top) + if (t.ticks) used += std::snprintf(text + used, sizeof(text) - used, " %ld:%.0f", t.tid, ms(t.ticks)); + const LONG frames = frame - last_frame; + log("x2w-present split over %ld frames (%.1f ms/frame): presenting thread %lu inside timed d3d12_xs calls %.1f " + "ms/frame, outside %.1f ms/frame (xmem/XCRDAPI time counts as outside); its CPU %.1f ms/frame, so %.1f ms/frame " + "blocked or not running; timed d3d12_xs ms by thread (tid:ms over the window):%s; %ld threads seen", + frames, wall / frames, tid, in / frames, (wall - in) / frames, + cpu_ms / frames, (wall - cpu_ms) / frames, text, count); + fence_times::report(); // X2W_FENCE_TIMES=1, same window + } + last = now; + last_frame = frame; + last_inside = inside; + last_cpu = cpu; + last_tid = tid; + for (LONG i = 0; i < count; ++i) last_ticks[i] = thread_inside[i].ticks; +} // Render mode: a coarse signature of the presented picture for input-script waits (present_signature.h, // present_signature_sampler.h). The block always counts presents; samples are taken every 4 presents @@ -5815,22 +8321,108 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa static LONG frames; static ULONGLONG started, last_report; const LONG frame = InterlockedIncrement(&frames); + if (const LONG period = present_split_period(); period > 0) { + static ULONGLONG split_due; + const ULONGLONG tick = GetTickCount64(); + if (frame == 1 || frame % period == 0 || tick >= split_due) { + split_due = tick + 10000; + present_split(frame); + } + } frame_number = frame; + const bool gpu_trace_end = gpu_trace_frame == frame; + if (vbind::compute_capture_in_flight.load() && TryAcquireSRWLockExclusive(&draw_lock)) { + vbind::compute_capture_poll_locked(); + ReleaseSRWLockExclusive(&draw_lock); + } + if (range_watch_count()) range_watch_sample("present"); + note_present_planes(frame, planes, plane_parameters, present_parameters); + note_quiet_frame(frame); + note_descriptor_watch(frame); draw_dump_flush(); red_producers().flush(); + cull_capture_flush(); // LOCAL: X2W_CULL_INPUT_CAPTURE + cx_dump::poll(); // LOCAL lt-lead probe: X2W_CX_DUMP_INPUTS read-back + dd_dump::poll(); // LOCAL lt-lead probe: X2W_DRAW_DUMP_INPUTS read-back { - static const LONG wanted = [] { - char value[16]{}; - return GetEnvironmentVariableA("X2W_D3D12_TRACE_FRAME", value, sizeof(value)) ? std::atol(value) : 0L; - }(); + auto& scene = gpu_scene_trace(); + if (scene.mrt || !scene.request_file.empty()) { + LONG completed = -1; + { + std::lock_guard<std::mutex> held(scene.lock); + if (scene.active_frame && scene.active_frame <= frame) { + completed = scene.active_id; + InterlockedExchange(&gpu_trace_request_id, 0); + scene.active_frame = scene.active_id = 0; + std::atomic_store(&gpu_scene_stage_override, TraceStageKey{}); + std::atomic_store(&gpu_scene_second_override, TraceStageKey{}); + InterlockedExchange(&gpu_trace_frame, 0); + InterlockedExchange(&trace_frame_active, 0); + InterlockedExchange(&trace_uav_busy_frame, 0); + } + } + if (completed >= 0) { + if (x2w_local::env_on("X2W_D3D12_TRACE_TARGETS")) + summarise_traced_targets(static_cast<ID3D12CommandQueue*>(self->own().real), completed); + log("x2w-frame ---- end deferred frame %ld request %ld", frame, completed); + } + scene.poll(); + } + const LONG wanted = trace_requested_frame(); // The call that presents frame n-1 starts the trace; the one that presents frame n ends it. - if (wanted && frame == wanted - 1) { + if (wanted && !gpu_trace_frame && frame == wanted - 1) { log("x2w-frame ---- begin frame %ld", wanted); + reset_gpu_trace_commands(); + InterlockedExchange(&gpu_trace_frame, wanted); InterlockedExchange(&trace_frame_active, 1); - } else if (wanted && frame == wanted) { + } else if (wanted && gpu_trace_frame == wanted && frame == wanted) { InterlockedExchange(&trace_frame_active, 0); + InterlockedExchange(&gpu_trace_frame, 0); + if (x2w_gpu::gpu_abi_on() && x2w_local::env_on("X2W_D3D12_TRACE_TARGETS")) + summarise_traced_targets(static_cast<ID3D12CommandQueue*>(self->own().real)); log("x2w-frame ---- end frame %ld", wanted); } + // LOCAL: X2W_D3D12_TRACE_BUSY=n traces one frame after the first frame with at least n dispatches + // (the first busy frame after loading), then one more every 3000 frames. + static const LONG busy = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_D3D12_TRACE_BUSY", value, sizeof(value)) ? std::atol(value) : 0L; + }(); + static LONG busy_end, busy_next; + const LONG dispatched = InterlockedExchange(&frame_dispatches, 0); + mesh_stats_present(frame); // LOCAL meshrt: traced mesh calls' pipeline statistics, 8 presents after the traced frame + mesh_fs_present(); // LOCAL meshrt: X2W_MESH_STATS_FRAMES + if (busy && busy_end && frame == busy_end) { + InterlockedExchange(&gpu_trace_frame, 0); + InterlockedExchange(&trace_uav_busy_frame, 0); + InterlockedExchange(&trace_frame_active, 0); + log("x2w-frame ---- end busy frame %ld", frame); + // The target read-back stalls Present for about a second: only with X2W_D3D12_TRACE_TARGETS=1. + static const bool targets = x2w_local::env_on("X2W_D3D12_TRACE_TARGETS"); + record_trace_report(static_cast<ID3D12CommandQueue*>(self->own().real)); // LOCAL (scene): X2W_MESH_RECORD_TRACE + if (targets) summarise_traced_targets(static_cast<ID3D12CommandQueue*>(self->own().real)); + summarise_indirect_calls(); + busy_end = 0; + } else if (busy && !scene.mrt && !scene.waiting.load() && !gpu_trace_frame && !busy_end && frame >= busy_next) { + // LOCAL (scene): X2W_D3D12_TRACE_BUSY_AFTER=n delays the traced frame by n frames after the first busy + // frame (the scene's first frames are black while its pipelines still compile). + static const LONG after = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_D3D12_TRACE_BUSY_AFTER", value, sizeof(value)) ? std::atol(value) : 0L; + }(); + static LONG busy_seen; + if (!busy_seen && dispatched >= busy) busy_seen = frame; + if (busy_seen && frame >= busy_seen + after) { + log("x2w-frame ---- begin busy frame %ld (previous frame: %ld dispatches; first busy frame %ld)", frame + 1, dispatched, busy_seen); + reset_gpu_trace_commands(); + InterlockedExchange(&gpu_trace_frame, frame + 1); + InterlockedExchange(&trace_frame_active, 1); + busy_end = frame + 1; + InterlockedExchange(&trace_uav_busy_frame, busy_end); + busy_next = frame + 3000; + busy_seen = 0; + } + } } bool shown_in_window = false; { @@ -5839,6 +8431,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa if (planes && words && x2w_local::readable(words, 0x18) && words[1] >= 1 && x2w_local::readable(reinterpret_cast<const void*>(words[2]), 8)) surface = as_wrapper(*reinterpret_cast<void* const*>(words[2])); capture::present(frame, surface); + if (gpu_trace_end && surface && surface->own().kind == resource_kind) + log("x2w-frame gpu present frame %ld: title=%p desktop=%p", frame, static_cast<void*>(surface), + static_cast<void*>(surface->own().real)); if (surface && surface->own().kind == resource_kind) red_producers().present(static_cast<ID3D12Resource*>(surface->own().real)); // Render mode: the presented surface goes to the title's window through a swap chain. @@ -5855,20 +8450,42 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa hex_text(present_parameters, 0x40, b, sizeof(b)); log("x2w-d3d12 CommandQueue::slot32(present) planes=%u plane=[%s] present=[%s]", planes, a, b); } - if (render_mode() && frame % (shown_in_window ? 60 : 6) == 0 && planes && plane_parameters) { + // LOCAL: X2W_D3D12_SHOT_FRAMES=<n> reads the presented surface back (and writes a numbered shot) every + // n frames while the window shows frames, instead of every 60 (0.5 s at 120 fps): the setup driver + // waits for fresh shots between presses. + static const ULONGLONG shot_frames = [] { + char value[8]{}; + const DWORD n = GetEnvironmentVariableA("X2W_D3D12_SHOT_FRAMES", value, sizeof(value)); + const unsigned long frames = n && n < sizeof(value) ? std::strtoul(value, nullptr, 10) : 0ul; + return frames ? static_cast<ULONGLONG>(frames) : 60ull; + }(); + if (render_mode()) read_back_presented(nullptr, nullptr, false); // LOCAL stall: picks up a finished copy + const bool paired = red_producers().pair_present(frame, static_cast<ID3D12CommandQueue*>(self->own().real)); + // Wall-clock sampling also captures transitions that present only a few frames per minute. + static const DWORD shot_ms = [] { + char value[12]{}; + const DWORD n = GetEnvironmentVariableA("X2W_D3D12_SHOT_MS", value, sizeof(value)); + return n && n < sizeof(value) ? std::strtoul(value, nullptr, 10) : 0ul; + }(); + static std::atomic<ULONGLONG> last_shot{0}; + auto previous = last_shot.load(std::memory_order_relaxed); + const bool due = shot_ms ? now >= previous && now - previous >= shot_ms && + last_shot.compare_exchange_strong(previous, now, std::memory_order_relaxed) + : frame % (shown_in_window ? shot_frames : 6) == 0; + if (render_mode() && (paired || due) && planes && plane_parameters) { // Plane parameters: +0x00 frame token, +0x08 resource count, +0x10 pointer to the resources. const auto* words = static_cast<const u64*>(plane_parameters); if (x2w_local::readable(words, 0x18) && words[1] >= 1 && x2w_local::readable(reinterpret_cast<const void*>(words[2]), 8)) { Wrapper* surface = as_wrapper(*reinterpret_cast<void* const*>(words[2])); if (surface && surface->own().kind == resource_kind && surface->own().real) - read_back_presented(static_cast<ID3D12CommandQueue*>(self->own().real), static_cast<ID3D12Resource*>(surface->own().real)); + read_back_presented(static_cast<ID3D12CommandQueue*>(self->own().real), static_cast<ID3D12Resource*>(surface->own().real), true, paired ? frame : 0); else std::snprintf(shown_note, sizeof(shown_note), "presented object %p is not a known resource", *reinterpret_cast<void* const*>(words[2])); } } if (shown_in_window) { - if (frame % 30 == 0) { + if (!present_in_title_window() && frame % 30 == 0) { // About 100 fixed characters, the revision (at most 46) and three numbers fit in 256. wchar_t text[256]; swprintf(text, 256, L"Xbox2Windows %ls - frame %ld, %.1f fps, %ld translated draws (title bar is diagnostics, picture is game output)", @@ -5881,7 +8498,7 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa // The null-binding total and its causes change together under draw_lock (draw_translated holds it), so they are copied there. LONG null_total = 0, null_causes[x2w_local::null_cause_count] = {}; if (render_mode() && frame % 300 == 0) { - AcquireSRWLockExclusive(&draw_lock); + lock_draw(0 + __LINE__); null_total = null_bindings; for (int c = 0; c < x2w_local::null_cause_count; ++c) null_causes[c] = null_by_cause[c]; ReleaseSRWLockExclusive(&draw_lock); @@ -5889,17 +8506,31 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa if (render_mode() && frame % 300 == 0) log("x2w-render totals: resets %ld (failed %ld), closes %ld, clears %ld, target binds %ld (unresolved %ld), executes %ld, draws %ld (skipped %ld), " "translated draws %ld (not drawn %ld), pipelines translated %ld / missing %ld, null bindings %ld (entry %ld, buffer %ld, token %ld, wrapper %ld, dimension %ld), " - "formatted-load draws refused %ld, textures uploaded %ld (%ld KiB, unreadable %ld), heap-indexed roots deferred %ld (real draws refused: view heap %ld, " + "buffer links %ld, refused-view entries %ld (nulled %ld, rewritten markers %ld), textures uploaded %ld (%ld KiB, unreadable %ld), heap-indexed roots deferred %ld (real draws refused: view heap %ld, " "sampler heap %ld, both heaps %ld, state %ld), pipelines first looked up by ExecuteIndirect %ld, compute requests published %ld (already present %ld, failed %ld, pointer-like blob qwords %ld)", render_resets, render_reset_failures, render_closes, render_clears, render_target_binds, render_target_unresolved, render_executes, render_draws, render_draws_skipped, translated_draws, untranslated_draws, translation_ready, translation_missing, null_total, - null_causes[0], null_causes[1], null_causes[2], null_causes[3], null_causes[4], formatted_draws_refused, textures_uploaded, + null_causes[0], null_causes[1], null_causes[2], null_causes[3], null_causes[4], buffer_links, buffer_refused_views, buffer_links_nulled, marker_rewrites, textures_uploaded, texture_bytes_uploaded, textures_unreadable, heap_roots_deferred, heap_root_refusals[static_cast<int>(x2w_startup::RealRootDecision::view_heap_missing)], heap_root_refusals[static_cast<int>(x2w_startup::RealRootDecision::sampler_heap_missing)], heap_root_refusals[static_cast<int>(x2w_startup::RealRootDecision::both_heaps_missing)], heap_root_refusals[static_cast<int>(x2w_startup::RealRootDecision::state_not_restorable)], indirect_first_lookups, compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words); + if (render_mode() && frame % 300 == 0) report_target_binds(); + if (render_mode() && frame % 300 == 0) report_draw_state(); // LOCAL (renderstate): d3d12_draw.inl + if (frame % 300 == 0) draw_lock_times::report("300 frames"); // LOCAL stall: X2W_DRAW_LOCK_TIMES + if (x2w_local::probe_cache_on()) { // LOCAL stall: X2W_PROBE_CACHE (local_log.h); entries also end at each present + x2w_local::invalidate_probe_cache(); + if (frame % 300 == 0) { + x2w_local::ProbeCache& c = x2w_local::probe_cache(); + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + log("x2w-probe cache (X2W_PROBE_CACHE, %llu ms, cleared at each present): since start %lld probes answered from the cache without a " + "fault, %lld faults (%lld VirtualQuery, %.1f ms), %lld unreadable ranges kept, %lld query-first rejections", x2w_local::probe_cache_ms(), c.hits, c.faults, + c.queries, static_cast<double>(c.query_ticks) * 1000.0 / static_cast<double>(f.QuadPart), c.cached, c.preflight_rejects); + } + } 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", @@ -5926,6 +8557,12 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa if (calls) n += std::snprintf(line + n, sizeof(line) - n, " %d:%.1f", i, calls / 300.0); } log("%s", line); + report_dispatches(); + report_indirect(300); // LOCAL: d3d12_indirect.inl + report_mesh(300); // LOCAL meshrt: d3d12_mesh.inl (X2W_MESH=1) + regblob::report(); + report_cx_views(); + gpu_time::report(); // LOCAL: X2W_CX_GPU_TIME } if (now - last_report >= 5000) { last_report = now; @@ -5936,7 +8573,7 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); - char text[512]; + char text[768]; int used = 0; for (int i = 0; i < time_count; ++i) { const LONG64 ticks = InterlockedExchange64(&time_ticks[i], 0), calls = InterlockedExchange64(&time_calls[i], 0); @@ -5945,6 +8582,13 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa static_cast<long long>(ticks * 1000 / frequency.QuadPart), static_cast<long long>(calls)); } log("x2w-d3d12 time inside the stand-in since the last report (ms/calls):%s", text); + static LONG64 placed_reported = 0; // LOCAL: slot 133 totals, when they changed + const LONG64 placed_calls = placed_calls_total; + if (placed_calls != placed_reported) { + placed_reported = placed_calls; + log("x2w-d3d12 placed resources (slot 133) since the start: %lld calls, %lld ms inside", static_cast<long long>(placed_calls), + static_cast<long long>(placed_ticks_total * 1000 / frequency.QuadPart)); + } used = 0; text[0] = 0; for (int i = 0; i < 256; ++i) { @@ -5955,6 +8599,12 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa } if (used) log("x2w-d3d12 command-list slots over 20 ms:%s", text); } + rawaddr_report(); // LOCAL raw-address shaders (d3d12_rawaddr.inl) + report_srv_copies(); // LOCAL stall: X2W_DRAW_SRV_STATS / X2W_DRAW_SRV_IN_PLACE (d3d12_draw.inl) + report_cx_async(); // LOCAL stall: X2W_CX_ASYNC (d3d12_compute.inl) + report_heap_raw(); // LOCAL: `heapraw 1` drains and evictions (d3d12_heap_raw.inl) + report_prewarm_known("at the heartbeat"); // LOCAL stall: X2W_CX_PREWARM_ALL + report_draw_async(); // LOCAL stall: X2W_DRAW_ASYNC (d3d12_draw.inl) memory_srv_census.report([](const char* line) { log("%s", line); }, true); token_null_census.report([](const char* line) { log("%s", line); }, true); memory_srv_writes.report([](const char* line) { log("%s", line); }, true); @@ -6057,6 +8707,8 @@ void build_tables() // Xbox order from here. tables[device_kind][48] = reinterpret_cast<void*>(&device_create_command_queue_x); tables[device_kind][70] = reinterpret_cast<void*>(&device_memory_srv); + if (memory_srv_buffer_on()) tables[device_kind][71] = reinterpret_cast<void*>(&device_memory_uav); // LOCAL (video) + if (texture_census_on()) tables[device_kind][61] = reinterpret_cast<void*>(&device_slot61_census); // LOCAL (textures) tables[device_kind][73] = reinterpret_cast<void*>(&device_create_command_list_x); tables[device_kind][78] = reinterpret_cast<void*>(&device_frame_interval); tables[device_kind][79] = reinterpret_cast<void*>(&device_frame_event); @@ -6076,6 +8728,7 @@ void build_tables() fill_noops<list_kind>(tables[list_kind], std::make_index_sequence<slot_count>{}); tables[list_kind][7] = reinterpret_cast<void*>(&child_get_device); } + list_typed[148] = reinterpret_cast<ListTyped>(&list_allocate_upload); if (render_mode()) { list_typed[9] = reinterpret_cast<ListTyped>(&list_close); list_typed[51] = reinterpret_cast<ListTyped>(&list_clear_depth_stencil); @@ -6091,30 +8744,55 @@ void build_tables() list_typed[54] = reinterpret_cast<ListTyped>(&list_clear_uav<true>); list_typed[55] = reinterpret_cast<ListTyped>(&list_discard); list_typed[139] = reinterpret_cast<ListTyped>(&list_reset); - list_typed[148] = reinterpret_cast<ListTyped>(&list_allocate_upload); + // Upstream per-recording upload pages (list_upload_pages.h) replace the local slot 148 arena only with + // X2W_LIST_UPLOAD_PAGES=1; without it list_upload_gpu finds no pages and its users fall through. + if (x2w_local::env_on("X2W_LIST_UPLOAD_PAGES")) list_typed[148] = reinterpret_cast<ListTyped>(&list_allocate_upload_pages); list_typed[12] = reinterpret_cast<ListTyped>(&list_draw); + list_typed[14] = reinterpret_cast<ListTyped>(&list_dispatch); + list_typed[61] = reinterpret_cast<ListTyped>(&list_execute_indirect); + list_typed[33] = reinterpret_cast<ListTyped>(&list_compute_root); + list_typed[35] = reinterpret_cast<ListTyped>(&list_compute_table); + list_typed[37] = reinterpret_cast<ListTyped>(&list_compute_constant); + list_typed[39] = reinterpret_cast<ListTyped>(&list_compute_constants); + list_typed[41] = reinterpret_cast<ListTyped>(&list_compute_cbv); + list_typed[43] = reinterpret_cast<ListTyped>(&list_compute_srv); + list_typed[45] = reinterpret_cast<ListTyped>(&list_compute_uav); list_typed[16] = reinterpret_cast<ListTyped>(&list_copy_texture); + list_typed[85] = reinterpret_cast<ListTyped>(&list_copy_texture_x); list_typed[20] = reinterpret_cast<ListTyped>(&list_topology); list_typed[21] = reinterpret_cast<ListTyped>(&list_viewports); list_typed[22] = reinterpret_cast<ListTyped>(&list_scissors); list_typed[23] = reinterpret_cast<ListTyped>(&list_blend_factor); - list_typed[24] = reinterpret_cast<ListTyped>(&list_stencil_ref); + // LOCAL merge: upstream installs slot 24 always; here with the depth group, X2W_DEPTH_STATE, or + // X2W_UPSTREAM_STENCIL_REF=1 (slot 24 alone, upstream's OMSetStencilRef forwarding). + if (x2w_pipeline_state::switches_from_env().depth || x2w_local::env_on("X2W_DEPTH_STATE") || + x2w_local::env_on("X2W_UPSTREAM_STENCIL_REF")) list_typed[24] = reinterpret_cast<ListTyped>(&list_stencil_ref); // LOCAL (renderstate) + if (x2w_pipeline_state::switches_from_env().depth_clear) // LOCAL (renderstate): not through noop_slot (float argument) + tables[list_kind][51] = reinterpret_cast<void*>(&list_clear_depth); list_typed[25] = reinterpret_cast<ListTyped>(&list_pipeline); list_typed[x2w_list_slots::resource_barrier_slot] = reinterpret_cast<ListTyped>(&list_resource_barriers); list_typed[32] = reinterpret_cast<ListTyped>(&list_set_descriptor_heaps); - list_typed[33] = reinterpret_cast<ListTyped>(&list_compute_root); + // Upstream desktop compute binding (slot 33 root, slot 43 upload-page SRV; feeds its ExecuteIndirect dispatch + // forwarding) replaces the local compute root handlers only with X2W_UPSTREAM_COMPUTE_ROOT=1. + static const bool upstream_compute_root = x2w_local::env_on("X2W_UPSTREAM_COMPUTE_ROOT"); + if (upstream_compute_root) list_typed[33] = reinterpret_cast<ListTyped>(&list_compute_root_desktop); list_typed[34] = reinterpret_cast<ListTyped>(&list_graphics_root); - list_typed[43] = reinterpret_cast<ListTyped>(&list_compute_upload_srv); + if (upstream_compute_root) list_typed[43] = reinterpret_cast<ListTyped>(&list_compute_upload_srv); list_typed[44] = reinterpret_cast<ListTyped>(&list_root_srv); + list_typed[46] = reinterpret_cast<ListTyped>(&list_root_uav); // LOCAL draw-rt (d3d12_draw.inl) list_typed[42] = reinterpret_cast<ListTyped>(&list_root_cbv); list_typed[50] = reinterpret_cast<ListTyped>(&list_targets); list_typed[13] = reinterpret_cast<ListTyped>(&list_draw_indexed); - list_typed[35] = reinterpret_cast<ListTyped>(&list_compute_table); + if (upstream_compute_root) list_typed[35] = reinterpret_cast<ListTyped>(&list_compute_table_desktop); list_typed[36] = reinterpret_cast<ListTyped>(&list_table); list_typed[40] = reinterpret_cast<ListTyped>(&list_root_constants); list_typed[47] = reinterpret_cast<ListTyped>(&list_index_buffer); list_typed[48] = reinterpret_cast<ListTyped>(&list_vertex_buffers); - list_typed[x2w_list_slots::execute_indirect_slot] = reinterpret_cast<ListTyped>(&list_execute_indirect); + install_copy_buffer(list_typed); + // Upstream ExecuteIndirect (#2232 .. #2262, translated indirect draws with X2W_TRANSLATED_INDIRECT_DRAW=1) + // replaces the local d3d12_indirect.inl slot 61 only with X2W_UPSTREAM_EXECUTE_INDIRECT=1. + if (x2w_local::env_on("X2W_UPSTREAM_EXECUTE_INDIRECT")) + list_typed[x2w_list_slots::execute_indirect_slot] = reinterpret_cast<ListTyped>(&list_execute_indirect_upstream); // X2W_D3D12_QUERY_SLOTS=1 (diagnostic): which console methods sit at 28 to 30 is a hypothesis, so the query // bindings are opt-in. Unset, the slots stay no-ops. if (wchar_t on[4]{}; GetEnvironmentVariableW(L"X2W_D3D12_QUERY_SLOTS", on, 4) && on[0] == L'1') { @@ -6124,13 +8802,20 @@ void build_tables() } } tables[device_kind][16] = reinterpret_cast<void*>(&device_create_root_signature); + // Translated shader ABI (X2W_GPU_ABI=1): its slot handlers over the ones above (gpu_hooks.inl). Off: + // nothing changes. + if (x2w_gpu::gpu_abi_on()) gpu_install(); // Queue: not the desktop order (slot 18 is GetTimestampFrequency, desktop 16). Slots are // dispatched by argument shape until the order is known; see queue_dynamic. fill_queue_dynamic(tables[queue_kind], std::make_index_sequence<64>{}); tables[queue_kind][17] = reinterpret_cast<void*>(&queue_wait); tables[queue_kind][18] = reinterpret_cast<void*>(&queue_timestamp_frequency); - tables[queue_kind][31] = reinterpret_cast<void*>(&queue_page_mappings); + // LOCAL: upstream's slot 31 page batch (#2307) makes much more title memory readable, which multiplies the + // X2W_MEMORY_SRV_DETILE texture copies past the video memory budget. It is installed only with + // X2W_UPSTREAM_QUEUE_PAGE_BATCH=1; otherwise slot 31 stays the queue_dynamic no-op (x2w-noop CommandQueue::slot31). + if (x2w_local::env_on("X2W_UPSTREAM_QUEUE_PAGE_BATCH")) + tables[queue_kind][31] = reinterpret_cast<void*>(&queue_page_mappings); tables[queue_kind][32] = reinterpret_cast<void*>(&queue_present); // Fence: GetCompletedValue, SetEventOnCompletion, Signal, GetCreationFlags. @@ -6153,6 +8838,12 @@ void build_tables() tables[descriptor_heap_kind][9] = reinterpret_cast<void*>(&descriptor_heap_cpu_start); tables[descriptor_heap_kind][10] = reinterpret_cast<void*>(&descriptor_heap_gpu_start); if (device_noop()) fill_all_remaining_noops(std::make_index_sequence<kind_count>{}); + // Say what the tables hold after the fill, so a census run shows which build it ran. + if (noop_census_enabled()) + log("x2w-noop-census tables: device slot 70 = %s, list slot 12 typed = %s, list slot 44 typed = %s, render mode %d, device noop %d, list noop %d", + tables[device_kind][70] == reinterpret_cast<void*>(&device_memory_srv) ? "memory SRV handler" + : tables[device_kind][70] == reinterpret_cast<void*>(&device_noop_slot<70>) ? "NO-OP" : "other", + list_typed[12] ? "yes" : "NO", list_typed[44] ? "yes" : "NO", render_mode() ? 1 : 0, device_noop() ? 1 : 0, list_noop() ? 1 : 0); } SRWLOCK written_lock = SRWLOCK_INIT; @@ -6169,6 +8860,25 @@ void note_texture_write(void* base, UINT bc7_width, UINT bc7_height) ReleaseSRWLockExclusive(&written_lock); } } // namespace +#include "startup_stubs/d3d12_mem_counters.inl" // LOCAL memcut: x2w_memory_counters export +#include "startup_stubs/d3d12_memcut_release.inl" // LOCAL memcut: X2W_MEMCUT_RELEASE +#include "startup_stubs/d3d12_memcut_alias.inl" // LOCAL memcut: X2W_MEMCUT_ALIAS_SLABS +// LOCAL memcut: upload ring counters for fixtures (d3d12_upload_ring.inl upload_ring_counter). +extern "C" __declspec(dllexport) BOOL x2w_desktop_range_test(UINT64 address, UINT64 bytes, ID3D12Resource** window, UINT64* offset) +{ + if (!window || !offset || !desktop_range(address, bytes, window, offset)) return FALSE; + (*window)->AddRef(); + return TRUE; +} + +extern "C" __declspec(dllexport) UINT64 x2w_gpu_find_address_test(UINT64 address, UINT64 bytes) +{ + GpuFound found{}; + return gpu_find(address, bytes, &found) ? found.resource->GetGPUVirtualAddress() + found.offset : 0; +} +extern "C" __declspec(dllexport) unsigned long long x2w_upload_ring_test(int what) { return upload_ring_counter(what); } +// Translated shader ABI hook counters (x2w_gpu::GpuCounter) for fixtures; -1 for an unknown counter. +extern "C" __declspec(dllexport) long long x2w_gpu_counter(int which) { return gpu_count(which); } void x2w_startup::attach_device(ID3D12Device* device, void** wrapped) { @@ -6177,6 +8887,7 @@ void x2w_startup::attach_device(ID3D12Device* device, void** wrapped) removal_device = device; the_device = wrap(device, device_kind); *wrapped = the_device; + prewarm_known_start(); // LOCAL stall: X2W_CX_PREWARM_ALL (d3d12_compute.inl) } HRESULT x2w_startup::resolve_placed_build(void* guest_device, UINT64 dest, UINT64 scratch, @@ -6251,6 +8962,36 @@ HRESULT x2w_d3d12_permissive_create_device(IUnknown* adapter, const void* parame log("x2w-d3d12 debug layer: 0x%08lx%s", static_cast<unsigned long>(debug_hr), SUCCEEDED(debug_hr) ? " enabled" : " (not installed?)"); } + // LOCAL stall: X2W_BACKGROUND_PRIORITY=1 (the launcher sets it) lowers this process's GPU scheduling + // priority class and its CPU priority class to below normal, so the desktop compositor and other + // programs win while a run saturates the GPU. Both are allowed for an unelevated process lowering its + // own priority; the results are logged. Unset or 0: today's priorities. + static const bool background = [] { + if (!x2w_local::env_on("X2W_BACKGROUND_PRIORITY")) return false; + // gdi32!D3DKMTSetProcessSchedulingPriorityClass(process, D3DKMT_SCHEDULINGPRIORITYCLASS): + // 0 idle, 1 below normal, 2 normal (d3dkmthk.h); NTSTATUS result. + using SetGpuClass = LONG(APIENTRY*)(HANDLE, int); + const HMODULE gdi = LoadLibraryW(L"gdi32.dll"); + const auto set_gpu = gdi ? reinterpret_cast<SetGpuClass>(GetProcAddress(gdi, "D3DKMTSetProcessSchedulingPriorityClass")) : nullptr; + const LONG gpu = set_gpu ? set_gpu(GetCurrentProcess(), 1) : -1; + const BOOL cpu = SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); + const DWORD cpu_error = cpu ? 0 : GetLastError(); + log("x2w-d3d12 background priority: GPU scheduling class below normal -> 0x%08lx%s; CPU priority class below normal -> %s " + "(error %lu, class now 0x%lx)", static_cast<unsigned long>(gpu), set_gpu ? "" : " (entry point not found)", + cpu ? "ok" : "refused", cpu_error, GetPriorityClass(GetCurrentProcess())); + return true; + }(); + (void)background; + if (x2w_local::env_on("X2W_D3D12_DRED")) { + // LOCAL: device-removed extended data (breadcrumbs and page fault), reported by check_device. + ID3D12DeviceRemovedExtendedDataSettings* dred = nullptr; + if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&dred)))) { + dred->SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + dred->SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + dred->Release(); + log("x2w-d3d12 DRED enabled"); + } + } ID3D12Device* device = nullptr; const HRESULT hr = kind_for(iid) == device_kind || iid == __uuidof(IUnknown) ? D3D12CreateDevice(adapter ? reinterpret_cast<IUnknown*>(unwrap(reinterpret_cast<u64>(adapter))) : nullptr, diff --git a/src/startup_stubs/d3d12_xs_traps.cpp b/src/startup_stubs/d3d12_xs_traps.cpp new file mode 100644 index 0000000000..2bb6c57d73 --- /dev/null +++ b/src/startup_stubs/d3d12_xs_traps.cpp @@ -0,0 +1,7 @@ +// Trap exports added to the desktop d3d12_xs.dll. +// Every export traps; see trap.h. Local scaffolding, not an ABI claim. +#define X2W_TRAP_MODULE "d3d12_xs.dll" +#define X2W_TRAP_MODULE_ID 7 +#include "startup_stubs/trap.h" + +X2W_TRAP_EXPORT(0, D3D12ConfigureVirtualMemoryX) diff --git a/src/startup_stubs/derived_blend.h b/src/startup_stubs/derived_blend.h index faced7f24d..97afe075e6 100644 --- a/src/startup_stubs/derived_blend.h +++ b/src/startup_stubs/derived_blend.h @@ -1,5 +1,7 @@ #pragma once +#include "pipeline_state_decode.h" + #include <d3d12.h> #include <cstddef> #include <cstdint> @@ -13,16 +15,11 @@ static_assert(record_size == 0x14c); inline bool last_blend(const unsigned char* records, std::size_t bytes, D3D12_BLEND_DESC& blend, std::size_t& offset) { - if (!records || bytes % record_size) return false; - for (std::size_t end = bytes; end; end -= record_size) { - const std::size_t at = end - record_size; - std::uint32_t tag; - std::memcpy(&tag, records + at, sizeof(tag)); - if (tag != 2) continue; - offset = at + sizeof(tag); - std::memcpy(&blend, records + offset, sizeof(blend)); - return true; - } - return false; + // The record walk is shared with the other parts (pipeline_state_decode.h). + const std::size_t at = x2w_pipeline_state::last_part(records, bytes, x2w_pipeline_state::part_blend); + if (at == SIZE_MAX) return false; + offset = at; + std::memcpy(&blend, records + offset, sizeof(blend)); + return true; } } // namespace x2w_derived_blend diff --git a/src/startup_stubs/draw_bmp.h b/src/startup_stubs/draw_bmp.h index deba981cb3..dfef6c46c8 100644 --- a/src/startup_stubs/draw_bmp.h +++ b/src/startup_stubs/draw_bmp.h @@ -2,7 +2,9 @@ #include <dxgiformat.h> #include <windows.h> +#include <DirectXPackedVector.h> #include <cstdint> +#include <cstring> #include <cstdio> #include <vector> @@ -14,13 +16,41 @@ inline bool supported(DXGI_FORMAT format) || format == DXGI_FORMAT_B8G8R8A8_UNORM || format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; } +inline bool hdr(DXGI_FORMAT format) +{ + return format == DXGI_FORMAT_R16G16B16A16_FLOAT || format == DXGI_FORMAT_R11G11B10_FLOAT || format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP; +} + +inline bool trace_supported(DXGI_FORMAT format) +{ + return supported(format) || hdr(format) || format == DXGI_FORMAT_R16G16_FLOAT; +} + +// A fixed exposure for diagnostic images across frames. Preserve the original +// float values in the trace's raw sample grid. Negative values and NaNs go black. +inline unsigned char display_float(float value) +{ + if (!(value > 0)) return 0; + return static_cast<unsigned char>(255.f * (1.f - 1.f / (1.f + value)) + 0.5f); +} + +// Signed two-channel data: zero is mid-gray, +/-1 use half the available +// contrast, larger magnitudes approach the corresponding endpoint. +inline unsigned char display_signed(float value) +{ + if (value > 0) return static_cast<unsigned char>(128.f + 127.f * (1.f - 1.f / (1.f + value)) + 0.5f); + if (value < 0) return static_cast<unsigned char>(128.f / (1.f - value) + 0.5f); + return 128; +} + // D3D12 copy footprints include row padding. BMP input here starts at the footprint offset. inline bool write(FILE* file, const unsigned char* pixels, UINT width, UINT height, UINT row_pitch, DXGI_FORMAT format) { const std::uint64_t stride = std::uint64_t{width} * 4; constexpr DWORD header_bytes = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); - if (!file || !pixels || !supported(format) || !width || !height || stride > row_pitch || + const UINT pixel_bytes = format == DXGI_FORMAT_R16G16B16A16_FLOAT ? 8u : 4u; + if (!file || !pixels || !trace_supported(format) || !width || !height || std::uint64_t{width} * pixel_bytes > row_pitch || stride * height > MAXDWORD - header_bytes) return false; BITMAPFILEHEADER header{}; @@ -42,6 +72,38 @@ inline bool write(FILE* file, const unsigned char* pixels, UINT width, UINT heig for (UINT y = height; y > 0; --y) { const auto* source = pixels + size_t{y - 1} * row_pitch; for (size_t x = 0; x < row.size(); x += 4) { + if (format == DXGI_FORMAT_R16G16_FLOAT) { + using namespace DirectX::PackedVector; + HALF channels[2]; + std::memcpy(channels, source + x, sizeof(channels)); + row[x] = 128; + row[x + 1] = display_signed(XMConvertHalfToFloat(channels[1])); + row[x + 2] = display_signed(XMConvertHalfToFloat(channels[0])); + row[x + 3] = 255; + continue; + } + if (hdr(format)) { + DirectX::XMFLOAT3 rgb{}; + using namespace DirectX::PackedVector; + if (pixel_bytes == 8) { + HALF channels[4]; + std::memcpy(channels, source + 2 * x, sizeof(channels)); + rgb = {XMConvertHalfToFloat(channels[0]), XMConvertHalfToFloat(channels[1]), XMConvertHalfToFloat(channels[2])}; + } else if (format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) { + XMFLOAT3SE packed; + std::memcpy(&packed, source + x, sizeof(packed)); + DirectX::XMStoreFloat3(&rgb, XMLoadFloat3SE(&packed)); + } else { + XMFLOAT3PK packed; + std::memcpy(&packed, source + x, sizeof(packed)); + DirectX::XMStoreFloat3(&rgb, XMLoadFloat3PK(&packed)); + } + row[x] = display_float(rgb.z); + row[x + 1] = display_float(rgb.y); + row[x + 2] = display_float(rgb.x); + row[x + 3] = 255; + continue; + } row[x] = source[x + (rgba ? 2 : 0)]; row[x + 1] = source[x + 1]; row[x + 2] = source[x + (rgba ? 0 : 2)]; diff --git a/src/startup_stubs/draw_input_dump.inl b/src/startup_stubs/draw_input_dump.inl new file mode 100644 index 0000000000..2b551aec3c --- /dev/null +++ b/src/startup_stubs/draw_input_dump.inl @@ -0,0 +1,693 @@ +// LOCAL (lt-lead probe, opt-in; nothing changes while X2W_DRAW_DUMP_INPUTS is unset). Included by d3d12_draw.inl just +// before draw_translated. Not related to X2W_DRAW_DUMP_FRAME / X2W_DRAW_DUMP_DIR (the per-frame target-0 bitmaps). +// +// X2W_DRAW_DUMP_INPUTS=<key hex>[:<occurrence>][,<key>[:<occurrence>]...] (up to 8 entries; "," ";" or " " between +// them; "*" for a key matches every key, for tests): the occurrence-th translated draw (default 1) of the key. Draws +// are counted per key (entries of the same key share one count, so k:1,k:2 are the first and second draw of k) over the +// run from present X2W_DRAW_DUMP_INPUTS_FROM_FRAME (default 0), in any frame (no traced frame needed). Each entry is +// dumped once. A draw that is counted but then not issued (a refusal after the count, or skipped index data) is +// uncounted again, so the next draw of the key takes its place. Indirect and mesh draws are never selected or counted; +// the first indirect one of a listed key logs a line. A listed key whose draws are refused before the count (no +// desktop pipeline, heap or texture refusals ...) logs its first refusal reason once ("x2w-dddump <key>: draw not +// issued (first refusal of this key): <why>"); a pipeline with no translation record at all is logged by the runtime's +// own "no translation for pipeline <key>" line. +// For the selected draw the runtime writes: +// - the draw arguments, the vertex window the draw copies (vertex_first, vertex_count), the entry values with their +// kinds, the list's root constants and root descriptor addresses, viewport 0, the bound targets and depth view; +// - the index range the draw reads (CPU bytes at record time, the same bytes the draw copies); +// - each srv buffer (vertex streams, root srvs, table buffers): the range as bound, CPU bytes at record time (at most +// X2W_DRAW_DUMP_INPUTS_MAX_MIB MiB, default 16), with how it was bound (copied, in place, null, ...). An in-place +// binding is read by the GPU later, when the list runs: the dump is what the CPU saw at record time; +// - each srv texture: a GPU copy of mip 0 / slice 0 just BEFORE the draw. The whole subresource when that is at most +// X2W_DRAW_DUMP_INPUTS_FULL_MIB MiB (default 4), else the box X2W_DRAW_DUMP_INPUTS_BOX=x,y,w,h (default 64x64 at +// the centre, aligned to 4). Depth resources only whole (up to X2W_DRAW_DUMP_INPUTS_DEPTH_MIB, default 32); +// - uav textures: copies before and after the draw; +// - every bound render target: a copy BEFORE and AFTER the draw (same size rules), and the depth target after it; +// - heap draws (`heap 1`): the title view heap's descriptor bytes (CPU, at most 4 MiB) and one line per view-token +// slot (view id, kind, resource, dimensions) for the first 16384 slots. The descriptors a heap shader indexes are +// computed on the GPU, so their textures and buffers are not followed by default: X2W_DRAW_DUMP_INPUTS_HEAP=<i>,<j>.. +// (decimal slot numbers, up to 32) follows those slots: a texture slot is copied like an srv texture, a buffer slot +// (view token or hardware descriptor) is written as CPU bytes. The per-view info buffer (vinfo) is GPU-built and is +// not dumped. +// Files go to X2W_DRAW_DUMP_INPUTS_DIR, else the folder of X2W_TRAP_LOG, else the current folder: +// dddump_<key>_o<occurrence>_f<frame>_p<process id>.txt index, one line per item (see lt_work/dddump_read.py) +// dddump_<key>_o<occurrence>_f<frame>_p<process id>_<name>.bin +// A texture is copied only when its state is known: moved by this list, or untouched by it (COMMON) after an upload or +// GPU write filled it. It is restored after the copy. Otherwise the index says "skipped: not moved by this list and +// not uploaded or written yet" (for example a followed heap texture that was never uploaded). +// Texture files hold tightly packed rows (row pitch removed). GPU copies are read back at a later present once a marker +// copied at the end of the same command list has arrived and two more presents have passed (or at once through the test +// export x2w_draw_dump_inputs_test(1), after the caller waited for the list). +namespace dd_dump { + +inline unsigned env_number(const char* name, unsigned fallback) +{ + char value[32]{}; + return GetEnvironmentVariableA(name, value, sizeof(value)) ? static_cast<unsigned>(std::strtoul(value, nullptr, 10)) : fallback; +} + +constexpr u64 any_key = ~0ull; +struct Entry { + u64 key = 0; // any_key: "*", every key + LONG occurrence = 1; + unsigned counter = 0; // index into Selection::counters (one per distinct key) + bool done = false; +}; +struct Counter { + u64 key = 0; + LONG seen = 0; // draws of this key counted so far (issued, or in flight) + bool announced = false, indirect_noted = false, refusal_noted = false; +}; +struct Selection { + Entry entries[8]; + unsigned count = 0; + Counter counters[8]; + unsigned counter_count = 0; + LONG from_frame = 0; + std::uint32_t heap_slots[32]{}; + unsigned heap_count = 0; +}; +inline std::mutex& lock() +{ + static std::mutex m; + return m; +} +inline Selection& selection() +{ + static Selection s = [] { + Selection out; + char value[8 * 24 + 16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_DRAW_DUMP_INPUTS", value, sizeof(value)); + if (!n || n >= sizeof(value)) return out; + for (char* p = value; *p && out.count < 8;) { + while (*p == ',' || *p == ';' || *p == ' ') ++p; + char* end = nullptr; + u64 key = 0; + if (*p == '*') { // any key (for tests: the first translated draw of whatever key comes) + key = any_key; + end = p + 1; + } else { + key = _strtoui64(p, &end, 16); + } + if (end == p) break; + p = end; + LONG occurrence = 1; + if (*p == ':') { + occurrence = std::strtol(p + 1, &end, 10); + p = end; + } + if (!key) continue; + unsigned c = 0; + while (c < out.counter_count && out.counters[c].key != key) ++c; + if (c == out.counter_count) out.counters[out.counter_count++].key = key; + out.entries[out.count++] = Entry{key, occurrence < 1 ? 1 : occurrence, c}; + } + out.from_frame = static_cast<LONG>(env_number("X2W_DRAW_DUMP_INPUTS_FROM_FRAME", 0)); + char slots[32 * 12]{}; + if (GetEnvironmentVariableA("X2W_DRAW_DUMP_INPUTS_HEAP", slots, sizeof(slots))) + for (char* p = slots; *p && out.heap_count < 32;) { + while (*p == ',' || *p == ';' || *p == ' ') ++p; + char* end = nullptr; + const unsigned long slot = std::strtoul(p, &end, 10); + if (end == p) break; + out.heap_slots[out.heap_count++] = static_cast<std::uint32_t>(slot); + p = end; + } + for (unsigned i = 0; i < out.count; ++i) + log("x2w-dddump X2W_DRAW_DUMP_INPUTS: key %016llx occurrence %ld (from frame %ld, %u heap slots followed)", + static_cast<unsigned long long>(out.entries[i].key), out.entries[i].occurrence, out.from_frame, out.heap_count); + return out; + }(); + return s; +} +inline bool on() { return selection().count != 0; } + +inline std::string out_dir() +{ + char path[MAX_PATH]{}; + DWORD n = GetEnvironmentVariableA("X2W_DRAW_DUMP_INPUTS_DIR", path, MAX_PATH); + if (n && n < MAX_PATH) return std::string(path, n); + n = GetEnvironmentVariableA("X2W_TRAP_LOG", path, MAX_PATH); + if (n && n < MAX_PATH) { + std::string s(path, n); + const auto cut = s.find_last_of("\\/"); + return cut == std::string::npos ? std::string(".") : s.substr(0, cut); + } + return "."; +} + +struct Copy { + std::string name, line; + Microsoft::WRL::ComPtr<ID3D12Resource> readback; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT rows = 0; + UINT64 row_bytes = 0; +}; +struct Pending { + u64 key = 0; + std::string stem; + std::vector<Copy> copies; + std::vector<std::string> lines; // record-time lines (CPU files already written) + Microsoft::WRL::ComPtr<ID3D12Resource> marker_upload, marker_readback; + std::uint32_t magic[4]{}; + int seen = -1; + int waited = 0; + bool active = false; +}; +inline std::vector<Pending>& pending() +{ + static std::vector<Pending> p; + return p; +} + +// The title view heap a heap draw indexes (the same choice as draw_title_heap, d3d12_draw.inl). +inline bool title_heap(const Pass& pass, u64* address, u64* bytes) +{ + *address = *bytes = 0; + if (pass.source_view_heap) { + AcquireSRWLockShared(¬e_lock); + for (const HeapInfo& h : heap_infos()) + if (h.wrapper == pass.source_view_heap && h.title_cpu) { + *address = h.title_cpu; + *bytes = u64{h.logical_count} * h.increment; + } + ReleaseSRWLockShared(¬e_lock); + } + return *address || title_view_heap(pass, address, bytes); +} + +// A view record's resource, only while it is a live resource wrapper (the same test upload_heap_textures applies). +inline Wrapper* live(u64 title_resource) +{ + Wrapper* w = title_resource ? as_wrapper(reinterpret_cast<const void*>(title_resource)) : nullptr; + if (!w || w != reinterpret_cast<Wrapper*>(title_resource) || w->own().kind != resource_kind || !w->own().real) return nullptr; + return InterlockedCompareExchange(&w->own().refs, 0, 0) > 0 ? w : nullptr; +} + +inline bool view_record(std::uint32_t id, ViewRecord& out) +{ + AcquireSRWLockShared(¬e_lock); + const bool known = id < view_records().size(); + if (known) out = view_records()[id]; + ReleaseSRWLockShared(¬e_lock); + return known; +} + +// One selected draw, from the binding loop to the draw. Inactive (and free) for every other draw. +class Draw { +public: + Draw(Wrapper* self, u64 key, bool indirect, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance) + : self_(self), key_(key) + { + if (!key || !on() || frame_number < selection().from_frame) return; + std::lock_guard<std::mutex> guard(lock()); + Selection& s = selection(); + for (unsigned c = 0; c < s.counter_count; ++c) { + Counter& k = s.counters[c]; + if (k.key != key && k.key != any_key) continue; + if (indirect) { + if (!k.indirect_noted) log("x2w-dddump %016llx: an indirect draw of this key is not dumped (plain draws only)", static_cast<unsigned long long>(key)); + k.indirect_noted = true; + continue; + } + if (!k.announced) log("x2w-dddump %016llx: first draw of this key seen (frame %ld)", static_cast<unsigned long long>(key), frame_number); + k.announced = true; + ++k.seen; + counted_ |= 1u << c; + } + for (unsigned i = 0; i < s.count && counted_; ++i) { + Entry& e = s.entries[i]; + if (!e.done && (counted_ & (1u << e.counter)) && s.counters[e.counter].seen == e.occurrence) { + entry_ = &e; + break; + } + } + if (!entry_) return; + active_ = true; + frame_ = frame_number + 1; // the frame being recorded (presented next) + char stem[96]; + std::snprintf(stem, sizeof(stem), "dddump_%016llx_o%ld_f%ld_p%lu", static_cast<unsigned long long>(key), entry_->occurrence, frame_, + static_cast<unsigned long>(GetCurrentProcessId())); + stem_ = stem; + dir_ = out_dir(); + line("draw %s count %u instances %u start %u base_vertex %d start_instance %u", indexed ? "indexed" : "plain", count, instances, start, + base_vertex, start_instance); + log("x2w-dddump %016llx: occurrence %ld selected (frame %ld)", static_cast<unsigned long long>(key), entry_->occurrence, frame_); + } + ~Draw() + { + if (!counted_ || issued_) return; + std::lock_guard<std::mutex> guard(lock()); + Selection& s = selection(); + for (unsigned c = 0; c < s.counter_count; ++c) + if (counted_ & (1u << c)) s.counters[c].seen -= 1; // not issued: the next draw of this key takes its place + if (active_) + log("x2w-dddump %016llx: selected draw was not issued (%s); re-armed", static_cast<unsigned long long>(key_), why_ ? why_ : "refused"); + } + explicit operator bool() const { return active_; } + void not_issued(const char* why) { why_ = why; } + + void geometry(INT vertex_first, UINT vertex_count, bool indexed, u64 index_address, std::size_t index_bytes, UINT index_size, bool indices_ok, + UINT topology, const Pass& pass) + { + if (!active_) return; + line("vertices first %d count %u topology 0x%x", vertex_first, vertex_count, topology); + const D3D12_VIEWPORT& v = pass.viewport0; + line("viewport0 %.9g %.9g %.9g %.9g depth %.9g %.9g (title set: viewport %d scissor %d)", v.TopLeftX, v.TopLeftY, v.Width, v.Height, + v.MinDepth, v.MaxDepth, pass.viewport_set ? 1 : 0, pass.scissor_set ? 1 : 0); + for (UINT k = 0; k < 8; ++k) + if (pass.vb[k].BufferLocation) + line("vb %u title 0x%llx bytes %u stride %u", k, static_cast<unsigned long long>(pass.vb[k].BufferLocation), pass.vb[k].SizeInBytes, + pass.vb[k].StrideInBytes); + if (!indexed) return; + line("ib title 0x%llx bytes %u format %d", static_cast<unsigned long long>(pass.ib.BufferLocation), pass.ib.SizeInBytes, static_cast<int>(pass.ib.Format)); + write_cpu("indices", indices_ok ? index_address : 0, index_bytes, "indices read by the draw (index size %u)", index_size); + } + + // A texture srv as bound (texture null: bound null). how: "bound", "null", ... + void srv_texture(UINT i, int kind, u64 entry, const std::uint32_t (&words)[8], ID3D12Resource* texture, DXGI_FORMAT view_format, const char* how) + { + if (!active_) return; + char label[48]; + std::snprintf(label, sizeof(label), "srv%u", i); + textures_.push_back(Tex{label, texture, false}); + line("srv %u texture kind %d entry 0x%llx words %08x %08x %08x %08x %08x %08x %08x %08x view_format %d desktop %p: %s", i, kind, + static_cast<unsigned long long>(entry), words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7], + static_cast<int>(view_format), static_cast<void*>(texture), how); + } + // A buffer srv: the range as computed, before the binding chooses how (then bound()). + void srv_buffer(UINT i, int source, int a, int b, u64 entry, const std::uint32_t (&words)[8], u64 address, std::size_t bytes, UINT stride) + { + if (!active_) return; + pending_srv_ = static_cast<int>(i); + std::snprintf(srv_text_, sizeof(srv_text_), + "srv %u buffer source %d(%d,%d) entry 0x%llx words %08x %08x %08x %08x title 0x%llx bytes %zu stride %u", i, source, a, b, + static_cast<unsigned long long>(entry), words[0], words[1], words[2], words[3], static_cast<unsigned long long>(address), bytes, + stride); + srv_address_ = address; + srv_bytes_ = bytes; + } + void bound(UINT i, const char* how, std::size_t bound_bytes) + { + if (!active_ || pending_srv_ != static_cast<int>(i)) return; + pending_srv_ = -1; + char name[32]; + std::snprintf(name, sizeof(name), "srv%u", i); + write_cpu(name, srv_address_, srv_bytes_, "%s: %s, %zu bytes bound", srv_text_, how, bound_bytes); + } + void uav_texture(UINT j, ID3D12Resource* texture) + { + if (!active_) return; + char label[48]; + std::snprintf(label, sizeof(label), "uav%u", j); + textures_.push_back(Tex{label, texture, true}); + line("uav %u texture desktop %p", j, static_cast<void*>(texture)); + } + void uav_buffer(UINT j, std::uint32_t base, std::uint32_t stride, std::uint32_t word3) + { + if (!active_) return; + line("uav %u buffer base-entry 0x%08x stride %u word3 0x%08x (contents not dumped)", j, base, stride, word3); + } + + void values(const Translation& tr, const std::uint32_t* values, const Pass& pass) + { + if (!active_) return; + std::string kinds; + char part[32]; + for (std::size_t i = 0; i < tr.uds.size(); ++i) { + std::snprintf(part, sizeof(part), " %d(%d,%d)=%08x", static_cast<int>(tr.uds[i].kind), tr.uds[i].a, tr.uds[i].b, values[i]); + kinds += part; + } + line("entry %zu values, kind(a,b)=value:%s", tr.uds.size(), kinds.c_str()); + write_mem("entry", values, tr.uds.size() * sizeof(values[0]), "entry values (root parameter 0), u32 each"); + write_mem("root_constants", pass.constants, sizeof(pass.constants), "list root constants [parameter 0-15][word 0-7] u32"); + for (UINT p = 0; p < 16; ++p) + if (pass.root_address[p]) line("root descriptor %u title 0x%llx", p, static_cast<unsigned long long>(pass.root_address[p])); + } + + // Heap draws: the descriptor bytes, the token slots, and the followed slots. + void heap(const Pass& pass) + { + if (!active_) return; + u64 address = 0, bytes = 0; + if (!title_heap(pass, &address, &bytes)) return line("heap: title view heap not reachable"); + const std::size_t want = static_cast<std::size_t>(bytes < (4u << 20) ? bytes : (4u << 20)); + write_cpu("heap", address, want, "title view heap descriptors (32 bytes each), heap 0x%llx bytes %llu", + static_cast<unsigned long long>(address), static_cast<unsigned long long>(bytes)); + const std::size_t readable = address && want ? static_cast<std::size_t>(readable_window(address, want)) : 0; + const std::uint32_t slots = static_cast<std::uint32_t>(readable / 32 < 16384 ? readable / 32 : 16384); + unsigned tokens = 0; + for (std::uint32_t k = 0; k < slots; ++k) { + const auto* d = reinterpret_cast<const std::uint32_t*>(address + u64{k} * 32); + if (d[0] != view_token_magic) continue; + ++tokens; + line("heapslot %u %s", k, describe_token(d[1]).c_str()); + } + line("heap slots scanned %u, view tokens %u", slots, tokens); + const Selection& s = selection(); + for (unsigned f = 0; f < s.heap_count; ++f) follow(address, readable, s.heap_slots[f]); + } + + // GPU copies before the draw (srv / uav textures, every render target). Call just before the draw is recorded. + void before(ID3D12GraphicsCommandList* list, const Pass& pass) + { + if (!active_) return; + for (const Tex& t : textures_) + if (t.texture) copy_texture(list, t.texture, t.label + "_pre", t.label.c_str(), "pre"); + for (UINT k = 0; k < pass.target_count && k < 8; ++k) { + char label[16]; + std::snprintf(label, sizeof(label), "rtv%u", k); + line("rtv %u desktop %p format %d", k, static_cast<void*>(pass.targets[k]), static_cast<int>(pass.target_formats[k])); + if (pass.targets[k]) copy_texture(list, pass.targets[k], std::string(label) + "_pre", label, "pre"); + } + line("dsv desktop %p format %d read_only %d", static_cast<void*>(pass.dsv_resource), static_cast<int>(pass.dsv_format), pass.dsv_read_only ? 1 : 0); + } + // After the draw: render targets, depth target, uav textures; then the marker. Only when the draw was issued. + void after(ID3D12GraphicsCommandList* list, const Pass& pass) + { + issued_ = true; + if (!active_) return; + for (UINT k = 0; k < pass.target_count && k < 8; ++k) { + char label[16]; + std::snprintf(label, sizeof(label), "rtv%u", k); + if (pass.targets[k]) copy_texture(list, pass.targets[k], std::string(label) + "_post", label, "post"); + } + if (pass.dsv_resource) copy_texture(list, pass.dsv_resource, "dsv_post", "dsv", "post"); + for (const Tex& t : textures_) + if (t.texture && t.uav) copy_texture(list, t.texture, t.label + "_post", t.label.c_str(), "post"); + finish(list); + } + +private: + struct Tex { + std::string label; + ID3D12Resource* texture; + bool uav; + }; + + void line(const char* format, ...) + { + char text[1024]; + va_list args; + va_start(args, format); + std::vsnprintf(text, sizeof(text), format, args); + va_end(args); + lines_.emplace_back(text); + } + + void write_mem(const char* name, const void* data, std::size_t bytes, const char* note) + { + const std::string file = stem_ + "_" + name + ".bin"; + bool ok = false; + if (std::FILE* f = std::fopen((dir_ + "\\" + file).c_str(), "wb")) { + ok = !bytes || std::fwrite(data, 1, bytes, f) == bytes; + ok = std::fclose(f) == 0 && ok; + } + line("file %s bytes %zu%s: %s", file.c_str(), bytes, ok ? "" : " (WRITE FAILED)", note); + } + // CPU bytes of a title range now, cut to the readable part and to X2W_DRAW_DUMP_INPUTS_MAX_MIB. + void write_cpu(const char* name, u64 address, std::size_t bytes, const char* format, ...) + { + char note[1024]; + va_list args; + va_start(args, format); + std::vsnprintf(note, sizeof(note), format, args); + va_end(args); + static const std::size_t cap = std::size_t{env_number("X2W_DRAW_DUMP_INPUTS_MAX_MIB", 16)} << 20; + const std::size_t wanted = bytes < cap ? bytes : cap; + const std::size_t have = address && wanted ? static_cast<std::size_t>(readable_window(address, wanted)) : 0; + if (!have) return line("file - bytes 0 of %zu (%s): %s", bytes, address ? "not readable" : "no address", note); + const std::string file = stem_ + "_" + name + ".bin"; + bool ok = false; + if (std::FILE* f = std::fopen((dir_ + "\\" + file).c_str(), "wb")) { + ok = std::fwrite(reinterpret_cast<const void*>(address), 1, have, f) == have; + ok = std::fclose(f) == 0 && ok; + } + line("file %s bytes %zu of %zu%s%s: %s", file.c_str(), have, bytes, have < bytes ? " (cut)" : "", ok ? "" : " (WRITE FAILED)", note); + } + + std::string describe_token(std::uint32_t id) + { + ViewRecord r{}; + char text[256]; + if (!view_record(id, r)) { + std::snprintf(text, sizeof(text), "view %u unknown", id); + return text; + } + Wrapper* w = live(r.resource); + const bool res = w != nullptr; + ID3D12Resource* real = res ? static_cast<ID3D12Resource*>(w->own().real) : nullptr; + const D3D12_RESOURCE_DESC d = real ? real->GetDesc() : D3D12_RESOURCE_DESC{}; + std::snprintf(text, sizeof(text), "view %u slot %u resource 0x%llx title 0x%llx desktop %p dim %d %llux%ux%u fmt %d desc_bytes %u", id, r.slot, + static_cast<unsigned long long>(r.resource), res ? static_cast<unsigned long long>(reinterpret_cast<u64>(w->own().title_memory)) : 0ull, + static_cast<void*>(real), static_cast<int>(d.Dimension), static_cast<unsigned long long>(d.Width), d.Height, d.DepthOrArraySize, + static_cast<int>(d.Format), r.desc_bytes); + return text; + } + + void follow(u64 heap, std::size_t readable, std::uint32_t slot) + { + char name[32]; + std::snprintf(name, sizeof(name), "heap%u", slot); + if (u64{slot} * 32 + 32 > readable) return line("follow heap %u: outside the readable heap", slot); + std::uint32_t d[8]; + std::memcpy(d, reinterpret_cast<const void*>(heap + u64{slot} * 32), 32); + if (d[0] != view_token_magic) { + const u64 at = d[0] | (static_cast<u64>(d[1] & 0xffff) << 32); + const UINT stride = (d[1] >> 16) & 0x3fff; + return write_cpu(name, at, std::size_t{stride ? stride : 1u} * d[2], "follow heap %u hardware words %08x %08x %08x %08x", slot, d[0], d[1], + d[2], d[3]); + } + ViewRecord r{}; + if (!view_record(d[1], r)) return line("follow heap %u: view %u unknown", slot, d[1]); + Wrapper* w = live(r.resource); + if (r.resource && !w) return line("follow heap %u: view %u names a released or unknown resource", slot, d[1]); + if (r.slot == 17 && r.desc_bytes >= 12) { + u64 at = 0; + std::uint32_t size = 0; + std::memcpy(&at, r.desc, 8); + std::memcpy(&size, r.desc + 8, 4); + return write_cpu(name, at, size, "follow heap %u constant buffer view %u", slot, d[1]); + } + if (r.slot == 18 && r.desc_bytes >= 40) { + D3D12_SHADER_RESOURCE_VIEW_DESC v; + std::memcpy(&v, r.desc, 40); + if (v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { + if (!w || !w->own().title_memory) return line("follow heap %u: buffer view %u without title memory", slot, d[1]); + const bool typed = !v.Buffer.StructureByteStride && v.Format != DXGI_FORMAT_R32_TYPELESS; + const UINT element = v.Buffer.StructureByteStride ? v.Buffer.StructureByteStride : typed ? x2w_startup::typed_buffer_format_bytes(v.Format) : 4; + return write_cpu(name, reinterpret_cast<u64>(w->own().title_memory) + v.Buffer.FirstElement * element, + std::size_t{v.Buffer.NumElements} * element, "follow heap %u buffer view %u element %u", slot, d[1], element); + } + ID3D12Resource* texture = sampled_address_texture(w); + line("follow heap %u texture view %u dim %d fmt %d desktop %p", slot, d[1], static_cast<int>(v.ViewDimension), static_cast<int>(v.Format), + static_cast<void*>(texture)); + if (texture) textures_.push_back(Tex{name, texture, false}); + return; + } + line("follow heap %u: view %u slot %u not followed", slot, d[1], r.slot); + } + + void copy_texture(ID3D12GraphicsCommandList* list, ID3D12Resource* texture, const std::string& file_label, const char* what, const char* phase) + { + auto* device = device_of(the_device); + const D3D12_RESOURCE_DESC rd = texture->GetDesc(); + if (rd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return line("tex %s %s skipped: a buffer", what, phase); + if (rd.SampleDesc.Count != 1) return line("tex %s %s skipped: multisampled (%u samples)", what, phase, rd.SampleDesc.Count); + const bool depth = (rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) != 0; + D3D12_FEATURE_DATA_FORMAT_INFO info{rd.Format, 1}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, &info, sizeof(info)))) info.PlaneCount = 1; + const UINT per_plane = rd.MipLevels * (rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1u : rd.DepthOrArraySize); + static const UINT64 full_mib = env_number("X2W_DRAW_DUMP_INPUTS_FULL_MIB", 4), depth_mib = env_number("X2W_DRAW_DUMP_INPUTS_DEPTH_MIB", 32); + const UINT64 full_limit = (depth ? depth_mib : full_mib) << 20; + // The state this list holds the texture in now, restored after the copy. A texture this list has not moved is in + // COMMON (lists return what they moved to COMMON at Close), but it is copied only once something filled it: the + // upload record says the title memory was staged into it or a list wrote it. Any other untracked texture is + // skipped (a heap texture never uploaded, copied as if in COMMON, made Close fail with E_INVALIDARG). + D3D12_RESOURCE_STATES before = D3D12_RESOURCE_STATE_COMMON; + bool tracked = false; + if (const auto* entry = pass_of(self_).states.find(texture)) before = entry->depth, tracked = true; + if (!tracked) { + const auto found = texture_uploads().find(texture); + const bool filled = found != texture_uploads().end() && (found->second.staged || found->second.gpu_written) && !found->second.pending_list; + if (!filled) + return line("tex %s %s desktop %p skipped: not moved by this list and not uploaded or written yet", what, phase, static_cast<void*>(texture)); + } + for (UINT plane = 0; plane < (info.PlaneCount ? info.PlaneCount : 1u); ++plane) { + const UINT sub = plane * per_plane; + Copy c; + UINT64 total = 0; + device->GetCopyableFootprints(&rd, sub, 1, 0, &c.footprint, &c.rows, &c.row_bytes, &total); + D3D12_BOX box{0, 0, 0, static_cast<UINT>(rd.Width), rd.Height, c.footprint.Footprint.Depth}; + const bool whole = total <= full_limit; + if (!whole) { + if (depth) return line("tex %s %s skipped: depth resource above X2W_DRAW_DUMP_INPUTS_DEPTH_MIB (D3D12 copies depth only whole)", what, phase); + unsigned bx = 0, by = 0, bw = 64, bh = 64; + char value[64]{}; + const bool given = GetEnvironmentVariableA("X2W_DRAW_DUMP_INPUTS_BOX", value, sizeof(value)) && + std::sscanf(value, "%u,%u,%u,%u", &bx, &by, &bw, &bh) == 4; + const UINT w = static_cast<UINT>(rd.Width), h = rd.Height; + if (!given) bx = w > 64 ? (w / 2 - 32) : 0, by = h > 64 ? (h / 2 - 32) : 0; + bx &= ~3u, by &= ~3u, bw = (bw + 3) & ~3u, bh = (bh + 3) & ~3u; + if (bx >= w || by >= h) return line("tex %s %s skipped: box outside the texture", what, phase); + if (bx + bw > w) bw = w - bx; + if (by + bh > h) bh = h - by; + D3D12_RESOURCE_DESC part = rd; + part.Width = bw, part.Height = bh, part.MipLevels = 1, part.DepthOrArraySize = 1; + device->GetCopyableFootprints(&part, 0, 1, 0, &c.footprint, &c.rows, &c.row_bytes, &total); + box = D3D12_BOX{bx, by, 0, bx + bw, by + bh, 1}; + } + c.readback = cx_dump::buffer(D3D12_HEAP_TYPE_READBACK, total); + if (!c.readback) return line("tex %s %s skipped: readback allocation failed", what, phase); + char name[160], text[512]; + if (info.PlaneCount > 1) std::snprintf(name, sizeof(name), "%s_%s_p%u.bin", stem_.c_str(), file_label.c_str(), plane); + else std::snprintf(name, sizeof(name), "%s_%s.bin", stem_.c_str(), file_label.c_str()); + std::snprintf(text, sizeof(text), + "tex %s %s desktop %p dim %d %llux%ux%u mips %u fmt %d flags 0x%x plane %u box %u,%u %ux%u row_bytes %llu rows %u file %s", what, + phase, static_cast<void*>(texture), static_cast<int>(rd.Dimension), static_cast<unsigned long long>(rd.Width), rd.Height, + rd.DepthOrArraySize, rd.MipLevels, static_cast<int>(rd.Format), static_cast<unsigned>(rd.Flags), plane, box.left, box.top, + box.right - box.left, box.bottom - box.top, static_cast<unsigned long long>(c.row_bytes), c.rows, name); + c.name = name; + c.line = text; + require_state(self_, texture, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION to{c.readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = c.footprint; + const D3D12_TEXTURE_COPY_LOCATION from{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {sub}}; + list->CopyTextureRegion(&to, 0, 0, 0, &from, whole ? nullptr : &box); + require_state(self_, texture, before); + copies_.push_back(std::move(c)); + } + } + + void finish(ID3D12GraphicsCommandList* list) + { + finished_ = true; + std::lock_guard<std::mutex> guard(lock()); + entry_->done = true; + Pending p; + p.key = key_; + p.stem = stem_; + p.copies = std::move(copies_); + p.lines = std::move(lines_); + p.marker_upload = cx_dump::buffer(D3D12_HEAP_TYPE_UPLOAD, 16); + p.marker_readback = cx_dump::buffer(D3D12_HEAP_TYPE_READBACK, 16); + p.magic[0] = 0x504d4444; // "DDMP" + p.magic[1] = static_cast<std::uint32_t>(key_); + p.magic[2] = static_cast<std::uint32_t>(frame_); + p.magic[3] = static_cast<std::uint32_t>(GetTickCount()) ^ static_cast<std::uint32_t>(pending().size()); + void* memory = nullptr; + if (!p.marker_upload || !p.marker_readback || FAILED(p.marker_upload->Map(0, nullptr, &memory))) { + log("x2w-dddump %016llx: marker buffers failed; nothing is read back", static_cast<unsigned long long>(key_)); + return; + } + std::memcpy(memory, p.magic, 16); + p.marker_upload->Unmap(0, nullptr); + list->CopyBufferRegion(p.marker_readback.Get(), 0, p.marker_upload.Get(), 0, 16); + p.active = true; + log("x2w-dddump %016llx: %zu texture copies and %zu lines recorded; read back at a later present", static_cast<unsigned long long>(key_), + p.copies.size(), p.lines.size()); + pending().push_back(std::move(p)); + } + + Wrapper* self_; + u64 key_; + Entry* entry_ = nullptr; + unsigned counted_ = 0; // bits: the counters this draw incremented + bool active_ = false, finished_ = false, issued_ = false; + const char* why_ = nullptr; + LONG frame_ = 0; + std::string stem_, dir_; + std::vector<std::string> lines_; + std::vector<Tex> textures_; + std::vector<Copy> copies_; + int pending_srv_ = -1; + char srv_text_[400]{}; + u64 srv_address_ = 0; + std::size_t srv_bytes_ = 0; +}; + +// Each present (and the test export): write a dump once its marker has arrived and, unless `now`, two more presents +// have passed. Returns the number of dumps written. +inline int poll(bool now = false) +{ + if (!on()) return 0; + std::lock_guard<std::mutex> guard(lock()); + int written = 0; + const std::string dir = out_dir(); + for (auto it = pending().begin(); it != pending().end();) { + Pending& p = *it; + if (p.seen < 0) { + void* memory = nullptr; + const D3D12_RANGE read{0, 16}, none{}; + if (SUCCEEDED(p.marker_readback->Map(0, &read, &memory))) { + if (!std::memcmp(memory, p.magic, 16)) p.seen = 0; + p.marker_readback->Unmap(0, &none); + } + if (p.seen < 0) { + if (!now && ++p.waited > 600) { + log("x2w-dddump %016llx: marker never arrived (list not executed?); dump dropped", static_cast<unsigned long long>(p.key)); + it = pending().erase(it); + } else { + ++it; + } + continue; + } + } + if (!now && ++p.seen < 2) { + ++it; + continue; + } + std::FILE* index = std::fopen((dir + "\\" + p.stem + ".txt").c_str(), "w"); + if (index) std::fprintf(index, "x2w-dddump 1 %s\n", p.stem.c_str()); + for (const auto& l : p.lines) + if (index) std::fprintf(index, "%s\n", l.c_str()); + for (Copy& c : p.copies) { + void* memory = nullptr; + // The last row ends at row_bytes, not at a full pitch (the buffer is sized by GetCopyableFootprints). + const UINT64 lines = UINT64{c.rows} * c.footprint.Footprint.Depth; + const D3D12_RANGE read{0, static_cast<SIZE_T>(c.footprint.Offset + (lines ? (lines - 1) * c.footprint.Footprint.RowPitch : 0) + c.row_bytes)}, + none{}; + bool ok = false; + if (SUCCEEDED(c.readback->Map(0, &read, &memory))) { + if (std::FILE* f = std::fopen((dir + "\\" + c.name).c_str(), "wb")) { + const auto* base = static_cast<const unsigned char*>(memory) + c.footprint.Offset; + for (UINT z = 0; z < c.footprint.Footprint.Depth; ++z) + for (UINT y = 0; y < c.rows; ++y) + std::fwrite(base + (UINT64{z} * c.rows + y) * c.footprint.Footprint.RowPitch, 1, static_cast<std::size_t>(c.row_bytes), f); + ok = std::fclose(f) == 0; + } + c.readback->Unmap(0, &none); + } + if (index) std::fprintf(index, "%s%s\n", c.line.c_str(), ok ? "" : " (write failed)"); + } + if (index) std::fclose(index); + log("x2w-dddump %016llx: %zu lines and %zu texture copies written to %s\\%s.*", static_cast<unsigned long long>(p.key), p.lines.size(), + p.copies.size(), dir.c_str(), p.stem.c_str()); + ++written; + it = pending().erase(it); + } + return written; +} + +} // namespace dd_dump + +// From the draw calls (slots 12 and 13) when a translated draw returned false: the first refusal of a listed key is +// logged once (a refusal before the dump hook leaves no other trace in the dump log). +void draw_dump_note_not_drawn(u64 key, const char* why) +{ + if (!key || !dd_dump::on()) return; + std::lock_guard<std::mutex> guard(dd_dump::lock()); + dd_dump::Selection& s = dd_dump::selection(); + for (unsigned c = 0; c < s.counter_count; ++c) { + dd_dump::Counter& k = s.counters[c]; + if (k.key != key || k.refusal_noted) continue; + k.refusal_noted = true; + log("x2w-dddump %016llx: draw not issued (first refusal of this key): %s", static_cast<unsigned long long>(key), why ? why : "draw failed"); + } +} + +// Test export: op 1 writes every dump whose marker has arrived now (the caller waited for its list); returns the count. +extern "C" __declspec(dllexport) int WINAPI x2w_draw_dump_inputs_test(int op) +{ + return op == 1 ? dd_dump::poll(true) : -1; +} diff --git a/src/startup_stubs/dstorage_status_stats.h b/src/startup_stubs/dstorage_status_stats.h new file mode 100644 index 0000000000..91c76c37e8 --- /dev/null +++ b/src/startup_stubs/dstorage_status_stats.h @@ -0,0 +1,220 @@ +// Experimental (docs/startup-runtime.md): how long DirectStorage status entries stay pending, for the +// XCRDAPI stand-in's heartbeat. LOCAL diagnostics; X2W_DSTORAGE_STATUS_STATS=0 turns them off. +// +// Per status array: the QPC time each index's EnqueueStatus happened, completions and their wait +// (EnqueueStatus to the result write) per heartbeat interval, the title's IsComplete polls that found +// the entry pending or complete, the first poller's return address, and two slot-reuse counts: an index +// enqueued again before its previous status was written ("reused"), and a result write for an older +// status landing on an index that a newer EnqueueStatus had set pending again ("stale": IsComplete then +// reports the newer status complete early). The heartbeat lists every index pending for over a second +// with its queue's entry counts, so a stuck status shows as such and a busy wait does not. +#pragma once + +#include <windows.h> + +#include <cstdio> +#include <new> + +namespace x2w_dstorage_stats { + +struct StatusStats { + unsigned capacity = 0; + unsigned serial = 0; + const volatile LONG* results = nullptr; // the array's results (owned by the stand-in) + LONG64* enqueued_at = nullptr; // QPC ticks of the latest EnqueueStatus per index + LONG* enqueued_gen = nullptr; // EnqueueStatus calls per index + LONG* completed_gen = nullptr; // generation of the latest result written per index + void* volatile queue = nullptr; // the queue of the latest EnqueueStatus (opaque here) + void* volatile poller = nullptr; + volatile LONG64 polls_pending = 0, polls_complete = 0; + volatile LONG64 completions = 0, wait_ticks = 0, wait_max = 0; // reset by each report + volatile LONG64 completions_total = 0; + volatile LONG reused = 0, stale = 0; +}; + +inline bool enabled() noexcept +{ + static const bool on = [] { + const DWORD saved = GetLastError(); + char value[4]{}; + const bool off = GetEnvironmentVariableA("X2W_DSTORAGE_STATUS_STATS", value, sizeof(value)) && value[0] == '0'; + SetLastError(saved); + return !off; + }(); + return on; +} + +inline LONG64 now() noexcept +{ + LARGE_INTEGER t{}; + QueryPerformanceCounter(&t); + return t.QuadPart; +} + +inline double ms(LONG64 ticks) noexcept +{ + static const double frequency = [] { + LARGE_INTEGER f{}; + QueryPerformanceFrequency(&f); + return f.QuadPart ? static_cast<double>(f.QuadPart) : 1.0; + }(); + return static_cast<double>(ticks) * 1000.0 / frequency; +} + +constexpr LONG max_arrays = 64; +inline StatusStats* arrays[max_arrays]; +inline volatile LONG array_count = 0; + +// Null when off or out of memory; every other call accepts null. +inline StatusStats* make(unsigned capacity, const volatile LONG* results) noexcept +{ + if (!enabled() || !capacity || !results) return nullptr; + auto* s = new (std::nothrow) StatusStats; + if (!s) return nullptr; + s->capacity = capacity; + s->results = results; + s->enqueued_at = new (std::nothrow) LONG64[capacity](); + s->enqueued_gen = new (std::nothrow) LONG[capacity](); + s->completed_gen = new (std::nothrow) LONG[capacity](); + if (!s->enqueued_at || !s->enqueued_gen || !s->completed_gen) { + delete[] s->enqueued_at; + delete[] s->enqueued_gen; + delete[] s->completed_gen; + delete s; + return nullptr; + } + const LONG slot = InterlockedIncrement(&array_count) - 1; + s->serial = static_cast<unsigned>(slot); + if (slot < max_arrays) arrays[slot] = s; // later arrays are tracked but not reported + return s; +} + +// At EnqueueStatus, before the index is set pending. Returns the entry's generation (0 when off). +inline LONG on_enqueue(StatusStats* s, unsigned index, void* queue) noexcept +{ + if (!s || index >= s->capacity) return 0; + const LONG gen = InterlockedIncrement(&s->enqueued_gen[index]); + if (s->completed_gen[index] != gen - 1) InterlockedIncrement(&s->reused); + s->queue = queue; + InterlockedExchange64(&s->enqueued_at[index], now()); + return gen; +} + +// Right before the result is written (afterwards the title may enqueue the index again). +inline void on_complete(StatusStats* s, unsigned index, LONG gen) noexcept +{ + if (!s || index >= s->capacity || !gen) return; + if (gen != s->enqueued_gen[index]) { + InterlockedIncrement(&s->stale); + return; + } + const LONG64 wait = now() - s->enqueued_at[index]; + InterlockedIncrement64(&s->completions); + InterlockedIncrement64(&s->completions_total); + InterlockedAdd64(&s->wait_ticks, wait); + for (LONG64 seen = s->wait_max; wait > seen;) { + const LONG64 prior = InterlockedCompareExchange64(&s->wait_max, wait, seen); + if (prior == seen) break; + seen = prior; + } + InterlockedExchange(&s->completed_gen[index], gen); +} + +// IsComplete runs at tens of millions of calls per second while the title waits, so the poll counts are +// plain (unlocked) increments on the array's own counters: approximate when several threads poll one +// array or a report resets them mid-increment, but no locked instruction on the title's poll path. +inline void on_poll(StatusStats* s, bool complete, void* caller) noexcept +{ + if (!s) return; + volatile LONG64& polls = complete ? s->polls_complete : s->polls_pending; + polls = polls + 1; + if (!s->poller) InterlockedCompareExchangePointer(&s->poller, caller, nullptr); +} + +inline void module_offset(const void* address, char* out, std::size_t size) noexcept +{ + HMODULE module = nullptr; + char path[MAX_PATH] = "?"; + if (address && GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast<const char*>(address), &module) && module) { + GetModuleFileNameA(module, path, MAX_PATH); + const char* name = path; + for (const char* p = path; *p; ++p) + if (*p == '\\' || *p == '/') name = p + 1; + std::snprintf(out, size, "%s+0x%llx", name, + static_cast<unsigned long long>(static_cast<const char*>(address) - reinterpret_cast<const char*>(module))); + } else { + std::snprintf(out, size, "%p", address); + } +} + +// Heartbeat. `queue_text` describes a queue's entry counts into a buffer (the stand-in's own state). +// `pending_result` is the value an index holds while pending. +template <class Log, class QueueText> +void report(int second, LONG pending_result, Log log, QueueText queue_text) +{ + if (!enabled()) return; + const LONG count = array_count < max_arrays ? array_count : max_arrays; + LONG64 completions = 0, wait_ticks = 0, wait_max = 0, polls_pending = 0, polls_complete = 0; + LONG reused = 0, stale = 0, max_at = -1, active = 0; + char pollers[256] = ""; + int used = 0; + void* seen_pollers[4] = {}; + for (LONG i = 0; i < count; ++i) { + StatusStats* s = arrays[i]; + if (!s) continue; + const LONG64 c = InterlockedExchange64(&s->completions, 0); + const LONG64 t = InterlockedExchange64(&s->wait_ticks, 0); + const LONG64 m = InterlockedExchange64(&s->wait_max, 0); + const LONG64 pp = InterlockedExchange64(&s->polls_pending, 0); + const LONG64 pc = InterlockedExchange64(&s->polls_complete, 0); + if (c || pp || pc) ++active; + completions += c; + wait_ticks += t; + if (m > wait_max) { + wait_max = m; + max_at = i; + } + polls_pending += pp; + polls_complete += pc; + reused += s->reused; + stale += s->stale; + void* poller = s->poller; + bool known = !poller; + for (void*& p : seen_pollers) { + if (p == poller) known = true; + if (!known && !p) { + p = poller; + char where[160]; + module_offset(poller, where, sizeof(where)); + if (used < static_cast<int>(sizeof(pollers)) - 1) + used += std::snprintf(pollers + used, sizeof(pollers) - used, " %s", where); + known = true; + } + } + } + if (completions || polls_pending || polls_complete || reused || stale) + log("x2w-dstorage status %d s: arrays %ld (active %ld), completions %lld, wait mean %.3f ms max %.3f ms (array #%ld); " + "IsComplete polls (approximate) pending %lld complete %lld; reused before complete %ld, stale writes %ld (since start); first pollers:%s", + second, static_cast<long>(array_count), static_cast<long>(active), completions, + completions ? ms(wait_ticks) / static_cast<double>(completions) : 0.0, ms(wait_max), static_cast<long>(max_at), + polls_pending, polls_complete, static_cast<long>(reused), static_cast<long>(stale), used ? pollers : " none"); + int shown = 0; + const LONG64 t = now(); + for (LONG i = 0; i < count && shown < 8; ++i) { + StatusStats* s = arrays[i]; + if (!s) continue; + for (unsigned index = 0; index < s->capacity && shown < 8; ++index) { + if (s->results[index] != pending_result || !s->enqueued_gen[index]) continue; + const double age = ms(t - s->enqueued_at[index]); + if (age < 1000.0) continue; + char queue[160] = ""; + queue_text(s->queue, queue, sizeof(queue)); + log("x2w-dstorage status PENDING array #%ld index %u for %.1f s (enqueued %ld, completed %ld; %s)", static_cast<long>(i), index, + age / 1000.0, static_cast<long>(s->enqueued_gen[index]), static_cast<long>(s->completed_gen[index]), queue); + ++shown; + } + } +} + +} // namespace x2w_dstorage_stats diff --git a/src/startup_stubs/frame_rgb_report.inl b/src/startup_stubs/frame_rgb_report.inl new file mode 100644 index 0000000000..0f2524aa2a --- /dev/null +++ b/src/startup_stubs/frame_rgb_report.inl @@ -0,0 +1,50 @@ +// Both stages sample the same normalized coordinates. Values stay in their native +// encoding (linear half float or normalized display bytes); alpha is counted separately. +void report_frame_rgb(const char* stage, LONG frame, const void* surface, const void* mapped, + const D3D12_RESOURCE_DESC& desc, const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& fp) +{ + using namespace x2w_frame_sample; + Format format; + switch (desc.Format) { + case DXGI_FORMAT_R16G16B16A16_FLOAT: format = Format::rgba16f; break; + case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: format = Format::rgba8; break; + case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: format = Format::bgra8; break; + default: + log("x2w-frame-pair %s submit_frame=%ld unsupported format=%u", stage, frame, desc.Format); + return; + } + const auto* base = static_cast<const unsigned char*>(mapped) + fp.Offset; + constexpr unsigned width = 96, height = 54; + std::vector<float> image(width * height * 3); + for (unsigned band = 0; band < 6; ++band) { + Counts c; + for (unsigned iy = band * 9; iy < (band + 1) * 9; ++iy) { + auto* row = base + UINT64{coordinate(desc.Height, iy, 54)} * fp.Footprint.RowPitch; + for (unsigned ix = 0; ix < 96; ++ix) { + const auto x = coordinate(static_cast<unsigned>(desc.Width), ix, 96); + const auto pixel = decode(row + x * (format == Format::rgba16f ? 8 : 4), format); + c.add(pixel); + const unsigned at = ((height - 1 - iy) * width + ix) * 3; // PFM stores the bottom row first. + image[at] = pixel.r; + image[at + 1] = pixel.g; + image[at + 2] = pixel.b; + } + } + log("x2w-frame-pair %s submit_frame=%ld target=%p fmt=%u band=%u/6 samples=864 rgb=%u alpha-only=%u nonfinite=%u peak-abs-rgb=%.7g", + stage, frame, surface, desc.Format, band + 1, c.rgb, c.alpha_only, c.nonfinite, c.peak); + } + wchar_t trap_path[MAX_PATH]{}; + const DWORD length = GetEnvironmentVariableW(L"X2W_TRAP_LOG", trap_path, MAX_PATH); + if (!length || length >= MAX_PATH) return; + std::wstring path(trap_path, length); + path.resize(path.find_last_of(L"/\\") + 1); + path += L"frame-" + std::to_wstring(frame) + L"-" + std::wstring(stage, stage + std::strlen(stage)) + L".pfm"; + FILE* output = nullptr; + if (_wfopen_s(&output, path.c_str(), L"wb") || !output) { + log("x2w-frame-pair %s submit_frame=%ld image open failed", stage, frame); + return; + } + const bool written = std::fprintf(output, "PF\n%u %u\n-1.0\n", width, height) > 0 && + std::fwrite(image.data(), sizeof(float), image.size(), output) == image.size(); + if (std::fclose(output) || !written) log("x2w-frame-pair %s submit_frame=%ld image write failed", stage, frame); +} diff --git a/src/startup_stubs/frame_rgb_sample.h b/src/startup_stubs/frame_rgb_sample.h new file mode 100644 index 0000000000..976d2e4a12 --- /dev/null +++ b/src/startup_stubs/frame_rgb_sample.h @@ -0,0 +1,45 @@ +#pragma once + +#include <DirectXPackedVector.h> +#include <cmath> +#include <cstdint> +#include <cstring> + +namespace x2w_frame_sample { +enum class Format { rgba16f, rgba8, bgra8 }; +struct Sample { float r, g, b, a; }; + +inline Sample decode(const unsigned char* p, Format format) +{ + if (format == Format::rgba16f) { + std::uint16_t words[4]; + std::memcpy(words, p, sizeof(words)); + using DirectX::PackedVector::XMConvertHalfToFloat; + return {XMConvertHalfToFloat(words[0]), XMConvertHalfToFloat(words[1]), + XMConvertHalfToFloat(words[2]), XMConvertHalfToFloat(words[3])}; + } + const bool bgra = format == Format::bgra8; + return {p[bgra ? 2 : 0] / 255.f, p[1] / 255.f, p[bgra ? 0 : 2] / 255.f, p[3] / 255.f}; +} + +struct Counts { + unsigned rgb = 0, alpha_only = 0, nonfinite = 0; + float peak = 0; + void add(Sample s) + { + if (!std::isfinite(s.r) || !std::isfinite(s.g) || !std::isfinite(s.b) || !std::isfinite(s.a)) { + ++nonfinite; + } else if (s.r != 0 || s.g != 0 || s.b != 0) { + ++rgb; + peak = std::fmax(peak, std::fmax(std::fabs(s.r), std::fmax(std::fabs(s.g), std::fabs(s.b)))); + } else if (s.a != 0) { + ++alpha_only; + } + } +}; + +inline unsigned coordinate(unsigned size, unsigned cell, unsigned cells) +{ + return static_cast<unsigned>((2ull * cell + 1) * size / (2 * cells)); +} +} diff --git a/src/startup_stubs/gfx10_layout_equations.inc b/src/startup_stubs/gfx10_layout_equations.inc new file mode 100644 index 0000000000..0000cfca81 --- /dev/null +++ b/src/startup_stubs/gfx10_layout_equations.inc @@ -0,0 +1,62 @@ +// GENERATED by tests/gfx10_layout_check.cpp --print-equations from AMD addrlib (Mesa 5c142e46f3f6e752ed745fd48912ebb8fad67145, +// mesa-25.1.0, src/amd/addrlib, MIT; see gfx10_layout.h): [thick][4KB_S 4KB_D 64KB_S 64KB_D][log2 bytes]. +{ + { + {12, {0x00, 0x01, 0x02, 0x03, 0x40, 0x41, 0x42, 0x43, 0x44, 0x04, 0x45, 0x05, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0x00, 0x01, 0x02, 0x40, 0x41, 0x42, 0x03, 0x43, 0x04, 0x44, 0x05, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0x00, 0x01, 0x40, 0x41, 0x42, 0x02, 0x43, 0x03, 0x44, 0x04, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0xc2, 0x00, 0x40, 0x41, 0x01, 0x02, 0x42, 0x03, 0x43, 0x04, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0xc2, 0xc3, 0x40, 0x41, 0x00, 0x01, 0x42, 0x02, 0x43, 0x03, 0xff, 0xff, 0xff, 0xff}}, + }, + { + {12, {0x00, 0x01, 0x02, 0x41, 0x40, 0x42, 0x03, 0x43, 0x44, 0x04, 0x45, 0x05, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0x00, 0x01, 0x02, 0x40, 0x41, 0x42, 0x03, 0x43, 0x04, 0x44, 0x05, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0x00, 0x01, 0x40, 0x41, 0x42, 0x02, 0x43, 0x03, 0x44, 0x04, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0xc2, 0x00, 0x40, 0x01, 0x02, 0x41, 0x42, 0x03, 0x43, 0x04, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0xc2, 0xc3, 0x00, 0x40, 0x01, 0x41, 0x42, 0x02, 0x43, 0x03, 0xff, 0xff, 0xff, 0xff}}, + }, + { + {16, {0x00, 0x01, 0x02, 0x03, 0x40, 0x41, 0x42, 0x43, 0x44, 0x04, 0x45, 0x05, 0x46, 0x06, 0x47, 0x07}}, + {16, {0xc0, 0x00, 0x01, 0x02, 0x40, 0x41, 0x42, 0x03, 0x43, 0x04, 0x44, 0x05, 0x45, 0x06, 0x46, 0x07}}, + {16, {0xc0, 0xc1, 0x00, 0x01, 0x40, 0x41, 0x42, 0x02, 0x43, 0x03, 0x44, 0x04, 0x45, 0x05, 0x46, 0x06}}, + {16, {0xc0, 0xc1, 0xc2, 0x00, 0x40, 0x41, 0x01, 0x02, 0x42, 0x03, 0x43, 0x04, 0x44, 0x05, 0x45, 0x06}}, + {16, {0xc0, 0xc1, 0xc2, 0xc3, 0x40, 0x41, 0x00, 0x01, 0x42, 0x02, 0x43, 0x03, 0x44, 0x04, 0x45, 0x05}}, + }, + { + {16, {0x00, 0x01, 0x02, 0x41, 0x40, 0x42, 0x03, 0x43, 0x44, 0x04, 0x45, 0x05, 0x46, 0x06, 0x47, 0x07}}, + {16, {0xc0, 0x00, 0x01, 0x02, 0x40, 0x41, 0x42, 0x03, 0x43, 0x04, 0x44, 0x05, 0x45, 0x06, 0x46, 0x07}}, + {16, {0xc0, 0xc1, 0x00, 0x01, 0x40, 0x41, 0x42, 0x02, 0x43, 0x03, 0x44, 0x04, 0x45, 0x05, 0x46, 0x06}}, + {16, {0xc0, 0xc1, 0xc2, 0x00, 0x40, 0x01, 0x02, 0x41, 0x42, 0x03, 0x43, 0x04, 0x44, 0x05, 0x45, 0x06}}, + {16, {0xc0, 0xc1, 0xc2, 0xc3, 0x00, 0x40, 0x01, 0x41, 0x42, 0x02, 0x43, 0x03, 0x44, 0x04, 0x45, 0x05}}, + }, +}, +{ + { + {12, {0x00, 0x01, 0x80, 0x40, 0x81, 0x41, 0x02, 0x82, 0x42, 0x03, 0x83, 0x43, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0x00, 0x80, 0x40, 0x81, 0x41, 0x01, 0x82, 0x42, 0x02, 0x83, 0x43, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0x00, 0x40, 0x80, 0x41, 0x01, 0x81, 0x42, 0x02, 0x82, 0x43, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0xc2, 0x00, 0x80, 0x40, 0x01, 0x81, 0x41, 0x02, 0x82, 0x42, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0xc2, 0xc3, 0x80, 0x40, 0x00, 0x81, 0x41, 0x01, 0x82, 0x42, 0xff, 0xff, 0xff, 0xff}}, + }, + { + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + }, + { + {16, {0x00, 0x01, 0x80, 0x40, 0x81, 0x41, 0x02, 0x82, 0x42, 0x03, 0x83, 0x43, 0x04, 0x84, 0x44, 0x05}}, + {16, {0xc0, 0x00, 0x80, 0x40, 0x81, 0x41, 0x01, 0x82, 0x42, 0x02, 0x83, 0x43, 0x03, 0x84, 0x44, 0x04}}, + {16, {0xc0, 0xc1, 0x00, 0x40, 0x80, 0x41, 0x01, 0x81, 0x42, 0x02, 0x82, 0x43, 0x03, 0x83, 0x44, 0x04}}, + {16, {0xc0, 0xc1, 0xc2, 0x00, 0x80, 0x40, 0x01, 0x81, 0x41, 0x02, 0x82, 0x42, 0x03, 0x83, 0x43, 0x04}}, + {16, {0xc0, 0xc1, 0xc2, 0xc3, 0x80, 0x40, 0x00, 0x81, 0x41, 0x01, 0x82, 0x42, 0x02, 0x83, 0x43, 0x03}}, + }, + { + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + }, +}, diff --git a/src/startup_stubs/gfx10_layout_local.h b/src/startup_stubs/gfx10_layout_local.h new file mode 100644 index 0000000000..73b27454d1 --- /dev/null +++ b/src/startup_stubs/gfx10_layout_local.h @@ -0,0 +1,244 @@ +#pragma once +// LOCAL (textures): GFX10 surface layout of console-swizzled textures (layouts 0x100 linear, 0x105 SW_4KB_S, +// 0x106 SW_4KB_D, 0x109 SW_64KB_S, 0x10a SW_64KB_D; Layout field = gfx10 swizzle mode + 0x100), for detiling +// memory views into desktop textures. +// +// Derived from AMD addrlib as shipped in Mesa (src/amd/addrlib at commit 5c142e46f3f6e752ed745fd48912ebb8fad67145, +// tag mesa-25.1.0): the mip, tail and slice placement follows Gfx10Lib::ComputeSurfaceInfoMacroTiled, +// Gfx10Lib::HwlComputeSurfaceInfoLinear and Gfx10Lib::ComputeSurfaceAddrFromCoordMacroTiled (gfx10addrlib.cpp), +// the block dimensions Lib::ComputeThinBlockDimension / ComputeThickBlockDimension / GetMipTailDim +// (addrlib2.cpp), and the in-block equations below were generated from addrlib's own address computation +// (tests/gfx10_layout_check.cpp --print-equations, which also checks this table against addrlib). Only the +// non-XOR modes are covered: they do not depend on the pipe/bank configuration (GB_ADDR_CONFIG). +// +// addrlib notice: +// Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved. +// SPDX-License-Identifier: MIT +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +// documentation files (the "Software"), to deal in the Software without restriction, including without +// limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the +// Software, and to permit persons to whom the Software is furnished to do so, subject to the following +// conditions: The above copyright notice and this permission notice shall be included in all copies or +// substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +// AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR +// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +// ASSUMED, not measured: the console lays a texture out as addrlib's gfx10 code does for the same swizzle mode, +// with no extra pitch or slice padding, and a memory view's address is the surface base. + +#include <cstdint> + +namespace x2w_startup::gfx10_local { + +constexpr unsigned sw_linear = 0, sw_4kb_s = 5, sw_4kb_d = 6, sw_64kb_s = 9, sw_64kb_d = 10; + +// Address bit i of a block comes from src[i]: 0x00|k element x bit k, 0x40|k y bit k, 0x80|k z bit k, +// 0xc0|k byte k inside the element. +struct Equation { + std::uint8_t bits; + std::uint8_t src[16]; +}; + +inline int mode_index(unsigned mode) +{ + switch (mode) { + case sw_4kb_s: return 0; + case sw_4kb_d: return 1; + case sw_64kb_s: return 2; + case sw_64kb_d: return 3; + default: return -1; + } +} + +// [thick][mode_index][log2 element bytes]; bits 0 = addrlib has no equation for the combination. +// GENERATED by tests/gfx10_layout_check.cpp --print-equations (addrlib, see above). +inline const Equation equations[2][4][5] = { +#include "gfx10_layout_equations.inc" +}; + +inline constexpr Equation rbplus_display32[] = { + {12, {0xc0,0xc1,0,1,0x40,0x41,2,0x42,0x43,3,0x44,4,0xff,0xff,0xff,0xff}}, + {16, {0xc0,0xc1,0,1,0x40,0x41,2,0x42,0x43,3,0x44,4,0x45,5,0x46,6}} +}; + +struct Level { + unsigned pitch = 0, height = 0; // in elements, as addrlib aligns them (for tail levels the tail's dimensions) + std::uint64_t offset = 0; // macroBlockOffset (tiled) or the level offset (linear), inside one slice + unsigned tail_x = 0, tail_y = 0, tail_z = 0; + bool in_tail = false; // addrlib's test: mipTailOffset != 0 +}; + +struct Layout { + bool valid = false, linear = false, thick = false; + unsigned mode = 0, elem_log2 = 0, block_log2 = 0, bw = 1, bh = 1, bd = 1; + unsigned mips = 0, slices = 0; + std::uint64_t slice_size = 0, size = 0; + const Equation* eq = nullptr; + Level level[16]; + + // Test-only mutations (tests/gfx10_layout_check.cpp negative controls). + enum Mutation { none, floor_mips, no_tail_coords }; + + // width/height in elements (4x4 blocks for BC); depth_or_array: volume depth for 3D, else array size. + Layout(unsigned swizzle_mode, bool is3d, unsigned elem_bytes, unsigned width, unsigned height, unsigned depth_or_array, + unsigned mip_count, Mutation mutation = none, bool rb_plus = false) + { + unsigned e = 0; + while ((1u << e) < elem_bytes) ++e; + if ((1u << e) != elem_bytes || e > 4 || !width || !height || !depth_or_array || !mip_count || mip_count > 15) return; + mode = swizzle_mode; + elem_log2 = e; + mips = mip_count; + const auto ceil_shift = [&](unsigned v, unsigned s) { + if (mutation == floor_mips) return (v >> s) ? (v >> s) : 1u; + return (v + (1u << s) - 1) >> s; + }; + const auto align = [](std::uint64_t v, std::uint64_t a) { return (v + a - 1) / a * a; }; + if (mode == sw_linear) { + linear = true; + const unsigned pitch_align = 256u >> e; + slices = depth_or_array; + std::uint64_t slice = 0; + for (int i = static_cast<int>(mips) - 1; i >= 0; --i) { + Level& l = level[i]; + l.pitch = static_cast<unsigned>(align(ceil_shift(width, i), pitch_align)); + l.height = ceil_shift(height, i); + l.offset = slice; + slice += std::uint64_t{l.pitch} * l.height * elem_bytes; + } + slice_size = slice; + size = slice_size * slices; + valid = true; + return; + } + const int mi = mode_index(mode); + if (mi < 0) return; + thick = is3d; // the S and D modes are thick for 3D resources (Gfx10Lib::HwlIsThick) + eq = &equations[thick][mi][e]; + if (rb_plus && !thick && e == 2 && (mode == sw_4kb_d || mode == sw_64kb_d)) + eq = &rbplus_display32[mode == sw_64kb_d]; + if (!eq->bits) return; + block_log2 = (mode == sw_4kb_s || mode == sw_4kb_d) ? 12 : 16; + if (!thick) { + const unsigned n = block_log2 - e, w = (n + 1) / 2; + bw = 1u << w; + bh = 1u << (n - w); + bd = 1; + } else { + static const unsigned b1k[5][3] = {{16, 8, 8}, {8, 8, 8}, {8, 8, 4}, {8, 4, 4}, {4, 4, 4}}; + const unsigned in1k = block_log2 - 10, avg = in1k / 3, rest = in1k % 3; + bw = b1k[e][0] << avg; + bh = b1k[e][1] << (avg + rest / 2); + bd = b1k[e][2] << (avg + (rest ? 1 : 0)); + } + const std::uint64_t block = std::uint64_t{1} << block_log2; + const unsigned pitch0 = static_cast<unsigned>(align(width, bw)), height0 = static_cast<unsigned>(align(height, bh)); + slices = static_cast<unsigned>(align(depth_or_array, bd)); + if (mips == 1) { + slice_size = std::uint64_t{pitch0} * height0 * elem_bytes; + size = slice_size * slices; + level[0].pitch = pitch0; + level[0].height = height0; + valid = true; + return; + } + unsigned tail_w = bw, tail_h = bh, tail_d = bd; + if (thick) { + const unsigned dim = block_log2 % 3; + if (dim == 0) tail_h >>= 1; + else if (dim == 1) tail_w >>= 1; + else tail_d >>= 1; + } else { + tail_w >>= 1; + } + (void)tail_d; + const unsigned depth0 = thick ? depth_or_array : 1; + unsigned effective = block_log2; + if (thick) effective -= (block_log2 - 8) / 3; + const unsigned max_in_tail = effective <= 11 ? 1 + (1u << (effective - 9)) : effective - 4; + unsigned first_tail = mips; + std::uint64_t chain = 0, mip_slice[16]{}; + for (unsigned i = 0; i < mips; ++i) { + const unsigned w = ceil_shift(width, i), h = ceil_shift(height, i), d = ceil_shift(depth0, i); + if (w <= tail_w && h <= tail_h && mips - i <= max_in_tail) { + first_tail = i; + chain += block / bd; + break; + } + const unsigned p = static_cast<unsigned>(align(w, bw)), hh = static_cast<unsigned>(align(h, bh)); + (void)d; + const std::uint64_t slice = std::uint64_t{p} * hh * elem_bytes; + mip_slice[i] = slice * bd; + chain += slice; + level[i].pitch = p; + level[i].height = hh; + } + slice_size = chain; + size = chain * slices; + std::uint64_t macro = first_tail != mips ? block : 0; + for (int i = static_cast<int>(first_tail) - 1; i >= 0; --i) { + level[i].offset = macro; + macro += mip_slice[i]; + } + static const unsigned b256_2d[5][2] = {{16, 16}, {16, 8}, {8, 8}, {8, 4}, {4, 4}}; + static const unsigned b256_3d[5][3] = {{8, 4, 8}, {4, 4, 8}, {4, 4, 4}, {4, 2, 4}, {2, 2, 4}}; + unsigned pitch = tail_w, height_t = tail_h; + for (unsigned i = first_tail; i < mips; ++i) { + const unsigned m = max_in_tail - 1 - (i - first_tail); + const unsigned offset = m > 6 ? (16u << m) : (m << 8); + Level& l = level[i]; + l.offset = 0; + l.in_tail = offset != 0; + l.pitch = pitch; + l.height = height_t; + unsigned x = ((offset >> 9) & 1) | ((offset >> 10) & 2) | ((offset >> 11) & 4) | ((offset >> 12) & 8) | + ((offset >> 13) & 16) | ((offset >> 14) & 32); + unsigned y = ((offset >> 8) & 1) | ((offset >> 9) & 2) | ((offset >> 10) & 4) | ((offset >> 11) & 8) | + ((offset >> 12) & 16) | ((offset >> 13) & 32); + if (block_log2 & 1) { + const unsigned t = x; + x = y; + y = t; + if (e & 1) { + y = (y << 1) | (x & 1); + x >>= 1; + } + } + const unsigned ew = thick ? b256_3d[e][0] : b256_2d[e][0], eh = thick ? b256_3d[e][1] : b256_2d[e][1]; + if (mutation != no_tail_coords) { + l.tail_x = x * ew; + l.tail_y = y * eh; + } + pitch = pitch >> 1 > ew ? pitch >> 1 : ew; + height_t = height_t >> 1 > eh ? height_t >> 1 : eh; + } + valid = true; + } + + std::uint64_t block_offset(unsigned x, unsigned y, unsigned z) const + { + std::uint64_t off = 0; + for (unsigned i = 0; i < eq->bits; ++i) { + const unsigned s = eq->src[i], k = s & 0x3f; + const unsigned v = (s & 0xc0) == 0x00 ? x : (s & 0xc0) == 0x40 ? y : (s & 0xc0) == 0x80 ? z : 0; + off |= std::uint64_t{(v >> k) & 1} << i; + } + return off; + } + + // Byte offset of element (x, y) of slice or depth z in level mip, from the surface base. + std::uint64_t address(unsigned mip, unsigned x, unsigned y, unsigned z) const + { + const Level& l = level[mip]; + if (linear) return slice_size * z + l.offset + (std::uint64_t{y} * l.pitch + x) * (1u << elem_log2); + const std::uint64_t slice = thick ? slice_size * bd : slice_size; + const unsigned slice_id = thick ? z / bd : z; + const unsigned xx = l.in_tail ? x + l.tail_x : x, yy = l.in_tail ? y + l.tail_y : y, zz = l.in_tail ? z + l.tail_z : z; + const std::uint64_t blk = std::uint64_t{y / bh} * (l.pitch / bw) + x / bw; + return slice * slice_id + l.offset + (blk << block_log2) + block_offset(xx, yy, zz); + } +}; + +} // namespace x2w_startup::gfx10_local diff --git a/src/startup_stubs/gfx10_raw_vdesc.h b/src/startup_stubs/gfx10_raw_vdesc.h new file mode 100644 index 0000000000..4e1e29ef12 --- /dev/null +++ b/src/startup_stubs/gfx10_raw_vdesc.h @@ -0,0 +1,67 @@ +#pragma once +#include <cstdint> + +namespace x2w_startup { + +constexpr std::uint32_t heap_raw_token_magic = 0x56573258; // "X2WV" (d3d12_capture.inl view_token_magic) +// Translated draw heap layout (d3d12_draw.inl ensure_draw_heap): ring [0, 2^18), 8 empty views, 8 views per view id +// for 90000 ids, then the raw windows. +constexpr std::uint32_t heap_raw_window_first = (1u << 18) + 8 + 8 * 90000; // 982152 +constexpr std::uint32_t heap_raw_windows_max = 256; +// The entry's window field (heap_raw_prelude.hlsli hbuf): 0..255 a window, base 4-aligned; heap_raw_window_unaligned | +// window, a base that is not (the program reads each dword from two); heap_raw_window_paged, a range whose 64 KiB pages +// are in different windows or at scattered offsets of one: the offset field is its first page record (8 bytes each, +// window index and the window offset of the page's start) in the view at heap_raw_pages_view. A program from the +// earlier prelude (window < 256 only) reads both as a miss, as before. +constexpr std::uint32_t heap_raw_window_unaligned = 0x100, heap_raw_window_paged = 0x200; +constexpr std::uint32_t heap_raw_pages_view = heap_raw_window_first + heap_raw_windows_max; // 982408 +constexpr std::uint32_t heap_raw_page_records = 1u << 20; + // split ranges of 57-182 pages by frame 8573, still growing) +constexpr std::uint32_t heap_raw_paged_max_pages = 4096; // a paged range spans at most 256 MiB +constexpr std::uint32_t heap_raw_map_entries = 1u << 19; +constexpr std::uint32_t heap_raw_probes = 16; // the same in heap_raw_prelude.hlsli vraw +constexpr std::uint32_t heap_raw_resolve_budget = 8192; // heap-sweep finds resolved per drain (the rest wait for the next) +constexpr std::uint32_t heap_raw_retry_frames = 120; // an unresolved range is tried again after this many frames +constexpr std::uint32_t heap_raw_sweep_frames = 16; // the heap sweep reads the whole heap in this many frames +constexpr std::uint32_t heap_raw_revalidate_passes = 4; // a resolved entry is resolved again after this many sweep passes +constexpr std::uint64_t heap_raw_window_view_bytes = 4ull << 27; // a raw buffer SRV names at most 2^27 dwords + +struct RawBufferWords { + std::uint64_t base = 0; + std::uint32_t stride = 0, num_records = 0, bytes = 0, format = 0, oob = 0; +}; +// True for a buffer V# the table can bound: not a view token, TYPE 0, base != 0, no SWIZZLE_ENABLE, no ADD_TID_ENABLE, +// OOB_SELECT 0, 1 or 3, and a nonzero size by the rule above. bytes saturates at 0xffffffff (no table entry is that +// large: it must fit in one window). +inline bool raw_buffer_words(const std::uint32_t w[4], RawBufferWords& out) +{ + if (w[0] == heap_raw_token_magic || (w[3] >> 30) != 0 || (w[1] >> 31) || ((w[3] >> 23) & 1)) return false; + out.base = std::uint64_t{w[0]} | (std::uint64_t{w[1] & 0xffff} << 32); + if (!out.base) return false; + out.stride = (w[1] >> 16) & 0x3fff; + out.num_records = w[2]; + out.format = (w[3] >> 12) & 127; + out.oob = (w[3] >> 28) & 3; + if (out.oob == 2) return false; + const std::uint64_t bytes = out.oob == 3 ? std::uint64_t{w[2]} : std::uint64_t{out.stride} * w[2]; + if (!bytes) return false; + out.bytes = bytes > 0xffffffffull ? 0xffffffffu : static_cast<std::uint32_t>(bytes); + return true; +} +// The shape of the V#s the runtime writes (gfx10_buffer_words): words 4-7 zero, word 3 only DST_SEL, FORMAT and +// OOB_SELECT (TYPE 0). The heap reads (d3d12_heap_raw.inl heap_raw_sweep_range) take only slots of this shape, so arena +// bytes and other data in the heap range rarely look like one; one that does is a read-only range of title memory. +inline bool runtime_vdesc_shape(const std::uint32_t w[8]) +{ + return !(w[4] | w[5] | w[6] | w[7]) && !(w[3] & 0xcff80000u); +} +inline std::uint32_t raw_map_hash(std::uint32_t base_lo, std::uint32_t base_hi, std::uint32_t bytes) +{ + std::uint32_t x = (base_lo * 0x9e3779b1u) ^ (base_hi * 0x85ebca6bu) ^ (bytes * 0xc2b2ae35u); + x ^= x >> 16; + x *= 0x7feb352du; + x ^= x >> 15; + return x; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/gfx10_view_words.h b/src/startup_stubs/gfx10_view_words.h new file mode 100644 index 0000000000..e63f80232e --- /dev/null +++ b/src/startup_stubs/gfx10_view_words.h @@ -0,0 +1,324 @@ +#pragma once +// LOCAL (compute translation runtime): facts the translated console compute programs need about a D3D12 view +// that the title created, in the console's own terms. +// +// - buffer_view_layout: where a buffer view starts and how an index steps through it. A typed buffer view +// (StructureByteStride 0, not RAW) steps by the format's element size, as the hardware buffer descriptor of a +// typed buffer holds stride = element size (buffer_load_format ... idxen addresses base + index * stride). +// - gfx10_format: the GFX10_FORMAT code (the 7-bit BUF_FMT / 9-bit IMG format of RDNA 1) of a DXGI format. +// - gfx10_buffer_words / gfx10_image_words: the dwords of the buffer (V#) or image (T#) descriptor that the +// console would hold for the view, for programs that read descriptor fields as numbers. +// +// Sources (public, Mesa revision bb59ce45, 2026-11-24): +// - src/amd/registers/gfx10-rsrc.json: field bits of SQ_BUF_RSRC_WORD1..3 and SQ_IMG_RSRC_WORD1..5, and the +// GFX10_FORMAT enum. +// - src/amd/registers/gfx6.json: SQ_RSRC_IMG_TYPE (1D 8, 2D 9, 3D 10, CUBE 11, 1D_ARRAY 12, 2D_ARRAY 13) and +// SQ_SEL_XYZW01 (0 0, 1 1, X 4, Y 5, Z 6, W 7). +// - src/amd/common/ac_descriptors.c: ac_build_buffer_descriptor (word1 = BASE_ADDRESS_HI | STRIDE, word2 = size), +// ac_build_raw_buffer_descriptor (format 32_FLOAT, swizzle XYZW, OOB_SELECT_RAW), and +// ac_build_gfx10_texture_descriptor (word1 FORMAT | WIDTH_LO(width - 1), word2 WIDTH_HI((width - 1) >> 2) | +// HEIGHT(height - 1), word3 DST_SEL | BASE_LEVEL | LAST_LEVEL | TYPE, word4 DEPTH | BASE_ARRAY with "Depth is +// the last accessible layer", word5 ARRAY_PITCH (3D: 0 SRV, 1 UAV) | MAX_MIP = levels - 1). +// - src/amd/common/gfx10_format_table.py: format names list channels from the most significant bits ("Keep the +// bit sizes in little-endian order"), so DXGI R10G10B10A2 is 2_10_10_10 and R11G11B10 is 10_11_11. +// +// Fields that are NOT synthesized and stay 0 (the runtime logs this once per kind): buffer base address (word0, +// word1 BASE_ADDRESS_HI), SWIZZLE_ENABLE, CACHE_SWIZZLE, INDEX_STRIDE, ADD_TID_ENABLE, RESOURCE_LEVEL; image base +// address (word0, word1 BASE_ADDRESS_HI), MIN_LOD, RESOURCE_LEVEL, SW_MODE, BC_SWIZZLE, PERF_MOD, words 6-7 +// (metadata / compression). +#include <d3d12.h> + +#include <cstdint> +#include <cstring> + +namespace x2w_startup { + +namespace gfx10 { +constexpr std::uint32_t sel_0 = 0, sel_1 = 1, sel_x = 4, sel_y = 5, sel_z = 6, sel_w = 7; // SQ_SEL_XYZW01 +constexpr std::uint32_t dst_sel(std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint32_t w) +{ + return x | (y << 3) | (z << 6) | (w << 9); // DST_SEL_X [0,2], _Y [3,5], _Z [6,8], _W [9,11] +} +constexpr std::uint32_t xyzw = dst_sel(sel_x, sel_y, sel_z, sel_w), xyz1 = dst_sel(sel_x, sel_y, sel_z, sel_1), + xy01 = dst_sel(sel_x, sel_y, sel_0, sel_1), x001 = dst_sel(sel_x, sel_0, sel_0, sel_1), + zyxw = dst_sel(sel_z, sel_y, sel_x, sel_w), zyx1 = dst_sel(sel_z, sel_y, sel_x, sel_1), + a8 = dst_sel(sel_0, sel_0, sel_0, sel_x); +constexpr std::uint32_t img_1d = 8, img_2d = 9, img_3d = 10, img_cube = 11, img_1d_array = 12, img_2d_array = 13; // SQ_RSRC_IMG_TYPE +constexpr std::uint32_t format_32_float = 22; +constexpr std::uint32_t oob_structured_with_offset = 0, oob_raw = 3; // SQ_BUF_RSRC_WORD3__OOB_SELECT +} // namespace gfx10 + +struct Gfx10Format { + std::uint32_t code = 0; // GFX10_FORMAT; 0 = not mapped + std::uint32_t bytes = 0; // element bytes when usable as a buffer format, else 0 + std::uint32_t dst_sel = 0; // DST_SEL_X..W of the channels the format has +}; + +// The GFX10_FORMAT of a desktop DXGI format (typed, not typeless). Unmapped formats return code 0. +inline Gfx10Format gfx10_format(DXGI_FORMAT f) +{ + using namespace gfx10; + switch (f) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: return {77, 16, xyzw}; + case DXGI_FORMAT_R32G32B32A32_UINT: return {75, 16, xyzw}; + case DXGI_FORMAT_R32G32B32A32_SINT: return {76, 16, xyzw}; + case DXGI_FORMAT_R32G32B32_FLOAT: return {74, 12, xyz1}; + case DXGI_FORMAT_R32G32B32_UINT: return {72, 12, xyz1}; + case DXGI_FORMAT_R32G32B32_SINT: return {73, 12, xyz1}; + case DXGI_FORMAT_R16G16B16A16_FLOAT: return {71, 8, xyzw}; + case DXGI_FORMAT_R16G16B16A16_UNORM: return {65, 8, xyzw}; + case DXGI_FORMAT_R16G16B16A16_UINT: return {69, 8, xyzw}; + case DXGI_FORMAT_R16G16B16A16_SNORM: return {66, 8, xyzw}; + case DXGI_FORMAT_R16G16B16A16_SINT: return {70, 8, xyzw}; + case DXGI_FORMAT_R32G32_FLOAT: return {64, 8, xy01}; + case DXGI_FORMAT_R32G32_UINT: return {62, 8, xy01}; + case DXGI_FORMAT_R32G32_SINT: return {63, 8, xy01}; + case DXGI_FORMAT_R10G10B10A2_UNORM: return {50, 4, xyzw}; // 2_10_10_10_UNORM + case DXGI_FORMAT_R10G10B10A2_UINT: return {54, 4, xyzw}; // 2_10_10_10_UINT + case DXGI_FORMAT_R11G11B10_FLOAT: return {36, 4, xyz1}; // 10_11_11_FLOAT + case DXGI_FORMAT_R8G8B8A8_UNORM: return {56, 4, xyzw}; + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return {130, 0, xyzw}; // 8_8_8_8_SRGB (image only) + case DXGI_FORMAT_R8G8B8A8_UINT: return {60, 4, xyzw}; + case DXGI_FORMAT_R8G8B8A8_SNORM: return {57, 4, xyzw}; + case DXGI_FORMAT_R8G8B8A8_SINT: return {61, 4, xyzw}; + case DXGI_FORMAT_B8G8R8A8_UNORM: return {56, 4, zyxw}; + case DXGI_FORMAT_B8G8R8X8_UNORM: return {56, 4, zyx1}; + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return {130, 0, zyxw}; + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return {130, 0, zyx1}; + case DXGI_FORMAT_R16G16_FLOAT: return {29, 4, xy01}; + case DXGI_FORMAT_R16G16_UNORM: return {23, 4, xy01}; + case DXGI_FORMAT_R16G16_UINT: return {27, 4, xy01}; + case DXGI_FORMAT_R16G16_SNORM: return {24, 4, xy01}; + case DXGI_FORMAT_R16G16_SINT: return {28, 4, xy01}; + case DXGI_FORMAT_D32_FLOAT: return {22, 0, x001}; + case DXGI_FORMAT_R32_FLOAT: return {22, 4, x001}; + case DXGI_FORMAT_R32_UINT: return {20, 4, x001}; + case DXGI_FORMAT_R32_SINT: return {21, 4, x001}; + case DXGI_FORMAT_R8G8_UNORM: return {14, 2, xy01}; + case DXGI_FORMAT_R8G8_UINT: return {18, 2, xy01}; + case DXGI_FORMAT_R8G8_SNORM: return {15, 2, xy01}; + case DXGI_FORMAT_R8G8_SINT: return {19, 2, xy01}; + case DXGI_FORMAT_R16_FLOAT: return {13, 2, x001}; + case DXGI_FORMAT_D16_UNORM: return {7, 0, x001}; + case DXGI_FORMAT_R16_UNORM: return {7, 2, x001}; + case DXGI_FORMAT_R16_UINT: return {11, 2, x001}; + case DXGI_FORMAT_R16_SNORM: return {8, 2, x001}; + case DXGI_FORMAT_R16_SINT: return {12, 2, x001}; + case DXGI_FORMAT_R8_UNORM: return {1, 1, x001}; + case DXGI_FORMAT_R8_UINT: return {5, 1, x001}; + case DXGI_FORMAT_R8_SNORM: return {2, 1, x001}; + case DXGI_FORMAT_R8_SINT: return {6, 1, x001}; + case DXGI_FORMAT_A8_UNORM: return {1, 1, a8}; + case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: return {132, 0, xyz1}; // 5_9_9_9_FLOAT + // Depth/stencil as Mesa's hardcoded table (Z24_UNORM_S8_UINT 8_24_UNORM, Z32_FLOAT_S8X24 X24_8_32_FLOAT). + case DXGI_FORMAT_D24_UNORM_S8_UINT: case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: return {141, 0, x001}; + case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: return {146, 0, x001}; + case DXGI_FORMAT_BC1_UNORM: return {169, 0, xyzw}; + case DXGI_FORMAT_BC1_UNORM_SRGB: return {170, 0, xyzw}; + case DXGI_FORMAT_BC2_UNORM: return {171, 0, xyzw}; + case DXGI_FORMAT_BC2_UNORM_SRGB: return {172, 0, xyzw}; + case DXGI_FORMAT_BC3_UNORM: return {173, 0, xyzw}; + case DXGI_FORMAT_BC3_UNORM_SRGB: return {174, 0, xyzw}; + case DXGI_FORMAT_BC4_UNORM: return {175, 0, x001}; + case DXGI_FORMAT_BC4_SNORM: return {176, 0, x001}; + case DXGI_FORMAT_BC5_UNORM: return {177, 0, xy01}; + case DXGI_FORMAT_BC5_SNORM: return {178, 0, xy01}; + case DXGI_FORMAT_BC6H_UF16: return {179, 0, xyz1}; + case DXGI_FORMAT_BC6H_SF16: return {180, 0, xyz1}; + case DXGI_FORMAT_BC7_UNORM: return {181, 0, xyzw}; + case DXGI_FORMAT_BC7_UNORM_SRGB: return {182, 0, xyzw}; + default: return {}; + } +} + +// ---- Buffer views ---------------------------------------------------------------------------------------------- +enum class BufferViewKind { raw, structured, typed, unknown }; +struct BufferViewLayout { + BufferViewKind kind = BufferViewKind::unknown; + std::uint64_t offset = 0; // bytes from the resource start to element 0 + std::uint64_t bytes = 0; // bytes the view covers + std::uint32_t index_stride = 0; // bytes per index step (descriptor STRIDE); 0 for raw views + std::uint32_t num_records = 0; // descriptor NUM_RECORDS: elements when strided, bytes when raw + Gfx10Format format{}; // typed views only +}; + +// first_element/count/structure_stride/flags as in D3D12_BUFFER_SRV / D3D12_BUFFER_UAV (flags bit 0 = RAW in both). +// legacy = the behaviour before the typed-view fix (element 4 bytes when the stride is 0, index stride 0). +inline BufferViewLayout buffer_view_layout(DXGI_FORMAT format, std::uint64_t first_element, std::uint32_t count, + std::uint32_t structure_stride, std::uint32_t flags, bool legacy = false) +{ + BufferViewLayout l; + std::uint32_t element = 4; + if (legacy) { + element = structure_stride ? structure_stride : 4; + l.kind = structure_stride ? BufferViewKind::structured : BufferViewKind::unknown; + l.index_stride = structure_stride; + } else if (structure_stride) { + element = structure_stride; + l.kind = BufferViewKind::structured; + l.index_stride = structure_stride; + } else if ((flags & 1) || format == DXGI_FORMAT_R32_TYPELESS) { + l.kind = BufferViewKind::raw; + } else if (const Gfx10Format f = gfx10_format(format); f.code && f.bytes) { + element = f.bytes; + l.kind = BufferViewKind::typed; + l.index_stride = f.bytes; + l.format = f; + } + l.offset = first_element * element; + l.bytes = std::uint64_t{count} * element; + l.num_records = l.index_stride ? count : static_cast<std::uint32_t>(l.bytes); + return l; +} + +// The buffer part of a recorded D3D12 view description: slot 18 SRV {Format, ViewDimension, Mapping, Buffer at 16}, +// slot 19 UAV {Format, ViewDimension, Buffer at 8}; Buffer = {FirstElement u64, NumElements, StructureByteStride, +// (UAV: CounterOffsetInBytes u64), Flags}, so Flags is at byte 32 in both. False when it is not a buffer view. +inline bool buffer_view_layout_from_desc(bool uav, const unsigned char* desc, std::size_t bytes, BufferViewLayout& out, bool legacy = false) +{ + if (bytes < 36) return false; + std::uint32_t format = 0, dim = 0, count = 0, stride = 0, flags = 0; + std::uint64_t first = 0; + const std::size_t at = uav ? 8 : 16; + std::memcpy(&format, desc, 4); + std::memcpy(&dim, desc + 4, 4); + if (dim != 1) return false; // D3D12_SRV_DIMENSION_BUFFER == D3D12_UAV_DIMENSION_BUFFER == 1 + std::memcpy(&first, desc + at, 8); + std::memcpy(&count, desc + at + 8, 4); + std::memcpy(&stride, desc + at + 12, 4); + std::memcpy(&flags, desc + 32, 4); + out = buffer_view_layout(static_cast<DXGI_FORMAT>(format), first, count, stride, flags, legacy); + return true; +} + +// V# dwords 0..3 (4..7 = 0) for a buffer view. Word 0 / BASE_ADDRESS_HI stay 0 (no address is synthesized). +inline void gfx10_buffer_words(const BufferViewLayout& l, std::uint32_t out[8]) +{ + using namespace gfx10; + std::memset(out, 0, 8 * sizeof(std::uint32_t)); + out[1] = (l.index_stride & 0x3fff) << 16; // STRIDE [16,29] + out[2] = l.num_records; // NUM_RECORDS + const bool typed = l.kind == BufferViewKind::typed; + const std::uint32_t format = typed ? l.format.code : format_32_float; + const std::uint32_t sel = typed ? l.format.dst_sel : xyzw; + const std::uint32_t oob = l.index_stride ? oob_structured_with_offset : oob_raw; + out[3] = sel | ((format & 127) << 12) | (oob << 28); // FORMAT [12,18], OOB_SELECT [28,29], TYPE [30,31] = 0 +} + +// ---- Image views ----------------------------------------------------------------------------------------------- +struct ImageViewFacts { + // the resource (desktop description; same extent as the title's) + D3D12_RESOURCE_DIMENSION dimension = D3D12_RESOURCE_DIMENSION_UNKNOWN; + std::uint64_t width = 0; + std::uint32_t height = 0, depth_or_array = 0, mip_levels = 0; + // the view + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; // typed view format (typeless already mapped) + std::uint32_t view_dimension = 0; // D3D12_SRV_DIMENSION / D3D12_UAV_DIMENSION value (same numbers here) + bool uav = false; + std::uint32_t base_level = 0, level_count = 0; // level_count 0xffffffff: to the last level + std::uint32_t first_slice = 0, slice_count = 0; +}; + +// Reads the view part of a recorded D3D12 view description (slot 18 SRV: union at byte 16; slot 19 UAV: at byte 8). +// False for buffer, multisampled or unknown view dimensions. +inline bool image_view_from_desc(bool uav, const unsigned char* desc, std::size_t bytes, ImageViewFacts& v) +{ + if (bytes < 8) return false; + std::uint32_t f = 0, dim = 0, u[6] = {}; + std::memcpy(&f, desc, 4); + std::memcpy(&dim, desc + 4, 4); + const std::size_t at = uav ? 8 : 16; + if (bytes < at + sizeof(u)) return false; + std::memcpy(u, desc + at, sizeof(u)); + v.format = static_cast<DXGI_FORMAT>(f); + v.view_dimension = dim; + v.uav = uav; + v.first_slice = 0; + v.slice_count = 1; + if (uav) { + // UAV: Texture1D {MipSlice}, 1DArray {MipSlice, First, Size}, 2D {MipSlice, Plane}, 2DArray {MipSlice, First, + // Size, Plane}, 3D {MipSlice, FirstWSlice, WSize} + v.base_level = u[0]; + v.level_count = 1; + if (dim == D3D12_UAV_DIMENSION_TEXTURE1DARRAY || dim == D3D12_UAV_DIMENSION_TEXTURE2DARRAY || dim == D3D12_UAV_DIMENSION_TEXTURE3D) { + v.first_slice = u[1]; + v.slice_count = u[2]; + } else if (dim != D3D12_UAV_DIMENSION_TEXTURE1D && dim != D3D12_UAV_DIMENSION_TEXTURE2D) { + return false; + } + return true; + } + // SRV: {MostDetailedMip, MipLevels, ...}; arrays add FirstArraySlice, ArraySize; cube array First2DArrayFace, NumCubes + v.base_level = u[0]; + v.level_count = u[1]; + switch (dim) { + case D3D12_SRV_DIMENSION_TEXTURE1D: case D3D12_SRV_DIMENSION_TEXTURE2D: case D3D12_SRV_DIMENSION_TEXTURE3D: break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: v.first_slice = u[2]; v.slice_count = u[3]; break; + case D3D12_SRV_DIMENSION_TEXTURECUBE: v.slice_count = 6; break; + case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: v.first_slice = u[2]; v.slice_count = 6 * u[3]; break; + default: return false; + } + return true; +} + +// T# dwords 0..7. False (all words 0) when the view cannot be described; unmapped_format is set when the format +// has no GFX10_FORMAT (the words are still written, with FORMAT 0). +inline bool gfx10_image_words(const ImageViewFacts& v, std::uint32_t out[8], bool* unmapped_format = nullptr) +{ + using namespace gfx10; + std::memset(out, 0, 8 * sizeof(std::uint32_t)); + if (unmapped_format) *unmapped_format = false; + if (!v.width || !v.height || !v.mip_levels) return false; + std::uint32_t type = 0; + const bool three_d = v.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + switch (v.view_dimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: type = img_1d; break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: type = img_1d_array; break; + case D3D12_SRV_DIMENSION_TEXTURE2D: type = img_2d; break; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: type = img_2d_array; break; + case D3D12_SRV_DIMENSION_TEXTURE3D: type = img_3d; break; // D3D12_UAV_DIMENSION_TEXTURE3D is also 8 + case D3D12_SRV_DIMENSION_TEXTURECUBE: case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: type = v.uav ? 0 : img_cube; break; + default: break; + } + if (!type || (type == img_3d) != three_d) return false; + const Gfx10Format f = gfx10_format(v.format); + if (!f.code && unmapped_format) *unmapped_format = true; + const std::uint32_t w = static_cast<std::uint32_t>(v.width - 1), h = v.height - 1; + std::uint32_t base = v.base_level < v.mip_levels ? v.base_level : 0; + std::uint32_t count = v.level_count == 0xffffffffu || v.level_count == 0 || base + v.level_count > v.mip_levels ? v.mip_levels - base : v.level_count; + const std::uint32_t last = base + count - 1; + out[1] = ((f.code & 511) << 20) | ((w & 3) << 30); // FORMAT [20,28], WIDTH_LO [30,31] + out[2] = ((w >> 2) & 0xfff) | ((h & 0x3fff) << 14); // WIDTH_HI [0,11], HEIGHT [14,27] + out[3] = (f.code ? f.dst_sel : xyzw) | ((base & 15) << 12) | ((last & 15) << 16) | (type << 28); // BASE/LAST_LEVEL, TYPE + std::uint32_t depth = 0, base_array = 0, array_pitch = 0; + if (type == img_3d) { + if (v.uav) { // UAV mode: BASE_ARRAY first slice, DEPTH last slice of the bound level + const std::uint32_t level_depth = (v.depth_or_array >> base) ? (v.depth_or_array >> base) : 1; + const std::uint32_t first = v.first_slice < level_depth ? v.first_slice : 0; + const std::uint32_t n = v.slice_count == 0xffffffffu || first + v.slice_count > level_depth ? level_depth - first : v.slice_count; + depth = first + n - 1; + base_array = first; + array_pitch = 1; + } else { + depth = v.depth_or_array - 1; // SRV mode: last slice of level 0 + } + } else if (type == img_1d_array || type == img_2d_array || type == img_cube) { + const std::uint32_t layers = v.depth_or_array ? v.depth_or_array : 1; + const std::uint32_t first = v.first_slice < layers ? v.first_slice : 0; + const std::uint32_t n = v.slice_count == 0 || v.slice_count == 0xffffffffu || first + v.slice_count > layers ? layers - first : v.slice_count; + depth = first + n - 1; // the last accessible layer + base_array = first; + } + out[4] = (depth & 0x1fff) | ((base_array & 0x1fff) << 16); // DEPTH [0,12], BASE_ARRAY [16,28] + out[5] = (array_pitch & 15) | (((v.mip_levels - 1) & 15) << 4); // ARRAY_PITCH [0,3], MAX_MIP [4,7] + return true; +} + +// The UAV format of an integer texture UAV (manifest kind tex2du, RWTexture2D<uint>) over a resource of this format: +// R32_UINT, or UNKNOWN when D3D12 does not allow an R32_UINT view of it. +inline DXGI_FORMAT integer_uav_format(DXGI_FORMAT resource_format) +{ + return resource_format == DXGI_FORMAT_R32_TYPELESS || resource_format == DXGI_FORMAT_R32_UINT ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_UNKNOWN; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/gpu_abi.h b/src/startup_stubs/gpu_abi.h new file mode 100644 index 0000000000..62dc7315b2 --- /dev/null +++ b/src/startup_stubs/gpu_abi.h @@ -0,0 +1,394 @@ +// Shared switches, ABI constants and types for running translated DXIL. These types depend only on Windows, D3D12 +// and standard headers. The Wrapper-dependent hooks live in gpu_hooks.h inside the device shim's anonymous +// namespace. +// +// Shader keys are the first eight BLAKE3 bytes of the exact title bytecode, formatted as 16 lowercase hex digits. +// GpuStage describes the requested pipeline stage and GpuHwStage describes the translated hardware stage. +// The reader converts the serialized root codes (0..5 or 6+x) to GpuRootType and a separate code for Other. +#pragma once + +#include <windows.h> +#include <d3d12.h> + +#include <cstddef> +#include <cstdint> +#include <memory> +#include <vector> + +namespace x2w_depth_twins { struct Twins; } +namespace x2w_gpu { + +// --------------------------------------------------------------------------------------------------------------- +// Switches. X2W_GPU_ABI=1 turns the whole path on (read once). Off (unset, the default): every call site runs +// the old X2W path exactly; that is the rollback. On: the translated shader path only, no mixing with gfx2hlsl +// pipelines. The sub-switches are on by default under ABI=1 and turned off with "=0" (for bisecting); off when ABI +// is off. +// --------------------------------------------------------------------------------------------------------------- +inline bool gpu_env_is(const char* name, char first) noexcept +{ + const DWORD saved = GetLastError(); + char value[4]{}; + const bool is = GetEnvironmentVariableA(name, value, sizeof(value)) && value[0] == first; + SetLastError(saved); + return is; +} +inline bool gpu_abi_on() noexcept +{ + static const bool on = gpu_env_is("X2W_GPU_ABI", '1'); + return on; +} +// X2W_GPU_INDIRECT=0: ExecuteIndirect calls are dropped and counted (WP4). +inline bool gpu_indirect_on() noexcept +{ + static const bool on = gpu_abi_on() && !gpu_env_is("X2W_GPU_INDIRECT", '0'); + return on; +} +// X2W_GPU_MESH=0: mesh pipelines are refused (WP2) and mesh dispatches dropped (WP4). +inline bool gpu_mesh_on() noexcept +{ + static const bool on = gpu_abi_on() && !gpu_env_is("X2W_GPU_MESH", '0'); + return on; +} +// X2W_GPU_TWINS=0: no raw twins in the mirror heap (WP5). Must agree with the export manifest's raw_views +// (GpuManifest::raw_views == 0 for an export made with raw_views=0); the reader asserts it. +inline bool gpu_twins_on() noexcept +{ + static const bool on = gpu_abi_on() && !gpu_env_is("X2W_GPU_TWINS", '0'); + return on; +} +// X2W_GPU_KEYLOG=<path> (G0): every bytecode at device slots 10/11/62/86 is logged once per (key, stage) as +// "<key16> <stage> slot<N> <bytes>" (gpu_hooks.inl). Unset: no key file (counters still run). + +// ABI constants embedded in the translated DXIL. +namespace abi { +// Binding unit: the console's. A table's user-data dword is (handle - heap start) in these bytes. +constexpr UINT view_increment = 32; // CBV_SRV_UAV, device slot 15 under ABI +constexpr UINT sampler_increment = 16; // SAMPLER, device slot 15 under ABI +// RTV and DSV retain the desktop increment for handle mapping. + +// Register spaces of the translated shaders. +constexpr UINT user_data_space = 0; // b0: the per-stage 32-bit root constants (user data) +constexpr UINT sampler_space = 0; // s<n>: immediate samplers as static samplers +constexpr UINT root_cbv_space = 1; // b<param> / t<param> / u<param>: root CBV/SRV/UAV, param = title root index + +// Reserved shader runtime slots in root_cbv_space. +constexpr std::uint8_t slot_strides = 255; // root SRV: SLOT_STRIDES buffer (dword i = stride of view slot i) +constexpr std::uint8_t slot_memory = 254; // root SRV: title memory directory (BVH only; such shaders are dropped) +constexpr std::uint8_t slot_faults = 253; // root UAV: memory faults (BVH only; dropped) +constexpr std::uint32_t slot_strides_count = 1u << 21; // dwords of the SLOT_STRIDES buffer +constexpr std::uint32_t view_stride_bits = (1u << 30) - 1; +constexpr std::uint32_t view_integer = 1u << 31; // typed buffer view of a UINT/SINT format +constexpr std::uint32_t view_signed = 1u << 30; // with view_integer: SINT +constexpr std::uint32_t memory_pages = 1u << 21; +constexpr std::uint32_t memory_read_only = 1u << 31; +constexpr std::uint32_t memory_faults = 4096; + +// RootType::Other codes of user-data dwords the host computes (GpuUserData::other). +constexpr std::uint32_t user_memory_base = 0x100; +constexpr std::uint32_t user_view_address = 0x101; // +1: high bits (0x102) +constexpr std::uint32_t user_view_bias = 0x103; +constexpr std::uint32_t user_root_address = 0x104; // +1: high bits (0x105) +constexpr std::uint32_t user_dispatch_threads_x = 0x106; + +// Mirror view heap layout (WP5), with twins: [0, count) title slots, [count, null) dynamic, null slot, twins. +constexpr std::uint32_t raw_views = 1u << 21; // twin of slot i at raw_views + i +constexpr std::uint32_t view_heap_limit = (1u << 21) - 1; // the null slot; view indices are clamped to it +constexpr std::uint32_t heap_views_with_twins = 1u << 22; +constexpr std::uint32_t dynamic_min = 1u << 18; // dynamic_slots() = clamp(null - count, dynamic_min, dynamic_max) +constexpr std::uint32_t dynamic_max = 1u << 20; + +// Console pipeline-stream subobject numbers that differ from the PC's. +constexpr std::uint32_t subobject_amplification = 23; +constexpr std::uint32_t subobject_mesh = 24; + +// Console command-signature argument type run as a plain dispatch. +constexpr std::uint32_t indirect_console_dispatch = 0x69; +} // namespace abi + +// Stage of the supplied bytecode. Device slot 10 orders vertex, pixel, domain, hull and geometry in the head. Slots +// 11 and 62 take compute. Slot 86 takes stream subobjects 1–6, 23 and 24. +enum class GpuStage : std::uint8_t { vertex, pixel, domain, hull, geometry, compute, amplification, mesh, count }; +inline const char* gpu_stage_name(GpuStage s) noexcept +{ + static const char* const names[] = {"vertex", "pixel", "domain", "hull", "geometry", "compute", "amplification", "mesh"}; + return s < GpuStage::count ? names[static_cast<int>(s)] : "unknown"; +} +// Console hardware stage of the translated program, in cache order. +enum class GpuHwStage : std::uint8_t { ls, hs, es, gs, vs, ps, ms, cs }; + +// Exported shader and pipeline metadata. Spans point into the process-lifetime database mapping. Counts are in +// elements. +template <typename T> +struct GpuSpan { + const T* data = nullptr; + std::uint32_t count = 0; + const T* begin() const noexcept { return data; } + const T* end() const noexcept { return data + count; } + const T& operator[](std::uint32_t i) const noexcept { return data[i]; } + bool empty() const noexcept { return count == 0; } +}; + +// Decoded title root parameter kind. +enum class GpuRootType : std::uint8_t { + constants, // a root-constant dword + descriptor, // a 64-bit buffer address (root CBV/SRV/UAV) + table, // the heap address of a descriptor table range: (handle - heap start) in console bytes + immediate_sampler, // a sampler the root signature fixes + resource_heap, // the CBV/SRV/UAV heap's address (SM 6.6): 0 on the host + sampler_heap, // the sampler heap's address: 0 on the host + other, // `other` holds the code: abi::user_* (host-computed dwords), or an unknown value +}; + +// User-data dword `index` holds dword `dword` of title root parameter `slot`. +struct GpuUserData { + std::uint32_t index; + std::uint32_t slot; // title root parameter index + GpuRootType root; + std::uint32_t other; // RootType::Other code when root == other, else 0 + std::uint32_t dword; // dword within the parameter (for user_dispatch_threads_x: the group width) +}; + +// The four console sampler words of an immediate sampler s<n> (HostShader::samplers). +struct GpuSamplerWords { + std::uint32_t words[4]; +}; + +// Decoded immediate sampler in D3D12 enum values. The root builder applies filter_for_host because anisotropic +// point-mip needs D3D12_OPTIONS19. +struct GpuStaticSampler { + std::uint32_t filter; + std::uint32_t address[3]; // U, V, W + float mip_lod_bias; + std::uint32_t max_anisotropy; + std::uint32_t comparison; + std::uint32_t border; + float min_lod; + float max_lod; +}; + +// A heap descriptor whose byte address is evaluated at bind time from a table base and a root constant. +struct GpuRootIndexedView { + std::uint32_t table_slot; // u8 + std::uint32_t constant_slot; // u8 + std::uint32_t constant_dword; + std::uint32_t byte_offset; + std::uint32_t shift; // u8 +}; + +// Srv=0, Sampler=1, Cbv=2, Uav=3, Other(n) (kind == other, `other_kind` = n). +enum class GpuResourceType : std::uint8_t { srv, sampler, cbv, uav, other }; + +// A descriptor range the console program reads (Translated::used). All eight fields. +struct GpuUsedResource { + GpuResourceType kind; + std::uint8_t other_kind; // ResourceType::Other(n) when kind == other + GpuRootType root; + std::uint32_t root_other; // RootType::Other code when root == other + std::uint32_t table_offset_dwords; + std::uint32_t lower_bound; // shader register of the first descriptor read + std::uint32_t stride; + std::uint8_t dwords; // descriptor size, 4 or 8 + std::uint8_t user_data; // user SGPR + std::uint8_t slot; // title root parameter +}; + +struct GpuShader { + char key[17]; // C1 key, NUL-terminated + GpuStage stage; // the stage the export recorded it under + GpuHwStage hw_stage; // HostShader::stage + const void* dxil = nullptr; // the DXIL container (signed/hashed as D3D12 expects) + std::size_t dxil_bytes = 0; + std::uint16_t material_fields = 0; + GpuSpan<GpuUserData> user_data; + GpuSpan<GpuSamplerWords> samplers; // s<n> at position n + GpuSpan<GpuStaticSampler> static_samplers; // the same, decoded; s<n> at position n + GpuSpan<std::uint8_t> root_cbvs; // title root parameter indices: b<i> space1 + GpuSpan<std::uint8_t> root_srvs; // t<i> space1 (may contain abi::slot_strides / slot_memory) + GpuSpan<std::uint8_t> root_uavs; // u<i> space1 (may contain abi::slot_faults) + GpuSpan<GpuRootIndexedView> root_indexed_views; + // Translated (not in the cache record; the export must add them, C2). + bool has_threads = false; // Translated::threads is Some + std::uint32_t threads[3]{}; // compute threads per group + GpuSpan<GpuUsedResource> used; + bool stores = true; // the code can store to buffer memory (true when unknown) + bool stores_by_address = true; // the code can store through raw addresses (true when unknown) + bool builder = false; + + // HostShader::user_data_dwords: round4(max index + 1), 0 when it reads none. Root constants must cover it. + std::uint32_t user_data_dwords() const noexcept + { + std::uint32_t n = 0; + for (const auto& u : user_data) + if (u.index + 1 > n) n = u.index + 1; + return (n + 3) & ~3u; + } +}; + +// Contract C3: the export manifest header. +struct GpuManifest { + std::uint32_t view_heap_limit; // expected abi::view_heap_limit + std::uint32_t raw_views; // expected abi::raw_views (0: exported without twins) + bool host_rdna; + std::uint32_t max_wave; + std::uint64_t opt_bits; // X2W_SHADERCFG_SHADER_OPT + bool group_sync; // X2W_SHADERCFG_GROUP_SYNC + bool helper_own; // X2W_SHADERCFG_HELPER_OWN + std::uint64_t bvh_bits; // BVH switches + char commit[48]; // translator revision recorded at export +}; + +// Pipeline creation records title bytecode and state. The host pipeline is built on first use. A draw receives null +// while its pipeline is pending or after refusal. +// +// The creation hook computes the key before the title bytecode goes out of scope. +struct GpuStageCode { + GpuStage stage; + const void* bytes; // title memory; valid during gpu_create_pipeline only + std::size_t size; + char key[17]; +}; + +// What the creation slot passed (WP0 fills it, WP2 records it). +struct GpuCreateDesc { + int slot; // device slot: 10, 11, 62 or 86 + const void* desc; // the title's description: GraphicsHead (10), ComputeHead (11/62), stream bytes (86) + std::size_t desc_bytes; // slot 86: the stream's SizeInBytes; else the head's size + const void* title_root; // the root signature wrapper the head names (10/11/62), or the stream's (86), or null + std::uint32_t stage_count; + GpuStageCode stages[8]; + bool unreadable; // a stage's bytes, or the stream, could not be read (the pipeline will be dropped) +}; + +// The host root parameter a title root view is bound at. +struct GpuRootSlot { + std::uint8_t title; // title root parameter index + std::uint8_t host; // host root parameter index (a one-view table by default, or a root descriptor) + bool table; // true: a one-view descriptor table (bounded_root_srvs); false: a root descriptor +}; + +struct GpuPipelineStage { + const GpuShader* shader = nullptr; + GpuStage stage{}; + std::uint32_t user_data_param = UINT32_MAX; // host root parameter of the b0 constants, UINT32_MAX: none + std::uint32_t user_data_dwords = 0; + std::vector<GpuRootSlot> root_cbvs, root_srvs, root_uavs; +}; + +struct GpuInputElement { + std::uint32_t slot; + std::uint32_t offset; + DXGI_FORMAT format; + bool per_instance; + std::uint32_t step_rate; +}; + +// A made pipeline, owned by WP2, read by WP3/WP4. The title wrapper's own().real stays null: X2W's old +// list_pipeline must never bind it. +struct GpuPipeline { + bool compute = false; + bool mesh = false; + bool rects = false; // Drawn with the rectangle geometry shader + ID3D12PipelineState* pso = nullptr; + UINT color_mask = D3D12_COLOR_WRITE_ENABLE_ALL; + bool depth_test = false, depth_write = false; + ID3D12RootSignature* root = nullptr; + std::uint32_t stage_count = 0; + GpuPipelineStage stages[4]; // compute: CS; mesh: (AS) MS PS; graphics: VS PS + std::uint32_t vertex_slots = 0; // mask of vertex buffer slots the input layout reads + std::vector<GpuInputElement> inputs; + D3D12_PRIMITIVE_TOPOLOGY_TYPE topology_type = D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED; + std::uint32_t title_topology = 0; // the stream's topology as the title gave it (console values) + std::uint32_t strides_param = UINT32_MAX; // host param of SLOT_STRIDES, UINT32_MAX: none + // DispatchX (WP4): where USER_DISPATCH_THREADS_X lives, UINT32_MAX: none. + std::uint32_t threads_x_param = UINT32_MAX; + std::uint32_t threads_x_dword = 0; + void* impl = nullptr; // WP2's private state +}; + +// The targets bound at the draw, for pipelines whose stream formats differ from the bound views (WP2 makes a variant). +struct GpuTargets { + std::uint32_t count = 0; + DXGI_FORMAT rtv[8]{}; + DXGI_FORMAT dsv = DXGI_FORMAT_UNKNOWN; + std::uint32_t samples = 1; + bool read_depth_plane = false, read_stencil_plane = false; +}; + +// --------------------------------------------------------------------------------------------------------------- +// Root arguments (WP3). One per title root parameter, graphics and compute kept apart, any number of parameters and +// dwords. WP3's per-list record (GpuListState, gpu_roots.h) holds vectors of these. +// --------------------------------------------------------------------------------------------------------------- +enum class GpuRootKind : std::uint8_t { none, table, constants, cbv, srv, uav }; +struct GpuRoot { + GpuRootKind kind = GpuRootKind::none; + std::uint64_t handle = 0; // table: the title GPU handle + std::uint64_t address = 0; // cbv/srv/uav: the title GPU address + std::vector<std::uint32_t> dwords; // constants +}; +struct GpuListState; // WP3, gpu_roots.h + +// --------------------------------------------------------------------------------------------------------------- +// Mirror heaps and views (WP5). Opaque heap; the functions are in gpu_hooks.h. +// --------------------------------------------------------------------------------------------------------------- +struct GpuHostHeap; // WP5 + +// One title shader-visible heap as WP3 needs it. +struct GpuHeapInfo { + GpuHostHeap* heap = nullptr; + const void* title_heap = nullptr; // the title's descriptor heap wrapper + std::uint64_t title_gpu = 0; // the GPU start the title was given (handles are title_gpu + index * increment) + std::uint64_t title_cpu = 0; // the title's descriptor memory + std::uint32_t count = 0; // title slots + bool sampler = false; + ID3D12DescriptorHeap* host = nullptr; // for SetDescriptorHeaps +}; + +// View decoded from the title slot's token or descriptor words. +enum class GpuViewKind : std::uint8_t { none, srv, uav, cbv, sampler }; +struct GpuViewInfo { + GpuViewKind kind = GpuViewKind::none; + bool texture = false; + bool buffer = false; + UINT first_mip{}, first_slice{}, plane{}; + DXGI_FORMAT view_format = DXGI_FORMAT_UNKNOWN; + const void* title_resource = nullptr; // the resource wrapper, or null (placed/address views) + ID3D12Resource* desktop = nullptr; // the desktop resource the view names, or null + std::shared_ptr<x2w_depth_twins::Twins> depth_twins; + std::uint64_t title_address = 0; // buffer: the title GPU address of the first byte + std::uint64_t bytes = 0; // buffer: the view's size + std::uint32_t stride = 0; // buffer: bytes per element (the SLOT_STRIDES value) +}; + +// --------------------------------------------------------------------------------------------------------------- +// Title memory (WP3, gpu_find.h): what is at a title GPU address, bounded (never the bare window end). +// --------------------------------------------------------------------------------------------------------------- +struct GpuFound { + ID3D12Resource* resource = nullptr; // the desktop window or buffer + std::uint64_t offset = 0; // of `address` in it + std::uint64_t bytes_left = 0; // from `address` to the end of the title buffer or the contiguous run +}; + +// --------------------------------------------------------------------------------------------------------------- +// Counters kept by the WP0 hooks (not by the stubs, so they stay when the stubs are filled). Read by tests through +// the dll export x2w_gpu_counter(int) (gpu_hooks.inl) and logged as "x2w-gpu ..." lines. +// --------------------------------------------------------------------------------------------------------------- +enum GpuCounter : int { + vc_pipelines, // creation calls at 10/11/62/86 under ABI + vc_pipelines_kept, // gpu_create_pipeline returned true + vc_keys, // distinct (key, stage) pairs logged + vc_refused_57, + vc_refused_67, + vc_heaps, // descriptor heaps passed to gpu_heap_created + vc_views, // view slots passed to gpu_heap_view + vc_copies, // descriptor copies passed to gpu_heap_copy* + vc_setters, // list setter calls passed on + vc_draws, vc_draws_dropped, + vc_dispatches, vc_dispatches_dropped, + vc_meshes, vc_meshes_dropped, + vc_indirects, vc_indirects_dropped, + vc_mesh_x_dropped, // DispatchMeshX (dropped) + vc_resets, vc_closes, vc_submits, + vc_count +}; + +} // namespace x2w_gpu diff --git a/src/startup_stubs/gpu_ambient.h b/src/startup_stubs/gpu_ambient.h new file mode 100644 index 0000000000..801b1c734e --- /dev/null +++ b/src/startup_stubs/gpu_ambient.h @@ -0,0 +1,154 @@ +#pragma once + +#include "startup_stubs/gpu_ambient_kernels.h" +#include <d3d12.h> +#include <d3dcompiler.h> +#include <wrl/client.h> + +#include <array> +#include <cstdint> +#include <cstring> +#include <string> + +namespace x2w_gpu::ambient { + +enum class Role { none, resolve, radiance, air }; +struct Settings { + float level = 0, constant = 0, strength = 1, radius = 0.6f, air = 0; +}; +struct Views { + D3D12_GPU_DESCRIPTOR_HANDLE depth{}, image{}; + UINT width = 0, height = 0, slices = 1; +}; + +// Own one instance per device. The caller serializes recording, binds the shader-visible +// heap and prepares the image for unordered access and the resolve depth for compute reads. +class Pass { +public: + HRESULT error() const { return status_; } + const std::string& diagnostic() const { return diagnostic_; } + + bool record(ID3D12Device* device, ID3D12GraphicsCommandList* list, Role role, + const Settings& settings, const Views& views) + { + if (!device || !list || role == Role::none || (!views.width || !views.height || !views.image.ptr) || + !(settings.level > 0 || settings.constant > 0)) return false; + if (role == Role::resolve && !views.depth.ptr) return false; + if (role != Role::radiance && settings.constant == 0 && !measured_) return false; + if (role == Role::air && (!views.slices || settings.constant > 0 || !(settings.air > 0))) return false; + if (status_ == S_FALSE) status_ = initialize(device); + if (FAILED(status_)) return false; + + const struct Parameters { + float intensity, fixed, strength, radius, near_plane, vertical_slope; + UINT width, height; + float adaptation, maximum_ratio, fog_ratio, reserved; + } data{settings.level, settings.constant, settings.strength, settings.radius, 0.1f, 0.45f, + views.width, views.height, 0.04f, 4.0f, settings.air, 0.0f}; + static_assert(sizeof(data) == 12 * sizeof(UINT)); + + D3D12_RESOURCE_BARRIER order{}; + order.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &order); + list->SetComputeRootSignature(root_.Get()); + list->SetComputeRoot32BitConstants(0, 12, &data, 0); + if (role == Role::resolve) list->SetComputeRootDescriptorTable(1, views.depth); + list->SetComputeRootDescriptorTable(2, views.image); + list->SetComputeRootUnorderedAccessView(3, history_->GetGPUVirtualAddress()); + list->SetComputeRootUnorderedAccessView(4, probes_->GetGPUVirtualAddress()); + const auto dispatch = [&](Kernel kernel, UINT x, UINT y, UINT z) { + list->SetPipelineState(pipelines_[kernel].Get()); + list->Dispatch(x, y, z); + list->ResourceBarrier(1, &order); + }; + const auto groups = [](UINT size, UINT width) { return (size - 1) / width + 1; }; + switch (role) { + case Role::radiance: + dispatch(measure, 8, 9, 1); + dispatch(adapt, 1, 1, 1); + measured_ = true; + break; + case Role::resolve: + if (settings.constant == 0) { + dispatch(locate, 8, 9, 1); + dispatch(integrate, 20, 45, 1); + } + dispatch(resolve, groups(views.width, 8), groups(views.height, 8), 1); + break; + case Role::air: + dispatch(limit_fog, groups(views.width, 8), groups(views.height, 8), groups(views.slices, 2)); + break; + case Role::none: return false; + } + return true; + } + +private: + template<class T> using ComPtr = Microsoft::WRL::ComPtr<T>; + enum Kernel { measure, adapt, locate, integrate, resolve, limit_fog, count }; + HRESULT initialize(ID3D12Device* device) + { + D3D12_DESCRIPTOR_RANGE srv{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0}; + D3D12_DESCRIPTOR_RANGE uav{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0}; + D3D12_ROOT_PARAMETER params[5]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants.Num32BitValues = 12; + params[1].ParameterType = params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &srv}; + params[2].DescriptorTable = {1, &uav}; + params[3].ParameterType = params[4].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[3].Descriptor.ShaderRegister = 1; + params[4].Descriptor.ShaderRegister = 2; + D3D12_ROOT_SIGNATURE_DESC signature{5, params}; + ComPtr<ID3DBlob> bytes, messages; + HRESULT hr = D3D12SerializeRootSignature(&signature, D3D_ROOT_SIGNATURE_VERSION_1, &bytes, &messages); + if (FAILED(hr)) return hr; + hr = device->CreateRootSignature(0, bytes->GetBufferPointer(), bytes->GetBufferSize(), IID_PPV_ARGS(&root_)); + if (FAILED(hr)) return hr; + + const struct Program { const char* part; const char* entry; } programs[count] = { + {"MEASURE", "Measure"}, {"MEASURE", "Adapt"}, {"PROBES", "Locate"}, {"PROBES", "Integrate"}, + {"RESOLVE", "ResolveDiffuse"}, {"SCATTER", "LimitFog"} + }; + for (UINT i = 0; i < count; ++i) { + const D3D_SHADER_MACRO defines[] = {{programs[i].part, "1"}, {}}; + bytes.Reset(); + messages.Reset(); + hr = D3DCompile(detail::source, sizeof(detail::source)-1, "gpu_ambient", defines, nullptr, + programs[i].entry, "cs_5_1", 0, 0, &bytes, &messages); + if (FAILED(hr)) { + diagnostic_ = programs[i].entry; + if (messages) diagnostic_.append(": ").append(static_cast<const char*>(messages->GetBufferPointer()), + messages->GetBufferSize()); + return hr; + } + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = root_.Get(); + pso.CS = {bytes->GetBufferPointer(), bytes->GetBufferSize()}; + hr = device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&pipelines_[i])); + if (FAILED(hr)) { diagnostic_ = programs[i].entry; return hr; } + } + + const auto make_buffer = [&](UINT64 size, ComPtr<ID3D12Resource>& result) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = size; + d.Height = d.DepthOrArraySize = d.MipLevels = d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + return device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&result)); + }; + hr = make_buffer((2 * 64 * 36 + 1) * 16, history_); + return SUCCEEDED(hr) ? make_buffer(160 * 90 * 3 * 16, probes_) : hr; + } + + HRESULT status_ = S_FALSE; + std::string diagnostic_; + bool measured_ = false; + ComPtr<ID3D12RootSignature> root_; + std::array<ComPtr<ID3D12PipelineState>, count> pipelines_; + ComPtr<ID3D12Resource> history_, probes_; +}; +} diff --git a/src/startup_stubs/gpu_ambient_kernels.h b/src/startup_stubs/gpu_ambient_kernels.h new file mode 100644 index 0000000000..9d595bfb4c --- /dev/null +++ b/src/startup_stubs/gpu_ambient_kernels.h @@ -0,0 +1,185 @@ +// GPU kernels for screen-space indirect illumination. +#pragma once + +namespace x2w_gpu::ambient::detail { +inline constexpr char source[] = R"hlsl( +cbuffer LightingSettings : register(b0) { + float intensity, fixedLight, creaseStrength, creaseRadius; + float nearPlane, verticalSlope; uint2 extent; + float adaptation, maximumRatio, fogRatio, reserved; +}; +Texture2D<float> sceneDepth : register(t0); +RWStructuredBuffer<float4> history : register(u1); +RWStructuredBuffer<float4> coefficients : register(u2); +static const uint2 cellGrid = uint2(64,36); +static const uint2 probeGrid = uint2(160,90); +static const uint cellCount = 2304; +static const float3 lumaWeights = float3(0.2126,0.7152,0.0722); + +float3 eyePosition(int2 pixel) { + float sampleDepth = sceneDepth.Load(int3(clamp(pixel, 0, int2(extent)-1), 0)); + float distance = min(1000.0, nearPlane / max(sampleDepth, 1e-7)); + float2 uv = (pixel + 0.5) / float2(extent); + float2 ray = (2.0 * uv - 1.0) * float2(float(extent.x)/extent.y, -1) * verticalSlope; + return float3(ray,1) * distance; +} +float3 gridPosition(uint2 bin, uint2 grid) { + return eyePosition(int2((bin + 0.5) * float2(extent) / grid)); +} + +#ifdef MEASURE +RWTexture2D<float3> sceneColor : register(u0); +[numthreads(8,4,1)] +void Measure(uint3 tid : SV_DispatchThreadID) { + uint2 resolution; + sceneColor.GetDimensions(resolution.x, resolution.y); + float3 energy = 0; + for (uint j = 0; j != 25; ++j) { + float2 offset = (float2(j % 5, j / 5) + 0.5) / 5.0; + uint2 samplePixel = uint2((tid.xy + offset) * resolution / cellGrid); + float3 value = max(sceneColor[samplePixel], 0); + if (any(isinf(value)) || any(isnan(value))) value = 0; + energy += value / max(1.0, dot(value,lumaWeights) / 20.0); + } + history[tid.y * cellGrid.x + tid.x] = float4(energy / 25, 1); +} +[numthreads(1,1,1)] +void Adapt() { + float3 average = 0; + for (uint i = 0; i < cellCount; ++i) average += history[i].rgb; + average /= cellCount; + float4 old = history[cellCount]; + history[cellCount] = float4(old.a > 0 ? lerp(old.rgb, average, adaptation) : average, 1); +} +#endif + +#ifdef PROBES +[numthreads(8,4,1)] +void Locate(uint3 tid : SV_DispatchThreadID) { + float3 pos = gridPosition(tid.xy, cellGrid); + history[cellCount + 1 + tid.x + cellGrid.x * tid.y] = float4(pos, pos.z * pos.z); +} +[numthreads(8,2,1)] +void Integrate(uint3 tid : SV_DispatchThreadID) { + float3 pos = gridPosition(tid.xy, probeGrid); + float softening = 0.25 + 0.0025 * pos.z * pos.z; + float sumWeight = 0; + float3 sumDirection = 0, sumEnergy = 0; + float3 momentR = 0, momentG = 0, momentB = 0; + for (uint i = 0; i < cellCount; ++i) { + float4 cell = history[cellCount + 1 + i]; + float3 difference = cell.xyz - pos; + float dist2 = dot(difference,difference); + float weight = cell.w / (dist2 + softening); + float3 direction = difference / sqrt(dist2 + 0.25 * softening); + float3 light = history[i].rgb; + sumWeight += weight; + sumDirection += weight * direction; + sumEnergy += weight * light; + momentR += weight * light.r * direction; + momentG += weight * light.g * direction; + momentB += weight * light.b * direction; + } + sumWeight = max(sumWeight, 1e-6); + float3 energy = sumEnergy / sumWeight; + float3 meanDirection = sumDirection / sumWeight; + uint start = 3 * (tid.y * probeGrid.x + tid.x); + coefficients[start] = float4(momentR / sumWeight - energy.r * meanDirection, energy.r); + coefficients[start+1] = float4(momentG / sumWeight - energy.g * meanDirection, energy.g); + coefficients[start+2] = float4(momentB / sumWeight - energy.b * meanDirection, energy.b); +} +#endif + +#ifdef SCATTER +RWTexture3D<float3> fog : register(u0); +[numthreads(8,8,2)] +void LimitFog(uint3 voxel : SV_DispatchThreadID) { + uint3 size; + fog.GetDimensions(size.x,size.y,size.z); + if (any(voxel >= size)) return; + uint2 probe = min(uint2((voxel.xy + 0.5) * probeGrid / float2(size.xy)),probeGrid-1); + uint start = 3 * (probe.x + probe.y * probeGrid.x); + float3 localAverage = float3(coefficients[start].w,coefficients[start+1].w,coefficients[start+2].w); + float cap = fogRatio * lerp(dot(history[cellCount].rgb,lumaWeights),dot(localAverage,lumaWeights), + float(voxel.z) / size.z); + float3 value = fog[voxel]; + float brightness = dot(value,lumaWeights); + if (brightness > cap) fog[voxel] = value * (cap/brightness); +} +#endif + +#ifdef RESOLVE +RWTexture2D<uint> indirectLight : register(u0); +float3 decodeRGB9E5(uint bits) { + return float3(bits & 511, (bits >> 9) & 511, (bits >> 18) & 511) * exp2(float(bits >> 27)-24); +} +uint encodeRGB9E5(float3 value) { + value = clamp(value, 0, 65408); + float peak = max(value.r,max(value.g,value.b)); + int exponent = clamp((int)floor(log2(max(peak,1e-9))) + 16,0,31); + if (peak * exp2(float(24 - exponent)) >= 511.5) exponent = min(31,exponent+1); + uint3 m = min(uint3(value * exp2(float(24 - exponent)) + 0.5),511u); + return m.r | (m.g << 9) | (m.b << 18) | (uint(exponent) << 27); +} +float3 slope(int2 p, int2 step, float3 center) { + float3 back = center - eyePosition(p-step); + float3 forward = eyePosition(p+step) - center; + return abs(back.z) < abs(forward.z) ? back : forward; +} +float openness(int2 pixel, float3 center, float3 normal, float noise) { + float footprint = min(128.0, creaseRadius * extent.y / (2 * verticalSlope * center.z)); + if (creaseStrength <= 0 || footprint < 1.5 || center.z >= 400) return 1; + float sum = 0; + for (int j = 0; j < 12; ++j) { + float angle = j * 2.399963 + noise * 6.2831853; + float2 offset = float2(cos(angle),sin(angle)) * (sqrt((j + 0.5)/12) * footprint); + float3 delta = eyePosition(pixel + int2(round(offset))) - center; + float d2 = dot(delta,delta); + float above = max(0.0, dot(delta,normal) - 0.004 * center.z - 0.005); + sum += above / sqrt(d2 + 1e-6) * saturate(1.0 - d2/(creaseRadius*creaseRadius)); + } + return saturate(1.0 - creaseStrength * 2 * sum / 12); +} +[numthreads(8,8,1)] +void ResolveDiffuse(uint3 thread : SV_DispatchThreadID) { + if (any(thread.xy >= extent)) return; + int2 pixel = int2(thread.xy); + float3 center = eyePosition(pixel); + float3 normal = normalize(cross(slope(pixel,int2(0,1),center),slope(pixel,int2(1,0),center)) + float3(0,0,-1e-9)); + if (dot(normal,center) > 0) normal = -normal; + float jitter = frac(52.9829189 * frac(dot(float2(pixel),float2(0.06711056,0.00583715)))); + float visibility = openness(pixel,center,normal,jitter); + if (fixedLight > 0) { + indirectLight[pixel] = encodeRGB9E5(float3(1.0,0.98,0.94) * fixedLight * visibility); + return; + } + float2 at = (pixel + 0.5) * probeGrid / float2(extent) - 0.5 + 0.5 * (jitter-0.5); + int2 base = int2(floor(at)); + float2 blend = at-base; + float weights = 0; + float4 r = 0, g = 0, b = 0; + for (int i = 0; i < 4; ++i) { + int2 corner = int2(i&1,i>>1); + uint2 probe = uint2(clamp(base+corner,0,int2(probeGrid)-1)); + float dz = abs(gridPosition(probe,probeGrid).z-center.z)/center.z; + float2 bilinear = lerp(1.0-blend,blend,float2(corner)); + float w = (bilinear.x * bilinear.y + 0.001) / (0.02 + dz); + uint idx = 3 * (probe.x + probe.y * probeGrid.x); + r += w * coefficients[idx]; + g += w * coefficients[idx+1]; + b += w * coefficients[idx+2]; + weights += w; + } + float3 diffuse = float3(r.w,g.w,b.w) / weights; + float3 directional = diffuse + 1.2 * float3(dot(r.xyz,normal),dot(g.xyz,normal),dot(b.xyz,normal)) / weights; + float3 estimate = lerp(clamp(directional,0.2*diffuse,2.5*diffuse),history[cellCount].rgb,0.2) + * intensity * visibility; + float3 prior = decodeRGB9E5(indirectLight[pixel]); + if (prior.g < 0.5 * min(prior.r,prior.b) && max(prior.r,prior.b) > 0.02) prior = 0; + float ceiling = max(dot(estimate,lumaWeights) * maximumRatio,1e-6); + prior *= min(1.0,ceiling / max(dot(prior,lumaWeights),1e-6)); + indirectLight[pixel] = encodeRGB9E5(max(prior,estimate)); +} +#endif +)hlsl"; +} diff --git a/src/startup_stubs/gpu_as_address.h b/src/startup_stubs/gpu_as_address.h new file mode 100644 index 0000000000..33a32d3cf3 --- /dev/null +++ b/src/startup_stubs/gpu_as_address.h @@ -0,0 +1,22 @@ +#pragma once + +#include <cstdint> + +namespace x2w_as_address { +// X2WV native view token leaves words 3 and 6..7 for metadata. Preserve its +// capture id and resource when a placed AS view is made at a desktop GPU VA. +constexpr std::uint32_t token = 0x56573258; +constexpr std::uint32_t annotation = 0x41573258; +inline bool annotate(std::uint32_t* words, std::uint64_t title) +{ + if (words[0] != token || words[2] != 18) return false; + words[3] = annotation; + words[6] = std::uint32_t(title); + words[7] = std::uint32_t(title >> 32); + return true; +} +inline std::uint64_t address(const std::uint32_t* words, std::uint64_t captured) +{ + return words[3] == annotation ? std::uint64_t{words[6]} | (std::uint64_t{words[7]} << 32) : captured; +} +} diff --git a/src/startup_stubs/gpu_bind.inl b/src/startup_stubs/gpu_bind.inl new file mode 100644 index 0000000000..a72cd51ef8 --- /dev/null +++ b/src/startup_stubs/gpu_bind.inl @@ -0,0 +1,1768 @@ +// Root argument binding and direct draws for translated shaders. Root arguments are recorded per command list. The +// binder locates title buffers in desktop memory windows and bounds each view by the title allocation. +// +// Table CBVs and misaligned root CBVs are copied at recording time into 256-byte-aligned upload-ring slots. The +// title must have populated the constants by then. Dynamic slots are returned after the last submission fence. +// Other shim operations can replace heaps, roots and PSOs, so cached bindings must be invalidated after such +// operations. Buffer barriers order access to the shared windows with a global UAV barrier. + +using x2w_gpu::GpuListState; + +namespace vbind { + +namespace abi = x2w_gpu::abi; +using x2w_gpu::GpuResourceType; +using x2w_gpu::GpuRootType; +using x2w_gpu::GpuViewKind; + +// ---- counters (one line per 300 frames, from gpu_bind_submitted) ------------------------------------------------- +enum Drop : int { + drop_no_pipeline, drop_wrong_kind, drop_no_view_heap, drop_no_slots, drop_memory_shader, drop_root_uav, drop_root_srv, + drop_index_buffer, drop_rectangles, drop_not_recording, drop_invalid_targets, drop_count +}; +LONG dispatched, drawn, dropped[drop_count]; +thread_local Drop last_drop; +LONG user_misses, cbv_copies, cbv_copy_failed, cbv_null, root_uav_null, root_uav_unknown, root_uav_cut, root_srv_null, + root_srv_cut, vertex_unbound, textures_uploaded, foreign_tables, slots_released, slots_kept, buffer_barriers, + tables_skipped, table_views_missing, missing_sampler_heap; +bool drop(Drop why) +{ + InterlockedIncrement(&dropped[why]); + if (gpu_drop_trace()) last_drop = why; + return false; +} + +bool bind_cache() { static const bool on = x2w_local::env_on("X2W_GPU_BIND_CACHE"); return on; } +// Caps for root views in MiB (as X2W_SHADERCFG_ROOT_VIEW_MB / X2W_SHADERCFG_ROOT_UAV_MB); unset: the title buffer alone. +std::uint64_t env_mb(const char* name) +{ + char v[24]{}; + const DWORD n = GetEnvironmentVariableA(name, v, sizeof(v)); + const unsigned long long mb = n && n < sizeof(v) ? std::strtoull(v, nullptr, 10) : 0; + return mb ? mb << 20 : ~0ull; +} +std::uint64_t root_srv_limit() { static const std::uint64_t l = env_mb("X2W_GPU_ROOT_VIEW_MB"); return l; } +std::uint64_t root_uav_limit() { static const std::uint64_t l = env_mb("X2W_GPU_ROOT_UAV_MB"); return l; } +// Maximum readable range when no title buffer record covers an address (X2W_GPU_UNKNOWN_SRV_KB, default 1024; +// zero disables reads). Writes receive a null view. +std::uint64_t unknown_read_bytes() +{ + static const std::uint64_t b = [] { + char v[24]{}; + const DWORD n = GetEnvironmentVariableA("X2W_GPU_UNKNOWN_SRV_KB", v, sizeof(v)); + return n && n < sizeof(v) ? std::strtoull(v, nullptr, 10) << 10 : (1ull << 20); + }(); + return b; +} +// Textures uploaded per call from WP5's queue (X2W_GPU_UPLOADS_PER_CALL, default 64). +std::size_t upload_due_most() +{ + static const std::size_t n = [] { + char v[24]{}; + const DWORD k = GetEnvironmentVariableA("X2W_GPU_UPLOADS_PER_CALL", v, sizeof(v)); + return k && k < sizeof(v) ? static_cast<std::size_t>(std::strtoull(v, nullptr, 10)) : std::size_t{64}; + }(); + return n; +} +ID3D12Resource* window_of(const x2w_vbind::Found& f) { return static_cast<ID3D12Resource*>(f.buffer); } + +// ---- per-list state (own().gpu[0] of the list wrapper) ------------------------------------------------------------ +GpuListState& state_of(Wrapper* list) +{ + auto& slot = list->own().gpu[0]; // ADAPT to WP0's type of the slot + if (!slot) slot = new GpuListState(); + return *static_cast<GpuListState*>(slot); +} +GpuListState* state_if(Wrapper* list) { return static_cast<GpuListState*>(list->own().gpu[0]); } + +#include "startup_stubs/gpu_compute_trace.inl" + +std::optional<bool> prepare_packed_light(Wrapper* self, Wrapper* proxy, ID3D12Resource* destination, + x2w_packed_light::BoundCopy* bound) +{ + if (!packed_light_enabled() || !proxy->own().linear_memory_srv) return {}; + const auto destination_format = destination->GetDesc().Format; + if (!x2w_packed_light::color_bytes(destination_format)) return {}; + const auto* info = resource_info(proxy); + if (!info || destination_format != info->console.Format) return {}; + const auto address = reinterpret_cast<u64>(proxy->own().title_memory); + auto source = packed_light_source(address, info->console); + if (!source) return {}; + // An explicit write to the view's own host resource already holds its data. + if (list_wrote(self, destination)) return true; + const auto& uploaded = texture_uploads(); + if (auto it = uploaded.find(destination); it != uploaded.end() && it->second.gpu_written) return true; + if (bound && bound->contains(source.Get(), destination)) { + static LONG64 skipped; + const auto n = InterlockedIncrement64(&skipped); + if ((n & (n - 1)) == 0) log("x2w-gpu repeated packed light bindings skipped %lld", n); + return true; + } + auto& copies = state_of(self).light_copies; + const auto found = std::find_if(copies.begin(), copies.end(), [&](const auto& c) { + return c->source.Get() == source.Get() && c->destination.Get() == destination; + }); + std::shared_ptr<x2w_packed_light::Copy> copy; + if (found != copies.end()) copy = *found; + else { + copy = std::make_shared<x2w_packed_light::Copy>(); + auto* scratch = copies.empty() ? nullptr : copies.back()->scratch.Get(); + if (!copy->init(device_of(the_device), source.Get(), destination, scratch)) return false; + copies.push_back(copy); + } + const auto previous = pass_of(self).states.state(source.Get()); + auto require = [&](auto* r, auto state) { require_state(self, r, state); }; + auto* list = recording(self); + copy->record(list, require, previous); + const LONG trace_frame = gpu_trace_frame; + if (trace_frame && trace_frame != copy->last_trace_frame) { + copy->last_trace_frame = trace_frame; + log("x2w-frame alias copy frame=%ld list=%p source=%p destination=%p title=0x%llx size=%llux%u", + trace_frame, static_cast<void*>(self), static_cast<void*>(source.Get()), static_cast<void*>(destination), + address, info->console.Width, info->console.Height); + } + if (bound) *bound = {source.Get(), destination}; + require(destination, x2w_gpu::texture_read_state(list->GetType())); + static LONG64 recorded; + const auto n = InterlockedIncrement64(&recorded); + const auto from = source->GetDesc().Format, to = destination_format; + static std::atomic<u64> pairs[128][2]{}; + bool first_pair = false; + if (static_cast<UINT>(from) < 128 && static_cast<UINT>(to) < 128) { + auto& seen = pairs[from][to / 64]; + const u64 bit = u64{1} << (to % 64); + if (!(seen.load(std::memory_order_relaxed) & bit)) + first_pair = !(seen.fetch_or(bit, std::memory_order_relaxed) & bit); + } + if (first_pair || (n & (n - 1)) == 0) + log("x2w-gpu packed light GPU copies %lld: title 0x%llx, %llux%u, %zu subresources, format %u to %u", + n, address, info->console.Width, info->console.Height, copy->source_rows.size(), from, to); + return true; +} + +// Slots of recordings that may still run, given back when their fences have passed. +struct Retiring { + std::vector<x2w_vbind::Dynamic> slots; + std::vector<std::pair<ID3D12Fence*, std::uint64_t>> fences; + std::vector<std::shared_ptr<x2w_depth_twins::Twins>> depth_refs; + std::vector<std::shared_ptr<x2w_vmemory::Recording>> memories; + std::vector<std::shared_ptr<x2w_packed_light::Copy>> light_copies; +}; +x2w_vmemory::FaultPages memory_fault_pages; +SRWLOCK retire_lock = SRWLOCK_INIT; +std::vector<Retiring>& retiring() { static std::vector<Retiring> v; return v; } +void release_slots(std::vector<x2w_vbind::Dynamic>& slots) +{ + for (const auto& d : slots) { + gpu_heap_release(d.heap, d.first, d.n); + InterlockedExchangeAdd(&slots_released, static_cast<LONG>(d.n)); + } + slots.clear(); +} +void retire_passed() +{ + std::vector<Retiring> passed; + AcquireSRWLockExclusive(&retire_lock); + auto& r = retiring(); + for (auto it = r.begin(); it != r.end();) { + if (std::all_of(it->fences.begin(), it->fences.end(), [](const auto& f) { return f.first->GetCompletedValue() >= f.second; })) { + passed.push_back(std::move(*it)); + it = r.erase(it); + } else { + ++it; + } + } + ReleaseSRWLockExclusive(&retire_lock); + for (auto& p : passed) { + release_slots(p.slots); + for (const auto& m : p.memories) { + const auto faults = m->read_faults(); + const auto known = memory_fault_pages.report(faults); + if (gpu_drop_trace()) { + static LONG completed, nonempty; + const LONG n = InterlockedIncrement(&completed); + const LONG reports = faults.empty() ? 0 : InterlockedIncrement(&nonempty); + if ((n & (n - 1)) == 0 || (reports && (reports & (reports - 1)) == 0)) + log("x2w-gpu memory feedback: recording %ld pages reported %zu first 0x%x known %zu mapped %zu", + n, faults.size(), faults.empty() ? 0 : faults.front(), known, m->addresses.size()); + } + } + } +} +// The recording ends (reset or release): what it made is forgotten; its slots retire behind its submissions. +void end_recording(GpuListState& s) +{ + if (!s.dynamic.empty() || !s.depth_refs.empty() || !s.light_copies.empty()) { + if (s.submitted.empty()) { + release_slots(s.dynamic); // never submitted: nothing on the GPU reads them + } else { + AcquireSRWLockExclusive(&retire_lock); + retiring().push_back({std::move(s.dynamic), std::move(s.submitted), std::move(s.depth_refs), std::move(s.memories), std::move(s.light_copies)}); + ReleaseSRWLockExclusive(&retire_lock); + } + } + s.dynamic.clear(); + s.trace_request = 0; + s.trace_current.reset(); + s.trace_captures.clear(); + s.depth_refs.clear(); + s.memories.clear(); + s.memory_back.clear(); + s.light_copies.clear(); + s.writable_depth.clear(); + s.submitted.clear(); + s.fresh_tables.clear(); + s.table_constants.clear(); + s.root_srv_slots.clear(); + s.root_uav_slots.clear(); + s.host_heaps[0] = s.host_heaps[1] = nullptr; + s.host_roots[0] = s.host_roots[1] = nullptr; + s.host_pso = nullptr; +} +// Our fence per desktop queue, signalled after a submission that carried a translated recording holding slots. +SRWLOCK fence_lock = SRWLOCK_INIT; +std::unordered_map<ID3D12CommandQueue*, std::pair<ID3D12Fence*, std::uint64_t>>& queue_fences() +{ + static std::unordered_map<ID3D12CommandQueue*, std::pair<ID3D12Fence*, std::uint64_t>> m; + return m; +} + +// ---- heaps ---------------------------------------------------------------------------------------------------------- +struct Bound { + GpuHeapInfo views{}, samplers{}; + x2w_vbind::HeapSpan spans[2]{}; // view heap, sampler heap (start 0: none) +}; +Bound bound_heaps(const GpuListState& s) +{ + Bound b; + for (void* h : s.heaps) { + GpuHeapInfo info{}; + if (!h || !gpu_heap_for(static_cast<Wrapper*>(h), &info) || !info.heap) continue; + (info.sampler ? b.samplers : b.views) = info; + b.spans[info.sampler ? 1 : 0] = {info.title_gpu, info.count, info.sampler}; + } + return b; +} +// The bound heap a handle lies in, and its slot index there. +const GpuHeapInfo* heap_index(const Bound& b, std::uint64_t handle, std::uint32_t* index) +{ + if (b.views.heap) + if (const auto i = b.spans[0].index(handle)) return *index = *i, &b.views; + if (b.samplers.heap) + if (const auto i = b.spans[1].index(handle)) return *index = *i, &b.samplers; + return nullptr; +} +// X2W also accepts inline V# and X2WP records. Their format and payload extend past the token prefix. +bool record_words(const GpuHeapInfo& h, std::uint32_t index, std::uint32_t (&words)[8]) +{ + if (h.sampler || !h.title_cpu || index >= h.count) return false; + const auto* at = reinterpret_cast<const void*>(h.title_cpu + std::uint64_t{index} * abi::view_increment); + static_assert(sizeof(words) == abi::view_increment); + if (!x2w_local::readable(at, sizeof(words))) return false; + std::memcpy(words, at, sizeof(words)); + return true; +} +// ---- window states -------------------------------------------------------------------------------------------------- +// A window is title memory for every kind of read at once: one read state for vertex, index, constant and shader +// reads (so this path does not move a window between read states), unless the list holds it as UAV: one 256 MiB +// window often carries a UAV of the same call, and one state cannot be both (as the old path's window_read_state). +thread_local std::vector<ID3D12Resource*>* memory_bind_reads; +thread_local std::vector<ID3D12Resource*>* memory_bind_writes; +void window_read(Wrapper* self, ID3D12Resource* window) +{ + if (!window) return; + if (memory_bind_reads) memory_bind_reads->push_back(window); + if (pass_of(self).states.state(window) == D3D12_RESOURCE_STATE_UNORDERED_ACCESS) return; + require_state(self, window, x2w_gpu::buffer_read_state(recording(self)->GetType())); +} +void window_write(Wrapper* self, ID3D12Resource* window) +{ + if (window && memory_bind_writes) memory_bind_writes->push_back(window); + if (window) require_state(self, window, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); +} + +// ---- readable: what a shader reads or writes through a view, made ready --------------------------------- +// Buffers: title memory in place, nothing to copy; their window in the state the access needs. Textures the title +// fills (no target, depth or unordered access): uploaded from title memory, as the old compute path does +// (d3d12_compute.inl texture_view). Textures read: both shader-read states, with DEPTH_READ when it is the depth +// target the draw tests; textures written: UNORDERED_ACCESS. +void readable(Wrapper* self, GpuResourceType kind, const GpuViewInfo& view, bool compute, x2w_packed_light::BoundCopy& bound) +{ + const bool write = kind == GpuResourceType::uav; + if (view.buffer) { + x2w_vbind::Found f; + if (!view.title_address || !find(view.title_address, view.bytes ? view.bytes : 1, ~0ull, unknown_read_bytes(), &f)) return; + write ? window_write(self, window_of(f)) : window_read(self, window_of(f)); + return; + } + if (!view.texture || !view.desktop) return; + if (write) { + if (view.kind != GpuViewKind::uav) return; + bound.invalidate(view.desktop); + if (view.depth_twins && view.desktop == view.depth_twins->colour.Get()) { + auto& s = state_of(self); + auto* pair = view.depth_twins.get(); + if (std::find(s.writable_depth.begin(), s.writable_depth.end(), pair) == s.writable_depth.end()) { + if (std::find(s.depth_refs.begin(), s.depth_refs.end(), view.depth_twins) == s.depth_refs.end()) + s.depth_refs.push_back(view.depth_twins); + s.writable_depth.push_back(pair); + const auto before = pass_of(self).states.state(pair->depth.Get()); + pair->copy_colour(recording(self), true, [&](auto* r, auto state) { require_state(self, r, state); }); + require_state(self, pair->depth.Get(), before); + } + } + window_write(self, view.desktop); + return; + } + if (view.kind != GpuViewKind::srv) return; + ID3D12Resource* texture = view.desktop; + Wrapper* resource = as_wrapper(view.title_resource); + const D3D12_RESOURCE_DESC rd = texture->GetDesc(); + if (bc_bind_trace::enabled() && ((rd.Format >= DXGI_FORMAT_BC1_TYPELESS && rd.Format <= DXGI_FORMAT_BC5_SNORM) || + (rd.Format >= DXGI_FORMAT_BC6H_TYPELESS && rd.Format <= DXGI_FORMAT_BC7_UNORM_SRGB))) + bc_bind_trace::read(self, resource, texture, rd); + if (resource && resource->own().kind == resource_kind && + !(rd.Flags & (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))) { + warm_texture(resource); + memcut_revive(resource); + const auto alias = prepare_packed_light(self, resource, texture, &bound); + if (!alias) bound.invalidate(texture); + if (alias ? *alias : upload_texture(self, resource, texture)) InterlockedIncrement(&textures_uploaded); + } + D3D12_RESOURCE_STATES state = x2w_gpu::texture_read_state(recording(self)->GetType()); + if (!compute) require_sampled(self, texture, state); + else require_state(self, texture, state); +} + +// ---- constant buffers: the console wants 16-byte alignment, the host 256 --------------------------------------------------- +bool defer_table_cbv() +{ + static const bool on = x2w_local::env_on("X2W_GPU_DEFER_TABLE_CBV"); + return on; +} +// A copy of the title's constants in the upload ring (record time, see the header): 256-byte steps, the tail past the +// readable bytes zeroed. The ring places at 512 bytes (reserve_upload_ring), which covers a CBV's 256. 0: no copy. +D3D12_GPU_VIRTUAL_ADDRESS constant_copy(std::uint64_t address, std::uint64_t bytes, ID3D12Resource** buffer, std::uint32_t* size, + x2w_gpu::TableConstants* deferred = nullptr) +{ + const std::size_t readable = readable_window(address, static_cast<std::size_t>((std::min<std::uint64_t>)(bytes, 1ull << 16))); + if (!readable) { + InterlockedIncrement(&cbv_copy_failed); + return 0; + } + std::uint64_t offset = 0; + const std::size_t want = x2w_vbind::constant_view_bytes(readable); + RingTag tag; + unsigned char* dest = reserve_upload_ring(want, &offset, buffer, deferred ? &tag : nullptr); + if (!dest || !*buffer || (offset & 255)) { + InterlockedIncrement(&cbv_copy_failed); + return 0; + } + const void* source = reinterpret_cast<const void*>(address); + if (deferred) source = deferred->remember(source, readable, {tag.chunk, tag.generation, offset}); + std::memcpy(dest, source, readable); + std::memset(dest + readable, 0, want - readable); + InterlockedIncrement(&cbv_copies); + *size = static_cast<std::uint32_t>(want); + return (*buffer)->GetGPUVirtualAddress() + offset; +} + +bool take_dynamic(GpuListState& s, GpuHostHeap* heap, std::uint32_t n, std::uint32_t* first) +{ + if (!gpu_heap_dynamic(heap, n, first)) return false; + s.dynamic.push_back({heap, *first, n}); + return true; +} + +// ---- tables ------------------------------------------------------------------------------ +UINT64 trace_min_width() +{ + static const auto width = gpu_pipeline_setting("X2W_TRACE_TARGET_MIN_WIDTH", 0, D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + return width; +} + +bool trace_pass(Wrapper* self, bool compute) +{ + if (compute || !trace_min_width()) return true; + const Pass& pass = pass_of(self); + return std::any_of(pass.targets, pass.targets + (std::min)(pass.target_count, 8u), [](ID3D12Resource* target) { + return target && target->GetDesc().Width >= trace_min_width(); + }); +} + +bool trace_stage_matches(const char* key) +{ + const auto filter = gpu_trace_stage_key(); + if (!filter || (key && _stricmp(filter->c_str(), key) == 0)) return true; + const auto second = std::atomic_load(&gpu_scene_second_override); + return second && key && !_stricmp(second->c_str(), key); +} + +bool trace_tables(Wrapper* self, bool compute, const char* key) +{ + return gpu_trace_frame && trace_stage_matches(key) && gpu_trace_per_kind[compute ? 1 : 0] < 64 && trace_pass(self, compute); +} + +void light_binding(GpuListState& s, UINT slot, UINT offset, GpuResourceType kind, const GpuViewInfo& view, + GpuHostHeap* heap, UINT index) +{ + using x2w_gpu::ambient::Role; + if (s.light_role == Role::none || !view.texture || !view.desktop) return; + const auto desc = view.desktop->GetDesc(); + if (s.light_role == Role::resolve && slot == 0 && offset == 464 && kind == GpuResourceType::srv && + view.kind == GpuViewKind::srv && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D) { + s.light_views.depth = gpu_heap_gpu_handle(heap, index); + s.light_depth_width = desc.Width; + s.light_depth_height = desc.Height; + } + const bool volume = s.light_role == Role::air; + const UINT output = volume ? 32 : s.light_role == Role::radiance ? 16 : 176; + const auto format = s.light_role == Role::resolve ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R11G11B10_FLOAT; + if (slot != 1 || offset != output || kind != GpuResourceType::uav || view.kind != GpuViewKind::uav || + desc.Format != format || desc.Dimension != (volume ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : D3D12_RESOURCE_DIMENSION_TEXTURE2D)) return; + s.light_views.image = gpu_heap_gpu_handle(heap, index); + s.light_views.width = UINT(desc.Width); + s.light_views.height = desc.Height; + s.light_views.slices = desc.DepthOrArraySize; + if (s.light_role != Role::resolve) s.light_views.depth = s.light_views.image; +} + +void finish_light(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + using namespace x2w_gpu::ambient; + auto& s = state_of(self); + if (s.light_role == Role::none || !s.light_views.depth.ptr || !s.light_views.image.ptr || + (s.light_role == Role::resolve && (s.light_depth_width != s.light_views.width || + s.light_depth_height != s.light_views.height))) return; + static std::mutex lock; + static std::unordered_map<ID3D12Device*, std::unique_ptr<x2w_gpu::ambient::Pass>> passes; + std::lock_guard<std::mutex> guard(lock); + auto* device = device_of(the_device); + auto& pass = passes[device]; + if (!pass) pass = std::make_unique<x2w_gpu::ambient::Pass>(); + if (pass->record(device, list, s.light_role, indirect_light_settings(), s.light_views)) { + s.host_roots[1] = nullptr; + s.host_pso = nullptr; + static LONG calls[4]{}; + const auto n = InterlockedIncrement(&calls[unsigned(s.light_role)]); + if ((n & (n-1)) == 0) log("x2w-gpu indirect light recorded role=%u count=%ld size=%ux%u", + unsigned(s.light_role), n, s.light_views.width, s.light_views.height); + } else if (FAILED(pass->error())) { + static LONG errors; + if (InterlockedIncrement(&errors) == 1) log("x2w-gpu indirect light init HRESULT %08lx: %s", pass->error(), pass->diagnostic().c_str()); + } +} + +void inventory_uav_binding(Wrapper* self, const char* shader, UINT slot, UINT offset, const GpuViewInfo& view) +{ + static const bool enabled = x2w_local::env_on("X2W_TRACE_PASS_INVENTORY"); + const LONG frame = gpu_trace_frame; + if (!frame || !enabled || !view.desktop) return; + static std::mutex mutex; + static LONG observed{}; + static std::set<std::tuple<ID3D12Resource*, const char*, UINT, UINT>> seen; + { + std::lock_guard guard(mutex); + if (frame < observed) return; + if (frame != observed) { observed = frame; seen.clear(); } + if (seen.size() >= 4096 || !seen.emplace(view.desktop, shader, slot, offset).second) return; + } + const auto d = view.desktop->GetDesc(); + log("x2w-frame UAV binding frame=%ld list=%p shader=%s slot=%u offset=%u resource=%p format=%u size=%llux%u", + frame, static_cast<void*>(self), shader, slot, offset, static_cast<void*>(view.desktop), UINT(view.view_format), d.Width, d.Height); +} + +// Report the materialized descriptor, including dynamically indexed texture slots. +void trace_texture_binding(Wrapper* self, bool compute, const char* key, UINT slot, UINT offset, + GpuResourceType kind, const GpuViewInfo& view) +{ + if (!view.texture) return; + if (gpu_trace_frame && compute && kind == GpuResourceType::uav && view.kind == GpuViewKind::uav) + inventory_uav_binding(self, key, slot, offset, view); + if (!compute && pixel_capture_on() && compute_capture_pending.load()) { + auto& s = state_of(self); + if (s.pixel_capture_shader && !std::strcmp(s.pixel_capture_shader->key, key) && view.desktop && + kind == GpuResourceType::srv && view.kind == GpuViewKind::srv && s.pixel_bindings.size() < 40) { + const auto& bindings = s.pixel_bindings; + if (std::none_of(bindings.begin(), bindings.end(), [&](const auto& entry) { return entry.slot == slot && entry.offset == offset; })) + s.pixel_bindings.push_back({view.desktop, slot, offset, false, false, view.first_mip, view.first_slice, view.view_format, view.plane}); + } + } + if (compute && compute_capture_on() && compute_capture_pending.load()) { + auto& s = state_of(self); + if (s.trace_request && s.trace_request == compute_capture_pending.load() && + ((kind == GpuResourceType::uav && view.kind == GpuViewKind::uav) || + (kind == GpuResourceType::srv && view.kind == GpuViewKind::srv))) + { + using Role = x2w_gpu::ambient::Role; + auto* pipeline = static_cast<Wrapper*>(s.pipeline); + const auto* entry = pipeline ? static_cast<const GpuPipelineEntry*>(pipeline->own().gpu[0]) : nullptr; + const auto role = entry ? entry->light_role : Role::none; + const bool priority = (role == Role::resolve && ((slot == 0 && offset == 464) || (slot == 1 && offset == 176))) || + (role == Role::radiance && slot == 1 && offset == 16) || + (role == Role::air && slot == 1 && offset == 32); + static const bool wide = x2w_local::env_on("X2W_TRACE_COMPUTE_WIDE"); + s.trace_bindings.add({view.desktop, slot, offset, kind == GpuResourceType::uav, false, + view.first_mip, view.first_slice, view.view_format, view.plane}, priority, wide); + } + } + if (!gpu_trace_frame || !gpu_trace_stage_key() || !trace_tables(self, compute, key)) return; + if (InterlockedIncrement(&gpu_trace_bindings) > 256) return; + const auto d = view.desktop ? view.desktop->GetDesc() : D3D12_RESOURCE_DESC{}; + log("x2w-frame resolved texture frame=%ld list=%p shader=%s slot=%u offset_dwords=%u access=%s " + "resource=%p format=%u size=%llux%u depth_or_array=%u dim=%u mips=%u", gpu_trace_frame, static_cast<void*>(self), key, slot, offset, + kind == GpuResourceType::uav ? "UAV" : "SRV", static_cast<void*>(view.desktop), UINT(d.Format), d.Width, d.Height, UINT(d.DepthOrArraySize), UINT(d.Dimension), UINT(d.MipLevels)); +} + +// What a stage reads through tables: entries mirrored in place, or a fresh table in dynamic slots for tables with a CBV +// and tables past the host heap. `made` gets the fresh tables' byte offsets; false: one found no slots (drop the call). +bool tables(Wrapper* self, GpuListState& s, const Bound& b, const x2w_gpu::GpuShader& sh, bool compute, + std::vector<x2w_vbind::MadeTable>& made, x2w_packed_light::BoundCopy& bound) +{ + const auto plan = x2w_vbind::plan_tables(s.roots, compute, sh.used.data, sh.used.count, sh.root_indexed_views.data, + sh.root_indexed_views.count, b.spans, 2, + [](const x2w_vbind::HeapSpan& h) { return h.count; }); + if (!plan.skipped.empty()) InterlockedExchangeAdd(&tables_skipped, static_cast<LONG>(plan.skipped.size())); + for (const std::size_t i : plan.mirrored) { + const auto& u = sh.used[static_cast<std::uint32_t>(i)]; + const x2w_gpu::GpuRoot* r = s.roots.at(compute, u.slot); + if (!r || r->kind != GpuRootKind::table) continue; + const std::uint64_t handle = r->handle + std::uint64_t{u.table_offset_dwords} * 4; + std::uint32_t index = 0; + const GpuHeapInfo* h = heap_index(b, handle, &index); + if (!h) { + InterlockedIncrement(&foreign_tables); + continue; + } + GpuViewInfo view{}; + const bool mirrored = gpu_heap_mirror(h->heap, index, handle, true, &view); + if (mirrored && !h->sampler) { + light_binding(s, u.slot, u.table_offset_dwords, u.kind, view, h->heap, index); + trace_texture_binding(self, compute, sh.key, u.slot, u.table_offset_dwords, u.kind, view); + readable(self, u.kind, view, compute, bound); + } + if (trace_tables(self, compute, sh.key)) + log("x2w-frame table %s slot=%u offset=%u heap-index=%u mirrored=%d desktop=%p kept=%p", + sh.key, u.slot, u.table_offset_dwords, index, int(mirrored), static_cast<void*>(view.desktop), + static_cast<void*>(gpu_heap_kept_at(h->heap, index))); + } + for (const auto& f : plan.fresh) { + const GpuHeapInfo& h = b.views; + const std::uint32_t title_first = *b.spans[0].index(f.table); + const auto entry = [&](std::uint32_t k) -> const x2w_gpu::GpuUsedResource* { + for (const auto& u : sh.used) + if (x2w_vbind::in_table(u) && u.slot == f.slot && u.table_offset_dwords / 8 == k) return &u; + return nullptr; + }; + const auto selected = [&](std::uint32_t k) { return std::binary_search(f.selected.begin(), f.selected.end(), k); }; + const auto kind_of = [&](std::uint32_t k, const GpuViewInfo& view) { + const auto* u = entry(k); + return u ? u->kind : view.kind == GpuViewKind::uav ? GpuResourceType::uav : GpuResourceType::srv; + }; + // Key the table by its address and the first words of its descriptor records. + auto* mirror = gpu_detail_heap::host_of(h.heap); + std::vector<std::pair<std::uint32_t, gpu_mirror::View>> late_views; + const auto late_view = [&](std::uint32_t k) -> const gpu_mirror::View* { + const auto it = std::lower_bound(late_views.begin(), late_views.end(), k, + [](const auto& item, std::uint32_t offset) { return item.first < offset; }); + return it != late_views.end() && it->first == k ? &it->second : nullptr; + }; + const auto table_view = [&](std::uint32_t k, GpuViewInfo& info) { + const auto* v = late_view(k); + if (!v) return gpu_heap_view_at(h.heap, title_first + k, &info); + gpu_detail_heap::view_info(*v, &info); + return info.kind != GpuViewKind::none; + }; + x2w_vbind::RecordHash hash; + for (std::uint32_t k = 0; k < f.n; ++k) { + std::uint32_t w[8]{}; + record_words(h, title_first + k, w); + hash.add_record(w); + if (x2w_late_texture::marker(w[0]) && mirror) { + auto& texture = late_views.emplace_back(k, gpu_mirror::View{}).second; + mirror->view_at(title_first + k, w, texture); + texture.retained = texture.resource; + const auto host = reinterpret_cast<std::uint64_t>(texture.resource); + hash.add(k, static_cast<std::uint32_t>(texture.key), static_cast<std::uint32_t>(texture.key >> 32)); + hash.add(k, static_cast<std::uint32_t>(host), static_cast<std::uint32_t>(host >> 32)); + } + const auto* u = entry(k); + if (u && u->kind == GpuResourceType::cbv) hash.add(k, 0, 0x434256); + } + const x2w_vbind::FreshKey key{f.table, f.n, hash.value}; + if (const auto known = s.fresh_tables.find(key); known != s.fresh_tables.end()) { + // Made before in this list: what it reads made ready again (states may have moved since). + for (std::uint32_t k = 0; k < f.n; ++k) { + const auto* u = entry(k); + if ((u && u->kind == GpuResourceType::cbv) || (!u && !selected(k))) continue; + GpuViewInfo view{}; + if (!table_view(k, view)) continue; + if (view.texture) view.desktop = gpu_heap_kept_at(h.heap, known->second + k); + if (trace_tables(self, compute, sh.key) && u) + log("x2w-frame fresh cached %s slot=%u source=%u dynamic=%u kind=%u address=%llx kept=%p", + sh.key, f.slot, title_first + k, known->second + k, static_cast<unsigned>(view.kind), + view.title_address, static_cast<void*>(gpu_heap_kept_at(h.heap, known->second + k))); + light_binding(s, f.slot, k * 8, kind_of(k, view), view, h.heap, known->second + k); + trace_texture_binding(self, compute, sh.key, f.slot, k * 8, kind_of(k, view), view); + readable(self, kind_of(k, view), view, compute, bound); + } + made.push_back({f.slot, known->second * abi::view_increment}); + continue; + } + std::uint32_t first = 0; + if (!take_dynamic(s, h.heap, f.n, &first)) { + made.push_back({f.slot, UINT32_MAX}); + continue; + } + s.fresh_tables.emplace(key, first); + // The whole range: a shader may index past the entries it names (descriptor arrays). + for (std::uint32_t k = 0; k < f.n; ++k) { + const std::uint32_t index = first + k; + GpuViewInfo view{}; + if (!table_view(k, view) || view.kind == GpuViewKind::none) { + gpu_heap_make_null(h.heap, index); + if (const auto* use = entry(k)) { + InterlockedIncrement(&table_views_missing); + if (gpu_drop_trace()) { + static LONG samples; + const LONG n = InterlockedIncrement(&samples); + if (n <= 16 || (n & (n - 1)) == 0 || trace_tables(self, compute, sh.key)) { + std::uint32_t w[8]{}; + const bool read = record_words(h, title_first + k, w); + const bool empty = std::all_of(std::begin(w), std::end(w), [](UINT word) { return word == 0; }); + const char* form = !read ? "unreadable" : empty ? "empty" : + w[0] == gpu_mirror::token_magic ? "captured" : "inline"; + log("x2w-gpu missing table view: frame=%ld count=%ld key=%s slot=%u offset=%u kind=%u title-index=%u form=%s words=%08x,%08x,%08x,%08x,%08x,%08x,%08x,%08x", + frame_number, n, sh.key, f.slot, use->table_offset_dwords, unsigned(use->kind), + title_first + k, form, w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]); + if (w[0] == gpu_mirror::token_magic && (w[4] || w[5])) { + gpu_mirror::Record r; + const bool have = gpu_detail_heap::env_record(nullptr, w[1], &r); + Wrapper* owner = have ? as_wrapper(reinterpret_cast<const void*>(r.resource)) : nullptr; + UINT fields[2]{}; + if (r.desc_bytes >= sizeof(fields)) std::memcpy(fields, r.desc, sizeof(fields)); + log("x2w-gpu unresolved captured view: key=%s id=%x recorded=%d original-created=%d wrapper=%p refs=%ld host=%p desc-bytes=%u format=%u dimension=%u", + sh.key, w[1], int(have), int(have && r.materialized), owner, + owner ? InterlockedCompareExchange(&owner->own().refs, 0, 0) : -1L, + owner ? owner->own().real : nullptr, r.desc_bytes, fields[0], fields[1]); + } + } + } + } + continue; + } + const auto* usage = entry(k); + // A console buffer record also describes the byte range of a table constant. + // The desktop shader accesses that slot with a CBV-typed heap handle. + const bool constant_buffer = usage && usage->kind == GpuResourceType::cbv && + view.kind == GpuViewKind::srv && view.buffer; + if (view.kind == GpuViewKind::cbv || constant_buffer) { + ID3D12Resource* buffer = nullptr; + std::uint32_t size = 0; + const D3D12_GPU_VIRTUAL_ADDRESS gpu = constant_copy(view.title_address, view.bytes, &buffer, &size, + defer_table_cbv() ? &s.table_constants : nullptr); + if (!gpu) { + InterlockedIncrement(&cbv_null); + gpu_heap_make_null(h.heap, index); + continue; + } + gpu_heap_constant_at(h.heap, index, buffer, gpu, size); + if (trace_tables(self, compute, sh.key)) + log("x2w-frame fresh constant %s slot=%u source=%u dynamic=%u address=%llx bytes=%llu copied=%u", + sh.key, f.slot, title_first + k, index, view.title_address, view.bytes, size); + continue; + } + // The title's view, made in the dynamic slot. + std::uint32_t words[8]{}; + GpuViewInfo made_view{}; + bool materialized = false; + if (const auto* resolved = late_view(k)) { + const auto& texture = *resolved; + std::copy(texture.placement.begin(), texture.placement.end(), words); + mirror->make_at(index, texture); + made_view = view; + made_view.desktop = mirror->kept_at(index); + materialized = true; + } else { + materialized = record_words(h, title_first + k, words) && + gpu_heap_make_listed(h.heap, title_first + k, words, index, &made_view); + } + if (trace_tables(self, compute, sh.key) && entry(k)) + log("x2w-frame fresh %s slot=%u source=%u dynamic=%u kind=%u prefix=%08x w3=%08x made=%d address=%llx kept=%p", + sh.key, f.slot, title_first + k, index, static_cast<unsigned>(view.kind), words[0], words[3], + int(materialized), view.title_address, static_cast<void*>(gpu_heap_kept_at(h.heap, index))); + if (!materialized) { + gpu_heap_make_null(h.heap, index); + continue; + } + if (entry(k) || selected(k)) { + light_binding(s, f.slot, k * 8, kind_of(k, made_view), made_view, h.heap, index); + trace_texture_binding(self, compute, sh.key, f.slot, k * 8, kind_of(k, made_view), made_view); + readable(self, kind_of(k, made_view), made_view, compute, bound); + } + } + made.push_back({f.slot, first * abi::view_increment}); + } + return std::none_of(made.begin(), made.end(), [](const x2w_vbind::MadeTable& m) { return m.offset == UINT32_MAX; }); +} + +// ---- root views ------------------------------------------------------------ +// A root SRV as a one-view table: a raw view from `address` to the end of its title buffer (from the 16 bytes below +// when the shader adds the bias), or a null view. One dynamic slot per address per list. +bool root_srv_table(Wrapper* self, GpuListState& s, const Bound& b, std::uint64_t address, bool biased, std::uint32_t* index, + std::uint32_t* bias) +{ + *bias = 0; + if (!b.views.heap) return false; + const auto key = std::make_pair(static_cast<const void*>(b.views.heap), address | (std::uint64_t{biased} << 63)); + if (const auto known = s.root_srv_slots.find(key); known != s.root_srv_slots.end()) { + *index = known->second.index; + *bias = known->second.bias; + window_read(self, known->second.window); + return true; + } + if (!take_dynamic(s, b.views.heap, 1, index)) return false; + x2w_vbind::RootSlot& slot = s.root_srv_slots.emplace(key, x2w_vbind::RootSlot{*index, nullptr, 0}).first->second; + x2w_vbind::Found f; + x2w_vbind::RawWindow raw; + if (address && find(address, 1, root_srv_limit(), unknown_read_bytes(), &f) && x2w_vbind::raw_window(f.offset, f.left, biased, &raw)) { + if (f.cut_by_window) InterlockedIncrement(&root_srv_cut); + gpu_heap_raw_at(b.views.heap, *index, window_of(f), raw.first, raw.bytes); + // Reuse the bias from the window offset at which the view was made. + *bias = slot.bias = raw.bias; + slot.window = window_of(f); + window_read(self, slot.window); + } else { + InterlockedIncrement(&root_srv_null); + gpu_heap_null_raw_at(b.views.heap, *index); + } + return true; +} +// A root UAV as a one-view table: a raw UAV from the 16 bytes below `address` to the end of its title buffer, or a null +// view (no address, memory no title buffer record holds, a window shaders cannot write). +bool root_uav_table(Wrapper* self, GpuListState& s, const Bound& b, std::uint64_t address, std::uint32_t* index, std::uint32_t* bias) +{ + *bias = 0; + if (!b.views.heap) return false; + const auto key = std::make_pair(static_cast<const void*>(b.views.heap), address); + if (const auto known = s.root_uav_slots.find(key); known != s.root_uav_slots.end()) { + *index = known->second.index; + *bias = known->second.bias; + window_write(self, known->second.window); + return true; + } + if (!take_dynamic(s, b.views.heap, 1, index)) return false; + x2w_vbind::RootSlot& slot = s.root_uav_slots.emplace(key, x2w_vbind::RootSlot{*index, nullptr, 0}).first->second; + x2w_vbind::Found f; + // No allowance for memory no title buffer record holds (unknown_most 0): a write there could land anywhere. + const bool found = address && find(address, 1, root_uav_limit(), 0, &f); + if (address && !found) InterlockedIncrement(f.known_extent ? &root_uav_null : &root_uav_unknown); + x2w_vbind::RawWindow raw; + if (found && x2w_vbind::raw_window(f.offset, f.left, true, &raw) && + (window_of(f)->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + if (f.cut_by_window) InterlockedIncrement(&root_uav_cut); + gpu_heap_raw_uav_at(b.views.heap, *index, window_of(f), raw.first, raw.bytes); + *bias = slot.bias = raw.bias; + slot.window = window_of(f); + window_write(self, slot.window); + } else { + gpu_heap_null_raw_uav_at(b.views.heap, *index); + } + return true; +} +// A root view bound as a root descriptor (X2W_SHADERCFG_ROOT_SRV_DIRECT=1 pipelines, and root CBVs): its GPU address, from the +// 16 bytes below for a biased SRV or a UAV, with the bias it then needs. 0: nothing to bind. +D3D12_GPU_VIRTUAL_ADDRESS root_direct(Wrapper* self, std::uint64_t address, bool write, bool biased, std::uint32_t* bias) +{ + *bias = 0; + x2w_vbind::Found f; + if (!address || !find(address, 1, write ? root_uav_limit() : root_srv_limit(), write ? 0 : unknown_read_bytes(), &f)) return 0; + write ? window_write(self, window_of(f)) : window_read(self, window_of(f)); + const D3D12_GPU_VIRTUAL_ADDRESS gpu = window_of(f)->GetGPUVirtualAddress() + f.offset; + if (!write && !biased) return gpu; + *bias = static_cast<std::uint32_t>(f.offset & 15); + return gpu - *bias; +} +// A root CBV: in place when 256-aligned (64 KiB at most, cut at its buffer's end), else a copy in the upload ring. +D3D12_GPU_VIRTUAL_ADDRESS root_cbv(Wrapper* self, std::uint64_t address) +{ + x2w_vbind::Found f; + if (!address || !find(address, 1, 1ull << 16, unknown_read_bytes(), &f)) { + InterlockedIncrement(&cbv_null); + return 0; + } + const D3D12_GPU_VIRTUAL_ADDRESS gpu = window_of(f)->GetGPUVirtualAddress() + f.offset; + if (gpu % 256 == 0) { + window_read(self, window_of(f)); + return gpu; + } + ID3D12Resource* buffer = nullptr; + std::uint32_t size = 0; + return constant_copy(address, x2w_vbind::root_cbv_bytes(f.left), &buffer, &size); +} + +// ---- the bind sequence ----------------------------------------------------------------------------- +bool shader_reads_memory(const x2w_gpu::GpuShader& sh) +{ + for (const auto s : sh.root_srvs) + if (s == abi::slot_memory) return true; + for (const auto u : sh.root_uavs) + if (u == abi::slot_faults) return true; + return false; +} +bool biased_view(const x2w_gpu::GpuShader& sh, std::uint32_t slot) +{ + for (const auto& u : sh.user_data) + if (u.slot == slot && u.root == GpuRootType::other && u.other == abi::user_view_bias) return true; + return false; +} + +u64 buffer_address(const Bound& b, const GpuListState& s, bool compute, UINT slot, UINT dword) +{ + const auto* r = s.roots.at(compute, slot); + if (!r || r->kind != GpuRootKind::table) return 0; + UINT index = 0; + const auto* heap = heap_index(b, r->handle + u64{dword} * 4, &index); + return heap && !heap->sampler ? gpu_heap_title_address_at(heap->heap, index) : 0; +} + +bool memory_window(u64 at, ID3D12Resource** resource, u64* offset) +{ + using Location = BOOL(WINAPI*)(const void*, HANDLE*, ULONG64*); + static const auto location = reinterpret_cast<Location>(GetProcAddress(GetModuleHandleW(L"xmem.dll"), "x2w_xmem_gpu_location")); + HANDLE section = nullptr; + u64 where = 0, start = 0, end = 0; + if (!(location && location(reinterpret_cast<const void*>(at), §ion, &where)) && + !(known_private(at, &start, &end) && end - at >= x2w_vmemory::page_bytes)) { + if (!builder_memory_on()) return false; + std::lock_guard<std::mutex> guard(builder_upload_lock); + if (std::none_of(builder_upload_blocks.begin(), builder_upload_blocks.end(), + [&](u64 base) { return at >= base && at - base <= (64ull << 20) - x2w_vmemory::page_bytes; })) return false; + } + return desktop_range(at, x2w_vmemory::page_bytes, resource, offset); +} + +enum class MemoryRefusal { store, heap, allocation, overlapping_read, output, arena_input, directory_capacity, descriptor_capacity, count }; +bool refuse_memory(const x2w_gpu::GpuShader& sh, MemoryRefusal reason) +{ + static constexpr const char* names[] = {"address-store", "view-heap", "directory-allocation", + "window-also-bound-for-read", "unmapped-declared-uav", "arena-input-or-capacity", "live-directory-budget", "dynamic-descriptor-slots"}; + static LONG hits[unsigned(MemoryRefusal::count)]{}; + const LONG n = InterlockedIncrement(&hits[unsigned(reason)]); + if (n <= 4 || (n & (n - 1)) == 0) + log("x2w-gpu memory refusal: frame=%ld reason=%s count=%ld key=%s", frame_number, names[unsigned(reason)], n, sh.key); + return drop(drop_memory_shader); +} + +#include "gpu_memory_store.inl" + +x2w_vmemory::Recording* memory_ready(Wrapper* self, ID3D12GraphicsCommandList* list, GpuListState& s, + const Bound& b, const x2w_gpu::GpuShader& shader, + std::vector<x2w_vmemory::CopyBack>& pending) +{ + // Declared root UAV instructions can lower to a raw store through the directory + // even with stores_by_address=false. Read-only directory entries cannot serve them. + const bool root_store = shader.stores && std::any_of(shader.root_uavs.begin(), shader.root_uavs.end(), + [](auto slot) { return slot != abi::slot_faults; }); + const bool writes = root_store || shader.builder || shader.stores_by_address; + static const bool cpu_pages = x2w_local::env_on("X2W_GPU_MEMORY_CPU_PAGES"); + const bool arena = writes ? builder_memory_on() && directory_only_builder(shader) : cpu_pages || builder_memory_on(); + if (!b.views.heap || (writes && !arena)) { + refuse_memory(shader, b.views.heap ? MemoryRefusal::store : MemoryRefusal::heap); + return nullptr; + } + x2w_vmemory::Recording* m = nullptr; + for (auto& it : s.memories) if (it->heap == b.views.heap && it->writable_mode == writes) m = it.get(); + if (!m) { + auto created = std::make_shared<x2w_vmemory::Recording>(); + bool at_capacity = false; + if (!created->create(device_of(the_device), &at_capacity)) { + refuse_memory(shader, at_capacity ? MemoryRefusal::directory_capacity : MemoryRefusal::allocation); + return nullptr; + } + if (!take_dynamic(s, b.views.heap, x2w_vmemory::slots, &created->base)) { + refuse_memory(shader, MemoryRefusal::descriptor_capacity); + return nullptr; + } + created->heap = b.views.heap; + created->writable_mode = writes; + gpu_heap_null_raw_uav_at(created->heap, created->base); + s.memories.push_back(created); + m = created.get(); + } + m->restore_read_aliases(list, [&](auto* r, auto state) { require_state(self, r, state); }); + if (arena) { + if (builder_pages(self,list,s,b,shader,*m,pending)) return m; + refuse_memory(shader, MemoryRefusal::arena_input); + return nullptr; + } + const auto page = [&](UINT number) { + m->map(list, number, memory_window, + [&](UINT index, auto* w, UINT64 size) { gpu_heap_raw_uav_at(m->heap, index, w, 0, size); }, + [&](auto* r, auto state) { require_state(self, r, state); }); + }; + const auto span = [&](u64 at, u64 len) { + if (at < (1ull << 32) || at >= (u64{abi::memory_pages - 1} << 16)) return; + const auto first = at >> 16, last = (at + len - 1) >> 16; + if (m->ranges.insert((first << 32) | last).second) + for (auto n = first; n <= last; ++n) page(UINT(n)); + }; + for (const auto& root : s.roots.compute) { + if (shader.builder && x2w_vbind::is_view(root.kind)) + span(root.address, root.kind == GpuRootKind::uav ? 4ull << 20 : 256ull << 10); + if (root.kind != GpuRootKind::constants) continue; + for (size_t i = 0; i < root.dwords.size(); ++i) { + const UINT lo = root.dwords[i]; + if (i + 1 < root.dwords.size() && lo >= 65536 && root.dwords[i + 1] >= 1 && root.dwords[i + 1] <= 31) + span((u64{root.dwords[i + 1]} << 32) | lo, 1); + if (shader.builder && lo >= 0x01000000 && lo < 0x20000000) span(u64{lo} << 8, 1); + } + } + for (const auto& u : shader.user_data) + if (u.root == GpuRootType::other && u.other == abi::user_view_address) + span(buffer_address(b, s, true, u.slot, u.dword), 256ull << 10); + if (!m->faults_seeded) { + memory_fault_pages.seed(frame_number, [&](UINT n) { page(n); return m->addresses.count(n) != 0; }); + m->faults_seeded = true; + } + return m; +} + +bool bind(Wrapper* self, ID3D12GraphicsCommandList* l, GpuListState& s, const GpuPipeline& p, bool compute) +{ + x2w_packed_light::BoundCopy bound_copy; + const Bound b = bound_heaps(s); + static const bool lazy = x2w_local::env_on("X2W_GPU_LAZY_DETILE"); + if (lazy && b.views.heap) { + static gpu_mirror::LazyBudget budget; + if (auto* heap = gpu_detail_heap::host_of(b.views.heap)) heap->warm_lazy(self, frame_number, budget); + } + x2w_vmemory::Recording* memory = nullptr; + std::vector<x2w_vmemory::CopyBack> pending; + bool needs_views = false; + for (std::uint32_t i = 0; i < p.stage_count; ++i) { + const auto& st = p.stages[i]; + if (!st.shader) return drop(drop_no_pipeline); + if (shader_reads_memory(*st.shader)) { + static const bool on = x2w_local::env_on("X2W_GPU_MEMORY_READS"); + if (!on || !compute || p.stage_count != 1) return drop(drop_memory_shader); + if (!(memory = memory_ready(self, l, s, b, *st.shader, pending))) return false; + } + needs_views |= std::any_of(st.root_srvs.begin(), st.root_srvs.end(), [](const auto& r) { return r.table; }) || + std::any_of(st.root_uavs.begin(), st.root_uavs.end(), [](const auto& r) { return r.table; }); + } + // Borrow a view heap when the title has none bound. + if (needs_views && !b.views.heap) return drop(drop_no_view_heap); + std::vector<ID3D12Resource*> reads, writes; + struct ReadScope { + bool enabled; + ReadScope(bool on, std::vector<ID3D12Resource*>& read, std::vector<ID3D12Resource*>& write) : enabled(on) { + if (enabled) { memory_bind_reads = &read; memory_bind_writes = &write; } + } + ~ReadScope() { if (enabled) { memory_bind_reads = nullptr; memory_bind_writes = nullptr; } } + } reading(memory != nullptr, reads, writes); + // Heaps first: a root signature with directly indexed heaps must be set after them. + ID3D12DescriptorHeap* heaps[2]{}; + UINT n = 0; + if (b.views.heap) heaps[n++] = b.views.host ? b.views.host : gpu_heap_host(b.views.heap); + if (b.samplers.heap) heaps[n++] = b.samplers.host ? b.samplers.host : gpu_heap_host(b.samplers.heap); + if (!b.samplers.heap) InterlockedIncrement(&missing_sampler_heap); + else { + static LONG shown; + if (first_calls(shown, 1)) log("x2w-gpu bind: title sampler heap bound before %s root signature", compute ? "compute" : "graphics"); + } + if (!bind_cache() || s.host_heaps[0] != heaps[0] || s.host_heaps[1] != heaps[1]) { + if (n) l->SetDescriptorHeaps(n, heaps); + s.host_heaps[0] = heaps[0]; + s.host_heaps[1] = heaps[1]; + s.host_roots[0] = s.host_roots[1] = nullptr; + } + if (!bind_cache() || s.host_roots[compute] != p.root) { + if (compute) l->SetComputeRootSignature(p.root); + else l->SetGraphicsRootSignature(p.root); + s.host_roots[compute] = p.root; + } + if (!bind_cache() || s.host_pso != p.pso) { + l->SetPipelineState(p.pso); + s.host_pso = p.pso; + } + for (std::uint32_t i = 0; i < p.stage_count; ++i) { + const auto& st = p.stages[i]; + const x2w_gpu::GpuShader& sh = *st.shader; + std::vector<x2w_vbind::MadeTable> made; + if (!tables(self, s, b, sh, compute, made, bound_copy)) return drop(drop_no_slots); + // Root views before the user data, so the bias each word carries is the one bound. + std::vector<x2w_vbind::BoundBias> biases; + struct Table { std::uint32_t param, index; }; + struct Direct { std::uint32_t param; D3D12_GPU_VIRTUAL_ADDRESS gpu; int kind; }; // 0 CBV, 1 SRV, 2 UAV + std::vector<Table> view_tables; + std::vector<Direct> directs; + for (const auto& rs : st.root_cbvs) { + const x2w_gpu::GpuRoot* r = s.roots.at(compute, rs.title); + if (!r || !x2w_vbind::is_view(r->kind)) continue; // "a shader reads a root view the title did not set" + if (const auto gpu = root_cbv(self, r->address)) directs.push_back({rs.host, gpu, 0}); + } + for (const auto& rs : st.root_srvs) { + if (memory && rs.title == abi::slot_memory) { + directs.push_back({rs.host, memory->directory->GetGPUVirtualAddress(), 1}); + continue; + } + if (rs.title == abi::slot_strides) { + // Ours: the per-slot strides of the heap the shader picks buffers from by index. + const std::uint64_t gpu = b.views.heap ? gpu_heap_strides_gpu(b.views.heap) : 0; + if (gpu) directs.push_back({rs.host, gpu, 1}); + continue; + } + const x2w_gpu::GpuRoot* r = s.roots.at(compute, rs.title); + const std::uint64_t address = r && x2w_vbind::is_view(r->kind) ? r->address : 0; + const bool biased = biased_view(sh, rs.title); + std::uint32_t bias = 0; + if (rs.table) { + std::uint32_t index = 0; + if (!root_srv_table(self, s, b, address, biased, &index, &bias)) return drop(drop_root_srv); + view_tables.push_back({rs.host, index}); + } else if (const auto gpu = root_direct(self, address, false, biased, &bias)) { + directs.push_back({rs.host, gpu, 1}); + } + biases.push_back({rs.title, bias}); + } + for (const auto& rs : st.root_uavs) { + if (memory && rs.title == abi::slot_faults) { + directs.push_back({rs.host, memory->faults->GetGPUVirtualAddress(), 2}); + continue; + } + const x2w_gpu::GpuRoot* r = s.roots.at(compute, rs.title); + const std::uint64_t address = r && x2w_vbind::is_view(r->kind) ? r->address : 0; + std::uint32_t bias = 0; + if (rs.table) { + std::uint32_t index = 0; + if (!root_uav_table(self, s, b, address, &index, &bias)) return drop(drop_root_uav); + if (memory && (!address || !gpu_heap_kept_at(b.views.heap, index))) return refuse_memory(sh, MemoryRefusal::output); + view_tables.push_back({rs.host, index}); + } else { + const auto gpu = root_direct(self, address, true, true, &bias); + if (!gpu) return drop(drop_root_uav); // A root UAV requires a valid GPU address. + directs.push_back({rs.host, gpu, 2}); + } + biases.push_back({rs.title, bias}); + } + if (st.user_data_param != UINT32_MAX && st.user_data_dwords) { + unsigned misses = 0; + const auto values = x2w_vbind::fill_user_data(s.roots, compute, sh.user_data.data, sh.user_data.count, st.user_data_dwords, + made, b.spans, 2, biases, memory ? memory->base : 0, [&](std::uint32_t slot, std::uint32_t dword) -> std::uint64_t { + return buffer_address(b, s, compute, slot, dword); + }, &misses); + if (misses) InterlockedExchangeAdd(&user_misses, static_cast<LONG>(misses)); + if (!compute && values.size() >= 15 && sh.material_fields) { + s.material_heap = b.views.heap; + s.material_shader = &sh; + s.material_raw_slot = (std::min)((values[8] + 2752u) >> 5, x2w_material_trace::null_index); + s.material_base = values[14]; + } + if (compute) l->SetComputeRoot32BitConstants(st.user_data_param, st.user_data_dwords, values.data(), 0); + else l->SetGraphicsRoot32BitConstants(st.user_data_param, st.user_data_dwords, values.data(), 0); + } + for (const Direct& d : directs) { + if (compute) { + if (d.kind == 0) l->SetComputeRootConstantBufferView(d.param, d.gpu); + else if (d.kind == 1) l->SetComputeRootShaderResourceView(d.param, d.gpu); + else l->SetComputeRootUnorderedAccessView(d.param, d.gpu); + } else { + if (d.kind == 0) l->SetGraphicsRootConstantBufferView(d.param, d.gpu); + else if (d.kind == 1) l->SetGraphicsRootShaderResourceView(d.param, d.gpu); + else l->SetGraphicsRootUnorderedAccessView(d.param, d.gpu); + } + } + for (const Table& t : view_tables) { + const D3D12_GPU_DESCRIPTOR_HANDLE handle = gpu_heap_gpu_handle(b.views.heap, t.index); + if (compute) l->SetComputeRootDescriptorTable(t.param, handle); + else l->SetGraphicsRootDescriptorTable(t.param, handle); + } + } + if (memory) { + const auto state = [&](auto* r, auto next) { require_state(self, r, next); }; + const auto view = [&](UINT slot, auto* r, UINT64 size) { gpu_heap_raw_uav_at(memory->heap, slot, r, 0, size); }; + if (!memory->allow_ordinary_reads(l, reads, writes, x2w_gpu::buffer_read_state(l->GetType()), view, state)) + return refuse_memory(*p.stages[0].shader, MemoryRefusal::overlapping_read); + if (!memory->ordinary_reads.empty()) { + static LONG shared; + const LONG n = InterlockedIncrement(&shared); + if (n <= 4 || (n & (n - 1)) == 0) + log("x2w-gpu memory simultaneous reads: frame=%ld count=%ld key=%s pages=%zu windows=%zu", + frame_number, n, p.stages[0].shader->key, memory->restore_rows.size(), memory->ordinary_reads.size()); + } + memory->ready(l, state); + // Root UAVs and raw directory entries can alias the same title pages across + // builder dispatches. A transition alone doesn't order an already-UAV window. + D3D12_RESOURCE_BARRIER order{}; + order.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + l->ResourceBarrier(1, &order); + s.memory_back = std::move(pending); // published only by an issued command's completion hook + static LONG dispatched_with_memory; + const LONG n = InterlockedIncrement(&dispatched_with_memory); + if ((n & (n - 1)) == 0) + log("x2w-gpu memory binds %ld: key=%s pages=%zu windows=%zu", n, p.stages[0].shader->key, + memory->addresses.size(), memory->windows.size()); + } + return true; +} + +// ---- draw state: vertex and index buffers, topology, targets -------------------------------------- +bool prepare_draw(Wrapper* self, ID3D12GraphicsCommandList* l, GpuListState& s, const GpuPipeline& p, bool indexed) +{ + const Pass& pass = pass_of(self); + D3D12_VERTEX_BUFFER_VIEW views[32]{}; + UINT count = 0; + for (UINT slot = 0; slot < 32; ++slot) { + if (!(p.vertex_slots & (1u << slot))) continue; + count = slot + 1; + x2w_vbind::VertexView v = s.roots.vertex[slot]; + if (!s.vertex_hooked && slot < 8) v = {pass.vb[slot].BufferLocation, pass.vb[slot].SizeInBytes, pass.vb[slot].StrideInBytes}; + if (!v.address || !v.size) continue; + x2w_vbind::Found f; + if (!find(v.address, 1, v.size, v.size, &f)) { + InterlockedIncrement(&vertex_unbound); + continue; + } + views[slot] = {window_of(f)->GetGPUVirtualAddress() + f.offset, static_cast<UINT>((std::min<std::uint64_t>)(v.size, f.left)), v.stride}; + window_read(self, window_of(f)); + } + if (count) l->IASetVertexBuffers(0, count, views); + if (indexed) { + x2w_vbind::IndexView v = s.roots.index; + if (!s.vertex_hooked) v = {pass.ib.BufferLocation, pass.ib.SizeInBytes, static_cast<std::uint32_t>(pass.ib.Format)}; + x2w_vbind::Found f; + if (!v.address || !v.size || !find(v.address, 1, v.size, v.size, &f)) return drop(drop_index_buffer); + const D3D12_INDEX_BUFFER_VIEW view{window_of(f)->GetGPUVirtualAddress() + f.offset, + static_cast<UINT>((std::min<std::uint64_t>)(v.size, f.left)), static_cast<DXGI_FORMAT>(v.format)}; + window_read(self, window_of(f)); + l->IASetIndexBuffer(&view); + } + const UINT topology = s.roots.topology_set ? s.roots.topology : pass.topology; + if (topology) l->IASetPrimitiveTopology(static_cast<D3D12_PRIMITIVE_TOPOLOGY>(x2w_vbind::host_topology(topology))); + // The targets' states again: a dispatch or a read in between may have moved them. + for (UINT i = 0; i < pass.target_count && i < 8; ++i) + if (pass.targets[i]) use_as_target(self, pass.targets[i]); + if (pass.dsv_resource) { + constexpr auto shader_bits = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + D3D12_RESOURCE_STATES reads = D3D12_RESOURCE_STATE_COMMON; + if (const auto* entry = pass.states.find(pass.dsv_resource)) reads = (entry->depth | entry->stencil) & shader_bits; + require_bound_depth(self, reads); + } + return true; +} + +// The bound targets, for a pipeline whose stream formats differ from them (WP2 makes a variant). +GpuTargets targets_of(Wrapper* self) +{ + const Pass& pass = pass_of(self); + GpuTargets t; + t.count = (std::min)(pass.target_count, 8u); + for (std::uint32_t i = 0; i < t.count; ++i) t.rtv[i] = pass.target_formats[i]; + t.dsv = pass.dsv_format; + t.read_depth_plane = pass.read_depth_plane; + t.read_stencil_plane = pass.read_stencil_plane; + ID3D12Resource* any = t.count && pass.targets[0] ? pass.targets[0] : pass.dsv_resource; + t.samples = any ? any->GetDesc().SampleDesc.Count : 1; + return t; +} + +// The pipeline bound to the list for a call of this kind; null (counted) when the call must be dropped. +enum class Call { dispatch, draw, indexed, mesh, indirect }; +bool sample_drop(Wrapper* list, Wrapper* pipeline, Call call, GpuPsoDrop pso, Drop why_dropped = last_drop) +{ + if (!gpu_drop_trace()) return false; + static constexpr const char* calls[] = {"dispatch", "draw", "indexed", "mesh", "indirect"}; + static constexpr const char* bind_reasons[] = {"no-pipeline", "wrong-kind", "no-view-heap", "no-free-slots", + "memory-shader", "root-uav", "root-srv", "index-buffer", "rectangle", "not-recording", "invalid-targets"}; + static constexpr const char* pso_reasons[] = {"no-pipeline", "async-pending", "missing-shader", "warm-bad", + "worker-failure", "pipeline-refused"}; + static_assert(std::size(bind_reasons) == drop_count && std::size(pso_reasons) == unsigned(GpuPsoStatus::count)); + const unsigned reason = why_dropped == drop_no_pipeline ? drop_count + unsigned(pso.status) : unsigned(why_dropped); + static LONG counts[std::size(calls)][drop_count + std::size(pso_reasons)]{}; + const LONG n = InterlockedIncrement(&counts[unsigned(call)][reason]); + if (n > 4 && (n & (n - 1)) != 0) return false; + const auto* entry = pipeline ? static_cast<const GpuPipelineEntry*>(pipeline->own().gpu[0]) : nullptr; + std::string keys; + if (entry) { + for (const auto* shader : entry->records) + if (shader) keys += std::string(" ") + x2w_gpu::gpu_stage_name(shader->stage) + "=" + shader->key; + if (entry->missing_keys) keys += *entry->missing_keys; + } + const char* why = why_dropped == drop_no_pipeline ? pso_reasons[unsigned(pso.status)] : bind_reasons[why_dropped]; + log("x2w-gpu scene drop: frame=%ld call=%s reason=%s count=%ld list=%p pso=%p keys=%s detail=%s", + frame_number, calls[unsigned(call)], why, n, static_cast<void*>(list), static_cast<void*>(pipeline), + keys.empty() ? "<none>" : keys.c_str(), pso.detail); + return false; +} + +const GpuPipeline* pipeline_for(Wrapper* self, GpuListState& s, Call call, GpuPsoDrop* failure) +{ + if (!s.pipeline) return drop(drop_no_pipeline), nullptr; + const GpuTargets targets = call == Call::dispatch ? GpuTargets{} : targets_of(self); + const GpuPipeline* p = gpu_pipeline_ready(static_cast<Wrapper*>(s.pipeline), call == Call::dispatch ? nullptr : &targets, failure); + if (!p || !p->pso || !p->root) return drop(drop_no_pipeline), nullptr; + const bool ok = call == Call::dispatch ? p->compute : call == Call::mesh ? (!p->compute && p->mesh) : (!p->compute && !p->mesh); + if (!ok) return drop(drop_wrong_kind), nullptr; // "a draw or mesh dispatch with another kind of pipeline" + if (call == Call::draw || call == Call::indexed) { + const UINT topology = s.roots.topology_set ? s.roots.topology : pass_of(self).topology; + if (topology == x2w_vbind::topology_rectangles) { + static LONG with_gs, without_gs; + if (first_calls(p->rects ? with_gs : without_gs, 1)) + log("x2w-gpu rectangle draw: %s, title PSO topology %u, indexed %u", + p->rects ? "geometry stage" : "no geometry stage", p->title_topology, call == Call::indexed ? 1u : 0u); + } + // Rectangle draws require a rectangle geometry stage. + if (topology == x2w_vbind::topology_rectangles && !p->rects) return drop(drop_rectangles), nullptr; + } + return p; +} +// Everything a call needs set on the host list, without issuing it. +bool prepare(Wrapper* self, ID3D12GraphicsCommandList* l, Call call) +{ + if (!l) { + drop(drop_not_recording); + return sample_drop(self, nullptr, call, {}); + } + GpuListState& s = state_of(self); + if (call != Call::dispatch && pass_of(self).targets_refused) { + drop(drop_invalid_targets); + return sample_drop(self, static_cast<Wrapper*>(s.pipeline), call, {}); + } + s.writable_depth.clear(); + s.light_role = x2w_gpu::ambient::Role::none; + if (call == Call::dispatch && s.pipeline && indirect_light_settings().level > 0) { + const auto* entry = static_cast<const GpuPipelineEntry*>(static_cast<Wrapper*>(s.pipeline)->own().gpu[0]); + if (entry) { + if (entry->records.size() == 1 && entry->records.front() && entry->records.front()->builder) return false; + s.light_role = entry->light_role; + s.light_views = {}; + s.light_depth_width = s.light_depth_height = 0; + } + } + GpuPsoDrop failure; + const GpuPipeline* p = pipeline_for(self, s, call, gpu_drop_trace() ? &failure : nullptr); + s.memory_back.clear(); + if (!p) return sample_drop(self, static_cast<Wrapper*>(s.pipeline), call, failure); + // Bindless textures WP5 queued (made into mirror slots, or changed): uploaded on this open list first (PLAN 4b). + gpu_heap_upload_due(self, upload_due_most()); + const bool compute = call == Call::dispatch; + if (compute_capture_on()) { + s.trace_request = 0; + s.trace_shader = compute && p->stage_count ? p->stages[0].shader : nullptr; + if (s.trace_shader) s.trace_request = match_compute_capture(s.trace_shader->key); + if (s.trace_request) s.trace_bindings = {}; + } + s.pixel_capture_shader = nullptr; + if (!compute && pixel_capture_on() && compute_capture_pending.load()) { + s.pixel_bindings.clear(); + s.pixel_capture_pipeline = p; + for (UINT i = 0; i < p->stage_count; ++i) { + const auto* sh = p->stages[i].shader; + if (sh && sh->stage == x2w_gpu::GpuStage::pixel) { + s.trace_request = match_compute_capture(sh->key); + if (s.trace_request) s.pixel_capture_shader = sh; + } + } + } + s.material_heap = nullptr; + if (!bind(self, l, s, *p, compute) || (!compute && !prepare_draw(self, l, s, *p, call == Call::indexed))) + return sample_drop(self, static_cast<Wrapper*>(s.pipeline), call, failure); + if (s.material_heap && l->GetType() == D3D12_COMMAND_LIST_TYPE_DIRECT) { + prepare_material(self, l, s); + if (gpu_trace_request_id && gpu_trace_stage_key() && trace_tables(self, false, s.material_shader->key)) + material_capture(self, l, s, p->pso); + } + return true; +} + +void report() +{ + LONG d[drop_count]; + LONG total = 0; + for (int i = 0; i < drop_count; ++i) total += d[i] = InterlockedExchange(&dropped[i], 0); + log("x2w-gpu bind 300 frames: dispatched %ld drawn %ld dropped %ld (no pipeline %ld, wrong kind %ld, no view heap %ld, " + "no free slots %ld, memory shader %ld, root uav %ld, root srv %ld, index buffer %ld, rectangles %ld, not recording %ld, refused targets %ld); " + "user-data misses %ld, cbv copies %ld (failed %ld, null %ld), root uav null %ld unknown memory %ld cut %ld, root srv null %ld " + "cut %ld, vertex views unbound %ld, textures uploaded %ld, tables outside the heaps %ld, fresh tables skipped %ld, " + "table views missing %ld, buffer barriers %ld, slots released %ld kept %ld, binds without sampler heap %ld", + InterlockedExchange(&dispatched, 0), InterlockedExchange(&drawn, 0), total, d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], + d[8], d[9], d[drop_invalid_targets], InterlockedExchange(&user_misses, 0), InterlockedExchange(&cbv_copies, 0), InterlockedExchange(&cbv_copy_failed, 0), + InterlockedExchange(&cbv_null, 0), InterlockedExchange(&root_uav_null, 0), InterlockedExchange(&root_uav_unknown, 0), + InterlockedExchange(&root_uav_cut, 0), InterlockedExchange(&root_srv_null, 0), InterlockedExchange(&root_srv_cut, 0), + InterlockedExchange(&vertex_unbound, 0), InterlockedExchange(&textures_uploaded, 0), InterlockedExchange(&foreign_tables, 0), + InterlockedExchange(&tables_skipped, 0), InterlockedExchange(&table_views_missing, 0), InterlockedExchange(&buffer_barriers, 0), + InterlockedExchange(&slots_released, 0), InterlockedExchange(&slots_kept, 0), InterlockedExchange(&missing_sampler_heap, 0)); +} + +} // namespace vbind + +// ===== the declared hooks (gpu_hooks.h) ================================================================================= + +// ---- list setters 32-46 (EXCLUSIVE under ABI: X2W's handlers are not called, Pass root state is stale) ---------------------- +void gpu_set_heaps(Wrapper* list, UINT count, void* const* heaps) +{ + auto& s = vbind::state_of(list); + s.heaps[0] = s.heaps[1] = nullptr; + if (!count || count > 4 || !x2w_local::readable(heaps, std::size_t{count} * sizeof(*heaps))) return; + for (UINT i = 0; i < count; ++i) { + GpuHeapInfo info{}; + if (heaps[i] && gpu_heap_for(as_wrapper(heaps[i]), &info) && info.heap) s.heaps[info.sampler ? 1 : 0] = as_wrapper(heaps[i]); + } + static LONG selected; + if (s.heaps[0] && s.heaps[1] && first_calls(selected, 1)) + log("x2w-gpu list slot 32 selected title view and sampler heaps"); +} +void gpu_roots_signature(Wrapper*, bool, Wrapper*) {} // The host root signature belongs to the pipeline. +void gpu_roots_table(Wrapper* list, bool compute, UINT parameter, std::uint64_t handle) +{ + vbind::state_of(list).roots.set_table(compute, parameter, handle); +} +void gpu_roots_constants(Wrapper* list, bool compute, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) +{ + if (!count || !x2w_local::readable(data, std::size_t{count} * 4)) return; + vbind::state_of(list).roots.set_constants(compute, parameter, data, count, offset); +} +void gpu_roots_view(Wrapper* list, bool compute, UINT parameter, std::uint64_t address, GpuRootKind kind) +{ + vbind::state_of(list).roots.set_view(compute, parameter, address, kind); +} + +// ---- non-root draw state (ADDITIVE, after X2W's handler) ---------------------------------------------------------------------- +// X2W forwards topologies 1-5 only; the console's own become triangle lists. +void gpu_topology(Wrapper* list, UINT topology) +{ + auto& s = vbind::state_of(list); + s.roots.topology = topology; + s.roots.topology_set = true; + if (auto* l = recording(list)) l->IASetPrimitiveTopology(static_cast<D3D12_PRIMITIVE_TOPOLOGY>(x2w_vbind::host_topology(topology))); +} +// Viewports, scissors and the blend factor: X2W's handlers forward them to the desktop list already. +void gpu_viewports(Wrapper*, UINT, const D3D12_VIEWPORT*) {} +void gpu_scissors(Wrapper*, UINT, const D3D12_RECT*) {} +void gpu_blend_factor(Wrapper*, const float*) {} +// Slot 24 is installed under ABI, also where X2W's own handler is not (a second forward of the same value is harmless). +void gpu_stencil_ref(Wrapper* list, UINT ref) +{ + if (auto* l = recording(list)) l->OMSetStencilRef(ref); +} +void gpu_set_pipeline(Wrapper* list, Wrapper* pipeline) { vbind::state_of(list).pipeline = pipeline; } +// Barriers: X2W forwards UAV barriers on desktop resources. A barrier that names a title BUFFER (or no resource) +// also orders the windows this path binds in its place: one global UAV barrier. +void gpu_barriers(Wrapper* list, UINT count, const D3D12_RESOURCE_BARRIER* barriers) +{ + auto* l = recording(list); + if (!l || !count || !barriers || !x2w_local::readable(barriers, std::size_t{count} * sizeof(*barriers))) return; + const auto type = l->GetType(); + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_COMPUTE) return; + bool buffer = false; + for (UINT i = 0; i < count && !buffer; ++i) { + D3D12_RESOURCE_BARRIER b; + std::memcpy(&b, barriers + i, sizeof(b)); + if (b.Type == D3D12_RESOURCE_BARRIER_TYPE_ALIASING) continue; + void* named = b.Type == D3D12_RESOURCE_BARRIER_TYPE_UAV ? static_cast<void*>(b.UAV.pResource) : static_cast<void*>(b.Transition.pResource); + if (!named) { + buffer = b.Type == D3D12_RESOURCE_BARRIER_TYPE_UAV; + continue; + } + Wrapper* w = as_wrapper(named); + const ResourceInfo* info = w && w->own().kind == resource_kind ? resource_info(w) : nullptr; + buffer = info && info->console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER; + } + if (!buffer) return; + D3D12_RESOURCE_BARRIER all{}; + all.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + all.UAV.pResource = nullptr; + l->ResourceBarrier(1, &all); + InterlockedIncrement(&vbind::buffer_barriers); +} +void gpu_ia_index(Wrapper* list, const D3D12_INDEX_BUFFER_VIEW* view) +{ + auto& s = vbind::state_of(list); + s.vertex_hooked = true; + if (view && x2w_local::readable(view, sizeof(*view))) { + const x2w_vbind::IndexView v{view->BufferLocation, view->SizeInBytes, static_cast<std::uint32_t>(view->Format)}; + s.roots.set_index(&v); + } else { + s.roots.set_index(nullptr); + } +} +void gpu_ia_vertex(Wrapper* list, UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) +{ + auto& s = vbind::state_of(list); + s.vertex_hooked = true; + if (views && !x2w_local::readable(views, std::size_t{count} * sizeof(*views))) return; + for (UINT i = 0; i < count && std::size_t{start} + i < 32; ++i) { + const x2w_vbind::VertexView v = views ? x2w_vbind::VertexView{views[i].BufferLocation, views[i].SizeInBytes, views[i].StrideInBytes} + : x2w_vbind::VertexView{}; + s.roots.set_vertex(start + i, 1, &v); + } +} +// Targets: X2W's slot 50 maps the RTV / DSV handles and sets them; the draw reads Pass (formats, states). +void gpu_targets(Wrapper*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL, const D3D12_CPU_DESCRIPTOR_HANDLE*) {} +// Depth bounds: X2W has no handler. Forwarded where the device supports the test. +void gpu_depth_bounds(Wrapper* list, float min, float max) +{ + static const bool supported = [] { + D3D12_FEATURE_DATA_D3D12_OPTIONS2 o2{}; + return the_device && SUCCEEDED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS2, &o2, sizeof(o2))) && + o2.DepthBoundsTestSupported; + }(); + auto* l = recording(list); + if (!l || !supported) return; + x2w_startup::ComPtr<ID3D12GraphicsCommandList1> l1; + if (SUCCEEDED(l->QueryInterface(IID_PPV_ARGS(&l1)))) l1->OMSetDepthBounds(min, max); +} + +// ---- draws (EXCLUSIVE): true when issued, false when dropped (counted here by reason, by WP0 in total) --------------------- +void gpu_trace_pass_inventory(const GpuPipeline& p, const Pass& pass, const char* command, bool compute, + LONG frame, LONG sequence, UINT x, UINT y, UINT z) +{ + struct Entry { ID3D12PipelineState* pso; ID3D12Resource* target; }; + struct Inventory { + LONG frame = 0; + std::vector<Entry> entries; + bool capped = false; + }; + static std::mutex lock; + static Inventory seen[2]; + auto* target = !compute && pass.target_count ? pass.targets[0] : nullptr; + std::lock_guard<std::mutex> guard(lock); + auto& current = seen[compute ? 1 : 0]; + if (frame < current.frame) return; + if (frame != current.frame) { + current.entries.clear(); + current.capped = false; + current.frame = frame; + } + if (current.capped || std::any_of(current.entries.begin(), current.entries.end(), + [&](const Entry& e) { return e.pso == p.pso && e.target == target; })) return; + if (current.entries.size() == 128) { + log("x2w-frame pass inventory %ld %s capped at 128 distinct entries", frame, compute ? "compute" : "graphics"); + current.capped = true; + return; + } + current.entries.push_back({p.pso, target}); + const auto key = [&](UINT i) { return i < p.stage_count && p.stages[i].shader ? p.stages[i].shader->key : "-"; }; + const auto desc = target ? target->GetDesc() : D3D12_RESOURCE_DESC{}; + log("x2w-frame pass inventory %ld #%ld %s stages=%s,%s,%s,%s args=%u,%u,%u RTs=%u RTV0=%p size=%llux%u", + frame, sequence, command, key(0), key(1), key(2), key(3), x, y, z, compute ? 0u : pass.target_count, + static_cast<void*>(target), desc.Width, desc.Height); +} + +void gpu_trace_issue(Wrapper* self, const char* command, bool compute, UINT a, UINT b, UINT c) +{ + if (compute) { + static const bool trace_busy = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_D3D12_TRACE_BUSY", value, sizeof(value)) && std::atol(value) > 0; + }(); + if (trace_busy) InterlockedIncrement(&frame_dispatches); + } + auto& scene = gpu_scene_trace(); + if (!compute && scene.waiting.load(std::memory_order_acquire)) { + const Pass& pass = pass_of(self); + const auto width = vbind::trace_min_width() ? vbind::trace_min_width() : 2560; + const auto needed = scene.mrt ? scene.mrt : 5; + const auto count = (std::min)(pass.target_count, 8u); + if (count >= static_cast<UINT>(needed) && std::count_if(pass.targets, pass.targets + count, + [width](ID3D12Resource* target) { return target && target->GetDesc().Width >= width; }) >= needed) { + std::lock_guard<std::mutex> held(scene.lock); + const LONG next = InterlockedCompareExchange(&frame_number, 0, 0) + 1; + if (scene.waiting.load() && !gpu_trace_frame) { + if (!scene.first) scene.first = next; + if (scene.pending || next - scene.first >= scene.after) { + if ((vbind::compute_capture_on() || vbind::pixel_capture_on()) && scene.pending) + vbind::arm_compute_capture(scene.pending, scene.pending_key, scene.second_key, scene.pending_point); + std::atomic_store(&gpu_scene_stage_override, std::move(scene.pending_key)); + std::atomic_store(&gpu_scene_second_override, std::move(scene.second_key)); + scene.active_id = scene.pending; + InterlockedExchange(&gpu_trace_request_id, scene.active_id); + scene.pending = 0; + scene.active_frame = next; + scene.waiting.store(false); + reset_gpu_trace_commands(); + InterlockedExchange(&trace_uav_busy_frame, next); + InterlockedExchange(&trace_frame_active, 1); + InterlockedExchange(&gpu_trace_frame, next); + log("x2w-frame ---- begin deferred frame %ld request %ld first qualifying frame %ld targets %u", + next, scene.active_id, scene.first, count); + } + } + } + } + const LONG frame = gpu_trace_frame; + if (!frame) return; + const LONG n = InterlockedIncrement(&gpu_trace_commands); + if (!vbind::trace_pass(self, compute)) return; + UINT topology = 0; + const GpuPipeline* p = nullptr; + static const bool inventory = x2w_local::env_on("X2W_TRACE_PASS_INVENTORY"); + if (inventory) { + p = gpu_bound_pipeline(self, &topology); + if (p) gpu_trace_pass_inventory(*p, pass_of(self), command, compute, frame, n, a, b, c); + } + if (gpu_trace_stage_key()) { + if (!p) p = gpu_bound_pipeline(self, &topology); + if (!p || std::none_of(p->stages, p->stages + p->stage_count, [](const auto& stage) { + return stage.shader && vbind::trace_stage_matches(stage.shader->key); + })) return; + } + const LONG kind_count = InterlockedIncrement(&gpu_trace_per_kind[compute ? 1 : 0]); + if (kind_count > 64) { + if (kind_count == 65) log("x2w-frame gpu frame %ld: %s command trace capped at 64", frame, compute ? "compute" : "graphics"); + return; + } + if (!p) p = gpu_bound_pipeline(self, &topology); + if (!p) return; + const auto key = [&](UINT i) { + return i < p->stage_count && p->stages[i].shader ? p->stages[i].shader->key : "-"; + }; + const Pass& pass = pass_of(self); + log("x2w-frame gpu %ld #%ld %s list=%p pso=%p args=%u,%u,%u stage0=%s stage1=%s topology=%u " + "RTs=%u depth=%p viewport_set=%u xywh=%.1f,%.1f,%.1f,%.1f scissor_set=%u ltrb=%ld,%ld,%ld,%ld", + frame, n, command, static_cast<void*>(self), static_cast<void*>(p->pso), a, b, c, key(0), key(1), topology, + compute ? 0u : pass.target_count, compute ? nullptr : static_cast<void*>(pass.dsv_resource), + UINT(pass.viewport_set), pass.viewport0.TopLeftX, pass.viewport0.TopLeftY, pass.viewport0.Width, pass.viewport0.Height, + UINT(pass.scissor_set), pass.scissor0.left, pass.scissor0.top, pass.scissor0.right, pass.scissor0.bottom); + static const bool readback = x2w_local::env_on("X2W_D3D12_TRACE_TARGETS"); + for (UINT i = 0; !compute && i < pass.target_count && i < 8; ++i) { + ID3D12Resource* rt = pass.targets[i]; + if (!rt) continue; + const auto desc = rt->GetDesc(); + const auto* tracked = pass.states.find(rt); + log("x2w-frame gpu %ld #%ld RTV[%u]=%p size=%llux%u resource_fmt=%u view_fmt=%u tracked_state=0x%x", + frame, n, i, static_cast<void*>(rt), desc.Width, desc.Height, UINT(desc.Format), UINT(pass.target_formats[i]), + tracked ? UINT(tracked->depth) : UINT_MAX); + if (readback && desc.Width >= vbind::trace_min_width() && tracked && tracked->depth == D3D12_RESOURCE_STATE_RENDER_TARGET) + note_traced_target(self, rt, true, D3D12_RESOURCE_STATE_RENDER_TARGET, true, pass.target_formats[i], n, i); + } +} + +// Copies run on the list that used the UAV, including compute lists. Each use starts from the +// original texture and publishes its writes before any following title command can read it. +void gpu_finish_depth_writes(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + auto& s = vbind::state_of(self); + if (!s.memory_back.empty()) { + for (const auto& range : s.memory_back) + vbind::builder_arenas().publish(list,range,[&](auto* r, auto next) { require_state(self,r,next); }, + s.memories.front()->zeros.Get()); + s.memory_back.clear(); + s.host_roots[1] = nullptr; + s.host_pso = nullptr; + } + for (auto* pair : s.writable_depth) { + const auto before = pass_of(self).states.state(pair->depth.Get()); + pair->copy_colour(list, false, [&](auto* r, auto state) { require_state(self, r, state); }); + require_state(self, pair->depth.Get(), before); + require_state(self, pair->colour.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + s.writable_depth.clear(); +} +bool gpu_depth_barrier(Wrapper* self, Wrapper* resource) +{ + std::shared_ptr<x2w_depth_twins::Twins> pair; + { + std::lock_guard<std::mutex> guard(gpu_detail_heap::depth_lock); + const auto& pairs = gpu_detail_heap::depth_pairs(); + const auto it = pairs.find(resource); + if (it == pairs.end() || !it->second) return false; + pair = it->second; + } + auto* list = recording(self); + if (!list) return false; + auto& s = vbind::state_of(self); + if (std::find(s.depth_refs.begin(), s.depth_refs.end(), pair) == s.depth_refs.end()) s.depth_refs.push_back(pair); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + barrier.UAV.pResource = pair->colour.Get(); + list->ResourceBarrier(1, &barrier); + return true; +} +void gpu_note_exposure_reset(Wrapper* self) +{ + static std::atomic<bool> seen{false}; + if (!gpu_drop_trace() || seen.load(std::memory_order_relaxed)) return; + auto* p = static_cast<Wrapper*>(vbind::state_of(self).pipeline); + auto* entry = p ? static_cast<GpuPipelineEntry*>(p->own().gpu[0]) : nullptr; + if (entry && entry->exposure_reset && !seen.exchange(true)) + log("x2w-gpu exposure reset draw recorded: frame=%ld list=%p", frame_number, static_cast<void*>(self)); +} + +bool gpu_draw(Wrapper* self, ID3D12GraphicsCommandList* list, UINT vertices, UINT instances, UINT first_vertex, UINT first_instance) +{ + if (!vbind::prepare(self, list, vbind::Call::draw)) return false; + if (vbind::pixel_capture_on()) vbind::pixel_capture_before(self, list, "draw"); + list->DrawInstanced(vertices, instances, first_vertex, first_instance); + if (vbind::pixel_capture_on()) vbind::pixel_capture_after(self, list); + if (vertices && instances) gpu_note_exposure_reset(self); + gpu_trace_issue(self, "draw", false, vertices, instances, first_vertex); + gpu_finish_depth_writes(self, list); + InterlockedIncrement(&vbind::drawn); + return true; +} +bool gpu_draw_indexed(Wrapper* self, ID3D12GraphicsCommandList* list, UINT count, UINT instances, UINT start, INT base_vertex, + UINT first_instance) +{ + if (!vbind::prepare(self, list, vbind::Call::indexed)) return false; + if (vbind::pixel_capture_on()) vbind::pixel_capture_before(self, list, "indexed"); + list->DrawIndexedInstanced(count, instances, start, base_vertex, first_instance); + if (count && instances) gpu_note_exposure_reset(self); + if (vbind::pixel_capture_on()) vbind::pixel_capture_after(self, list); + gpu_trace_issue(self, "indexed", false, count, instances, start); + gpu_finish_depth_writes(self, list); + InterlockedIncrement(&vbind::drawn); + return true; +} +bool gpu_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z) +{ + if (!vbind::prepare(self, list, vbind::Call::dispatch)) return false; + vbind::compute_capture_before(self, list); + list->Dispatch(x, y, z); + if (x && y && z) vbind::finish_light(self, list); + vbind::compute_capture_after(self, list); + gpu_trace_issue(self, "dispatch", true, x, y, z); + gpu_finish_depth_writes(self, list); + InterlockedIncrement(&vbind::dispatched); + return true; +} +// The bind sequence without the issue, for WP4 (ExecuteIndirect, DispatchMesh, DispatchX). +bool gpu_bind_draw(Wrapper* self, ID3D12GraphicsCommandList* list, bool indexed) +{ + return vbind::prepare(self, list, indexed ? vbind::Call::indexed : vbind::Call::draw); +} +bool gpu_bind_mesh(Wrapper* self, ID3D12GraphicsCommandList* list) { return vbind::prepare(self, list, vbind::Call::mesh); } +bool gpu_bind_compute(Wrapper* self, ID3D12GraphicsCommandList* list) { return vbind::prepare(self, list, vbind::Call::dispatch); } +// WP4's clamp set its own compute root signature and the list's PSO (vindirect 101900): both are set again at the next +// bind; graphics roots and heaps are untouched. Root arguments are set at every bind anyway. +void gpu_bind_forget_compute(Wrapper* self) +{ + if (auto* s = vbind::state_if(self)) { + s->host_roots[1] = nullptr; + s->host_pso = nullptr; + } +} +// The made pipeline bound on the list (with the bound targets for a graphics one), or null; the console topology last +// set at slot 20 (WP4: kind check, indirect rectangles, DispatchX; vindirect 101523). +const GpuPipeline* gpu_bound_pipeline(Wrapper* self, UINT* title_topology, GpuPsoDrop* drop) +{ + auto* s = vbind::state_if(self); + if (title_topology) *title_topology = s && s->roots.topology_set ? s->roots.topology : pass_of(self).topology; + if (!s || !s->pipeline) return nullptr; + // One call: WP2 ignores the targets for a compute pipeline (no graphics state), so no stream-format variant is made. + const GpuTargets targets = vbind::targets_of(self); + return gpu_pipeline_ready(static_cast<Wrapper*>(s->pipeline), &targets, drop); +} + +// ---- list lifecycle --------------------------------------------------------------------------------------------------------- +void gpu_bind_list_reset(Wrapper* list) +{ + vbind::retire_passed(); + auto& s = vbind::state_of(list); + vbind::end_recording(s); + s.roots.clear(); + s.vertex_hooked = false; + s.pipeline = nullptr; + s.heaps[0] = s.heaps[1] = nullptr; +} +void gpu_bind_list_close(Wrapper* self) +{ + auto* s = vbind::state_if(self); + auto* l = recording(self); + if (s && l) + for (const auto& m : s->memories) + m->close(l, [&](auto* r, auto state) { require_state(self, r, state); }); +} +// After ExecuteCommandLists (draw_lock and allocator_lock held): one fence value for the translated recordings that +// hold slots; the 300-frame report line. +void gpu_bind_first_submit(UINT count, Wrapper* const* lists) +{ + if (!vbind::defer_table_cbv()) return; + for (UINT i = 0; i < count; ++i) { + auto* s = lists[i] ? vbind::state_if(lists[i]) : nullptr; + if (!s) continue; + const auto result = s->table_constants.first_submit([](const x2w_gpu::TableConstantSlice& slice, + const unsigned char* bytes, size_t size) { + auto& r = upload_ring_state(); + AcquireSRWLockShared(&r.lock); + const auto* c = slice.chunk < r.chunks.size() ? &r.chunks[slice.chunk] : nullptr; + const bool valid = !r.legacy && c && c->mapped && c->generation == slice.generation && + c->state == RingChunk::in_use && slice.offset >= c->base && slice.offset - c->base <= c->used && + size <= c->used - (slice.offset - c->base); + if (valid) std::memcpy(c->mapped + (slice.offset - c->base), bytes, size); + ReleaseSRWLockShared(&r.lock); + return valid; + }); + if (result.checked) { + // Submission holds the draw and allocator locks. Aggregate once per list. + static UINT64 checked, changed, unreadable, stale, next = 1; + const bool first_delta = !changed && result.changed; + checked += result.checked; + changed += result.changed; + unreadable += result.unreadable; + stale += result.stale; + if (first_delta || checked >= next) { + while (next <= checked) next *= 2; + log("x2w-gpu table constants at first submit: frame=%ld checked=%llu changed=%llu unreadable=%llu stale=%llu", + frame_number, checked, changed, unreadable, stale); + } + } + } +} + +void gpu_bind_submitted(ID3D12CommandQueue* queue, UINT count, Wrapper* const* lists) +{ + std::vector<GpuListState*> ours; + for (UINT i = 0; i < count; ++i) + if (auto* s = lists[i] ? vbind::state_if(lists[i]) : nullptr; s && (!s->dynamic.empty() || !s->depth_refs.empty() || !s->light_copies.empty() || !s->trace_captures.empty())) ours.push_back(s); + if (!ours.empty()) { + AcquireSRWLockExclusive(&vbind::fence_lock); + auto& [fence, value] = vbind::queue_fences()[queue]; + if (!fence) { + ID3D12Device* device = nullptr; + if (SUCCEEDED(queue->GetDevice(IID_PPV_ARGS(&device)))) { + if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) fence = nullptr; + device->Release(); + } + } + const bool signalled = fence && SUCCEEDED(queue->Signal(fence, value + 1)); + if (signalled) ++value; + const auto mark = std::make_pair(fence, value); + ReleaseSRWLockExclusive(&vbind::fence_lock); + for (auto* s : ours) { + for (const auto& cap : s->trace_captures) + vbind::compute_capture_submitted(cap, signalled ? fence : nullptr, value); + if (signalled) { + s->submitted.push_back(mark); + } else { + // Nothing says when the GPU is done with them: the slots are never handed out again (counted). + for (const auto& d : s->dynamic) InterlockedExchangeAdd(&vbind::slots_kept, static_cast<LONG>(d.n)); + s->dynamic.clear(); + AcquireSRWLockExclusive(&vbind::retire_lock); + static std::vector<std::shared_ptr<x2w_depth_twins::Twins>> unfenced; + unfenced.insert(unfenced.end(), s->depth_refs.begin(), s->depth_refs.end()); + s->depth_refs.clear(); + static std::vector<std::shared_ptr<x2w_vmemory::Recording>> unfenced_memory; + unfenced_memory.insert(unfenced_memory.end(), s->memories.begin(), s->memories.end()); + s->memories.clear(); + static std::vector<std::shared_ptr<x2w_packed_light::Copy>> unfenced_light; + unfenced_light.insert(unfenced_light.end(), s->light_copies.begin(), s->light_copies.end()); + ReleaseSRWLockExclusive(&vbind::retire_lock); + } + } + } + vbind::retire_passed(); + static LONG reported = -1; + const LONG frame = frame_number / 300; + if (InterlockedExchange(&reported, frame) != frame && frame > 0) vbind::report(); +} +void gpu_list_released(Wrapper* list) +{ + if (auto* s = vbind::state_if(list)) { + vbind::end_recording(*s); + delete s; + list->own().gpu[0] = nullptr; + } +} diff --git a/src/startup_stubs/gpu_build_queue.h b/src/startup_stubs/gpu_build_queue.h new file mode 100644 index 0000000000..dd90c2d928 --- /dev/null +++ b/src/startup_stubs/gpu_build_queue.h @@ -0,0 +1,173 @@ +#pragma once +#include <atomic> +#include <chrono> +#include <condition_variable> +#include <cstdint> +#include <deque> +#include <functional> +#include <exception> +#include <memory> +#include <mutex> +#include <string> +#include <thread> +#include <unordered_map> +#include <vector> + +namespace x2w_gpu { + +// One job owns all input it needs independently of the title pipeline. Equal keys requested +// concurrently share one build; screen passes have reserved workers and a separate frame budget. +template<class T> class VpBuildQueue { +public: + using Ms = std::chrono::milliseconds; + using Clock = std::chrono::steady_clock; + struct Job { + std::shared_ptr<T> state; + std::atomic<bool> done{false}; + std::exception_ptr failure; + Clock::time_point first_use_deadline{}; // protected by the queue mutex + std::function<void(T&)> build; + }; + using Handle = std::shared_ptr<Job>; + // A worker publishes this stack record only while it owns a build. An external + // monitor may take it over only once the worker is permanently parked. + struct ActiveBuild { + VpBuildQueue* queue; + Handle job; + bool screen; + std::thread::id thread; + void lost(std::exception_ptr reason) const { queue->replace(*this, reason); } + }; + static inline thread_local ActiveBuild* active = nullptr; + + VpBuildQueue(unsigned general, unsigned screen_workers, Ms ordinary_budget, Ms screen_budget, + void (*thread_start)(bool) = nullptr) : limits_{ordinary_budget, screen_budget}, thread_start_(thread_start) { + try { + for (unsigned i = 0; i < general + screen_workers; ++i) + workers_.emplace_back([this, only_screen = i >= general] { work(only_screen); }); + } catch (...) { + shutdown(); + throw; + } + } + ~VpBuildQueue() { shutdown(); } + + Handle request(std::string key, const std::shared_ptr<T>& state, bool screen, std::function<void(T&)> build, bool initialization = false) { + std::lock_guard<std::mutex> lock(mutex_); + auto& weak = jobs_[std::move(key)]; + if (auto job = weak.lock()) return job; + auto job = std::make_shared<Job>(); + job->state = state; + job->build = std::move(build); + auto& lane = screen && limits_[1].count() != 0 ? screen_ : normal_; + if (initialization) lane.push_front(job); + else lane.push_back(job); + weak = job; + available_.notify_all(); + return job; + } + + // A one-shot initializer cannot rely on the title recording the draw again. All + // callers share one absolute deadline for its exact native pipeline, including variants. + bool ready_initialization(const Handle& job) { + if (job->done.load(std::memory_order_acquire)) return true; + std::unique_lock<std::mutex> lock(mutex_); + if (job->first_use_deadline == Clock::time_point{}) + job->first_use_deadline = Clock::now() + (limits_[1].count() ? limits_[1] : limits_[0]); + return finished_.wait_until(lock, job->first_use_deadline, [&] { + return job->done.load(std::memory_order_acquire); + }); + } + + bool ready(const Handle& job, std::uint64_t frame, bool screen) { + if (job->done.load(std::memory_order_acquire)) return true; + const unsigned lane = screen && limits_[1].count() != 0 ? 1 : 0; + std::unique_lock<std::mutex> lock(mutex_); + auto& budget = budgets_[lane]; + if (!budget.started || budget.frame < frame) + budget = {frame, limits_[lane], true}; + if (budget.frame != frame || budget.left <= Clock::duration::zero()) + return job->done.load(std::memory_order_acquire); + // Reserve the rest now, so concurrent recording threads cannot each spend a full budget. + const auto started = Clock::now(); + const auto deadline = started + budget.left; + budget.left = {}; + finished_.wait_until(lock, deadline, [&] { return job->done.load(std::memory_order_acquire); }); + const auto now = Clock::now(); + if (budget.frame == frame && now < deadline) budget.left += deadline - now; + return job->done.load(std::memory_order_acquire); + } + +private: + struct Budget { std::uint64_t frame{}; Clock::duration left{}; bool started{}; }; + void shutdown() { + { + std::unique_lock<std::mutex> lock(mutex_); + stop_ = true; + available_.notify_all(); + finished_.wait(lock, [&] { return closed_workers_ == workers_.size(); }); + } + for (auto& worker : workers_) if (worker.joinable()) worker.join(); + } + void work(bool only_screen) { + if (thread_start_) thread_start_(only_screen); + for (;;) { + Handle job; + { + std::unique_lock<std::mutex> lock(mutex_); + available_.wait(lock, [&] { return stop_ || !screen_.empty() || (!only_screen && !normal_.empty()); }); + if (stop_) { + ++closed_workers_; + finished_.notify_all(); + return; + } + auto& q = screen_.empty() ? normal_ : screen_; + job = std::move(q.front()); + q.pop_front(); + } + ActiveBuild owner{this, job, only_screen, std::this_thread::get_id()}; + active = &owner; + try { job->build(*job->state); } + catch (...) { job->failure = std::current_exception(); } + active = nullptr; + // A test worker can report its own loss and return normally. + if (job->done.load(std::memory_order_acquire)) return; + job->build = {}; + { + std::lock_guard<std::mutex> lock(mutex_); + job->done.store(true, std::memory_order_release); + } + finished_.notify_all(); + } + } + + void replace(const ActiveBuild& owner, std::exception_ptr reason) { + std::lock_guard<std::mutex> lock(mutex_); + owner.job->failure = reason; + owner.job->done.store(true, std::memory_order_release); + finished_.notify_all(); + for (auto& worker : workers_) { + if (worker.get_id() != owner.thread) continue; + worker.detach(); + ++closed_workers_; + if (!stop_) { + worker = std::thread([this, screen = owner.screen] { work(screen); }); + --closed_workers_; + } + break; + } + } + + Ms limits_[2]; + void (*thread_start_)(bool); + Budget budgets_[2]{}; + std::mutex mutex_; + std::condition_variable available_, finished_; + std::deque<Handle> normal_, screen_; + std::unordered_map<std::string, std::weak_ptr<Job>> jobs_; + std::vector<std::thread> workers_; + bool stop_ = false; + std::size_t closed_workers_ = 0; +}; + +} // namespace x2w_gpu diff --git a/src/startup_stubs/gpu_compute_trace.h b/src/startup_stubs/gpu_compute_trace.h new file mode 100644 index 0000000000..9f6aa92e72 --- /dev/null +++ b/src/startup_stubs/gpu_compute_trace.h @@ -0,0 +1,208 @@ +#pragma once + +#include "startup_stubs/draw_bmp.h" +#include "startup_stubs/list_copy.h" +#include "startup_stubs/gpu_material_trace.h" +#include "startup_stubs/gpu_indirect_capture.h" +#include <d3d12.h> +#include <wrl/client.h> +#include <algorithm> +#include <array> +#include <string> +#include <vector> + +namespace x2w_compute_trace { +using Microsoft::WRL::ComPtr; + +inline bool supported(DXGI_FORMAT f) +{ + return x2w_draw_bmp::trace_supported(f) || f == DXGI_FORMAT_R32G32B32A32_FLOAT || f == DXGI_FORMAT_R32_FLOAT || f == DXGI_FORMAT_R32_UINT || + f == DXGI_FORMAT_R16_FLOAT || f == DXGI_FORMAT_R16_UINT || f == DXGI_FORMAT_R8_UNORM || + f == DXGI_FORMAT_R8_UINT || f == DXGI_FORMAT_R8G8B8A8_TYPELESS || f == DXGI_FORMAT_R10G10B10A2_UNORM; +} + +inline bool depth_format(DXGI_FORMAT f) +{ + return f == DXGI_FORMAT_R32_TYPELESS || f == DXGI_FORMAT_D32_FLOAT || f == DXGI_FORMAT_R32G8X24_TYPELESS || + f == DXGI_FORMAT_D32_FLOAT_S8X24_UINT; +} + +struct Binding { + ID3D12Resource* texture{}; + UINT slot{}, offset{}; + bool write{}, priority{}; + UINT mip{}, slice{}; + DXGI_FORMAT view_format = DXGI_FORMAT_UNKNOWN; + UINT plane{}; +}; +struct Bindings { + std::array<Binding, 32> values{}; + UINT count = 0, reads = 0, writes = 0; + void add(Binding b, bool priority = false, bool wide = false) + { + const UINT limit = wide ? 16u : 3u; + if (!b.texture || (!priority && (b.write ? writes : reads) >= limit)) return; + b.priority = priority; + const auto d = b.texture->GetDesc(); + const bool flat = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && d.DepthOrArraySize == 1; + const bool depth = depth_format(d.Format) || (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + const auto format = b.view_format == DXGI_FORMAT_UNKNOWN ? d.Format : b.view_format; + if (d.SampleDesc.Count != 1 || d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || + (!wide && ((!flat && d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) || d.MipLevels != 1)) || + (depth ? ((!priority && !wide) || b.write || !depth_format(d.Format)) : !supported(format))) return; + for (UINT i = 0; i < count; ++i) + if (values[i].texture == b.texture && values[i].write == b.write && values[i].mip == b.mip && + values[i].slice == b.slice && values[i].plane == b.plane && values[i].view_format == b.view_format) { + if (priority && !values[i].priority) values[i] = b; + return; + } + if ((b.write ? writes : reads) >= limit) { + for (UINT i = count; i > 0; --i) { + auto& old = values[i - 1]; + if (old.write == b.write && !old.priority) { old = b; return; } + } + return; + } + values[count++] = b; + ++(b.write ? writes : reads); + } +}; + +struct Image { + struct Focus { UINT x, y; }; // thousandths of the full image + static D3D12_BOX color_box(UINT width, UINT height, Focus focus) + { + // One comparison covers the same screen area on both sides of a 1440p to 4K draw. + const UINT w = (std::min)(256u, (width + 14) / 15); + const UINT h = (std::min)(128u, (height * 8 + 134) / 135); + const auto origin = [](UINT extent, UINT length, UINT center) { + const UINT pixel = (std::min)(1000u, center) * extent / 1000; + return (std::min)(extent - length, pixel > length / 2 ? pixel - length / 2 : 0u); + }; + const UINT x = origin(width, w, focus.x), y = origin(height, h, focus.y); + return {x,y,0,x+w,y+h,1}; + } + Binding binding; + ComPtr<ID3D12Resource> source, pre, post; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + D3D12_BOX box{}; + UINT64 row_bytes = 0, size = 0; + UINT source_depth = 1; + UINT source_subresource{}; + bool sparse = false, full_depth_plane = false; + UINT width() const { return box.right - box.left; } + UINT height() const { return box.bottom - box.top; } + UINT64 output_row_bytes() const { return row_bytes / footprint.Footprint.Width * width(); } + const unsigned char* row(const unsigned char* pixels, UINT y, UINT z) const + { + const auto& layout = footprint.Footprint; + const UINT64 row_index = UINT64(z) * layout.Height + y + (full_depth_plane ? box.top : 0); + return pixels + row_index * layout.RowPitch + (full_depth_plane ? box.left * (row_bytes / layout.Width) : 0); + } + UINT source_z(UINT z) const { return sparse && z > 0 ? (z == 1 ? source_depth / 2 : source_depth - 1) : z; } + bool init(ID3D12Device* device, Binding b, const Focus* focus = nullptr) + { + binding = b; + source = b.texture; + auto d = source->GetDesc(); + const auto original = d; + const bool volume = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + if (b.plane) { + D3D12_FEATURE_DATA_FORMAT_INFO info{d.Format}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, &info, sizeof(info))) || b.plane >= info.PlaneCount) return false; + } + const UINT slices = volume ? 1u : d.DepthOrArraySize; + source_subresource = b.mip + b.slice * d.MipLevels + b.plane * slices * d.MipLevels; + if (b.view_format != DXGI_FORMAT_UNKNOWN) { + if (!x2w_startup::compatible_formats(d.Format, b.view_format)) return false; + d.Format = b.view_format; + } + if (b.mip >= d.MipLevels || (!volume && b.slice >= d.DepthOrArraySize)) return false; + d.Width = (std::max)(UINT64{1}, d.Width >> b.mip); + d.Height = (std::max)(1u, d.Height >> b.mip); + if (volume) d.DepthOrArraySize = static_cast<UINT16>((std::max)(1, d.DepthOrArraySize >> b.mip)); + UINT width = static_cast<UINT>((std::min)(d.Width, volume ? UINT64{64} : UINT64{256})); + UINT height = (std::min)(d.Height, volume ? 64u : 128u); + source_depth = volume ? d.DepthOrArraySize : 1; + sparse = volume && source_depth > 3 && (d.Width > width || d.Height > height || source_depth > 64); + const UINT x = (static_cast<UINT>(d.Width) - width) / 2, y = (d.Height - height) / 2; + box = {x, y, 0, x + width, y + height, source_depth}; + const bool screen_aspect = d.Width * 9 == UINT64{d.Height} * 16; + if (focus && !volume && ((d.Width >= 1024 && d.Height >= 512) || (screen_aspect && d.Height >= 90))) { + box = color_box(UINT(d.Width), d.Height, *focus); + width = box.right - box.left; + height = box.bottom - box.top; + } + full_depth_plane = depth_format(d.Format) || (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + if (!full_depth_plane) { + d.Width = width; + d.Height = height; + d.Flags = D3D12_RESOURCE_FLAG_NONE; + d.Alignment = 0; + d.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + d.MipLevels = 1; + } + // Depth-stencil planes must be copied whole. Extract the center from the completed readback. + const UINT64 limit = full_depth_plane ? 32ull << 20 : (volume ? 1024ull : 512ull) << 10; + const auto layout = [&] { + if (full_depth_plane) { + device->GetCopyableFootprints(&original, source_subresource, 1, 0, &footprint, nullptr, &row_bytes, &size); + return; + } + d.DepthOrArraySize = static_cast<UINT16>(sparse ? 3 : source_depth); + device->GetCopyableFootprints(&d, 0, 1, 0, &footprint, nullptr, &row_bytes, &size); + }; + layout(); + if (volume && size > limit && !sparse && source_depth > 3) { + sparse = true; + layout(); + } + if (!size || size > limit) return false; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC buf{}; + buf.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buf.Width = size; + buf.Height = buf.DepthOrArraySize = buf.MipLevels = buf.SampleDesc.Count = 1; + buf.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + auto make = [&](ComPtr<ID3D12Resource>& out) { + return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buf, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&out))); + }; + return make(pre) && (!b.write || make(post)); + } + void record(ID3D12GraphicsCommandList* list, bool after) const + { + D3D12_TEXTURE_COPY_LOCATION dst{}, src{}; + dst.pResource = after ? post.Get() : pre.Get(); + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = footprint; + src.pResource = source.Get(); + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + src.SubresourceIndex = source_subresource; + if (!sparse) { + list->CopyTextureRegion(&dst, 0, 0, 0, &src, full_depth_plane ? nullptr : &box); + return; + } + for (UINT z = 0; z < footprint.Footprint.Depth; ++z) { + auto plane = box; + plane.front = source_z(z); + plane.back = plane.front + 1; + list->CopyTextureRegion(&dst, 0, 0, z, &src, &plane); + } + } +}; + +struct Capture { + bool pixel = false; + bool paired = false; + IndirectArguments indirect; + x2w_material_trace::Probe material; + ComPtr<ID3D12DescriptorHeap> feedback_heap; + ComPtr<ID3D12Resource> feedback_source; + long request{}, frame{}; + std::string key; + std::vector<Image> images; + std::vector<std::pair<ID3D12Fence*, UINT64>> fences; + bool published = false, unfenced = false; +}; +} diff --git a/src/startup_stubs/gpu_compute_trace.inl b/src/startup_stubs/gpu_compute_trace.inl new file mode 100644 index 0000000000..457671d0d3 --- /dev/null +++ b/src/startup_stubs/gpu_compute_trace.inl @@ -0,0 +1,462 @@ +// Only the selected shader in a numbered trace request can record copies. +using ComputeCapture = x2w_compute_trace::Capture; +std::mutex compute_capture_lock; +std::array<std::weak_ptr<ComputeCapture>, 2> compute_capture_slots; +std::atomic<LONG> compute_capture_pending{0}; +x2w_gpu::CaptureSelection capture_selection; +x2w_gpu::CapturePoint requested_point; +void arm_compute_capture(LONG id, const TraceStageKey& key, const TraceStageKey& second, x2w_gpu::CapturePoint point) +{ + std::lock_guard<std::mutex> guard(compute_capture_lock); + requested_point = point; + capture_selection = {key ? id : 0, {key ? x2w_gpu::stage_key_number(*key) : std::nullopt, + second ? x2w_gpu::stage_key_number(*second) : std::nullopt}, bool(second)}; + compute_capture_pending.store(key ? id : 0); +} +LONG match_compute_capture(const char* key) +{ + if (!key || !compute_capture_pending.load()) return 0; + std::lock_guard<std::mutex> guard(compute_capture_lock); + return capture_selection.matches(capture_selection.id, key) ? capture_selection.id : 0; +} + +// Readback buffers remain owned by their recording across replays. A second reference +// survives Reset until every queue that actually submitted that recording has completed. +std::vector<std::shared_ptr<ComputeCapture>> compute_capture_flights; // accessed under draw_lock +std::atomic<bool> compute_capture_in_flight{false}; + +void compute_capture_copy(Wrapper* self, ID3D12GraphicsCommandList* list, ComputeCapture& cap, bool post) +{ + for (auto& image : cap.images) { + if (post && !image.binding.write) continue; + auto* source = image.source.Get(); + auto& states = pass_of(self).states; + const auto* it = states.find(source); + // Every enrolled image was checked before any copy on this dispatch. + if (!it) continue; + if (image.full_depth_plane) { + const auto prior = *it; + require_planes(self, source, image.binding.plane ? prior.depth : D3D12_RESOURCE_STATE_COPY_SOURCE, + image.binding.plane ? D3D12_RESOURCE_STATE_COPY_SOURCE : prior.stencil); + image.record(list, post); + require_planes(self, source, prior.depth, prior.stencil); + continue; + } + const auto previous = it->depth; + require_state(self, source, D3D12_RESOURCE_STATE_COPY_SOURCE); + image.record(list, post); + require_state(self, source, previous); + } +} +x2w_compute_trace::Image::Focus capture_focus() +{ + static const auto focus = []() { + x2w_compute_trace::Image::Focus point{500,500}, parsed{}; + char value[32]{}, extra{}; + const auto n = GetEnvironmentVariableA("X2W_TRACE_PIXEL_CENTER", value, sizeof(value)); + if (n && n < sizeof(value) && sscanf_s(value, "%u,%u%c", &parsed.x, &parsed.y, &extra, 1u) == 2 && + parsed.x <= 1000 && parsed.y <= 1000) point = parsed; + return point; + }(); + if (requested_point) return {(*requested_point)[0], (*requested_point)[1]}; + return focus; +} +void compute_capture_before(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + if (!compute_capture_on() || !compute_capture_pending.load()) return; + auto& s = state_of(self); + if (!s.trace_request || !s.trace_bindings.writes) return; + std::lock_guard<std::mutex> guard(compute_capture_lock); + if (!s.trace_shader || !capture_selection.matches(s.trace_request, s.trace_shader->key)) return; + auto slot = std::find_if(compute_capture_slots.begin(), compute_capture_slots.end(), [](auto& weak) { return weak.expired(); }); + if (slot == compute_capture_slots.end()) return; + auto cap = std::make_shared<ComputeCapture>(); + cap->request = s.trace_request; + cap->frame = InterlockedCompareExchange(&frame_number, 0, 0) + 1; + cap->key = s.trace_shader->key; + cap->paired = capture_selection.paired; + for (UINT i = 0; i < s.trace_bindings.count; ++i) { + const auto& b = s.trace_bindings.values[i]; + const auto& states = pass_of(self).states; + const auto* found = states.find(b.texture); + if (!found) continue; + const auto state = b.plane ? found->stencil : found->depth; + if (b.write ? state != D3D12_RESOURCE_STATE_UNORDERED_ACCESS : + !(state & D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)) continue; + x2w_compute_trace::Image image; + const auto& focus = capture_focus(); + if (image.init(device_of(the_device), b, &focus)) cap->images.push_back(std::move(image)); + } + if (std::none_of(cap->images.begin(), cap->images.end(), [](const auto& i) { return i.binding.write; })) return; + capture_selection.complete(cap->key); + compute_capture_pending.store(capture_selection.id); + *slot = cap; + s.trace_current = cap; + s.trace_captures.push_back(cap); + compute_capture_copy(self, list, *cap, false); + log("x2w-compute-capture request %ld frame %ld shader=%s list=%p sampled %zu selected textures", + cap->request, cap->frame, cap->key.c_str(), static_cast<void*>(self), cap->images.size()); +} +void compute_capture_after(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + if (!compute_capture_on()) return; + auto& s = state_of(self); + if (!s.trace_current) return; + compute_capture_copy(self, list, *s.trace_current, true); + s.trace_current.reset(); +} + +void pixel_capture_before(Wrapper* self, ID3D12GraphicsCommandList* list, const char* command) +{ + auto& s = state_of(self); + if (!s.pixel_capture_shader || list->GetType() != D3D12_COMMAND_LIST_TYPE_DIRECT) return; + auto& pass = pass_of(self); + if (pass.target_count != 1 || !pass.targets[0]) return; + const auto dest = pass.targets[0]->GetDesc(); + if (dest.MipLevels != 1 || dest.DepthOrArraySize != 1 || dest.SampleDesc.Count != 1) return; + std::lock_guard<std::mutex> guard(compute_capture_lock); + if (!capture_selection.matches(s.trace_request, s.pixel_capture_shader->key)) return; + auto seat = std::find_if(compute_capture_slots.begin(), compute_capture_slots.end(), [](auto& w){ return w.expired(); }); + if (seat == compute_capture_slots.end()) return; + auto cap = std::make_shared<ComputeCapture>(); + const auto stage = [&](x2w_compute_trace::Binding b) { + + const auto& focus = capture_focus(); + const auto d = b.texture->GetDesc(); + const auto f = b.view_format == DXGI_FORMAT_UNKNOWN ? d.Format : b.view_format; + const bool ds = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) != 0; + if (d.SampleDesc.Count != 1 || d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || + (ds ? (b.write || b.plane > 1 || !x2w_compute_trace::depth_format(d.Format)) : !x2w_compute_trace::supported(f))) return false; + const auto* state = pass.states.find(b.texture); + if (!state || !((b.plane ? state->stencil : state->depth) & + (b.write ? D3D12_RESOURCE_STATE_RENDER_TARGET : D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE))) return false; + x2w_compute_trace::Image image; + if (!image.init(device_of(the_device), b, &focus)) return false; + cap->images.push_back(std::move(image)); + return true; + }; + if (!stage({pass.targets[0], 0, 0, true, false, 0, 0, pass.target_formats[0]})) return; + for (const auto& b : s.pixel_bindings) stage(b); + cap->pixel = true; + cap->request = s.trace_request; + cap->paired = capture_selection.paired; + cap->frame = InterlockedCompareExchange(&frame_number, 0, 0) + 1; + cap->key = s.pixel_capture_shader->key; + capture_selection.complete(cap->key); + compute_capture_pending.store(capture_selection.id); + *seat = cap; + s.trace_current = cap; + s.trace_captures.push_back(cap); + compute_capture_copy(self, list, *cap, false); + const auto* p = s.pixel_capture_pipeline; + log("x2w-pixel-capture request=%ld frame=%ld shader=%s list=%p command=%s rtv=%p color_mask=%x depth_test=%d depth_write=%d scene inputs captured=%zu/%zu", + cap->request, cap->frame, cap->key.c_str(), static_cast<void*>(self), command, pass.targets[0], p->color_mask, + int(p->depth_test), int(p->depth_write), cap->images.size() - 1, s.pixel_bindings.size()); +} +void pixel_capture_after(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + auto& cap = state_of(self).trace_current; + if (!cap || !cap->pixel) return; + compute_capture_copy(self, list, *cap, true); + cap.reset(); +} + +struct MaterialFeedback { + Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> heap; + x2w_material_trace::Words words{}; + x2w_material::Mask fields{}; +}; +struct MaterialSample { + ID3D12DescriptorHeap* heap{}; + ID3D12Resource* source{}; + UINT64 offset{}; + LONG frame{}; + x2w_material::Mask fields{}; + std::weak_ptr<ComputeCapture> capture; +}; +std::mutex material_feedback_lock; +std::deque<MaterialFeedback> material_ready; +std::array<MaterialSample, 192> material_samples{}; +void collect_material_feedback(ComputeCapture& cap) +{ + x2w_material_trace::Words words{}; + D3D12_RANGE range{0, x2w_material::byte_count(cap.material.fields)}, none{}; + void* ptr{}; + if (FAILED(cap.material.readback->Map(0, &range, &ptr))) return; + std::memcpy(words.data(), ptr, range.End); + cap.material.readback->Unmap(0, &none); + std::lock_guard<std::mutex> guard(material_feedback_lock); + if (material_ready.size() == material_samples.size()) material_ready.pop_front(); + material_ready.push_back({cap.feedback_heap, words, cap.material.fields}); +} +void prepare_material(Wrapper* self, ID3D12GraphicsCommandList* list, GpuListState& s) +{ + static const bool lazy = x2w_local::env_on("X2W_GPU_LAZY_DETILE"); + if (!lazy || !s.host_heaps[0]) return; + std::array<MaterialFeedback, 3> ready; + unsigned n = 0; + { + std::lock_guard<std::mutex> guard(material_feedback_lock); + for (auto it = material_ready.begin(); it != material_ready.end() && n < ready.size();) { + if (it->heap.Get() == s.host_heaps[0]) { + ready[n++] = std::move(*it); + it = material_ready.erase(it); + } else ++it; + } + } + unsigned made = 0; + for (unsigned i = 0; i < n; ++i) made += gpu_materialize(self, s.material_heap, ready[i].words, ready[i].fields); + const auto fields = s.material_shader->material_fields; + const auto r = gpu_material_record(s.material_heap, s.material_raw_slot, s.material_base, fields); + if (!r.source) return; + x2w_material_trace::Words words; + const bool cpu = x2w_material_trace::cpu_words(r, words); + if (cpu) made += gpu_materialize(self, s.material_heap, words, fields); + if (made) { + static LONG count; + if (first_calls(count, 96)) log("x2w-material resident frame=%ld record=%u fenced_records=%u upload_heap=%d slots=%u", + frame_number, s.material_base, n, int(cpu), made); + } + if (cpu) return; + const auto* state = pass_of(self).states.find(r.source.Get()); + if (!state) return; + const auto before = state->depth; + const LONG frame = InterlockedCompareExchange(&frame_number, 0, 0); + std::shared_ptr<ComputeCapture> cap; + { + std::lock_guard<std::mutex> guard(material_feedback_lock); + MaterialSample* dest = nullptr; + unsigned recording = 0; + for (auto& entry : material_samples) { + const bool active = !entry.capture.expired(); + recording += entry.frame == frame && entry.source; + if (entry.heap == s.host_heaps[0] && entry.source == r.source.Get() && entry.offset == r.offset && + (entry.fields & fields) == fields && + (active || frame - entry.frame < 30)) return; + if (!active && (!dest || entry.frame < dest->frame)) dest = &entry; + } + if (!dest || recording >= 12) return; + cap = std::make_shared<ComputeCapture>(); + *dest = {s.host_heaps[0], r.source.Get(), r.offset, frame, fields, cap}; + } + D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_READBACK}; + props.CreationNodeMask = props.VisibleNodeMask = 1; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = x2w_material::byte_count(fields); + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (FAILED(device_of(the_device)->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&cap->material.readback)))) return; + cap->feedback_heap = s.host_heaps[0]; + cap->feedback_source = r.source; + cap->material.fields = fields; + s.trace_captures.push_back(cap); + x2w_material_trace::copy_record(list, r, cap->material.readback.Get(), before, + [&](D3D12_RESOURCE_STATES next) { require_state(self, r.source.Get(), next); }); +} + +void material_capture(Wrapper* self, ID3D12GraphicsCommandList* list, GpuListState& s, ID3D12PipelineState* graphics) +{ + static std::mutex capture_lock; + static std::atomic<LONG> previous{}; + const LONG request = gpu_trace_request_id; + if (!request || request == previous.load() || !s.host_heaps[0]) return; + std::lock_guard<std::mutex> guard(capture_lock); + if (request == previous || request != gpu_trace_request_id) return; + const UINT raw = s.material_raw_slot | (x2w_material_trace::null_index + 1); + if (raw >= s.host_heaps[0]->GetDesc().NumDescriptors) return; + auto* resource = gpu_heap_kept_at(s.material_heap, s.material_raw_slot); + if (resource) { + const auto& states = pass_of(self).states; + const auto* found = states.find(resource); + if (!found || !(found->depth & D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)) return; + } + previous.store(request); + auto cap = std::make_shared<ComputeCapture>(); + auto& p = cap->material; + if (!x2w_material_trace::init(device_of(the_device), p)) { + log("x2w-material request=%ld probe initialization failed", request); + return; + } + cap->request = request; + cap->frame = gpu_trace_frame; + cap->key = s.material_shader->key; + p.fields = s.material_shader->material_fields; + p.raw_slot = s.material_raw_slot; + p.base = s.material_base; + gpu_material_slots(s.material_heap, p.slots); + s.trace_captures.push_back(cap); + x2w_material_trace::record(list, p, gpu_heap_gpu_handle(s.material_heap, raw)); + list->SetPipelineState(graphics); + s.host_roots[1] = nullptr; + log("x2w-material request=%ld frame=%ld list=%p captured material table=%u record=%u", request, + cap->frame, static_cast<void*>(self), p.raw_slot, p.base); +} + +void compute_capture_save(ComputeCapture& cap) +{ + if (cap.feedback_heap) { + collect_material_feedback(cap); + return; + } + if (cap.material.readback) { + auto& p = cap.material; + D3D12_RANGE range{0, x2w_material::byte_count(p.fields)}, none{}; + void* data{}; + if (FAILED(p.readback->Map(0, &range, &data))) return; + for (UINT field = 0; field < range.End; field += 4) { + if (!(p.fields & (1u << (field / 4)))) continue; + const UINT word = static_cast<const UINT*>(data)[field / 4]; + const UINT index = x2w_material_trace::index(word); + const auto it = std::find_if(p.slots.begin(), p.slots.end(), [index](auto& slot) { return slot.index == index; }); + const x2w_material_trace::Slot empty{}; + const auto& slot = it == p.slots.end() ? empty : *it; + log("x2w-material request=%ld frame=%ld shader=%s table=%u record=%u field=%u word=%08x index=%u " + "observed_at_record=%d host=%llx dimension=%u size=%ux%u format=%u view_format=%u address=%llx " + "lazy_pending=%d late_pending=%d feedback_retry=%s words=%08x,%08x,%08x,%08x,%08x,%08x,%08x,%08x", + cap.request, cap.frame, cap.key.c_str(), p.raw_slot, p.base, field, word, index, it != p.slots.end(), + slot.host, slot.dimension, slot.width, slot.height, slot.format, slot.view_format, slot.texture_address, + int(slot.lazy), int(slot.late), slot.material_retry, slot.words[0], slot.words[1], slot.words[2], slot.words[3], + slot.words[4], slot.words[5], slot.words[6], slot.words[7]); + } + p.readback->Unmap(0, &none); + std::vector<x2w_material_trace::Slot>{}.swap(p.slots); + return; + } + wchar_t root[MAX_PATH]{}; + const DWORD len = GetEnvironmentVariableW(L"X2W_TRACE_TARGET_DIR", root, MAX_PATH); + if (!len || len >= MAX_PATH) return; + auto dir = std::filesystem::path(root) / ((cap.pixel ? L"pixel-request-" : L"compute-request-") + std::to_wstring(cap.request)); + if (cap.paired) dir += "-" + cap.key; + std::error_code ec; + if (!std::filesystem::create_directory(dir, ec)) { + log("x2w-compute-capture request %ld needs a fresh directory, error %d", cap.request, ec.value()); + return; + } + x2w_compute_trace::IndirectArguments::Snapshot args{}; + if (cap.indirect.read(args)) { + const auto& indirect = cap.indirect; + const UINT active = (std::min)(indirect.copied, args.count); + FILE* table = nullptr; + _wfopen_s(&table, (dir / L"indirect-arguments.tsv").c_str(), L"wbx"); + if (table) { + std::fprintf(table, "kind\tstride\tmaximum\tcount_buffer\teffective\tsampled\n%u\t%u\t%u\t%u\t%u\t%u\n", + indirect.kind, indirect.stride, indirect.maximum, unsigned(indirect.counted), args.count, active); + if (indirect.kind == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW) + std::fputs("record\tvertex_count\tinstance_count\tstart_vertex\tstart_instance\n", table); + else if (indirect.kind == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED) + std::fputs("record\tindex_count\tinstance_count\tstart_index\tbase_vertex\tstart_instance\n", table); + else std::fputs("record\tgroups_x\tgroups_y\tgroups_z\n", table); + } + log("x2w-pixel-capture request=%ld frame=%ld shader=%s indirect kind=%u stride=%u maximum=%u counted=%u effective=%u sampled=%u", + cap.request, cap.frame, cap.key.c_str(), indirect.kind, indirect.stride, indirect.maximum, unsigned(indirect.counted), args.count, active); + for (UINT i = 0; i < active; ++i) { + const auto& r = args.records[i]; + if (table) { + std::fprintf(table, "%u", i); + for (UINT field = 0; field < indirect.fields; ++field) { + if (indirect.kind == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED && field == 3) + std::fprintf(table, "\t%d", static_cast<INT>(r[field])); + else std::fprintf(table, "\t%u", r[field]); + } + std::fputc('\n', table); + } + log("x2w-pixel-capture request=%ld frame=%ld shader=%s indirect record=%u fields=%u words=%u,%u,%u,%u,%u", + cap.request, cap.frame, cap.key.c_str(), i, indirect.fields, r[0], r[1], r[2], r[3], r[4]); + } + if (table) std::fclose(table); + } + for (const auto& image : cap.images) { + const auto& b = image.binding; + for (unsigned phase = 0; phase < (b.write ? 2u : 1u); ++phase) { + auto* buffer = phase ? image.post.Get() : image.pre.Get(); + const auto& area = image.footprint.Footprint; + const D3D12_RANGE range{0, static_cast<SIZE_T>(image.size)}; + void* mapped = nullptr; + if (FAILED(buffer->Map(0, &range, &mapped))) continue; + const auto* pixels = static_cast<const unsigned char*>(mapped) + image.footprint.Offset; + wchar_t label[96]{}; + const wchar_t* role = b.write ? (cap.pixel ? L"rtv" : L"uav") : L"srv"; + swprintf_s(label, L"%ls-%u-%u-%ls", role, b.slot, b.offset, phase ? L"post" : L"pre"); + const auto stem = dir / label; + if (cap.pixel) log("x2w-pixel-capture request=%ld shader=%s role=%ls slot=%u offset_dwords=%u " + "mip=%u first_slice=%u plane=%u resource_format=%u view_format=%u", cap.request, cap.key.c_str(), role, b.slot, b.offset, + b.mip, b.slice, b.plane, UINT(image.source->GetDesc().Format), UINT(b.view_format)); + const UINT total_rows = image.height() * area.Depth; + const UINT64 row_bytes = image.output_row_bytes(); + UINT64 hash = 14695981039346656037ull, nonzero = 0; + for (UINT y = 0; y < total_rows; ++y) { + const auto* row = image.row(pixels, y % image.height(), y / image.height()); + for (UINT64 x = 0; x < row_bytes; ++x) { + hash = (hash ^ row[x]) * 1099511628211ull; + nonzero += row[x] != 0; + } + } + FILE* file = nullptr; + bool raw = false, bmp = false; + if (_wfopen_s(&file, (stem.wstring() + L".bin").c_str(), L"wbx") == 0) { + raw = true; + for (UINT y = 0; y < total_rows && raw; ++y) + raw = std::fwrite(image.row(pixels, y % image.height(), y / image.height()), 1, SIZE_T(row_bytes), file) == row_bytes; + raw = std::fclose(file) == 0 && raw; + } + if (x2w_draw_bmp::trace_supported(area.Format)) { + bmp = true; + for (UINT z = 0; z < area.Depth; ++z) { + if (z != 0 && z != area.Depth / 2 && z != area.Depth - 1) continue; + const auto suffix = image.source_depth > 1 ? L"-z" + std::to_wstring(image.source_z(z)) : L""; + if (_wfopen_s(&file, (stem.wstring() + suffix + L".bmp").c_str(), L"wbx") != 0) { bmp = false; continue; } + const auto* plane = image.row(pixels, 0, z); + const bool ok = x2w_draw_bmp::write(file, plane, image.width(), image.height(), area.RowPitch, area.Format); + bmp = (std::fclose(file) == 0 && ok) && bmp; + } + } + const D3D12_RANGE none{0,0}; + buffer->Unmap(0, &none); + log("x2w-%s-capture request=%ld frame=%ld shader=%s slot=%u offset_dwords=%u %ls %s resource=%p " + "fmt=%u box=%u,%u %ux%u depth=%u/%u layout=%s rowbytes=%llu fnv64=%016llx nonzero_bytes=%llu raw=%u bmp=%u", + cap.pixel ? "pixel" : "compute", cap.request, cap.frame, cap.key.c_str(), + b.slot, b.offset, role, phase ? "post" : "pre", static_cast<void*>(b.texture), + UINT(area.Format), image.box.left, image.box.top, image.width(), image.height(), area.Depth, image.source_depth, + image.full_depth_plane ? (b.plane ? "stencil-plane-1" : "depth-plane-0") : + image.sparse ? "first-middle-last" : "contiguous", row_bytes, hash, nonzero, raw, bmp); + } + } +} + +void compute_capture_submitted(const std::shared_ptr<ComputeCapture>& cap, ID3D12Fence* fence, UINT64 value) +{ + auto& flights = compute_capture_flights; + if (std::find(flights.begin(), flights.end(), cap) == flights.end()) flights.push_back(cap); + compute_capture_in_flight.store(true); + if (!fence) { + cap->unfenced = true; + log("x2w-compute-capture request %ld queue fence failed; retaining buffers", cap->request); + return; + } + for (auto& f : cap->fences) + if (f.first == fence) { f.second = value; return; } + cap->fences.emplace_back(fence, value); // queue_fences owns the fence for the lifetime of the device +} +// Called only under draw_lock, which serializes every native submission and therefore replay. +void compute_capture_poll_locked() +{ + auto& flights = compute_capture_flights; + for (auto it = flights.begin(); it != flights.end();) { + auto& cap = **it; + if (cap.unfenced) { ++it; continue; } + bool ready = true, removed = false; + for (const auto& f : cap.fences) { + const auto completed = f.first->GetCompletedValue(); + if (completed == UINT64_MAX) removed = true; + else if (completed < f.second) ready = false; + } + if (!ready) { ++it; continue; } + if (!removed && !cap.published) compute_capture_save(cap); + cap.published = true; + cap.fences.clear(); + it = flights.erase(it); + } + compute_capture_in_flight.store(!flights.empty()); +} diff --git a/src/startup_stubs/gpu_db.cpp b/src/startup_stubs/gpu_db.cpp new file mode 100644 index 0000000000..bc5d1ffd79 --- /dev/null +++ b/src/startup_stubs/gpu_db.cpp @@ -0,0 +1,241 @@ +// Shader database reader (WP1, vexport): contract C1-C6 over X2W's shader database (src/shader_db). The database is +// the file x2w_shaders writes (x2w_shaders.vxdb), from a shader export (--payload) or from the C++ translator port. +// It is found at %X2W_GPU_DB%, else %X2W_SHADER_CACHE%\x2w_shaders.vxdb, mapped once at the first lookup and +// kept for the process. Its manifest must agree with abi::view_heap_limit and, with twins on, abi::raw_views (0 +// with X2W_GPU_TWINS=0); otherwise nothing is loaded and every lookup misses. Lookups after the load take no +// lock; a miss is logged once per key (C6). +#include "startup_stubs/gpu_db.h" +#include "startup_stubs/gpu_material_fields.h" + +#include <algorithm> +#include <cstring> +#include <mutex> +#include <string> +#include <unordered_set> +#include <vector> + +#include "shader_db/shader_db.h" +#include "startup_stubs/blake3/blake3.h" +#include "startup_stubs/local_log.h" + +namespace x2w_gpu { + +void gpu_key(const void* bytes, std::size_t size, char out[17]) noexcept +{ + blake3_hasher hasher; + blake3_hasher_init(&hasher); + if (size) blake3_hasher_update(&hasher, bytes, size); + std::uint8_t hash[8]; + blake3_hasher_finalize(&hasher, hash, sizeof(hash)); + static const char digits[] = "0123456789abcdef"; + for (int i = 0; i < 8; ++i) { + out[2 * i] = digits[hash[i] >> 4]; + out[2 * i + 1] = digits[hash[i] & 15]; + } + out[16] = 0; +} + +namespace { + +static_assert(sizeof(GpuSamplerWords) == 16, "sampler words as stored"); +static_assert(sizeof(GpuStaticSampler) == sizeof(shader_db::VxStaticSampler), "static sampler as stored"); +static_assert(sizeof(GpuRootIndexedView) == sizeof(shader_db::VxRootIndexedView), "root indexed view as stored"); + +struct Loaded { + bool ok = false; + std::vector<std::uint64_t> keys; // sorted, parallel to shaders + std::vector<GpuShader> shaders; + std::vector<GpuUserData> user_data; + std::vector<GpuUsedResource> used; + GpuManifest manifest{}; + std::mutex miss_lock; + std::unordered_set<std::uint64_t> missed; +}; + +void log_line(const char* line) { x2w_local::logf("x2w-gpu %s", line); } + +GpuRootType root_of(std::uint32_t code, std::uint32_t& other) +{ + other = 0; + if (code < shader_db::root_other_base) return static_cast<GpuRootType>(code); + other = code - shader_db::root_other_base; + return GpuRootType::other; +} + +GpuStage title_stage(shader_db::Stage s) +{ + switch (s) { + case shader_db::Stage::vs: return GpuStage::vertex; + case shader_db::Stage::ps: return GpuStage::pixel; + case shader_db::Stage::ms: return GpuStage::mesh; + case shader_db::Stage::cs: return GpuStage::compute; + default: return GpuStage::count; + } +} + +bool switch_set(const char* value) { return value[0] && std::strcmp(value, "0") != 0; } + +std::wstring database_path() +{ + wchar_t path[MAX_PATH]; + DWORD n = GetEnvironmentVariableW(L"X2W_GPU_DB", path, MAX_PATH); + if (n && n < MAX_PATH) return path; + n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", path, MAX_PATH); + if (n && n < MAX_PATH) return std::wstring(path) + L"\\x2w_shaders.vxdb"; + return {}; +} + +void load(Loaded& l) +{ + const DWORD saved = GetLastError(); + const std::wstring path = database_path(); + if (path.empty()) { + x2w_local::logf("x2w-gpu db: no database (set X2W_GPU_DB or X2W_SHADER_CACHE); every shader misses"); + SetLastError(saved); + return; + } + const std::uint32_t raw_views = gpu_twins_on() ? abi::raw_views : 0; + if (!shader_db::gpu_db_open(path.c_str(), abi::view_heap_limit, 0, log_line)) { + SetLastError(saved); + return; + } + const shader_db::Manifest& m = *shader_db::gpu_db_manifest(); + if (m.raw_views != raw_views) { + x2w_local::logf("x2w-gpu db: refused: made with raw_views %u, this run's heap has %u (X2W_GPU_TWINS)", m.raw_views, raw_views); + shader_db::gpu_db_close(); + SetLastError(saved); + return; + } + GpuManifest& v = l.manifest; + v.view_heap_limit = m.view_heap_limit; + v.raw_views = m.raw_views; + v.host_rdna = m.host_rdna != 0; + v.max_wave = m.max_wave; + v.opt_bits = m.shader_opt; + v.group_sync = m.group_sync != 0; + v.helper_own = switch_set(m.helper_own); + v.bvh_bits = (switch_set(m.bvh_fences) ? 1u : 0u) | (switch_set(m.bvh_bounds) ? 2u : 0u); + std::snprintf(v.commit, sizeof(v.commit), "%s", m.commit); + + const std::size_t count = shader_db::gpu_db_count(); + std::size_t user_data = 0, used = 0; + for (std::size_t i = 0; i < count; ++i) { + user_data += shader_db::gpu_db_at(i)->user_data_count; + used += shader_db::gpu_db_at(i)->used_count; + } + l.user_data.reserve(user_data); // the spans below point into these: no reallocation after reserve + l.used.reserve(used); + l.keys.reserve(count); + l.shaders.resize(count); + for (std::size_t i = 0; i < count; ++i) { + const shader_db::GpuShader& s = *shader_db::gpu_db_at(i); + GpuShader& o = l.shaders[i]; + std::snprintf(o.key, sizeof(o.key), "%016llx", static_cast<unsigned long long>(s.key)); + o.stage = title_stage(s.stage); + o.hw_stage = static_cast<GpuHwStage>(s.stage); + o.dxil = s.dxil; + o.dxil_bytes = s.dxil_bytes; + o.material_fields = o.stage == GpuStage::pixel ? x2w_material::lookup(s.key, s.dxil, s.dxil_bytes) : 0; + const std::size_t ud_first = l.user_data.size(); + for (std::uint32_t k = 0; k < s.user_data_count; ++k) { + const shader_db::VxUserData& u = s.user_data[k]; + GpuUserData d{}; + d.index = u.index; + d.slot = u.slot; + d.root = root_of(u.root, d.other); + d.dword = u.dword; + l.user_data.push_back(d); + } + o.user_data = {l.user_data.data() + ud_first, s.user_data_count}; + o.samplers = {reinterpret_cast<const GpuSamplerWords*>(s.samplers), s.sampler_count}; + o.static_samplers = {reinterpret_cast<const GpuStaticSampler*>(s.static_samplers), s.static_sampler_count}; + o.root_cbvs = {s.root_cbvs, s.root_cbv_count}; + o.root_srvs = {s.root_srvs, s.root_srv_count}; + o.root_uavs = {s.root_uavs, s.root_uav_count}; + o.root_indexed_views = {reinterpret_cast<const GpuRootIndexedView*>(s.root_indexed_views), s.root_indexed_view_count}; + o.has_threads = s.has_threads; + std::memcpy(o.threads, s.threads, sizeof(o.threads)); + const std::size_t used_first = l.used.size(); + for (std::uint32_t k = 0; k < s.used_count; ++k) { + const shader_db::VxUsed& u = s.used[k]; + GpuUsedResource d{}; + if (u.kind < shader_db::resource_other_base) { + d.kind = static_cast<GpuResourceType>(u.kind); + } else { + d.kind = GpuResourceType::other; + d.other_kind = static_cast<std::uint8_t>(u.kind - shader_db::resource_other_base); + } + d.root = root_of(u.root, d.root_other); + d.table_offset_dwords = u.table_offset_dwords; + d.lower_bound = u.lower_bound; + d.stride = u.stride; + d.dwords = static_cast<std::uint8_t>(u.dwords); + d.user_data = static_cast<std::uint8_t>(u.user_data); + d.slot = static_cast<std::uint8_t>(u.slot); + l.used.push_back(d); + } + o.used = {l.used.data() + used_first, s.used_count}; + o.stores = s.stores; + o.stores_by_address = s.stores_by_address; + o.builder = s.builder; + l.keys.push_back(s.key); + } + l.ok = true; + SetLastError(saved); +} + +Loaded& loaded() +{ + static Loaded l; + static std::once_flag once; + std::call_once(once, [] { load(l); }); + return l; +} + +std::uint64_t parse_key(const char key[17]) +{ + std::uint64_t v = 0; + for (int i = 0; i < 16; ++i) { + const char c = key[i]; + const int d = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1; + if (d < 0) return 0; + v = v << 4 | static_cast<std::uint64_t>(d); + } + return v; +} + +const GpuShader* find(std::uint64_t key, GpuStage stage, std::size_t bytes) +{ + Loaded& l = loaded(); + const GpuShader* found = nullptr; + if (l.ok) { + const auto at = std::lower_bound(l.keys.begin(), l.keys.end(), key); + if (at != l.keys.end() && *at == key) found = &l.shaders[static_cast<std::size_t>(at - l.keys.begin())]; + } + if (found && found->stage == stage) return found; + std::lock_guard<std::mutex> hold(l.miss_lock); + if (l.missed.insert(key).second) + x2w_local::logf("x2w-gpu db miss key=%016llx stage=%s bytes=%zu%s%s", static_cast<unsigned long long>(key), gpu_stage_name(stage), bytes, + found ? " recorded as " : "", found ? gpu_stage_name(found->stage) : ""); + return nullptr; +} + +} // namespace + +const GpuShader* gpu_shader(const void* bytes, std::size_t size, GpuStage stage) noexcept +{ + if (!bytes || !size) return nullptr; + char key[17]; + gpu_key(bytes, size, key); + return find(parse_key(key), stage, size); +} + +const GpuShader* gpu_shader_by_key(const char key[17], GpuStage stage) noexcept { return find(parse_key(key), stage, 0); } + +const GpuManifest* gpu_manifest() noexcept +{ + Loaded& l = loaded(); + return l.ok ? &l.manifest : nullptr; +} + +} // namespace x2w_gpu diff --git a/src/startup_stubs/gpu_db.h b/src/startup_stubs/gpu_db.h new file mode 100644 index 0000000000..a2fc8162e3 --- /dev/null +++ b/src/startup_stubs/gpu_db.h @@ -0,0 +1,22 @@ +// Shader database reader (WP1, vexport): the C1-C6 contract over X2W's shader database (src/shader_db), +// memory-mapped and thread-safe. gpu_db.cpp says where the database file is found. +#pragma once + +#include "startup_stubs/gpu_abi.h" + +namespace x2w_gpu { + +// The C1 key of `bytes` (blake3, first 16 hex digits, lowercase), into out[17]. Implemented in gpu_db.cpp on the +// vendored reference code (startup_stubs/blake3/, portable only). +void gpu_key(const void* bytes, std::size_t size, char out[17]) noexcept; + +// C5 lookup: the record for the bytecode as created at `stage`, or null (C6: the reader logs a miss once per key). +const GpuShader* gpu_shader(const void* bytes, std::size_t size, GpuStage stage) noexcept; +// The same by a key already computed (the creation slots compute it for the G0 key log). +const GpuShader* gpu_shader_by_key(const char key[17], GpuStage stage) noexcept; + +// C3: the manifest of the loaded export, or null when none is loaded. The reader refuses an export whose +// view_heap_limit / raw_views disagree with abi:: and gpu_twins_on(). +const GpuManifest* gpu_manifest() noexcept; + +} // namespace x2w_gpu diff --git a/src/startup_stubs/gpu_depth_twins.h b/src/startup_stubs/gpu_depth_twins.h new file mode 100644 index 0000000000..4d7163f391 --- /dev/null +++ b/src/startup_stubs/gpu_depth_twins.h @@ -0,0 +1,121 @@ +#pragma once + +#include <d3d12.h> +#include <wrl/client.h> +#include <vector> + +namespace x2w_depth_twins { +using Microsoft::WRL::ComPtr; + +struct Twins { + ComPtr<ID3D12Resource> depth, colour, depth_plane, through; + std::vector<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> stencil_rows; + + bool create(ID3D12Device* device, ID3D12Resource* original, const D3D12_RESOURCE_DESC& title) + { + constexpr auto both = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if (!original || (title.Flags & both) != both) return false; + auto d = original->GetDesc(); + if (d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || d.SampleDesc.Count != 1) return false; + const auto of = d; + bool stencil = false; + switch (d.Format) { + case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_D32_FLOAT: d.Format = DXGI_FORMAT_R32_TYPELESS; break; + case DXGI_FORMAT_R16_TYPELESS: case DXGI_FORMAT_D16_UNORM: d.Format = DXGI_FORMAT_R16_TYPELESS; break; + case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: + case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_D24_UNORM_S8_UINT: + stencil = true; + d.Format = DXGI_FORMAT_R8_TYPELESS; + break; + default: return false; + } + d.Alignment = 0; + d.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto allocate = [&](const D3D12_RESOURCE_DESC& desc, ComPtr<ID3D12Resource>& result) { + return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&result))); + }; + if (!allocate(d, colour)) return false; + if (stencil) { + const UINT planes = UINT{of.MipLevels} * of.DepthOrArraySize; + stencil_rows.resize(planes); + UINT64 bytes = 0; + device->GetCopyableFootprints(&of, planes, planes, 0, stencil_rows.data(), nullptr, nullptr, &bytes); + if (!bytes || bytes == UINT64_MAX) return false; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = bytes; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (!allocate(buffer, through)) return false; + const auto format = static_cast<UINT>(title.Format); + d.Format = format >= 118 && format <= 120 ? DXGI_FORMAT_R16_TYPELESS : DXGI_FORMAT_R32_TYPELESS; + if (!allocate(d, depth_plane)) return false; + } + depth = original; + return true; + } + + // Extract the selected depth/stencil plane into a single-plane host texture. + ID3D12Resource* view(const D3D12_UNORDERED_ACCESS_VIEW_DESC* input, D3D12_UNORDERED_ACCESS_VIEW_DESC& out) const + { + if (!depth || !colour) return nullptr; + out = input ? *input : D3D12_UNORDERED_ACCESS_VIEW_DESC{}; + if (!input) { + const UINT slices = depth->GetDesc().DepthOrArraySize; + out.ViewDimension = slices > 1 ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : D3D12_UAV_DIMENSION_TEXTURE2D; + if (slices > 1) out.Texture2DArray.ArraySize = slices; + } + UINT* plane = nullptr; + if (out.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2D) plane = &out.Texture2D.PlaneSlice; + if (out.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY) plane = &out.Texture2DArray.PlaneSlice; + if (!plane || *plane > 1) return nullptr; + if (through && (*plane == 1 || out.Format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT || out.Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT)) { + *plane = 0; + out.Format = DXGI_FORMAT_R8_UINT; + return colour.Get(); + } + if (*plane != 0) return nullptr; + ID3D12Resource* backing = through ? depth_plane.Get() : colour.Get(); + if (!backing) return nullptr; + const DXGI_FORMAT f = out.Format; + const bool depth_stencil = (f >= 19 && f <= 21) || (f >= 44 && f <= 46); + const bool steps = backing->GetDesc().Format == DXGI_FORMAT_R16_TYPELESS; + if (f == DXGI_FORMAT_UNKNOWN || depth_stencil || (steps && (f == DXGI_FORMAT_R16_TYPELESS || f == DXGI_FORMAT_D16_UNORM)) || + (!steps && (f == DXGI_FORMAT_R32_TYPELESS || f == DXGI_FORMAT_D32_FLOAT))) + out.Format = steps ? DXGI_FORMAT_R16_UNORM : DXGI_FORMAT_R32_FLOAT; + return backing; + } + + // One-plane depth is a bit-compatible copy. Stencil uses the depth resource's plane footprints, + // including row alignment, for both legs. The caller owns the states of depth and colour. + template<class SetState> + void copy_colour(ID3D12GraphicsCommandList* list, bool to_colour, SetState&& state) const + { + ID3D12Resource* from = to_colour ? depth.Get() : colour.Get(); + ID3D12Resource* to = to_colour ? colour.Get() : depth.Get(); + state(from, D3D12_RESOURCE_STATE_COPY_SOURCE); + state(to, D3D12_RESOURCE_STATE_COPY_DEST); + if (!through) { + list->CopyResource(to, from); + return; + } + const UINT plane_count = static_cast<UINT>(stencil_rows.size()); + const auto leg = [&](bool into_buffer) { + state(through.Get(), into_buffer ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COPY_SOURCE); + for (UINT i = 0; i < plane_count; ++i) { + D3D12_TEXTURE_COPY_LOCATION buffer{through.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + buffer.PlacedFootprint = stencil_rows[i]; + D3D12_TEXTURE_COPY_LOCATION texture{into_buffer ? from : to, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + texture.SubresourceIndex = i + (texture.pResource == depth.Get() ? plane_count : 0); + list->CopyTextureRegion(into_buffer ? &buffer : &texture, 0, 0, 0, into_buffer ? &texture : &buffer, nullptr); + } + }; + leg(true); + leg(false); + } +}; +} diff --git a/src/startup_stubs/gpu_find.h b/src/startup_stubs/gpu_find.h new file mode 100644 index 0000000000..bc7bcff375 --- /dev/null +++ b/src/startup_stubs/gpu_find.h @@ -0,0 +1,78 @@ +// Translated shader ABI memory adapter (PLAN.md section 1.5, WP3, owner vbind): what lies at a title GPU address, +// bounded by the title buffer or the contiguous run of its window. Included by d3d12_xs_device.cpp inside its +// anonymous namespace, before gpu_bind.inl (it uses desktop_range and the address indexes). Contract: +// gpu_hooks.h. The bounding itself is x2w_vbind::find_bounded (gpu_roots.h, header-tested); this is X2W's +// side of it. +#pragma once + +namespace vbind { +bool buffer_extent(std::uint64_t address, std::uint64_t* base, std::uint64_t* end, const Wrapper** identity, + std::uint64_t length = 1) +{ + x2w_vbind::TitleBufferExtent extent; + AcquireSRWLockShared(¬e_lock); + resource_address_index().for_each_reaching(address, 1, [&](const Wrapper* w) { + const auto it = resource_infos().find(w); + if (it == resource_infos().end()) return false; + const ResourceInfo& info = it->second; + if (info.console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) return false; + if (InterlockedCompareExchange(&const_cast<Wrapper*>(w)->own().refs, 0, 0) <= 0) return false; + const std::uint64_t b = reinterpret_cast<std::uint64_t>(w->own().title_memory), width = info.console.Width; + extent.consider(address, length, b, width, reinterpret_cast<std::uintptr_t>(w)); + return false; + }); + ReleaseSRWLockShared(¬e_lock); + if (!extent.base) return false; + *base = extent.base; + *end = extent.end; + if (identity) *identity = reinterpret_cast<const Wrapper*>(extent.identity); + return true; +} +// find_bounded over X2W: windows from desktop_range (cached per frame), extents from the resource records. +bool find(std::uint64_t address, std::uint64_t len, std::uint64_t most, std::uint64_t unknown_most, x2w_vbind::Found* out) +{ + // Title buffers can be created or released mid-frame. Recheck the live extent, + // then reuse the prefix previously validated against this frame's desktop windows. + std::uint64_t base = 0, end = 0; + const bool known = address && len && buffer_extent(address, &base, &end, nullptr, len) && end > address; + const auto limit = (std::min)(most, known ? end - address : unknown_most); + struct Prefix { + std::uint64_t address{}, len{}, limit{}, generation{}; + LONG frame{-1}; + x2w_vbind::Found found{}; + }; + static thread_local std::array<Prefix, 256> prefixes{}; + const LONG frame = frame_number; + const auto generation = gpu_mapping_generation(); + const auto mix = (address ^ (len * 1099511628211ull) ^ limit) * 0x9e3779b97f4a7c15ull; + auto& slot = prefixes[(mix >> 32) % prefixes.size()]; + if (slot.frame == frame && slot.generation == generation && slot.address == address && slot.len == len && slot.limit == limit && + slot.found.known_extent == known) { + *out = slot.found; + return true; + } + const bool found = x2w_vbind::find_bounded(address, len, most, unknown_most, + [&](std::uint64_t, std::uint64_t* b, std::uint64_t* e) { *b = base; *e = end; return known; }, + [](std::uint64_t a, std::uint64_t n, void** buffer, std::uint64_t* offset) { + ID3D12Resource* b = nullptr; + const bool ok = desktop_range(a, n, &b, offset); + *buffer = b; + return ok && b; + }, out); + if (found && gpu_mapping_generation() == generation) slot = {address, len, limit, generation, frame, *out}; + return found; +} +} // namespace vbind + +bool gpu_find(std::uint64_t address, std::uint64_t bytes, GpuFound* out) +{ + x2w_vbind::Found f; + if (!out) return false; + *out = {}; + const std::uint64_t len = bytes ? bytes : 1; + if (!vbind::find(address, len, ~0ull, len, &f)) return false; + out->resource = static_cast<ID3D12Resource*>(f.buffer); + out->offset = f.offset; + out->bytes_left = f.left; + return true; +} diff --git a/src/startup_stubs/gpu_heap.h b/src/startup_stubs/gpu_heap.h new file mode 100644 index 0000000000..ebbe2ae200 --- /dev/null +++ b/src/startup_stubs/gpu_heap.h @@ -0,0 +1,502 @@ +// Device-independent mirror heap layout, stride tracking, descriptor diffs and dynamic slot allocation. +// +// For a host supporting 2^22 views, slots [0,count) mirror the title heap. Dynamic table slots follow. Shaders +// clamp indices to the null slot at 2^21 - 1. The raw twin of slot i is at 2^21 + i. Unused twin slots hold null +// raw buffer views. +#pragma once + +#include "startup_stubs/gpu_abi.h" +#include "startup_stubs/gpu_as_address.h" +#include "startup_stubs/gpu_depth_twins.h" +#include "startup_stubs/gpu_late_texture.h" +#include <map> +#include <set> + +#include <windows.h> +#include <d3d12.h> + +#include <algorithm> +#include <atomic> +#include <cstdarg> +#include <cstddef> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <deque> +#include <memory> +#include <mutex> +#include <optional> +#include <type_traits> +#include <unordered_map> +#include <vector> + +namespace gpu_heap { + +using u32 = std::uint32_t; +using u64 = std::uint64_t; + +// What a host that caps view heaps (NVIDIA) takes. +constexpr u32 portable_views = 1'000'000; +// Every view heap on a host that takes more; the last is the null slot. +constexpr u32 uncapped_views = 1u << 21; +// Where the raw twins start in a heap that has them. +constexpr u32 raw_twins_first = 1u << 21; +// Base dynamic slot count. +constexpr u32 dynamic_base = 1u << 18; +// X2W_SHADERCFG_DYNAMIC_SLOTS defaults to DYNAMIC << 2. +constexpr u32 dynamic_most_default = dynamic_base << 2; + +// Table of buffer element strides at t255 in the root CBV space. Each view slot has one dword. +constexpr u32 slot_strides_count = 1u << 21; +constexpr u32 view_stride_bits = (1u << 30) - 1; +constexpr u32 view_integer = 1u << 31; +constexpr u32 view_signed = 1u << 30; + +static_assert(raw_twins_first == x2w_gpu::abi::raw_views, "twins at the export's raw_views"); +static_assert(uncapped_views - 1 == x2w_gpu::abi::view_heap_limit, "the null slot the export clamps to"); +static_assert(2 * raw_twins_first == x2w_gpu::abi::heap_views_with_twins, "2^22 views with twins"); +static_assert(dynamic_base == x2w_gpu::abi::dynamic_min && dynamic_most_default == x2w_gpu::abi::dynamic_max, + "dynamic_slots bounds"); + +// Bytes per descriptor by heap type (views, samplers, RTV, DSV). +inline std::optional<u32> increment(u32 kind) +{ + constexpr u32 steps[4] = {32, 16, 128, 128}; + if (kind < 4) return steps[kind]; + return std::nullopt; +} + +// What probe_view_limit settles once: the null slot every view index is clamped to, and where +// the raw twins start (0: none). +struct Limits { + u32 views = 0; // heap ends at the null slot views - 1 (without twins) + u32 raw = 0; // raw twins' first slot, 0 if none + u32 null() const { return views - 1; } +}; + +// `fits(count)` says whether the host takes a shader-visible view heap of `count` descriptors. With twins wanted, a +// host that takes 2 * RAW_TWINS gets them. +template <class Fits> +Limits probe_view_limit(bool twins_wanted, Fits&& fits) +{ + Limits l; + const bool twins = twins_wanted && fits(2 * raw_twins_first); + if (twins) l.raw = raw_twins_first; + if (twins) l.views = raw_twins_first; + else if (fits(uncapped_views)) l.views = uncapped_views; + else l.views = portable_views; + return l; +} + +// DYNAMIC, or up to four times as many where the host heap has room. +inline u32 dynamic_slots(u32 count, u32 null, u32 most = dynamic_most_default) +{ + if (null < portable_views) return dynamic_base; + const u32 room = null > count ? null - count : 0; + return (std::max)((std::min)(room, most), dynamic_base); +} + +// The layout of one host heap: what is made, and where. +struct Layout { + bool sampler = false; + u32 title = 0; // the title's own count + u32 count = 0; // title slots that have host slots (fewer if capped) + u32 dynamic = 0; // dynamic slots, from `count` on + u32 null = 0; // the null slot (0: none, sampler heaps) + u32 raw = 0; // first twin slot (0: none) + u32 size = 0; // descriptors in the host heap + u32 twins = 0; // slots with a twin: [0, twins) + bool capped = false; + + u32 twin(u32 index) const { return raw + index; } + bool has_twin(u32 index) const { return raw != 0 && index < twins; } + bool is_dynamic(u32 index) const { return index >= count && index - count < dynamic; } + // The host slot a shader's view index reads (indices at or past the null slot are clamped + // there by the translated shader, twins excepted). + u32 clamp(u32 index) const { return null && index > null ? null : index; } + // How many slots fill_null makes plain null views before the twins' null buffer views. + u32 null_views_end() const { return raw ? (std::min)(raw, size) : size; } +}; + +inline Layout layout_for(bool sampler, u32 count, const Limits& limits, u32 most = dynamic_most_default) +{ + Layout l; + l.sampler = sampler; + l.title = count; + const u32 null = sampler ? 0 : limits.null(); + const u32 raw = sampler ? 0 : limits.raw; + const u32 extra = sampler ? 0 : dynamic_slots(count, null, most); + l.dynamic = extra; + l.null = null; + l.raw = raw; + if (null == 0) { + l.count = count; + l.size = count + extra; + } else { + l.size = raw == 0 ? null + 1 : 2 * raw; + if (u64{count} + extra <= null) { + l.count = count; + } else { + // Descriptors beyond the host limit read the null slot. + l.count = null > extra ? null - extra : 0; + l.capped = true; + } + } + l.twins = raw == 0 ? 0 : l.count + extra; + return l; +} + +// Bytes per element and the element's width in texels, by DXGI format. +struct Element { u64 bytes, block; }; +inline std::optional<Element> element(u32 f) +{ + if (f >= 1 && f <= 4) return Element{16, 1}; + if (f >= 5 && f <= 8) return Element{12, 1}; + if (f >= 9 && f <= 22) return Element{8, 1}; + if ((f >= 23 && f <= 47) || f == 67 || (f >= 87 && f <= 93) || f == 116 || f == 117 || f == 189 || f == 191) + return Element{4, 1}; + if (f >= 118 && f <= 120) return Element{3, 1}; + if ((f >= 48 && f <= 59) || f == 68 || f == 69 || f == 85 || f == 86 || f == 115) return Element{2, 1}; + if ((f >= 60 && f <= 65) || f == 190) return Element{1, 1}; + if ((f >= 70 && f <= 72) || (f >= 79 && f <= 81)) return Element{8, 4}; + if ((f >= 73 && f <= 78) || (f >= 82 && f <= 84) || (f >= 94 && f <= 99)) return Element{16, 4}; + return std::nullopt; +} +inline u64 element_bytes(u32 f) { auto e = element(f); return e ? e->bytes : 0; } + +// The console's 16-bit depth with stencil has no PC format. +inline u32 pc_format(u32 f) +{ + switch (f) { + case 118: return 45; + case 119: return 46; + case 120: return 47; + default: return f; + } +} + +// The typeless format of a format's family (itself if none). +inline u32 family(u32 f) +{ + constexpr u32 families[22][2] = {{1, 4}, {5, 8}, {9, 14}, {15, 18}, {19, 22}, {23, 25}, {27, 32}, {33, 38}, + {39, 43}, {44, 47}, {48, 52}, {53, 59}, {60, 64}, {70, 72}, {73, 75}, {76, 78}, + {79, 81}, {82, 84}, {90, 91}, {92, 93}, {94, 96}, {97, 99}}; + if (f == 87) return 90; + if (f == 88) return 92; + for (const auto& r : families) + if (f >= r[0] && f <= r[1]) return r[0]; + return f; +} + +constexpr u32 format_unknown = 0; +constexpr u32 format_r32_typeless = 39; + +// Element layout of a buffer view. +struct Elements { + u32 stride = 0; + bool raw = false; + u32 format = 0; +}; + +// Bytes per element as the console's descriptor holds them for indexed reads (structured: the stride; raw: 1, the +// index is the byte; typed: the format's). +inline u32 view_stride(const Elements& e) +{ + if (e.stride > 0) return e.stride; + if (e.raw) return 1; + return static_cast<u32>(element_bytes(e.format)); +} + +// VIEW_INTEGER (and VIEW_SIGNED) for a typed buffer view of an integer format. +inline u32 view_kind(const Elements& e) +{ + if (e.stride != 0 || e.raw) return 0; + switch (e.format) { + case 3: case 7: case 12: case 17: case 25: case 30: case 36: case 42: case 50: case 57: case 62: + return view_integer; + case 4: case 8: case 14: case 18: case 32: case 38: case 43: case 52: case 59: case 64: + return view_integer | view_signed; + default: + return 0; + } +} + +// The word the table of strides holds for a slot: 0 if it is no buffer view. +inline u32 stride_word(const std::optional<Elements>& e) +{ + if (!e) return 0; + return view_stride(*e) | view_kind(*e); +} + +// A buffer view that begins `offset` bytes into its host copy where no host view can begin. +inline bool off_elements(u64 offset, u32 stride, bool raw, u64 element) +{ + if (raw) return offset % 16 != 0; + if (stride > 0) return offset % 16 != 0 && offset % stride != 0; + return element > 0 && offset % element != 0; +} + +// A structured view (`first`, `count` elements of `stride` bytes, `offset` bytes into its host copy) as a raw view +// of the same bytes: first dword and dwords. Only when the bytes start on 16 and are whole dwords. +struct RawWindow { u64 first; u32 dwords; }; +inline std::optional<RawWindow> raw_window(u64 offset, u64 first, u32 count, u32 stride) +{ + if (stride == 0) return std::nullopt; + if (first > (~u64{0} - offset) / stride) return std::nullopt; + const u64 start = first * stride + offset; + const u64 bytes = u64{count} * stride; + if (start % 16 != 0 || bytes % 4 != 0) return std::nullopt; + if (bytes / 4 > 0xffffffffull) return std::nullopt; + return RawWindow{start / 4, static_cast<u32>(bytes / 4)}; +} + +// Whether the host accepts a buffer view with these fields of a buffer of `width` bytes (it removes the device for +// one it does not). +inline bool buffer_view_ok(u32 format, u64 first, u32 count, u32 stride, bool raw, u64 width) +{ + u64 el = 0; + if (raw) { + if (format != format_r32_typeless || stride != 0 || first % 4 != 0) return false; + el = 4; + } else if (stride > 0) { + if (format != format_unknown || stride > 2048 || stride % 4 != 0) return false; + el = stride; + } else { + const bool typeless = family(format) == format && family(format + 1) == format; + const auto e = element(format); + if (!e || e->block != 1 || format == 0 || typeless || e->bytes == 0) return false; + el = e->bytes; + } + if (count == 0) return false; + const u64 end = first + count; + if (end < first) return false; + if (el && end > ~u64{0} / el) return false; + return end * el <= width; +} + +// The bytes a buffer view the host takes shows as a raw view: first dword, dwords, and the bytes past that dword it +// begins (a raw view begins on 16 bytes). +struct TwinWindow { u64 first; u32 dwords; u32 by; }; +inline std::optional<TwinWindow> twin_window(u32 format, u64 first, u32 count, u32 stride, bool raw, u64 width) +{ + u64 el = raw ? 4 : stride > 0 ? stride : element_bytes(format); + const u64 start = first * el; + u64 end = (first + count) * el; + end = (end + 3) & ~u64{3}; + end = (std::min)(end, width & ~u64{3}); + const u64 from = start & ~u64{15}; + if (end <= start) return std::nullopt; + const u64 dwords = (end - from) / 4; + if (dwords > 0xffffffffull) return std::nullopt; + return TwinWindow{from / 4, static_cast<u32>(dwords), static_cast<u32>(start - from)}; +} + +// Whole 256s, at most the 64 KiB a shader can index. +inline u32 constant_bytes(u32 size) +{ + constexpr u32 largest = 64u << 10; + const u32 s = (std::min)(size, largest); + return (s + 255) & ~255u; +} + +// The records (`step` bytes each, the first is slot `first`) that differ between `last` and `records` (of one +// length) go into `out` and `last`. Sixteen at a time. +inline void changed_records(unsigned char* last, const unsigned char* records, std::size_t len, std::size_t step, + u32 first, std::vector<u32>& out) +{ + constexpr std::size_t at_a_time = 16; + const std::size_t block = at_a_time * step; + for (std::size_t b = 0, at = 0; at < len; ++b, at += block) { + const std::size_t n = (std::min)(block, len - at); + if (std::memcmp(last + at, records + at, n) == 0) continue; + for (std::size_t r = 0; r + step <= n; r += step) { + if (std::memcmp(last + at + r, records + at + r, step) != 0) { + std::memcpy(last + at + r, records + at + r, step); + out.push_back(first + static_cast<u32>(b * at_a_time + r / step)); + } + } + } +} + +// The console's sampler description (CreateSamplerX, 27 words: flags, magnification, minification, mip and depth +// filters, filter mode, three address modes, minimum and maximum LOD, LOD bias, secondary bias, anisotropy, its +// bias and threshold, comparison, border colour, then tuning words) as the host's. +inline float lod_finite(float value, float fallback) +{ + if (value != value) return fallback; + return (std::min)((std::max)(value, -D3D12_FLOAT32_MAX), D3D12_FLOAT32_MAX); +} +inline D3D12_SAMPLER_DESC console_sampler(const u32 w[27]) +{ + const auto f = [&](int i) { + float v; + std::memcpy(&v, &w[i], 4); + return v; + }; + const u32 mag = w[1], min = w[2], mip = w[3], mode = w[5], anisotropy = w[13], compare = w[16]; + const auto linear = [](u32 x) { return u32{x == 1 || x == 3}; }; + const bool aniso = mag >= 2 || min >= 2; + // A sampler given a real test (less ... greater-or-equal) is a comparison sampler; never, always and none not. + const bool compares = compare >= 2 && compare <= 7; + const u32 reduction = mode == 1 ? 2 : mode == 2 ? 3 : u32{compares}; + const u32 filter = aniso ? 0x55 : (linear(min) << 4 | linear(mag) << 2 | u32{mip == 2}); + const float min_lod = lod_finite(f(9), 0.0f); + // Without a mip filter the console clamps sampling to min_lod. + const float max_lod = mip == 0 ? min_lod : (std::max)(lod_finite(f(10), min_lod), min_lod); + const auto address = [](u32 m) { + return m >= 1 && m <= 5 ? static_cast<D3D12_TEXTURE_ADDRESS_MODE>(m) : D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + }; + D3D12_SAMPLER_DESC d{}; + d.Filter = static_cast<D3D12_FILTER>(reduction << 7 | filter); + d.AddressU = address(w[6]); + d.AddressV = address(w[7]); + d.AddressW = address(w[8]); + const float bias = f(11); + d.MipLODBias = bias != bias ? 0.0f : (std::min)((std::max)(bias, D3D12_MIP_LOD_BIAS_MIN), D3D12_MIP_LOD_BIAS_MAX); + d.MaxAnisotropy = aniso ? (std::min)((std::max)(anisotropy, 1u), 16u) : 1; + d.ComparisonFunc = reduction == 1 ? static_cast<D3D12_COMPARISON_FUNC>(compare) : D3D12_COMPARISON_FUNC_NEVER; + for (int i = 0; i < 4; ++i) d.BorderColor[i] = f(17 + i); + d.MinLOD = min_lod; + d.MaxLOD = max_lod; + return d; +} + +// The record WP5 writes into a title slot for a placed buffer view (device slots 70 and 71) that X2W's handler left +// without a record it can follow: {"X2WP", address lo, hi, first element, elements, stride, format | raw << 16 | +// unordered << 17, the buffer's width}. Copies of it travel with the title's memory copies like X2WV tokens. +constexpr u32 placed_magic = 0x50573258; // "X2WP" +struct PlacedRecord { + u64 address = 0; + u32 first = 0, elements = 0, stride = 0, format = 0; + bool raw = false, unordered = false; + u32 width = 0; +}; +inline void placed_words(const PlacedRecord& p, u32 out[8]) +{ + out[0] = placed_magic; + out[1] = static_cast<u32>(p.address); + out[2] = static_cast<u32>(p.address >> 32); + out[3] = p.first; + out[4] = p.elements; + out[5] = p.stride; + out[6] = (p.format & 0xffff) | (p.raw ? 1u << 16 : 0) | (p.unordered ? 1u << 17 : 0); + out[7] = p.width; +} +inline bool placed_of(const u32 w[8], PlacedRecord& p) +{ + if (w[0] != placed_magic) return false; + p.address = w[1] | (u64{w[2]} << 32); + p.first = w[3]; + p.elements = w[4]; + p.stride = w[5]; + p.format = w[6] & 0xffff; + p.raw = (w[6] >> 16) & 1; + p.unordered = (w[6] >> 17) & 1; + p.width = w[7]; + return p.address != 0 && p.elements != 0; +} + +// Reserve dynamic slots until release. The caller holds the heap lock. +class DynamicRuns { +public: + DynamicRuns() = default; + DynamicRuns(u32 count, u32 dynamic) { reset(count, dynamic); } + void reset(u32 count, u32 dynamic) + { + count_ = count; + dynamic_ = dynamic; + taken_.assign(dynamic, 0); + next_ = 0; + free_ = dynamic; + too_long_ = ~0u; + } + // `n` consecutive free dynamic slots: the first's heap index. + std::optional<u32> take(u32 n) + { + if (n == 0 || n > dynamic_) return std::nullopt; + const bool enough = free_ >= n && n < too_long_; + if (!enough) return std::nullopt; + const std::size_t cursor = next_, end = dynamic_; + const std::size_t second_end = (std::min)(cursor + (n - 1), end); + std::size_t run = 0, last = ~std::size_t{0}; + std::optional<std::size_t> found; + auto look = [&](std::size_t at) { + if (at != last + 1) run = 0; + last = at; + run = taken_[at] ? 0 : run + 1; + if (run == n) found = at + 1 - n; + return found.has_value(); + }; + for (std::size_t at = cursor; at < end && !found; ++at) look(at); + for (std::size_t at = 0; at < second_end && !found; ++at) look(at); + if (!found) { + too_long_ = (std::min)(too_long_, n); + return std::nullopt; + } + std::fill(taken_.begin() + *found, taken_.begin() + *found + n, std::uint8_t{1}); + free_ -= n; + next_ = static_cast<u32>((*found + n) % end); + return count_ + static_cast<u32>(*found); + } + // Gives back `n` dynamic slots from heap index `first`. + void release(u32 first, u32 n) + { + if (first < count_) return; + const u32 at = first - count_; + const u64 end = (std::min<u64>)(u64{at} + n, dynamic_); + if (at >= end) return; + u32 given = 0; + for (u64 i = at; i < end; ++i) { + given += taken_[i] ? 1 : 0; + taken_[i] = 0; + } + free_ += given; + too_long_ = ~0u; + } + u32 free() const { return free_; } + u32 size() const { return dynamic_; } + +private: + u32 count_ = 0, dynamic_ = 0, next_ = 0, free_ = 0, too_long_ = ~0u; + std::vector<std::uint8_t> taken_; +}; + +// One slot's bit in a set of slots: put, remove, take the changed ones. +class SlotSet { +public: + void resize(std::size_t n) { words_.assign((n + 63) / 64, 0); } + bool put(u32 i) { return flip(i, true); } + bool remove(u32 i) { return flip(i, false); } + bool has(u32 i) const { return i / 64 < words_.size() && (words_[i / 64] >> (i % 64) & 1); } + template <class F> void each(F&& f) const + { + for (std::size_t w = 0; w < words_.size(); ++w) + for (u64 bits = words_[w]; bits; bits &= bits - 1) { + unsigned long b = 0; + for (u64 t = bits; !(t & 1); t >>= 1) ++b; + f(static_cast<u32>(w * 64 + b)); + } + } + std::vector<u32> take() + { + std::vector<u32> out; + each([&](u32 i) { out.push_back(i); }); + std::fill(words_.begin(), words_.end(), 0); + return out; + } + +private: + // Whether the bit was set before. + bool flip(u32 i, bool on) + { + if (i / 64 >= words_.size()) return false; + u64& w = words_[i / 64]; + const u64 bit = u64{1} << (i % 64); + const bool was = (w & bit) != 0; + w = on ? (w | bit) : (w & ~bit); + return was; + } + std::vector<u64> words_; +}; + +} // namespace gpu_heap diff --git a/src/startup_stubs/gpu_heap.inl b/src/startup_stubs/gpu_heap.inl new file mode 100644 index 0000000000..69a191e40b --- /dev/null +++ b/src/startup_stubs/gpu_heap.inl @@ -0,0 +1,2132 @@ +#include "startup_stubs/gpu_material_trace.h" +// Host mirror heaps for title descriptors. The shim supplies resources through Env, which lets WARP fixtures +// exercise the same device code. Include gpu_heap.h at global scope before including this file in the shim's +// anonymous namespace. +// +// Title slot i maps to host slot i. Dynamic slots follow title slots, the null slot is at 2^21 - 1, and raw twins +// start at 2^21. The stride table tracks buffer element sizes. Submission mirrors byte-copied records and queues +// indexed textures for upload. +// +// An X2WV token names a captured CBV (17), SRV (18), UAV (19) or sampler (22). Raw GFX10 V# words describe a placed +// buffer range, and S# words describe samplers. Buffer bounds come from the title allocation. An unrepresentable +// read-only view gets a copy refreshed at submission. The equivalent UAV is null because writes to a copy would be +// lost. +#pragma once + +#include "gpu_heap.h" +#include "gpu_view_trace.h" +#include "gpu_srgb.h" +#include "gfx10_view_words.h" +#include "translated_sampler_bindings.h" + +// (Its own namespace: in the shim this file is inside the anonymous namespace, where gpu_heap, from the header at +// the top of the file, cannot be reopened.) +namespace gpu_mirror { +using namespace ::gpu_heap; + +// What the mirror needs of X2W. The shim fills it from view_records, unwrap, gpu_find/desktop_range and +// upload_texture; fixtures fill it with their own. +struct Record { + u32 id = 0, slot = 0; // slot: 17 CBV, 18 SRV, 19 UAV, 22 sampler + u64 resource = 0, counter = 0; // title wrappers (0: none) + bool materialized = true; + u32 desc_bytes = 0; + unsigned char desc[64]{}; // as the desktop takes it (formats mapped, as view_slot passes it) +}; +struct ResourceFacts { + ID3D12Resource* desktop = nullptr; // the desktop resource (no reference held) + bool buffer = false; + bool depth_and_uav = false; + u64 title_memory = 0; // a buffer: the title address of its first byte + u64 bytes = 0; // a buffer: its width +}; +// Shared by all heaps warmed on the same device. A try-lock leaves a concurrently recording +// list free to continue without spending the same frame budget twice. +struct LazyBudget { + std::mutex mutex; + u64 frame = ~u64{0}, bytes = 0, room = 0; + u32 visits = 0; + double elapsed_ms = 0; +}; +struct Env { + ID3D12Device* device = nullptr; + u64 (*mapping_epoch)() = nullptr; + u64 (*copied_bytes)() = nullptr; + u64 (*local_room)(ID3D12Device*) = nullptr; + u64 (*allocation_size)(ID3D12Device*, const u32*) = nullptr; + u64 (*allocated_bytes)() = nullptr; + void* ctx = nullptr; + // [address, address + bytes) of title memory on the desktop: the resource and the offset of `address` in it, and + // the bytes from `address` to the end of the title buffer or contiguous run there. + // A fixed, coherent window can be bound directly for the lifetime of the descriptor. + // A CPU shadow or a remappable chunk needs its submit-time refresh. + bool (*coherent_window)(u64 address, u64 bytes, ID3D12Resource*, u64 offset) = nullptr; + bool (*find)(void* ctx, u64 address, u64 bytes, ID3D12Resource** resource, u64* offset, u64* left) = nullptr; + // The view record a token's id names; false if none (or its resource is gone). + bool (*record)(void* ctx, u32 id, Record* out) = nullptr; + // A title resource wrapper. + bool (*resource)(void* ctx, u64 wrapper, ResourceFacts* out) = nullptr; + std::shared_ptr<x2w_depth_twins::Twins> (*depth_uav)(u64 wrapper) = nullptr; + // Uploads the texture of title resource `wrapper` (desktop `texture`) on list `list` and leaves it readable by + // shaders (SRV | non-pixel SRV); false if it could not. + bool (*upload)(void* ctx, void* list, u64 wrapper, ID3D12Resource* texture) = nullptr; + // Reads title memory into `out`, false if any of it cannot be read (a page the title unmapped). + bool (*read)(void* ctx, u64 address, void* out, std::size_t bytes) = nullptr; + bool (*placement)(u64 wrapper, const D3D12_SHADER_RESOURCE_VIEW_DESC& view, u32 (&words)[8]) = nullptr; + u64 (*late_texture)(const u32* words, D3D12_SHADER_RESOURCE_VIEW_DESC& view, bool& pending, bool allow_create) = nullptr; +}; + +// Reads title memory through env.read, or through the kernel (a page the title unmapped fails the read where a read +// in place would fault). +inline bool read_memory(const Env& env, u64 address, void* out, std::size_t bytes) +{ + if (env.read) return env.read(env.ctx, address, out, bytes); + SIZE_T got = 0; + return ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<const void*>(address), out, bytes, &got) && got == bytes; +} + +constexpr u32 token_magic = 0x56573258; // "X2WV" (d3d12_capture.inl view_token_magic) + +// Counters (since the start), for the "x2w-gpu heap" lines and the tests. +enum Count : int { + c_made, c_retried, c_lazy_warmed, c_lazy_staged, c_retained_pending, c_null, c_twins, c_twins_moved, c_twins_unmoved, c_twins_null, c_refused, c_cbv_unaligned, + c_cross_uav, c_exact, c_exact_failed, c_exact_invalid, c_exact_capacity, c_exact_create, c_exact_map, + c_exact_unreadable, c_direct_offset, c_vsharp, c_ssharp, c_textures_due, c_uploads, c_mirrored, c_changed, + c_unfit, c_fit_cut, c_fit_refused, c_count +}; +inline std::atomic<u64>* counts() +{ + static std::atomic<u64> c[c_count]; + return c; +} +inline void tally(Count c, u64 n = 1) { counts()[c].fetch_add(n, std::memory_order_relaxed); } +inline u64 counted(Count c) { return counts()[c].load(std::memory_order_relaxed); } + +// Decoded title descriptor. +enum class Kind : std::uint8_t { none, constant, shader, unordered, sampler, placed }; +struct View { + Kind kind = Kind::none; + u64 key = 0; // what the slot was made from (0: nothing): token id + 1 with its resource, or + // a hash of the V#/S# words + u64 wrapper = 0; // the title resource (textures: what is uploaded) + ID3D12Resource* resource = nullptr; // the desktop resource of a shader/unordered view (no reference held) + ID3D12Resource* counter = nullptr; + std::shared_ptr<x2w_depth_twins::Twins> depth_twins; + bool buffer = false; // a view of buffer memory + bool unordered = false; // placed: an unordered view + u64 address = 0; // constant: its location; buffer: the title address of the buffer's start + u64 bytes = 0; // constant: its size; buffer: the buffer's width (the view's extent) + std::array<u32, 8> placement{}; + bool pending = false; + Microsoft::WRL::ComPtr<ID3D12Resource> retained; + bool explicit_null = false; + bool has_desc = false; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + D3D12_SAMPLER_DESC sampler{}; + + bool is_texture() const { return (kind == Kind::shader || kind == Kind::unordered) && !buffer && resource; } + // Whether this view addresses a buffer. + bool is_buffer() const { return kind == Kind::constant || kind == Kind::placed || buffer; } +}; + +// A buffer view's structure stride, whether it is raw, and its format. +inline std::optional<Elements> view_elements(const View& v) +{ + if (!v.buffer || !v.has_desc) return std::nullopt; + const bool uav = v.kind == Kind::unordered || (v.kind == Kind::placed && v.unordered); + if (uav) { + if (v.uav.ViewDimension != D3D12_UAV_DIMENSION_BUFFER) return std::nullopt; + return Elements{v.uav.Buffer.StructureByteStride, (v.uav.Buffer.Flags & D3D12_BUFFER_UAV_FLAG_RAW) != 0, + static_cast<u32>(v.uav.Format)}; + } + if (v.srv.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) return std::nullopt; + return Elements{v.srv.Buffer.StructureByteStride, (v.srv.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) != 0, + static_cast<u32>(v.srv.Format)}; +} + +// Whether the view has a raw twin when its slot is made. +inline bool twinned(const View& v) { return v.kind == Kind::constant || view_elements(v).has_value(); } + +// ---- Reading records ------------------------------------------------------------------------------------------- + +inline u64 mix_words(const std::uint32_t* w, std::size_t n, u64 seed) +{ + u64 h = seed; + for (std::size_t i = 0; i < n; ++i) h = (h ^ w[i]) * 0x100000001b3ull; + return h | 1; // never 0 +} + +// The DXGI format of a GFX10 buffer format code with `bytes` per element (the reverse of gfx10_format), 0 if none. +inline u32 dxgi_of_gfx10(u32 code, u32 bytes) +{ + static const u32* table = [] { + static u32 t[128]{}; + static u32 b[128]{}; + for (u32 f = 1; f < 130; ++f) { + const auto g = x2w_startup::gfx10_format(static_cast<DXGI_FORMAT>(f)); + if (g.code && g.code < 128 && g.bytes && !t[g.code]) { + t[g.code] = f; + b[g.code] = g.bytes; + } + } + return t; + }(); + if (code >= 128 || !table[code]) return 0; + return element_bytes(table[code]) == bytes ? table[code] : 0; +} + +// A V# (GFX10 buffer resource words) as a placed buffer SRV: raw when it has no stride, structured otherwise (a +// typed one with a format the host has: typed). +inline bool view_of_vsharp(const std::uint32_t w[4], View& v) +{ + const u64 base = w[0] | (u64{w[1] & 0xffff} << 32); + const u32 stride = (w[1] >> 16) & 0x3fff; + const u32 records = w[2]; + const u32 format = (w[3] >> 12) & 127; + const u32 oob = (w[3] >> 28) & 3; + const u32 type = w[3] >> 30; + if (!base || !records || type != 0 || (w[3] & 0xfff) == 0) return false; + if (stride == 0 && oob != 3) return false; + v = View{}; + v.kind = Kind::placed; + v.buffer = true; + v.has_desc = true; + v.address = base; + v.srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (stride == 0) { + v.srv.Format = DXGI_FORMAT_R32_TYPELESS; + v.srv.Buffer.NumElements = records / 4; + v.srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + v.bytes = records & ~3u; + if (!v.srv.Buffer.NumElements) return false; + } else { + const u32 typed = dxgi_of_gfx10(format, stride); + // (A typed V# of a format of `stride` bytes reads as that format; any other strided one is structured.) + if (typed && format != 22 /* 32_FLOAT, the raw/structured descriptors' */) { + v.srv.Format = static_cast<DXGI_FORMAT>(typed); + } else { + if (stride % 4 != 0) return false; + v.srv.Format = DXGI_FORMAT_UNKNOWN; + v.srv.Buffer.StructureByteStride = stride; + } + v.srv.Buffer.NumElements = records; + v.bytes = u64{records} * stride; + } + v.key = mix_words(w, 4, 0x56ull); + tally(c_vsharp); + return true; +} + +inline bool title_as_address(const Env& env, const std::uint32_t words[8], u64* address) +{ + if (words[0] != token_magic || words[2] != 18) return false; + Record record{}; + if (!env.record || !env.record(env.ctx, words[1], &record) || record.slot != 18 || + record.desc_bytes < sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)) return false; + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + std::memcpy(&desc, record.desc, sizeof(desc)); + if (desc.ViewDimension != D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE) return false; + *address = x2w_as_address::address(words, desc.RaytracingAccelerationStructure.Location); + return true; +} + +// The view a slot's record names, from `words`, the record's first 8 dwords. `sampler_heap`: a sampler heap's +// record (S# words where it is no token). +inline bool view_of_record(const Env& env, const std::uint32_t words[8], bool sampler_heap, View& v, bool allow_create = true) +{ + v = View{}; + if (!sampler_heap && x2w_late_texture::marker(words[0]) && env.late_texture) { + D3D12_RESOURCE_DESC desc{}; + if (!x2w_late_texture::decode(words, desc, v.srv)) return false; + v.kind = Kind::shader; + v.has_desc = true; + v.key = mix_words(words, 8, 0x54ull); + std::copy_n(words, 8, v.placement.begin()); + v.placement[0] = x2w_late_texture::magic; + v.wrapper = env.late_texture(words, v.srv, v.pending, allow_create); + ResourceFacts f{}; + if (v.wrapper && env.resource && env.resource(env.ctx, v.wrapper, &f)) { + v.resource = f.desktop; + u32 fields[sizeof(v.srv) / sizeof(u32)]; + std::memcpy(fields, &v.srv, sizeof(fields)); + v.key = mix_words(fields, std::size(fields), v.key); + } + return true; + } + if (words[0] == token_magic) { + Record r; + if (!env.record || !env.record(env.ctx, words[1], &r)) return false; + v.key = (u64{r.id} + 1) ^ (r.resource * 0x9e3779b97f4a7c15ull); + if (!v.key) v.key = 1; + v.wrapper = r.resource; + switch (r.slot) { + case 17: { + if (r.desc_bytes < sizeof(D3D12_CONSTANT_BUFFER_VIEW_DESC)) return false; + D3D12_CONSTANT_BUFFER_VIEW_DESC c; + std::memcpy(&c, r.desc, sizeof(c)); + v.kind = Kind::constant; + v.address = c.BufferLocation; + v.bytes = c.SizeInBytes; + return v.address != 0; + } + case 18: + case 19: { + const bool uav = r.slot == 19; + if (uav && r.desc_bytes >= sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC)) { + std::memcpy(&v.uav, r.desc, sizeof(v.uav)); + v.has_desc = true; + } else if (!uav && r.desc_bytes >= sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)) { + std::memcpy(&v.srv, r.desc, sizeof(v.srv)); + v.has_desc = true; + } + + v.kind = uav ? Kind::unordered : Kind::shader; + if (!r.resource) { + if (!r.materialized || !v.has_desc || r.counter) return false; + if (!uav && v.srv.ViewDimension == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE) return false; + v.buffer = uav ? v.uav.ViewDimension == D3D12_UAV_DIMENSION_BUFFER : v.srv.ViewDimension == D3D12_SRV_DIMENSION_BUFFER; + v.explicit_null = true; + return true; + } + ResourceFacts f; + if (!env.resource || !env.resource(env.ctx, r.resource, &f) || !f.desktop) { + return false; + } + v.resource = f.desktop; + v.buffer = f.buffer; + v.address = f.title_memory; + v.bytes = f.bytes; + if (uav && r.counter && env.resource) { + ResourceFacts c; + if (env.resource(env.ctx, r.counter, &c)) v.counter = c.desktop; + } + if (uav && f.depth_and_uav && env.depth_uav) { + auto twins = env.depth_uav(r.resource); + D3D12_UNORDERED_ACCESS_VIEW_DESC adapted{}; + auto* backing = twins ? twins->view(v.has_desc ? &v.uav : nullptr, adapted) : nullptr; + // A packed depth plane needs a graphics pass to return its values. Expose only + // twins whose writes can already be carried back on this path. + if (backing && backing == twins->colour.Get()) { + v.resource = backing; + v.uav = adapted; + v.has_desc = true; + v.depth_twins = std::move(twins); + } + } + if (!uav && !v.buffer && v.has_desc && env.placement) { + u32 words[8]{}; + if (env.placement(r.resource, v.srv, words)) std::copy_n(words, 8, v.placement.begin()); + } + // A buffer view of a buffer object needs its description. + return !v.buffer || v.has_desc; + } + case 22: + if (r.desc_bytes < sizeof(D3D12_SAMPLER_DESC)) return false; + std::memcpy(&v.sampler, r.desc, sizeof(v.sampler)); + v.kind = Kind::sampler; + return true; + default: + return false; + } + } + if (PlacedRecord p; placed_of(words, p)) { + v.kind = Kind::placed; + v.buffer = true; + v.unordered = p.unordered; + v.has_desc = true; + v.address = p.address; + v.bytes = p.width; + if (p.unordered) { + v.uav.Format = static_cast<DXGI_FORMAT>(p.format); + v.uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + v.uav.Buffer.FirstElement = p.first; + v.uav.Buffer.NumElements = p.elements; + v.uav.Buffer.StructureByteStride = p.stride; + v.uav.Buffer.Flags = p.raw ? D3D12_BUFFER_UAV_FLAG_RAW : D3D12_BUFFER_UAV_FLAG_NONE; + } else { + v.srv.Format = static_cast<DXGI_FORMAT>(p.format); + v.srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.srv.Buffer.FirstElement = p.first; + v.srv.Buffer.NumElements = p.elements; + v.srv.Buffer.StructureByteStride = p.stride; + v.srv.Buffer.Flags = p.raw ? D3D12_BUFFER_SRV_FLAG_RAW : D3D12_BUFFER_SRV_FLAG_NONE; + } + v.key = mix_words(words, 8, 0x50ull); + return true; + } + if (sampler_heap) { + // The title's own S# words (translated_sampler_bindings.h decode_sampler). + const bool any = words[0] | words[1] | words[2] | words[3]; + if (!any) return false; + x2w_startup::SamplerWords s{words[0], words[1], words[2], words[3]}; + const D3D12_STATIC_SAMPLER_DESC d = x2w_startup::decode_sampler(s, 0, false, true); + v.kind = Kind::sampler; + v.sampler.Filter = d.Filter; + v.sampler.AddressU = d.AddressU; + v.sampler.AddressV = d.AddressV; + v.sampler.AddressW = d.AddressW; + v.sampler.MipLODBias = d.MipLODBias; + v.sampler.MaxAnisotropy = d.MaxAnisotropy; + v.sampler.ComparisonFunc = d.ComparisonFunc; + const float border = d.BorderColor == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK ? 0.0f : d.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE ? 1.0f : 0.0f; + v.sampler.BorderColor[0] = v.sampler.BorderColor[1] = v.sampler.BorderColor[2] = border; + v.sampler.BorderColor[3] = d.BorderColor == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK ? 0.0f : 1.0f; + v.sampler.MinLOD = d.MinLOD; + v.sampler.MaxLOD = d.MaxLOD; + v.key = mix_words(words, 4, 0x55ull); + tally(c_ssharp); + return true; + } + return view_of_vsharp(words, v); +} + +// ---- Null views --------- + +inline void null_view(ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HANDLE at) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + d.Texture2D.MipLevels = 1; + gpu_view_trace::MirrorCall{device, __FUNCTION__}.srv(nullptr, &d, at); +} +inline void null_buffer_view(ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HANDLE at) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + d.Buffer.NumElements = 1; + d.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + gpu_view_trace::MirrorCall{device, __FUNCTION__}.srv(nullptr, &d, at); +} +// A texture view that reads zeros with the title's dimension (one mip, one slice, plane 0). +inline void null_like(ID3D12Device* device, const D3D12_SHADER_RESOURCE_VIEW_DESC& title, D3D12_CPU_DESCRIPTOR_HANDLE at) +{ + const u32 dim = static_cast<u32>(title.ViewDimension); + if (dim < 2 || dim > 10) return null_view(device, at); + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.ViewDimension = title.ViewDimension; + d.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + // Words 5 (and 7) of the union are MipLevels (and ArraySize / NumCubes). + std::uint32_t w[10]{}; + w[1] = dim; + switch (dim) { + case 6: break; // 2DMS + case 7: w[5] = 1; break; // 2DMS array: ArraySize at word 5 + case 3: case 5: case 10: w[5] = 1; w[7] = 1; break; // 1D array, 2D array, cube array + default: w[5] = 1; break; + } + std::memcpy(reinterpret_cast<unsigned char*>(&d) + 16, &w[4], 24); + gpu_view_trace::MirrorCall{device, __FUNCTION__}.srv(nullptr, &d, at); +} +inline D3D12_UNORDERED_ACCESS_VIEW_DESC null_uav_desc(std::optional<u32> dimension) +{ + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_UINT; + d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + if (!dimension) return d; + switch (*dimension) { + case D3D12_UAV_DIMENSION_TEXTURE1D: d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; break; + case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: + d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; + d.Texture1DArray.ArraySize = 1; + break; + case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: + d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + d.Texture2DArray.ArraySize = 1; + break; + case D3D12_UAV_DIMENSION_TEXTURE3D: + d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + d.Texture3D.WSize = ~0u; + break; + default: break; + } + return d; +} +// What a slot of `view` reads when the host cannot make it. +inline void null_for(ID3D12Device* device, const View& v, D3D12_CPU_DESCRIPTOR_HANDLE at) +{ + bool buffer = false; + std::optional<u32> dimension; + switch (v.kind) { + case Kind::unordered: + buffer = v.buffer || (v.has_desc && v.uav.ViewDimension == D3D12_UAV_DIMENSION_BUFFER); + if (v.has_desc) dimension = static_cast<u32>(v.uav.ViewDimension); + break; + case Kind::placed: + if (!v.unordered) return null_buffer_view(device, at); + buffer = true; + break; + case Kind::shader: + if (v.buffer || (v.has_desc && v.srv.ViewDimension == D3D12_SRV_DIMENSION_BUFFER)) return null_buffer_view(device, at); + if (v.has_desc) return null_like(device, v.srv, at); + return null_view(device, at); + case Kind::constant: { + D3D12_CONSTANT_BUFFER_VIEW_DESC c{}; + return gpu_view_trace::MirrorCall{device, __FUNCTION__}.cbv(&c, at); + } + default: + return null_view(device, at); + } + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + if (buffer) { + d.Format = DXGI_FORMAT_R32_UINT; + d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + } else { + d = null_uav_desc(dimension); + } + gpu_view_trace::MirrorCall{device, __FUNCTION__}.uav(nullptr, nullptr, &d, at); +} +inline void null_sampler(ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HANDLE at) +{ + D3D12_SAMPLER_DESC d{}; + d.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + d.AddressU = d.AddressV = d.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + d.MaxAnisotropy = 1; + d.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; + gpu_view_trace::MirrorCall{device, __FUNCTION__}.sampler(&d, at); +} + +// ---- Copies of a view's own bytes ------------------------------------------- + +// A buffer of `bytes` of title memory from `start`, in upload memory the GPU reads, refreshed from title memory at +// every submit (Exacts::refresh). Kept while a slot shows it, then for a few submits. +struct Exact { + u64 start = 0, bytes = 0; + Microsoft::WRL::ComPtr<ID3D12Resource> buffer; + void* data = nullptr; + u64 used = 0; // the submit it was last made for +}; +class Exacts { +public: + // The copy of [start, start + bytes), made if new and filled now. Null if it cannot be. + Microsoft::WRL::ComPtr<ID3D12Resource> get(const Env& env, u64 start, u64 bytes, u64 submit) + { + constexpr u64 most = 64ull << 20; // bytes of copies in all + std::lock_guard<std::mutex> lock(mutex_); + const auto key = std::make_pair(start, bytes); + auto found = by_key_.find(key); + if (found != by_key_.end()) { + found->second.used = submit; + return found->second.buffer; + } + if (!start || !bytes || bytes > most || start > UINT64_MAX - bytes) { + tally(c_exact_invalid); + return nullptr; + } + const u64 width = (bytes + 255) & ~u64{255}; + if (width > most - total_) { + tally(c_exact_capacity); + return nullptr; + } + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_UPLOAD}; + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = width; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + Microsoft::WRL::ComPtr<ID3D12Resource> buffer; + if (FAILED(env.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&buffer)))) { + tally(c_exact_create); + return nullptr; + } + void* data = nullptr; + const D3D12_RANGE none{0, 0}; + if (FAILED(buffer->Map(0, &none, &data))) { + tally(c_exact_map); + return nullptr; + } + if (!read_memory(env, start, data, bytes)) { + tally(c_exact_unreadable); + return nullptr; + } + total_ += width; + Exact& e = by_key_[key]; + e = Exact{start, bytes, buffer, data, submit}; + return buffer; + } + // Every copy gets title memory's bytes again; those no slot has shown for `keep` submits go. A slot that shows a + // copy (and the retired list, for a few submits after) holds a reference to its buffer: a copy whose only + // reference is ours is shown by no slot. + void refresh(const Env& env, u64 submit, u64 keep) + { + std::lock_guard<std::mutex> lock(mutex_); + for (auto it = by_key_.begin(); it != by_key_.end();) { + Exact& e = it->second; + e.buffer->AddRef(); + if (e.buffer->Release() > 1) e.used = submit; + if (submit > e.used + keep) { + total_ -= (e.bytes + 255) & ~u64{255}; + it = by_key_.erase(it); + continue; + } + read_memory(env, e.start, e.data, e.bytes); + ++it; + } + } + std::size_t size() + { + std::lock_guard<std::mutex> lock(mutex_); + return by_key_.size(); + } + +private: + std::mutex mutex_; + std::map<std::pair<u64, u64>, Exact> by_key_; + u64 total_ = 0; +}; + +// ---- Making views ----------------------------------------------------- + +// What a made view shows of the host's: the resource the slot holds (null: none, the view needs nothing kept). +struct Made { + bool ok = false; + ID3D12Resource* kept = nullptr; // no reference: the caller takes one + u64 raw_start{}, raw_bytes{}; + Microsoft::WRL::ComPtr<ID3D12Resource> pin; // keeps an exact copy alive until the slot owns it +}; + +// Where a buffer view (title memory from `base`, `width` bytes of buffer) is on the desktop: the resource, the +// offset of `base` in it, and the width of what may be viewed there from the resource's start. +struct Home { + ID3D12Resource* resource = nullptr; + u64 offset = 0; // of `base` + u64 width = 0; // bytes from the resource start that are this buffer's +}; + +// Moves the raw view at `at` (a CPU-only slot) `by` bytes on, where AMD's descriptor is its address (48 bits) and +// bytes; false if the descriptor is not that. +inline bool move_raw(D3D12_CPU_DESCRIPTOR_HANDLE at, u64 start, u32 bytes, u32 by) +{ + if (by >= bytes) return false; + std::uint32_t words[4]; + SIZE_T got = 0; + if (!ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<const void*>(at.ptr), words, sizeof(words), &got) || + got != sizeof(words)) + return false; + const u64 address = words[0] | (u64{words[1]} << 32); + if (address != start || words[2] != bytes || (start >> 48) != 0) return false; + const u64 moved = start + by; + auto* w = reinterpret_cast<std::uint32_t*>(at.ptr); + w[0] = static_cast<std::uint32_t>(moved); + w[1] = static_cast<std::uint32_t>(moved >> 32); + w[2] = bytes - by; + return true; +} + +// The bytes per element of a buffer SRV description. +inline u64 element_size(const D3D12_SHADER_RESOURCE_VIEW_DESC& d) +{ + if (d.Buffer.StructureByteStride > 0) return d.Buffer.StructureByteStride; + if (d.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) return 4; + return element_bytes(static_cast<u32>(d.Format)); +} +inline u64 element_size(const D3D12_UNORDERED_ACCESS_VIEW_DESC& d) +{ + if (d.Buffer.StructureByteStride > 0) return d.Buffer.StructureByteStride; + if (d.Buffer.Flags & D3D12_BUFFER_UAV_FLAG_RAW) return 4; + return element_bytes(static_cast<u32>(d.Format)); +} + +inline void (*&fit_log())(const char*) +{ + static void (*sink)(const char*) = nullptr; + return sink; +} +inline void fit_note(const char* site, const char* what, ID3D12Resource* r, u64 a, u64 b, u64 c) +{ + static std::atomic<int> lines{0}; + if (!fit_log() || lines.fetch_add(1) >= 24) return; + char text[400]; + const D3D12_RESOURCE_DESC d = r ? r->GetDesc() : D3D12_RESOURCE_DESC{}; + std::snprintf(text, sizeof(text), "x2w-gpu heap fit: %s: %s (resource %p dim %d width %llu height %u depth %u mips %u; " + "%llu %llu %llu)", site, what, static_cast<void*>(r), static_cast<int>(d.Dimension), + static_cast<unsigned long long>(d.Width), d.Height, d.DepthOrArraySize, d.MipLevels, + static_cast<unsigned long long>(a), static_cast<unsigned long long>(b), static_cast<unsigned long long>(c)); + fit_log()(text); +} +inline bool fit_refuse(const char* site, const char* what, ID3D12Resource* r, u64 a = 0, u64 b = 0, u64 c = 0) +{ + tally(c_fit_refused); + fit_note(site, what, r, a, b, c); + return false; +} +// A buffer view (SRV or UAV description, ViewDimension BUFFER) on `r`: cut at its end; false when none of it is there. +template <class Desc> +bool fit_buffer(ID3D12Resource* r, Desc& d, const char* site) +{ + if (!r) return true; + const D3D12_RESOURCE_DESC rd = r->GetDesc(); + if (rd.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) return fit_refuse(site, "buffer view of a texture", r); + const u64 e = element_size(d); + if (!e) return fit_refuse(site, "buffer view without an element size (format)", r, static_cast<u64>(d.Format)); + const u64 total = rd.Width / e; + const u64 first = d.Buffer.FirstElement, n = d.Buffer.NumElements; + if (!n || first >= total) return fit_refuse(site, "buffer view past the buffer (first, count, element bytes)", r, first, n, e); + if (first + n > total) { + d.Buffer.NumElements = static_cast<UINT>(total - first); + tally(c_fit_cut); + fit_note(site, "buffer view cut at the buffer's end (first, count, element bytes)", r, first, n, e); + } + return true; +} +inline bool fit_cbv(const D3D12_CONSTANT_BUFFER_VIEW_DESC& c, const char* site) +{ + if (!c.BufferLocation && !c.SizeInBytes) return true; + if (c.BufferLocation % 256 || c.SizeInBytes % 256 || c.SizeInBytes > (64u << 10) || !c.SizeInBytes) + return fit_refuse(site, "constant view (location, size)", nullptr, c.BufferLocation, c.SizeInBytes); + return true; +} +// Mips [most, most + count) of `mips` (count ~0: all from most): the count cut; false when `most` is past them. +inline bool fit_mips(UINT most, UINT& count, UINT mips) +{ + if (most >= mips) return false; + if (count != ~0u && (count == 0 || most + u64{count} > mips)) count = mips - most; + return true; +} +inline bool fit_slices(UINT first, UINT& size, UINT slices) +{ + if (first >= slices) return false; + if (size == 0 || first + u64{size} > slices) size = slices - first; + return true; +} +inline bool fit_srv(ID3D12Resource* r, D3D12_SHADER_RESOURCE_VIEW_DESC* d, const char* site) +{ + if (!r || !d) return true; + if (d->ViewDimension == D3D12_SRV_DIMENSION_BUFFER) return fit_buffer(r, *d, site); + const D3D12_RESOURCE_DESC rd = r->GetDesc(); + const UINT mips = rd.MipLevels ? rd.MipLevels : 1; + const UINT slices = rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1u : rd.DepthOrArraySize; + const auto want = [&](D3D12_RESOURCE_DIMENSION dim) { return rd.Dimension == dim; }; + const auto t1 = D3D12_RESOURCE_DIMENSION_TEXTURE1D, t2 = D3D12_RESOURCE_DIMENSION_TEXTURE2D, t3 = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + bool ok = true; + switch (d->ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: ok = want(t1) && fit_mips(d->Texture1D.MostDetailedMip, d->Texture1D.MipLevels, mips); break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: + ok = want(t1) && fit_mips(d->Texture1DArray.MostDetailedMip, d->Texture1DArray.MipLevels, mips) && + fit_slices(d->Texture1DArray.FirstArraySlice, d->Texture1DArray.ArraySize, slices); + break; + case D3D12_SRV_DIMENSION_TEXTURE2D: ok = want(t2) && fit_mips(d->Texture2D.MostDetailedMip, d->Texture2D.MipLevels, mips); break; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: + ok = want(t2) && fit_mips(d->Texture2DArray.MostDetailedMip, d->Texture2DArray.MipLevels, mips) && + fit_slices(d->Texture2DArray.FirstArraySlice, d->Texture2DArray.ArraySize, slices); + break; + case D3D12_SRV_DIMENSION_TEXTURE2DMS: ok = want(t2); break; + case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: + ok = want(t2) && fit_slices(d->Texture2DMSArray.FirstArraySlice, d->Texture2DMSArray.ArraySize, slices); + break; + case D3D12_SRV_DIMENSION_TEXTURE3D: ok = want(t3) && fit_mips(d->Texture3D.MostDetailedMip, d->Texture3D.MipLevels, mips); break; + case D3D12_SRV_DIMENSION_TEXTURECUBE: + ok = want(t2) && slices >= 6 && fit_mips(d->TextureCube.MostDetailedMip, d->TextureCube.MipLevels, mips); + break; + case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: { + auto& c = d->TextureCubeArray; + ok = want(t2) && fit_mips(c.MostDetailedMip, c.MipLevels, mips) && c.First2DArrayFace + 6ull <= slices; + if (ok && (c.NumCubes == 0 || c.First2DArrayFace + u64{c.NumCubes} * 6 > slices)) c.NumCubes = (slices - c.First2DArrayFace) / 6; + break; + } + default: return true; // raytracing: not made by the mirror + } + if (ok) return true; + return fit_refuse(site, "texture SRV the texture cannot take (view dimension, words 4 and 6 of the description)", r, + static_cast<u64>(d->ViewDimension), d->Texture2DArray.MostDetailedMip, d->Texture2DArray.FirstArraySlice); +} +inline bool fit_uav(ID3D12Resource* r, D3D12_UNORDERED_ACCESS_VIEW_DESC* d, const char* site) +{ + if (!r || !d) return true; + if (d->ViewDimension == D3D12_UAV_DIMENSION_BUFFER) return fit_buffer(r, *d, site); + const D3D12_RESOURCE_DESC rd = r->GetDesc(); + const UINT mips = rd.MipLevels ? rd.MipLevels : 1; + const UINT slices = rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1u : rd.DepthOrArraySize; + const auto want = [&](D3D12_RESOURCE_DIMENSION dim) { return rd.Dimension == dim; }; + const auto t1 = D3D12_RESOURCE_DIMENSION_TEXTURE1D, t2 = D3D12_RESOURCE_DIMENSION_TEXTURE2D, t3 = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + bool ok = true; + switch (d->ViewDimension) { + case D3D12_UAV_DIMENSION_TEXTURE1D: ok = want(t1) && d->Texture1D.MipSlice < mips; break; + case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: + ok = want(t1) && d->Texture1DArray.MipSlice < mips && fit_slices(d->Texture1DArray.FirstArraySlice, d->Texture1DArray.ArraySize, slices); + break; + case D3D12_UAV_DIMENSION_TEXTURE2D: ok = want(t2) && d->Texture2D.MipSlice < mips; break; + case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: + ok = want(t2) && d->Texture2DArray.MipSlice < mips && fit_slices(d->Texture2DArray.FirstArraySlice, d->Texture2DArray.ArraySize, slices); + break; + case D3D12_UAV_DIMENSION_TEXTURE3D: { + auto& w = d->Texture3D; + ok = want(t3) && w.MipSlice < mips; + const UINT depth = ok ? (std::max)(1u, static_cast<UINT>(rd.DepthOrArraySize) >> w.MipSlice) : 0u; + ok = ok && w.FirstWSlice < depth; + if (ok && w.WSize != ~0u && (w.WSize == 0 || w.FirstWSlice + u64{w.WSize} > depth)) w.WSize = depth - w.FirstWSlice; + break; + } + default: return true; + } + if (ok) return true; + return fit_refuse(site, "texture UAV the texture cannot take (view dimension, mip, first slice)", r, + static_cast<u64>(d->ViewDimension), d->Texture2DArray.MipSlice, d->Texture2DArray.FirstArraySlice); +} + +// The raw twin of a buffer view made at `at` on `resource`: the same bytes from the 16 below, moved on where the host +// lets it (staged slots only), else a null buffer view. +template <class Desc> +bool make_twin(ID3D12Device* device, ID3D12Resource* resource, Desc desc, u64 first, u32 n, u32 stride, bool raw, + u64 width, D3D12_CPU_DESCRIPTOR_HANDLE twin, bool staged) +{ + const auto w = twin_window(static_cast<u32>(desc.Format), first, n, stride, raw, width); + if (!w) { + null_buffer_view(device, twin); + tally(c_twins_null); + return false; + } + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Buffer.FirstElement = w->first; + desc.Buffer.NumElements = w->dwords; + desc.Buffer.StructureByteStride = 0; + if constexpr (std::is_same_v<Desc, D3D12_UNORDERED_ACCESS_VIEW_DESC>) { + desc.Buffer.CounterOffsetInBytes = 0; + desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + if (!fit_buffer(resource, desc, "twin")) { + null_buffer_view(device, twin); + tally(c_twins_null); + return false; + } + gpu_view_trace::MirrorCall{device, __FUNCTION__}.uav(resource, nullptr, &desc, twin); + } else { + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (!fit_buffer(resource, desc, "twin")) { + null_buffer_view(device, twin); + tally(c_twins_null); + return false; + } + gpu_view_trace::MirrorCall{device, __FUNCTION__}.srv(resource, &desc, twin); + } + tally(c_twins); + if (w->by == 0) return true; + // Only a staged slot of ours, which the card does not see, is moved. + const u64 start = resource->GetGPUVirtualAddress() + w->first * 4; + if (staged && move_raw(twin, start, w->dwords * 4u, w->by)) { + tally(c_twins_moved); + return true; + } + tally(c_twins_unmoved); + tally(c_twins_null); + null_buffer_view(device, twin); + return false; +} + +// Use the same tested raw descriptor layout as a moved twin, but only in a private CPU +// staging slot. The read stays on the authoritative GPU resource when the driver accepts it. +inline bool offset_raw_srv(ID3D12Device* device, const Home& home, u64 offset, u64 bytes, + D3D12_CPU_DESCRIPTOR_HANDLE at, std::optional<D3D12_CPU_DESCRIPTOR_HANDLE> twin) +{ + const u64 aligned = offset & ~u64{15}; + const UINT delta = UINT(offset - aligned); + const auto resource = home.resource->GetDesc(); + const u64 limit = (std::min<u64>)(resource.Width, home.width); + if (!delta || ((offset | bytes) & 3) || !bytes || bytes > UINT32_MAX - delta || + resource.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || offset > limit || bytes > limit - offset) + return false; + const UINT span = static_cast<UINT>(bytes) + delta; + D3D12_SHADER_RESOURCE_VIEW_DESC raw{}; + raw.Format = DXGI_FORMAT_R32_TYPELESS; + raw.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + raw.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + raw.Buffer.FirstElement = aligned / 4; + raw.Buffer.NumElements = span / 4; + raw.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + gpu_view_trace::MirrorCall{device, __FUNCTION__}.srv(home.resource, &raw, at); + if (!move_raw(at, home.resource->GetGPUVirtualAddress() + aligned, span, delta)) return false; + if (twin) { + gpu_view_trace::MirrorCall{device, __FUNCTION__}.copy(1, *twin, at, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + tally(c_twins); + tally(c_twins_moved); + } + tally(c_direct_offset); + return true; +} + +// Create a buffer SRV or UAV on the window containing the title range. Base and width describe the buffer or placed +// memory; desc describes the title view. +template <class Desc> +Made buffer_view(const Env& env, Exacts& exacts, u64 submit, u64 base, u64 width, Desc desc, ID3D12Resource* own, + D3D12_CPU_DESCRIPTOR_HANDLE at, std::optional<D3D12_CPU_DESCRIPTOR_HANDLE> twin, bool staged, bool primary_staged) +{ + constexpr bool uav = std::is_same_v<Desc, D3D12_UNORDERED_ACCESS_VIEW_DESC>; + ID3D12Device* const device = env.device; + const u64 unit = element_size(desc); + if (!unit || desc.Buffer.FirstElement > (UINT64_MAX - base) / unit) return {}; + const u64 start = base + desc.Buffer.FirstElement * unit; + const u64 len = u64{desc.Buffer.NumElements} * unit; + // The window of the whole buffer, else of the view's own range, else the buffer object's own desktop resource. + Home home; + { + ID3D12Resource* r = nullptr; + u64 off = 0, left = 0; + if (env.find && base && width && env.find(env.ctx, base, width, &r, &off, &left)) { + home = {r, off, off + (std::min)(width, left)}; + } else if (env.find && start && len && env.find(env.ctx, start, len, &r, &off, &left)) { + home = {r, off, off + (std::min)(len, left)}; + desc.Buffer.FirstElement = 0; + base = start; + } else if (own) { + home = {own, 0, (std::min)(width, own->GetDesc().Width)}; + } + } + if (!home.resource || desc.Buffer.FirstElement > (UINT64_MAX - home.offset) / unit) return {}; + Microsoft::WRL::ComPtr<ID3D12Resource> pin; + bool raw_flag; + if constexpr (uav) raw_flag = (desc.Buffer.Flags & D3D12_BUFFER_UAV_FLAG_RAW) != 0; + else raw_flag = (desc.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) != 0; + if (off_elements(home.offset + desc.Buffer.FirstElement * unit, desc.Buffer.StructureByteStride, raw_flag, + element_bytes(static_cast<u32>(desc.Format)))) { + if constexpr (uav) { + // What a shader writes through a copy is lost: null, counted (PLAN.md 1.3). + tally(c_cross_uav); + return {}; + } else { + const u64 offset = home.offset + desc.Buffer.FirstElement * unit; + if (primary_staged && (raw_flag || (desc.Format == DXGI_FORMAT_UNKNOWN && desc.Buffer.StructureByteStride)) && + env.coherent_window && env.coherent_window(start, len, home.resource, offset) && + offset_raw_srv(device, home, offset, len, at, twin)) + return {true, home.resource, twin ? offset : 0, twin ? len : 0}; + pin = exacts.get(env, start, len, submit); + if (!pin) { + tally(c_exact_failed); + return {}; + } + tally(c_exact); + home = {pin.Get(), 0, len}; + desc.Buffer.FirstElement = 0; + } + } + const u64 offset = home.offset; + // A structured view as a raw view of the same bytes. + std::optional<RawWindow> window; + if (desc.Format == DXGI_FORMAT_UNKNOWN) + window = raw_window(offset, desc.Buffer.FirstElement, desc.Buffer.NumElements, desc.Buffer.StructureByteStride); + if (window) { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Buffer.FirstElement = window->first; + desc.Buffer.NumElements = window->dwords; + desc.Buffer.StructureByteStride = 0; + if constexpr (uav) desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + else desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + } else { + const u64 element = element_size(desc); + if (element == 0 || offset % element != 0) { + tally(c_refused); + return {}; + } + desc.Buffer.FirstElement += offset / element; + } + if constexpr (uav) desc.Buffer.CounterOffsetInBytes = 0; + const u64 first = desc.Buffer.FirstElement; + const u32 n = desc.Buffer.NumElements, stride = desc.Buffer.StructureByteStride; + bool raw; + if constexpr (uav) raw = (desc.Buffer.Flags & D3D12_BUFFER_UAV_FLAG_RAW) != 0; + else raw = (desc.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) != 0; + const u64 view_width = home.width; + if constexpr (uav) { + if (!(home.resource->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + tally(c_refused); + return {}; + } + } + if (!buffer_view_ok(static_cast<u32>(desc.Format), first, n, stride, raw, view_width)) { + tally(c_refused); + return {}; + } + if (!fit_buffer(home.resource, desc, uav ? "buffer UAV" : "buffer SRV")) return {}; + if constexpr (uav) { + gpu_view_trace::MirrorCall{device, __FUNCTION__}.uav(home.resource, nullptr, &desc, at); + } else { + // The console has no component mapping. + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + gpu_view_trace::MirrorCall{device, __FUNCTION__}.srv(home.resource, &desc, at); + } + Made made{true, home.resource}; + made.pin = std::move(pin); + if (twin && make_twin(device, home.resource, desc, first, n, stride, raw, view_width, *twin, staged) && !uav) { + const auto w = twin_window(static_cast<u32>(desc.Format), first, n, stride, raw, view_width); + made.raw_start = w->first * 4 + w->by; + made.raw_bytes = u64{w->dwords} * 4 - w->by; + } + return made; +} + +// Whether the host can make a shader (or unordered) view of `texture` in `format` (0: its own); a view of a typed +// texture in another format of its family takes the texture's. +inline bool fits(ID3D12Resource* texture, DXGI_FORMAT* format, bool unordered) +{ + const D3D12_RESOURCE_DESC d = texture->GetDesc(); + const bool allowed = unordered ? (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) != 0 + : (d.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) == 0; + const u32 own = static_cast<u32>(d.Format); + // The typed depth formats. + const bool depth = own == 20 || own == 40 || own == 45 || own == 55; + if (!allowed || depth) { + tally(c_unfit); + return false; + } + const bool typeless = family(own) == own && family(own + 1) == own; + // An unordered view in an sRGB format: the linear one. + if (unordered && x2w_srgb::linear(d.Format) != d.Format) { + // An externally supplied typed sRGB texture cannot provide our typed UAV. + tally(c_unfit); + return false; + } + if (format && unordered) *format = x2w_srgb::linear(*format); + const u32 view = format ? static_cast<u32>(*format) : 0; + if (view == 0) { + if (typeless) tally(c_unfit); + return !typeless; + } + // For an unsupported target format, use its rendering stand-in: formats 86 and 115 map to 28, and 67 maps to 10. + const u32 stand_in = view == 86 || view == 115 ? 28u : view == 67 ? 10u : view; + if (view != own && stand_in == own) { + *format = d.Format; + return true; + } + if (family(view) != family(own)) { + tally(c_unfit); + return false; + } + if (!typeless) *format = d.Format; + return true; +} + +// The host descriptor for `view` at `at`, and its raw twin at `twin` (a buffer view's; a constant buffer's is the +// same view again). `staged`: `twin` is a CPU-only slot (move_raw may change it). +inline Made make_twinned(const Env& env, Exacts& exacts, u64 submit, const View& view, D3D12_CPU_DESCRIPTOR_HANDLE at, + std::optional<D3D12_CPU_DESCRIPTOR_HANDLE> twin, bool staged, bool primary_staged) +{ + ID3D12Device* const device = env.device; + if (view.explicit_null) { + const bool uav = view.kind == Kind::unordered; + if (uav) gpu_view_trace::MirrorCall{device, __FUNCTION__}.uav(nullptr, nullptr, &view.uav, at); + else gpu_view_trace::MirrorCall{device, __FUNCTION__}.srv(nullptr, &view.srv, at); + if (twin && view.buffer) { + if (uav) { + D3D12_UNORDERED_ACCESS_VIEW_DESC raw{}; + raw.Format = DXGI_FORMAT_R32_TYPELESS; + raw.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + raw.Buffer.NumElements = 1; + raw.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + gpu_view_trace::MirrorCall{device, __FUNCTION__}.uav(nullptr, nullptr, &raw, *twin); + } else null_buffer_view(device, *twin); + } + return {true, nullptr}; + } + switch (view.kind) { + case Kind::constant: { + ID3D12Resource* r = nullptr; + u64 off = 0, left = 0; + if (!env.find || !env.find(env.ctx, view.address, (std::max<u64>)(view.bytes, 1), &r, &off, &left)) return {}; + const u64 gpu = r->GetGPUVirtualAddress() + off; + if (gpu % 256 != 0) { + // WP3 copies such constants per draw (PLAN.md 1.3). + tally(c_cbv_unaligned); + return {}; + } + u32 size = constant_bytes(static_cast<u32>((std::min<u64>)(view.bytes, 0xffffffffu))); + // Not past the window. + const u64 room = r->GetDesc().Width - off; + if (size > room) size = static_cast<u32>(room & ~u64{255}); + if (!size) return {}; + D3D12_CONSTANT_BUFFER_VIEW_DESC c{gpu, size}; + if (!fit_cbv(c, "constant")) return {}; + gpu_view_trace::MirrorCall{device, __FUNCTION__}.cbv(&c, at); + if (twin) gpu_view_trace::MirrorCall{device, __FUNCTION__}.cbv(&c, *twin); + return {true, r}; + } + case Kind::shader: { + if (view.buffer) { + if (!view.has_desc) return {}; + return buffer_view(env, exacts, submit, view.address, view.bytes, view.srv, view.resource, at, twin, staged, primary_staged); + } + D3D12_SHADER_RESOURCE_VIEW_DESC desc = view.srv; + if (!view.resource || !fits(view.resource, view.has_desc ? &desc.Format : nullptr, false)) return {}; + if (view.has_desc && !fit_srv(view.resource, &desc, "texture SRV")) return {}; + gpu_view_trace::MirrorCall{device, __FUNCTION__}.srv(view.resource, view.has_desc ? &desc : nullptr, at); + return {true, view.resource}; + } + case Kind::unordered: { + if (view.buffer) { + if (!view.has_desc) return {}; + return buffer_view(env, exacts, submit, view.address, view.bytes, view.uav, view.resource, at, twin, staged, primary_staged); + } + D3D12_UNORDERED_ACCESS_VIEW_DESC desc = view.uav; + if (!fits(view.resource, view.has_desc ? &desc.Format : nullptr, true)) return {}; + if (view.has_desc && !fit_uav(view.resource, &desc, "texture UAV")) return {}; + gpu_view_trace::MirrorCall{device, __FUNCTION__}.uav(view.resource, view.counter, view.has_desc ? &desc : nullptr, at); + return {true, view.resource}; + } + case Kind::sampler: + gpu_view_trace::MirrorCall{device, __FUNCTION__}.sampler(&view.sampler, at); + return {true, nullptr}; + case Kind::placed: + if (view.unordered) return buffer_view(env, exacts, submit, view.address, view.bytes, view.uav, nullptr, at, twin, staged, primary_staged); + return buffer_view(env, exacts, submit, view.address, view.bytes, view.srv, nullptr, at, twin, staged, primary_staged); + default: + return {}; + } +} + +// ---- The mirror heap ---------------------------------------------- + + +// Slots of this thread's own in heaps the card does not see: two of views and two of samplers. Descriptors are made +// there and copied whole into the heap the card sees, so no submission reads one half made. +struct Stage { + ID3D12Device* device = nullptr; + ID3D12DescriptorHeap* heaps[2]{}; + u64 starts[2]{}; + u32 steps[2]{}; + ~Stage() + { + for (auto* h : heaps) + if (h) h->Release(); + } +}; +inline bool view_copy_on() +{ + static const bool on = [] { + char v[4]{}; + return !(GetEnvironmentVariableA("X2W_GPU_VIEW_COPY", v, sizeof(v)) && v[0] == '0'); + }(); + return on; +} +inline std::optional<D3D12_CPU_DESCRIPTOR_HANDLE> staged(ID3D12Device* device, bool sampler, u32 which) +{ + if (!view_copy_on()) return std::nullopt; + thread_local Stage stage; + if (stage.device != device) { + for (auto*& h : stage.heaps) + if (h) h->Release(), h = nullptr; + stage.device = device; + for (int k = 0; k < 2; ++k) { + D3D12_DESCRIPTOR_HEAP_DESC d{k ? D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER : D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + if (FAILED(device->CreateDescriptorHeap(&d, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&stage.heaps[k])))) { + stage.heaps[k] = nullptr; + continue; + } + stage.starts[k] = stage.heaps[k]->GetCPUDescriptorHandleForHeapStart().ptr; + stage.steps[k] = device->GetDescriptorHandleIncrementSize(d.Type); + } + } + const int k = sampler ? 1 : 0; + if (!stage.heaps[k]) return std::nullopt; + return D3D12_CPU_DESCRIPTOR_HANDLE{static_cast<SIZE_T>(stage.starts[k] + u64{which} * stage.steps[k])}; +} + +// What is known of a record a list's tables hold. +struct Listed { + Kind kind = Kind::none; + bool unordered = false; + bool texture = false; +}; + +class HostHeap { + struct MaterialRetry { + std::array<u32, 8> words; + const char* reason; + }; +public: + // The layout for `count` title slots under `limits` (probe_view_limit), every slot null. `title_cpu`, `title_step`: + // the title's descriptor memory and its bytes a slot (records are read there). + static std::unique_ptr<HostHeap> create(const Env& env, bool sampler, u32 count, const Limits& limits, u64 title_cpu, + u32 title_step, u32 dynamic_most = dynamic_most_default) + { + std::unique_ptr<HostHeap> h(new HostHeap); + h->env_ = env; + h->layout_ = layout_for(sampler, count, limits, dynamic_most); + h->title_cpu_ = title_cpu; + h->title_step_ = title_step; + const auto kind = sampler ? D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER : D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + D3D12_DESCRIPTOR_HEAP_DESC d{kind, h->layout_.size, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + if (FAILED(env.device->CreateDescriptorHeap(&d, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&h->heap_)))) + return nullptr; + h->cpu_ = h->heap_->GetCPUDescriptorHandleForHeapStart().ptr; + h->gpu_ = h->heap_->GetGPUDescriptorHandleForHeapStart().ptr; + h->step_ = env.device->GetDescriptorHandleIncrementSize(kind); + const Layout& l = h->layout_; + h->made_.assign(l.count, 0); + h->twin_shown_.assign(l.twins, 0); + h->kept_.assign(u64{l.count} + l.dynamic, nullptr); + h->runs_.reset(l.count, l.dynamic); + h->buffers_.resize(l.count); + h->changed_.resize(l.count); + if (title_cpu) h->last_.assign(std::size_t{l.count} * title_step, 0); + for (auto& lock : h->locks_) InitializeSRWLock(&lock); + if (!sampler) { + const u64 bytes = u64{slot_strides_count} * 4; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_UPLOAD}; + D3D12_RESOURCE_DESC b{}; + b.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + b.Width = bytes; + b.Height = 1; + b.DepthOrArraySize = 1; + b.MipLevels = 1; + b.SampleDesc.Count = 1; + b.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + const D3D12_RANGE none{0, 0}; + if (SUCCEEDED(env.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &b, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, __uuidof(ID3D12Resource), + reinterpret_cast<void**>(&h->strides_))) && + SUCCEEDED(h->strides_->Map(0, &none, reinterpret_cast<void**>(&h->stride_words_)))) { + std::memset(h->stride_words_, 0, bytes); + h->strides_->SetName(L"x2w-gpu element strides by view heap slot"); + } + } + if (!h->fill_null(kind)) return nullptr; + return h; + } + ~HostHeap() + { + for (auto* r : kept_) + if (r) r->Release(); + for (auto& [_, r] : retired_) + if (r) r->Release(); + if (strides_) strides_->Release(); + if (heap_) heap_->Release(); + } + HostHeap(const HostHeap&) = delete; + HostHeap& operator=(const HostHeap&) = delete; + + const Layout& layout() const { return layout_; } + ID3D12DescriptorHeap* heap() const { return heap_; } + u32 count() const { return layout_.count; } + u32 step() const { return step_; } + bool sampler() const { return layout_.sampler; } + D3D12_CPU_DESCRIPTOR_HANDLE cpu(u32 index) const { return {static_cast<SIZE_T>(cpu_ + u64{index} * step_)}; } + D3D12_GPU_DESCRIPTOR_HANDLE gpu_handle(u32 index) const { return {gpu_ + u64{index} * step_}; } + // GPU address and resource for the stride table. + u64 strides_gpu() const { return strides_ ? strides_->GetGPUVirtualAddress() : 0; } + ID3D12Resource* strides_buffer() const { return strides_; } + u32 stride_word(u32 index) const { return stride_words_ && index < slot_strides_count ? stride_words_[index] : 0; } + + // Makes host slot `index` from the record the title has at its slot if it changed since; true if the slot shows a + // view. A list's dynamic table owns these slot references until its submission retires. A rejected view keeps + // nullptr even when the original title record still names a texture. + ID3D12Resource* kept_at(u32 index) + { + if (index >= kept_.size()) return nullptr; + SRWLOCK& lock = lock_of(index); + AcquireSRWLockShared(&lock); + ID3D12Resource* resource = kept_[index]; + ReleaseSRWLockShared(&lock); + return resource; + } + x2w_material_trace::Record material_record(u32 slot, u32 base, x2w_material::Mask fields) + { + x2w_material_trace::Record record; + if (!fields || slot >= kept_.size() || base % 4) return record; + auto& lock = lock_of(slot); + AcquireSRWLockShared(&lock); + const auto& ranges = raw_ranges_[slot % 512]; + const auto it = ranges.find(slot); + if (it != ranges.end() && base <= it->second.second && it->second.second - base >= x2w_material::byte_count(fields)) { + record.source = kept_[slot]; + record.offset = it->second.first + base; + record.bytes = it->second.second - base; + record.fields = fields; + } + ReleaseSRWLockShared(&lock); + return record; + } + void material_slots(std::vector<x2w_material_trace::Slot>& slots) + { + for (UINT stripe = 0; stripe < 512; ++stripe) { + auto& lock = locks_[stripe]; + AcquireSRWLockShared(&lock); + struct Unlock { SRWLOCK* lock; ~Unlock() { ReleaseSRWLockShared(lock); } } unlock{&lock}; + std::lock_guard<std::mutex> guard(mutex_); + for (UINT i = stripe; i < layout_.count; i += 512) { + x2w_material_trace::Slot item; + const size_t pos = size_t(i) * title_step_; + if (title_step_ <= 32 && pos + title_step_ <= last_.size()) + std::memcpy(item.words.data(), last_.data() + pos, title_step_); + auto* resource = i < kept_.size() ? kept_[i] : nullptr; + if (!resource && !item.words[0] && !item.words[1]) continue; + item.index = i; + if (resource) { + const auto desc = resource->GetDesc(); + item.host = reinterpret_cast<UINT_PTR>(resource); + item.format = desc.Format; + item.dimension = desc.Dimension; + item.width = static_cast<UINT>(desc.Width); + item.height = desc.Height; + } + const auto& group = textures_[i % textures_.size()]; + const auto tex = group.find(i); + if (tex != group.end()) { + const auto& t = tex->second; + item.view_format = t.srv.Format; + item.texture_address = u64(t.placement[2]) << 32 | t.placement[1]; + } + if (item.words[0] == x2w_late_texture::lazy || item.words[0] == x2w_late_texture::magic) { + item.lazy = lazy_.count(i) || lazy_waiting_.count(i); + for (const auto* retries : {&material_due_, &material_waiting_}) { + auto it = retries->find(i); + if (it != retries->end() && it->second.words == item.words) + item.material_retry = it->second.reason; + } + item.late = late_.count(i) != 0; + if (!item.texture_address) item.texture_address = u64(item.words[2]) << 32 | item.words[1]; + if (!item.view_format) item.view_format = (item.words[4] >> 8) & 255; + } + slots.push_back(item); + } + } + } + bool mirror(u32 index, bool use = true) + { + if (index >= layout_.count) return false; + std::uint32_t words[8]{}; + const u32 bytes = (std::min)(title_step_, 32u); + if (!title_cpu_ || !read_title(title_cpu_ + u64{index} * title_step_, words, bytes)) return false; + // Remember the mirrored words so submit detects a title copy that clears this slot. + if (title_step_ <= 32) { + std::lock_guard<std::mutex> lock(mutex_); + if (!last_.empty()) std::memcpy(last_.data() + std::size_t{index} * title_step_, words, title_step_); + } + return mirror_words(index, words, use); + } + // As mirror, from the record's words as already read. + bool mirror_words(u32 index, const std::uint32_t words[8], bool use = true) + { + if (index >= layout_.count) return false; + View v; + if (!use && words[0] == x2w_late_texture::lazy && !layout_.sampler) { + tally(c_lazy_staged); + v.kind = Kind::shader; + v.has_desc = true; + D3D12_RESOURCE_DESC desc{}; + if (!x2w_late_texture::decode(words, desc, v.srv)) { + make_null(index); + return false; + } + std::copy_n(words, 8, v.placement.begin()); + v.placement[0] = x2w_late_texture::magic; + SRWLOCK& lock = lock_of(index); + AcquireSRWLockExclusive(&lock); + const bool retained = restore_pending(index, v); + if (!retained) { + make_locked(index, v); + made_[index] = 0; + note_buffer(index, nullptr); + } + { + std::lock_guard<std::mutex> guard(mutex_); + late_.erase(index); + unmade_.erase(index); + lazy_waiting_.erase(index); + lazy_.insert(index); + } + ReleaseSRWLockExclusive(&lock); + return retained; + } + const bool has = view_of_record(env_, words, layout_.sampler, v); + SRWLOCK& lock = lock_of(index); + AcquireSRWLockExclusive(&lock); + const u64 shown = made_[index]; + if (!has) { + // Not a view of ours (never written, or of a resource the title released): nothing to read. + if (shown != 0) { + made_[index] = 0; + make_null_locked(index); + note_buffer(index, nullptr); + } + ReleaseSRWLockExclusive(&lock); + return false; + } + if (v.pending && !v.resource && restore_pending(index, v)) { + tally(c_retained_pending); + { + std::lock_guard<std::mutex> guard(mutex_); + late_.insert(index); + } + ReleaseSRWLockExclusive(&lock); + return true; + } + if (shown == v.key && (!x2w_late_texture::marker(words[0]) || (v.resource && kept_[index] == v.resource))) { + if (v.pending) { + std::lock_guard<std::mutex> guard(mutex_); + late_.insert(index); + } + ReleaseSRWLockExclusive(&lock); + return true; + } + tally(c_mirrored); + const bool made = make_locked(index, v); + // A view that could not be made (its window not yet known, say) shows null and is not taken as made: it is + // tried again at the next submits (retry_unmade) until it is, or its record changes. + made_[index] = made ? v.key : 0; + note_buffer(index, made ? &v : nullptr); + ReleaseSRWLockExclusive(&lock); + { + std::lock_guard<std::mutex> guard(mutex_); + if (words[0] == x2w_late_texture::lazy && made && !v.pending) { + lazy_.erase(index); + lazy_waiting_.erase(index); + material_due_.erase(index); + material_waiting_.erase(index); + } + if ((!made || v.pending) && x2w_late_texture::marker(words[0])) late_.insert(index); + else if (made) unmade_.erase(index); + else ++unmade_[index]; + } + return made; + } + // The slots whose views could not be made, tried again (at most `most` of them a submit; a slot is given up after + // 64 tries, until its record changes); how many were made. + u64 retry_unmade(std::size_t most) + { + constexpr u32 tries = 64; + std::vector<u32> trying; + { + std::lock_guard<std::mutex> guard(mutex_); + for (auto it = unmade_.begin(); it != unmade_.end() && trying.size() < most;) { + if (it->second >= tries) { + it = unmade_.erase(it); + continue; + } + trying.push_back(it->first); + ++it; + } + } + u64 made = 0; + for (u32 index : trying) + if (made_[index] == 0 && mirror(index) && made_[index] != 0) ++made; + return made; + } + // Mirrors `n` slots from `first` (a range the title wrote or copied by a call). + void mirror_range(u32 first, u32 n) + { + for (u64 i = first; i < u64{first} + n && i < layout_.count; ++i) mirror(static_cast<u32>(i), false); + } + bool view_at(u32 source, const u32 words[8], View& view) + { + if (!view_of_record(env_, words, layout_.sampler, view)) return false; + if (view.pending && !view.resource && source < layout_.count) { + auto& lock = lock_of(source); + AcquireSRWLockShared(&lock); + restore_pending(source, view); + ReleaseSRWLockShared(&lock); + } + return true; + } + // Data-dependent GPU indices have no CPU table lookup. Resolve a bounded rotating set on an open + // list, recording the upload before exposing the real binding. Re-read the title after the upload. + void warm_lazy(void* list, u64 frame, LazyBudget& budget, u32 visit_limit = 4096, + u64 byte_limit = 96ull << 20, double time_limit_ms = 32) + { + if (!visit_limit || !env_.upload) return; + std::unique_lock budget_lock(budget.mutex, std::try_to_lock); + if (!budget_lock) return; + { + std::lock_guard guard(mutex_); + if (lazy_.empty() && lazy_waiting_.empty()) return; + } + if (budget.frame != frame) { + budget.frame = frame; + budget.bytes = budget.visits = 0; + budget.elapsed_ms = 0; + budget.room = env_.local_room ? env_.local_room(env_.device) : UINT64_MAX; + } + if (budget.visits >= visit_limit || budget.bytes >= byte_limit || + budget.elapsed_ms >= time_limit_ms) return; + const auto begin = now(); + const u64 generation = env_.mapping_epoch ? env_.mapping_epoch() : 0; + { + std::lock_guard guard(mutex_); + if (lazy_frame_ != frame || lazy_generation_ != generation) { + lazy_.merge(lazy_waiting_); + material_due_.merge(material_waiting_); + lazy_frame_ = frame; + lazy_generation_ = generation; + } + if (lazy_.empty()) return; + } + for (u32 i = 0; i < 64 && budget.visits < visit_limit && budget.bytes < byte_limit; ++i) { + if (budget.elapsed_ms + ms(now() - begin) >= time_limit_ms) break; + if (env_.local_room && budget.visits && (budget.visits % 32 == 0)) + budget.room = env_.local_room(env_.device); + u32 slot; + std::optional<MaterialRetry> selected; + { + std::lock_guard guard(mutex_); + if (lazy_.empty() || (!budget.room && material_due_.empty())) break; + auto it = lazy_.lower_bound(lazy_cursor_); + if (it == lazy_.end()) it = lazy_.begin(); + slot = *it; + // Leave every fourth visit to the general queue while allocations are possible. + if (!material_due_.empty() && (!budget.room || budget.visits % 4 != 3)) { + auto next = material_due_.lower_bound(material_cursor_); + if (next == material_due_.end()) next = material_due_.begin(); + slot = next->first; + material_cursor_ = slot + 1; + } else lazy_cursor_ = slot + 1; + if (auto entry = material_due_.extract(slot); !entry.empty()) selected = entry.mapped(); + lazy_.erase(slot); + } + ++budget.visits; + const u64 before = env_.copied_bytes ? env_.copied_bytes() : 0; + const u64 allocated = env_.allocated_bytes ? env_.allocated_bytes() : 0; + warm_slot(list, slot, false, budget.room, selected ? &*selected : nullptr); + if (env_.copied_bytes) budget.bytes += env_.copied_bytes() - before; + if (env_.allocated_bytes) { + const u64 delta = env_.allocated_bytes() - allocated; + budget.room -= (std::min)(budget.room, delta); + } + } + budget.elapsed_ms += ms(now() - begin); + } + bool warm_slot(void* list, u32 slot, bool targeted = false, u64 room = UINT64_MAX, const MaterialRetry* retry = nullptr) + { + if (!env_.upload || slot >= layout_.count || title_step_ != 32) return false; + const u64 at = title_cpu_ + u64{slot} * title_step_; + u32 words[8]{}, latest[8]; + const auto park_locked = [&](const char* reason) { + if ((targeted || retry) && words[0] == x2w_late_texture::lazy && + (material_waiting_.count(slot) || material_due_.count(slot) || + material_waiting_.size() + material_due_.size() < 512)) { + MaterialRetry entry{}; + std::copy_n(words, 8, entry.words.begin()); + entry.reason = reason; + material_due_.erase(slot); + material_waiting_[slot] = entry; + lazy_.erase(slot); + } + if (!lazy_.count(slot)) lazy_waiting_.insert(slot); + }; + const auto park = [&](const char* reason) { + std::lock_guard guard(mutex_); + park_locked(reason); + return false; + }; + if (!read_title(at, words, sizeof(words))) { + if (retry) std::copy_n(retry->words.begin(), 8, words); + return park("descriptor_unreadable"); + } + if (retry && !std::equal(retry->words.begin(), retry->words.end(), words)) { + mirror_words(slot, words, false); + return false; + } + if (words[0] != x2w_late_texture::lazy) return false; + D3D12_RESOURCE_DESC desc{}; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + if (!x2w_late_texture::decode(words, desc, srv)) return false; + if (targeted) { + std::lock_guard<std::mutex> guard(mutex_); + const auto& bucket = textures_[slot % textures_.size()]; + const auto it = bucket.find(slot); + if (it != bucket.end() && it->second.texture && !lazy_.count(slot) && !lazy_waiting_.count(slot) && + it->second.placement[0] == x2w_late_texture::magic && + std::equal(words + 1, words + 8, it->second.placement.begin() + 1)) return false; + } + if (targeted && room == UINT64_MAX && env_.local_room) room = env_.local_room(env_.device); + // Selected materials may already have a compatible placement or streamed mip suffix. + // Charge an allocation only when the publisher actually creates a host texture. + const bool allow_create = room && (room == UINT64_MAX || !env_.allocation_size || + env_.allocation_size(env_.device, words) <= room); + if (!allow_create && !targeted && !retry) return park("local_budget"); + const u64 generation = !allow_create && env_.mapping_epoch ? env_.mapping_epoch() : 0; + View view; + const bool ready = view_of_record(env_, words, false, view, allow_create) && view.resource && + env_.upload(env_.ctx, list, view.wrapper, view.resource); + if (!read_title(at, latest, sizeof(latest))) return park("descriptor_unreadable"); + if (!std::equal(std::begin(words), std::end(words), latest)) { + mirror_words(slot, latest, false); + return false; + } + if (!allow_create && env_.mapping_epoch && env_.mapping_epoch() != generation) return park("mapping_changed"); + if (!ready) return park(view.resource ? "upload_failed" : !allow_create ? "local_budget" : + view.pending ? "backing_unavailable" : "unresolved"); + SRWLOCK& lock = lock_of(slot); + AcquireSRWLockExclusive(&lock); + bool made = false; + if (read_title(at, latest, sizeof(latest)) && std::equal(std::begin(words), std::end(words), latest)) { + made = make_locked(slot, view); + made_[slot] = made ? view.key : 0; + note_buffer(slot, nullptr); + if (made) tally(c_lazy_warmed); + std::lock_guard<std::mutex> guard(mutex_); + if (!made || view.pending) { + park_locked(made ? "partial_mips" : "view_failed"); + } else { + material_due_.erase(slot); + material_waiting_.erase(slot); + lazy_.erase(slot); + lazy_waiting_.erase(slot); + } + } else { + park("descriptor_changed"); + } + ReleaseSRWLockExclusive(&lock); + return made; + } + unsigned materialize(void* list, const x2w_material_trace::Words& words, x2w_material::Mask fields) + { + unsigned made = 0; + for (size_t i = 0; fields; fields >>= 1, ++i) + if (fields & 1) made += warm_slot(list, x2w_material_trace::index(words[i]), true); + return made; + } + // Whether the slot currently exposes a null descriptor. + bool shows_none(u32 index) const { return index >= layout_.count || made_[index] == 0; } + + // Makes slot `index` (a dynamic one) from `view`; a null view if the host cannot. + void make_at(u32 index, const View& view) + { + if (index >= layout_.size) return; + SRWLOCK& lock = lock_of(index); + AcquireSRWLockExclusive(&lock); + make_locked(index, view); + ReleaseSRWLockExclusive(&lock); + } + // Makes slot `index` (a dynamic one) the view the record `words` names. Constant buffers are not made so (their + // bytes are copied for each draw, WP3): nullopt, as for a record that names no view. + std::optional<Listed> make_listed(u32 index, const std::uint32_t words[8], u32 source = UINT32_MAX, View* result = nullptr) + { + if (layout_.sampler) return std::nullopt; + View v; + if (!view_at(source, words, v) || v.kind == Kind::constant) return std::nullopt; + make_at(index, v); + if (result) *result = v; + return Listed{v.kind, v.kind == Kind::unordered || (v.kind == Kind::placed && v.unordered), v.is_texture()}; + } + // Reset a dynamic slot to a null descriptor. + void make_null(u32 index) + { + if (index >= layout_.size) return; + SRWLOCK& lock = lock_of(index); + AcquireSRWLockExclusive(&lock); + make_null_locked(index); + if (index < layout_.count) { + made_[index] = 0; + note_buffer(index, nullptr); + } + ReleaseSRWLockExclusive(&lock); + } + + // Slot `index` (a dynamic one) a raw view of `len` bytes of `buffer` from byte `offset` (a multiple of 16): a root + // SRV with a size. + void raw_at(u32 index, ID3D12Resource* buffer, u64 offset, u64 len) + { + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + d.Buffer.FirstElement = offset / 4; + d.Buffer.NumElements = static_cast<UINT>((std::min<u64>)((std::max<u64>)(len / 4, 1), 0xffffffffu)); + d.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + if (!fit_buffer(buffer, d, "root SRV")) return null_raw_at(index); + made_by(index, buffer, [&](D3D12_CPU_DESCRIPTOR_HANDLE at) { gpu_view_trace::MirrorCall{env_.device, __FUNCTION__}.srv(buffer, &d, at); }); + } + // A root UAV with a size. + void raw_uav_at(u32 index, ID3D12Resource* buffer, u64 offset, u64 len) + { + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d.Buffer.FirstElement = offset / 4; + d.Buffer.NumElements = static_cast<UINT>((std::min<u64>)((std::max<u64>)(len / 4, 1), 0xffffffffu)); + d.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + if (!fit_buffer(buffer, d, "root UAV")) return null_raw_uav_at(index); + made_by(index, buffer, [&](D3D12_CPU_DESCRIPTOR_HANDLE at) { gpu_view_trace::MirrorCall{env_.device, __FUNCTION__}.uav(buffer, nullptr, &d, at); }); + } + // Create a null raw SRV or UAV. + void null_raw_at(u32 index) + { + made_by(index, nullptr, [&](D3D12_CPU_DESCRIPTOR_HANDLE at) { null_buffer_view(env_.device, at); }); + } + void null_raw_uav_at(u32 index) + { + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d.Buffer.NumElements = 1; + d.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + made_by(index, nullptr, [&](D3D12_CPU_DESCRIPTOR_HANDLE at) { gpu_view_trace::MirrorCall{env_.device, __FUNCTION__}.uav(nullptr, nullptr, &d, at); }); + } + // Slot `index` (a dynamic one) a constant buffer view of `size` bytes at `gpu` of `buffer`, which the slot holds; + // its twin the raw view of the same bytes. + void constant_at(u32 index, ID3D12Resource* buffer, u64 gpu, u32 size) + { + if (index >= layout_.size) return; + D3D12_CONSTANT_BUFFER_VIEW_DESC c{gpu, constant_bytes(size)}; + if (!fit_cbv(c, "constant_at")) c = {}; + SRWLOCK& lock = lock_of(index); + AcquireSRWLockExclusive(&lock); + const auto at = make_place(0); + gpu_view_trace::MirrorCall{env_.device, __FUNCTION__}.cbv(&c, at.first); + put(index, at); + bool twin = false; + if (layout_.has_twin(index) && c.SizeInBytes > 0 && buffer) { + const auto t = make_place(1); + D3D12_SHADER_RESOURCE_VIEW_DESC raw{}; + raw.Format = DXGI_FORMAT_R32_TYPELESS; + raw.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + raw.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + raw.Buffer.FirstElement = (gpu - buffer->GetGPUVirtualAddress()) / 4; + raw.Buffer.NumElements = c.SizeInBytes / 4; + raw.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + if (fit_buffer(buffer, raw, "constant twin")) gpu_view_trace::MirrorCall{env_.device, __FUNCTION__}.srv(buffer, &raw, t.first); + else null_buffer_view(env_.device, t.first); + put(layout_.twin(index), t); + twin = true; + } + twin_made(index, twin); + keep(index, buffer); + ReleaseSRWLockExclusive(&lock); + } + + // Allocate and release dynamic descriptor slots. + std::optional<u32> dynamic(u32 n) + { + if (layout_.sampler) return std::nullopt; + std::lock_guard<std::mutex> lock(mutex_); + const auto first = runs_.take(n); + if (!first) { + static std::atomic<bool> said{false}; + if (!said.exchange(true)) log("x2w-gpu heap: no free dynamic descriptor slots: a table is not made (%u asked)", n); + } + return first; + } + void release(u32 first, u32 n) + { + std::lock_guard<std::mutex> lock(mutex_); + runs_.release(first, n); + } + + // Track occupied buffer slots and changes to their descriptors. + std::vector<u32> buffer_slots() + { + std::lock_guard<std::mutex> lock(mutex_); + std::vector<u32> out; + buffers_.each([&](u32 i) { out.push_back(i); }); + return out; + } + std::vector<u32> buffer_changes() + { + std::lock_guard<std::mutex> lock(mutex_); + return changed_.take(); + } + + // At submission, compare title records with their last mirrored bytes to catch descriptors copied without API + // calls. Refresh private buffer-view copies, retire old resources and schedule a portion of visible textures for + // upload. Return the slots that changed. + u64 submit() + { + const LONGLONG began = now(); + const u64 at = ++submits_; + u64 changed = 0; + // Retry the previous submit's unresolved slots before scanning new writes. mirror() updates + // last_ from the live record, so the diff does not resolve the same unchanged slot twice. + // Revisit a bounded rotating subset each submit. Read the live record in mirror() + // so a descriptor overwritten while streaming cannot restore the earlier texture. + std::vector<u32> late; + if (env_.late_texture) { + std::lock_guard<std::mutex> guard(mutex_); + auto it = late_.lower_bound(late_cursor_); + if (it == late_.end()) it = late_.begin(); + while (it != late_.end() && late.size() < 32) { + late.push_back(*it); + it = late_.erase(it); + } + late_cursor_ = it == late_.end() ? 0 : *it; + } + for (u32 index : late) mirror(index); + if (title_cpu_) { + const std::size_t step = title_step_; + const std::size_t total = std::size_t{layout_.count} * step; + { + std::lock_guard<std::mutex> lock(mutex_); + if (last_.size() != total) last_.assign(total, 0); + } + constexpr std::size_t piece = 64u << 10; + std::vector<unsigned char> now_bytes(piece); + std::vector<u32> slots; + for (std::size_t from = 0; from < total; from += piece) { + const std::size_t n = (std::min)(piece, total - from) / step * step; + if (!n) break; + if (!read_title(title_cpu_ + from, now_bytes.data(), n)) continue; + slots.clear(); + { + std::lock_guard<std::mutex> lock(mutex_); + changed_records(last_.data() + from, now_bytes.data(), n, step, static_cast<u32>(from / step), slots); + } + for (u32 index : slots) { + std::uint32_t words[8]{}; + std::memcpy(words, now_bytes.data() + (std::size_t{index} * step - from), (std::min<std::size_t>)(step, 32)); + mirror_words(index, words, false); + } + changed += slots.size(); + } + } + tally(c_changed, changed); + tally(c_retried, retry_unmade(4096)); + exacts_.refresh(env_, at, 3); + retire(at); + sweep_textures(at); + const LONGLONG spent = now() - began; + submit_ticks_ += spent; + if ((at & (at - 1)) == 0) + log("x2w-gpu heap submit %llu: %llu records changed (%llu in all), %.2f ms (%.2f ms a submit); made %llu, null %llu, " + "twins %llu (moved %llu, null %llu), refused %llu, unaligned CBVs %llu, crossing UAVs %llu, own-byte copies %llu " + "(%zu live, %llu failed: invalid %llu, cache full %llu, create %llu, map %llu, unreadable %llu), direct unaligned SRVs %llu, retried and made %llu, V# %llu, S# %llu, unfit %llu, textures due %llu, uploaded %llu, views cut to fit %llu, refused as unfit for the host %llu, matching pending texture views retained %llu, lazy visible slots staged %llu, warmed on bind %llu", + at, changed, counted(c_changed), ms(spent), ms(submit_ticks_) / static_cast<double>(at), counted(c_made), + counted(c_null), counted(c_twins), counted(c_twins_moved), counted(c_twins_null), counted(c_refused), + counted(c_cbv_unaligned), counted(c_cross_uav), counted(c_exact), exacts_.size(), counted(c_exact_failed), + counted(c_exact_invalid), counted(c_exact_capacity), counted(c_exact_create), counted(c_exact_map), + counted(c_exact_unreadable), counted(c_direct_offset), counted(c_retried), + counted(c_vsharp), counted(c_ssharp), counted(c_unfit), counted(c_textures_due), counted(c_uploads), counted(c_fit_cut), + counted(c_fit_refused), counted(c_retained_pending), counted(c_lazy_staged), counted(c_lazy_warmed)); + return changed; + } + + // PLAN.md 4b: up to `max` textures due (made into a slot, or swept again) are uploaded on `list`; how many. + std::size_t upload_due(void* list, std::size_t max) + { + if (!env_.upload) return 0; + std::size_t done = 0; + while (done < max) { + Texture t; + { + std::lock_guard<std::mutex> lock(mutex_); + if (due_.empty()) break; + const u32 index = due_.front(); + due_.pop_front(); + due_set_[index] = 0; + const auto& group = textures_[index % textures_.size()]; + const auto found = group.find(index); + if (found == group.end()) continue; + t = found->second; + t.texture->AddRef(); + } + if (env_.upload(env_.ctx, list, t.wrapper, t.texture)) tally(c_uploads); + t.texture->Release(); + ++done; + } + return done; + } + std::size_t textures_due() + { + std::lock_guard<std::mutex> lock(mutex_); + return due_.size(); + } + +private: + HostHeap() = default; + + struct Texture { + u64 wrapper = 0; + ID3D12Resource* texture = nullptr; // held by kept_ while the slot shows it + std::array<u32, 8> placement{}; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + u64 view_key = 0; + }; + + static LONGLONG now() + { + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return t.QuadPart; + } + static double ms(LONGLONG ticks) + { + static const double per = [] { + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + return 1000.0 / static_cast<double>(f.QuadPart); + }(); + return static_cast<double>(ticks) * per; + } + void log(const char* format, ...) const + { + if (!env_log()) return; + char text[1024]; + va_list args; + va_start(args, format); + std::vsnprintf(text, sizeof(text), format, args); + va_end(args); + env_log()(text); + } + +public: + // Where log lines go (the shim's log; fixtures: stdout). Null: nowhere. + static void (*&env_log())(const char*) + { + static void (*sink)(const char*) = nullptr; + return sink; + } + +private: + bool read_title(u64 address, void* out, std::size_t bytes) const + { + return read_memory(env_, address, out, bytes); + } + SRWLOCK& lock_of(u32 index) { return locks_[index % 512]; } + + // Create the descriptor in this thread's staged slot (or in place), then copy it. + std::pair<D3D12_CPU_DESCRIPTOR_HANDLE, bool> make_place(u32 which) + { + if (const auto s = staged(env_.device, layout_.sampler, which)) return {*s, true}; + return {D3D12_CPU_DESCRIPTOR_HANDLE{0}, false}; + } + D3D12_CPU_DESCRIPTOR_HANDLE where(std::pair<D3D12_CPU_DESCRIPTOR_HANDLE, bool> place, u32 index) const + { + return place.second ? place.first : cpu(index); + } + void put(u32 index, std::pair<D3D12_CPU_DESCRIPTOR_HANDLE, bool> place) + { + if (!place.second) return; // made in place + gpu_view_trace::MirrorCall{env_.device, __FUNCTION__}.copy(1, cpu(index), place.first, + layout_.sampler ? D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER : D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + } + + // The body of mirror and make_at, under the slot's lock. + bool make_locked(u32 index, const View& v) + { + auto at = make_place(0); + at.first = where(at, index); + std::optional<D3D12_CPU_DESCRIPTOR_HANDLE> twin; + auto tw = make_place(1); + const bool twins = layout_.has_twin(index); + if (twins) { + tw.first = where(tw, layout_.twin(index)); + twin = tw.first; + } + const Made m = make_twinned(env_, exacts_, submits_, v, at.first, twin, tw.second, at.second); + if (!m.ok && !layout_.sampler) { + null_for(env_.device, v, at.first); + tally(c_null); + } + if (m.ok) tally(c_made); + if (m.ok || !layout_.sampler) put(index, at); + const bool twin_shown = m.ok && twinned(v) && twins; + if (twin_shown) put(layout_.twin(index), tw); + twin_made(index, twin_shown); + keep(index, m.ok ? m.kept : nullptr); + if (m.raw_bytes) raw_ranges_[index % 512][index] = {m.raw_start, m.raw_bytes}; + note_texture(index, m.ok && v.is_texture() && !v.depth_twins ? &v : nullptr); + return m.ok; + } + void make_null_locked(u32 index) + { + auto at = make_place(0); + at.first = where(at, index); + if (layout_.sampler) null_sampler(env_.device, at.first); + else null_view(env_.device, at.first); + put(index, at); + twin_made(index, false); + keep(index, nullptr); + note_texture(index, nullptr); + } + // A dynamic slot made by `make` (raw_at and its kin): bound by its handle, not read by index, so no twin. + template <class F> void made_by(u32 index, ID3D12Resource* kept, F&& make) + { + if (index >= layout_.size) return; + SRWLOCK& lock = lock_of(index); + AcquireSRWLockExclusive(&lock); + auto at = make_place(0); + at.first = where(at, index); + make(at.first); + put(index, at); + twin_made(index, false); + keep(index, kept); + ReleaseSRWLockExclusive(&lock); + } + // Copy the staged descriptor into the twin of slot `index`, or clear it to a null buffer view. + void twin_made(u32 index, bool made) + { + if (!layout_.has_twin(index)) return; + if (made) { + twin_shown_[index] = 1; + return; + } + if (twin_shown_[index]) { + twin_shown_[index] = 0; + auto at = make_place(1); + at.first = where(at, layout_.twin(index)); + null_buffer_view(env_.device, at.first); + put(layout_.twin(index), at); + } + } + // Slot `index` now views `resource` (one reference held); the old one is released some submits on (a running + // submission may still read it through the slot). + void keep(u32 index, ID3D12Resource* resource) + { + raw_ranges_[index % 512].erase(index); + if (index >= kept_.size()) return; + ID3D12Resource*& slot = kept_[index]; + if (slot == resource) return; + if (resource) resource->AddRef(); + ID3D12Resource* old = slot; + slot = resource; + if (old) { + std::lock_guard<std::mutex> lock(mutex_); + retired_.push_back({submits_, old}); + } + } + void retire(u64 at) + { + constexpr u64 keep_submits = 3; + std::vector<ID3D12Resource*> going; + { + std::lock_guard<std::mutex> lock(mutex_); + while (!retired_.empty() && retired_.front().first + keep_submits < at) { + going.push_back(retired_.front().second); + retired_.pop_front(); + } + } + for (auto* r : going) r->Release(); + } + // The table of strides, and the set of buffer slots. + void note_buffer(u32 index, const View* v) + { + if (layout_.sampler) return; + const auto e = v ? view_elements(*v) : std::nullopt; + if (stride_words_ && index < slot_strides_count) { + volatile std::uint32_t* w = stride_words_ + index; + *w = ::gpu_heap::stride_word(e); + } + std::lock_guard<std::mutex> lock(mutex_); + const bool was = e ? buffers_.put(index) || true : buffers_.remove(index); + if (was) changed_.put(index); + } + // PLAN.md 4b: a texture view made into a slot is due for upload. + void note_texture(u32 index, const View* v) + { + if (layout_.sampler) return; + std::lock_guard<std::mutex> lock(mutex_); + if (!v || !v->wrapper) { + textures_[index % textures_.size()].erase(index); + return; + } + textures_[index % textures_.size()][index] = Texture{v->wrapper, v->resource, v->placement, v->srv, v->key}; + queue_texture(index); + } + bool restore_pending(u32 index, View& v) + { + std::lock_guard<std::mutex> guard(mutex_); + const auto& group = textures_[index % textures_.size()]; + const auto it = group.find(index); + if (it == group.end() || it->second.placement != v.placement || !it->second.texture) return false; + v.retained = it->second.texture; + v.resource = v.retained.Get(); + v.wrapper = it->second.wrapper; + v.srv = it->second.srv; + v.key = it->second.view_key; + return true; + } + void queue_texture(u32 index) + { + if (due_set_.size() < layout_.count) due_set_.resize(layout_.count, 0); + if (index >= due_set_.size() || due_set_[index]) return; + due_set_[index] = 1; + due_.push_back(index); + tally(c_textures_due); + } + // A sixteenth of the slots that show a texture are due again at each submit: the title may have written its + // memory since (upload_texture uploads only what changed). + void sweep_textures(u64 at) + { + std::lock_guard<std::mutex> lock(mutex_); + for (const auto& [index, texture] : textures_[at % textures_.size()]) queue_texture(index); + } + + // The first `size` slots null: one null slot in a CPU-side heap, doubled to a block, the block copied over the + // heap; the twins null buffer views. + bool fill_null(D3D12_DESCRIPTOR_HEAP_TYPE kind) + { + constexpr u32 block = 1u << 16; + ID3D12DescriptorHeap* cpu_heap = nullptr; + D3D12_DESCRIPTOR_HEAP_DESC d{kind, block, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + if (FAILED(env_.device->CreateDescriptorHeap(&d, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&cpu_heap)))) return false; + const u64 start = cpu_heap->GetCPUDescriptorHandleForHeapStart().ptr; + const auto at = [&](u32 i) { return D3D12_CPU_DESCRIPTOR_HANDLE{static_cast<SIZE_T>(start + u64{i} * step_)}; }; + const u32 total = layout_.size; + const u32 ends[2] = {layout_.null_views_end(), total}; + u32 done = 0; + for (int twin = 0; twin < 2; ++twin) { + if (done >= ends[twin]) continue; + if (layout_.sampler) null_sampler(env_.device, at(0)); + else if (twin) null_buffer_view(env_.device, at(0)); + else null_view(env_.device, at(0)); + for (u32 filled = 1; filled < block;) { + const u32 n = (std::min)(filled, block - filled); + gpu_view_trace::MirrorCall{env_.device, __FUNCTION__}.copy(n, at(filled), at(0), kind); + filled += n; + } + while (done < ends[twin]) { + const u32 n = (std::min)(block, ends[twin] - done); + gpu_view_trace::MirrorCall{env_.device, __FUNCTION__}.copy(n, cpu(done), at(0), kind); + done += n; + } + } + cpu_heap->Release(); + return true; + } + + Env env_; + Layout layout_; + ID3D12DescriptorHeap* heap_ = nullptr; + u64 cpu_ = 0, gpu_ = 0; + u32 step_ = 0; + u64 title_cpu_ = 0; + u32 title_step_ = 32; + SRWLOCK locks_[512]; + std::unordered_map<u32, std::pair<u64, u64>> raw_ranges_[512]; + std::vector<u64> made_; // per title slot: the key of the record it was made from (0: none) + std::vector<std::uint8_t> twin_shown_; // per slot with a twin: the twin is not a null view + std::unordered_map<u32, u32> unmade_; // slots whose views could not be made: tries (mutex_) + std::set<u32> late_; // unmapped placed textures (mutex_) + u32 late_cursor_ = 0; + std::set<u32> lazy_, lazy_waiting_; + std::map<u32, MaterialRetry> material_due_, material_waiting_; + u32 material_cursor_ = 0; + u32 lazy_cursor_ = 0; + u64 lazy_generation_ = 0; + u64 lazy_frame_ = ~u64{0}; + std::vector<ID3D12Resource*> kept_; // per slot: what it views (one reference) + std::mutex mutex_; // runs_, retired_, buffers_, changed_, last_, textures_, due_ + DynamicRuns runs_; + std::deque<std::pair<u64, ID3D12Resource*>> retired_; + SlotSet buffers_, changed_; + std::vector<unsigned char> last_; // the records last seen of the title's heap + std::array<std::unordered_map<u32, Texture>, 16> textures_; + std::deque<u32> due_; + std::vector<std::uint8_t> due_set_; + Exacts exacts_; + ID3D12Resource* strides_ = nullptr; + std::uint32_t* stride_words_ = nullptr; + std::atomic<u64> submits_{0}; + LONGLONG submit_ticks_ = 0; +}; + +// Probe once per device for 2^22 views including twins, then 2^21 views, then 1,000,000. +inline Limits probe_view_limit(ID3D12Device* device, bool twins_wanted) +{ + return ::gpu_heap::probe_view_limit(twins_wanted, [device](u32 n) { + D3D12_DESCRIPTOR_HEAP_DESC d{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, n, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + ID3D12DescriptorHeap* heap = nullptr; + if (FAILED(device->CreateDescriptorHeap(&d, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&heap)))) return false; + heap->Release(); + return true; + }); +} + +} // namespace gpu_mirror diff --git a/src/startup_stubs/gpu_hooks.h b/src/startup_stubs/gpu_hooks.h new file mode 100644 index 0000000000..45e32c4f32 --- /dev/null +++ b/src/startup_stubs/gpu_hooks.h @@ -0,0 +1,163 @@ +// Hook declarations for translated shaders. Include after Wrapper inside the device shim's anonymous namespace. +// Shared types live in gpu_abi.h. Definitions follow the shim helpers so they can use desktop_range, +// upload_texture and desktop_format. +// +// Heap, descriptor, copy and list lifecycle hooks augment existing handlers. Copy passes, clears, barriers and +// queries may replace the bound heaps, root signature and PSO. Refresh these before the next draw or dispatch. +// Pipeline creation and draw, dispatch, mesh and indirect calls use exclusive handlers that count refusals. +// +// Different command lists record concurrently. Unless indicated, callers hold no shim lock. Wrapper state uses +// own().gpu[0] for pipelines, descriptor heaps or list bindings, and [1] for indirect list state. +// Last-reference release dispatches cleanup by object kind. +using x2w_gpu::GpuCreateDesc; +using x2w_gpu::GpuFound; +using x2w_gpu::GpuHeapInfo; +using x2w_gpu::GpuHostHeap; +using x2w_gpu::GpuPipeline; +using x2w_gpu::GpuRootKind; +using x2w_gpu::GpuTargets; +using x2w_gpu::GpuViewInfo; + +// ----- WP0 (gpu_hooks.inl) --------------------------------------------------------------------------------- +// The release of the last reference of any wrapper whose own().gpu[0] or [1] is set; forwards by kind to +// gpu_pipeline_released / gpu_heap_released / gpu_list_released. +void gpu_released(Wrapper* object); +// G0 / tests: a hook counter (x2w_gpu::GpuCounter). +long long gpu_count(int counter); + +// ----- +// WP2 vpipe (gpu_pipeline.inl) ------------------------------------------------------------------------- +// Device slots 10, 11, 62, 86 under ABI (EXCLUSIVE). `pipeline` is the placeholder wrapper WP0 already made and +// returns to the title with S_OK whatever this returns. Records the stages and an owned copy of the state; makes +// nothing (pipelines are made lazily). Returns false when nothing was kept. +bool gpu_create_pipeline(Wrapper* pipeline, const GpuCreateDesc& desc); +// At draw / dispatch / mesh / indirect (WP3, WP4): the made pipeline for the bound targets (null `targets`: the +// stream's own formats), made synchronously on first use; null while it cannot be made (the draw is dropped). +enum class GpuPsoStatus { unavailable, compiling, missing_shader, warm_bad, worker_failure, refused, count }; +struct GpuPsoDrop { + GpuPsoStatus status = GpuPsoStatus::unavailable; + const char* detail = ""; +}; +const GpuPipeline* gpu_pipeline_ready(Wrapper* pipeline, const GpuTargets* targets, GpuPsoDrop* drop = nullptr); +void gpu_pipeline_released(Wrapper* pipeline); + +// ----- WP5 rawtwins (gpu_heap.inl, gpu_views.inl) ------------------------------------------------------- +// Device slot 14 (ADDITIVE): after X2W made the desktop heap and its title memory. `heap` is the new wrapper (out), +// `title_cpu` the title descriptor memory (0 when none), `title_gpu` the GPU start handed to the title (0: not +// shader visible). Under ABI the title stride is abi::view_increment / sampler_increment for those types. +void gpu_heap_created(Wrapper* device, Wrapper* heap, const D3D12_DESCRIPTOR_HEAP_DESC& desc, std::uint64_t title_cpu, + std::uint64_t title_gpu); +void gpu_heap_released(Wrapper* heap); +// Device view slots (ADDITIVE, after X2W's view_slot / memory handlers and their X2WV token write; for 70/71 the title +// slot then holds X2W's X2WV token or the GFX10 V# words of write_buffer_descriptor, as without the switch). The raw title +// arguments as passed (wrapped pointers), by slot: +// 17 CBV (desc, dest) 18 SRV (resource, desc, dest) 19 UAV (resource, counter, desc, dest) +// 20 RTV (resource, desc, dest) 21 DSV (resource, desc, dest) 22 sampler (desc, dest) +// 61 console sampler (desc [27 words], dest) 70 placed SRV (resource desc, view desc+address, dest) +// 71 placed UAV (resource desc, view desc+address at +0x28, dest) +void gpu_heap_view(Wrapper* device, int slot, std::uint64_t a, std::uint64_t b, std::uint64_t c, std::uint64_t d); +// Device slots 24 and 23 (ADDITIVE, after X2W's desktop copies; title CPU handles). +void gpu_heap_copy_simple(Wrapper* device, UINT count, std::uint64_t dest, std::uint64_t src, D3D12_DESCRIPTOR_HEAP_TYPE type); +void gpu_heap_copy(Wrapper* device, UINT dest_count, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts, const UINT* dest_sizes, + UINT src_count, const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, const UINT* src_sizes, + D3D12_DESCRIPTOR_HEAP_TYPE type); +// Before each submission (called from gpu_list_submit): mirror the records the title byte-copied, upload changed +// texture slots (PLAN 4b). Runs with draw_lock and allocator_lock held. +void gpu_heap_submit(ID3D12CommandQueue* queue, UINT count, Wrapper* const* lists); +// Mirror heap operations used during shader binding. +bool gpu_heap_for(Wrapper* title_heap, GpuHeapInfo* out); // a heap the title set (slot 32) +bool gpu_heap_at(std::uint64_t title_gpu_handle, GpuHeapInfo* out); // the heap a handle lies in +bool gpu_heap_view_at(GpuHostHeap* heap, std::uint32_t index, GpuViewInfo* out); // the title's view there +u64 gpu_heap_title_address_at(GpuHostHeap* heap, std::uint32_t index); +ID3D12Resource* gpu_heap_kept_at(GpuHostHeap* heap, std::uint32_t index); +void gpu_material_slots(GpuHostHeap* heap, std::vector<x2w_material_trace::Slot>& slots); +x2w_material_trace::Record gpu_material_record(GpuHostHeap* heap, UINT slot, UINT base, x2w_material::Mask fields); +unsigned gpu_materialize(Wrapper* list, GpuHostHeap* heap, const x2w_material_trace::Words& words, x2w_material::Mask fields); +bool gpu_depth_barrier(Wrapper* list, Wrapper* resource); +bool gpu_heap_mirror(GpuHostHeap* heap, std::uint32_t index, std::uint64_t title_handle, bool for_draw, + GpuViewInfo* out); // make host slot `index` from the title slot +bool gpu_heap_dynamic(GpuHostHeap* heap, std::uint32_t n, std::uint32_t* first); +void gpu_heap_release(GpuHostHeap* heap, std::uint32_t first, std::uint32_t n); +bool gpu_heap_make_listed(GpuHostHeap* heap, std::uint32_t source, const std::uint32_t (&record)[8], std::uint32_t index, + GpuViewInfo* out); +void gpu_heap_make_null(GpuHostHeap* heap, std::uint32_t index); +void gpu_heap_raw_at(GpuHostHeap* heap, std::uint32_t index, ID3D12Resource* buffer, std::uint64_t offset, std::uint64_t bytes); +void gpu_heap_raw_uav_at(GpuHostHeap* heap, std::uint32_t index, ID3D12Resource* buffer, std::uint64_t offset, + std::uint64_t bytes); +void gpu_heap_null_raw_at(GpuHostHeap* heap, std::uint32_t index); +void gpu_heap_null_raw_uav_at(GpuHostHeap* heap, std::uint32_t index); +void gpu_heap_constant_at(GpuHostHeap* heap, std::uint32_t index, ID3D12Resource* buffer, std::uint64_t gpu, std::uint32_t bytes); +D3D12_GPU_DESCRIPTOR_HANDLE gpu_heap_gpu_handle(GpuHostHeap* heap, std::uint32_t index); +std::uint32_t gpu_heap_count(GpuHostHeap* heap); // title slots +ID3D12DescriptorHeap* gpu_heap_host(GpuHostHeap* heap); +std::uint64_t gpu_heap_strides_gpu(GpuHostHeap* heap); // the SLOT_STRIDES buffer's GPU address, 0: none +// Bindless textures (PLAN 4b): upload up to `max` textures WP5 has queued (made into mirror slots, or changed), with +// upload_texture on this open list, and move them to SRV | non-pixel SRV. Called by WP3 on the draw/dispatch path +// before the bind. False: nothing was due. +bool gpu_heap_upload_due(Wrapper* list, std::size_t max); + +// ----- WP3 vbind (gpu_bind.inl, gpu_find.h) ------------------------------------------------------------- +bool gpu_find(std::uint64_t address, std::uint64_t bytes, GpuFound* out); +// List setters 32-46 (EXCLUSIVE under ABI: X2W's handlers are not called, since they issue desktop root calls with +// the title's parameter indices; the parameter is unbounded). X2W's Pass root state is therefore stale under ABI. +void gpu_set_heaps(Wrapper* list, UINT count, void* const* heaps); // 32 +void gpu_roots_signature(Wrapper* list, bool compute, Wrapper* root); // 33 / 34 +void gpu_roots_table(Wrapper* list, bool compute, UINT parameter, std::uint64_t handle); // 35 / 36 +void gpu_roots_constants(Wrapper* list, bool compute, UINT parameter, UINT count, const std::uint32_t* data, + UINT offset); // 37 / 38 (count 1), 39 / 40 +void gpu_roots_view(Wrapper* list, bool compute, UINT parameter, std::uint64_t address, GpuRootKind kind); // 41-46 +// Non-root draw state (ADDITIVE, after X2W's handler; slots that X2W does not install are installed under ABI). +void gpu_topology(Wrapper* list, UINT topology); // 20 (console values) +void gpu_viewports(Wrapper* list, UINT count, const D3D12_VIEWPORT* viewports); // 21 +void gpu_scissors(Wrapper* list, UINT count, const D3D12_RECT* rects); // 22 +void gpu_blend_factor(Wrapper* list, const float* factor); // 23 +void gpu_stencil_ref(Wrapper* list, UINT ref); // 24 +void gpu_set_pipeline(Wrapper* list, Wrapper* pipeline); // 25 +void gpu_barriers(Wrapper* list, UINT count, const D3D12_RESOURCE_BARRIER* barriers); // 26 +void gpu_ia_index(Wrapper* list, const D3D12_INDEX_BUFFER_VIEW* view); // 47 +void gpu_ia_vertex(Wrapper* list, UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views); // 48 +void gpu_targets(Wrapper* list, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs, BOOL single, + const D3D12_CPU_DESCRIPTOR_HANDLE* dsv); // 50 (title handles) +void gpu_depth_bounds(Wrapper* list, float min, float max); // 70 (newer layout 68+2) +// Draws (EXCLUSIVE). `list` is recording(self) (null when the list is not open). +bool gpu_draw(Wrapper* self, ID3D12GraphicsCommandList* list, UINT vertices, UINT instances, UINT first_vertex, + UINT first_instance); // 12 +bool gpu_draw_indexed(Wrapper* self, ID3D12GraphicsCommandList* list, UINT count, UINT instances, UINT start, + INT base_vertex, UINT first_instance); // 13 +bool gpu_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z); // 14 +// The bind sequence without the issue, for WP4. False: the call would be dropped. +bool gpu_bind_draw(Wrapper* self, ID3D12GraphicsCommandList* list, bool indexed); +bool gpu_bind_mesh(Wrapper* self, ID3D12GraphicsCommandList* list); +bool gpu_bind_compute(Wrapper* self, ID3D12GraphicsCommandList* list); +// WP4's clamp pass set its own compute root and PSO: the next compute bind must set them again. +void gpu_bind_forget_compute(Wrapper* self); +// The made pipeline bound on the list (gpu_set_pipeline + gpu_pipeline_ready for the bound targets), or null; +// *title_topology = the console topology last set at slot 20 (17 = rectangles). +const GpuPipeline* gpu_bound_pipeline(Wrapper* self, UINT* title_topology, GpuPsoDrop* drop = nullptr); +// List lifecycle, WP3's part (dispatched from the gpu_list_* hooks below). +void gpu_bind_list_reset(Wrapper* list); +void gpu_bind_list_close(Wrapper* list); +void gpu_bind_submitted(ID3D12CommandQueue* queue, UINT count, Wrapper* const* lists); +void gpu_bind_first_submit(UINT count, Wrapper* const* lists); +void gpu_list_released(Wrapper* list); + +// ----- WP4 vindirect (gpu_indirect.inl) --------------------------------------------------------------------- +// List slot 61 ExecuteIndirect (EXCLUSIVE; with X2W_GPU_INDIRECT=0 WP0 drops it without calling). +bool gpu_indirect(Wrapper* self, ID3D12GraphicsCommandList* list, void* signature, UINT max_count, Wrapper* arguments, + std::uint64_t offset, Wrapper* count_resource, std::uint64_t count_offset); +// List slot 129 DispatchMesh(x, y, z) (newer layout 127+2; EXCLUSIVE; X2W_GPU_MESH=0: dropped by WP0). +bool gpu_mesh(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z); +// List slot 80 DispatchX(x, y, z, flags) (newer layout 78+2; EXCLUSIVE): flags & 0x20 = the counts are threads. +bool gpu_dispatch_x(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z, UINT flags); +void gpu_indirect_list_reset(Wrapper* list); +void gpu_indirect_list_close(Wrapper* list); // clears the per-list budget slot (a list may record without a reset) + +// ----- WP0 dispatchers (gpu_hooks.inl) ---------------------------------------------------------------------- +// List slot 139 Reset: after a successful reset (the desktop list is open). Calls bind then indirect reset. +void gpu_list_reset(Wrapper* list); +// List slot 9 Close: before X2W's close (the desktop list is still open). Calls bind then indirect close. +void gpu_list_close(Wrapper* list); +// Queue ExecuteCommandLists: before the desktop ExecuteCommandLists (heap submit), and after it (bind submitted). +// Both run with draw_lock and allocator_lock held. `lists` are the submitted (ready) wrappers. +void gpu_list_submit(ID3D12CommandQueue* queue, UINT count, Wrapper* const* lists); +void gpu_list_submitted(ID3D12CommandQueue* queue, UINT count, Wrapper* const* lists); diff --git a/src/startup_stubs/gpu_hooks.inl b/src/startup_stubs/gpu_hooks.inl new file mode 100644 index 0000000000..a0158a0f61 --- /dev/null +++ b/src/startup_stubs/gpu_hooks.inl @@ -0,0 +1,542 @@ +// Device and command-list hooks for translated shaders. gpu_install installs these handlers only when the ABI +// is enabled. +// +// Device slots 57 and 67 return E_NOTIMPL and a null output. Slot 15 reports descriptor increments of 32 for views +// and 16 for samplers. Slots 10, 11, 62 and 86 log stage keys when X2W_GPU_KEYLOG is set, record the pipeline, +// and return a placeholder with S_OK. Heap, view and copy hooks extend the shim handler. +// +// List setters 32–46 record heaps and roots. State setters augment the existing handler. Direct and indirect draws, +// mesh and dispatch calls use translated pipelines and count dropped work. Reset and close update the recording +// lifetime. + +namespace gpu_detail { + +volatile LONG64 counters[x2w_gpu::vc_count]; +const char* const counter_names[x2w_gpu::vc_count] = { + "pipelines", "pipelines kept", "keys", "refused 57", "refused 67", "heaps", "views", "copies", "setters", + "draws", "draws dropped", "dispatches", "dispatches dropped", "meshes", "meshes dropped", "indirects", + "indirects dropped", "mesh-x dropped", "resets", "closes", "submits"}; + +// Counts and, at 1, 2, 4, 8 ... (from 1024 on, every 1024th), logs one line with every counter: there is no exit hook +// and runs end by PID, so the log always holds a recent total. +void bump(int which) +{ + const LONG64 n = InterlockedIncrement64(&counters[which]); + if (which == x2w_gpu::vc_views || which == x2w_gpu::vc_copies || which == x2w_gpu::vc_setters) return; + if ((n & (n - 1)) != 0 && (n < 1024 || (n & 1023) != 0)) return; + char line[1024]; + int used = std::snprintf(line, sizeof(line), "x2w-gpu %s %lld:", counter_names[which], static_cast<long long>(n)); + for (int i = 0; i < x2w_gpu::vc_count && used > 0 && used < static_cast<int>(sizeof(line)); ++i) + used += std::snprintf(line + used, sizeof(line) - used, " %s=%lld%s", counter_names[i], + static_cast<long long>(counters[i]), i + 1 < x2w_gpu::vc_count ? "," : ""); + log("%s", line); +} + +// The G0 key log: one line per new (key, stage), written straight to the file (no buffering) so a killed run keeps it. +SRWLOCK key_lock = SRWLOCK_INIT; +std::unordered_set<std::uint64_t>& seen_keys() { static std::unordered_set<std::uint64_t> s; return s; } +HANDLE key_file() +{ + static const HANDLE file = [] { + char path[MAX_PATH]{}; + const DWORD n = GetEnvironmentVariableA("X2W_GPU_KEYLOG", path, sizeof(path)); + if (!n || n >= sizeof(path)) return INVALID_HANDLE_VALUE; + const HANDLE h = CreateFileA(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + log("x2w-gpu key log %s -> %s", path, h == INVALID_HANDLE_VALUE ? "NOT opened" : "opened"); + return h; + }(); + return file; +} + +// Keys `bytes` into `code` and logs a new (key, stage). False: the bytes cannot be read. +bool key_stage(int slot, x2w_gpu::GpuStage stage, const void* bytes, std::size_t size, x2w_gpu::GpuStageCode& code) +{ + code = {}; + code.stage = stage; + code.bytes = bytes; + code.size = size; + if (!bytes || !size || size > (64u << 20) || !x2w_local::readable(bytes, size)) return false; + x2w_gpu::gpu_key(bytes, size, code.key); + const std::uint64_t id = std::strtoull(code.key, nullptr, 16) * 9 + static_cast<std::uint64_t>(stage); + AcquireSRWLockExclusive(&key_lock); + const bool fresh = seen_keys().insert(id).second; + ReleaseSRWLockExclusive(&key_lock); + if (!fresh) return true; + char line[128]; + const int n = std::snprintf(line, sizeof(line), "%s %s slot%d %zu\r\n", code.key, x2w_gpu::gpu_stage_name(stage), + slot, size); + if (const HANDLE file = key_file(); file != INVALID_HANDLE_VALUE && n > 0) { + DWORD written = 0; + WriteFile(file, line, static_cast<DWORD>(n), &written, nullptr); + } + static LONG shown; + if (first_calls(shown, 8)) log("x2w-gpu key %s %s slot%d bytes %zu", code.key, x2w_gpu::gpu_stage_name(stage), slot, size); + bump(x2w_gpu::vc_keys); + return true; +} + +struct Bytecode { + const void* code; + std::size_t size; +}; + +// A stage at `at` (a D3D12_SHADER_BYTECODE in title memory) into the description. +void add_stage(GpuCreateDesc& desc, x2w_gpu::GpuStage stage, const void* at) +{ + Bytecode code{}; + if (!x2w_local::readable(at, sizeof(code))) { + desc.unreadable = true; + return; + } + std::memcpy(&code, at, sizeof(code)); + if (!code.code || !code.size) return; // the stage is absent + if (desc.stage_count >= 8) return; + if (!key_stage(desc.slot, stage, code.code, code.size, desc.stages[desc.stage_count])) desc.unreadable = true; + ++desc.stage_count; +} + +// A pipeline subobject's size (type included) and stage: the console numbers amplification and mesh 23 and 24. 0: +// unknown (the walk stops). +std::size_t subobject(std::uint32_t kind, int& stage) +{ + using S = x2w_gpu::GpuStage; + stage = -1; + switch (kind) { + case 1: stage = static_cast<int>(S::vertex); return 24; + case 2: stage = static_cast<int>(S::pixel); return 24; + case 3: stage = static_cast<int>(S::domain); return 24; + case 4: stage = static_cast<int>(S::hull); return 24; + case 5: stage = static_cast<int>(S::geometry); return 24; + case 6: stage = static_cast<int>(S::compute); return 24; + case 23: stage = static_cast<int>(S::amplification); return 24; + case 24: stage = static_cast<int>(S::mesh); return 24; + case 0: return 16; + case 12: case 19: return 24; + case 7: case 15: return 40; + case 8: return 336; + case 10: return 48; + case 11: return 56; + case 17: return 16; + case 21: return 64; + case 22: return 32; + case 9: case 13: case 14: case 16: case 18: case 20: return 8; + default: return 0; + } +} + +// Hands the stages to WP2 and returns the placeholder pipeline (S_OK) the title keeps. +HRESULT hand_out(GpuCreateDesc& desc, const GUID* iid, void** out) +{ + bump(x2w_gpu::vc_pipelines); + Wrapper* pipeline = wrap(nullptr, pipeline_kind); + *out = pipeline; + if (gpu_create_pipeline(pipeline, desc)) bump(x2w_gpu::vc_pipelines_kept); + (void)iid; + return S_OK; +} + +} // namespace gpu_detail + +long long gpu_count(int counter) +{ + return counter >= 0 && counter < x2w_gpu::vc_count ? static_cast<long long>(gpu_detail::counters[counter]) : -1; +} + +void gpu_released(Wrapper* object) +{ + switch (object->own().kind) { + case pipeline_kind: gpu_pipeline_released(object); break; + case descriptor_heap_kind: gpu_heap_released(object); break; + case resource_kind: { + if (builder_memory_on()) vbind::builder_arenas().forget(object); + std::lock_guard<std::mutex> guard(gpu_detail_heap::depth_lock); + gpu_detail_heap::depth_pairs().erase(object); + break; + } + case list_kind: gpu_list_released(object); break; + default: break; + } +} + +void gpu_list_reset(Wrapper* list) +{ + gpu_detail::bump(x2w_gpu::vc_resets); + gpu_bind_list_reset(list); + gpu_indirect_list_reset(list); +} +void gpu_list_close(Wrapper* list) +{ + gpu_detail::bump(x2w_gpu::vc_closes); + gpu_bind_list_close(list); + gpu_indirect_list_close(list); +} +void gpu_list_submit(ID3D12CommandQueue* queue, UINT count, Wrapper* const* lists) +{ + gpu_detail::bump(x2w_gpu::vc_submits); + gpu_bind_first_submit(count, lists); + gpu_heap_submit(queue, count, lists); +} +void gpu_list_submitted(ID3D12CommandQueue* queue, UINT count, Wrapper* const* lists) +{ + gpu_bind_submitted(queue, count, lists); +} + +// Device slots 10 and 11 take (head, riid, ppv). The graphics head contains the root signature, VS, PS, DS, HS and +// GS. The compute head used by slots 11 and 62 contains the root signature and CS. +template <int N> +HRESULT __stdcall gpu_create_pipeline_slot(Wrapper*, const void* head, const GUID* iid, void** out) +{ + Timed timed(time_pipeline); + if (!out || !iid) return E_POINTER; + *out = nullptr; + if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE; + if (!head) return E_INVALIDARG; + using S = x2w_gpu::GpuStage; + GpuCreateDesc desc{}; + desc.slot = N; + desc.desc = head; + desc.desc_bytes = sizeof(void*) + (N == 10 ? 5 : 1) * sizeof(gpu_detail::Bytecode); + if (!x2w_local::readable(head, desc.desc_bytes)) return E_INVALIDARG; + std::memcpy(&desc.title_root, head, sizeof(void*)); + const auto* stages = static_cast<const unsigned char*>(head) + sizeof(void*); + if constexpr (N == 10) { + const S order[] = {S::vertex, S::pixel, S::domain, S::hull, S::geometry}; + for (int i = 0; i < 5; ++i) gpu_detail::add_stage(desc, order[i], stages + i * sizeof(gpu_detail::Bytecode)); + } else { + gpu_detail::add_stage(desc, S::compute, stages); + } + return gpu_detail::hand_out(desc, iid, out); +} + +// Slot 62 takes the compute descriptor, extension count, extensions, riid and output pointer. Extensions are +// ignored. +HRESULT __stdcall gpu_create_compute_x_slot(Wrapper* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* head, u64, u64, + const GUID* iid, void** out) +{ + return gpu_create_pipeline_slot<62>(self, head, iid, out); +} + +// Slot 86: (stream desc {size, stream}, riid, ppv). +HRESULT __stdcall gpu_create_stream_slot(Wrapper*, const D3D12_PIPELINE_STATE_STREAM_DESC* stream, const GUID* iid, void** out) +{ + Timed timed(time_pipeline); + if (!out || !iid) return E_POINTER; + *out = nullptr; + if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE; + if (!stream || !x2w_local::readable(stream, sizeof(*stream)) || !stream->pPipelineStateSubobjectStream) return E_INVALIDARG; + GpuCreateDesc desc{}; + desc.slot = 86; + desc.desc = stream->pPipelineStateSubobjectStream; + desc.desc_bytes = stream->SizeInBytes; + const auto* bytes = static_cast<const unsigned char*>(stream->pPipelineStateSubobjectStream); + if (desc.desc_bytes > (1u << 20) || !x2w_local::readable(bytes, desc.desc_bytes)) { + desc.unreadable = true; + } else { + for (std::size_t at = 0; at + 8 <= desc.desc_bytes;) { + std::uint32_t kind; + std::memcpy(&kind, bytes + at, sizeof(kind)); + int stage; + const std::size_t size = gpu_detail::subobject(kind, stage); + if (!size || at + size > desc.desc_bytes) { + static LONG unknown; + if (size == 0 && first_calls(unknown, 4)) + log("x2w-gpu slot86: subobject %u of unknown size at +0x%zx; the rest is ignored", kind, at); + break; + } + if (kind == 0 && !desc.title_root) std::memcpy(&desc.title_root, bytes + at + 8, sizeof(void*)); + if (stage >= 0) gpu_detail::add_stage(desc, static_cast<x2w_gpu::GpuStage>(stage), bytes + at + 8); + at += size; + } + } + return gpu_detail::hand_out(desc, iid, out); +} + +// Slots 57 and 67: refused, out null. The title goes without the pipeline. +template <int N> +HRESULT __stdcall gpu_refuse_pipeline_slot(Wrapper*, const void* desc, const GUID*, void** out) +{ + if (out) *out = nullptr; + gpu_detail::bump(N == 57 ? x2w_gpu::vc_refused_57 : x2w_gpu::vc_refused_67); + static LONG shown; + if (first_calls(shown, 2)) { + char bytes[3 * 64 + 1]; + hex_text(desc, 64, bytes, sizeof(bytes)); + log("x2w-gpu Device::slot%d refused (E_NOTIMPL) desc=[%s]", N, bytes); + } + return E_NOTIMPL; +} + +// Slot 15: the console's increments for views and samplers. +static_assert(x2w_startup::title_sampler_stride == x2w_gpu::abi::sampler_increment); +UINT __stdcall gpu_increment_slot(Wrapper* self, UINT type) +{ + if (type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) return x2w_gpu::abi::view_increment; + if (type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) return x2w_gpu::abi::sampler_increment; + return device_descriptor_increment_size(self, type); +} + +// Slot 14: X2W's heap (with title_stride 32 / 16 under ABI, device_create_descriptor_heap), then WP5. +HRESULT __stdcall gpu_heap_slot(Wrapper* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc, const GUID* iid, void** out) +{ + const HRESULT hr = device_create_descriptor_heap(self, desc, iid, out); + if (FAILED(hr) || !out || !*out) return hr; + Wrapper* heap = static_cast<Wrapper*>(*out); + const u64 gpu = (desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && heap->own().real + ? static_cast<ID3D12DescriptorHeap*>(heap->own().real)->GetGPUDescriptorHandleForHeapStart().ptr : 0; + gpu_detail::bump(x2w_gpu::vc_heaps); + gpu_heap_created(self, heap, *desc, heap->own().title_cpu, gpu); + return hr; +} + +// View slots 17-22: X2W's view_slot (token write, desktop view), then WP5. +template <int N, int D> +u64 gpu_view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) +{ + const u64 result = view_slot<N, D>(self, a, b, c, d); + gpu_detail::bump(x2w_gpu::vc_views); + gpu_heap_view(self, N, a, b, c, d); + return result; +} +// Slot 61, the console sampler (desc, dest): X2W has no handler (a no-op, or the census). +u64 __stdcall gpu_sampler_x_slot(Wrapper* self, u64 desc, u64 dest, u64 r9) +{ + if (texture_census_on()) device_slot61_census(self, desc, dest, r9); + gpu_detail::bump(x2w_gpu::vc_views); + gpu_heap_view(self, 61, desc, dest, 0, 0); + return 0; +} +// Slots 70 and 71, the placed SRV / UAV (resource desc, view desc + address, dest). +void __stdcall gpu_placed_srv_slot(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, + u64 destination) +{ + device_memory_srv(self, resource, input, destination); + gpu_detail::bump(x2w_gpu::vc_views); + gpu_heap_view(self, 70, reinterpret_cast<u64>(resource), reinterpret_cast<u64>(input), destination, 0); +} +void __stdcall gpu_placed_uav_slot(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const MemoryUnorderedAccessView* input, + u64 destination) +{ + if (memory_srv_buffer_on()) device_memory_uav(self, resource, input, destination); + gpu_detail::bump(x2w_gpu::vc_views); + gpu_heap_view(self, 71, reinterpret_cast<u64>(resource), reinterpret_cast<u64>(input), destination, 0); +} +// Copy slots 24 and 23. +void __stdcall gpu_copy_simple_slot(Wrapper* self, UINT count, u64 dest, u64 src, D3D12_DESCRIPTOR_HEAP_TYPE type) +{ + device_copy_descriptors_simple(self, count, dest, src, type); + gpu_detail::bump(x2w_gpu::vc_copies); + gpu_heap_copy_simple(self, count, dest, src, type); +} +void __stdcall gpu_copy_slot(Wrapper* self, UINT dest_count, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts, const UINT* dest_sizes, + UINT src_count, const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, const UINT* src_sizes, + D3D12_DESCRIPTOR_HEAP_TYPE type) +{ + device_copy_descriptors(self, dest_count, dest_starts, dest_sizes, src_count, src_starts, src_sizes, type); + gpu_detail::bump(x2w_gpu::vc_copies); + gpu_heap_copy(self, dest_count, dest_starts, dest_sizes, src_count, src_starts, src_sizes, type); +} + +// ----- List slots (entered through noop_slot -> list_typed) ------------------------------------------------------ +namespace gpu_detail { +ListTyped vh_old_typed[slot_count]; // list_typed as X2W installed it, before gpu_install +inline Wrapper* vh_w(u64 v) { return reinterpret_cast<Wrapper*>(v); } +inline u64 vh_old(int slot, u64 a, u64 b, u64 c, u64 d, u64 e, u64 f, u64 g, u64 h) +{ + return vh_old_typed[slot] ? vh_old_typed[slot](a, b, c, d, e, f, g, h) : 0; +} +#define X2W_GPU_ARGS u64 self, u64 a1, u64 a2, u64 a3, u64 s0, u64 s1, u64 s2, u64 s3 +#define X2W_GPU_OLD(slot) vh_old(slot, self, a1, a2, a3, s0, s1, s2, s3) + +// Root setters 32-46: the hook only. X2W's handlers would issue desktop root calls (list_graphics_root's +// SetGraphicsRootSignature, list_root_srv's SetGraphicsRootShaderResourceView, the *_desktop compute variants) with the +// title's parameter indices onto the list WP3 binds with its own host roots, so under ABI they are not called. +template <int N> +u64 __stdcall vh_setter(X2W_GPU_ARGS) +{ + bump(x2w_gpu::vc_setters); + Wrapper* list = vh_w(self); + const UINT p = static_cast<UINT>(a1); + switch (N) { + case 32: gpu_set_heaps(list, static_cast<UINT>(a1), reinterpret_cast<void* const*>(a2)); break; + case 33: case 34: gpu_roots_signature(list, N == 33, as_wrapper(reinterpret_cast<const void*>(a1))); break; + case 35: case 36: gpu_roots_table(list, N == 35, p, a2); break; + case 37: case 38: { // (parameter, value, offset) + const std::uint32_t value = static_cast<std::uint32_t>(a2); + gpu_roots_constants(list, N == 37, p, 1, &value, static_cast<UINT>(a3)); + break; + } + case 39: case 40: // (parameter, count, data, offset) + gpu_roots_constants(list, N == 39, p, static_cast<UINT>(a2), reinterpret_cast<const std::uint32_t*>(a3), + static_cast<UINT>(s0)); + break; + case 41: case 42: gpu_roots_view(list, N == 41, p, a2, GpuRootKind::cbv); break; + case 43: case 44: gpu_roots_view(list, N == 43, p, a2, GpuRootKind::srv); break; + case 45: case 46: gpu_roots_view(list, N == 45, p, a2, GpuRootKind::uav); break; + default: break; + } + (void)s1, (void)s2, (void)s3; + return 0; +} + +// Other draw state: X2W's handler first, then the hook. +template <int N> +u64 __stdcall vh_state(X2W_GPU_ARGS) +{ + const u64 result = X2W_GPU_OLD(N); + Wrapper* list = vh_w(self); + switch (N) { + case 20: gpu_topology(list, static_cast<UINT>(a1)); break; + case 21: gpu_viewports(list, static_cast<UINT>(a1), reinterpret_cast<const D3D12_VIEWPORT*>(a2)); break; + case 22: gpu_scissors(list, static_cast<UINT>(a1), reinterpret_cast<const D3D12_RECT*>(a2)); break; + case 23: gpu_blend_factor(list, reinterpret_cast<const float*>(a1)); break; + case 24: gpu_stencil_ref(list, static_cast<UINT>(a1)); break; + case 25: gpu_set_pipeline(list, as_wrapper(reinterpret_cast<const void*>(a1))); break; + case 26: gpu_barriers(list, static_cast<UINT>(a1), reinterpret_cast<const D3D12_RESOURCE_BARRIER*>(a2)); break; + case 47: gpu_ia_index(list, reinterpret_cast<const D3D12_INDEX_BUFFER_VIEW*>(a1)); break; + case 48: gpu_ia_vertex(list, static_cast<UINT>(a1), static_cast<UINT>(a2), reinterpret_cast<const D3D12_VERTEX_BUFFER_VIEW*>(a3)); break; + case 50: + gpu_targets(list, static_cast<UINT>(a1), reinterpret_cast<const D3D12_CPU_DESCRIPTOR_HANDLE*>(a2), static_cast<BOOL>(a3 & 0xff), + reinterpret_cast<const D3D12_CPU_DESCRIPTOR_HANDLE*>(s0)); + break; + default: break; + } + return result; +} + +void vh_counted(bool issued, int done, int dropped) { bump(issued ? done : dropped); } + +// Draws and dispatches: only the translated shader path. +u64 __stdcall vh_draw(X2W_GPU_ARGS) +{ + (void)s1, (void)s2, (void)s3; + Wrapper* s = vh_w(self); + vh_counted(gpu_draw(s, recording(s), static_cast<UINT>(a1), static_cast<UINT>(a2), static_cast<UINT>(a3), static_cast<UINT>(s0)), + x2w_gpu::vc_draws, x2w_gpu::vc_draws_dropped); + return 0; +} +u64 __stdcall vh_draw_indexed(X2W_GPU_ARGS) +{ + (void)s2, (void)s3; + Wrapper* s = vh_w(self); + vh_counted(gpu_draw_indexed(s, recording(s), static_cast<UINT>(a1), static_cast<UINT>(a2), static_cast<UINT>(a3), + static_cast<INT>(static_cast<UINT>(s0)), static_cast<UINT>(s1)), + x2w_gpu::vc_draws, x2w_gpu::vc_draws_dropped); + return 0; +} +u64 __stdcall vh_dispatch(X2W_GPU_ARGS) +{ + (void)s0, (void)s1, (void)s2, (void)s3; + Wrapper* s = vh_w(self); + vh_counted(gpu_dispatch(s, recording(s), static_cast<UINT>(a1), static_cast<UINT>(a2), static_cast<UINT>(a3)), + x2w_gpu::vc_dispatches, x2w_gpu::vc_dispatches_dropped); + return 0; +} +u64 __stdcall vh_dispatch_x(X2W_GPU_ARGS) // slot 80: (x, y, z, flags) +{ + (void)s1, (void)s2, (void)s3; + Wrapper* s = vh_w(self); + vh_counted(gpu_dispatch_x(s, recording(s), static_cast<UINT>(a1), static_cast<UINT>(a2), static_cast<UINT>(a3), static_cast<UINT>(s0)), + x2w_gpu::vc_dispatches, x2w_gpu::vc_dispatches_dropped); + return 0; +} +u64 __stdcall vh_mesh(X2W_GPU_ARGS) // slot 129: (x, y, z) +{ + (void)s0, (void)s1, (void)s2, (void)s3; + Wrapper* s = vh_w(self); + const bool issued = x2w_gpu::gpu_mesh_on() && + gpu_mesh(s, recording(s), static_cast<UINT>(a1), static_cast<UINT>(a2), static_cast<UINT>(a3)); + vh_counted(issued, x2w_gpu::vc_meshes, x2w_gpu::vc_meshes_dropped); + return 0; +} +u64 __stdcall vh_mesh_x(X2W_GPU_ARGS) // slot 100: DispatchMeshX(x, flags, indirect arguments, payload), dropped +{ + (void)self, (void)a1, (void)a2, (void)a3, (void)s0, (void)s1, (void)s2, (void)s3; + bump(x2w_gpu::vc_mesh_x_dropped); + return 0; +} +u64 __stdcall vh_indirect(X2W_GPU_ARGS) // slot 61: (signature, max count, arguments, offset, count, count offset) +{ + (void)s3; + Wrapper* s = vh_w(self); + const bool issued = x2w_gpu::gpu_indirect_on() && + gpu_indirect(s, recording(s), reinterpret_cast<void*>(a1), static_cast<UINT>(a2), vh_w(a3), s0, vh_w(s1), s2); + vh_counted(issued, x2w_gpu::vc_indirects, x2w_gpu::vc_indirects_dropped); + return 0; +} +// List reset (139) and close (9). +u64 __stdcall vh_reset(X2W_GPU_ARGS) +{ + const u64 result = X2W_GPU_OLD(139); + if (SUCCEEDED(static_cast<HRESULT>(result))) gpu_list_reset(vh_w(self)); + return result; +} +u64 __stdcall vh_close(X2W_GPU_ARGS) +{ + gpu_list_close(vh_w(self)); + return X2W_GPU_OLD(9); +} +#undef X2W_GPU_OLD +#undef X2W_GPU_ARGS + +// Slot 70, depth bounds (min, max): float arguments, so the table entry itself (noop_slot passes integer registers). +void __stdcall vh_depth_bounds(Wrapper* self, float min, float max) { gpu_depth_bounds(self, min, max); } + +template <int... N> +void vh_install_setters(std::integer_sequence<int, N...>) +{ + ((list_typed[N] = reinterpret_cast<ListTyped>(&vh_setter<N>)), ...); +} +template <int... N> +void vh_install_state(std::integer_sequence<int, N...>) +{ + ((list_typed[N] = reinterpret_cast<ListTyped>(&vh_state<N>)), ...); +} +} // namespace gpu_detail + +// Called by build_tables when gpu_abi_on(), after X2W's own entries are in. +void gpu_install() +{ + using namespace gpu_detail; + void** device = tables[device_kind]; + device[10] = reinterpret_cast<void*>(&gpu_create_pipeline_slot<10>); + device[11] = reinterpret_cast<void*>(&gpu_create_pipeline_slot<11>); + device[62] = reinterpret_cast<void*>(&gpu_create_compute_x_slot); + device[86] = reinterpret_cast<void*>(&gpu_create_stream_slot); + device[57] = reinterpret_cast<void*>(&gpu_refuse_pipeline_slot<57>); + device[67] = reinterpret_cast<void*>(&gpu_refuse_pipeline_slot<67>); + device[15] = reinterpret_cast<void*>(&gpu_increment_slot); + device[14] = reinterpret_cast<void*>(&gpu_heap_slot); + device[17] = reinterpret_cast<void*>(&gpu_view_slot<17, 1>); + device[18] = reinterpret_cast<void*>(&gpu_view_slot<18, 2>); + device[19] = reinterpret_cast<void*>(&gpu_view_slot<19, 3>); + device[20] = reinterpret_cast<void*>(&gpu_view_slot<20, 2>); + device[21] = reinterpret_cast<void*>(&gpu_view_slot<21, 2>); + device[22] = reinterpret_cast<void*>(&gpu_view_slot<22, 1>); + device[23] = reinterpret_cast<void*>(&gpu_copy_slot); + device[24] = reinterpret_cast<void*>(&gpu_copy_simple_slot); + device[61] = reinterpret_cast<void*>(&gpu_sampler_x_slot); + device[70] = reinterpret_cast<void*>(&gpu_placed_srv_slot); + device[71] = reinterpret_cast<void*>(&gpu_placed_uav_slot); + + std::copy(std::begin(list_typed), std::end(list_typed), std::begin(vh_old_typed)); + vh_install_setters(std::integer_sequence<int, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46>{}); + vh_install_state(std::integer_sequence<int, 20, 21, 22, 23, 24, 25, 26, 47, 48, 50>{}); + list_typed[12] = reinterpret_cast<ListTyped>(&vh_draw); + list_typed[13] = reinterpret_cast<ListTyped>(&vh_draw_indexed); + list_typed[14] = reinterpret_cast<ListTyped>(&vh_dispatch); + list_typed[x2w_list_slots::execute_indirect_slot] = reinterpret_cast<ListTyped>(&vh_indirect); + // Newer list layouts shift slots by two starting at slot 59. DispatchX uses 80, DispatchMeshX uses 100 and + // DispatchMesh uses 129. + list_typed[80] = reinterpret_cast<ListTyped>(&vh_dispatch_x); + list_typed[100] = reinterpret_cast<ListTyped>(&vh_mesh_x); + list_typed[129] = reinterpret_cast<ListTyped>(&vh_mesh); + if (vh_old_typed[x2w_list_slots::reset_slot]) list_typed[x2w_list_slots::reset_slot] = reinterpret_cast<ListTyped>(&vh_reset); + if (vh_old_typed[9]) list_typed[9] = reinterpret_cast<ListTyped>(&vh_close); + if (list_noop()) tables[list_kind][70] = reinterpret_cast<void*>(&vh_depth_bounds); + log("x2w-gpu ABI on: slots 57/67 refused, slot 15 answers %u/%u, slots 10/11/62/86 keyed%s; indirect %s, mesh %s, twins %s", + x2w_gpu::abi::view_increment, x2w_gpu::abi::sampler_increment, + key_file() != INVALID_HANDLE_VALUE ? " (key log open)" : " (no X2W_GPU_KEYLOG)", + x2w_gpu::gpu_indirect_on() ? "on" : "off", x2w_gpu::gpu_mesh_on() ? "on" : "off", + x2w_gpu::gpu_twins_on() ? "on" : "off"); +} diff --git a/src/startup_stubs/gpu_indirect.inl b/src/startup_stubs/gpu_indirect.inl new file mode 100644 index 0000000000..bc83ce05fb --- /dev/null +++ b/src/startup_stubs/gpu_indirect.inl @@ -0,0 +1,434 @@ +// Indirect draws, mesh dispatch and DispatchX. Device slot 41 records signatures. ExecuteIndirect accepts a single +// draw, indexed draw, dispatch, mesh dispatch or console single-pass dispatch (0x69). Root-changing signatures and +// calls incompatible with the bound pipeline are dropped. Indirect rectangles can use their first triangle when +// there are no per-vertex inputs. +// +// The GPU clamps title records and counts into the indirect ring. Each list has a budget of 2^27 in a 32-byte pool +// slot, cleared at its first clamp after creation or reset. The effective count follows the records. The binder +// restores the compute root and PSO after the clamp, then issues the host command signature. DispatchMesh uses +// min(x,65535) groups in one dimension. For DispatchX, flag 0x20 supplies thread counts and USER_DISPATCH_THREADS_X +// preserves the original x count. +// +// X2W_GPU_INDIRECT=0 drops indirect calls. X2W_GPU_MESH=0 drops mesh dispatches. +// X2W_GPU_INDIRECT_WIDE=0 limits AMD dispatches to 65,535 groups in x. X2W_GPU_INDIRECT_REST=0 drops a +// record that exceeds the remaining budget. X2W_GPU_THREAD_DIMENSIONS=0 treats counts as groups. +// X2W_GPU_INDIRECT_NOTES=1 enables CPU-visible budget diagnostics. + +namespace vi = x2w_gpu_indirect; + +// WP3's gpu_bound_pipeline (the made pipeline bound on the list) is declared in gpu_hooks.h, defined in +// gpu_bind.inl. + +// ---- counters, logged every 300 frames ------------------------------------------------------------------------- +enum GpuIndirectKindIndex { vik_draw, vik_indexed, vik_dispatch, vik_mesh, vik_other, vik_kinds }; +constexpr const char* gpu_indirect_kind_names[vik_kinds] = {"draw", "indexed", "dispatch", "mesh", "other"}; +int gpu_indirect_kind_index(UINT kind) +{ + return kind == vi::kind_draw ? vik_draw : kind == vi::kind_indexed ? vik_indexed : kind == vi::kind_dispatch ? vik_dispatch + : kind == vi::kind_mesh ? vik_mesh : vik_other; +} +enum GpuIndirectDrop { + vid_not_recording, + vid_signature, // unknown signature, not exactly one argument of a kind the host takes, or no host signature + vid_mesh_off, // X2W_GPU_MESH=0 + vid_pipeline, // No translated pipeline bound, one of another kind, or rectangles it cannot draw + vid_buffer, // records or count not found in title memory, or a layout the clamp refuses + vid_scratch, // no ring chunk for the clamped records + vid_clamp, // the clamp or the budget pool could not be made + vid_bind, // WP3 refused to bind the draw state + vid_reasons +}; +constexpr const char* gpu_indirect_drop_names[vid_reasons] = {"not-recording", "signature", "mesh-off", "pipeline", + "buffer", "scratch", "clamp", "bind"}; +struct GpuIndirectCounts { + LONG calls[vik_kinds]; + LONG executed[vik_kinds]; + LONG dropped[vid_reasons][vik_kinds]; + LONG console_single; // calls of signatures of type 0x69 + LONG counted; // calls with a count buffer + LONG rect_triangles; // indirect rectangles drawn as their first triangle + LONG mesh, mesh_dropped, mesh_cut, mesh_yz; // direct DispatchMesh: calls, dropped, x > 65,535, y * z != 1 + LONG dispatch_x, dispatch_x_threads, dispatch_x_dropped; +}; +GpuIndirectCounts gpu_indirect_counts; +bool gpu_indirect_drop(int kind, GpuIndirectDrop why) +{ + InterlockedIncrement(&gpu_indirect_counts.dropped[why][kind]); + return false; // dropped: WP0 counts it and the old path does not run +} +bool gpu_indirect_env_zero(const char* name) { return x2w_gpu::gpu_env_is(name, '0'); } + +// ---- the clamp, the host signatures, the budget pool ------------------------------------------------------------- +vi::Clamp gpu_clamp; +vi::HostSignatures gpu_host_signatures; +// The budget pool: a list takes the next slot at its first clamp since its creation or reset. A slot is used again only +// after gpu_budget_slots more recordings, far longer than any list stays in flight. +constexpr std::uint32_t gpu_budget_slots = 1u << 16; +ID3D12Resource* gpu_budget_pool; +ID3D12Resource* gpu_budget_zeros; // upload heap, 256 zero bytes +const volatile std::uint32_t* gpu_budget_words; // the mapped pool (X2W_GPU_INDIRECT_NOTES=1), or null +volatile LONG gpu_budget_next; + +bool gpu_indirect_ready() +{ + static SRWLOCK lock = SRWLOCK_INIT; + static bool failed; + if (gpu_budget_pool) return true; + AcquireSRWLockExclusive(&lock); + if (!gpu_budget_pool && !failed) { + ID3D12Device* device = device_of(the_device); + const bool amd = vi::is_amd(device); + const bool wide = !gpu_indirect_env_zero("X2W_GPU_INDIRECT_WIDE"); + const bool rest = !gpu_indirect_env_zero("X2W_GPU_INDIRECT_REST"); + const bool notes = x2w_gpu::gpu_env_is("X2W_GPU_INDIRECT_NOTES", '1'); + std::string errors; + vi::Clamp clamp; + HRESULT hr = vi::make_clamp(device, vi::clamp_text(vi::widest(amd, wide), rest), &clamp, &errors); + if (FAILED(hr)) log("x2w-gpu indirect: argument clamp refused 0x%08lx: %.400s", static_cast<unsigned long>(hr), errors.c_str()); + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = u64{gpu_budget_slots} * vi::budget_slot_bytes; + 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; + ID3D12Resource* pool = nullptr; + void* mapped = nullptr; + if (SUCCEEDED(hr) && notes) { + const D3D12_HEAP_PROPERTIES visible{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0}; + if (FAILED(device->CreateCommittedResource(&visible, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&pool))) || + FAILED(pool->Map(0, nullptr, &mapped))) { + if (pool) pool->Release(); + pool = nullptr; + mapped = nullptr; + } + } + if (SUCCEEDED(hr) && !pool) { + const D3D12_HEAP_PROPERTIES local{D3D12_HEAP_TYPE_DEFAULT}; + hr = device->CreateCommittedResource(&local, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&pool)); + } + ID3D12Resource* zeros = nullptr; + if (SUCCEEDED(hr)) { + const D3D12_HEAP_PROPERTIES upload{D3D12_HEAP_TYPE_UPLOAD}; + buffer.Width = 256; + buffer.Flags = D3D12_RESOURCE_FLAG_NONE; + hr = device->CreateCommittedResource(&upload, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&zeros)); + void* z = nullptr; + if (SUCCEEDED(hr)) hr = zeros->Map(0, nullptr, &z); + if (SUCCEEDED(hr)) { + std::memset(z, 0, 256); + zeros->Unmap(0, nullptr); + } + } + log("x2w-gpu indirect: argument clamp %s (widest %u groups in x, %s card, rest %s), budget pool %u slots %s -> 0x%08lx", + clamp.pso ? "made" : "REFUSED", vi::widest(amd, wide), amd ? "an AMD" : "a non-AMD", rest ? "on" : "off", gpu_budget_slots, + mapped ? "CPU-visible (notes)" : "device local", static_cast<unsigned long>(hr)); + if (SUCCEEDED(hr) && clamp.pso && pool && zeros) { + gpu_clamp = clamp; + gpu_budget_zeros = zeros; + gpu_budget_words = static_cast<const volatile std::uint32_t*>(mapped); + MemoryBarrier(); + gpu_budget_pool = pool; + } else { + if (pool) pool->Release(); + if (zeros) zeros->Release(); + clamp.release(); + failed = true; + } + } + ReleaseSRWLockExclusive(&lock); + return gpu_budget_pool != nullptr; +} + +// Per list (own().gpu[1], WP4's): 0 = no budget slot since the creation or reset, else the slot + 1. +std::uintptr_t& gpu_indirect_list_word(Wrapper* list) { return reinterpret_cast<std::uintptr_t&>(list->own().gpu[1]); } + +// List reset: the list's next recording takes a fresh budget slot, zeroed at its first clamp. A new list starts at 0 +// (own().gpu is zero at creation, and wrapper memory is never reused). +void gpu_indirect_list_reset(Wrapper* list) +{ + if (list) gpu_indirect_list_word(list) = 0; +} + +// List close (gpu_hooks.h, vhooks fe1f8bd31): a list may record again without a reset, so its next recording +// also takes a fresh budget slot. +void gpu_indirect_list_close(Wrapper* list) +{ + if (list) gpu_indirect_list_word(list) = 0; +} + +// The GPU address of the list's budget slot; records the slot's zeroing at the list's first clamp since its reset. +// One thread records one list at a time, so own().gpu[1] needs no lock. +u64 gpu_indirect_budget(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + std::uintptr_t& word = gpu_indirect_list_word(self); + if (!word) { + const std::uint32_t slot = static_cast<std::uint32_t>(InterlockedIncrement(&gpu_budget_next)) % gpu_budget_slots; + vi::record_budget_zero(list, gpu_budget_pool, u64{slot} * vi::budget_slot_bytes, gpu_budget_zeros); + word = std::uintptr_t{slot} + 1; + } + return gpu_budget_pool->GetGPUVirtualAddress() + u64{static_cast<std::uint32_t>(word - 1)} * vi::budget_slot_bytes; +} + +// The title records of a buffer wrapper at [offset, offset + bytes), in place. +bool gpu_indirect_records(Wrapper* resource, u64 offset, u64 bytes, ID3D12Resource** window, u64* at) +{ + if (!resource || resource->own().kind != resource_kind || !resource->own().title_memory) return false; + GpuFound found; + if (!gpu_find(reinterpret_cast<u64>(resource->own().title_memory) + offset, bytes, &found) || !found.resource || + found.bytes_left < bytes) + return false; + *window = found.resource; + *at = found.offset; + return true; +} + +void gpu_indirect_report(); + +// ---- ExecuteIndirect (list slot 61) ------------------------------------------------------------------------------ +bool gpu_indirect(Wrapper* self, ID3D12GraphicsCommandList* list, void* signature, UINT max_count, Wrapper* arguments, + std::uint64_t offset, Wrapper* count_resource, std::uint64_t count_offset) +{ + gpu_indirect_report(); + // The signature: its stride and argument types (device slot 41 keeps them, the console's 0x69 included). + UINT stride = 0; + std::uint32_t types[2] = {~0u, ~0u}; + std::size_t argument_count = 0; + AcquireSRWLockShared(&signature_lock); + const auto found = signature_infos().find(signature); + if (found != signature_infos().end()) { + stride = found->second.stride; + argument_count = found->second.args.size(); + for (std::size_t i = 0; i < argument_count && i < 2; ++i) types[i] = static_cast<std::uint32_t>(found->second.args[i].Type); + } + ReleaseSRWLockShared(&signature_lock); + std::uint32_t kind = ~0u; + const bool runs = vi::signature_kind(types, argument_count, &kind); + const int k = runs ? gpu_indirect_kind_index(kind) : vik_other; + InterlockedIncrement(&gpu_indirect_counts.calls[k]); + if (argument_count == 1 && types[0] == vi::console_single_dispatch) InterlockedIncrement(&gpu_indirect_counts.console_single); + if (count_resource) InterlockedIncrement(&gpu_indirect_counts.counted); + if (!list) return gpu_indirect_drop(k, vid_not_recording); + if (!runs) { + static LONG told; + if (first_calls(told, 8)) + log("x2w-gpu indirect: signature %p dropped (%zu arguments, first type %u, stride %u)", signature, argument_count, + types[0], stride); + return gpu_indirect_drop(k, vid_signature); + } + if (kind == vi::kind_mesh && !x2w_gpu::gpu_mesh_on()) return gpu_indirect_drop(k, vid_mesh_off); + if (!max_count) return true; // nothing to run (D3D12 runs no record either) + // The pipeline must be of the kind. + UINT topology = 0; + GpuPsoDrop failure; + const GpuPipeline* p = gpu_bound_pipeline(self, &topology, gpu_drop_trace() ? &failure : nullptr); + if (!p) { + if (gpu_drop_trace()) { + const auto* s = vbind::state_if(self); + vbind::sample_drop(self, s ? static_cast<Wrapper*>(s->pipeline) : nullptr, vbind::Call::indirect, + failure, vbind::drop_no_pipeline); + } + return gpu_indirect_drop(k, vid_pipeline); + } + constexpr UINT rectangles = 17; // The console's rectangle list + const bool rect = topology == rectangles; + bool per_vertex_inputs = false; + for (const auto& e : p->inputs) per_vertex_inputs |= !e.per_instance; + const bool rect_triangles = !p->rects && kind == vi::kind_draw && rect && !per_vertex_inputs; + bool matches = false; + if (kind == vi::kind_draw || kind == vi::kind_indexed) matches = (!rect || rect_triangles || p->rects) && !p->compute && !p->mesh; + else if (kind == vi::kind_mesh) matches = !p->compute && p->mesh; + else matches = p->compute; + if (!matches) return gpu_indirect_drop(k, vid_pipeline); + if (rect_triangles) { + static LONG told; + if (first_calls(told, 1)) log("x2w-gpu indirect: rectangles without vertex inputs drawn as their first triangle"); + InterlockedIncrement(&gpu_indirect_counts.rect_triangles); + } + // The records and the count, in title memory. + const u64 bytes = u64{stride} * max_count; + ID3D12Resource* args_window = nullptr; + ID3D12Resource* count_window = nullptr; + u64 args_at = 0, count_at = 0; + if (!gpu_indirect_records(arguments, offset, bytes, &args_window, &args_at) || + (count_resource && !gpu_indirect_records(count_resource, count_offset, 4, &count_window, &count_at)) || + !vi::validate_layout(kind, stride, max_count, args_at, count_resource != nullptr, count_at, nullptr)) + return gpu_indirect_drop(k, vid_buffer); + if (!gpu_indirect_ready()) return gpu_indirect_drop(k, vid_clamp); + ID3D12CommandSignature* host = gpu_host_signatures.get(device_of(the_device), kind, stride); + if (!host) { + static LONG told; + if (first_calls(told, 4)) log("x2w-gpu indirect: host signature (kind %u, stride %u) refused", kind, stride); + return gpu_indirect_drop(k, vid_signature); + } + const bool compute = kind == vi::kind_dispatch; + vi::ClampCall c; + c.kind = kind; + c.stride = stride; + c.records = max_count; + c.src = args_window; + c.src_offset = args_at; + c.count = count_window; + c.count_offset = count_at; + c.count_out = count_resource != nullptr; + u64 slot = 0; + ID3D12Resource* scratch = reserve_indirect_ring(vi::scratch_bytes(c), &slot); // a chunk in COMMON + if (!scratch) return gpu_indirect_drop(k, vid_scratch); + c.dst = scratch; + c.dst_offset = slot; + c.dst_before = D3D12_RESOURCE_STATE_COMMON; + c.budget_gpu = gpu_indirect_budget(self, list); + c.budget_resource = gpu_budget_pool; + if (!vi::record_clamp(list, gpu_clamp, c)) return gpu_indirect_drop(k, vid_buffer); + // The clamp set its own compute root signature and pipeline state (the one PSO of the list, graphics too): WP3 sets + // both again at the bind that follows. + gpu_bind_forget_compute(self); + const D3D12_RESOURCE_BARRIER rest = vi::transition(scratch, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + const bool bound = compute ? gpu_bind_compute(self, list) + : kind == vi::kind_mesh ? gpu_bind_mesh(self, list) + : gpu_bind_draw(self, list, kind == vi::kind_indexed); + if (!bound) { + list->ResourceBarrier(1, &rest); + return gpu_indirect_drop(k, vid_bind); + } + if (compute) vbind::compute_capture_before(self, list); + else if (vbind::pixel_capture_on()) { + vbind::pixel_capture_before(self, list, "indirect"); + if (const auto& cap = vbind::state_of(self).trace_current; cap && cap->pixel && + !cap->indirect.record(device_of(the_device), list, scratch, slot, kind, stride, max_count, count_resource != nullptr)) + log("x2w-pixel-capture request=%ld frame=%ld shader=%s indirect argument readback unavailable", + cap->request, cap->frame, cap->key.c_str()); + } + list->ExecuteIndirect(host, max_count, scratch, slot, count_resource ? scratch : nullptr, count_resource ? slot + bytes : 0); + if (compute) vbind::compute_capture_after(self, list); + else if (vbind::pixel_capture_on()) vbind::pixel_capture_after(self, list); + gpu_trace_issue(self, "indirect", compute, max_count, stride, static_cast<UINT>(kind)); + gpu_finish_depth_writes(self, list); + list->ResourceBarrier(1, &rest); + InterlockedIncrement(&gpu_indirect_counts.executed[k]); + return true; +} + +// ---- DispatchMesh (list slot 129) --------------------------------------------------------------------------------- +bool gpu_mesh(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z) +{ + gpu_indirect_report(); + InterlockedIncrement(&gpu_indirect_counts.mesh); + if (static_cast<u64>(y) * z != 1) { + InterlockedIncrement(&gpu_indirect_counts.mesh_yz); + static LONG told; + if (first_calls(told, 1)) log("x2w-gpu mesh: a mesh dispatch with y or z groups (%u, %u, %u): run as (%u, 1, 1)", x, y, z, vi::mesh_groups(x)); + } + ID3D12GraphicsCommandList6* list6 = nullptr; + if (!list || !x2w_gpu::gpu_mesh_on() || !gpu_bind_mesh(self, list) || + FAILED(list->QueryInterface(IID_PPV_ARGS(&list6)))) { + InterlockedIncrement(&gpu_indirect_counts.mesh_dropped); + return false; + } + if (x > 65535u) InterlockedIncrement(&gpu_indirect_counts.mesh_cut); + list6->DispatchMesh(vi::mesh_groups(x), 1, 1); + gpu_trace_issue(self, "mesh", false, vi::mesh_groups(x), 1, 1); + gpu_finish_depth_writes(self, list); + list6->Release(); + return true; +} + +// ---- DispatchX (list slot 80) ------------------------------------------------------------------------------------ +bool gpu_dispatch_x(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z, UINT flags) +{ + gpu_indirect_report(); + InterlockedIncrement(&gpu_indirect_counts.dispatch_x); + static const bool thread_dimensions = !gpu_indirect_env_zero("X2W_GPU_THREAD_DIMENSIONS"); + UINT topology = 0; + const GpuPipeline* p = list ? gpu_bound_pipeline(self, &topology) : nullptr; + const x2w_gpu::GpuShader* cs = p && p->compute && p->stage_count ? p->stages[0].shader : nullptr; + if (!(flags & vi::thread_dimensions_flag) || !thread_dimensions || !cs || !cs->has_threads) { + // Counted in groups: a plain dispatch (WP3). + const bool ran = gpu_dispatch(self, list, x, y, z); + if (!ran) InterlockedIncrement(&gpu_indirect_counts.dispatch_x_dropped); + return ran; + } + InterlockedIncrement(&gpu_indirect_counts.dispatch_x_threads); + if (!gpu_bind_compute(self, list)) { + InterlockedIncrement(&gpu_indirect_counts.dispatch_x_dropped); + return false; + } + const std::uint32_t threads[3] = {x, y, z}; + std::uint32_t groups[3]; + vi::dispatch_groups(threads, cs->threads, groups); + // The program is told how many threads run in x, where it asks (its bind set that to all of them). + if (p->threads_x_param != UINT32_MAX) list->SetComputeRoot32BitConstant(p->threads_x_param, x, p->threads_x_dword); + vbind::compute_capture_before(self, list); + list->Dispatch(groups[0], groups[1], groups[2]); + if (groups[0] && groups[1] && groups[2]) vbind::finish_light(self, list); + vbind::compute_capture_after(self, list); + gpu_trace_issue(self, "dispatch-x", true, groups[0], groups[1], groups[2]); + gpu_finish_depth_writes(self, list); + return true; +} + +// ---- the report, every 300 frames --------------------------------------------------------------------------------- +void gpu_indirect_report() +{ + static volatile LONG reported; + const LONG frame = frame_number; + const LONG last = reported; + if (frame - last < 300 || InterlockedCompareExchange(&reported, frame, last) != last) return; + GpuIndirectCounts c{}; + for (int t = 0; t < vik_kinds; ++t) { + c.calls[t] = InterlockedExchange(&gpu_indirect_counts.calls[t], 0); + c.executed[t] = InterlockedExchange(&gpu_indirect_counts.executed[t], 0); + for (int r = 0; r < vid_reasons; ++r) c.dropped[r][t] = InterlockedExchange(&gpu_indirect_counts.dropped[r][t], 0); + } + c.console_single = InterlockedExchange(&gpu_indirect_counts.console_single, 0); + c.counted = InterlockedExchange(&gpu_indirect_counts.counted, 0); + c.rect_triangles = InterlockedExchange(&gpu_indirect_counts.rect_triangles, 0); + c.mesh = InterlockedExchange(&gpu_indirect_counts.mesh, 0); + c.mesh_dropped = InterlockedExchange(&gpu_indirect_counts.mesh_dropped, 0); + c.mesh_cut = InterlockedExchange(&gpu_indirect_counts.mesh_cut, 0); + c.mesh_yz = InterlockedExchange(&gpu_indirect_counts.mesh_yz, 0); + c.dispatch_x = InterlockedExchange(&gpu_indirect_counts.dispatch_x, 0); + c.dispatch_x_threads = InterlockedExchange(&gpu_indirect_counts.dispatch_x_threads, 0); + c.dispatch_x_dropped = InterlockedExchange(&gpu_indirect_counts.dispatch_x_dropped, 0); + char dropped[768] = ""; + int at = 0; + for (int r = 0; r < vid_reasons; ++r) { + LONG total = 0; + for (int t = 0; t < vik_kinds; ++t) total += c.dropped[r][t]; + if (!total || at >= static_cast<int>(sizeof(dropped)) - 96) continue; + at += std::snprintf(dropped + at, sizeof(dropped) - at, "%s%s %ld [", at ? ", " : "", gpu_indirect_drop_names[r], total); + bool first = true; + for (int t = 0; t < vik_kinds; ++t) + if (c.dropped[r][t]) { + at += std::snprintf(dropped + at, sizeof(dropped) - at, "%s%s %ld", first ? "" : " ", gpu_indirect_kind_names[t], + c.dropped[r][t]); + first = false; + } + at += std::snprintf(dropped + at, sizeof(dropped) - at, "]"); + } + log("x2w-gpu indirect to frame %ld: calls (draw %ld, indexed %ld, dispatch %ld of which 0x69 %ld, mesh %ld, other %ld), " + "executed (draw %ld, indexed %ld, dispatch %ld, mesh %ld), dropped (%s); count buffer %ld, rectangles as triangles %ld; " + "DispatchMesh %ld (dropped %ld, cut to 65535 %ld, y*z != 1 %ld); DispatchX %ld (in threads %ld, dropped %ld)", + frame, c.calls[0], c.calls[1], c.calls[2], c.console_single, c.calls[3], c.calls[4], c.executed[0], c.executed[1], c.executed[2], + c.executed[3], at ? dropped : "none", c.counted, c.rect_triangles, c.mesh, c.mesh_dropped, c.mesh_cut, c.mesh_yz, c.dispatch_x, + c.dispatch_x_threads, c.dispatch_x_dropped); + if (gpu_budget_words) { + // Each slot holds the notes of the last recording that used it (zeroed at that recording's first clamp). + unsigned long long refused = 0, mesh_asked = 0; + std::uint32_t biggest = 0, largest = 0, spent_full = 0; + for (std::uint32_t s = 0; s < gpu_budget_slots; ++s) { + const volatile std::uint32_t* w = gpu_budget_words + u64{s} * (vi::budget_slot_bytes / 4); + if (w[0] >= vi::budget) ++spent_full; + largest = w[1] > largest ? w[1] : largest; + mesh_asked += w[2]; + refused += w[3]; + biggest = w[4] > biggest ? w[4] : biggest; + } + log("x2w-gpu indirect notes (last recording per pool slot): lists that spent the whole budget %u, records refused %llu, " + "largest cost %u, largest mesh group count asked %u, mesh groups asked %llu", + spent_full, refused, biggest, largest, mesh_asked); + } +} diff --git a/src/startup_stubs/gpu_indirect_capture.h b/src/startup_stubs/gpu_indirect_capture.h new file mode 100644 index 0000000000..f535acb6a4 --- /dev/null +++ b/src/startup_stubs/gpu_indirect_capture.h @@ -0,0 +1,65 @@ +#pragma once +#include <d3d12.h> +#include <wrl/client.h> +#include <algorithm> +#include <array> +#include <cstring> + +namespace x2w_compute_trace { +struct IndirectArguments { + static constexpr UINT limit = 8, words = 5; + using Record = std::array<UINT, words>; + struct Snapshot { UINT count{}; std::array<Record, limit> records{}; }; + Microsoft::WRL::ComPtr<ID3D12Resource> buffer; + UINT kind{}, stride{}, maximum{}, copied{}, fields{}; + bool counted{}; + + bool record(ID3D12Device* device, ID3D12GraphicsCommandList* list, ID3D12Resource* source, + UINT64 offset, UINT type, UINT step, UINT max, bool has_count) + { + const UINT payload = type == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW ? 4 : + type == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED ? 5 : 3; + if (!source || step < payload * sizeof(UINT) || !max || step % 4) return false; + const auto width = source->GetDesc().Width; + const UINT64 bytes = UINT64(step) * max; + if (offset > width || bytes > width - offset || (has_count && width - offset - bytes < 4)) return false; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = sizeof(Snapshot); + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&buffer)))) return false; + kind = type; stride = step; maximum = max; counted = has_count; + copied = (std::min)(limit, max); + fields = payload; + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {source, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE}; + list->ResourceBarrier(1, &barrier); + if (counted) list->CopyBufferRegion(buffer.Get(), 0, source, offset + bytes, 4); + for (UINT i = 0; i < copied; ++i) + list->CopyBufferRegion(buffer.Get(), sizeof(UINT) + sizeof(Record) * i, source, offset + UINT64(step)*i, fields*4); + std::swap(barrier.Transition.StateBefore, barrier.Transition.StateAfter); + list->ResourceBarrier(1, &barrier); + return true; + } + + bool read(Snapshot& snap) const + { + void* data = nullptr; + D3D12_RANGE range{0, sizeof(Snapshot)}; + if (!buffer || FAILED(buffer->Map(0, &range, &data))) return false; + const auto* bytes = static_cast<const unsigned char*>(data); + if (counted) std::memcpy(&snap.count, bytes, sizeof(UINT)); + else snap.count = maximum; + for (UINT i=0; i<copied; ++i) + std::memcpy(snap.records[i].data(), bytes + sizeof(UINT) + sizeof(Record)*i, fields*4); + const D3D12_RANGE none{}; + buffer->Unmap(0, &none); + return true; + } +}; +} diff --git a/src/startup_stubs/gpu_indirect_clamp.h b/src/startup_stubs/gpu_indirect_clamp.h new file mode 100644 index 0000000000..a241dda6e7 --- /dev/null +++ b/src/startup_stubs/gpu_indirect_clamp.h @@ -0,0 +1,482 @@ +// Indirect signature decoding and GPU argument clamping. Console single-pass dispatch (type 105, stride 12) maps to +// plain dispatch. A host command signature is cached per kind and stride. Signatures that change root arguments are +// refused. +// +// The clamp is a cs_5_1 shader with an embedded root signature. Its destination is a four-byte-aligned offset in +// the indirect ring. Chunks retire after submission. The effective count min(records,count) follows the clamped +// records when bit 2 of has_count is set. The source is rebased to its own GPU address so large window offsets fit. +// Each list's 2^27 budget is cleared on the GPU at its first clamp after reset because the previous recording may +// still be in flight. +#pragma once + +#include <d3d12.h> +#include <d3dcompiler.h> +#include <dxgi1_4.h> + +#include <cstddef> +#include <cstdint> +#include <cstdio> +#include <mutex> +#include <string> +#include <utility> +#include <vector> + +namespace x2w_gpu_indirect { + +using u32 = std::uint32_t; +using u64 = std::uint64_t; + +// PC argument numbering (D3D12_INDIRECT_ARGUMENT_TYPE). +constexpr u32 kind_draw = 0; +constexpr u32 kind_indexed = 1; +constexpr u32 kind_dispatch = 2; +constexpr u32 kind_mesh = 10; +// The console's single-pass dispatch: stride 12, the three group counts (its flags live in the signature; the +// title passes none). Run as a plain dispatch. +constexpr u32 console_single_dispatch = 105; + +// The budget slot's words (bytes): what the list spent [0], mesh records' largest group count asked [4], mesh +// groups asked in all [8], records refused for want of budget [12], the largest cost >= 2^22 [16]. +constexpr u32 budget_slot_bytes = 32; +constexpr u32 budget = 1u << 27; + +// The kind a signature runs as, or false when it cannot run: exactly one argument, of a kind the host signature +// takes (draw, indexed draw, dispatch, mesh dispatch, or the console's single-pass dispatch, which becomes a +// dispatch). +inline bool signature_kind(const u32* types, std::size_t count, u32* kind) +{ + if (!types || count != 1) return false; + const u32 type = types[0] == console_single_dispatch ? kind_dispatch : types[0]; + if (type != kind_draw && type != kind_indexed && type != kind_dispatch && type != kind_mesh) return false; + *kind = type; + return true; +} +template <class Description> +bool signature_kind_of(const Description* arguments, std::size_t count, u32* kind) +{ + if (!arguments || count != 1) return false; + const u32 type = static_cast<u32>(arguments[0].Type); + return signature_kind(&type, 1, kind); +} + +// Minimum record byte stride of `kind`, or 0 for a kind the clamp does not take. +constexpr u32 min_stride(u32 kind) +{ + return kind == kind_draw ? 16 : kind == kind_indexed ? 20 : kind == kind_dispatch || kind == kind_mesh ? 12 : 0; +} + +// Validate record alignment, minimum stride, and the 32-bit scratch size stride * records. +inline bool validate_layout(u32 kind, u32 stride, u32 records, u64 src_offset, bool has_count, u64 count_offset, u64* bytes) +{ + const u32 least = min_stride(kind); + if (!least || stride < least || stride % 4 || src_offset % 4) return false; + if (has_count && count_offset % 4) return false; + const u64 total = u64{stride} * records; + if (total > 0xffffffffull) return false; + if (bytes) *bytes = total; + return true; +} + +// The groups a direct DispatchMesh runs: the console's mesh programs are one-dimensional and the host takes 65,535 +// groups in a dimension. +constexpr u32 mesh_groups(u32 x) { return x < 65535u ? x : 65535u; } + +// DispatchX with "use thread dimensions" (console flag 0x20): the counts are threads, run as the groups of the +// program's size that hold them. +constexpr u32 thread_dimensions_flag = 0x20; +inline void dispatch_groups(const u32 threads[3], const u32 size[3], u32 groups[3]) +{ + for (int i = 0; i < 3; ++i) groups[i] = size[i] ? (threads[i] + size[i] - 1) / size[i] : threads[i]; +} + +// The most groups in x an indirect dispatch runs as asked: 2^20 on an AMD card (its dispatch packets take 32-bit +// counts, as the console's), 65,535 elsewhere. +constexpr u32 widest(bool amd, bool wide_on = true) { return amd && wide_on ? (1u << 20) : 65535u; } + +// Whether `device` is an AMD card's (vendor 0x1002). +inline bool is_amd(ID3D12Device* device) +{ + if (!device) return false; + IDXGIFactory4* factory = nullptr; + if (FAILED(CreateDXGIFactory2(0, __uuidof(IDXGIFactory4), reinterpret_cast<void**>(&factory)))) return false; + IDXGIAdapter1* adapter = nullptr; + bool amd = false; + if (SUCCEEDED(factory->EnumAdapterByLuid(device->GetAdapterLuid(), __uuidof(IDXGIAdapter1), reinterpret_cast<void**>(&adapter)))) { + DXGI_ADAPTER_DESC1 desc{}; + amd = SUCCEEDED(adapter->GetDesc1(&desc)) && desc.VendorId == 0x1002; + adapter->Release(); + } + factory->Release(); + return amd; +} + +// The clamp writes the effective record count after the records when bit 2 of has_count is set (count_out). +// clamp_text supplies WIDEST and REST. +constexpr char clamp_source[] = R"hlsl( +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { + uint kind; + uint stride; + uint records; + uint args_offset; + // Bit 0: a count buffer bounds the records. Bit 1: the records are a + // window clamped ahead of their draws: one that asks for more than can + // run is left empty and costs nothing. Bit 2 (X2W): the effective count + // is stored after the records, for ExecuteIndirect's count buffer. + uint has_count; + uint count_offset; +}; +ByteAddressBuffer src_args : register(t0); +ByteAddressBuffer count_buf : register(t1); +RWByteAddressBuffer dst_args : register(u0); +// The list's work so far (vertex instances, threads): past the budget, +// records run empty. +RWByteAddressBuffer budget : register(u1); +static const uint BUDGET = 1u << 27; +// The vertices or indices an instance from which a draw record runs empty. +static const uint MOST_DRAW = 1u << 23; +// Groups of one dispatch; more run empty. +static const uint GROUPS = 1u << 20; +// Each group charges the budget once: the costs of its records go here, +// one thread charges their sum, saturating as each record would in lane +// order, and every thread then reads whether its own record fitted. +groupshared uint costs[64]; +groupshared uint fits[64]; +groupshared uint largest_asked; +groupshared uint all_asked; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { + uint eff_count = records; + bool ahead = (has_count & 2u) != 0; + if ((has_count & 1u) != 0) { + eff_count = min(eff_count, count_buf.Load(count_offset)); + } + if ((has_count & 4u) != 0 && id.x == 0) { + dst_args.Store(records * stride, eff_count); + } + // Threads past the records take part in the group's charge (cost 0) + // and store nothing. + bool active = id.x < eff_count; + uint src_at = args_offset + id.x * stride; + uint dst_at = id.x * stride; + uint cost = 0; + uint asked = 0; + uint2 draw_counts = uint2(0, 0); + uint3 groups = uint3(0, 0, 0); + if (gi == 0) { + largest_asked = 0; + all_asked = 0; + } + if (active && kind <= 1) { + // Draws: vertex or index count, then instances. + uint2 want = src_args.Load2(src_at); + if (ahead && (want.x > (1u << 24) || want.y > (1u << 24))) { + want = uint2(0, 0); + } + // A record of MOST_DRAW vertices or indices an instance, or more, is + // no draw of the title's (a slot it has not filled): it runs empty + // and charges nothing. + if (want.x >= MOST_DRAW) { + want = uint2(0, 0); + } + uint count = want.x; + uint instances = min(want.y, (1u << 26) / max(count, 1u)); + cost = count * instances; + draw_counts = uint2(count, instances); + } else if (active && kind == 2) { + uint3 g = src_args.Load3(src_at); + // Up to WIDEST groups in x run as asked (`widest`). + g = min(g, uint3(g.x <= WIDEST ? WIDEST : 65535u, 65535u, 65535u)); + // x * y fits 32 bits where it is looked at; the whole count may not. + if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) { + g = uint3(0, 0, 0); + } + cost = g.x * g.y * g.z * 64u; + groups = g; + } else if (active) { + // Mesh dispatches: the console's are one-dimensional. + uint3 g = src_args.Load3(src_at); + // A record over the most a dispatch runs is a slot the title has + // not filled (the title leaves all ones there): empty, + // and not counted below either. + if (g.x > 65535u) { + g = uint3(0, 0, 0); + } + asked = g.x; + g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); + cost = g.x * g.y * g.z * 128u; + groups = g; + } + costs[gi] = cost; + GroupMemoryBarrierWithGroupSync(); + if (active && kind > 2) { + // Diagnostics, in the budget buffer's next words: the largest group + // count a mesh record asked for, and the groups asked in all. + uint was; + InterlockedMax(largest_asked, asked, was); + InterlockedAdd(all_asked, min(asked, 1u << 24), was); + } + // The group's own records: none for a group past a count buffer's + // count, which touches the budget not at all. + uint first = id.x - gi; + uint n = eff_count > first ? min(64u, eff_count - first) : 0u; + if (gi == 0 && n > 0) { + // What the records charge, from `before` on, in lane order: a + // record that does not fit whole runs empty and takes the rest + // (`REST`). + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint next = before; + for (uint j = 0; j < n; j++) { + uint c = costs[j]; + if (c > 0 && next < BUDGET) { + next = (BUDGET - next < c) ? (REST ? BUDGET : next) : (next + c); + } + } + if (next == before) break; + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + uint at = before; + uint refused = 0; + uint biggest = 0; + for (uint k = 0; k < n; k++) { + uint c = costs[k]; + uint fit = 1; + if (c > 0) { + fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u; + at = (at >= BUDGET || BUDGET - at < c) ? (REST ? BUDGET : at) : (at + c); + refused += 1 - fit; + biggest = max(biggest, c); + } + fits[k] = fit; + } + // Diagnostics: the records that run empty for want of budget, and + // the largest cost there was (small ones are not told). + uint told; + if (refused > 0) { + budget.InterlockedAdd(12, refused, told); + } + if (biggest >= (1u << 22)) { + budget.InterlockedMax(16, biggest, told); + } + } + GroupMemoryBarrierWithGroupSync(); + if (gi == 0 && kind > 2 && n > 0) { + uint was; + budget.InterlockedMax(4, largest_asked, was); + budget.InterlockedAdd(8, all_asked, was); + } + if (!active) { + return; + } + bool over = fits[gi] == 0; + if (kind <= 1) { + if (over) { + draw_counts = uint2(0, 0); + } + dst_args.Store2(dst_at, draw_counts); + for (uint off = 8; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } + } else { + if (over) { + groups = uint3(0, 0, 0); + } + dst_args.Store3(dst_at, groups); + for (uint off = 12; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } + } +} +)hlsl"; + +// The clamp's text with WIDEST and REST defined. +inline std::string clamp_text(u32 widest_groups, bool rest, const char* source = clamp_source) +{ + char head[96]; + std::snprintf(head, sizeof(head), "#define WIDEST %uu\n#define REST %u\n", widest_groups, rest ? 1u : 0u); + return std::string(head) + source; +} + +struct Clamp { + ID3D12RootSignature* root = nullptr; + ID3D12PipelineState* pso = nullptr; + void release() + { + if (pso) pso->Release(); + if (root) root->Release(); + pso = nullptr; + root = nullptr; + } +}; + +// Compiles `text` (clamp_text) with FXC as cs_5_1 and makes its root signature (inside the shader) and pipeline. +// `errors` (optional) gets the compiler's message. +inline HRESULT make_clamp(ID3D12Device* device, const std::string& text, Clamp* out, std::string* errors = nullptr) +{ + if (!device || !out) return E_INVALIDARG; + ID3DBlob* code = nullptr; + ID3DBlob* messages = nullptr; + HRESULT hr = D3DCompile(text.data(), text.size(), "gpu_clamp", nullptr, nullptr, "main", "cs_5_1", 0, 0, &code, &messages); + if (messages) { + if (errors) errors->assign(static_cast<const char*>(messages->GetBufferPointer()), messages->GetBufferSize()); + messages->Release(); + } + if (FAILED(hr)) { + if (code) code->Release(); + return hr; + } + Clamp made; + hr = device->CreateRootSignature(0, code->GetBufferPointer(), code->GetBufferSize(), IID_PPV_ARGS(&made.root)); + if (SUCCEEDED(hr)) { + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = made.root; + desc.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + hr = device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&made.pso)); + } + code->Release(); + if (FAILED(hr)) { + made.release(); + return hr; + } + *out = made; + return S_OK; +} + +inline D3D12_RESOURCE_BARRIER transition(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; + return b; +} +inline D3D12_RESOURCE_BARRIER uav_barrier(ID3D12Resource* resource = nullptr) +{ + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + b.UAV.pResource = resource; + return b; +} + +// One clamp. +struct ClampCall { + u32 kind = 0, stride = 0, records = 0; + ID3D12Resource* src = nullptr; // the records, read through a root SRV (any state a root SRV may read) + u64 src_offset = 0; + ID3D12Resource* count = nullptr; // null: no count buffer + u64 count_offset = 0; + ID3D12Resource* dst = nullptr; // the scratch buffer (UAV-capable, device local) + u64 dst_offset = 0; // 4-aligned + D3D12_RESOURCE_STATES dst_before = D3D12_RESOURCE_STATE_COMMON; + u64 budget_gpu = 0; // the list's budget slot (budget_slot_bytes) + // The buffer holding the budget slot, when it rests in COMMON (a pool shared by lists): it is moved to + // UNORDERED_ACCESS for the clamp and back to COMMON with the clamp's own barriers, so that no list leaves it + // in another state (buffers decay to COMMON only at the end of a whole ExecuteCommandLists, and the next list + // of the same call expects COMMON). Null: the slot's buffer is left as it is (tests' mapped buffers). + ID3D12Resource* budget_resource = nullptr; + bool ahead = false; // a window clamped ahead of its draws (unfilled slots empty and free) + bool count_out = false; // store min(records, count) at dst_offset + stride * records +}; + +// The scratch bytes a call needs: the records, and the count after them when count_out. +inline u64 scratch_bytes(const ClampCall& c) { return u64{c.stride} * c.records + (c.count_out ? 4 : 0); } + +// Records the clamp of `c` into `list`: a UAV barrier for every earlier shader write (the title's argument and +// count passes), dst before -> UNORDERED_ACCESS, the clamp dispatch, a UAV barrier, dst -> INDIRECT_ARGUMENT. +// Replaces the list's compute root signature and pipeline (the caller binds its own after). False, with nothing +// recorded, when the layout or the addresses do not fit the clamp. +inline bool record_clamp(ID3D12GraphicsCommandList* list, const Clamp& clamp, const ClampCall& c) +{ + u64 bytes = 0; + if (!list || !clamp.pso || !c.src || !c.dst) return false; + if (!validate_layout(c.kind, c.stride, c.records, c.src_offset, c.count != nullptr, c.count_offset, &bytes)) return false; + if (c.dst_offset % 4 || c.budget_gpu % 4 || !c.budget_gpu) return false; + if (c.count_out && bytes + 4 > 0xffffffffull) return false; + const u64 src_gpu = c.src->GetGPUVirtualAddress() + c.src_offset; + const u64 dst_gpu = c.dst->GetGPUVirtualAddress() + c.dst_offset; + if (src_gpu % 4 || dst_gpu % 4) return false; + u64 count_gpu = src_gpu; + u32 has_count = 0; + if (c.count) { + count_gpu = c.count->GetGPUVirtualAddress() + c.count_offset; + if (count_gpu % 4) return false; + has_count = 1; + } + has_count |= (c.ahead ? 2u : 0u) | (c.count_out ? 4u : 0u); + // The source is rebased to its own address (args_offset 0), the count likewise (count_offset 0). + const u32 constants[6] = {c.kind, c.stride, c.records, 0, has_count, 0}; + D3D12_RESOURCE_BARRIER first[3] = {uav_barrier(), {}, {}}; + UINT n = 1; + if (c.dst_before != D3D12_RESOURCE_STATE_UNORDERED_ACCESS) + first[n++] = transition(c.dst, c.dst_before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (c.budget_resource) + first[n++] = transition(c.budget_resource, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->ResourceBarrier(n, first); + if (c.records > 0) { + list->SetComputeRootSignature(clamp.root); + list->SetPipelineState(clamp.pso); + list->SetComputeRoot32BitConstants(0, 6, constants, 0); + list->SetComputeRootShaderResourceView(1, src_gpu); + list->SetComputeRootShaderResourceView(2, count_gpu); + list->SetComputeRootUnorderedAccessView(3, dst_gpu); + list->SetComputeRootUnorderedAccessView(4, c.budget_gpu); + list->Dispatch((c.records + 63) / 64, 1, 1); + } + const D3D12_RESOURCE_BARRIER second[3] = { + uav_barrier(), transition(c.dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + c.budget_resource ? transition(c.budget_resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON) : D3D12_RESOURCE_BARRIER{}}; + list->ResourceBarrier(c.budget_resource ? 3 : 2, second); + return true; +} + +// Zeroes a list's budget slot on the GPU at its first clamp after a reset: `pool` (in COMMON, where every list +// leaves it) gets budget_slot_bytes zeros at `offset` from `zeros` (a buffer of at least that many zero bytes, in a +// state a copy reads, e.g. an upload heap's GENERIC_READ), and goes back to COMMON. The clamps that follow name +// the pool as their ClampCall::budget_resource. +inline void record_budget_zero(ID3D12GraphicsCommandList* list, ID3D12Resource* pool, u64 offset, ID3D12Resource* zeros) +{ + const D3D12_RESOURCE_BARRIER to_copy = transition(pool, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(pool, offset, zeros, 0, budget_slot_bytes); + const D3D12_RESOURCE_BARRIER back = transition(pool, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + list->ResourceBarrier(1, &back); +} + +// Host command signatures of one argument of `kind` with records `stride` bytes apart, no root arguments and so no +// root signature, made once per device. +class HostSignatures { +public: + ID3D12CommandSignature* get(ID3D12Device* device, u32 kind, u32 stride) + { + std::lock_guard<std::mutex> hold(lock_); + for (const auto& m : made_) + if (m.device == device && m.kind == kind && m.stride == stride) return m.signature; + D3D12_INDIRECT_ARGUMENT_DESC argument{}; + argument.Type = static_cast<D3D12_INDIRECT_ARGUMENT_TYPE>(kind); + const D3D12_COMMAND_SIGNATURE_DESC desc{stride, 1, &argument, 0}; + ID3D12CommandSignature* signature = nullptr; + if (!device || FAILED(device->CreateCommandSignature(&desc, nullptr, IID_PPV_ARGS(&signature)))) return nullptr; + made_.push_back({device, kind, stride, signature}); + return signature; + } + +private: + struct Made { + ID3D12Device* device; + u32 kind, stride; + ID3D12CommandSignature* signature; + }; + std::mutex lock_; + std::vector<Made> made_; +}; + +} // namespace x2w_gpu_indirect diff --git a/src/startup_stubs/gpu_late_texture.h b/src/startup_stubs/gpu_late_texture.h new file mode 100644 index 0000000000..87a7ad67b6 --- /dev/null +++ b/src/startup_stubs/gpu_late_texture.h @@ -0,0 +1,161 @@ +#pragma once + +#include <d3d12.h> +#include <cstdint> +#include <cstring> + +namespace x2w_late_texture { +// A copied title descriptor must retain every field needed to rebuild its SRV. +// Array markers use the high bit of word 5, unused by D3D12 component mapping. +constexpr std::uint32_t magic = 0x54573258; // X2WT +constexpr std::uint32_t lazy = 0x4c573258; // X2WL +inline bool marker(std::uint32_t word) { return word == magic || word == lazy; } +inline bool texture_format(DXGI_FORMAT f) +{ + // Standard DXGI values plus console formats 116–120 translated by desktop_format(). + const UINT n = static_cast<UINT>(f); + return (n >= 1 && n <= 120) || (n >= 130 && n <= 132) || (n >= 189 && n <= 191); +} +inline bool valid_shape(const D3D12_RESOURCE_DESC& r, bool allow_full_chain = false) +{ + const bool volume = r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + if (!volume && r.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return false; + const UINT limit = volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION; + const UINT slices = volume ? limit : D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION; + if (!r.Width || r.Width > limit || !r.Height || r.Height > limit || !r.DepthOrArraySize || + r.DepthOrArraySize > slices || (!r.MipLevels && !allow_full_chain) || !texture_format(r.Format)) return false; + UINT largest = r.Width > r.Height ? static_cast<UINT>(r.Width) : r.Height; + if (volume && r.DepthOrArraySize > largest) largest = r.DepthOrArraySize; + UINT levels = 1; + while (largest >>= 1) ++levels; + return r.MipLevels <= levels; +} +inline bool encode(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v, + std::uint64_t address, std::uint32_t (&w)[8]) +{ + const bool volume = r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE3D; + const bool cube = v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBE; + if (!address || !valid_shape(r) || (!volume && r.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) || r.Alignment || + !r.Width || r.Width > 65535 || !r.Height || r.Height > 65535 || !r.DepthOrArraySize || + (v.Format != DXGI_FORMAT_UNKNOWN && !texture_format(v.Format)) || + unsigned(r.Layout) < 0x100 || unsigned(r.Layout) > 0x1ff || unsigned(r.Flags) != 0x300000 || + r.SampleDesc.Count != 1 || r.SampleDesc.Quality || v.Shader4ComponentMapping > 0x1fff) + return false; + const bool array = v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + if (array) { + const auto& a = v.Texture2DArray; + if (r.DepthOrArraySize > 2048 || a.PlaneSlice || a.FirstArraySlice >= r.DepthOrArraySize || + !a.ArraySize || a.ArraySize > r.DepthOrArraySize - a.FirstArraySlice || + a.MostDetailedMip > 255 || (!a.MipLevels || (a.MipLevels >= 511 && a.MipLevels != UINT32_MAX))) return false; + } else if (volume || cube) { + const UINT most = volume ? v.Texture3D.MostDetailedMip : v.TextureCube.MostDetailedMip; + const UINT levels = volume ? v.Texture3D.MipLevels : v.TextureCube.MipLevels; + if ((cube && (r.DepthOrArraySize != 6 || r.Width != r.Height)) || + most > 65535 || !levels || (levels >= 65535 && levels != UINT32_MAX)) return false; + } else if (r.DepthOrArraySize != 1 || v.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D || + v.Texture2D.PlaneSlice || v.Texture2D.MostDetailedMip > 65535 || + (v.Texture2D.MipLevels > 65535 && v.Texture2D.MipLevels != UINT32_MAX)) return false; + w[0] = magic; + w[1] = std::uint32_t(address); + w[2] = std::uint32_t(address >> 32); + w[3] = std::uint32_t(r.Width) | (r.Height << 16); + w[4] = unsigned(r.Format) | (unsigned(v.Format) << 8) | ((unsigned(r.Layout) & 255) << 16) | + (unsigned(r.MipLevels) << 24); + if (array) { + const auto& a = v.Texture2DArray; + const std::uint64_t packed = (1ull << 63) | v.Shader4ComponentMapping | + (std::uint64_t(r.DepthOrArraySize - 1) << 13) | (std::uint64_t(a.FirstArraySlice) << 24) | + (std::uint64_t(a.ArraySize - 1) << 35) | (std::uint64_t(a.MostDetailedMip) << 46) | + (std::uint64_t(a.MipLevels == UINT32_MAX ? 511 : a.MipLevels) << 54); + w[5] = std::uint32_t(packed >> 32); + w[6] = std::uint32_t(packed); + std::memcpy(w + 7, &a.ResourceMinLODClamp, 4); + } else if (volume || cube) { + const UINT most = volume ? v.Texture3D.MostDetailedMip : v.TextureCube.MostDetailedMip; + const UINT levels = volume ? v.Texture3D.MipLevels : v.TextureCube.MipLevels; + w[5] = (1u << 30) | (unsigned(volume) << 29) | (unsigned(r.DepthOrArraySize) << 13) | v.Shader4ComponentMapping; + w[6] = most | ((levels & 65535) << 16); + const float clamp = volume ? v.Texture3D.ResourceMinLODClamp : v.TextureCube.ResourceMinLODClamp; + std::memcpy(w + 7, &clamp, 4); + } else { + w[5] = v.Shader4ComponentMapping | (v.Texture2D.MipLevels == UINT32_MAX ? 1u << 28 : 0u); + w[6] = v.Texture2D.MostDetailedMip | (v.Texture2D.MipLevels << 16); + std::memcpy(w + 7, &v.Texture2D.ResourceMinLODClamp, 4); + } + return true; +} +enum class Resolution { hosted, unavailable, refused, publish_failed, published }; + +// A GPU resource with the exact address and description may outlive the CPU +// mapping of its texels. Only a new detiled copy requires that mapping. +template<class Lookup, class Check, class Publish> +auto resolve(Lookup lookup, Check check, Publish publish, Resolution& why) +{ + auto texture = lookup(); + if (texture) { + why = Resolution::hosted; + return texture; + } + const unsigned decline = check(); + if (decline) { + why = decline == 8 ? Resolution::unavailable : Resolution::refused; + return texture; + } + texture = publish(); + why = texture ? Resolution::published : Resolution::publish_failed; + return texture; +} + +inline bool decode(const std::uint32_t* w, D3D12_RESOURCE_DESC& r, D3D12_SHADER_RESOURCE_VIEW_DESC& v) +{ + r = {}; + v = {}; + if (!w || !marker(w[0]) || (!w[1] && !w[2])) return false; + r.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + r.Width = w[3] & 65535; + r.Height = w[3] >> 16; + r.DepthOrArraySize = 1; + r.Format = DXGI_FORMAT(w[4] & 255); + r.MipLevels = UINT16(w[4] >> 24); + r.Layout = D3D12_TEXTURE_LAYOUT(0x100 | ((w[4] >> 16) & 255)); + r.SampleDesc.Count = 1; + r.Flags = D3D12_RESOURCE_FLAGS(0x300000); + v.Format = DXGI_FORMAT((w[4] >> 8) & 255); + if (v.Format != DXGI_FORMAT_UNKNOWN && !texture_format(v.Format)) return false; + if (w[5] >> 31) { + const std::uint64_t packed = (std::uint64_t(w[5]) << 32) | w[6]; + r.DepthOrArraySize = UINT16(((packed >> 13) & 2047) + 1); + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + v.Shader4ComponentMapping = UINT(packed & 0x1fff); + auto& a = v.Texture2DArray; + a.FirstArraySlice = UINT((packed >> 24) & 2047); + a.ArraySize = UINT(((packed >> 35) & 2047) + 1); + a.MostDetailedMip = UINT((packed >> 46) & 255); + a.MipLevels = UINT((packed >> 54) & 511); + if (a.MipLevels == 511) a.MipLevels = UINT32_MAX; + std::memcpy(&a.ResourceMinLODClamp, w + 7, 4); + return valid_shape(r) && a.FirstArraySlice < r.DepthOrArraySize && + a.ArraySize <= r.DepthOrArraySize - a.FirstArraySlice && a.MipLevels; + } + if (w[5] & (1u << 30)) { + const bool volume = (w[5] & (1u << 29)) != 0; + if (volume) r.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + r.DepthOrArraySize = UINT16(w[5] >> 13); + v.ViewDimension = volume ? D3D12_SRV_DIMENSION_TEXTURE3D : D3D12_SRV_DIMENSION_TEXTURECUBE; + v.Shader4ComponentMapping = w[5] & 0x1fff; + const UINT most = w[6] & 65535; + const UINT levels = (w[6] >> 16) == 65535 ? UINT32_MAX : w[6] >> 16; + float clamp; + std::memcpy(&clamp, w + 7, 4); + if (volume) v.Texture3D = {most, levels, clamp}; + else v.TextureCube = {most, levels, clamp}; + return valid_shape(r) && (volume || (r.Width == r.Height && r.DepthOrArraySize == 6)) && levels; + } + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.Shader4ComponentMapping = w[5] & 0x1fff; + v.Texture2D.MostDetailedMip = w[6] & 65535; + v.Texture2D.MipLevels = (w[5] & (1u << 28)) ? UINT32_MAX : w[6] >> 16; + std::memcpy(&v.Texture2D.ResourceMinLODClamp, w + 7, 4); + return valid_shape(r); +} +} diff --git a/src/startup_stubs/gpu_list_states.h b/src/startup_stubs/gpu_list_states.h new file mode 100644 index 0000000000..b62096cc88 --- /dev/null +++ b/src/startup_stubs/gpu_list_states.h @@ -0,0 +1,84 @@ +#pragma once + +#include "startup_stubs/gpu_transition.h" +#include <unordered_map> +#include <vector> + +namespace x2w_gpu { + +class ListStates { +public: + struct Entry { + ID3D12Resource* resource; + D3D12_RESOURCE_STATES depth = D3D12_RESOURCE_STATE_COMMON; + D3D12_RESOURCE_STATES stencil = D3D12_RESOURCE_STATE_COMMON; + }; + + const Entry* find(ID3D12Resource* resource) const + { + const auto it = indices_.find(resource); + return it == indices_.end() ? nullptr : &ordered_[it->second]; + } + D3D12_RESOURCE_STATES state(ID3D12Resource* resource) const + { + const auto* entry = find(resource); + return entry ? entry->depth : D3D12_RESOURCE_STATE_COMMON; + } + Entry& track(ID3D12Resource* resource) + { + const auto [it, inserted] = indices_.try_emplace(resource, ordered_.size()); + if (inserted) { + try { + ordered_.push_back({resource}); + } catch (...) { + indices_.erase(it); + throw; + } + } + return ordered_[it->second]; + } + void require(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, + D3D12_RESOURCE_STATES depth, D3D12_RESOURCE_STATES stencil) + { + change(list, track(resource), depth, stencil); + } + void close(ID3D12GraphicsCommandList* list) + { + for (auto& entry : ordered_) + change(list, entry, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COMMON); + clear(); + } + void clear() { ordered_.clear(); indices_.clear(); } + std::size_t size() const { return ordered_.size(); } + +private: + static void change(ID3D12GraphicsCommandList* list, Entry& entry, + D3D12_RESOURCE_STATES depth, D3D12_RESOURCE_STATES stencil) + { + if (entry.depth == depth && entry.stencil == stencil) return; + if (entry.depth == entry.stencil && depth == stencil) { + transition_all(list, entry.resource, entry.depth, depth); + } else { + const auto desc = entry.resource->GetDesc(); + const UINT stride = UINT(desc.MipLevels) * desc.DepthOrArraySize; + const auto plane = [&](UINT index, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + if (before == after) return; + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Transition = {entry.resource, 0, before, after}; + for (UINT i = 0; i < stride; ++i) { + barrier.Transition.Subresource = index * stride + i; + list->ResourceBarrier(1, &barrier); + } + }; + plane(0, entry.depth, depth); + plane(1, entry.stencil, stencil); + } + entry.depth = depth; + entry.stencil = stencil; + } + + std::vector<Entry> ordered_; + std::unordered_map<ID3D12Resource*, std::size_t> indices_; +}; + +} // namespace x2w_gpu diff --git a/src/startup_stubs/gpu_material_fields.h b/src/startup_stubs/gpu_material_fields.h new file mode 100644 index 0000000000..bcdceb2aa2 --- /dev/null +++ b/src/startup_stubs/gpu_material_fields.h @@ -0,0 +1,62 @@ +#pragma once +#include <algorithm> +#include <cstdint> +#include <cstring> +#include <cstdlib> +#include <fstream> +#include <sstream> +#include <vector> + +namespace x2w_material { +using Mask = std::uint16_t; +constexpr unsigned byte_count(Mask mask) +{ + unsigned bytes = 0; + for (; mask; mask >>= 1) bytes += 4; + return bytes; +} +struct Entry { + std::uint64_t key, hash_low, hash_high; + Mask fields; +}; +// Each local profile row contains the shader key, both DXBC hash halves and the field mask, in hexadecimal. +inline std::vector<Entry> read_profile(std::istream& input) +{ + std::vector<Entry> entries; + std::string line; + while (std::getline(input, line)) { + std::istringstream row(line); + Entry entry{}; + unsigned fields; + std::string trailing; + if ((row >> std::hex >> entry.key >> entry.hash_low >> entry.hash_high >> fields) && + fields <= 0xffff && !(row >> trailing)) { + entry.fields = static_cast<Mask>(fields); + entries.push_back(entry); + } + } + std::sort(entries.begin(), entries.end(), [](const Entry& a, const Entry& b) { return a.key < b.key; }); + return entries; +} +inline Mask lookup(const std::vector<Entry>& entries, std::uint64_t key, const void* dxil, std::size_t bytes) +{ + const auto end = entries.end(); + const auto it = std::lower_bound(entries.begin(), end, key, [](const Entry& r, std::uint64_t k) { return r.key < k; }); + if (it == end || it->key != key || !dxil || bytes < 20 || std::memcmp(dxil, "DXBC", 4)) return 0; + std::uint64_t hash[2]; + std::memcpy(hash, static_cast<const char*>(dxil) + 4, sizeof(hash)); + for (auto row = it; row != end && row->key == key; ++row) + if (hash[0] == row->hash_low && hash[1] == row->hash_high) return row->fields; + return 0; +} +inline Mask lookup(std::uint64_t key, const void* dxil, std::size_t bytes) +{ + static const auto profile = [] { + const char* path = std::getenv("X2W_MATERIAL_FIELDS_PROFILE"); + if (!path || !*path) return std::vector<Entry>{}; + std::ifstream input(path); + return read_profile(input); + }(); + return lookup(profile, key, dxil, bytes); +} +} diff --git a/src/startup_stubs/gpu_material_trace.h b/src/startup_stubs/gpu_material_trace.h new file mode 100644 index 0000000000..c48de37979 --- /dev/null +++ b/src/startup_stubs/gpu_material_trace.h @@ -0,0 +1,116 @@ +#pragma once +#include "startup_stubs/gpu_material_fields.h" +#include <algorithm> +#include <cstring> +#include <d3dcompiler.h> +#include <d3d12.h> +#include <array> +#include <vector> +#include <wrl/client.h> + +namespace x2w_material_trace { +constexpr UINT null_index = 2097151; +inline UINT index(UINT value) { return (std::min)(value & 0x07ffffffu, null_index); } +struct Record { + Microsoft::WRL::ComPtr<ID3D12Resource> source; + UINT64 offset{}, bytes{}; + x2w_material::Mask fields{}; +}; +using Words = std::array<UINT, 16>; +template<class State> +inline void copy_record(ID3D12GraphicsCommandList* list, const Record& r, ID3D12Resource* readback, + D3D12_RESOURCE_STATES before, State&& state) +{ + if (!(before & D3D12_RESOURCE_STATE_COPY_SOURCE)) state(D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(readback, 0, r.source.Get(), r.offset, x2w_material::byte_count(r.fields)); + if (!(before & D3D12_RESOURCE_STATE_COPY_SOURCE)) state(before); +} +inline bool cpu_words(const Record& r, Words& words) +{ + D3D12_HEAP_PROPERTIES props{}; + D3D12_HEAP_FLAGS flags{}; + const UINT size = x2w_material::byte_count(r.fields); + if (!size || !r.source || r.bytes < size || FAILED(r.source->GetHeapProperties(&props, &flags)) || + props.Type != D3D12_HEAP_TYPE_UPLOAD) return false; + void* data{}; + D3D12_RANGE read{SIZE_T(r.offset), SIZE_T(r.offset + size)}, none{}; + if (FAILED(r.source->Map(0, &read, &data))) return false; + std::memcpy(words.data(), static_cast<const unsigned char*>(data) + r.offset, size); + r.source->Unmap(0, &none); + return true; +} +struct Slot { + UINT index{}, format{}, view_format{}, dimension{}, width{}, height{}; + UINT64 host{}, texture_address{}; + std::array<UINT, 8> words{}; + bool lazy{}, late{}; + const char* material_retry = "none"; +}; +struct Probe { + Microsoft::WRL::ComPtr<ID3D12RootSignature> root; + Microsoft::WRL::ComPtr<ID3D12PipelineState> pipeline; + Microsoft::WRL::ComPtr<ID3D12Resource> buffer, readback; + UINT raw_slot{}, base{}; + x2w_material::Mask fields{}; + std::vector<Slot> slots; +}; +inline bool init(ID3D12Device* device, Probe& p) +{ + using Microsoft::WRL::ComPtr; + constexpr char source[] = + "ByteAddressBuffer records:register(t0); RWByteAddressBuffer words:register(u0);" + "cbuffer Params:register(b0){uint offset; uint count;};" + "[numthreads(1,1,1)] void main(){for(uint i=0;i<count;i++)" + "words.Store(i*4,records.Load(offset+i*4));}"; + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[3]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[2].Constants.Num32BitValues = 2; + D3D12_ROOT_SIGNATURE_DESC sig{3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> root, cs; + if (FAILED(D3D12SerializeRootSignature(&sig, D3D_ROOT_SIGNATURE_VERSION_1, &root, nullptr)) || + FAILED(device->CreateRootSignature(0, root->GetBufferPointer(), root->GetBufferSize(), IID_PPV_ARGS(&p.root))) || + FAILED(D3DCompile(source, sizeof(source)-1, "material-record", nullptr, nullptr, "main", "cs_5_0", 0, 0, &cs, nullptr))) + return false; + D3D12_COMPUTE_PIPELINE_STATE_DESC pipeline{}; + pipeline.pRootSignature = p.root.Get(); + pipeline.CS = {cs->GetBufferPointer(), cs->GetBufferSize()}; + if (FAILED(device->CreateComputePipelineState(&pipeline, IID_PPV_ARGS(&p.pipeline)))) return false; + D3D12_HEAP_PROPERTIES heap{}; + heap.CreationNodeMask = heap.VisibleNodeMask = 1; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = sizeof(Words); + d.Height = d.DepthOrArraySize = d.MipLevels = d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + nullptr, IID_PPV_ARGS(&p.buffer)))) return false; + heap.Type = D3D12_HEAP_TYPE_READBACK; + d.Flags = D3D12_RESOURCE_FLAG_NONE; + return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&p.readback))); +} +inline void record(ID3D12GraphicsCommandList* list, const Probe& p, D3D12_GPU_DESCRIPTOR_HANDLE raw) +{ + list->SetComputeRootSignature(p.root.Get()); + list->SetPipelineState(p.pipeline.Get()); + list->SetComputeRootDescriptorTable(0, raw); + list->SetComputeRootUnorderedAccessView(1, p.buffer->GetGPUVirtualAddress()); + const UINT count = x2w_material::byte_count(p.fields) / 4; + const UINT constants[]{p.base, count}; + list->SetComputeRoot32BitConstants(2, 2, constants, 0); + list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {p.buffer.Get(), 0, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE}; + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(p.readback.Get(), 0, p.buffer.Get(), 0, count * 4); + std::swap(barrier.Transition.StateBefore, barrier.Transition.StateAfter); + list->ResourceBarrier(1, &barrier); +} +} diff --git a/src/startup_stubs/gpu_memory.h b/src/startup_stubs/gpu_memory.h new file mode 100644 index 0000000000..29c9fee348 --- /dev/null +++ b/src/startup_stubs/gpu_memory.h @@ -0,0 +1,328 @@ +#pragma once + +#include "gpu_abi.h" +#include <wrl/client.h> +#include <algorithm> +#include <array> +#include <atomic> +#include <cstring> +#include <mutex> +#include <unordered_map> +#include <unordered_set> +#include <vector> + +namespace x2w_vmemory { +struct BuildRecording; +using Microsoft::WRL::ComPtr; +namespace abi = x2w_gpu::abi; +constexpr UINT page_bytes = 65536; +constexpr UINT slots = 256; +constexpr UINT entries = 65536; +constexpr UINT fault_bytes = abi::memory_faults * sizeof(UINT); +constexpr UINT directory_bytes = abi::memory_pages * 8; + +inline bool title_page(UINT64 page) { return page >= 65536 && page < abi::memory_pages - 1; } + +enum class MapError { none, page, view, slots, updates }; + +// Keep missing-page reports separate from confirmed mappings. The reference's +// 128-per-frame and 2048-total budgets count pages it successfully maps. +class FaultPages { +public: + size_t report(const std::vector<UINT>& faults) { + std::lock_guard<std::mutex> lock(mutex_); + if (confirmed_.size() < 2048) + pending_.insert(faults.begin(), faults.end()); + return confirmed_.size(); + } + template<class Map> void seed(LONG frame, Map map) { + std::vector<UINT> known; + std::vector<UINT> requests; + size_t remaining{}; + { + std::lock_guard<std::mutex> lock(mutex_); + known = confirmed_; + if (frame > frame_) { frame_ = frame; admitted_ = 0; } + if (frame == frame_ && admitted_ < 128 && known.size() < 2048) { + remaining = (std::min)(size_t{128} - admitted_, size_t{2048} - known.size()); + requests.assign(pending_.begin(), pending_.end()); + pending_.clear(); + } + } + for (UINT page : known) map(page); + if (requests.empty()) return; + std::sort(requests.begin(), requests.end()); + std::vector<UINT> accepted; + for (UINT page : requests) { + if (!std::binary_search(known.begin(), known.end(), page) && map(page)) { + accepted.push_back(page); + if (accepted.size() == remaining) break; + } + } + std::lock_guard<std::mutex> lock(mutex_); + for (UINT page : accepted) { + if (frame != frame_ || admitted_ == 128 || confirmed_.size() == 2048) { + if (confirmed_.size() < 2048) pending_.insert(page); + continue; + } + auto pos = std::lower_bound(confirmed_.begin(), confirmed_.end(), page); + if (pos == confirmed_.end() || *pos != page) { + confirmed_.insert(pos, page); + ++admitted_; + } + } + } +private: + std::mutex mutex_; + std::vector<UINT> confirmed_; + std::unordered_set<UINT> pending_; + LONG frame_ = -1; + size_t admitted_ = 0; +}; + +inline bool buffer(ID3D12Device* dev, UINT64 size, D3D12_HEAP_TYPE type, bool uav, ID3D12Resource** out, + D3D12_RESOURCE_STATES initial = D3D12_RESOURCE_STATE_COMMON) +{ + D3D12_HEAP_PROPERTIES hp{}; + hp.Type = type; + hp.CreationNodeMask = hp.VisibleNodeMask = 1; + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = size; + d.Height = d.DepthOrArraySize = d.MipLevels = d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (uav) d.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const auto state = type == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ : + type == D3D12_HEAP_TYPE_READBACK ? D3D12_RESOURCE_STATE_COPY_DEST : initial; + return SUCCEEDED(dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, IID_PPV_ARGS(out))); +} + +// Per recording and view heap. The GPU sees directory changes in command order. +// Staging entries are append-only. Their storage and the source windows survive every submit. +struct Recording { + x2w_gpu::GpuHostHeap* heap = nullptr; + UINT base = 0; + ComPtr<ID3D12Resource> directory, faults, results, staging, zeros; + std::vector<ComPtr<ID3D12Resource>> windows; + struct ReadAlias { UINT64 original; UINT chunk_slot, offset, rows; }; + std::unordered_map<UINT, ReadAlias> read_aliases; + std::vector<std::pair<UINT, UINT>> restore_rows; + std::vector<ID3D12Resource*> ordinary_reads; + UINT alias_chunk = 0, alias_used = 0; + std::unordered_set<ID3D12Resource*> permanent_uavs; + std::unordered_map<UINT, UINT64> addresses; + std::unordered_set<UINT> absent; + std::unordered_set<UINT64> ranges; + std::unordered_set<UINT> refreshed; + std::unordered_set<UINT64> packed_seen; + std::shared_ptr<BuildRecording> build; + UINT updates = 0; + std::array<UINT, 2>* data = nullptr; + bool closed = false; + bool faults_seeded = false; + bool initialized = false; + bool writable_mode = false; + bool claimed = false; + inline static std::atomic<UINT> active{0}; + ~Recording() + { + if (data) staging->Unmap(0, nullptr); + if (claimed) --active; + } + + bool create(ID3D12Device* d, bool* at_capacity = nullptr) + { + // Each live recording holds a 16 MiB directory. Reaching the limit refuses + // this bind until a recording retires; nothing in flight is reused. + constexpr UINT directory_budget = 512u << 20; + if (active.fetch_add(1) >= directory_budget / directory_bytes) { + --active; + if (at_capacity) *at_capacity = true; + return false; + } + claimed = true; + static std::mutex lock; + static ComPtr<ID3D12Device> cached_device; + static ComPtr<ID3D12Resource> cached_zero; + D3D12_RANGE none{}; + { + std::lock_guard<std::mutex> guard(lock); + if (cached_device.Get() != d || !cached_zero) { + ComPtr<ID3D12Resource> zero; + void* mapped = nullptr; + if (!buffer(d, directory_bytes, D3D12_HEAP_TYPE_UPLOAD, false, &zero) || + FAILED(zero->Map(0, &none, &mapped))) return false; + std::memset(mapped, 0, directory_bytes); + zero->Unmap(0, nullptr); + cached_zero = zero; + cached_device = d; + } + zeros = cached_zero; + } + return buffer(d, directory_bytes, D3D12_HEAP_TYPE_DEFAULT, false, &directory) && + buffer(d, fault_bytes, D3D12_HEAP_TYPE_DEFAULT, true, &faults) && + buffer(d, fault_bytes, D3D12_HEAP_TYPE_READBACK, false, &results) && + buffer(d, UINT64{entries} * 8, D3D12_HEAP_TYPE_UPLOAD, false, &staging) && + SUCCEEDED(staging->Map(0, &none, reinterpret_cast<void**>(&data))); + } + template<class State> void begin(ID3D12GraphicsCommandList* list, State state) + { + if (initialized) return; + // A closed native list may be submitted more than once. Its initial map and + // fault set must be empty every time the recording starts executing. + state(directory.Get(), D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(directory.Get(), 0, zeros.Get(), 0, directory_bytes); + state(faults.Get(), D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(faults.Get(), 0, zeros.Get(), 0, fault_bytes); + initialized = true; + } + template<class Find, class View, class State> + void map(ID3D12GraphicsCommandList* list, UINT page, Find find, View view, State state) + { + if (!title_page(page) || addresses.count(page) || absent.count(page) || addresses.size() >= entries) return; + UINT64 offset = 0; + ID3D12Resource* window = nullptr; + if (!find(UINT64{page} * page_bytes, &window, &offset) || !window) { + absent.insert(page); + return; + } + map_to(list, page, window, offset, false, view, state); + } + template<class View, class State> + bool map_to(ID3D12GraphicsCommandList* list, UINT page, ID3D12Resource* window, UINT64 offset, + bool writable, View view, State state, bool permanent = false, MapError* error = nullptr) + { + const auto reject = [&](MapError why) { if (error) *error = why; return false; }; + if (!title_page(page) || !window) return reject(MapError::page); + const auto desc = window->GetDesc(); + if (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) || offset % 4 || + desc.Width > UINT32_MAX || offset > desc.Width || page_bytes > desc.Width - offset) return reject(MapError::view); + UINT number = 1; + for (const auto& w : windows) { + if (w.Get() == window) break; + ++number; + } + if (number > windows.size()) { + if (number >= slots) return reject(MapError::slots); + windows.emplace_back(window); + view(base + number, window, desc.Width); + } + if (permanent) permanent_uavs.insert(window); + const UINT permission = writable ? 0 : abi::memory_read_only; + const UINT64 binding = ((UINT64{number} | permission) << 32) | offset; + if (auto known = addresses.find(page); known != addresses.end() && known->second == binding) return true; + if (updates == entries) return reject(MapError::updates); + const auto i = updates++; + begin(list, state); + data[i] = {permission | number, UINT(offset)}; + addresses[page] = binding; + state(directory.Get(), D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(directory.Get(), UINT64{page} * 8, staging.Get(), i * 8, 8); + return true; + } + template<class State> void restore_read_aliases(ID3D12GraphicsCommandList* list, State state) + { + if (!restore_rows.empty()) { + state(directory.Get(), D3D12_RESOURCE_STATE_COPY_DEST); + for (const auto& [page, row] : restore_rows) + list->CopyBufferRegion(directory.Get(), UINT64{page} * 8, staging.Get(), UINT64{row} * 8, 8); + restore_rows.clear(); + } + ordinary_reads.clear(); + } + + // The directory shader loads through a UAV even for protected pages. Give it + // a GPU-time snapshot when a normal shader binding reads the same resource. + template<class View, class State> + bool allow_ordinary_reads(ID3D12GraphicsCommandList* list, const std::vector<ID3D12Resource*>& reads, + const std::vector<ID3D12Resource*>& writes, D3D12_RESOURCE_STATES read_state, View view, State state) + { + if (reads.empty()) return true; + std::array<bool, slots> conflict{}; + std::vector<ID3D12Resource*> shared; + for (UINT i = 0; i < windows.size(); ++i) { + auto* w = windows[i].Get(); + if (std::find(reads.begin(), reads.end(), w) == reads.end()) continue; + if (writable_mode || permanent_uavs.count(w) || std::find(writes.begin(), writes.end(), w) != writes.end()) return false; + conflict[i + 1] = true; + shared.push_back(w); + } + if (shared.empty()) return true; + constexpr UINT chunk_pages = 64, chunk_bytes = chunk_pages * page_bytes; + std::vector<UINT> pages; + for (const auto& [page, binding] : addresses) { + const UINT entry = UINT(binding >> 32); + if (!conflict[entry & ~abi::memory_read_only]) continue; + if (!(entry & abi::memory_read_only)) return false; + auto found = read_aliases.find(page); + if (found == read_aliases.end() || found->second.original != binding) { + if (updates > entries - 2) return false; + if (!alias_chunk || alias_used == chunk_pages) { + if (windows.size() >= slots - 1) return false; + ComPtr<ID3D12Device> device; + ComPtr<ID3D12Resource> target; + if (FAILED(directory->GetDevice(IID_PPV_ARGS(&device))) || + !buffer(device.Get(), chunk_bytes, D3D12_HEAP_TYPE_DEFAULT, true, &target)) return false; + windows.push_back(target); + alias_chunk = UINT(windows.size()); + alias_used = 0; + view(base + alias_chunk, target.Get(), chunk_bytes); + } + const UINT offset = alias_used++ * page_bytes; + read_aliases[page] = {binding, alias_chunk, offset, updates}; + data[updates++] = {alias_chunk | abi::memory_read_only, offset}; + data[updates++] = {entry, UINT(binding)}; + } + pages.push_back(page); + } + // All slots and immutable directory patches exist before changing GPU-visible state. + if (!pages.empty()) state(directory.Get(), D3D12_RESOURCE_STATE_COPY_DEST); + for (auto* source : shared) state(source, D3D12_RESOURCE_STATE_COPY_SOURCE); + for (auto page : pages) { + const auto& a = read_aliases.at(page); + const UINT source = UINT(a.original >> 32) & ~abi::memory_read_only; + auto* dest = windows[a.chunk_slot - 1].Get(); + state(dest, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(dest, a.offset, windows[source - 1].Get(), UINT(a.original), page_bytes); + list->CopyBufferRegion(directory.Get(), UINT64{page} * 8, staging.Get(), UINT64{a.rows} * 8, 8); + restore_rows.emplace_back(page, a.rows + 1); + } + for (auto* source : shared) state(source, read_state); + ordinary_reads = std::move(shared); + return true; + } + + template<class State> void ready(ID3D12GraphicsCommandList* list, State state) + { + // Reads from an unseeded directory return zero and report the missing + // pages. Clear both buffers before this first dispatch, including on replay. + begin(list, state); + state(directory.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + state(faults.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + for (const auto& w : windows) + if (!permanent_uavs.count(w.Get()) && std::find(ordinary_reads.begin(), ordinary_reads.end(), w.Get()) == ordinary_reads.end()) + state(w.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + template<class State> void close(ID3D12GraphicsCommandList* list, State state) + { + if (!initialized) return; + state(faults.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(results.Get(), 0, faults.Get(), 0, fault_bytes); + closed = true; + } + // Call only after all fences for this recording passed. + std::vector<UINT> read_faults() const + { + std::vector<UINT> pages; + if (!initialized || !closed) return pages; + D3D12_RANGE range{0, fault_bytes}; + UINT* words = nullptr; + if (FAILED(results->Map(0, &range, reinterpret_cast<void**>(&words)))) return pages; + for (UINT i = 1; i < abi::memory_faults; ++i) + if (title_page(words[i])) pages.push_back(words[i]); + D3D12_RANGE none{}; + results->Unmap(0, &none); + return pages; + } +}; +} diff --git a/src/startup_stubs/gpu_memory_arena.h b/src/startup_stubs/gpu_memory_arena.h new file mode 100644 index 0000000000..9bbffc1a6a --- /dev/null +++ b/src/startup_stubs/gpu_memory_arena.h @@ -0,0 +1,207 @@ +#pragma once + +#include "gpu_memory.h" +#include <d3dcompiler.h> + +namespace x2w_vmemory { +constexpr UINT arena_bytes = 64 << 20; +constexpr UINT arena_pages = arena_bytes / page_bytes; +constexpr UINT max_arena_pages = 3u << 14; + +// Length of a version 6 packed structure, including its markers and final 64-byte node. +inline UINT packed_bytes(UINT64 header) +{ + const UINT version = UINT(header); + const UINT64 nodes = header >> 32; + const auto size = (nodes + 1) * 64; + return (version & 65535) == 6 && ((version >> 16) & 0x8100) == 0x8100 && nodes && size <= (64u << 20) ? UINT(size) : 0; +} + +struct Arena { + ComPtr<ID3D12Resource> bytes, previous; + UINT used = 0; +}; +struct Place { + std::shared_ptr<Arena> arena; + UINT offset = 0; + ComPtr<ID3D12Resource> source; + UINT64 source_offset = 0; + UINT64 cpu_identity = 0; +}; +struct CopyBack { + Place page; + UINT offset; + UINT bytes; +}; +struct PageChoice { + Place overlay; + ID3D12Resource* source = nullptr; + UINT64 source_offset = 0; + const void* owner = nullptr; // a live title buffer holding the entire page +}; +struct BuildRecording { + std::unordered_map<UINT, PageChoice> pages; + std::unordered_map<UINT, const char*> unavailable_pages; + std::unordered_set<UINT64> scanned_uploads; + std::vector<UINT_PTR> reservations; + bool took_reservations = false; + UINT cpu_pages = 0; + UINT64 grant_epoch = 0; +}; + +// The overlay and previous title dwords stay on the card across lists. Compare at +// execution time, after queue waits for streaming. An unchanged title dword leaves +// the builder's GPU result intact. Refreshes never copy an arena to the title. +class Arenas { + std::mutex lock_; + ComPtr<ID3D12Device> device_; + ComPtr<ID3D12RootSignature> root_; + ComPtr<ID3D12PipelineState> pso_; + std::vector<std::shared_ptr<Arena>> arenas_; + std::unordered_map<UINT, Place> places_; + // Per structure (old header, last frame, resend decision), updated on the GPU + // in submission order, including when a closed list is replayed. + ComPtr<ID3D12Resource> decisions_; + std::unordered_map<UINT64, UINT> packed_; + std::unordered_set<const void*> opened_; + std::atomic<UINT64> grant_epoch_{0}; + +public: + bool open(const void* identity, bool grant) + { + std::lock_guard<std::mutex> lock(lock_); + if (grant && opened_.insert(identity).second) ++grant_epoch_; + return opened_.count(identity) != 0; + } + void forget(const void* identity) + { + std::lock_guard<std::mutex> lock(lock_); + if (opened_.erase(identity)) ++grant_epoch_; + } + UINT64 grant_epoch() const { return grant_epoch_.load(); } + bool create(ID3D12Device* d) + { + std::lock_guard<std::mutex> lock(lock_); + if (pso_) return device_.Get() == d; + static constexpr char code[] = R"( + ByteAddressBuffer source : register(t0); + RWByteAddressBuffer oldTitle : register(u0); + RWByteAddressBuffer overlay : register(u1); + RWByteAddressBuffer decisions : register(u2); + cbuffer Args : register(b0) { uint sourceAt, arenaAt, count, mode, frame; } + [numthreads(64,1,1)] void merge(uint i:SV_DispatchThreadID) { + if (mode == 0xfffffffe) { + if (i < count) oldTitle.Store(sourceAt + i*4,overlay.Load(arenaAt + i*4)); + return; + } + if (mode == 0xffffffff) { + if (i != 0) return; + uint2 header = source.Load2(sourceAt); + uint4 prev = decisions.Load4(arenaAt); + bool matches = (header.x & 0xffff) == 6 && ((header.x >> 16) & 0x8100) == 0x8100 + && header.y > 0 && header.y < 1048576 && ((header.y+1)*64 == count); + bool fresh = any(header != prev.xy) || (frame > prev.z && frame - prev.z > 8); + decisions.Store4(arenaAt,uint4(header,frame,matches && fresh ? 1 : 0)); + return; + } + if (i >= count) return; + uint x = source.Load(sourceAt + i*4), at = arenaAt + i*4; + uint before = oldTitle.Load(at); + bool resend = mode == 1; + if (mode >= 2) resend = decisions.Load((mode-2)*16+12) != 0; + if (resend || x != before) { overlay.Store(at,x); oldTitle.Store(at,x); } + })"; + ComPtr<ID3DBlob> cs, blob, errors; + if (FAILED(D3DCompile(code, sizeof(code)-1, nullptr, nullptr, nullptr, "merge", "cs_5_1", D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, &cs, &errors))) return false; + D3D12_ROOT_PARAMETER args[5]{}; + args[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + args[1].ParameterType = args[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + args[2].Descriptor.ShaderRegister = 1; + args[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + args[3].Constants.Num32BitValues = 5; + args[4].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + args[4].Descriptor.ShaderRegister = 2; + D3D12_ROOT_SIGNATURE_DESC desc{5, args}; + if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &errors)) || + FAILED(d->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root_)))) return false; + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root_.Get(); + pd.CS = {cs->GetBufferPointer(), cs->GetBufferSize()}; + if (!buffer(d, 65536 * 16, D3D12_HEAP_TYPE_DEFAULT, true, &decisions_, D3D12_RESOURCE_STATE_UNORDERED_ACCESS) || + FAILED(d->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pso_)))) return false; + device_ = d; + return true; + } + bool place(UINT page, ID3D12Resource* source, UINT64 at, Place& out, UINT64 cpu_identity = 0, bool* full = nullptr) + { + std::lock_guard<std::mutex> lock(lock_); + auto found = places_.find(page); + if (found != places_.end() && (cpu_identity ? found->second.cpu_identity == cpu_identity : + found->second.source.Get() == source && found->second.source_offset == at)) { + out = found->second; + if (cpu_identity) out.source = source; // immutable snapshot for this recording + return true; + } + // Allocate paired payload and preceding-title slabs on demand. + // A remapped page takes a new slot; recorded GPU work retains its old bytes. + if (arenas_.empty() || arenas_.back()->used == arena_pages) { + if (arenas_.size() >= max_arena_pages / arena_pages) { if (full) *full = true; return false; } + auto a = std::make_shared<Arena>(); + if (!buffer(device_.Get(), arena_bytes, D3D12_HEAP_TYPE_DEFAULT, true, &a->bytes, D3D12_RESOURCE_STATE_UNORDERED_ACCESS) || + !buffer(device_.Get(), arena_bytes, D3D12_HEAP_TYPE_DEFAULT, true, &a->previous, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)) return false; + arenas_.push_back(a); + } + auto a = arenas_.back(); + out = {a, a->used++ * page_bytes, source, at, cpu_identity}; + places_[page] = out; + if (cpu_identity) places_[page].source.Reset(); + return true; + } + bool lookup(UINT page, ID3D12Resource* source, UINT64 at, Place& out) + { + std::lock_guard<std::mutex> lock(lock_); + const auto found = places_.find(page); + if (found == places_.end() || found->second.source.Get() != source || found->second.source_offset != at) return false; + out = found->second; + return true; + } + UINT packed_slot(UINT64 address) + { + std::lock_guard<std::mutex> lock(lock_); + if (auto it = packed_.find(address); it != packed_.end()) return it->second; + const UINT slot = UINT(packed_.size()); + if (slot >= 65536) return UINT32_MAX; + packed_.emplace(address, slot); + return slot; + } + template<class State> void run(ID3D12GraphicsCommandList* l, const Place& p, UINT source_at, + UINT target, UINT count, UINT mode, UINT frame, State state, ID3D12Resource* zero = nullptr) + { + const bool publishing = mode == UINT32_MAX - 1; + if (!p.cpu_identity) + state(p.source.Get(), publishing ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS : D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + D3D12_RESOURCE_BARRIER order{}; + order.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + l->ResourceBarrier(1, &order); + l->SetComputeRootSignature(root_.Get()); + l->SetPipelineState(pso_.Get()); + l->SetComputeRootShaderResourceView(0, (publishing ? zero : p.source.Get())->GetGPUVirtualAddress()); + l->SetComputeRootUnorderedAccessView(1, (publishing ? p.source.Get() : p.arena->previous.Get())->GetGPUVirtualAddress()); + l->SetComputeRootUnorderedAccessView(2, p.arena->bytes->GetGPUVirtualAddress()); + l->SetComputeRootUnorderedAccessView(4, decisions_->GetGPUVirtualAddress()); + const UINT values[]{source_at, target, count, mode, frame}; + l->SetComputeRoot32BitConstants(3, 5, values, 0); + l->Dispatch(mode == UINT32_MAX ? 1 : (count + 63)/64, 1, 1); + l->ResourceBarrier(1, &order); + } + template<class State> void publish(ID3D12GraphicsCommandList* l, const CopyBack& range, State state, ID3D12Resource* zero) + { + const auto& p = range.page; + run(l, p, UINT(p.source_offset) + range.offset, p.offset + range.offset, range.bytes / 4, UINT32_MAX-1, 0, state, zero); + } + template<class State> void merge(ID3D12GraphicsCommandList* l, const Place& p, UINT off, UINT size, UINT mode, State state) + { + run(l, p, UINT(p.source_offset) + off, p.offset + off, size / 4, mode, 0, state); + } +}; +} diff --git a/src/startup_stubs/gpu_memory_store.inl b/src/startup_stubs/gpu_memory_store.inl new file mode 100644 index 0000000000..bcaf2a8466 --- /dev/null +++ b/src/startup_stubs/gpu_memory_store.inl @@ -0,0 +1,251 @@ +// Included inside vbind after memory_window and the heap/binding helpers. +x2w_vmemory::Arenas& builder_arenas() +{ + static auto* arenas = new x2w_vmemory::Arenas; + return *arenas; +} +bool directory_only_builder(const x2w_gpu::GpuShader& sh) +{ + if (!sh.builder || !sh.root_cbvs.empty()) return false; + for (auto i : sh.root_srvs) if (i != abi::slot_memory) return false; + for (auto i : sh.root_uavs) if (i != abi::slot_faults) return false; + for (const auto& u : sh.used) + if (u.root != GpuRootType::descriptor && u.root != GpuRootType::constants) return false; + return true; +} + +// A fallback is limited to an allocation the title owns and a whole committed, +// readable page. The immutable upload snapshot belongs to this recording. +UINT64 cpu_page(Wrapper* self, x2w_vmemory::BuildRecording& build, u64 at, ID3D12Resource** source, const char*& why) +{ + using namespace x2w_vmemory; + if (build.cpu_pages >= 512) { why = "cpu-page-limit"; return 0; } + if (!build.took_reservations) { + using Ranges = SIZE_T(WINAPI*)(UINT_PTR*,SIZE_T); + static const auto ranges = reinterpret_cast<Ranges>(GetProcAddress(GetModuleHandleW(L"xmem.dll"),"x2w_xmem_reserved_ranges")); + if (ranges) { + build.reservations.resize(2*4096); + const auto n = ranges(build.reservations.data(),4096); + build.reservations.resize(2*(std::min<size_t>)(n,4096)); + } + build.took_reservations = true; + } + u64 first = 0, last = 0; + bool owned = (known_private(at,&first,&last) || buffer_extent(at,&first,&last,nullptr,page_bytes)) && last-at >= page_bytes; + for (size_t i = 0; !owned && i+1 < build.reservations.size(); i+=2) { + const auto start = build.reservations[i], len = build.reservations[i+1]; + owned = len >= page_bytes && at >= start && at-start <= len-page_bytes; + } + if (!owned) { + std::lock_guard<std::mutex> guard(builder_upload_lock); + owned = std::any_of(builder_upload_blocks.begin(),builder_upload_blocks.end(), + [&](u64 base){return at>=base && at-base <= (64ull<<20)-page_bytes;}); + } + if (!owned && self->own().list_uploads) + for (const auto& p : self->own().list_uploads->pages) { + const auto base = reinterpret_cast<u64>(p->cpu); + if (p->size >= page_bytes && at >= base && at-base <= p->size-page_bytes) { owned = true; break; } + } + MEMORY_BASIC_INFORMATION info{}; + if (!owned) { why = "unowned-page"; return 0; } + why = "unreadable-page"; + if (VirtualQuery(reinterpret_cast<void*>(at),&info,sizeof(info)) != sizeof(info) || + info.State != MEM_COMMIT || (info.Protect & (PAGE_NOACCESS | PAGE_GUARD)) || + at - reinterpret_cast<u64>(info.BaseAddress) + page_bytes > info.RegionSize) return 0; + ComPtr<ID3D12Resource> up; + why = "cpu-snapshot-allocation"; + if (!buffer(device_of(the_device),page_bytes,D3D12_HEAP_TYPE_UPLOAD,false,&up)) return 0; + void* data = nullptr; + D3D12_RANGE none{}; + if (FAILED(up->Map(0,&none,&data))) return 0; + SIZE_T got = 0; + why = "cpu-snapshot-read"; + const bool copied = ReadProcessMemory(GetCurrentProcess(),reinterpret_cast<void*>(at),data,page_bytes,&got) && got == page_bytes; + up->Unmap(0,nullptr); + if (!copied) return 0; + *source = up.Detach(); + ++build.cpu_pages; + return reinterpret_cast<u64>(info.AllocationBase); +} + +bool builder_pages(Wrapper* self, ID3D12GraphicsCommandList* list, GpuListState& s, + const Bound& b, const x2w_gpu::GpuShader& shader, x2w_vmemory::Recording& m, + std::vector<x2w_vmemory::CopyBack>& pending) +{ + using namespace x2w_vmemory; + auto& arenas = builder_arenas(); + const char* cause = nullptr; + u64 fault_address = 0; + auto reject = [&](const char* reason, u64 at) { + if (!cause) { cause = reason; fault_address = at; } + return false; + }; + auto report = [&] { + static LONG refusals; + const auto n = InterlockedIncrement(&refusals); + if (n <= 8 || (n & (n - 1)) == 0) + log("x2w-gpu arena refusal: frame=%ld count=%ld key=%s cause=%s address=0x%llx pages=%zu windows=%zu updates=%u", + frame_number, n, shader.key, cause, fault_address, m.addresses.size(), m.windows.size(), m.updates); + return false; + }; + if (!arenas.create(device_of(the_device))) { reject("device-setup", 0); return report(); } + if (!m.build) m.build = std::make_shared<BuildRecording>(); + auto& build = *m.build; + const auto state = [&](auto* resource, auto next) { require_state(self, resource, next); }; + const auto view = [&](UINT index, auto* resource, UINT64 bytes) { gpu_heap_raw_uav_at(m.heap, index, resource, 0, bytes); }; + std::vector<std::pair<u64,u64>> small_outputs; + if (shader.builder) { + for (const auto& u : shader.used) { + const auto* root = s.roots.at(true, u.slot); + if (u.kind != GpuResourceType::uav || u.root != GpuRootType::descriptor || !root || !root->address) continue; + u64 start = 0, end = 0; + const Wrapper* owner = nullptr; + if (!buffer_extent(root->address, &start, &end, &owner)) continue; // outside a buffer: the arena takes its writes + arenas.open(owner, true); + if (end - start <= (256u << 10)) { + if ((start | end) & 3) { reject("output-not-dword-aligned", root->address); return report(); } + small_outputs.emplace_back(start,end); + } + } + } + const auto epoch = arenas.grant_epoch(); + if (build.grant_epoch != epoch) { m.ranges.clear(); build.grant_epoch = epoch; } + auto page = [&](UINT n) -> PageChoice* { + if (!title_page(n) || build.unavailable_pages.count(n)) return nullptr; + auto it = build.pages.find(n); + const u64 at = u64{n} << 16; + if (it == build.pages.end()) { + PageChoice selected; + UINT64 cpu = 0; + ComPtr<ID3D12Resource> snapshot; + if (!memory_window(at, &selected.source, &selected.source_offset)) { + const char* why = nullptr; + cpu = cpu_page(self,build,at,&snapshot,why); + if (!cpu) { build.unavailable_pages.emplace(n, why); return nullptr; } + selected.source = snapshot.Get(); + selected.source_offset = 0; + } + u64 start = 0, end = 0; + const Wrapper* owner = nullptr; + if (!cpu && buffer_extent(at, &start, &end, &owner, page_bytes) && end - at >= page_bytes) selected.owner = owner; + else { + bool full = false; + if (!arenas.place(n, selected.source, selected.source_offset, selected.overlay, cpu, &full)) { + build.unavailable_pages.emplace(n, full ? "arena-page-limit" : "arena-allocation"); + return nullptr; + } + } + it = build.pages.emplace(n,std::move(selected)).first; + } + auto& p = it->second; + MapError error{}; + if (p.owner) { + m.map_to(list,n,p.source,p.source_offset,shader.builder && arenas.open(p.owner,false),view,state,false,&error); + } else { + if (m.refreshed.insert(n).second) { + arenas.merge(list,p.overlay,0,page_bytes,0,state); + s.host_roots[1] = nullptr; + s.host_pso = nullptr; + } + m.map_to(list,n,p.overlay.arena->bytes.Get(),p.overlay.offset,shader.builder,view,state,true,&error); + } + if (error != MapError::none) { + static constexpr const char* errors[] = {"", "invalid-page", "invalid-window-view", "descriptor-slots", "directory-updates"}; + reject(errors[unsigned(error)], at); + } + return &p; + }; + const auto missing = [&](UINT n, const char* fallback) { + auto it = build.unavailable_pages.find(n); + return it == build.unavailable_pages.end() ? fallback : it->second; + }; + const auto span = [&](u64 at,u64 len) { + if (at < (1ull << 32) || at >= (u64{abi::memory_pages - 1} << 16) || !len) return; + const auto first = at >> 16, last = (at + len - 1) >> 16; + if (m.ranges.insert((first << 32) | last | (shader.builder ? 1ull<<63 : 0)).second) + for (auto n = first; n <= last; ++n) page(UINT(n)); + }; + // A checked packed header covers its actual structure. Re-seed just those bytes + // if the GPU sees a new header at submission, or the last use was >8 frames ago. + const auto packed = [&](u64 at) { + if ((at & 255) || !m.packed_seen.insert(at).second) return; + UINT64 header = 0; + SIZE_T got = 0; + if (!ReadProcessMemory(GetCurrentProcess(),reinterpret_cast<void*>(at),&header,8,&got) || got != 8) return; + const UINT len = packed_bytes(header); + if (!len) return; + auto* start = page(UINT(at >> 16)); + if (!start) { reject(missing(UINT(at >> 16), "packed-missing-page"), at); return; } + if (!start->overlay.arena) return; + const UINT slot = arenas.packed_slot(at); + if (slot == UINT32_MAX) { reject("packed-header-slots", at); return; } + const auto first = start->overlay; + arenas.run(list,first,UINT(first.source_offset + (at & 65535)),slot*16,len,UINT32_MAX,frame_number,state); + s.host_roots[1] = nullptr; + s.host_pso = nullptr; + for (u64 p = at >> 16; p <= (at + len - 1) >> 16; ++p) { + auto* c = page(UINT(p)); + if (!c || !c->overlay.arena) { reject(c ? "packed-crosses-owned-page" : missing(UINT(p), "packed-missing-page"), p << 16); return; } + const u64 base = p << 16; + const UINT lo = UINT((std::max)(base,at)-base); + const UINT hi = UINT((std::min)(base+page_bytes,at+len)-base); + arenas.merge(list,c->overlay,lo,hi-lo,slot+2,state); + } + }; + const auto in_upload = [&](u64 address) { + u64 start = 0, size = 0; + { + std::lock_guard<std::mutex> guard(builder_upload_lock); + auto it = builder_upload_spans.upper_bound(address); + if (it != builder_upload_spans.begin()) { + --it; + if (address - it->first < it->second) { start = it->first; size = it->second; } + } + } + if (!start && self->own().list_uploads) + for (const auto& a : self->own().list_uploads->allocations) + if (address >= a.cpu && address-a.cpu < a.bytes) { start = a.cpu; size = a.bytes; break; } + if (!start || !build.scanned_uploads.insert(start).second) return; + // These legacy upload blocks are process-owned and never unmapped. + for (auto* words = reinterpret_cast<const u64*>(start); size >= 8; ++words, size -= 8) { + const auto value = *words; + if (!(value & 255) && title_page(value >> 16)) page(UINT(value >> 16)); + } + }; + for (const auto& root : s.roots.compute) { + if (shader.builder && x2w_vbind::is_view(root.kind) && title_page(root.address >> 16)) { + packed(root.address); + in_upload(root.address); + span(root.address,root.kind == GpuRootKind::uav ? 4ull << 20 : 256ull << 10); + } + if (root.kind != GpuRootKind::constants) continue; + for (size_t i = 0; i < root.dwords.size(); ++i) { + const UINT lo = root.dwords[i]; + if (i+1 < root.dwords.size() && lo >= 65536 && root.dwords[i+1] >= 1 && root.dwords[i+1] <= 31) + span((u64{root.dwords[i+1]} << 32) | lo,1); + if (shader.builder && lo >= 0x01000000 && lo < 0x20000000) span(u64{lo} << 8,1); + } + } + for (const auto& u : shader.user_data) + if (u.root == GpuRootType::other && u.other == abi::user_view_address) + span(buffer_address(b,s,true,u.slot,u.dword),256ull << 10); + if (!m.faults_seeded) { + memory_fault_pages.seed(frame_number, [&](UINT n) { page(n); return m.addresses.count(n) != 0; }); + m.faults_seeded = true; + } + for (const auto& out : small_outputs) { + for (u64 n = out.first >> 16; n <= (out.second-1) >> 16; ++n) { + auto* c = page(UINT(n)); + if (!c) { reject(missing(UINT(n), "output-missing-page"), n << 16); continue; } + if (c->owner) continue; + if (c->overlay.cpu_identity) { reject("output-needs-cpu-copyback", n << 16); continue; } + const u64 base = n << 16; + const UINT lo = UINT((std::max)(base,out.first)-base); + const UINT hi = UINT((std::min)(base+page_bytes,out.second)-base); + pending.push_back({c->overlay,lo,hi-lo}); + } + } + m.begin(list,state); + if (m.writable_mode && m.addresses.empty()) reject("store-with-empty-directory", 0); + return cause ? report() : true; +} diff --git a/src/startup_stubs/gpu_packed_light.h b/src/startup_stubs/gpu_packed_light.h new file mode 100644 index 0000000000..ab01771748 --- /dev/null +++ b/src/startup_stubs/gpu_packed_light.h @@ -0,0 +1,136 @@ +#pragma once +#include <d3d12.h> +#include <wrl/client.h> +#include <vector> +#include "memory_srv_buffer.h" + +namespace x2w_packed_light { +// One table-binding pass, ending before the title's draw or dispatch can write. +struct BoundCopy { + ID3D12Resource* source = nullptr; + ID3D12Resource* destination = nullptr; + + bool contains(ID3D12Resource* from, ID3D12Resource* to) const + { + return source == from && destination == to; + } + void invalidate(ID3D12Resource* texture) + { + if (texture == source || texture == destination) *this = {}; + } +}; + +inline bool shape(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) +{ + return a.Dimension == b.Dimension && (a.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D || + a.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) && a.Width == b.Width && a.Height == b.Height && + a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels && a.MipLevels == b.MipLevels && + a.SampleDesc.Count == 1 && b.SampleDesc.Count == 1 && !a.SampleDesc.Quality && !b.SampleDesc.Quality; +} + +// Typed, uncompressed, single-plane color formats. Packed and planar YUV are excluded. +inline UINT color_bytes(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: + case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return 4; + case DXGI_FORMAT_A8_UNORM: return 1; + default: return x2w_startup::typed_buffer_format_bytes(format); + } +} + +// A native resource already passed device size limits. Without the title allocation +// size, its unpadded texels still give a lower bound on the occupied byte range. +inline UINT64 minimum_span(const D3D12_RESOURCE_DESC& desc) +{ + UINT64 width = desc.Width, height = desc.Height, depth = desc.DepthOrArraySize, bytes = 0; + for (UINT mip = 0; mip < desc.MipLevels; ++mip) { + bytes += width * height * depth * color_bytes(desc.Format); + if (width > 1) width >>= 1; + if (height > 1) height >>= 1; + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && depth > 1) depth >>= 1; + } + return bytes; +} + +inline bool compatible(const D3D12_RESOURCE_DESC& writer, const D3D12_RESOURCE_DESC& reader) +{ + const UINT count = writer.MipLevels * (writer.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1u : writer.DepthOrArraySize); + const UINT bytes = color_bytes(writer.Format); + return count && count <= 128 && bytes && bytes == color_bytes(reader.Format) && writer.Format != reader.Format && + (writer.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) && + !(writer.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && + !(reader.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) && shape(writer, reader); +} + +struct Copy { + LONG last_trace_frame{}; + Microsoft::WRL::ComPtr<ID3D12Resource> source, destination, scratch; + std::vector<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> source_rows, dest_rows; + + bool init(ID3D12Device* device, ID3D12Resource* from, ID3D12Resource* to, ID3D12Resource* reusable = nullptr) + { + const auto a = from->GetDesc(), b = to->GetDesc(); + if (!compatible(a, b)) return false; + const UINT count = a.MipLevels * (a.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1u : a.DepthOrArraySize); + + source_rows.resize(count); + dest_rows.resize(count); + UINT64 bytes = 0, dest_bytes = 0; + device->GetCopyableFootprints(&a, 0, count, 0, source_rows.data(), nullptr, nullptr, &bytes); + device->GetCopyableFootprints(&b, 0, count, 0, dest_rows.data(), nullptr, nullptr, &dest_bytes); + if (!bytes || bytes != dest_bytes || bytes == UINT64_MAX) return false; + for (UINT i = 0; i < count; ++i) { + const auto& x = source_rows[i]; + const auto& y = dest_rows[i]; + if (x.Offset != y.Offset || x.Footprint.RowPitch != y.Footprint.RowPitch || + x.Footprint.Depth != y.Footprint.Depth || x.Footprint.Height != y.Footprint.Height || + x.Footprint.Width != y.Footprint.Width) return false; + } + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = bytes; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (reusable && reusable->GetDesc().Width >= bytes) scratch = reusable; + else if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&scratch)))) return false; + source = from; + destination = to; + return true; + } + + template<class Require> + void record(ID3D12GraphicsCommandList* list, Require require, D3D12_RESOURCE_STATES previous_source_state) + { + auto transfer = [&](bool to_buffer) { + auto& rows = to_buffer ? source_rows : dest_rows; + for (UINT i = 0; i < rows.size(); ++i) { + D3D12_TEXTURE_COPY_LOCATION linear{}, texture{}; + linear.pResource = scratch.Get(); + linear.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + linear.PlacedFootprint = rows[i]; + texture.pResource = to_buffer ? source.Get() : destination.Get(); + texture.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + texture.SubresourceIndex = i; + if (to_buffer) list->CopyTextureRegion(&linear, 0, 0, 0, &texture, nullptr); + else list->CopyTextureRegion(&texture, 0, 0, 0, &linear, nullptr); + } + }; + require(source.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE); + require(scratch.Get(), D3D12_RESOURCE_STATE_COPY_DEST); + transfer(true); + require(source.Get(), previous_source_state); + require(scratch.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE); + require(destination.Get(), D3D12_RESOURCE_STATE_COPY_DEST); + transfer(false); + require(scratch.Get(), D3D12_RESOURCE_STATE_COMMON); + } +}; +} diff --git a/src/startup_stubs/gpu_pipeline.inl b/src/startup_stubs/gpu_pipeline.inl new file mode 100644 index 0000000000..d6e042b504 --- /dev/null +++ b/src/startup_stubs/gpu_pipeline.inl @@ -0,0 +1,783 @@ +// Pipeline creation records shader metadata and owns a copy of graphics stream state. First use requests a host +// root signature and PSO. Pipelines with matching stages and state share the result. +// +// Render-target formats use desktop_format with packed_target_format stand-ins as required by the adapter. Depth +// and input elements use desktop_format. A draw with different bound targets requests a variant using +// GpuTargets. +// +// X2W_GPU_MESH=0 disables mesh pipelines. X2W_GPU_ROOT_SRV_DIRECT=1 uses unbounded root descriptors for +// title SRVs and UAVs in place of bounded one-view tables. + +// One title pipeline: what it is made of, and the host pipelines made for it. +using GpuJobs = x2w_gpu::VpBuildQueue<x2w_gpu::VpPending>; + +// Park the compiler worker in the exception callback so driver frames and driver-owned locks stay intact. The +// monitor publishes the terminal result and starts a replacement. Slots live for the process. +struct GpuCompileFault { + GpuJobs::ActiveBuild* owner = nullptr; + ULONG_PTR address = 0, instruction = 0; + DWORD tid = 0; + std::atomic<bool> ready{false}; +}; +constexpr unsigned gpu_fault_limit = 8; +GpuCompileFault gpu_faults[gpu_fault_limit]; +std::atomic<unsigned> gpu_fault_count{0}; +HANDLE gpu_fault_event = nullptr; +uintptr_t gpu_compiler_base = 0, gpu_compiler_end = 0; +thread_local bool gpu_in_compiler = false; + +std::filesystem::path gpu_cache_setting(const wchar_t* name) +{ + const DWORD size = GetEnvironmentVariableW(name, nullptr, 0); + if (!size) return {}; + std::wstring path(size, L'\0'); + const DWORD chars = GetEnvironmentVariableW(name, path.data(), size); + if (!chars || chars >= size) return {}; + path.resize(chars); + return path; +} + +// The copied reference list stays read-only. The local list belongs to the +// selected adapter/driver and records exact identities from this runtime. +const std::filesystem::path& gpu_local_fault_cache() +{ + static const auto path = gpu_cache_setting(L"X2W_GPU_LOCAL_FAULT_FILE"); + return path; +} + +LONG CALLBACK gpu_compiler_fault(EXCEPTION_POINTERS* info) +{ + auto* owner = GpuJobs::active; + const auto& fault = *info->ExceptionRecord; + const auto ip = reinterpret_cast<uintptr_t>(fault.ExceptionAddress); + if (!owner || !gpu_in_compiler || fault.ExceptionCode != EXCEPTION_ACCESS_VIOLATION || + fault.NumberParameters < 2 || fault.ExceptionInformation[0] > 1 || fault.ExceptionInformation[1] >= 0x10000 || + ip < gpu_compiler_base || ip >= gpu_compiler_end) return EXCEPTION_CONTINUE_SEARCH; + const auto index = gpu_fault_count.fetch_add(1, std::memory_order_relaxed); + if (index >= gpu_fault_limit) return EXCEPTION_CONTINUE_SEARCH; + gpu_in_compiler = false; + auto& slot = gpu_faults[index]; + slot.owner = owner; + slot.address = fault.ExceptionInformation[1]; + slot.instruction = ip; + slot.tid = GetCurrentThreadId(); + slot.ready.store(true, std::memory_order_release); + SetEvent(gpu_fault_event); + for (;;) Sleep(INFINITE); +} + +void gpu_watch_compiler_faults() +{ + while (WaitForSingleObject(gpu_fault_event, INFINITE) == WAIT_OBJECT_0) { + for (auto& slot : gpu_faults) { + if (!slot.ready.exchange(false, std::memory_order_acquire)) continue; + const auto& pending = *slot.owner->job->state; + std::string keys; + for (const auto& shader : pending.shaders) { + const auto* record = static_cast<const x2w_gpu::GpuShader*>(shader.tag); + keys += " stage " + std::to_string(shader.stage) + "=" + (record ? record->key : "missing"); + if (record && !pending.graphics && pending.shaders.size() == 1 && shader.stage == x2w_gpu::vp_stage_compute) { + const auto id = x2w_gpu::gpu_compute_pending_key(record->key); + keys += " warm-bad=" + id; + if (!gpu_local_fault_cache().empty()) { + std::ofstream out(gpu_local_fault_cache(), std::ios::app); + if (!(out << id << " compiler fault on compute " << record->key << '\n').flush()) + log("x2w-gpu could not save local compiler fault: %s", id.c_str()); + } + } + } + log("x2w-gpu compiler worker parked: tid %lu amdxc64+%llx access %llx%s", slot.tid, + static_cast<unsigned long long>(slot.instruction - gpu_compiler_base), + static_cast<unsigned long long>(slot.address), keys.c_str()); + try { slot.owner->lost(std::make_exception_ptr(std::runtime_error("AMD compiler worker parked:" + keys))); } + catch (const std::system_error& e) { log("x2w-gpu could not replace compiler worker: %s", e.what()); } + } + } +} + +void gpu_install_compiler_guard() +{ + if (x2w_gpu::gpu_env_is("X2W_GPU_COMPILER_GUARD", '0')) return; + HMODULE compiler = nullptr; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, L"amdxc64.dll", &compiler)) return; + gpu_compiler_base = reinterpret_cast<uintptr_t>(compiler); + const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(compiler); + const auto* pe = reinterpret_cast<const IMAGE_NT_HEADERS*>(gpu_compiler_base + dos->e_lfanew); + gpu_compiler_end = gpu_compiler_base + pe->OptionalHeader.SizeOfImage; + gpu_fault_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!gpu_fault_event) return; + const auto handler = AddVectoredExceptionHandler(1, gpu_compiler_fault); + if (!handler) { + CloseHandle(gpu_fault_event); + gpu_fault_event = nullptr; + return; + } + try { std::thread(gpu_watch_compiler_faults).detach(); } + catch (const std::system_error& e) { + RemoveVectoredExceptionHandler(handler); + CloseHandle(gpu_fault_event); + gpu_fault_event = nullptr; + log("x2w-gpu compiler guard unavailable: %s", e.what()); + } +} +struct GpuRequest { + std::shared_ptr<x2w_gpu::VpPending> pending = std::make_shared<x2w_gpu::VpPending>(); + std::once_flag requested; + GpuJobs::Handle job; + std::atomic<bool> reported{false}; + std::atomic<bool> timeout_reported{false}; +}; +namespace vbind { +bool compute_capture_on() +{ + static const bool enabled = x2w_local::env_on("X2W_TRACE_COMPUTE_TEXTURES"); + return enabled; +} +bool pixel_capture_on() +{ + static const bool enabled = x2w_local::env_on("X2W_TRACE_PIXEL_TEXTURES"); + return enabled; +} +} + +const x2w_gpu::ambient::Settings& indirect_light_settings() +{ + static const auto settings = [] { + x2w_gpu::ambient::Settings out{}; + auto positive = [](const char* key) { + char value[48]{}; + const DWORD n = GetEnvironmentVariableA(key, value, sizeof(value)); + char* end = nullptr; + if (!n || n >= sizeof(value)) return 0.0f; + const float f = std::strtof(value, &end); + return end && !*end && std::isfinite(f) && f > 0 ? f : 0.0f; + }; + out.level = positive("X2W_GPU_INDIRECT_LIGHT"); + out.air = positive("X2W_GPU_INDIRECT_LIGHT_AIR"); + return out; + }(); + return settings; +} + +struct GpuPipelineEntry { + x2w_gpu::ambient::Role light_role = x2w_gpu::ambient::Role::none; + GpuRequest base; + bool listed_bad = false; + bool exposure_reset = false; + std::vector<x2w_gpu::GpuStage> stages; // per pending.shaders entry + std::vector<const x2w_gpu::GpuShader*> records; + std::unique_ptr<std::string> missing_keys; // requested keys absent from the shader DB, only when tracing drops + // The pipeline for the stream's own targets, then variants for bound targets that differ. + std::mutex lock; + std::vector<std::pair<x2w_gpu::GpuTargets, std::unique_ptr<GpuRequest>>> variants; +}; + +// A made host pipeline and its view for WP3/WP4, never freed (draws recorded with it may still be in flight). +struct GpuMade { + std::shared_ptr<const x2w_gpu::VpHostPipeline> host; + x2w_gpu::GpuPipeline view; +}; + +x2w_gpu::VpPipelineCache& gpu_pipeline_cache() +{ + static auto* cache = new x2w_gpu::VpPipelineCache; + return *cache; +} + +// The views by host pipeline (one per host pipeline, shared like it). +std::mutex gpu_made_lock; +std::map<const x2w_gpu::VpHostPipeline*, GpuMade*>& gpu_made() +{ + static auto* made = new std::map<const x2w_gpu::VpHostPipeline*, GpuMade*>; + return *made; +} + +std::uint32_t gpu_vp_stage(x2w_gpu::GpuStage s) +{ + using x2w_gpu::GpuStage; + switch (s) { + case GpuStage::vertex: return x2w_gpu::vp_stage_vertex; + case GpuStage::pixel: return x2w_gpu::vp_stage_pixel; + case GpuStage::domain: return x2w_gpu::vp_stage_domain; + case GpuStage::hull: return x2w_gpu::vp_stage_hull; + case GpuStage::geometry: return x2w_gpu::vp_stage_geometry; + case GpuStage::compute: return x2w_gpu::vp_stage_compute; + case GpuStage::amplification: return x2w_gpu::vp_stage_amplification; + case GpuStage::mesh: return x2w_gpu::vp_stage_mesh; + default: return x2w_gpu::vp_stage_none; + } +} + +x2w_gpu::GpuStage gpu_stage_of(std::uint32_t vp) +{ + using x2w_gpu::GpuStage; + switch (vp) { + case x2w_gpu::vp_stage_vertex: return GpuStage::vertex; + case x2w_gpu::vp_stage_pixel: return GpuStage::pixel; + case x2w_gpu::vp_stage_domain: return GpuStage::domain; + case x2w_gpu::vp_stage_hull: return GpuStage::hull; + case x2w_gpu::vp_stage_geometry: return GpuStage::geometry; + case x2w_gpu::vp_stage_compute: return GpuStage::compute; + case x2w_gpu::vp_stage_amplification: return GpuStage::amplification; + case x2w_gpu::vp_stage_mesh: return GpuStage::mesh; + default: return GpuStage::count; + } +} + +// D3D12_FORMAT_SUPPORT1 of a format on the device, asked once per format. +UINT gpu_format_support1(DXGI_FORMAT format) +{ + static std::atomic<UINT> known[256]; // support | 0x80000000 once asked + const UINT f = static_cast<UINT>(format); + if (f < 256) { + const UINT seen = known[f].load(std::memory_order_relaxed); + if (seen) return seen & 0x7fffffffu; + } + UINT support = 0; + if (the_device) { + D3D12_FEATURE_DATA_FORMAT_SUPPORT data{format}; + if (SUCCEEDED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &data, sizeof(data)))) + support = static_cast<UINT>(data.Support1) & 0x7fffffffu; + } + if (f < 256) known[f].store(support | 0x80000000u, std::memory_order_relaxed); + return support; +} + +// Render target formats as X2W makes such textures: desktop_format, then the packed stand-in when the adapter cannot +// render to the format and can to the stand-in (packed_target_stand_in's rule for a render target). +DXGI_FORMAT gpu_target_format(std::uint32_t console) +{ + const DXGI_FORMAT format = desktop_format(static_cast<DXGI_FORMAT>(console)); + const auto* mapping = x2w_startup::packed_target_mapping(format); + if (!mapping) return format; + const UINT target = D3D12_FORMAT_SUPPORT1_RENDER_TARGET; + if (gpu_format_support1(format) & target) return format; + return gpu_format_support1(mapping->replacement) & target ? mapping->replacement : format; +} + +DXGI_FORMAT gpu_plain_format(std::uint32_t console) { return desktop_format(static_cast<DXGI_FORMAT>(console)); } + +bool gpu_readable(const void* p, std::size_t bytes) { return x2w_local::readable(p, bytes); } + +const std::wstring& gpu_reference_library_path() +{ + static const std::wstring path = [] { + constexpr auto name = L"X2W_GPU_REFERENCE_LIBRARY"; + const DWORD size = GetEnvironmentVariableW(name, nullptr, 0); + std::wstring value(size, L'\0'); + if (!size) return value; + const DWORD chars = GetEnvironmentVariableW(name, value.data(), size); + value.resize(chars < size ? chars : 0); + return value; + }(); + return path; +} + +HRESULT gpu_load_reference_compute(ID3D12Device* device, const std::vector<unsigned char>& root, + const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc, ID3D12PipelineState** out) +{ + struct Entry { + Microsoft::WRL::ComPtr<ID3D12Device> device; + std::once_flag once; + std::unique_ptr<x2w_gpu::VpReferenceLibrary> library; + HRESULT opened = E_FAIL; + }; + static std::mutex lock; + static auto* entries = new std::map<ID3D12Device*, std::unique_ptr<Entry>>; + Entry* entry; + { + std::lock_guard<std::mutex> held(lock); + auto& slot = (*entries)[device]; + if (!slot) { + slot = std::make_unique<Entry>(); + slot->device = device; + } + entry = slot.get(); + } + std::call_once(entry->once, [&] { + auto library = std::make_unique<x2w_gpu::VpReferenceLibrary>(); + entry->opened = library->open(device, gpu_reference_library_path().c_str()); + if (SUCCEEDED(entry->opened)) entry->library = std::move(library); + log("x2w-gpu read-only reference pipeline library: open 0x%08lx", static_cast<unsigned long>(entry->opened)); + }); + if (FAILED(entry->opened)) return entry->opened; + const auto name = x2w_gpu::vp_compute_library_name(root, desc.CS); + const auto start = GetTickCount64(); + const HRESULT hr = entry->library->load(name, desc, out); + static LONG hits, misses; + if (first_calls(SUCCEEDED(hr) ? hits : misses, 24) || GetTickCount64() - start >= 3000) + log("x2w-gpu reference compute %ls: load 0x%08lx in %llu ms", name.c_str(), static_cast<unsigned long>(hr), + GetTickCount64() - start); + return hr; +} + +x2w_gpu::VpMakeOptions gpu_make_options() +{ + static const x2w_gpu::VpMakeOptions options = [] { + x2w_gpu::VpMakeOptions o; + o.allow_mesh = x2w_gpu::gpu_mesh_on(); + if (!gpu_reference_library_path().empty()) o.load_compute = gpu_load_reference_compute; + o.root.bounded_root_views = !x2w_gpu::gpu_env_is("X2W_GPU_ROOT_SRV_DIRECT", '1'); + return o; + }(); + return options; +} + +const x2w_gpu::VpDeviceCaps& gpu_caps() +{ + static const x2w_gpu::VpDeviceCaps caps = [] { + const auto c = x2w_gpu::vp_device_caps(device_of(the_device)); + log("x2w-gpu pipelines: mesh shaders %d, depth bounds %d, aniso point-mip %d, root views %s, mesh %s", c.mesh_shaders, + c.depth_bounds, c.aniso_point_mip, gpu_make_options().root.bounded_root_views ? "one-view tables" : "root descriptors", + gpu_make_options().allow_mesh ? "on" : "off (X2W_GPU_MESH=0)"); + return c; + }(); + return caps; +} + +const x2w_gpu::GpuWarmBad& gpu_warm_bad() +{ + static const auto list = [] { + x2w_gpu::GpuWarmBad result; + const auto reference = gpu_cache_setting(L"X2W_GPU_WARM_BAD_FILE"); + for (const auto& path : {reference, gpu_local_fault_cache()}) { + if (path.empty()) continue; + std::ifstream input(path); + if (!input) { + if (path == reference) log("x2w-gpu could not open the configured warm-bad cache"); + continue; + } + x2w_gpu::GpuWarmBad parsed; + parsed.read(input); + if (input.bad()) log("x2w-gpu failed to read a configured warm-bad cache"); + else result.keys.merge(parsed.keys); + } + if (!reference.empty() || !gpu_local_fault_cache().empty()) + log("x2w-gpu loaded %zu warm-bad pipeline keys (single-stage compute matching)", result.keys.size()); + return result; + }(); + return list; +} + +bool gpu_drop_trace() +{ + static const bool on = x2w_local::env_on("X2W_GPU_DROP_TRACE"); + return on; +} + +void gpu_queue_request(GpuRequest& request, bool initialization); +bool gpu_synchronous_build(); + +bool gpu_create_pipeline(Wrapper* pipeline, const GpuCreateDesc& desc) +{ + if (!pipeline || desc.unreadable || !desc.stage_count) return false; + auto entry = std::make_unique<GpuPipelineEntry>(); + entry->base.pending->creation_slot = static_cast<std::uint32_t>(desc.slot); + for (std::uint32_t i = 0; i < desc.stage_count && i < std::size(desc.stages); ++i) { + const auto& code = desc.stages[i]; + const x2w_gpu::GpuShader* record = x2w_gpu::gpu_shader_by_key(code.key, code.stage); + entry->base.pending->add(x2w_gpu::vp_record_view(record, gpu_vp_stage(code.stage))); + entry->stages.push_back(code.stage); + entry->records.push_back(record); + static const char* const exposure_key = std::getenv("X2W_EXPOSURE_RESET_KEY"); + if (code.stage == x2w_gpu::GpuStage::pixel && exposure_key && std::strcmp(code.key, exposure_key) == 0) + entry->exposure_reset = true; + if (desc.stage_count == 1 && code.stage == x2w_gpu::GpuStage::compute && + (indirect_light_settings().level > 0 || vbind::compute_capture_on()) && + code.bytes && code.size) { + using Role = x2w_gpu::ambient::Role; + const std::string_view container(static_cast<const char*>(code.bytes), code.size); + static const char* const resolve = std::getenv("X2W_LIGHT_RESOLVE_MARKER"); + static const char* const radiance = std::getenv("X2W_LIGHT_RADIANCE_MARKER"); + static const char* const air = std::getenv("X2W_LIGHT_AIR_MARKER"); + if (resolve && *resolve && container.find(resolve) != container.npos) entry->light_role = Role::resolve; + else if (radiance && *radiance && container.find(radiance) != container.npos) entry->light_role = Role::radiance; + else if (air && *air && container.find(air) != container.npos) entry->light_role = Role::air; + if (entry->light_role != Role::none) + log("x2w-gpu indirect light shader %s role=%u", code.key, unsigned(entry->light_role)); + } + if (!record && gpu_drop_trace()) { + if (!entry->missing_keys) entry->missing_keys = std::make_unique<std::string>(); + *entry->missing_keys += std::string(" ") + x2w_gpu::gpu_stage_name(code.stage) + "=" + code.key; + } + } + if (desc.slot == 86) { + // Keep the parsed graphics state alongside the stage keys recorded at creation. + if (!desc.desc || desc.desc_bytes < 8 || desc.desc_bytes > 0x10000 || !x2w_local::readable(desc.desc, desc.desc_bytes)) + return false; + std::vector<std::uint64_t> copy((desc.desc_bytes + 7) / 8); + std::memcpy(copy.data(), desc.desc, desc.desc_bytes); + x2w_gpu::VpFormatMap map; + map.target = &gpu_target_format; + map.depth = &gpu_plain_format; + map.input = &gpu_plain_format; + x2w_gpu::VpStream stream = x2w_gpu::vp_parse_stream(copy.data(), desc.desc_bytes, map, &gpu_readable); + if (stream.stopped || stream.truncated) { + static LONG stops; + if (first_calls(stops, 8)) + log("x2w-gpu stream: subobject %u at +0x%zx %s; the rest is ignored", stream.stopped_kind, stream.stopped_at, + stream.truncated ? "runs past the end" : "of unknown size"); + } + // A compute stream keeps no graphics state (HostPipeline::new takes the compute stage alone). + const bool compute = desc.stage_count == 1 && desc.stages[0].stage == x2w_gpu::GpuStage::compute; + if (!compute) entry->base.pending->graphics = std::make_unique<x2w_gpu::VpGraphicsState>(std::move(stream.graphics)); + } + entry->listed_bad = gpu_warm_bad().contains(desc, entry->base.pending->graphics != nullptr); + if (entry->exposure_reset && !entry->listed_bad && !entry->base.pending->missing && the_device && !gpu_synchronous_build()) + gpu_queue_request(entry->base, true); + pipeline->own().gpu[0] = entry.release(); + return true; +} + +// The view WP3/WP4 read, made once per host pipeline. +const x2w_gpu::GpuPipeline* gpu_view_for(const std::shared_ptr<const x2w_gpu::VpHostPipeline>& host_ptr, + const x2w_gpu::VpPending& pending, + const std::vector<x2w_gpu::GpuStage>& stages) +{ + const x2w_gpu::VpHostPipeline* host = host_ptr.get(); + std::lock_guard<std::mutex> held(gpu_made_lock); + auto& slot = gpu_made()[host]; + if (slot) return &slot->view; + auto* made = new GpuMade; + made->host = host_ptr; + x2w_gpu::GpuPipeline& v = made->view; + v.compute = host->compute; + v.mesh = host->mesh; + v.rects = host->rects; + v.pso = host->pso; + if (pending.graphics) { + const auto& g = *pending.graphics; + v.color_mask = x2w_gpu::vp_host_blend(g.blend, g.targets).RenderTarget[0].RenderTargetWriteMask; + v.depth_test = g.depth.DepthEnable != FALSE; + v.depth_write = v.depth_test && g.depth.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ALL; + } + v.root = host->root; + v.stage_count = static_cast<std::uint32_t>((std::min<std::size_t>)(host->stages.size(), std::size(v.stages))); + const auto slots = [](const std::vector<x2w_gpu::VpRootView>& in, std::vector<x2w_gpu::GpuRootSlot>& out) { + for (const auto& r : in) out.push_back({r.slot, static_cast<std::uint8_t>(r.param), r.table}); + }; + for (std::uint32_t i = 0; i < v.stage_count; ++i) { + const x2w_gpu::VpBoundStage& b = host->stages[i]; + x2w_gpu::GpuPipelineStage& s = v.stages[i]; + s.shader = static_cast<const x2w_gpu::GpuShader*>(b.tag); + s.stage = gpu_stage_of(b.stage); + s.user_data_param = b.has_user_data ? b.user_data_param : UINT32_MAX; + s.user_data_dwords = b.user_data_dwords; + slots(b.root_cbvs, s.root_cbvs); + slots(b.root_srvs, s.root_srvs); + slots(b.root_uavs, s.root_uavs); + for (const auto& r : b.root_srvs) + if (r.slot == x2w_gpu::abi::slot_strides && v.strides_param == UINT32_MAX) v.strides_param = r.param; + // DispatchX: the user-data dword the host fills with the thread count along X. + if (host->compute && s.shader && b.has_user_data) + for (const auto& u : s.shader->user_data) + if (u.root == x2w_gpu::GpuRootType::other && u.other == x2w_gpu::abi::user_dispatch_threads_x) { + v.threads_x_param = b.user_data_param; + v.threads_x_dword = u.index; + } + } + v.vertex_slots = host->slots; + const x2w_gpu::VpGraphicsState* g = pending.graphics.get(); + for (std::size_t i = 0; i < host->inputs.size(); ++i) { + const auto& e = host->inputs[i]; + const UINT step = g && i < g->inputs.size() ? g->inputs[i].InstanceDataStepRate : 0; + v.inputs.push_back({e.slot, e.offset, static_cast<DXGI_FORMAT>(e.format), e.per_instance, step}); + } + v.topology_type = host->compute ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED + : host->mesh ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : x2w_gpu::vp_host_topology_type(host->topology); + v.title_topology = static_cast<std::uint32_t>(host->topology); + if (v.title_topology == x2w_gpu::vp_topology_rectangles) + log("x2w-gpu rectangle PSO %p: %s", static_cast<void*>(v.pso), v.rects ? "geometry stage" : "fallback"); + v.impl = made; + (void)stages; + slot = made; + return &made->view; +} + +bool gpu_same_targets(const x2w_gpu::GpuTargets& t, const x2w_gpu::VpGraphicsState& g) +{ + if ((t.read_depth_plane && g.depth.DepthEnable && g.depth.DepthWriteMask != D3D12_DEPTH_WRITE_MASK_ZERO) || + (t.read_stencil_plane && g.depth.StencilEnable && g.depth.StencilWriteMask)) return false; + if (t.count != g.targets.NumRenderTargets || t.dsv != g.depth_format || (t.samples ? t.samples : 1) != g.samples.Count) return false; + for (std::uint32_t i = 0; i < t.count && i < 8; ++i) + if (t.rtv[i] != g.targets.RTFormats[i]) return false; + return true; +} + +bool gpu_same(const x2w_gpu::GpuTargets& a, const x2w_gpu::GpuTargets& b) +{ + return a.read_depth_plane == b.read_depth_plane && a.read_stencil_plane == b.read_stencil_plane && + a.count == b.count && a.dsv == b.dsv && a.samples == b.samples && std::equal(a.rtv, a.rtv + (std::min)(a.count, 8u), b.rtv); +} + +struct GpuCompileWatch { + const x2w_gpu::VpShaderView* stages; + std::size_t count; + DWORD thread; + ULONGLONG started; + bool reported = false; + + std::string stage_keys() const + { + std::string keys; + for (std::size_t i = 0; i < count; ++i) { + const auto* record = static_cast<const x2w_gpu::GpuShader*>(stages[i].tag); + keys += " stage " + std::to_string(stages[i].stage) + "=" + (record ? record->key : "missing"); + } + return keys; + } + + static void CALLBACK elapsed(PTP_CALLBACK_INSTANCE, void* context, PTP_TIMER) + { + auto& watch = *static_cast<GpuCompileWatch*>(context); + static LONG reports; + if (!first_calls(reports, 48)) return; + watch.reported = true; + log("x2w-gpu PSO still building: tid %lu start tick %llu elapsed %llu ms%s", + watch.thread, watch.started, GetTickCount64() - watch.started, watch.stage_keys().c_str()); + } +}; + +bool gpu_observe_build(ID3D12Device* device, const x2w_gpu::VpDeviceCaps& caps, const x2w_gpu::VpShaderView* shaders, + std::size_t count, const x2w_gpu::VpGraphicsState* graphics, const x2w_gpu::VpMakeOptions& options, + x2w_gpu::VpHostPipeline& host, std::string& why) +{ + GpuCompileWatch watch{shaders, count, GetCurrentThreadId(), GetTickCount64()}; + static const bool every_build = x2w_gpu::gpu_env_is("X2W_GPU_PSO_WATCH", '2'); + if (every_build) { + std::string targets; + if (graphics) { + for (UINT i = 0; i < (std::min)(graphics->targets.NumRenderTargets, 8u); ++i) + targets += " rt" + std::to_string(i) + "=" + std::to_string(graphics->targets.RTFormats[i]); + targets += " depth=" + std::to_string(graphics->depth_format) + " topology=" + std::to_string(graphics->topology) + + " samples=" + std::to_string(graphics->samples.Count); + } + log("x2w-gpu PSO begin: tid %lu start tick %llu%s%s", watch.thread, watch.started, watch.stage_keys().c_str(), targets.c_str()); + const bool ok = x2w_gpu::vp_make_host_pipeline(device, caps, shaders, count, graphics, options, host, why); + log("x2w-gpu PSO end: tid %lu start tick %llu result %s", watch.thread, watch.started, ok ? "success" : why.c_str()); + return ok; + } + struct Timer { + PTP_TIMER handle; + void stop() { + if (!handle) return; + SetThreadpoolTimer(handle, nullptr, 0, 0); + WaitForThreadpoolTimerCallbacks(handle, TRUE); + CloseThreadpoolTimer(handle); + handle = nullptr; + } + ~Timer() { stop(); } + } timer{CreateThreadpoolTimer(GpuCompileWatch::elapsed, &watch, nullptr)}; + if (timer.handle) { + LARGE_INTEGER delay{}; + delay.QuadPart = -5000ll * 10000; + FILETIME due{delay.LowPart, static_cast<DWORD>(delay.HighPart)}; + SetThreadpoolTimer(timer.handle, &due, 0, 0); + } + const bool ok = x2w_gpu::vp_make_host_pipeline(device, caps, shaders, count, graphics, options, host, why); + timer.stop(); + if (watch.reported) + log("x2w-gpu PSO build returned: tid %lu start tick %llu elapsed %llu ms result %s", + watch.thread, watch.started, GetTickCount64() - watch.started, ok ? "success" : why.c_str()); + return ok; +} + +unsigned gpu_pipeline_setting(const char* name, unsigned fallback, unsigned maximum) +{ + char text[24]{}; + const DWORD size = GetEnvironmentVariableA(name, text, sizeof(text)); + if (!size || size >= sizeof(text) || text[0] == '-') return fallback; + char* end = nullptr; + const unsigned long value = std::strtoul(text, &end, 10); + return end && *end == 0 ? static_cast<unsigned>((std::min<unsigned long>)(maximum, value)) : fallback; +} + +GpuJobs& gpu_build_queue() +{ + static GpuJobs* jobs = [] { + // Workers are process-scoped; a title wrapper may be released while its build is pending. + HMODULE module = nullptr; + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, + reinterpret_cast<LPCWSTR>(&gpu_build_queue), &module); + gpu_install_compiler_guard(); + const unsigned normal = std::clamp(std::thread::hardware_concurrency() * 2 / 3, 2u, 16u); + const unsigned workers = (std::max)(1u, gpu_pipeline_setting("X2W_GPU_PIPELINE_WORKERS", normal, 64)); + const unsigned wait = gpu_pipeline_setting("X2W_GPU_PIPELINE_WAIT_MS", 500, 10000); + const unsigned screen = gpu_pipeline_setting("X2W_GPU_SCREEN_WAIT_MS", 10000, 20000); + log("x2w-gpu pipeline workers %u + %u screen, shared frame waits %u / %u ms", workers, screen ? 2u : 0u, wait, screen); + return new GpuJobs(workers, screen ? 2 : 0, GpuJobs::Ms(wait), GpuJobs::Ms(screen), [](bool screen_only) { + if (!screen_only) SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); + }); + }(); + return *jobs; +} + +bool gpu_compile_host(ID3D12Device* device, const x2w_gpu::VpDeviceCaps& caps, + const x2w_gpu::VpShaderView* shaders, std::size_t count, const x2w_gpu::VpGraphicsState* graphics, + const x2w_gpu::VpMakeOptions& options, x2w_gpu::VpHostPipeline& host, std::string& why) +{ + static const bool watch = x2w_gpu::gpu_env_is("X2W_GPU_PSO_WATCH", '1') || + x2w_gpu::gpu_env_is("X2W_GPU_PSO_WATCH", '2'); + struct Scope { + Scope() { gpu_in_compiler = true; } + ~Scope() { gpu_in_compiler = false; } + } scope; + const auto make = watch ? gpu_observe_build : x2w_gpu::vp_make_host_pipeline; + return make(device, caps, shaders, count, graphics, options, host, why); +} + +bool gpu_synchronous_build() +{ + static const bool synchronous = x2w_gpu::gpu_env_is("X2W_GPU_PIPELINE_SYNC", '1'); + return synchronous; +} + +void gpu_queue_request(GpuRequest& request, bool initialization) +{ + std::call_once(request.requested, [&] { + const auto options = gpu_make_options(); + Microsoft::WRL::ComPtr<ID3D12Device> device = device_of(the_device); + const auto caps = gpu_caps(); + auto& pending = *request.pending; + const bool screen = initialization || (pending.graphics && pending.graphics->screen_pass()); + auto key = x2w_gpu::vp_pipeline_key(pending, options); + request.job = gpu_build_queue().request(std::move(key), request.pending, screen, + [device, caps, options](x2w_gpu::VpPending& p) { + x2w_gpu::vp_ready(p, device.Get(), caps, gpu_pipeline_cache(), options, gpu_compile_host); + }, initialization); + }); +} + +const x2w_gpu::GpuPipeline* gpu_pipeline_ready(Wrapper* pipeline, const GpuTargets* targets, GpuPsoDrop* drop) +{ + auto* entry = pipeline ? static_cast<GpuPipelineEntry*>(pipeline->own().gpu[0]) : nullptr; + if (!entry || !the_device) return nullptr; + if (entry->listed_bad) { + if (drop) drop->status = GpuPsoStatus::warm_bad; + if (!entry->base.reported.exchange(true)) { + static LONG reports; + if (first_calls(reports, 32)) + log("x2w-gpu refused compute pipeline listed in configured warm-bad cache: %s", + entry->records[0] ? entry->records[0]->key : "missing shader record"); + } + return nullptr; + } + auto& cache = gpu_pipeline_cache(); + // A depth target given by its typeless texture format (a DSV without a recorded view format) is the D format. + x2w_gpu::GpuTargets bound{}; + if (targets) { + bound = *targets; + if (depth_target_format(bound.dsv) != DXGI_FORMAT_UNKNOWN) bound.dsv = depth_target_format(bound.dsv); + targets = &bound; + } + GpuRequest* request = &entry->base; + auto* pending = request->pending.get(); + const x2w_gpu::VpGraphicsState* g = pending->graphics.get(); + if (targets && g && !gpu_same_targets(*targets, *g)) { + std::lock_guard<std::mutex> held(entry->lock); + request = nullptr; + for (auto& v : entry->variants) + if (gpu_same(v.first, *targets)) request = v.second.get(); + if (!request) { + // A copy of the title pipeline with the bound formats. + auto variant = std::make_unique<GpuRequest>(); + variant->pending->creation_slot = entry->base.pending->creation_slot; + for (const auto& s : entry->base.pending->shaders) variant->pending->add(s); + auto state = std::make_unique<x2w_gpu::VpGraphicsState>(*g); + state->targets = {}; + for (std::uint32_t i = 0; i < targets->count && i < 8; ++i) state->targets.RTFormats[i] = targets->rtv[i]; + state->targets.NumRenderTargets = (std::min)(targets->count, 8u); + state->depth_format = targets->dsv; + if (targets->read_depth_plane) state->depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + if (targets->read_stencil_plane) state->depth.StencilWriteMask = 0; + state->samples.Count = targets->samples ? targets->samples : 1; + if (state->samples.Count == 1) state->samples.Quality = 0; + variant->pending->graphics = std::move(state); + request = variant.get(); + entry->variants.emplace_back(*targets, std::move(variant)); + static LONG variants; + if (first_calls(variants, 8)) + log("x2w-gpu pipeline variant for bound targets (%u targets, first %d, depth %d; the stream named %u, first %d, depth %d)", + targets->count, targets->count ? static_cast<int>(targets->rtv[0]) : 0, static_cast<int>(targets->dsv), + g->targets.NumRenderTargets, static_cast<int>(g->targets.RTFormats[0]), static_cast<int>(g->depth_format)); + } + } + pending = request->pending.get(); + if (gpu_synchronous_build() || pending->missing) { + x2w_gpu::vp_ready(*pending, device_of(the_device), gpu_caps(), cache, gpu_make_options(), gpu_compile_host); + } else { + auto& jobs = gpu_build_queue(); + const bool screen = pending->graphics && pending->graphics->screen_pass(); + gpu_queue_request(*request, entry->exposure_reset); + const auto frame = static_cast<unsigned>(InterlockedCompareExchange(&frame_number, 0, 0)); + const bool ready = entry->exposure_reset ? jobs.ready_initialization(request->job) : jobs.ready(request->job, frame, screen); + if (!ready) { + if (entry->exposure_reset && !request->timeout_reported.exchange(true)) + log("x2w-gpu exposure reset PSO timed out at first use, frame=%u variant=%d", + frame, int(request != &entry->base)); + if (drop) drop->status = GpuPsoStatus::compiling; + return nullptr; + } + if (request->job->failure) { + if (drop) drop->status = GpuPsoStatus::worker_failure; + if (!request->reported.exchange(true)) { + try { std::rethrow_exception(request->job->failure); } + catch (const std::exception& e) { log("x2w-gpu pipeline worker failed: %s", e.what()); } + catch (...) { log("x2w-gpu pipeline worker failed with an unknown C++ exception"); } + } + return nullptr; + } + pending = request->job->state.get(); + } + const auto* host = pending->made.get(); + const bool fresh = !request->reported.exchange(true, std::memory_order_relaxed); + if (!host) { + if (drop) { + drop->status = pending->missing ? GpuPsoStatus::missing_shader : GpuPsoStatus::refused; + drop->detail = pending->why.c_str(); + } + if (fresh) { + // Once per reason, with the keys of the first few. + static std::mutex seen_lock; + static std::vector<std::string> seen; + static LONG refusals; + bool first = false; + { + std::lock_guard<std::mutex> held(seen_lock); + if (std::find(seen.begin(), seen.end(), pending->why) == seen.end()) { + seen.push_back(pending->why); + first = true; + } + } + if (first || first_calls(refusals, 16)) { + std::string keys; + for (std::size_t i = 0; i < entry->records.size(); ++i) { + keys += ' '; + keys += x2w_gpu::gpu_stage_name(entry->stages[i]); + keys += ' '; + keys += entry->records[i] ? entry->records[i]->key : "missing"; + } + log("x2w-gpu no host pipeline (slot %u):%s: %s", pending->creation_slot, keys.c_str(), pending->why.c_str()); + } + } + return nullptr; + } + if (fresh) { + static LONG made; + if (first_calls(made, 16)) + log("x2w-gpu host %s pipeline made (slot %u; %llu made, %llu shared, %llu refused so far)", + host->compute ? "compute" : host->mesh ? "mesh" : "graphics", pending->creation_slot, + static_cast<unsigned long long>(cache.made_count.load()), static_cast<unsigned long long>(cache.shared_count.load()), + static_cast<unsigned long long>(cache.refused_count.load())); + } + return gpu_view_for(pending->made, *pending, entry->stages); +} + +void gpu_pipeline_released(Wrapper* pipeline) +{ + if (!pipeline) return; + auto* entry = static_cast<GpuPipelineEntry*>(pipeline->own().gpu[0]); + pipeline->own().gpu[0] = nullptr; + // The host pipelines stay in the cache (a recorded draw may still use them); the record goes. + delete entry; +} diff --git a/src/startup_stubs/gpu_pipeline_build.h b/src/startup_stubs/gpu_pipeline_build.h new file mode 100644 index 0000000000..5de740ced0 --- /dev/null +++ b/src/startup_stubs/gpu_pipeline_build.h @@ -0,0 +1,570 @@ +// Host root signature and pipeline construction for translated shaders. Tests supply a device and exercise the ABI +// with compiled HLSL on WARP and hardware. +// +// Each stage gets user_data_dwords 32-bit root constants (multiple of four) at b0 space0. Resource and sampler +// heaps are directly indexed. Immediate samplers become static samplers at s<n> space0 in list order. Title root +// CBVs use b<p> space1. Title root SRVs and UAVs use bounded one-view tables at t<p> or u<p> space1 with volatile +// descriptors and data. The stride table (t255), memory directory (t254) and fault buffer (u253) stay root +// descriptors. Disabling bounded_root_views makes every root SRV/UAV direct. +// +// Noncompute roots, including mesh, allow the input assembler. Use root signature version 1.1. DXIL declares any +// required wave size. +#pragma once + +#include <d3d12.h> + +#include <cstddef> +#include <cstdint> +#include <cstdio> +#include <string> +#include <vector> + +#include "startup_stubs/gpu_pipeline_state.h" +#include "startup_stubs/gpu_rect.h" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4324) // stream subobjects are padded to pointer alignment on purpose +#endif + +namespace x2w_gpu { + +constexpr UINT vp_user_data_space = 0; +constexpr UINT vp_sampler_space = 0; +constexpr UINT vp_root_cbv_space = 1; +constexpr std::uint8_t vp_slot_strides = 255; +constexpr std::uint8_t vp_slot_memory = 254; +constexpr std::uint8_t vp_slot_faults = 253; + +// A decoded immediate sampler; the integers are D3D12_FILTER, D3D12_TEXTURE_ADDRESS_MODE, D3D12_COMPARISON_FUNC and +// D3D12_STATIC_BORDER_COLOR. +struct VpStaticSampler { + std::uint32_t filter; + std::uint32_t address[3]; + float mip_lod_bias; + std::uint32_t max_anisotropy; + std::uint32_t comparison; + std::uint32_t border; + float min_lod; + float max_lod; +}; + +// Anisotropic point-mip filtering is optional (OPTIONS19); without it the filter keeps the +// linear-mip approximation (StaticSampler::filter_for_host). +inline std::uint32_t vp_filter_for_host(std::uint32_t filter, bool aniso_point_mip_supported) +{ + return !aniso_point_mip_supported && (filter & ~0x180u) == 0x54 ? filter | 1 : filter; +} + +// What the root builder reads of a translated shader (HostShader). +struct VpShaderView { + std::uint32_t stage = vp_stage_none; // console stage number (vp_stage_*) + const void* dxil = nullptr; + std::size_t dxil_size = 0; + std::uint32_t user_data_dwords = 0; // HostShader::user_data_dwords(): round4(max index + 1) + const VpStaticSampler* samplers = nullptr; + std::size_t sampler_count = 0; + const std::uint8_t* root_cbvs = nullptr; + std::size_t root_cbv_count = 0; + const std::uint8_t* root_srvs = nullptr; + std::size_t root_srv_count = 0; + const std::uint8_t* root_uavs = nullptr; + std::size_t root_uav_count = 0; + const void* tag = nullptr; // the caller's record, kept in VpBoundStage +}; + +// HostShader::user_data_dwords from the user-data indices. +inline std::uint32_t vp_user_data_dwords(const std::uint32_t* indices, std::size_t count) +{ + std::uint32_t n = 0; + for (std::size_t i = 0; i < count; ++i) n = (std::max)(n, indices[i] + 1); + return (n + 3) & ~3u; +} + +// A title root view and the host root parameter it goes to. +struct VpRootView { + std::uint8_t slot; // the title's root parameter index (= the register in space1) + std::uint32_t param; // ours + bool table; // a one-view descriptor table (else a root descriptor) +}; + +// One stage of a host pipeline and where its bindings go. +struct VpBoundStage { + std::uint32_t stage = vp_stage_none; + const void* tag = nullptr; + bool has_user_data = false; + std::uint32_t user_data_param = 0; + std::uint32_t user_data_dwords = 0; + std::vector<VpRootView> root_cbvs, root_srvs, root_uavs; +}; + +struct VpRootOptions { + bool bounded_root_views = true; // Bound title root SRVs and UAVs by their view size. + bool aniso_point_mip = false; // OPTIONS19 AnisoFilterWithPointMipSupported + bool heap_indexing = true; // false only in the tests' negative control +}; + +// The root's description, with storage that stays put while it lives. +struct VpRootLayout { + std::vector<D3D12_ROOT_PARAMETER1> params; + std::vector<D3D12_DESCRIPTOR_RANGE1> ranges; // reserved up front: params point into it + std::vector<D3D12_STATIC_SAMPLER_DESC> samplers; + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + std::vector<VpBoundStage> stages; +}; + +inline D3D12_SHADER_VISIBILITY vp_visibility(std::uint32_t stage) +{ + switch (stage) { + case vp_stage_vertex: return D3D12_SHADER_VISIBILITY_VERTEX; + case vp_stage_pixel: return D3D12_SHADER_VISIBILITY_PIXEL; + case vp_stage_mesh: return D3D12_SHADER_VISIBILITY_MESH; + default: return D3D12_SHADER_VISIBILITY_ALL; + } +} + +// The root parameters the stages' bindings define, in binding order: per stage its user data, then root CBVs, SRVs, +// UAVs; static samplers per stage. `stages` is the compute stage alone, or the vertex or mesh stage then the pixel +// stage. +inline VpRootLayout vp_root_layout(const VpShaderView* stages, std::size_t count, bool compute, const VpRootOptions& o) +{ + VpRootLayout r; + std::size_t views = 0; + for (std::size_t s = 0; s < count; ++s) views += stages[s].root_srv_count + stages[s].root_uav_count; + r.ranges.reserve(views); + for (std::size_t s = 0; s < count; ++s) { + const VpShaderView& t = stages[s]; + const D3D12_SHADER_VISIBILITY visibility = compute ? D3D12_SHADER_VISIBILITY_ALL : vp_visibility(t.stage); + VpBoundStage bound; + bound.stage = t.stage; + bound.tag = t.tag; + if (t.user_data_dwords > 0) { + bound.has_user_data = true; + bound.user_data_param = static_cast<std::uint32_t>(r.params.size()); + bound.user_data_dwords = t.user_data_dwords; + D3D12_ROOT_PARAMETER1 p{}; + p.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + p.Constants = {0, vp_user_data_space, t.user_data_dwords}; + p.ShaderVisibility = visibility; + r.params.push_back(p); + } + struct Kind { + const std::uint8_t* slots; + std::size_t count; + D3D12_ROOT_PARAMETER_TYPE type; + std::vector<VpRootView>* out; + }; + const Kind kinds[] = { + {t.root_cbvs, t.root_cbv_count, D3D12_ROOT_PARAMETER_TYPE_CBV, &bound.root_cbvs}, + {t.root_srvs, t.root_srv_count, D3D12_ROOT_PARAMETER_TYPE_SRV, &bound.root_srvs}, + {t.root_uavs, t.root_uav_count, D3D12_ROOT_PARAMETER_TYPE_UAV, &bound.root_uavs}, + }; + for (const Kind& k : kinds) { + for (std::size_t i = 0; i < k.count; ++i) { + const std::uint8_t slot = k.slots[i]; + const bool uav = k.type == D3D12_ROOT_PARAMETER_TYPE_UAV; + const bool ours = uav ? slot == vp_slot_faults : (slot == vp_slot_strides || slot == vp_slot_memory); + const std::uint32_t param = static_cast<std::uint32_t>(r.params.size()); + D3D12_ROOT_PARAMETER1 p{}; + p.ShaderVisibility = visibility; + if ((uav || k.type == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && o.bounded_root_views) { + D3D12_DESCRIPTOR_RANGE1 range{}; + range.RangeType = uav ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + range.NumDescriptors = 1; + range.BaseShaderRegister = slot; + range.RegisterSpace = vp_root_cbv_space; + range.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE; + range.OffsetInDescriptorsFromTableStart = 0; + r.ranges.push_back(range); + p.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + p.DescriptorTable = {1, &r.ranges.back()}; + k.out->push_back({slot, param, true}); + } else { + p.ParameterType = k.type; + p.Descriptor = {slot, vp_root_cbv_space, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE}; + k.out->push_back({slot, param, false}); + } + r.params.push_back(p); + } + } + for (std::size_t n = 0; n < t.sampler_count; ++n) { + const VpStaticSampler& ss = t.samplers[n]; + D3D12_STATIC_SAMPLER_DESC d{}; + d.Filter = static_cast<D3D12_FILTER>(vp_filter_for_host(ss.filter, o.aniso_point_mip)); + d.AddressU = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(ss.address[0]); + d.AddressV = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(ss.address[1]); + d.AddressW = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(ss.address[2]); + d.MipLODBias = ss.mip_lod_bias; + d.MaxAnisotropy = ss.max_anisotropy; + d.ComparisonFunc = static_cast<D3D12_COMPARISON_FUNC>(ss.comparison); + d.BorderColor = static_cast<D3D12_STATIC_BORDER_COLOR>(ss.border); + d.MinLOD = ss.min_lod; + d.MaxLOD = ss.max_lod; + d.ShaderRegister = static_cast<UINT>(n); + d.RegisterSpace = vp_sampler_space; + d.ShaderVisibility = visibility; + r.samplers.push_back(d); + } + r.stages.push_back(std::move(bound)); + } + r.flags = compute ? D3D12_ROOT_SIGNATURE_FLAG_NONE : D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; + if (o.heap_indexing) + r.flags |= D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + return r; +} + +// Serializes the layout (version 1.1). On failure `why` holds the serializer's text. +inline HRESULT vp_serialize_root(const VpRootLayout& r, std::vector<unsigned char>& blob, std::string& why) +{ + D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; + desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + desc.Desc_1_1.NumParameters = static_cast<UINT>(r.params.size()); + desc.Desc_1_1.pParameters = r.params.empty() ? nullptr : r.params.data(); + desc.Desc_1_1.NumStaticSamplers = static_cast<UINT>(r.samplers.size()); + desc.Desc_1_1.pStaticSamplers = r.samplers.empty() ? nullptr : r.samplers.data(); + desc.Desc_1_1.Flags = r.flags; + ID3DBlob* out = nullptr; + ID3DBlob* error = nullptr; + const HRESULT hr = D3D12SerializeVersionedRootSignature(&desc, &out, &error); + if (error) { + why.assign(static_cast<const char*>(error->GetBufferPointer()), error->GetBufferSize()); + error->Release(); + } + if (SUCCEEDED(hr) && out) { + const auto* p = static_cast<const unsigned char*>(out->GetBufferPointer()); + blob.assign(p, p + out->GetBufferSize()); + } + if (out) out->Release(); + return SUCCEEDED(hr) && blob.empty() ? E_FAIL : hr; +} + +// Query device support for mesh shaders, depth bounds and OPTIONS19 once per device. +struct VpDeviceCaps { + bool mesh_shaders = false; // MeshShaderTier >= 1 and shader model 6.6 + bool depth_bounds = false; // OPTIONS2 DepthBoundsTestSupported + bool aniso_point_mip = false; // OPTIONS19 AnisoFilterWithPointMipSupported +}; + +inline VpDeviceCaps vp_device_caps(ID3D12Device* device) +{ + VpDeviceCaps caps; + D3D12_FEATURE_DATA_D3D12_OPTIONS7 o7{}; + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + caps.mesh_shaders = SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &o7, sizeof(o7))) && + o7.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED && + SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model))) && + model.HighestShaderModel >= D3D_SHADER_MODEL_6_6; + D3D12_FEATURE_DATA_D3D12_OPTIONS2 o2{}; + caps.depth_bounds = SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS2, &o2, sizeof(o2))) && + o2.DepthBoundsTestSupported; + D3D12_FEATURE_DATA_D3D12_OPTIONS19 o19{}; + caps.aniso_point_mip = SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS19, &o19, sizeof(o19))) && + o19.AnisoFilterWithPointMipSupported; + return caps; +} + +// A stream subobject: its type, then its description, pointer-aligned. +template <class T> +struct alignas(alignof(void*)) VpSub { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type; + T value; +}; + +template <class S> +HRESULT vp_stream_pipeline(ID3D12Device* device, S& stream, ID3D12PipelineState** out) +{ + ID3D12Device2* device2 = nullptr; + HRESULT hr = device->QueryInterface(IID_PPV_ARGS(&device2)); + if (FAILED(hr)) return hr; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(S), &stream}; + hr = device2->CreatePipelineState(&desc, IID_PPV_ARGS(out)); + device2->Release(); + return hr; +} + +// Mesh pipeline state streams omit the input layout and specify triangle topology. The library requires an explicit +// topology and translated mesh shaders emit triangles. +template <class D> +struct VpMeshStream { + VpSub<ID3D12RootSignature*> root; + VpSub<D3D12_SHADER_BYTECODE> ms; + VpSub<D3D12_SHADER_BYTECODE> ps; + VpSub<D3D12_BLEND_DESC> blend; + VpSub<UINT> mask; + VpSub<D3D12_RASTERIZER_DESC> raster; + VpSub<D> depth; + VpSub<D3D12_RT_FORMAT_ARRAY> targets; + VpSub<DXGI_FORMAT> dsv; + VpSub<DXGI_SAMPLE_DESC> samples; + VpSub<D3D12_PRIMITIVE_TOPOLOGY_TYPE> topology; +}; + +inline HRESULT vp_mesh_pipeline(ID3D12Device* device, ID3D12RootSignature* root, D3D12_SHADER_BYTECODE ms, + D3D12_SHADER_BYTECODE ps, const VpGraphicsState& g, bool depth_bounds, + ID3D12PipelineState** out) +{ + const auto fill = [&](auto& s) { + s.root = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root}; + s.ms = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms}; + s.ps = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps}; + s.blend = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, vp_host_blend(g.blend, g.targets)}; + s.mask = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask}; + s.raster = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer}; + s.targets = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets}; + s.dsv = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format}; + s.samples = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples}; + s.topology = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE}; + }; + if (depth_bounds) { + VpMeshStream<D3D12_DEPTH_STENCIL_DESC1> s{}; + fill(s); + s.depth = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, g.depth1()}; + return vp_stream_pipeline(device, s, out); + } + VpMeshStream<D3D12_DEPTH_STENCIL_DESC> s{}; + fill(s); + s.depth = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth}; + return vp_stream_pipeline(device, s, out); +} + +// A graphics pipeline enabling the depth bounds test: the plain description has no field for it, so it is made as a +// stream with DEPTH_STENCIL1. +inline HRESULT vp_graphics_depth_bounds_pipeline(ID3D12Device* device, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& d, + const D3D12_DEPTH_STENCIL_DESC1& depth, ID3D12PipelineState** out) +{ + struct Stream { + VpSub<ID3D12RootSignature*> root; + VpSub<D3D12_SHADER_BYTECODE> vs; + VpSub<D3D12_SHADER_BYTECODE> ps; + VpSub<D3D12_BLEND_DESC> blend; + VpSub<UINT> mask; + VpSub<D3D12_RASTERIZER_DESC> raster; + VpSub<D3D12_DEPTH_STENCIL_DESC1> depth; + VpSub<D3D12_INPUT_LAYOUT_DESC> input; + VpSub<D3D12_INDEX_BUFFER_STRIP_CUT_VALUE> strip_cut; + VpSub<D3D12_PRIMITIVE_TOPOLOGY_TYPE> topology; + VpSub<D3D12_RT_FORMAT_ARRAY> targets; + VpSub<DXGI_FORMAT> dsv; + VpSub<DXGI_SAMPLE_DESC> samples; + VpSub<D3D12_SHADER_BYTECODE> gs; // left out of the size when there is no GS + } s{}; + D3D12_RT_FORMAT_ARRAY targets{}; + for (int i = 0; i < 8; ++i) targets.RTFormats[i] = d.RTVFormats[i]; + targets.NumRenderTargets = d.NumRenderTargets; + s.root = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, d.pRootSignature}; + s.vs = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, d.VS}; + s.ps = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, d.PS}; + s.blend = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, d.BlendState}; + s.mask = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, d.SampleMask}; + s.raster = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, d.RasterizerState}; + s.depth = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, depth}; + s.input = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, d.InputLayout}; + s.strip_cut = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, d.IBStripCutValue}; + s.topology = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, d.PrimitiveTopologyType}; + s.targets = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, targets}; + s.dsv = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, d.DSVFormat}; + s.samples = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, d.SampleDesc}; + s.gs = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, d.GS}; + ID3D12Device2* device2 = nullptr; + HRESULT hr = device->QueryInterface(IID_PPV_ARGS(&device2)); + if (FAILED(hr)) return hr; + const std::size_t bytes = d.GS.pShaderBytecode ? sizeof(s) : offsetof(Stream, gs); + const D3D12_PIPELINE_STATE_STREAM_DESC desc{bytes, &s}; + hr = device2->CreatePipelineState(&desc, IID_PPV_ARGS(out)); + device2->Release(); + return hr; +} + +// A made host pipeline. Holds one reference on pso and root. +struct VpHostPipeline { + bool compute = false; + bool mesh = false; + ID3D12PipelineState* pso = nullptr; + ID3D12RootSignature* root = nullptr; + std::vector<unsigned char> root_blob; + // Vertex or mesh, then pixel; or the compute stage. + std::vector<VpBoundStage> stages; + std::uint32_t slots = 0; // vertex buffer slots read (bit per slot) + std::vector<VpInput> inputs; + bool rects = false; // host PSO has the rectangle geometry stage + bool depth_bounds = false; + D3D12_PRIMITIVE_TOPOLOGY_TYPE topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED; // the title's (19/32 kept) + + VpHostPipeline() = default; + VpHostPipeline(const VpHostPipeline&) = delete; + VpHostPipeline& operator=(const VpHostPipeline&) = delete; + ~VpHostPipeline() + { + if (pso) pso->Release(); + if (root) root->Release(); + } +}; + +struct VpMakeOptions { + VpRootOptions root; + HRESULT (*load_compute)(ID3D12Device*, const std::vector<unsigned char>&, + const D3D12_COMPUTE_PIPELINE_STATE_DESC&, ID3D12PipelineState**) = nullptr; + bool allow_mesh = true; // X2W_GPU_MESH=0 turns it off +}; + +// Makes the host pipeline for translated `shaders` with the graphics state `g` (null: none was kept, as for the +// plain graphics description), or for one compute shader. Returns false with `why` set when it is refused. +inline bool vp_make_host_pipeline(ID3D12Device* device, const VpDeviceCaps& caps, const VpShaderView* shaders, + std::size_t count, const VpGraphicsState* g, const VpMakeOptions& options, + VpHostPipeline& out, std::string& why) +{ + const auto find = [&](std::uint32_t stage) -> const VpShaderView* { + for (std::size_t i = 0; i < count; ++i) + if (shaders[i].stage == stage) return &shaders[i]; + return nullptr; + }; + const bool compute = count == 1 && shaders[0].stage == vp_stage_compute; + if (!compute) { + for (std::size_t i = 0; i < count; ++i) { + const std::uint32_t s = shaders[i].stage; + if (s != vp_stage_vertex && s != vp_stage_pixel && s != vp_stage_mesh) { + why = "only vertex, mesh, pixel and compute stages are translated"; + return false; + } + } + } + const VpShaderView* mesh = find(vp_stage_mesh); + std::vector<VpShaderView> stages; + if (compute) { + stages.push_back(shaders[0]); + } else { + const VpShaderView* first = mesh ? mesh : find(vp_stage_vertex); + if (!first) { + why = "no vertex or mesh shader"; + return false; + } + stages.push_back(*first); + if (const VpShaderView* ps = find(vp_stage_pixel)) stages.push_back(*ps); + } + if (mesh && !options.allow_mesh) { + why = "mesh pipelines are off (X2W_GPU_MESH=0)"; + return false; + } + if (mesh && !caps.mesh_shaders) { + why = "the host GPU has no mesh shaders (or no shader model 6.6)"; + return false; + } + for (const auto& s : stages) { + if (!s.dxil || !s.dxil_size) { + why = "a stage has no translated DXIL"; + return false; + } + } + if (!compute && !g) { + why = "graphics state not kept (plain description)"; + return false; + } + if (g && g->bad_inputs) { + why = "the input layout was not readable or had more than 32 elements"; + return false; + } + + VpRootOptions root_options = options.root; + root_options.aniso_point_mip = caps.aniso_point_mip; + VpRootLayout layout = vp_root_layout(stages.data(), stages.size(), compute, root_options); + std::vector<unsigned char> blob; + std::string text; + HRESULT hr = vp_serialize_root(layout, blob, text); + if (FAILED(hr)) { + char line[64]; + std::snprintf(line, sizeof(line), "host root signature refused 0x%08lx: ", static_cast<unsigned long>(hr)); + why = line + text; + return false; + } + ID3D12RootSignature* root = nullptr; + hr = device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root)); + if (FAILED(hr)) { + char line[64]; + std::snprintf(line, sizeof(line), "CreateRootSignature 0x%08lx", static_cast<unsigned long>(hr)); + why = line; + return false; + } + const auto code = [&](std::size_t i) { + return i < stages.size() ? D3D12_SHADER_BYTECODE{stages[i].dxil, stages[i].dxil_size} : D3D12_SHADER_BYTECODE{}; + }; + ID3D12PipelineState* pso = nullptr; + const char* what = "host pipeline"; + bool depth_bounds = false; + if (compute) { + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root; + desc.CS = code(0); + bool create = true; + if (options.load_compute) { + hr = options.load_compute(device, blob, desc, &pso); + create = FAILED(hr) && SUCCEEDED(device->GetDeviceRemovedReason()); + } + if (create) hr = device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso)); + } else { + depth_bounds = g->depth_bounds && caps.depth_bounds; + if (mesh) { + what = "host mesh pipeline"; + hr = vp_mesh_pipeline(device, root, code(0), code(1), *g, depth_bounds, &pso); + } else { + const std::vector<D3D12_INPUT_ELEMENT_DESC> inputs = g->input_layout(); + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root; + desc.VS = code(0); + desc.PS = code(1); + std::vector<unsigned char> rect_gs; + if (static_cast<int>(g->topology) == vp_topology_rectangles) { + rect_gs = vp_rectangle_stage(desc.VS, desc.PS); + if (!rect_gs.empty()) desc.GS = {rect_gs.data(), rect_gs.size()}; + } + desc.BlendState = vp_host_blend(g->blend, g->targets); + desc.SampleMask = g->sample_mask; + desc.RasterizerState = g->rasterizer; + desc.DepthStencilState = g->depth; + desc.InputLayout = {inputs.empty() ? nullptr : inputs.data(), static_cast<UINT>(inputs.size())}; + desc.IBStripCutValue = g->strip_cut; + desc.PrimitiveTopologyType = vp_host_topology_type(g->topology); + desc.NumRenderTargets = g->targets.NumRenderTargets; + for (int i = 0; i < 8; ++i) desc.RTVFormats[i] = g->targets.RTFormats[i]; + desc.DSVFormat = g->depth_format; + desc.SampleDesc = g->samples; + const auto make = [&] { + return depth_bounds ? vp_graphics_depth_bounds_pipeline(device, desc, g->depth1(), &pso) + : device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso)); + }; + hr = make(); + if (FAILED(hr) && desc.GS.pShaderBytecode) { + std::fprintf(stderr, "x2w-gpu pipeline: host refused rectangle geometry stage 0x%08lx, retrying without it\n", + static_cast<unsigned long>(hr)); + desc.GS = {}; + hr = make(); + } + out.rects = SUCCEEDED(hr) && desc.GS.pShaderBytecode != nullptr; + } + } + if (FAILED(hr) || !pso) { + char line[96]; + std::snprintf(line, sizeof(line), "%s refused 0x%08lx", what, static_cast<unsigned long>(hr)); + why = line; + root->Release(); + return false; + } + out.compute = compute; + out.mesh = mesh != nullptr; + out.pso = pso; + out.root = root; + out.root_blob = std::move(blob); + out.stages = std::move(layout.stages); + out.depth_bounds = depth_bounds; + if (g && !compute && !mesh) { + out.slots = g->slots(); + out.inputs = g->elements(); + } + if (g) out.topology = g->topology; + return true; +} + +} // namespace x2w_gpu + +#ifdef _MSC_VER +#pragma warning(pop) +#endif diff --git a/src/startup_stubs/gpu_pipeline_pending.h b/src/startup_stubs/gpu_pipeline_pending.h new file mode 100644 index 0000000000..116067e97a --- /dev/null +++ b/src/startup_stubs/gpu_pipeline_pending.h @@ -0,0 +1,150 @@ +// Cache host pipelines by stage records and graphics state. Title pipeline creation records these inputs. Building +// the root signature and PSO on demand avoids compiling every pipeline the title creates during startup. +#pragma once + +#include <atomic> +#include <map> +#include <memory> +#include <mutex> +#include <string> +#include <vector> + +#include "startup_stubs/gpu_pipeline_build.h" + +namespace x2w_gpu { + +struct VpPending { + // The translated stages, in the order the title gave them. A stage whose record was missing + // has dxil null (the pipeline is then refused at ready()). + std::vector<VpShaderView> shaders; + // Owned copies of the arrays the views point at, so a view never outlives its record. + std::vector<std::vector<VpStaticSampler>> sampler_store; + std::vector<std::vector<std::uint8_t>> slot_store; + std::unique_ptr<VpGraphicsState> graphics; // null: compute, or the plain graphics description + std::uint32_t missing = 0; // stages without a translated record + std::uint32_t creation_slot = 0; // device slot the title created it with (10, 11, 62, 86) + + std::once_flag once; + std::shared_ptr<const VpHostPipeline> made; + std::string why; // set when refused + std::atomic<bool> done{false}; + + // Takes a copy of the view's arrays (the record may live in a mapped file the caller owns, + // but the pending pipeline must not depend on that). + void add(const VpShaderView& view) + { + VpShaderView v = view; + if (v.sampler_count) { + sampler_store.emplace_back(v.samplers, v.samplers + v.sampler_count); + v.samplers = sampler_store.back().data(); + } + const auto keep = [this](const std::uint8_t*& p, std::size_t n) { + if (!n) return; + slot_store.emplace_back(p, p + n); + p = slot_store.back().data(); + }; + keep(v.root_cbvs, v.root_cbv_count); + keep(v.root_srvs, v.root_srv_count); + keep(v.root_uavs, v.root_uav_count); + if (!v.dxil || !v.dxil_size) ++missing; + shaders.push_back(v); + } +}; + +// Host pipelines by what they are made of; shared by every pending pipeline with that key. +struct VpPipelineCache { + std::mutex lock; + std::map<std::string, std::shared_ptr<const VpHostPipeline>> made; + std::map<std::string, std::string> refused; + std::atomic<std::uint64_t> made_count{0}, shared_count{0}, refused_count{0}; +}; + +// What identifies a pending pipeline's host pipeline: each stage's number, record, DXIL bytes and +// binding lists, then the graphics state. +inline std::string vp_pipeline_key(const VpPending& p, const VpMakeOptions& options) +{ + std::string key; + const auto put = [&key](const void* data, std::size_t n) { key.append(static_cast<const char*>(data), n); }; + const char flags[3] = {options.root.bounded_root_views ? '1' : '0', options.root.heap_indexing ? '1' : '0', + options.allow_mesh ? '1' : '0'}; + put(flags, sizeof(flags)); + for (const auto& s : p.shaders) { + put(&s.stage, sizeof(s.stage)); + // The record itself: two records with the same DXIL can still map user data, used views or threads differently, and + // the made pipeline hands its stages' records to the bind path. Records are deduplicated by container key, so the + // same container shares. + put(&s.tag, sizeof(s.tag)); + const std::uint64_t n = s.dxil_size; + put(&n, sizeof(n)); + // The DXIL by two 64-bit hashes, not by its bytes (a key per pipeline would hold them all). + std::uint64_t a = 0xcbf29ce484222325ull, b = 0x84222325cbf29ce4ull; + for (std::size_t i = 0; s.dxil && i < s.dxil_size; ++i) { + const unsigned char c = static_cast<const unsigned char*>(s.dxil)[i]; + a = (a ^ c) * 0x100000001b3ull; + b = (b + c + 1) * 0x9e3779b97f4a7c15ull; + b ^= b >> 29; + } + put(&a, sizeof(a)); + put(&b, sizeof(b)); + put(&s.user_data_dwords, sizeof(s.user_data_dwords)); + const std::uint64_t counts[4] = {s.sampler_count, s.root_cbv_count, s.root_srv_count, s.root_uav_count}; + put(counts, sizeof(counts)); + if (s.sampler_count) put(s.samplers, s.sampler_count * sizeof(VpStaticSampler)); + if (s.root_cbv_count) put(s.root_cbvs, s.root_cbv_count); + if (s.root_srv_count) put(s.root_srvs, s.root_srv_count); + if (s.root_uav_count) put(s.root_uavs, s.root_uav_count); + } + if (p.graphics) p.graphics->append_key(key); + return key; +} + +// The host pipeline if it is made or can be made now; null if it is refused (p.why says why). +// Thread-safe; the first caller makes it. +inline const VpHostPipeline* vp_ready(VpPending& p, ID3D12Device* device, const VpDeviceCaps& caps, VpPipelineCache& cache, + const VpMakeOptions& options, decltype(&vp_make_host_pipeline) build = vp_make_host_pipeline) +{ + std::call_once(p.once, [&] { + if (p.missing) { + p.why = "a stage has no translated record in the export"; + cache.refused_count.fetch_add(1, std::memory_order_relaxed); + } else { + const std::string key = vp_pipeline_key(p, options); + { + std::lock_guard<std::mutex> held(cache.lock); + const auto found = cache.made.find(key); + if (found != cache.made.end()) { + p.made = found->second; + cache.shared_count.fetch_add(1, std::memory_order_relaxed); + } else if (const auto no = cache.refused.find(key); no != cache.refused.end()) { + p.why = no->second; + cache.refused_count.fetch_add(1, std::memory_order_relaxed); + } + } + if (!p.made && p.why.empty()) { + // Made outside the lock: a driver compile takes up to seconds. + auto host = std::make_shared<VpHostPipeline>(); + std::string why; + if (build(device, caps, p.shaders.data(), p.shaders.size(), p.graphics.get(), options, *host, why)) { + std::lock_guard<std::mutex> held(cache.lock); + auto& slot = cache.made[key]; + if (!slot) { + slot = host; + cache.made_count.fetch_add(1, std::memory_order_relaxed); + } else { + cache.shared_count.fetch_add(1, std::memory_order_relaxed); + } + p.made = slot; + } else { + std::lock_guard<std::mutex> held(cache.lock); + cache.refused[key] = why; + p.why = why; + cache.refused_count.fetch_add(1, std::memory_order_relaxed); + } + } + } + p.done.store(true, std::memory_order_release); + }); + return p.made.get(); +} + +} // namespace x2w_gpu diff --git a/src/startup_stubs/gpu_pipeline_record.h b/src/startup_stubs/gpu_pipeline_record.h new file mode 100644 index 0000000000..b32296e751 --- /dev/null +++ b/src/startup_stubs/gpu_pipeline_record.h @@ -0,0 +1,29 @@ +#pragma once +#include "startup_stubs/gpu_abi.h" +#include "startup_stubs/gpu_pipeline_state.h" +namespace x2w_gpu { +static_assert(sizeof(x2w_gpu::GpuStaticSampler) == sizeof(x2w_gpu::VpStaticSampler), + "the export's decoded sampler and the builder's are the same fields"); + +// A record as the root builder reads it (the record's spans live for the process). +inline VpShaderView vp_record_view(const GpuShader* s, std::uint32_t stage) +{ + x2w_gpu::VpShaderView v; + v.stage = stage; + v.tag = s; + if (!s) return v; + v.dxil = s->dxil; + v.dxil_size = s->dxil_bytes; + v.user_data_dwords = s->user_data_dwords(); + v.samplers = reinterpret_cast<const x2w_gpu::VpStaticSampler*>(s->static_samplers.data); + v.sampler_count = s->static_samplers.count; + v.root_cbvs = s->root_cbvs.data; + v.root_cbv_count = s->root_cbvs.count; + v.root_srvs = s->root_srvs.data; + v.root_srv_count = s->root_srvs.count; + v.root_uavs = s->root_uavs.data; + v.root_uav_count = s->root_uavs.count; + return v; +} + +} diff --git a/src/startup_stubs/gpu_pipeline_state.h b/src/startup_stubs/gpu_pipeline_state.h new file mode 100644 index 0000000000..544e4cf700 --- /dev/null +++ b/src/startup_stubs/gpu_pipeline_state.h @@ -0,0 +1,467 @@ +// Decode a console pipeline-state stream for host pipeline creation. Subobjects begin with a 32-bit type and are +// padded to eight bytes. Data starts at +4, or +8 for pointer-bearing subobjects. Console amplification and mesh +// shader types are 23 and 24 (desktop 24 and 25). Stop at an unknown size or truncated subobject. +// +// The caller maps console formats through VpFormatMap so pipelines use the same desktop formats and packed-target +// stand-ins as their textures. Parsing requires no device. +#pragma once + +#include <d3d12.h> + +#include <algorithm> +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <string> +#include <vector> + +namespace x2w_gpu { + +// Console stage numbers in a stream (subobject types). +enum VpStage : std::uint32_t { + vp_stage_none = 0, + vp_stage_vertex = 1, + vp_stage_pixel = 2, + vp_stage_domain = 3, + vp_stage_hull = 4, + vp_stage_geometry = 5, + vp_stage_compute = 6, + vp_stage_amplification = 23, + vp_stage_mesh = 24, +}; + +inline const char* vp_stage_name(std::uint32_t stage) +{ + switch (stage) { + case vp_stage_vertex: return "vertex"; + case vp_stage_pixel: return "pixel"; + case vp_stage_domain: return "domain"; + case vp_stage_hull: return "hull"; + case vp_stage_geometry: return "geometry"; + case vp_stage_compute: return "compute"; + case vp_stage_amplification: return "amplification"; + case vp_stage_mesh: return "mesh"; + default: return "none"; + } +} + +// Subobject size including the type, and stage for shader subobjects. Zero means unknown size. +struct VpSubobject { + std::size_t size; + std::uint32_t stage; +}; + +inline VpSubobject vp_subobject(std::uint32_t kind) +{ + switch (kind) { + case 1: case 2: case 3: case 4: case 5: case 6: case 23: case 24: return {24, kind}; + case 0: return {16, 0}; + case 12: case 19: return {24, 0}; + case 7: case 15: return {40, 0}; + case 8: return {336, 0}; + case 10: return {48, 0}; + case 11: return {56, 0}; + case 17: return {16, 0}; + case 21: return {64, 0}; + case 22: return {32, 0}; + case 9: case 13: case 14: case 16: case 18: case 20: return {8, 0}; + default: return {0, 0}; + } +} + +// The console's own primitive topology types; both draw as triangles on the host. +constexpr int vp_topology_rectangles = 19; +constexpr int vp_topology_quads = 32; + +inline D3D12_PRIMITIVE_TOPOLOGY_TYPE vp_host_topology_type(D3D12_PRIMITIVE_TOPOLOGY_TYPE t) +{ + const int v = static_cast<int>(t); + return v == vp_topology_rectangles || v == vp_topology_quads ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : t; +} + +// Map console depth formats 118–120 to desktop formats. +inline DXGI_FORMAT vp_pc_format(std::uint32_t format) +{ + switch (format) { + case 118: return DXGI_FORMAT_D24_UNORM_S8_UINT; + case 119: return DXGI_FORMAT_R24_UNORM_X8_TYPELESS; + case 120: return DXGI_FORMAT_X24_TYPELESS_G8_UINT; + default: return static_cast<DXGI_FORMAT>(format); + } +} + +// Console format -> host format, per use. Null members fall back on vp_pc_format. +struct VpFormatMap { + DXGI_FORMAT (*target)(std::uint32_t) = nullptr; // render target formats (subobject 15) + DXGI_FORMAT (*depth)(std::uint32_t) = nullptr; // depth-stencil format (16) + DXGI_FORMAT (*input)(std::uint32_t) = nullptr; // input elements (12) +}; + +inline DXGI_FORMAT vp_map(DXGI_FORMAT (*f)(std::uint32_t), std::uint32_t format) +{ + return f ? f(format) : vp_pc_format(format); +} + +// Bytes of one element of `format` and texels per element. {0, 0}: not known. +struct VpElement { + std::uint32_t bytes; + std::uint32_t texels; +}; + +inline VpElement vp_element(std::uint32_t f) +{ + if (f >= 1 && f <= 4) return {16, 1}; + if (f >= 5 && f <= 8) return {12, 1}; + if (f >= 9 && f <= 22) return {8, 1}; + if ((f >= 23 && f <= 47) || f == 67 || (f >= 87 && f <= 93) || f == 116 || f == 117 || f == 189 || f == 191) return {4, 1}; + if (f >= 118 && f <= 120) return {3, 1}; + if ((f >= 48 && f <= 59) || f == 68 || f == 69 || f == 85 || f == 86 || f == 115) return {2, 1}; + if ((f >= 60 && f <= 65) || f == 190) return {1, 1}; + if ((f >= 70 && f <= 72) || (f >= 79 && f <= 81)) return {8, 4}; + if ((f >= 73 && f <= 78) || (f >= 82 && f <= 84) || (f >= 94 && f <= 99)) return {16, 4}; + return {0, 0}; +} + +// Integer render target formats: D3D12 cannot blend into them. +inline bool vp_integer_format(DXGI_FORMAT f) +{ + switch (f) { + 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; + } +} + +// The title's blend state as the host takes it: blending off on integer render targets (the console ignores it +// there, D3D12 refuses the pipeline). With one description for every target, each target gets its own copy so the +// others keep theirs. +inline D3D12_BLEND_DESC vp_host_blend(const D3D12_BLEND_DESC& blend, const D3D12_RT_FORMAT_ARRAY& targets) +{ + const UINT count = std::min<UINT>(targets.NumRenderTargets, 8); + const bool per_target = blend.IndependentBlendEnable != FALSE; + const auto blends = [&](UINT i) { return blend.RenderTarget[per_target ? i : 0].BlendEnable != FALSE; }; + bool any = false; + for (UINT i = 0; i < count; ++i) any = any || (vp_integer_format(targets.RTFormats[i]) && blends(i)); + if (!any) return blend; + D3D12_BLEND_DESC host = blend; + if (!per_target) { + host.IndependentBlendEnable = TRUE; + for (auto& t : host.RenderTarget) t = blend.RenderTarget[0]; + } + for (UINT i = 0; i < count; ++i) + if (vp_integer_format(targets.RTFormats[i])) host.RenderTarget[i].BlendEnable = FALSE; + return host; +} + +// One input element as the draw path reads it: vertex buffer slot, byte offset, format. +struct VpInput { + std::uint32_t slot; + std::uint32_t offset; + std::uint32_t format; + bool per_instance; +}; + +// A stream's graphics state, owned (the title's stream lives only for the creation call). +// Subobjects the stream leaves out keep D3D12's defaults. +struct VpGraphicsState { + D3D12_BLEND_DESC blend{}; + UINT sample_mask = ~0u; + D3D12_RASTERIZER_DESC rasterizer{}; + D3D12_DEPTH_STENCIL_DESC depth{}; + bool depth_bounds = false; + // Input elements with SemanticName left null; the names are kept in `names` (input_layout() + // puts the pointers in). + std::vector<D3D12_INPUT_ELEMENT_DESC> inputs; + std::vector<std::string> names; + // The layout had more than 32 elements, or names or elements were not readable: the pipeline + // is refused. + bool bad_inputs = false; + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE strip_cut = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; + D3D12_PRIMITIVE_TOPOLOGY_TYPE topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED; + D3D12_RT_FORMAT_ARRAY targets{}; + DXGI_FORMAT depth_format = DXGI_FORMAT_UNKNOWN; + DXGI_SAMPLE_DESC samples{1, 0}; + + VpGraphicsState() + { + D3D12_RENDER_TARGET_BLEND_DESC target{}; + target.SrcBlend = D3D12_BLEND_ONE; + target.DestBlend = D3D12_BLEND_ZERO; + target.BlendOp = D3D12_BLEND_OP_ADD; + target.SrcBlendAlpha = D3D12_BLEND_ONE; + target.DestBlendAlpha = D3D12_BLEND_ZERO; + target.BlendOpAlpha = D3D12_BLEND_OP_ADD; + target.LogicOp = D3D12_LOGIC_OP_NOOP; + target.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + for (auto& t : blend.RenderTarget) t = target; + rasterizer.FillMode = D3D12_FILL_MODE_SOLID; + rasterizer.CullMode = D3D12_CULL_MODE_BACK; + rasterizer.DepthClipEnable = TRUE; + const D3D12_DEPTH_STENCILOP_DESC keep{D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, + D3D12_COMPARISON_FUNC_ALWAYS}; + depth.DepthEnable = TRUE; + depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + depth.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + depth.StencilReadMask = 0xff; + depth.StencilWriteMask = 0xff; + depth.FrontFace = keep; + depth.BackFace = keep; + } + + // A pass over the screen: no vertex input, no depth or stencil, a target, triangles. + bool screen_pass() const + { + return inputs.empty() && + (depth_format == DXGI_FORMAT_UNKNOWN || (!depth.DepthEnable && !depth.StencilEnable)) && + targets.NumRenderTargets > 0 && topology == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + } + + D3D12_DEPTH_STENCIL_DESC1 depth1() const + { + D3D12_DEPTH_STENCIL_DESC1 d{}; + d.DepthEnable = depth.DepthEnable; + d.DepthWriteMask = depth.DepthWriteMask; + d.DepthFunc = depth.DepthFunc; + d.StencilEnable = depth.StencilEnable; + d.StencilReadMask = depth.StencilReadMask; + d.StencilWriteMask = depth.StencilWriteMask; + d.FrontFace = depth.FrontFace; + d.BackFace = depth.BackFace; + d.DepthBoundsTestEnable = depth_bounds ? TRUE : FALSE; + return d; + } + + // The input elements with their names in place (valid while this state lives unchanged). + std::vector<D3D12_INPUT_ELEMENT_DESC> input_layout() const + { + std::vector<D3D12_INPUT_ELEMENT_DESC> out = inputs; + for (std::size_t i = 0; i < out.size() && i < names.size(); ++i) out[i].SemanticName = names[i].c_str(); + return out; + } + + // The vertex buffer slots the input layout reads (bit per slot). + std::uint32_t slots() const + { + std::uint32_t m = 0; + for (const auto& e : inputs) m |= 1u << std::min<UINT>(e.InputSlot, 31); + return m; + } + + // The input elements with their byte offsets worked out. An appended element starts at the + // next multiple of min(4, its size) after the previous one, where D3D12 places it. + std::vector<VpInput> elements() const + { + std::uint32_t next[32] = {}; + std::vector<VpInput> out; + out.reserve(inputs.size()); + for (const auto& e : inputs) { + const std::uint32_t slot = std::min<UINT>(e.InputSlot, 31); + const std::uint32_t format = static_cast<std::uint32_t>(e.Format); + const std::uint32_t bytes = vp_element(format).bytes; + std::uint32_t offset = e.AlignedByteOffset; + if (e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT) { + const std::uint64_t align = std::clamp<std::uint32_t>(bytes, 1, 4); + const std::uint64_t rounded = (static_cast<std::uint64_t>(next[slot]) + align - 1) / align * align; + offset = rounded > 0xffffffffull ? 0xffffffffu : static_cast<std::uint32_t>(rounded); + } + const std::uint64_t end = static_cast<std::uint64_t>(offset) + bytes; + next[slot] = end > 0xffffffffull ? 0xffffffffu : static_cast<std::uint32_t>(end); + out.push_back({slot, offset, format, e.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA}); + } + return out; + } + + // Everything the state holds, as bytes for a key (names included). + void append_key(std::string& key) const + { + const auto put = [&key](const void* p, std::size_t n) { key.append(static_cast<const char*>(p), n); }; + put(&blend, sizeof(blend)); + put(&sample_mask, sizeof(sample_mask)); + put(&rasterizer, sizeof(rasterizer)); + put(&depth, sizeof(depth)); + const char bounds = depth_bounds ? 1 : 0; + put(&bounds, 1); + for (std::size_t i = 0; i < inputs.size(); ++i) { + D3D12_INPUT_ELEMENT_DESC e = inputs[i]; + e.SemanticName = nullptr; + put(&e, sizeof(e)); + if (i < names.size()) key += names[i]; + key += '\0'; + } + put(&strip_cut, sizeof(strip_cut)); + put(&topology, sizeof(topology)); + put(&targets, sizeof(targets)); + put(&depth_format, sizeof(depth_format)); + put(&samples, sizeof(samples)); + } +}; + +// Whether `bytes` at `p` may be read; the default trusts the caller. +using VpReadable = bool (*)(const void* p, std::size_t bytes); + +// Takes in one subobject of a stream: its type, then its data at +4 (+8 for those holding pointers). `at` points at +// a whole subobject of type `kind`. +inline void vp_read_subobject(VpGraphicsState& g, std::uint32_t kind, const unsigned char* at, const VpFormatMap& map, + VpReadable readable = nullptr) +{ + const unsigned char* data = at + 4; + switch (kind) { + case 8: std::memcpy(&g.blend, data, sizeof(g.blend)); break; + case 9: std::memcpy(&g.sample_mask, data, sizeof(g.sample_mask)); break; + case 10: std::memcpy(&g.rasterizer, data, sizeof(g.rasterizer)); break; + case 11: + std::memcpy(&g.depth, data, sizeof(g.depth)); + g.depth_bounds = false; + break; + case 21: { + D3D12_DEPTH_STENCIL_DESC1 d{}; + std::memcpy(&d, data, sizeof(d)); + g.depth_bounds = d.DepthBoundsTestEnable != FALSE; + g.depth.DepthEnable = d.DepthEnable; + g.depth.DepthWriteMask = d.DepthWriteMask; + g.depth.DepthFunc = d.DepthFunc; + g.depth.StencilEnable = d.StencilEnable; + g.depth.StencilReadMask = d.StencilReadMask; + g.depth.StencilWriteMask = d.StencilWriteMask; + g.depth.FrontFace = d.FrontFace; + g.depth.BackFace = d.BackFace; + break; + } + case 12: { + D3D12_INPUT_LAYOUT_DESC layout{}; + std::memcpy(&layout, at + 8, sizeof(layout)); + if (!layout.pInputElementDescs) return; + g.inputs.clear(); + g.names.clear(); + UINT count = layout.NumElements; + if (count > D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) { + g.bad_inputs = true; + count = 0; + } + if (count && readable && !readable(layout.pInputElementDescs, count * sizeof(D3D12_INPUT_ELEMENT_DESC))) { + g.bad_inputs = true; + count = 0; + } + for (UINT i = 0; i < count; ++i) { + D3D12_INPUT_ELEMENT_DESC e{}; + std::memcpy(&e, layout.pInputElementDescs + i, sizeof(e)); + std::string name; + if (e.SemanticName) { + // Semantic names are short; one past 255 characters, or not readable, is refused. + const char* s = e.SemanticName; + bool ended = false; + for (std::size_t n = 0; n < 256; ++n) { + if (readable && !readable(s + n, 1)) break; + if (!s[n]) { + ended = true; + break; + } + name += s[n]; + } + if (!ended) g.bad_inputs = true; + } + e.SemanticName = nullptr; + e.Format = vp_map(map.input, static_cast<std::uint32_t>(e.Format)); + g.inputs.push_back(e); + g.names.push_back(std::move(name)); + } + break; + } + case 13: { + std::int32_t v = 0; + std::memcpy(&v, data, sizeof(v)); + g.strip_cut = static_cast<D3D12_INDEX_BUFFER_STRIP_CUT_VALUE>(v); + break; + } + case 14: { + std::int32_t v = 0; + std::memcpy(&v, data, sizeof(v)); + g.topology = static_cast<D3D12_PRIMITIVE_TOPOLOGY_TYPE>(v); + break; + } + case 15: + std::memcpy(&g.targets, data, sizeof(g.targets)); + for (auto& f : g.targets.RTFormats) f = vp_map(map.target, static_cast<std::uint32_t>(f)); + break; + case 16: { + std::uint32_t f = 0; + std::memcpy(&f, data, sizeof(f)); + g.depth_format = vp_map(map.depth, f); + break; + } + case 17: std::memcpy(&g.samples, data, sizeof(g.samples)); break; + default: break; + } +} + +// A shader stage in a stream: its console stage number and the title's bytecode. +struct VpStreamShader { + std::uint32_t stage; + const void* code; + std::size_t size; +}; + +struct VpStream { + std::vector<VpStreamShader> shaders; + VpGraphicsState graphics; + const void* root = nullptr; // the title's root signature (subobject 0), as passed + std::uint32_t stopped_kind = 0; // a type of unknown size ended the walk (stopped is true) + std::size_t stopped_at = 0; + bool stopped = false; + bool truncated = false; // a subobject ran past the stream's end +}; + +// Walks a stream. `stream` is `size` readable bytes (the caller checks that and should pass a copy). Shader stages +// with null code or no bytes are left out. +inline VpStream vp_parse_stream(const void* stream, std::size_t size, const VpFormatMap& map, VpReadable readable = nullptr) +{ + VpStream out; + const auto* bytes = static_cast<const unsigned char*>(stream); + std::size_t at = 0; + while (bytes && at + 8 <= size) { + std::uint32_t kind = 0; + std::memcpy(&kind, bytes + at, sizeof(kind)); + const VpSubobject sub = vp_subobject(kind); + if (!sub.size) { + out.stopped = true; + out.stopped_kind = kind; + out.stopped_at = at; + break; + } + if (sub.size > size - at) { + out.truncated = true; + out.stopped_kind = kind; + out.stopped_at = at; + break; + } + if (kind == 0) std::memcpy(&out.root, bytes + at + 8, sizeof(out.root)); + if (sub.stage) { + D3D12_SHADER_BYTECODE code{}; + std::memcpy(&code, bytes + at + 8, sizeof(code)); + if (code.pShaderBytecode && code.BytecodeLength) out.shaders.push_back({sub.stage, code.pShaderBytecode, code.BytecodeLength}); + } + vp_read_subobject(out.graphics, kind, bytes + at, map, readable); + at += sub.size; + } + return out; +} + +} // namespace x2w_gpu + +// d3d12_xs_device.cpp includes only this WP2 header at its top (outside every namespace); the root signature and +// pipeline builders and the lazy cache that gpu_pipeline.inl uses come with it. Define +// X2W_GPU_PIPELINE_STATE_ONLY for the header-only check, which links no d3d12. +#ifndef X2W_GPU_PIPELINE_STATE_ONLY +#include "startup_stubs/gpu_pipeline_pending.h" +#endif diff --git a/src/startup_stubs/gpu_read_states.h b/src/startup_stubs/gpu_read_states.h new file mode 100644 index 0000000000..98c8416349 --- /dev/null +++ b/src/startup_stubs/gpu_read_states.h @@ -0,0 +1,17 @@ +#pragma once +#include <d3d12.h> + +namespace x2w_gpu { +inline D3D12_RESOURCE_STATES texture_read_state(D3D12_COMMAND_LIST_TYPE type) +{ + return type == D3D12_COMMAND_LIST_TYPE_COMPUTE ? D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE + : D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE; +} + +inline D3D12_RESOURCE_STATES buffer_read_state(D3D12_COMMAND_LIST_TYPE type) +{ + auto state = texture_read_state(type) | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; + if (type == D3D12_COMMAND_LIST_TYPE_DIRECT) state |= D3D12_RESOURCE_STATE_INDEX_BUFFER; + return state; +} +} // namespace x2w_gpu diff --git a/src/startup_stubs/gpu_rect.cpp b/src/startup_stubs/gpu_rect.cpp new file mode 100644 index 0000000000..1b8703fd71 --- /dev/null +++ b/src/startup_stubs/gpu_rect.cpp @@ -0,0 +1,19 @@ +#include "startup_stubs/gpu_rect.h" +#include "startup_stubs/local_log.h" +#include "x2w_shader/emit/rect.h" +#include "x2w_shader/error.h" + +namespace x2w_gpu { +std::vector<unsigned char> vp_rectangle_stage(D3D12_SHADER_BYTECODE vs, D3D12_SHADER_BYTECODE ps) +{ + const auto bytes = [](D3D12_SHADER_BYTECODE code) { + return std::span(static_cast<const std::uint8_t*>(code.pShaderBytecode), code.BytecodeLength); + }; + try { + return x2w::vs::rect_list_gs(bytes(vs), ps.pShaderBytecode ? std::optional(bytes(ps)) : std::nullopt); + } catch (const x2w::vs::ShaderError& e) { + x2w_local::logf("x2w-gpu pipeline: no rectangle geometry stage: %s", e.what()); + return {}; + } +} +} diff --git a/src/startup_stubs/gpu_rect.h b/src/startup_stubs/gpu_rect.h new file mode 100644 index 0000000000..b868d62905 --- /dev/null +++ b/src/startup_stubs/gpu_rect.h @@ -0,0 +1,10 @@ +#pragma once + +#include <d3d12.h> +#include <vector> + +namespace x2w_gpu { +// Generate a geometry stage compatible with these translated stages. An unsupported +// signature leaves rectangle expansion to the draw path. +std::vector<unsigned char> vp_rectangle_stage(D3D12_SHADER_BYTECODE vs, D3D12_SHADER_BYTECODE ps); +} diff --git a/src/startup_stubs/gpu_reference_library.h b/src/startup_stubs/gpu_reference_library.h new file mode 100644 index 0000000000..058bc0feee --- /dev/null +++ b/src/startup_stubs/gpu_reference_library.h @@ -0,0 +1,95 @@ +#pragma once +#include "startup_stubs/blake3/blake3.h" +#include <d3d12.h> +#include <wrl/client.h> +#include <unordered_map> +#include <cstdint> +#include <mutex> +#include <string> +#include <vector> + +namespace x2w_gpu { +// Compute library key from the stage name, serialized root signature, DXIL and empty graphics suffix. +inline std::wstring vp_compute_library_name(const std::vector<unsigned char>& root, D3D12_SHADER_BYTECODE code) +{ + blake3_hasher hash; + blake3_hasher_init(&hash); + auto part = [&](const void* data, std::uint64_t bytes) { + unsigned char length[8]; + for (unsigned i = 0; i < 8; ++i) length[i] = static_cast<unsigned char>(bytes >> (8 * i)); + blake3_hasher_update(&hash, length, sizeof(length)); + if (bytes) blake3_hasher_update(&hash, data, static_cast<std::size_t>(bytes)); + }; + part("compute", 7); + part(root.data(), root.size()); + part(code.pShaderBytecode, code.BytecodeLength); + part(nullptr, 0); + unsigned char digest[16]; + blake3_hasher_finalize(&hash, digest, sizeof(digest)); + constexpr wchar_t hex[] = L"0123456789abcdef"; + std::wstring name(32, L'0'); + for (std::size_t i = 0; i < sizeof(digest); ++i) { + name[2 * i] = hex[digest[i] >> 4]; + name[2 * i + 1] = hex[digest[i] & 15]; + } + return name; +} + +class VpReferenceEntryLocks { +public: + std::mutex& for_name(const std::wstring& name) { + std::lock_guard<std::mutex> lock(index_mutex_); + // References survive rehash. Entries live as long as their library. + return entries_.try_emplace(name).first->second; + } +private: + std::mutex index_mutex_; + std::unordered_map<std::wstring, std::mutex> entries_; +}; + +// D3D12 borrows the library bytes for the lifetime of the object. Keep both the immutable mapping and the +// underlying file handle open across any atomic replacement of the pipeline cache. +class VpReferenceLibrary { +public: + VpReferenceLibrary() = default; + VpReferenceLibrary(const VpReferenceLibrary&) = delete; + VpReferenceLibrary& operator=(const VpReferenceLibrary&) = delete; + ~VpReferenceLibrary() { + library_.Reset(); + if (bytes_) UnmapViewOfFile(bytes_); + if (mapping_) CloseHandle(mapping_); + if (file_ != INVALID_HANDLE_VALUE) CloseHandle(file_); + } + + HRESULT open(ID3D12Device* device, const wchar_t* path) { + if (file_ != INVALID_HANDLE_VALUE) return E_UNEXPECTED; + Microsoft::WRL::ComPtr<ID3D12Device1> device1; + HRESULT hr = device->QueryInterface(IID_PPV_ARGS(&device1)); + if (FAILED(hr)) return hr; + file_ = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file_ == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32(GetLastError()); + LARGE_INTEGER length{}; + if (!GetFileSizeEx(file_, &length)) return HRESULT_FROM_WIN32(GetLastError()); + if (length.QuadPart <= 0 || static_cast<ULONGLONG>(length.QuadPart) > SIZE_MAX) return E_INVALIDARG; + mapping_ = CreateFileMappingW(file_, nullptr, PAGE_READONLY, 0, 0, nullptr); + if (!mapping_) return HRESULT_FROM_WIN32(GetLastError()); + bytes_ = MapViewOfFile(mapping_, FILE_MAP_READ, 0, 0, 0); + if (!bytes_) return HRESULT_FROM_WIN32(GetLastError()); + return device1->CreatePipelineLibrary(bytes_, static_cast<SIZE_T>(length.QuadPart), IID_PPV_ARGS(&library_)); + } + + HRESULT load(const std::wstring& name, const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc, ID3D12PipelineState** result) { + *result = nullptr; + if (!library_) return E_NOINTERFACE; + // D3D12 permits concurrent accesses to the library but requires serialization by entry name. + std::lock_guard<std::mutex> lock(loads_.for_name(name)); + return library_->LoadComputePipeline(name.c_str(), &desc, IID_PPV_ARGS(result)); + } +private: + HANDLE file_ = INVALID_HANDLE_VALUE; + HANDLE mapping_ = nullptr; + const void* bytes_ = nullptr; + Microsoft::WRL::ComPtr<ID3D12PipelineLibrary> library_; + VpReferenceEntryLocks loads_; +}; +} // namespace x2w_gpu diff --git a/src/startup_stubs/gpu_resident_mips.h b/src/startup_stubs/gpu_resident_mips.h new file mode 100644 index 0000000000..a20bc6d950 --- /dev/null +++ b/src/startup_stubs/gpu_resident_mips.h @@ -0,0 +1,114 @@ +#pragma once + +#include "startup_stubs/gfx10_layout_local.h" +#include <d3d12.h> +#include <algorithm> +#include <cstdint> +#include <cstring> + +namespace x2w_resident_mips { +struct Suffix { + unsigned first; + std::uint64_t prefix; +}; + +inline std::uint64_t prefix_bytes(const x2w_startup::gfx10_local::Layout& layout, unsigned first) +{ + if (!first) return layout.slice_size; + const auto end = layout.level[first - 1].offset; + return !end && !layout.linear ? std::uint64_t{1} << layout.block_log2 : end; +} + +// Only omit levels already hidden by the title SRV. A shader using GetDimensions, +// Load, or explicit SampleLevel must see the same logical mip zero after rebasing. +inline UINT host_base(const D3D12_RESOURCE_DESC& desc, const D3D12_SHADER_RESOURCE_VIEW_DESC& view, + const x2w_startup::gfx10_local::Layout& layout, bool compressed) +{ + if (!layout.valid || layout.thick || layout.slices != 1 || !layout.mips || + desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1 || + view.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D || view.Texture2D.MostDetailedMip >= layout.mips) + return 0; + UINT base = view.Texture2D.MostDetailedMip; + while (base && !layout.linear && !layout.level[base - 1].offset) --base; + while (base && compressed && ((desc.Width >> base) < 4 || (desc.Height >> base) < 4 || + ((desc.Width >> base) % 4) || ((desc.Height >> base) % 4))) --base; + return prefix_bytes(layout, base) < layout.slice_size ? base : 0; +} + +inline D3D12_RESOURCE_DESC host_desc(D3D12_RESOURCE_DESC desc, UINT base) +{ + if (!base) return desc; + desc.Width = (std::max)(UINT64{1}, desc.Width >> base); + desc.Height = (std::max)(1u, desc.Height >> base); + desc.MipLevels = static_cast<UINT16>(desc.MipLevels - base); + return desc; +} + +inline void rebase(D3D12_SHADER_RESOURCE_VIEW_DESC& view, UINT base) +{ + if (!base) return; + auto& v = view.Texture2D; + v.MostDetailedMip -= base; + v.ResourceMinLODClamp = (std::max)(0.0f, v.ResourceMinLODClamp - static_cast<float>(base)); +} + +// Each thin slice stores its smallest mip(s) first. Tiled mip tails share an entire block. +// Require the same suffix in every array slice; array indexing must never reach an unfilled slice. +template<class Readable> +Suffix find(const x2w_startup::gfx10_local::Layout& layout, std::uintptr_t address, Readable readable) +{ + const Suffix none{layout.mips, 0}; + if (!layout.valid || layout.thick || !layout.mips || !layout.slice_size || !address || + layout.size > (1ull << 30) || layout.size > UINTPTR_MAX - address) return none; + const auto available = [&](unsigned first) { + const auto bytes = prefix_bytes(layout, first); + if (!bytes || bytes > layout.slice_size) return false; + for (unsigned slice = 0; slice < layout.slices; ++slice) + if (!readable(address + slice * layout.slice_size, bytes)) return false; + return true; + }; + unsigned lo = 0, hi = layout.mips; + while (lo < hi) { + const auto mid = lo + (hi - lo) / 2; + if (available(mid)) hi = mid; + else lo = mid + 1; + } + return lo == layout.mips ? none : Suffix{lo, prefix_bytes(layout, lo)}; +} + +inline bool stage_rows(const x2w_startup::gfx10_local::Layout& layout, Suffix suffix, UINT mip, + const unsigned char* source, unsigned char* destination, UINT columns, UINT rows, UINT pitch) +{ + if (!source || !destination || mip < suffix.first || mip >= layout.mips) return false; + const auto element = 1u << layout.elem_log2; + if (std::uint64_t(columns) * element > pitch) return false; + for (UINT y = 0; y < rows; ++y) { + auto* out = destination + std::uint64_t(y) * pitch; + for (UINT x = 0; x < columns; ++x) { + const auto offset = layout.address(mip, x, y, 0); + if (offset + element > suffix.prefix) return false; + std::memcpy(out + std::uint64_t(x) * element, source + offset, element); + } + } + return true; +} +inline bool limit_view(D3D12_SHADER_RESOURCE_VIEW_DESC& view, unsigned mips, unsigned first) +{ + const auto apply = [&](auto& v) { + if (v.MostDetailedMip >= mips || first >= mips || !v.MipLevels) return false; + const UINT count = (std::min)(v.MipLevels, mips - v.MostDetailedMip); + if (first >= v.MostDetailedMip + count) return false; + if (first <= v.MostDetailedMip) return true; + // Preserve the shader's mip numbering and dimensions. For a rebased title view, + // defer until its own base is resident instead of combining two LOD origins. + if (v.MostDetailedMip) return false; + v.ResourceMinLODClamp = (std::max)(v.ResourceMinLODClamp, static_cast<float>(first)); + return true; + }; + switch (view.ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE2D: return apply(view.Texture2D); + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: return apply(view.Texture2DArray); + default: return false; + } +} +} diff --git a/src/startup_stubs/gpu_roots.h b/src/startup_stubs/gpu_roots.h new file mode 100644 index 0000000000..361239a9ee --- /dev/null +++ b/src/startup_stubs/gpu_roots.h @@ -0,0 +1,545 @@ +// Per-list graphics and compute root arguments, input-assembler views, topology, heaps and dynamic slots. User data +// is passed as root constants at b0 space0. A table dword is a byte offset in console heap units (32 bytes per +// view, 16 per sampler). RootType::Other codes select host-computed values. +#pragma once + +#include "startup_stubs/gpu_abi.h" +#include "startup_stubs/gpu_memory.h" +#include "startup_stubs/gpu_compute_trace.h" +#include "startup_stubs/gpu_ambient.h" +#include "startup_stubs/gpu_memory_arena.h" +#include "startup_stubs/gpu_packed_light.h" +#include "startup_stubs/gpu_table_constants.h" + +#include <algorithm> +#include <cstddef> +#include <cstdint> +#include <optional> +#include <unordered_map> +#include <utility> +#include <vector> +#if defined(_MSC_VER) +#include <intrin.h> +#endif + +namespace x2w_vbind { + +using x2w_gpu::GpuResourceType; +using x2w_gpu::GpuRoot; +using x2w_gpu::GpuRootIndexedView; +using x2w_gpu::GpuRootKind; +using x2w_gpu::GpuRootType; +using x2w_gpu::GpuUsedResource; +using x2w_gpu::GpuUserData; +namespace abi = x2w_gpu::abi; + +inline constexpr std::uint32_t fresh_most = 1u << 18; // Maximum slots in a single fresh table. +inline constexpr std::uint32_t mesh_groups_most = 65535; // DispatchMesh: the host's limit per dimension + +inline bool is_view(GpuRootKind k) +{ + return k == GpuRootKind::cbv || k == GpuRootKind::srv || k == GpuRootKind::uav; +} + +struct VertexView { std::uint64_t address = 0; std::uint32_t size = 0, stride = 0; }; // D3D12_VERTEX_BUFFER_VIEW +struct IndexView { std::uint64_t address = 0; std::uint32_t size = 0, format = 0; }; // D3D12_INDEX_BUFFER_VIEW + +// Separate graphics and compute root arguments, 32 input-assembler vertex slots and the title topology. +struct Roots { + std::vector<GpuRoot> graphics, compute; + VertexView vertex[32]{}; + IndexView index{}; + std::uint32_t topology = 0; // console numbering + bool topology_set = false; + + std::vector<GpuRoot>& of(bool is_compute) { return is_compute ? compute : graphics; } + const std::vector<GpuRoot>& of(bool is_compute) const { return is_compute ? compute : graphics; } + const GpuRoot* at(bool is_compute, std::uint32_t slot) const + { + const auto& r = of(is_compute); + return slot < r.size() ? &r[slot] : nullptr; + } + GpuRoot& place(bool is_compute, std::uint32_t slot) + { + auto& r = of(is_compute); + if (r.size() <= slot) r.resize(std::size_t{slot} + 1); + return r[slot]; + } + void set_table(bool is_compute, std::uint32_t slot, std::uint64_t handle) + { + GpuRoot& r = place(is_compute, slot); + r.kind = GpuRootKind::table; + r.handle = handle; + r.address = 0; + r.dwords.clear(); + } + void set_view(bool is_compute, std::uint32_t slot, std::uint64_t address, GpuRootKind kind) + { + GpuRoot& r = place(is_compute, slot); + r.kind = is_view(kind) ? kind : GpuRootKind::srv; + r.address = address; + r.handle = 0; + r.dwords.clear(); + } + // A parameter previously holding another kind starts empty and grows to offset + count. + void set_constants(bool is_compute, std::uint32_t slot, const std::uint32_t* values, std::uint32_t count, std::uint32_t offset) + { + GpuRoot& r = place(is_compute, slot); + if (r.kind != GpuRootKind::constants) { + r.kind = GpuRootKind::constants; + r.handle = r.address = 0; + r.dwords.clear(); + } + const std::size_t end = std::size_t{offset} + count; + if (r.dwords.size() < end) r.dwords.resize(end, 0); + for (std::uint32_t i = 0; i < count; ++i) r.dwords[std::size_t{offset} + i] = values[i]; + } + void set_vertex(std::uint32_t start, std::uint32_t count, const VertexView* views) + { + for (std::uint32_t i = 0; i < count && std::size_t{start} + i < 32; ++i) + vertex[start + i] = views ? views[i] : VertexView{}; + } + void set_index(const IndexView* view) { index = view ? *view : IndexView{}; } + void clear() { *this = Roots{}; } +}; + +// ---- topology ------------------------------------------------------------------- +inline constexpr std::uint32_t topology_triangle_fan = 6; +inline constexpr std::uint32_t topology_rectangles = 17; +inline constexpr std::uint32_t topology_line_loop = 18; +inline constexpr std::uint32_t topology_quads = 19; +inline constexpr std::uint32_t topology_quad_strip = 20; +// The host topology for the title's: the console-only ones become triangle lists (4). +inline std::uint32_t host_topology(std::uint32_t title) +{ + switch (title) { + case topology_rectangles: + case topology_triangle_fan: + case topology_line_loop: + case topology_quads: + case topology_quad_strip: return 4; + default: return title; + } +} + +// ---- user data --------------------------------------------------------------------- +// A heap the title bound: its title GPU start, its descriptor count, and whether it holds samplers. +struct HeapSpan { + std::uint64_t start = 0; + std::uint32_t count = 0; + bool samplers = false; + std::uint32_t step() const { return samplers ? abi::sampler_increment : abi::view_increment; } + std::optional<std::uint32_t> index(std::uint64_t handle) const + { + if (!start || handle < start) return std::nullopt; + const std::uint64_t i = (handle - start) / step(); + return i < count ? std::optional<std::uint32_t>(static_cast<std::uint32_t>(i)) : std::nullopt; + } +}; +// The bound heap holding `handle`. +inline const HeapSpan* heap_of(const HeapSpan* heaps, std::size_t n, std::uint64_t handle) +{ + for (std::size_t i = 0; i < n; ++i) + if (heaps[i].start && heaps[i].index(handle)) return &heaps[i]; + return nullptr; +} + +// Why a user-data dword came out 0 (counted by the caller). +enum class UserMiss : std::uint8_t { none, table_outside_heaps, root_not_set, unknown_host_word, view_address_missing }; + +// The value of a user-data dword that names a title root argument: a table's byte offset in its heap (console +// units), a constant's value. Other(...) codes are the host's (host_word), 0 here. +inline std::uint32_t user_value(const Roots& roots, bool is_compute, std::uint32_t slot, GpuRootType root, std::uint32_t dword, + const HeapSpan* heaps, std::size_t heap_count, UserMiss* miss = nullptr) +{ + if (root == GpuRootType::other) return 0; + const GpuRoot* r = roots.at(is_compute, slot); + if (r && r->kind == GpuRootKind::table && root == GpuRootType::table) { + if (const HeapSpan* h = heap_of(heaps, heap_count, r->handle)) return static_cast<std::uint32_t>(r->handle - h->start); + if (miss) *miss = UserMiss::table_outside_heaps; + return 0; + } + if (r && r->kind == GpuRootKind::constants && root == GpuRootType::constants) + return dword < r->dwords.size() ? r->dwords[dword] : 0; + if (miss) *miss = UserMiss::root_not_set; + return 0; +} + +// The bias the bound raw view of root parameter `slot` begins before the title's address (0-15), as the caller +// bound it (root_srv_table / root_uav): taken from what was bound, not found again. +struct BoundBias { + std::uint32_t slot; + std::uint32_t bias; +}; +inline std::uint32_t bias_of(const std::vector<BoundBias>& bound, std::uint32_t slot) +{ + for (const auto& b : bound) + if (b.slot == slot) return b.bias; + return 0; +} + +// A host-computed user-data dword. `view_address(slot, dword)` gives the title address of the buffer view at dword +// `dword` of the table in root parameter `slot` (0: none). +template<class ViewAddress> +std::uint32_t host_word(const Roots& roots, bool is_compute, std::uint32_t code, std::uint32_t slot, std::uint32_t dword, + const std::vector<BoundBias>& biases, std::uint32_t memory_base, ViewAddress&& view_address, + UserMiss* miss = nullptr) +{ + if (code == abi::user_memory_base) return memory_base; + if (code == abi::user_dispatch_threads_x) return 0; // all of every group, unless the dispatch says otherwise + const GpuRoot* r = roots.at(is_compute, slot); + if (code == abi::user_root_address || code == abi::user_root_address + 1) { + if (!r || !is_view(r->kind)) return 0; + return code == abi::user_root_address ? static_cast<std::uint32_t>(r->address) : static_cast<std::uint32_t>(r->address >> 32); + } + if (code == abi::user_view_bias) return r && is_view(r->kind) ? bias_of(biases, slot) : 0; + if (code != abi::user_view_address && code != abi::user_view_address + 1) { + if (miss) *miss = UserMiss::unknown_host_word; + return 0; + } + const std::uint64_t address = r && r->kind == GpuRootKind::table ? static_cast<std::uint64_t>(view_address(slot, dword)) : 0; + if (!address && miss) *miss = UserMiss::view_address_missing; + return code == abi::user_view_address ? static_cast<std::uint32_t>(address) : static_cast<std::uint32_t>(address >> 32); +} + +// The fresh offset a table got for this draw (tables()), by root parameter. UINT32_MAX: no room (drop the draw). +struct MadeTable { + std::uint32_t slot; + std::uint32_t offset; +}; + +// The stage's user-data dwords: `dwords` of them, every word the shader reads filled in. Words whose index lies +// past `dwords` are left out (the pipeline's root has only `dwords`). +template<class ViewAddress> +std::vector<std::uint32_t> fill_user_data(const Roots& roots, bool is_compute, const GpuUserData* words, std::size_t word_count, + std::uint32_t dwords, const std::vector<MadeTable>& made, const HeapSpan* heaps, + std::size_t heap_count, const std::vector<BoundBias>& biases, + std::uint32_t memory_base, ViewAddress&& view_address, unsigned* misses = nullptr) +{ + std::vector<std::uint32_t> values(dwords, 0); + for (std::size_t i = 0; i < word_count; ++i) { + const GpuUserData& u = words[i]; + if (u.index >= dwords) continue; + UserMiss miss = UserMiss::none; + if (u.root == GpuRootType::other) { + values[u.index] = host_word(roots, is_compute, u.other, u.slot, u.dword, biases, memory_base, view_address, &miss); + } else { + const auto fresh = std::find_if(made.begin(), made.end(), [&](const MadeTable& m) { + return m.slot == u.slot && u.root == GpuRootType::table; + }); + values[u.index] = fresh != made.end() ? fresh->offset + : user_value(roots, is_compute, u.slot, u.root, u.dword, heaps, heap_count, &miss); + } + if (miss != UserMiss::none && misses) ++*misses; + } + return values; +} + +// ---- tables made afresh -------------------------------------------------------- +// A table the draw gets in dynamic slots: root parameter, title GPU handle, slot count, and the entries root state +// selects (root_indexed_views), by descriptor index in the table, sorted. +struct FreshPlan { + std::uint32_t slot; + std::uint64_t table; + std::uint32_t n; + std::vector<std::uint32_t> selected; +}; +enum class PlanSkip : std::uint8_t { none, sampler_or_unaligned, too_long }; +struct TablePlan { + std::vector<FreshPlan> fresh; // tables made afresh (constant buffers; past the host heap) + std::vector<std::size_t> mirrored; // indices into `used` whose entry is mirrored in place (table_entry) + std::vector<std::pair<std::uint32_t, PlanSkip>> skipped; // Fresh tables left as the title's +}; +inline bool in_table(const GpuUsedResource& u) { return u.root == GpuRootType::table; } + +// `host_count(heap)`: how many title slots the host heap holds (normally heap.count). Tables holding a CBV are made +// afresh (the host wants 256-byte aligned CBVs, the console 16), and tables reaching past the host's slots. +template<class HostCount> +TablePlan plan_tables(const Roots& roots, bool is_compute, const GpuUsedResource* used, std::size_t used_count, + const GpuRootIndexedView* indexed, std::size_t indexed_count, const HeapSpan* heaps, std::size_t heap_count, + HostCount&& host_count) +{ + TablePlan plan; + std::vector<std::uint32_t> fresh; + const auto has = [&](std::uint32_t s) { return std::find(fresh.begin(), fresh.end(), s) != fresh.end(); }; + for (std::size_t i = 0; i < used_count; ++i) + if (in_table(used[i]) && used[i].kind == GpuResourceType::cbv && !has(used[i].slot)) fresh.push_back(used[i].slot); + for (std::size_t i = 0; i < used_count; ++i) { + const GpuUsedResource& u = used[i]; + if (!in_table(u) || has(u.slot)) continue; + const GpuRoot* r = roots.at(is_compute, u.slot); + if (!r || r->kind != GpuRootKind::table) continue; + const std::uint64_t end = r->handle + std::uint64_t{u.table_offset_dwords} * 4; + const HeapSpan* h = heap_of(heaps, heap_count, r->handle); + if (!h) continue; + const auto index = h->index(end); + if (!index) continue; + if (*index >= host_count(*h)) fresh.push_back(u.slot); + } + std::sort(fresh.begin(), fresh.end()); + for (std::size_t i = 0; i < used_count; ++i) + if (in_table(used[i]) && !has(used[i].slot)) plan.mirrored.push_back(i); + for (const std::uint32_t slot : fresh) { + const GpuRoot* r = roots.at(is_compute, slot); + if (!r || r->kind != GpuRootKind::table) continue; + const std::uint64_t table = r->handle; + const HeapSpan* h = heap_of(heaps, heap_count, table); + if (!h) continue; + if (h->samplers || (table - h->start) % abi::view_increment != 0) { + plan.skipped.emplace_back(slot, PlanSkip::sampler_or_unaligned); + continue; + } + std::vector<std::uint32_t> selected; + for (std::size_t k = 0; k < indexed_count; ++k) { + const GpuRootIndexedView& x = indexed[k]; + if (x.table_slot != slot) continue; + const std::uint32_t constant = user_value(roots, is_compute, x.constant_slot, GpuRootType::constants, + x.constant_dword, heaps, heap_count); + // The shader adds i32 byte offsets and shifts by 5 (u32 wrapping). + selected.push_back((x.byte_offset + (constant << x.shift)) / abi::view_increment); + } + std::sort(selected.begin(), selected.end()); + selected.erase(std::unique(selected.begin(), selected.end()), selected.end()); + std::uint32_t most = selected.empty() ? 0 : selected.back(); + for (std::size_t i = 0; i < used_count; ++i) + if (in_table(used[i]) && used[i].slot == slot) most = (std::max)(most, used[i].table_offset_dwords / 8); + const std::uint32_t n = most + 1; + const std::uint64_t last = table + std::uint64_t{n - 1} * abi::view_increment; + if (n > fresh_most || last < table || !h->index(last)) { + plan.skipped.emplace_back(slot, PlanSkip::too_long); + continue; + } + plan.fresh.push_back({slot, table, n, std::move(selected)}); + } + return plan; +} + +// ---- RecordHash: a hash of descriptor records' first three words ------------------------------------- +inline std::uint64_t fold64(std::uint64_t x, std::uint64_t y) +{ +#if defined(_MSC_VER) && defined(_M_X64) + std::uint64_t high = 0; + const std::uint64_t low = _umul128(x, y, &high); + return low ^ high; +#else + const unsigned __int128 p = static_cast<unsigned __int128>(x) * y; + return static_cast<std::uint64_t>(p) ^ static_cast<std::uint64_t>(p >> 64); +#endif +} +struct RecordHash { + std::uint64_t value = 0; + void add_record(const std::uint32_t (&record)[8]) + { + add(record[0], record[1], record[2]); + add(record[3], record[4], record[5]); + add(record[6], record[7], 0); + } + void add(std::uint32_t a, std::uint32_t b, std::uint32_t c) + { + const std::uint64_t words = std::uint64_t{a} << 32 | b; + const std::uint64_t first = fold64(value ^ words ^ 0x2d358dccaa6c78a5ull, 0x8bb84b93962eacc9ull ^ std::uint64_t{c}); + const std::uint64_t rotated = value << 23 | value >> 41; + value = fold64(first ^ 0x4b33a62ed433d4a3ull, 0x4d5a2da51de1aa47ull ^ rotated) ^ first; + } +}; + +// ---- dispatch arithmetic -------------------------------------------------------------------------------------------- +// The groups of `size` threads that hold `threads`. +inline void dispatch_groups(const std::uint32_t threads[3], const std::uint32_t size[3], std::uint32_t out[3]) +{ + for (int i = 0; i < 3; ++i) out[i] = size[i] ? (threads[i] + size[i] - 1) / size[i] : 0; +} +// DispatchMesh(x, 1, 1): the console's mesh programs count groups in x only; the host takes 65,535 a dimension. +inline std::uint32_t mesh_groups(std::uint32_t x) { return (std::min)(x, mesh_groups_most); } + +// ---- raw view bounding ------------------------------------------------------------ +// A raw view for a root view at byte `offset` of its host buffer with `left` bytes after it: from the 16 bytes +// below when the shader adds the bias (biased), else only when on 16 bytes. False: a null view. +struct RawWindow { + std::uint64_t first = 0; // byte offset of the view in the buffer (a multiple of 16) + std::uint64_t bytes = 0; // bytes the view covers + std::uint32_t bias = 0; // what the shader adds (USER_VIEW_BIAS) +}; +inline bool raw_window(std::uint64_t offset, std::uint64_t left, bool biased, RawWindow* out) +{ + if (!left) return false; + const std::uint64_t bias = offset & 15; + if (!biased && bias) return false; // "a root SRV not on 16 bytes reads zeros" + out->first = offset - bias; + out->bytes = left + bias; + out->bias = static_cast<std::uint32_t>(bias); + return true; +} +// A raw R32_TYPELESS view spans whole dwords with a minimum of one element. +inline std::uint32_t raw_elements(std::uint64_t bytes) +{ + const std::uint64_t n = bytes / 4; + return n < 1 ? 1u : n > 0xffffffffull ? 0xffffffffu : static_cast<std::uint32_t>(n); +} +// A root CBV covers up to 64 KiB, bounded by the end of its buffer. +inline std::uint64_t root_cbv_bytes(std::uint64_t left) { return (std::min)(left, std::uint64_t{1} << 16); } +// The size of a CBV for `bytes` of constants: 256-byte steps, at most 64 KiB (D3D12's limits). +inline std::uint32_t constant_view_bytes(std::uint64_t bytes) +{ + const std::uint64_t b = (std::min)(bytes, std::uint64_t{1} << 16); + return static_cast<std::uint32_t>((b + 255) & ~std::uint64_t{255}); +} + +// Bound a title buffer access by the allocation end, contiguous desktop window and caller limit. Desktop windows +// can span 512 MiB, so using the window end alone can let a raw UAV overwrite neighboring title allocations. +// Without a title buffer record only unknown_most bytes may be exposed; zero refuses the access. The extent +// callback locates the title allocation and the window callback resolves the bounded range to a host buffer and +// offset. +struct TitleBufferExtent { + std::uint64_t base{}, end{}; + std::uintptr_t identity{}; + + bool consider(std::uint64_t address, std::uint64_t length, std::uint64_t start, + std::uint64_t bytes, std::uintptr_t id) + { + if (!start || address < start || address - start >= bytes || bytes > UINT64_MAX - start) return false; + const auto limit = start + bytes; + const bool covers = length <= limit - address; + const bool previous_covers = base && length <= end - address; + if (base && (covers != previous_covers ? !covers : + start < base || (start == base && id <= identity))) return false; + base = start; + end = limit; + identity = id; + return true; + } +}; + +struct Found { + void* buffer = nullptr; // the desktop window (ID3D12Resource*) + std::uint64_t offset = 0; // byte offset of `address` in it + std::uint64_t left = 0; // bytes usable from `address` on + bool known_extent = false; // a title buffer record bounds `left` + bool cut_by_window = false; // the title buffer runs on past where the window allows +}; + +template<class Extent, class Window> +bool find_bounded(std::uint64_t address, std::uint64_t len, std::uint64_t most, std::uint64_t unknown_most, Extent&& extent, + Window&& window, Found* out) +{ + *out = Found{}; + if (!address || !len) return false; + std::uint64_t base = 0, end = 0; + std::uint64_t left = 0; + if (extent(address, &base, &end) && end > address) { + left = end - address; + out->known_extent = true; + } else { + left = unknown_most; // no record: only the caller's allowance for unknown memory + } + if (left > most) left = most; + if (left > ~0ull - address) left = ~0ull - address; // an unbounded allowance must not wrap the address space + if (left < len) return false; + void* buffer = nullptr; + std::uint64_t offset = 0; + if (!window(address, len, &buffer, &offset) || !buffer) return false; + // The whole bounded range in one window, else the longest prefix of it that is. Windows break only on page + // boundaries (64 KiB chunk pages, 256 MiB window steps, allocation ends), so the prefix ends on the last 4 KiB + // boundary that still answers: a binary search over boundaries (at most ~17 tries for 512 MiB; desktop_range + // caches its answers per frame). + void* b = nullptr; + std::uint64_t o = 0; + if (left != len && (!window(address, left, &b, &o) || b != buffer)) { + constexpr std::uint64_t page = 4096; + std::uint64_t good_end = address + len; + const std::uint64_t bad_end = address + left; + std::uint64_t lo = (good_end + page - 1) / page, hi = (bad_end - 1) / page; + while (lo <= hi) { + const std::uint64_t mid = lo + (hi - lo) / 2; + if (mid * page > good_end && window(address, mid * page - address, &b, &o) && b == buffer) { + good_end = mid * page; + lo = mid + 1; + } else if (mid * page <= good_end) { + lo = mid + 1; + } else { + hi = mid - 1; + } + } + left = good_end - address; + out->cut_by_window = true; + } + out->buffer = buffer; + out->offset = offset; + out->left = left; + return true; +} + + +// ---- per-list host-side bookkeeping --------- +struct Dynamic { + x2w_gpu::GpuHostHeap* heap; + std::uint32_t first, n; +}; +struct RootSlot { + std::uint32_t index; // the dynamic slot holding the one-view table + ID3D12Resource* window; // the desktop window it shows (null: a null view) + std::uint32_t bias; // what the shader adds (biased SRVs, UAVs) +}; +struct KeyHash { + std::size_t operator()(const std::pair<const void*, std::uint64_t>& k) const + { + return std::hash<std::uint64_t>()(reinterpret_cast<std::uint64_t>(k.first) * 1099511628211ull ^ k.second); + } +}; +struct FreshKey { + std::uint64_t table; + std::uint32_t n; + std::uint64_t hash; + bool operator==(const FreshKey& o) const { return table == o.table && n == o.n && hash == o.hash; } +}; +struct FreshHash { + std::size_t operator()(const FreshKey& k) const + { + return std::hash<std::uint64_t>()(k.table ^ (std::uint64_t{k.n} << 40) ^ k.hash * 31); + } +}; + +} // namespace x2w_vbind + +// One command list's translated state (declared in gpu_abi.h), hung off the list wrapper's own().gpu[0] +// (gpu_hooks.h). Made at the first hook call on the list, freed by gpu_list_released. A list records on one +// thread at a time. +namespace x2w_gpu { +struct GpuListState { + x2w_vbind::Roots roots; + ambient::Role light_role = ambient::Role::none; + ambient::Views light_views{}; + UINT64 light_depth_width = 0; + UINT light_depth_height = 0; + LONG trace_request = 0; + const GpuShader* trace_shader = nullptr; + UINT material_raw_slot = 0, material_base = 0; + const GpuShader* material_shader = nullptr; + GpuHostHeap* material_heap = nullptr; + x2w_compute_trace::Bindings trace_bindings; + std::vector<x2w_compute_trace::Binding> pixel_bindings; + const GpuShader* pixel_capture_shader = nullptr; + const GpuPipeline* pixel_capture_pipeline = nullptr; + std::shared_ptr<x2w_compute_trace::Capture> trace_current; + std::vector<std::shared_ptr<x2w_compute_trace::Capture>> trace_captures; + bool vertex_hooked = false; // slots 47/48 reached us (else X2W's Pass.vb / Pass.ib are read) + void* pipeline = nullptr; // slot 25: the title pipeline wrapper + void* heaps[2]{}; // slot 32: view heap, sampler heap (title wrappers) + // What the host list has (only trusted with X2W_GPU_BIND_CACHE=1, or until gpu_bind_forget_compute). + ID3D12DescriptorHeap* host_heaps[2]{}; + ID3D12RootSignature* host_roots[2]{}; // graphics, compute + ID3D12PipelineState* host_pso = nullptr; + // Made in this recording, given back with `dynamic`. + std::unordered_map<x2w_vbind::FreshKey, std::uint32_t, x2w_vbind::FreshHash> fresh_tables; + TableConstants table_constants; + std::unordered_map<std::pair<const void*, std::uint64_t>, x2w_vbind::RootSlot, x2w_vbind::KeyHash> root_srv_slots, root_uav_slots; + std::vector<x2w_vbind::Dynamic> dynamic; + std::vector<std::shared_ptr<x2w_depth_twins::Twins>> depth_refs; + std::vector<std::shared_ptr<x2w_vmemory::Recording>> memories; + std::vector<x2w_vmemory::CopyBack> memory_back; + std::vector<std::shared_ptr<x2w_packed_light::Copy>> light_copies; + std::vector<x2w_depth_twins::Twins*> writable_depth; + // The fences of this recording's submissions: its slots go back once all have passed (X2W does not wait). + std::vector<std::pair<ID3D12Fence*, std::uint64_t>> submitted; +}; +} // namespace x2w_gpu diff --git a/src/startup_stubs/gpu_srgb.h b/src/startup_stubs/gpu_srgb.h new file mode 100644 index 0000000000..0fc7a65810 --- /dev/null +++ b/src/startup_stubs/gpu_srgb.h @@ -0,0 +1,83 @@ +#pragma once +#include <d3d12.h> + +namespace x2w_srgb { +inline DXGI_FORMAT family(DXGI_FORMAT f) +{ + switch (f) { + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return DXGI_FORMAT_R8G8B8A8_TYPELESS; + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8A8_TYPELESS; + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8X8_TYPELESS; + default: return f; + } +} + +inline DXGI_FORMAT linear(DXGI_FORMAT f) +{ + switch (f) { + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM; + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8A8_UNORM; + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8X8_UNORM; + default: return f; + } +} + +inline DXGI_FORMAT backing_format(const D3D12_RESOURCE_DESC& d) +{ + if (d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + return family(d.Format); + return d.Format; +} + +// These resources allow unordered access, which rules out multisampling. A default view addresses +// all slices and the first mip for a target, or all mips for a shader resource. +inline D3D12_SHADER_RESOURCE_VIEW_DESC srv(const D3D12_RESOURCE_DESC& d, DXGI_FORMAT format) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = format; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + const UINT slices = d.DepthOrArraySize; + if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && slices == 1) { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; v.Texture1D.MipLevels = d.MipLevels; + } else if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY; v.Texture1DArray.MipLevels = d.MipLevels; v.Texture1DArray.ArraySize = slices; + } else if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; v.Texture3D.MipLevels = d.MipLevels; + } else if (slices == 1) { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; v.Texture2D.MipLevels = d.MipLevels; + } else { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; v.Texture2DArray.MipLevels = d.MipLevels; v.Texture2DArray.ArraySize = slices; + } + return v; +} + +inline D3D12_UNORDERED_ACCESS_VIEW_DESC uav(const D3D12_RESOURCE_DESC& d, DXGI_FORMAT format) +{ + D3D12_UNORDERED_ACCESS_VIEW_DESC v{}; + v.Format = linear(format); + const UINT slices = d.DepthOrArraySize; + if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && slices == 1) v.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; + else if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) { + v.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; v.Texture1DArray.ArraySize = slices; + } else if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { + v.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; v.Texture3D.WSize = slices; + } else if (slices == 1) v.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + else { v.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; v.Texture2DArray.ArraySize = slices; } + return v; +} + +inline D3D12_RENDER_TARGET_VIEW_DESC rtv(const D3D12_RESOURCE_DESC& d, DXGI_FORMAT format) +{ + D3D12_RENDER_TARGET_VIEW_DESC v{}; + v.Format = format; + const UINT slices = d.DepthOrArraySize; + if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && slices == 1) v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D; + else if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY; v.Texture1DArray.ArraySize = slices; + } else if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D; v.Texture3D.WSize = slices; + } else if (slices == 1) v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; + else { v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; v.Texture2DArray.ArraySize = slices; } + return v; +} +} // namespace x2w_srgb diff --git a/src/startup_stubs/gpu_table_constants.h b/src/startup_stubs/gpu_table_constants.h new file mode 100644 index 0000000000..1024d1cb92 --- /dev/null +++ b/src/startup_stubs/gpu_table_constants.h @@ -0,0 +1,60 @@ +#pragma once + +#include <windows.h> +#include <d3d12.h> +#include <array> +#include <cstdint> +#include <cstring> +#include <vector> + +namespace x2w_gpu { +// Ring offsets survive until first execution; generations distinguish a recycled +// backing chunk. The original CPU bytes let us compare without reading GPU upload memory. +struct TableConstantSlice { + UINT chunk; + UINT64 generation, offset; +}; +struct TableConstantRefresh { + size_t checked = 0, changed = 0, unreadable = 0, stale = 0; +}; +class TableConstants { + struct Fill { + const unsigned char* source; + TableConstantSlice slice; + size_t start, bytes; + }; + std::vector<Fill> fills_; + std::vector<unsigned char> original_; +public: + // Take one snapshot for both the original descriptor and the comparison. + const unsigned char* remember(const void* source, size_t bytes, TableConstantSlice slice) + { + const auto start = original_.size(); + const auto* ptr = static_cast<const unsigned char*>(source); + original_.insert(original_.end(), ptr, ptr + bytes); + fills_.push_back({ptr, slice, start, bytes}); + return original_.data() + start; + } + template<class Write> TableConstantRefresh first_submit(Write write) + { + TableConstantRefresh result; + if (fills_.empty()) return result; + static thread_local std::array<unsigned char, D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT * 16> scratch; + for (const auto& fill : fills_) { + ++result.checked; + SIZE_T read = 0; + if (fill.bytes > scratch.size() || !ReadProcessMemory(GetCurrentProcess(), fill.source, scratch.data(), fill.bytes, &read) || + read != fill.bytes) { + ++result.unreadable; + continue; + } + if (std::memcmp(original_.data() + fill.start, scratch.data(), fill.bytes) == 0) continue; + if (write(fill.slice, scratch.data(), fill.bytes)) ++result.changed; + else ++result.stale; + } + clear(); + return result; + } + void clear() { fills_.clear(); original_.clear(); } +}; +} diff --git a/src/startup_stubs/gpu_trace_request.h b/src/startup_stubs/gpu_trace_request.h new file mode 100644 index 0000000000..125131c016 --- /dev/null +++ b/src/startup_stubs/gpu_trace_request.h @@ -0,0 +1,93 @@ +#pragma once + +#include <charconv> +#include <array> +#include <cstdint> +#include <optional> +#include <string_view> + +namespace x2w_gpu { + +using CapturePoint = std::optional<std::array<unsigned, 2>>; +struct SceneRequest { + long id; + std::string_view stage_key; + std::string_view second_key; + CapturePoint point{}; +}; + +inline std::optional<std::uint64_t> stage_key_number(std::string_view key) +{ + if (key.size() != 16) return {}; + std::uint64_t value{}; + const auto result = std::from_chars(key.data(), key.data() + key.size(), value, 16); + if (result.ec != std::errc{} || result.ptr != key.data() + key.size()) return {}; + return value; +} + +// Accessed under the capture mutex. A bind from an earlier request cannot claim a new slot. +struct CaptureSelection { + long id{}; + std::array<std::optional<std::uint64_t>, 2> keys; + bool paired{}; + + bool matches(long request, std::string_view key) const + { + const auto value = stage_key_number(key); + return request && request == id && value && (value == keys[0] || value == keys[1]); + } + void complete(std::string_view key) + { + const auto value = stage_key_number(key); + for (auto& pending : keys) if (pending == value) pending.reset(); + if (!keys[0] && !keys[1]) id = 0; + } +}; + +// A positive sequence number followed by zero, one or two distinct 16-digit shader keys. +inline std::optional<SceneRequest> parse_scene_request(std::string_view text) +{ + constexpr auto spaces = " \t\r\n"; + const auto start = text.find_first_not_of(spaces); + if (start == text.npos) return {}; + text = text.substr(start, text.find_last_not_of(spaces) - start + 1); + CapturePoint point; + const auto marker = text.find('@'); + if (marker != text.npos) { + if (!marker || text.find_last_of(spaces, marker) != marker - 1) return {}; + const auto coords = text.substr(marker + 1); + const auto comma = coords.find(','); + if (comma == coords.npos) return {}; + const auto coordinate = [](std::string_view value, unsigned& out) { + if (value.empty()) return false; + const auto end = value.data() + value.size(); + const auto result = std::from_chars(value.data(), end, out); + return result.ec == std::errc{} && result.ptr == end && out <= 1000; + }; + std::array<unsigned, 2> xy{}; + if (!coordinate(coords.substr(0, comma), xy[0]) || !coordinate(coords.substr(comma + 1), xy[1])) return {}; + point = xy; + text = text.substr(0, text.find_last_not_of(spaces, marker - 1) + 1); + } + if (text.front() == '+') text.remove_prefix(1); + long id = 0; + const char* end = text.data() + text.size(); + const auto parsed = std::from_chars(text.data(), end, id); + if (parsed.ec != std::errc{} || id <= 0) return {}; + if (parsed.ptr == end) return SceneRequest{id, {}, {}, point}; + std::string_view tail(parsed.ptr, static_cast<std::size_t>(end - parsed.ptr)); + const auto key_start = tail.find_first_not_of(spaces); + if (!key_start || key_start == tail.npos) return {}; + tail.remove_prefix(key_start); + const auto separator = tail.find_first_of(spaces); + const auto first = tail.substr(0, separator); + const auto number = stage_key_number(first); + if (!number) return {}; + if (separator == tail.npos) return SceneRequest{id, first, {}, point}; + const auto second = tail.substr(tail.find_first_not_of(spaces, separator)); + const auto other = stage_key_number(second); + if (!other || other == number) return {}; + return SceneRequest{id, first, second, point}; +} + +} diff --git a/src/startup_stubs/gpu_transition.h b/src/startup_stubs/gpu_transition.h new file mode 100644 index 0000000000..e8c40ff4c4 --- /dev/null +++ b/src/startup_stubs/gpu_transition.h @@ -0,0 +1,18 @@ +#pragma once + +#include <d3d12.h> + +namespace x2w_gpu { + +inline bool transition_all(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, + D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) +{ + if (before == after) return false; + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + list->ResourceBarrier(1, &barrier); + return true; +} + +} diff --git a/src/startup_stubs/gpu_view_trace.h b/src/startup_stubs/gpu_view_trace.h new file mode 100644 index 0000000000..bbb48f1e4f --- /dev/null +++ b/src/startup_stubs/gpu_view_trace.h @@ -0,0 +1,98 @@ +#pragma once + +#include "startup_stubs/local_log.h" +#include <d3d12.h> +#include <type_traits> + +namespace gpu_view_trace { +inline bool watching(ID3D12Device* device) noexcept +{ + static const bool enabled = x2w_local::env_on("X2W_GPU_VIEW_TRACE"); + return enabled && device && device->GetDeviceRemovedReason() == S_OK; +} + +// A view creation returns void. Only claim a transition when the device was healthy immediately before the call. +// Another queue or thread can still remove the device during the same interval. +template <typename Desc> +inline void report(const char* site, const char* kind, HRESULT reason, ID3D12Resource* resource, ID3D12Resource* counter, + const Desc* desc, D3D12_CPU_DESCRIPTOR_HANDLE at) +{ + const auto facts = resource ? resource->GetDesc() : D3D12_RESOURCE_DESC{}; + const auto counter_facts = counter ? counter->GetDesc() : D3D12_RESOURCE_DESC{}; + unsigned words[16]{}; + static_assert(sizeof(Desc) <= sizeof(words)); + const bool readable = desc && x2w_local::readable(desc, sizeof(*desc)); + if (readable) std::memcpy(words, desc, sizeof(*desc)); + x2w_local::logf("x2w-view-transition: %s %s tid=%lu before=S_OK after=0x%08lx dest=0x%llx resource=%p " + "dim=%u width=%llu height=%u depthOrArray=%u mips=%u format=%u flags=0x%x samples=%u " + "counter=%p counterWidth=%llu desc=%p readable=%d words=%08x,%08x,%08x,%08x,%08x,%08x,%08x,%08x,%08x,%08x,%08x,%08x,%08x", + site, kind, GetCurrentThreadId(), static_cast<unsigned long>(reason), static_cast<unsigned long long>(at.ptr), + static_cast<void*>(resource), facts.Dimension, facts.Width, facts.Height, facts.DepthOrArraySize, facts.MipLevels, + facts.Format, facts.Flags, facts.SampleDesc.Count, static_cast<void*>(counter), counter_facts.Width, + static_cast<const void*>(desc), int(readable), words[0], words[1], words[2], words[3], words[4], words[5], + words[6], words[7], words[8], words[9], words[10], words[11], words[12]); + if (!readable) return; + if constexpr (std::is_same_v<Desc, D3D12_UNORDERED_ACCESS_VIEW_DESC>) { + if (desc->ViewDimension == D3D12_UAV_DIMENSION_BUFFER) + x2w_local::logf("x2w-view-detail UAV format=%u first=%llu elements=%u stride=%u flags=%u counterOffset=%llu", + desc->Format, desc->Buffer.FirstElement, desc->Buffer.NumElements, desc->Buffer.StructureByteStride, + desc->Buffer.Flags, desc->Buffer.CounterOffsetInBytes); + } else if constexpr (std::is_same_v<Desc, D3D12_SHADER_RESOURCE_VIEW_DESC>) { + if (desc->ViewDimension == D3D12_SRV_DIMENSION_BUFFER) + x2w_local::logf("x2w-view-detail SRV format=%u first=%llu elements=%u stride=%u flags=%u", desc->Format, + desc->Buffer.FirstElement, desc->Buffer.NumElements, desc->Buffer.StructureByteStride, desc->Buffer.Flags); + } else if constexpr (std::is_same_v<Desc, D3D12_CONSTANT_BUFFER_VIEW_DESC>) { + x2w_local::logf("x2w-view-detail CBV address=0x%llx bytes=%u", desc->BufferLocation, desc->SizeInBytes); + } +} + +inline LONG reported = 0; +template <typename Desc> +inline void after(const char* site, const char* kind, HRESULT reason, ID3D12Resource* resource, ID3D12Resource* counter, + const Desc* desc, D3D12_CPU_DESCRIPTOR_HANDLE at) +{ + if (FAILED(reason) && InterlockedCompareExchange(&reported, 1, 0) == 0) + report(site, kind, reason, resource, counter, desc, at); +} + +struct MirrorCall { + ID3D12Device* device; + const char* site; + void srv(ID3D12Resource* r, const D3D12_SHADER_RESOURCE_VIEW_DESC* d, D3D12_CPU_DESCRIPTOR_HANDLE at) const + { + const bool watch = watching(device); + device->CreateShaderResourceView(r, d, at); + if (watch) after(site, "mirror SRV", device->GetDeviceRemovedReason(), r, nullptr, d, at); + } + void uav(ID3D12Resource* r, ID3D12Resource* c, const D3D12_UNORDERED_ACCESS_VIEW_DESC* d, D3D12_CPU_DESCRIPTOR_HANDLE at) const + { + const bool watch = watching(device); + device->CreateUnorderedAccessView(r, c, d, at); + if (watch) after(site, "mirror UAV", device->GetDeviceRemovedReason(), r, c, d, at); + } + void cbv(const D3D12_CONSTANT_BUFFER_VIEW_DESC* d, D3D12_CPU_DESCRIPTOR_HANDLE at) const + { + const bool watch = watching(device); + device->CreateConstantBufferView(d, at); + if (watch) after(site, "mirror CBV", device->GetDeviceRemovedReason(), nullptr, nullptr, d, at); + } + void sampler(const D3D12_SAMPLER_DESC* d, D3D12_CPU_DESCRIPTOR_HANDLE at) const + { + const bool watch = watching(device); + device->CreateSampler(d, at); + if (watch) after(site, "mirror sampler", device->GetDeviceRemovedReason(), nullptr, nullptr, d, at); + } + void copy(UINT count, D3D12_CPU_DESCRIPTOR_HANDLE dest, D3D12_CPU_DESCRIPTOR_HANDLE src, D3D12_DESCRIPTOR_HEAP_TYPE heap) const + { + const bool watch = watching(device); + device->CopyDescriptorsSimple(count, dest, src, heap); + if (!watch) return; + const HRESULT reason = device->GetDeviceRemovedReason(); + if (FAILED(reason) && InterlockedCompareExchange(&reported, 1, 0) == 0) + x2w_local::logf("x2w-view-transition: %s mirror copy tid=%lu before=S_OK after=0x%08lx " + "dest=0x%llx src=0x%llx count=%u heap=%u", site, GetCurrentThreadId(), + static_cast<unsigned long>(reason), static_cast<unsigned long long>(dest.ptr), + static_cast<unsigned long long>(src.ptr), count, heap); + } +}; +} diff --git a/src/startup_stubs/gpu_views.inl b/src/startup_stubs/gpu_views.inl new file mode 100644 index 0000000000..b4ed7d47f9 --- /dev/null +++ b/src/startup_stubs/gpu_views.inl @@ -0,0 +1,747 @@ +// Mirror shader-visible view and sampler heaps with title descriptor memory. Slot i mirrors title slot i. Refresh +// on view creation (slots 17–19, 22, 61, 70 and 71), copies (23 and 24), explicit lookup and submission. Submission +// catches records copied by the title as raw bytes. Samplers and placed buffers use X2WV or X2WP records so their +// metadata survives such copies. +// +// Queue newly visible textures for upload and revisit one sixteenth at submission. gpu_heap_upload_due performs +// uploads on the draw path where a recording list is available. + +namespace vbind { std::optional<bool> prepare_packed_light(Wrapper*, Wrapper*, ID3D12Resource*, x2w_packed_light::BoundCopy* = nullptr); } +namespace gpu_detail_heap { + +using gpu_mirror::HostHeap; + +struct Mirror { + Wrapper* title_heap = nullptr; + u64 title_cpu = 0, title_gpu = 0; + std::uint32_t count = 0, step = 0; + bool sampler = false; + std::unique_ptr<HostHeap> host; +}; + +SRWLOCK lock = SRWLOCK_INIT; +std::vector<Mirror*>& mirrors() +{ + static std::vector<Mirror*> m; + return m; +} +// Released heaps: kept (a submission may still read through their descriptors); few are ever released. +std::vector<Mirror*>& gone() +{ + static std::vector<Mirror*> g; + return g; +} + +inline GpuHostHeap* opaque(HostHeap* h) { return reinterpret_cast<GpuHostHeap*>(h); } +inline HostHeap* host_of(GpuHostHeap* h) { return reinterpret_cast<HostHeap*>(h); } + +// The mirror whose title memory holds title CPU handle `handle`, and the slot. +Mirror* mirror_at(u64 handle, std::uint32_t* index) +{ + Mirror* found = nullptr; + AcquireSRWLockShared(&lock); + for (Mirror* m : mirrors()) + if (handle >= m->title_cpu && handle < m->title_cpu + u64{m->count} * m->step) { + found = m; + if (index) *index = static_cast<std::uint32_t>((handle - m->title_cpu) / m->step); + break; + } + ReleaseSRWLockShared(&lock); + return found; +} +Mirror* mirror_of(const HostHeap* h) +{ + Mirror* found = nullptr; + AcquireSRWLockShared(&lock); + for (Mirror* m : mirrors()) + if (m->host.get() == h) found = m; + ReleaseSRWLockShared(&lock); + return found; +} + +// ---- Env from X2W ---------------------------------------------------------------------------------------------- + +bool env_find(void*, u64 address, u64 bytes, ID3D12Resource** resource, u64* offset, u64* left) +{ + GpuFound f; + if (gpu_find(address, bytes, &f) && f.resource) { + *resource = f.resource; + *offset = f.offset; + *left = f.bytes_left; + return true; + } + // Until WP3's gpu_find answers: the window that holds the whole range, bounded by the range. + ID3D12Resource* window = nullptr; + u64 at = 0; + if (!desktop_range(address, bytes, &window, &at) || !window) return false; + *resource = window; + *offset = at; + *left = bytes; + return true; +} + +bool env_record(void*, std::uint32_t id, gpu_mirror::Record* out) +{ + ViewRecord r{}; + bool have = false; + AcquireSRWLockShared(¬e_lock); + if (id < view_records().size()) { + r = view_records()[id]; + out->materialized = view_materialized()[id] != 0; + have = true; + } + ReleaseSRWLockShared(¬e_lock); + if (!have || r.slot < 17 || r.slot > 22 || r.slot == 20 || r.slot == 21) return false; + out->id = id; + out->slot = r.slot; + out->resource = r.resource; + out->counter = r.counter; + out->desc_bytes = r.desc_bytes; + std::memcpy(out->desc, r.desc, sizeof(out->desc)); + // The description as view_slot gives it to the desktop: console formats mapped, depth views fixed. + if (r.slot == 18 || r.slot == 19) { + // (A resource the title released has no desktop resource to fix the view for.) + Wrapper* const w = r.resource ? as_wrapper(reinterpret_cast<const void*>(r.resource)) : nullptr; + ID3D12Resource* const desktop = w && InterlockedCompareExchange(&w->own().refs, 0, 0) > 0 + ? reinterpret_cast<ID3D12Resource*>(unwrap(r.resource)) : nullptr; + if (r.desc_bytes >= 4) { + DXGI_FORMAT format; + std::memcpy(&format, out->desc, sizeof(format)); + format = desktop_format(format); + std::memcpy(out->desc, &format, sizeof(format)); + } + if (r.slot == 18 && desktop && reinterpret_cast<u64>(desktop) != r.resource) { + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + if (r.desc_bytes >= sizeof(d)) { + std::memcpy(&d, out->desc, sizeof(d)); + fix_srv(d, desktop); + std::memcpy(out->desc, &d, sizeof(d)); + } else if (default_depth_srv(desktop, d)) { + std::memcpy(out->desc, &d, sizeof(d)); + out->desc_bytes = sizeof(d); + } + } + } + return true; +} + +bool env_resource(void*, u64 wrapper, gpu_mirror::ResourceFacts* out) +{ + Wrapper* w = as_wrapper(reinterpret_cast<const void*>(wrapper)); + if (!w || InterlockedCompareExchange(&w->own().refs, 0, 0) <= 0) return false; + auto* const desktop = static_cast<ID3D12Resource*>(w->own().real); + if (!desktop) return false; + const D3D12_RESOURCE_DESC d = desktop->GetDesc(); + out->desktop = desktop; + out->buffer = d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER; + out->title_memory = reinterpret_cast<u64>(w->own().title_memory); + const ResourceInfo* info = resource_info(w); + constexpr auto both = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + out->depth_and_uav = info && (info->console.Flags & both) == both; + out->bytes = info && info->console.Width ? info->console.Width : d.Width; + return true; +} + +using DepthPair = std::shared_ptr<x2w_depth_twins::Twins>; +std::mutex depth_lock; +std::unordered_map<Wrapper*, DepthPair>& depth_pairs() +{ + static std::unordered_map<Wrapper*, DepthPair> pairs; + return pairs; +} +DepthPair depth_uav(u64 wrapper) +{ + auto* w = as_wrapper(reinterpret_cast<const void*>(wrapper)); + std::lock_guard<std::mutex> guard(depth_lock); + if (!w || InterlockedCompareExchange(&w->own().refs, 0, 0) <= 0) return {}; + auto& pairs = depth_pairs(); + if (auto it = pairs.find(w); it != pairs.end()) return it->second; + const auto* info = resource_info(w); + auto pair = std::make_shared<x2w_depth_twins::Twins>(); + if (!info || !pair->create(device_of(the_device), static_cast<ID3D12Resource*>(w->own().real), info->console)) pair.reset(); + pairs.emplace(w, pair); + return pair; +} + + +bool env_upload(void*, void* list, u64 wrapper, ID3D12Resource* texture) +{ + Wrapper* w = as_wrapper(reinterpret_cast<const void*>(wrapper)); + auto* l = static_cast<Wrapper*>(list); + if (!w || !l || !recording(l)) return false; + if (auto result = vbind::prepare_packed_light(l, w, texture)) return *result; + bool entered_copy_dest = false; + const bool ok = upload_texture(l, w, texture, &entered_copy_dest); + // A heap-indexed read has no per-table binding that can restore the resource after the copy. + // Early exits before COPY_DEST (including GPU-written/UAV textures) preserve the existing state. + if (entered_copy_dest) require_state(l, texture, x2w_gpu::texture_read_state(recording(l)->GetType())); + return ok; +} + +u64 late_texture(const std::uint32_t* words, D3D12_SHADER_RESOURCE_VIEW_DESC& srv, bool& pending, bool allow_create) +{ + D3D12_RESOURCE_DESC desc{}; + if (!x2w_late_texture::decode(words, desc, srv)) { pending = false; return 0; } + const u64 address = u64{words[1]} | (u64{words[2]} << 32); + if (!address) return 0; + using x2w_late_texture::Resolution; + Resolution why{}; + Wrapper* texture = x2w_late_texture::resolve([&] { + if (auto* native = native_tiled_bc_texture(address, desc, srv)) return native; + Wrapper* w = existing_memory_texture(address, desc); + if (w && w->own().real) return w; + return packed_light_source(address, desc) ? publish_linear_texture(the_device, address, desc, true, false, 0, allow_create) : nullptr; + }, [&] { + // Small mips begin at the start of the allocation. If its first byte is unavailable, skip building the detile + // layout. + if (!x2w_local::descriptor_memory_readable(address, 1)) return 8u; + return detile_decline(desc, srv, address); + }, + [&] { + const bool streamed = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.MipLevels > 1; + return publish_linear_texture(the_device, address, desc, true, streamed, streamed ? deferred_host_base(desc, srv) : 0, allow_create); + }, why); + if (allow_create) { + static LONG outcomes[5], attempts; + InterlockedIncrement(&outcomes[static_cast<unsigned>(why)]); + const LONG attempt = InterlockedIncrement(&attempts); + if ((attempt & (attempt - 1)) == 0) + log("x2w-gpu deferred texture retries %ld: existing host %ld, bytes unavailable %ld, layout refused %ld, " + "publish failed %ld, published %ld", attempt, outcomes[0], outcomes[1], outcomes[2], outcomes[3], outcomes[4]); + } + pending = why == Resolution::unavailable; + if (pending && !texture) texture = partial_mip_texture(desc, srv, address, pending, allow_create); + if (!allow_create) { + static LONG lookups, hits; + if (texture) InterlockedIncrement(&hits); + const LONG n = InterlockedIncrement(&lookups); + if ((n & (n - 1)) == 0) log("x2w-gpu material texture budget lookups %ld, reused %ld", n, hits); + } + if (!texture) return 0; + if (texture->own().partial_mip_srv) { + const auto native = static_cast<ID3D12Resource*>(texture->own().real)->GetDesc(); + x2w_resident_mips::rebase(srv, desc.MipLevels - native.MipLevels); + } + srv.Format = desktop_format(srv.Format); + fix_srv(srv, static_cast<ID3D12Resource*>(texture->own().real)); + static LONG recovered; + const LONG n = InterlockedIncrement(&recovered); + if ((n & (n - 1)) == 0) + log("x2w-gpu deferred texture lookups recovered %ld: 0x%llx %llux%u format %d", n, address, + desc.Width, desc.Height, desc.Format); + return reinterpret_cast<u64>(texture); +} + +// The runtime owns a single desktop device. Sample the local budget without retaining its device. +u64 lazy_local_room(ID3D12Device* device) +{ + using Microsoft::WRL::ComPtr; + static const ComPtr<IDXGIAdapter3> adapter = [device] { + ComPtr<IDXGIFactory4> factory; + ComPtr<IDXGIAdapter3> result; + if (device && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) + factory->EnumAdapterByLuid(device->GetAdapterLuid(), IID_PPV_ARGS(&result)); + return result; + }(); + DXGI_QUERY_VIDEO_MEMORY_INFO info{}; + if (adapter && SUCCEEDED(adapter->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &info)) && info.Budget) { + const auto ceiling = info.Budget - info.Budget / 10; + return ceiling > info.CurrentUsage ? ceiling - info.CurrentUsage : 0; + } + std::lock_guard lock(linear_srv_mutex); + constexpr u64 ceiling = 4ull << 30; + return ceiling > linear_srv_bytes ? ceiling - linear_srv_bytes : 0; +} + +gpu_mirror::Env env_for(Wrapper* device) +{ + gpu_mirror::Env e; + e.device = device ? device_of(device) : nullptr; + e.mapping_epoch = gpu_mapping_generation; + e.copied_bytes = []() -> u64 { return x2w_startup::SliceFootprints::recorded_bytes; }; + e.allocated_bytes = []() -> u64 { return thread_linear_allocations; }; + e.local_room = lazy_local_room; + e.allocation_size = [](ID3D12Device* device, const std::uint32_t* words) -> u64 { + D3D12_RESOURCE_DESC guest{}; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + if (!x2w_late_texture::decode(words, guest, srv)) return UINT64_MAX; + const auto native = x2w_resident_mips::host_desc(sanitized(guest), deferred_host_base(guest, srv)); + return device->GetResourceAllocationInfo(0, 1, &native).SizeInBytes; + }; + e.coherent_window = [](u64 address, u64 bytes, ID3D12Resource* expected, u64 offset) { + u64 begin = 0, end = 0; + if (!known_private(address, &begin, &end) || bytes > end - address) return false; + ID3D12Resource* current = nullptr; + u64 at = 0; + return desktop_range(address, bytes, ¤t, &at) && current == expected && at == offset; + }; + e.find = env_find; + e.record = env_record; + e.resource = env_resource; + e.depth_uav = depth_uav; + static const bool retry = x2w_local::env_on("X2W_GPU_LATE_TEXTURES"); + if (retry) { + e.late_texture = late_texture; + e.placement = [](u64 wrapper, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, std::uint32_t (&words)[8]) { + auto* w = reinterpret_cast<Wrapper*>(wrapper); + if (!w->own().title_memory) return false; + auto* info = resource_info(w); + if (!info) return false; + auto guest = srv; + if (w->own().partial_mip_srv && guest.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D) { + const auto native = static_cast<ID3D12Resource*>(w->own().real)->GetDesc(); + const UINT base = info->console.MipLevels - native.MipLevels; + guest.Texture2D.MostDetailedMip += base; + if (guest.Texture2D.ResourceMinLODClamp > 0) + guest.Texture2D.ResourceMinLODClamp += float(base); + } + return x2w_late_texture::encode(info->console, guest, reinterpret_cast<u64>(w->own().title_memory), words); + }; + } + e.upload = env_upload; + return e; +} + +void sink(const char* text) { log("%s", text); } + +// probe_view_limit, once: 2^22 views with twins (X2W_GPU_TWINS=0: none), else 2^21, else 1,000,000. +const gpu_mirror::Limits& limits(ID3D12Device* device) +{ + static const gpu_mirror::Limits l = [device] { + const auto found = gpu_mirror::probe_view_limit(device, x2w_gpu::gpu_twins_on()); + log("x2w-gpu heap: host view heaps hold %u views, twins %s (from %u); view indices are clamped to the null " + "slot %u", found.raw ? 2 * found.raw : found.views, found.raw ? "on" : "off", found.raw, found.null()); + if (x2w_gpu::gpu_twins_on() && !found.raw) + log("x2w-gpu heap: the host takes no heap of 2^22 views: no raw twins, but the export expects them " + "(raw_views=2^21); shaders that pick a twin read the null slot"); + return found; + }(); + return l; +} + +void info_of(const Mirror* m, GpuHeapInfo* out) +{ + if (!out) return; + *out = {}; + out->heap = opaque(m->host.get()); + out->title_heap = m->title_heap; + out->title_gpu = m->title_gpu; + out->title_cpu = m->title_cpu; + out->count = m->count; + out->sampler = m->sampler; + out->host = m->host->heap(); +} + +void view_info(const gpu_mirror::View& v, GpuViewInfo* out) +{ + if (!out) return; + *out = {}; + using x2w_gpu::GpuViewKind; + switch (v.kind) { + case gpu_mirror::Kind::constant: out->kind = GpuViewKind::cbv; break; + case gpu_mirror::Kind::shader: out->kind = GpuViewKind::srv; break; + case gpu_mirror::Kind::unordered: out->kind = GpuViewKind::uav; break; + case gpu_mirror::Kind::sampler: out->kind = GpuViewKind::sampler; break; + case gpu_mirror::Kind::placed: out->kind = v.unordered ? GpuViewKind::uav : GpuViewKind::srv; break; + default: out->kind = GpuViewKind::none; break; + } + out->texture = v.is_texture(); + if (out->texture && v.has_desc && out->kind == GpuViewKind::srv) { + out->view_format = v.srv.Format; + switch (v.srv.ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: out->first_mip = v.srv.Texture1D.MostDetailedMip; break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: + out->first_mip = v.srv.Texture1DArray.MostDetailedMip; + out->first_slice = v.srv.Texture1DArray.FirstArraySlice; break; + case D3D12_SRV_DIMENSION_TEXTURE2D: + out->first_mip = v.srv.Texture2D.MostDetailedMip; + out->plane = v.srv.Texture2D.PlaneSlice; break; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: + out->first_mip = v.srv.Texture2DArray.MostDetailedMip; + out->plane = v.srv.Texture2DArray.PlaneSlice; + out->first_slice = v.srv.Texture2DArray.FirstArraySlice; break; + case D3D12_SRV_DIMENSION_TEXTURE3D: out->first_mip = v.srv.Texture3D.MostDetailedMip; break; + case D3D12_SRV_DIMENSION_TEXTURECUBE: out->first_mip = v.srv.TextureCube.MostDetailedMip; break; + case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: + out->first_mip = v.srv.TextureCubeArray.MostDetailedMip; + out->first_slice = v.srv.TextureCubeArray.First2DArrayFace; break; + default: break; + } + } + out->buffer = v.is_buffer(); + out->title_resource = reinterpret_cast<const void*>(v.wrapper); + out->desktop = v.resource; + out->depth_twins = v.depth_twins; + const auto e = gpu_mirror::view_elements(v); + if (v.kind == gpu_mirror::Kind::constant) { + out->title_address = v.address; + out->bytes = v.bytes; + } else if (e && v.has_desc) { + const bool uav = v.kind == gpu_mirror::Kind::unordered || (v.kind == gpu_mirror::Kind::placed && v.unordered); + const u64 unit = uav ? gpu_mirror::element_size(v.uav) : gpu_mirror::element_size(v.srv); + const u64 first = uav ? v.uav.Buffer.FirstElement : v.srv.Buffer.FirstElement; + const std::uint32_t n = uav ? v.uav.Buffer.NumElements : v.srv.Buffer.NumElements; + out->title_address = v.address + first * unit; + out->bytes = u64{n} * unit; + out->stride = gpu_mirror::stride_word(e); + } +} + +// The record at title slot `handle`, as mirror reads it (8 dwords; a sampler heap's 4). +bool read_record(const Mirror* m, u64 handle, std::uint32_t words[8]) +{ + std::memset(words, 0, 32); + const std::size_t bytes = (std::min<std::size_t>)(m->step, 32); + return gpu_mirror::read_memory(gpu_mirror::Env{}, handle, words, bytes); +} + +// Device slot 61's description (27 words) as an X2WV sampler record at `dest`, which the title's copies then carry. +void note_console_sampler(Wrapper* device, u64 desc, u64 dest) +{ + if (!desc || !x2w_local::readable(reinterpret_cast<const void*>(desc), 27 * 4)) return; + // The destination can be a CPU-only staging heap. Such heaps have no shader-visible + // mirror, but CopyDescriptors must see a valid desktop sampler and its 16-byte title token. + AcquireSRWLockShared(¬e_lock); + const bool in_sampler_heap = std::any_of(heap_infos().begin(), heap_infos().end(), [&](const HeapInfo& h) { + constexpr u64 step = x2w_gpu::abi::sampler_increment; + return h.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER && h.title_cpu && dest >= h.title_cpu && + (dest - h.title_cpu) % step == 0 && (dest - h.title_cpu) / step < h.count; + }); + ReleaseSRWLockShared(¬e_lock); + if (!in_sampler_heap) return; + std::uint32_t words[27]; + std::memcpy(words, reinterpret_cast<const void*>(desc), sizeof(words)); + const D3D12_SAMPLER_DESC d = gpu_mirror::console_sampler(words); + view_slot<22, 1>(device, reinterpret_cast<u64>(&d), dest, 0, 0); +} + +// Device slots 70 and 71: a buffer view of memory that X2W's handler left with no record the mirror can follow (it +// refused it, or wrote nothing) gets an X2WP record of the view. +template <class Input> +void note_placed(Mirror* m, const D3D12_RESOURCE_DESC* resource, const Input* input, u64 dest, bool unordered) +{ + if (!resource || !input || !x2w_local::readable(resource, sizeof(*resource)) || !x2w_local::readable(input, sizeof(*input))) + return; + if (resource->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || static_cast<int>(input->view.ViewDimension) != 1 || + !input->address) + return; + std::uint32_t words[8]; + if (!read_record(m, dest, words)) return; + gpu_mirror::View v; + if (gpu_mirror::view_of_record(env_for(the_device), words, false, v)) return; // X2W's record stands + if (input->view.Buffer.FirstElement > 0xffffffffu || !input->view.Buffer.NumElements) return; + gpu_mirror::PlacedRecord p; + p.address = input->address; + p.first = static_cast<std::uint32_t>(input->view.Buffer.FirstElement); + p.elements = input->view.Buffer.NumElements; + p.stride = input->view.Buffer.StructureByteStride; + p.format = static_cast<std::uint32_t>(desktop_format(input->view.Format)); + p.raw = (input->view.Buffer.Flags & 1) != 0; + p.unordered = unordered; + p.width = static_cast<std::uint32_t>((std::min<u64>)(resource->Width, 0xffffffffu)); + gpu_mirror::placed_words(p, words); + if (!x2w_local::writable(reinterpret_cast<void*>(dest), 32)) return; + std::memcpy(reinterpret_cast<void*>(dest), words, (std::min<std::size_t>)(m->step, 32)); +} + +} // namespace gpu_detail_heap + +// ---- gpu_hooks.h: WP5 ------------------------------------------------------------------------------------- + +void gpu_heap_created(Wrapper* device, Wrapper* heap, const D3D12_DESCRIPTOR_HEAP_DESC& desc, std::uint64_t title_cpu, + std::uint64_t title_gpu) +{ + using namespace gpu_detail_heap; + const bool views = desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + const bool samplers = desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; + if (!(views || samplers) || !(desc.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) || !title_cpu || !heap || !device) return; + static const bool logged = (HostHeap::env_log() = sink, gpu_mirror::fit_log() = sink, true); + (void)logged; + const std::uint32_t step = views ? x2w_gpu::abi::view_increment : x2w_gpu::abi::sampler_increment; + const gpu_mirror::Env e = env_for(device); + auto host = HostHeap::create(e, samplers, desc.NumDescriptors, limits(e.device), title_cpu, step); + if (!host) { + log("x2w-gpu heap: no mirror heap for the title's %s heap of %u", views ? "view" : "sampler", desc.NumDescriptors); + return; + } + const gpu_mirror::Layout& l = host->layout(); + log("x2w-gpu heap: mirror of the title's %s heap at 0x%llx: %u title slots%s, %u dynamic, null slot %u, twins from %u, " + "%u host views", views ? "view" : "sampler", title_cpu, l.count, l.capped ? " (capped)" : "", l.dynamic, l.null, l.raw, + l.size); + auto* m = new Mirror; + m->title_heap = heap; + m->title_cpu = title_cpu; + m->title_gpu = title_gpu; + m->count = l.count; + m->step = step; + m->sampler = samplers; + m->host = std::move(host); + AcquireSRWLockExclusive(&lock); + mirrors().push_back(m); + ReleaseSRWLockExclusive(&lock); + heap->own().gpu[0] = m; +} + +void gpu_heap_released(Wrapper* heap) +{ + using namespace gpu_detail_heap; + auto* m = static_cast<Mirror*>(heap->own().gpu[0]); + if (!m) return; + heap->own().gpu[0] = nullptr; + AcquireSRWLockExclusive(&lock); + auto& all = mirrors(); + all.erase(std::remove(all.begin(), all.end(), m), all.end()); + gone().push_back(m); + ReleaseSRWLockExclusive(&lock); +} + +void gpu_heap_view(Wrapper* device, int slot, std::uint64_t a, std::uint64_t b, std::uint64_t c, std::uint64_t d) +{ + using namespace gpu_detail_heap; + u64 dest = 0; + switch (slot) { + case 17: case 22: case 61: dest = b; break; + case 18: case 70: case 71: dest = c; break; + case 19: dest = d; break; + default: return; // 20, 21: render targets and depth are not in shader-visible heaps + } + if (slot == 61) note_console_sampler(device, a, dest); + std::uint32_t index = 0; + Mirror* m = mirror_at(dest, &index); + if (!m) return; + if (slot == 70) + note_placed(m, reinterpret_cast<const D3D12_RESOURCE_DESC*>(a), reinterpret_cast<const MemoryShaderResourceView*>(b), dest, false); + if (slot == 71) + note_placed(m, reinterpret_cast<const D3D12_RESOURCE_DESC*>(a), reinterpret_cast<const MemoryUnorderedAccessView*>(b), dest, true); + m->host->mirror(index, false); +} + +void gpu_heap_copy_simple(Wrapper*, UINT count, std::uint64_t dest, std::uint64_t, D3D12_DESCRIPTOR_HEAP_TYPE) +{ + using namespace gpu_detail_heap; + std::uint32_t index = 0; + if (Mirror* m = mirror_at(dest, &index)) m->host->mirror_range(index, count); +} + +void gpu_heap_copy(Wrapper*, UINT dest_count, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts, const UINT* dest_sizes, UINT, + const D3D12_CPU_DESCRIPTOR_HANDLE*, const UINT*, D3D12_DESCRIPTOR_HEAP_TYPE) +{ + using namespace gpu_detail_heap; + if (!dest_starts) return; + for (UINT i = 0; i < dest_count; ++i) { + std::uint32_t index = 0; + if (Mirror* m = mirror_at(dest_starts[i].ptr, &index)) m->host->mirror_range(index, dest_sizes ? dest_sizes[i] : 1); + } +} + +void gpu_heap_submit(ID3D12CommandQueue*, UINT, Wrapper* const*) +{ + using namespace gpu_detail_heap; + std::vector<Mirror*> all; + AcquireSRWLockShared(&lock); + all = mirrors(); + ReleaseSRWLockShared(&lock); + for (Mirror* m : all) m->host->submit(); +} + +bool gpu_heap_for(Wrapper* title_heap, GpuHeapInfo* out) +{ + using namespace gpu_detail_heap; + if (!title_heap) return false; + auto* m = static_cast<Mirror*>(title_heap->own().gpu[0]); + if (!m) return false; + info_of(m, out); + return true; +} + +bool gpu_heap_at(std::uint64_t title_gpu_handle, GpuHeapInfo* out) +{ + using namespace gpu_detail_heap; + Mirror* found = nullptr; + AcquireSRWLockShared(&lock); + for (Mirror* m : mirrors()) + if (m->title_gpu && title_gpu_handle >= m->title_gpu && title_gpu_handle < m->title_gpu + u64{m->count} * m->step) found = m; + ReleaseSRWLockShared(&lock); + if (!found) return false; + info_of(found, out); + return true; +} + +bool gpu_heap_view_at(GpuHostHeap* heap, std::uint32_t index, GpuViewInfo* out) +{ + using namespace gpu_detail_heap; + auto* h = host_of(heap); + if (!h || index >= h->count()) return false; + Mirror* m = mirror_of(h); + if (!m) return false; + std::uint32_t words[8]; + if (!read_record(m, m->title_cpu + u64{index} * m->step, words)) return false; + gpu_mirror::View v; + if (!h->view_at(index, words, v)) return false; + view_info(v, out); + return true; +} + +u64 gpu_heap_title_address_at(GpuHostHeap* heap, std::uint32_t index) +{ + using namespace gpu_detail_heap; + auto* host = host_of(heap); + auto* m = host && index < host->count() ? mirror_of(host) : nullptr; + std::uint32_t words[8]; + if (!m || m->sampler || !read_record(m, m->title_cpu + u64{index} * m->step, words)) return 0; + const auto env = env_for(the_device); + u64 address = 0; + if (gpu_mirror::title_as_address(env, words, &address)) { + static LONG samples; + const auto n = InterlockedIncrement(&samples); + if (n <= 4 || (n & (n-1)) == 0) + log("x2w-gpu AS title address: frame=%ld count=%ld index=%u address=%llx", frame_number, n, index, address); + return address; + } + gpu_mirror::View v; + if (!gpu_mirror::view_of_record(env, words, false, v)) return 0; + GpuViewInfo view{}; + view_info(v, &view); + return view.buffer ? view.title_address : 0; +} + +ID3D12Resource* gpu_heap_kept_at(GpuHostHeap* heap, std::uint32_t index) +{ + auto* host = gpu_detail_heap::host_of(heap); + return host ? host->kept_at(index) : nullptr; +} + +void gpu_material_slots(GpuHostHeap* heap, std::vector<x2w_material_trace::Slot>& slots) +{ + if (auto* host = gpu_detail_heap::host_of(heap)) host->material_slots(slots); +} + +x2w_material_trace::Record gpu_material_record(GpuHostHeap* heap, UINT slot, UINT base, x2w_material::Mask fields) +{ + auto* h = gpu_detail_heap::host_of(heap); + return h ? h->material_record(slot, base, fields) : x2w_material_trace::Record{}; +} +unsigned gpu_materialize(Wrapper* list, GpuHostHeap* heap, const x2w_material_trace::Words& words, x2w_material::Mask fields) +{ + auto* h = gpu_detail_heap::host_of(heap); + return h ? h->materialize(list, words, fields) : 0; +} + +bool gpu_heap_mirror(GpuHostHeap* heap, std::uint32_t index, std::uint64_t title_handle, bool, GpuViewInfo* out) +{ + using namespace gpu_detail_heap; + auto* h = host_of(heap); + if (!h || index >= h->count()) return false; + if (title_handle) { + // (The handle the caller read the table at names the slot.) + std::uint32_t at = 0; + Mirror* m = mirror_at(title_handle, &at); + if (m && m->host.get() == h) index = at; + } + const bool shown = h->mirror(index); + if (out && gpu_heap_view_at(heap, index, out) && out->texture) out->desktop = h->kept_at(index); + return shown; +} + +bool gpu_heap_dynamic(GpuHostHeap* heap, std::uint32_t n, std::uint32_t* first) +{ + auto* h = gpu_detail_heap::host_of(heap); + if (!h) return false; + const auto got = h->dynamic(n); + if (!got) return false; + if (first) *first = *got; + return true; +} + +void gpu_heap_release(GpuHostHeap* heap, std::uint32_t first, std::uint32_t n) +{ + if (auto* h = gpu_detail_heap::host_of(heap)) h->release(first, n); +} + +bool gpu_heap_make_listed(GpuHostHeap* heap, std::uint32_t source, const std::uint32_t (&record)[8], std::uint32_t index, + GpuViewInfo* out) +{ + using namespace gpu_detail_heap; + auto* h = host_of(heap); + if (!h) return false; + gpu_mirror::View v; + if (!h->make_listed(index, record, source, &v)) return false; + view_info(v, out); + if (out && out->texture) out->desktop = h->kept_at(index); + return true; +} + +void gpu_heap_make_null(GpuHostHeap* heap, std::uint32_t index) +{ + if (auto* h = gpu_detail_heap::host_of(heap)) h->make_null(index); +} + +void gpu_heap_raw_at(GpuHostHeap* heap, std::uint32_t index, ID3D12Resource* buffer, std::uint64_t offset, std::uint64_t bytes) +{ + if (auto* h = gpu_detail_heap::host_of(heap)) h->raw_at(index, buffer, offset, bytes); +} + +void gpu_heap_raw_uav_at(GpuHostHeap* heap, std::uint32_t index, ID3D12Resource* buffer, std::uint64_t offset, + std::uint64_t bytes) +{ + if (auto* h = gpu_detail_heap::host_of(heap)) h->raw_uav_at(index, buffer, offset, bytes); +} + +void gpu_heap_null_raw_at(GpuHostHeap* heap, std::uint32_t index) +{ + if (auto* h = gpu_detail_heap::host_of(heap)) h->null_raw_at(index); +} + +void gpu_heap_null_raw_uav_at(GpuHostHeap* heap, std::uint32_t index) +{ + if (auto* h = gpu_detail_heap::host_of(heap)) h->null_raw_uav_at(index); +} + +void gpu_heap_constant_at(GpuHostHeap* heap, std::uint32_t index, ID3D12Resource* buffer, std::uint64_t gpu, std::uint32_t bytes) +{ + if (auto* h = gpu_detail_heap::host_of(heap)) h->constant_at(index, buffer, gpu, bytes); +} + +D3D12_GPU_DESCRIPTOR_HANDLE gpu_heap_gpu_handle(GpuHostHeap* heap, std::uint32_t index) +{ + auto* h = gpu_detail_heap::host_of(heap); + return h ? h->gpu_handle(index) : D3D12_GPU_DESCRIPTOR_HANDLE{}; +} + +std::uint32_t gpu_heap_count(GpuHostHeap* heap) +{ + auto* h = gpu_detail_heap::host_of(heap); + return h ? h->count() : 0; +} + +ID3D12DescriptorHeap* gpu_heap_host(GpuHostHeap* heap) +{ + auto* h = gpu_detail_heap::host_of(heap); + return h ? h->heap() : nullptr; +} + +std::uint64_t gpu_heap_strides_gpu(GpuHostHeap* heap) +{ + auto* h = gpu_detail_heap::host_of(heap); + return h ? h->strides_gpu() : 0; +} + +// Declared in gpu_hooks.h (vhooks fe1f8bd31, bool result): PLAN.md 4b, the textures shaders pick by index that +// are due, up to `max`, uploaded on `list` (a recording title list, the draw's: upload_texture needs one). True when +// at least one was uploaded. +bool gpu_heap_upload_due(Wrapper* list, std::size_t max) +{ + using namespace gpu_detail_heap; + auto* command = list ? recording(list) : nullptr; + if (!command) return false; + const auto type = command->GetType(); + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_COMPUTE) return false; + std::vector<Mirror*> all; + AcquireSRWLockShared(&lock); + all = mirrors(); + ReleaseSRWLockShared(&lock); + std::size_t done = 0; + for (Mirror* m : all) + if (!m->sampler && done < max) done += m->host->upload_due(list, max - done); + return done != 0; +} diff --git a/src/startup_stubs/gpu_warm_bad.h b/src/startup_stubs/gpu_warm_bad.h new file mode 100644 index 0000000000..8a54f08aca --- /dev/null +++ b/src/startup_stubs/gpu_warm_bad.h @@ -0,0 +1,58 @@ +#pragma once +#include "startup_stubs/blake3/blake3.h" +#include "startup_stubs/gpu_abi.h" + +#include <istream> +#include <string> +#include <string_view> +#include <unordered_set> + +namespace x2w_gpu { + +// Hash the stage name, lowercase ASCII shader key and graphics description when present. A single compute stage has +// an empty graphics suffix. +inline std::string gpu_compute_pending_key(std::string_view shader) +{ + blake3_hasher hash; + blake3_hasher_init(&hash); + constexpr std::string_view stage = "compute"; + blake3_hasher_update(&hash, stage.data(), stage.size()); + blake3_hasher_update(&hash, shader.data(), shader.size()); + unsigned char digest[16]{}; + blake3_hasher_finalize(&hash, digest, sizeof(digest)); + constexpr char hex[] = "0123456789abcdef"; + std::string key(32, '0'); + for (size_t i = 0; i < sizeof(digest); ++i) { + key[2 * i] = hex[digest[i] >> 4]; + key[2 * i + 1] = hex[digest[i] & 15]; + } + return key; +} + +struct GpuWarmBad { + std::unordered_set<std::string> keys; + + void read(std::istream& input) + { + std::string line; + constexpr auto space = " \t\r\n\f\v"; + while (std::getline(input, line)) { + const auto first = line.find_first_not_of(space); + if (first == std::string::npos || line[first] == '#') continue; + const auto end = line.find_first_of(space, first); + auto token = line.substr(first, end - first); + if (token.size() == 32 && token.find_first_not_of("0123456789abcdef") == std::string::npos) + keys.insert(std::move(token)); + } + } + + bool contains(const GpuCreateDesc& desc, bool has_graphics_state) const + { + // Graphics keys include the complete pipeline state description. A shader-only match could refuse unrelated + // pipelines using the same stages. + if (keys.empty() || has_graphics_state || desc.stage_count != 1 || desc.stages[0].stage != GpuStage::compute) return false; + return keys.count(gpu_compute_pending_key(std::string_view(desc.stages[0].key, 16))) != 0; + } +}; + +} // namespace x2w_gpu diff --git a/src/startup_stubs/heap_raw_prelude.hlsli b/src/startup_stubs/heap_raw_prelude.hlsli new file mode 100644 index 0000000000..23149313e7 --- /dev/null +++ b/src/startup_stubs/heap_raw_prelude.hlsli @@ -0,0 +1,120 @@ +// LOCAL (compute translation runtime, manifest `heapraw 1`): the heap prelude of a translated compute program whose +// heap SRV buffers resolve raw GFX10 V# words as well as view tokens. Replaces the `heap 1` lines heapmem / vinfo / +// vid / vix / vstride / vfmt; a heap SRV buffer H<k> is `#define H<k> hbuf(h<k>)` instead of hres<k>. The runtime +// side, the table layout and the hash are in gfx10_raw_vdesc.h (raw_map_hash == vrawh) and d3d12_heap_raw.inl. +// The constants: 0x56573258 "X2WV" token, 90000 view ids, 262144 empty views, 262152 first view id view, +// 982152 first raw window view (heap_raw_window_first), 256 windows, 982408 page-record view (heap_raw_pages_view), +// 16 probes (linear; with 8, about 1% of inserts found every probe occupied at 45% load in rawheap-bench). +// The entry's window field (gfx10_raw_vdesc.h): 0..255 a window; 0x100 | window, a base that is not 4-aligned; 0x200 +// paged (each dword through its 64 KiB page's record); 0xfffe / 0xffff misses. The earlier prelude took < 256 only. +ByteAddressBuffer heapmem : register(t0, space1); +ByteAddressBuffer vinfo : register(t1, space1); +ByteAddressBuffer rawmap : register(t2, space1); +uint vid(uint h) { return heapmem.Load(h) == 0x56573258u ? heapmem.Load(h + 4) : 0xffffffffu; } +uint vix(uint h, uint k) { uint i = vid(h); return i < 90000u ? 262152u + i * 8u + k : 262144u + k; } +// A buffer V# the table can bound and its bytes (gfx10_raw_vdesc.h raw_buffer_words, the same rule): not a token, +// TYPE 0, base != 0, no SWIZZLE_ENABLE (word 1 bit 31), no ADD_TID_ENABLE (word 3 bit 23), OOB_SELECT 0, 1 or 3; +// bytes NUM_RECORDS for OOB_SELECT 3, else STRIDE x NUM_RECORDS (saturated at 0xffffffff), and not 0. +uint vrawbytes(uint4 w) +{ + uint s = (w.y >> 16) & 0x3fffu; + if (((w.w >> 28) & 3u) == 3u) return w.z; + return s == 0u ? 0u : (w.z > 0xffffffffu / s ? 0xffffffffu : s * w.z); +} +bool vrawok(uint4 w) +{ + return w.x != 0x56573258u && (w.w >> 30) == 0u && (w.y >> 31) == 0u && ((w.w >> 23) & 1u) == 0u && ((w.w >> 28) & 3u) != 2u && + (w.x | (w.y & 0xffffu)) != 0u && vrawbytes(w) != 0u; +} +uint vrawh(uint lo, uint hi, uint b) { uint x = (lo * 0x9e3779b1u) ^ (hi * 0x85ebca6bu) ^ (b * 0xc2b2ae35u); x ^= x >> 16; x *= 0x7feb352du; x ^= x >> 15; return x; } +// The window index of the V# in slot h (0xffffffff: no table entry), its byte offset in that window and its bytes. +uint vraw(uint h, out uint o, out uint n) +{ + o = 0u; + n = 0u; + uint4 w = heapmem.Load4(h); + if (!vrawok(w)) return 0xffffffffu; + uint b = vrawbytes(w), hi = w.y & 0xffffu, cap; + rawmap.GetDimensions(cap); + cap /= 16u; + if (cap == 0u || (cap & (cap - 1u)) != 0u) return 0xffffffffu; // no table bound (switch off): a null view + uint i = vrawh(w.x, hi, b); + [loop] for (uint p = 0u; p < 16u; ++p) { + uint4 e = rawmap.Load4(((i + p) & (cap - 1u)) * 16u); + if (e.z == 0u) break; + if (e.x == w.x && (e.y & 0xffffu) == hi && e.z == b) { o = e.w; n = b; return e.y >> 16; } + } + return 0xffffffffu; +} +// The stride and format of a V# slot only when the table resolves it (vraw hits): a miss binds the empty view, and +// its stride and format must be those of the empty view (0), as before `heapraw` and with X2W_HEAP_RAW=0, so a typed +// load of a miss reads raw 0 and not a decoded default (W = 1.0). +bool vrawhit(uint h) { uint o, n; return vid(h) == 0xffffffffu && vraw(h, o, n) <= 0x200u; } +uint vstride(uint h) +{ + uint i = vid(h); + if (i < 90000u) return vinfo.Load(i * 16u); + return vrawhit(h) ? (heapmem.Load(h + 4) >> 16) & 0x3fffu : 0u; +} +// FORMAT of a resolved V# as vinfo word 1 holds it for a view: 0 for raw (OOB_SELECT 3) and 32_FLOAT (22) V#s, which +// the runtime's own V#s of raw and structured views carry (vinfo: 0 for both). +uint vfmt(uint h) +{ + uint i = vid(h), n; + vinfo.GetDimensions(n); + if (i < 90000u) return i * 16u + 8u <= n ? vinfo.Load(i * 16u + 4u) : 0u; + if (!vrawhit(h)) return 0u; + uint w3 = heapmem.Load(h + 12), f = (w3 >> 12) & 127u; + return ((w3 >> 28) & 3u) != 3u && f != 22u ? f : 0u; +} +// The dword at byte x (4-aligned) of a paged range, x counted from the start of its first page; `first` its first +// page record (window index, window offset of the page's start). +uint hpage(uint first, uint x) +{ + ByteAddressBuffer t = ResourceDescriptorHeap[982408u]; + uint2 r = t.Load2((first + (x >> 16)) * 8u); + ByteAddressBuffer b = ResourceDescriptorHeap[NonUniformResourceIndex(982152u + r.x)]; + return b.Load(r.y + (x & 0xffffu)); +} +// A heap SRV buffer: a view token's raw view (bounded by D3D12), or a resolved V#'s window with its offset and its +// size (a dword at byte a is read when a + 4 <= n, else 0: the ISA's offset + payload > NUM_RECORDS), or a paged +// range (q: its base's offset in its first page + 1, o its first page record), or the empty view. A base that is not +// 4-aligned is read byte-exact, from the two dwords around each one (both inside the range). +struct HBuf { + uint d; + uint o; + uint n; + uint q; + uint Word(uint x) + { + if (q != 0u) return hpage(o, x); + ByteAddressBuffer b = ResourceDescriptorHeap[d]; + return b.Load(x); + } + uint Load(uint a) + { + if (!(a <= n - 4u && n >= 4u)) return 0u; + uint x = (q != 0u ? q - 1u : o) + a, k = (x & 3u) * 8u, lo = Word(x & ~3u); + if (k == 0u) return lo; // not ?: (both sides evaluated before HLSL 2021: a second load on every aligned read) + return (lo >> k) | (Word((x & ~3u) + 4u) << (32u - k)); + } +}; +HBuf hbuf(uint h) +{ + HBuf r; + r.d = vix(h, 4u); + r.o = 0u; + r.n = 0xffffffffu; + r.q = 0u; + if (vid(h) == 0xffffffffu) { + uint o, n, wi = vraw(h, o, n); + if (wi <= 0x200u) { + if (wi == 0x200u) r.q = (heapmem.Load(h) & 0xffffu) + 1u; + else r.d = 982152u + (wi & 255u); + r.o = o; + r.n = n; + } + } + return r; +} +uint ldu(HBuf b, uint a) { uint k = (a & 3) * 8, lo = b.Load(a & ~3u); if (k == 0) return lo; return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); } diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 5ed62c7248..f6f94aabd3 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -123,6 +123,7 @@ bool list_wrote(Wrapper* list, ID3D12Resource* resource) void discard_list_gpu_writes(Wrapper* self) { + if (bc_bind_trace::enabled()) bc_bind_trace::close_recording(self, false); AcquireSRWLockExclusive(&pending_writes_lock); pending_gpu_writes().erase(self); ReleaseSRWLockExclusive(&pending_writes_lock); @@ -130,6 +131,7 @@ void discard_list_gpu_writes(Wrapper* self) void commit_list_gpu_writes(Wrapper* self) { + if (bc_bind_trace::enabled()) bc_bind_trace::close_recording(self, true); AcquireSRWLockShared(&pending_writes_lock); if (const auto it = pending_gpu_writes().find(self); it != pending_gpu_writes().end()) { for (ID3D12Resource* resource : it->second) { @@ -152,6 +154,11 @@ void mark_gpu_written(Wrapper* self, const CopyEndpoint& destination) ReleaseSRWLockExclusive(&pending_writes_lock); } +void mark_copied_texture(Wrapper* list, Wrapper* wrapper, ID3D12Resource* texture) +{ + mark_gpu_written(list, {texture, wrapper}); +} + // Refusal shared by the three handlers once the descriptions passed, or none. x2w_startup::CopyRefusal check_roles_and_sync(Wrapper* self, const CopyEndpoint& to, const CopyEndpoint& from, bool sync) { diff --git a/src/startup_stubs/list_copy_texture.h b/src/startup_stubs/list_copy_texture.h index 6a2fe981c2..ae88fbc3ac 100644 --- a/src/startup_stubs/list_copy_texture.h +++ b/src/startup_stubs/list_copy_texture.h @@ -130,7 +130,7 @@ inline End footprint_end(const Side& s, std::uint32_t w, std::uint32_t h, std::u } // box == nullptr copies the whole source (for a footprint source, the whole footprint). -inline Verdict check(const Side& dst, std::uint32_t x, std::uint32_t y, std::uint32_t z, const Side& src, const Box* box) noexcept +inline Verdict check(const Side& dst, std::uint32_t x, std::uint32_t y, std::uint32_t z, const Side& src, const Box* box, bool same_format_family = false) noexcept { if (dst.kind == Kind::placed_footprint && src.kind == Kind::placed_footprint) return Verdict::buffer_to_buffer; for (const Side* s : {&dst, &src}) { @@ -139,7 +139,7 @@ inline Verdict check(const Side& dst, std::uint32_t x, std::uint32_t y, std::uin return Verdict::bad_subresource; } if (dst.samples != src.samples) return Verdict::sample_mismatch; - if (dst.format != src.format) return Verdict::format_mismatch; + if (dst.format != src.format && !same_format_family) return Verdict::format_mismatch; const Side& tex = dst.kind == Kind::subresource ? dst : src; // the side that knows the block size // D3D12 measures a block-compressed region in whole blocks: a 2x2 or 1x1 mip spans one 4x4 block, and // GetCopyableFootprints describes it as a 4x4 footprint, so each side's extent rounds up to the block. diff --git a/src/startup_stubs/list_copy_texture.inl b/src/startup_stubs/list_copy_texture.inl index 4f2ca279b5..7848e21a73 100644 --- a/src/startup_stubs/list_copy_texture.inl +++ b/src/startup_stubs/list_copy_texture.inl @@ -3,6 +3,8 @@ // list_copy_texture.h, the two resources move to COPY_SOURCE / COPY_DEST for the call (the list's Close // puts them back to COMMON), and a call the desktop would reject is counted and logged, not forwarded. #include "list_copy_texture.h" +#include "title_texture_readback.inl" +#include "bc_bind_trace.inl" volatile LONG list_copy_texture_forwarded, list_copy_texture_refused; @@ -99,7 +101,160 @@ bool fixed_heap_state(ID3D12Resource* resource, D3D12_HEAP_TYPE& type) } // namespace // List slot 16 (unshifted, like slots 12 to 25), CopyTextureRegion(dst, x, y, z, src, box). -void __stdcall list_copy_texture(Wrapper* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x, UINT y, UINT z, +bool encoded_block_pair(DXGI_FORMAT raw, DXGI_FORMAT bc) +{ + switch (bc) { + case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB: + case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM: + return raw == DXGI_FORMAT_R32G32_UINT || raw == DXGI_FORMAT_R32G32_SINT || + raw == DXGI_FORMAT_R16G16B16A16_UINT || raw == DXGI_FORMAT_R16G16B16A16_SINT; + case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: + return raw == DXGI_FORMAT_R32G32B32A32_UINT || raw == DXGI_FORMAT_R32G32B32A32_SINT; + default: return false; + } +} + +x2w_list_copy_texture::Verdict check_block_copy(x2w_list_copy_texture::Side dst, UINT x, UINT y, UINT z, + x2w_list_copy_texture::Side src, const x2w_list_copy_texture::Box* box, bool compressed_source) +{ + using namespace x2w_list_copy_texture; + auto blocks = [](UINT pixels) { return pixels / 4 + (pixels % 4 != 0); }; + auto& compressed = compressed_source ? src : dst; + Box area{}; + if (compressed_source && box) { + if (box->right > src.width || box->bottom > src.height) return Verdict::source_overflow; + if (box->left % 4 || box->top % 4 || (box->right % 4 && box->right != src.width) || + (box->bottom % 4 && box->bottom != src.height)) return Verdict::bad_alignment; + area = {box->left/4, box->top/4, box->front, blocks(box->right), blocks(box->bottom), box->back}; + box = &area; + } else if (!compressed_source) { + if (x % 4 || y % 4) return Verdict::bad_alignment; + x /= 4; + y /= 4; + } + compressed.width = blocks(compressed.width); + compressed.height = blocks(compressed.height); + dst.block_w = dst.block_h = src.block_w = src.block_h = 1; + return check(dst, x, y, z, src, box, true); +} + +void mark_copied_texture(Wrapper*, Wrapper*, ID3D12Resource*); + +ID3D12Resource* recording_plane_scratch(Wrapper* self, UINT64 bytes) +{ + auto& state = self->own(); + auto*& scratch = state.plane_copy_scratch; + if (scratch && scratch->GetDesc().Width >= bytes) return scratch; + Microsoft::WRL::ComPtr<ID3D12Resource> created; + if (!x2w_vmemory::buffer(device_of(state.list_device), bytes, D3D12_HEAP_TYPE_DEFAULT, false, &created)) return nullptr; + ID3D12Resource* buffer = nullptr; + AcquireSRWLockExclusive(&allocator_lock); + const auto found = list_recordings.find(self); + if (found != list_recordings.end() && found->second) { + try { + found->second->scratches.push_back(std::move(created)); + buffer = scratch = found->second->scratches.back().Get(); + } catch (const std::bad_alloc&) {} + } + ReleaseSRWLockExclusive(&allocator_lock); + return buffer; +} + +bool copy_depth_plane(Wrapper* self, ID3D12Resource* src, const x2w_list_copy_texture::Side& s, + ID3D12Resource* dst, const x2w_list_copy_texture::Side& d) +{ + using x2w_list_copy_texture::Kind; + if (s.kind != Kind::subresource || d.kind != Kind::subresource || + s.format != DXGI_FORMAT_R32G8X24_TYPELESS || d.format != DXGI_FORMAT_R32_TYPELESS || + !s.depth_stencil || !d.depth_stencil || s.planes != 2 || d.planes != 1 || + s.subresource >= s.mips * s.array_size || s.samples != 1 || d.samples != 1 || + s.width != d.width || s.height != d.height || s.depth != 1 || d.depth != 1) return false; + auto* device = device_of(self->own().list_device); + const auto from_desc = src->GetDesc(), to_desc = dst->GetDesc(); + if (from_desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || to_desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return false; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT from{}, to{}; + UINT64 bytes{}, dest_bytes{}; + device->GetCopyableFootprints(&from_desc, s.subresource, 1, 0, &from, nullptr, nullptr, &bytes); + device->GetCopyableFootprints(&to_desc, d.subresource, 1, 0, &to, nullptr, nullptr, &dest_bytes); + if (!bytes || bytes == UINT64_MAX || bytes != dest_bytes || from.Offset != to.Offset || + from.Footprint.Format != DXGI_FORMAT_R32_TYPELESS || to.Footprint.Format != DXGI_FORMAT_R32_TYPELESS || + from.Footprint.RowPitch != to.Footprint.RowPitch || from.Footprint.Width != s.width || + to.Footprint.Width != d.width || from.Footprint.Height != s.height || to.Footprint.Height != d.height) return false; + auto* scratch = recording_plane_scratch(self, bytes); + if (!scratch) return false; + auto* list = recording(self); + const auto before = current_planes(self, src, D3D12_RESOURCE_STATE_COMMON); + require_planes(self, src, D3D12_RESOURCE_STATE_COPY_SOURCE, before.stencil); + require_state(self, scratch, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_TEXTURE_COPY_LOCATION image{src, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + image.SubresourceIndex = s.subresource; + D3D12_TEXTURE_COPY_LOCATION buffer{scratch, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + buffer.PlacedFootprint = from; + list->CopyTextureRegion(&buffer, 0, 0, 0, &image, nullptr); + require_state(self, scratch, D3D12_RESOURCE_STATE_COPY_SOURCE); + require_state(self, dst, D3D12_RESOURCE_STATE_COPY_DEST); + buffer.PlacedFootprint = to; + image.pResource = dst; + image.SubresourceIndex = d.subresource; + list->CopyTextureRegion(&image, 0, 0, 0, &buffer, nullptr); + return true; +} + +void report_planar_copy(UINT slot, const x2w_list_copy_texture::Side& src, ID3D12Resource* src_resource, + const x2w_list_copy_texture::Side& dst, ID3D12Resource* dst_resource, + Wrapper* src_wrapper, Wrapper* dst_wrapper, UINT x, UINT y, UINT z, const D3D12_BOX* box) +{ + using namespace x2w_list_copy_texture; + static LONG64 refused; + const auto n = InterlockedIncrement64(&refused); + if ((n & (n - 1)) == 0) log("x2w-d3d12 planar copies refused %lld", n); + Subresource s{}, d{}; + decode_subresource(src.subresource, src.mips, src.array_size, src.planes, s); + decode_subresource(dst.subresource, dst.mips, dst.array_size, dst.planes, d); + using Key = std::array<UINT, 10>; + const Key key{slot, UINT(src.kind), src.format, s.plane, src.samples, UINT(dst.kind), dst.format, d.plane, dst.samples, UINT(box != nullptr)}; + static std::mutex mutex; + static std::array<Key, 24> seen{}; + static size_t used = 0; + { + std::lock_guard guard(mutex); + if (used == seen.size() || std::find(seen.begin(), seen.begin() + used, key) != seen.begin() + used) return; + seen[used++] = key; + } + D3D12_BOX area{}; + SIZE_T copied = 0; + const bool valid = box && ReadProcessMemory(GetCurrentProcess(), box, &area, sizeof(area), &copied) && copied == sizeof(area); + log("x2w-d3d12 planar copy sample=%lld slot=%u dst_origin=%u,%u,%u box=%s %u,%u,%u..%u,%u,%u", + n, slot, x, y, z, !box ? "full" : valid ? "region" : "unreadable", + area.left, area.top, area.front, area.right, area.bottom, area.back); + const auto side = [&](const char* name, const Side& value, Subresource parts, ID3D12Resource* resource, Wrapper* wrapper) { + const auto desc = resource->GetDesc(); + const auto* title = resource_info(wrapper); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT placed{}; + if (value.kind == x2w_list_copy_texture::Kind::placed_footprint) + placed = {value.offset, {DXGI_FORMAT(value.format), value.width, value.height, value.depth, value.row_pitch}}; + else if (value.samples == 1) { + Microsoft::WRL::ComPtr<ID3D12Device> device; + if (SUCCEEDED(resource->GetDevice(IID_PPV_ARGS(&device)))) + device->GetCopyableFootprints(&desc, value.subresource, 1, 0, &placed, nullptr, nullptr, nullptr); + } + const auto& f = placed.Footprint; + log("x2w-d3d12 planar copy sample=%lld %s kind=%u title_fmt=%u title_layout=0x%x resource_fmt=%u dim=%u flags=0x%x samples=%u " + "sub=%u plane=%u/%u mip=%u/%u slice=%u/%u mip_size=%ux%ux%u footprint_fmt=%u footprint=%ux%ux%u pitch=%u offset=%llu", + n, name, UINT(value.kind), title ? UINT(title->console.Format) : UINT_MAX, title ? UINT(title->console.Layout) : UINT_MAX, + UINT(desc.Format), UINT(desc.Dimension), UINT(desc.Flags), value.samples, + value.subresource, parts.plane, value.planes, parts.mip, value.mips, parts.slice, value.array_size, + value.width, value.height, value.depth, UINT(f.Format), f.Width, f.Height, f.Depth, f.RowPitch, placed.Offset); + }; + side("src", src, s, src_resource, src_wrapper); + side("dst", dst, d, dst_resource, dst_wrapper); +} + +void record_texture_copy(UINT slot, Wrapper* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x, UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src, const D3D12_BOX* box) { if (!self->own().list_open) return; @@ -116,7 +271,21 @@ void __stdcall list_copy_texture(Wrapper* self, const D3D12_TEXTURE_COPY_LOCATIO !copy_texture_side(src, real_src, side_src, format_src, bad_subresource)) return refuse(bad_subresource ? "bad_subresource" : "unknown_resource"); // Planar (depth-stencil, video) copies name a plane footprint format; only single-plane copies are forwarded. - if (side_dst.planes > 1 || side_src.planes > 1) return refuse("planar_unsupported"); + if (side_dst.planes > 1 || side_src.planes > 1) { + if (!box && !x && !y && !z && copy_depth_plane(self, real_src, side_src, real_dst, side_dst)) { + auto* dst_wrapper = as_wrapper(dst->pResource); + mark_copied_texture(self, dst_wrapper, real_dst); + retire_hold(self, dst_wrapper); + retire_hold(self, as_wrapper(src->pResource)); + InterlockedIncrement(&list_copy_texture_forwarded); + static LONG64 copies; + const auto n = InterlockedIncrement64(&copies); + if ((n & (n - 1)) == 0) log("x2w-d3d12 depth-plane copies forwarded %lld slot=%u %ux%u", n, slot, side_src.width, side_src.height); + return; + } + report_planar_copy(slot, side_src, real_src, side_dst, real_dst, as_wrapper(src->pResource), as_wrapper(dst->pResource), x, y, z, box); + return refuse("planar_unsupported"); + } ID3D12Resource* texture = side_dst.kind == x2w_list_copy_texture::Kind::subresource ? real_dst : real_src; if (side_dst.kind == x2w_list_copy_texture::Kind::subresource || side_src.kind == x2w_list_copy_texture::Kind::subresource) { x2w_list_copy_texture::Side blocks{}; @@ -129,7 +298,93 @@ void __stdcall list_copy_texture(Wrapper* self, const D3D12_TEXTURE_COPY_LOCATIO } x2w_list_copy_texture::Box copy_box{}; if (box && x2w_local::readable(box, sizeof(*box))) copy_box = {box->left, box->top, box->front, box->right, box->bottom, box->back}; - const auto verdict = x2w_list_copy_texture::check(side_dst, x, y, z, side_src, box ? ©_box : nullptr); + const bool same_family = x2w_startup::compatible_formats(format_src, format_dst); + const bool textures = side_src.kind == x2w_list_copy_texture::Kind::subresource && + side_dst.kind == x2w_list_copy_texture::Kind::subresource && side_src.samples == 1 && side_dst.samples == 1; + const bool compressed_source = textures && encoded_block_pair(format_dst, format_src); + const bool encoded = compressed_source || (textures && encoded_block_pair(format_src, format_dst)); + const auto verdict = encoded ? check_block_copy(side_dst, x, y, z, side_src, box ? ©_box : nullptr, compressed_source) + : x2w_list_copy_texture::check(side_dst, x, y, z, side_src, box ? ©_box : nullptr, same_family); + if (verdict == x2w_list_copy_texture::Verdict::format_mismatch) { + // Report each distinct pair once: the first calls can all be copies of one atlas level. + using Shape = std::array<UINT, 5>; + static std::mutex mutex; + static std::array<Shape, 16> seen{}; + static size_t used{}; + const Shape shape{slot, UINT(side_src.kind), UINT(format_src), UINT(side_dst.kind), UINT(format_dst)}; + std::lock_guard guard(mutex); + if (used < seen.size() && std::find(seen.begin(), seen.begin() + used, shape) == seen.begin() + used) { + seen[used++] = shape; + log("x2w-d3d12 CopyTextureRegion slot%u format mismatch src kind=%u fmt=%u %ux%ux%u sub=%u " + "dst kind=%u fmt=%u %ux%ux%u sub=%u corner=%u,%u,%u box=%u", + slot, shape[1], shape[2], side_src.width, side_src.height, side_src.depth, side_src.subresource, + shape[3], shape[4], side_dst.width, side_dst.height, side_dst.depth, side_dst.subresource, x, y, z, unsigned(box != nullptr)); + } + } + Wrapper* const src_wrapper = as_wrapper(src->pResource); + Wrapper* const dst_wrapper = as_wrapper(dst->pResource); + const auto* dest_info = resource_info(dst_wrapper); + if (side_dst.kind == x2w_list_copy_texture::Kind::placed_footprint && + side_src.kind == x2w_list_copy_texture::Kind::subresource && dst_wrapper->own().title_memory && dest_info && + (dest_info->placement != Placement::aliased_buffer || + verdict != x2w_list_copy_texture::Verdict::ok)) { + // Stage only the source region, leaving the uncopied part of the CPU footprint intact. + if (side_dst.depth != 1 || side_src.samples != 1 || !side_dst.bytes_per_block || !side_dst.row_pitch) + return refuse("unsupported_title_footprint"); + const auto width = box ? copy_box.right - copy_box.left : side_src.width; + const auto height = box ? copy_box.bottom - copy_box.top : side_src.height; + if (!width || !height || z || UINT64(x) + width > side_dst.width || UINT64(y) + height > side_dst.height || + x % side_dst.block_w || y % side_dst.block_h) return refuse("bad_title_region"); + const UINT64 row = ((UINT64(width) + side_dst.block_w - 1) / side_dst.block_w) * side_dst.bytes_per_block; + const UINT64 host_pitch = (row + 255) & ~UINT64(255); + const UINT rows = UINT((UINT64(height) + side_dst.block_h - 1) / side_dst.block_h); + const UINT64 start_x = UINT64(x / side_dst.block_w) * side_dst.bytes_per_block; + const UINT64 within = UINT64(y / side_dst.block_h) * side_dst.row_pitch + start_x; + UINT64 start{}, end{}; + if (row + start_x > side_dst.row_pitch || host_pitch > UINT_MAX || + !x2w_list_copy_texture::checked_add(side_dst.offset, within, start) || + !x2w_list_copy_texture::checked_add(start, UINT64(rows - 1) * side_dst.row_pitch + row, end) || + end > dest_info->console.Width || end > UINTPTR_MAX - reinterpret_cast<UINT_PTR>(dst_wrapper->own().title_memory)) + return refuse("title_footprint_overflow"); + auto host = side_dst; + host.width = width; host.height = height; host.offset = 0; host.row_pitch = UINT(host_pitch); + host.resource_bytes = host_pitch * rows; + const auto valid = x2w_list_copy_texture::check(host, 0, 0, 0, side_src, box ? ©_box : nullptr, same_family); + if (valid != x2w_list_copy_texture::Verdict::ok) return refuse(x2w_list_copy_texture::name(valid)); + auto copy = std::make_shared<TitleTextureReadback>(); + copy->dest = static_cast<unsigned char*>(dst_wrapper->own().title_memory) + start; + copy->width = UINT(row); copy->rows = rows; copy->host_pitch = UINT(host_pitch); copy->title_pitch = side_dst.row_pitch; + if (!x2w_local::writable(copy->dest, SIZE_T(end-start))) return refuse("title_destination_unwritable"); + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, host.resource_bytes, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + Microsoft::WRL::ComPtr<ID3D12Device> device; + if (FAILED(real_src->GetDevice(IID_PPV_ARGS(&device))) || FAILED(device->CreateCommittedResource( + &props, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(©->staging)))) + return refuse("title_readback_allocation"); + auto* list = recording(self); + { + std::lock_guard lock(texture_readback_mutex); + texture_readback_lists[list].push_back(copy); + } + AcquireSRWLockExclusive(&draw_lock); + upload_texture(self, src_wrapper, real_src); + ReleaseSRWLockExclusive(&draw_lock); + require_state(self, real_src, D3D12_RESOURCE_STATE_COPY_SOURCE); + auto to = *dst, from = *src; + to.pResource = copy->staging.Get(); + to.PlacedFootprint = {0, {format_dst, width, height, 1, UINT(host_pitch)}}; + from.pResource = real_src; + list->CopyTextureRegion(&to, 0, 0, 0, &from, box); + retire_hold(self, src_wrapper); + retire_hold(self, dst_wrapper); + // Preserve a valid desktop buffer copy as well as the separate CPU backing. + D3D12_HEAP_TYPE heap{}; + if (verdict != x2w_list_copy_texture::Verdict::ok || (fixed_heap_state(real_dst, heap) && heap == D3D12_HEAP_TYPE_UPLOAD)) { + InterlockedIncrement(&list_copy_texture_forwarded); + return; + } + } if (verdict != x2w_list_copy_texture::Verdict::ok) return refuse(x2w_list_copy_texture::name(verdict)); // One resource tracks one state, so two subresources of it cannot be COPY_SOURCE and COPY_DEST at once. if (real_src == real_dst) return refuse("same_resource"); @@ -138,8 +393,6 @@ void __stdcall list_copy_texture(Wrapper* self, const D3D12_TEXTURE_COPY_LOCATIO if (src_fixed && heap == D3D12_HEAP_TYPE_READBACK) return refuse("bad_heap"); const bool dst_fixed = fixed_heap_state(real_dst, heap); if (dst_fixed && heap == D3D12_HEAP_TYPE_UPLOAD) return refuse("bad_heap"); - Wrapper* const src_wrapper = as_wrapper(src->pResource); - Wrapper* const dst_wrapper = as_wrapper(dst->pResource); // A copied (non-aliased) buffer has no refresh path here, so its desktop bytes may be stale. if (side_src.kind == x2w_list_copy_texture::Kind::placed_footprint) { const auto* info = resource_info(src_wrapper); @@ -168,6 +421,8 @@ void __stdcall list_copy_texture(Wrapper* self, const D3D12_TEXTURE_COPY_LOCATIO to.pResource = real_dst; from.pResource = real_src; static_cast<ID3D12GraphicsCommandList*>(self->own().real)->CopyTextureRegion(&to, x, y, z, &from, box ? box : nullptr); + if (encoded && !compressed_source && bc_bind_trace::enabled()) bc_bind_trace::copied(self, dst_wrapper, real_dst, side_dst.subresource); + if (side_dst.kind == x2w_list_copy_texture::Kind::subresource) mark_copied_texture(self, dst_wrapper, real_dst); retire_hold(self, dst_wrapper); retire_hold(self, src_wrapper); InterlockedIncrement(&list_copy_texture_forwarded); @@ -178,3 +433,15 @@ extern "C" __declspec(dllexport) void x2w_d3d12_list_copy_texture_stats(LONG* fo if (forwarded) *forwarded = list_copy_texture_forwarded; if (refused) *refused = list_copy_texture_refused; } + +void __stdcall list_copy_texture(Wrapper* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x, UINT y, UINT z, + const D3D12_TEXTURE_COPY_LOCATION* src, const D3D12_BOX* box) +{ + record_texture_copy(16, self, dst, x, y, z, src, box); +} + +void __stdcall list_copy_texture_x(Wrapper* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x, UINT y, UINT z, + const D3D12_TEXTURE_COPY_LOCATION* src, const D3D12_BOX* box, UINT) +{ + record_texture_copy(85, self, dst, x, y, z, src, box); +} diff --git a/src/startup_stubs/local_log.h b/src/startup_stubs/local_log.h index bea306fde9..0539c7b6c2 100644 --- a/src/startup_stubs/local_log.h +++ b/src/startup_stubs/local_log.h @@ -2,10 +2,14 @@ // permissive startup paths. Lines go to stderr and are appended to %X2W_TRAP_LOG% when set. #pragma once +#include "startup_stubs/log_cap.h" #include "startup_stubs/trap.h" #include <cstdarg> +#include <cstddef> +#include <cstdint> #include <cstdio> +#include <cstdlib> namespace x2w_local { @@ -33,35 +37,167 @@ inline void logf(const char* format, ...) noexcept line[n++] = '\n'; const DWORD error = GetLastError(); x2w_trap::write_all(GetStdHandle(STD_ERROR_HANDLE), line, static_cast<DWORD>(n)); - x2w_trap::append_log(line, static_cast<DWORD>(n), false); + x2w_trap::append_trap_log(line, static_cast<DWORD>(n)); // one open handle per module (trap.h) SetLastError(error); } -// True for the first `limit` calls on `counter`. The counter stops at the limit instead of counting -// every call: a gate on a hot path would otherwise pass 2^31 calls, turn negative and pass again. -inline bool first_calls(volatile LONG& counter, LONG limit) noexcept -{ - LONG seen = counter; - while (seen < limit) { - const LONG previous = InterlockedCompareExchange(&counter, seen + 1, seen); - if (previous == seen) return true; - seen = previous; - } - return false; -} +// first_calls (a saturating log cap) is in startup_stubs/log_cap.h. // Number of contiguous readable bytes at start, up to bytes, found by touching one byte per page. -// VirtualQuery is not used for this: on the title's multi-gigabyte regions one query takes about a +// By default VirtualQuery is avoided on the readable path: on the title's multi-gigabyte regions one query takes about a // millisecond (it walks the region to size it). A bad pointer costs a first-chance exception, so // callers on hot paths should pass values that normally are pointers. A guard page that the probe // trips is re-armed. -inline std::size_t probe_readable(std::uintptr_t start, std::size_t bytes) noexcept +// +// LOCAL stall: X2W_PROBE_CACHE=1 (default off) remembers the regions a probe faulted in. After a fault (not a guard +// page) one VirtualQuery at the faulting page; a region that is free, reserved or no-access is kept for +// X2W_PROBE_CACHE_MS (default 100 ms; each module has its own cache), and later probes return at its start without +// touching it (no exception). Only UNREADABLE ranges are cached: a readable range is never assumed, because the title +// and the other stub modules (xmem, the title's own VirtualAlloc / VirtualFree) change pages without any hook this +// module sees, and a stale "readable" would turn a fault the probe catches into one the caller's memcpy does not. The +// cost of a stale entry is the other way round: memory committed in that range inside the expiry reads as unreadable +// (the caller binds null / skips, as for any unreadable range) until the entry expires or invalidate_probe_cache(). +struct ProbeCache { + struct Range { std::uintptr_t start, end, page; ULONGLONG until; }; + static constexpr unsigned size = 64; + SRWLOCK lock = SRWLOCK_INIT; + Range ranges[size] = {}; + unsigned next = 0; + volatile LONG64 hits = 0, faults = 0, cached = 0, queries = 0, query_ticks = 0, preflight_rejects = 0; + volatile LONG generation = 0; // invalidate_probe_cache: entries of an older generation are ignored + LONG range_generation[size] = {}; +}; +inline ProbeCache& probe_cache() noexcept +{ + static ProbeCache cache; + return cache; +} +inline bool probe_cache_on() noexcept +{ + static const bool on = env_on("X2W_PROBE_CACHE"); + return on; +} +inline ULONGLONG probe_cache_ms() noexcept +{ + static const ULONGLONG ms = [] { + const DWORD saved = GetLastError(); + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_PROBE_CACHE_MS", value, sizeof(value)); + SetLastError(saved); + const unsigned long parsed = n && n < sizeof(value) ? std::strtoul(value, nullptr, 10) : 100; + return static_cast<ULONGLONG>(parsed); + }(); + return ms; +} +inline void invalidate_probe_cache() noexcept { InterlockedIncrement(&probe_cache().generation); } +// The end of the part of [start, end) before the first cached unreadable range; start itself when start is in one. +inline std::uintptr_t probe_cache_clamp(std::uintptr_t start, std::uintptr_t end, bool& recheck) noexcept +{ + ProbeCache& c = probe_cache(); + const ULONGLONG now = GetTickCount64(); + const LONG generation = c.generation; + AcquireSRWLockShared(&c.lock); + for (unsigned i = 0; i < ProbeCache::size; ++i) { + const ProbeCache::Range& r = c.ranges[i]; + if (r.end <= start || r.start >= end || r.end <= r.start) continue; + if (now >= r.until || c.range_generation[i] != generation) { + // Recheck the actual failed page. A formerly free region may span unrelated allocations. + if (r.page < end && r.page + 4096 > start) recheck = true; + continue; + } + end = r.start <= start ? start : r.start; + if (end == start) break; + } + ReleaseSRWLockShared(&c.lock); + return end; +} +inline void probe_cache_remember(const MEMORY_BASIC_INFORMATION& info, std::uintptr_t at) noexcept +{ + ProbeCache& c = probe_cache(); + const DWORD protect = info.Protect & 0xFF; + const bool unreadable = info.State != MEM_COMMIT || protect == PAGE_NOACCESS || protect == 0; + if (!unreadable || (info.Protect & PAGE_GUARD)) return; + const auto begin = reinterpret_cast<std::uintptr_t>(info.BaseAddress); + AcquireSRWLockExclusive(&c.lock); + const unsigned slot = c.next++ % ProbeCache::size; + c.ranges[slot] = {begin, begin + info.RegionSize, at & ~std::uintptr_t{4095}, GetTickCount64() + probe_cache_ms()}; + c.range_generation[slot] = c.generation; + ReleaseSRWLockExclusive(&c.lock); + InterlockedIncrement64(&c.cached); +} +inline void probe_cache_fault(std::uintptr_t at) noexcept +{ + ProbeCache& c = probe_cache(); + InterlockedIncrement64(&c.faults); + MEMORY_BASIC_INFORMATION info{}; + LARGE_INTEGER t0, t1; + QueryPerformanceCounter(&t0); + const SIZE_T got = VirtualQuery(reinterpret_cast<const void*>(at), &info, sizeof(info)); + QueryPerformanceCounter(&t1); + InterlockedIncrement64(&c.queries); + InterlockedAdd64(&c.query_ticks, t1.QuadPart - t0.QuadPart); + if (got != sizeof(info) || !info.RegionSize) return; + probe_cache_remember(info, at); +} +// Speculative GPU addresses can refer to reserved or unmapped texture memory. +// A positive hint only skips a repeated VirtualQuery: the SEH-protected page +// reads below still verify every page in the returned prefix. +inline bool probe_query_first() noexcept +{ + // The xmem fault handler can supply valid backing for an apparently reserved page. + static const bool on = env_on("X2W_PROBE_QUERY_FIRST") && !env_on("X2W_XMEM_LAZY_COMMIT"); + return on; +} +struct ProbeRegionHint { std::uintptr_t begin, end; }; +inline ProbeRegionHint& probe_region_hint() noexcept +{ + static thread_local ProbeRegionHint hint{}; + return hint; +} +inline std::uintptr_t probe_mapped_prefix(std::uintptr_t at, std::uintptr_t end, bool cache) noexcept +{ + auto& hint = probe_region_hint(); + while (at < end) { + if (hint.begin <= at && at < hint.end) { + at = hint.end; + continue; + } + MEMORY_BASIC_INFORMATION info{}; + const DWORD saved = GetLastError(); + const SIZE_T got = VirtualQuery(reinterpret_cast<const void*>(at), &info, sizeof(info)); + SetLastError(saved); + if (got != sizeof(info) || !info.RegionSize) return end; // defer to protected reads + const auto begin = reinterpret_cast<std::uintptr_t>(info.BaseAddress); + const auto limit = begin + info.RegionSize; + if (limit <= at) return end; + if (info.State != MEM_COMMIT || (info.Protect & 0xff) == PAGE_NOACCESS) { + if (cache) probe_cache_remember(info, at); + InterlockedIncrement64(&probe_cache().preflight_rejects); + return at; + } + if (info.Protect & PAGE_GUARD) return end; // preserve guard handling + hint = {begin, limit}; + at = limit; + } + return end; +} +inline std::size_t probe_readable(std::uintptr_t start, std::size_t bytes, bool speculative = false) noexcept { if (start < 0x10000 || start > 0x00007FFFFFFEFFFFull || bytes == 0) return 0; std::size_t done = 0; DWORD code = 0; std::uintptr_t at = start; - const std::uintptr_t end = start + bytes; + std::uintptr_t end = start + bytes; + bool recheck = false; + const bool cache = probe_cache_on(); + if (cache) { + const std::uintptr_t clamped = probe_cache_clamp(start, end, recheck); + if (clamped != end) InterlockedIncrement64(&probe_cache().hits); + end = clamped; + if (end == start) return 0; + } + const bool preflight = (speculative || recheck) && probe_query_first(); + if (preflight) end = probe_mapped_prefix(start, end, cache); __try { volatile unsigned char sink = 0; while (at < end) { @@ -72,16 +208,30 @@ inline std::size_t probe_readable(std::uintptr_t start, std::size_t bytes) noexc } (void)sink; } __except (code = GetExceptionCode(), EXCEPTION_EXECUTE_HANDLER) { + if (preflight) probe_region_hint() = {}; if (code == 0x80000001u) { // STATUS_GUARD_PAGE_VIOLATION: the system dropped the guard bit MEMORY_BASIC_INFORMATION info{}; DWORD old = 0; if (VirtualQuery(reinterpret_cast<const void*>(at), &info, sizeof(info)) && info.State == MEM_COMMIT) VirtualProtect(reinterpret_cast<void*>(at & ~std::uintptr_t{0xFFF}), 0x1000, info.Protect | PAGE_GUARD, &old); + } else if (cache) { + probe_cache_fault(at); } } return done; } +// Descriptor payloads can miss on their first probe. Other addresses use first-touch probing +// unless the same page previously failed. +inline std::size_t probe_descriptor_address(std::uintptr_t address, std::size_t bytes) noexcept +{ + return probe_readable(address, bytes, true); +} +inline bool descriptor_memory_readable(std::uintptr_t address, std::size_t bytes) noexcept +{ + return bytes && probe_descriptor_address(address, bytes) == bytes; +} + // With X2W_XMEM_LAZY_COMMIT, physical pages are committed on first touch (xmem_mapped_pages.cpp). A check of the // commit state, or a write that cannot fault (kernel I/O, GPU), commits the range first. A no-op without xmem.dll // or without the switch. diff --git a/src/startup_stubs/log_cap.h b/src/startup_stubs/log_cap.h new file mode 100644 index 0000000000..78798298bf --- /dev/null +++ b/src/startup_stubs/log_cap.h @@ -0,0 +1,33 @@ +// Experimental (docs/startup-runtime.md): caps for diagnostic log lines in the startup stand-ins. +// +// The old pattern `static LONG calls; if (InterlockedIncrement(&calls) <= N) log(...)` wraps after +// 2^31 calls: the counter turns negative, `<= N` holds again, and the line is logged on every call for +// the next two billion calls. A title that polls a stand-in at tens of millions of calls per second +// reaches that in under a minute (a status poll did, and wrote 7.8 million identical lines). +#pragma once + +#include <windows.h> + +namespace x2w_local { + +// True for the first `limit` calls that reach it, false for every later one, from any number of +// threads. The counter never goes past limit + 1, and once it is there a call only reads it: no +// interlocked write, so a hot caller does not keep moving the counter's cache line between cores. +// For a pure log budget only: a counter that is also reported as a total must keep counting (see +// first_of below). +inline bool first_calls(volatile LONG& counter, LONG limit) noexcept +{ + LONG seen = counter; + for (;;) { + if (seen > limit) return false; + const LONG prior = InterlockedCompareExchange(&counter, seen + 1, seen); + if (prior == seen) return seen + 1 <= limit; + seen = prior; + } +} + +// For a count that is also a statistic (it must keep counting): true when the value an increment +// returned is one of the first `limit`, false once the count has wrapped negative. +inline bool first_of(LONG count, LONG limit) noexcept { return count > 0 && count <= limit; } + +} // namespace x2w_local diff --git a/src/startup_stubs/mesh_xmem_handoff.inl b/src/startup_stubs/mesh_xmem_handoff.inl index 77d27e59cf..51ac66b0b6 100644 --- a/src/startup_stubs/mesh_xmem_handoff.inl +++ b/src/startup_stubs/mesh_xmem_handoff.inl @@ -288,10 +288,6 @@ void note_mesh_xmem_write(Wrapper* list, Wrapper* owner, u64 offset, u64 bytes, } if (lease->untracked || lease->owner != owner || lease->offset != offset || lease->bytes != bytes || !lease->matches(address)) return; - auto& states = pass_of(list).states; - // Reserve before recording a barrier so a failed allocation cannot - // leave an untracked transition on the desktop list. - states.reserve(states.size() + 1); require_state(list, lease->buffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST); desktop_list->CopyBufferRegion(lease->buffer.Get(), lease->lease.first_byte, source, source_offset, bytes); recorded.writers[index] = lease; @@ -430,7 +426,9 @@ const char* record_mesh_xmem_reads(Wrapper* list, MeshXMemRead* reads, size_t co } try { auto& states = pass_of(list).states; - states.reserve(states.size() + count); + // Allocate tracking for every input before recording the first barrier. + for (size_t i = 0; i < count; ++i) + states.track(verified[mesh_xmem_index(reads[i].bytes)].lease->buffer.Get()); auto& recorded = mesh_xmem_recordings[desktop_list]; if (trace_call) recorded.trace_call = trace_call; for (size_t i = 0; i < count; ++i) { diff --git a/src/startup_stubs/overlay_window.h b/src/startup_stubs/overlay_window.h index bf8c13e73f..daae37ebb4 100644 --- a/src/startup_stubs/overlay_window.h +++ b/src/startup_stubs/overlay_window.h @@ -19,6 +19,19 @@ inline bool is_title_window(HWND candidate, wchar_t (&name)[256]) return GetClassNameW(candidate, name, 256) && lstrcmpW(name, presenter_class) != 0; } +inline HWND title_picture_window() +{ + HWND window = nullptr; + EnumWindows([](HWND candidate, LPARAM out) -> BOOL { + wchar_t name[256]{}; + if (!is_title_window(candidate, name) || lstrcmpW(name, dialog_class) == 0 || + (GetWindowLongPtrW(candidate, GWL_EXSTYLE) & WS_EX_TOOLWINDOW)) return TRUE; + *reinterpret_cast<HWND*>(out) = candidate; + return FALSE; + }, reinterpret_cast<LPARAM>(&window)); + return window; +} + inline HWND overlay_window() { HWND window = nullptr; diff --git a/src/startup_stubs/pipeline_state_decode.h b/src/startup_stubs/pipeline_state_decode.h index 77f5842191..8d624e3afd 100644 --- a/src/startup_stubs/pipeline_state_decode.h +++ b/src/startup_stubs/pipeline_state_decode.h @@ -1,6 +1,17 @@ -// Experimental (docs/startup-runtime.md): the depth-stencil state of a pipeline created through -// device slot 57, decoded from the register words in its state block A (#1999, item A). +// Experimental (docs/startup-runtime.md): fixed-function state of a pipeline created through device +// slot 57, decoded from its state block A, plus the desktop-layout parts a slot 55 derivation patches. // +// State block A is a packed struct of selected register values, one u32 each at fixed offsets (local +// layout notes; mesh pipelines, A+0x004 == 6, carry the same fields 0x54 bytes later from +0x058 on): +// +0x078 CB_SHADER_MASK, +0x09c PA_CL_CLIP_CNTL, +0x0a0 PA_SU_SC_MODE_CNTL, +// +0x0ac / +0x0b0 / +0x0b4 three floats taken as PA_SU_POLY_OFFSET_CLAMP / _FRONT_SCALE / _FRONT_OFFSET +// (the hardware register order; value ranges fit, not measured), +0x0b8 DB_DEPTH_CONTROL, +// +0x0bc DB_STENCIL_CONTROL, +0x0c0 / +0x0c4 DB_STENCILREFMASK / _BF, +0x0cc CB_TARGET_MASK, +// +0x0d0 .. +0x0ec CB_BLEND0..7_CONTROL (decoded by cb_blend.h). +// Field layouts and enumerations: Mesa's src/amd/registers/gfx10.json (MIT). Facing and polygon offset +// conventions as Mesa's RADV programs them (src/amd/vulkan/radv_cmd_buffer.c: FACE = VkFrontFace, so +// FACE 0 is counter-clockwise in framebuffer space; POLY_OFFSET_FRONT_SCALE = slope factor * 16) and +// as vkd3d-proton maps D3D12 (FrontCounterClockwise -> VK_FRONT_FACE_COUNTER_CLOCKWISE). // State block A holds DB_DEPTH_CONTROL at +0xB8, DB_STENCIL_CONTROL at +0xBC and DB_STENCILREFMASK / // DB_STENCILREFMASK_BF at +0xC0 / +0xC4, before the CB_BLENDn_CONTROL words at +0xD0 (#1216). The // positions were measured locally on the vertex-pipeline layout, whose word at +0x004 is 4. @@ -9,34 +20,65 @@ // on sits 0x54 bytes later (so DB_DEPTH_CONTROL is at +0x10C), and the words before +0x058 keep their // offsets. Also measured locally; a block with any other value at +0x004 is read at the vertex offsets. // -// Field layouts and enumerations follow Mesa's src/amd/registers/gfx10.json (MIT): DB_DEPTH_CONTROL -// STENCIL_ENABLE [0], Z_ENABLE [1], Z_WRITE_ENABLE [2], DEPTH_BOUNDS_ENABLE [3], ZFUNC [6:4], -// BACKFACE_ENABLE [7], STENCILFUNC [10:8], STENCILFUNC_BF [22:20], ENABLE_COLOR_WRITES_ON_DEPTH_FAIL [30], -// DISABLE_COLOR_WRITES_ON_DEPTH_PASS [31]; DB_STENCIL_CONTROL STENCILFAIL [3:0], STENCILZPASS [7:4], -// STENCILZFAIL [11:8] and the _BF fields at [15:12], [19:16], [23:20]; DB_STENCILREFMASK STENCILTESTVAL -// [7:0], STENCILMASK [15:8], STENCILWRITEMASK [23:16], STENCILOPVAL [31:24]; CompareFrag FRAG_NEVER (0) -// .. FRAG_ALWAYS (7); StencilOp STENCIL_KEEP (0) .. STENCIL_XNOR (15). -// -// Pure functions, not used by the draw path yet. A form D3D12 cannot express is refused with a -// reason so the caller can keep the state it had before. +// Pure functions; a form D3D12 cannot express is refused with a reason (or, where noted, approximated +// and flagged) so the caller can keep its previous state and count the cause. #pragma once +#include "cb_blend.h" + #include <d3d12.h> +#include <cmath> #include <cstddef> #include <cstdint> #include <cstring> namespace x2w_pipeline_state { -// ---- state block A offsets (vertex-pipeline layout) ---- -constexpr std::size_t a_depth = 0x0b8, a_stencil = 0x0bc, a_refmask = 0x0c0, a_refmask_bf = 0x0c4; -// The mesh-pipeline layout: the word at +0x004 and the shift applied from +0x058 on. -constexpr std::size_t a_layout = 0x004, a_mesh_shift_from = 0x058, a_mesh_shift = 0x54; -constexpr std::uint32_t a_layout_mesh = 6; +// ---- state block A offsets (vertex / keyed pipelines; mesh_shift added from +0x058 on) ---- +constexpr std::size_t a_shader_mask = 0x078, a_clip = 0x09c, a_mode = 0x0a0, a_bias = 0x0ac, a_depth = 0x0b8, + a_stencil = 0x0bc, a_refmask = 0x0c0, a_refmask_bf = 0x0c4, a_target_mask = 0x0cc, a_blend = 0x0d0; +constexpr std::size_t mesh_shift = 0x54; constexpr std::uint32_t bits(std::uint32_t v, unsigned lo, unsigned hi) { return (v >> lo) & ((1u << (hi - lo + 1)) - 1); } +// The register words of one state block A. +struct Words { + std::uint32_t shader_mask = 0, clip = 0, mode = 0, depth = 0, stencil = 0, refmask = 0, refmask_bf = 0, target_mask = 0; + std::uint32_t blend[8] = {}; + float bias_clamp = 0, bias_scale = 0, bias_offset = 0; + bool mesh = false; +}; + +inline bool read_words(const unsigned char* a, std::size_t bytes, Words& w) +{ + if (!a || bytes < 8) return false; + std::uint32_t kind; + std::memcpy(&kind, a + 4, 4); + w.mesh = kind == 6; + const std::size_t s = w.mesh ? mesh_shift : 0; + if (bytes < a_blend + s + 32) return false; + auto u = [&](std::size_t off) { std::uint32_t v; std::memcpy(&v, a + off + s, 4); return v; }; + auto f = [&](std::size_t off) { float v; std::memcpy(&v, a + off + s, 4); return v; }; + w.shader_mask = u(a_shader_mask); + w.clip = u(a_clip); + w.mode = u(a_mode); + w.bias_clamp = f(a_bias); + w.bias_scale = f(a_bias + 4); + w.bias_offset = f(a_bias + 8); + w.depth = u(a_depth); + w.stencil = u(a_stencil); + w.refmask = u(a_refmask); + w.refmask_bf = u(a_refmask_bf); + w.target_mask = u(a_target_mask); + for (unsigned i = 0; i < 8; ++i) w.blend[i] = u(a_blend + 4 * i); + return true; +} + +// The mesh-pipeline layout: the word at +0x004 and the shift applied from +0x058 on. +constexpr std::size_t a_layout = 0x004, a_mesh_shift_from = 0x058, a_mesh_shift = mesh_shift; +constexpr std::uint32_t a_layout_mesh = 6; + // Bytes to add to a vertex-layout offset at or after +0x058 for this block (0 or a_mesh_shift). inline std::size_t state_block_a_shift(const unsigned char* a, std::size_t bytes) { @@ -66,12 +108,13 @@ inline bool read_depth_stencil_words(const unsigned char* a, std::size_t bytes, return true; } +// ---- depth / stencil: DB_DEPTH_CONTROL, DB_STENCIL_CONTROL, DB_STENCILREFMASK(_BF) ---- struct DepthStencil { bool ok = false; const char* reason = nullptr; D3D12_DEPTH_STENCIL_DESC desc{}; std::uint8_t stencil_ref = 0; // STENCILTESTVAL: D3D12 sets it on the command list (OMSetStencilRef) - bool depth_bounds = false; // DEPTH_BOUNDS_ENABLE: not applied (the bounds are separate state); flagged only + bool depth_bounds = false; // DEPTH_BOUNDS_ENABLE: not applied (values are dynamic); flagged only bool masks_differ = false; // back-face read/write masks or reference differ from the front: front used, flagged }; @@ -79,7 +122,7 @@ struct DepthStencil { constexpr D3D12_COMPARISON_FUNC compare(std::uint32_t frag) { return static_cast<D3D12_COMPARISON_FUNC>((frag & 7) + 1); } // StencilOp -> D3D12_STENCIL_OP; 0 when D3D12 has no equivalent. opval: STENCILOPVAL, the amount the -// ADD / SUB ops apply (D3D12's INCR / DECR forms add or subtract one). +// ADD / SUB ops apply (D3D12's INCR / DECR forms add one). inline D3D12_STENCIL_OP stencil_op(std::uint32_t op, std::uint32_t opval) { switch (op) { @@ -132,12 +175,243 @@ inline DepthStencil decode_depth_stencil(std::uint32_t depth_control, std::uint3 d.FrontFace = d.BackFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}; } else { out.stencil_ref = static_cast<std::uint8_t>(bits(refmask, 0, 7)); - // D3D12 has one reference and one pair of masks for both faces. - if (back_own && bits(refmask_bf, 0, 23) != bits(refmask, 0, 23)) out.masks_differ = true; + if (back_own && bits(refmask_bf, 0, 23) != bits(refmask, 0, 23)) out.masks_differ = true; // masks or reference (upstream) } if (!z) d.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; // canonical: the function of a disabled test is ignored out.ok = true; return out; } +// ---- rasterizer: PA_SU_SC_MODE_CNTL, PA_CL_CLIP_CNTL, polygon offset ---- +struct Raster { + bool ok = false; + const char* reason = nullptr; + D3D12_RASTERIZER_DESC desc{}; + bool clip_split = false; // only one of ZCLIP_NEAR/FAR_DISABLE: D3D12 has one switch; clipping kept + bool bias_rounded = false; // FRONT_OFFSET not an integer: rounded to DepthBias +}; + +// flip_winding: run-time switch for the one convention that was not observed on a frame (FACE 0 is +// taken as FrontCounterClockwise = TRUE; flip inverts that). +inline Raster decode_rasterizer(std::uint32_t mode, std::uint32_t clip, float bias_clamp, float bias_scale, float bias_offset, + bool flip_winding) +{ + Raster out; + D3D12_RASTERIZER_DESC& r = out.desc; + if (bits(mode, 3, 4)) { // POLY_MODE dual: per-face point / line / triangle drawing + const std::uint32_t front = bits(mode, 5, 7), back = bits(mode, 8, 10); + if (front != back || front == 0) { + out.reason = "polygon mode with points or with different front and back modes"; + return out; + } + r.FillMode = front == 1 ? D3D12_FILL_MODE_WIREFRAME : D3D12_FILL_MODE_SOLID; + } else { + r.FillMode = D3D12_FILL_MODE_SOLID; + } + const bool cull_front = bits(mode, 0, 0) != 0, cull_back = bits(mode, 1, 1) != 0; + if (cull_front && cull_back) { + out.reason = "both faces culled"; + return out; + } + r.CullMode = cull_front ? D3D12_CULL_MODE_FRONT : cull_back ? D3D12_CULL_MODE_BACK : D3D12_CULL_MODE_NONE; + r.FrontCounterClockwise = (bits(mode, 2, 2) == 0) != flip_winding; + const bool offset_front = bits(mode, 11, 11) != 0, offset_back = bits(mode, 12, 12) != 0; + if (offset_front != offset_back) { + out.reason = "polygon offset on one face only"; + return out; + } + if (offset_front) { + if (!std::isfinite(bias_clamp) || !std::isfinite(bias_scale) || !std::isfinite(bias_offset) || std::fabs(bias_offset) > 1e6f) { + out.reason = "polygon offset values not finite"; + return out; + } + const float rounded = std::nearbyint(bias_offset); + out.bias_rounded = rounded != bias_offset; + r.DepthBias = static_cast<INT>(rounded); + r.DepthBiasClamp = bias_clamp; + r.SlopeScaledDepthBias = bias_scale / 16.0f; + } + const bool near_off = bits(clip, 26, 26) != 0, far_off = bits(clip, 27, 27) != 0; + out.clip_split = near_off != far_off; + r.DepthClipEnable = !(near_off && far_off); + r.MultisampleEnable = FALSE; + r.AntialiasedLineEnable = FALSE; + r.ForcedSampleCount = 0; + r.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; + out.ok = true; + return out; +} + +// ---- blend: CB_BLENDn_CONTROL (cb_blend.h) with CB_TARGET_MASK & CB_SHADER_MASK per target ---- +struct Blend { + bool ok = false; + const char* reason = nullptr; + unsigned refused_targets = 0; + D3D12_BLEND_DESC desc{}; + bool dual_source = false; // an enabled target uses a SRC1 factor: the pixel shader must export a second colour + unsigned masked_targets = 0; // bit per target whose write mask is narrower than RGBA +}; + +inline bool uses_src1(D3D12_BLEND f) +{ + return f == D3D12_BLEND_SRC1_COLOR || f == D3D12_BLEND_INV_SRC1_COLOR || f == D3D12_BLEND_SRC1_ALPHA || f == D3D12_BLEND_INV_SRC1_ALPHA; +} + +// apply_masks false reproduces state_block_blend.h (every target writes RGBA). +inline Blend decode_blend(const std::uint32_t control[8], std::uint32_t target_mask, std::uint32_t shader_mask, bool apply_masks, + bool alpha_factor_supported) +{ + Blend out; + out.desc.IndependentBlendEnable = TRUE; + for (unsigned t = 0; t < 8; ++t) { + const std::uint32_t mask = apply_masks ? ((target_mask & shader_mask) >> (4 * t)) & 0xF : 0xF; + const x2w_cb_blend::Decoded d = x2w_cb_blend::decode(control[t], mask, alpha_factor_supported); + if (!d.ok) { + if (!out.refused_targets) out.reason = d.reason; + out.refused_targets |= 1u << t; + continue; + } + out.desc.RenderTarget[t] = d.desc; + if (mask != 0xF) out.masked_targets |= 1u << t; + const auto& r = d.desc; + if (r.BlendEnable && (uses_src1(r.SrcBlend) || uses_src1(r.DestBlend) || uses_src1(r.SrcBlendAlpha) || uses_src1(r.DestBlendAlpha))) + out.dual_source = true; + } + out.ok = !out.refused_targets; + return out; +} + +// ---- slot 55 derived records: {u32 part; desktop desc} of record_size bytes; the last of a part wins ---- +constexpr std::size_t record_size = sizeof(std::uint32_t) + sizeof(D3D12_BLEND_DESC); +static_assert(record_size == 0x14c, "derived record size"); +enum Part : std::uint32_t { part_depth_stencil = 0, part_rasterizer = 1, part_blend = 2 }; + +// Returns the byte offset of the last record's desc with the given part, or SIZE_MAX. +inline std::size_t last_part(const unsigned char* records, std::size_t bytes, std::uint32_t part) +{ + if (!records || !bytes || bytes % record_size) return SIZE_MAX; + for (std::size_t end = bytes; end; end -= record_size) { + std::uint32_t tag; + std::memcpy(&tag, records + end - record_size, sizeof(tag)); + if (tag == part) return end - record_size + sizeof(tag); + } + return SIZE_MAX; +} + +inline bool valid_stencil_face(const D3D12_DEPTH_STENCILOP_DESC& f) +{ + auto op = [](D3D12_STENCIL_OP o) { return o >= D3D12_STENCIL_OP_KEEP && o <= D3D12_STENCIL_OP_DECR; }; + return op(f.StencilFailOp) && op(f.StencilDepthFailOp) && op(f.StencilPassOp) && f.StencilFunc >= D3D12_COMPARISON_FUNC_NEVER && + f.StencilFunc <= D3D12_COMPARISON_FUNC_ALWAYS; +} + +// A derived depth-stencil part, read field by field (the title leaves garbage in padding); false when a +// field is outside its enumeration. +inline bool derived_depth_stencil(const unsigned char* records, std::size_t bytes, D3D12_DEPTH_STENCIL_DESC& out) +{ + const std::size_t at = last_part(records, bytes, part_depth_stencil); + if (at == SIZE_MAX) return false; + D3D12_DEPTH_STENCIL_DESC d; + std::memcpy(&d, records + at, sizeof(d)); + if (static_cast<std::uint32_t>(d.DepthWriteMask) > 1 || d.DepthFunc < D3D12_COMPARISON_FUNC_NEVER || d.DepthFunc > D3D12_COMPARISON_FUNC_ALWAYS || + !valid_stencil_face(d.FrontFace) || !valid_stencil_face(d.BackFace)) + return false; + D3D12_DEPTH_STENCIL_DESC clean{}; // field by field: the padding after StencilWriteMask holds garbage + clean.DepthEnable = d.DepthEnable != 0; + clean.DepthWriteMask = d.DepthWriteMask; + clean.DepthFunc = d.DepthFunc; + clean.StencilEnable = d.StencilEnable != 0; + clean.StencilReadMask = d.StencilReadMask; + clean.StencilWriteMask = d.StencilWriteMask; + clean.FrontFace = d.FrontFace; + clean.BackFace = d.BackFace; + out = clean; + return true; +} + +inline bool derived_rasterizer(const unsigned char* records, std::size_t bytes, D3D12_RASTERIZER_DESC& out) +{ + const std::size_t at = last_part(records, bytes, part_rasterizer); + if (at == SIZE_MAX) return false; + D3D12_RASTERIZER_DESC r; + std::memcpy(&r, records + at, sizeof(r)); + if (r.FillMode < D3D12_FILL_MODE_WIREFRAME || r.FillMode > D3D12_FILL_MODE_SOLID || r.CullMode < D3D12_CULL_MODE_NONE || + r.CullMode > D3D12_CULL_MODE_BACK || !std::isfinite(r.DepthBiasClamp) || !std::isfinite(r.SlopeScaledDepthBias) || + r.ForcedSampleCount > 16 || static_cast<std::uint32_t>(r.ConservativeRaster) > 1) + return false; + r.FrontCounterClockwise = r.FrontCounterClockwise != 0; + r.DepthClipEnable = r.DepthClipEnable != 0; + r.MultisampleEnable = r.MultisampleEnable != 0; + r.AntialiasedLineEnable = r.AntialiasedLineEnable != 0; + out = r; + return true; +} + +// ---- a decoded depth-stencil state against the depth target the draw has bound ---- +enum TargetAdjust : unsigned { + adjust_no_target = 1, // depth or stencil test with no depth target bound: both turned off + adjust_no_stencil = 2, // stencil test on a format without a stencil plane: stencil turned off + adjust_read_only = 4, // read-only depth target: depth and stencil writes turned off +}; + +inline unsigned adjust_for_target(D3D12_DEPTH_STENCIL_DESC& d, bool has_target, bool stencil_plane, bool read_only) +{ + unsigned done = 0; + if (!has_target) { + if (d.DepthEnable || d.StencilEnable) done |= adjust_no_target; + d.DepthEnable = FALSE; + d.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + d.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + d.StencilEnable = FALSE; + return done; + } + if (d.StencilEnable && !stencil_plane) { + d.StencilEnable = FALSE; + done |= adjust_no_stencil; + } + if (read_only && ((d.DepthEnable && d.DepthWriteMask != D3D12_DEPTH_WRITE_MASK_ZERO) || (d.StencilEnable && d.StencilWriteMask))) { + d.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + d.StencilWriteMask = 0; + done |= adjust_read_only; + } + return done; +} + +struct Switches { + bool depth = false, cull = false, flip = false, blend = false, depth_clear = false, uncleared = false, depthclip = false; +}; + +inline bool is_one(const char* v) { return v && v[0] == '1' && v[1] == 0; } +inline bool is_zero(const char* v) { return v && v[0] == '0' && v[1] == 0; } + +inline Switches parse_switches(const char* all, const char* depth, const char* cull, const char* blend, const char* flip, + const char* depth_clear = nullptr, const char* uncleared = nullptr, const char* depthclip = nullptr) +{ + Switches s; + if (is_zero(all)) return s; + s.depthclip = is_one(depthclip); + s.depth = is_one(depth); + s.cull = is_one(cull); + s.flip = s.cull && is_one(flip); + s.blend = is_one(blend); + s.depth_clear = is_one(depth_clear); + s.uncleared = s.depth && is_one(uncleared); + return s; +} + +#ifdef _WIN32 +inline Switches switches_from_env() +{ + constexpr int n = 8; + char v[n][8] = {}; + const char* names[n] = {"X2W_DRAW_STATE", "X2W_DRAW_STATE_DEPTH", "X2W_DRAW_STATE_CULL", + "X2W_DRAW_STATE_BLEND", "X2W_DRAW_STATE_CULL_FLIP", "X2W_DRAW_STATE_DEPTH_CLEAR", + "X2W_DRAW_STATE_DEPTH_UNCLEARED", "X2W_DRAW_STATE_DEPTHCLIP"}; + const char* p[n] = {}; + for (int i = 0; i < n; ++i) + if (GetEnvironmentVariableA(names[i], v[i], sizeof(v[i])) && v[i][0]) p[i] = v[i]; + return parse_switches(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]); +} +#endif + } // namespace x2w_pipeline_state diff --git a/src/startup_stubs/placed_buffer_range.h b/src/startup_stubs/placed_buffer_range.h index 456cdfe6b6..e46bf9df57 100644 --- a/src/startup_stubs/placed_buffer_range.h +++ b/src/startup_stubs/placed_buffer_range.h @@ -58,6 +58,21 @@ inline QueryRegion query_region() } } // namespace placed_detail +// OpenExistingHeapFromAddress imports the whole private allocation. VirtualQuery +// splits it at any change of commitment or page protection; a second region +// belonging to the same allocation therefore disqualifies the import. +inline bool private_heap_importable(void* base) +{ + MEMORY_BASIC_INFORMATION first{}, next{}; + if (!base || VirtualQuery(base, &first, sizeof(first)) != sizeof(first) || + first.AllocationBase != base || first.BaseAddress != base || first.Type != MEM_PRIVATE || + first.State != MEM_COMMIT || (first.Protect & (PAGE_GUARD | PAGE_NOACCESS))) return false; + const auto start = reinterpret_cast<std::uintptr_t>(base); + if (first.RegionSize > UINTPTR_MAX - start) return false; + return VirtualQuery(reinterpret_cast<void*>(start + first.RegionSize), &next, sizeof(next)) == sizeof(next) && + next.AllocationBase != base; +} + // 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. diff --git a/src/startup_stubs/placed_pool.h b/src/startup_stubs/placed_pool.h new file mode 100644 index 0000000000..582e0696ba --- /dev/null +++ b/src/startup_stubs/placed_pool.h @@ -0,0 +1,98 @@ +// LOCAL (perf_work/STARTUP.md), opt-in X2W_D3D12_PLACED_POOL=1: small buffers that Device slot 133 +// cannot alias with title memory (the "not aliased" fallback) are placed on default heaps that the +// stand-in creates in 64 MiB blocks, instead of one committed resource (one kernel allocation) each. +// The start-up loop creates ~2,800 such buffers (0x410 and 0x1000 bytes) one after the other. +// +// Each buffer takes a fresh 64 KiB slot (the desktop placement alignment, which is also the size a +// committed buffer this small occupies). Slots are never reused, so a buffer starts zero-filled as a +// committed one does; the memory of a released buffer is not returned until the process ends. +// X2W_D3D12_PLACED_POOL_MIB (default 512) caps the pool; past it, and for buffers over 64 KiB, the +// caller falls back to a committed resource. Unmeasured: whether placement is cheaper here. +#pragma once + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include <windows.h> +#include <d3d12.h> + +#include <cstdint> +#include <cstdlib> + +namespace x2w_startup { + +class PlacedPool { +public: + static constexpr std::uint64_t slot_bytes = std::uint64_t{64} << 10; + static constexpr std::uint64_t heap_bytes = std::uint64_t{64} << 20; + + // S_OK with *out set, or a failure (pool off, full, buffer too large, or a desktop error): the + // caller then creates a committed resource as before. + HRESULT create(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, ID3D12Resource** out) + { + *out = nullptr; + if (!enabled() || desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || desc.Width == 0 || desc.Width > slot_bytes) + return E_NOTIMPL; + AcquireSRWLockExclusive(&lock_); + HRESULT hr = S_OK; + if (!heap_ || used_ + slot_bytes > heap_bytes) { + if (total_ + heap_bytes > budget()) { + hr = E_OUTOFMEMORY; + } else { + D3D12_HEAP_DESC heap_desc{}; + heap_desc.SizeInBytes = heap_bytes; + heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT; + heap_desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS; + ID3D12Heap* heap = nullptr; + hr = device->CreateHeap(&heap_desc, IID_PPV_ARGS(&heap)); + if (SUCCEEDED(hr)) { + heap_ = heap; // kept for the life of the process (placed buffers also hold it) + used_ = 0; + total_ += heap_bytes; + ++heaps_; + } + } + } + if (SUCCEEDED(hr)) { + D3D12_RESOURCE_DESC placed = desc; + placed.Alignment = 0; + hr = device->CreatePlacedResource(heap_, used_, &placed, state, nullptr, IID_PPV_ARGS(out)); + if (SUCCEEDED(hr)) { + used_ += slot_bytes; + ++placed_; + } + } + ReleaseSRWLockExclusive(&lock_); + return hr; + } + + std::uint64_t placed() const { return placed_; } + std::uint64_t heaps() const { return heaps_; } + +private: + static bool enabled() + { + static const bool on = [] { + char value[4]{}; + return GetEnvironmentVariableA("X2W_D3D12_PLACED_POOL", value, sizeof(value)) && value[0] == '1'; + }(); + return on; + } + static std::uint64_t budget() + { + static const std::uint64_t bytes = [] { + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_D3D12_PLACED_POOL_MIB", value, sizeof(value)); + const unsigned long mib = n && n < sizeof(value) ? std::strtoul(value, nullptr, 10) : 512ul; + return std::uint64_t{mib} << 20; + }(); + return bytes; + } + + SRWLOCK lock_ = SRWLOCK_INIT; + ID3D12Heap* heap_ = nullptr; + std::uint64_t used_ = 0, total_ = 0, heaps_ = 0, placed_ = 0; +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/rawaddr_table.h b/src/startup_stubs/rawaddr_table.h new file mode 100644 index 0000000000..16c9f91a11 --- /dev/null +++ b/src/startup_stubs/rawaddr_table.h @@ -0,0 +1,167 @@ +#pragma once + +#include <d3d12.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <string> +#include <vector> + +namespace x2w_startup::rawaddr { + +constexpr unsigned kRegions = 8; +constexpr unsigned kSpace = 100; +constexpr unsigned kNullSlot = kRegions; +constexpr unsigned kStatsSlot = kRegions + 1; +constexpr unsigned kSlots = kRegions + 2; +constexpr unsigned kTableDwords = 3 * kRegions; +// Statistics slot written by the shader: [0] miss count, [16 + 8 * (n & 7)] the missed address (lo, hi). +constexpr unsigned kStatsBytes = 128; +constexpr unsigned kStatsRing = 8; + +enum class SeedKind { rootconst64, rootconst32, rootdesc }; +struct Seed { + SeedKind kind; + unsigned param = 0, word = 0, shift = 0; +}; + +// Parses a sidecar; false when it is not a version-1 file with the expected table shape. +inline bool parse_sidecar(const std::string& text, std::vector<Seed>& seeds) +{ + seeds.clear(); + bool version = false, shape = false; + for (std::size_t at = 0; at < text.size();) { + std::size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + const std::string line = text.substr(at, end - at); + at = end + 1; + unsigned a = 0, b = 0, c = 0; + char kind[24] = ""; + if (line.rfind("rawaddr 1", 0) == 0) { + version = true; + } else if (std::sscanf(line.c_str(), "slots %u space %u", &a, &b) == 2) { + shape = a == kRegions && b == kSpace; + } else if (std::sscanf(line.c_str(), "seed %23s %u %u %u", kind, &a, &b, &c) >= 2) { + Seed s{}; + if (!std::strcmp(kind, "rootconst64")) s = {SeedKind::rootconst64, a, b, 0}; + else if (!std::strcmp(kind, "rootconst32")) s = {SeedKind::rootconst32, a, b, c}; + else if (!std::strcmp(kind, "rootdesc")) s = {SeedKind::rootdesc, a, 0, 0}; + else return false; + if (s.param >= 16 || s.word >= 16 || (s.kind == SeedKind::rootconst64 && s.word >= 15) || s.shift >= 40) return false; + seeds.push_back(s); + } + } + return version && shape; +} + +// The title address a seed names, from the title's root state (16 parameters x 16 constant words, and the +// title address of each root descriptor). 0 when the parameter is not of the expected kind. +inline std::uint64_t seed_address(const Seed& s, const int kind[16], const std::uint32_t constants[16][16], const std::uint64_t address[16]) +{ + if (s.param >= 16) return 0; + switch (s.kind) { + case SeedKind::rootconst64: + return kind[s.param] == 1 && s.word < 15 ? (constants[s.param][s.word] | (std::uint64_t{constants[s.param][s.word + 1]} << 32)) : 0; + case SeedKind::rootconst32: + return kind[s.param] == 1 && s.word < 16 ? (std::uint64_t{constants[s.param][s.word]} << s.shift) : 0; + case SeedKind::rootdesc: + return kind[s.param] == 3 || kind[s.param] == 4 ? address[s.param] : 0; + } + return 0; +} + +// One region of the table: the title address the view's first byte stands for, and the bytes it covers. +// A raw view must start 16-byte aligned, so the window offset is rounded down and the difference is folded +// into the base (the shader then also accepts the 0..15 bytes before the title address: still the same +// window memory). +struct Region { + std::uint64_t base = 0; + std::uint32_t size = 0; + std::uint64_t view_offset = 0; // byte offset of the view in the window buffer (16-byte aligned) +}; +inline Region make_region(std::uint64_t title_address, std::uint64_t bytes, std::uint64_t window_offset) +{ + Region r; + const std::uint64_t slack = window_offset & 15; + r.view_offset = window_offset - slack; + const std::uint64_t size = bytes + slack; + r.size = static_cast<std::uint32_t>(size > 0xfffffff0ull ? 0xfffffff0ull : size) & ~3u; + r.base = title_address - slack; + return r; +} +inline bool region_contains(const Region& r, std::uint64_t address) { return r.size && address - r.base < r.size; } + +inline void fill_table(const Region* regions, unsigned count, std::uint32_t words[kTableDwords]) +{ + std::memset(words, 0, sizeof(std::uint32_t) * kTableDwords); + for (unsigned k = 0; k < count && k < kRegions; ++k) { + words[3 * k] = static_cast<std::uint32_t>(regions[k].base); + words[3 * k + 1] = static_cast<std::uint32_t>(regions[k].base >> 32); + words[3 * k + 2] = regions[k].size; + } +} + +// The title root signature plus [n] kTableDwords constants b0 space100 and [n + 1] a table of kSlots UAVs +// u0 space100. The heap-directly-indexed flags are cleared as device_create_root_signature does. +// *first_extra = n. Returns the serialized blob (caller releases) or null; *error gets the failing step. +inline ID3DBlob* augmented_root(const void* blob, std::size_t bytes, UINT* first_extra, const char** error) +{ + *error = nullptr; + ID3D12VersionedRootSignatureDeserializer* reader = nullptr; + if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(blob, bytes, IID_PPV_ARGS(&reader)))) { + *error = "deserialize"; + return nullptr; + } + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* source = nullptr; + if (FAILED(reader->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &source)) || !source) { + reader->Release(); + *error = "version 1.1"; + return nullptr; + } + const D3D12_ROOT_SIGNATURE_DESC1& in = source->Desc_1_1; + std::vector<D3D12_ROOT_PARAMETER1> params(in.pParameters, in.pParameters + in.NumParameters); + for (const auto& p : params) + if ((p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE && [&] { + for (UINT i = 0; i < p.DescriptorTable.NumDescriptorRanges; ++i) + if (p.DescriptorTable.pDescriptorRanges[i].RegisterSpace == kSpace) return true; + return false; + }()) || + ((p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) && p.Constants.RegisterSpace == kSpace) || + ((p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV || p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV || + p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_UAV) && p.Descriptor.RegisterSpace == kSpace)) { + reader->Release(); + *error = "title root uses register space 100"; + return nullptr; + } + *first_extra = static_cast<UINT>(params.size()); + D3D12_ROOT_PARAMETER1 table{}; + table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + table.Constants = {0, kSpace, kTableDwords}; + table.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + params.push_back(table); + static const D3D12_DESCRIPTOR_RANGE1 range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, kSlots, 0, kSpace, + D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, 0}; + D3D12_ROOT_PARAMETER1 uavs{}; + uavs.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + uavs.DescriptorTable = {1, &range}; + uavs.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + params.push_back(uavs); + constexpr UINT indexed = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC out{}; + out.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + out.Desc_1_1 = {static_cast<UINT>(params.size()), params.data(), in.NumStaticSamplers, in.pStaticSamplers, + static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(in.Flags & ~indexed)}; + ID3DBlob* result = nullptr; + ID3DBlob* errors = nullptr; + const HRESULT hr = D3D12SerializeVersionedRootSignature(&out, &result, &errors); + if (errors) errors->Release(); + reader->Release(); // owns source: released only after serialization + if (FAILED(hr)) { + *error = "serialize (over 64 root dwords?)"; + return nullptr; + } + return result; +} + +} // namespace x2w_startup::rawaddr diff --git a/src/startup_stubs/red_producer_diagnostic.inl b/src/startup_stubs/red_producer_diagnostic.inl index 0fb886a557..4e71f86766 100644 --- a/src/startup_stubs/red_producer_diagnostic.inl +++ b/src/startup_stubs/red_producer_diagnostic.inl @@ -1,6 +1,37 @@ // Opt-in diagnostic for writes to the title-selected presentation texture. extern LONG frame_number; +struct TraceUavSelection { + u64 key = 0; + int slot = -1; + constexpr int match(u64 candidate) const { return key == candidate ? slot : -1; } +}; + +constexpr TraceUavSelection parse_trace_uav(std::string_view value) +{ + if (value.size() < 18 || value.size() > 19 || value[16] != ',') return {}; + u64 key = 0; + for (char c : value.substr(0, 16)) { + unsigned digit = 0; + if (c >= '0' && c <= '9') digit = c - '0'; + else if (c >= 'a' && c <= 'f') digit = c - 'a' + 10; + else if (c >= 'A' && c <= 'F') digit = c - 'A' + 10; + else return {}; + key = (key << 4) | digit; + } + int slot = 0; + for (char c : value.substr(17)) { + if (c < '0' || c > '9') return {}; + slot = 10 * slot + c - '0'; + } + return slot < 64 ? TraceUavSelection{key, slot} : TraceUavSelection{}; +} + +static_assert(parse_trace_uav("0123456789abCDef,63").match(0x0123456789abcdefULL) == 63); +static_assert(parse_trace_uav("0123456789abcdef,20").match(1) == -1); +static_assert(parse_trace_uav("0123456789abcdef,64").slot == -1); +static_assert(parse_trace_uav("0123456789abcdef,2x").slot == -1); + class RedProducers { using Resource = Microsoft::WRL::ComPtr<ID3D12Resource>; using Fence = Microsoft::WRL::ComPtr<ID3D12Fence>; @@ -18,6 +49,9 @@ class RedProducers { bool live = true; bool pending = false; bool ambiguous = false; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0, row_bytes = 0; + UINT rows = 0; }; struct History { const void* list; @@ -39,6 +73,10 @@ class RedProducers { std::size_t history_next_ = 0, history_count_ = 0; unsigned submit_order_ = 0; bool full_logged_ = false; + TraceUavSelection uav_; + bool pair_ = false; + unsigned uav_samples_ = 0; + LONG uav_last_frame_ = 0; public: struct Disabled {}; @@ -47,6 +85,9 @@ public: RedProducers() { char value[48]{}; + const DWORD size = GetEnvironmentVariableA("X2W_CX_TRACE_UAV", value, sizeof(value)); + if (size && size < sizeof(value)) uav_ = parse_trace_uav({value, size}); + pair_ = uav_.slot >= 0 && x2w_local::env_on("X2W_CX_TRACE_PAIR"); if (GetEnvironmentVariableA("X2W_RED_PRODUCER_FRAMES", value, sizeof(value)) && std::sscanf(value, "%ld,%ld", &first_, &last_) == 2 && first_ >= 1 && last_ >= first_) { log("x2w-red producer capture frames %ld..%ld; max 512 center texels from known present targets", first_, last_); @@ -75,7 +116,7 @@ public: } } - bool enabled() const { return first_ || auto_count_; } + bool enabled() const { return first_ || auto_count_ || uav_.slot >= 0; } bool matches(const unsigned char* rgba) const { return rgba[0] == target_rgb_[0] && rgba[1] == target_rgb_[1] && rgba[2] == target_rgb_[2]; @@ -111,7 +152,7 @@ public: void present(ID3D12Resource* surface) { - if (!enabled() || !surface) return; + if ((!first_ && !auto_count_) || !surface) return; std::lock_guard<std::mutex> guard(lock_); const auto found = std::find_if(surfaces_.begin(), surfaces_.end(), [=](const Resource& r) { return r.Get() == surface; }); if (found == surfaces_.end() && surfaces_.size() < 8) { @@ -134,7 +175,7 @@ public: if (history_count_ < history_limit) ++history_count_; } if (!interested()) return 0; - if (entries_.size() >= 512) { + if (entries_.size() - uav_samples_ >= 512) { if (!full_logged_) log("x2w-red producer capture limit reached at frame %ld", frame_number + 1); full_logged_ = true; return 0; @@ -162,6 +203,51 @@ public: return ordinal; } + bool pair_present(LONG frame, ID3D12CommandQueue* queue) + { + if (!pair_) return false; + std::lock_guard<std::mutex> guard(lock_); + return std::any_of(entries_.begin(), entries_.end(), [=](const Entry& e) { + return e.bytes && !e.ambiguous && e.queue == queue && e.record_frame == frame && e.submit_frame == frame; + }); + } + + int uav_slot(u64 key) const { return uav_.match(key); } + + void after_uav(Wrapper* owner, ID3D12GraphicsCommandList* list, ID3D12Resource* texture, LONG frame, u64 key, unsigned slot) + { + std::lock_guard<std::mutex> guard(lock_); + if (!frame || trace_uav_busy_frame != frame || uav_samples_ >= 2 || uav_last_frame_ == frame) return; + const auto& states = pass_of(owner).states; + const auto* bound = states.find(texture); + if (!bound || bound->depth != D3D12_RESOURCE_STATE_UNORDERED_ACCESS) return; + const auto desc = texture->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.DepthOrArraySize != 1 || desc.SampleDesc.Count != 1) return; + Entry entry{list, {}, Resource(texture), {}, nullptr, frame, 0, slot, static_cast<unsigned>(entries_.size() + 1), 0, "compute-uav", key}; + auto* device = device_of(the_device); + device->GetCopyableFootprints(&desc, 0, 1, 0, &entry.footprint, &entry.rows, &entry.row_bytes, &entry.bytes); + if (!entry.bytes || entry.bytes > (32ull << 20) || entry.rows != desc.Height || !desc.Width || + entry.row_bytes % desc.Width || entry.row_bytes / desc.Width > 16) return; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = entry.bytes; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&entry.readback)))) return; + x2w_budget::committed(device, entry.readback.Get(), D3D12_HEAP_TYPE_READBACK); + const D3D12_TEXTURE_COPY_LOCATION from{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION to{entry.readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = entry.footprint; + require_state(owner, texture, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + require_state(owner, texture, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + entries_.push_back(std::move(entry)); + uav_last_frame_ = frame; + ++uav_samples_; + } + void after(Wrapper* owner, unsigned ordinal) { if (!ordinal) return; @@ -241,6 +327,20 @@ private: log("x2w-red producer ambiguous resubmit ordinal=%u order=%u", entry.ordinal, entry.submit_order); continue; } + if (entry.bytes) { + const D3D12_RANGE read{0, static_cast<SIZE_T>(entry.bytes)}, none{}; + void* memory = nullptr; + if (SUCCEEDED(entry.readback->Map(0, &read, &memory))) { + char label[192]; + std::snprintf(label, sizeof(label), "x2w-frame post-dispatch %016llx u%u frame %ld order %u target %p", + entry.key, entry.attachment, entry.record_frame, entry.submit_order, static_cast<void*>(entry.surface.Get())); + report_texture_pixels(label, label, memory, entry.surface->GetDesc(), entry.footprint, entry.rows, entry.row_bytes); + if (pair_ && entry.record_frame == entry.submit_frame) report_frame_rgb("lighting-uav", entry.submit_frame, entry.surface.Get(), memory, + entry.surface->GetDesc(), entry.footprint); + entry.readback->Unmap(0, &none); + } + continue; + } const D3D12_RANGE read{0, after_offset + 4}, none{}; void* memory = nullptr; if (FAILED(entry.readback->Map(0, &read, &memory))) continue; @@ -262,7 +362,8 @@ RedProducers& red_producers() // Closed lists may be submitted again and still hold these GPU references. static auto* const tracker = [] { char value[2]{}; - if (GetEnvironmentVariableA("X2W_RED_PRODUCER_FRAMES", value, sizeof(value)) || + if (GetEnvironmentVariableA("X2W_CX_TRACE_UAV", value, sizeof(value)) || + GetEnvironmentVariableA("X2W_RED_PRODUCER_FRAMES", value, sizeof(value)) || GetEnvironmentVariableA("X2W_RED_PRODUCER_AUTO", value, sizeof(value))) return new RedProducers; return &disabled; }(); diff --git a/src/startup_stubs/resource_address_index.h b/src/startup_stubs/resource_address_index.h index 1992f82cbb..2c4a69aa09 100644 --- a/src/startup_stubs/resource_address_index.h +++ b/src/startup_stubs/resource_address_index.h @@ -76,6 +76,15 @@ class AddressIndex { } } } + template<class F> + void for_each_at(std::uint64_t base, F&& f) const + { + for (const Group& group : groups_) { + const auto [first, last] = group.by_base.equal_range(base); + for (auto it = first; it != last; ++it) + if (f(it->second.key)) return; + } + } bool contains(std::uint64_t base, Key key) const { for (const Group& group : groups_) { diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 7c9a170462..33f5f3d3e8 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -194,10 +194,7 @@ using x2w_api_trace::no_argument; template <int N> __declspec(noinline) u64 forward(Proxy* self, u64 a, u64 b, u64 c, u64 s0, u64 s1, u64 s2, u64 s3, u64 s4, u64 s5, u64 s6, u64 s7) { - // call_counts also feeds the periodic call-rate summary, so it keeps counting; a count that has - // passed 2^31 is negative and must not log again. - const LONG call = N >= 3 ? InterlockedIncrement(&call_counts[self->provider][N]) : 0; - const bool log_it = call > 0 && call <= 6; + const bool log_it = N >= 3 && x2w_local::first_of(InterlockedIncrement(&call_counts[self->provider][N]), 6); u64 args[11] = {a, b, c, s0, s1, s2, s3, s4, s5, s6, s7}; // Declared outputs are snapshotted so the write is seen rather than assumed; nothing else is read. The // snapshot is bounded by the declared width, so a one-byte flag, a DWORD and a caller-sized buffer @@ -322,11 +319,99 @@ void fill_slots(std::index_sequence<I...>) ((slot_table[I] = reinterpret_cast<void*>(&forward<static_cast<int>(I)>)), ...); } +// LOCAL (performance): repeated QueryApiImpl answers. The title's static runtime library calls +// QueryApiImpl before every API call (query, call one method, Release), so a title that polls one +// API (seen: the connectivity hint, about 120 times a second) also asks the runtime for the same +// object each time. Once the runtime has returned the same object for one (provider, interface) +// pair cache_after times in a row, that object is kept with a reference of the cache's own and later +// queries for the pair get it (with AddRef, as the runtime gives it) without calling the runtime. +// The extra reference keeps the object alive even if the runtime made a new one per call. +// X2W_RUNTIME_QUERY_CACHE=0 turns this off. +struct CachedQuery { + GUID provider, iid; + void* real; // what the runtime returned + void* answer; // what the title received (the proxy, or the object itself) + int same; + bool cached; +}; +constexpr int max_cached_queries = 32, cache_after = 8; +CachedQuery cached_queries[max_cached_queries]; +int cached_query_count; +SRWLOCK cached_query_lock = SRWLOCK_INIT; +volatile LONG cached_answers; // queries answered from the cache (heartbeat) +bool query_cache_on() noexcept +{ + static const bool on = [] { + char value[8]; + const DWORD n = GetEnvironmentVariableA("X2W_RUNTIME_QUERY_CACHE", value, sizeof(value)); + return !(n == 1 && value[0] == '0'); + }(); + return on; +} +using AddRefMethod = ULONG(__stdcall*)(void*); +void add_ref(void* object) { reinterpret_cast<AddRefMethod>((*reinterpret_cast<void***>(object))[1])(object); } + +bool cached_answer(const GUID* provider, const GUID* iid, void** out) +{ + void* real = nullptr; + void* answer = nullptr; + AcquireSRWLockShared(&cached_query_lock); + for (int i = 0; i < cached_query_count; ++i) { + const CachedQuery& entry = cached_queries[i]; + if (entry.cached && IsEqualGUID(entry.provider, *provider) && IsEqualGUID(entry.iid, *iid)) { + real = entry.real; + answer = entry.answer; + break; + } + } + ReleaseSRWLockShared(&cached_query_lock); + if (!answer) return false; + add_ref(real); // the title releases the answer once per query; the proxy forwards Release to real + *out = answer; + InterlockedIncrement(&cached_answers); + return true; +} + +void note_answer(const GUID& provider, const GUID& iid, void* real, void* answer) +{ + AcquireSRWLockExclusive(&cached_query_lock); + CachedQuery* entry = nullptr; + for (int i = 0; i < cached_query_count && !entry; ++i) + if (IsEqualGUID(cached_queries[i].provider, provider) && IsEqualGUID(cached_queries[i].iid, iid)) entry = &cached_queries[i]; + if (!entry && cached_query_count < max_cached_queries) { + entry = &cached_queries[cached_query_count++]; + *entry = CachedQuery{provider, iid, real, answer, 0, false}; + } + bool now_cached = false; + if (entry && !entry->cached) { + if (entry->real == real && entry->answer == answer) { + ++entry->same; + } else { + entry->real = real; + entry->answer = answer; + entry->same = 1; + } + if (entry->same >= cache_after) { + add_ref(real); // the cache's own reference, never released + entry->cached = now_cached = true; + } + } + ReleaseSRWLockExclusive(&cached_query_lock); + if (now_cached) + x2w_local::logf("x2w-runtime QueryApiImpl %08lx/%08lx: same object %d times, later queries answered from the cache " + "(X2W_RUNTIME_QUERY_CACHE=0 turns this off)", provider.Data1, iid.Data1, cache_after); +} + HRESULT __stdcall proxy_query(const GUID* provider, const GUID* iid, void** out) { + if (provider && iid && out && query_cache_on() && cached_answer(provider, iid, out)) return S_OK; const QueryApi query = load_real_query(); if (!query) return E_FAIL; const HRESULT hr = query(provider, iid, out); + const bool cacheable = hr == S_OK && provider && iid && out && *out && query_cache_on(); + void* const real_object = cacheable ? *out : nullptr; + // Read only after a successful real query: a failed one may have been given an unreadable provider (E_POINTER). + const GUID asked_provider = cacheable ? *provider : GUID{}; const bool output_writable = FAILED(hr) && fake_user() && x2w_local::writable(out, sizeof(*out)); const bool pair_readable = output_writable && x2w_local::readable(provider, sizeof(*provider)) && x2w_local::readable(iid, sizeof(*iid)); @@ -397,6 +482,7 @@ HRESULT __stdcall proxy_query(const GUID* provider, const GUID* iid, void** out) } ReleaseSRWLockExclusive(&proxy_lock); if (proxy) *out = proxy; + if (cacheable) note_answer(asked_provider, *iid, real_object, *out); if (local) return proxy ? S_OK : hr; return hr; } @@ -1229,9 +1315,7 @@ bool save_call(int slot, u64* args, u64* result) } } -// ---- other areas, answered as an offline console with one installed package -------------------- -// Which provider is which area, and what an offline console answers, follow the public VIctory -// project's runtime notes (github.com/Marvisak/VIctory, used as a reference for facts only). +// Offline runtime providers expose one installed package. unsigned env_number(const char* name, unsigned fallback, int base) { char text[32]{}; @@ -1326,13 +1410,10 @@ bool area_call(const GUID& provider_id, int slot, u64* args, u64* result) return true; } if (slot == 3 && IsEqualGUID(provider_id, store_provider_id)) { - // XStoreCreateContext(user, &context). Vtable slot 3 of XStoreImpl - // (0dd112ac-7c24-448c-b92b-3960fb5bd30c): QueryInterface, AddRef, Release, then this. - // The public GDK takes the console user and writes an XStoreContextHandle. The VIctory - // runtime notes (github.com/Marvisak/VIctory, facts only) answer it offline by writing one - // context and returning success; catalog, licence and purchase methods stay unanswered. - // Only the local user is answered. A different user is refused and the output is left - // unchanged. A buffer that cannot be written is E_INVALIDARG. + // XStoreCreateContext(user, &context) occupies XStoreImpl vtable slot 3 after IUnknown. The interface ID is + // 0dd112ac-7c24-448c-b92b-3960fb5bd30c. Supply a store context for the local console user. A different user leaves + // the output unchanged. An unwritable output yields E_INVALIDARG. Catalog, licence and purchase methods remain + // unanswered. if (args[0] != local_user_handle) { *result = 0x80004005; return true; @@ -1345,6 +1426,18 @@ bool area_call(const GUID& provider_id, int slot, u64* args, u64* result) *result = 0; return true; } + if (slot > 3 && IsEqualGUID(provider_id, store_provider_id)) { + // LOCAL: every other store method that receives the offline context must not reach the + // runtime, which dereferences the handle. Refused with E_FAIL, as an offline store would. + for (int i = 0; i < 6; ++i) { + if (args[i] != store_context_handle) continue; + static LONG refused; + if (x2w_local::first_calls(refused, 16)) + x2w_local::logf("x2w-runtime store slot %d with the offline context -> E_FAIL", slot); + *result = 0x80004005; + return true; + } + } return false; } @@ -1487,6 +1580,7 @@ BOOL WINAPI DllMain(HINSTANCE self, DWORD reason, void*) // logs have gone quiet. if (HANDLE heartbeat = CreateThread(nullptr, 0, [](void*) -> DWORD { static LONG seen[max_providers][max_slots]; + LONG cached_seen = 0; for (int second = 10;; second += 10) { Sleep(10000); char line[1024]; @@ -1501,6 +1595,12 @@ BOOL WINAPI DllMain(HINSTANCE self, DWORD reason, void*) any = true; } } + const LONG cached_now = cached_answers, cached_delta = cached_now - cached_seen; + cached_seen = cached_now; + if (cached_delta > 0 && n < static_cast<int>(sizeof(line)) - 40) { + n += std::snprintf(line + n, sizeof(line) - n, " (queries from cache x%ld)", cached_delta); + any = true; + } if (any) x2w_local::logf("%s", line); } }, nullptr, 0, nullptr)) CloseHandle(heartbeat); diff --git a/src/startup_stubs/slice_footprints.h b/src/startup_stubs/slice_footprints.h index 40f8b49712..63d8a57103 100644 --- a/src/startup_stubs/slice_footprints.h +++ b/src/startup_stubs/slice_footprints.h @@ -17,6 +17,7 @@ inline bool recheck_cpu_texture(const D3D12_RESOURCE_DESC& desc, UINT64 bytes, U // GetCopyableFootprints orders a single NV12 image as Y followed by UV. // Keep this layout identical in the XG writer and the desktop draw uploader. struct SliceFootprints { + inline static thread_local UINT64 recorded_bytes = 0; static constexpr UINT max_mips = 15; UINT planes; UINT count; @@ -68,6 +69,7 @@ struct SliceFootprints { D3D12_TEXTURE_COPY_LOCATION to{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; to.SubresourceIndex = static_cast<UINT>(subresource); list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + recorded_bytes += bytes(i); } }; } // namespace x2w_startup diff --git a/src/startup_stubs/small_texture_heap.h b/src/startup_stubs/small_texture_heap.h new file mode 100644 index 0000000000..0d66a54d55 --- /dev/null +++ b/src/startup_stubs/small_texture_heap.h @@ -0,0 +1,83 @@ +#pragma once + +#include "small_texture_4k.h" +#include <d3d12.h> +#include <wrl/client.h> +#include <algorithm> +#include <vector> +#include <utility> + +namespace x2w_startup { + +// publish_linear_texture serializes access and keeps every published resource. +// Only unused heap tails are allocated; offsets never return to the allocator. +class SmallTextureHeap { + using Heap = Microsoft::WRL::ComPtr<ID3D12Heap>; + struct Chunk { Heap heap; UINT64 size{}, used{}; }; + std::vector<Chunk> chunks_; + ID3D12Device* owner_ = nullptr; + UINT64 next_size_ = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + static constexpr UINT64 max_chunk = 1u << 20; + static constexpr GUID backing_id = {0xd5b4b235, 0x9fb8, 0x4924, {0xb2,0x8b,0x69,0xd2,0x72,0x63,0x19,0xa6}}; + +public: + UINT64 count{}, committed_equivalent{}, reserved{}, occupied{}; + + bool place(ID3D12Device* device, D3D12_RESOURCE_DESC desc, UINT64 standard_bytes, ID3D12Resource** output) + { + *output = nullptr; + if (!standard_bytes || standard_bytes == UINT64_MAX || desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || + desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN || desc.Flags != D3D12_RESOURCE_FLAG_NONE || + desc.SampleDesc.Count != 1 || desc.SampleDesc.Quality || (owner_ && owner_ != device)) return false; + const auto tile = small_texture_4k_detail::block(small_texture_4k_bits(desc.Format)); + if (!tile.width || !desc.Width || !desc.Height || desc.Width > 16 * tile.width || desc.Height > 16 * tile.height || + ((desc.Width + tile.width - 1) / tile.width) * ((desc.Height + tile.height - 1) / tile.height) > 16) return false; + + desc.Alignment = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT; + const auto requested = device->GetResourceAllocationInfo(0, 1, &desc); + const UINT64 bytes = requested.SizeInBytes; + if (requested.Alignment != desc.Alignment || !bytes || bytes >= standard_bytes || bytes > max_chunk || + bytes % desc.Alignment) return false; + + Chunk* chunk = nullptr; + for (auto& c : chunks_) { + const auto room = c.size - c.used; + if (room >= bytes && (!chunk || room < chunk->size - chunk->used)) chunk = &c; + } + Chunk fresh; + if (!chunk) { + const UINT64 alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + const UINT64 slots = (std::max)(UINT64{1}, next_size_ / bytes); + fresh.size = (slots * bytes + alignment - 1) & ~(alignment - 1); + D3D12_HEAP_DESC heap{}; + heap.SizeInBytes = fresh.size; + heap.Properties.Type = D3D12_HEAP_TYPE_DEFAULT; + heap.Properties.CreationNodeMask = heap.Properties.VisibleNodeMask = 1; + heap.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES; + if (FAILED(device->CreateHeap(&heap, IID_PPV_ARGS(&fresh.heap)))) return false; + chunk = &fresh; + } + Microsoft::WRL::ComPtr<ID3D12Resource> placed; + if (FAILED(device->CreatePlacedResource(chunk->heap.Get(), chunk->used, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&placed))) || + FAILED(placed->SetPrivateDataInterface(backing_id, chunk->heap.Get()))) return false; + + chunk->used += bytes; + if (chunk == &fresh) { + const UINT64 size = fresh.size; + if (fresh.used < size) chunks_.push_back(std::move(fresh)); + reserved += size; + next_size_ = (std::min)(max_chunk, size * 2); + owner_ = device; + } else if (chunk->used == chunk->size) { + if (chunk != &chunks_.back()) *chunk = std::move(chunks_.back()); + chunks_.pop_back(); + } + committed_equivalent += standard_bytes; + occupied += bytes; + ++count; + *output = placed.Detach(); + return true; + } +}; +} diff --git a/src/startup_stubs/state_block_blend.h b/src/startup_stubs/state_block_blend.h index 31cb19c83e..f6f2745831 100644 --- a/src/startup_stubs/state_block_blend.h +++ b/src/startup_stubs/state_block_blend.h @@ -2,11 +2,11 @@ // slot 57, read from its state block A (#1216). // // State block A holds the eight CB_BLENDn_CONTROL words at +0xD0, one per render target (measured -// on #1216). They are decoded with cb_blend.h. CB_TARGET_MASK has not been located, so every -// target keeps all four channels. +// on #1216). They are decoded with cb_blend.h. Every target keeps all four channels here; the +// write masks (CB_TARGET_MASK & CB_SHADER_MASK) are pipeline_state_decode.h's, behind a switch. #pragma once -#include "cb_blend.h" +#include "pipeline_state_decode.h" #include <cstddef> #include <cstdint> @@ -42,35 +42,32 @@ inline bool state_block_blend(const unsigned char* block, std::size_t bytes, boo why = "state block A shorter than the blend words"; return false; } - D3D12_BLEND_DESC blend{}; - blend.IndependentBlendEnable = TRUE; - unsigned refused = 0; - bool target0_dual_source = false; - for (unsigned target = 0; target < 8; ++target) { - std::uint32_t word; - std::memcpy(&word, block + state_block_blend_offset + 4 * target, sizeof(word)); - const x2w_cb_blend::Decoded decoded = x2w_cb_blend::decode(word, 0xF, alpha_factor_supported); - if (decoded.ok && decoded.desc.BlendEnable) { - const bool dual = uses_dual_source(decoded.desc); - if (target == 0) { - target0_dual_source = dual; - } else if (dual || target0_dual_source) { - if (!refused) - why = dual ? "dual-source factor on a target other than 0" - : "dual-source blend on target 0 with another blending target"; - refused |= 1u << target; - continue; - } - } - if (decoded.ok) { - blend.RenderTarget[target] = decoded.desc; - continue; - } - if (!refused) why = decoded.reason; - refused |= 1u << target; + // One decoder for the eight words (pipeline_state_decode.h), with every target writing RGBA. + std::uint32_t words[8]; + std::memcpy(words, block + state_block_blend_offset, sizeof(words)); + const x2w_pipeline_state::Blend decoded = x2w_pipeline_state::decode_blend(words, 0, 0, false, alpha_factor_supported); + // Upstream rule kept at the merge: D3D12 dual-source blending is target 0 only, and no other target may blend + // beside it. A dual-source factor on another target, or a blending target beside a dual-source target 0, is refused. + unsigned dual_refused = 0; + const char* dual_why = nullptr; + const auto& t0 = decoded.desc.RenderTarget[0]; + const bool target0_dual_source = t0.BlendEnable && uses_dual_source(t0); + for (unsigned target = 1; target < 8; ++target) { + const auto& t = decoded.desc.RenderTarget[target]; + if (!t.BlendEnable) continue; + const bool dual = uses_dual_source(t); + if (!dual && !target0_dual_source) continue; + if (!dual_refused && !(decoded.refused_targets & ((1u << target) - 1))) + dual_why = dual ? "dual-source factor on a target other than 0" : "dual-source blend on target 0 with another blending target"; + dual_refused |= 1u << target; } - if (refused_targets) *refused_targets = refused; - if (refused) return false; + if (refused_targets) *refused_targets = decoded.refused_targets | dual_refused; + if (!decoded.ok || dual_refused) { + why = dual_why && (!decoded.refused_targets || (dual_refused & -dual_refused) < (decoded.refused_targets & -decoded.refused_targets)) + ? dual_why : decoded.reason ? decoded.reason : dual_why; + return false; + } + const D3D12_BLEND_DESC& blend = decoded.desc; *out = blend; return true; } diff --git a/src/startup_stubs/title_composition.h b/src/startup_stubs/title_composition.h new file mode 100644 index 0000000000..755113b7e2 --- /dev/null +++ b/src/startup_stubs/title_composition.h @@ -0,0 +1,48 @@ +#pragma once + +#include <dcomp.h> +#include <dxgi1_4.h> +#include <wrl/client.h> + +namespace x2w_startup { + +// Attach the GPU output to the existing client area without taking ownership of the window or its message loop. +struct TitleComposition { + Microsoft::WRL::ComPtr<IDCompositionDevice> device; + Microsoft::WRL::ComPtr<IDCompositionTarget> target; + Microsoft::WRL::ComPtr<IDCompositionVisual> visual; + HWND window = nullptr; + SIZE size{}; + + HRESULT show(HWND hwnd, IDXGISwapChain1* chain, UINT width, UINT height) + { + RECT client{}; + if (!GetClientRect(hwnd, &client)) return HRESULT_FROM_WIN32(ERROR_INVALID_WINDOW_HANDLE); + if (client.right <= 0 || client.bottom <= 0) return S_FALSE; + if (!device) { + HRESULT hr = DCompositionCreateDevice(nullptr, IID_PPV_ARGS(device.GetAddressOf())); + if (FAILED(hr)) return hr; + } + if (window != hwnd || !target) { + Microsoft::WRL::ComPtr<IDCompositionTarget> next_target; + Microsoft::WRL::ComPtr<IDCompositionVisual> next_visual; + HRESULT hr = device->CreateTargetForHwnd(hwnd, TRUE, next_target.GetAddressOf()); + if (SUCCEEDED(hr)) hr = device->CreateVisual(next_visual.GetAddressOf()); + if (SUCCEEDED(hr)) hr = next_visual->SetContent(chain); + if (SUCCEEDED(hr)) hr = next_target->SetRoot(next_visual.Get()); + if (FAILED(hr)) return hr; + target = next_target; + visual = next_visual; + window = hwnd; + size = {}; + } + if (size.cx == client.right && size.cy == client.bottom) return S_OK; + D2D_MATRIX_3X2_F transform{static_cast<float>(client.right) / width, 0, 0, + static_cast<float>(client.bottom) / height, 0, 0}; + HRESULT hr = visual->SetTransform(transform); + if (SUCCEEDED(hr)) hr = device->Commit(); + if (SUCCEEDED(hr)) size = {client.right, client.bottom}; + return hr; + } +}; +} diff --git a/src/startup_stubs/title_heap_memory.h b/src/startup_stubs/title_heap_memory.h index 8c1372370c..200a0f4491 100644 --- a/src/startup_stubs/title_heap_memory.h +++ b/src/startup_stubs/title_heap_memory.h @@ -14,16 +14,17 @@ #include <cstdint> namespace x2w_startup { -inline bool heap_needs_title_memory(D3D12_DESCRIPTOR_HEAP_TYPE type, std::uint64_t desktop_cpu_start) +inline bool heap_needs_title_memory(D3D12_DESCRIPTOR_HEAP_TYPE type, std::uint64_t desktop_cpu_start, bool gpu_samplers = false) { - return type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || (desktop_cpu_start & (alignof(void*) - 1)) != 0; + return type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || (gpu_samplers && type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) || + (desktop_cpu_start & (alignof(void*) - 1)) != 0; } // An opaque start cannot be exposed as CPU memory if the required allocation fails. template <class Allocate> bool ensure_title_heap_memory(D3D12_DESCRIPTOR_HEAP_TYPE type, std::uint64_t desktop_cpu_start, - std::uint64_t bytes, std::uint64_t& title_memory, Allocate allocate) + std::uint64_t bytes, std::uint64_t& title_memory, Allocate allocate, bool gpu_samplers = false) { - if (title_memory || !heap_needs_title_memory(type, desktop_cpu_start)) return true; + if (title_memory || !heap_needs_title_memory(type, desktop_cpu_start, gpu_samplers)) return true; if (bytes) title_memory = allocate(bytes); return title_memory != 0; } diff --git a/src/startup_stubs/title_texture_readback.inl b/src/startup_stubs/title_texture_readback.inl new file mode 100644 index 0000000000..d00ffceb5b --- /dev/null +++ b/src/startup_stubs/title_texture_readback.inl @@ -0,0 +1,114 @@ +// A placed title buffer may have a separate desktop allocation or a tight, unaligned +// footprint. Stage the copied texels and publish the actual rows at the guest pitch. +struct TitleTextureReadback { + Microsoft::WRL::ComPtr<ID3D12Resource> staging; + Microsoft::WRL::ComPtr<ID3D12Fence> last; + unsigned char* dest{}; + UINT width{}, rows{}, host_pitch{}, title_pitch{}; +}; + +using TextureReadbackPtr = std::shared_ptr<TitleTextureReadback>; +std::mutex texture_readback_mutex; +std::unordered_map<ID3D12CommandList*, std::vector<TextureReadbackPtr>> texture_readback_lists; + +void discard_texture_readbacks(ID3D12CommandList* list) +{ + std::lock_guard lock(texture_readback_mutex); + texture_readback_lists.erase(list); +} + +struct TextureReadbackFlight { + std::vector<TextureReadbackPtr> copies; + Microsoft::WRL::ComPtr<ID3D12Fence> fence; + HANDLE event{}; + ~TextureReadbackFlight() { if (event) CloseHandle(event); } +}; + +void CALLBACK land_texture_readbacks(PTP_CALLBACK_INSTANCE, void* data, PTP_WAIT wait, TP_WAIT_RESULT) +{ + std::unique_ptr<TextureReadbackFlight> flight(static_cast<TextureReadbackFlight*>(data)); + if (flight->fence->GetCompletedValue() == 1) { + for (const auto& copy : flight->copies) { + void* mapped{}; + const SIZE_T size = SIZE_T(copy->rows - 1) * copy->host_pitch + copy->width; + const D3D12_RANGE read{0, size}; + if (FAILED(copy->staging->Map(0, &read, &mapped))) continue; + bool landed = true; + for (UINT y = 0; y < copy->rows && landed; ++y) { + auto* to = copy->dest + SIZE_T(y) * copy->title_pitch; + auto* from = static_cast<unsigned char*>(mapped) + SIZE_T(y) * copy->host_pitch; + SIZE_T wrote{}; + landed = x2w_local::writable(to, copy->width) && + WriteProcessMemory(GetCurrentProcess(), to, from, copy->width, &wrote) && wrote == copy->width; + } + static LONG reports, failures; + if ((!landed && first_calls(failures, 8)) || (landed && first_calls(reports, 16))) + log("x2w-gpu placed texture readback landed=%u address=%p row_bytes=%u rows=%u first_float=%g", + unsigned(landed), copy->dest, copy->width, copy->rows, + copy->width >= sizeof(float) ? double(*static_cast<const float*>(mapped)) : 0.); + const D3D12_RANGE none{}; + copy->staging->Unmap(0, &none); + } + } + flight->fence->Signal(2); + if (wait) CloseThreadpoolWait(wait); +} + +// Preserve staging until the queue reaches the copies. The queue then waits for CPU +// publication, so a later guest fence can be observed without any subsequent present. +std::unique_ptr<TextureReadbackFlight> prepare_texture_readbacks(ID3D12CommandQueue* queue, + const std::vector<ID3D12CommandList*>& lists) +{ + std::lock_guard lock(texture_readback_mutex); + std::unique_ptr<TextureReadbackFlight> flight; + for (auto* list : lists) { + const auto found = texture_readback_lists.find(list); + if (found == texture_readback_lists.end()) continue; + if (!flight) flight = std::make_unique<TextureReadbackFlight>(); + for (const auto& copy : found->second) { + if (copy->last && copy->last->GetCompletedValue() < 2) queue->Wait(copy->last.Get(), 2); + flight->copies.push_back(copy); + } + } + if (!flight) return {}; + Microsoft::WRL::ComPtr<ID3D12Device> device; + if (FAILED(queue->GetDevice(IID_PPV_ARGS(&device))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&flight->fence)))) { + log("x2w-gpu placed texture readback could not create submission fence"); + return {}; + } + for (const auto& copy : flight->copies) copy->last = flight->fence; + return flight; +} + +void submit_texture_readbacks(ID3D12CommandQueue* queue, std::unique_ptr<TextureReadbackFlight> flight) +{ + if (!flight) return; + if (FAILED(queue->Signal(flight->fence.Get(), 1))) { + flight->fence->Signal(2); + log("x2w-gpu placed texture readback queue signal failed"); + return; + } + // A pending thread-pool callback can outlive the last application reference to this DLL. + static const bool pinned = [] { + HMODULE module{}; + return GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast<LPCWSTR>(&land_texture_readbacks), &module) != FALSE; + }(); + if (pinned) flight->event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const auto wait = flight->event ? CreateThreadpoolWait(land_texture_readbacks, flight.get(), nullptr) : nullptr; + if (wait && SUCCEEDED(flight->fence->SetEventOnCompletion(1, flight->event))) { + queue->Wait(flight->fence.Get(), 2); + auto* pending = flight.release(); + SetThreadpoolWait(wait, pending->event, nullptr); + return; + } + if (wait) CloseThreadpoolWait(wait); + // Losing an event must not expose stale bytes or release an active readback buffer. + if (SUCCEEDED(flight->fence->SetEventOnCompletion(1, nullptr))) { + land_texture_readbacks(nullptr, flight.release(), nullptr, 0); + } else { + flight->fence->Signal(2); + log("x2w-gpu placed texture readback completion failed"); + } +} diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index a4aca72ddf..c2729ccf8d 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -19,15 +19,59 @@ constexpr UINT translated_sampler_space = 1; constexpr UINT translated_sampler_fallback = translated_sampler_count - 1; constexpr UINT title_sampler_stride = sizeof(SamplerWords); +// LOCAL (textures): X2W_SAMPLER_LOD=1 also carries the LOD and border fields of the S# words (sampler_lod_fields). +// Off by default: fixtures and manifests written with word 1 = 0 would otherwise be limited to mip 0 (MAX_LOD 0). +inline bool sampler_lod_fields_on() +{ + static const bool on = [] { + char value[4]{}; + const DWORD saved = GetLastError(); + const bool v = GetEnvironmentVariableA("X2W_SAMPLER_LOD", value, sizeof(value)) && value[0] == '1'; + SetLastError(saved); + return v; + }(); + return on; +} + +struct SamplerLodFields { + float bias, min_lod, max_lod; + D3D12_STATIC_BORDER_COLOR border; + bool border_register; // BORDER_COLOR_TYPE 3 (a border colour table entry): not translated, transparent black +}; + +// Field positions of SQ_IMG_SAMP_WORD1..3 (Mesa src/amd/registers/gfx10-rsrc.json, as cited in tools/pixel_aot.py): +// word 1 bits 11:0 MIN_LOD and 23:12 MAX_LOD, unsigned 4.8 fixed point; word 2 bits 13:0 LOD_BIAS, signed 5.8 +// (bits 19:14 LOD_BIAS_SEC, the secondary bias, are not carried); word 3 bits 31:30 BORDER_COLOR_TYPE +// (0 transparent black, 1 opaque black, 2 opaque white, 3 register), numbered as D3D12_STATIC_BORDER_COLOR 0..2. +// MAX_LOD 0xfff (15.996) stays unlimited. D3D12 limits the bias to [-16, 15.99]. +inline SamplerLodFields sampler_lod_fields(const SamplerWords& words) +{ + SamplerLodFields f{}; + int bias = static_cast<int>(words[2] & 0x3fff); + if (bias & 0x2000) bias -= 0x4000; + f.bias = static_cast<float>(bias) / 256.0f; + if (f.bias < D3D12_MIP_LOD_BIAS_MIN) f.bias = D3D12_MIP_LOD_BIAS_MIN; + if (f.bias > D3D12_MIP_LOD_BIAS_MAX) f.bias = D3D12_MIP_LOD_BIAS_MAX; + f.min_lod = static_cast<float>(words[1] & 0xfff) / 256.0f; + const UINT max_raw = (words[1] >> 12) & 0xfff; + f.max_lod = max_raw == 0xfff ? D3D12_FLOAT32_MAX : static_cast<float>(max_raw) / 256.0f; + if (f.max_lod < f.min_lod) f.max_lod = f.min_lod; + const UINT type = words[3] >> 30; + f.border_register = type == 3; + f.border = type == 3 ? D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK : static_cast<D3D12_STATIC_BORDER_COLOR>(type); + return f; +} + // comparison: the sampler is read through a SamplerComparisonState (manifest line smpc). SQ_IMG_SAMP_WORD0 bits // 14:12 hold SQ_TEX_DEPTH_COMPARE, which lists NEVER..ALWAYS in the order of D3D12_COMPARISON_FUNC minus one. +// lod_fields (LOCAL, X2W_SAMPLER_LOD): bias, LOD and border fields of the descriptor. // lod_limits (manifest line smpl, image_sample_b and a constant sampler of image_sample, _l, _lz): the descriptor's LOD clamp is carried over. 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:5169-5170 encodes them as S_FIXED(x, 8)), so MinLOD and MaxLOD are the fields // divided by 256. dynamic_sampler() sets it for every heap entry. Without it MinLOD stays 0 and MaxLOD unbounded, as // for the other sample forms. inline D3D12_STATIC_SAMPLER_DESC decode_sampler(const SamplerWords& words, UINT shader_register, bool comparison = false, - bool lod_limits = false) + bool lod_limits = false, bool lod_fields = sampler_lod_fields_on()) { static const D3D12_TEXTURE_ADDRESS_MODE modes[8] = { D3D12_TEXTURE_ADDRESS_MODE_WRAP, D3D12_TEXTURE_ADDRESS_MODE_MIRROR, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, @@ -54,6 +98,13 @@ inline D3D12_STATIC_SAMPLER_DESC decode_sampler(const SamplerWords& words, UINT : border_type == 1u ? D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK : D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; s.MaxLOD = D3D12_FLOAT32_MAX; + if (lod_fields) { + const auto f = sampler_lod_fields(words); + s.MipLODBias = f.bias; + s.MinLOD = f.min_lod; + s.MaxLOD = f.max_lod; + s.BorderColor = f.border; + } if (lod_limits) { s.MinLOD = static_cast<float>(words[1] & 0xfffu) / 256.0f; s.MaxLOD = static_cast<float>((words[1] >> 12) & 0xfffu) / 256.0f; @@ -106,7 +157,7 @@ inline std::vector<D3D12_STATIC_SAMPLER_DESC> decode_statics(const TranslatedSam std::vector<D3D12_STATIC_SAMPLER_DESC> statics; for (UINT i = 0; i < samplers.statics.size(); ++i) statics.push_back(decode_sampler(samplers.statics[i], i, i < samplers.comparison.size() && samplers.comparison[i], - i < samplers.lod_limits.size() && samplers.lod_limits[i])); + i < samplers.lod_limits.size() && samplers.lod_limits[i], sampler_lod_fields_on())); return statics; } @@ -187,21 +238,26 @@ inline SamplerSnapshot snapshot_samplers(SamplerSource source, bool reserved_fal return snapshot; } -inline D3D12_SAMPLER_DESC dynamic_sampler(const SamplerWords& words) +inline D3D12_SAMPLER_DESC dynamic_sampler(const SamplerWords& words, bool lod_fields = sampler_lod_fields_on()) { - // A heap entry is the title's own descriptor, so its MIN_LOD, MAX_LOD (#2221) and fixed border color apply. - const auto s = decode_sampler(words, 0, false, true); - const float rgb = s.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE ? 1.0f : 0.0f; - const float alpha = (s.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE || - s.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK) ? 1.0f : 0.0f; - return {s.Filter, s.AddressU, s.AddressV, s.AddressW, s.MipLODBias, s.MaxAnisotropy, s.ComparisonFunc, - {rgb, rgb, rgb, alpha}, s.MinLOD, s.MaxLOD}; + // A heap entry is the title's own descriptor, so its MIN_LOD and MAX_LOD apply (#2221). LOCAL: with + // X2W_SAMPLER_LOD the bias and border fields too (the LOD limits still override MIN_LOD / MAX_LOD). + const auto s = decode_sampler(words, 0, false, true, lod_fields); + D3D12_SAMPLER_DESC d{s.Filter, s.AddressU, s.AddressV, s.AddressW, s.MipLODBias, s.MaxAnisotropy, s.ComparisonFunc, + {}, s.MinLOD, s.MaxLOD}; + if (lod_fields) { + const float rgb = s.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE ? 1.0f : 0.0f; + const float alpha = s.BorderColor == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK ? 0.0f : 1.0f; + d.BorderColor[0] = d.BorderColor[1] = d.BorderColor[2] = rgb; + d.BorderColor[3] = alpha; + } + return d; } inline D3D12_SAMPLER_DESC border_sampler() { // Not a title descriptor: its zero word 1 is not a LOD clamp, so the full mip range stays available. - auto s = dynamic_sampler({6u | (6u << 3) | (6u << 6), 0, 0, 0}); + auto s = dynamic_sampler({6u | (6u << 3) | (6u << 6), 0, 0, 0}, false); s.MaxLOD = D3D12_FLOAT32_MAX; return s; } diff --git a/src/startup_stubs/trap.h b/src/startup_stubs/trap.h index 150686eed5..31d997152e 100644 --- a/src/startup_stubs/trap.h +++ b/src/startup_stubs/trap.h @@ -36,6 +36,46 @@ inline void write_all(HANDLE handle, const char* text, DWORD length) noexcept WriteFile(handle, text, length, &written, nullptr); } +inline void append_trap_log(const char* text, DWORD length) noexcept +{ + const DWORD error = GetLastError(); + wchar_t path[MAX_PATH]; + const DWORD path_length = GetEnvironmentVariableW(L"X2W_TRAP_LOG", path, MAX_PATH); + const bool usable = path_length && path_length < MAX_PATH; + static const bool reopen = [] { + char value[4]{}; + return GetEnvironmentVariableA("X2W_TRAP_LOG_REOPEN", value, sizeof(value)) && value[0] == '1'; + }(); + if (reopen) { + if (usable) { + HANDLE out = CreateFileW(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (out != INVALID_HANDLE_VALUE) { + write_all(out, text, length); + CloseHandle(out); + } + } + SetLastError(error); + return; + } + static SRWLOCK lock = SRWLOCK_INIT; + static HANDLE handle = INVALID_HANDLE_VALUE; + static wchar_t open_path[MAX_PATH]; + AcquireSRWLockExclusive(&lock); + if (handle != INVALID_HANDLE_VALUE && (!usable || std::wcscmp(path, open_path) != 0)) { + CloseHandle(handle); + handle = INVALID_HANDLE_VALUE; + } + if (handle == INVALID_HANDLE_VALUE && usable) { + handle = CreateFileW(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle != INVALID_HANDLE_VALUE) std::wmemcpy(open_path, path, path_length + 1); + } + write_all(handle, text, length); + ReleaseSRWLockExclusive(&lock); + SetLastError(error); +} + // Switch: %X2W_TRAP_CONTINUE% lists export names (comma-separated, or *) whose // trap logs the call with "x2w-continue" and returns 0 instead of terminating. Off when unset. inline bool listed(const char* variable, const char* name) noexcept diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index d3cbc51986..b3229887e1 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -257,6 +257,9 @@ extern "C" __declspec(noinline) long XApuConnect(u64 rcx, u64 rdx, u64 r8, u64 r ReleaseSRWLockExclusive(&connection_lock); *reinterpret_cast<void**>(rdx) = buffer; *reinterpret_cast<void**>(r8) = reinterpret_cast<void*>(handle); +#ifdef X2W_HAVE_OPUS + x2w_local::logf("x2w-audio XApu decoder=%s typed_completions=%d", opus_get_version_string(), typed_completions()); +#endif x2w_local::logf("x2w-audio XApuConnect input=[%s] output(before)=[%s] -> handle %p, buffer %p (0x%x bytes), S_OK", input, output, reinterpret_cast<void*>(handle), buffer, buffer_bytes); return hr_ok; @@ -352,7 +355,14 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 } if (hr == hr_ok) { place_result(*conn, entry); - if (pcm) std::memcpy(dest, pcm, entry.value); + if (pcm) { + std::memcpy(dest, pcm, entry.value); + static bool logged_decode = false; + if (!logged_decode) { + logged_decode = true; + x2w_local::logf("x2w-audio XApu first Opus packet decoded slot=%u pcm_bytes=%u", entry.slot, entry.value); + } + } } #else hr = push_result(*conn, entry) ? hr_ok : hr_out_of_memory; diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index a6d013a71a..046dbf8c1b 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -14,6 +14,11 @@ #include "startup_stubs/dstorage_error_record.h" #include "startup_stubs/dstorage_file_read.h" #include "startup_stubs/bcpack_decoder.h" +#include "startup_stubs/bcpack_bc6h.h" +#include "startup_stubs/dstorage_status_stats.h" +#include <algorithm> +#include <memory> +#include <map> #include <psapi.h> @@ -62,6 +67,7 @@ struct Object { struct QueueWork* work = nullptr; // Queue: entries waiting for Submit and the worker running them struct Unrecorded* unrecorded_head = nullptr; // Queue: entries no queue storage could hold, see push() struct Unrecorded* unrecorded_tail = nullptr; + x2w_dstorage_stats::StatusStats* stats = nullptr; // StatusArray: LOCAL wait diagnostics (dstorage_status_stats.h) }; struct FileObject : Object { @@ -97,6 +103,7 @@ struct Entry { u64 id = 0; u64 submission_id = 0; u64 after = 0; // failing: entries the worker must have finished before this one completes + LONG status_gen = 0; // status entry: its EnqueueStatus generation (dstorage_status_stats.h) }; struct CachedStream { u64 source = 0; @@ -123,6 +130,9 @@ struct QueueWork { u64 next_submission_id = 0; static constexpr std::size_t max_cached_streams = 16; std::deque<CachedStream> cached_streams; + // LOCAL: the latest request this queue served per options value (8 values, worker only), for FAIL lines. + struct Served { bool used; unsigned char bytes[0x48]; } served[8] = {}; + unsigned served_next = 0; void put_stream(u64 source, u64 base_offset, unsigned compressed_size, unsigned chunk_size, std::vector<u64> continuation_ids, std::vector<unsigned char> data) @@ -178,6 +188,73 @@ static bool destination_writable(const void* destination, std::size_t bytes) return true; } +static volatile LONG destination_served_after_wait = 0, destination_dropped = 0; + +static ULONG destination_wait_ms() noexcept +{ + static const ULONG value = [] { + char text[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_DSTORAGE_DEST_WAIT_MS", text, sizeof(text)); + return n && n < sizeof(text) ? static_cast<ULONG>(std::strtoul(text, nullptr, 10)) : 250ul; + }(); + return value; +} + +static void log_unwritable(const char* what, const void* destination, std::size_t capacity, ULONG waited, LONG n) +{ + using PageEvent = BOOL(WINAPI*)(const void*, ULONG*, ULONG64*, ULONG*, ULONG64*, ULONG64*, ULONG64*); + static const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + static const auto page_event = xmem ? reinterpret_cast<PageEvent>(GetProcAddress(xmem, "x2w_xmem_page_event")) : nullptr; + const auto start = reinterpret_cast<std::uintptr_t>(destination); + std::uintptr_t bad = start; // the first unwritable page now (for a served read: none, the start is shown) + for (std::uintptr_t at = start & ~std::uintptr_t{0xFFFF}; at < start + capacity; at += 0x10000) { + const std::uintptr_t from = at < start ? start : at; + const std::uintptr_t to = at + 0x10000 < start + capacity ? at + 0x10000 : start + capacity; + if (!destination_writable(reinterpret_cast<const void*>(from), to - from)) { + bad = from; + break; + } + } + MEMORY_BASIC_INFORMATION info{}; + VirtualQuery(reinterpret_cast<const void*>(bad), &info, sizeof(info)); + ULONG kind = 0, thread = 0; + ULONG64 page = 0, age = 0, serial = 0, remaps = 0; + const BOOL view = page_event ? page_event(reinterpret_cast<const void*>(bad), &kind, &page, &thread, &age, &serial, &remaps) + : FALSE; + x2w_local::logf("x2w-dstorage destination %p+0x%zx %s after %lu ms (#%ld; wait bound %lu ms, " + "X2W_DSTORAGE_DEST_WAIT_MS): page %p state 0x%lx type 0x%lx protect 0x%lx allocation %p | xmem: %s, " + "last event %s page 0x%llx thread %lu %llu ms ago (step %llu), %llu remaps so far", + destination, capacity, what, waited, n, destination_wait_ms(), reinterpret_cast<void*>(bad), info.State, + info.Type, info.Protect, info.AllocationBase, + !page_event ? "no x2w_xmem_page_event" : view ? "view recorded" : "no view recorded", + kind == 1 ? "map" : kind == 2 ? "UNMAP" : "none (never mapped or unmapped by xmem)", + static_cast<unsigned long long>(page), thread, static_cast<unsigned long long>(age), + static_cast<unsigned long long>(serial), static_cast<unsigned long long>(remaps)); +} + +// Writes bytes of data to the title's destination (capacity bytes must be writable). False: nothing written. +static bool write_destination(void* destination, const void* data, std::size_t bytes, std::size_t capacity) +{ + using WriteWait = BOOL(WINAPI*)(void*, const void*, SIZE_T, SIZE_T, ULONG, ULONG*); + static const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + static const auto write_wait = + xmem ? reinterpret_cast<WriteWait>(GetProcAddress(xmem, "x2w_xmem_write_settled_wait")) : nullptr; + if (!write_wait) { + if (!destination_writable(destination, capacity)) return false; + std::memcpy(destination, data, bytes); + return true; + } + ULONG waited = 0; + if (write_wait(destination, data, bytes, capacity, 0, &waited)) return true; + if (write_wait(destination, data, bytes, capacity, destination_wait_ms(), &waited)) { + const LONG n = InterlockedIncrement(&destination_served_after_wait); + if (n <= 16 || (n & (n - 1)) == 0) log_unwritable("was not writable, SERVED after a wait", destination, capacity, waited, n); + return true; + } + log_unwritable("stays NOT writable, read dropped", destination, capacity, waited, InterlockedIncrement(&destination_dropped)); + return false; +} + // Return the exact queued requests that continue this stream in this submission, in queue order. // Status entries and requests for unrelated files are skipped. In the same file, any non-matching // size, non-consecutive offset, or submission boundary ends the continuation chain (Refs #1136, #1144, #1198, #1214). @@ -237,7 +314,7 @@ void log(const char* format, ...) line[n++] = '\r'; line[n++] = '\n'; x2w_trap::write_all(GetStdHandle(STD_ERROR_HANDLE), line, static_cast<DWORD>(n)); - x2w_trap::append_log(line, static_cast<DWORD>(n), false); + x2w_trap::append_trap_log(line, static_cast<DWORD>(n)); // one open handle per module (trap.h) } void guid_text(const void* guid, char* out, std::size_t size) @@ -343,6 +420,7 @@ long __stdcall factory_create_status_array(Object*, unsigned capacity, const cha // Win32 implementation of this API (Xbox-GDK-Samples, MIT: SimpleDirectStorageCombo/DirectStorageWin32/ // DirectStorageWin32WrapperStatusArray.cpp). A caller may poll IsComplete before a slot's first use. for (unsigned i = 0; i < capacity; ++i) object->results[i] = S_OK; + object->stats = x2w_dstorage_stats::make(capacity, object->results); *out = object; return S_OK; } @@ -399,6 +477,63 @@ long __stdcall file_information(Object* self, BY_HANDLE_FILE_INFORMATION* info) // synchronously; compressed ones are logged and left undone. The first requests are logged in full. LONG requests_done, requests_compressed, requests_failed, requests_bcpack_blank; +// LOCAL: BC6H (BCPack format 6) is zero-filled unless X2W_BC6H_FALLBACK=1. With it, streams go through +// bcpack_bc6h.h: blocks free of the format's dictionary (unknown) are rebuilt, the rest get the +// endpoints of the nearest known block or a constant (approximate texels, never exact); =2 uses the +// constant for every unknown-endpoint block (no copying). X2W_BC6H_FILL_BASE (decimal, +// mode-13 base, default 16913 = UF16 2^-7) sets the constant; 0 gives zero blocks. +char bc6h_fallback_mode() { + static const char mode = [] { + char value[8] = {}; + return GetEnvironmentVariableA("X2W_BC6H_FALLBACK", value, sizeof(value)) ? value[0] : '0'; + }(); + return mode; +} + +bool bc6h_fallback_enabled() { return bc6h_fallback_mode() == '1' || bc6h_fallback_mode() == '2'; } + +volatile LONG64 bc6h_blocks, bc6h_exact, bc6h_endpoints_only, bc6h_copied, bc6h_constant; +LONG bc6h_streams; + +bool decode_bc6h_fallback(const unsigned char* input, std::size_t size, unsigned char* out, std::size_t out_size, + std::size_t* produced) { + static const uint16_t fill = [] { + char value[16] = {}; + if (!GetEnvironmentVariableA("X2W_BC6H_FILL_BASE", value, sizeof(value))) return x2w_bcpack::bc6h::DEFAULT_FILL_BASE; + return static_cast<uint16_t>(std::strtoul(value, nullptr, 10)); + }(); + x2w_bcpack::bc6h::Stats st; + if (!x2w_bcpack::bc6h::decode_stream(input, size, out, out_size, produced, &st, nullptr, fill, + bc6h_fallback_mode() != '2')) return false; + InterlockedAdd64(&bc6h_blocks, static_cast<LONG64>(st.blocks)); + InterlockedAdd64(&bc6h_exact, static_cast<LONG64>(st.exact)); + InterlockedAdd64(&bc6h_endpoints_only, static_cast<LONG64>(st.endpoints_only)); + InterlockedAdd64(&bc6h_copied, static_cast<LONG64>(st.copied)); + InterlockedAdd64(&bc6h_constant, static_cast<LONG64>(st.constant)); + const LONG n = InterlockedIncrement(&bc6h_streams); + if (x2w_local::first_of(n, 16) || (n & 63) == 0) + log("x2w-dstorage BC6H fallback: stream %ld blocks %zu exact %zu endpoints-only %zu copied %zu constant %zu " + "(totals: blocks %lld exact %lld endpoints-only %lld copied %lld constant %lld)", + n, st.blocks, st.exact, st.endpoints_only, st.copied, st.constant, bc6h_blocks, bc6h_exact, + bc6h_endpoints_only, bc6h_copied, bc6h_constant); + return true; +} +// LOCAL: failed requests by outcome text (outcomes are string literals), for the heartbeat. +struct FailureTally { const char* outcome; LONG count; }; +FailureTally failure_tally[16]; +SRWLOCK failure_lock = SRWLOCK_INIT; +void tally_failure(const char* outcome) +{ + AcquireSRWLockExclusive(&failure_lock); + for (auto& t : failure_tally) { + if (!t.outcome || t.outcome == outcome || std::strcmp(t.outcome, outcome) == 0) { + t.outcome = outcome; + ++t.count; + break; + } + } + ReleaseSRWLockExclusive(&failure_lock); +} // Failed requests by cause, for the heartbeat (#1198). Each failure site names its cause and // count_failure adds it to requests_failed as well, so the causes add up to that total. "other" holds // the failures without a cause of their own: unknown option bits, page grants and page writes, a page @@ -547,8 +682,161 @@ int format_page_ends(char* out, std::size_t size, int second, const PageEndCount second, n[0][0], n[0][1], n[1][0], n[1][1], n[2][0], n[2][1]); } -LONG bcpack_requests[16], bcpack_blank[16]; LONG zero_tokens_at_enqueue, zero_tokens_at_run, tokens_replaced_after_enqueue; +// Archives of one kind (an RDS5 boundary table at file offset 0) are addressed by the executable 14 x 64 KiB +// after where their data sits on disk (measured on one executable: every shifted zlib stream starts exactly +// at a table boundary 0xE0000 before the requested offset, and pieces in the last 0xE0000 bytes point past +// the end of the file). Why the executable adds the shift is not known. A request is read from the shifted +// offset when the table has a boundary there and none at the requested offset, or when only the shifted +// range fits in the file. LOCAL SHORTCUT until the offset arithmetic is understood. +struct Rds5Boundary { u64 stored, logical; unsigned codec, padding; }; +const std::vector<Rds5Boundary>* rds5_table(HANDLE handle) +{ + static std::mutex lock; + static std::map<HANDLE, std::unique_ptr<std::vector<Rds5Boundary>>> tables; + const std::lock_guard guard(lock); + auto& slot = tables[handle]; + if (slot) return slot->empty() ? nullptr : slot.get(); + slot = std::make_unique<std::vector<Rds5Boundary>>(); + const auto read_at = [handle](u64 at, void* out, DWORD size) { + OVERLAPPED overlapped{}; + overlapped.Offset = static_cast<DWORD>(at); + overlapped.OffsetHigh = static_cast<DWORD>(at >> 32); + DWORD read = 0; + return ReadFile(handle, out, size, &read, &overlapped) && read == size; + }; + unsigned char header[16]; + if (!read_at(0, header, 16) || std::memcmp(header, "RDS5", 4) != 0) return nullptr; + std::uint32_t count = 0; + std::memcpy(&count, header + 4, 4); + if (count < 2 || count > (1u << 20)) return nullptr; + std::vector<std::uint32_t> raw(std::size_t{count} * 2); + if (!read_at(16, raw.data(), count * 8)) return nullptr; + slot->reserve(count); + for (std::uint32_t i = 0; i < count; ++i) { + const std::uint32_t low = raw[2 * i], high = raw[2 * i + 1]; + slot->push_back({u64{low & 0x03ffffffu} * 256, (u64{high & 0xfffffu} * 4 + (low >> 30)) * 4096, (low >> 26) & 15, high >> 20}); + } + return slot.get(); +} +LONG requests_archive_shifted, requests_archive_past_end; +u64 archive_read_offset(HANDLE handle, u64 offset, unsigned size) +{ + static const bool enabled = x2w_local::env_on("X2W_DSTORAGE_ARCHIVE_SHIFT"); + constexpr u64 shift = 14 * 0x10000; + if (!enabled || offset < shift) return offset; + LARGE_INTEGER file_size{}; + if (!GetFileSizeEx(handle, &file_size)) return offset; + const u64 end = static_cast<u64>(file_size.QuadPart); + const bool fits = offset + size <= end, shifted_fits = offset - shift + size <= end; + if (!fits && shifted_fits) { + InterlockedIncrement(&requests_archive_past_end); + return offset - shift; + } + const auto* table = rds5_table(handle); + if (!table || !shifted_fits) return offset; + const auto boundary = [&](u64 at) { + const auto it = std::lower_bound(table->begin(), table->end(), at, [](const Rds5Boundary& b, u64 v) { return b.stored < v; }); + return it != table->end() && it->stored == at; + }; + if (boundary(offset - shift) && !boundary(offset)) { + InterlockedIncrement(&requests_archive_shifted); + return offset - shift; + } + return offset; +} + +struct Rds5Slice { u64 stored; std::size_t decoded_size, at; }; +LONG requests_interval_slices; +bool rds5_slice(HANDLE handle, u64 offset, unsigned compressed, unsigned destination_size, unsigned codec, Rds5Slice& slice) +{ + const auto* table = rds5_table(handle); + if (!table || !compressed || !destination_size) return false; + auto it = std::upper_bound(table->begin(), table->end(), offset, [](u64 v, const Rds5Boundary& b) { return v < b.stored; }); + for (int steps = 0; it != table->begin() && steps < 0x10000; ++steps) { + --it; + const u64 at = offset - it->stored; + if (at >= (64u << 20)) break; + if (it + 1 == table->end()) continue; + const u64 span = (it + 1)->stored - it->stored, decoded = (it + 1)->logical - it->logical; + if (it->codec != codec || span <= it->padding || span - it->padding != compressed) continue; + // A request for the whole interval already works below (and must not evict cached streams). + if (at + destination_size > decoded || (!at && destination_size == decoded)) return false; + slice ={it->stored, static_cast<std::size_t>(decoded), static_cast<std::size_t>(at)}; + return true; + } + return false; +} + +// LOCAL: multi-piece zlib streams across queues and submissions (measured on one executable). One +// stream that inflates to several destination-sized pieces is enqueued as one request per piece; +// every piece names the same compressed size and piece k's offset is the stream's offset plus k +// times the destination size. The continuation cache above only covers pieces queued in the same +// submission on the same queue. Pieces that miss it are served from a shared cache of recently +// inflated streams, or by finding the stream start on disk (offset - k * piece, a zlib header, and a +// full Adler-checked inflate past piece k). +LONG requests_stream_pieces, requests_pieces_found_on_disk; +bool stream_pieces_enabled() +{ + static const bool on = x2w_local::env_on("X2W_DSTORAGE_STREAM_PIECES"); + return on; +} +struct InflatedStream { u64 source, base; unsigned compressed; std::shared_ptr<const std::vector<unsigned char>> data; }; +std::mutex streams_lock; +std::deque<InflatedStream> streams; +void remember_stream(u64 source, u64 base, unsigned compressed, std::shared_ptr<const std::vector<unsigned char>> data) +{ + const std::lock_guard guard(streams_lock); + streams.push_front({source, base, compressed, std::move(data)}); + if (streams.size() > 16) streams.pop_back(); +} +std::shared_ptr<const std::vector<unsigned char>> remembered_stream(u64 source, u64 base, unsigned compressed) +{ + const std::lock_guard guard(streams_lock); + for (const InflatedStream& s : streams) + if (s.source == source && s.base == base && s.compressed == compressed) return s.data; + return nullptr; +} +bool find_stream(u64 source, u64 offset, unsigned compressed, unsigned piece, std::shared_ptr<const std::vector<unsigned char>>& data, u64& base) +{ + const std::lock_guard guard(streams_lock); + for (const InflatedStream& s : streams) { + if (s.source != source || s.compressed != compressed || offset <= s.base || !piece) continue; + const u64 at = offset - s.base; + if (at % piece || at >= s.data->size()) continue; + data = s.data; + base = s.base; + return true; + } + return false; +} +std::shared_ptr<const std::vector<unsigned char>> stream_on_disk(HANDLE handle, u64 offset, unsigned compressed, unsigned piece, u64& base) +{ + if (!piece || compressed > (64u << 20)) return nullptr; + const auto read_at = [handle](u64 at, unsigned char* out, unsigned size) { + OVERLAPPED overlapped{}; + overlapped.Offset = static_cast<DWORD>(at); + overlapped.OffsetHigh = static_cast<DWORD>(at >> 32); + DWORD read = 0; + return ReadFile(handle, out, size, &read, &overlapped) && read == size; + }; + std::vector<unsigned char> packed; + for (u64 k = 1; k <= 64 && k * piece <= offset; ++k) { + const u64 at = offset - k * piece; + unsigned char head[2]; + if (!read_at(at, head, 2) || head[0] != 0x78 || ((head[0] << 8) | head[1]) % 31) continue; + packed.resize(compressed); + if (!read_at(at, packed.data(), compressed)) continue; + std::vector<unsigned char> big(std::min<std::size_t>(std::size_t{32} << 20, std::max<std::size_t>(std::size_t{4} << 20, std::size_t{piece} * (k + 64)))); + std::size_t produced = 0; + if (!x2w_inflate::inflate_zlib(packed.data(), compressed, big.data(), big.size(), &produced) || produced <= k * piece) continue; + base = at; + return std::make_shared<const std::vector<unsigned char>>(big.begin(), big.begin() + produced); + } + return nullptr; +} + +LONG bcpack_requests[16], bcpack_blank[16]; const char* format_counts(char* out, std::size_t size, LONG* counts) { @@ -628,10 +916,19 @@ static bool try_serve_cached_continuation(Object* self, u64 source, u64 offset, return false; } +// Per-worker batches keep independent queues and long idle intervals out of the timings. +struct StorageRequestTimes { + unsigned count = 0; + LONG64 lookup = 0, read = 0, decode = 0, write = 0; +}; + void execute_request(Object* self, const unsigned char* request, const ULONG_PTR* tokens, u64 entry_id, u64 submission_id) { X2W_ZONE("DirectStorage request"); if (!request) return; + static const bool time_requests = x2w_local::env_on("X2W_DSTORAGE_TIMING"); + const LONG64 began = time_requests ? x2w_dstorage_stats::now() : 0; + LONG64 lookup_end = began, read_end = began, decode_end = began; const u64 options = *reinterpret_cast<const u64*>(request); auto* const destination = *reinterpret_cast<unsigned char* const*>(request + 0x08); const unsigned destination_size = *reinterpret_cast<const unsigned*>(request + 0x18); @@ -663,6 +960,8 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR std::size_t decode_length = source_size; const std::size_t destination_capacity = destination_size; bool written = false; + bool interval_request = false; + Rds5Slice slice{}; if (options & ~known) { outcome = "unknown option bits, not done"; @@ -672,8 +971,15 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR input = reinterpret_cast<const unsigned char*>(source); } else { auto* file_object = reinterpret_cast<Object*>(source); + // A zlib or a decoded BCPack format, not both (the table has one codec per interval). + const unsigned codec = zlib ? (bcpack ? 0u : 8u) + : (bcpack == 7 || bcpack == 1 || (bcpack >= 3 && bcpack <= 5) || + (bcpack == 6 && bc6h_fallback_enabled()) ? bcpack : 0u); + interval_request = codec && file_object && file_object->kind == file && + rds5_slice(file_object->handle, offset, source_size, destination_size, codec, slice); + if (time_requests) lookup_end = x2w_dstorage_stats::now(); if (file_object && file_object->kind == file && - x2w_startup::read_storage_file(file_object->handle, offset, source_size, packed)) + x2w_startup::read_storage_file(file_object->handle, interval_request ? slice.stored : archive_read_offset(file_object->handle, offset, source_size), source_size, packed)) input = packed.data(); else { outcome = "read failed"; @@ -681,9 +987,36 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR } } + if (time_requests) read_end = decode_end = x2w_dstorage_stats::now(); if (input) { data = input; - if (zlib) { + if (interval_request) { + // LOCAL: decode the whole interval to its logical size once (kept for its other pieces), then + // serve this request's slice of it (see rds5_slice). + std::shared_ptr<const std::vector<unsigned char>> whole = remembered_stream(source, slice.stored, source_size); + if (!whole || whole->size() != slice.decoded_size) { + whole = nullptr; + auto decoded = std::make_shared<std::vector<unsigned char>>(slice.decoded_size); + std::size_t produced = 0; + const bool ok = zlib ? x2w_inflate::inflate_zlib(input, source_size, decoded->data(), decoded->size(), &produced) + : bcpack == 6 ? decode_bc6h_fallback(input, source_size, decoded->data(), decoded->size(), &produced) + : x2w_bcpack::decode_bcpack(input, source_size, bcpack, decoded->data(), decoded->size(), &produced); + if (ok && produced == decoded->size()) { + whole = std::move(decoded); + remember_stream(source, slice.stored, source_size, whole); + } + } + if (whole) { + output.assign(whole->begin() + slice.at, whole->begin() + slice.at + destination_size); + data = output.data(); + decode_length = destination_size; + outcome = zlib ? "inflated (RDS5 interval slice)" : "bcpack decoded (RDS5 interval slice)"; + InterlockedIncrement(&requests_interval_slices); + } else { + outcome = zlib ? "zlib failed (RDS5 interval)" : "bcpack failed (RDS5 interval)"; + data = nullptr; + } + } else if (zlib) { bool direct_decoded = false; bool decode_error = false; if (has_zlib_header(input, source_size)) { @@ -733,6 +1066,16 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR cached_chunked = true; } } + if (!cached_chunked && !memory_source && !bcpack && produced > destination_size && stream_pieces_enabled()) { + // LOCAL: piece 0 of a multi-piece stream whose other pieces are not in this + // submission: keep the whole stream for them and serve this piece's slice. + remember_stream(source, offset, source_size, std::make_shared<const std::vector<unsigned char>>(output)); + decode_length = destination_size; + data = output.data(); + outcome = "inflated (stream piece 0, shared cache)"; + InterlockedIncrement(&requests_stream_pieces); + cached_chunked = true; + } if (!cached_chunked) { decode_length = produced; data = output.data(); @@ -757,6 +1100,30 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR } } + if (!direct_decoded && !decode_error && !memory_source && !bcpack && stream_pieces_enabled()) { + // LOCAL: a later piece that missed the submission's cache (see remember_stream). Not for a + // request whose own bytes start a zlib stream that failed to decode: that is a damaged + // stream, and it fails like on the queue-cache path above. + std::shared_ptr<const std::vector<unsigned char>> whole; + u64 base = 0; + auto* file_object = reinterpret_cast<Object*>(source); + const bool from_file = file_object && file_object->kind == file && file_object->handle != INVALID_HANDLE_VALUE; + if (find_stream(source, offset, source_size, destination_size, whole, base)) { + } else if (from_file && (whole = stream_on_disk(file_object->handle, offset, source_size, destination_size, base))) { + remember_stream(source, base, source_size, whole); + InterlockedIncrement(&requests_pieces_found_on_disk); + } + if (whole) { + const std::size_t at = static_cast<std::size_t>(offset - base); + const std::size_t take = std::min<std::size_t>(destination_size, whole->size() - at); + output.assign(whole->begin() + at, whole->begin() + at + take); + data = output.data(); + decode_length = take; + outcome = "inflated (stream piece)"; + InterlockedIncrement(&requests_stream_pieces); + direct_decoded = true; + } + } if (!direct_decoded) { outcome = "zlib failed"; failure = StorageFailure::zlib; @@ -772,31 +1139,49 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR } } if (input) { - bool bcpack_decoded = false; - if (data && bcpack) { - if (bcpack == 7 || bcpack == 1 || bcpack == 4 || bcpack == 5 || bcpack == 3) { - std::vector<unsigned char> decoded(destination_size); - std::size_t produced = 0; - if (x2w_bcpack::decode_bcpack(data, decode_length, bcpack, decoded.data(), decoded.size(), &produced)) { - output = std::move(decoded); - data = output.data(); - decode_length = produced; - outcome = zlib ? "inflated + bcpack decoded" : "bcpack decoded"; - bcpack_decoded = true; - } else { - outcome = "bcpack failed"; - failure = StorageFailure::bcpack; - data = nullptr; - } + bool bcpack_decoded = interval_request && data; + if (data && bcpack && !interval_request) { + // BC3/BC4/BC5 (3-5) decode since 42cd462f; a failure there zero-fills as before (counted as + // bcpack-blank), because a failed request has crashed the title and a blank texture has not. + // BC6H (6) only with X2W_BC6H_FALLBACK=1; a failure zero-fills like BC3-5. + const bool bc6h = bcpack == 6 && bc6h_fallback_enabled(); + const bool bcn_fallback = (bcpack >= 3 && bcpack <= 5) || bc6h; + std::vector<unsigned char> decoded; + std::size_t produced = 0; + const bool tried = bcpack == 7 || bcpack == 1 || bcn_fallback; + const bool ok = tried && (decoded.resize(destination_size), + bc6h ? decode_bc6h_fallback(data, decode_length, decoded.data(), decoded.size(), &produced) + : x2w_bcpack::decode_bcpack(data, decode_length, bcpack, decoded.data(), decoded.size(), &produced)); + if (ok) { + output = std::move(decoded); + data = output.data(); + decode_length = produced; + outcome = zlib ? "inflated + bcpack decoded" : "bcpack decoded"; + bcpack_decoded = true; + } else if (tried && !bcn_fallback) { + outcome = "bcpack failed"; + failure = StorageFailure::bcpack; + data = nullptr; } else { + if (bcn_fallback) { + static LONG bcn_failed; + if (x2w_local::first_calls(bcn_failed, 16)) + log("x2w-dstorage BCPack format %u decode failed: zero-filled as before (dest_size=0x%x offset=0x%llx size=0x%x)", + bcpack, destination_size, offset, source_size); + } // shortcut for formats not decoded yet: texels are left zero (a blank texture) so the // title's loading continues. Counted as bcpack_blank. output.assign(destination_size, 0); data = output.data(); decode_length = destination_size; outcome = "BCPack not decoded: zero-filled"; + static LONG blank_logged; + if (x2w_local::first_calls(blank_logged, 16)) + log("x2w-dstorage BCPack format %u not decoded: zero-filled (options=0x%llx dest_size=0x%x offset=0x%llx size=0x%x)", + bcpack, options, destination_size, offset, source_size); } } + if (time_requests) decode_end = x2w_dstorage_stats::now(); if (data) { // Track decode length and destination capacity as separate values (Refs #1144). // A short destination or missing/insufficient page grant must fail the request @@ -843,8 +1228,8 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR // The title's destination can be smaller in memory than its declared capacity (#870: // a write fault inside this copy). Judge the whole declared capacity before the first // byte is written, so a refusal leaves every page untouched. - if (destination_writable(destination, destination_capacity)) { - std::memcpy(destination, data, decode_length); + if (write_destination(destination, data, decode_length, destination_capacity)) { + // written (through xmem's locked write when available) } else { outcome = "destination not writable"; failure = StorageFailure::destination_not_writable; @@ -864,16 +1249,69 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR } } } + if (time_requests) { + thread_local StorageRequestTimes batch; + batch.lookup += lookup_end - began; + batch.read += read_end - lookup_end; + batch.decode += decode_end - read_end; + batch.write += x2w_dstorage_stats::now() - decode_end; + if (++batch.count == 256) { + log("x2w-dstorage timing queue=%p requests=%u total ms: lookup=%.2f read=%.2f decode=%.2f write=%.2f", + static_cast<void*>(self), batch.count, x2w_dstorage_stats::ms(batch.lookup), + x2w_dstorage_stats::ms(batch.read), x2w_dstorage_stats::ms(batch.decode), x2w_dstorage_stats::ms(batch.write)); + batch = {}; + } + } const bool empty = std::strcmp(outcome, "empty") == 0; const bool failed = (data == nullptr || !written) && !empty; const HRESULT result = failure_result(failure); if (failed) count_failure(failure, self, request, result); + if (failed) tally_failure(outcome); if (!empty) count_page_request(request, failed); if (failed && self) InterlockedExchange(&self->pending, static_cast<LONG>(result)); - static LONG summaries, failures; + static LONG summaries, failures; // upstream: the first twelve failures are logged as well if (x2w_local::first_calls(summaries, 12) || (failed && x2w_local::first_calls(failures, 12))) log("x2w-dstorage options=0x%llx dest=%p dest_size=0x%x source=0x%llx offset=0x%llx size=0x%x -> %s", options, static_cast<void*>(destination), destination_size, source, offset, source_size, outcome); + if (failed) { + // LOCAL: every failure, one line, with the source file's path, for offline analysis. + wchar_t path[300] = L"memory"; + LARGE_INTEGER file_size{}; + file_size.QuadPart = -1; + auto* file_object = reinterpret_cast<Object*>(source); + if (!(options & 0x400000) && file_object && x2w_local::readable(file_object, sizeof(Object)) && file_object->kind == file && + file_object->handle != INVALID_HANDLE_VALUE) { + if (!GetFinalPathNameByHandleW(file_object->handle, path, 300, FILE_NAME_NORMALIZED)) std::wcscpy(path, L"?"); + if (!GetFileSizeEx(file_object->handle, &file_size)) file_size.QuadPart = -1; + } + const u64* words = reinterpret_cast<const u64*>(request); + // The whole 0x48-byte request as enqueued, so a refused request can be compared field by field + // with served ones of the same options (the two garbage-size requests of every run). + char bytes[3 * 0x48 + 1] = ""; + for (int i = 0; i < 0x48; ++i) std::snprintf(bytes + 3 * i, 4, "%02x ", request[i]); + log("x2w-dstorage FAIL options=0x%llx dest_size=0x%x offset=0x%llx size=0x%x outcome=\"%s\" file=\"%ls\" file_size=0x%llx +10=0x%llx +38=0x%llx +40=0x%llx bytes=[%s]", options, + destination_size, offset, source_size, outcome, path, static_cast<unsigned long long>(file_size.QuadPart), words[2], words[7], words[8], bytes); + if (self && self->work) { + for (const auto& served : self->work->served) { + if (!served.used || std::memcmp(served.bytes, request, 8) != 0) continue; + for (int i = 0; i < 0x48; ++i) std::snprintf(bytes + 3 * i, 4, "%02x ", served.bytes[i]); + log("x2w-dstorage the queue's latest served request with the same options: [%s]", bytes); + } + } + } else if (self && self->work && std::strcmp(outcome, "empty") != 0) { + QueueWork& work = *self->work; + QueueWork::Served* slot = nullptr; + for (auto& served : work.served) + if (served.used && std::memcmp(served.bytes, request, 8) == 0) slot = &served; + if (!slot) slot = &work.served[work.served_next++ % 8]; + std::memcpy(slot->bytes, request, sizeof slot->bytes); + slot->used = true; + } + static LONG slices_logged; + if (interval_request && slice.at && x2w_local::first_calls(slices_logged, 32)) + log("x2w-dstorage RDS5 slice options=0x%llx dest_size=0x%x offset=0x%llx size=0x%x: interval 0x%llx decoded 0x%zx at 0x%zx +10=0x%llx -> %s", + options, destination_size, offset, source_size, slice.stored, slice.decoded_size, slice.at, + *reinterpret_cast<const u64*>(request + 0x10), outcome); } void signal_fence(void* fence, u64 value); @@ -893,6 +1331,7 @@ void run_entry(Object* self, Entry& entry) if (!title || !x2w_local::readable(title, bytes)) { count_failure(StorageFailure::other, self, entry.bytes); count_page_request(entry.bytes, true); + tally_failure("page array unreadable"); if (self) InterlockedExchange(&self->pending, static_cast<LONG>(E_FAIL)); static LONG unreadable; if (x2w_local::first_calls(unreadable, 12)) @@ -911,6 +1350,7 @@ void run_entry(Object* self, Entry& entry) execute_request(self, entry.bytes, entry.token_count ? entry.tokens.get() : nullptr, entry.id, entry.submission_id); } else if (entry.type == Entry::status_entry) { const LONG result = InterlockedExchange(&self->pending, S_OK); + x2w_dstorage_stats::on_complete(entry.array->stats, entry.index, entry.status_gen); InterlockedExchange(&entry.array->results[entry.index], result); } else { signal_fence(entry.fence, entry.value); @@ -937,6 +1377,7 @@ void fail_entry(Object* self, const Entry& entry, const char* reason) noexcept { count_failure(StorageFailure::other, self, entry.type == Entry::request ? entry.bytes : nullptr); if (entry.type == Entry::request) count_page_request(entry.bytes, true); + tally_failure("exception"); // LOCAL: heartbeat tally (a literal: the tally keeps the pointer) InterlockedExchange(&self->pending, static_cast<LONG>(E_FAIL)); static LONG reported; if (x2w_local::first_calls(reported, 12)) @@ -1053,6 +1494,7 @@ struct Unrecorded { unsigned index; void* fence; u64 value; + LONG status_gen; unsigned char bytes[sizeof(StorageRequest)]; }; @@ -1068,7 +1510,7 @@ bool deferred_pending(const QueueWork& work) // Fails an entry that will not run: a request counts as failed, a status entry completes with the // pending failure (E_OUTOFMEMORY when nothing worse is pending), a fence is signaled. -void fail_unstarted(Object* self, Entry::Type type, Object* array, unsigned index, void* fence, u64 value, +void fail_unstarted(Object* self, Entry::Type type, Object* array, unsigned index, void* fence, u64 value, LONG status_gen, const unsigned char* request) { if (type == Entry::request) { @@ -1077,6 +1519,7 @@ void fail_unstarted(Object* self, Entry::Type type, Object* array, unsigned inde } else if (type == Entry::status_entry) { const LONG pending = InterlockedExchange(&self->pending, S_OK); if (array && array->results && index < array->capacity) { + x2w_dstorage_stats::on_complete(array->stats, index, status_gen); InterlockedExchange(&array->results[index], pending < 0 ? pending : static_cast<LONG>(E_OUTOFMEMORY)); } @@ -1108,9 +1551,9 @@ bool has_unrecorded(Object* self) void defer_unrecorded(Object* self, const 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{nullptr, 0, 0, entry.type, entry.array, entry.index, entry.fence, entry.value, entry.status_gen, {}}; if (!node) { - fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value, entry.bytes); + fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value, entry.status_gen, entry.bytes); return; } if (entry.type == Entry::request) std::memcpy(node->bytes, entry.bytes, sizeof node->bytes); @@ -1129,7 +1572,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); + fail_unstarted(self, node->type, node->array, node->index, node->fence, node->value, node->status_gen, node->bytes); delete node; node = next; } @@ -1146,7 +1589,7 @@ void fail_waiting(Object* self, QueueWork* work) entry = std::move(work->waiting.front()); work->waiting.pop_front(); } - fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value, entry.bytes); + fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value, entry.status_gen, entry.bytes); } } @@ -1274,10 +1717,10 @@ void complete_deferred(Object* self, QueueWork* work) } } if (node) { - fail_unstarted(self, node->type, node->array, node->index, node->fence, node->value, node->bytes); + fail_unstarted(self, node->type, node->array, node->index, node->fence, node->value, node->status_gen, node->bytes); delete node; } else { - fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value, entry.bytes); + fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value, entry.status_gen, entry.bytes); } } } @@ -1352,9 +1795,11 @@ void __stdcall queue_enqueue_status(Object* self, Object* array, unsigned index) log("x2w-dstorage Queue::EnqueueStatus array=%p index=%u%s (requests done=%ld inflated=%ld failed=%ld)", static_cast<void*>(array), index, valid ? "" : " INVALID ARRAY", requests_done, requests_compressed, requests_failed); if (!valid) return; + const LONG gen = x2w_dstorage_stats::on_enqueue(array->stats, index, self); InterlockedExchange(&array->results[index], static_cast<LONG>(0x8000000A)); // E_PENDING until its turn Entry entry{}; entry.type = Entry::status_entry; + entry.status_gen = gen; entry.array = array; entry.index = index; push(self, std::move(entry)); @@ -1429,6 +1874,7 @@ void __stdcall queue_retrieve_error_record(Object* self, StorageErrorRecord* out bool __stdcall status_is_complete(Object* self, unsigned index) { const bool complete = index < self->capacity && self->results[index] != static_cast<LONG>(0x8000000A); + x2w_dstorage_stats::on_poll(self->stats, complete, _ReturnAddress()); static LONG calls; if (x2w_local::first_calls(calls, 4)) log("x2w-dstorage StatusArray::IsComplete index=%u -> %d", index, complete); return complete; @@ -1558,10 +2004,20 @@ extern "C" long __stdcall DStorageGetFactory(const GUID* riid, void** out) std::snprintf(section_text, sizeof(section_text), "unknown"); // Heartbeat preserves "inflated=%ld" format string for tools/startup/live_view.py; // requests_compressed counts all compressed streams (zlib and standalone/embedded BCPack). - log("x2w-dstorage heartbeat %d s: requests done=%ld inflated=%ld failed=%ld bcpack-blank=%ld; page tokens 0 at enqueue=%ld, " - "still 0 at run=%ld, replaced after enqueue=%ld; %s, live physical-page sections=%s", second, requests_done, requests_compressed, - failed, requests_bcpack_blank, zero_tokens_at_enqueue, zero_tokens_at_run, tokens_replaced_after_enqueue, memory, - section_text); + log("x2w-dstorage heartbeat %d s: requests done=%ld inflated=%ld failed=%ld bcpack-blank=%ld archive-shifted=%ld past-end=%ld stream-pieces=%ld found-on-disk=%ld rds5-slices=%ld; page tokens 0 at enqueue=%ld, " + "still 0 at run=%ld, replaced after enqueue=%ld; %s, live physical-page sections=%s; destinations served after wait=%ld dropped=%ld", second, requests_done, requests_compressed, + requests_failed, requests_bcpack_blank, requests_archive_shifted, requests_archive_past_end, requests_stream_pieces, requests_pieces_found_on_disk, requests_interval_slices, zero_tokens_at_enqueue, zero_tokens_at_run, tokens_replaced_after_enqueue, memory, + section_text, destination_served_after_wait, destination_dropped); + char tally[512]; + int at = 0; + tally[0] = 0; + AcquireSRWLockShared(&failure_lock); + for (const auto& t : failure_tally) { + if (!t.outcome || at >= static_cast<int>(sizeof(tally)) - 1) break; + at += std::snprintf(tally + at, sizeof(tally) - at, " [%s]=%ld", t.outcome, t.count); + } + ReleaseSRWLockShared(&failure_lock); + if (tally[0]) log("x2w-dstorage failures by outcome:%s", tally); char causes[384]; if (format_failure_causes(causes, sizeof(causes), second, failure_counts) > 0) log("%s", causes); char ends[384]; @@ -1569,6 +2025,18 @@ extern "C" long __stdcall DStorageGetFactory(const GUID* riid, void** out) last = total2; last_memory = sample; } + x2w_dstorage_stats::report(second, static_cast<LONG>(0x8000000A), [](const char* format, auto... args) { log(format, args...); }, [](void* queue, char* out, std::size_t size) { + auto* const q = static_cast<Object*>(queue); + QueueWork* const work = q ? q->work : nullptr; + if (!work) { + std::snprintf(out, size, "queue %p: no work", queue); + return; + } + const std::lock_guard guard(work->mutex); + std::snprintf(out, size, "queue %p: entries submitted %llu finished %llu, %zu to run, %zu waiting for Submit, %zu failing", queue, + static_cast<unsigned long long>(work->submitted_total), static_cast<unsigned long long>(work->finished_total), + work->submitted.size(), work->waiting.size(), work->failing.size()); + }); } }, nullptr, 0, nullptr); (void)heartbeat; diff --git a/src/x2w_shader/bvh.cpp b/src/x2w_shader/bvh.cpp new file mode 100644 index 0000000000..51494ff091 --- /dev/null +++ b/src/x2w_shader/bvh.cpp @@ -0,0 +1,265 @@ +// Preserve operation order and disable FMA contraction. The lowering is compared against this arithmetic +// dword for dword. +#include "x2w_shader/bvh.h" + +#include <bit> +#include <cmath> +#include <utility> + +#if defined(_MSC_VER) && !defined(__clang__) +#pragma fp_contract(off) +#else +#pragma STDC FP_CONTRACT OFF +#endif + +namespace x2w::vs::bvh { + +namespace { + +float from_bits(std::uint32_t b) { return std::bit_cast<float>(b); } +std::uint32_t bits_of(float f) { return std::bit_cast<std::uint32_t>(f); } + +// A NaN operand gives the other operand. +float fmin_rs(float a, float b) { return std::fmin(a, b); } +float fmax_rs(float a, float b) { return std::fmax(a, b); } + +} // namespace + +Ray Ray::make(Vec3 origin, Vec3 direction, float extent) +{ + Ray r; + r.extent = extent; + r.origin = origin; + r.direction = direction; + for (int i = 0; i < 3; ++i) r.inverse[i] = 1.0f / direction[i]; + return r; +} + +std::uint32_t kind(std::uint64_t pointer) { return static_cast<std::uint32_t>(pointer & 7); } + +std::uint64_t node_address(std::uint32_t word0, std::uint32_t word1, std::uint64_t pointer) +{ + const std::uint64_t base = ((std::uint64_t{word1 & 0xff} << 32) | std::uint64_t{word0}) << 8; + return base + ((pointer >> 3) << 6); // wrapping +} + +Result4 to_bits(const std::array<float, 4>& values) +{ + return {bits_of(values[0]), bits_of(values[1]), bits_of(values[2]), bits_of(values[3])}; +} + +Result4 intersect(const Words& words, std::uint32_t k, const Ray& ray, bool sort) +{ + switch (k & 7) { + case 4: return boxes(children(words), boxes16(words), ray, sort); + case 5: return boxes(children(words), boxes32(words), ray, sort); + case 0: + case 1: + case 2: + case 3: return to_bits(triangle(triangle_vertices(words, k & 7), ray)); + default: return to_bits(MISS); + } +} + +Result4 children(const Words& words) { return {words[0], words[1], words[2], words[3]}; } + +Boxes boxes16(const Words& words) +{ + Boxes out{}; + for (std::size_t b = 0; b < 4; ++b) { + for (std::size_t k = 0; k < 6; ++k) { + const std::size_t half = 6 * b + k; + out[b][k] = half_to_f32(static_cast<std::uint16_t>(words[4 + half / 2] >> (16 * (half % 2)))); + } + } + return out; +} + +Boxes boxes32(const Words& words) +{ + Boxes out{}; + for (std::size_t b = 0; b < 4; ++b) + for (std::size_t k = 0; k < 6; ++k) out[b][k] = from_bits(words[4 + 6 * b + k]); + return out; +} + +std::uint32_t vertex_map(std::uint32_t k) +{ + const auto& v = TRIANGLE_VERTICES[k & 3]; + return v[0] | (v[1] << 4) | (v[2] << 8); +} + +Triangle triangle_vertices(const Words& words, std::uint32_t k) +{ + const std::uint32_t id = words[15] >> (8 * k); + const std::uint32_t i = id & 3, j = (id >> 2) & 3; + // An id naming one vertex twice, or a vertex 3, is malformed; it reads + // what this arithmetic lands on (a vertex of the node), as the emitted + // code does. + const std::uint32_t first = (3u - i - j) & 3; + const std::uint32_t names[3] = {first, i, j}; + Triangle out{}; + for (int t = 0; t < 3; ++t) { + const std::size_t vertex = (vertex_map(k) >> (4 * names[t])) & 0xf; + for (std::size_t c = 0; c < 3; ++c) out[t][c] = from_bits(words[3 * vertex + c]); + } + return out; +} + +Result4 boxes(const Result4& children, const Boxes& bounds, const Ray& ray, bool sort) +{ + // An infinite inverse (a direction component of 0) would turn an origin + // exactly on a box's face into a NaN. (Maximum then minimum, as the + // emitted code: a NaN becomes the lower bound.) + constexpr float big = std::numeric_limits<float>::max(); + Vec3 inverse{}; + for (int a = 0; a < 3; ++a) inverse[a] = fmin_rs(fmax_rs(ray.inverse[a], -big), big); + Result4 ids{NONE, NONE, NONE, NONE}; + const float inf = std::numeric_limits<float>::infinity(); + std::array<float, 4> distances{inf, inf, inf, inf}; + for (std::size_t n = 0; n < 4; ++n) { + const Box& b = bounds[n]; + float near_[3], far_[3]; + for (int a = 0; a < 3; ++a) { + const float low = (b[a] - ray.origin[a]) * inverse[a]; + const float high = (b[3 + a] - ray.origin[a]) * inverse[a]; + near_[a] = fmin_rs(low, high); + far_[a] = fmax_rs(low, high); + } + const float enter = fmax_rs(fmax_rs(near_[0], near_[1]), near_[2]); + const float leave = fmin_rs(fmin_rs(far_[0], far_[1]), far_[2]); + // A box whose minimum x is NaN is switched off. A child that is not + // there may have inverted infinite bounds, which every ray enters at + // minus infinity: it would be first of the sorted children and end the + // walk before them. + if (children[n] != NONE && !std::isnan(b[0]) && leave >= fmax_rs(enter, 0.0f) && enter < ray.extent) { + ids[n] = children[n]; + distances[n] = enter; + } + } + if (sort) { + constexpr std::pair<int, int> network[5] = {{0, 1}, {2, 3}, {0, 2}, {1, 3}, {1, 2}}; + for (auto [a, b] : network) { + if (distances[b] < distances[a]) { + std::swap(distances[a], distances[b]); + std::swap(ids[a], ids[b]); + } + } + } + return ids; +} + +std::array<float, 4> triangle(const Triangle& p, const Ray& ray) +{ + const Vec3& d = ray.direction; + const Vec3 size{std::fabs(d[0]), std::fabs(d[1]), std::fabs(d[2])}; + // The largest axis, and the other two in an order that keeps the + // triangle's winding. + int kz; + if (size[0] >= size[1]) + kz = size[0] >= size[2] ? 0 : 2; + else if (size[1] >= size[2]) + kz = 1; + else + kz = 2; + int kx = (kz + 1) % 3, ky = (kz + 2) % 3; + if (d[kz] < 0.0f) std::swap(kx, ky); + const float sz = ray.inverse[kz]; + const float sx = d[kx] * sz, sy = d[ky] * sz; + struct Sheared { + float x, y, z; + }; + auto sheared = [&](const Vec3& v) { + const float r[3] = {v[0] - ray.origin[0], v[1] - ray.origin[1], v[2] - ray.origin[2]}; + const float x = r[kx] - sx * r[kz]; + const float y = r[ky] - sy * r[kz]; + const float z = sz * r[kz]; + return Sheared{x, y, z}; + }; + const Sheared a = sheared(p[0]); + const Sheared b = sheared(p[1]); + const Sheared c = sheared(p[2]); + const float u = c.x * b.y - c.y * b.x; + const float v = a.x * c.y - a.y * c.x; + const float w = b.x * a.y - b.y * a.x; + const bool behind = u < 0.0f || v < 0.0f || w < 0.0f; + const bool before = u > 0.0f || v > 0.0f || w > 0.0f; + const float det = u + (v + w); + const float t = (u * a.z + v * b.z) + w * c.z; + const bool ahead = (det > 0.0f && t >= 0.0f) || (det < 0.0f && t <= 0.0f); + if (!(behind && before) && ahead) return {t, det, v, w}; + return MISS; +} + +float half_to_f32(std::uint16_t h) +{ + const std::uint32_t sign = std::uint32_t{static_cast<std::uint32_t>(h >> 15)} << 31; + const std::uint32_t exponent = (h >> 10) & 0x1f, mantissa = h & 0x3ffu; + std::uint32_t bits; + if (exponent == 0 && mantissa == 0) { + bits = sign; + } else if (exponent == 0) { + // Subnormal: normalise. + const std::uint32_t shift = static_cast<std::uint32_t>(std::countl_zero(mantissa)) - 21; + bits = sign | ((113 - shift) << 23) | (((mantissa << shift) & 0x3ff) << 13); + } else if (exponent == 0x1f) { + bits = sign | (0xffu << 23) | (mantissa << 13); + } else { + bits = sign | ((exponent + 112) << 23) | (mantissa << 13); + } + return from_bits(bits); +} + +namespace testing { + +std::uint16_t f32_to_half(float x, bool up) +{ + bool have = false; + std::uint16_t best = 0; + for (std::uint32_t hh = 0; hh <= 0xffff; ++hh) { + const auto h = static_cast<std::uint16_t>(hh); + const float f = half_to_f32(h); + if (std::isnan(f) || (up ? f < x : f > x)) continue; + if (have && std::fabs(half_to_f32(best) - x) <= std::fabs(f - x)) continue; + best = h; + have = true; + } + return best; // a half always exists for the values the tests use +} + +Words box32(const Result4& children, const Boxes& bounds) +{ + Words w{}; + for (int i = 0; i < 4; ++i) w[i] = children[i]; + for (std::size_t b = 0; b < 4; ++b) + for (std::size_t k = 0; k < 6; ++k) w[4 + 6 * b + k] = bits_of(bounds[b][k]); + return w; +} + +Words box16(const Result4& children, const Boxes& bounds) +{ + Words w{}; + for (int i = 0; i < 4; ++i) w[i] = children[i]; + for (std::size_t b = 0; b < 4; ++b) { + for (std::size_t k = 0; k < 6; ++k) { + const std::size_t half = 6 * b + k; + const float x = bounds[b][k]; + const std::uint16_t h = std::isnan(x) ? std::uint16_t{0x7e00} : f32_to_half(x, k >= 3); + w[4 + half / 2] |= std::uint32_t{h} << (16 * (half % 2)); + } + } + return w; +} + +Words triangles(const Vec3* vertices, std::size_t count, std::uint32_t id) +{ + Words w{}; + for (std::size_t n = 0; n < count; ++n) + for (std::size_t c = 0; c < 3; ++c) w[3 * n + c] = bits_of(vertices[n][c]); + w[15] = id; + return w; +} + +} // namespace testing + +} // namespace x2w::vs::bvh diff --git a/src/x2w_shader/bvh.h b/src/x2w_shader/bvh.h new file mode 100644 index 0000000000..89560cd63f --- /dev/null +++ b/src/x2w_shader/bvh.h @@ -0,0 +1,125 @@ +// The console GPU's ray-tracing node test, `image_bvh_intersect_ray` and +// `image_bvh64_intersect_ray`, on the CPU: the node formats, and what the +// instruction returns for one ray and one node. The emitter lowers the +// instruction to the same arithmetic in the same order (emit/intersect), so +// its code can be compared against this dword for dword. +// +// BVH node pointers, box nodes, and triangle intersections. +// +// The instruction tests one ray against one 64-byte node of a bounding +// volume hierarchy and returns four dwords. Traversal (the stack, instance +// transforms, culling, the hit distance `numerator / denominator`) is the +// program's own code. +// +// Node pointers: the low three bits are the node's kind, the rest its byte +// offset in 8-byte units: the node is at `(pointer >> 3) << 6` past the base +// address of the descriptor (40 bits in dword 0 and the low byte of dword 1, +// in 256-byte units). +// +// kind 0-3 triangle 0-3 of a triangle node +// kind 4 box node, 16-bit floats (64 bytes) +// kind 5 box node, 32-bit floats (128 bytes) +// kind 6 instance: not read by the instruction +// kind 7 procedural primitive: not read by the instruction +// +// Not known: how the console rounds, which of two boxes entered at the same +// distance it returns first, and what it returns for a ray exactly through an +// edge (here: a hit in both triangles of the edge) or for kinds 6 and 7 +// (here: a triangle miss). +#pragma once + +#include <array> +#include <cstddef> +#include <cstdint> +#include <limits> + +namespace x2w::vs::bvh { + +// The result dword for a box the ray misses, or a child that is not there. +inline constexpr std::uint32_t NONE = 0xffff'ffffu; + +// The node's vertices that make triangle 0-3, by the triangle's own vertex +// numbers 0-2. +inline constexpr std::array<std::array<std::uint32_t, 3>, 4> TRIANGLE_VERTICES{{ + {0, 1, 2}, {1, 3, 2}, {2, 3, 4}, {2, 4, 0}}}; + +// Descriptor dword 1: boxes are returned nearest first. +inline constexpr std::uint32_t BOX_SORT = 1u << 31; +// Descriptor dword 3: triangles return the numerators of I and J. +inline constexpr std::uint32_t RETURN_BARYCENTRICS = 1u << 24; +// Descriptor dword 3, bits 31:28: the descriptor's type, a ray-tracing +// structure. +inline constexpr std::uint32_t DESCRIPTOR_TYPE = 8; + +using Vec3 = std::array<float, 3>; +using Words = std::array<std::uint32_t, 28>; +using Box = std::array<float, 6>; +using Boxes = std::array<Box, 4>; +using Result4 = std::array<std::uint32_t, 4>; +using Triangle = std::array<Vec3, 3>; + +// The ray as the instruction takes it. +struct Ray { + float extent = 0; + Vec3 origin{}; + Vec3 direction{}; + // What the program computed as `1 / direction`. + Vec3 inverse{}; + + // A ray with the inverse direction a program computes by division. + static Ray make(Vec3 origin, Vec3 direction, float extent); + bool operator==(const Ray&) const = default; +}; + +// The kind of the node a pointer names. +std::uint32_t kind(std::uint64_t pointer); + +// The byte address of the node `pointer` names, for a descriptor whose first +// two dwords are `word0` and `word1`. +std::uint64_t node_address(std::uint32_t word0, std::uint32_t word1, std::uint64_t pointer); + +// What the instruction returns for the node at `words` (its first 28 dwords; +// a 64-byte node's dwords 16-27 are not read) named by a pointer of this +// `kind`, with box sorting as `sort` says and the triangle return mode set. +Result4 intersect(const Words& words, std::uint32_t kind, const Ray& ray, bool sort); + +// A box node's four child pointers. +Result4 children(const Words& words); +// The four boxes of a 16-bit box node: minimum x y z, maximum x y z. +Boxes boxes16(const Words& words); +// The four boxes of a 32-bit box node. +Boxes boxes32(const Words& words); +// TRIANGLE_VERTICES of triangle `k` in four bits each, vertex 0 lowest. +std::uint32_t vertex_map(std::uint32_t k); +// The vertices of triangle `k` (0-3) of a triangle node, the first being the +// one neither barycentric weighs, then I's, then J's. +Triangle triangle_vertices(const Words& words, std::uint32_t k); +// The box test: child pointers of the boxes the ray enters, NONE for the +// others; sorted by entry distance when `sort`, in child order otherwise. +Result4 boxes(const Result4& children, const Boxes& boxes, const Ray& ray, bool sort); + +// What a triangle the ray misses returns. +inline constexpr std::array<float, 4> MISS{std::numeric_limits<float>::infinity(), 1.0f, 0.0f, 0.0f}; +// The triangle test (watertight): the hit distance's numerator, the +// denominator, and the numerators of the weights of vertices 1 and 2; MISS +// otherwise. +std::array<float, 4> triangle(const Triangle& p, const Ray& ray); +// A 16-bit float as a 32-bit one (exact). +float half_to_f32(std::uint16_t h); + +// `values` as their bit patterns. +Result4 to_bits(const std::array<float, 4>& values); + +// Test helpers shared with the emitter tests. +namespace testing { +// The smallest 16-bit float not below `x` (`up`) or not above it. +std::uint16_t f32_to_half(float x, bool up); +// A 32-bit box node. +Words box32(const Result4& children, const Boxes& boxes); +// A 16-bit box node holding `boxes` rounded outward. +Words box16(const Result4& children, const Boxes& boxes); +// A triangle node: up to five vertices, and the dword at byte 60. +Words triangles(const Vec3* vertices, std::size_t count, std::uint32_t id); +} // namespace testing + +} // namespace x2w::vs::bvh diff --git a/src/x2w_shader/dxbc.cpp b/src/x2w_shader/dxbc.cpp new file mode 100644 index 0000000000..f5ee53f9f3 --- /dev/null +++ b/src/x2w_shader/dxbc.cpp @@ -0,0 +1,110 @@ +// The DXBC container. +#include "x2w_shader/dxbc.h" + +#include <cstring> + +namespace x2w::vs::dxbc { + +namespace { +constexpr std::size_t HEADER_SIZE = 0x20; +constexpr std::size_t MAX_PARTS = 256; +} // namespace + +std::string FourCC::to_string() const { + std::string s; + for (std::uint8_t c : b) { + // is_ascii_graphic: '!'..='~' + s += (c >= 0x21 && c <= 0x7E) ? char(c) : '.'; + } + return s; +} + +Container Container::parse(Bytes data) { + if (data.size() < HEADER_SIZE || std::memcmp(data.data(), "DXBC", 4) != 0) { + throw ShaderError::not_dxbc(); + } + Container c; + std::memcpy(c.digest.data(), data.data() + 4, 16); + std::uint16_t major = u16_at(data, 0x14); + std::uint16_t minor = u16_at(data, 0x16); + c.version = {major, minor}; + std::size_t total = u32_at(data, 0x18); + if (total > data.size() || total < HEADER_SIZE) { + throw ShaderError::malformed("container size disagrees with data"); + } + data = data.first(total); + std::size_t count = u32_at(data, 0x1C); + if (count > MAX_PARTS) { + throw ShaderError::malformed("implausible part count"); + } + c.parts.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + std::size_t offset = u32_at(data, HEADER_SIZE + 4 * i); + // data.get(offset..offset + 4): offset + 4 cannot overflow a usize from a u32 here. + if (offset + 4 > data.size()) { + throw ShaderError::malformed("part header out of bounds"); + } + FourCC fourcc; + std::memcpy(fourcc.b.data(), data.data() + offset, 4); + std::size_t size = u32_at(data, offset + 4); + if (offset + 8 + size > data.size()) { + throw ShaderError::malformed("part data out of bounds"); + } + c.parts.push_back(Part{fourcc, offset, data.subspan(offset + 8, size)}); + } + return c; +} + +const Part* Container::part(FourCC fourcc) const { + for (const Part& p : parts) { + if (p.fourcc == fourcc) return &p; + } + return nullptr; +} + +std::uint16_t u16_at(Bytes data, std::size_t at) { + if (at > data.size() || data.size() - at < 2) throw ShaderError::malformed("truncated"); + return std::uint16_t(data[at] | data[at + 1] << 8); +} + +std::uint32_t u32_at(Bytes data, std::size_t at) { + if (at > data.size() || data.size() - at < 4) throw ShaderError::malformed("truncated"); + return std::uint32_t(data[at]) | std::uint32_t(data[at + 1]) << 8 | std::uint32_t(data[at + 2]) << 16 | + std::uint32_t(data[at + 3]) << 24; +} + +std::uint64_t u64_at(Bytes data, std::size_t at) { + if (at > data.size() || data.size() - at < 8) throw ShaderError::malformed("truncated"); + std::uint64_t v = 0; + for (int i = 7; i >= 0; --i) v = v << 8 | data[at + i]; + return v; +} + +std::vector<std::uint8_t> build(const std::vector<std::pair<FourCC, Bytes>>& parts) { + std::size_t table = HEADER_SIZE + 4 * parts.size(); + std::size_t total = table; + for (const auto& p : parts) total += 8 + p.second.size(); + std::vector<std::uint8_t> out; + out.reserve(total); + auto put32 = [&](std::uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); + }; + out.insert(out.end(), {'D', 'X', 'B', 'C'}); + out.insert(out.end(), 16, 0); + out.insert(out.end(), {1, 0, 0, 0}); // version 1.0 + put32(std::uint32_t(total)); + put32(std::uint32_t(parts.size())); + std::size_t offset = table; + for (const auto& p : parts) { + put32(std::uint32_t(offset)); + offset += 8 + p.second.size(); + } + for (const auto& p : parts) { + out.insert(out.end(), p.first.b.begin(), p.first.b.end()); + put32(std::uint32_t(p.second.size())); + out.insert(out.end(), p.second.begin(), p.second.end()); + } + return out; +} + +} // namespace x2w::vs::dxbc diff --git a/src/x2w_shader/dxbc.h b/src/x2w_shader/dxbc.h new file mode 100644 index 0000000000..4777d3767c --- /dev/null +++ b/src/x2w_shader/dxbc.h @@ -0,0 +1,93 @@ +// The DXBC container: a header, then a table of FourCC-tagged parts. +// +// 0x00 "DXBC" +// 0x04 digest[16] +// 0x14 version major u16, minor u16 +// 0x18 total size u32 +// 0x1C part count u32 +// 0x20 part offsets u32[count] +// part: fourcc[4], size u32, data[size] +#pragma once + +#include <array> +#include <cstddef> +#include <cstdint> +#include <span> +#include <string> +#include <utility> +#include <vector> + +#include "x2w_shader/error.h" + +namespace x2w::vs::dxbc { + +using Bytes = std::span<const std::uint8_t>; + +struct FourCC { + std::array<std::uint8_t, 4> b{}; + + static const FourCC DXIL; + // Native code another compiler made, in place of `DXIL`. + static const FourCC ACCC; + static const FourCC STAT; + static const FourCC RTS0; + static const FourCC PSV0; + static const FourCC ISG1; + static const FourCC OSG1; + // Per-primitive outputs of a mesh shader. + static const FourCC PSG1; + static const FourCC SFI0; + static const FourCC HASH; + static const FourCC ILDB; + static const FourCC ILDN; + + // Display and Debug: the four bytes, '.' for any that is not ASCII graphic. + std::string to_string() const; + bool operator==(const FourCC&) const = default; + auto operator<=>(const FourCC&) const = default; +}; + +constexpr FourCC fourcc(const char (&s)[5]) { + return FourCC{{std::uint8_t(s[0]), std::uint8_t(s[1]), std::uint8_t(s[2]), std::uint8_t(s[3])}}; +} +inline constexpr FourCC FourCC::DXIL = fourcc("DXIL"); +inline constexpr FourCC FourCC::ACCC = fourcc("ACCC"); +inline constexpr FourCC FourCC::STAT = fourcc("STAT"); +inline constexpr FourCC FourCC::RTS0 = fourcc("RTS0"); +inline constexpr FourCC FourCC::PSV0 = fourcc("PSV0"); +inline constexpr FourCC FourCC::ISG1 = fourcc("ISG1"); +inline constexpr FourCC FourCC::OSG1 = fourcc("OSG1"); +inline constexpr FourCC FourCC::PSG1 = fourcc("PSG1"); +inline constexpr FourCC FourCC::SFI0 = fourcc("SFI0"); +inline constexpr FourCC FourCC::HASH = fourcc("HASH"); +inline constexpr FourCC FourCC::ILDB = fourcc("ILDB"); +inline constexpr FourCC FourCC::ILDN = fourcc("ILDN"); + +struct Part { + FourCC fourcc; + // Offset of the part header within the container. + std::size_t offset = 0; + Bytes data; +}; + +// Borrows the bytes it was parsed from: keep them alive. +struct Container { + std::array<std::uint8_t, 16> digest{}; + std::pair<std::uint16_t, std::uint16_t> version{}; + std::vector<Part> parts; + + // Throws ShaderError::not_dxbc / malformed. + static Container parse(Bytes data); + // The first part of that tag, or nullptr. + const Part* part(FourCC fourcc) const; +}; + +// Little-endian reads; throw ShaderError::malformed("truncated") past the end (pub(crate)). +std::uint16_t u16_at(Bytes data, std::size_t at); +std::uint32_t u32_at(Bytes data, std::size_t at); +std::uint64_t u64_at(Bytes data, std::size_t at); + +// Builds a container from parts for tests. +std::vector<std::uint8_t> build(const std::vector<std::pair<FourCC, Bytes>>& parts); + +} // namespace x2w::vs::dxbc diff --git a/src/x2w_shader/dxil.cpp b/src/x2w_shader/dxil.cpp new file mode 100644 index 0000000000..2feb5978f8 --- /dev/null +++ b/src/x2w_shader/dxil.cpp @@ -0,0 +1,93 @@ +// The DXIL program inside a container's `DXIL` (or `STAT`) part. +#include "x2w_shader/dxil.h" + +#include <cstring> + +namespace x2w::vs::dxil { + +namespace { +constexpr std::uint8_t LLVM_BITCODE_MAGIC[4] = {0x42, 0x43, 0xC0, 0xDE}; +constexpr std::uint32_t STANDARD_BITCODE_OFFSET = 16; +} // namespace + +ShaderKind shader_kind_from_raw(std::uint16_t v) { return static_cast<ShaderKind>(v); } + +std::string debug(ShaderKind k) { + static const char* const NAMES[16] = { + "Pixel", "Vertex", "Geometry", "Hull", "Domain", "Compute", "Library", "RayGeneration", + "Intersection", "AnyHit", "ClosestHit", "Miss", "Callable", "Mesh", "Amplification", "Node", + }; + auto v = static_cast<std::uint16_t>(k); + if (v < 16) return NAMES[v]; + return "Unknown(" + std::to_string(v) + ")"; +} + +DxilProgram DxilProgram::parse(Bytes part) { + std::uint32_t version = dxbc::u32_at(part, 0); + std::size_t size = std::size_t(dxbc::u32_at(part, 4)) * 4; + if (!(size <= part.size() && size >= 24)) { + throw ShaderError::malformed("program size disagrees with part size"); + } + part = part.first(size); + if (std::memcmp(part.data() + 8, "DXIL", 4) != 0) { + throw ShaderError::malformed("missing DXIL magic"); + } + std::uint32_t dxil_version = dxbc::u32_at(part, 12); + std::uint32_t offset = dxbc::u32_at(part, 16); + std::size_t len = dxbc::u32_at(part, 20); + std::size_t start = 8 + std::size_t(offset); + if (start + len > part.size()) { + throw ShaderError::malformed("bitcode out of bounds"); + } + Bytes bitcode = part.subspan(start, len); + if (bitcode.size() < 4 || std::memcmp(bitcode.data(), LLVM_BITCODE_MAGIC, 4) != 0) { + throw ShaderError::malformed("bitcode lacks LLVM magic"); + } + if (start < 24) { + throw ShaderError::malformed("bitcode offset too small"); + } + DxilProgram p; + p.kind = shader_kind_from_raw(std::uint16_t(version >> 16)); + p.shader_model = {std::uint8_t((version >> 4) & 0xF), std::uint8_t(version & 0xF)}; + p.dxil_version = dxil_version; + p.bitcode = bitcode; + p.prefix = part.subspan(24, start - 24); + p.trailer = part.subspan(start + len); + return p; +} + +bool DxilProgram::is_standard_layout() const { return prefix.empty() && trailer.empty(); } + +XboxExtras DxilProgram::xbox_extras() const { + XboxExtras x; + x.xdat = prefix.size() >= 4 && std::memcmp(prefix.data(), "XDAT", 4) == 0; + for (std::size_t i = 0; i + 4 <= trailer.size(); ++i) { + if (std::memcmp(trailer.data() + i, "xbop", 4) == 0) { + x.xbop = true; + break; + } + } + return x; +} + +std::vector<std::uint8_t> build_standard(std::uint16_t kind, std::pair<std::uint8_t, std::uint8_t> sm, + std::uint32_t dxil_version, Bytes bitcode) { + std::vector<std::uint8_t> out; + auto put32 = [&](std::uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); + }; + std::uint32_t version = std::uint32_t(kind) << 16 | std::uint32_t(sm.first) << 4 | std::uint32_t(sm.second); + std::size_t padded = (bitcode.size() + 3) / 4 * 4; + std::size_t size_dwords = (24 + padded) / 4; + put32(version); + put32(std::uint32_t(size_dwords)); + out.insert(out.end(), {'D', 'X', 'I', 'L'}); + put32(dxil_version); + put32(STANDARD_BITCODE_OFFSET); + put32(std::uint32_t(bitcode.size())); + out.insert(out.end(), bitcode.begin(), bitcode.end()); + out.resize(24 + padded, 0); + return out; +} + +} // namespace x2w::vs::dxil diff --git a/src/x2w_shader/dxil.h b/src/x2w_shader/dxil.h new file mode 100644 index 0000000000..6b84899cff --- /dev/null +++ b/src/x2w_shader/dxil.h @@ -0,0 +1,80 @@ +// The DXIL program inside a container's `DXIL` (or `STAT`) part. +// +// 0x00 program version u32 (kind << 16 | major << 4 | minor) +// 0x04 size in dwords u32 +// 0x08 "DXIL" <- bitcode offset is relative to here +// 0x0C dxil version u32 +// 0x10 bitcode offset u32 (16 in standard PC DXIL) +// 0x14 bitcode size u32 +#pragma once + +#include <cstdint> +#include <string> +#include <utility> +#include <vector> + +#include "x2w_shader/dxbc.h" +#include "x2w_shader/error.h" + +namespace x2w::vs::dxil { + +using dxbc::Bytes; + +// Values beyond Node retain their numeric stage identifier. +enum class ShaderKind : std::uint16_t { + Pixel = 0, + Vertex = 1, + Geometry = 2, + Hull = 3, + Domain = 4, + Compute = 5, + Library = 6, + RayGeneration = 7, + Intersection = 8, + AnyHit = 9, + ClosestHit = 10, + Miss = 11, + Callable = 12, + Mesh = 13, + Amplification = 14, + Node = 15, +}; + +inline bool is_unknown(ShaderKind k) { return static_cast<std::uint16_t>(k) > 15; } +ShaderKind shader_kind_from_raw(std::uint16_t v); +// Diagnostic spelling: "Pixel",..., "Unknown(17)". +std::string debug(ShaderKind k); + +// Borrows the part it was parsed from. +struct DxilProgram { + ShaderKind kind = ShaderKind::Pixel; + std::pair<std::uint8_t, std::uint8_t> shader_model{}; + std::uint32_t dxil_version = 0; + // LLVM bitcode (starts with `BC C0 DE`). + Bytes bitcode; + // Bytes between the bitcode header and the bitcode. Empty on PC. + Bytes prefix; + // Bytes after the bitcode, up to the program size. Empty on PC. + Bytes trailer; + + // Throws ShaderError::malformed. + static DxilProgram parse(Bytes part); + // True for a program laid out exactly like PC DXIL. + bool is_standard_layout() const; + struct XboxExtras xbox_extras() const; +}; + +// Xbox additions recognised around the bitcode. +struct XboxExtras { + // The prefix starts with an `XDAT` table. + bool xdat = false; + // The trailer contains an `xbop` blob (compiler options). + bool xbop = false; + bool operator==(const XboxExtras&) const = default; +}; + +// Builds a standard PC-layout program around `bitcode` (test helper). +std::vector<std::uint8_t> build_standard(std::uint16_t kind, std::pair<std::uint8_t, std::uint8_t> sm, + std::uint32_t dxil_version, Bytes bitcode); + +} // namespace x2w::vs::dxil diff --git a/src/x2w_shader/emit/CMakeLists.txt b/src/x2w_shader/emit/CMakeLists.txt new file mode 100644 index 0000000000..dbf595786a --- /dev/null +++ b/src/x2w_shader/emit/CMakeLists.txt @@ -0,0 +1,80 @@ +# DXIL writer for the shader translator. +# Usable on its own (cmake -S src/x2w_shader/emit -B out/build/vs-emit) or through +# add_subdirectory from a parent that defines the other x2w_shader packages. +cmake_minimum_required(VERSION 3.21) +if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) + project(x2w_vs_emit LANGUAGES CXX) + enable_testing() +endif() + +get_filename_component(x2w_vs_src "${CMAKE_CURRENT_SOURCE_DIR}/../.." ABSOLUTE) +get_filename_component(x2w_vs_root "${x2w_vs_src}/.." ABSOLUTE) +set(x2w_vs_emit_tests "${x2w_vs_root}/tests/x2w_shader/emit") + +function(x2w_vs_emit_options target) + target_include_directories(${target} PUBLIC "${x2w_vs_src}") + target_compile_features(${target} PUBLIC cxx_std_20) + if(MSVC) + target_compile_options(${target} PRIVATE /W4 /permissive- /utf-8 /EHsc) + target_compile_definitions(${target} PUBLIC _CRT_SECURE_NO_WARNINGS NOMINMAX) + endif() +endfunction() + +# A test executable from tests/x2w_shader/emit/<name>.cpp linked to `libs`. +function(x2w_vs_emit_test name) + add_executable(x2w_vs_${name} "${x2w_vs_emit_tests}/${name}.cpp") + x2w_vs_emit_options(x2w_vs_${name}) + target_link_libraries(x2w_vs_${name} PRIVATE ${ARGN}) + target_include_directories(x2w_vs_${name} PRIVATE "${x2w_vs_emit_tests}" "${x2w_vs_emit_tests}/..") + add_test(NAME x2w_vs_${name} COMMAND x2w_vs_${name}) +endfunction() + +# The other x2w_shader packages when built standalone (the root CMakeLists defines x2w_shader). +if(NOT TARGET x2w_shader) + add_library(x2w_shader STATIC + "${x2w_vs_src}/x2w_shader/lib.cpp" + "${x2w_vs_src}/x2w_shader/dxbc.cpp" + "${x2w_vs_src}/x2w_shader/dxil.cpp" + "${x2w_vs_src}/x2w_shader/ir.cpp" + "${x2w_vs_src}/x2w_shader/gfx10/mod.cpp" + "${x2w_vs_src}/x2w_shader/gfx10/fields.cpp" + "${x2w_vs_src}/x2w_shader/gfx10/opcodes.cpp" + "${x2w_vs_src}/x2w_shader/gfx10/sp3.cpp") + # vs-front's sources, as far as they are merged. + foreach(f bvh native structure spill io resource) + if(EXISTS "${x2w_vs_src}/x2w_shader/${f}.cpp") + target_sources(x2w_shader PRIVATE "${x2w_vs_src}/x2w_shader/${f}.cpp") + endif() + endforeach() + target_include_directories(x2w_shader PUBLIC "${x2w_vs_src}") + target_compile_features(x2w_shader PUBLIC cxx_std_20) +endif() + +# The parts that need no other x2w_shader package. +add_library(x2w_vs_emit_base STATIC + bitcode.cpp + census.cpp + sampler.cpp +) +x2w_vs_emit_options(x2w_vs_emit_base) + +x2w_vs_emit_test(bitcode_test x2w_vs_emit_base) +x2w_vs_emit_test(sampler_test x2w_vs_emit_base) + +# Per-module fragments: opt.cmake, container.cmake, +# wave.cmake, validator.cmake, host.cmake, ... +# -DX2W_VS_EMIT_ONLY=opt;wave limits the build to those fragments (each helper builds its own +# while the others are in progress). +set(X2W_VS_EMIT_ONLY "" CACHE STRING "Fragments to include (empty: all)") +if(X2W_VS_EMIT_ONLY) + set(x2w_vs_emit_fragments "") + foreach(f IN LISTS X2W_VS_EMIT_ONLY) + list(APPEND x2w_vs_emit_fragments "${CMAKE_CURRENT_SOURCE_DIR}/cmake/${f}.cmake") + endforeach() +else() + file(GLOB x2w_vs_emit_fragments "${CMAKE_CURRENT_SOURCE_DIR}/cmake/*.cmake") + list(SORT x2w_vs_emit_fragments) +endif() +foreach(fragment IN LISTS x2w_vs_emit_fragments) + include("${fragment}") +endforeach() diff --git a/src/x2w_shader/emit/bitcode.cpp b/src/x2w_shader/emit/bitcode.cpp new file mode 100644 index 0000000000..5401208ee4 --- /dev/null +++ b/src/x2w_shader/emit/bitcode.cpp @@ -0,0 +1,876 @@ +// LLVM bitcode module and writer. + +#include "x2w_shader/emit/bitcode.h" + +#include <stdexcept> + +#include "x2w_shader/emit/census.h" + +namespace x2w::vs::bitcode { + +void bug(const char* what) { throw std::logic_error(what); } + +namespace { + +void hash_mix(std::size_t& h, std::uint64_t v) { + // FNV-style mixing; only lookup speed depends on it. + h ^= std::size_t(v) + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2); +} + +} // namespace + +std::size_t TypeDefHash::operator()(const TypeDef& t) const noexcept { + std::size_t h = t.kind; + hash_mix(h, t.n); + hash_mix(h, t.of.id); + if (t.name) hash_mix(h, std::hash<std::string>{}(*t.name)); + for (Ty x : t.list) hash_mix(h, x.id); + return h; +} + +std::size_t ConstKeyHash::operator()(const std::pair<Ty, Const>& k) const noexcept { + std::size_t h = k.first.id; + hash_mix(h, k.second.kind); + hash_mix(h, std::uint64_t(k.second.value)); + hash_mix(h, k.second.bits); + for (std::uint32_t x : k.second.ids) hash_mix(h, x); + return h; +} + +Ty Module::ty(const TypeDef& def) { + auto it = type_ids.find(def); + if (it != type_ids.end()) return Ty{it->second}; + auto t = std::uint32_t(types.size()); + types.push_back(def); + type_ids.emplace(def, t); + return Ty{t}; +} + +Ty Module::void_() { return ty(TypeDef{TypeDef::Void}); } +Ty Module::int_(std::uint32_t bits) { return ty(TypeDef{TypeDef::Int, bits}); } +Ty Module::float_() { return ty(TypeDef{TypeDef::Float}); } +Ty Module::double_() { return ty(TypeDef{TypeDef::Double}); } +Ty Module::ptr(Ty to) { return ty(TypeDef{TypeDef::Ptr, 0, to}); } +Ty Module::ptr_in(Ty to, std::uint32_t space) { return ty(TypeDef{TypeDef::Ptr, space, to}); } +Ty Module::array(std::uint32_t n, Ty of) { return ty(TypeDef{TypeDef::Array, n, of}); } +Ty Module::named_struct(std::string_view name, std::vector<Ty> fields) { + return ty(TypeDef{TypeDef::Struct, 0, Ty{}, std::string(name), std::move(fields)}); +} +Ty Module::func_ty(Ty ret, std::vector<Ty> params) { + return ty(TypeDef{TypeDef::Func, 0, ret, std::nullopt, std::move(params)}); +} + +bool Module::is_void(Ty t) const { return types[t.id].kind == TypeDef::Void; } + +V Module::constant(Ty t, const Const& c) { + auto key = std::make_pair(t, c); + auto it = const_ids.find(key); + if (it != const_ids.end()) return V::constant(it->second); + auto i = std::uint32_t(consts.size()); + consts.push_back(key); + const_ids.emplace(std::move(key), i); + return V::constant(i); +} + +V Module::int_const(Ty t, std::int64_t v) { + Const c; + c.kind = Const::Int; + c.value = v; + return constant(t, c); +} + +V Module::i32(std::uint32_t v) { + Ty t = int_(32); + return int_const(t, std::int64_t(std::int32_t(v))); +} + +V Module::i8(std::uint8_t v) { + Ty t = int_(8); + return int_const(t, std::int64_t(std::int8_t(v))); +} + +V Module::bool_(bool v) { + Ty t = int_(1); + return int_const(t, -std::int64_t(v)); +} + +V Module::f32(std::uint32_t bits) { + Ty t = float_(); + Const c; + c.kind = Const::Float; + c.bits = bits; + return constant(t, c); +} + +V Module::undef(Ty t) { + Const c; + c.kind = Const::Undef; + return constant(t, c); +} + +V Module::aggregate(Ty t, std::span<const V> fields) { + Const c; + c.kind = Const::Aggregate; + c.ids.reserve(fields.size()); + for (V f : fields) { + if (f.kind != V::Const) bug("aggregate of a non-constant"); + c.ids.push_back(f.i); + } + return constant(t, c); +} + +std::optional<std::int64_t> Module::int_value(V v) const { + if (v.kind != V::Const) return std::nullopt; + const Const& c = consts[v.i].second; + if (c.kind != Const::Int) return std::nullopt; + return c.value; +} + +void Module::replace_const(V old, V new_) { + // Replacing the slot contents preserves the existing lookup key. + if (old.kind == V::Const && new_.kind == V::Const) consts[old.i] = consts[new_.i]; +} + +V Module::function(std::string_view name, Ty t, std::optional<Attr> attr, bool body) { + std::string key(name); + auto it = func_ids.find(key); + if (it != func_ids.end()) return V::func(it->second); + auto i = std::uint32_t(funcs.size()); + funcs.push_back(Func{key, t, attr, body}); + func_ids.emplace(std::move(key), i); + return V::func(i); +} + +V Module::global(std::string_view name, Ty t, std::uint32_t space) { + Ty p = ptr_in(t, space); + globals.push_back(Global{std::string(name), t, p, space, std::nullopt}); + return V::global(std::uint32_t(globals.size()) - 1); +} + +V Module::constant_global(std::string_view name, V init) { + if (init.kind != V::Const) bug("a global initialised with a non-constant"); + Ty t = consts[init.i].first; + V g = global(name, t, 0); + globals[g.i].init = init.i; + return g; +} + +void Module::tag(V v, Tag t) { + if (v.kind == V::Inst && census::enabled()) tags[v.i] = t; +} + +std::size_t Module::new_block() { + blocks.emplace_back(); + return blocks.size() - 1; +} + +Ty Module::type_of(V v) const { + switch (v.kind) { + case V::Global: + return globals[v.i].ptr; + case V::Const: + return consts[v.i].first; + case V::Inst: + return insts[v.i].ty; + case V::Func: { + Ty t = funcs[v.i].ty; + auto it = type_ids.find(TypeDef{TypeDef::Ptr, 0, t}); + if (it == type_ids.end()) bug("function pointer type"); + return Ty{it->second}; + } + } + bug("type_of"); +} + +V Module::push(std::size_t block, Ty t, Op op) { + auto i = std::uint32_t(insts.size()); + insts.push_back(Inst{t, std::move(op)}); + // Terminators are kept apart, so a block can still grow at its end. + blocks[block].body.push_back(i); + return V::inst(i); +} + +V Module::bin(std::size_t block, Bin op, V a, V b) { + Ty t = type_of(a); + Op o; + o.kind = Op::Bin; + o.code = std::uint8_t(op); + o.a = a; + o.b = b; + return push(block, t, std::move(o)); +} + +V Module::cast(std::size_t block, Cast op, V v, Ty to) { + Op o; + o.kind = Op::Cast; + o.code = std::uint8_t(op); + o.a = v; + return push(block, to, std::move(o)); +} + +V Module::cmp(std::size_t block, std::uint8_t p, V a, V b) { + Ty t = int_(1); + Op o; + o.kind = Op::Cmp; + o.code = p; + o.a = a; + o.b = b; + return push(block, t, std::move(o)); +} + +V Module::select(std::size_t block, V c, V t, V f) { + Ty ty_ = type_of(t); + Op o; + o.kind = Op::Select; + o.a = c; + o.b = t; + o.c = f; + return push(block, ty_, std::move(o)); +} + +V Module::extract(std::size_t block, V agg, std::uint32_t index) { + const TypeDef& d = types[type_of(agg).id]; + Ty t; + if (d.kind == TypeDef::Struct) + t = d.list[index]; + else if (d.kind == TypeDef::Array) + t = d.of; + else + bug("extractvalue from a non-aggregate"); + Op o; + o.kind = Op::Extract; + o.a = agg; + o.index = index; + return push(block, t, std::move(o)); +} + +V Module::call(std::size_t block, V f, std::vector<V> args) { + if (f.kind != V::Func) bug("call of a non-function"); + const TypeDef& d = types[funcs[f.i].ty.id]; + if (d.kind != TypeDef::Func) bug("unreachable: function type"); + Ty ret = d.of; + Op o; + o.kind = Op::Call; + o.index = f.i; + o.list = std::move(args); + return push(block, ret, std::move(o)); +} + +V Module::phi(std::size_t block, Ty t) { + auto i = std::uint32_t(insts.size()); + Op o; + o.kind = Op::Phi; + insts.push_back(Inst{t, std::move(o)}); + blocks[block].phis.push_back(i); + return V::inst(i); +} + +V Module::element(std::size_t block, V p, V index) { + const TypeDef pd = types[type_of(p).id]; + if (pd.kind != TypeDef::Ptr) bug("element of a non-pointer"); + Ty arr = pd.of; + std::uint32_t space = pd.n; + const TypeDef& ad = types[arr.id]; + if (ad.kind != TypeDef::Array) bug("element of a non-array"); + Ty elem = ad.of; + Ty t = ptr_in(elem, space); + V zero = i32(0); + Op o; + o.kind = Op::Gep; + o.ty = arr; + o.a = p; + o.list = {zero, index}; + return push(block, t, std::move(o)); +} + +V Module::load(std::size_t block, V p) { + const TypeDef& d = types[type_of(p).id]; + if (d.kind != TypeDef::Ptr) bug("load from a non-pointer"); + Ty t = d.of; + Op o; + o.kind = Op::Load; + o.a = p; + return push(block, t, std::move(o)); +} + +void Module::store(std::size_t block, V p, V value) { + Ty v = void_(); + Op o; + o.kind = Op::Store; + o.a = p; + o.b = value; + push(block, v, std::move(o)); +} + +V Module::atomic(std::size_t block, Rmw op, V p, V value) { + Ty t = type_of(value); + Op o; + o.kind = Op::AtomicRmw; + o.code = std::uint8_t(op); + o.a = p; + o.b = value; + return push(block, t, std::move(o)); +} + +V Module::cmpxchg(std::size_t block, V p, V expected, V new_) { + Ty i32t = type_of(new_); + Ty i1 = int_(1); + Ty pair = ty(TypeDef{TypeDef::Struct, 0, Ty{}, std::nullopt, {i32t, i1}}); + Op o; + o.kind = Op::CmpXchg; + o.a = p; + o.b = expected; + o.c = new_; + V r = push(block, pair, std::move(o)); + return extract(block, r, 0); +} + +void Module::set_phi(V phi_, std::vector<std::pair<V, std::size_t>> incoming) { + if (phi_.kind != V::Inst) bug("set_phi of a non-instruction"); + Op& o = insts[phi_.i].op; + o = Op{}; + o.kind = Op::Phi; + o.incoming = std::move(incoming); +} + +void Module::terminate(std::size_t block, Term t) { blocks[block].term = t; } + +Md Module::md_str(std::string_view s) { + MdDef d; + d.kind = MdDef::Str; + d.str = std::string(s); + mds.push_back(std::move(d)); + return Md{std::uint32_t(mds.size()) - 1}; +} + +Md Module::md_value(V v) { + MdDef d; + d.kind = MdDef::Value; + d.ty = type_of(v); + d.v = v; + mds.push_back(std::move(d)); + return Md{std::uint32_t(mds.size()) - 1}; +} + +Md Module::md_node(std::vector<std::optional<Md>> ops) { + MdDef d; + d.kind = MdDef::Node; + d.ops = std::move(ops); + mds.push_back(std::move(d)); + return Md{std::uint32_t(mds.size()) - 1}; +} + +void Module::named_md(std::string_view name, std::vector<Md> nodes) { + named.emplace_back(std::string(name), std::move(nodes)); +} + +std::vector<bool> Module::live() const { + std::vector<bool> lv(insts.size(), false); + std::vector<std::uint32_t> work; + auto mark = [&](V v) { + if (v.kind == V::Inst && !lv[v.i]) { + lv[v.i] = true; + work.push_back(v.i); + } + }; + for (const Block& b : blocks) { + for (std::uint32_t i : b.body) mark(V::inst(i)); + if (b.term && b.term->kind == Term::CondBr) mark(b.term->cond); + } + while (!work.empty()) { + std::uint32_t i = work.back(); + work.pop_back(); + for_each_operand(insts[i].op, mark); + } + return lv; +} + +namespace { + +constexpr std::uint64_t MODULE_BLOCK = 8; +constexpr std::uint64_t PARAMATTR_BLOCK = 9; +constexpr std::uint64_t PARAMATTR_GROUP_BLOCK = 10; +constexpr std::uint64_t CONSTANTS_BLOCK = 11; +constexpr std::uint64_t FUNCTION_BLOCK = 12; +constexpr std::uint64_t VALUE_SYMTAB_BLOCK = 14; +constexpr std::uint64_t METADATA_BLOCK = 15; +constexpr std::uint64_t TYPE_BLOCK = 17; + +std::vector<std::uint64_t> chars(std::string_view s) { + std::vector<std::uint64_t> r; + r.reserve(s.size()); + for (unsigned char c : s) r.push_back(c); + return r; +} + +} // namespace + +Succs successors(const std::optional<Term>& term) { + Succs s; + if (term && term->kind == Term::Br) { + s.to[0] = term->t; + s.len = 1; + } else if (term && term->kind == Term::CondBr) { + s.to[0] = term->t; + s.to[1] = term->f; + s.len = 2; + } + return s; +} + +std::uint64_t signed_vbr(std::int64_t v) { + if (v >= 0) return std::uint64_t(v) << 1; + std::uint64_t mag = 0 - std::uint64_t(v); + return (mag << 1) | 1; +} + +std::vector<std::uint8_t> Module::write() const { + Writer w; + const std::uint8_t magic[4] = {'B', 'C', 0xC0, 0xDE}; + w.bytes(magic, 4); + w.enter(MODULE_BLOCK, 3); + w.record(1, {1}); // VERSION: relative value ids + + // Attribute groups 1-4 and one list per group. + w.enter(PARAMATTR_GROUP_BLOCK, 3); + { + const std::vector<std::pair<std::uint64_t, std::vector<std::uint64_t>>> groups = { + {1, {18, 20}}, {2, {18}}, {3, {18, 21}}, {4, {12, 18}}}; + for (const auto& [id, kinds] : groups) { + std::vector<std::uint64_t> r = {id, 0xFFFFFFFFull}; + for (std::uint64_t k : kinds) { + r.push_back(0); + r.push_back(k); + } + w.record(3, r); + } + } + w.exit(); + w.enter(PARAMATTR_BLOCK, 3); + for (std::uint64_t id = 1; id <= 4; ++id) w.record(2, {id}); + w.exit(); + + w.enter(TYPE_BLOCK, 4); + w.record(1, {std::uint64_t(types.size())}); + for (const TypeDef& t : types) { + switch (t.kind) { + case TypeDef::Void: + w.record(2, {}); + break; + case TypeDef::Float: + w.record(3, {}); + break; + case TypeDef::Double: + w.record(4, {}); + break; + case TypeDef::Int: + w.record(7, {std::uint64_t(t.n)}); + break; + case TypeDef::Ptr: + w.record(8, {std::uint64_t(t.of.id), std::uint64_t(t.n)}); + break; + case TypeDef::Array: + w.record(11, {std::uint64_t(t.n), std::uint64_t(t.of.id)}); + break; + case TypeDef::Struct: { + std::vector<std::uint64_t> r = {0}; + for (Ty f : t.list) r.push_back(f.id); + if (t.name) { + w.record(19, chars(*t.name)); + w.record(20, r); + } else { + w.record(18, r); + } + break; + } + case TypeDef::Func: { + std::vector<std::uint64_t> r = {0, std::uint64_t(t.of.id)}; + for (Ty p : t.list) r.push_back(p.id); + w.record(21, r); + break; + } + } + } + w.exit(); + + w.record(2, chars("dxil-ms-dx")); + w.record(3, chars("e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64")); + const std::uint64_t first_const = globals.size() + funcs.size(); + for (const Global& g : globals) { + // [type, address space << 2 | explicit type | constant, init id + 1, linkage (external 0, + // internal 3), log2 alignment + 1, section] + std::uint64_t constant = 0, init = 0, linkage = 0; + if (g.init) { + constant = 1; + init = first_const + std::uint64_t(*g.init) + 1; + linkage = 3; + } + w.record(7, {std::uint64_t(g.ty.id), (std::uint64_t(g.space) << 2) | 2 | constant, init, linkage, 3, 0}); + } + for (const Func& f : funcs) { + // [type, cc, isproto, linkage, paramattr, align, section, visibility, gc, unnamed_addr, + // prologue, dllstorage, comdat, prefix] + std::uint64_t attr = f.attr ? std::uint64_t(*f.attr) : 0; + w.record(8, {std::uint64_t(f.ty.id), 0, std::uint64_t(!f.body), 0, attr, 0, 0, 0, 0, 0, 0, 0, 0, 0}); + } + + // Value ids: globals, functions, constants, instructions. + const auto nglobals = std::uint32_t(globals.size()); + const auto nfuncs = nglobals + std::uint32_t(funcs.size()); + auto const_id = [&](std::uint32_t i) { return std::uint64_t(nfuncs + i); }; + w.enter(CONSTANTS_BLOCK, 4); + { + std::optional<Ty> current; + for (const auto& [t, c] : consts) { + if (current != t) { + w.record(1, {std::uint64_t(t.id)}); + current = t; + } + switch (c.kind) { + case Const::Undef: + w.record(3, {}); + break; + case Const::Int: + w.record(4, {signed_vbr(c.value)}); + break; + case Const::Float: + w.record(6, {std::uint64_t(c.bits)}); + break; + case Const::Aggregate: { + std::vector<std::uint64_t> r; + r.reserve(c.ids.size()); + for (std::uint32_t i : c.ids) r.push_back(const_id(i)); + w.record(7, r); + break; + } + } + } + } + w.exit(); + + // Phis nothing reads are left out (one register per phi makes many). + const std::vector<bool> lv = live(); + + // Blocks are laid out in reverse postorder, so every block follows its forward predecessors + // (drivers take a branch to an earlier block for a loop's back edge). + auto succs = [&](std::size_t b) { return successors(blocks[b].term); }; + const std::size_t nblocks = blocks.size(); + std::vector<bool> seen(nblocks, false); + std::vector<std::size_t> post; + std::vector<std::pair<std::size_t, std::size_t>> stack = {{0, 0}}; + seen[0] = true; + while (!stack.empty()) { + auto& top = stack.back(); + auto [b, k] = top; + top.second += 1; + Succs s = succs(b); + if (k < s.size()) { + std::size_t n = s.to[k]; + if (!seen[n]) { + seen[n] = true; + stack.push_back({n, 0}); + } + } else { + post.push_back(b); + stack.pop_back(); + } + } + std::vector<std::size_t> rpo(post.rbegin(), post.rend()); + constexpr std::uint64_t NONE = ~std::uint64_t(0); + std::vector<std::uint64_t> pos(nblocks, NONE); + for (std::size_t n = 0; n < rpo.size(); ++n) pos[rpo[n]] = n; + // An empty latch (only a branch back to its loop header) is folded into its one predecessor, + // so the exiting block is the latch as in DXC's loops; the AMD driver hangs on divergent loops + // otherwise. + std::vector<std::vector<std::size_t>> preds(nblocks); + for (std::size_t b : rpo) + for (std::size_t s : succs(b)) preds[s].push_back(b); + std::vector<std::optional<std::pair<std::size_t, std::size_t>>> fold(nblocks); + for (std::size_t b : rpo) { + const Block& blk = blocks[b]; + if (!blk.term || blk.term->kind != Term::Br) continue; + bool empty = blk.body.empty(); + for (std::uint32_t i : blk.phis) + if (lv[i]) empty = false; + if (!empty || preds[b].size() != 1) continue; + std::size_t h = blk.term->t; + std::size_t p = preds[b][0]; + if (pos[h] < pos[b] && !succs(p).contains(h)) fold[b] = std::make_pair(p, h); + } + std::vector<std::size_t> layout; + for (std::size_t b : rpo) + if (!fold[b]) layout.push_back(b); + std::fill(pos.begin(), pos.end(), NONE); + for (std::size_t n = 0; n < layout.size(); ++n) pos[layout[n]] = n; + // Branch targets and phi blocks through folded latches. + auto target = [&](std::size_t t) { return fold[t] ? pos[fold[t]->second] : pos[t]; }; + auto from = [&](std::size_t b) { return fold[b] ? pos[fold[b]->first] : pos[b]; }; + + // Instruction value ids, in layout order. + const std::uint32_t base = nfuncs + std::uint32_t(consts.size()); + std::vector<std::uint32_t> ids(insts.size(), UINT32_MAX); + { + std::uint32_t next = base; + for (std::size_t lb : layout) { + const Block& b = blocks[lb]; + for (std::uint32_t i : b.phis) { + if (!lv[i]) continue; + if (!is_void(insts[i].ty)) ids[i] = next++; + } + for (std::uint32_t i : b.body) + if (!is_void(insts[i].ty)) ids[i] = next++; + } + } + auto abs = [&](V v) -> std::uint32_t { + switch (v.kind) { + case V::Global: + return v.i; + case V::Func: + return nglobals + v.i; + case V::Const: + return nfuncs + v.i; + case V::Inst: { + std::uint32_t id = ids[v.i]; + if (id == UINT32_MAX) bug("use of a void value"); + return id; + } + } + bug("abs"); + }; + + w.enter(METADATA_BLOCK, 3); + for (const MdDef& m : mds) { + switch (m.kind) { + case MdDef::Str: + w.record(1, chars(m.str)); + break; + case MdDef::Value: + w.record(2, {std::uint64_t(m.ty.id), std::uint64_t(abs(m.v))}); + break; + case MdDef::Node: { + std::vector<std::uint64_t> r; + r.reserve(m.ops.size()); + for (const auto& o : m.ops) r.push_back(o ? std::uint64_t(o->id) + 1 : 0); + w.record(3, r); + break; + } + } + } + for (const auto& [name, nodes] : named) { + w.record(4, chars(name)); + std::vector<std::uint64_t> r; + r.reserve(nodes.size()); + for (Md m : nodes) r.push_back(m.id); + w.record(10, r); + } + w.exit(); + // The metadata kinds an LLVM 3.7 module declares, as DXC writes them. + w.enter(METADATA_BLOCK, 3); + { + static const char* const kinds[] = {"dbg", + "tbaa", + "prof", + "fpmath", + "range", + "tbaa.struct", + "invariant.load", + "alias.scope", + "noalias", + "nontemporal", + "llvm.mem.parallel_loop_access", + "nonnull", + "dereferenceable", + "dereferenceable_or_null"}; + std::uint64_t id = 0; + for (const char* kind : kinds) { + std::vector<std::uint64_t> r = {id++}; + for (unsigned char c : std::string_view(kind)) r.push_back(c); + w.record(6, r); + } + } + w.exit(); + + w.enter(VALUE_SYMTAB_BLOCK, 4); + { + std::uint64_t i = 0; + auto sym = [&](const std::string& name) { + std::vector<std::uint64_t> r = {i++}; + for (unsigned char c : name) r.push_back(c); + w.record(1, r); + }; + for (const Global& g : globals) sym(g.name); + for (const Func& f : funcs) sym(f.name); + } + w.exit(); + + w.enter(FUNCTION_BLOCK, 4); + w.record(1, {std::uint64_t(layout.size())}); + std::uint32_t inst_id = base; + // The operands of variable-length records, reused across them. + std::vector<std::uint64_t> r; + auto one = [&](std::uint32_t i) { + const Inst& inst = insts[i]; + auto rel = [&](V v) -> std::uint64_t { + std::uint32_t a = abs(v); + if (!(a < inst_id)) bug("forward reference outside a phi"); + return std::uint64_t(inst_id - a); + }; + const Op& op = inst.op; + switch (op.kind) { + case Op::Bin: + w.record(2, {rel(op.a), rel(op.b), std::uint64_t(op.code)}); + break; + case Op::Cast: + w.record(3, {rel(op.a), std::uint64_t(inst.ty.id), std::uint64_t(op.code)}); + break; + case Op::Cmp: + w.record(28, {rel(op.a), rel(op.b), std::uint64_t(op.code)}); + break; + case Op::Select: + w.record(29, {rel(op.b), rel(op.c), rel(op.a)}); + break; + case Op::Extract: + w.record(26, {rel(op.a), std::uint64_t(op.index)}); + break; + case Op::Call: + r.clear(); + r.push_back(0); + r.push_back(1 << 15); + r.push_back(funcs[op.index].ty.id); + r.push_back(rel(V::func(op.index))); + for (V a : op.list) r.push_back(rel(a)); + w.record(34, r); + break; + case Op::Phi: + r.clear(); + r.push_back(inst.ty.id); + for (const auto& [v, b] : op.incoming) { + r.push_back(signed_vbr(std::int64_t(inst_id) - std::int64_t(abs(v)))); + r.push_back(from(b)); + } + w.record(16, r); + break; + case Op::Gep: + r.clear(); + r.push_back(0); + r.push_back(op.ty.id); + r.push_back(rel(op.a)); + for (V x : op.list) r.push_back(rel(x)); + w.record(43, r); + break; + // Alignment 4 (log2 + 1), not volatile. + case Op::Load: + w.record(20, {rel(op.a), std::uint64_t(inst.ty.id), 3, 0}); + break; + case Op::Store: + w.record(44, {rel(op.a), rel(op.b), 3, 0}); + break; + // Sequentially consistent, across threads. + case Op::AtomicRmw: + w.record(38, {rel(op.a), rel(op.b), std::uint64_t(op.code), 0, 6, 1}); + break; + case Op::CmpXchg: + w.record(46, {rel(op.a), rel(op.b), rel(op.c), 0, 6, 1, 6, 0}); + break; + } + if (!is_void(inst.ty)) inst_id += 1; + }; + for (std::size_t lb : layout) { + const Block& b = blocks[lb]; + for (std::uint32_t i : b.phis) + if (lv[i]) one(i); + for (std::uint32_t i : b.body) one(i); + if (!b.term) bug("unterminated block"); + const Term& t = *b.term; + switch (t.kind) { + case Term::Ret: + w.record(10, {}); + break; + case Term::Br: + w.record(11, {target(t.t)}); + break; + case Term::CondBr: { + std::uint32_t a = abs(t.cond); + if (!(a < inst_id)) bug("branch condition after its branch"); + w.record(11, {target(t.t), target(t.f), std::uint64_t(inst_id - a)}); + break; + } + } + } + w.exit(); + w.exit(); + return w.finish(); +} + +std::uint32_t Writer::width() const { return stack.empty() ? 2 : stack.back().first; } + +void Writer::emit(std::uint64_t v, std::uint32_t w) { + cur |= v << bits; + bits += w; + while (bits >= 32) { + words.push_back(std::uint32_t(cur)); + cur >>= 32; + bits -= 32; + } +} + +void Writer::vbr(std::uint64_t v, std::uint32_t w) { + const std::uint64_t hi = std::uint64_t(1) << (w - 1); + while (v >= hi) { + emit((v & (hi - 1)) | hi, w); + v >>= w - 1; + } + emit(v, w); +} + +void Writer::align() { + if (bits > 0) { + words.push_back(std::uint32_t(cur)); + cur = 0; + bits = 0; + } +} + +void Writer::bytes(const std::uint8_t* b, std::size_t n) { + for (std::size_t k = 0; k < n; ++k) emit(b[k], 8); +} + +void Writer::enter(std::uint64_t id, std::uint32_t w) { + emit(1, width()); // ENTER_SUBBLOCK + vbr(id, 8); + vbr(w, 4); + align(); + words.push_back(0); + stack.push_back({w, words.size()}); +} + +void Writer::exit() { + emit(0, width()); // END_BLOCK + align(); + if (stack.empty()) bug("open block"); + std::size_t start = stack.back().second; + stack.pop_back(); + words[start - 1] = std::uint32_t(words.size() - start); +} + +void Writer::record(std::uint64_t code, const std::uint64_t* ops, std::size_t n) { + emit(3, width()); + vbr(code, 6); + vbr(n, 6); + for (std::size_t k = 0; k < n; ++k) vbr(ops[k], 6); +} + +std::vector<std::uint8_t> Writer::finish() { + align(); + std::vector<std::uint8_t> out; + out.reserve(words.size() * 4); + for (std::uint32_t x : words) { + out.push_back(std::uint8_t(x)); + out.push_back(std::uint8_t(x >> 8)); + out.push_back(std::uint8_t(x >> 16)); + out.push_back(std::uint8_t(x >> 24)); + } + return out; +} + +} // namespace x2w::vs::bitcode diff --git a/src/x2w_shader/emit/bitcode.h b/src/x2w_shader/emit/bitcode.h new file mode 100644 index 0000000000..0099902bf7 --- /dev/null +++ b/src/x2w_shader/emit/bitcode.h @@ -0,0 +1,452 @@ +#pragma once + +// A DXIL module and its LLVM 3.7 bitcode, written with unabbreviated records only (the format DXIL fixes; +// codes from LLVM's LLVMBitCodes.h). +// +// Values are symbolic while the module is built (V) and numbered when it is written: functions, +// then constants (all at module level), then the instructions of `main` in block order. +// +// Builder calls assign type, constant, function and instruction numbers. Evaluate them in separate +// statements in the intended order to keep output bytes deterministic. Internal invariant failures throw +// std::logic_error. The trailing underscores on predicate names avoid the macros in windows.h. + +#include <compare> +#include <cstddef> +#include <cstdint> +#include <initializer_list> +#include <optional> +#include <span> +#include <string> +#include <string_view> +#include <unordered_map> +#include <utility> +#include <vector> + +namespace x2w::vs::bitcode { + +namespace census { +struct Census; +} +namespace opt { +struct Usage; +enum class Effect : std::uint8_t; +} + +// Signals a translator invariant failure. +[[noreturn]] void bug(const char* what); + +struct Ty { + std::uint32_t id = 0; + auto operator<=>(const Ty&) const = default; +}; + +// What the lowering made an instruction for, where it says so (counted by census, nothing else +// reads it). +enum class Tag : std::uint8_t { + // The select that keeps a register's old value in lanes a guard masks. + Guard, + // An index clamp the translation adds (the console has none). + Clamp, + // The iteration counter and limit test the translation adds to a loop. + Counter, +}; + +struct TypeDef { + enum Kind : std::uint8_t { Void, Int, Float, Double, Ptr, Struct, Array, Func }; + Kind kind = Void; + // Int: bits. Ptr: address space. Array: element count. + std::uint32_t n = 0; + // Ptr: pointee. Array: element. Func: return type. + Ty of; + // Struct: named (Some) or literal (None). + std::optional<std::string> name; + // Struct: fields. Func: parameters. + std::vector<Ty> list; + bool operator==(const TypeDef&) const = default; +}; + +// Order values by kind (Global < Func < Const < Inst), then by index. +struct V { + enum Kind : std::uint8_t { Global, Func, Const, Inst }; + Kind kind = Const; + std::uint32_t i = 0; + static constexpr V global(std::uint32_t i) { return V{Global, i}; } + static constexpr V func(std::uint32_t i) { return V{Func, i}; } + static constexpr V constant(std::uint32_t i) { return V{Const, i}; } + static constexpr V inst(std::uint32_t i) { return V{Inst, i}; } + bool is_inst() const { return kind == Inst; } + auto operator<=>(const V&) const = default; +}; + +struct VHash { + std::size_t operator()(const V& v) const noexcept { + return std::hash<std::uint64_t>{}((std::uint64_t(v.kind) << 32) | v.i); + } +}; + +// A global variable declaration (thread-group shared memory, constant tables). +struct Global { + std::string name; + Ty ty; + // Its pointer type. + Ty ptr; + std::uint32_t space = 0; + // An internal constant with this initialiser (a constant table). + std::optional<std::uint32_t> init; +}; + +struct Const { + enum Kind : std::uint8_t { Int, Float, Undef, Aggregate }; + Kind kind = Undef; + std::int64_t value = 0; // Int + std::uint32_t bits = 0; // Float + std::vector<std::uint32_t> ids; // Aggregate: constant ids + bool operator==(const Const&) const = default; +}; + +// LLVM binary opcodes (the same codes serve the float forms). +enum class Bin : std::uint8_t { + Add = 0, + Sub = 1, + Mul = 2, + UDiv = 3, + SDiv = 4, + URem = 5, + Shl = 7, + LShr = 8, + AShr = 9, + And = 10, + Or = 11, + Xor = 12, +}; + +// atomicrmw operations. +enum class Rmw : std::uint8_t { + Xchg = 0, + Add = 1, + Sub = 2, + And = 3, + Or = 5, + Xor = 6, + Max = 7, + Min = 8, + UMax = 9, + UMin = 10, +}; + +enum class Cast : std::uint8_t { + Trunc = 0, + ZExt = 1, + SExt = 2, + FpToUi = 3, + FpToSi = 4, + UiToFp = 5, + SiToFp = 6, + Bitcast = 11, +}; + +// Compare predicates: floats 0-15, integers 32-41. +namespace pred { +inline constexpr std::uint8_t FALSE_ = 0; +inline constexpr std::uint8_t OEQ = 1; +inline constexpr std::uint8_t OGT = 2; +inline constexpr std::uint8_t OGE = 3; +inline constexpr std::uint8_t OLT = 4; +inline constexpr std::uint8_t OLE = 5; +// Not emitted: the AMD D3D12 driver treats it as UNE, so v_cmp_lg lowers as OLT | OGT instead. +inline constexpr std::uint8_t ONE = 6; +inline constexpr std::uint8_t ORD = 7; +inline constexpr std::uint8_t UNO = 8; +inline constexpr std::uint8_t UEQ = 9; +inline constexpr std::uint8_t UGT = 10; +inline constexpr std::uint8_t UGE = 11; +inline constexpr std::uint8_t ULT = 12; +inline constexpr std::uint8_t ULE = 13; +inline constexpr std::uint8_t UNE = 14; +inline constexpr std::uint8_t TRUE_ = 15; +inline constexpr std::uint8_t EQ = 32; +inline constexpr std::uint8_t NE = 33; +inline constexpr std::uint8_t IUGT = 34; +inline constexpr std::uint8_t IUGE = 35; +inline constexpr std::uint8_t IULT = 36; +inline constexpr std::uint8_t IULE = 37; +inline constexpr std::uint8_t SGT = 38; +inline constexpr std::uint8_t SGE = 39; +inline constexpr std::uint8_t SLT = 40; +inline constexpr std::uint8_t SLE = 41; +} // namespace pred + +// An instruction's operation. Which fields hold what, by kind: +// Bin code = Bin, a, b +// Cast code = Cast, a +// Cmp code = predicate, a, b +// Select a = condition, b = true value, c = false value +// Extract a = aggregate, index = field +// Call index = function number, list = arguments +// Phi incoming = (value, block); filled in later +// Gep ty = pointee type, a = pointer, list = indices +// Load a = pointer +// Store a = pointer, b = value +// AtomicRmw code = Rmw, a = pointer, b = value +// CmpXchg a = pointer, b = expected, c = new; returns {i32, i1} +struct Op { + enum Kind : std::uint8_t { Bin, Cast, Cmp, Select, Extract, Call, Phi, Gep, Load, Store, AtomicRmw, CmpXchg }; + Kind kind = Bin; + std::uint8_t code = 0; + V a, b, c; + std::uint32_t index = 0; + Ty ty; + std::vector<V> list; + std::vector<std::pair<V, std::size_t>> incoming; +}; + +struct Inst { + Ty ty; + Op op; +}; + +struct Term { + enum Kind : std::uint8_t { Br, CondBr, Ret }; + Kind kind = Ret; + V cond; + std::size_t t = 0; + std::size_t f = 0; + static Term br(std::size_t to) { return Term{Br, V{}, to, 0}; } + static Term cond_br(V c, std::size_t t, std::size_t f) { return Term{CondBr, c, t, f}; } + static Term ret() { return Term{Ret, V{}, 0, 0}; } +}; + +struct Block { + std::vector<std::uint32_t> phis; + std::vector<std::uint32_t> body; + std::optional<Term> term; +}; + +// Function attributes of a dx.op declaration. +enum class Attr : std::uint8_t { + ReadNone = 1, + NoUnwind = 2, + ReadOnly = 3, + // Barriers. + NoDuplicate = 4, +}; + +struct Func { + std::string name; + Ty ty; + std::optional<Attr> attr; + bool body = false; +}; + +// A metadata node operand. +struct Md { + std::uint32_t id = 0; + auto operator<=>(const Md&) const = default; +}; + +struct MdDef { + enum Kind : std::uint8_t { Str, Value, Node }; + Kind kind = Str; + std::string str; + Ty ty; + V v; + std::vector<std::optional<Md>> ops; +}; + +struct TypeDefHash { + std::size_t operator()(const TypeDef& t) const noexcept; +}; +struct ConstKeyHash { + std::size_t operator()(const std::pair<Ty, Const>& k) const noexcept; +}; + +// A block's successors (at most two). +struct Succs { + std::size_t to[2] = {0, 0}; + std::size_t len = 0; + const std::size_t* begin() const { return to; } + const std::size_t* end() const { return to + len; } + std::size_t size() const { return len; } + bool empty() const { return len == 0; } + bool contains(std::size_t b) const { + for (std::size_t k = 0; k < len; ++k) + if (to[k] == b) return true; + return false; + } +}; + +Succs successors(const std::optional<Term>& term); + +// Calls f with every value op reads, in operand order. +template <class F> +void for_each_operand(const Op& op, F&& f) { + switch (op.kind) { + case Op::Bin: + case Op::Cmp: + case Op::Store: + case Op::AtomicRmw: + f(op.a); + f(op.b); + break; + case Op::Cast: + case Op::Extract: + case Op::Load: + f(op.a); + break; + case Op::Select: + case Op::CmpXchg: + f(op.a); + f(op.b); + f(op.c); + break; + case Op::Call: + for (V v : op.list) f(v); + break; + case Op::Phi: + for (const auto& x : op.incoming) f(x.first); + break; + case Op::Gep: + f(op.a); + for (V v : op.list) f(v); + break; + } +} + +// The optimizer and instruction census access the module members directly. +struct Module { + std::vector<TypeDef> types; + std::unordered_map<TypeDef, std::uint32_t, TypeDefHash> type_ids; + std::vector<std::pair<Ty, Const>> consts; + std::unordered_map<std::pair<Ty, Const>, std::uint32_t, ConstKeyHash> const_ids; + std::vector<Global> globals; + std::vector<Func> funcs; + std::unordered_map<std::string, std::uint32_t> func_ids; + std::vector<Inst> insts; + std::vector<Block> blocks; + std::vector<MdDef> mds; + std::vector<std::pair<std::string, std::vector<Md>>> named; + // See Tag: by instruction. + std::unordered_map<std::uint32_t, Tag> tags; + + Ty ty(const TypeDef& def); + Ty void_(); + Ty int_(std::uint32_t bits); + Ty float_(); + Ty double_(); + Ty ptr(Ty to); + Ty ptr_in(Ty to, std::uint32_t space); + Ty array(std::uint32_t n, Ty of); + Ty named_struct(std::string_view name, std::vector<Ty> fields); + Ty func_ty(Ty ret, std::vector<Ty> params); + bool is_void(Ty t) const; + + V constant(Ty ty, const Const& c); + V int_const(Ty ty, std::int64_t v); + V i32(std::uint32_t v); + V i8(std::uint8_t v); + V bool_(bool v); + V f32(std::uint32_t bits); + V undef(Ty ty); + // A constant struct or array of constants. + V aggregate(Ty ty, std::span<const V> fields); + V aggregate(Ty ty, std::initializer_list<V> fields) { + return aggregate(ty, std::span<const V>(fields.begin(), fields.size())); + } + // The value of an integer constant; nullopt for anything else. + std::optional<std::int64_t> int_value(V v) const; + // Gives constant `old` the content of `new_` (both stay valid). + void replace_const(V old, V new_); + + // A function declaration (or `main` with `body`), found by name. + V function(std::string_view name, Ty ty, std::optional<Attr> attr, bool body); + // An external global of type `ty` in address space `space` (DXIL declares thread-group shared + // memory this way). + V global(std::string_view name, Ty ty, std::uint32_t space); + // An internal constant global initialised with the constant `init`. + V constant_global(std::string_view name, V init); + // Notes what instruction v is for (see Tag); only when modules are counted. + void tag(V v, Tag tag); + + std::size_t new_block(); + Ty type_of(V v) const; + + V push(std::size_t block, Ty ty, Op op); + V bin(std::size_t block, Bin op, V a, V b); + V cast(std::size_t block, Cast op, V v, Ty to); + V cmp(std::size_t block, std::uint8_t pred, V a, V b); + V select(std::size_t block, V c, V t, V f); + V extract(std::size_t block, V agg, std::uint32_t index); + V call(std::size_t block, V f, std::vector<V> args); + // A phi at the top of block; incoming values come with set_phi. + V phi(std::size_t block, Ty ty); + // The address of element index of the array ptr points to. + V element(std::size_t block, V ptr, V index); + V load(std::size_t block, V ptr); + void store(std::size_t block, V ptr, V value); + V atomic(std::size_t block, Rmw op, V ptr, V value); + // The old value of a compare-exchange. + V cmpxchg(std::size_t block, V ptr, V expected, V new_); + + void set_phi(V phi, std::vector<std::pair<V, std::size_t>> incoming); + void terminate(std::size_t block, Term t); + + Md md_str(std::string_view s); + Md md_value(V v); + Md md_node(std::vector<std::optional<Md>> ops); + void named_md(std::string_view name, std::vector<Md> nodes); + + // Which instructions are written: every body instruction, the branch conditions, and whatever + // they read, transitively (a phi nothing reads is dropped). + std::vector<bool> live() const; + // The module as bitcode. + std::vector<std::uint8_t> write() const; + + // opt.cpp. Runs the clean-up passes named in `passes` (opt::ALL: every one). + void optimise(std::uint32_t passes); + // Per function: what a call of it does. + std::vector<opt::Effect> effects() const; + // The blocks reached from the entry. + std::vector<bool> reached() const; + // An integer constant: its width and its bits. + std::optional<std::pair<std::uint32_t, std::uint64_t>> int_k(V v) const; + // A float constant's value. + std::optional<float> float_k(V v) const; + // A bound on |v| (see opt.cpp). + std::optional<float> bounded(V v, std::uint32_t depth) const; + // What the written instructions use, of the features a shader declares by flag. + opt::Usage usage() const; + + // census.cpp: the instructions write() writes, by kind. + census::Census census() const; +}; + +// LLVM's signed VBR operand: magnitude shifted left, sign in bit 0. +std::uint64_t signed_vbr(std::int64_t v); + +// The bitstream: little-endian 32-bit words filled from bit 0. +struct Writer { + std::vector<std::uint32_t> words; + std::uint64_t cur = 0; + std::uint32_t bits = 0; + // Per open block: abbreviation width, index of its length word. + std::vector<std::pair<std::uint32_t, std::size_t>> stack; + + std::uint32_t width() const; + void emit(std::uint64_t v, std::uint32_t width); + void vbr(std::uint64_t v, std::uint32_t width); + void align(); + void bytes(const std::uint8_t* b, std::size_t n); + void enter(std::uint64_t id, std::uint32_t width); + void exit(); + // An unabbreviated record. + void record(std::uint64_t code, const std::uint64_t* ops, std::size_t n); + void record(std::uint64_t code, const std::vector<std::uint64_t>& ops) { + record(code, ops.data(), ops.size()); + } + void record(std::uint64_t code, std::initializer_list<std::uint64_t> ops) { + record(code, ops.begin(), ops.size()); + } + std::vector<std::uint8_t> finish(); +}; + +} // namespace x2w::vs::bitcode diff --git a/src/x2w_shader/emit/census.cpp b/src/x2w_shader/emit/census.cpp new file mode 100644 index 0000000000..5cc0e62476 --- /dev/null +++ b/src/x2w_shader/emit/census.cpp @@ -0,0 +1,174 @@ + +#include "x2w_shader/emit/census.h" + +#include <algorithm> +#include <cstdlib> +#include <string_view> +#include <tuple> +#include <utility> +#include <vector> + +namespace x2w::vs::bitcode::census { + +namespace { + +// The modules this thread wrote since the last take(): the length and a hash of each one's +// bitcode, with its counts (a program may be emitted in several forms before one is kept). +thread_local std::vector<std::tuple<std::size_t, std::uint64_t, Census>> written; + +std::uint64_t fnv(std::span<const std::uint8_t> bytes) { + std::uint64_t h = 0xcbf29ce484222325ull; + for (std::uint8_t b : bytes) h = (h ^ b) * 0x00000100000001b3ull; + return h; +} + +std::size_t k(std::string_view s) { + for (std::size_t i = 0; i < KINDS.size(); ++i) + if (s == KINDS[i]) return i; + bug("kind"); +} + +bool starts(std::string_view s, std::string_view p) { return s.substr(0, p.size()) == p; } + +} // namespace + +std::size_t kind(std::string_view name) { + std::string_view n = starts(name, "dx.op.") ? name.substr(6) : name; + n = n.substr(0, n.find('.')); + if (n == "unary" || n == "binary" || n == "tertiary" || n == "unaryBits" || n == "legacyF16ToF32" || + n == "legacyF32ToF16" || n == "isSpecialFloat" || n == "dot2" || n == "dot3" || n == "dot4" || + n == "quaternary") + return k("math_call"); + if (n == "bufferLoad" || n == "rawBufferLoad") return k("buffer_load"); + if (n == "cbufferLoadLegacy" || n == "cbufferLoad") return k("cbuffer_load"); + if (n == "bufferStore" || n == "rawBufferStore" || n == "textureStore") return k("buffer_store"); + if (n == "atomicBinOp" || n == "atomicCompareExchange") return k("atomic"); + if (n == "createHandle" || n == "createHandleFromBinding" || n == "createHandleFromHeap") return k("handle"); + if (n == "annotateHandle") return k("annotate"); + if (n == "getDimensions") return k("dimensions"); + if (n == "barrier") return k("barrier"); + if (starts(n, "wave") || starts(n, "quad")) return k("wave_op"); + if (starts(n, "textureLoad") || starts(n, "sample") || starts(n, "textureGather") || starts(n, "calculateLOD")) + return k("texture_read"); + return k("io_other"); +} + +bool enabled() { + static const bool on = std::getenv("X2W_SHADERCFG_SHADER_CENSUS") != nullptr; + return on; +} + +std::optional<Census> take(std::span<const std::uint8_t> dxil) { + auto list = std::exchange(written, {}); + const std::uint8_t magic[4] = {'B', 'C', 0xC0, 0xDE}; + auto it = std::search(dxil.begin(), dxil.end(), magic, magic + 4); + if (it == dxil.end()) return std::nullopt; + auto at = std::size_t(it - dxil.begin()); + for (auto r = list.rbegin(); r != list.rend(); ++r) { + auto& [len, hash, c] = *r; + if (at + len <= dxil.size() && fnv(dxil.subspan(at, len)) == hash) return c; + } + return std::nullopt; +} + +void note(const Module& m, std::span<const std::uint8_t> bitcode) { + if (!enabled()) return; + Census c = m.census(); + written.emplace_back(bitcode.size(), fnv(bitcode), c); +} + +} // namespace x2w::vs::bitcode::census + +namespace x2w::vs::bitcode { + +census::Census Module::census() const { + auto k = [](std::string_view s) { + for (std::size_t i = 0; i < census::KINDS.size(); ++i) + if (s == census::KINDS[i]) return i; + bug("kind"); + }; + std::vector<std::size_t> call_kind; + call_kind.reserve(funcs.size()); + for (const Func& f : funcs) call_kind.push_back(census::kind(f.name)); + const std::vector<bool> lv = live(); + // The blocks write() lays out: those reached from the entry. + std::vector<bool> seen(blocks.size(), false); + std::vector<std::size_t> stack = {0}; + if (!blocks.empty()) seen[0] = true; + while (!stack.empty()) { + std::size_t b = stack.back(); + stack.pop_back(); + for (std::size_t s : successors(blocks[b].term)) { + if (!seen[s]) { + seen[s] = true; + stack.push_back(s); + } + } + } + census::Census c; + for (std::size_t b = 0; b < blocks.size(); ++b) { + if (!seen[b]) continue; + const Block& blk = blocks[b]; + c.counts[k("blocks")] += 1; + auto count = [&](std::uint32_t i) { + c.counts[0] += 1; + const Op& op = insts[i].op; + std::size_t at = 0; + switch (op.kind) { + case Op::Bin: + case Op::Cmp: + at = k("arith"); + break; + case Op::Cast: + at = op.code == std::uint8_t(Cast::Bitcast) ? k("bitcast") : k("cast"); + break; + case Op::Select: + at = k("select"); + break; + case Op::Extract: + at = k("extract"); + break; + case Op::Phi: + at = k("phi"); + break; + case Op::Gep: + at = k("gep"); + break; + case Op::Load: + at = k("lds_load"); + break; + case Op::Store: + at = k("lds_store"); + break; + case Op::AtomicRmw: + case Op::CmpXchg: + at = k("atomic"); + break; + case Op::Call: + at = call_kind[op.index]; + break; + } + c.counts[at] += 1; + auto t = tags.find(i); + if (t != tags.end()) { + switch (t->second) { + case Tag::Guard: + c.counts[k("guard_select")] += 1; + break; + case Tag::Clamp: + c.counts[k("clamp")] += 1; + break; + case Tag::Counter: + c.counts[k("loop_counter")] += 1; + break; + } + } + }; + for (std::uint32_t i : blk.phis) + if (lv[i]) count(i); + for (std::uint32_t i : blk.body) count(i); + } + return c; +} + +} // namespace x2w::vs::bitcode diff --git a/src/x2w_shader/emit/census.h b/src/x2w_shader/emit/census.h new file mode 100644 index 0000000000..850a10151d --- /dev/null +++ b/src/x2w_shader/emit/census.h @@ -0,0 +1,45 @@ +#pragma once + +// Counts of a module's instructions by kind (a diagnostic): what a translated program costs before the +// driver's compiler sees it. +// +// X2W_SHADERCFG_SHADER_CENSUS (any value) turns the counting on; the counts of the module a thread +// wrote last are read with take(). + +#include <array> +#include <cstdint> +#include <optional> +#include <span> + +#include "x2w_shader/emit/bitcode.h" + +namespace x2w::vs::bitcode::census { + +// The kinds, in the order of Census::counts. +inline constexpr std::array<const char*, 26> KINDS = { + "total", "arith", "math_call", "bitcast", "cast", "select", "guard_select", + "phi", "extract", "buffer_load", "cbuffer_load", "texture_read", "lds_load", "buffer_store", + "lds_store", "atomic", "handle", "annotate", "dimensions", "barrier", "wave_op", + "io_other", "gep", "clamp", "loop_counter", "blocks", +}; + +// Instruction counts of one written module, by KINDS. +struct Census { + std::array<std::uint32_t, KINDS.size()> counts{}; + bool operator==(const Census&) const = default; +}; + +// Whether modules are counted (X2W_SHADERCFG_SHADER_CENSUS set). +bool enabled(); + +// The counts of the module whose bitcode the container `dxil` holds, if this thread wrote it +// since the last call (which forgets the others). +std::optional<Census> take(std::span<const std::uint8_t> dxil); + +// Counts m, whose written form is `bitcode`, and keeps the result for take(). +void note(const Module& m, std::span<const std::uint8_t> bitcode); + +// The kind (index into KINDS) of a call of the function `name`. +std::size_t kind(std::string_view name); + +} // namespace x2w::vs::bitcode::census diff --git a/src/x2w_shader/emit/cmake/dxil.cmake b/src/x2w_shader/emit/cmake/dxil.cmake new file mode 100644 index 0000000000..598091c013 --- /dev/null +++ b/src/x2w_shader/emit/cmake/dxil.cmake @@ -0,0 +1,17 @@ +# Build the shader container, rectangle stage, settings, and signature readers. Requires opt. +add_library(x2w_vs_emit_dxil STATIC + "${CMAKE_CURRENT_SOURCE_DIR}/container.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/shader.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/settings.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/mod_signature.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/rect.cpp") +x2w_vs_emit_options(x2w_vs_emit_dxil) +target_link_libraries(x2w_vs_emit_dxil PUBLIC x2w_vs_emit_opt x2w_vs_emit_base x2w_shader) + +# Compare emitted containers against reference outputs in tests/x2w_shader/emit/ref. +set(x2w_vs_ref "${x2w_vs_emit_tests}/ref") +x2w_vs_emit_test(ref_test x2w_vs_emit_dxil) +set_tests_properties(x2w_vs_ref_test PROPERTIES ENVIRONMENT "X2W_REF_DIR=${x2w_vs_ref}/out") +add_test(NAME x2w_vs_ref_test_opt0 COMMAND x2w_vs_ref_test) +set_tests_properties(x2w_vs_ref_test_opt0 PROPERTIES ENVIRONMENT "X2W_REF_DIR=${x2w_vs_ref}/out_opt0;X2W_SHADERCFG_SHADER_OPT=0") +x2w_vs_emit_test(container_test x2w_vs_emit_dxil) diff --git a/src/x2w_shader/emit/cmake/host.cmake b/src/x2w_shader/emit/cmake/host.cmake new file mode 100644 index 0000000000..5de2671d4f --- /dev/null +++ b/src/x2w_shader/emit/cmake/host.cmake @@ -0,0 +1,21 @@ +# DXIL validator (dxil.dll) and D3D12 test host. +# host.cpp reads signature parts and builds the stub shaders (x2w_vs_emit_dxil: shader.cpp, +# mod_signature.cpp; x2w_shader: dxbc.cpp); its HostShader stub_vs/stub_ps wrappers compile once +# x2w_shader/native.h exists. +# Build alone with -DX2W_VS_EMIT_ONLY="opt;dxil;host". +add_library(x2w_vs_emit_host STATIC + "${CMAKE_CURRENT_SOURCE_DIR}/validator.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/host.cpp") +x2w_vs_emit_options(x2w_vs_emit_host) +target_link_libraries(x2w_vs_emit_host PUBLIC x2w_vs_emit_dxil x2w_vs_emit_base x2w_shader d3d12 dxgi) + +x2w_vs_emit_test(validator_test x2w_vs_emit_host) +x2w_vs_emit_test(host_test x2w_vs_emit_host) + +# Validate the same reference containers used by ref_test. +if(DEFINED x2w_vs_ref) + x2w_vs_emit_test(ref_validate_test x2w_vs_emit_host) + set_tests_properties(x2w_vs_ref_validate_test PROPERTIES ENVIRONMENT "X2W_REF_DIR=${x2w_vs_ref}/out") + add_test(NAME x2w_vs_ref_validate_test_opt0 COMMAND x2w_vs_ref_validate_test) + set_tests_properties(x2w_vs_ref_validate_test_opt0 PROPERTIES ENVIRONMENT "X2W_REF_DIR=${x2w_vs_ref}/out_opt0") +endif() diff --git a/src/x2w_shader/emit/cmake/lower.cmake b/src/x2w_shader/emit/cmake/lower.cmake new file mode 100644 index 0000000000..06867cc178 --- /dev/null +++ b/src/x2w_shader/emit/cmake/lower.cmake @@ -0,0 +1,30 @@ +# Lower console IR to host DXIL using shader, container and front-end data. +set(x2w_vs_lower_sources + lower_free lower_core lower_input_mem lower_ops_lanes lower_ds_sop lower_smem lower_desc + lower_valu lower_valu16 lower_int_cmp_interp lower_image lower_buffer_exit lower_intersect) +list(TRANSFORM x2w_vs_lower_sources PREPEND "${CMAKE_CURRENT_SOURCE_DIR}/") +list(TRANSFORM x2w_vs_lower_sources APPEND ".cpp") +add_library(x2w_vs_emit_lower STATIC ${x2w_vs_lower_sources}) +x2w_vs_emit_options(x2w_vs_emit_lower) +if(MSVC) + target_compile_options(x2w_vs_emit_lower PRIVATE /bigobj) +endif() +# wave.cmake comes later in the fragment order; the name resolves at generate time (wave also links +# lower: own_bits calls reads_mask_as_data, a cycle CMake handles for static libraries). +target_link_libraries(x2w_vs_emit_lower PUBLIC x2w_vs_emit_dxil x2w_vs_emit_opt x2w_vs_emit_wave x2w_shader) +x2w_vs_emit_test(lower_test x2w_vs_emit_lower) + +# Validate lowered programs with dxil.dll when available, then run them on the host GPU or WARP. +if(TARGET x2w_vs_emit_host) + foreach(t IN ITEMS lower_valu_test lower_waterfall_test lower_wave64_test lower_permlane_test + lower_cube_lod_test lower_probe_test lower_size_test) + # HostShader::user_data_dwords (host::Stage reads it) lives in mod.cpp, the translate + # fragment's x2w_vs_emit (defined after this fragment; linked when it exists). + x2w_vs_emit_test(${t} x2w_vs_emit_lower x2w_vs_emit_host "$<TARGET_NAME_IF_EXISTS:x2w_vs_emit>") + endforeach() + # the_record_count_of_a_structured_buffer_read_by_index crashes the process. Run the remaining + # cases separately. See board/msgs/112707_vs-emit_to-vs-lower_size-test.md. + set_tests_properties(x2w_vs_lower_size_test PROPERTIES DISABLED TRUE) + add_test(NAME x2w_vs_lower_size_test_skip_record_count + COMMAND x2w_vs_lower_size_test --skip the_record_count_of_a_structured_buffer_read_by_index) +endif() diff --git a/src/x2w_shader/emit/cmake/opt.cmake b/src/x2w_shader/emit/cmake/opt.cmake new file mode 100644 index 0000000000..1f9c5dc39e --- /dev/null +++ b/src/x2w_shader/emit/cmake/opt.cmake @@ -0,0 +1,6 @@ +# Clean-up passes over a finished module. +add_library(x2w_vs_emit_opt STATIC "${CMAKE_CURRENT_SOURCE_DIR}/opt.cpp") +x2w_vs_emit_options(x2w_vs_emit_opt) +target_link_libraries(x2w_vs_emit_opt PUBLIC x2w_vs_emit_base) + +x2w_vs_emit_test(opt_test x2w_vs_emit_opt x2w_vs_emit_base) diff --git a/src/x2w_shader/emit/cmake/wave.cmake b/src/x2w_shader/emit/cmake/wave.cmake new file mode 100644 index 0000000000..ba7e564fcf --- /dev/null +++ b/src/x2w_shader/emit/cmake/wave.cmake @@ -0,0 +1,50 @@ +# Whole-wave sections, jump threading, and per-lane bit tracking. +# +# x2w_vs_emit_wave needs vs-core's ir (x2w_shader); threading.cpp and own_bits.cpp also need +# vs-front's structure.h/.cpp (in x2w_shader), and own_bits.cpp vs-lower's +# lower::reads_mask_as_data (x2w_vs_emit_lower, whose fragment lower.cmake comes before this one). +# What is not in the tree yet is left out, with a message. + +set(x2w_vs_wave_sources wave.cpp) +set(x2w_vs_wave_have_structure OFF) +if(EXISTS "${x2w_vs_src}/x2w_shader/structure.h") + set(x2w_vs_wave_have_structure ON) + list(APPEND x2w_vs_wave_sources threading.cpp own_bits.cpp) +else() + message(STATUS "x2w_vs_emit_wave: no x2w_shader/structure.h (vs-front) yet: threading and own_bits left out") +endif() +add_library(x2w_vs_emit_wave STATIC ${x2w_vs_wave_sources}) +x2w_vs_emit_options(x2w_vs_emit_wave) +target_link_libraries(x2w_vs_emit_wave PUBLIC x2w_vs_emit_base x2w_shader) + +x2w_vs_emit_test(wave_test x2w_vs_emit_wave) +# (all of wave_test's tests: ir::build is in x2w_shader) +target_compile_definitions(x2w_vs_wave_test PRIVATE X2W_VS_HAVE_IR) + +# threading_test and own_bits_test need structure.cpp linked (in x2w_shader). +set(x2w_vs_wave_have_structure_impl OFF) +if(x2w_vs_wave_have_structure) + get_target_property(x2w_vs_shader_sources x2w_shader SOURCES) + foreach(s IN LISTS x2w_vs_shader_sources) + if(s MATCHES "structure\\.cpp$") + set(x2w_vs_wave_have_structure_impl ON) + endif() + endforeach() +endif() +if(x2w_vs_wave_have_structure_impl) + x2w_vs_emit_test(threading_test x2w_vs_emit_wave) + if(TARGET x2w_vs_emit_lower) + x2w_vs_emit_test(own_bits_test x2w_vs_emit_wave x2w_vs_emit_lower) + else() + message(STATUS "x2w_vs_emit_wave: no x2w_vs_emit_lower (vs-lower) yet: own_bits_test left out") + endif() +elseif(x2w_vs_wave_have_structure) + message(STATUS "x2w_vs_emit_wave: structure.cpp (vs-front) not in x2w_shader: threading_test, own_bits_test left out") +endif() + +# The lowering reads wave sections and own bits, and own_bits.cpp reads the lowering's +# reads_mask_as_data: the two static libraries depend on each other (CMake repeats them on links). +if(TARGET x2w_vs_emit_lower) + target_link_libraries(x2w_vs_emit_lower PUBLIC x2w_vs_emit_wave) + target_link_libraries(x2w_vs_emit_wave PUBLIC x2w_vs_emit_lower) +endif() diff --git a/src/x2w_shader/emit/cmake/x_translate.cmake b/src/x2w_shader/emit/cmake/x_translate.cmake new file mode 100644 index 0000000000..04cd233720 --- /dev/null +++ b/src/x2w_shader/emit/cmake/x_translate.cmake @@ -0,0 +1,23 @@ +# Translation and emission entry points. Requires lowering +# (vs-lower's x2w_vs_emit_lower), the front end (vs-front) and wave/threading. +if(TARGET x2w_vs_emit_lower AND TARGET x2w_vs_emit_wave) + # The translator's source fingerprint (fingerprint.cmake), made at every build so that an edit of any + # x2w_shader source changes translation_fingerprint(); the header is rewritten only when it changes. + file(GLOB_RECURSE x2w_vs_fp_files CONFIGURE_DEPENDS "${x2w_vs_src}/x2w_shader/*.h" "${x2w_vs_src}/x2w_shader/*.cpp") + set(x2w_vs_fp_dir "${CMAKE_CURRENT_BINARY_DIR}/x2w_vs_fingerprint") + add_custom_command(OUTPUT "${x2w_vs_fp_dir}/x2w_vs_fingerprint.stamp" + COMMAND "${CMAKE_COMMAND}" "-DSRC=${x2w_vs_src}" "-DOUT=${x2w_vs_fp_dir}/x2w_vs_fingerprint.h" + -P "${CMAKE_CURRENT_SOURCE_DIR}/fingerprint.cmake" + COMMAND "${CMAKE_COMMAND}" -E touch "${x2w_vs_fp_dir}/x2w_vs_fingerprint.stamp" + DEPENDS ${x2w_vs_fp_files} "${CMAKE_CURRENT_SOURCE_DIR}/fingerprint.cmake" + BYPRODUCTS "${x2w_vs_fp_dir}/x2w_vs_fingerprint.h" + COMMENT "x2w_shader translator fingerprint") + add_custom_target(x2w_vs_fingerprint DEPENDS "${x2w_vs_fp_dir}/x2w_vs_fingerprint.stamp") + + add_library(x2w_vs_emit STATIC "${CMAKE_CURRENT_SOURCE_DIR}/mod.cpp") + x2w_vs_emit_options(x2w_vs_emit) + add_dependencies(x2w_vs_emit x2w_vs_fingerprint) + target_include_directories(x2w_vs_emit PRIVATE "${x2w_vs_fp_dir}") + target_compile_definitions(x2w_vs_emit PRIVATE X2W_VS_FINGERPRINT_HEADER) + target_link_libraries(x2w_vs_emit PUBLIC x2w_vs_emit_lower x2w_vs_emit_wave x2w_vs_emit_dxil) +endif() diff --git a/src/x2w_shader/emit/cmake/y_tool.cmake b/src/x2w_shader/emit/cmake/y_tool.cmake new file mode 100644 index 0000000000..76529a4ef9 --- /dev/null +++ b/src/x2w_shader/emit/cmake/y_tool.cmake @@ -0,0 +1,34 @@ +# The x2w shaders command-line tool (tools/x2w). The parts that need no translator (BLAKE3, SGD5, the container scan and +# the export loop) and their tests are built always; the dump itself and the `x2w` executable only +# once the translator library (x2w_vs_emit, x_translate.cmake) exists. Named y_ so that it is +# included after x_translate.cmake. +set(x2w_tool_dir "${x2w_vs_root}/tools/x2w") +set(x2w_tool_tests "${x2w_vs_root}/tests/x2w_tool") + +add_library(x2w_tool_base STATIC + "${x2w_tool_dir}/blake3.cpp" + "${x2w_tool_dir}/sgd5.cpp" + "${x2w_tool_dir}/scan.cpp") +x2w_vs_emit_options(x2w_tool_base) +target_include_directories(x2w_tool_base PUBLIC "${x2w_tool_dir}") +target_link_libraries(x2w_tool_base PUBLIC x2w_shader) + +foreach(t blake3_test sgd5_test scan_test) + add_executable(x2w_tool_${t} "${x2w_tool_tests}/${t}.cpp") + x2w_vs_emit_options(x2w_tool_${t}) + target_include_directories(x2w_tool_${t} PRIVATE "${x2w_vs_emit_tests}") + target_link_libraries(x2w_tool_${t} PRIVATE x2w_tool_base) + add_test(NAME x2w_tool_${t} COMMAND x2w_tool_${t}) +endforeach() + +if(TARGET x2w_vs_emit) + add_library(x2w_tool_dump STATIC "${x2w_tool_dir}/shaders_dump.cpp") + x2w_vs_emit_options(x2w_tool_dump) + target_compile_definitions(x2w_tool_dump PRIVATE "X2W_TOOL_SOURCE_DIR=\"${x2w_vs_root}\"") + target_link_libraries(x2w_tool_dump PUBLIC x2w_tool_base x2w_vs_emit d3d12 dxgi) + + add_executable(x2w_tool_exe "${x2w_tool_dir}/main.cpp") + x2w_vs_emit_options(x2w_tool_exe) + set_target_properties(x2w_tool_exe PROPERTIES OUTPUT_NAME x2w) + target_link_libraries(x2w_tool_exe PRIVATE x2w_tool_dump) +endif() diff --git a/src/x2w_shader/emit/cmake/z_difftests.cmake b/src/x2w_shader/emit/cmake/z_difftests.cmake new file mode 100644 index 0000000000..94031d7898 --- /dev/null +++ b/src/x2w_shader/emit/cmake/z_difftests.cmake @@ -0,0 +1,12 @@ +# Run translated and lowered shaders on the host GPU. The z_ prefix places these tests after +# the fragments defining their targets. +# rect_test needs only the DXIL writer and the host. +if(TARGET x2w_vs_emit_host) + x2w_vs_emit_test(rect_test x2w_vs_emit_host) +endif() +# diff_test (the console's dxc against the PC's: X2W_SHADERCFG_CONSOLE_DXC, X2W_SHADERCFG_PC_DXC, X2W_SHADERCFG_WARP) +# and intersect_test (the BVH node test against bvh.cpp's reference) need the translator. +if(TARGET x2w_vs_emit AND TARGET x2w_vs_emit_host) + x2w_vs_emit_test(diff_test x2w_vs_emit x2w_vs_emit_host) + x2w_vs_emit_test(intersect_test x2w_vs_emit x2w_vs_emit_lower x2w_vs_emit_host) +endif() diff --git a/src/x2w_shader/emit/cmake/z_modtests.cmake b/src/x2w_shader/emit/cmake/z_modtests.cmake new file mode 100644 index 0000000000..e2cf21ec6b --- /dev/null +++ b/src/x2w_shader/emit/cmake/z_modtests.cmake @@ -0,0 +1,15 @@ +# Translation, atomic and barycentric tests run +# over the whole translator (x2w_vs_emit, cmake/x_translate.cmake) and the D3D12 test host and +# validator (x2w_vs_emit_host, cmake/host.cmake). The GPU and dxc/dxil.dll parts skip, and say so, +# where there is no device or Windows SDK. +if(TARGET x2w_vs_emit AND TARGET x2w_vs_emit_host) + x2w_vs_emit_test(mod_test x2w_vs_emit x2w_vs_emit_host) + # scalar_buffer_loads_read_the_same_dwords_one_call_or_four: "run the test once plain and once + # with X2W_SHADERCFG_SHADER_OPT=127" (the wide loads, bitcode::opt::WIDE). + add_test(NAME x2w_vs_mod_test_opt127 COMMAND x2w_vs_mod_test) + set_tests_properties(x2w_vs_mod_test_opt127 PROPERTIES ENVIRONMENT "X2W_SHADERCFG_SHADER_OPT=127") + x2w_vs_emit_test(atomic_test x2w_vs_emit x2w_vs_emit_host) + x2w_vs_emit_test(barycentric_test x2w_vs_emit x2w_vs_emit_host) +else() + message(STATUS "z_modtests: no x2w_vs_emit or x2w_vs_emit_host yet: mod_test, atomic_test, barycentric_test left out") +endif() diff --git a/src/x2w_shader/emit/container.cpp b/src/x2w_shader/emit/container.cpp new file mode 100644 index 0000000000..7b019fd0a3 --- /dev/null +++ b/src/x2w_shader/emit/container.cpp @@ -0,0 +1,392 @@ + +#include "x2w_shader/emit/container.h" + +#include <algorithm> +#include <bit> +#include <cstring> +#include <limits> +#include <numeric> +#include <tuple> + +#include "x2w_shader/emit/shader.h" + +namespace x2w::vs::container { + +namespace { + +void put32(std::vector<std::uint8_t>& out, std::uint32_t v) { + out.push_back(std::uint8_t(v)); + out.push_back(std::uint8_t(v >> 8)); + out.push_back(std::uint8_t(v >> 16)); + out.push_back(std::uint8_t(v >> 24)); +} + +void put32_at(std::uint8_t* at, std::uint32_t v) { + at[0] = std::uint8_t(v); + at[1] = std::uint8_t(v >> 8); + at[2] = std::uint8_t(v >> 16); + at[3] = std::uint8_t(v >> 24); +} + +void put16_at(std::uint8_t* at, std::uint16_t v) { + at[0] = std::uint8_t(v); + at[1] = std::uint8_t(v >> 8); +} + +std::optional<std::size_t> find(std::span<const std::uint8_t> hay, std::span<const std::uint8_t> needle) { + if (needle.size() > hay.size()) return std::nullopt; + for (std::size_t i = 0; i + needle.size() <= hay.size(); ++i) + if (std::equal(needle.begin(), needle.end(), hay.begin() + std::ptrdiff_t(i))) return i; + return std::nullopt; +} + +void md5_block(std::array<std::uint32_t, 4>& state, const std::uint8_t* block) { + static constexpr std::uint32_t S[16] = {7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21}; + static constexpr std::uint32_t K[64] = { + 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391, + }; + std::uint32_t x[16]; + for (int i = 0; i < 16; ++i) + x[i] = std::uint32_t(block[4 * i]) | std::uint32_t(block[4 * i + 1]) << 8 | + std::uint32_t(block[4 * i + 2]) << 16 | std::uint32_t(block[4 * i + 3]) << 24; + std::uint32_t a = state[0], b = state[1], c = state[2], d = state[3]; + for (std::uint32_t i = 0; i < 64; ++i) { + std::uint32_t f = 0, g = 0; + switch (i / 16) { + case 0: + f = (b & c) | (~b & d); + g = i; + break; + case 1: + f = (d & b) | (~d & c); + g = (5 * i + 1) % 16; + break; + case 2: + f = b ^ c ^ d; + g = (3 * i + 5) % 16; + break; + default: + f = c ^ (b | ~d); + g = (7 * i) % 16; + break; + } + std::uint32_t rotated = std::rotl(a + f + K[i] + x[g], int(S[(i / 16) * 4 + i % 4])); + std::uint32_t nb = b + rotated; + a = d; + d = c; + c = b; + b = nb; + } + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; +} + +} // namespace + +// (Exposed for the test of the MD5 core.) +void md5_block_for_test(std::array<std::uint32_t, 4>& state, const std::uint8_t* block) { md5_block(state, block); } + +std::uint32_t SigElement::system_value() const { + switch (kind) { + case 1: return 6; // vertex id + case 2: return 8; // instance id + case 3: return 1; // position + case 4: return 4; // render target array index + case 5: return 5; // viewport array index + case 6: return 2; // clip distance + case 7: return 3; // cull distance + case 10: return 7; // primitive id + case 12: return 10; + case 13: return 9; // front face + case 14: return 66; + case 15: return 70; + case 16: return 64; // target + case 17: return 65; // depth + case 18: return 68; + case 19: return 67; + case 20: return 69; + case 28: return 23; // barycentrics + case 30: return 25; // cull primitive + default: return 0; + } +} + +std::uint32_t SigElement::sig_comp() const { + switch (comp) { + case 1: + case 5: + return 1; // bool and u32 + case 4: + return 2; + case 9: + return 3; + default: + return 0; + } +} + +std::uint8_t SigElement::mask() const { return std::uint8_t(((1u << cols) - 1) << col); } + +std::vector<std::uint8_t> signature(std::span<const SigElement> elements, bool input) { + std::vector<std::uint8_t> out; + put32(out, std::uint32_t(elements.size())); + put32(out, 8); + // Validator 1.6 writes one name per element in element order, repeats included, except that + // system values share theirs (it keys names by the semantic's string, which is one static + // string per system value); the rows sorted by register (unallocated last), then name offset. + std::vector<std::uint32_t> offsets; + std::uint32_t next = 8 + 32 * std::uint32_t(elements.size()); + std::vector<const std::string*> names; + for (std::size_t i = 0; i < elements.size(); ++i) { + const SigElement& e = elements[i]; + std::optional<std::size_t> shared; + if (e.kind != 0) { + for (std::size_t j = 0; j < i; ++j) + if (elements[j].kind == e.kind) { + shared = j; + break; + } + } + if (shared) { + offsets.push_back(offsets[*shared]); + } else { + offsets.push_back(next); + next += std::uint32_t(e.name.size()) + 1; + names.push_back(&e.name); + } + } + std::vector<std::size_t> order(elements.size()); + std::iota(order.begin(), order.end(), std::size_t(0)); + std::stable_sort(order.begin(), order.end(), [&](std::size_t x, std::size_t y) { + auto kx = std::make_pair(elements[x].row.value_or(UINT32_MAX), offsets[x]); + auto ky = std::make_pair(elements[y].row.value_or(UINT32_MAX), offsets[y]); + return kx < ky; + }); + for (std::size_t i : order) { + const SigElement& e = elements[i]; + std::uint32_t offset = offsets[i]; + auto used = std::uint8_t(e.usage << e.col); + std::uint8_t rw = input ? used : std::uint8_t(~used & 0xf); + for (std::uint32_t v : {0u, offset, e.index, e.system_value(), e.sig_comp(), e.row.value_or(UINT32_MAX)}) + put32(out, v); + out.push_back(e.mask()); + out.push_back(rw); + out.push_back(0); + out.push_back(0); + put32(out, 0); + } + for (const std::string* name : names) { + out.insert(out.end(), name->begin(), name->end()); + out.push_back(0); + } + return out; +} + +std::uint64_t mesh_output_bytes(std::span<const SigElement> vertex, std::span<const SigElement> primitive, + std::uint32_t max_vertices, std::uint32_t max_primitives) { + auto scalars = [](std::span<const SigElement> els) { + std::uint64_t n = 0; + for (const SigElement& e : els) n += e.cols; + return n; + }; + auto align = [](std::uint32_t n) { return (std::uint64_t(n) + 31) / 32 * 32; }; + return 4 * (scalars(vertex) * align(max_vertices) + scalars(primitive) * align(max_primitives)); +} + +std::vector<std::uint8_t> psv(const Psv& p) { + auto vectors = [](std::span<const SigElement> els) { + std::uint32_t m = 0; + for (const SigElement& e : els) + if (e.row) m = std::max(m, *e.row + 1); + return m; + }; + const std::uint32_t in_vectors = vectors(p.inputs), out_vectors = vectors(p.outputs); + std::vector<std::uint8_t> out; + put32(out, 48); + std::uint8_t info[48] = {}; + info[0] = std::uint8_t(p.flag); + if (p.stage == 0) { + // PSInfo.SampleFrequency: an input interpolated per sample, or the sample index. + bool any = false; + for (const SigElement& e : p.inputs) + if (e.interp == 6 || e.interp == 7 || e.kind == 12) any = true; + info[1] = std::uint8_t(any); + } + std::uint32_t wmin = 0, wmax = UINT32_MAX; + if (p.wave_size) wmin = wmax = *p.wave_size; + put32_at(info + 16, wmin); + put32_at(info + 20, wmax); + info[24] = p.stage; + for (std::size_t k = 0; k < 3; ++k) put32_at(info + 36 + 4 * k, p.threads[k]); + info[28] = std::uint8_t(p.inputs.size()); + info[29] = std::uint8_t(p.outputs.size()); + info[31] = std::uint8_t(in_vectors); + info[32] = std::uint8_t(out_vectors); + if (p.mesh) { + const shader::Mesh& mesh = *p.mesh; + put32_at(info + 0, p.mesh_lds_bytes); + put16_at(info + 12, std::uint16_t(mesh.max_vertices)); + put16_at(info + 14, std::uint16_t(mesh.max_primitives)); + info[26] = std::uint8_t(vectors(p.prims)); + info[27] = mesh.topology; + info[30] = std::uint8_t(p.prims.size()); + } + if (p.geometry) { + // Input primitive (3: triangles), output topology (5: triangle strips), stream mask, + // position written; the vertex maximum. + put32_at(info + 0, 3); + put32_at(info + 4, 5); + put32_at(info + 8, 1); + info[12] = std::uint8_t(p.flag); + put16_at(info + 26, std::uint16_t(*p.geometry)); + } + out.insert(out.end(), info, info + 48); + put32(out, std::uint32_t(p.bindings.size())); + if (!p.bindings.empty()) { + put32(out, 24); + for (const Binding& b : p.bindings) + for (std::uint32_t v : {b.kind, b.space, b.register_, b.register_, b.dxil_kind, 0u}) put32(out, v); + } + // Names of arbitrary semantics (system values use ""), then indices. + std::vector<std::uint8_t> strings = {0}; + std::vector<std::uint32_t> indices; + struct Row { + std::uint32_t name, index; + std::uint8_t start, cols; + const SigElement* e; + }; + std::vector<Row> elements; + auto add = [&](const SigElement& e) { + std::size_t name = 0; + if (e.kind == 0) { + std::vector<std::uint8_t> needle(e.name.begin(), e.name.end()); + needle.push_back(0); + if (auto at = find(strings, needle)) { + name = *at; + } else { + strings.insert(strings.end(), needle.begin(), needle.end()); + name = strings.size() - needle.size(); + } + } + std::size_t index = 0; + auto it = std::find(indices.begin(), indices.end(), e.index); + if (it != indices.end()) { + index = std::size_t(it - indices.begin()); + } else { + indices.push_back(e.index); + index = indices.size() - 1; + } + std::uint8_t start = 0, alloc = 0; + if (e.row) { + start = std::uint8_t(*e.row); + alloc = std::uint8_t(0x40 | (e.col << 4)); + } + elements.push_back(Row{std::uint32_t(name), std::uint32_t(index), start, std::uint8_t(e.cols | alloc), &e}); + }; + for (const SigElement& e : p.inputs) add(e); + for (const SigElement& e : p.outputs) add(e); + for (const SigElement& e : p.prims) add(e); + strings.resize((strings.size() + 3) / 4 * 4, 0); + put32(out, std::uint32_t(strings.size())); + out.insert(out.end(), strings.begin(), strings.end()); + put32(out, std::uint32_t(indices.size())); + for (std::uint32_t i : indices) put32(out, i); + if (!elements.empty()) { + put32(out, 16); + for (const Row& r : elements) { + put32(out, r.name); + put32(out, r.index); + const std::uint8_t rec[8] = {1, r.start, r.cols, r.e->kind, std::uint8_t(r.e->sig_comp()), r.e->interp, 0, 0}; + out.insert(out.end(), rec, rec + 8); + } + } + // Input-to-output dependencies, as the view-id state declares them: every output scalar on + // every input scalar. + if (in_vectors > 0 && out_vectors > 0) { + auto scalars = [](std::span<const SigElement> els) { + std::uint32_t m = 0; + for (const SigElement& e : els) + if (e.row) m = std::max(m, *e.row * 4 + std::uint32_t(std::uint8_t(e.col + e.cols))); + return m; + }; + const std::uint32_t ni = scalars(p.inputs), no = scalars(p.outputs); + const std::uint32_t per = (out_vectors * 4 + 31) / 32; + for (std::uint32_t i = 0; i < in_vectors * 4; ++i) { + for (std::uint32_t k = 0; k < per; ++k) { + std::uint32_t bits = 0; + if (i < ni) bits = std::min(no > 32 * k ? no - 32 * k : 0u, 32u); + std::uint32_t mask = bits == 32 ? UINT32_MAX : (1u << bits) - 1; + put32(out, mask); + } + } + } + return out; +} + +std::vector<std::uint8_t> build(std::span<const Part> parts) { + const std::size_t table = 0x20 + 4 * parts.size(); + std::size_t total = table; + for (const Part& p : parts) total += 8 + p.data.size(); + std::vector<std::uint8_t> out; + out.reserve(total); + const char magic[4] = {'D', 'X', 'B', 'C'}; + out.insert(out.end(), magic, magic + 4); + out.insert(out.end(), 16, 0); + out.push_back(1); + out.push_back(0); + out.push_back(0); + out.push_back(0); + put32(out, std::uint32_t(total)); + put32(out, std::uint32_t(parts.size())); + std::size_t offset = table; + for (const Part& p : parts) { + put32(out, std::uint32_t(offset)); + offset += 8 + p.data.size(); + } + for (const Part& p : parts) { + out.insert(out.end(), p.fourcc.begin(), p.fourcc.end()); + put32(out, std::uint32_t(p.data.size())); + out.insert(out.end(), p.data.begin(), p.data.end()); + } + auto digest = hash(std::span<const std::uint8_t>(out).subspan(20)); + std::copy(digest.begin(), digest.end(), out.begin() + 4); + return out; +} + +std::array<std::uint8_t, 16> hash(std::span<const std::uint8_t> data) { + const std::size_t len = data.size(); + const std::size_t left = len % 64; + std::vector<std::uint8_t> tail; + tail.reserve(128); + auto put = [&](std::uint32_t v) { put32(tail, v); }; + if (left < 56) { + put(std::uint32_t(len) << 3); + tail.insert(tail.end(), data.begin() + std::ptrdiff_t(len - left), data.end()); + tail.push_back(0x80); + tail.resize(60, 0); + } else { + tail.insert(tail.end(), data.begin() + std::ptrdiff_t(len - left), data.end()); + tail.push_back(0x80); + tail.resize(64, 0); + put(std::uint32_t(len) << 3); + tail.resize(124, 0); + } + put((std::uint32_t(len) << 1) | 1); + std::array<std::uint32_t, 4> state = {0x67452301u, 0xefcdab89u, 0x98badcfeu, 0x10325476u}; + for (std::size_t at = 0; at + 64 <= len - left; at += 64) md5_block(state, data.data() + at); + for (std::size_t at = 0; at + 64 <= tail.size(); at += 64) md5_block(state, tail.data() + at); + std::array<std::uint8_t, 16> out{}; + for (std::size_t k = 0; k < 4; ++k) put32_at(out.data() + 4 * k, state[k]); + return out; +} + +} // namespace x2w::vs::container diff --git a/src/x2w_shader/emit/container.h b/src/x2w_shader/emit/container.h new file mode 100644 index 0000000000..e5c30af02f --- /dev/null +++ b/src/x2w_shader/emit/container.h @@ -0,0 +1,110 @@ +#pragma once + +// The PC container around emitted DXIL: feature flags (SFI0), the signatures (ISG1, OSG1), pipeline state +// validation (PSV0) and the program (DXIL), laid out as validator version 1.6 lays them out, plus the +// container hash that D3D12 checks. + +#include <array> +#include <cstdint> +#include <optional> +#include <span> +#include <string> +#include <utility> +#include <vector> + +namespace x2w::vs::shader { +struct Mesh; +} + +namespace x2w::vs::container { + +// One signature element: one row (D3D12 links stages by semantic). +struct SigElement { + std::string name; + std::uint32_t index = 0; + // DXIL semantic kind (0 arbitrary, 1 vertex id, 3 position, 16 target...). + std::uint8_t kind = 0; + // DXIL component type (4 i32, 5 u32, 9 f32, 1 i1). + std::uint8_t comp = 0; + // DXIL interpolation mode (0 for none). + std::uint8_t interp = 0; + // Start row, if the element has a register. + std::optional<std::uint32_t> row; + std::uint8_t col = 0; + std::uint8_t cols = 0; + // Components read (inputs) or written (outputs), relative to col. + std::uint8_t usage = 0; + // 16-bit on the console (declared 32-bit here). + bool half = false; + + std::uint32_t system_value() const; + std::uint32_t sig_comp() const; + std::uint8_t mask() const; + bool operator==(const SigElement&) const = default; +}; + +// ISG1/OSG1: 32-byte rows, then the names. +std::vector<std::uint8_t> signature(std::span<const SigElement> elements, bool input); + +// The most a mesh shader's outputs may take, in bytes (D3D12). +inline constexpr std::uint64_t MESH_OUTPUT_LIMIT = 32 * 1024; + +// A mesh shader's output size as the DXIL validator measures it against MESH_OUTPUT_LIMIT: 4 +// bytes per component of every vertex element and primitive element, times the maxima rounded up +// to multiples of 32. +std::uint64_t mesh_output_bytes(std::span<const SigElement> vertex, std::span<const SigElement> primitive, + std::uint32_t max_vertices, std::uint32_t max_primitives); + +// A resource bound by register, as PSV0 lists it. +struct Binding { + // PSV resource type: 1 sampler, 2 CBV, 4 raw SRV, 7 raw UAV. + std::uint32_t kind = 0; + std::uint32_t space = 0; + std::uint32_t register_ = 0; + // DXIL resource kind (13 cbuffer, 14 sampler). + std::uint32_t dxil_kind = 0; +}; + +// The spans describing PSV0 borrow their input storage. +struct Psv { + // PSV shader kind: 0 pixel, 1 vertex, 2 geometry, 5 compute. + std::uint8_t stage = 0; + // Vertex: writes SV_Position. Pixel: writes depth. + bool flag = false; + std::span<const SigElement> inputs; + std::span<const SigElement> outputs; + // Mesh: per-primitive outputs. + std::span<const SigElement> prims; + // Mesh: its state and the group-shared bytes it declares. (A pointer: Mesh is declared in + // shader.h, which includes this header.) + const shader::Mesh* mesh = nullptr; + std::uint32_t mesh_lds_bytes = 0; + // Geometry (triangles in, triangle strips out on stream 0): its maximum vertex count. flag: + // writes SV_Position. + std::optional<std::uint32_t> geometry; + std::span<const Binding> bindings; + // Compute: thread-group size and required wave size. + std::array<std::uint32_t, 3> threads{}; + std::optional<std::uint32_t> wave_size; +}; + +// PSV0 with runtime info version 2 (validator 1.6). +std::vector<std::uint8_t> psv(const Psv& p); + +// One part: its fourcc and data. +struct Part { + std::array<std::uint8_t, 4> fourcc; + std::span<const std::uint8_t> data; +}; + +// The container: parts in order, hashed. +std::vector<std::uint8_t> build(std::span<const Part> parts); + +// The container hash D3D12 checks: MD5 whose last block carries the bit count first and +// 2 x bytes + 1 last instead of standard padding. +std::array<std::uint8_t, 16> hash(std::span<const std::uint8_t> data); + +// The MD5 compression of one 64-byte block (for the test of the MD5 core). +void md5_block_for_test(std::array<std::uint32_t, 4>& state, const std::uint8_t* block); + +} // namespace x2w::vs::container diff --git a/src/x2w_shader/emit/emit.h b/src/x2w_shader/emit/emit.h new file mode 100644 index 0000000000..566ee4bfc8 --- /dev/null +++ b/src/x2w_shader/emit/emit.h @@ -0,0 +1,118 @@ +#pragma once + +// Emit Shader Model 6.6 DXIL for console vertex, pixel, compute and mesh shaders. The host binds user data +// at b0 space 0, indexes ResourceDescriptorHeap and SamplerDescriptorHeap with console indices, binds +// immediate samplers as static samplers at s<n> space 0, and binds root CBVs/SRVs/UAVs in ROOT_CBV_SPACE. +// Signatures follow the console container. +// +// Translation errors throw ShaderError. + +#include <array> +#include <cstdint> +#include <optional> +#include <span> +#include <string_view> +#include <vector> + +#include "x2w_shader/emit/rect.h" +#include "x2w_shader/emit/sampler.h" +#include "x2w_shader/emit/settings.h" +#include "x2w_shader/emit/shader.h" +#include "x2w_shader/emit/signature.h" +#include "x2w_shader/error.h" +#include "x2w_shader/native.h" +#include "x2w_shader/resource.h" + +namespace x2w::vs { + +namespace dxbc { +struct Container; +} +namespace ir { +struct Program; +} +namespace structure { +struct Structured; +} +namespace io { +struct Io; +} + +// Public shader, sampler, and rectangle-list interfaces. +using sampler::StaticSampler; +using shader::MEMORY_FAULTS; +using shader::MEMORY_PAGES; +using shader::MEMORY_READ_ONLY; +using shader::raw_views; +using shader::ROOT_CBV_SPACE; +using shader::SAMPLER_SPACE; +using shader::set_raw_views; +using shader::set_view_heap_limit; +using shader::SLOT_FAULTS; +using shader::SLOT_MEMORY; +using shader::SLOT_STRIDES; +using shader::SLOT_STRIDES_COUNT; +using shader::USER_DATA_SPACE; +using shader::USER_DISPATCH_THREADS_X; +using shader::USER_MEMORY_BASE; +using shader::USER_ROOT_ADDRESS; +using shader::USER_VIEW_ADDRESS; +using shader::USER_VIEW_BIAS; +using shader::VIEW_INTEGER; +using shader::VIEW_SIGNED; +using shader::VIEW_STRIDE_BITS; +using shader::view_heap_limit; + +// X2W_VS_SOURCE_HASH and X2W_VS_SWITCHES identify the translator build and its switches for the cache +// fingerprint. +std::vector<std::uint8_t> translation_fingerprint(); + +// One dword of user data and the root parameter that fills it. +struct UserData { + // Dword in the user-data buffer (the console's user-data index). + std::uint32_t index = 0; + // Root parameter index in the title's root signature. + std::uint8_t slot = 0; + // Constants or Table (see the module notes for the value). + native::RootType root{}; + // Dword within the parameter. + std::uint32_t dword = 0; + bool operator==(const UserData&) const = default; +}; + +// A translated shader and what the host binds for it. +struct HostShader { + native::HwStage stage{}; + // The DXIL container, hashed as D3D12 expects. + std::vector<std::uint8_t> dxil; + // The user-data dwords the shader reads. + std::vector<UserData> user_data; + // Immediate samplers: the four sampler words of s<n>. + std::vector<std::array<std::uint32_t, 4>> samplers; + // The same samplers decoded, s<n> at position n: the static sampler descriptions the host's + // root signature declares. + std::vector<StaticSampler> static_samplers; + // Root CBVs the shader reads: root parameter indices, each bound as b<index> in ROOT_CBV_SPACE. + std::vector<std::uint8_t> root_cbvs; + // Root SRVs (raw buffers) the shader reads: t<index> in ROOT_CBV_SPACE. + std::vector<std::uint8_t> root_srvs; + // Root UAVs (raw buffers) the shader reads or writes: u<index> in ROOT_CBV_SPACE. + std::vector<std::uint8_t> root_uavs; + // Heap descriptors that can be selected from root state at bind time. + std::vector<resource::RootIndexedView> root_indexed_views; + + // Size of the user-data buffer the shader declares, in dwords (a multiple of 4; 0 when it + // reads none). Root constants must cover it. + std::uint32_t user_data_dwords() const; + bool operator==(const HostShader&) const = default; +}; + +// Translates the vertex, pixel, compute or mesh program of a console shader container (bytes as +// the title passes them at pipeline creation). Throws ShaderError. +HostShader translate(std::span<const std::uint8_t> container); + +// Emits a program whose earlier stages already ran. Throws ShaderError. +HostShader emit(const dxbc::Container& c, const native::NativeProgram& native, const ir::Program& p, + const structure::Structured& st, const io::Io& io, const resource::Resources& res); + +} // namespace x2w::vs diff --git a/src/x2w_shader/emit/fingerprint.cmake b/src/x2w_shader/emit/fingerprint.cmake new file mode 100644 index 0000000000..6807718ed8 --- /dev/null +++ b/src/x2w_shader/emit/fingerprint.cmake @@ -0,0 +1,29 @@ +# cmake -DSRC=<src dir> -DOUT=<header> -P fingerprint.cmake: the translator's source fingerprint and the +# X2W_SHADERCFG_* switches it reads. Hash sorted sources and relative paths with SHA-256. Write OUT only +# when it changes. Run at build time from cmake/x_translate.cmake. +file(GLOB_RECURSE files "${SRC}/x2w_shader/*.h" "${SRC}/x2w_shader/*.cpp") +list(SORT files) +set(text "") +set(switches "") +foreach(f IN LISTS files) + file(RELATIVE_PATH rel "${SRC}" "${f}") + file(READ "${f}" body) + string(APPEND text "${rel}\n${body}\n") + string(REGEX MATCHALL "\"X2W_SHADERCFG_[A-Z0-9_]+\"" found "${body}") + foreach(s IN LISTS found) + string(REPLACE "\"" "" s "${s}") + list(APPEND switches "${s}") + endforeach() +endforeach() +string(SHA256 hash "${text}") +list(REMOVE_DUPLICATES switches) +list(SORT switches) +string(REPLACE ";" "," switches "${switches}") +set(content "#define X2W_VS_SOURCE_HASH \"${hash}\"\n#define X2W_VS_SWITCHES \"${switches}\"\n") +set(old "") +if(EXISTS "${OUT}") + file(READ "${OUT}" old) +endif() +if(NOT old STREQUAL content) + file(WRITE "${OUT}" "${content}") +endif() diff --git a/src/x2w_shader/emit/host.cpp b/src/x2w_shader/emit/host.cpp new file mode 100644 index 0000000000..00e9e5927f --- /dev/null +++ b/src/x2w_shader/emit/host.cpp @@ -0,0 +1,1006 @@ +// device creation, root signatures, compute, graphics and mesh pipelines, the stub shaders, and the test +// drivers Host::draw and Host::dispatch. +// +// stub_vs/stub_ps (the HostShader wrappers) compile once x2w_shader/native.h exists; the DXIL +// they carry (stub_vs_dxil/stub_ps_dxil) is built now. + +#include "x2w_shader/emit/host.h" + +#include <algorithm> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <optional> +#include <string> +#include <thread> + +#include "x2w_shader/dxbc.h" +#include "x2w_shader/emit/bitcode.h" +#include "x2w_shader/emit/container.h" +#include "x2w_shader/emit/shader.h" +#include "x2w_shader/emit/signature.h" + +#if __has_include("x2w_shader/native.h") +#define X2W_VS_HOST_STUBS 1 +#include "x2w_shader/emit/emit.h" +#else +#define X2W_VS_HOST_STUBS 0 +#endif + +namespace x2w::vs::host { + +namespace { + +[[noreturn]] void fail(HRESULT hr) { throw Error(message(hr)); } +void check(HRESULT hr) { + if (FAILED(hr)) fail(hr); +} + +std::size_t round_up(std::size_t x, std::size_t to) { return (x + to - 1) / to * to; } + +bool env_is(const char* name, const char* value) { + const char* v = std::getenv(name); + return v && std::strcmp(v, value) == 0; +} + +D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + // A borrowed pointer; the barrier never releases it. + b.Transition.pResource = r; + b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + b.Transition.StateBefore = before; + b.Transition.StateAfter = after; + return b; +} + +D3D12_RESOURCE_DESC buffer_desc(std::uint64_t size, D3D12_RESOURCE_FLAGS flags) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = size; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc = {1, 0}; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + return d; +} + +D3D12_RESOURCE_DESC texture_desc(std::uint32_t w, std::uint32_t h, D3D12_RESOURCE_FLAGS flags, DXGI_FORMAT format) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = w; + d.Height = h; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.Format = format; + d.SampleDesc = {1, 0}; + d.Flags = flags; + return d; +} + +ComPtr<ID3D12Resource> make(ID3D12Device* dev, D3D12_HEAP_TYPE type, const D3D12_RESOURCE_DESC& desc, + D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear = nullptr) { + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = type; + ComPtr<ID3D12Resource> r; + check(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, clear, IID_PPV_ARGS(&r))); + if (!r) throw Error("no resource"); + return r; +} + +D3D12_TEXTURE_COPY_LOCATION subresource(ID3D12Resource* r, UINT index = 0) { + D3D12_TEXTURE_COPY_LOCATION l{}; + l.pResource = r; + l.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + l.SubresourceIndex = index; + return l; +} + +D3D12_TEXTURE_COPY_LOCATION footprint(ID3D12Resource* r, DXGI_FORMAT format, std::uint32_t w, std::uint32_t h, + std::uint32_t pitch) { + D3D12_TEXTURE_COPY_LOCATION l{}; + l.pResource = r; + l.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + l.PlacedFootprint.Offset = 0; + l.PlacedFootprint.Footprint = {format, w, h, 1, pitch}; + return l; +} + +// Copies w x h RGBA32F texels (rows of w) into an upload buffer of pitch-byte rows. +void fill_rows(ID3D12Resource* upload, const std::array<float, 4>* texels, std::uint32_t w, std::uint32_t h, + std::size_t pitch) { + void* p = nullptr; + check(upload->Map(0, nullptr, &p)); + for (std::size_t y = 0; y < h; ++y) + std::memcpy(static_cast<std::uint8_t*>(p) + y * pitch, texels + y * w, std::size_t(w) * 16); + upload->Unmap(0, nullptr); +} + +// Runs list on queue and waits for it; throws when the device is removed. +void run(ID3D12Device* dev, ID3D12CommandQueue* queue, ID3D12GraphicsCommandList* list, bool check_after) { + check(list->Close()); + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + ComPtr<ID3D12Fence> fence; + check(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); + check(queue->Signal(fence.Get(), 1)); + while (fence->GetCompletedValue() < 1) { + HRESULT reason = dev->GetDeviceRemovedReason(); + if (FAILED(reason)) throw Error("device removed: " + message(reason)); + std::this_thread::yield(); + } + if (check_after) { + HRESULT reason = dev->GetDeviceRemovedReason(); + if (FAILED(reason)) throw Error("device removed: " + message(reason)); + } +} + +struct Queue { + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> alloc; + ComPtr<ID3D12GraphicsCommandList> list; +}; + +Queue direct_queue(ID3D12Device* dev, ID3D12PipelineState* pso) { + Queue q; + D3D12_COMMAND_QUEUE_DESC qd{}; + qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + check(dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&q.queue))); + check(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&q.alloc))); + check(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, q.alloc.Get(), pso, IID_PPV_ARGS(&q.list))); + return q; +} + +ComPtr<ID3D12DescriptorHeap> heap(ID3D12Device* dev, D3D12_DESCRIPTOR_HEAP_TYPE ty, std::size_t n) { + D3D12_DESCRIPTOR_HEAP_DESC d{}; + d.Type = ty; + d.NumDescriptors = static_cast<UINT>(std::max<std::size_t>(n, 1)); + d.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + ComPtr<ID3D12DescriptorHeap> h; + check(dev->CreateDescriptorHeap(&d, IID_PPV_ARGS(&h))); + return h; +} + +} // namespace + +std::string message(HRESULT hr) { + char* text = nullptr; + DWORD n = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, static_cast<DWORD>(hr), 0, reinterpret_cast<char*>(&text), 0, nullptr); + std::string s; + if (n && text) { + s.assign(text, n); + while (!s.empty() && (s.back() == '\n' || s.back() == '\r' || s.back() == ' ')) + s.pop_back(); + } + if (text) LocalFree(text); + if (s.empty()) { + char buf[32]; + std::snprintf(buf, sizeof buf, "HRESULT 0x%08x", static_cast<unsigned>(hr)); + s = buf; + } + return s; +} + +Host::Host(bool warp) { + warp = warp || env_is("X2W_SHADERCFG_WARP", "1"); + // X2W_SHADERCFG_D3D12_DEBUG: the debug layer, whose messages a refused pipeline's error then + // carries. + if (std::getenv("X2W_SHADERCFG_D3D12_DEBUG")) { + ComPtr<ID3D12Debug> debug; + if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug))) && debug) debug->EnableDebugLayer(); + } + if (warp) { + ComPtr<IDXGIFactory4> factory; + check(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory))); + ComPtr<IDXGIAdapter> adapter; + check(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))); + check(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device))); + } else { + check(D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device))); + // A machine without a graphics card gives the software adapter as its default device (a + // hosted test runner, whose first adapter is a display stub that cannot make a device): + // that is no hardware device, and the tests that ask for one skip it, as they do where + // there is none. + if (device) { + ComPtr<IDXGIFactory4> factory; + check(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory))); + ComPtr<IDXGIAdapter1> adapter; + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(factory->EnumAdapterByLuid(device->GetAdapterLuid(), IID_PPV_ARGS(&adapter))) && + SUCCEEDED(adapter->GetDesc1(&desc)) && + ((desc.Flags & 2) != 0 || (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c))) + throw Error("the default device is the software adapter"); + } + } + if (!device) throw Error("no device"); + D3D12_FEATURE_DATA_SHADER_MODEL sm{D3D_SHADER_MODEL_6_6}; + check(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &sm, sizeof sm)); + if (sm.HighestShaderModel < D3D_SHADER_MODEL_6_6) { + char buf[64]; + std::snprintf(buf, sizeof buf, "the device supports SM 0x%x only", static_cast<unsigned>(sm.HighestShaderModel)); + throw Error(buf); + } +} + +ComPtr<ID3D12RootSignature> Host::root_signature(const Stage& vs, const Stage& ps) const { + return root_signature_for({{vs, D3D12_SHADER_VISIBILITY_VERTEX}, {ps, D3D12_SHADER_VISIBILITY_PIXEL}}); +} + +ComPtr<ID3D12RootSignature> Host::root_signature_for( + std::span<const std::pair<Stage, D3D12_SHADER_VISIBILITY>> stages) const { + std::vector<D3D12_ROOT_PARAMETER1> params; + for (const auto& [s, vis] : stages) { + D3D12_ROOT_PARAMETER1 p{}; + p.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + p.Constants.ShaderRegister = 0; + p.Constants.RegisterSpace = shader::USER_DATA_SPACE; + p.Constants.Num32BitValues = std::max<std::uint32_t>(s.user_data_dwords, 1); + p.ShaderVisibility = vis; + params.push_back(p); + } + // By slot, then kind: 0 CBV, 1 SRV, 2 UAV. + std::vector<std::pair<std::uint8_t, std::uint8_t>> views; + for (const auto& [s, vis] : stages) { + for (std::uint8_t r : s.root_cbvs) views.emplace_back(r, std::uint8_t{0}); + for (std::uint8_t r : s.root_srvs) views.emplace_back(r, std::uint8_t{1}); + for (std::uint8_t r : s.root_uavs) views.emplace_back(r, std::uint8_t{2}); + } + std::sort(views.begin(), views.end()); + views.erase(std::unique(views.begin(), views.end()), views.end()); + for (const auto& [slot, kind] : views) { + D3D12_ROOT_PARAMETER1 p{}; + p.ParameterType = kind == 1 ? D3D12_ROOT_PARAMETER_TYPE_SRV + : kind == 2 ? D3D12_ROOT_PARAMETER_TYPE_UAV + : D3D12_ROOT_PARAMETER_TYPE_CBV; + p.Descriptor.ShaderRegister = slot; + p.Descriptor.RegisterSpace = shader::ROOT_CBV_SPACE; + p.Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE; + p.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + params.push_back(p); + } + // Older runtimes may not recognize OPTIONS19; that means no support. + D3D12_FEATURE_DATA_D3D12_OPTIONS19 options{}; + const bool aniso_point_mip_supported = + SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS19, &options, sizeof options)) && + options.AnisoFilterWithPointMipSupported; + std::vector<D3D12_STATIC_SAMPLER_DESC> samplers; + for (const auto& [s, vis] : stages) { + for (std::size_t n = 0; n < s.static_samplers.size(); ++n) { + const sampler::StaticSampler& d = s.static_samplers[n]; + D3D12_STATIC_SAMPLER_DESC sd{}; + sd.Filter = static_cast<D3D12_FILTER>(d.filter_for_host(aniso_point_mip_supported)); + sd.AddressU = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(d.address[0]); + sd.AddressV = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(d.address[1]); + sd.AddressW = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(d.address[2]); + sd.MipLODBias = d.mip_lod_bias; + sd.MaxAnisotropy = d.max_anisotropy; + sd.ComparisonFunc = static_cast<D3D12_COMPARISON_FUNC>(d.comparison); + sd.BorderColor = static_cast<D3D12_STATIC_BORDER_COLOR>(d.border); + sd.MinLOD = d.min_lod; + sd.MaxLOD = d.max_lod; + sd.ShaderRegister = static_cast<UINT>(n); + sd.RegisterSpace = shader::SAMPLER_SPACE; + sd.ShaderVisibility = vis; + samplers.push_back(sd); + } + } + D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; + desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + desc.Desc_1_1.NumParameters = static_cast<UINT>(params.size()); + desc.Desc_1_1.pParameters = params.data(); + desc.Desc_1_1.NumStaticSamplers = static_cast<UINT>(samplers.size()); + desc.Desc_1_1.pStaticSamplers = samplers.data(); + desc.Desc_1_1.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | + D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | + D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + ComPtr<ID3DBlob> blob; + ComPtr<ID3DBlob> error; + check(D3D12SerializeVersionedRootSignature(&desc, &blob, &error)); + if (!blob) throw Error("no root signature blob"); + ComPtr<ID3D12RootSignature> root; + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root))); + return root; +} + +Pipeline Host::compute_pipeline(const Stage& cs) const { + auto root = root_signature_for({{cs, D3D12_SHADER_VISIBILITY_ALL}}); + auto pso = compute_pipeline_with(root.Get(), cs.dxil); + return {std::move(root), std::move(pso)}; +} + +ComPtr<ID3D12PipelineState> Host::compute_pipeline_with(ID3D12RootSignature* root, + std::span<const std::uint8_t> cs) const { + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + // A borrowed pointer the descriptor never releases. + desc.pRootSignature = root; + desc.CS = {cs.data(), cs.size()}; + ComPtr<ID3D12PipelineState> pso; + HRESULT hr = device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso)); + if (FAILED(hr)) throw Error(explained(hr)); + return pso; +} + +std::string Host::explained(HRESULT hr) const { + std::string text = message(hr); + ComPtr<ID3D12InfoQueue> queue; + if (FAILED(device.As(&queue))) return text; + // Each message is read into a buffer of the size the queue asks for, aligned for the message + // header. + const UINT64 count = queue->GetNumStoredMessages(); + for (UINT64 i = 0; i < count; ++i) { + SIZE_T len = 0; + (void)queue->GetMessage(i, nullptr, &len); + std::vector<std::uint64_t> buffer((len + 7) / 8); + auto* m = reinterpret_cast<D3D12_MESSAGE*>(buffer.data()); + if (SUCCEEDED(queue->GetMessage(i, m, &len))) { + const SIZE_T n = m->DescriptionByteLength ? m->DescriptionByteLength - 1 : 0; + text += " | "; + text.append(m->pDescription, n); + } + } + queue->ClearStoredMessages(); + return text; +} + +std::vector<std::array<float, 4>> Host::draw(ID3D12RootSignature* root, ID3D12PipelineState* pso, + const Draw& d) const { + ID3D12Device* dev = device.Get(); + const auto [w, h] = d.size; + // D3D12 calls with descriptions that outlive them; resources are kept alive until the fence + // says the GPU is done. + Queue q = direct_queue(dev, pso); + ID3D12GraphicsCommandList* list = q.list.Get(); + D3D12_CLEAR_VALUE clear{}; + clear.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + auto target = make(dev, D3D12_HEAP_TYPE_DEFAULT, + texture_desc(w, h, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, DXGI_FORMAT_R32G32B32A32_FLOAT), + D3D12_RESOURCE_STATE_RENDER_TARGET, &clear); + ComPtr<ID3D12DescriptorHeap> rtv_heap; + { + D3D12_DESCRIPTOR_HEAP_DESC hd{}; + hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + hd.NumDescriptors = 1; + check(dev->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtv_heap))); + } + const D3D12_CPU_DESCRIPTOR_HANDLE rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + dev->CreateRenderTargetView(target.Get(), nullptr, rtv); + auto views = heap(dev, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, d.textures.size()); + auto sampler_heap = heap(dev, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, d.samplers.size()); + const std::size_t view_size = dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const std::size_t sampler_size = dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + std::vector<ComPtr<ID3D12Resource>> keep; + for (std::size_t i = 0; i < d.textures.size(); ++i) { + const Texture& t = d.textures[i]; + if (t.texels.size() < std::size_t(t.width) * t.height) bitcode::bug("host: texture texels too short"); + auto tex = make(dev, D3D12_HEAP_TYPE_DEFAULT, + texture_desc(t.width, t.height, D3D12_RESOURCE_FLAG_NONE, DXGI_FORMAT_R32G32B32A32_FLOAT), + D3D12_RESOURCE_STATE_COPY_DEST); + const std::size_t pitch = round_up(std::size_t(t.width) * 16, 256); + auto upload = make(dev, D3D12_HEAP_TYPE_UPLOAD, buffer_desc(pitch * t.height, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ); + fill_rows(upload.Get(), t.texels.data(), t.width, t.height, pitch); + const auto dst = subresource(tex.Get()); + const auto src = footprint(upload.Get(), DXGI_FORMAT_R32G32B32A32_FLOAT, t.width, t.height, + static_cast<std::uint32_t>(pitch)); + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + const auto barrier = transition(tex.Get(), D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list->ResourceBarrier(1, &barrier); + D3D12_CPU_DESCRIPTOR_HANDLE at = views->GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * view_size; + dev->CreateShaderResourceView(tex.Get(), nullptr, at); + keep.push_back(std::move(tex)); + keep.push_back(std::move(upload)); + } + for (std::size_t i = 0; i < d.samplers.size(); ++i) { + D3D12_CPU_DESCRIPTOR_HANDLE at = sampler_heap->GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * sampler_size; + dev->CreateSampler(&d.samplers[i], at); + } + ComPtr<ID3D12Resource> vb; + if (!d.vertices.empty()) { + const std::size_t bytes = d.vertices.size() * 4; + vb = make(dev, D3D12_HEAP_TYPE_UPLOAD, buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ); + void* p = nullptr; + check(vb->Map(0, nullptr, &p)); + std::memcpy(p, d.vertices.data(), bytes); + vb->Unmap(0, nullptr); + } + ID3D12DescriptorHeap* heaps[] = {views.Get(), sampler_heap.Get()}; + list->SetDescriptorHeaps(2, heaps); + list->SetGraphicsRootSignature(root); + for (const auto& [param, arg] : d.roots) { + switch (arg.kind) { + case Root::Constants: + list->SetGraphicsRoot32BitConstants(param, static_cast<UINT>(arg.data.size()), arg.data.data(), 0); + break; + case Root::Table: { + ID3D12DescriptorHeap* hp = arg.sampler ? sampler_heap.Get() : views.Get(); + const std::size_t size = arg.sampler ? sampler_size : view_size; + D3D12_GPU_DESCRIPTOR_HANDLE at = hp->GetGPUDescriptorHandleForHeapStart(); + at.ptr += static_cast<UINT64>(arg.index * size); + list->SetGraphicsRootDescriptorTable(param, at); + break; + } + case Root::View: + throw Error("root views in a draw"); + } + } + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + D3D12_VIEWPORT viewport{0, 0, static_cast<float>(w), static_cast<float>(h), 0, 1}; + list->RSSetViewports(1, &viewport); + D3D12_RECT scissor{0, 0, static_cast<LONG>(w), static_cast<LONG>(h)}; + list->RSSetScissorRects(1, &scissor); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + if (vb) { + D3D12_VERTEX_BUFFER_VIEW vbv{vb->GetGPUVirtualAddress(), static_cast<UINT>(d.vertices.size() * 4), d.stride}; + list->IASetVertexBuffers(0, 1, &vbv); + } + if (d.mesh_groups > 0) { + ComPtr<ID3D12GraphicsCommandList6> list6; + check(q.list.As(&list6)); + list6->DispatchMesh(d.mesh_groups, 1, 1); + } else { + list->DrawInstanced(3, 1, 0, 0); + } + { + const auto barrier = + transition(target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &barrier); + } + const std::size_t pitch = round_up(std::size_t(w) * 16, 256); + auto readback = make(dev, D3D12_HEAP_TYPE_READBACK, buffer_desc(pitch * h, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST); + { + const auto dst = + footprint(readback.Get(), DXGI_FORMAT_R32G32B32A32_FLOAT, w, h, static_cast<std::uint32_t>(pitch)); + const auto src = subresource(target.Get()); + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + run(dev, q.queue.Get(), list, true); + void* p = nullptr; + check(readback->Map(0, nullptr, &p)); + std::vector<std::array<float, 4>> out; + out.reserve(std::size_t(w) * h); + for (std::size_t y = 0; y < h; ++y) { + const auto* row = reinterpret_cast<const std::array<float, 4>*>(static_cast<const std::uint8_t*>(p) + y * pitch); + out.insert(out.end(), row, row + w); + } + readback->Unmap(0, nullptr); + keep.clear(); + return out; +} + +std::vector<std::vector<std::uint32_t>> Host::dispatch(ID3D12RootSignature* root, ID3D12PipelineState* pso, + const Dispatch& d) const { + ID3D12Device* dev = device.Get(); + // D3D12 calls with descriptions that outlive them; resources stay alive until the fence says + // the GPU is done. + Queue q = direct_queue(dev, pso); + ID3D12GraphicsCommandList* list = q.list.Get(); + // An upload buffer holding data (sized for a constant buffer). + auto upload = [&](std::span<const std::uint32_t> data) { + const std::size_t size = round_up(data.size() * 4, 256); + auto b = make(dev, D3D12_HEAP_TYPE_UPLOAD, buffer_desc(size, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ); + void* p = nullptr; + check(b->Map(0, nullptr, &p)); + if (!data.empty()) std::memcpy(p, data.data(), data.size() * 4); + b->Unmap(0, nullptr); + return b; + }; + auto views = heap(dev, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, d.views.size()); + auto samplers = heap(dev, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, d.samplers.size()); + const std::size_t view_size = dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const std::size_t sampler_size = dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + std::vector<ComPtr<ID3D12Resource>> keep; + // UAVs: (resource, texture size or none, dwords or texel words, readback buffer). + struct Uav { + ComPtr<ID3D12Resource> r; + std::optional<std::pair<std::uint32_t, std::uint32_t>> size; + std::uint32_t n = 0; + ComPtr<ID3D12Resource> rb; + }; + std::vector<Uav> uavs; + for (std::size_t i = 0; i < d.views.size(); ++i) { + const View& v = d.views[i]; + D3D12_CPU_DESCRIPTOR_HANDLE at = views->GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * view_size; + switch (v.kind) { + case View::Texture: + case View::Cube: { + const std::uint32_t w = v.w, h = v.h; + const std::uint32_t faces = v.kind == View::Cube ? 6 : 1; + const std::uint16_t mips = v.kind == View::Cube ? v.mips : 1; + std::span<const std::array<float, 4>> texels = v.texels; + auto desc = texture_desc(w, h, D3D12_RESOURCE_FLAG_NONE, DXGI_FORMAT_R32G32B32A32_FLOAT); + desc.DepthOrArraySize = static_cast<UINT16>(faces); + desc.MipLevels = mips; + auto tex = make(dev, D3D12_HEAP_TYPE_DEFAULT, desc, D3D12_RESOURCE_STATE_COPY_DEST); + for (std::uint32_t sub = 0; sub < std::uint32_t(mips) * faces; ++sub) { + const std::uint32_t mip = sub % std::uint32_t(mips); + const std::uint32_t mw = std::max<std::uint32_t>(w >> mip, 1); + const std::uint32_t mh = std::max<std::uint32_t>(h >> mip, 1); + const std::size_t pitch = round_up(std::size_t(mw) * 16, 256); + auto up = make(dev, D3D12_HEAP_TYPE_UPLOAD, buffer_desc(pitch * mh, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ); + const std::size_t count = std::size_t(mw) * mh; + if (texels.size() < count) bitcode::bug("host: view texels too short"); + fill_rows(up.Get(), texels.data(), mw, mh, pitch); + texels = texels.subspan(count); + const auto dst = subresource(tex.Get(), sub); + const auto src = footprint(up.Get(), DXGI_FORMAT_R32G32B32A32_FLOAT, mw, mh, + static_cast<std::uint32_t>(pitch)); + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + keep.push_back(std::move(up)); + } + const auto barrier = transition(tex.Get(), D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list->ResourceBarrier(1, &barrier); + D3D12_SHADER_RESOURCE_VIEW_DESC cube{}; + cube.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + cube.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; + cube.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + cube.TextureCube.MipLevels = mips; + dev->CreateShaderResourceView(tex.Get(), faces == 6 ? &cube : nullptr, at); + keep.push_back(std::move(tex)); + break; + } + case View::RawUav: + case View::HalfUav: { + std::uint32_t n, elements; + DXGI_FORMAT format; + D3D12_BUFFER_UAV_FLAGS flags; + if (v.kind == View::HalfUav) { + n = 2 * v.n; + format = DXGI_FORMAT_R16G16B16A16_FLOAT; + elements = v.n; + flags = D3D12_BUFFER_UAV_FLAG_NONE; + } else { + n = v.n; + format = DXGI_FORMAT_R32_TYPELESS; + elements = v.n; + flags = D3D12_BUFFER_UAV_FLAG_RAW; + } + const std::uint64_t bytes = std::uint64_t(n) * 4; + auto b = make(dev, D3D12_HEAP_TYPE_DEFAULT, + buffer_desc(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COMMON); + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + desc.Format = format; + desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + desc.Buffer.NumElements = elements; + desc.Buffer.Flags = flags; + dev->CreateUnorderedAccessView(b.Get(), nullptr, &desc, at); + auto rb = make(dev, D3D12_HEAP_TYPE_READBACK, buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST); + uavs.push_back({std::move(b), std::nullopt, n, std::move(rb)}); + break; + } + case View::TextureUav: + case View::UintTextureUav: { + const bool uint = v.kind == View::UintTextureUav; + auto t = make(dev, D3D12_HEAP_TYPE_DEFAULT, + texture_desc(v.w, v.h, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + uint ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R32G32B32A32_FLOAT), + D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + dev->CreateUnorderedAccessView(t.Get(), nullptr, nullptr, at); + const std::uint32_t pitch = static_cast<std::uint32_t>(round_up(std::size_t(v.w) * (uint ? 4 : 16), 256)); + auto rb = make(dev, D3D12_HEAP_TYPE_READBACK, + buffer_desc(std::uint64_t(pitch * v.h), D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST); + uavs.push_back({std::move(t), std::pair{v.w, v.h}, uint ? 1u : 4u, std::move(rb)}); + break; + } + case View::Cbv: { + auto b = upload(v.data); + D3D12_CONSTANT_BUFFER_VIEW_DESC desc{b->GetGPUVirtualAddress(), + static_cast<UINT>(round_up(v.data.size() * 4, 256))}; + dev->CreateConstantBufferView(&desc, at); + keep.push_back(std::move(b)); + break; + } + case View::Buffer: { + auto b = upload(v.data); + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + std::size_t elements = 0; + std::uint32_t stride = 0; + D3D12_BUFFER_SRV_FLAGS flags = D3D12_BUFFER_SRV_FLAG_NONE; + switch (v.stride.kind) { + case Stride::Raw: + format = DXGI_FORMAT_R32_TYPELESS; + elements = v.data.size(); + flags = D3D12_BUFFER_SRV_FLAG_RAW; + break; + case Stride::Typed: + format = DXGI_FORMAT_R32G32B32A32_FLOAT; + elements = v.data.size() / 4; + break; + case Stride::Structured: + if (v.stride.bytes == 0) bitcode::bug("host: structured stride 0"); + format = DXGI_FORMAT_UNKNOWN; + elements = v.data.size() * 4 / v.stride.bytes; + stride = v.stride.bytes; + break; + case Stride::Format: + if (v.stride.bytes == 0) bitcode::bug("host: format stride 0"); + format = v.stride.format; + elements = v.data.size() * 4 / v.stride.bytes; + break; + } + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = format; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Buffer.FirstElement = 0; + desc.Buffer.NumElements = static_cast<UINT>(elements); + desc.Buffer.StructureByteStride = stride; + desc.Buffer.Flags = flags; + dev->CreateShaderResourceView(b.Get(), &desc, at); + keep.push_back(std::move(b)); + break; + } + } + } + for (std::size_t i = 0; i < d.samplers.size(); ++i) { + D3D12_CPU_DESCRIPTOR_HANDLE at = samplers->GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * sampler_size; + dev->CreateSampler(&d.samplers[i], at); + } + ID3D12DescriptorHeap* heaps[] = {views.Get(), samplers.Get()}; + list->SetDescriptorHeaps(2, heaps); + list->SetComputeRootSignature(root); + for (const auto& [param, arg] : d.roots) { + switch (arg.kind) { + case Root::Constants: + list->SetComputeRoot32BitConstants(param, static_cast<UINT>(arg.data.size()), arg.data.data(), 0); + break; + case Root::Table: { + ID3D12DescriptorHeap* hp = arg.sampler ? samplers.Get() : views.Get(); + const std::size_t size = arg.sampler ? sampler_size : view_size; + D3D12_GPU_DESCRIPTOR_HANDLE at = hp->GetGPUDescriptorHandleForHeapStart(); + at.ptr += static_cast<UINT64>(arg.index * size); + list->SetComputeRootDescriptorTable(param, at); + break; + } + case Root::View: { + auto b = upload(arg.data); + const D3D12_GPU_VIRTUAL_ADDRESS va = b->GetGPUVirtualAddress(); + if (arg.srv) + list->SetComputeRootShaderResourceView(param, va); + else + list->SetComputeRootConstantBufferView(param, va); + keep.push_back(std::move(b)); + break; + } + } + } + list->Dispatch(d.groups[0], d.groups[1], d.groups[2]); + for (const Uav& u : uavs) { + // (Buffers were promoted from the common state by the dispatch.) + const auto barrier = + transition(u.r.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &barrier); + if (u.size) { + const auto [w, h] = *u.size; + const auto dst = footprint(u.rb.Get(), u.n == 1 ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R32G32B32A32_FLOAT, + w, h, static_cast<std::uint32_t>(round_up(std::size_t(w) * 4 * u.n, 256))); + const auto src = subresource(u.r.Get()); + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } else { + list->CopyBufferRegion(u.rb.Get(), 0, u.r.Get(), 0, std::uint64_t(u.n) * 4); + } + } + run(dev, q.queue.Get(), list, false); + std::vector<std::vector<std::uint32_t>> out; + for (const Uav& u : uavs) { + void* p = nullptr; + check(u.rb->Map(0, nullptr, &p)); + std::vector<std::uint32_t> words; + if (u.size) { + const auto [w, h] = *u.size; + const std::size_t per = u.n; + const std::size_t pitch = round_up(std::size_t(w) * 4 * per, 256); + for (std::size_t y = 0; y < h; ++y) { + const auto* row = reinterpret_cast<const std::uint32_t*>(static_cast<const std::uint8_t*>(p) + y * pitch); + words.insert(words.end(), row, row + std::size_t(w) * per); + } + } else { + const auto* all = static_cast<const std::uint32_t*>(p); + words.assign(all, all + u.n); + } + u.rb->Unmap(0, nullptr); + out.push_back(std::move(words)); + } + keep.clear(); + return out; +} + + +using container::SigElement; + +namespace { + +// What the stage declares that a pipeline must match. +std::vector<SigElement> sig(std::span<const std::uint8_t> dxil, dxbc::FourCC fourcc) { + try { + const dxbc::Container c = dxbc::Container::parse(dxil); + const dxbc::Part* p = c.part(fourcc); + if (!p) return {}; + return vs::signature(p->data); + } catch (const std::exception& e) { + throw Error(e.what()); + } +} + +DXGI_FORMAT input_format(const SigElement& e) { + const std::size_t i = std::size_t(std::clamp<std::uint8_t>(e.cols, 1, 4)) - 1; + static constexpr DXGI_FORMAT F[4] = {DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32G32B32_FLOAT, + DXGI_FORMAT_R32G32B32A32_FLOAT}; + static constexpr DXGI_FORMAT S[4] = {DXGI_FORMAT_R32_SINT, DXGI_FORMAT_R32G32_SINT, DXGI_FORMAT_R32G32B32_SINT, + DXGI_FORMAT_R32G32B32A32_SINT}; + static constexpr DXGI_FORMAT U[4] = {DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32G32_UINT, DXGI_FORMAT_R32G32B32_UINT, + DXGI_FORMAT_R32G32B32A32_UINT}; + switch (e.comp) { + case 9: return F[i]; + case 4: return S[i]; + default: return U[i]; + } +} + +DXGI_FORMAT target_format(const SigElement& e) { + switch (e.comp) { + case 9: return DXGI_FORMAT_R32G32B32A32_FLOAT; + case 4: return DXGI_FORMAT_R32G32B32A32_SINT; + default: return DXGI_FORMAT_R32G32B32A32_UINT; + } +} + +D3D12_SHADER_BYTECODE code(std::span<const std::uint8_t> b) { return {b.data(), b.size()}; } + +D3D12_RASTERIZER_DESC rasterizer() { + D3D12_RASTERIZER_DESC r{}; + r.FillMode = D3D12_FILL_MODE_SOLID; + r.CullMode = D3D12_CULL_MODE_NONE; + r.DepthClipEnable = TRUE; + return r; +} + +// The targets, depth and stencil the pixel shader's outputs ask for. +struct Targets { + D3D12_RT_FORMAT_ARRAY rts{}; + D3D12_DEPTH_STENCIL_DESC depth{}; + DXGI_FORMAT dsv = DXGI_FORMAT_UNKNOWN; +}; + +Targets targets(const std::vector<SigElement>& outputs) { + Targets t; + for (const SigElement& o : outputs) { + if (o.kind != 16) continue; + const std::size_t n = o.row.value_or(0); + if (n >= 8) bitcode::bug("host: render target index out of bounds"); + t.rts.RTFormats[n] = target_format(o); + t.rts.NumRenderTargets = std::max<UINT>(t.rts.NumRenderTargets, static_cast<UINT>(n) + 1); + } + if (std::any_of(outputs.begin(), outputs.end(), [](const SigElement& o) { return o.kind >= 17 && o.kind <= 19; })) { + t.dsv = DXGI_FORMAT_D32_FLOAT; + t.depth.DepthEnable = TRUE; + t.depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + t.depth.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + } + if (std::any_of(outputs.begin(), outputs.end(), [](const SigElement& o) { return o.kind == 20; })) { + t.dsv = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + t.depth.StencilEnable = TRUE; + } + return t; +} + +} // namespace + +Pipeline Host::pipeline(const Stage& vs, const Stage& ps) const { + auto root = root_signature(vs, ps); + auto pso = pipeline_with(root.Get(), vs.dxil, ps.dxil); + return {std::move(root), std::move(pso)}; +} + +ComPtr<ID3D12PipelineState> Host::pipeline_with(ID3D12RootSignature* root, std::span<const std::uint8_t> vs, + std::span<const std::uint8_t> ps) const { + return pipeline_with_gs(root, vs, {}, ps); +} + +ComPtr<ID3D12PipelineState> Host::pipeline_with_gs(ID3D12RootSignature* root, std::span<const std::uint8_t> vs, + std::span<const std::uint8_t> gs, + std::span<const std::uint8_t> ps) const { + const std::vector<SigElement> inputs = sig(vs, dxbc::FourCC::ISG1); + std::vector<D3D12_INPUT_ELEMENT_DESC> layout; + for (const SigElement& e : inputs) { + if (e.kind != 0) continue; + D3D12_INPUT_ELEMENT_DESC l{}; + l.SemanticName = e.name.c_str(); + l.SemanticIndex = e.index; + l.Format = input_format(e); + l.InputSlot = 0; + l.AlignedByteOffset = D3D12_APPEND_ALIGNED_ELEMENT; + l.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA; + l.InstanceDataStepRate = 0; + layout.push_back(l); + } + const std::vector<SigElement> outputs = sig(ps, dxbc::FourCC::OSG1); + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + // A borrowed pointer the descriptor never releases. + desc.pRootSignature = root; + desc.VS = code(vs); + desc.PS = code(ps); + if (!gs.empty()) desc.GS = code(gs); + desc.SampleMask = UINT32_MAX; + desc.RasterizerState = rasterizer(); + desc.InputLayout = {layout.data(), static_cast<UINT>(layout.size())}; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.SampleDesc = {1, 0}; + for (auto& rt : desc.BlendState.RenderTarget) rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + const Targets t = targets(outputs); + for (UINT i = 0; i < 8; ++i) desc.RTVFormats[i] = t.rts.RTFormats[i]; + desc.NumRenderTargets = t.rts.NumRenderTargets; + desc.DSVFormat = t.dsv; + desc.DepthStencilState = t.depth; + ComPtr<ID3D12PipelineState> pso; + HRESULT hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso)); + if (FAILED(hr)) throw Error(message(hr)); + return pso; +} + +Pipeline Host::mesh_pipeline(const Stage& ms, const Stage& ps) const { + auto root = root_signature_for({{ms, D3D12_SHADER_VISIBILITY_MESH}, {ps, D3D12_SHADER_VISIBILITY_PIXEL}}); + auto pso = mesh_pipeline_with(root.Get(), ms.dxil, ps.dxil); + return {std::move(root), std::move(pso)}; +} + +namespace { +// A stream subobject: its type, then its description, pointer-aligned (padding intended). +#pragma warning(push) +#pragma warning(disable : 4324) +template <class T> +struct alignas(void*) Sub { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type; + T value; +}; +#pragma warning(pop) +} // namespace + +ComPtr<ID3D12PipelineState> Host::mesh_pipeline_with(ID3D12RootSignature* root, std::span<const std::uint8_t> ms, + std::span<const std::uint8_t> ps) const { + struct Stream { + Sub<ID3D12RootSignature*> root; + Sub<D3D12_SHADER_BYTECODE> ms; + Sub<D3D12_SHADER_BYTECODE> ps; + Sub<D3D12_BLEND_DESC> blend; + Sub<UINT> mask; + Sub<D3D12_RASTERIZER_DESC> raster; + Sub<D3D12_DEPTH_STENCIL_DESC> depth; + Sub<D3D12_RT_FORMAT_ARRAY> targets; + Sub<DXGI_FORMAT> dsv; + Sub<DXGI_SAMPLE_DESC> samples; + }; + const std::vector<SigElement> outputs = sig(ps, dxbc::FourCC::OSG1); + D3D12_BLEND_DESC blend{}; + for (auto& rt : blend.RenderTarget) rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + const Targets t = targets(outputs); + Stream stream{ + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, code(ms)}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, code(ps)}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, blend}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, UINT32_MAX}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, rasterizer()}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, t.depth}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, t.rts}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, t.dsv}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC{1, 0}}, + }; + D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(Stream), &stream}; + ComPtr<ID3D12Device2> device2; + HRESULT hr = device.As(&device2); + if (FAILED(hr)) throw Error(message(hr)); + // The stream points at live data and outlives the call. + ComPtr<ID3D12PipelineState> pso; + hr = device2->CreatePipelineState(&desc, IID_PPV_ARGS(&pso)); + if (FAILED(hr)) throw Error(message(hr)); + return pso; +} + +namespace { + +std::vector<std::uint8_t> stub(bool pixel, std::vector<SigElement> outputs) { + shader::Shader s(pixel); + const std::size_t b = s.entry; + for (std::size_t id = 0; id < outputs.size(); ++id) { + const SigElement& e = outputs[id]; + for (std::uint8_t col = 0; col < e.cols; ++col) { + // Allocate zero before the id and column operands. + const char* suffix; + bitcode::V zero; + if (e.comp == 9) { + suffix = ".f32"; + zero = s.m.f32(0); + } else { + suffix = ".i32"; + zero = s.m.i32(0); + } + const bitcode::V a0 = s.m.i32(static_cast<std::uint32_t>(id)); + const bitcode::V a1 = s.m.i32(0); + const bitcode::V a2 = s.m.i8(col); + const bitcode::V args[] = {a0, a1, a2, zero}; + s.op(b, std::string("storeOutput") + suffix, bitcode::Attr::NoUnwind, s.t.void_, 5, args); + } + } + for (SigElement& e : outputs) e.usage = static_cast<std::uint8_t>((1u << e.cols) - 1); + s.outputs = std::move(outputs); + s.m.terminate(b, bitcode::Term::ret()); + return s.finish(); +} + +} // namespace + +std::vector<std::uint8_t> stub_vs_dxil(std::span<const std::uint8_t> ps) { + std::vector<SigElement> outputs; + for (SigElement& e : sig(ps, dxbc::FourCC::ISG1)) + if (e.kind == 0 || e.kind == 3 || e.kind == 6 || e.kind == 7) outputs.push_back(std::move(e)); + if (std::none_of(outputs.begin(), outputs.end(), [](const SigElement& e) { return e.kind == 3; })) { + std::uint32_t row = 0; + for (const SigElement& e : outputs) + if (e.row) row = std::max(row, *e.row + 1); + SigElement pos; + pos.name = "SV_Position"; + pos.index = 0; + pos.kind = 3; + pos.comp = 9; + pos.interp = 4; + pos.row = row; + pos.col = 0; + pos.cols = 4; + pos.usage = 0; + pos.half = false; + outputs.push_back(std::move(pos)); + } + return stub(false, std::move(outputs)); +} + +std::vector<std::uint8_t> stub_ps_dxil() { + SigElement target; + target.name = "SV_Target"; + target.index = 0; + target.kind = 16; + target.comp = 9; + target.interp = 0; + target.row = 0; + target.col = 0; + target.cols = 4; + target.usage = 0; + target.half = false; + return stub(true, {target}); +} + +#if X2W_VS_HOST_STUBS + +namespace { +HostShader stub_shader(bool pixel, std::vector<std::uint8_t> dxil) { + HostShader h; + h.stage = pixel ? native::HwStage::Ps : native::HwStage::Vs; + h.dxil = std::move(dxil); + return h; +} +} // namespace + +HostShader stub_vs(const HostShader& ps) { return stub_shader(false, stub_vs_dxil(ps.dxil)); } + +HostShader stub_ps() { return stub_shader(true, stub_ps_dxil()); } + +#endif // X2W_VS_HOST_STUBS + +} // namespace x2w::vs::host diff --git a/src/x2w_shader/emit/host.h b/src/x2w_shader/emit/host.h new file mode 100644 index 0000000000..8b955d4e11 --- /dev/null +++ b/src/x2w_shader/emit/host.h @@ -0,0 +1,256 @@ +#pragma once + +// Check emitted shaders by creating host D3D12 pipelines. Host::draw renders a full-screen triangle and +// Host::dispatch executes a compute shader. Both support readback in tests. +// +// Host failures throw host::Error with the diagnostic in what(). +// +// Stage borrows the DXIL, user data size, static samplers and root CBV/SRV/UAV bindings of a HostShader +// (emit.h). It converts implicitly from a compatible shader so the host can build a pipeline without +// depending on native.h. Keep the shader alive through the call. +// +// stub_vs and stub_ps need HostShader complete: they are compiled once x2w_shader/native.h exists. +// The DXIL they carry is stub_vs_dxil/stub_ps_dxil (additions, built now). + +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cstdint> +#include <span> +#include <stdexcept> +#include <string> +#include <utility> +#include <vector> + +#include "x2w_shader/emit/sampler.h" + +namespace x2w::vs { +struct HostShader; +} + +namespace x2w::vs::host { + +using Microsoft::WRL::ComPtr; + +// A host pipeline or device failure. +struct Error : std::runtime_error { + using std::runtime_error::runtime_error; +}; + +// What the host reads of a HostShader. Borrows. +struct Stage { + std::span<const std::uint8_t> dxil; + std::uint32_t user_data_dwords = 0; + std::span<const sampler::StaticSampler> static_samplers; + std::span<const std::uint8_t> root_cbvs; + std::span<const std::uint8_t> root_srvs; + std::span<const std::uint8_t> root_uavs; + + Stage() = default; + template <class S> + requires requires(const S& s) { + s.dxil; + s.user_data_dwords(); + s.static_samplers; + s.root_cbvs; + s.root_srvs; + s.root_uavs; + } + Stage(const S& s) // NOLINT: implicit shader-to-stage conversion + : dxil(s.dxil), + user_data_dwords(s.user_data_dwords()), + static_samplers(s.static_samplers), + root_cbvs(s.root_cbvs), + root_srvs(s.root_srvs), + root_uavs(s.root_uavs) {} +}; + +using Pipeline = std::pair<ComPtr<ID3D12RootSignature>, ComPtr<ID3D12PipelineState>>; + +// A root argument for Host::draw / Host::dispatch. +struct Root { + enum Kind : std::uint8_t { Constants, Table, View }; + Kind kind = Constants; + // Constants: the dwords. View: the buffer's dwords. + std::vector<std::uint32_t> data; + // Table: a table starting at this heap index (of the sampler heap with sampler). + bool sampler = false; + std::size_t index = 0; + // View: a root CBV (or with srv, a root SRV) over a buffer of data (Host::dispatch only). + bool srv = false; + + static Root constants(std::vector<std::uint32_t> data) { return Root{Constants, std::move(data), false, 0, false}; } + static Root table(bool sampler, std::size_t index) { return Root{Table, {}, sampler, index, false}; } + static Root view(bool srv, std::vector<std::uint32_t> data) { return Root{View, std::move(data), false, 0, srv}; } +}; + +// An RGBA32F texture for Host::draw: (width, height, texels). +struct Texture { + std::uint32_t width = 0; + std::uint32_t height = 0; + std::span<const std::array<float, 4>> texels; +}; + +// Bindings for Host::draw: root arguments and the heap contents. +struct Draw { + std::vector<std::pair<std::uint32_t, Root>> roots; + // RGBA32F textures at view-heap indices 0.. + std::span<const Texture> textures; + // Samplers at sampler-heap indices 0.. + std::span<const D3D12_SAMPLER_DESC> samplers; + // Three vertices of stride bytes (none for position-free layouts). + std::span<const float> vertices; + std::uint32_t stride = 0; + std::pair<std::uint32_t, std::uint32_t> size{}; + // Mesh thread groups to dispatch instead of drawing (0: draw). + std::uint32_t mesh_groups = 0; +}; + +// How View::Buffer is viewed. +struct Stride { + enum Kind : std::uint8_t { + Raw, + // RGBA32F elements. + Typed, + // Structured, elements of bytes bytes. + Structured, + // Typed, elements in format of bytes bytes. + Format, + }; + Kind kind = Raw; + std::uint32_t bytes = 0; + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + + static Stride raw() { return Stride{Raw, 0, DXGI_FORMAT_UNKNOWN}; } + static Stride typed() { return Stride{Typed, 0, DXGI_FORMAT_UNKNOWN}; } + static Stride structured(std::uint32_t bytes) { return Stride{Structured, bytes, DXGI_FORMAT_UNKNOWN}; } + static Stride format_of(DXGI_FORMAT f, std::uint32_t bytes) { return Stride{Format, bytes, f}; } +}; + +// A view in the heap for Host::dispatch. +struct View { + enum Kind : std::uint8_t { + // An RGBA32F texture SRV (width, height, texels). + Texture, + // An RGBA32F cube SRV (face size, mip count, texels in D3D subresource order). + Cube, + // A raw buffer UAV of n dwords, zeroed. + RawUav, + // An RGBA32F texture UAV (width, height), zeroed. + TextureUav, + // An R32_UINT texture UAV (width, height), zeroed (atomics). + UintTextureUav, + // A typed RGBA16F buffer UAV of n elements, zeroed. + HalfUav, + // A constant buffer of data. + Cbv, + // A buffer SRV over data. + Buffer, + }; + Kind kind = RawUav; + // Texture/TextureUav/UintTextureUav: width, height. Cube: face size in w (and h). + std::uint32_t w = 0; + std::uint32_t h = 0; + // Cube: mip count. + std::uint16_t mips = 1; + // RawUav: dwords. HalfUav: elements. + std::uint32_t n = 0; + std::span<const std::array<float, 4>> texels; + std::span<const std::uint32_t> data; + Stride stride; + + static View texture(std::uint32_t w, std::uint32_t h, std::span<const std::array<float, 4>> t) { + View v; v.kind = Texture; v.w = w; v.h = h; v.texels = t; return v; + } + static View cube(std::uint32_t size, std::uint16_t mips, std::span<const std::array<float, 4>> t) { + View v; v.kind = Cube; v.w = size; v.h = size; v.mips = mips; v.texels = t; return v; + } + static View raw_uav(std::uint32_t dwords) { View v; v.kind = RawUav; v.n = dwords; return v; } + static View texture_uav(std::uint32_t w, std::uint32_t h) { View v; v.kind = TextureUav; v.w = w; v.h = h; return v; } + static View uint_texture_uav(std::uint32_t w, std::uint32_t h) { + View v; v.kind = UintTextureUav; v.w = w; v.h = h; return v; + } + static View half_uav(std::uint32_t elements) { View v; v.kind = HalfUav; v.n = elements; return v; } + static View cbv(std::span<const std::uint32_t> d) { View v; v.kind = Cbv; v.data = d; return v; } + static View buffer(std::span<const std::uint32_t> d, Stride s) { + View v; v.kind = Buffer; v.data = d; v.stride = s; return v; + } +}; + +// Bindings for Host::dispatch: root arguments, the view heap in order, the sampler heap, and the +// group counts. +struct Dispatch { + std::vector<std::pair<std::uint32_t, Root>> roots; + std::span<const View> views; + std::span<const D3D12_SAMPLER_DESC> samplers; + std::array<std::uint32_t, 3> groups{1, 1, 1}; +}; + +class Host { +public: + ComPtr<ID3D12Device> device; + + // The default adapter, or WARP with warp (or X2W_SHADERCFG_WARP=1). Throws Error (also when the + // default device is the software adapter or lacks SM 6.6: tests then skip). + explicit Host(bool warp); + static Host create(bool warp) { return Host(warp); } + + // The root signature translated shaders expect: user data per stage at b0, immediate + // samplers per stage at s<n>, heaps directly indexed. + ComPtr<ID3D12RootSignature> root_signature(const Stage& vs, const Stage& ps) const; + // The root signature for these stages: user data of stage k is root parameter k, root views + // follow. + ComPtr<ID3D12RootSignature> root_signature_for(std::span<const std::pair<Stage, D3D12_SHADER_VISIBILITY>> stages) const; + ComPtr<ID3D12RootSignature> root_signature_for(std::initializer_list<std::pair<Stage, D3D12_SHADER_VISIBILITY>> stages) const { + return root_signature_for(std::span(stages.begin(), stages.size())); + } + + // A compute pipeline; user data is root parameter 0. + Pipeline compute_pipeline(const Stage& cs) const; + ComPtr<ID3D12PipelineState> compute_pipeline_with(ID3D12RootSignature* root, std::span<const std::uint8_t> cs) const; + + // A graphics pipeline from a vertex and a pixel shader, with float or integer 32-bit targets + // as the pixel shader writes them. + Pipeline pipeline(const Stage& vs, const Stage& ps) const; + // A graphics pipeline with the given root signature; vertex inputs packed in register order. + ComPtr<ID3D12PipelineState> pipeline_with(ID3D12RootSignature* root, std::span<const std::uint8_t> vs, + std::span<const std::uint8_t> ps) const; + // As pipeline_with, with a geometry shader between the two (the rectangle stage, + // rect_list_gs); gs empty: none. + ComPtr<ID3D12PipelineState> pipeline_with_gs(ID3D12RootSignature* root, std::span<const std::uint8_t> vs, + std::span<const std::uint8_t> gs, + std::span<const std::uint8_t> ps) const; + // A mesh pipeline from a mesh and a pixel shader (user data of the mesh stage is root + // parameter 0, the pixel stage's 1). + Pipeline mesh_pipeline(const Stage& ms, const Stage& ps) const; + // A mesh pipeline with the given root signature: the pipeline-state stream form, with the + // targets pipeline_with would use. + ComPtr<ID3D12PipelineState> mesh_pipeline_with(ID3D12RootSignature* root, std::span<const std::uint8_t> ms, + std::span<const std::uint8_t> ps) const; + + // Draws one triangle into an RGBA32F target and returns its texels. + std::vector<std::array<float, 4>> draw(ID3D12RootSignature* root, ID3D12PipelineState* pso, const Draw& d) const; + // Runs a compute pipeline and returns each UAV's contents in heap order (texels as float + // bits, row by row). + std::vector<std::vector<std::uint32_t>> dispatch(ID3D12RootSignature* root, ID3D12PipelineState* pso, + const Dispatch& d) const; + + // The error text with the debug layer's messages since the last call, if the layer is on + // (X2W_SHADERCFG_D3D12_DEBUG). + std::string explained(HRESULT hr) const; +}; + +// A vertex shader that feeds ps's inputs (zeros) and a position. (Needs native.h.) +HostShader stub_vs(const HostShader& ps); +// A pixel shader that reads nothing and writes target 0. (Needs native.h.) +HostShader stub_ps(); +// The containers of stub_vs (from the pixel shader's container) and stub_ps. +std::vector<std::uint8_t> stub_vs_dxil(std::span<const std::uint8_t> ps); +std::vector<std::uint8_t> stub_ps_dxil(); + +// Format the system message for an HRESULT. +std::string message(HRESULT hr); + +} // namespace x2w::vs::host diff --git a/src/x2w_shader/emit/lower.h b/src/x2w_shader/emit/lower.h new file mode 100644 index 0000000000..3392449c29 --- /dev/null +++ b/src/x2w_shader/emit/lower.h @@ -0,0 +1,163 @@ +// IR to DXIL, one machine instruction at a time. +// +// Every register dword is an `i32` (SCC an `i1`); float operations bitcast their operands. Lane +// masks exist only as the per-lane booleans of structurisation; branches and guards are built from +// them. A value the emitter cannot express is `Missing` with a reason, and only fails the program +// when something with an effect (an export, a branch) needs it. +// +// This header is what the rest of emit/ (mod.cpp) uses of the lowering. The emitter's state and +// its methods are private: lower_impl.h. +// +// Lowering reports translation failures by throwing ShaderError (lib.h). +#pragma once + +#include <array> +#include <cstdint> +#include <optional> +#include <string_view> +#include <utility> +#include <vector> + +#include "x2w_shader/emit/container.h" // SigElement +#include "x2w_shader/emit/emit.h" // UserData +#include "x2w_shader/error.h" +#include "x2w_shader/io.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/native.h" +#include "x2w_shader/resource.h" +#include "x2w_shader/structure.h" + +namespace x2w::vs::lower { + +using container::SigElement; + +// static text, compared by content. +using Why = const char*; + +struct Lowered { + std::vector<std::uint8_t> dxil; + // Bit n: immediate sampler n is a comparison sampler. + std::uint64_t cmp_samplers = 0; + std::vector<std::uint8_t> root_cbvs; + std::vector<std::uint8_t> root_srvs; + std::vector<std::uint8_t> root_uavs; + std::vector<UserData> user_data; + std::vector<std::array<std::uint32_t, 4>> samplers; + // The wave size the shader requires of the host, if any. + std::optional<std::uint32_t> wave_size; + // Test counters record non-uniform heap indexing and wave operations. + std::uint32_t nonuniform_handles = 0; + bool wave_ops = false; +}; + +struct Parts { + const native::NativeProgram* native = nullptr; + const ir::Program* p = nullptr; + const structure::Structured* st = nullptr; + const io::Io* io = nullptr; + const resource::Resources* res = nullptr; + std::vector<SigElement> inputs; + std::vector<SigElement> outputs; + std::vector<SigElement> prims; + // Mesh: what the group id arrives multiplied by. + std::uint32_t mesh_stride = 0; +}; + +// Throws ShaderError. +Lowered lower(const Parts& parts); + +// `lower`; `counted`: the lanes past a dispatch's count of threads leave at once (shader.h +// USER_DISPATCH_THREADS_X). Throws ShaderError. +Lowered lower_counted(const Parts& parts, bool counted); + +// Iterations after which a loop is left (per entry into it), unless x2w::vs::loop_limit() says +// otherwise. A lane that reaches the limit leaves the program as killed (a pixel discards). +inline constexpr std::uint32_t LOOP_LIMIT = 1u << 20; + +// What a value holding a lane mask read as a number stops with. +inline constexpr Why LANE_MASK = "a lane mask read as data"; +// A mask with lanes outside EXEC where it is written, read as a number where the lanes that run +// that block are not all of the wave. +inline constexpr Why MASK_ELSEWHERE = "a lane mask holding lanes elsewhere read as data"; +// The refusal of a first half of an interpolation whose result is read as data. +inline constexpr Why FIRST_HALF = "the first half of an interpolation"; + +// The per-lane branches (by block) whose regions hold a block of `needs`: the ones to take +// wave-wide (structure::structure_wide). None if one of them has no known wave-wide meaning. +std::optional<std::vector<std::size_t>> branches_around(const structure::Structured& st, + const std::vector<std::size_t>& needs); +// Whether a refusal is of code that needs every lane of the wave where it stands. +bool needs_every_lane(std::string_view what); +// The blocks where the last lowering on this thread wanted every lane and did not have it, which +// it forgets. +std::vector<std::size_t> take_needs(); + +// Whether a console wave64 program may run with each host wave as a wave of its own. Error: +// (offset, what). +std::optional<std::pair<std::size_t, Why>> wave_local(const ir::Program& p, + const structure::Structured& st); + +bool reads_mask_as_data(const structure::Structured& st, const ir::Inst& i); + +// The host GPU's WaveLaneCountMax (process-wide). +void set_host_max_wave(std::uint32_t lanes); +std::uint32_t host_max_wave(); +// Tells the translator that the host's shaders run on AMD RDNA hardware (emit::rdna_float()). +void set_host_rdna(bool on); +// The bits of emit::rdna that count on this host. +std::uint32_t host_rdna(); +// What the translator was told of the host, for a cache's key. +std::array<std::uint32_t, 4> host_settings(); + +namespace detail { +// Thread-local switches for the with_* scopes below. +bool replace_local_waves(bool on); +bool replace_local_any(bool on); +bool replace_first_half_pairs(bool on); +} // namespace detail + +// Run f with each 32-lane host wave treated as an independent wave for console Wave64 programs. Restore the +// switch even if f throws. +template <class F> +auto with_local_waves(F&& f) -> decltype(f()) { + struct Restore { + bool was; + ~Restore() { detail::replace_local_waves(was); } + } r{detail::replace_local_waves(true)}; + return f(); +} + +// As with_local_waves, with every other use of a lane mask as a number and every lane read and +// write taken per host wave too. +template <class F> +auto with_local_waves_any(F&& f) -> decltype(f()) { + struct Restore { + bool was; + ~Restore() { detail::replace_local_any(was); } + } r{detail::replace_local_any(true)}; + return with_local_waves(std::forward<F>(f)); +} + +// Runs `translate` with first halves of interpolations evaluated as the pair they start. +template <class F> +auto with_first_half_pairs(F&& translate) -> decltype(translate()) { + struct Restore { + bool was; + ~Restore() { detail::replace_first_half_pairs(was); } + } r{detail::replace_first_half_pairs(true)}; + return translate(); +} + +// Per-thread test hooks. +namespace test { +// VS_DUMP=<dir> names the modules lowered from now on <name>__<n>.dxil. +void set_dump_name(std::string_view name); +void set_f16_nearest(std::optional<bool> on); +void set_rdna(std::optional<std::uint32_t> bits); +void set_host_wave(std::optional<std::uint32_t> lanes); +// TEST_MEMORY identifies a heap slot for a raw buffer and the title address of its first byte for device +// tests. +void set_memory(std::optional<std::pair<std::uint32_t, std::uint64_t>> slot_and_address); +} // namespace test + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_buffer_exit.cpp b/src/x2w_shader/emit/lower_buffer_exit.cpp new file mode 100644 index 0000000000..f646e02c00 --- /dev/null +++ b/src/x2w_shader/emit/lower_buffer_exit.cpp @@ -0,0 +1,1158 @@ +// Buffer accesses, exports, block exits, loop counters, edges and phis. +#include <algorithm> +#include <cstdlib> +#include <set> +#include <stdexcept> +#include <string> + +#include "x2w_shader/emit/lower_impl.h" + +namespace x2w::vs::lower { + +namespace { + +[[noreturn]] void unreachable_here() { throw std::logic_error("unreachable"); } + +// Replace every occurrence. +std::string replace_all(std::string_view s, std::string_view from, std::string_view to) { + std::string out; + std::size_t at = 0; + while (true) { + std::size_t k = s.find(from, at); + if (k == std::string_view::npos) { + out.append(s.substr(at)); + return out; + } + out.append(s.substr(at, k - at)); + out.append(to); + at = k + from.size(); + } +} + +std::optional<std::string_view> strip_prefix(std::string_view s, std::string_view p) { + if (s.starts_with(p)) return s.substr(p.size()); + return std::nullopt; +} + +// ---- front-end shapes (vs-front headers not published when written) ---- +// Usage::Other(0) +bool usage_is_other0(const Usage& u) { return u.kind == Usage::Kind::Other && u.other == 0; } +// LaneExit::Branch { when, .. } on a condition not over uniform atoms only. +bool all_uniform(const Structured& st, Bool when) { + for (const Atom& a : st.bools.support(when)) { + if (a.kind != Atom::Kind::Uniform) return false; + } + return true; +} + +} // namespace + +void Lower::buffer(const Inst& inst, std::size_t b, std::size_t i) { + this->root_copy = std::nullopt; + const auto* bf = std::get_if<gfx10::Buffer>(&inst.fields); + if (!bf) unreachable_here(); + const auto& data = bf->data; + const auto& addr = bf->addr; + const auto& soffset = bf->soffset; + const std::uint16_t offset = bf->offset; + const bool offen = bf->offen; + const bool idxen = bf->idxen; + const auto& format = bf->format; + std::string_view name = inst.name(); + if (name == "buffer_gl0_inv" || name == "buffer_gl1_inv") { + // The host has no console buffer cache to invalidate. + return; + } + if (bf->lds || bf->tfe) fail("a buffer access to LDS or with tfe"); + if (format.has_value() && !name.starts_with("tbuffer_load_format_")) fail(name.data()); + const Site site = {b, i}; + const std::optional<V> guard = this->guard(b, i); + const std::size_t c = this->cur; + const bool store = name.starts_with("buffer_store_"); + // DXIL atomic operations: add, and, or, xor, signed and unsigned min and max, exchange; + // compare-exchange apart. + std::optional<std::uint32_t> atomic; + if (auto rest = strip_prefix(name, "buffer_atomic_")) { + if (*rest == "add") atomic = 0; + else if (*rest == "and") atomic = 1; + else if (*rest == "or") atomic = 2; + else if (*rest == "xor") atomic = 3; + else if (*rest == "smin") atomic = 4; + else if (*rest == "smax") atomic = 5; + else if (*rest == "umin") atomic = 6; + else if (*rest == "umax") atomic = 7; + else if (*rest == "swap") atomic = 8; + else if (*rest == "cmpswap") atomic = UINT32_MAX; + else fail(name.data()); + } + // Byte and 16-bit accesses: bits, and whether a load sign-extends. + std::optional<std::pair<std::uint32_t, bool>> narrow; + if (name == "buffer_load_ubyte" || name == "buffer_store_byte") narrow = std::pair{8u, false}; + else if (name == "buffer_load_sbyte") narrow = std::pair{8u, true}; + else if (name == "buffer_load_ushort" || name == "buffer_store_short") narrow = std::pair{16u, false}; + else if (name == "buffer_load_sshort") narrow = std::pair{16u, true}; + // d16: two 16-bit channels per VGPR, low half first (buffer and tbuffer formats alike). + const bool d16 = name.find("_format_d16_") != std::string_view::npos; + const std::string plain = replace_all(name, "_format_d16_", "_format_"); + std::optional<std::string_view> kind = strip_prefix(plain, "buffer_load_"); + if (!kind) kind = strip_prefix(plain, "buffer_store_"); + if (!kind) kind = strip_prefix(plain, "tbuffer_load_"); + bool typed = false; + std::uint32_t count = 0; + if (atomic.has_value() || narrow.has_value()) { + typed = false, count = 1; + } else if (kind == "dword") { + typed = false, count = 1; + } else if (kind == "dwordx2") { + typed = false, count = 2; + } else if (kind == "dwordx3") { + typed = false, count = 3; + } else if (kind == "dwordx4") { + typed = false, count = 4; + } else if (kind == "format_x") { + typed = true, count = 1; + } else if (kind == "format_xy") { + typed = true, count = 2; + } else if (kind == "format_xyz") { + typed = true, count = 3; + } else if (kind == "format_xyzw") { + typed = true, count = 4; + } else { + fail(name.data()); + } + if (addr.kind != Operand::Kind::Vector) fail("a buffer address"); + const std::uint8_t areg = addr.reg; + auto vaddr = [&](Lower& l, std::uint8_t k) -> V { + Value v = ok_or(inst.read(Reg::V(static_cast<std::uint8_t>(areg + k))), "a buffer address"); + return l.i32_of(v); + }; + std::optional<V> index; + if (idxen) index = vaddr(*this, 0); + V off = this->s.m.i32(static_cast<std::uint32_t>(offset)); + if (offen) { + V o = vaddr(*this, static_cast<std::uint8_t>(idxen ? 1 : 0)); + off = this->s.m.bin(c, Bin::Add, off, o); + } + if (!((soffset.kind == Operand::Kind::Scalar && soffset.code == gfx10::NULL_CODE) || + (soffset.kind == Operand::Kind::Const && soffset.code == 128))) { + V so = this->operand(inst, soffset); + off = this->s.m.bin(c, Bin::Add, off, so); + } + const Source* src = nullptr; + { + auto it = this->descriptors.find(std::pair{site, false}); + if (it == this->descriptors.end()) fail("an untracked buffer"); + src = it->second; + } + const UsedResource* used = this->used_kind(*src); + auto [base, extra] = this->built_offset(*src); + if (base != 0) { + V bk = this->s.m.i32(base); + off = this->s.m.bin(c, Bin::Add, off, bk); + } + if (extra) off = this->s.m.bin(c, Bin::Add, off, *extra); + // A buffer the program picks from the view heap by an index it computes: no used-resource + // entry gives its stride, the host's table by heap slot does; the access becomes a raw one at + // the element's byte. (Also tells the host this shader reads such buffers.) + { + std::optional<V> stride = this->slot_stride(*src); + if (stride && index && !typed && used == nullptr) { + V at = this->s.m.bin(c, Bin::Mul, *index, *stride); + off = this->s.m.bin(c, Bin::Add, at, off); + index = std::nullopt; + } + } + // A structured buffer by its used-resource entry's stride: raw bytes too. The host makes its + // buffer views raw (a raw read through a structured view gives zeros on NVIDIA), and one kind + // of view can then serve every shader that reads the buffer. + if (index && used && !typed && used->kind != ResourceType::Cbv() && used->stride >= 4 && + used->stride % 4 == 0) { + V k = this->s.m.i32(used->stride); + V at = this->s.m.bin(c, Bin::Mul, *index, k); + off = this->s.m.bin(c, Bin::Add, at, off); + index = std::nullopt; + } + if (used && used->kind == ResourceType::Cbv() && !typed) { + // A constant buffer read per lane (a dynamically indexed array). + // shortcut: the console's CBV descriptor is taken to have a 16-byte stride, as the vector + // loads of whole rows suggest. + V h = this->handle(site, *src, false, {13, 0x1'0000}); + V byte = off; + if (index) { + V sixteen = this->s.m.i32(16); + V rows = this->s.m.bin(c, Bin::Mul, *index, sixteen); + byte = this->s.m.bin(c, Bin::Add, rows, off); + } + if (!data || data->kind != Operand::Kind::Vector) fail("a buffer result"); + const std::uint8_t reg = data->reg; + for (std::uint32_t k = 0; k < count; ++k) { + V four = this->s.m.i32(4 * k); + V a = this->s.m.bin(c, Bin::Add, byte, four); + V x = this->cbuffer_dword(h, a); + this->write(inst, Reg::V(static_cast<std::uint8_t>(reg + k)), x, guard); + } + return; + } + if (this->root_address(*src).has_value()) { + // Title memory by address: the byte in the host copy from here on. + if (index) { + if (used == nullptr || used->stride != 1) { + fail("an indexed access through a root view by address"); + } + off = this->s.m.bin(c, Bin::Add, *index, off); + index = std::nullopt; + } + if (auto m = this->root_memory(*src, off, guard, store || atomic.has_value())) { + off = m->second; + } + } + const std::size_t c2 = this->cur; + const bool uav = store || atomic.has_value() || (used && used->kind == ResourceType::Uav()); + std::uint32_t u = uav ? 0x1000 : 0; + if (uav && !typed) { + auto e = this->entry(*src); + if (e && this->coherent.contains(*e)) u |= 0x4000; + } + V iu = this->s.m.undef(this->s.t.i32); + if (narrow) { + const auto [bits, signed_] = *narrow; + // Below a dword: raw buffers are read and written in dwords on 4 bytes, so the dword that + // holds the value is read and shifted, or changed with two atomic operations that touch + // only the value's own bits (other lanes may write the rest of the dword at the same + // time). A 16-bit value at a dword's last byte continues in the next dword. + V byte = off; + if (index) { + if (used && used->stride == 1) { + byte = this->s.m.bin(c2, Bin::Add, *index, off); + } else { + fail("a byte or 16-bit buffer access by index"); + } + } + V h = this->handle(site, *src, false, {11 | u, 0}); + V k3 = this->s.m.i32(3); + V within = this->s.m.bin(c2, Bin::And, byte, k3); + V aligned = this->s.m.bin(c2, Bin::Sub, byte, within); + V shift = this->s.m.bin(c2, Bin::Shl, within, k3); + V four = this->s.m.i32(4); + V next = this->s.m.bin(c2, Bin::Add, aligned, four); + V ones = this->s.m.i32(bits == 8 ? 0xff : 0xffff); + V zero = this->s.m.i32(0); + V k8 = this->s.m.i32(8); + V straddles = this->s.m.cmp(c2, pred::EQ, within, k3); + if (!store) { + V mask = this->s.m.i8(1); + V align = this->s.m.i32(4); + auto dword = [&](Lower& l, V at) -> V { + V r = l.s.op(c2, "rawBufferLoad.f32", Attr::ReadOnly, l.s.t.res_ret, 139, + std::vector<V>{h, at, iu, mask, align}); + V f = l.s.m.extract(c2, r, 0); + return l.as_int(f); + }; + V low = dword(*this, aligned); + V x = this->s.m.bin(c2, Bin::LShr, low, shift); + if (bits == 16) { + V high = dword(*this, next); + high = this->s.m.bin(c2, Bin::Shl, high, k8); + high = this->s.m.select(c2, straddles, high, zero); + x = this->s.m.bin(c2, Bin::Or, x, high); + } + x = this->s.m.bin(c2, Bin::And, x, ones); + if (signed_) { + V up = this->s.m.i32(32 - bits); + x = this->s.m.bin(c2, Bin::Shl, x, up); + x = this->s.m.bin(c2, Bin::AShr, x, up); + } + if (!data || data->kind != Operand::Kind::Vector) fail("a buffer result"); + this->write(inst, Reg::V(data->reg), x, guard); + return; + } + if (!data) fail("buffer store data"); + const Operand& d = *data; + V v = this->vgprs(inst, d, 1).at(0); + v = this->s.m.bin(c2, Bin::And, v, ones); + V all = this->s.m.i32(UINT32_MAX); + V clear = this->s.m.bin(c2, Bin::Shl, ones, shift); + V keep = this->s.m.bin(c2, Bin::Xor, clear, all); + V set = this->s.m.bin(c2, Bin::Shl, v, shift); + V keep_next = this->s.m.i32(0xffff'ff00u); + V set_next = this->s.m.bin(c2, Bin::LShr, v, k8); + V and_ = this->s.m.i32(1); + V or_ = this->s.m.i32(2); + const Ty i32t = this->s.t.i32; + auto at = this->begin_guarded(guard); + for (auto [op, x] : {std::pair{and_, keep}, std::pair{or_, set}}) { + this->s.op(this->cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, + std::vector<V>{h, op, aligned, iu, iu, x}); + } + if (bits == 16) { + auto second = this->begin_guarded(straddles); + for (auto [op, x] : {std::pair{and_, keep_next}, std::pair{or_, set_next}}) { + this->s.op(this->cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, + std::vector<V>{h, op, next, iu, iu, x}); + } + this->end_guarded(second, {}); + } + this->end_guarded(at, {}); + return; + } + if (atomic) { + const std::uint32_t op = *atomic; + if (!data) fail("buffer atomic data"); + const Operand& d = *data; + std::vector<V> vals = this->vgprs(inst, d, op == UINT32_MAX ? 2 : 1); + V h{}; + std::array<V, 3> coords{}; + if (index && used && used->stride == 1) { + // A raw buffer (stride 1) read by index: the index is the byte. + V byte = this->s.m.bin(c2, Bin::Add, *index, off); + h = this->handle(site, *src, false, {11 | u, 0}); + coords = {byte, iu, iu}; + } else if (index) { + const std::uint32_t stride = used ? used->stride : 0; + if (stride < 4 || stride % 4 != 0) fail("a structured buffer of unknown stride"); + h = this->handle(site, *src, false, {12 | u, stride}); + coords = {*index, off, iu}; + } else { + h = this->handle(site, *src, false, {11 | u, 0}); + coords = {off, iu, iu}; + } + if (d.kind != Operand::Kind::Vector) fail("buffer atomic data"); + const std::uint8_t reg = d.reg; + const bool returns = bf->cache.glc; + V old{}; + { + auto r = inst.read(Reg::V(reg)); + if (r && returns) { + old = this->i32_of(*r); + } else { + old = this->s.m.i32(0); + } + } + auto at = this->begin_guarded(guard); + const Ty i32t = this->s.t.i32; + V r{}; + if (op == UINT32_MAX) { + // cmpswap: data is (new, compare). + std::vector<V> args{h}; + args.insert(args.end(), coords.begin(), coords.end()); + args.push_back(vals.at(1)); + args.push_back(vals.at(0)); + r = this->s.op(this->cur, "atomicCompareExchange.i32", Attr::NoUnwind, i32t, 79, args); + } else { + V opk = this->s.m.i32(op); + std::vector<V> args{h, opk}; + args.insert(args.end(), coords.begin(), coords.end()); + args.push_back(vals.at(0)); + r = this->s.op(this->cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, args); + } + const std::pair<V, V> joined[] = {{r, old}}; + r = this->end_guarded(at, joined).at(0); + if (returns) this->write(inst, Reg::V(reg), r, std::nullopt); + return; + } + if (store) { + const std::uint32_t regs = d16 ? div_ceil(count, 2u) : count; + if (!data) fail("buffer store data"); + std::vector<V> vals = this->vgprs(inst, *data, static_cast<std::uint8_t>(regs)); + if (d16) { + // Widen d16 data as f16 for a 32-bit float store. For an integer view, zero- or sign-extend the 16-bit + // integer. The face network stores halves through UINT views. This format information is available for + // views selected from the heap. The handle remains float-typed and the driver passes its bits through. + std::optional<std::pair<V, V>> integer; + if (typed) integer = this->integer_view(*src); + std::vector<V> wide; + for (std::uint32_t k = 0; k < count; ++k) { + V x = vals.at(k / 2); + if (k % 2 == 1) { + V k16 = this->s.m.i32(16); + x = this->s.m.bin(c2, Bin::LShr, x, k16); + } + const Ty f32t = this->s.t.f32; + V f = this->s.op(c2, "legacyF16ToF32", Attr::ReadNone, f32t, 131, std::vector<V>{x}); + V w = this->as_int(f); + if (integer) { + const auto [int_, signed_] = *integer; + V k16 = this->s.m.i32(16); + V low = this->s.m.i32(0xFFFF); + V zero_ext = this->s.m.bin(c2, Bin::And, x, low); + V up = this->s.m.bin(c2, Bin::Shl, x, k16); + V sign_ext = this->s.m.bin(c2, Bin::AShr, up, k16); + V n = this->s.m.select(c2, signed_, sign_ext, zero_ext); + w = this->s.m.select(c2, int_, n, w); + } + wide.push_back(w); + } + vals = std::move(wide); + } + std::vector<V> args; + std::uint32_t op = 0; + std::string_view opname; + if (typed) { + // shortcut: typed stores are taken to write all four channels of a float format. + if (count != 4 || offen || offset != 0) { + fail("a typed buffer store of some channels or at an offset"); + } + args.push_back(this->handle(site, *src, false, {10 | u, 0x409})); + // Create the zero constant even when an index is present to preserve constant numbering. + V zero = this->s.m.i32(0); + args.push_back(index.value_or(zero)); + args.push_back(iu); + for (V x : vals) args.push_back(this->as_float(x)); + op = 69, opname = "bufferStore.f32"; + } else { + if (index && used && used->stride == 1) { + // A raw buffer (stride 1) written by index: the index is the byte. + V byte = this->s.m.bin(c2, Bin::Add, *index, off); + args.push_back(this->handle(site, *src, false, {11 | u, 0})); + args.push_back(byte); + args.push_back(iu); + } else if (index) { + const std::uint32_t stride = used ? used->stride : 0; + if (stride < 4 || stride % 4 != 0) fail("a structured buffer of unknown stride"); + args.push_back(this->handle(site, *src, false, {12 | u, stride})); + args.push_back(*index); + args.push_back(off); + } else { + args.push_back(this->handle(site, *src, false, {11 | u, 0})); + args.push_back(off); + args.push_back(iu); + } + args.insert(args.end(), vals.begin(), vals.end()); + args.resize(3 + 4, iu); + op = 140, opname = "rawBufferStore.i32"; + } + args.push_back(this->s.m.i8(typed ? 0xF : static_cast<std::uint8_t>((1u << count) - 1))); + if (!typed) args.push_back(this->s.m.i32(4)); + auto at = this->begin_guarded(guard); + const Ty void_t = this->s.t.void_; + this->s.op(this->cur, opname, Attr::NoUnwind, void_t, op, args); + this->end_guarded(at, {}); + return; + } + if (format) { + const std::uint8_t f = *format; + if (index) fail("a typed-format load by index"); + V h = this->handle(site, *src, false, {11 | u, 0}); + if (!data || data->kind != Operand::Kind::Vector) fail("a buffer result"); + const std::uint8_t reg = data->reg; + std::vector<V> xs = this->format_load(h, off, f, count); + if (d16) xs = this->d16_channels(f, std::move(xs)); + for (std::size_t k = 0; k < xs.size(); ++k) { + this->write(inst, Reg::V(static_cast<std::uint8_t>(reg + k)), xs[k], guard); + } + return; + } + V r{}; + if (typed) { + if (offen || off.kind == V::Inst || offset != 0) { + fail("a typed buffer load at an offset"); + } + if (uav) this->s.flags |= flags::TYPED_UAV_LOADS; + V h = this->handle(site, *src, false, {10 | u, 0x409}); + // Create the zero constant even when an index is present to preserve constant numbering. + V zero = this->s.m.i32(0); + V ix = index.value_or(zero); + r = this->s.op(c2, "bufferLoad.f32", Attr::ReadOnly, this->s.t.res_ret, 68, + std::vector<V>{h, ix, iu}); + } else { + V mask = this->s.m.i8(static_cast<std::uint8_t>((1u << count) - 1)); + V align = this->s.m.i32(4); + if (index && used && used->stride == 1) { + // A raw buffer (stride 1) read by index: the index is the byte. + V byte = this->s.m.bin(c2, Bin::Add, *index, off); + V h = this->handle(site, *src, false, {11 | u, 0}); + r = this->s.op(c2, "rawBufferLoad.f32", Attr::ReadOnly, this->s.t.res_ret, 139, + std::vector<V>{h, byte, iu, mask, align}); + } else if (index) { + const std::uint32_t stride = used ? used->stride : 0; + if (stride < 4 || stride % 4 != 0) fail("a structured buffer of unknown stride"); + V h = this->handle(site, *src, false, {12 | u, stride}); + r = this->s.op(c2, "rawBufferLoad.f32", Attr::ReadOnly, this->s.t.res_ret, 139, + std::vector<V>{h, *index, off, mask, align}); + } else { + V h = this->handle(site, *src, false, {11 | u, 0}); + r = this->s.op(c2, "rawBufferLoad.f32", Attr::ReadOnly, this->s.t.res_ret, 139, + std::vector<V>{h, off, iu, mask, align}); + } + } + if (!data || data->kind != Operand::Kind::Vector) fail("a buffer result"); + const std::uint8_t reg = data->reg; + if (d16) { + // Two f16 channels per VGPR (an odd last high half 0); the low 16 bits of an integer + // view's (see the stores above). + std::optional<std::pair<V, V>> integer; + if (typed) integer = this->integer_view(*src); + V k16 = this->s.m.i32(16); + const Ty i32t = this->s.t.i32; + for (std::uint32_t k = 0; k < div_ceil(count, 2u); ++k) { + std::optional<V> x; + const std::uint32_t end = std::min(2 * k + 2, count); + for (std::uint32_t ch = end; ch-- > 2 * k;) { + V f = this->s.m.extract(c2, r, ch); + V h = this->s.op(c2, "legacyF32ToF16", Attr::ReadNone, i32t, 130, std::vector<V>{f}); + if (integer) { + const V int_ = integer->first; + V bits = this->as_int(f); + V low = this->s.m.i32(0xFFFF); + low = this->s.m.bin(c2, Bin::And, bits, low); + h = this->s.m.select(c2, int_, low, h); + } + if (x) { + V hi = this->s.m.bin(c2, Bin::Shl, *x, k16); + x = this->s.m.bin(c2, Bin::Or, h, hi); + } else { + x = h; + } + } + if (!x) unreachable_here(); // expect("a channel") + this->write(inst, Reg::V(static_cast<std::uint8_t>(reg + k)), *x, guard); + } + return; + } + for (std::uint32_t k = 0; k < count; ++k) { + V x = this->s.m.extract(c2, r, k); + x = this->as_int(x); + this->write(inst, Reg::V(static_cast<std::uint8_t>(reg + k)), x, guard); + } +} + +void Lower::export_(std::size_t b, std::size_t i) { + const Export* e = nullptr; + { + auto it = this->exports.find(Site{b, i}); + if (it == this->exports.end()) fail("an export I/O raising did not see"); + e = it->second; + } + if (e->compressed) fail("a compressed export"); + const std::optional<V> guard = this->guard(b, i); + const bool mesh = this->s.mesh.has_value(); + const std::size_t c = this->cur; + if (guard && !mesh) { + const V g = *guard; + if (!(e->done && this->s.pixel)) fail("a conditional export"); + V t = this->s.m.bool_(true); + V kill = this->s.m.bin(c, Bin::Xor, g, t); + this->s.op(c, "discard", Attr::NoUnwind, this->s.t.void_, 82, std::vector<V>{kill}); + } + const Target& target = e->target; + if (mesh && target.kind == Target::Kind::Primitive) { + this->emit_indices(*e, guard); + return; + } + auto param_row = [&](const Usage& usage, std::uint8_t row) -> std::optional<std::uint8_t> { + // The 2020 compiler leaves a mesh program's first entry zeroed (usage "position"): its row + // is the one no other entry names. + if (usage_is_other0(usage) && mesh) return this->unnamed_row(); + return row; + }; + // (output element, channel) per exported channel; per-primitive outputs are elements of + // `prims`. + std::vector<std::tuple<std::size_t, std::uint8_t, Value, std::optional<bool>>> stores; + const bool primitive = target.kind == Target::Kind::PrimitiveParam; + const std::vector<SigElement>& outputs = primitive ? this->s.prims : this->s.outputs; + auto by_kind = [&](std::uint8_t kind) -> std::optional<std::size_t> { + for (std::size_t k = 0; k < outputs.size(); ++k) { + if (outputs[k].kind == kind) return k; + } + return std::nullopt; + }; + // 16-bit vertex outputs: the halves each dword carries, as (output element, channel, high + // half) per channel. + std::optional<std::pair<std::uint8_t, std::pair<bool, std::optional<std::uint8_t>>>> halves; + if (target.kind == Target::Kind::Param) { + if (auto r = param_row(target.usage, target.row)) { + auto it = this->half_outputs_.find(*r); + if (it != this->half_outputs_.end()) halves = std::pair{*r, it->second}; + } + } + if (halves) { + const std::uint8_t row = halves->first; + const bool pack2 = halves->second.first; + // order: packed_layout sorts the packs. + std::vector<std::pair<std::uint8_t, std::optional<std::uint8_t>>> packs; + for (const auto& [r, h] : this->half_outputs_) { + if (h.first) packs.emplace_back(r, h.second); + } + for (std::uint8_t ch = 0; ch < 4; ++ch) { + const std::optional<Value> value = e->values[ch]; + if (!value) continue; + for (bool high : {false, true}) { + const std::uint8_t h = static_cast<std::uint8_t>(2 * ch + (high ? 1 : 0)); + std::optional<std::pair<std::uint8_t, std::uint8_t>> src; + if (pack2) { + src = packed_half(outputs, packs, row, h); + } else if (!high) { + src = std::pair{row, ch}; + } + std::optional<std::size_t> found; + if (src) { + const auto [r, cc] = *src; + for (std::size_t k = 0; k < outputs.size(); ++k) { + const auto& o = outputs[k]; + if (o.row == std::optional<std::uint32_t>(r) && cc >= o.col && + cc < o.col + o.cols) { + found = k; + break; + } + } + } + if (found) { + const std::uint8_t col = static_cast<std::uint8_t>(src->second - outputs[*found].col); + stores.emplace_back(*found, col, *value, std::optional<bool>(high)); + } + } + } + } + for (std::uint8_t ch = 0; ch < 4; ++ch) { + const std::optional<Value> value = e->values[ch]; + if (!value) continue; + if (halves) break; + std::optional<std::pair<std::size_t, std::uint8_t>> found; + switch (target.kind) { + case Target::Kind::Color: { + for (std::size_t k = 0; k < outputs.size(); ++k) { + if (outputs[k].kind == 16 && + outputs[k].row == std::optional<std::uint32_t>(target.n)) { + found = std::pair{k, ch}; + break; + } + } + break; + } + case Target::Kind::Position: + if (target.n == 0) { + if (auto id = by_kind(3)) found = std::pair{*id, ch}; + } else if (target.n >= 1 && target.n <= 2) { + const std::uint8_t n = target.n; + // shortcut: without the misc vector (point size, render target or viewport index) + // pos1 and pos2 carry the clip then cull distances, in semantic order. + for (const auto& o : outputs) { + if (o.kind == 4 || o.kind == 5) fail("render-target or viewport index exports"); + } + std::vector<std::size_t> dists; + for (std::size_t k = 0; k < outputs.size(); ++k) { + if (outputs[k].kind == 6 || outputs[k].kind == 7) dists.push_back(k); + } + std::stable_sort(dists.begin(), dists.end(), [&](std::size_t a, std::size_t bb) { + return std::pair{outputs[a].kind, outputs[a].index} < + std::pair{outputs[bb].kind, outputs[bb].index}; + }); + std::vector<std::pair<std::size_t, std::uint8_t>> flat; + for (std::size_t k : dists) { + for (std::uint8_t cc = 0; cc < outputs[k].cols; ++cc) flat.emplace_back(k, cc); + } + // Channels past the distances the signature declares are ones the clipper does + // not enable (`PA_CL_VS_OUT_CNTL`). + const std::size_t k = static_cast<std::size_t>(n - 1) * 4 + ch; + if (k < flat.size()) found = flat[k]; + } else { + fail("clip, cull or point-size exports"); + } + break; + case Target::Kind::Depth: + if (ch == 0) { + auto id = by_kind(17); + if (!id) id = by_kind(18); + if (!id) id = by_kind(19); + if (id) found = std::pair{*id, std::uint8_t{0}}; + } else if (ch == 1) { + if (auto id = by_kind(20)) found = std::pair{*id, std::uint8_t{0}}; + } else if (ch == 2) { + if (auto id = by_kind(14)) found = std::pair{*id, std::uint8_t{0}}; + } + break; + case Target::Kind::Param: + case Target::Kind::PrimitiveParam: { + const auto row = param_row(target.usage, target.row); + for (std::size_t k = 0; k < outputs.size(); ++k) { + const auto& o = outputs[k]; + if (row && o.row == std::optional<std::uint32_t>(*row) && ch >= o.col && + ch < o.col + o.cols) { + found = std::pair{k, static_cast<std::uint8_t>(ch - o.col)}; + break; + } + } + break; + } + case Target::Kind::Null: + case Target::Kind::Unread: + break; + case Target::Kind::Primitive: + fail("a primitive export"); + } + if (found) stores.emplace_back(found->first, found->second, *value, std::nullopt); + } + auto elements = [&](Lower& l, bool prim) -> std::vector<SigElement>& { + return prim ? l.s.prims : l.s.outputs; + }; + for (const auto& st : stores) { + if (!std::get<3>(st).has_value() && elements(*this, primitive).at(std::get<0>(st)).half) { + fail("a 16-bit output the stage data does not mark"); + } + } + // A mesh lane writes its own vertex or primitive, where it exports. + std::optional<std::pair<std::size_t, std::size_t>> at; + if (mesh) { + V flat = this->mesh_thread(); + std::uint32_t limit = 0; + if (this->s.mesh) limit = primitive ? this->s.mesh->max_primitives : this->s.mesh->max_vertices; + const std::uint32_t threads = this->s.threads ? (*this->s.threads)[0] : UINT32_MAX; + std::optional<V> mesh_guard; + if (limit > 0 && threads > limit) { + V lim = this->s.m.i32(limit); + V in_bounds = this->s.m.cmp(this->cur, pred::IULT, flat, lim); + if (guard) { + mesh_guard = this->s.m.bin(this->cur, Bin::And, *guard, in_bounds); + } else { + mesh_guard = in_bounds; + } + } else { + mesh_guard = guard; + } + at = this->begin_guarded(mesh_guard); + } + std::string_view name; + std::uint32_t opcode = 0; + if (!mesh) { + name = "storeOutput", opcode = 5; + } else if (!primitive) { + name = "storeVertexOutput", opcode = 171; + } else { + name = "storePrimitiveOutput", opcode = 172; + } + for (const auto& [id, col, value, half] : stores) { + V x = this->i32_of(value); + if (half) { + // An f16 half, declared a 32-bit float on the host. + const std::size_t cc = this->cur; + if (*half) { + V k16 = this->s.m.i32(16); + x = this->s.m.bin(cc, Bin::LShr, x, k16); + } + const Ty f32t = this->s.t.f32; + V f = this->s.op(cc, "legacyF16ToF32", Attr::ReadNone, f32t, 131, std::vector<V>{x}); + x = this->as_int(f); + } + SigElement& el = elements(*this, primitive).at(id); + el.usage = static_cast<std::uint8_t>(el.usage | (1u << col)); + const std::uint8_t comp = el.comp; + std::string_view suffix; + if (comp == 9 && half.has_value()) { + suffix = ".f32", x = this->as_float(x); + } else if (comp == 9) { + auto it = this->floats.find(value); + V f = it != this->floats.end() ? it->second : this->as_float(x); + suffix = ".f32", x = f; + } else { + suffix = ".i32"; + } + V a0 = this->s.m.i32(static_cast<std::uint32_t>(id)); + V a1 = this->s.m.i32(0); + V a2 = this->s.m.i8(col); + std::vector<V> args{a0, a1, a2, x}; + if (mesh) args.push_back(this->mesh_thread()); + const Ty void_t = this->s.t.void_; + std::string full = std::string(name) + std::string(suffix); + this->s.op(this->cur, full, Attr::NoUnwind, void_t, opcode, args); + } + this->end_guarded(at, {}); +} + +// Mesh: `exp prim` as the lane's primitive. Each corner takes ten bits: a 9-bit vertex index +// and, above it, its edge flag (bits 9, 19 and 29), which only the console's edge-flag +// rasterisation reads and which is no part of the index. Bit 31 culls it (all indices 0: no +// area). +void Lower::emit_indices(const Export& e, std::optional<V> guard) { + Value v = ok_or(e.values[0], "a primitive export without its indices"); + V x = this->i32_of(v); + V flat = this->mesh_thread(); + if (this->s.mesh) { + const Mesh mesh = *this->s.mesh; + const std::uint32_t threads = this->s.threads ? (*this->s.threads)[0] : UINT32_MAX; + if (threads > mesh.max_primitives) { + V p = this->s.m.i32(mesh.max_primitives); + V in_bounds = this->s.m.cmp(this->cur, pred::IULT, flat, p); + if (guard) { + guard = this->s.m.bin(this->cur, Bin::And, *guard, in_bounds); + } else { + guard = in_bounds; + } + } + } + auto at = this->begin_guarded(guard); + const std::size_t c = this->cur; + V z = this->s.m.i32(0); + V culled = this->s.m.cmp(c, pred::SLT, x, z); + // A primitive that names a vertex past the declared count, or one no lane writes (lane n + // writes vertex n alone), is culled too: the host would read a vertex nothing set, at any + // position. + std::optional<std::uint32_t> written; + if (this->s.mesh) { + const std::uint32_t t = this->s.threads ? (*this->s.threads)[0] : UINT32_MAX; + written = std::min(this->s.mesh->max_vertices, t); + } + std::array<V, 3> indices = {z, z, z}; + for (std::size_t k = 0; k < indices.size(); ++k) { + V shift = this->s.m.i32(10 * static_cast<std::uint32_t>(k)); + V mask = this->s.m.i32(0x1FF); + V idx = this->s.m.bin(c, Bin::LShr, x, shift); + idx = this->s.m.bin(c, Bin::And, idx, mask); + if (written) { + V n = this->s.m.i32(*written); + V past = this->s.m.cmp(c, pred::IUGE, idx, n); + culled = this->s.m.bin(c, Bin::Or, culled, past); + } + indices[k] = idx; + } + std::vector<V> args{flat}; + for (V idx : indices) args.push_back(this->s.m.select(c, culled, z, idx)); + const Ty void_t = this->s.t.void_; + this->s.op(c, "emitIndices", Attr::NoUnwind, void_t, 169, args); + this->end_guarded(at, {}); +} + +// The per-vertex arbitrary row no mesh output entry names but one (the 2020 compiler's zeroed +// entry). +std::optional<std::uint8_t> Lower::unnamed_row() const { + const auto* ms = std::get_if<native::MeshIo>(&this->x.native->io); + if (!ms) return std::nullopt; + auto named = [&](std::uint32_t r) { + for (const auto& o : ms->outputs) { + if ((o.param & 0x80) == 0 && !usage_is_other0(o.usage) && + static_cast<std::uint32_t>(o.row) == r) { + return true; + } + } + return false; + }; + std::set<std::uint32_t> free; + for (const auto& o : this->s.outputs) { + if (o.kind != 0 || !o.row) continue; + if (!named(*o.row)) free.insert(*o.row); + } + if (free.size() == 1) { + const std::uint32_t r = *free.begin(); + if (r <= 0xFF) return static_cast<std::uint8_t>(r); + return std::nullopt; + } + return std::nullopt; +} + +void Lower::exit(std::size_t b) { + const auto& blk = this->x.p->blocks.at(b); + const std::size_t offset = blk.insts.empty() ? blk.offset : blk.insts.back().machine.offset; + const LaneExit& ex = this->x.st->exits.at(b); + Term term = Term::ret(); + switch (ex.kind) { + case LaneExit::Kind::Jump: { + const std::size_t t = ex.target; + if (this->counters.contains(t) && this->rpo.at(t) <= this->rpo.at(b)) { + V ok_ = this->count_iteration(t, pred::IULT); + const std::size_t abort_ = this->abort_block(); + term = Term::cond_br(ok_, this->block.at(t).value(), abort_); + } else { + this->enter_loop(b, t, this->cur); + term = Term::br(this->block.at(t).value()); + } + break; + } + case LaneExit::Kind::Branch: { + const Bool when = ex.when; + std::size_t taken = ex.taken; + std::size_t not_taken = ex.not_taken; + // A negated condition branches the other way round. + V cond{}; + const auto node = this->x.st->bools.node(when); + try { + if (this->x.st->wide.contains(b)) { + cond = this->wave_wide(b, when); + } else if (node && std::get<1>(*node) == Bool::True && std::get<2>(*node) == Bool::False) { + cond = this->atom(std::get<0>(*node), this->cur); + std::swap(taken, not_taken); + } else { + cond = this->boolean(when, this->cur); + } + } catch (const WhyFail& w) { + unsupported(offset, w.why); + } + // A back edge is taken only below the iteration limit. + auto back = [&](const Lower& l, std::size_t to) { + return l.counters.contains(to) && l.rpo.at(to) <= l.rpo.at(b); + }; + // (No `xor` of a compare: a loop exit testing one hung the AMD driver.) + if (back(*this, taken)) { + V ok_ = this->count_iteration(taken, pred::IULT); + cond = this->s.m.bin(this->cur, Bin::And, cond, ok_); + } else if (back(*this, not_taken)) { + V stop = this->count_iteration(not_taken, pred::IUGE); + cond = this->s.m.bin(this->cur, Bin::Or, cond, stop); + } + // Critical edges get a block of their own, so loops have dedicated exits and preheaders + // as DXC emits them. + const std::size_t t = this->edge(b, taken); + const std::size_t f = this->edge(b, not_taken); + for (auto [to, via] : {std::pair{taken, t}, std::pair{not_taken, f}}) { + if (!back(*this, to)) { + // From an edge block, or from here. + const std::size_t from = + std::optional<std::size_t>(via) == this->block.at(to) ? this->cur : via; + this->enter_loop(b, to, from); + } + } + term = Term::cond_br(cond, t, f); + break; + } + case LaneExit::Kind::End: + if (this->s.pixel && !this->exported.at(b) && !this->has_done_export(b)) { + // A lane leaving without its final export was killed. + V t = this->s.m.bool_(true); + this->s.op(this->cur, "discard", Attr::NoUnwind, this->s.t.void_, 82, std::vector<V>{t}); + } + term = Term::ret(); + break; + case LaneExit::Kind::Indirect: + unsupported(offset, "an indirect jump"); + } + this->s.m.terminate(this->cur, term); +} + +// A forward edge into loop header `to` (from DXIL block `via`) starts its count at 0. +void Lower::enter_loop(std::size_t /*from*/, std::size_t to, std::size_t via) { + auto it = this->counters.find(to); + if (it != this->counters.end()) { + V z = this->s.m.i32(0); + it->second.second.emplace_back(z, via); + } +} + +// A back edge to header `to` (a back edge keeps its block, no critical-edge block): the count goes +// up; the result compares it with LOOP_LIMIT by `p` (below: go on; at or above: stop). +V Lower::count_iteration(std::size_t to, std::uint8_t p) { + const std::size_t c = this->cur; + const V phi = this->counters.at(to).first; + V one = this->s.m.i32(1); + V next = this->s.m.bin(c, Bin::Add, phi, one); + this->s.m.tag(phi, Tag::Counter); + this->s.m.tag(next, Tag::Counter); + // Per stage unless the switch names one: a loop that never meets its exit (a count read from + // a buffer the host has not got yet, say) runs to the limit in every lane. A million + // iterations a pixel hung the GPU for seconds a draw until Windows reset it + // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop past 256 or a compute loop + // past 4,096 is cut short. (They were 1,024, 4,096 and 65,536: the opening cutscene then lost + // the card 14-25 frames in, in a minimap or shadow mesh draw; with every loop cut at 64 it ran + // 90 frames. Raise them again once shaders stop reading data that is not there yet.) + const std::uint32_t named = loop_limit(); + std::uint32_t limit = named; + if (named == LOOP_LIMIT) { + if (this->s.pixel) { + limit = 1u << 7; + } else if (this->s.mesh.has_value() || !this->s.threads.has_value()) { + limit = 1u << 8; + } else { + limit = 1u << 12; + } + } + V lim = this->s.m.i32(limit); + this->counters.at(to).second.emplace_back(next, c); + V over = this->s.m.cmp(c, p, next, lim); + this->s.m.tag(over, Tag::Counter); + return over; +} + +// The block a lane stopped by LOOP_LIMIT leaves through. +std::size_t Lower::abort_block() { + if (this->abort) return *this->abort; + const std::size_t a = this->s.m.new_block(); + if (this->s.pixel) { + V t = this->s.m.bool_(true); + this->s.op(a, "discard", Attr::NoUnwind, this->s.t.void_, 82, std::vector<V>{t}); + } + this->s.m.terminate(a, Term::ret()); + this->abort = a; + return a; +} + +// The DXIL block a branch from IR block `from` to `to` goes to. +std::size_t Lower::edge(std::size_t from, std::size_t to) { + const std::size_t target = this->block.at(to).value(); + std::size_t preds = 0; + for (std::size_t q : this->x.p->blocks.at(to).preds) { + if (this->block.at(q).has_value()) ++preds; + } + // Back edges stay as they are: the exiting block is the latch. + if (preds < 2 || this->rpo.at(to) <= this->rpo.at(from)) return target; + const std::size_t e = this->s.m.new_block(); + this->s.m.terminate(e, Term::br(target)); + this->edges.insert_or_assign(std::pair{from, to}, e); + return e; +} + +void Lower::fill_phis() { + const Program& p = *this->x.p; + // Lane-mask joins first (what an edge brings may ask for more joins, of masks and of + // numbers): each edge's mask as the structure tracked it, a constant or a scalar-built one + // included. + const Structured& st = *this->x.st; + while (!this->pending_masks.empty()) { + const auto [v, b, i] = this->pending_masks.back(); + this->pending_masks.pop_back(); + const auto& phi = p.blocks.at(b).phis.at(i); + const std::size_t offset = p.blocks.at(b).offset; + auto found = st.phi_masks.find(phi.value); + if (found == st.phi_masks.end()) unsupported(offset, "a lane-mask join of an untracked mask"); + const auto& args = found->second; + std::vector<std::pair<V, std::size_t>> incoming; + const auto& preds = p.blocks.at(b).preds; + for (std::size_t n = 0; n < preds.size(); ++n) { + const std::size_t q = preds[n]; + if (!this->tail.at(q)) continue; + std::size_t qb = *this->tail.at(q); + if (auto e = this->edges.find(std::pair{q, b}); e != this->edges.end()) qb = e->second; + V x{}; + try { + x = this->boolean(args.at(n), qb); + } catch (const WhyFail& w) { + unsupported(offset, w.why); + } + incoming.emplace_back(x, qb); + } + this->s.m.set_phi(v, std::move(incoming)); + } + // A join that only another join reads is read wherever that one is. Left unmarked, a value + // without a DXIL form coming into it became zero without a word (the looked-up tint of the + // material resolve programs, whose size computation had no value, was zero in every lane that + // way). + // shortcut: only with `X2W_SHADERCFG_STRICT_JOINS` set (the offline pack listing sets it to count + // them): 40 programs that translate today stop by name with it (vehicle paint pixel shaders + // at "the first half of an interpolation", foliage mesh shaders); until those are lowered + // they keep drawing with that zero. + static const bool strict = std::getenv("X2W_SHADERCFG_STRICT_JOINS") != nullptr; + std::vector<Value> work; + if (strict) { + // order: the work list only grows read_phis; its final contents do not depend on order. + work.assign(this->read_phis.begin(), this->read_phis.end()); + } + while (!work.empty()) { + const Value v = work.back(); + work.pop_back(); + auto at = this->phi_at.find(v); + if (at == this->phi_at.end()) continue; + const auto [b, i] = at->second; + for (const Value a : p.blocks.at(b).phis.at(i).args) { + if (this->phi_at.contains(a) && this->read_phis.insert(a).second) work.push_back(a); + } + } + auto data_phis = std::move(this->data_phis); + this->data_phis.clear(); + for (const auto& [v, b, i] : data_phis) { + const auto& phi = p.blocks.at(b).phis.at(i); + const bool bit = phi.reg == Reg::Scc; + // A join of numbers with dead registers (`dead`): the paths that bring those never read + // the result, so they bring zero. Not for a join that is itself a lane mask (a ballot + // gives that one as data). + bool numbers = !bit && !st.masks.contains(phi.value) && !st.highs.contains(phi.value); + if (numbers) { + bool any = false; + for (const Value a : phi.args) { + auto it = this->vals.find(a); + if (it != this->vals.end() && it->second.is_i32()) { + any = true; + break; + } + } + numbers = any; + } + std::vector<std::pair<V, std::size_t>> incoming; + const auto& preds = p.blocks.at(b).preds; + for (std::size_t n = 0; n < preds.size(); ++n) { + const std::size_t q = preds[n]; + if (!this->tail.at(q)) continue; + std::size_t qb = *this->tail.at(q); + if (auto e = this->edges.find(std::pair{q, b}); e != this->edges.end()) qb = e->second; + const Value arg = phi.args.at(n); + if (this->read_phis.contains(phi.value) && !this->vals.contains(arg)) { + // A failed lazy barycentric lookup leaves the argument unresolved. + try { + (void)this->lazy_barycentric(arg); + } catch (const WhyFail&) { + } + // A root parameter nothing read before the join (user data is loaded on first + // use, in the entry block). + if (!this->vals.contains(arg)) { + if (auto pr = this->params.find(arg); pr != this->params.end()) { + const auto [param, dword] = pr->second; + Val val = this->user(param, dword); + this->vals.insert_or_assign(arg, val); + } + } + } + std::optional<Val> got; + if (auto it = this->vals.find(arg); it != this->vals.end()) got = it->second; + const bool none_or_missing = !got || got->is_missing(); + V x{}; + if ((got && got->is_i32() && !bit) || (got && got->is_bit() && bit)) { + x = got->v; + } else if (none_or_missing && !bit && numbers && [&] { + std::vector<Value> seen; + return this->dead(arg, seen); + }()) { + x = this->s.m.i32(0); + } else if (none_or_missing && !bit && this->read_phis.contains(phi.value) && + this->mask_data == MaskData::Console && + (st.masks.contains(arg) || st.highs.contains(arg))) { + // A lane mask joined with numbers (a traversal that keeps its lanes' masks on a + // stack with its node numbers): the mask comes as the number it is, the ballot of + // its lanes where it is written. + try { + x = this->mask_dword(arg); + } catch (const WhyFail& w) { + throw StopRetry{phi.value, w.why}; + } + } else if (none_or_missing && bit && this->read_phis.contains(phi.value) && + this->mask_data == MaskData::Console && st.scc_some.contains(arg)) { + // SCC of a mask operation ("some lane is left") joined with a scalar test: the + // compiler branches around code that sets SCC and tests SCC after it, the skip + // bringing "no lane" along. As data it is "some lane of the wave has the bit" - + // right only if the wave took that skip together, as the console does: a lane + // that skipped alone would bring "some lane" where the console has the skipped + // code's SCC. So the branch must be one the wave takes together; else its region + // is named for `emit`'s retry to widen it. + const LaneExit& qe = st.exits.at(q); + const bool per_lane = !st.wide.contains(q) && qe.kind == LaneExit::Kind::Branch && + !all_uniform(st, qe.when); + if (per_lane) { + for (const std::size_t other : p.blocks.at(b).preds) { + if (other != q) need(other); + } + throw StopRetry{phi.value, LANE_MASK}; + } + try { + x = this->scc_some(arg); + } catch (const WhyFail& w) { + throw StopRetry{phi.value, w.why}; + } + } else if (got && got->is_bit() && !bit && this->read_phis.contains(phi.value)) { + throw StopRetry{phi.value, "an SCC joined with SGPR values"}; + } else if (got && got->is_missing() && this->read_phis.contains(phi.value)) { + throw StopRetry{phi.value, got->why}; + } else if (this->read_phis.contains(phi.value)) { + throw StopRetry{phi.value, "a join of mismatched values"}; + } else if (bit) { + x = this->s.m.bool_(false); + } else { + x = this->s.m.i32(0); + } + incoming.emplace_back(x, qb); + } + this->s.m.set_phi(v, std::move(incoming)); + } + // order: set_phi only fills phis made before; no value is made here. + auto counters = std::move(this->counters); + this->counters.clear(); + for (auto& [hdr, entry] : counters) { + (void)hdr; + this->s.m.set_phi(entry.first, std::move(entry.second)); + } +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_core.cpp b/src/x2w_shader/emit/lower_core.cpp new file mode 100644 index 0000000000..6fcc951dc5 --- /dev/null +++ b/src/x2w_shader/emit/lower_core.cpp @@ -0,0 +1,1026 @@ +// The emitter's set-up, its run over the program, and the whole-wave sections. +#include <algorithm> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <numeric> +#include <stdexcept> +#include <string> + +#include "x2w_shader/emit/lower_impl.h" + +namespace x2w::vs::lower { + +namespace { + +// std::env::var_os(name).is_some() +bool env_set(const char* name) { return std::getenv(name) != nullptr; } + +// Multiply thread counts modulo 2^32. +std::uint32_t product3(const std::array<std::uint32_t, 3>& t) { return t[0] * t[1] * t[2]; } + +// st.masks.get(&mask): the lane boolean of a mask by its low dword. +std::optional<Bool> mask_of(const Structured& st, Value mask) { + auto it = st.masks.find(mask); + if (it == st.masks.end()) return std::nullopt; + return it->second; +} + +} // namespace + +Lower::Lower(const Parts& parts, const HashMap<Value, Why>& bad_) + : s(parts.native->stage == HwStage::Ps), x(parts), bad(bad_) { + const Program& p = *x.p; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& block_ = p.blocks[b]; + for (std::size_t i = 0; i < block_.phis.size(); ++i) { + phi_at.insert_or_assign(block_.phis[i].value, std::pair{b, i}); + } + } + s.inputs = x.inputs; + s.outputs = x.outputs; + auto any_inst = [&](auto&& f) { + for (const auto& blk : p.blocks) { + for (const auto& i : blk.insts) { + if (f(i)) return true; + } + } + return false; + }; + bool writes_uavs_ = any_inst([](const Inst& i) { + auto n = i.name(); + return (std::holds_alternative<gfx10::Image>(i.fields) || + std::holds_alternative<gfx10::Buffer>(i.fields)) && + (n.find("store") != std::string_view::npos || + n.find("atomic") != std::string_view::npos); + }); + bool console_lanes_ = false; + // LDS accesses get a group barrier each (a console wave split in two host waves) + bool split_lds_ = false; + // with `split_lds`, LDS accesses in lane branches: the blocks every lane runs, and where the + // host waves meet around those branches (`lds_meetings`) + std::optional<std::pair<std::vector<bool>, std::vector<std::pair<bool, bool>>>> lds_meet_; + // a console wave64 program in two host waves of 32 (`exchange`) + std::optional<std::tuple<std::uint32_t, bool, std::vector<bool>>> exchange_; + // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter + std::optional<std::uint32_t> halves_; + if (const auto* cs = std::get_if<native::ComputeIo>(&x.native->io)) { + s.threads = cs->threads; + s.lds_dwords = cs->lds_bytes() / 4; + // Code reading other lanes needs the console's wave size and lane order; so do lane + // masks read as numbers, and LDS shared within one wave, where the console compiler + // leaves out barriers. + console_lanes_ = any_inst([&](const Inst& i) { + auto n = i.name(); + const auto* v = std::get_if<gfx10::Valu>(&i.fields); + return n.starts_with("ds_swizzle") || + n.find("permute") != std::string_view::npos || + n.starts_with("v_permlane") || n.starts_with("v_mbcnt") || + n == "v_readlane_b32" || n == "v_writelane_b32" || + (v && v->dpp.has_value()) || reads_mask_as_data(*x.st, i); + }) || + lane_constant_masks(*x.st) + // (a branch the wave takes together asks the wave) + || !x.st->wide.empty(); + std::uint32_t wave_ = x.native->wave64 ? 64 : 32; + std::uint32_t group = product3(cs->threads); + bool one_wave = group <= wave_; + // A host whose waves are at most 32 lanes (NVIDIA) refuses `WaveSize(64)`. A console + // wave64 program whose cross-lane code stays inside 32-lane halves - DPP rows, + // `ds_swizzle`, `v_permlane16` / `v_permlanex16`, which the ISA confines there - runs + // exactly in waves of 32: the thread relabelling makes each host wave one half of a + // console wave (lanes 32k..32k+31). Not when it crosses halves (`v_mbcnt`, `v_readlane`, + // `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant masks), nor when LDS + // may be shared within the console wave without barriers (a group over 32 threads with + // LDS): those still need 64-lane waves. + if (wave_ == 64 && host_max_wave() == 32 && + (console_lanes_ || (one_wave && s.lds_dwords > 0))) { + bool crosses = any_inst([&](const Inst& i) { + auto n = i.name(); + return n.starts_with("v_mbcnt") || n == "v_readlane_b32" || + n == "v_writelane_b32" || n.starts_with("ds_permute") || + n.starts_with("ds_bpermute") || reads_mask_as_data(*x.st, i); + }) || + lane_constant_masks(*x.st) || !x.st->wide.empty(); + if (!crosses && (s.lds_dwords == 0 || group <= 32)) { + wave_ = 32; + } else { + // (Groups of several console waves too: each console wave is two host waves, + // which exchange through their own pair of dwords.) + // LDS the console shares within its one wave without barriers: split into two + // waves of 32, a group barrier before every LDS access keeps their order - where + // every thread of the group gets there (no lane branch around it, no guard), + // else a barrier would hang the group + auto lds = [](const Inst& i) { + auto n = i.name(); + return std::holds_alternative<gfx10::Ds>(i.fields) && + !(n.starts_with("ds_swizzle") || n.find("permute") != std::string_view::npos); + }; + if (auto all_ = all_lane_blocks(*x.st)) { + std::vector<bool> all = std::move(*all_); + auto all_at = [&](std::size_t b) { return b < all.size() && all[b]; }; + bool ok = true; + for (std::size_t b = 0; b < p.blocks.size() && ok; ++b) { + for (const auto& inst : p.blocks[b].insts) { + if (!(!lds(inst) || all_at(b))) { + ok = false; + break; + } + } + } + bool lds_ok = !(s.lds_dwords > 0 && group > 32) || ok; + if (!lds_ok) { + if (auto meet = lds_meetings(p, *x.st, all)) { + lds_meet_ = std::pair{all, std::move(*meet)}; + lds_ok = true; + } + } + if (!lds_ok) { + // (the blocks whose LDS accesses not every lane runs: with the branches + // around them taken wave-wide they get their barriers) + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& blk = p.blocks[b]; + if (!all_at(b) && std::any_of(blk.insts.begin(), blk.insts.end(), lds)) { + need(b); + } + } + } + if (lds_ok) { + wave_ = 32; + split_lds_ = s.lds_dwords > 0 && group > 32; + if (crosses) { + // lanes 32..63 are the other host wave: masks, lane reads and lane + // numbers go through two exchange dwords past the program's LDS + exchange_ = std::tuple{s.lds_dwords, group <= 32, std::move(all)}; + s.lds_dwords += 2 * div_ceil<std::uint32_t>(group, 64); + } + } + } + } + // `X2W_SHADERCFG_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason) + if (wave_ == 64 && env_set("X2W_SHADERCFG_WAVE_WHY")) { + std::vector<std::string_view> why; + for (const auto& blk : p.blocks) { + for (const auto& i : blk.insts) { + auto n = i.name(); + std::string_view r; + if (n.starts_with("v_mbcnt")) { + r = "v_mbcnt"; + } else if (n == "v_readlane_b32") { + r = "v_readlane"; + } else if (n == "v_writelane_b32") { + r = "v_writelane"; + } else if (n.starts_with("ds_permute") || n.starts_with("ds_bpermute")) { + r = "ds_(b)permute"; + } else if (reads_mask_as_data(*x.st, i)) { + r = "mask as data"; + } else { + continue; + } + if (std::find(why.begin(), why.end(), r) == why.end()) why.push_back(r); + } + } + if (lane_constant_masks(*x.st)) why.push_back("lane-constant mask"); + if (s.lds_dwords > 0 && group > 32) { + why.push_back("LDS in a group over 32"); + auto all = all_lane_blocks(*x.st); + if (!all) { + why.push_back("an indirect exit"); + } else if (!lds_meetings(p, *x.st, *all)) { + why.push_back("an LDS read and write in one lane-branch region"); + } + } + std::sort(why.begin(), why.end()); + std::string joined; + for (std::size_t k = 0; k < why.size(); ++k) { + if (k) joined += ", "; + joined += why[k]; + } + std::fprintf(stderr, "WAVE64-WHY group=%u lds=%s [%s]\n", group, + s.lds_dwords > 0 ? "true" : "false", joined.c_str()); + } + } + if (wave_ == 32 && x.native->wave64) { + // console threads go to host waves in the order the waves take them (`wave_base`) + halves_ = s.lds_dwords; + s.lds_dwords += 1; + } + if (console_lanes_ || (one_wave && s.lds_dwords > 0)) { + s.wave_size = wave_; + } + } + // The title's barriers a thread of the group may never reach, which leaves the others + // waiting on the host: those in blocks some lanes do not run, and all of them in a program + // with a loop closed by a plain jump (a lane still in it at the iteration limit leaves the + // program there, `abort_block`). + HashSet<std::size_t> fence_only_; + if (any_inst([](const Inst& i) { return i.name() == "s_barrier"; })) { + auto order = ir::reverse_postorder(p.blocks); + std::vector<std::size_t> place(p.blocks.size(), SIZE_MAX); + for (std::size_t n = 0; n < order.size(); ++n) place[order[n]] = n; + auto at = [&](std::size_t b) { return b < place.size() ? place[b] : SIZE_MAX; }; + auto back = [&](std::size_t from, std::size_t to) { + return at(from) != SIZE_MAX && at(to) <= at(from); + }; + bool cut_short = false; + for (std::size_t b = 0; b < x.st->exits.size(); ++b) { + const auto& e = x.st->exits[b]; + if (e.kind == LaneExit::Kind::Jump && back(b, e.target)) { + cut_short = true; + break; + } + } + auto all = all_lane_blocks(*x.st); + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& insts = p.blocks[b].insts; + bool barrier = std::any_of(insts.begin(), insts.end(), + [](const Inst& i) { return i.name() == "s_barrier"; }); + if (!barrier) continue; + if (cut_short || !all || !(b < all->size() && (*all)[b])) fence_only_.insert(b); + } + } + HashSet<std::size_t> no_barrier_; + if (const auto* ms = std::get_if<native::MeshIo>(&x.native->io)) { + s.prims = x.prims; + s.threads = std::array<std::uint32_t, 3>{ms->threads, 1, 1}; + s.lds_dwords = div_ceil<std::uint32_t>(ms->lds_bytes, 4); + s.mesh = Mesh{ms->max_vertices, ms->max_primitives, ms->topology}; + // Barriers order the lanes' LDS accesses; the console's allocation request needs them + // too, but the host does not. One lane sends that request, and what it dominates (the + // path for counts out of range) runs in that lane alone, so its barrier would hang the + // host. + auto order = ir::reverse_postorder(p.blocks); + std::vector<std::size_t> index(p.blocks.size(), SIZE_MAX); + for (std::size_t n = 0; n < order.size(); ++n) index[order[n]] = n; + auto idom = ir::idoms(p.blocks, order, index); + std::vector<std::size_t> alloc; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + for (const auto& i : p.blocks[b].insts) { + const auto* sopp = std::get_if<gfx10::Sopp>(&i.fields); + if (i.name() == "s_sendmsg" && sopp && (sopp->imm & 0xF) == GS_ALLOC_REQ) { + alloc.push_back(b); + break; + } + } + } + for (std::size_t b : order) { + std::size_t d = b; + bool dominated; + for (;;) { + if (std::find(alloc.begin(), alloc.end(), d) != alloc.end()) { + dominated = true; + break; + } + if (idom.at(d) == d || idom.at(d) == SIZE_MAX) { + dominated = false; + break; + } + d = idom.at(d); + } + if (ms->lds_bytes == 0 || dominated) no_barrier_.insert(b); + } + } + // The struct literal, field by field (none of these make builder calls). + block.assign(p.blocks.size(), std::nullopt); + cur = 0; + if (x.native->stage == HwStage::Ps) ordered = ordered_section(p); + for (const auto& [v, pp, d] : x.res->params) params.insert_or_assign(v, std::pair{pp, d}); + for (const auto& d : x.res->descriptors) { + descriptors.insert_or_assign(std::pair{d.site, d.role == Role::Sampler}, &d.source); + } + for (const auto& [site, a] : x.res->scalar) scalar.insert_or_assign(site, a); + for (const auto& e : x.io->exports) exports.insert_or_assign(e.site, &e); + for (const auto& [site, i] : x.io->interps) interps.insert_or_assign(site, &i); + // A first half whose result is also read as data (an f16 second half keeps the other half of + // its dst): evaluated as the pair it starts. Approximate for those other + // bits (P0 + i P10 on the console); a first half only the second half reads is gone before + // lowering. Only in the second translation of a program the first one refused for it + // (with_first_half_pairs). + if (first_half_pairs_on()) { + const char* fh = std::getenv("X2W_SHADERCFG_FIRST_HALF"); + if (fh == nullptr || std::strcmp(fh, "0") != 0) { + for (const auto& [site, i] : x.io->interps) { + if (i.kind == io::Interp::Kind::Interpolated) { + for (const Site& f : i.first) interps.try_emplace(f, &i); + } + } + } + } + exported.assign(p.blocks.size(), false); + rpo.assign(p.blocks.size(), SIZE_MAX); + tail.assign(p.blocks.size(), std::nullopt); + writes_uavs = writes_uavs_; + console_lanes = console_lanes_; + split_lds = split_lds_; + lds_meet = std::move(lds_meet_); + local = exchange_.has_value() && local_waves_on(); + local_ok = false; + local_any = local_any_on(); + if (exchange_ && !std::get<1>(*exchange_) && !local_waves_on()) { + uniform = lane_uniform(p, *x.st, std::get<2>(*exchange_)); + } + if (exchange_ && !std::get<1>(*exchange_) && !local_waves_on() && own_bits_on()) { + own_bits = own_bits::find(p, *x.st, env_set("X2W_SHADERCFG_WAVE_WHY")); + } + exchange = std::move(exchange_); + halves = halves_; + no_barrier = std::move(no_barrier_); + fence_only = std::move(fence_only_); + half_outputs_ = half_outputs(x.native->io, x.outputs); + switch (x.native->stage) { + case HwStage::Cs: + mask_data = MaskData::Console; + break; + case HwStage::Ps: + case HwStage::Vs: + mask_data = MaskData::Host; + break; + default: + mask_data = MaskData::None; + break; + } + mask_ok = false; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& blk = p.blocks[b]; + for (const auto& i : blk.insts) { + for (const auto& w : i.writes) def_block.insert_or_assign(w.second, b); + } + for (const auto& phi : blk.phis) def_block.insert_or_assign(phi.value, b); + } + cur_ir = 0; +} + +// The dword of the program's code at byte `byte` (a constant table the compiler appends +// to the code), as an internal constant array. +// shortcut: an index outside the table reads its last dword (the console would read whatever +// memory follows the code). +V Lower::code_dword(V byte) { + V g; + std::uint32_t base, len; + if (this->code_table) { + std::tie(g, base, len) = *this->code_table; + } else { + std::optional<std::uint32_t> first_; + auto take = [&](const Address& a) { + if (a.param != resource::CODE) return; + std::uint32_t o = a.offset & ~3u; + if (!first_ || o < *first_) first_ = o; + }; + for (const auto& sc : this->x.res->scalar) take(sc.second); + for (const auto& d : this->x.res->descriptors) { + for (const Source* l : d.source.leaves()) { + if (l->kind == Source::Kind::Built) take(l->address); + } + } + std::uint32_t first = ok_or(first_, "a code table"); + const auto& code = this->x.native->code; + if (first > code.size()) fail("a code table past the code"); + std::vector<std::uint32_t> words; + for (std::size_t at = first; at < code.size(); at += 4) { + std::uint8_t w[4] = {0, 0, 0, 0}; + for (std::size_t k = 0; k < 4 && at + k < code.size(); ++k) w[k] = code[at + k]; + words.push_back(std::uint32_t(w[0]) | std::uint32_t(w[1]) << 8 | + std::uint32_t(w[2]) << 16 | std::uint32_t(w[3]) << 24); + } + if (words.empty()) fail("a code table past the code"); + std::vector<V> elems; + for (std::uint32_t w : words) elems.push_back(this->s.m.i32(w)); + Ty arr = this->s.m.array(static_cast<std::uint32_t>(words.size()), this->s.t.i32); + V init = this->s.m.aggregate(arr, elems); + g = this->s.m.constant_global("code", init); + base = first; + len = static_cast<std::uint32_t>(words.size()); + this->code_table = std::tuple{g, base, len}; + } + std::size_t c = this->cur; + V k = this->s.m.i32(base); + V rel = this->s.m.bin(c, Bin::Sub, byte, k); + V two = this->s.m.i32(2); + V index = this->s.m.bin(c, Bin::LShr, rel, two); + V last = this->s.m.i32(len - 1); + V over = this->s.m.cmp(c, pred::IUGT, index, last); + index = this->s.m.select(c, over, last, index); + V at = this->s.m.element(c, g, index); + return this->s.m.load(c, at); +} + +// A global memory load (`global_load_*`): from the program's constant table, or from a +// root SRV at the address the title sets. +void Lower::flat(const Inst& inst, std::size_t b, std::size_t i) { + const auto& fl = std::get<gfx10::Flat>(inst.fields); + const auto& dst = fl.dst; + this->root_copy = std::nullopt; + auto name = inst.name(); + { + auto it = this->scalar.find(Site{b, i}); + if (it != this->scalar.end() && it->second.param == resource::MEMORY) { + return this->memory_flat(inst, b, i); + } + } + if (!name.starts_with("global_load_")) fail("a global memory write"); + auto rest = name.substr(std::string_view("global_load_").size()); + std::uint32_t n; + std::optional<std::pair<std::uint32_t, bool>> sub; + if (rest == "dword") { + n = 1; + } else if (rest == "dwordx2") { + n = 2; + } else if (rest == "dwordx3") { + n = 3; + } else if (rest == "dwordx4") { + n = 4; + } else if (rest == "ubyte") { + n = 1, sub = std::pair{8u, false}; + } else if (rest == "sbyte") { + n = 1, sub = std::pair{8u, true}; + } else if (rest == "ushort") { + n = 1, sub = std::pair{16u, false}; + } else if (rest == "sshort") { + n = 1, sub = std::pair{16u, true}; + } else { + fail(name.data()); + } + Address a; + { + auto it = this->scalar.find(Site{b, i}); + if (it == this->scalar.end()) fail("an untracked global address"); + a = it->second; + } + std::optional<V> guard = this->guard(b, i); + if (!dst || dst->kind != Operand::Kind::Vector) fail("a global load result"); + std::uint8_t reg = dst->reg; + std::size_t c = this->cur; + V off = this->s.m.i32(a.offset); + if (a.dynamic) { + V d = this->i32_of(*a.dynamic); + off = this->s.m.bin(c, Bin::Add, off, d); + } + std::optional<V> h; + if (a.param == resource::CODE) { + h = std::nullopt; + } else { + Source src = Source::Built(a, 0, {0, 0}); + if (auto bias = this->root_bias(a.param)) { + off = this->s.m.bin(c, Bin::Add, off, *bias); + } + if (auto mem = this->root_memory(src, off, guard, false)) { + off = mem->second; + h = mem->first; + } else { + h = this->handle(Site{b, i}, src, false, {11, 0}); + } + } + c = this->cur; + auto dword = [&](Lower& l, V byte) -> V { + if (!h) return l.code_dword(byte); + std::size_t c = l.cur; + V u = l.s.m.undef(l.s.t.i32); + V mask = l.s.m.i8(1); + V al = l.s.m.i32(4); + V r = l.s.op(c, "rawBufferLoad.f32", Attr::ReadOnly, l.s.t.res_ret, 139, + std::vector<V>{*h, byte, u, mask, al}); + V xx = l.s.m.extract(c, r, 0); + return l.as_int(xx); + }; + for (std::uint32_t k = 0; k < n; ++k) { + V xv; + if (!sub) { + V four = this->s.m.i32(4 * k); + V at = this->s.m.bin(c, Bin::Add, off, four); + xv = dword(*this, at); + } else { + auto [width, is_signed] = *sub; + // shortcut: the field is taken not to cross a dword. + V not3 = this->s.m.i32(~3u); + V three = this->s.m.i32(3); + V at = this->s.m.bin(c, Bin::And, off, not3); + V w = dword(*this, at); + V byte = this->s.m.bin(c, Bin::And, off, three); + V sh = this->s.m.bin(c, Bin::Shl, byte, three); + V xx = this->s.m.bin(c, Bin::LShr, w, sh); + V left = this->s.m.i32(32 - width); + xx = this->s.m.bin(c, Bin::Shl, xx, left); + xv = this->s.m.bin(c, is_signed ? Bin::AShr : Bin::LShr, xx, left); + } + this->write(inst, Reg::V(static_cast<std::uint8_t>(reg + static_cast<std::uint8_t>(k))), xv, guard); + } +} + +// Finds the whole-wave sections and the values they leave. +void Lower::find_sections() { + const Program& p = *this->x.p; + HashMap<Value, std::tuple<std::size_t, std::size_t, std::size_t>> inside; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + auto found = wave::sections(p, b); + // order: SSA values are written once, so `inside` gets the same entries in any order. + for (const auto& [start, sec] : found) { + for (std::size_t i = start + 1; i < sec.end; ++i) { + for (const auto& w : p.blocks[b].insts[i].writes) { + inside.insert_or_assign(w.second, std::tuple{b, start, sec.end}); + } + } + } + if (!found.empty()) this->sections.insert_or_assign(b, std::move(found)); + } + if (inside.empty()) return; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& blk = p.blocks[b]; + for (const auto& phi : blk.phis) { + for (const Value& a : phi.args) { + if (inside.contains(a)) this->section_out.insert(a); + } + } + for (std::size_t i = 0; i < blk.insts.size(); ++i) { + for (const auto& rd : blk.insts[i].reads) { + auto it = inside.find(rd.second); + if (it == inside.end()) continue; + auto [sb, start, end] = it->second; + if (!(sb == b && i > start && i < end)) this->section_out.insert(rd.second); + } + } + } +} + +// An instruction inside a whole-wave section: the values that leave the section are made +// from what the simulation found them to be. +void Lower::section_inst(std::size_t b, std::size_t i, std::size_t start) { + static constexpr Why UNKNOWN = "a whole-wave section step the simulation does not follow"; + const Inst& inst = this->x.p->blocks[b].insts[i]; + for (const auto& wr : inst.writes) { + Value w = wr.second; + Val val; + if (this->section_out.contains(w)) { + const auto& shapes = this->sections.at(b).at(start).shapes; + std::optional<wave::Shape> shape; + if (auto it = shapes.find(w); it != shapes.end()) shape = it->second; + bool own = this->own_bits.totals.contains(w); + if (!shape) { + val = Val::Missing(UNKNOWN); + } else { + try { + val = Val::I32(this->shape(*shape, own)); + } catch (const WhyFail& e) { + val = Val::Missing(e.why); + } + } + } else { + val = Val::Missing(UNKNOWN); + } + this->vals.insert_or_assign(w, val); + } +} + +// A value a whole-wave section leaves, as DXIL wave operations over the host's active +// lanes: the console's result with console lanes; on another wave size, what the HLSL wave +// operation the console compiler expanded gives on that wave. +// +// `own`: a wave OR that only steers a loop over each lane's own bits (own_bits); where two host +// waves cannot exchange their halves' ORs it is this host wave's. +// wave::Shape is vs-emit's tagged struct (wave.h: a/b/c, k, flag per kind). +V Lower::shape(wave::Shape shape, bool own) { + using wave::Op; + using SK = wave::Shape::Kind; + Op op; + Value src, mask; + std::uint32_t ident; + std::optional<bool> prefix; + switch (shape.kind) { + case SK::K: + return this->s.m.i32(shape.k); + case SK::Value: + return this->i32_of(shape.a); + case SK::Active: + op = shape.op, src = shape.a, mask = shape.b, ident = shape.k; + break; + case SK::ActiveF64: + return this->active_f64_sum(shape.a, shape.b, shape.c, shape.flag); + case SK::Masked: { + std::size_t c = this->cur; + Bool m = ok_or(mask_of(*this->x.st, shape.b), "a wave reduction's untracked mask"); + V on = this->boolean(m, c); + V xv = this->i32_of(shape.a); + V id = this->s.m.i32(shape.k); + return this->s.m.select(c, on, xv, id); + } + case SK::Prefix: + default: + op = shape.op, src = shape.a, mask = shape.b, ident = shape.k; + prefix = shape.flag; + break; + } + // Mesh: no host wave size can be declared, so a reduction is over this host wave only. A + // minimum or maximum is taken that way: the compiler's "next distinct value" loop (the wave's + // minimum, then the lanes that hold it) serves every lane however the lanes are divided into + // waves. A sum, a bit reduction or a prefix would be of part of a console wave: still refused. + if (this->mask_data == MaskData::None && + (prefix.has_value() || !(op == Op::MinU || op == Op::MaxU || op == Op::MinI || + op == Op::MaxI || op == Op::MinF || op == Op::MaxF))) { + fail("a wave reduction in a mesh shader"); + } + std::size_t c = this->cur; + Bool m = ok_or(mask_of(*this->x.st, mask), "a wave reduction's untracked mask"); + V on = this->boolean(m, c); + V xv = this->i32_of(src); + V id = this->s.m.i32(ident); + xv = this->s.m.select(c, on, xv, id); + this->s.flags |= flags::WAVE_OPS; + if (op == Op::AddH) { + if (prefix) fail("a wave prefix of an operation other than a sum"); + return this->half_sum(xv); + } + bool is_float = op == Op::AddF || op == Op::MinF || op == Op::MaxF; + Ty i32t = this->s.t.i32; + Ty f32t = this->s.t.f32; + V arg = is_float ? this->as_float(xv) : xv; + Ty ty = is_float ? f32t : i32t; + std::string sfx = is_float ? "f32" : "i32"; + V r; + if (prefix) { + if (op == Op::AddU || op == Op::AddF) { + bool inclusive = *prefix; + V k0 = this->s.m.i8(0); + V k1 = this->s.m.i8(1); + r = this->s.op(c, "wavePrefixOp." + sfx, Attr::NoUnwind, ty, 121, + std::vector<V>{arg, k0, k1}); + if (inclusive) r = this->s.m.bin(c, Bin::Add, r, arg); + } else { + fail("a wave prefix of an operation other than a sum"); + } + } else if (op == Op::Or || op == Op::And || op == Op::Xor) { + V k = this->s.m.i8(op == Op::And ? 0 : op == Op::Or ? 1 : 2); + r = this->s.op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, std::vector<V>{arg, k}); + } else { + std::uint8_t code, is_unsigned; + switch (op) { + case Op::AddU: code = 0, is_unsigned = 1; break; + case Op::AddF: code = 0, is_unsigned = 0; break; + case Op::MinU: code = 2, is_unsigned = 1; break; + case Op::MaxU: code = 3, is_unsigned = 1; break; + case Op::MinI: + case Op::MinF: code = 2, is_unsigned = 0; break; + default: code = 3, is_unsigned = 0; break; + } + V k = this->s.m.i8(code); + V u = this->s.m.i8(is_unsigned); + r = this->s.op(c, "waveActiveOp." + sfx, Attr::NoUnwind, ty, 119, std::vector<V>{arg, k, u}); + } + // two host waves of 32 hold the console's 64 lanes: their results combine + if (this->local || (this->exchange && std::get<1>(*this->exchange))) { + // this host wave's own result (and prefix): each wave on its own, or a group of 32 + // threads or fewer, which one host wave holds whole (combining with the 0 a missing half + // "gives" broke AND, MIN and signed MAX) + } else if (own && !prefix && op == Op::Or && !this->all_lanes(this->cur_ir)) { + // each thread walks the bits of this value and works only at its own, which the host + // wave's OR holds: the same run as with the console wave's OR + } else if (this->exchange) { + if (!this->all_lanes(this->cur_ir)) { + need(this->cur_ir); + fail("a wave reduction where not every lane runs"); + } + auto bits = [&](Lower& l, V v) { return is_float ? l.as_int(v) : v; }; + auto back = [&](Lower& l, V v) { return is_float ? l.as_float(v) : v; }; + if (prefix) { + // the upper half adds the lower half's total to its prefix + V k0 = this->s.m.i8(0); + V ku = this->s.m.i8(static_cast<std::uint8_t>(!is_float)); + V total = this->s.op(c, "waveActiveOp." + sfx, Attr::NoUnwind, ty, 119, + std::vector<V>{arg, k0, ku}); + V tb = bits(*this, total); + std::size_t c2 = this->cur; + V lo = this->exchange_halves(c2, tb).first; + lo = back(*this, lo); + V cl = this->console_lane(); + V k32 = this->s.m.i32(32); + V upper = this->s.m.cmp(c2, pred::IUGE, cl, k32); + V zero = is_float ? this->s.m.f32(0) : this->s.m.i32(0); + V add = this->s.m.select(c2, upper, lo, zero); + r = this->s.m.bin(c2, Bin::Add, r, add); + } else { + V rb = bits(*this, r); + std::size_t c2 = this->cur; + auto [lo0, hi0] = this->exchange_halves(c2, rb); + V lo = back(*this, lo0); + V hi = back(*this, hi0); + switch (op) { + case Op::AddU: + case Op::AddF: r = this->s.m.bin(c2, Bin::Add, lo, hi); break; + case Op::Or: r = this->s.m.bin(c2, Bin::Or, lo, hi); break; + case Op::And: r = this->s.m.bin(c2, Bin::And, lo, hi); break; + case Op::Xor: r = this->s.m.bin(c2, Bin::Xor, lo, hi); break; + default: { + // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40 + std::uint32_t code = op == Op::MaxF ? 35 + : op == Op::MinF ? 36 + : op == Op::MinU ? 40 + : op == Op::MaxU ? 39 + : op == Op::MinI ? 38 + : 37; + r = this->s.op(c2, "binary." + sfx, Attr::ReadNone, ty, code, std::vector<V>{lo, hi}); + break; + } + } + } + } + return is_float ? this->as_int(r) : r; +} + +// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere), +// returning the low (`!high`) or high (`high`) 32-bit word. +V Lower::active_f64_sum(Value lo_, Value hi_, Value mask, bool high) { + if (this->mask_data == MaskData::None) fail("a wave reduction in a mesh shader"); + std::size_t c = this->cur; + Bool m = ok_or(mask_of(*this->x.st, mask), "a wave reduction's untracked mask"); + V on = this->boolean(m, c); + V lo = this->i32_of(lo_); + V hi = this->i32_of(hi_); + V z = this->s.m.i32(0); + lo = this->s.m.select(c, on, lo, z); + hi = this->s.m.select(c, on, hi, z); + this->s.flags |= flags::WAVE_OPS | flags::DOUBLES; + Ty f64t = this->s.m.double_(); + Ty i32t = this->s.t.i32; + Ty split_ty = this->s.m.named_struct("dx.types.splitdouble", std::vector<Ty>{i32t, i32t}); + V arg = this->s.op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, std::vector<V>{lo, hi}); + V k0 = this->s.m.i8(0); + V k0b = this->s.m.i8(0); + V sum = this->s.op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, std::vector<V>{arg, k0, k0b}); + V split = this->s.op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, std::vector<V>{sum}); + V r_lo = this->s.m.extract(c, split, 0); + V r_hi = this->s.m.extract(c, split, 1); + if (this->exchange) { + if (!this->all_lanes(this->cur_ir)) { + need(this->cur_ir); + fail("a wave reduction where not every lane runs"); + } + auto [lo0, lo1] = this->exchange_halves(this->cur, r_lo); + auto [hi0, hi1] = this->exchange_halves(this->cur, r_hi); + std::size_t c2 = this->cur; + V d0 = this->s.op(c2, "makeDouble.f64", Attr::ReadNone, f64t, 101, std::vector<V>{lo0, hi0}); + V d1 = this->s.op(c2, "makeDouble.f64", Attr::ReadNone, f64t, 101, std::vector<V>{lo1, hi1}); + V total = this->s.m.bin(c2, Bin::Add, d0, d1); + V split2 = this->s.op(c2, "splitDouble.f64", Attr::ReadNone, split_ty, 102, std::vector<V>{total}); + r_lo = this->s.m.extract(c2, split2, 0); + r_hi = this->s.m.extract(c2, split2, 1); + } + return high ? r_hi : r_lo; +} + +// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's +// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest (f16_nearest). +V Lower::add_halves(V a, V b) { + std::size_t c = this->cur; + Ty f32t = this->s.t.f32; + V low = this->s.m.i32(0xFFFF); + auto wide = [&](Lower& l, V xv) { + V h = l.s.m.bin(c, Bin::And, xv, low); + return l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, std::vector<V>{h}); + }; + V fa = wide(*this, a); + V fb = wide(*this, b); + V f = this->s.m.bin(c, Bin::Add, fa, fb); + return this->f16_nearest(f); +} + +// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the lanes outside the +// mask), bit for bit as the console adds it: every addition rounds to 16 bits, so the order counts, and the +// compiler's is the balanced tree over the lanes in their order (lanes 2k and 2k+1, then pairs,... then the +// wave's two halves; wave::buddies). Each lane adds its partner's partial sum, read from the lane whose +// number differs in one bit, step by step; two host waves of 32 then exchange their halves' sums for the +// last addition. The high half of the result is lane 0's, which no `v_add_f16` writes. On a host wave of 64 +// lanes where not every lane runs, the lanes that are elsewhere count as the console's do (it masks them to +// +0): a partner's partial sum is read from the first lane there is of the partner's run of lanes, and is +// +0 without one. Two host waves of 32 can only exchange where every lane runs: refused elsewhere, in a +// thread group that does not fill its waves, and for each half-wave on its own (half a sum is no sum). +V Lower::half_sum(V xv) { + static constexpr Why WHERE = "a wave sum of 16-bit floats where not every lane runs"; + auto threads = ok_or(this->s.threads, "a wave sum of 16-bit floats outside compute"); + if (product3(threads) % 64 != 0) fail("a wave sum of 16-bit floats in a wave that is not full"); + if (this->local) fail("a wave sum of 16-bit floats in a half-wave"); + // two host waves of 32 that exchange, or one host wave of 64 lanes + bool halves_; + if (this->exchange && !std::get<1>(*this->exchange)) { + halves_ = true; + } else if (!this->exchange && this->s.wave_size == std::optional<std::uint32_t>(64) && + this->x.p->wave64) { + halves_ = false; + } else { + fail("a wave sum of 16-bit floats on these waves"); + } + bool every; + if (halves_) { + every = this->all_lanes(this->cur_ir); + } else { + auto all = all_lane_blocks(*this->x.st); + every = all && this->cur_ir < all->size() && (*all)[this->cur_ir]; + } + if (!every && halves_) { + need(this->cur_ir); + fail(WHERE); + } + std::size_t c = this->cur; + Ty i32t = this->s.t.i32; + V lane = this->s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, std::vector<V>{}); + V high = this->s.m.i32(0xFFFF0000u); + V low = this->s.m.i32(0xFFFF); + V zero = this->s.m.i32(0); + // the lanes that are here, when not all are + std::optional<std::pair<V, V>> here; + if (!every) { + this->s.flags |= flags::WAVE_OPS; + Ty four = this->s.m.named_struct("dx.types.fouri32", std::vector<Ty>(4, i32t)); + V yes = this->s.m.bool_(true); + V r = this->s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, std::vector<V>{yes}); + V e0 = this->s.m.extract(c, r, 0); + V e1 = this->s.m.extract(c, r, 1); + here = std::pair{e0, e1}; + } + // `v` of the first lane here of the `n` (a power of two) lanes from `base`: +0 of none + auto first_of = [&](Lower& l, V v, V base, std::uint32_t n) -> V { + if (!here) return l.read_lane(v, base); + auto [lo, hi] = *here; + V k31 = l.s.m.i32(31); + V k32 = l.s.m.i32(32); + V lower_ = l.s.m.cmp(c, pred::IULT, base, k32); + V word = l.s.m.select(c, lower_, lo, hi); + V shift = l.s.m.bin(c, Bin::And, base, k31); + word = l.s.m.bin(c, Bin::LShr, word, shift); + V run = l.s.m.i32(0xFFFFFFFFu >> (32 - n)); + word = l.s.m.bin(c, Bin::And, word, run); + V any = l.s.m.cmp(c, pred::NE, word, zero); + V nth = l.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, std::vector<V>{word}); + V from = l.s.m.bin(c, Bin::Add, base, nth); + // (no lane there: this one, which is here; the read is not used) + from = l.s.m.select(c, any, from, lane); + V got = l.read_lane(v, from); + return l.s.m.select(c, any, got, zero); + }; + V sum = xv; + std::uint32_t steps = halves_ ? 5 : 6; + for (std::uint32_t step = 0; step < steps; ++step) { + V bit = this->s.m.i32(1u << step); + V partner = this->s.m.bin(c, Bin::Xor, lane, bit); + if (!every) { + V run = this->s.m.i32(~((1u << step) - 1)); + partner = this->s.m.bin(c, Bin::And, partner, run); + } + V theirs = first_of(*this, sum, partner, 1u << step); + sum = this->add_halves(sum, theirs); + } + V first = first_of(*this, xv, zero, 1); + first = this->s.m.bin(c, Bin::And, first, high); + sum = this->s.m.bin(c, Bin::And, sum, low); + V mine = this->s.m.bin(c, Bin::Or, first, sum); + if (!halves_) return mine; + auto [lo, hi] = this->exchange_halves(c, mine); + std::size_t c2 = this->cur; + V total = this->add_halves(lo, hi); + total = this->s.m.bin(c2, Bin::And, total, low); + V first2 = this->s.m.bin(c2, Bin::And, lo, high); + return this->s.m.bin(c2, Bin::Or, first2, total); +} + +Lowered Lower::run(bool counted) { + const Program& p = *this->x.p; + if (counted) { + // Before anything else, so that wave counts, reads of the first lane and stores know + // only the lanes that run. + std::size_t original = this->s.entry; + if (!this->s.threads) throw std::logic_error("compute thread count"); + std::uint32_t width = (*this->s.threads)[0]; + V limit = this->host_word(RootType::Other(USER_DISPATCH_THREADS_X), 0, width); + Val gv = this->compute_id("groupId.i32", 94, 0); + if (!gv.is_i32()) throw std::logic_error("unreachable"); + V group = gv.v; + Val tv = this->thread_id(0); + if (!tv.is_i32()) throw std::logic_error("unreachable"); + V thread = tv.v; + V widthv = this->s.m.i32(width); + V first = this->s.m.bin(original, Bin::Mul, group, widthv); + V xv = this->s.m.bin(original, Bin::Add, first, thread); + V zero = this->s.m.i32(0); + V all = this->s.m.cmp(original, pred::EQ, limit, zero); + V inside = this->s.m.cmp(original, pred::IULT, xv, limit); + V runs = this->s.m.bin(original, Bin::Or, all, inside); + std::size_t body = this->s.m.new_block(); + std::size_t done = this->s.m.new_block(); + this->s.m.terminate(original, Term::cond_br(runs, body, done)); + this->s.m.terminate(done, Term::ret()); + this->s.entry = body; + } + this->find_coherent(); + auto order = ir::reverse_postorder(p.blocks); + for (std::size_t n = 0; n < order.size(); ++n) this->rpo[order[n]] = n; + for (std::size_t n = 0; n < order.size(); ++n) { + this->block[order[n]] = n == 0 ? this->s.entry : this->s.m.new_block(); + } + // Loop headers count iterations (`LOOP_LIMIT`). + for (std::size_t b : order) { + bool header = false; + for (std::size_t q : p.blocks[b].preds) { + if (this->block[q].has_value() && this->rpo[b] <= this->rpo[q]) { + header = true; + break; + } + } + if (header) { + std::size_t blk = this->block[b].value(); + V phi = this->s.m.phi(blk, this->s.t.i32); + this->counters.insert_or_assign(b, std::pair{phi, std::vector<std::pair<V, std::size_t>>{}}); + } + } + this->cur = this->s.entry; + this->find_sections(); + this->inputs(); + if (this->s.mesh) { + Mesh mesh = *this->s.mesh; + try { + this->mesh_prologue(mesh); + } catch (const WhyFail& e) { + unsupported(0, e.why); + } + this->block[order[0]] = this->cur; + } + for (std::size_t b : order) { + this->cur = this->block[b].value(); + this->cur_ir = b; + std::vector<std::size_t> preds; + for (std::size_t q : p.blocks[b].preds) { + if (this->block[q].has_value()) preds.push_back(q); + } + this->exported[b] = !preds.empty() && std::all_of(preds.begin(), preds.end(), [&](std::size_t q) { + return this->exported_out(q); + }); + const auto& phis = p.blocks[b].phis; + for (std::size_t i = 0; i < phis.size(); ++i) { + const auto& phi = phis[i]; + Val val; + if (phi.reg.is_s() && (phi.reg.n == ir::EXEC || phi.reg.n == ir::EXEC + 1)) { + val = Val::Missing("a lane mask"); + } else if (auto it = this->bad.find(phi.value); it != this->bad.end()) { + val = Val::Missing(it->second); + } else if (phi.reg.is_scc()) { + V v = this->s.m.phi(this->cur, this->s.t.i1); + this->data_phis.emplace_back(v, b, i); + val = Val::Bit(v); + } else { + V v = this->s.m.phi(this->cur, this->s.t.i32); + this->data_phis.emplace_back(v, b, i); + val = Val::I32(v); + } + this->vals.insert_or_assign(phi.value, val); + } + if (this->lds_meet && this->lds_meet->second.at(b).first) this->lds_meeting(); + std::size_t i = 0; + while (i < p.blocks[b].insts.size()) { + this->inst(b, i); + std::optional<std::size_t> end; + if (auto sb = this->sections.find(b); sb != this->sections.end()) { + if (auto si = sb->second.find(i); si != sb->second.end()) end = si->second.end; + } + if (end) { + for (std::size_t j = i + 1; j < *end; ++j) this->section_inst(b, j, i); + i = *end; + continue; + } + i += 1; + } + this->mask_ok = this->mask_data == MaskData::Console; + if (this->lds_meet && this->lds_meet->second.at(b).second) this->lds_meeting(); + this->tail[b] = this->cur; + this->exit(b); + } + this->fill_phis(); + std::vector<UserData> user_data_; + for (const auto& [k, u] : this->user_reads) user_data_.push_back(u); + this->s.samplers = static_cast<std::uint32_t>(this->samplers.size()); + std::vector<std::uint8_t> root_cbvs; + for (const auto& r : this->s.root_cbvs) root_cbvs.push_back(r.first); + std::vector<std::uint8_t> root_srvs; + for (const auto& r : this->s.root_srvs) root_srvs.push_back(r.first); + std::vector<std::uint8_t> root_uavs; + for (const auto& r : this->s.root_uavs) root_uavs.push_back(r.first); + Lowered out; + out.wave_size = this->s.wave_size; + out.cmp_samplers = this->s.cmp_samplers; + out.root_cbvs = std::move(root_cbvs); + out.root_srvs = std::move(root_srvs); + out.root_uavs = std::move(root_uavs); + out.nonuniform_handles = this->s.nonuniform_handles; + out.wave_ops = (this->s.flags & flags::WAVE_OPS) != 0; + out.dxil = std::move(this->s).finish(); + out.user_data = std::move(user_data_); + out.samplers = std::move(this->samplers); + return out; +} + +bool Lower::exported_out(std::size_t b) const { return this->exported[b] || this->has_done_export(b); } + +bool Lower::has_done_export(std::size_t b) const { + for (std::size_t i = 0; i < this->x.p->blocks[b].insts.size(); ++i) { + auto it = this->exports.find(Site{b, i}); + if (it != this->exports.end() && it->second->done) return true; + } + return false; +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_desc.cpp b/src/x2w_shader/emit/lower_desc.cpp new file mode 100644 index 0000000000..f8497e07c9 --- /dev/null +++ b/src/x2w_shader/emit/lower_desc.cpp @@ -0,0 +1,769 @@ +// normalized-format quotients, d16 channels, and the descriptors' handles and heap indices (handle, +// raw_twin, the descriptor and sampler phis, the slot words of heap views, per-lane heap indices). +// +// resource::Source is vs-front's tagged struct (kind + per-kind fields, leaves()). +#include <algorithm> + +#include "x2w_shader/emit/lower_impl.h" +#include "x2w_shader/spill.h" + +namespace x2w::vs::lower { + +namespace { + +// the shape of resource::Source. +using SK = Source::Kind; +bool is(const Source& s, SK k) { return s.kind == k; } + +// The root parameter `param` of the layout, none past its end (CODE). +const native::RootParam* layout_get(const NativeProgram& n, std::size_t param) { + return param < n.layout.size() ? &n.layout[param] : nullptr; +} + +bool root_is(const RootType& r, RootType::Kind k) { return r.kind == k; } + +} // namespace + +V Lower::norm_quotient(V a, std::uint32_t w) { + if (w == 11 || w == 12) { + return this->exact_norm(a, w); + } + std::size_t c = this->cur; + std::uint64_t d = (std::uint64_t{1} << w) - 1; + std::uint64_t kk = (std::uint64_t{1} << 32) / d; + std::uint64_t r = (std::uint64_t{1} << 32) % d; + auto k = [](Lower& l, std::uint64_t v) { return l.s.m.i32(static_cast<std::uint32_t>(v)); }; + V one = k(*this, 1); + V kv = k(*this, kk); + V q = this->s.m.bin(c, Bin::Mul, a, kv); + if (r != 1) { + V rv = k(*this, r); + V dv = k(*this, d); + V t = this->s.m.bin(c, Bin::Mul, a, rv); + V more = this->s.m.bin(c, Bin::UDiv, t, dv); + q = this->s.m.bin(c, Bin::Add, q, more); + } + // The bits to drop (1 to 8) from the exponent of `q >> 8`, which converts exactly (fewer than + // 25 bits); none when `q` fits. + V k8 = k(*this, 8); + V top = this->s.m.bin(c, Bin::LShr, q, k8); + top = this->s.m.cast(c, Cast::UiToFp, top, this->s.t.f32); + top = this->as_int(top); + V k23 = k(*this, 23); + V e = this->s.m.bin(c, Bin::LShr, top, k23); + V bias = k(*this, 127 + 15); + V shift = this->s.m.bin(c, Bin::Sub, e, bias); + V zero = k(*this, 0); + V b24 = k(*this, 1 << 24); + V fits = this->s.m.cmp(c, pred::IULT, q, b24); + shift = this->s.m.select(c, fits, zero, shift); + // Rounded up when the highest dropped bit is set: `a / d` is never exact, so a dropped half is + // more than half, never a tie. + V up = this->s.m.bin(c, Bin::Shl, q, one); + up = this->s.m.bin(c, Bin::LShr, up, shift); + up = this->s.m.bin(c, Bin::And, up, one); + V m = this->s.m.bin(c, Bin::LShr, q, shift); + m = this->s.m.bin(c, Bin::Add, m, up); + // At most 2^24: exact as a float, and so its scale by 2^(shift - 32). + V f = this->s.m.cast(c, Cast::UiToFp, m, this->s.t.f32); + V b95 = k(*this, 127 - 32); + V scale = this->s.m.bin(c, Bin::Add, shift, b95); + scale = this->s.m.bin(c, Bin::Shl, scale, k23); + scale = this->as_float(scale); + f = this->s.m.bin(c, Bin::Mul, f, scale); + return this->as_int(f); +} + +// norm_quotient in integers only, for any width up to 16: `Q` as there, 8 more bits when +// that leaves fewer than 25 (codes of wide formats near 0), then rounded to 24 bits to nearest +// even with the remainder as sticky bit, and assembled as float bits. +V Lower::exact_norm(V a, std::uint32_t w) { + std::size_t c = this->cur; + std::uint64_t d = (std::uint64_t{1} << w) - 1; + std::uint64_t kk = (std::uint64_t{1} << 32) / d; + std::uint64_t r = (std::uint64_t{1} << 32) % d; + auto k = [](Lower& l, std::uint64_t v) { return l.s.m.i32(static_cast<std::uint32_t>(v)); }; + V one = k(*this, 1); + V zero = k(*this, 0); + V dv = k(*this, d); + V k8 = k(*this, 8); + V kv = k(*this, kk); + V q = this->s.m.bin(c, Bin::Mul, a, kv); + V rem = a; + if (r != 1) { + V rv = k(*this, r); + V t = this->s.m.bin(c, Bin::Mul, a, rv); + V more = this->s.m.bin(c, Bin::UDiv, t, dv); + q = this->s.m.bin(c, Bin::Add, q, more); + rem = this->s.m.bin(c, Bin::URem, t, dv); + } + // The exponent's bias less the 32 (or 40) fraction bits of `q`; the shift below is added. + V bias = k(*this, 127 + 23 - 32); + if (kk < (std::uint64_t{1} << 24)) { + // Fewer than 25 bits for the smallest codes: 8 more. + V t = this->s.m.bin(c, Bin::Shl, rem, k8); + V more = this->s.m.bin(c, Bin::UDiv, t, dv); + V rest = this->s.m.bin(c, Bin::URem, t, dv); + V wide = this->s.m.bin(c, Bin::Shl, q, k8); + wide = this->s.m.bin(c, Bin::Or, wide, more); + V limit = k(*this, 1 << 24); + V small = this->s.m.cmp(c, pred::IULT, q, limit); + q = this->s.m.select(c, small, wide, q); + rem = this->s.m.select(c, small, rest, rem); + V b40 = k(*this, 127 + 23 - 40); + bias = this->s.m.select(c, small, b40, bias); + } + // Bits to drop: the bit length less 24, 1 to 8. + V shift = one; + for (std::uint32_t bit = 25; bit < 32; ++bit) { + V at = k(*this, std::uint64_t{1} << bit); + V ge = this->s.m.cmp(c, pred::IUGE, q, at); + V add = this->s.m.select(c, ge, one, zero); + shift = this->s.m.bin(c, Bin::Add, shift, add); + } + V mant = this->s.m.bin(c, Bin::LShr, q, shift); + V below = this->s.m.bin(c, Bin::Sub, shift, one); + V half = this->s.m.bin(c, Bin::LShr, q, below); + half = this->s.m.bin(c, Bin::And, half, one); + V low = this->s.m.bin(c, Bin::Shl, one, below); + low = this->s.m.bin(c, Bin::Sub, low, one); + low = this->s.m.bin(c, Bin::And, q, low); + V rest = this->s.m.bin(c, Bin::Or, low, rem); + V sticky = this->s.m.cmp(c, pred::NE, rest, zero); + V odd = this->s.m.bin(c, Bin::And, mant, one); + V tie = this->s.m.select(c, sticky, one, odd); + V up = this->s.m.bin(c, Bin::And, half, tie); + mant = this->s.m.bin(c, Bin::Add, mant, up); + // Rounding up to 2^24 moves to the next exponent. + V k24 = k(*this, 24); + V carry = this->s.m.bin(c, Bin::LShr, mant, k24); + mant = this->s.m.bin(c, Bin::LShr, mant, carry); + V e = this->s.m.bin(c, Bin::Add, bias, shift); + e = this->s.m.bin(c, Bin::Add, e, carry); + V k23 = k(*this, 23); + e = this->s.m.bin(c, Bin::Shl, e, k23); + V fraction = k(*this, 0x7F'FFFF); + V m = this->s.m.bin(c, Bin::And, mant, fraction); + V bits = this->s.m.bin(c, Bin::Or, e, m); + V is_zero = this->s.m.cmp(c, pred::EQ, a, zero); + return this->s.m.select(c, is_zero, zero, bits); +} + +// Channels of buffer format `format`, as format_load gives them, as d16 data: 16 bits +// each, two per dword, low half first (an odd last high half 0). Integer formats keep their low +// 16 bits; the others become f16. +std::vector<V> Lower::d16_channels(std::uint8_t format, std::vector<V> channels) { + auto fmt = ok_or(buffer_format(format), "a buffer format"); + Numeric numeric = fmt.second; + std::size_t c = this->cur; + std::vector<V> halves; + for (V x : channels) { + if (numeric == Numeric::Uint || numeric == Numeric::Sint) { + V m = this->s.m.i32(0xFFFF); + halves.push_back(this->s.m.bin(c, Bin::And, x, m)); + } else { + V f = this->as_float(x); + Ty i32t = this->s.t.i32; + halves.push_back(this->s.op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, std::vector<V>{f})); + } + } + std::vector<V> out; + for (std::size_t n = 0; n < halves.size(); n += 2) { + if (n + 1 < halves.size()) { + V lo = halves[n]; + V k16 = this->s.m.i32(16); + V hi = this->s.m.bin(c, Bin::Shl, halves[n + 1], k16); + out.push_back(this->s.m.bin(c, Bin::Or, lo, hi)); + } else { + out.push_back(halves[n]); + } + } + return out; +} + +// The byte offset a buffer descriptor built around a root descriptor adds (constant and +// computed parts); none for other descriptors. +std::pair<std::uint32_t, std::optional<V>> Lower::built_offset(const Source& src) { + if (is(src, SK::Built)) { + const Address& address = src.address; + std::optional<V> x; + if (address.dynamic) { + x = this->i32_of(*address.dynamic); + } + if (auto bias = this->root_bias(address.param)) { + if (x) { + x = this->s.m.bin(this->cur, Bin::Add, *x, *bias); + } else { + x = *bias; + } + } + return {address.offset, x}; + } + return {0, std::nullopt}; +} + +// For a root view the host binds as a raw view that may begin before the title's address (USER_VIEW_BIAS): +// the bytes to add to offsets through it. Every root UAV (root SRVs keep the views they have). +std::optional<V> Lower::root_bias(std::size_t param) { + const native::RootParam* p = layout_get(*this->x.native, param); + if (!p) return std::nullopt; + native::RootParam rp = *p; + // (Title memory by address where the user-data table is spilled: root_memory.) + if (!root_is(rp.root, RootType::Kind::Descriptor) || spill::is_spilled(*this->x.native)) { + return std::nullopt; + } + std::optional<ResourceType> kind; + for (const UsedResource& u : this->x.native->used) { + if (u.user_data == rp.user_data) { + kind = u.kind; + break; + } + } + if (kind && kind->kind == ResourceType::Kind::Uav) { + return this->host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0); + } + return std::nullopt; +} + +// The used-resource entry a descriptor loaded from a table falls in. +const UsedResource* Lower::used_kind(const Source& src) const { + + if (is(src, SK::Phi) || is(src, SK::Select) || is(src, SK::Lanes)) { + if (src.args.empty()) return nullptr; + return this->used_kind(src.args.front()); + } + if (is(src, SK::LanePhi)) { + for (const auto& a : src.lane_args) { + if (!a) continue; + if (const UsedResource* u = this->used_kind(*a)) return u; + } + return nullptr; + } + if (is(src, SK::Built)) { + const native::RootParam* rp = layout_get(*this->x.native, src.address.param); + if (!rp) return nullptr; + for (const UsedResource& u : this->x.native->used) { + if (root_is(u.root, RootType::Kind::Descriptor) && u.user_data == rp->user_data) return &u; + } + return nullptr; + } + if (!is(src, SK::Loaded) && !is(src, SK::Fetched)) { + return nullptr; + } + auto ai = this->scalar.find(src.load); + if (ai == this->scalar.end()) return nullptr; + const Address& a = ai->second; + const native::RootParam* rp = layout_get(*this->x.native, a.param); + if (!rp) return nullptr; + if (!root_is(rp->root, RootType::Kind::Table)) { + return nullptr; + } + std::uint32_t dword = (a.offset / 4) + std::uint32_t{src.first}; + // For equal maximum keys, prefer the last entry. + const UsedResource* best = nullptr; + for (const UsedResource& u : this->x.native->used) { + if (root_is(u.root, RootType::Kind::Table) && u.user_data == rp->user_data && + u.table_offset_dwords <= dword) { + if (!best || u.table_offset_dwords >= best->table_offset_dwords) best = &u; + } + } + return best; +} + +// A handle for the descriptor `src` read at `site`. +V Lower::handle(Site site, const Source& src, bool sampler, std::pair<std::uint32_t, std::uint32_t> props) { + switch (src.kind) { + case SK::Loaded: { + auto key = std::make_tuple(this->cur, src.load, src.first, sampler, props); + if (auto it = this->handles.find(key); it != this->handles.end()) { + return it->second; + } + V index = this->heap_index(src.load, src.first, sampler); + auto [twin, bounded] = this->raw_twin(src, index, sampler, props); + // A waterfall loop's load at the first lane's offset reads each lane's own entry (see + // `resource::Waterfall`). + const auto& loads = this->x.res->waterfall.loads; + bool per_lane = std::find(loads.begin(), loads.end(), src.load) != loads.end(); + V h = this->s.heap_handle_at(this->cur, twin, sampler, per_lane, props, bounded); + this->handles.insert_or_assign(key, h); + return h; + } + case SK::Constant: { + if (sampler) { + std::uint32_t n = this->register_sampler(src.constant, (props.first & 0x8000) != 0); + return this->s.sampler_handle(this->cur, n); + } + fail("a constant resource descriptor"); + } + case SK::Built: { + if (this->root_copy) { + return *this->root_copy; + } + const native::RootParam* p = layout_get(*this->x.native, src.address.param); + if (!p) fail("a descriptor built around a table in the code"); + native::RootParam rp = *p; + std::optional<ResourceType> kind; + for (const UsedResource& u : this->x.native->used) { + if (u.user_data == rp.user_data) { + kind = u.kind; + break; + } + } + bool desc = root_is(rp.root, RootType::Kind::Descriptor); + auto kind_is = [&](ResourceType::Kind k) { return kind && kind->kind == k; }; + if (desc && (kind_is(ResourceType::Kind::Cbv) || !kind) && props.first == 13) { + return this->s.root_cbv_handle(rp.slot); + } + if (desc && kind_is(ResourceType::Kind::Srv) && props.first == 11) { + return this->s.root_srv_handle(rp.slot); + } + // A root UAV: a raw buffer whether the access reads (11) or writes (11 with the UAV bit). + // Indexed accesses reach here as raw ones at index times the entry's stride (`buffer`). + if (desc && kind_is(ResourceType::Kind::Uav) && (props.first == 11 || props.first == 0x100b)) { + return this->s.root_uav_handle(rp.slot); + } + if (desc && kind_is(ResourceType::Kind::Srv) && props.first == 0x100b) { + fail("a write through a root SRV"); + } + fail("a typed root view"); + } + case SK::Phi: { + (void)site; + V phi = this->descriptor_phi(src.block, src.args, sampler, 8); + auto [index, bounded] = this->raw_twin(src, phi, sampler, props); + return this->s.heap_handle_at(this->cur, index, sampler, false, props, bounded); + } + case SK::Select: { + // The heap index of each choice, picked by SCC (uniform). + if (src.args.size() != 2 || !is(src.args[0], SK::Loaded) || !is(src.args[1], SK::Loaded)) { + fail("a descriptor chosen by a condition"); + } + Site a = src.args[0].load; + std::uint8_t fa = src.args[0].first; + Site b = src.args[1].load; + std::uint8_t fb = src.args[1].first; + Val g = this->get(src.scc); + if (!g.is_bit()) fail("SCC without a value"); + V cond = g.v; + V set = this->heap_index(a, fa, sampler); + V clear = this->heap_index(b, fb, sampler); + V index = this->s.m.select(this->cur, cond, set, clear); + auto [twin, bounded] = this->raw_twin(src, index, sampler, props); + return this->s.heap_handle_at(this->cur, twin, sampler, false, props, bounded); + } + case SK::Fetched: + case SK::Lanes: + case SK::LanePhi: { + // A descriptor each lane has its own of (a waterfall loop reads it from the first active + // lane): each lane's heap index, non-uniform. + V index = this->lane_heap_index(src, sampler); + auto [twin, bounded] = this->raw_twin(src, index, sampler, props); + return this->s.heap_handle_at(this->cur, twin, sampler, true, props, bounded); + } + } + std::abort(); // unreachable: every kind handled +} + +// The heap index to read descriptor `src` at, `index` being the title's: for a buffer read +// as raw bytes, through a table or picked from the heap itself (or picked and read as a constant +// buffer), the host's raw twin of that slot (shader raw_views), whose reads end where the view +// does. Everything else (textures, typed buffers, tables' constant buffers) stays in place. And +// whether it is a twin's (inside the host's heap). +// +// Tables too: a view that does not begin on 16 bytes cannot be raw, and a structured view with an eight-byte stride may start at offset eight. +std::pair<V, bool> Lower::raw_twin(const Source& src, V index, bool sampler, + std::pair<std::uint32_t, std::uint32_t> props) { + // Raw and constant buffers (DXIL resource kinds 11 and 13). + constexpr std::uint32_t RAW = 11; + constexpr std::uint32_t CONSTANT = 13; + std::uint32_t first = raw_views(); + auto picked = [&](const Source* leaf) { + if (!is(*leaf, SK::Loaded) && !is(*leaf, SK::Fetched)) { + return false; + } + auto ai = this->scalar.find(leaf->load); + if (ai == this->scalar.end()) return false; + const native::RootParam* p = layout_get(*this->x.native, ai->second.param); + if (!p) return false; + return root_is(p->root, RootType::Kind::ResourceHeap) || + (root_is(p->root, RootType::Kind::Table) && (props.first & 0xFF) == RAW); + }; + std::uint32_t kind = props.first & 0xFF; + if (first == 0 || sampler || !(kind == RAW || kind == CONSTANT)) { + return {index, false}; + } + std::vector<const Source*> leaves = src.leaves(); + if (!std::all_of(leaves.begin(), leaves.end(), picked)) { + return {index, false}; + } + std::size_t c = this->cur; + V last = this->s.m.i32(first - 1); + V firstv = this->s.m.i32(first); + Ty i32t = this->s.t.i32; + // (As `dx.op.binary` UMin, see `heap_handle`.) + V clamped = this->s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, std::vector<V>{index, last}); + this->s.m.tag(clamped, Tag::Clamp); + return {this->s.m.bin(c, Bin::Or, clamped, firstv), true}; +} + +// The heap index a descriptor phi picks. Each predecessor computes its heap index at its +// end and the join picks one with a phi; a predecessor whose descriptor is itself chosen by control +// flow (a phi of an earlier join, which dominates it) gives that join's phi, at most `depth` joins +// deep. +V Lower::descriptor_phi(std::size_t block, std::span<const Source> args, bool sampler, std::uint32_t depth) { + constexpr Why WHY = "a descriptor chosen by control flow"; + const Program& p = *this->x.p; + std::vector<std::pair<V, std::size_t>> incoming; + const auto& preds = p.blocks.at(block).preds; + for (std::size_t n = 0; n < preds.size() && n < args.size(); ++n) { + std::size_t q = preds[n]; + const Source& arg = args[n]; + if (!this->block.at(q)) { + continue; + } + std::size_t tail = ok_or(this->tail.at(q), WHY); + auto ei = this->edges.find({q, block}); + std::size_t at = ei != this->edges.end() ? ei->second : tail; + V index; + if (is(arg, SK::Loaded)) { + std::size_t here = std::exchange(this->cur, at); + try { + index = this->heap_index(arg.load, arg.first, sampler); + } catch (const WhyFail&) { + this->cur = here; + throw; + } + this->cur = here; + } else if (is(arg, SK::Phi) && depth > 0) { + index = this->descriptor_phi(arg.block, arg.args, sampler, depth - 1); + } else { + fail(WHY); + } + incoming.emplace_back(index, at); + } + std::size_t join = ok_or(this->block.at(block), WHY); + V phi = this->s.m.phi(join, this->s.t.i32); + this->s.m.set_phi(phi, incoming); + return phi; +} + +// Registers an immediate sampler constant and returns its slot index: a constant used with +// and without comparison takes one slot for each. +std::uint32_t Lower::register_sampler(std::span<const std::uint32_t> words_in, bool cmp) { + if (words_in.size() < 4) fail("a sampler constant"); + std::array<std::uint32_t, 4> words{words_in[0], words_in[1], words_in[2], words_in[3]}; + std::optional<std::size_t> slot; + for (std::size_t n = 0; n < this->samplers.size(); ++n) { + // (n < 64: at most 64 slots are ever pushed) + if (this->samplers[n] == words && (((this->s.cmp_samplers >> n) & 1) != 0) == cmp) { + slot = n; + break; + } + } + std::size_t n; + if (slot) { + n = *slot; + } else { + n = this->samplers.size(); + if (n >= 64) { + fail("more than 64 immediate sampler slots"); + } + this->samplers.push_back(words); + this->s.cmp_samplers |= std::uint64_t{cmp} << n; + } + return static_cast<std::uint32_t>(n); +} + +// Resolves a control-flow phi of immediate sampler constants into either a single static +// sampler register (`One`) or a uniform `i32` phi index over `regs` (`Many`) for branch dispatch at +// the sample site. +std::pair<std::optional<V>, std::vector<std::uint32_t>> Lower::sampler_phi_choice( + std::size_t block, std::span<const Source> args, bool cmp, std::uint32_t depth) { + constexpr Why WHY = "a descriptor chosen by control flow"; + std::vector<std::array<std::uint32_t, 4>> distinct; + this->collect_constant_samplers(block, args, depth, distinct); + if (distinct.empty()) { + fail(WHY); + } + std::vector<std::uint32_t> regs; + regs.reserve(distinct.size()); + for (const auto& w : distinct) { + regs.push_back(this->register_sampler(w, cmp)); + } + if (regs.size() == 1) { + return {std::nullopt, regs}; + } + V idx = this->sampler_index_phi(block, args, 0, distinct, depth); + return {idx, regs}; +} + +void Lower::collect_constant_samplers(std::size_t block, std::span<const Source> args, std::uint32_t depth, + std::vector<std::array<std::uint32_t, 4>>& distinct) const { + constexpr Why WHY = "a descriptor chosen by control flow"; + const Program& p = *this->x.p; + const auto& preds = p.blocks.at(block).preds; + for (std::size_t n = 0; n < preds.size() && n < args.size(); ++n) { + std::size_t q = preds[n]; + const Source& arg = args[n]; + if (!this->block.at(q)) { + continue; + } + if (is(arg, SK::Constant) && arg.constant.size() >= 4) { + std::array<std::uint32_t, 4> k{arg.constant[0], arg.constant[1], arg.constant[2], arg.constant[3]}; + if (std::find(distinct.begin(), distinct.end(), k) == distinct.end()) { + distinct.push_back(k); + } + } else if (is(arg, SK::Phi) && depth > 0) { + this->collect_constant_samplers(arg.block, arg.args, depth - 1, distinct); + } else { + fail(WHY); + } + } +} + +V Lower::sampler_index_phi(std::size_t block, std::span<const Source> args, std::uint32_t lower, + std::span<const std::array<std::uint32_t, 4>> distinct, std::uint32_t depth) { + constexpr Why WHY = "a descriptor chosen by control flow"; + const Program& p = *this->x.p; + std::vector<std::pair<V, std::size_t>> incoming; + const auto& preds = p.blocks.at(block).preds; + for (std::size_t n = 0; n < preds.size() && n < args.size(); ++n) { + std::size_t q = preds[n]; + const Source& arg = args[n]; + if (!this->block.at(q)) { + continue; + } + std::size_t tail = ok_or(this->tail.at(q), WHY); + auto ei = this->edges.find({q, block}); + std::size_t at = ei != this->edges.end() ? ei->second : tail; + V idx; + if (is(arg, SK::Constant) && arg.constant.size() >= 4) { + std::array<std::uint32_t, 4> k{arg.constant[0], arg.constant[1], arg.constant[2], arg.constant[3]}; + auto it = std::find(distinct.begin(), distinct.end(), k); + if (it == distinct.end()) fail(WHY); + auto pos = static_cast<std::uint32_t>(it - distinct.begin()); + idx = this->s.m.i32(lower + pos); + } else if (is(arg, SK::Phi) && depth > 0) { + idx = this->sampler_index_phi(arg.block, arg.args, lower, distinct, depth - 1); + } else { + fail(WHY); + } + incoming.emplace_back(idx, at); + } + std::size_t join = ok_or(this->block.at(block), WHY); + V phi = this->s.m.phi(join, this->s.t.i32); + this->s.m.set_phi(phi, incoming); + return phi; +} + +// The bytes per element of the buffer view `src` names, if the program picks it from the +// view heap at an index it computes (root type ResourceHeap): read from the host's table by heap +// slot in the current block. +std::optional<V> Lower::slot_stride(const Source& src) { + std::optional<V> word = this->slot_word(src); + if (!word) return std::nullopt; + V bits = this->s.m.i32(VIEW_STRIDE_BITS); + return this->s.m.bin(this->cur, Bin::And, *word, bits); +} + +// Whether the typed buffer view `src` names is one of an integer format, and whether a +// signed one, as slot_stride (none: a view the program does not pick from the heap). +std::optional<std::pair<V, V>> Lower::integer_view(const Source& src) { + std::optional<V> word = this->slot_word(src); + if (!word) { + return std::nullopt; + } + std::size_t c = this->cur; + V zero = this->s.m.i32(0); + auto test = [&](std::uint32_t bit) { + V bv = this->s.m.i32(bit); + V x = this->s.m.bin(c, Bin::And, *word, bv); + return this->s.m.cmp(c, pred::NE, x, zero); + }; + V integer = test(VIEW_INTEGER); + V signed_ = test(VIEW_SIGNED); + return std::pair<V, V>{integer, signed_}; +} + +// The host's word for the buffer view `src` names: its stride and format kind +// (shader SLOT_STRIDES). +std::optional<V> Lower::slot_word(const Source& src) { + if (!is(src, SK::Loaded)) { + return std::nullopt; + } + Site load = src.load; + std::uint8_t first = src.first; + bool heap = false; + if (auto ai = this->scalar.find(load); ai != this->scalar.end()) { + const native::RootParam* p = layout_get(*this->x.native, ai->second.param); + heap = p && root_is(p->root, RootType::Kind::ResourceHeap); + } + if (!heap) { + return std::nullopt; + } + auto key = std::make_tuple(this->cur, load, first); + if (auto it = this->strides.find(key); it != this->strides.end()) { + return it->second; + } + std::size_t c = this->cur; + V slot = this->heap_index(load, first, false); + // Inside the table whatever the index (lanes that do not run compute one too): a root view has + // no bounds of its own. + V last = this->s.m.i32(SLOT_STRIDES_COUNT - 1); + Ty i32t = this->s.t.i32; + slot = this->s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, std::vector<V>{slot, last}); + this->s.m.tag(slot, Tag::Clamp); + V two = this->s.m.i32(2); + V byte = this->s.m.bin(c, Bin::Shl, slot, two); + V h = this->s.root_srv_handle(SLOT_STRIDES); + V iu = this->s.m.undef(this->s.t.i32); + V mask = this->s.m.i8(1); + V align = this->s.m.i32(4); + V r = this->s.op(c, "rawBufferLoad.f32", Attr::ReadOnly, this->s.t.res_ret, 139, + std::vector<V>{h, byte, iu, mask, align}); + V f = this->s.m.extract(c, r, 0); + V v = this->as_int(f); + this->strides.insert_or_assign(key, v); + return v; +} + +// The heap index of a descriptor that may differ between lanes, computed in the current +// block (or, chosen by control flow, at the join). +V Lower::lane_heap_index(const Source& src, bool sampler) { + switch (src.kind) { + case SK::Loaded: + return this->heap_index(src.load, src.first, sampler); + case SK::Fetched: + return this->fetched_index(src.load, src.first, sampler); + case SK::Lanes: + case SK::Select: { + Value mask = is(src, SK::Lanes) ? src.mask : src.scc; + if (src.args.size() != 2) { + fail("a descriptor chosen per lane"); + } + const Source& a = src.args[0]; + const Source& b = src.args[1]; + V cond; + if (is(src, SK::Lanes)) { + auto mi = this->x.st->masks.find(mask); + if (mi == this->x.st->masks.end()) fail("a descriptor chosen per lane by an untracked mask"); + Bool m = mi->second; + cond = this->boolean(m, this->cur); + } else { + Val g = this->get(mask); + if (!g.is_bit()) fail("SCC without a value"); + cond = g.v; + } + V set = this->lane_heap_index(a, sampler); + V clear = this->lane_heap_index(b, sampler); + return this->s.m.select(this->cur, cond, set, clear); + } + case SK::LanePhi: { + // Each predecessor computes its heap index at its end (what it reads is there: the dwords + // are, on that edge); the join picks the one of the edge the lane came by. An edge no lane + // reading it takes gives index 0. + std::size_t block = src.block; + std::size_t join = ok_or(this->block.at(block), "a per-lane descriptor chosen by control flow"); + std::vector<std::pair<V, std::size_t>> incoming; + const auto& preds = this->x.p->blocks.at(block).preds; + for (std::size_t n = 0; n < preds.size() && n < src.lane_args.size(); ++n) { + std::size_t q = preds[n]; + const auto& arg = src.lane_args[n]; + if (!this->block.at(q)) { + continue; + } + std::size_t tail = ok_or(this->tail.at(q), "a per-lane descriptor joined from a later block"); + auto ei = this->edges.find({q, block}); + std::size_t at = ei != this->edges.end() ? ei->second : tail; + V index; + if (arg) { + std::size_t here = std::exchange(this->cur, at); + try { + index = this->lane_heap_index(*arg, sampler); + } catch (const WhyFail&) { + this->cur = here; + throw; + } + this->cur = here; + } else { + index = this->s.m.i32(0); + } + incoming.emplace_back(index, at); + } + V phi = this->s.m.phi(join, this->s.t.i32); + this->s.m.set_phi(phi, incoming); + return phi; + } + default: + fail("a per-lane descriptor from neither a heap load nor a choice of them"); + } +} + +// The heap index of the descriptor at dword `first` of what the global load at `load` +// reads, in each lane: its address (base plus offsets) over the descriptor size. +V Lower::fetched_index(Site load, std::uint8_t first, bool sampler) { + constexpr Why WHY = "a per-lane descriptor load"; + auto ai = this->scalar.find(load); + if (ai == this->scalar.end()) fail("an untracked descriptor load"); + Address a = ai->second; + const native::RootParam* rp = layout_get(*this->x.native, a.param); + if (!rp || !(root_is(rp->root, RootType::Kind::Table) || root_is(rp->root, RootType::Kind::ResourceHeap) || + root_is(rp->root, RootType::Kind::SamplerHeap))) { + fail("a descriptor outside the heaps"); + } + const Inst& li = this->x.p->blocks.at(load.first).insts.at(load.second); + const auto* fl = std::get_if<gfx10::Flat>(&li.fields); + if (!fl || !fl->addr || fl->addr->kind != Operand::Kind::Vector) { + fail(WHY); + } + std::uint8_t reg = fl->addr->reg; + std::optional<Operand> saddr = fl->saddr; + std::int16_t offset = fl->offset; + std::size_t c = this->cur; + // The low dword of the address: SGPR base plus VGPR offset, or the VGPR pair's low half (heap + // addresses fit in 32 bits). + V at = this->i32_of(ok_or(li.read(Reg::V(reg)), WHY)); + if (saddr && saddr->kind == Operand::Kind::Scalar && saddr->code != gfx10::NULL_CODE) { + V base = this->i32_of(ok_or(li.read(Reg::S(saddr->code)), WHY)); + at = this->s.m.bin(c, Bin::Add, base, at); + } + V k = this->s.m.i32(static_cast<std::uint32_t>(static_cast<std::int32_t>(offset)) + 4 * std::uint32_t{first}); + at = this->s.m.bin(c, Bin::Add, at, k); + V shift = this->s.m.i32(sampler ? 4 : 5); + return this->s.m.bin(c, Bin::LShr, at, shift); +} + +// The heap index of the descriptor at dword `first` of what the scalar load at `load` +// reads, computed in the current block. +V Lower::heap_index(Site load, std::uint8_t first, bool sampler) { + auto ai = this->scalar.find(load); + if (ai == this->scalar.end()) fail("an untracked descriptor load"); + Address a = ai->second; + const native::RootParam* rp = layout_get(*this->x.native, a.param); + if (!rp || !(root_is(rp->root, RootType::Kind::Table) || root_is(rp->root, RootType::Kind::ResourceHeap) || + root_is(rp->root, RootType::Kind::SamplerHeap))) { + fail("a descriptor outside the heaps"); + } + const Inst& li = this->x.p->blocks.at(load.first).insts.at(load.second); + const auto* sm = std::get_if<gfx10::Smem>(&li.fields); + if (!sm) { + fail("a descriptor load"); + } + if (sm->base.kind != Operand::Kind::Scalar) { + fail("a descriptor load"); + } + std::uint8_t code = sm->base.code; + std::size_t c = this->cur; + Value base = ok_or(li.read(Reg::S(code)), "a descriptor load"); + V addr = this->i32_of(base); + V k = this->s.m.i32(static_cast<std::uint32_t>(sm->offset) + 4 * std::uint32_t{first}); + addr = this->s.m.bin(c, Bin::Add, addr, k); + if (!(sm->soffset.kind == Operand::Kind::Scalar && sm->soffset.code == gfx10::NULL_CODE)) { + V so = this->operand(li, sm->soffset); + addr = this->s.m.bin(c, Bin::Add, addr, so); + } + V shift = this->s.m.i32(sampler ? 4 : 5); + return this->s.m.bin(c, Bin::LShr, addr, shift); +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_ds_sop.cpp b/src/x2w_shader/emit/lower_ds_sop.cpp new file mode 100644 index 0000000000..96b8c8b5fc --- /dev/null +++ b/src/x2w_shader/emit/lower_ds_sop.cpp @@ -0,0 +1,1353 @@ +// LDS, instruction dispatch, and scalar ALU lowering. See lower_impl.h and GMR/vs_port/lower/PORTING.md. +#include <algorithm> +#include <cstdint> +#include <optional> +#include <string> +#include <string_view> +#include <utility> +#include <vector> + +#include "x2w_shader/emit/lower_impl.h" +#include "x2w_shader/spill.h" + +namespace x2w::vs::lower { + +namespace { + +// removes every trailing repetition of `pat`. +std::string_view trim_end_matches(std::string_view s, std::string_view pat) { + while (!pat.empty() && s.ends_with(pat)) s.remove_suffix(pat.size()); + return s; +} + +// every non-overlapping occurrence, left to right. +std::string replace_all(std::string_view s, std::string_view from, std::string_view to) { + std::string out; + std::size_t at = 0; + while (true) { + std::size_t k = s.find(from, at); + if (k == std::string_view::npos) break; + out.append(s.substr(at, k - at)); + out.append(to); + at = k + from.size(); + } + out.append(s.substr(at)); + return out; +} + +bool contains(std::string_view s, std::string_view x) { return s.find(x) != std::string_view::npos; } + +// the text after the last '_' (all of it without one). +std::string_view last_part(std::string_view n) { + std::size_t k = n.rfind('_'); + return k == std::string_view::npos ? n : n.substr(k + 1); +} + +} // namespace + +void Lower::ds(const Inst& inst, std::size_t b, std::size_t i) { + const auto& f = std::get<gfx10::Ds>(inst.fields); + const auto& dst = f.dst; + const auto& addr = f.addr; + const auto& data = f.data; + const std::uint8_t offset0 = f.offset0; + const std::uint8_t offset1 = f.offset1; + if (f.gds) { + fail("GDS"); + } + const std::string_view name = inst.name(); + const std::optional<V> guard = this->guard(b, i); + const std::size_t c = this->cur; + const std::uint32_t offset = std::uint32_t(offset0) | (std::uint32_t(offset1) << 8); + std::optional<std::uint8_t> dst_reg; + if (dst && dst->kind == Operand::Kind::Vector) dst_reg = dst->reg; + if (name == "ds_swizzle_b32") { + // Bit 15 set: each lane of a quad picks a lane of it; else lanes + // of each group of 32 combine their index with and/or/xor masks. + const bool quad = (offset & 0x8000) != 0 || + ((offset & 0x1C) == 0x1C && (offset & 0x380) == 0 && ((offset >> 10) & 0x1F) < 4); + // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the + // console's, so quad-local swizzles read through quad operations. + const bool mesh_quad = this->s.mesh.has_value() && quad; + if (!mesh_quad) { + this->cross_lane(quad); + } + // The source sits in the address field. + const Operand src_op = ok_or(addr, "a swizzle source"); + const V x = this->vgprs(inst, src_op, 1).at(0); + const V lane = this->lane_index(); + auto k = [](Lower& l, std::uint32_t v) { return l.s.m.i32(v); }; + V src{}; + if ((offset & 0x8000) != 0) { + V three = k(*this, 3); + V one = k(*this, 1); + V sel = this->s.m.bin(c, Bin::And, lane, three); + V sh = this->s.m.bin(c, Bin::Shl, sel, one); + V pattern = k(*this, offset & 0xFF); + V pick = this->s.m.bin(c, Bin::LShr, pattern, sh); + pick = this->s.m.bin(c, Bin::And, pick, three); + V not3 = k(*this, ~3u); + V base = this->s.m.bin(c, Bin::And, lane, not3); + src = this->s.m.bin(c, Bin::Or, base, pick); + } else { + V and_ = k(*this, (offset & 0x1F) | ~0x1Fu); + V or_ = k(*this, (offset >> 5) & 0x1F); + V xor_ = k(*this, (offset >> 10) & 0x1F); + V t = this->s.m.bin(c, Bin::And, lane, and_); + t = this->s.m.bin(c, Bin::Or, t, or_); + src = this->s.m.bin(c, Bin::Xor, t, xor_); + } + V r{}; + if (mesh_quad) { + r = this->quad_pick(x, src); + } else if (this->helpers_read(quad)) { + std::array<std::uint8_t, 4> lanes{}; + for (std::uint32_t q = 0; q < 4; ++q) { + if ((offset & 0x8000) != 0) { + lanes[q] = std::uint8_t((offset >> (2 * q)) & 3); + } else { + lanes[q] = std::uint8_t((((q & offset) | ((offset >> 5) & 3)) ^ ((offset >> 10) & 3))) & 3; + } + } + r = this->quad_read(x, lanes); + } else { + r = this->read_lane(x, src); + } + const std::uint8_t reg = ok_or(dst_reg, "a swizzle result"); + this->write(inst, Reg::V(reg), r, guard); + return; + } + if (name == "ds_bpermute_b32") { + // Backward permute: no LDS is touched. Each lane takes the data + // register of the lane its address names, (address + offset) / 4 + // within the wave; a source lane outside EXEC gives 0. (the title's + // checkerboard shadow-mask generators read their neighbours' samples + // with it; without them every shadowed light was multiplied by an + // empty mask.) + // shortcut: a source lane that is not at this instruction on the + // host (it left through a branch, not a guard) is read as the + // host gives it; the console reads 0. + this->cross_lane(false); + if (this->exchange && !std::get<1>(*this->exchange)) { + // a console wave of 64 run as two host waves: the lane named + // may be in the other one + fail("a lane permute across two host waves"); + } + const Operand at_op = ok_or(addr, "a permute address"); + V at = this->vgprs(inst, at_op, 1).at(0); + const Operand* x_op = ok_or(data.empty() ? nullptr : &data[0], "a permute source"); + V x = this->vgprs(inst, *x_op, 1).at(0); + V o = this->s.m.i32(offset); + at = this->s.m.bin(c, Bin::Add, at, o); + V two = this->s.m.i32(2); + V src = this->s.m.bin(c, Bin::LShr, at, two); + V last = this->s.m.i32(this->wave() - 1); + src = this->s.m.bin(c, Bin::And, src, last); + if (guard) { + V z = this->s.m.i32(0); + x = this->s.m.select(c, *guard, x, z); + } + V r = this->read_lane(x, src); + const std::uint8_t reg = ok_or(dst_reg, "a permute result"); + this->write(inst, Reg::V(reg), r, guard); + return; + } + if (this->s.lds_dwords == 0) { + fail("LDS the program does not allocate"); + } + const Operand a_op = ok_or(addr, "an LDS address"); + const V a = this->vgprs(inst, a_op, 1).at(0); + // shortcut: LDS addresses are taken as dword-aligned and in bounds + // (out-of-bounds console accesses read 0 and drop writes). + auto dword = [a](Lower& l, std::uint32_t bytes) -> V { + const std::size_t c = l.cur; + V o = l.s.m.i32(bytes); + V at = l.s.m.bin(c, Bin::Add, a, o); + V two = l.s.m.i32(2); + V index = l.s.m.bin(c, Bin::LShr, at, two); + V lds = l.s.lds(); + return l.s.m.element(c, lds, index); + }; + auto width = [](std::string_view n) -> std::uint32_t { + std::string_view last = last_part(n); + if (last == "b64") return 2; + if (last == "b96") return 3; + if (last == "b128") return 4; + return 1; + }; + // (byte offset, dwords) per element; read2/write2 scale their two + // offsets by the element size (x64 for st64). + auto pair_of = [&](std::string_view n) -> std::vector<std::pair<std::uint32_t, std::uint32_t>> { + const std::uint32_t w = width(n); + const std::uint32_t scale = 4 * w * (contains(n, "st64") ? 64u : 1u); + return { + {std::uint32_t(offset0) * scale, w}, + {std::uint32_t(offset1) * scale, w}, + }; + }; + // Bytes and halves: the dword holding them, and their bit position + // in it (naturally aligned, so they never straddle dwords). + // `_d16` reads fill a register's low half (`_d16_hi` its high half) + // and keep the other; `_d16_hi` writes take the data's high half. + const std::string_view base = trim_end_matches(trim_end_matches(name, "_hi"), "_d16"); + std::optional<std::uint32_t> sub; + if (base == "ds_read_u8" || base == "ds_read_i8" || base == "ds_write_b8") { + sub = 8u; + } else if (base == "ds_read_u16" || base == "ds_read_i16" || base == "ds_write_b16") { + sub = 16u; + } + if (sub && !(base == name || (name.ends_with("_d16") && base.starts_with("ds_read")) || + name.ends_with("_d16_hi"))) { + sub.reset(); + } + if (sub) { + const std::uint32_t bits = *sub; + V p = dword(*this, offset); + V o = this->s.m.i32(offset); + V at = this->s.m.bin(c, Bin::Add, a, o); + V three = this->s.m.i32(3); + V byte = this->s.m.bin(c, Bin::And, at, three); + V sh = this->s.m.bin(c, Bin::Shl, byte, three); + V mask = this->s.m.i32((1u << bits) - 1); + if (name.starts_with("ds_read")) { + const std::uint8_t reg = ok_or(dst_reg, "an LDS read result"); + V w = this->s.m.load(c, p); + V x = this->s.m.bin(c, Bin::LShr, w, sh); + if (contains(base, "_i")) { + V k = this->s.m.i32(32 - bits); + x = this->s.m.bin(c, Bin::Shl, x, k); + x = this->s.m.bin(c, Bin::AShr, x, k); + } else { + x = this->s.m.bin(c, Bin::And, x, mask); + } + if (base != name) { + V old{}; + if (auto v = inst.read(Reg::V(reg))) { + old = this->i32_of(*v); + } else { + old = this->s.m.i32(0); + } + V half = this->s.m.i32(0xFFFF); + x = this->s.m.bin(c, Bin::And, x, half); + V keep{}; + if (name.ends_with("_hi")) { + V k16 = this->s.m.i32(16); + x = this->s.m.bin(c, Bin::Shl, x, k16); + keep = half; + } else { + keep = this->s.m.i32(0xFFFF'0000u); + } + old = this->s.m.bin(c, Bin::And, old, keep); + x = this->s.m.bin(c, Bin::Or, old, x); + } + this->write(inst, Reg::V(reg), x, guard); + } else { + // Clear, then set: two atomics, so lanes writing other + // bytes of the dword keep theirs. + const Operand* d = ok_or(data.empty() ? nullptr : &data[0], "an LDS write"); + V x = this->vgprs(inst, *d, 1).at(0); + if (name != base) { + // The data's high half. + V k16 = this->s.m.i32(16); + x = this->s.m.bin(c, Bin::LShr, x, k16); + } + x = this->s.m.bin(c, Bin::And, x, mask); + x = this->s.m.bin(c, Bin::Shl, x, sh); + V m = this->s.m.bin(c, Bin::Shl, mask, sh); + V ones = this->s.m.i32(0xFFFF'FFFFu); + V keep = this->s.m.bin(c, Bin::Xor, m, ones); + auto at_g = this->begin_guarded(guard); + this->s.m.atomic(this->cur, Rmw::And, p, keep); + this->s.m.atomic(this->cur, Rmw::Or, p, x); + this->end_guarded(at_g, {}); + } + return; + } + if (name.starts_with("ds_read")) { + const std::string_view rest = name.substr(std::string_view("ds_read").size()); + std::vector<std::pair<std::uint32_t, std::uint32_t>> elements; + if (rest.starts_with('2')) { + elements = pair_of(name); + } else if (rest == "_b32" || rest == "_b64" || rest == "_b96" || rest == "_b128") { + elements = {{offset, width(name)}}; + } else { + fail("an LDS read of bytes or halves"); + } + const std::uint8_t reg = ok_or(dst_reg, "an LDS read result"); + std::uint8_t n = 0; + for (auto [off, w] : elements) { + for (std::uint32_t k = 0; k < w; ++k) { + V p = dword(*this, off + 4 * k); + V x = this->s.m.load(this->cur, p); + this->write(inst, Reg::V(std::uint8_t(reg + n)), x, guard); + n += 1; + } + } + return; + } + if (name.starts_with("ds_write")) { + const std::string_view rest = name.substr(std::string_view("ds_write").size()); + std::vector<std::pair<std::uint32_t, std::uint32_t>> elements; + if (rest.starts_with('2')) { + elements = pair_of(name); + } else if (rest == "_b32" || rest == "_b64" || rest == "_b96" || rest == "_b128") { + elements = {{offset, width(name)}}; + } else { + fail("an LDS write of bytes or halves"); + } + std::vector<std::pair<std::uint32_t, V>> stores; + for (std::size_t e = 0; e < elements.size(); ++e) { + auto [off, w] = elements[e]; + const Operand* d = ok_or(e < data.size() ? &data[e] : nullptr, "an LDS write"); + std::vector<V> vals = this->vgprs(inst, *d, std::uint8_t(w)); + for (std::size_t k = 0; k < vals.size(); ++k) { + stores.emplace_back(off + 4 * std::uint32_t(k), vals[k]); + } + } + auto at_g = this->begin_guarded(guard); + for (auto [off, x] : stores) { + V p = dword(*this, off); + this->s.m.store(this->cur, p, x); + } + this->end_guarded(at_g, {}); + return; + } + // Atomics: the old value returns with `_rtn`. + if (!name.starts_with("ds_")) fail("an LDS operation"); + const std::string op = replace_all(name.substr(3), "_rtn", ""); + std::optional<Rmw> rmw; + if (op == "add_u32") { + rmw = Rmw::Add; + } else if (op == "sub_u32") { + rmw = Rmw::Sub; + } else if (op == "and_b32") { + rmw = Rmw::And; + } else if (op == "or_b32") { + rmw = Rmw::Or; + } else if (op == "xor_b32") { + rmw = Rmw::Xor; + } else if (op == "min_i32") { + rmw = Rmw::Min; + } else if (op == "max_i32") { + rmw = Rmw::Max; + } else if (op == "min_u32") { + rmw = Rmw::UMin; + } else if (op == "max_u32") { + rmw = Rmw::UMax; + } else if (op == "wrxchg_b32") { + rmw = Rmw::Xchg; + } else if (op == "cmpst_b32" || op == "max_f32" || op == "min_f32") { + rmw.reset(); + } else { + fail("an LDS operation"); + } + const Operand* d0 = ok_or(data.empty() ? nullptr : &data[0], "an LDS atomic"); + const V v0 = this->vgprs(inst, *d0, 1).at(0); + std::optional<V> v1; + if (data.size() > 1) { + v1 = this->vgprs(inst, data[1], 1).at(0); + } + std::optional<std::pair<std::uint8_t, Value>> old_reg; + if (dst_reg) { + if (auto v = inst.read(Reg::V(*dst_reg))) old_reg = std::make_pair(*dst_reg, *v); + } + V outside{}; + if (old_reg) { + // both are evaluated, in this order. + std::optional<V> got = ok([&] { return this->i32_of(old_reg->second); }); + V z = this->s.m.i32(0); + outside = got ? *got : z; + } else { + outside = this->s.m.i32(0); + } + const V p = dword(*this, offset); + std::optional<bool> fminmax; + if (op == "max_f32") { + fminmax = true; + } else if (op == "min_f32") { + fminmax = false; + } + if (fminmax) { + const bool max = *fminmax; + auto at_g = this->begin_guarded(guard); + V r = this->lds_float_min_max(p, v0, max); + std::vector<std::pair<V, V>> vals{{r, outside}}; + r = this->end_guarded(at_g, vals).at(0); + if (dst_reg) { + this->write(inst, Reg::V(*dst_reg), r, std::nullopt); + } + return; + } + auto at_g = this->begin_guarded(guard); + V r{}; + if (rmw) { + r = this->s.m.atomic(this->cur, *rmw, p, v0); + } else { + // Compare with data0, store data1. + const std::size_t cur = this->cur; + const V nv = ok_or(v1, "an LDS compare"); + r = this->s.m.cmpxchg(cur, p, v0, nv); + } + std::vector<std::pair<V, V>> vals{{r, outside}}; + r = this->end_guarded(at_g, vals).at(0); + if (dst_reg) { + this->write(inst, Reg::V(*dst_reg), r, std::nullopt); + } +} + +// `ds_max_f32` (`max`) or `ds_min_f32` on the LDS dword at `p` with the float bits `data`; the old +// bits return. DXIL has no float atomics on group-shared memory, so this is a compare-exchange loop +// around lds_float_pick, which gives what RDNA2 writes (measured on gfx1036): an sNaN, data first, +// then memory, is written quieted; otherwise a NaN loses to a number (two quiet NaNs give the +// data); numbers compare as floats with -0 below +0. +// shortcut: f32 denormals compare as kept; with the console's MODE flushing them they would order +// as +-0 first (MODE is not modelled). +V Lower::lds_float_min_max(V p, V data, bool max) { + const std::size_t pre = this->cur; + V init = this->s.m.load(pre, p); + const std::size_t lp = this->s.m.new_block(); + const std::size_t exit = this->s.m.new_block(); + this->s.m.terminate(pre, Term::br(lp)); + const Ty i32t = this->s.t.i32; + V old = this->s.m.phi(lp, i32t); + this->cur = lp; + V nw = this->lds_float_pick(old, data, max); + V prev = this->s.m.cmpxchg(lp, p, old, nw); + V done = this->s.m.cmp(lp, pred::EQ, prev, old); + this->s.m.set_phi(old, std::vector<std::pair<V, std::size_t>>{{init, pre}, {prev, lp}}); + this->s.m.terminate(lp, Term::cond_br(done, exit, lp)); + this->cur = exit; + return old; +} + +// What `ds_max_f32` (`max`) or `ds_min_f32` writes over the dword `mem` with `data` (float bits). +V Lower::lds_float_pick(V mem, V data, bool max) { + const std::size_t c = this->cur; + auto k = [](Lower& l, std::uint32_t v) { return l.s.m.i32(v); }; + const V abs_mask = k(*this, 0x7FFF'FFFFu); + const V inf = k(*this, 0x7F80'0000u); + const V quiet = k(*this, 0x40'0000u); + const V zero = k(*this, 0); + auto nan = [&](Lower& l, V x) { + V m = l.s.m.bin(c, Bin::And, x, abs_mask); + return l.s.m.cmp(c, pred::IUGT, m, inf); + }; + auto snan = [&](Lower& l, V x) { + V n = nan(l, x); + V q = l.s.m.bin(c, Bin::And, x, quiet); + V sig = l.s.m.cmp(c, pred::EQ, q, zero); + return l.s.m.bin(c, Bin::And, n, sig); + }; + // A total order of the numbers as signed integers, -0 below +0: + // negative floats' magnitude bits reversed. + auto key = [&](Lower& l, V x) { + V k31 = l.s.m.i32(31); + V sign = l.s.m.bin(c, Bin::AShr, x, k31); + V flip = l.s.m.bin(c, Bin::And, sign, abs_mask); + return l.s.m.bin(c, Bin::Xor, x, flip); + }; + V dk = key(*this, data); + V mk = key(*this, mem); + V take = this->s.m.cmp(c, max ? pred::SGT : pred::SLT, dk, mk); + V r = this->s.m.select(c, take, data, mem); + V dn = nan(*this, data); + V mn = nan(*this, mem); + // One NaN: the number; two quiet NaNs: the data. + r = this->s.m.select(c, mn, data, r); + V both = this->s.m.bin(c, Bin::And, dn, mn); + V only_data{}; + { + V t = this->s.m.bool_(true); + V not_both = this->s.m.bin(c, Bin::Xor, both, t); + only_data = this->s.m.bin(c, Bin::And, dn, not_both); + } + r = this->s.m.select(c, only_data, mem, r); + // Signalling NaNs win, quieted: the data's first. + V qm = this->s.m.bin(c, Bin::Or, mem, quiet); + V sm = snan(*this, mem); + r = this->s.m.select(c, sm, qm, r); + V qd = this->s.m.bin(c, Bin::Or, data, quiet); + V sd = snan(*this, data); + return this->s.m.select(c, sd, qd, r); +} + +// ---- instructions ---- + +// (Result<(), Stop>) +void Lower::inst(std::size_t b, std::size_t i) { + const Inst& inst = this->x.p->blocks.at(b).insts.at(i); + const std::size_t offset = inst.machine.offset; + const std::string_view name = inst.name(); + this->local_ok = name.starts_with("s_bcnt1_i32_") || name.starts_with("s_ff1_i32_") || + name.starts_with("v_mbcnt_"); + switch (this->mask_data) { + case MaskData::Console: + this->mask_ok = true; + break; + case MaskData::Host: + this->mask_ok = name.starts_with("s_bcnt1_i32_") || name.starts_with("s_ff1_i32_") || + name.starts_with("v_mbcnt_") || name == "s_cmp_eq_u32" || name == "s_cmp_lg_u32" || + name == "s_cmp_eq_u64" || name == "s_cmp_lg_u64"; + break; + case MaskData::None: + // Mesh: only "do all lanes hold the first lane's value?" (`uniform_test`), which + // each host wave answers for itself. + this->mask_ok = this->uniform_test(inst); + break; + } + const bool is_ds = std::holds_alternative<gfx10::Ds>(inst.fields); + const bool effect = std::holds_alternative<gfx10::Exp>(inst.fields) || + (std::holds_alternative<gfx10::Flat>(inst.fields) && !name.starts_with("global_load_")) || + contains(name, "store") || contains(name, "atomic") || name == "s_barrier" || + (is_ds && !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || + contains(name, "permute"))); + if (this->split_lds && is_ds && !(name.starts_with("ds_swizzle") || contains(name, "permute")) && + (!this->lds_meet || this->lds_meet->first.at(b))) { + // the two host waves of a console wave meet before each LDS access: what the other + // half wrote is visible, and what it still reads is not overwritten + V mode = this->s.m.i32(meeting_mode()); + const Ty void_t = this->s.t.void_; + this->s.op(this->cur, "barrier", Attr::NoDuplicate, void_t, 80, std::vector<V>{mode}); + } + // The structure builder uses atomics to hand work from one thread to the next as it builds a tree from its + // leaves. The next thread must see writes preceding the previous thread's atomic, including writes ordered + // by console waits. + const bool ordered_ = (name.starts_with("buffer_atomic") || name.starts_with("global_atomic")) && + spill::is_spilled(*this->x.native) && emit::builder_fences(); + if (ordered_) { + this->memory_fence(); + } + std::optional<Why> err; + try { + const Fields& fields = inst.fields; + if (std::holds_alternative<gfx10::Sop>(fields)) { + this->sop(inst); + } else if (std::holds_alternative<gfx10::Sopp>(fields) && name == "s_barrier" && + this->no_barrier.contains(b)) { + } else if (std::holds_alternative<gfx10::Sopp>(fields) && name == "s_barrier") { + // Thread-group sync with a shared-memory fence, and a UAV fence when the program + // writes UAVs (the waits before an s_barrier make those writes visible on the console). + std::uint32_t mode = this->writes_uavs ? (1 | 2 | 8) : (1 | 8); + // Without the wait for the group (bit 0) where not every lane arrives, or where the + // switch says so. + bool waits = false; + switch (emit::group_sync()) { + case 0: + waits = false; + break; + case 1: + waits = !this->fence_only.contains(b); + break; + default: + waits = true; + break; + } + if (!waits) { + mode &= ~1u; + } + V mode_v = this->s.m.i32(mode); + const Ty void_t = this->s.t.void_; + this->s.op(this->cur, "barrier", Attr::NoDuplicate, void_t, 80, std::vector<V>{mode_v}); + } else if (std::holds_alternative<gfx10::Sopp>(fields)) { + } else if (std::holds_alternative<gfx10::Smem>(fields)) { + this->smem(inst, Site{b, i}); + } else if (std::holds_alternative<gfx10::Valu>(fields) && name.starts_with("v_interp_")) { + this->interp(inst, Site{b, i}); + } else if (std::holds_alternative<gfx10::Valu>(fields)) { + this->valu(inst, b, i); + } else if (std::holds_alternative<gfx10::Vintrp>(fields)) { + this->interp(inst, Site{b, i}); + } else if (std::holds_alternative<gfx10::Image>(fields) && name.starts_with("image_bvh")) { + // The ray and node test. A failure is a refusal at once: an instruction without a + // side effect otherwise only stops the program where its results are needed, and + // two trace programs came out without their test that way. + std::optional<Why> bvh_err; + try { + this->bvh(inst, b, i); + } catch (const WhyFail& e) { + bvh_err = e.why; + } + if (bvh_err) unsupported(offset, *bvh_err); + return; + } else if (std::holds_alternative<gfx10::Image>(fields)) { + this->image(inst, b, i); + } else if (std::holds_alternative<gfx10::Buffer>(fields)) { + this->buffer(inst, b, i); + } else if (std::holds_alternative<gfx10::Exp>(fields)) { + this->export_(b, i); + } else if (is_ds) { + this->ds(inst, b, i); + } else if (std::holds_alternative<gfx10::Flat>(fields) && name.starts_with("global_")) { + this->flat(inst, b, i); + } else { + fail("flat memory"); + } + } catch (const WhyFail& e) { + err = e.why; + } + if (ordered_ && !err) { + this->memory_fence(); + } + if (!err) return; + if (effect) unsupported(offset, *err); + for (const auto& w : inst.writes) { + this->vals.insert_or_assign(w.second, Val::Missing(*err)); + } +} + +// Writes to buffers made before are seen, by every group, before those made after. +void Lower::memory_fence() { + V mode = this->s.m.i32(2); + const Ty void_t = this->s.t.void_; + this->s.op(this->cur, "barrier", Attr::NoDuplicate, void_t, 80, std::vector<V>{mode}); +} + +// The two host waves of a console wave meet (a group barrier with a shared-memory fence): LDS +// writes before are seen by reads after. +void Lower::lds_meeting() { + V mode = this->s.m.i32(meeting_mode()); + const Ty void_t = this->s.t.void_; + this->s.op(this->cur, "barrier", Attr::NoDuplicate, void_t, 80, std::vector<V>{mode}); +} + +// Whether `v` is a register no program reads as a number: a descriptor dword without a host value +// (stale), a lane mask's dword (outside compute, where a ballot gives the mask as data), or a join +// of only such values. Compiled code joins numbers with numbers: where one of these meets numbers +// at a join, the register is dead on that path. +bool Lower::dead(Value v, std::vector<Value>& seen) const { + if (this->stale.contains(v)) { + return true; + } + const Structured& st = *this->x.st; + if (this->mask_data != MaskData::Console && (st.masks.contains(v) || st.highs.contains(v))) { + return true; + } + auto it = this->phi_at.find(v); + if (it == this->phi_at.end()) { + return false; + } + const auto [b, i] = it->second; + if (std::find(seen.begin(), seen.end(), v) != seen.end()) { + return true; + } + seen.push_back(v); + for (const Value& a : this->x.p->blocks.at(b).phis.at(i).args) { + if (!this->dead(a, seen)) return false; + } + return true; +} + +// `s_bcnt1_i32_b*` of the lanes that differ from the first lane's value: `v_readfirstlane_b32 s, +// v`, `v_cmp_eq_u32 m, s, v`, `s_xor_b* d, m, exec`. The compiler tests a value for being the same +// in the whole wave this way, to take a scalar path; both paths give each lane the same result, so +// the lanes of a host wave may ask it of their own first lane, whatever the wave's size. +bool Lower::uniform_test(const Inst& inst) const { + const Program& p = *this->x.p; + auto writer = [&](std::optional<Value> v) -> const Inst* { + if (!v) return nullptr; + auto it = this->def_block.find(*v); + if (it == this->def_block.end()) return nullptr; + for (const Inst& i : p.blocks.at(it->second).insts) { + for (const auto& w : i.writes) { + if (w.second == *v) return &i; + } + } + return nullptr; + }; + auto scalar = [](const Inst& i, const Operand& op) -> std::optional<Value> { + if (op.kind == Operand::Kind::Scalar && op.code != gfx10::NULL_CODE && op.code != ir::EXEC) { + return i.read(Reg::S(op.code)); + } + return std::nullopt; + }; + if (!inst.name().starts_with("s_bcnt1_i32_")) { + return false; + } + const auto* sop = std::get_if<gfx10::Sop>(&inst.fields); + if (!sop) { + return false; + } + const Inst* xr = sop->src.empty() ? nullptr : writer(scalar(inst, sop->src[0])); + if (!xr) { + return false; + } + const auto* xsop = std::get_if<gfx10::Sop>(&xr->fields); + if (!xsop) { + return false; + } + const std::string_view xname = xr->name(); + bool has_exec = false; + for (const Operand& o : xsop->src) { + if (o.kind == Operand::Kind::Scalar && o.code == ir::EXEC) { + has_exec = true; + break; + } + } + if (!(xname == "s_xor_b64" || xname == "s_xor_b32") || !has_exec) { + return false; + } + std::optional<Value> cmp_v; + for (const Operand& o : xsop->src) { + if (auto v = scalar(*xr, o)) { + cmp_v = v; + break; + } + } + const Inst* cmp = writer(cmp_v); + if (!cmp) { + return false; + } + const auto* f = std::get_if<gfx10::Valu>(&cmp->fields); + if (!f) { + return false; + } + const std::string_view cname = cmp->name(); + if (!(cname == "v_cmp_eq_u32" || cname == "v_cmp_eq_i32") || f->sdwa.has_value() || f->dpp.has_value()) { + return false; + } + std::optional<Value> lanes; + for (const Operand& o : f->src) { + if (o.kind == Operand::Kind::Vector) { + if (auto v = cmp->read(Reg::V(o.reg))) { + lanes = v; + break; + } + } + } + std::optional<Value> first_v; + for (const Operand& o : f->src) { + if (auto v = scalar(*cmp, o)) { + first_v = v; + break; + } + } + const Inst* fl = writer(first_v); + if (!lanes.has_value() || !fl) { + return false; + } + if (fl->name() != "v_readfirstlane_b32") { + return false; + } + const auto* g = std::get_if<gfx10::Valu>(&fl->fields); + if (!g || g->src.empty() || g->src[0].kind != Operand::Kind::Vector) { + return false; + } + return fl->read(Reg::V(g->src[0].reg)) == lanes; +} + +bool Lower::is_mask(std::optional<Value> v) const { + return v.has_value() && this->x.st->masks.contains(*v); +} + +void Lower::sop(const Inst& inst) { + const auto& f = std::get<gfx10::Sop>(inst.fields); + const auto& dst = f.dst; + const auto& src = f.src; + const auto& imm = f.imm; + const std::string_view name = inst.name(); + const std::optional<Value> scc = inst.write(Reg::Scc); + std::optional<std::uint8_t> dst_code; + if (dst && dst->kind == Operand::Kind::Scalar) dst_code = dst->code; + const std::optional<Value> lo = dst_code ? inst.write(Reg::S(*dst_code)) : std::nullopt; + if (inst.write(Reg::S(ir::EXEC)).has_value() || this->is_mask(lo)) { + fail(LANE_MASK); + } + if (name == "s_setreg_imm32_b32" || name == "s_setreg_b32" || name == "s_swappc_b64" || name == "s_version" || + name.starts_with("s_waitcnt")) { + // shortcut: the float MODE register is not modelled; s_swappc_b64 is the + // vertex fetch call, whose results arrive as inputs. + fail("a register the emitter does not model"); + } + if (name == "s_getpc_b64") { + // The address of the next instruction is no number the host has: tables in the code are + // read by their tracked address. As a number the counter is that instruction's offset in + // the code, so an address paths join before one load is the byte in the code, whichever + // table each path took (resource tracking gives such a join as the computed term, with no + // base). + V z = this->s.m.i32(0); + V at = this->s.m.i32(std::uint32_t(inst.machine.offset) + 4); + const std::optional<Value> hi = + dst_code ? inst.write(Reg::S(std::uint8_t(*dst_code + 1))) : std::nullopt; + this->set(lo, Val::I32(at)); + this->set(hi, Val::I32(z)); + return; + } + const std::size_t c = this->cur; + auto src32 = [&](Lower& l, std::size_t k) -> V { + // SOPK arithmetic reads its destination as the first source. + if (k == 0 && (name == "s_addk_i32" || name == "s_mulk_i32")) { + const Operand d = ok_or(dst, "a missing operand"); + return l.operand(inst, d); + } + const Operand* op = ok_or(k < src.size() ? &src[k] : nullptr, "a missing operand"); + return l.operand(inst, *op); + }; + auto sext16 = [&](Lower& l) { + return l.s.m.i32(std::uint32_t(std::int32_t(std::int16_t(imm.value_or(0))))); + }; + // Dword `h` of 64-bit source `k` (inline constants sign-extend). + auto half = [&](Lower& l, std::size_t k, std::uint8_t h) -> V { + const Operand* op = k < src.size() ? &src[k] : nullptr; + if (op && op->kind == Operand::Kind::Scalar && op->code != gfx10::NULL_CODE) { + Value v = ok_or(inst.read(Reg::S(std::uint8_t(op->code + h))), "an unread operand"); + return l.i32_of(v); + } + if (op && h == 0) { + return l.operand(inst, *op); + } + if (op && op->kind == Operand::Kind::Const) { + std::uint32_t x = ok_or(resource::inline_constant(op->code), "a special operand"); + return l.s.m.i32(std::int32_t(x) < 0 ? 0xFFFF'FFFFu : 0u); + } + // Of a signed operand, a literal sign-extends too. + if (op && op->kind == Operand::Kind::Literal && name.ends_with("_i64")) { + return l.s.m.i32(std::int32_t(op->literal) < 0 ? 0xFFFF'FFFFu : 0u); + } + return l.s.m.i32(0); + }; + if (name.starts_with("s_bitcmp")) { + const std::string_view op = name.substr(std::string_view("s_bitcmp").size()); + // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form) + // of src0 is clear (bitcmp0) or set (bitcmp1). + V bit = src32(*this, 1); + V k31 = this->s.m.i32(31); + V idx = this->s.m.bin(c, Bin::And, bit, k31); + V word{}; + if (op.ends_with("_b64")) { + V a = half(*this, 0, 0); + V b = half(*this, 0, 1); + V k32 = this->s.m.i32(32); + V upper = this->s.m.bin(c, Bin::And, bit, k32); + V z = this->s.m.i32(0); + upper = this->s.m.cmp(c, pred::NE, upper, z); + word = this->s.m.select(c, upper, b, a); + } else { + word = src32(*this, 0); + } + V shifted = this->s.m.bin(c, Bin::LShr, word, idx); + V one = this->s.m.i32(1); + V tested = this->s.m.bin(c, Bin::And, shifted, one); + V want = this->s.m.i32(op.starts_with('1') ? 1u : 0u); + V r = this->s.m.cmp(c, pred::EQ, tested, want); + this->set(scc, Val::Bit(r)); + return; + } + if (name.starts_with("s_cmp_") && name.substr(6).ends_with("_u64")) { + const std::string_view op = name.substr(6); + // eq and lg only: both dwords. + std::optional<V> r; + for (std::uint8_t h = 0; h < 2; ++h) { + V a = half(*this, 0, h); + V b = half(*this, 1, h); + V e = this->s.m.cmp(c, pred::EQ, a, b); + if (r) { + r = this->s.m.bin(c, Bin::And, *r, e); + } else { + r = e; + } + } + V rr = *r; // two dwords + if (op.starts_with("lg")) { + V t = this->s.m.bool_(true); + rr = this->s.m.bin(c, Bin::Xor, rr, t); + } + this->set(scc, Val::Bit(rr)); + return; + } + if (name.starts_with("s_cmp_") || name.starts_with("s_cmpk_")) { + const std::string_view op = name.starts_with("s_cmp_") ? name.substr(6) : name.substr(7); + V a{}; + V b{}; + if (name.starts_with("s_cmpk_")) { + if (op.ends_with("_i32")) { + b = sext16(*this); + } else { + b = this->s.m.i32(std::uint32_t(imm.value_or(0))); + } + a = src32(*this, 0); + } else { + if (op.ends_with("64")) { + fail("a 64-bit scalar compare"); + } + a = src32(*this, 0); + b = src32(*this, 1); + } + const bool signed_ = op.ends_with("_i32"); + const std::string_view two = op.substr(0, 2); + std::uint8_t pr = 0; + if (two == "eq") { + pr = pred::EQ; + } else if (two == "lg") { + pr = pred::NE; + } else if (two == "gt" && signed_) { + pr = pred::SGT; + } else if (two == "ge" && signed_) { + pr = pred::SGE; + } else if (two == "lt" && signed_) { + pr = pred::SLT; + } else if (two == "le" && signed_) { + pr = pred::SLE; + } else if (two == "gt") { + pr = pred::IUGT; + } else if (two == "ge") { + pr = pred::IUGE; + } else if (two == "lt") { + pr = pred::IULT; + } else if (two == "le") { + pr = pred::IULE; + } else { + fail("a scalar compare"); + } + V r = this->s.m.cmp(c, pr, a, b); + this->set(scc, Val::Bit(r)); + return; + } + const bool wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64"); + if (wide) { + const std::optional<Value> hi = + dst_code ? inst.write(Reg::S(std::uint8_t(*dst_code + 1))) : std::nullopt; + auto nonzero = [&](Lower& l, V a, V b) { + V o = l.s.m.bin(c, Bin::Or, a, b); + V z = l.s.m.i32(0); + return l.s.m.cmp(c, pred::NE, o, z); + }; + if (name == "s_quadmask_b64") { + V a = half(*this, 0, 0); + V b = half(*this, 0, 1); + V low = this->quad_mask(a); + V high = this->quad_mask(b); + V k8 = this->s.m.i32(8); + high = this->s.m.bin(c, Bin::Shl, high, k8); + V mask = this->s.m.bin(c, Bin::Or, low, high); + V zero = this->s.m.i32(0); + this->set(lo, Val::I32(mask)); + this->set(hi, Val::I32(zero)); + V nz = this->s.m.cmp(c, pred::NE, mask, zero); + this->set(scc, Val::Bit(nz)); + return; + } + if (name == "s_bcnt1_i32_b64") { + V a = half(*this, 0, 0); + V b = half(*this, 0, 1); + const Ty i32t = this->s.t.i32; + V na = this->s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, std::vector<V>{a}); + V nb = this->s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, std::vector<V>{b}); + V r = this->s.m.bin(c, Bin::Add, na, nb); + this->set(lo, Val::I32(r)); + V z = this->s.m.i32(0); + V sv = this->s.m.cmp(c, pred::NE, r, z); + this->set(scc, Val::Bit(sv)); + return; + } + if (name == "s_ff1_i32_b64") { + // The lowest set bit; -1 for none (as DXIL's first bit low). + V a = half(*this, 0, 0); + V b = half(*this, 0, 1); + const Ty i32t = this->s.t.i32; + V fa = this->s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, std::vector<V>{a}); + V fb = this->s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, std::vector<V>{b}); + V z = this->s.m.i32(0); + V k32 = this->s.m.i32(32); + V fb32 = this->s.m.bin(c, Bin::Add, fb, k32); + V none = this->s.m.cmp(c, pred::EQ, b, z); + fb = this->s.m.select(c, none, fb, fb32); + V low = this->s.m.cmp(c, pred::NE, a, z); + V r = this->s.m.select(c, low, fa, fb); + this->set(lo, Val::I32(r)); + return; + } + if (name == "s_and_b64" || name == "s_or_b64" || name == "s_xor_b64" || name == "s_andn2_b64" || + name == "s_orn2_b64" || name == "s_nand_b64" || name == "s_nor_b64" || name == "s_xnor_b64" || + name == "s_not_b64") { + V ones = this->s.m.i32(0xFFFF'FFFFu); + std::vector<V> r; + for (std::uint8_t h = 0; h < 2; ++h) { + V a = half(*this, 0, h); + V x{}; + if (name == "s_not_b64") { + x = this->s.m.bin(c, Bin::Xor, a, ones); + } else { + V b = half(*this, 1, h); + if (contains(name, "n2")) { + b = this->s.m.bin(c, Bin::Xor, b, ones); + } + const std::string_view mid = name.substr(2, 3); + Bin op = Bin::Xor; + if (mid == "and" || mid == "nan") { + op = Bin::And; + } else if (mid == "or_" || mid == "orn" || mid == "nor") { + op = Bin::Or; + } + x = this->s.m.bin(c, op, a, b); + if (name == "s_nand_b64" || name == "s_nor_b64" || name == "s_xnor_b64") { + x = this->s.m.bin(c, Bin::Xor, x, ones); + } + } + r.push_back(x); + } + this->set(lo, Val::I32(r[0])); + this->set(hi, Val::I32(r[1])); + V sv = nonzero(*this, r[0], r[1]); + this->set(scc, Val::Bit(sv)); + return; + } + if (name == "s_lshl_b64" || name == "s_lshr_b64" || name == "s_ashr_i64") { + V a = half(*this, 0, 0); + V b = half(*this, 0, 1); + V n = src32(*this, 1); + const Ty i64t = this->s.m.int_(64); + this->s.flags |= flags::INT64; + a = this->s.m.cast(c, Cast::ZExt, a, i64t); + b = this->s.m.cast(c, Cast::ZExt, b, i64t); + V k32 = this->s.m.int_const(i64t, 32); + b = this->s.m.bin(c, Bin::Shl, b, k32); + V x = this->s.m.bin(c, Bin::Or, a, b); + V k63 = this->s.m.i32(63); + n = this->s.m.bin(c, Bin::And, n, k63); + n = this->s.m.cast(c, Cast::ZExt, n, i64t); + Bin op = Bin::AShr; + if (name == "s_lshl_b64") { + op = Bin::Shl; + } else if (name == "s_lshr_b64") { + op = Bin::LShr; + } + V r = this->s.m.bin(c, op, x, n); + V rl = this->s.m.cast(c, Cast::Trunc, r, this->s.t.i32); + V rh = this->s.m.bin(c, Bin::LShr, r, k32); + rh = this->s.m.cast(c, Cast::Trunc, rh, this->s.t.i32); + this->set(lo, Val::I32(rl)); + this->set(hi, Val::I32(rh)); + V sv = nonzero(*this, rl, rh); + this->set(scc, Val::Bit(sv)); + return; + } + if (name == "s_mov_b64") { + // Each half by itself: two numbers that travel as a pair (two scalars parked in + // neighbouring VGPR lanes, say) need not both have a value. + const std::pair<std::uint8_t, std::optional<Value>> both[2] = {{0, lo}, {1, hi}}; + for (const auto& [h, v] : both) { + Val val{}; + try { + val = Val::I32(half(*this, 0, h)); + } catch (const WhyFail& e) { + val = Val::Missing(e.why); + } + this->set(v, val); + } + return; + } + if (name == "s_cselect_b64") { + V cond = this->scc_in(inst); + const std::pair<std::uint8_t, std::optional<Value>> both[2] = {{0, lo}, {1, hi}}; + for (const auto& [h, v] : both) { + V a = half(*this, 0, h); + V b = half(*this, 1, h); + V r = this->s.m.select(c, cond, a, b); + this->set(v, Val::I32(r)); + } + return; + } + fail(name.data()); + } + V r{}; + std::optional<V> carry; + if (name == "s_mov_b32") { + r = src32(*this, 0); + } else if (name == "s_movk_i32") { + r = sext16(*this); + } else if (name == "s_quadmask_b32") { + V pixels = src32(*this, 0); + r = this->quad_mask(pixels); + } else if (name == "s_cselect_b32") { + V cond = this->scc_in(inst); + V a = src32(*this, 0); + V b = src32(*this, 1); + r = this->s.m.select(c, cond, a, b); + } else if (name == "s_brev_b32") { + V a = src32(*this, 0); + r = this->s.op(c, "unary.i32", Attr::ReadNone, this->s.t.i32, 30, std::vector<V>{a}); + } else if (name == "s_not_b32") { + V a = src32(*this, 0); + V ones = this->s.m.i32(0xFFFF'FFFFu); + r = this->s.m.bin(c, Bin::Xor, a, ones); + } else if (name == "s_add_u32" || name == "s_add_i32" || name == "s_addk_i32") { + V a = src32(*this, 0); + V b = name == "s_addk_i32" ? sext16(*this) : src32(*this, 1); + r = this->s.m.bin(c, Bin::Add, a, b); + if (name == "s_add_u32") { + carry = this->s.m.cmp(c, pred::IULT, r, a); + } + } else if (name == "s_sub_u32" || name == "s_sub_i32") { + V a = src32(*this, 0); + V b = src32(*this, 1); + r = this->s.m.bin(c, Bin::Sub, a, b); + if (name == "s_sub_u32") { + carry = this->s.m.cmp(c, pred::IULT, a, b); + } + } else if (name == "s_addc_u32" || name == "s_subb_u32") { + V a = src32(*this, 0); + V b = src32(*this, 1); + V cin = this->scc_in(inst); + auto [rr, cc] = this->add_sub_carry(c, name == "s_addc_u32", a, b, cin); + r = rr; + carry = cc; + } else if (name == "s_mul_i32" || name == "s_mulk_i32") { + V a = src32(*this, 0); + V b = name == "s_mulk_i32" ? sext16(*this) : src32(*this, 1); + r = this->s.m.bin(c, Bin::Mul, a, b); + } else if (name == "s_mul_hi_u32" || name == "s_mul_hi_i32") { + V a = src32(*this, 0); + V b = src32(*this, 1); + r = this->mul_hi(a, b, name.ends_with("i32")); + } else if (name == "s_flbit_i32_b32" || name == "s_flbit_i32") { + // The first bit from the top (differing from the sign for the signed form), -1 for none: + // DXIL's first-bit-high. + V a = src32(*this, 0); + const std::uint32_t op = name == "s_flbit_i32_b32" ? 33 : 34; + r = this->s.op(c, "unaryBits.i32", Attr::ReadNone, this->s.t.i32, op, std::vector<V>{a}); + } else if (name == "s_ff1_i32_b32" || name == "s_bcnt1_i32_b32") { + // First set bit (-1 for zero, as DXIL's), or the bit count. + V a = src32(*this, 0); + const std::uint32_t op = name == "s_ff1_i32_b32" ? 32 : 31; + r = this->s.op(c, "unaryBits.i32", Attr::ReadNone, this->s.t.i32, op, std::vector<V>{a}); + } else if (name == "s_bfe_u32" || name == "s_bfe_i32") { + // src1: offset in bits 0-4, width in bits 16-22. + V a = src32(*this, 0); + V b = src32(*this, 1); + V k16 = this->s.m.i32(16); + V k127 = this->s.m.i32(0x7F); + V w = this->s.m.bin(c, Bin::LShr, b, k16); + w = this->s.m.bin(c, Bin::And, w, k127); + r = this->bfe(a, b, w, name == "s_bfe_i32"); + } else if (name == "s_and_b32" || name == "s_or_b32" || name == "s_xor_b32" || name == "s_andn2_b32" || + name == "s_orn2_b32" || name == "s_nand_b32" || name == "s_nor_b32" || name == "s_xnor_b32") { + V a = src32(*this, 0); + V b = src32(*this, 1); + V ones = this->s.m.i32(0xFFFF'FFFFu); + if (contains(name, "n2")) { + b = this->s.m.bin(c, Bin::Xor, b, ones); + } + const std::string_view mid = name.substr(2, 3); + Bin op = Bin::Xor; + if (mid == "and" || mid == "nan") { + op = Bin::And; + } else if (mid == "or_" || mid == "orn" || mid == "nor") { + op = Bin::Or; + } + r = this->s.m.bin(c, op, a, b); + if (name == "s_nand_b32" || name == "s_nor_b32" || name == "s_xnor_b32") { + r = this->s.m.bin(c, Bin::Xor, r, ones); + } + } else if (name == "s_lshl_b32" || name == "s_lshr_b32" || name == "s_ashr_i32") { + V a = src32(*this, 0); + V b = src32(*this, 1); + V k31 = this->s.m.i32(31); + b = this->s.m.bin(c, Bin::And, b, k31); + Bin op = Bin::AShr; + if (name == "s_lshl_b32") { + op = Bin::Shl; + } else if (name == "s_lshr_b32") { + op = Bin::LShr; + } + r = this->s.m.bin(c, op, a, b); + } else if (name == "s_lshl1_add_u32" || name == "s_lshl2_add_u32" || name == "s_lshl3_add_u32" || + name == "s_lshl4_add_u32") { + V a = src32(*this, 0); + V b = src32(*this, 1); + V k = this->s.m.i32(std::uint32_t(std::uint8_t(name[6]) - std::uint8_t('0'))); + V t = this->s.m.bin(c, Bin::Shl, a, k); + r = this->s.m.bin(c, Bin::Add, t, b); + } else if (name == "s_min_u32" || name == "s_max_u32" || name == "s_min_i32" || name == "s_max_i32") { + V a = src32(*this, 0); + V b = src32(*this, 1); + std::uint8_t pr = pred::SGT; + if (name == "s_min_u32") { + pr = pred::IULT; + } else if (name == "s_max_u32") { + pr = pred::IUGT; + } else if (name == "s_min_i32") { + pr = pred::SLT; + } + V t = this->s.m.cmp(c, pr, a, b); + r = this->s.m.select(c, t, a, b); + } else if (name == "s_abs_i32") { + V a = src32(*this, 0); + V z = this->s.m.i32(0); + V neg = this->s.m.cmp(c, pred::SLT, a, z); + V n = this->s.m.bin(c, Bin::Sub, z, a); + r = this->s.m.select(c, neg, n, a); + } else if (name == "s_bitset0_b32" || name == "s_bitset1_b32") { + // Sets (clears) bit src[4:0] of the destination it reads. + const Operand d = ok_or(dst, "a missing operand"); + V old = this->operand(inst, d); + V a = src32(*this, 0); + V k31 = this->s.m.i32(31); + V one = this->s.m.i32(1); + a = this->s.m.bin(c, Bin::And, a, k31); + V bit = this->s.m.bin(c, Bin::Shl, one, a); + if (name == "s_bitset1_b32") { + r = this->s.m.bin(c, Bin::Or, old, bit); + } else { + V ones = this->s.m.i32(0xFFFF'FFFFu); + V nb = this->s.m.bin(c, Bin::Xor, bit, ones); + r = this->s.m.bin(c, Bin::And, old, nb); + } + } else if (name == "s_bfm_b32") { + V a = src32(*this, 0); + V b = src32(*this, 1); + V k31 = this->s.m.i32(31); + V one = this->s.m.i32(1); + a = this->s.m.bin(c, Bin::And, a, k31); + b = this->s.m.bin(c, Bin::And, b, k31); + V m = this->s.m.bin(c, Bin::Shl, one, a); + m = this->s.m.bin(c, Bin::Sub, m, one); + r = this->s.m.bin(c, Bin::Shl, m, b); + } else { + fail(name.data()); + } + this->set(lo, Val::I32(r)); + if (scc) { + Val val{}; + if (carry) { + val = Val::Bit(*carry); + } else if (name == "s_mov_b32" || name == "s_movk_i32" || name == "s_cselect_b32" || name == "s_brev_b32" || + name == "s_mul_i32" || name == "s_mulk_i32") { + return; + } else if (name.starts_with("s_add") || name.starts_with("s_sub")) { + val = Val::Missing("the carry of a scalar operation"); + } else { + V z = this->s.m.i32(0); + val = Val::Bit(this->s.m.cmp(c, pred::NE, r, z)); + } + this->vals.insert_or_assign(*scc, val); + } +} + +// Packs whether each consecutive group of four pixels has a set bit. +V Lower::quad_mask(V pixels) { + const std::size_t c = this->cur; + V one = this->s.m.i32(1); + V shifted = this->s.m.bin(c, Bin::LShr, pixels, one); + V mask = this->s.m.bin(c, Bin::Or, pixels, shifted); + // Fold each nibble into its bottom bit, then gather those bits into the low byte in three + // stages without needing a 64-bit operation. + const std::pair<std::uint32_t, std::uint32_t> steps[4] = { + {2, 0x1111'1111u}, + {3, 0x0303'0303u}, + {6, 0x000f'000fu}, + {12, 0x0000'00ffu}, + }; + for (const auto& [dist, keep_bits] : steps) { + V distance = this->s.m.i32(dist); + V sh = this->s.m.bin(c, Bin::LShr, mask, distance); + V combined = this->s.m.bin(c, Bin::Or, mask, sh); + V keep = this->s.m.i32(keep_bits); + mask = this->s.m.bin(c, Bin::And, combined, keep); + } + return mask; +} + +// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the scalar and vector +// add-with-carry instructions set it. +std::pair<V, V> Lower::add_sub_carry(std::size_t c, bool add, V a, V b, std::optional<V> cin) { + const Bin op = add ? Bin::Add : Bin::Sub; + V r = this->s.m.bin(c, op, a, b); + // Without a carry in: a + b wraps below a; a - b borrows when a < b. + V carry = add ? this->s.m.cmp(c, pred::IULT, r, a) : this->s.m.cmp(c, pred::IULT, a, b); + if (cin) { + V one = this->s.m.cast(c, Cast::ZExt, *cin, this->s.t.i32); + V t = r; + r = this->s.m.bin(c, op, t, one); + // The carry in carries on when the partial result is all ones (add) or zero (sub). + V edge = this->s.m.i32(add ? 0xFFFF'FFFFu : 0u); + V at_edge = this->s.m.cmp(c, pred::EQ, t, edge); + V more = this->s.m.bin(c, Bin::And, *cin, at_edge); + carry = this->s.m.bin(c, Bin::Or, carry, more); + } + return {r, carry}; +} + +V Lower::scc_in(const Inst& inst) { + const Value v = ok_or(inst.read(Reg::Scc), "an unread SCC"); + std::optional<Why> err; + Val g{}; + try { + g = this->get(v); + } catch (const WhyFail& e) { + err = e.why; + } + if (err) { + // Of a mask operation whose result lies within EXEC: whether some lane is left. + if (same(*err, LANE_MASK) && this->within_exec(v)) { + return this->scc_some(v); + } + fail(*err); + } + if (g.is_bit()) { + return g.v; + } + fail("SCC without a value"); +} + +// Whether the mask operation that sets the SCC value `scc` gives no lane outside EXEC a bit. +bool Lower::within_exec(Value scc) const { + auto it = this->def_block.find(scc); + if (it == this->def_block.end()) { + return false; + } + const Inst* by = nullptr; + for (const Inst& i : this->x.p->blocks.at(it->second).insts) { + if (i.write(Reg::Scc) == std::optional<Value>(scc)) { + by = &i; + break; + } + } + if (!by) { + return false; + } + if (by->write(Reg::S(ir::EXEC)).has_value()) { + return true; + } + const auto* sop = std::get_if<gfx10::Sop>(&by->fields); + if (sop && sop->dst && sop->dst->kind == Operand::Kind::Scalar) { + if (auto lo = by->write(Reg::S(sop->dst->code))) { + return this->x.st->active.contains(*lo); + } + } + return false; +} + +// Whether the dwords of one console load are read by one call for up to four of them +// (`bitcode::opt::WIDE` of `X2W_SHADERCFG_SHADER_OPT`), not by a call each. +bool Lower::wide_loads() { + return (emit::shader_opt() & opt::WIDE) != 0; +} + +// `count` dwords from byte `addr` on of the raw view `h`, as integers, read in the current block by one +// call for every four of them (wide_loads). They are the dwords of ONE console load, which the console +// reads as one (address plus 4, 8,... without wrapping at 32 bits): the same bytes as a call a dword reads. +// Loads of different console instructions are never joined: the program computes their offsets in 32-bit +// registers, and `x - 4` and `x` at `x = 0` are one dword out of the view and its first one, where one call +// from `x - 4` on would read both out of it. +std::vector<V> Lower::raw_dwords(V h, V addr, std::uint32_t count) { + const std::size_t c = this->cur; + V u = this->s.m.undef(this->s.t.i32); + V al = this->s.m.i32(4); + std::vector<V> out; + out.reserve(count); + for (std::uint32_t first = 0; first < count; first += 4) { + const std::uint32_t n = std::min<std::uint32_t>(count - first, 4); + V off = this->s.m.i32(4 * first); + V a = this->s.m.bin(c, Bin::Add, addr, off); + V mask = this->s.m.i8(std::uint8_t((1u << n) - 1)); + V r = this->s.op(c, "rawBufferLoad.f32", Attr::ReadOnly, this->s.t.res_ret, 139, + std::vector<V>{h, a, u, mask, al}); + for (std::uint32_t k = 0; k < n; ++k) { + V x = this->s.m.extract(c, r, k); + out.push_back(this->as_int(x)); + } + } + return out; +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_free.cpp b/src/x2w_shader/emit/lower_free.cpp new file mode 100644 index 0000000000..15904dadc3 --- /dev/null +++ b/src/x2w_shader/emit/lower_free.cpp @@ -0,0 +1,1269 @@ +// The free functions and per-process / per-thread settings of the lowering. +#include <algorithm> +#include <atomic> +#include <cassert> +#include <cstdlib> +#include <cstdio> +#include <stdexcept> + +#include "x2w_shader/emit/lower_impl.h" +#include "x2w_shader/spill.h" + +namespace x2w::vs::lower { + +namespace { + +// std::env::var_os(name) as text. +std::optional<std::string> env_var(const char* name) { +#ifdef _MSC_VER +#pragma warning(suppress : 4996) +#endif + const char* v = std::getenv(name); + if (!v) return std::nullopt; + return std::string(v); +} + +// The scalar operands' and an instruction's mask test of lane_uniform / reads_mask_as_data. +bool is_mask_of(const Structured& st, Value v) { + return st.masks.contains(v) || st.highs.contains(v); +} + +} // namespace + +Lowered lower(const Parts& parts) { + bool counted = [&] { + // counted_in_threads: whether the title dispatches the program by a count of threads + // whose last group may be partial: the structure builder's programs of one dimension. + // Their lanes past the count must not run. Not where a group barrier would wait for lanes + // that left, nor where two host waves of 32 stand for a console wave. + const auto* cs = std::get_if<native::ComputeIo>(&parts.native->io); + if (!cs) return false; + if (!(cs->threads[0] > 1 && cs->threads[1] == 1 && cs->threads[2] == 1)) return false; + if (!spill::is_spilled(*parts.native)) return false; + if (!(!parts.native->wave64 || host_max_wave() >= 64)) return false; + for (const auto& b : parts.p->blocks) { + for (const auto& i : b.insts) { + if (i.name() == "s_barrier") return false; + } + } + return true; + }(); + return lower_counted(parts, counted); +} + +namespace { +// VS_DUMP=<dir> writes each lowered module to <dir>/<name>__<n>.dxil. Set the name with +// test::set_dump_name. Each name has its own counter. +thread_local std::string dump_name = "main"; +thread_local std::uint32_t dump_n = 0; +void dump(const std::vector<std::uint8_t>& dxil) { + const char* dir = std::getenv("VS_DUMP"); + if (!dir) return; + std::string path = std::string(dir) + "/" + dump_name + "__" + std::to_string(dump_n++) + ".dxil"; + if (std::FILE* f = std::fopen(path.c_str(), "wb")) { + std::fwrite(dxil.data(), 1, dxil.size(), f); + std::fclose(f); + } +} +} // namespace + +void test::set_dump_name(std::string_view name) { + dump_name.assign(name); + dump_n = 0; +} + +Lowered lower_counted(const Parts& parts, bool counted) { + HashMap<Value, Why> bad; + for (;;) { + try { + Lower l(parts, bad); + Lowered out = l.run(counted); + dump(out.dxil); + return out; + } catch (const StopRetry& r) { + // the value was already missing once. + bool had = bad.contains(r.value); + bad.insert_or_assign(r.value, r.why); + if (had) { + throw ShaderError::unsupported(0, "a phi that does not settle"); + } + } + // Stop::Fail: the ShaderError passes through. + } +} + +// The instructions inside a pixel program's ordered section (primitive-ordered pixel +// shading, which the console compiler makes of rasterizer ordered views): from the write of +// POPS_PACKER, along every path, to the message that ends the section or the program's end. The +// console waits there until the waves holding earlier primitives' samples of the same pixels have +// left their sections; a host's rasterizer ordered views wait by themselves, at their first +// access. Empty for a program without such a section. +HashSet<Site> ordered_section(const Program& p) { + auto starts = [](const Inst& i) { + if (i.name() != "s_setreg_b32") return false; + const auto* sop = std::get_if<gfx10::Sop>(&i.fields); + return sop && sop->imm && (*sop->imm & 0x3F) == POPS_PACKER; + }; + auto ends = [](const Inst& i) { + if (i.name() != "s_sendmsg") return false; + const auto* sopp = std::get_if<gfx10::Sopp>(&i.fields); + return sopp && (sopp->imm & 0xF) == ORDERED_PS_DONE; + }; + HashSet<Site> section; + std::vector<bool> entered(p.blocks.size(), false); + std::vector<Site> work; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& block = p.blocks[b]; + for (std::size_t i = 0; i < block.insts.size(); ++i) { + if (starts(block.insts[i])) work.push_back({b, i}); + } + } + while (!work.empty()) { + auto [b, from] = work.back(); + work.pop_back(); + const auto& block = p.blocks[b]; + bool done = false; + for (std::size_t i = from; i < block.insts.size(); ++i) { + if (ends(block.insts[i])) { + done = true; + break; + } + section.insert({b, i}); + } + if (done) continue; + for (std::size_t t = 0; t < p.blocks.size(); ++t) { + const auto& next = p.blocks[t]; + bool pred = std::find(next.preds.begin(), next.preds.end(), b) != next.preds.end(); + if (pred && !entered[t]) { // !std::mem::replace(&mut entered[t], true) + entered[t] = true; + work.push_back({t, 0}); + } + } + } + return section; +} + +// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0, -1.0, 2.0, -2.0, +// 4.0, -4.0, 1/(2 pi)). +std::uint32_t inline_f16(std::uint8_t c) { + static constexpr std::array<std::uint32_t, 9> K = {0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, + 0xC000, 0x4400, 0xC400, 0x3118}; + return K.at(static_cast<std::size_t>(c - 240)); +} + +// A GFX10 buffer format (the unified format of typed buffer loads): the channel widths from the lowest bits +// up, and how the channels convert. Formats are numbered in families (`8`, `16`, `8_8`,...: AMD names list +// channels from the highest bits), each with its numeric formats in the order unorm, snorm, uscaled, +// sscaled, uint, sint, float. +std::optional<std::pair<std::span<const std::uint32_t>, Numeric>> buffer_format(std::uint8_t format) { + using N = Numeric; + static constexpr N NORM[] = {N::Unorm, N::Snorm, N::Uscaled, N::Sscaled, N::Uint, N::Sint}; + static constexpr N ALL[] = {N::Unorm, N::Snorm, N::Uscaled, N::Sscaled, N::Uint, N::Sint, N::Float}; + static constexpr N WIDE[] = {N::Uint, N::Sint, N::Float}; + // Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10 buffer formats have no + // 5_9_9_9. Channel order from Mesa (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and + // 10_10_10_2 has its 2-bit channel in the lowest bits. + static constexpr std::uint32_t B8[] = {8}; + static constexpr std::uint32_t B16[] = {16}; + static constexpr std::uint32_t B8_8[] = {8, 8}; + static constexpr std::uint32_t B32[] = {32}; + static constexpr std::uint32_t B16_16[] = {16, 16}; + static constexpr std::uint32_t B10_11_11[] = {11, 11, 10}; // 10_11_11 + static constexpr std::uint32_t B11_11_10[] = {10, 11, 11}; // 11_11_10 + static constexpr std::uint32_t B10_10_10_2[] = {2, 10, 10, 10}; // 10_10_10_2 + static constexpr std::uint32_t B2_10_10_10[] = {10, 10, 10, 2}; // 2_10_10_10 + static constexpr std::uint32_t B8_8_8_8[] = {8, 8, 8, 8}; + static constexpr std::uint32_t B32_32[] = {32, 32}; + static constexpr std::uint32_t B16x4[] = {16, 16, 16, 16}; + static constexpr std::uint32_t B32x3[] = {32, 32, 32}; + static constexpr std::uint32_t B32x4[] = {32, 32, 32, 32}; + struct Family { + std::span<const std::uint32_t> bits; + std::span<const N> numerics; + }; + static const Family FAMILIES[14] = { + {B8, NORM}, {B16, ALL}, {B8_8, NORM}, {B32, WIDE}, + {B16_16, ALL}, {B10_11_11, ALL}, {B11_11_10, ALL}, {B10_10_10_2, NORM}, + {B2_10_10_10, NORM}, {B8_8_8_8, NORM}, {B32_32, WIDE}, {B16x4, ALL}, + {B32x3, WIDE}, {B32x4, WIDE}, + }; + if (format == 0) return std::nullopt; // format.checked_sub(1)? + std::size_t n = static_cast<std::size_t>(format - 1); + for (const auto& f : FAMILIES) { + if (n < f.numerics.size()) { + return std::pair{f.bits, f.numerics[n]}; + } + n -= f.numerics.size(); + } + return std::nullopt; +} + +// How far a float channel of `width` bits (16, or the unsigned 11- and 10-bit floats of the +// packed formats) shifts up to be a half: the small floats are a half's exponent (5 bits, biased 15) +// and the top of its mantissa, without the sign, so `legacyF16ToF32` widens them exactly, +// denormals, infinities and NaNs included. +std::uint32_t half_shift(std::uint32_t width) { + assert((width == 10 || width == 11 || width == 16) && "float width"); + return width == 16 ? 0 : 15 - width; +} + +namespace { + +// Every per-lane branch (by its block) with its region: the blocks reachable from it that do +// not post-dominate it, which only some lanes run. Not the branches the wave takes together +// (Structured::wide), nor those on scalar conditions. None with an indirect exit. +std::optional<std::vector<std::pair<std::size_t, std::vector<bool>>>> lane_regions(const Structured& st) { + const std::size_t n = st.exits.size(); + std::vector<std::vector<std::size_t>> succ(n); + for (std::size_t b = 0; b < n; ++b) { + const auto& e = st.exits[b]; + switch (e.kind) { + case LaneExit::Kind::Jump: + succ[b].push_back(e.target); + break; + case LaneExit::Kind::Branch: + succ[b].push_back(e.taken); + succ[b].push_back(e.not_taken); + break; + case LaneExit::Kind::End: + break; + case LaneExit::Kind::Indirect: + return std::nullopt; + } + } + // post-dominators (bitsets; a virtual exit after every End) + const std::size_t words = div_ceil<std::size_t>(n, 64); + const std::vector<std::uint64_t> full(words, ~std::uint64_t{0}); + std::vector<std::vector<std::uint64_t>> pdom; + pdom.reserve(n); + for (std::size_t b = 0; b < n; ++b) { + if (succ[b].empty()) { + std::vector<std::uint64_t> v(words, 0); + v[b / 64] |= std::uint64_t{1} << (b % 64); + pdom.push_back(std::move(v)); + } else { + pdom.push_back(full); + } + } + bool changed = true; + while (changed) { + changed = false; + for (std::size_t bb = n; bb-- > 0;) { + const std::size_t b = bb; + if (succ[b].empty()) continue; + auto v = full; + for (std::size_t t : succ[b]) { + for (std::size_t w = 0; w < words; ++w) v[w] &= pdom[t][w]; + } + v[b / 64] |= std::uint64_t{1} << (b % 64); + if (v != pdom[b]) { + pdom[b] = std::move(v); + changed = true; + } + } + } + std::vector<std::pair<std::size_t, std::vector<bool>>> regions; + for (std::size_t d = 0; d < n; ++d) { + const auto& e = st.exits[d]; + if (e.kind != LaneExit::Kind::Branch) continue; + bool uniform = true; + for (const auto& a : st.bools.support(e.when)) { + if (a.kind != Atom::Kind::Uniform) { + uniform = false; + break; + } + } + if (st.wide.contains(d) || uniform) { + continue; // a wave-wide or uniform branch: all lanes go the same way + } + // blocks reachable from the lane branch that do not post-dominate it + std::vector<bool> seen(n, false); + std::vector<std::size_t> stack = succ[d]; + while (!stack.empty()) { + std::size_t b = stack.back(); + stack.pop_back(); + if (seen[b] || ((pdom[d][b / 64] >> (b % 64)) & 1) == 1) continue; + seen[b] = true; + stack.insert(stack.end(), succ[b].begin(), succ[b].end()); + } + regions.emplace_back(d, std::move(seen)); + } + return regions; +} + +} // namespace + +// Per IR block: every lane of the wave that started the program runs it – no per-lane +// branch separates it from the entry (it lies in no lane branch's region). None with an indirect +// exit (not followed). +std::optional<std::vector<bool>> all_lane_blocks(const Structured& st) { + const std::size_t n = st.exits.size(); + std::vector<bool> all(n, true); + auto regions = lane_regions(st); + if (!regions) return std::nullopt; + for (const auto& [_, region] : *regions) { + for (std::size_t b = 0; b < n; ++b) { + if (region[b]) all[b] = false; + } + } + return all; +} + +std::optional<std::vector<std::size_t>> branches_around(const Structured& st, + const std::vector<std::size_t>& needs) { + std::vector<std::size_t> out; + auto regions = lane_regions(st); + if (!regions) return std::nullopt; + for (const auto& [d, region] : *regions) { + bool any = false; + for (std::size_t b : needs) { + if (b < region.size() && region[b]) { + any = true; + break; + } + } + if (any) { + // st.wave_any.get(d).copied().flatten()? + if (d >= st.wave_any.size() || !st.wave_any[d].has_value()) return std::nullopt; + out.push_back(d); + } + } + return out; +} + +bool needs_every_lane(std::string_view what) { + return what.ends_with("where not every lane runs") || what == std::string_view(MASK_ELSEWHERE); +} + +namespace { +// thread_local! { NEEDS, LOCAL_WAVES, LOCAL_ANY } +thread_local std::vector<std::size_t> NEEDS; +thread_local bool LOCAL_WAVES = false; +thread_local bool LOCAL_ANY = false; +thread_local bool FIRST_HALF_PAIRS = false; +// Per-thread test choices. +thread_local std::optional<bool> TEST_F16_NEAREST; +thread_local std::optional<std::uint32_t> TEST_RDNA; +thread_local std::optional<std::uint32_t> TEST_HOST_WAVE; +// Test title-memory mapping. +thread_local std::optional<std::pair<std::uint32_t, std::uint64_t>> TEST_MEMORY; + +// The widest wave the host GPU runs (0: not known – no host-specific forms). +std::atomic<std::uint32_t> HOST_MAX_WAVE{0}; +std::atomic<bool> HOST_RDNA{false}; +} // namespace + +std::vector<std::size_t> take_needs() { return std::exchange(NEEDS, {}); } + +void need(std::size_t block) { + if (std::find(NEEDS.begin(), NEEDS.end(), block) == NEEDS.end()) NEEDS.push_back(block); +} + +// VGPR values that are the same in every lane holding them (`all` is all_lane_blocks): +// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars, +// constants and such values; or loaded from an address made of them. The compiler keeps +// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`. +// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes run +// (no lane branch can have split the arriving lanes); loop-carried values never do. +HashSet<Value> lane_uniform(const Program& p, const Structured& st, const std::vector<bool>& all) { + auto is_mask = [&](Value v) { return is_mask_of(st, v); }; + HashSet<Value> same; + for (std::size_t b : ir::reverse_postorder(p.blocks)) { + const auto& block = p.blocks[b]; + bool whole = std::all_of(block.preds.begin(), block.preds.end(), + [&](std::size_t q) { return q < all.size() && all[q]; }); + for (const auto& phi : block.phis) { + if (phi.reg.is_v() && whole && + std::all_of(phi.args.begin(), phi.args.end(), [&](Value a) { return same.contains(a); })) { + same.insert(phi.value); + } + } + for (std::size_t i = 0; i < block.insts.size(); ++i) { + const auto& inst = block.insts[i]; + auto name = inst.name(); + const auto* v = std::get_if<gfx10::Valu>(&inst.fields); + if (!(v && !v->dpp.has_value() && !v->sdwa.has_value() && !name.starts_with("v_mbcnt") && + !name.starts_with("v_cmpx") && name.find("lane") == std::string_view::npos)) { + continue; + } + const std::vector<Operand> ops = v->src; + if (st.guards[b][i].has_value()) { + continue; // lanes outside EXEC keep another value + } + bool alike = std::all_of(ops.begin(), ops.end(), [&](const Operand& op) { + if (op.kind == Operand::Kind::Vector) { + // every dword of the operand the instruction reads from that register on + std::vector<Value> read; + for (const auto& r : inst.reads) { + if (r.first.is_v() && r.first.n >= op.reg) read.push_back(r.second); + } + return !read.empty() && + std::all_of(read.begin(), read.end(), [&](Value x) { return same.contains(x); }); + } + // a scalar is one value; a lane mask is not, unless a compare of such values made it + if (op.kind == Operand::Kind::Scalar && op.code != gfx10::NULL_CODE) { + auto x = inst.read(Reg::S(op.code)); + return !x || !is_mask(*x) || same.contains(*x); + } + return true; + }); + if (alike) { + for (const auto& w : inst.writes) { + if (w.first != Reg::Scc) same.insert(w.second); + } + } + } + } + return same; +} + +namespace { + +// What a register value holds, for wave_local. +struct Wave { + enum class Kind : std::uint8_t { + // Nothing that depends on how the threads are divided into waves. + Plain, + // The number of the wave's first lane in a mask (`s_ff1`). + First, + // A reduction over the wave's lanes: a count, a sum, a minimum... + Total, + // A count or sum over the lanes below this one. + Prefix, + // Derived from what a first-lane atomic returned: the slots the wave reserved. + Base, + // A mix the idiom does not make. + Mixed, + }; + Kind kind = Kind::Plain; + wave::Op op = wave::Op::AddU; // Used only for Total. Other operation kinds retain the default. + + static constexpr Wave of(Kind k) { return Wave{k, wave::Op::AddU}; } + static constexpr Wave total(wave::Op o) { return Wave{Kind::Total, o}; } + constexpr bool operator==(const Wave&) const = default; +}; +constexpr Wave PLAIN = Wave::of(Wave::Kind::Plain); +constexpr Wave FIRST_W = Wave::of(Wave::Kind::First); +constexpr Wave PREFIX_W = Wave::of(Wave::Kind::Prefix); +constexpr Wave BASE_W = Wave::of(Wave::Kind::Base); +constexpr Wave MIXED_W = Wave::of(Wave::Kind::Mixed); + +} // namespace + +// Whether a console wave64 program may run with each host wave as a wave of its own +// (with_local_waves): its wave-wide values are used only as the allocation idiom uses them, which +// does not care how the threads are divided into waves. A first-lane number only picks the first +// lane; a count or sum only goes into that lane's atomic on a shared counter; a prefix only goes +// onto the base that atomic returned; the first lane does nothing else. Anything else done with +// them takes one wave to be the whole thread group (a tile's result, say) and is refused, with the +// offset and what was found. Lane masks read as numbers by other instructions and lane reads +// outside whole-wave sections are stopped by the lowering itself. +// shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this host +// wave's first lane), and a guarded write of a plain value over a wave-dependent one is the only +// mix of old and new lanes that is looked at. +std::optional<std::pair<std::size_t, Why>> wave_local(const Program& p, const Structured& st) { + using wave::Op; + using K = Wave::Kind; + static constexpr Why FIRST = "a wave's first-lane number used as data"; + static constexpr Why TOTAL = "a count or sum over the wave used as data"; + static constexpr Why PREFIX = "a count or sum over the lanes below used without a reserved base"; + static constexpr Why MIXED = "a value that depends on the wave on some paths only"; + static constexpr Why EFFECT = "a write by the wave's first lane other than its reservation"; + using KindMap = HashMap<Value, Wave>; + auto of = [](const KindMap& kind, std::optional<Value> v) -> Wave { + if (!v) return PLAIN; + auto it = kind.find(*v); + return it == kind.end() ? PLAIN : it->second; + }; + auto put = [](KindMap& kind, Value v, Wave k) { + if (k == PLAIN) { + kind.erase(v); + } else { + kind.insert_or_assign(v, k); + } + }; + auto wild = [](Wave k) { return !(k.kind == K::Plain || k.kind == K::Base); }; + auto why = [](Wave k) -> Why { + switch (k.kind) { + case K::First: + return FIRST; + case K::Total: + return TOTAL; + case K::Prefix: + return PREFIX; + default: + return MIXED; + } + }; + // a mask (by its low dword) under which only a wave's first lane runs + auto first_mask = [&](const HashSet<Value>& firsts, std::optional<Value> m) { + if (!m) return false; + auto it = st.masks.find(*m); + if (it == st.masks.end()) return false; + for (const auto& a : st.bools.support(it->second)) { + if (a.kind == Atom::Kind::Lane && firsts.contains(a.value)) return true; + } + return false; + }; + // One instruction outside a section: the kind of what it writes, and whether it is a first + // lane's reservation. Err: throws WhyFail. + auto step = [&](const Inst& inst, const KindMap& kind, HashSet<Value>& firsts) -> std::pair<Wave, bool> { + auto name = inst.name(); + auto val = [&](const Operand& op) -> std::optional<Value> { + if (op.kind == Operand::Kind::Vector) return inst.read(Reg::V(op.reg)); + if (op.kind == Operand::Kind::Scalar && op.code != gfx10::NULL_CODE) return inst.read(Reg::S(op.code)); + return std::nullopt; + }; + std::vector<Operand> ops; + if (const auto* v = std::get_if<gfx10::Valu>(&inst.fields)) { + ops = v->src; + } else if (const auto* s = std::get_if<gfx10::Sop>(&inst.fields)) { + ops = s->src; + if (name == "s_addk_i32" || name == "s_mulk_i32") { + if (s->dst) ops.push_back(*s->dst); + } + } else if (const auto* bf = std::get_if<gfx10::Buffer>(&inst.fields); + bf && (name.find("_atomic_") != std::string_view::npos || + name.find("_store_") != std::string_view::npos)) { + if (bf->data) ops.push_back(*bf->data); + } + std::vector<Wave> kinds; + for (const auto& o : ops) kinds.push_back(of(kind, val(o))); + // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide operands) + // must not depend on the wave. Not EXEC, and not the old value of a VGPR it writes, which + // only the lanes outside EXEC keep. + std::vector<Value> named; + for (const auto& o : ops) { + if (auto v = val(o)) named.push_back(*v); + } + for (const auto& [r, v] : inst.reads) { + bool kept = r.is_v() && std::any_of(inst.writes.begin(), inst.writes.end(), + [&](const auto& w) { return w.first == r; }); + if ((r.is_s() && (r.n == ir::EXEC || r.n == ir::EXEC + 1)) || kept || + std::find(named.begin(), named.end(), v) != named.end()) { + continue; + } + Wave k = of(kind, v); + if (wild(k)) fail(why(k)); + } + Wave w = MIXED_W; + for (Wave k : kinds) { + if (wild(k)) { + w = k; + break; + } + } + auto sum = [](Wave k) { return k == Wave::total(Op::AddU); }; + auto is_mask = [&](const Operand& o) { + auto v = val(o); + return v && is_mask_of(st, *v); + }; + bool reserved = false; + bool any_wild = std::any_of(kinds.begin(), kinds.end(), wild); + auto is = [&](std::initializer_list<std::string_view> names) { + return std::find(names.begin(), names.end(), name) != names.end(); + }; + Wave out; + if (is({"s_ff1_i32_b64", "s_ff1_i32_b32"}) && !ops.empty() && is_mask(ops[0])) { + out = FIRST_W; + } else if (is({"s_bcnt1_i32_b64", "s_bcnt1_i32_b32"}) && !ops.empty() && is_mask(ops[0])) { + out = Wave::total(Op::AddU); + } else if (is({"v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"}) && kinds.size() == 2) { + // bits of a mask below the lane; with -1 for the mask, the lane's number + bool scalar = ops[0].kind == Operand::Kind::Scalar; + Wave b = kinds[1]; + if (b.kind == K::Prefix || (scalar && (b.kind == K::Plain || b.kind == K::Base))) { + out = PREFIX_W; + } else if (!scalar && (b.kind == K::Plain || b.kind == K::Base)) { + out = PLAIN; + } else { + fail(why(b)); + } + } else if (!any_wild) { + // nothing wave-dependent goes in; what derives from a reserved base stays marked + bool derives = std::holds_alternative<gfx10::Valu>(inst.fields) || + std::holds_alternative<gfx10::Sop>(inst.fields); + out = derives && std::find(kinds.begin(), kinds.end(), BASE_W) != kinds.end() ? BASE_W : PLAIN; + } else if (is({"v_mov_b32", "s_mov_b32"}) && kinds.size() == 1) { + out = kinds[0]; + } else if (is({"v_cmp_eq_i32", "v_cmp_eq_u32", "v_cmpx_eq_i32", "v_cmpx_eq_u32"}) && kinds.size() == 2) { + // the lane whose own number is the first lane's + Wave a = kinds[0], b = kinds[1]; + const Operand* lane; + if (a == FIRST_W && !wild(b)) { + lane = &ops[1]; + } else if (b == FIRST_W && !wild(a)) { + lane = &ops[0]; + } else { + fail(why(w)); + } + if (lane->kind != Operand::Kind::Vector) fail(FIRST); + std::optional<Value> mask; + if (name.starts_with("v_cmpx")) { + mask = inst.write(Reg::S(ir::EXEC)); + } else if (const auto* v = std::get_if<gfx10::Valu>(&inst.fields)) { + if (v->dst && v->dst->kind == Operand::Kind::Scalar) mask = inst.write(Reg::S(v->dst->code)); + } + if (mask) firsts.insert(*mask); + out = PLAIN; + } else if (is({"v_add_nc_u32", "s_add_i32"}) && kinds.size() == 2) { + Wave a = kinds[0], b = kinds[1]; + if ((a == PREFIX_W && b == BASE_W) || (a == BASE_W && b == PREFIX_W)) { + out = BASE_W; + } else if ((a == PREFIX_W && (b == PLAIN || b == PREFIX_W)) || (a == PLAIN && b == PREFIX_W)) { + out = PREFIX_W; + } else if (sum(a) && sum(b)) { + out = a; + } else { + fail(why(w)); + } + } else if (is({"v_sub_nc_u32", "s_sub_i32"}) && kinds.size() == 2) { + Wave a = kinds[0], b = kinds[1]; + if (a == BASE_W && b == PREFIX_W) { + out = BASE_W; + } else if (a == PREFIX_W && b == PLAIN) { + out = PREFIX_W; + } else if (a == PLAIN && sum(b) && ops[0] == Operand::Const(128)) { + out = b; + } else { + fail(why(w)); + } + } else if (is({"s_mul_i32", "v_mul_lo_u32", "v_mul_u32_u24"}) && kinds.size() == 2) { + // `(x, Plain) | (Plain, x) if sum(x) || x == Prefix`: the guard is tried per alternative + Wave a = kinds[0], b = kinds[1]; + if (b == PLAIN && (sum(a) || a == PREFIX_W)) { + out = a; + } else if (a == PLAIN && (sum(b) || b == PREFIX_W)) { + out = b; + } else { + fail(why(w)); + } + } else if (name == "s_lshl_b32" && kinds.size() == 2 && kinds[1] == PLAIN && + (sum(kinds[0]) || kinds[0] == PREFIX_W)) { + out = kinds[0]; + } else if (name == "v_lshlrev_b32" && kinds.size() == 2 && kinds[0] == PLAIN && + (sum(kinds[1]) || kinds[1] == PREFIX_W)) { + out = kinds[1]; + } else if (name == "v_lshl_add_u32" && kinds.size() == 3 && kinds[0] == PREFIX_W && kinds[1] == PLAIN && + !wild(kinds[2])) { + out = kinds[2] == BASE_W ? BASE_W : PREFIX_W; + } else if (kinds.size() == 1 && kinds[0].kind == K::Total && name.find("_atomic_") != std::string_view::npos) { + // the reservation: the first lane adds its wave's total to a shared counter + std::string_view want; + switch (kinds[0].op) { + case Op::AddU: + want = "buffer_atomic_add"; + break; + case Op::MinU: + want = "buffer_atomic_umin"; + break; + case Op::MaxU: + want = "buffer_atomic_umax"; + break; + case Op::MinI: + want = "buffer_atomic_smin"; + break; + case Op::MaxI: + want = "buffer_atomic_smax"; + break; + case Op::Or: + want = "buffer_atomic_or"; + break; + case Op::And: + want = "buffer_atomic_and"; + break; + case Op::Xor: + want = "buffer_atomic_xor"; + break; + default: + want = ""; + break; + } + if (name != want || !first_mask(firsts, inst.read(Reg::S(ir::EXEC)))) fail(TOTAL); + reserved = true; + out = BASE_W; + } else { + fail(why(w)); + } + return {out, reserved}; + }; + std::vector<std::unordered_map<std::size_t, wave::Section>> sections; + for (std::size_t b = 0; b < p.blocks.size(); ++b) sections.push_back(wave::sections(p, b)); + const auto order = ir::reverse_postorder(p.blocks); + auto pass = [&](KindMap& kind, HashSet<Value>& firsts, bool check) -> std::optional<std::pair<std::size_t, Why>> { + for (std::size_t b : order) { + const auto& block = p.blocks[b]; + for (const auto& phi : block.phis) { + Wave k = PLAIN; + for (std::size_t n = 0; n < phi.args.size(); ++n) { + Wave x = of(kind, phi.args[n]); + if (n == 0) { + k = x; + } else if (k == x) { + // k + } else if (k == PLAIN && (x == BASE_W || x == PREFIX_W)) { + k = x; + } else if ((k == BASE_W || k == PREFIX_W) && x == PLAIN) { + // k + } else { + k = MIXED_W; + } + } + put(kind, phi.value, k); + } + for (std::size_t i = 0; i < block.insts.size(); ++i) { + const auto& inst = block.insts[i]; + // inside a whole-wave section: what the simulation found each value to be + // order: sections of one block do not overlap, at most one holds i + const wave::Section* sec = nullptr; + for (const auto& [s, se] : sections[b]) { + if (i > s && i < se.end) { + sec = &se; + break; + } + } + if (sec) { + for (const auto& [_, w] : inst.writes) { + Wave k; + auto it = sec->shapes.find(w); + if (it == sec->shapes.end()) { + k = MIXED_W; + } else { + const wave::Shape& sh = it->second; + switch (sh.kind) { + case wave::Shape::Kind::K: + k = PLAIN; + break; + case wave::Shape::Kind::Value: + k = of(kind, sh.a); + break; + case wave::Shape::Kind::Masked: + k = of(kind, sh.a); + break; + case wave::Shape::Kind::Active: { + Wave s = of(kind, sh.a); + if (s.kind == K::Plain || s.kind == K::Base) { + k = Wave::total(sh.op); + } else if (s.kind == K::Total && s.op == sh.op && first_mask(firsts, sh.b)) { + // the first lane's own sum of a total is that total + k = Wave::total(sh.op); + } else { + k = MIXED_W; + } + break; + } + case wave::Shape::Kind::Prefix: + if (sh.op == Op::AddU) { + Wave s = of(kind, sh.a); + if (s.kind == K::Plain || s.kind == K::Base) { + k = PREFIX_W; + } else if (s == Wave::total(Op::AddU) && first_mask(firsts, sh.b)) { + k = PREFIX_W; + } else { + k = MIXED_W; + } + } else { + k = MIXED_W; + } + break; + default: + k = MIXED_W; + break; + } + } + put(kind, w, k); + } + continue; + } + auto name = inst.name(); + if (name.starts_with("s_cbranch")) { + continue; // with the block's exit, below + } + Wave k; + bool reserved; + try { + std::tie(k, reserved) = step(inst, kind, firsts); + } catch (const WhyFail& e) { + if (check) return std::pair{inst.machine.offset, e.why}; + k = MIXED_W; + reserved = false; + } + // the same test as `Lower::inst`'s `effect` + bool effect = std::holds_alternative<gfx10::Exp>(inst.fields) || + (std::holds_alternative<gfx10::Flat>(inst.fields) && !name.starts_with("global_load_")) || + name.find("store") != std::string_view::npos || + name.find("atomic") != std::string_view::npos || + (std::holds_alternative<gfx10::Ds>(inst.fields) && + !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || + name.find("permute") != std::string_view::npos)); + if (check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(ir::EXEC)))) { + return std::pair{inst.machine.offset, EFFECT}; + } + bool guarded = st.guards[b][i].has_value(); + for (const auto& [r, w] : inst.writes) { + Wave kw = k; + // "some lane is counted" keeps the count's kind; any other SCC is one bit of data + if (r.is_scc() && !name.starts_with("s_bcnt1")) { + kw = wild(k) ? MIXED_W : PLAIN; + } + // a guarded write leaves the old value in the lanes outside EXEC + if (guarded && r.is_v() && kw == PLAIN) { + Wave old = of(kind, inst.read(r)); + if (old.kind == K::First || old.kind == K::Total || old.kind == K::Prefix) kw = MIXED_W; + } + put(kind, w, kw); + } + } + // a branch on "some lane is counted": fine where the structure made it the lane's own + // bit (the mask is EXEC under a scalar condition) + if (check && !block.insts.empty()) { + const auto& last = block.insts.back(); + if (last.name().starts_with("s_cbranch_scc")) { + if (auto scc = last.read(Reg::Scc); scc && wild(of(kind, scc))) { + bool own = false; + const auto& e = st.exits[b]; + if (e.kind == LaneExit::Kind::Branch) { + own = true; + for (const auto& a : st.bools.support(e.when)) { + if (a.kind == Atom::Kind::Uniform && a.value == *scc) { + own = false; + break; + } + } + } + if (!own) return std::pair{last.machine.offset, TOTAL}; + } + } + } + } + return std::nullopt; + }; + KindMap kind; + HashSet<Value> firsts; + // to a fixpoint (values carried around loops), then once more to say what is wrong + bool settled = false; + for (int n = 0; n < 16; ++n) { + KindMap before = kind; + std::size_t before_firsts = firsts.size(); + if (auto e = pass(kind, firsts, false)) return e; + if (before == kind && before_firsts == firsts.size()) { + settled = true; + break; + } + } + if (!settled) return std::pair{std::size_t{0}, MIXED}; + return pass(kind, firsts, true); +} + +// The mode of a group barrier the translation adds (host waves meeting): a wait for the +// group with a shared-memory fence; the fence alone with X2W_SHADERCFG_GROUP_SYNC=0. +std::uint32_t meeting_mode() { return x2w::vs::group_sync() == 0 ? 8 : (1 | 8); } + +// LDS accesses of a console wave run as two host waves, where some sit in blocks that only +// some lanes run (`all` is all_lane_blocks): per IR block, whether the host waves meet (a group +// barrier) at its start and before its exit. None if barriers cannot keep the console's order. +// +// The console runs the wave's lanes in step, so an LDS write is seen by every later read. Two host +// waves keep that order if they meet between any two accesses of which one writes. A barrier must +// be run by every thread, so it cannot stand in a lane branch's region; but every way into and out +// of such a region passes a block all lanes run, and the waves meet there: before the exit of an +// all-lane block into a region with LDS accesses, and at the start of an all-lane block entered +// from one. Accesses in all-lane blocks get their own barrier as before. What that cannot order is +// a write and a read inside one region (blocks joined without an all-lane block between them): +// refused. +// shortcut: two writes in one region are taken not to hit the same dword from both halves. +std::optional<std::vector<std::pair<bool, bool>>> lds_meetings(const Program& p, const Structured& st, + const std::vector<bool>& all) { + const std::size_t n = st.exits.size(); + auto succ = [&](std::size_t b) -> std::vector<std::size_t> { + const auto& e = st.exits[b]; + switch (e.kind) { + case LaneExit::Kind::Jump: + return {e.target}; + case LaneExit::Kind::Branch: + return {e.taken, e.not_taken}; + default: + return {}; + } + }; + // regions: blocks not every lane runs, joined by the edges between them + std::vector<std::size_t> region(n); + for (std::size_t b = 0; b < n; ++b) region[b] = b; + auto find = [](std::vector<std::size_t>& region, std::size_t b) { + while (region[b] != b) { + region[b] = region[region[b]]; + b = region[b]; + } + return b; + }; + for (std::size_t b = 0; b < n; ++b) { + for (std::size_t t : succ(b)) { + if (!all[b] && !all[t]) { + std::size_t x = find(region, b); + std::size_t y = find(region, t); + region[x] = y; + } + } + } + // per region: LDS reads, LDS writes + std::vector<bool> reads(n, false); + std::vector<bool> writes(n, false); + for (std::size_t b = 0; b < p.blocks.size() && b < n; ++b) { + const auto& block = p.blocks[b]; + if (all[b]) continue; + std::size_t r = find(region, b); + for (const auto& i : block.insts) { + auto name = i.name(); + if (!std::holds_alternative<gfx10::Ds>(i.fields) || name.starts_with("ds_swizzle") || + name.find("permute") != std::string_view::npos) { + continue; + } + if (name.starts_with("ds_read")) { + reads[r] = true; + } else { + writes[r] = true; + } + } + } + for (std::size_t r = 0; r < n; ++r) { + if (reads[r] && writes[r]) return std::nullopt; + } + std::vector<std::pair<bool, bool>> meet(n, {false, false}); + for (std::size_t b = 0; b < n; ++b) { + for (std::size_t t : succ(b)) { + if (all[b] && !all[t]) { + std::size_t r = find(region, t); + meet[b].second = meet[b].second || reads[r] || writes[r]; + } else if (!all[b] && all[t]) { + std::size_t r = find(region, b); + meet[t].first = meet[t].first || reads[r] || writes[r]; + } + } + } + return meet; +} + +// Masks held as numbers or constant lane sets in guards or lane branches: the lane tests its +// own bit by its console lane. +bool lane_constant_masks(const Structured& st) { + std::vector<Bool> work; + for (const auto& per_block : st.guards) { + for (const auto& g : per_block) { + if (g) work.push_back(*g); + } + } + for (const auto& e : st.exits) { + if (e.kind == LaneExit::Kind::Branch) work.push_back(e.when); + } + // Through lane-mask joins too: an edge that brings a number or a constant lane set needs the + // lane's own bit of it. + // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such a + // program still stops with "a constant lane mask" or "an opaque lane mask". + std::vector<Bool> seen; // a set (Bool has ==; no hash needed) + HashSet<Value> joins; + while (!work.empty()) { + Bool g = work.back(); + work.pop_back(); + if (std::find(seen.begin(), seen.end(), g) != seen.end()) continue; + seen.push_back(g); + for (const auto& a : st.bools.support(g)) { + if (a.kind == Atom::Kind::Opaque || a.kind == Atom::Kind::Constant) return true; + if (a.kind == Atom::Kind::Phi && joins.insert(a.value).second) { + auto it = st.phi_masks.find(a.value); + if (it != st.phi_masks.end()) work.insert(work.end(), it->second.begin(), it->second.end()); + } + } + } + return false; +} + +void set_host_max_wave(std::uint32_t lanes) { HOST_MAX_WAVE.store(lanes, std::memory_order_relaxed); } + +namespace detail { +bool replace_local_waves(bool on) { return std::exchange(LOCAL_WAVES, on); } +bool replace_local_any(bool on) { return std::exchange(LOCAL_ANY, on); } +bool replace_first_half_pairs(bool on) { return std::exchange(FIRST_HALF_PAIRS, on); } +} // namespace detail + +bool local_waves_on() { return LOCAL_WAVES; } +bool local_any_on() { return LOCAL_ANY; } +bool first_half_pairs_on() { return FIRST_HALF_PAIRS; } + +// X2W_SHADERCFG_F16_NEAREST=1: the results of 16-bit float operations are rounded to nearest as +// the console rounds them (Lower::f16_nearest) instead of as the host's `f32tof16` does. Off by +// default. +bool f16_nearest_on() { + if (TEST_F16_NEAREST) return *TEST_F16_NEAREST; + static const bool ON = [] { + auto v = env_var("X2W_SHADERCFG_F16_NEAREST"); + return v && *v == "1"; + }(); + return ON; +} + +// X2W_SHADERCFG_WAVE_OWN_BITS=0: a wave OR where not every lane runs is refused as before. +bool own_bits_on() { + static const bool ON = [] { + auto v = env_var("X2W_SHADERCFG_WAVE_OWN_BITS"); + return !v || *v != "0"; + }(); + return ON; +} + +// What the translator was told of the host, for a cache's key: the widest wave, the view +// heap's limit, where the raw twins of its views start, and what it writes for the console's own +// hardware. +std::array<std::uint32_t, 4> host_settings() { + std::uint32_t a = host_max_wave(); + std::uint32_t b = shader::view_heap_limit(); + std::uint32_t c = shader::raw_views(); + std::uint32_t d = host_rdna(); + return {a, b, c, d}; +} + +void set_host_rdna(bool on) { HOST_RDNA.store(on, std::memory_order_relaxed); } + +std::uint32_t host_rdna() { + if (TEST_RDNA) return *TEST_RDNA; + return HOST_RDNA.load(std::memory_order_relaxed) ? x2w::vs::rdna_float() : 0; +} + +std::uint32_t host_max_wave() { + if (TEST_HOST_WAVE) return *TEST_HOST_WAVE; + return HOST_MAX_WAVE.load(std::memory_order_relaxed); +} + +namespace test { +void set_f16_nearest(std::optional<bool> on) { TEST_F16_NEAREST = on; } +void set_rdna(std::optional<std::uint32_t> bits) { TEST_RDNA = bits; } +void set_host_wave(std::optional<std::uint32_t> lanes) { TEST_HOST_WAVE = lanes; } +void set_memory(std::optional<std::pair<std::uint32_t, std::uint64_t>> slot_and_address) { + TEST_MEMORY = slot_and_address; +} +} // namespace test + +std::optional<std::pair<std::uint32_t, std::uint64_t>> test_memory() { return TEST_MEMORY; } + +// Instructions that read a lane mask (not EXEC implicitly, not a lane's bit) as a number. +bool reads_mask_as_data(const Structured& st, const Inst& i) { + std::vector<const Operand*> ops; + if (const auto* sop = std::get_if<gfx10::Sop>(&i.fields)) { + // A mask operation (its result a mask) is no data use. + for (const auto& [r, w] : i.writes) { + if (r.is_s() && is_mask_of(st, w)) return false; + } + for (const auto& o : sop->src) ops.push_back(&o); + } else if (const auto* v = std::get_if<gfx10::Valu>(&i.fields); + v && i.name() != "v_cndmask_b32" && i.name().find("_co_ci_") == std::string_view::npos) { + for (const auto& o : v->src) ops.push_back(&o); + } else { + return false; + } + for (const Operand* op : ops) { + if (op->kind == Operand::Kind::Scalar && op->code != gfx10::NULL_CODE) { + auto x = i.read(Reg::S(op->code)); + if (x && is_mask_of(st, *x)) return true; + } + } + return false; +} + +// The parameters packing 16-bit rows two per dword and where each lays its elements out: +// (first row, [(dword, register, column, columns)]). +// +// The console allocates whole dwords to each 16-bit element. The first element of each row comes first. A +// short element packed into spare columns of an earlier register follows in the first parameter with whole +// dwords left, in row order. Packed pedestrian shaders use both layouts. +PackedLayout packed_layout(std::span<const SigElement> elements, + std::span<const std::pair<std::uint8_t, std::optional<std::uint8_t>>> packs_in) { + auto of_row = [&](std::uint8_t r) { + std::vector<const SigElement*> of; + for (const auto& e : elements) { + if (e.row == std::optional<std::uint32_t>(r)) of.push_back(&e); + } + std::stable_sort(of.begin(), of.end(), [](const SigElement* a, const SigElement* b) { return a->col < b->col; }); + return of; + }; + std::vector<std::pair<std::uint8_t, std::optional<std::uint8_t>>> packs(packs_in.begin(), packs_in.end()); + std::sort(packs.begin(), packs.end()); + // dedup_by_key(|p| p.0): keeps the first of each run + packs.erase(std::unique(packs.begin(), packs.end(), [](const auto& a, const auto& b) { return a.first == b.first; }), + packs.end()); + // Per parameter: its first row, the dwords used, the elements. + using Placed = std::tuple<std::uint8_t, std::uint8_t, std::uint8_t, std::uint8_t>; + std::vector<std::tuple<std::uint8_t, std::uint8_t, std::vector<Placed>>> layout; + std::vector<std::tuple<std::uint8_t, std::uint8_t, std::uint8_t>> behind; + for (const auto& [a, b] : packs) { + std::vector<Placed> placed; + std::uint8_t at = 0; + if (!of_row(a).empty()) { + std::vector<std::uint8_t> rows{a}; + if (b) rows.push_back(*b); + for (std::uint8_t r : rows) { + auto of = of_row(r); + if (of.empty()) continue; + const SigElement* lead = of[0]; + placed.emplace_back(at, r, lead->col, lead->cols); + at = static_cast<std::uint8_t>(at + div_ceil<std::uint8_t>(lead->cols, 2)); + for (std::size_t k = 1; k < of.size(); ++k) behind.emplace_back(r, of[k]->col, of[k]->cols); + } + } + layout.emplace_back(a, at, std::move(placed)); + } + std::sort(behind.begin(), behind.end()); + for (const auto& [r, col, cols] : behind) { + std::uint8_t need = div_ceil<std::uint8_t>(cols, 2); + for (auto& p : layout) { + if (std::get<1>(p) + need <= 4) { + std::get<2>(p).emplace_back(std::get<1>(p), r, col, cols); + std::get<1>(p) = static_cast<std::uint8_t>(std::get<1>(p) + need); + break; + } + } + } + PackedLayout out; + for (auto& [a, _, of] : layout) out.emplace_back(a, std::move(of)); + return out; +} + +// Where half `h` (dword h / 2, the high half when odd) of the parameter whose first 16-bit +// row is `a` comes from: a register and column of `elements`, none for padding. +std::optional<std::pair<std::uint8_t, std::uint8_t>> packed_half( + std::span<const SigElement> elements, + std::span<const std::pair<std::uint8_t, std::optional<std::uint8_t>>> packs, std::uint8_t a, + std::uint8_t h) { + auto layout = packed_layout(elements, packs); + auto it = std::find_if(layout.begin(), layout.end(), [&](const auto& p) { return p.first == a; }); + if (it == layout.end()) return std::nullopt; + for (const auto& [dword, row, col, cols] : it->second) { + std::uint8_t two = static_cast<std::uint8_t>(2 * dword); + if (h < two) continue; // h.checked_sub(2 * dword)? + std::uint8_t k = static_cast<std::uint8_t>(h - two); + if (k < cols) return std::pair{row, static_cast<std::uint8_t>(col + k)}; + } + return std::nullopt; +} + +// The pixel inputs packing two 16-bit rows per dword, as (first row, second row). +std::vector<std::pair<std::uint8_t, std::optional<std::uint8_t>>> input_packs(const StageIo& io, + std::span<const SigElement> inputs) { + const auto* ps = std::get_if<native::PsIo>(&io); + if (!ps) return {}; + auto partners = half_input_partners(io, inputs); + std::vector<std::pair<std::uint8_t, std::optional<std::uint8_t>>> out; + for (const auto& i : ps->inputs) { + if (!(i.fp16 && i.pack2)) continue; + std::optional<std::uint8_t> b; + if (i.row2 != i.row) { + b = i.row2; + } else if (auto it = partners.find(i.row); it != partners.end()) { + b = it->second; + } + out.emplace_back(i.row, b); + } + return out; +} + +// Vertex or mesh outputs of 16-bit values (see Lower::half_outputs): a packed row's partner +// is the next 16-bit row of the signature that no output entry names, taken in row order. +HashMap<std::uint8_t, std::pair<bool, std::optional<std::uint8_t>>> half_outputs( + const StageIo& io, std::span<const SigElement> outputs) { + const std::vector<native::VsOutput>* entries; + if (const auto* vs = std::get_if<native::VsIo>(&io)) { + entries = &vs->outputs; + } else if (const auto* ms = std::get_if<native::MeshIo>(&io)) { + entries = &ms->outputs; + } else { + return {}; + } + std::vector<const native::VsOutput*> per_vertex; + for (const auto& o : *entries) { + if ((o.param & 0x80) == 0) per_vertex.push_back(&o); + } + std::vector<std::uint8_t> free; + for (const auto& e : outputs) { + if (!(e.half && e.kind == 0) || !e.row || *e.row > 0xFF) continue; + auto r = static_cast<std::uint8_t>(*e.row); + if (std::any_of(per_vertex.begin(), per_vertex.end(), [&](const auto* o) { return o->row == r; })) continue; + free.push_back(r); + } + std::sort(free.begin(), free.end()); + free.erase(std::unique(free.begin(), free.end()), free.end()); + std::vector<const native::VsOutput*> halves; + for (const auto* o : per_vertex) { + if (o->fp16) halves.push_back(o); + } + std::stable_sort(halves.begin(), halves.end(), [](const auto* a, const auto* b) { return a->row < b->row; }); + HashMap<std::uint8_t, std::pair<bool, std::optional<std::uint8_t>>> out; + for (const auto* o : halves) { + std::optional<std::uint8_t> b; + if (o->pack2) { + auto it = std::find_if(free.begin(), free.end(), [&](std::uint8_t r) { return r > o->row; }); + if (it != free.end()) { + b = *it; + free.erase(it); + } + } + out.insert_or_assign(o->row, std::pair{o->pack2, b}); + } + return out; +} + +// Pixel inputs packing two 16-bit rows per dword whose second row the metadata leaves out +// (`row2` = `row`): as for outputs (half_outputs), the next 16-bit row of the signature that no +// input entry names, taken in row order (rows the metadata does give are taken first). +HashMap<std::uint8_t, std::uint8_t> half_input_partners(const StageIo& io, std::span<const SigElement> inputs) { + const auto* ps = std::get_if<native::PsIo>(&io); + if (!ps) return {}; + const auto& entries = ps->inputs; + auto packed = [&](const native::PsInput& i) { return i.fp16 && i.pack2; }; + std::vector<std::uint8_t> free; + for (const auto& e : inputs) { + if (!(e.half && e.kind == 0) || !e.row || *e.row > 0xFF) continue; + auto r = static_cast<std::uint8_t>(*e.row); + if (std::any_of(entries.begin(), entries.end(), [&](const auto& i) { return i.row == r; })) continue; + if (std::any_of(entries.begin(), entries.end(), + [&](const auto& i) { return packed(i) && i.row2 != i.row && i.row2 == r; })) { + continue; + } + free.push_back(r); + } + std::sort(free.begin(), free.end()); + free.erase(std::unique(free.begin(), free.end()), free.end()); + std::vector<const native::PsInput*> missing; + for (const auto& i : entries) { + if (packed(i) && i.row2 == i.row) missing.push_back(&i); + } + std::stable_sort(missing.begin(), missing.end(), [](const auto* a, const auto* b) { return a->row < b->row; }); + HashMap<std::uint8_t, std::uint8_t> partners; + for (const auto* i : missing) { + auto it = std::find_if(free.begin(), free.end(), [&](std::uint8_t r) { return r > i->row; }); + if (it != free.end()) { + partners.insert_or_assign(i->row, *it); + free.erase(it); + } + } + return partners; +} + +std::optional<std::uint8_t> interp_mode(Barycentric kind) { + switch (kind) { + case Barycentric::PerspectiveCenter: + return 2; + case Barycentric::PerspectiveCentroid: + return 3; + case Barycentric::PerspectiveSample: + return 6; + case Barycentric::LinearCenter: + return 4; + case Barycentric::LinearCentroid: + return 5; + case Barycentric::LinearSample: + return 7; + case Barycentric::PerspectivePullModel: + return std::nullopt; + } + return std::nullopt; +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_image.cpp b/src/x2w_shader/emit/lower_image.cpp new file mode 100644 index 0000000000..2dc78e02d5 --- /dev/null +++ b/src/x2w_shader/emit/lower_image.cpp @@ -0,0 +1,811 @@ +// Image instructions. See lower_impl.h and GMR/vs_port/lower/PORTING.md for the conventions. +#include <algorithm> +#include <bit> +#include <cstdlib> + +#include "x2w_shader/emit/lower_impl.h" + +namespace x2w::vs::lower { + +void Lower::image(const Inst& inst, std::size_t b, std::size_t i) { + const auto& img = std::get<gfx10::Image>(inst.fields); + const Operand& data = img.data; + const std::vector<Operand>& addr = img.addr; + const bool unorm = img.unorm; + const bool a16 = img.a16; + const bool d16 = img.d16; + if (img.tfe || img.lwe) { + fail("an image access with tfe or lwe"); + } + const std::string_view name = inst.name(); + // A load or sample with no channel enabled returns the first. + const std::uint8_t dmask = img.dmask == 0 ? std::uint8_t{1} : img.dmask; + const Site site{b, i}; + const std::optional<V> guard = this->guard(b, i); + const std::size_t c = this->cur; + std::uint32_t kind = 0; + std::size_t coords = 0; + switch (img.dim) { + case 0: kind = 1; coords = 1; break; + case 1: kind = 2; coords = 2; break; + case 2: kind = 4; coords = 3; break; + case 3: + // Sampled (face coordinates and face, see `cube_direction`) or sized only. + if (name.starts_with("image_sample") || name.starts_with("image_gather") || + name == "image_get_resinfo") { + kind = 5; + coords = 3; + break; + } + fail("an image dimension (cube loads or MSAA)"); + case 4: kind = 6; coords = 2; break; + case 5: kind = 7; coords = 3; break; + default: fail("an image dimension (cube loads or MSAA)"); + } + // Address VGPRs in order. + std::vector<std::uint8_t> regs; + for (const Operand& a : addr) { + if (a.kind == Operand::Kind::Vector) { + for (std::uint8_t k = 0; k < a.dwords; ++k) { + regs.push_back(static_cast<std::uint8_t>(a.reg + k)); + } + } + } + // Full 32-bit address VGPR at `reg_idx` (offset, bias, z-compare). + auto addr_u32 = [&](Lower& l, std::size_t reg_idx) -> V { + if (reg_idx >= regs.size()) fail("an image address"); + const std::uint8_t r = regs[reg_idx]; + const Value v = ok_or(inst.read(Reg::V(r)), "an image address"); + return l.i32_of(v); + }; + // With a16, two 16-bit components per VGPR starting at `base_reg`, low half first. + auto addr_packed = [&](Lower& l, std::size_t base_reg, std::size_t k) -> V { + const V x = addr_u32(l, base_reg + (a16 ? k / 2 : k)); + if (!a16) { + return x; + } + const std::size_t c = l.cur; + const V sh = l.s.m.i32(16 * (static_cast<std::uint32_t>(k) % 2)); + const V mask = l.s.m.i32(0xFFFF); + const V y = l.s.m.bin(c, Bin::LShr, x, sh); + return l.s.m.bin(c, Bin::And, y, mask); + }; + auto addr_val = [&](Lower& l, std::size_t k) -> V { return addr_packed(l, 0, k); }; + const Source* src = nullptr; + { + auto it = this->descriptors.find(std::pair<Site, bool>{site, false}); + if (it == this->descriptors.end()) fail("an untracked image"); + src = it->second; + } + const bool store = name.starts_with("image_store"); + bool uav = store; + if (!uav) { + const UsedResource* u = this->used_kind(*src); + uav = u != nullptr && u->kind == ResourceType::Uav(); + } + // A UAV inside an ordered section is a rasterizer ordered view. + const bool ordered = uav && this->ordered.contains(site); + if (ordered) { + this->s.flags |= flags::ROVS; + } + const std::uint32_t rov = ordered ? 0x2000 : 0; + const std::pair<std::uint32_t, std::uint32_t> props{kind | (uav ? 0x1000u : 0u) | rov, 0x409}; + if (name.starts_with("image_atomic_")) { + const std::string_view op = name.substr(std::string_view("image_atomic_").size()); + // GLC returns the old value. DXIL implements subtraction by adding the two's complement + // of the operand at the same width. + std::uint32_t code = 0; + if (op == "add" || op == "sub") code = 0; + else if (op == "and") code = 1; + else if (op == "or") code = 2; + else if (op == "xor") code = 3; + else if (op == "smin") code = 4; + else if (op == "smax") code = 5; + else if (op == "umin") code = 6; + else if (op == "umax") code = 7; + else if (op == "swap") code = 8; + else if (op == "cmpswap") code = std::numeric_limits<std::uint32_t>::max(); + else fail(name.data()); + const gfx10::Cache& cache = img.cache; + // 16-bit coordinates (a16) are read as `addr_val` reads them. + if (d16) { + fail("a 16-bit image atomic"); + } + // Compare-exchange consumes a replacement followed by a comparand. + const bool compare = code == std::numeric_limits<std::uint32_t>::max(); + bool wide = false; + if ((!compare && dmask == 1) || (compare && dmask == 3)) { + wide = false; + } else if ((!compare && dmask == 3) || (compare && dmask == 15)) { + wide = true; + } else { + fail("an image atomic data mask"); + } + const V iu = this->s.m.undef(this->s.t.i32); + std::vector<V> cs(3, iu); + for (std::size_t k = 0; k < cs.size() && k < coords; ++k) { + cs[k] = addr_val(*this, k); + } + if (data.kind != Operand::Kind::Vector) { + fail("image atomic data"); + } + const std::uint8_t reg = data.reg; + const std::uint8_t width = wide ? 2 : 1; + const std::vector<V> vals = + this->vgprs(inst, data, static_cast<std::uint8_t>(compare ? 2 * width : width)); + Ty ty{}; + std::uint32_t component = 0; + if (wide) { + this->s.flags |= flags::INT64 | flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64; + ty = this->s.m.int_(64); // one uint64_t in an R32G32_UINT view + component = 0x107; + } else { + ty = this->s.t.i32; + component = 0x105; + } + const V original = wide ? this->join64(vals.at(0), vals.at(1)) : vals.at(0); + V value = original; + if (op == "sub") { + const V zero = this->s.m.int_const(ty, 0); + value = this->s.m.bin(c, Bin::Sub, zero, original); + } + const V h = this->handle(site, *src, false, {kind | 0x1000 | rov, component}); + std::vector<V> args{h}; + const char* intrinsic = nullptr; + std::uint32_t opcode = 0; + if (compare) { + const V comparand = wide ? this->join64(vals.at(2), vals.at(3)) : vals.at(1); + args.insert(args.end(), cs.begin(), cs.end()); + args.push_back(comparand); + args.push_back(value); + intrinsic = wide ? "atomicCompareExchange.i64" : "atomicCompareExchange.i32"; + opcode = 79; + } else { + const V k = this->s.m.i32(code); + args.push_back(k); + args.insert(args.end(), cs.begin(), cs.end()); + args.push_back(value); + intrinsic = wide ? "atomicBinOp.i64" : "atomicBinOp.i32"; + opcode = 78; + } + const auto at = this->begin_guarded(guard); + const V r = this->s.op(this->cur, intrinsic, Attr::NoUnwind, ty, opcode, args); + if (cache.glc) { + const std::vector<std::pair<V, V>> pairs{{r, original}}; + const V old = this->end_guarded(at, pairs).at(0); + if (wide) { + const auto [lo, hi] = this->split64(old); + this->write(inst, Reg::V(reg), lo, std::nullopt); + this->write(inst, Reg::V(static_cast<std::uint8_t>(reg + 1)), hi, std::nullopt); + } else { + this->write(inst, Reg::V(reg), old, std::nullopt); + } + } else { + this->end_guarded(at, {}); + } + return; + } + if (store) { + if (name != "image_store") { + fail("an image store to a mip level"); + } + // shortcut: stores are taken to write all four channels of a float format (the console + // converts by the view's format). One channel goes into a view the program also counts in. + const bool counter = dmask == 1 && this->is_counter(*src); + if (dmask != 0xF && !counter) { + fail("an image store of some channels"); + } + const V iu = this->s.m.undef(this->s.t.i32); + std::vector<V> cs(3, iu); + for (std::size_t k = 0; k < cs.size() && k < coords; ++k) { + cs[k] = addr_val(*this, k); + } + if (data.kind != Operand::Kind::Vector) { + fail("image store data"); + } + const std::uint8_t reg = data.reg; + if (counter) { + const Value v = ok_or(inst.read(Reg::V(reg)), "image store data"); + const V x = this->i32_of(v); + // A 16-bit integer, extended by the view's sign: the same number either way only if it + // is known to be small. + if (d16) { + const auto kx = this->s.m.int_k(x); + if (!(kx && kx->second < 0x8000)) { + fail("a 16-bit image store of one channel"); + } + } + const V h = this->handle(site, *src, false, {kind | 0x1000 | rov, 0x105}); + const auto at = this->begin_guarded(guard); + // All four channels are written (the validator wants them all): the view has the first + // alone. + std::vector<V> args{h}; + args.insert(args.end(), cs.begin(), cs.end()); + for (int n = 0; n < 4; ++n) args.push_back(x); + const V mask = this->s.m.i8(0xF); + args.push_back(mask); + const Ty void_ = this->s.t.void_; + this->s.op(this->cur, "textureStore.i32", Attr::NoUnwind, void_, 67, args); + this->end_guarded(at, {}); + return; + } + std::vector<V> vals; + for (std::uint8_t k = 0; k < 4; ++k) { + // d16: two f16 channels per VGPR, low half first. + const std::uint8_t r = d16 ? k / 2 : k; + const Value v = + ok_or(inst.read(Reg::V(static_cast<std::uint8_t>(reg + r))), "image store data"); + if (d16) { + V x = this->i32_of(v); + if (k % 2 == 1) { + const V k16 = this->s.m.i32(16); + x = this->s.m.bin(this->cur, Bin::LShr, x, k16); + } + const Ty f32t = this->s.t.f32; + vals.push_back(this->s.op(this->cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, + std::vector<V>{x})); + } else { + vals.push_back(this->float_of(v)); + } + } + const V h = this->handle(site, *src, false, props); + const auto at = this->begin_guarded(guard); + std::vector<V> args{h}; + args.insert(args.end(), cs.begin(), cs.end()); + args.insert(args.end(), vals.begin(), vals.end()); + const V mask = this->s.m.i8(0xF); + args.push_back(mask); + const Ty void_ = this->s.t.void_; + this->s.op(this->cur, "textureStore.f32", Attr::NoUnwind, void_, 67, args); + this->end_guarded(at, {}); + return; + } + const bool has_cl = name.ends_with("_cl"); + std::uint32_t op = 0; + bool sample = false; + if (name == "image_sample" || name == "image_sample_o" || name == "image_sample_cl") { + op = 60; sample = true; + } else if (name == "image_sample_lz" || name == "image_sample_l" || name == "image_sample_lz_o") { + op = 62; sample = true; + } else if (name == "image_sample_b" || name == "image_sample_b_cl") { + op = 61; sample = true; + } else if (name == "image_sample_c_lz") { + op = 65; sample = true; + } else if (name == "image_sample_d" || name == "image_sample_d_cl") { + op = 63; sample = true; + } else if (name == "image_get_lod" && this->s.pixel) { + op = 81; sample = true; + } else if (name == "image_sample_c" && this->s.pixel) { + // Implicit derivatives: pixel shaders only. + op = 64; sample = true; + } else if (name == "image_sample_c_cl" && this->s.pixel) { + op = 64; sample = true; + } else if (name == "image_gather4" || name == "image_gather4_lz" || name == "image_gather4_lz_o" || + name == "image_gather4_l" || name == "image_gather4_l_o") { + op = 73; sample = true; + } else if (name == "image_load" || name == "image_load_mip") { + op = 66; sample = false; + } else if (name == "image_get_resinfo") { + op = 72; sample = false; + } else { + fail(name.data()); + } + if (op == 72) { + // Width, height, depth or layers, levels (per dmask) of the level in the first address: + // DXIL's dimensions; a channel DXIL leaves out reads 1 (UAVs: one level). + const V h = this->handle(site, *src, false, props); + const V mip = uav ? this->s.m.undef(this->s.t.i32) : addr_val(*this, 0); + const Ty i32t = this->s.t.i32; + const Ty dims = this->s.m.named_struct("dx.types.Dimensions", std::vector<Ty>(4, i32t)); + const V d = this->s.op(c, "getDimensions", Attr::ReadOnly, dims, 72, std::vector<V>{h, mip}); + const V one = this->s.m.i32(1); + std::array<bool, 4> present{true, true, true, true}; + if (kind == 1) present = {true, false, false, true}; + else if (kind == 2 || kind == 5 || kind == 6) present = {true, true, false, true}; + if (data.kind != Operand::Kind::Vector) { + fail("an image result"); + } + const std::uint8_t reg = data.reg; + std::size_t k = 0; + for (std::uint32_t ch = 0; ch < 4; ++ch) { + if (((dmask >> ch) & 1) == 0) continue; + const V x = (ch == 3 && uav) || !present[ch] ? one : this->s.m.extract(c, d, ch); + this->write(inst, Reg::V(static_cast<std::uint8_t>(reg + k)), x, guard); + ++k; + } + return; + } + if (uav && op != 66) { + fail("sampling a UAV"); + } + const V h = this->handle(site, *src, false, props); + const V fu = this->s.m.undef(this->s.t.f32); + const V iu = this->s.m.undef(this->s.t.i32); + // A gather at a named level, done as four texel reads (below). + std::optional<std::array<V, 4>> gathered; + V r{}; + if (sample) { + const Source* ss = nullptr; + { + auto it = this->descriptors.find(std::pair<Site, bool>{site, true}); + if (it == this->descriptors.end()) fail("an untracked sampler"); + ss = it->second; + } + // Comparison: the reference value is the first address after the bias, and the sampler is + // a comparison sampler. + const bool cmp = op == 64 || op == 65; + if (cmp && (a16 || std::popcount(dmask) != 1)) { + fail("a comparison sample of 16-bit coordinates or several channels"); + } + std::optional<std::pair<V, std::vector<std::uint32_t>>> sampler_choice; + V sh{}; + if (const Source* phi = ss->kind == Source::Kind::Phi ? ss : nullptr) { + std::optional<std::pair<std::optional<V>, std::vector<std::uint32_t>>> choice; + try { + choice = this->sampler_phi_choice(phi->block, phi->args, cmp, 8); + } catch (const WhyFail&) { + choice.reset(); + } + if (choice && !choice->first) { + sh = this->s.sampler_handle(this->cur, choice->second.at(0)); + } else if (choice) { + const V first = this->s.sampler_handle(this->cur, choice->second.at(0)); + sampler_choice = std::pair<V, std::vector<std::uint32_t>>{*choice->first, + std::move(choice->second)}; + sh = first; + } else { + sh = this->handle(site, *ss, true, {14u | (cmp ? 0x8000u : 0u), 0}); + } + } else { + sh = this->handle(site, *ss, true, {14u | (cmp ? 0x8000u : 0u), 0}); + } + // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13, signed (programmable offsets: + // gathers only). + const bool offset_word = name.ends_with("_o"); + const std::size_t first = std::size_t(offset_word) + + std::size_t(name.starts_with("image_sample_b")) + std::size_t(cmp); + // Coordinates the size divides (not the array slice); explicit gradients (x then y) come + // before the coordinates. + const std::size_t spatial = coords - std::size_t(kind == 6 || kind == 7); + // A cube's gradients are the two of its face coordinates. + const std::size_t grads = kind == 5 ? 2 : spatial; + const std::size_t deriv_regs = op == 63 ? (a16 ? div_ceil<std::size_t>(grads, 2) : grads) : 0; + const std::size_t coord_base = first + 2 * deriv_regs; + std::vector<V> cs(4, fu); + // With a16, sampling coordinates, gradients, LOD and clamp are f16. + auto to_float = [&](Lower& l, V x) -> V { + if (a16) { + const Ty f = l.s.t.f32; + return l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, std::vector<V>{x}); + } + return l.as_float(x); + }; + if (kind == 5 && (unorm || op == 81)) { + fail("a cube sample with texel coordinates or a level query"); + } + for (std::size_t k = 0; k < cs.size() && k < coords; ++k) { + const V x = addr_packed(*this, coord_base, k); + cs[k] = to_float(*this, x); + } + if (kind == 5) { + const std::array<V, 3> dir = this->cube_direction(cs[0], cs[1], cs[2]); + cs[0] = dir[0]; + cs[1] = dir[1]; + cs[2] = dir[2]; + } + if (unorm) { + // Texel coordinates: divided by the size of level 0. + const Ty i32t = this->s.t.i32; + const Ty dims = this->s.m.named_struct("dx.types.Dimensions", std::vector<Ty>(4, i32t)); + const V z = this->s.m.i32(0); + const V d = this->s.op(c, "getDimensions", Attr::ReadOnly, dims, 72, std::vector<V>{h, z}); + for (std::size_t k = 0; k < cs.size() && k < spatial; ++k) { + const V n0 = this->s.m.extract(c, d, static_cast<std::uint32_t>(k)); + const V n = this->s.m.cast(c, Cast::UiToFp, n0, this->s.t.f32); + cs[k] = this->s.m.bin(c, Bin::SDiv, cs[k], n); // fdiv: same opcode as sdiv + } + } + if (op == 81) { + // The clamped then the unclamped level of detail. + if (data.kind != Operand::Kind::Vector) { + fail("an image result"); + } + const std::uint8_t reg = data.reg; + const Ty f32t = this->s.t.f32; + std::size_t k = 0; + for (std::uint32_t ch = 0; ch < 2; ++ch) { + if (((dmask >> ch) & 1) == 0) continue; + const V clamped = this->s.m.bool_(ch == 0); + const V lod = this->s.op(c, "calculateLOD.f32", Attr::ReadOnly, f32t, 81, + std::vector<V>{h, sh, cs[0], cs[1], cs[2], clamped}); + const V x = this->as_int(lod); + this->write(inst, Reg::V(static_cast<std::uint8_t>(reg + k)), x, guard); + ++k; + } + return; + } + const std::size_t offsets = + kind == 5 ? 0 : std::min<std::size_t>(coords - std::size_t(kind == 6 || kind == 7), 3); + const V zero = this->s.m.i32(0); + std::vector<V> os(3, iu); + for (std::size_t k = 0; k < offsets; ++k) { + os[k] = zero; + } + if (offset_word && offsets > 0) { + const V w = addr_val(*this, 0); + const std::pair<std::size_t, std::uint32_t> fields[2] = {{0, 26}, {1, 18}}; + for (std::size_t n = 0; n < std::min<std::size_t>(offsets, 2); ++n) { + const auto [k, at] = fields[n]; + // Bits at..at+5 sign-extended: shift up, then down. + const V left = this->s.m.i32(at); + const V t = this->s.m.bin(c, Bin::Shl, w, left); + const V k26 = this->s.m.i32(26); + os[k] = this->s.m.bin(c, Bin::AShr, t, k26); + } + } + std::vector<V> args{h, sh}; + args.insert(args.end(), cs.begin(), cs.end()); + V clamp = fu; + if (has_cl) { + const V x = addr_packed(*this, coord_base, coords); + clamp = to_float(*this, x); + } + auto call_sample = [&](Lower& l, const char* intrinsic, std::uint32_t opcode, + const std::vector<V>& args, + std::optional<std::array<V, 4>>& gathered) -> V { + if (!sampler_choice) { + return l.s.op(c, intrinsic, Attr::ReadOnly, l.s.t.res_ret, opcode, args); + } + const V idx = sampler_choice->first; + const std::vector<std::uint32_t>& regs = sampler_choice->second; + const std::size_t merge = l.s.m.new_block(); + std::size_t cur_test = c; + std::array<std::vector<std::pair<V, std::size_t>>, 4> per_ch; + V last_r = args.at(0); + for (std::size_t i = 0; i < regs.size(); ++i) { + const std::uint32_t reg = regs[i]; + std::size_t arm = 0; + if (i + 1 == regs.size()) { + arm = cur_test; + } else { + arm = l.s.m.new_block(); + const std::size_t next = l.s.m.new_block(); + const V k = l.s.m.i32(static_cast<std::uint32_t>(i)); + const V cond = l.s.m.cmp(cur_test, pred::EQ, idx, k); + l.s.m.terminate(cur_test, Term::cond_br(cond, arm, next)); + cur_test = next; + } + std::vector<V> arm_args = args; + arm_args.at(1) = l.s.sampler_handle(arm, reg); + const V r_i = l.s.op(arm, intrinsic, Attr::ReadOnly, l.s.t.res_ret, opcode, arm_args); + for (std::size_t ch = 0; ch < 4; ++ch) { + const V v = l.s.m.extract(arm, r_i, static_cast<std::uint32_t>(ch)); + per_ch[ch].push_back({v, arm}); + } + l.s.m.terminate(arm, Term::br(merge)); + last_r = r_i; + } + std::array<V, 4> phis{fu, fu, fu, fu}; + for (std::size_t ch = 0; ch < 4; ++ch) { + const V phi = l.s.m.phi(merge, l.s.t.f32); + l.s.m.set_phi(phi, std::move(per_ch[ch])); + phis[ch] = phi; + } + gathered = phis; + l.cur = merge; + return last_r; + }; + if (op == 60 && !this->s.pixel) { + // Outside a pixel shader there are no screen derivatives: the validator refuses + // `sample` there ("features incompatible with the shader stage": 730 compute programs, + // among them the G-buffer resolves and the sky), and what a driver does with it is its + // own affair. + // shortcut: such a sample reads level 0 (a bias: that level). The console takes + // derivatives from neighbouring lanes there; compute them from the lanes if a resolve + // shows the wrong mip. + args.insert(args.end(), os.begin(), os.end()); + const V z = this->s.m.f32(0); + args.push_back(z); + r = call_sample(*this, "sampleLevel.f32", 62, args, gathered); + } else if (op == 60) { + if (offset_word) { + // DXIL immediate offsets must be in [-8, 7]. Console offsets are six bits and may be computed. Emit + // immediates for in-range constants and use the computed offsets otherwise. + const V w0 = addr_val(*this, 0); + if (const auto wv = this->s.m.int_value(w0)) { + const std::uint32_t w = static_cast<std::uint32_t>(*wv); + auto field = [&](std::size_t k) -> std::int32_t { + const std::int32_t x = static_cast<std::int32_t>((w >> (8 * k)) & 0x3F); + return x >= 32 ? x - 64 : x; + }; + const std::size_t n = std::min<std::size_t>(offsets, 2); + bool all = true; + for (std::size_t k = 0; k < n; ++k) { + const std::int32_t f = field(k); + if (!(f >= -8 && f <= 7)) { + all = false; + break; + } + } + if (all) { + for (std::size_t k = 0; k < os.size() && k < n; ++k) { + os[k] = this->s.m.i32(static_cast<std::uint32_t>(field(k))); + } + } + } + } + args.insert(args.end(), os.begin(), os.end()); + args.push_back(clamp); + r = call_sample(*this, "sample.f32", 60, args, gathered); + } else if (op == 61) { + // With a16 the bias is an f16 in the low half of its word (the word is whole, the value + // is not). + const V bias0 = addr_u32(*this, std::size_t(offset_word)); + V bias{}; + if (a16) { + const V low = this->s.m.i32(0xFFFF); + const V b16 = this->s.m.bin(c, Bin::And, bias0, low); + bias = to_float(*this, b16); + } else { + bias = this->as_float(bias0); + } + args.insert(args.end(), os.begin(), os.end()); + if (this->s.pixel) { + args.push_back(bias); + args.push_back(clamp); + r = call_sample(*this, "sampleBias.f32", 61, args, gathered); + } else { + // As above: the bias is the level. + args.push_back(bias); + r = call_sample(*this, "sampleLevel.f32", 62, args, gathered); + } + } else if (op == 63 && kind == 5) { + // A cube with explicit gradients: the host wants them as changes of the direction, the + // console gives the changes of the face coordinates (the face is one unit wide). The + // level they select is taken from the longer of the two, in texels, and sampled + // directly. + // shortcut: no anisotropic filtering for these samples (the longer axis alone decides + // the level). + std::array<V, 2> len{fu, fu}; + for (std::size_t axis = 0; axis < 2; ++axis) { + V sum = this->s.m.f32(0); + for (std::size_t k = 0; k < 2; ++k) { + const V x0 = addr_packed(*this, first + axis * deriv_regs, k); + const V x = to_float(*this, x0); + const V sq = this->s.m.bin(c, Bin::Mul, x, x); + sum = this->s.m.bin(c, Bin::Add, sum, sq); + } + len[axis] = this->unary(24, sum); // square root + } + const V longer = this->binary(35, len[0], len[1]); // maximum + const Ty i32t = this->s.t.i32; + const Ty dims = this->s.m.named_struct("dx.types.Dimensions", std::vector<Ty>(4, i32t)); + const V z = this->s.m.i32(0); + const V d = this->s.op(c, "getDimensions", Attr::ReadOnly, dims, 72, std::vector<V>{h, z}); + const V width0 = this->s.m.extract(c, d, 0); + const V width = this->s.m.cast(c, Cast::UiToFp, width0, this->s.t.f32); + const V texels = this->s.m.bin(c, Bin::Mul, longer, width); + // DXIL uses a base-2 logarithm. A length of zero gives minus infinity, which the sampler clamps to level + // zero. Apply the instruction's minimum level here because SampleLevel takes no clamp. + V lod = this->unary(23, texels); + if (has_cl) { + lod = this->binary(35, lod, clamp); + } + args.insert(args.end(), os.begin(), os.end()); + args.push_back(lod); + r = call_sample(*this, "sampleLevel.f32", 62, args, gathered); + } else if (op == 63) { + std::vector<V> g(6, fu); + for (std::size_t k = 0; k < spatial; ++k) { + const V x = addr_packed(*this, first, k); + g.at(k) = to_float(*this, x); + const V y = addr_packed(*this, first + deriv_regs, k); + g.at(3 + k) = to_float(*this, y); + } + args.insert(args.end(), os.begin(), os.end()); + args.insert(args.end(), g.begin(), g.end()); + args.push_back(clamp); + r = call_sample(*this, "sampleGrad.f32", 63, args, gathered); + } else if (op == 64 || op == 65) { + const V reference0 = addr_u32(*this, first - 1); + const V reference = this->as_float(reference0); + args.insert(args.end(), os.begin(), os.end()); + args.push_back(reference); + const char* intrinsic = nullptr; + if (op == 64) { + args.push_back(clamp); + intrinsic = "sampleCmp.f32"; + } else { + intrinsic = "sampleCmpLevelZero.f32"; + } + r = call_sample(*this, intrinsic, op, args, gathered); + } else if (op == 62) { + V lod{}; + if (name == "image_sample_l") { + const V x = addr_packed(*this, coord_base, coords); + lod = to_float(*this, x); + } else { + lod = this->s.m.f32(0); + } + args.insert(args.end(), os.begin(), os.end()); + args.push_back(lod); + r = call_sample(*this, "sampleLevel.f32", 62, args, gathered); + } else { + if (name == "image_gather4") { + fail("a gather with implicit level"); + } + if (std::popcount(dmask) != 1) { + fail("a gather of several channels"); + } + if ((name == "image_gather4_l" || name == "image_gather4_l_o") && coords == 2 && + spatial == 2) { + // The host's gather has no level: it read level 0 where the title names one (the + // depth pyramid its occlusion tests read: most of the world was culled against the + // wrong depths). The four texels are read at the level instead, in the gather's + // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0). + // With an offset too (`image_gather4_l_o`): the offset is in texels of that level. + // The title's meshlet culling takes a 4x4 block of the pyramid as one gather and + // three offset ones ((2,0), (0,2), (2,2)); the three read level 0, two texels + // beside the first one's place, so a meshlet three or four texels wide was tested + // against a quarter of what it covers. + // shortcut: the level is rounded to a whole one and coordinates past the edge are + // clamped, whatever the sampler says. + const V lod0 = addr_packed(*this, coord_base, coords); + V lod = to_float(*this, lod0); + const Ty i32t = this->s.t.i32; + const Ty f32t = this->s.t.f32; + const V fzero = this->s.m.f32(0); + lod = this->binary(35, lod, fzero); // maximum + lod = this->unary(26, lod); // round to nearest + const V mip = this->s.m.cast(c, Cast::FpToUi, lod, i32t); + const Ty dims = this->s.m.named_struct("dx.types.Dimensions", std::vector<Ty>(4, i32t)); + const V d = this->s.op(c, "getDimensions", Attr::ReadOnly, dims, 72, + std::vector<V>{h, mip}); + const V half = this->s.m.f32(f32_bits(0.5f)); + const V one = this->s.m.f32(f32_bits(1.0f)); + std::array<V, 2> lo{iu, iu}; + std::array<V, 2> hi{iu, iu}; + for (std::size_t k = 0; k < 2; ++k) { + const V n0 = this->s.m.extract(c, d, static_cast<std::uint32_t>(k)); + const V n = this->s.m.cast(c, Cast::UiToFp, n0, f32t); + const V last = this->s.m.bin(c, Bin::Sub, n, one); + const V t0 = this->s.m.bin(c, Bin::Mul, cs[k], n); + const V t = this->s.m.bin(c, Bin::Sub, t0, half); + const V first0 = this->unary(27, t); // round down + // The offset word's field (0 without one). + const V by = this->s.m.cast(c, Cast::SiToFp, os[k], f32t); + const V firstk = this->s.m.bin(c, Bin::Add, first0, by); + const V next = this->s.m.bin(c, Bin::Add, firstk, one); + const std::pair<V*, V> pairs[2] = {{&lo[k], firstk}, {&hi[k], next}}; + for (const auto& [slot, x0] : pairs) { + const V x1 = this->binary(35, x0, fzero); // maximum + const V x = this->binary(36, x1, last); // minimum + *slot = this->s.m.cast(c, Cast::FpToSi, x, i32t); + } + } + const std::uint32_t ch = static_cast<std::uint32_t>(std::countr_zero(dmask)); + std::array<V, 4> g{fu, fu, fu, fu}; + std::optional<V> read; + const std::array<std::pair<V, V>, 4> texels{ + std::pair<V, V>{lo[0], hi[1]}, {hi[0], hi[1]}, {hi[0], lo[1]}, {lo[0], lo[1]}}; + for (std::size_t n = 0; n < 4; ++n) { + const auto [x, y] = texels[n]; + const V rr = this->s.op(c, "textureLoad.f32", Attr::ReadOnly, this->s.t.res_ret, 66, + std::vector<V>{h, mip, x, y, iu, iu, iu, iu}); + g[n] = this->s.m.extract(c, rr, ch); + read = rr; + } + gathered = g; + r = *read; // "four reads" + } else { + args.push_back(os[0]); + args.push_back(os[1]); + const V chv = this->s.m.i32(static_cast<std::uint32_t>(std::countr_zero(dmask))); + args.push_back(chv); + r = call_sample(*this, "textureGather.f32", 73, args, gathered); + } + } + } else { + std::vector<V> cs(3, iu); + for (std::size_t k = 0; k < cs.size() && k < coords; ++k) { + cs[k] = addr_val(*this, k); + } + V mip{}; + if (name == "image_load_mip") { + mip = addr_val(*this, coords); + } else if (uav) { + // Our declarations have four channels. + this->s.flags |= flags::TYPED_UAV_LOADS; + mip = iu; + } else { + mip = this->s.m.i32(0); + } + std::vector<V> args{h, mip}; + args.insert(args.end(), cs.begin(), cs.end()); + args.push_back(iu); + args.push_back(iu); + args.push_back(iu); + r = this->s.op(c, "textureLoad.f32", Attr::ReadOnly, this->s.t.res_ret, 66, args); + } + if (data.kind != Operand::Kind::Vector) { + fail("an image result"); + } + const std::uint8_t reg = data.reg; + std::vector<std::uint32_t> channels; + if (op == 73) { + channels = {0, 1, 2, 3}; + } else { + for (std::uint32_t ch = 0; ch < 4; ++ch) { + if (((dmask >> ch) & 1) != 0) channels.push_back(ch); + } + } + std::vector<V> xs; + for (const std::uint32_t ch : channels) { + const V x = gathered ? (*gathered)[ch] : this->s.m.extract(c, r, ch); + if (d16) { + // shortcut: d16 results are taken as floats (rounded to nearest even); integer formats + // would keep 16 bits. + const Ty i32t = this->s.t.i32; + xs.push_back(this->s.op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, std::vector<V>{x})); + } else { + xs.push_back(this->as_int(x)); + } + } + if (d16) { + // Two channels per VGPR, low half first (an odd last high half 0). + const V k16 = this->s.m.i32(16); + std::vector<V> packed; + for (std::size_t n = 0; n < xs.size(); n += 2) { + if (n + 1 < xs.size()) { + const V hi = this->s.m.bin(c, Bin::Shl, xs[n + 1], k16); + packed.push_back(this->s.m.bin(c, Bin::Or, xs[n], hi)); + } else { + packed.push_back(xs[n]); + } + } + xs = std::move(packed); + } + for (std::size_t k = 0; k < xs.size(); ++k) { + this->write(inst, Reg::V(static_cast<std::uint8_t>(reg + k)), xs[k], guard); + } +} + +// The direction a cube sample's face coordinates stand for: the console takes s and t in [1, 2] +// (`v_cubesc`/`v_cubetc` over `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the +// host's cube sampling turns back into the same texel. +// shortcut: the view is taken as a cube, not a cube array (whose face operand adds 8 x the slice). +std::array<V, 3> Lower::cube_direction(V s, V t, V face) { + const std::size_t c = this->cur; + auto k = [](Lower& l, float v) { return l.s.m.f32(f32_bits(v)); }; + const V two = k(*this, 2.0f); + const V three = k(*this, 3.0f); + const V u0 = this->s.m.bin(c, Bin::Mul, s, two); + const V u = this->s.m.bin(c, Bin::Sub, u0, three); + const V v0 = this->s.m.bin(c, Bin::Mul, t, two); + const V v = this->s.m.bin(c, Bin::Sub, v0, three); + const V z = this->s.m.f32(0x8000'0000u); + const V nu = this->s.m.bin(c, Bin::Sub, z, u); + const V nv = this->s.m.bin(c, Bin::Sub, z, v); + const V one = k(*this, 1.0f); + const V mone = k(*this, -1.0f); + const V f = this->s.m.cast(c, Cast::FpToUi, face, this->s.t.i32); + // Per face +x, -x, +y, -y, +z, -z. + const std::array<std::array<V, 6>, 3> table{{ + {one, mone, u, u, u, nu}, + {nv, nv, one, mone, nv, nv}, + {nu, u, v, nv, one, mone}, + }}; + std::array<V, 3> out{}; + for (std::size_t row = 0; row < 3; ++row) { + V r = table[row][0]; + for (std::size_t n = 1; n < 6; ++n) { + const V kn = this->s.m.i32(static_cast<std::uint32_t>(n)); + const V is = this->s.m.cmp(c, pred::EQ, f, kn); + r = this->s.m.select(c, is, table[row][n], r); + } + out[row] = r; + } + return out; +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_impl.h b/src/x2w_shader/emit/lower_impl.h new file mode 100644 index 0000000000..158e5795ee --- /dev/null +++ b/src/x2w_shader/emit/lower_impl.h @@ -0,0 +1,585 @@ +// Emitter state and methods private to lower_*.cpp. +// +// Methods throw WhyFail for a missing value, StopRetry to retry lowering, or ShaderError for a terminal +// refusal. A false result can indicate an absent optional operation. Keep one builder call per statement +// because creation order determines type, constant and instruction numbers. Sort unordered collections +// before emitting anything that depends on their order. See GMR/vs_port/lower/NOTES.md. +#pragma once + +#include <array> +#include <bit> +#include <cmath> +#include <cstdint> +#include <cstring> +#include <functional> +#include <limits> +#include <map> +#include <optional> +#include <span> +#include <string> +#include <string_view> +#include <tuple> +#include <type_traits> +#include <unordered_map> +#include <unordered_set> +#include <utility> +#include <vector> + +#include "x2w_shader/emit/bitcode.h" +#include "x2w_shader/emit/lower.h" +#include "x2w_shader/emit/opt.h" +#include "x2w_shader/emit/opt.h" +#include "x2w_shader/emit/own_bits.h" +#include "x2w_shader/emit/shader.h" +#include "x2w_shader/emit/wave.h" +#include "x2w_shader/gfx10/fields.h" +#include "x2w_shader/spill.h" +#include "x2w_shader/structure.h" +#include "x2w_shader/resource.h" +#include "x2w_shader/io.h" +#include "x2w_shader/native.h" +#include "x2w_shader/bvh.h" +#include <algorithm> + +namespace x2w::vs::lower { + +// Namespaces used by the lowering implementation. +namespace emit = ::x2w::vs; +using bitcode::Attr; +using bitcode::Bin; +using bitcode::Cast; +using bitcode::Rmw; +using bitcode::Tag; +using bitcode::Term; +using bitcode::Ty; +using bitcode::V; +namespace pred = bitcode::pred; +namespace opt = bitcode::opt; +using shader::Mesh; +using shader::Shader; +namespace flags = shader::flags; +// Shader ABI constants and heap settings, including SLOT_STRIDES, USER_VIEW_BIAS, raw_views and +// view_heap_limit. +using namespace ::x2w::vs::shader; +using ir::Inst; +using ir::Program; +using ir::Reg; +using ir::Value; +using gfx10::Dpp; +using gfx10::Fields; +using gfx10::Operand; +using io::Barycentric; +using io::Export; +using io::Input; +using io::Interp; +using io::Io; +using io::Target; +using native::HwStage; +using native::NativeProgram; +using native::ResourceType; +using native::RootType; +using native::StageIo; +using native::Usage; +using native::UsedResource; +using resource::Address; +using resource::Resources; +using resource::Role; +using resource::Site; +using resource::Source; +using structure::Atom; +using structure::Bool; +using structure::LaneExit; +using structure::Structured; + +// Hashing composite keys. +template <class T> +std::size_t hash_of(const T& v); + +inline std::size_t hash_mix(std::size_t seed, std::size_t h) { + return seed ^ (h + 0x9e3779b97f4a7c15ull + (seed << 6) + (seed >> 2)); +} + +template <class A, class B> +std::size_t hash_of_pair(const std::pair<A, B>& p) { + return hash_mix(hash_of(p.first), hash_of(p.second)); +} + +template <class T> +std::size_t hash_of(const T& v) { + if constexpr (requires { std::tuple_size<T>::value; } && !std::is_array_v<T>) { + std::size_t seed = 0; + std::apply([&](const auto&... e) { ((seed = hash_mix(seed, hash_of(e))), ...); }, v); + return seed; + } else if constexpr (std::is_same_v<T, ir::Value>) { + return std::hash<std::uint32_t>{}(v.n); + } else if constexpr (std::is_same_v<T, bitcode::V>) { + return bitcode::VHash{}(v); + } else if constexpr (std::is_same_v<T, structure::Bool>) { + return structure::BoolHash{}(v); + } else if constexpr (std::is_same_v<T, ir::Reg>) { + return std::hash<std::uint32_t>{}(static_cast<std::uint32_t>(v.kind) << 8 | v.n); + } else if constexpr (std::is_enum_v<T>) { + return std::hash<std::underlying_type_t<T>>{}(static_cast<std::underlying_type_t<T>>(v)); + } else { + return std::hash<T>{}(v); + } +} + +struct Hash { + template <class T> + std::size_t operator()(const T& v) const { + return hash_of(v); + } +}; + +template <class K, class T> +using HashMap = std::unordered_map<K, T, Hash>; +template <class K> +using HashSet = std::unordered_set<K, Hash>; +template <class K, class T> +using BTreeMap = std::map<K, T>; + +// Failures while resolving values. +struct WhyFail { + Why why; +}; +// a phi whose incoming value has no DXIL form was read: redo with it missing. (`Stop::Fail(e)` is a thrown +// ShaderError.) +struct StopRetry { + Value value; + Why why; +}; + +[[noreturn]] inline void fail(Why why) { throw WhyFail{why}; } +// Throw an unsupported instruction error with the offset and reason. +[[noreturn]] inline void unsupported(std::size_t offset, Why what) { + throw ShaderError::unsupported(offset, what); +} +template <class T> +T ok_or(std::optional<T> o, Why why) { + if (!o) fail(why); + return *o; +} +template <class T> +T* ok_or(T* p, Why why) { + if (!p) fail(why); + return p; +} +template <class F> +auto ok(F&& f) -> std::optional<decltype(f())> { + try { + return f(); + } catch (const WhyFail&) { + return std::nullopt; + } +} +template <class F> +bool is_ok(F&& f) { + try { + f(); + return true; + } catch (const WhyFail&) { + return false; + } +} +// Return the error from f, if any. +template <class F> +std::optional<Why> err_of(F&& f) { + try { + f(); + } catch (const WhyFail& e) { + return e.why; + } + return std::nullopt; +} + +inline bool same(Why a, Why b) { return std::string_view(a) == std::string_view(b); } + +// Shift counts must be below the operand width. Assert in debug builds and mask the count in release +// builds. +inline std::uint32_t shl32(std::uint32_t x, std::uint32_t n) { return x << (n & 31); } +inline std::uint32_t shr32(std::uint32_t x, std::uint32_t n) { return x >> (n & 31); } +inline std::uint64_t shl64(std::uint64_t x, std::uint32_t n) { return x << (n & 63); } +inline std::uint64_t shr64(std::uint64_t x, std::uint32_t n) { return x >> (n & 63); } +// Sites requiring a zero for an out-of-range shift check the count explicitly. + +inline std::uint32_t f32_as_u32(float f) { + if (std::isnan(f) || f <= 0.0f) return 0; + if (f >= 4294967296.0f) return std::numeric_limits<std::uint32_t>::max(); + return static_cast<std::uint32_t>(f); +} +inline std::int32_t f32_as_i32(float f) { + if (std::isnan(f)) return 0; + if (f <= -2147483648.0f) return std::numeric_limits<std::int32_t>::min(); + if (f >= 2147483648.0f) return std::numeric_limits<std::int32_t>::max(); + return static_cast<std::int32_t>(f); +} +inline std::uint32_t f32_bits(float f) { return std::bit_cast<std::uint32_t>(f); } +inline float f32_from_bits(std::uint32_t b) { return std::bit_cast<float>(b); } +// the other operand when one is NaN. +inline float rs_fmin(float a, float b) { return std::isnan(a) ? b : std::isnan(b) ? a : (a < b ? a : b); } +inline float rs_fmax(float a, float b) { return std::isnan(a) ? b : std::isnan(b) ? a : (a > b ? a : b); } +// usize::div_ceil, u32::div_ceil. +template <class T> +constexpr T div_ceil(T a, T b) { + return a / b + (a % b != 0 ? 1 : 0); +} + +// How interpolation evaluates an input channel. +struct Eval { + enum class Kind : std::uint8_t { Mode, Weights } kind = Kind::Mode; + // Mode: loaded with this DXIL interpolation mode (1: constant, P0). + std::uint8_t mode = 0; + // Weights: from the vertex values of a constant element: P0 when `p0`, plus i (P1 - P0), plus + // j (P2 - P0), weights as floats. + bool p0 = false; + std::optional<V> i; + std::optional<V> j; + + static Eval Mode(std::uint8_t m) { + Eval e; + e.kind = Kind::Mode; + e.mode = m; + return e; + } + static Eval Weights(bool p0, std::optional<V> i, std::optional<V> j) { + Eval e; + e.kind = Kind::Weights; + e.p0 = p0; + e.i = i; + e.j = j; + return e; + } +}; + +struct Val { + enum class Kind : std::uint8_t { I32, Bit, Missing } kind = Kind::Missing; + V v{}; + Why why = ""; + + static Val I32(V v) { return Val{Kind::I32, v, ""}; } + static Val Bit(V v) { return Val{Kind::Bit, v, ""}; } + static Val Missing(Why w) { return Val{Kind::Missing, V{}, w}; } + bool is_i32() const { return kind == Kind::I32; } + bool is_bit() const { return kind == Kind::Bit; } + bool is_missing() const { return kind == Kind::Missing; } +}; + +// How lane masks become data. +enum class MaskData : std::uint8_t { Console, Host, None }; + +struct NodeAt; +struct Ray; + +// Lowering helpers implemented in lower_free.cpp. +HashSet<Site> ordered_section(const Program& p); +std::uint32_t inline_f16(std::uint8_t c); +enum class Numeric : std::uint8_t { Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float }; +std::optional<std::pair<std::span<const std::uint32_t>, Numeric>> buffer_format(std::uint8_t format); +std::uint32_t half_shift(std::uint32_t width); +std::optional<std::vector<bool>> all_lane_blocks(const Structured& st); +void need(std::size_t block); +HashSet<Value> lane_uniform(const Program& p, const Structured& st, const std::vector<bool>& all); +std::uint32_t meeting_mode(); +std::optional<std::vector<std::pair<bool, bool>>> lds_meetings(const Program& p, const Structured& st, + const std::vector<bool>& all); +bool lane_constant_masks(const Structured& st); +bool f16_nearest_on(); +bool own_bits_on(); +bool local_waves_on(); // LOCAL_WAVES.get() +bool local_any_on(); // LOCAL_ANY.get() +bool first_half_pairs_on(); // FIRST_HALF_PAIRS.get() +std::optional<std::pair<std::uint32_t, std::uint64_t>> test_memory(); // intersect TEST_MEMORY +using PackedLayout = std::vector<std::pair<std::uint8_t, std::vector<std::tuple<std::uint8_t, std::uint8_t, std::uint8_t, std::uint8_t>>>>; +PackedLayout packed_layout(std::span<const SigElement> elements, + std::span<const std::pair<std::uint8_t, std::optional<std::uint8_t>>> packs); +std::optional<std::pair<std::uint8_t, std::uint8_t>> packed_half( + std::span<const SigElement> elements, + std::span<const std::pair<std::uint8_t, std::optional<std::uint8_t>>> packs, std::uint8_t a, + std::uint8_t h); +std::vector<std::pair<std::uint8_t, std::optional<std::uint8_t>>> input_packs( + const StageIo& io, std::span<const SigElement> inputs); +HashMap<std::uint8_t, std::pair<bool, std::optional<std::uint8_t>>> half_outputs( + const StageIo& io, std::span<const SigElement> outputs); +HashMap<std::uint8_t, std::uint8_t> half_input_partners(const StageIo& io, + std::span<const SigElement> inputs); +std::optional<std::uint8_t> interp_mode(Barycentric kind); + +inline constexpr float TWO_PI = 6.28318530717958647692f; // std::f32::consts::TAU +// `s_sendmsg` id of a mesh or NGG stage's output allocation request. +inline constexpr std::uint16_t GS_ALLOC_REQ = 9; +// `s_sendmsg` id that ends a pixel wave's ordered section. +inline constexpr std::uint16_t ORDERED_PS_DONE = 7; +// Hardware register (of `s_setreg_b32`) a pixel wave names its packer in. +inline constexpr std::uint16_t POPS_PACKER = 25; +// The operand `src_pops_exiting_wave_id`. +inline constexpr std::uint8_t POPS_EXITING = 239; + +// ---- the emitter ------------------------------------------------------------------------------- +class Lower { +public: + Lower(const Parts& x, const HashMap<Value, Why>& bad); + // Consumes the emitter. Throws StopRetry or ShaderError. + Lowered run(bool counted); + + // Emitter state. + Shader s; + const Parts& x; + const HashMap<Value, Why>& bad; + HashMap<Value, Why> lane_fail; + HashMap<Value, Val> vals; + HashMap<Value, V> floats; + // DXIL block per IR block (unreachable: none). + std::vector<std::optional<std::size_t>> block; + std::size_t cur = 0; + HashMap<std::pair<std::size_t, Bool>, V> bools; + HashMap<Value, V> lane_bits; + // IR phi location by value. + HashMap<Value, std::pair<std::size_t, std::size_t>> phi_at; + // Descriptor dwords with no host value. + HashSet<Value> stale; + HashSet<Site> ordered; + HashSet<std::pair<std::size_t, std::uint32_t>> coherent; + std::optional<V> root_copy; + std::optional<V> page_there; + HashMap<Value, V> mask_phis; + std::vector<std::tuple<V, std::size_t, std::size_t>> pending_masks; + std::vector<std::tuple<V, std::size_t, std::size_t>> data_phis; + HashSet<Value> read_phis; + HashMap<Value, std::pair<std::size_t, std::uint32_t>> params; + std::optional<V> user_data; + BTreeMap<std::uint32_t, UserData> user_reads; + std::vector<std::array<std::uint32_t, 4>> samplers; + HashMap<std::pair<Site, bool>, const Source*> descriptors; + HashMap<Site, Address> scalar; + HashMap<Site, const Export*> exports; + HashMap<Site, const Interp*> interps; + HashMap<std::tuple<std::size_t, Site, std::uint8_t, bool, std::pair<std::uint32_t, std::uint32_t>>, V> handles; + HashMap<std::tuple<std::size_t, Site, std::uint8_t>, V> strides; + HashMap<std::pair<std::size_t, std::size_t>, std::size_t> edges; + std::vector<bool> exported; + std::vector<std::size_t> rpo; + std::vector<std::optional<std::size_t>> tail; + bool writes_uavs = false; + std::optional<V> src0; + bool console_lanes = false; + std::optional<V> flat_; + HashSet<std::size_t> no_barrier; + HashSet<std::size_t> fence_only; + bool split_lds = false; + std::optional<std::pair<std::vector<bool>, std::vector<std::pair<bool, bool>>>> lds_meet; + std::optional<std::tuple<std::uint32_t, bool, std::vector<bool>>> exchange; + bool local = false; + bool local_ok = false; + bool local_any = false; + HashSet<Value> uniform; + own_bits::OwnBits own_bits; + std::optional<V> clane; + std::optional<V> pair; + std::optional<std::uint32_t> halves; + std::optional<V> wave_base_; + HashMap<std::uint8_t, std::pair<bool, std::optional<std::uint8_t>>> half_outputs_; + MaskData mask_data = MaskData::None; + bool mask_ok = false; + HashMap<Value, std::pair<V, V>> ballots; + HashSet<Value> balloting; + HashMap<Value, std::size_t> def_block; + std::size_t cur_ir = 0; + HashMap<std::size_t, std::unordered_map<std::size_t, wave::Section>> sections; + HashSet<Value> section_out; + std::optional<std::tuple<V, std::uint32_t, std::uint32_t>> code_table; + HashMap<std::size_t, std::pair<V, std::vector<std::pair<V, std::size_t>>>> counters; + std::optional<std::size_t> abort; + + // Lowering methods. + V code_dword(V byte); + void flat(const Inst& inst, std::size_t b, std::size_t i); + void find_sections(); + void section_inst(std::size_t b, std::size_t i, std::size_t start); + V shape(wave::Shape shape, bool own); + V active_f64_sum(Value lo, Value hi, Value mask, bool high); + V add_halves(V a, V b); + V half_sum(V x); + bool exported_out(std::size_t b) const; + bool has_done_export(std::size_t b) const; + void inputs(); // (Result<(), Stop>) + bool pops_collision(Value v) const; + Val input(Input input); + Val compute_id(std::string_view name, std::uint32_t opcode, std::uint8_t c); + std::optional<std::pair<std::size_t, std::uint8_t>> find_input(std::uint8_t row, std::uint8_t channel) const; + Val load_input(std::size_t id, std::uint8_t col); + Val load_any_input(std::size_t id, std::uint8_t col); + Val get(Value v); + bool lazy_barycentric(Value v); // (Option<Result<(), Why>>) + Val barycentric(Barycentric kind, std::uint8_t index); + V i32_of(Value v); + Val user(std::size_t param, std::uint32_t dword); + std::uint32_t user_first() const; + V host_word(RootType root, std::uint8_t slot, std::uint32_t dword); + V user_at(std::uint32_t index); + bool read_as_number(Value v) const; + bool computed_with(Value v, std::uint32_t depth) const; + bool is_counter(const Source& src) const; + std::optional<std::pair<std::size_t, std::uint32_t>> entry(const Source& src) const; + void find_coherent(); + std::optional<bool> sized_view(const Inst& inst, Site site, std::uint8_t code, std::uint32_t count) const; + std::optional<std::pair<V, V>> view_address(Site site); + std::pair<V, V> address_plus(V lo, V hi, std::int32_t off); + std::pair<V, V> memory(V lo, V hi, std::optional<V> guard, bool store); + std::optional<std::pair<V, V>> root_address(const Source& src); + std::optional<std::pair<V, V>> root_memory(const Source& src, V off, std::optional<V> guard, bool store); + void memory_flat(const Inst& inst, std::size_t b, std::size_t i); + void memory_smem(const Inst& inst); + V mask_dword(Value v); + V operand(const Inst& inst, const Operand& op); + V f16_operand(const Inst& inst, const Operand& op); + V as_float(V x); + V as_int(V f); + static std::optional<std::pair<std::uint8_t, bool>> sdwa_src(const Inst& inst, std::size_t k); + V select_bits(V x, std::uint8_t sel, bool sext); + V fsrc(const Inst& inst, std::size_t k); + V src(const Inst& inst, std::size_t k); + V unary(std::uint32_t op, V f); + V binary(std::uint32_t op, V a, V b); + V max_min(bool max, V a, V b); + V fmad(V a, V b, V c); + V f16_toward_zero(V f); + V f16_nearest(V f); + V bfe(V a, V off, V width, bool signed_); + V is_nan_f32(V f); + V med3(V a, V b, V third); + V fract(V a, float threshold, float below_one); + V trig_turns(V x, bool cosine); + V mul_hi(V a, V b, bool signed_); + V legacy_mul(V a, V b); + V boolean(Bool b, std::size_t at); + V atom(Atom atom, std::size_t at); + std::optional<V> wave_base(); + V console_thread(); + V console_lane(); + void group_sync(std::size_t block); + std::pair<V, V> exchange_halves(std::size_t at, V mine); + V exchange_pair(std::uint32_t slot); + V scc_some(Value scc); + V wave_wide(std::size_t b, Bool when); + bool all_lanes(std::size_t b) const; + V lane_bit(std::size_t at, V lo, std::optional<V> hi); + std::optional<Value> pair_high(Value lo) const; + std::optional<V> guard(std::size_t b, std::size_t i); + void set(std::optional<Value> v, Val val); + void write(const Inst& inst, Reg reg, V x, std::optional<V> guard); + void write_placed(const Inst& inst, Reg reg, V x, std::optional<V> guard); + static std::optional<std::pair<std::uint8_t, std::uint8_t>> sdwa_dst(const Inst& inst); + V place_bits(const Inst& inst, Reg reg, V x, std::uint8_t sel, std::uint8_t unused); + void write_f(const Inst& inst, V f, std::optional<V> guard); + void write_i(const Inst& inst, V x, std::optional<V> guard); + std::optional<std::pair<std::size_t, std::size_t>> begin_guarded(std::optional<V> guard); + std::vector<V> end_guarded(std::optional<std::pair<std::size_t, std::size_t>> at, std::span<const std::pair<V, V>> values); + void cross_lane(bool quad); + Val thread_id(std::uint8_t c); + void mesh_prologue(Mesh mesh); + V mesh_thread(); + std::uint32_t wave() const; + V lane_index(); + V quad_pick(V x, V src); + bool helpers_read(bool quad) const; + V quad_read(V x, std::array<std::uint8_t, 4> lanes); + std::pair<V, V> first_lane(V x, std::optional<V> guard); + V helper_lane(); + std::pair<V, V> first_live_lane(V x, std::optional<V> guard); + V read_lane(V x, V lane); + V float_of(Value v); + std::vector<V> vgprs(const Inst& inst, const Operand& op, std::uint8_t n); + void ds(const Inst& inst, std::size_t b, std::size_t i); + V lds_float_min_max(V p, V data, bool max); + V lds_float_pick(V mem, V data, bool max); + void inst(std::size_t b, std::size_t i); // (Result<(), Stop>) + void memory_fence(); + void lds_meeting(); + bool dead(Value v, std::vector<Value>& seen) const; + bool uniform_test(const Inst& inst) const; + bool is_mask(std::optional<Value> v) const; + void sop(const Inst& inst); + V quad_mask(V pixels); + std::pair<V, V> add_sub_carry(std::size_t c, bool add, V a, V b, std::optional<V> cin); + V scc_in(const Inst& inst); + bool within_exec(Value scc) const; + static bool wide_loads(); + std::vector<V> raw_dwords(V h, V addr, std::uint32_t count); + void smem(const Inst& inst, Site site); + void descriptor_data(const Inst& inst, Site site); + std::optional<std::tuple<std::uint8_t, std::pair<std::uint32_t, std::uint32_t>, std::optional<std::uint32_t>, bool, const UsedResource*>> unused_descriptor_kind(const Inst& inst, Site site, std::uint8_t code, std::uint32_t count) const; + void code_smem(const Inst& inst, Address a); + V cbuffer_dword(V h, V a); + std::vector<V> format_load(V h, V off, std::uint8_t format, std::uint32_t channels); + V norm_quotient(V a, std::uint32_t w); + V exact_norm(V a, std::uint32_t w); + std::vector<V> d16_channels(std::uint8_t format, std::vector<V> channels); + std::pair<std::uint32_t, std::optional<V>> built_offset(const Source& src); + std::optional<V> root_bias(std::size_t param); + const UsedResource* used_kind(const Source& src) const; + V handle(Site site, const Source& src, bool sampler, std::pair<std::uint32_t, std::uint32_t> props); + std::pair<V, bool> raw_twin(const Source& src, V index, bool sampler, std::pair<std::uint32_t, std::uint32_t> props); + V descriptor_phi(std::size_t block, std::span<const Source> args, bool sampler, std::uint32_t depth); + std::uint32_t register_sampler(std::span<const std::uint32_t> words, bool cmp); + std::pair<std::optional<V>, std::vector<std::uint32_t>> sampler_phi_choice(std::size_t block, std::span<const Source> args, bool cmp, std::uint32_t depth); + void collect_constant_samplers(std::size_t block, std::span<const Source> args, std::uint32_t depth, std::vector<std::array<std::uint32_t, 4>>& distinct) const; + V sampler_index_phi(std::size_t block, std::span<const Source> args, std::uint32_t lower, std::span<const std::array<std::uint32_t, 4>> distinct, std::uint32_t depth); + std::optional<V> slot_stride(const Source& src); + std::optional<std::pair<V, V>> integer_view(const Source& src); + std::optional<V> slot_word(const Source& src); + V lane_heap_index(const Source& src, bool sampler); + V fetched_index(Site load, std::uint8_t first, bool sampler); + V heap_index(Site load, std::uint8_t first, bool sampler); + void valu(const Inst& inst, std::size_t b, std::size_t i); + std::pair<V, std::optional<V>> dpp(const Inst& inst, const Dpp& dpp); + void valu_op(const Inst& inst, std::optional<V> guard); + V src64(const Inst& inst, std::size_t k); + std::pair<V, V> f64_pair(const Inst& inst, std::size_t k); + V f64_to_f32_bits(V lo, V hi); + V join64(V lo, V hi); + V f64_bits_to_f32_bits(V lo, V hi); + std::pair<V, V> split64(V x); + V half_src(const Inst& inst, std::size_t k); + V half_fsrc(const Inst& inst, std::size_t k); + void write_half(const Inst& inst, V x, std::optional<V> guard); + bool valu16(const Inst& inst, std::string_view name, std::optional<V> guard); // (Option<Result<(), Why>>) + void valu16_op(const Inst& inst, std::string_view name, std::optional<V> guard, std::span<const std::string_view> float1, std::span<const std::string_view> float2, std::span<const std::string_view> float3); + V cvt_norm16(const Inst& inst, bool signed_); + V packed_src(const Inst& inst, std::size_t k, bool high, bool float_); + V fmac_half(const Inst& inst, std::size_t k, bool high); + void packed16(const Inst& inst, std::string_view op, std::optional<V> guard); + V integer(const Inst& inst, Why name); // (name: &'static str) + void compare(const Inst& inst, std::string_view rest); + void lane(const Inst& inst, std::optional<bool> value); + void lane_bits_for(const Inst& inst, V r); + void interp(const Inst& inst, Site site); + bool per_vertex(std::uint8_t row) const; + bool interpolated(std::uint8_t row) const; + V eval_channel(std::uint8_t row, std::uint8_t ch, Eval eval); + V vertex_input(std::size_t id, std::uint8_t col, std::uint8_t k); + V low_half(const Inst& inst, std::uint8_t reg, V x); + void image(const Inst& inst, std::size_t b, std::size_t i); + std::array<V, 3> cube_direction(V s, V t, V face); + void buffer(const Inst& inst, std::size_t b, std::size_t i); + void export_(std::size_t b, std::size_t i); + void emit_indices(const Export& e, std::optional<V> guard); + std::optional<std::uint8_t> unnamed_row() const; + void exit(std::size_t b); // (Result<(), Stop>) + void enter_loop(std::size_t from, std::size_t to, std::size_t via); + V count_iteration(std::size_t to, std::uint8_t p); + std::size_t abort_block(); + std::size_t edge(std::size_t from, std::size_t to); + void fill_phis(); // (Result<(), Stop>) + + // Ray intersection methods (lower_intersect.cpp). + void bvh(const Inst& inst, std::size_t b, std::size_t i); // irs:64 + std::tuple<V, V, V> bvh_memory(V low, V high, std::optional<V> guard); // irs:230 + NodeAt bvh_second_half(NodeAt at); // irs:256 + std::vector<V> bvh_node_words(NodeAt at, std::optional<V> base, std::uint32_t offset, std::uint32_t count); // irs:280 + std::pair<V, V> bvh_address(V word0, V word1, V pointer, std::optional<V> pointer_high); // irs:316 + std::array<V, 4> bvh_boxes(NodeAt at, V kind, const Ray& ray, bool sort); // irs:335 + std::array<V, 4> bvh_triangle(NodeAt at, V kind, const Ray& ray); // irs:467 +}; + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_input_mem.cpp b/src/x2w_shader/emit/lower_input_mem.cpp new file mode 100644 index 0000000000..c0029274cd --- /dev/null +++ b/src/x2w_shader/emit/lower_input_mem.cpp @@ -0,0 +1,1174 @@ +// Inputs, user data, descriptors' entries and title memory. See lower_impl.h and +// GMR/vs_port/lower/PORTING.md for lowering conventions. +#include <algorithm> +#include <bit> +#include <string> +#include <vector> + +#include "x2w_shader/emit/lower_impl.h" +#include "x2w_shader/spill.h" + +namespace x2w::vs::lower { + +namespace { + +// ---- small adapters to vs-front's representations (resource.h, io.h) ---- + +std::optional<std::pair<Site, std::uint8_t>> loaded_of(const Source& src) { + if (src.kind != Source::Kind::Loaded) return std::nullopt; + return std::pair<Site, std::uint8_t>{src.load, src.first}; +} + +const Address* built_address(const Source& src) { + if (src.kind != Source::Kind::Built) return nullptr; + return &src.address; +} + +Source make_loaded(Site site, std::uint8_t first) { + return Source::Loaded(site, first); +} + +bool is_barycentric_input(const Input& i) { return i.kind == Input::Kind::Barycentric; } + +} // namespace + +void Lower::inputs() { + // A later entry for the same value replaces the earlier one. + HashMap<Value, Input> io_inputs; + for (const auto& [w, in] : this->x.io->inputs) io_inputs.insert_or_assign(w, in); + for (const auto& [reg, v] : this->x.p->inputs) { + auto found = io_inputs.find(v); + const Input* input = found == io_inputs.end() ? nullptr : &found->second; + Val val; + if (reg.is_s() && this->params.contains(v)) { + continue; // loaded on first use + } + // Most programs only interpolate with them: loaded on first use as a value (`get`). + if (reg.is_v() && input && is_barycentric_input(*input)) { + continue; + } + if (reg.is_s()) { + std::uint8_t n = reg.n; + if (input) { + val = this->input(*input); + } else if (n <= 105 && this->x.io->initialized_sgprs.has_value() && + n >= *this->x.io->initialized_sgprs) { + // Above the SGPRs the hardware initializes, a register holds what the last wave + // left, so no program depends on it: a read the paths only seem to allow (a + // branch past the write, taken only with one past the read) reads zero, as VGPRs + // do. + val = Val::I32(this->s.m.i32(0)); + } else if (n >= ir::PARKED) { + // A scalar parked in a VGPR lane (`ir::unspill`), read where the paths only seem + // to allow it before any save: the lane of a VGPR nobody wrote, and VGPRs nobody + // set read as zero. + val = Val::I32(this->s.m.i32(0)); + } else if (this->pops_collision(v)) { + // No wave overlaps this one (see `ordered_section`). + val = Val::I32(this->s.m.i32(0)); + } else { + val = Val::Missing("a hardware SGPR input"); + } + } else if (reg.is_scc()) { + val = Val::Missing("SCC on entry"); + } else { + if (input) { + val = this->input(*input); + } else { + // Registers no one set read as zero (the validator refuses reads of undef). + val = Val::I32(this->s.m.i32(0)); + } + } + this->vals.insert_or_assign(v, val); + } +} + +// Whether the input SGPR `v` is the POPS collision wave id: a program with an ordered section only +// takes its fields apart (bit 31 says that the wave overlaps another, the others which packer and +// waves). +bool Lower::pops_collision(Value v) const { + if (this->ordered.empty()) { + return false; + } + bool packer = false; + for (const auto& block : this->x.p->blocks) { + for (const auto& p : block.phis) { + if (std::find(p.args.begin(), p.args.end(), v) != p.args.end()) return false; + } + for (const auto& i : block.insts) { + bool reads = std::any_of(i.reads.begin(), i.reads.end(), + [&](const auto& r) { return r.second == v; }); + if (!reads) { + continue; + } + const auto* sop = std::get_if<gfx10::Sop>(&i.fields); + if (!sop) { + return false; + } + auto name = i.name(); + const Operand* s1 = sop->src.size() > 1 ? &sop->src[1] : nullptr; + if (name == "s_bfe_u32" && s1 && s1->kind == Operand::Kind::Literal && + s1->literal == 0x0002'001Cu) { + packer = true; // bits 28 and 29: the packer + } else if (name == "s_bfe_u32" || name == "s_lshr_b32") { + } else { + return false; + } + } + } + return packer; +} + +Val Lower::input(Input input) { + std::uint8_t kind = 0; + std::uint8_t col = 0; + switch (input.kind) { + case Input::Kind::VertexId: + kind = 1; + col = 0; + break; + case Input::Kind::InstanceId: + kind = 2; + col = 0; + break; + case Input::Kind::Position: + kind = 3; + col = input.n; + break; + case Input::Kind::Attribute: { + auto found = this->find_input(input.row, input.channel); + if (found) return this->load_input(found->first, found->second); + return Val::Missing("a vertex input the signature lacks"); + } + case Input::Kind::Barycentric: + return this->barycentric(input.barycentric, input.index); + case Input::Kind::PrimitiveId: + return Val::Missing("the primitive id"); + case Input::Kind::FrontFace: + // The console code tests it against 0 (`v_cmp_ne_u32`), as the host's value can be. + kind = 13; + col = 0; + break; + case Input::Kind::ThreadIdInGroup: + return this->thread_id(input.n); + case Input::Kind::GroupId: + return this->compute_id("groupId.i32", 94, input.n); + case Input::Kind::GroupInfo: + return Val::Missing("the thread-group info SGPR"); + case Input::Kind::MeshGroup: { + Val g = this->compute_id("groupId.i32", 94, 0); + if (!g.is_i32()) std::abort(); // unreachable!() + V n = this->s.m.i32(this->x.mesh_stride); + return Val::I32(this->s.m.bin(this->s.entry, Bin::Mul, g.v, n)); + } + case Input::Kind::MergedWaveInfo: { + // shortcut: only the wave index (bits 24-27) is set; the console's other bits (lane + // counts) are read by no program. + V f = this->mesh_thread(); + std::uint32_t tz = static_cast<std::uint32_t>(std::countr_zero(this->wave())); + V shift = this->s.m.i32(tz); + V w = this->s.m.bin(this->s.entry, Bin::LShr, f, shift); + V k24 = this->s.m.i32(24); + return Val::I32(this->s.m.bin(this->s.entry, Bin::Shl, w, k24)); + } + default: + return Val::Missing("a pixel system input"); + } + auto max_row = [&]() { + std::uint32_t best = 0; + bool any = false; + for (const auto& e : this->s.inputs) { + if (!e.row) continue; + std::uint32_t r = *e.row + 1; + if (!any || r > best) best = r; + any = true; + } + return any ? best : 0u; + }; + std::uint32_t free = max_row(); + std::optional<std::size_t> pos; + for (std::size_t k = 0; k < this->s.inputs.size(); ++k) { + if (this->s.inputs[k].kind == kind) { + pos = k; + break; + } + } + std::size_t id; + if (pos) { + id = *pos; + if (kind != 3) { + auto& row = this->s.inputs.at(id).row; + if (!row) row = free; + } + } else if (kind >= 3) { + return Val::Missing("a pixel system input the signature lacks"); + } else { + // The console signature leaves out vertex and instance ids; PC gives them a row after the + // others. + std::uint32_t row = max_row(); + static const char* const NAMES[] = {"", "SV_VertexID", "SV_InstanceID"}; + SigElement e; + e.name = NAMES[kind]; + e.index = 0; + e.kind = kind; + e.comp = 5; + e.interp = 0; + e.row = row; + e.col = 0; + e.cols = 1; + e.usage = 0; + e.half = false; + this->s.inputs.push_back(std::move(e)); + id = this->s.inputs.size() - 1; + } + return this->load_input(id, col); +} + +// A component of a compute thread or group id, read in the entry block. +Val Lower::compute_id(std::string_view name, std::uint32_t opcode, std::uint8_t c) { + std::size_t entry = this->s.entry; + V k = this->s.m.i32(std::uint32_t{c}); + return Val::I32( + this->s.op(entry, name, Attr::ReadNone, this->s.t.i32, opcode, std::vector<V>{k})); +} + +std::optional<std::pair<std::size_t, std::uint8_t>> Lower::find_input(std::uint8_t row, + std::uint8_t channel) const { + for (std::size_t id = 0; id < this->s.inputs.size(); ++id) { + const auto& e = this->s.inputs[id]; + if (!e.row) continue; + std::uint32_t r = *e.row; + // `then`, not `then_some`: the channel is only past `col` when the condition holds. + if (r == std::uint32_t{row} && channel >= e.col && + channel < static_cast<std::uint8_t>(e.col + e.cols)) { + return std::pair<std::size_t, std::uint8_t>{id, + static_cast<std::uint8_t>(channel - e.col)}; + } + } + return std::nullopt; +} + +Val Lower::load_input(std::size_t id, std::uint8_t col) { + if (this->s.inputs.at(id).half) { + // shortcut: 16-bit vertex inputs (the fetch routine's) are not unpacked; pixel inputs + // are (`interp`). + return Val::Missing("a 16-bit input"); + } + return this->load_any_input(id, col); +} + +// An input element's channel as declared (16-bit ones as 32-bit floats). +Val Lower::load_any_input(std::size_t id, std::uint8_t col) { + auto& e = this->s.inputs.at(id); + e.usage = static_cast<std::uint8_t>(e.usage | (1u << col)); + bool int_ = e.comp != 9; + bool bit = e.comp == 1; + Ty ty = bit ? this->s.t.i1 : int_ ? this->s.t.i32 : this->s.t.f32; + const char* suffix = bit ? ".i1" : int_ ? ".i32" : ".f32"; + std::size_t entry = this->s.entry; + V a0 = this->s.m.i32(static_cast<std::uint32_t>(id)); + V a1 = this->s.m.i32(0); + V a2 = this->s.m.i8(col); + V a3 = this->s.m.undef(this->s.t.i32); + V v = this->s.op(entry, std::string("loadInput") + suffix, Attr::ReadNone, ty, 4, + std::vector<V>{a0, a1, a2, a3}); + if (bit) { + V z = this->s.m.cast(entry, Cast::ZExt, v, this->s.t.i32); + return Val::I32(z); + } else if (int_) { + return Val::I32(v); + } else { + return Val::I32(this->s.m.cast(entry, Cast::Bitcast, v, this->s.t.i32)); + } +} + +// The DXIL form of an IR value. +Val Lower::get(Value v) { + if (this->phi_at.contains(v)) { + this->read_phis.insert(v); + } + bool is_mask = this->x.st->masks.contains(v) || this->x.st->highs.contains(v); + { + auto it = this->vals.find(v); + bool none = it == this->vals.end(); + if ((none || it->second.is_missing()) && this->mask_ok && is_mask) { + return Val::I32(this->mask_dword(v)); + } + if (!none) { + if (it->second.is_missing()) fail(it->second.why); + return it->second; + } + } + auto pit = this->params.find(v); + if (pit != this->params.end()) { + auto [param, dword] = pit->second; + Val val = this->user(param, dword); + this->vals.insert_or_assign(v, val); + return val; + } + if (this->lazy_barycentric(v)) { // Some(Err) throws + return this->vals.at(v); + } + fail("a value defined after its use"); +} + +// Loads `v` if it is a barycentric input VGPR not loaded yet (see `inputs`): false (None) if it is +// not one; Some(Err) throws. +bool Lower::lazy_barycentric(Value v) { + const Input* found = nullptr; + for (const auto& [w, i] : this->x.io->inputs) { + if (is_barycentric_input(i) && w == v) { + found = &i; + break; + } + } + if (!found) return false; + Barycentric kind = found->barycentric; + std::uint8_t index = found->index; + Val val = this->barycentric(kind, index); + this->vals.insert_or_assign(v, val); + if (val.is_missing()) fail(val.why); + return true; +} + +// Barycentric `index` (0 i, 1 j) of `kind` as a value: a channel of `SV_Barycentrics` declared +// with the same interpolation mode. +// +// GFX10 interpolates P0 + i (P1 - P0) + j (P2 - P0), so i and j are the weights of vertices 1 and +// 2. The host's weights (x, y, z) are those of vertices 0, 1 and 2, vertex 0 being the provoking +// vertex, which is the console's P0 (`v_interp_mov` P0 is lowered to a flat input): i is y and j +// is z. +// shortcut: triangles only; on lines and points the console's i and j are not checked against +// the host's weights. +Val Lower::barycentric(Barycentric kind, std::uint8_t index) { + auto mode_opt = interp_mode(kind); + if (!mode_opt) { + return Val::Missing("pull-model barycentrics"); + } + std::uint8_t mode = *mode_opt; + if (index > 1) { + return Val::Missing("pull-model barycentrics"); + } + // One element per interpolation mode (the console's own, if its signature declares one): + // DXIL allows two. + auto bary = [](const SigElement& e) { return e.kind == 28; }; + std::optional<std::size_t> pos; + for (std::size_t k = 0; k < this->s.inputs.size(); ++k) { + const auto& e = this->s.inputs[k]; + if (bary(e) && (e.interp == mode || e.usage == 0)) { + pos = k; + break; + } + } + std::size_t id; + if (pos) { + id = *pos; + } else { + std::uint32_t n = static_cast<std::uint32_t>( + std::count_if(this->s.inputs.begin(), this->s.inputs.end(), bary)); + if (n >= 2) { + return Val::Missing("barycentrics of a third interpolation mode"); + } + // A system value the validator wants unpacked (packing location -1), like other + // non-packed system values. + SigElement e; + e.name = "SV_Barycentrics"; + e.index = n; + e.kind = 28; + e.comp = 9; + e.interp = mode; + e.row = std::nullopt; + e.col = 0; + e.cols = 3; + e.usage = 0; + e.half = false; + this->s.inputs.push_back(std::move(e)); + id = this->s.inputs.size() - 1; + } + auto& e = this->s.inputs.at(id); + if (e.col != 0 || e.cols < 3) { + return Val::Missing("a console barycentrics element without i and j"); + } + e.row = std::nullopt; + e.interp = mode; + this->s.flags |= flags::BARYCENTRICS; + return this->load_any_input(id, static_cast<std::uint8_t>(index + 1)); +} + +V Lower::i32_of(Value v) { + Val val = this->get(v); + switch (val.kind) { + case Val::Kind::I32: + return val.v; + case Val::Kind::Bit: + return this->s.m.cast(this->cur, Cast::ZExt, val.v, this->s.t.i32); + case Val::Kind::Missing: + default: + fail(val.why); + } +} + +// A user-data dword: a root parameter's value. +Val Lower::user(std::size_t param, std::uint32_t dword) { + const auto rp = this->x.native->layout.at(param); + if (rp.root == RootType::ResourceHeap() || rp.root == RootType::SamplerHeap()) { + return Val::I32(this->s.m.i32(0)); + } else if (rp.root == RootType::Constants() || rp.root == RootType::Table()) { + } else { + return Val::Missing("a root descriptor"); + } + std::uint32_t index = std::uint32_t{rp.user_data} + dword - this->user_first(); + UserData u; + u.index = index; + u.slot = rp.slot; + u.root = rp.root; + u.dword = dword; + this->user_reads.insert_or_assign(index, u); + return Val::I32(this->user_at(index)); +} + +// The user-data index that is dword 0 of the host's user data: 0, or 16 for a program with a +// spilled user-data table, whose parameters all sit at 16 and above. (The host's root signature +// has 64 dwords: a builder stage with constants up to index 45, eight root views, their biases +// and the memory directory would not fit with 16 dwords nothing reads in front.) +std::uint32_t Lower::user_first() const { + if (spill::is_spilled(*this->x.native)) { + return 16; + } else { + return 0; + } +} + +// A user-data dword no register of the console's holds: one the host computes when it binds (`root` says +// what, an `Other` code), placed after the layout's own dwords. +V Lower::host_word(RootType root, std::uint8_t slot, std::uint32_t dword) { + std::optional<std::uint32_t> known; + // Iterate in key order. + for (const auto& [k, u] : this->user_reads) { + if (u.root == root && u.slot == slot && u.dword == dword) { + known = u.index; + break; + } + } + std::uint32_t index; + if (known) { + index = *known; + } else { + std::uint32_t first = this->user_first(); + const auto& layout = this->x.native->layout; + std::uint32_t top = 0; + for (const auto& e : layout) top = std::max(top, std::uint32_t{e.user_data} + e.sgprs); + index = top > first ? top - first : 0; // saturating_sub + while (this->user_reads.contains(index)) { + index += 1; + } + UserData u; + u.index = index; + u.slot = slot; + u.root = root; + u.dword = dword; + this->user_reads.insert_or_assign(index, u); + } + return this->user_at(index); +} + +// User-data dword `index`, loaded in the entry block. +V Lower::user_at(std::uint32_t index) { + this->s.user_data = std::max(this->s.user_data, index + 1); + V h; + if (this->user_data) { + h = *this->user_data; + } else { + h = this->s.user_data_handle(); + this->user_data = h; + } + std::size_t entry = this->s.entry; + V row = this->s.m.i32(index / 4); + V r = this->s.op(entry, "cbufferLoadLegacy.i32", Attr::ReadOnly, this->s.t.cbuf_ret, 59, + std::vector<V>{h, row}); + return this->s.m.extract(entry, r, index % 4); +} + +// Whether some instruction reads `v` as a number (or may, through a join), rather than in a +// descriptor operand. +bool Lower::read_as_number(Value v) const { + for (const auto& b : this->x.p->blocks) { + for (const auto& p : b.phis) { + if (std::find(p.args.begin(), p.args.end(), v) != p.args.end()) return true; + } + for (const auto& i : b.insts) { + bool arith = std::holds_alternative<gfx10::Sop>(i.fields) || + std::holds_alternative<gfx10::Valu>(i.fields); + if (arith && std::any_of(i.reads.begin(), i.reads.end(), + [&](const auto& r) { return r.second == v; })) { + return true; + } + } + } + return false; +} + +// Whether some instruction computes with `v` (scalar or vector arithmetic), rather than only naming +// it in a descriptor operand, moving it (at most `depth` moves are followed) or comparing it: a +// waterfall loop keeps a descriptor's dwords per lane, reads the first lane's back and compares +// the lanes' with them. +bool Lower::computed_with(Value v, std::uint32_t depth) const { + for (const auto& b : this->x.p->blocks) { + for (const auto& i : b.insts) { + if (!std::any_of(i.reads.begin(), i.reads.end(), + [&](const auto& r) { return r.second == v; })) { + continue; + } + auto name = i.name(); + bool moves = name == "s_mov_b32" || name == "s_mov_b64" || name == "v_mov_b32" || + name == "v_readfirstlane_b32" || name == "v_readlane_b32" || + name == "v_writelane_b32" || name == "v_cndmask_b32"; + bool arith = std::holds_alternative<gfx10::Sop>(i.fields) || + std::holds_alternative<gfx10::Valu>(i.fields); + bool r; + if (arith && moves) { + r = depth > 0 && std::any_of(i.writes.begin(), i.writes.end(), [&](const auto& w) { + return this->computed_with(w.second, depth - 1); + }); + } else if (arith) { + r = !(name.starts_with("v_cmp") || name.starts_with("s_cmp")); + } else { + r = false; + } + if (r) return true; + } + } + return false; +} + +// Whether the image `src` names is one of 32-bit integers (one channel): the program has an +// integer atomic on the same table entry, which takes no other view. +bool Lower::is_counter(const Source& src) const { + auto self_entry = this->entry(src); + if (!self_entry) { + return false; + } + for (const auto& d : this->x.res->descriptors) { + const auto& i = this->x.p->blocks.at(d.site.first).insts.at(d.site.second); + if (d.role != Role::Resource) continue; + const auto* img = std::get_if<gfx10::Image>(&i.fields); + if (!img || img->dmask != 1) continue; + auto n = i.name(); + bool atomic = n == "image_atomic_add" || n == "image_atomic_sub" || + n == "image_atomic_and" || n == "image_atomic_or" || + n == "image_atomic_xor" || n == "image_atomic_smin" || + n == "image_atomic_smax" || n == "image_atomic_umin" || + n == "image_atomic_umax"; + if (!atomic) continue; + if (this->entry(d.source) == self_entry) return true; + } + return false; +} + +// Which table entry `src` is loaded from: its root parameter and byte. +std::optional<std::pair<std::size_t, std::uint32_t>> Lower::entry(const Source& src) const { + auto l = loaded_of(src); + if (!l) { + return std::nullopt; + } + auto it = this->scalar.find(l->first); + if (it == this->scalar.end() || it->second.dynamic.has_value()) return std::nullopt; + const Address& a = it->second; + return std::pair<std::size_t, std::uint32_t>{a.param, a.offset + 4 * std::uint32_t{l->second}}; +} + +// See Lower::coherent. +void Lower::find_coherent() { + std::vector<std::pair<std::size_t, std::uint32_t>> found; + for (const auto& d : this->x.res->descriptors) { + const auto& i = this->x.p->blocks.at(d.site.first).insts.at(d.site.second); + const auto* buf = std::get_if<gfx10::Buffer>(&i.fields); + if (!(buf && buf->cache.glc)) continue; + if (!i.name().starts_with("buffer_load_dword")) continue; + const UsedResource* u = this->used_kind(d.source); + if (!(u && u->kind == ResourceType::Uav())) continue; + if (auto e = this->entry(d.source)) found.push_back(*e); + } + for (const auto& e : found) this->coherent.insert(e); +} + +// The kind of a view no instruction uses (in this program, or through another load of its +// address), by what the code reads of the descriptor the load `inst` at `site` writes to the +// SGPRs from `code`: `Some(true)` for a 2D image, read only for its size, `Some(false)` for a +// structured buffer, read only for its record count. +// +// - Eight dwords are an image's. `GetDimensions` of a 2D one reads the width (dwords 1 and 2), the +// height (dword 2, bits 14-29, with one `s_bfe_u32`) and the base level or the last (dword 3); +// of an array, a cube or a volume also dword 4. +// - Four dwords at a table entry the used resources list as an SRV or UAV are a buffer's. A stride +// above 4 bytes there is an element's (a typed or raw view has at most 4): a test for a null +// view reads the record count, nothing else. +std::optional<bool> Lower::sized_view(const Inst& inst, Site site, std::uint8_t code, + std::uint32_t count) const { + auto dword = [&](std::uint8_t k) { + return inst.write(Reg::S(static_cast<std::uint8_t>(code + k))); + }; + auto read = [&](Value v) { + for (const auto& b : this->x.p->blocks) { + for (const auto& i : b.insts) { + if (std::any_of(i.reads.begin(), i.reads.end(), + [&](const auto& r) { return r.second == v; })) { + return true; + } + } + for (const auto& p : b.phis) { + if (std::find(p.args.begin(), p.args.end(), v) != p.args.end()) return true; + } + } + return false; + }; + auto only = [&](std::initializer_list<std::uint8_t> allowed) { + std::uint8_t n = static_cast<std::uint8_t>(count); // `count as u8` + for (std::uint8_t k = 0; k < n; ++k) { + bool ok = std::find(allowed.begin(), allowed.end(), k) != allowed.end(); + if (!ok) { + auto d = dword(k); + ok = !(d.has_value() && read(*d)); + } + if (!ok) return false; + } + return true; + }; + switch (count) { + case 8: { + constexpr std::uint32_t HEIGHT = (16u << 16) | 14; + auto v = dword(2); + if (!v) return std::nullopt; + bool height = false; + for (const auto& b : this->x.p->blocks) { + for (const auto& i : b.insts) { + if (i.name() != "s_bfe_u32") continue; + if (!std::any_of(i.reads.begin(), i.reads.end(), + [&](const auto& r) { return r.second == *v; })) { + continue; + } + const auto* sop = std::get_if<gfx10::Sop>(&i.fields); + if (sop && sop->src.size() > 1 && sop->src[1].kind == Operand::Kind::Literal && + sop->src[1].literal == HEIGHT) { + height = true; + break; + } + } + if (height) break; + } + if (height && only({1, 2, 3})) return true; + return std::nullopt; + } + case 4: { + const UsedResource* used = this->used_kind(make_loaded(site, 0)); + if (!used) return std::nullopt; + auto it = this->scalar.find(site); + if (it == this->scalar.end()) return std::nullopt; + const Address& a = it->second; + bool buffer = used->dwords == 4 && !a.dynamic.has_value() && + used->table_offset_dwords == a.offset / 4 && + (used->kind == ResourceType::Srv() || used->kind == ResourceType::Uav()) && + used->stride > 4 && used->stride % 4 == 0; + if (buffer && only({2})) return false; + return std::nullopt; + } + default: + return std::nullopt; + } +} + +// The title address (low dword, bits from 32 up) of the buffer view whose descriptor the scalar load at +// `site` reads from the start of a table entry, as the host tells it when it binds (USER_VIEW_ADDRESS); +// none for anything else. (The console's descriptor holds more in the second dword, the stride from bit 16 +// up; code that takes the address masks those away.) +std::optional<std::pair<V, V>> Lower::view_address(Site site) { + auto it = this->scalar.find(site); + if (it == this->scalar.end()) return std::nullopt; + const Address a = it->second; + if (a.param >= this->x.native->layout.size()) return std::nullopt; + const auto rp = this->x.native->layout[a.param]; + if (rp.root != RootType::Table() || a.dynamic.has_value() || a.offset % 32 != 0) { + return std::nullopt; + } + std::uint32_t dword = a.offset / 4; + // For equal maximum keys, prefer the last entry. + const UsedResource* used = nullptr; + for (const auto& u : this->x.native->used) { + if (u.root == RootType::Table() && u.user_data == rp.user_data && + u.table_offset_dwords <= dword) { + if (!used || u.table_offset_dwords >= used->table_offset_dwords) used = &u; + } + } + if (!used) return std::nullopt; + if (used->dwords != 4 || !(used->kind == ResourceType::Srv() || used->kind == ResourceType::Uav())) { + return std::nullopt; + } + V lo = this->host_word(RootType::Other(USER_VIEW_ADDRESS), rp.slot, dword); + V hi = this->host_word(RootType::Other(USER_VIEW_ADDRESS + 1), rp.slot, dword); + return std::pair<V, V>{lo, hi}; +} + +// `lo`, `hi` plus the instruction's byte offset `off`, with the carry. +std::pair<V, V> Lower::address_plus(V lo, V hi, std::int32_t off) { + if (off == 0) { + return {lo, hi}; + } + std::size_t c = this->cur; + Ty i32t = this->s.t.i32; + V k = this->s.m.i32(static_cast<std::uint32_t>(off)); + V sum = this->s.m.bin(c, Bin::Add, lo, k); + // Up: a carry when the sum wrapped below `lo`. Down: a borrow when it wrapped above. + V wrapped = this->s.m.cmp(c, off > 0 ? pred::IULT : pred::IUGT, sum, lo); + V one = this->s.m.cast(c, Cast::ZExt, wrapped, i32t); + V hi2 = this->s.m.bin(c, off > 0 ? Bin::Add : Bin::Sub, hi, one); + return {sum, hi2}; +} + +// Title memory at the 40-bit address `lo`, `hi` (SLOT_MEMORY): the handle of the raw view of the host copy +// holding it and the byte in that view. A page without a copy reads zeros (and drops writes) through the +// null view at the first slot, and its number is left for the host, for lanes that run (`guard`). Goes on +// in another block. With `store`, a page that is not to be written (MEMORY_READ_ONLY) is the null view. +std::pair<V, V> Lower::memory(V lo, V hi, std::optional<V> guard, bool store) { + std::size_t c = this->cur; + Ty i32t = this->s.t.i32; + Ty res = this->s.t.res_ret; + auto k = [](Lower& l, std::uint32_t v) { return l.s.m.i32(v); }; + V k16 = k(*this, 16); + V k8 = k(*this, 0xFF); + V low = this->s.m.bin(c, Bin::LShr, lo, k16); + V high = this->s.m.bin(c, Bin::And, hi, k8); + high = this->s.m.bin(c, Bin::Shl, high, k16); + V page = this->s.m.bin(c, Bin::Or, low, high); + // Inside the directory whatever the address (lanes that do not run compute one too); its last + // entry is never filled. + V last = k(*this, MEMORY_PAGES - 1); + page = this->s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, std::vector<V>{page, last}); + this->s.m.tag(page, Tag::Clamp); + V k3 = k(*this, 3); + V at = this->s.m.bin(c, Bin::Shl, page, k3); + V directory = this->s.root_srv_handle(SLOT_MEMORY); + V iu = this->s.m.undef(i32t); + V both = this->s.m.i8(3); + V align = k(*this, 4); + V entry = this->s.op(c, "rawBufferLoad.f32", Attr::ReadOnly, res, 139, + std::vector<V>{directory, at, iu, both, align}); + V copy0 = this->s.m.extract(c, entry, 0); + V start0 = this->s.m.extract(c, entry, 1); + V number = this->as_int(copy0); + V start = this->as_int(start0); + V mask = k(*this, ~MEMORY_READ_ONLY); + V copy = this->s.m.bin(c, Bin::And, number, mask); + // A page without a copy: its number, at a place by the number. In a branch: the notes lie in + // the PC's memory, and a store there with every node of every ray would be most of what a + // trace does. + V zero = k(*this, 0); + V missing = this->s.m.cmp(c, pred::EQ, copy, zero); + if (guard) { + missing = this->s.m.bin(c, Bin::And, missing, *guard); + } + V places = k(*this, MEMORY_FAULTS - 1); + V faults = this->s.root_uav_handle(SLOT_FAULTS); + auto noting = this->begin_guarded(missing); + c = this->cur; + V place = this->s.m.bin(c, Bin::URem, page, places); + V one = k(*this, 1); + place = this->s.m.bin(c, Bin::Add, place, one); + V k2 = k(*this, 2); + place = this->s.m.bin(c, Bin::Shl, place, k2); + Ty void_ = this->s.t.void_; + V mask1 = this->s.m.i8(1); + this->s.op(c, "rawBufferStore.i32", Attr::NoUnwind, void_, 140, + std::vector<V>{faults, place, iu, page, iu, iu, iu, mask1, align}); + this->end_guarded(noting, {}); + c = this->cur; + this->page_there = this->s.m.cmp(c, pred::NE, copy, zero); + if (store) { + V closed = this->s.m.cmp(c, pred::SLT, number, zero); + copy = this->s.m.select(c, closed, zero, copy); + } + V base = this->host_word(RootType::Other(USER_MEMORY_BASE), 0, 0); + V slot = this->s.m.bin(c, Bin::Add, base, copy); + // The builder's threads read what others of the dispatch wrote (a refit climbs from children + // to parents): globally coherent. + std::uint32_t coherent = spill::is_spilled(*this->x.native) ? 0x4000u : 0u; + V h = this->s.heap_handle(c, slot, false, true, {11u | 0x1000u | coherent, 0u}); + V k64k = k(*this, 0xFFFF); + V within = this->s.m.bin(c, Bin::And, lo, k64k); + V byte = this->s.m.bin(c, Bin::Add, start, within); + return {h, byte}; +} + +// The title address in the root view `src` is built around, in a program with a spilled user-data table +// (USER_ROOT_ADDRESS). +std::optional<std::pair<V, V>> Lower::root_address(const Source& src) { + const Address* address = built_address(src); + if (!address) { + return std::nullopt; + } + if (address->param >= this->x.native->layout.size()) return std::nullopt; + const auto rp = this->x.native->layout[address->param]; + if (rp.root != RootType::Descriptor() || !spill::is_spilled(*this->x.native)) { + return std::nullopt; + } + const UsedResource* used = nullptr; + for (const auto& u : this->x.native->used) { + if (u.user_data == rp.user_data) { + used = &u; + break; + } + } + if (!used) return std::nullopt; + if (!(used->kind == ResourceType::Srv() || used->kind == ResourceType::Uav())) { + return std::nullopt; + } + V lo = this->host_word(RootType::Other(USER_ROOT_ADDRESS), rp.slot, 0); + V hi = this->host_word(RootType::Other(USER_ROOT_ADDRESS + 1), rp.slot, 0); + return std::pair<V, V>{lo, hi}; +} + +// For an access through such a root view: the raw view of the host copy and the byte in it of +// the view's byte `off` (signed: an offset below the address stays below it). Lower::handle gives +// the same view for the rest of the instruction. None for any other source. Goes on in another +// block. +// shortcut: an access of several dwords is taken not to cross the end of a host copy (the +// builder's records lie on their size). +std::optional<std::pair<V, V>> Lower::root_memory(const Source& src, V off, std::optional<V> guard, + bool store) { + auto addr = this->root_address(src); + if (!addr) return std::nullopt; + auto [lo, hi0] = *addr; + std::size_t c = this->cur; + Ty i32t = this->s.t.i32; + V sum = this->s.m.bin(c, Bin::Add, lo, off); + V wrapped = this->s.m.cmp(c, pred::IULT, sum, lo); + V carry = this->s.m.cast(c, Cast::ZExt, wrapped, i32t); + V k31 = this->s.m.i32(31); + V sign = this->s.m.bin(c, Bin::AShr, off, k31); + V hi1 = this->s.m.bin(c, Bin::Add, hi0, carry); + V hi = this->s.m.bin(c, Bin::Add, hi1, sign); + if (builder_bounds()) { + // No structure is near 64 MiB (the greatest seen has 14). One whose memory was written + // over says it has gigabytes, and the builder's copy of it went through all other + // structures' memory after it and, past 2 GiB, before it. Nothing is there instead. + V below = this->s.m.i32(16u << 20); + V all = this->s.m.i32(80u << 20); + V zero = this->s.m.i32(0); + V at = this->s.m.bin(c, Bin::Add, off, below); + V near_ = this->s.m.cmp(c, pred::IULT, at, all); + sum = this->s.m.select(c, near_, sum, zero); + hi = this->s.m.select(c, near_, hi, zero); + } + auto [h, byte] = this->memory(sum, hi, guard, store); + this->root_copy = h; + return std::pair<V, V>{h, byte}; +} + +// `global_load_*`, `global_store_*` and `global_atomic_*` on title memory by address +// (`resource::MEMORY`): the address is the VGPR pair, each lane its own. +void Lower::memory_flat(const Inst& inst, std::size_t b, std::size_t i) { + const auto& f = std::get<gfx10::Flat>(inst.fields); // let Fields::Flat {..} else unreachable + bool saddr_ok = !f.saddr.has_value() || + (f.saddr->kind == Operand::Kind::Scalar && f.saddr->code == gfx10::NULL_CODE); + if (f.lds || !saddr_ok) { + fail("a global address with a scalar base"); + } + if (!(f.addr.has_value() && f.addr->kind == Operand::Kind::Vector)) { + fail("a global address not in VGPRs"); + } + std::uint8_t areg = f.addr->reg; + auto word = [&](Lower& l, std::uint8_t k) -> V { + auto v = ok_or(inst.read(Reg::V(static_cast<std::uint8_t>(areg + k))), "a global address"); + return l.i32_of(v); + }; + V lo0 = word(*this, 0); + V hi0 = word(*this, 1); + auto [lo, hi] = this->address_plus(lo0, hi0, std::int32_t{f.offset}); + auto guard = this->guard(b, i); + Ty i32t = this->s.t.i32; + Ty res = this->s.t.res_ret; + Ty void_ = this->s.t.void_; + V iu = this->s.m.undef(i32t); + V align = this->s.m.i32(4); + std::string_view name = inst.name(); + auto count = [&](std::string_view rest) -> std::uint8_t { + if (rest == "dword") return 1; + if (rest == "dwordx2") return 2; + if (rest == "dwordx3") return 3; + if (rest == "dwordx4") return 4; + fail(name.data()); + }; + if (name.starts_with("global_load_")) { + std::uint8_t n = count(name.substr(std::string_view("global_load_").size())); + if (!(f.dst.has_value() && f.dst->kind == Operand::Kind::Vector)) { + fail("a global load result"); + } + std::uint8_t reg = f.dst->reg; + auto [h, byte] = this->memory(lo, hi, guard, false); + std::size_t c = this->cur; + V mask = this->s.m.i8(static_cast<std::uint8_t>((1u << n) - 1)); + V r = this->s.op(c, "rawBufferLoad.f32", Attr::ReadOnly, res, 139, + std::vector<V>{h, byte, iu, mask, align}); + for (std::uint8_t k = 0; k < n; ++k) { + V x = this->s.m.extract(c, r, std::uint32_t{k}); + x = this->as_int(x); + this->write(inst, Reg::V(static_cast<std::uint8_t>(reg + k)), x, guard); + } + return; + } + if (name.starts_with("global_store_")) { + std::uint8_t n = count(name.substr(std::string_view("global_store_").size())); + if (!f.data) fail("global store data"); + const Operand& d = *f.data; + std::vector<V> vals = this->vgprs(inst, d, n); + auto [h, byte] = this->memory(lo, hi, guard, true); + std::vector<V> args{h, byte, iu}; + args.insert(args.end(), vals.begin(), vals.end()); + args.resize(3 + 4, iu); + args.push_back(this->s.m.i8(static_cast<std::uint8_t>((1u << n) - 1))); + args.push_back(align); + auto at = this->begin_guarded(guard); + this->s.op(this->cur, "rawBufferStore.i32", Attr::NoUnwind, void_, 140, args); + this->end_guarded(at, {}); + return; + } + if (!name.starts_with("global_atomic_")) { + fail(name.data()); + } + std::string_view op = name.substr(std::string_view("global_atomic_").size()); + if (!f.data) fail("global atomic data"); + const Operand& d = *f.data; + V v = this->vgprs(inst, d, 1).at(0); + // With `glc` the value from before comes back, in the result register the instruction names. + std::optional<std::uint8_t> back; + if (f.dst.has_value() && f.dst->kind == Operand::Kind::Vector && f.cache.glc) { + back = f.dst->reg; + } + std::optional<Value> back_v; + if (back) back_v = inst.read(Reg::V(*back)); + V old = back_v ? this->i32_of(*back_v) : this->s.m.i32(0); + auto [h, byte] = this->memory(lo, hi, guard, true); + std::size_t c = this->cur; + // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed minimum 4 and maximum 5, + // unsigned 6 and 7, exchange 8. + std::optional<std::pair<std::uint32_t, V>> simple; + if (op == "add") { + simple = std::pair<std::uint32_t, V>{0, v}; + } else if (op == "sub") { + V zero = this->s.m.i32(0); + simple = std::pair<std::uint32_t, V>{0, this->s.m.bin(c, Bin::Sub, zero, v)}; + } else if (op == "and") { + simple = std::pair<std::uint32_t, V>{1, v}; + } else if (op == "or") { + simple = std::pair<std::uint32_t, V>{2, v}; + } else if (op == "xor") { + simple = std::pair<std::uint32_t, V>{3, v}; + } else if (op == "smin") { + simple = std::pair<std::uint32_t, V>{4, v}; + } else if (op == "smax") { + simple = std::pair<std::uint32_t, V>{5, v}; + } else if (op == "umin") { + simple = std::pair<std::uint32_t, V>{6, v}; + } else if (op == "umax") { + simple = std::pair<std::uint32_t, V>{7, v}; + } else if (op == "swap") { + simple = std::pair<std::uint32_t, V>{8, v}; + } else if (op == "fmin" || op == "fmax") { + simple = std::nullopt; + } else { + fail(name.data()); + } + auto at = this->begin_guarded(guard); + V was; + if (simple) { + V code = this->s.m.i32(simple->first); + was = this->s.op(this->cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, + std::vector<V>{h, code, byte, iu, iu, simple->second}); + } else { + // A float minimum or maximum has no atomic operation on the host: the dword is exchanged + // for the smaller (larger) of itself and the value until no other thread got in between. + // Each failed pass means another one's succeeded; the limit only keeps a broken card from + // hanging. + std::size_t head = this->cur; + V mask = this->s.m.i8(1); + V first = this->s.op(head, "rawBufferLoad.f32", Attr::ReadOnly, res, 139, + std::vector<V>{h, byte, iu, mask, align}); + first = this->s.m.extract(head, first, 0); + first = this->as_int(first); + std::size_t pass = this->s.m.new_block(); + std::size_t done = this->s.m.new_block(); + this->s.m.terminate(head, Term::br(pass)); + this->cur = pass; + V seen = this->s.m.phi(pass, i32t); + V n = this->s.m.phi(pass, i32t); + Ty f32t = this->s.t.f32; + V fv = this->as_float(v); + V fseen = this->as_float(seen); + // `dx.op.binary`: FMax 35, FMin 36. + std::uint32_t pick = op == "fmin" ? 36 : 35; + V wanted = this->s.op(pass, "binary.f32", Attr::ReadNone, f32t, pick, + std::vector<V>{fseen, fv}); + wanted = this->as_int(wanted); + V found = this->s.op(pass, "atomicCompareExchange.i32", Attr::NoUnwind, i32t, 79, + std::vector<V>{h, byte, iu, iu, seen, wanted}); + V one = this->s.m.i32(1); + V n1 = this->s.m.bin(pass, Bin::Add, n, one); + V lost = this->s.m.cmp(pass, pred::NE, found, seen); + V limit = this->s.m.i32(1u << 16); + V more = this->s.m.cmp(pass, pred::IULT, n1, limit); + V again = this->s.m.bin(pass, Bin::And, lost, more); + this->s.m.terminate(pass, Term::cond_br(again, pass, done)); + V zero = this->s.m.i32(0); + this->s.m.set_phi(seen, std::vector<std::pair<V, std::size_t>>{{first, head}, {found, pass}}); + this->s.m.set_phi(n, std::vector<std::pair<V, std::size_t>>{{zero, head}, {n1, pass}}); + this->cur = done; + was = found; + } + std::vector<std::pair<V, V>> keep{{was, old}}; + was = this->end_guarded(at, keep).at(0); + if (back) { + this->write(inst, Reg::V(*back), was, std::nullopt); + } +} + +// `s_load_dword*` from title memory by address (`resource::MEMORY`): the SGPR pair plus the +// instruction's offsets. +void Lower::memory_smem(const Inst& inst) { + const auto* sm = std::get_if<gfx10::Smem>(&inst.fields); + if (!(sm && sm->data.has_value() && sm->data->kind == Operand::Kind::Scalar && + sm->base.kind == Operand::Kind::Scalar)) { + fail("a scalar load from memory"); + } + std::uint8_t code = sm->data->code; + std::uint8_t base = sm->base.code; + std::int32_t offset = sm->offset; + const Operand soffset = sm->soffset; + std::uint8_t count; + std::string_view name = inst.name(); + constexpr std::string_view PRE = "s_load_dword"; + if (!name.starts_with(PRE)) fail("a scalar memory access by address"); + std::string_view rest = name.substr(PRE.size()); + if (rest == "") { + count = 1; + } else if (rest == "x2") { + count = 2; + } else if (rest == "x4") { + count = 4; + } else if (rest == "x8") { + count = 8; + } else if (rest == "x16") { + count = 16; + } else { + fail("a scalar memory access by address"); + } + auto word = [&](Lower& l, std::uint8_t k) -> V { + auto v = ok_or(inst.read(Reg::S(static_cast<std::uint8_t>(base + k))), + "an address not in SGPRs"); + return l.i32_of(v); + }; + V lo = word(*this, 0); + V hi = word(*this, 1); + std::size_t c = this->cur; + Ty i32t = this->s.t.i32; + Ty res = this->s.t.res_ret; + if (!(soffset.kind == Operand::Kind::Scalar && soffset.code == gfx10::NULL_CODE)) { + // An offset register counts up from the address. + V so = this->operand(inst, soffset); + V sum = this->s.m.bin(c, Bin::Add, lo, so); + V carry = this->s.m.cmp(c, pred::IULT, sum, lo); + carry = this->s.m.cast(c, Cast::ZExt, carry, i32t); + hi = this->s.m.bin(c, Bin::Add, hi, carry); + lo = sum; + } + V iu = this->s.m.undef(i32t); + V align = this->s.m.i32(4); + for (std::uint8_t first = 0; first < count; first += 4) { + std::uint8_t n = std::min<std::uint8_t>(static_cast<std::uint8_t>(count - first), 4); + auto [alo, ahi] = this->address_plus(lo, hi, offset + 4 * std::int32_t{first}); + auto [h, byte] = this->memory(alo, ahi, std::nullopt, false); + std::size_t c2 = this->cur; + V mask = this->s.m.i8(static_cast<std::uint8_t>((1u << n) - 1)); + V r = this->s.op(c2, "rawBufferLoad.f32", Attr::ReadOnly, res, 139, + std::vector<V>{h, byte, iu, mask, align}); + for (std::uint8_t k = 0; k < n; ++k) { + V x = this->s.m.extract(c2, r, std::uint32_t{k}); + x = this->as_int(x); + this->write(inst, Reg::S(static_cast<std::uint8_t>(code + first + k)), x, std::nullopt); + } + } +} + +// A dword of a lane mask as a number: the ballot of the lanes' bits, taken in the block that +// writes the mask (see MaskData). +V Lower::mask_dword(Value v) { + Value lo = v; + bool high = false; + if (auto it = this->x.st->highs.find(v); it != this->x.st->highs.end()) { + lo = it->second; + high = true; + } + auto mit = this->x.st->masks.find(lo); + if (mit == this->x.st->masks.end()) fail(LANE_MASK); + Bool m = mit->second; + // A mask that holds lanes outside EXEC where it is written (the complement of one, say) is the + // ballot of the lanes that are there: all of them, where two exchanging host waves know every + // lane runs that block. + std::optional<std::size_t> made; + if (auto it = this->def_block.find(lo); it != this->def_block.end()) made = it->second; + bool whole = this->exchange.has_value() && !this->local && (!made || this->all_lanes(*made)); + if (!this->x.st->active.contains(lo) && !whole) { + if (this->exchange.has_value() && !this->local) { + need(made.value_or(0)); + } + fail(MASK_ELSEWHERE); + } + std::pair<V, V> xy; + if (auto it = this->ballots.find(lo); it != this->ballots.end()) { + xy = it->second; + } else { + std::size_t at; + auto db = this->def_block.find(lo); + if (db == this->def_block.end()) { + at = this->s.entry; // Program inputs (EXEC on entry). + } else if (db->second == this->cur_ir) { + at = this->cur; + } else { + at = ok_or(this->tail.at(db->second), "a lane mask written after its use"); + } + if (!this->balloting.insert(lo).second) { + fail("a lane mask whose lanes depend on its own value"); + } + V bit; + try { + bit = this->boolean(m, at); + } catch (const WhyFail&) { + this->balloting.erase(lo); + throw; + } + this->balloting.erase(lo); + Ty i32t = this->s.t.i32; + Ty four = this->s.m.named_struct("dx.types.fouri32", std::vector<Ty>(4, i32t)); + V r = this->s.op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, std::vector<V>{bit}); + this->s.flags |= flags::WAVE_OPS; + V x0 = this->s.m.extract(at, r, 0); + V y0 = this->s.m.extract(at, r, 1); + xy = {x0, y0}; + if (this->exchange.has_value()) { + // a host wave's ballot is its half's 32 bits: the halves exchange them + std::optional<std::size_t> b = made; // def_block.get(&lo), as above + if (this->local) { + if (!this->local_ok && !this->local_any) { + fail("a lane mask read as data in a half-wave"); + } + } else if (!std::get<1>(*this->exchange) && !(!b || this->all_lanes(*b))) { + // (a group of 32 or fewer has no other half to exchange with) + need(b.value_or(0)); + fail("a lane mask exchanged where not every lane runs"); + } + xy = this->exchange_halves(at, xy.first); + } + this->ballots.insert_or_assign(lo, xy); + } + return high ? xy.second : xy.first; +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_int_cmp_interp.cpp b/src/x2w_shader/emit/lower_int_cmp_interp.cpp new file mode 100644 index 0000000000..b246f2e8de --- /dev/null +++ b/src/x2w_shader/emit/lower_int_cmp_interp.cpp @@ -0,0 +1,997 @@ +// Integer VALU operations, compares, lane bits and interpolation. +#include <array> +#include <cstdint> +#include <initializer_list> +#include <optional> +#include <stdexcept> +#include <string> +#include <tuple> +#include <string_view> +#include <utility> +#include <variant> +#include <vector> + +#include "x2w_shader/emit/lower_impl.h" + +namespace x2w::vs::lower { + +namespace { + +bool one_of(std::string_view s, std::initializer_list<std::string_view> names) { + for (auto n : names) { + if (s == n) return true; + } + return false; +} + +} // namespace + +V Lower::integer(const Inst& inst, Why name_) { + const std::string_view name(name_); + const std::size_t c = this->cur; + auto s = [&](Lower& l, std::size_t k) { return l.src(inst, k); }; + auto k = [](Lower& l, std::uint32_t x) { return l.s.m.i32(x); }; + auto m31 = [c](Lower& l, V x) { + auto k31 = l.s.m.i32(31); + return l.s.m.bin(c, Bin::And, x, k31); + }; + if (one_of(name, {"v_and_b32", "v_or_b32", "v_xor_b32", "v_add_nc_u32", "v_sub_nc_u32", + "v_subrev_nc_u32", "v_mul_lo_u32"})) { + auto a = s(*this, 0); + auto b = s(*this, 1); + Bin op; + if (name == "v_and_b32") { + op = Bin::And; + } else if (name == "v_or_b32") { + op = Bin::Or; + } else if (name == "v_xor_b32") { + op = Bin::Xor; + } else if (name == "v_add_nc_u32") { + op = Bin::Add; + } else if (name == "v_sub_nc_u32") { + op = Bin::Sub; + } else if (name == "v_subrev_nc_u32") { + op = Bin::Sub; + std::swap(a, b); + } else { + op = Bin::Mul; + } + return this->s.m.bin(c, op, a, b); + } + if (name == "v_xnor_b32") { + auto a = s(*this, 0); + auto b = s(*this, 1); + auto x = this->s.m.bin(c, Bin::Xor, a, b); + auto ones = k(*this, 0xFFFF'FFFFu); + return this->s.m.bin(c, Bin::Xor, x, ones); + } + if (name == "v_not_b32") { + auto a = s(*this, 0); + auto ones = k(*this, 0xFFFF'FFFFu); + return this->s.m.bin(c, Bin::Xor, a, ones); + } + if (one_of(name, {"v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32"})) { + auto sh = s(*this, 0); + auto a = s(*this, 1); + sh = m31(*this, sh); + Bin op = name == "v_lshlrev_b32" ? Bin::Shl : name == "v_lshrrev_b32" ? Bin::LShr : Bin::AShr; + return this->s.m.bin(c, op, a, sh); + } + if (one_of(name, {"v_lshl_add_u32", "v_lshl_or_b32", "v_add_lshl_u32", "v_and_or_b32", "v_or3_b32", + "v_xad_u32", "v_add3_u32", "v_xor3_b32"})) { + auto a = s(*this, 0); + auto b = s(*this, 1); + auto d = s(*this, 2); + if (name == "v_lshl_add_u32" || name == "v_lshl_or_b32") { + b = m31(*this, b); + auto t = this->s.m.bin(c, Bin::Shl, a, b); + Bin op = name == "v_lshl_add_u32" ? Bin::Add : Bin::Or; + return this->s.m.bin(c, op, t, d); + } + if (name == "v_add_lshl_u32") { + auto t = this->s.m.bin(c, Bin::Add, a, b); + d = m31(*this, d); + return this->s.m.bin(c, Bin::Shl, t, d); + } + Bin o1, o2; + if (name == "v_and_or_b32") { + o1 = Bin::And, o2 = Bin::Or; + } else if (name == "v_or3_b32") { + o1 = Bin::Or, o2 = Bin::Or; + } else if (name == "v_xad_u32") { + o1 = Bin::Xor, o2 = Bin::Add; + } else if (name == "v_add3_u32") { + o1 = Bin::Add, o2 = Bin::Add; + } else { + o1 = Bin::Xor, o2 = Bin::Xor; + } + auto t = this->s.m.bin(c, o1, a, b); + return this->s.m.bin(c, o2, t, d); + } + if (name == "v_mul_u32_u24" || name == "v_mul_i32_i24") { + auto a = s(*this, 0); + auto b = s(*this, 1); + auto sh = k(*this, 8); + Bin op = name == "v_mul_i32_i24" ? Bin::AShr : Bin::LShr; + a = this->s.m.bin(c, Bin::Shl, a, sh); + a = this->s.m.bin(c, op, a, sh); + b = this->s.m.bin(c, Bin::Shl, b, sh); + b = this->s.m.bin(c, op, b, sh); + return this->s.m.bin(c, Bin::Mul, a, b); + } + if (name == "v_mul_hi_u32_u24" || name == "v_mul_hi_i32_i24") { + // The high dword of the same 48-bit product: the low 24 bits of each operand, zero- or + // sign-extended, multiplied. + auto a = s(*this, 0); + auto b = s(*this, 1); + bool signed_ = name == "v_mul_hi_i32_i24"; + auto sh = k(*this, 8); + Bin op = signed_ ? Bin::AShr : Bin::LShr; + a = this->s.m.bin(c, Bin::Shl, a, sh); + a = this->s.m.bin(c, op, a, sh); + b = this->s.m.bin(c, Bin::Shl, b, sh); + b = this->s.m.bin(c, op, b, sh); + return this->mul_hi(a, b, signed_); + } + if (name == "v_bfe_u32" || name == "v_bfe_i32") { + auto a = s(*this, 0); + auto off = s(*this, 1); + auto w = s(*this, 2); + w = m31(*this, w); + return this->bfe(a, off, w, name == "v_bfe_i32"); + } + if (name == "v_bfi_b32") { + auto m = s(*this, 0); + auto a = s(*this, 1); + auto b = s(*this, 2); + auto ones = k(*this, 0xFFFF'FFFFu); + auto nm = this->s.m.bin(c, Bin::Xor, m, ones); + auto x = this->s.m.bin(c, Bin::And, m, a); + auto y = this->s.m.bin(c, Bin::And, nm, b); + return this->s.m.bin(c, Bin::Or, x, y); + } + if (one_of(name, {"v_max_i32", "v_min_i32", "v_max_u32", "v_min_u32"})) { + auto a = s(*this, 0); + auto b = s(*this, 1); + std::uint8_t p = name == "v_max_i32" ? pred::SGT + : name == "v_min_i32" ? pred::SLT + : name == "v_max_u32" ? pred::IUGT + : pred::IULT; + auto t = this->s.m.cmp(c, p, a, b); + return this->s.m.select(c, t, a, b); + } + if (name == "v_mul_hi_u32" || name == "v_mul_hi_i32") { + auto a = s(*this, 0); + auto b = s(*this, 1); + return this->mul_hi(a, b, name == "v_mul_hi_i32"); + } + if (name == "v_alignbit_b32" || name == "v_alignbyte_b32") { + // The low dword of {a, b} >> shift. + auto a = s(*this, 0); + auto b = s(*this, 1); + auto sh = s(*this, 2); + if (name == "v_alignbyte_b32") { + auto three = k(*this, 3); + auto t = this->s.m.bin(c, Bin::And, sh, three); + auto k3 = k(*this, 3); + sh = this->s.m.bin(c, Bin::Shl, t, k3); + } else { + sh = m31(*this, sh); + } + auto k32 = k(*this, 32); + auto lo = this->s.m.bin(c, Bin::LShr, b, sh); + auto left = this->s.m.bin(c, Bin::Sub, k32, sh); + left = m31(*this, left); + auto hi = this->s.m.bin(c, Bin::Shl, a, left); + auto zero = k(*this, 0); + auto none = this->s.m.cmp(c, pred::EQ, sh, zero); + hi = this->s.m.select(c, none, zero, hi); + return this->s.m.bin(c, Bin::Or, lo, hi); + } + if (name == "v_bfrev_b32") { + auto a = s(*this, 0); + return this->s.op(c, "unary.i32", Attr::ReadNone, this->s.t.i32, 30, std::vector<V>{a}); + } + if (name == "v_bcnt_u32_b32") { + auto a = s(*this, 0); + auto b = s(*this, 1); + auto n = this->s.op(c, "unaryBits.i32", Attr::ReadNone, this->s.t.i32, 31, std::vector<V>{a}); + return this->s.m.bin(c, Bin::Add, n, b); + } + if (name == "v_mad_u32_u24" || name == "v_mad_i32_i24") { + auto a = s(*this, 0); + auto b = s(*this, 1); + auto d = s(*this, 2); + auto sh = k(*this, 8); + Bin op = name == "v_mad_i32_i24" ? Bin::AShr : Bin::LShr; + a = this->s.m.bin(c, Bin::Shl, a, sh); + a = this->s.m.bin(c, op, a, sh); + b = this->s.m.bin(c, Bin::Shl, b, sh); + b = this->s.m.bin(c, op, b, sh); + auto m = this->s.m.bin(c, Bin::Mul, a, b); + return this->s.m.bin(c, Bin::Add, m, d); + } + if (one_of(name, {"v_sad_u8", "v_sad_hi_u8", "v_sad_u16", "v_sad_u32", "v_msad_u8"})) { + // src2 plus the sum of the unsigned differences |a - b| of the operands' bytes, halves or + // whole dwords, wrapping at 32 bits. v_sad_hi_u8 adds the sum shifted to the high half; + // v_msad_u8 leaves out a byte whose mask byte (src1) is 0. + auto a = s(*this, 0); + auto b = s(*this, 1); + auto d = s(*this, 2); + std::uint32_t width, parts; + if (name == "v_sad_u16") { + width = 16, parts = 2; + } else if (name == "v_sad_u32") { + width = 32, parts = 1; + } else { + width = 8, parts = 4; + } + auto zero = k(*this, 0); + auto sum = zero; + for (std::uint32_t i = 0; i < parts; ++i) { + auto x = a; + auto y = b; + if (width < 32) { + auto sh = k(*this, width * i); + auto mask = k(*this, (1u << width) - 1); + x = this->s.m.bin(c, Bin::LShr, x, sh); + x = this->s.m.bin(c, Bin::And, x, mask); + y = this->s.m.bin(c, Bin::LShr, y, sh); + y = this->s.m.bin(c, Bin::And, y, mask); + } + auto above = this->s.m.cmp(c, pred::IUGT, x, y); + auto hi = this->s.m.select(c, above, x, y); + auto lo = this->s.m.select(c, above, y, x); + auto diff = this->s.m.bin(c, Bin::Sub, hi, lo); + if (name == "v_msad_u8") { + auto masked = this->s.m.cmp(c, pred::NE, y, zero); + diff = this->s.m.select(c, masked, diff, zero); + } + sum = this->s.m.bin(c, Bin::Add, sum, diff); + } + if (name == "v_sad_hi_u8") { + auto k16 = k(*this, 16); + sum = this->s.m.bin(c, Bin::Shl, sum, k16); + } + return this->s.m.bin(c, Bin::Add, sum, d); + } + if (one_of(name, {"v_min3_i32", "v_max3_i32", "v_min3_u32", "v_max3_u32", "v_med3_i32", "v_med3_u32"})) { + auto a = s(*this, 0); + auto b = s(*this, 1); + auto d = s(*this, 2); + bool signed_ = name.ends_with("i32"); + std::uint8_t lt = signed_ ? pred::SLT : pred::IULT; + std::uint8_t gt = signed_ ? pred::SGT : pred::IUGT; + auto pick = [c](Lower& l, std::uint8_t p, V x, V y) { + auto t = l.s.m.cmp(c, p, x, y); + return l.s.m.select(c, t, x, y); + }; + auto kind = name.substr(2, 4); + if (kind == "min3") { + auto t = pick(*this, lt, a, b); + return pick(*this, lt, t, d); + } + if (kind == "max3") { + auto t = pick(*this, gt, a, b); + return pick(*this, gt, t, d); + } + auto lo = pick(*this, lt, a, b); + auto hi = pick(*this, gt, a, b); + auto t = pick(*this, lt, hi, d); + return pick(*this, gt, lo, t); + } + if (name == "v_perm_b32") { + // Byte i of the result is byte S of {src0, src1} (src1 the low dword) for selector byte S + // below 8; 8-11 repeat the sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00, + // higher 0xFF. + const auto& v = std::get<gfx10::Valu>(inst.fields); + std::uint32_t sel; + const Operand* s2 = v.src.size() > 2 ? &v.src[2] : nullptr; + if (s2 && s2->kind == Operand::Kind::Literal) { + sel = s2->literal; + } else if (s2 && s2->kind == Operand::Kind::Const) { + sel = ok_or(resource::inline_constant(s2->code), name_); + } else { + // A computed selector: each byte picked at run time. + auto a = s(*this, 0); + auto b = s(*this, 1); + auto sv = s(*this, 2); + auto r = k(*this, 0); + for (std::uint32_t i = 0; i < 4; ++i) { + auto sh = k(*this, 8 * i); + auto ff = k(*this, 0xFF); + auto selv = this->s.m.bin(c, Bin::LShr, sv, sh); + selv = this->s.m.bin(c, Bin::And, selv, ff); + // Select a dword and a byte within it. Later selects handle codes 8 and above. + auto four = k(*this, 4); + auto zero = k(*this, 0); + auto high = this->s.m.bin(c, Bin::And, selv, four); + high = this->s.m.cmp(c, pred::NE, high, zero); + auto word = this->s.m.select(c, high, a, b); + auto three = k(*this, 3); + auto index = this->s.m.bin(c, Bin::And, selv, three); + auto bits = this->s.m.bin(c, Bin::Shl, index, three); + auto x = this->s.m.bin(c, Bin::LShr, word, bits); + auto byte = this->s.m.bin(c, Bin::And, x, ff); + // 8-11: the sign of bytes 1, 3 of src1, then of src0. + const std::array<std::tuple<std::uint32_t, V, std::uint32_t>, 4> signs{ + {{8, b, 15}, {9, b, 31}, {10, a, 15}, {11, a, 31}}}; + for (const auto& [n, src, bit] : signs) { + auto left = k(*this, 31 - bit); + auto t = this->s.m.bin(c, Bin::Shl, src, left); + auto k31 = k(*this, 31); + t = this->s.m.bin(c, Bin::AShr, t, k31); + t = this->s.m.bin(c, Bin::And, t, ff); + auto kn = k(*this, n); + auto is = this->s.m.cmp(c, pred::EQ, selv, kn); + byte = this->s.m.select(c, is, t, byte); + } + auto k12 = k(*this, 12); + auto z = k(*this, 0); + auto is12 = this->s.m.cmp(c, pred::EQ, selv, k12); + byte = this->s.m.select(c, is12, z, byte); + auto above = this->s.m.cmp(c, pred::IUGT, selv, k12); + byte = this->s.m.select(c, above, ff, byte); + auto at = k(*this, 8 * i); + byte = this->s.m.bin(c, Bin::Shl, byte, at); + r = this->s.m.bin(c, Bin::Or, r, byte); + } + return r; + } + auto a = s(*this, 0); + auto b = s(*this, 1); + auto r = k(*this, 0); + for (std::uint32_t i = 0; i < 4; ++i) { + std::uint32_t pick = (sel >> (8 * i)) & 0xFF; + V byte; + if (pick <= 7) { + V src = pick < 4 ? b : a; + std::uint32_t n = pick < 4 ? pick : pick - 4; + auto sh = k(*this, 8 * n); + auto t = this->s.m.bin(c, Bin::LShr, src, sh); + auto ff = k(*this, 0xFF); + byte = this->s.m.bin(c, Bin::And, t, ff); + } else if (pick <= 11) { + V src = pick < 10 ? b : a; + std::uint32_t bit = pick % 2 == 0 ? 15 : 31; + auto left = k(*this, 31 - bit); + auto t = this->s.m.bin(c, Bin::Shl, src, left); + auto k31 = k(*this, 31); + t = this->s.m.bin(c, Bin::AShr, t, k31); + auto ff = k(*this, 0xFF); + byte = this->s.m.bin(c, Bin::And, t, ff); + } else if (pick == 12) { + continue; + } else { + byte = k(*this, 0xFF); + } + auto at = k(*this, 8 * i); + byte = this->s.m.bin(c, Bin::Shl, byte, at); + r = this->s.m.bin(c, Bin::Or, r, byte); + } + return r; + } + if (name == "v_bfm_b32") { + // ((1 << src0[4:0]) - 1) << src1[4:0] + auto a = s(*this, 0); + auto b = s(*this, 1); + auto one = k(*this, 1); + a = m31(*this, a); + b = m31(*this, b); + auto m = this->s.m.bin(c, Bin::Shl, one, a); + m = this->s.m.bin(c, Bin::Sub, m, one); + return this->s.m.bin(c, Bin::Shl, m, b); + } + if (name == "v_cvt_pk_u8_f32") { + // src0 rounded to nearest even and saturated to a byte, into byte src1[1:0] of src2. + auto f = this->fsrc(inst, 0); + auto b = s(*this, 1); + auto d = s(*this, 2); + f = this->unary(26, f); + auto zero = this->s.m.f32(0); + auto max = this->s.m.f32(f32_bits(255.0f)); + f = this->binary(35, f, zero); + f = this->binary(36, f, max); + auto x = this->s.m.cast(c, Cast::FpToUi, f, this->s.t.i32); + auto three = k(*this, 3); + auto k3 = k(*this, 3); + auto sh = this->s.m.bin(c, Bin::And, b, three); + sh = this->s.m.bin(c, Bin::Shl, sh, k3); + x = this->s.m.bin(c, Bin::Shl, x, sh); + auto ff = k(*this, 0xFF); + auto hole = this->s.m.bin(c, Bin::Shl, ff, sh); + auto ones = k(*this, 0xFFFF'FFFFu); + hole = this->s.m.bin(c, Bin::Xor, hole, ones); + d = this->s.m.bin(c, Bin::And, d, hole); + return this->s.m.bin(c, Bin::Or, d, x); + } + if (name == "v_ffbl_b32") { + // -1 for zero, as DXIL's first-bit-low. + auto a = s(*this, 0); + return this->s.op(c, "unaryBits.i32", Attr::ReadNone, this->s.t.i32, 32, std::vector<V>{a}); + } + if (name == "v_mbcnt_lo_u32_b32" || name == "v_mbcnt_hi_u32_b32") { + // Bits of the mask's low (high) half below this lane, plus src1: with an all-ones mask, + // the lane index. + auto a = s(*this, 0); + auto b = s(*this, 1); + // Mesh lanes are the console's by construction; pixel and vertex lanes are the host's, as + // their masks are. + if (this->mask_data == MaskData::Host) { + // Host lanes: the mask must be one (a ballot) or all lanes. + const auto& v = std::get<gfx10::Valu>(inst.fields); + bool host = false; + if (!v.src.empty()) { + const Operand& first = v.src.front(); + if (first.kind == Operand::Kind::Const && first.code == 193) { + host = true; + } else if (first.kind == Operand::Kind::Scalar) { + auto m = inst.read(Reg::S(first.code)); + host = m && (this->x.st->masks.contains(*m) || this->x.st->highs.contains(*m)); + } + } + if (!host) { + fail("v_mbcnt of a mask that is no ballot (console lane layout)"); + } + this->s.flags |= flags::WAVE_OPS; + } else if (!this->s.mesh) { + this->cross_lane(false); + } + auto lane = this->console_lane(); + V below; + if (name == "v_mbcnt_lo_u32_b32") { + below = lane; + } else { + auto k32 = k(*this, 32); + auto z = k(*this, 0); + auto t = this->s.m.bin(c, Bin::Sub, lane, k32); + auto low = this->s.m.cmp(c, pred::IULT, lane, k32); + below = this->s.m.select(c, low, z, t); + } + // (1 << below) - 1, all ones from 32 on. + auto one = k(*this, 1); + auto k32 = k(*this, 32); + auto ones = k(*this, 0xFFFF'FFFFu); + auto sh = m31(*this, below); + auto m = this->s.m.bin(c, Bin::Shl, one, sh); + m = this->s.m.bin(c, Bin::Sub, m, one); + auto full = this->s.m.cmp(c, pred::IUGE, below, k32); + m = this->s.m.select(c, full, ones, m); + auto x = this->s.m.bin(c, Bin::And, a, m); + auto n = this->s.op(c, "unaryBits.i32", Attr::ReadNone, this->s.t.i32, 31, std::vector<V>{x}); + return this->s.m.bin(c, Bin::Add, n, b); + } + fail(name_); +} + +void Lower::compare(const Inst& inst, std::string_view rest) { + auto us = rest.rfind('_'); + if (us == std::string_view::npos) fail("a compare"); + const std::string_view op = rest.substr(0, us); + const std::string_view ty = rest.substr(us + 1); + const std::size_t c = this->cur; + V r; + if ((ty == "f32" || ty == "f16") && op == "class") { + // Bit k of src1 tests class k: signalling NaN, quiet NaN, -inf, -normal, -denormal, -0, + // +0, +denormal, +normal, +inf. + bool f16 = ty == "f16"; + V x; + if (f16) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + auto h = this->half_src(inst, 0); + if ((v.abs & 1) != 0) { + auto m = this->s.m.i32(0x7FFF); + h = this->s.m.bin(c, Bin::And, h, m); + } + if ((v.neg & 1) != 0) { + auto sg = this->s.m.i32(0x8000); + h = this->s.m.bin(c, Bin::Xor, h, sg); + } + x = h; + } else { + auto f = this->fsrc(inst, 0); + x = this->as_int(f); + } + auto mask = this->src(inst, 1); + auto k = [](Lower& l, std::uint32_t v) { return l.s.m.i32(v); }; + std::uint32_t exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit; + if (f16) { + exp_sh = 10, sign_sh = 15, exp_mask = 0x1F, mant_mask = 0x03FF, quiet_bit = 0x0200; + } else { + exp_sh = 23, sign_sh = 31, exp_mask = 0xFF, mant_mask = 0x7F'FFFF, quiet_bit = 0x40'0000; + } + auto k_exp = k(*this, exp_sh); + auto k_sign = k(*this, sign_sh); + auto k_emax = k(*this, exp_mask); + auto mant = k(*this, mant_mask); + auto quiet = k(*this, quiet_bit); + auto e = this->s.m.bin(c, Bin::LShr, x, k_exp); + e = this->s.m.bin(c, Bin::And, e, k_emax); + auto m = this->s.m.bin(c, Bin::And, x, mant); + auto neg = this->s.m.bin(c, Bin::LShr, x, k_sign); + auto zero = k(*this, 0); + auto e0 = this->s.m.cmp(c, pred::EQ, e, zero); + auto emax = this->s.m.cmp(c, pred::EQ, e, k_emax); + auto m0 = this->s.m.cmp(c, pred::EQ, m, zero); + auto q = this->s.m.bin(c, Bin::And, x, quiet); + q = this->s.m.cmp(c, pred::NE, q, zero); + // Positive classes 6-9; negative ones are 11 minus those. + auto normal = k(*this, 8); + auto inf = k(*this, 9); + auto zero_c = k(*this, 6); + auto denorm = k(*this, 7); + auto t = this->s.m.select(c, m0, zero_c, denorm); + t = this->s.m.select(c, e0, t, normal); + t = this->s.m.select(c, emax, inf, t); + auto eleven = k(*this, 11); + auto mirrored = this->s.m.bin(c, Bin::Sub, eleven, t); + auto is_neg = this->s.m.cmp(c, pred::NE, neg, zero); + t = this->s.m.select(c, is_neg, mirrored, t); + auto one = k(*this, 1); + auto snan = k(*this, 0); + auto nan_class = this->s.m.select(c, q, one, snan); + auto yes = this->s.m.bool_(true); + auto nan = this->s.m.bin(c, Bin::Xor, m0, yes); + nan = this->s.m.bin(c, Bin::And, nan, emax); + t = this->s.m.select(c, nan, nan_class, t); + auto bit = this->s.m.bin(c, Bin::LShr, mask, t); + bit = this->s.m.bin(c, Bin::And, bit, one); + r = this->s.m.cmp(c, pred::NE, bit, zero); + } else if (ty == "f32" || ty == "f16") { + V a, b; + if (ty == "f16") { + a = this->half_fsrc(inst, 0); + b = this->half_fsrc(inst, 1); + } else { + a = this->fsrc(inst, 0); + b = this->fsrc(inst, 1); + } + if (op == "lg") { + // Ordered and not equal, false for a NaN, as `olt | ogt`. `fcmp one` means the same, + // but the AMD D3D12 driver runs it as unordered (true for a NaN) where NVIDIA and + // WARP do not; olt and ogt agree on all three. + auto lt = this->s.m.cmp(c, pred::OLT, a, b); + auto gt = this->s.m.cmp(c, pred::OGT, a, b); + r = this->s.m.bin(c, Bin::Or, lt, gt); + } else { + std::uint8_t p; + if (op == "f") { + p = pred::FALSE_; + } else if (op == "lt") { + p = pred::OLT; + } else if (op == "eq") { + p = pred::OEQ; + } else if (op == "le") { + p = pred::OLE; + } else if (op == "gt") { + p = pred::OGT; + } else if (op == "ge") { + p = pred::OGE; + } else if (op == "o") { + p = pred::ORD; + } else if (op == "u") { + p = pred::UNO; + } else if (op == "nge") { + p = pred::ULT; + } else if (op == "nlg") { + p = pred::UEQ; + } else if (op == "ngt") { + p = pred::ULE; + } else if (op == "nle") { + p = pred::UGT; + } else if (op == "neq") { + p = pred::UNE; + } else if (op == "nlt") { + p = pred::UGE; + } else if (op == "tru") { + p = pred::TRUE_; + } else { + fail(inst.name().data()); + } + r = this->s.m.cmp(c, p, a, b); + } + } else if (ty == "u64" || ty == "i64") { + auto a = this->src64(inst, 0); + auto b = this->src64(inst, 1); + bool signed_ = ty == "i64"; + std::uint8_t p; + if (op == "eq") { + p = pred::EQ; + } else if (op == "ne" || op == "lg") { + p = pred::NE; + } else if (op == "lt") { + p = signed_ ? pred::SLT : pred::IULT; + } else if (op == "le") { + p = signed_ ? pred::SLE : pred::IULE; + } else if (op == "gt") { + p = signed_ ? pred::SGT : pred::IUGT; + } else if (op == "ge") { + p = signed_ ? pred::SGE : pred::IUGE; + } else { + fail("a 64-bit compare"); + } + r = this->s.m.cmp(c, p, a, b); + } else if (ty == "u32" || ty == "i32" || ty == "u16" || ty == "i16") { + V a, b; + if (ty.ends_with("16")) { + a = this->half_src(inst, 0); + b = this->half_src(inst, 1); + if (ty == "i16") { + auto k16 = this->s.m.i32(16); + for (V* x : {&a, &b}) { + auto t = this->s.m.bin(c, Bin::Shl, *x, k16); + *x = this->s.m.bin(c, Bin::AShr, t, k16); + } + } + } else { + a = this->src(inst, 0); + b = this->src(inst, 1); + } + bool signed_ = ty == "i32" || ty == "i16"; + std::uint8_t p; + if (op == "eq") { + p = pred::EQ; + } else if (op == "ne" || op == "lg") { + p = pred::NE; + } else if (op == "lt") { + p = signed_ ? pred::SLT : pred::IULT; + } else if (op == "le") { + p = signed_ ? pred::SLE : pred::IULE; + } else if (op == "gt") { + p = signed_ ? pred::SGT : pred::IUGT; + } else if (op == "ge") { + p = signed_ ? pred::SGE : pred::IUGE; + } else if (op == "f" || op == "t") { + this->lane(inst, op == "t"); + return; + } else { + fail("an integer compare"); + } + r = this->s.m.cmp(c, p, a, b); + } else { + fail(inst.name().data()); + } + this->lane_bits_for(inst, r); +} + +void Lower::lane(const Inst& inst, std::optional<bool> value) { + auto b = this->s.m.bool_(value == std::optional<bool>(true)); + this->lane_bits_for(inst, b); +} + +void Lower::lane_bits_for(const Inst& inst, V r) { + const auto* v = std::get_if<gfx10::Valu>(&inst.fields); + if (!v) return; + std::optional<std::uint8_t> code; + if (inst.name().starts_with("v_cmpx")) { + code = ir::EXEC; + } else if (v->dst && v->dst->kind == Operand::Kind::Scalar) { + code = v->dst->code; + } + if (code) { + if (auto lo = inst.write(Reg::S(*code))) { + this->lane_bits.insert_or_assign(*lo, r); + } + } + for (const auto& [_, w] : inst.writes) { + this->vals.try_emplace(w, Val::Missing("a lane mask read as data")); + } +} + +void Lower::interp(const Inst& inst, Site site) { + auto found = this->interps.find(site); + if (found == this->interps.end()) { + // The first half of a pair: its second half interpolates the attribute itself, so nothing + // needs this half's partial sum. But an f16 second half that writes the high half of the + // register this one wrote keeps the low half as it was (the console compiler reuses the + // register; the low half is not read), so the register needs a value: 0. + auto name = inst.name(); + if (name == "v_interp_p1_f32" || name == "v_interp_p1ll_f16") { + std::optional<Operand> dst; + if (const auto* vi = std::get_if<gfx10::Vintrp>(&inst.fields)) { + dst = vi->dst; + } else if (const auto* va = std::get_if<gfx10::Valu>(&inst.fields)) { + dst = va->dst; + } + if (dst && dst->kind == Operand::Kind::Vector) { + auto zero = this->s.m.i32(0); + this->write(inst, Reg::V(dst->reg), zero, std::nullopt); + return; + } + } + fail(FIRST_HALF); + } + const Interp& interp = *found->second; + const auto name = inst.name(); + Operand dst; + std::optional<Operand> src; + if (const auto* vi = std::get_if<gfx10::Vintrp>(&inst.fields)) { + dst = vi->dst; + src = vi->src; + } else if (const auto* va = std::get_if<gfx10::Valu>(&inst.fields)) { + if (va->abs != 0 || va->neg != 0) { + fail("interpolation operand modifiers"); + } + dst = ok_or(va->dst, "an interpolation"); + if (va->src.size() > 1) src = va->src[1]; + } else { + throw std::logic_error("unreachable: interp fields"); + } + if (dst.kind != Operand::Kind::Vector) { + fail("an interpolation"); + } + const std::uint8_t reg = dst.reg; + // A float operand of the instruction. + auto float_ = [&inst](Lower& l, std::optional<Operand> op) -> V { + auto o = ok_or(op, "an interpolation operand"); + auto x = l.operand(inst, o); + return l.as_float(x); + }; + // What the result adds to the evaluated channel (a second half's first half, when the halves + // evaluate on their own). + std::optional<V> add; + io::Attribute attribute; + Eval eval; + if (const auto* in = interp.kind == io::Interp::Kind::Interpolated ? &interp : nullptr) { + attribute = in->attribute; + auto mode = ok_or(interp_mode(in->barycentric), "pull-model interpolation"); + if (this->per_vertex(attribute.row)) { + // The element is read per vertex elsewhere, so it is constant: weigh its vertices + // with SV_Barycentrics. + std::array<std::optional<V>, 2> ij{}; + for (std::size_t index = 0; index < ij.size(); ++index) { + Val bv = this->barycentric(in->barycentric, static_cast<std::uint8_t>(index)); + V xv; + if (bv.is_i32()) { + xv = bv.v; + } else if (bv.is_missing()) { + fail(bv.why); + } else { + throw std::logic_error("unreachable: a barycentric bit"); + } + ij[index] = this->as_float(xv); + } + eval = Eval::Weights(true, ij[0], ij[1]); + } else { + eval = Eval::Mode(mode); + } + } else if (const auto* vx = interp.kind == io::Interp::Kind::Vertex ? &interp : nullptr) { + attribute = vx->attribute; + if (vx->vertex == 2) { + // P0, the provoking vertex: a flat (nointerpolation) input. + eval = Eval::Mode(1); + } else if (this->interpolated(attribute.row)) { + // P10 and P20: what the first and second halves weigh, P1 - P0 and P2 - P0, which is + // what the hardware holds for an attribute the program also interpolates. + std::optional<V> one = this->s.m.f32(f32_bits(1.0f)); + std::optional<V> i, j; + if (vx->vertex == 0) { + i = one; + } else { + j = one; + } + eval = Eval::Weights(false, i, j); + } else { + fail("a non-provoking vertex value"); + } + } else { + const auto& wt = interp; // Weighted + attribute = wt.attribute; + if (name.starts_with("v_interp_p1")) { + // A half of an interpolation with computed i or j: P0 + i P10, or the old dst (f16: + // the third operand) + j P20. + std::optional<V> i = float_(*this, src); + eval = Eval::Weights(true, i, std::nullopt); + } else { + std::optional<Operand> old; + if (const auto* va = std::get_if<gfx10::Valu>(&inst.fields)) { + if (va->src.size() > 2) old = va->src[2]; + } else { + old = dst; + } + add = float_(*this, old); + std::optional<V> j = float_(*this, src); + eval = Eval::Weights(false, std::nullopt, j); + } + } + // (pack2, packs) of a 16-bit input row. + std::optional<std::pair<bool, std::vector<std::pair<std::uint8_t, std::optional<std::uint8_t>>>>> packing; + if (const auto* ps = std::get_if<native::PsIo>(&this->x.native->io)) { + for (const auto& i : ps->inputs) { + if (i.row == attribute.row && i.fp16) { + std::vector<std::pair<std::uint8_t, std::optional<std::uint8_t>>> packs; + if (i.pack2) { + packs = input_packs(this->x.native->io, this->s.inputs); + } + packing.emplace(i.pack2, std::move(packs)); + break; + } + } + } + const bool f16 = name.ends_with("_f16"); + // The evaluated channel plus `add`, as a float. + auto total = [eval, add](Lower& l, std::uint8_t row, std::uint8_t ch) -> V { + auto xv = l.eval_channel(row, ch, eval); + xv = l.as_float(xv); + if (add) return l.s.m.bin(l.cur, Bin::Add, *add, xv); + return xv; + }; + V x; + if (!packing) { + if (f16 || attribute.high) fail("a 16-bit read of a 32-bit input"); + auto t = total(*this, attribute.row, attribute.channel); + x = this->as_int(t); + } else { + const bool pack2 = packing->first; + const auto& packs = packing->second; + // 16-bit values: one in the low half of each dword, or two per dword (`packed_half`); the + // host's are 32-bit floats. + auto half = [&](Lower& l, std::uint8_t h) -> std::optional<V> { + std::optional<std::pair<std::uint8_t, std::uint8_t>> srcp; + if (pack2) { + srcp = packed_half(l.s.inputs, packs, attribute.row, h); + } else if (h % 2 == 0) { + srcp = std::pair<std::uint8_t, std::uint8_t>{attribute.row, static_cast<std::uint8_t>(h / 2)}; + } + if (srcp) return total(l, srcp->first, srcp->second); + return std::nullopt; + }; + auto to_f16 = [](Lower& l, V f) { + auto i32t = l.s.t.i32; + return l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, std::vector<V>{f}); + }; + const std::uint8_t h = static_cast<std::uint8_t>(2 * attribute.channel + (attribute.high ? 1 : 0)); + const std::size_t c = this->cur; + if (name == "v_interp_p1ll_f16") { + // An f32 result from 16-bit vertex values. + auto f = ok_or(half(*this, h), "a packed input half no element holds"); + x = this->as_int(f); + } else if (f16) { + auto f = ok_or(half(*this, h), "a packed input half no element holds"); + if (const auto* v = std::get_if<gfx10::Valu>(&inst.fields)) { + // Apply omod and clamp before the single rounding to 16 bits. op_sel[3] selects the destination half. + const std::uint8_t omod = v->omod; + const bool clamp = v->clamp; + if (omod != 0) { + const float factor = std::array<float, 4>{1.0f, 2.0f, 4.0f, 0.5f}.at(omod); + auto kf = this->s.m.f32(f32_bits(factor)); + f = this->s.m.bin(c, Bin::Mul, f, kf); + } + if (clamp) { + f = this->unary(7, f); + } + auto lo = to_f16(*this, f); + this->write_half(inst, lo, std::nullopt); + return; + } + auto lo = to_f16(*this, f); + x = this->low_half(inst, reg, lo); + } else if (eval.kind == Eval::Kind::Mode && eval.mode == 1) { + // The whole dword of a flat input: both halves. + const std::uint8_t h0 = static_cast<std::uint8_t>(2 * attribute.channel); + auto z = this->s.m.i32(0); + V lo, hi; + if (auto f = half(*this, h0)) { + lo = to_f16(*this, *f); + } else { + lo = z; + } + if (auto f = half(*this, static_cast<std::uint8_t>(h0 + 1))) { + hi = to_f16(*this, *f); + } else { + hi = z; + } + auto k16 = this->s.m.i32(16); + hi = this->s.m.bin(c, Bin::Shl, hi, k16); + x = this->s.m.bin(c, Bin::Or, lo, hi); + } else { + fail("32-bit interpolation of a 16-bit input"); + } + } + // A pixel interpolates in every lane; guards only hide inactive ones. + this->write(inst, Reg::V(reg), x, std::nullopt); +} + +// Whether the program reads attribute row `row` per vertex (an interpolation with computed +// barycentrics, or P10 or P20): then its element is declared constant and read with +// `attributeAtVertex`. +bool Lower::per_vertex(std::uint8_t row) const { + for (const auto& [_, i] : this->x.io->interps) { + if (i.kind == io::Interp::Kind::Weighted) { + const auto* wt = &i; + if (wt->attribute.row == row) return true; + } else if (i.kind == io::Interp::Kind::Vertex) { + const auto* vx = &i; + if (vx->attribute.row == row && vx->vertex != 2 && this->interpolated(row)) return true; + } + } + return false; +} + +// Whether the program interpolates attribute row `row` (so the hardware holds P1 - P0 and P2 - P0 +// for it). +bool Lower::interpolated(std::uint8_t row) const { + for (const auto& [_, i] : this->x.io->interps) { + if (i.kind == io::Interp::Kind::Interpolated || i.kind == io::Interp::Kind::Weighted) { + if (i.attribute.row == row) return true; + } + } + return false; +} + +// Channel `ch` of input row `row` evaluated as `eval` says, as raw bits. +V Lower::eval_channel(std::uint8_t row, std::uint8_t ch, Eval eval) { + auto [id, col] = ok_or(this->find_input(row, ch), "an input the signature lacks"); + const std::uint8_t mode = eval.kind == Eval::Kind::Mode ? eval.mode : 1; + { + auto& e = this->s.inputs.at(id); + if (e.interp != mode && e.usage != 0) { + fail("one input interpolated two ways"); + } + e.interp = mode; + } + if (eval.kind != Eval::Kind::Weights) { + Val v = this->load_any_input(id, col); + if (v.is_i32()) return v.v; + fail("an input"); + } + const bool p0 = eval.p0; + auto v0 = this->vertex_input(id, col, 0); + const std::size_t c = this->cur; + std::optional<V> acc; + if (p0) acc = v0; + const std::array<std::pair<std::uint8_t, std::optional<V>>, 2> ws{{{1, eval.i}, {2, eval.j}}}; + for (const auto& [k, w] : ws) { + if (!w) continue; + auto vk = this->vertex_input(id, col, k); + auto d = this->s.m.bin(c, Bin::Sub, vk, v0); + if (acc) { + acc = this->fmad(*w, d, *acc); + } else { + acc = this->s.m.bin(c, Bin::Mul, *w, d); + } + } + auto a = ok_or(acc, "an interpolation"); + return this->as_int(a); +} + +// Vertex `k` (0 the provoking vertex, as `barycentric` orders them) of a constant input element's +// channel, as a float. +V Lower::vertex_input(std::size_t id, std::uint8_t col, std::uint8_t k) { + auto& e = this->s.inputs.at(id); + e.usage |= static_cast<std::uint8_t>(1u << col); + const bool int_ = e.comp != 9; + Ty ty = int_ ? this->s.t.i32 : this->s.t.f32; + std::string_view suffix = int_ ? ".i32" : ".f32"; + this->s.flags |= flags::BARYCENTRICS; + const std::size_t entry = this->s.entry; + auto a0 = this->s.m.i32(static_cast<std::uint32_t>(id)); + auto a1 = this->s.m.i32(0); + auto a2 = this->s.m.i8(col); + auto a3 = this->s.m.i8(k); + std::string opname = "attributeAtVertex"; + opname += suffix; + auto v = this->s.op(entry, opname, Attr::ReadNone, ty, 137, std::vector<V>{a0, a1, a2, a3}); + if (int_) { + return this->s.m.cast(entry, Cast::Bitcast, v, this->s.t.f32); + } + return v; +} + +// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit results keep the register's +// high half (GFX10). +V Lower::low_half(const Inst& inst, std::uint8_t reg, V x) { + const std::size_t c = this->cur; + std::optional<V> got; + if (auto o = inst.read(Reg::V(reg))) { + got = ok([&] { return this->i32_of(*o); }); + } + V old = got ? *got : this->s.m.i32(0); + auto high = this->s.m.i32(0xFFFF'0000u); + auto low = this->s.m.i32(0xFFFF); + old = this->s.m.bin(c, Bin::And, old, high); + x = this->s.m.bin(c, Bin::And, x, low); + return this->s.m.bin(c, Bin::Or, old, x); +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_intersect.cpp b/src/x2w_shader/emit/lower_intersect.cpp new file mode 100644 index 0000000000..2828707fcd --- /dev/null +++ b/src/x2w_shader/emit/lower_intersect.cpp @@ -0,0 +1,601 @@ +// The console's ray-tracing node test, `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`, as inline +// DXIL: the host has no instruction that tests one ray against one node of the title's own structures. +// +// bvh.h (crate::bvh) says what the instruction computes and is the reference: the code made here +// does the same float operations in the same order (DXIL float operations carry no fast-math +// flags, so the host may not reorder or fuse them), and the tests in intersect_tests run it on the +// card against the reference. +// +// The title's nodes are in title memory, named by address: they are read through the host's +// copies of title memory (Lower::memory), one look in its directory per node (two for a 128-byte +// box node). +// +// Shape of the code, under the instruction's lane guard: +// +// kind = pointer & 7 +// box (4, 5): 4 child pointers; 24 box floats (kind 5) or 24 halves widened (kind 4); +// four slab tests; the sorting network +// triangle (0-3): the id dword, three vertices at the bytes it names; the watertight test +// other (6, 7): a triangle miss +// +// Each lane reads only the dwords its node's kind needs: 28 for a 32-bit box node, 16 for a 16-bit +// one, 10 for a triangle. + +#include <algorithm> +#include <array> +#include <cstdint> +#include <cstdlib> +#include <limits> +#include <optional> +#include <tuple> +#include <utility> +#include <variant> +#include <vector> + +#include "x2w_shader/bvh.h" +#include "x2w_shader/emit/lower_impl.h" + +namespace x2w::vs::lower { + +// The instruction's node resides in a buffer or in mapped memory. +struct NodeAt { + enum class Kind : std::uint8_t { + // At this byte of a raw buffer of the host. + Buffer, + // In title memory: the raw view of the host copy holding the node's first 64 bytes and the + // node's byte in it (Lower::bvh_memory), the node's address, for the second half of a + // 128-byte node, and whether there is a copy. + Memory, + }; + Kind kind = Kind::Buffer; + V handle{}; + V byte{}; + V low{}; // Memory + V high{}; // Memory + V mapped{}; // Memory + + static NodeAt Buffer(V handle, V byte) { + NodeAt n; + n.kind = Kind::Buffer; + n.handle = handle; + n.byte = byte; + return n; + } + static NodeAt Memory(V handle, V byte, V low, V high, V mapped) { + NodeAt n; + n.kind = Kind::Memory; + n.handle = handle; + n.byte = byte; + n.low = low; + n.high = high; + n.mapped = mapped; + return n; + } +}; + +// The ray operands, as floats. +struct Ray { + V extent{}; + std::array<V, 3> origin{}; + std::array<V, 3> direction{}; + std::array<V, 3> inverse{}; +}; + +// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`. +void Lower::bvh(const Inst& inst, std::size_t b, std::size_t i) { + const auto& img = std::get<gfx10::Image>(inst.fields); + const Operand& data = img.data; + const auto& addr = img.addr; + const Operand& rsrc = img.rsrc; + if (img.a16 || img.d16 || img.tfe || img.lwe || img.dmask != 0xf) { + fail("a ray-tracing node test with 16-bit operands or a partial result"); + } + const bool wide = inst.name() == "image_bvh64_intersect_ray"; + // Operand VGPRs in order: the node pointer (two dwords in the 64-bit form), the ray's extent, + // origin, direction and inverse direction. + std::vector<std::uint8_t> regs; + for (const Operand& a : addr) { + if (a.kind == Operand::Kind::Vector) { + for (std::uint8_t k = 0; k < a.dwords; ++k) { + regs.push_back(static_cast<std::uint8_t>(a.reg + k)); + } + } + } + if (regs.size() != (wide ? 12u : 11u)) { + fail("a ray-tracing node test's operands"); + } + if (data.kind != Operand::Kind::Vector) { + fail("a ray-tracing node test's result"); + } + const std::uint8_t dst = data.reg; + const Site site{b, i}; + // x.res->bvh: vector<pair<Site, BvhNodes>>. + std::optional<resource::BvhNodes> found; + for (const auto& n : this->x.res->bvh) { + if (n.first == site) { + found = n.second; + break; + } + } + const resource::BvhNodes nodes = ok_or(found, "an untracked ray-tracing structure"); + bool sort = false; + bool barycentrics = false; + if (nodes.kind == resource::BvhNodes::Kind::Resource) { + sort = true; + barycentrics = true; + } else { + sort = (nodes.word1 & bvh::BOX_SORT) != 0; + barycentrics = (nodes.word3 & bvh::RETURN_BARYCENTRICS) != 0; + } + if (!barycentrics) { + // Mode 0 returns a triangle id and a hit status in the last two dwords; no program of the + // title asks for it. + fail("a ray-tracing structure that returns triangle ids"); + } + const std::optional<V> guard = this->guard(b, i); + std::vector<V> x; + x.reserve(regs.size()); + for (std::uint8_t r : regs) { + const Value v = ok_or(inst.read(Reg::V(r)), "an unread operand"); + x.push_back(this->i32_of(v)); + } + const V pointer = x[0]; + const std::optional<V> pointer_high = wide ? std::optional<V>(x[1]) : std::nullopt; + std::vector<V> f; + for (std::size_t n = 1 + (wide ? 1 : 0); n < x.size(); ++n) { + f.push_back(this->as_float(x[n])); + } + Ray ray; + ray.extent = f.at(0); + ray.origin = {f.at(1), f.at(2), f.at(3)}; + ray.direction = {f.at(4), f.at(5), f.at(6)}; + ray.inverse = {f.at(7), f.at(8), f.at(9)}; + const std::size_t c = this->cur; + NodeAt at; + if (nodes.kind == resource::BvhNodes::Kind::Resource) { + auto d = this->descriptors.find(std::pair<Site, bool>{site, false}); + if (d == this->descriptors.end()) fail("an untracked ray-tracing structure"); + const Source* src = d->second; + const V handle = this->handle(site, *src, false, {11, 0}); + // (pointer >> 3) << 6 from the buffer's start. + const V kind_bits = this->s.m.i32(~7u); + const V k3 = this->s.m.i32(3); + V byte = this->s.m.bin(c, Bin::And, pointer, kind_bits); + byte = this->s.m.bin(c, Bin::Shl, byte, k3); + at = NodeAt::Buffer(handle, byte); + } else { + if (rsrc.kind != Operand::Kind::Scalar) { + fail("a ray-tracing structure descriptor not in SGPRs"); + } + const std::uint8_t code = rsrc.code; + std::array<V, 2> words{pointer, pointer}; + for (std::size_t k = 0; k < 2; ++k) { + const Value v = ok_or(inst.read(Reg::S(static_cast<std::uint8_t>(code + k))), "an unread operand"); + words[k] = this->i32_of(v); + } + const auto [low, high] = this->bvh_address(words[0], words[1], pointer, pointer_high); + // One look for the node's copy, before the branches: a node is 64 bytes on 64, so its + // first half lies in one 64 KiB page whatever its kind. + const auto [handle, byte, mapped] = this->bvh_memory(low, high, guard); + at = NodeAt::Memory(handle, byte, low, high, mapped); + } + const V zero = this->s.m.i32(0); + const auto gate = this->begin_guarded(guard); + const std::size_t head = this->cur; + const V k4 = this->s.m.i32(4); + const V k6 = this->s.m.i32(6); + const V k7 = this->s.m.i32(7); + const V kind = this->s.m.bin(head, Bin::And, pointer, k7); + const V pair = this->s.m.bin(head, Bin::And, pointer, k6); + const V is_box = this->s.m.cmp(head, pred::EQ, pair, k4); + const V is_triangle = this->s.m.cmp(head, pred::IULT, kind, k4); + const std::size_t box_block = this->s.m.new_block(); + const std::size_t leaf_block = this->s.m.new_block(); + const std::size_t triangle_block = this->s.m.new_block(); + const std::size_t join = this->s.m.new_block(); + this->s.m.terminate(head, Term::cond_br(is_box, box_block, leaf_block)); + this->s.m.terminate(leaf_block, Term::cond_br(is_triangle, triangle_block, join)); + this->cur = box_block; + const std::array<V, 4> boxes = this->bvh_boxes(at, kind, ray, sort); + const std::size_t box_end = this->cur; + this->s.m.terminate(box_end, Term::br(join)); + this->cur = triangle_block; + const std::array<V, 4> triangle = this->bvh_triangle(at, kind, ray); + const std::size_t triangle_end = this->cur; + this->s.m.terminate(triangle_end, Term::br(join)); + this->cur = join; + // Kinds 6 and 7 (an instance, a procedural primitive): not known what the console returns; + // the title's programs do not read it. + std::array<V, 4> other{}; + for (std::size_t k = 0; k < 4; ++k) { + other[k] = this->s.m.i32(f32_bits(bvh::MISS[k])); + } + const Ty i32t = this->s.t.i32; + std::vector<std::pair<V, V>> results; + results.reserve(4); + for (std::size_t k = 0; k < 4; ++k) { + const V phi = this->s.m.phi(join, i32t); + this->s.m.set_phi(phi, std::vector<std::pair<V, std::size_t>>{ + {boxes[k], box_end}, + {triangle[k], triangle_end}, + {other[k], leaf_block}, + }); + results.emplace_back(phi, zero); + } + const std::vector<V> out = this->end_guarded(gate, results); + for (std::size_t k = 0; k < out.size(); ++k) { + this->write(inst, Reg::V(static_cast<std::uint8_t>(dst + k)), out[k], guard); + } +} + +// Title memory at `low`/`high` for a node's bytes: the raw view of the host copy holding the address and +// the byte in that view (Lower::memory: a page the host has no copy of reads zeros and is left for the host +// to fetch, for lanes that run). +std::tuple<V, V, V> Lower::bvh_memory(V low, V high, std::optional<V> guard) { + // Device tests can override test_memory(). + if (const auto tm = test_memory()) { + const auto [slot_n, base] = *tm; + // The buffer at heap slot `slot` holds the bytes from title address `base` on; any other + // address reads past its end, which is zeros. + const std::size_t c = this->cur; + const V slot = this->s.m.i32(slot_n); + const V handle = this->s.heap_handle(c, slot, false, false, {11, 0}); + const V base_low = this->s.m.i32(static_cast<std::uint32_t>(base)); + const V base_high = this->s.m.i32(static_cast<std::uint32_t>(base >> 32)); + V at = this->s.m.bin(c, Bin::Sub, low, base_low); + const V in_low = this->s.m.cmp(c, pred::IUGE, low, base_low); + const V in_high = this->s.m.cmp(c, pred::EQ, high, base_high); + const V inside = this->s.m.bin(c, Bin::And, in_low, in_high); + const V outside = this->s.m.i32(0xffff'ff00u); + at = this->s.m.select(c, inside, at, outside); + return {handle, at, inside}; + } + const auto [handle, byte] = this->memory(low, high, guard, false); + if (!this->page_there) std::abort(); + const V mapped = *this->page_there; + return {handle, byte, mapped}; +} + +// The second 64 bytes of a 128-byte node: in a page, and in a copy, of their own maybe. Goes on in another +// block. +NodeAt Lower::bvh_second_half(NodeAt at) { + if (at.kind == NodeAt::Kind::Buffer) { + const V size = this->s.m.i32(64); + const V byte = this->s.m.bin(this->cur, Bin::Add, at.byte, size); + return NodeAt::Buffer(at.handle, byte); + } + const auto [low, high] = this->address_plus(at.low, at.high, 64); + // Every lane in this block runs the instruction. + const auto [handle, byte, mapped] = this->bvh_memory(low, high, std::nullopt); + return NodeAt::Memory(handle, byte, low, high, mapped); +} + +// `count` dwords of 64 bytes of a node from their byte `base` + `offset` (`base` computed, `offset` fixed), +// read four at a time. +std::vector<V> Lower::bvh_node_words(NodeAt at, std::optional<V> base, std::uint32_t offset, + std::uint32_t count) { + const V undef = this->s.m.undef(this->s.t.i32); + const V align = this->s.m.i32(4); + const V handle = at.handle; + const V start_byte = at.byte; + std::vector<V> out; + out.reserve(count); + for (std::uint32_t start = 0; start < count; start += 4) { + const std::uint32_t n = std::min<std::uint32_t>(count - start, 4); + const std::uint32_t node_byte = offset + 4 * start; + V byte = start_byte; + const std::size_t c = this->cur; + if (base) { + byte = this->s.m.bin(c, Bin::Add, byte, *base); + } + const V k = this->s.m.i32(node_byte); + byte = this->s.m.bin(c, Bin::Add, byte, k); + const V mask = this->s.m.i8(static_cast<std::uint8_t>((1u << n) - 1)); + const V r = this->s.op(c, "rawBufferLoad.f32", Attr::ReadOnly, this->s.t.res_ret, 139, + std::vector<V>{handle, byte, undef, mask, align}); + for (std::uint32_t kk = 0; kk < n; ++kk) { + const V fv = this->s.m.extract(c, r, kk); + out.push_back(this->as_int(fv)); + } + } + return out; +} + +// The node's title address, bvh::node_address: the descriptor's base (dword 0 and the low byte of dword 1, +// in 256-byte units) plus `(pointer >> 3) << 6`. +std::pair<V, V> Lower::bvh_address(V word0, V word1, V pointer, std::optional<V> pointer_high) { + const std::size_t c = this->cur; + const Ty i64t = this->s.m.int_(64); + const V zero = this->s.m.i32(0); + const V byte = this->s.m.i32(0xff); + const V base_high = this->s.m.bin(c, Bin::And, word1, byte); + V base = this->join64(word0, base_high); + const V k8 = this->s.m.int_const(i64t, 8); + base = this->s.m.bin(c, Bin::Shl, base, k8); + V p = this->join64(pointer, pointer_high.value_or(zero)); + const V k3 = this->s.m.int_const(i64t, 3); + const V k6 = this->s.m.int_const(i64t, 6); + p = this->s.m.bin(c, Bin::LShr, p, k3); + p = this->s.m.bin(c, Bin::Shl, p, k6); + const V a = this->s.m.bin(c, Bin::Add, base, p); + this->s.flags |= flags::INT64; + return this->split64(a); +} + +// The box test (bvh::boxes): four result dwords. Starts in the current block and leaves `this->cur` at the +// block it ends in. +std::array<V, 4> Lower::bvh_boxes(NodeAt at, V kind, const Ray& ray, bool sort) { + const std::size_t head = this->cur; + const std::vector<V> children = this->bvh_node_words(at, std::nullopt, 0, 4); + const V k5 = this->s.m.i32(5); + const V wide = this->s.m.cmp(head, pred::EQ, kind, k5); + std::size_t wide_block = this->s.m.new_block(); + const std::size_t half_block = this->s.m.new_block(); + const std::size_t join = this->s.m.new_block(); + this->s.m.terminate(head, Term::cond_br(wide, wide_block, half_block)); + // 32-bit floats: 24 dwords from byte 16. + this->cur = wide_block; + const V k16 = this->s.m.i32(16); + std::vector<V> words = this->bvh_node_words(at, std::nullopt, 16, 12); + const NodeAt second = this->bvh_second_half(at); + { + const std::vector<V> more = this->bvh_node_words(second, std::nullopt, 0, 12); + words.insert(words.end(), more.begin(), more.end()); + } + std::vector<V> floats; + floats.reserve(words.size()); + for (const V w : words) { + floats.push_back(this->as_float(w)); + } + // (The look for the second half goes on in another block.) + wide_block = this->cur; + this->s.m.terminate(wide_block, Term::br(join)); + // 16-bit floats: 24 halves in 12 dwords from byte 16, the low half of a dword first. + this->cur = half_block; + const std::vector<V> hwords = this->bvh_node_words(at, std::nullopt, 16, 12); + const Ty f32t = this->s.t.f32; + std::vector<V> halves; + halves.reserve(24); + for (std::size_t n = 0; n < 24; ++n) { + V h = hwords.at(n / 2); + if (n % 2 == 1) { + h = this->s.m.bin(half_block, Bin::LShr, h, k16); + } + // The conversion reads the low 16 bits. + halves.push_back( + this->s.op(half_block, "legacyF16ToF32", Attr::ReadNone, f32t, 131, std::vector<V>{h})); + } + this->s.m.terminate(half_block, Term::br(join)); + this->cur = join; + // A page that is not there reads zeros, which are a child and a box: no child of it is hit. + // (The last two boxes of a 128-byte node are in its second half.) + std::optional<std::array<V, 4>> there; + if (at.kind == NodeAt::Kind::Memory && second.kind == NodeAt::Kind::Memory) { + const V first = at.mapped; + const V last = second.mapped; + const Ty i1t = this->s.m.type_of(first); + const V mapped = this->s.m.phi(join, i1t); + this->s.m.set_phi(mapped, std::vector<std::pair<V, std::size_t>>{{last, wide_block}, {first, half_block}}); + const V both = this->s.m.bin(join, Bin::And, first, mapped); + there = std::array<V, 4>{first, first, both, both}; + } + std::vector<V> coords; + coords.reserve(24); + for (std::size_t n = 0; n < 24; ++n) { + const V phi = this->s.m.phi(join, f32t); + this->s.m.set_phi(phi, std::vector<std::pair<V, std::size_t>>{{floats.at(n), wide_block}, {halves.at(n), half_block}}); + coords.push_back(phi); + } + // The inverse direction held finite (bvh::boxes). + const V most = this->s.m.f32(f32_bits(std::numeric_limits<float>::max())); + const V least = this->s.m.f32(f32_bits(-std::numeric_limits<float>::max())); + std::array<V, 3> inverse{}; + for (std::size_t a = 0; a < 3; ++a) { + const V xv = this->binary(35, ray.inverse[a], least); + inverse[a] = this->binary(36, xv, most); + } + const std::size_t c = join; + const V none = this->s.m.i32(bvh::NONE); + const V infinity = this->s.m.f32(f32_bits(std::numeric_limits<float>::infinity())); + const V fzero = this->s.m.f32(0); + std::array<V, 4> ids{none, none, none, none}; + std::array<V, 4> distances{infinity, infinity, infinity, infinity}; + for (std::size_t n = 0; n < 4; ++n) { + const V* bx = &coords[6 * n]; + std::array<V, 3> near_{fzero, fzero, fzero}; + std::array<V, 3> far_{fzero, fzero, fzero}; + for (std::size_t a = 0; a < 3; ++a) { + V low = this->s.m.bin(c, Bin::Sub, bx[a], ray.origin[a]); + low = this->s.m.bin(c, Bin::Mul, low, inverse[a]); + V high = this->s.m.bin(c, Bin::Sub, bx[3 + a], ray.origin[a]); + high = this->s.m.bin(c, Bin::Mul, high, inverse[a]); + near_[a] = this->binary(36, low, high); + far_[a] = this->binary(35, low, high); + } + V enter = this->binary(35, near_[0], near_[1]); + enter = this->binary(35, enter, near_[2]); + V leave = this->binary(36, far_[0], far_[1]); + leave = this->binary(36, leave, far_[2]); + const V from = this->binary(35, enter, fzero); + // Ordered compares: a NaN anywhere is a miss. + const V through = this->s.m.cmp(c, pred::OGE, leave, from); + const V before = this->s.m.cmp(c, pred::OLT, enter, ray.extent); + const V off = this->is_nan_f32(bx[0]); + V on = this->s.m.bool_(true); + on = this->s.m.bin(c, Bin::Xor, off, on); + V hit = this->s.m.bin(c, Bin::And, through, before); + hit = this->s.m.bin(c, Bin::And, hit, on); + const V child = this->s.m.cmp(c, pred::NE, children.at(n), none); + hit = this->s.m.bin(c, Bin::And, hit, child); + if (there) { + hit = this->s.m.bin(c, Bin::And, hit, (*there)[n]); + } + ids[n] = this->s.m.select(c, hit, children.at(n), none); + distances[n] = this->s.m.select(c, hit, enter, infinity); + } + if (sort) { + static constexpr std::array<std::pair<std::size_t, std::size_t>, 5> NET{ + {{0, 1}, {2, 3}, {0, 2}, {1, 3}, {1, 2}}}; + for (const auto& [a, bb] : NET) { + const V swap = this->s.m.cmp(c, pred::OLT, distances[bb], distances[a]); + const V da = distances[a]; + const V db = distances[bb]; + distances[a] = this->s.m.select(c, swap, db, da); + distances[bb] = this->s.m.select(c, swap, da, db); + const V ia = ids[a]; + const V ib = ids[bb]; + ids[a] = this->s.m.select(c, swap, ib, ia); + ids[bb] = this->s.m.select(c, swap, ia, ib); + } + } + return ids; +} + +// The triangle test (bvh::triangle of bvh::triangle_vertices): four result dwords, made in the current +// block. +std::array<V, 4> Lower::bvh_triangle(NodeAt at, V kind, const Ray& ray) { + const std::size_t c = this->cur; + auto k = [](Lower& l, std::uint32_t v) { return l.s.m.i32(v); }; + // The triangle's byte of the dword at byte 60: which of its vertices barycentric I and J weigh. + V id = this->bvh_node_words(at, std::nullopt, 60, 1).at(0); + const V k2 = k(*this, 2); + const V k3 = k(*this, 3); + const V k12 = k(*this, 12); + const V k15 = k(*this, 15); + const V shift = this->s.m.bin(c, Bin::Shl, kind, k3); + id = this->s.m.bin(c, Bin::LShr, id, shift); + const V i = this->s.m.bin(c, Bin::And, id, k3); + V j = this->s.m.bin(c, Bin::LShr, id, k2); + j = this->s.m.bin(c, Bin::And, j, k3); + V first = this->s.m.bin(c, Bin::Sub, k3, i); + first = this->s.m.bin(c, Bin::Sub, first, j); + first = this->s.m.bin(c, Bin::And, first, k3); + // The node's vertices the triangle is made of, four bits each. + const V k0 = k(*this, 0); + const V k1 = k(*this, 1); + std::array<V, 4> maps{}; + for (std::uint32_t n = 0; n < 4; ++n) { + maps[n] = k(*this, bvh::vertex_map(n)); + } + const V is0 = this->s.m.cmp(c, pred::EQ, kind, k0); + const V is1 = this->s.m.cmp(c, pred::EQ, kind, k1); + const V is2 = this->s.m.cmp(c, pred::EQ, kind, k2); + V map = this->s.m.select(c, is2, maps[2], maps[3]); + map = this->s.m.select(c, is1, maps[1], map); + map = this->s.m.select(c, is0, maps[0], map); + std::vector<std::array<V, 3>> p; + p.reserve(3); + for (const V n : {first, i, j}) { + const V nibble = this->s.m.bin(c, Bin::Shl, n, k2); + V vertex = this->s.m.bin(c, Bin::LShr, map, nibble); + vertex = this->s.m.bin(c, Bin::And, vertex, k15); + const V byte = this->s.m.bin(c, Bin::Mul, vertex, k12); + const std::vector<V> words = this->bvh_node_words(at, byte, 0, 3); + // Relative to the ray's origin. + std::array<V, 3> r{}; + for (std::size_t a = 0; a < 3; ++a) { + const V fv = this->as_float(words.at(a)); + r[a] = this->s.m.bin(c, Bin::Sub, fv, ray.origin[a]); + } + p.push_back(r); + } + // The ray's largest axis z, and x and y after it in an order that keeps the winding. + const V fzero = this->s.m.f32(0); + std::array<V, 3> size{}; + for (std::size_t a = 0; a < 3; ++a) { + size[a] = this->unary(6, ray.direction[a]); + } + const V xy = this->s.m.cmp(c, pred::OGE, size[0], size[1]); + const V xz = this->s.m.cmp(c, pred::OGE, size[0], size[2]); + const V yz = this->s.m.cmp(c, pred::OGE, size[1], size[2]); + const V z0 = this->s.m.bin(c, Bin::And, xy, xz); + const V on = this->s.m.bool_(true); + const V not_xy = this->s.m.bin(c, Bin::Xor, xy, on); + const V z1 = this->s.m.bin(c, Bin::And, not_xy, yz); + // Component (kz + n) % 3 of `q`. + auto pick = [c, z0, z1](Lower& l, const std::array<V, 3>& q, std::size_t n) { + const V rest = l.s.m.select(c, z1, q[(1 + n) % 3], q[(2 + n) % 3]); + return l.s.m.select(c, z0, q[n % 3], rest); + }; + const V dz = pick(*this, ray.direction, 0); + const V backwards = this->s.m.cmp(c, pred::OLT, dz, fzero); + // (x, y, z) of `q`: the two after the largest axis, swapped for a ray that runs backwards + // along it. + auto axes = [&pick, c, backwards](Lower& l, const std::array<V, 3>& q) { + const V xx = pick(l, q, 1); + const V yy = pick(l, q, 2); + const V a0 = l.s.m.select(c, backwards, yy, xx); + const V a1 = l.s.m.select(c, backwards, xx, yy); + const V a2 = pick(l, q, 0); + return std::array<V, 3>{a0, a1, a2}; + }; + const std::array<V, 3> d = axes(*this, ray.direction); + const V sz = pick(*this, ray.inverse, 0); + const V sx = this->s.m.bin(c, Bin::Mul, d[0], sz); + const V sy = this->s.m.bin(c, Bin::Mul, d[1], sz); + std::vector<std::array<V, 3>> sheared; + sheared.reserve(3); + for (const auto& r0 : p) { + const std::array<V, 3> r = axes(*this, r0); + V xv = this->s.m.bin(c, Bin::Mul, sx, r[2]); + xv = this->s.m.bin(c, Bin::Sub, r[0], xv); + V yv = this->s.m.bin(c, Bin::Mul, sy, r[2]); + yv = this->s.m.bin(c, Bin::Sub, r[1], yv); + const V zv = this->s.m.bin(c, Bin::Mul, sz, r[2]); + sheared.push_back({xv, yv, zv}); + } + if (sheared.size() != 3) std::abort(); // unreachable + const V ax = sheared[0][0], ay = sheared[0][1], az = sheared[0][2]; + const V bx = sheared[1][0], by = sheared[1][1], bz = sheared[1][2]; + const V cx = sheared[2][0], cy = sheared[2][1], cz = sheared[2][2]; + // p * q - r * s. + auto cross = [c](Lower& l, V pp, V q, V r, V s) { + const V a = l.s.m.bin(c, Bin::Mul, pp, q); + const V bb = l.s.m.bin(c, Bin::Mul, r, s); + return l.s.m.bin(c, Bin::Sub, a, bb); + }; + const V u = cross(*this, cx, by, cy, bx); + const V v = cross(*this, ax, cy, ay, cx); + const V w = cross(*this, bx, ay, by, ax); + auto any = [c, u, v, w, fzero](Lower& l, std::uint8_t pr) { + V a = l.s.m.cmp(c, pr, u, fzero); + const V bb = l.s.m.cmp(c, pr, v, fzero); + const V dd = l.s.m.cmp(c, pr, w, fzero); + a = l.s.m.bin(c, Bin::Or, a, bb); + return l.s.m.bin(c, Bin::Or, a, dd); + }; + const V behind = any(*this, pred::OLT); + const V before = any(*this, pred::OGT); + const V outside = this->s.m.bin(c, Bin::And, behind, before); + const V inside = this->s.m.bin(c, Bin::Xor, outside, on); + V det = this->s.m.bin(c, Bin::Add, v, w); + det = this->s.m.bin(c, Bin::Add, u, det); + V t = this->s.m.bin(c, Bin::Mul, u, az); + V t2 = this->s.m.bin(c, Bin::Mul, v, bz); + t = this->s.m.bin(c, Bin::Add, t, t2); + t2 = this->s.m.bin(c, Bin::Mul, w, cz); + t = this->s.m.bin(c, Bin::Add, t, t2); + // The distance is not negative: the numerator has the denominator's sign (or is 0). Ordered + // compares: a denominator of 0 or a NaN is a miss. + V front = this->s.m.cmp(c, pred::OGT, det, fzero); + const V front_ahead = this->s.m.cmp(c, pred::OGE, t, fzero); + front = this->s.m.bin(c, Bin::And, front, front_ahead); + V back = this->s.m.cmp(c, pred::OLT, det, fzero); + const V back_ahead = this->s.m.cmp(c, pred::OLE, t, fzero); + back = this->s.m.bin(c, Bin::And, back, back_ahead); + const V ahead = this->s.m.bin(c, Bin::Or, front, back); + const V hit = this->s.m.bin(c, Bin::And, inside, ahead); + std::array<V, 4> miss{}; + for (std::size_t n = 0; n < 4; ++n) { + miss[n] = this->s.m.f32(f32_bits(bvh::MISS[n])); + } + const std::array<V, 4> out{t, det, v, w}; + std::array<V, 4> result{}; + for (std::size_t n = 0; n < 4; ++n) { + const V fv = this->s.m.select(c, hit, out[n], miss[n]); + result[n] = this->as_int(fv); + } + return result; +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_ops_lanes.cpp b/src/x2w_shader/emit/lower_ops_lanes.cpp new file mode 100644 index 0000000000..8ae038b7ee --- /dev/null +++ b/src/x2w_shader/emit/lower_ops_lanes.cpp @@ -0,0 +1,1316 @@ +// Lowering helpers for operands, floats, lane booleans, wave exchange, and results. +#include <cstdlib> +#include <stdexcept> + +#include "x2w_shader/emit/container.h" // MESH_OUTPUT_LIMIT, mesh_output_bytes +#include "x2w_shader/emit/lower_impl.h" +#include "x2w_shader/resource.h" // inline_constant + +namespace x2w::vs::lower { + +namespace { + +[[noreturn]] void unreachable() { throw std::logic_error("unreachable"); } + +} // namespace + +V Lower::operand(const Inst& inst, const Operand& op) { + switch (op.kind) { + case Operand::Kind::Scalar: { + if (op.code == gfx10::NULL_CODE) return this->s.m.i32(0); + auto v = ok_or(inst.read(Reg::S(op.code)), "an unread operand"); + return this->i32_of(v); + } + case Operand::Kind::Vector: { + auto v = ok_or(inst.read(Reg::V(op.reg)), "an unread operand"); + return this->i32_of(v); + } + case Operand::Kind::Const: { + // src_scc reads SCC as zero or one. + if (op.code == 253) { + V bit = this->scc_in(inst); + return this->s.m.cast(this->cur, Cast::ZExt, bit, this->s.t.i32); + } + // Nothing to wait for (see `ordered_section`). + if (op.code == POPS_EXITING && !this->ordered.empty()) return this->s.m.i32(0); + std::optional<std::uint32_t> x = resource::inline_constant(op.code); + if (!x) fail("a special operand (vccz, execz, scc, lds_direct)"); + return this->s.m.i32(*x); + } + case Operand::Kind::Literal: + return this->s.m.i32(op.literal); + case Operand::Kind::Attr: + fail("an attribute operand"); + } + unreachable(); +} + +// A GFX10 inline f16 constant occupies the low half of the operand. +V Lower::f16_operand(const Inst& inst, const Operand& op) { + if (op.kind == Operand::Kind::Const && op.code >= 240 && op.code <= 248) { + return this->s.m.i32(inline_f16(op.code)); + } + return this->operand(inst, op); +} + +V Lower::as_float(V x) { return this->s.m.cast(this->cur, Cast::Bitcast, x, this->s.t.f32); } + +V Lower::as_int(V f) { return this->s.m.cast(this->cur, Cast::Bitcast, f, this->s.t.i32); } + +// The SDWA operand selection of source `k`: a byte or word of the dword, zero- or sign-extended +// (none: the whole dword). +std::optional<std::pair<std::uint8_t, bool>> Lower::sdwa_src(const Inst& inst, std::size_t k) { + const auto* v = std::get_if<gfx10::Valu>(&inst.fields); + if (!v) return std::nullopt; + if (!v->sdwa) return std::nullopt; + const auto& s = *v->sdwa; + if (k >= s.src_sel.size()) return std::nullopt; + std::uint8_t sel = s.src_sel[k]; + bool sext = ((s.sext >> k) & 1) != 0; + if (sel < 6) return std::pair<std::uint8_t, bool>{sel, sext}; + return std::nullopt; +} + +// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended. +V Lower::select_bits(V x, std::uint8_t sel, bool sext) { + std::size_t c = this->cur; + std::uint32_t width, at; + if (sel < 4) { + width = 8; + at = 8u * sel; + } else { + width = 16; + at = 16u * (sel - 4u); + } + V left = this->s.m.i32(32 - width - at); + V t = this->s.m.bin(c, Bin::Shl, x, left); + V right = this->s.m.i32(32 - width); + Bin op = sext ? Bin::AShr : Bin::LShr; + return this->s.m.bin(c, op, t, right); +} + +// A float source with its abs/neg modifiers. +V Lower::fsrc(const Inst& inst, std::size_t k) { + const auto* vp = std::get_if<gfx10::Valu>(&inst.fields); + if (!vp) unreachable(); + const auto& v = *vp; + if (k >= v.src.size()) fail("a missing operand"); + Operand op = v.src[k]; + auto selected = Lower::sdwa_src(inst, k); + V f; + if (selected) { + auto [sel, sext] = *selected; + V x = this->operand(inst, op); + x = this->select_bits(x, sel, sext); + f = this->as_float(x); + } else if (k == 0 && this->src0) { + V x = *this->src0; + f = this->as_float(x); + } else if ((op.kind == Operand::Kind::Vector || op.kind == Operand::Kind::Scalar) && + !(op.kind == Operand::Kind::Scalar && op.code == gfx10::NULL_CODE)) { + Reg r = op.kind == Operand::Kind::Vector ? Reg::V(op.reg) : Reg::S(op.code); + Value val = ok_or(inst.read(r), "an unread operand"); + auto it = this->floats.find(val); + if (it != this->floats.end()) { + f = it->second; + } else { + V x = this->i32_of(val); + f = this->as_float(x); + } + } else { + V x = this->operand(inst, op); + f = this->as_float(x); + } + if (((v.abs >> k) & 1) != 0) { + f = this->unary(6, f); + } + if (((v.neg >> k) & 1) != 0) { + V z = this->s.m.f32(0x8000'0000u); + f = this->s.m.bin(this->cur, Bin::Sub, z, f); + } + return f; +} + +V Lower::src(const Inst& inst, std::size_t k) { + const auto* vp = std::get_if<gfx10::Valu>(&inst.fields); + if (!vp) unreachable(); + const auto& v = *vp; + if (k >= v.src.size()) fail("a missing operand"); + Operand op = v.src[k]; + if (((v.abs >> k) & 1) != 0 || ((v.neg >> k) & 1) != 0) { + fail("integer operand modifiers"); + } + if (this->src0 && k == 0) return *this->src0; + V x = this->operand(inst, op); + if (auto s = Lower::sdwa_src(inst, k)) return this->select_bits(x, s->first, s->second); + return x; +} + +V Lower::unary(std::uint32_t op, V f) { + return this->s.op(this->cur, "unary.f32", Attr::ReadNone, this->s.t.f32, op, std::vector<V>{f}); +} + +V Lower::binary(std::uint32_t op, V a, V b) { + return this->s.op(this->cur, "binary.f32", Attr::ReadNone, this->s.t.f32, op, + std::vector<V>{a, b}); +} + +// The hardware's maximum (`max`) or minimum of two floats: as DXIL's FMax/FMin, but -0 orders +// below +0 (RDNA2 ISA, `v_max_f32`), where the compare and select DXIL specifies gives either zero. +V Lower::max_min(bool max, V a, V b) { + std::size_t c = this->cur; + V r = this->binary(max ? 35 : 36, a, b); + if ((host_rdna() & rdna::MAX_MIN) != 0) { + return r; + } + V ia = this->as_int(a); + V ib = this->as_int(b); + V either = this->s.m.bin(c, Bin::Or, ia, ib); + V magnitude = this->s.m.i32(0x7FFF'FFFFu); + either = this->s.m.bin(c, Bin::And, either, magnitude); + V zero = this->s.m.i32(0); + V zeros = this->s.m.cmp(c, pred::EQ, either, zero); + // Of two zeros, +0 unless both are -0 (max), -0 unless neither (min). + Bin op = max ? Bin::And : Bin::Or; + V sign = this->s.m.bin(c, op, ia, ib); + V signed_ = this->as_float(sign); + return this->s.m.select(c, zeros, signed_, r); +} + +V Lower::fmad(V a, V b, V c) { + return this->s.op(this->cur, "tertiary.f32", Attr::ReadNone, this->s.t.f32, 46, + std::vector<V>{a, b, c}); +} + +// `f` as an f16 in the low bits, rounded toward zero: the nearest-even conversion, one step back +// toward zero where it rounded away (which also turns an overflow to infinity into the largest +// finite half). +V Lower::f16_toward_zero(V f) { + std::size_t c = this->cur; + Ty i32t = this->s.t.i32; + V h = this->s.op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, std::vector<V>{f}); + V back = this->s.op(c, "legacyF16ToF32", Attr::ReadNone, this->s.t.f32, 131, std::vector<V>{h}); + V fa = this->unary(6, f); + V ba = this->unary(6, back); + // Ordered: never for NaN. + V away = this->s.m.cmp(c, pred::OGT, ba, fa); + V one = this->s.m.i32(1); + V stepped = this->s.m.bin(c, Bin::Sub, h, one); + return this->s.m.select(c, away, stepped, h); +} + +// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's 16-bit float +// operations round, whatever the host's own conversion does (D3D lets `f32tof16` round toward +// zero, and the NVIDIA driver's does). The conversion toward zero, or the next half away from zero +// where that one is nearer, or as near and the first one odd. Past the largest half the next one +// counts as 2^16, so 65520 and up become infinity. (`f` is an f32 result of two halves here; +// rounding it again to 16 bits gives the rounding of the exact result.) +V Lower::f16_nearest(V f) { + std::size_t c = this->cur; + Ty f32t = this->s.t.f32; + V lo = this->f16_toward_zero(f); + V one = this->s.m.i32(1); + V zero = this->s.m.i32(0); + V hi = this->s.m.bin(c, Bin::Add, lo, one); + auto size = [&](Lower& l, V h) { + V w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, std::vector<V>{h}); + return l.unary(6, w); + }; + V below = size(*this, lo); + V above = size(*this, hi); + V magnitude = this->s.m.i32(0x7FFF); + V infinity = this->s.m.i32(0x7C00); + V m = this->s.m.bin(c, Bin::And, hi, magnitude); + V top = this->s.m.cmp(c, pred::EQ, m, infinity); + V bound = this->s.m.f32(f32_bits(65536.0f)); + above = this->s.m.select(c, top, bound, above); + V fa = this->unary(6, f); + // (both differences are exact: the three values lie within one half's step) + V under = this->s.m.bin(c, Bin::Sub, fa, below); + V over = this->s.m.bin(c, Bin::Sub, above, fa); + // Ordered: never for NaN, which stays what the conversion made of it. + V nearer = this->s.m.cmp(c, pred::OLT, over, under); + V tie = this->s.m.cmp(c, pred::OEQ, over, under); + V odd = this->s.m.bin(c, Bin::And, lo, one); + odd = this->s.m.cmp(c, pred::NE, odd, zero); + tie = this->s.m.bin(c, Bin::And, tie, odd); + V up = this->s.m.bin(c, Bin::Or, nearer, tie); + return this->s.m.select(c, up, hi, lo); +} + +// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's top bit when `signed`; +// widths from 32 on take every bit. A signed field that runs past bit 31 extends from bit 31, as +// the hardware does: the shift is arithmetic then. +V Lower::bfe(V a, V off, V width, bool signed_) { + std::size_t c = this->cur; + V k31 = this->s.m.i32(31); + V k32 = this->s.m.i32(32); + V zero = this->s.m.i32(0); + V one = this->s.m.i32(1); + V ones = this->s.m.i32(std::numeric_limits<std::uint32_t>::max()); + off = this->s.m.bin(c, Bin::And, off, k31); + Bin shift = signed_ ? Bin::AShr : Bin::LShr; + V shifted = this->s.m.bin(c, shift, a, off); + V full = this->s.m.cmp(c, pred::IUGE, width, k32); + V w = this->s.m.bin(c, Bin::And, width, k31); + V mask = this->s.m.bin(c, Bin::Shl, one, w); + mask = this->s.m.bin(c, Bin::Sub, mask, one); + mask = this->s.m.select(c, full, ones, mask); + V r = this->s.m.bin(c, Bin::And, shifted, mask); + if (!signed_) { + return r; + } + // Sign-extend a field narrower than 32 bits (none for width 0). + V left = this->s.m.bin(c, Bin::Sub, k32, w); + left = this->s.m.bin(c, Bin::And, left, k31); + V t = this->s.m.bin(c, Bin::Shl, r, left); + t = this->s.m.bin(c, Bin::AShr, t, left); + V is0 = this->s.m.cmp(c, pred::EQ, w, zero); + V keep = this->s.m.bin(c, Bin::Or, full, is0); + return this->s.m.select(c, keep, r, t); +} + +// Whether an f32 value is NaN, tested in integer arithmetic so host drivers (such as NVIDIA) do +// not fold `fcmp uno` away under fast-math. +V Lower::is_nan_f32(V f) { + std::size_t c = this->cur; + V bits = this->as_int(f); + V mask = this->s.m.i32(0x7FFF'FFFFu); + V abs = this->s.m.bin(c, Bin::And, bits, mask); + V inf = this->s.m.i32(0x7F80'0000u); + return this->s.m.cmp(c, pred::IUGT, abs, inf); +} + +// The median of three. With a NaN among them the hardware gives the minimum of the three instead +// (the host's minimum skips NaNs, so that is the smallest number among them). +V Lower::med3(V a, V b, V third) { + std::size_t c = this->cur; + // Between two constants in order: the lower one for a NaN either way. + if ((host_rdna() & rdna::MED3) != 0) { + std::optional<float> k0 = this->s.m.float_k(a); + std::optional<float> k1 = this->s.m.float_k(b); + std::optional<float> k2 = this->s.m.float_k(third); + struct Ordered { + V v, p, q; + float x, y; + }; + std::optional<Ordered> ordered; + if (!k0 && k1 && k2) { + ordered = Ordered{a, b, third, *k1, *k2}; + } else if (k0 && !k1 && k2) { + ordered = Ordered{b, a, third, *k0, *k2}; + } else if (k0 && k1 && !k2) { + ordered = Ordered{third, a, b, *k0, *k1}; + } + if (ordered && !std::isnan(ordered->x) && !std::isnan(ordered->y) && + ordered->x != ordered->y) { + V low = ordered->x < ordered->y ? ordered->p : ordered->q; + V high = ordered->x < ordered->y ? ordered->q : ordered->p; + V t = this->binary(35, ordered->v, low); + return this->binary(36, t, high); + } + } + V lo = this->binary(36, a, b); + V hi = this->binary(35, a, b); + V t = this->binary(36, hi, third); + V median = this->binary(35, lo, t); + V least = this->binary(36, lo, third); + V nan_a = this->is_nan_f32(a); + V nan_b = this->is_nan_f32(b); + V nan_3 = this->is_nan_f32(third); + V nan_ab = this->s.m.bin(c, Bin::Or, nan_a, nan_b); + V nan = this->s.m.bin(c, Bin::Or, nan_ab, nan_3); + return this->s.m.select(c, nan, least, median); +} + +// `a - floor(a)`, which on the hardware never reaches 1.0: where it would round to it (a tiny +// negative `a`), the result is `below_one`, the largest value under 1.0 in the operation's width. +// Hosts differ here (some give 1.0). Comparing against a `threshold` distinct from `below_one` +// prevents drivers (observed on NVIDIA) from folding `r > k ? k : r` into `minNum` (`FMNMX`) and +// swallowing NaN. +V Lower::fract(V a, float threshold, float below_one) { + std::size_t c = this->cur; + V r = this->unary(22, a); + if ((host_rdna() & rdna::FRACT) != 0 && below_one == f32_from_bits(0x3F7F'FFFFu)) { + return r; + } + V limit = this->s.m.f32(f32_bits(threshold)); + V k = this->s.m.f32(f32_bits(below_one)); + V over = this->s.m.cmp(c, pred::OGE, r, limit); + return this->s.m.select(c, over, k, r); +} + +// Sine, or cosine, of an angle in turns, as the hardware takes it. The whole turns are taken off +// first (`x - round_even(x)`, exact, within half a turn), so a large angle keeps its fraction; +// scaling to radians first rounds it away. A zero passes unreduced (the sine of -0 is -0). The sine +// of a half turn and the cosine of a quarter turn are exactly +0 on the hardware, where the host's +// function of the rounded angle gives about 1e-7. Infinities and NaN give NaN. +// shortcut: below 2^-12 turns the hardware scales by a slightly different constant than 2Ï€ (a +// last-place difference). +V Lower::trig_turns(V x, bool cosine) { + std::size_t c = this->cur; + V zero = this->s.m.f32(0); + V whole = this->unary(26, x); + V part = this->s.m.bin(c, Bin::Sub, x, whole); + V is_zero = this->s.m.cmp(c, pred::OEQ, x, zero); + part = this->s.m.select(c, is_zero, x, part); + V k = this->s.m.f32(f32_bits(TWO_PI)); + V angle = this->s.m.bin(c, Bin::Mul, part, k); + V r = this->unary(cosine ? 12 : 13, angle); + float at_f = cosine ? 0.25f : 0.5f; + V at = this->s.m.f32(f32_bits(at_f)); + V size = this->unary(6, part); + V exact = this->s.m.cmp(c, pred::OEQ, size, at); + return this->s.m.select(c, exact, zero, r); +} + +// The high dword of a 32 x 32-bit product. +V Lower::mul_hi(V a, V b, bool signed_) { + std::size_t c = this->cur; + Ty i64t = this->s.m.int_(64); + Cast ext = signed_ ? Cast::SExt : Cast::ZExt; + a = this->s.m.cast(c, ext, a, i64t); + b = this->s.m.cast(c, ext, b, i64t); + V m = this->s.m.bin(c, Bin::Mul, a, b); + V k32 = this->s.m.int_const(i64t, 32); + V hi = this->s.m.bin(c, Bin::LShr, m, k32); + this->s.flags |= flags::INT64; + return this->s.m.cast(c, Cast::Trunc, hi, this->s.t.i32); +} + +// `0 x anything = 0`, as in D3D9. +V Lower::legacy_mul(V a, V b) { + std::size_t c = this->cur; + if ((host_rdna() & rdna::LEGACY) != 0) { + V m = this->s.m.bin(c, Bin::Mul, a, b); + V zero = this->s.m.f32(0); + // A product is not 0 only where one factor is 0 and the other an infinity or no number: + // never of a value with itself, nor of two finite ones, and only where the finite one of + // two is 0. + bool fa = this->s.m.bounded(a, 12).has_value(); + bool fb = this->s.m.bounded(b, 12).has_value(); + auto not_zero = [](const Lower& l, V x) { + auto k = l.s.m.float_k(x); + return k.has_value() && *k != 0.0f && std::isfinite(*k); + }; + if (a == b || (fa && fb) || not_zero(*this, a) || not_zero(*this, b)) { + return m; + } + V asked; + if (fa) { + asked = a; + } else if (fb) { + asked = b; + } else { + V aa = this->unary(6, a); + V bb = this->unary(6, b); + asked = this->binary(36, aa, bb); + } + V z = this->s.m.cmp(c, pred::OEQ, asked, zero); + return this->s.m.select(c, z, zero, m); + } + V m = this->s.m.bin(c, Bin::Mul, a, b); + V zero = this->s.m.f32(0); + V az = this->s.m.cmp(c, pred::OEQ, a, zero); + V bz = this->s.m.cmp(c, pred::OEQ, b, zero); + V z = this->s.m.bin(c, Bin::Or, az, bz); + return this->s.m.select(c, z, zero, m); +} + +// ---- lane booleans ---- + +V Lower::boolean(Bool b, std::size_t at) { + if (b == Bool::True || b == Bool::False) { + return this->s.m.bool_(b == Bool::True); + } + auto found = this->bools.find(std::pair<std::size_t, Bool>{at, b}); + if (found != this->bools.end()) { + return found->second; + } + auto node = this->x.st->bools.node(b); + if (!node) throw std::logic_error("not a constant"); + auto [atom, lo, hi] = *node; + V a = this->atom(atom, at); + V v; + if (lo == Bool::False && hi == Bool::True) { + v = a; + } else if (lo == Bool::True && hi == Bool::False) { + V t = this->s.m.bool_(true); + v = this->s.m.bin(at, Bin::Xor, a, t); + } else if (lo == Bool::False) { + V h = this->boolean(hi, at); + v = this->s.m.bin(at, Bin::And, a, h); + } else if (hi == Bool::True) { + V l = this->boolean(lo, at); + v = this->s.m.bin(at, Bin::Or, a, l); + } else { + V l = this->boolean(lo, at); + V h = this->boolean(hi, at); + v = this->s.m.select(at, a, h, l); + } + this->bools.insert_or_assign(std::pair<std::size_t, Bool>{at, b}, v); + return v; +} + +V Lower::atom(Atom atom, std::size_t at) { + switch (atom.kind) { + case Atom::Kind::Lane: { + auto it = this->lane_bits.find(atom.value); + if (it != this->lane_bits.end()) return it->second; + auto f = this->lane_fail.find(atom.value); + fail(f != this->lane_fail.end() ? f->second : "a lane mask from a carry"); + } + case Atom::Kind::Uniform: { + Val g = this->get(atom.value); + switch (g.kind) { + case Val::Kind::Bit: + return g.v; + case Val::Kind::I32: { + V z = this->s.m.i32(0); + return this->s.m.cmp(at, pred::NE, g.v, z); + } + case Val::Kind::Missing: + fail(g.why); + } + unreachable(); + } + case Atom::Kind::Phi: { + Value id = atom.value; + auto mp = this->mask_phis.find(id); + if (mp != this->mask_phis.end()) { + return mp->second; + } + auto pa = this->phi_at.find(id); + if (pa == this->phi_at.end()) fail("a lane-mask join without a phi"); + auto [b, i] = pa->second; + std::size_t blk = ok_or(this->block.at(b), "an unreachable join"); + V v = this->s.m.phi(blk, this->s.t.i1); + this->mask_phis.insert_or_assign(id, v); + this->pending_masks.emplace_back(v, b, i); + return v; + } + // shortcut: "some lane of the quad is set" is taken as true: the lanes it adds only feed + // derivatives, and exports keep their own masks. Wrong if such a section had a side effect. + case Atom::Kind::Quad: + return this->s.m.bool_(true); + // With console lanes, a mask held as a number is the console's: the lane tests its own bit. + case Atom::Kind::Opaque: { + if (!this->console_lanes) fail("an opaque lane mask"); + Value v = atom.value; + std::optional<Val> hi; + if (auto h = this->pair_high(v)) { + hi = this->get(*h); + } + Val lo = this->get(v); + auto word = [](const Val& w) -> V { + if (w.kind == Val::Kind::I32) return w.v; + fail("an opaque lane mask"); + }; + V lo_w = word(lo); + std::optional<V> hi_w; + if (hi) hi_w = word(*hi); + return this->lane_bit(at, lo_w, hi_w); + } + case Atom::Kind::Constant: { + if (!this->console_lanes) fail("a constant lane mask"); + std::uint64_t k = atom.constant; + V lo = this->s.m.i32(static_cast<std::uint32_t>(k)); + V hi = this->s.m.i32(static_cast<std::uint32_t>(k >> 32)); + return this->lane_bit(at, lo, hi); + } + } + unreachable(); +} + +// A console wave64 program in host waves of 32: the first console thread of this host wave (0, 32, 64,...). +// A GPU need not give a host wave consecutive thread indices (NVIDIA's 8 x 8 groups), so each wave takes +// the next 32 from an LDS counter instead: every thread zeroes it, the group meets, each wave's first lane +// adds 32 and the wave takes what it found. Branch-free, in the entry block, which every thread runs. +std::optional<V> Lower::wave_base() { + if (!this->halves) return std::nullopt; + std::uint32_t slot = *this->halves; + if (this->wave_base_) { + return this->wave_base_; + } + std::size_t e = this->s.entry; + Ty i32t = this->s.t.i32; + V lds = this->s.lds(); + V k = this->s.m.i32(slot); + V ptr = this->s.m.element(e, lds, k); + V zero = this->s.m.i32(0); + this->s.m.store(e, ptr, zero); + this->group_sync(e); + V lane = this->s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, std::vector<V>{}); + V first = this->s.m.cmp(e, pred::EQ, lane, zero); + V k32 = this->s.m.i32(32); + V add = this->s.m.select(e, first, k32, zero); + ptr = this->s.m.element(e, lds, k); + V old = this->s.m.atomic(e, Rmw::Add, ptr, add); + V base = this->s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, std::vector<V>{old}); + this->s.flags |= flags::WAVE_OPS; + this->wave_base_ = base; + return base; +} + +// The console thread index of this thread in the group: `wave_base` plus the host lane (host waves +// of 32), else the wave's first thread index rounded down plus the lane. +V Lower::console_thread() { + std::size_t e = this->s.entry; + Ty i32t = this->s.t.i32; + V lane = this->s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, std::vector<V>{}); + if (auto base = this->wave_base()) { + return this->s.m.bin(e, Bin::Add, *base, lane); + } + V flat = this->s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, std::vector<V>{}); + V first = this->s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, std::vector<V>{flat}); + std::uint32_t wave = this->s.wave_size.value_or(32); + V mask = this->s.m.i32(~(wave - 1)); + V base = this->s.m.bin(e, Bin::And, first, mask); + return this->s.m.bin(e, Bin::Add, base, lane); +} + +// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host wave +// holds a 32-aligned run of console lanes. Without `exchange`: the host lane. +V Lower::console_lane() { + if (!this->exchange) { + return this->lane_index(); + } + if (this->clane) { + return *this->clane; + } + std::size_t e = this->s.entry; + V f = this->console_thread(); + V k63 = this->s.m.i32(63); + V cl = this->s.m.bin(e, Bin::And, f, k63); + this->s.flags |= flags::WAVE_OPS; + this->clane = cl; + return cl; +} + +// A group barrier with an LDS fence in `block`. +void Lower::group_sync(std::size_t block) { + V mode = this->s.m.i32(meeting_mode()); + Ty void_t = this->s.t.void_; + this->s.op(block, "barrier", Attr::NoDuplicate, void_t, 80, std::vector<V>{mode}); +} + +// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get +// (lower half's, upper half's). A group with no upper half gets 0 for it. +std::pair<V, V> Lower::exchange_halves(std::size_t at, V mine) { + if (!this->exchange) { + V z = this->s.m.i32(0); + return {mine, z}; + } + std::uint32_t slot = std::get<0>(*this->exchange); + bool small = std::get<1>(*this->exchange); + if (small) { + V z = this->s.m.i32(0); + return {mine, z}; + } + if (this->local) { + // each host wave on its own: its half holds `mine`, the other nothing + V cl = this->console_lane(); + V k32 = this->s.m.i32(32); + V z = this->s.m.i32(0); + V upper = this->s.m.cmp(at, pred::IUGE, cl, k32); + V lo = this->s.m.select(at, upper, z, mine); + V hi = this->s.m.select(at, upper, mine, z); + return {lo, hi}; + } + // the pair of dwords of this thread's console wave: its half's, then both + V pair = this->exchange_pair(slot); + V cl = this->console_lane(); + V five = this->s.m.i32(5); + V half = this->s.m.bin(at, Bin::LShr, cl, five); + V index = this->s.m.bin(at, Bin::Add, pair, half); + V lds = this->s.lds(); + V ptr = this->s.m.element(at, lds, index); + this->s.m.store(at, ptr, mine); + this->group_sync(at); + V one = this->s.m.i32(1); + V k1 = this->s.m.bin(at, Bin::Add, pair, one); + V p0 = this->s.m.element(at, lds, pair); + V p1 = this->s.m.element(at, lds, k1); + V lo = this->s.m.load(at, p0); + V hi = this->s.m.load(at, p1); + // the slots are written again only after every thread read them + this->group_sync(at); + return {lo, hi}; +} + +// The first of the two exchange dwords of this thread's console wave (made in the entry block): a +// group of several console waves has a pair for each. +V Lower::exchange_pair(std::uint32_t slot) { + if (this->pair) { + return *this->pair; + } + std::size_t e = this->s.entry; + V thread = this->console_thread(); + V six = this->s.m.i32(6); + V wave = this->s.m.bin(e, Bin::LShr, thread, six); + V one = this->s.m.i32(1); + V twice = this->s.m.bin(e, Bin::Shl, wave, one); + V base = this->s.m.i32(slot); + V v = this->s.m.bin(e, Bin::Add, base, twice); + this->pair = v; + return v; +} + +// The console's decision of the branch closing IR block `b`, which the wave takes together +// (Structured::wide): see wave_wide. SCC of a mask operation as data (Structured::scc_some): +// whether some lane of the console wave has its bit of the result, asked where the operation +// stands. The lanes that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so +// with the console's waves the host wave's answer is the console's; two host waves of 32 exchange +// theirs, which needs every lane there. +V Lower::scc_some(Value scc) { + auto found = this->x.st->scc_some.find(scc); + if (found == this->x.st->scc_some.end()) fail(LANE_MASK); + Bool m = found->second; + // (not for a console wave cut into host waves that do not exchange) + if (!this->console_lanes || this->local || (!this->exchange && this->halves)) { + fail(LANE_MASK); + } + std::optional<std::size_t> made; + if (auto d = this->def_block.find(scc); d != this->def_block.end()) made = d->second; + std::size_t at; + if (!made) { + at = this->s.entry; + } else if (*made == this->cur_ir) { + at = this->cur; + } else { + at = ok_or(this->tail.at(*made), "a lane mask written after its use"); + } + V bit = this->boolean(m, at); + Ty i1t = this->s.t.i1; + Ty i32t = this->s.t.i32; + V some = this->s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, std::vector<V>{bit}); + this->s.flags |= flags::WAVE_OPS; + if (!(this->exchange && !std::get<1>(*this->exchange))) { + return some; + } + if (!(!made || this->all_lanes(*made))) { + need(made.value_or(0)); + fail("a lane mask exchanged where not every lane runs"); + } + some = this->s.m.cast(at, Cast::ZExt, some, i32t); + auto [lo, hi] = this->exchange_halves(at, some); + V both = this->s.m.bin(at, Bin::Or, lo, hi); + V z = this->s.m.i32(0); + return this->s.m.cmp(at, pred::NE, both, z); +} + +V Lower::wave_wide(std::size_t b, Bool when) { + static constexpr Why WHY = "a wave-wide branch where not every lane runs"; + const auto& wa = this->x.st->wave_any; + std::optional<bool> any_o = b < wa.size() ? wa[b] : std::nullopt; + bool any = ok_or(any_o, "a wave-wide branch on a scalar condition"); + if (!this->exchange && !this->halves && this->console_lanes && + this->mask_data == MaskData::Console) { + // The host's waves are the console's: the wave's own answer. The lanes that are elsewhere + // have no bit set, as on the console, so "some lane" needs no one but the lanes here, and + // "every lane's bit is clear" is true of the others anyway. + std::size_t c = this->cur; + V mine = this->boolean(when, c); + Ty i1t = this->s.t.i1; + this->s.flags |= flags::WAVE_OPS; + const char* name = any ? "waveAnyTrue" : "waveAllTrue"; + std::uint32_t code = any ? 113 : 114; + return this->s.op(c, name, Attr::NoUnwind, i1t, code, std::vector<V>{mine}); + } + if (this->local || !(this->exchange && !std::get<1>(*this->exchange))) { + fail(WHY); + } + if (!this->all_lanes(b)) { + need(b); + fail(WHY); + } + std::size_t c = this->cur; + V mine = this->boolean(when, c); + // what the halves exchange is "some lane speaks against" either way (for `any`: some lane's + // `when` holds; else: some lane's does not), so a half with no lane says nothing + V set; + if (any) { + set = mine; + } else { + V t = this->s.m.bool_(true); + set = this->s.m.bin(c, Bin::Xor, mine, t); + } + Ty i1t = this->s.t.i1; + Ty i32t = this->s.t.i32; + V some = this->s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, std::vector<V>{set}); + this->s.flags |= flags::WAVE_OPS; + some = this->s.m.cast(c, Cast::ZExt, some, i32t); + auto [lo, hi] = this->exchange_halves(c, some); + c = this->cur; + V both = this->s.m.bin(c, Bin::Or, lo, hi); + V z = this->s.m.i32(0); + return this->s.m.cmp(c, any ? pred::NE : pred::EQ, both, z); +} + +// Whether every lane runs IR block `b` (always true without `exchange`). +bool Lower::all_lanes(std::size_t b) const { + if (!this->exchange) return true; + const auto& all = std::get<2>(*this->exchange); + return b < all.size() ? bool(all[b]) : false; +} + +// This lane's bit of the mask `lo`, `hi` (wave64). +V Lower::lane_bit(std::size_t at, V lo, std::optional<V> hi) { + this->s.flags |= flags::WAVE_OPS; + V lane; + if (this->exchange) { + lane = this->console_lane(); + } else { + lane = this->s.op(at, "waveGetLaneIndex", Attr::ReadOnly, this->s.t.i32, 111, std::vector<V>{}); + } + V k31 = this->s.m.i32(31); + V k32 = this->s.m.i32(32); + V one = this->s.m.i32(1); + V z = this->s.m.i32(0); + V word; + if (hi) { + V low = this->s.m.cmp(at, pred::IULT, lane, k32); + word = this->s.m.select(at, low, lo, *hi); + } else { + word = lo; + } + V sh = this->s.m.bin(at, Bin::And, lane, k31); + V t = this->s.m.bin(at, Bin::LShr, word, sh); + t = this->s.m.bin(at, Bin::And, t, one); + return this->s.m.cmp(at, pred::NE, t, z); +} + +// The value of the high dword of the wave64 register pair whose low dword holds `lo` (none in +// wave32). +std::optional<Value> Lower::pair_high(Value lo) const { + if (!this->x.native->wave64) { + return std::nullopt; + } + const Program& p = *this->x.p; + auto pick = [](Reg reg) -> std::optional<Reg> { + if (reg.is_s()) return Reg::S(static_cast<std::uint8_t>(reg.n + 1)); + return std::nullopt; + }; + for (const auto& in : p.inputs) { + if (in.second == lo) { + auto h = pick(in.first); + if (!h) return std::nullopt; + for (const auto& j : p.inputs) { + if (j.first == *h) return j.second; + } + return std::nullopt; + } + } + if (auto pa = this->phi_at.find(lo); pa != this->phi_at.end()) { + auto [b, i] = pa->second; + auto h = pick(p.blocks[b].phis[i].reg); + if (!h) return std::nullopt; + for (const auto& q : p.blocks[b].phis) { + if (q.reg == *h) return q.value; + } + return std::nullopt; + } + auto d = this->def_block.find(lo); + if (d == this->def_block.end()) return std::nullopt; + std::size_t b = d->second; + const Inst* inst = nullptr; + for (const auto& i : p.blocks[b].insts) { + bool any = false; + for (const auto& w : i.writes) { + if (w.second == lo) { + any = true; + break; + } + } + if (any) { + inst = &i; + break; + } + } + if (!inst) return std::nullopt; + const std::pair<Reg, Value>* wr = nullptr; + for (const auto& w : inst->writes) { + if (w.second == lo) { + wr = &w; + break; + } + } + if (!wr) return std::nullopt; + auto h = pick(wr->first); + if (!h) return std::nullopt; + return inst->write(*h); +} + +std::optional<V> Lower::guard(std::size_t b, std::size_t i) { + std::optional<Bool> g = this->x.st->guards[b][i]; + if (!g) return std::nullopt; + return this->boolean(*g, this->cur); +} + +// ---- results ---- + +void Lower::set(std::optional<Value> v, Val val) { + if (v) { + this->vals.insert_or_assign(*v, val); + } +} + +// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`. +void Lower::write(const Inst& inst, Reg reg, V x, std::optional<V> guard) { + if (auto d = Lower::sdwa_dst(inst); d && reg.is_v()) { + x = this->place_bits(inst, reg, x, d->first, d->second); + } + this->write_placed(inst, reg, x, guard); +} + +// `write` of a dword already placed (SDWA applied). +void Lower::write_placed(const Inst& inst, Reg reg, V x, std::optional<V> guard) { + auto new_ = inst.write(reg); + if (!new_) return; + if (guard && reg.is_v()) { + V g = *guard; + std::optional<V> old; + if (auto o = inst.read(reg)) { + old = ok([&] { return this->i32_of(*o); }); + } + // The validator refuses reads of undef. + if (!old) old = this->s.m.i32(0); + V v = this->s.m.select(this->cur, g, x, *old); + this->s.m.tag(v, Tag::Guard); + x = v; + } + this->vals.insert_or_assign(*new_, Val::I32(x)); +} + +// The SDWA destination selection: a byte or word, and what the other bits get (0 zeros, 1 the sign +// above the field, 2 the old bits). +std::optional<std::pair<std::uint8_t, std::uint8_t>> Lower::sdwa_dst(const Inst& inst) { + const auto* v = std::get_if<gfx10::Valu>(&inst.fields); + if (!v) return std::nullopt; + if (!v->sdwa) return std::nullopt; + const auto& s = *v->sdwa; + if (s.dst_sel < 6) return std::pair<std::uint8_t, std::uint8_t>{s.dst_sel, s.dst_unused}; + return std::nullopt; +} + +// The low byte or word of `x` placed at `sel` in VGPR `reg`. +V Lower::place_bits(const Inst& inst, Reg reg, V x, std::uint8_t sel, std::uint8_t unused) { + std::size_t c = this->cur; + std::uint32_t width, at; + if (sel < 4) { + width = 8; + at = 8u * sel; + } else { + width = 16; + at = 16u * (sel - 4u); + } + V left = this->s.m.i32(32 - width); + V t = this->s.m.bin(c, Bin::Shl, x, left); + V right = this->s.m.i32(32 - width - at); + if (unused == 1) { + // Bits below the field shift in as zeros. + return this->s.m.bin(c, Bin::AShr, t, right); + } + V field = this->s.m.bin(c, Bin::LShr, t, right); + if (unused != 2) { + return field; + } + std::optional<V> old; + if (auto o = inst.read(reg)) { + old = ok([&] { return this->i32_of(*o); }); + } + if (!old) old = this->s.m.i32(0); + std::uint32_t bits = static_cast<std::uint32_t>((std::uint64_t{1} << width) - 1); + V keep = this->s.m.i32(~(bits << at)); + V kept = this->s.m.bin(c, Bin::And, *old, keep); + return this->s.m.bin(c, Bin::Or, kept, field); +} + +void Lower::write_f(const Inst& inst, V f, std::optional<V> guard) { + const auto* vp = std::get_if<gfx10::Valu>(&inst.fields); + if (!vp) unreachable(); + const auto& v = *vp; + if (v.omod != 0) { + static constexpr float FACTORS[4] = {1.0f, 2.0f, 4.0f, 0.5f}; + float factor = FACTORS[v.omod]; // omod is 2 bits + V c = this->s.m.f32(f32_bits(factor)); + f = this->s.m.bin(this->cur, Bin::Mul, f, c); + } + if (v.clamp) { + f = this->unary(7, f); + } + if (!(v.dst && v.dst->kind == Operand::Kind::Vector)) { + fail("a float result outside a VGPR"); + } + std::uint8_t reg = v.dst->reg; + V x = this->as_int(f); + this->write(inst, Reg::V(reg), x, guard); + if (!guard && !Lower::sdwa_dst(inst)) { + if (auto new_ = inst.write(Reg::V(reg))) { + this->floats.insert_or_assign(*new_, f); + } + } +} + +void Lower::write_i(const Inst& inst, V x, std::optional<V> guard) { + const auto* vp = std::get_if<gfx10::Valu>(&inst.fields); + if (!vp) unreachable(); + const auto& v = *vp; + if (v.clamp || v.omod != 0) { + fail("integer output modifiers"); + } + if (v.dst && v.dst->kind == Operand::Kind::Vector) { + this->write(inst, Reg::V(v.dst->reg), x, guard); + } else if (v.dst && v.dst->kind == Operand::Kind::Scalar) { + this->write(inst, Reg::S(v.dst->code), x, std::nullopt); + } else { + fail("a result without a register"); + } +} + +// Starts code only the lanes where `guard` holds run (a store under a lane guard): returns where +// it started and the join block. +std::optional<std::pair<std::size_t, std::size_t>> Lower::begin_guarded(std::optional<V> guard) { + if (!guard) return std::nullopt; + V g = *guard; + std::size_t then = this->s.m.new_block(); + std::size_t join = this->s.m.new_block(); + this->s.m.terminate(this->cur, Term::cond_br(g, then, join)); + std::size_t head = this->cur; + this->cur = then; + return std::pair<std::size_t, std::size_t>{head, join}; +} + +// Ends guarded code; each (value inside, value outside) becomes a phi. +std::vector<V> Lower::end_guarded(std::optional<std::pair<std::size_t, std::size_t>> at, + std::span<const std::pair<V, V>> values) { + std::vector<V> out; + if (!at) { + for (const auto& v : values) out.push_back(v.first); + return out; + } + auto [head, join] = *at; + std::size_t then = this->cur; + this->s.m.terminate(then, Term::br(join)); + this->cur = join; + for (const auto& [inside, outside] : values) { + Ty ty = this->s.m.type_of(inside); + V phi = this->s.m.phi(join, ty); + this->s.m.set_phi(phi, std::vector<std::pair<V, std::size_t>>{{inside, then}, {outside, head}}); + out.push_back(phi); + } + return out; +} + +// Code that depends on the lane layout: wave operations, and in compute the console's wave size +// (lanes are thread ids in group order there). Pixel lanes match only within a quad. +void Lower::cross_lane(bool quad) { + if (this->s.mesh) { + // shortcut: no wave size for mesh shaders in SM 6.6, so host lanes cannot follow the + // console's; emulate through group-shared memory if mesh programs turn out to need these. + fail("a cross-lane operation in a mesh shader"); + } + if (!this->s.threads && !(quad && this->s.pixel)) { + fail("a cross-lane operation outside compute"); + } + // debug_assert!(threads.is_none() || console_lanes) + this->s.flags |= flags::WAVE_OPS; +} + +// Component `c` of the thread id in the group. With console lanes, the thread is relabelled so +// that its host lane is its console lane: the flat id is the wave's first lane's, rounded down to +// the wave size, plus the lane index. (A bijection while each host wave holds a wave-aligned run +// of flat ids, as the console's waves do.) +Val Lower::thread_id(std::uint8_t c) { + if (!this->console_lanes) { + return this->compute_id("threadIdInGroup.i32", 95, c); + } + if (!this->s.threads) throw std::logic_error("compute"); + std::uint32_t x = (*this->s.threads)[0]; + std::uint32_t y = (*this->s.threads)[1]; + std::size_t e = this->s.entry; + Ty i32t = this->s.t.i32; + auto split = [&](V f) { + V xk = this->s.m.i32(x); + V yk = this->s.m.i32(y); + V xy = this->s.m.i32(x * y); + if (c == 0) return this->s.m.bin(e, Bin::URem, f, xk); + if (c == 1) { + V t = this->s.m.bin(e, Bin::UDiv, f, xk); + return this->s.m.bin(e, Bin::URem, t, yk); + } + return this->s.m.bin(e, Bin::UDiv, f, xy); + }; + if (this->halves) { + V f = this->console_thread(); + this->s.flags |= flags::WAVE_OPS; + return Val::I32(split(f)); + } + V flat = this->s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, std::vector<V>{}); + V first = this->s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, std::vector<V>{flat}); + if (!this->s.wave_size) throw std::logic_error("set with console lanes"); + std::uint32_t wave = *this->s.wave_size; + V mask = this->s.m.i32(~(wave - 1)); + V base = this->s.m.bin(e, Bin::And, first, mask); + V lane = this->lane_index(); + V f = this->s.m.bin(e, Bin::Add, base, lane); + this->s.flags |= flags::WAVE_OPS; + return Val::I32(split(f)); +} + +// Mesh: the counts and the primitives no lane exports. The console's counts come from one lane's +// allocation request, which DXIL cannot express (one call, dominating every output write). +// shortcut: the counts are the declared maxima and each lane first culls its primitive (all +// indices 0, zero area), so primitives past the program's count are culled and vertices past it +// unused; this costs the host the unused vertex and primitive slots. Pass the program's own counts +// if that shows in frame time. +void Lower::mesh_prologue(Mesh mesh) { + if (!this->s.threads) throw std::logic_error("mesh"); + std::uint32_t threads = (*this->s.threads)[0]; + if (mesh.topology != 2) { + fail("a mesh shader not drawing triangles"); + } + if (threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256) { + fail("a mesh shader beyond the host's limits"); + } + // D3D12 caps the outputs of the declared maxima at 32 KiB. Lane n writes only vertex n and + // primitive n, so maxima past the lanes are never reached: they come down to the lane count + // when the outputs do not fit. + const auto& outputs = this->s.outputs; + const auto& prims = this->s.prims; + auto fits = [&](const Mesh& m) { + return container::mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= + container::MESH_OUTPUT_LIMIT; + }; + if (!fits(mesh)) { + mesh.max_vertices = std::min(mesh.max_vertices, threads); + mesh.max_primitives = std::min(mesh.max_primitives, threads); + // shortcut: outputs past the cap even at the lane count are still emitted with the lower + // maxima (drivers take them); refuse them here if one hangs. + // Experiment (`X2W_SHADERCFG_MESH_OUTPUT_STRICT=1`): they are refused. + if (!fits(mesh) && std::getenv("X2W_SHADERCFG_MESH_OUTPUT_STRICT") != nullptr) { + fail("a mesh shader whose outputs pass the host's 32 KiB"); + } + this->s.mesh = mesh; + } + std::size_t e = this->s.entry; + Ty void_t = this->s.t.void_; + V v = this->s.m.i32(mesh.max_vertices); + V p = this->s.m.i32(mesh.max_primitives); + this->s.op(e, "setMeshOutputCounts", Attr::NoUnwind, void_t, 168, std::vector<V>{v, p}); + V flat = this->mesh_thread(); + V z = this->s.m.i32(0); + // Every primitive of the declared count starts culled, also those past the lanes (a count of + // 256 with 128 lanes): lane n culls primitives n, n + lanes, ... The host draws all it was + // promised, and one never written has whatever indices its memory held. + std::uint32_t passes = div_ceil(mesh.max_primitives, std::max(threads, 1u)); + for (std::uint32_t pass = 0; pass < passes; ++pass) { + V index; + if (pass == 0) { + index = flat; + } else { + V past = this->s.m.i32(pass * threads); + index = this->s.m.bin(this->cur, Bin::Add, flat, past); + } + std::optional<V> guard; + if ((pass + 1) * threads > mesh.max_primitives) { + guard = this->s.m.cmp(this->cur, pred::IULT, index, p); + } + auto at = this->begin_guarded(guard); + this->s.op(this->cur, "emitIndices", Attr::NoUnwind, void_t, 169, std::vector<V>{index, z, z, z}); + this->end_guarded(at, std::span<const std::pair<V, V>>{}); + } +} + +// Mesh: the thread's index in the group, which is its vertex and primitive index. +V Lower::mesh_thread() { + if (this->flat_) { + return *this->flat_; + } + std::size_t e = this->s.entry; + V f = this->s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, this->s.t.i32, 96, + std::vector<V>{}); + this->flat_ = f; + return f; +} + +// The console wave size. +std::uint32_t Lower::wave() const { return this->x.native->wave64 ? 64 : 32; } + +V Lower::lane_index() { + if (this->s.mesh) { + // The console's lane: mesh code reads no other lanes, so host waves need not match the + // console's. + V f = this->mesh_thread(); + V m = this->s.m.i32(this->wave() - 1); + return this->s.m.bin(this->s.entry, Bin::And, f, m); + } + return this->s.op(this->cur, "waveGetLaneIndex", Attr::ReadOnly, this->s.t.i32, 111, + std::vector<V>{}); +} + +// `x` of lane `src` (in this lane's quad) through quad reads, whose lane must be a constant. +V Lower::quad_pick(V x, V src) { + this->s.flags |= flags::WAVE_OPS; + std::size_t c = this->cur; + V three = this->s.m.i32(3); + V q = this->s.m.bin(c, Bin::And, src, three); + V r = x; + for (std::uint32_t n = 0; n < 4; ++n) { + V kn = this->s.m.i32(n); + V read = this->s.op(c, "quadReadLaneAt.i32", Attr::NoUnwind, this->s.t.i32, 122, + std::vector<V>{x, kn}); + V is = this->s.m.cmp(c, pred::EQ, q, kn); + r = this->s.m.select(c, is, read, r); + } + return r; +} + +// Whether a quad-local read takes its lane with the host's quad operations: in a pixel program +// always. Lanes of a quad the primitive does not cover, or that were discarded, are helpers on the +// host; wave reads leave those out (AMD gives 0 from them), quad reads are what reaches them. +bool Lower::helpers_read(bool quad) const { return quad && this->s.pixel; } + +// `x` of the lane of this lane's quad that `lanes` names for each of the quad's four, by the +// host's quad operations. +V Lower::quad_read(V x, std::array<std::uint8_t, 4> lanes) { + this->s.flags |= flags::WAVE_OPS; + std::size_t c = this->cur; + Ty i32t = this->s.t.i32; + if (lanes == std::array<std::uint8_t, 4>{0, 1, 2, 3}) { + return x; + } + // One lane for all. + if (lanes[1] == lanes[0] && lanes[2] == lanes[0] && lanes[3] == lanes[0]) { + V n = this->s.m.i32(lanes[0]); + return this->s.op(c, "quadReadLaneAt.i32", Attr::NoUnwind, i32t, 122, std::vector<V>{x, n}); + } + // Else each lane's own, its neighbour across in x (1) or y (2), or the diagonal one (3). + auto across = [&](std::size_t i) { return static_cast<std::uint8_t>(static_cast<std::uint8_t>(i) ^ lanes[i]); }; + std::optional<V> r; + for (std::uint8_t by = 0; by < 4; ++by) { + bool used = false; + for (std::size_t i = 0; i < 4; ++i) { + if (across(i) == by) { + used = true; + break; + } + } + if (!used) { + continue; + } + V read; + if (by == 0) { + read = x; + } else { + // QuadReadAcrossX, Y, Diagonal. + V kind = this->s.m.i8(static_cast<std::uint8_t>(by - 1)); + read = this->s.op(c, "quadOp.i32", Attr::NoUnwind, i32t, 123, std::vector<V>{x, kind}); + } + if (!r) { + r = read; + } else { + V here = this->s.m.bool_(false); + V lane = this->lane_index(); + V three = this->s.m.i32(3); + V at = this->s.m.bin(c, Bin::And, lane, three); + for (std::size_t i = 0; i < 4; ++i) { + if (across(i) != by) continue; + V k = this->s.m.i32(static_cast<std::uint32_t>(i)); + V is = this->s.m.cmp(c, pred::EQ, at, k); + here = this->s.m.bin(c, Bin::Or, here, is); + } + r = this->s.m.select(c, here, read, *r); + } + } + return r.value_or(x); +} + +// `x` in the first lane of this host wave where `guard` holds, and whether it has such a lane: the +// console reads the first lane of EXEC, and a lane that got here with EXEC clear (a guard, not a +// branch) is not one. With none, `x` of the wave's first lane here. +// +// A helper lane of a pixel shader takes its own value: the console's whole-quad mode has helper lanes in +// EXEC, so a waterfall loop serves them too, and the host's wave operations leave them out. Once only +// helper lanes are left in such a loop none of them ever matched: they ran to the iteration limit, and left +// with no sample for their quad's derivatives, along every triangle's edges. +std::pair<V, V> Lower::first_lane(V x, std::optional<V> guard) { + auto [first, any] = this->first_live_lane(x, guard); + if (!this->s.pixel || !helper_own()) { + return {first, any}; + } + V helper = this->helper_lane(); + std::size_t c = this->cur; + V yes = this->s.m.bool_(true); + V a = this->s.m.select(c, helper, x, first); + V b = this->s.m.select(c, helper, yes, any); + return {a, b}; +} + +// Whether this lane of a pixel shader is a helper lane. +V Lower::helper_lane() { + Ty i1t = this->s.t.i1; + return this->s.op(this->cur, "isHelperLane.i1", Attr::ReadOnly, i1t, 221, std::vector<V>{}); +} + +std::pair<V, V> Lower::first_live_lane(V x, std::optional<V> guard) { + std::size_t c = this->cur; + Ty i32t = this->s.t.i32; + this->s.flags |= flags::WAVE_OPS; + V first = this->s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, std::vector<V>{x}); + if (!guard) { + V t = this->s.m.bool_(true); + return {first, t}; + } + V g = *guard; + Ty four = this->s.m.named_struct("dx.types.fouri32", std::vector<Ty>(4, i32t)); + V r = this->s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, std::vector<V>{g}); + V lo = this->s.m.extract(c, r, 0); + V hi = this->s.m.extract(c, r, 1); + V z = this->s.m.i32(0); + V k32 = this->s.m.i32(32); + // FirstbitLo (dx.op 32): the lowest set bit + V flo = this->s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, std::vector<V>{lo}); + V fhi = this->s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, std::vector<V>{hi}); + fhi = this->s.m.bin(c, Bin::Add, fhi, k32); + V in_lo = this->s.m.cmp(c, pred::NE, lo, z); + V in_hi = this->s.m.cmp(c, pred::NE, hi, z); + V any = this->s.m.bin(c, Bin::Or, in_lo, in_hi); + V lane = this->s.m.select(c, in_lo, flo, fhi); + // no lane in EXEC: read this lane (one that is here); the read is not used + V me = this->s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, std::vector<V>{}); + lane = this->s.m.select(c, any, lane, me); + V at = this->read_lane(x, lane); + V picked = this->s.m.select(c, any, at, first); + return {picked, any}; +} + +V Lower::read_lane(V x, V lane) { + return this->s.op(this->cur, "waveReadLaneAt.i32", Attr::NoUnwind, this->s.t.i32, 117, + std::vector<V>{x, lane}); +} + +// The float value of a register value. +V Lower::float_of(Value v) { + if (auto it = this->floats.find(v); it != this->floats.end()) { + return it->second; + } + V x = this->i32_of(v); + return this->as_float(x); +} + +// The values of VGPRs `reg..reg + n` as `inst` reads them. +std::vector<V> Lower::vgprs(const Inst& inst, const Operand& op, std::uint8_t n) { + if (op.kind != Operand::Kind::Vector) { + fail("a vector operand"); + } + std::uint8_t reg = op.reg; + std::vector<V> out; + for (std::uint8_t k = 0; k < n; ++k) { + Value v = ok_or(inst.read(Reg::V(static_cast<std::uint8_t>(reg + k))), "an unread operand"); + out.push_back(this->i32_of(v)); + } + return out; +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_smem.cpp b/src/x2w_shader/emit/lower_smem.cpp new file mode 100644 index 0000000000..853a0da1c8 --- /dev/null +++ b/src/x2w_shader/emit/lower_smem.cpp @@ -0,0 +1,866 @@ +// Lower scalar memory operations, descriptor reads, code constants, and typed buffer formats. +#include <algorithm> +#include <cstdio> +#include <cstdlib> +#include <string> + +#include "x2w_shader/emit/lower_impl.h" + +namespace x2w::vs::lower { + +namespace { + +// Inspect resource::Source variants from resource.h. + +// Construct a source loaded at the specified site and first dword. +Source make_loaded(Site load, std::uint8_t first) { + return Source::Loaded(load, first); +} + +// Return the first dword if this source was loaded at the given site. +std::optional<std::uint8_t> loaded_at(const Source& l, Site site) { + if (l.kind == Source::Kind::Loaded && l.load == site) { + return l.first; + } + return std::nullopt; +} + +// Test whether a built source refers to code memory. +bool built_in_code(const Source& src) { + return src.kind == Source::Kind::Built && src.address.param == resource::CODE; +} + +// Test for the scalar null register. +bool is_null_scalar(const Operand& op) { + return op.kind == Operand::Kind::Scalar && op.code == gfx10::NULL_CODE; +} + +// Test whether the value is a constant. +bool is_const_v(V v) { + return v.kind == V::Const; +} + +std::optional<std::uint32_t> dword_count(std::string_view rest) { + if (rest == "") return 1u; + if (rest == "x2") return 2u; + if (rest == "x4") return 4u; + if (rest == "x8") return 8u; + if (rest == "x16") return 16u; + return std::nullopt; +} + +bool contains(std::string_view s, std::string_view x) { return s.find(x) != std::string_view::npos; } + +std::string debug_address(const std::optional<Address>& a) { + if (!a) return "None"; + std::string s = "Some(Address { param: " + std::to_string(a->param) + + ", offset: " + std::to_string(a->offset) + ", dynamic: "; + s += a->dynamic ? "Some(Value(" + std::to_string(a->dynamic->n) + "))" : std::string("None"); + return s + " })"; +} + +} // namespace + +void Lower::smem(const Inst& inst, Site site) { + const auto& sm = std::get<gfx10::Smem>(inst.fields); + const std::optional<Operand>& data = sm.data; + const std::int32_t offset0 = sm.offset; + const Operand& soffset = sm.soffset; + this->root_copy = std::nullopt; + std::string_view name = inst.name(); + if (auto it = this->scalar.find(site); it != this->scalar.end() && it->second.param == resource::CODE) { + Address a = it->second; + return this->code_smem(inst, a); + } + if (auto it = this->scalar.find(site); it != this->scalar.end() && it->second.param == resource::MEMORY) { + return this->memory_smem(inst); + } + constexpr std::string_view prefix = "s_buffer_load_dword"; + if (!name.starts_with(prefix)) { + return this->descriptor_data(inst, site); + } + std::uint32_t count = ok_or(dword_count(name.substr(prefix.size())), "a scalar buffer load"); + if (!data || data->kind != Operand::Kind::Scalar) { + fail("a scalar buffer load"); + } + std::uint8_t code = data->code; + const Source* src = nullptr; + if (auto it = this->descriptors.find(std::pair{site, false}); it != this->descriptors.end()) { + src = it->second; + } + ok_or(src, "an untracked descriptor"); + const UsedResource* kind = this->used_kind(*src); + std::size_t c = this->cur; + auto [base, extra] = this->built_offset(*src); + // Add the base offset modulo 2^32. + const std::int32_t offset = static_cast<std::int32_t>(static_cast<std::uint32_t>(offset0) + base); + V addr = this->s.m.i32(static_cast<std::uint32_t>(offset)); + if (extra) { + addr = this->s.m.bin(c, Bin::Add, addr, *extra); + } + if (!is_null_scalar(soffset)) { + V so = this->operand(inst, soffset); + addr = this->s.m.bin(c, Bin::Add, addr, so); + } + if (built_in_code(*src)) { + // A descriptor built around a table in the code. + for (std::uint32_t k = 0; k < count; ++k) { + V off = this->s.m.i32(4 * k); + V a = this->s.m.bin(c, Bin::Add, addr, off); + V x = this->code_dword(a); + this->write(inst, Reg::S(static_cast<std::uint8_t>(code + k)), x, std::nullopt); + } + return; + } + // A buffer the program picks from the view heap by an index it computes (`ResourceHeap`) has + // no used-resource entry, and the heap holds a buffer view there, not a constant buffer: read + // as raw bytes, as a table's SRV is below. Read as a constant buffer (the host's validation: + // "Descriptor Type in Heap: SRV, Register Type: CBV", heap index 17) the loads gave nothing: + // the title's meshlet culling reads its batch records, mesh headers and instance transforms + // this way, so it passed no meshlet and every indirect mesh draw ran empty. The host's table + // of strides by heap slot tells a buffer view (not 0) from anything else, which is still read + // as a constant buffer; only the load that fits the slot runs. + std::optional<V> picked; + if (kind == nullptr) { + picked = this->slot_stride(*src); + } + if (picked) { + V stride = *picked; + V zero = this->s.m.i32(0); + V is_buffer = this->s.m.cmp(this->cur, pred::NE, stride, zero); + auto at = this->begin_guarded(is_buffer); + V h = this->handle(site, *src, false, {11, 0}); + std::vector<std::pair<V, V>> raw; + bool wide = Lower::wide_loads(); + if (wide) { + std::vector<V> dwords = this->raw_dwords(h, addr, count); + for (V x : dwords) raw.emplace_back(x, zero); + } + for (std::uint32_t k = 0; k < (wide ? 0 : count); ++k) { + std::size_t b = this->cur; + V off = this->s.m.i32(4 * k); + V a = this->s.m.bin(b, Bin::Add, addr, off); + V mask = this->s.m.i8(1); + V u = this->s.m.undef(this->s.t.i32); + V al = this->s.m.i32(4); + V r = this->s.op(b, "rawBufferLoad.f32", Attr::ReadOnly, this->s.t.res_ret, 139, + std::vector<V>{h, a, u, mask, al}); + V x = this->s.m.extract(b, r, 0); + x = this->as_int(x); + raw.emplace_back(x, zero); + } + std::vector<V> raw_v = this->end_guarded(at, raw); + V other = this->s.m.cmp(this->cur, pred::EQ, stride, zero); + auto at2 = this->begin_guarded(other); + V h2 = this->handle(site, *src, false, {13, 0x1'0000}); + std::vector<std::pair<V, V>> both; + for (std::size_t k = 0; k < raw_v.size(); ++k) { + V r = raw_v[k]; + std::size_t b = this->cur; + V off = this->s.m.i32(4 * static_cast<std::uint32_t>(k)); + V a = this->s.m.bin(b, Bin::Add, addr, off); + V x = this->cbuffer_dword(h2, a); + both.emplace_back(x, r); + } + std::vector<V> both_v = this->end_guarded(at2, both); + for (std::size_t k = 0; k < both_v.size(); ++k) { + this->write(inst, Reg::S(static_cast<std::uint8_t>(code + k)), both_v[k], std::nullopt); + } + return; + } + if (kind != nullptr && kind->kind == ResourceType::Srv()) { + // The size in a structure's header (its second dword), which a copy of it loops over. + bool size = offset == 4 && count == 1 && !extra && is_null_scalar(soffset) && + emit::builder_bounds(); + bool root = false; + V h; + if (auto rm = this->root_memory(*src, addr, std::nullopt, false)) { + h = rm->first; + addr = rm->second; + root = true; + } else { + h = this->handle(site, *src, false, {11, 0}); + } + if (Lower::wide_loads()) { + std::vector<V> dwords = this->raw_dwords(h, addr, count); + for (std::size_t k = 0; k < dwords.size(); ++k) { + this->write(inst, Reg::S(static_cast<std::uint8_t>(code + k)), dwords[k], std::nullopt); + } + return; + } + std::size_t c2 = this->cur; + for (std::uint32_t k = 0; k < count; ++k) { + V off = this->s.m.i32(4 * k); + V a = this->s.m.bin(c2, Bin::Add, addr, off); + V mask = this->s.m.i8(1); + V u = this->s.m.undef(this->s.t.i32); + V al = this->s.m.i32(4); + V r = this->s.op(c2, "rawBufferLoad.f32", Attr::ReadOnly, this->s.t.res_ret, 139, + std::vector<V>{h, a, u, mask, al}); + V x = this->s.m.extract(c2, r, 0); + x = this->as_int(x); + if (size && root) { + V most = this->s.m.i32(1u << 20); + V zero = this->s.m.i32(0); + V sane = this->s.m.cmp(c2, pred::IULT, x, most); + x = this->s.m.select(c2, sane, x, zero); + } + this->write(inst, Reg::S(static_cast<std::uint8_t>(code + k)), x, std::nullopt); + } + return; + } + V h = this->handle(site, *src, false, {13, 0x1'0000}); + std::optional<std::uint32_t> constant; + if (is_const_v(addr) && is_null_scalar(soffset) && !extra) { + constant = static_cast<std::uint32_t>(offset); + } + // order: lookups only. + HashMap<std::uint32_t, V> rows; + for (std::uint32_t k = 0; k < count; ++k) { + V x; + if (constant) { + std::uint32_t byte = *constant + 4 * k; + V row; + if (auto it = rows.find(byte >> 4); it != rows.end()) { + row = it->second; + } else { + V ri = this->s.m.i32(byte >> 4); + V r = this->s.op(c, "cbufferLoadLegacy.i32", Attr::ReadOnly, this->s.t.cbuf_ret, 59, + std::vector<V>{h, ri}); + rows.insert_or_assign(byte >> 4, r); + row = r; + } + x = this->s.m.extract(c, row, (byte >> 2) & 3); + } else { + V off = this->s.m.i32(4 * k); + V a = this->s.m.bin(c, Bin::Add, addr, off); + x = this->cbuffer_dword(h, a); + } + this->write(inst, Reg::S(static_cast<std::uint8_t>(code + k)), x, std::nullopt); + } +} + +// A descriptor load (`s_load_dword*` from a table or heap) whose dwords the code also reads as +// numbers: the console compiler computes sizes from descriptor bits (an image's width, height, +// depth, levels; a buffer's record count) instead of querying them. Those fields are rebuilt from +// the host view's dimensions in the GFX10 layout (image dword 1 bits 30-31 and dword 2 bits 0-13 +// width - 1, dword 2 bits 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at +// 28, dword 4 depth or layers - 1; buffer dword 2 the record count). +// shortcut: the base level reads 0 (the host view starts at its own level 0, so sizes the code +// shifts by it come out right) and the other dwords (addresses, formats, tiling) have no host +// value: reading them stops the program. +void Lower::descriptor_data(const Inst& inst, Site site) { + constexpr Why OTHER = "a descriptor's address or format read as data"; + const auto* sm = std::get_if<gfx10::Smem>(&inst.fields); + if (!sm || !sm->data || sm->data->kind != Operand::Kind::Scalar) { + fail("a scalar memory read as data"); + } + const std::uint8_t code = sm->data->code; + constexpr std::string_view prefix = "s_load_dword"; + std::string_view iname = inst.name(); + if (!iname.starts_with(prefix)) fail("a scalar memory read as data"); + const std::uint32_t count = ok_or(dword_count(iname.substr(prefix.size())), "a scalar memory read as data"); + // How the program uses the descriptor tells the view's kind: an image or buffer instruction + // before a scalar buffer load, which reads any buffer. + const Parts& x = this->x; + // per resource descriptor (in order) whose leaves load from `of`, its site and the first such leaf's first + // dword. + auto uses = [&](Site of) { + std::vector<std::pair<Site, std::uint8_t>> out; + for (const auto& d : x.res->descriptors) { + if (d.role != Role::Resource) continue; + for (const Source* l : d.source.leaves()) { + if (auto first = loaded_at(*l, of)) { + out.emplace_back(d.site, *first); + break; + } + } + } + return out; + }; + auto by_scalar_load = [&](const std::pair<Site, std::uint8_t>& u) { + return std::holds_alternative<gfx10::Smem>( + x.p->blocks.at(u.first.first).insts.at(u.first.second).fields); + }; + auto use_of = [&](Site of) -> std::optional<std::pair<Site, std::uint8_t>> { + auto all = uses(of); + for (const auto& u : all) { + if (!by_scalar_load(u)) return u; + } + if (!all.empty()) return all.front(); + return std::nullopt; + }; + // The console compiler loads a descriptor again wherever it needs it, and for a size it reads + // the dwords of a load that nothing uses as a descriptor. Another load of as many dwords from + // the same address reads the same descriptor, so what uses that one tells this one's kind. The + // handle is still made from this load's own operands, which hold here. + std::optional<Address> address; + if (auto it = this->scalar.find(site); it != this->scalar.end()) address = it->second; + auto twin = [&]() -> std::optional<std::pair<Site, std::uint8_t>> { + if (!address) return std::nullopt; + const Address a = *address; + auto same_name = [&](Site s) { return x.p->blocks.at(s.first).insts.at(s.second).name() == inst.name(); }; + for (const auto& [s, b] : x.res->scalar) { + if (s != site && b == a && same_name(s)) { + if (auto u = use_of(s)) return u; + } + } + return std::nullopt; + }; + std::optional<std::pair<Site, std::uint8_t>> use_at = use_of(site); + if (!use_at) use_at = twin(); + // A view whose kind no use tells, but what is read of it does. + std::optional<bool> sized; + if (!use_at) sized = this->sized_view(inst, site, code, count); + // A descriptor nothing uses as one, whose size the code reads all the same (a texture picked + // from the heap by an index in a constant buffer, its width and height turned into a texel + // size): the kind from its dwords and its used-resource entry. Only an image whose layers or + // depth (dword 4) are not read: those are no 2D texture's; and no buffer `sized_view` did not + // take (a stride of 4 or less may be a typed view's component count, and the address is + // `view_address`'s below). + bool layers = false; + if (auto v = inst.write(Reg::S(static_cast<std::uint8_t>(code + 4)))) layers = this->read_as_number(*v); + std::optional<std::tuple<std::uint8_t, std::pair<std::uint32_t, std::uint32_t>, std::optional<std::uint32_t>, bool, const UsedResource*>> unused; + if (!use_at && !sized && count == 8 && !layers) { + unused = this->unused_descriptor_kind(inst, site, code, count); + } + std::uint8_t first = 0; + std::pair<std::uint32_t, std::uint32_t> props{0, 0}; + std::optional<std::uint32_t> image; + bool uav = false; + const UsedResource* used = nullptr; + if (unused) { + std::tie(first, props, image, uav, used) = *unused; + } else { + std::optional<std::pair<Site, std::uint8_t>> chosen = use_at; + if (!chosen && sized) chosen = std::pair<Site, std::uint8_t>{site, 0}; + if (!chosen) { + // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only copies + // its dwords and compares them, lane against first lane, and every load that reaches + // those lanes reads one address. Each dword stands in as its place in the table, so + // the lanes compare equal as they do on the console. + const auto& lc = this->x.res->lane_copied; + if (std::find(lc.begin(), lc.end(), site) != lc.end()) { + if (auto it = this->scalar.find(site); it != this->scalar.end()) { + Address a = it->second; + for (std::uint32_t k = 0; k < count; ++k) { + V xk = this->s.m.i32(a.offset / 4 + k); + this->write(inst, Reg::S(static_cast<std::uint8_t>(code + k)), xk, std::nullopt); + } + return; + } + } + // A sampler's descriptor: no program reads its dwords as numbers, so where one meets + // numbers at a join the register is dead on that path (`dead`), as a descriptor's + // address or format is. + bool sampler = false; + for (const auto& d : x.res->descriptors) { + if (d.role != Role::Sampler) continue; + for (const Source* l : d.source.leaves()) { + if (loaded_at(*l, site)) { + sampler = true; + break; + } + } + if (sampler) break; + } + if (sampler) { + for (const auto& w : inst.writes) this->stale.insert(w.second); + fail("a sampler's descriptor read as data"); + } + // A buffer view the code only takes the address of, to walk the memory behind it (a + // ray-tracing structure): the address from the host, the other dwords have no value. + if (count <= 4) { + if (auto va = this->view_address(site)) { + auto [lo, hi] = *va; + for (std::uint32_t k = 0; k < count; ++k) { + Reg reg = Reg::S(static_cast<std::uint8_t>(code + k)); + if (k == 0) { + this->write(inst, reg, lo, std::nullopt); + } else if (k == 1) { + this->write(inst, reg, hi, std::nullopt); + } else if (auto v = inst.write(reg)) { + this->vals.insert_or_assign(*v, Val::Missing(OTHER)); + this->stale.insert(*v); + } + } + return; + } + } + if (std::getenv("X2W_SHADERCFG_DESC_WHY") != nullptr) { + bool copied = std::find(lc.begin(), lc.end(), site) != lc.end(); + std::fprintf(stderr, "DESC-WHY %s %.*s scalar=%s lane_copied=%s\n", + hex_alt(inst.machine.offset).c_str(), static_cast<int>(iname.size()), + iname.data(), debug_address(address).c_str(), copied ? "true" : "false"); + } + fail("a descriptor read only as data"); + } + const Site at = chosen->first; + first = chosen->second; + const Source src0 = make_loaded(site, first); + used = this->used_kind(src0); + const Inst& ui = this->x.p->blocks.at(at.first).insts.at(at.second); + std::string_view un = ui.name(); + uav = contains(un, "store") || contains(un, "atomic") || + (used != nullptr && used->kind == ResourceType::Uav()); + const std::uint32_t u = uav ? 0x1000 : 0; + if (sized && *sized) { + props = {2 | u, 0x409}; + image = 2; + } else if (sized) { + props = {11 | u, 0}; + image = std::nullopt; + } else if (std::holds_alternative<gfx10::Image>(ui.fields) && un.starts_with("image_bvh")) { + // A ray-tracing structure in a buffer of the host: read raw. + props = {11, 0}; + image = std::nullopt; + } else if (const auto* im = std::get_if<gfx10::Image>(&ui.fields)) { + std::uint32_t k; + switch (im->dim) { + case 0: k = 1; break; + case 1: k = 2; break; + case 2: k = 4; break; + case 4: k = 6; break; + case 5: k = 7; break; + default: fail("an image dimension (cube or MSAA)"); + } + props = {k | u, 0x409}; + image = k; + } else if (const auto* bu = std::get_if<gfx10::Buffer>(&ui.fields)) { + std::uint32_t stride = used != nullptr ? used->stride : 0; + bool counted = false; + if (auto v = inst.write(Reg::S(static_cast<std::uint8_t>(code + first + 2)))) { + counted = this->read_as_number(*v); + } + if (un.starts_with("buffer_load_format") || un.starts_with("buffer_store_format")) { + props = {10 | u, 0x409}; + } else if (!counted && bu->idxen && !bu->format && stride >= 4 && stride % 4 == 0) { + // Nothing reads the count: the query is cleaned up. + props = {12 | u, stride}; + } else { + // Structured ones too: the host's views of them are raw (see `buffer`), which + // count bytes, and a size asked for as a structured view's is that count on AMD. + props = {11 | u, 0}; + } + if (used != nullptr && used->kind == ResourceType::Cbv()) { + for (const auto& w : inst.writes) this->stale.insert(w.second); + fail("a constant buffer's descriptor read as data"); + } + image = std::nullopt; + } else if (std::holds_alternative<gfx10::Smem>(ui.fields) && used != nullptr && + used->kind == ResourceType::Srv()) { + // Read by scalar buffer loads alone: the raw view `smem` reads it through. + props = {11, 0}; + image = std::nullopt; + } else if (std::holds_alternative<gfx10::Smem>(ui.fields)) { + // A constant buffer: nothing of its descriptor is a number. + for (const auto& w : inst.writes) this->stale.insert(w.second); + fail("a constant buffer's descriptor read as data"); + } else { + fail("a scalar memory read as data"); + } + } + const Source src = make_loaded(site, first); + V h = this->handle(site, src, false, props); + std::size_t c = this->cur; + Ty i32t = this->s.t.i32; + Ty dims = this->s.m.named_struct("dx.types.Dimensions", std::vector<Ty>(4, i32t)); + V mip; + if (image && !uav) { + mip = this->s.m.i32(0); + } else { + mip = this->s.m.undef(i32t); + } + V d = this->s.op(c, "getDimensions", Attr::ReadOnly, dims, 72, std::vector<V>{h, mip}); + auto field = [&](std::uint32_t k) { return this->s.m.extract(c, d, k); }; + std::vector<std::pair<std::uint32_t, V>> words; + if (image) { + const std::uint32_t kind = *image; + V one = this->s.m.i32(1); + V w = field(0); + V height, depth; + switch (kind) { + case 1: + height = one; + depth = one; + break; + case 2: + height = field(1); + depth = one; + break; + case 6: + height = one; + depth = field(1); + break; + default: + height = field(1); + depth = field(2); + break; + } + V levels = uav ? one : field(3); + auto less = [&](V v) { return this->s.m.bin(c, Bin::Sub, v, one); }; + w = less(w); + height = less(height); + depth = less(depth); + levels = less(levels); + auto k = [&](std::uint32_t v) { return this->s.m.i32(v); }; + V k30 = k(30); + V k2 = k(2); + V k14 = k(14); + V k16 = k(16); + V mask = k(0x3FFF); + V d1 = this->s.m.bin(c, Bin::Shl, w, k30); + V hi = this->s.m.bin(c, Bin::LShr, w, k2); + hi = this->s.m.bin(c, Bin::And, hi, mask); + V ht = this->s.m.bin(c, Bin::Shl, height, k14); + V d2 = this->s.m.bin(c, Bin::Or, hi, ht); + static constexpr std::uint32_t TY[8] = {0, 8, 9, 0, 10, 0, 12, 13}; + std::uint32_t ty = TY[kind]; // kind is 1, 2, 4, 6 or 7 + V base = k(0xFAC | ty << 28); + V last = this->s.m.bin(c, Bin::Shl, levels, k16); + V d3 = this->s.m.bin(c, Bin::Or, base, last); + words = {{1, d1}, {2, d2}, {3, d3}, {4, depth}}; + } else { + // A raw view counts bytes; the descriptor's record count is in elements. + V n = field(0); + std::uint32_t stride = used != nullptr ? used->stride : 0; + bool counted = false; + if (auto v = inst.write(Reg::S(static_cast<std::uint8_t>(code + first + 2)))) { + counted = this->read_as_number(*v); + } + if ((props.first & 0xFF) == 11 && stride > 1) { + V kk = this->s.m.i32(stride); + n = this->s.m.bin(c, Bin::UDiv, n, kk); + } else { + std::optional<V> slot; + if ((props.first & 0xFF) == 11 && counted) slot = this->slot_stride(src); + if (slot) { + // Picked from the heap: the host's table has the stride. + Ty i32t2 = this->s.t.i32; + V one = this->s.m.i32(1); + V kk = this->s.op(c, "binary.i32", Attr::ReadNone, i32t2, 39, std::vector<V>{*slot, one}); + n = this->s.m.bin(c, Bin::UDiv, n, kk); + } + } + words = {{2, n}}; + // Its address too, where the code computes with it and the host can tell it. + bool computed = false; + for (std::uint8_t k = 0; k < 2 && !computed; ++k) { + if (auto v = inst.write(Reg::S(static_cast<std::uint8_t>(code + first + k)))) { + computed = this->computed_with(*v, 6); + } + } + // (A descriptor nothing uses as one gets it whenever the host can tell it, as a buffer + // whose address alone is read does.) + if (first == 0 && (computed || unused)) { + if (auto va = this->view_address(site)) { + words.emplace_back(0, va->first); + words.emplace_back(1, va->second); + } + } + } + for (std::uint32_t k = 0; k < count; ++k) { + std::uint32_t rel = k - static_cast<std::uint32_t>(first); // wrapping_sub + const std::pair<std::uint32_t, V>* found = nullptr; + for (const auto& w : words) { + if (w.first == rel) { + found = &w; + break; + } + } + if (found) { + this->write(inst, Reg::S(static_cast<std::uint8_t>(code + k)), found->second, std::nullopt); + } else if (auto v = inst.write(Reg::S(static_cast<std::uint8_t>(code + k)))) { + this->vals.insert_or_assign(*v, Val::Missing(OTHER)); + this->stale.insert(*v); + } + } +} + +// What descriptor_data makes of a descriptor load that nothing uses as a descriptor but whose +// dwords the code reads: the first dword, the handle properties, the image kind (none for a +// buffer), whether it is an unordered view, and its used-resource entry. An image's eight dwords +// read as a 2D texture's, a buffer's four as a raw view's where the code reads its record count +// (dword 2); none for anything else (a constant buffer, a sampler, a buffer whose address alone +// is read). +// shortcut: an image whose kind nothing tells is taken for a 2D texture (the title's reads are +// texel sizes of 2D textures: puddle masks, shadow masks); a host view of another kind would +// answer its own sizes. +std::optional<std::tuple<std::uint8_t, std::pair<std::uint32_t, std::uint32_t>, std::optional<std::uint32_t>, bool, const UsedResource*>> +Lower::unused_descriptor_kind(const Inst& inst, Site site, std::uint8_t code, std::uint32_t count) const { + // Kept per lane and compared (`Resources::lane_copied`), or a sampler's: the cases + // `descriptor_data` handles on their own. + const auto& lc = this->x.res->lane_copied; + if (std::find(lc.begin(), lc.end(), site) != lc.end()) return std::nullopt; + for (const auto& d : this->x.res->descriptors) { + if (d.role != Role::Sampler) continue; + for (const Source* l : d.source.leaves()) { + if (loaded_at(*l, site)) return std::nullopt; + } + } + const UsedResource* used = this->used_kind(make_loaded(site, 0)); + if (used != nullptr && !(used->kind == ResourceType::Srv() || used->kind == ResourceType::Uav())) { + return std::nullopt; + } + auto read = [&](std::uint32_t k) { + auto v = inst.write(Reg::S(static_cast<std::uint8_t>(code + k))); + if (!v) return false; + for (const auto& b : this->x.p->blocks) { + for (const auto& i : b.insts) { + for (const auto& r : i.reads) { + if (r.second == *v) return true; + } + } + } + return false; + }; + const bool uav = used != nullptr && used->kind == ResourceType::Uav(); + const std::uint32_t u = uav ? 0x1000 : 0; + if (count == 8) { + // width (dwords 1-2), height (2), levels (3), depth (4) + bool any = false; + for (std::uint32_t k = 1; k < 5 && !any; ++k) any = read(k); + if (any && (used == nullptr || used->dwords == 8)) { + return std::tuple{std::uint8_t{0}, std::pair<std::uint32_t, std::uint32_t>{2 | u, 0x409}, + std::optional<std::uint32_t>{2}, uav, used}; + } + } else if (count == 4) { + // the record count + if (read(2) && (used == nullptr || used->dwords == 4)) { + return std::tuple{std::uint8_t{0}, std::pair<std::uint32_t, std::uint32_t>{11 | u, 0}, + std::optional<std::uint32_t>{}, uav, used}; + } + } + return std::nullopt; +} + +// `s_load_dword*` from the program's constant table. +void Lower::code_smem(const Inst& inst, Address a) { + const auto* sm = std::get_if<gfx10::Smem>(&inst.fields); + if (!sm || !sm->data || sm->data->kind != Operand::Kind::Scalar) { + fail("a scalar load"); + } + const std::uint8_t code = sm->data->code; + constexpr std::string_view prefix = "s_load_dword"; + std::string_view iname = inst.name(); + if (!iname.starts_with(prefix)) fail("a scalar load from the code"); + const std::uint32_t count = ok_or(dword_count(iname.substr(prefix.size())), "a scalar load from the code"); + std::size_t c = this->cur; + V addr = this->s.m.i32(a.offset); + if (a.dynamic) { + const Value value = *a.dynamic; + V d = this->i32_of(value); + // A term held per lane reached the address through `v_readfirstlane_b32`: the first lane's. + bool per_lane = false; + if (auto it = this->def_block.find(value); it != this->def_block.end()) { + for (const auto& i : this->x.p->blocks.at(it->second).insts) { + for (const auto& w : i.writes) { + if (w.second == value && w.first.is_v()) { + per_lane = true; + break; + } + } + if (per_lane) break; + } + } + if (per_lane) { + this->s.flags |= flags::WAVE_OPS; + Ty i32t = this->s.t.i32; + V first = this->s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, std::vector<V>{d}); + if (this->s.pixel && emit::helper_own()) { + V helper = this->helper_lane(); + d = this->s.m.select(c, helper, d, first); + } else { + d = first; + } + } + addr = this->s.m.bin(c, Bin::Add, addr, d); + } + for (std::uint32_t k = 0; k < count; ++k) { + V off = this->s.m.i32(4 * k); + V at = this->s.m.bin(c, Bin::Add, addr, off); + V xk = this->code_dword(at); + this->write(inst, Reg::S(static_cast<std::uint8_t>(code + k)), xk, std::nullopt); + } +} + +// The dword at a computed byte address of a constant buffer. +V Lower::cbuffer_dword(V h, V a) { + std::size_t c = this->cur; + V four = this->s.m.i32(4); + V ri = this->s.m.bin(c, Bin::LShr, a, four); + V r = this->s.op(c, "cbufferLoadLegacy.i32", Attr::ReadOnly, this->s.t.cbuf_ret, 59, std::vector<V>{h, ri}); + V two = this->s.m.i32(2); + V three = this->s.m.i32(3); + V comp = this->s.m.bin(c, Bin::LShr, a, two); + comp = this->s.m.bin(c, Bin::And, comp, three); + V x = this->s.m.extract(c, r, 0); + for (std::uint32_t j = 1; j < 4; ++j) { + V e = this->s.m.extract(c, r, j); + V jc = this->s.m.i32(j); + V is = this->s.m.cmp(c, pred::EQ, comp, jc); + x = this->s.m.select(c, is, e, x); + } + return x; +} + +// `channels` channels of the element at byte `off` of raw buffer `h`, converted from the GFX10 +// buffer format `format` as the hardware's typed loads do (channels past the format's read 0, 0, +// 0, 1). +// shortcut: the descriptor's channel swizzle is taken as the identity (it is for raw views and +// the descriptors code builds), elements of 4 bytes or more as dword-aligned. +std::vector<V> Lower::format_load(V h, V off, std::uint8_t format, std::uint32_t channels) { + auto [bits, numeric] = ok_or(buffer_format(format), "a buffer format"); + std::size_t c = this->cur; + std::uint32_t total = 0; + for (std::uint32_t b : bits) total += b; + V u = this->s.m.undef(this->s.t.i32); + V align = this->s.m.i32(4); + auto load = [&](V at, std::uint32_t n) { + V mask = this->s.m.i8(static_cast<std::uint8_t>((1u << n) - 1)); + V r = this->s.op(c, "rawBufferLoad.f32", Attr::ReadOnly, this->s.t.res_ret, 139, + std::vector<V>{h, at, u, mask, align}); + std::vector<V> out; + for (std::uint32_t k = 0; k < n; ++k) { + V x = this->s.m.extract(c, r, k); + out.push_back(this->as_int(x)); + } + return out; + }; + std::vector<V> words; + if (total < 32) { + // A byte or half inside the dword that holds it. + V not3 = this->s.m.i32(~3u); + V three = this->s.m.i32(3); + V at = this->s.m.bin(c, Bin::And, off, not3); + V w = load(at, 1).at(0); + V byte = this->s.m.bin(c, Bin::And, off, three); + V sh = this->s.m.bin(c, Bin::Shl, byte, three); + words = {this->s.m.bin(c, Bin::LShr, w, sh)}; + } else { + words = load(off, total / 32); + } + auto float_ = [&](V f) { return this->as_int(f); }; + std::vector<V> out; + std::uint32_t at = 0; + for (std::uint32_t w : bits) { + V word = words.at(at / 32); + V field; + if (w == 32) { + field = word; + } else { + V sh = this->s.m.i32(at % 32); + V t = this->s.m.bin(c, Bin::LShr, word, sh); + V m = this->s.m.i32((1u << w) - 1); + field = this->s.m.bin(c, Bin::And, t, m); + } + at += w; + // Sign-extended from the field's top bit. + auto signed_ = [&]() { + if (w == 32) return field; + V k = this->s.m.i32(32 - w); + V t = this->s.m.bin(c, Bin::Shl, field, k); + return this->s.m.bin(c, Bin::AShr, t, k); + }; + Ty f32t = this->s.t.f32; + // A normalized format's ends are exactly 1.0 and -1.0. The host may divide through a + // reciprocal and land just below 1.0: RDNA 4 loaded 16_16_UNORM's 65535 as the half + // 0x3BFF, not 0x3C00. + V x; + switch (numeric) { + case Numeric::Unorm: { + std::uint64_t top = (std::uint64_t{1} << w) - 1; + V q; + if (w <= 16) { + V qi = this->norm_quotient(field, w); + q = this->as_float(qi); + } else { + V f = this->s.m.cast(c, Cast::UiToFp, field, f32t); + V max = this->s.m.f32(f32_bits(static_cast<float>(top))); + q = this->s.m.bin(c, Bin::SDiv, f, max); + } + V high = this->s.m.i32(static_cast<std::uint32_t>(top)); + V one = this->s.m.f32(f32_bits(1.0f)); + V at_top = this->s.m.cmp(c, pred::EQ, field, high); + q = this->s.m.select(c, at_top, one, q); + x = float_(q); + break; + } + case Numeric::Snorm: { + V sv = signed_(); + std::uint32_t top = (1u << (w - 1)) - 1; + V q; + if (w <= 17) { + // The magnitude's quotient, signed (codes at and below -top are -1.0 below). + V zero = this->s.m.i32(0); + V sign = this->s.m.i32(0x8000'0000u); + V neg = this->s.m.cmp(c, pred::SLT, sv, zero); + V minus = this->s.m.bin(c, Bin::Sub, zero, sv); + V m = this->s.m.select(c, neg, minus, sv); + V qi = this->norm_quotient(m, w - 1); + sign = this->s.m.select(c, neg, sign, zero); + qi = this->s.m.bin(c, Bin::Or, qi, sign); + q = this->as_float(qi); + } else { + V f = this->s.m.cast(c, Cast::SiToFp, sv, f32t); + V max = this->s.m.f32(f32_bits(static_cast<float>(top))); + q = this->s.m.bin(c, Bin::SDiv, f, max); + } + // The lowest value is -1.0 too, as is the one above it. + V high = this->s.m.i32(top); + V one = this->s.m.f32(f32_bits(1.0f)); + V at_top = this->s.m.cmp(c, pred::SGE, sv, high); + q = this->s.m.select(c, at_top, one, q); + V low = this->s.m.i32(0u - top); // wrapping_neg + V minus_one = this->s.m.f32(f32_bits(-1.0f)); + V at_bottom = this->s.m.cmp(c, pred::SLE, sv, low); + q = this->s.m.select(c, at_bottom, minus_one, q); + x = float_(q); + break; + } + case Numeric::Uscaled: { + V f = this->s.m.cast(c, Cast::UiToFp, field, f32t); + x = float_(f); + break; + } + case Numeric::Sscaled: { + V sv = signed_(); + V f = this->s.m.cast(c, Cast::SiToFp, sv, f32t); + x = float_(f); + break; + } + case Numeric::Uint: + x = field; + break; + case Numeric::Sint: + x = signed_(); + break; + case Numeric::Float: { + if (w == 32) { + x = field; + break; + } + V hv; + std::uint32_t k = half_shift(w); + if (k == 0) { + hv = field; + } else { + V sh = this->s.m.i32(k); + hv = this->s.m.bin(c, Bin::Shl, field, sh); + } + V f = this->s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, std::vector<V>{hv}); + x = float_(f); + break; + } + } + out.push_back(x); + } + std::uint32_t one = (numeric == Numeric::Uint || numeric == Numeric::Sint) ? 1u : f32_bits(1.0f); + for (std::uint32_t k = static_cast<std::uint32_t>(out.size()); k < channels; ++k) { + out.push_back(this->s.m.i32(k == 3 ? one : 0)); + } + if (out.size() > channels) out.resize(channels); // truncate + return out; +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_valu.cpp b/src/x2w_shader/emit/lower_valu.cpp new file mode 100644 index 0000000000..f94d4dc91a --- /dev/null +++ b/src/x2w_shader/emit/lower_valu.cpp @@ -0,0 +1,1230 @@ +// VALU instructions. See GMR/vs_port/lower/PORTING.md for the conventions. +#include "x2w_shader/emit/lower_impl.h" + +#include <algorithm> +#include <cstdlib> +#include <string> + +namespace x2w::vs::lower { + +namespace { + +// `Some(Operand::Vector { reg, .. })` of an optional operand. +std::optional<std::uint8_t> vector_reg(const std::optional<Operand>& o) { + if (o && o->kind == Operand::Kind::Vector) return o->reg; + return std::nullopt; +} +std::optional<std::uint8_t> vector_reg(const Operand* o) { + if (o && o->kind == Operand::Kind::Vector) return o->reg; + return std::nullopt; +} +// `Some(Operand::Scalar { code, .. })` of an optional operand. +std::optional<std::uint8_t> scalar_code(const std::optional<Operand>& o) { + if (o && o->kind == Operand::Kind::Scalar) return o->code; + return std::nullopt; +} +std::optional<std::uint8_t> scalar_code(const Operand* o) { + if (o && o->kind == Operand::Kind::Scalar) return o->code; + return std::nullopt; +} +// `v.src.get(k)`. +const Operand* src_at(const gfx10::Valu& v, std::size_t k) { + return k < v.src.size() ? &v.src[k] : nullptr; +} + +} // namespace + +void Lower::valu(const Inst& inst, std::size_t b, std::size_t i) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + std::string_view name = inst.name(); + + { + const auto& compares = this->x.res->waterfall.compares; + if (std::find(compares.begin(), compares.end(), Site{b, i}) != compares.end()) { + // The first lane's dwords of a waterfall loop are each lane's + // own (see `resource::Waterfall`). + this->lane(inst, true); + return; + } + } + // One lane of a VGPR a whole-wave section left. + if (name == "v_readlane_b32" && !inst.writes.empty()) { + Value w = inst.writes.front().second; + std::optional<wave::Shape> sh; + if (auto s = this->sections.find(b); s != this->sections.end()) { + // Take the first completed section that read w. Sections do not overlap, and each value is normally read by + // at most one qualifying section. The table has no stable iteration order. + for (const auto& [start, sec] : s->second) { + if (!(sec.end < i)) continue; + if (auto r = sec.reads.find(w); r != sec.reads.end()) { + sh = r->second; + break; + } + } + } + if (sh) { + V x = this->shape(*sh, false); + this->vals.insert_or_assign(w, Val::I32(x)); + return; + } + } + { + std::optional<std::string_view> rest; + if (name.starts_with("v_cmp_")) { + rest = name.substr(6); + } else if (name.starts_with("v_cmpx_")) { + rest = name.substr(7); + } + if (rest) { + std::optional<Why> why; + if (v.dpp) { + why = "a compare with DPP"; + } else { + try { + this->compare(inst, *rest); + } catch (const WhyFail& e) { + why = e.why; + } + } + if (why) { + for (const auto& [_, w] : inst.writes) { + this->lane_fail.insert_or_assign(w, *why); + } + fail(*why); + } + return; + } + } + std::optional<V> guard = this->guard(b, i); + if (v.dpp) { + auto [x, enable] = this->dpp(inst, *v.dpp); + if (guard && enable) { + guard = this->s.m.bin(this->cur, Bin::And, *guard, *enable); + } else if (!guard) { + guard = enable; + } + this->src0 = x; + } + // Clear src0 after evaluating the instruction. + try { + this->valu_op(inst, guard); + } catch (...) { + this->src0 = std::nullopt; + throw; + } + this->src0 = std::nullopt; +} + +// DPP: src0 as read from another lane, and which lanes write their result (none: all). +std::pair<V, std::optional<V>> Lower::dpp(const Inst& inst, const Dpp& dpp) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + auto reg0 = vector_reg(v.src.empty() ? nullptr : &v.src.front()); + if (!reg0) fail("a DPP operand"); + std::uint8_t reg = *reg0; + V x = this->i32_of(ok_or(inst.read(Reg::V(reg)), "a DPP operand")); + // Quad permutations and DPP8 stay in groups the pixel layout shares. + const auto* row_dpp = std::get_if<gfx10::DppRow>(&dpp); + bool quad = row_dpp && row_dpp->ctrl <= 0xFF; + bool mesh_quad = this->s.mesh.has_value() && quad; + if (!mesh_quad) { + this->cross_lane(quad); + } + std::size_t c = this->cur; + V lane = this->lane_index(); + auto k = [&](std::uint32_t n) { return this->s.m.i32(n); }; + V sixteen_mask = k(~15u); + V low = k(15); + V row = this->s.m.bin(c, Bin::And, lane, sixteen_mask); + V pos = this->s.m.bin(c, Bin::And, lane, low); + // Source lane, and whether it lies in the row. + V src; + std::optional<V> inside; + std::optional<std::pair<std::uint8_t, std::uint8_t>> masks; + bool zero = false; + if (const auto* lanes = std::get_if<gfx10::DppLanes>(&dpp)) { + V seven = k(7); + V not7 = k(~7u); + V three = k(3); + V p = this->s.m.bin(c, Bin::And, lane, seven); + V sh = this->s.m.bin(c, Bin::Mul, p, three); + V sel = k(lanes->sel); + V pick = this->s.m.bin(c, Bin::LShr, sel, sh); + pick = this->s.m.bin(c, Bin::And, pick, seven); + V base = this->s.m.bin(c, Bin::And, lane, not7); + src = this->s.m.bin(c, Bin::Or, base, pick); + } else { + const auto& d = *row_dpp; + std::uint16_t ctrl = d.ctrl; + std::uint32_t n = std::uint32_t(ctrl & 15); + if (ctrl <= 0xFF) { + V three = k(3); + V one = k(1); + V not3 = k(~3u); + V p = this->s.m.bin(c, Bin::And, lane, three); + V sh = this->s.m.bin(c, Bin::Shl, p, one); + V perm = k(std::uint32_t(ctrl)); + V pick = this->s.m.bin(c, Bin::LShr, perm, sh); + pick = this->s.m.bin(c, Bin::And, pick, three); + V base = this->s.m.bin(c, Bin::And, lane, not3); + src = this->s.m.bin(c, Bin::Or, base, pick); + } else if ((ctrl >= 0x101 && ctrl <= 0x10F) || (ctrl >= 0x111 && ctrl <= 0x11F)) { + V nn = k(n); + bool left = ctrl < 0x110; + Bin op = left ? Bin::Add : Bin::Sub; + std::uint8_t p = left ? pred::IULT : pred::IUGE; + V s = this->s.m.bin(c, op, lane, nn); + // Left: pos + n < 16; right: pos >= n. + V bound = left ? k(16 - n) : nn; + src = s; + inside = this->s.m.cmp(c, p, pos, bound); + } else if (ctrl >= 0x121 && ctrl <= 0x12F) { + V nn = k(n); + V t = this->s.m.bin(c, Bin::Sub, pos, nn); + t = this->s.m.bin(c, Bin::And, t, low); + src = this->s.m.bin(c, Bin::Or, row, t); + } else if (ctrl == 0x140 || ctrl == 0x141) { + V m = k(ctrl == 0x140 ? 15 : 7); + src = this->s.m.bin(c, Bin::Xor, lane, m); + } else if (ctrl >= 0x150 && ctrl <= 0x15F) { + V nn = k(n); + src = this->s.m.bin(c, Bin::Or, row, nn); + } else if (ctrl >= 0x160 && ctrl <= 0x16F) { + V nn = k(n); + src = this->s.m.bin(c, Bin::Xor, lane, nn); + } else { + fail("a DPP lane pattern"); + } + if (d.row_mask != 0xF || d.bank_mask != 0xF) masks = std::pair{d.row_mask, d.bank_mask}; + zero = d.bound_ctrl; + } + V r; + if (mesh_quad) { + r = this->quad_pick(x, src); + } else if (row_dpp && this->helpers_read(quad)) { + std::uint16_t ctrl = row_dpp->ctrl; + std::array<std::uint8_t, 4> pick{}; + for (int q = 0; q < 4; ++q) pick[q] = std::uint8_t((ctrl >> (2 * q)) & 3); + r = this->quad_read(x, pick); + } else { + r = this->read_lane(x, src); + } + std::optional<V> enable; + if (inside) { + if (zero) { + V z = k(0); + r = this->s.m.select(c, *inside, r, z); + } else { + enable = *inside; + } + } + if (masks) { + auto [rows, banks] = *masks; + // Row (16 lanes) and bank (4 lanes of a row) write masks. + V four = k(4); + V two = k(2); + V three = k(3); + V ri = this->s.m.bin(c, Bin::LShr, lane, four); + ri = this->s.m.bin(c, Bin::And, ri, three); + V bi = this->s.m.bin(c, Bin::LShr, lane, two); + bi = this->s.m.bin(c, Bin::And, bi, three); + V rm = k(std::uint32_t(rows)); + V bm = k(std::uint32_t(banks)); + V rb = this->s.m.bin(c, Bin::LShr, rm, ri); + V bb = this->s.m.bin(c, Bin::LShr, bm, bi); + V both = this->s.m.bin(c, Bin::And, rb, bb); + V one = k(1); + V z = k(0); + both = this->s.m.bin(c, Bin::And, both, one); + V on = this->s.m.cmp(c, pred::NE, both, z); + if (enable) { + enable = this->s.m.bin(c, Bin::And, *enable, on); + } else { + enable = on; + } + } + return {r, enable}; +} + +void Lower::valu_op(const Inst& inst, std::optional<V> guard) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + std::string_view name = inst.name(); + std::size_t c = this->cur; + auto f = [&](std::size_t k) { return this->fsrc(inst, k); }; + auto s = [&](std::size_t k) { return this->src(inst, k); }; + auto float_w = [&](V r) { this->write_f(inst, r, guard); }; + auto int_w = [&](V r) { this->write_i(inst, r, guard); }; + if (this->valu16(inst, name, guard)) { + return; + } + if (name.starts_with("v_pk_")) { + this->packed16(inst, name.substr(5), guard); + return; + } + auto is = [&](std::initializer_list<std::string_view> names) { + for (auto n : names) { + if (name == n) return true; + } + return false; + }; + if (name == "v_mad_u64_u32") { + // a * b + c, c and the result 64 bits wide; the carry out + // of the sum is this lane's bit of the mask it names. + V a = s(0); + V b = s(1); + V x = this->src64(inst, 2); + Ty i64t = this->s.m.int_(64); + this->s.flags |= flags::INT64; + a = this->s.m.cast(c, Cast::ZExt, a, i64t); + b = this->s.m.cast(c, Cast::ZExt, b, i64t); + V product = this->s.m.bin(c, Bin::Mul, a, b); + V r = this->s.m.bin(c, Bin::Add, product, x); + V carry = this->s.m.cmp(c, pred::IULT, r, x); + auto reg = vector_reg(v.dst); + if (!reg) fail("a 64-bit result"); + auto [lo, hi] = this->split64(r); + this->write(inst, Reg::V(*reg), lo, guard); + this->write(inst, Reg::V(std::uint8_t(*reg + 1)), hi, guard); + if (auto code = scalar_code(v.carry)) { + if (auto w = inst.write(Reg::S(*code))) { + this->lane_bits.insert_or_assign(*w, carry); + } + } + for (const auto& [_, w] : inst.writes) { + this->vals.try_emplace(w, Val::Missing("a lane mask read as data")); + } + return; + } else if (is({"v_lshlrev_b64", "v_lshrrev_b64", "v_ashrrev_i64"})) { + V n = s(0); + V x = this->src64(inst, 1); + Ty i64t = this->s.m.int_(64); + V k63 = this->s.m.i32(63); + n = this->s.m.bin(c, Bin::And, n, k63); + n = this->s.m.cast(c, Cast::ZExt, n, i64t); + Bin op = name == "v_lshlrev_b64" ? Bin::Shl : name == "v_lshrrev_b64" ? Bin::LShr : Bin::AShr; + V r = this->s.m.bin(c, op, x, n); + auto reg = vector_reg(v.dst); + if (!reg) fail("a 64-bit result"); + auto [lo, hi] = this->split64(r); + this->write(inst, Reg::V(*reg), lo, guard); + this->write(inst, Reg::V(std::uint8_t(*reg + 1)), hi, guard); + return; + } else if (is({"v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32"})) { + // Cube-map face coordinates (AMD's ISA): the major axis is z + // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|, + // else x. + V x = f(0); + V y = f(1); + V z = f(2); + V ax = this->unary(6, x); + V ay = this->unary(6, y); + V az = this->unary(6, z); + V zx = this->s.m.cmp(c, pred::OGE, az, ax); + V zy = this->s.m.cmp(c, pred::OGE, az, ay); + V zmaj = this->s.m.bin(c, Bin::And, zx, zy); + V ymaj = this->s.m.cmp(c, pred::OGE, ay, ax); + V zero = this->s.m.f32(0); + auto neg = [&](V w) { return this->s.m.cmp(c, pred::OLT, w, zero); }; + auto minus = [&](V w) { + V zz = this->s.m.f32(0x8000'0000u); + return this->s.m.bin(c, Bin::Sub, zz, w); + }; + auto pick = [&](V zv, V yv, V xv) { + V t = this->s.m.select(c, ymaj, yv, xv); + return this->s.m.select(c, zmaj, zv, t); + }; + V r; + if (name == "v_cubeid_f32") { + auto k = [&](float w) { return this->s.m.f32(f32_bits(w)); }; + V nz = neg(z); + V ny = neg(y); + V nx = neg(x); + V f5 = k(5.0f); + V f4 = k(4.0f); + V f3 = k(3.0f); + V f2 = k(2.0f); + V f1 = k(1.0f); + V f0 = k(0.0f); + V zf = this->s.m.select(c, nz, f5, f4); + V yf = this->s.m.select(c, ny, f3, f2); + V xf = this->s.m.select(c, nx, f1, f0); + r = pick(zf, yf, xf); + } else if (name == "v_cubesc_f32") { + V nz = neg(z); + V nx = neg(x); + V mx = minus(x); + V mz = minus(z); + V zf = this->s.m.select(c, nz, mx, x); + V xf = this->s.m.select(c, nx, z, mz); + r = pick(zf, x, xf); + } else if (name == "v_cubetc_f32") { + V ny = neg(y); + V my = minus(y); + V mz = minus(z); + V yf = this->s.m.select(c, ny, mz, z); + r = pick(my, yf, my); + } else { + V t = pick(z, y, x); + V two = this->s.m.f32(f32_bits(2.0f)); + r = this->s.m.bin(c, Bin::Mul, t, two); + } + float_w(r); + return; + } else if (is({"v_movrels_b32", "v_movreld_b32", "v_movrelsd_b32"})) { + // M0 indexes the source (movrels), the destination (movreld) + // or both, from the encoded register up to the program's + // VGPR count (the registers the instruction reads or writes). + V m0 = this->i32_of(ok_or(inst.read(Reg::S(ir::M0)), "M0")); + auto sreg_o = vector_reg(v.src.empty() ? nullptr : &v.src.front()); + auto dreg_o = vector_reg(v.dst); + if (!sreg_o || !dreg_o) fail("an M0-relative move"); + std::uint8_t sreg = *sreg_o; + std::uint8_t dreg = *dreg_o; + bool indexed_src = name != "v_movreld_b32"; + V value; + if (indexed_src) { + V r = this->s.m.i32(0); + for (unsigned k = 0; k <= 255u - sreg; ++k) { + auto xv = inst.read(Reg::V(std::uint8_t(sreg + k))); + if (!xv) break; + V xx = this->i32_of(*xv); + V kk = this->s.m.i32(std::uint32_t(k)); + V eq = this->s.m.cmp(c, pred::EQ, m0, kk); + r = this->s.m.select(c, eq, xx, r); + } + value = r; + } else { + value = s(0); + } + if (name == "v_movrels_b32") { + int_w(value); + return; + } + for (unsigned k = 0; k <= 255u - dreg; ++k) { + Reg rk = Reg::V(std::uint8_t(dreg + k)); + if (!inst.write(rk)) break; + V old; + if (auto o = inst.read(rk)) { + old = this->i32_of(*o); + } else { + old = this->s.m.i32(0); + } + V kk = this->s.m.i32(std::uint32_t(k)); + V eq = this->s.m.cmp(c, pred::EQ, m0, kk); + V xx = this->s.m.select(c, eq, value, old); + this->write_placed(inst, rk, xx, guard); + } + return; + } else if (name == "v_swap_b32") { + auto sreg_o = vector_reg(v.src.empty() ? nullptr : &v.src.front()); + auto dreg_o = vector_reg(v.dst); + if (!sreg_o || !dreg_o) fail("v_swap_b32"); + std::uint8_t sreg = *sreg_o; + std::uint8_t dreg = *dreg_o; + V a = this->i32_of(ok_or(inst.read(Reg::V(dreg)), "v_swap_b32")); + V b = this->i32_of(ok_or(inst.read(Reg::V(sreg)), "v_swap_b32")); + this->write_placed(inst, Reg::V(dreg), b, guard); + if (dreg != sreg) { + this->write_placed(inst, Reg::V(sreg), a, guard); + } + return; + } else if (name == "v_ffbh_u32" || name == "v_ffbh_i32") { + // Counted from the top bit, -1 when none (DXIL's too). + V a = s(0); + std::uint32_t op = name == "v_ffbh_u32" ? 33 : 34; + V r = this->s.op(c, "unaryBits.i32", Attr::ReadNone, this->s.t.i32, op, std::vector<V>{a}); + int_w(r); + return; + } else if (name == "v_dot4c_i32_i8") { + // D += the dot product of four signed bytes, wrapping: DXIL's + // Dot4AddI8Packed. + V a = s(0); + V bb = s(1); + auto reg = vector_reg(v.dst); + if (!reg) fail("an accumulator"); + V acc = this->i32_of(ok_or(inst.read(Reg::V(*reg)), "an accumulator")); + Ty i32_ty = this->s.t.i32; + V r = this->s.op(c, "dot4AddPacked.i32", Attr::ReadNone, i32_ty, 163, std::vector<V>{acc, a, bb}); + int_w(r); + return; + } else if (name == "v_dot4_i32_i8") { + // VOP3P: op_sel picks the half each multiplicand's low half + // reads, op_sel_hi its high half's; the accumulator is read + // whole (as AMD's compilers fold constants into it). + if (v.clamp || v.neg_hi != 0) { + fail("a saturating or negated dot product"); + } + std::vector<V> xs; + for (std::size_t k = 0; k < 2; ++k) { + V xx = s(k); + bool lo = ((v.opsel >> k) & 1) != 0; + bool hi = ((v.opsel_hi >> k) & 1) != 0; + if (!lo && hi) { + xs.push_back(xx); + continue; + } + V k16 = this->s.m.i32(16); + V lowm = this->s.m.i32(0xFFFF); + V top = this->s.m.bin(c, Bin::LShr, xx, k16); + V bottom = this->s.m.bin(c, Bin::And, xx, lowm); + V hv = this->s.m.bin(c, Bin::Shl, hi ? top : bottom, k16); + xs.push_back(this->s.m.bin(c, Bin::Or, lo ? top : bottom, hv)); + } + V acc = s(2); + Ty i32_ty = this->s.t.i32; + V r = this->s.op(c, "dot4AddPacked.i32", Attr::ReadNone, i32_ty, 163, + std::vector<V>{acc, xs[0], xs[1]}); + int_w(r); + return; + } else if (name == "v_mov_b32") { + if (v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0) { + V a = f(0); + float_w(a); + return; + } + V a = s(0); + int_w(a); + return; + } else if (is({"v_add_f32", "v_sub_f32", "v_subrev_f32", "v_mul_f32", "v_mul_legacy_f32", "v_max_f32", + "v_min_f32"})) { + V a = f(0); + V bb = f(1); + V r; + if (name == "v_add_f32") { + r = this->s.m.bin(c, Bin::Add, a, bb); + } else if (name == "v_sub_f32") { + r = this->s.m.bin(c, Bin::Sub, a, bb); + } else if (name == "v_subrev_f32") { + r = this->s.m.bin(c, Bin::Sub, bb, a); + } else if (name == "v_mul_f32") { + r = this->s.m.bin(c, Bin::Mul, a, bb); + } else if (name == "v_mul_legacy_f32") { + r = this->legacy_mul(a, bb); + } else if (name == "v_max_f32") { + r = this->max_min(true, a, bb); + } else { + r = this->max_min(false, a, bb); + } + float_w(r); + return; + } else if (is({"v_fma_f32", "v_fmaak_f32", "v_fmamk_f32"})) { + // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse. + V a = f(0); + V bb = f(1); + V cc = f(2); + V r = this->fmad(a, bb, cc); + float_w(r); + return; + } else if (name == "v_div_scale_f32") { + // RDNA2 ISA: src0 = value to scale, src1 = denominator, src2 = numerator. + V a = f(0); + V den = f(1); + V num = f(2); + V ai = this->as_int(a); + V ni = this->as_int(num); + V di = this->as_int(den); + V k23 = this->s.m.i32(23); + V k255 = this->s.m.i32(0xFF); + V kabs = this->s.m.i32(0x7FFF'FFFF); + V zero = this->s.m.i32(0); + V k23_exp = this->s.m.i32(23); + V k232_exp = this->s.m.i32(232); + V k96 = this->s.m.i32(96); + auto exp_of = [&](V xx) { + V sh = this->s.m.bin(c, Bin::LShr, xx, k23); + return this->s.m.bin(c, Bin::And, sh, k255); + }; + V e1 = exp_of(ni); + V e2 = exp_of(di); + V n_abs = this->s.m.bin(c, Bin::And, ni, kabs); + V d_abs = this->s.m.bin(c, Bin::And, di, kabs); + V z1 = this->s.m.cmp(c, pred::EQ, n_abs, zero); + V z2 = this->s.m.cmp(c, pred::EQ, d_abs, zero); + V any_zero = this->s.m.bin(c, Bin::Or, z1, z2); + V special; + { + V s1 = this->s.m.cmp(c, pred::EQ, e1, k255); + V s2 = this->s.m.cmp(c, pred::EQ, e2, k255); + V a12 = this->s.m.bin(c, Bin::Or, s1, s2); + special = this->s.m.bin(c, Bin::Or, a12, any_zero); + } + V is_den = this->s.m.cmp(c, pred::EQ, ai, di); + V diff = this->s.m.bin(c, Bin::Sub, e2, e1); + V den_tiny = this->s.m.cmp(c, pred::IULE, e2, k23_exp); + V den_huge = this->s.m.cmp(c, pred::IUGE, e2, k232_exp); + V num_tiny_exp = this->s.m.cmp(c, pred::IULE, e1, k23_exp); + V num_huge = this->s.m.cmp(c, pred::IUGE, e1, k232_exp); + V num_gap = this->s.m.cmp(c, pred::SGE, diff, k96); + V not_den_huge; + { + V t = this->s.m.bool_(true); + not_den_huge = this->s.m.bin(c, Bin::Xor, den_huge, t); + } + num_gap = this->s.m.bin(c, Bin::And, num_gap, not_den_huge); + V num_tiny = this->s.m.bin(c, Bin::Or, num_tiny_exp, num_gap); + V up_raw = this->s.m.select(c, is_den, den_tiny, num_tiny); + V dn_raw = this->s.m.select(c, is_den, den_huge, num_huge); + V not_special; + { + V t = this->s.m.bool_(true); + not_special = this->s.m.bin(c, Bin::Xor, special, t); + } + V up = this->s.m.bin(c, Bin::And, up_raw, not_special); + V dn = this->s.m.bin(c, Bin::And, dn_raw, not_special); + V uncancelled; + { + V x_tiny = this->s.m.bin(c, Bin::Xor, den_tiny, num_tiny); + V x_huge = this->s.m.bin(c, Bin::Xor, den_huge, num_huge); + uncancelled = this->s.m.bin(c, Bin::Or, x_tiny, x_huge); + } + V flag_raw = this->s.m.select(c, is_den, uncancelled, up_raw); + V flag = this->s.m.bin(c, Bin::And, flag_raw, not_special); + V k_up = this->s.m.f32(0x5F80'0000u); + V k_dn = this->s.m.f32(0x1F80'0000u); + V a_up = this->s.m.bin(c, Bin::Mul, a, k_up); + V a_dn = this->s.m.bin(c, Bin::Mul, a, k_dn); + V r = this->s.m.select(c, dn, a_dn, a); + r = this->s.m.select(c, up, a_up, r); + V qnan = this->s.m.f32(0x7FC0'0000u); + r = this->s.m.select(c, any_zero, qnan, r); + float_w(r); + if (auto code = scalar_code(v.carry)) { + if (auto w = inst.write(Reg::S(*code))) { + this->lane_bits.insert_or_assign(*w, flag); + } + } + for (const auto& [_, w] : inst.writes) { + this->vals.try_emplace(w, Val::Missing("a lane mask read as data")); + } + return; + } else if (name == "v_div_fmas_f32") { + V a = f(0); + V bb = f(1); + V cc = f(2); + std::optional<Bool> m; + if (auto vcc = inst.read(Reg::S(ir::VCC))) { + + if (auto it = this->x.st->masks.find(*vcc); it != this->x.st->masks.end()) m = it->second; + } + if (!m) fail("v_div_fmas_f32 without VCC"); + V vcc = this->boolean(*m, c); + V tmp = this->fmad(a, bb, cc); + V ci = this->as_int(cc); + V k23 = this->s.m.i32(23); + V k255 = this->s.m.i32(0xFF); + V k128 = this->s.m.i32(128); + V sh = this->s.m.bin(c, Bin::LShr, ci, k23); + V exp = this->s.m.bin(c, Bin::And, sh, k255); + V exp_ge = this->s.m.cmp(c, pred::IUGE, exp, k128); + V k_up = this->s.m.f32(0x5F80'0000u); + V k_dn = this->s.m.f32(0x1F80'0000u); + V scale = this->s.m.select(c, exp_ge, k_up, k_dn); + V scaled = this->s.m.bin(c, Bin::Mul, tmp, scale); + V r = this->s.m.select(c, vcc, scaled, tmp); + float_w(r); + return; + } else if (name == "v_div_fixup_f32") { + V q = f(0); + V den = f(1); + V num = f(2); + V qi = this->as_int(q); + V di = this->as_int(den); + V ni = this->as_int(num); + V ksign = this->s.m.i32(0x8000'0000u); + V kabs = this->s.m.i32(0x7FFF'FFFF); + V kinf = this->s.m.i32(0x7F80'0000); + V kqnan_bit = this->s.m.i32(0x0040'0000); + V kneg_qnan = this->s.m.i32(0xFFC0'0000u); + V zero = this->s.m.i32(0); + V sign; + { + V xx = this->s.m.bin(c, Bin::Xor, ni, di); + sign = this->s.m.bin(c, Bin::And, xx, ksign); + } + V q_abs = this->s.m.bin(c, Bin::And, qi, kabs); + V d_abs = this->s.m.bin(c, Bin::And, di, kabs); + V n_abs = this->s.m.bin(c, Bin::And, ni, kabs); + V q_nan = this->s.m.cmp(c, pred::IUGT, q_abs, kinf); + V d_nan = this->s.m.cmp(c, pred::IUGT, d_abs, kinf); + V n_nan = this->s.m.cmp(c, pred::IUGT, n_abs, kinf); + V d_inf = this->s.m.cmp(c, pred::EQ, d_abs, kinf); + V n_inf = this->s.m.cmp(c, pred::EQ, n_abs, kinf); + V d_zero = this->s.m.cmp(c, pred::EQ, d_abs, zero); + V n_zero = this->s.m.cmp(c, pred::EQ, n_abs, zero); + V both_inf = this->s.m.bin(c, Bin::And, n_inf, d_inf); + V both_zero = this->s.m.bin(c, Bin::And, n_zero, d_zero); + V invalid = this->s.m.bin(c, Bin::Or, both_inf, both_zero); + V make_inf; + { + V t = this->s.m.bin(c, Bin::Or, n_inf, d_zero); + make_inf = this->s.m.bin(c, Bin::Or, t, q_nan); + } + V make_zero = this->s.m.bin(c, Bin::Or, d_inf, n_zero); + V signed_q = this->s.m.bin(c, Bin::Or, sign, q_abs); + V signed_inf = this->s.m.bin(c, Bin::Or, sign, kinf); + V n_qnan = this->s.m.bin(c, Bin::Or, ni, kqnan_bit); + V d_qnan = this->s.m.bin(c, Bin::Or, di, kqnan_bit); + V r = this->s.m.select(c, make_zero, sign, signed_q); + r = this->s.m.select(c, make_inf, signed_inf, r); + r = this->s.m.select(c, invalid, kneg_qnan, r); + r = this->s.m.select(c, d_nan, d_qnan, r); + r = this->s.m.select(c, n_nan, n_qnan, r); + V rf = this->as_float(r); + float_w(rf); + return; + } else if (is({"v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32"})) { + V a = f(0); + V bb = f(1); + auto reg = vector_reg(v.dst); + if (!reg) fail("an accumulator"); + Value acc_v = ok_or(inst.read(Reg::V(*reg)), "an accumulator"); + V acc; + if (auto it = this->floats.find(acc_v); it != this->floats.end()) { + acc = it->second; + } else { + V xx = this->i32_of(acc_v); + acc = this->as_float(xx); + } + V r; + if (name == "v_fmac_f32") { + r = this->fmad(a, bb, acc); + } else if (name == "v_mac_f32") { + V m = this->s.m.bin(c, Bin::Mul, a, bb); + r = this->s.m.bin(c, Bin::Add, m, acc); + } else { + V m = this->legacy_mul(a, bb); + r = this->s.m.bin(c, Bin::Add, m, acc); + } + float_w(r); + return; + } else if (is({"v_mad_f32", "v_madak_f32", "v_madmk_f32", "v_mad_legacy_f32"})) { + V a = f(0); + V bb = f(1); + V cc = f(2); + V m = name == "v_mad_legacy_f32" ? this->legacy_mul(a, bb) : this->s.m.bin(c, Bin::Mul, a, bb); + V r = this->s.m.bin(c, Bin::Add, m, cc); + float_w(r); + return; + } else if (is({"v_max3_f32", "v_min3_f32", "v_med3_f32"})) { + V a = f(0); + V bb = f(1); + V cc = f(2); + V r; + if (name == "v_max3_f32") { + V t = this->max_min(true, a, bb); + r = this->max_min(true, t, cc); + } else if (name == "v_min3_f32") { + V t = this->max_min(false, a, bb); + r = this->max_min(false, t, cc); + } else { + r = this->med3(a, bb, cc); + } + float_w(r); + return; + } else if (name == "v_rcp_f32" || name == "v_rcp_iflag_f32") { + // shortcut: the hardware reciprocal is approximate (1 ULP); this divides. + V a = f(0); + V one = this->s.m.f32(f32_bits(1.0f)); + V r = this->s.m.bin(c, Bin::SDiv, one, a); + float_w(r); + return; + } else if (is({"v_rsq_f32", "v_sqrt_f32", "v_log_f32", "v_exp_f32", "v_fract_f32", "v_trunc_f32", + "v_floor_f32", "v_ceil_f32", "v_rndne_f32", "v_sin_f32", "v_cos_f32"})) { + V a = f(0); + std::uint32_t op = name == "v_rsq_f32" ? 25 + : name == "v_sqrt_f32" ? 24 + : name == "v_log_f32" ? 23 + : name == "v_exp_f32" ? 21 + : name == "v_fract_f32" ? 22 + : name == "v_trunc_f32" ? 29 + : name == "v_floor_f32" ? 27 + : name == "v_ceil_f32" ? 28 + : name == "v_rndne_f32" ? 26 + : name == "v_sin_f32" ? 13 + : 12; + V r; + if (op == 12 || op == 13) { + r = this->trig_turns(a, op == 12); + } else if (op == 22) { + r = this->fract(a, 1.0f, f32_from_bits(0x3F7F'FFFF)); + } else { + r = this->unary(op, a); + } + float_w(r); + return; + } else if (is({"v_cvt_i32_f32", "v_cvt_u32_f32", "v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32"})) { + V a = f(0); + if (name == "v_cvt_rpi_i32_f32") { + V h = this->s.m.f32(f32_bits(0.5f)); + a = this->s.m.bin(c, Bin::Add, a, h); + } + if (name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32") { + a = this->unary(27, a); + } + // D3D's conversions saturate and give 0 for NaN, as the + // hardware does (checked on the RX 6700 XT and WARP). + Cast op = name == "v_cvt_u32_f32" ? Cast::FpToUi : Cast::FpToSi; + V r = this->s.m.cast(c, op, a, this->s.t.i32); + int_w(r); + return; + } else if (name == "v_cvt_f32_f64") { + auto [lo, hi] = this->f64_pair(inst, 0); + V bits = this->f64_to_f32_bits(lo, hi); + V r = this->as_float(bits); + float_w(r); + return; + } else if (is({"v_cvt_f32_i32", "v_cvt_f32_u32", "v_cvt_f32_ubyte0", "v_cvt_f32_ubyte1", "v_cvt_f32_ubyte2", + "v_cvt_f32_ubyte3"})) { + V a = s(0); + if (name.starts_with("v_cvt_f32_ubyte")) { + std::string_view n = name.substr(std::string_view("v_cvt_f32_ubyte").size()); + V sh = this->s.m.i32(8 * std::uint32_t(std::uint8_t(n.at(0) - '0'))); + V ff = this->s.m.i32(0xff); + a = this->s.m.bin(c, Bin::LShr, a, sh); + a = this->s.m.bin(c, Bin::And, a, ff); + } + Cast op = name == "v_cvt_f32_i32" ? Cast::SiToFp : Cast::UiToFp; + V r = this->s.m.cast(c, op, a, this->s.t.f32); + float_w(r); + return; + } else if (name == "v_cvt_off_f32_i4") { + // The low nibble as a signed 4-bit integer, over 16. + V a = s(0); + V k28 = this->s.m.i32(28); + a = this->s.m.bin(c, Bin::Shl, a, k28); + a = this->s.m.bin(c, Bin::AShr, a, k28); + V fl = this->s.m.cast(c, Cast::SiToFp, a, this->s.t.f32); + V k = this->s.m.f32(f32_bits(0.0625f)); + V r = this->s.m.bin(c, Bin::Mul, fl, k); + float_w(r); + return; + } else if (is({"v_fma_mix_f32", "v_fma_mixlo_f16", "v_fma_mixhi_f16"})) { + // Each source is f32, or with op_sel_hi the low (op_sel: high) + // f16 half; neg_hi is the absolute value here. + std::vector<V> xs; + for (std::size_t i = 0; i < 3; ++i) { + const Operand* op = ok_or(src_at(v, i), "a missing operand"); + V xx; + if (((v.opsel_hi >> i) & 1) != 0) { + V h0 = this->f16_operand(inst, *op); + V h = h0; + if (((v.opsel >> i) & 1) != 0) { + V k16 = this->s.m.i32(16); + h = this->s.m.bin(c, Bin::LShr, h0, k16); + } + xx = this->s.op(c, "legacyF16ToF32", Attr::ReadNone, this->s.t.f32, 131, std::vector<V>{h}); + } else { + V o = this->operand(inst, *op); + xx = this->as_float(o); + } + if (((v.neg_hi >> i) & 1) != 0) { + xx = this->unary(6, xx); + } + if (((v.neg >> i) & 1) != 0) { + V z = this->s.m.f32(0x8000'0000u); + xx = this->s.m.bin(c, Bin::Sub, z, xx); + } + xs.push_back(xx); + } + V r = this->fmad(xs[0], xs[1], xs[2]); + if (name == "v_fma_mix_f32") { + float_w(r); + return; + } + if (v.clamp) { + r = this->unary(7, r); + } + // The f16 result goes to one half; the other half stays. + auto reg = vector_reg(v.dst); + if (!reg) fail("a mixed-precision result"); + V old; + if (auto o = inst.read(Reg::V(*reg))) { + old = this->i32_of(*o); + } else { + old = this->s.m.i32(0); + } + V h = this->s.op(c, "legacyF32ToF16", Attr::ReadNone, this->s.t.i32, 130, std::vector<V>{r}); + std::uint32_t keep_bits; + if (name == "v_fma_mixhi_f16") { + V k16 = this->s.m.i32(16); + keep_bits = 0xFFFF; + h = this->s.m.bin(c, Bin::Shl, h, k16); + } else { + keep_bits = 0xFFFF'0000u; + } + V keep = this->s.m.i32(keep_bits); + old = this->s.m.bin(c, Bin::And, old, keep); + V xx = this->s.m.bin(c, Bin::Or, old, h); + this->write(inst, Reg::V(*reg), xx, guard); + return; + } else if (name == "v_cvt_pkrtz_f16_f32") { + V a = f(0); + V bb = f(1); + V lo = this->f16_toward_zero(a); + V hi = this->f16_toward_zero(bb); + V sh = this->s.m.i32(16); + hi = this->s.m.bin(c, Bin::Shl, hi, sh); + V r = this->s.m.bin(c, Bin::Or, lo, hi); + int_w(r); + return; + } else if (name == "v_cvt_f16_f32" && v.opsel == 0) { + // Rounded to nearest even (the MODE default) into the low half. + V a = f(0); + V r = this->s.op(c, "legacyF32ToF16", Attr::ReadNone, this->s.t.i32, 130, std::vector<V>{a}); + auto reg = vector_reg(v.dst); + if (!reg) fail("a 16-bit result outside a VGPR"); + r = this->low_half(inst, *reg, r); + int_w(r); + return; + } else if (name == "v_pack_b32_f16") { + // Two f16 sources (op_sel: their high halves; abs and neg on + // the sign bit) into the low and high half. + std::vector<V> halves; + for (std::size_t k = 0; k < 2; ++k) { + const Operand* op = ok_or(src_at(v, k), "a missing operand"); + V xx = this->f16_operand(inst, *op); + if (((v.opsel >> k) & 1) != 0) { + V k16 = this->s.m.i32(16); + xx = this->s.m.bin(c, Bin::LShr, xx, k16); + } + std::uint32_t mask_bits = ((v.abs >> k) & 1) != 0 ? 0x7FFF : 0xFFFF; + V mask = this->s.m.i32(mask_bits); + xx = this->s.m.bin(c, Bin::And, xx, mask); + if (((v.neg >> k) & 1) != 0) { + V sign = this->s.m.i32(0x8000); + xx = this->s.m.bin(c, Bin::Xor, xx, sign); + } + halves.push_back(xx); + } + V k16 = this->s.m.i32(16); + V hi = this->s.m.bin(c, Bin::Shl, halves[1], k16); + V r = this->s.m.bin(c, Bin::Or, halves[0], hi); + int_w(r); + return; + } else if (name == "v_cvt_f32_f16" && v.opsel == 0) { + V a = s(0); + V r = this->s.op(c, "legacyF16ToF32", Attr::ReadNone, this->s.t.f32, 131, std::vector<V>{a}); + float_w(r); + return; + } else if (name == "v_cndmask_b32") { + std::optional<Value> mask; + if (auto code = scalar_code(src_at(v, 2))) mask = inst.read(Reg::S(*code)); + static constexpr Why UNTRACKED = "a select on an untracked mask"; + std::optional<Bool> tracked; + if (mask) { + + if (auto it = this->x.st->masks.find(*mask); it != this->x.st->masks.end()) tracked = it->second; + } + V cond; + if (tracked) { + cond = this->boolean(*tracked, c); + } else if (this->mask_data == MaskData::Console) { + // A mask the code holds as a number (a constant bit + // pattern: every other lane, every other pair...): + // this lane's bit of it. Exact where host lanes are + // the console's. + // Each host wave taken as a wave of its own has no + // console lane numbers to pick the bits by. + if (this->local) { + fail("a constant lane mask in a half-wave"); + } + Value m = ok_or(mask, UNTRACKED); + V lo; + try { + lo = this->i32_of(m); + } catch (const WhyFail&) { + fail(UNTRACKED); + } + // wave64: the register after it holds lanes 32-63. + std::optional<Value> high; + if (auto code = scalar_code(src_at(v, 2)); code && this->x.native->wave64) { + high = ok_or(inst.read(Reg::S(std::uint8_t(*code + 1))), UNTRACKED); + } + std::optional<V> hi; + if (high) { + try { + hi = this->i32_of(*high); + } catch (const WhyFail&) { + fail(UNTRACKED); + } + } + this->cross_lane(false); + cond = this->lane_bit(c, lo, hi); + } else { + fail(UNTRACKED); + } + if (v.abs != 0 || v.neg != 0) { + V a = f(0); + V bb = f(1); + V r = this->s.m.select(c, cond, bb, a); + float_w(r); + return; + } + V a = s(0); + V bb = s(1); + V r = this->s.m.select(c, cond, bb, a); + int_w(r); + return; + } else if (is({"v_add_co_u32", "v_sub_co_u32", "v_subrev_co_u32", "v_add_co_ci_u32", "v_sub_co_ci_u32", + "v_subrev_co_ci_u32"})) { + // The carry (borrow) out is a lane mask: this lane's bit. + V a = s(0); + V bb = s(1); + if (name.find("subrev") != std::string_view::npos) { + std::swap(a, bb); + } + std::optional<V> cin; + if (name.ends_with("_ci_u32")) { + std::optional<Value> m; + if (auto code = scalar_code(src_at(v, 2))) m = inst.read(Reg::S(*code)); + std::optional<Bool> mb; + if (m) { + + if (auto it = this->x.st->masks.find(*m); it != this->x.st->masks.end()) mb = it->second; + } + Bool bm = ok_or(mb, "a carry-in from an untracked mask"); + cin = this->boolean(bm, c); + } + auto [r, carry] = this->add_sub_carry(c, name.starts_with("v_add"), a, bb, cin); + int_w(r); + if (auto code = scalar_code(v.carry)) { + if (auto w = inst.write(Reg::S(*code))) { + this->lane_bits.insert_or_assign(*w, carry); + } + } + for (const auto& [_, w] : inst.writes) { + this->vals.try_emplace(w, Val::Missing("a lane mask read as data")); + } + return; + } else if (name == "v_permlane16_b32" || name == "v_permlanex16_b32") { + // RDNA2 ISA 12.12: each nibble of {src2, src1} selects a lane + // in this row of 16, or the other row of the same 32-lane half. + // OP_SEL[0:1] are fetch-inactive and bound-control, not half selects. + if (v.abs != 0 || v.neg != 0 || (v.opsel & ~3u) != 0) { + fail("permlane input modifiers"); + } + this->cross_lane(false); + bool fetch_inactive = (v.opsel & 1) != 0; + if (fetch_inactive) { + auto all = all_lane_blocks(*this->x.st); + if (!(all && (*all).at(this->cur_ir))) { + // DXIL cannot read the last VGPR value of a host invocation + // that has left through a lane branch. A guard keeps it here. + fail("a permlane fetch from lanes outside the host branch"); + } + } + V xx = s(0); + V lo = s(1); + V hi = s(2); + V lane = this->lane_index(); + V k7 = this->s.m.i32(7); + V k8 = this->s.m.i32(8); + V k15 = this->s.m.i32(15); + V k16 = this->s.m.i32(16); + V k31 = this->s.m.i32(31); + V k32 = this->s.m.i32(32); + V k4 = this->s.m.i32(4); + V one = this->s.m.i32(1); + V zero = this->s.m.i32(0); + V pos = this->s.m.bin(c, Bin::And, lane, k15); + V lower = this->s.m.cmp(c, pred::IULT, pos, k8); + V packed = this->s.m.select(c, lower, lo, hi); + V shift = this->s.m.bin(c, Bin::And, pos, k7); + shift = this->s.m.bin(c, Bin::Mul, shift, k4); + V pick = this->s.m.bin(c, Bin::LShr, packed, shift); + pick = this->s.m.bin(c, Bin::And, pick, k15); + V not15 = this->s.m.i32(~15u); + V row = this->s.m.bin(c, Bin::And, lane, not15); + if (name == "v_permlanex16_b32") { + row = this->s.m.bin(c, Bin::Xor, row, k16); + } + V src = this->s.m.bin(c, Bin::Or, row, pick); + V r; + if (fetch_inactive) { + r = this->read_lane(xx, src); + } else { + // Ballot the console EXEC guard as well as the host's active + // invocations. Never shuffle from an inactive host lane. + V enabled = guard ? *guard : this->s.m.bool_(true); + Ty i32t = this->s.t.i32; + Ty four = this->s.m.named_struct("dx.types.fouri32", std::vector<Ty>(4, i32t)); + V mask = this->s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, std::vector<V>{enabled}); + V mlo = this->s.m.extract(c, mask, 0); + V mhi = this->s.m.extract(c, mask, 1); + V lower2 = this->s.m.cmp(c, pred::IULT, src, k32); + V word = this->s.m.select(c, lower2, mlo, mhi); + V bit = this->s.m.bin(c, Bin::And, src, k31); + bit = this->s.m.bin(c, Bin::LShr, word, bit); + bit = this->s.m.bin(c, Bin::And, bit, one); + V active = this->s.m.cmp(c, pred::NE, bit, zero); + V safe = this->s.m.select(c, active, src, lane); + V read = this->read_lane(xx, safe); + V fallback; + if ((v.opsel & 2) != 0) { + fallback = zero; + } else { + auto reg = vector_reg(v.dst); + if (!reg) fail("a permlane result outside a VGPR"); + fallback = this->i32_of(ok_or(inst.read(Reg::V(*reg)), "a permlane old value")); + } + r = this->s.m.select(c, active, read, fallback); + } + int_w(r); + return; + } else if (name == "v_readlane_b32") { + V a = s(0); + V lane = s(1); + // A computed lane in a pixel or vertex program is a host lane + // (from a mask or `v_mbcnt`); a constant one is the console's. + if (this->mask_data == MaskData::Host && !(lane.kind == V::Kind::Const)) { + this->s.flags |= flags::WAVE_OPS; + } else { + this->cross_lane(false); + } + if (this->exchange) { + std::uint32_t slot = std::get<0>(*this->exchange); + if (this->local && this->local_any) { + // this host wave's lane of that number (lanes 32..63 are 0..31 here) + V k31 = this->s.m.i32(31); + V here = this->s.m.bin(this->cur, Bin::And, lane, k31); + V r = this->read_lane(a, here); + int_w(r); + return; + } + if (this->local) { + fail("a lane read in a half-wave"); + } + if (std::get<1>(*this->exchange)) { + // a group of 32 or fewer: the lane is in this host wave + V r = this->read_lane(a, lane); + int_w(r); + return; + } + // the lane that holds it may be in the other host wave: it gives it through LDS + if (!this->all_lanes(this->cur_ir)) { + need(this->cur_ir); + fail("a lane read where not every lane runs"); + } + V cl = this->console_lane(); + V eq = this->s.m.cmp(this->cur, pred::EQ, cl, lane); + V k = this->exchange_pair(slot); + auto at = this->begin_guarded(eq); + V lds = this->s.lds(); + V ptr = this->s.m.element(this->cur, lds, k); + this->s.m.store(this->cur, ptr, a); + this->end_guarded(at, {}); + std::size_t c2 = this->cur; + this->group_sync(c2); + V ptr2 = this->s.m.element(c2, lds, k); + V r = this->s.m.load(c2, ptr2); + this->group_sync(c2); + int_w(r); + return; + } + V r = this->read_lane(a, lane); + int_w(r); + return; + } else if (name == "v_writelane_b32") { + // The lane given takes the scalar; the others keep their value. + V a = s(0); + V lane = s(1); + auto reg = vector_reg(v.dst); + if (!reg) fail("a lane write"); + V old; + if (auto o = inst.read(Reg::V(*reg))) { + old = this->i32_of(*o); + } else { + old = this->s.m.i32(0); + } + this->cross_lane(false); + if (this->local && !this->local_any) { + fail("a lane write in a half-wave"); + } + V me = this->console_lane(); + V eq = this->s.m.cmp(c, pred::EQ, me, lane); + V r = this->s.m.select(c, eq, a, old); + int_w(r); + return; + } else if (name == "v_readfirstlane_b32" && !inst.writes.empty() && [&] { + + const auto& reads = this->x.res->waterfall.reads; + return std::find(reads.begin(), reads.end(), inst.writes.front().second) != reads.end(); + }()) { + // A waterfall loop's read of a descriptor dword: the lane's own. + V a = s(0); + int_w(a); + return; + } else if (name == "v_readfirstlane_b32" && [&] { + auto reg = vector_reg(v.src.empty() ? nullptr : &v.src.front()); + if (!reg) return false; + auto xr = inst.read(Reg::V(*reg)); + return xr && this->own_bits.alike.count(*xr) != 0; + }()) { + // The bits a loop over a wave OR has still to visit (`own_bits`): every lane of + // the host wave holds the same, so the first lane's is the lane's own. + V a = s(0); + int_w(a); + return; + } else if (name == "v_readfirstlane_b32") { + V a = s(0); + auto [mine, any] = this->first_lane(a, guard); + // two host waves that exchange: the console's first lane may be in the other + // one, unless every lane holds the same value + bool alike = true; + if (auto reg = vector_reg(v.src.empty() ? nullptr : &v.src.front())) { + auto xr = inst.read(Reg::V(*reg)); + alike = xr && this->uniform.count(*xr) != 0; + } + bool halves = this->exchange && !std::get<1>(*this->exchange) && !this->local; + V r; + if (halves && !alike) { + if (!this->all_lanes(this->cur_ir)) { + // shortcut: `X2W_SHADERCFG_FIRSTLANE_OWN=1` takes the host wave's own + // first lane, exact when the value is the same in every lane of + // the console wave (the ray-tracing builder's scans read a sum of + // scalars this way, inside a loop whose exit is per console wave). + static const bool OWN = [] { + const char* e = std::getenv("X2W_SHADERCFG_FIRSTLANE_OWN"); + return e && std::string_view(e) == "1"; + }(); + if (OWN) { + int_w(mine); + return; + } + need(this->cur_ir); + fail("a first-lane read where not every lane runs"); + } + std::size_t cc = this->cur; + if (!guard && (shader_opt() & opt::FIRST) != 0) { + // Every lane is in EXEC: the console's first lane is + // lane 0, which the lower half of every console wave + // has. No half needs to ask the other whether it has + // a lane (an exchange of the constant 1: two group + // barriers), and the lower half's value is the answer. + auto [lo, _] = this->exchange_halves(cc, mine); + r = lo; + } else { + Ty i32t = this->s.t.i32; + V has = this->s.m.cast(cc, Cast::ZExt, any, i32t); + auto [lo_has, hi_has] = this->exchange_halves(cc, has); + auto [lo, hi] = this->exchange_halves(cc, mine); + V z = this->s.m.i32(0); + V in_lo = this->s.m.cmp(cc, pred::NE, lo_has, z); + V in_hi = this->s.m.cmp(cc, pred::NE, hi_has, z); + // neither half has a lane in EXEC: the console reads lane 0 + V hi2 = this->s.m.select(cc, in_hi, hi, lo); + r = this->s.m.select(cc, in_lo, lo, hi2); + } + } else { + r = mine; + } + int_w(r); + return; + } else { + // `name` is static (the opcode table), NUL-terminated. + V r = this->integer(inst, name.data()); + int_w(r); + return; + } +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/lower_valu16.cpp b/src/x2w_shader/emit/lower_valu16.cpp new file mode 100644 index 0000000000..13bf37d7b5 --- /dev/null +++ b/src/x2w_shader/emit/lower_valu16.cpp @@ -0,0 +1,876 @@ +// 64-bit operand helpers, 16-bit and packed 16-bit VALU operations. +#include <algorithm> + +#include "x2w_shader/emit/lower_impl.h" + +namespace x2w::vs::lower { + +namespace { + +bool bit(std::uint32_t mask, std::size_t k) { return ((mask >> k) & 1u) != 0; } + +bool in_list(std::span<const std::string_view> l, std::string_view name) { + return std::find(l.begin(), l.end(), name) != l.end(); +} + +} // namespace + +V Lower::src64(const Inst& inst, std::size_t k) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + if (bit(v.abs, k) || bit(v.neg, k) || v.sdwa.has_value() || v.dpp.has_value()) { + fail("64-bit operand modifiers"); + } + std::size_t c = this->cur; + Ty i64t = this->s.m.int_(64); + this->s.flags |= flags::INT64; + if (k >= v.src.size()) fail("a missing operand"); + Operand op = v.src[k]; + auto pair = [&](Lower& l, Reg r, Reg r1) -> V { + auto rv = ok_or(inst.read(r), "an unread operand"); + V lo = l.i32_of(rv); + auto rv1 = ok_or(inst.read(r1), "an unread operand"); + V hi = l.i32_of(rv1); + return l.join64(lo, hi); + }; + if (op.kind == Operand::Kind::Vector) { + return pair(*this, Reg::V(op.reg), Reg::V(static_cast<std::uint8_t>(op.reg + 1))); + } + if (op.kind == Operand::Kind::Scalar && op.code != gfx10::NULL_CODE) { + return pair(*this, Reg::S(op.code), Reg::S(static_cast<std::uint8_t>(op.code + 1))); + } + if (op.kind == Operand::Kind::Const && op.code >= 128 && op.code <= 208) { + std::uint32_t x = ok_or(resource::inline_constant(op.code), "a special operand"); + return this->s.m.int_const(i64t, static_cast<std::int64_t>(static_cast<std::int32_t>(x))); + } + // A signed 64-bit operand sign-extends its 32-bit literal, as the hardware does (LLVM's + // AMDGPU operand rules). + if (op.kind == Operand::Kind::Literal && inst.name().ends_with("_i64")) { + return this->s.m.int_const(i64t, static_cast<std::int64_t>(static_cast<std::int32_t>(op.literal))); + } + // Literals (of unsigned and bit operands) and the null register: zero-extended. + V x = this->operand(inst, op); + return this->s.m.cast(c, Cast::ZExt, x, i64t); +} + +// Reads an IEEE-754 binary64 operand as (lo, hi) 32-bit words, applying abs and neg input +// modifiers on operand k. +std::pair<V, V> Lower::f64_pair(const Inst& inst, std::size_t k) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + if (v.sdwa.has_value() || v.dpp.has_value()) { + fail("64-bit operand modifiers"); + } + if (k >= v.src.size()) fail("a missing operand"); + Operand op = v.src[k]; + auto pair = [&](Lower& l, Reg r, Reg r1) -> std::pair<V, V> { + auto rv = ok_or(inst.read(r), "an unread operand"); + V lo = l.i32_of(rv); + auto rv1 = ok_or(inst.read(r1), "an unread operand"); + V hi = l.i32_of(rv1); + return {lo, hi}; + }; + V lo{}; + V hi{}; + if (op.kind == Operand::Kind::Vector) { + std::tie(lo, hi) = pair(*this, Reg::V(op.reg), Reg::V(static_cast<std::uint8_t>(op.reg + 1))); + } else if (op.kind == Operand::Kind::Scalar && op.code != gfx10::NULL_CODE) { + std::tie(lo, hi) = pair(*this, Reg::S(op.code), Reg::S(static_cast<std::uint8_t>(op.code + 1))); + } else if (op.kind == Operand::Kind::Const && op.code == 128) { + lo = this->s.m.i32(0); + hi = this->s.m.i32(0); + } else if (op.kind == Operand::Kind::Const && op.code >= 240 && op.code <= 248) { + static constexpr double INLINE_F64[9] = { + 0.5, -0.5, 1.0, -1.0, 2.0, -2.0, 4.0, -4.0, + 1.0 / 6.28318530717958647692528676655900577, // 1 / std::f64::consts::TAU + }; + std::uint64_t bits = std::bit_cast<std::uint64_t>(INLINE_F64[op.code - 240]); + lo = this->s.m.i32(static_cast<std::uint32_t>(bits)); + hi = this->s.m.i32(static_cast<std::uint32_t>(bits >> 32)); + } else if (op.kind == Operand::Kind::Literal) { + // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand. + lo = this->s.m.i32(0); + hi = this->s.m.i32(op.literal); + } else { + fail("a 64-bit float operand"); + } + std::size_t c = this->cur; + if (bit(v.abs, k)) { + V mask = this->s.m.i32(0x7FFF'FFFF); + hi = this->s.m.bin(c, Bin::And, hi, mask); + } + if (bit(v.neg, k)) { + V sign = this->s.m.i32(0x8000'0000); + hi = this->s.m.bin(c, Bin::Xor, hi, sign); + } + return {lo, hi}; +} + +// Converts IEEE-754 binary64 (lo, hi) to binary32 bits with round-to-nearest-even, without +// requiring host DOUBLES (f64) support. +V Lower::f64_to_f32_bits(V lo, V hi) { + auto& m = this->s.m; + std::size_t c = this->cur; + V k0 = m.i32(0); + V k1 = m.i32(1); + V sign_mask = m.i32(0x8000'0000); + V sign = m.bin(c, Bin::And, hi, sign_mask); + + V k20 = m.i32(20); + V k7ff = m.i32(0x7FF); + V exp64 = m.bin(c, Bin::LShr, hi, k20); + exp64 = m.bin(c, Bin::And, exp64, k7ff); + + V frac_mask = m.i32(0x000F'FFFF); + V frac_hi = m.bin(c, Bin::And, hi, frac_mask); + V frac_any = m.bin(c, Bin::Or, frac_hi, lo); + V frac_nz = m.cmp(c, pred::NE, frac_any, k0); + + V k3 = m.i32(3); + V k29 = m.i32(29); + V m23_hi = m.bin(c, Bin::Shl, frac_hi, k3); + V m23_lo = m.bin(c, Bin::LShr, lo, k29); + V m23 = m.bin(c, Bin::Or, m23_hi, m23_lo); + + V rem_mask = m.i32(0x1FFF'FFFF); + V rem = m.bin(c, Bin::And, lo, rem_mask); + V half_rem = m.i32(0x1000'0000); + V gt_half = m.cmp(c, pred::IUGT, rem, half_rem); + V eq_half = m.cmp(c, pred::EQ, rem, half_rem); + V m23_odd_bit = m.bin(c, Bin::And, m23, k1); + V m23_odd = m.cmp(c, pred::NE, m23_odd_bit, k0); + V tie_up = m.bin(c, Bin::And, eq_half, m23_odd); + V norm_round = m.bin(c, Bin::Or, gt_half, tie_up); + V norm_inc = m.select(c, norm_round, k1, k0); + + // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254]. + V k896 = m.i32(896); + V k23 = m.i32(23); + V exp32 = m.bin(c, Bin::Sub, exp64, k896); + V exp32_sh = m.bin(c, Bin::Shl, exp32, k23); + V norm_body = m.bin(c, Bin::Add, exp32_sh, m23); + norm_body = m.bin(c, Bin::Add, norm_body, norm_inc); + V norm_res = m.bin(c, Bin::Or, sign, norm_body); + + // Subnormal range: exp64 in [874, 896] -> shift in [1, 23]. + V k897 = m.i32(897); + V k32 = m.i32(32); + V k31 = m.i32(31); + V imp = m.i32(0x0080'0000); + V sig24 = m.bin(c, Bin::Or, imp, m23); + V raw_shift = m.bin(c, Bin::Sub, k897, exp64); + // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch. + V lt1 = m.cmp(c, pred::IULT, raw_shift, k1); + V shift = m.select(c, lt1, k1, raw_shift); + V gt23 = m.cmp(c, pred::IUGT, shift, k23); + shift = m.select(c, gt23, k23, shift); + V sub_m = m.bin(c, Bin::LShr, sig24, shift); + V inv_shift = m.bin(c, Bin::Sub, k32, shift); + V lost = m.bin(c, Bin::Shl, sig24, inv_shift); + V round_bit = m.bin(c, Bin::LShr, lost, k31); + V round_on = m.cmp(c, pred::NE, round_bit, k0); + V low31 = m.i32(0x7FFF'FFFF); + V lost_lo = m.bin(c, Bin::And, lost, low31); + V sticky = m.bin(c, Bin::Or, lost_lo, rem); + V sticky_on = m.cmp(c, pred::NE, sticky, k0); + V sub_odd_bit = m.bin(c, Bin::And, sub_m, k1); + V sub_odd = m.cmp(c, pred::NE, sub_odd_bit, k0); + V sub_tie = m.bin(c, Bin::Or, sticky_on, sub_odd); + V sub_round = m.bin(c, Bin::And, round_on, sub_tie); + V sub_inc = m.select(c, sub_round, k1, k0); + V sub_body = m.bin(c, Bin::Add, sub_m, sub_inc); + V sub_res = m.bin(c, Bin::Or, sign, sub_body); + + // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min + // subnormal (1). + V k873 = m.i32(873); + V eq873 = m.cmp(c, pred::EQ, exp64, k873); + V round_min = m.bin(c, Bin::And, eq873, frac_nz); + V min_bit = m.select(c, round_min, k1, k0); + V under_res = m.bin(c, Bin::Or, sign, min_bit); + + // Overflow / Inf / NaN: exp64 >= 1151. + V is_exp_all = m.cmp(c, pred::EQ, exp64, k7ff); + V is_nan = m.bin(c, Bin::And, is_exp_all, frac_nz); + V inf_bits = m.i32(0x7F80'0000); + V qnan_bits = m.i32(0x7FC0'0000); + V nan_body = m.bin(c, Bin::Or, qnan_bits, m23); + V over_body = m.select(c, is_nan, nan_body, inf_bits); + V over_res = m.bin(c, Bin::Or, sign, over_body); + + // Select final result by exponent range. + V k874 = m.i32(874); + V k1151 = m.i32(1151); + V is_under = m.cmp(c, pred::IULT, exp64, k874); + V is_sub = m.cmp(c, pred::IULT, exp64, k897); + V is_over = m.cmp(c, pred::IUGE, exp64, k1151); + V r = m.select(c, is_over, over_res, norm_res); + r = m.select(c, is_sub, sub_res, r); + return m.select(c, is_under, under_res, r); +} + +V Lower::join64(V lo, V hi) { + std::size_t c = this->cur; + Ty ty = this->s.m.int_(64); + lo = this->s.m.cast(c, Cast::ZExt, lo, ty); + hi = this->s.m.cast(c, Cast::ZExt, hi, ty); + V shift = this->s.m.int_const(ty, 32); + hi = this->s.m.bin(c, Bin::Shl, hi, shift); + return this->s.m.bin(c, Bin::Or, lo, hi); +} + +// The bits of the float nearest the double whose dwords are lo and hi, on 32-bit integers: round to nearest +// even, infinities and NaN kept (a NaN stays quiet), a result below the smallest normal float signed zero +// (flushed, as the console's default float mode does). The flush-to-zero form of v_cvt_f32_f64: kept beside +// the IEEE form in use until the console's float mode for this instruction is checked. +V Lower::f64_bits_to_f32_bits(V lo, V hi) { + std::size_t c = this->cur; + auto k = [](Lower& l, std::uint32_t x) { return l.s.m.i32(x); }; + V k20 = k(*this, 20); + V k29 = k(*this, 29); + V k3 = k(*this, 3); + V k23 = k(*this, 23); + V sign_mask = k(*this, 0x8000'0000); + V sign = this->s.m.bin(c, Bin::And, hi, sign_mask); + V e = this->s.m.bin(c, Bin::LShr, hi, k20); + V e_mask = k(*this, 0x7ff); + e = this->s.m.bin(c, Bin::And, e, e_mask); + // The top 23 bits of the 52-bit mantissa, and the 29 below them. + V m_mask = k(*this, 0x000f'ffff); + V mh = this->s.m.bin(c, Bin::And, hi, m_mask); + mh = this->s.m.bin(c, Bin::Shl, mh, k3); + V ml = this->s.m.bin(c, Bin::LShr, lo, k29); + V m = this->s.m.bin(c, Bin::Or, mh, ml); + V rest_mask = k(*this, 0x1fff'ffff); + V rest = this->s.m.bin(c, Bin::And, lo, rest_mask); + // Round to nearest even: up past half, or at half when odd. + V half = k(*this, 0x1000'0000); + V one = k(*this, 1); + V above = this->s.m.cmp(c, pred::IUGT, rest, half); + V at = this->s.m.cmp(c, pred::EQ, rest, half); + V odd = this->s.m.bin(c, Bin::And, m, one); + V zero = k(*this, 0); + odd = this->s.m.cmp(c, pred::NE, odd, zero); + V tie = this->s.m.bin(c, Bin::And, at, odd); + V up = this->s.m.bin(c, Bin::Or, above, tie); + up = this->s.m.select(c, up, one, zero); + // Rebias the exponent (1023 -> 127); a carry out of the mantissa steps the exponent, up to + // infinity. + V bias = k(*this, 1023 - 127); + V e32 = this->s.m.bin(c, Bin::Sub, e, bias); + V ex = this->s.m.bin(c, Bin::Shl, e32, k23); + V normal = this->s.m.bin(c, Bin::Add, ex, m); + normal = this->s.m.bin(c, Bin::Add, normal, up); + normal = this->s.m.bin(c, Bin::Or, normal, sign); + // Exponents out of the float's range (signed, after rebiasing). + V inf = k(*this, 0x7f80'0000); + inf = this->s.m.bin(c, Bin::Or, inf, sign); + V k255 = k(*this, 255); + V big = this->s.m.cmp(c, pred::SGE, e32, k255); + V small = this->s.m.cmp(c, pred::SLE, e32, zero); + V r = this->s.m.select(c, big, inf, normal); + r = this->s.m.select(c, small, sign, r); + // Infinity and NaN (a NaN with any mantissa bit set stays a NaN). + V all = k(*this, 0x7ff); + V special = this->s.m.cmp(c, pred::EQ, e, all); + V any = this->s.m.bin(c, Bin::Or, mh, ml); + any = this->s.m.bin(c, Bin::Or, any, rest); + V nan = this->s.m.cmp(c, pred::NE, any, zero); + V quiet = k(*this, 0x0040'0000); + quiet = this->s.m.select(c, nan, quiet, zero); + V special_bits = this->s.m.bin(c, Bin::Or, inf, quiet); + return this->s.m.select(c, special, special_bits, r); +} + +// The low and high dwords of an i64. +std::pair<V, V> Lower::split64(V x) { + std::size_t c = this->cur; + Ty i64t = this->s.m.int_(64); + V k32 = this->s.m.int_const(i64t, 32); + V lo = this->s.m.cast(c, Cast::Trunc, x, this->s.t.i32); + V hi = this->s.m.bin(c, Bin::LShr, x, k32); + hi = this->s.m.cast(c, Cast::Trunc, hi, this->s.t.i32); + return {lo, hi}; +} + +// Source k of a 16-bit operation in the low 16 bits (the rest 0): op_sel (or an SDWA word select) +// picks the high half; inline float constants are f16 values here. +V Lower::half_src(const Inst& inst, std::size_t k) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + if (k >= v.src.size()) fail("a missing operand"); + Operand op = v.src[k]; + bool high = bit(v.opsel, k); + if (v.sdwa) { + std::uint8_t sel = k < v.sdwa->src_sel.size() ? v.sdwa->src_sel[k] : 6; + switch (sel) { + case 4: break; + case 5: high = true; break; + case 6: break; + default: fail("a byte select on a 16-bit operation"); + } + } + V x{}; + if (this->src0 && k == 0) { + x = *this->src0; + } else { + x = this->f16_operand(inst, op); + } + std::size_t c = this->cur; + if (high) { + V k16 = this->s.m.i32(16); + x = this->s.m.bin(c, Bin::LShr, x, k16); + } + V m = this->s.m.i32(0xFFFF); + return this->s.m.bin(c, Bin::And, x, m); +} + +// An f16 source as an f32 (exact), with its abs/neg modifiers. +V Lower::half_fsrc(const Inst& inst, std::size_t k) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + V h = this->half_src(inst, k); + Ty f32t = this->s.t.f32; + V f = this->s.op(this->cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, std::vector<V>{h}); + if (bit(v.abs, k)) { + f = this->unary(6, f); + } + if (bit(v.neg, k)) { + V z = this->s.m.f32(0x8000'0000); + f = this->s.m.bin(this->cur, Bin::Sub, z, f); + } + return f; +} + +// Writes a 16-bit result (low bits of x) into the destination's low half, or its high half with +// op_sel bit 3 (or an SDWA WORD_1 select); the other half is kept (GFX10). +void Lower::write_half(const Inst& inst, V x, std::optional<V> guard) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + if (!v.dst || v.dst->kind != Operand::Kind::Vector) { + fail("a 16-bit result outside a VGPR"); + } + std::uint8_t reg = v.dst->reg; + bool high = bit(v.opsel, 3); + // SDWA: the word written, the other one kept (preserve) or zero (pad; a sign extension above + // the high word adds nothing). + bool keep = true; + if (v.sdwa) { + std::uint8_t sel = v.sdwa->dst_sel; + std::uint8_t unused = v.sdwa->dst_unused; + if (sel == 4 && unused == 2) { + } else if (sel == 5 && unused == 2) { + high = true; + } else if (sel == 4 || sel == 6) { + keep = false; + } else if (sel == 5) { + high = true; + keep = false; + } else { + fail("an SDWA destination of a 16-bit operation"); + } + } + std::size_t c = this->cur; + // Convert a register whenever it is read, even if the result is discarded. Use zero if conversion fails. + std::optional<V> read_old; + if (auto o = inst.read(Reg::V(reg))) { + read_old = ok([&] { return this->i32_of(*o); }); + } + V old{}; + if (read_old && keep) { + old = *read_old; + } else { + old = this->s.m.i32(0); + } + V k16 = this->s.m.i32(16); + V low = this->s.m.i32(0xFFFF); + x = this->s.m.bin(c, Bin::And, x, low); + V r{}; + if (high) { + V o = this->s.m.bin(c, Bin::And, old, low); + V xs = this->s.m.bin(c, Bin::Shl, x, k16); + r = this->s.m.bin(c, Bin::Or, o, xs); + } else { + V keepk = this->s.m.i32(0xFFFF'0000); + V o = this->s.m.bin(c, Bin::And, old, keepk); + r = this->s.m.bin(c, Bin::Or, o, x); + } + this->write_placed(inst, Reg::V(reg), r, guard); +} + +// 16-bit operations, computed in f32 or i32: f16 sums, differences and products are exact there +// and round once to f16 (f32 has the 2 x 11 + 2 bits that make double rounding harmless); false +// (None) if name is none. +bool Lower::valu16(const Inst& inst, std::string_view name, std::optional<V> guard) { + static constexpr std::string_view FLOAT2[] = { + "v_add_f16", "v_sub_f16", "v_subrev_f16", "v_mul_f16", "v_max_f16", "v_min_f16", + }; + static constexpr std::string_view FLOAT3[] = { + "v_fma_f16", "v_mad_f16", "v_fmac_f16", "v_mac_f16", "v_max3_f16", "v_min3_f16", "v_med3_f16", + }; + static constexpr std::string_view FLOAT1[] = { + "v_rcp_f16", "v_sqrt_f16", "v_rsq_f16", "v_log_f16", "v_exp_f16", + "v_fract_f16", "v_trunc_f16", "v_floor_f16", "v_ceil_f16", "v_rndne_f16", + "v_sin_f16", "v_cos_f16", "v_cvt_f16_u16", "v_cvt_f16_i16", + }; + static constexpr std::string_view INT[] = { + "v_add_nc_u16", "v_sub_nc_u16", "v_subrev_nc_u16", "v_mul_lo_u16", + "v_lshlrev_b16", "v_lshrrev_b16", "v_ashrrev_i16", "v_max_u16", + "v_max_i16", "v_min_u16", "v_min_i16", "v_cvt_u16_f16", + "v_cvt_i16_f16", "v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16", + }; + bool any = in_list(FLOAT1, name) || in_list(FLOAT2, name) || in_list(FLOAT3, name) || + in_list(INT, name); + if (!any && !(name == "v_cvt_f16_f32" || name == "v_cvt_f32_f16")) { + return false; + } + this->valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3); + return true; +} + +void Lower::valu16_op(const Inst& inst, std::string_view name, std::optional<V> guard, + std::span<const std::string_view> float1, std::span<const std::string_view> float2, + std::span<const std::string_view> float3) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + std::size_t c = this->cur; + Ty i32t = this->s.t.i32; + Ty f32t = this->s.t.f32; + if (name == "v_cvt_f32_f16") { + V f = this->half_fsrc(inst, 0); + this->write_f(inst, f, guard); + return; + } + auto float_result = [&](Lower& l, V f) { + if (v.omod != 0) { + static constexpr float FACTORS[4] = {1.0f, 2.0f, 4.0f, 0.5f}; + float factor = FACTORS[v.omod]; + V k = l.s.m.f32(f32_bits(factor)); + f = l.s.m.bin(l.cur, Bin::Mul, f, k); + } + if (v.clamp) { + f = l.unary(7, f); + } + // The console rounds to nearest; the host's conversion may round toward zero (NVIDIA's + // does), one step of the last place lower where the two differ. + // shortcut: the host's conversion unless `X2W_SHADERCFG_F16_NEAREST=1` (f16_nearest_on), which + // costs a dozen instructions per result. + V h{}; + if (f16_nearest_on()) { + h = l.f16_nearest(f); + } else { + h = l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, std::vector<V>{f}); + } + l.write_half(inst, h, guard); + }; + if (name == "v_cvt_f16_f32") { + V f = this->fsrc(inst, 0); + float_result(*this, f); + return; + } + if (in_list(float2, name)) { + V a = this->half_fsrc(inst, 0); + V b = this->half_fsrc(inst, 1); + V r{}; + if (name == "v_add_f16") { + r = this->s.m.bin(c, Bin::Add, a, b); + } else if (name == "v_sub_f16") { + r = this->s.m.bin(c, Bin::Sub, a, b); + } else if (name == "v_subrev_f16") { + r = this->s.m.bin(c, Bin::Sub, b, a); + } else if (name == "v_mul_f16") { + r = this->s.m.bin(c, Bin::Mul, a, b); + } else if (name == "v_max_f16") { + r = this->max_min(true, a, b); + } else { + r = this->max_min(false, a, b); + } + float_result(*this, r); + return; + } + if (in_list(float3, name)) { + V a = this->half_fsrc(inst, 0); + V b = this->half_fsrc(inst, 1); + V acc{}; + if (name == "v_fmac_f16" || name == "v_mac_f16") { + // The accumulator is the destination's half that is written. + if (!v.dst || v.dst->kind != Operand::Kind::Vector) { + fail("an accumulator"); + } + std::uint8_t reg = v.dst->reg; + Value rv = ok_or(inst.read(Reg::V(reg)), "an accumulator"); + V x = this->i32_of(rv); + if (bit(v.opsel, 3)) { + V k16 = this->s.m.i32(16); + x = this->s.m.bin(c, Bin::LShr, x, k16); + } + V m = this->s.m.i32(0xFFFF); + x = this->s.m.bin(c, Bin::And, x, m); + acc = this->s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, std::vector<V>{x}); + } else { + acc = this->half_fsrc(inst, 2); + } + V r{}; + if (name == "v_fma_f16" || name == "v_fmac_f16" || name == "v_mad_f16" || name == "v_mac_f16") { + // shortcut: fused f16 multiply-adds as FMad in f32 (the product is exact; the sum + // rounds twice). + r = this->fmad(a, b, acc); + } else if (name == "v_max3_f16") { + V t = this->max_min(true, a, b); + r = this->max_min(true, t, acc); + } else if (name == "v_min3_f16") { + V t = this->max_min(false, a, b); + r = this->max_min(false, t, acc); + } else { + r = this->med3(a, b, acc); + } + float_result(*this, r); + return; + } + if (in_list(float1, name)) { + V r{}; + if (name == "v_cvt_f16_u16" || name == "v_cvt_f16_i16") { + V x = this->half_src(inst, 0); + Cast op{}; + if (name == "v_cvt_f16_i16") { + V k16 = this->s.m.i32(16); + V t = this->s.m.bin(c, Bin::Shl, x, k16); + x = this->s.m.bin(c, Bin::AShr, t, k16); + op = Cast::SiToFp; + } else { + op = Cast::UiToFp; + } + r = this->s.m.cast(c, op, x, f32t); + } else if (name == "v_rcp_f16") { + V a = this->half_fsrc(inst, 0); + V one = this->s.m.f32(f32_bits(1.0f)); + r = this->s.m.bin(c, Bin::SDiv, one, a); + } else { + V a = this->half_fsrc(inst, 0); + std::uint32_t op = name == "v_sqrt_f16" ? 24 + : name == "v_rsq_f16" ? 25 + : name == "v_log_f16" ? 23 + : name == "v_exp_f16" ? 21 + : name == "v_fract_f16" ? 22 + : name == "v_trunc_f16" ? 29 + : name == "v_floor_f16" ? 27 + : name == "v_ceil_f16" ? 28 + : name == "v_rndne_f16" ? 26 + : name == "v_sin_f16" ? 13 + : 12; + if (op == 12 || op == 13) { + r = this->trig_turns(a, op == 12); + } else if (op == 22) { + // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11). + r = this->fract(a, 1.0f - 1.0f / 4096.0f, 1.0f - 1.0f / 2048.0f); + } else { + r = this->unary(op, a); + } + } + float_result(*this, r); + return; + } + if (name == "v_cvt_u16_f16" || name == "v_cvt_i16_f16") { + if (v.clamp || v.omod != 0) { + fail("modifiers on a 16-bit integer operation"); + } + // Toward zero, saturating at the 16-bit range (infinities included); NaN gives 0. Clamped in f32 first, + // where every f16 is exact, so the conversion never leaves i32's range. half_fsrc applies the source + // modifiers. + V a = this->half_fsrc(inst, 0); + float lof = 0.0f; + float hif = 0.0f; + if (name == "v_cvt_u16_f16") { + lof = 0.0f; + hif = 65535.0f; + } else { + lof = -32768.0f; + hif = 32767.0f; + } + V lo = this->s.m.f32(f32_bits(lof)); + V hi = this->s.m.f32(f32_bits(hif)); + V t = this->binary(35, a, lo); + t = this->binary(36, t, hi); + V r = this->s.m.cast(c, Cast::FpToSi, t, i32t); + V nan = this->s.m.cmp(c, pred::UNO, a, a); + V z = this->s.m.i32(0); + r = this->s.m.select(c, nan, z, r); + this->write_half(inst, r, guard); + return; + } + if (name == "v_cvt_norm_i16_f16" || name == "v_cvt_norm_u16_f16") { + if (v.clamp || v.omod != 0) { + fail("modifiers on a 16-bit integer operation"); + } + V r = this->cvt_norm16(inst, name == "v_cvt_norm_i16_f16"); + this->write_half(inst, r, guard); + return; + } + // 16-bit integers: computed on the low halves, the low 16 bits kept. + if (v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0) { + fail("modifiers on a 16-bit integer operation"); + } + V r{}; + { + V a = this->half_src(inst, 0); + V b = this->half_src(inst, 1); + V k16 = this->s.m.i32(16); + auto sext = [&](Lower& l, V x) { + V t = l.s.m.bin(c, Bin::Shl, x, k16); + return l.s.m.bin(c, Bin::AShr, t, k16); + }; + if (name.ends_with("_i16")) { + a = sext(*this, a); + b = sext(*this, b); + } + V k15 = this->s.m.i32(15); + if (name == "v_add_nc_u16") { + r = this->s.m.bin(c, Bin::Add, a, b); + } else if (name == "v_sub_nc_u16") { + r = this->s.m.bin(c, Bin::Sub, a, b); + } else if (name == "v_subrev_nc_u16") { + r = this->s.m.bin(c, Bin::Sub, b, a); + } else if (name == "v_mul_lo_u16") { + r = this->s.m.bin(c, Bin::Mul, a, b); + } else if (name == "v_lshlrev_b16" || name == "v_lshrrev_b16" || name == "v_ashrrev_i16") { + // src0 is the shift (4 bits), src1 the value. + V sh = this->s.m.bin(c, Bin::And, a, k15); + V x = name == "v_ashrrev_i16" ? sext(*this, b) : b; + Bin op = name == "v_lshlrev_b16" ? Bin::Shl : name == "v_lshrrev_b16" ? Bin::LShr : Bin::AShr; + r = this->s.m.bin(c, op, x, sh); + } else { + std::uint8_t p = name == "v_max_u16" ? pred::IUGT + : name == "v_min_u16" ? pred::IULT + : name == "v_max_i16" ? pred::SGT + : pred::SLT; + V t = this->s.m.cmp(c, p, a, b); + r = this->s.m.select(c, t, a, b); + } + } + this->write_half(inst, r, guard); +} + +// v_cvt_norm_i16_f16 / v_cvt_norm_u16_f16: the f16 source (with its abs/neg modifiers) clamped to +// [-1, 1] or [0, 1], times 32767 or 65535, rounded to nearest even once from the exact product; NaN +// gives 0. Worked on the f16's bits in integers, because in f32 the product (up to 26 significant +// bits) would round before the rounding to an integer. +V Lower::cvt_norm16(const Inst& inst, bool signed_) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + std::size_t c = this->cur; + auto k = [](Lower& l, std::uint32_t x) { return l.s.m.i32(x); }; + V h = this->half_src(inst, 0); + if ((v.abs & 1) != 0) { + V m = k(*this, 0x7FFF); + h = this->s.m.bin(c, Bin::And, h, m); + } + if ((v.neg & 1) != 0) { + V m = k(*this, 0x8000); + h = this->s.m.bin(c, Bin::Xor, h, m); + } + std::uint32_t scale = signed_ ? 0x7FFF : 0xFFFF; + V k0 = k(*this, 0); + V k1 = k(*this, 1); + V k10 = k(*this, 10); + V mag_mask = k(*this, 0x7FFF); + V mag = this->s.m.bin(c, Bin::And, h, mag_mask); + V k15 = k(*this, 15); + V neg = this->s.m.bin(c, Bin::LShr, h, k15); + neg = this->s.m.cmp(c, pred::NE, neg, k0); + // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24. + V exp = this->s.m.bin(c, Bin::LShr, mag, k10); + V man_mask = k(*this, 0x3FF); + V man = this->s.m.bin(c, Bin::And, mag, man_mask); + V implicit = k(*this, 0x400); + V normal = this->s.m.bin(c, Bin::Or, man, implicit); + V sub = this->s.m.cmp(c, pred::EQ, exp, k0); + V m = this->s.m.select(c, sub, man, normal); + V k25 = k(*this, 25); + V s_norm = this->s.m.bin(c, Bin::Sub, k25, exp); + V k24 = k(*this, 24); + V sh = this->s.m.select(c, sub, k24, s_norm); + V ks = k(*this, scale); + V p = this->s.m.bin(c, Bin::Mul, m, ks); + V q = this->s.m.bin(c, Bin::LShr, p, sh); + V one_s = this->s.m.bin(c, Bin::Shl, k1, sh); + V low_mask = this->s.m.bin(c, Bin::Sub, one_s, k1); + V rem = this->s.m.bin(c, Bin::And, p, low_mask); + V half = this->s.m.bin(c, Bin::LShr, one_s, k1); + V above = this->s.m.cmp(c, pred::IUGT, rem, half); + V tie = this->s.m.cmp(c, pred::EQ, rem, half); + V odd = this->s.m.bin(c, Bin::And, q, k1); + odd = this->s.m.cmp(c, pred::NE, odd, k0); + V tie_up = this->s.m.bin(c, Bin::And, tie, odd); + V up = this->s.m.bin(c, Bin::Or, above, tie_up); + V r = this->s.m.select(c, up, k1, k0); + r = this->s.m.bin(c, Bin::Add, q, r); + // |x| >= 1 (and infinity) saturates; NaN gives 0. + V one_h = k(*this, 0x3C00); + V big = this->s.m.cmp(c, pred::IUGE, mag, one_h); + r = this->s.m.select(c, big, ks, r); + V inf = k(*this, 0x7C00); + V nan = this->s.m.cmp(c, pred::IUGT, mag, inf); + r = this->s.m.select(c, nan, k0, r); + if (signed_) { + V n = this->s.m.bin(c, Bin::Sub, k0, r); + r = this->s.m.select(c, neg, n, r); + } else { + r = this->s.m.select(c, neg, k0, r); + } + V m16 = k(*this, 0xFFFF); + return this->s.m.bin(c, Bin::And, r, m16); +} + +// Half `high` of source k of a packed (VOP3P) operation, in the low 16 bits: op_sel picks the half +// the low result reads, op_sel_hi the half the high result reads. Packed integer instructions see +// the f32 bits of an inline float constant. +V Lower::packed_src(const Inst& inst, std::size_t k, bool high, bool float_) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + if (k >= v.src.size()) fail("a missing operand"); + Operand op = v.src[k]; + bool sel = bit(high ? v.opsel_hi : v.opsel, k); + V x{}; + if (float_) { + x = this->f16_operand(inst, op); + } else { + x = this->operand(inst, op); + } + std::size_t c = this->cur; + if (sel) { + V k16 = this->s.m.i32(16); + x = this->s.m.bin(c, Bin::LShr, x, k16); + } + V m = this->s.m.i32(0xFFFF); + return this->s.m.bin(c, Bin::And, x, m); +} + +// Half `high` of source k of v_pk_fmac_f16, in the low 16 bits: a VOP2 operation (no op_sel) whose +// third source is its destination. +V Lower::fmac_half(const Inst& inst, std::size_t k, bool high) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + std::optional<Operand> opo; + if (k == 2) { + opo = v.dst; + } else if (k < v.src.size()) { + opo = v.src[k]; + } + Operand op = ok_or(opo, "a missing operand"); + if (op.kind == Operand::Kind::Const || op.kind == Operand::Kind::Literal) { + // shortcut: no constant operand seen; its high half is not known. + fail("a constant operand of v_pk_fmac_f16"); + } + V x = this->operand(inst, op); + std::size_t c = this->cur; + if (high) { + V k16 = this->s.m.i32(16); + x = this->s.m.bin(c, Bin::LShr, x, k16); + } + V m = this->s.m.i32(0xFFFF); + return this->s.m.bin(c, Bin::And, x, m); +} + +// Packed 16-bit operations (v_pk_*): each half computed as the 16-bit operation does, f16 through +// f32 as in valu16. +void Lower::packed16(const Inst& inst, std::string_view op, std::optional<V> guard) { + const auto& v = std::get<gfx10::Valu>(inst.fields); + bool float_ = op.ends_with("_f16"); + std::size_t n = 0; + if (op == "fma_f16" || op == "fmac_f16" || op == "mad_u16" || op == "mad_i16") { + n = 3; + } else if (op == "add_f16" || op == "mul_f16" || op == "min_f16" || op == "max_f16" || + op == "add_u16" || op == "sub_u16" || op == "add_i16" || op == "sub_i16" || + op == "mul_lo_u16" || op == "lshlrev_b16" || op == "lshrrev_b16" || + op == "ashrrev_i16" || op == "max_u16" || op == "min_u16" || op == "max_i16" || + op == "min_i16") { + n = 2; + } else { + fail("a packed 16-bit operation"); + } + if (v.omod != 0 || (!float_ && (v.clamp || v.neg != 0 || v.neg_hi != 0))) { + fail("modifiers on a packed integer operation"); + } + std::size_t c = this->cur; + Ty i32t = this->s.t.i32; + Ty f32t = this->s.t.f32; + std::vector<V> halves; + for (bool high : {false, true}) { + std::vector<V> xs; + for (std::size_t k = 0; k < n; ++k) { + V h{}; + if (op == "fmac_f16") { + h = this->fmac_half(inst, k, high); + } else { + h = this->packed_src(inst, k, high, float_); + } + if (float_) { + V f = this->s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, std::vector<V>{h}); + std::uint8_t neg = high ? v.neg_hi : v.neg; + if (bit(neg, k)) { + V z = this->s.m.f32(0x8000'0000); + f = this->s.m.bin(c, Bin::Sub, z, f); + } + xs.push_back(f); + } else { + xs.push_back(h); + } + } + V r{}; + if (float_) { + V f{}; + if (op == "add_f16") { + f = this->s.m.bin(c, Bin::Add, xs[0], xs[1]); + } else if (op == "mul_f16") { + f = this->s.m.bin(c, Bin::Mul, xs[0], xs[1]); + } else if (op == "min_f16") { + f = this->max_min(false, xs[0], xs[1]); + } else if (op == "max_f16") { + f = this->max_min(true, xs[0], xs[1]); + } else { + // shortcut: FMad in f32, as v_fma_f16. + f = this->fmad(xs[0], xs[1], xs[2]); + } + if (v.clamp) { + f = this->unary(7, f); + } + r = this->s.op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, std::vector<V>{f}); + } else { + V k16 = this->s.m.i32(16); + auto sext = [&](Lower& l, V x) { + V t = l.s.m.bin(c, Bin::Shl, x, k16); + return l.s.m.bin(c, Bin::AShr, t, k16); + }; + if (op.ends_with("_i16")) { + for (auto& x : xs) { + x = sext(*this, x); + } + } + V k15 = this->s.m.i32(15); + if (op == "add_u16" || op == "add_i16") { + r = this->s.m.bin(c, Bin::Add, xs[0], xs[1]); + } else if (op == "sub_u16" || op == "sub_i16") { + r = this->s.m.bin(c, Bin::Sub, xs[0], xs[1]); + } else if (op == "mul_lo_u16") { + r = this->s.m.bin(c, Bin::Mul, xs[0], xs[1]); + } else if (op == "mad_u16" || op == "mad_i16") { + V m = this->s.m.bin(c, Bin::Mul, xs[0], xs[1]); + r = this->s.m.bin(c, Bin::Add, m, xs[2]); + } else if (op == "lshlrev_b16" || op == "lshrrev_b16" || op == "ashrrev_i16") { + V sh = this->s.m.bin(c, Bin::And, xs[0], k15); + Bin o = op == "lshlrev_b16" ? Bin::Shl : op == "lshrrev_b16" ? Bin::LShr : Bin::AShr; + V x = op == "ashrrev_i16" ? sext(*this, xs[1]) : xs[1]; + r = this->s.m.bin(c, o, x, sh); + } else { + std::uint8_t p = op == "max_u16" ? pred::IUGT + : op == "min_u16" ? pred::IULT + : op == "max_i16" ? pred::SGT + : pred::SLT; + V t = this->s.m.cmp(c, p, xs[0], xs[1]); + r = this->s.m.select(c, t, xs[0], xs[1]); + } + } + V m = this->s.m.i32(0xFFFF); + halves.push_back(this->s.m.bin(c, Bin::And, r, m)); + } + V k16 = this->s.m.i32(16); + V hi = this->s.m.bin(c, Bin::Shl, halves[1], k16); + V r = this->s.m.bin(c, Bin::Or, halves[0], hi); + if (!v.dst || v.dst->kind != Operand::Kind::Vector) { + fail("a packed result outside a VGPR"); + } + this->write(inst, Reg::V(v.dst->reg), r, guard); +} + +} // namespace x2w::vs::lower diff --git a/src/x2w_shader/emit/mod.cpp b/src/x2w_shader/emit/mod.cpp new file mode 100644 index 0000000000..0de4a93c72 --- /dev/null +++ b/src/x2w_shader/emit/mod.cpp @@ -0,0 +1,484 @@ +// the entry points (translate, emit), the wave64 retries, emit_program and the translation fingerprint. The +// settings are in settings.cpp, the signature readers in mod_signature.cpp. + +#include <algorithm> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <set> +#include <string> +#include <string_view> + +#include "x2w_shader/dxbc.h" +#include "x2w_shader/emit/emit.h" +#include "x2w_shader/emit/lower.h" +#include "x2w_shader/emit/opt.h" +#include "x2w_shader/emit/threading.h" +#include "x2w_shader/io.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/native.h" +#include "x2w_shader/resource.h" +#include "x2w_shader/spill.h" +#include "x2w_shader/structure.h" + +#ifdef X2W_VS_FINGERPRINT_HEADER +#include "x2w_vs_fingerprint.h" // generated at build time (cmake/x_translate.cmake) +#endif +#ifndef X2W_VS_SOURCE_HASH +#define X2W_VS_SOURCE_HASH "unknown" +#endif +#ifndef X2W_VS_SWITCHES +#define X2W_VS_SWITCHES "" +#endif + +namespace x2w::vs { + +namespace { + +using dxbc::Container; +using dxbc::FourCC; +using native::HwStage; +using native::NativeProgram; + +std::optional<std::string_view> env(const char* name) { + const char* v = std::getenv(name); + if (!v) return std::nullopt; + return std::string_view(v); +} + +bool is_unsupported(const ShaderError& e) { return e.kind == ShaderError::Kind::Unsupported; } +bool what_is(const ShaderError& e, const char* what) { + return is_unsupported(e) && std::strcmp(e.reason, what) == 0; +} + +struct Emitted { + std::optional<std::pair<HostShader, std::optional<std::uint32_t>>> ok; + std::optional<ShaderError> err; + bool is_ok() const { return ok.has_value(); } + // Ok with a wave size other than 64. + bool done() const { return ok && ok->second != std::optional<std::uint32_t>(64); } +}; + +template <class F> +Emitted capture(F&& f) { + Emitted r; + try { + r.ok = f(); + } catch (const ShaderError& e) { + r.err = e; + } + return r; +} + +HostShader unwrap(Emitted r) { + if (r.err) throw *r.err; + return std::move(r.ok->first); +} + +// The translated program, and the wave size it requires of the host. +std::pair<HostShader, std::optional<std::uint32_t>> emit_program(const Container& c, const NativeProgram& native, + const ir::Program& p, const structure::Structured& st, + const io::Io& io, const resource::Resources& res) { + auto sig = [&](FourCC fourcc) -> std::vector<container::SigElement> { + if (const dxbc::Part* part = c.part(fourcc)) return signature(part->data); + return {}; + }; + const bool pixel = native.stage == HwStage::Ps; + std::vector<container::SigElement> inputs = sig(FourCC::ISG1); + std::vector<container::SigElement> outputs = sig(FourCC::OSG1); + // Interpolation as DXC declares it by default; pixel inputs that are read get the mode their + // barycentrics say. + std::vector<container::SigElement>& interpolated = pixel ? inputs : outputs; + for (container::SigElement& e : interpolated) { + if (e.kind == 3) + e.interp = 4; + else if (e.kind == 13) + // Constant, as DXC declares it (the AMD compiler crashed on a front face without a + // mode). + e.interp = 1; + else if (e.kind == 28) + // Until a read says which mode (lower). + e.interp = 2; + else if ((e.kind == 0 || e.kind == 6 || e.kind == 7) && e.comp == 9) + e.interp = 2; + else if (e.kind == 0) + e.interp = 1; + else + e.interp = 0; + } + if (native.stage == HwStage::Vs) { + if (const dxbc::Part* psv = c.part(FourCC::PSV0)) vertex_output_interpolation(psv->data, outputs); + } + // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL wants the position + // centroid (or per sample), as DXC declares it then. + if (pixel && std::any_of(outputs.begin(), outputs.end(), + [](const container::SigElement& e) { return e.kind == 18 || e.kind == 19; })) { + for (container::SigElement& e : inputs) + if (e.kind == 3) e.interp = 5; + } + // Per-primitive outputs are constant. The console never exports a primitive id or cull flag a + // mesh shader writes (it culls with the primitive export), so those rows are left out. + std::vector<container::SigElement> prims = sig(FourCC::PSG1); + prims.erase(std::remove_if(prims.begin(), prims.end(), + [](const container::SigElement& e) { return e.kind == 10 || e.kind == 30; }), + prims.end()); + for (container::SigElement& e : prims) e.interp = 1; + // A mesh group's id arrives multiplied by max(threads, vertices, primitives) (the code divides + // by that); the thread count is in PSV0 from runtime info version 2 on. + // shortcut: older containers fall back to the group's lane count, right when the HLSL group + // fills its waves (the title's do). + std::uint32_t mesh_stride = 0; + if (const auto* ms = std::get_if<native::MeshIo>(&native.io)) { + std::optional<std::uint32_t> threads; + if (const dxbc::Part* psv = c.part(FourCC::PSV0)) { + auto n = try_shader([&] { return dxbc::u32_at(psv->data, 0); }); + if (n && *n >= 48) threads = try_shader([&] { return dxbc::u32_at(psv->data, 4 + 36); }); + } + mesh_stride = threads ? std::max({*threads, ms->max_vertices, ms->max_primitives}) : ms->threads; + } + lower::Parts parts; + parts.native = &native; + parts.p = &p; + parts.st = &st; + parts.io = &io; + parts.res = &res; + parts.inputs = std::move(inputs); + parts.outputs = std::move(outputs); + parts.prims = std::move(prims); + parts.mesh_stride = mesh_stride; + lower::Lowered l = lower::lower(parts); + const std::optional<std::uint32_t> wave_size = l.wave_size; + HostShader shader; + shader.stage = native.stage; + shader.dxil = std::move(l.dxil); + shader.user_data = std::move(l.user_data); + for (std::size_t n = 0; n < l.samplers.size(); ++n) { + StaticSampler s = StaticSampler::from_words(l.samplers[n]); + if (((l.cmp_samplers >> n) & 1) != 0) s.filter |= 0x80; + shader.static_samplers.push_back(s); + } + shader.samplers = std::move(l.samplers); + shader.root_cbvs = std::move(l.root_cbvs); + shader.root_srvs = std::move(l.root_srvs); + shader.root_uavs = std::move(l.root_uavs); + shader.root_indexed_views = res.root_indexed_views; + return {std::move(shader), wave_size}; +} + +// p (a console wave64 compute program on a host of 32-lane waves) with the per-lane branches +// around its cross-lane code taken wave-wide (structure::structure_wide): the lowering names the +// blocks where the two host waves must meet and could not (lower::take_needs), the branches whose +// regions hold them are widened, and so on until it translates or a branch cannot be widened. +// Only where a thread group is one console wave. +Emitted widen(const Container& c, const NativeProgram& native, const ir::Program& p, bool why) { + const ShaderError NOT = + ShaderError::unsupported(0, "wave-wide branches in a thread group of several console waves"); + const auto* cs = std::get_if<native::ComputeIo>(&native.io); + if (!cs) return Emitted{std::nullopt, NOT}; + // (a program whose waves are the host's meets no one: no barrier, any group) + const bool own = !(native.wave64 && lower::host_max_wave() == 32); + if (!own && cs->threads[0] * cs->threads[1] * cs->threads[2] != 64) { + if (why) + std::fprintf(stderr, "WAVE64-WIDE not tried: thread groups of [%u, %u, %u]\n", cs->threads[0], cs->threads[1], + cs->threads[2]); + return Emitted{std::nullopt, NOT}; + } + std::set<std::size_t> wide; + for (;;) { + Emitted r; + std::vector<std::size_t> needs; + std::optional<structure::Structured> st; + try { + st = structure::structure_wide(p, wide); + const io::Io io = io::raise(p, native); + const resource::Resources res = resource::track(p, native.layout, native.stage, &*st); + lower::take_needs(); + r = capture([&] { return emit_program(c, native, p, *st, io, res); }); + needs = lower::take_needs(); + } catch (const ShaderError& e) { + return Emitted{std::nullopt, e}; + } + // (or translated for 64-lane waves still: shared memory read and written where not every + // lane runs, whose blocks the lowering names too) + const bool stuck = + (r.err && is_unsupported(*r.err) && + (lower::needs_every_lane(r.err->reason) || (std::strcmp(r.err->reason, lower::LANE_MASK) == 0 && !needs.empty()))) || + (r.ok && r.ok->second == std::optional<std::uint32_t>(64) && !needs.empty()); + if (!stuck) { + if (why) std::fprintf(stderr, "WAVE64-WIDE %zu branches taken wave-wide\n", wide.size()); + return r; + } + std::vector<std::size_t> more; + for (std::size_t b : lower::branches_around(*st, needs).value_or(std::vector<std::size_t>{})) + if (!wide.count(b)) more.push_back(b); + if (more.empty()) { + if (why) + std::fprintf(stderr, "WAVE64-WIDE stopped with %zu branches wave-wide: a branch around it cannot be\n", + wide.size()); + return r; + } + wide.insert(more.begin(), more.end()); + } +} + +void report(bool why, const std::string& what, const Emitted& r) { + if (!why) return; + if (r.ok) { + if (r.ok->second) + std::fprintf(stderr, "WAVE64-RETRY %s: wave Some(%u)\n", what.c_str(), *r.ok->second); + else + std::fprintf(stderr, "WAVE64-RETRY %s: wave None\n", what.c_str()); + } else { + std::fprintf(stderr, "WAVE64-RETRY %s: %s\n", what.c_str(), r.err->to_string().c_str()); + } +} + +// The program in another form, with its earlier stages run again. +struct Form { + ir::Program p; + structure::Structured st; + io::Io io; + resource::Resources res; +}; + +std::optional<Form> form(const NativeProgram& native, std::optional<ir::Program> p) { + if (!p) return std::nullopt; + auto st = try_shader([&] { return structure::structure(*p); }); + if (!st) return std::nullopt; + auto io = try_shader([&] { return io::raise(*p, native); }); + if (!io) return std::nullopt; + auto res = try_shader([&] { return resource::track(*p, native.layout, native.stage, &*st); }); + if (!res) return std::nullopt; + return Form{std::move(*p), std::move(*st), std::move(*io), std::move(*res)}; +} + +HostShader translate_plain(std::span<const std::uint8_t> container) { + const Container c = Container::parse(container); + const dxbc::Part* dxil = c.part(FourCC::DXIL); + if (!dxil) dxil = c.part(FourCC::ACCC); + if (!dxil) throw ShaderError::malformed("no DXIL part"); + std::vector<NativeProgram> programs = native::native_programs(dxil->data); + auto it = std::find_if(programs.begin(), programs.end(), [](const NativeProgram& p) { + return p.stage == HwStage::Vs || p.stage == HwStage::Ps || p.stage == HwStage::Cs || p.stage == HwStage::Ms; + }); + if (it == programs.end()) + throw ShaderError::unsupported(0, "a container without a vertex, pixel, compute or mesh program"); + const NativeProgram& native = *it; + const ir::Program p = spill::build(native); + // Structurisation first: tracing per-lane descriptors needs it (its failure is reported after + // the earlier stages'). + std::optional<structure::Structured> st; + std::optional<ShaderError> st_err; + try { + st = structure::structure(p); + } catch (const ShaderError& e) { + st_err = e; + } + const resource::Resources res = resource::track(p, native.layout, native.stage, st ? &*st : nullptr); + const io::Io io = io::raise(p, native); + if (st_err) throw *st_err; + return emit(c, native, p, *st, io, res); +} + +} // namespace + +std::uint32_t HostShader::user_data_dwords() const { + std::uint32_t n = 0; + for (const UserData& u : user_data) n = std::max(n, u.index + 1); + return (n + 3) / 4 * 4; +} + +std::vector<std::uint8_t> translation_fingerprint() { + std::vector<std::uint8_t> out; + auto bytes = [&](std::string_view s) { out.insert(out.end(), s.begin(), s.end()); }; + auto le32 = [&](std::uint32_t v) { + for (int k = 0; k < 4; ++k) out.push_back(std::uint8_t(v >> (8 * k))); + }; + bytes(X2W_VS_SOURCE_HASH); +#ifdef X2W_VS_DIAGNOSTICS + out.push_back(1); +#else + out.push_back(0); +#endif +#ifdef NDEBUG + out.push_back(0); +#else + out.push_back(1); +#endif + std::string_view names = X2W_VS_SWITCHES; + while (!names.empty()) { + std::size_t comma = names.find(','); + std::string_view name = names.substr(0, comma); + names = comma == std::string_view::npos ? std::string_view() : names.substr(comma + 1); + if (name.empty()) continue; + bytes(name); + out.push_back('='); + const std::string n(name); + if (auto v = env(n.c_str())) bytes(*v); + out.push_back(0); + } + le32(lower::host_max_wave()); + le32(lower::host_rdna()); + le32(shader::view_heap_limit()); + le32(shader::raw_views()); + le32(loop_limit()); + out.push_back(group_sync()); + le32(shader_opt()); + return out; +} + +HostShader translate(std::span<const std::uint8_t> container) { + try { + return translate_plain(container); + } catch (const ShaderError& e) { + if (!what_is(e, lower::FIRST_HALF)) throw; + } + return lower::with_first_half_pairs([&] { return translate_plain(container); }); +} + +HostShader emit(const dxbc::Container& c, const native::NativeProgram& native, const ir::Program& p, + const structure::Structured& st, const io::Io& io, const resource::Resources& res) { + // (what an earlier program's lowering on this thread left behind) + lower::take_needs(); + Emitted original = capture([&] { return emit_program(c, native, p, st, io, res); }); + // A console wave64 compute program on a host of 32-lane waves that still needs 64 lanes, or + // whose cross-lane code sits where not every lane runs: once more with its early-outs left out + // (ir::without_early_outs), which is what usually keeps the whole body from being a block + // every lane runs. + bool stuck = false; + if (original.ok) + stuck = original.ok->second == std::optional<std::uint32_t>(64); + else if (is_unsupported(*original.err)) + stuck = lower::needs_every_lane(original.err->reason); + // (a mask with lanes elsewhere is only helped by the exact forms: not by each half-wave on its + // own) + const bool exact_only = original.err && what_is(*original.err, lower::MASK_ELSEWHERE); + if (stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32) { + const bool why = env("X2W_SHADERCFG_WAVE_WHY").has_value(); + // Each host wave as a wave of its own (lower::with_local_waves), for programs still stopped + // where not every lane runs. + const bool local_on = [] { + auto v = env("X2W_SHADERCFG_WAVE_LOCAL"); + return !v || *v != "0"; + }(); + // Where the wave operations are the allocation idiom (lower::wave_local) that is exact. + // Other programs are taken the same way last of all, each half-wave giving its own results + // (approximate); X2W_SHADERCFG_WAVE_LOCAL=idiom refuses those instead. + const bool strict = [] { + auto v = env("X2W_SHADERCFG_WAVE_LOCAL"); + return v && *v == "idiom"; + }(); + auto idiom = [&](const ir::Program& fp, const structure::Structured& fst) { + auto err = lower::wave_local(fp, fst); + if (!err) return true; + if (why) + std::fprintf(stderr, "WAVE64-RETRY local waves: not the allocation idiom at %s: %s\n", + hex_alt(err->first).c_str(), err->second); + return false; + }; + // The program in two other forms: without its early-outs, and without any branch that only + // skips code no lane is left for. + std::optional<Form> f_early = form(native, ir::without_early_outs(p)); + std::optional<Form> f_skips = form(native, ir::without_skips(p, false)); + const std::pair<const char*, std::optional<Form>*> forms[2] = {{"without early-outs", &f_early}, + {"without skips", &f_skips}}; + for (const auto& [name, f] : forms) { + if (!*f) continue; + const Form& g = **f; + Emitted again = capture([&] { return emit_program(c, native, g.p, g.st, g.io, g.res); }); + report(why, name, again); + if (again.done()) return unwrap(std::move(again)); + } + const bool wide_on = [] { + auto v = env("X2W_SHADERCFG_WAVE_WIDE"); + return v && *v == "1"; + }(); + // exact first: each host wave on its own where that is exact (the idiom, every form; no + // barriers), then the other exact forms; then approximate + for (const bool exact : {true, false}) { + if (!exact) { + // Before anything approximate, the exact forms that cost group barriers. Every skip + // left out that the code after it cannot see (ir::without_skips, deep). + const bool deep_on = [] { + auto v = env("X2W_SHADERCFG_WAVE_DEEP_SKIPS"); + return !v || *v != "0"; + }(); + std::optional<Form> deep = deep_on ? form(native, ir::without_skips(p, true)) : std::nullopt; + if (deep) { + Emitted again = capture([&] { return emit_program(c, native, deep->p, deep->st, deep->io, deep->res); }); + report(why, "without skips, scalars followed", again); + if (again.done()) return unwrap(std::move(again)); + } + // Still stopped where not every lane runs: the per-lane branches around those places + // taken as the console takes them, by the whole wave at once (widen), at two group + // barriers per such branch. + if (wide_on) { + const ir::Program* base = deep ? &deep->p : f_skips ? &f_skips->p : f_early ? &f_early->p : &p; + Emitted again = widen(c, native, *base, why); + report(why, "wave-wide branches", again); + if (again.done()) return unwrap(std::move(again)); + } + if (strict) break; + } + if (!local_on || exact_only) continue; + for (const auto& [name, f] : forms) { + if (!*f) continue; + const Form& g = **f; + if (idiom(g.p, g.st) != exact) continue; + Emitted local = capture( + [&] { return lower::with_local_waves([&] { return emit_program(c, native, g.p, g.st, g.io, g.res); }); }); + report(why, std::string("local waves (") + (exact ? "idiom" : "APPROXIMATE") + "), " + name, local); + if (local.done()) return unwrap(std::move(local)); + } + if (idiom(p, st) == exact) { + Emitted local = + capture([&] { return lower::with_local_waves([&] { return emit_program(c, native, p, st, io, res); }); }); + report(why, exact ? "local waves (idiom)" : "local waves (APPROXIMATE)", local); + if (local.done()) return unwrap(std::move(local)); + } + } + if (local_on && !exact_only) { + // Last: every mask and lane read per host wave. + if (!strict) { + for (const auto& [name, f] : forms) { + if (!*f) continue; + const Form& g = **f; + Emitted local = capture([&] { + return lower::with_local_waves_any([&] { return emit_program(c, native, g.p, g.st, g.io, g.res); }); + }); + report(why, std::string("local waves (APPROXIMATE, any mask), ") + name, local); + if (local.done()) return unwrap(std::move(local)); + } + Emitted local = capture( + [&] { return lower::with_local_waves_any([&] { return emit_program(c, native, p, st, io, res); }); }); + report(why, "local waves (APPROXIMATE, any mask)", local); + if (local.done()) return unwrap(std::move(local)); + } + } + } + // SCC of a mask operation joined with a scalar test behind a per-lane skip (the 32-lane trace + // programs): right once the wave takes that skip together (widen; the lowering has named the + // skipped blocks). + if (original.err && native.stage == HwStage::Cs && what_is(*original.err, lower::LANE_MASK)) { + auto v = env("X2W_SHADERCFG_WAVE_WIDE"); + if (!v || *v != "0") { + Emitted again = widen(c, native, p, env("X2W_SHADERCFG_WAVE_WHY").has_value()); + if (again.ok) + original = std::move(again); + else + original = capture([&] { return emit_program(c, native, p, st, io, res); }); + } + } + // Retry unsupported programs only. Threading can separate an unknown register value from its + // apparent use on a mutually exclusive path. + if (!(original.err && is_unsupported(*original.err))) return unwrap(std::move(original)); + const auto edges = threading::constant_edges(p, st); + if (edges.empty()) return unwrap(std::move(original)); + const ir::Program tp = ir::thread_edges(p, edges); + const structure::Structured tst = structure::structure(tp); + const io::Io tio = io::raise(tp, native); + const resource::Resources tres = resource::track(tp, native.layout, native.stage, &tst); + return emit_program(c, native, tp, tst, tio, tres).first; +} + +} // namespace x2w::vs diff --git a/src/x2w_shader/emit/mod_signature.cpp b/src/x2w_shader/emit/mod_signature.cpp new file mode 100644 index 0000000000..43b2e8f333 --- /dev/null +++ b/src/x2w_shader/emit/mod_signature.cpp @@ -0,0 +1,136 @@ +// Read shader signatures and vertex output interpolation. + +#include <bit> +#include <string> + +#include "x2w_shader/dxbc.h" +#include "x2w_shader/emit/signature.h" +#include "x2w_shader/error.h" + +namespace x2w::vs { + +void vertex_output_interpolation(std::span<const std::uint8_t> data, std::span<container::SigElement> outputs) { + const ShaderError TRUNCATED = ShaderError::malformed("truncated vertex pipeline validation data"); + auto take = [&](std::size_t len) { + if (len > data.size()) throw TRUNCATED; + auto head = data.first(len); + data = data.subspan(len); + return head; + }; + auto size = [&]() { + auto b = take(4); + return std::size_t(std::uint32_t(b[0]) | std::uint32_t(b[1]) << 8 | std::uint32_t(b[2]) << 16 | + std::uint32_t(b[3]) << 24); + }; + auto mul = [&](std::size_t a, std::size_t b) { + if (b != 0 && a > SIZE_MAX / b) throw TRUNCATED; + return a * b; + }; + const std::size_t info_size = size(); + const auto info = take(info_size); + // PSVRuntimeInfo0 has no signature. PSVRuntimeInfo1 and later share these stage and signature + // count fields. + if (info.size() < 36 || info[24] != 1 || info[29] == 0) return; + const std::size_t resources = size(); + if (resources != 0) { + const std::size_t stride = size(); + take(mul(resources, stride)); + } + const std::size_t strings = size(); + take(strings); + const std::size_t indices = size(); + take(mul(indices, 4)); + const std::size_t stride = size(); + if (stride < 16) throw TRUNCATED; + const std::size_t count = std::size_t(info[28]) + std::size_t(info[29]); + const auto elements = take(mul(count, stride)); + for (std::size_t r = std::size_t(info[28]); r < count; ++r) { + const auto record = elements.subspan(r * stride, stride); + const std::uint8_t packed = record[10]; + if ((packed & 0x40) == 0) continue; + if (record[13] > 7) throw ShaderError::malformed("invalid vertex output interpolation"); + const std::uint32_t first = record[9]; + const std::uint32_t last = first + record[8]; + for (container::SigElement& output : outputs) { + if (output.row && *output.row >= first && *output.row < last && output.col == ((packed >> 4) & 3) && + output.cols == (packed & 15) && output.kind == record[11]) + output.interp = record[13]; + } + } +} + +std::vector<container::SigElement> signature(std::span<const std::uint8_t> part) { + using dxbc::u32_at; + const std::size_t count = u32_at(part, 0); + const std::size_t base = u32_at(part, 4); + std::vector<container::SigElement> out; + out.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + const std::size_t at = base + 32 * i; + const std::size_t name_at = u32_at(part, at + 4); + if (name_at > part.size()) throw ShaderError::malformed("signature name out of bounds"); + std::size_t end = name_at; + while (end < part.size() && part[end] != 0) ++end; + const std::string name(part.begin() + std::ptrdiff_t(name_at), part.begin() + std::ptrdiff_t(end)); + if (at + 24 >= part.size()) throw ShaderError::malformed("truncated"); + const std::uint8_t mask = part[at + 24]; + if (u32_at(part, at + 28) != 0) throw ShaderError::unsupported(0, "a minimum-precision signature element"); + if (u32_at(part, at) != 0) throw ShaderError::unsupported(0, "a signature element of another stream"); + std::uint8_t kind; + switch (u32_at(part, at + 12)) { + case 0: kind = 0; break; + case 1: kind = 3; break; + case 2: kind = 6; break; + case 3: kind = 7; break; + case 4: kind = 4; break; + case 5: kind = 5; break; + case 6: kind = 1; break; + case 7: kind = 10; break; + case 8: kind = 2; break; + case 9: kind = 13; break; + case 10: kind = 12; break; + case 64: kind = 16; break; + case 65: kind = 17; break; + case 66: kind = 14; break; + case 67: kind = 19; break; + case 68: kind = 18; break; + case 69: kind = 20; break; + case 70: kind = 15; break; + case 23: kind = 28; break; // barycentrics + case 25: kind = 30; break; // cull primitive + default: throw ShaderError::unsupported(0, "a system value in the signature"); + } + // 16-bit elements are declared 32-bit; reading or writing one converts (16-bit values + // travel packed on the console). + const std::uint32_t raw = u32_at(part, at + 16); + std::uint8_t comp; + if (kind == 13) { + // DXIL declares the front face a uint (the validator insists). + comp = 5; + } else if (raw == 1 || raw == 4) { + comp = 5; + } else if (raw == 2 || raw == 5) { + comp = 4; + } else if (raw == 3 || raw == 6) { + comp = 9; + } else { + throw ShaderError::unsupported(0, raw == 0 ? "a signature element of unknown type" : "a 64-bit signature element"); + } + const std::uint32_t reg = u32_at(part, at + 20); + container::SigElement e; + e.name = name; + e.index = u32_at(part, at + 8); + e.kind = kind; + e.comp = comp; + e.interp = 0; + if (reg != UINT32_MAX) e.row = reg; + e.col = std::uint8_t(std::min(std::countr_zero(std::uint8_t(mask)), 3)); + e.cols = std::uint8_t(std::max(std::popcount(std::uint8_t(mask)), 1)); + e.usage = 0; + e.half = raw >= 4 && raw <= 6; + out.push_back(std::move(e)); + } + return out; +} + +} // namespace x2w::vs diff --git a/src/x2w_shader/emit/opt.cpp b/src/x2w_shader/emit/opt.cpp new file mode 100644 index 0000000000..b33f64796d --- /dev/null +++ b/src/x2w_shader/emit/opt.cpp @@ -0,0 +1,1276 @@ +// clean-up of a finished module before it is written. The lowering emits one instruction after another as +// the console code names them, and nothing stands between it and the driver's compiler. Every pass here is +// exact: the module computes the same values and has the same effects for every input. +// +// - DEAD: instructions without an effect whose result nothing reads are left out (the lowering +// computes every dword of every register a console instruction writes; a guarded write reads +// the register's old value whether anything reads the new one or not). +// - FOLD: integer arithmetic on constants is done here, and identities (`x + 0`, `x & -1`, a +// select between a value and itself, a cast there and back, a join of one value) give their +// operand. Float arithmetic is left alone: `x + 0.0` and `x * 1.0` are not `x` for every `x`. +// - REUSE: an instruction without an effect whose operands are those of an earlier one that +// every path to it has run gives that one's result (a descriptor handle made again in each +// block, an index clamped again, a register read as a float again). +// - FACTS: in the blocks only one side of a branch leads to, the branch's condition is that +// side's constant, and so is what the condition was made of (both terms of an `and` that held, +// the opposite comparison). The lowering branches on a lane's condition and then guards each +// instruction behind the branch with the same condition. +// - LOADS: within a block, a read of the same place as an earlier read gives that one's result +// while no store, atomic, barrier or other call with an effect stands between them (another +// thread's unsynchronised store may fall between any two reads or before both: the title's +// code cannot tell which). +// +// The known, read, joins, facts and func_ids tables are only queried or updated. Their iteration order does +// not affect output. + +#include "x2w_shader/emit/opt.h" + +#include <algorithm> +#include <bit> +#include <cmath> +#include <cstddef> +#include <limits> +#include <optional> +#include <string_view> +#include <tuple> +#include <unordered_map> +#include <utility> +#include <vector> + +namespace x2w::vs::bitcode { + +namespace { + +using opt::Effect; + +constexpr std::size_t NONE = std::numeric_limits<std::size_t>::max(); + +// a NaN operand gives the other. +float fmax_rs(float a, float b) { + if (std::isnan(a)) return b; + if (std::isnan(b)) return a; + return a > b ? a : b; +} + +void mix(std::size_t& h, std::uint64_t v) { h ^= std::size_t(v) + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2); } + +std::uint64_t vbits(V v) { return (std::uint64_t(v.kind) << 32) | v.i; } + +// What makes two instructions without an effect the same value. +struct Key { + enum Kind : std::uint8_t { Bin, Cast, Cmp, Select, Extract, Call, Gep, Load }; + Kind kind = Bin; + std::uint8_t code = 0; + // Cast: type. Extract: index. Call: function. Gep: pointee type. + std::uint32_t n = 0; + std::vector<V> vs; + bool operator==(const Key&) const = default; +}; + +struct KeyHash { + std::size_t operator()(const Key& k) const noexcept { + std::size_t h = k.kind; + mix(h, k.code); + mix(h, k.n); + for (V v : k.vs) mix(h, vbits(v)); + return h; + } +}; + +using Cmp3 = std::tuple<std::uint8_t, V, V>; + +struct Cmp3Hash { + std::size_t operator()(const Cmp3& k) const noexcept { + std::size_t h = std::get<0>(k); + mix(h, vbits(std::get<1>(k))); + mix(h, vbits(std::get<2>(k))); + return h; + } +}; + +using JoinKey = std::vector<std::pair<std::size_t, V>>; + +struct JoinKeyHash { + std::size_t operator()(const JoinKey& k) const noexcept { + std::size_t h = k.size(); + for (const auto& [b, v] : k) { + mix(h, b); + mix(h, vbits(v)); + } + return h; + } +}; + +// The blocks reached from the entry, each after the blocks that dominate it, and each block's +// children in the dominator tree. +struct Tree { + std::vector<std::size_t> order; + std::vector<std::vector<std::size_t>> children; + // Per block: the reached blocks that branch to it, once per edge. + std::vector<std::vector<std::size_t>> preds; +}; + +// What holds in the block being walked: values that are a known bit there, and comparisons (by +// their operands) with a known outcome. +struct Facts { + std::unordered_map<V, bool, VHash> bits; + std::unordered_map<Cmp3, bool, Cmp3Hash> compares; +}; + +// The facts a block added, to forget when its part of the tree is done. +struct Learned { + std::vector<V> bits; + std::vector<Cmp3> compares; +}; + +std::uint64_t mask(std::uint32_t bits) { return bits >= 64 ? ~std::uint64_t(0) : (std::uint64_t(1) << bits) - 1; } + +// `x` of `bits` bits as a signed number. +std::int64_t signed_(std::uint32_t bits, std::uint64_t x) { + if (bits < 64 && ((x >> (bits - 1)) & 1) != 0) return std::int64_t(x | ~mask(bits)); + return std::int64_t(x); +} + +// What `v` stands for after the replacements so far. +V resolve(const std::vector<std::optional<V>>& repl, V v) { + while (v.kind == V::Inst) { + if (v.i >= repl.size()) bug("index out of bounds: resolve"); + const auto& r = repl[v.i]; + if (!r) break; + v = *r; + } + return v; +} + +// Replaces every value `op` reads by `f` of it. +template <class F> +void map_operands(Op& op, F&& f) { + switch (op.kind) { + case Op::Bin: + case Op::Cmp: + case Op::Store: + case Op::AtomicRmw: + op.a = f(op.a); + op.b = f(op.b); + break; + case Op::Cast: + case Op::Extract: + case Op::Load: + op.a = f(op.a); + break; + case Op::Select: + case Op::CmpXchg: + op.a = f(op.a); + op.b = f(op.b); + op.c = f(op.c); + break; + case Op::Call: + for (V& a : op.list) a = f(a); + break; + case Op::Phi: + for (auto& x : op.incoming) x.first = f(x.first); + break; + case Op::Gep: + op.a = f(op.a); + for (V& i : op.list) i = f(i); + break; + } +} + +bool starts_with(std::string_view s, std::string_view p) { return s.substr(0, p.size()) == p; } +bool ends_with(std::string_view s, std::string_view p) { + return s.size() >= p.size() && s.substr(s.size() - p.size()) == p; +} +std::string_view strip_dx_op(std::string_view name) { + return starts_with(name, "dx.op.") ? name.substr(6) : name; +} + +std::optional<std::uint32_t> int_bits(const Module& m, Ty ty) { + const TypeDef& d = m.types.at(ty.id); + if (d.kind == TypeDef::Int) return d.n; + return std::nullopt; +} + +bool is_op(const Module& m, V v, Op::Kind kind) { return v.kind == V::Inst && m.insts.at(v.i).op.kind == kind; } + +Tree dominator_tree(const Module& m) { + const std::size_t n = m.blocks.size(); + auto succs = [&](std::size_t b) { return successors(m.blocks.at(b).term); }; + // Reverse postorder, as `write` lays the blocks out. + std::vector<bool> seen(n, false); + std::vector<std::size_t> post; + std::vector<std::pair<std::size_t, std::size_t>> stack = {{0, 0}}; + seen.at(0) = true; + while (!stack.empty()) { + auto& top = stack.back(); + auto [b, k] = top; + top.second += 1; + Succs s = succs(b); + if (k < s.size()) { + std::size_t t = s.to[k]; + if (!seen.at(t)) { + seen[t] = true; + stack.push_back({t, 0}); + } + } else { + post.push_back(b); + stack.pop_back(); + } + } + std::reverse(post.begin(), post.end()); + std::vector<std::size_t> order = std::move(post); + std::vector<std::size_t> number(n, NONE); + for (std::size_t k = 0; k < order.size(); ++k) number[order[k]] = k; + std::vector<std::vector<std::size_t>> preds(n); + for (std::size_t b : order) + for (std::size_t s : succs(b)) preds.at(s).push_back(b); + // Immediate dominators (Cooper, Harvey and Kennedy's iteration). + std::vector<std::size_t> idom(n, NONE); + idom[0] = 0; + bool changed = true; + while (changed) { + changed = false; + for (std::size_t o = 1; o < order.size(); ++o) { + std::size_t b = order[o]; + std::size_t nw = NONE; + for (std::size_t p : preds[b]) { + if (idom[p] == NONE) continue; + if (nw == NONE) { + nw = p; + continue; + } + std::size_t x = p, y = nw; + while (x != y) { + while (number[x] > number[y]) x = idom[x]; + while (number[y] > number[x]) y = idom[y]; + } + nw = x; + } + if (idom[b] != nw) { + idom[b] = nw; + changed = true; + } + } + } + std::vector<std::vector<std::size_t>> children(n); + for (std::size_t o = 1; o < order.size(); ++o) { + std::size_t b = order[o]; + if (idom[b] >= n) bug("index out of bounds: idom"); + children[idom[b]].push_back(b); + } + return Tree{std::move(order), std::move(children), std::move(preds)}; +} + +// Notes that `v` (an i1) is `holds` in the block being walked, and what follows from it for the +// values `v` was made of. +void learn(const Module& m, V v, bool holds, Facts& facts, Learned& learned, std::uint32_t depth) { + if (v.kind != V::Inst) return; + if (facts.bits.contains(v)) return; + facts.bits.emplace(v, holds); + learned.bits.push_back(v); + if (depth == 0) return; + const Op& op = m.insts.at(v.i).op; + if (op.kind == Op::Bin && op.code == std::uint8_t(Bin::And) && holds) { + // Both terms of an `and` that holds hold; neither of an `or` that does not. + learn(m, op.a, true, facts, learned, depth - 1); + learn(m, op.b, true, facts, learned, depth - 1); + } else if (op.kind == Op::Bin && op.code == std::uint8_t(Bin::Or) && !holds) { + learn(m, op.a, false, facts, learned, depth - 1); + learn(m, op.b, false, facts, learned, depth - 1); + } else if (op.kind == Op::Bin && op.code == std::uint8_t(Bin::Xor)) { + auto ka = m.int_k(op.a); + auto kb = m.int_k(op.b); + V x; + std::uint64_t k; + if (!ka && kb && kb->first == 1) { + x = op.a; + k = kb->second; + } else if (ka && ka->first == 1 && !kb) { + x = op.b; + k = ka->second; + } else { + return; + } + learn(m, x, holds != (k != 0), facts, learned, depth - 1); + } else if (op.kind == Op::Cmp) { + // The opposite comparison of the same operands. + Cmp3 key{opt::opposite(op.code), op.a, op.b}; + if (!facts.compares.contains(key)) { + facts.compares.emplace(key, !holds); + learned.compares.push_back(key); + } + } +} + +// The constant `x` of the integer type `ty`, kept sign-extended as Module::i32 and Module::bool_ +// keep theirs. +V k_(Module& m, Ty ty, std::uint32_t bits, std::uint64_t x) { return m.int_const(ty, signed_(bits, x & mask(bits))); } + +bool int_pred_holds(std::uint8_t p, std::uint64_t x, std::uint64_t y, std::uint32_t bits) { + std::int64_t sx = signed_(bits, x), sy = signed_(bits, y); + switch (p) { + case pred::EQ: + return x == y; + case pred::NE: + return x != y; + case pred::IUGT: + return x > y; + case pred::IUGE: + return x >= y; + case pred::IULT: + return x < y; + case pred::IULE: + return x <= y; + case pred::SGT: + return sx > sy; + case pred::SGE: + return sx >= sy; + case pred::SLT: + return sx < sy; + default: + return sx <= sy; + } +} + +// The value instruction `i` is known to have without it, if any: a constant or an earlier value. +// May instead give `i` simpler operands (`changed` says so). +std::optional<V> simplify(Module& m, std::uint32_t i, bool& changed) { + const Ty ty = m.insts.at(i).ty; + // Constants made below grow consts and types, never insts: the reference stays valid. + const Op& op = m.insts[i].op; + switch (op.kind) { + case Op::Bin: { + // Floats: `x + 0.0`, `x * 1.0` and the like are not `x` for every `x` (a negative zero, + // a signalling NaN). + auto bits_ = int_bits(m, ty); + if (!bits_) return std::nullopt; + const std::uint32_t bits = *bits_; + const V a = op.a, b = op.b; + std::optional<std::uint64_t> ka, kb; + if (auto k = m.int_k(a)) ka = k->second; + if (auto k = m.int_k(b)) kb = k->second; + const std::uint64_t all = mask(bits); + const Bin bo = Bin(op.code); + if (ka && kb) { + const std::uint64_t x = *ka, y = *kb; + // A shift by the width or more and a division by zero have no defined result: left + // as they are. + std::optional<std::uint32_t> amount; + if (y <= 0xFFFFFFFFull && std::uint32_t(y) < bits) amount = std::uint32_t(y); + std::uint64_t r; + switch (bo) { + case Bin::Add: + r = x + y; + break; + case Bin::Sub: + r = x - y; + break; + case Bin::Mul: + r = x * y; + break; + case Bin::And: + r = x & y; + break; + case Bin::Or: + r = x | y; + break; + case Bin::Xor: + r = x ^ y; + break; + case Bin::Shl: + if (!amount) return std::nullopt; + r = x << *amount; + break; + case Bin::LShr: + if (!amount) return std::nullopt; + r = x >> *amount; + break; + case Bin::AShr: + if (!amount) return std::nullopt; + r = std::uint64_t(signed_(bits, x) >> *amount); + break; + case Bin::UDiv: + if (y == 0) return std::nullopt; + r = x / y; + break; + case Bin::URem: + if (y == 0) return std::nullopt; + r = x % y; + break; + default: + return std::nullopt; + } + return k_(m, ty, bits, r); + } + auto is = [](std::optional<std::uint64_t> k, std::uint64_t v) { return k && *k == v; }; + auto any = [&](std::initializer_list<Bin> l) { return std::find(l.begin(), l.end(), bo) != l.end(); }; + if (any({Bin::Add, Bin::Sub, Bin::Or, Bin::Xor, Bin::Shl, Bin::LShr, Bin::AShr}) && is(kb, 0)) return a; + if (any({Bin::Add, Bin::Or, Bin::Xor}) && is(ka, 0)) return b; + if (any({Bin::Mul, Bin::UDiv}) && is(kb, 1)) return a; + if (bo == Bin::Mul && is(ka, 1)) return b; + if (any({Bin::Mul, Bin::And}) && is(kb, 0)) return b; + if (any({Bin::Mul, Bin::And}) && is(ka, 0)) return a; + if (bo == Bin::And && is(kb, all)) return a; + if (bo == Bin::And && is(ka, all)) return b; + if (bo == Bin::Or && is(kb, all)) return b; + if (bo == Bin::Or && is(ka, all)) return a; + if (any({Bin::And, Bin::Or}) && a == b) return a; + return std::nullopt; + } + case Op::Cmp: { + const std::uint8_t p = op.code; + const V a = op.a, b = op.b; + if (p <= pred::TRUE_) { + // Two float constants compare one way (`v_mul_legacy` asks whether its constant + // factor is zero). + if (a.kind != V::Const || b.kind != V::Const) return std::nullopt; + const Const& cx = m.consts.at(a.i).second; + const Const& cy = m.consts.at(b.i).second; + if (cx.kind != Const::Float || cy.kind != Const::Float) return std::nullopt; + const float x = std::bit_cast<float>(cx.bits), y = std::bit_cast<float>(cy.bits); + const bool unordered = std::isnan(x) || std::isnan(y); + // Bits 0-2 of a predicate: equal, greater, less; bit 3: or unordered. + bool holds; + if (unordered) + holds = (p & 8) != 0; + else + holds = ((p & 1) != 0 && x == y) || ((p & 2) != 0 && x > y) || ((p & 4) != 0 && x < y); + return m.bool_(holds); + } + if (!(p >= pred::EQ && p <= pred::SLE)) return std::nullopt; + auto ka = m.int_k(a); + auto kb = m.int_k(b); + if (ka && kb) return m.bool_(int_pred_holds(p, ka->second, kb->second, ka->first)); + if (a == b) return m.bool_(int_pred_holds(p, 0, 0, 32)); + // A bit widened and tested again is the bit. + if (p == pred::NE && kb && kb->second == 0 && a.kind == V::Inst) { + const Op& z = m.insts.at(a.i).op; + if (z.kind == Op::Cast && z.code == std::uint8_t(Cast::ZExt) && m.type_of(z.a) == ty) return z.a; + } + return std::nullopt; + } + case Op::Select: { + const V c = op.a; + V t = op.b, f = op.c; + if (auto kc = m.int_k(c)) return kc->second != 0 ? t : f; + // Under the same condition an inner select is one of its operands (two guarded writes of + // one register in a row). + bool inner = false; + while (t.kind == V::Inst) { + const Op& o = m.insts.at(t.i).op; + if (!(o.kind == Op::Select && o.a == c)) break; + t = o.b; + inner = true; + } + while (f.kind == V::Inst) { + const Op& o = m.insts.at(f.i).op; + if (!(o.kind == Op::Select && o.a == c)) break; + f = o.c; + inner = true; + } + if (t == f) return t; + auto kt = m.int_k(t); + auto kf = m.int_k(f); + if (int_bits(m, ty) == std::optional<std::uint32_t>(1) && kt && kt->second == 1 && kf && kf->second == 0) + return c; + if (inner) { + Op& o = m.insts[i].op; + o.a = c; + o.b = t; + o.c = f; + changed = true; + } + return std::nullopt; + } + case Op::Cast: { + const Cast co = Cast(op.code); + const V x = op.a; + const Ty from = m.type_of(x); + std::optional<std::pair<Cast, V>> through; + if (x.kind == V::Inst) { + const Op& o = m.insts.at(x.i).op; + if (o.kind == Op::Cast) through = std::make_pair(Cast(o.code), o.a); + } + switch (co) { + case Cast::Bitcast: { + if (from == ty) return x; + // There and back: the bits are the same. + if (through && through->first == Cast::Bitcast && m.type_of(through->second) == ty) return through->second; + if (x.kind != V::Const) return std::nullopt; + const bool to_float = m.types.at(ty.id).kind == TypeDef::Float; + const Const c = m.consts.at(x.i).second; + if (c.kind == Const::Int && to_float && int_bits(m, from) == std::optional<std::uint32_t>(32)) + return m.f32(std::uint32_t(std::uint64_t(c.value))); + if (c.kind == Const::Float && int_bits(m, ty) == std::optional<std::uint32_t>(32)) + return m.int_const(ty, std::int64_t(std::int32_t(c.bits))); + return std::nullopt; + } + case Cast::ZExt: + case Cast::SExt: + case Cast::Trunc: { + auto to = int_bits(m, ty); + if (!to) return std::nullopt; + if (auto kx = m.int_k(x)) { + std::uint64_t k = co == Cast::SExt ? std::uint64_t(signed_(kx->first, kx->second)) : kx->second; + return k_(m, ty, *to, k); + } + // Widened and narrowed again. + if (co == Cast::Trunc && through && (through->first == Cast::ZExt || through->first == Cast::SExt) && + m.type_of(through->second) == ty) + return through->second; + return std::nullopt; + } + default: + return std::nullopt; + } + } + default: + return std::nullopt; + } +} + +// What kind of instruction `i` is for merging. +Effect class_of(const Module& m, const std::vector<Effect>& effects, std::uint32_t i) { + const Op& op = m.insts.at(i).op; + switch (op.kind) { + case Op::Bin: + case Op::Cast: + case Op::Cmp: + case Op::Select: + case Op::Extract: + case Op::Gep: + return Effect::Pure; + case Op::Load: { + // A constant table reads the same whatever is stored. + V p = op.a; + V base = p; + if (p.kind == V::Inst) { + const Op& g = m.insts.at(p.i).op; + if (g.kind == Op::Gep) base = g.a; + } + if (base.kind == V::Global && m.globals.at(base.i).init.has_value()) return Effect::Pure; + return Effect::Reads; + } + case Op::Store: + case Op::AtomicRmw: + case Op::CmpXchg: + return Effect::Writes; + case Op::Phi: + return Effect::Lanes; + case Op::Call: + return effects.at(op.index); + } + bug("unreachable: class"); +} + +std::optional<Key> key_of(const Module& m, std::uint32_t i) { + const Inst& inst = m.insts.at(i); + const Op& op = inst.op; + Key k; + switch (op.kind) { + case Op::Bin: { + // Integer sums, products and bit operations whichever way round; float ones as written + // (which NaN an operation of two NaNs gives is the hardware's choice by operand). + const Bin bo = Bin(op.code); + const bool commutes = (bo == Bin::Add || bo == Bin::Mul || bo == Bin::And || bo == Bin::Or || bo == Bin::Xor) && + int_bits(m, inst.ty).has_value(); + k.kind = Key::Bin; + k.code = op.code; + if (commutes && op.b < op.a) + k.vs = {op.b, op.a}; + else + k.vs = {op.a, op.b}; + return k; + } + case Op::Cast: + k.kind = Key::Cast; + k.code = op.code; + k.n = inst.ty.id; + k.vs = {op.a}; + return k; + case Op::Cmp: + k.kind = Key::Cmp; + k.code = op.code; + k.vs = {op.a, op.b}; + return k; + case Op::Select: + k.kind = Key::Select; + k.vs = {op.a, op.b, op.c}; + return k; + case Op::Extract: + k.kind = Key::Extract; + k.n = op.index; + k.vs = {op.a}; + return k; + case Op::Call: + k.kind = Key::Call; + k.n = op.index; + k.vs = op.list; + return k; + case Op::Gep: + k.kind = Key::Gep; + k.n = op.ty.id; + k.vs.reserve(op.list.size() + 1); + k.vs.push_back(op.a); + k.vs.insert(k.vs.end(), op.list.begin(), op.list.end()); + return k; + case Op::Load: + k.kind = Key::Load; + k.vs = {op.a}; + return k; + default: + return std::nullopt; + } +} + +// FOLD, REUSE, FACTS and LOADS: one walk over the dominator tree. Returns whether anything +// changed. +bool merge(Module& m, std::uint32_t passes) { + if (m.blocks.empty()) return false; + const std::vector<Effect> effects = m.effects(); + const Tree tree = dominator_tree(m); + std::vector<std::optional<V>> repl(m.insts.size()); + bool changed = false; + // Joins of one value: until none is left (one gone can leave another with one value). + if ((passes & opt::FOLD) != 0) { + bool again = true; + while (again) { + again = false; + for (std::size_t b : tree.order) { + for (std::uint32_t p : m.blocks[b].phis) { + if (repl.at(p)) continue; + const Op& op = m.insts.at(p).op; + if (op.kind != Op::Phi) continue; + std::optional<V> one; + bool same = true; + for (const auto& inc : op.incoming) { + V v = resolve(repl, inc.first); + if (v == V::inst(p)) continue; + if (!one) + one = v; + else if (*one != v) + same = false; + } + if (same && one) { + repl[p] = *one; + again = true; + changed = true; + } + } + } + } + } + // The values every path to the block being walked has computed (those of the blocks above it + // in the tree, and its own so far). + std::unordered_map<Key, V, KeyHash> known; + // The reads of the block being walked since its last store. + std::unordered_map<Key, V, KeyHash> read; + Facts facts; + const V yes = m.bool_(true); + const V no = m.bool_(false); + struct Step { + bool leave = false; + std::size_t b = 0; + std::vector<Key> keys; + Learned learned; + }; + std::vector<Step> steps; + steps.push_back(Step{false, 0, {}, {}}); + auto known_bit = [&](V v) { + auto it = facts.bits.find(v); + if (it == facts.bits.end()) return v; + return it->second ? yes : no; + }; + while (!steps.empty()) { + Step step = std::move(steps.back()); + steps.pop_back(); + if (step.leave) { + for (const Key& k : step.keys) known.erase(k); + for (V v : step.learned.bits) facts.bits.erase(v); + for (const Cmp3& k : step.learned.compares) facts.compares.erase(k); + continue; + } + const std::size_t b = step.b; + std::vector<Key> added; + // Reached from one block alone, by one side of its branch: the condition is that side's, + // here and in every block below. + Learned learned; + if ((passes & opt::FACTS) != 0 && tree.preds.at(b).size() == 1) { + std::size_t p = tree.preds[b][0]; + const auto& term = m.blocks.at(p).term; + if (term && term->kind == Term::CondBr && term->t != term->f) + learn(m, resolve(repl, term->cond), b == term->t, facts, learned, 8); + } + read.clear(); + // Two joins of the same values from the same blocks are one. + if ((passes & opt::REUSE) != 0 && m.blocks[b].phis.size() > 1) { + std::unordered_map<JoinKey, V, JoinKeyHash> joins; + for (std::uint32_t p : m.blocks[b].phis) { + if (repl.at(p)) continue; + const Ty ty = m.insts.at(p).ty; + const Op& op = m.insts[p].op; + if (op.kind != Op::Phi) continue; + JoinKey key; + key.reserve(op.incoming.size() + 1); + for (const auto& [v, from] : op.incoming) key.emplace_back(from, resolve(repl, v)); + std::sort(key.begin(), key.end()); + // The type too: an undefined value of one type is not that of another. + key.emplace_back(std::size_t(ty.id), V::global(0xFFFFFFFFu)); + auto it = joins.find(key); + if (it != joins.end()) { + repl[p] = it->second; + changed = true; + } else { + joins.emplace(std::move(key), V::inst(p)); + } + } + } + std::vector<std::uint32_t> body = std::move(m.blocks[b].body); + m.blocks[b].body.clear(); + std::vector<std::uint32_t> kept; + kept.reserve(body.size()); + for (std::uint32_t i : body) { + map_operands(m.insts.at(i).op, [&](V v) { + V r = resolve(repl, v); + V bit = known_bit(r); + changed |= bit != r; + return bit; + }); + { + const Op& op = m.insts[i].op; + if (op.kind == Op::Cmp) { + auto it = facts.compares.find(Cmp3{op.code, op.a, op.b}); + if (it != facts.compares.end()) { + repl[i] = it->second ? yes : no; + changed = true; + continue; + } + } + } + if ((passes & opt::FOLD) != 0) { + if (auto v = simplify(m, i, changed)) { + repl[i] = *v; + changed = true; + continue; + } + } + const Effect cls = class_of(m, effects, i); + if ((passes & opt::REUSE) != 0 && cls == Effect::Pure) { + if (auto key = key_of(m, i)) { + auto it = known.find(*key); + if (it != known.end()) { + repl[i] = it->second; + changed = true; + continue; + } + known.emplace(*key, V::inst(i)); + added.push_back(std::move(*key)); + } + } + // Reads of memory, and wave operations (the same lanes run the whole block): the + // block's own earlier one. + if ((passes & opt::LOADS) != 0 && (cls == Effect::Reads || cls == Effect::Lanes)) { + if (auto key = key_of(m, i)) { + auto it = read.find(*key); + if (it != read.end()) { + repl[i] = it->second; + changed = true; + continue; + } + read.emplace(std::move(*key), V::inst(i)); + } + } + if (cls == Effect::Writes) read.clear(); + kept.push_back(i); + } + m.blocks[b].body = std::move(kept); + if (auto& term = m.blocks[b].term; term && term->kind == Term::CondBr) term->cond = known_bit(resolve(repl, term->cond)); + steps.push_back(Step{true, 0, std::move(added), std::move(learned)}); + const auto& ch = tree.children.at(b); + for (auto it = ch.rbegin(); it != ch.rend(); ++it) steps.push_back(Step{false, *it, {}, {}}); + } + if (!changed) return false; + // Everything that read a replaced value reads its replacement (joins read values from blocks + // walked after them). + for (Block& blk : m.blocks) { + std::erase_if(blk.phis, [&](std::uint32_t p) { return repl.at(p).has_value(); }); + if (blk.term && blk.term->kind == Term::CondBr) blk.term->cond = resolve(repl, blk.term->cond); + } + auto res = [&](V v) { return resolve(repl, v); }; + for (const Block& blk : m.blocks) { + for (std::uint32_t i : blk.phis) map_operands(m.insts.at(i).op, res); + for (std::uint32_t i : blk.body) map_operands(m.insts.at(i).op, res); + } + return true; +} + +// FOLD: a branch on a constant goes one way. The side not taken loses the branching block's +// values at its joins, and so do the joins of blocks that nothing reaches any more. Returns +// whether a branch changed. +bool prune(Module& m) { + bool changed = false; + for (std::size_t b = 0; b < m.blocks.size(); ++b) { + if (!m.blocks[b].term || m.blocks[b].term->kind != Term::CondBr) continue; + const Term t = *m.blocks[b].term; + // Both sides one block: two edges into it, left as they are. + if (t.t == t.f) continue; + auto k = m.int_k(t.cond); + if (!k) continue; + std::size_t taken = k->second != 0 ? t.t : t.f; + std::size_t not_ = k->second != 0 ? t.f : t.t; + m.blocks[b].term = Term::br(taken); + changed = true; + for (std::uint32_t p : m.blocks.at(not_).phis) { + Op& op = m.insts.at(p).op; + if (op.kind == Op::Phi) std::erase_if(op.incoming, [&](const auto& x) { return x.second == b; }); + } + } + if (!changed) return false; + const std::vector<bool> reached = m.reached(); + for (std::size_t b = 0; b < m.blocks.size(); ++b) { + if (!reached[b]) continue; + for (std::uint32_t p : m.blocks[b].phis) { + Op& op = m.insts.at(p).op; + if (op.kind == Op::Phi) + std::erase_if(op.incoming, [&](const auto& x) { return !reached.at(x.second); }); + } + } + return true; +} + +// Whether instruction `i` must stay whatever reads it. +bool has_effect(const Module& m, const std::vector<Effect>& effects, std::uint32_t i) { + const Op& op = m.insts.at(i).op; + switch (op.kind) { + case Op::Store: + case Op::AtomicRmw: + case Op::CmpXchg: + return true; + case Op::Call: + return effects.at(op.index) == Effect::Writes; + default: + return false; + } +} + +// A constant table no remaining load reads leaves the module (the validator refuses an internal +// declaration nothing uses). Shared memory stays declared whether it is read or not. +void drop_unused_tables(Module& m) { + std::vector<bool> used; + used.reserve(m.globals.size()); + for (const Global& g : m.globals) used.push_back(!g.init.has_value()); + if (std::all_of(used.begin(), used.end(), [](bool u) { return u; })) return; + auto note = [&](V v) { + if (v.kind == V::Global) used.at(v.i) = true; + }; + for (const Block& blk : m.blocks) { + for (std::uint32_t i : blk.phis) for_each_operand(m.insts.at(i).op, note); + for (std::uint32_t i : blk.body) for_each_operand(m.insts.at(i).op, note); + } + for (const MdDef& md : m.mds) + if (md.kind == MdDef::Value && md.v.kind == V::Global) used.at(md.v.i) = true; + if (std::all_of(used.begin(), used.end(), [](bool u) { return u; })) return; + std::vector<std::uint32_t> nw(used.size(), 0xFFFFFFFFu); + { + std::uint32_t next = 0; + for (std::size_t old = 0; old < used.size(); ++old) + if (used[old]) nw[old] = next++; + } + { + std::vector<Global> kept; + for (std::size_t g = 0; g < m.globals.size(); ++g) + if (used[g]) kept.push_back(std::move(m.globals[g])); + m.globals = std::move(kept); + } + auto renumber = [&](V v) { + if (v.kind == V::Global && used.at(v.i)) return V::global(nw[v.i]); + return v; + }; + for (Inst& inst : m.insts) map_operands(inst.op, renumber); + for (MdDef& md : m.mds) + if (md.kind == MdDef::Value) md.v = renumber(md.v); +} + +// Declarations no remaining call names leave the module (the validator refuses an external +// function nothing uses); the others keep their order, so `main` stays function 0. +void drop_unused_functions(Module& m) { + std::vector<bool> used; + used.reserve(m.funcs.size()); + for (const Func& f : m.funcs) used.push_back(f.body); + auto note = [&](std::uint32_t i) { + const Op& op = m.insts.at(i).op; + if (op.kind == Op::Call) used.at(op.index) = true; + }; + for (const Block& blk : m.blocks) { + for (std::uint32_t i : blk.phis) note(i); + for (std::uint32_t i : blk.body) note(i); + } + for (const MdDef& md : m.mds) + if (md.kind == MdDef::Value && md.v.kind == V::Func) used.at(md.v.i) = true; + if (std::all_of(used.begin(), used.end(), [](bool u) { return u; })) return; + std::vector<std::uint32_t> nw(used.size(), 0xFFFFFFFFu); + { + std::uint32_t next = 0; + for (std::size_t old = 0; old < used.size(); ++old) + if (used[old]) nw[old] = next++; + } + { + std::vector<Func> kept; + for (std::size_t f = 0; f < m.funcs.size(); ++f) + if (used[f]) kept.push_back(std::move(m.funcs[f])); + m.funcs = std::move(kept); + } + m.func_ids.clear(); + for (std::size_t i = 0; i < m.funcs.size(); ++i) m.func_ids[m.funcs[i].name] = std::uint32_t(i); + // Instructions that left their block keep a stale number: nothing reads them again. + for (Inst& inst : m.insts) + if (inst.op.kind == Op::Call && used.at(inst.op.index)) inst.op.index = nw[inst.op.index]; + for (MdDef& md : m.mds) + if (md.kind == MdDef::Value && md.v.kind == V::Func) md.v.i = nw.at(md.v.i); +} + +// DEAD: keeps the instructions with an effect, the branch conditions, and what they read, +// transitively; the rest leave their blocks. Blocks no branch reaches are emptied (they are not +// written). +void drop_dead(Module& m) { + const std::vector<Effect> effects = m.effects(); + const std::vector<bool> reached = m.reached(); + std::vector<bool> live(m.insts.size(), false); + std::vector<std::uint32_t> work; + auto mark = [&](V v) { + if (v.kind == V::Inst && !live.at(v.i)) { + live[v.i] = true; + work.push_back(v.i); + } + }; + for (std::size_t b = 0; b < m.blocks.size(); ++b) { + if (!reached[b]) continue; + const Block& blk = m.blocks[b]; + for (std::uint32_t i : blk.body) + if (has_effect(m, effects, i)) mark(V::inst(i)); + if (blk.term && blk.term->kind == Term::CondBr) mark(blk.term->cond); + } + while (!work.empty()) { + std::uint32_t i = work.back(); + work.pop_back(); + for_each_operand(m.insts.at(i).op, mark); + } + for (std::size_t b = 0; b < m.blocks.size(); ++b) { + Block& blk = m.blocks[b]; + if (reached[b]) { + std::erase_if(blk.body, [&](std::uint32_t i) { return !live.at(i); }); + std::erase_if(blk.phis, [&](std::uint32_t i) { return !live.at(i); }); + } else { + blk.body.clear(); + blk.phis.clear(); + } + } + drop_unused_functions(m); + drop_unused_tables(m); +} + +} // namespace + +namespace opt { + +Effect effect(const Func& f) { + const std::string_view name = strip_dx_op(f.name); + if (f.attr == Attr::ReadNone) return Effect::Pure; + if (f.attr == Attr::ReadOnly) { + // A shader cannot write a constant buffer or resize a resource. + if (starts_with(name, "cbufferLoadLegacy") || starts_with(name, "getDimensions")) return Effect::Pure; + if (starts_with(name, "wave")) return Effect::Lanes; + return Effect::Reads; + } + // Declared with the attribute of calls that have effects, and have none: they read the other + // lanes' values. + if (starts_with(name, "wave") || starts_with(name, "quad")) return Effect::Lanes; + return Effect::Writes; +} + +std::uint8_t opposite(std::uint8_t p) { + if (p <= 15) return std::uint8_t(15 - p); + switch (p) { + case pred::EQ: + return pred::NE; + case pred::NE: + return pred::EQ; + case pred::IUGT: + return pred::IULE; + case pred::IULE: + return pred::IUGT; + case pred::IUGE: + return pred::IULT; + case pred::IULT: + return pred::IUGE; + case pred::SGT: + return pred::SLE; + case pred::SLE: + return pred::SGT; + case pred::SGE: + return pred::SLT; + default: + return pred::SGE; + } +} + +} // namespace opt + +void Module::optimise(std::uint32_t passes) { + if ((passes & (opt::FOLD | opt::REUSE | opt::FACTS | opt::LOADS)) != 0) { + // Values merged in one round can make two joins the same in the next (a loop's registers + // that only go round), and a branch that goes one way leaves blocks with one way in. + for (int round = 0; round < 4; ++round) { + bool changed = merge(*this, passes); + if ((passes & opt::FOLD) != 0) changed |= prune(*this); + if (!changed) break; + } + } + if ((passes & opt::DEAD) != 0) drop_dead(*this); +} + +std::vector<opt::Effect> Module::effects() const { + std::vector<opt::Effect> r; + r.reserve(funcs.size()); + for (const Func& f : funcs) r.push_back(opt::effect(f)); + return r; +} + +std::vector<bool> Module::reached() const { + std::vector<bool> seen(blocks.size(), false); + if (blocks.empty()) return seen; + std::vector<std::size_t> stack = {0}; + seen[0] = true; + while (!stack.empty()) { + std::size_t b = stack.back(); + stack.pop_back(); + for (std::size_t s : successors(blocks[b].term)) { + if (!seen.at(s)) { + seen[s] = true; + stack.push_back(s); + } + } + } + return seen; +} + +// An integer constant's width and value (the bits of that width). +std::optional<std::pair<std::uint32_t, std::uint64_t>> Module::int_k(V v) const { + if (v.kind != V::Const) return std::nullopt; + const auto& [ty, c] = consts.at(v.i); + if (c.kind != Const::Int) return std::nullopt; + auto bits = int_bits(*this, ty); + if (!bits) return std::nullopt; + return std::make_pair(*bits, std::uint64_t(c.value) & mask(*bits)); +} + +// The bits of a 32-bit float that is a constant, given as one or as a cast of an integer constant. +std::optional<float> Module::float_k(V v) const { + bool cast = false; + if (v.kind == V::Inst) { + const Op& op = insts.at(v.i).op; + if (!(op.kind == Op::Cast && op.code == std::uint8_t(Cast::Bitcast))) return std::nullopt; + v = op.a; + cast = true; + } + if (v.kind != V::Const) return std::nullopt; + const Const& c = consts.at(v.i).second; + if (c.kind == Const::Float && !cast) return std::bit_cast<float>(c.bits); + if (c.kind == Const::Int && cast) { + auto k = int_k(v); + if (!k) return std::nullopt; + if (k->first != 32) return std::nullopt; + return std::bit_cast<float>(std::uint32_t(k->second)); + } + return std::nullopt; +} + +// For a float that is a number and not an infinity whatever the program reads: a power of two +// its magnitude does not pass. +std::optional<float> Module::bounded(V v, std::uint32_t depth) const { + if (auto k = float_k(v)) { + if (!std::isfinite(*k)) return std::nullopt; + return std::ceil(std::log2(fmax_rs(std::fabs(*k), 1e-30f))); + } + if (v.kind != V::Inst) return std::nullopt; + if (depth == 0) return std::nullopt; + const std::uint32_t d = depth - 1; + auto of = [&](V x) { return bounded(x, d); }; + // (A power that overflows, or might with rounding, is no bound.) + auto held = [](float b) -> std::optional<float> { + if (b < 126.0f) return b; + return std::nullopt; + }; + const Op& op = insts.at(v.i).op; + switch (op.kind) { + case Op::Cast: { + const Cast co = Cast(op.code); + if (co == Cast::UiToFp || co == Cast::SiToFp) return 32.0f; + if (co == Cast::Bitcast) { + V x = op.a; + if (x.kind != V::Inst) return std::nullopt; + const Op& o = insts.at(x.i).op; + if (o.kind == Op::Cast && o.code == std::uint8_t(Cast::Bitcast) && type_of(o.a) == type_of(v)) return of(o.a); + return std::nullopt; + } + return std::nullopt; + } + case Op::Bin: { + const Bin bo = Bin(op.code); + if (bo == Bin::Mul) { + auto a = of(op.a); + if (!a) return std::nullopt; + auto b = of(op.b); + if (!b) return std::nullopt; + return held(*a + *b); + } + if (bo == Bin::Add || bo == Bin::Sub) { + auto a = of(op.a); + if (!a) return std::nullopt; + auto b = of(op.b); + if (!b) return std::nullopt; + return held(fmax_rs(*a, *b) + 1.0f); + } + return std::nullopt; + } + case Op::Select: { + auto a = of(op.b); + if (!a) return std::nullopt; + auto b = of(op.c); + if (!b) return std::nullopt; + return fmax_rs(*a, *b); + } + case Op::Call: { + const auto& args = op.list; + if (args.empty()) return std::nullopt; + auto kc = int_k(args[0]); + if (!kc) return std::nullopt; + const std::uint64_t code = kc->second; + const std::size_t n = args.size() - 1; + // Saturated, a fraction, a cosine or sine (of a number). + if (code == 7 && n == 1) return 0.0f; + if (code == 6 && n == 1) return of(args[1]); + if ((code == 22 || code == 12 || code == 13) && n == 1) { + if (of(args[1])) return 0.0f; + return std::nullopt; + } + if (code >= 26 && code <= 29 && n == 1) { + auto x = of(args[1]); + if (!x) return std::nullopt; + return held(*x + 1.0f); + } + // Of two numbers; or one of them the other way round: the minimum (36) of a constant and + // a maximum of another. + if ((code == 35 || code == 36) && n == 2) { + const V a = args[1], b = args[2]; + auto x = of(a); + auto y = of(b); + if (x && y) return fmax_rs(*x, *y); + const std::uint64_t other = code == 35 ? 36 : 35; + V inner, kv; + if (float_k(b).has_value()) { + inner = a; + kv = b; + } else { + inner = b; + kv = a; + } + if (!float_k(kv)) return std::nullopt; + auto k = of(kv); + if (!k) return std::nullopt; + if (inner.kind != V::Inst) return std::nullopt; + const Op& io = insts.at(inner.i).op; + if (io.kind != Op::Call) return std::nullopt; + if (io.list.empty()) return std::nullopt; + auto ic = int_k(io.list[0]); + if (!ic) return std::nullopt; + std::optional<V> low; + for (std::size_t j = 1; j < io.list.size(); ++j) { + if (float_k(io.list[j]).has_value()) { + low = io.list[j]; + break; + } + } + if (!low) return std::nullopt; + if (ic->second != other) return std::nullopt; + auto l = of(*low); + if (!l) return std::nullopt; + return fmax_rs(*k, *l); + } + if (code == 46 && n == 3) { + auto a = of(args[1]); + if (!a) return std::nullopt; + auto b = of(args[2]); + if (!b) return std::nullopt; + auto c = of(args[3]); + if (!c) return std::nullopt; + return held(fmax_rs(*a + *b, *c) + 1.0f); + } + return std::nullopt; + } + default: + return std::nullopt; + } +} + +// See Usage: over the blocks reached from the entry. +opt::Usage Module::usage() const { + opt::Usage u; + const std::vector<bool> rch = reached(); + auto wide = [&](Ty ty) { + const TypeDef& d = types.at(ty.id); + return d.kind == TypeDef::Int && d.n == 64 && d.of.id == 0 && !d.name && d.list.empty(); + }; + // The first field of a handle's annotation: its kind, with the UAV bit; the second: the + // component type and count. + auto annotation = [&](V h) -> std::optional<std::pair<std::int64_t, std::int64_t>> { + if (h.kind != V::Inst) return std::nullopt; + const Op& op = insts.at(h.i).op; + if (op.kind != Op::Call) return std::nullopt; + if (funcs.at(op.index).name != "dx.op.annotateHandle") return std::nullopt; + if (op.list.size() <= 2) return std::nullopt; + V props = op.list[2]; + if (props.kind != V::Const) return std::nullopt; + const Const& pc = consts.at(props.i).second; + if (pc.kind != Const::Aggregate) return std::nullopt; + const Const& f0 = consts.at(pc.ids.at(0)).second; + const Const& f1 = consts.at(pc.ids.at(1)).second; + if (f0.kind == Const::Int && f1.kind == Const::Int) return std::make_pair(f0.value, f1.value); + return std::nullopt; + }; + auto one = [&](std::uint32_t i) { + const Inst& inst = insts.at(i); + u.int64 |= wide(inst.ty); + for_each_operand(inst.op, [&](V v) { u.int64 |= wide(type_of(v)); }); + if (inst.op.kind != Op::Call) return; + const auto& args = inst.op.list; + const std::string_view name = strip_dx_op(funcs.at(inst.op.index).name); + if (starts_with(name, "wave") || starts_with(name, "quad")) { + u.wave_ops = true; + } else if (name == "createHandleFromHeap") { + std::optional<std::pair<std::uint32_t, std::uint64_t>> k; + if (args.size() > 2) k = int_k(args[2]); + if (k && k->second == 0) + u.heap_views = true; + else + u.heap_samplers = true; + } else if (name == "annotateHandle") { + auto a = annotation(V::inst(i)); + u.rovs |= a && (a->first & 0x2000) != 0; + } else if (starts_with(name, "atomic") && ends_with(name, ".i64")) { + u.atomic64 = true; + } else if (starts_with(name, "textureLoad") || starts_with(name, "bufferLoad")) { + std::optional<std::pair<std::int64_t, std::int64_t>> a; + if (args.size() > 1) a = annotation(args[1]); + u.typed_uav_loads |= !a || ((a->first & 0x1000) != 0 && ((a->second >> 8) & 0xff) > 1); + } + }; + for (std::size_t b = 0; b < blocks.size(); ++b) { + if (!rch[b]) continue; + for (std::uint32_t i : blocks[b].phis) one(i); + for (std::uint32_t i : blocks[b].body) one(i); + } + return u; +} + +} // namespace x2w::vs::bitcode diff --git a/src/x2w_shader/emit/opt.h b/src/x2w_shader/emit/opt.h new file mode 100644 index 0000000000..92fc330999 --- /dev/null +++ b/src/x2w_shader/emit/opt.h @@ -0,0 +1,73 @@ +#pragma once + +// Clean-up of a finished module before it is written. Every pass is exact: the module computes the same +// values and has the same effects for every input. The passes run as Module::optimise(passes); which ones +// is shader_opt() (X2W_SHADERCFG_SHADER_OPT), part of the translation and so of the shader cache's key. + +#include <cstdint> + +#include "x2w_shader/emit/bitcode.h" + +namespace x2w::vs::bitcode::opt { + +// Dead-code elimination. +inline constexpr std::uint32_t DEAD = 1; +// Constants folded, identities removed. +inline constexpr std::uint32_t FOLD = 2; +// One instruction for one value. +inline constexpr std::uint32_t REUSE = 4; +// What a branch taken says about its condition. +inline constexpr std::uint32_t FACTS = 8; +// One read for one place within a block, while nothing is stored. +inline constexpr std::uint32_t LOADS = 16; +// Not a pass over the module: the lowering of a first-lane read in a wave64 program run as two +// host waves skips the exchange that asks which half has a lane where every lane is in EXEC. +inline constexpr std::uint32_t FIRST = 32; +// Not a pass over the module either: the lowering reads the dwords of one console load by one +// call for every four of them (lower `raw_dwords`). +inline constexpr std::uint32_t WIDE = 64; +// The passes over the module. +inline constexpr std::uint32_t MODULE = DEAD | FOLD | REUSE | FACTS | LOADS; +// Every pass. +inline constexpr std::uint32_t ALL = MODULE | FIRST | WIDE; +// The passes that run when nothing says which: every one but WIDE. +inline constexpr std::uint32_t DEFAULT = ALL & ~WIDE; + +// What the instructions a module writes use, of the features a shader declares by flag (the +// validator's "flags must match usage"). +struct Usage { + // A wave or quad operation. + bool wave_ops = false; + // A rasterizer ordered view. + bool rovs = false; + // A 64-bit integer, as a result or an operand. + bool int64 = false; + // A typed load of several components from a UAV. + bool typed_uav_loads = false; + // A handle from the view heap. + bool heap_views = false; + // A handle from the sampler heap. + bool heap_samplers = false; + // A 64-bit atomic. + bool atomic64 = false; + bool operator==(const Usage&) const = default; +}; + +// What a call does besides returning its result. +enum class Effect : std::uint8_t { + // Nothing, and the result depends on the arguments alone for the whole run of the shader. + Pure, + // Nothing, but the result depends on memory a store may change (buffer and texture reads). + Reads, + // Nothing, but the result depends on which lanes run the instruction (wave and quad ops). + Lanes, + // Stores, atomics, barriers, outputs, discards: always kept. + Writes, +}; + +Effect effect(const Func& f); + +// The comparison that holds exactly when p does not (floats 0-15, integers 32-41). +std::uint8_t opposite(std::uint8_t p); + +} // namespace x2w::vs::bitcode::opt diff --git a/src/x2w_shader/emit/own_bits.cpp b/src/x2w_shader/emit/own_bits.cpp new file mode 100644 index 0000000000..daff04cd40 --- /dev/null +++ b/src/x2w_shader/emit/own_bits.cpp @@ -0,0 +1,811 @@ +// Wave ORs that only steer a loop over each lane's own bits. +// +// The title's light loops are "scalarised": the lanes' light masks are ORed over the wave and the +// wave walks the set bits of the result together, each lane working only where its own mask has +// the bit: +// +// merged = WaveActiveBitOr(mask); // over the lanes that run +// while (merged != 0) { +// bit = firstbitlow(merged); +// if (mask & (1 << bit)) { ... } // the body +// merged ^= 1 << bit; +// } +// +// A console wave64 program in two host waves of 32 cannot exchange the halves' ORs where not every +// lane runs (a group barrier must be reached by every thread). It does not have to: as one thread +// runs it, the loop visits the bits of `merged` in rising order and does something only at the bits +// of the thread's own mask, so any `merged` that holds the thread's own bits gives that thread the +// same run. The host wave's own OR is such a value. +// +// That holds only if the OR is used for nothing else, and if a round of the loop at a bit the +// thread does not have leaves nothing behind. find proves both for each wave OR, with no +// instruction sequence taken on trust: +// +// - the OR and what derives from it as "the bits still to visit" (copies, the loop's join, the +// first-lane read of it, the set less the visited bit) are read only by the loop's own steps: the +// test for an empty set, the lowest set bit, the removal of that bit, the test that ends the loop; +// - the lane's test is its own bit of the very value that was ORed, and "the body" is what a lane +// only reaches with that test true in the same round; +// - outside the body the loop has no side effect and no cross-lane step, writes nothing that is +// read after the loop or carried into a later round, and is left only by the test for "no bits +// left"; +// - no lane mask that depends on the test is used outside the round that made it. +// +// Anything else is refused there as before ("a wave reduction where not every lane runs") and left +// to the forms of the program in which every lane runs that code (`emit`'s retries: the skips left +// out, the branches around it taken wave-wide), where the halves do exchange. +// `X2W_SHADERCFG_WAVE_OWN_BITS=0` turns this off (checked by the lowering). + +#include "x2w_shader/emit/own_bits.h" + +#include <algorithm> +#include <cstdio> +#include <map> +#include <optional> +#include <set> +#include <unordered_map> +#include <unordered_set> +#include <utility> +#include <variant> +#include <vector> + +#include "x2w_shader/emit/wave.h" +#include "x2w_shader/structure.h" + +namespace x2w::vs::lower { +// Declared in emit/lower.h. A forward declaration avoids pulling in the lowering headers. +bool reads_mask_as_data(const structure::Structured& st, const ir::Inst& i); +} // namespace x2w::vs::lower + +namespace x2w::vs::own_bits { + +using gfx10::Fields; +using gfx10::NULL_CODE; +using gfx10::Operand; +using gfx10::Valu; +using ir::EXEC; +using ir::Exit; +using ir::Inst; +using ir::Program; +using ir::Reg; +using ir::Value; +using structure::Atom; +using structure::Bool; +using structure::BoolHash; +using structure::LaneExit; +using structure::Structured; +using wave::Op; +using wave::Shape; + +namespace { + +using Why = const char*; + +constexpr Why USED = "a wave OR used as data"; +constexpr Why NO_LOOP = "a wave OR that steers no loop over its bits"; +constexpr Why SHAPE = "a loop over a wave OR's bits of another shape"; +constexpr Why TEST = "a loop over a wave OR's bits whose lanes do not test their own bit"; +constexpr Why LEAVES = "a value of a round over a wave OR's bits that outlives the round"; +constexpr Why EFFECT = "an effect in a loop over a wave OR's bits outside the lanes' own bits"; +constexpr Why CROSS = "a cross-lane step in a loop over a wave OR's bits outside the lanes' own bits"; +constexpr Why EXIT = "a loop over a wave OR's bits left another way"; +constexpr Why STALE = "a lane's own-bit test used outside its round"; +constexpr Why MASK = "a wave OR over a mask a running lane may be outside"; + +using Site = std::pair<std::size_t, std::size_t>; + +struct User { + enum Kind : std::uint8_t { Inst, Phi }; + Kind kind; + std::size_t b; + std::size_t i; // Inst: the instruction; Phi: the phi + bool operator==(const User&) const = default; +}; + +struct Arg { + enum Kind : std::uint8_t { Val, K, Other }; + Kind kind = Other; + Value v{}; + std::uint32_t k = 0; + bool operator==(const Arg&) const = default; + static Arg val(Value v) { return Arg{Val, v, 0}; } + static Arg konst(std::uint32_t k) { return Arg{K, Value{}, k}; } + static Arg other() { return Arg{}; } +}; + +// Where and why a wave OR is not such a loop. +struct Err { + std::size_t offset; + Why what; +}; + +template <class C, class T> +bool contains(const C& c, const T& x) { + return std::find(c.begin(), c.end(), x) != c.end(); +} + +bool is_cmp_scalar(std::string_view name) { + return name == "s_cmp_eq_u32" || name == "s_cmp_lg_u32" || name == "s_cmp_eq_i32" || name == "s_cmp_lg_i32"; +} + +// The values instruction `i` of block `b` uses: what its operands read, without EXEC (lane masks +// are followed as booleans) and without the old value of a VGPR it writes, which only lanes +// outside a guard keep. +std::vector<Value> used(const Program& p, const Structured& st, std::size_t b, std::size_t i) { + const Inst& inst = p.blocks.at(b).insts.at(i); + const std::vector<Reg> ops = ir::operand_reads(p, inst); + const bool guarded = st.guards.at(b).at(i).has_value(); + std::vector<Value> out; + for (const auto& [r, v] : inst.reads) { + bool keep = true; + if (r.is_s() && (r.n == EXEC || r.n == EXEC + 1)) { + keep = false; + } else if (r.is_v()) { + keep = contains(ops, r) || guarded; + } + if (keep) out.push_back(v); + } + return out; +} + +std::optional<Value> value(const Inst& inst, const Operand& op) { + if (op.kind == Operand::Kind::Scalar && op.code != NULL_CODE) return inst.read(Reg::S(op.code)); + if (op.kind == Operand::Kind::Vector) return inst.read(Reg::V(op.reg)); + return std::nullopt; +} + +// The sources of a scalar or unmodified vector operation. +std::vector<Arg> args(const Inst& inst) { + const std::vector<Operand>* src = nullptr; + if (const auto* s = std::get_if<gfx10::Sop>(&inst.fields)) { + src = &s->src; + } else if (const auto* v = std::get_if<Valu>(&inst.fields); + v && !v->dpp && !v->sdwa && v->abs == 0 && v->neg == 0 && !v->clamp && v->omod == 0) { + src = &v->src; + } + std::vector<Arg> out; + if (!src) return out; + for (const Operand& o : *src) { + if (const auto x = value(inst, o)) { + out.push_back(Arg::val(*x)); + } else if (o.kind == Operand::Kind::Const) { + const auto c = wave::detail::inline_constant(o.code); // resource::inline + out.push_back(c ? Arg::konst(*c) : Arg::other()); + } else if (o.kind == Operand::Kind::Literal) { + out.push_back(Arg::konst(o.literal)); + } else { + out.push_back(Arg::other()); + } + } + return out; +} + +// The other source of a two-source operation that reads `a`. +std::optional<Arg> other(const Inst& inst, Value a) { + const auto s = args(inst); + if (s.size() != 2) return std::nullopt; + if (s[0].kind == Arg::Val && s[0].v == a) return s[1]; + if (s[1].kind == Arg::Val && s[1].v == a) return s[0]; + return std::nullopt; +} + +// The scalar (not SCC) or vector dword an instruction writes, if it writes one. +std::optional<Value> result(const Inst& inst) { + std::optional<Value> one; + std::size_t count = 0; + for (const auto& w : inst.writes) { + if (w.first == Reg::Scc) continue; + if (++count == 1) one = w.second; + if (count == 2) return std::nullopt; + } + return one; +} + +// The same test as `wave_local`'s and `Lower::inst`'s `effect`, and the messages a program sends. +bool effect(const Inst& inst) { + const std::string_view name = inst.name(); + const bool ds = std::holds_alternative<gfx10::Ds>(inst.fields); + return std::holds_alternative<gfx10::Exp>(inst.fields) || + (std::holds_alternative<gfx10::Flat>(inst.fields) && !name.starts_with("global_load_")) || + name.find("store") != std::string_view::npos || name.find("atomic") != std::string_view::npos || + (ds && !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || + name.find("permute") != std::string_view::npos)) || + name == "s_barrier" || name == "s_sendmsg" || name == "s_sendmsghalt"; +} + +bool contains_text(std::string_view s, std::string_view part) { return s.find(part) != std::string_view::npos; } + +class Ctx { +public: + Ctx(const Program& program, const Structured& structured) : p(program), st(structured) { + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& block = p.blocks[b]; + for (std::size_t k = 0; k < block.phis.size(); ++k) { + for (Value a : block.phis[k].args) users[a].push_back(User{User::Phi, b, k}); + } + for (std::size_t i = 0; i < block.insts.size(); ++i) { + for (Value v : used(p, st, b, i)) { + users[v].push_back(User{User::Inst, b, i}); + live.insert(v); + } + for (const auto& w : block.insts[i].writes) def.insert_or_assign(w.second, Site{b, i}); + } + } + // through joins + bool changed = true; + while (changed) { + changed = false; + for (const auto& block : p.blocks) { + for (const auto& phi : block.phis) { + if (live.contains(phi.value)) { + for (Value a : phi.args) changed |= live.insert(a).second; + } + } + } + } + const std::vector<std::size_t> order = ir::reverse_postorder(p.blocks); + std::vector<std::size_t> index(p.blocks.size(), SIZE_MAX); + for (std::size_t n = 0; n < order.size(); ++n) index.at(order[n]) = n; + idom = ir::idoms(p.blocks, order, index); + sections.reserve(p.blocks.size()); + for (std::size_t b = 0; b < p.blocks.size(); ++b) sections.push_back(wave::sections(p, b)); + } + + const Program& p; + const Structured& st; + // User vectors preserve insertion order. The lookup tables are used only by key. + std::map<Value, std::vector<User>> users; + // The instruction writing each value. + std::map<Value, Site> def; + // Values an instruction reads, directly or through joins. + std::set<Value> live; + std::vector<std::size_t> idom; + std::vector<std::unordered_map<std::size_t, wave::Section>> sections; + + const Inst& inst(Site u) const { return p.blocks.at(u.first).insts.at(u.second); } + + std::size_t at(Site u) const { return inst(u).machine.offset; } + + const std::vector<User>* users_of(Value v) const { + const auto it = users.find(v); + return it == users.end() ? nullptr : &it->second; + } + + // Whether block `a` dominates block `b`. + bool dominates(std::size_t a, std::size_t b) const { + while (true) { + if (a == b) return true; + const std::size_t d = b < idom.size() ? idom[b] : SIZE_MAX; + if (d == b || d == SIZE_MAX) return false; + b = d; + } + } + + std::vector<Site> readers(Value v) const { + std::vector<Site> out; + if (const auto* us = users_of(v)) { + for (const User& u : *us) { + if (u.kind == User::Inst) out.emplace_back(u.b, u.i); + } + } + std::sort(out.begin(), out.end()); + out.erase(std::unique(out.begin(), out.end()), out.end()); + return out; + } + + // The joins reading `v` whose value something reads. + std::vector<Site> joins(Value v) const { + std::vector<Site> out; + if (const auto* us = users_of(v)) { + for (const User& u : *us) { + if (u.kind == User::Phi && live.contains(p.blocks.at(u.b).phis.at(u.i).value)) out.emplace_back(u.b, u.i); + } + } + std::sort(out.begin(), out.end()); + out.erase(std::unique(out.begin(), out.end()), out.end()); + return out; + } + + // The loop of header `h`: the blocks that reach one of its back edges without passing it. + std::vector<bool> natural_loop(std::size_t h) const { + std::vector<bool> inside(p.blocks.size(), false); + std::vector<std::size_t> work; + for (std::size_t q : p.blocks.at(h).preds) { + if (dominates(h, q)) work.push_back(q); + } + if (work.empty()) return inside; + inside.at(h) = true; + while (!work.empty()) { + const std::size_t b = work.back(); + work.pop_back(); + if (inside.at(b)) continue; + inside[b] = true; + const auto& preds = p.blocks.at(b).preds; + work.insert(work.end(), preds.begin(), preds.end()); + } + return inside; + } + + // Whether `b` holds only in lanes where `a` does. + bool implied(Bool b, const Atom& a, std::unordered_map<Bool, bool, BoolHash>& memo) const { + if (b == Bool::False) return true; + if (const auto it = memo.find(b); it != memo.end()) return it->second; + bool r = false; + const auto node = st.bools.node(b); + if (!node) { + r = false; + } else if (std::get<0>(*node) == a) { + r = std::get<1>(*node) == Bool::False; + } else { + r = implied(std::get<1>(*node), a, memo) && implied(std::get<2>(*node), a, memo); + } + memo.insert_or_assign(b, r); + return r; + } + + struct BranchOn { + Site u; + std::size_t set; + std::size_t clear; + }; + + // The conditional branch reading `scc`, as (its place, the block it goes to when SCC is set, + // the other one). + std::optional<BranchOn> branch(Value scc) const { + const auto rs = readers(scc); + if (rs.size() != 1) return std::nullopt; + const Site u = rs[0]; + const Exit& ex = p.blocks.at(u.first).exit; + if (ex.kind != Exit::Kind::Branch) return std::nullopt; + if (u.second + 1 != p.blocks.at(u.first).insts.size()) return std::nullopt; + const std::string_view name = inst(u).name(); + if (name == "s_cbranch_scc1") return BranchOn{u, ex.taken, ex.not_taken}; + if (name == "s_cbranch_scc0") return BranchOn{u, ex.not_taken, ex.taken}; + return std::nullopt; + } + + // One wave OR `t` of `x` over the lanes of `mask`, left by a section of block `sb`: the VGPR + // values its loop keeps alike, or where and why it is not such a loop. + std::variant<std::vector<Value>, Err> site(std::size_t sb, Value t, Value x, Value mask) const; +}; + +std::variant<std::vector<Value>, Err> Ctx::site(std::size_t sb, Value t, Value x, Value mask) const { + const std::size_t n = p.blocks.size(); + const std::size_t here = p.blocks.at(sb).offset; + auto is_mask = [&](Value v) { return st.masks.contains(v) || st.highs.contains(v); }; + // every lane that runs the section is one of the lanes ORed + const auto mit = st.masks.find(mask); + if (mit == st.masks.end()) return Err{here, MASK}; + const Bool mb = mit->second; + if (st.bools.meet({{st.reach.at(sb), true}, {mb, false}})) return Err{here, MASK}; + // Bits still to visit and steps executed by the loop. + std::set<Value> rem{t}; + std::set<Site> pattern; + std::vector<Value> alike; + // an unguarded copy + auto copy = [&](Site u) -> std::optional<Value> { + const Inst& i = inst(u); + const std::string_view name = i.name(); + if ((name == "v_mov_b32" || name == "s_mov_b32") && args(i).size() == 1 && + !st.guards.at(u.first).at(u.second).has_value()) { + return result(i); + } + return std::nullopt; + }; + std::vector<Value> init{t}; + // (SCC, whether it is set when the OR is empty) + std::optional<std::pair<Value, bool>> zero; + for (const Site u : readers(t)) { + const Inst& i = inst(u); + const std::string_view name = i.name(); + std::optional<Value> scc; + if (is_cmp_scalar(name) && other(i, t) == Arg::konst(0) && !zero && (scc = i.write(Reg::Scc))) { + zero = std::pair{*scc, contains_text(name, "_eq_")}; + rem.insert(*scc); + } else if (const auto w = copy(u)) { + init.push_back(*w); + rem.insert(*w); + if (i.writes.at(0).first.is_v()) alike.push_back(*w); + } else { + return Err{at(u), USED}; + } + pattern.insert(u); + } + // the loop's join of them + std::optional<Site> join; + for (const Value v : init) { + if (v != t) { + const auto rs = readers(v); + if (!rs.empty()) return Err{at(rs[0]), USED}; + } + for (const Site j : joins(v)) { + if (join && *join != j) return Err{p.blocks.at(j.first).offset, USED}; + join = j; + } + } + if (!join) return Err{here, NO_LOOP}; + const std::size_t h = join->first; + const std::size_t k = join->second; + const ir::Phi& phi = p.blocks.at(h).phis.at(k); + const Value r = phi.value; + rem.insert(r); + const std::size_t head = p.blocks.at(h).offset; + const std::vector<bool> lp = natural_loop(h); + if (!lp[h] || lp.at(sb)) return Err{head, NO_LOOP}; + // the set as a scalar: the first lane's copy of it + Value cur = r; + if (phi.reg.is_v()) { + alike.push_back(r); + const auto rs = readers(r); + if (rs.size() != 1) return Err{head, USED}; + const Site u = rs[0]; + const Inst& i = inst(u); + if (i.name() != "v_readfirstlane_b32" || args(i).size() != 1 || !lp.at(u.first)) return Err{at(u), USED}; + pattern.insert(u); + const auto c = result(i); + if (!c) return Err{at(u), SHAPE}; + if (!joins(r).empty()) return Err{head, USED}; + cur = *c; + } + rem.insert(cur); + // its lowest bit, the set without it, the tests for "that was the last" + std::optional<Value> idx; + std::optional<std::pair<Value, Value>> next; + // (SCC, whether it is set while bits remain) + std::vector<std::pair<Value, bool>> more; + std::vector<Value> bits; + for (const Site u : readers(cur)) { + const Inst& i = inst(u); + const std::string_view name = i.name(); + if (!lp.at(u.first)) return Err{at(u), USED}; + const std::vector<Arg> a = args(i); + if (name == "s_ff1_i32_b32" && a.size() == 1 && a[0].kind == Arg::Val && !idx) { + idx = result(i); + } else if ((name == "s_xor_b32" || (name == "s_andn2_b32" && a.size() == 2 && a[0].kind == Arg::Val && + a[1].kind == Arg::Val)) && + !next) { + Value bit{}; + if (name == "s_andn2_b32") { + // ("s_andn2_b32", [Arg::Val(c), Arg::Val(b)]) if *c == cur && *b != cur + if (!(a[0].v == cur && a[1].v != cur)) return Err{at(u), USED}; + bit = a[1].v; + } else { + const auto o = other(i, cur); + if (!(o && o->kind == Arg::Val && o->v != cur)) return Err{at(u), USED}; + bit = o->v; + } + const auto w = result(i); + if (!w) return Err{at(u), SHAPE}; + next = std::pair{*w, bit}; + bits.push_back(bit); + if (const auto scc = i.write(Reg::Scc)) { + more.emplace_back(*scc, true); + rem.insert(*scc); + } + } else if (is_cmp_scalar(name)) { + const auto o = other(i, cur); + const auto scc = i.write(Reg::Scc); + if (!(o && o->kind == Arg::Val && scc)) return Err{at(u), USED}; + bits.push_back(o->v); + more.emplace_back(*scc, contains_text(name, "_lg_")); + rem.insert(*scc); + } else { + return Err{at(u), USED}; + } + pattern.insert(u); + } + if (cur != r && !joins(cur).empty()) return Err{head, USED}; + if (!idx || !next) return Err{head, SHAPE}; + const Value nx = next->first; + const Value bit = next->second; + if (std::any_of(bits.begin(), bits.end(), [&](Value b) { return b != bit; })) return Err{head, SHAPE}; + // the bit: 1 shifted by the lowest set bit's number (a shift takes five bits of it) + auto made = [&](Value v) -> std::optional<Site> { + const auto it = def.find(v); + if (it == def.end()) return std::nullopt; + return it->second; + }; + std::optional<Value> shifted; + if (const auto u = made(bit); u && inst(*u).name() == "s_lshl_b32" && lp.at(u->first)) { + const auto a = args(inst(*u)); + if (a.size() == 2 && a[0] == Arg::konst(1) && a[1].kind == Arg::Val) shifted = a[1].v; + } + bool by_idx = false; + if (shifted) { + const Value sh = *shifted; + if (sh == *idx) { + by_idx = true; + } else if (const auto u = made(sh)) { + const Inst& i = inst(*u); + by_idx = i.name() == "s_and_b32" && other(i, *idx) == Arg::konst(31); + } + } + if (!by_idx) return Err{head, SHAPE}; + // the set less the bit: back into the join, or tested for empty + rem.insert(nx); + std::vector<Value> nexts{nx}; + for (const Site u : readers(nx)) { + const Inst& i = inst(u); + const std::string_view name = i.name(); + std::optional<Value> scc; + if (is_cmp_scalar(name) && other(i, nx) == Arg::konst(0) && (scc = i.write(Reg::Scc))) { + more.emplace_back(*scc, contains_text(name, "_lg_")); + rem.insert(*scc); + } else if (const auto w = copy(u)) { + nexts.push_back(*w); + rem.insert(*w); + if (i.writes.at(0).first.is_v()) alike.push_back(*w); + } else { + return Err{at(u), USED}; + } + pattern.insert(u); + } + for (const Value v : nexts) { + if (v != nx) { + const auto rs = readers(v); + if (!rs.empty()) return Err{at(rs[0]), USED}; + } + const auto js = joins(v); + if (std::any_of(js.begin(), js.end(), [&](Site j) { return j != Site{h, k}; })) return Err{head, USED}; + } + { + const auto& preds = p.blocks.at(h).preds; + const std::size_t m = std::min(preds.size(), phi.args.size()); + for (std::size_t e = 0; e < m; ++e) { + const bool ok = lp.at(preds[e]) ? contains(nexts, phi.args[e]) : contains(init, phi.args[e]); + if (!ok) return Err{head, SHAPE}; + } + } + // the loop goes on while bits remain and is left when none does + std::set<std::size_t> leaves; + for (const auto& [scc, set_while_more] : more) { + if (!joins(scc).empty()) return Err{head, USED}; + if (readers(scc).empty()) continue; + const auto br = branch(scc); + if (!br) return Err{head, USED}; + const std::size_t on = set_while_more ? br->set : br->clear; + const std::size_t out = set_while_more ? br->clear : br->set; + if (!lp.at(br->u.first) || !lp.at(on) || lp.at(out)) return Err{at(br->u), SHAPE}; + leaves.insert(br->u.first); + pattern.insert(br->u); + } + if (leaves.empty()) return Err{head, SHAPE}; + // "no bit at all" skips the loop; what lies between that test and the loop runs only when + // there is one + std::vector<bool> pre(n, false); + if (zero) { + const auto [scc, set_when_empty] = *zero; + if (!joins(scc).empty()) return Err{here, USED}; + if (!readers(scc).empty()) { + const auto br = branch(scc); + if (!br) return Err{here, USED}; + const Site u = br->u; + const std::size_t none = set_when_empty ? br->set : br->clear; + const std::size_t some = set_when_empty ? br->clear : br->set; + if (none == some || lp.at(u.first)) return Err{at(u), SHAPE}; + if (some != h) { + const auto& sp = p.blocks.at(some).preds; + if (!(sp.size() == 1 && sp[0] == u.first) || !dominates(some, h)) return Err{at(u), SHAPE}; + for (std::size_t b = 0; b < n; ++b) pre[b] = dominates(some, b) && !dominates(h, b); + for (std::size_t b = 0; b < n; ++b) { + if (!pre[b]) continue; + const Exit& e = p.blocks[b].exit; + bool inside = false; + if (e.kind != Exit::Kind::End && e.kind != Exit::Kind::Indirect) { + const auto succ = e.successors(); + inside = std::all_of(succ.begin(), succ.end(), [&](std::size_t s) { return pre.at(s) || s == h; }); + } + if (!inside) return Err{p.blocks[b].offset, SHAPE}; + } + } + pattern.insert(u); + } + } + // ---- the lane's test of its own bit ---- + // (the atom of the compare, its block, its index) + struct Test { + Atom atom; + std::size_t b; + std::size_t i; + }; + std::vector<Test> tests; + for (const Site u : readers(bit)) { + const Inst& i = inst(u); + if (i.name() != "v_and_b32" || other(i, bit) != Arg::val(x) || st.guards.at(u.first).at(u.second).has_value()) { + continue; + } + const auto y = result(i); + if (!y) continue; + for (const Site c : readers(*y)) { + const Inst& ci = inst(c); + const std::string_view cn = ci.name(); + const bool ne = cn == "v_cmp_ne_u32" || cn == "v_cmpx_ne_u32" || cn == "v_cmp_lg_u32" || + cn == "v_cmpx_lg_u32" || cn == "v_cmp_ne_i32" || cn == "v_cmpx_ne_i32" || + cn == "v_cmp_lg_i32" || cn == "v_cmpx_lg_i32"; + if (ne && other(ci, *y) == Arg::konst(0) && lp.at(c.first)) { + for (const auto& w : ci.writes) tests.push_back(Test{Atom::Lane(w.second), c.first, c.second}); + } + } + } + if (tests.empty()) return Err{head, TEST}; + std::vector<std::unordered_map<Bool, bool, BoolHash>> memo(tests.size()); + // what a lane only reaches with its own bit set, in the round of that test + std::vector<bool> body_block(n, false); + for (std::size_t b = 0; b < n; ++b) { + if (!lp[b]) continue; + bool any = false; + for (std::size_t j = 0; j < tests.size() && !any; ++j) { + const Test& tj = tests[j]; + any = b != tj.b && dominates(tj.b, b) && implied(st.reach.at(b), tj.atom, memo[j]); + } + body_block[b] = any; + } + auto body_inst = [&](std::size_t b, std::size_t i) { + if (body_block[b]) return true; + if (!lp[b]) return false; + const auto& g = st.guards.at(b).at(i); + if (!g) return false; + for (std::size_t j = 0; j < tests.size(); ++j) { + const Test& tj = tests[j]; + if (((b == tj.b && i > tj.i) || (b != tj.b && dominates(tj.b, b))) && implied(*g, tj.atom, memo[j])) { + return true; + } + } + return false; + }; + // ---- a round outside the body leaves nothing behind ---- + for (std::size_t b = 0; b < n; ++b) { + if (!(lp[b] || pre[b])) continue; + const auto& insts = p.blocks[b].insts; + for (std::size_t i = 0; i < insts.size(); ++i) { + const Inst& in = insts[i]; + if (lp[b] && body_inst(b, i)) continue; + const Site u{b, i}; + for (const auto& [reg, w] : in.writes) { + if (rem.contains(w) || is_mask(w) || (reg.is_s() && (reg.n == EXEC || reg.n == EXEC + 1))) continue; + if (const auto* us = users_of(w)) { + for (const User& user : *us) { + bool stays = false; + if (user.kind == User::Inst) { + stays = lp.at(user.b) || pre.at(user.b); + } else { + stays = body_block.at(user.b) || !live.contains(p.blocks.at(user.b).phis.at(user.i).value); + } + if (!stays) return Err{at(u), LEAVES}; + } + } + } + if (pattern.contains(u)) continue; + if (effect(in)) return Err{at(u), EFFECT}; + const std::string_view name = in.name(); + bool cross = name.starts_with("ds_swizzle") || contains_text(name, "permute") || + name.starts_with("v_mbcnt") || contains_text(name, "lane"); + if (!cross) { + const auto* v = std::get_if<Valu>(&in.fields); + cross = v && v->dpp.has_value(); + } + if (!cross) cross = lower::reads_mask_as_data(st, in); + if (!cross) { + for (const auto& [s, sec] : sections.at(b)) { + if (i >= s && i <= sec.end) { + cross = true; + break; + } + } + } + if (cross) return Err{at(u), CROSS}; + const auto uv = used(p, st, b, i); + if (std::any_of(uv.begin(), uv.end(), [&](Value v) { return rem.contains(v); })) return Err{at(u), USED}; + } + // left only by "no bits left"; the body may leave it as it likes + if (lp[b] && !body_block[b]) { + const Exit& e = p.blocks[b].exit; + bool ok = false; + if (e.kind != Exit::Kind::End && e.kind != Exit::Kind::Indirect) { + const auto succ = e.successors(); + ok = leaves.contains(b) || std::all_of(succ.begin(), succ.end(), [&](std::size_t s) { return lp.at(s); }); + } + if (!ok) return Err{p.blocks[b].offset, EXIT}; + } + } + // ---- no mask that depends on the test outlives its round ---- + std::unordered_set<Atom, structure::AtomHash> dep; + for (const Test& tt : tests) dep.insert(tt.atom); + auto depends = [&](Bool e) { + const auto sup = st.bools.support(e); + return std::any_of(sup.begin(), sup.end(), [&](const Atom& a) { return dep.contains(a); }); + }; + bool changed = true; + while (changed) { + changed = false; + // (a fixed point: the order of the map does not change it) + for (const auto& [id, edges] : st.phi_masks) { + if (!dep.contains(Atom::Phi(id)) && std::any_of(edges.begin(), edges.end(), depends)) { + dep.insert(Atom::Phi(id)); + changed = true; + } + } + } + std::unordered_map<Bool, bool, BoolHash> seen; + auto tainted = [&](Bool b) -> bool { + if (const auto it = seen.find(b); it != seen.end()) return it->second; + const bool r = depends(b); + seen.emplace(b, r); + return r; + }; + for (std::size_t b = 0; b < n; ++b) { + if (lp[b] && std::any_of(tests.begin(), tests.end(), [&](const Test& tt) { return dominates(tt.b, b); })) { + continue; + } + bool stale = false; + for (const auto& g : st.guards.at(b)) { + if (g && tainted(*g)) { + stale = true; + break; + } + } + if (!stale) { + const LaneExit& e = st.exits.at(b); + stale = e.kind == LaneExit::Kind::Branch && tainted(e.when); + } + if (stale) return Err{p.blocks[b].offset, STALE}; + } + // (any mask found gives the same error: the order of the map does not matter) + for (const auto& [v, m] : st.masks) { + if (!tainted(m)) continue; + if (const auto* us = users_of(v)) { + for (const User& user : *us) { + bool outside = false; + if (user.kind == User::Inst) { + outside = !lp.at(user.b); + } else { + outside = !lp.at(user.b) && live.contains(p.blocks.at(user.b).phis.at(user.i).value); + } + if (outside) return Err{head, STALE}; + } + } + } + return alike; +} + +} // namespace + +OwnBits find(const Program& p, const Structured& st, bool why) { + OwnBits out; + std::optional<Ctx> ctx; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto sections = wave::sections(p, b); + std::vector<std::size_t> starts; + starts.reserve(sections.size()); + for (const auto& [s, _] : sections) starts.push_back(s); + std::sort(starts.begin(), starts.end()); + for (const std::size_t s : starts) { + const wave::Section& sec = sections.at(s); + std::vector<std::pair<Value, Shape>> left(sec.shapes.begin(), sec.shapes.end()); + std::sort(left.begin(), left.end(), [](const auto& l, const auto& r) { return l.first.n < r.first.n; }); + for (const auto& [t, shape] : left) { + if (!(shape.kind == Shape::Active && shape.op == Op::Or && shape.k == 0)) continue; + const Value x = shape.a; + const Value mask = shape.b; + if (!ctx) ctx.emplace(p, st); + // (values only the section itself reads are not results) + auto inside = [&](const User& u) { return u.kind == User::Inst && u.b == b && u.i > s && u.i < sec.end; }; + const auto* us = ctx->users_of(t); + if (!us || std::all_of(us->begin(), us->end(), inside)) continue; + auto r = ctx->site(b, t, x, mask); + if (auto* alike = std::get_if<std::vector<Value>>(&r)) { + out.totals.insert(t); + out.alike.insert(alike->begin(), alike->end()); + } else if (why) { + const Err& e = std::get<Err>(r); + std::fprintf(stderr, + "WAVE64-OWN-BITS the wave OR at 0x%zx: not a loop over the lanes' own bits at 0x%zx: %s\n", + p.blocks[b].insts.at(s).machine.offset, e.offset, e.what); + } + } + } + } + return out; +} + +} // namespace x2w::vs::own_bits diff --git a/src/x2w_shader/emit/own_bits.h b/src/x2w_shader/emit/own_bits.h new file mode 100644 index 0000000000..6d83bcc310 --- /dev/null +++ b/src/x2w_shader/emit/own_bits.h @@ -0,0 +1,27 @@ +#pragma once + +// A wave OR whose bits a loop then visits one at a time, each lane testing its own bit: a host wave may +// take over its own lanes wherever they stand. X2W_SHADERCFG_WAVE_OWN_BITS=0 turns this off. + +#include <set> + +#include "x2w_shader/ir.h" + +namespace x2w::vs::structure { +struct Structured; +} + +namespace x2w::vs::own_bits { + +// Sets of values established by find. +struct OwnBits { + // Wave ORs (the values their sections leave) a host wave may take over its own lanes. + std::set<ir::Value> totals; + // VGPR values of those loops that every lane of a host wave holds alike (the bits still to + // visit): a first-lane read of one is the lane's own value. + std::set<ir::Value> alike; +}; + +OwnBits find(const ir::Program& p, const structure::Structured& st, bool why); + +} // namespace x2w::vs::own_bits diff --git a/src/x2w_shader/emit/rect.cpp b/src/x2w_shader/emit/rect.cpp new file mode 100644 index 0000000000..1b6d196f55 --- /dev/null +++ b/src/x2w_shader/emit/rect.cpp @@ -0,0 +1,250 @@ +// the geometry shader that completes the console's rectangle lists (list topology 17, pipeline topology +// type 19). +// +// A rectangle comes as three vertices, three corners of a screen-aligned rectangle; the hardware +// draws the whole rectangle and continues every vertex shader output linearly into the fourth +// corner. The host has no such topology: the draw goes out as a triangle list with this shader +// behind the translated vertex shader, so vertex counts, vertex numbers, indices and indirect +// arguments stay the title's, and each rectangle arrives here as one triangle. +// +// Which vertex is the corner between the other two varies: the corner is the vertex that shares x +// with one of the others and y with the other; the fourth vertex lies opposite it, a + b - corner +// for the position and every float output. That holds for three vertices with one positive w; +// three that differ in w, or are not such corners, stay the triangle they make. +// +// Flat values are the first vertex's: both triangles start with it, which is the vertex the host +// takes a flat input from, and the fourth vertex's integer outputs are the first vertex's. +// +// shortcut: that the console takes a rectangle's flat values from its first vertex follows from +// the hardware's provoking-vertex setting for triangles; it is not measured on a rectangle. + +#include "x2w_shader/emit/rect.h" + +#include <algorithm> + +#include "x2w_shader/dxbc.h" +#include "x2w_shader/emit/shader.h" +#include "x2w_shader/emit/signature.h" +#include "x2w_shader/error.h" + +namespace x2w::vs { + +namespace { + +using bitcode::Attr; +using bitcode::Bin; +using bitcode::Term; +using bitcode::V; +namespace pred = bitcode::pred; +using container::SigElement; +using shader::Geometry; +using shader::Shader; + +// Vertices emitted per rectangle: two triangles. +constexpr std::uint32_t VERTICES = 6; + +// The scalars a geometry shader may emit per invocation (vertices times output components). +constexpr std::uint32_t MAX_SCALARS = 1024; + +// Column col of input id at vertex `vertex` of the triangle. +V load(Shader& s, std::size_t id, std::uint8_t col, std::uint32_t vertex) { + const bool f = s.inputs[id].comp == 9; + const char* name = f ? "loadInput.f32" : "loadInput.i32"; + bitcode::Ty ty = f ? s.t.f32 : s.t.i32; + const V args[4] = {s.m.i32(std::uint32_t(id)), s.m.i32(0), s.m.i8(col), s.m.i32(vertex)}; + std::size_t entry = s.entry; + return s.op(entry, name, Attr::ReadNone, ty, 4, args); +} + +// Two floats are equal. +V same(Shader& s, V a, V b) { return s.m.cmp(s.entry, pred::OEQ, a, b); } +V both(Shader& s, V a, V b) { return s.m.bin(s.entry, Bin::And, a, b); } +V either(Shader& s, V a, V b) { return s.m.bin(s.entry, Bin::Or, a, b); } +V not_(Shader& s, V a) { + std::size_t entry = s.entry; + V on = s.m.bool_(true); + return s.m.bin(entry, Bin::Xor, a, on); +} + +} // namespace + +std::vector<std::uint8_t> rect_build(std::vector<SigElement> outputs, std::span<const SigElement> ps_inputs) { + auto unsupported = [](const char* what) { return ShaderError::unsupported(0, what); }; + if (std::any_of(outputs.begin(), outputs.end(), [](const SigElement& e) { return !e.row; })) + throw unsupported("a rectangle list output without a register"); + std::size_t position = outputs.size(); + for (std::size_t i = 0; i < outputs.size(); ++i) { + const SigElement& e = outputs[i]; + if (e.kind == 3 && e.comp == 9 && e.cols == 4) { + position = i; + break; + } + } + if (position == outputs.size()) throw unsupported("a rectangle list without a four-component position"); + for (SigElement& e : outputs) { + // Interpolation as emit_program declares a vertex shader's outputs; a geometry shader's + // inputs carry the same modes. + if (e.kind == 3) + e.interp = 4; + else if ((e.kind == 0 || e.kind == 6 || e.kind == 7) && e.comp == 9) + e.interp = 2; + else if (e.kind == 0) + e.interp = 1; + else + e.interp = 0; + e.usage = std::uint8_t((1u << e.cols) - 1); + } + Shader s(false); + s.geometry = Geometry{VERTICES}; + s.inputs = outputs; + // The primitive id the pixel shader declares, as one more output. + const SigElement* wanted = nullptr; + for (const SigElement& e : ps_inputs) + if (e.kind == 10 && e.row) { + wanted = &e; + break; + } + if (wanted && std::any_of(outputs.begin(), outputs.end(), [](const SigElement& o) { return o.kind == 10; })) + wanted = nullptr; + std::optional<std::size_t> primitive; + if (wanted) { + const SigElement& e = *wanted; + // Alone in its columns, and in a row of constant elements. + const bool clash = std::any_of(outputs.begin(), outputs.end(), [&](const SigElement& o) { + const bool overlap = o.col < e.col + e.cols && e.col < o.col + o.cols; + return o.row == e.row && (o.interp != 1 || overlap); + }); + if (clash) throw unsupported("a rectangle list whose primitive id shares a register with a vertex output"); + SigElement p = e; + p.interp = 1; + p.usage = std::uint8_t((1u << e.cols) - 1); + outputs.push_back(std::move(p)); + primitive = outputs.size() - 1; + } + std::uint32_t scalars = 0; + for (const SigElement& e : outputs) scalars += e.cols; + if (scalars * VERTICES > MAX_SCALARS) + throw unsupported("a rectangle list with more output components than a geometry shader emits"); + s.outputs = outputs; + const std::size_t b = s.entry; + + // Every input of the three vertices: [element][column][vertex]. + using V3 = std::array<V, 3>; + std::vector<std::vector<V3>> corners; + for (std::size_t id = 0; id < s.inputs.size(); ++id) { + std::vector<V3> columns; + for (std::uint8_t col = 0; col < s.inputs[id].cols; ++col) { + V3 c; + for (std::uint32_t vertex = 0; vertex < 3; ++vertex) c[vertex] = load(s, id, col, vertex); + columns.push_back(c); + } + corners.push_back(std::move(columns)); + } + + // One positive w, and no two vertices in one place. + const V3 x = corners[position][0], y = corners[position][1], w = corners[position][3]; + V zero = s.m.f32(0); + V plain = s.m.cmp(b, pred::OGT, w[0], zero); + for (std::size_t k = 1; k < 3; ++k) { + V one_w = same(s, w[k], w[0]); + plain = both(s, plain, one_w); + } + for (auto [i, j] : {std::pair{0, 1}, std::pair{0, 2}, std::pair{1, 2}}) { + V same_x = same(s, x[i], x[j]); + V same_y = same(s, y[i], y[j]); + V together = both(s, same_x, same_y); + V apart = not_(s, together); + plain = both(s, plain, apart); + } + // corner[i]: vertex i is the corner between the other two (the first that shares x with one + // of them and y with the other). + std::vector<V> corner; + for (std::size_t i = 0; i < 3; ++i) { + const std::size_t a = (i + 1) % 3, c = (i + 2) % 3; + V xa = same(s, x[i], x[a]); + V yc = same(s, y[i], y[c]); + V xc = same(s, x[i], x[c]); + V ya = same(s, y[i], y[a]); + V one = both(s, xa, yc); + V other = both(s, xc, ya); + V shares = either(s, one, other); + V here = both(s, shares, plain); + for (V found : corner) { + V earlier = not_(s, found); + here = both(s, here, earlier); + } + corner.push_back(here); + } + + // What the six emitted vertices carry: [element][column][vertex]. + using V6 = std::array<V, 6>; + std::vector<std::vector<V6>> emitted; + for (std::size_t id = 0; id < corners.size(); ++id) { + const bool fl = s.inputs[id].comp == 9; + std::vector<V6> out; + for (const V3& pc : corners[id]) { + const V p0 = pc[0], p1 = pc[1], p2 = pc[2]; + // The fourth vertex: a + b - corner. Integers (flat), and three vertices without a + // corner, keep the first vertex's value; the second triangle of the latter is then + // empty. + V fourth = p0; + if (fl) { + const std::array<std::array<V, 3>, 3> sides = {{{p1, p2, p0}, {p2, p0, p1}, {p0, p1, p2}}}; + for (std::size_t k = 0; k < 3; ++k) { + V sum = s.m.bin(b, Bin::Add, sides[k][0], sides[k][1]); + V opposite = s.m.bin(b, Bin::Sub, sum, sides[k][2]); + fourth = s.m.select(b, corner[k], opposite, fourth); + } + } + // Corner first: (v0, v1, v3), (v0, v3, v2). Second: (v0, v1, v2), (v0, v2, v3). + // Third: (v0, v1, v2), (v0, v3, v1). + V third = s.m.select(b, corner[0], fourth, p2); + V fifth = s.m.select(b, corner[1], p2, fourth); + V sixth = s.m.select(b, corner[0], p2, p1); + sixth = s.m.select(b, corner[1], fourth, sixth); + out.push_back(V6{p0, p1, third, p0, fifth, sixth}); + } + emitted.push_back(std::move(out)); + } + + // The rectangle's number: the triangle's, three vertices a rectangle. + std::optional<std::pair<std::size_t, V>> number; + if (primitive) { + V n = s.op(b, "primitiveID.i32", Attr::ReadNone, s.t.i32, 108, std::span<const V>()); + number = std::make_pair(*primitive, n); + } + V stream = s.m.i8(0); + for (std::size_t vertex = 0; vertex < VERTICES; ++vertex) { + for (std::size_t id = 0; id < emitted.size(); ++id) { + const char* name = s.outputs[id].comp == 9 ? "storeOutput.f32" : "storeOutput.i32"; + for (std::size_t col = 0; col < emitted[id].size(); ++col) { + const V args[4] = {s.m.i32(std::uint32_t(id)), s.m.i32(0), s.m.i8(std::uint8_t(col)), + emitted[id][col][vertex]}; + s.op(b, name, Attr::NoUnwind, s.t.void_, 5, args); + } + } + if (number) { + const V args[4] = {s.m.i32(std::uint32_t(number->first)), s.m.i32(0), s.m.i8(0), number->second}; + s.op(b, "storeOutput.i32", Attr::NoUnwind, s.t.void_, 5, args); + } + s.op(b, "emitStream", Attr::NoUnwind, s.t.void_, 97, {stream}); + // The strip ends after the first triangle. + if (vertex == 2) s.op(b, "cutStream", Attr::NoUnwind, s.t.void_, 98, {stream}); + } + s.m.terminate(b, Term::ret()); + return s.finish(); +} + +std::vector<std::uint8_t> rect_list_gs(std::span<const std::uint8_t> vs, std::optional<std::span<const std::uint8_t>> ps) { + auto sig = [](std::span<const std::uint8_t> dxil, dxbc::FourCC fourcc) -> std::vector<SigElement> { + const dxbc::Container c = dxbc::Container::parse(dxil); + if (const dxbc::Part* part = c.part(fourcc)) return signature(part->data); + return {}; + }; + std::vector<SigElement> outputs = sig(vs, dxbc::FourCC::OSG1); + std::vector<SigElement> wanted; + if (ps) wanted = sig(*ps, dxbc::FourCC::ISG1); + return rect_build(std::move(outputs), wanted); +} + +} // namespace x2w::vs diff --git a/src/x2w_shader/emit/rect.h b/src/x2w_shader/emit/rect.h new file mode 100644 index 0000000000..15975ad8dc --- /dev/null +++ b/src/x2w_shader/emit/rect.h @@ -0,0 +1,26 @@ +#pragma once + +// The geometry shader that completes the console's rectangle lists (rect.cpp). + +#include <cstdint> +#include <optional> +#include <span> +#include <vector> + +#include "x2w_shader/emit/container.h" + +namespace x2w::vs { + +// The geometry shader (a DXIL container) for rectangle lists drawn with the translated vertex +// shader `vs` and, if the pipeline has one, the translated pixel shader `ps` (both as +// HostShader::dxil). Its inputs and outputs are the vertex shader's outputs, register for +// register, so it links with both. A pixel shader that declares a primitive id gets the +// rectangle's number. Throws ShaderError. +std::vector<std::uint8_t> rect_list_gs(std::span<const std::uint8_t> vs, + std::optional<std::span<const std::uint8_t>> ps); + +// rect_list_gs from the vertex shader's outputs and the pixel shader's inputs. +std::vector<std::uint8_t> rect_build(std::vector<container::SigElement> outputs, + std::span<const container::SigElement> ps_inputs); + +} // namespace x2w::vs diff --git a/src/x2w_shader/emit/sampler.cpp b/src/x2w_shader/emit/sampler.cpp new file mode 100644 index 0000000000..e5c708d2a1 --- /dev/null +++ b/src/x2w_shader/emit/sampler.cpp @@ -0,0 +1,59 @@ + +#include "x2w_shader/emit/sampler.h" + +#include <algorithm> + +namespace x2w::vs::sampler { + +std::uint32_t StaticSampler::filter_for_host(bool aniso_point_mip_supported) const { + if (!aniso_point_mip_supported && (filter & ~0x180u) == 0x54) return filter | 1; + return filter; +} + +StaticSampler StaticSampler::from_words(std::array<std::uint32_t, 4> w) { + auto bits = [](std::uint32_t word, std::uint32_t at, std::uint32_t n) { return (word >> at) & ((1u << n) - 1); }; + // wrap, mirror, clamp, mirror once; the half-border modes have no D3D form and become their + // nearest. + auto address = [](std::uint32_t m) { + static const std::uint32_t table[8] = {1, 2, 3, 5, 3, 5, 4, 5}; + return table[m]; + }; + const std::uint32_t mag = bits(w[2], 20, 2), min = bits(w[2], 22, 2), mip = bits(w[2], 26, 2); + std::uint32_t reduction = 0; + switch (bits(w[0], 29, 2)) { + case 1: + reduction = 2; + break; + case 2: + reduction = 3; + break; + default: + reduction = 0; + } + std::uint32_t f = 0; + if (mag >= 2 || min >= 2) + f = 0x54 | std::uint32_t(mip == 2) | reduction << 7; + else + f = (min & 1) << 4 | (mag & 1) << 2 | std::uint32_t(mip == 2) | reduction << 7; + auto lod = [](std::uint32_t v) { return float(v) / 256.0f; }; + // Without a mip filter the base level is sampled. + float min_lod = 0, max_lod = 0; + if (mip != 0) { + min_lod = lod(bits(w[1], 0, 12)); + max_lod = lod(bits(w[1], 12, 12)); + } + StaticSampler s; + s.filter = f; + s.address = {address(bits(w[0], 0, 3)), address(bits(w[0], 3, 3)), address(bits(w[0], 6, 3))}; + s.mip_lod_bias = float(std::int32_t(bits(w[2], 0, 14) << 18) >> 18) / 256.0f; + s.max_anisotropy = 1u << std::min(bits(w[0], 9, 3), 4u); + s.comparison = bits(w[0], 12, 3) + 1; + // shortcut: a custom border colour (type 3, a table entry) becomes transparent black; upgrade + // when a title uses one. + s.border = bits(w[3], 30, 2) % 3; + s.min_lod = min_lod; + s.max_lod = max_lod; + return s; +} + +} // namespace x2w::vs::sampler diff --git a/src/x2w_shader/emit/sampler.h b/src/x2w_shader/emit/sampler.h new file mode 100644 index 0000000000..b119d37075 --- /dev/null +++ b/src/x2w_shader/emit/sampler.h @@ -0,0 +1,40 @@ +#pragma once + +// Immediate samplers: the console's four sampler words (the GPU's public SQ_IMG_SAMP_WORD0-3 layout) as a +// D3D12 static sampler. +// +// Word 0: address modes x, y, z (bits 0-8, 3 each), log2 of the maximum anisotropy (9-11), +// comparison function (12-14), reduction (29-30: 0 filtering, 1 minimum, 2 maximum). Word 1: +// minimum and maximum LOD (0-11, 12-23, unsigned 4.8). Word 2: LOD bias (0-13, signed 5.8), +// magnification and minification filters (20-21, 22-23: point, linear, anisotropic point, +// anisotropic linear), mip filter (26-27: none, point, linear). Word 3: border colour (30-31: +// transparent black, opaque black, opaque white, custom). + +#include <array> +#include <cstdint> + +namespace x2w::vs::sampler { + +// A static sampler in D3D12 terms; the integers are the D3D12_FILTER, +// D3D12_TEXTURE_ADDRESS_MODE, D3D12_COMPARISON_FUNC and D3D12_STATIC_BORDER_COLOR values. +struct StaticSampler { + std::uint32_t filter = 0; + // U, V, W. + std::array<std::uint32_t, 3> address{}; + float mip_lod_bias = 0; + std::uint32_t max_anisotropy = 0; + std::uint32_t comparison = 0; + std::uint32_t border = 0; + float min_lod = 0; + float max_lod = 0; + + // The filter supported by the host device. Anisotropic point-mip filtering is optional + // (D3D12_OPTIONS19); older devices retain the previous linear-mip approximation. + std::uint32_t filter_for_host(bool aniso_point_mip_supported) const; + // Decodes the four sampler words. + static StaticSampler from_words(std::array<std::uint32_t, 4> w); + // (The floats come from fixed-point fields: never NaN.) + bool operator==(const StaticSampler&) const = default; +}; + +} // namespace x2w::vs::sampler diff --git a/src/x2w_shader/emit/settings.cpp b/src/x2w_shader/emit/settings.cpp new file mode 100644 index 0000000000..9f7aff6677 --- /dev/null +++ b/src/x2w_shader/emit/settings.cpp @@ -0,0 +1,131 @@ +// Emitter settings and loop-limit parsing. + +#include "x2w_shader/emit/settings.h" + +#include <cstdlib> +#include <string> + +#include "x2w_shader/emit/opt.h" + +namespace x2w::vs { + +namespace { + +std::optional<std::string_view> env(const char* name) { + const char* v = std::getenv(name); + if (!v) return std::nullopt; + return std::string_view(v); +} + +std::string_view trim(std::string_view s) { + auto space = [](char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'; }; + while (!s.empty() && space(s.front())) s.remove_prefix(1); + while (!s.empty() && space(s.back())) s.remove_suffix(1); + return s; +} + +// Accept an optional plus sign followed by one or more digits. Reject overflow. +std::optional<std::uint32_t> parse_u32(std::string_view s, unsigned radix) { + if (!s.empty() && s.front() == '+') s.remove_prefix(1); + if (s.empty()) return std::nullopt; + std::uint64_t n = 0; + for (char c : s) { + unsigned d; + if (c >= '0' && c <= '9') + d = unsigned(c - '0'); + else if (c >= 'a' && c <= 'z') + d = unsigned(c - 'a') + 10; + else if (c >= 'A' && c <= 'Z') + d = unsigned(c - 'A') + 10; + else + return std::nullopt; + if (d >= radix) return std::nullopt; + n = n * radix + d; + if (n > UINT32_MAX) return std::nullopt; + } + return std::uint32_t(n); +} + +// value.map(str::trim).and_then(0x hex or decimal). +std::optional<std::uint32_t> parse_number(std::optional<std::string_view> value) { + if (!value) return std::nullopt; + std::string_view v = trim(*value); + if (v.substr(0, 2) == "0x") return parse_u32(v.substr(2), 16); + return parse_u32(v, 10); +} + +} // namespace + +std::uint32_t parse_set(std::optional<std::string_view> value, std::uint32_t unset, std::uint32_t all) { + auto parsed = parse_number(value); + return parsed ? (*parsed & all) : unset; +} + +std::uint32_t parse_shader_opt(std::optional<std::string_view> value) { + auto parsed = parse_number(value); + return parsed ? (*parsed & bitcode::opt::ALL) : bitcode::opt::DEFAULT; +} + +std::uint32_t parse_loop_limit(std::optional<std::string_view> value) { + auto parsed = parse_number(value); + if (parsed && *parsed > 0) return *parsed; + return DEFAULT_LOOP_LIMIT; +} + +std::uint32_t loop_limit() { +#ifdef X2W_VS_DIAGNOSTICS + static const std::uint32_t limit = parse_loop_limit(env("X2W_SHADERCFG_SHADER_LOOP_LIMIT")); + return limit; +#else + return DEFAULT_LOOP_LIMIT; +#endif +} + +bool helper_own() { + static const bool on = [] { + auto v = env("X2W_SHADERCFG_HELPER_OWN"); + return !v || *v != "0"; + }(); + return on; +} + +std::uint8_t group_sync() { + static const std::uint8_t mode = [] { + auto v = env("X2W_SHADERCFG_GROUP_SYNC"); + if (v) { + std::string_view t = trim(*v); + if (t == "0") return std::uint8_t(0); + if (t == "1") return std::uint8_t(1); + } + return std::uint8_t(2); + }(); + return mode; +} + +bool builder_fences() { + static const bool on = [] { + auto v = env("X2W_SHADERCFG_BVH_FENCES"); + return !v || *v != "0"; + }(); + return on; +} + +bool builder_bounds() { + static const bool on = [] { + auto v = env("X2W_SHADERCFG_BVH_BOUNDS"); + return !v || *v != "0"; + }(); + return on; +} + +std::uint32_t shader_opt() { + static const std::uint32_t passes = parse_shader_opt(env("X2W_SHADERCFG_SHADER_OPT")); + return passes; +} + +std::uint32_t rdna_float() { + static const std::uint32_t bits = parse_set(env("X2W_SHADERCFG_RDNA_FLOAT"), rdna::ALL, rdna::ALL); + return bits; +} + +} // namespace x2w::vs diff --git a/src/x2w_shader/emit/settings.h b/src/x2w_shader/emit/settings.h new file mode 100644 index 0000000000..e25b986e56 --- /dev/null +++ b/src/x2w_shader/emit/settings.h @@ -0,0 +1,55 @@ +#pragma once + +// Translation switches shared by shader emission and lowering, kept separate from emit.h to avoid a header +// cycle. + +#include <cstdint> +#include <optional> +#include <string_view> + +namespace x2w::vs { + +// The loop limit without an override: 2^20 (lower LOOP_LIMIT). +inline constexpr std::uint32_t DEFAULT_LOOP_LIMIT = 1u << 20; + +// DEFAULT_LOOP_LIMIT bounds iterations per lane and per loop entry. Builds with X2W_VS_DIAGNOSTICS read +// X2W_SHADERCFG_SHADER_LOOP_LIMIT. +std::uint32_t loop_limit(); +// Whether a pixel shader's helper lane reads its own value where the console reads the first +// lane's; on unless X2W_SHADERCFG_HELPER_OWN=0. +bool helper_own(); +// Which group barriers wait for the whole group (X2W_SHADERCFG_GROUP_SYNC: unset/2 every one, 1 only +// in blocks every lane runs, 0 none). +std::uint8_t group_sync(); +// Whether buffer atomics of the ray-tracing structure builder stand between two fences +// (X2W_SHADERCFG_BVH_FENCES=0: they do not). +bool builder_fences(); +// Whether the structure builder's accesses through its root views stay near them +// (X2W_SHADERCFG_BVH_BOUNDS=0: not). +bool builder_bounds(); +// The clean-up passes (bitcode::opt bits) that run before a module is written +// (X2W_SHADERCFG_SHADER_OPT; unset: opt::DEFAULT). +std::uint32_t shader_opt(); +// On an RDNA host (set_host_rdna): which float instructions are written as the one host +// operation (X2W_SHADERCFG_RDNA_FLOAT, rdna bits; unset: rdna::ALL). +std::uint32_t rdna_float(); + +// The bits of rdna_float(). +namespace rdna { +// v_max_f32 and the like: the host's FMax and FMin, without the code that orders -0 below +0. +inline constexpr std::uint32_t MAX_MIN = 1; +// v_mul_legacy_f32 and the like (0 times anything is 0). +inline constexpr std::uint32_t LEGACY = 2; +// v_med3_f32 of a value between two ordered constants: a minimum of a maximum. +inline constexpr std::uint32_t MED3 = 4; +// v_fract_f32: the host's Frc as it is. +inline constexpr std::uint32_t FRACT = 8; +inline constexpr std::uint32_t ALL = 15; +} // namespace rdna + +// Pure parsers of the switches above (for testing). +std::uint32_t parse_set(std::optional<std::string_view> value, std::uint32_t unset, std::uint32_t all); +std::uint32_t parse_shader_opt(std::optional<std::string_view> value); +std::uint32_t parse_loop_limit(std::optional<std::string_view> value); + +} // namespace x2w::vs diff --git a/src/x2w_shader/emit/shader.cpp b/src/x2w_shader/emit/shader.cpp new file mode 100644 index 0000000000..7e89852215 --- /dev/null +++ b/src/x2w_shader/emit/shader.cpp @@ -0,0 +1,579 @@ + +#include "x2w_shader/emit/shader.h" + +#include <algorithm> +#include <string> + +#include "x2w_shader/emit/census.h" +#include "x2w_shader/emit/opt.h" +#include "x2w_shader/emit/settings.h" + +namespace x2w::vs::shader { + +using bitcode::Tag; +using container::Binding; +using container::Psv; + +namespace { + +std::atomic<std::uint32_t> VIEW_LIMIT{0}; +std::atomic<std::uint32_t> RAW_VIEWS{0}; +thread_local std::optional<std::uint32_t> RAW_VIEWS_HERE; + +} // namespace + +void set_view_heap_limit(std::uint32_t null_slot) { VIEW_LIMIT.store(null_slot, std::memory_order_relaxed); } +std::uint32_t view_heap_limit() { return VIEW_LIMIT.load(std::memory_order_relaxed); } + +void set_raw_views(std::uint32_t first) { RAW_VIEWS.store(first, std::memory_order_relaxed); } +std::uint32_t raw_views() { + if (RAW_VIEWS_HERE) return *RAW_VIEWS_HERE; + return RAW_VIEWS.load(std::memory_order_relaxed); +} +void set_raw_views_here(std::optional<std::uint32_t> first) { RAW_VIEWS_HERE = first; } + +Shader::Shader(bool pixel_) : pixel(pixel_) { + Ty voidt = m.void_(); + Ty i1 = m.int_(1); + Ty i8 = m.int_(8); + Ty i32 = m.int_(32); + Ty f32 = m.float_(); + Ty i8p = m.ptr(i8); + Ty handle = m.named_struct("dx.types.Handle", {i8p}); + Ty props = m.named_struct("dx.types.ResourceProperties", {i32, i32}); + Ty bind = m.named_struct("dx.types.ResBind", {i32, i32, i32, i8}); + Ty cbuf_ret = m.named_struct("dx.types.CBufRet.i32", {i32, i32, i32, i32}); + Ty res_ret = m.named_struct("dx.types.ResRet.f32", {f32, f32, f32, f32, i32}); + Ty main_ty = m.func_ty(voidt, {}); + m.ptr(main_ty); + main_ = m.function("main", main_ty, std::nullopt, true); + entry = m.new_block(); + t = Types{voidt, i1, i32, f32, handle, props, bind, cbuf_ret, res_ret}; +} + +V Shader::lds() { + if (lds_) return *lds_; + Ty arr = m.array(lds_dwords, t.i32); + V g = m.global("lds", arr, 3); + lds_ = g; + return g; +} + +V Shader::op(std::size_t block, std::string_view name, Attr attr, Ty ret, std::uint32_t opcode, + std::span<const V> args) { + std::vector<Ty> params = {t.i32}; + for (V a : args) params.push_back(m.type_of(a)); + Ty fty = m.func_ty(ret, std::move(params)); + m.ptr(fty); + std::string full = "dx.op."; + full += name; + V f = m.function(full, fty, attr, false); + std::vector<V> all = {m.i32(opcode)}; + all.insert(all.end(), args.begin(), args.end()); + return m.call(block, f, std::move(all)); +} + +V Shader::user_data_handle() { + V bind_[4] = {m.i32(0), m.i32(0), m.i32(USER_DATA_SPACE), m.i8(2)}; // CBV + V b = m.aggregate(t.bind, bind_); + std::size_t block = entry; + V i = m.i32(0); + V f = m.bool_(false); + V h = op(block, "createHandleFromBinding", Attr::ReadNone, t.handle, 217, {b, i, f}); + // The size is known in finish, which fixes this placeholder. + return annotate(block, h, 13, UINT32_MAX); +} + +V Shader::root_cbv_handle(std::uint8_t slot) { + for (const auto& r : root_cbvs) + if (r.first == slot) return r.second; + V r = m.i32(slot); + V bind_[4] = {r, r, m.i32(ROOT_CBV_SPACE), m.i8(2)}; + V b = m.aggregate(t.bind, bind_); + V f = m.bool_(false); + std::size_t block = entry; + V h = op(block, "createHandleFromBinding", Attr::ReadNone, t.handle, 217, {b, r, f}); + h = annotate(block, h, 13, 65536); + root_cbvs.emplace_back(slot, h); + return h; +} + +V Shader::root_srv_handle(std::uint8_t slot) { + for (const auto& r : root_srvs) + if (r.first == slot) return r.second; + V r = m.i32(slot); + V bind_[4] = {r, r, m.i32(ROOT_CBV_SPACE), m.i8(0)}; + V b = m.aggregate(t.bind, bind_); + V f = m.bool_(false); + std::size_t block = entry; + V h = op(block, "createHandleFromBinding", Attr::ReadNone, t.handle, 217, {b, r, f}); + h = annotate(block, h, 11, 0); + flags |= flags::RAW_BUFFERS; + root_srvs.emplace_back(slot, h); + return h; +} + +V Shader::root_uav_handle(std::uint8_t slot) { + for (const auto& r : root_uavs) + if (r.first == slot) return r.second; + V r = m.i32(slot); + V bind_[4] = {r, r, m.i32(ROOT_CBV_SPACE), m.i8(1)}; + V b = m.aggregate(t.bind, bind_); + V f = m.bool_(false); + std::size_t block = entry; + V h = op(block, "createHandleFromBinding", Attr::ReadNone, t.handle, 217, {b, r, f}); + h = annotate(block, h, 11 | 0x1000, 0); + flags |= flags::RAW_BUFFERS; + root_uavs.emplace_back(slot, h); + return h; +} + +V Shader::sampler_handle(std::size_t block, std::uint32_t n) { + V bind_[4] = {m.i32(n), m.i32(n), m.i32(SAMPLER_SPACE), m.i8(3)}; // sampler + V b = m.aggregate(t.bind, bind_); + V i = m.i32(n); + V f = m.bool_(false); + V h = op(block, "createHandleFromBinding", Attr::ReadNone, t.handle, 217, {b, i, f}); + std::uint32_t cmp = ((cmp_samplers >> n) & 1) != 0 ? 0x8000 : 0; + return annotate(block, h, 14 | cmp, 0); +} + +V Shader::annotate(std::size_t block, V h, std::uint32_t props0, std::uint32_t props1) { + V p_[2] = {m.i32(props0), m.i32(props1)}; + V p = m.aggregate(t.props, p_); + return op(block, "annotateHandle", Attr::ReadNone, t.handle, 216, {h, p}); +} + +V Shader::heap_handle(std::size_t block, V index, bool sampler, bool nonuniform, + std::pair<std::uint32_t, std::uint32_t> props) { + return heap_handle_at(block, index, sampler, nonuniform, props, false); +} + +V Shader::heap_handle_at(std::size_t block, V index, bool sampler, bool nonuniform, + std::pair<std::uint32_t, std::uint32_t> props, bool bounded) { + // a view index past the host heap (set_view_heap_limit) reads its null slot instead (the raw + // twins of buffer views lie past it: such an index comes bounded) + std::uint32_t limit = bounded ? 0 : VIEW_LIMIT.load(std::memory_order_relaxed); + // (as dx.op.binary UMin: a compare and select emitted here made the bitcode invalid) + if (!sampler && limit != 0) { + V null = m.i32(limit); + Ty i32t = t.i32; + V v = op(block, "binary.i32", Attr::ReadNone, i32t, 40, {index, null}); + m.tag(v, Tag::Clamp); + index = v; + } else if (sampler) { + // A sampler heap has at most 2,048 samplers on any host: an index past that (a number + // read from memory the host has not got yet) stays inside the largest heap there is. + // shortcut: not the bound heap's own count, which a title heap smaller than 2,048 would + // need. + V last = m.i32(2047); + Ty i32t = t.i32; + V v = op(block, "binary.i32", Attr::ReadNone, i32t, 40, {index, last}); + m.tag(v, Tag::Clamp); + index = v; + } + flags |= sampler ? flags::SAMPLER_HEAP : flags::RESOURCE_HEAP; + nonuniform_handles += std::uint32_t(nonuniform); + V s = m.bool_(sampler); + V n = m.bool_(nonuniform); + V h = op(block, "createHandleFromHeap", Attr::ReadNone, t.handle, 218, {index, s, n}); + return annotate(block, h, props.first, props.second); +} + +void Shader::fix_user_data_size(std::uint32_t size) { + V old_[2] = {m.i32(13), m.i32(UINT32_MAX)}; + V old = m.aggregate(t.props, old_); + V new_[2] = {m.i32(13), m.i32(size)}; + V nw = m.aggregate(t.props, new_); + m.replace_const(old, nw); +} + +std::optional<Md> Shader::signature_md(std::vector<SigElement> elements) { + if (elements.empty()) return std::nullopt; + std::vector<std::optional<Md>> list; + for (std::size_t id = 0; id < elements.size(); ++id) { + const SigElement& e = elements[id]; + auto c32 = [this](std::uint32_t v) -> std::optional<Md> { + V c = m.i32(v); + return m.md_value(c); + }; + auto c8 = [this](std::uint8_t v) -> std::optional<Md> { + V c = m.i8(v); + return m.md_value(c); + }; + auto idx = c32(e.index); + std::optional<Md> indices = m.md_node({idx}); + std::optional<Md> usage; + if (e.usage != 0) { + auto tag = c32(3); + auto mask = c32(e.usage); + usage = m.md_node({tag, mask}); + } + // Braced lists evaluate from left to right. + std::vector<std::optional<Md>> ops = { + c32(std::uint32_t(id)), + m.md_str(e.name), + c8(e.comp), + c8(e.kind), + indices, + c8(e.interp), + c32(1), + c8(e.cols), + c32(e.row.value_or(UINT32_MAX)), + c8(e.row ? e.col : std::uint8_t(0xFF)), + usage, + }; + list.push_back(m.md_node(std::move(ops))); + } + return m.md_node(std::move(list)); +} + +std::vector<std::uint8_t> Shader::finish() { + if (pixel) { + // Reading a per-vertex value with attributeAtVertex needs a constant input, even when the + // source declaration was smooth. D3D requires all components packed into the same + // register to share a mode, including the ones the shader never reads. + for (std::size_t index = 0; index < inputs.size(); ++index) { + const SigElement& unused = inputs[index]; + if (unused.kind != 0 || unused.usage != 0 || !unused.row) continue; + std::optional<std::uint8_t> mode; + bool all = true; + for (const SigElement& e : inputs) { + if (!(e.row == unused.row && e.usage != 0)) continue; + if (!mode) + mode = e.interp; + else if (e.interp != *mode) + all = false; + } + // Read the first mode before testing the remaining modes. + if (mode && (*mode == 1 || unused.comp == 9) && all) inputs[index].interp = *mode; + } + } + const std::uint32_t ud_size = (user_data * 4 + 15) / 16 * 16; + fix_user_data_size(ud_size); + // The clean-up, before anything is declared about the code: a feature whose last use it + // removed must not be declared (the validator compares the flags with what the code uses). + const std::uint32_t passes = shader_opt() & bitcode::opt::MODULE; + if (passes != 0) { + m.optimise(passes); + const bitcode::opt::Usage used = m.usage(); + const std::pair<std::uint64_t, bool> table[] = { + {flags::ROVS, used.rovs}, + {flags::WAVE_OPS, used.wave_ops}, + {flags::INT64, used.int64}, + {flags::TYPED_UAV_LOADS, used.typed_uav_loads}, + {flags::RESOURCE_HEAP, used.heap_views}, + {flags::SAMPLER_HEAP, used.heap_samplers}, + {flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64, used.atomic64}, + }; + for (const auto& [flag, u] : table) + if (!u) flags &= ~flag; + } + // Unordered views outside pixel and compute programs (memory by address), as DXC counts them: ranges + // declared below, not views picked from the heap. + const bool compute = threads.has_value() && !mesh && !geometry; + if (!root_uavs.empty() && !pixel && !compute) flags |= flags::UAVS_EVERY_STAGE; + std::optional<Md> resources; + std::vector<Binding> bindings; + auto i32c = [this](std::uint32_t v) { + V c = m.i32(v); + return m.md_value(c); + }; + if (user_data > 0 || samplers > 0 || !root_cbvs.empty() || !root_srvs.empty() || !root_uavs.empty()) { + Md empty = m.md_str(""); + std::optional<Md> cbvs; + std::vector<std::optional<Md>> cbv_list; + if (user_data > 0) { + Ty arr = m.array((user_data + 3) / 4 * 4, t.i32); + Ty ty = m.named_struct("UserData", {arr}); + Ty p = m.ptr(ty); + V u = m.undef(p); + std::vector<std::optional<Md>> ops = { + i32c(0), m.md_value(u), empty, i32c(USER_DATA_SPACE), i32c(0), i32c(1), i32c(ud_size), std::nullopt, + }; + cbv_list.push_back(m.md_node(std::move(ops))); + bindings.push_back(Binding{2, USER_DATA_SPACE, 0, 13}); + } + Ty blob = m.array(16384, t.i32); + Ty ty = m.named_struct("RootCbv", {blob}); + Ty p = m.ptr(ty); + V u = m.undef(p); + const auto cbv_slots = root_cbvs; + for (const auto& [slot, h] : cbv_slots) { + (void)h; + std::vector<std::optional<Md>> ops = { + i32c(std::uint32_t(cbv_list.size())), + m.md_value(u), + empty, + i32c(ROOT_CBV_SPACE), + i32c(slot), + i32c(1), + i32c(65536), + std::nullopt, + }; + cbv_list.push_back(m.md_node(std::move(ops))); + bindings.push_back(Binding{2, ROOT_CBV_SPACE, slot, 13}); + } + if (!cbv_list.empty()) cbvs = m.md_node(std::move(cbv_list)); + std::optional<Md> srvs; + if (!root_srvs.empty()) { + Ty sty = m.named_struct("struct.ByteAddressBuffer", {t.i32}); + Ty sp = m.ptr(sty); + V su = m.undef(sp); + std::vector<std::optional<Md>> list; + const auto slots = root_srvs; + for (std::size_t n = 0; n < slots.size(); ++n) { + std::uint8_t slot = slots[n].first; + std::vector<std::optional<Md>> ops = { + i32c(std::uint32_t(n)), m.md_value(su), empty, i32c(ROOT_CBV_SPACE), i32c(slot), + i32c(1), i32c(11), i32c(0), std::nullopt, + }; + list.push_back(m.md_node(std::move(ops))); + bindings.push_back(Binding{4, ROOT_CBV_SPACE, slot, 11}); + } + srvs = m.md_node(std::move(list)); + } + std::optional<Md> uavs; + if (!root_uavs.empty()) { + Ty uty = m.named_struct("struct.RWByteAddressBuffer", {t.i32}); + Ty up = m.ptr(uty); + V uu = m.undef(up); + V nov = m.bool_(false); + Md no = m.md_value(nov); + std::vector<std::optional<Md>> list; + const auto slots = root_uavs; + for (std::size_t n = 0; n < slots.size(); ++n) { + std::uint8_t slot = slots[n].first; + // Id, variable, name, space, lower bound, range size, shape (11: raw buffer), + // globally coherent, counter, rasterizer ordered, no extra properties. + std::vector<std::optional<Md>> ops = { + i32c(std::uint32_t(n)), m.md_value(uu), empty, i32c(ROOT_CBV_SPACE), i32c(slot), i32c(1), + i32c(11), no, no, no, std::nullopt, + }; + list.push_back(m.md_node(std::move(ops))); + bindings.push_back(Binding{7, ROOT_CBV_SPACE, slot, 11}); + } + uavs = m.md_node(std::move(list)); + } + std::optional<Md> samps; + if (samplers > 0) { + Ty sty = m.named_struct("struct.SamplerState", {t.i32}); + Ty sp = m.ptr(sty); + V su = m.undef(sp); + std::vector<std::optional<Md>> list; + for (std::uint32_t n = 0; n < samplers; ++n) { + auto kind = std::uint32_t((cmp_samplers >> n) & 1); + std::vector<std::optional<Md>> ops = { + i32c(n), m.md_value(su), empty, i32c(SAMPLER_SPACE), i32c(n), i32c(1), + // Sampler kind: 1 comparison. + i32c(kind), std::nullopt, + }; + list.push_back(m.md_node(std::move(ops))); + bindings.push_back(Binding{1, SAMPLER_SPACE, n, 14}); + } + samps = m.md_node(std::move(list)); + } + resources = m.md_node({srvs, uavs, cbvs, samps}); + // PSV0 lists them as the module does: CBVs, samplers, SRVs, UAVs. + auto key = [](const Binding& b) { + switch (b.kind) { + case 2: return 0; + case 1: return 1; + case 7: return 3; + default: return 2; + } + }; + std::stable_sort(bindings.begin(), bindings.end(), + [&](const Binding& a, const Binding& b) { return key(a) < key(b); }); + } + if (resources) m.named_md("dx.resources", {*resources}); + + const bool graphics = !threads || mesh.has_value(); + if (graphics) { + // shortcut: every output is declared to depend on every input; the exact sets need a + // dependence pass. Drivers read this state. + auto scalars = [](const std::vector<SigElement>& els) { + std::uint32_t mx = 0; + for (const SigElement& e : els) + if (e.row) mx = std::max(mx, *e.row * 4 + std::uint32_t(std::uint8_t(e.col + e.cols))); + return mx; + }; + const std::uint32_t ni = scalars(inputs), no = scalars(outputs); + std::vector<std::uint32_t> view = {ni, no}; + // Mesh shaders have no inputs: then the primitive outputs' count. + if (mesh) view.push_back(scalars(prims)); + for (std::uint32_t i = 0; i < ni; ++i) { + for (std::uint32_t k = 0; k < (no + 31) / 32; ++k) { + std::uint32_t bits = std::min(no - 32 * k, 32u); + view.push_back(bits == 32 ? UINT32_MAX : (1u << bits) - 1); + } + } + // A geometry shader lists four streams: the other three have no outputs. + if (geometry) view.insert(view.end(), {0, 0, 0}); + Ty arrt = m.array(std::uint32_t(view.size()), t.i32); + std::vector<V> elems; + elems.reserve(view.size()); + for (std::uint32_t v : view) elems.push_back(m.i32(v)); + V arr = m.aggregate(arrt, elems); + Md arrmd = m.md_value(arr); + Md view_node = m.md_node({arrmd}); + m.named_md("dx.viewIdState", {view_node}); + } + + std::optional<Md> sigs; + if (graphics) { + auto ins = signature_md(inputs); + auto outs = signature_md(outputs); + auto prs = signature_md(prims); + sigs = m.md_node({ins, outs, prs}); + } + // A pixel shader with an SV_StencilRef output (as DXC collects it). + if (pixel && std::any_of(outputs.begin(), outputs.end(), [](const SigElement& o) { return o.kind == 20; })) + flags |= flags::STENCIL_REF; + // Entry properties: shader flags (tag 0), geometry state (1), thread-group size (4), wave size + // (11). + std::vector<Md> props; + if (flags != 0) { + props.push_back(i32c(0)); + Ty i64t = m.int_(64); + V f = m.int_const(i64t, std::int64_t(flags)); + props.push_back(m.md_value(f)); + } + if (geometry) { + // Input primitive (3: triangles), maximum vertices, stream mask, output topology (5: + // triangle strips), instances. + props.push_back(i32c(1)); + std::vector<std::optional<Md>> state; + for (std::uint32_t n : {3u, geometry->max_vertices, 1u, 5u, 1u}) state.push_back(i32c(n)); + props.push_back(m.md_node(std::move(state))); + } + if (threads) { + std::vector<std::optional<Md>> tl; + for (std::uint32_t n : *threads) tl.push_back(i32c(n)); + Md tn = m.md_node(std::move(tl)); + if (mesh) { + // Mesh state (tag 9): threads, maximum vertices and primitives, topology, payload + // bytes. + props.push_back(i32c(9)); + std::vector<std::optional<Md>> node = {tn}; + for (std::uint32_t n : {mesh->max_vertices, mesh->max_primitives, std::uint32_t(mesh->topology), 0u}) + node.push_back(i32c(n)); + props.push_back(m.md_node(std::move(node))); + } else { + props.push_back(i32c(4)); + props.push_back(tn); + } + } + if (wave_size) { + props.push_back(i32c(11)); + std::optional<Md> n = i32c(*wave_size); + props.push_back(m.md_node({n})); + } + std::optional<Md> propsmd; + if (!props.empty()) { + std::vector<std::optional<Md>> list(props.begin(), props.end()); + propsmd = m.md_node(std::move(list)); + } + Md mainmd = m.md_value(main_); + Md name = m.md_str("main"); + Md entrymd = m.md_node({mainmd, name, sigs, resources, propsmd}); + + Md ident = m.md_str("Xbox2Windows"); + ident = m.md_node({ident}); + m.named_md("llvm.ident", {ident}); + Md one = i32c(1); + Md six = i32c(6); + Md version = m.md_node({one, six}); + m.named_md("dx.version", {version}); + m.named_md("dx.valver", {version}); + // Program kinds: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh. + const char* kname; + std::uint32_t kind; + if (mesh) { + kname = "ms"; + kind = 13; + } else if (geometry) { + kname = "gs"; + kind = 2; + } else if (threads) { + kname = "cs"; + kind = 5; + } else if (pixel) { + kname = "ps"; + kind = 0; + } else { + kname = "vs"; + kind = 1; + } + Md smname = m.md_str(kname); + Md sm = m.md_node({smname, six, six}); + m.named_md("dx.shaderModel", {sm}); + m.named_md("dx.entryPoints", {entrymd}); + + const std::vector<std::uint8_t> bc = m.write(); + bitcode::census::note(m, bc); + std::vector<std::uint8_t> dxil; + dxil.reserve(24 + bc.size()); + auto put32 = [](std::vector<std::uint8_t>& out, std::uint32_t v) { + for (int k = 0; k < 4; ++k) out.push_back(std::uint8_t(v >> (8 * k))); + }; + put32(dxil, kind << 16 | 0x66); + put32(dxil, std::uint32_t((24 + bc.size()) / 4)); + dxil.insert(dxil.end(), {'D', 'X', 'I', 'L'}); + put32(dxil, 0x106); + put32(dxil, 16); + put32(dxil, std::uint32_t(bc.size())); + dxil.insert(dxil.end(), bc.begin(), bc.end()); + + std::uint64_t features = 0; + if (flags & flags::DOUBLES) features |= 0x1; + if (flags & flags::UAVS_EVERY_STAGE) features |= 0x4; + if (flags & flags::STENCIL_REF) features |= 0x200; + if (flags & flags::TYPED_UAV_LOADS) features |= 0x800; + if (flags & flags::ROVS) features |= 0x1000; + if (flags & flags::WAVE_OPS) features |= 0x4000; + if (flags & flags::INT64) features |= 0x8000; + if (flags & flags::BARYCENTRICS) features |= 0x20000; + if (flags & flags::RESOURCE_HEAP) features |= 0x2000000; + if (flags & flags::SAMPLER_HEAP) features |= 0x4000000; + if (flags & flags::ATOMIC_TYPED64) features |= 0x400000; + if (flags & flags::ATOMIC_HEAP64) features |= 0x10000000; + std::vector<std::uint8_t> sfi0; + for (int k = 0; k < 8; ++k) sfi0.push_back(std::uint8_t(features >> (8 * k))); + const std::vector<std::uint8_t> isg1 = container::signature(inputs, true); + const std::vector<std::uint8_t> osg1 = container::signature(outputs, false); + bool flag; + if (pixel) + flag = std::any_of(outputs.begin(), outputs.end(), [](const SigElement& o) { return o.kind >= 17 && o.kind <= 19; }); + else + flag = std::any_of(outputs.begin(), outputs.end(), [](const SigElement& o) { return o.kind == 3; }); + Psv psvd; + psvd.stage = std::uint8_t(kind); + psvd.flag = flag && !threads; + psvd.inputs = inputs; + psvd.outputs = outputs; + psvd.prims = prims; + if (mesh) { + psvd.mesh = &*mesh; + psvd.mesh_lds_bytes = lds_dwords * 4; + } + if (geometry) psvd.geometry = geometry->max_vertices; + psvd.bindings = bindings; + psvd.threads = threads.value_or(std::array<std::uint32_t, 3>{}); + psvd.wave_size = wave_size; + const std::vector<std::uint8_t> psv0 = container::psv(psvd); + const std::uint8_t hashpart[20] = {}; + const std::vector<std::uint8_t> psg1 = container::signature(prims, false); + std::vector<container::Part> parts = { + {{'S', 'F', 'I', '0'}, sfi0}, + {{'I', 'S', 'G', '1'}, isg1}, + {{'O', 'S', 'G', '1'}, osg1}, + }; + if (mesh) parts.push_back({{'P', 'S', 'G', '1'}, psg1}); + parts.push_back({{'P', 'S', 'V', '0'}, psv0}); + parts.push_back({{'H', 'A', 'S', 'H'}, std::span<const std::uint8_t>(hashpart, 20)}); + parts.push_back({{'D', 'X', 'I', 'L'}, dxil}); + return container::build(parts); +} + +} // namespace x2w::vs::shader diff --git a/src/x2w_shader/emit/shader.h b/src/x2w_shader/emit/shader.h new file mode 100644 index 0000000000..010433427e --- /dev/null +++ b/src/x2w_shader/emit/shader.h @@ -0,0 +1,209 @@ +#pragma once + +// A DXIL vertex, pixel, compute or mesh shader under construction: the module, the dx.op declarations it +// calls, its signatures and bound resources, and the metadata and container that wrap it up (SM 6.6, +// validator 1.6). + +#include <array> +#include <atomic> +#include <cstdint> +#include <optional> +#include <span> +#include <string_view> +#include <utility> +#include <vector> + +#include "x2w_shader/emit/bitcode.h" +#include "x2w_shader/emit/container.h" + +namespace x2w::vs::shader { + +using bitcode::Attr; +using bitcode::Md; +using bitcode::Module; +using bitcode::Ty; +using bitcode::V; +using container::SigElement; + +// Where the shader reads its user data: b0 in this space. +inline constexpr std::uint32_t USER_DATA_SPACE = 0; +// Where immediate samplers are bound: s<n> in this space. +inline constexpr std::uint32_t SAMPLER_SPACE = 0; +// Where root CBVs and SRVs are bound: b<root parameter index> and t<root parameter index> in +// this space. +inline constexpr std::uint32_t ROOT_CBV_SPACE = 1; + +// The root SRV t<SLOT_STRIDES> in ROOT_CBV_SPACE of a shader that reads buffers through +// descriptors it picks from the view heap at an index it computes (SM 6.6 dynamic resources): a +// raw buffer of SLOT_STRIDES_COUNT dwords the host keeps, dword i the bytes per element of the +// buffer view at heap slot i (0: none or not a buffer). A shader that has this root SRV also +// tells the host that the buffer views of the whole heap must be ready when it runs. +inline constexpr std::uint8_t SLOT_STRIDES = 255; +// The bits of a SLOT_STRIDES dword that hold the stride. +inline constexpr std::uint32_t VIEW_STRIDE_BITS = (1u << 30) - 1; +// In a SLOT_STRIDES dword: a typed buffer view of an integer format (UINT or SINT), whose 16-bit +// typed accesses (_d16) pass bits. +inline constexpr std::uint32_t VIEW_INTEGER = 1u << 31; +// With VIEW_INTEGER: a signed (SINT) format. +inline constexpr std::uint32_t VIEW_SIGNED = 1u << 30; +// Dwords of the SLOT_STRIDES buffer: heap indices are clamped to it. +inline constexpr std::uint32_t SLOT_STRIDES_COUNT = 1u << 21; + +// Title memory by address (resource MEMORY): The root SRV t<SLOT_MEMORY> in ROOT_CBV_SPACE is a directory +// of MEMORY_PAGES entries of two dwords, one per 64 KiB of title address space (host copy number, +// MEMORY_READ_ONLY; byte offset in that copy); copy n is the raw view at view-heap slot base + n (base: the +// user-data dword USER_MEMORY_BASE); the root UAV u<SLOT_FAULTS> takes the page numbers of accesses that +// found no copy (MEMORY_FAULTS dwords, dword 0 a sink). +inline constexpr std::uint8_t SLOT_MEMORY = 254; +inline constexpr std::uint8_t SLOT_FAULTS = 253; +// Entries of the SLOT_MEMORY directory: title addresses below 128 GiB. +inline constexpr std::uint32_t MEMORY_PAGES = 1u << 21; +// In a directory entry's first dword: shaders do not store there by address. +inline constexpr std::uint32_t MEMORY_READ_ONLY = 1u << 31; +// Dwords of the SLOT_FAULTS buffer. +inline constexpr std::uint32_t MEMORY_FAULTS = 4096; +// RootType::Other code of a user-data dword the host computes: the view heap slot of the memory +// copies' views (SLOT_MEMORY). +inline constexpr std::uint32_t USER_MEMORY_BASE = 0x100; +// RootType::Other code: the low 32 bits of the title address of the buffer view at dword `dword` +// of the descriptor table of root parameter `slot`; USER_VIEW_ADDRESS + 1: its bits from 32 up. +inline constexpr std::uint32_t USER_VIEW_ADDRESS = 0x101; +// RootType::Other code: the bytes (0 to 15) by which the raw view the host binds for the root +// view of root parameter `slot` begins before the title's address. Asked for every root UAV. +inline constexpr std::uint32_t USER_VIEW_BIAS = 0x103; +// RootType::Other code: the low 32 bits of the title address in the root view of root parameter +// `slot`; USER_ROOT_ADDRESS + 1: its bits from 32 up. +inline constexpr std::uint32_t USER_ROOT_ADDRESS = 0x104; +// RootType::Other code of a user-data dword the host sets at a dispatch counted in threads (the +// console's DispatchX): how many of the threads numbered along X run (0: all of every group). +inline constexpr std::uint32_t USER_DISPATCH_THREADS_X = 0x106; + +// ShaderFlags bits (metadata) and their SFI0 feature bits. +namespace flags { +inline constexpr std::uint64_t RAW_BUFFERS = 1ull << 4; +inline constexpr std::uint64_t DOUBLES = 1ull << 2; +inline constexpr std::uint64_t STENCIL_REF = 1ull << 11; +inline constexpr std::uint64_t TYPED_UAV_LOADS = 1ull << 13; +// Unordered views in a vertex, geometry or mesh program. +inline constexpr std::uint64_t UAVS_EVERY_STAGE = 1ull << 16; +inline constexpr std::uint64_t ROVS = 1ull << 18; +inline constexpr std::uint64_t WAVE_OPS = 1ull << 19; +inline constexpr std::uint64_t BARYCENTRICS = 1ull << 22; +inline constexpr std::uint64_t INT64 = 1ull << 20; +inline constexpr std::uint64_t ATOMIC_TYPED64 = 1ull << 27; +inline constexpr std::uint64_t ATOMIC_HEAP64 = 1ull << 32; +inline constexpr std::uint64_t RESOURCE_HEAP = 1ull << 30; +inline constexpr std::uint64_t SAMPLER_HEAP = 1ull << 31; +} // namespace flags + +struct Types { + Ty void_; + Ty i1; + Ty i32; + Ty f32; + Ty handle; + Ty props; + Ty bind; + Ty cbuf_ret; + Ty res_ret; +}; + +// What a mesh shader declares beyond its thread-group size. +struct Mesh { + std::uint32_t max_vertices = 0; + std::uint32_t max_primitives = 0; + // 1 lines, 2 triangles. + std::uint8_t topology = 0; +}; + +// What a geometry shader declares: triangles in, triangle strips out on stream 0, one instance. +struct Geometry { + std::uint32_t max_vertices = 0; +}; + +// The null slot every host view heap keeps at its end (0: no limit). Shaders translated while it +// is set read that slot for any view index at or past it. +void set_view_heap_limit(std::uint32_t null_slot); +std::uint32_t view_heap_limit(); + +// Where the host's raw twins of its buffer views start in its view heaps (0: there are none). A power of +// two above every slot index. See RAW_VIEWS. +void set_raw_views(std::uint32_t first); +std::uint32_t raw_views(); +// Override raw_views() on the current test thread. +void set_raw_views_here(std::optional<std::uint32_t> first); + +struct Shader { + Module m; + Types t; + bool pixel = false; + std::vector<SigElement> inputs; + std::vector<SigElement> outputs; + // A mesh shader's per-primitive outputs. + std::vector<SigElement> prims; + // A mesh shader (threads is its thread-group size). + std::optional<Mesh> mesh; + // A geometry shader (the rectangle stage, rect.cpp); pixel is false. + std::optional<Geometry> geometry; + // Dwords of user data the shader reads (0: no user-data buffer). + std::uint32_t user_data = 0; + // Immediate samplers, bound as s0.. in SAMPLER_SPACE. + std::uint32_t samplers = 0; + // Bit n: immediate sampler n is a comparison sampler. + std::uint64_t cmp_samplers = 0; + // Root CBVs read, by root parameter index, with their handles. + std::vector<std::pair<std::uint8_t, V>> root_cbvs; + // Root SRVs (raw buffers) read, likewise. + std::vector<std::pair<std::uint8_t, V>> root_srvs; + // Root UAVs (raw buffers) read or written, likewise. + std::vector<std::pair<std::uint8_t, V>> root_uavs; + std::uint64_t flags = 0; + // Heap handles made with a non-uniform index. + std::uint32_t nonuniform_handles = 0; + // A compute shader with this thread-group size. + std::optional<std::array<std::uint32_t, 3>> threads; + // The wave size a compute shader requires (WaveSize). + std::optional<std::uint32_t> wave_size; + // Thread-group shared memory, in dwords. + std::uint32_t lds_dwords = 0; + std::size_t entry = 0; + + explicit Shader(bool pixel); + + // The thread-group shared memory: [lds_dwords x i32] in address space 3. + V lds(); + // Calls dx.op.<name> (class and overload) with opcode and args. + V op(std::size_t block, std::string_view name, Attr attr, Ty ret, std::uint32_t opcode, + std::span<const V> args); + V op(std::size_t block, std::string_view name, Attr attr, Ty ret, std::uint32_t opcode, + std::initializer_list<V> args) { + return op(block, name, attr, ret, opcode, std::span<const V>(args.begin(), args.size())); + } + // The handle of the user-data constant buffer, made in the entry block. + V user_data_handle(); + // The handle of the root CBV of root parameter slot, made in the entry block. + V root_cbv_handle(std::uint8_t slot); + // The handle of the root SRV (a raw buffer) of root parameter slot. + V root_srv_handle(std::uint8_t slot); + // The handle of the root UAV (a raw buffer) of root parameter slot: u<slot> in ROOT_CBV_SPACE. + V root_uav_handle(std::uint8_t slot); + // The handle of immediate sampler n (a comparison sampler when its bit in cmp_samplers is set). + V sampler_handle(std::size_t block, std::uint32_t n); + V annotate(std::size_t block, V h, std::uint32_t props0, std::uint32_t props1); + // A descriptor heap handle, annotated with props; nonuniform when the index may differ + // between lanes (NonUniformResourceIndex). + V heap_handle(std::size_t block, V index, bool sampler, bool nonuniform, std::pair<std::uint32_t, std::uint32_t> props); + // heap_handle; bounded: the index is inside the host's heap already (raw_views). + V heap_handle_at(std::size_t block, V index, bool sampler, bool nonuniform, + std::pair<std::uint32_t, std::uint32_t> props, bool bounded); + // Finish the shader container. Call once. + std::vector<std::uint8_t> finish(); + +private: + std::optional<V> lds_; + V main_; + void fix_user_data_size(std::uint32_t size); + std::optional<Md> signature_md(std::vector<SigElement> elements); +}; + +} // namespace x2w::vs::shader diff --git a/src/x2w_shader/emit/signature.h b/src/x2w_shader/emit/signature.h new file mode 100644 index 0000000000..d36d4ef56e --- /dev/null +++ b/src/x2w_shader/emit/signature.h @@ -0,0 +1,22 @@ +#pragma once + +// Read signatures and vertex output interpolation without including emit.h and its front-end dependencies in rect.cpp or the +// tests. + +#include <cstdint> +#include <span> +#include <vector> + +#include "x2w_shader/emit/container.h" + +namespace x2w::vs { + +// The rows of an ISG1/OSG1 part. Throws ShaderError. +std::vector<container::SigElement> signature(std::span<const std::uint8_t> part); + +// The title's vertex output interpolation lives in PSV0 (`data`: the part). A float packed beside +// an integer can be explicitly constant, as can a float on its own. OSG1 supplies the physical +// rows and columns used to match both tables. Throws ShaderError. +void vertex_output_interpolation(std::span<const std::uint8_t> data, std::span<container::SigElement> outputs); + +} // namespace x2w::vs diff --git a/src/x2w_shader/emit/threading.cpp b/src/x2w_shader/emit/threading.cpp new file mode 100644 index 0000000000..8efff858f5 --- /dev/null +++ b/src/x2w_shader/emit/threading.cpp @@ -0,0 +1,174 @@ +// Jump threading for uniform diamonds. One arm can set a flag that fixes the join's next branch. Registers +// recycled on that arm then never reach the other successor, even if an ordinary SSA phi joins their +// values. + +#include "x2w_shader/emit/threading.h" + +#include <algorithm> +#include <map> +#include <optional> +#include <variant> + +#include "x2w_shader/emit/wave.h" +#include "x2w_shader/structure.h" + +namespace x2w::vs::threading { + +using gfx10::Fields; +using gfx10::Operand; +using gfx10::Valu; +using ir::Exit; +using ir::Program; +using ir::Reg; +using ir::Value; +using structure::Atom; +using structure::Bool; +using structure::LaneExit; +using structure::Structured; + +namespace { + +bool plain(const Valu& v) { + return v.abs == 0 && v.neg == 0 && v.opsel == 0 && !v.clamp && v.omod == 0 && !v.sdwa && !v.dpp; +} + +std::optional<std::uint32_t> immediate(const Operand& op) { + switch (op.kind) { + case Operand::Kind::Const: return wave::detail::inline_constant(op.code); // resource::inline + case Operand::Kind::Literal: return op.literal; + default: return std::nullopt; + } +} + +} // namespace + +std::vector<std::tuple<std::size_t, std::size_t, std::size_t>> constant_edges(const Program& p, + const Structured& st) { + std::map<Value, std::uint32_t> constants; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& block = p.blocks[b]; + for (std::size_t i = 0; i < block.insts.size(); ++i) { + const auto& inst = block.insts[i]; + if (inst.name() != "v_mov_b32" || st.guards.at(b).at(i).has_value()) continue; + const auto* v = std::get_if<Valu>(&inst.fields); + if (!v || !plain(*v) || v->src.size() != 1) continue; + const auto word = immediate(v->src[0]); + if (!word || inst.writes.size() != 1) continue; + constants.insert_or_assign(inst.writes[0].second, *word); + } + } + std::vector<std::tuple<std::size_t, std::size_t, std::size_t>> edges; + for (std::size_t join = 0; join < p.blocks.size(); ++join) { + const auto& block = p.blocks[join]; + const LaneExit& ex = st.exits.at(join); + if (ex.kind != LaneExit::Kind::Branch) continue; + const Bool when = ex.when; + const std::size_t taken = ex.taken; + const std::size_t not_taken = ex.not_taken; + if (when == Bool::True || when == Bool::False) continue; + // Keep memory accesses and wave operations at their original reconvergence point. Only + // duplicate scalar ALU and comparisons. + const bool scalar_only = std::all_of(block.insts.begin(), block.insts.end(), [](const ir::Inst& i) { + if (std::holds_alternative<gfx10::Sop>(i.fields)) return true; + if (std::holds_alternative<gfx10::Sopp>(i.fields)) return i.name().starts_with("s_cbranch_"); + if (std::holds_alternative<Valu>(i.fields)) return i.name().starts_with("v_cmp_"); + return false; + }); + if (!scalar_only) continue; + if (block.preds.size() != 2) continue; + const std::size_t a = block.preds[0]; + const std::size_t b = block.preds[1]; + // A triangle has a direct edge from the fork to the join. A full diamond has an + // unconditional jump at the end of each arm. + auto arm_from = [&](std::size_t arm) -> std::optional<std::size_t> { + const auto& blk = p.blocks.at(arm); + if (blk.preds.size() == 1 && blk.exit == Exit::Jump(join)) return blk.preds[0]; + return std::nullopt; + }; + const auto fa = arm_from(a); + const auto fb = arm_from(b); + std::size_t fork = 0; + if (fa && fb && *fa == *fb) { + fork = *fa; + } else if (fb && *fb == a) { + fork = *fb; + } else if (fa && *fa == b) { + fork = *fa; + } else { + continue; + } + if (fork == join || a == b) continue; + const LaneExit& fx = st.exits.at(fork); + if (fx.kind != LaneExit::Kind::Branch) continue; + const Bool entry = fx.when; + const auto sup = st.bools.support(entry); + if (!std::all_of(sup.begin(), sup.end(), [](const Atom& at) { return at.kind == Atom::Kind::Uniform; })) { + continue; + } + for (std::size_t edge = 0; edge < block.preds.size(); ++edge) { + const std::size_t pred = block.preds[edge]; + auto value = [&](Value v) -> std::optional<std::uint32_t> { + Value input = v; + for (const auto& phi : block.phis) { + if (phi.value == v) { + input = phi.args.at(edge); + break; + } + } + const auto it = constants.find(input); + if (it == constants.end()) return std::nullopt; + return it->second; + }; + // Restrict the branch's decision diagram to known comparisons. Unknown tests stop the + // proof. Keep the original join for the other arm, which may still go either way. + Bool cond = when; + while (true) { + const auto node = st.bools.node(cond); + if (!node || std::get<0>(*node).kind != Atom::Kind::Lane) break; + const Value id = std::get<0>(*node).value; + const Bool lo = std::get<1>(*node); + const Bool hi = std::get<2>(*node); + const ir::Inst* inst = nullptr; + for (const auto& i : block.insts) { + if (std::any_of(i.writes.begin(), i.writes.end(), [&](const auto& w) { return w.second == id; })) { + inst = &i; + break; + } + } + if (!inst) break; + const auto* v = std::get_if<Valu>(&inst->fields); + if (!v) break; + if (v->src.size() != 2) break; + auto operand = [&](const Operand& op) -> std::optional<std::uint32_t> { + if (op.kind == Operand::Kind::Vector && op.dwords == 1) { + const auto r = inst->read(Reg::V(op.reg)); + if (!r) return std::nullopt; + return value(*r); + } + return immediate(op); + }; + const auto x = operand(v->src[0]); + const auto y = operand(v->src[1]); + if (!x || !y) break; + if (!plain(*v)) break; + const std::string_view name = inst->name(); + bool yes = false; + if (name == "v_cmp_eq_u32" || name == "v_cmp_eq_i32") { + yes = *x == *y; + } else if (name == "v_cmp_ne_u32" || name == "v_cmp_ne_i32") { + yes = *x != *y; + } else { + break; + } + cond = yes ? hi : lo; + } + if (cond == Bool::True || cond == Bool::False) { + edges.emplace_back(pred, join, cond == Bool::True ? taken : not_taken); + break; + } + } + } + return edges; +} + +} // namespace x2w::vs::threading diff --git a/src/x2w_shader/emit/threading.h b/src/x2w_shader/emit/threading.h new file mode 100644 index 0000000000..1cf6411459 --- /dev/null +++ b/src/x2w_shader/emit/threading.h @@ -0,0 +1,24 @@ +#pragma once + +// Jump threading for refused programs: edges along which a register's value is a known constant, so that +// the program can be retried with those edges threaded (ir::thread_edges). + +#include <cstddef> +#include <tuple> +#include <vector> + +#include "x2w_shader/ir.h" + +namespace x2w::vs::structure { +struct Structured; +} + +namespace x2w::vs::threading { + +// (predecessor, join, destination) triples, as ir::thread_edges takes them: along the edge from +// `predecessor` into `join`, the join's closing branch goes to `destination` (its taken or +// not-taken successor). At most one edge per join. +std::vector<std::tuple<std::size_t, std::size_t, std::size_t>> constant_edges(const ir::Program& p, + const structure::Structured& st); + +} // namespace x2w::vs::threading diff --git a/src/x2w_shader/emit/validator.cpp b/src/x2w_shader/emit/validator.cpp new file mode 100644 index 0000000000..7c10a2ba28 --- /dev/null +++ b/src/x2w_shader/emit/validator.cpp @@ -0,0 +1,141 @@ +// the DXIL validator in dxil.dll (IDxcValidator). + +#include "x2w_shader/emit/validator.h" + +// Not WIN32_LEAN_AND_MEAN: dxcapi.h needs the OLE types (BSTR, IUnknown). +#include <windows.h> + +#include <dxcapi.h> + +#include <algorithm> +#include <cstdio> +#include <cstdlib> +#include <system_error> +#include <vector> + +namespace x2w::vs::validator { + +namespace { + +// Validator and blob interface IDs, supplied explicitly to avoid a dependency on the UUID declarations in +// dxcapi.h. +constexpr GUID CLSID_DXC_VALIDATOR = {0x8ca3e215, 0xf728, 0x4cf3, {0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1}}; +constexpr GUID IID_IDXC_VALIDATOR = {0xa6e82bd2, 0x1fd7, 0x4826, {0x98, 0x11, 0x28, 0x57, 0xe7, 0x97, 0xf4, 0x9a}}; +constexpr GUID IID_IDXC_BLOB = {0x8ba5fb08, 0x5195, 0x40e2, {0xac, 0x58, 0x0d, 0x98, 0x9c, 0x3a, 0x01, 0x02}}; +// DxcValidatorFlags_InPlaceEdit: sign the container we pass. +constexpr UINT32 IN_PLACE_EDIT = 1; + +using CreateInstance = HRESULT(WINAPI*)(REFCLSID, REFIID, LPVOID*); + +std::string hex(HRESULT hr) { + char buf[16]; + std::snprintf(buf, sizeof buf, "0x%x", static_cast<unsigned>(hr)); + return buf; +} + +// An IDxcBlob over our bytes: QueryInterface, AddRef, Release, GetBufferPointer, +// GetBufferSize. Lives on the caller's stack (AddRef/Release do nothing). +class Blob final : public IDxcBlob { +public: + Blob(std::uint8_t* data, std::size_t len) : data_(data), len_(len) {} + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override { + if (iid == __uuidof(IUnknown) || iid == IID_IDXC_BLOB) { + *out = static_cast<IDxcBlob*>(this); + return S_OK; + } + *out = nullptr; + return E_NOINTERFACE; + } + ULONG STDMETHODCALLTYPE AddRef() override { return 1; } + ULONG STDMETHODCALLTYPE Release() override { return 1; } + LPVOID STDMETHODCALLTYPE GetBufferPointer() override { return data_; } + SIZE_T STDMETHODCALLTYPE GetBufferSize() override { return len_; } + +private: + std::uint8_t* data_; + std::size_t len_; +}; + +bool is_trimmed(char c) { return c == '\0' || c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'; } + +} // namespace + +std::optional<std::filesystem::path> Validator::default_path() { + if (const wchar_t* p = _wgetenv(L"X2W_SHADERCFG_DXIL")) return std::filesystem::path(p); + const std::filesystem::path kits = LR"(C:\Program Files (x86)\Windows Kits\10\bin)"; + std::error_code ec; + std::filesystem::directory_iterator it(kits, ec); + if (ec) return std::nullopt; + std::vector<std::filesystem::path> versions; + for (; it != std::filesystem::directory_iterator(); it.increment(ec)) { + if (ec) break; + std::filesystem::path p = it->path() / LR"(x64\dxil.dll)"; + std::error_code e2; + if (std::filesystem::exists(p, e2)) versions.push_back(std::move(p)); + } + std::sort(versions.begin(), versions.end()); + if (versions.empty()) return std::nullopt; + return versions.back(); +} + +std::optional<Validator> Validator::load(const std::optional<std::filesystem::path>& path, std::string* error) { + auto fail = [&](std::string text) -> std::optional<Validator> { + if (error) *error = std::move(text); + return std::nullopt; + }; + const std::wstring name = path ? path->wstring() : std::wstring(L"dxil.dll"); + HMODULE module = LoadLibraryW(name.c_str()); + if (!module) return fail("cannot load " + (path ? path->string() : std::string("dxil.dll"))); + auto proc = GetProcAddress(module, "DxcCreateInstance"); + if (!proc) return fail("dxil.dll lacks DxcCreateInstance"); + auto create = reinterpret_cast<CreateInstance>(reinterpret_cast<void*>(proc)); + void* object = nullptr; + HRESULT hr = create(CLSID_DXC_VALIDATOR, IID_IDXC_VALIDATOR, &object); + if (FAILED(hr) || !object) return fail("DxcCreateInstance(validator) failed: " + hex(hr)); + return Validator(object); +} + +std::optional<std::string> Validator::validate(std::span<std::uint8_t> container) { + Blob blob(container.data(), container.size()); + auto* v = static_cast<IDxcValidator*>(object_); + IDxcOperationResult* result = nullptr; + HRESULT hr = v->Validate(&blob, IN_PLACE_EDIT, &result); + if (FAILED(hr) || !result) return "Validate failed: " + hex(hr); + HRESULT status = 0; + result->GetStatus(&status); + std::string text; + if (status < 0) { + IDxcBlobEncoding* errors = nullptr; + if (result->GetErrorBuffer(&errors) >= 0 && errors) { + const char* p = static_cast<const char*>(errors->GetBufferPointer()); + std::size_t n = errors->GetBufferSize(); + text.assign(p, p + n); + // trim_end_matches('\0').trim() + while (!text.empty() && is_trimmed(text.back())) text.pop_back(); + std::size_t start = 0; + while (start < text.size() && is_trimmed(text[start]) && text[start] != '\0') ++start; + text.erase(0, start); + errors->Release(); + } + if (text.empty()) text = "rejected (" + hex(status) + ")"; + } + result->Release(); + if (status < 0) return text; + return std::nullopt; +} + +Validator& Validator::operator=(Validator&& o) noexcept { + if (this != &o) { + if (object_) static_cast<IUnknown*>(object_)->Release(); + object_ = o.object_; + o.object_ = nullptr; + } + return *this; +} + +Validator::~Validator() { + // We own one reference. + if (object_) static_cast<IUnknown*>(object_)->Release(); +} + +} // namespace x2w::vs::validator diff --git a/src/x2w_shader/emit/validator.h b/src/x2w_shader/emit/validator.h new file mode 100644 index 0000000000..78a4bb6497 --- /dev/null +++ b/src/x2w_shader/emit/validator.h @@ -0,0 +1,47 @@ +#pragma once + +// The DXIL validator in dxil.dll (IDxcValidator), for tests and the offline batch. Translated shaders do +// not need it: they carry the container hash we compute (container::hash). +// +// The DLL is found at X2W_SHADERCFG_DXIL if set, else the newest Windows SDK's bin\<version>\x64\dxil.dll, +// else wherever LoadLibrary finds it. +// +// Creation returns nullopt and writes an error string on failure. Validation returns the rejection message +// on failure and nullopt on success. + +#include <cstdint> +#include <filesystem> +#include <optional> +#include <span> +#include <string> + +namespace x2w::vs::validator { + +class Validator { +public: + // Where dxil.dll is looked for. + static std::optional<std::filesystem::path> default_path(); + + // Loads path's validator (or dxil.dll from the DLL search path when path is nullopt). + // nullopt on failure, with the reason in *error if error is given. + static std::optional<Validator> load(const std::optional<std::filesystem::path>& path, + std::string* error = nullptr); + + // Validates container and signs it in place (DxcValidatorFlags_InPlaceEdit: the validator + // writes its hash into the container's digest); the error text if it is rejected. + std::optional<std::string> validate(std::span<std::uint8_t> container); + + Validator(Validator&& o) noexcept : object_(o.object_) { o.object_ = nullptr; } + Validator& operator=(Validator&& o) noexcept; + Validator(const Validator&) = delete; + Validator& operator=(const Validator&) = delete; + ~Validator(); + +private: + explicit Validator(void* object) : object_(object) {} + // The IDxcValidator; we own one reference. The validator object is free-threaded (DXC's validator has no + // thread affinity); calls are serialised by the caller. + void* object_ = nullptr; +}; + +} // namespace x2w::vs::validator diff --git a/src/x2w_shader/emit/wave.cpp b/src/x2w_shader/emit/wave.cpp new file mode 100644 index 0000000000..2942dc2411 --- /dev/null +++ b/src/x2w_shader/emit/wave.cpp @@ -0,0 +1,715 @@ +// Whole-wave sections: code between `s_or_saveexec -1` (or `s_nand_saveexec 0`) and the restore of the +// saved mask runs in every lane of the console's wave, the inactive ones included, which is how the +// compiler expands HLSL wave reductions and prefix sums (an identity put into the inactive lanes with +// `v_cndmask`, then DPP, `v_permlanex16` and `v_readlane` steps). A host lane that is elsewhere cannot run +// that code, so each section is simulated on the console's lanes with symbolic values, and a value it +// leaves is lowered by what it turned out to be: the reduction or prefix of one operation over the lanes' +// (masked) inputs, which DXIL's wave operations compute over the host's active lanes. No instruction +// sequence is matched; any step the simulation does not model leaves the values it writes unknown. + +#include "x2w_shader/emit/wave.h" +#include "x2w_shader/resource.h" + +#include "x2w_shader/emit/bitcode.h" + +#include <algorithm> +#include <bit> +#include <utility> +#include <variant> +#include <vector> + +namespace x2w::vs::wave { + +using gfx10::DppLanes; +using gfx10::DppRow; +using gfx10::Fields; +using gfx10::NULL_CODE; +using gfx10::Operand; +using gfx10::Sop; +using gfx10::Valu; +using ir::EXEC; +using ir::Inst; +using ir::Program; +using ir::Reg; +using ir::Value; + +namespace detail { + +std::optional<std::uint32_t> inline_constant(std::uint8_t code) { return resource::inline_constant(code); } + +} // namespace detail + +using detail::inline_constant; + +std::optional<Op> op_of(std::string_view name) { + // the low dword of a 64-bit sum (`v_add_co_ci_u32` carries into the high one) is the 32-bit + // sum of the low dwords + if (name == "v_add_nc_u32" || name == "v_add_co_u32") return Op::AddU; + if (name == "v_add_f32") return Op::AddF; + if (name == "v_add_f16") return Op::AddH; + if (name == "v_min_u32") return Op::MinU; + if (name == "v_max_u32") return Op::MaxU; + if (name == "v_min_i32") return Op::MinI; + if (name == "v_max_i32") return Op::MaxI; + if (name == "v_min_f32") return Op::MinF; + if (name == "v_max_f32") return Op::MaxF; + if (name == "v_or_b32") return Op::Or; + if (name == "v_and_b32") return Op::And; + if (name == "v_xor_b32") return Op::Xor; + return std::nullopt; +} + +bool identity(Op op, std::uint32_t k) { + switch (op) { + case Op::AddU: + case Op::AddH: + case Op::Or: + case Op::Xor: + case Op::MaxU: return k == 0; + case Op::AddF: return k == 0 || k == 0x8000'0000u; + case Op::MinU: + case Op::And: return k == 0xFFFF'FFFFu; + case Op::MinI: return k == 0x7FFF'FFFFu; + case Op::MaxI: return k == 0x8000'0000u; + case Op::MinF: return k == 0x7F80'0000u; + case Op::MaxF: return k == 0xFF80'0000u; + } + return false; +} + +bool counts(Op op) { return op == Op::AddU || op == Op::AddF || op == Op::AddH || op == Op::Xor; } + +// Whether the lane sets `a` and `b` are the two halves of one aligned run of lanes: lanes 2k and +// 2k+1, then two such pairs side by side, and so on up to the two halves of the wave. Sums joined +// only that way form the balanced tree over the lanes in their order, whichever of the two a lane +// adds to the other (the addition is commutative). +bool buddies(std::uint64_t a, std::uint64_t b) { + const auto n = static_cast<std::uint32_t>(std::popcount(a)); + if (n != static_cast<std::uint32_t>(std::popcount(b)) || !std::has_single_bit(n) || n == 64) return false; + auto run = [n](std::uint64_t s) -> std::optional<std::uint32_t> { + const auto first = static_cast<std::uint32_t>(std::countr_zero(s)); + if (first % n == 0 && (s >> first) == (std::uint64_t{1} << n) - 1) return first; + return std::nullopt; + }; + const auto x = run(a); + const auto y = run(b); + if (!x || !y) return false; + const std::uint32_t lo = std::min(*x, *y); + const std::uint32_t diff = *x > *y ? *x - *y : *y - *x; + return lo % (2 * n) == 0 && diff == n; +} + +namespace { + +std::uint8_t saved_code(const Inst& inst) { + if (const auto* s = std::get_if<Sop>(&inst.fields); s && s->dst && s->dst->kind == Operand::Kind::Scalar) { + return s->dst->code; + } + return NULL_CODE; +} + +Sym combine(Op op, const Sym& a, const Sym& b) { + // (Sym::K(k), x) | (x, Sym::K(k)) if op.identity(k) => x: the guard is tried per alternative. + if (a.kind == Sym::K && identity(op, a.k)) return b; + if (b.kind == Sym::K && identity(op, b.k)) return a; + if (a.kind == Sym::Red && b.kind == Sym::Red && a.src == b.src && a.mask == b.mask && a.ident == b.ident && + identity(op, a.ident) && (!a.op || *a.op == op) && (!b.op || *b.op == op) && + (!counts(op) || (a.lanes & b.lanes) == 0) && (op != Op::AddH || buddies(a.lanes, b.lanes))) { + return Sym::red(op, a.src, a.mask, a.ident, a.lanes | b.lanes); + } + return Sym::unknown(); +} + +// The lane a `v_readlane_b32` names. +std::optional<std::uint32_t> lane_number(const Operand& op) { + switch (op.kind) { + case Operand::Kind::Const: return inline_constant(op.code); + case Operand::Kind::Literal: return op.literal; + default: return std::nullopt; + } +} + +// Values of the VGPRs and scalars written by this section, indexed by register. +using VecMap = std::map<Value, std::vector<Sym>>; +using UniMap = std::map<Value, Sym>; + +std::uint32_t reverse_bits(std::uint32_t x) { + std::uint32_t r = 0; + for (int i = 0; i < 32; ++i) { + r = (r << 1) | (x & 1); + x >>= 1; + } + return r; +} + +std::pair<VecMap, UniMap> simulate(std::span<const Inst> insts, std::uint32_t wave, Value saved) { + const std::uint64_t all = wave == 64 ? ~std::uint64_t{0} : std::uint64_t{0xFFFF'FFFFu}; + std::uint64_t exec = all; + VecMap vec; + UniMap uni; + const std::size_t W = wave; + // Masks the section derives from the saved EXEC (`s_and` with it). + std::vector<Value> masked{saved}; + auto is_masked = [&masked](Value v) { return std::find(masked.begin(), masked.end(), v) != masked.end(); }; + for (const Inst& inst : insts) { + const std::string_view name = inst.name(); + if (inst.write(Reg::S(EXEC))) { + // Constant lane sets (prefix sums); anything else ends what the simulation can follow. + std::optional<std::uint64_t> lo; + if (name.starts_with("s_mov_b")) lo = detail::constant(inst); + if (!lo) return {std::move(vec), std::move(uni)}; + const std::uint64_t k = *lo; + exec = (name == "s_mov_b64" ? k : (exec & ~std::uint64_t{0xFFFF'FFFFu}) | (k & 0xFFFF'FFFFu)) & all; + continue; + } + if (inst.write(Reg::S(static_cast<std::uint8_t>(EXEC + 1)))) { + std::optional<std::uint64_t> hi; + if (name.starts_with("s_mov_b")) hi = detail::constant(inst); + if (!hi) return {std::move(vec), std::move(uni)}; + const std::uint64_t k = *hi; + exec = ((exec & 0xFFFF'FFFFu) | ((k & 0xFFFF'FFFFu) << 32)) & all; + continue; + } + if (const auto* sop = std::get_if<Sop>(&inst.fields)) { + if (name.starts_with("s_and_b")) { + bool from_saved = false; + for (const Operand& o : sop->src) { + if (o.kind != Operand::Kind::Scalar) continue; + const auto v = inst.read(Reg::S(o.code)); + if (v && is_masked(*v)) { + from_saved = true; + break; + } + } + if (from_saved) { + for (const auto& w : inst.writes) { + if (w.first.is_s()) { + masked.push_back(w.second); + break; + } + } + } + } + if (name == "s_mov_b32" && sop->dst && sop->dst->kind == Operand::Kind::Scalar && !sop->src.empty() && + sop->dst->code != NULL_CODE) { + if (const auto w = inst.write(Reg::S(sop->dst->code))) { + const Operand& s0 = sop->src[0]; + Sym sym = Sym::unknown(); + if (s0.kind == Operand::Kind::Scalar && s0.code != NULL_CODE) { + if (const auto x = inst.read(Reg::S(s0.code))) { + const auto it = uni.find(*x); + sym = it != uni.end() ? it->second : Sym::uni(*x); + } + } else if (s0.kind == Operand::Kind::Const) { + if (const auto c = inline_constant(s0.code)) sym = Sym::konst(*c); + } else if (s0.kind == Operand::Kind::Literal) { + sym = Sym::konst(s0.literal); + } + uni.insert_or_assign(*w, sym); + } + } + for (const auto& w : inst.writes) uni.try_emplace(w.second, Sym::unknown()); + continue; + } + const auto* vp = std::get_if<Valu>(&inst.fields); + if (!vp) { + for (const auto& w : inst.writes) vec.insert_or_assign(w.second, std::vector<Sym>(W, Sym::unknown())); + continue; + } + const Valu& v = *vp; + auto lanes = [&](const Operand& op) -> std::vector<Sym> { + auto one = [W](const Sym& s) { return std::vector<Sym>(W, s); }; + if (op.kind == Operand::Kind::Vector) { + const auto x = inst.read(Reg::V(op.reg)); + if (!x) return one(Sym::unknown()); + const auto it = vec.find(*x); + if (it != vec.end()) return it->second; + return one(Sym::own(*x)); + } + if (op.kind == Operand::Kind::Scalar && op.code != NULL_CODE) { + const auto x = inst.read(Reg::S(op.code)); + if (!x) return one(Sym::unknown()); + const auto it = uni.find(*x); + return one(it != uni.end() ? it->second : Sym::uni(*x)); + } + if (op.kind == Operand::Kind::Const) { + const auto c = inline_constant(op.code); + return one(c ? Sym::konst(*c) : Sym::unknown()); + } + if (op.kind == Operand::Kind::Literal) return one(Sym::konst(op.literal)); + return one(Sym::unknown()); + }; + const bool modifiers = v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 || v.sdwa.has_value(); + if (name == "v_readlane_b32") { + if (!(v.dst && v.dst->kind == Operand::Kind::Scalar && v.src.size() >= 2)) continue; + const std::uint8_t code = v.dst->code; + const auto l = lane_number(v.src[1]); + const std::vector<Sym> x = lanes(v.src[0]); + if (const auto w = inst.write(Reg::S(code))) { + Sym s = Sym::unknown(); + if (l && *l < x.size()) s = x[*l]; + uni.insert_or_assign(*w, s); + } + continue; + } + if (name == "v_add_f64" && !modifiers && !v.dpp && v.dst && v.dst->kind == Operand::Kind::Vector) { + const std::uint8_t dreg = v.dst->reg; + const std::uint8_t dreg1 = static_cast<std::uint8_t>(dreg + 1); + const auto dst_lo = inst.write(Reg::V(dreg)); + const auto dst_hi = inst.write(Reg::V(dreg1)); + if (dst_lo && dst_hi) { + using Pair = std::pair<std::vector<Sym>, std::vector<Sym>>; + auto pair_lanes = [&](const Operand* op) -> std::optional<Pair> { + if (!op) return std::nullopt; + if (op->kind == Operand::Kind::Vector) { + auto first = lanes(Operand::Vector(op->reg, 1)); + auto second = lanes(Operand::Vector(static_cast<std::uint8_t>(op->reg + 1), 1)); + return Pair{std::move(first), std::move(second)}; + } + if (op->kind == Operand::Kind::Scalar && op->code != NULL_CODE) { + auto first = lanes(Operand::Scalar(op->code, 1)); + auto second = lanes(Operand::Scalar(static_cast<std::uint8_t>(op->code + 1), 1)); + return Pair{std::move(first), std::move(second)}; + } + return std::nullopt; + }; + const std::vector<Sym> old_lo = lanes(Operand::Vector(dreg, 1)); + const std::vector<Sym> old_hi = lanes(Operand::Vector(dreg1, 1)); + struct Term { + Value lo, hi, mask; + std::uint64_t lanes; + }; + auto f64_term = [](const Sym& lo_s, const Sym& hi_s) -> std::optional<Term> { + if (lo_s.kind == Sym::Red && !lo_s.op && lo_s.ident == 0 && hi_s.kind == Sym::Red && !hi_s.op && + hi_s.ident == 0 && lo_s.mask == hi_s.mask && lo_s.lanes == hi_s.lanes) { + return Term{lo_s.src, hi_s.src, lo_s.mask, lo_s.lanes}; + } + if (lo_s.kind == Sym::Red64F && !lo_s.high && hi_s.kind == Sym::Red64F && hi_s.high && + lo_s.src == hi_s.src && lo_s.hi == hi_s.hi && lo_s.mask == hi_s.mask && lo_s.lanes == hi_s.lanes) { + return Term{lo_s.src, lo_s.hi, lo_s.mask, lo_s.lanes}; + } + return std::nullopt; + }; + std::vector<Sym> out_lo(W, Sym::unknown()); + std::vector<Sym> out_hi(W, Sym::unknown()); + const auto a = pair_lanes(v.src.size() > 0 ? &v.src[0] : nullptr); + const auto b = pair_lanes(v.src.size() > 1 ? &v.src[1] : nullptr); + if (a && b) { + for (std::size_t l = 0; l < W; ++l) { + Sym rl = Sym::unknown(); + Sym rh = Sym::unknown(); + const auto ta = f64_term(a->first[l], a->second[l]); + const auto tb = f64_term(b->first[l], b->second[l]); + if (ta && tb && ta->lo == tb->lo && ta->hi == tb->hi && ta->mask == tb->mask && + (ta->lanes & tb->lanes) == 0) { + rl = Sym::red64f(ta->lo, ta->hi, ta->mask, ta->lanes | tb->lanes, false); + rh = Sym::red64f(ta->lo, ta->hi, ta->mask, ta->lanes | tb->lanes, true); + } + const bool on = ((exec >> l) & 1) != 0; + out_lo[l] = on ? rl : old_lo[l]; + out_hi[l] = on ? rh : old_hi[l]; + } + } + vec.insert_or_assign(*dst_lo, std::move(out_lo)); + vec.insert_or_assign(*dst_hi, std::move(out_hi)); + continue; + } + } + if (!(v.dst && v.dst->kind == Operand::Kind::Vector)) { + for (const auto& w : inst.writes) uni.insert_or_assign(w.second, Sym::unknown()); + continue; + } + const std::uint8_t dreg = v.dst->reg; + const auto dst_opt = inst.write(Reg::V(dreg)); + if (!dst_opt) continue; + const Value dst = *dst_opt; + const std::vector<Sym> old = lanes(Operand::Vector(dreg, 1)); + // src0 as each lane fetches it (DPP), with the lanes that write. + std::optional<std::vector<Sym>> src0; + if (!v.src.empty()) src0 = lanes(v.src[0]); + std::uint64_t writes = exec; + std::optional<std::vector<Sym>> fetched; + if (v.dpp && src0) { + if (exec != all) { + vec.insert_or_assign(dst, std::vector<Sym>(W, Sym::unknown())); + continue; + } + const std::vector<Sym>& s = *src0; + std::vector<Sym> f; + f.reserve(W); + bool ok = true; + for (std::uint32_t l = 0; l < wave; ++l) { + const auto d = detail::dpp_lane(*v.dpp, l); + if (d && std::get<0>(*d) < wave) { + const auto [src, zero, on] = *d; + f.push_back(zero ? Sym::konst(0) : s[src]); + if (!on) writes &= ~(std::uint64_t{1} << l); + } else { + ok = false; + } + } + if (ok) fetched = std::move(f); + } else if (!v.dpp && src0) { + fetched = *src0; + } + auto src = [&](std::size_t k) -> std::optional<std::vector<Sym>> { + if (k < v.src.size()) return lanes(v.src[k]); + return std::nullopt; + }; + std::vector<Sym> result; + if (modifiers || !fetched) { + result.assign(W, Sym::unknown()); + } else if (name == "v_mov_b32") { + result = std::move(*fetched); + } else if (name == "v_bfrev_b32") { + result.reserve(W); + for (const Sym& s : *fetched) { + result.push_back(s.kind == Sym::K ? Sym::konst(reverse_bits(s.k)) : Sym::unknown()); + } + } else if (name == "v_cndmask_b32") { + const std::vector<Sym>& a = *fetched; + std::optional<Value> mask; + if (v.src.size() > 2 && v.src[2].kind == Operand::Kind::Scalar) mask = inst.read(Reg::S(v.src[2].code)); + const std::vector<Sym> b = src(1).value_or(std::vector<Sym>{}); + result.reserve(W); + for (std::size_t l = 0; l < W; ++l) { + if (a[l].kind == Sym::K && l < b.size() && b[l].kind == Sym::Own && mask && is_masked(*mask)) { + result.push_back(Sym::red(std::nullopt, b[l].src, *mask, a[l].k, std::uint64_t{1} << l)); + } else { + result.push_back(Sym::unknown()); + } + } + } else if (name == "v_permlanex16_b32") { + const std::vector<Sym>& a = *fetched; + // Lanes of each row read the other row of their half; lane i's pick is nibble i of + // {src2, src1}. + auto sel = [&](std::size_t k) -> std::optional<std::uint32_t> { + if (k >= v.src.size()) return std::nullopt; + const Operand& o = v.src[k]; + if (o.kind == Operand::Kind::Const) return inline_constant(o.code); + if (o.kind == Operand::Kind::Literal) return o.literal; + return std::nullopt; + }; + const auto s1 = sel(1); + const auto s2 = sel(2); + if (s1 && s2) { + const std::uint64_t s = std::uint64_t{*s1} | (std::uint64_t{*s2} << 32); + result.reserve(W); + for (std::uint32_t l = 0; l < wave; ++l) { + const std::uint32_t other = (l & ~31u) | ((l & 16) ^ 16); + const auto pick = static_cast<std::uint32_t>((s >> (4 * (l & 15))) & 15); + result.push_back(a.at(other | pick)); + } + } else { + result.assign(W, Sym::unknown()); + } + } else if (name == "v_sub_nc_u32") { + const std::vector<Sym>& a = *fetched; + // A prefix sum less the lane's own term: the exclusive one. + const std::vector<Sym> b = src(1).value_or(std::vector<Sym>{}); + auto addu = [](const Sym& s) { + return s.kind == Sym::Red && (!s.op || *s.op == Op::AddU) && s.ident == 0; + }; + result.reserve(W); + for (std::size_t l = 0; l < W; ++l) { + if (addu(a[l]) && l < b.size() && addu(b[l]) && a[l].src == b[l].src && a[l].mask == b[l].mask && + (a[l].lanes & b[l].lanes) == b[l].lanes) { + const std::uint64_t rest = a[l].lanes & ~b[l].lanes; + result.push_back(rest == 0 ? Sym::konst(0) : Sym::red(Op::AddU, a[l].src, a[l].mask, 0, rest)); + } else { + result.push_back(Sym::unknown()); + } + } + } else { + const std::vector<Sym>& a = *fetched; + const auto op = op_of(name); + const auto b = src(1); + if (op && b) { + result.reserve(W); + for (std::size_t l = 0; l < W; ++l) result.push_back(combine(*op, a.at(l), b->at(l))); + } else { + result.assign(W, Sym::unknown()); + } + } + std::vector<Sym> merged; + merged.reserve(W); + for (std::size_t l = 0; l < W; ++l) merged.push_back(((writes >> l) & 1) != 0 ? result.at(l) : old.at(l)); + vec.insert_or_assign(dst, std::move(merged)); + } + return {std::move(vec), std::move(uni)}; +} + +// The shape of a scalar. +std::optional<Shape> single(const Sym& s, std::uint32_t wave) { + const std::uint64_t all = ~std::uint64_t{0} >> (64 - wave); + switch (s.kind) { + case Sym::K: return Shape::konst(s.k); + case Sym::Own: + case Sym::Uni: return Shape::value(s.src); + case Sym::Red: + if (s.op && s.lanes == all) return Shape::active(*s.op, s.src, s.mask, s.ident); + return std::nullopt; + case Sym::Red64F: + if (s.lanes == all) return Shape::active_f64(s.src, s.hi, s.mask, s.high); + return std::nullopt; + default: return std::nullopt; + } +} + +// The shape of each value, where every lane agrees on one. +std::map<Value, Shape> shapes(const VecMap& vec, const UniMap& uni, std::uint32_t wave) { + const std::uint64_t all = ~std::uint64_t{0} >> (64 - wave); + std::map<Value, Shape> out; + for (const auto& [v, s] : uni) { + if (const auto sh = single(s, wave)) out.insert_or_assign(v, *sh); + } + for (const auto& [v, lanes] : vec) { + if (const auto sh = detail::per_lane(lanes, all)) out.insert_or_assign(v, *sh); + } + return out; +} + +} // namespace + +namespace detail { + +std::optional<std::tuple<std::uint32_t, bool, bool>> dpp_lane(const gfx10::Dpp& d, std::uint32_t l) { + if (const auto* lanes = std::get_if<DppLanes>(&d)) { + return std::tuple{(l & ~7u) | ((lanes->sel >> (3 * (l & 7))) & 7), false, true}; + } + const auto& r = std::get<DppRow>(d); + const std::uint32_t row = l & ~15u; + const std::uint32_t pos = l & 15; + const std::uint32_t n = std::uint32_t(r.ctrl & 15); + const bool enabled = ((std::uint32_t(r.row_mask) >> ((l >> 4) & 3)) & 1) != 0 && + ((std::uint32_t(r.bank_mask) >> ((l >> 2) & 3)) & 1) != 0; + std::uint32_t src = 0; + bool inside = true; + const std::uint16_t ctrl = r.ctrl; + if (ctrl <= 0xFF) { + src = (l & ~3u) | ((std::uint32_t(ctrl) >> (2 * (l & 3))) & 3); + } else if (ctrl >= 0x101 && ctrl <= 0x10F) { + src = l + n; + inside = pos + n < 16; + } else if (ctrl >= 0x111 && ctrl <= 0x11F) { + src = l - n; // wrapping_sub + inside = pos >= n; + } else if (ctrl >= 0x121 && ctrl <= 0x12F) { + src = row | ((pos - n) & 15); + } else if (ctrl == 0x140) { + src = l ^ 15; + } else if (ctrl == 0x141) { + src = l ^ 7; + } else if (ctrl >= 0x150 && ctrl <= 0x15F) { + src = row | n; + } else if (ctrl >= 0x160 && ctrl <= 0x16F) { + src = l ^ n; + } else { + return std::nullopt; + } + if (inside) return std::tuple{src, false, enabled}; + if (r.bound_ctrl) return std::tuple{l, true, enabled}; + return std::tuple{l, false, false}; +} + +std::optional<std::uint64_t> constant(const Inst& inst) { + const auto* s = std::get_if<Sop>(&inst.fields); + if (!s || s->src.empty()) return std::nullopt; + const bool wide = inst.name() == "s_mov_b64"; + const Operand& o = s->src[0]; + if (o.kind == Operand::Kind::Scalar && o.code == NULL_CODE) return 0; + if (o.kind == Operand::Kind::Const && o.code >= 128 && o.code <= 208) { + const auto x = inline_constant(o.code); + if (!x) return std::nullopt; + if (wide) return static_cast<std::uint64_t>(static_cast<std::int64_t>(static_cast<std::int32_t>(*x))); + return std::uint64_t{*x}; + } + if (o.kind == Operand::Kind::Const && !wide) { + const auto x = inline_constant(o.code); + if (!x) return std::nullopt; + return std::uint64_t{*x}; + } + if (o.kind == Operand::Kind::Literal) return std::uint64_t{o.literal}; + return std::nullopt; +} + +std::optional<Shape> per_lane(std::span<const Sym> lanes, std::uint64_t all) { + if (lanes.empty()) bitcode::bug("wave::per_lane: no lanes"); + const Sym first = lanes[0]; + struct Own { + Value src, mask; + std::uint32_t ident; + bool operator==(const Own&) const = default; + }; + auto own = [](std::size_t l, const Sym& s) -> std::optional<Own> { + if (s.kind == Sym::Red && !s.op && s.lanes == (std::uint64_t{1} << l)) return Own{s.src, s.mask, s.ident}; + return std::nullopt; + }; + if (const auto m = own(0, first)) { + bool every = true; + for (std::size_t l = 0; l < lanes.size(); ++l) { + if (own(l, lanes[l]) != m) { + every = false; + break; + } + } + if (every) return Shape::masked(m->src, m->mask, m->ident); + } + if (std::all_of(lanes.begin(), lanes.end(), [&](const Sym& s) { return s == first; })) { + switch (first.kind) { + case Sym::K: return Shape::konst(first.k); + case Sym::Uni: + case Sym::Own: return Shape::value(first.src); + case Sym::Red: + if (first.op && first.lanes == all) return Shape::active(*first.op, first.src, first.mask, first.ident); + return std::nullopt; + case Sym::Red64F: + if (first.lanes == all) return Shape::active_f64(first.src, first.hi, first.mask, first.high); + return std::nullopt; + default: return std::nullopt; + } + } + // Prefixes: lane l holds lanes 0..l (exclusive) or 0..=l (inclusive). + struct Meta { + Value src, mask; + std::uint32_t ident; + bool inclusive; + bool operator==(const Meta&) const = default; + }; + std::optional<Meta> meta; + std::optional<Op> op_found; + for (std::size_t l = 0; l < lanes.size(); ++l) { + const Sym& s = lanes[l]; + const std::uint64_t bit = std::uint64_t{1} << l; + const std::uint64_t below = bit - 1; + if (s.kind != Sym::Red) { + // Lane 0 of an exclusive prefix holds the identity. + if (s.kind == Sym::K && l == 0) continue; + return std::nullopt; + } + const std::uint64_t set = s.lanes; + const bool inclusive = set == (below | bit); + if (!inclusive && set != below) return std::nullopt; + if (l == 0 && !inclusive) return std::nullopt; + if (!s.op && std::popcount(set) != 1) return std::nullopt; + const Meta lane_meta{s.src, s.mask, s.ident, inclusive}; + if (!meta) { + meta = lane_meta; + } else if (!(*meta == lane_meta)) { + return std::nullopt; + } + if (s.op) { + if (!op_found) { + op_found = *s.op; + } else if (*op_found != *s.op) { + return std::nullopt; + } + } + } + if (!meta || !op_found) return std::nullopt; + const Op op = *op_found; + if (!identity(op, meta->ident)) return std::nullopt; + const Sym& l0 = lanes[0]; + const bool ok = (l0.kind == Sym::K && !meta->inclusive && l0.k == meta->ident) || (l0.kind == Sym::Red && meta->inclusive); + if (!ok) return std::nullopt; + return Shape::prefix(op, meta->src, meta->mask, meta->ident, meta->inclusive); +} + +} // namespace detail + +std::unordered_map<std::size_t, Section> sections(const Program& p, std::size_t block) { + const std::vector<Inst>& insts = p.blocks.at(block).insts; + const std::uint32_t wave = p.wave64 ? 64 : 32; + std::unordered_map<std::size_t, Section> out; + std::size_t i = 0; + while (i < insts.size()) { + const Inst& inst = insts[i]; + const std::string_view name = inst.name(); + // EXEC becomes every lane: `s_or_saveexec -1` or `s_nand_saveexec 0`. + std::optional<Operand> all; + if (name == "s_or_saveexec_b64" || name == "s_or_saveexec_b32") { + all = Operand::Const(193); + } else if (name == "s_nand_saveexec_b64" || name == "s_nand_saveexec_b32") { + all = Operand::Const(128); + } + bool start = false; + if (all) { + if (const auto* s = std::get_if<Sop>(&inst.fields)) start = !s->src.empty() && s->src[0] == *all; + } + std::optional<Value> saved; + if (start) { + if (const auto* s = std::get_if<Sop>(&inst.fields); s && s->dst && s->dst->kind == Operand::Kind::Scalar) { + saved = inst.write(Reg::S(s->dst->code)); + } + } + if (!saved) { + ++i; + continue; + } + std::optional<std::size_t> end; + for (std::size_t j = i + 1; j < insts.size(); ++j) { + if (insts[j].write(Reg::S(EXEC)) && insts[j].read(Reg::S(saved_code(inst))) == saved) { + end = j; + break; + } + } + if (!end) break; + auto [vec, uni] = simulate(std::span<const Inst>(insts).subspan(i + 1, *end - (i + 1)), wave, *saved); + std::map<Value, Shape> reads; + for (std::size_t j = *end + 1; j < insts.size(); ++j) { + const Inst& later = insts[j]; + if (later.name() != "v_readlane_b32") continue; + const auto* v = std::get_if<Valu>(&later.fields); + if (!v || !v->dst || v->dst->kind != Operand::Kind::Scalar || v->src.size() != 2 || + v->src[0].kind != Operand::Kind::Vector) { + continue; + } + const std::uint8_t code = v->dst->code; + const auto x = later.read(Reg::V(v->src[0].reg)); + if (!x) continue; + const auto left = vec.find(*x); + if (left == vec.end()) continue; + const auto w = later.write(Reg::S(code)); + if (!w) continue; + const auto l = lane_number(v->src[1]); + if (!l || *l >= left->second.size()) continue; + const Sym sym = left->second[*l]; + // (a lane's own value stays a lane read) + if (sym.kind == Sym::Own) continue; + const auto shape = single(sym, wave); + if (!shape) continue; + reads.insert_or_assign(*w, *shape); + } + auto sh = shapes(vec, uni, wave); + out.insert_or_assign(i, Section{*end, std::move(sh), std::move(reads)}); + i = *end + 1; + } + return out; +} + +// `WaveActiveBitOr(v7)` into s7 as the console compiler expands it: every lane takes part, those +// outside the saved EXEC (s[4:5]) with 0. +const std::array<std::uint32_t, 20> WAVE_OR_V7_TO_S7 = { + 0xBE84'25C1, // s_or_saveexec_b64 s[4:5], -1 + 0xD501'0001, + 0x0012'0E80, // v_cndmask_b32 v1, 0, v7, s[4:5] + 0x3802'02E9, + 0xDE54'C101, // v_or_b32 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6] + 0x3802'02E9, + 0x9360'1201, // v_or_b32 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4] + 0x3802'02E9, + 0x0009'2401, // v_or_b32 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0] + 0x3802'02FA, + 0xFF09'4001, // v_or_b32 v1, v1, v1 row_mirror bound_ctrl:1 + 0xD778'0002, + 0x0201'0101, // v_permlanex16_b32 v2, v1, 0, 0 + 0x3802'0302, // v_or_b32 v1, v2, v1 + 0xD760'0007, + 0x0001'4101, // v_readlane_b32 s7, v1, 32 + 0x3802'0207, // v_or_b32 v1, s7, v1 + 0xD760'0007, + 0x0001'0101, // v_readlane_b32 s7, v1, 0 + 0xBEFE'0404, // s_mov_b64 exec, s[4:5] +}; + +} // namespace x2w::vs::wave diff --git a/src/x2w_shader/emit/wave.h b/src/x2w_shader/emit/wave.h new file mode 100644 index 0000000000..350cf2653c --- /dev/null +++ b/src/x2w_shader/emit/wave.h @@ -0,0 +1,174 @@ +#pragma once + +// Whole-wave sections: code between `s_or_saveexec -1` (or `s_nand_saveexec 0`) and the restore of the +// saved mask runs in every lane of the console's wave, the inactive ones included, which is how the +// compiler expands HLSL wave reductions and prefix sums. Each section is simulated on the console's lanes +// with symbolic values, and a value it leaves is lowered by what it turned out to be: the reduction or +// prefix of one operation over the lanes' (masked) inputs. + +#include <array> +#include <cstddef> +#include <cstdint> +#include <map> +#include <optional> +#include <span> +#include <string_view> +#include <tuple> +#include <unordered_map> + +#include "x2w_shader/ir.h" + +namespace x2w::vs::wave { + +// An associative operation and its identity. +enum class Op : std::uint8_t { + AddU, + AddF, + // A sum of 16-bit floats in the low halves (v_add_f16), each addition rounded to 16 bits: not + // associative, so only the balanced tree over the lanes in their order is followed (buddies). + AddH, + MinU, + MaxU, + MinI, + MaxI, + MinF, + MaxF, + Or, + And, + Xor, +}; + +// The operation a VALU instruction name stands for. +std::optional<Op> op_of(std::string_view name); +// Whether k leaves the other operand unchanged. +bool identity(Op op, std::uint32_t k); +// Counting a lane twice changes the result. +bool counts(Op op); + +// Whether the lane sets a and b are the two halves of one aligned run of lanes. +bool buddies(std::uint64_t a, std::uint64_t b); + +// A lane's value inside a section. Fields by kind: Unknown; K: k; Own: src (the lane's own value of a +// VGPR value from before the section); Uni: src (a uniform value from before the section); Red: op +// (nullopt: one lane), src, mask, ident, lanes (op over lanes of mask ? src : ident); Red64F: lo = src, +// hi, mask, lanes, high (low/high 32 bits of the f64 sum over lanes of mask ? f64(lo, hi) : 0.0). +struct Sym { + enum Kind : std::uint8_t { Unknown, K, Own, Uni, Red, Red64F }; + Kind kind = Unknown; + std::uint32_t k = 0; + std::optional<Op> op; + ir::Value src{}; + ir::Value hi{}; + ir::Value mask{}; + std::uint32_t ident = 0; + std::uint64_t lanes = 0; + bool high = false; + bool operator==(const Sym&) const = default; + + // Leave unused fields at their defaults so equality compares only relevant state. + static Sym unknown() { return Sym{}; } + static Sym konst(std::uint32_t k) { + Sym s; + s.kind = K; + s.k = k; + return s; + } + static Sym own(ir::Value v) { + Sym s; + s.kind = Own; + s.src = v; + return s; + } + static Sym uni(ir::Value v) { + Sym s; + s.kind = Uni; + s.src = v; + return s; + } + static Sym red(std::optional<Op> op, ir::Value src, ir::Value mask, std::uint32_t ident, std::uint64_t lanes) { + Sym s; + s.kind = Red; + s.op = op; + s.src = src; + s.mask = mask; + s.ident = ident; + s.lanes = lanes; + return s; + } + static Sym red64f(ir::Value lo, ir::Value hi, ir::Value mask, std::uint64_t lanes, bool high) { + Sym s; + s.kind = Red64F; + s.src = lo; + s.hi = hi; + s.mask = mask; + s.lanes = lanes; + s.high = high; + return s; + } +}; + +// What a value a section leaves holds in every lane. Fields by kind: K(k); Value(a); Masked(a = src, b = +// mask, ident): the lane's own mask ? src : ident; Active(op, a = src, b = mask, ident): op over every +// lane; ActiveF64(a = lo, b = hi, c = mask, flag = high): low/high 32 bits of the f64 sum over every lane; +// Prefix(op, a = src, b = mask, ident, flag = inclusive): op over the lanes below (inclusive: and +// including) each lane. +struct Shape { + enum Kind : std::uint8_t { K, Value, Masked, Active, ActiveF64, Prefix }; + Kind kind = K; + std::uint32_t k = 0; // K's constant; ident for Masked, Active, Prefix + Op op = Op::AddU; + ir::Value a{}; + ir::Value b{}; + ir::Value c{}; + bool flag = false; + bool operator==(const Shape&) const = default; + + static Shape konst(std::uint32_t k) { return Shape{K, k}; } + static Shape value(ir::Value v) { return Shape{Value, 0, Op::AddU, v}; } + static Shape masked(ir::Value src, ir::Value mask, std::uint32_t ident) { + return Shape{Masked, ident, Op::AddU, src, mask}; + } + static Shape active(Op op, ir::Value src, ir::Value mask, std::uint32_t ident) { + return Shape{Active, ident, op, src, mask}; + } + static Shape active_f64(ir::Value lo, ir::Value hi, ir::Value mask, bool high) { + return Shape{ActiveF64, 0, Op::AddU, lo, hi, mask, high}; + } + static Shape prefix(Op op, ir::Value src, ir::Value mask, std::uint32_t ident, bool inclusive) { + return Shape{Prefix, ident, op, src, mask, ir::Value{}, inclusive}; + } +}; + +// The section starting at instruction `start` of a block: its restore index and the shapes of the values it +// writes. +struct Section { + std::size_t end = 0; + std::map<ir::Value, Shape> shapes; + // What a v_readlane_b32 of one lane takes, later in the block, from a VGPR the section leaves + // (by the scalar it writes): the last lanes of a reduction hold it before the first do. + std::map<ir::Value, Shape> reads; +}; + +// Every whole-wave section of block, by start index. +std::unordered_map<std::size_t, Section> sections(const ir::Program& p, std::size_t block); + +// Test program words. +extern const std::array<std::uint32_t, 20> WAVE_OR_V7_TO_S7; + +// Internal declarations used by the tests, threading.cpp and own_bits.cpp. +namespace detail { + +// resource::inline_constant shared by wave analysis, threading and own_bits. +std::optional<std::uint32_t> inline_constant(std::uint8_t code); + +// The lane `l` reads with DPP, whether it reads 0 instead, and whether it writes; nullopt for +// patterns not modelled. +std::optional<std::tuple<std::uint32_t, bool, bool>> dpp_lane(const gfx10::Dpp& d, std::uint32_t l); +// The value an `s_mov_b32`/`s_mov_b64` to EXEC sets (its low dwords), if constant. +std::optional<std::uint64_t> constant(const ir::Inst& inst); +// The shape of a VGPR value from its lanes, where every lane agrees on one. +std::optional<Shape> per_lane(std::span<const Sym> lanes, std::uint64_t all); + +} // namespace detail + +} // namespace x2w::vs::wave diff --git a/src/x2w_shader/error.h b/src/x2w_shader/error.h new file mode 100644 index 0000000000..d1482884e1 --- /dev/null +++ b/src/x2w_shader/error.h @@ -0,0 +1,65 @@ +// Shared ShaderError declaration for the shader module headers included by lib.h. +#pragma once + +#include <cstddef> +#include <cstdint> +#include <exception> +#include <optional> +#include <string> +#include <utility> + +namespace x2w::vs { + +// The reason field stores static text for malformed input, ISA decoding errors and unsupported +// instructions. Compare its contents. +struct ShaderError : std::exception { + enum class Kind : std::uint8_t { NotDxbc, Malformed, Isa, Unsupported }; + + Kind kind = Kind::NotDxbc; + std::size_t offset = 0; // Isa, Unsupported + const char* reason = ""; // Malformed, Isa, Unsupported + + static ShaderError not_dxbc(); + static ShaderError malformed(const char* why); + static ShaderError isa(std::size_t offset, const char* reason); + static ShaderError unsupported(std::size_t offset, const char* what); + + // User-facing diagnostics: "not a DXBC container" / "malformed shader: {0}" / "GFX10 code at {offset:#x}: + // {reason}" / "GFX10 code at {offset:#x}: {what} is not supported" + std::string to_string() const; + // Diagnostic form, for example Isa { offset: 4, reason: "..." }. + std::string debug() const; + const char* what() const noexcept override; + + bool operator==(const ShaderError& o) const; + +private: + std::string text_; // to_string(), for what() + void fill(); +}; + +// Call f and catch ShaderError. +template <class F> +auto try_shader(F&& f) -> std::optional<decltype(f())> { + try { + return f(); + } catch (const ShaderError&) { + return std::nullopt; + } +} + +// The ShaderError `f()` throws, if any (`f` returns void or anything). +template <class F> +std::optional<ShaderError> catch_shader_error(F&& f) { + try { + f(); + } catch (const ShaderError& e) { + return e; + } + return std::nullopt; +} + +// `{:#x}` of a usize: "0x1f", "0x0". +std::string hex_alt(std::uint64_t v); + +} // namespace x2w::vs diff --git a/src/x2w_shader/front/CMakeLists.txt b/src/x2w_shader/front/CMakeLists.txt new file mode 100644 index 0000000000..e2a6bf87cb --- /dev/null +++ b/src/x2w_shader/front/CMakeLists.txt @@ -0,0 +1,76 @@ +# Shader front-end modules (native, io, resource, spill, structure, bvh) and +# their tests. Usable on its own (cmake -S src/x2w_shader/front -B out/build/vs-front) or through +# add_subdirectory from a parent that defines the vs-core library. +# +# Standalone, the vs-core sources (lib, dxbc, dxil, ir, gfx10) are compiled from X2W_VS_CORE_DIR +# (default: this tree's src/x2w_shader); a parent can instead set X2W_VS_CORE_TARGET to its library. +cmake_minimum_required(VERSION 3.21) +if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) + project(x2w_vs_front LANGUAGES CXX) + enable_testing() +endif() + +get_filename_component(x2w_vs_front_src "${CMAKE_CURRENT_SOURCE_DIR}/../.." ABSOLUTE) +get_filename_component(x2w_vs_front_root "${x2w_vs_front_src}/.." ABSOLUTE) +set(x2w_vs_front_dir "${x2w_vs_front_src}/x2w_shader") +set(x2w_vs_front_tests "${x2w_vs_front_root}/tests/x2w_shader") + +function(x2w_vs_front_options target) + target_include_directories(${target} PUBLIC "${x2w_vs_front_src}") + target_compile_features(${target} PUBLIC cxx_std_20) + if(MSVC) + # /fp:precise keeps multiply and add as separate operations. + target_compile_options(${target} PRIVATE /W4 /permissive- /utf-8 /EHsc /fp:precise) + target_compile_definitions(${target} PUBLIC _CRT_SECURE_NO_WARNINGS NOMINMAX) + else() + target_compile_options(${target} PRIVATE -ffp-contract=off) + endif() +endfunction() + +set(X2W_VS_CORE_TARGET "" CACHE STRING "Library target with the vs-core modules (empty: build them here)") +set(X2W_VS_CORE_DIR "${x2w_vs_front_dir}" CACHE PATH "Directory with the vs-core sources") +if(X2W_VS_CORE_TARGET) + set(x2w_vs_front_core ${X2W_VS_CORE_TARGET}) +else() + add_library(x2w_vs_front_core STATIC + "${X2W_VS_CORE_DIR}/lib.cpp" + "${X2W_VS_CORE_DIR}/dxbc.cpp" + "${X2W_VS_CORE_DIR}/dxil.cpp" + "${X2W_VS_CORE_DIR}/ir.cpp" + "${X2W_VS_CORE_DIR}/gfx10/fields.cpp" + "${X2W_VS_CORE_DIR}/gfx10/mod.cpp" + "${X2W_VS_CORE_DIR}/gfx10/opcodes.cpp" + "${X2W_VS_CORE_DIR}/gfx10/sp3.cpp" + ) + # The vs-core headers come from this tree; only the sources from X2W_VS_CORE_DIR. + target_include_directories(x2w_vs_front_core BEFORE PUBLIC "${x2w_vs_front_src}") + x2w_vs_front_options(x2w_vs_front_core) + set(x2w_vs_front_core x2w_vs_front_core) +endif() + +add_library(x2w_vs_front STATIC + "${x2w_vs_front_dir}/bvh.cpp" + "${x2w_vs_front_dir}/native.cpp" + "${x2w_vs_front_dir}/structure.cpp" + "${x2w_vs_front_dir}/spill.cpp" + "${x2w_vs_front_dir}/io.cpp" + "${x2w_vs_front_dir}/resource.cpp" +) +x2w_vs_front_options(x2w_vs_front) +target_link_libraries(x2w_vs_front PUBLIC ${x2w_vs_front_core}) + +# A test executable from tests/x2w_shader/<name>.cpp. +function(x2w_vs_front_test name) + add_executable(x2w_${name} "${x2w_vs_front_tests}/${name}.cpp") + x2w_vs_front_options(x2w_${name}) + target_link_libraries(x2w_${name} PRIVATE x2w_vs_front) + target_include_directories(x2w_${name} PRIVATE "${x2w_vs_front_tests}") + add_test(NAME x2w_${name} COMMAND x2w_${name}) +endfunction() + +x2w_vs_front_test(vs_bvh_test) +x2w_vs_front_test(vs_native_test) +x2w_vs_front_test(vs_structure_test) +x2w_vs_front_test(vs_spill_test) +x2w_vs_front_test(vs_io_test) +x2w_vs_front_test(vs_resource_test) diff --git a/src/x2w_shader/front_hash.h b/src/x2w_shader/front_hash.h new file mode 100644 index 0000000000..e96a88e045 --- /dev/null +++ b/src/x2w_shader/front_hash.h @@ -0,0 +1,38 @@ +// Hashers for SSA values, sites and pairs use the FxHash multiply-rotate step. Tables are used for lookup +// or collected in a stable order before their contents affect output. +#pragma once + +#include <cstddef> +#include <cstdint> +#include <utility> + +#include "x2w_shader/ir.h" + +namespace x2w::vs::fhash { + +constexpr std::uint64_t mix(std::uint64_t h, std::uint64_t n) +{ + return (((h << 5) | (h >> 59)) ^ n) * 0x517c'c1b7'2722'0a95ull; +} + +struct ValueHash { + std::size_t operator()(ir::Value v) const { return static_cast<std::size_t>(mix(0, v.n)); } +}; + +// (Value, Value): a lane mask by its dwords. +struct ValuePairHash { + std::size_t operator()(const std::pair<ir::Value, ir::Value>& k) const + { + return static_cast<std::size_t>(mix(mix(0, k.first.n), k.second.n)); + } +}; + +// (block, instruction). +struct SiteHash { + std::size_t operator()(const std::pair<std::size_t, std::size_t>& s) const + { + return static_cast<std::size_t>(mix(mix(0, s.first), s.second)); + } +}; + +} // namespace x2w::vs::fhash diff --git a/src/x2w_shader/gfx10/fields.cpp b/src/x2w_shader/gfx10/fields.cpp new file mode 100644 index 0000000000..b0485ae8a2 --- /dev/null +++ b/src/x2w_shader/gfx10/fields.cpp @@ -0,0 +1,576 @@ +// Operand fields of GFX10 instructions, by encoding. +#include <algorithm> +#include <bit> + +#include "x2w_shader/gfx10/mod.h" + +namespace x2w::vs::gfx10 { + +namespace { + +constexpr std::uint8_t VCC = 106; +constexpr std::uint8_t EXEC = 126; + +// VOP3-only opcodes that take two sources (the rest take three). +constexpr std::string_view VOP3_TWO_SOURCES[] = { + "v_add_f64", + "v_mul_f64", + "v_min_f64", + "v_max_f64", + "v_ldexp_f64", + "v_mul_lo_u32", + "v_mul_hi_u32", + "v_mul_lo_i32", + "v_mul_hi_i32", + "v_trig_preop_f64", + "v_lshlrev_b64", + "v_lshrrev_b64", + "v_ashrrev_i64", + "v_add_nc_u16", + "v_sub_nc_u16", + "v_mul_lo_u16", + "v_lshrrev_b16", + "v_ashrrev_i16", + "v_max_u16", + "v_max_i16", + "v_min_u16", + "v_min_i16", + "v_add_nc_i16", + "v_sub_nc_i16", + "v_add_co_u32", + "v_sub_co_u32", + "v_subrev_co_u32", + "v_pack_b32_f16", + "v_cvt_pknorm_i16_f16", + "v_cvt_pknorm_u16_f16", + "v_lshlrev_b16", + "v_interp_p1ll_f16", + "v_readlane_b32", + "v_writelane_b32", + "v_ldexp_f32", + "v_bfm_b32", + "v_bcnt_u32_b32", + "v_mbcnt_lo_u32_b32", + "v_mbcnt_hi_u32_b32", + "v_cvt_pknorm_i16_f32", + "v_cvt_pknorm_u16_f32", + "v_cvt_pk_u16_u32", + "v_cvt_pk_i16_i32", + "v_sub_nc_i32", + "v_add_nc_i32", +}; + +// VOP3 opcodes whose bits 14:8 hold a scalar destination instead of `abs`/`opsel`. +constexpr std::string_view VOP3B[] = { + "v_add_co_u32", + "v_sub_co_u32", + "v_subrev_co_u32", + "v_add_co_ci_u32", + "v_sub_co_ci_u32", + "v_subrev_co_ci_u32", + "v_div_scale_f32", + "v_div_scale_f64", + "v_mad_u64_u32", + "v_mad_i64_i32", +}; + +template <std::size_t N> +bool in(const std::string_view (&list)[N], std::string_view name) { + return std::find(std::begin(list), std::end(list), name) != std::end(list); +} + +bool is_any(std::string_view name, std::initializer_list<std::string_view> list) { + return std::find(list.begin(), list.end(), name) != list.end(); +} + +std::vector<std::string_view> split(std::string_view s, char sep) { + std::vector<std::string_view> out; + std::size_t start = 0; + for (;;) { + std::size_t at = s.find(sep, start); + if (at == std::string_view::npos) { + out.push_back(s.substr(start)); + return out; + } + out.push_back(s.substr(start, at - start)); + start = at + 1; + } +} + +constexpr bool bit(std::uint32_t word, std::uint32_t n) { return ((word >> n) & 1) != 0; } + +Operand scalar(std::uint8_t code, std::uint8_t dwords) { return Operand::Scalar(code, dwords); } + +// the low 8 bits. +Operand vector(std::uint32_t reg, std::uint8_t dwords) { return Operand::Vector(std::uint8_t(reg), dwords); } + +// A 9-bit source field (8-bit scalar fields are the same codes below 256). +Operand source(std::uint32_t code, std::uint8_t dwords, std::uint32_t literal) { + if (code <= 127) return scalar(std::uint8_t(code), dwords); + if (code == 255) return Operand::Literal(literal); + if (code >= 256) return vector(code - 256, dwords); + return Operand::Const(std::uint8_t(code)); +} + +// VALU destinations that are SGPRs. +Operand valu_dst(std::string_view name, std::uint32_t field, std::uint8_t dwords) { + if (name == "v_readlane_b32" || name == "v_readfirstlane_b32") return scalar(std::uint8_t(field), 1); + return vector(field, dwords); +} + +// Dwords of a type suffix such as `b64` or `f32`. +std::uint8_t type_dwords(std::string_view token) { + return is_any(token, {"b64", "u64", "i64", "f64"}) ? 2 : 1; +} + +struct Salu { + std::uint8_t dst, src0, src1; +}; + +// (sdst, ssrc0, ssrc1) dwords of a scalar ALU opcode. +Salu salu_dwords(std::string_view name) { + if (is_any(name, {"s_lshl_b64", "s_lshr_b64", "s_ashr_i64", "s_bfe_u64", "s_bfe_i64", "s_bitcmp0_b64", + "s_bitcmp1_b64"})) { + return {2, 2, 1}; + } + if (is_any(name, {"s_bfm_b64", "s_bitset0_b64", "s_bitset1_b64", "s_bitreplicate_b64_b32"})) return {2, 1, 1}; + if (is_any(name, {"s_bcnt0_i32_b64", "s_bcnt1_i32_b64", "s_ff0_i32_b64", "s_ff1_i32_b64", "s_flbit_i32_b64", + "s_flbit_i32_i64"})) { + return {1, 2, 2}; + } + std::size_t at = name.rfind('_'); + std::uint8_t n = type_dwords(at == std::string_view::npos ? name : name.substr(at + 1)); + return {n, n, n}; +} + +struct ValuDwords { + std::uint8_t dst; + std::array<std::uint8_t, 3> src; +}; + +// (vdst, [src0, src1, src2]) dwords of a VALU opcode. +ValuDwords valu_dwords(std::string_view name) { + if (is_any(name, {"v_lshlrev_b64", "v_lshrrev_b64", "v_ashrrev_i64"})) return {2, {1, 2, 2}}; + if (is_any(name, {"v_ldexp_f64", "v_trig_preop_f64", "v_cmp_class_f64", "v_cmpx_class_f64"})) { + return {2, {2, 1, 2}}; + } + if (is_any(name, {"v_mad_u64_u32", "v_mad_i64_i32"})) return {2, {1, 1, 2}}; + if (is_any(name, {"v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8"})) return {2, {2, 1, 2}}; + if (name == "v_mqsad_u32_u8") return {4, {2, 1, 4}}; + if (name == "v_frexp_exp_i32_f64") return {1, {2, 2, 2}}; + auto parts = split(name, '_'); + if (parts.size() == 4 && parts[1] == "cvt") { + std::uint8_t s = type_dwords(parts[3]); + return {type_dwords(parts[2]), {s, s, s}}; + } + std::uint8_t n = type_dwords(parts.back()); + return {n, {n, n, n}}; +} + +// Dwords of loaded, stored or atomic data, from the opcode name. +std::uint8_t data_dwords(std::string_view name) { + std::uint8_t n = 1; + for (std::string_view token : split(name, '_')) { + if (is_any(token, {"dwordx2", "x2", "xy", "b64", "u64", "i64", "f64"})) { + n = 2; + } else if (is_any(token, {"dwordx3", "xyz", "b96"})) { + n = 3; + } else if (is_any(token, {"dwordx4", "xyzw", "b128"})) { + n = 4; + } else if (token == "dwordx8") { + n = 8; + } else if (token == "dwordx16") { + n = 16; + } + } + if (name.find("cmpswap") != std::string_view::npos) n = std::uint8_t(n * 2); + if (name.find("format_d16") != std::string_view::npos) n = std::uint8_t((n + 1) / 2); + return n; +} + +// Address dwords of an image opcode: offset, bias, compare, derivatives, coordinates, then +// LOD/clamp/mip, packed in pairs with `a16`. +std::uint8_t image_addr_dwords(std::string_view name, std::uint8_t dim, bool a16) { + // (coordinates, derivatives per direction) for 1D 2D 3D CUBE 1D_ARRAY 2D_ARRAY 2D_MSAA + // 2D_MSAA_ARRAY. + static constexpr std::uint8_t DIMS[8][2] = {{1, 1}, {2, 2}, {3, 3}, {3, 2}, {2, 1}, {3, 2}, {3, 2}, {4, 2}}; + std::uint8_t coords = DIMS[dim & 7][0], grads = DIMS[dim & 7][1]; + if (name == "image_bvh_intersect_ray") return a16 ? 8 : 11; + if (name == "image_bvh64_intersect_ray") return a16 ? 9 : 12; + if (name == "image_get_resinfo") return 1; + unsigned whole = 0, derivs = 0, packed = coords; + std::optional<std::string_view> rest; + if (name.starts_with("image_sample")) { + rest = name.substr(std::string_view("image_sample").size()); + } else if (name.starts_with("image_gather4")) { + rest = name.substr(std::string_view("image_gather4").size()); + } + if (rest) { + for (std::string_view token : split(*rest, '_')) { + if (is_any(token, {"o", "b", "c"})) { + whole += 1; + } else if (is_any(token, {"d", "cd"})) { + derivs = grads; + } else if (is_any(token, {"l", "cl"})) { + packed += 1; + } + } + } else if (name.find("_mip") != std::string_view::npos) { + packed += 1; + } + if (a16) return std::uint8_t(whole + 2 * ((derivs + 1) / 2) + (packed + 1) / 2); + return std::uint8_t(whole + 2 * derivs + packed); +} + +} // namespace + +bool ds_pair(std::string_view name) { + for (std::string_view t : split(name, '_')) { + if (t.starts_with("read2") || t.starts_with("write2") || t.starts_with("wrxchg2")) return true; + } + return false; +} + +Fields Instruction::fields(bool wave64) const { + std::string_view name = this->name().value_or(""); + auto w = [&](std::size_t i) -> std::uint32_t { return i < words.size() ? words[i] : 0; }; + std::uint32_t w0 = w(0), w1 = w(1); + auto cache = [](bool glc, bool slc, bool dlc) { return Cache{glc, slc, dlc}; }; + switch (encoding) { + case Encoding::Sop2: + case Encoding::Sop1: + case Encoding::Sopc: { + Salu d = salu_dwords(name); + Operand sdst = scalar(std::uint8_t((w0 >> 16) & 0x7F), d.dst); + auto ssrc = [&](std::uint32_t shift, std::uint8_t dwords) { return source((w0 >> shift) & 0xFF, dwords, w1); }; + Sop s; + if (encoding == Encoding::Sop2) { + s.dst = sdst; + s.src = {ssrc(0, d.src0), ssrc(8, d.src1)}; + } else if (encoding == Encoding::Sopc) { + s.src = {ssrc(0, d.src0), ssrc(8, d.src1)}; + } else if (name == "s_getpc_b64") { + s.dst = sdst; + } else if (name == "s_setpc_b64" || name == "s_rfe_b64") { + s.src = {ssrc(0, d.src0)}; + } else { + s.dst = sdst; + s.src = {ssrc(0, d.src0)}; + } + return s; + } + case Encoding::Sopk: { + Operand sdst = scalar(std::uint8_t((w0 >> 16) & 0x7F), std::uint8_t(1 + (name == "s_call_b64" ? 1 : 0))); + Sop s; + if (name == "s_setreg_imm32_b32") { + s.src = {Operand::Literal(w1)}; + } else if (name == "s_version") { + } else if (name.starts_with("s_cmpk_") || name.starts_with("s_waitcnt_") || name == "s_setreg_b32") { + s.src = {sdst}; + } else { + s.dst = sdst; + } + s.imm = std::uint16_t(w0); + return s; + } + case Encoding::Sopp: + return Sopp{std::uint16_t(w0)}; + case Encoding::Smem: { + std::uint8_t sdata = std::uint8_t((w0 >> 6) & 0x7F); + // s_atc_probe*: SDATA is a 7-bit immediate, not an SGPR. The buffer form's resource is 4 + // dwords. GLC and DLC are not operands. + bool probe = name == "s_atc_probe" || name == "s_atc_probe_buffer"; + Smem s; + if (probe) { + s.data = Operand::Literal(sdata); + } else if (is_any(name, {"s_gl1_inv", "s_dcache_inv", "s_dcache_wb"}) || name.starts_with("s_dcache_discard")) { + } else if (name == "s_memtime" || name == "s_memrealtime") { + s.data = scalar(sdata, 2); + } else { + s.data = scalar(sdata, data_dwords(name)); + } + std::uint8_t base = + std::uint8_t(2 + 2 * ((name.starts_with("s_buffer_") || name == "s_atc_probe_buffer") ? 1 : 0)); + s.base = scalar(std::uint8_t((w0 & 0x3F) << 1), base); + s.offset = std::int32_t(w1 << 11) >> 11; + s.soffset = scalar(std::uint8_t(w1 >> 25), 1); + s.cache = probe ? Cache{} : cache(bit(w0, 16), false, bit(w0, 14)); + return s; + } + case Encoding::Vop1: + case Encoding::Vop2: + case Encoding::Vopc: + case Encoding::Vop3: + case Encoding::Vop3p: + return valu(name, wave64 ? 2 : 1); + case Encoding::Vintrp: { + std::uint8_t vsrc = std::uint8_t(w0 & 0xFF); + Vintrp v; + v.dst = vector(w0 >> 18, 1); + v.src = name == "v_interp_mov_f32" ? Operand::Const(vsrc) : vector(vsrc, 1); + v.attr = Operand::Attr(std::uint8_t((w0 >> 10) & 0x3F), std::uint8_t((w0 >> 8) & 3), false); + return v; + } + case Encoding::Ds: { + std::uint8_t ty = data_dwords(name); + bool pair = ds_pair(name); + bool returns = name.find("read") != std::string_view::npos || name.find("_rtn") != std::string_view::npos || + is_any(name, {"ds_swizzle_b32", "ds_permute_b32", "ds_bpermute_b32", "ds_append", + "ds_consume", "ds_ordered_count"}); + bool no_addr = name.starts_with("ds_gws") || name.find("addtid") != std::string_view::npos || + is_any(name, {"ds_nop", "ds_append", "ds_consume"}); + unsigned data; + if (name.find("read") != std::string_view::npos || name.find("src2") != std::string_view::npos || + is_any(name, {"ds_swizzle_b32", "ds_nop", "ds_append", "ds_consume", "ds_ordered_count", + "ds_gws_sema_v", "ds_gws_sema_p", "ds_gws_sema_release_all"})) { + data = 0; + } else if (pair || name.find("cmpst") != std::string_view::npos || name.find("mskor") != std::string_view::npos) { + data = 2; + } else { + data = 1; + } + Ds d; + if (returns) d.dst = vector(w1 >> 24, std::uint8_t(ty * (1 + (pair ? 1 : 0)))); + if (!no_addr) d.addr = vector(w1 & 0xFF, 1); + for (unsigned i = 0; i < data; ++i) d.data.push_back(vector((w1 >> (8 + 8 * i)) & 0xFF, ty)); + d.offset0 = std::uint8_t(w0); + d.offset1 = std::uint8_t(w0 >> 8); + d.gds = bit(w0, 17); + return d; + } + case Encoding::Mubuf: + case Encoding::Mtbuf: { + bool offen = bit(w0, 12), idxen = bit(w0, 13), tfe = bit(w1, 23); + bool mtbuf = encoding == Encoding::Mtbuf; + Buffer b; + if (!name.ends_with("_inv")) { + b.data = vector((w1 >> 8) & 0xFF, std::uint8_t(data_dwords(name) + (tfe ? 1 : 0))); + } + b.addr = vector(w1 & 0xFF, std::uint8_t(1 + ((offen && idxen) ? 1 : 0))); + b.rsrc = scalar(std::uint8_t(((w1 >> 16) & 0x1F) << 2), 4); + b.soffset = source(w1 >> 24, 1, 0); + b.offset = std::uint16_t(w0 & 0xFFF); + b.offen = offen; + b.idxen = idxen; + if (mtbuf) b.format = std::uint8_t((w0 >> 19) & 0x7F); + b.lds = !mtbuf && bit(w0, 16); + b.tfe = tfe; + b.cache = cache(bit(w0, 14), bit(w1, 22), bit(w0, 15)); + return b; + } + case Encoding::Mimg: { + std::uint8_t dim = std::uint8_t((w0 >> 3) & 7), dmask = std::uint8_t((w0 >> 8) & 0xF); + bool a16 = bit(w1, 30), d16 = bit(w1, 31); + bool r128 = bit(w0, 15), tfe = bit(w0, 16), lwe = bit(w0, 17); + std::uint8_t data = name.starts_with("image_gather4") + ? 4 + : std::uint8_t(std::max(std::popcount(unsigned(dmask)), 1)); + if (d16) data = std::uint8_t((data + 1) / 2); + std::uint8_t count = image_addr_dwords(name, dim, a16); + Image im; + if (((w0 >> 1) & 3) == 0) { + im.addr = {vector(w1 & 0xFF, count)}; + } else { + // NSA: one VGPR per address, the first in dword 1, the rest in the extra dwords. + for (std::size_t i = 0; i < count; ++i) { + if (i == 0) { + im.addr.push_back(vector(w1 & 0xFF, 1)); + } else { + im.addr.push_back(vector((w(2 + (i - 1) / 4) >> (8 * ((i - 1) % 4))) & 0xFF, 1)); + } + } + } + bool sampled = name.starts_with("image_sample") || name.starts_with("image_gather4") || + name.starts_with("image_get_lod"); + im.data = vector((w1 >> 8) & 0xFF, std::uint8_t(data + ((tfe || lwe) ? 1 : 0))); + im.rsrc = scalar(std::uint8_t(((w1 >> 16) & 0x1F) << 2), r128 ? 4 : 8); + if (sampled) im.sampler = scalar(std::uint8_t(((w1 >> 21) & 0x1F) << 2), 4); + im.dmask = dmask; + im.dim = dim; + im.unorm = bit(w0, 12); + im.r128 = r128; + im.a16 = a16; + im.d16 = d16; + im.tfe = tfe; + im.lwe = lwe; + im.cache = cache(bit(w0, 13), bit(w0, 25), bit(w0, 7)); + return im; + } + case Encoding::Flat: + case Encoding::Global: + case Encoding::Scratch: { + std::uint8_t saddr = std::uint8_t((w1 >> 16) & 0x7F); + bool glc = bit(w0, 16); + std::uint8_t n = data_dwords(name); + bool load = name.find("_load_") != std::string_view::npos; + bool atomic = name.find("_atomic_") != std::string_view::npos; + Flat f; + if (encoding == Encoding::Flat) { + f.addr = vector(w1 & 0xFF, 2); + } else if (encoding == Encoding::Global) { + f.addr = vector(w1 & 0xFF, std::uint8_t(1 + (saddr == NULL_CODE ? 1 : 0))); + } else if (saddr == NULL_CODE) { + // With an SGPR base, scratch takes no VGPR. + f.addr = vector(w1 & 0xFF, 1); + } + std::uint8_t ret = (atomic && name.find("cmpswap") != std::string_view::npos) ? std::uint8_t(n / 2) : n; + if (load || (atomic && glc)) f.dst = vector(w1 >> 24, ret); + if (!load) f.data = vector((w1 >> 8) & 0xFF, n); + if (encoding != Encoding::Flat) { + f.saddr = scalar(saddr, std::uint8_t(1 + (encoding == Encoding::Global ? 1 : 0))); + } + // GFX10 FLAT offsets are 11-bit and unsigned: the hardware ignores bit 11. + f.offset = encoding == Encoding::Flat ? std::int16_t(w0 & 0x7FF) + : std::int16_t(std::int16_t(std::uint16_t(w0 << 4)) >> 4); + f.lds = bit(w0, 13); + f.cache = cache(glc, bit(w0, 17), bit(w0, 12)); + return f; + } + case Encoding::Exp: { + bool compr = bit(w0, 10); + Exp e; + e.target = std::uint8_t((w0 >> 4) & 0x3F); + for (std::uint32_t i = 0; i < 4; ++i) { + std::uint32_t slot = compr ? i / 2 : i; + if (bit(w0, i)) e.src[i] = vector((w1 >> (8 * slot)) & 0xFF, 1); + } + e.compr = compr; + e.done = bit(w0, 11); + e.vm = bit(w0, 12); + return e; + } + } + return Sopp{}; +} + +Valu Instruction::valu(std::string_view name, std::uint8_t lanes) const { + // No operands; the console compiler stores a shader hash in their fields. + if (is_any(name, {"v_nop", "v_pipeflush", "v_clrexcp"})) return Valu{}; + auto w = [&](std::size_t i) -> std::uint32_t { return i < words.size() ? words[i] : 0; }; + std::uint32_t w0 = w(0); + ValuDwords n = valu_dwords(name); + bool compare = encoding == Encoding::Vopc || (encoding == Encoding::Vop3 && opcode < 0x100); + bool vop3b = in(VOP3B, name); + bool carry_in = name.ends_with("_co_ci_u32") || name == "v_cndmask_b32"; + Valu v; + switch (encoding) { + case Encoding::Vop1: + case Encoding::Vop2: + case Encoding::Vopc: { + std::uint32_t ext = w(1); + std::uint32_t src0 = w0 & 0x1FF; + std::uint32_t vsrc1 = 256 + ((w0 >> 9) & 0xFF); + std::uint32_t src1 = vsrc1; + if (src0 == 0xF9) { + Sdwa sdwa; + sdwa.dst_sel = std::uint8_t((ext >> 8) & 7); + sdwa.dst_unused = std::uint8_t((ext >> 11) & 3); + sdwa.src_sel = {std::uint8_t((ext >> 16) & 7), std::uint8_t((ext >> 24) & 7)}; + sdwa.sext = std::uint8_t(((ext >> 19) & 1) | ((ext >> 26) & 2)); + // The s0/s1 bits select an SGPR or constant instead of a VGPR. + src0 = (ext & 0xFF) | (((ext >> 23) & 1) == 0 ? 256u : 0u); + if (ext >> 31 == 1) src1 = vsrc1 - 256; + v.neg = std::uint8_t(((ext >> 20) & 1) | ((ext >> 27) & 2)); + v.abs = std::uint8_t(((ext >> 21) & 1) | ((ext >> 28) & 2)); + if (compare) { + if (((ext >> 15) & 1) == 1) v.dst = scalar(std::uint8_t((ext >> 8) & 0x7F), lanes); + Sdwa c = sdwa; + c.dst_sel = 6; + c.dst_unused = 0; + v.sdwa = c; + } else { + v.clamp = ((ext >> 13) & 1) == 1; + v.omod = std::uint8_t((ext >> 14) & 3); + v.sdwa = sdwa; + } + } else if (src0 == 0xFA) { + src0 = 256 + (ext & 0xFF); + v.neg = std::uint8_t(((ext >> 20) & 1) | ((ext >> 21) & 2)); + v.abs = std::uint8_t(((ext >> 21) & 1) | ((ext >> 22) & 2)); + v.dpp = DppRow{std::uint16_t((ext >> 8) & 0x1FF), std::uint8_t(ext >> 28), std::uint8_t((ext >> 24) & 0xF), + ((ext >> 19) & 1) == 1, ((ext >> 18) & 1) == 1}; + } else if (src0 == 0xE9 || src0 == 0xEA) { + v.dpp = DppLanes{ext >> 8, src0 == 0xEA}; + src0 = 256 + (ext & 0xFF); + } + Operand op0 = source(src0, n.src[0], ext); + Operand op1 = source(src1, n.src[1], ext); + if (encoding == Encoding::Vopc) { + std::uint8_t mask = name.starts_with("v_cmpx") ? EXEC : VCC; + if (!v.dst) v.dst = scalar(mask, lanes); + v.src = {op0, op1}; + } else if (encoding == Encoding::Vop1) { + v.dst = valu_dst(name, (w0 >> 17) & 0xFF, n.dst); + v.src = {op0}; + } else { + v.dst = vector((w0 >> 17) & 0xFF, n.dst); + if (name.ends_with("mk_f32") || name.ends_with("mk_f16")) { + v.src = {op0, Operand::Literal(ext), op1}; + } else if (name.ends_with("ak_f32") || name.ends_with("ak_f16")) { + v.src = {op0, op1, Operand::Literal(ext)}; + } else { + v.src = {op0, op1}; + } + if (carry_in) v.src.push_back(scalar(VCC, lanes)); + if (name.ends_with("_co_ci_u32")) v.carry = scalar(VCC, lanes); + } + break; + } + case Encoding::Vop3: + case Encoding::Vop3p: { + std::uint32_t w1 = w(1); + auto field = [&](std::uint32_t i) { return (w1 >> (9 * i)) & 0x1FF; }; + std::size_t count; + if (encoding == Encoding::Vop3p) { + count = (name.starts_with("v_pk_") && name.find("_fma_") == std::string_view::npos && + name.find("_mad_") == std::string_view::npos) + ? 2 + : 3; + } else if (opcode < 0x100) { + count = 2; + } else if (opcode < 0x140) { + count = 2 + (carry_in ? 1 : 0); + } else if (opcode >= 0x180 && opcode < 0x200) { + count = 1; + } else if (in(VOP3_TWO_SOURCES, name)) { + count = 2; + } else { + count = 3; + } + for (std::size_t i = 0; i < count; ++i) { + std::uint32_t code = field(std::uint32_t(i)); + if (i == 0 && name.starts_with("v_interp_")) { + v.src.push_back(Operand::Attr(std::uint8_t(code & 0x3F), std::uint8_t((code >> 6) & 3), ((code >> 8) & 1) == 1)); + } else if (i == 2 && carry_in) { + v.src.push_back(source(code, lanes, w(2))); + } else { + v.src.push_back(source(code, n.src[i], w(2))); + } + } + v.clamp = ((w0 >> 15) & 1) == 1; + v.neg = std::uint8_t(w1 >> 29); + if (encoding == Encoding::Vop3p) { + v.neg_hi = std::uint8_t((w0 >> 8) & 7); + v.opsel = std::uint8_t((w0 >> 11) & 7); + v.opsel_hi = std::uint8_t(((w1 >> 27) & 3) | ((w0 >> 12) & 4)); + } else { + v.omod = std::uint8_t((w1 >> 27) & 3); + if (vop3b) { + v.carry = scalar(std::uint8_t((w0 >> 8) & 0x7F), lanes); + } else { + v.abs = std::uint8_t((w0 >> 8) & 7); + v.opsel = std::uint8_t((w0 >> 11) & 0xF); + } + } + std::uint32_t vdst = w0 & 0xFF; + v.dst = compare ? scalar(std::uint8_t(vdst), lanes) : valu_dst(name, vdst, n.dst); + break; + } + default: + // unreachable!("not a VALU encoding") + break; + } + return v; +} + +} // namespace x2w::vs::gfx10 diff --git a/src/x2w_shader/gfx10/fields.h b/src/x2w_shader/gfx10/fields.h new file mode 100644 index 0000000000..f5bde2460c --- /dev/null +++ b/src/x2w_shader/gfx10/fields.h @@ -0,0 +1,263 @@ +// Operand fields of GFX10 instructions, by encoding. +// +// Layouts follow AMD's RDNA ISA reference. Register ranges carry their size in dwords, which depends +// on the opcode (read from its name) and, for lane masks (VCC, EXEC, compare results), on the wave +// size. +#pragma once + +#include <array> +#include <cstdint> +#include <optional> +#include <string> +#include <string_view> +#include <variant> +#include <vector> + +namespace x2w::vs::gfx10 { + +// A source or destination of an instruction. Leave unused fields at zero so equality compares only relevant +// state. +struct Operand { + enum class Kind : std::uint8_t { Scalar, Vector, Const, Literal, Attr }; + + Kind kind = Kind::Const; + // Scalar: registers by operand code: 0-105 `s0`-`s105`, 106/107 `vcc_lo`/`vcc_hi`, 108-123 + // `ttmp0`-`ttmp15`, 124 `m0`, 125 `null`, 126/127 `exec_lo`/`exec_hi`. The decoder gives no code + // above 127; the IR names scalars parked in VGPR lanes by the codes from 128 up (ir::PARKED). + // Const: inline constant or read-only special source, by operand code (128-192: 0-64, + // 193-208: -1 to -16, 240-248: floats, 251-254: vccz, execz, scc, lds_direct). + std::uint8_t code = 0; + // Vector: the first VGPR. + std::uint8_t reg = 0; + // Scalar, Vector. + std::uint8_t dwords = 0; + // Literal: the 32-bit literal that follows the instruction. + std::uint32_t literal = 0; + // Attr: interpolation attribute and channel (0-3 = x-w); `high` selects the upper f16 half. + std::uint8_t index = 0; + std::uint8_t chan = 0; + bool high = false; + + static constexpr Operand Scalar(std::uint8_t code, std::uint8_t dwords) { + Operand o; + o.kind = Kind::Scalar; + o.code = code; + o.dwords = dwords; + return o; + } + static constexpr Operand Vector(std::uint8_t reg, std::uint8_t dwords) { + Operand o; + o.kind = Kind::Vector; + o.reg = reg; + o.dwords = dwords; + return o; + } + static constexpr Operand Const(std::uint8_t code) { + Operand o; + o.kind = Kind::Const; + o.code = code; + return o; + } + static constexpr Operand Literal(std::uint32_t value) { + Operand o; + o.kind = Kind::Literal; + o.literal = value; + return o; + } + static constexpr Operand Attr(std::uint8_t index, std::uint8_t chan, bool high) { + Operand o; + o.kind = Kind::Attr; + o.index = index; + o.chan = chan; + o.high = high; + return o; + } + + constexpr bool is_scalar() const { return kind == Kind::Scalar; } + constexpr bool is_vector() const { return kind == Kind::Vector; } + constexpr bool is_const() const { return kind == Kind::Const; } + constexpr bool is_literal() const { return kind == Kind::Literal; } + constexpr bool is_attr() const { return kind == Kind::Attr; } + + bool operator==(const Operand&) const = default; + + // Display: SP3 syntax (`s5`, `v[2:3]`, `vcc`, `lit(0x3f000000)`, `attr1.x`...), in sp3.cpp. + std::string to_string() const; + // Diagnostic spelling: `Scalar { code: 5, dwords: 1 }`, `Const(128)`, `Attr { index: 1, chan: 0, high: + // false }`. + std::string debug() const; +}; + +// Operand code of the null register, which always reads as zero. +inline constexpr std::uint8_t NULL_CODE = 125; + +struct Cache { + bool glc = false; + bool slc = false; + bool dlc = false; + bool operator==(const Cache&) const = default; +}; + +struct Sdwa { + // Selects: 0-3 byte, 4-5 word, 6 dword. Compares have no `dst_sel`. + std::uint8_t dst_sel = 0; + // 0 pad with zeros, 1 sign-extend, 2 preserve. + std::uint8_t dst_unused = 0; + std::array<std::uint8_t, 2> src_sel{}; + // Bit i sign-extends `src[i]`. + std::uint8_t sext = 0; + bool operator==(const Sdwa&) const = default; +}; + +// DPP16: `ctrl` is the 9-bit permutation (quad_perm, row shifts...). +struct DppRow { + std::uint16_t ctrl = 0; + std::uint8_t row_mask = 0; + std::uint8_t bank_mask = 0; + bool bound_ctrl = false; + bool fi = false; + bool operator==(const DppRow&) const = default; +}; + +// DPP8: eight 3-bit lane selects. +struct DppLanes { + std::uint32_t sel = 0; + bool fi = false; + bool operator==(const DppLanes&) const = default; +}; + +using Dpp = std::variant<DppRow, DppLanes>; + +// VOP1, VOP2, VOPC, VOP3 and VOP3P, with their SDWA and DPP forms. +struct Valu { + // A VGPR range, an SGPR (`v_readlane_b32`...) or a lane mask (compares). + std::optional<Operand> dst; + // Carry-out or the second result of VOP3B (`v_add_co_u32`, `v_div_scale_f32`...). + std::optional<Operand> carry; + // In operand order, including the implicit VCC of VOP2 `v_cndmask_b32` and carry-in, and the + // literal of `v_madmk`/`v_madak` forms. + std::vector<Operand> src; + // Bit i applies to `src[i]`. For VOP3P, `neg` is the low half's. + std::uint8_t neg = 0; + std::uint8_t abs = 0; + // VOP3P: negate the high half (`v_fma_mix*`: absolute value). + std::uint8_t neg_hi = 0; + // VOP3: bit 3 is the destination. VOP3P with `opsel_hi`: the halves used. + std::uint8_t opsel = 0; + std::uint8_t opsel_hi = 0; + bool clamp = false; + // Output modifier: 1 x2, 2 x4, 3 /2. + std::uint8_t omod = 0; + std::optional<Sdwa> sdwa; + std::optional<Dpp> dpp; + bool operator==(const Valu&) const = default; +}; + +// Decoded operand field variants. + +// SOP1, SOP2, SOPC, SOPK; `imm` is SOPK's 16-bit immediate. +struct Sop { + std::optional<Operand> dst; + std::vector<Operand> src; + std::optional<std::uint16_t> imm; + bool operator==(const Sop&) const = default; +}; + +// The 16-bit immediate: branch offset in dwords, wait counts, message... +struct Sopp { + std::uint16_t imm = 0; + bool operator==(const Sopp&) const = default; +}; + +struct Smem { + std::optional<Operand> data; + Operand base; + // Signed byte offset, added to `soffset`. + std::int32_t offset = 0; + Operand soffset; + Cache cache; + bool operator==(const Smem&) const = default; +}; + +struct Vintrp { + Operand dst; + // The i/j VGPR, or for `v_interp_mov_f32` the parameter (0 `p10`, 1 `p20`, 2 `p0`) as Const. + Operand src; + Operand attr; + bool operator==(const Vintrp&) const = default; +}; + +struct Ds { + std::optional<Operand> dst; + std::optional<Operand> addr; + std::vector<Operand> data; + std::uint8_t offset0 = 0; + std::uint8_t offset1 = 0; + bool gds = false; + bool operator==(const Ds&) const = default; +}; + +// MUBUF, and MTBUF with `format` set. +struct Buffer { + // Loaded, stored, or the atomic operand (and result with `glc`). + std::optional<Operand> data; + Operand addr; + Operand rsrc; + Operand soffset; + std::uint16_t offset = 0; + bool offen = false; + bool idxen = false; + std::optional<std::uint8_t> format; + bool lds = false; + bool tfe = false; + Cache cache; + bool operator==(const Buffer&) const = default; +}; + +struct Image { + Operand data; + // One range, or one VGPR per address with the NSA form. + std::vector<Operand> addr; + Operand rsrc; + std::optional<Operand> sampler; + std::uint8_t dmask = 0; + std::uint8_t dim = 0; + bool unorm = false; + bool r128 = false; + bool a16 = false; + bool d16 = false; + bool tfe = false; + bool lwe = false; + Cache cache; + bool operator==(const Image&) const = default; +}; + +// FLAT, GLOBAL and SCRATCH. +struct Flat { + std::optional<Operand> dst; + std::optional<Operand> addr; + std::optional<Operand> data; + std::optional<Operand> saddr; + std::int16_t offset = 0; + bool lds = false; + Cache cache; + bool operator==(const Flat&) const = default; +}; + +struct Exp { + std::uint8_t target = 0; + // Per channel; nullopt when disabled. + std::array<std::optional<Operand>, 4> src{}; + bool compr = false; + bool done = false; + bool vm = false; + bool operator==(const Exp&) const = default; +}; + +// Use std::get_if<Sop>(&fields) and the corresponding variant types to inspect decoded operands. +using Fields = std::variant<Sop, Sopp, Smem, Valu, Vintrp, Ds, Buffer, Image, Flat, Exp>; + +// LDS opcodes on two addresses (`ds_read2_b32`...), with `offset0`/`offset1` (pub(super)). +bool ds_pair(std::string_view name); + +} // namespace x2w::vs::gfx10 diff --git a/src/x2w_shader/gfx10/mod.cpp b/src/x2w_shader/gfx10/mod.cpp new file mode 100644 index 0000000000..3fdd3beeb8 --- /dev/null +++ b/src/x2w_shader/gfx10/mod.cpp @@ -0,0 +1,283 @@ +// GFX10 machine code: instruction boundaries, encodings and opcodes. +#include "x2w_shader/gfx10/mod.h" + +#include <algorithm> +#include <iterator> +#include <map> + +#include "x2w_shader/gfx10/opcodes.h" + +namespace x2w::vs::gfx10 { + +namespace { + +ShaderError isa(std::size_t offset, const char* reason) { return ShaderError::isa(offset, reason); } + +bool name_is(const std::optional<std::string_view>& n, std::string_view s) { return n && *n == s; } + +Flow flow(const Instruction& inst, std::size_t next, std::size_t len) { + auto target = [&]() -> std::size_t { + std::int64_t delta = 4 * std::int64_t(std::int16_t(std::uint16_t(inst.words[0]))); + std::int64_t t = std::int64_t(next) + delta; + if (t < 0 || std::uint64_t(t) >= len) throw isa(inst.offset, "branch target outside the code"); + return std::size_t(t); + }; + std::string_view name = inst.name().value_or(""); + if (inst.encoding == Encoding::Sopp) { + if (name == "s_endpgm" || name == "s_endpgm_saved" || name == "s_endpgm_ordered_ps_done" || + name == "s_code_end") { + return Flow::Stop(); + } + if (name == "s_branch") return Flow::Jump(target()); + if (name.starts_with("s_cbranch_")) return Flow::Branch(target()); + } + if (inst.encoding == Encoding::Sopk && name == "s_call_b64") return Flow::Branch(target()); + // Indirect jump; `decode` resolves the compiler's far-jump form. + if (inst.encoding == Encoding::Sop1 && name == "s_setpc_b64") return Flow::Stop(); + return Flow::Next(); +} + +// Resolves the far jump compilers emit beyond the reach of a branch offset: `s_getpc_b64 s[n:n+1]`, +// `s_add_u32|s_sub_u32 sn, sn, literal`, a carry into s(n+1), `s_setpc_b64 s[n:n+1]`, looking back +// over the straight-line run just decoded. Any other `s_setpc_b64` (e.g. a handover to the next +// merged stage through registers) gives nullopt. +std::optional<std::size_t> far_jump(const Before& before, const Instruction& setpc, std::size_t len) { + std::uint32_t n = setpc.words[0] & 0xFF; + std::optional<std::int64_t> delta; + std::size_t at = setpc.offset; + for (int k = 0; k < 4; ++k) { + const Instruction* prev = before(at); + if (!prev) break; + if (prev->offset + 4 * prev->words.size() != at) break; + std::uint32_t w = prev->words[0]; + std::uint32_t sdst = (w >> 16) & 0x7F, ssrc0 = w & 0xFF, ssrc1 = (w >> 8) & 0xFF; + auto pname = prev->name(); + if (prev->encoding == Encoding::Sop2 && (name_is(pname, "s_add_u32") || name_is(pname, "s_sub_u32")) && + sdst == n && ssrc0 == n && ssrc1 == 0xFF && !delta) { + // The low dword of a signed 64-bit offset: a backward jump adds a negative one (its + // high dword is -1). + std::int64_t literal = std::int64_t(std::int32_t(prev->words.at(1))); + delta = name_is(pname, "s_add_u32") ? literal : -literal; + } else if (prev->encoding == Encoding::Sop1 && name_is(pname, "s_getpc_b64") && sdst == n) { + if (!delta) break; + // s_getpc_b64 yields the address of the instruction after it. + std::int64_t t = std::int64_t(prev->offset) + 4 + *delta; + if (t < 0 || std::uint64_t(t) >= len) throw isa(setpc.offset, "far jump target outside the code"); + return std::size_t(t); + } + at = prev->offset; + } + return std::nullopt; +} + +Instruction instruction(std::span<const std::uint8_t> code, std::size_t offset) { + auto word = [&](std::size_t i) -> std::uint32_t { + std::size_t at = offset + 4 * i; + if (at + 4 > code.size()) throw isa(offset, "instruction runs past the end of the code"); + return std::uint32_t(code[at]) | std::uint32_t(code[at + 1]) << 8 | std::uint32_t(code[at + 2]) << 16 | + std::uint32_t(code[at + 3]) << 24; + }; + std::uint32_t w = word(0); + Encoding encoding = Encoding::Sopp; + std::uint32_t opcode = 0; + std::size_t len = 0; + if (w >> 31 == 0) { + std::uint32_t src0 = w & 0x1FF; + // Literal constant, SDWA, DPP16, DPP8, DPP8 with fetch-inactive. + std::size_t extra = (src0 == 0xFF || src0 == 0xF9 || src0 == 0xFA || src0 == 0xE9 || src0 == 0xEA) ? 1 : 0; + std::uint32_t op = w >> 25; + if (op == 0x3F) { + encoding = Encoding::Vop1, opcode = (w >> 9) & 0xFF, len = 1 + extra; + } else if (op == 0x3E) { + encoding = Encoding::Vopc, opcode = (w >> 17) & 0xFF, len = 1 + extra; + } else { + auto n = name(Encoding::Vop2, std::uint16_t(op)); + bool mk_ak = n && (*n == "v_madmk_f32" || *n == "v_madak_f32" || *n == "v_fmamk_f32" || + *n == "v_fmaak_f32" || *n == "v_madmk_f16" || *n == "v_madak_f16" || + *n == "v_fmamk_f16" || *n == "v_fmaak_f16"); + encoding = Encoding::Vop2, opcode = op, len = 1 + std::max(extra, std::size_t(mk_ak)); + } + } else if (w >> 30 == 0b10) { + auto literal1 = [](std::uint32_t a) -> std::size_t { return 1 + (a == 0xFF ? 1 : 0); }; + auto literal2 = [](std::uint32_t a, std::uint32_t b) -> std::size_t { + return 1 + ((a == 0xFF || b == 0xFF) ? 1 : 0); + }; + std::uint32_t top = w >> 23; + if (top == 0x17D) { + encoding = Encoding::Sop1, opcode = (w >> 8) & 0xFF, len = literal1(w & 0xFF); + } else if (top == 0x17E) { + encoding = Encoding::Sopc, opcode = (w >> 16) & 0x7F, len = literal2(w & 0xFF, (w >> 8) & 0xFF); + } else if (top == 0x17F) { + encoding = Encoding::Sopp, opcode = (w >> 16) & 0x7F, len = 1; + } else if (w >> 28 == 0b1011) { + std::uint32_t op = (w >> 23) & 0x1F; + bool imm32 = name_is(name(Encoding::Sopk, std::uint16_t(op)), "s_setreg_imm32_b32"); + encoding = Encoding::Sopk, opcode = op, len = 1 + (imm32 ? 1 : 0); + } else { + encoding = Encoding::Sop2, opcode = (w >> 23) & 0x7F, len = literal2(w & 0xFF, (w >> 8) & 0xFF); + } + } else { + auto vop3 = [](std::uint32_t w1) -> std::size_t { + bool lit = (w1 & 0x1FF) == 0xFF || ((w1 >> 9) & 0x1FF) == 0xFF || ((w1 >> 18) & 0x1FF) == 0xFF; + return 2 + (lit ? 1 : 0); + }; + switch (w >> 26) { + case 0x32: + encoding = Encoding::Vintrp, opcode = (w >> 16) & 0x3, len = 1; + break; + case 0x33: + encoding = Encoding::Vop3p, opcode = (w >> 16) & 0x7F, len = vop3(word(1)); + break; + case 0x35: + encoding = Encoding::Vop3, opcode = (w >> 16) & 0x3FF, len = vop3(word(1)); + break; + case 0x36: + encoding = Encoding::Ds, opcode = (w >> 18) & 0xFF, len = 2; + break; + case 0x37: + switch ((w >> 14) & 3) { + case 0: + encoding = Encoding::Flat; + break; + case 1: + encoding = Encoding::Scratch; + break; + case 2: + encoding = Encoding::Global; + break; + default: + throw isa(offset, "reserved FLAT segment"); + } + opcode = (w >> 18) & 0x7F, len = 2; + break; + case 0x38: + encoding = Encoding::Mubuf, opcode = ((w >> 18) & 0x7F) | ((w >> 25) & 1) << 7, len = 2; + break; + case 0x3A: + encoding = Encoding::Mtbuf, opcode = ((w >> 16) & 0x7) | ((word(1) >> 21) & 1) << 3, len = 2; + break; + // Bits 2:1 count extra dwords of non-sequential address registers. + case 0x3C: + encoding = Encoding::Mimg, opcode = ((w >> 18) & 0x7F) | (w & 1) << 7, len = 2 + ((w >> 1) & 3); + break; + case 0x3D: + encoding = Encoding::Smem, opcode = (w >> 18) & 0xFF, len = 2; + break; + case 0x3E: + encoding = Encoding::Exp, opcode = 0, len = 2; + break; + default: + throw isa(offset, "unknown encoding"); + } + } + std::vector<std::uint32_t> words; + words.reserve(len); + for (std::size_t i = 0; i < len; ++i) words.push_back(word(i)); + return Instruction(offset, encoding, std::uint16_t(opcode), std::move(words)); +} + +} // namespace + +const char* debug(Encoding e) { + static const char* const NAMES[] = { + "Sop2", "Sopk", "Sop1", "Sopc", "Sopp", "Smem", "Vop2", "Vop1", "Vopc", "Vop3", + "Vop3p", "Vintrp", "Ds", "Mubuf", "Mtbuf", "Mimg", "Exp", "Flat", "Global", "Scratch", + }; + return NAMES[static_cast<int>(e)]; +} + +Instruction::Instruction(std::size_t offset_, Encoding encoding_, std::uint16_t opcode_, + std::vector<std::uint32_t> words_) + : offset(offset_), encoding(encoding_), opcode(opcode_), words(std::move(words_)), + name_(gfx10::name(encoding_, opcode_)) {} + +std::vector<Instruction> decode(std::span<const std::uint8_t> code) { + if (code.size() % 4 != 0) throw isa(code.size(), "code size is not a multiple of 4"); + std::map<std::size_t, Instruction> found; + std::vector<std::size_t> pending{0}; + Before before = [&](std::size_t at) -> const Instruction* { + auto it = found.lower_bound(at); + if (it == found.begin()) return nullptr; + return &std::prev(it)->second; + }; + while (!pending.empty()) { + std::size_t offset = pending.back(); + pending.pop_back(); + while (!found.contains(offset)) { + Instruction inst = instruction(code, offset); + std::size_t next = offset + 4 * inst.words.size(); + Flow f = control(inst, code.size(), before); + found.emplace(offset, std::move(inst)); + if (f.kind == Flow::Kind::Stop) break; + if (f.kind == Flow::Kind::Jump) { + offset = f.target; + } else { + if (f.kind == Flow::Kind::Branch) pending.push_back(f.target); + offset = next; + } + } + } + std::vector<Instruction> list; + list.reserve(found.size()); + for (auto& entry : found) list.push_back(std::move(entry.second)); + for (std::size_t i = 0; i + 1 < list.size(); ++i) { + if (list[i].offset + 4 * list[i].words.size() > list[i + 1].offset) { + throw isa(list[i + 1].offset, "a branch lands inside an instruction"); + } + } + return list; +} + +Flow control(const Instruction& inst, std::size_t len, const Before& before) { + Flow f = flow(inst, inst.offset + 4 * inst.words.size(), len); + if (f.kind == Flow::Kind::Stop && name_is(inst.name(), "s_setpc_b64")) { + auto t = far_jump(before, inst, len); + return t ? Flow::Jump(*t) : Flow::Stop(); + } + return f; +} + +std::optional<std::string_view> name(Encoding encoding, std::uint16_t opcode) { + namespace t = opcodes; + opcodes::Table table; + std::uint16_t op = opcode; + switch (encoding) { + case Encoding::Sop2: table = t::SOP2; break; + case Encoding::Sopk: table = t::SOPK; break; + case Encoding::Sop1: table = t::SOP1; break; + case Encoding::Sopc: table = t::SOPC; break; + case Encoding::Sopp: table = t::SOPP; break; + case Encoding::Smem: table = t::SMEM; break; + case Encoding::Vop2: table = t::VOP2; break; + case Encoding::Vop1: table = t::VOP1; break; + case Encoding::Vopc: table = t::VOPC; break; + // VOP3 also encodes the VOPC, VOP2 and VOP1 opcodes at fixed bases. + case Encoding::Vop3: + if (opcode < 0x100) { + table = t::VOPC; + } else if (opcode < 0x140) { + table = t::VOP2, op = std::uint16_t(opcode - 0x100); + } else if (opcode >= 0x180 && opcode < 0x200) { + table = t::VOP1, op = std::uint16_t(opcode - 0x180); + } else { + table = t::VOP3; + } + break; + case Encoding::Vop3p: table = t::VOP3P; break; + case Encoding::Vintrp: table = t::VINTRP; break; + case Encoding::Ds: table = t::DS; break; + case Encoding::Mubuf: table = t::MUBUF; break; + case Encoding::Mtbuf: table = t::MTBUF; break; + case Encoding::Mimg: table = t::MIMG; break; + case Encoding::Exp: return std::string_view("exp"); + case Encoding::Flat: table = t::FLAT; break; + case Encoding::Global: table = t::GLOBAL; break; + case Encoding::Scratch: table = t::SCRATCH; break; + } + auto it = std::lower_bound(table.begin(), table.end(), op, + [](const opcodes::Entry& e, std::uint16_t v) { return e.op < v; }); + if (it != table.end() && it->op == op) return it->name; + return std::nullopt; +} + +} // namespace x2w::vs::gfx10 diff --git a/src/x2w_shader/gfx10/mod.h b/src/x2w_shader/gfx10/mod.h new file mode 100644 index 0000000000..9d17d468f4 --- /dev/null +++ b/src/x2w_shader/gfx10/mod.h @@ -0,0 +1,118 @@ +// GFX10 machine code: instruction boundaries, encodings and opcodes. +// +// Instructions are found by following control flow from offset 0, not by a linear sweep: compilers +// place data (constant tables) in the code region after the end of the program. +// Instruction::fields decodes the operand fields and Instruction::text prints them in AMD's SP3 +// syntax. +// +// Encodings by the top bits of the first dword: +// +// 0xxxxxxx VOP2; 0111111 VOP1; 0111110 VOPC +// 10 SOP2; 1011 SOPK; 101111101 SOP1; 101111110 SOPC; 101111111 SOPP +// 110010 VINTRP 110011 VOP3P 110101 VOP3 110110 DS 110111 FLAT/GLOBAL/SCRATCH +// 111000 MUBUF 111010 MTBUF 111100 MIMG 111101 SMEM 111110 EXP +#pragma once + +#include <cstddef> +#include <cstdint> +#include <functional> +#include <optional> +#include <span> +#include <string> +#include <string_view> +#include <vector> + +#include "x2w_shader/error.h" +#include "x2w_shader/gfx10/fields.h" + +namespace x2w::vs::gfx10 { + +enum class Encoding : std::uint8_t { + Sop2, + Sopk, + Sop1, + Sopc, + Sopp, + Smem, + Vop2, + Vop1, + Vopc, + Vop3, + Vop3p, + Vintrp, + Ds, + Mubuf, + Mtbuf, + Mimg, + Exp, + Flat, + Global, + Scratch, +}; + +// Diagnostic spelling for Encoding: "Sop2", "Vop3p",... +const char* debug(Encoding e); + +class Instruction { +public: + // Byte offset in the program. + std::size_t offset = 0; + Encoding encoding = Encoding::Sopp; + std::uint16_t opcode = 0; + // Every dword of the instruction, including literals and extra dwords. + std::vector<std::uint32_t> words; + + Instruction() = default; + // An instruction of these words, its name resolved. + Instruction(std::size_t offset, Encoding encoding, std::uint16_t opcode, std::vector<std::uint32_t> words); + + // AMD's name for the opcode, if it is in our table (static storage, NUL-terminated). + std::optional<std::string_view> name() const { return name_; } + + // Decodes the operand fields. `wave64` sizes lane masks (fields.cpp). + Fields fields(bool wave64) const; + // The instruction in SP3 syntax, e.g. `v_add_f32 v1, 0.5, v8`. Branch targets are written + // `label_<byte offset>` (sp3.cpp). + std::string text(bool wave64) const; + + bool operator==(const Instruction&) const = default; + +private: + // name() of `encoding` and `opcode`, resolved once at decode time. + std::optional<std::string_view> name_; + Valu valu(std::string_view name, std::uint8_t lanes) const; +}; + +// Decodes every instruction reachable from offset 0, sorted by offset. Throws ShaderError::isa. +std::vector<Instruction> decode(std::span<const std::uint8_t> code); + +// Control flow after an instruction. +struct Flow { + enum class Kind : std::uint8_t { + Next, + // End of the program, or an indirect jump that is not a far jump. + Stop, + Jump, + // Conditional: to the target or the next instruction. + Branch, + }; + Kind kind = Kind::Next; + std::size_t target = 0; // Jump, Branch + + static constexpr Flow Next() { return {Kind::Next, 0}; } + static constexpr Flow Stop() { return {Kind::Stop, 0}; } + static constexpr Flow Jump(std::size_t t) { return {Kind::Jump, t}; } + static constexpr Flow Branch(std::size_t t) { return {Kind::Branch, t}; } + bool operator==(const Flow&) const = default; +}; + +// `before(at)`: the decoded instruction with the highest offset below `at`, or nullptr. +using Before = std::function<const Instruction*(std::size_t)>; + +// Control flow after `inst`, resolving far jumps (pub(crate)). Throws ShaderError::isa. +Flow control(const Instruction& inst, std::size_t len, const Before& before); + +// The opcode table lookup behind Instruction::name. +std::optional<std::string_view> name(Encoding encoding, std::uint16_t opcode); + +} // namespace x2w::vs::gfx10 diff --git a/src/x2w_shader/gfx10/opcodes.cpp b/src/x2w_shader/gfx10/opcodes.cpp new file mode 100644 index 0000000000..01c0f1e703 --- /dev/null +++ b/src/x2w_shader/gfx10/opcodes.cpp @@ -0,0 +1,1344 @@ +// GFX10 opcode names, generated from Mesa's src/amd/compiler/aco_opcodes.py +// (tag mesa-22.3.0, GFX10 column), which carries this notice: +// +// Copyright (c) 2018 Valve Corporation +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice (including the next +// paragraph) shall be included in all copies or substantial portions of the +// Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. +// +// Each table is sorted by opcode. VOP3 holds only VOP3-only opcodes; VOP3 +// encodings of VOPC/VOP2/VOP1 ops (0x000-0x13f, 0x180-0x1ff) use those tables. + +#include "x2w_shader/gfx10/opcodes.h" + +namespace x2w::vs::gfx10::opcodes { + +namespace { +constexpr Entry SOP2_[] = { + {0x000, "s_add_u32"}, + {0x001, "s_sub_u32"}, + {0x002, "s_add_i32"}, + {0x003, "s_sub_i32"}, + {0x004, "s_addc_u32"}, + {0x005, "s_subb_u32"}, + {0x006, "s_min_i32"}, + {0x007, "s_min_u32"}, + {0x008, "s_max_i32"}, + {0x009, "s_max_u32"}, + {0x00a, "s_cselect_b32"}, + {0x00b, "s_cselect_b64"}, + {0x00e, "s_and_b32"}, + {0x00f, "s_and_b64"}, + {0x010, "s_or_b32"}, + {0x011, "s_or_b64"}, + {0x012, "s_xor_b32"}, + {0x013, "s_xor_b64"}, + {0x014, "s_andn2_b32"}, + {0x015, "s_andn2_b64"}, + {0x016, "s_orn2_b32"}, + {0x017, "s_orn2_b64"}, + {0x018, "s_nand_b32"}, + {0x019, "s_nand_b64"}, + {0x01a, "s_nor_b32"}, + {0x01b, "s_nor_b64"}, + {0x01c, "s_xnor_b32"}, + {0x01d, "s_xnor_b64"}, + {0x01e, "s_lshl_b32"}, + {0x01f, "s_lshl_b64"}, + {0x020, "s_lshr_b32"}, + {0x021, "s_lshr_b64"}, + {0x022, "s_ashr_i32"}, + {0x023, "s_ashr_i64"}, + {0x024, "s_bfm_b32"}, + {0x025, "s_bfm_b64"}, + {0x026, "s_mul_i32"}, + {0x027, "s_bfe_u32"}, + {0x028, "s_bfe_i32"}, + {0x029, "s_bfe_u64"}, + {0x02a, "s_bfe_i64"}, + {0x02c, "s_absdiff_i32"}, + {0x02e, "s_lshl1_add_u32"}, + {0x02f, "s_lshl2_add_u32"}, + {0x030, "s_lshl3_add_u32"}, + {0x031, "s_lshl4_add_u32"}, + {0x032, "s_pack_ll_b32_b16"}, + {0x033, "s_pack_lh_b32_b16"}, + {0x034, "s_pack_hh_b32_b16"}, + {0x035, "s_mul_hi_u32"}, + {0x036, "s_mul_hi_i32"}, +}; + +constexpr Entry SOPK_[] = { + {0x000, "s_movk_i32"}, + {0x001, "s_version"}, + {0x002, "s_cmovk_i32"}, + {0x003, "s_cmpk_eq_i32"}, + {0x004, "s_cmpk_lg_i32"}, + {0x005, "s_cmpk_gt_i32"}, + {0x006, "s_cmpk_ge_i32"}, + {0x007, "s_cmpk_lt_i32"}, + {0x008, "s_cmpk_le_i32"}, + {0x009, "s_cmpk_eq_u32"}, + {0x00a, "s_cmpk_lg_u32"}, + {0x00b, "s_cmpk_gt_u32"}, + {0x00c, "s_cmpk_ge_u32"}, + {0x00d, "s_cmpk_lt_u32"}, + {0x00e, "s_cmpk_le_u32"}, + {0x00f, "s_addk_i32"}, + {0x010, "s_mulk_i32"}, + {0x012, "s_getreg_b32"}, + {0x013, "s_setreg_b32"}, + {0x015, "s_setreg_imm32_b32"}, + {0x016, "s_call_b64"}, + {0x017, "s_waitcnt_vscnt"}, + {0x018, "s_waitcnt_vmcnt"}, + {0x019, "s_waitcnt_expcnt"}, + {0x01a, "s_waitcnt_lgkmcnt"}, + {0x01b, "s_subvector_loop_begin"}, + {0x01c, "s_subvector_loop_end"}, +}; + +constexpr Entry SOP1_[] = { + {0x003, "s_mov_b32"}, + {0x004, "s_mov_b64"}, + {0x005, "s_cmov_b32"}, + {0x006, "s_cmov_b64"}, + {0x007, "s_not_b32"}, + {0x008, "s_not_b64"}, + {0x009, "s_wqm_b32"}, + {0x00a, "s_wqm_b64"}, + {0x00b, "s_brev_b32"}, + {0x00c, "s_brev_b64"}, + {0x00d, "s_bcnt0_i32_b32"}, + {0x00e, "s_bcnt0_i32_b64"}, + {0x00f, "s_bcnt1_i32_b32"}, + {0x010, "s_bcnt1_i32_b64"}, + {0x011, "s_ff0_i32_b32"}, + {0x012, "s_ff0_i32_b64"}, + {0x013, "s_ff1_i32_b32"}, + {0x014, "s_ff1_i32_b64"}, + {0x015, "s_flbit_i32_b32"}, + {0x016, "s_flbit_i32_b64"}, + {0x017, "s_flbit_i32"}, + {0x018, "s_flbit_i32_i64"}, + {0x019, "s_sext_i32_i8"}, + {0x01a, "s_sext_i32_i16"}, + {0x01b, "s_bitset0_b32"}, + {0x01c, "s_bitset0_b64"}, + {0x01d, "s_bitset1_b32"}, + {0x01e, "s_bitset1_b64"}, + {0x01f, "s_getpc_b64"}, + {0x020, "s_setpc_b64"}, + {0x021, "s_swappc_b64"}, + {0x022, "s_rfe_b64"}, + {0x024, "s_and_saveexec_b64"}, + {0x025, "s_or_saveexec_b64"}, + {0x026, "s_xor_saveexec_b64"}, + {0x027, "s_andn2_saveexec_b64"}, + {0x028, "s_orn2_saveexec_b64"}, + {0x029, "s_nand_saveexec_b64"}, + {0x02a, "s_nor_saveexec_b64"}, + {0x02b, "s_xnor_saveexec_b64"}, + {0x02c, "s_quadmask_b32"}, + {0x02d, "s_quadmask_b64"}, + {0x02e, "s_movrels_b32"}, + {0x02f, "s_movrels_b64"}, + {0x030, "s_movreld_b32"}, + {0x031, "s_movreld_b64"}, + {0x034, "s_abs_i32"}, + {0x035, "s_mov_fed_b32"}, + {0x037, "s_andn1_saveexec_b64"}, + {0x038, "s_orn1_saveexec_b64"}, + {0x039, "s_andn1_wrexec_b64"}, + {0x03a, "s_andn2_wrexec_b64"}, + {0x03b, "s_bitreplicate_b64_b32"}, + {0x03c, "s_and_saveexec_b32"}, + {0x03d, "s_or_saveexec_b32"}, + {0x03e, "s_xor_saveexec_b32"}, + {0x03f, "s_andn2_saveexec_b32"}, + {0x040, "s_orn2_saveexec_b32"}, + {0x041, "s_nand_saveexec_b32"}, + {0x042, "s_nor_saveexec_b32"}, + {0x043, "s_xnor_saveexec_b32"}, + {0x044, "s_andn1_saveexec_b32"}, + {0x045, "s_orn1_saveexec_b32"}, + {0x046, "s_andn1_wrexec_b32"}, + {0x047, "s_andn2_wrexec_b32"}, + {0x049, "s_movrelsd_2_b32"}, +}; + +constexpr Entry SOPC_[] = { + {0x000, "s_cmp_eq_i32"}, + {0x001, "s_cmp_lg_i32"}, + {0x002, "s_cmp_gt_i32"}, + {0x003, "s_cmp_ge_i32"}, + {0x004, "s_cmp_lt_i32"}, + {0x005, "s_cmp_le_i32"}, + {0x006, "s_cmp_eq_u32"}, + {0x007, "s_cmp_lg_u32"}, + {0x008, "s_cmp_gt_u32"}, + {0x009, "s_cmp_ge_u32"}, + {0x00a, "s_cmp_lt_u32"}, + {0x00b, "s_cmp_le_u32"}, + {0x00c, "s_bitcmp0_b32"}, + {0x00d, "s_bitcmp1_b32"}, + {0x00e, "s_bitcmp0_b64"}, + {0x00f, "s_bitcmp1_b64"}, + {0x012, "s_cmp_eq_u64"}, + {0x013, "s_cmp_lg_u64"}, +}; + +constexpr Entry SOPP_[] = { + {0x000, "s_nop"}, + {0x001, "s_endpgm"}, + {0x002, "s_branch"}, + {0x003, "s_wakeup"}, + {0x004, "s_cbranch_scc0"}, + {0x005, "s_cbranch_scc1"}, + {0x006, "s_cbranch_vccz"}, + {0x007, "s_cbranch_vccnz"}, + {0x008, "s_cbranch_execz"}, + {0x009, "s_cbranch_execnz"}, + {0x00a, "s_barrier"}, + {0x00b, "s_setkill"}, + {0x00c, "s_waitcnt"}, + {0x00d, "s_sethalt"}, + {0x00e, "s_sleep"}, + {0x00f, "s_setprio"}, + {0x010, "s_sendmsg"}, + {0x011, "s_sendmsghalt"}, + {0x012, "s_trap"}, + {0x013, "s_icache_inv"}, + {0x014, "s_incperflevel"}, + {0x015, "s_decperflevel"}, + {0x016, "s_ttracedata"}, + {0x017, "s_cbranch_cdbgsys"}, + {0x018, "s_cbranch_cdbguser"}, + {0x019, "s_cbranch_cdbgsys_or_user"}, + {0x01a, "s_cbranch_cdbgsys_and_user"}, + {0x01b, "s_endpgm_saved"}, + {0x01e, "s_endpgm_ordered_ps_done"}, + {0x01f, "s_code_end"}, + {0x020, "s_inst_prefetch"}, + {0x021, "s_clause"}, + {0x022, "s_wait_idle"}, + {0x023, "s_waitcnt_depctr"}, + {0x024, "s_round_mode"}, + {0x025, "s_denorm_mode"}, + {0x028, "s_ttracedata_imm"}, +}; + +constexpr Entry SMEM_[] = { + {0x000, "s_load_dword"}, + {0x001, "s_load_dwordx2"}, + {0x002, "s_load_dwordx4"}, + {0x003, "s_load_dwordx8"}, + {0x004, "s_load_dwordx16"}, + {0x005, "s_scratch_load_dword"}, + {0x006, "s_scratch_load_dwordx2"}, + {0x007, "s_scratch_load_dwordx4"}, + {0x008, "s_buffer_load_dword"}, + {0x009, "s_buffer_load_dwordx2"}, + {0x00a, "s_buffer_load_dwordx4"}, + {0x00b, "s_buffer_load_dwordx8"}, + {0x00c, "s_buffer_load_dwordx16"}, + {0x010, "s_store_dword"}, + {0x011, "s_store_dwordx2"}, + {0x012, "s_store_dwordx4"}, + {0x015, "s_scratch_store_dword"}, + {0x016, "s_scratch_store_dwordx2"}, + {0x017, "s_scratch_store_dwordx4"}, + {0x018, "s_buffer_store_dword"}, + {0x019, "s_buffer_store_dwordx2"}, + {0x01a, "s_buffer_store_dwordx4"}, + {0x01f, "s_gl1_inv"}, + {0x020, "s_dcache_inv"}, + {0x021, "s_dcache_wb"}, + {0x024, "s_memtime"}, + {0x025, "s_memrealtime"}, + {0x026, "s_atc_probe"}, + {0x027, "s_atc_probe_buffer"}, + {0x028, "s_dcache_discard"}, + {0x029, "s_dcache_discard_x2"}, + {0x02a, "s_get_waveid_in_workgroup"}, + {0x040, "s_buffer_atomic_swap"}, + {0x041, "s_buffer_atomic_cmpswap"}, + {0x042, "s_buffer_atomic_add"}, + {0x043, "s_buffer_atomic_sub"}, + {0x044, "s_buffer_atomic_smin"}, + {0x045, "s_buffer_atomic_umin"}, + {0x046, "s_buffer_atomic_smax"}, + {0x047, "s_buffer_atomic_umax"}, + {0x048, "s_buffer_atomic_and"}, + {0x049, "s_buffer_atomic_or"}, + {0x04a, "s_buffer_atomic_xor"}, + {0x04b, "s_buffer_atomic_inc"}, + {0x04c, "s_buffer_atomic_dec"}, + {0x060, "s_buffer_atomic_swap_x2"}, + {0x061, "s_buffer_atomic_cmpswap_x2"}, + {0x062, "s_buffer_atomic_add_x2"}, + {0x063, "s_buffer_atomic_sub_x2"}, + {0x064, "s_buffer_atomic_smin_x2"}, + {0x065, "s_buffer_atomic_umin_x2"}, + {0x066, "s_buffer_atomic_smax_x2"}, + {0x067, "s_buffer_atomic_umax_x2"}, + {0x068, "s_buffer_atomic_and_x2"}, + {0x069, "s_buffer_atomic_or_x2"}, + {0x06a, "s_buffer_atomic_xor_x2"}, + {0x06b, "s_buffer_atomic_inc_x2"}, + {0x06c, "s_buffer_atomic_dec_x2"}, + {0x080, "s_atomic_swap"}, + {0x081, "s_atomic_cmpswap"}, + {0x082, "s_atomic_add"}, + {0x083, "s_atomic_sub"}, + {0x084, "s_atomic_smin"}, + {0x085, "s_atomic_umin"}, + {0x086, "s_atomic_smax"}, + {0x087, "s_atomic_umax"}, + {0x088, "s_atomic_and"}, + {0x089, "s_atomic_or"}, + {0x08a, "s_atomic_xor"}, + {0x08b, "s_atomic_inc"}, + {0x08c, "s_atomic_dec"}, + {0x0a0, "s_atomic_swap_x2"}, + {0x0a1, "s_atomic_cmpswap_x2"}, + {0x0a2, "s_atomic_add_x2"}, + {0x0a3, "s_atomic_sub_x2"}, + {0x0a4, "s_atomic_smin_x2"}, + {0x0a5, "s_atomic_umin_x2"}, + {0x0a6, "s_atomic_smax_x2"}, + {0x0a7, "s_atomic_umax_x2"}, + {0x0a8, "s_atomic_and_x2"}, + {0x0a9, "s_atomic_or_x2"}, + {0x0aa, "s_atomic_xor_x2"}, + {0x0ab, "s_atomic_inc_x2"}, + {0x0ac, "s_atomic_dec_x2"}, +}; + +constexpr Entry VOP2_[] = { + {0x001, "v_cndmask_b32"}, + {0x002, "v_dot2c_f32_f16"}, + {0x003, "v_add_f32"}, + {0x004, "v_sub_f32"}, + {0x005, "v_subrev_f32"}, + {0x006, "v_mac_legacy_f32"}, + {0x007, "v_mul_legacy_f32"}, + {0x008, "v_mul_f32"}, + {0x009, "v_mul_i32_i24"}, + {0x00a, "v_mul_hi_i32_i24"}, + {0x00b, "v_mul_u32_u24"}, + {0x00c, "v_mul_hi_u32_u24"}, + {0x00d, "v_dot4c_i32_i8"}, + {0x00f, "v_min_f32"}, + {0x010, "v_max_f32"}, + {0x011, "v_min_i32"}, + {0x012, "v_max_i32"}, + {0x013, "v_min_u32"}, + {0x014, "v_max_u32"}, + {0x016, "v_lshrrev_b32"}, + {0x018, "v_ashrrev_i32"}, + {0x01a, "v_lshlrev_b32"}, + {0x01b, "v_and_b32"}, + {0x01c, "v_or_b32"}, + {0x01d, "v_xor_b32"}, + {0x01e, "v_xnor_b32"}, + {0x01f, "v_mac_f32"}, + {0x020, "v_madmk_f32"}, + {0x021, "v_madak_f32"}, + {0x025, "v_add_nc_u32"}, + {0x026, "v_sub_nc_u32"}, + {0x027, "v_subrev_nc_u32"}, + {0x028, "v_add_co_ci_u32"}, + {0x029, "v_sub_co_ci_u32"}, + {0x02a, "v_subrev_co_ci_u32"}, + {0x02b, "v_fmac_f32"}, + {0x02c, "v_fmamk_f32"}, + {0x02d, "v_fmaak_f32"}, + {0x02f, "v_cvt_pkrtz_f16_f32"}, + {0x032, "v_add_f16"}, + {0x033, "v_sub_f16"}, + {0x034, "v_subrev_f16"}, + {0x035, "v_mul_f16"}, + {0x036, "v_fmac_f16"}, + {0x037, "v_fmamk_f16"}, + {0x038, "v_fmaak_f16"}, + {0x039, "v_max_f16"}, + {0x03a, "v_min_f16"}, + {0x03b, "v_ldexp_f16"}, + {0x03c, "v_pk_fmac_f16"}, +}; + +constexpr Entry VOP1_[] = { + {0x000, "v_nop"}, + {0x001, "v_mov_b32"}, + {0x002, "v_readfirstlane_b32"}, + {0x003, "v_cvt_i32_f64"}, + {0x004, "v_cvt_f64_i32"}, + {0x005, "v_cvt_f32_i32"}, + {0x006, "v_cvt_f32_u32"}, + {0x007, "v_cvt_u32_f32"}, + {0x008, "v_cvt_i32_f32"}, + {0x00a, "v_cvt_f16_f32"}, + {0x00b, "v_cvt_f32_f16"}, + {0x00c, "v_cvt_rpi_i32_f32"}, + {0x00d, "v_cvt_flr_i32_f32"}, + {0x00e, "v_cvt_off_f32_i4"}, + {0x00f, "v_cvt_f32_f64"}, + {0x010, "v_cvt_f64_f32"}, + {0x011, "v_cvt_f32_ubyte0"}, + {0x012, "v_cvt_f32_ubyte1"}, + {0x013, "v_cvt_f32_ubyte2"}, + {0x014, "v_cvt_f32_ubyte3"}, + {0x015, "v_cvt_u32_f64"}, + {0x016, "v_cvt_f64_u32"}, + {0x017, "v_trunc_f64"}, + {0x018, "v_ceil_f64"}, + {0x019, "v_rndne_f64"}, + {0x01a, "v_floor_f64"}, + {0x01b, "v_pipeflush"}, + {0x020, "v_fract_f32"}, + {0x021, "v_trunc_f32"}, + {0x022, "v_ceil_f32"}, + {0x023, "v_rndne_f32"}, + {0x024, "v_floor_f32"}, + {0x025, "v_exp_f32"}, + {0x027, "v_log_f32"}, + {0x02a, "v_rcp_f32"}, + {0x02b, "v_rcp_iflag_f32"}, + {0x02e, "v_rsq_f32"}, + {0x02f, "v_rcp_f64"}, + {0x031, "v_rsq_f64"}, + {0x033, "v_sqrt_f32"}, + {0x034, "v_sqrt_f64"}, + {0x035, "v_sin_f32"}, + {0x036, "v_cos_f32"}, + {0x037, "v_not_b32"}, + {0x038, "v_bfrev_b32"}, + {0x039, "v_ffbh_u32"}, + {0x03a, "v_ffbl_b32"}, + {0x03b, "v_ffbh_i32"}, + {0x03c, "v_frexp_exp_i32_f64"}, + {0x03d, "v_frexp_mant_f64"}, + {0x03e, "v_fract_f64"}, + {0x03f, "v_frexp_exp_i32_f32"}, + {0x040, "v_frexp_mant_f32"}, + {0x041, "v_clrexcp"}, + {0x042, "v_movreld_b32"}, + {0x043, "v_movrels_b32"}, + {0x044, "v_movrelsd_b32"}, + {0x048, "v_movrelsd_2_b32"}, + {0x050, "v_cvt_f16_u16"}, + {0x051, "v_cvt_f16_i16"}, + {0x052, "v_cvt_u16_f16"}, + {0x053, "v_cvt_i16_f16"}, + {0x054, "v_rcp_f16"}, + {0x055, "v_sqrt_f16"}, + {0x056, "v_rsq_f16"}, + {0x057, "v_log_f16"}, + {0x058, "v_exp_f16"}, + {0x059, "v_frexp_mant_f16"}, + {0x05a, "v_frexp_exp_i16_f16"}, + {0x05b, "v_floor_f16"}, + {0x05c, "v_ceil_f16"}, + {0x05d, "v_trunc_f16"}, + {0x05e, "v_rndne_f16"}, + {0x05f, "v_fract_f16"}, + {0x060, "v_sin_f16"}, + {0x061, "v_cos_f16"}, + {0x062, "v_sat_pk_u8_i16"}, + {0x063, "v_cvt_norm_i16_f16"}, + {0x064, "v_cvt_norm_u16_f16"}, + {0x065, "v_swap_b32"}, + {0x068, "v_swaprel_b32"}, +}; + +constexpr Entry VOPC_[] = { + {0x000, "v_cmp_f_f32"}, + {0x001, "v_cmp_lt_f32"}, + {0x002, "v_cmp_eq_f32"}, + {0x003, "v_cmp_le_f32"}, + {0x004, "v_cmp_gt_f32"}, + {0x005, "v_cmp_lg_f32"}, + {0x006, "v_cmp_ge_f32"}, + {0x007, "v_cmp_o_f32"}, + {0x008, "v_cmp_u_f32"}, + {0x009, "v_cmp_nge_f32"}, + {0x00a, "v_cmp_nlg_f32"}, + {0x00b, "v_cmp_ngt_f32"}, + {0x00c, "v_cmp_nle_f32"}, + {0x00d, "v_cmp_neq_f32"}, + {0x00e, "v_cmp_nlt_f32"}, + {0x00f, "v_cmp_tru_f32"}, + {0x010, "v_cmpx_f_f32"}, + {0x011, "v_cmpx_lt_f32"}, + {0x012, "v_cmpx_eq_f32"}, + {0x013, "v_cmpx_le_f32"}, + {0x014, "v_cmpx_gt_f32"}, + {0x015, "v_cmpx_lg_f32"}, + {0x016, "v_cmpx_ge_f32"}, + {0x017, "v_cmpx_o_f32"}, + {0x018, "v_cmpx_u_f32"}, + {0x019, "v_cmpx_nge_f32"}, + {0x01a, "v_cmpx_nlg_f32"}, + {0x01b, "v_cmpx_ngt_f32"}, + {0x01c, "v_cmpx_nle_f32"}, + {0x01d, "v_cmpx_neq_f32"}, + {0x01e, "v_cmpx_nlt_f32"}, + {0x01f, "v_cmpx_tru_f32"}, + {0x020, "v_cmp_f_f64"}, + {0x021, "v_cmp_lt_f64"}, + {0x022, "v_cmp_eq_f64"}, + {0x023, "v_cmp_le_f64"}, + {0x024, "v_cmp_gt_f64"}, + {0x025, "v_cmp_lg_f64"}, + {0x026, "v_cmp_ge_f64"}, + {0x027, "v_cmp_o_f64"}, + {0x028, "v_cmp_u_f64"}, + {0x029, "v_cmp_nge_f64"}, + {0x02a, "v_cmp_nlg_f64"}, + {0x02b, "v_cmp_ngt_f64"}, + {0x02c, "v_cmp_nle_f64"}, + {0x02d, "v_cmp_neq_f64"}, + {0x02e, "v_cmp_nlt_f64"}, + {0x02f, "v_cmp_tru_f64"}, + {0x030, "v_cmpx_f_f64"}, + {0x031, "v_cmpx_lt_f64"}, + {0x032, "v_cmpx_eq_f64"}, + {0x033, "v_cmpx_le_f64"}, + {0x034, "v_cmpx_gt_f64"}, + {0x035, "v_cmpx_lg_f64"}, + {0x036, "v_cmpx_ge_f64"}, + {0x037, "v_cmpx_o_f64"}, + {0x038, "v_cmpx_u_f64"}, + {0x039, "v_cmpx_nge_f64"}, + {0x03a, "v_cmpx_nlg_f64"}, + {0x03b, "v_cmpx_ngt_f64"}, + {0x03c, "v_cmpx_nle_f64"}, + {0x03d, "v_cmpx_neq_f64"}, + {0x03e, "v_cmpx_nlt_f64"}, + {0x03f, "v_cmpx_tru_f64"}, + {0x080, "v_cmp_f_i32"}, + {0x081, "v_cmp_lt_i32"}, + {0x082, "v_cmp_eq_i32"}, + {0x083, "v_cmp_le_i32"}, + {0x084, "v_cmp_gt_i32"}, + {0x085, "v_cmp_ne_i32"}, + {0x086, "v_cmp_ge_i32"}, + {0x087, "v_cmp_t_i32"}, + {0x088, "v_cmp_class_f32"}, + {0x089, "v_cmp_lt_i16"}, + {0x08a, "v_cmp_eq_i16"}, + {0x08b, "v_cmp_le_i16"}, + {0x08c, "v_cmp_gt_i16"}, + {0x08d, "v_cmp_ne_i16"}, + {0x08e, "v_cmp_ge_i16"}, + {0x08f, "v_cmp_class_f16"}, + {0x090, "v_cmpx_f_i32"}, + {0x091, "v_cmpx_lt_i32"}, + {0x092, "v_cmpx_eq_i32"}, + {0x093, "v_cmpx_le_i32"}, + {0x094, "v_cmpx_gt_i32"}, + {0x095, "v_cmpx_ne_i32"}, + {0x096, "v_cmpx_ge_i32"}, + {0x097, "v_cmpx_t_i32"}, + {0x098, "v_cmpx_class_f32"}, + {0x099, "v_cmpx_lt_i16"}, + {0x09a, "v_cmpx_eq_i16"}, + {0x09b, "v_cmpx_le_i16"}, + {0x09c, "v_cmpx_gt_i16"}, + {0x09d, "v_cmpx_ne_i16"}, + {0x09e, "v_cmpx_ge_i16"}, + {0x09f, "v_cmpx_class_f16"}, + {0x0a0, "v_cmp_f_i64"}, + {0x0a1, "v_cmp_lt_i64"}, + {0x0a2, "v_cmp_eq_i64"}, + {0x0a3, "v_cmp_le_i64"}, + {0x0a4, "v_cmp_gt_i64"}, + {0x0a5, "v_cmp_ne_i64"}, + {0x0a6, "v_cmp_ge_i64"}, + {0x0a7, "v_cmp_t_i64"}, + {0x0a8, "v_cmp_class_f64"}, + {0x0a9, "v_cmp_lt_u16"}, + {0x0aa, "v_cmp_eq_u16"}, + {0x0ab, "v_cmp_le_u16"}, + {0x0ac, "v_cmp_gt_u16"}, + {0x0ad, "v_cmp_ne_u16"}, + {0x0ae, "v_cmp_ge_u16"}, + {0x0b0, "v_cmpx_f_i64"}, + {0x0b1, "v_cmpx_lt_i64"}, + {0x0b2, "v_cmpx_eq_i64"}, + {0x0b3, "v_cmpx_le_i64"}, + {0x0b4, "v_cmpx_gt_i64"}, + {0x0b5, "v_cmpx_ne_i64"}, + {0x0b6, "v_cmpx_ge_i64"}, + {0x0b7, "v_cmpx_t_i64"}, + {0x0b8, "v_cmpx_class_f64"}, + {0x0b9, "v_cmpx_lt_u16"}, + {0x0ba, "v_cmpx_eq_u16"}, + {0x0bb, "v_cmpx_le_u16"}, + {0x0bc, "v_cmpx_gt_u16"}, + {0x0bd, "v_cmpx_ne_u16"}, + {0x0be, "v_cmpx_ge_u16"}, + {0x0c0, "v_cmp_f_u32"}, + {0x0c1, "v_cmp_lt_u32"}, + {0x0c2, "v_cmp_eq_u32"}, + {0x0c3, "v_cmp_le_u32"}, + {0x0c4, "v_cmp_gt_u32"}, + {0x0c5, "v_cmp_ne_u32"}, + {0x0c6, "v_cmp_ge_u32"}, + {0x0c7, "v_cmp_t_u32"}, + {0x0c8, "v_cmp_f_f16"}, + {0x0c9, "v_cmp_lt_f16"}, + {0x0ca, "v_cmp_eq_f16"}, + {0x0cb, "v_cmp_le_f16"}, + {0x0cc, "v_cmp_gt_f16"}, + {0x0cd, "v_cmp_lg_f16"}, + {0x0ce, "v_cmp_ge_f16"}, + {0x0cf, "v_cmp_o_f16"}, + {0x0d0, "v_cmpx_f_u32"}, + {0x0d1, "v_cmpx_lt_u32"}, + {0x0d2, "v_cmpx_eq_u32"}, + {0x0d3, "v_cmpx_le_u32"}, + {0x0d4, "v_cmpx_gt_u32"}, + {0x0d5, "v_cmpx_ne_u32"}, + {0x0d6, "v_cmpx_ge_u32"}, + {0x0d7, "v_cmpx_t_u32"}, + {0x0d8, "v_cmpx_f_f16"}, + {0x0d9, "v_cmpx_lt_f16"}, + {0x0da, "v_cmpx_eq_f16"}, + {0x0db, "v_cmpx_le_f16"}, + {0x0dc, "v_cmpx_gt_f16"}, + {0x0dd, "v_cmpx_lg_f16"}, + {0x0de, "v_cmpx_ge_f16"}, + {0x0df, "v_cmpx_o_f16"}, + {0x0e0, "v_cmp_f_u64"}, + {0x0e1, "v_cmp_lt_u64"}, + {0x0e2, "v_cmp_eq_u64"}, + {0x0e3, "v_cmp_le_u64"}, + {0x0e4, "v_cmp_gt_u64"}, + {0x0e5, "v_cmp_ne_u64"}, + {0x0e6, "v_cmp_ge_u64"}, + {0x0e7, "v_cmp_t_u64"}, + {0x0e8, "v_cmp_u_f16"}, + {0x0e9, "v_cmp_nge_f16"}, + {0x0ea, "v_cmp_nlg_f16"}, + {0x0eb, "v_cmp_ngt_f16"}, + {0x0ec, "v_cmp_nle_f16"}, + {0x0ed, "v_cmp_neq_f16"}, + {0x0ee, "v_cmp_nlt_f16"}, + {0x0ef, "v_cmp_tru_f16"}, + {0x0f0, "v_cmpx_f_u64"}, + {0x0f1, "v_cmpx_lt_u64"}, + {0x0f2, "v_cmpx_eq_u64"}, + {0x0f3, "v_cmpx_le_u64"}, + {0x0f4, "v_cmpx_gt_u64"}, + {0x0f5, "v_cmpx_ne_u64"}, + {0x0f6, "v_cmpx_ge_u64"}, + {0x0f7, "v_cmpx_t_u64"}, + {0x0f8, "v_cmpx_u_f16"}, + {0x0f9, "v_cmpx_nge_f16"}, + {0x0fa, "v_cmpx_nlg_f16"}, + {0x0fb, "v_cmpx_ngt_f16"}, + {0x0fc, "v_cmpx_nle_f16"}, + {0x0fd, "v_cmpx_neq_f16"}, + {0x0fe, "v_cmpx_nlt_f16"}, + {0x0ff, "v_cmpx_tru_f16"}, +}; + +constexpr Entry VOP3_[] = { + {0x140, "v_mad_legacy_f32"}, + {0x141, "v_mad_f32"}, + {0x142, "v_mad_i32_i24"}, + {0x143, "v_mad_u32_u24"}, + {0x144, "v_cubeid_f32"}, + {0x145, "v_cubesc_f32"}, + {0x146, "v_cubetc_f32"}, + {0x147, "v_cubema_f32"}, + {0x148, "v_bfe_u32"}, + {0x149, "v_bfe_i32"}, + {0x14a, "v_bfi_b32"}, + {0x14b, "v_fma_f32"}, + {0x14c, "v_fma_f64"}, + {0x14d, "v_lerp_u8"}, + {0x14e, "v_alignbit_b32"}, + {0x14f, "v_alignbyte_b32"}, + {0x150, "v_mullit_f32"}, + {0x151, "v_min3_f32"}, + {0x152, "v_min3_i32"}, + {0x153, "v_min3_u32"}, + {0x154, "v_max3_f32"}, + {0x155, "v_max3_i32"}, + {0x156, "v_max3_u32"}, + {0x157, "v_med3_f32"}, + {0x158, "v_med3_i32"}, + {0x159, "v_med3_u32"}, + {0x15a, "v_sad_u8"}, + {0x15b, "v_sad_hi_u8"}, + {0x15c, "v_sad_u16"}, + {0x15d, "v_sad_u32"}, + {0x15e, "v_cvt_pk_u8_f32"}, + {0x15f, "v_div_fixup_f32"}, + {0x160, "v_div_fixup_f64"}, + {0x164, "v_add_f64"}, + {0x165, "v_mul_f64"}, + {0x166, "v_min_f64"}, + {0x167, "v_max_f64"}, + {0x168, "v_ldexp_f64"}, + {0x169, "v_mul_lo_u32"}, + {0x16a, "v_mul_hi_u32"}, + {0x16b, "v_mul_lo_i32"}, + {0x16c, "v_mul_hi_i32"}, + {0x16d, "v_div_scale_f32"}, + {0x16e, "v_div_scale_f64"}, + {0x16f, "v_div_fmas_f32"}, + {0x170, "v_div_fmas_f64"}, + {0x171, "v_msad_u8"}, + {0x172, "v_qsad_pk_u16_u8"}, + {0x173, "v_mqsad_pk_u16_u8"}, + {0x174, "v_trig_preop_f64"}, + {0x175, "v_mqsad_u32_u8"}, + {0x176, "v_mad_u64_u32"}, + {0x177, "v_mad_i64_i32"}, + {0x178, "v_xor3_b32"}, + {0x2ff, "v_lshlrev_b64"}, + {0x300, "v_lshrrev_b64"}, + {0x301, "v_ashrrev_i64"}, + {0x303, "v_add_nc_u16"}, + {0x304, "v_sub_nc_u16"}, + {0x305, "v_mul_lo_u16"}, + {0x307, "v_lshrrev_b16"}, + {0x308, "v_ashrrev_i16"}, + {0x309, "v_max_u16"}, + {0x30a, "v_max_i16"}, + {0x30b, "v_min_u16"}, + {0x30c, "v_min_i16"}, + {0x30d, "v_add_nc_i16"}, + {0x30e, "v_sub_nc_i16"}, + {0x30f, "v_add_co_u32"}, + {0x310, "v_sub_co_u32"}, + {0x311, "v_pack_b32_f16"}, + {0x312, "v_cvt_pknorm_i16_f16"}, + {0x313, "v_cvt_pknorm_u16_f16"}, + {0x314, "v_lshlrev_b16"}, + {0x319, "v_subrev_co_u32"}, + {0x340, "v_mad_u16"}, + {0x342, "v_interp_p1ll_f16"}, + {0x343, "v_interp_p1lv_f16"}, + {0x344, "v_perm_b32"}, + {0x345, "v_xad_u32"}, + {0x346, "v_lshl_add_u32"}, + {0x347, "v_add_lshl_u32"}, + {0x34b, "v_fma_f16"}, + {0x351, "v_min3_f16"}, + {0x352, "v_min3_i16"}, + {0x353, "v_min3_u16"}, + {0x354, "v_max3_f16"}, + {0x355, "v_max3_i16"}, + {0x356, "v_max3_u16"}, + {0x357, "v_med3_f16"}, + {0x358, "v_med3_i16"}, + {0x359, "v_med3_u16"}, + {0x35a, "v_interp_p2_f16"}, + {0x35e, "v_mad_i16"}, + {0x35f, "v_div_fixup_f16"}, + {0x360, "v_readlane_b32"}, + {0x361, "v_writelane_b32"}, + {0x362, "v_ldexp_f32"}, + {0x363, "v_bfm_b32"}, + {0x364, "v_bcnt_u32_b32"}, + {0x365, "v_mbcnt_lo_u32_b32"}, + {0x366, "v_mbcnt_hi_u32_b32"}, + {0x368, "v_cvt_pknorm_i16_f32"}, + {0x369, "v_cvt_pknorm_u16_f32"}, + {0x36a, "v_cvt_pk_u16_u32"}, + {0x36b, "v_cvt_pk_i16_i32"}, + {0x36d, "v_add3_u32"}, + {0x36f, "v_lshl_or_b32"}, + {0x371, "v_and_or_b32"}, + {0x372, "v_or3_b32"}, + {0x373, "v_mad_u32_u16"}, + {0x375, "v_mad_i32_i16"}, + {0x376, "v_sub_nc_i32"}, + {0x377, "v_permlane16_b32"}, + {0x378, "v_permlanex16_b32"}, + {0x37f, "v_add_nc_i32"}, +}; + +constexpr Entry VOP3P_[] = { + {0x000, "v_pk_mad_i16"}, + {0x001, "v_pk_mul_lo_u16"}, + {0x002, "v_pk_add_i16"}, + {0x003, "v_pk_sub_i16"}, + {0x004, "v_pk_lshlrev_b16"}, + {0x005, "v_pk_lshrrev_b16"}, + {0x006, "v_pk_ashrrev_i16"}, + {0x007, "v_pk_max_i16"}, + {0x008, "v_pk_min_i16"}, + {0x009, "v_pk_mad_u16"}, + {0x00a, "v_pk_add_u16"}, + {0x00b, "v_pk_sub_u16"}, + {0x00c, "v_pk_max_u16"}, + {0x00d, "v_pk_min_u16"}, + {0x00e, "v_pk_fma_f16"}, + {0x00f, "v_pk_add_f16"}, + {0x010, "v_pk_mul_f16"}, + {0x011, "v_pk_min_f16"}, + {0x012, "v_pk_max_f16"}, + {0x013, "v_dot2_f32_f16"}, + {0x014, "v_dot2_i32_i16"}, + {0x015, "v_dot2_u32_u16"}, + {0x016, "v_dot4_i32_i8"}, + {0x017, "v_dot4_u32_u8"}, + {0x019, "v_dot8_u32_u4"}, + {0x020, "v_fma_mix_f32"}, + {0x021, "v_fma_mixlo_f16"}, + {0x022, "v_fma_mixhi_f16"}, +}; + +constexpr Entry VINTRP_[] = { + {0x000, "v_interp_p1_f32"}, + {0x001, "v_interp_p2_f32"}, + {0x002, "v_interp_mov_f32"}, +}; + +constexpr Entry DS_[] = { + {0x000, "ds_add_u32"}, + {0x001, "ds_sub_u32"}, + {0x002, "ds_rsub_u32"}, + {0x003, "ds_inc_u32"}, + {0x004, "ds_dec_u32"}, + {0x005, "ds_min_i32"}, + {0x006, "ds_max_i32"}, + {0x007, "ds_min_u32"}, + {0x008, "ds_max_u32"}, + {0x009, "ds_and_b32"}, + {0x00a, "ds_or_b32"}, + {0x00b, "ds_xor_b32"}, + {0x00c, "ds_mskor_b32"}, + {0x00d, "ds_write_b32"}, + {0x00e, "ds_write2_b32"}, + {0x00f, "ds_write2st64_b32"}, + {0x010, "ds_cmpst_b32"}, + {0x011, "ds_cmpst_f32"}, + {0x012, "ds_min_f32"}, + {0x013, "ds_max_f32"}, + {0x014, "ds_nop"}, + {0x015, "ds_add_f32"}, + {0x018, "ds_gws_sema_release_all"}, + {0x019, "ds_gws_init"}, + {0x01a, "ds_gws_sema_v"}, + {0x01b, "ds_gws_sema_br"}, + {0x01c, "ds_gws_sema_p"}, + {0x01d, "ds_gws_barrier"}, + {0x01e, "ds_write_b8"}, + {0x01f, "ds_write_b16"}, + {0x020, "ds_add_rtn_u32"}, + {0x021, "ds_sub_rtn_u32"}, + {0x022, "ds_rsub_rtn_u32"}, + {0x023, "ds_inc_rtn_u32"}, + {0x024, "ds_dec_rtn_u32"}, + {0x025, "ds_min_rtn_i32"}, + {0x026, "ds_max_rtn_i32"}, + {0x027, "ds_min_rtn_u32"}, + {0x028, "ds_max_rtn_u32"}, + {0x029, "ds_and_rtn_b32"}, + {0x02a, "ds_or_rtn_b32"}, + {0x02b, "ds_xor_rtn_b32"}, + {0x02c, "ds_mskor_rtn_b32"}, + {0x02d, "ds_wrxchg_rtn_b32"}, + {0x02e, "ds_wrxchg2_rtn_b32"}, + {0x02f, "ds_wrxchg2st64_rtn_b32"}, + {0x030, "ds_cmpst_rtn_b32"}, + {0x031, "ds_cmpst_rtn_f32"}, + {0x032, "ds_min_rtn_f32"}, + {0x033, "ds_max_rtn_f32"}, + {0x034, "ds_wrap_rtn_b32"}, + {0x035, "ds_swizzle_b32"}, + {0x036, "ds_read_b32"}, + {0x037, "ds_read2_b32"}, + {0x038, "ds_read2st64_b32"}, + {0x039, "ds_read_i8"}, + {0x03a, "ds_read_u8"}, + {0x03b, "ds_read_i16"}, + {0x03c, "ds_read_u16"}, + {0x03d, "ds_consume"}, + {0x03e, "ds_append"}, + {0x03f, "ds_ordered_count"}, + {0x040, "ds_add_u64"}, + {0x041, "ds_sub_u64"}, + {0x042, "ds_rsub_u64"}, + {0x043, "ds_inc_u64"}, + {0x044, "ds_dec_u64"}, + {0x045, "ds_min_i64"}, + {0x046, "ds_max_i64"}, + {0x047, "ds_min_u64"}, + {0x048, "ds_max_u64"}, + {0x049, "ds_and_b64"}, + {0x04a, "ds_or_b64"}, + {0x04b, "ds_xor_b64"}, + {0x04c, "ds_mskor_b64"}, + {0x04d, "ds_write_b64"}, + {0x04e, "ds_write2_b64"}, + {0x04f, "ds_write2st64_b64"}, + {0x050, "ds_cmpst_b64"}, + {0x051, "ds_cmpst_f64"}, + {0x052, "ds_min_f64"}, + {0x053, "ds_max_f64"}, + {0x055, "ds_add_rtn_f32"}, + {0x060, "ds_add_rtn_u64"}, + {0x061, "ds_sub_rtn_u64"}, + {0x062, "ds_rsub_rtn_u64"}, + {0x063, "ds_inc_rtn_u64"}, + {0x064, "ds_dec_rtn_u64"}, + {0x065, "ds_min_rtn_i64"}, + {0x066, "ds_max_rtn_i64"}, + {0x067, "ds_min_rtn_u64"}, + {0x068, "ds_max_rtn_u64"}, + {0x069, "ds_and_rtn_b64"}, + {0x06a, "ds_or_rtn_b64"}, + {0x06b, "ds_xor_rtn_b64"}, + {0x06c, "ds_mskor_rtn_b64"}, + {0x06d, "ds_wrxchg_rtn_b64"}, + {0x06e, "ds_wrxchg2_rtn_b64"}, + {0x06f, "ds_wrxchg2st64_rtn_b64"}, + {0x070, "ds_cmpst_rtn_b64"}, + {0x071, "ds_cmpst_rtn_f64"}, + {0x072, "ds_min_rtn_f64"}, + {0x073, "ds_max_rtn_f64"}, + {0x076, "ds_read_b64"}, + {0x077, "ds_read2_b64"}, + {0x078, "ds_read2st64_b64"}, + {0x07e, "ds_condxchg32_rtn_b64"}, + {0x080, "ds_add_src2_u32"}, + {0x081, "ds_sub_src2_u32"}, + {0x082, "ds_rsub_src2_u32"}, + {0x083, "ds_inc_src2_u32"}, + {0x084, "ds_dec_src2_u32"}, + {0x085, "ds_min_src2_i32"}, + {0x086, "ds_max_src2_i32"}, + {0x087, "ds_min_src2_u32"}, + {0x088, "ds_max_src2_u32"}, + {0x089, "ds_and_src2_b32"}, + {0x08a, "ds_or_src2_b32"}, + {0x08b, "ds_xor_src2_b32"}, + {0x08d, "ds_write_src2_b32"}, + {0x092, "ds_min_src2_f32"}, + {0x093, "ds_max_src2_f32"}, + {0x095, "ds_add_src2_f32"}, + {0x0a0, "ds_write_b8_d16_hi"}, + {0x0a1, "ds_write_b16_d16_hi"}, + {0x0a2, "ds_read_u8_d16"}, + {0x0a3, "ds_read_u8_d16_hi"}, + {0x0a4, "ds_read_i8_d16"}, + {0x0a5, "ds_read_i8_d16_hi"}, + {0x0a6, "ds_read_u16_d16"}, + {0x0a7, "ds_read_u16_d16_hi"}, + {0x0b0, "ds_write_addtid_b32"}, + {0x0b1, "ds_read_addtid_b32"}, + {0x0b2, "ds_permute_b32"}, + {0x0b3, "ds_bpermute_b32"}, + {0x0c0, "ds_add_src2_u64"}, + {0x0c1, "ds_sub_src2_u64"}, + {0x0c2, "ds_rsub_src2_u64"}, + {0x0c3, "ds_inc_src2_u64"}, + {0x0c4, "ds_dec_src2_u64"}, + {0x0c5, "ds_min_src2_i64"}, + {0x0c6, "ds_max_src2_i64"}, + {0x0c7, "ds_min_src2_u64"}, + {0x0c8, "ds_max_src2_u64"}, + {0x0c9, "ds_and_src2_b64"}, + {0x0ca, "ds_or_src2_b64"}, + {0x0cb, "ds_xor_src2_b64"}, + {0x0cd, "ds_write_src2_b64"}, + {0x0d2, "ds_min_src2_f64"}, + {0x0d3, "ds_max_src2_f64"}, + {0x0de, "ds_write_b96"}, + {0x0df, "ds_write_b128"}, + {0x0fe, "ds_read_b96"}, + {0x0ff, "ds_read_b128"}, +}; + +constexpr Entry MUBUF_[] = { + {0x000, "buffer_load_format_x"}, + {0x001, "buffer_load_format_xy"}, + {0x002, "buffer_load_format_xyz"}, + {0x003, "buffer_load_format_xyzw"}, + {0x004, "buffer_store_format_x"}, + {0x005, "buffer_store_format_xy"}, + {0x006, "buffer_store_format_xyz"}, + {0x007, "buffer_store_format_xyzw"}, + {0x008, "buffer_load_ubyte"}, + {0x009, "buffer_load_sbyte"}, + {0x00a, "buffer_load_ushort"}, + {0x00b, "buffer_load_sshort"}, + {0x00c, "buffer_load_dword"}, + {0x00d, "buffer_load_dwordx2"}, + {0x00e, "buffer_load_dwordx4"}, + {0x00f, "buffer_load_dwordx3"}, + {0x018, "buffer_store_byte"}, + {0x019, "buffer_store_byte_d16_hi"}, + {0x01a, "buffer_store_short"}, + {0x01b, "buffer_store_short_d16_hi"}, + {0x01c, "buffer_store_dword"}, + {0x01d, "buffer_store_dwordx2"}, + {0x01e, "buffer_store_dwordx4"}, + {0x01f, "buffer_store_dwordx3"}, + {0x020, "buffer_load_ubyte_d16"}, + {0x021, "buffer_load_ubyte_d16_hi"}, + {0x022, "buffer_load_sbyte_d16"}, + {0x023, "buffer_load_sbyte_d16_hi"}, + {0x024, "buffer_load_short_d16"}, + {0x025, "buffer_load_short_d16_hi"}, + {0x026, "buffer_load_format_d16_hi_x"}, + {0x027, "buffer_store_format_d16_hi_x"}, + {0x030, "buffer_atomic_swap"}, + {0x031, "buffer_atomic_cmpswap"}, + {0x032, "buffer_atomic_add"}, + {0x033, "buffer_atomic_sub"}, + {0x034, "buffer_atomic_csub"}, + {0x035, "buffer_atomic_smin"}, + {0x036, "buffer_atomic_umin"}, + {0x037, "buffer_atomic_smax"}, + {0x038, "buffer_atomic_umax"}, + {0x039, "buffer_atomic_and"}, + {0x03a, "buffer_atomic_or"}, + {0x03b, "buffer_atomic_xor"}, + {0x03c, "buffer_atomic_inc"}, + {0x03d, "buffer_atomic_dec"}, + {0x03e, "buffer_atomic_fcmpswap"}, + {0x03f, "buffer_atomic_fmin"}, + {0x040, "buffer_atomic_fmax"}, + {0x050, "buffer_atomic_swap_x2"}, + {0x051, "buffer_atomic_cmpswap_x2"}, + {0x052, "buffer_atomic_add_x2"}, + {0x053, "buffer_atomic_sub_x2"}, + {0x055, "buffer_atomic_smin_x2"}, + {0x056, "buffer_atomic_umin_x2"}, + {0x057, "buffer_atomic_smax_x2"}, + {0x058, "buffer_atomic_umax_x2"}, + {0x059, "buffer_atomic_and_x2"}, + {0x05a, "buffer_atomic_or_x2"}, + {0x05b, "buffer_atomic_xor_x2"}, + {0x05c, "buffer_atomic_inc_x2"}, + {0x05d, "buffer_atomic_dec_x2"}, + {0x05e, "buffer_atomic_fcmpswap_x2"}, + {0x05f, "buffer_atomic_fmin_x2"}, + {0x060, "buffer_atomic_fmax_x2"}, + {0x071, "buffer_gl0_inv"}, + {0x072, "buffer_gl1_inv"}, + {0x080, "buffer_load_format_d16_x"}, + {0x081, "buffer_load_format_d16_xy"}, + {0x082, "buffer_load_format_d16_xyz"}, + {0x083, "buffer_load_format_d16_xyzw"}, + {0x084, "buffer_store_format_d16_x"}, + {0x085, "buffer_store_format_d16_xy"}, + {0x086, "buffer_store_format_d16_xyz"}, + {0x087, "buffer_store_format_d16_xyzw"}, +}; + +constexpr Entry MTBUF_[] = { + {0x000, "tbuffer_load_format_x"}, + {0x001, "tbuffer_load_format_xy"}, + {0x002, "tbuffer_load_format_xyz"}, + {0x003, "tbuffer_load_format_xyzw"}, + {0x004, "tbuffer_store_format_x"}, + {0x005, "tbuffer_store_format_xy"}, + {0x006, "tbuffer_store_format_xyz"}, + {0x007, "tbuffer_store_format_xyzw"}, + {0x008, "tbuffer_load_format_d16_x"}, + {0x009, "tbuffer_load_format_d16_xy"}, + {0x00a, "tbuffer_load_format_d16_xyz"}, + {0x00b, "tbuffer_load_format_d16_xyzw"}, + {0x00c, "tbuffer_store_format_d16_x"}, + {0x00d, "tbuffer_store_format_d16_xy"}, + {0x00e, "tbuffer_store_format_d16_xyz"}, + {0x00f, "tbuffer_store_format_d16_xyzw"}, +}; + +constexpr Entry MIMG_[] = { + {0x000, "image_load"}, + {0x001, "image_load_mip"}, + {0x002, "image_load_pck"}, + {0x003, "image_load_pck_sgn"}, + {0x004, "image_load_mip_pck"}, + {0x005, "image_load_mip_pck_sgn"}, + {0x008, "image_store"}, + {0x009, "image_store_mip"}, + {0x00a, "image_store_pck"}, + {0x00b, "image_store_mip_pck"}, + {0x00e, "image_get_resinfo"}, + {0x00f, "image_atomic_swap"}, + {0x010, "image_atomic_cmpswap"}, + {0x011, "image_atomic_add"}, + {0x012, "image_atomic_sub"}, + {0x014, "image_atomic_smin"}, + {0x015, "image_atomic_umin"}, + {0x016, "image_atomic_smax"}, + {0x017, "image_atomic_umax"}, + {0x018, "image_atomic_and"}, + {0x019, "image_atomic_or"}, + {0x01a, "image_atomic_xor"}, + {0x01b, "image_atomic_inc"}, + {0x01c, "image_atomic_dec"}, + {0x01d, "image_atomic_fcmpswap"}, + {0x01e, "image_atomic_fmin"}, + {0x01f, "image_atomic_fmax"}, + {0x020, "image_sample"}, + {0x021, "image_sample_cl"}, + {0x022, "image_sample_d"}, + {0x023, "image_sample_d_cl"}, + {0x024, "image_sample_l"}, + {0x025, "image_sample_b"}, + {0x026, "image_sample_b_cl"}, + {0x027, "image_sample_lz"}, + {0x028, "image_sample_c"}, + {0x029, "image_sample_c_cl"}, + {0x02a, "image_sample_c_d"}, + {0x02b, "image_sample_c_d_cl"}, + {0x02c, "image_sample_c_l"}, + {0x02d, "image_sample_c_b"}, + {0x02e, "image_sample_c_b_cl"}, + {0x02f, "image_sample_c_lz"}, + {0x030, "image_sample_o"}, + {0x031, "image_sample_cl_o"}, + {0x032, "image_sample_d_o"}, + {0x033, "image_sample_d_cl_o"}, + {0x034, "image_sample_l_o"}, + {0x035, "image_sample_b_o"}, + {0x036, "image_sample_b_cl_o"}, + {0x037, "image_sample_lz_o"}, + {0x038, "image_sample_c_o"}, + {0x039, "image_sample_c_cl_o"}, + {0x03a, "image_sample_c_d_o"}, + {0x03b, "image_sample_c_d_cl_o"}, + {0x03c, "image_sample_c_l_o"}, + {0x03d, "image_sample_c_b_o"}, + {0x03e, "image_sample_c_b_cl_o"}, + {0x03f, "image_sample_c_lz_o"}, + {0x040, "image_gather4"}, + {0x041, "image_gather4_cl"}, + {0x044, "image_gather4_l"}, + {0x045, "image_gather4_b"}, + {0x046, "image_gather4_b_cl"}, + {0x047, "image_gather4_lz"}, + {0x048, "image_gather4_c"}, + {0x049, "image_gather4_c_cl"}, + {0x04c, "image_gather4_c_l"}, + {0x04d, "image_gather4_c_b"}, + {0x04e, "image_gather4_c_b_cl"}, + {0x04f, "image_gather4_c_lz"}, + {0x050, "image_gather4_o"}, + {0x051, "image_gather4_cl_o"}, + {0x054, "image_gather4_l_o"}, + {0x055, "image_gather4_b_o"}, + {0x056, "image_gather4_b_cl_o"}, + {0x057, "image_gather4_lz_o"}, + {0x058, "image_gather4_c_o"}, + {0x059, "image_gather4_c_cl_o"}, + {0x05c, "image_gather4_c_l_o"}, + {0x05d, "image_gather4_c_b_o"}, + {0x05e, "image_gather4_c_b_cl_o"}, + {0x05f, "image_gather4_c_lz_o"}, + {0x060, "image_get_lod"}, + {0x068, "image_sample_cd"}, + {0x069, "image_sample_cd_cl"}, + {0x06a, "image_sample_c_cd"}, + {0x06b, "image_sample_c_cd_cl"}, + {0x06c, "image_sample_cd_o"}, + {0x06d, "image_sample_cd_cl_o"}, + {0x06e, "image_sample_c_cd_o"}, + {0x06f, "image_sample_c_cd_cl_o"}, + {0x080, "image_msaa_load"}, + {0x0a2, "image_sample_d_g16"}, + {0x0a3, "image_sample_d_cl_g16"}, + {0x0aa, "image_sample_c_d_g16"}, + {0x0ab, "image_sample_c_d_cl_g16"}, + {0x0b2, "image_sample_d_o_g16"}, + {0x0b3, "image_sample_d_cl_o_g16"}, + {0x0ba, "image_sample_c_d_o_g16"}, + {0x0bb, "image_sample_c_d_cl_o_g16"}, + {0x0e6, "image_bvh_intersect_ray"}, + {0x0e7, "image_bvh64_intersect_ray"}, +}; + +constexpr Entry FLAT_[] = { + {0x008, "flat_load_ubyte"}, + {0x009, "flat_load_sbyte"}, + {0x00a, "flat_load_ushort"}, + {0x00b, "flat_load_sshort"}, + {0x00c, "flat_load_dword"}, + {0x00d, "flat_load_dwordx2"}, + {0x00e, "flat_load_dwordx4"}, + {0x00f, "flat_load_dwordx3"}, + {0x018, "flat_store_byte"}, + {0x019, "flat_store_byte_d16_hi"}, + {0x01a, "flat_store_short"}, + {0x01b, "flat_store_short_d16_hi"}, + {0x01c, "flat_store_dword"}, + {0x01d, "flat_store_dwordx2"}, + {0x01e, "flat_store_dwordx4"}, + {0x01f, "flat_store_dwordx3"}, + {0x020, "flat_load_ubyte_d16"}, + {0x021, "flat_load_ubyte_d16_hi"}, + {0x022, "flat_load_sbyte_d16"}, + {0x023, "flat_load_sbyte_d16_hi"}, + {0x024, "flat_load_short_d16"}, + {0x025, "flat_load_short_d16_hi"}, + {0x030, "flat_atomic_swap"}, + {0x031, "flat_atomic_cmpswap"}, + {0x032, "flat_atomic_add"}, + {0x033, "flat_atomic_sub"}, + {0x035, "flat_atomic_smin"}, + {0x036, "flat_atomic_umin"}, + {0x037, "flat_atomic_smax"}, + {0x038, "flat_atomic_umax"}, + {0x039, "flat_atomic_and"}, + {0x03a, "flat_atomic_or"}, + {0x03b, "flat_atomic_xor"}, + {0x03c, "flat_atomic_inc"}, + {0x03d, "flat_atomic_dec"}, + {0x03e, "flat_atomic_fcmpswap"}, + {0x03f, "flat_atomic_fmin"}, + {0x040, "flat_atomic_fmax"}, + {0x050, "flat_atomic_swap_x2"}, + {0x051, "flat_atomic_cmpswap_x2"}, + {0x052, "flat_atomic_add_x2"}, + {0x053, "flat_atomic_sub_x2"}, + {0x055, "flat_atomic_smin_x2"}, + {0x056, "flat_atomic_umin_x2"}, + {0x057, "flat_atomic_smax_x2"}, + {0x058, "flat_atomic_umax_x2"}, + {0x059, "flat_atomic_and_x2"}, + {0x05a, "flat_atomic_or_x2"}, + {0x05b, "flat_atomic_xor_x2"}, + {0x05c, "flat_atomic_inc_x2"}, + {0x05d, "flat_atomic_dec_x2"}, + {0x05e, "flat_atomic_fcmpswap_x2"}, + {0x05f, "flat_atomic_fmin_x2"}, + {0x060, "flat_atomic_fmax_x2"}, +}; + +constexpr Entry GLOBAL_[] = { + {0x008, "global_load_ubyte"}, + {0x009, "global_load_sbyte"}, + {0x00a, "global_load_ushort"}, + {0x00b, "global_load_sshort"}, + {0x00c, "global_load_dword"}, + {0x00d, "global_load_dwordx2"}, + {0x00e, "global_load_dwordx4"}, + {0x00f, "global_load_dwordx3"}, + {0x016, "global_load_dword_addtid"}, + {0x017, "global_store_dword_addtid"}, + {0x018, "global_store_byte"}, + {0x019, "global_store_byte_d16_hi"}, + {0x01a, "global_store_short"}, + {0x01b, "global_store_short_d16_hi"}, + {0x01c, "global_store_dword"}, + {0x01d, "global_store_dwordx2"}, + {0x01e, "global_store_dwordx4"}, + {0x01f, "global_store_dwordx3"}, + {0x020, "global_load_ubyte_d16"}, + {0x021, "global_load_ubyte_d16_hi"}, + {0x022, "global_load_sbyte_d16"}, + {0x023, "global_load_sbyte_d16_hi"}, + {0x024, "global_load_short_d16"}, + {0x025, "global_load_short_d16_hi"}, + {0x030, "global_atomic_swap"}, + {0x031, "global_atomic_cmpswap"}, + {0x032, "global_atomic_add"}, + {0x033, "global_atomic_sub"}, + {0x034, "global_atomic_csub"}, + {0x035, "global_atomic_smin"}, + {0x036, "global_atomic_umin"}, + {0x037, "global_atomic_smax"}, + {0x038, "global_atomic_umax"}, + {0x039, "global_atomic_and"}, + {0x03a, "global_atomic_or"}, + {0x03b, "global_atomic_xor"}, + {0x03c, "global_atomic_inc"}, + {0x03d, "global_atomic_dec"}, + {0x03e, "global_atomic_fcmpswap"}, + {0x03f, "global_atomic_fmin"}, + {0x040, "global_atomic_fmax"}, + {0x050, "global_atomic_swap_x2"}, + {0x051, "global_atomic_cmpswap_x2"}, + {0x052, "global_atomic_add_x2"}, + {0x053, "global_atomic_sub_x2"}, + {0x055, "global_atomic_smin_x2"}, + {0x056, "global_atomic_umin_x2"}, + {0x057, "global_atomic_smax_x2"}, + {0x058, "global_atomic_umax_x2"}, + {0x059, "global_atomic_and_x2"}, + {0x05a, "global_atomic_or_x2"}, + {0x05b, "global_atomic_xor_x2"}, + {0x05c, "global_atomic_inc_x2"}, + {0x05d, "global_atomic_dec_x2"}, + {0x05e, "global_atomic_fcmpswap_x2"}, + {0x05f, "global_atomic_fmin_x2"}, + {0x060, "global_atomic_fmax_x2"}, +}; + +constexpr Entry SCRATCH_[] = { + {0x008, "scratch_load_ubyte"}, + {0x009, "scratch_load_sbyte"}, + {0x00a, "scratch_load_ushort"}, + {0x00b, "scratch_load_sshort"}, + {0x00c, "scratch_load_dword"}, + {0x00d, "scratch_load_dwordx2"}, + {0x00e, "scratch_load_dwordx4"}, + {0x00f, "scratch_load_dwordx3"}, + {0x018, "scratch_store_byte"}, + {0x019, "scratch_store_byte_d16_hi"}, + {0x01a, "scratch_store_short"}, + {0x01b, "scratch_store_short_d16_hi"}, + {0x01c, "scratch_store_dword"}, + {0x01d, "scratch_store_dwordx2"}, + {0x01e, "scratch_store_dwordx4"}, + {0x01f, "scratch_store_dwordx3"}, + {0x020, "scratch_load_ubyte_d16"}, + {0x021, "scratch_load_ubyte_d16_hi"}, + {0x022, "scratch_load_sbyte_d16"}, + {0x023, "scratch_load_sbyte_d16_hi"}, + {0x024, "scratch_load_short_d16"}, + {0x025, "scratch_load_short_d16_hi"}, +}; + +} // namespace + +const Table SOP2{SOP2_}; +const Table SOPK{SOPK_}; +const Table SOP1{SOP1_}; +const Table SOPC{SOPC_}; +const Table SOPP{SOPP_}; +const Table SMEM{SMEM_}; +const Table VOP2{VOP2_}; +const Table VOP1{VOP1_}; +const Table VOPC{VOPC_}; +const Table VOP3{VOP3_}; +const Table VOP3P{VOP3P_}; +const Table VINTRP{VINTRP_}; +const Table DS{DS_}; +const Table MUBUF{MUBUF_}; +const Table MTBUF{MTBUF_}; +const Table MIMG{MIMG_}; +const Table FLAT{FLAT_}; +const Table GLOBAL{GLOBAL_}; +const Table SCRATCH{SCRATCH_}; + +} // namespace x2w::vs::gfx10::opcodes diff --git a/src/x2w_shader/gfx10/opcodes.h b/src/x2w_shader/gfx10/opcodes.h new file mode 100644 index 0000000000..b33336fd20 --- /dev/null +++ b/src/x2w_shader/gfx10/opcodes.h @@ -0,0 +1,39 @@ +// GFX10 opcode names generated from Mesa's aco_opcodes.py (mesa-22.3.0, GFX10 column). See opcodes.cpp for the MIT notice. +// +// Each table is sorted by opcode. VOP3 holds only VOP3-only opcodes; VOP3 encodings of +// VOPC/VOP2/VOP1 ops (0x000-0x13f, 0x180-0x1ff) use those tables. +#pragma once + +#include <cstdint> +#include <span> +#include <string_view> + +namespace x2w::vs::gfx10::opcodes { + +struct Entry { + std::uint16_t op; + std::string_view name; +}; +using Table = std::span<const Entry>; + +extern const Table SOP2; +extern const Table SOPK; +extern const Table SOP1; +extern const Table SOPC; +extern const Table SOPP; +extern const Table SMEM; +extern const Table VOP2; +extern const Table VOP1; +extern const Table VOPC; +extern const Table VOP3; +extern const Table VOP3P; +extern const Table VINTRP; +extern const Table DS; +extern const Table MUBUF; +extern const Table MTBUF; +extern const Table MIMG; +extern const Table FLAT; +extern const Table GLOBAL; +extern const Table SCRATCH; + +} // namespace x2w::vs::gfx10::opcodes diff --git a/src/x2w_shader/gfx10/sp3.cpp b/src/x2w_shader/gfx10/sp3.cpp new file mode 100644 index 0000000000..66aac1afa8 --- /dev/null +++ b/src/x2w_shader/gfx10/sp3.cpp @@ -0,0 +1,567 @@ +// Instruction text in AMD's SP3 assembly syntax. +#include "x2w_shader/gfx10/sp3.h" + +#include <cstdio> +#include <utility> + +#include "x2w_shader/gfx10/mod.h" + +namespace x2w::vs::gfx10 { + +namespace { + +template <class... A> +std::string fmt(const char* f, A... a) { + char buf[128]; + std::snprintf(buf, sizeof buf, f, a...); + return buf; +} + +std::string join(const std::vector<std::string>& ops, const char* sep = ", ") { + std::string out; + for (std::size_t i = 0; i < ops.size(); ++i) { + if (i) out += sep; + out += ops[i]; + } + return out; +} + +std::string str(const Operand& o) { return o.to_string(); } + +bool is_null(const Operand& o) { return o.kind == Operand::Kind::Scalar && o.code == NULL_CODE; } + +// `s_atc_probe` immediate: 0..=64 in decimal, larger values in hex. +std::string atc_immediate(std::uint32_t imm) { + if (imm <= 64) return std::to_string(imm); + return fmt("0x%x", unsigned(imm)); +} + +// Cache flags; images write `dlc` first. +void flags(std::string& out, const Cache& cache, bool dlc_first) { + std::pair<bool, const char*> dlc = {cache.dlc, " dlc"}; + std::pair<bool, const char*> none = {false, ""}; + std::pair<bool, const char*> first = dlc_first ? dlc : none; + std::pair<bool, const char*> last = dlc_first ? none : dlc; + for (auto [on, text] : {first, std::pair<bool, const char*>{cache.glc, " glc"}, + std::pair<bool, const char*>{cache.slc, " slc"}, last}) { + if (on) out += text; + } + if (!out.empty() && out[0] == ' ') out.erase(0, 1); +} + +std::string label(const Instruction& inst, std::uint16_t imm) { + std::int64_t target = std::int64_t(inst.offset) + 4 * std::int64_t(inst.words.size()) + + 4 * std::int64_t(std::int16_t(imm)); + // Hex-format negative 64-bit values in two's complement. + return fmt("label_%04llX", static_cast<unsigned long long>(target)); +} + +std::string hwreg(std::uint16_t imm) { + unsigned id = imm & 0x3F, offset = (imm >> 6) & 0x1F, size = ((imm >> 11) & 0x1F) + 1; + std::string name; + switch (id) { + case 1: name = "HW_REG_MODE"; break; + case 20: name = "HW_REG_SHADER_FLAT_SCRATCH_LO"; break; + case 21: name = "HW_REG_SHADER_FLAT_SCRATCH_HI"; break; + case 25: name = "HW_REG_POPS_PACKER"; break; + default: name = std::to_string(id); break; + } + if (offset == 0 && size == 32) return "hwreg(" + name + ")"; + return "hwreg(" + name + ", " + std::to_string(offset) + ", " + std::to_string(size) + ")"; +} + +std::string waitcnt(std::uint16_t imm) { + unsigned vm = (imm & 0xF) | (unsigned(imm) >> 14) << 4; + unsigned exp = (imm >> 4) & 7; + unsigned lgkm = (imm >> 8) & 0x3F; + std::vector<std::string> parts; + if (vm != 0x3F) parts.push_back("vmcnt(" + std::to_string(vm) + ")"); + if (exp != 7) parts.push_back("expcnt(" + std::to_string(exp) + ")"); + if (lgkm != 0x3F) parts.push_back("lgkmcnt(" + std::to_string(lgkm) + ")"); + if (parts.size() == 0 || parts.size() == 3) return fmt("0x%04x", unsigned(imm)); + return join(parts, " & "); +} + +std::string sendmsg(std::uint16_t imm) { + unsigned msg = imm & 0xF, op = (imm >> 4) & 7, stream = (imm >> 8) & 3; + std::string msg_name; + switch (msg) { + case 2: msg_name = "MSG_GS"; break; + case 3: msg_name = "MSG_GS_DONE"; break; + case 7: msg_name = "MSG_ORDERED_PS_DONE"; break; + case 9: msg_name = "MSG_GS_ALLOC_REQ"; break; + default: msg_name = std::to_string(msg); break; + } + static const char* const OPS[] = {"GS_OP_NOP", "GS_OP_CUT", "GS_OP_EMIT", "GS_OP_EMIT_CUT"}; + std::string op_name = op < 4 ? OPS[op] : std::to_string(op); + if (msg == 3 && op == 0) return "sendmsg(" + msg_name + ", " + op_name + ")"; + return "sendmsg(" + msg_name + ", " + op_name + ", " + std::to_string(stream) + ")"; +} + +std::string buffer_format(std::uint8_t format) { + static const char* const NAMES[78] = { + "INVALID", + "8_UNORM", + "8_SNORM", + "8_USCALED", + "8_SSCALED", + "8_UINT", + "8_SINT", + "16_UNORM", + "16_SNORM", + "16_USCALED", + "16_SSCALED", + "16_UINT", + "16_SINT", + "16_FLOAT", + "8_8_UNORM", + "8_8_SNORM", + "8_8_USCALED", + "8_8_SSCALED", + "8_8_UINT", + "8_8_SINT", + "32_UINT", + "32_SINT", + "32_FLOAT", + "16_16_UNORM", + "16_16_SNORM", + "16_16_USCALED", + "16_16_SSCALED", + "16_16_UINT", + "16_16_SINT", + "16_16_FLOAT", + "10_11_11_UNORM", + "10_11_11_SNORM", + "10_11_11_USCALED", + "10_11_11_SSCALED", + "10_11_11_UINT", + "10_11_11_SINT", + "10_11_11_FLOAT", + "11_11_10_UNORM", + "11_11_10_SNORM", + "11_11_10_USCALED", + "11_11_10_SSCALED", + "11_11_10_UINT", + "11_11_10_SINT", + "11_11_10_FLOAT", + "10_10_10_2_UNORM", + "10_10_10_2_SNORM", + "10_10_10_2_USCALED", + "10_10_10_2_SSCALED", + "10_10_10_2_UINT", + "10_10_10_2_SINT", + "2_10_10_10_UNORM", + "2_10_10_10_SNORM", + "2_10_10_10_USCALED", + "2_10_10_10_SSCALED", + "2_10_10_10_UINT", + "2_10_10_10_SINT", + "8_8_8_8_UNORM", + "8_8_8_8_SNORM", + "8_8_8_8_USCALED", + "8_8_8_8_SSCALED", + "8_8_8_8_UINT", + "8_8_8_8_SINT", + "32_32_UINT", + "32_32_SINT", + "32_32_FLOAT", + "16_16_16_16_UNORM", + "16_16_16_16_SNORM", + "16_16_16_16_USCALED", + "16_16_16_16_SSCALED", + "16_16_16_16_UINT", + "16_16_16_16_SINT", + "16_16_16_16_FLOAT", + "32_32_32_UINT", + "32_32_32_SINT", + "32_32_32_FLOAT", + "32_32_32_32_UINT", + "32_32_32_32_SINT", + "32_32_32_32_FLOAT", + }; + if (format < 78) return std::string("BUF_FMT_") + NAMES[format]; + return std::to_string(format); +} + +std::string valu(std::string_view name, const Valu& v, Encoding encoding) { + auto bit = [](std::uint8_t mask, std::size_t i) { return ((mask >> i) & 1) != 0; }; + bool mix = name.starts_with("v_fma_mix"); + auto src = [&](std::size_t i) { + const Operand& o = v.src[i]; + std::string s = o.to_string(); + if (v.sdwa && bit(v.sdwa->sext, i)) s = "sext(" + s + ")"; + if (encoding == Encoding::Vop3p) { + if (mix) { + if (bit(v.opsel_hi, i)) s = std::string(bit(v.opsel, i) ? "sel_hi" : "sel_lo") + "(" + s + ")"; + if (bit(v.neg_hi, i)) s = "abs(" + s + ")"; + if (bit(v.neg, i)) s = "-" + s; + } else { + if (bit(v.neg, i) && bit(v.neg_hi, i)) s = "-" + s; + bool lo = bit(v.opsel, i), hi = bit(v.opsel_hi, i); + if (!lo && !hi) { + s = "sel_lo(" + s + ")"; + } else if (lo && hi) { + s = "sel_hi(" + s + ")"; + } else if (lo && !hi) { + s = "sel_hi_lo(" + s + ")"; + } + } + } else { + if (bit(v.abs, i)) s = "abs(" + s + ")"; + if (bit(v.neg, i)) s = "-" + s; + // v_permlane*: the opsel bits are fi and bound_ctrl. + if (bit(v.opsel, i) && !name.starts_with("v_permlane")) s = "sel_hi(" + s + ")"; + } + return s; + }; + std::vector<std::string> ops; + if (v.dst) ops.push_back(str(*v.dst)); + if (v.carry) ops.push_back(str(*v.carry)); + std::vector<std::size_t> order; + for (std::size_t i = 0; i < v.src.size(); ++i) order.push_back(i); + if (name.starts_with("v_interp_") && order.size() > 1) { + // dst, i/j, attribute, then the p1 result for p2. + std::swap(order[0], order[1]); + } + for (std::size_t i : order) ops.push_back(src(i)); + std::string out = join(ops); + auto suffix = [&](const std::string& s) { + out += ' '; + out += s; + }; + if (!v.src.empty() && v.src[0].kind == Operand::Kind::Attr && v.src[0].high) suffix("high"); + static const char* const OMOD[] = {"", "mul:2", "mul:4", "div:2"}; + std::string omod = OMOD[v.omod & 3]; + if (name.starts_with("v_permlane")) { + if (v.opsel & 1) suffix("fi:1"); + if (v.opsel & 2) suffix("bound_ctrl:1"); + } + if (encoding == Encoding::Vop3p && !mix) { + // `-src` above covers a source negated in both halves; LLVM syntax for the one-sided rest. + std::size_t n = v.src.size(); + std::pair<const char*, std::uint8_t> sides[] = { + {"neg_lo", std::uint8_t(v.neg & ~v.neg_hi)}, + {"neg_hi", std::uint8_t(v.neg_hi & ~v.neg)}, + }; + for (auto [field, only] : sides) { + bool any = false; + for (std::size_t i = 0; i < n; ++i) any = any || bit(only, i); + if (any) { + std::vector<std::string> bits; + for (std::size_t i = 0; i < n; ++i) bits.push_back(bit(only, i) ? "1" : "0"); + suffix(std::string(field) + ":[" + join(bits, ",") + "]"); + } + } + } + if (v.sdwa) { + const Sdwa& sdwa = *v.sdwa; + if (v.clamp) suffix("clamp"); + if (!omod.empty()) suffix(omod); + static const char* const SEL[] = {"BYTE_0", "BYTE_1", "BYTE_2", "BYTE_3", "WORD_0", "WORD_1", "DWORD", "?"}; + if (sdwa.dst_sel != 6) suffix(std::string("dst_sel:") + SEL[sdwa.dst_sel & 7]); + if (sdwa.dst_unused != 0) { + static const char* const UNUSED[] = {"UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE", "?"}; + suffix(std::string("dst_unused:") + UNUSED[sdwa.dst_unused & 3]); + } + for (std::size_t i = 0; i < sdwa.src_sel.size() && i < v.src.size(); ++i) { + std::uint8_t s = sdwa.src_sel[i]; + if (s != 6) suffix("src" + std::to_string(i) + "_sel:" + SEL[s & 7]); + } + } else { + if (!omod.empty()) suffix(omod); + if (v.clamp) suffix("clamp"); + } + if (v.dpp) { + if (const DppRow* r = std::get_if<DppRow>(&*v.dpp)) { + unsigned ctrl = r->ctrl; + std::string c; + if (ctrl <= 0x0FF) { + c = fmt("quad_perm:[%u,%u,%u,%u]", ctrl & 3, (ctrl >> 2) & 3, (ctrl >> 4) & 3, (ctrl >> 6) & 3); + } else if (ctrl >= 0x101 && ctrl <= 0x10F) { + c = fmt("row_shl:%u", ctrl & 0xF); + } else if (ctrl >= 0x111 && ctrl <= 0x11F) { + c = fmt("row_shr:%u", ctrl & 0xF); + } else if (ctrl >= 0x121 && ctrl <= 0x12F) { + c = fmt("row_ror:%u", ctrl & 0xF); + } else if (ctrl == 0x140) { + c = "row_mirror"; + } else if (ctrl == 0x141) { + c = "row_half_mirror"; + } else if (ctrl >= 0x150 && ctrl <= 0x15F) { + c = fmt("row_share:%u", ctrl & 0xF); + } else if (ctrl >= 0x160 && ctrl <= 0x16F) { + c = fmt("row_xmask:%u", ctrl & 0xF); + } else { + c = fmt("dpp_ctrl:0x%x", ctrl); + } + suffix(c); + if (r->row_mask != 0xF) suffix(fmt("row_mask:0x%x", unsigned(r->row_mask))); + if (r->bank_mask != 0xF) suffix(fmt("bank_mask:0x%x", unsigned(r->bank_mask))); + if (r->bound_ctrl) suffix("bound_ctrl:1"); + if (r->fi) suffix("fi:1"); + } else { + const DppLanes& l = std::get<DppLanes>(*v.dpp); + std::vector<std::string> lanes; + for (unsigned i = 0; i < 8; ++i) lanes.push_back(std::to_string((l.sel >> (3 * i)) & 7)); + suffix("dpp8:[" + join(lanes, ",") + "]"); + if (l.fi) suffix("fi:1"); + } + } + return out; +} + +std::string operands(const Instruction& inst, std::string_view name, const Fields& fields) { + std::string out; + if (const Sop* s = std::get_if<Sop>(&fields)) { + std::vector<std::string> list; + if (s->dst) list.push_back(str(*s->dst)); + for (const Operand& o : s->src) list.push_back(str(o)); + std::string regs = join(list); + if (name == "s_getreg_b32" && s->imm) { + out = regs + ", " + hwreg(*s->imm); + } else if ((name == "s_setreg_b32" || name == "s_setreg_imm32_b32") && s->imm) { + out = hwreg(*s->imm) + ", " + regs; + } else if (name == "s_call_b64" && s->imm) { + out = regs + ", " + label(inst, *s->imm); + } else if (s->imm && regs.empty()) { + out = fmt("0x%04x", unsigned(*s->imm)); + } else if (s->imm) { + out = regs + ", " + fmt("0x%04x", unsigned(*s->imm)); + } else { + out = regs; + } + } else if (const Sopp* p = std::get_if<Sopp>(&fields)) { + if (name == "s_endpgm" || name == "s_barrier" || name == "s_code_end" || name == "s_endpgm_saved" || + name == "s_endpgm_ordered_ps_done" || name == "s_wakeup" || name == "s_icache_inv" || + name == "s_ttracedata") { + out = ""; + } else if (name == "s_branch" || name.starts_with("s_cbranch_")) { + out = label(inst, p->imm); + } else if (name == "s_waitcnt") { + out = waitcnt(p->imm); + } else if (name == "s_sendmsg" || name == "s_sendmsghalt") { + out = sendmsg(p->imm); + } else { + out = fmt("0x%04x", unsigned(p->imm)); + } + } else if (const Smem* m = std::get_if<Smem>(&fields)) { + if (m->data) { + std::string data; + if ((name == "s_atc_probe" || name == "s_atc_probe_buffer") && m->data->kind == Operand::Kind::Literal) { + data = atc_immediate(m->data->literal); + } else { + data = str(*m->data); + } + std::string off; + bool null = is_null(m->soffset); + if (m->offset == 0) { + off = str(m->soffset); + } else if (null) { + off = fmt("0x%06x", unsigned(m->offset & 0x1FFFFF)); + } else { + off = str(m->soffset) + fmt(" offset:0x%06x", unsigned(m->offset & 0x1FFFFF)); + } + if (name == "s_memtime" || name == "s_memrealtime" || name == "s_get_waveid_in_workgroup") { + // The data is a counter or the wave ID; these have no address. + out = data; + } else { + out = data + ", " + str(m->base) + ", " + off; + } + } + flags(out, m->cache, false); + } else if (const Valu* v = std::get_if<Valu>(&fields)) { + out = valu(name, *v, inst.encoding); + } else if (const Vintrp* i = std::get_if<Vintrp>(&fields)) { + std::string src; + if (name == "v_interp_mov_f32" && i->src.kind == Operand::Kind::Const) { + static const char* const P[] = {"p10", "p20", "p0"}; + src = i->src.code < 3 ? P[i->src.code] : "p?"; + } else { + src = str(i->src); + } + out = str(i->dst) + ", " + src + ", " + str(i->attr); + } else if (const Ds* d = std::get_if<Ds>(&fields)) { + std::vector<std::string> list; + if (d->dst) list.push_back(str(*d->dst)); + if (d->addr) list.push_back(str(*d->addr)); + for (const Operand& o : d->data) list.push_back(str(o)); + out = join(list); + if (ds_pair(name)) { + if (d->offset0 != 0) out += " offset0:" + std::to_string(d->offset0); + if (d->offset1 != 0) out += " offset1:" + std::to_string(d->offset1); + } else { + unsigned offset = unsigned(d->offset1) << 8 | d->offset0; + if (offset != 0) out += " offset:" + std::to_string(offset); + } + if (d->gds) out += " gds"; + } else if (const Buffer* b = std::get_if<Buffer>(&fields)) { + if (b->data) { + // An LDS load returns its data to LDS, so vdata is unused. + if (b->lds && name.find("_load_") != std::string_view::npos) { + out = str(b->addr) + ", " + str(b->rsrc) + ", " + str(b->soffset); + } else { + out = str(*b->data) + ", " + str(b->addr) + ", " + str(b->rsrc) + ", " + str(b->soffset); + } + if (b->idxen) out += " idxen"; + if (b->offen) out += " offen"; + if (b->offset != 0) out += " offset:" + std::to_string(b->offset); + if (b->format) out += " format:[" + buffer_format(*b->format) + "]"; + } + flags(out, b->cache, false); + if (b->lds) out += " lds"; + if (b->tfe) out += " tfe"; + } else if (const Image* im = std::get_if<Image>(&fields)) { + std::string addr; + if (im->addr.size() == 1) { + addr = str(im->addr[0]); + } else { + std::vector<std::string> list; + for (const Operand& o : im->addr) list.push_back(str(o)); + addr = "[" + join(list, ",") + "]"; + } + std::vector<std::string> list = {str(im->data), addr, str(im->rsrc)}; + if (im->sampler) list.push_back(str(*im->sampler)); + out = join(list); + if (im->dmask != 1) out += fmt(" dmask:0x%x", unsigned(im->dmask)); + static const char* const DIMS[] = {"1D", "2D", "3D", "CUBE", "1D_ARRAY", "2D_ARRAY", "2D_MSAA", "2D_MSAA_ARRAY"}; + out += std::string(" dim:SQ_RSRC_IMG_") + DIMS[im->dim & 7]; + if (im->r128) out += " r128"; + if (im->unorm) out += " unorm"; + flags(out, im->cache, true); + if (im->a16) out += " a16"; + if (im->d16) out += " d16"; + if (im->tfe) out += " tfe"; + if (im->lwe) out += " lwe"; + } else if (const Flat* f = std::get_if<Flat>(&fields)) { + std::vector<std::string> list; + if (f->dst) list.push_back(str(*f->dst)); + list.push_back(f->addr ? str(*f->addr) : "off"); + if (f->data) list.push_back(str(*f->data)); + if (f->saddr) list.push_back(is_null(*f->saddr) ? "off" : str(*f->saddr)); + out = join(list); + if (f->offset != 0) out += " inst_offset:" + std::to_string(f->offset); + flags(out, f->cache, false); + if (f->lds) out += " lds"; + } else if (const Exp* e = std::get_if<Exp>(&fields)) { + unsigned t = e->target; + std::string target; + if (t <= 7) { + target = "mrt" + std::to_string(t); + } else if (t == 8) { + target = "mrtz"; + } else if (t == 9) { + target = "null"; + } else if (t >= 12 && t <= 15) { + target = "pos" + std::to_string(t - 12); + } else if (t == 20) { + target = "prim"; + } else if (t >= 32 && t <= 63) { + target = "param" + std::to_string(t - 32); + } else { + target = "<target " + std::to_string(t) + ">"; + } + std::vector<std::string> list = {target}; + for (const auto& s : e->src) list.push_back(s ? str(*s) : "off"); + out = join(list); + if (e->done) out += " done"; + if (e->compr) out += " compr"; + if (e->vm) out += " vm"; + } + return out; +} + +} // namespace + +namespace sp3 { + +std::string scalar_name(std::uint8_t code) { + if (code <= 105) return "s" + std::to_string(code); + if (code == 106) return "vcc_lo"; + if (code == 107) return "vcc_hi"; + if (code <= 123) return "ttmp" + std::to_string(code - 108); + if (code == 124) return "m0"; + if (code == 125) return "null"; + if (code == 126) return "exec_lo"; + return "exec_hi"; +} + +std::string const_name(std::uint8_t code) { + if (code >= 128 && code <= 192) return std::to_string(int(code) - 128); + if (code >= 193 && code <= 208) return std::to_string(192 - int(code)); + switch (code) { + case 240: return "0.5"; + case 241: return "-0.5"; + case 242: return "1.0"; + case 243: return "-1.0"; + case 244: return "2.0"; + case 245: return "-2.0"; + case 246: return "4.0"; + case 247: return "-4.0"; + case 248: return "0.15915494"; + case 235: return "src_shared_base"; + case 236: return "src_shared_limit"; + case 237: return "src_private_base"; + case 238: return "src_private_limit"; + case 239: return "src_pops_exiting_wave_id"; + case 251: return "src_vccz"; + case 252: return "src_execz"; + case 253: return "src_scc"; + case 254: return "src_lds_direct"; + default: return "<src " + std::to_string(code) + ">"; + } +} + +} // namespace sp3 + +std::string Operand::to_string() const { + switch (kind) { + case Kind::Scalar: + if (dwords == 1) return sp3::scalar_name(code); + if (code == 106 && dwords == 2) return "vcc"; + if (code == 126 && dwords == 2) return "exec"; + // Eight-bit arithmetic wraps. + if (code < 106) return "s[" + std::to_string(code) + ":" + std::to_string(std::uint8_t(code + dwords - 1)) + "]"; + if (code >= 108 && code < 124) { + return "ttmp[" + std::to_string(code - 108) + ":" + std::to_string(std::uint8_t(code - 108 + dwords - 1)) + "]"; + } + return sp3::scalar_name(code); + case Kind::Vector: + if (dwords == 1) return "v" + std::to_string(reg); + return "v[" + std::to_string(reg) + ":" + std::to_string(std::uint32_t(reg) + std::uint32_t(dwords) - 1u) + "]"; + case Kind::Const: + return sp3::const_name(code); + case Kind::Literal: + return fmt("lit(0x%08x)", unsigned(literal)); + case Kind::Attr: { + static const char XYZW[] = {'x', 'y', 'z', 'w'}; + return "attr" + std::to_string(index) + "." + XYZW[chan & 3]; + } + } + return {}; +} + +std::string Operand::debug() const { + switch (kind) { + case Kind::Scalar: + return "Scalar { code: " + std::to_string(code) + ", dwords: " + std::to_string(dwords) + " }"; + case Kind::Vector: + return "Vector { reg: " + std::to_string(reg) + ", dwords: " + std::to_string(dwords) + " }"; + case Kind::Const: + return "Const(" + std::to_string(code) + ")"; + case Kind::Literal: + return "Literal(" + std::to_string(literal) + ")"; + case Kind::Attr: + return "Attr { index: " + std::to_string(index) + ", chan: " + std::to_string(chan) + + ", high: " + (high ? "true" : "false") + " }"; + } + return {}; +} + +std::string Instruction::text(bool wave64) const { + std::string_view name = this->name().value_or("?"); + std::string ops = operands(*this, name, fields(wave64)); + if (ops.empty()) return std::string(name); + return std::string(name) + " " + ops; +} + +} // namespace x2w::vs::gfx10 diff --git a/src/x2w_shader/gfx10/sp3.h b/src/x2w_shader/gfx10/sp3.h new file mode 100644 index 0000000000..cd3c2c3812 --- /dev/null +++ b/src/x2w_shader/gfx10/sp3.h @@ -0,0 +1,13 @@ +// Instruction text in AMD's SP3 assembly syntax. The entry points are Instruction::text (mod.h) and +// Operand::to_string (fields.h); these are its helpers. +#pragma once + +#include <cstdint> +#include <string> + +namespace x2w::vs::gfx10::sp3 { + +std::string scalar_name(std::uint8_t code); +std::string const_name(std::uint8_t code); + +} // namespace x2w::vs::gfx10::sp3 diff --git a/src/x2w_shader/io.cpp b/src/x2w_shader/io.cpp new file mode 100644 index 0000000000..0a6488c229 --- /dev/null +++ b/src/x2w_shader/io.cpp @@ -0,0 +1,431 @@ +// Instruction inputs, interpolation and export targets. See io.h. +#include "x2w_shader/io.h" + +#include <algorithm> +#include <functional> +#include <span> +#include <string_view> +#include <unordered_map> +#include <unordered_set> +#include <variant> + +#include "x2w_shader/front_hash.h" + +namespace x2w::vs::io { + +namespace { + +using gfx10::Operand; +using ir::Exit; +using ir::Inst; +using ir::Program; +using ir::Reg; +using ir::Value; +using native::HwStage; +using native::PsInput; +using native::VsOutput; + +ShaderError unsupported(std::size_t offset, const char* what) { return ShaderError::unsupported(offset, what); } + +struct PsVgpr { + std::uint8_t count; + std::optional<Barycentric> kind; +}; + +// The pixel input VGPRs in hardware order: one entry per `SPI_PS_INPUT_ADDR` bit. +const PsVgpr PS_VGPRS[16] = { + {2, Barycentric::PerspectiveSample}, + {2, Barycentric::PerspectiveCenter}, + {2, Barycentric::PerspectiveCentroid}, + {3, Barycentric::PerspectivePullModel}, + {2, Barycentric::LinearSample}, + {2, Barycentric::LinearCenter}, + {2, Barycentric::LinearCentroid}, + {1, std::nullopt}, // line stipple + {1, std::nullopt}, // position x + {1, std::nullopt}, // y + {1, std::nullopt}, // z + {1, std::nullopt}, // w + {1, std::nullopt}, // front face + {1, std::nullopt}, // ancillary + {1, std::nullopt}, // sample coverage + {1, std::nullopt}, // fixed-point position +}; + +Input ps_system(std::size_t bit) +{ + if (bit == 7) return Input::Simple(Input::Kind::LineStipple); + if (bit >= 8 && bit <= 11) return Input::Position(static_cast<std::uint8_t>(bit - 8)); + if (bit == 12) return Input::Simple(Input::Kind::FrontFace); + if (bit == 13) return Input::Simple(Input::Kind::Ancillary); + if (bit == 14) return Input::Simple(Input::Kind::SampleCoverage); + return Input::Simple(Input::Kind::FixedPosition); +} + +using ValueSiteMap = std::unordered_map<Value, Site, fhash::ValueHash>; +using BaryOf = std::function<std::optional<std::pair<Barycentric, std::uint8_t>>(std::optional<Value>)>; + +// An interpolation before its attribute is known: `barycentric` none when i or j is computed. +struct Pair { + std::optional<Barycentric> barycentric; + std::vector<Site> first; + + Interp with(Attribute attribute) && + { + if (barycentric) return Interp::Interpolated(attribute, *barycentric, std::move(first)); + return Interp::Weighted(attribute); + } +}; + +bool has_site(const Io& io, Site s) +{ + return std::any_of(io.interps.begin(), io.interps.end(), [&](const auto& e) { return e.first == s; }); +} + +// Records interpolation `pair` at `site`, and its first halves too when they evaluate on their own +// (computed barycentrics). +void push_pair(Io& io, Site site, Pair pair, Attribute attribute) +{ + if (!pair.barycentric) { + for (const Site f : pair.first) + if (!has_site(io, f)) io.interps.push_back({f, Interp::Weighted(attribute)}); + } + io.interps.push_back({site, std::move(pair).with(attribute)}); +} + +struct HalvesError { + const char* what; +}; + +// Finds the first halves of interpolations. +struct Halves { + const Program* p; + const ValueSiteMap* defs; + const ValueSiteMap* phis; + + // The interpolation whose second half reads the first half's result `acc`, the barycentric `j`, + // and attribute `attr`: every first half must read the same attribute channel. With j and every + // first half's i loaded as one kind's, the pair interpolates with that kind; otherwise each half + // evaluates on its own (Interp::Weighted). Throws HalvesError. + Pair pair(const Operand& attr, std::optional<Value> acc, std::optional<Value> j, const BaryOf& barycentric) const + { + std::vector<Site> first; + if (!acc) throw HalvesError{"an interpolation without its first half"}; + std::vector<Value> seen; + sites(*acc, seen, first); + std::optional<Barycentric> kind; + if (const auto bj = barycentric(j); bj && bj->second == 1) kind = bj->first; + for (const auto& [b, i0] : first) { + const Inst& inst = p->blocks[b].insts[i0]; + Operand a; + std::optional<Value> i; + const auto* vi = std::get_if<gfx10::Vintrp>(&inst.fields); + const auto* va = std::get_if<gfx10::Valu>(&inst.fields); + if (vi && vi->src.is_vector() && inst.name() == "v_interp_p1_f32") { + a = vi->attr; + i = inst.read(Reg::V(vi->src.reg)); + } else if (va && inst.name() == "v_interp_p1ll_f16") { + if (va->src.size() > 1 && va->src[1].is_vector()) { + a = va->src[0]; + i = inst.read(Reg::V(va->src[1].reg)); + } else { + throw HalvesError{"an interpolation without its first half"}; + } + } else { + throw HalvesError{"an interpolation without its first half"}; + } + if (!(a == attr)) throw HalvesError{"interpolation halves of different attributes"}; + if (kind) { + const auto bi = barycentric(i); + if (!(bi && bi->first == *kind && bi->second == 0)) kind = std::nullopt; + } + } + return Pair{kind, std::move(first)}; + } + + // The instructions `v` comes from, through phis (`seen`: phis on the way; a loop back to one adds + // nothing). + void sites(Value v, std::vector<Value>& seen, std::vector<Site>& out) const + { + if (const auto it = defs->find(v); it != defs->end()) { + if (std::find(out.begin(), out.end(), it->second) == out.end()) out.push_back(it->second); + return; + } + const auto it = phis->find(v); + if (it == phis->end()) throw HalvesError{"an interpolation without its first half"}; + const auto [b, i] = it->second; + if (std::find(seen.begin(), seen.end(), v) == seen.end()) { + seen.push_back(v); + for (const Value a : p->blocks[b].phis[i].args) sites(a, seen, out); + } + } +}; + +} // namespace + +namespace detail { + +std::vector<std::pair<std::uint8_t, Input>> ps_vgprs(std::uint32_t addr) +{ + std::vector<std::pair<std::uint8_t, Input>> out; + std::uint8_t next = 0; + for (std::size_t bit = 0; bit < 16; ++bit) { + const auto& [count, kind] = PS_VGPRS[bit]; + if (((addr >> bit) & 1) == 0) continue; + for (std::uint8_t index = 0; index < count; ++index) { + const Input input = kind ? Input::Bary(*kind, index) : ps_system(bit); + out.push_back({static_cast<std::uint8_t>(next + index), input}); + } + next = static_cast<std::uint8_t>(next + count); + } + return out; +} + +} // namespace detail + +Io raise(const Program& p, const native::NativeProgram& native) +{ + std::vector<std::pair<Reg, Input>> loaded; + std::span<const PsInput> ps_inputs; + std::span<const VsOutput> params; + const auto* ps = std::get_if<native::PsIo>(&native.io); + const auto* vs = std::get_if<native::VsIo>(&native.io); + const auto* cs = std::get_if<native::ComputeIo>(&native.io); + const auto* ms = std::get_if<native::MeshIo>(&native.io); + if (ps && native.stage == HwStage::Ps) { + // A pixel shader exports no parameters; `[]` never reaches `Unread`. + for (const auto& [r, i] : detail::ps_vgprs(ps->input_addr)) loaded.push_back({Reg::V(r), i}); + ps_inputs = ps->inputs; + } else if (vs && native.stage == HwStage::Vs) { + loaded = { + {Reg::V(0), Input::Simple(Input::Kind::VertexId)}, + {Reg::V(2), Input::Simple(Input::Kind::PrimitiveId)}, + {Reg::V(3), Input::Simple(Input::Kind::InstanceId)}, + }; + for (const auto& i : vs->inputs) { + for (std::uint8_t channel = 0; channel < 4; ++channel) { + if (((i.mask >> channel) & 1) == 0) continue; + loaded.push_back({Reg::V(static_cast<std::uint8_t>(i.vgpr + channel)), Input::Attribute(i.row, channel)}); + } + } + params = vs->outputs; + } else if (cs && native.stage == HwStage::Cs) { + // Compute: thread ids in v0-v2, group ids and the group info in the SGPRs after the user data. + const auto [ids, info] = cs->system_sgprs(); + for (std::uint8_t c = 0; c < cs->thread_id_vgprs(); ++c) loaded.push_back({Reg::V(c), Input::ThreadIdInGroup(c)}); + for (std::size_t c = 0; c < ids.size(); ++c) + if (ids[c]) loaded.push_back({Reg::S(*ids[c]), Input::GroupId(static_cast<std::uint8_t>(c))}); + if (info) loaded.push_back({Reg::S(*info), Input::Simple(Input::Kind::GroupInfo)}); + } else if (ms && native.stage == HwStage::Ms) { + // The group input, and the phis that may carry it past a join. + std::vector<Value> group; + for (const auto& i : p.inputs) + if (i.first == Reg::V(5)) group.push_back(i.second); + auto in_group = [&](Value v) { return std::find(group.begin(), group.end(), v) != group.end(); }; + // No lane is active over the EXEC-zero edge of s_cbranch_execz or _execnz, the same case as a + // partial-EXEC write below. + auto no_lanes = [&](std::size_t q, std::size_t b) { + const auto& blk = p.blocks[q]; + if (blk.insts.empty() || !blk.exit.is_branch()) return false; + const std::string_view last = blk.insts.back().name(); + const std::size_t taken = blk.exit.taken, not_taken = blk.exit.not_taken; + if (last == "s_cbranch_execz") return taken == b && not_taken != b; + if (last == "s_cbranch_execnz") return not_taken == b && taken != b; + return false; + }; + for (;;) { + std::optional<Value> found; + for (std::size_t b = 0; b < p.blocks.size() && !found; ++b) { + for (const auto& f : p.blocks[b].phis) { + const auto& preds = p.blocks[b].preds; + bool carried = false; + const std::size_t n = std::min(f.args.size(), preds.size()); + for (std::size_t k = 0; k < n && !carried; ++k) + carried = in_group(f.args[k]) && !no_lanes(preds[k], b); + if (carried && !in_group(f.value)) { + found = f.value; + break; + } + } + } + if (!found) break; + group.push_back(*found); + } + // The group input holds the same value in every lane only as the first lane reads it. A + // write to v5 reads its old value too, which only lanes outside EXEC keep. + // shortcut: writes that may keep the old v5 in active lanes (v_fmac_f32's accumulator, a + // 16-bit half or d16 load, v_writelane_b32, v_movreld_b32, DPP that skips lanes) and + // partial-EXEC writes pass; check those too if a mesh program writes v5 that way. + for (const auto& b : p.blocks) { + for (const auto& i : b.insts) { + const auto r = i.read(Reg::V(5)); + if (!r || !in_group(*r) || i.name() == "v_readfirstlane_b32") continue; + bool per_lane = !i.write(Reg::V(5)).has_value(); + if (!per_lane) { + const auto ops = ir::operand_reads(p, i); + per_lane = std::find(ops.begin(), ops.end(), Reg::V(5)) != ops.end(); + } + if (per_lane) throw unsupported(i.machine.offset, "the mesh group input read per lane"); + } + } + loaded = { + {Reg::V(5), Input::Simple(Input::Kind::MeshGroup)}, + {Reg::S(3), Input::Simple(Input::Kind::MergedWaveInfo)}, + }; + params = ms->outputs; + } else { + throw unsupported(0, "I/O of this stage"); + } + std::vector<std::pair<Value, Input>> inputs; + for (const auto& [reg, v] : p.inputs) { + const auto it = std::find_if(loaded.begin(), loaded.end(), [&](const auto& l) { return l.first == reg; }); + if (it != loaded.end()) inputs.push_back({v, it->second}); + } + auto input_of = [&](Value v) -> std::optional<Input> { + for (const auto& i : inputs) + if (i.first == v) return i.second; + return std::nullopt; + }; + auto attribute = [&](const Inst& inst, const Operand& attr) -> Attribute { + if (!attr.is_attr()) throw unsupported(inst.machine.offset, "an interpolation operand"); + for (const PsInput& i : ps_inputs) + if (i.attr == attr.index) return Attribute{i.usage, i.row, attr.chan, attr.high}; + throw unsupported(inst.machine.offset, "an interpolated attribute the stage data does not list"); + }; + // A VGPR value's barycentric kind and index, if it is one as loaded. + const BaryOf barycentric = [&](std::optional<Value> v) -> std::optional<std::pair<Barycentric, std::uint8_t>> { + if (!v) return std::nullopt; + const auto i = input_of(*v); + if (!i || i->kind != Input::Kind::Barycentric) return std::nullopt; + return std::pair{i->barycentric, i->index}; + }; + + Io io; + io.inputs = inputs; + if (cs) io.initialized_sgprs = cs->initialized_sgprs(); + ValueSiteMap defs; + ValueSiteMap phis; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& block = p.blocks[b]; + for (std::size_t i = 0; i < block.insts.size(); ++i) + for (const auto& w : block.insts[i].writes) defs.insert_or_assign(w.second, Site{b, i}); + for (std::size_t i = 0; i < block.phis.size(); ++i) phis.insert_or_assign(block.phis[i].value, Site{b, i}); + } + const Halves halves{&p, &defs, &phis}; + auto pair_or_throw = [&](std::size_t at, const Operand& attr, std::optional<Value> acc, std::optional<Value> j) { + try { + return halves.pair(attr, acc, j, barycentric); + } catch (const HalvesError& e) { + throw unsupported(at, e.what); + } + }; + std::vector<std::pair<Site, Attribute>> first_halves; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& block = p.blocks[b]; + for (std::size_t i = 0; i < block.insts.size(); ++i) { + const Inst& inst = block.insts[i]; + const Site site{b, i}; + const std::size_t at = inst.machine.offset; + const std::string_view name = inst.name(); + if (const auto* vi = std::get_if<gfx10::Vintrp>(&inst.fields)) { + const Attribute attr = attribute(inst, vi->attr); + if (name == "v_interp_mov_f32" && vi->src.is_const()) { + io.interps.push_back({site, Interp::Vertex(attr, vi->src.code)}); + } else if (name == "v_interp_p1_f32") { + first_halves.push_back({site, attr}); + } else if (name == "v_interp_p2_f32" && vi->src.is_vector()) { + if (!vi->dst.is_vector()) throw unsupported(at, "an interpolation operand"); + const std::uint8_t d = vi->dst.reg; + // The first half's result is this one's old dst. + Pair interp = pair_or_throw(at, vi->attr, inst.read(Reg::V(d)), inst.read(Reg::V(vi->src.reg))); + push_pair(io, site, std::move(interp), attr); + } else { + throw unsupported(at, "an interpolation form"); + } + } else if (const auto* v = std::get_if<gfx10::Valu>(&inst.fields); v && name.starts_with("v_interp_")) { + if (name == "v_interp_p1ll_f16") { + first_halves.push_back({site, attribute(inst, v->src.at(0))}); + } else if (name == "v_interp_p2_f16") { + const Attribute attr = attribute(inst, v->src.at(0)); + auto read = [&](std::size_t k) -> std::optional<Value> { + if (k < v->src.size() && v->src[k].is_vector()) return inst.read(Reg::V(v->src[k].reg)); + return std::nullopt; + }; + const auto acc = read(2); + const auto j = read(1); + Pair interp = pair_or_throw(at, v->src[0], acc, j); + push_pair(io, site, std::move(interp), attr); + } else { + throw unsupported(at, "an interpolation form"); + } + } else if (const auto* e = std::get_if<gfx10::Exp>(&inst.fields)) { + const std::uint8_t t = e->target; + Target target; + if (t <= 7) { + target = Target::Color(t); + } else if (t == 8) { + target = Target::Simple(Target::Kind::Depth); + } else if (t == 9) { + target = Target::Simple(Target::Kind::Null); + } else if (t >= 12 && t <= 16) { + target = Target::Position(static_cast<std::uint8_t>(t - 12)); + } else if (t == 20) { + target = Target::Simple(Target::Kind::Primitive); + } else if (t == 32 && params.empty()) { + target = Target::Simple(Target::Kind::Unread); + } else if (t >= 32 && t <= 63) { + // Bit 7: a mesh program's per-primitive output. + const auto o = std::find_if(params.begin(), params.end(), + [&](const VsOutput& x) { return (x.param & 0x7F) == t - 32; }); + if (o == params.end()) throw unsupported(at, "a parameter export the stage data does not list"); + if ((o->param & 0x80) != 0) + target = Target::PrimitiveParam(o->usage, o->row); + else + target = Target::Param(o->usage, o->row); + } else { + throw unsupported(at, "an export target"); + } + Export x; + x.site = site; + x.target = target; + for (std::size_t c = 0; c < 4; ++c) { + const auto& s = e->src[c]; + if (s && s->is_vector()) x.values[c] = inst.read(Reg::V(s->reg)); + } + x.compressed = e->compr; + x.done = e->done; + io.exports.push_back(x); + } + } + } + if (first_halves.empty()) return io; + // A loaded i/j pair normally becomes one host interpolation: its first half need not be + // evaluated. A first half also read as data (or used without a second half) must keep + // P0 + i * P10. Follow phi uses too, without forcing ordinary pairs to read per-vertex + // attributes. + std::unordered_set<Site, fhash::SiteHash> folded; + for (const auto& [s, i] : io.interps) + if (i.kind == Interp::Kind::Interpolated) folded.insert(s); + std::unordered_set<Value, fhash::ValueHash> used; + for (std::size_t b = 0; b < p.blocks.size(); ++b) + for (std::size_t i = 0; i < p.blocks[b].insts.size(); ++i) { + if (folded.count(Site{b, i})) continue; + for (const auto& r : p.blocks[b].insts[i].reads) used.insert(r.second); + } + for (;;) { + const std::size_t before = used.size(); + for (const auto& b : p.blocks) + for (const auto& phi : b.phis) + if (used.count(phi.value)) used.insert(phi.args.begin(), phi.args.end()); + if (used.size() == before) break; + } + for (const auto& [site, attr] : first_halves) { + const auto& writes = p.blocks[site.first].insts[site.second].writes; + if (!has_site(io, site) && + std::any_of(writes.begin(), writes.end(), [&](const auto& w) { return used.count(w.second) != 0; })) + io.interps.push_back({site, Interp::Weighted(attr)}); + } + return io; +} + +} // namespace x2w::vs::io diff --git a/src/x2w_shader/io.h b/src/x2w_shader/io.h new file mode 100644 index 0000000000..57cb5561a2 --- /dev/null +++ b/src/x2w_shader/io.h @@ -0,0 +1,215 @@ +// I/O raising: what a program's input registers, its interpolation and its exports mean. +// +// Pixel shaders get the VGPRs `SPI_PS_INPUT_ADDR` enables, in a fixed order (barycentrics, then +// position, front face...). `v_interp_p1` and `v_interp_p2` (and their f16 forms) evaluate an +// attribute from a pair of barycentrics; `v_interp_mov` reads one vertex's value. After the 32-bit +// export patch (NativeProgram::patched_code) exports carry plain 32-bit values: `mrt<n>` is render +// target n, `mrtz` depth, stencil and sample mask, `null` nothing. A lane whose EXEC bit is clear at +// the export that ends the program (`done`) is discarded: that export's guard after +// structurisation. +// +// Vertex shaders that run as the hardware VS get the vertex id in v0, the primitive id in v2 and the +// instance id in v3; the fetch shader loads channel k of each attribute into its VGPR + k. +// `exp pos0` is the position, `exp param<n>` the output with parameter n. +// +// Attributes and outputs are named by their row: a register of the container's signature part. +// +// Compute programs get the thread id in the group in v0-v2 and the group id in the SGPRs after the +// user data, as `COMPUTE_PGM_RSRC2` enables them. +// +// Mesh programs run as one NGG stage. The program computes its thread index from the wave index +// (s3 bits 24-27) and the lane (`v_mbcnt`), and its group id from v5 of the first lane +// (`v_readfirstlane`: the group times the group size). Lane n exports vertex n (`exp pos`, +// `exp param`) and primitive n (`exp prim`: 9-bit vertex indices at bits 0, 10, 20, each with an +// edge flag above it, bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One lane +// sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices | primitives << 12). +#pragma once + +#include <array> +#include <cstddef> +#include <cstdint> +#include <optional> +#include <utility> +#include <vector> + +#include "x2w_shader/ir.h" +#include "x2w_shader/native.h" + +namespace x2w::vs { +namespace resource { +// (block, instruction). Also declared in resource.h. +using Site = std::pair<std::size_t, std::size_t>; +} // namespace resource + +namespace io { + +using resource::Site; + +enum class Barycentric : std::uint8_t { + PerspectiveSample, + PerspectiveCenter, + PerspectiveCentroid, + PerspectivePullModel, + LinearSample, + LinearCenter, + LinearCentroid, +}; + +struct Input { + enum class Kind : std::uint8_t { + VertexId, + PrimitiveId, + InstanceId, + // A vertex attribute the fetch shader loads (row, channel). + Attribute, + // `index` 0 is i, 1 is j (2 the pull model's w). + Barycentric, + // Pixel position channel (n: 0-3, x, y, z, w). + Position, + FrontFace, + // Sample id and other bits. + Ancillary, + SampleCoverage, + FixedPosition, + LineStipple, + // Compute: thread-group id component n (an SGPR). + GroupId, + // Compute: thread id within the group, component n (a VGPR). + ThreadIdInGroup, + // Compute: the thread-group info SGPR (wave index and count). + GroupInfo, + // Mesh: v5, the group id times the group size (read as uniform). + MeshGroup, + // Mesh: s3, the wave's index in the group in bits 24-27. + MergedWaveInfo, + }; + Kind kind = Kind::VertexId; + std::uint8_t row = 0; // Attribute + std::uint8_t channel = 0; // Attribute + Barycentric barycentric = Barycentric::PerspectiveSample; // Barycentric kind + std::uint8_t index = 0; // Barycentric + std::uint8_t n = 0; // Position, GroupId, ThreadIdInGroup + + static constexpr Input Simple(Kind k) { return {k, 0, 0, Barycentric::PerspectiveSample, 0, 0}; } + static constexpr Input Attribute(std::uint8_t row, std::uint8_t channel) + { + return {Kind::Attribute, row, channel, Barycentric::PerspectiveSample, 0, 0}; + } + static constexpr Input Bary(Barycentric kind, std::uint8_t index) { return {Kind::Barycentric, 0, 0, kind, index, 0}; } + static constexpr Input Position(std::uint8_t c) { return {Kind::Position, 0, 0, Barycentric::PerspectiveSample, 0, c}; } + static constexpr Input GroupId(std::uint8_t c) { return {Kind::GroupId, 0, 0, Barycentric::PerspectiveSample, 0, c}; } + static constexpr Input ThreadIdInGroup(std::uint8_t c) + { + return {Kind::ThreadIdInGroup, 0, 0, Barycentric::PerspectiveSample, 0, c}; + } + constexpr bool operator==(const Input&) const = default; +}; + +// An attribute channel of the input signature. +struct Attribute { + native::Usage usage; + std::uint8_t row = 0; + std::uint8_t channel = 0; + // The upper f16 half of the channel (packed fp16 inputs). + bool high = false; + bool operator==(const Attribute&) const = default; +}; + +struct Interp { + enum class Kind : std::uint8_t { + // This site's result (`v_interp_p2*`) is the attribute interpolated with `barycentric`; + // `first` are the `v_interp_p1*` halves it completes (one per path where the compiler shares a + // first half). + Interpolated, + // One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10, 1 for P20, 2 for P0 (the + // provoking vertex). + Vertex, + // A half of an interpolation whose i or j is computed rather than loaded: each half + // evaluates as the hardware does, from the attribute's vertex values (`v_interp_p1*`: + // P0 + i P10, with P10 = P1 - P0; `v_interp_p2*`: its old dst + j P20, with P20 = P2 - P0). + Weighted, + }; + Kind kind = Kind::Weighted; + Attribute attribute; + Barycentric barycentric = Barycentric::PerspectiveSample; // Interpolated + std::vector<Site> first; // Interpolated + std::uint8_t vertex = 0; // Vertex + + static Interp Interpolated(Attribute a, Barycentric b, std::vector<Site> first) + { + return {Kind::Interpolated, a, b, std::move(first), 0}; + } + static Interp Vertex(Attribute a, std::uint8_t vertex) + { + return {Kind::Vertex, a, Barycentric::PerspectiveSample, {}, vertex}; + } + static Interp Weighted(Attribute a) { return {Kind::Weighted, a, Barycentric::PerspectiveSample, {}, 0}; } + bool operator==(const Interp&) const = default; +}; + +struct Target { + enum class Kind : std::uint8_t { + Color, + // Depth, stencil, sample mask (channels as `DB_SHADER_CONTROL` enables). + Depth, + Null, + Position, + Param, + // `param0` of a vertex shader without outputs: the hardware wants one parameter export + // regardless. + Unread, + // The primitive export of a merged or mesh stage. + Primitive, + // A mesh program's per-primitive output (a row of `PSG1`). + PrimitiveParam, + }; + Kind kind = Kind::Null; + std::uint8_t n = 0; // Color, Position + native::Usage usage; // Param, PrimitiveParam + std::uint8_t row = 0; // Param, PrimitiveParam + + static constexpr Target Simple(Kind k) { return {k, 0, {}, 0}; } + static constexpr Target Color(std::uint8_t n) { return {Kind::Color, n, {}, 0}; } + static constexpr Target Position(std::uint8_t n) { return {Kind::Position, n, {}, 0}; } + static constexpr Target Param(native::Usage u, std::uint8_t row) { return {Kind::Param, 0, u, row}; } + static constexpr Target PrimitiveParam(native::Usage u, std::uint8_t row) + { + return {Kind::PrimitiveParam, 0, u, row}; + } + bool operator==(const Target&) const = default; +}; + +struct Export { + Site site; + Target target; + // Per channel, as the instruction enables them. + std::array<std::optional<ir::Value>, 4> values{}; + // Two f16 values per dword. + bool compressed = false; + // The program's last export (for pixels: kills the lanes not in EXEC). + bool done = false; + bool operator==(const Export&) const = default; +}; + +struct Io { + // Input values the hardware loads, with their meaning; other VGPRs read before written hold + // undefined values. + std::vector<std::pair<ir::Value, Input>> inputs; + std::vector<std::pair<Site, Interp>> interps; + std::vector<Export> exports; + // Compute: how many SGPRs the hardware initializes (ComputeIo::initialized_sgprs). + std::optional<std::uint8_t> initialized_sgprs; + bool operator==(const Io&) const = default; +}; + +// Raises the I/O of `p`, built from `native`'s patched code. Throws ShaderError for stages whose +// stage data is not read and on constructs not covered yet. +Io raise(const ir::Program& p, const native::NativeProgram& native); + +namespace detail { +// The pixel input VGPRs that `addr` enables, with their meaning. +std::vector<std::pair<std::uint8_t, Input>> ps_vgprs(std::uint32_t addr); +} // namespace detail + +} // namespace io +} // namespace x2w::vs diff --git a/src/x2w_shader/ir.cpp b/src/x2w_shader/ir.cpp new file mode 100644 index 0000000000..7d6576a467 --- /dev/null +++ b/src/x2w_shader/ir.cpp @@ -0,0 +1,1476 @@ +// One-to-one SSA form of a native program. +#include "x2w_shader/ir.h" + +#include <algorithm> +#include <array> +#include <stdexcept> +#include <unordered_map> +#include <unordered_set> + +namespace x2w::vs::ir { + +using gfx10::Fields; +using gfx10::Flow; +using gfx10::Instruction; +using gfx10::Operand; + +std::string Reg::debug() const { + switch (kind) { + case Kind::S: return "S(" + std::to_string(n) + ")"; + case Kind::Scc: return "Scc"; + case Kind::V: return "V(" + std::to_string(n) + ")"; + } + return {}; +} + +std::string Value::debug() const { return "Value(" + std::to_string(n) + ")"; } + +std::vector<std::size_t> Exit::successors() const { + switch (kind) { + case Kind::Jump: return {target}; + case Kind::Branch: return {taken, not_taken}; + default: return {}; + } +} + +std::string Exit::debug() const { + switch (kind) { + case Kind::Jump: return "Jump(" + std::to_string(target) + ")"; + case Kind::Branch: + return "Branch { taken: " + std::to_string(taken) + ", not_taken: " + std::to_string(not_taken) + " }"; + case Kind::End: return "End"; + case Kind::Indirect: return "Indirect"; + } + return {}; +} + +std::string_view Inst::name() const { return machine.name().value_or(""); } + +std::optional<Value> Inst::read(Reg reg) const { + for (const auto& r : reads) { + if (r.first == reg) return r.second; + } + return std::nullopt; +} + +std::optional<Value> Inst::write(Reg reg) const { + for (const auto& w : writes) { + if (w.first == reg) return w.second; + } + return std::nullopt; +} + +namespace { + +using detail::Effects; +using detail::NONE; + +// Scalar codes 0-255 (from PARKED up: parked scalars), SCC, VGPRs 0-255. +constexpr std::size_t REGS = 256 + 1 + 256; +constexpr std::size_t SET_WORDS = (REGS + 63) / 64; +using RegSet = std::array<std::uint64_t, SET_WORDS>; + +std::size_t index(Reg reg) { + switch (reg.kind) { + case Reg::Kind::S: return reg.n; + case Reg::Kind::Scc: return 256; + case Reg::Kind::V: return 257 + std::size_t(reg.n); + } + return 0; +} + +Reg reg_at(std::size_t i) { + if (i < 256) return Reg::S(std::uint8_t(i)); + if (i == 256) return Reg::Scc; + return Reg::V(std::uint8_t(i - 257)); +} + +void insert(RegSet& set, Reg reg) { + std::size_t i = index(reg); + set[i / 64] |= std::uint64_t{1} << (i % 64); +} + +bool contains(const RegSet& set, Reg reg) { + std::size_t i = index(reg); + return ((set[i / 64] >> (i % 64)) & 1) != 0; +} + +// In Reg order, which is also index order. +std::vector<Reg> members(const RegSet& set) { + std::vector<Reg> out; + for (std::size_t i = 0; i < REGS; ++i) { + if (((set[i / 64] >> (i % 64)) & 1) != 0) out.push_back(reg_at(i)); + } + return out; +} + +// `outs` is sorted by register, and holds every register live out. +Value lookup(const std::vector<std::pair<Reg, Value>>& outs, Reg reg) { + auto it = std::lower_bound(outs.begin(), outs.end(), reg, + [](const std::pair<Reg, Value>& e, Reg r) { return e.first < r; }); + if (it != outs.end() && it->first == reg) return it->second; + return NONE; +} + +// Registers live into and out of each block. +std::pair<std::vector<RegSet>, std::vector<RegSet>> liveness(const std::vector<Block>& blocks, + const std::vector<std::size_t>& order) { + RegSet empty{}; + std::vector<RegSet> uses(blocks.size(), empty), defs(blocks.size(), empty); + for (std::size_t b = 0; b < blocks.size(); ++b) { + for (const Inst& inst : blocks[b].insts) { + for (const auto& [reg, _] : inst.reads) { + if (!contains(defs[b], reg)) insert(uses[b], reg); + } + for (const auto& [reg, _] : inst.writes) insert(defs[b], reg); + } + } + std::vector<RegSet> live_in(blocks.size(), empty), live_out(blocks.size(), empty); + bool changed = true; + while (changed) { + changed = false; + for (auto it = order.rbegin(); it != order.rend(); ++it) { + std::size_t b = *it; + RegSet out = empty; + for (std::size_t s : blocks[b].exit.successors()) { + for (std::size_t w = 0; w < SET_WORDS; ++w) out[w] |= live_in[s][w]; + } + RegSet inn = empty; + for (std::size_t w = 0; w < SET_WORDS; ++w) inn[w] = uses[b][w] | (out[w] & ~defs[b][w]); + if (inn != live_in[b] || out != live_out[b]) { + live_in[b] = inn; + live_out[b] = out; + changed = true; + } + } + } + return {std::move(live_in), std::move(live_out)}; +} + +// A loop among the `inside` blocks entered at more than one block, with its entries. Loops nested in +// a single-entry loop are searched with its header removed, so one is found whenever the control +// flow is irreducible. +std::optional<std::pair<std::vector<bool>, std::vector<std::size_t>>> multi_entry_loop( + const std::vector<Block>& blocks, const std::vector<bool>& inside) { + auto reach = [&](std::size_t from, bool forward) { + std::vector<bool> seen(blocks.size(), false); + std::vector<std::size_t> stack{from}; + while (!stack.empty()) { + std::size_t b = stack.back(); + stack.pop_back(); + std::vector<std::size_t> next = forward ? blocks[b].exit.successors() : blocks[b].preds; + for (std::size_t n : next) { + if (inside[n] && !seen[n]) { + seen[n] = true; + stack.push_back(n); + } + } + } + return seen; + }; + std::vector<bool> done(blocks.size(), false); + for (std::size_t v = 0; v < blocks.size(); ++v) { + if (!inside[v] || done[v]) continue; + // Blocks on a cycle through `v`; `v` itself only if there is one. + std::vector<bool> ahead = reach(v, true), behind = reach(v, false); + std::vector<bool> region(blocks.size()); + for (std::size_t i = 0; i < blocks.size(); ++i) region[i] = ahead[i] && behind[i]; + if (!region[v]) continue; + for (std::size_t b = 0; b < blocks.size(); ++b) { + if (region[b]) done[b] = true; + } + std::vector<std::size_t> entries; + for (std::size_t b = 0; b < blocks.size(); ++b) { + if (!region[b]) continue; + for (std::size_t p : blocks[b].preds) { + if (!region[p]) { + entries.push_back(b); + break; + } + } + } + if (entries.empty()) continue; + if (entries.size() == 1) { + std::vector<bool> nested = region; + nested[entries[0]] = false; + if (auto found = multi_entry_loop(blocks, nested)) return found; + continue; + } + return std::make_pair(std::move(region), std::move(entries)); + } + return std::nullopt; +} + +// Scheduling hints, performance counters and tracing: no effect on results. +constexpr std::string_view DROPPED[] = { + "s_nop", + "s_waitcnt", + "s_waitcnt_vscnt", + "s_waitcnt_vmcnt", + "s_waitcnt_expcnt", + "s_waitcnt_lgkmcnt", + "s_waitcnt_depctr", + "s_wait_idle", + "s_inst_prefetch", + "s_clause", + "s_setprio", + "s_sleep", + "s_ttracedata", + "s_ttracedata_imm", + "s_incperflevel", + "s_decperflevel", + "v_nop", + "v_pipeflush", + "v_clrexcp", +}; + +bool contains_str(std::string_view s, std::string_view part) { return s.find(part) != std::string_view::npos; } + +// Scalar ALU opcodes that set SCC (carry, overflow, comparison, or "result is not zero"). +bool writes_scc(gfx10::Encoding encoding, std::string_view name) { + using gfx10::Encoding; + if (encoding == Encoding::Sopc) return true; + if (encoding == Encoding::Sopk) return name.starts_with("s_cmpk_") || name == "s_addk_i32"; + // name.split('_').nth(1) + std::string_view stem; + std::size_t a = name.find('_'); + if (a != std::string_view::npos) { + std::size_t b = name.find('_', a + 1); + stem = name.substr(a + 1, b == std::string_view::npos ? std::string_view::npos : b - a - 1); + } + static constexpr std::string_view STEMS[] = { + "add", "sub", "addc", "subb", "min", "max", "and", "or", "xor", "andn2", + "orn2", "nand", "nor", "xnor", "lshl", "lshr", "ashr", "bfe", "absdiff", "lshl1", + "lshl2", "lshl3", "lshl4", "not", "wqm", "bcnt0", "bcnt1", "quadmask", "abs", + }; + return contains_str(name, "saveexec") || contains_str(name, "wrexec") || + std::find(std::begin(STEMS), std::end(STEMS), stem) != std::end(STEMS); +} + +// What an atomic with `glc` returns: the old value (for compare-and-swap, half the data operand). +Operand atomic_result(const Operand& data, std::string_view name) { + if (data.kind == Operand::Kind::Vector && contains_str(name, "cmpswap")) { + return Operand::Vector(data.reg, std::uint8_t(data.dwords / 2)); + } + return data; +} + +// Appends the register dwords an operand names; reading `vccz`, `execz`, `scc` or `lds_direct` reads the +// register behind it. False: a range out of bounds. +bool add_regs(const Operand& op, std::uint8_t lanes, std::vector<Reg>& out) { + switch (op.kind) { + case Operand::Kind::Scalar: { + if (op.code == gfx10::NULL_CODE) return true; + unsigned end = unsigned(op.code) + unsigned(op.dwords); + // A machine operand ends within the machine's codes, a parked scalar (`unspill`) within those + // past them. + unsigned limit = op.code < PARKED ? 128 : 256; + if (end > limit) return false; + for (unsigned c = op.code; c < end; ++c) out.push_back(Reg::S(std::uint8_t(c))); + return true; + } + case Operand::Kind::Vector: + if (unsigned(op.reg) + unsigned(op.dwords) > 256) return false; + for (unsigned i = 0; i < op.dwords; ++i) out.push_back(Reg::V(std::uint8_t(op.reg + i))); + return true; + case Operand::Kind::Const: + if (op.code == 251) { + for (unsigned i = 0; i < lanes; ++i) out.push_back(Reg::S(std::uint8_t(VCC + i))); + } else if (op.code == 252) { + for (unsigned i = 0; i < lanes; ++i) out.push_back(Reg::S(std::uint8_t(EXEC + i))); + } else if (op.code == 253) { + out.push_back(Reg::Scc); + } else if (op.code == 254) { + out.push_back(Reg::S(M0)); + } + return true; + default: + return true; + } +} + +template <class T> +bool vec_contains(const std::vector<T>& v, const T& x) { + return std::find(v.begin(), v.end(), x) != v.end(); +} + +// (save, N, X, K) of `v_writelane_b32 vN, sX, K` / `v_readlane_b32 sX, vN, K`. +struct Park { + bool save; + std::uint8_t reg; + std::uint8_t code; + std::uint32_t lane; + bool operator==(const Park&) const = default; +}; + +std::optional<Park> parked(const Instruction& inst, const Fields& fields) { + const gfx10::Valu* v = std::get_if<gfx10::Valu>(&fields); + if (!v) return std::nullopt; + if (v->abs != 0 || v->neg != 0 || v->opsel != 0 || v->clamp || v->omod != 0 || v->sdwa || v->dpp) { + return std::nullopt; + } + auto lane = [](const Operand& op) -> std::optional<std::uint32_t> { + if (op.kind == Operand::Kind::Const && op.code >= 128 && op.code <= 191) return std::uint32_t(op.code) - 128; + return std::nullopt; + }; + auto name = inst.name(); + if (!name || !v->dst || v->src.size() != 2) return std::nullopt; + const Operand& dst = *v->dst; + const Operand& s0 = v->src[0]; + if (*name == "v_writelane_b32" && dst.kind == Operand::Kind::Vector && s0.kind == Operand::Kind::Scalar && + s0.code < 105) { + auto k = lane(v->src[1]); + if (!k) return std::nullopt; + return Park{true, dst.reg, s0.code, *k}; + } + if (*name == "v_readlane_b32" && dst.kind == Operand::Kind::Scalar && s0.kind == Operand::Kind::Vector && + dst.code < 105) { + auto k = lane(v->src[1]); + if (!k) return std::nullopt; + return Park{false, s0.reg, dst.code, *k}; + } + return std::nullopt; +} + +struct Move { + std::size_t index; + std::uint8_t dst; + std::uint8_t src; + auto operator<=>(const Move&) const = default; +}; + +// Scalar registers the compiler parked in lanes of a VGPR, as scalar moves. A VGPR used only by +// `v_writelane_b32 vN, sX, K` / `v_readlane_b32 sX, vN, K` with constant lanes is a store of scalars; each +// (VGPR, lane) gets a spare register code and the save and restore become `s_mov_b32` (or `s_mov_b64` for +// lane pairs in wave64) to and from it. Returns the moves (index in `list`, destination code, source code) +// in order. +std::vector<Move> unspill(std::vector<Instruction>& list, const std::vector<Flow>& flows, + const std::vector<std::size_t>& leaders, bool wave64, std::uint8_t lanes, + std::uint16_t vgprs) { + const std::size_t len = list.size(); + // VGPRs used by other than parking (the last such use), the scalar codes the program uses, and + // per instruction the scalar codes it writes and reads. + std::array<std::optional<std::size_t>, 256> other{}; + std::array<bool, 256> used{}; + std::vector<std::optional<Park>> parks; + std::vector<std::vector<std::uint8_t>> written, read; + parks.reserve(len); + written.reserve(len); + read.reserve(len); + for (const Instruction& inst : list) { + auto name = inst.name(); + if (!name) return {}; + Fields fields = inst.fields(wave64); + std::optional<Park> park = parked(inst, fields); + std::optional<Effects> effects; + try { + effects = detail::effects(inst, fields, *name, lanes, vgprs); + } catch (const ShaderError&) { + return {}; + } + std::vector<std::uint8_t> codes, from; + if (effects) { + const auto& [reads, writes] = *effects; + for (Reg reg : writes) { + if (reg.is_s()) codes.push_back(reg.n); + } + for (Reg reg : reads) { + if (reg.is_s()) from.push_back(reg.n); + } + // An M0-relative read (`v_movrels_b32`) names every VGPR from its base up; the compiler + // indexes a small array with it, never the lanes it parks scalars in, so it does not + // make those VGPRs ordinary ones. (Relative writes still do.) + bool relative = *name == "v_movrels_b32"; + std::size_t n_reads = reads.size(); + for (std::size_t k = 0; k < reads.size() + writes.size(); ++k) { + Reg reg = k < n_reads ? reads[k] : writes[k - n_reads]; + if (relative && k < n_reads && reg.is_v()) continue; + if (reg.is_s()) { + used[reg.n] = true; + } else if (reg.is_v()) { + // The parking instruction's VGPR acts as storage. + if (!(park && park->reg == reg.n)) other[reg.n] = parks.size(); + } + } + } + parks.push_back(park); + written.push_back(std::move(codes)); + read.push_back(std::move(from)); + } + auto leader = [&](std::size_t i) { return std::binary_search(leaders.begin(), leaders.end(), list[i].offset); }; + for (std::size_t reg = 0; reg < 256; ++reg) { + if (!other[reg]) continue; + std::size_t last = *other[reg]; + auto of = [&](const std::optional<Park>& p) -> std::optional<Park> { + if (p && p->reg == reg) return p; + return std::nullopt; + }; + std::optional<std::size_t> first; + for (std::size_t i = 0; i < parks.size(); ++i) { + auto p = of(parks[i]); + if (p && p->save) { + first = i; + break; + } + } + bool late = false; + if (first) { + std::size_t end = *first; + for (std::size_t i = parks.size(); i-- > 0;) { + if (of(parks[i])) { + end = i; + break; + } + } + late = last < *first; + if (late) { + for (std::size_t i = *first + 1; i <= end; ++i) { + if (leader(i)) { + late = false; + break; + } + } + } + if (late) { + std::vector<std::uint32_t> saved; + for (std::size_t i = *first; i <= end; ++i) { + auto p = of(parks[i]); + if (!p) continue; + if (p->save) saved.push_back(p->lane); + if (!vec_contains(saved, p->lane)) { + late = false; + break; + } + } + } + } + std::size_t from = late ? *first : parks.size(); + for (std::size_t i = 0; i < from; ++i) { + if (of(parks[i])) parks[i] = std::nullopt; + } + } + if (std::all_of(parks.begin(), parks.end(), [](const auto& p) { return !p; })) return {}; + // Lane pairs (register, lower lane) that always move together: each save of the lower lane is + // followed, in the same block and before its register changes, by the save of the next register + // into the next lane; each restore of the lower lane is followed at once by the restore of the + // next lane into the next register. Only wave64 programs have pairs. + // instruction -> the instruction that completes its pair + auto partner = [&](std::size_t i) -> std::optional<std::size_t> { + if (!parks[i]) return std::nullopt; + auto [save, reg, code, lane] = *parks[i]; + Park want{save, reg, std::uint8_t(code + 1), lane + 1}; + for (std::size_t j = i + 1; j < len && !leader(j); ++j) { + if (parks[j] == want) return j; + const auto& p = parks[j]; + bool lanes_touched = p && p->reg == reg && (p->lane == lane || p->lane == lane + 1); + if (save) { + if (lanes_touched || vec_contains(written[j], code) || vec_contains(written[j], std::uint8_t(code + 1))) { + return std::nullopt; + } + } else { + // The second restore may come a few instructions later: the pair is restored at the + // first, so nothing between may read or write the second register, write the first, + // or save into the lanes. + if ((lanes_touched && p->save) || vec_contains(written[j], code) || + vec_contains(written[j], std::uint8_t(code + 1)) || vec_contains(read[j], std::uint8_t(code + 1))) { + return std::nullopt; + } + } + } + return std::nullopt; + }; + using Slot = std::pair<std::uint8_t, std::uint32_t>; + auto slot = [&](std::size_t i) -> std::optional<Slot> { + if (!parks[i]) return std::nullopt; + return Slot{parks[i]->reg, parks[i]->lane}; + }; + auto at = [&](std::size_t offset) { + return std::size_t(std::partition_point(list.begin(), list.end(), + [&](const Instruction& x) { return x.offset < offset; }) - + list.begin()); + }; + // The store each parking instruction uses, and what the stores are lanes of: one per (VGPR, + // lane), or (`split`) one per life of it. + auto stores_of = [&](bool split) -> std::pair<std::vector<std::size_t>, std::vector<Slot>> { + // Instructions of one store, by the first of them. + std::vector<std::size_t> first(len); + for (std::size_t i = 0; i < len; ++i) first[i] = i; + if (split) { + auto root = [&](std::size_t i) { + while (first[i] != i) { + first[i] = first[first[i]]; + i = first[i]; + } + return i; + }; + for (std::size_t save = 0; save < len; ++save) { + if (!(parks[save] && parks[save]->save)) continue; + std::unordered_set<std::size_t> seen; + std::vector<std::size_t> work{save + 1}; + while (!work.empty()) { + std::size_t from = work.back(); + work.pop_back(); + for (std::size_t i = from; i < len; ++i) { + if (slot(i) && slot(i) == slot(save)) { + if (parks[i] && parks[i]->save) break; + std::size_t a = root(save), b = root(i); + first[std::max(a, b)] = std::min(a, b); + } + auto go = [&](std::size_t to) { + if (seen.insert(to).second) work.push_back(to); + }; + const Flow& f = flows[i]; + if (f.kind == Flow::Kind::Next) { + if (i + 1 < len && leader(i + 1)) { + go(i + 1); + } else { + continue; + } + } else if (f.kind == Flow::Kind::Jump) { + go(at(f.target)); + } else if (f.kind == Flow::Kind::Branch) { + go(at(f.target)); + go(i + 1); + } + break; + } + } + } + for (std::size_t i = 0; i < len; ++i) first[i] = root(i); + } else { + std::unordered_map<std::uint64_t, std::size_t> of; + for (std::size_t i = 0; i < len; ++i) { + if (auto s = slot(i)) { + std::uint64_t key = std::uint64_t(s->first) << 32 | s->second; + first[i] = of.emplace(key, i).first->second; + } + } + } + std::vector<std::pair<Slot, std::size_t>> stores; + for (std::size_t i = 0; i < len; ++i) { + if (first[i] == i) { + if (auto s = slot(i)) stores.push_back({*s, i}); + } + } + std::sort(stores.begin(), stores.end()); + auto number = [&](std::size_t i) -> std::optional<std::size_t> { + for (std::size_t k = 0; k < stores.size(); ++k) { + if (stores[k].second == first[i]) return k; + } + return std::nullopt; + }; + std::vector<std::size_t> of(len, SIZE_MAX); + for (std::size_t i = 0; i < len; ++i) { + if (parks[i]) { + if (auto k = number(i)) of[i] = *k; + } + } + std::vector<Slot> slots; + for (const auto& s : stores) slots.push_back(s.first); + return {std::move(of), std::move(slots)}; + }; + struct Plan { + std::vector<std::size_t> of; + std::vector<std::pair<std::size_t, std::size_t>> pairs; + std::vector<std::uint8_t> codes; + }; + // The stores that move as pairs (lower, upper) and every store's code; none if the spare codes + // do not suffice. + auto plan = [&](bool split) -> std::optional<Plan> { + auto [of, stores] = stores_of(split); + std::vector<std::pair<std::size_t, std::size_t>> pairs; + for (std::size_t n = 0; n < stores.size(); ++n) { + auto [reg, lane] = stores[n]; + if (!wave64 || std::any_of(pairs.begin(), pairs.end(), [&](const auto& p) { return p.second == n; })) { + continue; + } + std::vector<std::size_t> lower; + for (std::size_t i = 0; i < len; ++i) { + if (of[i] == n) lower.push_back(i); + } + std::vector<std::optional<std::size_t>> partners; + for (std::size_t i : lower) partners.push_back(partner(i)); + std::vector<std::size_t> distinct; + for (const auto& p : partners) { + if (p) distinct.push_back(*p); + } + std::sort(distinct.begin(), distinct.end()); + distinct.erase(std::unique(distinct.begin(), distinct.end()), distinct.end()); + if (distinct.empty()) continue; + std::size_t upper = of.at(distinct[0]); + bool all_some = std::all_of(partners.begin(), partners.end(), [](const auto& p) { return p.has_value(); }); + bool all_upper = std::all_of(distinct.begin(), distinct.end(), [&](std::size_t j) { return of[j] == upper; }); + std::size_t count = std::size_t(std::count(of.begin(), of.end(), upper)); + if (stores.at(upper) == Slot{reg, lane + 1} && all_some && distinct.size() == lower.size() && all_upper && + count == lower.size()) { + pairs.push_back({n, upper}); + } + } + // Lives of one lane that move alike share a code, as they share the lane. + using Role = std::pair<Slot, std::uint8_t>; + auto role = [&](std::size_t n) { + bool lo = std::any_of(pairs.begin(), pairs.end(), [&](const auto& p) { return p.first == n; }); + bool up = std::any_of(pairs.begin(), pairs.end(), [&](const auto& p) { return p.second == n; }); + return Role{stores[n], std::uint8_t((lo ? 1 : 0) + 2 * (up ? 1 : 0))}; + }; + std::vector<Role> shared; + for (std::size_t n = 0; n < stores.size(); ++n) shared.push_back(role(n)); + std::vector<Role> all = shared; + std::sort(shared.begin(), shared.end()); + shared.erase(std::unique(shared.begin(), shared.end()), shared.end()); + std::vector<std::size_t> place; + for (const Role& r : all) { + auto it = std::lower_bound(shared.begin(), shared.end(), r); + if (it != shared.end() && *it == r) place.push_back(std::size_t(it - shared.begin())); + } + for (std::size_t& o : of) { + if (o != SIZE_MAX) o = place[o]; + } + for (auto& p : pairs) p = {place[p.first], place[p.second]}; + std::sort(pairs.begin(), pairs.end()); + pairs.erase(std::unique(pairs.begin(), pairs.end()), pairs.end()); + // Codes for the parked scalars: the trap temporaries (108..=123), then user SGPRs the + // program never names, from the top, then the codes past the machine's (PARKED..=254; 255 + // stays unused so that the code after a parked one always exists). + const std::size_t past = PARKED; + std::array<bool, 256> free{}; + for (std::size_t c = 0; c < 105; ++c) free[c] = !used[c]; + for (std::size_t c = 108; c <= 123; ++c) free[c] = !used[c]; + for (std::size_t c = past; c < 255; ++c) free[c] = true; + std::vector<std::optional<std::uint8_t>> codes(shared.size()); + for (const auto& [lo, up] : pairs) { + std::optional<std::size_t> found; + auto try_pair = [&](std::size_t c) { + if (!found && free[c] && free[c + 1]) found = c; + }; + for (std::size_t c = 108; c < 123; ++c) try_pair(c); + for (std::size_t c = 104; c-- > 0;) try_pair(c); + for (std::size_t c = past; c < 254; ++c) try_pair(c); + // Not enough spare codes: leave the program as it is. + if (!found) return std::nullopt; + std::size_t c = *found; + free[c] = false; + free[c + 1] = false; + codes[lo] = std::uint8_t(c); + codes[up] = std::uint8_t(c + 1); + } + for (auto& code : codes) { + if (code) continue; + std::optional<std::size_t> found; + auto try_one = [&](std::size_t c) { + if (!found && free[c]) found = c; + }; + for (std::size_t c = 108; c <= 123; ++c) try_one(c); + for (std::size_t c = 105; c-- > 0;) try_one(c); + for (std::size_t c = past; c < 255; ++c) try_one(c); + if (!found) return std::nullopt; + free[*found] = false; + code = std::uint8_t(*found); + } + Plan out; + out.of = std::move(of); + out.pairs = std::move(pairs); + for (const auto& c : codes) out.codes.push_back(*c); + return out; + }; + std::optional<Plan> chosen = plan(false); + if (!chosen) return {}; + auto lonely = [&](const Plan& pl) { + for (std::size_t i = 0; i < len; ++i) { + if (parks[i] && parks[i]->save && partner(i) && + !std::any_of(pl.pairs.begin(), pl.pairs.end(), + [&](const auto& p) { return pl.of[i] == p.first || pl.of[i] == p.second; })) { + return true; + } + } + return false; + }; + if (wave64 && lonely(*chosen)) { + if (std::optional<Plan> split = plan(true); split && split->pairs.size() > chosen->pairs.size()) { + chosen = std::move(split); + } + } + const std::vector<std::size_t>& store = chosen->of; + const auto& pairs = chosen->pairs; + const std::vector<std::uint8_t>& codes = chosen->codes; + // `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code from PARKED up + // does not fit the word: s0 stands in for it there. + auto field = [](std::uint8_t code) -> std::uint32_t { return code < PARKED ? code : 0; }; + auto mov = [&](bool wide, std::uint8_t dst, std::uint8_t src) -> std::uint32_t { + return 0xBE80'0000u | field(dst) << 16 | (3u + (wide ? 1u : 0u)) << 8 | field(src); + }; + constexpr std::uint32_t NOP = 0xBF80'0000u; + struct Edit { + std::size_t at; + std::optional<std::tuple<bool, std::uint8_t, std::uint8_t>> mov; + }; + std::vector<Edit> edits; + for (std::size_t i = 0; i < len; ++i) { + if (!parks[i]) continue; + bool save = parks[i]->save; + std::uint8_t code = parks[i]->code; + std::uint8_t slot_code = codes.at(store[i]); + if (std::any_of(pairs.begin(), pairs.end(), [&](const auto& p) { return p.first == store[i]; })) { + auto j = partner(i); + if (!j) return {}; + // A save moves the pair where its second half is saved; a restore where its first half + // is restored. + std::size_t at_i = save ? *j : i, gone = save ? i : *j; + std::uint8_t dst = save ? slot_code : code, src = save ? code : slot_code; + edits.push_back({at_i, std::make_tuple(true, dst, src)}); + edits.push_back({gone, std::nullopt}); + } else if (std::any_of(pairs.begin(), pairs.end(), [&](const auto& p) { return p.second == store[i]; })) { + // the upper half of a pair: moved with the lower + } else { + std::uint8_t dst = save ? slot_code : code, src = save ? code : slot_code; + edits.push_back({i, std::make_tuple(false, dst, src)}); + } + } + std::vector<Move> moves; + for (const Edit& e : edits) { + if (e.mov) { + auto [wide, dst, src] = *e.mov; + list[e.at] = Instruction(list[e.at].offset, gfx10::Encoding::Sop1, std::uint16_t(3 + (wide ? 1 : 0)), + {mov(wide, dst, src)}); + moves.push_back({e.at, dst, src}); + } else { + list[e.at] = Instruction(list[e.at].offset, gfx10::Encoding::Sopp, 0, {NOP}); + } + } + std::sort(moves.begin(), moves.end()); + return moves; +} + +std::vector<std::pair<Reg, Value>> unset(const std::vector<Reg>& regs) { + std::vector<std::pair<Reg, Value>> out; + out.reserve(regs.size()); + for (Reg r : regs) out.push_back({r, NONE}); + return out; +} + +void retarget(Exit& exit, const std::function<std::size_t(std::size_t)>& to) { + if (exit.kind == Exit::Kind::Jump) { + exit.target = to(exit.target); + } else if (exit.kind == Exit::Kind::Branch) { + exit.taken = to(exit.taken); + exit.not_taken = to(exit.not_taken); + } +} + +bool all_sopp(const Block& b) { + return std::all_of(b.insts.begin(), b.insts.end(), + [](const Inst& i) { return std::holds_alternative<gfx10::Sopp>(i.fields); }); +} + +// Clears the phis and renames after the exits changed; nullopt if the flow became irreducible beyond +// repair. +std::optional<Program> relink(std::vector<Block> blocks, const Program& p) { + for (Block& block : blocks) block.phis.clear(); + detail::link(blocks); + try { + detail::split_irreducible(blocks); + } catch (const ShaderError&) { + return std::nullopt; + } + return detail::rename(std::move(blocks), p.wave64, p.vgprs); +} + +} // namespace + +namespace detail { + +void link(std::vector<Block>& blocks) { + for (Block& block : blocks) block.preds.clear(); + for (std::size_t b = 0; b < blocks.size(); ++b) { + for (std::size_t s : blocks[b].exit.successors()) blocks.at(s).preds.push_back(b); + } +} + +// Node splitting, before SSA. While a loop is entered at several blocks (a compiler-rotated loop +// whose peeled first test jumps into its body), the entry first in reverse postorder stays the +// header, and another entry's outside predecessors move to a copy of everything that entry reaches +// in the loop before the header. The copies run the same instructions, so behaviour is unchanged. +void split_irreducible(std::vector<Block>& blocks) { + const std::size_t limit = 4 * blocks.size() + 64; + for (;;) { + std::vector<std::size_t> order = reverse_postorder(blocks); + std::vector<std::size_t> idx(blocks.size(), SIZE_MAX); + for (std::size_t i = 0; i < order.size(); ++i) idx[order[i]] = i; + auto edge = irreducible_edge(blocks, order, idx); + if (!edge) return; + std::size_t from = edge->first; + std::optional<std::pair<std::vector<bool>, std::vector<std::size_t>>> found; + found = multi_entry_loop(blocks, std::vector<bool>(blocks.size(), true)); + if (!found || !(blocks.size() < limit)) { + throw ShaderError::unsupported(blocks[from].offset, "irreducible control flow"); + } + std::vector<bool> region = std::move(found->first); + std::vector<std::size_t> entries = std::move(found->second); + std::stable_sort(entries.begin(), entries.end(), [&](std::size_t a, std::size_t b) { return idx[a] < idx[b]; }); + std::size_t header = entries[0], entry = entries[1]; + + // What `entry` reaches in the loop before the header, and its copies. + std::vector<std::size_t> copy(blocks.size(), SIZE_MAX); + std::vector<std::size_t> copied; + std::vector<std::size_t> stack{entry}; + while (!stack.empty()) { + std::size_t b = stack.back(); + stack.pop_back(); + if (copy[b] != SIZE_MAX) continue; + copy[b] = blocks.size() + copied.size(); + copied.push_back(b); + for (std::size_t s : blocks[b].exit.successors()) { + if (region[s] && s != header) stack.push_back(s); + } + } + for (std::size_t b : copied) { + Block block = blocks[b]; + retarget(block.exit, [&](std::size_t s) { return copy[s] == SIZE_MAX ? s : copy[s]; }); + blocks.push_back(std::move(block)); + } + std::vector<std::size_t> outside; + for (std::size_t p : blocks[entry].preds) { + if (!region[p]) outside.push_back(p); + } + for (std::size_t p : outside) { + retarget(blocks[p].exit, [&](std::size_t s) { return s == entry ? copy[entry] : s; }); + } + link(blocks); + } +} + +// Rename register reads and writes after changing edges in a reducible graph. +Program rename(std::vector<Block> blocks, bool wave64, std::uint16_t vgprs) { + std::vector<std::size_t> order = reverse_postorder(blocks); + auto [live_in, live_out] = liveness(blocks, order); + std::uint32_t values = 0; + auto new_value = [&]() { return Value{values++}; }; + std::vector<std::pair<Reg, Value>> inputs; + std::vector<std::vector<std::pair<Reg, Value>>> outs(blocks.size()); + std::vector<Value> current(REGS, NONE); + for (std::size_t b : order) { + std::fill(current.begin(), current.end(), NONE); + Block& block = blocks[b]; + for (Reg reg : members(live_in[b])) { + Value v; + if (block.preds.empty()) { + v = new_value(); + inputs.push_back({reg, v}); + } else if (block.preds.size() == 1) { + // A single predecessor comes earlier in reverse postorder. + v = lookup(outs[block.preds[0]], reg); + } else { + v = new_value(); + block.phis.push_back(Phi{reg, v, {}}); + } + current[index(reg)] = v; + } + for (Inst& inst : block.insts) { + for (auto& [reg, v] : inst.reads) v = current[index(reg)]; + for (auto& [reg, v] : inst.writes) { + v = new_value(); + current[index(reg)] = v; + } + } + std::vector<std::pair<Reg, Value>> out; + for (Reg reg : members(live_out[b])) out.push_back({reg, current[index(reg)]}); + outs[b] = std::move(out); + } + for (Block& block : blocks) { + for (Phi& phi : block.phis) { + phi.args.clear(); + for (std::size_t p : block.preds) phi.args.push_back(lookup(outs[p], phi.reg)); + } + } + remove_trivial_phis_steps(blocks, values); + Program p; + p.wave64 = wave64; + p.vgprs = vgprs; + p.blocks = std::move(blocks); + p.inputs = std::move(inputs); + return p; +} + +// Phis are placed for every live register at every join; those whose arguments are all one value +// (or the phi itself) are replaced by it. +std::size_t remove_trivial_phis_steps(std::vector<Block>& blocks, std::uint32_t values) { + std::vector<Value> replaced(values); + for (std::uint32_t i = 0; i < values; ++i) replaced[i] = Value{i}; + std::size_t steps = 0; + // An unrenamed path can leave NONE here. A checked lookup rejects the out-of-range value. + auto find = [&](Value v) { + Value root = v; + while (replaced.at(root.n) != root) { + ++steps; + root = replaced[root.n]; + } + Value cur = v; + while (replaced.at(cur.n) != root) { + ++steps; + Value next = replaced[cur.n]; + replaced[cur.n] = root; + cur = next; + } + return root; + }; + bool changed = true; + while (changed) { + changed = false; + for (Block& block : blocks) { + std::vector<Phi> kept; + kept.reserve(block.phis.size()); + for (Phi& phi : block.phis) { + std::optional<Value> only; + bool keep = false; + for (Value a0 : phi.args) { + Value a = find(a0); + if (a == phi.value || (only && *only == a)) continue; + if (only) { + keep = true; + break; + } + only = a; + } + if (keep || !only) { + kept.push_back(std::move(phi)); + continue; + } + replaced.at(phi.value.n) = *only; + changed = true; + } + block.phis = std::move(kept); + } + } + for (Block& block : blocks) { + for (Phi& phi : block.phis) { + for (Value& a : phi.args) a = find(a); + } + for (Inst& inst : block.insts) { + for (auto& [_, v] : inst.reads) v = find(v); + } + } + return steps; +} + +std::optional<Effects> effects(const Instruction& inst, const Fields& fields, std::string_view name, + std::uint8_t lanes, std::uint16_t vgprs) { + if (std::find(std::begin(DROPPED), std::end(DROPPED), name) != std::end(DROPPED)) return std::nullopt; + // `name` comes from the opcode tables (static, NUL-terminated). + auto unsupported = [&]() { return ShaderError::unsupported(inst.offset, name.data()); }; + auto mask = [&](std::uint8_t code, std::vector<Reg>& out) { + for (unsigned i = 0; i < lanes; ++i) out.push_back(Reg::S(std::uint8_t(code + i))); + }; + std::vector<Reg> r, w; + auto regs = [&](const Operand& op, std::vector<Reg>& out) { + if (!add_regs(op, lanes, out)) throw ShaderError::isa(inst.offset, "register range out of bounds"); + }; + bool vector = !(std::holds_alternative<gfx10::Sop>(fields) || std::holds_alternative<gfx10::Sopp>(fields) || + std::holds_alternative<gfx10::Smem>(fields)); + if (const auto* s = std::get_if<gfx10::Sop>(&fields)) { + if (name.starts_with("s_movrel") || name.starts_with("s_subvector_loop") || name == "s_call_b64" || + name == "s_rfe_b64") { + throw unsupported(); + } + for (const Operand& o : s->src) regs(o, r); + if (s->dst) { + regs(*s->dst, w); + // These change (or may keep) the destination's old value. + if (name.starts_with("s_bitset") || name.starts_with("s_cmov") || name == "s_addk_i32" || + name == "s_mulk_i32") { + regs(*s->dst, r); + } + } + if (name == "s_addc_u32" || name == "s_subb_u32" || name == "s_cmovk_i32" || name.starts_with("s_cselect_") || + name.starts_with("s_cmov_")) { + r.push_back(Reg::Scc); + } + if (contains_str(name, "saveexec") || contains_str(name, "wrexec")) { + mask(EXEC, r); + mask(EXEC, w); + } + if (writes_scc(inst.encoding, name)) w.push_back(Reg::Scc); + } else if (std::holds_alternative<gfx10::Sopp>(fields)) { + if (name == "s_cbranch_scc0" || name == "s_cbranch_scc1") { + r.push_back(Reg::Scc); + } else if (name == "s_cbranch_vccz" || name == "s_cbranch_vccnz") { + mask(VCC, r); + } else if (name == "s_cbranch_execz" || name == "s_cbranch_execnz") { + mask(EXEC, r); + } else if (name == "s_sendmsg" || name == "s_sendmsghalt") { + r.push_back(Reg::S(M0)); + } else if (name == "s_endpgm" || name == "s_endpgm_saved" || name == "s_endpgm_ordered_ps_done" || + name == "s_code_end" || name == "s_branch" || name == "s_barrier" || name == "s_icache_inv" || + name == "s_wakeup" || name == "s_round_mode" || name == "s_denorm_mode") { + } else { + throw unsupported(); + } + } else if (const auto* m = std::get_if<gfx10::Smem>(&fields)) { + if (name == "s_memtime" || name == "s_memrealtime" || name == "s_get_waveid_in_workgroup") { + if (!m->data) throw unsupported(); + regs(*m->data, w); + } else if (name == "s_gl1_inv" || name == "s_dcache_inv" || name == "s_dcache_wb") { + } else if (contains_str(name, "_load_") || contains_str(name, "_store_")) { + regs(m->base, r); + regs(m->soffset, r); + if (!m->data) throw unsupported(); + regs(*m->data, contains_str(name, "_load_") ? w : r); + } else { + throw unsupported(); + } + } else if (const auto* v = std::get_if<gfx10::Valu>(&fields)) { + bool src_indexed = false, dst_indexed = false; + if (name == "v_movrels_b32") { + src_indexed = true; + } else if (name == "v_movreld_b32") { + dst_indexed = true; + } else if (name == "v_movrelsd_b32" || name == "v_movrelsd_2_b32" || name == "v_swaprel_b32") { + src_indexed = dst_indexed = true; + } + // v[reg + M0] for any M0 that stays inside the program's VGPRs. + auto indexed = [&](const Operand& op, std::vector<Reg>& out) { + if (op.kind == Operand::Kind::Vector && std::uint16_t(op.reg) < vgprs) { + for (std::uint16_t x = op.reg; x < vgprs; ++x) out.push_back(Reg::V(std::uint8_t(x))); + return; + } + throw ShaderError::isa(inst.offset, "relative VGPR base outside the program's VGPRs"); + }; + for (std::size_t i = 0; i < v->src.size(); ++i) { + if (i == 0 && src_indexed) { + indexed(v->src[i], r); + } else { + regs(v->src[i], r); + } + } + // GFX10 compares into EXEC write nothing else. + if (name.starts_with("v_cmpx")) { + mask(EXEC, w); + } else if (v->dst) { + if (dst_indexed) { + indexed(*v->dst, w); + } else { + regs(*v->dst, w); + } + } + if (v->carry) regs(*v->carry, w); + if (name == "v_swap_b32") { + regs(v->src.at(0), w); + if (v->dst) regs(*v->dst, r); + } else if (name == "v_swaprel_b32") { + indexed(v->src.at(0), w); + if (v->dst) indexed(*v->dst, r); + } else if (name == "v_div_fmas_f32" || name == "v_div_fmas_f64") { + mask(VCC, r); + } + if (name.starts_with("v_interp_") || src_indexed || dst_indexed) r.push_back(Reg::S(M0)); + } else if (const auto* i = std::get_if<gfx10::Vintrp>(&fields)) { + regs(i->src, r); + r.push_back(Reg::S(M0)); + regs(i->dst, w); + } else if (const auto* d = std::get_if<gfx10::Ds>(&fields)) { + if (d->addr) regs(*d->addr, r); + for (const Operand& o : d->data) regs(o, r); + if (d->dst) regs(*d->dst, w); + if (d->gds || name.starts_with("ds_gws") || contains_str(name, "addtid") || name == "ds_ordered_count" || + name == "ds_append" || name == "ds_consume") { + r.push_back(Reg::S(M0)); + } + } else if (const auto* b = std::get_if<gfx10::Buffer>(&fields)) { + if (b->offen || b->idxen) regs(b->addr, r); + regs(b->rsrc, r); + regs(b->soffset, r); + if (b->lds) r.push_back(Reg::S(M0)); + if (b->data) { + const Operand& dd = *b->data; + if (contains_str(name, "_load_")) { + if (!b->lds) regs(dd, w); + } else if (contains_str(name, "_store_")) { + regs(dd, r); + } else if (contains_str(name, "_atomic_")) { + regs(dd, r); + if (b->cache.glc) regs(atomic_result(dd, name), w); + } else { + throw unsupported(); + } + } + } else if (const auto* im = std::get_if<gfx10::Image>(&fields)) { + for (const Operand& a : im->addr) regs(a, r); + regs(im->rsrc, r); + if (im->sampler) regs(*im->sampler, r); + if (contains_str(name, "_store")) { + regs(im->data, r); + } else if (contains_str(name, "_atomic_")) { + regs(im->data, r); + if (im->cache.glc) regs(atomic_result(im->data, name), w); + } else { + regs(im->data, w); + } + } else if (const auto* f = std::get_if<gfx10::Flat>(&fields)) { + if (f->addr) regs(*f->addr, r); + if (f->data) regs(*f->data, r); + if (f->saddr) regs(*f->saddr, r); + if (f->dst) regs(*f->dst, w); + } else if (const auto* e = std::get_if<gfx10::Exp>(&fields)) { + for (const auto& s : e->src) { + if (s) regs(*s, r); + } + } + if (vector) mask(EXEC, r); + std::vector<Reg> deduped; + deduped.reserve(r.size()); + for (Reg reg : r) { + if (!vec_contains(deduped, reg)) deduped.push_back(reg); + } + return Effects{std::move(deduped), std::move(w)}; +} + +} // namespace detail + +Program build(std::span<const std::uint8_t> code, bool wave64, std::uint16_t vgprs) { + std::vector<Instruction> list = gfx10::decode(code); + const std::uint8_t lanes = std::uint8_t(1 + (wave64 ? 1 : 0)); + auto isa = [](std::size_t offset, const char* reason) { return ShaderError::isa(offset, reason); }; + + std::vector<Flow> flows; + flows.reserve(list.size()); + std::vector<std::size_t> leaders{0}; + gfx10::Before before = [&](std::size_t at) -> const Instruction* { + auto it = std::partition_point(list.begin(), list.end(), [&](const Instruction& i) { return i.offset < at; }); + return it == list.begin() ? nullptr : &*std::prev(it); + }; + for (std::size_t i = 0; i < list.size(); ++i) { + Flow f = gfx10::control(list[i], code.size(), before); + if (f.kind == Flow::Kind::Jump || f.kind == Flow::Kind::Branch) leaders.push_back(f.target); + if (f.kind != Flow::Kind::Next && i + 1 < list.size()) leaders.push_back(list[i + 1].offset); + flows.push_back(f); + } + std::sort(leaders.begin(), leaders.end()); + leaders.erase(std::unique(leaders.begin(), leaders.end()), leaders.end()); + std::vector<Move> parked = unspill(list, flows, leaders, wave64, lanes, vgprs); + auto block_at = [&](std::size_t offset) -> std::size_t { + auto it = std::lower_bound(leaders.begin(), leaders.end(), offset); + if (it == leaders.end() || *it != offset) throw isa(offset, "jump into a block"); + return std::size_t(it - leaders.begin()); + }; + + std::vector<Block> blocks; + blocks.reserve(leaders.size()); + for (std::size_t offset : leaders) { + Block b; + b.offset = offset; + b.exit = Exit::End; + blocks.push_back(std::move(b)); + } + std::vector<std::optional<std::size_t>> next_offsets(list.size()); + for (std::size_t i = 0; i + 1 < list.size(); ++i) next_offsets[i] = list[i + 1].offset; + for (std::size_t n = 0; n < list.size(); ++n) { + Instruction& machine = list[n]; + const Flow flow = flows[n]; + const std::optional<std::size_t> next = next_offsets[n]; + std::size_t b = std::size_t(std::upper_bound(leaders.begin(), leaders.end(), machine.offset) - leaders.begin()) - 1; + auto name_opt = machine.name(); + if (!name_opt) throw ShaderError::unsupported(machine.offset, "unknown opcode"); + std::string_view name = *name_opt; + Fields fields = machine.fields(wave64); + // A move to or from a scalar parked in a VGPR lane (`unspill`): its register codes may be + // ones the machine word cannot hold. + auto k = std::lower_bound(parked.begin(), parked.end(), n, [](const Move& m, std::size_t v) { return m.index < v; }); + if (k != parked.end() && k->index == n) { + if (auto* sop = std::get_if<gfx10::Sop>(&fields)) { + if (sop->dst && sop->dst->kind == Operand::Kind::Scalar && !sop->src.empty() && + sop->src[0].kind == Operand::Kind::Scalar) { + sop->dst->code = k->dst; + sop->src[0].code = k->src; + } + } + } + auto fallthrough = [&]() -> std::size_t { + if (!next) throw isa(machine.offset, "falls off the code"); + return block_at(*next); + }; + // A conditional SOPP branch to fallthrough has no register effects and contributes one edge + // to the join. Calls also use Flow::Branch but write a return address. + if (machine.encoding == gfx10::Encoding::Sopp && flow.kind == Flow::Kind::Branch && next && + flow.target == *next) { + blocks[b].exit = Exit::Jump(fallthrough()); + continue; + } + bool ends = flow.kind != Flow::Kind::Next || !next || + std::binary_search(leaders.begin(), leaders.end(), *next); + if (ends) { + switch (flow.kind) { + case Flow::Kind::Next: + blocks[b].exit = Exit::Jump(fallthrough()); + break; + case Flow::Kind::Jump: + blocks[b].exit = Exit::Jump(block_at(flow.target)); + break; + case Flow::Kind::Branch: { + std::size_t taken = block_at(flow.target); + std::size_t not_taken = fallthrough(); + blocks[b].exit = Exit::Branch(taken, not_taken); + break; + } + case Flow::Kind::Stop: + blocks[b].exit = name == "s_setpc_b64" ? Exit::Indirect : Exit::End; + break; + } + } + if (auto e = detail::effects(machine, fields, name, lanes, vgprs)) { + auto& [reads, writes] = *e; + // Lanes disabled in EXEC keep the old value. + for (Reg w : writes) { + if (w.is_v() && !vec_contains(reads, w)) reads.push_back(w); + } + Inst inst; + inst.machine = std::move(machine); + inst.fields = std::move(fields); + inst.reads = unset(reads); + inst.writes = unset(writes); + blocks[b].insts.push_back(std::move(inst)); + } + } + detail::link(blocks); + if (!blocks[0].preds.empty()) throw ShaderError::unsupported(0, "a branch to the program entry"); + detail::split_irreducible(blocks); + + return detail::rename(std::move(blocks), wave64, vgprs); +} + +Program thread_edges(const Program& p, + const std::vector<std::tuple<std::size_t, std::size_t, std::size_t>>& edges) { + std::vector<Block> blocks = p.blocks; + for (Block& block : blocks) block.phis.clear(); + for (const auto& [pred, join, dest] : edges) { + Block copy = blocks.at(join); + copy.exit = Exit::Jump(dest); + std::size_t target = blocks.size(); + Exit& exit = blocks.at(pred).exit; + if (exit.kind == Exit::Kind::Jump) { + exit.target = target; + } else if (exit.kind == Exit::Kind::Branch) { + if (exit.taken == join) exit.taken = target; + if (exit.not_taken == join) exit.not_taken = target; + } else { + throw std::logic_error("threading an incoming edge"); + } + blocks.push_back(std::move(copy)); + } + detail::link(blocks); + detail::split_irreducible(blocks); + return detail::rename(std::move(blocks), p.wave64, p.vgprs); +} + +std::optional<Program> without_early_outs(const Program& p) { + auto ends = [&](std::size_t b) { return p.blocks[b].exit == Exit::End && all_sopp(p.blocks[b]); }; + std::vector<Block> blocks = p.blocks; + bool any = false; + for (Block& block : blocks) { + if (block.exit.kind != Exit::Kind::Branch) continue; + std::size_t taken = block.exit.taken, not_taken = block.exit.not_taken; + if (ends(taken) && !block.insts.empty() && block.insts.back().name() == "s_cbranch_execz") { + block.insts.pop_back(); + block.exit = Exit::Jump(not_taken); + any = true; + } + } + if (!any) return std::nullopt; + return relink(std::move(blocks), p); +} + +std::optional<Program> without_skips(const Program& p, bool deep) { + const std::size_t n = p.blocks.size(); + auto ends = [&](std::size_t b) { return p.blocks[b].exit == Exit::End && all_sopp(p.blocks[b]); }; + // Scalars moved from register to register (a scalar the compiler parked in a VGPR lane comes back + // by such a move, `unspill`) are the value they copy. + std::unordered_map<Value, Value> copy; + // Values something reads, directly or through joins. A scalar operation none of whose results is + // read reads nothing either (the compiler restores EXEC from a saved mask and overwrites it at + // once where two branches end together). + std::unordered_set<Value> live; + auto idle = [&](const Inst& inst) { + std::string_view name = inst.name(); + return std::holds_alternative<gfx10::Sop>(inst.fields) && + !(name.starts_with("s_setpc") || name.starts_with("s_swappc") || name.starts_with("s_call") || + name.starts_with("s_rfe") || name.starts_with("s_movrel") || name.starts_with("s_subvector")) && + std::all_of(inst.writes.begin(), inst.writes.end(), [&](const auto& w) { return !live.contains(w.second); }); + }; + for (const Block& block : p.blocks) { + for (const Inst& inst : block.insts) { + if ((inst.name() == "s_mov_b32" || inst.name() == "s_mov_b64") && inst.reads.size() == inst.writes.size() && + std::all_of(inst.reads.begin(), inst.reads.end(), [](const auto& r) { return r.first.is_s(); }) && + std::all_of(inst.writes.begin(), inst.writes.end(), [](const auto& r) { return r.first.is_s(); })) { + for (std::size_t i = 0; i < inst.writes.size(); ++i) copy[inst.writes[i].second] = inst.reads[i].second; + } + } + } + bool changed = true; + while (changed) { + changed = false; + for (const Block& block : p.blocks) { + for (const Inst& inst : block.insts) { + if (!idle(inst)) { + for (const auto& r : inst.reads) changed |= live.insert(r.second).second; + } + } + for (const Phi& phi : block.phis) { + if (live.contains(phi.value)) { + for (Value a : phi.args) changed |= live.insert(a).second; + } + } + } + } + auto root = [&](Value v) { + while (deep) { + auto it = copy.find(v); + if (it == copy.end()) break; + v = it->second; + } + return v; + }; + // The region a skip of `b` to `target` leaves out, if it is a pure skip. + auto skipped = [&](std::size_t b, std::size_t target, std::size_t first) -> std::optional<std::vector<bool>> { + std::vector<bool> inside(n, false); + std::vector<std::size_t> stack{first}; + while (!stack.empty()) { + std::size_t x = stack.back(); + stack.pop_back(); + if (x == target || inside[x]) continue; + if (x == b) return std::nullopt; // a loop back to the branch + inside[x] = true; + const Exit& exit = p.blocks[x].exit; + if (exit.kind == Exit::Kind::End || exit.kind == Exit::Kind::Indirect) return std::nullopt; + for (std::size_t s : exit.successors()) stack.push_back(s); + } + // entered only through the branch + for (std::size_t x = 0; x < n; ++x) { + if (!inside[x]) continue; + for (std::size_t q : p.blocks[x].preds) { + if (q != b && !inside[q]) return std::nullopt; + } + } + // the join sees no scalar the region changed + const Block& join = p.blocks[target]; + for (const Phi& phi : join.phis) { + bool scalar = phi.reg.is_s() ? (phi.reg.n != 126 && phi.reg.n != 127) : phi.reg.is_scc(); + // (a join nothing reads shows no one the difference) + if (!scalar || (deep && !live.contains(phi.value))) continue; + std::vector<Value> before; + for (std::size_t k = 0; k < join.preds.size() && k < phi.args.size(); ++k) { + if (join.preds[k] == b) before.push_back(root(phi.args[k])); + } + for (std::size_t k = 0; k < join.preds.size() && k < phi.args.size(); ++k) { + if (inside[join.preds[k]] && !vec_contains(before, root(phi.args[k]))) return std::nullopt; + } + } + // Other ways into the join than the branch and the region (an inner branch that ends + // together with an outer one) change nothing in that: the lanes that would have skipped + // arrive from the region instead, with the same scalars. + if (!deep) { + for (std::size_t q : join.preds) { + if (q != b && !inside[q]) return std::nullopt; + } + } + return inside; + }; + std::vector<Block> blocks = p.blocks; + bool any = false; + for (std::size_t b = 0; b < n; ++b) { + if (p.blocks[b].exit.kind != Exit::Kind::Branch) continue; + std::size_t taken = p.blocks[b].exit.taken, not_taken = p.blocks[b].exit.not_taken; + if (p.blocks[b].insts.empty() || p.blocks[b].insts.back().name() != "s_cbranch_execz") continue; + if (ends(taken) || skipped(b, taken, not_taken)) { + blocks[b].insts.pop_back(); + blocks[b].exit = Exit::Jump(not_taken); + any = true; + } + } + if (!any) return std::nullopt; + return relink(std::move(blocks), p); +} + +std::vector<Reg> operand_reads(const Program& p, const Inst& inst) { + std::uint8_t lanes = std::uint8_t(1 + (p.wave64 ? 1 : 0)); + try { + auto e = detail::effects(inst.machine, inst.fields, inst.name(), lanes, p.vgprs); + if (e) return std::move(e->first); + } catch (const ShaderError&) { + } + return {}; +} + +std::vector<std::size_t> reverse_postorder(std::span<const Block> blocks) { + std::vector<bool> seen(blocks.size(), false); + std::vector<std::size_t> post; + post.reserve(blocks.size()); + std::vector<std::pair<std::size_t, std::size_t>> stack{{0, 0}}; + seen[0] = true; + while (!stack.empty()) { + auto& top = stack.back(); + auto [b, i] = top; + top.second += 1; + std::vector<std::size_t> succ = blocks[b].exit.successors(); + if (i < succ.size()) { + std::size_t s = succ[i]; + if (!seen[s]) { + seen[s] = true; + stack.push_back({s, 0}); + } + } else { + post.push_back(b); + stack.pop_back(); + } + } + std::reverse(post.begin(), post.end()); + return post; +} + +std::optional<std::pair<std::size_t, std::size_t>> irreducible_edge(std::span<const Block> blocks, + std::span<const std::size_t> order, + std::span<const std::size_t> index) { + if (order.empty()) return std::nullopt; + std::size_t entry = order[0]; + std::vector<std::size_t> idom = idoms(blocks, order, index); + for (std::size_t b : order) { + for (std::size_t s : blocks[b].exit.successors()) { + if (index[s] > index[b]) continue; + std::size_t d = b; + while (d != s && d != entry) d = idom[d]; + if (d != s) return std::make_pair(b, s); + } + } + return std::nullopt; +} + +std::vector<std::size_t> idoms(std::span<const Block> blocks, std::span<const std::size_t> order, + std::span<const std::size_t> index) { + std::vector<std::size_t> idom(blocks.size(), SIZE_MAX); + if (order.empty()) return idom; + std::size_t entry = order[0]; + idom[entry] = entry; + auto intersect = [&](std::size_t a, std::size_t b) { + while (a != b) { + while (index[a] > index[b]) a = idom[a]; + while (index[b] > index[a]) b = idom[b]; + } + return a; + }; + bool changed = true; + while (changed) { + changed = false; + for (std::size_t k = 1; k < order.size(); ++k) { + std::size_t b = order[k]; + std::size_t nw = SIZE_MAX; + for (std::size_t q : blocks[b].preds) { + if (idom[q] == SIZE_MAX) continue; + nw = nw == SIZE_MAX ? q : intersect(q, nw); + } + if (idom[b] != nw) { + idom[b] = nw; + changed = true; + } + } + } + return idom; +} + +} // namespace x2w::vs::ir diff --git a/src/x2w_shader/ir.h b/src/x2w_shader/ir.h new file mode 100644 index 0000000000..464a801d17 --- /dev/null +++ b/src/x2w_shader/ir.h @@ -0,0 +1,224 @@ +// One-to-one SSA form of a native program. +// +// Every machine instruction becomes one Inst, except scheduling-only ones (`s_nop`, `s_waitcnt*`, +// `s_inst_prefetch`...) and redundant conditional branches. Each register dword is a variable: a +// read names the Value it sees, a write defines a new one, and Phis merge values where control flow +// joins. Nothing is raised: an instruction keeps its opcode and decoded fields, so its exact +// semantics stay with it. +// +// Implicit operands are explicit: SCC, M0, and EXEC, which every vector instruction reads. A write +// to a VGPR also reads the register's old value, because lanes disabled in EXEC keep it. +// +// M0-relative VGPR access (`v_movrels/d/sd_b32`, `v_swaprel_b32`) names its operand's whole possible +// range: from the encoded register up to the program's VGPR count, all read (and all written, for a +// destination). +#pragma once + +#include <compare> +#include <cstddef> +#include <cstdint> +#include <functional> +#include <optional> +#include <span> +#include <string> +#include <string_view> +#include <tuple> +#include <utility> +#include <vector> + +#include "x2w_shader/error.h" +#include "x2w_shader/gfx10/mod.h" + +namespace x2w::vs::ir { + +// One register dword. Sort scalar registers before SCC, then vector registers. Scalar codes as in +// Operand::Scalar: 0-105 SGPRs, 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC. Codes from +// PARKED up are scalars the compiler parked in VGPR lanes (`unspill`): no machine instruction names them. +struct Reg { + enum class Kind : std::uint8_t { S = 0, Scc = 1, V = 2 }; + Kind kind = Kind::S; + // S: the scalar code; V: the VGPR; Scc: 0. + std::uint8_t n = 0; + + static constexpr Reg S(std::uint8_t code) { return {Kind::S, code}; } + static constexpr Reg V(std::uint8_t reg) { return {Kind::V, reg}; } + static const Reg Scc; + + constexpr bool is_s() const { return kind == Kind::S; } + constexpr bool is_scc() const { return kind == Kind::Scc; } + constexpr bool is_v() const { return kind == Kind::V; } + + constexpr bool operator==(const Reg&) const = default; + constexpr auto operator<=>(const Reg&) const = default; + // Diagnostic spelling: "S(5)", "Scc", "V(3)". + std::string debug() const; +}; +inline constexpr Reg Reg::Scc = {Reg::Kind::Scc, 0}; + +inline constexpr std::uint8_t VCC = 106; +inline constexpr std::uint8_t M0 = 124; +inline constexpr std::uint8_t EXEC = 126; +// The first scalar code past the machine's (0-127): see Reg. +inline constexpr std::uint8_t PARKED = 128; + +// An SSA value holds one register dword, or one bit for SCC. +struct Value { + std::uint32_t n = 0; + constexpr bool operator==(const Value&) const = default; + constexpr auto operator<=>(const Value&) const = default; + // Diagnostic spelling: "Value(3)". + std::string debug() const; +}; + +struct Exit { + enum class Kind : std::uint8_t { + Jump, + // `s_cbranch_*`, the block's last instruction. + Branch, + // `s_endpgm` and its variants. + End, + // `s_setpc_b64` to an address held in registers, e.g. the handover to the next half of a + // merged hardware stage. + Indirect, + }; + Kind kind = Kind::End; + std::size_t target = 0; // Jump + std::size_t taken = 0; // Branch + std::size_t not_taken = 0; // Branch + + static constexpr Exit Jump(std::size_t b) { return {Kind::Jump, b, 0, 0}; } + static constexpr Exit Branch(std::size_t taken, std::size_t not_taken) { + return {Kind::Branch, 0, taken, not_taken}; + } + static const Exit End; + static const Exit Indirect; + + constexpr bool is_jump() const { return kind == Kind::Jump; } + constexpr bool is_branch() const { return kind == Kind::Branch; } + constexpr bool is_end() const { return kind == Kind::End; } + constexpr bool is_indirect() const { return kind == Kind::Indirect; } + + std::vector<std::size_t> successors() const; + constexpr bool operator==(const Exit&) const = default; + // Diagnostic spelling: "Jump(2)", "Branch { taken: 2, not_taken: 1 }", "End", "Indirect". + std::string debug() const; +}; +inline constexpr Exit Exit::End = {Exit::Kind::End, 0, 0, 0}; +inline constexpr Exit Exit::Indirect = {Exit::Kind::Indirect, 0, 0, 0}; + +struct Phi { + Reg reg; + Value value; + // One per predecessor, in Block::preds order. + std::vector<Value> args; + bool operator==(const Phi&) const = default; +}; + +struct Inst { + gfx10::Instruction machine; + gfx10::Fields fields; + // Every register dword read, with the value it holds. + std::vector<std::pair<Reg, Value>> reads; + // Every register dword written, with the value it receives. + std::vector<std::pair<Reg, Value>> writes; + + // The opcode name ("" if unknown). Static storage: compare by content. + std::string_view name() const; + // The value `reg` holds when this instruction reads it. + std::optional<Value> read(Reg reg) const; + // The value this instruction writes to `reg`. + std::optional<Value> write(Reg reg) const; + bool operator==(const Inst&) const = default; +}; + +struct Block { + // Byte offset of the block's first machine instruction (shared by a block and its copies). + std::size_t offset = 0; + std::vector<std::size_t> preds; + std::vector<Phi> phis; + std::vector<Inst> insts; + Exit exit = Exit::End; + bool operator==(const Block&) const = default; +}; + +struct Program { + bool wave64 = false; + // VGPRs v0 up to this exist; bounds M0-relative access. + std::uint16_t vgprs = 0; + // In code order, then copies made to give every loop one entry; block 0 is the entry. + std::vector<Block> blocks; + // Registers read before any write, with their value on entry: what the hardware or a called + // fetch routine set up (user SGPRs, system values, vertex inputs). + std::vector<std::pair<Reg, Value>> inputs; + bool operator==(const Program&) const = default; +}; + +// Decodes `code` and builds its SSA form; `vgprs` is the program's VGPR count. Throws +// ShaderError::unsupported on instructions the IR cannot express yet (and ::isa on bad code). +Program build(std::span<const std::uint8_t> code, bool wave64, std::uint16_t vgprs); + +// Duplicate a join for each proven (predecessor, join, destination) edge. The instructions still +// execute on that path and define fresh SSA values (pub(crate)). Throws ShaderError. +Program thread_edges(const Program& p, const std::vector<std::tuple<std::size_t, std::size_t, std::size_t>>& edges); + +// The program without its early-outs (an `s_cbranch_execz` to a block that only ends the program); +// nullopt if the program has no such branch (pub(crate)). +std::optional<Program> without_early_outs(const Program& p); + +// As without_early_outs, and also without the branches that only skip a region when no lane is left +// for it; `deep` looks closer at what the code after the branch can see. nullopt if nothing changes +// (pub(crate)). +std::optional<Program> without_skips(const Program& p, bool deep); + +// The registers `inst` of `p` reads as operands: its reads without the old value of a VGPR it only +// writes (pub(crate)). +std::vector<Reg> operand_reads(const Program& p, const Inst& inst); + +std::vector<std::size_t> reverse_postorder(std::span<const Block> blocks); + +// An edge to an earlier block in reverse postorder whose target does not dominate its source, if +// any: there the control flow is irreducible. `index` is each block's position in `order`. +std::optional<std::pair<std::size_t, std::size_t>> irreducible_edge(std::span<const Block> blocks, + std::span<const std::size_t> order, + std::span<const std::size_t> index); + +// Each block's immediate dominator (the entry's is itself, unreachable blocks' SIZE_MAX); `order` is +// reverse postorder, `index` each block's position in it. +std::vector<std::size_t> idoms(std::span<const Block> blocks, std::span<const std::size_t> order, + std::span<const std::size_t> index); + +// Internal SSA helpers exposed to unit tests. +namespace detail { + +// Placeholder before renaming. +inline constexpr Value NONE = {0xFFFF'FFFFu}; + +// Registers read, registers written. +using Effects = std::pair<std::vector<Reg>, std::vector<Reg>>; + +// Registers an instruction reads and writes, one per dword, or nullopt if the IR drops it. +std::optional<Effects> effects(const gfx10::Instruction& inst, const gfx10::Fields& fields, + std::string_view name, std::uint8_t lanes, std::uint16_t vgprs); + +// Recomputes every block's predecessors from the exits. +void link(std::vector<Block>& blocks); +void split_irreducible(std::vector<Block>& blocks); +Program rename(std::vector<Block> blocks, bool wave64, std::uint16_t vgprs); +// Returns the union-find steps taken (a test bounds them). +std::size_t remove_trivial_phis_steps(std::vector<Block>& blocks, std::uint32_t values); + +} // namespace detail + +} // namespace x2w::vs::ir + +// Hashes for Reg and Value. Use ordered maps and sets where iteration order affects output. +template <> +struct std::hash<x2w::vs::ir::Reg> { + std::size_t operator()(const x2w::vs::ir::Reg& r) const noexcept { + return std::hash<unsigned>{}(unsigned(r.kind) << 8 | r.n); + } +}; +template <> +struct std::hash<x2w::vs::ir::Value> { + std::size_t operator()(const x2w::vs::ir::Value& v) const noexcept { return std::hash<std::uint32_t>{}(v.n); } +}; diff --git a/src/x2w_shader/lib.cpp b/src/x2w_shader/lib.cpp new file mode 100644 index 0000000000..42c0a5b19b --- /dev/null +++ b/src/x2w_shader/lib.cpp @@ -0,0 +1,99 @@ +// Shader error formatting. +#include "x2w_shader/lib.h" + +#include <cstdio> +#include <cstring> + +namespace x2w::vs { + +std::string hex_alt(std::uint64_t v) { + char buf[24]; + std::snprintf(buf, sizeof buf, "0x%llx", static_cast<unsigned long long>(v)); + return buf; +} + +ShaderError ShaderError::not_dxbc() { + ShaderError e; + e.kind = Kind::NotDxbc; + e.fill(); + return e; +} + +ShaderError ShaderError::malformed(const char* why) { + ShaderError e; + e.kind = Kind::Malformed; + e.reason = why; + e.fill(); + return e; +} + +ShaderError ShaderError::isa(std::size_t offset, const char* reason) { + ShaderError e; + e.kind = Kind::Isa; + e.offset = offset; + e.reason = reason; + e.fill(); + return e; +} + +ShaderError ShaderError::unsupported(std::size_t offset, const char* what) { + ShaderError e; + e.kind = Kind::Unsupported; + e.offset = offset; + e.reason = what; + e.fill(); + return e; +} + +void ShaderError::fill() { + switch (kind) { + case Kind::NotDxbc: + text_ = "not a DXBC container"; + break; + case Kind::Malformed: + text_ = std::string("malformed shader: ") + reason; + break; + case Kind::Isa: + text_ = "GFX10 code at " + hex_alt(offset) + ": " + reason; + break; + case Kind::Unsupported: + text_ = "GFX10 code at " + hex_alt(offset) + ": " + reason + " is not supported"; + break; + } +} + +std::string ShaderError::to_string() const { return text_; } + +namespace { +// Format diagnostic strings as quoted, with `"` and `\` escaped (the static texts hold nothing else). +std::string quoted(const char* s) { + std::string out = "\""; + for (; *s; ++s) { + if (*s == '"' || *s == '\\') out += '\\'; + out += *s; + } + return out + "\""; +} +} // namespace + +std::string ShaderError::debug() const { + switch (kind) { + case Kind::NotDxbc: + return "NotDxbc"; + case Kind::Malformed: + return "Malformed(" + quoted(reason) + ")"; + case Kind::Isa: + return "Isa { offset: " + std::to_string(offset) + ", reason: " + quoted(reason) + " }"; + case Kind::Unsupported: + return "Unsupported { offset: " + std::to_string(offset) + ", what: " + quoted(reason) + " }"; + } + return {}; +} + +const char* ShaderError::what() const noexcept { return text_.c_str(); } + +bool ShaderError::operator==(const ShaderError& o) const { + return kind == o.kind && offset == o.offset && std::strcmp(reason, o.reason) == 0; +} + +} // namespace x2w::vs diff --git a/src/x2w_shader/lib.h b/src/x2w_shader/lib.h new file mode 100644 index 0000000000..c28be70292 --- /dev/null +++ b/src/x2w_shader/lib.h @@ -0,0 +1,38 @@ +// Xbox Series shaders to host shaders. +// +// An Xbox Series shader is a standard DXBC container (dxbc.h). Its `DXIL` part (dxil.h) may carry +// Xbox additions around the LLVM bitcode: an `XDAT` table before it indexing blobs after it, among +// them `xbop` (compiler options) and the zlib-compressed GFX10 code. The bitcode may use console-only +// intrinsics, so the GFX10 code is translated in general. +// +// Translation failures throw ShaderError. Use catch_shader_error or try_shader to capture a refusal. +#pragma once + +#include "x2w_shader/error.h" + +// Public container, program and hardware stage types from the module headers, including native.h. +#include "x2w_shader/dxbc.h" +#include "x2w_shader/dxil.h" + +namespace x2w::vs { +using dxbc::Container; +using dxbc::FourCC; +using dxbc::Part; +using dxil::DxilProgram; +using dxil::ShaderKind; +using dxil::XboxExtras; +} // namespace x2w::vs + +#if __has_include("x2w_shader/native.h") +#include "x2w_shader/native.h" + +namespace x2w::vs { +using native::HwStage; +using native::native_programs; +using native::NativeProgram; +using native::ResourceType; +using native::RootParam; +using native::RootType; +using native::UsedResource; +} // namespace x2w::vs +#endif diff --git a/src/x2w_shader/native.cpp b/src/x2w_shader/native.cpp new file mode 100644 index 0000000000..3cd6fa2df1 --- /dev/null +++ b/src/x2w_shader/native.cpp @@ -0,0 +1,519 @@ +// Read native program layouts documented in native.h. +#include "x2w_shader/native.h" + +#include <algorithm> +#include <cstring> +#include <limits> + +#include "startup_stubs/inflate.h" +#include "x2w_shader/dxbc.h" + +namespace x2w::vs::native { + +namespace { + +using Bytes = std::span<const std::uint8_t>; +using dxbc::u32_at; +using dxbc::u64_at; + +constexpr std::size_t XDAT_OFFSET = 0x18; +constexpr std::size_t MAX_XDAT_ENTRIES = 64; +constexpr std::uint32_t KIND_NATIVE = 0x0d; +constexpr std::uint32_t XBCH_VERSION = 3; +constexpr std::size_t XBCH_HEADER = 0x18; +constexpr std::uint32_t FSSM_VERSION = 0x101; +constexpr std::size_t FSSM_HEADER = 0x10; +constexpr std::uint64_t GRAPHICS_SLOT_COUNT = 6; +// Where each stage's record offset sits in the FSSM payload. +constexpr std::pair<HwStage, std::size_t> SLOTS[8] = { + {HwStage::Ls, 0x08}, {HwStage::Hs, 0x10}, {HwStage::Es, 0x18}, {HwStage::Gs, 0x20}, + {HwStage::Vs, 0x28}, {HwStage::Ps, 0x30}, {HwStage::Ms, 0x48}, {HwStage::Cs, 0x60}, +}; +constexpr std::uint64_t ABSENT = 0xDEAD'BEEF'DEAD'BEEFull; +constexpr std::uint64_t RECORD_SIZE = 0x54; +constexpr std::size_t RECORD_FLAGS = 0x14; +constexpr std::uint32_t FLAG_WAVE32 = 1u << 5; +constexpr std::size_t RECORD_REGS = 0x50; +constexpr std::size_t RECORD_LAYOUT = 0x28; +constexpr std::size_t RECORD_USED = 0x30; +constexpr std::size_t RECORD_COUNTS = 0x38; +constexpr std::uint64_t ENTRY_SIZE = 20; +constexpr std::uint32_t MAX_SEMANTICS = 32; +constexpr std::size_t PS_INPUTS = 0x24; +constexpr std::size_t PS_INPUT_COUNT = 0x124; +constexpr std::size_t PS_INPUT_ADDR = 0x134; +constexpr std::size_t PS_DB_SHADER_CONTROL = 0x138; +constexpr std::size_t PS_PATCH_SIZE = 0x148; +constexpr std::size_t PS_PATCHES = 0x14c; +constexpr std::size_t PATCH_SLOT_DWORDS = 10; +// The variant that exports every channel as a raw 32-bit value. +constexpr std::size_t PATCH_FULL = 9; +constexpr std::size_t PATCH_BYTES = 4 + 10 * PATCH_SLOT_DWORDS * 4; +constexpr std::size_t MRTS = 8; +constexpr std::size_t VS_INPUTS = 0x24; +constexpr std::size_t VS_INPUT_COUNT = 0xc4; +constexpr std::size_t VS_OUTPUTS = 0xc8; +constexpr std::size_t VS_OUTPUT_COUNT = 0x188; +constexpr std::size_t CS_RSRC2 = 0x24; +constexpr std::size_t CS_THREADS = 0x28; +constexpr std::size_t RECORD_LDS = 0x4c; +constexpr std::size_t MS_CLIP_CNTL = 0x194; +constexpr std::size_t MS_INFO = 0x448; +constexpr std::uint32_t FSPX_VERSION = 1; +constexpr std::size_t FSPX_HEADER = 0x10; +constexpr std::uint32_t FSPX_PACKET = 0; +constexpr std::uint32_t FSPX_CODE = 6; +constexpr std::uint32_t FSPX_METADATA = 7; +constexpr std::size_t PACKET_THREADS = 0x0c; +constexpr std::size_t PACKET_FLAGS = 0x12; +constexpr std::uint16_t PACKET_WAVE32 = 1u << 4; +constexpr std::size_t PACKET_RSRC1 = 0x14; +constexpr std::size_t PACKET_RSRC2 = 0x18; +constexpr std::size_t FSPX_RECORDS = 0x18; +constexpr std::size_t FSPX_RECORD = 32; +// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes. +constexpr std::uint64_t MAX_UNPACKED = 16ull << 20; + +bool starts_with(Bytes data, const char (&magic)[5]) +{ + return data.size() >= 4 && std::memcmp(data.data(), magic, 4) == 0; +} + +// `data.get(at..at + 4) == Some(magic)`. +bool magic_at(Bytes data, std::size_t at, const char (&magic)[5]) +{ + return at <= data.size() && data.size() - at >= 4 && std::memcmp(data.data() + at, magic, 4) == 0; +} + +// For entries already sized by `as_chunks`. +std::uint32_t le32(const std::uint8_t* entry, std::size_t at) +{ + return std::uint32_t{entry[at]} | (std::uint32_t{entry[at + 1]} << 8) | (std::uint32_t{entry[at + 2]} << 16) | + (std::uint32_t{entry[at + 3]} << 24); +} + +// `data[offset..offset + len]` with untrusted 64-bit bounds. +std::optional<Bytes> bytes(Bytes data, std::uint64_t offset, std::uint64_t len) +{ + if (offset > std::numeric_limits<std::size_t>::max() || len > std::numeric_limits<std::size_t>::max()) + return std::nullopt; + const auto start = static_cast<std::size_t>(offset); + const auto n = static_cast<std::size_t>(len); + if (n > std::numeric_limits<std::size_t>::max() - start) return std::nullopt; + if (start + n > data.size()) return std::nullopt; + return data.subspan(start, n); +} + +Bytes need(std::optional<Bytes> b, const char* why) +{ + if (!b) throw ShaderError::malformed(why); + return *b; +} + +std::uint16_t fspx_u16_at(Bytes data, std::size_t at) +{ + if (at > data.size() || data.size() - at < 2) throw ShaderError::malformed("FSPX data out of bounds"); + return static_cast<std::uint16_t>(data[at] | (data[at + 1] << 8)); +} + +ResourceType resource_type(std::uint8_t raw) +{ + switch (raw) { + case 0: return ResourceType::Srv(); + case 1: return ResourceType::Sampler(); + case 2: return ResourceType::Cbv(); + case 3: return ResourceType::Uav(); + default: return ResourceType::Other(raw); + } +} + +// Inflates a zlib stream to exactly `expected` bytes, rejecting truncated, corrupt, under-filled or +// oversized streams. Bytes after the stream's end are ignored, as zlib does. +std::optional<std::vector<std::uint8_t>> inflate_zlib_exact(Bytes source, std::size_t expected) +{ + // zlib's window is at most 32 KiB (CINFO 7); zlib-rs with 15 window bits refuses larger ones. + if (source.size() >= 1 && (source[0] >> 4) > 7) return std::nullopt; + std::vector<std::uint8_t> out(expected); + std::size_t produced = 0; + const auto status = + x2w_inflate::inflate_zlib_ex(source.data(), source.size(), out.data(), out.size(), produced); + if (status != x2w_inflate::InflateStatus::ok || produced != expected) return std::nullopt; + return out; +} + +std::vector<std::uint8_t> unpack_blob(Bytes blob) +{ + if (!starts_with(blob, "XBCH")) throw ShaderError::malformed("native blob lacks XBCH magic"); + if (u32_at(blob, 4) != XBCH_VERSION) throw ShaderError::malformed("unknown XBCH version"); + const std::uint64_t packed = u64_at(blob, 8); + const std::uint64_t unpacked = u64_at(blob, 16); + if (unpacked > MAX_UNPACKED) throw ShaderError::malformed("implausible XBCH unpacked size"); + const Bytes stream = need(bytes(blob, XBCH_HEADER, packed), "XBCH stream out of bounds"); + auto out = inflate_zlib_exact(stream, static_cast<std::size_t>(unpacked)); + if (!out) throw ShaderError::malformed("XBCH stream does not inflate to its stated size"); + return std::move(*out); +} + +// The entries of `size` bytes from `at`, with their count at `count_at`. +Bytes semantics(Bytes data, std::size_t at, std::size_t size, std::size_t count_at) +{ + const std::uint32_t count = u32_at(data, count_at); + if (count > MAX_SEMANTICS) throw ShaderError::malformed("implausible semantic count"); + const std::size_t len = size * count; + if (at > data.size() || data.size() - at < len) throw ShaderError::malformed("stage data out of bounds"); + return data.subspan(at, len); +} + +StageIo ps_io(Bytes data, std::size_t code_len) +{ + PsIo io; + const Bytes in = semantics(data, PS_INPUTS, 8, PS_INPUT_COUNT); + for (std::size_t k = 0; k + 8 <= in.size(); k += 8) { + const std::uint8_t* e = in.data() + k; + PsInput i; + i.usage = Usage::from_raw(e[0]); + i.row = e[1]; + i.mask = e[2] & 0xf; + i.attr = e[3]; + i.flat = (e[7] & 1) != 0; + i.fp16 = (e[7] & 8) != 0; + i.pack2 = (e[7] & 0x10) != 0; + i.row2 = e[5]; + io.inputs.push_back(i); + } + const std::size_t size = u32_at(data, PS_PATCH_SIZE); + if (size > PATCH_SLOT_DWORDS) throw ShaderError::malformed("implausible export patch size"); + for (std::size_t mrt = 0; mrt < MRTS; ++mrt) { + const std::size_t at = PS_PATCHES + mrt * PATCH_BYTES; + const std::uint32_t offset = u32_at(data, at); + if (offset == std::numeric_limits<std::uint32_t>::max()) continue; + if ((std::size_t{offset} + size) * 4 > code_len) throw ShaderError::malformed("export patch outside the code"); + const std::size_t full = at + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4; + ExportPatch patch; + patch.mrt = static_cast<std::uint8_t>(mrt); + patch.offset = offset; + for (std::size_t i = 0; i < size; ++i) patch.code.push_back(u32_at(data, full + 4 * i)); + io.patches.push_back(std::move(patch)); + } + io.input_addr = u32_at(data, PS_INPUT_ADDR); + io.db_shader_control = u32_at(data, PS_DB_SHADER_CONTROL); + return io; +} + +std::vector<VsOutput> vs_outputs(Bytes data) +{ + std::vector<VsOutput> out; + const Bytes s = semantics(data, VS_OUTPUTS, 6, VS_OUTPUT_COUNT); + for (std::size_t k = 0; k + 6 <= s.size(); k += 6) { + const std::uint8_t* e = s.data() + k; + VsOutput o; + o.usage = Usage::from_raw(e[0]); + o.row = e[1]; + o.param = e[2]; + o.fp16 = (e[5] & 1) != 0; + o.pack2 = (e[5] & 2) != 0; + out.push_back(o); + } + return out; +} + +StageIo vs_io(Bytes data) +{ + VsIo io; + const Bytes s = semantics(data, VS_INPUTS, 5, VS_INPUT_COUNT); + for (std::size_t k = 0; k + 5 <= s.size(); k += 5) { + const std::uint8_t* e = s.data() + k; + VsInput i; + i.usage = Usage::from_raw(e[0]); + i.row = e[1]; + i.mask = e[2] & 0xf; + i.vgpr = e[3]; + io.inputs.push_back(i); + } + io.outputs = vs_outputs(data); + return io; +} + +StageIo ms_io(Bytes data, std::uint32_t lds_bytes) +{ + MeshIo io; + io.outputs = vs_outputs(data); + if (data.size() < MS_INFO + 8) throw ShaderError::malformed("stage data out of bounds"); + const std::uint8_t* info = data.data() + MS_INFO; + auto half = [&](std::size_t at) { return std::uint32_t{static_cast<std::uint16_t>(info[at] | (info[at + 1] << 8))}; }; + io.clip_cntl = u32_at(data, MS_CLIP_CNTL); + io.threads = half(0); + io.max_vertices = half(2); + io.max_primitives = half(4); + io.topology = info[7]; + io.lds_bytes = lds_bytes; + return io; +} + +std::vector<NativeProgram> programs(Bytes fssm) +{ + if (!starts_with(fssm, "FSSM")) throw ShaderError::malformed("native blob lacks FSSM magic"); + if (u32_at(fssm, 4) != FSSM_VERSION) throw ShaderError::malformed("unknown FSSM version"); + const Bytes payload = fssm.subspan(std::min(FSSM_HEADER, fssm.size())); + if (u64_at(fssm, 8) != payload.size()) throw ShaderError::malformed("FSSM payload size disagrees"); + if (u64_at(payload, 0) != GRAPHICS_SLOT_COUNT) throw ShaderError::malformed("unexpected FSSM slot count"); + std::vector<NativeProgram> out; + for (const auto& [stage, at] : SLOTS) { + const std::uint64_t start = u64_at(payload, at); + if (start == ABSENT) continue; + const Bytes record = need(bytes(payload, start, RECORD_SIZE), "FSSM record out of bounds"); + const std::uint64_t code_at = u64_at(record, 0); + const std::uint64_t code_size = u64_at(record, 8); + const Bytes code = need(bytes(payload, code_at, code_size), "native code out of bounds"); + const auto vgprs = static_cast<std::uint16_t>(u32_at(record, RECORD_REGS) & 0x3FF); + if (vgprs > 256) throw ShaderError::malformed("implausible VGPR count"); + auto table = [&](std::size_t table_at, std::size_t count_at) -> Bytes { + const std::uint64_t len = ENTRY_SIZE * std::uint64_t{u32_at(record, count_at)}; + if (len == 0) return {}; + const std::uint64_t offset = u64_at(record, table_at); + return need(bytes(payload, offset, len), "FSSM root table out of bounds"); + }; + NativeProgram p; + p.stage = stage; + const Bytes layout = table(RECORD_LAYOUT, RECORD_COUNTS); + for (std::size_t k = 0; k + ENTRY_SIZE <= layout.size(); k += ENTRY_SIZE) { + const std::uint8_t* e = layout.data() + k; + RootParam r; + r.root = RootType::from_raw(le32(e, 0)); + r.table_offset_dwords = le32(e, 4); + r.sgprs = le32(e, 8); + r.base_register = le32(e, 12); + r.user_data = e[16]; + r.slot = e[17]; + p.layout.push_back(r); + } + const Bytes used = table(RECORD_USED, RECORD_COUNTS + 4); + for (std::size_t k = 0; k + ENTRY_SIZE <= used.size(); k += ENTRY_SIZE) { + const std::uint8_t* e = used.data() + k; + UsedResource u; + u.kind = resource_type(e[0]); + u.root = RootType::from_raw(e[1]); + u.table_offset_dwords = le32(e, 4); + u.lower_bound = le32(e, 8); + u.stride = le32(e, 12); + u.dwords = e[16]; + u.user_data = e[17]; + u.slot = e[18]; + p.used.push_back(u); + } + // The record is in bounds, so its end is too. + const Bytes stage_data = payload.subspan(static_cast<std::size_t>(start + RECORD_SIZE)); + switch (stage) { + case HwStage::Ps: p.io = ps_io(stage_data, code.size()); break; + case HwStage::Vs: p.io = vs_io(stage_data); break; + case HwStage::Cs: { + ComputeIo cs; + cs.rsrc2 = u32_at(stage_data, CS_RSRC2); + cs.threads[0] = u32_at(stage_data, CS_THREADS); + cs.threads[1] = u32_at(stage_data, CS_THREADS + 4); + cs.threads[2] = u32_at(stage_data, CS_THREADS + 8); + p.io = cs; + break; + } + case HwStage::Ms: p.io = ms_io(stage_data, u32_at(record, RECORD_LDS)); break; + default: p.io = std::monostate{}; break; + } + p.wave64 = (u32_at(record, RECORD_FLAGS) & FLAG_WAVE32) == 0; + p.vgprs = vgprs; + p.code.assign(code.begin(), code.end()); + out.push_back(std::move(p)); + } + return out; +} + +} // namespace + +std::uint8_t user_sgpr(HwStage stage, std::uint8_t index) +{ + switch (stage) { + case HwStage::Ls: + case HwStage::Hs: + case HwStage::Es: + case HwStage::Gs: + case HwStage::Ms: return static_cast<std::uint8_t>(index + 8); + default: return index; + } +} + +Usage Usage::from_raw(std::uint8_t raw) +{ + switch (raw) { + case 6: return Generic(); + case 7: return ClipDistance(); + default: return Other(raw); + } +} + +RootType RootType::from_raw(std::uint32_t raw) +{ + switch (raw) { + case 0: return Constants(); + case 1: return Descriptor(); + case 3: return Table(); + case 4: return ImmediateSampler(); + case 5: return ResourceHeap(); + case 6: return SamplerHeap(); + default: return Other(raw); + } +} + +ResourceType ResourceType::from_raw(std::uint8_t raw) { return resource_type(raw); } + +std::uint8_t ComputeIo::user_sgprs() const { return static_cast<std::uint8_t>((rsrc2 >> 1) & 0x1F); } + +std::pair<std::array<std::optional<std::uint8_t>, 3>, std::optional<std::uint8_t>> ComputeIo::system_sgprs() const +{ + std::uint8_t next = user_sgprs(); + auto take = [&](unsigned bit) -> std::optional<std::uint8_t> { + if (((rsrc2 >> bit) & 1) == 0) return std::nullopt; + next = static_cast<std::uint8_t>(next + 1); + return static_cast<std::uint8_t>(next - 1); + }; + std::array<std::optional<std::uint8_t>, 3> ids; + ids[0] = take(7); + ids[1] = take(8); + ids[2] = take(9); + const auto info = take(10); + return {ids, info}; +} + +std::uint8_t ComputeIo::initialized_sgprs() const +{ + const auto [ids, info] = system_sgprs(); + std::optional<std::uint8_t> end; + for (const auto& s : {ids[0], ids[1], ids[2], info}) { + if (!s) continue; + const auto e = static_cast<std::uint8_t>(*s + 1); + if (!end || e > *end) end = e; + } + return static_cast<std::uint8_t>(std::max(end.value_or(0), user_sgprs()) + (rsrc2 & 1)); +} + +std::uint8_t ComputeIo::thread_id_vgprs() const { return static_cast<std::uint8_t>(((rsrc2 >> 11) & 3) + 1); } + +std::uint32_t ComputeIo::lds_bytes() const { return ((rsrc2 >> 15) & 0x1FF) * 512; } + +std::vector<std::uint8_t> NativeProgram::patched_code() const +{ + std::vector<std::uint8_t> out = code; + if (const auto* ps = std::get_if<PsIo>(&io)) { + for (const ExportPatch& p : ps->patches) { + const std::size_t at = std::size_t{p.offset} * 4; + for (std::size_t i = 0; i < p.code.size(); ++i) { + const std::uint32_t word = p.code[i]; + // ps_io validates that each patch falls within the code. + out.at(at + 4 * i + 0) = static_cast<std::uint8_t>(word); + out.at(at + 4 * i + 1) = static_cast<std::uint8_t>(word >> 8); + out.at(at + 4 * i + 2) = static_cast<std::uint8_t>(word >> 16); + out.at(at + 4 * i + 3) = static_cast<std::uint8_t>(word >> 24); + } + } + } + return out; +} + +std::vector<NativeProgram> native_programs(std::span<const std::uint8_t> part) +{ + if (starts_with(part, "FSPX")) return {fspx_program(part)}; + if (!magic_at(part, XDAT_OFFSET, "XDAT")) return {}; + const std::size_t count = u32_at(part, XDAT_OFFSET + 4); + if (count > MAX_XDAT_ENTRIES) throw ShaderError::malformed("implausible XDAT entry count"); + std::vector<NativeProgram> out; + for (std::size_t i = 0; i < count; ++i) { + const std::size_t at = XDAT_OFFSET + 12 + 12 * i; + if (u32_at(part, at) != KIND_NATIVE) continue; + const std::uint64_t offset = u32_at(part, at + 4); + const std::uint64_t size = u32_at(part, at + 8); + const Bytes blob = need(bytes(part, offset, size), "XDAT entry out of bounds"); + const std::vector<std::uint8_t> fssm = unpack_blob(blob); + for (NativeProgram& p : programs(fssm)) out.push_back(std::move(p)); + } + return out; +} + +NativeProgram fspx_program(std::span<const std::uint8_t> part) +{ + if (u32_at(part, 4) != FSPX_VERSION) throw ShaderError::malformed("unknown FSPX version"); + const std::size_t count = u32_at(part, 8); + if (count > MAX_XDAT_ENTRIES) throw ShaderError::malformed("implausible FSPX entry count"); + auto entry = [&](std::uint32_t kind) -> Bytes { + for (std::size_t i = 0; i < count; ++i) { + const std::size_t at = FSPX_HEADER + 16 * i; + if (u32_at(part, at) == kind) { + const std::uint32_t offset = u32_at(part, at + 4); + const std::uint32_t size = u32_at(part, at + 8); + return need(bytes(part, offset, size), "FSPX entry out of bounds"); + } + } + throw ShaderError::malformed("FSPX entry missing"); + }; + const Bytes packet = entry(FSPX_PACKET); + const Bytes code = entry(FSPX_CODE); + const Bytes meta = entry(FSPX_METADATA); + if (std::size_t{u32_at(meta, 8)} * 4 != code.size()) throw ShaderError::malformed("FSPX code size disagrees"); + const bool wave64 = (fspx_u16_at(packet, PACKET_FLAGS) & PACKET_WAVE32) == 0; + // VGPRs in granules of 4 (wave64) or 8 (wave32). + const std::uint32_t granules = (u32_at(packet, PACKET_RSRC1) & 0x3F) + 1; + const auto vgprs = static_cast<std::uint16_t>(std::min<std::uint32_t>(granules * (wave64 ? 4 : 8), 256)); + NativeProgram p; + p.stage = HwStage::Cs; + p.wave64 = wave64; + p.vgprs = vgprs; + const Bytes records = meta.size() >= FSPX_RECORDS ? meta.subspan(FSPX_RECORDS) : Bytes{}; + for (std::size_t k = 0; k + FSPX_RECORD <= records.size(); k += FSPX_RECORD) { + const std::uint8_t* e = records.data() + k; + if (e[0] == 0x42) continue; + if (e[0] == 0x43) break; + if (e[0] != 0x41) throw ShaderError::malformed("unknown FSPX metadata record"); + const RootType root = RootType::from_raw(e[5]); + UsedResource u; + u.kind = resource_type(e[4]); + u.root = root; + u.table_offset_dwords = le32(e, 8); + u.lower_bound = le32(e, 12); + u.stride = 0; + u.dwords = e[20]; + u.user_data = e[21]; + u.slot = e[22]; + std::uint32_t sgprs; + switch (root.kind) { + case RootType::Kind::Table: sgprs = 1; break; + case RootType::Kind::Descriptor: sgprs = 2; break; + // The code holds its words; no user data. + case RootType::Kind::ImmediateSampler: sgprs = 0; break; + default: throw ShaderError::malformed("an FSPX resource of an unknown root type"); + } + const bool listed = + std::any_of(p.layout.begin(), p.layout.end(), [&](const RootParam& r) { return r.slot == u.slot; }); + if (sgprs > 0 && !listed) { + RootParam r; + r.root = root; + r.table_offset_dwords = 0; + r.sgprs = sgprs; + r.base_register = u.lower_bound; + r.user_data = u.user_data; + r.slot = u.slot; + p.layout.push_back(r); + } + p.used.push_back(u); + } + ComputeIo cs; + cs.rsrc2 = u32_at(packet, PACKET_RSRC2); + cs.threads[0] = fspx_u16_at(packet, PACKET_THREADS); + cs.threads[1] = fspx_u16_at(packet, PACKET_THREADS + 2); + cs.threads[2] = fspx_u16_at(packet, PACKET_THREADS + 4); + p.io = cs; + p.code.assign(code.begin(), code.end()); + return p; +} + +namespace detail { +std::vector<std::uint8_t> unpack(std::span<const std::uint8_t> blob) { return unpack_blob(blob); } +} // namespace detail + +} // namespace x2w::vs::native diff --git a/src/x2w_shader/native.h b/src/x2w_shader/native.h new file mode 100644 index 0000000000..6075d53c25 --- /dev/null +++ b/src/x2w_shader/native.h @@ -0,0 +1,324 @@ +// Native GFX10 programs that the console compiler stores in a `DXIL` part. +// +// An `XDAT` index after the program header lists blobs stored around the bitcode; one or more of +// them hold native programs, zlib-packed (a vertex shader can carry two: compiled for use with and +// without a geometry shader). Layout as observed (index offsets are relative to the part data): +// +// +0x18 "XDAT" u32 entry count, u32 (0x24 seen), then per entry: u32 kind, u32 offset, u32 size +// kind 0x0d "XBCH" u32 version (3), u64 packed size, u64 unpacked size, zlib stream +// unpacked "FSSM" u32 version (0x101), u64 payload size, payload +// payload +0x00 u64 graphics slot count (6) +// +0x08 u64 record offsets: LS HS ES GS VS PS (0x08..0x30), mesh 0x48, compute 0x60; +// unused ones are 0xDEADBEEF_DEADBEEF +// record +0x00 u64 code offset, +0x08 u64 code size (payload-relative), +// +0x14 u32 flags: bit 5 wave32 (else wave64) +// +0x28 u64 root layout table, +0x30 u64 used-resource table (payload-relative), +// +0x38 u32 and +0x3c u32 their counts +// +0x50 u32 bits 0-9 VGPRs used, bits 20-27 SGPRs used +// layout 20 B: u32 root type, u32 table offset (dwords), u32 user SGPRs, u32 base register, +// u8 first user-data dword, u8 root slot, u16 0 +// used 20 B: u8 resource type, u8 root type, u16 0, u32 table offset (dwords), u32 lower +// bound, u32 stride, u8 descriptor dwords, u8 first user-data dword, u8 root slot, +// u8 0 +// +// Stage data follows the record; offsets from its end (E = record + 0x54): +// +// PS E+0x24 32 inputs of 8 B: u8 usage, u8 signature row, u8 channel mask, u8 attribute +// (v_interp `attr`), u8 default, u8 second row (of a packed pair), u8 parameter slot, +// u8 flags (bit 0 flat, 1 linear, 3 fp16, 4 fp16 packed); E+0x124 u32 count +// E+0x134 u32 SPI_PS_INPUT_ADDR, E+0x138 u32 DB_SHADER_CONTROL +// E+0x148 u32 export patch size (dwords), E+0x14c 8 patches, one per MRT: u32 code offset +// (dwords, -1 none), then the export code for each color format in 10 slots of 10 +// dwords (ZERO, 32_R, 32_GR, 32_AR, FP16, UNORM16, SNORM16, UINT16, SINT16, 32_ABGR) +// VS E+0x24 32 inputs of 5 B: u8 usage, u8 row, u8 channel mask, u8 VGPR of channel 0 (channel +// k in VGPR + k), u8 highest channel; E+0xc4 u32 count +// E+0xc8 32 outputs of 6 B: u8 usage, u8 row, u8 parameter (`exp param<n>`), u8 row again, +// u8 slot, u8 flags (bit 0 fp16, bit 1 two fp16 values per dword); E+0x188 u32 count +// CS E+0x24 u32 COMPUTE_PGM_RSRC2, E+0x28 u32 x3 thread-group size +// MS E+0xc8 outputs as VS, E+0x188 count; the param byte's bit 7 marks a per-primitive output +// (`PSG1` row) +// E+0x18c u32 SPI_VS_OUT_CONFIG, SPI_SHADER_POS_FORMAT, PA_CL_VS_OUT_CNTL, ... +// E+0x448 u16 thread-group size in lanes, u16 maximum vertices, u16 maximum primitives, +// u8 user SGPRs, u8 output topology (2 triangles) +// record +0x4c u32 LDS bytes (mesh programs read it here) +// +// Rows are registers of the container's signature parts (`ISG1`, `OSG1`). Merged stages keep their +// stage data in another layout (not read). Unknown versions are rejected so a format change shows +// up as an error. +#pragma once + +#include <array> +#include <cstddef> +#include <cstdint> +#include <optional> +#include <span> +#include <utility> +#include <variant> +#include <vector> + +#include "x2w_shader/error.h" + +namespace x2w::vs::native { + +// Hardware shader stage a native program runs as. +enum class HwStage : std::uint8_t { + Ls, + Hs, + Es, + Gs, + Vs, + Ps, + // Mesh shader. + Ms, + Cs, +}; + +// The SGPR holding user-data dword `index`: merged stages (and mesh shaders, which run as one) have +// 8 system SGPRs first. +std::uint8_t user_sgpr(HwStage stage, std::uint8_t index); + +// Semantic usage from stage data. Only Other carries a numeric code. +struct Usage { + enum class Kind : std::uint8_t { Generic, ClipDistance, Other }; + Kind kind = Kind::Generic; + std::uint8_t other = 0; + + static constexpr Usage Generic() { return {Kind::Generic, 0}; } + static constexpr Usage ClipDistance() { return {Kind::ClipDistance, 0}; } + static constexpr Usage Other(std::uint8_t n) { return {Kind::Other, n}; } + static Usage from_raw(std::uint8_t raw); + bool operator==(const Usage&) const = default; +}; + +// A pixel shader input: what `v_interp` of attribute `attr` reads. +struct PsInput { + Usage usage; + // Register in the input signature. + std::uint8_t row = 0; + std::uint8_t mask = 0; + std::uint8_t attr = 0; + bool flat = false; + bool fp16 = false; + // Two 16-bit values per dword (VsOutput::pack2); `row2` is the second element's register. + bool pack2 = false; + std::uint8_t row2 = 0; + bool operator==(const PsInput&) const = default; +}; + +// A vertex attribute the fetch shader loads: channel k into VGPR `vgpr + k`. +struct VsInput { + Usage usage; + std::uint8_t row = 0; + std::uint8_t mask = 0; + std::uint8_t vgpr = 0; + bool operator==(const VsInput&) const = default; +}; + +// What `exp param<param>` of a vertex shader writes. +struct VsOutput { + Usage usage; + // Register in the output signature. + std::uint8_t row = 0; + std::uint8_t param = 0; + // 16-bit values, one per dword (low half) unless `pack2`: then two per dword, channel c of this + // row in dword c / 2 (odd channels in the high half), then a second 16-bit row from the next + // whole dword (the next 16-bit row of the signature no entry names). + bool fp16 = false; + bool pack2 = false; + bool operator==(const VsOutput&) const = default; +}; + +// The export code of one render target for its full 32-bit format. +struct ExportPatch { + std::uint8_t mrt = 0; + // Where it goes in the code, in dwords. + std::uint32_t offset = 0; + std::vector<std::uint32_t> code; + bool operator==(const ExportPatch&) const = default; +}; + +// StageIo::Vs. +struct VsIo { + std::vector<VsInput> inputs; + std::vector<VsOutput> outputs; + bool operator==(const VsIo&) const = default; +}; + +// StageIo::Ps. +struct PsIo { + std::vector<PsInput> inputs; + // `SPI_PS_INPUT_ADDR`: which system values arrive in VGPRs. + std::uint32_t input_addr = 0; + // `DB_SHADER_CONTROL`: depth export, kill. + std::uint32_t db_shader_control = 0; + std::vector<ExportPatch> patches; + bool operator==(const PsIo&) const = default; +}; + +// A mesh program's outputs and limits (StageIo::Ms). It runs as one hardware NGG stage: lane n of +// the group (`threads` lanes) exports vertex n (`exp pos`, `exp param`) and primitive n +// (`exp prim`). +struct MeshIo { + // `exp param<n>` targets; `param` bit 7 set: a per-primitive output, `row` then a row of the + // primitive signature (`PSG1`). + std::vector<VsOutput> outputs; + // `PA_CL_VS_OUT_CNTL`: which clip and cull distances `pos1+` carry. + std::uint32_t clip_cntl = 0; + // Thread-group size in lanes (the HLSL group rounded up to waves). + std::uint32_t threads = 0; + std::uint32_t max_vertices = 0; + std::uint32_t max_primitives = 0; + // 1 lines, 2 triangles. + std::uint8_t topology = 0; + std::uint32_t lds_bytes = 0; + bool operator==(const MeshIo&) const = default; +}; + +// A compute program's dispatch settings (StageIo::Cs). +struct ComputeIo { + // `COMPUTE_PGM_RSRC2`: user SGPRs, which system SGPRs and VGPRs follow them, LDS size. + std::uint32_t rsrc2 = 0; + // Thread-group size (`numthreads`). + std::array<std::uint32_t, 3> threads{}; + + // User SGPRs before the system ones. + std::uint8_t user_sgprs() const; + // The SGPR of each enabled thread-group id component, in order after the user SGPRs, then the + // thread-group info SGPR if enabled. + std::pair<std::array<std::optional<std::uint8_t>, 3>, std::optional<std::uint8_t>> system_sgprs() const; + // SGPRs the hardware initializes: the user SGPRs, the enabled system ones, then the scratch wave + // offset when scratch is enabled (bit 0). The ones above hold whatever the previous wave left. + std::uint8_t initialized_sgprs() const; + // Thread id components in v0, v1, v2 (1 to 3). + std::uint8_t thread_id_vgprs() const; + // LDS bytes per thread group (512-byte granules). + std::uint32_t lds_bytes() const; + bool operator==(const ComputeIo&) const = default; +}; + +// Input and output stage data. std::monostate denotes missing stage information. +using StageIo = std::variant<std::monostate, VsIo, PsIo, ComputeIo, MeshIo>; + +// Only Other carries an unrecognized numeric root type. +struct RootType { + enum class Kind : std::uint8_t { + Constants, + // A 64-bit buffer address. + Descriptor, + // The 32-bit heap address of a descriptor table range. + Table, + // A sampler the root signature fixes. + ImmediateSampler, + // The 32-bit address of the CBV/SRV/UAV heap (SM 6.6 dynamic resources). + ResourceHeap, + // The 32-bit address of the sampler heap. + SamplerHeap, + Other, + }; + Kind kind = Kind::Constants; + std::uint32_t other = 0; + + static constexpr RootType Constants() { return {Kind::Constants, 0}; } + static constexpr RootType Descriptor() { return {Kind::Descriptor, 0}; } + static constexpr RootType Table() { return {Kind::Table, 0}; } + static constexpr RootType ImmediateSampler() { return {Kind::ImmediateSampler, 0}; } + static constexpr RootType ResourceHeap() { return {Kind::ResourceHeap, 0}; } + static constexpr RootType SamplerHeap() { return {Kind::SamplerHeap, 0}; } + static constexpr RootType Other(std::uint32_t n) { return {Kind::Other, n}; } + static RootType from_raw(std::uint32_t raw); + bool operator==(const RootType&) const = default; +}; + +// One root parameter (or table range) and the user SGPRs holding it. +struct RootParam { + RootType root; + // Of the range within its table. + std::uint32_t table_offset_dwords = 0; + // User SGPRs from `user_data` on. + std::uint32_t sgprs = 0; + // Shader register of the first descriptor (`b`/`t`/`u`/`s` number). + std::uint32_t base_register = 0; + // First user-data dword (user_sgpr). + std::uint8_t user_data = 0; + // Index of the parameter in the root signature. + std::uint8_t slot = 0; + bool operator==(const RootParam&) const = default; +}; + +struct ResourceType { + enum class Kind : std::uint8_t { Srv, Sampler, Cbv, Uav, Other }; + Kind kind = Kind::Srv; + std::uint8_t other = 0; + + static constexpr ResourceType Srv() { return {Kind::Srv, 0}; } + static constexpr ResourceType Sampler() { return {Kind::Sampler, 0}; } + static constexpr ResourceType Cbv() { return {Kind::Cbv, 0}; } + static constexpr ResourceType Uav() { return {Kind::Uav, 0}; } + static constexpr ResourceType Other(std::uint8_t n) { return {Kind::Other, n}; } + static ResourceType from_raw(std::uint8_t raw); + bool operator==(const ResourceType&) const = default; +}; + +// A descriptor range the program reads. +struct UsedResource { + ResourceType kind; + RootType root; + std::uint32_t table_offset_dwords = 0; + // Shader register of the first descriptor read. + std::uint32_t lower_bound = 0; + std::uint32_t stride = 0; + // Size of the descriptor (4 or 8). + std::uint8_t dwords = 0; + std::uint8_t user_data = 0; + std::uint8_t slot = 0; + bool operator==(const UsedResource&) const = default; +}; + +struct NativeProgram { + HwStage stage = HwStage::Ls; + // Runs as 64 lanes per wave (else 32); sizes lane masks. + bool wave64 = false; + // VGPRs the program uses (v0 up to this), the bound of indexed access. + std::uint16_t vgprs = 0; + // Where the root signature's parameters arrive (user SGPRs). + std::vector<RootParam> layout; + // The descriptors the program reads, by root parameter. + std::vector<UsedResource> used; + StageIo io; + // GFX10 machine code, as stored. + std::vector<std::uint8_t> code; + + // The code with each render target's export patched for its full 32-bit format, so exports carry + // the shader's values unconverted (as the console does at pipeline creation for that format). + std::vector<std::uint8_t> patched_code() const; + bool operator==(const NativeProgram&) const = default; +}; + +// The native programs in a `DXIL` part's data, or in an `ACCC` part's (fspx_program); empty for the +// PC layout. Throws ShaderError::malformed. +std::vector<NativeProgram> native_programs(std::span<const std::uint8_t> part); + +// The compute program of an `ACCC` part, which a container carries in place of `DXIL` when another +// compiler made the native code (an upscaler's shaders). Layout as observed (offsets from "FSPX"): +// +// +0x00 "FSPX" u32 version (1), u32 entry count, u32 size; entries of 16 B from +0x10: u32 kind, +// u32 offset, u32 size, u32 0 +// kind 0 pipeline registers, 0x1c B: +0x0c u16 x3 thread-group size, +0x12 u16 flags (bit 4 +// wave32), +0x14 COMPUTE_PGM_RSRC1, +0x18 COMPUTE_PGM_RSRC2 +// kind 1 pipeline metadata (a hash); kind 6 the GFX10 code +// kind 7 program metadata: u32 0x403, u32 size - 0x14, u32 code dwords, u64 0, u8 0x40, u8 first +// user-data dword, u8 count of 0x41 records, u8 0; then 32-byte records from +0x18, each +// tagged by its first byte: +// 0x41 a resource the code reads: u8 resource type (as FSSM's used entries), u8 root type, u16 0, +// u32 table offset (dwords), u32 register, u32 view dimension, u8 descriptor dwords, u8 +// user-data dword, u8 root slot, u8 0, u32 -1, u32 0 +// 0x42 a view declaration +// 0x43 the shader hash (16 B); the last record +NativeProgram fspx_program(std::span<const std::uint8_t> part); + +namespace detail { +// Unpack the XBCH blob for tests. +std::vector<std::uint8_t> unpack(std::span<const std::uint8_t> blob); +} // namespace detail + +} // namespace x2w::vs::native diff --git a/src/x2w_shader/resource.cpp b/src/x2w_shader/resource.cpp new file mode 100644 index 0000000000..39b234d591 --- /dev/null +++ b/src/x2w_shader/resource.cpp @@ -0,0 +1,2164 @@ +// Resource tracking implementation. See resource.h. +// +// R<T> holds a value or a static error message. TRY propagates a failure and reasons are compared by +// content. +#include "x2w_shader/resource.h" + +#include <algorithm> +#include <bit> +#include <cstring> +#include <map> +#include <string_view> +#include <tuple> +#include <variant> + +#include "x2w_shader/bvh.h" + +namespace x2w::vs::resource { + +namespace { + +using detail::Term; +using gfx10::Operand; +using ir::Exit; +using ir::Inst; +using ir::Program; +using ir::Reg; +using ir::Value; +using native::HwStage; +using native::RootParam; +using native::RootType; +using structure::Bool; +using structure::LaneExit; +using structure::Meets; +using structure::Structured; + +// The reasons an address traces to no root parameter for which the address is then taken as it +// stands (MEMORY). +constexpr const char* RAW[5] = { + "an address not from a root parameter", + "an address from a root parameter that is no address", + "an address in an SGPR that is no root parameter", + "an address loaded from memory", + "an address from a phi", +}; + +constexpr std::size_t MAX_ROUNDS = 64; +constexpr std::size_t MAX_JOINS = 8; +// VGPR values followed for one dword of a descriptor kept per lane. +constexpr std::size_t MAX_COPIES = 64; + +struct Err { + const char* why; +}; + +template <class T> +struct R { + T value{}; + const char* err = nullptr; + R(T v) : value(std::move(v)) {} + R(Err e) : err(e.why) {} + bool ok() const { return err == nullptr; } +}; + +#define TRY(var, expr) \ + auto var##_r = (expr); \ + if (!var##_r.ok()) return Err{var##_r.err}; \ + auto var = std::move(var##_r.value) + +bool same_text(const char* a, const char* b) { return std::strcmp(a, b) == 0; } + +// A 32-bit sum: optional root parameter (as its first dword), constant, optional computed term. +struct Sum { + std::optional<Value> base; + std::uint32_t offset = 0; + std::optional<Value> dynamic; +}; + +// What lanes are known to satisfy: each Bool where its flag is set, its negation where not. +using Known = std::vector<std::pair<Bool, bool>>; + +struct Moved { + bool is_const = false; + std::uint32_t n = 0; + static Moved Const(std::uint32_t c) { return {true, c}; } + static Moved Of(Value v) { return {false, v.n}; } + bool operator==(const Moved&) const = default; +}; + +bool starts(std::string_view s, std::string_view p) { return s.starts_with(p); } + +bool plain_valu(const gfx10::Valu& f) { return f.abs == 0 && f.neg == 0 && !f.sdwa && !f.dpp; } + +// A lane select given as a constant. +std::optional<std::uint32_t> lane_of(const Operand& op) +{ + if (op.is_const()) return inline_constant(op.code); + if (op.is_literal()) return op.literal; + return std::nullopt; +} + +// What dword `k` of a move's result copies. +std::optional<Moved> copy_source(const Inst& inst, std::size_t k) +{ + const auto* f = std::get_if<gfx10::Sop>(&inst.fields); + if (!f) return std::nullopt; + const std::string_view name = inst.name(); + if (name == "s_movk_i32") { + if (!f->imm) return std::nullopt; + return Moved::Const(static_cast<std::uint32_t>(static_cast<std::int32_t>(static_cast<std::int16_t>(*f->imm)))); + } + // A mask of S0 bits from bit S1, as the upscaler's compiler makes an immediate sampler's word. + if (name == "s_bfm_b32" && k == 0 && f->src.size() == 2 && f->src[0].is_const() && f->src[1].is_const()) { + const auto w0 = inline_constant(f->src[0].code); + if (!w0) return std::nullopt; + const auto at0 = inline_constant(f->src[1].code); + if (!at0) return std::nullopt; + const std::uint32_t w = *w0 & 31, at = *at0 & 31; + return Moved::Const(((1u << w) - 1) << at); + } + if (f->src.empty()) return std::nullopt; + const Operand& src = f->src[0]; + const bool mov = name == "s_mov_b32" || name == "s_mov_b64"; + if (mov && src.is_scalar() && src.code != gfx10::NULL_CODE) { + const auto v = inst.read(Reg::S(static_cast<std::uint8_t>(src.code + k))); + if (!v) return std::nullopt; + return Moved::Of(*v); + } + if (mov && src.is_scalar()) return Moved::Const(0); + if (name == "s_mov_b32" && src.is_literal()) return Moved::Const(src.literal); + if (name == "s_mov_b32" && src.is_const()) { + const auto c = inline_constant(src.code); + if (!c) return std::nullopt; + return Moved::Const(*c); + } + // shortcut: only the one-operand ways the compiler makes a constant that has no inline form; + // fold more if descriptors need it. + if (name == "s_brev_b32" && src.is_const()) { + const auto c = inline_constant(src.code); + if (!c) return std::nullopt; + std::uint32_t x = *c, r = 0; + for (int i = 0; i < 32; ++i) r |= ((x >> i) & 1u) << (31 - i); + return Moved::Const(r); + } + if (name == "s_not_b32" && src.is_const()) { + const auto c = inline_constant(src.code); + if (!c) return std::nullopt; + return Moved::Const(~*c); + } + // shortcut: a literal below 2^31, whose high dword is 0 whether the hardware extends it with + // zeros or with its sign. + if (name == "s_mov_b64" && src.is_literal() && (src.literal >> 31) == 0) + return Moved::Const(k == 0 ? src.literal : 0); + // 64-bit inline integers are sign-extended. + if (name == "s_mov_b64" && src.is_const() && src.code >= 128 && src.code <= 208) { + const auto low = inline_constant(src.code); + if (!low) return std::nullopt; + return Moved::Const(k == 0 ? *low : static_cast<std::uint32_t>(static_cast<std::int32_t>(*low) >> 31)); + } + return std::nullopt; +} + +template <class T> +bool contains(const std::vector<T>& v, const T& x) +{ + return std::find(v.begin(), v.end(), x) != v.end(); +} + +struct Tracer { + const Program* p; + std::span<const RootParam> layout; + HwStage stage; + // Defining instruction per value (phis and inputs have none). + std::vector<std::optional<Site>> defs; + // Block and index of each phi value. + std::vector<std::optional<std::pair<std::size_t, std::size_t>>> phis; + // Register per input value. + std::vector<std::optional<Reg>> inputs; + std::vector<Term> origin_; + // See Resources::lane_copied. + mutable std::vector<Site> lane_copied; + const Structured* lanes; + // While set, sum() keeps the first-lane read of an index as the computed term instead of what + // the lanes hold. + mutable bool read_first_lane = false; + // What the conditions asked of `lanes` so far came down to: the proofs of one program ask about + // the same blocks and masks again and again. + mutable Meets meets; + // Reverse-postorder index per block. + std::vector<std::size_t> rpo; + // The block of the access being traced (live()). + mutable std::optional<std::size_t> at; + + Tracer(const Program& prog, std::span<const RootParam> lay, HwStage st, const Structured* l) + : p(&prog), layout(lay), stage(st), lanes(l) + { + std::optional<std::size_t> max; + auto see = [&](Value v) { + const std::size_t n = std::size_t{v.n} + 1; + if (!max || n > *max) max = n; + }; + for (const auto& i : prog.inputs) see(i.second); + for (const auto& b : prog.blocks) { + for (const auto& phi : b.phis) see(phi.value); + for (const auto& i : b.insts) + for (const auto& w : i.writes) see(w.second); + } + const std::size_t n = max.value_or(0); + defs.assign(n, std::nullopt); + phis.assign(n, std::nullopt); + inputs.assign(n, std::nullopt); + for (const auto& [reg, v] : prog.inputs) inputs[v.n] = reg; + for (std::size_t b = 0; b < prog.blocks.size(); ++b) { + const auto& block = prog.blocks[b]; + for (std::size_t i = 0; i < block.phis.size(); ++i) phis[block.phis[i].value.n] = std::pair{b, i}; + for (std::size_t i = 0; i < block.insts.size(); ++i) + for (const auto& w : block.insts[i].writes) defs[w.second.n] = Site{b, i}; + } + rpo.assign(prog.blocks.size(), SIZE_MAX); + const auto order = ir::reverse_postorder(prog.blocks); + for (std::size_t k = 0; k < order.size(); ++k) rpo[order[k]] = k; + origin_ = propagate_copies(n); + } + + // Optimistic copy propagation: a move's result is its source's origin, a phi's the one origin + // its arguments agree on. Throws ShaderError. + std::vector<Term> propagate_copies(std::size_t n) const + { + std::vector<std::optional<Term>> o(n); + for (const auto& [reg, v] : p->inputs) o[v.n] = Term::Of(v); + const auto order = ir::reverse_postorder(p->blocks); + for (std::size_t round = 0; round < MAX_ROUNDS; ++round) { + bool changed = false; + for (const std::size_t b : order) { + const auto& block = p->blocks[b]; + for (const auto& phi : block.phis) { + const Term own = Term::Of(phi.value); + std::optional<Term> first; + bool all = true; + for (const Value a : phi.args) { + const auto t = o[a.n]; + if (!t || *t == own) continue; + if (!first) + first = *t; + else if (*t != *first) { + all = false; + break; + } + } + std::optional<Term> nw; + if (first) nw = all ? *first : own; + if (nw && nw != o[phi.value.n]) { + o[phi.value.n] = nw; + changed = true; + } + } + for (const auto& inst : block.insts) { + for (std::size_t k = 0; k < inst.writes.size(); ++k) { + const Value v = inst.writes[k].second; + auto moved = copy_source(inst, k); + if (!moved) moved = restored(inst); + std::optional<Term> nw; + if (!moved) + nw = Term::Of(v); + else if (moved->is_const) + nw = Term::Const(moved->n); + else + nw = o[moved->n]; + if (nw && nw != o[v.n]) { + o[v.n] = nw; + changed = true; + } + } + } + } + if (!changed) { + std::vector<Term> out; + out.reserve(n); + for (std::size_t v = 0; v < n; ++v) out.push_back(o[v].value_or(Term::Of(Value{static_cast<std::uint32_t>(v)}))); + return out; + } + } + throw ShaderError::unsupported(0, "copies that do not settle"); + } + + // Whether some lane can satisfy all of `conditions` (Bools::meet). + bool meet(const Structured& l, const Known& conditions) const { return l.bools.meet_seen(conditions, meets); } + + const Inst& inst(Site s) const { return p->blocks[s.first].insts[s.second]; } + const Inst* def(Value v) const + { + const auto& d = defs[v.n]; + return d ? &inst(*d) : nullptr; + } + Term origin(Value v) const { return origin_[v.n]; } + + // The origin of a one-dword operand as `inst` reads it. + std::optional<Term> term(const Inst& i, const Operand& op) const + { + if (op.is_scalar() && op.code == gfx10::NULL_CODE) return Term::Const(0); + if (op.is_scalar()) { + const auto v = i.read(Reg::S(op.code)); + if (!v) return std::nullopt; + return origin(*v); + } + if (op.is_const()) { + const auto c = inline_constant(op.code); + if (!c) return std::nullopt; + return Term::Const(*c); + } + if (op.is_literal()) return Term::Const(op.literal); + return std::nullopt; + } + + // Layout index and dword of the root parameter `reg` holds on entry. + std::optional<std::pair<std::size_t, std::uint32_t>> param_of(Reg reg) const + { + if (!reg.is_s()) return std::nullopt; + const std::uint32_t code = reg.n; + for (std::size_t i = 0; i < layout.size(); ++i) { + const std::uint32_t first = native::user_sgpr(stage, layout[i].user_data); + if (code < first) continue; + const std::uint32_t dword = code - first; + if (dword < layout[i].sgprs) return std::pair{i, dword}; + } + return std::nullopt; + } + + // The SOP2 operands of `v` if an instruction with one of `names` wrote it. + std::optional<std::pair<const Inst*, std::array<Term, 2>>> sop2(Value v, + std::initializer_list<std::string_view> names) const + { + const Inst* i = def(v); + if (!i) return std::nullopt; + if (std::find(names.begin(), names.end(), i->name()) == names.end()) return std::nullopt; + if (i->writes.empty() || i->writes[0].second != v) return std::nullopt; + const auto* f = std::get_if<gfx10::Sop>(&i->fields); + if (!f || f->src.empty()) return std::nullopt; + const auto a = term(*i, f->src[0]); + if (!a) return std::nullopt; + if (f->src.size() < 2) return std::nullopt; + const auto b = term(*i, f->src[1]); + if (!b) return std::nullopt; + return std::pair{i, std::array<Term, 2>{*a, *b}}; + } + std::optional<std::array<Term, 2>> sop2_terms(Value v, std::initializer_list<std::string_view> names) const + { + const auto s = sop2(v, names); + if (!s) return std::nullopt; + return s->second; + } + + std::optional<RootIndexedView> root_indexed_view(const Descriptor& d, + const std::vector<std::pair<Site, Address>>& scalar) const + { + if (d.role != Role::Resource) return std::nullopt; + if (d.source.kind != Source::Kind::Loaded) return std::nullopt; + const Site load = d.source.load; + const auto it = std::lower_bound(scalar.begin(), scalar.end(), load, + [](const auto& e, const Site& s) { return e.first < s; }); + if (it == scalar.end() || it->first != load) return std::nullopt; + const Address address = it->second; + if (address.param >= layout.size()) return std::nullopt; + const RootParam& base = layout[address.param]; + if (!(base.root == RootType::Table())) return std::nullopt; + if (!address.dynamic) return std::nullopt; + const Value dynamic = *address.dynamic; + Value input = dynamic; + std::uint8_t shift = 0; + if (const auto t = sop2_terms(dynamic, {"s_lshl_b32"}); t && (*t)[0].is_value() && (*t)[1].is_const()) { + input = (*t)[0].value(); + shift = static_cast<std::uint8_t>((*t)[1].n & 31); + } + const auto reg = inputs[input.n]; + if (!reg) return std::nullopt; + const auto pc = param_of(*reg); + if (!pc) return std::nullopt; + const auto [param, constant_dword] = *pc; + if (param >= layout.size()) return std::nullopt; + const RootParam& constant = layout[param]; + if (!(constant.root == RootType::Constants())) return std::nullopt; + return RootIndexedView{base.slot, constant.slot, constant_dword, + address.offset + std::uint32_t{d.source.first} * 4, shift}; + } + + Sum sum(Term t) const + { + if (t.is_const()) return Sum{std::nullopt, t.n, std::nullopt}; + const Value v = t.value(); + const Sum dynamic{std::nullopt, 0, v}; + if (const auto reg = inputs[v.n]) { + const auto pr = param_of(*reg); + if (pr && pr->second == 0) return Sum{v, 0, std::nullopt}; + return dynamic; + } + if (getpc(v)) return Sum{v, 0, std::nullopt}; + // Paths that each add an index to a table in the code and meet before one load: the join + // itself is the computed term. Lowering gives every `s_getpc_b64` its own offset in the code + // as its value, so the join is the byte in the code whichever table a path took (address() + // adds no base to it). + if (const auto pc = code_join(v)) return Sum{*pc, 0, v}; + // An address computed in VGPRs and taken from the first lane (a table in the code indexed by + // a value held per lane, or a table offset held per lane, the console's waterfall): the sum + // of what the lanes hold. Loads at one offset in different loops (each with its own + // `v_readfirstlane_b32`) then have one address, which is what tells lowering that they read + // one descriptor. With `read_first_lane` a first-lane read of an index alone stays the + // computed term (first_lane_offset). + if (const auto lane = first_lane(v)) { + const Sum per_lane = sum(vorigin(*lane)); + return per_lane.base || !read_first_lane ? per_lane : dynamic; + } + auto terms = sop2_terms(v, {"s_add_u32", "s_add_i32"}); + if (!terms) terms = vadd(v); + if (!terms) return dynamic; + const Sum x = sum((*terms)[0]); + const Sum y = sum((*terms)[1]); + if ((x.base && y.base) || (x.dynamic && y.dynamic)) return dynamic; + return Sum{x.base ? x.base : y.base, x.offset + y.offset, x.dynamic ? x.dynamic : y.dynamic}; + } + + // For a join `v` whose every incoming value adds to an `s_getpc_b64` low dword: the first of + // those (one level of joins only). The paths may add to different ones: two tables in the code, + // one picked by control flow. + std::optional<Value> code_join(Value v) const + { + const auto ph = phis[v.n]; + if (!ph) return std::nullopt; + std::optional<Value> base; + for (const Value a : p->blocks[ph->first].phis[ph->second].args) { + const Term t = vorigin(a); + if (!t.is_value()) return std::nullopt; + const Value x = t.value(); + if (x == v) continue; + const auto pc = code_base(x, 4); + if (!pc) return std::nullopt; + if (!base) base = pc; + } + return base; + } + + // `t` is the high dword of an `s_getpc_b64`, or `s_addc_u32`s of one. + bool code_high(Term t) const { return code_high_in(t, 4); } + + bool code_high_in(Term t, std::uint32_t depth) const + { + if (!t.is_value()) return false; + const Value x = t.value(); + if (const Inst* i = def(x); i && i->name() == "s_getpc_b64" && i->writes.size() > 1 && i->writes[1].second == x) + return true; + if (depth == 0) return false; + const auto s = sop2_terms(x, {"s_addc_u32"}); + return s && (code_high_in((*s)[0], depth - 1) || code_high_in((*s)[1], depth - 1)); + } + + // The `s_getpc_b64` low dword among the terms `v` adds up (`depth` additions deep; joins are + // not followed). + std::optional<Value> code_base(Value v, std::uint32_t depth) const + { + if (getpc(v)) return v; + // Computed in VGPRs and taken from the first lane. + if (const auto lane = first_lane(v)) { + const Term t = vorigin(*lane); + if (t.is_value()) return code_base(t.value(), depth); + return std::nullopt; + } + if (depth == 0 || phis[v.n]) return std::nullopt; + auto terms = sop2_terms(v, {"s_add_u32", "s_add_i32"}); + if (!terms) terms = vadd(v); + if (!terms) return std::nullopt; + for (const Term t : *terms) { + if (!t.is_value()) continue; + if (const auto r = code_base(t.value(), depth - 1)) return r; + } + return std::nullopt; + } + + // `t` is `high` or an `s_addc_u32` of it. + bool is_high(Term t, Value high) const + { + if (!t.is_value()) return false; + const Value x = t.value(); + if (x == high) return true; + const auto s = sop2_terms(x, {"s_addc_u32"}); + return s && ((*s)[0] == Term::Of(high) || (*s)[1] == Term::Of(high)); + } + + // The VGPR value `v_readfirstlane_b32` reads to write the scalar `v`. + std::optional<Value> first_lane(Value v) const + { + const Inst* i = def(v); + if (!i) return std::nullopt; + if (i->name() != "v_readfirstlane_b32" || i->writes.empty() || i->writes[0].second != v) return std::nullopt; + const auto* f = std::get_if<gfx10::Valu>(&i->fields); + if (!f) return std::nullopt; + if (!plain_valu(*f)) return std::nullopt; + if (f->src.empty() || !f->src[0].is_vector()) return std::nullopt; + return i->read(Reg::V(f->src[0].reg)); + } + + // The `s_getpc_b64` writing `lo` as its low dword. + const Inst* getpc(Value lo) const + { + const Inst* i = def(lo); + if (!i) return nullptr; + if (i->name() == "s_getpc_b64" && !i->writes.empty() && i->writes[0].second == lo) return i; + return nullptr; + } + + // The operands of a VALU addition (`v_add_co_u32`, `v_add_nc_u32`) writing `v`, through VGPR + // copies of scalars. + std::optional<std::array<Term, 2>> vadd(Value v) const + { + const Inst* i = def(v); + if (!i) return std::nullopt; + const auto* f = std::get_if<gfx10::Valu>(&i->fields); + if (!f) return std::nullopt; + const std::string_view name = i->name(); + if (!(name == "v_add_co_u32" || name == "v_add_nc_u32")) return std::nullopt; + if (!f->dst || !f->dst->is_vector()) return std::nullopt; + if (i->write(Reg::V(f->dst->reg)) != v) return std::nullopt; + if (!plain_valu(*f)) return std::nullopt; + if (f->src.empty()) return std::nullopt; + const auto a = vterm(*i, f->src[0]); + if (!a) return std::nullopt; + if (f->src.size() < 2) return std::nullopt; + const auto b = vterm(*i, f->src[1]); + if (!b) return std::nullopt; + return std::array<Term, 2>{*a, *b}; + } + + // The origin of a VALU operand. + std::optional<Term> vterm(const Inst& i, const Operand& op) const + { + if (op.is_vector()) { + const auto v = i.read(Reg::V(op.reg)); + if (!v) return std::nullopt; + return vorigin(*v); + } + return term(i, op); + } + + // A VGPR value's origin through `v_mov_b32` copies. + Term vorigin(Value v) const + { + if (const Inst* i = def(v); i && i->name() == "v_mov_b32") { + if (const auto* f = std::get_if<gfx10::Valu>(&i->fields); f && plain_valu(*f) && !f->src.empty()) { + if (const auto t = vterm(*i, f->src[0])) return *t; + } + } + return origin(v); + } + + // The address of an access that traces to no root parameter (`why` says how it failed): title + // memory at the address as it stands, in a compute program. + R<Address> by_address(const char* why) const + { + const bool raw = std::any_of(std::begin(RAW), std::end(RAW), [&](const char* r) { return same_text(r, why); }); + if (stage == HwStage::Cs && raw) return Address{MEMORY, 0, std::nullopt}; + return Err{why}; + } + + // A global memory address: an SGPR pair plus a VGPR offset, or a VGPR pair. + R<Address> flat_address(const Inst& i, const std::optional<Operand>& addr, const std::optional<Operand>& saddr, + std::int16_t offset) const + { + if (!addr || !addr->is_vector()) return Err{"a global address not in VGPRs"}; + const std::uint8_t reg = addr->reg; + const auto off = static_cast<std::uint32_t>(static_cast<std::int32_t>(offset)); + if (saddr && saddr->is_scalar() && saddr->code != gfx10::NULL_CODE) { + const std::uint8_t code = saddr->code; + auto word = [&](std::uint8_t k) -> std::optional<Term> { + const auto v = i.read(Reg::S(static_cast<std::uint8_t>(code + k))); + if (!v) return std::nullopt; + return origin(*v); + }; + const auto lo = word(0); + const auto hi = word(1); + if (!lo || !hi) return Err{"an address not in SGPRs"}; + const auto v = i.read(Reg::V(reg)); + if (!v) return Err{"a global address"}; + Sum extra = sum(vorigin(*v)); + if (extra.base) return Err{"an offset from a root parameter"}; + extra.offset += off; + return address(*lo, *hi, extra); + } + auto word = [&](std::uint8_t k) -> std::optional<Term> { + const auto v = i.read(Reg::V(static_cast<std::uint8_t>(reg + k))); + if (!v) return std::nullopt; + return vorigin(*v); + }; + const auto lo = word(0); + const auto hi = word(1); + if (!lo || !hi) return Err{"a global address"}; + return address(*lo, *hi, Sum{std::nullopt, off, std::nullopt}); + } + + // The address `lo` and `hi` hold, plus `extra` (an instruction's immediate and offset register). + R<Address> address(Term lo, Term hi0, Sum extra) const + { + // The high half as the lanes that read through the address hold it, where that is a constant + // or what a register held on entry (the code clears a table address's high half inside a + // branch and uses the address after the join). + Term hi = hi0; + { + const Term l = live(hi0); + if (l.is_const()) + hi = l; + else if (inputs[l.n]) + hi = l; + } + const Sum s = sum(lo); + if (s.dynamic && extra.dynamic) return Err{"an address with two computed terms"}; + if (!s.base) return Err{why_no_base(s.dynamic)}; + const Value base = *s.base; + if (const Inst* pc = getpc(base)) { + // A table in the code: the base is the next instruction's offset. + std::optional<Value> high; + if (pc->writes.size() > 1) high = pc->writes[1].second; + if (!high_half(hi, high) && !(high && carried(hi, *high))) return Err{"an address with an untracked high half"}; + // A join of paths into tables in the code is the byte in the code already: each path's + // `s_getpc_b64` counts as its own offset. + const bool joined = s.dynamic && code_join(*s.dynamic).has_value(); + const std::uint32_t first = joined ? 0 : static_cast<std::uint32_t>(pc->machine.offset) + 4; + return Address{CODE, first + s.offset + extra.offset, s.dynamic ? s.dynamic : extra.dynamic}; + } + const auto reg = inputs[base.n]; + if (!reg) return Err{"an address not from a root parameter"}; + const auto pr = param_of(*reg); + if (!pr) return Err{"an address not from a root parameter"}; + const std::size_t param = pr->first; + std::optional<Value> high; + const RootType root = layout[param].root; + if (root == RootType::Table() || root == RootType::ResourceHeap() || root == RootType::SamplerHeap()) { + high = std::nullopt; + } else if (root == RootType::Descriptor()) { + const Reg h = Reg::S(static_cast<std::uint8_t>(native::user_sgpr(stage, layout[param].user_data) + 1)); + const auto it = std::find_if(p->inputs.begin(), p->inputs.end(), [&](const auto& e) { return e.first == h; }); + if (it == p->inputs.end()) return Err{"a root descriptor without its high half"}; + high = it->second; + } else { + return Err{"an address from a root parameter that is no address"}; + } + // shortcut: with a computed term, a high half that adds anything to the base's is taken as the + // carry of that term (offsets below 4 GB). + const std::optional<Value> dynamic = s.dynamic ? s.dynamic : extra.dynamic; + if (!high_half(hi, high) && !(dynamic && high && carried(hi, *high))) + return Err{"an address with an untracked high half"}; + return Address{param, s.offset + extra.offset, dynamic}; + } + + // `hi` is `high` (0 for a table), possibly plus a carry. + bool high_half(Term hi, std::optional<Value> high) const + { + const Term want = high ? Term::Of(*high) : Term::Const(0); + if (hi == want) return true; + if (!hi.is_value()) return false; + const auto s = sop2_terms(hi.value(), {"s_addc_u32"}); + if (!s) return false; + const Term a = (*s)[0], b = (*s)[1]; + return (a == want && b == Term::Const(0)) || (b == want && a == Term::Const(0)); + } + + // Whether one of the first two VALU operands of `i` satisfies `pred` (through vterm). + template <class F> + bool carry_operand(const Inst& i, const gfx10::Valu& f, F pred) const + { + const std::size_t n = std::min<std::size_t>(2, f.src.size()); + for (std::size_t k = 0; k < n; ++k) { + const auto t = vterm(i, f.src[k]); + if (t && pred(*t)) return true; + } + return false; + } + + // `hi` adds something (with carry) to `high`: `s_addc_u32` or `v_add_co_ci_u32` with `high` as an + // operand. + bool carried(Term hi, Value high) const + { + if (!hi.is_value()) return false; + const Value v = hi.value(); + if (v == high) return true; + // A join (code_join): every path carries into the table's high half. + if (const auto ph = phis[v.n]) { + // A path may carry into another table's high half (code_join). + auto high_of = [&](Term t) { return is_high(t, high) || code_high(t); }; + for (const Value a : p->blocks[ph->first].phis[ph->second].args) { + const Term t = vorigin(a); + if (t == Term::Of(v) || high_of(t)) continue; + if (!t.is_value()) return false; + Value x = t.value(); + // Computed in VGPRs and taken from the first lane. + if (const auto lane = first_lane(x)) { + const Term y = vorigin(*lane); + if (y.is_const()) return false; + x = y.value(); + } + const Inst* i = def(x); + if (!i) return false; + const auto* f = std::get_if<gfx10::Valu>(&i->fields); + if (!f) return false; + if (!(i->name() == "v_add_co_ci_u32" && carry_operand(*i, *f, high_of))) return false; + } + return true; + } + if (const auto lane = first_lane(v)) return carried(vorigin(*lane), high); + if (const auto s = sop2_terms(v, {"s_addc_u32"})) return carried((*s)[0], high) || carried((*s)[1], high); + const Inst* i = def(v); + if (!i) return false; + const auto* f = std::get_if<gfx10::Valu>(&i->fields); + if (!f) return false; + return i->name() == "v_add_co_ci_u32" && carry_operand(*i, *f, [&](Term t) { return carried(t, high); }); + } + + const char* why_no_base(std::optional<Value> dynamic) const + { + if (!dynamic) return "a constant address"; + const Value v = *dynamic; + if (inputs[v.n]) return "an address in an SGPR that is no root parameter"; + std::vector<Value> ls; + leaves(v, ls); + if (std::any_of(ls.begin(), ls.end(), [&](Value l) { + const Inst* i = def(l); + return i && i->name() == "s_getpc_b64"; + })) + return "an address relative to the program counter"; + const Inst* i = def(v); + if (!i) return "an address from a phi"; + if (i->name().starts_with("s_load_")) return "an address loaded from memory"; + return "an address not from a root parameter"; + } + + // The terms of the additions that compute `v`. + void leaves(Value v, std::vector<Value>& out) const + { + const auto s = sop2_terms(v, {"s_add_u32", "s_add_i32"}); + if (!s) { + out.push_back(v); + return; + } + for (const Term t : *s) + if (t.is_value()) leaves(t.value(), out); + } + + R<Address> smem_address(const Inst& i, const Operand& base, std::int32_t offset, const Operand& soffset) const + { + if (!base.is_scalar()) return Err{"an address not in SGPRs"}; + const std::uint8_t code = base.code; + auto word = [&](std::uint8_t k) -> std::optional<Term> { + const auto v = i.read(Reg::S(static_cast<std::uint8_t>(code + k))); + if (!v) return std::nullopt; + return origin(*v); + }; + const auto lo = word(0); + const auto hi = word(1); + if (!lo || !hi) return Err{"an address not in SGPRs"}; + const auto so = term(i, soffset); + if (!so) return Err{"an unknown offset operand"}; + Sum extra = sum(*so); + if (extra.base) return Err{"an offset from a root parameter"}; + extra.offset += static_cast<std::uint32_t>(offset); + return address(*lo, *hi, extra); + } + + // The dwords of descriptor operand `op` as `i` reads them, as origins. + std::optional<std::vector<Term>> operand_words(const Inst& i, const Operand& op) const + { + std::vector<Term> words; + for (std::uint8_t k = 0; k < op.dwords; ++k) { + const auto v = i.read(Reg::S(static_cast<std::uint8_t>(op.code + k))); + if (!v) return std::nullopt; + words.push_back(origin(*v)); + } + return words; + } + + // The source of the descriptor operand `op` of `i`, in block `at`. + R<Source> descriptor(const Inst& i, const Operand& op, std::size_t blk) const + { + if (!op.is_scalar()) return Err{"a descriptor not in SGPRs"}; + auto w = operand_words(i, op); + if (!w) return Err{"a descriptor not in SGPRs"}; + std::vector<Term> words = std::move(*w); + // A byte access through a buffer descriptor made raw reads what the descriptor's view does with a raw host + // view. + if (i.name().find("format") == std::string_view::npos) { + if (const auto raw = made_raw(words)) words.assign(raw->begin(), raw->end()); + } + // Only the lanes that reach the access read the descriptor. + Known known; + if (lanes) known.push_back({lanes->reach[blk], true}); + std::vector<std::size_t> joins; + return classify(words, joins, known); + } + + // The source of a descriptor's words; `joins` are the phi blocks being resolved, `known` holds in + // every lane that reads them. + R<Source> classify(const std::vector<Term>& words, std::vector<std::size_t>& joins, Known& known) const + { + { + TRY(s, phi(words, joins, known)); + if (s) return std::move(*s); + } + { + TRY(s, select(words, joins, known)); + if (s) return std::move(*s); + } + auto read = [&](const Term& w) -> std::optional<Value> { + if (w.is_value()) return first_lane_source(w.value()); + return std::nullopt; + }; + std::vector<Value> sources; + bool all = true; + for (const Term& w : words) { + const auto r = read(w); + if (!r) { + all = false; + break; + } + sources.push_back(*r); + } + if (all) { + // One descriptor the code keeps per lane: the lanes agree. + if (auto s = lane_copies(words)) return std::move(*s); + // Read from the first active lane, as a waterfall loop does: the dwords each lane holds. + std::vector<Term> per; + for (const Value v : sources) per.push_back(Term::Of(v)); + return per_lane(per, joins, known); + } + if (std::any_of(words.begin(), words.end(), [&](const Term& w) { return read(w).has_value(); })) + return Err{"a descriptor partly read from the first lane"}; + if (std::all_of(words.begin(), words.end(), [](const Term& w) { return w.is_const(); })) { + std::vector<std::uint32_t> consts; + for (const Term& w : words) consts.push_back(w.n); + return Source::Constant(std::move(consts)); + } + if (auto s = loaded(words)) return std::move(*s); + if (words.size() == 4 && words[2].is_const() && words[3].is_const()) { + Term hi = words[1]; + std::uint32_t bits = 0; + while (hi.is_value()) { + const auto sb = set_bits(hi.value()); + if (!sb) break; + hi = sb->first; + bits |= sb->second; + } + TRY(addr, address(words[0], hi, Sum{})); + return Source::Built(addr, bits, {words[2].n, words[3].n}); + } + const bool any_loaded = std::any_of(words.begin(), words.end(), [&](const Term& w) { + if (!w.is_value()) return false; + const Inst* i = def(w.value()); + return i && i->name().starts_with("s_load_"); + }); + return Err{any_loaded ? "a descriptor changed after loading" : "a descriptor neither loaded nor built"}; + } + + // Pushes what lanes leaving block `q` for `block` know (its reach, and its branch's way). + void push_edge(Known& known, const Structured& l, std::size_t q, std::size_t block) const + { + known.push_back({l.reach[q], true}); + const LaneExit& e = l.exits[q]; + if (e.is_branch() && e.taken != e.not_taken) known.push_back({e.when, e.taken == block}); + } + + // The one edge into the join `block` that lanes satisfying `known` can have taken, if the lanes' + // paths (Structured) rule out every other. None at loop headers and without the lanes' paths. + std::optional<std::size_t> only_edge(std::size_t block, Known& known) const + { + if (!lanes) return std::nullopt; + const auto& preds = p->blocks[block].preds; + if (preds.size() < 2 || + std::any_of(preds.begin(), preds.end(), [&](std::size_t q) { return rpo[q] >= rpo[block]; })) + return std::nullopt; + std::optional<std::size_t> only; + for (std::size_t j = 0; j < preds.size(); ++j) { + const std::size_t n = known.size(); + push_edge(known, *lanes, preds[j], block); + const bool possible = meet(*lanes, known); + known.resize(n); + if (possible) { + if (only) return std::nullopt; + only = j; + } + } + return only; + } + + // Whether lowering can make a handle for `source` in any block: its heap index comes from root + // parameters and constants alone (a table offset the code computes exists only where the load + // is). + bool anywhere(const Source& source) const + { + switch (source.kind) { + case Source::Kind::Constant: return true; + case Source::Kind::Built: return !source.address.dynamic; + case Source::Kind::Loaded: { + const Inst& i = inst(source.load); + const auto* f = std::get_if<gfx10::Smem>(&i.fields); + if (!f) return false; + const auto a = smem_address(i, f->base, f->offset, f->soffset); + return a.ok() && !a.value.dynamic; + } + default: return false; + } + } + + // `t` as the lanes that reach the access being traced hold it: through joins they can have + // entered by one edge only (only_edge). + Term live(Term t) const + { + if (!at || !lanes) return t; + Known known{{lanes->reach[*at], true}}; + for (std::size_t k = 0; k < MAX_JOINS; ++k) { + if (!t.is_value()) break; + const auto ph = phis[t.n]; + if (!ph) break; + const auto j = only_edge(ph->first, known); + if (!j) break; + t = origin(p->blocks[ph->first].phis[ph->second].args[*j]); + } + return t; + } + + std::optional<std::pair<std::size_t, std::size_t>> phi_of(const Term& w) const + { + if (w.is_value()) return phis[w.n]; + return std::nullopt; + } + + // Words that phis of one block join, traced per predecessor (words defined before the join hold + // on every edge). + R<std::optional<Source>> phi(const std::vector<Term>& words, std::vector<std::size_t>& joins, Known& known) const + { + std::optional<std::size_t> found; + for (const Term& w : words) + if (const auto ph = phi_of(w)) { + found = ph->first; + break; + } + if (!found) return std::optional<Source>{}; + const std::size_t block = *found; + for (const Term& w : words) + if (const auto ph = phi_of(w); ph && ph->first != block) return Err{"a descriptor joined in several blocks"}; + if (contains(joins, block)) return Err{"a descriptor that changes in a loop"}; + // Each level multiplies the sources by the predecessor count. + if (joins.size() >= MAX_JOINS) return Err{"a descriptor joined too often"}; + joins.push_back(block); + const auto& block_phis = p->blocks[block].phis; + auto edge = [&](std::size_t j) { + std::vector<Term> e; + for (const Term& w : words) { + const auto ph = phi_of(w); + e.push_back(ph ? origin(block_phis[ph->second].args[j]) : w); + } + return e; + }; + std::vector<Source> args; + const char* error = nullptr; + for (std::size_t j = 0; j < p->blocks[block].preds.size(); ++j) { + auto a = classify(edge(j), joins, known); + if (!a.ok()) { + error = a.err; + break; + } + args.push_back(std::move(a.value)); + } + R<std::optional<Source>> source = std::optional<Source>{}; + if (!error) { + source = std::optional<Source>{Source::Phi(block, std::move(args))}; + } else { + // An edge holds no descriptor. With only one edge the lanes that read the descriptor can + // have come by, it is what the registers hold on that one (a wave that took another edge + // has no lane left that reads it), if that can be named where it is read. + source = Err{error}; + if (const auto j = only_edge(block, known)) { + auto s = classify(edge(*j), joins, known); + if (s.ok() && anywhere(s.value)) source = std::optional<Source>{std::move(s.value)}; + } + } + joins.pop_back(); + return source; + } + + // Words that `s_cselect` (or `s_cmov`) picks by one SCC value, traced per outcome (other words + // are the same for both). + R<std::optional<Source>> select(const std::vector<Term>& words, std::vector<std::size_t>& joins, + Known& known) const + { + std::vector<std::optional<std::tuple<Value, Term, Term>>> picks; + for (const Term& w : words) picks.push_back(w.is_value() ? picked(w.value()) : std::nullopt); + std::optional<Value> scc; + for (const auto& pk : picks) + if (pk) { + scc = std::get<0>(*pk); + break; + } + if (!scc) return std::optional<Source>{}; + for (const auto& pk : picks) + if (pk && std::get<0>(*pk) != *scc) return Err{"a descriptor chosen by several conditions"}; + // Each level doubles the sources; selects count like joins (a marker no block index reaches). + if (joins.size() >= MAX_JOINS) return Err{"a descriptor joined too often"}; + joins.push_back(SIZE_MAX); + auto side = [&](bool set) { + std::vector<Term> s; + for (std::size_t k = 0; k < words.size(); ++k) + s.push_back(picks[k] ? (set ? std::get<1>(*picks[k]) : std::get<2>(*picks[k])) : words[k]); + return s; + }; + std::vector<Source> args; + const char* error = nullptr; + for (const bool set : {true, false}) { + auto a = classify(side(set), joins, known); + if (!a.ok()) { + error = a.err; + break; + } + args.push_back(std::move(a.value)); + } + joins.pop_back(); + if (error) return Err{error}; + return std::optional<Source>{Source::Select(*scc, std::move(args))}; + } + + // For `v` written by `s_cselect_b32`/`_b64` or `s_cmov_b32`/`_b64`: the SCC it reads and the dword + // it is when SCC is set, then clear. + std::optional<std::tuple<Value, Term, Term>> picked(Value v) const + { + const Inst* i = def(v); + if (!i) return std::nullopt; + const auto* f = std::get_if<gfx10::Sop>(&i->fields); + if (!f) return std::nullopt; + const auto pos = std::find_if(i->writes.begin(), i->writes.end(), [&](const auto& w) { return w.second == v; }); + if (pos == i->writes.end()) return std::nullopt; + const auto k = static_cast<std::uint8_t>(pos - i->writes.begin()); + const std::string_view name = i->name(); + bool wide; + if (name == "s_cselect_b32" || name == "s_cmov_b32") + wide = false; + else if (name == "s_cselect_b64" || name == "s_cmov_b64") + wide = true; + else + return std::nullopt; + // A dword of a 32- or 64-bit operand: 64-bit inline integers are sign-extended; 64-bit + // literals and float constants are not followed. + auto dword = [&](const Operand& op) -> std::optional<Term> { + if (op.is_scalar() && op.code == gfx10::NULL_CODE) return Term::Const(0); + if (op.is_scalar()) { + const auto r = i->read(Reg::S(static_cast<std::uint8_t>(op.code + k))); + if (!r) return std::nullopt; + return origin(*r); + } + if (op.is_const() && !wide) { + const auto c = inline_constant(op.code); + if (!c) return std::nullopt; + return Term::Const(*c); + } + if (op.is_const() && op.code >= 128 && op.code <= 208) { + const auto low = inline_constant(op.code); + if (!low) return std::nullopt; + return Term::Const(k == 0 ? *low : static_cast<std::uint32_t>(static_cast<std::int32_t>(*low) >> 31)); + } + if (op.is_literal() && !wide) return Term::Const(op.literal); + return std::nullopt; + }; + if (f->src.empty()) return std::nullopt; + const auto set = dword(f->src[0]); + if (!set) return std::nullopt; + std::optional<Term> clear; + if (name.starts_with("s_cmov")) { + if (!f->dst) return std::nullopt; + clear = dword(*f->dst); + } else { + if (f->src.size() < 2) return std::nullopt; + clear = dword(f->src[1]); + } + if (!clear) return std::nullopt; + const auto scc = i->read(Reg::Scc); + if (!scc) return std::nullopt; + return std::tuple{*scc, *set, *clear}; + } + + // `v` as some other dword with constant bits set. + std::optional<std::pair<Term, std::uint32_t>> set_bits(Value v) const + { + if (const auto s = sop2_terms(v, {"s_or_b32"})) { + if ((*s)[1].is_const()) return std::pair{(*s)[0], (*s)[1].n}; + if ((*s)[0].is_const()) return std::pair{(*s)[1], (*s)[0].n}; + } + const Inst* i = def(v); + if (!i) return std::nullopt; + const auto* f = std::get_if<gfx10::Sop>(&i->fields); + if (!f || !f->dst || !f->dst->is_scalar()) return std::nullopt; + if (f->src.empty()) return std::nullopt; + const auto t = term(*i, f->src[0]); + if (!t) return std::nullopt; + if (i->name() == "s_bitset1_b32" && t->is_const()) { + const auto r = i->read(Reg::S(f->dst->code)); + if (!r) return std::nullopt; + return std::pair{origin(*r), 1u << (t->n & 31)}; + } + return std::nullopt; + } + + // `x op c` with `c` either side. + std::optional<Term> with(Value v, std::string_view name, std::uint32_t c) const + { + const auto s = sop2_terms(v, {name}); + if (!s) return std::nullopt; + if ((*s)[1].is_const() && (*s)[1].n == c) return (*s)[0]; + if ((*s)[0].is_const() && (*s)[0].n == c) return (*s)[1]; + return std::nullopt; + } + + // The words of a buffer descriptor that `words` makes raw, as the upscaler's compiler does before + // byte accesses: the stride (dword 1 bits 16-29) cleared, the record count times max(stride, 1), + // out-of-bounds checking by bytes (dword 3 bits 28-29 set). The bounds are then the view's size + // in bytes either way. + std::optional<std::array<Term, 4>> made_raw(const std::vector<Term>& words) const + { + if (words.size() != 4 || !words[1].is_value() || !words[2].is_value() || !words[3].is_value()) + return std::nullopt; + const Term w0 = words[0]; + const auto d1 = with(words[1].value(), "s_and_b32", 0xC000'FFFF); + if (!d1) return std::nullopt; + const auto m3 = with(words[3].value(), "s_or_b32", 0x3000'0000); + if (!m3 || !m3->is_value()) return std::nullopt; + const auto d3 = with(m3->value(), "s_and_b32", 0xCFFF'FFFF); + if (!d3) return std::nullopt; + const auto ab = sop2_terms(words[2].value(), {"s_mul_i32"}); + if (!ab) return std::nullopt; + const Term a = (*ab)[0], b = (*ab)[1]; + auto max = [&](Term t) -> std::optional<Term> { + if (!t.is_value()) return std::nullopt; + return with(t.value(), "s_max_u32", 1); + }; + const auto ma = max(a); + const auto mb = max(b); + Term d2, field; + if (mb) { + d2 = a; + field = *mb; + } else if (ma) { + d2 = b; + field = *ma; + } else { + return std::nullopt; + } + if (!field.is_value()) return std::nullopt; + // s_bfe_u32: offset 16, width 14. + const auto bfe = sop2_terms(field.value(), {"s_bfe_u32"}); + if (!bfe || !((*bfe)[1] == Term::Const(0x000E'0010))) return std::nullopt; + if ((*bfe)[0] != *d1) return std::nullopt; + return std::array<Term, 4>{w0, *d1, d2, *d3}; + } + + // For a `v_readfirstlane_b32` result: the VGPR value it reads. + std::optional<Value> first_lane_source(Value v) const + { + const Inst* i = def(v); + if (!i) return std::nullopt; + const auto* f = std::get_if<gfx10::Valu>(&i->fields); + if (!f) return std::nullopt; + if (i->name() != "v_readfirstlane_b32" || f->sdwa || f->dpp) return std::nullopt; + if (f->src.empty() || !f->src[0].is_vector()) return std::nullopt; + return i->read(Reg::V(f->src[0].reg)); + } + + // The `v_readfirstlane_b32` result the scalar load at `load` adds to its address as a table offset + // (the console's waterfall, `s_load_dwordx8 .., s[4:5], s20`): `track` proves the waterfall from + // it, and lowering reads it per lane there. + std::optional<Value> first_lane_offset(Site load) const + { + const Inst& i = inst(load); + const auto* f = std::get_if<gfx10::Smem>(&i.fields); + if (!f) return std::nullopt; + read_first_lane = true; + const auto address = smem_address(i, f->base, f->offset, f->soffset); + read_first_lane = false; + if (!address.ok() || !address.value.dynamic) return std::nullopt; + const Term t = origin(*address.value.dynamic); + if (t.is_value() && first_lane_source(t.value())) return t.value(); + return std::nullopt; + } + + // Whether the descriptor operand `op` of `i` is one the code keeps per lane (lane_copies). + bool kept_per_lane(const Inst& i, const Operand& op) const + { + if (!op.is_scalar()) return false; + const auto words = operand_words(i, op); + return words && lane_copies(*words).has_value(); + } + + // The `v_readfirstlane_b32` results the descriptor operand `op` of `i` is, when every dword is + // one. + std::optional<std::vector<Value>> first_lane_words(const Inst& i, const Operand& op) const + { + if (!op.is_scalar()) return std::nullopt; + std::vector<Value> out; + for (std::uint8_t k = 0; k < op.dwords; ++k) { + const auto r = i.read(Reg::S(static_cast<std::uint8_t>(op.code + k))); + if (!r) return std::nullopt; + const Term t = origin(*r); + if (!t.is_value() || !first_lane_source(t.value())) return std::nullopt; + out.push_back(t.value()); + } + return out; + } + + // `t` through VGPR copies (of VGPRs or of scalars) and copies. + Term lane_term(Term t) const + { + for (std::size_t k = 0; k < MAX_JOINS * 2; ++k) { + if (!t.is_value()) break; + const Term next = vorigin(t.value()); + if (next == t) break; + t = next; + } + return t; + } + + // Whether `t` is a value each lane holds its own of (one in VGPRs). + bool varies(Term t) const + { + if (!t.is_value()) return false; + const Value v = t.value(); + std::optional<Reg> reg; + if (inputs[v.n]) { + reg = inputs[v.n]; + } else if (const auto ph = phis[v.n]) { + reg = p->blocks[ph->first].phis[ph->second].reg; + } else if (const Inst* i = def(v)) { + for (const auto& w : i->writes) + if (w.second == v) { + reg = w.first; + break; + } + } + return reg && reg->is_v(); + } + + // lane_term(), where every lane in `known` runs each VGPR copy it follows. + R<Term> lane_value(Term t, const Known& known) const + { + for (std::size_t k = 0; k < MAX_JOINS * 2; ++k) { + if (!t.is_value()) break; + const Value v = t.value(); + const Term next = vstep(v); + if (next == t) break; + if (varies(t)) { + if (const auto site = defs[v.n]) { + TRY(ok, runs(*site, known)); + (void)ok; + } + } + t = next; + } + return t; + } + + // One copy of vorigin(): what the `v_mov_b32` writing `v` reads, or `v`'s origin. + Term vstep(Value v) const + { + if (const Inst* i = def(v); i && i->name() == "v_mov_b32") { + if (const auto* f = std::get_if<gfx10::Valu>(&i->fields); f && plain_valu(*f) && !f->src.empty()) { + if (const auto t = raw(*i, f->src[0])) return *t; + } + } + return origin(v); + } + + // A VALU operand as `i` reads it: a VGPR's value itself, other operands' origins. + std::optional<Term> raw(const Inst& i, const Operand& op) const + { + if (op.is_vector()) { + const auto v = i.read(Reg::V(op.reg)); + if (!v) return std::nullopt; + return Term::Of(*v); + } + return term(i, op); + } + + // Fails unless every lane in `known` that reaches the vector instruction at `site` runs it: one + // with its EXEC bit clear there keeps what the registers held before. + R<bool> runs(Site site, const Known& known) const + { + if (!lanes) return true; + if (site.first >= lanes->guards.size() || site.second >= lanes->guards[site.first].size()) return true; + const auto& guard = lanes->guards[site.first][site.second]; + if (!guard) return true; + Known skips = known; + skips.push_back({lanes->reach[site.first], true}); + skips.push_back({*guard, false}); + if (meet(*lanes, skips)) return Err{"a per-lane descriptor written where some lanes may keep the old one"}; + return true; + } + + // The source of descriptor dwords each lane holds its own of (a waterfall loop reads them from + // the first active lane): the same in every lane, loaded per lane from memory a heap address + // points to, or picked per lane between such sources, by a lane mask or by the path the lane + // took. `known` holds in every lane that accesses them. + R<Source> per_lane(const std::vector<Term>& words0, std::vector<std::size_t>& joins, Known& known) const + { + std::vector<Term> words; + for (const Term& w : words0) { + TRY(t, lane_value(w, known)); + words.push_back(t); + } + const auto lane = std::find_if(words.begin(), words.end(), [&](const Term& w) { return varies(w); }); + if (lane == words.end()) return classify(words, joins, known); + { + TRY(s, fetched(words, known)); + if (s) return std::move(*s); + } + { + TRY(s, lane_select(words, joins, known)); + if (s) return std::move(*s); + } + { + TRY(s, lane_phi(words, joins, known)); + if (s) return std::move(*s); + } + const Value v = lane->value(); + const Inst* i = def(v); + if (inputs[v.n]) return Err{"a descriptor read from the first lane of an input VGPR"}; + if (!i) return Err{"a descriptor read from the first lane of a phi"}; + const std::string_view n = i->name(); + if (n.starts_with("ds_read")) return Err{"a descriptor read from the first lane of an LDS read"}; + if (n.starts_with("buffer_load")) return Err{"a descriptor read from the first lane of a buffer load"}; + if (n.starts_with("global_load") || n.starts_with("flat_load")) + return Err{"a descriptor read from the first lane of a partial or mixed load"}; + return Err{"a descriptor read from the first lane of computed VGPRs"}; + } + + // Dwords of `global_load_dword*` that line up: `first..` of one load, then the bytes that follow + // (an image descriptor takes two `global_load_dwordx4`). + R<std::optional<Source>> fetched(const std::vector<Term>& words, const Known& known) const + { + std::vector<std::pair<Site, std::size_t>> sites; + for (const Term& w : words) { + if (!w.is_value()) return std::optional<Source>{}; + const Value v = w.value(); + const auto site = defs[v.n]; + if (!site) return std::optional<Source>{}; + const Inst& i = inst(*site); + if (!i.name().starts_with("global_load_dword")) return std::optional<Source>{}; + std::optional<std::size_t> k; + std::size_t n = 0; + for (const auto& wr : i.writes) { + if (!wr.first.is_v()) continue; + if (wr.second == v) { + k = n; + break; + } + ++n; + } + if (!k) return std::optional<Source>{}; + sites.push_back({*site, *k}); + } + auto address = [&](Site site) -> R<Address> { + const Inst& i = inst(site); + const auto* f = std::get_if<gfx10::Flat>(&i.fields); + if (!f) return Err{"a global load"}; + return flat_address(i, f->addr, f->saddr, f->offset); + }; + const auto [load, first] = sites[0]; + TRY(a0, address(load)); + for (std::size_t k = 0; k < sites.size(); ++k) { + const auto [site, dword] = sites[k]; + TRY(ok, runs(site, known)); + (void)ok; + TRY(a, address(site)); + const std::uint32_t want = a0.offset + static_cast<std::uint32_t>(4 * (first + k)); + if (a.param != a0.param || a.dynamic != a0.dynamic || a.offset + static_cast<std::uint32_t>(4 * dword) != want) + return Err{"a descriptor read from the first lane of loads that do not line up"}; + } + return std::optional<Source>{Source::Fetched(load, static_cast<std::uint8_t>(first))}; + } + + // Words that `v_cndmask_b32` picks by one lane mask, traced per outcome (other words are the same + // for both). + R<std::optional<Source>> lane_select(const std::vector<Term>& words, std::vector<std::size_t>& joins, + Known& known) const + { + std::vector<std::optional<std::tuple<Value, Term, Term>>> picks; + for (const Term& w : words) picks.push_back(w.is_value() ? lane_picked(w.value()) : std::nullopt); + std::optional<Value> mask; + for (const auto& pk : picks) + if (pk) { + mask = std::get<0>(*pk); + break; + } + if (!mask) return std::optional<Source>{}; + for (const auto& pk : picks) + if (pk && std::get<0>(*pk) != *mask) return Err{"a descriptor chosen per lane by several masks"}; + for (std::size_t k = 0; k < words.size(); ++k) { + if (words[k].is_value() && picks[k]) { + if (const auto site = defs[words[k].n]) { + TRY(ok, runs(*site, known)); + (void)ok; + } + } + } + if (joins.size() >= MAX_JOINS) return Err{"a descriptor joined too often"}; + joins.push_back(SIZE_MAX); + // Each side holds where the lane's bit of the mask is set, or clear. + std::optional<Bool> bit; + if (lanes) { + if (const auto it = lanes->masks.find(*mask); it != lanes->masks.end()) bit = it->second; + } + auto side = [&](bool set) { + std::vector<Term> s; + for (std::size_t k = 0; k < words.size(); ++k) + s.push_back(picks[k] ? (set ? std::get<1>(*picks[k]) : std::get<2>(*picks[k])) : words[k]); + return s; + }; + std::vector<Source> args; + const char* error = nullptr; + for (const bool set : {true, false}) { + const std::size_t n = known.size(); + if (bit) known.push_back({*bit, set}); + auto arg = per_lane(side(set), joins, known); + known.resize(n); + if (!arg.ok()) { + error = arg.err; + break; + } + args.push_back(std::move(arg.value)); + } + joins.pop_back(); + if (error) return Err{error}; + return std::optional<Source>{Source::Lanes(*mask, std::move(args))}; + } + + // For `v` written by a plain `v_cndmask_b32`: the low dword of the lane mask it reads, and the + // dword it is where the lane's bit is set (src1), then clear (src0). + std::optional<std::tuple<Value, Term, Term>> lane_picked(Value v) const + { + const Inst* i = def(v); + if (!i) return std::nullopt; + const auto* f = std::get_if<gfx10::Valu>(&i->fields); + if (!f) return std::nullopt; + if (!f->dst || !f->dst->is_vector()) return std::nullopt; + if (i->name() != "v_cndmask_b32" || i->write(Reg::V(f->dst->reg)) != v || f->abs != 0 || f->neg != 0 || + f->clamp || f->omod != 0 || f->sdwa || f->dpp) + return std::nullopt; + if (f->src.size() != 3 || !f->src[2].is_scalar()) return std::nullopt; + const Operand& clear = f->src[0]; + const Operand& set = f->src[1]; + const auto mask = i->read(Reg::S(f->src[2].code)); + if (!mask) return std::nullopt; + const auto s = raw(*i, set); + if (!s) return std::nullopt; + const auto c = raw(*i, clear); + if (!c) return std::nullopt; + return std::tuple{*mask, *s, *c}; + } + + // Per-lane words that phis of one block join, as an if/else on a per-lane condition leaves them: + // traced on each edge into the block that lanes in `known` can take (other words hold on every + // edge). Lanes take their own paths (Structured), so each gets the value of the edge it came by; + // an edge they cannot take is nullopt. + R<std::optional<Source>> lane_phi(const std::vector<Term>& words, std::vector<std::size_t>& joins, + Known& known) const + { + std::optional<std::size_t> found; + for (const Term& w : words) + if (const auto ph = phi_of(w)) { + found = ph->first; + break; + } + if (!found) return std::optional<Source>{}; + const std::size_t block = *found; + for (const Term& w : words) + if (const auto ph = phi_of(w); ph && ph->first != block) return Err{"a descriptor joined in several blocks"}; + if (contains(joins, block)) return Err{"a descriptor that changes in a loop"}; + const auto& preds = p->blocks[block].preds; + if (std::any_of(preds.begin(), preds.end(), [&](std::size_t q) { return rpo[q] >= rpo[block]; })) { + // shortcut: what a lane holds after some passes is not traced. + return Err{"a descriptor read from the first lane of a phi at a loop header"}; + } + if (!lanes) return Err{"a descriptor read from the first lane of a phi, without the lanes' paths"}; + // The other words must be there before the join: defined in a block that dominates it, which + // (both dominating the access) is one the join does not reach. + for (const Term& w : words) { + if (!w.is_value() || phi_of(w)) continue; + const auto d = defs[w.n]; + if (d && (d->first == block || reaches(block, d->first))) return Err{"a descriptor partly joined by control flow"}; + } + if (joins.size() >= MAX_JOINS) return Err{"a descriptor joined too often"}; + joins.push_back(block); + const auto& block_phis = p->blocks[block].phis; + std::vector<std::optional<Source>> args; + for (std::size_t j = 0; j < preds.size(); ++j) { + const std::size_t n = known.size(); + push_edge(known, *lanes, preds[j], block); + R<std::optional<Source>> arg = std::optional<Source>{}; + if (meet(*lanes, known)) { + std::vector<Term> edge; + for (const Term& w : words) { + const auto ph = phi_of(w); + edge.push_back(ph ? Term::Of(block_phis[ph->second].args[j]) : w); + } + auto s = per_lane(edge, joins, known); + if (s.ok()) + arg = std::optional<Source>{std::move(s.value)}; + else + arg = Err{s.err}; + } + known.resize(n); + if (!arg.ok()) { + joins.pop_back(); + return Err{arg.err}; + } + args.push_back(std::move(arg.value)); + } + joins.pop_back(); + return std::optional<Source>{Source::LanePhi(block, std::move(args))}; + } + + // Whether a path leads from block `from` to block `to` (to `from` itself only through a back + // edge). + bool reaches(std::size_t from, std::size_t to) const + { + std::vector<bool> seen(p->blocks.size(), false); + std::vector<std::size_t> stack = p->blocks[from].exit.successors(); + while (!stack.empty()) { + const std::size_t x = stack.back(); + stack.pop_back(); + if (x == to) return true; + if (seen[x]) continue; + seen[x] = true; + for (const std::size_t s : p->blocks[x].exit.successors()) stack.push_back(s); + } + return false; + } + + // Prove a single-block waterfall at the descriptor access. In each iteration the access serves + // exactly the matching lanes, and the back edge keeps exactly the other lanes active. Otherwise, + // why not. + // + // shortcut: only the accesses are proven. Any other per-lane work in the loop is taken to run + // once for each lane, as the access does; a body whose effect adds up over the passes a lane + // waits through (a counter before the mask is narrowed) would differ. Compilers put nothing but + // the reads, the compares and the access in these loops. + R<Waterfall> waterfall(std::size_t b, const std::vector<std::size_t>& accesses, const std::vector<Value>& reads) const + { + static constexpr const char* LOOP = "a descriptor read from the first lane outside a waterfall loop"; + static constexpr const char* SPLIT = "a waterfall loop nested in another or split over blocks"; + static constexpr const char* SELECT = "a waterfall loop whose compares do not select the access's lanes"; + static constexpr const char* RETRY = "a waterfall loop whose retry does not keep the lanes still waiting"; + const std::size_t access = accesses[0]; + const auto& block = p->blocks[b]; + if (!lanes) return Err{LOOP}; + const Structured& l = *lanes; + if (block.insts.empty()) return Err{LOOP}; + const Inst& exit = block.insts.back(); + if (!(block.exit.is_branch() && block.exit.taken == b && block.exit.not_taken != b) || + exit.name() != "s_cbranch_execnz") + return Err{LOOP}; + auto mask = [&](std::optional<Value> low, std::optional<Value> high) -> std::optional<Bool> { + std::optional<Value> h; + if (p->wave64) { + if (!high) return std::nullopt; + h = high; + } + if (!low) return std::nullopt; + return l.mask_bits(*low, h); + }; + auto exec = [&](const Inst& i) { + return mask(i.read(Reg::S(ir::EXEC)), i.read(Reg::S(ir::EXEC + 1))); + }; + // The reads belong to this loop's own block: a loop around this one (one per operand, as LLVM + // nests them for a per-lane image and sampler) is not followed. + if (std::any_of(reads.begin(), reads.end(), [&](Value v) { return !defs[v.n] || defs[v.n]->first != b; })) + return Err{SPLIT}; + const auto selected0 = exec(block.insts[access]); + if (!selected0) return Err{SELECT}; + const Bool selected = *selected0; + if (std::any_of(accesses.begin(), accesses.end(), [&](std::size_t i) { return exec(block.insts[i]) != selected; })) + return Err{SELECT}; + const auto retry0 = exec(exit); + if (!retry0) return Err{RETRY}; + const Bool retry = *retry0; + const auto first = defs[reads[0].n]; + if (!first) return Err{LOOP}; + const auto remaining0 = exec(inst(*first)); + if (!remaining0) return Err{SELECT}; + const Bool remaining = *remaining0; + if (std::any_of(reads.begin(), reads.end(), [&](Value v) { + const auto d = defs[v.n]; + return !d || d->second >= access || exec(inst(*d)) != remaining; + })) + return Err{SELECT}; + const std::pair<Bool, bool> reach{l.reach[b], true}; + auto meet_ = [&](const Known& conditions) { return meet(l, conditions); }; + Waterfall out; + Known required{{remaining, true}}; + for (std::size_t i = 0; i < access; ++i) { + const Inst& in = block.insts[i]; + const auto* f = std::get_if<gfx10::Valu>(&in.fields); + if (!f) continue; + const std::string_view name = in.name(); + std::string_view ty; + if (name.starts_with("v_cmp_eq_")) + ty = name.substr(9); + else if (name.starts_with("v_cmpx_eq_")) + ty = name.substr(10); + else + continue; + std::uint8_t dwords; + if (ty == "u32" || ty == "i32") + dwords = 1; + else if (ty == "u64" || ty == "i64") + dwords = 2; + else + continue; + if (!plain_valu(*f)) continue; + // The first lane's dwords on one side, the lane's own on the other. + auto pair = [&](const Operand& fst, const Operand& own) -> std::optional<std::vector<Value>> { + if (!fst.is_scalar() || !own.is_vector()) return std::nullopt; + std::vector<Value> xs; + for (std::uint8_t k = 0; k < dwords; ++k) { + const auto sv = in.read(Reg::S(static_cast<std::uint8_t>(fst.code + k))); + if (!sv) return std::nullopt; + const Term t = origin(*sv); + if (!t.is_value()) return std::nullopt; + const Value x = t.value(); + const auto lane = in.read(Reg::V(static_cast<std::uint8_t>(own.reg + k))); + if (!lane) return std::nullopt; + const auto d = defs[x.n]; + if (!d) return std::nullopt; + const std::size_t read = d->second; + bool same = false; + if (contains(reads, x) && read < i) { + const auto src = first_lane_source(x); + if (!src) return std::nullopt; + same = lane_term(Term::Of(*src)) == lane_term(Term::Of(*lane)); + } + if (!same) return std::nullopt; + xs.push_back(x); + } + return xs; + }; + if (f->src.size() < 2) continue; + const Operand& a = f->src[0]; + const Operand& c = f->src[1]; + auto xs = pair(a, c); + if (!xs) xs = pair(c, a); + if (!xs) continue; + std::uint8_t code; + if (name.starts_with("v_cmpx_")) + code = ir::EXEC; + else if (f->dst && f->dst->is_scalar()) + code = f->dst->code; + else + continue; + const auto matched0 = mask(in.write(Reg::S(code)), in.write(Reg::S(static_cast<std::uint8_t>(code + 1)))); + if (!matched0) continue; + const Bool matched = *matched0; + if (meet_({reach, {selected, true}, {matched, false}})) continue; + required.push_back({matched, true}); + out.compares.push_back({b, i}); + for (const Value x : *xs) + if (!contains(out.reads, x)) out.reads.push_back(x); + } + if (std::any_of(reads.begin(), reads.end(), [&](Value v) { return !contains(out.reads, v); }) || + meet_({reach, {selected, true}, {remaining, false}})) + return Err{SELECT}; + // The access must take every match. + required.push_back(reach); + required.push_back({selected, false}); + if (meet_(required)) return Err{SELECT}; + // The retry must keep exactly the lanes that were eligible but did not perform the access. + if (meet_({reach, {retry, true}, {remaining, false}}) || meet_({reach, {retry, true}, {selected, true}}) || + meet_({reach, {remaining, true}, {selected, false}, {retry, false}})) + return Err{RETRY}; + return out; + } + + // Consecutive dwords of one scalar load. + std::optional<Source> loaded(const std::vector<Term>& words) const + { + if (words.empty() || !words[0].is_value()) return std::nullopt; + const Value v0 = words[0].value(); + const auto load = defs[v0.n]; + if (!load) return std::nullopt; + const Inst& i = inst(*load); + if (!i.name().starts_with("s_load_")) return std::nullopt; + const auto pos = std::find_if(i.writes.begin(), i.writes.end(), [&](const auto& w) { return w.second == v0; }); + if (pos == i.writes.end()) return std::nullopt; + const std::size_t first = static_cast<std::size_t>(pos - i.writes.begin()); + for (std::size_t k = 0; k < words.size(); ++k) + if (first + k >= i.writes.size() || words[k] != Term::Of(i.writes[first + k].second)) return std::nullopt; + return Source::Loaded(*load, static_cast<std::uint8_t>(first)); + } + + // A descriptor the code keeps per lane: every dword of `words` is the first lane + // (`v_readfirstlane_b32`) of a VGPR that `v_mov_b32` filled from SGPRs. When every scalar those + // moves copy is the same dword of loads from one constant address, the lanes agree and the + // descriptor is any of those loads. + // shortcut: what else the VGPRs held (numbers, on paths or in lanes that never read them as a + // descriptor) is ignored, and a move is taken to leave either its source or what a move before it + // wrote; a descriptor read per lane from memory (`global_load_*`) refuses. + std::optional<Source> lane_copies(const std::vector<Term>& words) const + { + std::vector<Site> loads; + std::optional<std::size_t> first; + for (std::size_t k = 0; k < words.size(); ++k) { + if (!words[k].is_value()) return std::nullopt; + const Value v = words[k].value(); + std::vector<Term> copies; + const auto fl = first_lane(v); + if (!fl) return std::nullopt; + if (!scalar_copies(*fl, copies)) return std::nullopt; + bool found = false; + for (const Term c0 : copies) { + if (!c0.is_value()) continue; + const Value c = c0.value(); + const auto site = defs[c.n]; + if (!site) continue; + const Inst& load = inst(*site); + if (!load.name().starts_with("s_load_")) continue; + // Dword k of the operand is dword `first + k` of each load. + const auto pos = + std::find_if(load.writes.begin(), load.writes.end(), [&](const auto& x) { return x.second == c; }); + if (pos == load.writes.end()) return std::nullopt; + const std::size_t dword = static_cast<std::size_t>(pos - load.writes.begin()); + if (dword < k) return std::nullopt; + const std::size_t f = dword - k; + if (!first) first = f; + if (*first != f) return std::nullopt; + if (!contains(loads, *site)) loads.push_back(*site); + found = true; + } + if (!found) return std::nullopt; + } + auto address = [&](Site site) -> std::optional<Address> { + const Inst& i = inst(site); + const auto* f = std::get_if<gfx10::Smem>(&i.fields); + if (!f) return std::nullopt; + const auto a = smem_address(i, f->base, f->offset, f->soffset); + if (!a.ok()) return std::nullopt; + return a.value; + }; + if (loads.empty()) return std::nullopt; + const auto a = address(loads.front()); + if (!a) return std::nullopt; + if (a->dynamic || std::any_of(loads.begin(), loads.end(), [&](Site l) { return address(l) != a; })) + return std::nullopt; + // The handle is made where the descriptor is used, from the load's operands: take a load whose + // base is the root parameter's own SGPR. + std::sort(loads.begin(), loads.end()); + const auto load = std::find_if(loads.begin(), loads.end(), [&](Site l) { return base_from_entry(l); }); + if (load == loads.end()) return std::nullopt; + lane_copied.insert(lane_copied.end(), loads.begin(), loads.end()); + if (!first) return std::nullopt; + return Source::Loaded(*load, static_cast<std::uint8_t>(*first)); + } + + // The scalars (as origins) that `v_mov_b32` copies put in VGPR value `v`, through joins, moves + // between VGPRs and per-lane selects; a move keeps what it wrote over in the lanes it does not + // run. False if the VGPR may hold something read per lane from memory. + bool scalar_copies(Value v0, std::vector<Term>& out) const + { + std::vector<Value> seen; + std::vector<Value> work{v0}; + while (!work.empty()) { + const Value v = work.back(); + work.pop_back(); + if (contains(seen, v)) continue; + if (seen.size() == MAX_COPIES) return false; + seen.push_back(v); + if (const auto ph = phis[v.n]) { + const auto& args = p->blocks[ph->first].phis[ph->second].args; + work.insert(work.end(), args.begin(), args.end()); + continue; + } + // An entry value, or a number some instruction computed. + const Inst* i = def(v); + if (!i) continue; + if (i->name().starts_with("global_load_")) return false; + const auto* f = std::get_if<gfx10::Valu>(&i->fields); + if (!f) continue; + std::size_t sources; + if (i->name() == "v_mov_b32") + sources = 1; + else if (i->name() == "v_cndmask_b32") + sources = 2; + else + continue; + if (!plain_valu(*f)) continue; + for (std::size_t k = 0; k < std::min(sources, f->src.size()); ++k) { + const Operand& op = f->src[k]; + if (op.is_vector()) { + if (const auto r = i->read(Reg::V(op.reg))) work.push_back(*r); + } else if (op.is_scalar() && op.code != gfx10::NULL_CODE) { + if (const auto r = i->read(Reg::S(op.code))) out.push_back(origin(*r)); + } + } + // Lanes outside EXEC keep the old value. + if (f->dst && f->dst->is_vector()) { + if (const auto r = i->read(Reg::V(f->dst->reg))) work.push_back(*r); + } + } + return true; + } + + // The load at `site` has a constant offset and takes its base from a root parameter's SGPR + // through moves alone: a value that exists wherever the descriptor is used. + bool base_from_entry(Site site) const + { + const Inst& i = inst(site); + const auto* f = std::get_if<gfx10::Smem>(&i.fields); + if (!f || !f->base.is_scalar() || !(f->soffset.is_scalar() && f->soffset.code == gfx10::NULL_CODE)) return false; + auto v = i.read(Reg::S(f->base.code)); + if (!v) return false; + for (;;) { + if (inputs[v->n]) return true; + const Inst* d = def(*v); + if (!d) return false; + const auto pos = std::find_if(d->writes.begin(), d->writes.end(), [&](const auto& w) { return w.second == *v; }); + if (pos == d->writes.end()) return false; + const auto m = copy_source(*d, static_cast<std::size_t>(pos - d->writes.begin())); + if (!m || m->is_const) return false; + v = Value{m->n}; + } + } + + // For `v_readlane_b32` of a constant lane: the SGPR spilled to that lane, found by following the + // VGPR's `v_writelane_b32` writes. + std::optional<Moved> restored(const Inst& i) const + { + const auto* v = std::get_if<gfx10::Valu>(&i.fields); + if (!v) return std::nullopt; + if (i.name() != "v_readlane_b32") return std::nullopt; + if (v->src.size() != 2 || !v->src[0].is_vector()) return std::nullopt; + const auto r = i.read(Reg::V(v->src[0].reg)); + if (!r) return std::nullopt; + const auto lane = lane_of(v->src[1]); + if (!lane) return std::nullopt; + std::vector<Value> seen; + const auto s = spilled(*r, *lane, seen); + if (!s) return std::nullopt; + return *s; + } + + // What lane `lane` of VGPR value `v` holds: an empty inner optional for a phi in `seen` (already being + // resolved), nullopt if not a spilled SGPR. + std::optional<std::optional<Moved>> spilled(Value v, std::uint32_t lane, std::vector<Value>& seen) const + { + if (const auto ph = phis[v.n]) { + if (contains(seen, v)) return std::optional<Moved>{}; + seen.push_back(v); + std::optional<Moved> found; + for (const Value a : p->blocks[ph->first].phis[ph->second].args) { + const auto r = spilled(a, lane, seen); + if (!r) return std::nullopt; + if (*r) { + if (found && *found != **r) return std::nullopt; + found = **r; + } + } + return found; + } + const Inst* i = def(v); + if (!i) return std::nullopt; + const auto* w = std::get_if<gfx10::Valu>(&i->fields); + if (!w) return std::nullopt; + if (!w->dst || !w->dst->is_vector() || w->src.size() != 2) return std::nullopt; + const Operand value = w->src[0]; + const Operand at_ = w->src[1]; + if (i->name() != "v_writelane_b32") return std::nullopt; + const auto l = lane_of(at_); + if (!l) return std::nullopt; + if (*l != lane) { + const auto r = i->read(Reg::V(w->dst->reg)); + if (!r) return std::nullopt; + return spilled(*r, lane, seen); + } + std::optional<Moved> m; + if (value.is_scalar() && value.code != gfx10::NULL_CODE) { + if (const auto r = i->read(Reg::S(value.code))) m = Moved::Of(*r); + } else if (value.is_literal()) { + m = Moved::Const(value.literal); + } else if (value.is_const()) { + if (const auto c = inline_constant(value.code)) m = Moved::Const(*c); + } + if (!m) return std::nullopt; + return std::optional<Moved>{*m}; + } +}; + +#undef TRY + +} // namespace + +// ---- Source ---- + +Source Source::Loaded(Site load, std::uint8_t first) +{ + Source s; + s.kind = Kind::Loaded; + s.load = load; + s.first = first; + return s; +} +Source Source::Built(Address address, std::uint32_t bits, std::array<std::uint32_t, 2> words) +{ + Source s; + s.kind = Kind::Built; + s.address = address; + s.bits = bits; + s.words = words; + return s; +} +Source Source::Constant(std::vector<std::uint32_t> words) +{ + Source s; + s.kind = Kind::Constant; + s.constant = std::move(words); + return s; +} +Source Source::Phi(std::size_t block, std::vector<Source> args) +{ + Source s; + s.kind = Kind::Phi; + s.block = block; + s.args = std::move(args); + return s; +} +Source Source::Select(ir::Value scc, std::vector<Source> args) +{ + Source s; + s.kind = Kind::Select; + s.scc = scc; + s.args = std::move(args); + return s; +} +Source Source::Fetched(Site load, std::uint8_t first) +{ + Source s; + s.kind = Kind::Fetched; + s.load = load; + s.first = first; + return s; +} +Source Source::Lanes(ir::Value mask, std::vector<Source> args) +{ + Source s; + s.kind = Kind::Lanes; + s.mask = mask; + s.args = std::move(args); + return s; +} +Source Source::LanePhi(std::size_t block, std::vector<std::optional<Source>> args) +{ + Source s; + s.kind = Kind::LanePhi; + s.block = block; + s.lane_args = std::move(args); + return s; +} + +std::vector<const Source*> Source::leaves() const +{ + std::vector<const Source*> out; + switch (kind) { + case Kind::Phi: + case Kind::Select: + case Kind::Lanes: + for (const Source& a : args) + for (const Source* l : a.leaves()) out.push_back(l); + break; + case Kind::LanePhi: + for (const auto& a : lane_args) + if (a) + for (const Source* l : a->leaves()) out.push_back(l); + break; + default: out.push_back(this); + } + return out; +} + +bool Source::operator==(const Source& o) const +{ + if (kind != o.kind) return false; + switch (kind) { + case Kind::Loaded: + case Kind::Fetched: return load == o.load && first == o.first; + case Kind::Built: return address == o.address && bits == o.bits && words == o.words; + case Kind::Constant: return constant == o.constant; + case Kind::Phi: return block == o.block && args == o.args; + case Kind::Select: return scc == o.scc && args == o.args; + case Kind::Lanes: return mask == o.mask && args == o.args; + case Kind::LanePhi: return block == o.block && lane_args == o.lane_args; + } + return false; +} + +std::optional<std::uint32_t> inline_constant(std::uint8_t code) +{ + auto fl = [](float f) { return std::bit_cast<std::uint32_t>(f); }; + if (code >= 128 && code <= 192) return std::uint32_t{code} - 128; + if (code >= 193 && code <= 208) return static_cast<std::uint32_t>(192 - static_cast<std::int32_t>(code)); + switch (code) { + case 240: return fl(0.5f); + case 241: return fl(-0.5f); + case 242: return fl(1.0f); + case 243: return fl(-1.0f); + case 244: return fl(2.0f); + case 245: return fl(-2.0f); + case 246: return fl(4.0f); + case 247: return fl(-4.0f); + case 248: return 0x3E22'F983u; + default: return std::nullopt; + } +} + +namespace detail { +std::vector<Term> origins(const ir::Program& p, std::span<const native::RootParam> layout, native::HwStage stage) +{ + const Tracer t(p, layout, stage, nullptr); + return t.origin_; +} +} // namespace detail + +Resources track(const Program& p, std::span<const RootParam> layout, HwStage stage, const Structured* lanes) +{ + const Tracer t(p, layout, stage, lanes); + Resources out; + for (const auto& [reg, v] : p.inputs) + if (const auto pr = t.param_of(reg)) out.params.push_back({v, pr->first, pr->second}); + // Group accesses in the same loop so a shared mask can select several descriptors together. + std::map<std::size_t, std::pair<std::vector<std::size_t>, std::vector<Value>>> first_lane_at; + // The console compiler's waterfall reads the first lane's table offset and loads that entry: + // accesses, offset reads and loads by block. + std::map<std::size_t, std::tuple<std::vector<std::size_t>, std::vector<Value>, std::vector<Site>>> offset_at; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + t.at = b; + const auto& block = p.blocks[b]; + for (std::size_t i = 0; i < block.insts.size(); ++i) { + const Inst& inst = block.insts[i]; + const Site site{b, i}; + auto fail = [&](const char* what) { return ShaderError::unsupported(inst.machine.offset, what); }; + std::vector<Value> first_lane; + std::vector<std::pair<Value, Site>> offset; + auto descriptor = [&](const Operand& op, Role role) { + auto source = t.descriptor(inst, op, b); + if (!source.ok()) throw fail(source.err); + // A descriptor the code keeps per lane (lane_copies) is the same in every lane: its + // loop is lowered as it stands and needs no proof. + if (!t.kept_per_lane(inst, op)) { + if (const auto w = t.first_lane_words(inst, op)) first_lane.insert(first_lane.end(), w->begin(), w->end()); + } + if (source.value.kind == Source::Kind::Loaded) { + const Site load = source.value.load; + if (std::any_of(out.scalar.begin(), out.scalar.end(), [&](const auto& s) { return s.first == load; })) { + if (const auto v = t.first_lane_offset(load)) offset.push_back({*v, load}); + } + } + out.descriptors.push_back(Descriptor{site, role, std::move(source.value)}); + }; + const std::string_view name = inst.name(); + if (const auto* f = std::get_if<gfx10::Image>(&inst.fields)) { + if (name.starts_with("image_bvh")) { + // The ray and node test names no texture. A descriptor whose flag dwords the code + // sets as numbers and whose type is a ray-tracing structure is a range of title + // memory (the title: all of it, or from one structure's address on), and the + // node's address is among the operands; any other descriptor must be a resource + // of the host. + auto word = [&](std::uint8_t k) -> std::optional<Term> { + if (!f->rsrc.is_scalar() || k >= f->rsrc.dwords) return std::nullopt; + const auto v = inst.read(Reg::S(static_cast<std::uint8_t>(f->rsrc.code + k))); + if (!v) return std::nullopt; + return t.origin(*v); + }; + const auto w1 = word(1); + const auto w3 = word(3); + if (w1 && w1->is_const() && w3 && w3->is_const() && (w3->n >> 28) == bvh::DESCRIPTOR_TYPE) { + out.bvh.push_back({site, BvhNodes::Memory(w1->n, w3->n)}); + } else { + descriptor(f->rsrc, Role::Resource); + out.bvh.push_back({site, BvhNodes::Resource()}); + } + } else { + descriptor(f->rsrc, Role::Resource); + if (f->sampler) descriptor(*f->sampler, Role::Sampler); + } + } else if (const auto* fb = std::get_if<gfx10::Buffer>(&inst.fields)) { + // Cache invalidations name a buffer's address space but do not read its descriptor; + // the host has no cache to drop. + if (!name.ends_with("_inv")) descriptor(fb->rsrc, Role::Resource); + } else if (const auto* fs = std::get_if<gfx10::Smem>(&inst.fields)) { + if (name.starts_with("s_buffer_")) { + descriptor(fs->base, Role::Resource); + } else if (name.find("_load_") != std::string_view::npos || name.find("_store_") != std::string_view::npos) { + auto address = t.smem_address(inst, fs->base, fs->offset, fs->soffset); + if (!address.ok()) address = t.by_address(address.err); + if (!address.ok()) throw fail(address.err); + out.scalar.push_back({site, address.value}); + } + } else if (const auto* ff = std::get_if<gfx10::Flat>(&inst.fields)) { + if (name.starts_with("global_")) { + auto address = t.flat_address(inst, ff->addr, ff->saddr, ff->offset); + if (!address.ok()) address = t.by_address(address.err); + if (!address.ok()) throw fail(address.err); + out.scalar.push_back({site, address.value}); + } + } + if (!first_lane.empty()) { + auto& [accesses, reads] = first_lane_at[b]; + accesses.push_back(i); + reads.insert(reads.end(), first_lane.begin(), first_lane.end()); + } + if (!offset.empty()) { + auto& [accesses, reads, loads] = offset_at[b]; + accesses.push_back(i); + for (const auto& [v, load] : offset) { + reads.push_back(v); + loads.push_back(load); + } + } + } + } + // What follows traces no access of one block. + t.at = std::nullopt; + // The proof needs the per-lane form. Without it nothing is emitted, and its failure is the one to + // report, so the reads stay unproven here. + if (!t.lanes) return out; + auto sorted = [](std::vector<Value> reads) { + std::sort(reads.begin(), reads.end()); + reads.erase(std::unique(reads.begin(), reads.end()), reads.end()); + return reads; + }; + for (auto& [block, entry] : first_lane_at) { + const auto& accesses = entry.first; + const auto reads = sorted(entry.second); + const auto proof = t.waterfall(block, accesses, reads); + if (!proof.ok()) throw ShaderError::unsupported(t.inst({block, accesses[0]}).machine.offset, proof.err); + out.waterfall.compares.insert(out.waterfall.compares.end(), proof.value.compares.begin(), proof.value.compares.end()); + out.waterfall.reads.insert(out.waterfall.reads.end(), proof.value.reads.begin(), proof.value.reads.end()); + } + // Unproven, an offset read stays the first lane's (one uniform entry), which is what the hardware + // reads outside a waterfall loop. + for (auto& [block, entry] : offset_at) { + const auto& accesses = std::get<0>(entry); + const auto reads = sorted(std::get<1>(entry)); + const auto& loads = std::get<2>(entry); + const auto proof = t.waterfall(block, accesses, reads); + if (proof.ok()) { + out.waterfall.compares.insert(out.waterfall.compares.end(), proof.value.compares.begin(), + proof.value.compares.end()); + out.waterfall.reads.insert(out.waterfall.reads.end(), proof.value.reads.begin(), proof.value.reads.end()); + out.waterfall.loads.insert(out.waterfall.loads.end(), loads.begin(), loads.end()); + } + } + out.lane_copied = std::move(t.lane_copied); + std::sort(out.lane_copied.begin(), out.lane_copied.end()); + out.lane_copied.erase(std::unique(out.lane_copied.begin(), out.lane_copied.end()), out.lane_copied.end()); + for (const Descriptor& d : out.descriptors) + if (const auto v = t.root_indexed_view(d, out.scalar)) out.root_indexed_views.push_back(*v); + return out; +} + +} // namespace x2w::vs::resource diff --git a/src/x2w_shader/resource.h b/src/x2w_shader/resource.h new file mode 100644 index 0000000000..eaf280aff7 --- /dev/null +++ b/src/x2w_shader/resource.h @@ -0,0 +1,220 @@ +// Resource tracking: where each descriptor a program uses comes from, in terms of the root signature. +// +// Root parameters arrive in user SGPRs (RootParam): a descriptor table as the 32-bit heap address of +// its range (the code sets the high half to 0), a root descriptor as a 64-bit buffer address, root +// constants as themselves. A root signature with dynamic resources (SM 6.6) adds the 32-bit base +// addresses of both heaps; a descriptor is then loaded from one of them at an index the code +// computes (from a root constant, say). The code loads table descriptors from heap memory with +// `s_load_dword*`, and builds a buffer descriptor around a root descriptor's address itself. Each +// descriptor operand and each scalar memory address is traced through the SSA values back to those +// parameters, by data flow: copies, phis that agree, and additions. +#pragma once + +#include <array> +#include <cstddef> +#include <cstdint> +#include <optional> +#include <span> +#include <tuple> +#include <utility> +#include <vector> + +#include "x2w_shader/error.h" +#include "x2w_shader/front_hash.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/native.h" +#include "x2w_shader/structure.h" + +namespace x2w::vs::resource { + +// An instruction: block and index in ir::Block::insts. +using Site = std::pair<std::size_t, std::size_t>; +using SiteHash = fhash::SiteHash; + +// A byte address: a root parameter's, plus a constant and at most one value the program computes +// (an index times a stride, say). +struct Address { + // Index into the layout, or CODE (or MEMORY). + std::size_t param = 0; + // Added modulo 2^32 (with carry into the high half of a root descriptor's address). + std::uint32_t offset = 0; + std::optional<ir::Value> dynamic; + bool operator==(const Address&) const = default; +}; + +// Address::param of the program's own code: a constant table the compiler appends after the code +// and reads through `s_getpc_b64`; the offset is then the byte offset in the code. +inline constexpr std::size_t CODE = SIZE_MAX; + +// Address::param of title memory at an address no root parameter gives: one the code computes from +// root constants, reads out of a descriptor or loads from other memory (compute programs only: the +// ray-tracing structure builder and the programs that walk its structures). Offset and computed term +// are not used: lowering takes the 64-bit address from the instruction's operands. +inline constexpr std::size_t MEMORY = SIZE_MAX - 1; + +// Leave fields unused by the active source kind empty. +struct Source { + enum class Kind : std::uint8_t { + // Dwords `first..` of what the scalar load at `load` reads (see Resources::scalar for its + // address). + Loaded, + // A buffer descriptor built around an address: `bits` OR-ed into dword 1 (stride, swizzle), + // dwords 2 and 3 as given (`words`). + Built, + // Fixed in the code (an immediate sampler, say): `constant`. + Constant, + // Chosen by control flow: one source per predecessor of `block` (`args`), in + // ir::Block::preds order. + Phi, + // Chosen by SCC (`scc`, the value an `s_cselect` or `s_cmov` of each dword reads): the source + // when it is set, then when it is clear (`args`). + Select, + // Dwords `first..` of what the vector load at `load` (`global_load_*`) reads, each lane at its + // own address (see Resources::scalar); the dwords past that load come from loads of the bytes + // that follow. A descriptor that differs between lanes. + Fetched, + // Picked per lane by `v_cndmask_b32` reading the lane mask whose low dword is `mask`: the + // source where the lane's bit is set, then where it is clear (`args`). + Lanes, + // Per-lane dwords chosen by control flow (VGPRs joined where lanes that took different paths + // meet): one source per predecessor of `block` (`lane_args`), in ir::Block::preds order, + // nullopt on an edge no lane that accesses the descriptor takes. A descriptor that differs + // between lanes. + LanePhi, + }; + Kind kind = Kind::Constant; + Site load{}; // Loaded, Fetched + std::uint8_t first = 0; // Loaded, Fetched + Address address; // Built + std::uint32_t bits = 0; // Built + std::array<std::uint32_t, 2> words{}; // Built + std::vector<std::uint32_t> constant; // Constant + std::size_t block = 0; // Phi, LanePhi + ir::Value scc; // Select + ir::Value mask; // Lanes + std::vector<Source> args; // Phi, Select, Lanes + std::vector<std::optional<Source>> lane_args; // LanePhi + + static Source Loaded(Site load, std::uint8_t first); + static Source Built(Address address, std::uint32_t bits, std::array<std::uint32_t, 2> words); + static Source Constant(std::vector<std::uint32_t> words); + static Source Phi(std::size_t block, std::vector<Source> args); + static Source Select(ir::Value scc, std::vector<Source> args); + static Source Fetched(Site load, std::uint8_t first); + static Source Lanes(ir::Value mask, std::vector<Source> args); + static Source LanePhi(std::size_t block, std::vector<std::optional<Source>> args); + + // The sources this one picks from (itself unless a phi). + std::vector<const Source*> leaves() const; + bool operator==(const Source&) const; +}; + +enum class Role : std::uint8_t { + // Image, buffer or `s_buffer_load` resource. + Resource, + Sampler, +}; + +struct Descriptor { + Site site{}; + Role role = Role::Resource; + Source source; + bool operator==(const Descriptor&) const = default; +}; + +// A view-heap descriptor whose byte address can be evaluated when binding the draw, using a table +// base and a root constant. +struct RootIndexedView { + std::uint8_t table_slot = 0; + std::uint8_t constant_slot = 0; + std::uint32_t constant_dword = 0; + std::uint32_t byte_offset = 0; + std::uint8_t shift = 0; + bool operator==(const RootIndexedView&) const = default; +}; + +// A ray-tracing node test (bvh.h) addresses a range of memory containing nodes. +struct BvhNodes { + enum class Kind : std::uint8_t { + // A buffer of the host: the descriptor is loaded from a table (it is among + // Resources::descriptors), and node pointers count from the buffer's start. Its flags are not + // known to the shader: boxes are sorted and triangles return barycentrics, as every + // descriptor the title builds asks. + Resource, + // Title memory by address: the code makes the descriptor from numbers (the title: the whole + // address space, or one structure's address in dword 0). Dwords 1 and 3, which hold its + // flags. + Memory, + }; + Kind kind = Kind::Resource; + std::uint32_t word1 = 0; // Memory + std::uint32_t word3 = 0; // Memory + static constexpr BvhNodes Resource() { return {Kind::Resource, 0, 0}; } + static constexpr BvhNodes Memory(std::uint32_t w1, std::uint32_t w3) { return {Kind::Memory, w1, w3}; } + bool operator==(const BvhNodes&) const = default; +}; + +// Waterfall loops over descriptors that differ between lanes: each pass reads the first active +// lane's descriptor with `v_readfirstlane_b32`, compares it with every lane's own (`v_cmp_eq`), and +// runs the access with the lanes that match. Their accesses take each lane's own descriptor +// (Source::Fetched, Source::Lanes), so the first lane's dwords are each lane's own too: the compares +// hold in every lane and one pass serves all lanes. +struct Waterfall { + // The compares, true in every lane. + std::vector<Site> compares; + // The `v_readfirstlane_b32` results they compare, each the lane's own source dword. + std::vector<ir::Value> reads; + // Descriptor loads at a table offset among `reads` (the console compiler's form): each lane loads + // its own entry. + std::vector<Site> loads; + bool operator==(const Waterfall&) const = default; +}; + +struct Resources { + // Every scalar memory access by address (`s_load_*`, `s_store_*`), and every global memory + // access (`global_*`, the dynamic term per lane). + std::vector<std::pair<Site, Address>> scalar; + std::vector<Descriptor> descriptors; + // Direct descriptor sources with a draw-evaluable index. + std::vector<RootIndexedView> root_indexed_views; + // User SGPRs holding root parameters: value on entry, layout index, dword within the parameter. + std::vector<std::tuple<ir::Value, std::size_t, std::uint32_t>> params; + // Scalar loads of one descriptor the code keeps per lane in VGPRs: they read one address, so + // their dwords stand in for each other. + std::vector<Site> lane_copied; + Waterfall waterfall; + // Every `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`: where its nodes are. + std::vector<std::pair<Site, BvhNodes>> bvh; + bool operator==(const Resources&) const = default; +}; + +// Traces every descriptor and scalar address of `p`, which runs as `stage`, to the root parameters +// in `layout`. Throws ShaderError on the first one it cannot trace. `lanes`, `p` as one lane runs it, +// tells which paths the lanes that access a per-lane descriptor took and which writes they ran; +// without it (nullptr), per-lane descriptors chosen by control flow are refused and per-lane writes +// are taken to run in every lane. +Resources track(const ir::Program& p, std::span<const native::RootParam> layout, native::HwStage stage, + const structure::Structured* lanes); + +// The 32-bit value of an inline constant operand. +std::optional<std::uint32_t> inline_constant(std::uint8_t code); + +namespace detail { +// A dword after copy propagation. +struct Term { + enum class Kind : std::uint8_t { Const, Value }; + Kind kind = Kind::Const; + std::uint32_t n = 0; + static constexpr Term Const(std::uint32_t c) { return {Kind::Const, c}; } + static constexpr Term Of(ir::Value v) { return {Kind::Value, v.n}; } + constexpr bool is_const() const { return kind == Kind::Const; } + constexpr bool is_value() const { return kind == Kind::Value; } + constexpr ir::Value value() const { return {n}; } + constexpr bool operator==(const Term&) const = default; +}; +// Every value's origin after copy propagation (Tracer::new(..).origin, for the tests). Throws +// ShaderError. +std::vector<Term> origins(const ir::Program& p, std::span<const native::RootParam> layout, native::HwStage stage); +} // namespace detail + +} // namespace x2w::vs::resource diff --git a/src/x2w_shader/spill.cpp b/src/x2w_shader/spill.cpp new file mode 100644 index 0000000000..66a63fac0f --- /dev/null +++ b/src/x2w_shader/spill.cpp @@ -0,0 +1,267 @@ +// Spilled user-data tables. See spill.h. +#include "x2w_shader/spill.h" + +#include <algorithm> +#include <string_view> +#include <unordered_map> +#include <unordered_set> +#include <variant> + +#include "x2w_shader/front_hash.h" + +namespace x2w::vs::spill { + +namespace { + +using gfx10::Operand; +using ir::Program; +using ir::Reg; +using ir::Value; +using Site = std::pair<std::size_t, std::size_t>; +using ValueSet = std::unordered_set<Value, fhash::ValueHash>; + +// The user-data index of the table's first dword. +constexpr std::uint32_t FIRST = 16; + +bool contains(const std::vector<Value>& v, Value x) { return std::find(v.begin(), v.end(), x) != v.end(); } +bool contains(const std::vector<Site>& v, Site x) { return std::find(v.begin(), v.end(), x) != v.end(); } + +// Values some instruction or phi reads; with `skip`, not counting the instructions it lists. +ValueSet reads_of(const Program& p, const std::vector<Site>* skip) +{ + ValueSet used; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& block = p.blocks[b]; + for (const auto& phi : block.phis) used.insert(phi.args.begin(), phi.args.end()); + for (std::size_t i = 0; i < block.insts.size(); ++i) { + if (skip && contains(*skip, Site{b, i})) continue; + for (const auto& r : block.insts[i].reads) used.insert(r.second); + } + } + return used; +} + +} // namespace + +namespace detail { + +std::optional<std::vector<std::pair<std::uint32_t, std::uint32_t>>> spilled(const native::NativeProgram& native) +{ + const auto* cs = std::get_if<native::ComputeIo>(&native.io); + if (!cs) return std::nullopt; + if (native.stage != native::HwStage::Cs) return std::nullopt; + const std::uint32_t registers = cs->user_sgprs(); + std::vector<std::pair<std::uint32_t, std::uint32_t>> out; + for (const auto& e : native.layout) + if (e.sgprs > 0 && std::uint32_t{e.user_data} >= registers) out.push_back({e.user_data, e.sgprs}); + // Only the one arrangement seen: the table starts at index 16. + std::optional<std::uint32_t> min; + for (const auto& e : out) + if (!min || e.first < *min) min = e.first; + if (min == FIRST && registers >= 2) return out; + return std::nullopt; +} + +} // namespace detail + +Program build(const native::NativeProgram& native) +{ + const std::vector<std::uint8_t> code = native.patched_code(); + Program p = ir::build(code, native.wave64, native.vgprs); + user_data(p, native); + return p; +} + +bool is_spilled(const native::NativeProgram& native) { return detail::spilled(native).has_value(); } + +std::size_t user_data(Program& p, const native::NativeProgram& native) +{ + const auto spilled = detail::spilled(native); + if (!spilled) return 0; + auto entry = [&](Reg reg) -> std::optional<Value> { + for (const auto& i : p.inputs) + if (i.first == reg) return i.second; + return std::nullopt; + }; + const auto low = entry(Reg::S(0)); + const auto high = entry(Reg::S(1)); + if (!low || !high) return 0; + + // The pointer's halves: `s0` and its copies, `s1 & 0xff` and its copies. + std::vector<Value> lows{*low}; + std::vector<Value> highs; + std::vector<Value> raw_highs{*high}; + // Instructions that only form the pointer: dropped when nothing reads them any more. + std::vector<Site> forming; + for (;;) { + bool changed = false; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& block = p.blocks[b]; + for (std::size_t i = 0; i < block.insts.size(); ++i) { + const ir::Inst& inst = block.insts[i]; + const auto* f = std::get_if<gfx10::Sop>(&inst.fields); + if (!f) continue; + if (!f->dst || !f->dst->is_scalar()) continue; + const auto out = inst.write(Reg::S(f->dst->code)); + if (!out) continue; + auto read = [&](const Operand& op) -> std::optional<Value> { + if (op.is_scalar() && op.code != gfx10::NULL_CODE) return inst.read(Reg::S(op.code)); + return std::nullopt; + }; + std::vector<Value>* found = nullptr; + const std::string_view name = inst.name(); + if (name == "s_mov_b32" && f->src.size() == 1) { + const auto v = read(f->src[0]); + if (v && contains(lows, *v)) + found = &lows; + else if (v && contains(highs, *v)) + found = &highs; + else if (v && contains(raw_highs, *v)) + found = &raw_highs; + } else if (name == "s_and_b32" && f->src.size() == 2) { + auto masked = [&](const Operand& a, const Operand& m) { + if (!(m.is_literal() && m.literal == 0xff)) return false; + const auto v = read(a); + return v && contains(raw_highs, *v); + }; + if (masked(f->src[0], f->src[1]) || masked(f->src[1], f->src[0])) found = &highs; + } + if (found && !contains(*found, *out)) { + found->push_back(*out); + forming.push_back({b, i}); + changed = true; + } + } + } + if (!changed) break; + } + if (highs.empty()) return 0; + + // Values some instruction or phi reads. + const ValueSet read_somewhere = reads_of(p, nullptr); + std::uint32_t next = 0; + { + std::optional<std::uint32_t> max; + auto see = [&](Value v) { + const std::uint32_t n = v.n + 1; + if (!max || n > *max) max = n; + }; + for (const auto& i : p.inputs) see(i.second); + for (const auto& b : p.blocks) { + for (const auto& phi : b.phis) see(phi.value); + for (const auto& i : b.insts) + for (const auto& w : i.writes) see(w.second); + } + next = max.value_or(0); + } + + // Each load through the pointer: its dwords become entry values. + std::unordered_map<Value, Value, fhash::ValueHash> replaced; + std::vector<Site> gone; + auto inputs = p.inputs; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const auto& block = p.blocks[b]; + for (std::size_t i = 0; i < block.insts.size(); ++i) { + const ir::Inst& inst = block.insts[i]; + const auto* f = std::get_if<gfx10::Smem>(&inst.fields); + if (!f) continue; + if (!f->data || !f->data->is_scalar() || !f->base.is_scalar()) continue; + const std::uint8_t first = f->data->code; + const std::uint8_t base = f->base.code; + const std::int32_t offset = f->offset; + const Operand& soffset = f->soffset; + const bool soffset_none = (soffset.is_scalar() && soffset.code == gfx10::NULL_CODE) || + (soffset.is_const() && soffset.code == 128); + auto in = [&](std::uint8_t code, const std::vector<Value>& set) { + const auto v = inst.read(Reg::S(code)); + return v && contains(set, *v); + }; + if (!inst.name().starts_with("s_load_dword") || !soffset_none || offset < 0 || offset % 4 != 0 || + !in(base, lows) || !in(static_cast<std::uint8_t>(base + 1), highs)) + continue; + std::vector<std::pair<Reg, Value>> dwords; + bool skip = false; + for (const auto& [reg, v] : inst.writes) { + if (!reg.is_s() || reg.n < first) { + skip = true; + break; + } + const std::uint32_t k = static_cast<std::uint32_t>(reg.n - first); + const std::uint32_t index = FIRST + static_cast<std::uint32_t>(offset) / 4 + k; + const bool declared = std::any_of(spilled->begin(), spilled->end(), [&](const auto& e) { + return index >= e.first && index < e.first + e.second; + }); + if (!declared) { + if (read_somewhere.count(v)) { + skip = true; + break; + } + continue; + } + // SGPR codes end at 105; no root signature reaches there. + if (index > 105) { + skip = true; + break; + } + dwords.push_back({Reg::S(static_cast<std::uint8_t>(index)), v}); + } + if (skip) continue; + for (const auto& [reg, v] : dwords) { + Value value; + const auto it = + std::find_if(inputs.begin(), inputs.end(), [&](const auto& e) { return e.first == reg; }); + if (it != inputs.end()) { + value = it->second; + } else { + value = Value{next}; + next += 1; + inputs.push_back({reg, value}); + } + replaced.insert_or_assign(v, value); + } + gone.push_back({b, i}); + } + } + if (gone.empty()) return 0; + p.inputs = std::move(inputs); + auto renamed = [&](Value& v) { + if (const auto it = replaced.find(v); it != replaced.end()) v = it->second; + }; + for (auto& block : p.blocks) { + for (auto& phi : block.phis) + for (auto& a : phi.args) renamed(a); + for (auto& inst : block.insts) + for (auto& r : inst.reads) renamed(r.second); + } + // The loads go, then what only formed the pointer (last first, so a copy goes before what it + // copied). + std::vector<Site> drop = gone; + for (;;) { + const ValueSet used = reads_of(p, &drop); + const std::size_t before = drop.size(); + for (const Site& site : forming) { + const ir::Inst& inst = p.blocks[site.first].insts[site.second]; + const bool unread = std::all_of(inst.writes.begin(), inst.writes.end(), + [&](const auto& w) { return !used.count(w.second); }); + if (!contains(drop, site) && unread) drop.push_back(site); + } + if (drop.size() == before) break; + } + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + auto& insts = p.blocks[b].insts; + std::vector<ir::Inst> kept; + kept.reserve(insts.size()); + for (std::size_t i = 0; i < insts.size(); ++i) + if (!contains(drop, Site{b, i})) kept.push_back(std::move(insts[i])); + insts = std::move(kept); + } + // The pointer's registers are no inputs once nothing reads them. + const ValueSet read = reads_of(p, nullptr); + std::erase_if(p.inputs, [&](const std::pair<Reg, Value>& e) { + const bool pointer = e.first == Reg::S(0) || e.first == Reg::S(1); + return pointer && !read.count(e.second); + }); + return gone.size(); +} + +} // namespace x2w::vs::spill diff --git a/src/x2w_shader/spill.h b/src/x2w_shader/spill.h new file mode 100644 index 0000000000..4bb3937bea --- /dev/null +++ b/src/x2w_shader/spill.h @@ -0,0 +1,49 @@ +// The spilled user-data table of a compute program. +// +// A compute program has as many user SGPRs as `COMPUTE_PGM_RSRC2` says. A root signature that needs +// more dwords than that keeps none of its parameters in registers: user-data dwords 0 and 1 then hold +// the 40-bit address of a table in memory (`s0`, and `s1 & 0xff` as bits 32-39), and the parameter the +// layout declares at user-data index N (16 or above) is at byte `4 * (N - 16)` of that table. The code +// reads it with `s_load_dword*` through that pointer. (Every compute program of the console's +// ray-tracing structure builder is of this kind; measured there: 118 of 118 such loads land on a +// declared parameter.) +// +// user_data() rewrites those loads away: each dword they read becomes the entry value of the SGPR its +// user-data index names, as if the parameter had arrived in a register. Resource tracking and +// lowering then treat a spilled parameter like any other (the host binds user data by root slot and +// dword, not by register). +#pragma once + +#include <cstddef> +#include <cstdint> +#include <optional> +#include <utility> +#include <vector> + +#include "x2w_shader/ir.h" +#include "x2w_shader/native.h" + +namespace x2w::vs::spill { + +// ir::build of `native`'s code as the hardware runs it, with the loads of a spilled user-data table +// rewritten (user_data). Throws ShaderError. +ir::Program build(const native::NativeProgram& native); + +// Whether `native` reads its root parameters from a spilled user-data table. (In the title exactly +// the compute programs of the console's ray-tracing structure builder do.) +bool is_spilled(const native::NativeProgram& native); + +// Rewrites the loads of `native`'s spilled user-data table in `p`; returns how many loads it +// replaced. Nothing changes unless the program is a compute program whose layout has entries past +// its user SGPRs, the first at index 16. A load is left alone (and resource tracking then refuses it +// as before) when its offset is not a constant on a dword, or when a dword it reads and the program +// uses is in no layout entry. +std::size_t user_data(ir::Program& p, const native::NativeProgram& native); + +namespace detail { +// The entries no register holds, as (first user-data index, dwords), if the table starts at index 16 and +// the program has the two registers of its address. +std::optional<std::vector<std::pair<std::uint32_t, std::uint32_t>>> spilled(const native::NativeProgram& native); +} // namespace detail + +} // namespace x2w::vs::spill diff --git a/src/x2w_shader/structure.cpp b/src/x2w_shader/structure.cpp new file mode 100644 index 0000000000..77ef13a8b0 --- /dev/null +++ b/src/x2w_shader/structure.cpp @@ -0,0 +1,1201 @@ +// Control-flow structurisation. See structure.h. +// +// Node IDs follow creation order. Evaluate calls that may create a node (atom, mk, ite, mask, sop, operand) +// in separate statements so the IDs are reproducible. +#include "x2w_shader/structure.h" + +#include <algorithm> +#include <string_view> +#include <variant> + +namespace x2w::vs::structure { + +namespace { + +using gfx10::Operand; +using ir::Exit; +using ir::Inst; +using ir::Program; +using ir::Reg; +using ir::Value; + +constexpr std::size_t MAX_NODES = std::size_t{1} << 21; +constexpr std::size_t MAX_ROUNDS = 256; + +ShaderError too_large() { return ShaderError::isa(0, "lane conditions too large"); } + +using ValueSet = std::unordered_set<Value, ValueHash>; +template <class V> +using KeyMap = std::unordered_map<Key, V, fhash::ValuePairHash>; +template <class V> +using ValueMap = std::unordered_map<Value, V, ValueHash>; +using BoolMemo = std::unordered_map<Bool, Bool, BoolHash>; + +std::optional<std::string_view> strip_prefix(std::string_view s, std::string_view p) +{ + if (!s.starts_with(p)) return std::nullopt; + return s.substr(p.size()); +} +std::optional<std::string_view> strip_suffix(std::string_view s, std::string_view p) +{ + if (!s.ends_with(p)) return std::nullopt; + return s.substr(0, s.size() - p.size()); +} + +} // namespace + +// ---- Bools ---- + +Bools::Bools() +{ + nodes_.push_back({TERMINAL, Bool::False, Bool::False}); + nodes_.push_back({TERMINAL, Bool::True, Bool::True}); +} + +std::optional<std::tuple<Atom, Bool, Bool>> Bools::node(Bool b) const +{ + const auto& [v, lo, hi] = nodes_.at(b.n); + if (v == TERMINAL) return std::nullopt; + return std::tuple<Atom, Bool, Bool>{atoms_[v], lo, hi}; +} + +std::vector<Atom> Bools::support(Bool b) const +{ + std::vector<std::uint32_t> vs = vars(b); + std::sort(vs.begin(), vs.end()); + std::vector<Atom> out; + out.reserve(vs.size()); + for (std::uint32_t v : vs) out.push_back(atoms_[v]); + return out; +} + +std::vector<std::uint32_t> Bools::vars(Bool b) const +{ + std::vector<Bool> seen; + std::vector<std::uint32_t> out; + std::vector<Bool> stack{b}; + while (!stack.empty()) { + const Bool x = stack.back(); + stack.pop_back(); + const auto& [v, lo, hi] = nodes_[x.n]; + if (v == TERMINAL || std::find(seen.begin(), seen.end(), x) != seen.end()) continue; + seen.push_back(x); + if (std::find(out.begin(), out.end(), v) == out.end()) out.push_back(v); + stack.push_back(lo); + stack.push_back(hi); + } + return out; +} + +Bool Bools::atom(const Atom& atom, std::size_t born) +{ + std::uint32_t v; + const auto it = ids_.find(atom); + if (it != ids_.end()) { + v = it->second; + } else { + atoms_.push_back(atom); + born_.push_back(born); + v = static_cast<std::uint32_t>(atoms_.size() - 1); + ids_.emplace(atom, v); + } + return mk(v, Bool::False, Bool::True); +} + +Bool Bools::mk(std::uint32_t v, Bool lo, Bool hi) +{ + if (lo == hi) return lo; + const auto key = std::tuple<std::uint32_t, std::uint32_t, std::uint32_t>{v, lo.n, hi.n}; + if (const auto it = unique_.find(key); it != unique_.end()) return it->second; + if (nodes_.size() >= MAX_NODES) { + // The caller fails once it sees `overflow`. + overflow_ = true; + return Bool::False; + } + const Bool b{static_cast<std::uint32_t>(nodes_.size())}; + nodes_.push_back({v, lo, hi}); + unique_.emplace(key, b); + return b; +} + +std::pair<Bool, Bool> Bools::split(Bool b, std::uint32_t v) const +{ + const auto& [bv, lo, hi] = nodes_[b.n]; + if (bv == v) return {lo, hi}; + return {b, b}; +} + +Bool Bools::ite(Bool f, Bool g, Bool h) +{ + if (f == Bool::True || g == h) return g; + if (f == Bool::False) return h; + if (g == Bool::True && h == Bool::False) return f; + const auto key = std::tuple<std::uint32_t, std::uint32_t, std::uint32_t>{f.n, g.n, h.n}; + if (const auto it = memo_.find(key); it != memo_.end()) return it->second; + const std::uint32_t v = std::min(std::min(top(f), top(g)), top(h)); + const auto [f0, f1] = split(f, v); + const auto [g0, g1] = split(g, v); + const auto [h0, h1] = split(h, v); + const Bool lo = ite(f0, g0, h0); + const Bool hi = ite(f1, g1, h1); + const Bool r = mk(v, lo, hi); + memo_.insert_or_assign(key, r); + return r; +} + +Bool Bools::and_(Bool a, Bool b) { return ite(a, b, Bool::False); } +Bool Bools::or_(Bool a, Bool b) { return ite(a, Bool::True, b); } +Bool Bools::not_(Bool a) { return ite(a, Bool::False, Bool::True); } +Bool Bools::xor_(Bool a, Bool b) +{ + const Bool nb = not_(b); + return ite(a, nb, b); +} + +bool Bools::meet(const std::vector<std::pair<Bool, bool>>& all) const +{ + Meets seen; + return meet_seen(all, seen); +} + +bool Bools::meet_seen(const std::vector<std::pair<Bool, bool>>& all, Meets& seen) const +{ + return meet_within(all, MAX_MEET, seen); +} + +bool Bools::meet_within(const std::vector<std::pair<Bool, bool>>& all, std::size_t budget, Meets& seen) const +{ + std::vector<std::uint32_t> work; + work.reserve(all.size() * 8); + for (const auto& [b, holds] : all) work.push_back((b.n << 1) | (holds ? 1u : 0u)); + return meet_in(0, work, budget, seen); +} + +// The search of meet for the conditions `work[at..]` (a node doubled, plus one where it must hold), which +// it takes off `work`. A case split on the top variable; `seen` keeps the conditions that no lane satisfies +// with the case splits it took to find that out. +bool Bools::meet_in(std::size_t at, std::vector<std::uint32_t>& work, std::size_t& budget, Meets& seen) const +{ + // Constants either fail or say nothing. + std::size_t kept = at; + for (std::size_t i = at; i < work.size(); ++i) { + const std::uint32_t b = work[i] >> 1; + const bool holds = (work[i] & 1) != 0; + if (b > Bool::True.n) { + work[kept] = work[i]; + ++kept; + } else if ((b == Bool::True.n) != holds) { + work.resize(at); + return false; + } + } + work.resize(kept); + if (kept == at || budget == 0) { + work.resize(at); + return true; + } + // As a set: neither order nor repeats change the search. + std::sort(work.begin() + static_cast<std::ptrdiff_t>(at), work.end()); + std::size_t end = at + 1; + for (std::size_t i = at + 1; i < kept; ++i) { + if (work[i] != work[end - 1]) { + work[end] = work[i]; + ++end; + } + } + work.resize(end); + { + const std::vector<std::uint32_t> key(work.begin() + static_cast<std::ptrdiff_t>(at), work.end()); + if (const auto it = seen.none.find(key); it != seen.none.end()) { + const std::size_t splits = it->second; + const bool within = splits <= budget; + budget = budget >= splits ? budget - splits : 0; + work.resize(at); + return !within; + } + } + const std::size_t before = budget; + budget -= 1; + std::uint32_t v = TERMINAL; + for (std::size_t i = at; i < end; ++i) v = std::min(v, top(Bool{work[i] >> 1})); + bool found = false; + for (const bool value : {false, true}) { + for (std::size_t i = at; i < end; ++i) { + const auto [lo, hi] = split(Bool{work[i] >> 1}, v); + const std::uint32_t code = ((value ? hi : lo).n << 1) | (work[i] & 1); + work.push_back(code); + } + if (meet_in(end, work, budget, seen)) { + found = true; + break; + } + } + if (!found && seen.none.size() < MAX_MEETS) { + std::vector<std::uint32_t> key(work.begin() + static_cast<std::ptrdiff_t>(at), + work.begin() + static_cast<std::ptrdiff_t>(end)); + seen.none.insert_or_assign(std::move(key), before - budget); + } + work.resize(at); + return found; +} + +bool Bools::implies(Bool a, Bool b) +{ + const Bool nb = not_(b); + return and_(a, nb) == Bool::False; +} + +Bool Bools::forget(Bool b, std::size_t from, BoolMemo& memo) +{ + const auto [v, lo0, hi0] = nodes_[b.n]; + if (v == TERMINAL) return b; + if (const auto it = memo.find(b); it != memo.end()) return it->second; + const Bool lo = forget(lo0, from, memo); + const Bool hi = forget(hi0, from, memo); + const Bool r = born_[v] >= from ? or_(lo, hi) : mk(v, lo, hi); + memo.insert_or_assign(b, r); + return r; +} + +Bool Bools::restrict(Bool b, std::uint32_t v, bool value, BoolMemo& memo) +{ + const auto [bv, lo0, hi0] = nodes_[b.n]; + if (bv == TERMINAL || bv > v) return b; + if (bv == v) return value ? hi0 : lo0; + if (const auto it = memo.find(b); it != memo.end()) return it->second; + const Bool l = restrict(lo0, v, value, memo); + const Bool h = restrict(hi0, v, value, memo); + const Bool r = mk(bv, l, h); + memo.insert_or_assign(b, r); + return r; +} + +Bool Bools::given(Bool b, Bool known) +{ + for (const std::uint32_t v : vars(b)) { + const Bool x = mk(v, Bool::False, Bool::True); + const Bool nx = not_(x); + if (implies(known, x)) { + BoolMemo memo; + b = restrict(b, v, true, memo); + } else if (implies(known, nx)) { + BoolMemo memo; + b = restrict(b, v, false, memo); + } + } + return b; +} + +std::optional<Bool> Structured::mask_bits(Value low, std::optional<Value> high) const +{ + if (high) { + const auto it = paired_masks.find(Key{low, *high}); + if (it == paired_masks.end()) return std::nullopt; + return it->second; + } + const auto it = masks.find(low); + if (it == masks.end()) return std::nullopt; + return it->second; +} + +// ---- Lanes ---- + +namespace { + +// A mask join taken as `value` in every lane that reaches `block`: each incoming mask held (or +// failed) on its edge. +struct Join { + std::size_t block; + // The phi value naming the join. + Value id; + bool value; + bool derived; + std::vector<Key> args; +}; + +// A mask join represented as Atom::Phi, whose incoming edge masks are resolved once every block +// (including loop back edges) has been visited. +struct PhiJoin { + std::size_t block; + Value id; + bool derived; + std::vector<Key> args; +}; + +struct SopMasks { + std::optional<std::pair<Key, Bool>> dst; + std::optional<std::pair<Key, Bool>> exec; + // Some operand derives from EXEC or a VALU result. + bool derived = false; + // For branches: SCC ("result is not zero") per lane. + std::optional<Bool> scc; +}; + +struct Lanes { + const Program* p; + std::vector<std::size_t> order; + // Reverse-postorder index per block. + std::vector<std::size_t> index; + // Per block, in predecessor order: (block, over its taken edge). + std::vector<std::vector<std::pair<std::size_t, bool>>> incoming; + // Block and instruction index writing each value. + ValueMap<std::pair<std::size_t, std::size_t>> defs; + // Block and index of each phi value. + ValueMap<std::pair<std::size_t, std::size_t>> phis; + // Mask joins found wrong when resolved to a constant: atoms instead. + ValueSet unresolved; + // Phi ids whose joins depend on EXEC or VALU results (including along back edges), carried + // across resets so their joins stay in `masks`. + ValueSet derived_phis; + Bools b; + // Masks derived from EXEC and VALU results. + KeyMap<Bool> masks; + // Other values read as masks: constants, uniform selects, opaque ones. + KeyMap<Bool> other; + // Pairs read as masks that `mask` does not see: carry-ins, and pairs joins take over back edges. + std::vector<Key> seen; + // For branches: SCC of a mask operation ("some lane is set") as the lane's own bit. + ValueMap<Bool> scc_lane; + // Joins resolved to a constant, to check once all edges are known. + std::vector<Join> joins; + // Atom::Phi joins created in the current pass, resolved in check_joins and exported in finish. + std::vector<PhiJoin> phi_joins; + ValueSet phi_join_ids; + // Per block: what a lane knows on entry, over forward edges only. + std::vector<Bool> first; + // Per block ending in a branch: when a lane takes it. + std::vector<std::optional<Bool>> when; + ValueSet active; + std::set<std::size_t> wide; + // SCC values of scc_lane that are set when EVERY lane's bit is (`s_cmp_eq` of two masks: "no lane + // differs"); the others are set when some lane's is. + ValueSet scc_every; + std::vector<std::optional<bool>> wave_any; + + explicit Lanes(const Program& program); + void reset(); + std::vector<std::vector<std::optional<Bool>>> masks_in_order(); + Bool edge(Bool c, std::size_t q, bool taken); + std::pair<std::vector<Value>, std::vector<Value>> check_joins(const std::vector<Bool>& cond); + Structured finish(const std::vector<std::vector<std::optional<Bool>>>& execs, const std::vector<Bool>& cond); + template <class F> + std::optional<Key> key(F value, std::uint8_t code) const; + std::size_t born(Value v) const; + Bool exec(const Inst& inst); + std::pair<Bool, bool> mask(Key k); + std::optional<std::pair<Bool, bool>> join(Key k); + std::optional<std::pair<Bool, bool>> operand(const Inst& inst, const Operand& op); + std::optional<SopMasks> sop(const Inst& inst); + bool clear_after_loop(Value scc) const; + std::optional<Bool> combine(std::string_view f, Bool a, Bool c); + void step(const Inst& inst, std::optional<Bool> exec); + std::optional<bool> wave_kind(const Inst& inst) const; + Bool branch(const Inst& inst); + std::vector<Bool> paths(); +}; + +const Inst* def_of(const Program& p, std::optional<std::pair<std::size_t, std::size_t>> d) +{ + if (!d) return nullptr; + return &p.blocks[d->first].insts[d->second]; +} + +template <class M> +std::optional<std::pair<std::size_t, std::size_t>> lookup(const M& m, Value v) +{ + const auto it = m.find(v); + if (it == m.end()) return std::nullopt; + return it->second; +} + +// `ir::build` splits irreducible loops; checked again because everything here assumes a reducible +// graph. +void check_reducible(const Program& p, const std::vector<std::size_t>& order, const std::vector<std::size_t>& index) +{ + if (const auto e = ir::irreducible_edge(p.blocks, order, index)) + throw ShaderError::unsupported(p.blocks[e->first].offset, "irreducible control flow"); +} + +Lanes::Lanes(const Program& program) : p(&program) +{ + const auto& blocks = program.blocks; + order = ir::reverse_postorder(blocks); + index.assign(blocks.size(), SIZE_MAX); + for (std::size_t i = 0; i < order.size(); ++i) index[order[i]] = i; + check_reducible(program, order, index); + incoming.assign(blocks.size(), {}); + for (std::size_t bl = 0; bl < blocks.size(); ++bl) { + const auto succ = blocks[bl].exit.successors(); + for (std::size_t k = 0; k < succ.size(); ++k) incoming[succ[k]].push_back({bl, k == 0}); + for (std::size_t i = 0; i < blocks[bl].phis.size(); ++i) + phis.insert_or_assign(blocks[bl].phis[i].value, std::pair{bl, i}); + for (std::size_t i = 0; i < blocks[bl].insts.size(); ++i) + for (const auto& w : blocks[bl].insts[i].writes) defs.insert_or_assign(w.second, std::pair{bl, i}); + } + first.assign(blocks.size(), Bool::False); + when.assign(blocks.size(), std::nullopt); + wave_any.assign(blocks.size(), std::nullopt); +} + +void Lanes::reset() +{ + b = Bools(); + masks.clear(); + other.clear(); + seen.clear(); + scc_lane.clear(); + scc_every.clear(); + std::fill(wave_any.begin(), wave_any.end(), std::nullopt); + joins.clear(); + phi_joins.clear(); + phi_join_ids.clear(); + std::fill(first.begin(), first.end(), Bool::False); + std::fill(when.begin(), when.end(), std::nullopt); + active.clear(); +} + +template <class F> +std::optional<Key> Lanes::key(F value, std::uint8_t code) const +{ + const std::optional<Value> lo = value(Reg::S(code)); + if (!lo) return std::nullopt; + Value hi = *lo; + if (p->wave64) { + const std::optional<Value> h = value(Reg::S(static_cast<std::uint8_t>(code + 1))); + if (!h) return std::nullopt; + hi = *h; + } + return Key{*lo, hi}; +} + +#define READS [&inst](Reg r) { return inst.read(r); } +#define WRITES [&inst](Reg r) { return inst.write(r); } + +std::vector<std::vector<std::optional<Bool>>> Lanes::masks_in_order() +{ + const Program& prog = *p; + auto input = [&](Reg reg) -> std::optional<Value> { + for (const auto& i : prog.inputs) + if (i.first == reg) return i.second; + return std::nullopt; + }; + if (const auto lo = input(Reg::S(ir::EXEC))) { + const Value hi = prog.wave64 ? input(Reg::S(ir::EXEC + 1)).value_or(*lo) : *lo; + masks.insert_or_assign(Key{*lo, hi}, Bool::True); + active.insert(*lo); + } + std::vector<std::vector<std::optional<Bool>>> execs; + for (const auto& blk : prog.blocks) execs.emplace_back(blk.insts.size()); + for (std::size_t n = 0; n < order.size(); ++n) { + const std::size_t bl = order[n]; + Bool c = n == 0 ? Bool::True : Bool::False; + for (std::size_t k = 0; k < incoming[bl].size(); ++k) { + const auto [q, taken] = incoming[bl][k]; + if (index[q] < n) { + const Bool e = edge(first[q], q, taken); + c = b.or_(c, e); + } + } + first[bl] = c; + // EXEC joined at the block's entry holds the lanes that arrive. + for (const auto& phi : prog.blocks[bl].phis) + if (phi.reg == Reg::S(ir::EXEC)) active.insert(phi.value); + // EXEC where known in this block (read or written so far). + std::optional<Bool> now; + const auto& insts = prog.blocks[bl].insts; + for (std::size_t i = 0; i < insts.size(); ++i) { + const Inst& inst = insts[i]; + if (inst.read(Reg::S(ir::EXEC))) { + const Bool e = exec(inst); + execs[bl][i] = e; + now = e; + } + step(inst, now); + if (const auto k = key(WRITES, ir::EXEC)) { + if (const auto it = masks.find(*k); it != masks.end()) + now = it->second; + else if (const auto jt = other.find(*k); jt != other.end()) + now = jt->second; + else + now = std::nullopt; + } + } + if (prog.blocks[bl].exit.is_branch() && !insts.empty()) { + const Inst& last = insts.back(); + when[bl] = branch(last); + wave_any[bl] = wave_kind(last); + } + } + return execs; +} + +// `c` narrowed by the branch at the end of `q` towards one successor. +Bool Lanes::edge(Bool c, std::size_t q, bool taken) +{ + if (wide.count(q)) { + // the wave's decision: it says nothing about this lane's own bit + return c; + } + const std::optional<Bool> w = when[q]; + if (!w) return c; + if (taken) return b.and_(c, *w); + const Bool nw = b.not_(*w); + return b.and_(c, nw); +} + +// Joins whose constant fails on some edge, and joins that need another pass because a later edge +// turned out to derive from EXEC or VALU. +std::pair<std::vector<Value>, std::vector<Value>> Lanes::check_joins(const std::vector<Bool>& cond) +{ + std::vector<Value> wrong; + std::vector<Value> new_derived; + ValueSet seen_derived; + std::size_t j = 0; + std::size_t pj = 0; + // Checking an argument can resolve another join; it is checked too. + while (j < joins.size() || pj < phi_joins.size()) { + while (j < joins.size()) { + const std::size_t block = joins[j].block; + const Value id = joins[j].id; + const bool value = joins[j].value; + const bool was_derived = joins[j].derived; + bool failed = false; + const std::vector<Key> args = joins[j].args; + for (std::size_t n = 0; n < args.size(); ++n) { + const auto [q, taken] = incoming[block].at(n); + const Bool e = edge(cond[q], q, taken); + auto [m, d] = mask(args[n]); + if (!was_derived && d && !derived_phis.count(id) && seen_derived.insert(id).second) + new_derived.push_back(id); + if (!value) m = b.not_(m); + if (!failed && !b.implies(e, m)) { + wrong.push_back(id); + failed = true; + } + } + ++j; + } + while (pj < phi_joins.size()) { + const Value id = phi_joins[pj].id; + const bool was_derived = phi_joins[pj].derived; + const std::vector<Key> args = phi_joins[pj].args; + for (const Key& a : args) { + const bool d = mask(a).second; + if (!was_derived && d && !derived_phis.count(id) && seen_derived.insert(id).second) + new_derived.push_back(id); + } + ++pj; + } + } + return {wrong, new_derived}; +} + +Structured Lanes::finish(const std::vector<std::vector<std::optional<Bool>>>& execs, const std::vector<Bool>& cond) +{ + std::vector<PhiJoin> pjs = std::move(phi_joins); + phi_joins.clear(); + ValueMap<std::vector<Bool>> phi_masks; + for (PhiJoin& pj : pjs) { + std::vector<Bool> in; + for (std::size_t n = 0; n < pj.args.size(); ++n) { + const auto [q, taken] = incoming[pj.block].at(n); + const Bool e = edge(cond[q], q, taken); + const Bool m = mask(pj.args[n]).first; + in.push_back(b.given(m, e)); + } + phi_masks.insert_or_assign(pj.id, std::move(in)); + } + const auto& blocks = p->blocks; + std::vector<std::vector<std::optional<Bool>>> guards; + for (std::size_t n = 0; n < blocks.size(); ++n) { + // Reachability is fixed within the block. Vector instructions with the same EXEC therefore + // need the same guard. + std::optional<std::pair<Bool, std::optional<Bool>>> last_guard; + std::vector<std::optional<Bool>> row; + const auto& insts = blocks[n].insts; + for (std::size_t i = 0; i < insts.size(); ++i) { + const std::optional<Bool>& ex = execs[n][i]; + const auto& f = insts[i].fields; + const bool scalar = std::holds_alternative<gfx10::Sop>(f) || std::holds_alternative<gfx10::Sopp>(f) || + std::holds_alternative<gfx10::Smem>(f); + if (!ex || scalar) { + row.push_back(std::nullopt); + continue; + } + const Bool e = *ex; + if (last_guard && last_guard->first == e) { + row.push_back(last_guard->second); + continue; + } + std::optional<Bool> guard; + if (!b.implies(cond[n], e)) guard = b.given(e, cond[n]); + last_guard = std::pair{e, guard}; + row.push_back(guard); + } + guards.push_back(std::move(row)); + } + std::vector<LaneExit> exits; + for (std::size_t n = 0; n < blocks.size(); ++n) { + const Exit& x = blocks[n].exit; + switch (x.kind) { + case Exit::Kind::Jump: exits.push_back(LaneExit::Jump(x.target)); break; + case Exit::Kind::End: exits.push_back(LaneExit::End()); break; + case Exit::Kind::Indirect: exits.push_back(LaneExit::Indirect()); break; + case Exit::Kind::Branch: { + const Bool w = b.given(when[n].value_or(Bool::False), cond[n]); + exits.push_back(LaneExit::Branch(w, x.taken, x.not_taken)); + break; + } + } + } + if (b.overflow()) throw too_large(); + // Exports go by low dword. A low dword read with two high dwords (one rewritten alone) names no + // one mask: it is left out, so lowering refuses what reads it instead of taking the other pair's + // lanes 32-63. Not where the low dword holds a number: see the shortcut in `mask`. + ValueMap<Value> high; + ValueSet split; + auto note = [&](const Key& k) { + const auto [it, inserted] = high.try_emplace(k.first, k.second); + if (it->second != k.second) split.insert(k.first); + }; + for (const auto& kv : masks) note(kv.first); + for (const auto& kv : other) note(kv.first); + for (const Key& k : seen) note(k); + for (auto it = masks.begin(); it != masks.end();) { + if (split.count(it->first.first)) + it = masks.erase(it); + else + ++it; + } + for (auto it = active.begin(); it != active.end();) { + if (split.count(*it)) + it = active.erase(it); + else + ++it; + } + Structured s; + for (const auto& [k, m] : masks) s.masks.insert_or_assign(k.first, m); + // Iterate keys in sorted order so that if two low dwords share a high dword, the larger low dword wins. + std::vector<Key> keys; + for (const auto& kv : masks) keys.push_back(kv.first); + std::sort(keys.begin(), keys.end()); + for (const Key& k : keys) + if (k.first != k.second) s.highs.insert_or_assign(k.second, k.first); + if (p->wave64) s.paired_masks = masks; + s.active = active; + s.wide = wide; + s.wave_any = wave_any; + for (const auto& [scc, m] : scc_lane) + if (!scc_every.count(scc)) s.scc_some.insert_or_assign(scc, m); + s.phi_masks = std::move(phi_masks); + s.bools = std::move(b); + s.exits = std::move(exits); + s.guards = std::move(guards); + s.reach = cond; + return s; +} + +std::size_t Lanes::born(Value v) const +{ + if (const auto d = lookup(defs, v)) return index[d->first]; + if (const auto f = lookup(phis, v)) return index[f->first]; + return 0; +} + +Bool Lanes::exec(const Inst& inst) +{ + if (const auto k = key(READS, ir::EXEC)) return mask(*k).first; + return Bool::True; +} + +// The mask a value pair holds, and whether it derives from EXEC or a VALU result. +std::pair<Bool, bool> Lanes::mask(Key k) +{ + if (const auto it = masks.find(k); it != masks.end()) return {it->second, true}; + if (const auto it = other.find(k); it != other.end()) return {it->second, false}; + const Program& prog = *p; + std::pair<Bool, bool> result; + if (const auto j = join(k)) { + result = *j; + } else { + const auto lo = lookup(defs, k.first); + const auto hi = lookup(defs, k.second); + std::optional<Bool> m; + if (lo && hi && *lo == *hi) { + if (const Inst* i = def_of(prog, lo)) { + if (const auto r = sop(*i)) { + if (r->dst) m = r->dst->second; + } + } + } + // What an EXEC write the pass does not follow leaves there. + auto exec_write = [&](std::optional<std::pair<std::size_t, std::size_t>> d, Value v) { + const Inst* i = def_of(prog, d); + return i && (i->write(Reg::S(ir::EXEC)) == v || i->write(Reg::S(ir::EXEC + 1)) == v); + }; + const bool derived = exec_write(lo, k.first) || exec_write(hi, k.second); + // shortcut: the atom names the pair by its low dword, and lowering takes the high dword + // written beside it. For halves written apart (two `s_mov_b32`) lanes 32-63 are wrong unless + // lowering has no value for the low dword (EXEC, compares) and refuses. Give the atom both + // dwords when such code turns up. + if (!m) { + const std::size_t bn = born(k.first); + m = b.atom(Atom::Opaque(k.first), bn); + } + result = {*m, derived}; + } + auto& cache = result.second ? masks : other; + cache.insert_or_assign(k, result.first); + return result; +} + +// A mask joined by phis at a block entry, and whether a mask coming in on a forward edge derives +// from EXEC or a VALU result. Where every lane arriving so far has the incoming mask set (or clear), +// the join is that constant, for a lane can only read it after arriving. +std::optional<std::pair<Bool, bool>> Lanes::join(Key k) +{ + const Program& prog = *p; + const auto lo = lookup(phis, k.first); + const auto hi = lookup(phis, k.second); + std::size_t block; + if (lo && hi && lo->first != hi->first) return std::nullopt; + if (lo) + block = lo->first; + else if (hi) + block = hi->first; + else + return std::nullopt; + const ir::Block& target = prog.blocks[block]; + auto arg = [&](std::optional<std::pair<std::size_t, std::size_t>> phi, Value own, std::size_t n) { + return phi ? target.phis[phi->second].args.at(n) : own; + }; + std::vector<Key> args; + for (std::size_t n = 0; n < target.preds.size(); ++n) args.push_back(Key{arg(lo, k.first, n), arg(hi, k.second, n)}); + const Value id = lo ? k.first : k.second; + bool derived = derived_phis.count(id) != 0; + // (edge condition, mask) per forward edge; back edges come later. + std::vector<std::pair<Bool, Bool>> forward; + for (std::size_t n = 0; n < args.size(); ++n) { + const auto [q, taken] = incoming[block].at(n); + if (index[q] < index[block]) { + const auto [m, d] = mask(args[n]); + derived |= d; + const Bool e = edge(first[q], q, taken); + forward.push_back({e, m}); + } else { + seen.push_back(args[n]); + } + } + if (forward.size() == args.size() && !forward.empty()) { + const Bool m = forward.front().second; + if (std::all_of(forward.begin(), forward.end(), [&](const auto& f) { return f.second == m; })) + return std::pair{m, derived}; + } + if (!unresolved.count(id)) { + for (const bool value : {true, false}) { + bool holds = true; + for (const auto& [e, m0] : forward) { + const Bool m = value ? m0 : b.not_(m0); + if (!b.implies(e, m)) { + holds = false; + break; + } + } + if (holds) { + joins.push_back(Join{block, id, value, derived, args}); + return std::pair{value ? Bool::True : Bool::False, derived}; + } + } + } + if (phi_join_ids.insert(id).second) phi_joins.push_back(PhiJoin{block, id, derived, args}); + const std::size_t bn = index[block]; + const Bool a = b.atom(Atom::Phi(id), bn); + return std::pair{a, derived}; +} + +std::optional<std::pair<Bool, bool>> Lanes::operand(const Inst& inst, const Operand& op) +{ + const bool wave64 = p->wave64; + auto constant = [&](std::uint64_t v) { + v = wave64 ? v : (v & 0xFFFF'FFFFull); + if (v == 0) return Bool::False; + if (v == (~std::uint64_t{0} >> (32 * (wave64 ? 0 : 1)))) return Bool::True; + return b.atom(Atom::Constant(v), 0); + }; + switch (op.kind) { + case Operand::Kind::Scalar: { + if (op.code == gfx10::NULL_CODE) return std::nullopt; + const auto k = key(READS, op.code); + if (!k) return std::nullopt; + return mask(*k); + } + case Operand::Kind::Const: { + if (op.code < 128 || op.code > 208) return std::nullopt; + const std::int64_t v = op.code <= 192 ? std::int64_t{op.code} - 128 : 192 - std::int64_t{op.code}; + return std::pair{constant(static_cast<std::uint64_t>(v)), false}; + } + case Operand::Kind::Literal: return std::pair{constant(std::uint64_t{op.literal}), false}; + default: return std::nullopt; + } +} + +// Lane-mask meaning of a lane-width scalar operation. +std::optional<SopMasks> Lanes::sop(const Inst& inst) +{ + const auto* f = std::get_if<gfx10::Sop>(&inst.fields); + if (!f) return std::nullopt; + const std::string_view width = p->wave64 ? "_b64" : "_b32"; + const auto op0 = strip_prefix(inst.name(), "s_"); + if (!op0) return std::nullopt; + const auto op1 = strip_suffix(*op0, width); + if (!op1) return std::nullopt; + const std::string_view op = *op1; + std::optional<Key> dst; + if (f->dst && f->dst->is_scalar() && f->dst->code != gfx10::NULL_CODE) dst = key(WRITES, f->dst->code); + const std::optional<Key> exec_out = key(WRITES, ir::EXEC); + std::optional<bool> save; + std::string_view fn = op; + if (const auto s = strip_suffix(op, "_saveexec")) { + save = true; + fn = *s; + } else if (const auto w = strip_suffix(op, "_wrexec")) { + save = false; + fn = *w; + } + bool derived = exec_out.has_value() || save.has_value(); + auto arg = [&](std::size_t n) -> std::optional<Bool> { + if (n >= f->src.size()) return std::nullopt; + const auto r = operand(inst, f->src[n]); + if (!r) return std::nullopt; + derived |= r->second; + return r->first; + }; + auto with = [&](const std::optional<Key>& k, Bool m) -> std::optional<std::pair<Key, Bool>> { + if (!k) return std::nullopt; + return std::pair{*k, m}; + }; + if (save) { + const auto s = arg(0); + if (!s) return std::nullopt; + const Bool ex = exec(inst); + const auto nw = combine(fn, *s, ex); + if (!nw) return std::nullopt; + const Bool saved = *save ? ex : *nw; + return SopMasks{with(dst, saved), with(exec_out, *nw), derived, *nw}; + } + Bool result; + std::optional<Bool> scc; + if (op == "mov") { + const auto a = arg(0); + if (!a) return std::nullopt; + result = *a; + } else if (op == "not") { + const auto a = arg(0); + if (!a) return std::nullopt; + result = b.not_(*a); + scc = result; + } else if (op == "wqm") { + const auto a = arg(0); + if (!a) return std::nullopt; + const std::optional<Key> d = dst ? dst : exec_out; + if (!d) return std::nullopt; + const Value lo = d->first; + const std::size_t bn = born(lo); + const Bool q = b.atom(Atom::Quad(lo), bn); + result = b.or_(*a, q); + scc = result; + } else if (op == "cselect") { + const auto a = arg(0); + if (!a) return std::nullopt; + const auto c = arg(1); + if (!c) return std::nullopt; + const auto s = inst.read(Reg::Scc); + if (!s) return std::nullopt; + if (clear_after_loop(*s)) { + result = *c; + } else { + const std::size_t bn = born(*s); + const Bool u = b.atom(Atom::Uniform(*s), bn); + result = b.ite(u, *a, *c); + } + } else { + const auto a = arg(0); + if (!a) return std::nullopt; + const auto c = arg(1); + if (!c) return std::nullopt; + const auto r = combine(op, *a, *c); + if (!r) return std::nullopt; + result = *r; + scc = result; + } + return SopMasks{with(dst, result), with(exec_out, result), derived, scc}; +} + +// Whether SCC value `scc` is clear wherever it is read: the instruction before an +// `s_cbranch_execnz` that closes a loop wrote it as "the EXEC it leaves is not empty" +// (`s_andn2_wrexec`, say), and the wave leaves `do { .. } while (EXEC)` with EXEC empty. A read +// inside the loop or behind another way out of it sees a join of this value, not the value itself. +bool Lanes::clear_after_loop(Value scc) const +{ + const auto d = lookup(defs, scc); + if (!d) return false; + const auto [bl, i] = *d; + const ir::Block& block = p->blocks[bl]; + if (i >= block.insts.size() || block.insts.empty()) return false; + const Inst& writer = block.insts[i]; + const Inst& last = block.insts.back(); + const std::optional<Value> ex = writer.write(Reg::S(ir::EXEC)); + const bool back = block.exit.is_branch() && index[block.exit.taken] <= index[bl]; + return back && i + 2 == block.insts.size() && ex.has_value() && last.name() == "s_cbranch_execnz" && + last.read(Reg::S(ir::EXEC)) == ex && + (!p->wave64 || last.read(Reg::S(ir::EXEC + 1)) == writer.write(Reg::S(ir::EXEC + 1))); +} + +std::optional<Bool> Lanes::combine(std::string_view f, Bool a, Bool c) +{ + if (f == "and") return b.and_(a, c); + if (f == "or") return b.or_(a, c); + if (f == "xor") return b.xor_(a, c); + if (f == "andn2") { + const Bool nc = b.not_(c); + return b.and_(a, nc); + } + if (f == "orn2") { + const Bool nc = b.not_(c); + return b.or_(a, nc); + } + if (f == "andn1") { + const Bool na = b.not_(a); + return b.and_(na, c); + } + if (f == "orn1") { + const Bool na = b.not_(a); + return b.or_(na, c); + } + if (f == "nand") { + const Bool r = b.and_(a, c); + return b.not_(r); + } + if (f == "nor") { + const Bool r = b.or_(a, c); + return b.not_(r); + } + if (f == "xnor") { + const Bool r = b.xor_(a, c); + return b.not_(r); + } + return std::nullopt; +} + +// Records the masks `inst` defines; `exec` is EXEC there, if known. +void Lanes::step(const Inst& inst, std::optional<Bool> exec_now) +{ + const std::string_view name = inst.name(); + if (const auto* f = std::get_if<gfx10::Sop>(&inst.fields)) { + bool takes_mask = false; + for (const Operand& s : f->src) { + if (!s.is_scalar() || s.code == gfx10::NULL_CODE) continue; + const auto k = key(READS, s.code); + if (!k) continue; + const bool phi = phis.count(k->first) || phis.count(k->second); + bool t = masks.count(*k) != 0; + if (!t && phi) t = mask(*k).second; + takes_mask |= t; + } + const bool touches_exec = inst.write(Reg::S(ir::EXEC)).has_value() || inst.read(Reg::S(ir::EXEC)).has_value(); + if (takes_mask || touches_exec) { + const auto r = sop(inst); + if (r && r->derived) { + std::vector<std::pair<Key, Bool>> outs; + if (r->dst) outs.push_back(*r->dst); + if (r->exec) outs.push_back(*r->exec); + for (const auto& [k, m] : outs) { + masks.insert_or_assign(k, m); + // EXEC itself holds the lanes that run here. + bool act = r->exec && r->exec->first == k; + if (!act && exec_now) act = b.implies(m, *exec_now); + if (act) active.insert(k.first); + } + const auto scc = inst.write(Reg::Scc); + if (scc && r->scc) scc_lane.insert_or_assign(*scc, *r->scc); + } + } + // `s_cmp_eq/lg` of a mask: "no lane differs" per lane. + const std::string_view width = p->wave64 ? "64" : "32"; + if (takes_mask) { + const auto rest = strip_prefix(name, "s_cmp_"); + const auto scc = inst.write(Reg::Scc); + if (rest && scc) { + const auto r = strip_suffix(*rest, width); + if (r && (*r == "eq_u" || *r == "lg_u") && f->src.size() == 2) { + const auto a = operand(inst, f->src[0]); + const auto c = operand(inst, f->src[1]); + if (a && c) { + const Bool ne = b.xor_(a->first, c->first); + const bool eq = rest->starts_with("eq"); + const Bool m = eq ? b.not_(ne) : ne; + scc_lane.insert_or_assign(*scc, m); + if (eq) scc_every.insert(*scc); + } + } + } + } + // `s_bcnt1` of a mask every running lane sees alike (EXEC under a scalar condition, or EXEC + // itself): its SCC, "some lane is set", is each lane's own bit. A branch on it then reads no + // ballot. + if (takes_mask && name.starts_with("s_bcnt1_i32_b")) { + const auto scc = inst.write(Reg::Scc); + if (scc && f->src.size() == 1) { + const auto a = operand(inst, f->src[0]); + if (a && a->second) { + const Bool m = a->first; + const Bool e = exec_now.value_or(Bool::True); + const Bool own = b.given(m, e); + if (b.implies(m, e)) { + const auto sup = b.support(own); + if (std::all_of(sup.begin(), sup.end(), [](const Atom& x) { return x.kind == Atom::Kind::Uniform; })) + scc_lane.insert_or_assign(*scc, own); + } + } + } + } + return; + } + if (const auto* v = std::get_if<gfx10::Valu>(&inst.fields)) { + const Bool ex = exec(inst); + auto lane = [&](const Key& k) { + const std::size_t bn = born(k.first); + const Bool a = b.atom(Atom::Lane(k.first), bn); + const Bool m = b.and_(ex, a); + masks.insert_or_assign(k, m); + active.insert(k.first); + }; + // A select reads a mask nothing else may: a join of compare results is resolved here, as for + // EXEC. A carry-in is only recorded for `finish`: resolving its join would turn a refusal into + // a per-lane phi, wrong after a divergent branch. + if ((name == "v_cndmask_b32" || name.find("_co_ci_") != std::string_view::npos) && v->src.size() > 2 && + v->src[2].is_scalar() && v->src[2].code != gfx10::NULL_CODE) { + if (const auto k = key(READS, v->src[2].code)) { + if (name == "v_cndmask_b32") + mask(*k); + else + seen.push_back(*k); + } + } + if (name == "v_div_fmas_f32" || name == "v_div_fmas_f64") { + if (const auto k = key(READS, ir::VCC)) mask(*k); + } + if (name.starts_with("v_cmpx")) { + if (const auto k = key(WRITES, ir::EXEC)) lane(*k); + } else { + std::vector<Operand> ops; + if (v->dst && name.starts_with("v_cmp")) ops.push_back(*v->dst); + if (v->carry) ops.push_back(*v->carry); + for (const Operand& o : ops) { + if (!o.is_scalar()) continue; + if (const auto k = key(WRITES, o.code)) lane(*k); + } + } + } +} + +// How the console decides the branch `inst` on a lane mask, in terms of the lanes' own `when` +// (branch): taken when some lane's holds (true) or when every lane's does (false). nullopt for a +// branch on a scalar condition. +std::optional<bool> Lanes::wave_kind(const Inst& inst) const +{ + const std::string_view n = inst.name(); + if (n == "s_cbranch_execnz" || n == "s_cbranch_vccnz") return true; + if (n == "s_cbranch_execz" || n == "s_cbranch_vccz") return false; + if (n == "s_cbranch_scc0" || n == "s_cbranch_scc1") { + const auto scc = inst.read(Reg::Scc); + if (!scc) return std::nullopt; + if (!scc_lane.count(*scc)) return std::nullopt; + // set: SCC is 1 when some lane's bit is set (every lane's, for a compare) + const bool every = scc_every.count(*scc) != 0; + return (n == "s_cbranch_scc1") != every; + } + return std::nullopt; +} + +// The per-lane condition under which a block's closing branch is taken. +Bool Lanes::branch(const Inst& inst) +{ + const Bool ex = exec(inst); + const std::string_view n = inst.name(); + if (n == "s_cbranch_execz") return b.not_(ex); + if (n == "s_cbranch_execnz") return ex; + if (n == "s_cbranch_vccz" || n == "s_cbranch_vccnz") { + Bool vcc = Bool::False; + if (const auto k = key(READS, ir::VCC)) vcc = mask(*k).first; + const Bool any = b.and_(vcc, ex); + return n.ends_with("nz") ? any : b.not_(any); + } + const auto scc = inst.read(Reg::Scc); + if (!scc) return Bool::False; + Bool set; + if (const auto it = scc_lane.find(*scc); it != scc_lane.end()) { + set = it->second; + } else { + const std::size_t bn = born(*scc); + set = b.atom(Atom::Uniform(*scc), bn); + } + return n == "s_cbranch_scc1" ? set : b.not_(set); +} + +// What a lane knows on entering each block, to a fixpoint. A loop header forgets what the back edge +// says about atoms the loop redefines. +std::vector<Bool> Lanes::paths() +{ + const std::size_t n = p->blocks.size(); + std::vector<Bool> cond(n, Bool::False); + if (!order.empty()) cond[order.front()] = Bool::True; + for (std::size_t round = 0; round < MAX_ROUNDS; ++round) { + bool changed = false; + for (std::size_t i = 1; i < order.size(); ++i) { + const std::size_t s = order[i]; + Bool c = Bool::False; + for (std::size_t k = 0; k < incoming[s].size(); ++k) { + const auto [q, taken] = incoming[s][k]; + Bool e = edge(cond[q], q, taken); + if (i <= index[q]) { + BoolMemo memo; + e = b.forget(e, i, memo); + } + c = b.or_(c, e); + } + if (c != cond[s]) { + cond[s] = c; + changed = true; + } + } + if (b.overflow()) throw too_large(); + if (!changed) return cond; + } + throw ShaderError::isa(0, "lane conditions do not settle"); +} + +#undef READS +#undef WRITES + +} // namespace + +Structured structure(const Program& program) { return structure_wide(program, {}); } + +Structured structure_wide(const Program& program, const std::set<std::size_t>& wide) +{ + Lanes l(program); + l.wide = wide; + for (;;) { + const auto execs = l.masks_in_order(); + const auto cond = l.paths(); + auto [wrong, new_derived] = l.check_joins(cond); + if (l.b.overflow()) throw too_large(); + if (wrong.empty() && new_derived.empty()) return l.finish(execs, cond); + for (Value v : wrong) l.unresolved.insert(v); + for (Value v : new_derived) l.derived_phis.insert(v); + l.reset(); + } +} + +} // namespace x2w::vs::structure diff --git a/src/x2w_shader/structure.h b/src/x2w_shader/structure.h new file mode 100644 index 0000000000..e856ce938e --- /dev/null +++ b/src/x2w_shader/structure.h @@ -0,0 +1,248 @@ +// Control-flow structurisation: the program as one lane runs it, without EXEC. +// +// Lane masks (EXEC, compare and carry results, the SGPRs they are saved in) become per-lane booleans +// (Bools). A branch on a wave-wide test of a mask (`s_cbranch_execz`, `vccz`, SCC of a mask +// operation) becomes a branch on the lane's own bit: compiled code only skips work that lanes +// outside the mask would not change, or tests a value that is the same in every lane, so either way +// each lane can decide alone. A path-sensitive pass then proves, for each vector instruction, that +// EXEC holds in every lane that reaches it; what it cannot prove stays as the instruction's guard, a +// per-lane `if` around it. +// +// The control-flow graph keeps its shape and must be reducible (DXIL's only requirement). Helper +// lanes of a pixel shader count as live: on PC their side effects are dropped too, and what they +// compute is only read through derivatives. +#pragma once + +#include <cstddef> +#include <cstdint> +#include <optional> +#include <set> +#include <tuple> +#include <unordered_map> +#include <unordered_set> +#include <utility> +#include <vector> + +#include "x2w_shader/error.h" +#include "x2w_shader/front_hash.h" +#include "x2w_shader/ir.h" + +namespace x2w::vs::structure { + +// A per-lane boolean node. Equal functions share a node. Bool::False and Bool::True avoid the macros in +// windows.h. +struct Bool { + std::uint32_t n = 0; + static const Bool False; + static const Bool True; + constexpr bool operator==(const Bool&) const = default; + constexpr auto operator<=>(const Bool&) const = default; +}; +inline constexpr Bool Bool::False = {0}; +inline constexpr Bool Bool::True = {1}; + +struct BoolHash { + std::size_t operator()(Bool b) const { return static_cast<std::size_t>(fhash::mix(0, b.n)); } +}; + +// Meaning of a variable in Bools. Unused members stay zero. +struct Atom { + enum class Kind : std::uint8_t { + // The lane's bit of the compare or carry result in this VALU-written value, before EXEC + // masking. + Lane, + // An SCC value, the same in every lane. + Uniform, + // A lane mask joined at a block entry, by its low dword's phi. + Phi, + // `s_wqm` result: some lane of the quad is in the source mask. + Quad, + // A mask the pass cannot see into (loaded, built from scalars, an EXEC write it does not + // follow): the lane's bit of the register pair this value is a dword of. + Opaque, + // A constant mask other than all lanes or none. + Constant, + }; + Kind kind = Kind::Lane; + ir::Value value; + std::uint64_t constant = 0; + + static constexpr Atom Lane(ir::Value v) { return {Kind::Lane, v, 0}; } + static constexpr Atom Uniform(ir::Value v) { return {Kind::Uniform, v, 0}; } + static constexpr Atom Phi(ir::Value v) { return {Kind::Phi, v, 0}; } + static constexpr Atom Quad(ir::Value v) { return {Kind::Quad, v, 0}; } + static constexpr Atom Opaque(ir::Value v) { return {Kind::Opaque, v, 0}; } + static constexpr Atom Constant(std::uint64_t c) { return {Kind::Constant, {}, c}; } + constexpr bool operator==(const Atom&) const = default; +}; + +struct AtomHash { + std::size_t operator()(const Atom& a) const + { + return static_cast<std::size_t>( + fhash::mix(fhash::mix(fhash::mix(0, static_cast<std::uint64_t>(a.kind)), a.value.n), a.constant)); + } +}; + +// What Bools::meet found out about one Bools, for its later calls: the conditions no lane satisfies, +// and the case splits it took to find that out of each. +struct Meets { + struct KeyHash { + std::size_t operator()(const std::vector<std::uint32_t>& k) const + { + std::uint64_t h = 0; + for (std::uint32_t x : k) h = fhash::mix(h, x); + return static_cast<std::size_t>(fhash::mix(h, k.size())); + } + }; + std::unordered_map<std::vector<std::uint32_t>, std::size_t, KeyHash> none; +}; + +// Case splits Bools::meet makes before it gives up. +inline constexpr std::size_t MAX_MEET = std::size_t{1} << 16; +// Conditions Meets keeps; past that, they are searched anew. +inline constexpr std::size_t MAX_MEETS = std::size_t{1} << 18; + +// Reduced ordered binary decision diagrams over Atoms. +class Bools { +public: + Bools(); + + // The atom tested at the top of `b` and the results when it is false and true; nullopt for the + // constants. + std::optional<std::tuple<Atom, Bool, Bool>> node(Bool b) const; + // The atoms `b` depends on, in variable order. + std::vector<Atom> support(Bool b) const; + + // Whether some lane can satisfy every `(b, holds)` of `all` at once: `b` where `holds`, its + // negation where not. Yes when the search grows too large to finish. + bool meet(const std::vector<std::pair<Bool, bool>>& all) const; + // meet(), which looks up in `seen` what earlier calls on these Bools found out and adds what it + // finds. The answer is the one meet gives. + bool meet_seen(const std::vector<std::pair<Bool, bool>>& all, Meets& seen) const; + + // Internal helpers shared by this module and its tests. + Bool atom(const Atom& atom, std::size_t born); + Bool mk(std::uint32_t v, Bool lo, Bool hi); + std::pair<Bool, Bool> split(Bool b, std::uint32_t v) const; + Bool ite(Bool f, Bool g, Bool h); + Bool and_(Bool a, Bool b); + Bool or_(Bool a, Bool b); + Bool not_(Bool a); + Bool xor_(Bool a, Bool b); + bool meet_within(const std::vector<std::pair<Bool, bool>>& all, std::size_t budget, Meets& seen) const; + bool meet_in(std::size_t at, std::vector<std::uint32_t>& work, std::size_t& budget, Meets& seen) const; + bool implies(Bool a, Bool b); + Bool forget(Bool b, std::size_t from, std::unordered_map<Bool, Bool, BoolHash>& memo); + Bool restrict(Bool b, std::uint32_t v, bool value, std::unordered_map<Bool, Bool, BoolHash>& memo); + Bool given(Bool b, Bool known); + // The variable at the top of `b` (TERMINAL for the constants). + std::uint32_t top(Bool b) const { return std::get<0>(nodes_[b.n]); } + bool overflow() const { return overflow_; } + + static constexpr std::uint32_t TERMINAL = 0xFFFF'FFFFu; + +private: + struct TripleHash { + std::size_t operator()(const std::tuple<std::uint32_t, std::uint32_t, std::uint32_t>& t) const + { + return static_cast<std::size_t>( + fhash::mix(fhash::mix(fhash::mix(0, std::get<0>(t)), std::get<1>(t)), std::get<2>(t))); + } + }; + std::vector<std::uint32_t> vars(Bool b) const; + + // (variable, low, high); nodes 0 and 1 are the constants. + std::vector<std::tuple<std::uint32_t, Bool, Bool>> nodes_; + std::unordered_map<std::tuple<std::uint32_t, std::uint32_t, std::uint32_t>, Bool, TripleHash> unique_; + std::unordered_map<std::tuple<std::uint32_t, std::uint32_t, std::uint32_t>, Bool, TripleHash> memo_; + std::vector<Atom> atoms_; + // Reverse-postorder index of the block that defines each atom. + std::vector<std::size_t> born_; + std::unordered_map<Atom, std::uint32_t, AtomHash> ids_; + bool overflow_ = false; +}; + +// How a lane leaves a block. +struct LaneExit { + enum class Kind : std::uint8_t { + Jump, + // To `taken` in lanes where `when` holds. A condition over Atom::Uniform only is a uniform + // branch. + Branch, + End, + Indirect, + }; + Kind kind = Kind::End; + std::size_t target = 0; // Jump + Bool when; // Branch + std::size_t taken = 0; + std::size_t not_taken = 0; + + static constexpr LaneExit Jump(std::size_t t) { return {Kind::Jump, t, {}, 0, 0}; } + static constexpr LaneExit Branch(Bool when, std::size_t taken, std::size_t not_taken) + { + return {Kind::Branch, 0, when, taken, not_taken}; + } + static constexpr LaneExit End() { return {Kind::End, 0, {}, 0, 0}; } + static constexpr LaneExit Indirect() { return {Kind::Indirect, 0, {}, 0, 0}; } + constexpr bool is_branch() const { return kind == Kind::Branch; } + constexpr bool operator==(const LaneExit&) const = default; +}; + +using ValueHash = fhash::ValueHash; +// A lane mask by the values of its low and high dword (both the low one in wave32). +using Key = std::pair<ir::Value, ir::Value>; + +// A Program as one lane runs it: same blocks, per-lane branches. +struct Structured { + Bools bools; + // Per block. + std::vector<LaneExit> exits; + // Per block and instruction: the condition, beyond reaching it, under which a lane runs a vector + // instruction; nullopt when reaching it is enough (lanes outside EXEC then never get there, so a + // VGPR write needs no old value). Always nullopt for scalar instructions. + std::vector<std::vector<std::optional<Bool>>> guards; + // Per block: what holds in every lane that enters it (over forward edges; a loop header forgets + // what its loop redefines). + std::vector<Bool> reach; + // The lane's bit of each lane-mask value, by its low dword's value. + std::unordered_map<ir::Value, Bool, ValueHash> masks; + // Exact Wave64 pairs for checking masks at their uses. See mask_bits. + std::unordered_map<Key, Bool, fhash::ValuePairHash> paired_masks; + // Wave64 masks: low dword's value by the high dword's. + std::unordered_map<ir::Value, ir::Value, ValueHash> highs; + // Masks (low dwords) set only in lanes whose EXEC bit is set where they are written: every such + // lane reaches the writing block, so a ballot there gives the mask as data. No split low dword, + // as in `masks`. + std::unordered_set<ir::Value, ValueHash> active; + // Incoming lane boolean per predecessor edge (in block predecessor order) for each Atom::Phi id. + std::unordered_map<ir::Value, std::vector<Bool>, ValueHash> phi_masks; + // Blocks whose closing branch the whole wave takes together (structure_wide): its `when` is + // still the lane's own bit; the wave goes by all of them. + std::set<std::size_t> wide; + // Per block closed by a branch on a lane mask: whether the console takes it when some lane's + // `when` holds (true) or when every lane's does (false). + std::vector<std::optional<bool>> wave_any; + // SCC values a mask operation sets when some lane's bit of its result is set, with that lane + // bit: as data such an SCC is "some lane of the wave has it". + std::unordered_map<ir::Value, Bool, ValueHash> scc_some; + + // The lane bit of the mask whose dwords are `low` and `high` (`high` nullopt: by the low dword + // alone, as wave32 masks are) (pub(crate)). + std::optional<Bool> mask_bits(ir::Value low, std::optional<ir::Value> high) const; +}; + +// Builds the per-lane form of `program`. Throws ShaderError. +Structured structure(const ir::Program& program); + +// structure(), with the branches that close the blocks of `wide` kept as the console has them: one +// decision for the whole wave (`s_cbranch_execz` and `vccz`: taken when no lane's bit is set; +// `execnz` and `vccnz`: when some lane's is; SCC of a mask operation likewise, +// Structured::wave_any), which every lane follows. A lane then learns nothing about its own bit from +// the way it went, so past such a branch EXEC stays a guard on every vector instruction, as it is on +// the console. For a console wave run as two host waves, which exchange that decision and can then +// meet (a group barrier) inside the branch. +Structured structure_wide(const ir::Program& program, const std::set<std::size_t>& wide); + +} // namespace x2w::vs::structure diff --git a/src/xmem_census.cpp b/src/xmem_census.cpp new file mode 100644 index 0000000000..55a696a890 --- /dev/null +++ b/src/xmem_census.cpp @@ -0,0 +1,491 @@ +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include <windows.h> +#include <psapi.h> +#include <dxgi1_4.h> +#include <wrl/client.h> + +#include "xmem_census.h" +#include "startup_stubs/local_log.h" + +#include <algorithm> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <vector> + +namespace { +constexpr ULONGLONG mib = 1ull << 20; + +ULONGLONG system_commit(ULONGLONG* limit) noexcept +{ + PERFORMANCE_INFORMATION info{}; + info.cb = sizeof(info); + if (!GetPerformanceInfo(&info, sizeof(info))) return 0; + if (limit) *limit = static_cast<ULONGLONG>(info.CommitLimit) * info.PageSize; + return static_cast<ULONGLONG>(info.CommitTotal) * info.PageSize; +} + +// The system commit when xmem.dll was loaded: the reference for "this run". +const ULONGLONG commit_at_load = system_commit(nullptr); +const ULONGLONG tick_at_load = GetTickCount64(); + +SRWLOCK block_lock = SRWLOCK_INIT; +std::vector<std::pair<ULONG_PTR, SIZE_T>>* blocks; // sorted by base when the census reads it + +int append(char* out, int at, int capacity, const char* format, ...) noexcept +{ + if (at >= capacity - 1) return at; + va_list args; + va_start(args, format); + const int n = std::vsnprintf(out + at, static_cast<size_t>(capacity - at), format, args); + va_end(args); + if (n < 0) return at; + return std::min(capacity - 1, at + n); +} + +// GPU memory of this process per adapter that has some (DXGI segment groups). +int gpu_text(char* out, int at, int capacity) noexcept +{ + Microsoft::WRL::ComPtr<IDXGIFactory1> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return append(out, at, capacity, " gpu unknown"); + Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter; + bool any = false; + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) { + Microsoft::WRL::ComPtr<IDXGIAdapter3> three; + if (FAILED(adapter.As(&three))) continue; + DXGI_QUERY_VIDEO_MEMORY_INFO local{}, nonlocal{}; + if (FAILED(three->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &local))) continue; + three->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &nonlocal); + if (!local.CurrentUsage && !nonlocal.CurrentUsage) continue; + DXGI_ADAPTER_DESC1 desc{}; + adapter->GetDesc1(&desc); + at = append(out, at, capacity, " gpu%u(%04x) local=%llu/%llu non-local=%llu/%llu MiB", i, desc.DeviceId, + local.CurrentUsage / mib, local.Budget / mib, nonlocal.CurrentUsage / mib, nonlocal.Budget / mib); + any = true; + } + return any ? at : append(out, at, capacity, " gpu none"); +} + +int heap_text(char* out, int at, int capacity) noexcept +{ + HANDLE heaps[256]; + const DWORD n = GetProcessHeaps(256, heaps); + ULONGLONG committed = 0, largest = 0; + DWORD counted = 0; + for (DWORD i = 0; i < n && i < 256; ++i) { + HEAP_SUMMARY summary{}; + summary.cb = sizeof(summary); + if (!HeapSummary(heaps[i], 0, &summary)) continue; + committed += summary.cbCommitted; + largest = std::max<ULONGLONG>(largest, summary.cbCommitted); + ++counted; + } + return append(out, at, capacity, " heaps %lu committed=%llu MiB (largest %llu)", counted, committed / mib, largest / mib); +} + +int block_resident_walk(char* out, int at, int capacity); +int block_resident_text(char* out, int at, int capacity) noexcept +{ + try { + return block_resident_walk(out, at, capacity); + } catch (...) { + return at; // out of memory: no residency text this time + } +} +int block_resident_walk(char* out, int at, int capacity) +{ + std::vector<std::pair<ULONG_PTR, SIZE_T>> known; + AcquireSRWLockShared(&block_lock); + if (blocks) known = *blocks; + ReleaseSRWLockShared(&block_lock); + if (known.empty()) return at; + std::sort(known.begin(), known.end()); + constexpr SIZE_T page = 4096, chunk = 65536; + std::vector<PSAPI_WORKING_SET_EX_INFORMATION> info(chunk); + at = append(out, at, capacity, "; block resident MiB"); + for (const auto& [base, bytes] : known) { + if (bytes < (16ull << 20)) continue; + ULONGLONG resident = 0; + for (SIZE_T done = 0; done < bytes / page;) { + const SIZE_T n = std::min(chunk, bytes / page - done); + for (SIZE_T i = 0; i < n; ++i) info[i].VirtualAddress = reinterpret_cast<void*>(base + (done + i) * page); + if (!QueryWorkingSetEx(GetCurrentProcess(), info.data(), static_cast<DWORD>(n * sizeof(info[0])))) break; + for (SIZE_T i = 0; i < n; ++i) resident += info[i].VirtualAttributes.Valid; + done += n; + } + at = append(out, at, capacity, " %llx:%llu/%llu", static_cast<unsigned long long>(base), resident * page / mib, + static_cast<unsigned long long>(bytes / mib)); + } + return at; +} + +// Counters of other stand-ins (x2w_memory_counters exports). +int stand_in_text(char* out, int at, int capacity) noexcept +{ + HMODULE modules[512]; + DWORD needed = 0; + if (!EnumProcessModules(GetCurrentProcess(), modules, sizeof(modules), &needed)) return at; + const DWORD count = std::min<DWORD>(needed / sizeof(HMODULE), 512); + for (DWORD i = 0; i < count; ++i) { + const auto counters = reinterpret_cast<X2wMemoryCounters>(GetProcAddress(modules[i], "x2w_memory_counters")); + if (!counters) continue; + char name[64]{}; + GetModuleBaseNameA(GetCurrentProcess(), modules[i], name, sizeof(name)); + char text[512]{}; + const int n = counters(text, sizeof(text)); + if (n > 0) at = append(out, at, capacity, "; %s: %s", name, text); + } + return at; +} + +void report(ULONGLONG second) noexcept +{ + char line[1536]; // LOCAL memcut: was 1400; logf's own limit is 1536 + ULONGLONG limit = 0; + const ULONGLONG committed = system_commit(&limit); + PROCESS_MEMORY_COUNTERS_EX counters{}; + counters.cb = sizeof(counters); + GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&counters), sizeof(counters)); + X2wXmemStats x{}; + x2w_xmem_memory_stats(&x); + const long long delta = static_cast<long long>(committed) - static_cast<long long>(commit_at_load); + int at = std::snprintf(line, sizeof(line), + "x2w-mem %llu s: system %+lld MiB since load (committed %llu / limit %llu MiB, headroom %llu); " + "private %llu MiB (peak %llu); slabs %llu = %llu MiB, %llu file-backed, %llu moved for the GPU%s (pages %llu live, %llu free slots%s%llu%s); " + "xmem commits: startup blocks %llu MiB (%llu), permissive %llu MiB (%llu);", + second, delta / static_cast<long long>(mib), committed / mib, limit / mib, + limit > committed ? (limit - committed) / mib : 0, counters.PrivateUsage / mib, + counters.PeakPagefileUsage / mib, x.slabs, x.slab_bytes / mib, x.file_slabs, x.migrations, + x.migration_failures ? " (SOME MOVES FAILED)" : "", x.live_pages, x.free_slots, + x.slab_budget_bytes ? ", budget " : "", x.slab_budget_bytes / mib, + x.slab_refusals ? " MiB, REFUSED pages" : (x.slab_budget_bytes ? " MiB" : ""), + x.startup_block_bytes / mib, x.startup_block_calls, x.permissive_commit_bytes / mib, + x.permissive_commit_calls); + if (at < 0) return; + at = heap_text(line, at, sizeof(line)); + at = gpu_text(line, at, sizeof(line)); + at = stand_in_text(line, at, sizeof(line)); + x2w_local::logf("%s", line); +} + +// LOCAL memcut: X2W_MEM_CENSUS_CLASSES=1 adds an "x2w-mem census-classes" line at each census second: +// committed private memory outside the startup blocks by page protection (4 = read/write, 404 = write- +// combined: the driver's CPU views of GPU allocations and upload heaps), how much of it is resident +// (working set), the mapped views (slabs) with their residency, and the allocations that are new since +// the previous census. Residency is sampled: one page per 64 KiB (title pages are 64 KiB), times 64 KiB. +// Answers: do the desktop GPU copies also occupy RAM, and which allocations keep growing (memcut NOTES). +struct CensusRegion { ULONG_PTR start, base; ULONGLONG bytes; DWORD protect; bool mapped; }; +bool census_classes_on() noexcept +{ + static const bool on = [] { + char v[4]{}; + return GetEnvironmentVariableA("X2W_MEM_CENSUS_CLASSES", v, sizeof(v)) && v[0] == '1'; + }(); + return on; +} +// Resident bytes of [start, start + bytes), one sample per 64 KiB (the whole range when smaller). +ULONGLONG sampled_resident(ULONG_PTR start, ULONGLONG bytes, std::vector<PSAPI_WORKING_SET_EX_INFORMATION>& info) +{ + constexpr ULONGLONG stride = 65536; + const ULONGLONG samples = bytes <= stride ? 1 : (bytes + stride - 1) / stride; + const ULONGLONG weight = bytes <= stride ? bytes : stride; + ULONGLONG valid = 0; + for (ULONGLONG done = 0; done < samples;) { + const ULONGLONG n = std::min<ULONGLONG>(info.size(), samples - done); + for (ULONGLONG i = 0; i < n; ++i) info[i].VirtualAddress = reinterpret_cast<void*>(start + (done + i) * stride); + if (!QueryWorkingSetEx(GetCurrentProcess(), info.data(), static_cast<DWORD>(n * sizeof(info[0])))) break; + for (ULONGLONG i = 0; i < n; ++i) valid += info[i].VirtualAttributes.Valid; + done += n; + } + return std::min(bytes, valid * weight); +} +void census_classes(ULONGLONG second, const std::vector<CensusRegion>& regions) noexcept +{ + try { + const ULONGLONG began = GetTickCount64(); + static std::vector<ULONG_PTR> previous; // allocation bases at the last census (reporter thread only) + // Committed bytes per allocation base at the last census (sorted by base): which existing allocations grew. + static std::vector<std::pair<ULONG_PTR, ULONGLONG>> previous_bytes; + const bool first = previous.empty(); + struct Total { ULONG_PTR base; ULONGLONG committed, resident; int c; }; + std::vector<Total> totals; // per allocation base, this census + std::vector<PSAPI_WORKING_SET_EX_INFORMATION> info(16384); + // reservations: the stand-in's reserved ranges (size, not commit), where the title's pages are mapped + enum { p4, p404, other, mapped, reservations, classes }; + const char* const names[classes] = {"p4", "p404", "other", "mapped", "stand-in reservations"}; + ULONGLONG committed[classes]{}, resident[classes]{}, count[classes]{}; + ULONGLONG fresh_committed[classes]{}, fresh_resident[classes]{}, fresh_count[classes]{}; + struct Fresh { ULONG_PTR base; ULONGLONG committed, resident; DWORD protect; bool mapped; }; + std::vector<Fresh> fresh; + std::vector<ULONG_PTR> bases; + for (const CensusRegion& r : regions) { + const int c = r.mapped ? (r.protect ? mapped : reservations) : (r.protect & ~0x100u) == PAGE_READWRITE ? p4 + : (r.protect & ~0x100u) == (PAGE_READWRITE | PAGE_WRITECOMBINE) ? p404 : other; + const ULONGLONG res = sampled_resident(r.start, r.bytes, info); + const bool new_base = !std::binary_search(previous.begin(), previous.end(), r.base); + committed[c] += r.bytes; + resident[c] += res; + if (!totals.empty() && totals.back().base == r.base) { + totals.back().committed += r.bytes; + totals.back().resident += res; + } else { + totals.push_back({r.base, r.bytes, res, c}); + } + if (bases.empty() || bases.back() != r.base) { + bases.push_back(r.base); + ++count[c]; + if (new_base) ++fresh_count[c]; + } + if (!new_base || first) continue; + fresh_committed[c] += r.bytes; + fresh_resident[c] += res; + if (!fresh.empty() && fresh.back().base == r.base) { + fresh.back().committed += r.bytes; + fresh.back().resident += res; + } else { + fresh.push_back({r.base, r.bytes, res, r.protect, r.mapped}); + } + } + std::sort(bases.begin(), bases.end()); + bases.erase(std::unique(bases.begin(), bases.end()), bases.end()); + previous.swap(bases); + // Existing allocations (base seen at the last census) that grew most since then. + std::stable_sort(totals.begin(), totals.end(), [](const Total& a, const Total& b) { return a.base < b.base; }); + std::vector<Total> merged; // one entry per base (regions of one allocation are adjacent; merged to be sure) + for (const Total& t : totals) { + if (!merged.empty() && merged.back().base == t.base) { + merged.back().committed += t.committed; + merged.back().resident += t.resident; + } else { + merged.push_back(t); + } + } + struct Grown { ULONG_PTR base; ULONGLONG grown, committed, resident; int c; }; + std::vector<Grown> grown; + ULONGLONG grown_bytes[classes]{}; + std::vector<std::pair<ULONG_PTR, ULONGLONG>> now_bytes; + now_bytes.reserve(merged.size()); + for (const Total& t : merged) { + now_bytes.emplace_back(t.base, t.committed); + const auto before = std::lower_bound(previous_bytes.begin(), previous_bytes.end(), std::make_pair(t.base, ULONGLONG{0})); + if (first || before == previous_bytes.end() || before->first != t.base || t.committed <= before->second) continue; + grown.push_back({t.base, t.committed - before->second, t.committed, t.resident, t.c}); + grown_bytes[t.c] += t.committed - before->second; + } + previous_bytes.swap(now_bytes); + char line[1500]; + int n = std::snprintf(line, sizeof(line), "x2w-mem census-classes %llu s: outside startup blocks, committed/resident MiB (allocations):", + second); + if (n < 0) return; + for (int c = 0; c < classes; ++c) + n = append(line, n, sizeof(line), " %s %llu/%llu (%llu)", names[c], committed[c] / mib, resident[c] / mib, count[c]); + if (first) { + n = append(line, n, sizeof(line), "; first census: nothing to compare"); + } else { + n = append(line, n, sizeof(line), "; new since the last census:"); + for (int c = 0; c < classes; ++c) + n = append(line, n, sizeof(line), " %s %llu/%llu (%llu)", names[c], fresh_committed[c] / mib, fresh_resident[c] / mib, + fresh_count[c]); + std::sort(fresh.begin(), fresh.end(), [](const Fresh& a, const Fresh& b) { return a.committed > b.committed; }); + n = append(line, n, sizeof(line), "; largest new:"); + // A mapped view (counted under "mapped") is marked: its protection alone reads like a p4 allocation. + for (std::size_t i = 0; i < fresh.size() && i < 12; ++i) + n = append(line, n, sizeof(line), " %p:%llu/%llu %sp%lx", reinterpret_cast<void*>(fresh[i].base), fresh[i].committed / mib, + fresh[i].resident / mib, fresh[i].mapped ? "mapped-" : "", fresh[i].protect); + } + n = append(line, n, sizeof(line), " (%llu ms)", GetTickCount64() - began); + x2w_local::logf("%s", line); + if (first) return; + // Second line (logf keeps 1.5 KB a line): growth inside allocations that already existed at the last census. + char more[1024]; + int m = std::snprintf(more, sizeof(more), "x2w-mem census-grown %llu s: existing allocations grown MiB:", second); + if (m < 0) return; + for (int c = 0; c < classes; ++c) m = append(more, m, sizeof(more), " %s +%llu", names[c], grown_bytes[c] / mib); + std::sort(grown.begin(), grown.end(), [](const Grown& a, const Grown& b) { return a.grown > b.grown; }); + m = append(more, m, sizeof(more), "; grown most (base:+MiB, now committed/resident, class):"); + for (std::size_t i = 0; i < grown.size() && i < 10; ++i) + m = append(more, m, sizeof(more), " %p:+%llu %llu/%llu %s", reinterpret_cast<void*>(grown[i].base), grown[i].grown / mib, + grown[i].committed / mib, grown[i].resident / mib, names[grown[i].c]); + x2w_local::logf("%s", more); + } catch (...) { + // out of memory while counting: no line this time + } +} + +// A VirtualQuery walk outside the stand-in's page reservations: private committed bytes by kind +// and the largest private allocations. Bounded to a few seconds. +void census(ULONGLONG second) noexcept +{ + const ULONGLONG began = GetTickCount64(); + std::vector<ULONG_PTR> ranges(2 * 4096); + const SIZE_T total = x2w_xmem_reserved_ranges(ranges.data(), 4096); + std::vector<std::pair<ULONG_PTR, ULONG_PTR>> skip; + for (SIZE_T i = 0; i < std::min<SIZE_T>(total, 4096); ++i) skip.emplace_back(ranges[2 * i], ranges[2 * i] + ranges[2 * i + 1]); + std::sort(skip.begin(), skip.end()); + std::vector<std::pair<ULONG_PTR, SIZE_T>> known; + AcquireSRWLockShared(&block_lock); + if (blocks) known = *blocks; + ReleaseSRWLockShared(&block_lock); + std::sort(known.begin(), known.end()); + auto in_block = [&](ULONG_PTR address) { + auto it = std::upper_bound(known.begin(), known.end(), std::make_pair(address, ~SIZE_T{0})); + return it != known.begin() && address - std::prev(it)->first < std::prev(it)->second; + }; + struct Allocation { ULONG_PTR base; ULONGLONG committed, reserved; DWORD protect; }; + std::vector<Allocation> top; // largest committed private allocations, at most 16 + ULONGLONG blocks_bytes = 0, private_bytes = 0, image_charged = 0, mapped_bytes = 0, skipped_bytes = 0; + ULONGLONG buckets[5]{}, bucket_counts[5]{}; // <1 MiB, <16, <256, <1024, >=1024 MiB + ULONGLONG queries = 0; + const bool classes_on = census_classes_on(); // LOCAL memcut + std::vector<CensusRegion> regions; + Allocation current{0, 0, 0, 0}; + auto close = [&] { + if (!current.base || !current.committed) return; + if (in_block(current.base)) { + blocks_bytes += current.committed; + } else { + const ULONGLONG m = current.committed / mib; + const int b = m < 1 ? 0 : m < 16 ? 1 : m < 256 ? 2 : m < 1024 ? 3 : 4; + buckets[b] += current.committed; + ++bucket_counts[b]; + top.push_back(current); + std::sort(top.begin(), top.end(), [](const Allocation& a, const Allocation& c) { return a.committed > c.committed; }); + if (top.size() > 16) top.pop_back(); + } + }; + ULONG_PTR at = 0x10000; + std::size_t next_skip = 0; + bool partial = false; + while (at < 0x7FFFFFFF0000ull) { + while (next_skip < skip.size() && skip[next_skip].second <= at) ++next_skip; + if (next_skip < skip.size() && skip[next_skip].first <= at) { + skipped_bytes += skip[next_skip].second - at; + at = skip[next_skip].second; + continue; + } + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast<void*>(at), &info, sizeof(info))) break; + ++queries; + ULONG_PTR end = reinterpret_cast<ULONG_PTR>(info.BaseAddress) + info.RegionSize; + if (next_skip < skip.size() && end > skip[next_skip].first) end = skip[next_skip].first; // the part before a reservation + const ULONGLONG bytes = end - at; + if (info.State == MEM_COMMIT && classes_on && (info.Type == MEM_PRIVATE || info.Type == MEM_MAPPED) && !in_block(at)) + regions.push_back({at, reinterpret_cast<ULONG_PTR>(info.AllocationBase), bytes, info.Protect, info.Type == MEM_MAPPED}); // LOCAL memcut + if (info.State == MEM_COMMIT) { + if (info.Type == MEM_PRIVATE) { + private_bytes += bytes; + const auto base = reinterpret_cast<ULONG_PTR>(info.AllocationBase); + if (base != current.base) { + close(); + current = {base, 0, 0, info.Protect}; + } + current.committed += bytes; + } else if (info.Type == MEM_IMAGE) { + const DWORD p = info.Protect & 0xFF; + if (p == PAGE_READWRITE || p == PAGE_WRITECOPY || p == PAGE_EXECUTE_READWRITE || p == PAGE_EXECUTE_WRITECOPY) + image_charged += bytes; + } else if (info.Type == MEM_MAPPED) { + mapped_bytes += bytes; + } + } + if (info.Type == MEM_PRIVATE && info.State != MEM_FREE) { + const auto base = reinterpret_cast<ULONG_PTR>(info.AllocationBase); + if (base == current.base) current.reserved += bytes; + } + at = end; + if (GetTickCount64() - began > 5000) { + partial = true; + break; + } + } + close(); + char line[1500]; + int n = std::snprintf(line, sizeof(line), + "x2w-mem census %llu s (%llu ms, %llu queries%s, %llu MiB of %llu stand-in reservations skipped): " + "private committed %llu MiB = startup blocks %llu + other %llu [<1M %llu MiB/%llu, <16M %llu/%llu, " + "<256M %llu/%llu, <1G %llu/%llu, >=1G %llu/%llu]; image writable %llu MiB; mapped outside reservations %llu MiB; top:", + second, GetTickCount64() - began, queries, partial ? ", PARTIAL" : "", skipped_bytes / mib, + static_cast<unsigned long long>(total), private_bytes / mib, blocks_bytes / mib, + (private_bytes - blocks_bytes) / mib, buckets[0] / mib, bucket_counts[0], buckets[1] / mib, + bucket_counts[1], buckets[2] / mib, bucket_counts[2], buckets[3] / mib, bucket_counts[3], + buckets[4] / mib, bucket_counts[4], image_charged / mib, mapped_bytes / mib); + if (n < 0) return; + for (const Allocation& a : top) + n = append(line, n, sizeof(line), " %p:%llu/%lluMiB p%lx", reinterpret_cast<void*>(a.base), a.committed / mib, + a.reserved / mib, a.protect); + const ULONGLONG walk = GetTickCount64(); + n = block_resident_text(line, n, sizeof(line)); // LOCAL memcut + n = append(line, n, sizeof(line), " (%llu ms)", GetTickCount64() - walk); + x2w_local::logf("%s", line); + if (classes_on) { // LOCAL memcut + // The stand-in reservations (title pages are mapped there) as one class: base = the reservation. + for (const auto& [start, end] : skip) regions.push_back({start, start, end - start, 0, true}); + census_classes(second, regions); + } +} + +DWORD WINAPI reporter(void*) +{ + std::vector<ULONGLONG> census_at; + char text[256]{}; + const DWORD n = GetEnvironmentVariableA("X2W_MEM_CENSUS_AT", text, sizeof(text)); + if (n && n < sizeof(text)) + for (char* p = text; *p;) { + char* end = nullptr; + const ULONGLONG v = std::strtoull(p, &end, 10); + if (end == p) break; + census_at.push_back(v); + p = *end ? end + 1 : end; + } + std::sort(census_at.begin(), census_at.end()); + ULONGLONG next_report = 0; // a first line at once: a run may end within seconds + for (;;) { + const ULONGLONG second = (GetTickCount64() - tick_at_load) / 1000; + if (second >= next_report) { + report(second); + next_report = second < 30 ? second + 2 : second + 10; + } + if (!census_at.empty() && second >= census_at.front()) { + census_at.erase(census_at.begin()); + census(second); + } + Sleep(250); + } +} +} // namespace + +namespace x2w_census { +void note_block(void* base, SIZE_T bytes) noexcept +{ + AcquireSRWLockExclusive(&block_lock); + try { + if (!blocks) blocks = new std::vector<std::pair<ULONG_PTR, SIZE_T>>; + blocks->emplace_back(reinterpret_cast<ULONG_PTR>(base), bytes); + } catch (...) { + } + ReleaseSRWLockExclusive(&block_lock); +} + +void start() noexcept +{ + static INIT_ONCE once = INIT_ONCE_STATIC_INIT; + InitOnceExecuteOnce(&once, [](INIT_ONCE*, void*, void**) -> BOOL { + char value[4]{}; + const DWORD saved = GetLastError(); + // Startup runs only (the debugger sets X2W_TRAP_LOG): tests that load xmem.dll get no thread. + const bool off = (GetEnvironmentVariableA("X2W_MEM_REPORT", value, sizeof(value)) && value[0] == '0') || + !GetEnvironmentVariableA("X2W_TRAP_LOG", nullptr, 0); + if (!off) { + // Pin the module: the thread runs until the process ends. + HMODULE self = nullptr; + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast<LPCWSTR>(&reporter), &self); + if (HANDLE thread = CreateThread(nullptr, 64 << 10, reporter, nullptr, STACK_SIZE_PARAM_IS_A_RESERVATION, nullptr)) + CloseHandle(thread); + } + SetLastError(saved); + return TRUE; + }, nullptr, nullptr); +} +} // namespace x2w_census diff --git a/src/xmem_census.h b/src/xmem_census.h new file mode 100644 index 0000000000..51b022dc5c --- /dev/null +++ b/src/xmem_census.h @@ -0,0 +1,26 @@ +#pragma once +#include <windows.h> + +namespace x2w_census { +// The title's startup blocks (commit_startup_block): the census reports them as their own kind. +void note_block(void* base, SIZE_T bytes) noexcept; +// Starts the reporter once (cheap after the first call). +void start() noexcept; +} // namespace x2w_census + +// Other stand-in DLLs may export this; the reporter adds their counters to its line: +// extern "C" int WINAPI x2w_memory_counters(char* text, int capacity); +// writes "name=<MiB> ..." pairs (bytes held now), returns the length. +using X2wMemoryCounters = int(WINAPI*)(char* text, int capacity); + +// Exported by xmem.dll (xmem_mapped_pages.cpp). +struct X2wXmemStats { + ULONGLONG slabs, slab_bytes, live_pages, free_slots, slab_budget_bytes, slab_refusals; + ULONGLONG startup_block_bytes, startup_block_calls, permissive_commit_bytes, permissive_commit_calls; + ULONGLONG reservations; + ULONGLONG file_slabs, migrations, migration_failures; // X2W_XMEM_SLAB_DIR +}; +extern "C" BOOL WINAPI x2w_xmem_memory_stats(X2wXmemStats* stats); +// Copies up to capacity (base, bytes) pairs of the stand-in's page reservations; returns the count +// of all of them (may exceed capacity). +extern "C" SIZE_T WINAPI x2w_xmem_reserved_ranges(ULONG_PTR* pairs, SIZE_T capacity); diff --git a/src/xmem_gpu_pool.cpp b/src/xmem_gpu_pool.cpp new file mode 100644 index 0000000000..753088aa82 --- /dev/null +++ b/src/xmem_gpu_pool.cpp @@ -0,0 +1,78 @@ +// LOCAL: see xmem_gpu_pool.h. +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include "xmem_gpu_pool.h" + +#include "startup_stubs/local_log.h" + +#include <cwchar> + +namespace x2w_gpu_pool { +namespace { +LONG next_index = 0; +LONG misses = 0; + +// The pool is this process's alone: the process that creates the named event Local\x2w-gpu-slab-pool-owner owns it. +// The handle stays open until the process ends (also on a kill: the kernel closes it and the name goes away), so +// the claim does not depend on the thread that made it, unlike a mutex. +bool owner() noexcept +{ + static const bool owned = [] { + const HANDLE claim = CreateEventW(nullptr, TRUE, FALSE, L"Local\\x2w-gpu-slab-pool-owner"); + const DWORD error = GetLastError(); + const bool ok = claim && error != ERROR_ALREADY_EXISTS; + if (!ok) { + if (claim) CloseHandle(claim); + x2w_local::logf("x2w-xmem GPU slab pool: in use by another process (error %lu): fresh sections instead", error); + } + return ok; // the handle is kept open on purpose + }(); + return owned; +} +} // namespace + +Mode mode() noexcept +{ + static const Mode value = [] { + char text[8]{}; + const DWORD n = GetEnvironmentVariableA("X2W_XMEM_GPU_POOL", text, sizeof(text)); + if (n == 1 && text[0] == '0') return Mode::off; + if (n == 3 && (text[0] | 0x20) == 'a' && (text[1] | 0x20) == 'l' && (text[2] | 0x20) == 'l') return Mode::all; + return Mode::moves; + }(); + return value; +} + +HANDLE take(ULONG64 bytes) noexcept +{ + if (mode() == Mode::off || !owner()) return nullptr; + const LONG index = InterlockedIncrement(&next_index) - 1; + wchar_t name[64]; + swprintf(name, 64, L"Local\\x2w-gpu-slab-%ld", index); + const HANDLE section = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, name); + if (!section) { + const DWORD error = GetLastError(); + if (InterlockedIncrement(&misses) <= 2) + x2w_local::logf("x2w-xmem GPU slab pool: %ls not available (error %lu): a fresh section instead " + "(a pagefile one opened as a GPU heap stays charged after this process; " + "tools/startup/gpu_slab_pool.py ensure)", + name, error); + return nullptr; + } + // Size check through a view: the holder may run with another --mib. + void* view = MapViewOfFile(section, FILE_MAP_READ, 0, 0, 0); + MEMORY_BASIC_INFORMATION info{}; + const bool big_enough = view && VirtualQuery(view, &info, sizeof(info)) == sizeof(info) && info.RegionSize >= bytes; + if (view) UnmapViewOfFile(view); + if (!big_enough) { + CloseHandle(section); + x2w_local::logf("x2w-xmem GPU slab pool: %ls is smaller than 0x%llx bytes: a fresh section instead", name, + static_cast<unsigned long long>(bytes)); + return nullptr; + } + static LONG taken; + if (InterlockedIncrement(&taken) <= 64) + x2w_local::logf("x2w-xmem GPU slab pool: %ls taken for %s", name, mode() == Mode::all ? "a slab" : "a GPU slab"); + return section; +} +} // namespace x2w_gpu_pool diff --git a/src/xmem_gpu_pool.h b/src/xmem_gpu_pool.h new file mode 100644 index 0000000000..1cf39666e9 --- /dev/null +++ b/src/xmem_gpu_pool.h @@ -0,0 +1,11 @@ +#pragma once +#include <windows.h> + +namespace x2w_gpu_pool { +enum class Mode { off, moves, all }; +Mode mode() noexcept; +// The next unused pool section of at least bytes, opened read-write, or nullptr (pool off, not running, +// exhausted, owned by another process, or too small). The contents are whatever the previous user left: the caller +// overwrites or zeroes them. +HANDLE take(ULONG64 bytes) noexcept; +} // namespace x2w_gpu_pool diff --git a/src/xmem_low.h b/src/xmem_low.h new file mode 100644 index 0000000000..36beb4c92e --- /dev/null +++ b/src/xmem_low.h @@ -0,0 +1,48 @@ +#pragma once +// LOCAL EXPERIMENT (X2W_XMEM_LOW40=1, never upstream): place title memory below 1 TiB. +// The console's ray-tracing builder rejects acceleration-structure addresses with more than 40 bits +// set ("DestAccelerationStructureData can not have more than 40b of address set"); console title +// memory always lies below that, desktop allocations usually do not. Allocations whose address the +// stand-in chooses itself go through low_alloc, which asks VirtualAlloc2 for an end address below +// 2^40 and falls back to an unconstrained allocation when that range is exhausted. +#include <windows.h> + +namespace x2w_low { +inline bool on() noexcept +{ + static const bool value = [] { + char text[8]; + const DWORD n = GetEnvironmentVariableA("X2W_XMEM_LOW40", text, sizeof text); + return n && n < sizeof text && text[0] == '1'; + }(); + return value; +} + +using VirtualAlloc2Fn = PVOID(WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG); +inline VirtualAlloc2Fn virtual_alloc2() noexcept +{ + static const VirtualAlloc2Fn fn = [] { + const HMODULE base = GetModuleHandleW(L"kernelbase.dll"); + return base ? reinterpret_cast<VirtualAlloc2Fn>(GetProcAddress(base, "VirtualAlloc2")) : nullptr; + }(); + return fn; +} + +// address == nullptr only; type/protect as for VirtualAlloc2 (placeholders allowed). +inline void* alloc(SIZE_T bytes, ULONG type, ULONG protect) noexcept +{ + const auto fn = virtual_alloc2(); + if (!fn) return VirtualAlloc(nullptr, bytes, type, protect); + if (on()) { + MEM_ADDRESS_REQUIREMENTS requirements{}; + // Floor at 4 GiB: low 32-bit addresses can collide with values the title treats as non-pointers. + requirements.LowestStartingAddress = reinterpret_cast<void*>(ULONG_PTR{1} << 32); + requirements.HighestEndingAddress = reinterpret_cast<void*>((ULONG_PTR{1} << 40) - 1); + MEM_EXTENDED_PARAMETER parameter{}; + parameter.Type = MemExtendedParameterAddressRequirements; + parameter.Pointer = &requirements; + if (void* low = fn(GetCurrentProcess(), nullptr, bytes, type, protect, ¶meter, 1)) return low; + } + return fn(GetCurrentProcess(), nullptr, bytes, type, protect, nullptr, 0); +} +} // namespace x2w_low diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 7567418981..671d9cd520 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -1,8 +1,18 @@ #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <windows.h> +#include <winioctl.h> +#include <psapi.h> #include "era_physical.h" +#include "xmem_low.h" +#include "xmem_census.h" +#include "xmem_gpu_pool.h" + +#include <cstring> +#include "startup_stubs/local_log.h" + +#include <vector> #include "xmem_slab_slots.h" #include "xmem_section_lease.h" #include "xmem_page_batch.h" @@ -15,12 +25,16 @@ #include <vector> +#include <algorithm> +#include <atomic> #include <iterator> #include <limits> #include <map> #include <mutex> #include <new> +#include <optional> #include <set> +#include <unordered_map> #include <utility> namespace { @@ -32,7 +46,9 @@ struct Backing { bool committed = true; // false while a lazily mapped slot is untouched (X2W_XMEM_LAZY_COMMIT) }; -using Slot = std::pair<std::size_t, ULONG64>; +// The slot a page holds: (slab section, byte offset). LOCAL (local merge): keyed by section handle, the local +// allocator's slot identity (free_slots), not by an upstream SlabSlots index. +using Slot = std::pair<HANDLE, ULONG64>; struct SlotPin { unsigned references{}; bool retired{}; }; struct SectionLease { UINT version; @@ -43,11 +59,19 @@ struct SectionLease { // Keep grant transitions and section views serialized. A grant can outlive all its // views so its bytes survive unmapping. Its backing is released before reuse. +struct LinearReservation { + SIZE_T bytes; + std::size_t slab = SIZE_MAX; + ULONG64 offset = 0; + bool attempted = false; +}; + struct PhysicalMemory { std::mutex mutex; std::map<ULONG_PTR, Backing> backings; std::map<ULONG_PTR, ULONG_PTR> views; std::map<ULONG_PTR, SIZE_T> reservations; + std::map<ULONG_PTR, LinearReservation> linear_reservations; // A no-access graphics reservation (protection 0x801) made right after a // read-write one of the same size is that memory's GPU view on the console. Pages mapped into // the CPU view are mapped at the same offset into the GPU view too (the same section). @@ -57,11 +81,18 @@ struct PhysicalMemory { SIZE_T mirror_bytes = 0; std::set<ULONG_PTR> explicit_mirror_pages; std::map<ULONG_PTR, SIZE_T> runs; // OS views: base -> bytes - // The slabs and their 64 KiB slots; released slots are reused lowest first, so that pages reused together - // are adjacent slots again. - x2w_xmem::SlabSlots<HANDLE> slots{era_physical::page_bytes}; + std::vector<HANDLE> slabs; + ULONG64 slab_used = 0; + std::set<std::pair<HANDLE, ULONG64>> free_slots; // ordered, so that pages reused together are adjacent slots again + std::set<HANDLE> file_slabs; // LOCAL: slabs backed by a temporary file (X2W_XMEM_SLAB_DIR), not by the pagefile + ULONG64 migrations = 0, migration_failures = 0; + // LOCAL (X2W_XMEM_GPU_POOL=all, xmem_gpu_pool.h): slabs taken from the long-lived pool, each with a writable view + // of this process that zeroes a slot when it is first handed out (the section holds an earlier run's bytes). + std::map<HANDLE, unsigned char*> pool_views; + unsigned char* newest_pool_view = nullptr; // pool_views of slabs.back(), or nullptr when it is not a pool slab + ULONG64 pool_slabs = 0; // not counted against the slab budget: already charged by the holder // A grant may be freed after unmapping while a submitted GPU operation - // still uses the section. Keep those slots out of the reusable pool. + // still uses the section. Keep those slots out of the reusable pool (free_slots). std::map<Slot, SlotPin> pins; std::map<ULONG64, SectionLease> leases; ULONG64 next_lease = 1; @@ -70,7 +101,7 @@ struct PhysicalMemory { { for (const auto& run : runs) UnmapViewOfFile(reinterpret_cast<void*>(run.first)); - for (const HANDLE slab : slots.slabs()) + for (const HANDLE slab : slabs) CloseHandle(slab); } }; @@ -78,7 +109,27 @@ struct PhysicalMemory { PhysicalMemory memory; constexpr SIZE_T page_bytes = era_physical::page_bytes; -// Caller holds memory.mutex. A lease may only refer to committed pages whose +// LOCAL accounting (runtime_work/NOTES.md): what the memory stand-in commits on the title's behalf, +// by path. The slabs are pagefile-backed sections: their commit is charged to the system at +// creation, not to this process, so neither the process commit counter nor a job memory limit sees +// them. Counters only grow except where a free is visible here. +volatile LONG64 startup_block_bytes = 0, startup_block_calls = 0; // commit_startup_block +volatile LONG64 permissive_commit_bytes = 0, permissive_commit_calls = 0; // local_virtual_alloc commits +volatile LONG slab_refusals = 0; + +// X2W_XMEM_SLAB_BUDGET_MIB=<n>: no new slab once the slabs would pass n MiB; the page mapping or +// page write that needed it fails (ERROR_COMMITMENT_LIMIT), as on a host without memory, but +// inside the title instead of exhausting the host. 0 or unset: no budget. +ULONG64 slab_budget_bytes() noexcept +{ + static const ULONG64 value = [] { + char text[24]{}; + const DWORD n = GetEnvironmentVariableA("X2W_XMEM_SLAB_BUDGET_MIB", text, sizeof(text)); + return n && n < sizeof(text) ? std::strtoull(text, nullptr, 10) << 20 : 0ull; + }(); + return value; +} + // CPU and GPU views still name the same grant. bool mirrored_range(ULONG_PTR address, SIZE_T length) { @@ -104,7 +155,7 @@ void unpin_slot(const Slot& slot) { const auto found = memory.pins.find(slot); if (--found->second.references) return; - if (found->second.retired) memory.slots.release(slot.first, slot.second); + if (found->second.retired) memory.free_slots.insert(slot); // LOCAL allocator (option a) memory.pins.erase(found); } @@ -123,6 +174,123 @@ BOOL physical_result(era_physical::Status status) noexcept } } +constexpr ULONG64 slab_bytes = 4096 * ULONG64{page_bytes}; + +// LOCAL (runtime_work/NOTES.md): X2W_XMEM_SLAB_DIR=<absolute directory> backs new slabs with a +// delete-on-close sparse temporary file there instead of the pagefile. A file-backed section carries +// no commit charge, so the title's physical pages stop counting against the host commit limit; the +// pages still use RAM and are written to the file only under memory pressure. D3D12 opens only +// pagefile-backed sections as heaps (OpenExistingHeapFromFileMapping gives E_INVALIDARG for a file- +// or SEC_RESERVE-backed one), so a slab the GPU needs is moved to the pagefile first (migrate_slab). +// A relative path, or one on the process's current drive (the title runs from its data drive), is +// refused and the pagefile is used. +const wchar_t* slab_dir() noexcept +{ + static wchar_t dir[MAX_PATH]{}; + static const bool usable = [] { + const DWORD n = GetEnvironmentVariableW(L"X2W_XMEM_SLAB_DIR", dir, MAX_PATH); + if (!n || n >= MAX_PATH - 40) return false; + const bool absolute = n >= 3 && dir[1] == L':' && (dir[2] == L'\\' || dir[2] == L'/'); + wchar_t cwd[MAX_PATH]{}; + GetCurrentDirectoryW(MAX_PATH, cwd); + const bool same_drive = absolute && (cwd[0] | 0x20) == (dir[0] | 0x20) && cwd[1] == L':'; + const DWORD attributes = absolute ? GetFileAttributesW(dir) : INVALID_FILE_ATTRIBUTES; + const bool ok = absolute && !same_drive && attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY); + x2w_local::logf("x2w-xmem slab directory %ls: %s", dir, + ok ? "file-backed slabs (no commit charge; GPU slabs move to the pagefile)" + : "refused (must be an existing absolute directory off the current drive); pagefile slabs"); + return ok; + }(); + return usable ? dir : nullptr; +} + +ULONG64 pagefile_slabs() noexcept { return memory.slabs.size() - memory.file_slabs.size() - memory.pool_slabs; } + +HANDLE pagefile_slab() noexcept +{ + const ULONG64 budget = slab_budget_bytes(); + if (budget && (pagefile_slabs() + 1) * slab_bytes > budget) { + if (x2w_local::first_of(InterlockedIncrement(&slab_refusals), 4)) + x2w_local::logf("x2w-xmem slab budget reached (X2W_XMEM_SLAB_BUDGET_MIB=%llu, %llu pagefile slabs of 256 MiB): refused", + static_cast<unsigned long long>(budget >> 20), static_cast<unsigned long long>(pagefile_slabs())); + SetLastError(ERROR_COMMITMENT_LIMIT); + return nullptr; + } + return CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, static_cast<DWORD>(slab_bytes >> 32), + static_cast<DWORD>(slab_bytes), nullptr); +} + +// LOCAL (xmem_gpu_pool.h): a pagefile slab for the GPU, from the long-lived pool when it has one (same budget). +HANDLE gpu_slab(bool* pooled) noexcept +{ + *pooled = false; + const ULONG64 budget = slab_budget_bytes(); + if (!budget || (pagefile_slabs() + 1) * slab_bytes <= budget) + if (const HANDLE section = x2w_gpu_pool::take(slab_bytes)) { + *pooled = true; + return section; + } + return pagefile_slab(); +} + +// LOCAL (X2W_XMEM_GPU_POOL=all): the next pool section with a writable view of it, or nullptr (pool exhausted, +// not running or owned elsewhere: logged once, then fresh sections as without the pool). +HANDLE pool_slab(unsigned char** view) noexcept +{ + static bool exhausted = false; + if (exhausted) return nullptr; + const HANDLE section = x2w_gpu_pool::take(slab_bytes); + void* mapped = section ? MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 0) : nullptr; + if (!mapped) { + if (section) CloseHandle(section); + exhausted = true; + x2w_local::logf("x2w-xmem GPU slab pool (all): no further pool section after %llu (error %lu): fresh %s slabs from " + "now on%s", static_cast<unsigned long long>(memory.pool_slabs), GetLastError(), + slab_dir() ? "file-backed" : "pagefile", + slab_dir() ? " (moved for the GPU as without the pool)" : " (under the slab budget)"); + return nullptr; + } + *view = static_cast<unsigned char*>(mapped); + return section; +} + +// A new slab: from the pool with X2W_XMEM_GPU_POOL=all, else file-backed when X2W_XMEM_SLAB_DIR allows it, else from +// the pagefile. *file says whether it is file-backed, *pool_view is the pool section's view (or nullptr). +HANDLE new_slab(bool* file, unsigned char** pool_view) noexcept +{ + *file = false; + *pool_view = nullptr; + if (x2w_gpu_pool::mode() == x2w_gpu_pool::Mode::all) + if (const HANDLE slab = pool_slab(pool_view)) return slab; + if (const wchar_t* dir = slab_dir()) { + static LONG serial; + wchar_t path[MAX_PATH]; + swprintf_s(path, L"%ls\\x2w-slab-%lu-%ld.tmp", dir, GetCurrentProcessId(), InterlockedIncrement(&serial)); + const HANDLE backing = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + if (backing != INVALID_HANDLE_VALUE) { + DWORD returned = 0; + DeviceIoControl(backing, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &returned, nullptr); + const HANDLE slab = CreateFileMappingW(backing, nullptr, PAGE_READWRITE, static_cast<DWORD>(slab_bytes >> 32), + static_cast<DWORD>(slab_bytes), nullptr); + const DWORD error = GetLastError(); + CloseHandle(backing); // the section keeps the file; it is deleted when the section goes + if (slab) { + *file = true; + return slab; + } + static LONG failed; + if (x2w_local::first_calls(failed, 4)) + x2w_local::logf("x2w-xmem file-backed slab %ls failed (error %lu): pagefile slab instead", path, error); + } else { + static LONG failed; + if (x2w_local::first_calls(failed, 4)) + x2w_local::logf("x2w-xmem slab file %ls could not be created (error %lu): pagefile slab instead", path, GetLastError()); + } + } + return pagefile_slab(); +} + // Pages are slots of 256 MiB pagefile-backed sections rather than one section each: one handle and // one view per page is what makes large batches slow. A slab is created with SEC_RESERVE, so it costs // no commit until a slot is used; a slot is committed here, when its page is first mapped or written, @@ -294,52 +462,111 @@ LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) return EXCEPTION_CONTINUE_EXECUTION; } -HANDLE section_for(ULONG_PTR page, bool need_commit = true) +// LOCAL allocator kept at the upstream merge (option a): file-backed slabs (X2W_XMEM_SLAB_DIR), the GPU pool +// (X2W_XMEM_GPU_POOL) and slot reuse. Upstream's SlabSlots / commit-on-first-touch slots (X2W_XMEM_LAZY_COMMIT) +// are not ported: every slot is committed when its slab is created, so need_commit has nothing to do here. +bool ensure_fresh_slab() { - const auto existing = memory.backings.find(page); - if (existing != memory.backings.end()) { - if (need_commit && !commit_backing(existing->second)) return nullptr; - return existing->second.section; - } - // A fresh slot (never used) of a SEC_RESERVE slab reads as zero once committed, so it can wait for its first - // touch. A reused slot is committed and zeroed now, as before. - const bool defer = !need_commit && lazy_commit(); - x2w_xmem::SlabSlots<HANDLE>::Slot slot; - if (memory.slots.lowest_free(slot)) { - if (!commit_slot(slot.slab, slot.offset, true)) return nullptr; - memory.backings.emplace(page, Backing{slot.slab, 0, slot.offset, slot.slab_index}); - memory.slots.take_lowest_free(); - return slot.slab; - } - const ULONG64 slab_bytes = memory.slots.slab_bytes(); - bool first_slot_committed = false; - const auto make_slab = [slab_bytes, &first_slot_committed, defer](HANDLE& slab) { - slab = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, - static_cast<DWORD>(slab_bytes >> 32), static_cast<DWORD>(slab_bytes), nullptr); + if (memory.slabs.empty() || memory.slab_used == slab_bytes) { + bool file = false; + unsigned char* pool_view = nullptr; + const HANDLE slab = new_slab(&file, &pool_view); if (!slab) return false; - if (defer) return true; - first_slot_committed = commit_slot(slab, 0, false); - if (!first_slot_committed) { - const DWORD error = GetLastError(); + try { + memory.slabs.push_back(slab); + if (file) memory.file_slabs.insert(slab); + if (pool_view) memory.pool_views.emplace(slab, pool_view), ++memory.pool_slabs; + } catch (const std::bad_alloc&) { + if (pool_view) UnmapViewOfFile(pool_view); CloseHandle(slab); - SetLastError(error); + throw; } - return first_slot_committed; - }; - if (!memory.slots.take_fresh(make_slab, [](HANDLE slab) { CloseHandle(slab); }, slot)) return nullptr; - if (!defer && !first_slot_committed && !commit_slot(slot.slab, slot.offset, false)) { - const DWORD error = GetLastError(); - memory.slots.unwind_fresh(slot); - SetLastError(error); - return nullptr; + memory.newest_pool_view = pool_view; + memory.slab_used = 0; } - try { - memory.backings.emplace(page, Backing{slot.slab, 0, slot.offset, slot.slab_index, !defer}); - } catch (...) { - memory.slots.unwind_fresh(slot); - throw; + return true; +} + +bool linear_placement() +{ + static const bool enabled = x2w_local::env_on("X2W_XMEM_LINEAR_PLACEMENT"); + return enabled; +} + +// A hint claims only a free slot or an unused offset. Existing grants and retired slots take precedence. +std::optional<Slot> linear_slot(ULONG_PTR address) +{ + auto it = memory.linear_reservations.upper_bound(address); + if (it == memory.linear_reservations.begin()) return {}; + --it; + const ULONG_PTR delta = address - it->first; + auto& region = it->second; + if (delta >= region.bytes) return {}; + if (!region.attempted) { + region.attempted = true; + if (memory.free_slots.size() >= region.bytes / page_bytes) { + Slot previous{}; + SIZE_T length = 0; + for (const Slot& slot : memory.free_slots) { + length = slot.first == previous.first && slot.second == previous.second + page_bytes ? length + page_bytes : page_bytes; + previous = slot; + if (length == region.bytes) { + region.slab = std::find(memory.slabs.begin(), memory.slabs.end(), slot.first) - memory.slabs.begin(); + region.offset = slot.second + page_bytes - length; + break; + } + } + } + if (region.slab == SIZE_MAX && !memory.slabs.empty() && region.bytes <= slab_bytes - memory.slab_used) { + region.slab = memory.slabs.size() - 1; + region.offset = memory.slab_used; + } } - return slot.slab; + if (region.slab == SIZE_MAX) return {}; + return Slot{memory.slabs[region.slab], region.offset + delta}; +} + +HANDLE section_for(ULONG_PTR page, ULONG_PTR address = 0) +{ + const auto existing = memory.backings.find(page); + if (existing != memory.backings.end()) return existing->second.section; + if (memory.free_slots.empty() && !ensure_fresh_slab()) return nullptr; + auto free = memory.free_slots.end(); + bool use_tail = false; + if (address && linear_placement()) { + if (const auto slot = linear_slot(address)) { + free = memory.free_slots.find(*slot); + if (free == memory.free_slots.end() && slot->first == memory.slabs.back() && slot->second >= memory.slab_used) { + while (memory.slab_used < slot->second) { + memory.free_slots.emplace(slot->first, memory.slab_used); + memory.slab_used += page_bytes; + } + use_tail = true; + } + } + } + if (!use_tail && free == memory.free_slots.end()) free = memory.free_slots.begin(); + if (free != memory.free_slots.end()) { + const auto [section, offset] = *free; + if (const auto pool = memory.pool_views.find(section); pool != memory.pool_views.end()) { + std::memset(pool->second + offset, 0, page_bytes); // through the pool slab's own view + } else { + void* view = MapViewOfFile(section, FILE_MAP_WRITE, static_cast<DWORD>(offset >> 32), static_cast<DWORD>(offset), page_bytes); + if (!view) return nullptr; + std::memset(view, 0, page_bytes); // a reused slot starts zero-filled, as a fresh section did + UnmapViewOfFile(view); + } + memory.backings.emplace(page, Backing{section, 0, offset}); + memory.free_slots.erase(free); + return section; + } + const HANDLE section = memory.slabs.back(); + // LOCAL (X2W_XMEM_GPU_POOL=all): a pool slot holds an earlier run's bytes; zero it before anyone sees it, as the + // kernel's demand-zero fill does for a fresh section (cost: memleak_work/NOTES.md "zeroing"). + if (memory.newest_pool_view) std::memset(memory.newest_pool_view + memory.slab_used, 0, page_bytes); + memory.backings.emplace(page, Backing{section, 0, memory.slab_used}); + memory.slab_used += page_bytes; + return section; } auto owned_reservation(ULONG_PTR address) @@ -350,32 +577,43 @@ auto owned_reservation(ULONG_PTR address) return address - it->first < it->second ? it : memory.reservations.end(); } -// Only split a reservation owned by the shim. Caller-owned placeholders must already match the view. -// Once a split succeeds, report the retry's result even if it fails for a different reason. -template <class Map> -bool map_split(void* target, SIZE_T bytes, Map map) +// LOCAL (xmem_work/NOTES.md): the Windows errors of the last refused view on this thread, each call's own (the +// error a caller sees is only the last one): the first MapViewOfFile3, the placeholder split (VirtualFree +// MEM_PRESERVE_PLACEHOLDER; 0 = not tried because the address is in no recorded reservation), the second map. +struct MapErrors { + DWORD map = 0, split = 0, retry = 0; + bool split_tried = false; +}; +thread_local MapErrors map_errors; + +// One view of bytes at address: replace the placeholder, or split it out of a bigger recorded placeholder first. +bool map_placeholder(ULONG_PTR address, HANDLE section, ULONG64 section_offset, SIZE_T bytes) { + auto* target = reinterpret_cast<void*>(address); + auto map = [&] { + return MapViewOfFile3(section, GetCurrentProcess(), target, section_offset, bytes, MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, nullptr, 0) != nullptr; + }; + map_errors = MapErrors{}; if (map()) return true; - const DWORD error = GetLastError(); - const auto address = reinterpret_cast<ULONG_PTR>(target); - const auto reservation = owned_reservation(address); - if (reservation != memory.reservations.end() && bytes <= reservation->second - (address - reservation->first) && - VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) - return map(); - SetLastError(error); + map_errors.map = GetLastError(); + if (owned_reservation(address) == memory.reservations.end()) { + SetLastError(map_errors.map); + return false; + } + map_errors.split_tried = true; + if (!VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) { + map_errors.split = GetLastError(); + return false; + } + if (map()) return true; + map_errors.retry = GetLastError(); return false; } bool map_view(ULONG_PTR address, const Backing& backing) { - const HANDLE section = backing.section; - const ULONG64 section_offset = backing.offset; - auto* target = reinterpret_cast<void*>(address); - auto map = [&] { - return MapViewOfFile3(section, GetCurrentProcess(), target, section_offset, - page_bytes, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0) != nullptr; - }; - return map_split(target, page_bytes, map); + return map_placeholder(address, backing.section, backing.offset, page_bytes); } // Maps bytes of one section at address as a single view; falls back to one view per page when the @@ -383,12 +621,7 @@ bool map_view(ULONG_PTR address, const Backing& backing) bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, std::vector<std::pair<ULONG_PTR, SIZE_T>>& made, ULONG_PTR& failed_address) { - auto* target = reinterpret_cast<void*>(address); - auto map = [&] { - return MapViewOfFile3(backing.section, GetCurrentProcess(), target, backing.offset, bytes, - MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0) != nullptr; - }; - if (map_split(target, bytes, map)) { + if (map_placeholder(address, backing.section, backing.offset, bytes)) { memory.runs[address] = bytes; made.emplace_back(address, bytes); return true; @@ -439,6 +672,15 @@ struct RemapWindow { }; RemapWindow remap_window; +// The exception handler tracks only breaks in existing runs. GPU address caches also +// depend on first maps. Writers hold memory.mutex throughout the native view changes +// and registry publication, including recovery on an unsuccessful transaction. +std::atomic<ULONG64> gpu_mapping_generation{2}; +struct ChangingGpuMappings { + ChangingGpuMappings() { gpu_mapping_generation.fetch_add(1, std::memory_order_acq_rel); } + ~ChangingGpuMappings() { gpu_mapping_generation.fetch_add(1, std::memory_order_release); } +}; + void begin_break(const std::map<ULONG_PTR, SIZE_T>& broken) { std::vector<std::pair<ULONG_PTR, SIZE_T>> ranges(broken.begin(), broken.end()); @@ -496,6 +738,125 @@ struct MappingThread { ~MappingThread() { mapping_thread = false; } }; +struct MapFailure; +ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failure = nullptr); // defined below (upstream MapFailure) + +// LOCAL: the fault handler that retries an access to a page whose view is being replaced +// (retry_remapped_page), registered once and kept with the module pinned, as for shared views. +bool retry_handler_ready() noexcept +{ + static const bool ready = [] { + HMODULE pinned = nullptr; + return GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast<LPCWSTR>(&retry_remapped_page), &pinned) && + AddVectoredExceptionHandler(1, retry_remapped_page) != nullptr; + }(); + return ready; +} + +// LOCAL (X2W_XMEM_SLAB_DIR): moves a file-backed slab to a new pagefile-backed section so that D3D12 +// can open it as a heap. Called with memory.mutex held. Every view of the slab's pages is unmapped +// (a "break": a title thread that touches one meanwhile waits in retry_remapped_page for the mutex +// and retries), the bytes are copied, the registry is pointed at the new section and the views are +// mapped again at the same addresses. Returns the new section, or nullptr with everything as before. +// Limitation: a kernel-mode access (a ReadFile into such a page) during the move fails instead of +// waiting; the move happens once per slab the GPU uses. +HANDLE migrate_slab(HANDLE old_slab) +{ + const ULONG64 began = GetTickCount64(); + if (!retry_handler_ready()) { + ++memory.migrations, ++memory.migration_failures; + x2w_local::logf("x2w-xmem slab move refused: the fault handler could not be set up"); + return nullptr; + } + // LOCAL (local merge): a section lease (x2w_xmem_lease_section) hands out this section's handle, so a GPU heap + // opened over it would keep the old bytes after a move; a slab with a pinned slot stays where it is. + for (const auto& [slot, pin] : memory.pins) + if (slot.first == old_slab) { + ++memory.migrations, ++memory.migration_failures; + x2w_local::logf("x2w-xmem slab move refused: a section lease pins one of its slots"); + return nullptr; + } + std::map<ULONG_PTR, SIZE_T> broken; + for (const auto& [address, page] : memory.views) { + if (memory.backings.at(page).section != old_slab) continue; + auto run = memory.runs.upper_bound(address); + if (run == memory.runs.begin()) continue; + --run; + if (address - run->first < run->second) broken.insert(*run); + } + bool pooled = false; + const HANDLE moved = gpu_slab(&pooled); + if (!moved) { + ++memory.migration_failures; + x2w_local::logf("x2w-xmem slab move refused: no pagefile slab (error %lu)", GetLastError()); + return nullptr; + } + const MappingThread marker; + const ChangingGpuMappings changing; + begin_break(broken); + DWORD error = ERROR_SUCCESS; + std::vector<std::pair<ULONG_PTR, SIZE_T>> unmapped; + for (const auto& [base, size] : broken) { + if (!UnmapViewOfFile2(GetCurrentProcess(), reinterpret_cast<void*>(base), MEM_PRESERVE_PLACEHOLDER)) { + error = GetLastError(); + break; + } + memory.runs.erase(base); + unmapped.emplace_back(base, size); + } + bool copied = false; + if (error == ERROR_SUCCESS) { + void* from = MapViewOfFile(old_slab, FILE_MAP_READ, 0, 0, 0); + void* to = MapViewOfFile(moved, FILE_MAP_WRITE, 0, 0, 0); + if (from && to) { + // Only the used part of the newest slab holds pages. + const bool newest = !memory.slabs.empty() && memory.slabs.back() == old_slab; + std::memcpy(to, from, newest ? memory.slab_used : slab_bytes); + // A pool section holds an earlier run's bytes: the unused tail must read as zero, as a fresh one. + if (pooled && newest) std::memset(static_cast<char*>(to) + memory.slab_used, 0, slab_bytes - memory.slab_used); + copied = true; + } else { + error = GetLastError(); + } + if (from) UnmapViewOfFile(from); + if (to) UnmapViewOfFile(to); + } + if (copied) { + for (auto& [page, backing] : memory.backings) + if (backing.section == old_slab) backing.section = moved; + std::vector<std::pair<HANDLE, ULONG64>> slots; + for (auto it = memory.free_slots.begin(); it != memory.free_slots.end();) { + if (it->first == old_slab) { + slots.emplace_back(moved, it->second); + it = memory.free_slots.erase(it); + } else { + ++it; + } + } + memory.free_slots.insert(slots.begin(), slots.end()); + std::replace(memory.slabs.begin(), memory.slabs.end(), old_slab, moved); + memory.file_slabs.erase(old_slab); + } + ULONG_PTR lost = 0; + for (const auto& [base, size] : unmapped) lost += map_recorded(base, size, false); + end_break(); + ++memory.migrations; + if (!copied) { + ++memory.migration_failures; + CloseHandle(moved); + x2w_local::logf("x2w-xmem slab move failed (error %lu); %llu page(s) could not be mapped again", error, + static_cast<unsigned long long>(lost)); + return nullptr; + } + CloseHandle(old_slab); + x2w_local::logf("x2w-xmem slab moved to the pagefile for the GPU (#%llu): %llu view(s) in %llu ms, %llu page(s) lost, " + "%llu file-backed slab(s) left", static_cast<unsigned long long>(memory.migrations), + static_cast<unsigned long long>(unmapped.size()), static_cast<unsigned long long>(GetTickCount64() - began), + static_cast<unsigned long long>(lost), static_cast<unsigned long long>(memory.file_slabs.size())); + return moved; +} + // Shared views are opt-in: X2W_XMEM_SHARED_VIEWS=1, read once by the first mapping call. Without // it every page has a view of its own, as before: unmapping a page never takes a neighbour away, // no handler is registered, and the module unloads like any DLL. @@ -677,11 +1038,69 @@ ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failu return lost; } +struct PageEvent { + ULONG64 tick = 0, serial = 0; + ULONG_PTR page = 0; + DWORD thread = 0; + unsigned char kind = 0; // 1 map, 2 unmap +}; +std::unordered_map<ULONG_PTR, PageEvent> page_events; +ULONG64 page_event_serial = 0; // one per successful map or unmap step +ULONG64 remap_gaps = 0; // addresses unmapped and mapped again in one call (P -> Q): a VirtualQuery from another + // thread inside that call sees them uncommitted + +void note_events(const std::map<ULONG_PTR, ULONG_PTR>& batch, unsigned char kind) noexcept +{ + const ULONG64 tick = GetTickCount64(), serial = ++page_event_serial; + const DWORD thread = GetCurrentThreadId(); + try { + for (const auto& [address, page] : batch) page_events[address] = PageEvent{tick, serial, page, thread, kind}; + } catch (const std::bad_alloc&) { + } +} + +// LOCAL (xmem_work/NOTES.md): one line for a refused page mapping or unmapping, with everything needed to name the +// cause: the check that refused it or each Windows call's own error, what Windows shows at the address, what the +// registry holds there, and the state of the slabs. Called with memory.mutex held; error is left as the last error. +void log_refusal(const char* what, bool mapping, ULONG_PTR count, ULONG_PTR index, ULONG_PTR address, ULONG_PTR page, + const char* check, DWORD error, ULONG_PTR mapped_before, bool windows) noexcept +{ + MEMORY_BASIC_INFORMATION info{}; + const bool queried = address && VirtualQuery(reinterpret_cast<void*>(address), &info, sizeof(info)) == sizeof(info); + const auto live = memory.views.find(address); + const auto reservation = owned_reservation(address); + char windows_text[160] = ""; + if (windows) + std::snprintf(windows_text, sizeof(windows_text), " MapViewOfFile3 err %lu, split %s%lu, map again err %lu;", + map_errors.map, map_errors.split_tried ? "err " : "not tried ", map_errors.split, map_errors.retry); + x2w_local::logf("x2w-xmem REFUSED %s (%s) thread %lu: entry %llu of %llu, address %p page 0x%llx (token 0x%llx, %s): %s, " + "error %lu;%s %llu page(s) of the call mapped before it were taken back | Windows at the address: base %p " + "allocation %p size 0x%llx state 0x%lx type 0x%lx protect 0x%lx%s | registry: %s 0x%llx, reservation %p+0x%llx | " + "slabs %llu (%llu pool), %llu pages live, %llu free slots, budget %llu MiB", + what, mapping ? "map" : "unmap", GetCurrentThreadId(), static_cast<unsigned long long>(index), + static_cast<unsigned long long>(count), reinterpret_cast<void*>(address), static_cast<unsigned long long>(page), + static_cast<unsigned long long>(page << 4), page && era_physical::owns(page) ? "granted" : "NOT granted", + check, static_cast<unsigned long>(error), windows_text, static_cast<unsigned long long>(mapped_before), + queried ? info.BaseAddress : nullptr, queried ? info.AllocationBase : nullptr, + static_cast<unsigned long long>(queried ? info.RegionSize : 0), queried ? info.State : 0ul, + queried ? info.Type : 0ul, queried ? info.Protect : 0ul, queried ? "" : " (VirtualQuery failed)", + live != memory.views.end() ? "view of page" : "no view", static_cast<unsigned long long>( + live != memory.views.end() ? live->second : 0), + reservation != memory.reservations.end() ? reinterpret_cast<void*>(reservation->first) : nullptr, + static_cast<unsigned long long>(reservation != memory.reservations.end() ? reservation->second : 0), + static_cast<unsigned long long>(memory.slabs.size()), static_cast<unsigned long long>(memory.pool_slabs), + static_cast<unsigned long long>(memory.backings.size()), + static_cast<unsigned long long>(memory.free_slots.size()), + static_cast<unsigned long long>(slab_budget_bytes() >> 20)); + SetLastError(error); +} + // Destinations must be caller-owned, page-sized Windows placeholders. Live views // are owned by this shim until it unmaps them. The caller must not replace them. +// Called with memory.mutex held and a MappingThread marker on this thread (map_pages, local_apply). template <typename AddressAt> -BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& address_at, - bool share_views, MapFailure* failure = nullptr) noexcept +BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& address_at, bool share_views, + const char* what, MapFailure* failure = nullptr) noexcept { if (!count || count > era_physical::capacity_pages) return physical_result(era_physical::Status::invalid); @@ -690,26 +1109,42 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& for (ULONG_PTR i = 0; i < count; ++i) { const auto address = address_at(i); const auto live = memory.views.find(address); - const ULONG_PTR page = tokens ? tokens[i] : (live != memory.views.end() ? live->second : 0); - const char* invalid = nullptr; - if (!address || address % page_bytes) invalid = "invalid-address"; - else if (tokens && live != memory.views.end()) invalid = "already-mapped"; - else if (tokens && !era_physical::owns(page)) invalid = "unowned-page"; - else if (!tokens && live == memory.views.end()) invalid = "unmapped-address"; - else if (!batch.emplace(address, page).second) invalid = "duplicate-address"; - if (invalid) { - if (failure) failure->record(invalid, address, page, ERROR_INVALID_PARAMETER); + const char* check = !address || address % page_bytes ? "address is zero or not 64 KiB aligned" + : tokens && live != memory.views.end() ? "a view is already recorded at the address" + : tokens && !era_physical::owns(tokens[i]) ? "the page is not granted (era_physical::owns)" + : !tokens && live == memory.views.end() ? "no view is recorded at the address" + : nullptr; + if (!check && !batch.emplace(address, tokens ? tokens[i] : live->second).second) + check = "the address is named twice in the call"; + if (check) { + log_refusal(what, tokens != nullptr, count, i, address, + tokens ? tokens[i] : live != memory.views.end() ? live->second : 0, check, + ERROR_INVALID_PARAMETER, 0, false); + if (failure) { + const ULONG_PTR page = tokens ? tokens[i] : live != memory.views.end() ? live->second : 0; + const char* stage = !address || address % page_bytes ? "invalid-address" + : tokens && live != memory.views.end() ? "already-mapped" + : tokens && !era_physical::owns(page) ? "unowned-page" + : !tokens && live == memory.views.end() ? "unmapped-address" + : "duplicate-address"; + failure->record(stage, address, page, ERROR_INVALID_PARAMETER); + } return physical_result(era_physical::Status::invalid); } } // Adjacent pages that are adjacent slots of one section share a single view (a "run"): a // multi-gigabyte batch then takes a few views instead of one per 64 KiB page. if (tokens) { + ULONG_PTR index = 0; for (const auto& [address, page] : batch) { - if (!section_for(page, false)) { // committed on first touch with X2W_XMEM_LAZY_COMMIT - if (failure) failure->record("section-backing", address, page, GetLastError()); + if (!section_for(page, address)) { + const DWORD section_error = GetLastError(); + log_refusal(what, true, count, index, address, page, "no backing section for the page (section_for)", + section_error, 0, false); + if (failure) failure->record("section-backing", address, page, section_error); return FALSE; } + ++index; } std::vector<std::pair<ULONG_PTR, SIZE_T>> made; auto first = batch.begin(); @@ -724,9 +1159,20 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& ULONG_PTR failed_address; if (!map_run(first->first, head, bytes, made, failed_address)) { const DWORD error = GetLastError(); + // The page map_run stopped at: the first page of the run that has no view. + ULONG_PTR at = first->first; + while (memory.runs.count(at) && at < first->first + bytes) at += page_bytes; + const auto failed = batch.find(at); + log_refusal(what, true, count, static_cast<ULONG_PTR>(std::distance(batch.begin(), failed)), at, + failed != batch.end() ? failed->second : 0, + "Windows refused the view (sorted entry; MapViewOfFile3 / placeholder split)", error, + made.size(), true); if (failure) failure->record("map-view", failed_address, batch.at(failed_address), error); for (const auto& [base, size] : made) { - UnmapViewOfFile2(GetCurrentProcess(), reinterpret_cast<void*>(base), MEM_PRESERVE_PLACEHOLDER); + if (!UnmapViewOfFile2(GetCurrentProcess(), reinterpret_cast<void*>(base), MEM_PRESERVE_PLACEHOLDER)) + x2w_local::logf("x2w-xmem REFUSED %s: taking back the view %p+0x%llx failed (error %lu): a view the " + "registry does not know stays there", what, reinterpret_cast<void*>(base), + static_cast<unsigned long long>(size), GetLastError()); memory.runs.erase(base); } coalesce_unused(batch); @@ -737,6 +1183,7 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& } for (const auto& [address, page] : batch) ++memory.backings.at(page).views; + note_events(batch, 1); memory.views.merge(batch); } else { // Unmap every run that holds a page of the batch, then map the surviving pages of those @@ -769,6 +1216,7 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& } const bool refused = error != ERROR_SUCCESS; if (!refused) { + note_events(batch, 2); for (const auto& [address, page] : batch) { --memory.backings.at(page).views; memory.views.erase(address); @@ -795,14 +1243,17 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& } template <typename AddressAt> -BOOL map_pages(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& address_at, +BOOL map_pages(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& address_at, const char* what, MapFailure* failure = nullptr) noexcept { X2W_ZONE("xmem map_pages"); + if (!count || count > era_physical::capacity_pages) + return physical_result(era_physical::Status::invalid); const bool share_views = fault_retry.ready(); const MappingThread marker; const std::lock_guard guard(memory.mutex); - return map_pages_locked(count, tokens, address_at, share_views, failure); + const ChangingGpuMappings changing; + return map_pages_locked(count, tokens, address_at, share_views, what, failure); } } @@ -844,8 +1295,9 @@ void* local_virtual_alloc(void* address, SIZE_T bytes, DWORD type, ULONGLONG att how = "placeholder kept for page mapping"; } else if (type & MEM_COMMIT) { if (!address) { - result = VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, protect); + result = x2w_low::alloc(bytes, MEM_COMMIT | MEM_RESERVE, protect); how = "commit"; + if (result) InterlockedAdd64(&permissive_commit_bytes, static_cast<LONG64>(bytes)), InterlockedIncrement64(&permissive_commit_calls); } else { result = VirtualAlloc(address, bytes, MEM_COMMIT, protect); if (!result) { @@ -854,12 +1306,24 @@ void* local_virtual_alloc(void* address, SIZE_T bytes, DWORD type, ULONGLONG att MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, protect, nullptr, 0); } how = "commit at address"; + if (result) InterlockedAdd64(&permissive_commit_bytes, static_cast<LONG64>(bytes)), InterlockedIncrement64(&permissive_commit_calls); } } else { - result = VirtualAlloc2(GetCurrentProcess(), address, bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, - nullptr, 0); + result = address ? VirtualAlloc2(GetCurrentProcess(), address, bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, + nullptr, 0) + : x2w_low::alloc(bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS); // A caller that asks for a placeholder splits it itself; other reservations are split here on mapping. if (result && !(type & MEM_RESERVE_PLACEHOLDER)) record_reservation(result, bytes); + if (result && (type & MEM_RESERVE_PLACEHOLDER) && linear_placement()) { + const std::lock_guard guard(memory.mutex); + const auto start = reinterpret_cast<ULONG_PTR>(result); + auto& regions = memory.linear_reservations; + auto next = regions.lower_bound(start); + if (next != regions.begin() && start - std::prev(next)->first < std::prev(next)->second.bytes) + regions.erase(std::prev(next)); + while (next != regions.end() && next->first - start < bytes) next = regions.erase(next); + if (bytes && bytes <= slab_bytes && bytes % page_bytes == 0) regions.emplace(start, LinearReservation{bytes}); + } how = "placeholder reserve"; } const DWORD error = result ? 0 : GetLastError(); @@ -924,9 +1388,29 @@ void log_failed_ranges(const char* what, const char* operation, const std::vecto BOOL local_apply_locked(ULONG_PTR count, const ULONG_PTR* addresses, const ULONG_PTR* pages, const char* what, bool share_views) { - std::map<ULONG_PTR, ULONG_PTR> want; - for (ULONG_PTR i = 0; i < count; ++i) want[addresses[i]] = pages[i]; + // The pairs in ascending address order, the last pair for a repeated address winning, as an + // ordered map assigned in call order would give; but one allocation instead of a tree node per + // page (a single call can carry ~100,000 pages). + std::vector<std::pair<ULONG_PTR, ULONG_PTR>> want; + want.reserve(count); + bool ascending = true; + for (ULONG_PTR i = 0; i < count; ++i) { + ascending = ascending && (!i || addresses[i] > addresses[i - 1]); + want.emplace_back(addresses[i], pages[i]); + } + if (!ascending) { + std::stable_sort(want.begin(), want.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); + std::size_t kept = 0; + for (std::size_t i = 0; i < want.size(); ++i) { + if (i + 1 < want.size() && want[i + 1].first == want[i].first) continue; // a later pair names it again + want[kept++] = want[i]; + } + want.resize(kept); + } std::vector<ULONG_PTR> unmap, map_at, map_page; + // The plan (which addresses to unmap, which to map) and both steps run under ONE hold of the mutex (the + // caller's, local_apply): a call from another thread naming the same addresses in between would make the plan + // wrong and the call fail, where the console applies both calls one after the other. for (const auto& [address, page] : want) { const auto live = memory.views.find(address); if (!page) { @@ -936,6 +1420,7 @@ BOOL local_apply_locked(ULONG_PTR count, const ULONG_PTR* addresses, const ULONG if (live != memory.views.end()) { if (live->second == page) continue; unmap.push_back(address); + ++remap_gaps; } map_at.push_back(address); map_page.push_back(page); @@ -943,14 +1428,16 @@ BOOL local_apply_locked(ULONG_PTR count, const ULONG_PTR* addresses, const ULONG BOOL ok = TRUE; DWORD error = 0; MapFailure failure; + std::optional<ChangingGpuMappings> changing; + if (!unmap.empty() || !map_at.empty()) changing.emplace(); if (!unmap.empty() && !map_pages_locked(unmap.size(), nullptr, [&](ULONG_PTR i) { return unmap[i]; }, - share_views, &failure)) { + share_views, what, &failure)) { ok = FALSE; error = GetLastError(); } if (ok && !map_at.empty() && !map_pages_locked(map_at.size(), map_page.data(), [&](ULONG_PTR i) { return map_at[i]; }, - share_views, &failure)) { + share_views, what, &failure)) { ok = FALSE; error = GetLastError(); } @@ -961,10 +1448,14 @@ BOOL local_apply_locked(ULONG_PTR count, const ULONG_PTR* addresses, const ULONG } static LONG calls; if (!ok || x2w_local::first_calls(calls, 16)) - x2w_local::logf("x2w-xmem %s count=0x%llx first=%p map=%llu unmap=%llu -> %d (err %lu)", what, - static_cast<unsigned long long>(count), count ? reinterpret_cast<void*>(addresses[0]) : nullptr, - static_cast<unsigned long long>(map_at.size()), static_cast<unsigned long long>(unmap.size()), ok, - static_cast<unsigned long>(error)); + x2w_local::logf("x2w-xmem %s count=0x%llx first=%p map=%llu unmap=%llu -> %d (err %lu) thread %lu, %s, lowest %p " + "highest %p%s", what, static_cast<unsigned long long>(count), + count ? reinterpret_cast<void*>(addresses[0]) : nullptr, static_cast<unsigned long long>(map_at.size()), + static_cast<unsigned long long>(unmap.size()), ok, static_cast<unsigned long>(error), + GetCurrentThreadId(), ascending ? "ascending" : "unsorted", + want.empty() ? nullptr : reinterpret_cast<void*>(want.front().first), + want.empty() ? nullptr : reinterpret_cast<void*>(want.back().first), + ok ? "" : " (the x2w-xmem REFUSED line above names the entry and the cause; no page of the refused step is mapped)"); SetLastError(error); return ok; } @@ -1015,6 +1506,7 @@ BOOL free_pages(ULONG_PTR count, PULONG_PTR pages); extern "C" BOOL WINAPI XMemAllocatePhysicalPages(ULONG_PTR flags, PULONG_PTR count, PULONG_PTR pages) { + x2w_census::start(); static_assert(sizeof(ULONG_PTR) == sizeof(std::uint64_t)); if (local_permissive()) { const ULONG_PTR requested = count ? *count : 0; @@ -1062,11 +1554,12 @@ BOOL free_pages(ULONG_PTR count, PULONG_PTR pages) 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}; + // LOCAL allocator (option a): the slot returns to free_slots, unless a section lease still pins it. + const Slot slot{backing->second.section, 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.free_slots.insert(slot); memory.backings.erase(backing); } } @@ -1235,6 +1728,7 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& it->second.actual = 0; }; + const ChangingGpuMappings changing; begin_break(broken); const EndBreak end; DWORD error = ERROR_SUCCESS; @@ -1373,6 +1867,19 @@ extern "C" HRESULT WINAPI X2WMapPageBatch(UINT count, const X2WPageBatch* batche memory.explicit_mirror_pages.merge(explicit_pages); if (stats) *stats = result; } + static const bool trace = x2w_local::env_on("X2W_GPU_DROP_TRACE"); + if (trace) { + static UINT64 calls, changed, unchanged; + ++calls; + changed += SUCCEEDED(hr) ? result.pagesChanged : 0; + unchanged += SUCCEEDED(hr) ? result.pagesSkipped : 0; + if (calls <= 8 || !(calls & (calls - 1))) { + const auto& r = ranges.front(); + x2w_local::logf("x2w-xmem queue page batch %llu: hr=0x%08lx pool=0x%llx poolPages=%u ranges=%zu pages=%u firstDest=0x%llx kind=%u start=%u count=%u changed=%llu skipped=%llu", + calls, hr, pool, poolPages, ranges.size(), total, r.address, r.source.kind, r.source.start, r.source.count, + changed, unchanged); + } + } return hr; } catch (const std::bad_alloc&) { return E_OUTOFMEMORY; @@ -1405,10 +1912,10 @@ extern "C" BOOL WINAPI x2w_xmem_lease_section(UINT version, ULONG_PTR address, S if (!slot) return FALSE; if (selected.empty()) section = slot->section; - else if (slot->section != section || slot->slab != selected.front().first || + else if (slot->section != section || slot->offset != selected.front().second + i * page_bytes) return FALSE; - selected.emplace_back(slot->slab, slot->offset); + selected.emplace_back(slot->section, slot->offset); } if (!DuplicateHandle(GetCurrentProcess(), section, GetCurrentProcess(), &duplicate, 0, FALSE, DUPLICATE_SAME_ACCESS)) @@ -1445,7 +1952,7 @@ extern "C" BOOL WINAPI x2w_xmem_match_section(UINT version, ULONG64 lease, SIZE_ const auto first_page = address & ~(page_bytes - 1); for (SIZE_T slot = first_slot; slot <= last_slot; ++slot) { const auto* backing = lease_backing(version, first_page + (slot - first_slot) * page_bytes); - if (!backing || pin.slots[slot] != Slot{backing->slab, backing->offset}) return FALSE; + if (!backing || pin.slots[slot] != Slot{backing->section, backing->offset}) return FALSE; } return TRUE; } @@ -1471,6 +1978,41 @@ extern "C" BOOL WINAPI x2w_xmem_page_stats(ULONGLONG* live_sections) return TRUE; } +// LOCAL accounting exports (xmem_census.h). +extern "C" BOOL WINAPI x2w_xmem_memory_stats(X2wXmemStats* stats) +{ + if (!stats) return FALSE; + const std::lock_guard guard(memory.mutex); + stats->slabs = memory.slabs.size(); + stats->slab_bytes = memory.slabs.size() * slab_bytes; + stats->live_pages = memory.backings.size(); + stats->free_slots = memory.free_slots.size(); + stats->slab_budget_bytes = slab_budget_bytes(); + stats->slab_refusals = static_cast<ULONGLONG>(slab_refusals); + stats->startup_block_bytes = static_cast<ULONGLONG>(startup_block_bytes); + stats->startup_block_calls = static_cast<ULONGLONG>(startup_block_calls); + stats->permissive_commit_bytes = static_cast<ULONGLONG>(permissive_commit_bytes); + stats->permissive_commit_calls = static_cast<ULONGLONG>(permissive_commit_calls); + stats->reservations = memory.reservations.size(); + stats->file_slabs = memory.file_slabs.size(); + stats->migrations = memory.migrations; + stats->migration_failures = memory.migration_failures; + return TRUE; +} + +extern "C" SIZE_T WINAPI x2w_xmem_reserved_ranges(ULONG_PTR* pairs, SIZE_T capacity) +{ + const std::lock_guard guard(memory.mutex); + SIZE_T i = 0; + for (const auto& [base, bytes] : memory.reservations) { + if (pairs && i < capacity) { + pairs[2 * i] = base; + pairs[2 * i + 1] = bytes; + } + ++i; + } + return i; +} // 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. @@ -1478,12 +2020,16 @@ extern "C" BOOL WINAPI x2w_xmem_slab_stats(ULONGLONG* slabs, ULONGLONG* slots_in { if (!slabs || !slots_in_use || !slots_free) return FALSE; const std::lock_guard guard(memory.mutex); - *slabs = memory.slots.slab_count(); - *slots_in_use = memory.slots.slots_in_use(); - *slots_free = memory.slots.slots_free(); + // LOCAL allocator (option a at the upstream merge): slabs of memory.slabs (pagefile, file-backed and GPU-pool + // slabs alike), slots that back a granted page, and free slots: released ones plus the unused tail of the newest slab. + *slabs = memory.slabs.size(); + *slots_in_use = memory.backings.size(); + *slots_free = memory.free_slots.size() + (memory.slabs.empty() ? 0 : (slab_bytes - memory.slab_used) / page_bytes); return TRUE; } +// LOCAL note: commit-on-first-touch of slots is not ported onto the local allocator, so no slot is lazy and this +// only acts on lazy startup blocks (X2W_XMEM_LAZY_STARTUP); for mapped pages it reports already committed. // Experimental export (X2W_XMEM_LAZY_COMMIT): commits the lazily mapped slots behind [address, address + bytes) // before a writer that cannot fault one in uses the range: kernel-mode I/O into mapped pages fails with // STATUS_ACCESS_VIOLATION instead of faulting, and the GPU reads and writes placed resources without the CPU. @@ -1637,14 +2183,12 @@ extern "C" BOOL WINAPI x2w_xmem_write_physical(const ULONG_PTR* tokens, ULONG_PT ULONG_PTR index = 0; while (bytes) { if (index >= count || (tokens[index] & 0xF)) return FALSE; - HANDLE section = nullptr; - ULONG64 section_offset = 0; - { - const std::lock_guard guard(memory.mutex); - section = section_for(tokens[index] >> 4); - if (section) section_offset = memory.backings.at(tokens[index] >> 4).offset; - } + // The lock is held across the write: a slab move (migrate_slab) must not happen between + // finding the section and writing into it. + const std::lock_guard guard(memory.mutex); + const HANDLE section = section_for(tokens[index] >> 4); if (!section) return FALSE; + const ULONG64 section_offset = memory.backings.at(tokens[index] >> 4).offset; void* view = MapViewOfFile(section, FILE_MAP_WRITE, static_cast<DWORD>(section_offset >> 32), static_cast<DWORD>(section_offset), page_bytes); if (!view) return FALSE; @@ -1682,7 +2226,7 @@ extern "C" void* WINAPI XMemMapPhysicalPages(void* base, ULONG_PTR count, const if (!local_apply(count, addresses.data(), pages.data(), "XMemMapPhysicalPages")) return nullptr; return base; } - return map_pages(count, tokens, [=](ULONG_PTR i) { return address + i * page_bytes; }) ? base : nullptr; + return map_pages(count, tokens, [=](ULONG_PTR i) { return address + i * page_bytes; }, "XMemMapPhysicalPages") ? base : nullptr; } extern "C" BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, ULONG_PTR count, @@ -1696,7 +2240,7 @@ extern "C" BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, ULONG return FALSE; return TRUE; } - return map_pages(count, tokens, [=](ULONG_PTR i) { return reinterpret_cast<ULONG_PTR>(addresses[i]); }); + return map_pages(count, tokens, [=](ULONG_PTR i) { return reinterpret_cast<ULONG_PTR>(addresses[i]); }, "XMemMapPhysicalPagesScatter"); } // Startup compatibility configuration (#1758, under #874): X2W_XMEM_STARTUP_BELOW_40=1 places the @@ -1762,8 +2306,8 @@ static void* keep_startup_block_below_40(void* block, SIZE_T bytes, ULONGLONG at // granularity. Large pages themselves and the console protection bits above PAGE_READWRITE // are not reproduced. A host failure returns NULL with the host error. X2W_XMEM_STARTUP_BELOW_40 // adds an address limit for the 0x283 blocks (keep_startup_block_below_40). -static void* commit_startup_block(SIZE_T bytes, DWORD allocation_type, ULONGLONG attributes, - DWORD protection) noexcept +static void* commit_startup_block_raw(SIZE_T bytes, DWORD allocation_type, ULONGLONG attributes, + DWORD protection) noexcept { constexpr SIZE_T granularity = SIZE_T{64} << 10; const bool large_pages = allocation_type == 0x20003000; @@ -1781,10 +2325,14 @@ static void* commit_startup_block(SIZE_T bytes, DWORD allocation_type, ULONGLONG const DWORD type = lazy ? MEM_RESERVE : MEM_RESERVE | MEM_COMMIT; void* block = nullptr; if (!large_pages) { - block = VirtualAlloc(nullptr, bytes, type, PAGE_READWRITE); + block = x2w_low::alloc(bytes, type, PAGE_READWRITE); // LOCAL: X2W_XMEM_LOW40 (xmem_low.h) } else { MEM_ADDRESS_REQUIREMENTS requirements{}; requirements.Alignment = SIZE_T{2} << 20; + if (x2w_low::on()) { // LOCAL: X2W_XMEM_LOW40 (xmem_low.h) + requirements.LowestStartingAddress = reinterpret_cast<void*>(ULONG_PTR{1} << 32); + requirements.HighestEndingAddress = reinterpret_cast<void*>((ULONG_PTR{1} << 40) - 1); + } // supported already limits attribute 0x283 to protection 0x2004 or 0x2404. if (below_40 && !startup_below_40_mutant("no_limit")) requirements.HighestEndingAddress = reinterpret_cast<void*>(startup_low_limit - 1); @@ -1813,11 +2361,33 @@ static void* commit_startup_block(SIZE_T bytes, DWORD allocation_type, ULONGLONG return block; } +// LOCAL accounting: the startup blocks are counted and their first calls logged (the path was +// silent before); the ranges go to the census (xmem_census.cpp). +static void* commit_startup_block(SIZE_T bytes, DWORD allocation_type, ULONGLONG attributes, + DWORD protection) noexcept +{ + void* block = commit_startup_block_raw(bytes, allocation_type, attributes, protection); + const DWORD error = GetLastError(); + if (block) { + InterlockedAdd64(&startup_block_bytes, static_cast<LONG64>(bytes)); + x2w_census::note_block(block, bytes); + } + const LONG64 n = InterlockedIncrement64(&startup_block_calls); + if (n <= 64 || !block) + x2w_local::logf("x2w-xmem startup block #%lld size=0x%llx type=0x%lx attr=0x%llx prot=0x%lx -> %p (err %lu), %lld MiB so far", + static_cast<long long>(n), static_cast<unsigned long long>(bytes), static_cast<unsigned long>(allocation_type), + attributes, static_cast<unsigned long>(protection), block, block ? 0ul : static_cast<unsigned long>(error), + static_cast<long long>(startup_block_bytes >> 20)); + SetLastError(error); + return block; +} + // The startup commit profile above, and the reserve-only desktop profile from the source-built // #888 comparison. extern "C" void* WINAPI XMemVirtualAlloc(void* address, SIZE_T bytes, DWORD allocation_type, ULONGLONG attributes, DWORD protection) { + x2w_census::start(); constexpr DWORD startup_reserve = 0x20402000; constexpr SIZE_T gib = SIZE_T{1} << 30; if (!address && (allocation_type == 0x20003000 || allocation_type == (startup_reserve | MEM_COMMIT))) @@ -1839,8 +2409,7 @@ extern "C" void* WINAPI XMemVirtualAlloc(void* address, SIZE_T bytes, DWORD allo else ++it; } - auto* reservation = VirtualAlloc2(GetCurrentProcess(), nullptr, bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, - PAGE_NOACCESS, nullptr, 0); + auto* reservation = x2w_low::alloc(bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS); if (!reservation) return nullptr; try { memory.reservations.insert_or_assign(reinterpret_cast<ULONG_PTR>(reservation), bytes); @@ -1864,3 +2433,198 @@ extern "C" void* WINAPI XMemVirtualAlloc(void* address, SIZE_T bytes, DWORD allo } return reservation; } + +extern "C" BOOL WINAPI x2w_xmem_page_event(const void* address, ULONG* event_kind, ULONG64* page, ULONG* thread, + ULONG64* age_ms, ULONG64* serial, ULONG64* remaps) +{ + const auto at = reinterpret_cast<ULONG_PTR>(address) & ~(ULONG_PTR{page_bytes} - 1); + const std::lock_guard guard(memory.mutex); + const auto event = page_events.find(at); + const PageEvent e = event != page_events.end() ? event->second : PageEvent{}; + if (event_kind) *event_kind = e.kind; + if (page) *page = e.page; + if (thread) *thread = e.thread; + if (age_ms) *age_ms = e.tick ? GetTickCount64() - e.tick : 0; + if (serial) *serial = e.serial; + if (remaps) *remaps = remap_gaps; + return memory.views.count(at) != 0; +} + +bool writable_protection(DWORD protection) noexcept +{ + if (protection & PAGE_GUARD) return false; + const DWORD base = protection & 0xff; + return base == PAGE_READWRITE || base == PAGE_WRITECOPY || base == PAGE_EXECUTE_READWRITE || base == PAGE_EXECUTE_WRITECOPY; +} + +bool resident_writable(ULONG_PTR start, SIZE_T bytes) noexcept +{ + if (!bytes) return true; + static const ULONG_PTR os_page = [] { + SYSTEM_INFO info{}; + GetSystemInfo(&info); + return static_cast<ULONG_PTR>(info.dwPageSize); + }(); + const ULONG_PTR first = start - start % os_page; + const SIZE_T count = (start + bytes - 1 - first) / os_page + 1; + constexpr SIZE_T max_pages = 32; + if (count > max_pages) return false; + PSAPI_WORKING_SET_EX_INFORMATION pages[max_pages]; + for (SIZE_T i = 0; i < count; ++i) { + pages[i].VirtualAddress = reinterpret_cast<void*>(first + i * os_page); + pages[i].VirtualAttributes.Flags = 0; + } + if (!QueryWorkingSetEx(GetCurrentProcess(), pages, static_cast<DWORD>(count * sizeof(pages[0])))) return false; + for (SIZE_T i = 0; i < count; ++i) { + const auto attrs = pages[i].VirtualAttributes; + if (!attrs.Valid || attrs.Bad || !writable_protection(static_cast<DWORD>(attrs.Win32Protection))) return false; + } + return true; +} + +// True when every byte of [start, start + bytes) is committed read-write. +bool range_writable(ULONG_PTR start, SIZE_T bytes) noexcept +{ + if (resident_writable(start, bytes)) return true; + for (ULONG_PTR cursor = start; cursor < start + bytes;) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast<const void*>(cursor), &info, sizeof(info)) || info.State != MEM_COMMIT || + !writable_protection(info.Protect)) + return false; + const ULONG_PTR end = reinterpret_cast<ULONG_PTR>(info.BaseAddress) + info.RegionSize; + if (end <= cursor) return false; + cursor = end; + } + return true; +} + +extern "C" BOOL WINAPI x2w_xmem_write_settled(void* destination, const void* data, SIZE_T bytes, SIZE_T capacity) +{ + if (!destination || (bytes && !data) || bytes > capacity) return FALSE; + const auto start = reinterpret_cast<ULONG_PTR>(destination); + if (capacity > std::numeric_limits<ULONG_PTR>::max() - start) return FALSE; + const MappingThread marker; // a fault in the copy is never retried by retry_remapped_page (it takes the mutex) + static const bool timing = x2w_local::env_on("X2W_DSTORAGE_TIMING"); + LARGE_INTEGER began{}, locked{}, checked{}, copied{}; + if (timing) QueryPerformanceCounter(&began); + std::unique_lock guard(memory.mutex); + // Inside a recorded reservation, or one starts inside the destination. + const auto next = memory.reservations.upper_bound(start); + const bool ours = owned_reservation(start) != memory.reservations.end() || + (next != memory.reservations.end() && next->first < start + capacity); + if (!ours) guard.unlock(); + if (timing) QueryPerformanceCounter(&locked); + const bool writable = range_writable(start, capacity); + if (timing) QueryPerformanceCounter(&checked); + if (writable) std::memcpy(destination, data, bytes); + if (timing) { + if (guard.owns_lock()) guard.unlock(); + QueryPerformanceCounter(&copied); + struct Times { + unsigned requests{}, owned{}, refused{}; + ULONG_PTR first{}; + UINT64 bytes{}; + LONG64 lock{}, check{}, copy{}; + }; + thread_local Times batch; + if (!batch.requests) batch.first = start; + batch.lock += locked.QuadPart - began.QuadPart; + batch.check += checked.QuadPart - locked.QuadPart; + batch.copy += copied.QuadPart - checked.QuadPart; + batch.bytes += bytes; + batch.owned += unsigned(ours); + batch.refused += unsigned(!writable); + if (++batch.requests == 256) { + static const double to_ms = [] { + LARGE_INTEGER frequency{}; + QueryPerformanceFrequency(&frequency); + return 1000.0 / frequency.QuadPart; + }(); + x2w_local::logf("x2w-xmem storage writes tid=%lu first=0x%llx last=0x%llx requests=%u owned=%u refused=%u " + "bytes=%llu total ms: lock=%.2f writable=%.2f copy=%.2f", + GetCurrentThreadId(), static_cast<UINT64>(batch.first), static_cast<UINT64>(start), batch.requests, + batch.owned, batch.refused, batch.bytes, batch.lock * to_ms, batch.check * to_ms, batch.copy * to_ms); + batch = {}; + } + } + return writable; +} + +extern "C" BOOL WINAPI x2w_xmem_write_settled_wait(void* destination, const void* data, SIZE_T bytes, SIZE_T capacity, + ULONG wait_ms, ULONG* waited_ms) +{ + const ULONG64 began = GetTickCount64(); + for (;;) { + const BOOL ok = x2w_xmem_write_settled(destination, data, bytes, capacity); + const ULONG64 spent = GetTickCount64() - began; + if (ok || spent >= wait_ms) { + if (waited_ms) *waited_ms = static_cast<ULONG>(spent); + return ok; + } + Sleep(5); + } +} + +extern "C" ULONG64 WINAPI x2w_xmem_gpu_mapping_generation() +{ + const auto observed = gpu_mapping_generation.load(std::memory_order_acquire); + if ((observed & 1) == 0) return observed; + const std::lock_guard guard(memory.mutex); + return gpu_mapping_generation.load(std::memory_order_acquire); +} + +// LOCAL export: the section (a 256 MiB slab, see section_for) and byte offset behind a mapped title +// address, so that a desktop GPU heap opened over the slab reads and writes the pages the title maps. +// FALSE when the address is not in a mapped page. +extern "C" BOOL WINAPI x2w_xmem_gpu_location(const void* address, HANDLE* section, ULONG64* offset) +{ + if (!section || !offset) return FALSE; + const auto at = reinterpret_cast<ULONG_PTR>(address); + const std::lock_guard guard(memory.mutex); + const auto view = memory.views.find(at - at % page_bytes); + if (view == memory.views.end()) return FALSE; + const auto backing = memory.backings.find(view->second); + if (backing == memory.backings.end()) return FALSE; + if (memory.file_slabs.count(backing->second.section) && !migrate_slab(backing->second.section)) return FALSE; + *section = backing->second.section; // the pagefile slab after a move + *offset = backing->second.offset + at % page_bytes; + return TRUE; +} + +// LOCAL memcut (X2W_MEMCUT_ALIAS_SLABS in d3d12_xs): the pool section and byte offset behind [address, address + +// bytes) when that whole range is mapped pages of ONE long-lived pool section (X2W_XMEM_GPU_POOL=all) at consecutive +// offsets, so that one buffer placed on a heap over the section covers exactly the title's pages. Never moves a slab +// (file-backed and fresh pagefile slabs answer FALSE: a fresh section opened as a heap would stay charged after the +// run). address must be page aligned. +extern "C" BOOL WINAPI x2w_xmem_pool_run(const void* address, SIZE_T bytes, HANDLE* section, ULONG64* offset) +{ + if (!section || !offset || !bytes) return FALSE; + const auto at = reinterpret_cast<ULONG_PTR>(address); + if (at % page_bytes) return FALSE; +#ifdef X2W_XMEM_TEST_CONTROLS + // Test build only: any slab counts as a pool section (a fixture must not claim the real pool). + static const bool any_slab = x2w_local::env_on("X2W_XMEM_TEST_POOL_ANY"); +#else + constexpr bool any_slab = false; +#endif + const std::lock_guard guard(memory.mutex); + HANDLE first_section = nullptr; + ULONG64 first_offset = 0; + for (SIZE_T done = 0; done < bytes; done += page_bytes) { + const auto view = memory.views.find(at + done); + if (view == memory.views.end()) return FALSE; + const auto backing = memory.backings.find(view->second); + if (backing == memory.backings.end()) return FALSE; + const HANDLE s = backing->second.section; + if (!done) { + if (!memory.pool_views.count(s) && !any_slab) return FALSE; // not a pool section + first_section = s; + first_offset = backing->second.offset; + } else if (s != first_section || backing->second.offset != first_offset + done) { + return FALSE; // the pages are not consecutive in one section + } + } + *section = first_section; + *offset = first_offset; + return TRUE; +} diff --git a/src/xmem_shim.cpp b/src/xmem_shim.cpp index a5b43f0f1d..e9341ae9a6 100644 --- a/src/xmem_shim.cpp +++ b/src/xmem_shim.cpp @@ -28,6 +28,7 @@ #define NOMINMAX #endif #include <windows.h> +#include "xmem_low.h" namespace { // The BVH callers' query buffer. era_query writes at most its first 0x31 bytes. @@ -57,7 +58,7 @@ std::unordered_set<void*>& local_blocks() void* local_alloc(SIZE_T bytes, ULONGLONG attributes) { - void* block = bytes ? VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) : nullptr; + void* block = bytes ? x2w_low::alloc(bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) : nullptr; if (block) { AcquireSRWLockExclusive(&local_lock); local_blocks().insert(block); diff --git a/src/xmem_shim.def b/src/xmem_shim.def index 3776c7529f..3fb25287c3 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -15,10 +15,18 @@ EXPORTS XMemTransferMemory @13 x2w_xmem_write_physical @14 x2w_xmem_page_stats @15 - x2w_xmem_slab_stats @16 - x2w_xmem_commit_range @17 - x2w_xmem_commit_block @18 - x2w_xmem_lease_section @19 - x2w_xmem_release_section @20 - x2w_xmem_match_section @21 - X2WMapPageBatch @22 + x2w_xmem_gpu_location @16 + x2w_xmem_memory_stats @17 + x2w_xmem_reserved_ranges @18 + x2w_xmem_pool_run @19 + x2w_xmem_page_event @20 + x2w_xmem_write_settled @21 + x2w_xmem_write_settled_wait @22 + x2w_xmem_slab_stats @23 + x2w_xmem_commit_range @24 + x2w_xmem_commit_block @25 + x2w_xmem_lease_section @26 + x2w_xmem_release_section @27 + x2w_xmem_match_section @28 + X2WMapPageBatch @29 + x2w_xmem_gpu_mapping_generation @30 diff --git a/tests/bcpack_bc6h_test.cpp b/tests/bcpack_bc6h_test.cpp new file mode 100644 index 0000000000..341cb1d134 --- /dev/null +++ b/tests/bcpack_bc6h_test.cpp @@ -0,0 +1,127 @@ +// BC6H BCPack rebuild (src/startup_stubs/bcpack_bc6h.h) on synthetic lane symbols (no title data). +// 1. Exact path: 48 blocks over all 14 modes whose references stay inside the stream; expected bytes +// from an independent Python model (bcpack_bc6h_vectors.inl). +// 2. Fallback path: the same stream with block 0 pointed at the dictionary; every block whose +// endpoint chain starts there must be counted and must still be a legal block (mode, anchors). +// 3. Negative control: a mode code of 14 fails the stream. +// Exit code 0 = pass. +#include <cstdio> +#include <cstring> +#include <vector> + +#include "../src/startup_stubs/bcpack_bc6h.h" + +namespace { +#include "bcpack_bc6h_vectors.inl" + +using namespace x2w_bcpack; + +int failures = 0; + +void check(bool ok, const char* what) { + std::printf("%s %s\n", ok ? "pass" : "FAIL", what); + failures += ok ? 0 : 1; +} + +// Mode index of a packed block, or -1. +int mode_of(const uint8_t* b) { + const uint32_t m2 = b[0] & 3u; + if (m2 < 2) return static_cast<int>(m2); + for (int k = 2; k < 14; ++k) + if ((b[0] & 31u) == bc6h::MODES[k].code) return k; + return -1; +} + +} // namespace + +int main() { + const size_t nb = BC6H_VEC_BLOCKS; + std::vector<uint16_t> sym(BC6H_VEC_SYMBOLS, BC6H_VEC_SYMBOLS + 16 * 2 * nb); + std::vector<uint8_t> out(16 * nb); + bc6h::Stats st; + bool ok = bc6h::decode_blocks(sym, nb, out.data(), out.size(), &st); + check(ok, "exact stream decodes"); + check(st.exact == nb && st.endpoints_only == 0 && st.copied == 0 && st.constant == 0, "all blocks exact"); + size_t first = nb; + for (size_t i = 0; i < nb && first == nb; ++i) + if (std::memcmp(out.data() + 16 * i, BC6H_VEC_BLOCKS_OUT + 16 * i, 16) != 0) first = i; + if (first != nb) std::printf(" first mismatch at block %zu\n", first); + check(first == nb, "blocks match the independent model byte for byte"); + + // Block 0: endpoint reference 1 and index reference 1 (> 0 = before the stream start: slot 0). + std::vector<uint16_t> fb = sym; + const size_t t = 2 * nb; + fb[0 * t + 0] = 0; fb[0 * t + 1] = 0; // d = 0 -> er = x + fb[1 * t + 0] = 1; fb[1 * t + 1] = 0; // x = 1 + ok = bc6h::decode_blocks(fb, nb, out.data(), out.size(), &st); + check(ok, "dictionary-rooted stream decodes with fallback"); + std::printf(" exact %zu endpoints_only %zu copied %zu constant %zu\n", st.exact, st.endpoints_only, st.copied, + st.constant); + check(st.exact + st.endpoints_only + st.copied + st.constant == nb && st.exact < nb && st.copied + st.endpoints_only > 0, + "fallback classes counted"); + bool legal = true; + for (size_t i = 0; i < nb; ++i) legal &= mode_of(out.data() + 16 * i) >= 0; + check(legal, "fallback blocks carry valid modes"); + + // With a dictionary entry for slot 0 that equals the half-range start, block 0 behaves as ref 0. + static uint16_t dep[255][4][3]; + static uint8_t dix[255][16]; + static bool known[255]; + for (auto& e : dep) for (auto& r : e) for (auto& v : r) v = 0x8000; + for (auto& e : dix) for (auto& v : e) v = 8; + known[0] = true; + bc6h::Dictionary dict; + dict.ep = dep; dict.ep_known = known; dict.ix = dix; dict.ix_known = known; + std::vector<uint16_t> zero_ref = sym; + // in the original vector block 0 already references 0; compare dictionary path to it + std::vector<uint8_t> out2(16 * nb); + ok = bc6h::decode_blocks(fb, nb, out2.data(), out2.size(), &st, &dict); + std::vector<uint8_t> out3(16 * nb); + std::vector<uint16_t> fb0 = fb; + fb0[1 * t + 0] = 0; // x = 0, er = 0 + bc6h::Stats st3; + bool ok3 = bc6h::decode_blocks(fb0, nb, out3.data(), out3.size(), &st3); + check(ok && ok3 && st.exact == nb && std::memcmp(out2.data(), out3.data(), out2.size()) == 0, + "a known dictionary slot is used like a stream reference"); + + // Fallback classes against the independent model: a mixed stream (all four paths but constant) + // and a stream whose every endpoint chain is rooted (constant blocks only). + struct FbVec { const char* name; const uint16_t* symbols; const uint8_t* expected; const size_t* counts; }; + const FbVec fbv[] = { { "mixed", BC6H_MIX_SYMBOLS, BC6H_MIX_OUT, BC6H_MIX_COUNTS }, + { "all rooted", BC6H_ROOTED_SYMBOLS, BC6H_ROOTED_OUT, BC6H_ROOTED_COUNTS } }; + for (const FbVec& v : fbv) { + const size_t n = 40; + std::vector<uint16_t> s(v.symbols, v.symbols + 16 * 2 * n); + std::vector<uint8_t> o(16 * n); + bc6h::Stats fs; + const bool d = bc6h::decode_blocks(s, n, o.data(), o.size(), &fs); + const bool counts = fs.exact == v.counts[0] && fs.endpoints_only == v.counts[1] && fs.copied == v.counts[2] && + fs.constant == v.counts[3]; + std::printf(" %s: exact %zu endpoints_only %zu copied %zu constant %zu\n", v.name, fs.exact, fs.endpoints_only, + fs.copied, fs.constant); + check(d && counts && std::memcmp(o.data(), v.expected, o.size()) == 0, + v.name[0] == 'm' ? "mixed fallback stream matches the model (bytes and counts)" + : "all-rooted stream gives the model's constant blocks"); + } + // copy_known = false: the copied blocks of the mixed stream become constant blocks. + { + std::vector<uint16_t> s(BC6H_MIX_SYMBOLS, BC6H_MIX_SYMBOLS + 16 * 2 * 40); + std::vector<uint8_t> o(16 * 40); + bc6h::Stats ns; + const bool d = bc6h::decode_blocks(s, 40, o.data(), o.size(), &ns, nullptr, bc6h::DEFAULT_FILL_BASE, false); + check(d && ns.copied == 0 && ns.constant == BC6H_MIX_COUNTS[2] && ns.exact == BC6H_MIX_COUNTS[0], + "copy_known = false turns copied blocks into constant blocks"); + } + // The constant block: mode 13 (5-bit code 0x0f), base 16913 in all channels, x = 0, indices 0. + { + const uint8_t* c = BC6H_ROOTED_OUT; + check((c[0] & 31) == 0x0f, "constant block uses mode 13"); + } + + std::vector<uint16_t> bad = sym; + bad[15 * t + 2 * 5] = 14; + check(!bc6h::decode_blocks(bad, nb, out.data(), out.size(), &st), "mode code 14 is rejected"); + + std::printf("%s\n", failures ? "FAILED" : "ALL PASS"); + return failures ? 1 : 0; +} diff --git a/tests/bcpack_bc6h_vectors.inl b/tests/bcpack_bc6h_vectors.inl new file mode 100644 index 0000000000..4902b31c22 --- /dev/null +++ b/tests/bcpack_bc6h_vectors.inl @@ -0,0 +1,193 @@ +static constexpr size_t BC6H_VEC_BLOCKS = 48; +static constexpr uint16_t BC6H_VEC_SYMBOLS[16 * 96] = { + 0, 0, 0, 0, 2, 0, 1, 0, 0, 2, 3, 1, 3, 0, 0, 0, 1, 1, 0, 3, 0, 2, 0, 0, 0, 0, 3, 3, 0, 1, 1, 1, 3, 3, 6, 2, 1, 1, 1, 3, 1, 2, 0, 4, 5, 3, 1, 3, 1, 3, 2, 0, 1, 2, 1, 1, 1, 2, 0, 2, 3, 0, 1, 6, 6, 3, 0, 3, 3, 3, 0, 0, 2, 0, 4, 3, 5, 2, 0, 2, 6, 1, 7, 2, 0, 2, 3, 0, 1, 1, 2, 3, 1, 3, 1, 6, + 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 2, 0, 2, 0, 2, 0, 3, 0, 0, 0, 3, 0, 3, 1, 1, 2, 0, 2, 1, 0, 3, 0, 4, 0, 1, 1, 1, 3, 0, 3, 3, 2, 1, 0, 4, 1, 3, 1, 2, 3, 3, 0, 6, 1, 2, 0, 6, 0, 4, 0, 2, 0, 6, 1, 1, 3, 1, 0, 7, 3, 4, 0, 6, 3, 7, 0, 2, 3, 2, 0, 2, 0, 6, 0, 5, 1, 0, 4, 2, 6, 2, 4, 1, 7, 2, 7, + 58, 246, 125, 17, 34, 12, 111, 115, 202, 49, 35, 116, 57, 57, 53, 89, 164, 96, 46, 43, 142, 26, 205, 167, 233, 204, 165, 243, 166, 16, 244, 138, 107, 180, 186, 50, 82, 9, 216, 113, 131, 65, 219, 160, 55, 38, 111, 64, 120, 175, 0, 192, 157, 148, 27, 30, 155, 6, 157, 230, 30, 134, 109, 84, 0, 139, 88, 83, 97, 23, 253, 246, 163, 158, 182, 101, 198, 10, 34, 181, 138, 245, 112, 72, 68, 68, 117, 154, 73, 107, 9, 248, 150, 128, 156, 9, + 76, 119, 253, 52, 120, 72, 227, 111, 50, 175, 204, 206, 29, 96, 162, 103, 87, 233, 29, 93, 14, 77, 202, 201, 16, 210, 94, 245, 18, 72, 56, 210, 212, 155, 63, 166, 140, 2, 113, 31, 187, 173, 25, 41, 221, 216, 78, 7, 72, 24, 108, 115, 17, 159, 194, 38, 3, 172, 232, 207, 255, 160, 101, 153, 146, 101, 214, 39, 66, 221, 14, 81, 19, 216, 30, 230, 23, 35, 28, 235, 211, 114, 193, 177, 146, 224, 211, 106, 19, 129, 181, 145, 42, 145, 194, 112, + 47, 110, 50, 242, 73, 89, 146, 14, 164, 218, 197, 143, 75, 191, 232, 199, 74, 99, 163, 159, 52, 67, 192, 184, 221, 161, 182, 50, 3, 131, 56, 16, 31, 120, 137, 124, 151, 66, 192, 23, 132, 176, 224, 1, 7, 53, 22, 206, 190, 4, 90, 34, 99, 57, 139, 240, 22, 193, 189, 18, 1, 198, 217, 111, 173, 211, 165, 152, 129, 12, 231, 77, 205, 139, 144, 0, 231, 237, 39, 109, 193, 9, 148, 53, 159, 1, 203, 92, 125, 103, 200, 46, 186, 113, 6, 187, + 28, 7, 0, 18, 20, 19, 21, 12, 16, 1, 31, 5, 18, 22, 9, 20, 18, 3, 11, 20, 18, 21, 25, 4, 30, 3, 30, 11, 16, 0, 19, 1, 7, 5, 30, 6, 20, 13, 9, 6, 17, 24, 22, 28, 15, 28, 17, 10, 17, 2, 13, 20, 31, 8, 12, 29, 22, 28, 20, 14, 31, 14, 28, 5, 19, 18, 5, 24, 25, 20, 2, 6, 7, 12, 0, 5, 9, 7, 10, 17, 4, 30, 17, 29, 29, 30, 3, 6, 7, 22, 23, 22, 29, 16, 15, 4, + 14, 8, 3, 18, 26, 0, 28, 31, 29, 19, 27, 1, 13, 8, 25, 12, 0, 0, 10, 15, 11, 6, 31, 0, 16, 20, 4, 23, 7, 15, 0, 12, 30, 12, 18, 28, 22, 3, 25, 17, 0, 8, 20, 10, 4, 22, 1, 12, 6, 27, 1, 4, 8, 9, 5, 17, 2, 11, 7, 24, 16, 11, 14, 17, 20, 10, 26, 25, 31, 17, 15, 30, 25, 24, 11, 31, 11, 8, 3, 29, 31, 6, 15, 8, 27, 14, 21, 2, 28, 30, 9, 15, 29, 15, 19, 10, + 27, 17, 9, 24, 17, 22, 13, 13, 28, 1, 11, 25, 5, 4, 25, 4, 7, 25, 27, 30, 3, 30, 30, 16, 19, 6, 24, 0, 29, 1, 3, 7, 26, 24, 22, 9, 4, 7, 25, 20, 6, 24, 1, 25, 16, 29, 31, 17, 7, 29, 13, 6, 0, 30, 29, 7, 6, 15, 7, 12, 8, 21, 6, 31, 20, 26, 9, 16, 12, 17, 16, 10, 31, 2, 11, 18, 12, 2, 0, 25, 12, 25, 26, 15, 13, 5, 29, 19, 22, 14, 18, 20, 3, 29, 29, 22, + 3, 42, 5, 3, 13, 34, 8, 41, 20, 24, 36, 30, 38, 6, 35, 4, 47, 41, 5, 14, 8, 41, 51, 21, 30, 17, 13, 48, 56, 45, 2, 18, 44, 41, 13, 44, 43, 57, 12, 48, 34, 17, 61, 23, 47, 2, 49, 40, 43, 52, 13, 39, 2, 33, 45, 18, 53, 39, 30, 29, 49, 60, 39, 35, 48, 29, 57, 29, 9, 21, 25, 0, 6, 12, 17, 46, 6, 39, 44, 6, 11, 37, 41, 60, 40, 36, 37, 42, 42, 55, 27, 55, 26, 5, 4, 50, + 63, 38, 13, 42, 63, 31, 53, 36, 46, 21, 62, 46, 10, 7, 48, 25, 52, 17, 48, 53, 44, 28, 6, 55, 38, 28, 25, 8, 41, 45, 18, 3, 35, 46, 54, 4, 37, 45, 16, 54, 8, 20, 62, 38, 13, 1, 46, 28, 51, 57, 25, 44, 44, 61, 5, 59, 11, 27, 39, 10, 30, 24, 55, 38, 45, 11, 43, 49, 32, 60, 25, 50, 49, 21, 50, 3, 13, 10, 51, 28, 58, 44, 25, 40, 27, 61, 16, 22, 56, 43, 40, 6, 13, 46, 8, 55, + 37, 51, 18, 41, 47, 12, 26, 36, 6, 12, 28, 63, 0, 25, 42, 43, 13, 50, 29, 52, 21, 7, 36, 48, 26, 34, 43, 12, 27, 48, 40, 2, 20, 15, 43, 21, 2, 29, 32, 27, 47, 43, 57, 11, 63, 46, 40, 62, 53, 48, 49, 23, 38, 5, 9, 62, 48, 7, 24, 30, 5, 47, 39, 54, 13, 62, 49, 37, 41, 7, 63, 9, 57, 45, 3, 23, 50, 13, 24, 17, 22, 0, 39, 59, 60, 16, 6, 50, 38, 24, 16, 21, 9, 35, 3, 57, + 191, 121, 238, 109, 51, 106, 115, 116, 91, 204, 134, 7, 180, 15, 7, 40, 193, 152, 247, 215, 160, 239, 31, 213, 226, 242, 212, 60, 235, 153, 157, 35, 174, 51, 28, 11, 207, 234, 124, 108, 232, 136, 242, 119, 145, 104, 139, 89, 141, 144, 45, 8, 15, 52, 49, 122, 94, 31, 7, 136, 44, 27, 249, 105, 148, 71, 210, 245, 157, 130, 140, 212, 97, 52, 16, 94, 97, 235, 160, 119, 196, 58, 95, 65, 128, 71, 208, 37, 177, 42, 54, 40, 151, 81, 48, 175, + 106, 163, 99, 67, 48, 83, 93, 141, 144, 240, 55, 178, 132, 110, 29, 102, 17, 41, 40, 54, 160, 172, 207, 101, 150, 140, 247, 226, 111, 102, 87, 181, 222, 115, 64, 207, 110, 239, 20, 143, 219, 29, 232, 66, 219, 14, 2, 213, 69, 66, 202, 220, 133, 30, 146, 173, 30, 49, 26, 193, 195, 195, 197, 254, 132, 13, 14, 240, 201, 194, 73, 105, 147, 238, 218, 15, 101, 26, 50, 76, 8, 38, 95, 88, 100, 250, 126, 63, 170, 3, 244, 37, 160, 185, 24, 254, + 223, 55, 130, 116, 129, 228, 157, 43, 254, 108, 195, 25, 158, 140, 4, 134, 122, 3, 45, 227, 69, 85, 146, 65, 119, 11, 194, 89, 23, 14, 52, 64, 150, 246, 169, 244, 220, 238, 204, 102, 209, 92, 215, 105, 151, 12, 167, 137, 5, 92, 209, 26, 186, 10, 158, 84, 160, 17, 245, 26, 31, 219, 36, 185, 216, 247, 104, 228, 96, 64, 108, 31, 88, 36, 158, 141, 105, 142, 30, 151, 109, 190, 16, 224, 70, 123, 223, 181, 227, 252, 148, 218, 73, 81, 116, 197, + 90, 0, 94, 22, 245, 155, 12, 33, 246, 3, 199, 208, 210, 204, 44, 82, 149, 10, 90, 231, 27, 210, 187, 185, 176, 45, 246, 115, 60, 65, 98, 48, 0, 24, 91, 192, 46, 65, 132, 147, 144, 254, 190, 235, 127, 187, 76, 242, 159, 117, 56, 48, 165, 88, 151, 157, 4, 200, 130, 244, 32, 148, 223, 59, 35, 248, 78, 126, 37, 16, 79, 71, 160, 0, 31, 239, 81, 110, 149, 251, 157, 189, 219, 96, 21, 31, 178, 141, 112, 64, 196, 38, 24, 45, 81, 90, + 7, 23, 8, 16, 6, 23, 12, 20, 2, 18, 12, 8, 8, 6, 8, 22, 8, 10, 1, 16, 2, 12, 0, 14, 2, 0, 1, 9, 10, 9, 1, 18, 0, 9, 11, 23, 7, 10, 0, 22, 9, 12, 7, 30, 10, 22, 11, 27, 0, 20, 2, 16, 8, 22, 7, 12, 4, 16, 1, 3, 9, 13, 6, 31, 8, 23, 11, 1, 0, 7, 10, 15, 9, 17, 4, 8, 0, 2, 10, 27, 4, 14, 0, 31, 1, 29, 4, 17, 2, 19, 9, 26, 2, 3, 10, 8, +}; +static constexpr uint8_t BC6H_VEC_BLOCKS_OUT[768] = { + 0xd6, 0xc6, 0x5e, 0x02, 0x6e, 0x41, 0x19, 0xb6, 0xdd, 0xe2, 0x82, 0x07, 0xcc, 0x84, 0xc0, 0x22, + 0xda, 0xba, 0xe3, 0x0c, 0xa0, 0x32, 0xad, 0x3f, 0x1b, 0x17, 0xd2, 0x2b, 0xdb, 0x46, 0xff, 0xfa, + 0x12, 0x91, 0xce, 0x3e, 0x3f, 0xe1, 0xc8, 0xab, 0xaa, 0xed, 0x16, 0xd0, 0x5e, 0x38, 0x17, 0x8e, + 0x0b, 0x46, 0x0c, 0x6d, 0x3a, 0xbe, 0x68, 0x41, 0x9a, 0x90, 0x01, 0x47, 0xc9, 0xfe, 0x5d, 0xa7, + 0x62, 0xda, 0x5f, 0xa8, 0x76, 0x8f, 0x8e, 0x27, 0xb0, 0x48, 0x9a, 0x96, 0xb6, 0xf9, 0xfb, 0x6c, + 0xab, 0x1d, 0x3e, 0x44, 0x27, 0x86, 0x1b, 0x8e, 0xb7, 0x2d, 0x2f, 0x8f, 0x31, 0xbd, 0xf8, 0xa4, + 0x9a, 0x25, 0x2f, 0x04, 0x77, 0x49, 0x3a, 0x17, 0x81, 0xdd, 0x4c, 0xcb, 0xbf, 0xe4, 0x5b, 0xd5, + 0x3a, 0x23, 0x7c, 0x90, 0x38, 0xf7, 0xda, 0x57, 0x08, 0xdd, 0xa6, 0x31, 0xc4, 0xb8, 0xf1, 0x96, + 0xda, 0x82, 0x1d, 0x43, 0xfa, 0x73, 0x93, 0x3d, 0xaa, 0x41, 0xb9, 0x18, 0x75, 0x00, 0x5b, 0xda, + 0x95, 0xeb, 0xe8, 0xbb, 0x4d, 0xe9, 0xc8, 0xa2, 0xda, 0x14, 0x86, 0xe1, 0xcc, 0xaf, 0xcc, 0x52, + 0xc2, 0x83, 0x59, 0x7b, 0x3d, 0xb4, 0x03, 0xf4, 0xe3, 0x9c, 0x5d, 0x3d, 0x51, 0x71, 0x27, 0x25, + 0x7c, 0x65, 0x61, 0xd5, 0xed, 0xa2, 0x33, 0x94, 0x3c, 0xd3, 0xd1, 0x46, 0x04, 0x9f, 0x93, 0x85, + 0xe2, 0x14, 0x48, 0xe2, 0x3f, 0x99, 0x94, 0x00, 0x8b, 0x17, 0xcc, 0xfa, 0xe3, 0xa2, 0x1a, 0x0c, + 0x51, 0xa6, 0xbd, 0x9d, 0x7a, 0xa6, 0x27, 0x40, 0x33, 0x3c, 0x85, 0x90, 0x25, 0x9f, 0xeb, 0xbc, + 0xa3, 0x2b, 0x85, 0xe0, 0x03, 0x0b, 0x14, 0xcb, 0xb5, 0x57, 0x44, 0xd5, 0xed, 0x5c, 0xb1, 0x49, + 0xc5, 0xd2, 0xd6, 0xbf, 0x52, 0x12, 0x34, 0x96, 0x96, 0x53, 0x92, 0x1b, 0x65, 0x94, 0x13, 0xd9, + 0xa0, 0xa4, 0x5c, 0x33, 0x1d, 0xae, 0xca, 0x4f, 0x17, 0x37, 0x11, 0xda, 0x37, 0x32, 0xcf, 0x72, + 0xc7, 0xaa, 0x94, 0x2f, 0x75, 0x4c, 0xc4, 0xc5, 0xe6, 0x45, 0x84, 0x7f, 0xd4, 0xc2, 0x9a, 0x8d, + 0x76, 0x4f, 0xe7, 0x56, 0x68, 0xc3, 0x92, 0x6f, 0x81, 0x4b, 0x8d, 0xb3, 0x65, 0x2a, 0x05, 0x21, + 0x20, 0x4a, 0xc9, 0x1a, 0x80, 0xc9, 0xf1, 0x42, 0xd7, 0xc5, 0x32, 0xe7, 0x7f, 0x99, 0x79, 0x1d, + 0x3e, 0x2c, 0xa8, 0x4f, 0x69, 0x08, 0x12, 0x07, 0xb7, 0x8a, 0x21, 0xf2, 0xc9, 0xc9, 0x2f, 0x05, + 0xf6, 0x86, 0xda, 0xd7, 0x44, 0x97, 0x3b, 0xae, 0xf2, 0xd2, 0xc7, 0xa0, 0xe0, 0x83, 0xc4, 0x9c, + 0xa3, 0xe9, 0xa7, 0x20, 0x2f, 0x81, 0xcf, 0xd8, 0xf0, 0xed, 0x52, 0xda, 0xab, 0xbf, 0xe6, 0xe3, + 0xe7, 0x8d, 0x6e, 0xfd, 0x6f, 0xba, 0x1d, 0x96, 0x15, 0x59, 0xeb, 0x80, 0x4b, 0x51, 0x51, 0x32, + 0x40, 0x83, 0x0c, 0xa6, 0xf2, 0x9a, 0xe0, 0xe1, 0x2b, 0x84, 0x32, 0x93, 0xa7, 0xe8, 0xd9, 0xc1, + 0x02, 0xfb, 0xce, 0xfc, 0xa3, 0x96, 0x52, 0x89, 0xf2, 0x01, 0x8e, 0xb2, 0x91, 0x98, 0x76, 0x90, + 0xfa, 0x3f, 0x66, 0xed, 0x4c, 0x81, 0xac, 0x0c, 0xaf, 0xd1, 0xf2, 0x83, 0x64, 0x48, 0xdb, 0x95, + 0x96, 0xb0, 0xe4, 0x38, 0x69, 0xd2, 0x50, 0x73, 0x44, 0x86, 0x5d, 0x90, 0x99, 0x56, 0x94, 0xa9, + 0x2a, 0xcd, 0xae, 0xd7, 0x6a, 0xdd, 0xdc, 0xbf, 0x77, 0x15, 0xe2, 0xcb, 0x80, 0x05, 0x6f, 0x1a, + 0xf5, 0x13, 0xa3, 0x60, 0x2b, 0x80, 0x77, 0x35, 0x78, 0x6d, 0x60, 0x51, 0xe7, 0xd2, 0xf2, 0x13, + 0xbe, 0x59, 0xfc, 0x86, 0x34, 0x3e, 0xd0, 0xcd, 0x47, 0xbc, 0x8d, 0x76, 0x1b, 0xd4, 0xa9, 0x05, + 0x72, 0x3f, 0xcb, 0x2d, 0xf8, 0x77, 0x05, 0x66, 0x1f, 0xf3, 0x53, 0x7f, 0x55, 0x19, 0x21, 0xbc, + 0x3a, 0x8e, 0x78, 0xa8, 0x3c, 0xdb, 0x0f, 0x3d, 0x30, 0xf6, 0x76, 0x58, 0x4a, 0xa9, 0x7b, 0xce, + 0xa7, 0xb8, 0x73, 0x2f, 0x3b, 0x7c, 0x82, 0x9f, 0x4a, 0x46, 0x52, 0x08, 0x8b, 0x14, 0xab, 0xa9, + 0xb8, 0x82, 0x0a, 0x32, 0x65, 0x22, 0xa2, 0xf8, 0xf3, 0xed, 0x8c, 0x33, 0x97, 0xec, 0x9f, 0x6c, + 0x83, 0xd2, 0x5e, 0x63, 0xb3, 0x30, 0x08, 0xb2, 0x7a, 0x90, 0x9f, 0x51, 0xb3, 0x4a, 0x28, 0xf8, + 0xfe, 0x1b, 0xd1, 0xd8, 0x0b, 0xe6, 0xcd, 0xe6, 0x66, 0x34, 0x36, 0x5a, 0x6e, 0x43, 0xae, 0x6b, + 0x6a, 0x36, 0xe5, 0x37, 0xea, 0x85, 0x91, 0x84, 0xc4, 0x01, 0x31, 0x85, 0xa1, 0xef, 0x47, 0x60, + 0xf4, 0xe4, 0xaa, 0x62, 0x24, 0xba, 0xce, 0xaa, 0x4f, 0x59, 0x28, 0x63, 0xfd, 0xc7, 0x56, 0x8b, + 0xe3, 0xdf, 0xa2, 0xf9, 0x9b, 0x88, 0x81, 0x60, 0x77, 0x1d, 0xbc, 0xa2, 0xe1, 0x05, 0x64, 0x71, + 0x6a, 0x21, 0x0b, 0x78, 0x33, 0xb1, 0x80, 0x76, 0x0c, 0xd7, 0x45, 0xde, 0x04, 0xed, 0xca, 0xb0, + 0x1c, 0x16, 0x8f, 0xb2, 0x70, 0x89, 0x81, 0xee, 0x09, 0xf9, 0x8f, 0x8e, 0x26, 0x13, 0x95, 0xdf, + 0x4d, 0x4c, 0x5a, 0xab, 0x1c, 0xb5, 0x6c, 0x48, 0x54, 0xb4, 0x87, 0xe1, 0xa0, 0x19, 0x4f, 0xf5, + 0xaa, 0xdd, 0xa6, 0xda, 0xf4, 0xb9, 0x6e, 0x47, 0x44, 0x2d, 0xf2, 0xef, 0x13, 0x6d, 0x60, 0xf9, + 0x42, 0x7b, 0x32, 0x74, 0xa4, 0xf9, 0xf3, 0xbc, 0xbe, 0x78, 0xda, 0x43, 0x42, 0x3f, 0x07, 0x92, + 0x3e, 0xd8, 0x8e, 0x37, 0x43, 0x08, 0x2b, 0x40, 0x8e, 0x5f, 0x3b, 0x91, 0xaf, 0xef, 0x7b, 0xcd, + 0x42, 0xc9, 0x19, 0xe6, 0x5a, 0x6d, 0x8c, 0x0e, 0xc7, 0x68, 0x04, 0x44, 0xf0, 0xdb, 0x13, 0x0b, + 0xc3, 0x86, 0x28, 0xbf, 0x51, 0xbf, 0x36, 0xfa, 0xc5, 0x26, 0x83, 0xde, 0xf8, 0x80, 0x47, 0x44, +}; +// BC6H_MIX: exact 13, endpoints-only 8, copied 19, constant 0 (Python model) +static constexpr size_t BC6H_MIX_COUNTS[4] = { 13, 8, 19, 0 }; +static constexpr uint16_t BC6H_MIX_SYMBOLS[16 * 80] = { + 0, 0, 0, 2, 0, 1, 0, 3, 1, 0, 2, 1, 5, 0, 0, 0, 2, 0, 0, 1, 3, 1, 0, 0, 0, 2, 1, 3, 4, 0, 1, 1, 6, 2, 1, 1, 3, 1, 4, 0, 0, 4, 4, 1, 1, 0, 3, 1, 5, 2, 5, 1, 7, 1, 1, 6, 1, 0, 3, 4, 2, 1, 7, 4, 0, 3, 1, 4, 7, 2, 5, 0, 7, 7, 5, 1, 2, 2, 4, 2, + 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 3, 1, 1, 2, 1, 1, 1, 1, 2, 0, 1, 3, 0, 0, 3, 1, 1, 2, 0, 0, 0, 0, 3, 2, 3, 0, 1, 2, 0, 2, 0, 5, 1, 3, 2, 3, 2, 7, 0, 7, 1, 7, 1, 6, 2, 7, 3, 2, 0, 5, 3, 3, 2, 5, 1, 3, 4, 4, 3, 2, 4, 3, 3, 3, 0, 1, 1, + 71, 28, 188, 246, 77, 27, 129, 159, 166, 79, 98, 128, 87, 29, 96, 239, 56, 51, 63, 55, 243, 248, 69, 39, 40, 211, 113, 119, 40, 254, 18, 108, 123, 222, 164, 235, 108, 62, 81, 121, 202, 127, 64, 2, 159, 106, 5, 244, 202, 89, 11, 127, 138, 233, 40, 55, 169, 65, 43, 5, 150, 235, 55, 71, 164, 17, 46, 199, 115, 151, 37, 2, 18, 70, 169, 204, 111, 86, 47, 63, + 47, 185, 146, 236, 230, 137, 56, 204, 92, 244, 9, 220, 71, 11, 134, 21, 120, 235, 97, 0, 83, 177, 225, 225, 91, 170, 142, 141, 35, 202, 121, 82, 72, 81, 105, 10, 114, 7, 198, 219, 145, 250, 226, 254, 22, 190, 149, 218, 227, 229, 177, 158, 33, 220, 133, 112, 111, 135, 250, 102, 63, 97, 65, 132, 191, 163, 254, 95, 25, 87, 29, 238, 26, 124, 103, 195, 141, 225, 224, 156, + 220, 79, 126, 200, 169, 131, 197, 120, 77, 130, 86, 178, 213, 167, 85, 131, 118, 116, 119, 131, 229, 158, 75, 41, 171, 38, 113, 124, 228, 77, 20, 100, 153, 253, 89, 53, 115, 127, 113, 124, 188, 46, 144, 54, 82, 75, 177, 71, 227, 212, 167, 10, 235, 71, 133, 73, 101, 58, 180, 78, 32, 46, 46, 29, 158, 230, 204, 31, 71, 53, 191, 116, 92, 240, 200, 202, 51, 225, 71, 54, + 14, 30, 13, 15, 20, 21, 6, 7, 23, 28, 0, 13, 31, 11, 11, 7, 29, 17, 24, 14, 27, 28, 1, 29, 21, 0, 12, 24, 4, 8, 26, 17, 8, 3, 6, 26, 28, 3, 4, 20, 1, 2, 15, 28, 4, 11, 22, 3, 23, 31, 1, 21, 29, 16, 7, 17, 16, 5, 10, 12, 26, 7, 23, 23, 1, 13, 30, 19, 18, 15, 10, 19, 22, 13, 3, 23, 13, 11, 17, 9, + 28, 0, 18, 24, 10, 31, 13, 27, 22, 20, 18, 19, 8, 14, 3, 1, 26, 29, 25, 20, 25, 0, 27, 21, 11, 0, 27, 14, 23, 2, 8, 0, 0, 2, 22, 22, 13, 11, 10, 25, 2, 14, 18, 13, 26, 22, 13, 23, 26, 30, 14, 24, 27, 15, 30, 30, 10, 3, 15, 16, 20, 18, 24, 4, 5, 29, 25, 7, 29, 9, 0, 0, 15, 16, 7, 14, 21, 29, 0, 5, + 26, 12, 28, 31, 2, 8, 17, 20, 21, 26, 11, 15, 23, 10, 22, 8, 28, 12, 1, 9, 6, 12, 28, 11, 22, 15, 25, 28, 1, 5, 10, 22, 13, 20, 4, 29, 14, 9, 27, 24, 9, 27, 2, 17, 29, 22, 12, 3, 10, 13, 8, 16, 30, 11, 9, 23, 16, 19, 22, 25, 0, 12, 24, 25, 22, 17, 11, 20, 1, 10, 19, 13, 21, 4, 17, 16, 4, 7, 13, 19, + 49, 22, 61, 16, 32, 0, 22, 52, 6, 0, 13, 36, 17, 60, 32, 25, 41, 53, 17, 7, 24, 22, 36, 37, 39, 44, 49, 20, 22, 29, 29, 9, 10, 17, 58, 10, 21, 31, 16, 42, 53, 31, 19, 2, 36, 53, 58, 31, 50, 27, 11, 58, 26, 60, 43, 26, 45, 54, 0, 28, 10, 48, 18, 44, 5, 62, 54, 8, 41, 41, 27, 57, 11, 56, 61, 21, 58, 48, 47, 19, + 51, 37, 34, 14, 40, 22, 0, 19, 2, 3, 0, 1, 59, 41, 54, 36, 8, 20, 30, 12, 63, 19, 24, 58, 29, 63, 48, 8, 59, 40, 12, 1, 23, 28, 43, 55, 51, 30, 49, 38, 3, 63, 42, 3, 1, 13, 53, 39, 57, 21, 59, 43, 7, 37, 24, 25, 47, 12, 43, 58, 55, 31, 1, 46, 3, 49, 21, 32, 39, 62, 7, 50, 22, 13, 7, 20, 40, 19, 14, 55, + 4, 45, 3, 41, 48, 25, 6, 12, 3, 51, 43, 22, 60, 63, 32, 35, 45, 16, 44, 13, 37, 33, 18, 39, 37, 24, 46, 44, 16, 11, 9, 21, 35, 41, 54, 14, 36, 28, 24, 13, 36, 33, 42, 30, 23, 50, 52, 25, 13, 23, 11, 5, 61, 13, 26, 39, 3, 30, 18, 17, 25, 17, 34, 4, 3, 17, 52, 33, 31, 55, 27, 16, 34, 7, 39, 47, 21, 29, 32, 7, + 210, 220, 128, 249, 223, 251, 113, 138, 157, 37, 223, 174, 32, 26, 205, 233, 36, 1, 82, 176, 79, 1, 82, 82, 100, 211, 198, 160, 62, 1, 72, 55, 49, 214, 134, 42, 51, 54, 26, 183, 95, 54, 173, 2, 118, 167, 175, 253, 225, 185, 120, 82, 115, 245, 8, 41, 108, 82, 168, 31, 19, 64, 220, 156, 166, 189, 35, 105, 232, 189, 3, 25, 125, 236, 3, 69, 185, 65, 11, 218, + 46, 149, 66, 103, 57, 218, 90, 157, 100, 106, 235, 220, 127, 211, 173, 119, 222, 49, 173, 199, 229, 242, 50, 24, 52, 154, 52, 70, 96, 182, 111, 103, 241, 46, 146, 105, 20, 112, 171, 150, 46, 70, 99, 87, 99, 49, 231, 246, 114, 109, 168, 177, 195, 148, 119, 138, 163, 192, 118, 248, 131, 104, 50, 5, 167, 222, 110, 212, 93, 107, 115, 124, 78, 235, 69, 42, 73, 122, 99, 140, + 113, 156, 236, 253, 203, 246, 121, 75, 47, 122, 25, 111, 13, 230, 0, 208, 54, 24, 16, 75, 99, 60, 241, 105, 128, 203, 92, 52, 103, 139, 175, 62, 23, 9, 4, 49, 166, 104, 159, 3, 37, 171, 96, 212, 28, 142, 225, 37, 191, 187, 66, 163, 120, 77, 61, 63, 114, 18, 234, 123, 156, 55, 222, 161, 115, 161, 161, 223, 45, 243, 120, 116, 41, 248, 68, 52, 142, 121, 49, 253, + 75, 139, 112, 239, 102, 164, 49, 90, 168, 229, 208, 207, 98, 201, 56, 167, 88, 145, 104, 236, 213, 253, 218, 35, 163, 82, 138, 224, 161, 167, 209, 71, 117, 191, 54, 111, 119, 160, 194, 82, 38, 51, 190, 167, 18, 74, 27, 125, 241, 179, 50, 185, 155, 195, 208, 102, 56, 161, 136, 98, 30, 247, 43, 155, 5, 52, 212, 159, 224, 54, 210, 175, 101, 57, 148, 53, 142, 15, 98, 5, + 10, 22, 9, 20, 11, 30, 10, 16, 6, 5, 0, 24, 8, 21, 0, 31, 7, 25, 0, 16, 5, 30, 2, 1, 11, 14, 4, 26, 8, 19, 9, 25, 5, 22, 1, 29, 1, 29, 4, 8, 1, 14, 2, 7, 8, 26, 4, 29, 13, 7, 13, 9, 1, 9, 13, 10, 8, 10, 7, 31, 6, 1, 9, 2, 12, 28, 6, 20, 1, 2, 12, 30, 3, 14, 0, 22, 0, 23, 0, 24, +}; +static constexpr uint8_t BC6H_MIX_OUT[640] = { + 0xa3, 0x14, 0x4a, 0xfb, 0xf5, 0x1b, 0x55, 0x79, 0xe7, 0xfd, 0x94, 0x4c, 0x1a, 0xbd, 0x63, 0x27, + 0xa3, 0x14, 0x4a, 0xfb, 0xf5, 0x1b, 0x55, 0x79, 0x7f, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0xa3, 0x14, 0x4a, 0xfb, 0xf5, 0x1b, 0x55, 0x79, 0x7f, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0xe4, 0xd4, 0x91, 0x16, 0x61, 0x89, 0xa3, 0x3f, 0xbc, 0x06, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0xe4, 0xd4, 0x91, 0x16, 0x61, 0x89, 0xa3, 0x3f, 0xbc, 0x06, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0xe4, 0xd4, 0x91, 0x16, 0x61, 0x89, 0xa3, 0x3f, 0xbc, 0x06, 0x73, 0x4b, 0x3b, 0x12, 0x39, 0x4b, + 0xba, 0x19, 0xfc, 0x09, 0xe3, 0x0d, 0xfa, 0x17, 0xea, 0xa5, 0xbe, 0x6d, 0xdb, 0xde, 0xb6, 0x6d, + 0xba, 0x19, 0xfc, 0x09, 0xe3, 0x0d, 0xfa, 0x17, 0xea, 0xa5, 0xbe, 0x6d, 0xdb, 0xde, 0xb6, 0x6d, + 0xd6, 0x39, 0xc5, 0xb2, 0x8e, 0xbb, 0xa3, 0x17, 0x60, 0x30, 0x1f, 0x7c, 0x1d, 0x65, 0x82, 0xe5, + 0xf8, 0x5c, 0x91, 0xf7, 0x03, 0x67, 0xd5, 0xfe, 0xaa, 0x14, 0xbe, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, + 0x0e, 0xb2, 0x86, 0xd1, 0xcd, 0x68, 0xd7, 0xcc, 0x15, 0xcc, 0xdf, 0x36, 0x41, 0x05, 0xf9, 0x16, + 0x02, 0x36, 0x21, 0x24, 0x77, 0x3a, 0xd4, 0x8d, 0x0e, 0x3b, 0xbc, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, + 0x02, 0x36, 0x21, 0x24, 0x77, 0x3a, 0xd4, 0x8d, 0x0e, 0x3b, 0xbc, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, + 0x0a, 0xc7, 0x5f, 0x4b, 0xc0, 0xd2, 0x0f, 0xd6, 0x03, 0x4f, 0x47, 0x28, 0xf1, 0x82, 0x12, 0xd2, + 0x0a, 0xc7, 0x5f, 0x4b, 0xc0, 0xd2, 0x0f, 0xd6, 0x03, 0x4f, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0x7e, 0x70, 0xa8, 0x72, 0x1c, 0x14, 0x1b, 0xe7, 0xea, 0x39, 0xbf, 0x6d, 0xdb, 0xde, 0xb6, 0x6d, + 0x7e, 0x70, 0xa8, 0x72, 0x1c, 0x14, 0x1b, 0xe7, 0xea, 0x39, 0xbf, 0x6d, 0xdb, 0xde, 0xb6, 0x6d, + 0x2d, 0x95, 0xbf, 0x1b, 0x77, 0x80, 0xc6, 0x29, 0x8f, 0xab, 0x2b, 0xa5, 0xfd, 0xc0, 0x05, 0x0c, + 0x61, 0x4c, 0xae, 0xa9, 0x79, 0xe6, 0x9d, 0x44, 0x2a, 0xb8, 0x0f, 0x74, 0x88, 0x02, 0xf6, 0x3e, + 0x8a, 0x81, 0xc9, 0x4b, 0x40, 0x10, 0x03, 0x7d, 0xc4, 0x0c, 0xc1, 0x37, 0xb4, 0x45, 0x07, 0xef, + 0x65, 0xa1, 0x86, 0xb6, 0x95, 0x0f, 0xd0, 0x24, 0xde, 0xd3, 0x51, 0x48, 0xba, 0xeb, 0x28, 0x6b, + 0x82, 0x4e, 0xd3, 0xb9, 0xb0, 0x41, 0x59, 0xb5, 0xcc, 0xf0, 0x84, 0x44, 0xf4, 0x8d, 0x77, 0x4c, + 0x82, 0x4e, 0xd3, 0xb9, 0xb0, 0x41, 0x59, 0xb5, 0xcc, 0xf0, 0xbc, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, + 0x6f, 0x2c, 0xf6, 0xda, 0x41, 0xd7, 0x81, 0x0d, 0x7e, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0x6f, 0x2c, 0xf6, 0xda, 0x41, 0xd7, 0x81, 0x0d, 0x7e, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0x6f, 0x2c, 0xf6, 0xda, 0x41, 0xd7, 0x81, 0x0d, 0x7e, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0x3d, 0xcd, 0x67, 0x74, 0xd4, 0x0c, 0x84, 0x1e, 0x85, 0x28, 0x0d, 0xe0, 0x6e, 0xf8, 0xd0, 0xdc, + 0x3d, 0xcd, 0x67, 0x74, 0xd4, 0x0c, 0x84, 0x1e, 0x85, 0x28, 0xbd, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, + 0xd6, 0x23, 0x5a, 0xed, 0xcf, 0x35, 0x29, 0xaa, 0xc7, 0xec, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0xd6, 0x23, 0x5a, 0xed, 0xcf, 0x35, 0x29, 0xaa, 0xc7, 0xec, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0xd6, 0x23, 0x5a, 0xed, 0xcf, 0x35, 0x29, 0xaa, 0xc7, 0xec, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0x1e, 0xe8, 0x47, 0xb7, 0x02, 0x1e, 0xba, 0x20, 0x52, 0x5b, 0x6c, 0x16, 0xbf, 0xa5, 0x4b, 0x64, + 0x1e, 0xe8, 0x47, 0xb7, 0x02, 0x1e, 0xba, 0x20, 0x52, 0x5b, 0xbc, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, + 0xf2, 0xc7, 0x1d, 0xd2, 0x79, 0x49, 0xda, 0x46, 0x08, 0x9d, 0xbe, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0xf2, 0xc7, 0x1d, 0xd2, 0x79, 0x49, 0xda, 0x46, 0x08, 0x9d, 0xbe, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0x6b, 0xca, 0x41, 0x8b, 0x1d, 0x93, 0x37, 0x28, 0x7e, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0x6b, 0xca, 0x41, 0x8b, 0x1d, 0x93, 0x37, 0x28, 0x7e, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0x6b, 0xca, 0x41, 0x8b, 0x1d, 0x93, 0x37, 0x28, 0x7e, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0xb8, 0xec, 0xab, 0xe9, 0x75, 0xbe, 0x01, 0x54, 0x3d, 0x03, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0xb8, 0xec, 0xab, 0xe9, 0x75, 0xbe, 0x01, 0x54, 0x3d, 0x03, 0xab, 0x55, 0x4e, 0x22, 0x77, 0x99, +}; +// BC6H_ROOTED: exact 0, endpoints-only 0, copied 0, constant 40 (Python model) +static constexpr size_t BC6H_ROOTED_COUNTS[4] = { 0, 0, 0, 40 }; +static constexpr uint16_t BC6H_ROOTED_SYMBOLS[16 * 80] = { + 2, 0, 0, 1, 0, 0, 1, 0, 2, 1, 0, 3, 2, 2, 0, 1, 0, 1, 3, 1, 4, 0, 2, 0, 6, 1, 4, 2, 1, 0, 0, 4, 3, 2, 1, 1, 4, 1, 3, 3, 0, 7, 0, 4, 0, 5, 3, 5, 6, 5, 1, 6, 7, 0, 1, 5, 4, 2, 1, 5, 3, 3, 4, 6, 7, 2, 3, 6, 2, 0, 10, 2, 0, 1, 4, 6, 4, 1, 12, 1, + 1, 0, 0, 0, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 2, 2, 0, 0, 0, 0, 3, 3, 0, 0, 5, 0, 4, 1, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 4, 2, 0, 0, 4, 3, 5, 3, 6, 2, 0, 0, 6, 3, 7, 3, 0, 0, 1, 4, 0, 5, 1, 5, 0, 0, 3, 4, 0, 0, 0, 0, 0, 0, + 39, 15, 40, 12, 12, 23, 22, 59, 156, 225, 207, 66, 50, 80, 135, 172, 125, 26, 117, 195, 36, 36, 235, 146, 236, 99, 174, 46, 116, 23, 61, 27, 109, 111, 103, 130, 247, 102, 138, 141, 16, 100, 99, 67, 229, 23, 186, 206, 134, 201, 76, 198, 190, 106, 65, 247, 7, 160, 106, 29, 79, 31, 201, 175, 136, 212, 177, 176, 68, 31, 184, 4, 237, 140, 88, 142, 175, 179, 19, 82, + 173, 16, 238, 178, 241, 228, 227, 96, 177, 148, 25, 193, 97, 36, 82, 23, 2, 220, 98, 210, 169, 82, 159, 42, 206, 10, 124, 155, 13, 86, 89, 29, 35, 65, 17, 179, 191, 71, 242, 105, 82, 14, 141, 119, 210, 207, 77, 115, 146, 53, 250, 149, 173, 66, 26, 107, 233, 79, 25, 37, 76, 183, 143, 246, 189, 46, 136, 145, 44, 104, 254, 199, 47, 130, 109, 195, 165, 249, 99, 175, + 229, 206, 160, 126, 248, 13, 249, 38, 18, 162, 110, 249, 38, 147, 191, 224, 252, 88, 74, 40, 228, 112, 64, 245, 134, 76, 169, 249, 4, 21, 5, 151, 126, 37, 183, 236, 30, 55, 236, 49, 196, 234, 224, 114, 186, 73, 27, 156, 75, 186, 123, 29, 25, 219, 103, 241, 236, 113, 172, 140, 212, 177, 105, 108, 32, 84, 91, 28, 58, 80, 143, 155, 170, 67, 161, 231, 217, 153, 33, 69, + 20, 5, 21, 26, 10, 18, 18, 21, 16, 23, 8, 25, 21, 7, 16, 20, 23, 12, 31, 28, 28, 19, 7, 14, 1, 22, 30, 1, 18, 23, 25, 22, 12, 7, 22, 31, 29, 5, 12, 23, 17, 10, 23, 15, 1, 8, 20, 10, 23, 28, 24, 29, 8, 14, 10, 18, 6, 18, 7, 17, 28, 1, 12, 28, 7, 28, 1, 23, 31, 14, 22, 16, 3, 31, 8, 23, 29, 30, 6, 0, + 13, 23, 1, 30, 22, 10, 31, 16, 10, 13, 12, 31, 2, 3, 6, 9, 28, 13, 5, 27, 28, 23, 11, 20, 3, 15, 23, 13, 8, 27, 26, 7, 10, 11, 26, 30, 8, 28, 0, 7, 22, 18, 22, 27, 14, 16, 5, 26, 10, 21, 16, 18, 13, 17, 3, 30, 14, 7, 8, 19, 30, 18, 8, 18, 1, 3, 2, 24, 8, 13, 2, 13, 25, 28, 31, 14, 13, 12, 7, 24, + 24, 14, 25, 25, 20, 17, 10, 21, 16, 8, 23, 12, 24, 17, 26, 28, 22, 31, 24, 25, 25, 8, 17, 6, 22, 13, 29, 12, 12, 23, 14, 31, 6, 29, 27, 29, 4, 4, 0, 8, 10, 3, 28, 26, 27, 4, 10, 6, 24, 29, 27, 31, 26, 5, 11, 19, 7, 22, 12, 19, 9, 18, 24, 21, 3, 29, 9, 26, 31, 26, 7, 7, 30, 2, 28, 8, 0, 30, 9, 17, + 4, 7, 47, 58, 60, 44, 0, 50, 61, 6, 22, 60, 19, 28, 33, 40, 62, 22, 52, 30, 19, 63, 32, 12, 1, 47, 53, 35, 57, 58, 25, 29, 39, 49, 48, 13, 18, 59, 36, 8, 54, 25, 31, 49, 52, 54, 37, 36, 55, 19, 5, 6, 31, 23, 36, 54, 58, 53, 51, 23, 24, 34, 14, 22, 61, 40, 21, 35, 36, 1, 3, 11, 62, 57, 61, 2, 31, 54, 19, 56, + 31, 33, 43, 32, 17, 33, 58, 33, 55, 55, 63, 44, 59, 40, 16, 39, 61, 24, 29, 54, 48, 15, 44, 10, 9, 29, 9, 40, 33, 30, 11, 63, 27, 52, 24, 48, 42, 34, 48, 35, 19, 44, 54, 17, 52, 58, 28, 22, 34, 50, 29, 57, 41, 53, 60, 39, 41, 42, 47, 12, 21, 40, 51, 59, 48, 36, 12, 3, 6, 42, 21, 20, 18, 62, 54, 12, 57, 4, 44, 22, + 36, 18, 33, 50, 38, 0, 31, 7, 37, 17, 43, 33, 60, 29, 47, 15, 53, 61, 39, 10, 42, 39, 48, 55, 49, 1, 59, 36, 28, 32, 23, 26, 63, 40, 62, 17, 7, 25, 9, 51, 61, 24, 58, 60, 1, 7, 39, 7, 24, 28, 42, 60, 5, 6, 62, 25, 48, 39, 61, 27, 55, 16, 52, 1, 49, 53, 9, 34, 58, 37, 29, 26, 50, 19, 5, 34, 45, 29, 44, 32, + 49, 103, 139, 71, 133, 163, 212, 83, 213, 1, 242, 39, 179, 192, 110, 190, 123, 116, 216, 184, 79, 200, 175, 48, 249, 160, 14, 42, 7, 18, 97, 62, 223, 182, 61, 84, 106, 145, 209, 92, 87, 207, 200, 45, 204, 73, 129, 235, 40, 113, 83, 64, 230, 24, 201, 231, 157, 246, 182, 175, 26, 74, 13, 198, 153, 87, 202, 144, 157, 248, 169, 237, 115, 20, 81, 222, 25, 100, 151, 139, + 118, 168, 89, 207, 85, 7, 241, 157, 61, 191, 111, 89, 194, 124, 177, 1, 32, 211, 197, 246, 148, 54, 254, 69, 39, 235, 147, 162, 55, 111, 123, 27, 40, 82, 77, 107, 147, 214, 81, 183, 209, 177, 148, 161, 171, 106, 55, 30, 30, 2, 17, 204, 185, 247, 246, 245, 15, 5, 32, 7, 144, 156, 39, 99, 50, 215, 197, 206, 23, 28, 253, 186, 45, 53, 54, 50, 95, 149, 79, 100, + 67, 86, 157, 246, 250, 196, 239, 218, 123, 150, 170, 143, 124, 254, 202, 221, 210, 187, 242, 160, 16, 177, 17, 190, 145, 137, 42, 240, 227, 85, 167, 230, 81, 253, 76, 221, 136, 126, 148, 22, 170, 1, 111, 11, 237, 33, 110, 58, 102, 143, 222, 52, 28, 38, 60, 179, 120, 171, 54, 103, 248, 39, 73, 211, 82, 219, 201, 128, 228, 23, 62, 112, 202, 56, 244, 119, 137, 236, 10, 192, + 192, 172, 91, 251, 187, 220, 10, 129, 199, 187, 255, 214, 181, 212, 111, 141, 170, 197, 73, 176, 92, 221, 30, 8, 119, 200, 82, 77, 117, 125, 200, 225, 76, 215, 220, 250, 214, 139, 126, 240, 84, 178, 169, 212, 62, 118, 70, 126, 0, 107, 246, 206, 42, 162, 42, 127, 205, 194, 132, 113, 204, 139, 148, 150, 241, 248, 181, 37, 144, 34, 178, 5, 22, 182, 72, 205, 202, 120, 56, 77, + 6, 1, 10, 2, 0, 21, 7, 2, 8, 11, 6, 15, 3, 16, 5, 11, 9, 25, 8, 16, 12, 19, 2, 14, 2, 28, 11, 13, 13, 26, 1, 23, 13, 9, 7, 6, 11, 24, 8, 7, 1, 9, 10, 5, 1, 0, 9, 3, 5, 22, 7, 6, 4, 24, 1, 25, 3, 16, 3, 3, 11, 24, 9, 13, 6, 19, 13, 5, 9, 14, 4, 28, 6, 29, 12, 2, 6, 22, 9, 15, +}; +static constexpr uint8_t BC6H_ROOTED_OUT[640] = { + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; diff --git a/tests/bcpack_bcn_check.py b/tests/bcpack_bcn_check.py new file mode 100644 index 0000000000..de45bd1ab2 --- /dev/null +++ b/tests/bcpack_bcn_check.py @@ -0,0 +1,267 @@ +"""Synthetic BCPack BC3/BC4/BC5 streams: encode chosen blocks, decode, compare (no title data). + +The test owns its encoder side: it picks block contents (endpoints, ramp positions and the +references each block predicts from), derives the lane symbols from the reference rules, rANS +encodes every lane with the single-lane test encoder from bcpack_symbols_check.py, and interleaves +the lanes in the order the cycle-level decoder requests bytes. Expected blocks are packed here +directly from the chosen contents, not by the decoder under test. + +PINNED holds one stream per format produced by this encoder (seed 7); the C++ decoder in +src/startup_stubs/bcpack_decoder.h is checked against the same bytes by +tests/bcpack_bcn_decode_test.cpp, which keeps both implementations in step. +""" +import random +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tests")) +import bcpack_bcn # noqa: E402 +from bcpack_bcn import BCPackError, LAYOUTS, tables, zigzag # noqa: E402 +from _bcpack_rans import decode_lanes # noqa: E402 +from bcpack_symbols_check import encode_fragment # noqa: E402 + +ALPHA_CODE = (0, 2, 3, 4, 5, 6, 7, 1) +COLOUR_CODE = (0, 2, 3, 1) + + +def signed(v, bits): + v &= (1 << bits) - 1 + return v - (1 << bits) if v >> (bits - 1) else v + + +def nibbles(byte): + even = odd = 0 + for k in range(4): + even |= ((byte >> (2 * k)) & 1) << k + odd |= ((byte >> (2 * k + 1)) & 1) << k + return even, odd + + +def interleave_lanes(lane_values, alphabet_bits, rng): + """rANS-encode each lane (one flushed fragment) and interleave in decoder request order.""" + streams = [] + for values, ab in zip(lane_values, alphabet_bits): + q = rng.randrange(16) + streams.append(encode_fragment(ab + 1, q, values)) + cursor = [0] * len(streams) + + def source(lane): + byte = streams[lane][cursor[lane]] + cursor[lane] += 1 + return byte + + n = len(lane_values[0]) + order = decode_lanes(b"", list(alphabet_bits), [n] * len(alphabet_bits), source=source)["order"] + if cursor != [len(s) for s in streams]: + raise AssertionError("encoder schedule did not use every lane byte") + cursor = [0] * len(streams) + out = bytearray() + for lane in order: + out.append(streams[lane][cursor[lane]]) + cursor[lane] += 1 + return bytes(out) + + +class Encoder: + """Build lane symbols for chosen blocks of one format.""" + + def __init__(self, fmt, rng): + self.fmt = fmt + self.rng = rng + t = tables() + name = {3: "BC3", 4: "BC4", 5: "BC5"}[fmt] + self.dictionary = t[name + "_DICTIONARY"] + pairs = t["RANK_PAIR_BC3_ALPHA" if fmt == 3 else "RANK_PAIR_" + name] + self.pair_symbol = {tuple(ab): s for s, ab in enumerate(pairs)} + self.quad_symbol = {tuple(v): s for s, v in enumerate(t["RANK_QUAD_BC3_COLOUR"])} + self.ab, self.block, self.per = LAYOUTS[fmt] + self.lanes = [[] for _ in self.ab] + self.hist = [] + self.expected = bytearray() + self.n_ep = {3: 8, 4: 2, 5: 4}[fmt] + self.n_ix = 16 if fmt == 4 else 32 + + def source(self, i, r): + if r == 0: + return [0] * self.n_ep, [0] * self.n_ix + if r <= i: + return self.hist[i - r] + ep, ix = self.dictionary[r - i - 1] + return list(ep), list(ix) + + def put_ref(self, er, xr): + d = zigzag(signed(er - xr, 8)) + if self.per == 1: + self.lanes[0].append(d) + self.lanes[1].append(xr) + else: + self.lanes[0].extend(nibbles(d)) + self.lanes[1].extend(nibbles(xr)) + + def add(self, er, xr, ep, ix): + """Append one block with endpoint states `ep`, ramp positions `ix`, references er/xr.""" + i = len(self.hist) + ep_ref, _ = self.source(i, er) + _, ix_ref = self.source(i, xr) + self.put_ref(er, xr) + widths = {3: (8, 8, 5, 6, 5, 5, 6, 5), 4: (8, 8), 5: (8, 8, 8, 8)}[self.fmt] + res = [zigzag(signed(ep[k] - ep_ref[k], widths[k])) for k in range(self.n_ep)] + if self.fmt == 4: + self.lanes[2].append(res[0]) + self.lanes[3].append(res[1]) + elif self.fmt == 5: + self.lanes[2].extend(res[0:2]) + self.lanes[3].extend(res[2:4]) + else: + self.lanes[2].extend(res[0:2]) + for c in range(3): + self.lanes[7 + c].extend((res[2 + c], res[5 + c])) + alpha_channels = {3: 1, 4: 1, 5: 2}[self.fmt] + for c in range(alpha_channels): + for k in range(8): + p = 16 * c + 2 * k + sym = self.pair_symbol[((ix[p] - ix_ref[p]) & 7, (ix[p + 1] - ix_ref[p + 1]) & 7)] + if self.fmt == 4: + self.lanes[4 + k].append(sym) + else: + base = 3 if self.fmt == 3 else 4 + 4 * c + self.lanes[base + k // 2].append(sym) + if self.fmt == 3: + quad_pixels = [] + for ox, oy in ((0, 0), (2, 0), (0, 2), (2, 2)): + quad_pixels.append([16 + 4 * (oy + dy) + ox + dx for dx, dy in ((0, 0), (1, 0), (0, 1), (1, 1))]) + for q, pix in enumerate(quad_pixels): + key = tuple((ix[p] - ix_ref[p]) & 3 for p in pix) + self.lanes[10 + (q >> 1)].append(self.quad_symbol[key]) + self.hist.append((list(ep), list(ix))) + self.expected += self.pack(ep, ix) + + def pack(self, ep, ix): + def alpha(e0, e1, pos): + v = (e0 ^ 0x80) | (e1 ^ 0x80) << 8 + for p in range(16): + v |= ALPHA_CODE[pos[p]] << (16 + 3 * p) + return v.to_bytes(8, "little") + + if self.fmt == 4: + return alpha(ep[0], ep[1], ix) + if self.fmt == 5: + return alpha(ep[0], ep[1], ix[:16]) + alpha(ep[2], ep[3], ix[16:]) + c0 = ep[2] << 11 | ep[3] << 5 | ep[4] + c1 = ep[5] << 11 | ep[6] << 5 | ep[7] + w = sum(COLOUR_CODE[ix[16 + p]] << (2 * p) for p in range(16)) + return (alpha(ep[0], ep[1], ix[:16]) + c0.to_bytes(2, "little") + c1.to_bytes(2, "little") + + w.to_bytes(4, "little")) + + def random_block(self, er, xr): + rng = self.rng + i = len(self.hist) + ep_ref, ix_ref = self.source(i, er) + widths = {3: (8, 8, 5, 6, 5, 5, 6, 5), 4: (8, 8), 5: (8, 8, 8, 8)}[self.fmt] + # Small residuals mostly (like real data), sometimes a full-range value. + ep = [(ep_ref[k] + (rng.randrange(-3, 4) if rng.random() < 0.7 else rng.randrange(1 << widths[k]))) + & ((1 << widths[k]) - 1) for k in range(self.n_ep)] + ix = [] + for p in range(self.n_ix): + mask = 3 if self.fmt == 3 and p >= 16 else 7 + ix.append(rng.randrange(mask + 1)) + self.add(er, xr, ep, ix) + + def stream(self): + return interleave_lanes(self.lanes, self.ab, self.rng), bytes(self.expected) + + +def build(fmt, seed, blocks=24): + """Blocks cover: zero references, history references at several distances, dictionary + references before the first block, and non-zero index references.""" + rng = random.Random(seed) + enc = Encoder(fmt, rng) + for i in range(blocks): + choice = i % 6 + if i == 0: + er, xr = 3, 0 # dictionary entry 2 (before the chunk) + elif i == 1: + er, xr = 0, 2 # zero endpoint state, index state from dictionary entry 0 + elif choice == 2: + er, xr = 1, 1 + elif choice == 3: + er, xr = min(i, 5), 0 + elif choice == 4: + er, xr = 0, min(i, 3) + else: + er, xr = rng.randrange(1, i + 1), rng.randrange(0, i + 1) + enc.random_block(er, xr) + return enc.stream() + + +# Seed-7 streams of 4 blocks, as decoded by tests/bcpack_bcn_decode_test.cpp. +PINNED_SEED = 7 +PINNED_BLOCKS = 4 + + +class BcnChecks(unittest.TestCase): + def test_roundtrip_all_formats(self): + for fmt in (3, 4, 5): + for seed in (1, 2, 3): + with self.subTest(fmt=fmt, seed=seed): + stream, expected = build(fmt, seed) + self.assertEqual(bcpack_bcn.decode(stream, fmt, len(expected)), expected) + + def test_lane_shape_and_trailing_zeros(self): + stream, expected = build(5, 4) + syms, n = bcpack_bcn.lane_symbols(stream + bytes(16), 5, len(expected)) + self.assertEqual(n, len(expected) // 16) + self.assertTrue(all(len(lane) == 2 * n for lane in syms)) + with self.assertRaises(BCPackError): + bcpack_bcn.decode(stream + b"\x01", 5, len(expected)) + + def test_negative_controls(self): + for fmt in (3, 4, 5): + stream, expected = build(fmt, 5) + block = LAYOUTS[fmt][1] + with self.subTest(fmt=fmt, case="truncated"), self.assertRaises(BCPackError): + bcpack_bcn.decode(stream[:-1], fmt, len(expected)) + with self.subTest(fmt=fmt, case="one block too many"), self.assertRaises(BCPackError): + bcpack_bcn.decode(stream, fmt, len(expected) + block) + with self.subTest(fmt=fmt, case="not a block multiple"), self.assertRaises(ValueError): + bcpack_bcn.decode(stream, fmt, len(expected) - 1) + # A flipped payload byte must not reproduce the expected blocks. + bad = bytearray(stream) + bad[len(bad) // 2] ^= 0x40 + with self.subTest(fmt=fmt, case="flipped byte"): + try: + self.assertNotEqual(bcpack_bcn.decode(bytes(bad), fmt, len(expected)), expected) + except BCPackError: + pass + + def test_wrong_format_layout_rejected(self): + # A BC5 stream read with the BC4 layout must not decode cleanly to the same bytes. + stream, expected = build(5, 6) + try: + self.assertNotEqual(bcpack_bcn.decode(stream, 4, len(expected)), expected) + except BCPackError: + pass + + def test_cpp_vectors_match(self): + source = (ROOT / "tests" / "bcpack_bcn_decode_test.cpp").read_text(encoding="utf-8") + for fmt in (3, 4, 5): + stream, expected = build(fmt, PINNED_SEED, PINNED_BLOCKS) + with self.subTest(fmt=fmt): + self.assertIn('"%s"' % stream.hex(), source) + self.assertIn('"%s"' % expected.hex(), source) + + +def print_pinned(): + for fmt in (3, 4, 5): + stream, expected = build(fmt, PINNED_SEED, PINNED_BLOCKS) + print(fmt, stream.hex(), expected.hex()) + + +if __name__ == "__main__": + if sys.argv[1:] == ["--print-pinned"]: + print_pinned() + else: + unittest.main() diff --git a/tests/bcpack_bcn_decode_test.cpp b/tests/bcpack_bcn_decode_test.cpp new file mode 100644 index 0000000000..19c2ffac6e --- /dev/null +++ b/tests/bcpack_bcn_decode_test.cpp @@ -0,0 +1,94 @@ +// Synthetic BCPack BC3/BC4/BC5 vectors for x2w_bcpack::decode_bcpack (no title data). +// The streams and expected blocks come from the encoder in tests/bcpack_bcn_check.py +// (seed 7, 4 blocks per format); that test checks the Python reference decoder against the +// same bytes, so both implementations stay in step. Exit code 0 = pass. +#include <cstdio> +#include <cstring> +#include <string> +#include <vector> + +#include "../src/startup_stubs/bcpack_decoder.h" + +namespace { + +struct Vector { + unsigned format; + const char* stream; + const char* expected; +}; + +const Vector kVectors[] = { + { 3, + "161f1b1010181f18050706090909130705011b0101a301018801200000010065943056f5f3dcff88a924b9a56124db5bc1ffbc744452ff37dc161b1e1b0709130f782501035b0700f231ddfffb74154f9b596bffe137e40cfffed924eddefffd33f8600bff59b629d8ff074404ffcec7ffa2fff1c2ffb43052bdffe4ff03e9f2ffbd04c492ff7ef48cb1f218d1ffb0000054ffbc00d8ff00bd00000000", + "7e7d878883583f75118cf16338605daf7e7f876c275223349dfce007372de15a7c7fda48642d767b6ef3e9b7544521267b7e529254939b816f74d153cbbcbb9a" }, + { 4, + "1e191c1b101e1b1506050407060b090608020e92010108042446724900008a02fe0478742cfffffed0316b2950d4e0a6e540ad16e8ffff05c8d9131f1116060b0606050102976f003dc3ffffc4df08d625a4faff14fb1351e0ffff1b1ced11d1d5fff3a0000000ffcd49bbe8f6edff960000ee00000000", + "1f159241e8177588814b20d64f9d6809814b4e5c8e6a9c4a1d6239643b911aa1" }, + { 5, + "1f1e1f1f191214130f0711110a0909090101010101021c0301010202eef0cc13ff30ffffcf24ff39f2240302f94781a0ffffffff67411a97f105021a181f150d0d1309031b01032eec00acd3ffff785f81dccbe9a5ff87ffff016af4aeddfff10204f4fedd2afeffffffffd51ce5eefbf101be01d7ff20ffa72105b57dee14f19d02dda9ffff3001fff991fae9030205cbff98ffff8b17a51e09cf3673ff55ff0054c4208dfff6f10106ff2c0000000000f40000000000", + "7e7d20f48b3a441c8080c4faa9132d81817fa31aa7d2e7e5807e90ed446a84a6327fecf847cbbbf7817b3ea78d44d6627d7cffaf1c1433199b83c264885fed48" }, +}; + +std::vector<unsigned char> hex(const char* s) { + std::vector<unsigned char> out; + auto nibble = [](char c) -> unsigned { + return c <= '9' ? static_cast<unsigned>(c - '0') : static_cast<unsigned>(c - 'a' + 10); + }; + for (size_t i = 0; s[i] && s[i + 1]; i += 2) { + out.push_back(static_cast<unsigned char>(nibble(s[i]) << 4 | nibble(s[i + 1]))); + } + return out; +} + +int failures = 0; + +void check(bool ok, const std::string& what) { + std::printf("%s %s\n", ok ? "PASS" : "FAIL", what.c_str()); + if (!ok) ++failures; +} + +} // namespace + +int main() { + for (const Vector& v : kVectors) { + const std::vector<unsigned char> in = hex(v.stream); + const std::vector<unsigned char> want = hex(v.expected); + const std::string tag = "BC" + std::to_string(v.format); + const size_t block = v.format == 4 ? 8 : 16; + + std::vector<unsigned char> out(want.size(), 0xCD); + size_t produced = 0; + bool ok = x2w_bcpack::decode_bcpack(in.data(), in.size(), v.format, out.data(), out.size(), &produced); + check(ok && produced == want.size() && out == want, tag + " decodes the expected blocks"); + + // Zero padding after the stream is accepted (archive intervals are padded). + std::vector<unsigned char> padded = in; + padded.resize(in.size() + 16, 0); + ok = x2w_bcpack::decode_bcpack(padded.data(), padded.size(), v.format, out.data(), out.size(), &produced); + check(ok && out == want, tag + " accepts trailing zero padding"); + + // Negative controls: truncated stream, non-zero trailing byte, wrong block count, size + // that is not a whole number of blocks. + ok = x2w_bcpack::decode_bcpack(in.data(), in.size() - 1, v.format, out.data(), out.size(), &produced); + check(!ok, tag + " rejects a truncated stream"); + std::vector<unsigned char> junk = in; + junk.push_back(1); + ok = x2w_bcpack::decode_bcpack(junk.data(), junk.size(), v.format, out.data(), out.size(), &produced); + check(!ok, tag + " rejects non-zero trailing data"); + std::vector<unsigned char> big(want.size() + block); + ok = x2w_bcpack::decode_bcpack(in.data(), in.size(), v.format, big.data(), big.size(), &produced); + check(!ok, tag + " rejects one block more than encoded"); + ok = x2w_bcpack::decode_bcpack(in.data(), in.size(), v.format, out.data(), out.size() - 1, &produced); + check(!ok, tag + " rejects a size that is not a block multiple"); + } + + // BC6H has a verified lane layout but no block reconstruction: the decoder must refuse it. + const std::vector<unsigned char> any = hex(kVectors[2].stream); + std::vector<unsigned char> out(64); + size_t produced = 0; + check(!x2w_bcpack::decode_bcpack(any.data(), any.size(), 6, out.data(), out.size(), &produced), + "BC6H (format 6) is refused"); + + std::printf("%s (%d failures)\n", failures ? "FAILED" : "OK", failures); + return failures ? 1 : 0; +} diff --git a/tests/buffer_address_index_check.cpp b/tests/buffer_address_index_check.cpp new file mode 100644 index 0000000000..c2cd077ff1 --- /dev/null +++ b/tests/buffer_address_index_check.cpp @@ -0,0 +1,117 @@ +// LOCAL (textures): src/startup_stubs/buffer_address_index.h against a brute-force walk. +// buffer_address_index_check explicit overlap / move / erase cases, then 200000 random operations on +// overlapping ranges of every width class, each query compared with the walk +// buffer_address_index_check --mutate the same with the exact-start window (negative control: must fail) +// Synthetic ranges only. +#include "startup_stubs/buffer_address_index.h" + +#include <algorithm> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <map> +#include <random> +#include <set> +#include <utility> +#include <vector> + +using Index = x2w_startup::BufferAddressIndex<int>; + +namespace { +int failures; +void fail(const char* what, std::uint64_t a, std::uint64_t b) +{ + if (failures++ < 10) std::printf("FAIL %s (0x%llx, %llu)\n", what, static_cast<unsigned long long>(a), static_cast<unsigned long long>(b)); +} + +std::set<int> query(const Index& index, std::uint64_t address, std::uint64_t bytes) +{ + std::set<int> out; + index.containing(address, bytes, [&](int key, std::uint64_t, std::uint64_t) { + out.insert(key); + return true; + }); + return out; +} +std::set<int> walk(const std::map<int, std::pair<std::uint64_t, std::uint64_t>>& ranges, std::uint64_t address, std::uint64_t bytes) +{ + std::set<int> out; + for (const auto& [key, r] : ranges) { + const auto [base, width] = r; + if (address < base || address - base >= width || bytes > width - (address - base)) continue; + out.insert(key); + } + return out; +} + +void explicit_cases(Index::Mutation m) +{ + Index index(m); + index.insert(1, 0x10000, 0x1000); // small + index.insert(2, 0x10800, 0x100); // nested in 1 + index.insert(3, 0x0, 0x40000000); // 1 GiB, covers everything below + if (query(index, 0x10850, 4) != std::set<int>{1, 2, 3}) fail("overlap: nested ranges", 0x10850, 4); + if (query(index, 0x10fff, 1) != std::set<int>{1, 3}) fail("overlap: last byte of 1", 0x10fff, 1); + if (query(index, 0x10ffe, 4) != std::set<int>{3}) fail("crossing the end of 1", 0x10ffe, 4); + if (query(index, 0x11000, 1) != std::set<int>{3}) fail("one past 1", 0x11000, 1); + index.erase(2); + if (query(index, 0x10850, 4) != std::set<int>{1, 3}) fail("removal of 2", 0x10850, 4); + index.insert(1, 0x20000, 0x1000); // move + if (query(index, 0x10850, 4) != std::set<int>{3} || query(index, 0x20010, 4) != std::set<int>{1, 3}) fail("move of 1", 0x20010, 4); + index.erase(3); + if (!query(index, 0x10, 1).empty() || index.size() != 1) fail("removal of 3", 0x10, 1); + if (index.erase(3)) fail("second erase", 3, 0); +} + +void random_cases(Index::Mutation m, unsigned operations) +{ + Index index(m); + std::map<int, std::pair<std::uint64_t, std::uint64_t>> ranges; + std::mt19937_64 rng(20261125); + const std::uint64_t widths[] = {16, 256, 4096, 65536, 65537, 1ull << 20, (1ull << 20) + 16, 1ull << 24, 3ull << 24, 1ull << 28, 1ull << 30}; + const std::uint64_t space = 1ull << 32; // dense: ranges overlap often + unsigned queries = 0, hits = 0; + for (unsigned op = 0; op < operations; ++op) { + const unsigned kind = rng() % 10; + const int key = static_cast<int>(rng() % 4000); + if (kind < 3) { // insert or move + const std::uint64_t width = widths[rng() % std::size(widths)] - (rng() % 2 ? rng() % 8 : 0); + const std::uint64_t base = (rng() % space) & ~(rng() % 2 ? std::uint64_t{0xfff} : std::uint64_t{0}); + index.insert(key, base, width); + ranges[key] = {base, width}; + } else if (kind < 4) { + const bool was = ranges.erase(key) != 0; + if (index.erase(key) != was) fail("erase result", static_cast<std::uint64_t>(key), was); + } else { // query: inside a known range (start, interior, last byte), or anywhere + std::uint64_t address = rng() % space; + if (!ranges.empty() && rng() % 2) { + auto it = ranges.begin(); + std::advance(it, static_cast<long>(rng() % ranges.size())); + const auto [base, width] = it->second; + const unsigned where = rng() % 3; + address = where == 0 ? base : where == 1 ? base + rng() % width : base + width - 1; + } + const std::uint64_t bytes = rng() % 3 == 0 ? 1 : 1 + rng() % 8192; + const auto got = query(index, address, bytes), want = walk(ranges, address, bytes); + ++queries; + hits += !want.empty(); + if (got != want) fail("random query differs from the walk", address, bytes); + } + } + if (index.size() != ranges.size()) fail("size", index.size(), ranges.size()); + std::printf("buffer_address_index%s: %u operations, %u queries (%u with a containing range), %zu ranges at the end, %d failures\n", + m == Index::Mutation::exact_start ? " --mutate" : "", operations, queries, hits, ranges.size(), failures); +} +} // namespace + +int main(int argc, char** argv) +{ + const auto m = argc == 2 && std::strcmp(argv[1], "--mutate") == 0 ? Index::Mutation::exact_start : Index::Mutation::none; + if (argc > 2 || (argc == 2 && m == Index::Mutation::none)) { + std::puts("usage: buffer_address_index_check [--mutate]"); + return 2; + } + explicit_cases(m); + random_cases(m, 200000); + return failures ? 1 : 0; +} diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 84ff8c3f52..30ec7e50cc 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -13,7 +13,7 @@ Microsoft::WRL::ComPtr<ID3D12Resource> resource(ID3D12Device* device, const D3D1 D3D12_HEAP_TYPE heap, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear = nullptr); void check_compute(ID3D12Device* device, bool tables); void check_sampler_views(ID3D12Device* device, const char* shader_path); -bool check_startup_sampler_x(ID3D12Device* device, bool swapped); +bool check_startup_sampler_x(ID3D12Device* device, bool swapped, int words = 0); int check_startup_cb_blend(ID3D12Device* device, bool swapped); int check_startup_export_write_mask(ID3D12Device* device, bool unmasked); int check_startup_composite_provenance(ID3D12Device* device); diff --git a/tests/gfx10_layout_check.cpp b/tests/gfx10_layout_check.cpp new file mode 100644 index 0000000000..a137c3786f --- /dev/null +++ b/tests/gfx10_layout_check.cpp @@ -0,0 +1,659 @@ +// LOCAL (textures): checks src/startup_stubs/gfx10_layout.h (the console-swizzled texture layout used to detile +// memory views) on synthetic shapes. +// +// Without addrlib (every build): +// gfx10_layout_check <golden> every element address of every golden shape hashes to the addrlib value +// recorded in <golden>, and the layout agrees with the repo's two +// independent tiled forms (Bc16Surface, bc64::Chain) where they overlap +// gfx10_layout_check <golden> --mutate floor|tail negative controls: a floor mip size or dropped tail +// coordinates must be detected (the test then fails) +// With addrlib (XBOX2WINDOWS_ADDRLIB_DIR, Mesa 25.1.0 src/amd/addrlib, MIT; see tools/fetch_addrlib.py): +// --addrlib every element address and surface size against Addr2ComputeSurfaceAddrFromCoord +// / Addr2ComputeSurfaceInfo on four configurations (Navi1x and Navi21, 1 and +// 16 pipes), the in-tree equation table against addrlib, and BC formats given +// as pixels (ADDR_FMT_BC*) against the same shape given as 4x4 blocks +// --print-equations the equation table (src/startup_stubs/gfx10_layout_equations.inc) +// --write-golden <path> the golden file, hashed from addrlib's addresses (not from gfx10_layout.h) +// --write-tiled <shape> <path> --addrlib the synthetic surface of the WARP detile draw, every element at addrlib's +// address (the same without --addrlib uses gfx10_layout.h: plumbing only) +#include "startup_stubs/gfx10_layout_local.h" +#include "startup_stubs/bc64_chain.h" +#include "startup_stubs/bc7_4k_s.h" + +#include <algorithm> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <string> +#include <tuple> +#include <utility> +#include <vector> + +using x2w_startup::gfx10_local::Layout; + +namespace { +struct Shape { + const char* name; + unsigned mode; + bool is3d; + unsigned elem; // bytes per element + unsigned w, h, d, mips; // elements (4x4 blocks for BC), depth or array size + unsigned bc; // 0, or the BC number for the pixel-form addrlib check (pixel size = 4 * elements) + unsigned pw = 0, ph = 0; // BC: the pixel size when it is not 4 * elements (mip-0 blocks ceil(pixels / 4)) +}; + +const Shape shapes[] = { + {"r16_64x64x32_array", 5, false, 2, 64, 64, 32, 1, 0}, + {"r16_64x64x32_array_7mips", 5, false, 2, 64, 64, 32, 7, 0}, + {"bc1_12x44", 5, false, 8, 3, 11, 1, 1, 1}, + {"bc3_512x468", 5, false, 16, 128, 117, 1, 1, 3}, + {"bc1_2048_12mips", 5, false, 8, 512, 512, 1, 12, 1}, + {"bc3_256_9mips", 5, false, 16, 64, 64, 1, 9, 3}, + {"rgba16f_17cubed_3d", 5, true, 8, 17, 17, 17, 1, 0}, + {"rgba16f_17cubed_3d_5mips", 5, true, 8, 17, 17, 17, 5, 0}, + {"r32f_128x72_7mips_linear", 0, false, 4, 128, 72, 1, 7, 0}, + {"rgba8_300x200_9mips_4k_s", 5, false, 4, 300, 200, 1, 9, 0}, + {"rgba8_300x200_9mips_4k_d", 6, false, 4, 300, 200, 1, 9, 0}, + {"rgba8_300x200_9mips_64k_s", 9, false, 4, 300, 200, 1, 9, 0}, + {"rgba8_300x200_9mips_64k_d", 10, false, 4, 300, 200, 1, 9, 0}, + {"r8_1000x7_10mips_64k_s", 9, false, 1, 1000, 7, 1, 10, 0}, + {"r16_77x300_9mips_4k_s", 5, false, 2, 77, 300, 1, 9, 0}, + {"rg32_129x65_8mips_64k_d", 10, false, 8, 129, 65, 1, 8, 0}, + {"rgba8_64x64x6_7mips_64k_s", 9, false, 4, 64, 64, 6, 7, 0}, + {"r8_32cubed_3d_6mips_64k_s", 9, true, 1, 32, 32, 32, 6, 0}, + {"rgba32f_40x24x9_3d_6mips_4k_s", 5, true, 16, 40, 24, 9, 6, 0}, + {"bc7_1024_9mips_64k_s", 9, false, 16, 256, 256, 1, 9, 7}, + {"bc7_1024x512x2_9mips_64k_s", 9, false, 16, 256, 128, 2, 9, 7}, + {"bc5_4096_13mips_64k_s", 9, false, 16, 1024, 1024, 1, 13, 5}, + {"bc1_13x5_4mips_4k_s", 5, false, 8, 4, 2, 1, 3, 1}, + {"r32f_77x33_7mips_linear", 0, false, 4, 77, 33, 1, 7, 0}, + {"rgba8_5x3x4_linear_3d", 0, true, 4, 5, 3, 4, 1, 0}, + {"bc1_1024_11mips_64k_d", 10, false, 8, 256, 256, 1, 11, 1}, + {"bc7_2048x1024_12mips_64k_d", 10, false, 16, 512, 256, 1, 12, 7}, + {"bc7_300x200x3_7mips_4k_d", 6, false, 16, 75, 50, 3, 7, 7}, + {"bc1_44x12_4mips_4k_d", 6, false, 8, 11, 3, 1, 4, 1}, + // The WARP detile draw (tests/startup_memory_srv_detile.ps1; --write-tiled), with rgba16f_17cubed_3d_5mips. + {"bc1_256_9mips_4k_s", 5, false, 8, 64, 64, 1, 9, 1}, + {"bc1_256x128x2_8mips_64k_d", 10, false, 8, 64, 32, 2, 8, 1}, + {"bc3_256_9mips_4k_s", 5, false, 16, 64, 64, 1, 9, 3}, // a tiled_bc_srv description the tiled paths refuse (mips) + {"rgba16f_100x60_3mips_linear", 0, false, 8, 100, 60, 1, 3, 0}, + {"bc7_512x1056_8mips_4k_s", 5, false, 16, 128, 264, 1, 8, 7, 512, 1056}, + {"bc7_1000x600_10mips_64k_d", 10, false, 16, 250, 150, 1, 10, 7, 1000, 600}, + {"bc1_132_8mips_4k_s", 5, false, 8, 33, 33, 1, 8, 1, 132, 132}, + {"bc3_132x68x2_8mips_64k_d", 10, false, 16, 33, 17, 2, 8, 3, 132, 68}, +}; + +unsigned ceil_shift(unsigned v, unsigned s) { return (v + (1u << s) - 1) >> s; } + +struct Fnv { + std::uint64_t h = 1469598103934665603ull; + void add(std::uint64_t v) + { + for (int i = 0; i < 8; ++i) { + h ^= (v >> (8 * i)) & 0xff; + h *= 1099511628211ull; + } + } +}; + +// Every element of every level and slice, in a fixed order, with addrlib's (ceiling) level extents. +template<class Visit> void for_each_element(const Shape& s, Visit visit) +{ + for (unsigned mip = 0; mip < s.mips; ++mip) { + const unsigned w = ceil_shift(s.w, mip), h = ceil_shift(s.h, mip); + // A 3D mip holds max(1, depth >> mip) slices (D3D's floor; addrlib's Valid3DMipSliceIdConstraint refuses the + // rest), while width and height round up as the placement does. + const unsigned depth = s.is3d ? (std::max)(1u, s.d >> mip) : s.d; + for (unsigned z = 0; z < depth; ++z) + for (unsigned y = 0; y < h; ++y) + for (unsigned x = 0; x < w; ++x) visit(mip, x, y, z); + } +} + +Layout layout_of(const Shape& s, Layout::Mutation m = Layout::none, bool rb_plus = false) +{ + return Layout(s.mode, s.is3d, s.elem, s.w, s.h, s.d, s.mips, m, rb_plus); +} + +int failures; +void fail(const char* format, const char* a, std::uint64_t b = 0, std::uint64_t c = 0) +{ + if (failures++ < 12) { + std::printf("FAIL "); + std::printf(format, a, b, c); + std::printf("\n"); + } +} + +// The two existing, independently written tiled forms, where gfx10_layout.h covers the same surface. +void cross_check() +{ + // Bc16Surface: 16-byte 4 KiB standard, one level. + for (const auto [w, h] : {std::pair{512u, 468u}, std::pair{64u, 64u}, std::pair{100u, 36u}}) { + const x2w_startup::Bc16Surface bc(w, h); + const Layout l(5, false, 16, bc.columns, bc.rows, 1, 1); + for (unsigned y = 0; y < bc.rows; ++y) + for (unsigned x = 0; x < bc.columns; ++x) + if (l.address(0, x, y, 0) != bc.block_offset(x, y)) { + fail("Bc16Surface %s differs at %llu,%llu", "4KB_S", x, y); + return; + } + } + // bc64::Chain: 16-byte 64 KiB standard 1024-wide chains. + for (const auto [h, mips, slices] : {std::tuple{1024u, 6u, 1u}, std::tuple{1024u, 9u, 2u}, std::tuple{512u, 9u, 1u}}) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = 1024; + d.Height = h; + d.DepthOrArraySize = static_cast<UINT16>(slices); + d.MipLevels = static_cast<UINT16>(mips); + d.Format = DXGI_FORMAT_BC7_UNORM; + d.SampleDesc.Count = 1; + d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x109); + const x2w_startup::bc64::Chain chain(d); + const Layout l(9, false, 16, 256, h / 4, slices, mips); + if (l.size != chain.bytes()) fail("bc64::Chain size %s: %llu vs %llu", "64KB_S", l.size, chain.bytes()); + for (unsigned s = 0; s < slices; ++s) + for (unsigned mip = 0; mip < mips; ++mip) + for (unsigned y = 0; y < chain.rows(mip); ++y) + for (unsigned x = 0; x < chain.columns(mip); ++x) + if (l.address(mip, x, y, s) != chain.address(mip, x, y, s)) { + fail("bc64::Chain differs at mip/x %s %llu %llu", "64KB_S", mip, x); + return; + } + } +} + +int golden_check(const char* path, Layout::Mutation mutation) +{ + for (unsigned mode : {6u, 10u}) { + Layout surface(mode, false, 4, 512, 512, 1, 8, Layout::none, true); + const auto base = surface.address(0, 0, 0, 0); + if (surface.address(0, 4, 0, 0) != base + 64 || surface.address(0, 0, 4, 0) != base + 128) + fail("%s: incorrect RB+ display microtile", "rgba8"); + } + FILE* f = std::fopen(path, "r"); + if (!f) { + std::printf("FAIL cannot open %s\n", path); + return 1; + } + char line[512]; + unsigned checked = 0; + while (std::fgets(line, sizeof line, f)) { + if (line[0] == '#' || line[0] == '\n') continue; + char name[128]; + unsigned long long size = 0, hash = 0; + if (std::sscanf(line, "%127s %llu %llx", name, &size, &hash) != 3) continue; + const Shape* s = nullptr; + for (const auto& c : shapes) + if (std::strcmp(c.name, name) == 0) s = &c; + if (!s) { + fail("golden shape %s is not in the shape list", name); + continue; + } + const Layout l = layout_of(*s, mutation); + if (!l.valid) { + fail("%s: layout refused", name); + continue; + } + if (l.size != size) fail("%s: size %llu, golden %llu", name, l.size, size); + Fnv fnv; + for_each_element(*s, [&](unsigned mip, unsigned x, unsigned y, unsigned z) { fnv.add(l.address(mip, x, y, z)); }); + if (fnv.h != hash) fail("%s: address hash %llx, golden %llx", name, fnv.h, hash); + ++checked; + } + std::fclose(f); + if (checked != sizeof shapes / sizeof shapes[0]) fail("golden has %s%llu of %llu shapes", "", checked, sizeof shapes / sizeof shapes[0]); + if (mutation == Layout::none) cross_check(); + std::printf("gfx10_layout%s: %u golden shapes, %d failures\n", + mutation == Layout::floor_mips ? " --mutate floor" : mutation == Layout::no_tail_coords ? " --mutate tail" : "", + checked, failures); + return failures ? 1 : 0; +} + +const Shape* shape_named(const char* name) +{ + for (const auto& s : shapes) + if (std::strcmp(s.name, name) == 0) return &s; + return nullptr; +} + +std::uint16_t half_of(unsigned n) // an integer below 2048 as binary16 (exact) +{ + if (!n) return 0; + unsigned e = 0; + while ((2u << e) <= n) ++e; + return static_cast<std::uint16_t>(((e + 15) << 10) | ((n << (10 - e)) & 0x3ff)); +} + +// The synthetic element pattern of the WARP detile draw; tests/startup_memory_srv_detile.ps1 checks the same +// values in its pixel shader. BC1 shapes: a solid block (color0 = color1 = id, indices 0) with id = x | y << 6 | +// (mip + 8 * slice) << 12. BC3 shapes: the same color block after a solid alpha block (alpha0 = alpha1 = +// 16 * level + 5, indices 0). Other 8-byte shapes: R16G16B16A16_FLOAT (x, y, z, mip + 1). +bool pattern(const Shape& s, unsigned mip, unsigned x, unsigned y, unsigned z, unsigned char* out) +{ + if (s.bc == 3 && s.elem == 16) { + const unsigned level = mip + 8 * z; + if (x >= 64 || y >= 64 || level >= 16) return false; + const unsigned id = x | y << 6 | level << 12; + const auto alpha = static_cast<unsigned char>(16 * level + 5); + const unsigned char block[16] = {alpha, alpha, 0, 0, 0, 0, 0, 0, static_cast<unsigned char>(id), static_cast<unsigned char>(id >> 8), + static_cast<unsigned char>(id), static_cast<unsigned char>(id >> 8), 0, 0, 0, 0}; + std::memcpy(out, block, 16); + return true; + } + if (s.elem != 8) return false; + if (s.bc == 1) { + const unsigned level = mip + 8 * z; + if (x >= 64 || y >= 64 || level >= 16) return false; + const unsigned id = x | y << 6 | level << 12; + const unsigned char block[8] = {static_cast<unsigned char>(id), static_cast<unsigned char>(id >> 8), + static_cast<unsigned char>(id), static_cast<unsigned char>(id >> 8), 0, 0, 0, 0}; + std::memcpy(out, block, 8); + return true; + } + if (s.bc || x >= 2048 || y >= 2048 || z >= 2048) return false; + const std::uint16_t h[4] = {half_of(x), half_of(y), half_of(z), half_of(mip + 1)}; + std::memcpy(out, h, 8); + return true; +} + +// The surface bytes of a shape with every element's pattern at the address `address` gives (addrlib's for the +// WARP oracle, gfx10_layout.h's for the plumbing variant); gaps stay zero. +template<class Address> int write_tiled(const Shape& s, const char* path, std::uint64_t size, Address address) +{ + if (!size || size > (64ull << 20)) { + std::printf("FAIL %s: surface size %llu\n", s.name, static_cast<unsigned long long>(size)); + return 1; + } + std::vector<unsigned char> bytes(static_cast<std::size_t>(size)); + bool ok = true; + unsigned elements = 0; + for_each_element(s, [&](unsigned mip, unsigned x, unsigned y, unsigned z) { + std::uint64_t a = 0; + if (!ok || !address(mip, x, y, z, a) || a + s.elem > size || !pattern(s, mip, x, y, z, &bytes[static_cast<std::size_t>(a)])) + ok = false; + ++elements; + }); + FILE* f = ok ? std::fopen(path, "wb") : nullptr; + if (!f || std::fwrite(bytes.data(), 1, bytes.size(), f) != bytes.size()) { + std::printf("FAIL %s: cannot write the tiled surface to %s\n", s.name, path); + if (f) std::fclose(f); + return 1; + } + std::fclose(f); + std::printf("wrote %s: %s, %u elements, %llu bytes\n", path, s.name, elements, static_cast<unsigned long long>(size)); + return 0; +} + +int write_tiled_layout(const char* name, const char* path) +{ + const Shape* s = shape_named(name); + if (!s) return 2; + const Layout l = layout_of(*s); + if (!l.valid) return 1; + return write_tiled(*s, path, l.size, [&](unsigned mip, unsigned x, unsigned y, unsigned z, std::uint64_t& a) { + a = l.address(mip, x, y, z); + return true; + }); +} +} // namespace + +#ifdef XBOX2WINDOWS_HAVE_ADDRLIB +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include <windows.h> +#include "addrinterface.h" + +namespace { +VOID* ADDR_API alloc_sys_mem(const ADDR_ALLOCSYSMEM_INPUT* in) { return std::malloc(in->sizeInBytes); } +ADDR_E_RETURNCODE ADDR_API free_sys_mem(const ADDR_FREESYSMEM_INPUT* in) +{ + std::free(in->pVirtAddr); + return ADDR_OK; +} + +struct Config { + const char* name; + UINT_32 revision, gb_addr_config; + bool rb_plus; // Navi21: addrlib's RB+ pattern tables +}; +// Family NV (0x8F). Navi10 (revision 0x03, no RB+ tables) and Navi21 (0x28, RB+ tables); GB_ADDR_CONFIG NUM_PIPES +// (bits 0-2, log2) 0 or 4 with NUM_PKRS (bits 8-10) 0 or 4 and the 0x40 of Mesa's navi21 test configuration. +const Config configs[] = { + {"navi10 1 pipe", 0x03, 0x40, false}, + {"navi10 16 pipes", 0x03, 0x40 | 4u | (4u << 8), false}, + {"navi21 1 pipe", 0x28, 0x40, true}, + {"navi21 16 pipes", 0x28, 0x40 | 4u | (4u << 8), true}, +}; + +ADDR_HANDLE create(const Config& c) +{ + ADDR_CREATE_INPUT in{}; + ADDR_CREATE_OUTPUT out{}; + in.size = sizeof in; + out.size = sizeof out; + in.chipEngine = 0x0000000D; // CIASICIDGFXENGINE_ARCTICISLAND + in.chipFamily = 0x8F; + in.chipRevision = c.revision; + in.callbacks.allocSysMem = alloc_sys_mem; + in.callbacks.freeSysMem = free_sys_mem; + in.regValue.gbAddrConfig = c.gb_addr_config; + return AddrCreate(&in, &out) == ADDR_OK ? out.hLib : nullptr; +} + +AddrFormat element_format(unsigned elem) +{ + switch (elem) { + case 1: return ADDR_FMT_8; + case 2: return ADDR_FMT_16; + case 4: return ADDR_FMT_32; + case 8: return ADDR_FMT_32_32; + default: return ADDR_FMT_32_32_32_32; + } +} +AddrFormat bc_format(unsigned bc) +{ + switch (bc) { + case 1: return ADDR_FMT_BC1; + case 3: return ADDR_FMT_BC3; + case 5: return ADDR_FMT_BC5; + default: return ADDR_FMT_BC7; + } +} + +ADDR_E_RETURNCODE info(ADDR_HANDLE lib, const Shape& s, ADDR2_COMPUTE_SURFACE_INFO_OUTPUT& out, ADDR2_MIP_INFO* mips, + bool pixels = false) +{ + ADDR2_COMPUTE_SURFACE_INFO_INPUT in{}; + in.size = sizeof in; + in.flags.texture = 1; + in.swizzleMode = static_cast<AddrSwizzleMode>(s.mode); + in.resourceType = s.is3d ? ADDR_RSRC_TEX_3D : ADDR_RSRC_TEX_2D; + in.format = pixels ? bc_format(s.bc) : element_format(s.elem); + in.bpp = pixels ? 0 : s.elem * 8; + in.width = pixels ? (s.pw ? s.pw : s.w * 4) : s.w; + in.height = pixels ? (s.ph ? s.ph : s.h * 4) : s.h; + in.numSlices = s.d; + in.numMipLevels = s.mips; + in.numSamples = 1; + in.numFrags = 1; + out = {}; + out.size = sizeof out; + out.pMipInfo = mips; + return Addr2ComputeSurfaceInfo(lib, &in, &out); +} + +bool addr(ADDR_HANDLE lib, const Shape& s, unsigned mip, unsigned x, unsigned y, unsigned z, std::uint64_t& address) +{ + ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT in{}; + ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT out{}; + in.size = sizeof in; + out.size = sizeof out; + in.x = x; + in.y = y; + in.slice = z; + in.mipId = mip; + in.unalignedWidth = s.w; + in.unalignedHeight = s.h; + in.numSlices = s.d; + in.numMipLevels = s.mips; + in.numSamples = 1; + in.numFrags = 1; + in.swizzleMode = static_cast<AddrSwizzleMode>(s.mode); + in.resourceType = s.is3d ? ADDR_RSRC_TEX_3D : ADDR_RSRC_TEX_2D; + in.bpp = s.elem * 8; + in.flags.texture = 1; + if (Addr2ComputeSurfaceAddrFromCoord(lib, &in, &out) != ADDR_OK || out.bitPosition != 0) return false; + address = out.addr; + return true; +} + +// The in-block equation of (thick, mode, element bytes), probed bit by bit on a one-block surface: in a non-XOR +// mode each coordinate bit moves exactly one address bit. +x2w_startup::gfx10_local::Equation probe(ADDR_HANDLE lib, bool thick, unsigned mode, unsigned e) +{ + x2w_startup::gfx10_local::Equation eq{}; + Shape s{"probe", mode, thick, 1u << e, 1, 1, 1, 1, 0}; + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT o{}; + if (info(lib, s, o, nullptr) != ADDR_OK) return eq; + s.w = o.blockWidth; + s.h = o.blockHeight; + s.d = thick ? o.blockSlices : 1; + const unsigned block_log2 = (mode == 5 || mode == 6) ? 12 : 16; + std::uint8_t src[16]; + std::memset(src, 0xff, sizeof src); + for (unsigned k = 0; k < e; ++k) src[k] = static_cast<std::uint8_t>(0xc0 | k); + const auto place = [&](unsigned channel, unsigned extent, unsigned x, unsigned y, unsigned z, unsigned k) { + std::uint64_t a = 0; + if (!addr(lib, s, 0, x, y, z, a) || !a || (a & (a - 1)) || a >= (1ull << block_log2)) return false; + unsigned bit = 0; + while ((1ull << bit) != a) ++bit; + if (src[bit] != 0xff) return false; + src[bit] = static_cast<std::uint8_t>(channel | k); + (void)extent; + return true; + }; + for (unsigned k = 0; (1u << k) < s.w; ++k) + if (!place(0x00, s.w, 1u << k, 0, 0, k)) return eq; + for (unsigned k = 0; (1u << k) < s.h; ++k) + if (!place(0x40, s.h, 0, 1u << k, 0, k)) return eq; + if (thick) + for (unsigned k = 0; (1u << k) < s.d; ++k) + if (!place(0x80, s.d, 0, 0, 1u << k, k)) return eq; + for (unsigned i = 0; i < block_log2; ++i) + if (src[i] == 0xff) return eq; + eq.bits = static_cast<std::uint8_t>(block_log2); + std::memcpy(eq.src, src, sizeof src); + return eq; +} + +const unsigned table_modes[4] = {5, 6, 9, 10}; + +int print_equations() +{ + ADDR_HANDLE lib = create(configs[0]); + if (!lib) return 1; + std::printf("// GENERATED by tests/gfx10_layout_check.cpp --print-equations from AMD addrlib (Mesa 5c142e46f3f6e752ed745fd48912ebb8fad67145,\n" + "// mesa-25.1.0, src/amd/addrlib, MIT; see gfx10_layout.h): [thick][4KB_S 4KB_D 64KB_S 64KB_D][log2 bytes].\n"); + for (int thick = 0; thick < 2; ++thick) { + std::printf("{\n"); + for (unsigned mode : table_modes) { + std::printf(" {\n"); + for (unsigned e = 0; e < 5; ++e) { + const auto eq = probe(lib, thick != 0, mode, e); + std::printf(" {%u, {", eq.bits); + for (unsigned i = 0; i < 16; ++i) std::printf("%s0x%02x", i ? ", " : "", eq.bits ? eq.src[i] : 0); + std::printf("}},\n"); + } + std::printf(" },\n"); + } + std::printf("},\n"); + } + AddrDestroy(lib); + return 0; +} + +int write_golden(const char* path) +{ + ADDR_HANDLE lib = create(configs[0]); + FILE* f = lib ? std::fopen(path, "w") : nullptr; + if (!f) return 1; + std::fprintf(f, "# GENERATED by tests/gfx10_layout_check.cpp --write-golden from AMD addrlib (Mesa 5c142e46f3f6e752ed745fd48912ebb8fad67145,\n" + "# mesa-25.1.0, src/amd/addrlib, MIT), configuration %s: shape, surface bytes, FNV-1a 64 of every element\n" + "# address (level, slice or depth, row, column order, addrlib's level extents). Synthetic shapes only.\n", + configs[0].name); + for (const auto& s : shapes) { + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT o{}; + ADDR2_MIP_INFO mips[16]{}; + if (info(lib, s, o, mips) != ADDR_OK) { + std::printf("FAIL addrlib refuses %s\n", s.name); + return 1; + } + Fnv fnv; + bool ok = true; + for_each_element(s, [&](unsigned mip, unsigned x, unsigned y, unsigned z) { + std::uint64_t a = 0; + ok = ok && addr(lib, s, mip, x, y, z, a); + fnv.add(a); + }); + if (!ok) { + std::printf("FAIL addrlib address failed for %s\n", s.name); + return 1; + } + std::fprintf(f, "%s %llu %016llx\n", s.name, static_cast<unsigned long long>(o.surfSize), static_cast<unsigned long long>(fnv.h)); + } + std::fclose(f); + AddrDestroy(lib); + std::printf("wrote %s (%zu shapes)\n", path, sizeof shapes / sizeof shapes[0]); + return 0; +} + +int write_tiled_addrlib(const char* name, const char* path) +{ + const Shape* s = shape_named(name); + ADDR_HANDLE lib = s ? create(configs[0]) : nullptr; + if (!lib) return 2; + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT o{}; + ADDR2_MIP_INFO mips[16]{}; + int rc = 1; + if (info(lib, *s, o, mips) == ADDR_OK) + rc = write_tiled(*s, path, o.surfSize, [&](unsigned mip, unsigned x, unsigned y, unsigned z, std::uint64_t& a) { + return addr(lib, *s, mip, x, y, z, a); + }); + AddrDestroy(lib); + return rc; +} + +int debug_shape(const char* name) +{ + ADDR_HANDLE lib = create(configs[0]); + for (const auto& s : shapes) { + if (std::strcmp(s.name, name) != 0) continue; + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT o{}; + ADDR2_MIP_INFO mips[16]{}; + const auto rc = info(lib, s, o, mips); + const Layout l = layout_of(s); + std::printf("%s: addrlib rc %d size %llu slice %llu block %ux%ux%u first tail %u; layout size %llu slice %llu block %ux%ux%u\n", + s.name, rc, o.surfSize, o.sliceSize, o.blockWidth, o.blockHeight, o.blockSlices, o.firstMipIdInTail, l.size, + l.slice_size, l.bw, l.bh, l.bd); + for (unsigned m = 0; m < s.mips; ++m) { + std::uint64_t a = 0; + const bool ok = addr(lib, s, m, 0, 0, 0, a); + std::printf(" mip %u: addrlib pitch %u height %u depth %u offset %llu macro %llu tail %llu (%u,%u,%u) addr(0,0,0) %s%llu; " + "layout pitch %u height %u macro %llu tail %d (%u,%u) addr %llu\n", + m, mips[m].pitch, mips[m].height, mips[m].depth, mips[m].offset, mips[m].macroBlockOffset, static_cast<unsigned long long>(mips[m].mipTailOffset), + mips[m].mipTailCoordX, mips[m].mipTailCoordY, mips[m].mipTailCoordZ, ok ? "" : "FAILED ", a, l.level[m].pitch, + l.level[m].height, l.level[m].offset, l.level[m].in_tail, l.level[m].tail_x, l.level[m].tail_y, l.address(m, 0, 0, 0)); + } + } + AddrDestroy(lib); + return 0; +} + +// The D modes (4KB_D, 64KB_D) with 4-byte elements: addrlib's RB+ equation differs from the Navi1x one, so the +// in-tree table (Navi1x) is compared with Navi1x only, and on Navi21 the difference itself is asserted. The runtime +// selects the RB+ equation for these textures; the address sweep below checks both variants. +bool chip_dependent(unsigned mode, unsigned elem) { return (mode == 6 || mode == 10) && elem == 4; } + +int addrlib_check() +{ + unsigned compared = 0, chip_dependent_seen = 0; + for (const auto& c : configs) { + ADDR_HANDLE lib = create(c); + if (!lib) { + fail("AddrCreate %s", c.name); + continue; + } + for (int thick = 0; thick < 2; ++thick) + for (unsigned mi = 0; mi < 4; ++mi) + for (unsigned e = 0; e < 5; ++e) { + const auto eq = probe(lib, thick != 0, table_modes[mi], e); + const auto& in_tree = x2w_startup::gfx10_local::equations[thick][mi][e]; + const bool differs = eq.bits != in_tree.bits || (eq.bits && std::memcmp(eq.src, in_tree.src, sizeof eq.src) != 0); + if (c.rb_plus && !thick && chip_dependent(table_modes[mi], 1u << e)) { + if (!differs) fail("%s: the D-mode equation e %llu was expected to differ on RB+", c.name, e); + ++chip_dependent_seen; + continue; + } + if (differs) + fail("%s: equation thick %llu mode index/e %llu differs from the in-tree table", c.name, thick, mi * 10 + e); + } + for (const auto& s : shapes) { + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT o{}; + ADDR2_MIP_INFO mips[16]{}; + if (info(lib, s, o, mips) != ADDR_OK) { + fail("addrlib (%s) refuses shape %llu", c.name, static_cast<std::uint64_t>(&s - shapes)); + continue; + } + const Layout l = layout_of(s, Layout::none, c.rb_plus); + if (!l.valid) { + fail("%s: layout refuses it", s.name); + continue; + } + if (l.size != o.surfSize || l.slice_size != o.sliceSize) + fail("%s: size %llu vs addrlib %llu", s.name, l.size, o.surfSize); + bool reported = false; + for_each_element(s, [&](unsigned mip, unsigned x, unsigned y, unsigned z) { + std::uint64_t a = 0; + const bool ok = addr(lib, s, mip, x, y, z, a); + if (!ok || a != l.address(mip, x, y, z)) { + if (!reported) { + fail("%s: first address mismatch", s.name); + std::printf(" (%s) at mip %u x %u y %u z %u: addrlib %s%llu, layout %llu\n", c.name, mip, x, y, z, ok ? "" : "FAILED ", + static_cast<unsigned long long>(a), static_cast<unsigned long long>(l.address(mip, x, y, z))); + } + reported = true; + } + ++compared; + }); + if (s.bc) { + // The same shape given as BC pixels: identical sizes and level placement. + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT p{}; + ADDR2_MIP_INFO pm[16]{}; + if (info(lib, s, p, pm, true) != ADDR_OK) { + fail("addrlib (%s) refuses the BC pixel form of shape %llu", c.name, static_cast<std::uint64_t>(&s - shapes)); + continue; + } + if (p.surfSize != o.surfSize || p.sliceSize != o.sliceSize) fail("%s: BC pixel form size %llu vs %llu", s.name, p.surfSize, o.surfSize); + for (unsigned m = 0; m < s.mips; ++m) + if (pm[m].offset != mips[m].offset || pm[m].macroBlockOffset != mips[m].macroBlockOffset || + pm[m].mipTailOffset != mips[m].mipTailOffset) + fail("%s: BC pixel form level %llu offset %llu differs", s.name, m, pm[m].offset); + } + } + AddrDestroy(lib); + } + std::printf("gfx10_layout --addrlib: %zu configurations, %zu shapes, %u element addresses compared, %u chip-dependent D-mode " + "equations confirmed different on RB+, %d failures\n", + sizeof configs / sizeof configs[0], sizeof shapes / sizeof shapes[0], compared, chip_dependent_seen, failures); + return failures ? 1 : 0; +} +} // namespace +#endif + +int main(int argc, char** argv) +{ + if (argc == 4 && std::strcmp(argv[1], "--write-tiled") == 0) return write_tiled_layout(argv[2], argv[3]); + if (argc >= 2 && std::strncmp(argv[1], "--", 2) == 0) { +#ifdef XBOX2WINDOWS_HAVE_ADDRLIB + if (argc == 5 && std::strcmp(argv[1], "--write-tiled") == 0 && std::strcmp(argv[4], "--addrlib") == 0) + return write_tiled_addrlib(argv[2], argv[3]); + if (std::strcmp(argv[1], "--addrlib") == 0) return addrlib_check(); + if (std::strcmp(argv[1], "--print-equations") == 0) return print_equations(); + if (std::strcmp(argv[1], "--write-golden") == 0 && argc == 3) return write_golden(argv[2]); + if (std::strcmp(argv[1], "--debug") == 0 && argc == 3) return debug_shape(argv[2]); + std::puts("usage: gfx10_layout_check <golden> [--mutate floor|tail] | --addrlib | --print-equations | --write-golden <path>"); + return 2; +#else + std::puts("gfx10_layout: SKIP (built without addrlib; configure with -DXBOX2WINDOWS_ADDRLIB_DIR=<mesa>/src/amd/addrlib)"); + return 77; +#endif + } + if (argc == 2) return golden_check(argv[1], Layout::none); + if (argc == 4 && std::strcmp(argv[2], "--mutate") == 0) + return golden_check(argv[1], std::strcmp(argv[3], "floor") == 0 ? Layout::floor_mips : Layout::no_tail_coords); + std::puts("usage: gfx10_layout_check <golden> [--mutate floor|tail] | --addrlib | --print-equations | --write-golden <path>"); + return 2; +} diff --git a/tests/gfx10_layout_golden.txt b/tests/gfx10_layout_golden.txt new file mode 100644 index 0000000000..5a57b7faf6 --- /dev/null +++ b/tests/gfx10_layout_golden.txt @@ -0,0 +1,40 @@ +# GENERATED by tests/gfx10_layout_check.cpp --write-golden from AMD addrlib (Mesa 5c142e46f3f6e752ed745fd48912ebb8fad67145, +# mesa-25.1.0, src/amd/addrlib, MIT), configuration navi10 1 pipe: shape, surface bytes, FNV-1a 64 of every element +# address (level, slice or depth, row, column order, addrlib's level extents). Synthetic shapes only. +r16_64x64x32_array 262144 322424fe75dbef83 +r16_64x64x32_array_7mips 393216 6ce0a245c1c284d9 +bc1_12x44 4096 dbc347a0667eaaa7 +bc3_512x468 262144 16ef1352c0d7b283 +bc1_2048_12mips 2797568 867b7cc2d199d683 +bc3_256_9mips 90112 260e8160b1de2c74 +rgba16f_17cubed_3d 110592 43e0285162792dba +rgba16f_17cubed_3d_5mips 184320 7e95600211374e81 +r32f_128x72_7mips_linear 55552 958524d240edd663 +rgba8_300x200_9mips_4k_s 409600 39b182ea028ab720 +rgba8_300x200_9mips_4k_d 409600 39b182ea028ab720 +rgba8_300x200_9mips_64k_s 655360 45aeccbdf91a7f2c +rgba8_300x200_9mips_64k_d 655360 45aeccbdf91a7f2c +r8_1000x7_10mips_64k_s 524288 2f94bd6d219cea6d +r16_77x300_9mips_4k_s 126976 0bf355dd68c005a1 +rg32_129x65_8mips_64k_d 393216 e72b8efa0c1f8b56 +rgba8_64x64x6_7mips_64k_s 393216 a2ec140eb40e73ee +r8_32cubed_3d_6mips_64k_s 65536 e79b5cc07a360843 +rgba32f_40x24x9_3d_6mips_4k_s 376832 866e2f7e496c5388 +bc7_1024_9mips_64k_s 1441792 8a83925d27f45685 +bc7_1024x512x2_9mips_64k_s 1572864 15f301a6837bc1ef +bc5_4096_13mips_64k_s 22413312 d543ae5e9812860a +bc1_13x5_4mips_4k_s 4096 6b654a182752697c +r32f_77x33_7mips_linear 26368 1a35b3f65f020482 +rgba8_5x3x4_linear_3d 3072 71898ab306df7d03 +bc1_1024_11mips_64k_d 720896 403864daa4e00219 +bc7_2048x1024_12mips_64k_d 2883584 ecadf344d968835a +bc7_300x200x3_7mips_4k_d 368640 6287ed1ffb381865 +bc1_44x12_4mips_4k_d 4096 9def92b21b91b09a +bc1_256_9mips_4k_s 45056 1a9e971b8f78bd83 +bc1_256x128x2_8mips_64k_d 131072 af09b31a6ca7535f +bc3_256_9mips_4k_s 90112 260e8160b1de2c74 +rgba16f_100x60_3mips_linear 80640 ab16f83d4b2dc28a +bc7_512x1056_8mips_4k_s 770048 a1cacc58ccc68e04 +bc7_1000x600_10mips_64k_d 1179648 a44e6cc400a3e325 +bc1_132_8mips_4k_s 36864 737b019b60566d3c +bc3_132x68x2_8mips_64k_d 262144 eb2a1b819988722b diff --git a/tests/gpu_bind.cmake b/tests/gpu_bind.cmake new file mode 100644 index 0000000000..5ec45ec89a --- /dev/null +++ b/tests/gpu_bind.cmake @@ -0,0 +1,36 @@ +# WP3 vbind (PLAN.md WP3): Root arguments, binding and draw state. Included from CMakeLists.txt. +# +# Header checks (no device): the per-list root record and the console topologies (startup_gpu_roots_check); user +# data, table planning, raw view bounds, find_bounded, RecordHash, dispatch arithmetic (startup_gpu_user_data_check). +# Each has a --mutate negative control that must fail. +foreach(check IN ITEMS roots user_data) + add_executable(startup_gpu_${check}_check tests/startup_gpu_${check}_check.cpp) + target_include_directories(startup_gpu_${check}_check PRIVATE src) + target_compile_features(startup_gpu_${check}_check PRIVATE cxx_std_17) + add_test(NAME startup_gpu_${check} COMMAND startup_gpu_${check}_check) + add_test(NAME startup_gpu_${check}_mutate_control COMMAND startup_gpu_${check}_check --mutate) + set_tests_properties(startup_gpu_${check}_mutate_control PROPERTIES WILL_FAIL TRUE) + set_tests_properties(startup_gpu_${check} startup_gpu_${check}_mutate_control PROPERTIES TIMEOUT 30) +endforeach() + +# WARP binding checks with our own ABI shaders (tests/startup_gpu_bind.hlsl, cs_6_6, ResourceDescriptorHeap): +# startup_gpu_bind (table dword in console units, raw views from the 16 bytes below with the bias, a CBV made afresh +# in 256-byte steps) and startup_gpu_bounds (a root UAV bounded by its title buffer, null over unknown memory, cut at +# the window's end). Each has a --mutate negative control. 77: no WARP / SM 6.6 / binding tier 3. +add_executable(startup_gpu_bind_check tests/startup_gpu_bind_check.cpp) +foreach(entry IN ITEMS bind_main bounds_main) + set(header "${CMAKE_CURRENT_BINARY_DIR}/startup_gpu_bind_${entry}.h") + add_custom_command(OUTPUT "${header}" COMMAND "${DXC_EXECUTABLE}" -T cs_6_6 -E ${entry} + -Vn startup_gpu_bind_${entry} -Fh "${header}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gpu_bind.hlsl" + DEPENDS tests/startup_gpu_bind.hlsl VERBATIM) + target_sources(startup_gpu_bind_check PRIVATE "${header}") +endforeach() +target_include_directories(startup_gpu_bind_check PRIVATE src "${CMAKE_CURRENT_BINARY_DIR}") +target_compile_features(startup_gpu_bind_check PRIVATE cxx_std_17) +target_link_libraries(startup_gpu_bind_check PRIVATE d3d12 dxgi) +foreach(mode IN ITEMS bind bounds) + add_test(NAME startup_gpu_${mode} COMMAND startup_gpu_bind_check ${mode}) + add_test(NAME startup_gpu_${mode}_mutate_control COMMAND startup_gpu_bind_check ${mode} --mutate) + set_tests_properties(startup_gpu_${mode} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + set_tests_properties(startup_gpu_${mode}_mutate_control PROPERTIES WILL_FAIL TRUE SKIP_RETURN_CODE 77 TIMEOUT 60) +endforeach() diff --git a/tests/gpu_heap_tests.cmake b/tests/gpu_heap_tests.cmake new file mode 100644 index 0000000000..978086f1ab --- /dev/null +++ b/tests/gpu_heap_tests.cmake @@ -0,0 +1,69 @@ +# WP5 (rawtwins) tests of the descriptor mirror. Included from CMakeLists.txt by WP0's hook line; +# this file is WP5's own. +# The header-level layout and view rules of src/startup_stubs/gpu_heap.h. The mutated runs are +# the negative controls. +add_executable(startup_gpu_heap_layout_check tests/startup_gpu_heap_layout_check.cpp) +target_include_directories(startup_gpu_heap_layout_check PRIVATE src) +target_compile_features(startup_gpu_heap_layout_check PRIVATE cxx_std_17) +add_test(NAME startup_gpu_heap_layout COMMAND startup_gpu_heap_layout_check) +foreach(mutation probe most) + add_test(NAME startup_gpu_heap_layout_mutate_${mutation} + COMMAND startup_gpu_heap_layout_check --mutate ${mutation}) + set_tests_properties(startup_gpu_heap_layout_mutate_${mutation} PROPERTIES WILL_FAIL TRUE) +endforeach() + +# The mirror heap on a device (src/startup_stubs/gpu_heap.inl) with fixture title memory and our own SM 6.6 +# shader: twins, views, and records copied as bytes mirrored at submit. WARP: the layout at half scale (WARP takes +# no 2^22-view heap); hardware: the real one, skipped (77) on a host that takes no 2^22 views. +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/startup_gpu_heap_cs.h" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_6 -E PickMain -Vn startup_gpu_heap_cs -Fh "${CMAKE_CURRENT_BINARY_DIR}/startup_gpu_heap_cs.h" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gpu_heap.hlsl" + DEPENDS tests/startup_gpu_heap.hlsl VERBATIM) +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/startup_gpu_memory_cs.h" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_6 -E MemoryMain -Vn startup_gpu_memory_cs -Fh "${CMAKE_CURRENT_BINARY_DIR}/startup_gpu_memory_cs.h" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gpu_memory.hlsl" + DEPENDS tests/startup_gpu_memory.hlsl VERBATIM) +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/startup_gpu_memory_store_cs.h" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_6 -E StoreMain -Vn startup_gpu_memory_store_cs -Fh "${CMAKE_CURRENT_BINARY_DIR}/startup_gpu_memory_store_cs.h" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gpu_memory_store.hlsl" + DEPENDS tests/startup_gpu_memory_store.hlsl VERBATIM) +add_executable(startup_gpu_heap tests/startup_gpu_heap.cpp "${CMAKE_CURRENT_BINARY_DIR}/startup_gpu_heap_cs.h" "${CMAKE_CURRENT_BINARY_DIR}/startup_gpu_memory_cs.h" "${CMAKE_CURRENT_BINARY_DIR}/startup_gpu_memory_store_cs.h") +target_include_directories(startup_gpu_heap PRIVATE src "${CMAKE_CURRENT_BINARY_DIR}") +target_compile_features(startup_gpu_heap PRIVATE cxx_std_17) +target_link_libraries(startup_gpu_heap PRIVATE d3d12 dxgi d3dcompiler) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS twins views typed_null submit memory memory_empty memory_store packed_light material_record pixel_subresource_capture compute_texture_capture compute_volume_capture compute_sparse_volume_capture compute_priority_depth_capture ambient resident_mips small_texture_heap list_states) + add_test(NAME startup_gpu_${mode}_${backend} COMMAND startup_gpu_heap ${backend} ${mode}) + set_tests_properties(startup_gpu_${mode}_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endforeach() + +# The mirror heap through the shim (gpu_views.inl): a shader-visible title heap gets its mirror, a record the +# title copies as bytes is found at submit. The negative control verifies that a non-shader-visible heap has no mirror. +add_executable(startup_gpu_heap_shim tests/startup_gpu_heap_shim.cpp) +add_executable(startup_gpu_depth_twins tests/startup_gpu_depth_twins.cpp) +target_include_directories(startup_gpu_depth_twins PRIVATE src) +target_compile_features(startup_gpu_depth_twins PRIVATE cxx_std_17) +target_link_libraries(startup_gpu_depth_twins PRIVATE d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_gpu_depth_twins_${backend} COMMAND startup_gpu_depth_twins ${backend}) + set_tests_properties(startup_gpu_depth_twins_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) +endforeach() +target_compile_features(startup_gpu_heap_shim PRIVATE cxx_std_17) +target_link_libraries(startup_gpu_heap_shim PRIVATE d3d12_xs_shim d3d12 dxgi) +set_target_properties(startup_gpu_heap_shim PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") +add_test(NAME startup_gpu_heap_shim COMMAND startup_gpu_heap_shim) +add_test(NAME startup_gpu_heap_shim_lazy_detile COMMAND startup_gpu_heap_shim --lazy) +set_tests_properties(startup_gpu_heap_shim_lazy_detile PROPERTIES TIMEOUT 120 ENVIRONMENT + "X2W_GPU_ABI=1;X2W_D3D12_RENDER=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_GPU_LATE_TEXTURES=1;X2W_GPU_LAZY_DETILE=1;X2W_MEMORY_SRV_DETILE=1") +add_test(NAME startup_gpu_heap_shim_native_detile COMMAND startup_gpu_heap_shim --native) +set_tests_properties(startup_gpu_heap_shim_native_detile PROPERTIES TIMEOUT 120 ENVIRONMENT + "X2W_GPU_ABI=0;X2W_D3D12_RENDER=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_GPU_LATE_TEXTURES=1;X2W_GPU_LAZY_DETILE=1;X2W_MEMORY_SRV_DETILE=1") +add_test(NAME startup_gpu_heap_shim_mutate COMMAND startup_gpu_heap_shim --mutate) +set_tests_properties(startup_gpu_heap_shim startup_gpu_heap_shim_mutate PROPERTIES + TIMEOUT 120 ENVIRONMENT "X2W_GPU_ABI=1;X2W_D3D12_RENDER=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1") + +add_executable(startup_gpu_trace_request tests/startup_gpu_trace_request.cpp) +target_include_directories(startup_gpu_trace_request PRIVATE src) +target_compile_features(startup_gpu_trace_request PRIVATE cxx_std_17) +add_test(NAME startup_gpu_trace_request COMMAND startup_gpu_trace_request) diff --git a/tests/mesh_clip_distance_check.py b/tests/mesh_clip_distance_check.py new file mode 100644 index 0000000000..9aa2f72fff --- /dev/null +++ b/tests/mesh_clip_distance_check.py @@ -0,0 +1,112 @@ +"""A mesh-stage pos1 export as SV_ClipDistance0, from the pipeline's PA_CL_VS_OUT_CNTL (req_<key>.vsout). + +Hand-assembled NGG mesh program (no cache bytes): v1 = 1.0, v2 = 0; m0 = 3 vertices | 1 primitive << 12; +s_sendmsg 0x9 (GS_ALLOC_REQ); exp pos0 v1, v2, v2, v1; exp pos1 v1, v2, off, off (or v1, off, off, off) done; +exp param0; exp prim v2 done. On gfx10 the position exports are numbered in order (Mesa +src/amd/common/nir/ac_nir_prerast_utils.c ac_nir_export_position: target V_008DFC_SQ_EXP_POS + exp_num, pos0 first, +then the misc vector only when point size / edge flag / layer / viewport / shading rate is written, then the clip/cull +distance vectors 0..3 and 4..7 with write mask = the enabled distances). PA_CL_VS_OUT_CNTL (Mesa +src/amd/registers/gfx10.json) says which: VS_OUT_MISC_VEC_ENA (21) clear and VS_OUT_CCDIST0_VEC_ENA (22) set make +pos1 distances 0..3; CLIP_DIST_ENA_i [7:0], CULL_DIST_ENA_i [15:8]. The two values measured in the mesh pipelines that +export pos1 (regblob .vsregs u32 at +0xec, all 203 such programs): 0x01400101 (one distance, export mask x) and +0x01400f0f (four, mask xyzw), clip = cull in both; G.clip_vector_width lowers that as SV_ClipDistance alone. + +Checks: no PA_CL_VS_OUT_CNTL -> refused (negative control: the clip output is only emitted from the register state); +0x01400f0f with a two-channel export, cull-only, a misc vector and a second distance vector -> refused; 0x01400101 +with mask x -> float clip0 : SV_ClipDistance0, 0x01400303 with mask xy -> float2, in the mesh output struct and the +pixel input struct (identical, so the stages link), written under the lane's exec bit; dxc ms_6_5 + ps_6_0 compile +both when dxc is installed (skipped with a message otherwise). +""" +import os +import struct +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import root_blob # noqa: E402 + + +def mesh(pos1_word0, pos1_word1): + return struct.pack('<14I', + 0x7e0202f2, # v_mov_b32 v1, 1.0 + 0x7e040280, # v_mov_b32 v2, 0 + 0xb07c1003, # s_movk_i32 m0, 0x1003 + 0xbf900009, # s_sendmsg 0x9 + 0xf80000cf, 0x01020201, # exp pos0 v1, v2, v2, v1 + pos1_word0, pos1_word1, # exp pos1 ... done + 0xf800020f, 0x01020201, # exp param0 v1, v2, v2, v1 + 0xf8000941, 0x00000002, # exp prim v2 done + 0xbf810000, 0xbf810000) # s_endpgm (twice: padding) + + +MS_XY = mesh(0xf80008d3, 0x00000201) # exp pos1 v1, v2, off, off done +MS_X = mesh(0xf80008d1, 0x00000001) # exp pos1 v1, off, off, off done +PS = struct.pack('<4I', 0x7e0002f2, # v_mov_b32 v0, 1.0 + 0xf800180f, 0x00000000, # exp mrt0 v0, v0, v0, v0 done vm + 0xbf810000) + + +def refused(code, cntl, why): + try: + M.MeshPipeline(code, PS, root_blob(), vs_out_cntl=cntl).hlsl_ms() + except G.Unsupported as error: + assert why in str(error), (why, str(error)) + else: + raise AssertionError('accepted PA_CL_VS_OUT_CNTL %r' % cntl) + + +def accepted(code, cntl, decl, write): + pipe = M.MeshPipeline(code, PS, root_blob(), vs_out_cntl=cntl) + ms, ps = pipe.hlsl_ms(), pipe.hlsl_ps() + assert ' %s clip0 : SV_ClipDistance0;' % decl in ms, ms + assert ' %s clip0 : SV_ClipDistance0;' % decl in ps, ps + assert 'if (exec & 1) { %s }' % write in ms, ms + # the pixel input struct and the mesh output struct list the same fields in the same order (linkage) + def fields(text, name): + body = text.split('struct %s {' % name, 1)[1].split('};', 1)[0] + return [l.strip() for l in body.strip().splitlines()] + out_fields = fields(ms, 'MSOut') + ps_struct = next(n for n in ('PSIn', 'VSOut', 'PSInput') if 'struct %s {' % n in ps) + assert out_fields == fields(ps, ps_struct), (out_fields, fields(ps, ps_struct)) + return pipe + + +def main(): + text = [x[3] for x in G.decode(MS_XY)] + assert text[3] == 's_sendmsg 0x9' and text[5] == 'exp pos1 v1, v2, off, off done', text + assert [x[3] for x in G.decode(MS_X)][5] == 'exp pos1 v1, off, off, off done' + refused(MS_XY, None, 'pos1 without PA_CL_VS_OUT_CNTL') # negative control: no register state + refused(MS_XY, 0x01400f0f, 'PA_CL_VS_OUT_CNTL') # four distances enabled, two written + refused(MS_XY, 0x01400300, 'PA_CL_VS_OUT_CNTL') # cull distances only + refused(MS_XY, 0x01400303 | 1 << 21, 'PA_CL_VS_OUT_CNTL') # misc vector first: pos1 is not distances + refused(MS_XY, 0x01400303 | 1 << 23, 'PA_CL_VS_OUT_CNTL') # a second distance vector + accepted(MS_X, 0x01400101, 'float', 'o.clip0 = F(v1);') + accepted(MS_XY, 0x01400303, 'float2', 'o.clip0 = float2(F(v1), F(v2));') + compiled = 'dxc not found' + if os.path.isfile(M.DXC): + with tempfile.TemporaryDirectory() as d: + for key, (code, cntl) in enumerate(((MS_X, 0x01400101), (MS_XY, 0x01400303))): + r = M.translate_to(d, key, code, PS, root_blob(), vs_out_cntl=cntl) + assert r == 'ok', r + r = M.translate_to(d, 9, MS_XY, PS, root_blob()) + assert r.startswith('unsupported:') and 'pos1' in r, r + # a request: req_<key>.{a,b,root} and the optional .vsout beside it + base = os.path.join(d, 'req_%016x' % 5) + for ext, data in (('.a', PS), ('.b', MS_XY), ('.root', root_blob())): + open(base + ext, 'wb').write(data) + r = M.translate_request(d, 5) + assert r.startswith('unsupported:') and 'pos1' in r, r + open(base + '.vsout', 'w', newline='\n').write('pa_cl_vs_out_cntl 1 01400303\n') + r = M.translate_request(d, 5) + assert r == 'ok', r + assert 'SV_ClipDistance0' in open(os.path.join(d, '%016x.ms.hlsl' % 5)).read() + compiled = 'dxc ms_6_5 + ps_6_0 ok' + print('mesh clip distance: pos1 refused without PA_CL_VS_OUT_CNTL; 0x01400101 -> float, 0x01400303 -> float2 ' + 'SV_ClipDistance0 in both stage structs; 4 bad states refused; %s' % compiled) + + +if __name__ == '__main__': + main() diff --git a/tests/mesh_loop_state_check.py b/tests/mesh_loop_state_check.py new file mode 100644 index 0000000000..41345b4945 --- /dev/null +++ b/tests/mesh_loop_state_check.py @@ -0,0 +1,168 @@ +"""Loop-carried scalar state in the mesh-stage translator (mesh2hlsl MeshStage.loop_one / MeshPipeline.mesh_stage). + +Hand-assembled NGG mesh programs (no cache bytes), each a uniform scalar loop (s_cbranch_scc1 back edge, RDNA 2 ISA: +SCC from s_cmp_lt_u32, the branch taken when SCC = 1): + + counter: s0 = 0; L: s0 += 1; s_cmp_lt_u32 s0, 3; s_cbranch_scc1 L; v1 = float(s0); exp pos0 v1, ... + midentry: s2 = 0; s1 = 5; s_branch E; H: s1 = s4; E: s4 = s1 + 1; s2 += 1; s_cmp_lt_u32 s2, 3; s_cbranch_scc1 H; + v1 = float(s4) (H is reached only by the back edge: the loop is entered in its body) + +The console computes s0 = 3 and s4 = 8. A translation that keeps, at the loop head, the state of the instruction +above it folds the constant before the loop into the body (`s0 = 0x00000000u + 0x00000001u`: the HLSL loop never +ends and stops at its guard). Checks: the loop counters are read as variables in the loop body, and the program +exports the right value when the emitted body is evaluated by a small interpreter for the statement forms it +uses. + + taint: v1 = 0; s0 = 0; H: v_cmp_lt_u32 vcc, 0, v1; s_cbranch_vccz +1; s_nop; v1 = v5; s0 += 1; s_cmp_lt_u32 s0, 3; + s_cbranch_scc1 H (v1 is uniform on the entry edge and the vertex id on the back edge) + +The vccz branch reads a vcc that differs between lanes from the second pass on: the translation must refuse it +("lane-dependent vcc"), which it does only when the head's lane taint joins the back edge. (Since e1a2ad2a, the +base's loop-head rule alone keeps counter / midentry right; taint is what still needs the join.) +Negative control: with X2W_MESH_LOOP_JOIN=0 (the old linear state) the same checks FAIL (run in a child). +""" +import os +import re +import struct +import subprocess +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import root_blob # noqa: E402 + +TAIL = (0x7e020c00, # v_cvt_f32_u32 v1, s<src> + 0x7e040280, # v_mov_b32 v2, 0 + 0xb07c1003, # s_movk_i32 m0, 0x1003 + 0xbf900009, # s_sendmsg 0x9 + 0xf80008cf, 0x02020201, # exp pos0 v1, v2, v2, v2 done + 0xf8000941, 0x00000002, # exp prim v2 done + 0xbf810000) # s_endpgm + + +def program(words, src): + tail = list(TAIL) + tail[0] = 0x7e020c00 | src + return struct.pack('<%dI' % (len(words) + len(tail)), *(list(words) + tail)) + + +COUNTER = program([0xbe800380, # 0x00 s_mov_b32 s0, 0 + 0x80008100, # 0x04 s_add_u32 s0, s0, 1 + 0xbf0a8300, # 0x08 s_cmp_lt_u32 s0, 3 + 0xbf85fffd], # 0x0c s_cbranch_scc1 0x04 + 0) +MIDENTRY = program([0xbe820380, # 0x00 s_mov_b32 s2, 0 + 0xbe810385, # 0x04 s_mov_b32 s1, 5 + 0xbf820001, # 0x08 s_branch 0x10 + 0xbe810304, # 0x0c s_mov_b32 s1, s4 + 0x80048101, # 0x10 s_add_u32 s4, s1, 1 + 0x80028102, # 0x14 s_add_u32 s2, s2, 1 + 0xbf0a8302, # 0x18 s_cmp_lt_u32 s2, 3 + 0xbf85fffb], # 0x1c s_cbranch_scc1 0x0c + 4) +TAINT = program([0x7e020280, # 0x00 v_mov_b32 v1, 0 + 0xbe800380, # 0x04 s_mov_b32 s0, 0 + 0x7d820280, # 0x08 v_cmp_lt_u32 vcc, 0, v1 + 0xbf860001, # 0x0c s_cbranch_vccz 0x14 + 0xbf800000, # 0x10 s_nop 0 + 0x7e020305, # 0x14 v_mov_b32 v1, v5 + 0x80008100, # 0x18 s_add_u32 s0, s0, 1 + 0xbf0a8300, # 0x1c s_cmp_lt_u32 s0, 3 + 0xbf85fff9], # 0x20 s_cbranch_scc1 0x08 + 0) +TEXT = { + 'counter': ['s_mov_b32 s0, 0', 's_add_u32 s0, s0, 1', 's_cmp_lt_u32 s0, 3', 's_cbranch_scc1 label_0x4'], + 'midentry': ['s_mov_b32 s2, 0', 's_mov_b32 s1, 5', 's_branch label_0x10', 's_mov_b32 s1, s4', + 's_add_u32 s4, s1, 1', 's_add_u32 s2, s2, 1', 's_cmp_lt_u32 s2, 3', 's_cbranch_scc1 label_0xc'], + 'taint': ['v_mov_b32_e32 v1, 0', 's_mov_b32 s0, 0', 'v_cmp_lt_u32_e32 vcc_lo, 0, v1', 's_cbranch_vccz label_0x14', + 's_nop 0', 'v_mov_b32_e32 v1, v5', 's_add_u32 s0, s0, 1', 's_cmp_lt_u32 s0, 3', 's_cbranch_scc1 label_0x8'], +} + + +def run_body(hlsl): + """Evaluates the scalar statements of the emitted pc loop (uint assignments, scc compares, pc dispatch) for + one thread and returns the exported position x. Only the forms these programs produce are understood.""" + lines = [l.strip() for l in hlsl.split('uint pc = 0;', 1)[1].splitlines()] + blocks, cur = {}, None + for l in lines: + if l.startswith('GroupMemoryBarrierWithGroupSync'): + break + m = re.match(r'(?:else )?if \(pc == (\d+)\) \{$', l) + if m: + cur = int(m.group(1)) + blocks[cur] = [] + elif l.startswith('[loop] for ('): # a bounded pc loop around a loop's blocks (the dispatch below repeats) + continue + elif cur is not None and l != '}': + blocks[cur].append(l) + env = {'pc': 0, 'scc': 0, 'exec': 1} + + def ev(expr): + e = re.sub(r'0x([0-9a-f]+)u', lambda mm: str(int(mm.group(1), 16)), expr) + e = re.sub(r'\b(\d+)u\b', r'\1', e) + e = e.replace('U(float(', '(float(').replace('F(', '(') + e = re.sub(r'\((scc)\) \? (\d+) : (\d+)', r'(\2 if \1 else \3)', e) + e = e.replace('&&', ' and ').replace('||', ' or ') + return eval(e, {'float': float}, env) + for _ in range(1000): + pc = env['pc'] + if pc >= 0xffff or pc not in blocks: + break + for stmt in blocks[pc]: + for part in [p.strip() for p in stmt.split(';') if p.strip()]: + m = re.match(r'if \(exec & 1\) \{ o\.pos = float4\((.*?), .*$', part) + if m: + env['posx'] = ev(m.group(1)) + continue + if part.startswith(('if (exec & 1) { x2w_prim', 'if (exec & 1) x2w_alloc', '}')): + continue + m = re.match(r'(\w+) = (.*)$', part) + assert m, 'statement form %r' % part + value = ev(m.group(2)) + env[m.group(1)] = (int(value) & 0xffffffff) if isinstance(value, (int, bool)) else value + else: + raise AssertionError('the translated loop does not end') + return env.get('posx') + + +def check(): + # A loop entered from its middle. The forward jump skips an alignment + # NOP before the head; its only real predecessor is the back edge. + padded = MIDENTRY[:8] + struct.pack('<II', 0xbf820002, 0xbf800000) + MIDENTRY[12:] + pipeline = M.MeshPipeline(padded, None, root_blob()) + assert run_body(pipeline.hlsl_ms()) == 8.0 + if M.LOOP_JOIN: + assert not pipeline.vs._loop_entry[0x10] + for name, code, want, counter in (('counter', COUNTER, 3.0, 's0 = s0 + 0x00000001u;'), + ('midentry', MIDENTRY, 8.0, 's2 = s2 + 0x00000001u;')): + text = [x[3] for x in G.decode(code)][:len(TEXT[name])] + assert text == TEXT[name], (name, text) + hlsl = M.MeshPipeline(code, None, root_blob()).hlsl_ms() + assert counter in hlsl, (name, 'loop counter folded', [l for l in hlsl.splitlines() if ' s0 =' in l or ' s2 =' in l]) + got = run_body(hlsl) + assert got == want, (name, got, want) + text = [x[3] for x in G.decode(TAINT)][:len(TEXT['taint'])] + assert text == TEXT['taint'], ('taint', text) + try: + M.MeshPipeline(TAINT, None, root_blob()).hlsl_ms() + raise AssertionError('taint: vccz on a vcc that is lane-dependent through the back edge was translated') + except G.Unsupported as e: + assert 'lane-dependent vcc' in str(e), ('taint', str(e)) + return 'counter -> 3.0, mid-body entry -> 8.0, back-edge taint refused' + + +def main(): + if os.environ.get('X2W_MESH_LOOP_JOIN') == '0': # child of the negative control + check() + return + summary = check() + env = dict(os.environ, X2W_MESH_LOOP_JOIN='0') + r = subprocess.run([sys.executable, '-B', os.path.abspath(__file__)], env=env, capture_output=True, text=True) + assert r.returncode != 0 and 'AssertionError' in r.stderr, ('negative control passed', r.stdout, r.stderr) + print('mesh loop state: %s; X2W_MESH_LOOP_JOIN=0 fails (%s)' % (summary, r.stderr.strip().splitlines()[-1][:80])) + + +if __name__ == '__main__': + main() diff --git a/tests/mesh_pc_table_check.py b/tests/mesh_pc_table_check.py new file mode 100644 index 0000000000..6bbebd87e0 --- /dev/null +++ b/tests/mesh_pc_table_check.py @@ -0,0 +1,41 @@ +"""A source-built mesh reads an embedded four-word position table through GETPC.""" +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import mesh2hlsl as M +from mesh_loop_state_check import TAIL, root_blob + + +def stage(declared_bytes, contents): + # Assemble the low/high address in s[8:9], the byte size in s10, and the + # raw byte-addressed buffer control word in s11. v5 selects the byte offset. + words = [0xbe881f00, # s_getpc_b64 s[8:9] + 0x8008ff08, 0, # s_add_u32 s8, s8, pool - 4 + 0xb00a0000 | declared_bytes, # s_movk_i32 s10, declared_bytes + 0xbe8b03ff, 0x31016fac, # s_mov_b32 s11, raw buffer control + 0xe0301000, 0x80020105, # buffer_load_dword v1, v5, s[8:11], 0 offen + *TAIL[1:]] + words[2] = 4 * len(words) - 4 + words.extend(contents) + return M.MeshPipeline(struct.pack('<%dI' % len(words), *words), None, root_blob()) + + +if __name__ == '__main__': + contents = (0x3f800000, 0x40000000, 0x40400000, 0x40800000) + pipe = stage(16, contents) + hlsl = pipe.hlsl_ms() + (offset, size), = pipe.vs.literal_tables + name = pipe.vs.literal_tables[(offset, size)] + assert size == 16 + assert '%s[4] = {0x3f800000u, 0x40000000u, 0x40400000u, 0x40800000u}' % name in hlsl + assert 'a = v5 >> 2u;' in hlsl + assert '(a < 4u ? %s[min(a, 3u) + 0u] : 0u)' % name in hlsl + try: + stage(20, contents) + except M.Unsupported as e: + assert 'incomplete PC-relative raw buffer' in str(e), e + else: + raise AssertionError('accepted a literal table beyond the supplied program') + print('Embedded four-word position table translated; truncated table refused') diff --git a/tests/mesh_perlane_loop_check.py b/tests/mesh_perlane_loop_check.py new file mode 100644 index 0000000000..e49e9b51a9 --- /dev/null +++ b/tests/mesh_perlane_loop_check.py @@ -0,0 +1,109 @@ +"""Per-lane loops in the mesh-stage translator (mesh2hlsl MeshStage.perlane_loop). + +The compiler keeps the lanes that still loop in a mask M and loops while some lane does (SCC = M != 0): + + v_and_b32 v6, 3, v5 (each lane's own trip count - 1) + v_mov_b32 v1, 0 + s_mov_b64 s[6:7], exec; s_mov_b64 s[8:9], exec; s_mov_b32 s4, 0 + H: s_mov_b64 exec, s[8:9] (the lanes still looping) + v_add_f32 v1, 1.0, v1 + v_cmp_eq_u32 vcc, s4, v6 (this lane is done after this iteration) + s_add_u32 s4, s4, 1 + s_and_b64 exec, vcc, exec (exec = the lanes that are done) + s_andn2_b64 s[8:9], s[8:9], exec (they leave M; SCC = some lane remains) + s_cbranch_scc1 H + s_mov_b64 exec, s[6:7] + exp pos0 v1, ... + +On the console each lane runs (v5 & 3) + 1 iterations of its vector instructions (the wave runs the most), so it +exports float((v5 & 3) + 1). Hand-assembled programs (no cache bytes); RDNA 2 ISA encodings. Checks: + full every lane on: lanes 0..7 and 127 export float((v5 & 3) + 1) + partial exec narrowed first (v_cmpx_ne_u32 0, v5 & 3): those lanes the same, the others nothing + refused s4 read after the loop (the hardware leaves the wave's last count, a thread its own), an s_barrier + in the loop, no exec restore after it, an SCC not from `s_andn2_b64 M, M, exec` (s_xor) +and dxc ms_6_5 + ps_6_0 compile the full program. The emitted code is evaluated per lane (mesh_waterfall_check's +interpreter). Negative control: with X2W_MESH_PERLANE_LOOPS=0 the same checks FAIL (run in a child): the loop +is refused as before. +""" +import os +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import root_blob # noqa: E402 +from mesh_waterfall_check import run_lane, TAIL, PS, NARROW, words, refused # noqa: E402 + +PRE = [0x360c0a83, # v_and_b32 v6, 3, v5 + 0x7e020280, # v_mov_b32 v1, 0 + 0xbe86047e, # s_mov_b64 s[6:7], exec + 0xbe88047e, # s_mov_b64 s[8:9], exec + 0xbe840380] # s_mov_b32 s4, 0 +BODY = [0xbefe0408, # H: s_mov_b64 exec, s[8:9] + 0x060202f2, # v_add_f32 v1, 1.0, v1 + 0x7d840c04, # v_cmp_eq_u32 vcc, s4, v6 + 0x80048104, # s_add_u32 s4, s4, 1 + 0x87fe7e6a] # s_and_b64 exec, vcc, exec +EXIT = 0x8a887e08 # s_andn2_b64 s[8:9], s[8:9], exec +BACK = 0xbf85fff9 # s_cbranch_scc1 H +RESTORE = 0xbefe0406 # s_mov_b64 exec, s[6:7] + +FULL = words(PRE, BODY, [EXIT, BACK, RESTORE], TAIL) +PARTIAL = words(NARROW, PRE, BODY, [EXIT, BACK, RESTORE], TAIL) +LIVE_AFTER = words(PRE, BODY, [EXIT, BACK, RESTORE, 0x7e020c04], TAIL) # v_cvt_f32_u32 v1, s4 after it +BARRIER = words(PRE, BODY[:1], [0xbf8a0000], BODY[1:], [EXIT, 0xbf85fff8, RESTORE], TAIL) +NO_RESTORE = words(PRE, BODY, [EXIT, BACK, 0xbf800000], TAIL) # s_nop 0 in place of the restore +XOR = words(PRE, BODY, [0x89887e08, BACK, RESTORE], TAIL) # s_xor_b64 s[8:9], s[8:9], exec +TEXT = ['v_and_b32_e32 v6, 3, v5', 'v_mov_b32_e32 v1, 0', 's_mov_b64 s[6:7], exec', 's_mov_b64 s[8:9], exec', + 's_mov_b32 s4, 0', 's_mov_b64 exec, s[8:9]', 'v_add_f32_e32 v1, 1.0, v1', 'v_cmp_eq_u32_e32 vcc_lo, s4, v6', + 's_add_u32 s4, s4, 1', 's_and_b64 exec, vcc, exec', 's_andn2_b64 s[8:9], s[8:9], exec', + 's_cbranch_scc1 label_0x14', 's_mov_b64 exec, s[6:7]'] + + +def hlsl_of(code): + return M.MeshPipeline(code, None, root_blob()).hlsl_ms() + + +def check(): + assert [x[3] for x in G.decode(FULL)][:len(TEXT)] == TEXT, [x[3] for x in G.decode(FULL)] + full = hlsl_of(FULL) + for v5 in list(range(8)) + [127]: + got = run_lane(full, v5) + assert got == float((v5 & 3) + 1), ('full', v5, got) + partial = hlsl_of(PARTIAL) + for v5 in list(range(8)) + [64, 127]: + got = run_lane(partial, v5) + want = None if v5 % 4 == 0 else float((v5 & 3) + 1) + assert got == want, ('partial', v5, got, want) + refused(LIVE_AFTER, 's4 written in it is live after it') + refused(BARRIER, 's_barrier') + refused(NO_RESTORE, 'no s_mov_b64 exec restore') + refused(XOR, 'SCC not from the remaining-lanes mask') + compiled = 'dxc not found' + if os.path.isfile(M.DXC): + with tempfile.TemporaryDirectory() as d: + r = M.translate_to(d, 1, FULL, PS, root_blob()) + assert r == 'ok', r + compiled = 'dxc ms_6_5 + ps_6_0 ok' + return compiled + + +def main(): + if os.environ.get('X2W_MESH_PERLANE_LOOPS') == '0': # child of the negative control + check() + return + compiled = check() + env = dict(os.environ, X2W_MESH_PERLANE_LOOPS='0') + r = subprocess.run([sys.executable, '-B', os.path.abspath(__file__)], env=env, capture_output=True, text=True) + assert r.returncode != 0 and 'Unsupported' in r.stderr, ('negative control passed', r.stdout, r.stderr) + print('mesh per-lane loop: lanes 0..7/127 (full) and v5 %% 4 != 0 (partial) export float((v5 & 3) + 1); ' + 'live-after, barrier, no-restore and xor refused; %s; X2W_MESH_PERLANE_LOOPS=0 fails (%s)' + % (compiled, r.stderr.strip().splitlines()[-1][:90])) + + +if __name__ == '__main__': + main() diff --git a/tests/mesh_waterfall_check.py b/tests/mesh_waterfall_check.py new file mode 100644 index 0000000000..0d825dd59c --- /dev/null +++ b/tests/mesh_waterfall_check.py @@ -0,0 +1,177 @@ +"""Waterfall loops in the mesh-stage translator (mesh2hlsl MeshStage.waterfalls / waterfall_step). + +The compiler's loop for a value that must be uniform but differs between lanes (LLVM AMDGPU +SIInstrInfo emitLoadScalarOpsFromVGPRLoop): + + s_mov_b64 s[6:7], exec; s_mov_b64 s[8:9], exec + H: v_readfirstlane_b32 s4, v5 (the first remaining lane's value) + v_cmpx_eq_u32 s4, v5 (exec = the remaining lanes holding it) + v_cvt_f32_u32 v1, s4 (the body: uses s4 as a uniform value) + s_andn2_wrexec_b64 s[8:9], s[8:9] (the lanes done leave; SCC = some lane remains) + s_cbranch_scc1 H + s_mov_b64 exec, s[6:7] + exp pos0 v1, ... + +On the console each lane active at H makes exactly one pass, with s4 = its own v5 (v5 = the vertex id, different in +every lane), so it exports float(v5). Hand-assembled programs (no cache bytes); RDNA 2 ISA encodings. Checks: + full every lane on: lanes 0, 1, 37, 127 export float(v5) + partial exec narrowed first (v_cmpx_ne_u32 0, v5 & 3): lanes with v5 % 4 != 0 export float(v5), the + others nothing (every wave keeps active lanes: s_sendmsg is guarded by exec here) + refused s4 read after the loop (the hardware leaves the last pass's value), no exec restore after the loop, + an s_barrier in the body +and dxc ms_6_5 + ps_6_0 compile the full program. The emitted body is evaluated per lane by a small interpreter +for the statement forms it uses. Negative control: with X2W_MESH_WATERFALL=0 the same checks FAIL (run in a +child): the loops are refused as before (here at the lane-mask SCC publish inside the loop). +""" +import os +import re +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import root_blob # noqa: E402 + +NARROW = [0x360c0a83, # v_and_b32 v6, 3, v5 + 0x7daa0c80] # v_cmpx_ne_u32_e32 0, v6 (every fourth lane off, in every wave) +LOOP = [0xbe86047e, # s_mov_b64 s[6:7], exec + 0xbe88047e, # s_mov_b64 s[8:9], exec + 0x7e080505, # H: v_readfirstlane_b32 s4, v5 + 0x7da40a04, # v_cmpx_eq_u32_e32 s4, v5 + 0x7e020c04, # v_cvt_f32_u32_e32 v1, s4 + 0xbe883a08, # s_andn2_wrexec_b64 s[8:9], s[8:9] + 0xbf85fffb, # s_cbranch_scc1 H + 0xbefe0406] # s_mov_b64 exec, s[6:7] +TAIL = [0x7e040280, # v_mov_b32 v2, 0 + 0xb07c1003, # s_movk_i32 m0, 0x1003 + 0xbf900009, # s_sendmsg 0x9 + 0xf80008cf, 0x02020201, # exp pos0 v1, v2, v2, v2 done + 0xf8000941, 0x00000002, # exp prim v2 done + 0xbf810000] # s_endpgm +PS = struct.pack('<4I', 0x7e0002f2, 0xf800180f, 0x00000000, 0xbf810000) # v_mov v0, 1.0; exp mrt0; s_endpgm + + +def words(*parts): + w = [x for p in parts for x in p] + return struct.pack('<%dI' % len(w), *w) + + +FULL = words(LOOP, TAIL) +PARTIAL = words(NARROW, LOOP, TAIL) +LIVE_AFTER = words(LOOP, [0x7e020c04], TAIL) # v_cvt_f32_u32 v1, s4 after the restore +NO_RESTORE = words(LOOP[:-1], [0xbf800000], TAIL) # s_nop 0 in place of the restore +BARRIER = words(LOOP[:4], [0xbf8a0000], LOOP[4:6], [0xbf85fffa], LOOP[7:], TAIL) # s_barrier in the body +TEXT = ['s_mov_b64 s[6:7], exec', 's_mov_b64 s[8:9], exec', 'v_readfirstlane_b32 s4, v5', + 'v_cmpx_eq_u32_e32 s4, v5', 'v_cvt_f32_u32_e32 v1, s4', 's_andn2_wrexec_b64 s[8:9], s[8:9]', + 's_cbranch_scc1 label_0x8', 's_mov_b64 exec, s[6:7]'] + + +def run_lane(hlsl, v5): + """Evaluates the emitted pc loop for one thread whose v5 (vertex id) is v5; returns the exported position x, + or None when the thread exports nothing. Only the statement forms these programs produce are understood.""" + lines = [l.strip() for l in hlsl.split('uint pc = 0;', 1)[1].splitlines()] + blocks, cur = {}, None + for l in lines: + if l.startswith('GroupMemoryBarrierWithGroupSync'): + break + m = re.match(r'(?:else )?if \(pc == (\d+)\) \{$', l) + if m: + cur = int(m.group(1)) + blocks[cur] = [] + elif l.startswith('[loop] for ('): # a bounded pc loop around a loop's blocks (the dispatch below repeats) + continue + elif cur is not None and l != '}': + blocks[cur].append(l) + env = {'pc': 0, 'scc': 0, 'exec': 1, 'v5': v5} + + def ev(expr): + e = re.sub(r'0x([0-9a-f]+)u', lambda mm: str(int(mm.group(1), 16)), expr) + e = re.sub(r'\b(\d+)u\b', r'\1', e) + e = re.sub(r'\b[UF]\(', '(', e) + e = re.sub(r'\(\((.*?)\) \? (\d+) : (\d+)\)', r'(\2 if (\1) else \3)', e) + e = re.sub(r'^\((\w+)\) \? (\d+) : (\d+)$', r'(\2 if \1 else \3)', e) + e = re.sub(r'~(\w+)', r'(~\1 & 0xffffffff)', e) + e = e.replace('&&', ' and ').replace('||', ' or ').replace('false', '0').replace('true', '1') + return eval(e, {'float': float}, env) + posx = None + for _ in range(100): + pc = env['pc'] + if pc >= 0xffff or pc not in blocks: + break + for stmt in blocks[pc]: + guarded = stmt.startswith('if (exec & 1) ') + body = stmt[len('if (exec & 1) '):] if guarded else stmt + if guarded and not (env['exec'] & 1): + continue + body = body.strip('{} ') + for part in [p.strip() for p in body.split(';') if p.strip()]: + m = re.match(r'o\.pos = float4\((.*?), .*$', part) + if m: + posx = ev(m.group(1)) + continue + if part.startswith(('x2w_prim', 'x2w_alloc')): + continue + m = re.match(r'(\w+) = (.*)$', part) + assert m, 'statement form %r' % part + value = ev(m.group(2)) + env[m.group(1)] = (int(value) & 0xffffffff) if isinstance(value, (int, bool)) else value + else: + raise AssertionError('the translated program does not end') + return posx + + +def hlsl_of(code): + return M.MeshPipeline(code, None, root_blob()).hlsl_ms() + + +def refused(code, why): + try: + hlsl_of(code) + except G.Unsupported as e: + assert why in str(e), (why, str(e)) + return + raise AssertionError('not refused: %s' % why) + + +def check(): + assert [x[3] for x in G.decode(FULL)][:len(TEXT)] == TEXT, [x[3] for x in G.decode(FULL)] + full = hlsl_of(FULL) + for v5 in (0, 1, 37, 127): + got = run_lane(full, v5) + assert got == float(v5), ('full', v5, got) + partial = hlsl_of(PARTIAL) + for v5 in (0, 1, 2, 3, 4, 64, 65, 127): + got = run_lane(partial, v5) + want = None if v5 % 4 == 0 else float(v5) + assert got == want, ('partial', v5, got, want) + refused(LIVE_AFTER, 's4 written in it is live after it') + refused(NO_RESTORE, 'no s_mov_b64 exec restore') + refused(BARRIER, 's_barrier') + compiled = 'dxc not found' + if os.path.isfile(M.DXC): + with tempfile.TemporaryDirectory() as d: + r = M.translate_to(d, 1, FULL, PS, root_blob()) + assert r == 'ok', r + compiled = 'dxc ms_6_5 + ps_6_0 ok' + return compiled + + +def main(): + if os.environ.get('X2W_MESH_WATERFALL') == '0': # child of the negative control + check() + return + compiled = check() + env = dict(os.environ, X2W_MESH_WATERFALL='0') + r = subprocess.run([sys.executable, '-B', os.path.abspath(__file__)], env=env, capture_output=True, text=True) + assert r.returncode != 0 and 'Unsupported' in r.stderr, ('negative control passed', r.stdout, r.stderr) + print('mesh waterfall: one pass per lane, full exec lanes 0/1/37/127 and partial exec lanes v5 %% 4 != 0 export ' + 'float(v5); live-after, no-restore and barrier refused; %s; X2W_MESH_WATERFALL=0 fails (%s)' + % (compiled, r.stderr.strip().splitlines()[-1][:90])) + + +if __name__ == '__main__': + main() diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index d3973cdd18..b525bc7e73 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1242,10 +1242,10 @@ OperationResult run_startup_range_provenance(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } -template<bool Swapped> +template<bool Swapped, int Words = 0> OperationResult run_startup_sampler_x(const OperationContext& ctx) { - return skip_if_false(check_startup_sampler_x(ctx.device, Swapped), + return skip_if_false(check_startup_sampler_x(ctx.device, Swapped, Words), "skip: R32_FLOAT does not report filtered sampling with mips"); } @@ -1752,6 +1752,8 @@ const OperationSpec kOperations[] = { {"--descriptor-heap-paging-swapped", 3, 3, nullptr, kGateSm60BufferOps, run_descriptor_heap_paging<true>}, {"--startup-sampler-x", 3, 3, nullptr, kGateSm60BufferOps, run_startup_sampler_x<false>}, {"--startup-sampler-x-swapped", 3, 3, nullptr, kGateSm60BufferOps, run_startup_sampler_x<true>}, + {"--startup-sampler-x-words", 3, 3, nullptr, kGateSm60BufferOps, run_startup_sampler_x<false, 1>}, + {"--startup-sampler-x-words-dropped", 3, 3, nullptr, kGateSm60BufferOps, run_startup_sampler_x<false, 2>}, {"--startup-sampler-lod", 3, 3, nullptr, kNoGate, run_startup_sampler_lod<false>}, {"--startup-sampler-lod-dropped", 3, 3, nullptr, kNoGate, run_startup_sampler_lod<true>}, {"--startup-cb-blend", 3, 3, nullptr, kNoGate, run_startup_cb_blend<false>}, diff --git a/tests/section_window_ops_check.cpp b/tests/section_window_ops_check.cpp new file mode 100644 index 0000000000..23297c37ae --- /dev/null +++ b/tests/section_window_ops_check.cpp @@ -0,0 +1,295 @@ +#include <d3d12.h> +#include <d3d12sdklayers.h> +#include <d3dcompiler.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <string> + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT64 page = 65536, bytes = 4 * page; + +void drain(ID3D12Device* device) +{ + ComPtr<ID3D12InfoQueue> queue; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&queue)))) return; + for (UINT64 i = 0; i < queue->GetNumStoredMessages() && i < 16; ++i) { + SIZE_T size = 0; + queue->GetMessage(i, nullptr, &size); + std::string storage(size, '\0'); + auto* m = reinterpret_cast<D3D12_MESSAGE*>(storage.data()); + if (SUCCEEDED(queue->GetMessage(i, m, &size)) && m->Severity <= D3D12_MESSAGE_SEVERITY_WARNING) + std::printf("debug sev=%d id=%d %s\n", m->Severity, m->ID, m->pDescription); + } + queue->ClearStoredMessages(); +} +D3D12_RESOURCE_DESC buffer_desc(UINT64 width, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) +{ + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = width; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + return d; +} +ComPtr<ID3D12Resource> committed(ID3D12Device* device, D3D12_HEAP_TYPE type, UINT64 width, D3D12_RESOURCE_STATES state, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) +{ + const D3D12_HEAP_PROPERTIES heap{type}; + const D3D12_RESOURCE_DESC desc = buffer_desc(width, flags); + ComPtr<ID3D12Resource> r; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&r)))) return nullptr; + return r; +} +const char* const shader = R"( +RWByteAddressBuffer u : register(u0); +ByteAddressBuffer t : register(t0); +cbuffer C : register(b0) { uint4 c; }; +[numthreads(1, 1, 1)] void main() { u.Store(0, t.Load(0) + c.x + 1); } +)"; +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 3) return 2; + const bool warp = std::strcmp(argv[1], "warp") == 0; + const std::string op = argv[2]; + const bool debug = !(argc > 3 && std::strcmp(argv[3], "nodebug") == 0); + if (debug) { + ComPtr<ID3D12Debug> d; + if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&d)))) d->EnableDebugLayer(); + } + ComPtr<IDXGIFactory6> factory; + ComPtr<IDXGIAdapter1> adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77; + if (warp ? FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) + : FAILED(factory->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&adapter)))) + return 77; + ComPtr<ID3D12Device3> device; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) return 77; + std::printf("op %s on %s, debug layer %s\n", op.c_str(), argv[1], debug ? "on" : "off"); + + // The window: as section_va makes it. + const HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, static_cast<DWORD>(bytes), nullptr); + auto* view = section ? static_cast<unsigned*>(MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes)) : nullptr; + if (!view) return 3; + view[0] = 41; + ComPtr<ID3D12Heap> heap; + if (FAILED(device->OpenExistingHeapFromFileMapping(section, IID_PPV_ARGS(&heap)))) return 4; + std::printf("heap flags 0x%x\n", heap->GetDesc().Flags); + const D3D12_RESOURCE_DESC wdesc = + buffer_desc(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER); + ComPtr<ID3D12Resource> window; + if (FAILED(device->CreatePlacedResource(heap.Get(), 0, &wdesc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&window)))) return 5; + + ComPtr<ID3D12CommandQueue> queue; + const D3D12_COMMAND_QUEUE_DESC qdesc{}; + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + if (FAILED(device->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&queue))) || + 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))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) + return 6; + auto plain = committed(device.Get(), D3D12_HEAP_TYPE_DEFAULT, bytes, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + if (!plain) return 7; + + // A compute pipeline: root CBV b0, SRV t0, UAV u0, or one table (u0, t0) for the table ops. + const bool table = op == "table_uav" || op == "table_srv"; + ComPtr<ID3DBlob> cs, error, sig; + if (FAILED(D3DCompile(shader, std::strlen(shader), nullptr, nullptr, nullptr, "main", "cs_5_1", 0, 0, &cs, &error))) return 8; + D3D12_DESCRIPTOR_RANGE ranges[2] = {{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0}, {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 1}}; + D3D12_ROOT_PARAMETER params[3]{}; + UINT nparams = 0; + params[nparams].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + params[nparams++].Descriptor = {0, 0}; + if (table) { + params[nparams].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[nparams++].DescriptorTable = {2, ranges}; + } else { + params[nparams].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + params[nparams++].Descriptor = {0, 0}; + params[nparams].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[nparams++].Descriptor = {0, 0}; + } + const D3D12_ROOT_SIGNATURE_DESC rsd{nparams, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3D12RootSignature> root; + if (FAILED(D3D12SerializeRootSignature(&rsd, D3D_ROOT_SIGNATURE_VERSION_1, &sig, &error)) || + FAILED(device->CreateRootSignature(0, sig->GetBufferPointer(), sig->GetBufferSize(), IID_PPV_ARGS(&root)))) + return 9; + D3D12_COMPUTE_PIPELINE_STATE_DESC pdesc{}; + pdesc.pRootSignature = root.Get(); + pdesc.CS = {cs->GetBufferPointer(), cs->GetBufferSize()}; + ComPtr<ID3D12PipelineState> pso; + if (FAILED(device->CreateComputePipelineState(&pdesc, IID_PPV_ARGS(&pso)))) return 10; + ComPtr<ID3D12DescriptorHeap> gpu_heap, cpu_heap; + const D3D12_DESCRIPTOR_HEAP_DESC hv{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + const D3D12_DESCRIPTOR_HEAP_DESC hc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + if (FAILED(device->CreateDescriptorHeap(&hv, IID_PPV_ARGS(&gpu_heap))) || FAILED(device->CreateDescriptorHeap(&hc, IID_PPV_ARGS(&cpu_heap)))) + return 11; + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + auto cpu_at = [&](ID3D12DescriptorHeap* h, UINT i) { auto c = h->GetCPUDescriptorHandleForHeapStart(); c.ptr += i * step; return c; }; + auto gpu_at = [&](UINT i) { auto g = gpu_heap->GetGPUDescriptorHandleForHeapStart(); g.ptr += std::uint64_t{i} * step; return g; }; + + ID3D12Resource* uav_target = op == "root_uav" || op == "table_uav" ? window.Get() : plain.Get(); + ID3D12Resource* srv_source = op == "root_srv" || op == "table_srv" ? window.Get() : plain.Get(); + ID3D12Resource* cbv_source = op == "root_cbv" ? window.Get() : plain.Get(); + if (op == "copy_in") { + list->CopyBufferRegion(window.Get(), 0, plain.Get(), 0, page); + } else if (op == "copy_out") { + list->CopyBufferRegion(plain.Get(), 0, window.Get(), 0, page); + } else if (op == "clear_uav") { + D3D12_UNORDERED_ACCESS_VIEW_DESC u{}; + u.Format = DXGI_FORMAT_R32_UINT; + u.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + u.Buffer.NumElements = static_cast<UINT>(bytes / 4); + device->CreateUnorderedAccessView(window.Get(), nullptr, &u, cpu_at(gpu_heap.Get(), 0)); + device->CreateUnorderedAccessView(window.Get(), nullptr, &u, cpu_at(cpu_heap.Get(), 0)); + ID3D12DescriptorHeap* hs[] = {gpu_heap.Get()}; + list->SetDescriptorHeaps(1, hs); + const UINT values[4] = {7, 7, 7, 7}; + list->ClearUnorderedAccessViewUint(gpu_at(0), cpu_at(cpu_heap.Get(), 0), window.Get(), values, 0, nullptr); + } else if (op == "barrier_uav") { + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_UAV}; + b.UAV.pResource = window.Get(); + list->ResourceBarrier(1, &b); + } else if (op == "transition") { + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION}; + b.Transition = {window.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS}; + list->ResourceBarrier(1, &b); + std::swap(b.Transition.StateBefore, b.Transition.StateAfter); + list->ResourceBarrier(1, &b); + } else if (op == "root_uav" || op == "root_srv" || op == "root_cbv" || table) { + list->SetComputeRootSignature(root.Get()); + list->SetPipelineState(pso.Get()); + list->SetComputeRootConstantBufferView(0, cbv_source->GetGPUVirtualAddress()); + if (table) { + D3D12_UNORDERED_ACCESS_VIEW_DESC u{}; + u.Format = DXGI_FORMAT_R32_TYPELESS; + u.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + u.Buffer.NumElements = static_cast<UINT>(bytes / 4); + u.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(uav_target, nullptr, &u, cpu_at(gpu_heap.Get(), 0)); + D3D12_SHADER_RESOURCE_VIEW_DESC s{}; + s.Format = DXGI_FORMAT_R32_TYPELESS; + s.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + s.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + s.Buffer.NumElements = static_cast<UINT>(bytes / 4); + s.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(srv_source, &s, cpu_at(gpu_heap.Get(), 1)); + ID3D12DescriptorHeap* hs[] = {gpu_heap.Get()}; + list->SetDescriptorHeaps(1, hs); + list->SetComputeRootSignature(root.Get()); + list->SetComputeRootDescriptorTable(1, gpu_at(0)); + } else { + list->SetComputeRootShaderResourceView(1, srv_source->GetGPUVirtualAddress()); + list->SetComputeRootUnorderedAccessView(2, uav_target->GetGPUVirtualAddress()); + } + list->Dispatch(1, 1, 1); + } else if (op == "srv_past_end" || op == "uav_past_end" || op == "plain_srv_past_end") { + // A raw view that runs 64 KiB past the buffer's end, created into a shader-visible heap (no list work). + ID3D12Resource* target = op == "plain_srv_past_end" ? plain.Get() : window.Get(); + if (op == "uav_past_end") { + D3D12_UNORDERED_ACCESS_VIEW_DESC u{}; + u.Format = DXGI_FORMAT_R32_TYPELESS; + u.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + u.Buffer.NumElements = static_cast<UINT>((bytes + page) / 4); + u.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(target, nullptr, &u, cpu_at(gpu_heap.Get(), 0)); + } else { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Buffer.NumElements = static_cast<UINT>((bytes + page) / 4); + v.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(target, &v, cpu_at(gpu_heap.Get(), 0)); + } + std::printf("after the view: device removed reason 0x%08lx\n", static_cast<unsigned long>(device->GetDeviceRemovedReason())); + drain(device.Get()); + } else if (op == "cbv_big" || op == "cbv_unaligned" || op == "cbv_past_end" || op == "null_uav_zero" || + op == "tex_uav_bad_mip" || op == "tex3d_uav_bad_w" || op == "tex_srv_bad_mip") { + // Other descriptions the mirror can make, created into a shader-visible heap. + if (op == "cbv_big" || op == "cbv_unaligned" || op == "cbv_past_end") { + D3D12_CONSTANT_BUFFER_VIEW_DESC c{plain->GetGPUVirtualAddress(), 256}; + if (op == "cbv_big") c.SizeInBytes = 65536 + 256; + if (op == "cbv_unaligned") c.BufferLocation += 16; + if (op == "cbv_past_end") c = {plain->GetGPUVirtualAddress() + bytes - 256, 1024}; + device->CreateConstantBufferView(&c, cpu_at(gpu_heap.Get(), 0)); + } else if (op == "null_uav_zero") { + D3D12_UNORDERED_ACCESS_VIEW_DESC u{}; + u.Format = DXGI_FORMAT_R32_UINT; + u.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + device->CreateUnorderedAccessView(nullptr, nullptr, &u, cpu_at(gpu_heap.Get(), 0)); + } else { + const bool three = op == "tex3d_uav_bad_w"; + D3D12_RESOURCE_DESC t{}; + t.Dimension = three ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; + t.Width = 64; + t.Height = 64; + t.DepthOrArraySize = three ? 8 : 1; + t.MipLevels = 2; + t.Format = DXGI_FORMAT_R32_UINT; + t.SampleDesc.Count = 1; + t.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const D3D12_HEAP_PROPERTIES hp{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr<ID3D12Resource> tex; + if (FAILED(device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &t, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&tex)))) + return 12; + if (op == "tex_srv_bad_mip") { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_UINT; + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Texture2D.MostDetailedMip = 1; + v.Texture2D.MipLevels = 4; + device->CreateShaderResourceView(tex.Get(), &v, cpu_at(gpu_heap.Get(), 0)); + } else { + D3D12_UNORDERED_ACCESS_VIEW_DESC u{}; + u.Format = DXGI_FORMAT_R32_UINT; + if (three) { + u.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + u.Texture3D = {1, 0, 8}; // mip 1 has depth 4 + } else { + u.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + u.Texture2D.MipSlice = 3; + } + device->CreateUnorderedAccessView(tex.Get(), nullptr, &u, cpu_at(gpu_heap.Get(), 0)); + } + std::printf("after the view: device removed reason 0x%08lx\n", static_cast<unsigned long>(device->GetDeviceRemovedReason())); + drain(device.Get()); + list->Close(); + return device->GetDeviceRemovedReason() == S_OK ? 0 : 1; + } + std::printf("after the view: device removed reason 0x%08lx\n", static_cast<unsigned long>(device->GetDeviceRemovedReason())); + drain(device.Get()); + } else { + std::printf("unknown op\n"); + return 2; + } + const HRESULT closed = list->Close(); + std::printf("Close -> 0x%08lx\n", static_cast<unsigned long>(closed)); + drain(device.Get()); + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + queue->Signal(fence.Get(), 1); + for (const ULONGLONG deadline = GetTickCount64() + 20000; fence->GetCompletedValue() < 1;) { + if (GetTickCount64() >= deadline || device->GetDeviceRemovedReason() != S_OK) break; + Sleep(1); + } + drain(device.Get()); + const HRESULT removed = device->GetDeviceRemovedReason(); + std::printf("op %s: device removed reason 0x%08lx; window word 0 = %u\n", op.c_str(), static_cast<unsigned long>(removed), view[0]); + return removed == S_OK ? 0 : 1; +} diff --git a/tests/shader_db_check.cpp b/tests/shader_db_check.cpp new file mode 100644 index 0000000000..ad315eec1b --- /dev/null +++ b/tests/shader_db_check.cpp @@ -0,0 +1,233 @@ +// shader_db_check: X2W's shader database (src/shader_db) without a GPU. +// shader_db_check BLAKE3 vectors, a synthetic record written and read back, a refused manifest, +// the archive scan of a synthetic SGD5 record and a container stored as is. +// shader_db_check --mutate the same, but the refused manifest is expected to open: must fail (WILL_FAIL). +// shader_db_check --export <gpu export dir> [N] +// N records (default 5) of a real export written into a database and read back. +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> + +#include <cstdio> +#include <cstring> +#include <string> +#include <vector> + +#include "shader_db/archive_scan.h" +#include "shader_db/shader_db_writer.h" +#include "shader_db/shader_db.h" +#include "shader_db/gpu_export.h" + +using namespace shader_db; + +namespace { + +int failures = 0; + +void check(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +void quiet(const char*) {} + +std::wstring temp_file(const wchar_t* name) +{ + wchar_t dir[MAX_PATH]; + GetTempPathW(MAX_PATH, dir); + return std::wstring(dir) + name; +} + +bool same(const ShaderRecord& a, const ShaderRecord& b) +{ + const auto eq = [](const auto& x, const auto& y) { + return x.size() == y.size() && (x.empty() || !std::memcmp(x.data(), y.data(), x.size() * sizeof(x[0]))); + }; + return a.key == b.key && a.fnv64 == b.fnv64 && a.stage == b.stage && a.container_bytes == b.container_bytes && a.dxil == b.dxil && + a.user_data_dwords == b.user_data_dwords && eq(a.user_data, b.user_data) && eq(a.samplers, b.samplers) && + eq(a.static_samplers, b.static_samplers) && a.root_cbvs == b.root_cbvs && a.root_srvs == b.root_srvs && + a.root_uavs == b.root_uavs && eq(a.root_indexed_views, b.root_indexed_views) && eq(a.used, b.used) && + a.has_threads == b.has_threads && !std::memcmp(a.threads, b.threads, sizeof(a.threads)) && a.stores == b.stores && + a.stores_by_address == b.stores_by_address && a.builder == b.builder && a.wave_size == b.wave_size && a.vgprs == b.vgprs; +} + +std::string hex(uint64_t v) +{ + char t[17]; + std::snprintf(t, sizeof(t), "%016llx", static_cast<unsigned long long>(v)); + return t; +} + +// A minimal well-formed DXBC container with one part. +std::vector<uint8_t> container(const char* fourcc, const std::vector<uint8_t>& body) +{ + std::vector<uint8_t> c(32 + 4 + 8); + std::memcpy(c.data(), "DXBC", 4); + c.insert(c.end(), body.begin(), body.end()); + const uint32_t total = static_cast<uint32_t>(c.size()), count = 1, offset = 36, size = static_cast<uint32_t>(body.size()); + std::memcpy(c.data() + 24, &total, 4); + std::memcpy(c.data() + 28, &count, 4); + std::memcpy(c.data() + 32, &offset, 4); + std::memcpy(c.data() + 36, fourcc, 4); + std::memcpy(c.data() + 40, &size, 4); + return c; +} + +int synthetic(bool mutate) +{ + // BLAKE3 test vectors (the reference test_vectors.json: input of length 0, and of length 1 = byte 0). + check(gpu_key("", 0) == 0xaf1349b9f5f9a1a6ull, "BLAKE3 of the empty input"); + const uint8_t zero = 0; + check(gpu_key(&zero, 1) == 0x2d3adedff11b61f1ull, "BLAKE3 of one zero byte"); + check(fnv64("a", 1) == 0x44bd8ad473cd9906ull, "fnv_bytes of 'a' (X2W's basis 1469598103934665603)"); + + const std::vector<uint8_t> title = container("DXIL", {1, 2, 3, 4, 5, 6, 7, 8}); + ShaderRecord r; + r.key = gpu_key(title.data(), title.size()); + r.fnv64 = fnv64(title.data(), title.size()); + r.stage = Stage::ps; + r.container_bytes = static_cast<uint32_t>(title.size()); + r.dxil = container("DXIL", {9, 9, 9}); + r.user_data_dwords = 8; + r.user_data = {{0, 1, root_table, 0}, {5, 3, root_other_base + 7, 1}}; + r.samplers = {{0x400, 0xc00000, 0x18f00000, 0}}; + r.static_samplers = {{0x15, {1, 2, 3}, -0.5f, 16, 0, 0, 0.0f, 1000.0f}}; + r.root_cbvs = {2}; + r.root_srvs = {0, 3}; + r.root_uavs = {1}; + r.root_indexed_views = {{1, 2, 3, 32, 5}}; + r.used = {{resource_uav, root_table, 4, 0, 16, 8, 2, 1}}; + r.has_threads = true; + r.threads[0] = 64; + r.threads[1] = r.threads[2] = 1; + r.stores = r.builder = true; + r.wave_size = 64; + r.vgprs = 40; + ShaderRecord other = r; + other.key ^= 1; + other.stage = Stage::cs; + other.dxil = {7}; + + const std::wstring path = temp_file(mutate ? L"shader_db_check_mutate.vxdb" : L"shader_db_check.vxdb"); + const std::string manifest = "format gpu-x2w-1\nview_heap_limit 2097151\nraw_views 2097152\nmax_wave 64\nbuild abc\ncommit def\n"; + std::string error; + check(write_db(path, {other, r}, manifest, error), "write"); + check(!write_db(path + L".dup", {r, r}, manifest, error), "a repeated key is refused"); + check(gpu_db_open(path.c_str(), 2097151, 2097152, quiet), "open"); + check(gpu_db_count() == 2, "count"); + const GpuShader* s = gpu_shader(title.data(), title.size(), Stage::ps); + check(s && same(copy_record(*s), r), "record round trip"); + check(!gpu_shader(title.data(), title.size(), Stage::vs), "a stage mismatch is a miss"); + check(gpu_shader(title.data(), title.size(), Stage::any) == s, "Stage::any"); + check(!gpu_shader(title.data(), title.size() - 1, Stage::ps), "other bytes are a miss"); + const Manifest* m = gpu_db_manifest(); + check(m && m->view_heap_limit == 2097151 && m->raw_views == 2097152 && m->max_wave == 64 && !std::strcmp(m->build, "abc"), "manifest"); + gpu_db_close(); + + // A database made for another heap layout is refused (the negative control expects it to open). + const bool refused = !gpu_db_open(path.c_str(), mutate ? 2097151 : 1000000, 2097152, quiet); + check(refused, "a manifest whose view_heap_limit differs is refused"); + gpu_db_close(); + std::vector<uint8_t> damaged; + { + FILE* f = _wfopen(path.c_str(), L"rb"); + damaged.resize(1 << 16); + damaged.resize(std::fread(damaged.data(), 1, damaged.size(), f)); + std::fclose(f); + } + damaged.resize(damaged.size() - 1); + const std::wstring cut = path + L".cut"; + FILE* f = _wfopen(cut.c_str(), L"wb"); + std::fwrite(damaged.data(), 1, damaged.size(), f); + std::fclose(f); + check(!gpu_db_open(cut.c_str(), 0, 0, quiet), "a truncated database is refused"); + gpu_db_close(); + DeleteFileW(cut.c_str()); + DeleteFileW(path.c_str()); + + // Archive scan: an SGD5 record (raw deflate, one stored block) and a container stored as is with bytes after it. + const std::vector<uint8_t> packed_container = container("DXIL", {4, 4, 4, 4}); + std::vector<uint8_t> file = {'S', 'G', 'D', '5', 0, 0, 0, 0}; + const std::string name = "PS_Test_0011aabb_Wrapped"; + file.push_back(0xf4); + file.push_back(0x01); + file.push_back(0); + file.push_back(0); + file.push_back(static_cast<uint8_t>(name.size() + 1)); + file.insert(file.end(), name.begin(), name.end()); + file.push_back(0); + file.push_back(0x32); + std::vector<uint8_t> deflate = {0x01}; + const uint16_t len = static_cast<uint16_t>(packed_container.size()), nlen = static_cast<uint16_t>(~len); + deflate.push_back(len & 0xff); + deflate.push_back(len >> 8); + deflate.push_back(nlen & 0xff); + deflate.push_back(nlen >> 8); + deflate.insert(deflate.end(), packed_container.begin(), packed_container.end()); + const uint32_t n = static_cast<uint32_t>(deflate.size() + 12), marker = 0x000ddce7, unpacked = len; + for (uint32_t v : {n, marker, n, unpacked}) file.insert(file.end(), reinterpret_cast<const uint8_t*>(&v), reinterpret_cast<const uint8_t*>(&v) + 4); + file.insert(file.end(), deflate.begin(), deflate.end()); + const std::size_t raw_at = file.size(); + file.insert(file.end(), title.begin(), title.end()); + file.insert(file.end(), {0xde, 0xad, 0xbe, 0xef}); + std::vector<std::string> labels; + std::vector<std::vector<uint8_t>> found; + scan_bytes(file.data(), file.size(), [&](const uint8_t* b, std::size_t k, const std::string& label) { + labels.push_back(label); + found.emplace_back(b, b + k); + }); + // A stored deflate block keeps its bytes as they are, so the scan finds three containers: + // the record, its stored copy, and the following container. + check(found.size() == 3, "three containers found"); + if (found.size() == 3) { + check(found[0] == packed_container && labels[0].find(name) != std::string::npos, "the packed record, unpacked and named"); + check(found[1] == packed_container, "its stored bytes, as is"); + check(found[2] == title, "the container as is, cut to its size"); + char at[32]; + std::snprintf(at, sizeof(at), "@0x%zx", raw_at); + check(labels[2] == at, "its label is its offset"); + } + std::printf("%s\n", failures ? "shader_db_check: FAILED" : "shader_db_check: ok"); + return failures ? 1 : 0; +} + +int real(const wchar_t* dir, std::size_t n) +{ + GpuExport ex; + check(read_gpu_export(dir, ex, n), "read the export"); + check(ex.errors.empty(), "every record read"); + std::vector<ShaderRecord> records; + for (const auto& [key, row] : ex.rows) records.push_back(row.record); + const std::wstring path = temp_file(L"shader_db_check_real.vxdb"); + std::string error; + check(write_db(path, records, ex.manifest, error), "write"); + check(gpu_db_open(path.c_str(), 0, 0, quiet), "open"); + const Manifest* m = gpu_db_manifest(); + if (m) std::printf("manifest: view_heap_limit %u raw_views %u max_wave %u host_rdna %u build %.16s\n", m->view_heap_limit, m->raw_views, m->max_wave, + m->host_rdna, m->build); + for (const auto& r : records) { + const GpuShader* s = gpu_shader_by_key(r.key); + check(s && same(copy_record(*s), r), "record round trip"); + if (s) + std::printf("%s %u dxil=%zu user_data_dwords=%u user_data=%u samplers=%u cbv=%u srv=%u uav=%u riv=%u used=%u threads=%s stores=%d/%d wave=%u\n", + hex(s->key).c_str(), static_cast<unsigned>(s->stage), s->dxil_bytes, s->user_data_dwords, s->user_data_count, s->sampler_count, + s->root_cbv_count, s->root_srv_count, s->root_uav_count, s->root_indexed_view_count, s->used_count, + s->has_threads ? std::to_string(s->threads[0]).c_str() : "-", s->stores, s->stores_by_address, s->wave_size); + } + gpu_db_close(); + DeleteFileW(path.c_str()); + std::printf("%s (%zu records)\n", failures ? "shader_db_check --export: FAILED" : "shader_db_check --export: ok", records.size()); + return failures ? 1 : 0; +} + +} // namespace + +int wmain(int argc, wchar_t** argv) +{ + if (argc >= 3 && !std::wcscmp(argv[1], L"--export")) return real(argv[2], argc >= 4 ? static_cast<std::size_t>(_wtoi(argv[3])) : 5); + return synthetic(argc >= 2 && !std::wcscmp(argv[1], L"--mutate")); +} diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index d2a72fc2d3..1d9326fbc4 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -6,9 +6,11 @@ #include <cstring> #include <cwchar> #include <fstream> +#include <iterator> #include <vector> using Word = std::uint64_t; +extern "C" __declspec(dllimport) HRESULT XGCreateTextureComputer(const D3D12_RESOURCE_DESC*, void***, UINT64, UINT64); 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); @@ -342,6 +344,116 @@ int draw_bc_chain(void* guest, void* list) return 0; } +// LOCAL (textures): memory SRVs of a console-swizzled description (layout 0x105, flags 0x300000) whose memory the +// XG stand-in filled (CopyIntoSubresource announces the base). Two such textures A and B, two mips each, and a +// third texture C with the same description and the same footprint bytes written by hand (not announced). +// Columns: 0 A, 1 B, 2 C (refused: B stays), 3 A, 4 B, 5 C (refused: B stays), 6 A, 7 A. +int draw_announced_srvs(ID3D12Device* desktop, void* guest, void* list) +{ + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 2, 2, 1, 2, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + static_cast<D3D12_TEXTURE_LAYOUT>(0x105), static_cast<D3D12_RESOURCE_FLAGS>(0x300000)}; + static std::array<char, 4 * 65536> storage{}; + std::array<unsigned char*, 3> memory{}; + for (unsigned i = 0; i < 3; ++i) + memory[i] = reinterpret_cast<unsigned char*>(((ptr(storage.data()) + 0xffff) & ~Word{0xffff}) + i * Word{65536}); + const auto texel = [](unsigned which, unsigned mip, unsigned x, unsigned y) -> std::array<unsigned char, 4> { + if (mip) return which == 1 ? std::array<unsigned char, 4>{9, 99, 199, 255} : std::array<unsigned char, 4>{5, 6, 7, 255}; + return which == 1 ? std::array<unsigned char, 4>{static_cast<unsigned char>(100 + 20 * x + 50 * y), 50, 150, 255} + : std::array<unsigned char, 4>{static_cast<unsigned char>(10 + 40 * x + 80 * y), 200, 30, 255}; + }; + for (unsigned which = 0; which < 3; ++which) { + void** computer = nullptr; + if (FAILED(XGCreateTextureComputer(&desc, &computer, 0, 0)) || !computer) return 50; + const auto table = static_cast<void**>(computer[0]); + using Write = HRESULT(*)(void*, unsigned char*, UINT, UINT, const unsigned char*, UINT, UINT); + for (unsigned mip = 0; mip < 2; ++mip) { + const unsigned side = 2 >> mip; + std::array<unsigned char, 16> linear{}; + for (unsigned y = 0; y < side; ++y) + for (unsigned x = 0; x < side; ++x) std::memcpy(&linear[(y * side + x) * 4], texel(which % 2, mip, x, y).data(), 4); + if (which < 2) { + if (FAILED(reinterpret_cast<Write>(table[8])(computer, memory[which], 0, mip, linear.data(), side * 4, side * side * 4))) + return 51; + } else { + // C: the bytes CopyIntoSubresource would write (desktop footprints), without the announcement. + D3D12_RESOURCE_DESC plain = desc; + plain.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + plain.Flags = D3D12_RESOURCE_FLAG_NONE; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; + desktop->GetCopyableFootprints(&plain, mip, 1, 0, &fp, nullptr, nullptr, nullptr); + for (unsigned y = 0; y < side; ++y) + std::memcpy(memory[2] + fp.Offset + y * fp.Footprint.RowPitch, &linear[y * side * 4], side * 4); + } + } + reinterpret_cast<UINT64(*)(void*)>(table[1])(computer); + } + Word cpu = 0; + if (!bind_view_table(guest, list, cpu)) return 42; + ViewAt v{}; + v.view.Format = desc.Format; + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.view.Texture2D.MipLevels = 2; + const unsigned order[8] = {0, 1, 2, 0, 1, 2, 0, 0}; + for (LONG x = 0; x < 8; ++x) { + v.address = ptr(memory[order[x]]); + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + const D3D12_RECT strip{x, 0, x + 1, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + } + // Device slot 61 (the title's sampler call, a no-op): with X2W_TEXTURE_CENSUS=1 its arguments are logged. + std::array<std::uint32_t, 16> sampler_words{}; + for (unsigned i = 0; i < sampler_words.size(); ++i) sampler_words[i] = 0x61000000u + i; + invoke(guest, 61, ptr(sampler_words.data()), 0x5150, 1); + return 0; +} + +// LOCAL (textures): one memory SRV of a console-swizzled texture (X2W_MEMORY_SRV_DETILE). X2W_TEST_DETILE_SRV names +// the surface bytes (tests/gfx10_layout_check.cpp --write-tiled, synthetic), X2W_TEST_DETILE_DESC its description +// "<layout> <dimension> <format> <width> <height> <depth or array size> <mips>" (layout in hex; flags 0x300000). The memory is +// 64 KiB-aligned and was not announced by the XG stand-in; the view covers every level (and slice). +int draw_detile_srvs(void* guest, void* list) +{ + wchar_t path[MAX_PATH]{}; + char desc_text[128]{}; + const DWORD length = GetEnvironmentVariableW(L"X2W_TEST_DETILE_SRV", path, MAX_PATH); + if (!length || length >= MAX_PATH || !GetEnvironmentVariableA("X2W_TEST_DETILE_DESC", desc_text, sizeof desc_text)) return 43; + unsigned layout = 0, dimension = 0, format = 0, width = 0, height = 0, depth = 0, mips = 0; + if (std::sscanf(desc_text, "%x %u %u %u %u %u %u", &layout, &dimension, &format, &width, &height, &depth, &mips) != 7) return 43; + std::ifstream input(path, std::ios::binary); + const std::vector<char> bytes{std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>{}}; + if (bytes.empty()) return 43; + // 64 KiB-aligned, with 1 MiB of zero slack so a wrong (larger) layout in a control stays readable. + void* memory = VirtualAlloc(nullptr, bytes.size() + (1u << 20), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!memory) return 44; + std::memcpy(memory, bytes.data(), bytes.size()); + const D3D12_RESOURCE_DESC desc{static_cast<D3D12_RESOURCE_DIMENSION>(dimension), 0, width, height, static_cast<UINT16>(depth), + static_cast<UINT16>(mips), static_cast<DXGI_FORMAT>(format), {1, 0}, static_cast<D3D12_TEXTURE_LAYOUT>(layout), + static_cast<D3D12_RESOURCE_FLAGS>(0x300000)}; + ViewAt v{}; + v.address = ptr(memory); + v.view.Format = desc.Format; + v.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + v.view.Texture3D.MipLevels = mips; + } else if (depth > 1) { + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + v.view.Texture2DArray.MipLevels = mips; + v.view.Texture2DArray.ArraySize = depth; + } else { + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.view.Texture2D.MipLevels = mips; + } + Word cpu = 0; + if (!bind_view_table(guest, list, cpu)) return 42; + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); // the same view again: the first desktop texture is reused + invoke(list, 12, 3, 1); + return 0; +} + namespace { struct PlacedPair { std::array<DWORD*, 2> memory{}; diff --git a/tests/startup_bc_writer_srv.inl b/tests/startup_bc_writer_srv.inl new file mode 100644 index 0000000000..09e95ee5cc --- /dev/null +++ b/tests/startup_bc_writer_srv.inl @@ -0,0 +1,98 @@ +// Request the CPU-backed descriptor before a native texture exists. Then place a real +// texture at the same address and copy an opaque red BC3 block to it. The CPU bytes +// remain zero. A fresh slot-70 descriptor must sample the actual GPU-written red texel. +{ + auto* material_memory = VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + if (!material_memory) return 42; + ComPtr<ID3D12Device> native; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&native)))) return 43; + struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 backing, bytes; } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2}}; + void* guest_heap{}; + if (!ok(invoke(device, 14, arg(&heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&guest_heap)))) return 44; + const auto cpu = invoke(guest_heap, 9); + const UINT stride = native->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + auto material_desc = family_desc; + material_desc.Width = material_desc.Height = 64; + material_desc.Format = DXGI_FORMAT_BC3_UNORM; + material_desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x105); + struct { D3D12_SHADER_RESOURCE_VIEW_DESC view; UINT64 address; } input{}; + input.address = reinterpret_cast<UINT64>(material_memory); + input.view.Format = material_desc.Format; + input.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + input.view.Texture2D.MipLevels = 1; + input.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + invoke(device, 70, arg(&material_desc), arg(&input), cpu); + void* material{}; + if (!ok(invoke(device, 133, arg(material_memory), arg(&material_desc), D3D12_RESOURCE_STATE_COMMON, 0, + arg(&__uuidof(ID3D12Resource)), arg(&material))) || !material) return 45; + auto encoded_desc = family_desc; + encoded_desc.Width = encoded_desc.Height = 1; + encoded_desc.Format = DXGI_FORMAT_R32G32B32A32_UINT; + auto* encoded = make_resource(device, D3D12_HEAP_TYPE_DEFAULT, encoded_desc, D3D12_RESOURCE_STATE_COMMON); + if (!encoded || !ok(invoke(upload, 8, 0, 0, arg(&memory))) || !memory) return 46; + const BYTE red_block[16]{255, 255, 0, 0, 0, 0, 0, 0, 0, 248, 0, 0, 0, 0, 0, 0}; + std::memcpy(memory, red_block, 16); + invoke(upload, 9); + if (!ok(invoke(list, 139, arg(allocator), 0))) return 47; + auto encoded_upload = footprint(upload, 0, encoded_desc.Format); + encoded_upload.PlacedFootprint.Footprint.Width = encoded_upload.PlacedFootprint.Footprint.Height = 1; + const auto packed = subresource(encoded, 0), target = subresource(material, 0); + copy(packed, encoded_upload); + invoke(list, 85, arg(&target), 0, 0, 0, arg(&packed)); + if (!ok(invoke(list, 9)) || !submit()) return 48; + invoke(device, 70, arg(&material_desc), arg(&input), cpu + stride); + D3D12_DESCRIPTOR_HEAP_DESC visible_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr<ID3D12DescriptorHeap> visible; + check(native->CreateDescriptorHeap(&visible_desc, IID_PPV_ARGS(&visible)), "sample heap"); + // The shim may have allocated a title-side shadow heap. Copy from the + // actual desktop heap into a shader-visible one for this native dispatch. + constexpr GUID key{0xb5799bda, 0xe302, 0x4194, {0x87, 0x76, 0x36, 0x91, 0xf4, 0xdc, 0x44, 0x16}}; + if (!ok(invoke(device, 5, arg(&key), arg(guest_heap)))) return 50; + ComPtr<IUnknown> object; + UINT pointer_bytes = sizeof(IUnknown*); + check(native->GetPrivateData(key, &pointer_bytes, object.GetAddressOf()), "desktop heap reference"); + invoke(device, 5, arg(&key), 0); + ComPtr<ID3D12DescriptorHeap> native_heap; + check(object.As(&native_heap), "native descriptor heap"); + auto source_handle = native_heap->GetCPUDescriptorHandleForHeapStart(); + source_handle.ptr += stride; + native->CopyDescriptorsSimple(1, visible->GetCPUDescriptorHandleForHeapStart(), source_handle, visible_desc.Type); + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1}; + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + const D3D12_ROOT_SIGNATURE_DESC rd{2, params}; + ComPtr<ID3DBlob> serialized, blob; + check(D3D12SerializeRootSignature(&rd, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, nullptr), "sample root"); + ComPtr<ID3D12RootSignature> root; + check(native->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), IID_PPV_ARGS(&root)), "root"); + constexpr char shader[] = "Texture2D<float4> t:register(t0); RWStructuredBuffer<float4> o:register(u0);" + "[numthreads(1,1,1)] void main(){o[0]=t.Load(int3(0,0,0));}"; + check(D3DCompile(shader, sizeof(shader)-1, nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, &blob, nullptr), "sample shader"); + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.Get(); + pd.CS = {blob->GetBufferPointer(), blob->GetBufferSize()}; + ComPtr<ID3D12PipelineState> pso; + check(native->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pso)), "sample pso"); + auto out = make_buffer(native.Get(), 16, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto back = make_buffer(native.Get(), 16, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands commands(native.Get(), pso.Get()); + ID3D12DescriptorHeap* heaps[]{visible.Get()}; + commands.list->SetDescriptorHeaps(1, heaps); + commands.list->SetComputeRootSignature(root.Get()); + commands.list->SetComputeRootDescriptorTable(0, visible->GetGPUDescriptorHandleForHeapStart()); + commands.list->SetComputeRootUnorderedAccessView(1, out->GetGPUVirtualAddress()); + commands.list->Dispatch(1,1,1); + transition(commands.list.Get(), out.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + commands.list->CopyBufferRegion(back.Get(), 0, out.Get(), 0, 16); + commands.submit_and_wait(native.Get()); + void* sampled{}; + check(back->Map(0, nullptr, &sampled), "sample readback"); + const auto* rgba = static_cast<const float*>(sampled); + const bool red = rgba[0] == 1.f && rgba[1] == 0.f && rgba[2] == 0.f && rgba[3] == 1.f; + std::printf("slot70 after slot85 BC3 sample: %g %g %g %g\n", rgba[0], rgba[1], rgba[2], rgba[3]); + back->Unmap(0, nullptr); + if (!red || std::memcmp(material_memory, red_block, 16) == 0) return 49; +} diff --git a/tests/startup_bfm_absdiff_check.py b/tests/startup_bfm_absdiff_check.py new file mode 100644 index 0000000000..432eea6d68 --- /dev/null +++ b/tests/startup_bfm_absdiff_check.py @@ -0,0 +1,60 @@ +"""v_bfm_b32 (VOP3) and s_absdiff_i32 (SOP2). + +Synthetic gfx1013 words. References (AMD RDNA 2 ISA): V_BFM_B32 D = ((1 << S0[4:0]) - 1) << S1[4:0]; +S_ABSDIFF_I32 D = S0 - S1 (32-bit wrap), negated if negative, SCC = (D != 0) (LLVM SOPInstructions.td Defs = [SCC]). +The emitted HLSL is evaluated with the integer evaluator of startup_gfx2hlsl_bit_alu_check (abs added here with +HLSL int semantics: abs(INT_MIN) = INT_MIN) over an edge grid. Negative controls: a wrong expression of each form +(the shift count masked to 4 bits; abs dropped) is caught. +""" +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 +from startup_scalar_bits_check import GRID, MASK, asm, lines_of, rhs # noqa: E402 + + +class AbsExpr(Expr): + @staticmethod + def call(name, args): + if name == 'abs': + v, s = args[0] + assert s + x = v - (1 << 32) if v >> 31 else v + return (-x if x < 0 else x) & MASK, True + return Expr.call(name, args) + + +def s32(x): + return x - (1 << 32) if x >> 31 else x + + +def main(): + grid = GRID + [33 << 16 | 5, 0x1f001f, 0x3f] + words = [0xd4000000 | 0x363 << 16 | 2, 256 | 257 << 9] + assert asm(words) == ['v_bfm_b32 v2, v0, v1'], asm(words) + _, lines = lines_of(words) + expr = rhs(lines[0], 'v2') + ref = lambda a, b: (((1 << (a & 31)) - 1) << (b & 31)) & MASK # noqa: E731 + bad = [(a, b) for a in grid for b in grid if Expr(expr).run({'v0': a, 'v1': b})[0] & MASK != ref(a, b)] + assert not bad, (expr, bad[:4]) + wrong = Expr(expr.replace('{0} & 31'.format('v0'), 'v0 & 15')) + assert any(wrong.run({'v0': a, 'v1': b})[0] & MASK != ref(a, b) for a in grid for b in grid) + words = [0x80000000 | 0x2c << 23 | 5 << 16 | 7 << 8 | 6] + assert asm(words) == ['s_absdiff_i32 s5, s6, s7'], asm(words) + _, lines = lines_of(words) + assert len(lines) == 2 and lines[1] == 'scc = s5 != 0;', lines + expr = rhs(lines[0], 's5') + ref = lambda a, b: abs(s32((a - b) & MASK)) & MASK # noqa: E731 + bad = [(a, b) for a in grid for b in grid if AbsExpr(expr).run({'s6': a, 's7': b})[0] & MASK != ref(a, b)] + assert not bad, (expr, bad[:4]) + assert ref(0x80000000, 0) == 0x80000000 + wrong = AbsExpr(expr.replace('abs(', '(')) + assert any(wrong.run({'s6': a, 's7': b})[0] & MASK != ref(a, b) for a in grid for b in grid) + print('bfm_absdiff: v_bfm_b32 and s_absdiff_i32 (SCC = D != 0) match the ISA references on %d inputs; ' + 'negative controls caught' % len(grid) ** 2) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_buffer_address_check.py b/tests/startup_buffer_address_check.py index 6e2ba647ec..4dfec4e83a 100644 --- a/tests/startup_buffer_address_check.py +++ b/tests/startup_buffer_address_check.py @@ -230,9 +230,7 @@ def request(load): assert classify_shader_reason('buffer_load_format_xyzw requires descriptor FORMAT and DST_SEL') == 'buffer_* instruction' -def controls(): - formatted_mubuf_request_controls() - +def address_mode_controls(): # 1. Existing single-mode forms keep their exact HLSL output. asm, st = translate_bytes(encode_mubuf(imm=12, soffset=128 + 16)) assert asm == ['buffer_load_dword v4, off, s[16:19], 16 offset:12'], asm @@ -261,6 +259,11 @@ def controls(): assert st.lines[0] == 'a = v6 * ud2 + v7 + 5;', st.lines assert {6, 7}.issubset(st.used_v), st.used_v + +def controls(): + address_mode_controls() + formatted_mubuf_request_controls() + # 3. Scalar soffset from an SGPR (root constant, folded scalar constant, or runtime SGPR, up to s105). asm, st = translate_bytes(encode_mubuf(imm=12, idxen=1, offen=1, vaddr=2, soffset=8)) assert asm == ['buffer_load_dword v4, v[2:3], s[16:19], s8 idxen offen offset:12'], asm @@ -283,6 +286,8 @@ def controls(): assert st.lines[0] == 'a = v254 * ud2 + v255 + 4;', st.lines must_refuse_bytes(encode_mubuf(imm=4, idxen=1, offen=1, vaddr=255), 'v[255:256]') + must_refuse_asm('buffer_load_dword v4, off, s[16:19], 0 lwe', 'buffer modifier lwe') + # 6. Unmodeled modifiers (lds, tfe, unknown) are refused with Unsupported, never dropped or crashed. must_refuse_bytes(encode_mubuf(imm=8, offen=1, vaddr=2, lds=1), 'buffer modifier lds') must_refuse_bytes(encode_mubuf(imm=8, lds=1), 'buffer modifier lds') diff --git a/tests/startup_buffer_heap_index_check.py b/tests/startup_buffer_heap_index_check.py new file mode 100644 index 0000000000..a91c9dabb6 --- /dev/null +++ b/tests/startup_buffer_heap_index_check.py @@ -0,0 +1,100 @@ +"""Exercise buffer heap indexing with synthetic free slots and mapped buffers.""" +from pathlib import Path +import re +import sys +import tempfile + +from startup_draw_uav_check import run_mode + +IDENTITY = bytes((0, 0, 0x80, 0x3F)) +VALUE = bytes((99, 0, 0, 0)) +DECOY = bytes((55, 0, 0, 0)) +ON = {"X2W_BUFFER_HEAP_INDEX": "1", "X2W_BUFFER_ADDRESS_INDEX": "check"} +REWRITE_LOG = dict(ON, X2W_MARKER_REWRITE_LOG="1") +MODES = {"membuf": ON, "membuf-off": {}, "membuf-link": ON, "membuf-structured": ON, "membuf-typed": ON, "membuf-refused": REWRITE_LOG, + "membuf-unaligned": ON, "membuf-unaligned-off": {}, "membuf-rewrite": REWRITE_LOG} + + +def columns(image): + """Pixels (x, y) for x < 2 of the 8x4 RGBA8 read-back: what the two strips drew.""" + return {image[(y * 8 + x) * 4:(y * 8 + x) * 4 + 4] for y in range(4) for x in range(2)} + + +def check(directory, consumer, backend): + results = {} + for mode, env in MODES.items(): + got = run_mode(directory, consumer, backend, mode, dict(env, X2W_DRAW_NULL_IDENTITY="1")) + if got is None: + print("no existing-heap support or no adapter: skip") + return 77 + results[mode] = got + for mode, (_, image, log) in results.items(): + if DECOY in columns(image): + raise AssertionError(f"{mode}: the draw read the decoy at slot N (55)\n{log[-3000:]}") + _, image, log = results["membuf"] + if columns(image) != {VALUE}: + raise AssertionError(f"membuf: pixels {image[:32].hex()} (expected 99 = {VALUE.hex()})\n{log[-4000:]}") + # The switch-on modes run X2W_BUFFER_ADDRESS_INDEX=check: the index answers as the walk (here: no buffer). + for mode in ("membuf", "membuf-structured", "membuf-typed"): + lines = re.findall(r"^x2w-memsrv buffer address index checked (\d+) lookups against the walk: (\d+) differ$", results[mode][2], re.M) + if not lines or any(d != "0" for _, d in lines) or "DIFFERS" in results[mode][2]: + raise AssertionError(f"{mode}: address index check lines {lines}\n{results[mode][2][-3000:]}") + for mode, layout in (("membuf", "stride 0, records 256, word 3 0x"), ("membuf-structured", "stride 16, records 4, word 3 0x"), + ("membuf-typed", "stride 4, records 64, word 3 0x"), + ("membuf-unaligned", "stride 12, records 4, word 3 0x")): + _, image, log = results[mode] + words = re.search(r"^membuf entry words: (\w+) (\w+) (\w+) (\w+)$", log, re.M) + if columns(image) != {VALUE} or not words or words.group(1) in ("00000001", "56573258", "52463258") or words.group(4) == "00000000": + raise AssertionError(f"{mode}: pixels {image[:32].hex()} (expected 99), entry {words.group(0) if words else None}\n{log[-4000:]}") + written = re.search(r"^x2w-memsrv buffer descriptor written at .*$", log, re.M) + if "X2W_BUFFER_HEAP_INDEX=1" not in log or not written or layout not in written.group(0) or "stand-in buffer at" in log: + raise AssertionError(f"{mode}: descriptor line {written.group(0) if written else None} (expected {layout!r}), or a stand-in\n{log[-4000:]}") + _, image, log = results["membuf-unaligned"] + if "(a buffer is there, at an offset the view cannot name)" not in log \ + or "buffer descriptors: written 1 (no buffer 0, buffer at an offset the view cannot name 1)" not in log \ + or not re.search(r"per written call: buffer lookup \d+\.\d\d us, destination checks \d+\.\d\d us, shadow clear \d+\.\d\d us " + r"\(lock taken [01]\)", log): + raise AssertionError(f"membuf-unaligned: the found-buffer case is not named\n{log[-4000:]}") + _, image, log = results["membuf-unaligned-off"] + if columns(image) != {IDENTITY} or "reason=buffer_unavailable" not in log or "buffer descriptor written" in log: + raise AssertionError(f"membuf-unaligned-off: pixels {image[:32].hex()} (expected the identity fill)\n{log[-4000:]}") + _, image, log = results["membuf-refused"] + line = re.search(r"^x2w-frame srv-heapbuf .*$", log, re.M) + if columns(image) != {IDENTITY} or "membuf entry words: 52463258" not in log or not line \ + or "(refused: null_address)" not in line.group(0) \ + or not re.search(r"refused view: fmt \d+ layout 0x[0-9a-f]+ dim 1 mips \d+ [1-9]\d*x1x1 address 0x0 unreadable, detile: -$", + line.group(0)): + raise AssertionError(f"membuf-refused: pixels {image[:32].hex()}, line {line.group(0) if line else None}\n{log[-4000:]}") + # membuf-refused is also the negative control of X2W_MARKER_REWRITE_LOG: an intact marker is not flagged. + if "rewritten refused-view marker" in log or "X2W_MARKER_REWRITE_LOG=1" not in log: + raise AssertionError(f"membuf-refused: an intact marker was flagged as rewritten, or the switch line is missing\n{log[-4000:]}") + # membuf-rewrite: the title patches word 0 / word 1 bits 0-15 of the refused destination with a V# base after the + # call; the copied entry is flagged, with the description and the base read back from the rewritten words. + _, image, log = results["membuf-rewrite"] + entry = re.search(r"^membuf entry words: ([0-9a-f]{8}) ([0-9a-f]{8}) ([0-9a-f]{8}) ([0-9a-f]{8})$", log, re.M) + line = re.search(r"^x2w-draw rewritten refused-view marker .*$", log, re.M) + if not entry or not line: + raise AssertionError(f"membuf-rewrite: entry {entry.group(0) if entry else None}, line {line.group(0) if line else None}\n{log[-4000:]}") + base = int(entry.group(1), 16) | (int(entry.group(2), 16) & 0xFFFF) << 32 + if entry.group(1) == "52463258" or f"as a V# 0x{base:x}" not in line.group(0) \ + or not re.search(r"described as fmt \d+ layout 0x[0-9a-f]+ dim 1 mips \d+ [1-9]\d*x1x1 address 0x0 unreadable, detile: -;", + line.group(0)) \ + or "x2w-draw rewritten refused-view markers 1" not in log: + raise AssertionError(f"membuf-rewrite: base 0x{base:x}, line {line.group(0)}\n{log[-4000:]}") + _, image, log = results["membuf-off"] + if columns(image) != {IDENTITY} or "membuf entry words: 00000001 00000000 00000000 00000000" not in log \ + or "reason=buffer_unavailable" not in log or "X2W_BUFFER_HEAP_INDEX" in log: + raise AssertionError(f"membuf-off: pixels {image[:32].hex()} (expected the identity fill {IDENTITY.hex()})\n{log[-4000:]}") + _, image, log = results["membuf-link"] + line = re.search(r"^x2w-frame srv-heapbuf .*$", log, re.M) + if columns(image) != {IDENTITY} or not line or "(free link)" not in line.group(0) \ + or "slot N-1 0x0 words 00000001" not in line.group(0) or "slot N 0x1 token 56573258" not in line.group(0): + raise AssertionError(f"membuf-link: pixels {image[:32].hex()}, line {line.group(0) if line else None}\n{log[-4000:]}") + print(f"{backend}: slot-70 buffer without a resource read through a copied entry (99) with X2W_BUFFER_HEAP_INDEX; " + f"switch off: link 1 copied, identity fill; free link: bound null and logged with slots N-1 / N; decoy at slot N never read; structured and typed views 99; a refused call's marker is carried, bound null and named") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_buffer_store_check.py b/tests/startup_buffer_store_check.py new file mode 100644 index 0000000000..fde312ba85 --- /dev/null +++ b/tests/startup_buffer_store_check.py @@ -0,0 +1,136 @@ +"""buffer_store_dword* to a raw buffer UAV, behind X2W_DRAW_FEATURES=uav (tools/startup/gfx2hlsl.py). + +Synthetic register states (descriptor s[16:19] from table 0 at byte 0x20). Checked: +1. feature off: refused with the old message (the op name); +2. feature on: `a = ud<uavbase> + vaddr + soffset + offset`, Store3 of the three data VGPRs, the exec guard after a + branch made exec unknown, a literal soffset folded into the constant; +3. refusals: idxen (no UAV stride source), a vertex-buffer source, an unknown modifier, a ninth UAV; a buffer both read and + stored is read through the UAV (StoredSrv retry signal, rw_keys); descriptor edits that keep the base are accepted; +4. manifest `uav 0 buf table 0 32` after the srv lines, `udsrc <n> uavbase 0`, and the HLSL declaration + RWByteAddressBuffer u0 : register(u0). +Not checked: stores on a GPU (draw-rt's startup_draw_uav_check covers the runtime side with its own shaders). +""" +import os +import sys +from types import SimpleNamespace + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + sampler_heap = False + root = {'params': [], 'flags': 0} + uav = G.Pipeline.uav + resource = G.Pipeline.resource + + def __init__(self, features): + self.features = frozenset(features) + self.resources, self.uds, self.modified, self.heapvars = {}, [], set(), [] + + def ud(self, source): + if source not in self.uds: + self.uds.append(source) + return self.uds.index(source) + + +def stage(features=('uav',), source=('table', 0), pipe=None): + s = G.Stage(pipe or Pipe(features), 'ps', b'') + s.lines = [] + for i in range(4): + s.sym[16 + i] = ('desc', source, 0x20, i) + s.pc = 0 + return s + + +def refused(s, op, ops, mods, want): + try: + getattr(s, op)(ops, mods) + except G.Unsupported as error: + assert want in str(error), (want, str(error)) + else: + raise AssertionError('accepted: %s %s %s' % (op, ops, mods)) + + +STORE = ['v[4:6]', 'v1', 's[16:19]', '0'] + + +def main(): + refused(stage(()), 'op_buffer_store_dwordx3', STORE, ['offen'], 'buffer_store_dwordx3') + assert str(G.Unsupported('buffer_store_dwordx3')) == 'buffer_store_dwordx3' + + s = stage() + s.op_buffer_store_dwordx3(STORE, ['offen', 'offset:16']) + assert s.lines == ['a = ud0 + v1 + 16;', 'u0.Store3(a, uint3(v4, v5, v6));'], s.lines + assert s.pipe.uds == [('uavbase', 0)] and s.pipe.uavs == {(('table', 0), 0x20): 0}, (s.pipe.uds, s.pipe.uavs) + s = stage() + s.exec_known = False + s.op_buffer_store_dword(['v4', 'v1', 's[16:19]', 's3'], ['offen']) + assert s.lines == ['a = ud0 + v1 + s3 + 0;', 'if (exec & 1) u0.Store(a, v4);'], s.lines + s = stage() + s.op_buffer_store_dwordx2(['v[4:5]', 'off', 's[16:19]', '0x40'], []) + assert s.lines == ['a = ud0 + 64;', 'u0.Store2(a, uint2(v4, v5));'], s.lines + print('store: feature off refused as before; address with uavbase, exec guard, literal soffset folded') + + refused(stage(), 'op_buffer_store_dwordx3', STORE, ['idxen'], 'modifier idxen') + refused(stage(), 'op_buffer_store_dwordx3', STORE, ['offen', 'tfe'], 'modifier tfe') + refused(stage(source=('vbtab',)), 'op_buffer_store_dwordx3', STORE, ['offen'], 'through vbtab') + # A buffer read and stored: a load before the store raises StoredSrv (translate_to rebuilds with the key in + # rw_keys); with it there, or after a store, loads go through the UAV at the uavbase-shifted address. + s = stage() + s.op_buffer_load_dword(['v8', 'v1', 's[16:19]', '0'], ['offen']) + try: + s.op_buffer_store_dwordx3(STORE, ['offen']) + except G.StoredSrv as conflict: + assert conflict.key == (('table', 0), 0x20), conflict.key + else: + raise AssertionError('store after an SRV read accepted without rw_keys') + s = stage() + s.pipe.rw_keys = {(('table', 0), 0x20)} + s.op_buffer_load_dword(['v8', 'v1', 's[16:19]', '0'], ['offen']) + s.op_buffer_store_dwordx3(STORE, ['offen']) + assert s.lines == ['a = ud0 + v1 + 0;', 'v8 = u0.Load(a + 0);', 'a = ud0 + v1 + 0;', 'u0.Store3(a, uint3(v4, v5, v6));'], s.lines + refused(s, 'op_buffer_load_dword', ['v8', 'v1', 's[16:19]', '0'], ['idxen'], 'indexed load through a buffer') + refused(s, 'op_tbuffer_load_format_x', ['v8', 'v1', 's[16:19]', '0'], ['offen', 'format:[BUF_FMT_8_UNORM]'], + 'typed load through a buffer the program stores to') + refused(s, 'op_s_buffer_load_dword', ['s0', 's[16:19]', '0x0'], [], 'read as an SRV and stored to as a UAV') + s = stage() + s.op_buffer_store_dwordx3(STORE, ['offen']) + s.op_buffer_load_dword(['v8', 'v1', 's[16:19]', '0'], ['offen']) + assert s.lines[-1] == 'v8 = u0.Load(a + 0);', s.lines + + # Descriptor edits: stride cleared (AND keeping [15:0] of word 1), records and word 3 changed -> accepted; + # word 0 or a word-1 edit touching the base -> refused. + for edits, ok in (([(1, 's_and_b32', ('0xc000ffff',)), (2, 's_mul_i32', ('s10',)), (3, 's_or_b32', ('0x30000000',))], True), + ([(0, 's_add_u32', ('0x10',))], False), ([(1, 's_and_b32', ('0xc0000fff',))], False), + ([(1, 's_or_b32', ('0x10000',))], False)): + s = stage() + s.pipe.modified.add((('table', 0), 0x20)) + s.pipe.modified_words = {(('table', 0), 0x20): edits} + if ok: + s.op_buffer_store_dwordx3(['v[1:3]', 'off', 's[16:19]', 's13'], []) + assert s.lines[-1] == 'u0.Store3(a, uint3(v1, v2, v3));', s.lines + else: + refused(s, 'op_buffer_store_dwordx3', ['v[1:3]', 'off', 's[16:19]', 's13'], [], 'modified descriptor') + pipe = Pipe(('uav',)) + for n in range(8): + pipe.uav((('table', 0), 0x100 * (n + 1))) + refused(stage(pipe=pipe), 'op_buffer_store_dwordx3', ['v[4:6]', 'v1', 's[16:19]', '0'], ['offen'], 'more than 8 UAVs') + print('store: idxen, tfe, vertex buffer, ninth UAV refused; read+store through the UAV (retry signal, rw loads); base-keeping descriptor edits accepted, others refused') + + s = stage() + s.op_buffer_store_dwordx3(STORE, ['offen']) + p = s.pipe + p.resource((('table', 1), 0), 'buf') + fake = SimpleNamespace(uds=p.uds, resources=p.resources, uavs=p.uavs, heapvars=[], samplers={}, + uses_sampler_heap=False, params=[], ps=SimpleNamespace(exports={'mrt0': 1})) + manifest = G.Pipeline.manifest(fake).split('\n') + assert manifest[:5] == ['x2w-manifest 1', 'ud 1', 'udsrc 0 uavbase 0', 'srv 0 buf table 1 0', 'uav 0 buf table 0 32'], manifest + common = SimpleNamespace(helper_text='', uds=p.uds, resources=p.resources, uavs=p.uavs, samplers={}, heapvars=[], + uses_sampler_heap=False) + assert 'RWByteAddressBuffer u0 : register(u0);' in G.Pipeline.common(common) + print('manifest: uav line after the srv lines, uavbase entry; RWByteAddressBuffer declared') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_carry_dst_check.py b/tests/startup_carry_dst_check.py new file mode 100644 index 0000000000..d8f9e48d7d --- /dev/null +++ b/tests/startup_carry_dst_check.py @@ -0,0 +1,38 @@ +"""A carry-out or compare destination that is not an SGPR, vcc or exec is refused (it used to crash the translation). + +Synthetic VOP3B word: v_add_co_ci_u32_e64 v100, <sdst>, 0, v100, vcc_lo (op 0x128). With sdst vcc_hi (107) the +translator raised TypeError in write_compare (reg_range('vcc_hi') is None), which ends a whole translation as a +crash; it is now the refusal "compare or carry destination vcc_hi". Controls: sdst s20 is lowered and s20 becomes a +lane mask; sdst vcc_lo writes vcc. +""" +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_scalar_bits_check import asm, stage # noqa: E402 + + +def word(sdst): + return [0xd4000000 | 0x128 << 16 | sdst << 8 | 100, 128 | (256 + 100) << 9 | 106 << 18] + + +def main(): + assert asm(word(107)) == ['v_add_co_ci_u32_e64 v100, vcc_hi, 0, v100, vcc_lo'], asm(word(107)) + try: + stage(word(107)) + except G.Unsupported as error: + assert str(error) == 'compare or carry destination vcc_hi', str(error) + else: + raise AssertionError('vcc_hi carry-out accepted') + s = stage(word(20)) + assert 20 in s.masks, s.masks + s = stage(word(106)) + assert not s.masks + print('carry_dst: vcc_hi carry-out refused (was a TypeError crash); s20 and vcc_lo controls lowered') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_class_f16_sdwa_check.py b/tests/startup_class_f16_sdwa_check.py new file mode 100644 index 0000000000..d5a17e7c81 --- /dev/null +++ b/tests/startup_class_f16_sdwa_check.py @@ -0,0 +1,95 @@ +"""v_cmp_class_f16_sdwa: a binary16 value selected from a register, classified against a class-mask register. + +Synthetic VOPC SDWA words (word 0: src0 = 0xf9, vsrc1, op 0x8f = v_cmp_class_f16, 0x3e; word 1: src0, sdst | SD, +src0_sel, src0_neg, src0_abs, S0, src1_sel). SDWA source selection (AMD RDNA ISA, SDWA): the selected field is +zero-extended and the f16 op reads bits [15:0], so WORD_1 classifies the high half; neg/abs act on bit 15 of the +selected value. The emitted HLSL is checked as text, and its value is evaluated with a Python model of the ten class +bits (LLVM SIDefines.h ClassFlags order) for every field selection over sample halves. +Controls: a constant value is refused (its f16 inline form is not modelled); v_cmp_class_f32_sdwa is unchanged. +""" +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 vopc_sdwa(op, src0, vsrc1, sdst, src0_sel=6, src1_sel=6, neg0=False, abs0=False, s0=False): + w0 = 0xf9 | vsrc1 << 9 | op << 17 | 0x3e << 25 + w1 = src0 | (sdst | 0x80) << 8 | src0_sel << 16 | int(neg0) << 20 | int(abs0) << 21 | int(s0) << 23 \ + | src1_sel << 24 + return [w0, w1] + + +def one(words): + s = G.Stage(Pipe(), 'vs', b'') + s.lines = [] + _, n, name, text = G.decode(struct.pack('<2I', *words))[0] + s.pc = 0 + s.one(name, text) + return text, '\n'.join(s.lines) + + +def cls16(h): + e, m, neg = h >> 10 & 31, h & 0x3ff, h >> 15 & 1 + if e == 31: + return (1 if m & 0x200 else 0) if m else (2 if neg else 9) + if e == 0: + return (4 if neg else 7) if m else (5 if neg else 6) + return 3 if neg else 8 + + +def evaluate(expr, v1, v2): + """Evaluate the emitted uint expression in Python (x2w_class_f16 by the model, HLSL uint ops as Python ints).""" + py = expr.replace('u)', ')').replace('u ', ' ') + py = re.sub(r'(0x[0-9a-f]+|\d+)u\b', r'\1', py) + return eval(py, {'v1': v1, 'v2': v2, 'x2w_class_f16': lambda x, mask: mask >> cls16(x & 0xffff) & 1}) + + +def main(): + halves = [0x0000, 0x8000, 0x0001, 0x8001, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7e00, 0x7d00, 0x03ff, 0xfbff] + sels = {0: 'BYTE_0', 1: 'BYTE_1', 4: 'WORD_0', 5: 'WORD_1', 6: 'DWORD'} + checked = 0 + for sel, name in sels.items(): + for neg, ab in ((False, False), (True, False), (False, True), (True, True)): + text, body = one(vopc_sdwa(0x8f, 1, 2, 38, src0_sel=sel, neg0=neg, abs0=ab)) + shown = '-|v1|' if neg and ab else '-v1' if neg else '|v1|' if ab else 'v1' + assert text == 'v_cmp_class_f16_sdwa s38, %s, v2 src0_sel:%s src1_sel:DWORD' % (shown, name), text + m = re.fullmatch(r's38 = (.*);', body) + assert m and 'x2w_class_f16(' in body, body + for lo in halves: + for hi in halves: + v1 = hi << 16 | lo + off, width = G.SDWA_SEL[name] + field = (v1 >> off) & ((1 << width) - 1) + h = field & 0xffff + h = h & 0x7fff if ab else h # abs first, then neg (-|x| is negative) + h = h ^ 0x8000 if neg else h + for bit in range(10): + assert evaluate(m.group(1), v1, 1 << bit) == int(cls16(h) == bit), (name, neg, ab, hex(v1)) + checked += 1 + _, body = one(vopc_sdwa(0x8f, 1, 2, 38, src0_sel=5)) + assert body == 's38 = x2w_class_f16(((v1 >> 16u) & 0xffffu), v2);', body + try: + one(vopc_sdwa(0x8f, 240, 2, 38, s0=True)) # constant 0.5 + except G.Unsupported as error: + assert 'f16 value operand' in str(error), str(error) + else: + raise AssertionError('constant f16 class value accepted') + text, body = one(vopc_sdwa(0x88, 128, 6, 38, src1_sel=1, neg0=True, s0=True)) + assert body == 's38 = x2w_class_f32((0x00000000u ^ 0x80000000u), ((v6 >> 8u) & 0xffu));', body + print('class_f16 sdwa: %d (selection, modifier, value, class) cases match the class model; WORD_1 reads the ' + 'high half; constant value refused; f32 control unchanged' % checked) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_class_sdwa_check.py b/tests/startup_class_sdwa_check.py new file mode 100644 index 0000000000..52f2e5d459 --- /dev/null +++ b/tests/startup_class_sdwa_check.py @@ -0,0 +1,81 @@ +"""v_cmp_class_f32_sdwa: a constant f32 value classified against a byte of a register (src1_sel:BYTE_1). + +Synthetic VOPC SDWA words (word 0: src0 = 0xf9, vsrc1, op 0x88, 0x3e; word 1: src0, sdst | SD, src0_sel, src0_neg, +S0, src1_sel). A compiler tests single bits of a byte with it: class(-0.0) is mask bit 5, class(-denormal 0x80000001) +bit 4, class(0xffffffff, a quiet NaN) bit 1 (class bits: LLVM SIDefines.h ClassFlags, the order x2w_class_f32 +uses). The emitted HLSL is checked as text and its value computed with a Python model of the class bits. +Controls: src0_sel other than DWORD is refused, and an integer SDWA compare keeps its old lowering. +""" +import math +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 vopc_sdwa(op, src0, vsrc1, sdst, src0_sel=6, src1_sel=1, neg0=False, s0=True): + w0 = 0xf9 | vsrc1 << 9 | op << 17 | 0x3e << 25 + w1 = src0 | (sdst | 0x80) << 8 | src0_sel << 16 | int(neg0) << 20 | int(s0) << 23 | src1_sel << 24 + return [w0, w1] + + +def one(words): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + _, n, name, text = G.decode(struct.pack('<2I', *words))[0] + s.pc = 0 + s.one(name, text) + return text, '\n'.join(s.lines) + + +def cls(bits): + """Class bit index of an f32 bit pattern: 0 sNaN, 1 qNaN, 2 -inf, 3 -normal, 4 -denormal, 5 -0, 6 +0, 7 +denormal, + 8 +normal, 9 +inf.""" + e, m, neg = bits >> 23 & 255, bits & 0x7fffff, bits >> 31 + if e == 255: + return (1 if m & 0x400000 else 0) if m else (2 if neg else 9) + if e == 0: + return (4 if neg else 7) if m else (5 if neg else 6) + return 3 if neg else 8 + + +def main(): + cases = [(128, True, 'neg(0)', '(0x00000000u ^ 0x80000000u)', 5), + (129, True, 'neg(1)', '(0x00000001u ^ 0x80000000u)', 4), + (193, False, '-1', '0xffffffffu', 1)] + for src0, neg, shown, value, bit in cases: + text, body = one(vopc_sdwa(0x88, src0, 6, 38, neg0=neg)) + assert text == 'v_cmp_class_f32_sdwa s38, %s, v6 src0_sel:DWORD src1_sel:BYTE_1' % shown, text + want = 's38 = x2w_class_f32(%s, ((v6 >> 8u) & 0xffu));' % value + assert body == want, (body, want) + bits = int(re.sub(r'u', '', value.strip('()').split(' ^ ')[0]), 16) ^ (0x80000000 if neg else 0) + assert cls(bits) == bit, (shown, cls(bits)) + # the result is mask bit `bit` of byte 1 of v6 + for v6 in (0, 1 << (8 + bit), 0xff00 ^ 1 << (8 + bit), 0xffffffff): + assert (((v6 >> 8) & 0xff) >> cls(bits) & 1) == (v6 >> (8 + bit) & 1) + assert math.isnan(struct.unpack('<f', struct.pack('<I', 0xffffffff))[0]) + try: + one(vopc_sdwa(0x88, 6, 7, 38, src0_sel=1, s0=False)) # src0 v6 BYTE_1 + except G.Unsupported as error: + assert 'sub-dword f32 value' in str(error), str(error) + else: + raise AssertionError('sub-dword f32 class value accepted') + text, body = one(vopc_sdwa(0x84, 6, 7, 38, src0_sel=0, src1_sel=0, s0=False)) # v_cmp_gt_i32 BYTE_0, BYTE_0 + assert text.startswith('v_cmp_gt_i32_sdwa s38, v6, v7'), text + assert body == 's38 = ((int(((v6 >> 0u) & 0xffu)) > int(((v7 >> 0u) & 0xffu))) ? 1u : 0u);', body + print('class sdwa: -0.0 / -denormal / NaN against byte 1 of v6 (bits 5, 4, 1); sub-dword value refused; ' + 'integer SDWA control unchanged') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_clear_depth_stencil.cpp b/tests/startup_clear_depth_stencil.cpp index 50eadb6981..521a1a8373 100644 --- a/tests/startup_clear_depth_stencil.cpp +++ b/tests/startup_clear_depth_stencil.cpp @@ -102,12 +102,12 @@ struct Probe { SUCCEEDED(queue1->RegisterMessageCallback(on_message, D3D12_MESSAGE_CALLBACK_FLAG_NONE, nullptr, &cookie)); } - bool readback_depth(ID3D12Resource* target, UINT width, UINT height, std::vector<float>& out) + bool readback_depth(ID3D12Resource* target, UINT width, UINT height, std::vector<float>& out, UINT subresource = 0) { D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; UINT64 total = 0; const auto desc = target->GetDesc(); - desktop->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + desktop->GetCopyableFootprints(&desc, subresource, 1, 0, &footprint, nullptr, nullptr, &total); D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, total, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, @@ -132,6 +132,7 @@ struct Probe { D3D12_TEXTURE_COPY_LOCATION to{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; to.PlacedFootprint = footprint; D3D12_TEXTURE_COPY_LOCATION from{target, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + from.SubresourceIndex = subresource; copy->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); transition(copy.Get(), target, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); @@ -237,7 +238,7 @@ int main(int argc, char** argv) const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; Word backing, bytes; - } dsv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, 0, 0}, + } dsv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 6, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, 0, 0}, rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, 0, 0}; void* dsv_heap = nullptr; @@ -306,6 +307,29 @@ int main(int argc, char** argv) clear_dsv(list, handle_a, static_cast<D3D12_CLEAR_FLAGS>(0), 0.5f, 0, 0, nullptr); if (!check_count("6 zero clear flags", seen, 0)) return 15; + ComPtr<ID3D12Resource> mixed; + auto mixed_desc = depth_desc(8, 8); + mixed_desc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; + mixed_desc.MipLevels = 2; + mixed_desc.DepthOrArraySize = 2; + if (FAILED(probe.desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &mixed_desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&mixed)))) return 22; + unsigned before_binds = 0, after_binds = 0; + x2w_d3d12_render_target_stats(&before_binds, nullptr); + for (UINT i = 0; i < 2; ++i) { + D3D12_DEPTH_STENCIL_VIEW_DESC view{}; + view.Format = mixed_desc.Format; + view.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; + view.Texture2DArray.ArraySize = 2; + view.Flags = i ? D3D12_DSV_FLAG_READ_ONLY_STENCIL : D3D12_DSV_FLAG_READ_ONLY_DEPTH; + const D3D12_CPU_DESCRIPTOR_HANDLE handle{static_cast<SIZE_T>(dsv_cpu + (4 + i) * dsv_stride)}; + invoke(device, 21, arg(mixed.Get()), arg(&view), handle.ptr); + invoke(list, 50, 0, 0, FALSE, arg(&handle)); + clear_dsv(list, handle, i ? D3D12_CLEAR_FLAG_DEPTH : D3D12_CLEAR_FLAG_STENCIL, 0.5f, 7, 0, nullptr); + } + x2w_d3d12_render_target_stats(&after_binds, nullptr); + if (after_binds != before_binds + 2) return 23; + // Close and submit invoke(list, 9); if (!probe.submit(list)) return 16; @@ -323,6 +347,17 @@ int main(int argc, char** argv) if (values_b[i] != 0.75f) return 20; } + // Read the first texel from both planes of each array layer after alternating their write masks. + for (UINT slice = 0; slice < 2; ++slice) { + std::vector<float> depth, stencil; + if (!probe.readback_depth(mixed.Get(), 1, 1, depth, 2 * slice) || + !probe.readback_depth(mixed.Get(), 1, 1, stencil, 4 + 2 * slice)) return 24; + UINT d = 0, s = 0; + std::memcpy(&d, depth.data(), sizeof(d)); + std::memcpy(&s, stencil.data(), sizeof(s)); + std::printf("mixed D24S8 slice %u: depth %08x stencil %08x\n", slice, d, s); + if ((d & 0xffffff) != 0x800000 || (s & 0xff) != 7) return 25; + } const HRESULT removed = probe.desktop->GetDeviceRemovedReason(); const unsigned long long errors = debug_error_count.load(); std::printf("device removed reason: 0x%08lx, debug layer errors: %llu\n", static_cast<unsigned long>(removed), diff --git a/tests/startup_clip_distance_check.py b/tests/startup_clip_distance_check.py new file mode 100644 index 0000000000..92f06233c6 --- /dev/null +++ b/tests/startup_clip_distance_check.py @@ -0,0 +1,58 @@ +"""Check vertex clip distance exports and reject incompatible declarations.""" +import os +import struct +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import PS_WORDS, root_blob # noqa: E402 + +VS = struct.pack('<7I', 0x7e0802f2, 0x7e0a0280, # v_mov_b32 v4, 1.0 ; v_mov_b32 v5, 0 + 0xf80000cf, 0x04050504, # exp pos0 v4, v5, v5, v4 + 0xf80008d3, 0x00000504, # exp pos1 v4, v5, off, off done + 0xbf810000) +GOOD = 0x01400303 + + +def refused(cntl, why): + try: + G.Pipeline(VS, PS_WORDS, root_blob(), vs_out_cntl=cntl).hlsl_vs() + except G.Unsupported as error: + assert why in str(error), (why, str(error)) + else: + raise AssertionError('accepted PA_CL_VS_OUT_CNTL %r' % cntl) + + +def main(): + text = [x[3] for x in G.decode(VS)] + assert text[2] == 'exp pos0 v4, v5, v5, v4' and text[3] == 'exp pos1 v4, v5, off, off done', text + refused(None, 'export target pos1') + pipe = G.Pipeline(VS, PS_WORDS, root_blob(), vs_out_cntl=GOOD) + vs, ps = pipe.hlsl_vs(), pipe.hlsl_ps() + for line in (' float2 clip0 : SV_ClipDistance0;', 'o.clip0 = float2(F(v4), F(v5));', + ' o.clip0 = p.clip0 + r.clip0 - q.clip0;'): + assert line in vs, (line, vs) + assert ' float2 clip0 : SV_ClipDistance0;' in ps, ps + with tempfile.TemporaryDirectory() as d: + result = G.translate_to(d, 1, VS, PS_WORDS, root_blob(), vs_out_cntl=GOOD) + assert result == 'ok', result + assert os.path.getsize(os.path.join(d, '%016x.vs.cso' % 1)) > 0 + for content, ok in (('pa_cl_vs_out_cntl 1 01400303\n', True), ('pa_cl_vs_out_cntl 1 1400303\n', False)): + p = os.path.join(d, 'x.vsout') + open(p, 'w', newline='\n').write(content) + try: + assert G.read_vs_out(p) == GOOD and ok + except G.Unsupported as error: + assert not ok and 'invalid vertex output control file' in str(error), str(error) + refused(GOOD | 1 << 21, 'PA_CL_VS_OUT_CNTL') # misc vector first: pos1 is not the distances + refused(0x00400300, 'PA_CL_VS_OUT_CNTL') # cull distances only + refused(0x00400307, 'PA_CL_VS_OUT_CNTL') # three clip distances, two channels written + refused(GOOD | 1 << 23, 'PA_CL_VS_OUT_CNTL') # a second distance vector + refused(GOOD & ~(1 << 22), 'PA_CL_VS_OUT_CNTL') # no distance vector enabled + print('clip distance: pos1 refused without .vsout; 0x01400303 -> SV_ClipDistance0 float2, FXC ok; 5 refusals') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_counted_search_check.py b/tests/startup_counted_search_check.py new file mode 100644 index 0000000000..e063a73b7e --- /dev/null +++ b/tests/startup_counted_search_check.py @@ -0,0 +1,36 @@ +"""Check the unsigned bound on a pixel search emitted as a dynamic loop.""" +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G + + +def check(compare='scc = s15 >= s11;', step='s15 = s15 + 0x00000001u;', extra=(), expected=True): + stage = G.Stage.__new__(G.Stage) + stage.require_counted_search = True + stage.blocks = [ + (0, [compare], ('branch', '!scc', 2)), + (1, [], ('jump', 4)), + (2, list(extra), ('branch', '!scc', 4)), + (3, [step], ('jump', 0)), + (4, [], ('end',)), + ] + try: + body = stage.body() + except G.Unsupported as reason: + assert not expected and 'no proven unsigned iteration bound' in str(reason) + else: + assert expected and any('[loop] while' in line for line in body) + assert all('guard <' not in line for line in body) + + +if __name__ == '__main__': + check(extra=['s24 = s10 + s15;']) + check(compare='scc = s15 > s11;', expected=False) + check(compare='scc = s15 >= s15;', expected=False) + check(step='s15 = s15 + 0x00000002u;', expected=False) + check(extra=['s11 = s10 + s15;'], expected=False) + check(extra=['s15 -= 4u;'], expected=False) + check(extra=['foo(s11);'], expected=False) + print('Counted search and six malformed-loop controls passed.') diff --git a/tests/startup_cselect_vcc_lo_check.py b/tests/startup_cselect_vcc_lo_check.py new file mode 100644 index 0000000000..2ea7dc516f --- /dev/null +++ b/tests/startup_cselect_vcc_lo_check.py @@ -0,0 +1,52 @@ +"""s_cselect_b32 into vcc_lo (wave32 lane mask) and into a non-SGPR destination. + +Synthetic words. In wave32, vcc_lo is the whole VCC lane mask, so `s_cselect_b32 vcc_lo, -1, 0` sets the lane's +VCC bit from SCC, as the generic scalar path already treats vcc_lo. Before this the select path assumed an SGPR +destination and raised a TypeError. Control: s_cselect_b32 into an SGPR is unchanged; into m0 it is refused. +""" +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 one(word): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + _, n, name, text = G.decode(struct.pack('<I', word))[0] + s.pc = 0 + s.one(name, text) + return text, '\n'.join(s.lines) + + +SOP2_CSELECT_B32 = 0x80000000 | 10 << 23 # s_cselect_b32 sdst, ssrc0, ssrc1 + + +def main(): + # SOP2: sdst [22:16], ssrc1 [15:8], ssrc0 [7:0] + text, body = one(SOP2_CSELECT_B32 | 106 << 16 | 128 << 8 | 193) # vcc_lo, -1, 0 + assert text == 's_cselect_b32 vcc_lo, -1, 0', text + assert body == 'vcc = (scc ? 0xffffffffu : 0x00000000u) & 1;', body + text, body = one(SOP2_CSELECT_B32 | 5 << 16 | 193 << 8 | 128) # s5, 0, -1 + assert text == 's_cselect_b32 s5, 0, -1', text + assert 'scc ? 0x00000000u : 0xffffffffu' in body and 'vcc' not in body, body + try: + one(SOP2_CSELECT_B32 | 124 << 16 | 128 << 8 | 193) # m0, -1, 0 + except G.Unsupported as error: + assert 's_cselect into m0' in str(error), str(error) + else: + raise AssertionError('s_cselect into m0 accepted') + print('cselect: vcc_lo is the lane mask; SGPR destination unchanged; m0 refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_cx_async.cpp b/tests/startup_cx_async.cpp new file mode 100644 index 0000000000..f3be0108d9 --- /dev/null +++ b/tests/startup_cx_async.cpp @@ -0,0 +1,850 @@ +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <algorithm> +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <iterator> +#include <string> +#include <vector> + +#include "startup_cx_async_cs.h" +#include "startup_cx_heap_cs.h" +#include "startup_cx_heap_bench_cs.h" +#include "startup_cx_heap_raw_cs.h" +#include "startup_cx_heap_words_cs.h" // LOCAL isa-gaps +#include "startup_cx_sampler_cs.h" + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Word = std::uint64_t; +template <class T> Word arg(T* value) { return reinterpret_cast<Word>(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word); + return reinterpret_cast<Slot>((*static_cast<void***>(object))[index])(object, a, b, c, d, e, f); +} +bool ok(Word hr) { return SUCCEEDED(static_cast<HRESULT>(hr)); } +std::uint64_t fnv(const void* data, std::size_t bytes, std::uint64_t hash = 1469598103934665603ull) +{ + for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ static_cast<const unsigned char*>(data)[i]) * 1099511628211ull; + return hash; +} +bool write_file(const std::wstring& path, const void* data, std::size_t bytes) +{ + FILE* f = _wfopen(path.c_str(), L"wb"); + if (!f) return false; + const bool written = std::fwrite(data, 1, bytes, f) == bytes; + return std::fclose(f) == 0 && written; +} +std::string read_log(const std::wstring& path) +{ + std::ifstream file(path, std::ios::binary); + return std::string{std::istreambuf_iterator<char>(file), {}}; +} +HANDLE hold_event; +DWORD WINAPI release_later(void*) +{ + Sleep(300); + SetEvent(hold_event); + return 0; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) return 2; + const std::string mode = argv[2]; + if (mode != "async" && mode != "sync" && mode != "known" && mode != "seen" && mode != "heap" && mode != "sampler" && mode != "rawheap" && + mode != "rawheap-off" && mode != "rawheap-reset" && mode != "rawheap-late" && mode != "rawheap-bench" && mode != "slow" && mode != "slow-off" && + mode != "heapwords" && mode != "heapwords-raw") + return 2; + const bool slow = mode == "slow" || mode == "slow-off"; + const bool heapwords = mode.rfind("heapwords", 0) == 0; + const bool heapwords_raw = mode == "heapwords-raw"; // LOCAL isa-gaps: `heapwords 1` (the rawheap heap, d3d12_vdesc.inl words) + const bool rawheap = mode.rfind("rawheap", 0) == 0 || heapwords; // LOCAL: `heapraw 1` (d3d12_heap_raw.inl) + if (rawheap) { + SetEnvironmentVariableW(L"X2W_BUFFER_HEAP_INDEX", L"1"); + SetEnvironmentVariableW(L"X2W_HEAP_RAW", mode == "rawheap-off" ? L"0" : nullptr); + const bool reset_like = mode == "rawheap-reset" || mode == "rawheap-late"; + SetEnvironmentVariableW(L"X2W_HEAP_RAW_TEST_ENTRIES", reset_like ? L"16" : nullptr); + SetEnvironmentVariableW(L"X2W_HEAP_RAW_TIMES", reset_like ? L"1" : nullptr); + // The sweep thread's part waited for (results in the same frame, as an inline sweep): the late staging copy is + // resolved by the drain of the frame that copied it. rawheap-bench runs the thread as a title run does. + SetEnvironmentVariableW(L"X2W_HEAP_RAW_SWEEP_SYNC", mode == "rawheap-reset" ? L"1" : nullptr); + } + const bool bench = mode == "rawheap-bench"; // LOCAL: drain / eviction timings (X2W_BENCH_*: see the bench block) + if (bench) { + wchar_t entries[16] = L"16384"; + GetEnvironmentVariableW(L"X2W_BENCH_ENTRIES", entries, 16); // 0: the runtime's own table size + SetEnvironmentVariableW(L"X2W_HEAP_RAW_TEST_ENTRIES", std::wcscmp(entries, L"0") ? entries : nullptr); + SetEnvironmentVariableW(L"X2W_HEAP_RAW_TIMES", L"1"); + } + const bool sampler = mode == "sampler"; + if (sampler) SetEnvironmentVariableW(L"X2W_SAMPLER_LOD", L"1"); + const bool async = mode == "async"; + const bool heap = mode == "heap" || rawheap; // LOCAL meshrt: `heap 1`, HeapMain, a 4-slot title view heap (no hold) + const bool prewarm = mode == "known" || mode == "seen"; // X2W_CX_PREWARM_ALL (no hold) + ComPtr<IDXGIFactory6> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr<IDXGIAdapter> adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr<IDXGIAdapter1> candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) 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 (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + LARGE_INTEGER driver{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls driver=%u.%u.%u.%u mode=%s\n", adapter_desc.Description, HIWORD(driver.HighPart), LOWORD(driver.HighPart), + HIWORD(driver.LowPart), LOWORD(driver.LowPart), mode.c_str()); + { // existing heaps over process memory (the windows); a probe device only + ComPtr<ID3D12Device3> desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 4; + void* block = VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + ComPtr<ID3D12Heap> heap; + const HRESULT hr = block ? desktop->OpenExistingHeapFromAddress(block, IID_PPV_ARGS(&heap)) : E_OUTOFMEMORY; + heap.Reset(); + if (block) VirtualFree(block, 0, MEM_RELEASE); + if (FAILED(hr)) { + std::printf("OpenExistingHeapFromAddress -> 0x%08lx: capability skip\n", static_cast<unsigned long>(hr)); + return 77; + } + } + + // Shader cache, log and hold event of this process (process id + tick count: never an earlier run's files). + wchar_t temp[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, temp)) return 5; + const std::wstring tag = std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(GetTickCount64()); + const std::wstring cache = std::wstring(temp) + L"x2w_cx_async_" + tag; + CreateDirectoryW(cache.c_str(), nullptr); + SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()); + const std::wstring log_path = cache + L"\\trap.log"; + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + const std::wstring event_name = L"Local\\x2w_cx_hold_" + tag; + hold_event = CreateEventW(nullptr, TRUE, FALSE, event_name.c_str()); + if (!hold_event) return 5; + if (!prewarm && !heap && !sampler && !slow) SetEnvironmentVariableW(L"X2W_CX_TEST_HOLD_EVENT", event_name.c_str()); + + // The title's compute root signature (its bytes go into the key; the translated one comes from the manifest). + D3D12_ROOT_PARAMETER title_params[2]{}; + D3D12_DESCRIPTOR_RANGE title_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + title_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + title_params[1].DescriptorTable = {1, &title_range}; + title_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + const D3D12_ROOT_SIGNATURE_DESC title_root_desc{sampler ? 2u : 1u, title_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> title_blob; + if (FAILED(D3D12SerializeRootSignature(&title_root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &title_blob, nullptr))) return 5; + static unsigned char code[192]; // fake console code (the stand-in only hashes it) + for (int i = 0; i < 192; ++i) code[i] = static_cast<unsigned char>(0x3B ^ (i * 5)); + const std::uint64_t key = (fnv(title_blob->GetBufferPointer(), title_blob->GetBufferSize(), fnv(code, sizeof(code))) & 0x00ffffffffffffffull) | + (0x67ull << 56); + char key_text[24]; + std::snprintf(key_text, sizeof(key_text), "%016llx", static_cast<unsigned long long>(key)); + std::printf("compute key %s\n", key_text); + // known / seen: a second cached translation (key B, never created or dispatched); seen: a keys-seen file of + // B and C (C has no translation), so only B is queued at start and the file afterwards holds A, B and C. + const std::uint64_t key_b = key ^ 0x10, key_c = 0x67000000000000c0ull; + // slow / slow-off: S (slow, 6 s more) and T (normal) sort before key A (same size, smaller keys), so the one + // background worker takes S first, T and A wait behind it. + const std::uint64_t key_s = 0x6700000000000001ull, key_t = 0x6700000000000002ull; + char s_text[24], t_text[24]; + std::snprintf(s_text, sizeof(s_text), "%016llx", static_cast<unsigned long long>(key_s)); + std::snprintf(t_text, sizeof(t_text), "%016llx", static_cast<unsigned long long>(key_t)); + if (slow) { + const std::string slow_spec = std::string(s_text) + ":6000"; + SetEnvironmentVariableA("X2W_CX_TEST_SLOW_KEY", slow_spec.c_str()); + } + for (const std::uint64_t k : {key, key_b, key_s, key_t}) { + if (k == key_b && !prewarm) continue; + if ((k == key_s || k == key_t) && !slow) continue; + wchar_t name[24]; + swprintf(name, 24, L"%016llx", static_cast<unsigned long long>(k)); + const std::wstring base = cache + L"\\" + name; + const std::string manifest = sampler ? "cs 1 1 1\nuav 0 buf root 0 0\nsrv 1 tex2d table 1 0\ncssampler 1\n" + : heapwords_raw ? "cs 1 1 1\nuav 0 buf root 0 0\nheap 1\nheapraw 1\nheapwords 1\n" + : heapwords ? "cs 1 1 1\nuav 0 buf root 0 0\nheap 1\nheapwords 1\n" + : rawheap ? "cs 1 1 1\nuav 0 buf root 0 0\nheap 1\nheapraw 1\n" + : heap ? "cs 1 1 1\nuav 0 buf root 0 0\nheap 1\n" : "cs 1 1 1\nuav 0 buf root 0 0\n"; + if (!(sampler ? write_file(base + L".cs.cso", startup_cx_sampler_cs, sizeof(startup_cx_sampler_cs)) + : bench ? write_file(base + L".cs.cso", startup_cx_heap_bench_cs, sizeof(startup_cx_heap_bench_cs)) + : heapwords ? write_file(base + L".cs.cso", startup_cx_heap_words_cs, sizeof(startup_cx_heap_words_cs)) + : rawheap ? write_file(base + L".cs.cso", startup_cx_heap_raw_cs, sizeof(startup_cx_heap_raw_cs)) + : heap ? write_file(base + L".cs.cso", startup_cx_heap_cs, sizeof(startup_cx_heap_cs)) + : write_file(base + L".cs.cso", startup_cx_async_cs, sizeof(startup_cx_async_cs))) || + !write_file(base + L".cs.txt", manifest.data(), manifest.size())) + return 5; + } + const auto key_line = [](std::uint64_t k) { + char text[24]; + std::snprintf(text, sizeof(text), "%016llx\n", static_cast<unsigned long long>(k)); + return std::string(text); + }; + const std::wstring seen_path = cache + L"\\cx_keys_seen.lst"; + if (mode == "seen") { + const std::string seen = key_line(key_b) + key_line(key_c); + if (!write_file(seen_path, seen.data(), seen.size())) return 5; + } + + std::array<unsigned char, 64> device_parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), device_parameters.data(), __uuidof(ID3D12Device), &device))) return 6; + ComPtr<ID3D12Device> desktop; // the same device object as the stand-in's (one device per adapter) + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 6; + // known / seen: the start prewarm loads the known keys before the title creates anything (at most 15 s). + const std::string all_loaded = std::string("x2w-cx prewarm: all ") + (mode == "known" ? "2" : "1") + " known pipelines loaded"; + if (prewarm) { + bool loaded = false; + for (int i = 0; i < 300 && !loaded; ++i) { + loaded = read_log(log_path).find(all_loaded) != std::string::npos; + if (!loaded) Sleep(50); + } + std::printf("start prewarm: \"%s\" %s\n", all_loaded.c_str(), loaded ? "seen" : "NOT seen within 15 s"); + if (!loaded) return 9; + } + void *title_root = nullptr, *pipeline = nullptr; + if (!ok(invoke(device, 16, 0, arg(title_blob->GetBufferPointer()), title_blob->GetBufferSize(), arg(&__uuidof(ID3D12RootSignature)), arg(&title_root)))) + return 7; + // The slot-67 record: [0] root signature, [5]/[6] code. Creation queues the key for the prewarm workers, whose + // load now waits for the event. + alignas(8) static unsigned char record[0x300]; + Word record_words[9] = {}; + record_words[0] = arg(title_root); + record_words[5] = arg(code), record_words[6] = sizeof(code); + std::memcpy(record, record_words, sizeof(record_words)); + if (!ok(invoke(device, 67, arg(record), arg(&__uuidof(ID3D12PipelineState)), arg(&pipeline))) || !pipeline) return 8; + + // Title memory: 2 MiB, word 0 the counter; a placed buffer over all of it (the window the UAV is made on; a root + // UAV is bound over the readable bytes from its address, at most 1 MiB, which must lie inside one window). + auto* memory = static_cast<std::uint32_t*>(VirtualAlloc(nullptr, 2u << 20, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!memory) return 10; + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 2u << 20, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + void* placed = nullptr; + if (!ok(invoke(device, 133, arg(memory), arg(&buffer), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&placed)))) return 11; + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *queue = nullptr, *fence = nullptr, *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 13; + void *sampler_heap = nullptr, *image_heap = nullptr; + Word fence_value = 0; + // One list of `dispatches` Dispatch(1, 1, 1), executed and waited for. + const auto run_list = [&](int dispatches) { + invoke(list, 139, arg(allocator)); // Reset + if (image_heap) { + void* heaps[]{image_heap, sampler_heap}; + invoke(list, 32, sampler_heap ? 2 : 1, arg(heaps)); + } + invoke(list, 33, arg(title_root)); // SetComputeRootSignature + if (image_heap) invoke(list, 35, 1, invoke(image_heap, 10)); + invoke(list, 25, arg(pipeline)); // SetPipelineState (the slot-67 pipeline) + invoke(list, 45, 0, arg(memory)); // SetComputeRootUnorderedAccessView(0, title address) + for (int i = 0; i < dispatches; ++i) invoke(list, 14, 1, 1, 1); + invoke(list, 9); // Close + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), ++fence_value))) return false; + const auto deadline = GetTickCount64() + 30000; + while (invoke(fence, 8) < fence_value) { + if (GetTickCount64() >= deadline) return false; + Sleep(1); + } + return true; + }; + + int failures = 0; + if (sampler) { + const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; Word backing, bytes; } views{ + {D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, arg(memory + 0x50000), 32}; + if (!ok(invoke(device, 14, arg(&views), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&image_heap)))) return 12; + const D3D12_RESOURCE_DESC image{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 2, 2, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, + {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN}; + void* texture = nullptr; + auto* pixels = VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + if (!pixels || !ok(invoke(device, 133, arg(pixels), arg(&image), D3D12_RESOURCE_STATE_COMMON, 0, + arg(&__uuidof(ID3D12Resource)), arg(&texture)))) return 12; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{image.Format, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Texture2D.MipLevels = 1; + invoke(device, 18, arg(texture), arg(&srv), invoke(image_heap, 9)); + if (!run_list(1) || memory[0] != 0) return 16; + auto* words = memory + 0x40000; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } hd{{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, arg(words), 32}; + if (!ok(invoke(device, 14, arg(&hd), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&sampler_heap))) || !sampler_heap) return 12; + words[4] = 0x1ff; // BORDER on U, V and W + words[7] = 2u << 30; + if (!run_list(1) || memory[0] != 255) return 16; + words[4] = 0x56573258; words[5] = UINT_MAX; + if (!run_list(1) || memory[0] != 255) return 16; + std::puts("PASS: compute sampled the white border; unbound and invalid-token dispatches refused"); + return 0; + } + if (bench) { + using u64 = std::uint64_t; + const auto env = [](const wchar_t* name, unsigned long fallback) { + wchar_t v[32] = L""; + const DWORD n = GetEnvironmentVariableW(name, v, 32); + return n && n < 32 ? std::wcstoul(v, nullptr, 10) : fallback; + }; + const unsigned long frames = env(L"X2W_BENCH_FRAMES", 40), ranges = env(L"X2W_BENCH_RANGES", 300), + vslots = env(L"X2W_BENCH_VSLOTS", 2000), slots = env(L"X2W_BENCH_SLOTS", 65536), + period = env(L"X2W_BENCH_PERIOD", 0), blocks = env(L"X2W_BENCH_BLOCKS", 4); + if (vslots + 8 > slots || !ranges || !blocks) return 2; + const u64 heap_bytes = u64{slots} * 32; + void* heap_memory = VirtualAlloc(nullptr, static_cast<SIZE_T>(heap_bytes), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, static_cast<UINT>(slots), D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + arg(heap_memory), heap_bytes}; + void* view_heap = nullptr; + if (!heap_memory || !ok(invoke(device, 14, arg(&heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&view_heap))) || !view_heap) + return 12; + constexpr u64 block_bytes = 32ull << 20; + std::vector<unsigned char*> data; + for (unsigned long b = 0; b < blocks; ++b) { + data.push_back(static_cast<unsigned char*>(VirtualAlloc(nullptr, block_bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))); + if (!data.back()) return 12; + auto* d = reinterpret_cast<std::uint32_t*>(data.back()); // dword i: its own address >> 2 (the program checks it) + for (u64 i = 0; i < block_bytes / 4; ++i) d[i] = static_cast<std::uint32_t>((reinterpret_cast<u64>(d + i)) >> 2); + } + const Word cpu = invoke(view_heap, 9); + D3D12_RESOURCE_DESC rdesc{}; + rdesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rdesc.Width = block_bytes; + rdesc.Height = rdesc.DepthOrArraySize = rdesc.MipLevels = rdesc.SampleDesc.Count = 1; + rdesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + struct ViewAt { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + Word address; + Word tail[2]; + } v{}; + v.view = {DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + v.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + const auto mix = [](std::uint64_t x) { + x ^= x >> 33; + x *= 0xff51afd7ed558ccdull; + x ^= x >> 33; + return x; + }; + u64 cursor = 0, slot = 0; // byte cursor over the blocks, V# slot ring + const u64 space = block_bytes * blocks; + unsigned char planes[0x50] = {}, present[0x40] = {}; + LARGE_INTEGER f, t0, t1; + QueryPerformanceFrequency(&f); + double write_ms = 0; + const ULONGLONG started = GetTickCount64(); + unsigned long ring_checks = 0, ring_bad = 0; + for (unsigned long frame = 0; frame < frames; ++frame) { + if (period && frame % period == 0) cursor = 0; // ring: the same ranges again + const u64 salt = period ? frame % period : frame; + QueryPerformanceCounter(&t0); + // this frame's V#s; every 10th frame and the last check the whole ring (V#s of earlier frames, kept by the sweep) + const bool whole = frame + 1 == frames || frame % 10 == 9; + memory[1] = static_cast<std::uint32_t>(whole ? 0 : slot); + memory[2] = static_cast<std::uint32_t>(whole ? vslots : (std::min<u64>)(ranges, vslots)); + const std::uint32_t bad_before = memory[5]; + memory[3] = static_cast<std::uint32_t>(vslots); + for (unsigned long i = 0; i < ranges; ++i) { + const u64 bytes = 16 * (1 + mix(salt * 1000003ull + i) % 256); + if (cursor % block_bytes + bytes > block_bytes) cursor = (cursor / block_bytes + 1) * block_bytes; + if (cursor + bytes > space) cursor = 0; + v.view.Buffer.NumElements = static_cast<UINT>(bytes / 4); + v.address = arg(data[cursor / block_bytes] + cursor % block_bytes); + invoke(device, 70, arg(&rdesc), arg(&v), cpu + 32 * (8 + slot)); + cursor = (cursor + bytes + 255) & ~255ull; + slot = (slot + 1) % vslots; + } + QueryPerformanceCounter(&t1); + write_ms += static_cast<double>(t1.QuadPart - t0.QuadPart) * 1000.0 / static_cast<double>(f.QuadPart); + if (!run_list(1)) return 14; + if (whole) { + ++ring_checks; + ring_bad += memory[5] - bad_before; + } + invoke(queue, 32, 0, arg(planes), arg(present)); + } + const double wall = (GetTickCount64() - started) / 1000.0; + const std::string log = read_log(log_path); + if (log.find(std::string("x2w-cx ") + key_text + ": heap dispatch skipped: increment not 32") != std::string::npos) { + std::printf("heap dispatches need a 32-byte view increment: capability skip\n"); + return 77; + } + // The drain and eviction times the runtime logged (X2W_HEAP_RAW_TIMES=1). + const auto times = [&](const char* prefix, const char* number_after) { + std::vector<double> ms; + for (std::size_t p = log.find(prefix); p != std::string::npos; p = log.find(prefix, p + 1)) { + const std::size_t end = log.find('\n', p); + const std::string line = log.substr(p, end - p); + const std::size_t at = line.find(number_after); + if (at != std::string::npos) ms.push_back(std::strtod(line.c_str() + at + std::strlen(number_after), nullptr)); + } + return ms; + }; + const auto stats = [](const char* what, std::vector<double> ms, std::size_t skip) { + if (ms.size() <= skip) { + std::printf("%s: %zu samples\n", what, ms.size()); + return 0.0; + } + ms.erase(ms.begin(), ms.begin() + skip); + std::vector<double> sorted = ms; + std::sort(sorted.begin(), sorted.end()); + double sum = 0; + for (double x : ms) sum += x; + std::printf("%s: %zu samples (first %zu skipped), mean %.3f ms, p50 %.3f, p95 %.3f, max %.3f\n", what, ms.size(), skip, + sum / ms.size(), sorted[sorted.size() / 2], sorted[sorted.size() * 95 / 100], sorted.back()); + return sorted.back(); + }; + const std::vector<double> drains = times("x2w-heapraw drain time: ", "drain time: "); + const std::vector<double> work = times("x2w-heapraw frame work: ", "frame work: "); + std::printf("bench: %lu frames x %lu ranges (%s), %lu V# slots in a %lu-slot heap, %lu x 32 MiB data blocks; %.1f s wall, " + "slot-70 writes %.3f ms per frame\n", + frames, ranges, period ? "ring" : "fresh", vslots, slots, blocks, wall, write_ms / frames); + stats("drains (eviction included)", drains, 1); + stats("frame work (sweep and eviction, inside the drain)", work, 1); + for (const char* line : {"x2w-heapraw ranges:", "x2w-heapraw drain time", "x2w-heapraw frame work", "x2w-heapraw drains with work", "x2w-d3d12 time inside"}) { + const std::size_t p = log.rfind(line); + if (p != std::string::npos) std::printf("last: %s\n", log.substr(p, log.find('\n', p) - p).c_str()); + } + const bool counted = drains.size() == frames && (!frames || log.find("x2w-heapraw ranges:") != std::string::npos); + std::printf("drain lines %zu of %lu frames\n", drains.size(), frames); + // Correctness: every checked V# read its data (none missed or wrong), and the page cache agreed with + // desktop_range for every range (X2W_HEAP_RAW_CHECK=1). + const std::size_t c = log.rfind("check mismatches "); + const long mismatches = c == std::string::npos ? -1 : std::strtol(log.c_str() + c + 17, nullptr, 10); + std::printf("reads through V# slots: %u checked, %u wrong or missed; whole-ring reads: %lu of %lu slots each, %lu wrong or missed " + "in all; page cache check mismatches %ld\n", + memory[6], memory[5], ring_checks, vslots, ring_bad, mismatches); + // A miss is allowed only as a counted displacement of a recently seen entry (all probes occupied; the sweep + // brings it back within a pass), never from eviction. + const std::size_t d = log.rfind("(recent "); + const long recent = d == std::string::npos ? -1 : std::strtol(log.c_str() + d + 8, nullptr, 10); + std::printf("displaced recent entries %ld\n", recent); + if (static_cast<long>(memory[5]) > recent || memory[6] == 0 || mismatches != 0) ++failures; + if (desktop->GetDeviceRemovedReason() != S_OK || !counted || failures) return 16; + std::printf("PASS (timings are reported, not checked)\n"); + return 0; + } + if (rawheap) { + // A shader-visible 8-slot title view heap at title + 1 MiB (256 bytes); two private 64 KiB blocks no resource + // covers (two desktop windows): data (dwords 0xc0de0000 + i) and data2 (0xd2000000 + i). + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 10, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, arg(memory + 0x40000), 10 * 32}; + void* view_heap = nullptr; + if (!ok(invoke(device, 14, arg(&heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&view_heap))) || !view_heap) return 12; + auto* data = static_cast<std::uint32_t*>(VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + auto* data2 = static_cast<std::uint32_t*>(VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!data || !data2) return 12; + for (std::uint32_t i = 0; i < 64; ++i) data[i] = 0xc0de0000u + i, data2[i] = 0xd2000000u + i; + // Two adjacent private 64 KiB blocks (two allocations, so two desktop windows): pa dwords 0xa0000000 + i, pb + // 0xb000b000 + i. Slot 7's V# spans both (a paged entry). + auto* pa = static_cast<std::uint32_t*>(VirtualAlloc(nullptr, 2 * 65536, MEM_RESERVE, PAGE_NOACCESS)); + if (!pa || !VirtualFree(pa, 0, MEM_RELEASE)) return 12; + pa = static_cast<std::uint32_t*>(VirtualAlloc(pa, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + auto* pb = pa ? static_cast<std::uint32_t*>(VirtualAlloc(pa + 16384, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)) : nullptr; + if (!pa || !pb) return 12; + for (std::uint32_t i = 0; i < 16384; ++i) pa[i] = 0xa0000000u + i, pb[i] = 0xb000b000u + i; + const bool late = mode == "rawheap-late"; // the sweep thread as in a title run (no SYNC) + const bool reset = mode == "rawheap-reset" || late; + const bool on = mode != "rawheap-off"; + const Word cpu = invoke(view_heap, 9); // GetCPUDescriptorHandleForHeapStart: the title's slot 0 + D3D12_RESOURCE_DESC rdesc{}; + rdesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rdesc.Width = 65536; + rdesc.Height = rdesc.DepthOrArraySize = rdesc.MipLevels = rdesc.SampleDesc.Count = 1; + rdesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + struct ViewAt { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + Word address; + Word tail[2]; + } v{}; + static_assert(offsetof(ViewAt, address) == 0x28 && sizeof(ViewAt) == 0x40); + const D3D12_SHADER_RESOURCE_VIEW_DESC raw16 = [] { + D3D12_SHADER_RESOURCE_VIEW_DESC d{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + d.Buffer.NumElements = 4; + d.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + return d; + }(); + const auto memory_srv = [&](const D3D12_SHADER_RESOURCE_VIEW_DESC& view, Word address, int slot) { + v.view = view; + v.address = address; + invoke(device, 70, arg(&rdesc), arg(&v), cpu + 32 * slot); + }; + memory_srv(raw16, arg(data), 1); // slot 1: the runtime writes the V# + memory_srv(raw16, arg(data) + 2, 3); // slot 3: base not 4-aligned + memory_srv(raw16, arg(pa), 8); // slots 8 and 9: one window each + memory_srv(raw16, arg(pb), 9); + D3D12_SHADER_RESOURCE_VIEW_DESC raw32 = raw16; + raw32.Buffer.NumElements = 8; + memory_srv(raw32, arg(pa) + 0xfff0, 7); // slot 7: 32 bytes over both blocks + D3D12_SHADER_RESOURCE_VIEW_DESC structured{DXGI_FORMAT_UNKNOWN, D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + structured.Buffer.NumElements = 3; + structured.Buffer.StructureByteStride = 12; + memory_srv(structured, arg(data2), 4); // slot 4: structured, 3 x 12 bytes, the second window + D3D12_SHADER_RESOURCE_VIEW_DESC typed{DXGI_FORMAT_R32_UINT, D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + typed.Buffer.NumElements = 4; + memory_srv(typed, arg(data) + 128, 5); // slot 5: typed R32_UINT, 4 elements (data dwords 32..35) + // Slot 6: a view token, a raw SRV (slot 18) of the title buffer at byte 0xc0000, dword 0x70000001. + memory[0x30000] = 0x70000001u; + D3D12_SHADER_RESOURCE_VIEW_DESC token = raw16; + token.Buffer.FirstElement = 0x30000; + invoke(device, 18, arg(placed), arg(&token), cpu + 32 * 6); + auto* slots = reinterpret_cast<unsigned char*>(cpu); + const auto* w1 = reinterpret_cast<const std::uint32_t*>(slots + 32); + const auto* w4 = reinterpret_cast<const std::uint32_t*>(slots + 128); + const auto* w5 = reinterpret_cast<const std::uint32_t*>(slots + 160); + const auto* w6 = reinterpret_cast<const std::uint32_t*>(slots + 192); + std::printf("slot 1 words %08x %08x %08x %08x; slot 4 %08x %08x %08x %08x; slot 5 %08x %08x %08x %08x; slot 6 %08x %08x\n", w1[0], + w1[1], w1[2], w1[3], w4[0], w4[1], w4[2], w4[3], w5[0], w5[1], w5[2], w5[3], w6[0], w6[1]); + for (int i = 4; i < 32; ++i) memory[i] = 0x11111111u; + if (!reset) { + std::memcpy(slots + 64, slots + 32, 32); // slot 2: the title's own copy + if (heapwords) { // slot 3: a view token whose id has no view (the sentinel), then words never to be returned + const std::uint32_t bad[8] = {0x56573258u, 0xffffffffu, 0xbad00002u, 0xbad00003u, + 0xbad00004u, 0xbad00005u, 0xbad00006u, 0xbad00007u}; + std::memcpy(slots + 96, bad, 32); + } + if (!run_list(1)) return 14; + } + unsigned char first_v[32] = {}; + for (Word k = 1; reset && k <= 4; ++k) { // slot 2: a new V# before each dispatch, one frame each + unsigned char planes[0x50] = {}, present[0x40] = {}; + if (k > 1) invoke(queue, 32, 0, arg(planes), arg(present)); + memory_srv(raw16, arg(data) + 16 * k, 2); + if (k == (late ? 3 : 1)) std::memcpy(first_v, slots + 64, 32); + if (!run_list(1)) return 14; + } + if (reset) { // a late staging copy: an earlier slot-2 V# copied back with no note + unsigned char planes[0x50] = {}, present[0x40] = {}; + invoke(queue, 32, 0, arg(planes), arg(present)); + std::memcpy(slots + 64, first_v, 32); + if (!run_list(1)) return 14; + if (late) { // the thread's part of the copy frame is taken by the next frame's drain + invoke(queue, 32, 0, arg(planes), arg(present)); + if (!run_list(1)) return 14; + } + } + if (!reset) { // two empty console presents (queue slot 32) 5 s apart reach the heartbeat (report_heap_raw) + unsigned char planes[0x50] = {}, present[0x40] = {}; + invoke(queue, 32, 0, arg(planes), arg(present)); + Sleep(5200); + invoke(queue, 32, 0, arg(planes), arg(present)); + } + const std::string log = read_log(log_path); + const auto has = [&](const std::string& text) { return log.find(text) != std::string::npos; }; + if (has(std::string("x2w-cx ") + key_text + ": heap dispatch skipped: increment not 32")) { + std::printf("heap dispatches need a 32-byte view increment: capability skip\n"); + return memory[4] == 0x11111111u ? 77 : 16; + } + if (heapwords) { + const std::uint32_t want[12] = {w1[0], 16u, 0x30016facu, 16u, 0x30016facu, 0u, 0u, 0u, 17u, 0u, 16u, w1[3]}; + const char* what[12] = {"slot 1 word 0", "slot 1 word 2", "slot 1 word 3", "slot 2 word 2", "slot 2 word 3", + "slot 3 (token id 0xffffffff) word 0", "slot 3 word 2", "slot 0 word 0", "width idiom on slot 1", + "slot 6 (token) word 1 (printed only)", "slot 6 word 2 (vdesc)", "slot 6 word 3 (vdesc)"}; + for (int i = 0; i < 12; ++i) { + std::printf("%s: %08x (want %08x)\n", what[i], memory[4 + i], want[i]); + if (i != 9 && memory[4 + i] != want[i]) ++failures; + } + const bool vdesc_line = has("x2w-vdesc buffer ") && has(std::string("x2w-cx ") + key_text + ": heapwords 1: view descriptor words"); + std::printf("vdesc lines %d\n", vdesc_line); + if (!vdesc_line) ++failures; + const bool raw_line = has(std::string("x2w-cx ") + key_text + ": heapraw 1: raw V# table at t2 space1"); + std::printf("heapraw line %d (want %d)\n", raw_line, heapwords_raw); + if (raw_line != heapwords_raw) ++failures; + for (std::size_t p = log.find("x2w-vdesc"); p != std::string::npos; p = log.find("x2w-vdesc", p + 1)) { + const std::size_t end = log.find('\n', p); + std::printf("%s\n", log.substr(p, end == std::string::npos ? std::string::npos : end - p).c_str()); + } + for (std::size_t p = log.find("x2w-d3d12-debug"); p != std::string::npos; p = log.find("x2w-d3d12-debug", p + 1)) { + const std::size_t end = log.find('\n', p); + const std::string line = log.substr(p, end == std::string::npos ? std::string::npos : end - p); + std::printf("%s\n", line.c_str()); + if (line.find("sev=0 ") != std::string::npos || line.find("sev=1 ") != std::string::npos) ++failures; + } + std::printf("device removed reason: 0x%08lx\n", static_cast<unsigned long>(desktop->GetDeviceRemovedReason())); + if (desktop->GetDeviceRemovedReason() != S_OK) ++failures; + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; + } + const std::uint32_t s2 = late ? 0xcu : reset ? 0x4u : 0u; // slot 2's first dword in data (reset: the copied-back V#) + const std::uint32_t typed_format = (w5[3] >> 12) & 127; + const std::uint32_t want[28] = { + on ? 0xc0de0000u : 0u, on ? 0xc0de0003u : 0u, 0u, 0u, // slot 1 + on ? 0xc0de0000u + s2 : 0u, on ? 0xc0de0003u + s2 : 0u, on ? 0x0001c0deu + (s2 << 16) : 0u, 0u, // slot 2 + on ? 0x0001c0deu : 0u, 0x11111111u, 0x11111111u, 0x11111111u, // slot 3 + on ? 0xd2000008u : 0u, 0u, on ? 12u : 0u, 0u, // slot 4 + on ? 0xc0de0020u : 0u, on ? 4u : 0u, on && typed_format != 22 ? typed_format : 0u, 0u, // slot 5 + 0x70000001u, on ? 0xc0de0000u : 0u, 0u, 0u, // 6, 1, 3 + on ? 0xa0003ffcu : 0u, on ? 0xa0003fffu : 0u, on ? 0xb000b000u : 0u, on ? 0xb000a000u : 0u}; // slot 7 + const char* what[28] = {"slot 1 dword 0", "slot 1 dword 3", "slot 1 dword 4 (past 16 bytes)", "slot 1 stride", + "slot 2 dword 0", "slot 2 dword 3", "slot 2 byte 2", "(unused)", + "slot 3 dword 0 (base not 4-aligned: bytes 2..5)", "(unused)", "(unused)", "(unused)", + "slot 4 byte 32 (structured 3 x 12)", "slot 4 byte 36 (past 36 bytes)", "slot 4 stride", "slot 4 format", + "slot 5 dword 0 (typed)", "slot 5 stride", "slot 5 format", "slot 5 byte 16 (past 4 elements)", + "slot 6 dword 0 (token)", "slot 1 dword 0 (same program)", "slot 3 stride (raw: 0)", "slot 3 format (raw: 0)", + "slot 7 dword 0 (paged, first block)", "slot 7 dword 3", "slot 7 dword 4 (second block)", + "slot 7 byte 14 (across the page boundary)"}; + for (int i = 0; i < 28; ++i) { + if (std::strcmp(what[i], "(unused)") == 0) continue; + std::printf("%s: %08x (want %08x)\n", what[i], memory[4 + i], want[i]); + if (memory[4 + i] != want[i]) ++failures; + } + const bool v_written = w1[0] == static_cast<std::uint32_t>(arg(data)) && w1[2] == 16 && w1[3] == 0x30016facu && + w4[2] == 3 && ((w4[1] >> 16) & 0x3fff) == 12 && w5[2] == 4 && w6[0] == 0x56573258u; + const bool table_line = has("x2w-cx " + std::string(key_text) + ": heapraw 1: raw V# table at t2 space1"); + const bool two_windows = on ? has("x2w-heapraw window 3: ") && !has("x2w-heapraw window 4: ") : true; // data, data2, pa, pb + const bool counted = + late ? has("x2w-heapraw sweep thread started") && !has("sweep thread started (X2W_HEAP_RAW_SWEEP_SYNC=1)") && log.find("displaced 0 (recent 0)", log.rfind("x2w-heapraw drain time:")) != std::string::npos + : reset ? log.rfind("x2w-heapraw drain time:") != std::string::npos && + log.find("evicted 4, displaced 0 (recent 0)", log.rfind("x2w-heapraw drain time:")) != std::string::npos + : on ? has("(base not 4-aligned 1, paged 1); not resolved: base not 4-aligned 0, not in windows 0, ") && + has("x2w-heapraw drains with work: 1, ") && + has("table half full: reset 0 (evicted 0, displaced 0); resolved 7 new ranges, 0 waiting, 0 notes dropped") + : !has("x2w-heapraw ranges:") && !has("x2w-heapraw drains with work"); + std::printf("V#s and token written %d, heapraw line %d, two windows %d, counters %d\n", v_written, table_line, two_windows, counted); + if (!v_written || !table_line || !two_windows || !counted) ++failures; + for (std::size_t p = log.find("x2w-heapraw"); p != std::string::npos; p = log.find("x2w-heapraw", p + 1)) { + const std::size_t end = log.find('\n', p); + std::printf("%s\n", log.substr(p, end == std::string::npos ? std::string::npos : end - p).c_str()); + } + for (std::size_t p = log.find("x2w-d3d12-debug"); p != std::string::npos; p = log.find("x2w-d3d12-debug", p + 1)) { + const std::size_t end = log.find('\n', p); + const std::string line = log.substr(p, end == std::string::npos ? std::string::npos : end - p); + std::printf("%s\n", line.c_str()); + if (line.find("sev=0 ") != std::string::npos || line.find("sev=1 ") != std::string::npos) ++failures; + } + std::printf("device removed reason: 0x%08lx\n", static_cast<unsigned long>(desktop->GetDeviceRemovedReason())); + if (desktop->GetDeviceRemovedReason() != S_OK) ++failures; + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; + } + if (heap) { + // A shader-visible 4-slot title view heap at title + 1 MiB (128 bytes); word 0 of slot 1 = A, and word 0 of + // "slot 4", the first word past the heap, = B. heapmem is a bounded view of the heap, so the shader must + // read A and 0. (An unbounded root SRV, the earlier binding, reads B there.) + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, arg(memory + 0x40000), 4 * 32}; + void* view_heap = nullptr; + if (!ok(invoke(device, 14, arg(&heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&view_heap))) || !view_heap) return 12; + constexpr std::uint32_t A = 0xa1a1a1a1u, B = 0xb2b2b2b2u; + memory[0x40000 + 8] = A; // slot 1 (byte 32) + memory[0x40000 + 32] = B; // byte 128: past the heap + memory[1] = memory[2] = 0x11111111u; + if (!run_list(1)) return 14; + const std::string log = read_log(log_path); + const auto has = [&](const std::string& text) { return log.find(text) != std::string::npos; }; + const bool skipped32 = has(std::string("x2w-cx ") + key_text + ": heap dispatch skipped: increment not 32"); + std::printf("heap: in range %08x (want %08x), past the end %08x (want 00000000; unbounded would read %08x); increment skip %d\n", + memory[1], A, memory[2], B, skipped32); + if (skipped32) { // WARP: views are not 32 bytes apart, so `heap 1` dispatches are skipped by design + std::printf("heap dispatches need a 32-byte view increment: capability skip\n"); + return memory[1] == 0x11111111u && memory[2] == 0x11111111u ? 77 : 16; + } + const bool bounded = has(std::string("x2w-cx ") + key_text + ": bounded heap views: heapmem 128 bytes (title heap 128), vinfo "); + std::printf("log: bounded heap views line %d\n", bounded); + if (memory[1] != A || memory[2] != 0 || !bounded) { + std::printf("FAIL: heapmem is not a bounded view of the 128-byte heap\n"); + ++failures; + } + for (std::size_t p = log.find("x2w-d3d12-debug"); p != std::string::npos; p = log.find("x2w-d3d12-debug", p + 1)) { + const std::size_t end = log.find('\n', p); + const std::string line = log.substr(p, end == std::string::npos ? std::string::npos : end - p); + std::printf("%s\n", line.c_str()); + if (line.find("sev=0 ") != std::string::npos || line.find("sev=1 ") != std::string::npos) ++failures; + } + std::printf("device removed reason: 0x%08lx\n", static_cast<unsigned long>(desktop->GetDeviceRemovedReason())); + if (desktop->GetDeviceRemovedReason() != S_OK) ++failures; + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; + } + if (slow) { + const bool lane = mode == "slow"; + // The first dispatch waits until the worker is inside S's load (the watch's "load running" line, after + // X2W_CX_SLOW_LOG_MS = 500): a dispatch issued before the worker took S would demand A while it is still + // queued, and a demanded key is taken first with or without the lane, so the control would not starve. + const std::string s_running = std::string("x2w-cx ") + s_text + ": load running for "; + bool s_loading = false; + for (int i = 0; i < 200 && !s_loading; ++i) { // at most 10 s + s_loading = read_log(log_path).find(s_running) != std::string::npos; + if (!s_loading) Sleep(50); + } + if (!s_loading) { + std::printf("S's load never logged \"load running\" before the dispatch\n"); + return 15; + } + const ULONGLONG start = GetTickCount64(); + int lists = 0; + while (memory[0] == 0 && GetTickCount64() - start < 20000) { + if (!run_list(1)) return 14; + ++lists; + if (memory[0] == 0) Sleep(50); + } + const ULONGLONG a_ms = GetTickCount64() - start; + std::printf("A ran after %llu ms (%d one-dispatch lists), counter %u\n", static_cast<unsigned long long>(a_ms), lists, memory[0]); + const std::string s_ended = std::string("x2w-cx ") + s_text + ": slow load ended after "; + const std::string s_translated = std::string("x2w-cx ") + s_text + " translated: "; + std::string log; + for (int i = 0; i < 300; ++i) { // wait for S's load to end (at most 15 s) + log = read_log(log_path); + if (log.find(s_translated) != std::string::npos && (!lane || log.find(s_ended) != std::string::npos)) break; + Sleep(50); + } + const auto at = [&](const std::string& text) { return log.find(text); }; + const std::size_t s_at = at(s_translated), t_at = at(std::string("x2w-cx ") + t_text + " translated: "), + a_at = at(std::string("x2w-cx ") + key_text + " translated: "); + const bool running = at(std::string("x2w-cx ") + s_text + ": load running for ") != std::string::npos; + const bool marked = at(std::string("x2w-cx ") + s_text + ": marked slow after ") != std::string::npos && + at("a replacement worker started") != std::string::npos; + const bool ended = at(s_ended) != std::string::npos; + const bool lane_line = at("plus 1 demand-lane thread") != std::string::npos; + const bool all_three = s_at != std::string::npos && t_at != std::string::npos && a_at != std::string::npos; + std::printf("log: lane line %d, running line %d, marked slow %d, slow ended %d; translated order S %zd T %zd A %zd\n", lane_line, running, + marked, ended, static_cast<std::ptrdiff_t>(s_at), static_cast<std::ptrdiff_t>(t_at), static_cast<std::ptrdiff_t>(a_at)); + if (memory[0] != 1 || !all_three) ++failures; + if (lane) { + // A within 3 s (S's load takes >= 6 s), T before S, every watch line. + if (a_ms >= 3000 || !(a_at < s_at) || !(t_at < s_at) || !running || !marked || !ended || !lane_line) ++failures; + } else { + // the starvation the lane removes: A and T only after S (and no slow mark: X2W_CX_SLOW_MS above the test) -- A is measured from S's "load running" line (0.5-0.8 s into its 6 s), so >= 4 s + if (a_ms < 4000 || !(s_at < a_at) || !(s_at < t_at) || marked || lane_line || !running) ++failures; + } + for (std::size_t p = log.find("x2w-cx"); p != std::string::npos; p = log.find("x2w-cx", p + 1)) { + const std::size_t end = log.find('\n', p); + const std::string line = log.substr(p, end == std::string::npos ? std::string::npos : end - p); + if (line.find("prewarm") != std::string::npos || line.find("slow") != std::string::npos || line.find("running") != std::string::npos || + line.find("translated") != std::string::npos) + std::printf("%s\n", line.c_str()); + } + for (std::size_t p = log.find("x2w-d3d12-debug"); p != std::string::npos; p = log.find("x2w-d3d12-debug", p + 1)) { + const std::size_t end = log.find('\n', p); + const std::string line = log.substr(p, end == std::string::npos ? std::string::npos : end - p); + std::printf("%s\n", line.c_str()); + if (line.find("sev=0 ") != std::string::npos || line.find("sev=1 ") != std::string::npos) ++failures; + } + if (desktop->GetDeviceRemovedReason() != S_OK) ++failures; + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; + } + if (mode == "sync") { + if (const HANDLE t = CreateThread(nullptr, 0, release_later, nullptr, 0, nullptr)) CloseHandle(t); + else return 13; + } + const ULONGLONG list1_start = GetTickCount64(); + if (!run_list(3)) return 14; + const std::uint32_t after_first = memory[0]; + std::printf(prewarm ? "list 1 (3 dispatches, pipeline prewarmed at start): counter %u, recorded and executed in %llu ms\n" + : "list 1 (3 dispatches, pipeline held back): counter %u, recorded and executed in %llu ms\n", after_first, + static_cast<unsigned long long>(GetTickCount64() - list1_start)); + if (after_first != (async ? 0u : 3u)) { + std::printf("FAIL: list 1 should leave the counter at %u\n", async ? 0u : 3u); + ++failures; + } + int tries = 0; + if (async) { + SetEvent(hold_event); + while (memory[0] == 0 && tries < 200) { + Sleep(50); + ++tries; + if (!run_list(1)) return 14; + } + std::printf("after the release: counter %u after %d one-dispatch lists\n", memory[0], tries); + if (memory[0] != 1) { + std::printf("FAIL: once ready, exactly one dispatch should have run (counter 1)\n"); + ++failures; + } + } + + // The log (the worker writes the ready line just after the load completes: wait for it at most 5 s). + const std::string skip_line = std::string("x2w-cx ") + key_text + ": pipeline not loaded yet, dispatch skipped"; + const std::string ready_line = std::string("x2w-cx ") + key_text + " ready (X2W_CX_ASYNC)"; + std::string log = read_log(log_path); + for (int i = 0; async && i < 100 && log.find(ready_line) == std::string::npos; ++i) { + Sleep(50); + log = read_log(log_path); + } + const auto has = [&](const std::string& text) { return log.find(text) != std::string::npos; }; + long skipped = -1; + if (const std::size_t p = log.find(ready_line); p != std::string::npos) { + const std::string line = log.substr(p, log.find('\n', p) - p); + std::printf("log: %s\n", line.c_str()); + if (const std::size_t q = line.find("; "); q != std::string::npos) skipped = std::strtol(line.c_str() + q + 2, nullptr, 10); + } + const bool translated = has(std::string("x2w-cx ") + key_text + " translated: "); + const bool released = has(std::string("x2w-cx ") + key_text + ": load held by X2W_CX_TEST_HOLD_EVENT (released)"); + std::printf("log: translated %d, hold released %d, skip line %d, ready line %d (%ld dispatches skipped while compiling)\n", translated, released, + has(skip_line), has(ready_line), skipped); + if (!translated || released == prewarm) { + std::printf("FAIL: the translation was not loaded %s\n", prewarm ? "(or the hold was set)" : "through the hold"); + ++failures; + } + if (prewarm) { + // The queued line, and the keys-seen file the writer thread writes every 10 s (wait at most 25 s). + const std::string queued = mode == "known" + ? "x2w-cx prewarm: 2 known pipelines queued (X2W_CX_PREWARM_ALL; no keys seen file: every cached translation)" + : "x2w-cx prewarm: 1 known pipelines queued (X2W_CX_PREWARM_ALL; keys seen file "; + const std::string counts = ": 2 keys, 1 with a translation)"; + const bool queued_ok = has(queued) && (mode == "known" || has(counts)); + std::printf("log: queued line %d\n", queued_ok); + if (!queued_ok) { + std::printf("FAIL: the start prewarm did not queue what mode %s expects\n", mode.c_str()); + ++failures; + } + std::uint64_t sorted[3] = {key_c, key < key_b ? key : key_b, key < key_b ? key_b : key}; // key_c is the smallest + const std::string want = mode == "known" ? key_line(key) : key_line(sorted[0]) + key_line(sorted[1]) + key_line(sorted[2]); + std::string seen; + for (int i = 0; i < 250; ++i) { + seen = read_log(seen_path); + if (seen == want) break; + Sleep(100); + } + std::printf("keys seen file: \"%s\" (want \"%s\")\n", seen.c_str(), want.c_str()); + if (seen != want) { + std::printf("FAIL: the keys seen file is not the union of the earlier file and the dispatched key\n"); + ++failures; + } + } + if (async ? (!has(skip_line) || skipped < 3) : (has(skip_line) || has(ready_line))) { + std::printf("FAIL: the X2W_CX_ASYNC lines do not match mode %s\n", mode.c_str()); + ++failures; + } + for (std::size_t p = log.find("x2w-d3d12-debug"); p != std::string::npos; p = log.find("x2w-d3d12-debug", p + 1)) { + const std::size_t end = log.find('\n', p); + const std::string line = log.substr(p, end == std::string::npos ? std::string::npos : end - p); + std::printf("%s\n", line.c_str()); + if (line.find("sev=0 ") != std::string::npos || line.find("sev=1 ") != std::string::npos) ++failures; + } + std::printf("device removed reason: 0x%08lx\n", static_cast<unsigned long>(desktop->GetDeviceRemovedReason())); + if (desktop->GetDeviceRemovedReason() != S_OK) ++failures; + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; +} diff --git a/tests/startup_cx_async.hlsl b/tests/startup_cx_async.hlsl new file mode 100644 index 0000000000..86d8dbf196 --- /dev/null +++ b/tests/startup_cx_async.hlsl @@ -0,0 +1,29 @@ +// LOCAL stall: the translated slot-67 compute program of startup_cx_async.cpp. The stand-in's translated root +// signature: [0] one 32-bit constant (no entry values), [1] a table of 1 SRV (t0, unused) and 1 UAV (u0). +// Every executed dispatch adds 1 to the first word of the title buffer bound as root UAV 0. +RWByteAddressBuffer counter : register(u0); + +// HeapMain (mode heap, manifest `heap 1`, LOCAL meshrt): heapmem = the title view heap's memory (t0 space1). Stores +// word 0 of slot 1 (inside the 4-slot heap) at byte 4 and word 0 of slot 4 (just past its end) at byte 8 of u0. +ByteAddressBuffer heapmem : register(t0, space1); +[numthreads(1, 1, 1)] +void HeapMain() +{ + counter.Store2(4, uint2(heapmem.Load(32), heapmem.Load(128))); +} + +[numthreads(1, 1, 1)] +void CountMain() +{ + uint before; + counter.InterlockedAdd(0, 1, before); +} + +SamplerState title_sampler : register(s1, space1); +Texture2D<float4> image : register(t1); +[numthreads(1, 1, 1)] +void SamplerMain() +{ + uint before; + counter.InterlockedAdd(0, uint(round(image.SampleLevel(title_sampler, float2(-4,-4), 0).r * 255)), before); +} diff --git a/tests/startup_cx_heap_raw.hlsl b/tests/startup_cx_heap_raw.hlsl new file mode 100644 index 0000000000..4260aa68a2 --- /dev/null +++ b/tests/startup_cx_heap_raw.hlsl @@ -0,0 +1,56 @@ +// LOCAL: the translated program of startup_cx_async.cpp modes rawheap / rawheap-off / rawheap-reset (manifest +// `heap 1` + `heapraw 1`, d3d12_heap_raw.inl). The heap prelude is the one the compute translator emits for +// `heapraw 1`; H0 is a heap SRV buffer as the translator declares it. Stores to the title buffer (root UAV 0): +// 16..31 slot 1 (raw V#, 16 bytes, window 1): dwords 0 and 3, dword 4 (past the 16 bytes: 0), vstride (0) +// 32..47 slot 2 (rawheap: the title's memcpy of slot 1; reset: the last rewritten V#): dwords 0 and 3, the +// unaligned dword at byte 2, 0 +// 48..51 slot 3 (a V# whose base is not 4-aligned: read byte-exact) dword 0 +// 64..79 slot 4 (structured V#, stride 12 x 3 records, window 2): dword at byte 32, at byte 36 (past 36 bytes: 0), +// vstride (12), vfmt (32_FLOAT: 0) +// 80..95 slot 5 (typed R32_UINT V#, 4 elements): dword 0, vstride (4), vfmt (the V#'s FORMAT), dword at byte 16 (0) +// 96..111 slot 6 (a view token over the title buffer) dword 0, then slot 1 dword 0 again (one program reading a token +// slot and a V# slot), vstride / vfmt of slot 3 (raw: 0, 0) +// 112..127 slot 7 (32 bytes over two windows, a paged entry): dwords 0, 3 and 4 (the second window), the dword at +// byte 14 (two bytes from each window) +RWByteAddressBuffer counter : register(u0); +#include "heap_raw_prelude.hlsli" +#define H0 hbuf(h0) +[numthreads(1, 1, 1)] +void RawHeapMain() +{ + uint h0 = 1u << 5; + counter.Store4(16, uint4(H0.Load(0), H0.Load(12), H0.Load(16), vstride(h0))); + h0 = 2u << 5; + counter.Store4(32, uint4(H0.Load(0), H0.Load(12), ldu(H0, 2), 0u)); + h0 = 3u << 5; + counter.Store(48, H0.Load(0)); + h0 = 4u << 5; + counter.Store4(64, uint4(H0.Load(32), H0.Load(36), vstride(h0), vfmt(h0))); + h0 = 5u << 5; + counter.Store4(80, uint4(H0.Load(0), vstride(h0), vfmt(h0), H0.Load(16))); + h0 = 6u << 5; + uint token = H0.Load(0); + h0 = 1u << 5; + uint again = H0.Load(0); + h0 = 3u << 5; + counter.Store4(96, uint4(token, again, vstride(h0), vfmt(h0))); + h0 = 7u << 5; + counter.Store4(112, uint4(H0.Load(0), H0.Load(12), H0.Load(16), ldu(H0, 14))); +} + +// LOCAL: startup_cx_async.cpp rawheap-bench. Title words: [1] first ring index, [2] count, [3] ring size (V# slots +// from heap slot 8). Each checked slot's V# names title data the bench filled with dword (address >> 2): the program +// reads dword 0 through the slot and counts it in [6]; a wrong or empty read (a miss: 0) counts in [5]. +[numthreads(1, 1, 1)] +void RawBenchMain() +{ + uint first = counter.Load(4), count = counter.Load(8), ring = counter.Load(12), bad = 0u; + [loop] for (uint i = 0u; i < count; ++i) { + uint h0 = (8u + (first + i) % ring) << 5; + uint4 w = heapmem.Load4(h0); + uint want = (w.x >> 2) | ((w.y & 3u) << 30); + if (H0.Load(0) != want) ++bad; + } + counter.Store(20, counter.Load(20) + bad); + counter.Store(24, counter.Load(24) + count); +} diff --git a/tests/startup_cx_heap_words.hlsl b/tests/startup_cx_heap_words.hlsl new file mode 100644 index 0000000000..846d42752c --- /dev/null +++ b/tests/startup_cx_heap_words.hlsl @@ -0,0 +1,23 @@ +// LOCAL isa-gaps: the translated program of startup_cx_async.cpp mode heapwords (manifest `heap 1` + `heapwords 1`, +// d3d12_compute.inl / d3d12_vdesc.inl). The helper is the one the compute translator emits for `heapwords 1` +// (board 045000): a slot without the view-token magic reads the title's words from heapmem as they are (a raw +// descriptor: here the V# the runtime wrote for a slot-70 memory SRV, d3d12_heap_raw.inl); a token slot reads the +// view's words from vdesc (t3 space1, 32 bytes per view id, bounded: an id past it reads 0). Stores to root UAV 0: +// bytes 16..31: slot 1 (runtime-written V#, 16 bytes) words 0, 2, 3; slot 2 (the title's memcpy of slot 1) word 2 +// bytes 32..47: slot 2 word 3; slot 3 (a token with id 0xffffffff) words 0 and 2; slot 0 (zeros) word 0 +// bytes 48..51: the title idiom on slot 1: w = word 2 & 0x3fff; w == 0 ? 0 : ((w << 2) + 4) >> 2 +// bytes 52..63: slot 6 (a view token: a slot-18 raw SRV of 16 bytes of the title buffer) words 1, 2, 3 from vdesc +RWByteAddressBuffer counter : register(u0); +ByteAddressBuffer heapmem : register(t0, space1); +ByteAddressBuffer vinfo : register(t1, space1); +ByteAddressBuffer x2w_vdesc : register(t3, space1); +uint x2w_hword(uint h, uint i) { if (heapmem.Load(h) != 0x56573258u) return heapmem.Load(h + 4u * i); uint id = heapmem.Load(h + 4u); return id < 0x08000000u ? x2w_vdesc.Load(id * 32u + 4u * i) : 0u; } +[numthreads(1, 1, 1)] +void WordsMain() +{ + counter.Store4(16, uint4(x2w_hword(32u, 0u), x2w_hword(32u, 2u), x2w_hword(32u, 3u), x2w_hword(64u, 2u))); + counter.Store4(32, uint4(x2w_hword(64u, 3u), x2w_hword(96u, 0u), x2w_hword(96u, 2u), x2w_hword(0u, 0u))); + uint w = x2w_hword(32u, 2u) & 0x3fffu; + counter.Store(48, w == 0u ? 0u : ((w << 2) + 4u) >> 2); + counter.Store3(52, uint3(x2w_hword(192u, 1u), x2w_hword(192u, 2u), x2w_hword(192u, 3u))); +} diff --git a/tests/startup_cx_pso_time.cpp b/tests/startup_cx_pso_time.cpp new file mode 100644 index 0000000000..e645c9a36d --- /dev/null +++ b/tests/startup_cx_pso_time.cpp @@ -0,0 +1,88 @@ +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <iterator> +#include <string> + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +std::string read_log(const std::wstring& path) +{ + std::ifstream file(path, std::ios::binary); + return std::string{std::istreambuf_iterator<char>(file), {}}; +} +void print_lines(const std::string& log, const char* what) +{ + for (std::size_t p = log.find("x2w-cx "); p != std::string::npos; p = log.find("x2w-cx ", p + 1)) { + const std::size_t end = log.find('\n', p); + const std::string line = log.substr(p, end == std::string::npos ? std::string::npos : end - p); + if (line.find(what) != std::string::npos) std::printf("%s\n", line.c_str()); + } +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 3) return 2; + const int seconds = argc > 3 ? std::atoi(argv[3]) : 300; + ComPtr<IDXGIFactory6> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr<IDXGIAdapter> adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr<IDXGIAdapter1> candidate; + if (factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)) == DXGI_ERROR_NOT_FOUND) return 77; + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(candidate->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC ad{}; + LARGE_INTEGER driver{}; + adapter->GetDesc(&ad); + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls driver=%u.%u.%u.%u\n", ad.Description, HIWORD(driver.HighPart), LOWORD(driver.HighPart), HIWORD(driver.LowPart), + LOWORD(driver.LowPart)); + wchar_t dir[MAX_PATH]; + if (!MultiByteToWideChar(CP_UTF8, 0, argv[2], -1, dir, MAX_PATH)) return 4; + const std::wstring log_path = std::wstring(dir) + L"\\trap.log"; + DeleteFileW(log_path.c_str()); + SetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir); + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + SetEnvironmentVariableW(L"X2W_CX_PREWARM_ALL", L"1"); + SetEnvironmentVariableW(L"X2W_CX_PREWARM_THREADS", L"1"); + SetEnvironmentVariableW(L"X2W_CX_SLOW_LOG_MS", L"5000"); + SetEnvironmentVariableW(L"X2W_D3D12_RENDER", L"1"); + SetEnvironmentVariableW(L"X2W_D3D12_PERMISSIVE", L"1"); + SetEnvironmentVariableW(L"X2W_D3D12_LIST_NOOP", L"1"); + std::array<unsigned char, 64> parameters{}; + void* device = nullptr; + const ULONGLONG start = GetTickCount64(); + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &device))) return 6; + std::string log; + bool done = false; + while (!done && GetTickCount64() - start < static_cast<ULONGLONG>(seconds) * 1000) { + Sleep(200); + log = read_log(log_path); + done = log.find("x2w-cx prewarm: all ") != std::string::npos; + } + print_lines(log, "known pipelines queued"); + print_lines(log, " translated: "); + print_lines(log, ": load running for "); + print_lines(log, "prewarm: all "); + std::printf("%s after %.1f s\n", done ? "ALL LOADED" : "TIMEOUT", (GetTickCount64() - start) / 1000.0); + std::fflush(stdout); + TerminateProcess(GetCurrentProcess(), done ? 0 : 1); // a driver compile still running cannot be joined + return done ? 0 : 1; +} diff --git a/tests/startup_detile_draw.ps1 b/tests/startup_detile_draw.ps1 new file mode 100644 index 0000000000..c39b74dfb7 --- /dev/null +++ b/tests/startup_detile_draw.ps1 @@ -0,0 +1,40 @@ +function Invoke-DetileDraw($Dir, $Consumer, $Backend, $Fxc, $PixelShader, $Kind) { + $env:X2W_GPU_ABI = '0' + $env:X2W_D3D12_PERMISSIVE = '1' + $env:X2W_D3D12_DEVICE_NOOP = '1' + $env:X2W_D3D12_LIST_NOOP = '1' + $env:X2W_D3D12_RENDER = '1' + $env:X2W_D3D12_DEBUG = '0' + $env:X2W_TRAP_LOG = "$dir/trap.log" + $env:X2W_SHADER_CACHE = $dir + # Slot 86 recognizes the console container signature and hashes the opaque stage bytes. + # The desktop stage binaries under that key are compiled from the fixture's HLSL below. + $container = New-Object byte[] 32 + [Text.Encoding]::ASCII.GetBytes('DXBC').CopyTo($container, 0) + foreach ($stage in 'vs', 'ps') { + [Text.Encoding]::ASCII.GetBytes($stage).CopyTo($container, 4) + [IO.File]::WriteAllBytes("$dir/$stage", $container) + } + & $Consumer "$dir/vs" "$dir/ps" "$dir/root" | Out-Host + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $keys = @(Get-ChildItem $dir -Filter 'req_*' | ForEach-Object { + if ($_.Name -match '^req_([0-9a-f]{16})\.(rtv|a)$') { $Matches[1] } + } | Sort-Object -Unique) + if ($keys.Count -ne 1) { throw "Expected one captured pipeline, got $($keys.Count)" } + $prefix = Join-Path $dir $keys[0] + $source = @" +float4 vs(uint id : SV_VertexID) : SV_Position { + return float4(2.0 * float2((id << 1) & 2, id & 2) - 1.0, 0, 1); +} +$PixelShader +"@ + [IO.File]::WriteAllText("$dir/test.hlsl", $source) + foreach ($stage in 'vs', 'ps') { + & $Fxc /nologo /T "${stage}_5_0" /E $stage /Fo "$prefix.$stage.cso" "$dir/test.hlsl" | Out-Host + if ($LASTEXITCODE -ne 0) { throw "Failed to compile $stage" } + } + [IO.File]::WriteAllLines("$prefix.txt", @('x2w-manifest 1', 'ud 1', 'udsrc 0 rect', "srv 0 $Kind table 0 0", 'params 0', 'targets 0')) + & $Consumer "$dir/vs" "$dir/ps" "$dir/root" $Backend "$dir/pixels" | Out-Host + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + return ,([IO.File]::ReadAllBytes("$dir/pixels")) +} diff --git a/tests/startup_draw_async_check.py b/tests/startup_draw_async_check.py new file mode 100644 index 0000000000..6f637b881a --- /dev/null +++ b/tests/startup_draw_async_check.py @@ -0,0 +1,90 @@ +"""LOCAL stall: a translated draw issued while its desktop pipeline compile is held back (X2W_DRAW_ASYNC). + +The red pixel shader of startup_stream_draw_check is translated into the cache; the consumer then draws twice +(X2W_TEST_HOLD_RELEASE) while the stand-in holds every translated pipeline compile until a named event is set +(X2W_CX_TEST_HOLD_EVENT). + +- async (X2W_DRAW_ASYNC=1, the event set after the first draw): the first draw is skipped (pixels <output>.first + all clear, one "draw skipped and the build queued" line for the key); the second draw, 1.5 s after the release, + is red; the ready line counts 1 skipped draw. +- sync (control, switch off, the event set by a thread 300 ms after the first draw starts): the recording thread + waits, so both draws are red; neither line. +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +from startup_stream_check import gfx2hlsl +from startup_stream_draw_check import pixel, vertex + + +def check(directory, consumer, backend, mode): + if mode not in ("async", "sync"): + return 2 + cache = directory / "cache" + cache.mkdir() + vs, ps, root, output = (directory / name for name in ("vs", "ps", "root", "pixels")) + vs.write_bytes(vertex()) + ps.write_bytes(pixel(False)) + args = [consumer, vs, ps, root] + env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_SHADER_CACHE=str(cache)) + env.setdefault("X2W_D3D12_DEBUG", "0") + for name in ("X2W_DRAW_ASYNC", "X2W_CX_ASYNC", "X2W_DRAW_PSO_LOCKED"): + env.pop(name, None) + subprocess.run(args, env=env, check=True) + subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True) + key = gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()) + + run_env = dict(env, X2W_CX_TEST_HOLD_EVENT=f"Local\\x2w_draw_hold_{os.getpid()}", + X2W_TEST_HOLD_RELEASE="first" if mode == "async" else "300") + if mode == "async": + run_env["X2W_DRAW_ASYNC"] = "1" + result = subprocess.run(args + [backend, output], env=run_env, capture_output=True, text=True, timeout=60) + print(result.stdout, end="") + log = result.stderr + for line in log.splitlines(): + if "X2W_DRAW_ASYNC" in line or "X2W_CX_TEST_HOLD_EVENT" in line or "x2w-d3d12-debug " in line or "-> drawn;" in line: + print(line) + if backend == "hardware" and result.returncode == 77: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + if result.returncode: + raise RuntimeError(f"consumer failed on {backend}: {result.returncode}\n{log}") + red, clear = bytes((255, 0, 0, 255)), bytes((0, 0, 255, 255)) + drawn = (red * 4 + clear * 4) * 4 + first, second = Path(str(output) + ".first").read_bytes(), output.read_bytes() + skip_line = f"x2w-draw {key:016x}: desktop pipeline not built yet, draw skipped and the build queued (X2W_DRAW_ASYNC)" + ready_line = f"x2w-draw {key:016x} ready (X2W_DRAW_ASYNC); 1 draws skipped while compiling" + held = f"x2w-draw {key:016x}: load held by X2W_CX_TEST_HOLD_EVENT (released)" + draws = log.count("-> drawn;") + want_first = clear * 32 if mode == "async" else drawn + failures = [] + if first != want_first: + failures.append(f"first draw: {first.hex()} want {want_first.hex()}") + if second != drawn: + failures.append(f"second draw: {second.hex()} want {drawn.hex()}") + if draws != (1 if mode == "async" else 2): + failures.append(f"{draws} '-> drawn;' lines") + if held not in log: + failures.append("the compile was not held and released") + if mode == "async" and (log.count(skip_line) != 1 or ready_line not in log): + failures.append("skip / ready lines missing") + if mode == "sync" and ("X2W_DRAW_ASYNC" in log): + failures.append("X2W_DRAW_ASYNC lines without the switch") + if any("x2w-d3d12-debug " in line and (" sev=0 " in line or " sev=1 " in line) for line in log.splitlines()): + failures.append("debug-layer error or corruption") + print(f"{backend} {mode}: first draw {'clear' if first == clear * 32 else 'red' if first == drawn else 'other'}, " + f"second {'red' if second == drawn else 'other'}, {draws} drawn lines") + if failures: + print("FAIL: " + "; ".join(failures)) + return 1 + print("PASS") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:])) diff --git a/tests/startup_draw_bmp.cpp b/tests/startup_draw_bmp.cpp index 9369ebd1bc..ca3e3871a7 100644 --- a/tests/startup_draw_bmp.cpp +++ b/tests/startup_draw_bmp.cpp @@ -92,6 +92,47 @@ void tight_rows() std::fclose(output); } +void hdr_rows(DXGI_FORMAT format) +{ + std::array<unsigned char, 32> source{}; + // Second pixel of the top row is RGB (1, 0, 3). Both source rows have 16 bytes. + if (format == DXGI_FORMAT_R16G16B16A16_FLOAT) { + const std::uint16_t half[4] = {0x3c00, 0, 0x4200, 0xffff}; + std::memcpy(source.data() + 8, half, sizeof(half)); + } else { + const std::uint32_t packed = format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP + ? (17u << 27) | (384u << 18) | 128u // mantissas (128,0,384), scale 2^-7 + : (528u << 22) | 960u; + std::memcpy(source.data() + 4, &packed, sizeof(packed)); + } + FILE* output = std::tmpfile(); + if (!output) return expect("tmpfile", false); + expect("HDR image written", x2w_draw_bmp::write(output, source.data(), 2, 2, 16, format)); + std::rewind(output); + expect("HDR headers", headers(output, 2, 2)); + unsigned char pixels[16]{}; + const unsigned char expected[16] = {0,0,0,255, 0,0,0,255, 0,0,0,255, 191,0,128,255}; + expect("HDR row pitch, channels and exposure", std::fread(pixels, 1, sizeof(pixels), output) == sizeof(pixels) && + std::memcmp(pixels, expected, sizeof(pixels)) == 0); + std::fclose(output); +} + +void signed_rg() +{ + // (+1,-1), (0,0), (-infinity,+infinity) in binary16. + const std::uint16_t source[] = {0x3c00, 0xbc00, 0, 0, 0xfc00, 0x7c00}; + const unsigned char expected[] = {128,64,192,255, 128,128,128,255, 128,255,0,255}; + FILE* output = std::tmpfile(); + if (!output) return expect("tmpfile", false); + expect("signed RG preview", x2w_draw_bmp::write(output, reinterpret_cast<const unsigned char*>(source), 3, 1, + sizeof(source), DXGI_FORMAT_R16G16_FLOAT)); + std::rewind(output); + unsigned char pixels[sizeof(expected)]{}; + expect("signed RG channels, neutral, endpoints", headers(output, 3, 1) && + std::fread(pixels, 1, sizeof(pixels), output) == sizeof(pixels) && !std::memcmp(pixels, expected, sizeof(pixels))); + std::fclose(output); +} + // Calls the writer must refuse before it writes a byte. Each call gets its own empty file. // A writer that goes on reads past the four texel bytes, so some mutants fault here instead // of printing a FAIL line. @@ -138,6 +179,10 @@ int main(int argc, char** argv) expect("R8G8B8A8_UNORM_SRGB", check(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, false)); expect("B8G8R8A8_UNORM_SRGB", check(DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, true)); tight_rows(); + hdr_rows(DXGI_FORMAT_R16G16B16A16_FLOAT); + hdr_rows(DXGI_FORMAT_R11G11B10_FLOAT); + hdr_rows(DXGI_FORMAT_R9G9B9E5_SHAREDEXP); + signed_rg(); refused(); if (failures) return 1; std::printf("startup_draw_bmp: ok\n"); diff --git a/tests/startup_draw_dump_inputs_check.py b/tests/startup_draw_dump_inputs_check.py new file mode 100644 index 0000000000..dce064dea9 --- /dev/null +++ b/tests/startup_draw_dump_inputs_check.py @@ -0,0 +1,164 @@ +"""X2W_DRAW_DUMP_INPUTS=<key>[:occurrence]: the inputs and the render target of one translated draw go to files. + +Source-built gfx1013 code only: startup_stream_ps_inputs_check's draw (full-screen triangle, the pixel shader writes +red = SV_Position.x / 8 to the left half of an 8x4 RGBA8 target that is cleared to blue). The consumer never +presents, so it writes the dump through the shim's test export after its draw (x2w_draw_dump_inputs_test(1)). + off: without the switch: no dddump files, and the pixels are the reference pixels. + dump: X2W_DRAW_DUMP_INPUTS=<key>: the index names the plain draw (count 3), the entry values and the root + constants; rtv0_pre is the cleared target (all blue); rtv0_post equals the pixels the consumer read back + after the draw, byte for byte; the pixels are the same as with the switch off. + occurrence: X2W_DRAW_DUMP_INPUTS=<key>:2 with one draw: nothing is selected and nothing is written (the consumer + returns 63, its "no dump written" code). + buffers: startup_stream_fetch_check's two draws of one key (plain from vertex 3, then indexed: indices 4-9, base + vertex 5) with X2W_DRAW_DUMP_INPUTS=<key>:1,<key>:2 (two entries of one key count that key's draws once): + o1 is the plain draw, o2 the indexed one. Each vertex stream srv file holds exactly the six vertices the + draw reads (vertices 3-8, then 9-14) of the fixture's two float3 streams, the indexed dump's indices file + is the six u16 indices, and the pixels are the same as without the switch. +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import struct + +from startup_stream_interface_check import HEIGHT, WIDTH, check_pixels, gfx2hlsl, vertex +from startup_stream_ps_inputs_check import reading_pixel +import startup_stream_fetch_check as fetch + +BLUE = bytes((0, 0, 255, 255)) + + +def run(directory, consumer, backend, dump=None): + cache = directory / "cache" + out = directory / "dump" + cache.mkdir(parents=True) + out.mkdir() + vs, ps, root, output = (directory / name for name in ("vs", "ps", "root", "pixels")) + vs.write_bytes(vertex()) + ps.write_bytes(reading_pixel(0xf02)) + args = [consumer, vs, ps, root] + env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_SHADER_CACHE=str(cache), X2W_DRAW_DUMP_INPUTS_DIR=str(out)) + env.setdefault("X2W_D3D12_DEBUG", "0") + env.pop("X2W_DRAW_DUMP_INPUTS", None) + subprocess.run(args, env=env, check=True) + key = int(sorted(cache.glob("req_*.a"))[0].name[4:20], 16) + status = gfx2hlsl.translate_request(str(cache), key) + assert status == "ok", status + if dump is not None: + env["X2W_DRAW_DUMP_INPUTS"] = dump % key + result = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True) + print(result.stdout, end="") + if backend == "hardware" and result.returncode == 77: + return None + pixels = output.read_bytes() if output.exists() else None + return result, key, pixels, sorted(out.iterdir()) + + +def fixture_streams(): + """tests/startup_stream_draw.cpp X2W_TEST_VERTEX_FETCH: the TEXCOORD (slot 0) and POSITION (slot 1) float3 arrays.""" + texcoords, positions = [[0.0] * 3 for _ in range(15)], [[0.0] * 3 for _ in range(15)] + + def corners(out, first, x0, y0, x1, y1): + for v, (x, y) in enumerate(((x0, y0), (x1, y0), (x0, y1), (x1, y0), (x1, y1), (x0, y1))): + out[first + v] = [x, y, 0.5] + corners(texcoords, 3, -1.0, 1.0, 0.0, 0.5) + corners(positions, 3, -0.75, 0.5, -0.25, -0.5) + corners(texcoords, 9, -0.25, -0.5, 0.0, -1.0) + corners(positions, 9, -1.0, 1.0, -0.75, -1.0) + pack = lambda rows: b"".join(struct.pack("<3f", *r) for r in rows) + return pack(texcoords), pack(positions) + + +def check_buffers(directory, consumer, backend): + os.environ["X2W_UPSTREAM_STREAM_LAYOUT"] = "1" # as startup_stream_fetch_<backend>: the request carries the layout + run = fetch.Run(directory / "fetch_off", consumer, backend, fetch.vertex(), True) + assert gfx2hlsl.translate_request(str(run.cache), run.key) == "ok" + result = run.draw() + assert not result.returncode and result.stderr.count("-> drawn;") >= 2, result.stderr[-3000:] + reference = run.output.read_bytes() + run = fetch.Run(directory / "fetch_dump", consumer, backend, fetch.vertex(), True) + assert gfx2hlsl.translate_request(str(run.cache), run.key) == "ok" + out = directory / "fetch_files" + out.mkdir() + run.env.update(X2W_DRAW_DUMP_INPUTS="%016x:1,%016x:2" % (run.key, run.key), X2W_DRAW_DUMP_INPUTS_DIR=str(out)) + result = run.draw() + assert not result.returncode, (result.returncode, result.stdout, result.stderr[-3000:]) + assert run.output.read_bytes() == reference, "the dump changed the fetch draws' pixels" + names = {f.name: f for f in out.iterdir()} + index = sorted(n for n in names if n.endswith(".txt")) + assert len(index) == 2 and "_o1_" in index[0] and "_o2_" in index[1], index + texcoords, positions = fixture_streams() + for name, first, draw_line in ((index[0], 3, "draw plain count 6 instances 1 start 3 "), + (index[1], 9, "draw indexed count 6 instances 1 start 0 base_vertex 5 ")): + stem = name[:-4] + lines = names[name].read_text().splitlines() + assert any(l.startswith(draw_line) for l in lines), (draw_line, lines) + assert "vertices first %d count 6 topology 0x4" % first in lines, lines + streams = [l for l in lines if l.startswith("file ") and " srv " in l and " buffer source 1(" in l] + assert len(streams) == 2, lines + for l in streams: + slot = int(l.split(" buffer source 1(")[1].split(",")[0]) + data = names[l.split()[1]].read_bytes() + want = (texcoords, positions)[slot][12 * first:12 * (first + 6)] + assert data == want, (name, slot, data.hex(), want.hex()) + assert "bytes 72 of 72" in l and ": copied at record time, 72 bytes bound" in l, l + if first == 9: + assert names[stem + "_indices.bin"].read_bytes() == struct.pack("<6H", 4, 5, 6, 7, 8, 9) + print(f"{backend} buffers: o1 = plain draw, o2 = indexed draw of one key; both vertex streams hold exactly the " + "vertices each draw reads; indices exact; pixels unchanged") + + +def check(directory, consumer, backend): + off = run(directory / "off", consumer, backend) + if off is None: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + result, key, reference, files = off + if result.returncode or "-> drawn;" not in result.stderr: + raise RuntimeError(f"draw failed on {backend}: {result.returncode}\n{result.stderr}") + assert not check_pixels(reference), check_pixels(reference) + assert not files, files + print(f"{backend} off: no dump files; reference pixels pass the gradient check") + + result, key, pixels, files = run(directory / "dump", consumer, backend, "%016x") + if result.returncode or "-> drawn;" not in result.stderr: + raise RuntimeError(f"dump draw failed on {backend}: {result.returncode}\n{result.stdout}\n{result.stderr}") + assert pixels == reference, "the dump changed the drawn pixels" + names = {f.name: f for f in files} + index = [n for n in names if n.endswith(".txt")] + assert len(index) == 1, list(names) + stem = index[0][:-4] + assert stem.startswith("dddump_%016x_o1_f" % key), stem + lines = names[index[0]].read_text().splitlines() + assert lines[0] == "x2w-dddump 1 " + stem, lines[0] + assert any(l.startswith("draw plain count 3 instances 1 ") for l in lines), lines + assert any(l.startswith("entry ") for l in lines) and stem + "_root_constants.bin" in names, lines + assert (names[stem + "_root_constants.bin"].stat().st_size == 16 * 8 * 4) + tex = [l for l in lines if l.startswith("tex rtv0 ")] + assert len(tex) == 2 and " pre " in tex[0] and " post " in tex[1], tex + assert all(" %ux%ux1 " % (WIDTH, HEIGHT) in l and " fmt 28 " in l for l in tex), tex + pre = names[stem + "_rtv0_pre.bin"].read_bytes() + post = names[stem + "_rtv0_post.bin"].read_bytes() + assert pre == BLUE * (WIDTH * HEIGHT), pre.hex() + assert post == reference, (post.hex(), reference.hex()) + print(f"{backend} dump: index, entry and root constants written; rtv0 before the draw is the cleared target, " + "after it equals the read-back pixels byte for byte; pixels unchanged") + + result, key, pixels, files = run(directory / "second", consumer, backend, "%016x:2") + assert result.returncode == 63, (result.returncode, result.stdout, result.stderr) + assert not files, files + assert pixels == reference, "a non-selected dump changed the drawn pixels" + print(f"{backend} occurrence 2 of one draw: nothing selected, nothing written") + check_buffers(directory, consumer, backend) + return 0 + + +if __name__ == "__main__": + if len(sys.argv) != 3: + print("usage: startup_draw_dump_inputs_check.py <consumer> <backend>") + sys.exit(2) + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:])) diff --git a/tests/startup_draw_fma_check.py b/tests/startup_draw_fma_check.py new file mode 100644 index 0000000000..98620b67b7 --- /dev/null +++ b/tests/startup_draw_fma_check.py @@ -0,0 +1,110 @@ +"""The multiply-add rule in draw stages (tools/startup/gfx2hlsl.py, X2W_DRAW_FMA; lead 000800 answer). + +RDNA 2 ISA: V_FMA_F32 / V_FMAC_F32 / V_FMAMK_F32 / V_FMAAK_F32 compute a * b + c with one rounding; V_MAD_F32 / +V_MAC_F32 / V_MADMK_F32 / V_MADAK_F32 round the product first. Rule (the same as mesh2hlsl's): +- exact (default): fused ops -> x2w_fma_exact = (float)fma((double)a, (double)b, (double)c); unfused ops -> + x2w_mad_precise = precise multiply then precise add; the manifest says `fma exact`; +- precise: both through x2w_mad_precise; `fma precise`; +- legacy: `a * b + c` as before, no manifest line. +Checked on synthetic vertex stages (VOP3 v_fma_f32 and v_mad_f32 into v4, exp pos0 v[4:7]): the emitted call, +the helper definitions, the manifest line; a stage with no multiply-add has no `fma` line and no helper. The +helpers' arithmetic in Python with exact rationals: on a case where a * b + c rounded twice differs from the fused +value, the binary64 fma rounded to binary32 equals the fused value and the precise form equals the two-rounding +value. With fxc available, a vs_5_1 shader with both helpers compiles. Not checked: a GPU readback. +""" +import os +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)) +from startup_sampler_heap_check import root_blob # noqa: E402 +from startup_stream_check import gfx2hlsl as G # noqa: E402 + +EXPORT = (0xf80008cf, 0x07060504, 0xbf810000) # exp pos0 v4, v5, v6, v7 done; s_endpgm +PS = struct.pack('<3I', 0xf800180f, 0, 0xbf810000) +# v_mov_b32 v1, v0; v_mov_b32 v2, v3: the multiply-adds read v1 and v2 after a write. A vertex stage may read only v0 +# (vertex id) and v3 (instance id) at entry; an entry read of v1 or v2 refuses (startup_vs_instance_id_check.py). +PROLOGUE = (0x7e020300, 0x7e040303) + + +def vop3(op, dst, a, b, c): + return (0xd4000000 | op << 16 | dst, (256 + a) | (256 + b) << 9 | (256 + c) << 18) + + +def pipeline(*ops): + words = list(PROLOGUE) + [w for op in ops for w in vop3(*op)] + list(EXPORT) + vs = struct.pack('<%dI' % len(words), *words) + p = G.Pipeline(vs, PS, root_blob(flags=0)) + return [x[3] for x in G.decode(vs)][len(PROLOGUE):], p.hlsl_vs(), p.manifest().split('\n') + + +def f32(x): + return struct.unpack('<f', struct.pack('<f', float(x)))[0] + + +def round32(q): + """Fraction -> nearest binary32 (ties to even), through the exact neighbours.""" + lo = f32(q) + return lo if Fraction(lo) == q else min((lo, *(struct.unpack('<f', struct.pack('<I', struct.unpack('<I', struct.pack('<f', lo))[0] + d))[0] + for d in (-1, 1))), key=lambda v: (abs(Fraction(v) - q), struct.unpack('<I', struct.pack('<f', v))[0] & 1)) + + +def main(): + saved = G.DRAW_FMA + try: + G.DRAW_FMA = 'exact' + asm, hlsl, man = pipeline((0x14b, 4, 1, 2, 3), (0x141, 5, 1, 2, 3)) + assert asm[:2] == ['v_fma_f32 v4, v1, v2, v3', 'v_mad_f32 v5, v1, v2, v3'], asm + assert 'v4 = U(x2w_fma_exact(F(v1), F(v2), F(v3)));' in hlsl, hlsl + assert 'v5 = U(x2w_mad_precise(F(v1), F(v2), F(v3)));' in hlsl, hlsl + # draw stages carry the fxc-safe form (startup_fma_exact_fxc_check.py), same value as HELPERS['x2w_fma_exact'] + assert G.FMA_EXACT_FXC in hlsl and G.HELPERS['x2w_mad_precise'] in hlsl + assert 'fma exact' in man, man + G.DRAW_FMA = 'precise' + _, hlsl, man = pipeline((0x14b, 4, 1, 2, 3)) + assert 'v4 = U(x2w_mad_precise(F(v1), F(v2), F(v3)));' in hlsl and 'x2w_fma_exact' not in hlsl, hlsl + assert 'fma precise' in man, man + G.DRAW_FMA = 'legacy' + _, hlsl, man = pipeline((0x14b, 4, 1, 2, 3)) + assert 'v4 = U(F(v1) * F(v2) + F(v3));' in hlsl and not any(l.startswith('fma') for l in man), (hlsl, man) + G.DRAW_FMA = 'exact' + # negative control: no multiply-add, no rule line and no helper (v_add_f32 = VOP3 0x103) + _, hlsl, man = pipeline((0x103, 4, 1, 2, 2)) + assert not any(l.startswith('fma') for l in man) and 'x2w_fma_exact' not in hlsl, man + finally: + G.DRAW_FMA = saved + + # arithmetic: a = b = 1 + 2^-12, c = -(1 + 2^-11): a * b = 1 + 2^-11 + 2^-24, a tie in binary32 (rounds to + # 1 + 2^-11), so the two-rounding result is 0 and the fused one 2^-24 + a, b, c = f32(1 + 2 ** -12), f32(1 + 2 ** -12), f32(-(1 + 2 ** -11)) + exact = Fraction(a) * Fraction(b) + Fraction(c) + fused = round32(exact) + via_double = f32(float(exact)) # fma in binary64 (exact here), then binary32 + two_roundings = f32(f32(a * b) + c) # precise multiply then precise add + assert fused == via_double == 2.0 ** -24, (fused, via_double) + assert two_roundings == 0.0 and two_roundings != fused, two_roundings + + fxc = G.find_fxc() + compiled = 'skipped (no fxc)' + if fxc: + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, 'fma.hlsl') + open(src, 'w').write('%s\n%s\nfloat4 main(float4 p : POSITION) : SV_Position { return ' + 'float4(x2w_fma_exact(p.x, p.y, p.z), x2w_mad_precise(p.x, p.y, p.w), 0, 1); }\n' + % (G.HELPERS['x2w_fma_exact'], G.HELPERS['x2w_mad_precise'])) + r = subprocess.run([fxc, '/nologo', '/T', 'vs_5_1', '/E', 'main', '/Fo', os.path.join(d, 'fma.cso'), src], + capture_output=True, text=True) + assert r.returncode == 0, r.stderr + compiled = 'compiles with fxc vs_5_1' + print('draw_fma: fused -> x2w_fma_exact, unfused -> x2w_mad_precise, manifest fma exact/precise, legacy unchanged; ' + 'no multiply-add -> no line; fused value matched through binary64 where two roundings give 0; helpers %s' + % compiled) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_draw_heap_check.py b/tests/startup_draw_heap_check.py new file mode 100644 index 0000000000..50aed9492e --- /dev/null +++ b/tests/startup_draw_heap_check.py @@ -0,0 +1,83 @@ +"""Resource-heap (bindless) descriptors in a draw stage: manifest `heap 1`, behind X2W_DRAW_FEATURES=heap. + +Synthetic code: root flag 0x400 puts the resource-heap base in s8; the pixel stage builds a byte offset in s10, +loads an 8-dword image descriptor with `s_load_dwordx8 s[16:23], s[8:9], s10` and reads one texel through it. +The HLSL reads the view token at that offset from heapmem and indexes the view-id region with the layout agreed +with the draw runtime (draw-rt, board msgs 180500): heapmem t0 space1, vinfo t1 space1, Texture2D array in space2, +index 8 + 8 * id + kind (kind 0) for ids below 90000, else the empty view `kind`. With the feature off the stage is +refused exactly as before. +""" +import os +import struct +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import VS_WORDS # noqa: E402 + + +def heap_root(): + rts0 = struct.pack('<6I', 2, 0, 24, 0, 0, 0x400) + part = b'RTS0' + struct.pack('<I', len(rts0)) + rts0 + return b'DXBC' + bytes(16) + struct.pack('<III', 1, 32 + 4 + len(part), 1) + struct.pack('<I', 36) + part + + +S_MOV_S10_64 = 0xbe800000 | 10 << 16 | 3 << 8 | 192 # s_mov_b32 s10, 64 +S_LOAD_X8 = [0xf4000000 | 3 << 18 | 16 << 6 | 8 >> 1, 10 << 25] # s_load_dwordx8 s[16:23], s[8:9], s10 +V_MOV_V0_1 = 0x7e000000 | 0 << 17 | 1 << 9 | 129 # v_mov_b32 v0, 1 +V_MOV_V1_2 = 0x7e000000 | 1 << 17 | 1 << 9 | 130 # v_mov_b32 v1, 2 +IMAGE_LOAD = [0xf0000000 | 0xf << 8 | 1 << 3, 0 | 4 << 8 | (16 // 4) << 16] +EXPORT = [0xf800180f, 0x07060504] # exp mrt0 v4, v5, v6, v7 done vm + + +def words(*parts): + flat = [] + for p in parts: + flat += p if isinstance(p, list) else [p] + return struct.pack('<%dI' % (len(flat) + 1), *flat, 0xbf810000) + + +def main(): + ps = words(S_MOV_S10_64, S_LOAD_X8, V_MOV_V0_1, V_MOV_V1_2, IMAGE_LOAD, EXPORT) + text = [x[3] for x in G.decode(ps)] + assert text[1] == 's_load_dwordx8 s[16:23], s[8:9], s10', text + assert text[4] == 'image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D', text + try: + G.Pipeline(VS_WORDS, ps, heap_root(), features=()) + except G.Unsupported as error: + assert "s_load with a register offset through ('resheap',)" in str(error), str(error) + else: + raise AssertionError('heap load accepted with the feature off') + + pipe = G.Pipeline(VS_WORDS, ps, heap_root(), features=('heap',)) + hlsl, manifest = pipe.hlsl_ps(), pipe.manifest() + for line in ('ByteAddressBuffer heapmem : register(t0, space1);', + 'ByteAddressBuffer vinfo : register(t1, space1);', + 'uint x2w_vid(uint h) { return heapmem.Load(h) == 0x56573258u ? heapmem.Load(h + 4) : 0xffffffffu; }', + 'uint x2w_hix(uint h, uint k) { uint i = x2w_vid(h); return i < 90000u ? 8u + 8u * i + k : k; }', + 'Texture2D<float4> heaptex2d[720008] : register(t0, space2);', + 'h0 = 0x00000040u;', + 't = heaptex2d[NonUniformResourceIndex(x2w_hix(h0, 0u))].Load(int3(v0, v1, 0));'): + assert line in hlsl, (line, hlsl) + assert 'heaptex2da' not in hlsl and 'heapbuf' not in hlsl, 'only the kinds used are declared' + assert 'heap 1' in manifest.split('\n') and 'srv ' not in manifest, manifest + # The index helper, evaluated: ids below 90000 land at 8 + 8 * id + kind, others on the empty view kind. + hix = lambda i, k: 8 + 8 * i + k if i < 90000 else k # noqa: E731 + assert (hix(0, 0), hix(1, 0), hix(89999, 4), hix(0xffffffff, 2)) == (8, 16, 720004, 2) + assert hix(89999, 4) < 720008, 'the bounded arrays cover the whole view-id region' + # A heap descriptor's words are not numbers here: reading one is refused. + numeric = words(S_MOV_S10_64, S_LOAD_X8, 0x7e000000 | 4 << 17 | 1 << 9 | 17, # v_mov_b32 v4, s17 + V_MOV_V1_2, 0x7e000000 | 5 << 17 | 1 << 9 | 130, 0x7e000000 | 6 << 17 | 1 << 9 | 130, + 0x7e000000 | 7 << 17 | 1 << 9 | 130, EXPORT) + try: + G.Pipeline(VS_WORDS, numeric, heap_root(), features=('heap',)).hlsl_ps() + except G.Unsupported as error: + assert 'holding desc' in str(error), str(error) + else: + raise AssertionError('a heap descriptor word was read as a number') + print('heap: texel through a run-time heap offset; manifest heap 1; feature-off and numeric-word controls refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_draw_heapwords_check.py b/tests/startup_draw_heapwords_check.py new file mode 100644 index 0000000000..f7d2fe0a09 --- /dev/null +++ b/tests/startup_draw_heapwords_check.py @@ -0,0 +1,142 @@ +"""buffer_load_format_* through a resource-heap descriptor in a draw stage: manifest `heapwords 1`. + +Synthetic code (layout of startup_draw_heap_check): root flag 0x400 puts the resource-heap base in s8; the pixel +stage loads a 4-dword buffer descriptor with `s_load_dwordx4 s[16:19], s[8:9], s10` and then +`buffer_load_format_x v4, v0, s[16:19], 0 idxen`. The format and swizzle are in the descriptor's word 3, which +the title's heap slot does not hold as a number (it holds a view token). Contract (mesh_work/RUNTIME_NEEDS.md 6.3, +the same as mesh2hlsl's x2w_hword; runtime d3d12_vdesc.inl, bound for draws by d3d12_draw.inl): vdesc, 32 bytes per +view id, root SRV t2 space1, word i at id * 32 + 4 * i, 0 for an unknown slot or id >= 90000. + +Checked: with X2W_DRAW_FEATURES heap,bufword3,heapwords the load is x2w_fmt_load(heapbuf[...], a, +x2w_hword(h0, 3u), 0u), the address is the index times the view's vinfo stride, vdesc and x2w_hword are declared +and the manifest has `heap 1` then `heapwords 1`. The helper is evaluated in Python on a token / id table. +Negative controls: without heapwords (heap,bufword3 only) the old refusal "through heapdyn" stays; a program with +no heap format load has no vdesc declaration and no `heapwords 1` line. + +Words read as numbers (an image's base-level width and the null test `word1 == 0`, the waterfall dimension code): +`s_and_b32 s21, s18, 0x3fff; s_bfe_u32 s20, s17, 0x2001e; s_cmp_eq_i32 s17, 0; s_cselect_b32 s21, 0, s21` read +x2w_hword(h0, 2u) / (h0, 1u), with no heapmem slot kind in use (heap 1 and the helpers still declared); the emitted +expressions are evaluated on a vdesc word table. Refused: without heapwords, and a word of a descriptor the program +edited in place (s_and_b32 s19, s19, 0xcfffffff: no longer the synthesized word). +""" +import os +import struct +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import VS_WORDS # noqa: E402 +from startup_draw_heap_check import heap_root, words, S_MOV_S10_64, S_LOAD_X8, V_MOV_V0_1, V_MOV_V1_2, \ + IMAGE_LOAD, EXPORT # noqa: E402 + +S_LOAD_X4 = [0xf4000000 | 2 << 18 | 16 << 6 | 8 >> 1, 10 << 25] # s_load_dwordx4 s[16:19], s[8:9], s10 +FORMAT_X = [0xe0000000 | 0 << 18 | 1 << 13, 0 | 4 << 8 | 4 << 16 | 128 << 24] # buffer_load_format_x v4, v0, s[16:19], 0 idxen +MOVS = [0x7e000000 | n << 17 | 1 << 9 | 130 for n in (5, 6, 7)] # v_mov_b32 v5..v7, 2 + + +def sop2(op, dst, a, b): + return 0x80000000 | op << 23 | dst << 16 | b << 8 | a + + +# s_and_b32 s21, s18, 0x3fff; s_bfe_u32 s20, s17, 0x2001e; s_cmp_eq_i32 s17, 0; s_cselect_b32 s21, 0, s21; +# v_mov_b32 v4, s21 +NUMERIC = [sop2(14, 21, 18, 255), 0x3fff, sop2(39, 20, 17, 255), 0x2001e, 0xbf000000 | 128 << 8 | 17, + sop2(10, 21, 128, 21), 0x7e000000 | 4 << 17 | 1 << 9 | 21] +EDITED = [sop2(14, 19, 19, 255), 0xcfffffff, 0xbf000000 | 128 << 8 | 19] # s_and_b32 s19, s19, 0xcfffffff; s_cmp_eq_i32 s19, 0 + + +def hword(heapmem, vdesc, h, i): + """x2w_hword as emitted: token check at heapmem[h], id below 90000, else 0.""" + token, vid = heapmem.get(h, (0, 0)) + vid = vid if token == G.HEAP_TOKEN else 0xffffffff + return vdesc.get((vid, i), 0) if vid < 90000 else 0 + + +def main(): + ps = words(S_MOV_S10_64, S_LOAD_X4, V_MOV_V0_1, FORMAT_X, MOVS, EXPORT) + text = [x[3] for x in G.decode(ps)] + assert text[1] == 's_load_dwordx4 s[16:19], s[8:9], s10', text + assert text[3] == 'buffer_load_format_x v4, v0, s[16:19], 0 idxen', text + + for features in (('heap', 'bufword3'), ('heap', 'bufword3', 'uav')): + try: + G.Pipeline(VS_WORDS, ps, heap_root(), features=features).hlsl_ps() + except G.Unsupported as error: + assert 'buffer_load_format_x through heapdyn' in str(error), str(error) + else: + raise AssertionError('heap format load accepted without heapwords (%s)' % (features,)) + + pipe = G.Pipeline(VS_WORDS, ps, heap_root(), features=('heap', 'bufword3', 'heapwords')) + hlsl, manifest = pipe.hlsl_ps(), pipe.manifest() + for line in ('ByteAddressBuffer x2w_vdesc : register(t2, space1);', + 'uint x2w_hword(uint h, uint i) { uint id = x2w_vid(h); return id < 90000u ? ' + 'x2w_vdesc.Load(id * 32u + 4u * i) : 0u; }', + 'ByteAddressBuffer heapbuf[720008] : register(t0, space6);', + 'a = v0 * x2w_vstride(h0) + 0;', + 'v4 = x2w_fmt_load(heapbuf[NonUniformResourceIndex(x2w_hix(h0, 4u))], a, x2w_hword(h0, 3u), 0u);'): + assert line in hlsl, (line, hlsl) + assert 'uint x2w_fmt_load(' in hlsl, 'the format decoder is emitted' + lines = manifest.split('\n') + assert 'heap 1' in lines and 'heapwords 1' in lines and lines.index('heapwords 1') == lines.index('heap 1') + 1, manifest + assert not any(l.startswith('udsrc') and 'bufword3' in l for l in lines), manifest + + # the helper, evaluated: slot 64 holds view 7, whose word 3 is 0x00026fac (an arbitrary value) + heapmem = {64: (G.HEAP_TOKEN, 7), 96: (0x12345678, 7), 128: (G.HEAP_TOKEN, 90000)} + vdesc = {(7, 3): 0x00026fac, (7, 1): 0x00100000} + assert hword(heapmem, vdesc, 64, 3) == 0x00026fac and hword(heapmem, vdesc, 64, 1) == 0x00100000 + assert hword(heapmem, vdesc, 96, 3) == 0, 'a slot without the view token reads 0' + assert hword(heapmem, vdesc, 128, 3) == 0, 'an id at the limit reads 0' + assert hword(heapmem, vdesc, 32, 3) == 0, 'an empty slot reads 0' + + # Negative control: a heap program without a format load has neither vdesc nor `heapwords 1`. + plain = G.Pipeline(VS_WORDS, words(S_MOV_S10_64, S_LOAD_X8, V_MOV_V0_1, V_MOV_V1_2, IMAGE_LOAD, EXPORT), + heap_root(), features=('heap', 'bufword3', 'heapwords')) + assert 'x2w_vdesc' not in plain.hlsl_ps() and 'heapwords 1' not in plain.manifest().split('\n'), plain.manifest() + numeric = numeric_words(heapmem) + print('heapwords: heap typed load reads word 3 from vdesc (t2 space1); manifest heap 1 + heapwords 1; ' + 'refused without heapwords; helper evaluated on 4 slots; image-only heap program unchanged; ' + 'numeric word reads evaluated on %d views, refused without heapwords and after an in-place edit' % numeric) + + +def numeric_words(heapmem): + ps = words(S_MOV_S10_64, S_LOAD_X4, NUMERIC, MOVS, EXPORT) + text = [x[3] for x in G.decode(ps)] + assert text[2:7] == ['s_and_b32 s21, s18, 0x3fff', 's_bfe_u32 s20, s17, 0x2001e', 's_cmp_eq_i32 s17, 0', + 's_cselect_b32 s21, 0, s21', 'v_mov_b32_e32 v4, s21'], text + pipe = G.Pipeline(VS_WORDS, ps, heap_root(), features=('heap', 'bufword3', 'heapwords')) + hlsl, manifest = pipe.hlsl_ps(), pipe.manifest() + body = [line.strip() for line in hlsl.splitlines()] + expected = ['h0 = 0x00000040u;', 's21 = x2w_hword(h0, 2u) & 0x00003fffu;', + 's20 = (x2w_hword(h0, 1u) >> (0x0002001eu & 31)) & ((1u << ((0x0002001eu >> 16) & 127)) - 1);', + 'scc = int(x2w_hword(h0, 1u)) == int(0x00000000u);', 's21 = scc ? 0x00000000u : s21;', 'v4 = s21;'] + for line in expected: + assert line in body, (line, hlsl) + assert 'ByteAddressBuffer heapmem : register(t0, space1);' in body and 'ByteAddressBuffer x2w_vdesc : register(t2, space1);' in body, hlsl + lines = manifest.splitlines() + assert 'heap 1' in lines and 'heapwords 1' in lines, manifest + # The emitted lines, evaluated: v4 = WIDTH_HI field of word 2, or 0 for a null view (word 1 == 0). + views = 0 + for word1, word2 in ((0x00100000 | 2 << 30, 0x12345), (0, 0x12345), (1 << 8, 0x3fff), (0xc0000000, 0)): + vdesc = {(7, 1): word1, (7, 2): word2} + w1, w2 = hword(heapmem, vdesc, 64, 1), hword(heapmem, vdesc, 64, 2) + s21 = w2 & 0x3fff + s20 = (w1 >> (0x2001e & 31)) & ((1 << ((0x2001e >> 16) & 127)) - 1) + assert s20 == word1 >> 30 + v4 = 0 if w1 == 0 else s21 + assert v4 == (0 if word1 == 0 else word2 & 0x3fff) + views += 1 + for features, program, why in ((('heap', 'bufword3'), NUMERIC, 'numeric use of s17 holding desc'), + (('heap', 'bufword3', 'heapwords'), EDITED, 'numeric use of s19 holding desc')): + try: + G.Pipeline(VS_WORDS, words(S_MOV_S10_64, S_LOAD_X4, program, MOVS, EXPORT), heap_root(), + features=features).hlsl_ps() + except G.Unsupported as error: + assert why in str(error), str(error) + else: + raise AssertionError('accepted: ' + why) + return views + + +if __name__ == '__main__': + main() diff --git a/tests/startup_draw_lock_split_check.py b/tests/startup_draw_lock_split_check.py new file mode 100644 index 0000000000..64e079cd4e --- /dev/null +++ b/tests/startup_draw_lock_split_check.py @@ -0,0 +1,151 @@ +"""LOCAL stall: two threads issue translated draws with a buffer srv at the same time (X2W_DRAW_LOCK_SPLIT). + +The consumer runs a startup_frame_copy frame on X2W_TEST_THREADS=2 threads, X2W_TEST_REPEAT times each: per +thread its own constant buffer, target, list, queue and fence; one shared device and pipeline. Two frames: +- "changed": red, rewritten to blue between the two draws of one list, red again next frame: every frame copy + misses the cache (compare fails or nothing cached) and is copied fresh. +- "same": red twice: after each thread's first draw the copies are cache hits. +X2W_DRAW_LOCK_TIMES=1 in both modes; the consumer writes the lock-times report ("fixture") at the end. + +- split (X2W_DRAW_LOCK_SPLIT=1): exact pixels per thread; site ids read from d3d12_draw.inl: the tail lock_draw + and frame_copy_unlocked's lookup are taken once per draw; its commit (lookup id + 1) once per miss: every draw + for "changed", 2 to 49 of 100 for "same" (at least each thread's first; a hit whose ring chunk was recycled + meanwhile is a miss too). +- locked (control, switch off): the same pixels; no split-only site appears in the report. + +Both: the entry site of draw_translated is taken once per draw (2 per frame). +""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_address_srv_check import prepare_draw_cache + +HLSL = ( + "ByteAddressBuffer constants : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " return asfloat(constants.Load4(0));\n" + "}\n" +) +RED = bytes((255, 0, 0, 255)) +BLUE = bytes((0, 0, 255, 255)) +THREADS, REPEAT = 2, 25 +SOURCE = Path(__file__).resolve().parent.parent / "src" / "startup_stubs" / "d3d12_draw.inl" + + +def sites(): + """Site ids of draw_translated read from the source lines: entry, tail, frame_copy_unlocked lookup and commit + (lookup + 1), and every site that exists only under the switch.""" + lines = SOURCE.read_text(encoding="utf-8", errors="replace").splitlines() + start = next(i for i, line in enumerate(lines) if line.startswith("bool draw_translated(")) + entry = tail = lookup = None + compare = next(i for i, line in enumerate(lines) if line.startswith("bool compare_draw_copy(")) + copy_tail = next(100000 + i + 1 for i in range(compare, len(lines)) if "lock_draw(100000 + __LINE__)" in lines[i]) + split_only = {copy_tail} + for i in range(start, len(lines)): + line, number = lines[i], 100000 + i + 1 + if line.startswith("}"): + break + if entry is None and "lock_draw(100000 + __LINE__)" in line: + entry = number + if "SplitRelock relock(split, 100000 + __LINE__)" in line: + split_only.add(number) + if "have = frame_copy_unlocked(" in line: + lookup = number + split_only.update((number, number + 1)) + if "if (split) lock_draw(100000 + __LINE__)" in line: + tail = number + split_only.add(number) + if None in (entry, tail, lookup, copy_tail): + raise RuntimeError(f"draw_translated site ids not found in {SOURCE}: entry {entry} tail {tail} lookup {lookup}") + return entry, tail, lookup, lookup + 1, copy_tail, split_only + + +def report_holds(log): + lines = [line for line in log.splitlines() if "x2w-draw lock times (fixture" in line] + if len(lines) != 1: + raise AssertionError(f"{len(lines)} fixture lock-times lines") + return {int(m.group(1)): int(m.group(2)) for m in re.finditer(r" (\d+) \S+ (\d+)/[\d.]+/[\d.]+, \d+/", lines[0])}, lines[0] + + +def run(directory, consumer, backend, mode, frame): + """frame "changed": every draw misses the frame-copy cache (red, then blue, then red again on the next frame); + "same": red twice, so after each thread's first draw the copies are cache hits.""" + entry, tail, lookup, commit, copy_tail, split_only = sites() + folder = directory / frame + folder.mkdir() + env, args, output = prepare_draw_cache(folder, consumer, HLSL, {"X2W_TEST_FRAME_COPY": frame}, "srv 0 buf table 0 0") + for name in ("X2W_DRAW_LOCK_SPLIT", "X2W_DRAW_COPY_SPLIT_MIN", "X2W_DRAW_ASYNC", "X2W_DRAW_SRV_IN_PLACE"): + env.pop(name, None) + env.update(X2W_TEST_THREADS=str(THREADS), X2W_TEST_REPEAT=str(REPEAT), X2W_DRAW_LOCK_TIMES="1") + if mode == "split": + env["X2W_DRAW_LOCK_SPLIT"] = "1" + if mode == "copy": + env["X2W_DRAW_COPY_SPLIT_MIN"] = "1" + if mode == "below": + env["X2W_DRAW_COPY_SPLIT_MIN"] = "1048576" + result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True, timeout=120) + print(result.stdout, end="") + if backend == "hardware" and result.returncode == 77: + print("No D3D12 feature-level 12 hardware adapter") + return None + if result.returncode: + raise RuntimeError(f"consumer failed on {backend}: {result.returncode}\n{result.stderr[-5000:]}") + holds, line = report_holds(result.stderr) + print(line) + draws = THREADS * REPEAT * 2 + wanted = (RED * 4 + BLUE * 4) * 4 if frame == "changed" else RED * 32 + failures = [] + for t in range(THREADS): + pixels = Path(f"{output}.t{t}").read_bytes() + if pixels != wanted: + failures.append(f"{frame} thread {t}: {pixels.hex()} want {wanted.hex()}") + if holds.get(entry) != draws: + failures.append(f"{frame} entry site {entry}: {holds.get(entry)} holds, want {draws}") + seen = sorted(site for site in split_only if site in holds) + if mode == "copy": + if seen != [copy_tail] or not 0 < holds.get(copy_tail, 0) < draws: + failures.append(f"{frame}: need only compare relock {copy_tail}, between first snapshot and final draw; got {seen}, {holds}") + elif mode == "split": + if copy_tail in holds: + failures.append(f"{frame}: copy-only relock active in broad split") + if holds.get(tail) != draws: + failures.append(f"{frame} tail site {tail}: {holds.get(tail)} holds, want {draws}") + if holds.get(lookup) != draws: + failures.append(f"{frame} frame_copy lookup site {lookup}: {holds.get(lookup)} holds, want {draws}") + misses = holds.get(commit, 0) + if frame == "changed" and misses != draws: + failures.append(f"changed: {misses} frame_copy commits (misses), want {draws}") + if frame == "same" and not THREADS <= misses < draws // 2: + failures.append(f"same: {misses} frame_copy commits (misses), want {THREADS} to {draws // 2 - 1} (mostly hits)") + elif seen: + failures.append(f"{frame}: split-only sites {seen} without the switch") + if any("x2w-d3d12-debug " in l and (" sev=0 " in l or " sev=1 " in l) for l in result.stderr.splitlines()): + failures.append(f"{frame}: debug-layer error or corruption") + print(f"{backend} {mode} {frame}: {THREADS} threads x {REPEAT} frames, entry {entry}={holds.get(entry)}, tail {tail}={holds.get(tail)}, " + f"frame_copy lookup {lookup}={holds.get(lookup)} commit {commit}={holds.get(commit)}, split-only sites in the report {seen}") + return failures + + +def check(directory, consumer, backend, mode): + if mode not in ("split", "copy", "below", "locked"): + return 2 + failures = [] + for frame in ("changed", "same"): + result = run(directory, consumer, backend, mode, frame) + if result is None: + return 77 + failures += result + if failures: + print("FAIL: " + "; ".join(failures)) + return 1 + print("PASS") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:])) diff --git a/tests/startup_draw_lock_times.cpp b/tests/startup_draw_lock_times.cpp new file mode 100644 index 0000000000..615c4c597e --- /dev/null +++ b/tests/startup_draw_lock_times.cpp @@ -0,0 +1,87 @@ +// LOCAL stall: draw_lock hold and wait times by site (d3d12_draw.inl, X2W_DRAW_LOCK_TIMES). +// +// startup_draw_lock_times <on|off> +// (on: X2W_DRAW_LOCK_TIMES=1; the test sets X2W_TRAP_LOG itself) +// +// Three threads take draw_lock through the stand-in's own lock_draw (export x2w_draw_lock_times_test op 0), 50 times +// each: site 999001 holds 2 ms, site 999002 holds 2 ms, site 999003 holds 0 ms. Then op 1 writes the report. +// on: one "x2w-draw lock times (fixture" line; 999001 and 999002 each 50 holds, total 100-1000 ms, max >= 2 ms; +// 999003 50 holds; the waits over all sites > 0 with a total above 50 ms (the 2 ms holders contend). +// off (control): op 1 returns 0 and no such line is written. No GPU is used (the export never touches the device). +// Exit 0 pass, other values name the step. +#include <windows.h> + +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <fstream> +#include <iterator> +#include <string> +#include <thread> +#include <vector> + +using Test = std::uint64_t(WINAPI*)(int, std::uint64_t, std::uint64_t); + +namespace { +struct SiteRow { long holds = -1; double hold_total = 0, hold_max = 0; long waits = 0; double wait_total = 0, wait_max = 0; }; +SiteRow find_site(const std::string& line, long id) +{ + SiteRow row; + const std::string key = " " + std::to_string(id) + " fixture "; + const std::size_t p = line.find(key); + if (p == std::string::npos) return row; + std::sscanf(line.c_str() + p + key.size(), "%ld/%lf/%lf, %ld/%lf/%lf", &row.holds, &row.hold_total, &row.hold_max, &row.waits, + &row.wait_total, &row.wait_max); + return row; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + const std::string mode = argv[1]; + if (mode != "on" && mode != "off") return 2; + wchar_t temp[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, temp)) return 3; + const std::wstring log_path = std::wstring(temp) + L"x2w_draw_lock_times_" + std::to_wstring(GetCurrentProcessId()) + L"_" + + std::to_wstring(GetTickCount64()) + L".log"; + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + HMODULE module = LoadLibraryW(L"d3d12_xs.dll"); + if (!module) return 4; + const auto test = reinterpret_cast<Test>(GetProcAddress(module, "x2w_draw_lock_times_test")); + if (!test) return 5; + std::vector<std::thread> threads; + for (int t = 1; t <= 3; ++t) + threads.emplace_back([test, t] { + for (int i = 0; i < 50; ++i) test(0, t == 3 ? 0 : 2000, static_cast<std::uint64_t>(t)); + }); + for (auto& thread : threads) thread.join(); + const std::uint64_t reported = test(1, 0, 0); + + std::ifstream file(log_path, std::ios::binary); + const std::string log{std::istreambuf_iterator<char>(file), {}}; + const std::size_t at = log.find("x2w-draw lock times (fixture"); + const std::string line = at == std::string::npos ? std::string() : log.substr(at, log.find('\n', at) - at); + int failures = 0; + if (mode == "off") { + std::printf("op 1 -> %llu (want 0); report line %s (want none)\n", static_cast<unsigned long long>(reported), line.empty() ? "none" : "present"); + if (reported != 0 || !line.empty()) ++failures; + } else { + std::printf("%s\n", line.empty() ? "no report line" : line.c_str()); + if (reported != 1 || line.empty()) ++failures; + double waited = 0; + for (long id : {999001L, 999002L, 999003L}) { + const SiteRow r = find_site(line, id); + std::printf("site %ld: holds %ld total %.1f ms max %.2f ms; waits %ld total %.1f ms max %.2f ms\n", id, r.holds, r.hold_total, r.hold_max, + r.waits, r.wait_total, r.wait_max); + waited += r.wait_total; + if (r.holds != 50) ++failures; + if (id != 999003 && (r.hold_total < 100.0 || r.hold_total > 1000.0 || r.hold_max < 2.0)) ++failures; + } + std::printf("waited over the three sites %.1f ms (want > 50)\n", waited); + if (waited <= 50.0) ++failures; + } + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; +} diff --git a/tests/startup_draw_srv_limit_check.py b/tests/startup_draw_srv_limit_check.py new file mode 100644 index 0000000000..1486dbf735 --- /dev/null +++ b/tests/startup_draw_srv_limit_check.py @@ -0,0 +1,63 @@ +"""Read the final SRV of a translated draw table on WARP and check its upper bound.""" +import os +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from startup_formatted_view_draw_check import CASES, CLEAR, PIXEL, TARGET, spec +from startup_stream_check import gfx2hlsl +from startup_stream_draw_check import vertex + + +def check(work, consumer, fxc): + cache = work / 'cache' + cache.mkdir() + vs, ps, root, output = (work / name for name in ('vs', 'ps', 'root', 'pixels')) + vs.write_bytes(vertex()) + ps.write_bytes(PIXEL) + env = dict(os.environ, X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1', X2W_D3D12_RENDER='1', + X2W_D3D12_DEBUG='1', X2W_SHADER_CACHE=str(cache), X2W_FXC=fxc, + X2W_DRAW_FEATURES='bufword3', X2W_TEST_FORMATTED_VIEW=spec(CASES[0])) + + def draw(): + result = subprocess.run([consumer, vs, ps, root, 'warp', output, str(TARGET)], env=env, + capture_output=True, text=True, timeout=60) + if result.returncode == 77: + raise SystemExit(77) + assert result.returncode == 0, result.stderr[-2000:] + assert not re.search(r'x2w-d3d12-debug.*sev=[012]\b', result.stderr), result.stderr[-2000:] + return struct.unpack('<4I', output.read_bytes()[:16]), result.stderr + + for _ in range(2): + draw() + subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', cache], env=env, check=True) + variant = next(p for p in cache.glob('*.txt') if 'rtv1' in p.read_text()) + hlsl = variant.with_suffix('.ps.hlsl') + source = hlsl.read_text() + original_manifest = variant.read_text() + assert 'srv 0 buf table 0 0' in original_manifest and 'register(t0)' in source + # Only the final slot names the typed view. Reading any filler slot returns a different value. + for slot in (31, 32, 63, 64): + entries = ['srv %d buf vb 7' % i for i in range(slot)] + ['srv %d buf table 0 0' % slot] + manifest = original_manifest.replace('srv 0 buf table 0 0', '\n'.join(entries)) + for kind in ('stride', 'bufword3'): + manifest = re.sub(r'(udsrc \d+ %s )0$' % kind, lambda m: m[1] + str(slot), manifest, flags=re.M) + variant.write_text(manifest.replace(' bufword3 ', ' descword3 ')) + hlsl.write_text(source.replace('register(t0)', 'register(t%d)' % slot)) + subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', variant.with_suffix('.ps.cso'), hlsl], + check=True, capture_output=True) + words, log = draw() + accepted = slot < 64 + assert ('-> drawn;' in log) == accepted, (slot, log[-2000:]) + assert words == (CASES[0][5] if accepted else CLEAR), (slot, words, log[-2000:]) + print('t%d: %s' % (slot, 'bit-exact' if accepted else 'over-limit translation refused')) + + +if __name__ == '__main__': + if not Path(sys.argv[2]).is_file(): + raise SystemExit(77) + with tempfile.TemporaryDirectory() as temp: + check(Path(temp), *sys.argv[1:]) diff --git a/tests/startup_draw_state.cpp b/tests/startup_draw_state.cpp new file mode 100644 index 0000000000..aee01fc8d6 --- /dev/null +++ b/tests/startup_draw_state.cpp @@ -0,0 +1,296 @@ +// Draws through device slot 57 pipelines whose state block A carries hand-written DB_DEPTH_CONTROL, +// PA_SU_SC_MODE_CNTL and CB_TARGET_MASK words (pipeline_state_decode.h), into an 8x4 RGBA target with +// a D32 depth target, and writes each case's pixels to <outdir>/<case>. Whether the decoded state is +// applied is decided by the X2W_DRAW_STATE_* switches the driver script sets; this program only draws. +// No title data. +// +// usage: startup_draw_state <vs_near> <vs_far> <ps_green> <ps_red> <root out> <warp|hardware> [<outdir>] +// Without <outdir>: creates the stream pipelines only (their shader requests feed the offline translator). +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <iterator> +#include <string> +#include <vector> + +#include "startup_stream_setup.h" + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { + +using Word = std::uint64_t; +template <class T> Word ptr_arg(T* p) { return reinterpret_cast<Word>(p); } + +bool read_bytes(const char* path, std::vector<char>& out) +{ + std::ifstream file(path, std::ios::binary); + out.assign(std::istreambuf_iterator<char>(file), {}); + return !out.empty(); +} + +int pick_adapter(bool hardware, ComPtr<IDXGIAdapter>& adapter) +{ + ComPtr<IDXGIFactory4> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; + if (!hardware) return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) ? 0 : 4; + ComPtr<IDXGIFactory6> factory6; + if (FAILED(factory.As(&factory6))) return 77; + for (UINT n = 0;; ++n) { + ComPtr<IDXGIAdapter1> candidate; + const HRESULT hr = factory6->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 4; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 4; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + return 0; + } + } +} + +struct alignas(8) StageSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + D3D12_SHADER_BYTECODE shader; +}; +struct alignas(8) RootSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + ID3D12RootSignature* signature; +}; +struct PlainStream { + StageSubobject ps; + RootSubobject root; + StageSubobject vs; +}; + +void* create_stream_pso(void* device, void* root, const std::vector<char>& vs, const std::vector<char>& ps) +{ + using CreateStream = HRESULT(WINAPI*)(void*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); + PlainStream stream{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {ps.data(), ps.size()}}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, static_cast<ID3D12RootSignature*>(root)}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, {vs.data(), vs.size()}}}; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + void* pso = nullptr; + return SUCCEEDED(reinterpret_cast<CreateStream>((*static_cast<void***>(device))[86])(device, &desc, __uuidof(ID3D12PipelineState), &pso)) + ? pso : nullptr; +} + +// Slot 57 description as the stand-in reads it (tests/startup_stream_consumer.cpp): 64-bit words 0 (root +// signature), 1-2 (state block A and its size), 5-6 and 9-10 (vertex and pixel shader). The shaders are +// read at the first draw, so their storage outlives the pipeline here. +struct Slot57 { + std::vector<unsigned char> desc = std::vector<unsigned char>(0x300); + std::vector<unsigned char> state_a = std::vector<unsigned char>(0x200); +}; + +void* create_slot57(void* device, void* root, const std::vector<char>& vs, const std::vector<char>& ps, + const std::vector<std::pair<unsigned, std::uint32_t>>& words, Slot57& keep) +{ + for (const auto& [offset, word] : words) std::memcpy(keep.state_a.data() + offset, &word, sizeof(word)); + const Word d[12] = {ptr_arg(root), ptr_arg(keep.state_a.data()), keep.state_a.size(), 0, 0, ptr_arg(vs.data()), vs.size(), 0, 0, + ptr_arg(ps.data()), ps.size(), 0}; + std::memcpy(keep.desc.data(), d, sizeof(d)); + using Create = HRESULT(WINAPI*)(void*, const void*, REFIID, void**); + void* pso = nullptr; + return SUCCEEDED(reinterpret_cast<Create>((*static_cast<void***>(device))[57])(device, keep.desc.data(), __uuidof(ID3D12PipelineState), &pso)) + ? pso : nullptr; +} + +// The depth target is cleared on the desktop device (list slot 51 is the stand-in's own subject). +int clear_depth_desktop(ID3D12Device* desktop, ID3D12Resource* depth_tex, float value) +{ + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; + ComPtr<ID3D12DescriptorHeap> heap; + if (FAILED(desktop->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))) return 40; + const D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; + const D3D12_CPU_DESCRIPTOR_HANDLE handle = heap->GetCPUDescriptorHandleForHeapStart(); + desktop->CreateDepthStencilView(depth_tex, &dsv_desc, handle); + D3D12_COMMAND_QUEUE_DESC qd{}; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> alloc; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + if (FAILED(desktop->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue))) || + FAILED(desktop->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc))) || + FAILED(desktop->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.Get(), nullptr, IID_PPV_ARGS(&list))) || + FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) return 41; + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {depth_tex, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE}; + list->ResourceBarrier(1, &b); + list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH, value, 0, 0, nullptr); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; + list->ResourceBarrier(1, &b); + if (FAILED(list->Close())) return 42; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), 1))) return 43; + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!ev) return 44; + const bool ok = SUCCEEDED(fence->SetEventOnCompletion(1, ev)) && WaitForSingleObject(ev, 10000) == WAIT_OBJECT_0; + CloseHandle(ev); + return ok ? 0 : 45; +} + +int execute_guest_list(void* queue, void* list, void* fence, UINT64 fence_value) +{ + if (FAILED(static_cast<HRESULT>(invoke(list, 9)))) return 50; + void* lists[] = {list}; + invoke(queue, 10, 1, ptr_arg(lists)); + if (FAILED(static_cast<HRESULT>(invoke(queue, 14, ptr_arg(fence), fence_value)))) return 51; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < fence_value && GetTickCount64() < deadline) Sleep(1); + return invoke(fence, 8) >= fence_value ? 0 : 53; +} + +// State block A offsets (vertex layout) and register fields used here. +constexpr unsigned a_shader_mask = 0x78, a_mode = 0xa0, a_depth = 0xb8, a_target_mask = 0xcc; +constexpr std::uint32_t z_less_write = 1u << 1 | 1u << 2 | 1u << 4; // Z_ENABLE, Z_WRITE_ENABLE, ZFUNC FRAG_LESS +constexpr std::uint32_t cull_front = 1u << 0, cull_back = 1u << 1, face_cw = 1u << 2; + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 7 && argc != 8) return 2; + std::vector<char> vs_near, vs_far, ps_green, ps_red; + if (!read_bytes(argv[1], vs_near) || !read_bytes(argv[2], vs_far) || !read_bytes(argv[3], ps_green) || !read_bytes(argv[4], ps_red)) return 3; + const bool hardware = std::strcmp(argv[6], "hardware") == 0; + ComPtr<IDXGIAdapter> adapter; + if (const int rc = pick_adapter(hardware, adapter)) return rc; + std::array<unsigned char, 64> parameters{}; + void* guest = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &guest))) return 5; + D3D12_ROOT_SIGNATURE_DESC root_desc{}; + ComPtr<ID3DBlob> blob; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr))) return 6; + std::ofstream(argv[5], std::ios::binary).write(static_cast<const char*>(blob->GetBufferPointer()), blob->GetBufferSize()); + void* root = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 16, 0, ptr_arg(blob->GetBufferPointer()), blob->GetBufferSize(), + ptr_arg(&__uuidof(ID3D12RootSignature)), ptr_arg(&root))))) return 7; + if (argc == 7) { + // Request pass: the same shader pairs through slot 86 publish their translation requests. + return create_stream_pso(guest, root, vs_near, ps_green) && create_stream_pso(guest, root, vs_far, ps_red) ? 0 : 9; + } + const std::string outdir = argv[7]; + + // Every case keeps all channels writable unless it sets the target mask itself. + const std::vector<std::pair<unsigned, std::uint32_t>> rgba = {{a_shader_mask, 0xF}, {a_target_mask, 0xF}}; + auto with = [&](std::vector<std::pair<unsigned, std::uint32_t>> extra) { + auto words = rgba; + words.insert(words.end(), extra.begin(), extra.end()); + return words; + }; + struct Case { + const char* name; + std::vector<std::pair<unsigned, std::uint32_t>> words; + bool far_second; // also draw the far red triangle after the near green one, same state + UINT guest_clear = 0; // list slot 51 with these flags and guest_depth, after the desktop pre-clear + float desktop_depth = 1.0f; + float guest_depth = 1.0f; + }; + // The depth target is one resource for all cases and the shim never forgets a cleared target, so the cases that + // must see it uncleared run first. + const Case cases[] = { + {"uncleared", with({{a_depth, z_less_write}}), false, 0, 0.0f}, + // A stencil-only clear on a D32 target does not initialise depth: same as uncleared. + {"guest_clear_stencil_only", with({{a_depth, z_less_write}}), false, D3D12_CLEAR_FLAG_STENCIL, 0.0f}, + {"depth", with({{a_depth, z_less_write}}), true, D3D12_CLEAR_FLAG_DEPTH}, + // Negative control: bits 30-31 make the decoder refuse the word, so the draw keeps the state of before. + {"depth_refused", with({{a_depth, z_less_write | 1u << 30}}), true, D3D12_CLEAR_FLAG_DEPTH}, + {"no_state", with({}), true}, + {"cull_back", with({{a_mode, cull_back}}), false}, + {"cull_front", with({{a_mode, cull_front}}), false}, + {"cull_back_face1", with({{a_mode, cull_back | face_cw}}), false}, + {"mask_rg", {{a_shader_mask, 0xF}, {a_target_mask, 0x3}}, false}, + // List slot 51: a forwarded depth clear to 1 lets the near triangle pass LESS over a depth of 0. + {"guest_clear", with({{a_depth, z_less_write}}), false, D3D12_CLEAR_FLAG_DEPTH, 0.0f, 1.0f}, + // Negative control: a forwarded clear to 0 over a desktop depth of 1 makes LESS fail, so the value is forwarded. + {"guest_clear0", with({{a_depth, z_less_write}}), false, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0.0f}, + }; + std::vector<Slot57> keep(2 * std::size(cases)); + std::vector<std::pair<void*, void*>> psos; + for (std::size_t i = 0; i < std::size(cases); ++i) { + void* near_pso = create_slot57(guest, root, vs_near, ps_green, cases[i].words, keep[2 * i]); + void* far_pso = create_slot57(guest, root, vs_far, ps_red, cases[i].words, keep[2 * i + 1]); + if (!near_pso || !far_pso) return 10; + psos.emplace_back(near_pso, far_pso); + } + + ComPtr<ID3D12Device> desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 20; + constexpr UINT width = 8, height = 4; + StreamTarget state{}; + state.count = 1; + state.attachments[0].row_bytes = width * 4; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const float clear_color[] = {0.0f, 0.0f, 1.0f, 1.0f}; + const D3D12_RESOURCE_DESC rtv_tex_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE rtv_clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0.0f, 0.0f, 1.0f, 1.0f}}; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &rtv_tex_desc, D3D12_RESOURCE_STATE_COMMON, &rtv_clear, + IID_PPV_ARGS(&state.attachments[0].texture)))) return 21; + ComPtr<ID3D12Resource> depth_tex; + const D3D12_RESOURCE_DESC dsv_tex_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, DXGI_FORMAT_D32_FLOAT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}; + // No optimized clear value: the cases clear to 0 and to 1. + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &dsv_tex_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&depth_tex)))) return 21; + const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; Word backing, bytes; } rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}, + dsv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}, 0, 0}; + void* dsv_heap = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 14, ptr_arg(&rtv_heap_desc), ptr_arg(&__uuidof(ID3D12DescriptorHeap)), ptr_arg(&state.rtv_heap)))) || + FAILED(static_cast<HRESULT>(invoke(guest, 14, ptr_arg(&dsv_heap_desc), ptr_arg(&__uuidof(ID3D12DescriptorHeap)), ptr_arg(&dsv_heap))))) return 22; + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast<SIZE_T>(invoke(state.rtv_heap, 9))}; + const D3D12_CPU_DESCRIPTOR_HANDLE dsv{static_cast<SIZE_T>(invoke(dsv_heap, 9))}; + const D3D12_RENDER_TARGET_VIEW_DESC rtv_view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + const D3D12_DEPTH_STENCIL_VIEW_DESC dsv_view{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; + invoke(guest, 20, ptr_arg(state.attachments[0].texture.Get()), ptr_arg(&rtv_view), rtv.ptr); + invoke(guest, 21, ptr_arg(depth_tex.Get()), ptr_arg(&dsv_view), dsv.ptr); + D3D12_COMMAND_QUEUE_DESC qd{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast<HRESULT>(invoke(guest, 8, ptr_arg(&qd), ptr_arg(&__uuidof(ID3D12CommandQueue)), ptr_arg(&state.queue)))) || + FAILED(static_cast<HRESULT>(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, ptr_arg(&__uuidof(ID3D12CommandAllocator)), ptr_arg(&state.allocator)))) || + FAILED(static_cast<HRESULT>(invoke(guest, 73, ptr_arg(list_desc), ptr_arg(state.allocator), 0, ptr_arg(&__uuidof(ID3D12GraphicsCommandList)), + ptr_arg(&state.list)))) || + FAILED(static_cast<HRESULT>(invoke(guest, 36, 0, 0, ptr_arg(&__uuidof(ID3D12Fence)), ptr_arg(&state.fence))))) return 23; + const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(width), static_cast<float>(height), 0, 1}; + const D3D12_RECT rect{0, 0, 4, static_cast<LONG>(height)}; + + UINT64 fence_value = 0; + for (std::size_t i = 0; i < std::size(cases); ++i) { + if (const int rc = clear_depth_desktop(desktop.Get(), depth_tex.Get(), cases[i].desktop_depth)) return rc; + if (FAILED(static_cast<HRESULT>(invoke(state.allocator, 8)))) return 24; + if (FAILED(static_cast<HRESULT>(invoke(state.list, 139, ptr_arg(state.allocator))))) return 25; + invoke(state.list, 52, rtv.ptr, ptr_arg(clear_color)); + invoke(state.list, 21, 1, ptr_arg(&viewport)); + invoke(state.list, 22, 1, ptr_arg(&rect)); + invoke(state.list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(state.list, 50, 1, ptr_arg(&rtv), FALSE, ptr_arg(&dsv)); + if (cases[i].guest_clear) { + // Typed call: the depth value is a float argument (xmm3), which invoke cannot pass. + using ClearDepth = void(WINAPI*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, FLOAT, UINT8, UINT, const D3D12_RECT*); + reinterpret_cast<ClearDepth>((*static_cast<void***>(state.list))[51])(state.list, dsv, static_cast<D3D12_CLEAR_FLAGS>(cases[i].guest_clear), + cases[i].guest_depth, 0, 0, nullptr); + } + invoke(state.list, 25, ptr_arg(psos[i].first)); + invoke(state.list, 12, 3, 1); + if (cases[i].far_second) { + invoke(state.list, 25, ptr_arg(psos[i].second)); + invoke(state.list, 12, 3, 1); + } + if (const int rc = execute_guest_list(state.queue, state.list, state.fence, ++fence_value)) return rc; + if (const int rc = read_stream_target(desktop.Get(), state, (outdir + "/" + cases[i].name).c_str())) return rc; + } + return 0; +} diff --git a/tests/startup_draw_state_check.py b/tests/startup_draw_state_check.py new file mode 100644 index 0000000000..1aae58642e --- /dev/null +++ b/tests/startup_draw_state_check.py @@ -0,0 +1,112 @@ +"""Verify depth, culling and blending on translated draws.""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_stream_check import gfx2hlsl +from startup_stream_depth_check import vertex +from startup_stream_draw_check import pixel + +GREEN, RED, BLUE, CYAN = (0, 255, 0, 255), (255, 0, 0, 255), (0, 0, 255, 255), (0, 255, 255, 255) +SWITCHES = ("X2W_DRAW_STATE", "X2W_DRAW_STATE_DEPTH", "X2W_DRAW_STATE_CULL", "X2W_DRAW_STATE_BLEND", "X2W_DRAW_STATE_CULL_FLIP", + "X2W_DRAW_STATE_DEPTH_CLEAR", "X2W_DRAW_STATE_DEPTH_UNCLEARED") +GROUPS = {"X2W_DRAW_STATE_DEPTH": "1", "X2W_DRAW_STATE_CULL": "1", "X2W_DRAW_STATE_BLEND": "1"} +MODES = { + "off": {}, + "on": dict(GROUPS, X2W_DRAW_STATE_DEPTH_CLEAR="1"), + "on-noclear": GROUPS, + "on-uncleared": dict(GROUPS, X2W_DRAW_STATE_DEPTH_CLEAR="1", X2W_DRAW_STATE_DEPTH_UNCLEARED="1"), + "master-off": dict(GROUPS, X2W_DRAW_STATE="0", X2W_DRAW_STATE_DEPTH_CLEAR="1"), +} +BEFORE = {"uncleared": GREEN, "guest_clear_stencil_only": GREEN, "depth": RED, "depth_refused": RED, "no_state": RED, + "cull_back": GREEN, "cull_front": GREEN, "cull_back_face1": GREEN, "mask_rg": GREEN, "guest_clear": GREEN, + "guest_clear0": GREEN} +DECODED = dict(BEFORE, depth=GREEN, cull_front=BLUE, cull_back_face1=BLUE, mask_rg=CYAN, guest_clear0=BLUE) +EXPECTED = { + "off": BEFORE, + "on": DECODED, + # Nothing forwards the guest clears, so no depth target counts as initialised and every depth test stays off. + "on-noclear": dict(DECODED, depth=RED, guest_clear0=GREEN), + "on-uncleared": dict(DECODED, uncleared=BLUE, guest_clear_stencil_only=BLUE), + "master-off": BEFORE, +} +CLEARS = ["flags 0x2 depth 1 ", "flags 0x1 depth 1 ", "flags 0x1 depth 1 ", "flags 0x1 depth 1 ", "flags 0x1 depth 0 "] + + +def left(pixels, name): + assert len(pixels) == 8 * 4 * 4, f"{name}: {len(pixels)} bytes" + drawn = None + for y in range(4): + for x in range(8): + texel = tuple(pixels[(y * 8 + x) * 4:(y * 8 + x) * 4 + 4]) + if x >= 4: + assert texel == BLUE, f"{name}: outside the scissor ({x}, {y}) is {texel}" + elif drawn is None: + drawn = texel + else: + assert texel == drawn, f"{name}: ({x}, {y}) is {texel}, (0, 0) is {drawn}" + return drawn + + +def check(directory, program, backend): + cache = directory / "cache" + cache.mkdir() + vs_near, vs_far, ps_green, ps_red, root = (directory / n for n in ("vs_near", "vs_far", "ps_green", "ps_red", "root")) + vs_near.write_bytes(vertex(0x3e800000)) # z = 0.25 + vs_far.write_bytes(vertex(0x3f400000)) # z = 0.75 + ps_green.write_bytes(pixel(True)) + ps_red.write_bytes(pixel(False)) + base = {k: v for k, v in os.environ.items() if k not in SWITCHES} + base.update(X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", X2W_SHADER_CACHE=str(cache)) + base.setdefault("X2W_D3D12_DEBUG", "1") + args = [str(program), str(vs_near), str(vs_far), str(ps_green), str(ps_red), str(root), backend] + request = subprocess.run(args, env=base, capture_output=True, text=True) + if backend == "hardware" and request.returncode == 77: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + if request.returncode: + raise RuntimeError(f"request run failed: {request.returncode}\n{request.stderr}") + subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=base, check=True) + + for mode, switches in MODES.items(): + out = directory / mode + out.mkdir() + run = subprocess.run(args + [str(out)], env=dict(base, **switches), capture_output=True, text=True) + if run.returncode or "-> drawn;" not in run.stderr: + raise RuntimeError(f"{mode}: draw failed on {backend}: {run.returncode}\n{run.stderr[-3000:]}") + # The cases clear depth to 0 and to 1, so the debug layer's clear-value performance warnings (820 mismatching + # clear value, 821 no clear value at creation) are expected; every other warning or error fails. + errors = [line for line in run.stderr.splitlines() + if re.search(r"x2w-d3d12-debug.*sev=[012]\b", line) and not re.search(r"sev=2 id=82[01] ", line)] + assert not errors, f"{mode}: debug layer: {errors[:4]}" + on = mode.startswith("on") + expected = EXPECTED[mode] + decoded_psos = run.stderr.count(", decoded state") + switch_line = [line for line in run.stderr.splitlines() if "x2w-draw-state switches:" in line] + assert switch_line, f"{mode}: no switch line" + assert ("depth 1 cull 1" in switch_line[0]) == on, f"{mode}: {switch_line[0]}" + clears = [line for line in run.stderr.splitlines() if "x2w-render ClearDepthStencilView" in line] + if mode in ("on", "on-uncleared"): + assert len(clears) == len(CLEARS) and all(c in line for c, line in zip(CLEARS, clears)), clears + else: + assert not clears, f"{mode}: slot 51 forwarded: {clears}" + assert (decoded_psos > 0) == on, f"{mode}: {decoded_psos} pipelines with decoded state" + assert "decoded state refused" not in run.stderr, f"{mode}: a decoded PSO failed creation" + got = {name: left((out / name).read_bytes(), f"{mode} {name}") for name in expected} + print(f"{backend} {mode}: " + ", ".join(f"{n} {c}" for n, c in got.items()) + f"; PSOs with decoded state {decoded_psos}") + wrong = {name: (got[name], colour) for name, colour in expected.items() if got[name] != colour} + assert not wrong, f"{mode}: drew / expected {wrong}" + print(f"startup_draw_state: PASS on {backend} (off and X2W_DRAW_STATE=0 draw as before; on: depth LESS keeps near green, " + f"CULL_FRONT and FACE 1 + CULL_BACK cull the counter-clockwise triangle, CULL_BACK keeps it, target mask 0x3 keeps " + f"blue; refused depth word draws as before; slot 51 depth clear forwarded only with X2W_DRAW_STATE_DEPTH_CLEAR=1, " + f"a clear to 0 makes LESS fail; no depth test against a target no forwarded depth clear initialised, " + f"X2W_DRAW_STATE_DEPTH_UNCLEARED=1 restores it and hides the near triangle)") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:])) diff --git a/tests/startup_draw_uav.cpp b/tests/startup_draw_uav.cpp new file mode 100644 index 0000000000..57b2f85548 --- /dev/null +++ b/tests/startup_draw_uav.cpp @@ -0,0 +1,335 @@ +// Translated draws with UAV stores and resource-heap reads (tests/startup_draw_uav_check.py). Title buffers +// are private allocations: the stand-in opens them as desktop heaps, so the stores must reach these pages. +#include <d3d12.h> + +#include <cstddef> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <cwchar> +#include <fstream> +#include <iterator> +#include <vector> + +using Word = std::uint64_t; +Word invoke(void*, unsigned, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0); +namespace { +template<class T> Word ptr(T* value) { return reinterpret_cast<Word>(value); } +std::uint32_t* uav_memory; +wchar_t uav_mode[32]; + +bool mode_is(const wchar_t* name) { return std::wcscmp(uav_mode, name) == 0; } + +std::uint32_t* private_pages() +{ + return static_cast<std::uint32_t*>(VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); +} + +// A one-entry shader-visible view heap whose descriptor memory is `backing` (0: the stand-in's own). +void* view_heap(void* guest, void* backing, UINT entries = 1) +{ + struct Extended { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word address, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, entries, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, ptr(backing), backing ? 65536u : 0u}; + void* heap = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 14, ptr(&heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&heap))))) return nullptr; + return heap; +} + +void* placed(void* guest, void* memory, const D3D12_RESOURCE_DESC& desc) +{ + void* resource = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 133, ptr(memory), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + ptr(&__uuidof(ID3D12Resource)), ptr(&resource))))) return nullptr; + return resource; +} + +// Modes tex, tex-noflag, tex-uint: entry 0 is a view of an 8x4 texture (UAV-capable RGBA8, a plain RGBA8 texture +// with a shader-resource view, or an RGBA8 typeless texture with an R8G8B8A8_UINT UAV). tex3-rg: a UAV-capable R8G8 texture +// (tex3-rgba: RGBA8) for a `tex2d3` uav. +int bind_texture_entry(void* guest, Word cpu) +{ + if (mode_is(L"tex-d16")) { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 64, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + void* buffer = placed(guest, private_pages(), desc); + if (!buffer) return 46; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{DXGI_FORMAT_R16G16B16A16_UINT, D3D12_UAV_DIMENSION_BUFFER}; + uav.Buffer.NumElements = 8; + invoke(guest, 19, ptr(buffer), 0, ptr(&uav), cpu); + return 0; + } + const bool uav_flag = !mode_is(L"tex-noflag"); + const auto format = mode_is(L"tex-wide") ? DXGI_FORMAT_R32G32_UINT : + (mode_is(L"tex-atomic") || mode_is(L"tex-or")) ? DXGI_FORMAT_R32_UINT : + mode_is(L"tex-atomic-float") ? DXGI_FORMAT_R32_FLOAT : + mode_is(L"tex3-rg") ? DXGI_FORMAT_R8G8_UNORM : DXGI_FORMAT_R8G8B8A8_UNORM; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 8, 4, 1, 1, + mode_is(L"tex-uint") ? DXGI_FORMAT_R8G8B8A8_TYPELESS : format, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + uav_flag ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE}; + void* texture = placed(guest, private_pages(), desc); + if (!texture) return 46; + if (uav_flag) { + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{mode_is(L"tex-uint") ? DXGI_FORMAT_R8G8B8A8_UINT : format, + D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(guest, 19, ptr(texture), 0, ptr(&uav), cpu); + } else { + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Texture2D.MipLevels = 1; + invoke(guest, 18, ptr(texture), ptr(&srv), cpu); + } + return 0; +} + +// Mode heap: the view heap's memory is a private allocation (read in place as heapmem); entry 0 is a raw +// buffer view of a placed buffer whose first dword is 77. +int bind_heap_entry(void* guest, Word cpu) +{ + std::uint32_t* memory = private_pages(); + if (!memory) return 45; + memory[0] = 77; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 256; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + void* buffer = placed(guest, memory, desc); + if (!buffer) return 47; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer.NumElements = 64; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + invoke(guest, 18, ptr(buffer), ptr(&srv), cpu); + return 0; +} + +// LOCAL (textures) mode heaptex: entry 0 is a shader-resource view of a plain 8x4 RGBA8 texture that no table +// binds (only the heap references it); its title memory holds texel (x, y) = (10 + 20x, 30 + 40y, 7, 255) in the +// desktop footprint (row pitch 256). +// With X2W_TEST_HEAPTEX_SURFACE=<path> (tests/gfx10_layout_check.cpp --write-tiled bc1_256_9mips_4k_s): entry 0 is +// instead a memory SRV (device slot 70) of that console-swizzled surface: BC1 256x256, 9 mips, layout 0x105, flags +// 0x300000, not announced (X2W_MEMORY_SRV_DETILE). +int bind_heap_memory_entry(void* guest, Word cpu, const wchar_t* path) +{ + std::ifstream input(path, std::ios::binary); + const std::vector<char> bytes{std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>{}}; + if (bytes.empty()) return 43; + void* memory = VirtualAlloc(nullptr, bytes.size() + (1u << 20), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!memory) return 45; + std::memcpy(memory, bytes.data(), bytes.size()); + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 256, 256, 1, 9, DXGI_FORMAT_BC1_UNORM, {1, 0}, + static_cast<D3D12_TEXTURE_LAYOUT>(0x105), static_cast<D3D12_RESOURCE_FLAGS>(0x300000)}; + struct ViewAt { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + Word address; + Word tail[2]; + } v{}; + static_assert(offsetof(ViewAt, address) == 0x28 && sizeof(ViewAt) == 0x40); + v.view.Format = desc.Format; + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.view.Texture2D.MipLevels = 9; + v.address = ptr(memory); + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + return 0; +} + +int bind_heap_texture_entry(void* guest, Word cpu) +{ + wchar_t surface[MAX_PATH]{}; + const DWORD length = GetEnvironmentVariableW(L"X2W_TEST_HEAPTEX_SURFACE", surface, MAX_PATH); + if (length && length < MAX_PATH) return bind_heap_memory_entry(guest, cpu, surface); + auto* memory = reinterpret_cast<unsigned char*>(private_pages()); + if (!memory) return 45; + for (unsigned y = 0; y < 4; ++y) + for (unsigned x = 0; x < 8; ++x) { + unsigned char* t = memory + y * 256 + x * 4; + t[0] = static_cast<unsigned char>(10 + 20 * x); + t[1] = static_cast<unsigned char>(30 + 40 * y); + t[2] = 7; + t[3] = 255; + } + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 8, 4, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + void* texture = placed(guest, memory, desc); + if (!texture) return 46; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Texture2D.MipLevels = 1; + invoke(guest, 18, ptr(texture), ptr(&srv), cpu); + return 0; +} + +int bind_memory_buffer_entries(void* guest, Word cpu, UINT increment) +{ + if (increment < 32 || 128 % increment) return 48; + auto* heap_bytes = reinterpret_cast<unsigned char*>(cpu); + for (std::uint32_t m = 0; m < 5; ++m) { + const std::uint32_t link = m + 1; + std::memset(heap_bytes + m * increment, 0, increment); + std::memcpy(heap_bytes + m * increment, &link, 4); + } + std::uint32_t* decoy = private_pages(); + std::uint32_t* memory = private_pages(); + if (!decoy || !memory) return 45; + decoy[0] = 55; + memory[0] = 99; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 256; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + void* buffer = placed(guest, decoy, desc); + if (!buffer) return 47; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer.NumElements = 64; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + invoke(guest, 18, ptr(buffer), ptr(&srv), cpu + increment); + if (!mode_is(L"membuf-link")) { + struct ViewAt { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + Word address; + Word tail[2]; + } v{}; + static_assert(offsetof(ViewAt, address) == 0x28 && sizeof(ViewAt) == 0x40); + v.view = srv; + // membuf-refused / membuf-rewrite: null address, refused null_address + v.address = mode_is(L"membuf-refused") || mode_is(L"membuf-rewrite") ? 0 : ptr(memory); + if (mode_is(L"membuf-structured")) { + v.view.Format = DXGI_FORMAT_UNKNOWN; + v.view.Buffer.NumElements = 4; + v.view.Buffer.StructureByteStride = 16; + v.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; + } else if (mode_is(L"membuf-typed")) { + v.view.Format = DXGI_FORMAT_R32_UINT; + v.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; + } else if (std::wcsncmp(uav_mode, L"membuf-unaligned", 16) == 0) { + memory[0] = 0; + memory[5] = 99; + if (!placed(guest, memory, desc)) return 47; + v.address = ptr(memory) + 20; + v.view.Format = DXGI_FORMAT_UNKNOWN; + v.view.Buffer.NumElements = 4; + v.view.Buffer.StructureByteStride = 12; + v.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; + } + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + if (mode_is(L"membuf-rewrite")) { + // The title patches the descriptor it created in place: the V# base (word 0, word 1 bits 0-15) of the + // memory, the rest as it was (with X2W_BUFFER_HEAP_INDEX, the refused-view marker's description). + const std::uint64_t base = ptr(memory); + std::uint32_t w[2]; + std::memcpy(w, heap_bytes, sizeof w); + w[0] = static_cast<std::uint32_t>(base); + w[1] = (w[1] & 0xffff0000u) | static_cast<std::uint32_t>((base >> 32) & 0xffff); + std::memcpy(heap_bytes, w, sizeof w); + } + } + std::memcpy(heap_bytes + 128, heap_bytes, 32); + std::uint32_t copied[4]; + std::memcpy(copied, heap_bytes + 128, sizeof copied); + std::printf("membuf entry words: %08x %08x %08x %08x\n", copied[0], copied[1], copied[2], copied[3]); + std::fflush(stdout); + return 0; +} + +// A 64 KiB placed buffer over `memory` (title memory of a resource for CopyBufferRegion). +void* memory_buffer(void* guest, void* memory) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 65536; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return placed(guest, memory, desc); +} +void hardware_descriptor(Word cpu, Word base, std::uint32_t stride = 0) +{ + // gfx10 buffer descriptor: base [47:0], stride [61:48] (0 unless given), 256 records, word 3 a marker the shader + // checks. With a stride the record count is in records: 16 records of `stride` bytes. + const std::uint32_t words[8] = {static_cast<std::uint32_t>(base), (static_cast<std::uint32_t>(base >> 32) & 0xffff) | stride << 16, + stride ? 16u : 256u, 0x12345678u}; + std::memcpy(reinterpret_cast<void*>(cpu), words, sizeof(words)); +} +void* copy_dest; +void* copy_source; +Word copy_dest_offset, copy_source_offset; +std::uint32_t* copy_memory; // allocation of the copy destination +} + +// X2W_TEST_DRAW_UAV=<mode>. aligned|misaligned|uavbase: entry 0 is a hardware buffer descriptor at title + 64 +// or + 68 of a private allocation. Two draws, one column each. +int draw_uav_stores(ID3D12Device* desktop, void* guest, void* list) +{ + D3D12_FEATURE_DATA_EXISTING_HEAPS heaps{}; + if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &heaps, sizeof(heaps))) || !heaps.Supported) return 77; + GetEnvironmentVariableW(L"X2W_TEST_DRAW_UAV", uav_mode, 32); + const bool heap_texture_mode = mode_is(L"heaptex"); // LOCAL (textures) + const bool membuf_mode = std::wcsncmp(uav_mode, L"membuf", 6) == 0; // LOCAL (textures) + const bool heap_mode = mode_is(L"heap") || heap_texture_mode || membuf_mode; + // Heap draws need the console's 32-byte view slots (the title's own shader arithmetic). + std::printf("view increment %u\n", desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + std::fflush(stdout); + const bool copy_mode = std::wcsncmp(uav_mode, L"copy", 4) == 0; + void* heap = view_heap(guest, heap_mode ? private_pages() : nullptr, membuf_mode ? 5 : copy_mode ? 2 : 1); + if (!heap) return 42; + const Word cpu = invoke(heap, 9); + if (!cpu) return 42; + if (membuf_mode) { + if (const int rc = bind_memory_buffer_entries(guest, cpu, desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV))) + return rc; + } else if (heap_texture_mode) { + if (const int rc = bind_heap_texture_entry(guest, cpu)) return rc; + } else if (std::wcsncmp(uav_mode, L"tex", 3) == 0) { + if (const int rc = bind_texture_entry(guest, cpu)) return rc; + } else if (heap_mode) { + if (const int rc = bind_heap_entry(guest, cpu)) return rc; + } else if (copy_mode) { + // copy-*: entry 0 (uav 0) = title + 64 of allocation A, entry 1 (srv 0) = title + 0x400 of A (copy-same) or + // of a second allocation B. Between the two draws the list copies A + 64 (128 bytes) to the srv range. + uav_memory = private_pages(); + std::uint32_t* other = mode_is(L"copy-two") ? private_pages() : uav_memory; + if (!uav_memory || !other) return 45; + copy_memory = other; + copy_source = memory_buffer(guest, uav_memory); + copy_dest = other == uav_memory ? copy_source : memory_buffer(guest, other); + if (!copy_source || !copy_dest) return 47; + copy_source_offset = 64; + copy_dest_offset = 0x400; + hardware_descriptor(cpu, ptr(uav_memory) + 64); + hardware_descriptor(cpu + 32, ptr(other) + 0x400); + } else { + uav_memory = private_pages(); + if (!uav_memory) return 45; + // LOCAL pstrans: stride16 / stride0 (udsrc uavstride): title + 64 with a record stride of 16 or 0 bytes. + const bool stride_mode = std::wcsncmp(uav_mode, L"stride", 6) == 0; + hardware_descriptor(cpu, ptr(uav_memory) + (mode_is(L"aligned") || stride_mode ? 64 : 68), mode_is(L"stride16") ? 16u : 0u); + } + invoke(list, 32, 1, ptr(&heap)); + invoke(list, 36, 0, invoke(heap, 10)); + // copy-twice: three strips; a second copy after draw 2 takes A + 68 (what draw 2 stored), and draw 3 reads it. + const LONG strips = mode_is(L"copy-twice") ? 3 : 2; + for (LONG x = 0; x < strips; ++x) { + const D3D12_RECT strip{x, 0, x + 1, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + // CopyBufferRegion(dest, dest offset, source, source offset, bytes); copy-none: no copy (negative control) + if (x < strips - 1 && copy_dest && !mode_is(L"copy-none")) + invoke(list, 15, ptr(copy_dest), copy_dest_offset, ptr(copy_source), copy_source_offset + 4 * x, 128); + } + return 0; +} + +// After the list completed: the title memory as the CPU sees it. +void report_uav_stores() +{ + if (!uav_memory) return; + std::printf("uav memory:"); + for (int i = 0; i < 64; ++i) std::printf(" %u", uav_memory[i]); + if (copy_dest) { // copy-*: the copied range as the CPU sees it (title + 0x400 of the destination allocation) + const auto* copied = copy_memory + 0x100; + std::printf("\ncopied:"); + for (int i = 0; i < 32; ++i) std::printf(" %u", copied[i]); + } + std::printf("\n"); + std::fflush(stdout); +} diff --git a/tests/startup_draw_uav_check.py b/tests/startup_draw_uav_check.py new file mode 100644 index 0000000000..9ce6d0b1f6 --- /dev/null +++ b/tests/startup_draw_uav_check.py @@ -0,0 +1,393 @@ +"""Translated draws with UAV stores and resource-heap reads (src/startup_stubs/d3d12_draw.inl, LOCAL draw-rt). + +A synthetic pipeline (tools/startup/gfx2hlsl.py vertex stage, hand-written ps_5_1 pixel stage) gets extra +manifest lines; the fixture (tests/startup_draw_uav.cpp) binds a one-entry view table and draws two +one-column strips (columns 0 and 1). + +- aligned / misaligned / uavbase: `uav 0 buf table 0 0` and `srv 0 buf table 0 0` name the same hardware + buffer descriptor (title + 64 or + 68 of a private allocation, word 3 = MARK), plus `udsrc uavword3`, + `udsrc bufword3` and (uavbase) `udsrc uavbase`. The fixture prints the title memory after the GPU ran. +- tex / tex-noflag / tex-uint: `uav 0 tex2d table 0 0` on a UAV-capable RGBA8 texture (drawn), a texture + without unordered access (skipped) and an R8G8B8A8_UINT view (skipped). +- heap: `heap 1`; the pixel stage reads the view id from heapmem and the raw buffer of that view (dword 77). +- copy-same / copy-two / copy-twice / copy-none / copy-cpu: CopyBufferRegion (list slot 15) between the two draws. uav 0 = title + 64 + of allocation A (entry 0), srv 0 = title + 0x400 of A (copy-same) or of allocation B (copy-two) (entry 1). Draw 1 + stores into A, the list copies A + 64 (128 bytes) to the srv range, draw 2 reads the copied values as its srv + (the constant-buffer path of translated draws: raw srvs). X2W_D3D12_COPY_BUFFER=gpu must order the copy after + draw 1 on the GPU and let draw 2 read it in place. Controls: copy-none (no copy) and copy-cpu (same list, + X2W_D3D12_COPY_BUFFER=1: the record-time copy runs before draw 1 has stored anything) must both read zeros. +""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_stream_draw_check import gfx2hlsl, pixel, vertex + +MARK = 0x12345678 +CLEAR = bytes((0, 0, 255, 255)) + + +def buffer_hlsl(count, base): + uds = " ".join(f"uint ud{i};" for i in range(count + (3 if base else 2))) + offset = f"ud{count + 2} + " if base else "" + return ( + f"cbuffer entry : register(b0) {{ {uds} }};\n" + "ByteAddressBuffer t0 : register(t0);\n" + "RWByteAddressBuffer u0 : register(u0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint2 q = uint2(p.xy);\n" + " uint i = q.y * 8 + q.x;\n" + " uint seen = t0.Load(q.y * 32);\n" # what an earlier draw stored for column 0 of this row + f" uint marks = (ud{count} == {MARK}u ? 0u : 500000u) + (ud{count + 1} == {MARK}u ? 0u : 900000u);\n" + f" u0.Store({offset}i * 4, seen + 1000 + i + marks);\n" + " return float4(seen ? 1 : 0, 1, 0, 1);\n" + "}\n" + ) + + +def stride_hlsl(count): + """LOCAL pstrans (udsrc uavstride): two records written with idxen addressing, index 0 and 1, at index * stride.""" + uds = " ".join(f"uint ud{i};" for i in range(count + 1)) + return ( + f"cbuffer entry : register(b0) {{ {uds} }};\n" + "RWByteAddressBuffer u0 : register(u0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + f" u0.Store(0u * ud{count}, 111u);\n" + f" u0.Store(1u * ud{count}, 222u);\n" + " return float4(0, 1, 0, 1);\n" + "}\n" + ) + + +TEX3_HLSL = ( + "RWTexture2D<float3> u0 : register(u0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " u0[uint2(p.xy)] = float3(0.25, 0.5, 0.75);\n" + " return float4(0, 1, 0, 1);\n" + "}\n" +) + +TEX_HLSL = ( + "RWTexture2D<float4> u0 : register(u0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " u0[uint2(p.xy)] = float4(0.25, 0.5, 0.75, 1);\n" + " return float4(0, 1, 0, 1);\n" + "}\n" +) + +def atomic_hlsl(): + return """ +RWTexture2D<uint> u0 : register(u0); +float4 main(float4 p : SV_Position) : SV_Target { + uint2 xy = uint2(p.xy); + uint prior; + InterlockedExchange(u0[xy], 0xffffffffu, prior); + uint v8 = xy.x, v9 = xy.y, v6 = 11u, exec = 1u; + if (exec) InterlockedMin(u0[uint2(v8, v9)], v6); + v6 = 0x80000000u; + if (exec) InterlockedMin(u0[uint2(v8, v9)], v6); + v6 = 0u; + exec = 0u; + if (exec) InterlockedMin(u0[uint2(v8, v9)], v6); + InterlockedOr(u0[xy], 0u, prior); + return float4(0, prior == 11u, 0, 1); +} +""" + + +HEAP_HLSL = ( + "ByteAddressBuffer heapmem : register(t0, space1);\n" + "ByteAddressBuffer vinfo : register(t1, space1);\n" + "ByteAddressBuffer heapbuf[720008] : register(t0, space6);\n" + "uint vid(uint h) { return heapmem.Load(h) == 0x56573258u ? heapmem.Load(h + 4) : 0xffffffffu; }\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint i = vid(0);\n" + " uint k = i < 90000u ? 8u + 8u * i + 4u : 4u;\n" + " uint v = heapbuf[NonUniformResourceIndex(k)].Load(0);\n" + " return float4(v / 255.0, i < 90000u ? 1 : 0, 0, 1);\n" + "}\n" +) + + +# LOCAL (textures): heap texture modes (fixture mode heaptex) and their extra environment. The pixel stage reads the +# view id from heapmem and texel (x, y) of that view's Texture2D (heap kind 0). The detile modes publish entry 0 through +# slot 70 (X2W_TEST_HEAPTEX_SURFACE, set by the caller) and check every block of mip 0 (HEAP_DETILE_HLSL). +HEAP_TEXTURE_MODES = {"heaptex": {"X2W_HEAP_TEXTURE_UPLOAD": "1"}, "heaptex-off": {}, + "heaptex-detile": {"X2W_HEAP_TEXTURE_UPLOAD": "1", "X2W_MEMORY_SRV_DETILE": "1"}, + "heaptex-detile-noupload": {"X2W_MEMORY_SRV_DETILE": "1"}} +HEAP_TEXTURE_HLSL = ( + "ByteAddressBuffer heapmem : register(t0, space1);\n" + "ByteAddressBuffer vinfo : register(t1, space1);\n" + "Texture2D<float4> heaptex2d[720008] : register(t0, space2);\n" + "uint vid(uint h) { return heapmem.Load(h) == 0x56573258u ? heapmem.Load(h + 4) : 0xffffffffu; }\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint i = vid(0);\n" + " uint k = i < 90000u ? 8u + 8u * i : 0u;\n" + " return heaptex2d[NonUniformResourceIndex(k)].Load(int3(uint2(p.xy), 0));\n" + "}\n" +) +# BC1 solid blocks, id = x | y << 6 at mip 0 (tests/gfx10_layout_check.cpp pattern); 8 pixels x 512 blocks each. +HEAP_DETILE_HLSL = ( + "ByteAddressBuffer heapmem : register(t0, space1);\n" + "ByteAddressBuffer vinfo : register(t1, space1);\n" + "Texture2D<float4> heaptex2d[720008] : register(t0, space2);\n" + "uint vid(uint h) { return heapmem.Load(h) == 0x56573258u ? heapmem.Load(h + 4) : 0xffffffffu; }\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint i = vid(0);\n" + " uint k = i < 90000u ? 8u + 8u * i : 0u;\n" + " uint2 q = uint2(p.xy);\n" + " uint bad = 0, n = 0;\n" + " [loop] for (uint b = q.y * 2u + q.x; b < 4096u; b += 8u) {\n" + " uint x = b % 64u, y = b / 64u;\n" + " float4 c = heaptex2d[NonUniformResourceIndex(k)].Load(int3(4 * x, 4 * y, 0));\n" + " uint id = (uint(round(c.r * 31)) << 11) | (uint(round(c.g * 63)) << 5) | uint(round(c.b * 31));\n" + " if (id != (x | (y << 6))) bad++;\n" + " n++;\n" + " }\n" + " return float4(bad ? 0 : 1, n == 512u ? 1 : 0, 0, 1);\n" + "}\n" +) + +# LOCAL (textures): modes membuf* (tests/startup_buffer_heap_index_check.py): the bytes of dword 0 of srv 0 as the colour. +MEMBUF_HLSL = ( + "ByteAddressBuffer t0 : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint v = t0.Load(0);\n" + " return float4(v & 255u, (v >> 8) & 255u, (v >> 16) & 255u, v >> 24) / 255.0;\n" + "}\n" +) + +COPY_ENV = {"copy-same": "gpu", "copy-two": "gpu", "copy-twice": "gpu", "copy-none": "gpu", "copy-cpu": "1"} + + +def run_mode(directory, consumer, backend, mode, extra_env=None): + cache = directory / mode / "cache" + cache.mkdir(parents=True) + vs, ps, root, output = (directory / mode / name for name in ("vs", "ps", "root", "pixels")) + vs.write_bytes(vertex()) + ps.write_bytes(pixel(False)) + 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_SHADER_CACHE=str(cache), + X2W_TEST_DRAW_UAV="copy-same" if mode == "copy-cpu" else "heaptex" if mode in HEAP_TEXTURE_MODES else mode, + X2W_TRAP_LOG=str(directory / mode / "trap.log")) + if mode in COPY_ENV: + env["X2W_D3D12_COPY_BUFFER"] = COPY_ENV[mode] + env.update(HEAP_TEXTURE_MODES.get(mode, {})) + env.update(extra_env or {}) + args = [consumer, vs, ps, root] + subprocess.run(args, env=env, check=True) + subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True) + manifest, = cache.glob("*.txt") + text = manifest.read_text(encoding="ascii") + count = len(re.findall(r"^udsrc ", text, re.M)) + if re.search(r"^(srv|uav|heap) ", text, re.M): + raise AssertionError(f"the synthetic manifest already binds resources:\n{text}") + if mode.startswith("tex3"): # `tex2d3`: a 3-channel store, bound only to a view of at most 3 channels + lines, hlsl = ["uav 0 tex2d3 table 0 0"], TEX3_HLSL + elif mode == "tex-wide": + lines = ["uav 0 tex2dmax64 table 0 0"] + hlsl = """RWTexture2D<uint64_t> image : register(u0); +float4 main(float4 p : SV_Position) : SV_Target { + uint2 xy = uint2(p.xy); + uint64_t prior, a = uint64_t(0x80000000u) << 32, b = uint64_t(1u) << 32; + InterlockedExchange(image[xy], b, prior); + InterlockedMax(image[xy], a | 7u); + InterlockedMax(image[xy], b | 0xffffffffu, prior); + return float4(0, prior == (a | 7u), 0, 1); +}""" + elif mode == "tex-or": + lines = ["uav 0 tex2dor table 0 0"] + hlsl = """RWTexture2D<uint> image : register(u0); +float4 main(float4 p : SV_Position) : SV_Target { + uint2 xy = uint2(p.xy); uint v; + InterlockedExchange(image[xy], 4u, v); + InterlockedOr(image[xy], 2u); + InterlockedOr(image[xy], 0u, v); + return float4(0, v == 6u, 0, 1); +}""" + elif mode == "tex-d16": + lines = ["uav 0 buf16x4 table 0 0"] + hlsl = """RWBuffer<uint4> data : register(u0); +float4 main(float4 p : SV_Position) : SV_Target { + uint i = uint(p.x); + uint4 expected = uint4(0xffffu, 0x8000u, 2u, 0u); + data[i] = expected; + return float4(0, all(data[i] == expected), 0, 1); +}""" + elif mode.startswith("tex-atomic"): + lines, hlsl = ["uav 0 tex2dumin table 0 0"], atomic_hlsl() + elif mode.startswith("tex"): + lines, hlsl = ["uav 0 tex2d table 0 0"], TEX_HLSL + elif mode == "heap": + lines, hlsl = ["heap 1"], HEAP_HLSL + elif mode.startswith("stride"): + lines, hlsl = ["uav 0 buf table 0 0", f"udsrc {count} uavstride 0"], stride_hlsl(count) + elif mode in HEAP_TEXTURE_MODES: # LOCAL (textures): tests/startup_heap_texture_check.py + lines, hlsl = ["heap 1"], HEAP_DETILE_HLSL if "detile" in mode else HEAP_TEXTURE_HLSL + elif mode.startswith("membuf"): + lines, hlsl = ["srv 0 buf table 0 128"], MEMBUF_HLSL + else: + base = mode == "uavbase" + lines = ["uav 0 buf table 0 0", "srv 0 buf table 0 32" if mode in COPY_ENV else "srv 0 buf table 0 0", f"udsrc {count} uavword3 0", f"udsrc {count + 1} bufword3 0"] + if base: + lines.append(f"udsrc {count + 2} uavbase 0") + hlsl = buffer_hlsl(count, base) + manifest.write_text(text.rstrip("\n") + "\n" + "\n".join(lines) + "\n", encoding="ascii") + source = manifest.with_suffix(".ps.hlsl") + source.write_text(hlsl) + compiler = Path(env["X2W_FXC"]).with_name("dxc.exe") if mode == "tex-wide" else env["X2W_FXC"] + if mode == "tex-wide": + subprocess.run([compiler, "/nologo", "/T", "vs_6_0", "/E", "main", "/Fo", manifest.with_suffix(".vs.cso"), + manifest.with_suffix(".vs.hlsl")], check=True, stdout=subprocess.DEVNULL) + profile = "ps_6_6" if mode == "tex-wide" else "ps_5_1" + subprocess.run([compiler, "/nologo", "/T", profile, "/E", "main", "/Fo", manifest.with_suffix(".ps.cso"), source], + check=True, stdout=subprocess.DEVNULL) + result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True, timeout=60) + print(result.stdout, end="") + if result.returncode == 77: + return None + if result.returncode: + raise RuntimeError(f"{mode}: consumer failed ({result.returncode})\n{result.stderr[-5000:]}") + found = re.search(r"^uav memory:((?: \d+)+)$", result.stdout, re.M) + memory = [int(v) for v in found.group(1).split()] if found else None + copied = re.search(r"^copied:((?: \d+)+)$", result.stdout, re.M) + if copied: + memory = (memory, [int(v) for v in copied.group(1).split()]) + return memory, output.read_bytes(), result.stderr + "\n" + result.stdout + + +def need(log, mode, *needles): + for needle in needles: + if needle not in log: + raise AssertionError(f"{mode}: log lacks {needle!r}\n{log[-4000:]}") + + +def check(directory, consumer, backend): + results = {} + for mode in ("aligned", "misaligned", "uavbase", "tex", "tex-noflag", "tex-uint", "tex3-rg", "tex3-rgba", "tex-atomic", "tex-atomic-float", "tex-wide", "tex-or", "tex-d16", "heap", "copy-same", "copy-two", "copy-twice", "copy-none", "copy-cpu", + "stride16", "stride0"): + got = run_mode(directory, consumer, backend, mode) + if got is None: + print("no existing-heap support or no adapter: skip") + return 77 + results[mode] = got + # aligned: the view starts at title + 64 (dword 16). Draw 1 stores 1000 + i for column 0; draw 2 reads that + # value in place (srv over the range draw 1 wrote) and adds it. Word 3 reached both entry values (marks 0). + memory, image, log = results["aligned"] + expected = [0] * 64 + for y in range(4): + expected[16 + y * 8] = 1000 + y * 8 + expected[16 + y * 8 + 1] = (1000 + y * 8) + 1000 + y * 8 + 1 + if memory != expected: + raise AssertionError(f"aligned: memory {memory}\nexpected {expected}") + if image[:8] != bytes((0, 255, 0, 255, 255, 255, 0, 255)): + raise AssertionError(f"aligned: pixels {image[:16].hex()} (column 0 must read 0, column 1 the earlier store)") + need(log, "aligned", "x2w-draw-rt first draw with uavs", "from descriptor", "bound in place at window", ": bound") + # misaligned without uavbase: a null view, nothing stored (negative control for the stores above). + memory, image, log = results["misaligned"] + if any(memory): + raise AssertionError(f"misaligned: memory changed {memory}") + need(log, "misaligned", "NULL (not 16-byte aligned, no uavbase)") + # uavbase: the view starts at title + 64 and ud carries 4, so the stores land at title + 68 (dword 17). + # The srv over the written range is misaligned: it keeps the record-time copy (zeros), counted as stale. + memory, image, log = results["uavbase"] + expected = [0] * 64 + for y in range(4): + expected[17 + y * 8] = 1000 + y * 8 + expected[17 + y * 8 + 1] = 1000 + y * 8 + 1 + if memory != expected: + raise AssertionError(f"uavbase: memory {memory}\nexpected {expected}") + # tex: drawn (green columns 0 and 1) through a bound RGBA8 texture UAV; the others are skipped (clear). + green = bytes((0, 255, 0, 255)) + memory, image, log = results["tex"] + if image[:8] != green * 2 or image[8:12] != CLEAR: + raise AssertionError(f"tex: pixels {image[:16].hex()}") + need(log, "tex", "uav 0 texture: ", "format 28 mip 0: bound", "typed UAV store supported", "first draw with uavs") + for mode in ("tex-wide", "tex-or", "tex-d16"): + if results[mode][1][:8] != green * 2: + raise AssertionError(f"{mode}: operation failed: {results[mode][1][:16].hex()}") + _, image, log = results["tex-atomic"] + if image[:8] != green * 2 or image[8:12] != CLEAR: + raise AssertionError(f"tex-atomic: pixels {image[:16].hex()}") + need(log, "tex-atomic", "format 42 mip 0: bound") + memory, image, log = results["tex3-rg"] + if image[:8] != green * 2 or image[8:12] != CLEAR: + raise AssertionError(f"tex3-rg: pixels {image[:16].hex()}") + need(log, "tex3-rg", "uav 0 texture: ", "format 49 mip 0: bound", "first draw with uavs") + for mode, reason in (("tex-atomic-float", "incompatible integer atomic UAV format"), + ("tex-noflag", "texture without ALLOW_UNORDERED_ACCESS"), + ("tex-uint", "format not a float/unorm format of the texture"), + ("tex3-rgba", "4-channel format for a 3-channel (tex2d3) store")): + memory, image, log = results[mode] + if image[:8] != CLEAR * 2: + raise AssertionError(f"{mode}: the draw was not skipped: {image[:16].hex()}") + need(log, mode, f"draw skipped: texture uav: {reason}") + if "first draw with uavs" in log: + raise AssertionError(f"{mode}: a skipped draw was recorded") + # heap: heapmem gave view id i of entry 0 (green 1) and heapbuf[8 + 8 i + 4] its first dword (77). + # With a view increment other than the console's 32 bytes the draw must be skipped instead (WARP). + memory, image, log = results["heap"] + need(log, "heap", "heap 1 in root parameters") + increment = int(re.search(r"^view increment (\d+)$", log, re.M).group(1)) + if increment == 32: + if image[:8] != bytes((77, 255, 0, 255)) * 2: + raise AssertionError(f"heap: pixels {image[:16].hex()}") + need(log, "heap", "x2w-draw-rt first heap draw") + heap = "heap draw reads view id and buffer" + else: + if image[:8] != CLEAR * 2: + raise AssertionError(f"heap: increment {increment} but drawn: {image[:16].hex()}") + need(log, "heap", "heap draw skipped: descriptor increment is not 32") + heap = f"heap draw NOT exercised (view increment {increment}; skipped as required)" + # copy-*: GPU order against two controls. Simulated: draw x stores A[16 + 8y + x] = B[8y] + 1000 + 8y + x; + # after draw x (not the last) the list copies 128 bytes from A + 64 + 4x to B. copy-twice: the second copy reads + # what draw 2 stored, through a window draw 2 read in place (read state -> UAV for the copy). + def simulate(strips, copies): + a, b = [0] * 64, [0] * 32 + for x in range(strips): + for y in range(4): + a[16 + y * 8 + x] = b[y * 8] + 1000 + y * 8 + x + if copies and x < strips - 1: + b = a[16 + x:16 + x + 32] + return a, b + for mode in ("copy-same", "copy-two", "copy-twice", "copy-none", "copy-cpu"): + (memory, copied), image, log = results[mode] + gpu = mode in ("copy-same", "copy-two", "copy-twice") + strips = 3 if mode == "copy-twice" else 2 + expected, expected_copy = simulate(strips, gpu) + if memory != expected: + raise AssertionError(f"{mode}: memory {memory}\nexpected {expected}") + if copied != expected_copy: + raise AssertionError(f"{mode}: copied range {copied}\nexpected {expected_copy}") + row = b"".join(bytes((255 if x and gpu else 0, 255, 0, 255)) for x in range(strips)) + if image[:4 * strips] != row: + raise AssertionError(f"{mode}: pixels {image[:16].hex()}") + if gpu: + need(log, mode, "runs on the GPU in list order", "x2w-copy-gpu CopyBufferRegion", ": on the GPU, window") + if "record-time fallback" in log: + raise AssertionError(f"{mode}: copy fell back\n{log[-3000:]}") + elif mode == "copy-cpu": + need(log, mode, "copies title memory at record time") + # stride16 / stride0 (LOCAL pstrans, udsrc uavstride): the entry value is the descriptor's record stride. With + # 16 the two records land at dwords 16 and 20; the negative control (stride 0) has the second overwrite the first. + for mode, want in (("stride16", {16: 111, 20: 222}), ("stride0", {16: 222})): + memory, image, log = results[mode] + expected = [want.get(i, 0) for i in range(64)] + if memory != expected: + raise AssertionError(f"{mode}: memory {memory}\nexpected {expected}") + need(log, mode, "from descriptor", "first draw with uavs") + print(f"{backend}: udsrc uavstride passes the descriptor's record stride (16: two idxen records both land; " + f"stride 0 control: the second overwrites the first)") + print(f"{backend}: CopyBufferRegion on the GPU in list order (same window, two windows, copy-draw-copy-draw): each draw reads the " + f"bytes the draw before it stored; controls without the copy and with the record-time copy read zeros") + print(f"{backend}: draw UAV buffer stores reach title memory (aligned, in-place re-read, uavbase; misaligned " + f"control stores nothing); texture UAV bound, two refusals skip the draw; {heap}") + 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 6e456b9b83..5d8e0ec985 100644 --- a/tests/startup_dstorage_destination_check.cpp +++ b/tests/startup_dstorage_destination_check.cpp @@ -101,16 +101,22 @@ void refused(const char* name, DWORD protect, bool decommit_last) 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 std::printf("ok: %s refused, bytes before the bad page intact\n", name); + if (protect & PAGE_GUARD) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(region + page, &info, sizeof(info)) || !(info.Protect & PAGE_GUARD)) + fail(name, "validation consumed the guard"); + } VirtualFree(region, 0, MEM_RELEASE); } } // namespace int main(int argc, char** argv) { - if (argc != 2) { - std::printf("usage: startup_dstorage_destination_check <XCRDAPI.dll>\n"); + if (argc < 2 || argc > 3) { + std::printf("usage: startup_dstorage_destination_check <XCRDAPI.dll> [xmem.dll]\n"); return 2; } + if (argc == 3 && !LoadLibraryA(argv[2])) return 1; HMODULE library = LoadLibraryA(argv[1]); auto* get_factory = library ? reinterpret_cast<GetFactoryFn>(GetProcAddress(library, "DStorageGetFactory")) : nullptr; void* factory_pointer = nullptr; @@ -133,6 +139,15 @@ int main(int argc, char** argv) // The capacity runs one page past what is committed; the data itself (one page) would fit. refused("capacity past the committed pages", 0, true); + // A one-page capacity can span two OS pages when the destination is unaligned. + unsigned char* crossing = fresh_region(); + DWORD old = 0; + if (!crossing || !VirtualProtect(crossing + page, page, PAGE_READONLY, &old)) return 1; + const long crossing_hr = run_request(crossing + 1, page, page - 1); + if (crossing_hr == -1 || crossing_hr >= 0 || !untouched(crossing, 0, bytes)) + fail("unaligned capacity", "did not refuse the last read-only byte before writing"); + VirtualFree(crossing, 0, MEM_RELEASE); + // Control and recovery on the same queue: a fully writable destination still succeeds exactly. unsigned char* region = fresh_region(); if (!region) return 1; diff --git a/tests/startup_dstorage_status_stats_check.cpp b/tests/startup_dstorage_status_stats_check.cpp new file mode 100644 index 0000000000..4ea9f7c764 --- /dev/null +++ b/tests/startup_dstorage_status_stats_check.cpp @@ -0,0 +1,98 @@ +// The DirectStorage stand-in's status wait diagnostics (src/startup_stubs/dstorage_status_stats.h): +// completions and their wait, IsComplete polls, an index enqueued again before its status was written +// ("reused") and the older status's write landing afterwards ("stale"), and the listing of an index +// pending for over a second. `--mutate no-stale` skips the stale check in on_complete's caller +// contract (it passes generation 0 for every write), so the stale count stays 0: the negative control. +#include "startup_stubs/dstorage_status_stats.h" + +#include <cstdarg> +#include <cstring> +#include <string> +#include <vector> + +namespace { + +std::vector<std::string> lines; + +void capture(const char* format, ...) +{ + char line[1024]; + va_list args; + va_start(args, format); + std::vsnprintf(line, sizeof(line), format, args); + va_end(args); + lines.emplace_back(line); + std::printf(" | %s\n", line); +} + +int failures = 0; + +void expect(bool ok, const char* what) +{ + std::printf("%s %s\n", ok ? "ok " : "FAIL", what); + if (!ok) ++failures; +} + +bool logged(const char* text) +{ + for (const auto& l : lines) + if (l.find(text) != std::string::npos) return true; + return false; +} + +constexpr LONG pending = static_cast<LONG>(0x8000000A); + +} // namespace + +int main(int argc, char** argv) +{ + const bool no_stale = argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "no-stale") == 0; + namespace st = x2w_dstorage_stats; + auto queue_text = [](void* queue, char* out, std::size_t size) { std::snprintf(out, size, "queue %p", queue); }; + const auto report = [&](int second) { + lines.clear(); + st::report(second, pending, [](const char* f, auto... a) { capture(f, a...); }, queue_text); + }; + + volatile LONG results[2] = {pending, pending}; + st::StatusStats* s = st::make(2, results); + expect(s != nullptr, "make: stats for a capacity-2 array"); + if (!s) return 1; + int queue = 0; + + // One normal batch: enqueue, polled pending three times, completed, polled complete once. + LONG gen = st::on_enqueue(s, 0, &queue); + results[0] = pending; + for (int i = 0; i < 3; ++i) st::on_poll(s, false, nullptr); + st::on_complete(s, 0, no_stale ? 0 : gen); + results[0] = S_OK; + st::on_poll(s, true, nullptr); + report(10); + expect(logged(no_stale ? "completions 0" : "completions 1,"), "a completed status is counted"); + expect(logged("polls (approximate) pending 3 complete 1"), "IsComplete polls are counted by outcome"); + expect(logged("reused before complete 0, stale writes 0"), "no reuse in a normal batch"); + + // Index 0 enqueued again (gen a), then again before a's status was written (gen b): reused. a's write + // then lands on the index b set pending: stale (the title would see b complete early). + const LONG a = st::on_enqueue(s, 0, &queue); + results[0] = pending; + const LONG b = st::on_enqueue(s, 0, &queue); + results[0] = pending; + st::on_complete(s, 0, no_stale ? 0 : a); + results[0] = S_OK; + report(20); + expect(logged("reused before complete 1"), "an index enqueued again before its status was written counts as reused"); + expect(logged("stale writes 1"), "the older status's write after that counts as stale"); + st::on_complete(s, 0, no_stale ? 0 : b); + + // Index 1 pending for over a second is listed with its queue; index 0 (complete) is not. + st::on_enqueue(s, 1, &queue); + results[1] = pending; + Sleep(1100); + report(30); + expect(logged("status PENDING array #0 index 1 for 1."), "an index pending for over a second is listed"); + expect(!logged("index 0 for"), "a complete index is not listed"); + + std::printf("%s\n", failures ? "FAILED" : "PASSED"); + return failures ? 1 : 0; +} diff --git a/tests/startup_execz_join_check.py b/tests/startup_execz_join_check.py new file mode 100644 index 0000000000..d4d2215d7e --- /dev/null +++ b/tests/startup_execz_join_check.py @@ -0,0 +1,65 @@ +"""A join where one register is symbolic only on the s_cbranch_execz edge, then ANDed with exec in place. + +Measured form (a title pixel stage): s13 holds a copy of an entry SGPR (no run-time value) on the path that +s_cbranch_execz takes, a compare mask on the fall-through, and after the join `s_and_b32 s13, s13, exec_lo`. +RDNA 2 ISA: S_CBRANCH_EXECZ branches when EXEC is 0; S_AND_B32 D = S0 & S1. On the taken path this lane's exec +bit is 0 in the one-lane model, so the AND gives 0 whatever s13 held; on the other path s13's run-time variable +is its value. The translation reads the run-time variable there instead of refusing the conflict. +Synthetic words: s_mov_b32 s13, s0 (s0 a root pointer); v_cmp_lt_u32 vcc, 1, v0; s_and_saveexec_b32 s20, vcc_lo; +s_cbranch_execz L; s_and_b32 s13, vcc_lo, exec_lo; s_nop 0; L: s_and_b32 s13, s13, exec_lo. +The emitted line must be the in-place AND of the run-time variable; its value on both paths (v0 = 0: branch +taken, s13 never assigned at run time, result 0; v0 = 2: s13 the mask, result 1) is checked. +Controls (refused): the same join reached by s_cbranch_scc0 (exec not known to be 0 there); exec written between +the join and the AND; a use other than the in-place AND (s_lshl_b32). +""" +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_scalar_bits_check import sop1, stage # noqa: E402 + +CMP_VCC = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 +SAVE32 = sop1(0x3c, 20, 106) # s_and_saveexec_b32 s20, vcc_lo +NOP = 0xbf800000 + + +def sop2(op, dst, a, b): + return 0x80000000 | op << 23 | dst << 16 | b << 8 | a + + +def program(branch_op=8, before_use=(), use=None): + use = use if use is not None else sop2(0x0e, 13, 13, 126) # s_and_b32 s13, s13, exec_lo + return [sop1(3, 13, 0), CMP_VCC, SAVE32, 0xbf800000 | branch_op << 16 | 2, + sop2(0x0e, 13, 106, 126), NOP] + list(before_use) + [use] + + +def refused(words, label): + try: + stage(words) + except G.Unsupported as error: + assert 'conflict' in str(error) or 'execzero' in str(error), (label, str(error)) + return 1 + raise AssertionError('accepted: ' + label) + + +def main(): + s = stage(program()) + body = [line for _, lines, _ in s.blocks for line in lines] + assert 's13 = (s13 & exec) & 1;' in body, body + for v0, want in ((0, 0), (2, 1)): + exec_bit = int(1 < v0) + # the two paths: taken (exec 0, s13 never assigned at run time) and fall-through (s13 the mask) + s13 = 0x5678 if not exec_bit else 1 + assert (s13 & exec_bit) & 1 == want + controls = refused(program(branch_op=4), 's_cbranch_scc0 edge') + controls += refused(program(before_use=[sop1(3, 126, 20)]), 'exec written before the AND') + controls += refused(program(use=sop2(0x1e, 5, 13, 0x81)), 's_lshl_b32 use') # s_lshl_b32 s5, s13, 1 + print('execz_join: in-place AND with exec after an execz-only conflict reads the run-time variable (0 on the ' + 'taken path, the mask on the other); %d controls refused' % controls) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_fma_exact_fxc_check.py b/tests/startup_fma_exact_fxc_check.py new file mode 100644 index 0000000000..0254d4f084 --- /dev/null +++ b/tests/startup_fma_exact_fxc_check.py @@ -0,0 +1,226 @@ +"""Exact FMA (x2w_fma_exact) in fxc-compiled draw stages: no double immediates in the bytecode. + + (no arguments) translation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> <fxc> + compile probe pixel stages with FXC ps_5_1 and DXC ps_6_0, check the FXC + bytecode for d(...) immediates and draw one pixel per probe + +Defect (measured on WARP and on an RX 9070 XT, driver 32.0.32015.7029): when fxc 10.0.26100 folds a constant +operand of a double op into a d(a, b) immediate and the instruction writes .zw, the second half of the immediate +is not what the GPU uses. Two calls packed into one register then lose the second result: +`dfma r0.zw, r1.xyxy, r1.zwzw, d(0.0, 1.5)` adds 0.0, and an all-constant `dfma r0.xyzw` returns 0 in .zw. +gfx2hlsl's draw stages therefore XOR every helper operand with x2w_fz, a static that main() sets to p * p + p & 1 +of an input word (always 0; fxc does not fold it), so the double ops only ever read registers (FMA_EXACT_FXC). + +Probes: four helper calls written to mrt0.xyzw, so two land in .zw halves, in both orders (fwd / rev), with +operands that are literals ('c'), run-time values ('rt': z + literal, z = 0.0 from root constant 1), or run-time +a, b with a literal c ('rtc'), on two value sets (plain values and rounding cases). Expected words: the exact +rational a * b + c rounded to binary64, then to binary32 (the helper's definition), computed here in Python. +Every FXC and DXC result must match it bit for bit, and the FXC bytecode must have no d(...) immediate. +Negative control: the plain helper (HELPERS['x2w_fma_exact'], the form before the guard) must fail the four +literal probes and a run-time probe (a, b from z, literal c, second call first) under FXC and show the immediates. +""" +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)) +import gfx2hlsl as G # noqa: E402 +import startup_draw_fma_check as D # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS # noqa: E402 +from startup_sampler_heap_check import root_blob # noqa: E402 + + +def compile_hlsl(compiler, kind, source, out, profile, directory): + path = directory / ('%s.hlsl' % out) + path.write_text(source, encoding='ascii') + target = directory / ('%s.cso' % out) + if kind == 'fxc': + args = [compiler, '/nologo', '/T', profile, '/E', 'main', '/Fo', str(target), str(path)] + else: + args = [compiler, '-T', profile, '-E', 'main', '-Fo', str(target), str(path)] + subprocess.run(args, check=True, capture_output=True, text=True, timeout=60) + return target + + +def fma_pipeline(): + """startup_draw_fma_check's vertex stage with v_fma_f32 v4, v1, v2, v3 (exact FMA) and its plain pixel stage.""" + words = list(D.PROLOGUE) + [w for w in D.vop3(0x14b, 4, 1, 2, 3)] + list(D.EXPORT) + return G.Pipeline(struct.pack('<%dI' % len(words), *words), D.PS, root_blob(flags=0)) + +HEAD = '''#define F(x) asfloat(x) +#define U(x) asuint(x) +%s +cbuffer entry : register(b0) { uint ud0; uint ud1; uint ud2; uint ud3; }; +struct PSIn { float4 pos : SV_Position; }; +struct PSOut { float4 mrt0 : SV_Target0; }; +PSOut main(PSIn i) { + PSOut o = (PSOut)0; +%s + float z = F(ud1); +%s + return o; +} +''' +SETS = { + 'plain': [(0.25, 0.5, 1.5), (-0.25, 0.5, 1.5), (3.0, -0.75, 0.125), (1.0e-3, 7.0, -1.0)], + 'rounding': [(1.0 + 2 ** -23, 1.0 - 2 ** -24, -1.0), (16777215.0, 3.0, 1.0), (0.1, 0.2, 0.3), (-1.5, 2 ** -20, 2 ** 30)], +} + + +def f32(x): + return struct.unpack('<f', struct.pack('<f', x))[0] + + +def bits(x): + return struct.unpack('<I', struct.pack('<f', x))[0] + + +def expect(a, b, c): + a, b, c = f32(a), f32(b), f32(c) + return f32(float(Fraction(a) * Fraction(b) + Fraction(c))) # float(Fraction) rounds once to binary64 + + +def lit(x): + return 'F(0x%08xu)' % bits(f32(x)) + + +def body(quads, mode, order): + lines = [] + for k, (a, b, c) in enumerate(quads): + run_ab, run_c = mode in ('rt', 'rtc'), mode == 'rt' + lines.append(' float r%d = x2w_fma_exact(%s, %s, %s);' % ( + k, '(z + %s)' % lit(a) if run_ab else lit(a), '(z + %s)' % lit(b) if run_ab else lit(b), + '(z + %s)' % lit(c) if run_c else lit(c))) + if order == 'rev': + lines.reverse() + return '\n'.join(lines + [' o.mrt0 = float4(r0, r1, r2, r3);']) + + +class _Guarded: + def fma_guard(self): + return True + + +def shader(guarded, text): + helper = G.FMA_EXACT_FXC if guarded else G.HELPERS['x2w_fma_exact'] + init = '\n'.join(G.Pipeline.fma_guard_init(_Guarded(), 'asuint(i.pos.x)')) if guarded else '' + return HEAD % (helper, init, text) + + +def controls(): + saved = G.DRAW_FMA + G.DRAW_FMA = 'exact' + try: + pipe = fma_pipeline() + vs, ps = pipe.hlsl_vs(), pipe.hlsl_ps() + mesh = fma_pipeline() + mesh.hlsl_ms = None # a mesh pipeline (dxc, its mesh stage has no main() here to set x2w_fz) + mesh_common = '\n'.join(mesh.common()) + G.DRAW_FMA = 'legacy' + plain_vs, plain_ps = fma_pipeline().hlsl_vs(), fma_pipeline().hlsl_ps() + finally: + G.DRAW_FMA = saved + vinit = ' x2w_fz = (vid * vid + vid) & 1u; // always 0, see FMA_EXACT_FXC' + assert 'v4 = U(x2w_fma_exact(F(v1), F(v2), F(v3)));' in vs, vs + assert G.FMA_EXACT_FXC in vs and G.HELPERS['x2w_fma_exact'] not in vs and vs.count(vinit) == 1, vs + # The fixture reads v3 at entry, so its stage also takes SV_InstanceID (startup_gfx2hlsl_vs_instance_id_check.py). + assert vs.index('VSOut main(uint vid : SV_VertexID, uint iid : SV_InstanceID) {') < vs.index(vinit) < \ + vs.index('return body(vid, iid);'), vs + # Helpers are emitted for the pipeline, so the pixel stage declares the guard too and its main() sets it. + pinit = ' x2w_fz = (asuint(i.pos.x) * asuint(i.pos.x) + asuint(i.pos.x)) & 1u; // always 0, see FMA_EXACT_FXC' + assert G.FMA_EXACT_FXC in ps and ps.count(pinit) == 1, ps + assert not mesh.fma_guard() and G.FMA_EXACT_FXC not in mesh_common and G.HELPERS['x2w_fma_exact'] in mesh_common + assert 'x2w_fz' not in plain_vs + plain_ps and 'x2w_fma_exact' not in plain_vs + plain_ps + # The guard word is 0 for every input word (p (p + 1) is even, also mod 2^32). + for p in (0, 1, 2, 3, 0x3f000000, 0x7fffffff, 0x80000000, 0xfffffffe, 0xffffffff): + assert (p * p + p) & 0xffffffff & 1 == 0 + for name, quads in SETS.items(): + for q in quads: + assert expect(*q) == f32(expect(*q)) + print('x2w_fma_exact: draw stages use FMA_EXACT_FXC with the x2w_fz init in main(); mesh and legacy keep none') + + +def double_immediates(fxc, cso): + out = subprocess.run([fxc, '/nologo', '/dumpbin', str(cso)], capture_output=True, text=True, timeout=60).stdout + return [l.strip() for l in out.splitlines() if not l.lstrip().startswith('//') and re.search(r'\bd\(', l)] + + +def draw(renderer, adapter, vs, ps, want): + hexw = ','.join('%08x' % bits(w) for w in want) + run = subprocess.run([renderer, adapter, '--startup-image-3d', str(vs), str(ps), '0', hexw], + capture_output=True, text=True, timeout=90) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + if run.returncode == 0: + return None + m = re.search(r'actual=([0-9a-f,]+)', run.stderr) + if not m: + raise AssertionError(run.stdout + run.stderr) + return m.group(1) + + +def check_draw(dxc, renderer, adapter, fxc): + failed_control = 0 + with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + vss = {'fxc': compile_hlsl(fxc, 'fxc', FULLSCREEN_VS, 'vs5', 'vs_5_1', d), + 'dxc': compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'vs6', 'vs_6_0', d)} + for name, quads in SETS.items(): + want = [expect(*q) for q in quads] + for mode in ('c', 'rt', 'rtc'): + for order in ('fwd', 'rev'): + for guarded in (True, False): + text = shader(guarded, body(quads, mode, order)) + for kind, comp, prof in (('fxc', fxc, 'ps_5_1'), ('dxc', dxc, 'ps_6_0')): + label = '%s %s %s %s %s' % (name, mode, order, kind, 'guard' if guarded else 'plain') + ps = compile_hlsl(comp, kind, text, 'p', prof, d) + imm = double_immediates(fxc, ps) if kind == 'fxc' else [] + bad = draw(renderer, adapter, vss[kind], ps, want) + if guarded or kind == 'dxc': + assert not imm, (label, imm) + assert bad is None, (label, bad, ['%08x' % bits(w) for w in want]) + print('%-40s ok' % label, flush=True) + elif mode == 'c': + # negative control: the plain helper with literal operands, FXC + assert imm and bad is not None, (label, imm, bad) + failed_control += 1 + print('%-40s fails as expected: %s; %s' % (label, bad, imm[0]), flush=True) + # Run-time a and b, literal c, the second call first: plain fxc writes `dfma r0.zw, ..., d(0.0, 1.5)`. + text = (' float a4 = z + 0.25, a5 = z - 0.25, h = z + 0.5;\n float v5 = x2w_fma_exact(a5, h, 1.5);\n' + ' float v4 = x2w_fma_exact(a4, h, 1.5);\n o.mrt0 = float4(h, v4, v5, 0);') + want = [0.5, expect(0.25, 0.5, 1.5), expect(-0.25, 0.5, 1.5), 0.0] + for guarded in (True, False): + for kind, comp, prof in (('fxc', fxc, 'ps_5_1'), ('dxc', dxc, 'ps_6_0')): + label = 'runtime swapped %s %s' % (kind, 'guard' if guarded else 'plain') + ps = compile_hlsl(comp, kind, shader(guarded, text), 'p', prof, d) + imm = double_immediates(fxc, ps) if kind == 'fxc' else [] + bad = draw(renderer, adapter, vss[kind], ps, want) + if guarded or kind == 'dxc': + assert not imm and bad is None, (label, imm, bad) + print('%-40s ok' % label, flush=True) + else: + assert imm and bad is not None, (label, imm, bad) + failed_control += 1 + print('%-40s fails as expected: %s; %s' % (label, bad, imm[0]), flush=True) + assert failed_control == 5, failed_control + print('%s: guarded helper matches the binary64 reference under FXC and DXC in every probe, no d(...) ' + 'immediates; plain helper fails all %d control probes under FXC (4 literal, 1 run-time)' + % (adapter, failed_control)) + + +def main(): + controls() + if len(sys.argv) > 1 and sys.argv[1] == 'draw': + check_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_fmt_load_table_check.py b/tests/startup_fmt_load_table_check.py new file mode 100644 index 0000000000..5a0a8edd52 --- /dev/null +++ b/tests/startup_fmt_load_table_check.py @@ -0,0 +1,169 @@ +"""x2w_fmt_load in its table form gives the per-format chain's values (tools/startup/gfx2hlsl.py). + +The emitted helper (HELPERS['x2w_fmt_load'] = buf_format_helper_table()) looks the FORMAT code of V# word 3 up in a +constant table of channel widths and kind and decodes the channel with one routine; the older helper +(buf_format_helper(), kept as the reference) had one if-arm per format, which fxc compiled for minutes per call site. + +Checked in Python, over every FORMAT code 0..127, every DST_SEL value 0..7 for each of the four result channels, and +32 element addresses (all four byte alignments) of a pseudo-random buffer that also holds the most negative SNORM +fields: +- the reference: each format's channel expressions exactly as the old chain emits them (buf_format_channel), run + by a small evaluator, with the old helper's fills (unknown code: 0; selector 0/2/3: 0; 1: 1 or 1.0; a channel + the format lacks: 0, w: one); +- the new helper: its table parsed from the emitted HLSL text, and a line-for-line Python transcription of its + decoder, whose HLSL lines are asserted verbatim so the transcription cannot drift. +Float results are compared as binary32 bits; the division is rounded to binary32 once in both (on the GPU the +chain divided by a literal and the table form divides by a run-time value: equal results there are ASSUMED). +Negative controls: a table with one width changed, and a decoder with the SNORM clamp dropped, both mismatch. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +M = 0xffffffff +DATA = bytearray(((i * 0x9e3779b1) >> 13) & 0xff for i in range(256)) +DATA[2:5] = bytes((0x00, 0x80, 0x80)) # the most negative SNORM fields: -32768 at a = 2, -128 at a = 4 +ADDRS = list(range(0, 64, 2)) + + +def f32(x): + return struct.unpack('<f', struct.pack('<f', x))[0] + + +def bits(x): + return struct.unpack('<I', struct.pack('<f', f32(x)))[0] + + +def half(h): + return struct.unpack('<e', struct.pack('<H', h & 0xffff))[0] + + +def load(a): + return int.from_bytes(DATA[a & ~3:(a & ~3) + 4], 'little') + + +def ldu(a): + return int.from_bytes(DATA[a:a + 4], 'little') + + +def s32(x): + x &= M + return x - (1 << 32) if x >> 31 else x + + +def chain_channel(code, k, a): + """The old chain's expression for channel k of `code`, evaluated.""" + widths, kind = G.BUF_FORMATS[code] + text = G.buf_format_channel(widths, kind, k) + py = re.sub(r'(0x[0-9a-f]+|\d+)u\b', r'\1', text) + py = py.replace('b.Load(', 'load(').replace('ldu(b, ', 'ldu(').replace('uint(int(', 'u32(s32(') + py = py.replace('float(int(', 'float(s32(').replace('U(', 'ubits(') + env = {'a': a, 'load': load, 'ldu': ldu, 's32': s32, 'u32': lambda x: x & M, 'max': max, + 'ubits': lambda x: bits(x) if isinstance(x, float) else x & M, 'f16tof32': half, + 'float': float, '__builtins__': {}} + return eval(py, env) & M + + +def chain_load(code, a, w3, c): + s = (w3 >> (3 * c)) & 7 + if code not in G.BUF_FORMATS or s in (0, 2, 3): + return 0 + widths, kind = G.BUF_FORMATS[code] + one = 1 if kind in ('uint', 'sint') else 0x3f800000 + if s == 1: + return one + k = s - 4 + if k >= len(widths): + return one if k == 3 else 0 + return chain_channel(code, k, a) + + +DECODER = [ + 'uint x2w_fmt_chan(ByteAddressBuffer b, uint a, uint d, uint k, uint one) {', + ' uint n = (d >> (6u * k)) & 63u;', + ' if (n == 0u) return k == 3u ? one : 0u;', + ' uint pos = (k > 0u ? (d & 63u) : 0u) + (k > 1u ? ((d >> 6) & 63u) : 0u) + (k > 2u ? ((d >> 12) & 63u) : 0u);', + ' uint kind = (d >> 24) & 7u, sh = 32u - n;', + ' uint raw = n == 32u ? b.Load(a + pos / 8u) : ((ldu(b, a + 4u * (pos / 32u)) >> (pos % 32u)) & ((1u << n) - 1u));', + ' int sv = int(raw << sh) >> sh;', + ' if (kind == 0u || (kind == 4u && n == 32u)) return raw;', + ' if (kind == 1u) return uint(sv);', + ' if (kind == 2u) return U(float(raw) / float((1u << n) - 1u));', + ' if (kind == 3u) return U(max(float(sv) / float((1u << (n - 1u)) - 1u), -1.0));', + ' return U(f16tof32(n == 16u ? raw : raw << (15u - n))); }', + 'uint x2w_fmt_load(ByteAddressBuffer b, uint a, uint w3, uint c) {', + ' uint f = (w3 >> 12) & 127u, s = (w3 >> (3u * c)) & 7u;', + ' uint d = f < 78u ? x2w_fmt_tab[f] : 0u;', + ' if (d == 0u || s == 0u || s == 2u || s == 3u) return 0u;', + ' uint one = ((d >> 24) & 7u) <= 1u ? 1u : 0x3f800000u;', + ' return s == 1u ? one : x2w_fmt_chan(b, a, d, s - 4u, one); }'] + + +def table_chan(a, d, k, one, clamp=True): + """Line-for-line transcription of DECODER's x2w_fmt_chan (HLSL shifts take the low 5 bits of the count).""" + n = (d >> (6 * k)) & 63 + if n == 0: + return one if k == 3 else 0 + pos = ((d & 63) if k > 0 else 0) + (((d >> 6) & 63) if k > 1 else 0) + (((d >> 12) & 63) if k > 2 else 0) + kind, sh = (d >> 24) & 7, (32 - n) & 31 + raw = load(a + pos // 8) if n == 32 else (ldu(a + 4 * (pos // 32)) >> (pos % 32)) & ((1 << n) - 1) + sv = s32(raw << sh) >> sh + if kind == 0 or (kind == 4 and n == 32): + return raw + if kind == 1: + return sv & M + if kind == 2: + return bits(float(raw) / float((1 << n) - 1)) + if kind == 3: + q = float(sv) / float((1 << (n - 1)) - 1) + return bits(max(q, -1.0) if clamp else q) + return bits(half(raw if n == 16 else raw << (15 - n))) + + +def table_load(tab, a, w3, c, clamp=True): + f, s = (w3 >> 12) & 127, (w3 >> (3 * c)) & 7 + d = tab[f] if f < len(tab) else 0 + if d == 0 or s in (0, 2, 3): + return 0 + one = 1 if (d >> 24) & 7 <= 1 else 0x3f800000 + return one if s == 1 else table_chan(a, d, s - 4, one, clamp) + + +def mismatches(tab, clamp=True): + bad = [] + for code in range(128): + for c in range(4): + for s in range(8): + w3 = code << 12 | s << (3 * c) + for a in ADDRS: + if table_load(tab, a, w3, c, clamp) != chain_load(code, a, w3, c): + bad.append((code, c, s, a)) + return bad + + +def main(): + text = G.HELPERS['x2w_fmt_load'] + assert text == G.buf_format_helper_table(), 'the emitted helper is the table form' + lines = text.split('\n') + m = re.fullmatch(r'static const uint x2w_fmt_tab\[(\d+)\] = \{ (.*) \};', lines[0]) + assert m and lines[1:] == DECODER, lines[1:] + tab = [int(x[:-1], 16) for x in m.group(2).split(', ')] + assert len(tab) == int(m.group(1)) == 78 + bad = mismatches(tab) + assert not bad, bad[:5] + checked = 128 * 4 * 8 * len(ADDRS) + wrong = list(tab) + wrong[56] = (wrong[56] & ~63) | 7 # 8_8_8_8_UNORM x read as 7 bits + assert mismatches(wrong), 'a wrong width escaped' + assert mismatches(tab, clamp=False), 'a dropped SNORM clamp escaped' + print('fmt_load_table: table helper equals the per-format chain on %d (code, channel, selector, address) cases ' + '(%d formats); wrong-width and no-clamp controls caught' % (checked, len(G.BUF_FORMATS))) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_format_load_check.py b/tests/startup_format_load_check.py new file mode 100644 index 0000000000..3b8319ab71 --- /dev/null +++ b/tests/startup_format_load_check.py @@ -0,0 +1,111 @@ +"""buffer_load_format_* through a descriptor-table entry, behind X2W_DRAW_FEATURES=bufword3 (tools/startup/gfx2hlsl.py). + +The format and DST_SEL are in the descriptor's word 3, which the draw runtime passes as `udsrc <n> bufword3 <srv>` +(draw-rt RUNTIME_DONE.md). Checked here, on synthetic register states: +1. feature off: refused with the old message (the op name), so --requests output does not change; +2. feature on: idxen address index * stride + offset, one x2w_fmt_load per destination with the word-3 constant; + a root or vertex-buffer source (word 3 is 0 there) and an unknown modifier are refused; +3. BUF_FORMATS covers exactly the buffer FORMAT codes gfx10_view_words.h can synthesize (list copied below from its + gfx10_buffer_format cases with a nonzero element size), and the channel layout of a few formats; +4. with fxc available (X2W_FXC or the SDK default), the helper compiles for ps_5_1 in a minimal shader. +Not checked: the decoded values on a GPU (no readback here); the 0 / 0001 fills are assumptions. +""" +import os +import subprocess +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +# gfx10_view_words.h gfx10_buffer_format: codes with a nonzero element size (the buffer-capable ones) +HEADER_BUFFER_CODES = {77, 75, 76, 74, 72, 73, 71, 65, 69, 66, 70, 64, 62, 63, 50, 54, 36, 56, 60, 57, 61, + 29, 23, 27, 24, 28, 22, 20, 21, 14, 18, 15, 19, 13, 7, 11, 8, 12, 1, 5, 2, 6} + + +class Pipe: + sampler_heap = False + root = {'params': [], 'flags': 0} + + def __init__(self, features): + self.features = frozenset(features) + self.resources, self.uds, self.modified = {}, [], set() + + def resource(self, key, kind): + r = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) + return 'r%d' % r['index'] + + def ud(self, source): + if source not in self.uds: + self.uds.append(source) + return self.uds.index(source) + + +def stage(features, source=('table', 0)): + s = G.Stage(Pipe(features), 'ps', b'') + s.lines = [] + for i in range(4): + s.sym[16 + i] = ('desc', source, 0x20, i) + s.pc = 0 + return s + + +def main(): + try: + stage(()).op_buffer_load_format_x(['v2', 'v1', 's[16:19]', '0'], ['idxen']) + except G.Unsupported as error: + assert str(error) == 'buffer_load_format_x', str(error) + else: + raise AssertionError('accepted with the feature off') + + s = stage(('bufword3',)) + s.op_buffer_load_format_xy(['v[2:3]', 'v1', 's[16:19]', '0'], ['idxen', 'offset:8']) + assert s.pipe.uds == [('stride', 0), ('bufword3', 0)], s.pipe.uds + assert s.lines[0] == 'a = v1 * ud0 + 8;', s.lines + assert s.lines[1:] == ['v2 = x2w_fmt_load(r0, a, ud1, 0u);', 'v3 = x2w_fmt_load(r0, a, ud1, 1u);'], s.lines + for source, mods, want in ((('root', 2), ['offen'], 'through root'), (('vbtab',), ['idxen'], 'through vbtab'), + (('table', 0), ['tfe'], 'modifier tfe')): + try: + stage(('bufword3',), source).op_buffer_load_format_x(['v2', 'v1', 's[16:19]', '0'], mods) + except G.Unsupported as error: + assert want in str(error), (want, str(error)) + else: + raise AssertionError('accepted: %s %s' % (source, mods)) + print('format load: feature off refused as before; idxen address and word-3 constant; root/vb/tfe refused') + + assert set(G.BUF_FORMATS) == HEADER_BUFFER_CODES, sorted(set(G.BUF_FORMATS) ^ HEADER_BUFFER_CODES) + ch = G.buf_format_channel + assert ch((8, 8, 8, 8), 'unorm', 2) == 'U(float(((ldu(b, a + 0u) >> 16u) & 0xffu)) / 255.0)' + assert ch((10, 10, 10, 2), 'unorm', 3) == 'U(float(((ldu(b, a + 0u) >> 30u) & 0x3u)) / 3.0)' + assert ch((11, 11, 10), 'float', 2) == 'U(f16tof32((((ldu(b, a + 0u) >> 22u) & 0x3ffu) << 5u)))' + assert ch((11, 11, 10), 'float', 0) == 'U(f16tof32((((ldu(b, a + 0u) >> 0u) & 0x7ffu) << 4u)))' + assert ch((16,) * 4, 'float', 3) == 'U(f16tof32(((ldu(b, a + 4u) >> 16u) & 0xffffu)))' + assert ch((32,) * 4, 'sint', 2) == 'b.Load(a + 8u)' + assert ch((8,), 'sint', 0) == 'uint(int(((ldu(b, a + 0u) >> 0u) & 0xffu) << 24u) >> 24u)' + assert ch((16, 16), 'snorm', 1) == 'U(max(float(int(((ldu(b, a + 0u) >> 16u) & 0xffffu) << 16u) >> 16u) / 32767.0, -1.0))' + print('formats: %d codes, the header buffer set exactly; channel layouts as listed' % len(G.BUF_FORMATS)) + + fxc = G.find_fxc() + if not fxc: + print('fxc not found: compile step skipped') + return + src = '\n'.join(['#define U(x) asuint(x)', + 'uint ldu(ByteAddressBuffer b, uint a) { uint k = (a & 3) * 8, lo = b.Load(a & ~3u); if (k == 0) return lo; ' + 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }', + G.HELPERS['x2w_fmt_load'], + 'cbuffer entry : register(b0) { uint ud0; uint ud1; };', + 'ByteAddressBuffer r0 : register(t0);', + 'float4 main(float4 p : SV_Position) : SV_Target { uint a = uint(p.x) * 4u;', + ' return float4(asfloat(x2w_fmt_load(r0, a, ud0, 0u)), asfloat(x2w_fmt_load(r0, a, ud0, 1u)),', + ' asfloat(x2w_fmt_load(r0, a, ud1, 2u)), asfloat(x2w_fmt_load(r0, a, ud1, 3u))); }']) + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'f.hlsl') + open(path, 'w').write(src) + r = subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', os.path.join(tmp, 'f.cso'), path], + capture_output=True, text=True) + assert r.returncode == 0, r.stderr[-2000:] + print('helper compiles with fxc ps_5_1') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_format_store_check.py b/tests/startup_format_store_check.py new file mode 100644 index 0000000000..ab9485711b --- /dev/null +++ b/tests/startup_format_store_check.py @@ -0,0 +1,105 @@ +"""buffer_store_format_* to a typed buffer UAV, behind X2W_DRAW_FEATURES=uav,uavfmt (tools/startup/gfx2hlsl.py). + +Measured form (a title 1x1 pass): `buffer_store_format_xyzw v[20:23], v1, s[8:11], 0 idxen`, the descriptor a table +entry. RDNA 2 ISA MUBUF addressing: base + soffset + inst offset + stride * index (+ the offen VGPR); the format is +V# word 3 [18:12]. Checked on synthetic register states: +1. feature off (uav only): refused with the op name, as before; +2. on: `a = ud<uavbase> + v1 * ud<uavstride> + offset`, then x2w_fmt_store(u0, a, ud<uavword3>, data, count), + the exec guard when exec is not the entry mask, idxen + offen as index * stride + offset VGPR, an SGPR soffset; +3. the helper writes exactly the formats of BUF_FORMATS whose channels are all 32 bits (codes 20-22, 62-64, + 72-77), as many channels as the format has and the instruction gives; a Python model of the helper is run on + every code 0..127 against that rule. Negative control: a model that also writes 16-bit-channel formats + (71, 16_16_16_16_FLOAT) differs; +4. refusals: tfe, a vertex-buffer source, a modified descriptor. +ASSUMED (not measured): DST_SEL does not reorder a store; the index is in range. +""" +import os +import re +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + sampler_heap = False + root = {'params': [], 'flags': 0} + uav = G.Pipeline.uav + resource = G.Pipeline.resource + + def __init__(self, features): + self.features = frozenset(features) + self.resources, self.uds, self.modified, self.heapvars, self.notes = {}, [], set(), [], set() + + def ud(self, source): + if source not in self.uds: + self.uds.append(source) + return self.uds.index(source) + + +def stage(features=('uav', 'uavfmt'), source=('table', 1)): + s = G.Stage(Pipe(features), 'ps', b'') + s.lines = [] + for i in range(4): + s.sym[8 + i] = ('desc', source, 0x60, i) + s.pc = 0 + return s + + +def refused(s, ops, mods, want): + try: + s.op_buffer_store_format_xyzw(ops, mods) + except G.Unsupported as error: + assert want in str(error), (want, str(error)) + else: + raise AssertionError('accepted: %s %s' % (ops, mods)) + + +def helper_model(code, given, wide=False): + """Channels the helper writes for format code `code` and `given` data components.""" + ranges = re.findall(r'f >= (\d+)u && f <= (\d+)u\) \? (\d)u', G.HELPERS['x2w_fmt_store']) + n = 0 + for lo, hi, count in ranges: + if int(lo) <= code <= int(hi): + n = int(count) + if wide and code == 71: + n = 4 + return min(n, given) + + +def rule(code, given): + widths = G.BUF_FORMATS.get(code, ((),))[0] + return min(len(widths), given) if widths and all(w == 32 for w in widths) else 0 + + +def main(): + STORE = ['v[20:23]', 'v1', 's[8:11]', '0'] + refused(stage(('uav',)), STORE, ['idxen'], 'buffer_store_format_xyzw') + s = stage() + s.op_buffer_store_format_xyzw(STORE, ['idxen']) + assert s.lines == ['a = ud0 + v1 * ud2 + 0;', 'x2w_fmt_store(u0, a, ud1, uint4(v20, v21, v22, v23), 4u);'], s.lines + assert s.pipe.uds == [('uavbase', 0), ('uavword3', 0), ('uavstride', 0)], s.pipe.uds + s = stage() + s.exec_known = False + s.op_buffer_store_format_xy(['v[4:5]', 'v[1:2]', 's[8:11]', 's3'], ['idxen', 'offen', 'offset:8']) + assert s.lines == ['a = ud0 + s3 + v1 * ud2 + v2 + 8;', + 'if (exec & 1) x2w_fmt_store(u0, a, ud1, uint4(v4, v5, 0u, 0u), 2u);'], s.lines + refused(stage(), STORE, ['idxen', 'tfe'], 'modifier tfe') + refused(stage(source=('vbtab',)), STORE, ['idxen'], 'through vbtab') + s = stage() + s.pipe.modified.add((('table', 1), 0x60)) + refused(s, STORE, ['idxen'], 'modified descriptor') + checked = 0 + for code in range(128): + for given in (1, 2, 3, 4): + assert helper_model(code, given) == rule(code, given), (code, given) + checked += 1 + assert any(helper_model(c, g, wide=True) != rule(c, g) for c in range(128) for g in (1, 2, 3, 4)) + assert 'x2w_fmt_store' in G.HELPERS and 'RWByteAddressBuffer b' in G.HELPERS['x2w_fmt_store'] + print('format_store: feature off refused; idxen / idxen+offen / soffset addresses with uavbase, uavword3, ' + 'uavstride; exec guard; helper writes the 32-bit-channel formats only (%d code x count cases); ' + 'negative control caught; tfe, vertex buffer, modified descriptor refused' % checked) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_frame_copy.cpp b/tests/startup_frame_copy.cpp index 738fccae7b..2eb82dd7d0 100644 --- a/tests/startup_frame_copy.cpp +++ b/tests/startup_frame_copy.cpp @@ -1,7 +1,9 @@ #include <windows.h> #include <array> +#include <atomic> #include <cstdint> +#include <cstdio> #include <cstring> #include <vector> @@ -12,17 +14,66 @@ // memory between the draws: // changed the colour is rewritten in place (red, then blue) // same the memory is left alone (red both times) +// wrap upload ring reuse (run with a small X2W_UPLOAD_RING_TEST_KIB): red into the left half, then 64 draws +// with an empty scissor, each with new contents (64 fresh copies, 32 KiB, more than the test ring), +// then green into the right half, all in ONE list. The left half must still be red: its copy may not be +// overwritten before the list has executed. +// reuse upload chunk recycling across two submits of one frame (16 KiB test chunks): list A draws red into the +// left half, then 100 empty-scissor draws from a second buffer with fresh contents each (chunks 0-3); +// A is executed and waited for. The same list is Reset (draw_frame_copies_again): it draws the unchanged +// red constants into the right half (a frame-copy cache hit on chunk 0, whose fence has passed), then 64 +// fresh filler copies that recycle the chunks A used. Chunk 0 must not be one of them: the right half +// must be red. X2W_UPLOAD_RING_TEST_NO_REPIN=1 (negative control) skips the re-pin on the cache hit. +// X2W_TEST_RING_COUNTERS=<file> receives the ring counters (x2w_upload_ring_test) after the second list. +namespace { +// LOCAL stall: one constant buffer and one view heap backing per drawing thread (X2W_TEST_THREADS in +// startup_stream_consumer); the first thread to draw uses slot 0, as a single-threaded run always did. +constexpr int frame_slots = 8; +alignas(256) float frame_constants_by_slot[frame_slots][64]; +std::atomic<int> next_frame_slot{0}; +int frame_slot() +{ + thread_local const int slot = next_frame_slot.fetch_add(1) % frame_slots; + return slot; +} +alignas(256) float filler_constants[64] = {}; +void* reuse_heap = nullptr; +StreamWord reuse_table = 0, reuse_step = 0; +void* reuse_guest = nullptr; + +void filler_draws(void* list, int count, int salt) +{ + const D3D12_RECT none{0, 0, 0, 0}; + invoke(list, 22, 1, reinterpret_cast<std::uintptr_t>(&none)); + invoke(list, 36, 0, reuse_table + reuse_step); // the filler buffer + for (int i = 0; i < count; ++i) { + filler_constants[0] = 1.0f; // yellow, a different alpha each time: a fresh copy per draw + filler_constants[1] = 1.0f; + filler_constants[2] = 0.0f; + filler_constants[3] = static_cast<float>(salt + i + 1) / 256.0f; + invoke(list, 12, 3, 1); + } +} +} // namespace + int draw_frame_copies(ID3D12Device* desktop, void* guest, void* list, UINT width, UINT height) { char mode[16]{}; GetEnvironmentVariableA("X2W_TEST_FRAME_COPY", mode, sizeof(mode)); const bool changed = !std::strcmp(mode, "changed"); - if (!changed && std::strcmp(mode, "same")) return 2; + const bool wrap = !std::strcmp(mode, "wrap"); + const bool reuse = !std::strcmp(mode, "reuse"); + if (!changed && !wrap && !reuse && std::strcmp(mode, "same")) return 2; - alignas(256) static float constants[64] = {1.0f, 0.0f, 0.0f, 1.0f}; + const int slot = frame_slot(); + float* const constants = frame_constants_by_slot[slot]; + std::memset(constants, 0, sizeof(frame_constants_by_slot[slot])); + constants[0] = 1.0f; // red; set on every call, as "changed" leaves blue here for the next repeat + constants[3] = 1.0f; const UINT increment = desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - const UINT entries = (32 + increment - 1) / increment; - static std::vector<unsigned char> views; + const UINT entries = (32 + increment - 1) / increment + (reuse ? 2 : 0); + static std::vector<unsigned char> views_by_slot[frame_slots]; + std::vector<unsigned char>& views = views_by_slot[slot]; views.assign(static_cast<std::size_t>(entries) * increment, 0); const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; @@ -35,14 +86,41 @@ int draw_frame_copies(ID3D12Device* desktop, void* guest, void* list, UINT width reinterpret_cast<std::uintptr_t>(&heap))))) return 41; const StreamWord cpu = invoke(heap, 9); if (cpu != reinterpret_cast<std::uintptr_t>(views.data())) return 42; - const D3D12_CONSTANT_BUFFER_VIEW_DESC view{reinterpret_cast<std::uintptr_t>(constants), sizeof(constants)}; + const D3D12_CONSTANT_BUFFER_VIEW_DESC view{reinterpret_cast<std::uintptr_t>(constants), sizeof(frame_constants_by_slot[slot])}; invoke(guest, 17, reinterpret_cast<std::uintptr_t>(&view), cpu); // CreateConstantBufferView const StreamWord table = invoke(heap, 10); if (!table) return 43; + if (reuse) { + const D3D12_CONSTANT_BUFFER_VIEW_DESC filler{reinterpret_cast<std::uintptr_t>(filler_constants), sizeof(filler_constants)}; + invoke(guest, 17, reinterpret_cast<std::uintptr_t>(&filler), cpu + increment); + reuse_heap = heap; + reuse_table = table; + reuse_step = increment; + reuse_guest = guest; + } invoke(list, 32, 1, reinterpret_cast<std::uintptr_t>(&heap)); // SetDescriptorHeaps invoke(list, 36, 0, table); // SetGraphicsRootDescriptorTable invoke(list, 12, 3, 1); // draw into the left half + if (reuse) { + filler_draws(list, 100, 0); // the second half of the frame is recorded by draw_frame_copies_again + return 0; + } + if (wrap) { + const D3D12_RECT none{0, 0, 0, 0}; + invoke(list, 22, 1, reinterpret_cast<std::uintptr_t>(&none)); + for (int i = 0; i < 64; ++i) { + constants[0] = 1.0f; // yellow, a different alpha each time: a fresh copy per draw + constants[1] = 1.0f; + constants[2] = 0.0f; + constants[3] = static_cast<float>(i + 1) / 128.0f; + invoke(list, 12, 3, 1); + } + constants[0] = 0.0f; // green + constants[1] = 1.0f; + constants[2] = 0.0f; + constants[3] = 1.0f; + } if (changed) { constants[0] = 0.0f; // the same address now holds blue constants[2] = 1.0f; @@ -52,3 +130,40 @@ int draw_frame_copies(ID3D12Device* desktop, void* guest, void* list, UINT width invoke(list, 12, 3, 1); // draw into the right half return 0; } + +// reuse, the second list (the caller has executed the first, waited for it, and Reset the list with the target and +// pipeline bound again). +int draw_frame_copies_again(void* list, UINT width, UINT height) +{ + if (!reuse_heap) return 44; + const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(width), static_cast<float>(height), 0, 1}; + invoke(list, 21, 1, reinterpret_cast<std::uintptr_t>(&viewport)); + const D3D12_RECT right{static_cast<LONG>(width / 2), 0, static_cast<LONG>(width), static_cast<LONG>(height)}; + invoke(list, 22, 1, reinterpret_cast<std::uintptr_t>(&right)); + invoke(list, 32, 1, reinterpret_cast<std::uintptr_t>(&reuse_heap)); + invoke(list, 36, 0, reuse_table); // the red constants, unchanged since list A: a frame-copy cache hit + invoke(list, 12, 3, 1); + filler_draws(list, 64, 100); + return 0; +} + +// reuse: the ring counters after the second list, for the check script. +int write_ring_counters() +{ + char path[MAX_PATH]{}; + if (!GetEnvironmentVariableA("X2W_TEST_RING_COUNTERS", path, sizeof(path))) return 0; + HMODULE module = nullptr; + // The module that implements the guest device (its vtable lives there). + if (!reuse_guest || !GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + *static_cast<LPCWSTR*>(reuse_guest), &module)) + return 45; + using Counter = unsigned long long (*)(int); + const auto counter = reinterpret_cast<Counter>(GetProcAddress(module, "x2w_upload_ring_test")); + if (!counter) return 46; + FILE* file = nullptr; + if (fopen_s(&file, path, "w") || !file) return 47; + std::fprintf(file, "reserved=%llu\nchunks=%llu\nmade=%llu\nrepinned=%llu\nstale=%llu\nrefused=%llu\n", counter(0), counter(4), + counter(8), counter(9), counter(5), counter(1)); + std::fclose(file); + return 0; +} diff --git a/tests/startup_frame_copy_check.py b/tests/startup_frame_copy_check.py index 02986af126..d5690c8bc8 100644 --- a/tests/startup_frame_copy_check.py +++ b/tests/startup_frame_copy_check.py @@ -1,4 +1,9 @@ -"""A constant buffer the title rewrites between two draws of one frame reaches the second draw with its new contents.""" +"""A constant buffer the title rewrites between two draws of one frame reaches the second draw with its new contents. + +Upload ring (wrap mode, a 16 KiB test ring): 64 more copies than the ring holds, all in one list, must not overwrite the +first draw's copy (chain, the default); the legacy ring (X2W_UPLOAD_RING=legacy, the negative control) does overwrite it; +a chain capped at 2 chunks refuses the copies past the cap and does not issue the draw that needed one. +""" from pathlib import Path import sys import tempfile @@ -13,16 +18,18 @@ ) RED = bytes((255, 0, 0, 255)) BLUE = bytes((0, 0, 255, 255)) +GREEN = bytes((0, 255, 0, 255)) -def run(directory, consumer, backend, mode): - folder = directory / mode +def run(directory, consumer, backend, mode, name=None, env=None): + folder = directory / (name or mode) folder.mkdir() log = folder / "trap.log" - pixels = draw_texture(folder, consumer, backend, HLSL, {"X2W_TEST_FRAME_COPY": mode, "X2W_TRAP_LOG": str(log)}, + pixels = draw_texture(folder, consumer, backend, HLSL, + {"X2W_TEST_FRAME_COPY": mode, "X2W_TRAP_LOG": str(log), **(env or {})}, binding="srv 0 buf table 0 0") - refreshed = [line for line in log.read_text(errors="replace").splitlines() if "frame copy of" in line] if log.exists() else [] - return pixels, refreshed + lines = log.read_text(errors="replace").splitlines() if log.exists() else [] + return pixels, lines def check(directory, consumer, backend): @@ -32,14 +39,94 @@ def check(directory, consumer, backend): ("same", RED * 8 * 4, 0), # untouched: both draws red, no new copy ) for mode, expected, refreshed_lines in cases: - pixels, refreshed = run(directory, consumer, backend, mode) + pixels, lines = run(directory, consumer, backend, mode) if pixels is None: return 77 + refreshed = [line for line in lines if "frame copy of" in line] if pixels != expected: raise AssertionError(f"{mode}: actual {pixels.hex()} expected {expected.hex()}") if len(refreshed) != refreshed_lines: raise AssertionError(f"{mode}: {len(refreshed)} refresh log lines, expected {refreshed_lines}:\n" + "\n".join(refreshed)) print(f"{backend} {mode}: 32 pixels exact, {refreshed_lines} refresh log lines") + + ring = {"X2W_UPLOAD_RING_TEST_KIB": "16"} + wanted = (RED * 4 + GREEN * 4) * 4 + + def has(lines, text): + return any(text in line for line in lines) + + # Chain (default): the first draw keeps its own bytes although 64 later copies (32 KiB) pass the 16 KiB ring size. + pixels, lines = run(directory, consumer, backend, "wrap", "wrap_chain", ring) + if pixels is None: + return 77 + if pixels != wanted: + raise AssertionError(f"wrap chain: actual {pixels.hex()} expected {wanted.hex()}") + if not has(lines, "x2w-upload ring: chain") or not has(lines, "x2w-upload ring (chain): first copy past the old ring's size"): + raise AssertionError("wrap chain: missing the chain / would-have-wrapped log lines:\n" + "\n".join(l for l in lines if "upload ring" in l)) + print(f"{backend} wrap chain: 32 pixels exact (left red after 64 more copies than the test ring holds); would-have-wrapped logged") + + # Negative control: the legacy ring reuses the first draw's slot before the list has executed. + pixels, lines = run(directory, consumer, backend, "wrap", "wrap_legacy", {**ring, "X2W_UPLOAD_RING": "legacy"}) + if pixels is None: + return 77 + left = b"".join(pixels[row * 32: row * 32 + 16] for row in range(4)) + if left == RED * 16: + raise AssertionError("wrap legacy (negative control): the left half is still red; the control did not trip") + if not has(lines, "x2w-upload ring (legacy): first copy written over ring data the GPU had not read yet"): + raise AssertionError("wrap legacy: no overwrite log line") + print(f"{backend} wrap legacy (negative control): left half {left[:4].hex()} instead of red; overwrite logged") + + # Cap: 2 chunks of 16 KiB hold 64 copies; the rest are refused, and the green draw that needed one is not issued. + pixels, lines = run(directory, consumer, backend, "wrap", "wrap_cap", {**ring, "X2W_UPLOAD_RING_TEST_CAP_CHUNKS": "2"}) + if pixels is None: + return 77 + capped = (RED * 4 + BLUE * 4) * 4 + if pixels != capped: + raise AssertionError(f"wrap cap: actual {pixels.hex()} expected {capped.hex()} (left red, right not drawn)") + if not has(lines, "is free yet; the copy fails") or not has(lines, "not issued at frame"): + raise AssertionError("wrap cap: missing the refusal / draw-not-issued log lines") + print(f"{backend} wrap cap: left red, right not drawn (clear colour); refusal and draw-not-issued logged") + + # Reuse across two submits: list B binds list A's cached red copy (chunk 0, fence passed) again, then 64 fresh + # copies recycle A's chunks. Chunk 0 must be pinned again by that cache hit, so B's red draw reads its own bytes. + def counters(folder): + path = directory / folder / "ring.txt" + if not path.exists(): + raise AssertionError(f"{folder}: no ring counters written") + return {k: int(v) for k, v in (line.split("=") for line in path.read_text().split())} + + def reuse(folder, env): + target = directory / folder / "ring.txt" + return run(directory, consumer, backend, "reuse", folder, {**ring, "X2W_TEST_RING_COUNTERS": str(target), **env}) + + pixels, lines = reuse("reuse_chain", {}) + if pixels is None: + return 77 + c = counters("reuse_chain") + chunk = 16 << 10 + if pixels != RED * 8 * 4: + raise AssertionError(f"reuse chain: actual {pixels.hex()} expected all red; counters {c}") + if c["repinned"] < 1 or not has(lines, "first cached copy bound again from a chunk waiting for its fences"): + raise AssertionError(f"reuse chain: the cache hit did not re-pin a fenced chunk; counters {c}") + if c["reserved"] <= c["made"] * chunk: + raise AssertionError(f"reuse chain: no chunk was recycled (reserved {c['reserved']} bytes in {c['made']} chunks)") + if c["refused"]: + raise AssertionError(f"reuse chain: copies refused; counters {c}") + print(f"{backend} reuse chain: 32 pixels red (the second list's cache hit kept its chunk); {c['reserved'] >> 10} KiB " + f"reserved in {c['made']} chunks of 16 KiB (recycled), re-pinned {c['repinned']}") + + # Negative control: without the re-pin the recycled chunk 0 is overwritten by fillers before list B executes. + pixels, lines = reuse("reuse_norepin", {"X2W_UPLOAD_RING_TEST_NO_REPIN": "1"}) + if pixels is None: + return 77 + c = counters("reuse_norepin") + right = b"".join(pixels[row * 32 + 16: row * 32 + 32] for row in range(4)) + if right == RED * 16: + raise AssertionError(f"reuse no-repin (negative control): the right half is still red; the control did not trip; counters {c}") + if c["repinned"]: + raise AssertionError(f"reuse no-repin: re-pinned {c['repinned']} although the switch is set") + print(f"{backend} reuse no-repin (negative control): right half {right[:4].hex()} instead of red; " + f"{c['reserved'] >> 10} KiB in {c['made']} chunks") return 0 diff --git a/tests/startup_frame_rgb_sample.cpp b/tests/startup_frame_rgb_sample.cpp new file mode 100644 index 0000000000..473e6ff28a --- /dev/null +++ b/tests/startup_frame_rgb_sample.cpp @@ -0,0 +1,70 @@ +#include "startup_stubs/frame_rgb_sample.h" + +#include <windows.h> +#include <d3d12.h> +#include <array> +#include <cstdio> +#include <filesystem> +#include <fstream> +#include <string> +#include <vector> +#include <cstdint> + +static void log(const char*, ...) {} +#include "startup_stubs/frame_rgb_report.inl" + +static bool check_image_file() +{ + namespace fs = std::filesystem; + auto dir = fs::temp_directory_path() / (L"x2w-frame-rgb-" + std::to_wstring(GetCurrentProcessId())); + if (!fs::create_directory(dir)) return false; + auto trap = dir / L"trap.log"; + auto file = dir / L"frame-123-present.pfm"; + if (!SetEnvironmentVariableW(L"X2W_TRAP_LOG", trap.c_str())) return false; + std::array<unsigned char, 768> texture{}; + texture[256] = 255; // top row red, bottom row blue; nonzero footprint offset + texture[512 + 2] = 255; + D3D12_RESOURCE_DESC desc{}; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.Width = 1; + desc.Height = 2; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; + fp.Offset = 256; + fp.Footprint.RowPitch = 256; + report_frame_rgb("present", 123, nullptr, texture.data(), desc, fp); + std::ifstream in(file, std::ios::binary); + std::string magic, dimensions, scale; + std::getline(in, magic); + std::getline(in, dimensions); + std::getline(in, scale); + std::vector<float> rgb(96 * 54 * 3); + in.read(reinterpret_cast<char*>(rgb.data()), rgb.size() * sizeof(float)); + const bool ok = in && magic == "PF" && dimensions == "96 54" && scale == "-1.0" && + rgb[2] == 1 && rgb[0] == 0 && rgb[rgb.size()-3] == 1 && rgb.back() == 0 && + in.peek() == std::ifstream::traits_type::eof(); + in.close(); + fs::remove(file); + fs::remove(dir); + return ok; +} + +int main() +{ + using namespace x2w_frame_sample; + const std::array<std::uint16_t, 4> hdr{0xbc00, 0x0001, 0x4000, 0x3c00}; + auto pixel = decode(reinterpret_cast<const unsigned char*>(hdr.data()), Format::rgba16f); + if (pixel.r != -1 || pixel.g != std::ldexp(1.f, -24) || pixel.b != 2 || pixel.a != 1) return 1; + Counts c; + c.add(pixel); + c.add({0, -0.f, 0, 1}); + c.add({0, 0, 0, 0}); + c.add({NAN, 1, 1, 1}); + if (c.rgb != 1 || c.alpha_only != 1 || c.nonfinite != 1 || c.peak != 2) return 2; + const unsigned char bytes[]{0, 51, 255, 128}; + pixel = decode(bytes, Format::bgra8); + if (pixel.r != 1 || pixel.b != 0 || pixel.g != 51 / 255.f || pixel.a != 128 / 255.f) return 3; + pixel = decode(bytes, Format::rgba8); + if (pixel.r != 0 || pixel.b != 1) return 4; + if (coordinate(3840, 48, 96) != 1940 || coordinate(1, 95, 96) != 0) return 5; + return check_image_file() ? 0 : 6; +} diff --git a/tests/startup_front_face_check.py b/tests/startup_front_face_check.py new file mode 100644 index 0000000000..a3d180b01d --- /dev/null +++ b/tests/startup_front_face_check.py @@ -0,0 +1,126 @@ +"""The SPI input FRONT_FACE (SPI_PS_INPUT_ENA bit 12) in gfx2hlsl pixel stages, draw and mesh pipelines. + + (no arguments) translation controls, pure Python (dxc ps_6_0 compile when M.DXC exists) + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + translate, compile, draw one pixel (the startup_flat_param renderer) + +The VGPR holds +1.0 for a front face and -1.0 for a back face: Mesa nir_intrinsics.py front_face_fsign +"front_face ? 1.0 : -1.0", loaded as the front_face argument itself by ac_nir_lower_intrinsics_to_args.c (and +load_front_face as fgt(arg, 0)). The lowering is U(i.ff ? 1.0 : -1.0) over `bool ff : SV_IsFrontFace` (a pixel +input only, never in the vertex/mesh output), and the manifest says `frontface 1`: which face D3D calls front is the +PSO's FrontCounterClockwise, i.e. the runtime's cull convention, not the translator's. + +Synthetic pixel stage `exp mrt0 vA, vB, vC, vD done vm` (entry reads only). Layouts: ENA 0x1000 (front_face v0), +0x9002 (persp_center v0-v1, front_face v2, pos_fixed_pt v3), 0x1001 (persp_sample v0-v1, front_face v2: per-sample, but front face is not a +position input, so it is taken). +Controls: before the change the read was refused ("front_face ... not lowered"; reproduced by removing bit 12 from +PS_INPUT_HLSL); a pixel stage without the read has no SV_IsFrontFace and no `frontface` line; the mesh stage's +output struct never carries it; ancillary (bit 13) stays refused. The draw checks that the drawn word is +1.0 or +-1.0 and that the inverted expression draws the other one (the input is live, whichever face the renderer draws). +""" +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_mesh_spi_input_check import pixel_words, mesh # noqa: E402 +from startup_image_3d_check import VS_WORDS, root_blob # noqa: E402 + +LINE = ' v%d = U(i.ff ? 1.0 : -1.0); // SPI input front_face' +FIELD = ' bool ff : SV_IsFrontFace;' + + +def draw_pipe(ps, masks): + return G.Pipeline(VS_WORDS, ps, root_blob(), ps_hw_inputs=masks) + + +def refused(build, ps, masks, text): + try: + build(ps, masks).hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (text, str(error)) + return + raise AssertionError('accepted %s' % (masks,)) + + +def controls(): + assert G.ps_input_layout(0x1000, 0x1000) == {0: 12} + assert G.ps_input_layout(0x9002, 0x9002) == {0: 1, 1: 1, 2: 12, 3: 15} + texts = {} + for name, build in (('draw', draw_pipe), ('mesh', mesh)): + pipe = build(pixel_words(0, 0, 0, 0), (0x1000, 0x1000)) + ps = pipe.hlsl_ps() + assert LINE % 0 in ps.split('\n') and FIELD in ps.split('\n'), ps + assert 'frontface 1' in pipe.manifest().split('\n'), pipe.manifest() + texts[name] = ps + both = build(pixel_words(2, 3, 2, 3), (0x9002, 0x9002)).hlsl_ps() + assert LINE % 2 in both.split('\n') and 'v3 = (uint(i.pos.x) & 0xffffu)' in both, both + assert LINE % 2 in build(pixel_words(2, 2, 2, 2), (0x1001, 0x1001)).hlsl_ps() + plain = build(pixel_words(3, 3, 3, 3), (0x9002, 0x9002)) + assert 'SV_IsFrontFace' not in plain.hlsl_ps() and 'frontface' not in plain.manifest(), plain.hlsl_ps() + refused(build, pixel_words(0, 0, 0, 0), (0x2000, 0x2000), 'ancillary (v0) at 0x0: not lowered') + assert 'SV_IsFrontFace' not in draw_pipe(pixel_words(0, 0, 0, 0), (0x1000, 0x1000)).hlsl_vs() + saved = G.PS_INPUT_HLSL.pop(G.FRONT_FACE) + try: + refused(draw_pipe, pixel_words(0, 0, 0, 0), (0x1000, 0x1000), 'front_face (v0) at 0x0: not lowered') + finally: + G.PS_INPUT_HLSL[G.FRONT_FACE] = saved + compiled = 'dxc not found' + if os.path.isfile(M.DXC): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'ps.hlsl') + open(path, 'w').write(texts['mesh']) + r = subprocess.run([M.DXC, '-nologo', '-T', 'ps_6_0', '-E', 'main', '-Fo', path + '.cso', path], + capture_output=True, text=True) + assert r.returncode == 0, r.stderr + compiled = 'dxc ps_6_0 ok' + print('front_face: U(i.ff ? 1.0 : -1.0) over SV_IsFrontFace in draw and mesh pipelines, manifest frontface 1; ' + '%s; controls: refused before, absent when unread, not in the VS, ancillary refused' % compiled) + + +def check_draw(dxc, renderer, adapter, fxc=None): + from startup_flat_param_check import VS_WORDS as FLAT_VS, root_blob as flat_root, compile_hlsl, draw + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + words = {'+1.0': ','.join(['3f800000'] * 4), '-1.0': ','.join(['bf800000'] * 4)} + pipe = G.Pipeline(FLAT_VS, pixel_words(0, 0, 0, 0), flat_root(), ps_hw_inputs=(0x1000, 0x1000)) + good = pipe.hlsl_ps() + inverted = good.replace('i.ff ? 1.0 : -1.0', 'i.ff ? -1.0 : 1.0') + assert inverted != good + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + def build(name, source, profile): + return compile_hlsl(compiler, kind, source, '%s_%s' % (name, kind), profile, directory) + vs = build('vs', pipe.hlsl_vs(), vs_profile) + seen = [] + for label, source in (('translated', good), ('inverted', inverted)): + ps = build('ps_' + label, source, ps_profile) + match = [face for face, expected in words.items() if draw(renderer, adapter, vs, ps, expected).returncode == 0] + if len(match) != 1: + raise AssertionError('%s %s stage drew neither +1.0 nor -1.0' % (kind, label)) + seen.append(match[0]) + print('%s %s stage: every word %s' % (kind, label, match[0]), flush=True) + if seen[0] == seen[1]: + raise AssertionError('%s: the inverted expression drew the same word' % kind) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx10_view_words_check.cpp b/tests/startup_gfx10_view_words_check.cpp new file mode 100644 index 0000000000..72cfcbb203 --- /dev/null +++ b/tests/startup_gfx10_view_words_check.cpp @@ -0,0 +1,233 @@ +// Checks src/startup_stubs/gfx10_view_words.h without a device: buffer view layouts (typed views step by the +// element size), GFX10_FORMAT codes, V# and T# words decoded with an independent field table (bit positions of +// Mesa src/amd/registers/gfx10-rsrc.json), and the view descriptions read from real D3D12 SDK structs. +// --mutate legacy | width | order | uint: the helper's answer replaced the way a wrong helper would answer (the +// old `stride ? stride : 4` layout, the whole width - 1 in word 2, R10G10B10A2 as 10_10_10_2, an R32_FLOAT +// integer UAV); each must fail on the rows it concerns. +#include "startup_stubs/gfx10_view_words.h" + +#include <cstdio> +#include <cstring> + +namespace { +int failures, checks; +const char* mutation = ""; +using namespace x2w_startup; + +void expect(const char* name, unsigned long long got, unsigned long long wanted) +{ + ++checks; + if (got != wanted) { + ++failures; + std::printf("FAIL %s: got 0x%llx (%llu), wanted 0x%llx (%llu)\n", name, got, got, wanted, wanted); + } +} + +std::uint32_t field(const std::uint32_t* w, int word, int lo, int hi) { return (w[word] >> lo) & ((hi - lo == 31) ? ~0u : ((1u << (hi - lo + 1)) - 1)); } + +BufferViewLayout layout(DXGI_FORMAT f, std::uint64_t first, std::uint32_t count, std::uint32_t stride, std::uint32_t flags) +{ + return buffer_view_layout(f, first, count, stride, flags, !std::strcmp(mutation, "legacy")); +} + +void image_words(const ImageViewFacts& v, std::uint32_t w[8], bool* unmapped = nullptr) +{ + gfx10_image_words(v, w, unmapped); + if (!std::strcmp(mutation, "width")) { // a wrong split: all of width - 1 in word 2 + const std::uint32_t width = static_cast<std::uint32_t>(v.width - 1); + w[1] &= ~(3u << 30); + w[2] = (w[2] & ~0xfffu) | (width & 0xfff); + } +} + +std::uint32_t format_code(DXGI_FORMAT f) +{ + if (!std::strcmp(mutation, "order") && f == DXGI_FORMAT_R10G10B10A2_UNORM) return 44; + return gfx10_format(f).code; +} + +void buffers() +{ + // Typed R16_UINT view, FirstElement 3: element 2 bytes, starts at byte 6, 10 elements = 20 bytes. + BufferViewLayout l = layout(DXGI_FORMAT_R16_UINT, 3, 10, 0, 0); + expect("r16 typed kind", static_cast<int>(l.kind), static_cast<int>(BufferViewKind::typed)); + expect("r16 offset", l.offset, 6); + expect("r16 bytes", l.bytes, 20); + expect("r16 index stride", l.index_stride, 2); + expect("r16 format", l.format.code, 11); + // R32G32B32A32_FLOAT typed view: 16-byte elements. + l = layout(DXGI_FORMAT_R32G32B32A32_FLOAT, 2, 4, 0, 0); + expect("rgba32f offset", l.offset, 32); + expect("rgba32f bytes", l.bytes, 64); + expect("rgba32f index stride", l.index_stride, 16); + // R32_UINT typed: the old layout had the right base but index stride 0. + l = layout(DXGI_FORMAT_R32_UINT, 5, 8, 0, 0); + expect("r32u offset", l.offset, 20); + expect("r32u index stride", l.index_stride, 4); + // RAW and structured views keep the old layout. + l = layout(DXGI_FORMAT_R32_TYPELESS, 4, 64, 0, 1); + expect("raw kind", static_cast<int>(l.kind), static_cast<int>(BufferViewKind::raw)); + expect("raw offset", l.offset, 16); + expect("raw bytes", l.bytes, 256); + expect("raw index stride", l.index_stride, 0); + expect("raw num_records (bytes)", l.num_records, 256); + l = buffer_view_layout(DXGI_FORMAT_UNKNOWN, 7, 3, 36, 0); + expect("structured offset", l.offset, 252); + expect("structured index stride", l.index_stride, 36); + expect("structured num_records (elements)", l.num_records, 3); + + // V# of the R16_UINT view: STRIDE [16,29] = 2, NUM_RECORDS = 10, FORMAT [12,18] = 16_UINT, DST_SEL X001. + std::uint32_t w[8]; + gfx10_buffer_words(layout(DXGI_FORMAT_R16_UINT, 3, 10, 0, 0), w); + expect("v# word0 (no address)", w[0], 0); + expect("v# stride", field(w, 1, 16, 29), 2); + expect("v# base hi (no address)", field(w, 1, 0, 15), 0); + expect("v# num_records", w[2], 10); + expect("v# dst_sel_x", field(w, 3, 0, 2), 4); + expect("v# dst_sel_y", field(w, 3, 3, 5), 0); + expect("v# dst_sel_w", field(w, 3, 9, 11), 1); + expect("v# format", field(w, 3, 12, 18), 11); + expect("v# oob_select", field(w, 3, 28, 29), 0); + expect("v# type", field(w, 3, 30, 31), 0); + // Raw view V# as ac_build_raw_buffer_descriptor: 32_FLOAT, XYZW, OOB_SELECT_RAW, NUM_RECORDS in bytes. + gfx10_buffer_words(buffer_view_layout(DXGI_FORMAT_R32_TYPELESS, 0, 64, 0, 1), w); + expect("raw v# stride", field(w, 1, 16, 29), 0); + expect("raw v# num_records", w[2], 256); + expect("raw v# format", field(w, 3, 12, 18), 22); + expect("raw v# dst_sel", field(w, 3, 0, 11), 4 | 5 << 3 | 6 << 6 | 7 << 9); + expect("raw v# oob_select", field(w, 3, 28, 29), 3); + + // The record offsets against the SDK structs. + D3D12_SHADER_RESOURCE_VIEW_DESC s{}; + s.Format = DXGI_FORMAT_R8_UNORM; + s.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + s.Buffer.FirstElement = 9; + s.Buffer.NumElements = 100; + unsigned char bytes[64] = {}; + std::memcpy(bytes, &s, sizeof(s)); + expect("srv desc parsed", buffer_view_layout_from_desc(false, bytes, sizeof(s), l, !std::strcmp(mutation, "legacy")), 1); + expect("srv r8 offset", l.offset, 9); + expect("srv r8 bytes", l.bytes, 100); + D3D12_UNORDERED_ACCESS_VIEW_DESC u{}; + u.Format = DXGI_FORMAT_R32_TYPELESS; + u.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + u.Buffer.FirstElement = 12; + u.Buffer.NumElements = 4; + u.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + std::memset(bytes, 0, sizeof(bytes)); + std::memcpy(bytes, &u, sizeof(u)); + expect("uav desc parsed", buffer_view_layout_from_desc(true, bytes, sizeof(u), l), 1); + expect("uav raw kind", static_cast<int>(l.kind), static_cast<int>(BufferViewKind::raw)); + expect("uav raw offset", l.offset, 48); + u.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; + u.Format = DXGI_FORMAT_R16G16_FLOAT; + std::memcpy(bytes, &u, sizeof(u)); + buffer_view_layout_from_desc(true, bytes, sizeof(u), l, !std::strcmp(mutation, "legacy")); + expect("uav r16g16f index stride", l.index_stride, 4); + expect("uav r16g16f format", l.format.code, 29); +} + +void formats() +{ + expect("R10G10B10A2_UNORM = 2_10_10_10_UNORM", format_code(DXGI_FORMAT_R10G10B10A2_UNORM), 50); + expect("R11G11B10_FLOAT = 10_11_11_FLOAT", format_code(DXGI_FORMAT_R11G11B10_FLOAT), 36); + expect("R8G8B8A8_UNORM", format_code(DXGI_FORMAT_R8G8B8A8_UNORM), 56); + expect("R32_FLOAT", format_code(DXGI_FORMAT_R32_FLOAT), 22); + expect("R16G16B16A16_FLOAT", format_code(DXGI_FORMAT_R16G16B16A16_FLOAT), 71); + expect("BC7_UNORM", format_code(DXGI_FORMAT_BC7_UNORM), 181); + expect("typeless is unmapped", format_code(DXGI_FORMAT_R8G8B8A8_TYPELESS), 0); + expect("B8G8R8A8 swizzle ZYXW", gfx10_format(DXGI_FORMAT_B8G8R8A8_UNORM).dst_sel, 6 | 5 << 3 | 4 << 6 | 7 << 9); +} + +void images() +{ + // 2D 1920x1080, 11 mips, RGBA8 SRV of mips 2..: built from an SDK struct. + D3D12_SHADER_RESOURCE_VIEW_DESC s{}; + s.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + s.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + s.Texture2D.MostDetailedMip = 2; + s.Texture2D.MipLevels = UINT(-1); + unsigned char bytes[64] = {}; + std::memcpy(bytes, &s, sizeof(s)); + ImageViewFacts v{}; + expect("srv texture2d parsed", image_view_from_desc(false, bytes, sizeof(s), v), 1); + v.dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + v.width = 1920; + v.height = 1080; + v.depth_or_array = 1; + v.mip_levels = 11; + std::uint32_t w[8]; + bool unmapped = true; + image_words(v, w, &unmapped); + expect("t# format mapped", unmapped, 0); + const std::uint32_t width = field(w, 1, 30, 31) | field(w, 2, 0, 11) << 2; + expect("t# width - 1 (WIDTH_LO | WIDTH_HI << 2)", width, 1919); + expect("t# height - 1", field(w, 2, 14, 27), 1079); + expect("t# format", field(w, 1, 20, 28), 56); + expect("t# word1 nonzero (null test)", w[1] != 0, 1); + expect("t# base level", field(w, 3, 12, 15), 2); + expect("t# last level", field(w, 3, 16, 19), 10); + expect("t# type 2D", field(w, 3, 28, 31), 9); + expect("t# depth", field(w, 4, 0, 12), 0); + expect("t# max mip", field(w, 5, 4, 7), 10); + expect("t# word0 (no address)", w[0], 0); + expect("t# words 6-7", w[6] | w[7], 0); + // Hand-computed constants for the same view (word1 = 56 << 20 | 3 << 30; word2 = 479 | 1079 << 14). + expect("t# word1 exact", w[1], 0xc3800000u); + expect("t# word2 exact", w[2], 0x010dc1dfu); + + // 2D array UAV, slices 3..6 of 8, mip 1; 3D SRV depth 32. + D3D12_UNORDERED_ACCESS_VIEW_DESC u{}; + u.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + u.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + u.Texture2DArray = {1, 3, 4, 0}; + std::memset(bytes, 0, sizeof(bytes)); + std::memcpy(bytes, &u, sizeof(u)); + v = {}; + expect("uav array parsed", image_view_from_desc(true, bytes, sizeof(u), v), 1); + v.dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + v.width = 512; + v.height = 256; + v.depth_or_array = 8; + v.mip_levels = 4; + image_words(v, w); + expect("array type", field(w, 3, 28, 31), 13); + expect("array base level = last level", field(w, 3, 12, 15) * 16 + field(w, 3, 16, 19), 1 * 16 + 1); + expect("array base_array", field(w, 4, 16, 28), 3); + expect("array depth = last layer", field(w, 4, 0, 12), 6); + v = {}; + v.dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + v.view_dimension = D3D12_SRV_DIMENSION_TEXTURE3D; + v.format = DXGI_FORMAT_R11G11B10_FLOAT; + v.width = 64, v.height = 64, v.depth_or_array = 32, v.mip_levels = 1, v.level_count = UINT(-1); + image_words(v, w); + expect("3d type", field(w, 3, 28, 31), 10); + expect("3d depth - 1", field(w, 4, 0, 12), 31); + expect("3d array pitch (srv)", field(w, 5, 0, 3), 0); + // A view the synthesizer cannot describe yields zeros (the runtime treats it as null). + v.view_dimension = D3D12_SRV_DIMENSION_TEXTURE2D; + expect("2D view of a 3D resource refused", gfx10_image_words(v, w), 0); + expect("refused words zero", w[1] | w[2] | w[3], 0); +} + +void integer_uav() +{ + DXGI_FORMAT got = integer_uav_format(DXGI_FORMAT_R32_TYPELESS); + if (!std::strcmp(mutation, "uint")) got = DXGI_FORMAT_R32_FLOAT; + expect("R32_TYPELESS resource -> R32_UINT UAV", got, DXGI_FORMAT_R32_UINT); + expect("R32_UINT resource -> R32_UINT UAV", integer_uav_format(DXGI_FORMAT_R32_UINT), DXGI_FORMAT_R32_UINT); + expect("R32_FLOAT resource refused", integer_uav_format(DXGI_FORMAT_R32_FLOAT), DXGI_FORMAT_UNKNOWN); + expect("R8G8B8A8_TYPELESS resource refused", integer_uav_format(DXGI_FORMAT_R8G8B8A8_TYPELESS), DXGI_FORMAT_UNKNOWN); +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && !std::strcmp(argv[1], "--mutate")) mutation = argv[2]; + buffers(); + formats(); + images(); + integer_uav(); + std::printf("startup_gfx10_view_words%s%s: %d checks, %d failures\n", *mutation ? " --mutate " : "", mutation, checks, failures); + return failures ? 1 : 0; +} diff --git a/tests/startup_gfx2hlsl_bit_alu_check.py b/tests/startup_gfx2hlsl_bit_alu_check.py index 75f4e5e2a4..71a21de21c 100644 --- a/tests/startup_gfx2hlsl_bit_alu_check.py +++ b/tests/startup_gfx2hlsl_bit_alu_check.py @@ -334,7 +334,29 @@ def refused(assembly): return False +def check_scalar_flbit(): + _, _, name, asm = G.decode(bytes.fromhex('001582be'))[0] + assert asm == 's_flbit_i32_b32 s2, s0' + stage = Probe() + stage.masks = set() + stage.one(name, asm) + assert len(stage.lines) == 1 and stage.lines[0].startswith('s2 = '), stage.lines + expr = Expr(stage.lines[0][5:-1]) + for value in BITS: + expected = 32 - value.bit_length() if value else MASK + assert expr.run({'s0': value})[0] == expected, hex(value) + stage.masks.add(3) + for src in ('exec_lo', 'vcc', 's3', 'v1', 's[8:9]'): + try: + stage.one(name, name + ' s2, ' + src) + except G.Unsupported: + continue + raise AssertionError(src) + print('scalar flbit: unsigned leading zeros, zero sentinel, unchanged SCC and whole-word checks pass') + + def controls(): + check_scalar_flbit() for op in OPS: pipe, text = translate(op) check('%s: %d inputs match the reference (e32 and e64 lanes)' % (op, len(GRID[op])), diff --git a/tests/startup_gfx2hlsl_coverage_check.py b/tests/startup_gfx2hlsl_coverage_check.py new file mode 100644 index 0000000000..245e1a9337 --- /dev/null +++ b/tests/startup_gfx2hlsl_coverage_check.py @@ -0,0 +1,687 @@ +"""Lowerings added to tools/startup/gfx2hlsl.py for the startup pipeline requests, pure Python. + +Each case hand-encodes gfx1013 words (no title data), checks the shared disassembler prints the form the lowering +parses, and checks the translated statement. The integer helpers (64-bit shifts, the high word of a product and the +IEEE class of a binary32 or binary16 value) are evaluated by the integer HLSL evaluator of +startup_gfx2hlsl_bit_alu_check over edge grids and compared with references written from the ISA description with +Python integers and struct, not with the lowering's own expressions. Each lowering also has refusal controls for the +forms it does not prove. + +Semantics sources: LLVM AMDGPU (SIDefines.h ClassFlags, llvm.amdgcn.class(value, mask); GCNSubtarget +zeroesHigh16BitsOfDest for the gfx10 16-bit results; SIFoldOperands "Clamp is applied after omod"; +ConstantFoldAMDGCNCubeIntrinsic for v_cube*; SIInstrInfo s_and/s_cmp -> s_bitcmp folds; SOPInstructions.td for +the s_lshlN_add / s_abs / s_pack_ll patterns and which scalar ops define SCC; SIShrinkInstructions for the signed +SOPK immediate; AMDGPUISelDAGToDAG SelectVOP3PMadMixModsImpl and VOP3PInstructions.td VOP3P_Mix_Profile for the +mix operands; SIISelLowering packImage16bitOpsToDwords for a16) and Mesa main 13ebbc00 (ACO selection of +pack_[us]norm_2x16 to v_cvt_pknorm_*, nir_constant_expressions pack_[us]norm_1x16, util/macros.h CLAMP). +""" +import math +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_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +failures = [] + + +def check(label, ok): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + failures.append(label) + + +class FakePipe: + """The pipeline services one stage needs: resources, samplers, entry constants and the render-target kinds.""" + root = {'params': [{'type': 0}], 'flags': 0} + sampler_heap = False + uses_sampler_heap = False + ps_float_mode = 0xc0 # the pixel stage's launch FLOAT_MODE (a .psin third field 000000c0): MODE 0 rounding + + def __init__(self): + self.resources, self.samplers, self.modified, self.notes = {}, {}, set(), set() + + def resource(self, key, kind): + r = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) + assert r['kind'] == kind + return 'r%d' % r['index'] + + def sampler(self, key, comparison=False): + return 'q%d' % self.samplers.setdefault(key, len(self.samplers)) + + def ud(self, source): + return 0 + + def mrt_kind(self, slot): + return 'float' + + +def words_bytes(words): + return struct.pack('<%dI' % len(words), *words) + + +def stage(words, kind='ps'): + """Translate a whole program (s_endpgm appended).""" + return G.Stage(FakePipe(), kind, words_bytes(list(words) + [0xbf810000])) + + +def asm_of(words): + return G.decode(words_bytes(words))[0][3] + + +def lines(words, kind='ps', setup=None): + """Translate one instruction on a fresh stage after an optional setup(stage); returns its statements.""" + s = stage([], kind) + if setup: + setup(s) + s.lines = [] + _, n, name, asm = G.decode(words_bytes(words))[0] + s.pc = 0 + s.one(name, asm) + return s, '\n'.join(s.lines) + + +def refused(asm, kind='ps', setup=None, words=None): + s = stage([], kind) + if setup: + setup(s) + try: + if words is not None: + _, n, name, asm = G.decode(words_bytes(words))[0] + else: + name = asm.split(' ', 1)[0] + s.one(name, asm) + except G.Unsupported: + return True + return False + + +def helper_expr(name): + text = G.HELPERS[name] + return Expr(text[text.index('return ') + 7:text.rindex(';')]) + + +# ---- exports ------------------------------------------------------------------------------------- +def exports(): + w = [0xf8000000 | 0x3 | 1 << 10 | 1 << 11 | 1 << 12, 0x00000100] + check('exp compr with the zw pair off prints as v0, v0, off, off', asm_of(w) == 'exp mrt0 v0, v0, off, off done compr vm') + s, text = lines(w) + check(' x, y from the halves of v0; z, w read 0', 'o.mrt0 = float4(f16tof32(v0), f16tof32(v0 >> 16), 0.0, 0.0);' in text) + w = [0xf8000000 | 0xc | 1 << 10 | 1 << 11, 0x00000100] + check('exp compr with the xy pair off prints as off, off, v1, v1', asm_of(w) == 'exp mrt0 off, off, v1, v1 done compr') + check(' z, w from the halves of v1', 'float4(0.0, 0.0, f16tof32(v1), f16tof32(v1 >> 16))' in lines(w)[1]) + check('exp compr with an unpaired enable mask refused', + refused(None, words=[0xf8000000 | 0x1 | 1 << 10 | 1 << 11, 0x00000100])) + w = [0xf8000000 | 0x1 | 8 << 4 | 1 << 11 | 1 << 12, 5] + check('exp mrtz depth alone', asm_of(w) == 'exp mrtz v5, off, off, off done vm' and 'o.depth = F(v5);' in lines(w)[1]) + check('exp mrtz with stencil refused', refused(None, words=[0xf8000000 | 0x3 | 8 << 4 | 1 << 11, 0x0605])) + check('exp mrtz in a vertex stage refused', refused(None, 'vs', words=w)) + w = [0xf8000000 | 9 << 4 | 1 << 11 | 1 << 12, 0] + check('exp null with no data is a no-op', asm_of(w) == 'exp null off, off, off, off done vm' and lines(w)[1] == '') + check('exp null with data refused', refused(None, words=[0xf8000000 | 0x1 | 9 << 4 | 1 << 11, 0])) + # A whole pixel stage that exports depth and colour declares SV_Depth next to SV_Target0. + pipe = G.Pipeline.__new__(G.Pipeline) + pipe.rtv_formats = () + pipe.packed_position_vgpr = None # set by Pipeline.__init__ since upstream #1634 + pipe.resources, pipe.samplers, pipe.uds, pipe.uses_sampler_heap, pipe.helper_text = {}, {}, [], False, None + pipe.vs = pipe.ps = None + pipe.root = FakePipe.root + pipe.ps = G.Stage(pipe, 'ps', words_bytes([0xf8000000 | 0x1 | 8 << 4, 1, 0xf8000000 | 0xf | 1 << 11 | 1 << 12, 0x03020100, + 0xbf810000])) + pipe.vs = pipe.ps + pipe.params, pipe.flat = [], [] + text = pipe.hlsl_ps() + check('depth and colour: SV_Depth and SV_Target0 declared', + 'float depth : SV_Depth;' in text and 'float4 mrt0 : SV_Target0;' in text and 'o.depth = F(v1);' in text) + + +# ---- output modifiers ------------------------------------------------------------------------------ +def output_modifiers(): + w = [0xd4000000 | 0x185 << 16, 256 | 1 << 27] + check('v_cvt_f32_i32 omod prints mul:2', asm_of(w) == 'v_cvt_f32_i32_e64 v0, v0 mul:2') + # Upstream #1707 (VEC_U_TO_F) scales the float value directly, without the U()/F() round trip. + check(' the converted value is doubled', 'v0 = U((float(int(v0))) * 2.0);' in lines(w)[1]) + check('omod on an integer result refused', refused('v_add_nc_u32_e64 v0, v0, v1 mul:2')) + check('clamp on an integer result refused', refused('v_add_nc_u32_e64 v0, v0, v1 clamp')) + w = [0xd4000000 | 0x14b << 16 | 1 << 15 | 1, 258 | 259 << 9 | 0xf2 << 18 | 3 << 27 | 1 << 29] + check('v_fma_f32 clamp div:2 printed with clamp first', asm_of(w) == 'v_fma_f32 v1, -v2, v3, 1.0 clamp div:2') + check(' the clamp applies after the output modifier', + 'v1 = U(saturate((x2w_fma_exact((-F(v2)), F(v3), 1.0)) * 0.5));' in lines(w)[1]) # fused: X2W_DRAW_FMA exact + + +# ---- bit-exact selects and 16-bit results --------------------------------------------------------------- +def selects_and_halves(): + w = [0xd4000000 | 0x101 << 16 | 31, 286 | 286 << 9 | 106 << 18 | 2 << 29] + check('v_cndmask_b32 with -v30 prints the modifier', asm_of(w) == 'v_cndmask_b32_e64 v31, v30, -v30, vcc_lo') + check(' negation flips the sign bit of the selected word', 'v31 = (vcc & 1) ? (v30 ^ 0x80000000u) : v30;' in lines(w)[1]) + w = [0xd4000000 | 0x101 << 16 | 2 << 8 | 3, 259 | 260 << 9 | 106 << 18] + check(' abs clears it', 'v3 = (vcc & 1) ? (v4 & 0x7fffffffu) : v3;' in lines(w)[1]) + w = [0x3a << 25 | 21 << 17 | 21 << 9 | 0xff, 0x7bff] + check('v_min_f16 keeps D[31:16] (gfx10)', asm_of(w) == 'v_min_f16_e32 v21, 0x7bff, v21' and + 'v21 = (v21 & 0xffff0000u) | f32tof16(min(f16tof32(0x00007bffu), f16tof32(v21)));' in lines(w)[1]) + w = [0x39 << 25 | 21 << 17 | 21 << 9 | 0xf2] + check('v_max_f16 takes inline 1.0 in half form', asm_of(w) == 'v_max_f16_e32 v21, 1.0, v21' and + 'f16tof32(0x3c00u)' in lines(w)[1]) + check('v_min_f16 with clamp refused', refused('v_min_f16_e64 v1, v2, v3 clamp')) + check('v_min_f16 with a negated source refused', refused('v_min_f16_e64 v1, -v2, v3')) + w = [0x7e000000 | 5 << 17 | 0xa << 9 | 262] + check('v_cvt_f16_f32 keeps D[31:16] (gfx10)', asm_of(w) == 'v_cvt_f16_f32_e32 v5, v6' and + 'v5 = (v5 & 0xffff0000u) | x2w_f32tof16_rne(F(v6));' in lines(w)[1]) + w = [0xcc000000 | 0x11 << 16 | 1 << 14 | 3, 259 | 0xff << 9 | 1 << 27, 0x7bef] + check('v_pk_min_f16 op_sel_hi:[1,0] prints', asm_of(w) == 'v_pk_min_f16 v3, v3, 0x7bef op_sel_hi:[1,0]') + check(' low from both low halves, high from v3.hi and the literal low half', + lines(w)[1] == 'v3 = f32tof16(min(f16tof32(v3), f16tof32(0x00007befu))) | ' + '(f32tof16(min(f16tof32(v3 >> 16), f16tof32(0x00007befu))) << 16);') + check('v_pk_min_f16 reading a literal high half refused', + refused(None, words=[0xcc000000 | 0x11 << 16 | 1 << 14 | 3, 259 | 0xff << 9 | 3 << 27, 0x7bef])) + check('v_pk_min_f16 with neg_lo refused', refused('v_pk_min_f16 v3, v3, v4 neg_lo:[1,0]')) + + +# ---- integer helpers ---------------------------------------------------------------------------------- +EDGES = [0, 1, 2, 3, 0x7fff, 0x8000, 0xffff, 0x10000, 0x12345678, 0x7fffffff, 0x80000000, 0x80000001, 0xaaaaaaab, + 0xdeadbeef, 0xfffeffff, 0xffff0000, 0xfffffffe, MASK] + + +def integer_helpers(): + e = helper_expr('x2w_mul_hi_u32') + bad = [(a, b) for a in EDGES for b in EDGES if e.run({'a': a, 'b': b})[0] != (a * b) >> 32] + check('x2w_mul_hi_u32 matches (a * b) >> 32 on %d pairs' % len(EDGES) ** 2, not bad) + w = [0xd4000000 | 0x16a << 16 | 1, 256 | 0xff << 9, 0xaaaaaaab] + check('v_mul_hi_u32 lowers to the helper', asm_of(w) == 'v_mul_hi_u32 v1, v0, 0xaaaaaaab' and + 'v1 = x2w_mul_hi_u32(v0, 0xaaaaaaabu);' in lines(w)[1]) + pairs = [(l, h) for l in (0, 1, 0x80000000, 0x12345678, MASK) for h in (0, 1, 0x80000000, 0xdeadbeef, MASK)] + for helper, ref in (('x2w_lshr64', lambda v, n: v >> n), ('x2w_lshl64', lambda v, n: (v << n) & (2 ** 64 - 1))): + lo, hi = helper_expr(helper + '_lo'), helper_expr(helper + '_hi') + bad = [] + for l, h in pairs: + for n in list(range(64)) + [64, 65, 95, 0xffffffc1]: + want = ref(h << 32 | l, n & 63) + env = {'l': l, 'h': h, 'n': n} + if (lo.run(env)[0], hi.run(env)[0]) != (want & MASK, want >> 32): + bad.append((l, h, n)) + check('%s matches the 64-bit reference for counts 0..63 and wrapped counts' % helper, not bad) + w = [0xd4000000 | 0x300 << 16 | 10, 0x80 | 0x80 << 9] + check('v_lshrrev_b64 v[10:11], 0, 0', asm_of(w) == 'v_lshrrev_b64 v[10:11], 0, 0' and + 'q = uint2(x2w_lshr64_lo(0x00000000u, 0x00000000u, 0x00000000u), ' + 'x2w_lshr64_hi(0x00000000u, 0x00000000u, 0x00000000u));\nv10 = q.x;\nv11 = q.y;' in lines(w)[1]) + w = [0xd4000000 | 0x2ff << 16 | 2, 257 | 258 << 9] + check('v_lshlrev_b64 v[2:3], v1, v[2:3] reads both words before writing', + lines(w)[1] == 'q = uint2(x2w_lshl64_lo(v2, v3, v1), x2w_lshl64_hi(v2, v3, v1));\nv2 = q.x;\nv3 = q.y;') + check('a negative inline 64-bit constant is sign-extended', + 'x2w_lshr64_lo(0xffffffffu, 0xffffffffu, v1)' in lines([0xd4000000 | 0x300 << 16 | 10, 257 | 0xc1 << 9])[1]) + # A 32-bit literal in a 64-bit integer operand: only bit 31 decides zero- vs sign-extension, so a literal + # with bit 31 set stays refused and one with bit 31 clear reads a zero high dword (startup_lit64_check.py). + # An unsigned 64-bit shift zero-extends its literal (startup_gfx2hlsl_shift64_literal_check.py, which also keeps + # the default 64-bit operand rule: bit 31 set refused). + check('v_lshrrev_b64 zero-extends a literal with bit 31 set', not refused('v_lshrrev_b64 v[10:11], v1, 0x92345678')) + check('a 64-bit literal operand with bit 31 clear has a zero high dword', + not refused('v_lshrrev_b64 v[10:11], v1, 0x12345678')) + w = [0xbf000000 | 0xd << 16 | 0x81 << 8 | 11] + s, text = lines(w) + check('s_bitcmp1_b32 s11, 1 sets SCC from bit 1', asm_of(w) == 's_bitcmp1_b32 s11, 1' and + text == 'scc = ((s11 >> (0x00000001u & 31u)) & 1u) == 1u;') + e = Expr(text[len('scc = '):-1].replace('s11', 'x')) + check(' SCC is S0[S1[4:0]] for every bit', all(e.run({'x': x})[0] == (x >> 1) & 1 for x in EDGES)) + check('s_bitcmp0_b32 tests for zero', 'scc = ((s3 >> (s4 & 31u)) & 1u) == 0u;' in lines([0xbf000000 | 0xc << 16 | 4 << 8 | 3])[1]) + w = [0x80000000 | 0x25 << 23 | 44 << 16 | (0x80 + 54) << 8 | 0x82] + s, text = lines(w) + check('s_bfm_b64 s[44:45], 2, 54 folds to 0x00c00000:00000000', asm_of(w) == 's_bfm_b64 s[44:45], 2, 54' and + s.sym.get(44) == ('const', 0) and s.sym.get(45) == ('const', 0x00c00000)) + check('s_bfm_b64 with a run-time count refused', refused('s_bfm_b64 s[4:5], s6, 0')) + + +def ref_class(x, half): + """IEEE class bit (SIDefines.h ClassFlags order) of a binary32 or binary16 pattern.""" + if half: + x &= 0xffff + value, quiet, sign, tiny = struct.unpack('<e', struct.pack('<H', x))[0], x >> 9 & 1, x >> 15, 2.0 ** -14 + else: + value, quiet, sign, tiny = struct.unpack('<f', struct.pack('<I', x))[0], x >> 22 & 1, x >> 31, 2.0 ** -126 + if math.isnan(value): + return 1 if quiet else 0 + if math.isinf(value): + return 2 if sign else 9 + if value == 0: + return 5 if sign else 6 + if abs(value) >= tiny: + return 3 if sign else 8 + return 4 if sign else 7 + + +CLASS32 = [0, 0x80000000, 1, 0x80000001, 0x007fffff, 0x807fffff, 0x00800000, 0x80800000, 0x3f800000, 0xbf800000, + 0x7f7fffff, 0xff7fffff, 0x7f800000, 0xff800000, 0x7f800001, 0xff800001, 0x7fbfffff, 0x7fc00000, 0xffc00000, + MASK, 0x7fffffff] +CLASS16 = [0, 0x8000, 1, 0x8001, 0x3ff, 0x83ff, 0x400, 0x8400, 0x3c00, 0xbc00, 0x7bff, 0xfbff, 0x7c00, 0xfc00, 0x7c01, + 0xfc01, 0x7dff, 0x7e00, 0xfe00, 0xffff, 0x7fff, 0x12340000 | 0x7c01] + + +def classes(): + for name, grid, half in (('x2w_class_f32', CLASS32, False), ('x2w_class_f16', CLASS16, True)): + e = helper_expr(name) + bad = [(x, bit) for x in grid for bit in range(10) + if e.run({'x': x, 'mask': 1 << bit})[0] != int(ref_class(x, half) == bit)] + bad += [x for x in grid if e.run({'x': x, 'mask': 0xfffffc00})[0]] # mask bits above 9 never match + check('%s matches the IEEE class of %d patterns for every mask bit' % (name, len(grid)), not bad) + w = [0x7c000000 | 0x88 << 17 | 0xc1] + check('v_cmp_class_f32 vcc_lo, -1, v0: value -1, mask v0', asm_of(w) == 'v_cmp_class_f32_e32 vcc_lo, -1, v0' and + 'vcc = x2w_class_f32(0xffffffffu, v0);' in lines(w)[1]) + w = [0x7c000000 | 0x8f << 17 | 0xff, 0x7c01] + check('v_cmp_class_f16 with a literal value', asm_of(w) == 'v_cmp_class_f16_e32 vcc_lo, 0x7c01, v0' and + 'vcc = x2w_class_f16(0x00007c01u, v0);' in lines(w)[1]) + w = [0xd4000000 | 0x88 << 16 | 32, 0xc1 | 260 << 9] + s, text = lines(w) + check('v_cmp_class_f32_e64 writes an SGPR mask', 's32 = x2w_class_f32(0xffffffffu, v4);' in text and 32 in s.masks) + check(' -|v| sets the f32 sign bit', '((v2 & 0x7fffffffu) ^ 0x80000000u)' in lines([0xd4000000 | 0x88 << 16 | 1 << 8 | 32, + 258 | 260 << 9 | 1 << 29])[1]) + check('v_cmpx_class_f32 writes exec', 'exec = x2w_class_f32(v1, v2);' in lines([0x7c000000 | 0x98 << 17 | 2 << 9 | 257])[1]) + check('v_cmp_lt_f16 lowers (startup_gfx2hlsl_f16_arith_check.py)', not refused('v_cmp_lt_f16_e32 vcc_lo, v1, v2')) + + +# ---- cube-map face selection --------------------------------------------------------------------------- +def ref_cube(s0, s1, s2): + """(id, sc, tc, ma) as LLVM's ConstantFoldAMDGCNCubeIntrinsic computes them.""" + def negative(x): + return math.copysign(1.0, x) < 0 and x != 0 and not math.isnan(x) + if abs(s2) >= abs(s0) and abs(s2) >= abs(s1): + face, sc, tc, ma = (5, -s0, -s1, s2) if negative(s2) else (4, s0, -s1, s2) + elif abs(s1) >= abs(s0): + face, sc, tc, ma = (3, s0, -s2, s1) if negative(s1) else (2, s0, s2, s1) + else: + face, sc, tc, ma = (1, s2, -s1, s0) if negative(s0) else (0, -s2, -s1, s0) + return float(face), sc, tc, ma + ma + + +def cube_helper(): + """The HLSL of x2w_cube as a Python function: if/return statements, ternaries on 'x < 0.0', float4 tuples.""" + text = G.HELPERS['x2w_cube'] + body = text[text.index('{') + 1:text.rindex('}')] + body = re.sub(r'(\w) < 0\.0 \? ([^,]+?) : ([^,)]+)', r'(\2 if \1 < 0.0 else \3)', body) + body = body.replace('&&', 'and').replace('float4(', '(') + source = 'def cube(a, b, c):\n' + for statement in filter(None, (s.strip() for s in body.split(';'))): + if statement.startswith('if'): + cond, ret = re.fullmatch(r'if \((.*)\) (return .*)', statement).groups() + source += ' if %s:\n %s\n' % (cond, ret) + else: + source += ' %s\n' % statement + space = {} + exec(source, space) + return space['cube'] + + +def cubes(): + cube = cube_helper() + values = [0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 2.0, -2.0, 3.0, float('inf'), float('-inf'), float('nan')] + bad = [] + for a in values: + for b in values: + for c in values: + got, want = cube(a, b, c), ref_cube(a, b, c) + if any(not (x == y or (math.isnan(x) and math.isnan(y))) or math.copysign(1, x) != math.copysign(1, y) + for x, y in zip(got, want)): + bad.append((a, b, c, got, want)) + check('x2w_cube matches LLVM cube folding on %d inputs (ties, -0, inf, NaN)' % len(values) ** 3, not bad) + s, text = lines([0xd4000000 | 0x147 << 16 | 23, 276 | 278 << 9 | 274 << 18]) + check('v_cubema_f32 lowers to x2w_cube(...).w', text == 'v23 = U(x2w_cube(F(v20), F(v22), F(v18)).w);') + + +# ---- image_gather4_lz and the typed 16x4 float fetch --------------------------------------------------------- +def gather_setup(s): + for i in range(8): + s.sym[24 + i] = ('desc', ('table', 0), 0x40, i) + for i in range(4): + s.sym[16 + i] = ('const', 0x100 * (i + 1)) + + +def gather(): + base = 0xf0000000 | (0x47 & 0x7f) << 18 | 1 << 3 + w1 = 2 | 8 << 8 | (24 // 4) << 16 | (16 // 4) << 21 + for dmask, channel in ((1, 'Red'), (2, 'Green'), (4, 'Blue'), (8, 'Alpha')): + w = [base | dmask << 8, w1] + _, text = lines(w, setup=gather_setup) + check('image_gather4_lz dmask %#x reads Gather%s into four VGPRs' % (dmask, channel), + 'dmask:0x%x dim:SQ_RSRC_IMG_2D' % dmask in asm_of(w) and + text == 't = r0.Gather%s(q0, float2(F(v2), F(v3)));\nv8 = U(t.x);\nv9 = U(t.y);\nv10 = U(t.z);\nv11 = U(t.w);' % channel) + check('image_gather4_lz with two channels refused', refused(None, setup=gather_setup, words=[base | 3 << 8, w1])) + check('image_gather4_lz tfe refused', refused(None, setup=gather_setup, words=[base | 2 << 8 | 1 << 16, w1])) + check('image_gather4_lz d16 refused', refused(None, setup=gather_setup, words=[base | 2 << 8, w1 | 1 << 31])) + check('image_gather4_lz on a 2D array refused', + refused(None, setup=gather_setup, words=[(base & ~(7 << 3)) | 5 << 3 | 2 << 8, w1])) + check('image_gather4 (implicit level) still refused', refused(None, setup=gather_setup, + words=[0xf0000000 | (0x40 & 0x7f) << 18 | 1 << 3 | 1 << 8, w1])) + + +def typed_fetch(): + def setup(s): + for i in range(4): + s.sym[20 + i] = ('desc', ('table', 0), 0x80, i) + s = stage([]) + setup(s) + s.lines = [] + s.one('tbuffer_load_format_xyzw', 'tbuffer_load_format_xyzw v[0:3], v4, s[20:23], 0 format:[BUF_FMT_16_16_16_16_FLOAT] offen') + text = '\n'.join(s.lines) + check('BUF_FMT_16_16_16_16_FLOAT: four halves from two dwords', + text == 'a = v4 + 0;\nw = ldu(r0, a);\nv0 = U(f16tof32(w));\nv1 = U(f16tof32(w >> 16));\n' + 'v2 = U(f16tof32(ldu(r0, a + 4)));\nv3 = U(f16tof32(ldu(r0, a + 4) >> 16));') + + +# ---- control-flow joins --------------------------------------------------------------------------------- +JOIN = [0xf4000000 | 2 << 18 | 12 << 6 | 4, 125 << 25 | 0x20, # s_load_dwordx4 s[12:15], s[8:9], 0x20 + 0xbf000000 | 6 << 16 | 0x80 << 8 | 20, # s_cmp_eq_u32 s20, 0 + 0xbf840000 | 3, # s_cbranch_scc0 +0x1c + 0xf4000000 | 0xa << 18 | 12 << 6 | 6, 125 << 25 | 0x50, # s_buffer_load_dwordx4 s[12:15], s[12:15], 0x50 + 0xbf820000 | 2, # s_branch +0x24 + 0xf4000000 | 8 << 18 | 16 << 6 | 6, 125 << 25 | 0x10] # s_buffer_load_dword s16, s[12:15], 0x10 + + +def joins(): + s = stage(JOIN) + text = '\n'.join(line for block in s.blocks for line in block[1]) + check('a branch target reached only by the branch keeps the descriptor the branch saw', + 's16 = r0.Load(0x00000010u + 0);' in text and s.pipe.resources == {(('table', 0), 0x20): dict(index=0, kind='buf')}) + fall = JOIN[:6] + [0xbf800000] + JOIN[7:] # s_nop instead of s_branch: the clobbered path falls through + try: + stage(fall) + except G.Unsupported as error: + check('a join of a descriptor and a loaded word refused (%s)' % error, 'conflict' in str(error)) + else: + check('a join of a descriptor and a loaded word refused', False) + + +# ---- v_cvt_pknorm_{u16,i16}_f32 --------------------------------------------------------------------------- +def f32(x): + return struct.unpack('<f', struct.pack('<f', x))[0] + + +def roundeven(x): + # Python's round() on a float is round-half-to-even, like _mesa_roundevenf and HLSL round() + return float(round(x)) + + +def ref_pknorm(x, signed_form): + """Mesa main 13ebbc00: nir_constant_expressions.py pack_[us]norm_1x16 with util/macros.h CLAMP. + + (uint16_t)(int)_mesa_roundevenf(CLAMP(x, lo, 1.0f) * K), with CLAMP(X, MIN, MAX) = X > MIN ? (X > MAX ? MAX : X) + : MIN, so NaN takes MIN; the product is a binary32 multiply. + """ + lo, scale = (-1.0, 32767.0) if signed_form else (0.0, 65535.0) + clamped = (1.0 if x > 1.0 else x) if x > lo else lo + return int(roundeven(f32(clamped * scale))) & 0xffff + + +def pknorm_helper(name): + """The HLSL of x2w_pknorm_[ui]16 as a Python function over a binary32 value (the bits come in as a float).""" + text = G.HELPERS[name] + body = text[text.index('{') + 1:text.rindex('}')] + body = re.sub(r'\b(0x[0-9a-f]+|\d+)u\b', r'\1', body) + body = re.sub(r'round\((.*) \* ([\d.]+)\)', r'rne(f32(\1 * \2))', body) + source = 'def helper(x):\n' + for statement in filter(None, (s.strip() for s in body.split(';'))): + m = re.fullmatch(r'if \((.*)\) (return .*)', statement) + source += (' if %s:\n %s\n' % m.groups()) if m else ' %s\n' % statement + space = dict(asuint=lambda v: struct.unpack('<I', struct.pack('<f', v))[0], f32=f32, rne=roundeven, + clamp=lambda v, lo, hi: min(max(v, lo), hi), uint=lambda v: int(v) & MASK, int=int) + exec(source, space) + return space['helper'] + + +def pknorm(): + def bits(b): + return struct.unpack('<f', struct.pack('<I', b))[0] + nans = [float('nan'), -float('nan'), bits(0x7f800001), bits(0xffc00000)] + values = nans + [0.0, -0.0, 1.0, -1.0, 2.0, -2.0, 1e30, -1e30, float('inf'), float('-inf'), 0.5, -0.5, 0.25, + bits(1), bits(0x80000001), f32(1.5 / 65535), f32(2.5 / 65535), f32(-1.5 / 32767), f32(0.5 / 32767), + f32(1 - 2 ** -24), f32(-1 + 2 ** -24), 0.1, -0.1, 0.999, -0.999] + values += [f32(i / 1000.0 - 1.2) for i in range(2401)] + for name, signed_form in (('x2w_pknorm_u16', False), ('x2w_pknorm_i16', True)): + helper = pknorm_helper(name) + bad = [(x, helper(x), ref_pknorm(x, signed_form)) for x in values if helper(x) != ref_pknorm(x, signed_form)] + check('%s matches Mesa pack_%snorm_1x16 on %d inputs (NaN, +-0, ties, out of range)%s' + % (name, 's' if signed_form else 'u', len(values), (' first %r' % (bad[0],)) if bad else ''), not bad) + check('NaN packs as Mesa clamps it: unorm 0, snorm -32767', + pknorm_helper('x2w_pknorm_u16')(nans[0]) == 0 and pknorm_helper('x2w_pknorm_i16')(nans[0]) == 0x8001) + check('ties round to even: unorm 0.5 -> 32768, snorm 0.5 -> 16384', + pknorm_helper('x2w_pknorm_u16')(0.5) == 32768 and pknorm_helper('x2w_pknorm_i16')(0.5) == 16384) + vop3 = lambda op, extra=0, w1extra=0: [0xd4000000 | op << 16 | extra | 7, (256 + 7) | (256 + 4) << 9 | w1extra] + w = vop3(0x369) + _, text = lines(w) + check('v_cvt_pknorm_u16_f32: S0 in the low half, S1 in the high half', + asm_of(w) == 'v_cvt_pknorm_u16_f32 v7, v7, v4' and + text == 'v7 = x2w_pknorm_u16(F(v7)) | (x2w_pknorm_u16(F(v4)) << 16);') + w = vop3(0x368, w1extra=1 << 29) + _, text = lines(w) + check('v_cvt_pknorm_i16_f32 applies the source neg before packing', + asm_of(w) == 'v_cvt_pknorm_i16_f32 v7, -v7, v4' and + text == 'v7 = x2w_pknorm_i16((-F(v7))) | (x2w_pknorm_i16(F(v4)) << 16);') + check('v_cvt_pknorm_u16_f32 clamp refused', refused(None, words=vop3(0x369, 1 << 15))) + check('v_cvt_pknorm_u16_f32 omod refused', refused(None, words=vop3(0x369, 0, 1 << 27))) + + +# ---- scalar ALU: shift-add, abs, SOPK arithmetic, pack, and the SCC liveness check ------------------------- +SOP2 = lambda op, d, a, b: 0x80000000 | op << 23 | d << 16 | b << 8 | a +LSHL2_ADD = SOP2(0x2f, 20, 21, 22) # s_lshl2_add_u32 s20, s21, s22 +CSELECT = SOP2(0x0a, 23, 20, 21) # s_cselect_b32 s23, s20, s21 (reads SCC) +CMP_EQ = 0xbf000000 | 6 << 16 | 21 << 8 | 20 # s_cmp_eq_u32 s20, s21 (writes SCC) +NOP = 0xbf800000 +SOPP = lambda op, n: 0xbf800000 | op << 16 | (n & 0xffff) # s_branch 2, s_cbranch_scc1 5, vccz 6, vccnz 7 + + +class SignedExpr(Expr): + """Expr plus the signed max of s_abs_i32's lowering.""" + @staticmethod + def call(name, args): + if name == 'max': + (a, sa), (b, sb) = args + assert sa and sb + return max(G_signed(a), G_signed(b)) & MASK, True + return Expr.call(name, args) + + +def G_signed(v): + return v - (1 << 32) if v >> 31 else v + + +def translates(words): + try: + stage(words) + except G.Unsupported as error: + return str(error) + return None + + +def scalar_alu(): + grid = [0, 1, 2, 0x7fff, 0x8000, 0xffff, 0x10000, 0x12345678, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffffe, MASK] + _, text = lines([LSHL2_ADD]) + check('s_lshl2_add_u32 is (S0 << 2) + S1', asm_of([LSHL2_ADD]) == 's_lshl2_add_u32 s20, s21, s22' and + text == 's20 = (s21 << 2) + s22;') + e = Expr(text.split(' = ', 1)[1].rstrip(';')) + check('s_lshl2_add_u32 wraps modulo 2^32 on the grid', + all(e.run({'s21': a, 's22': b})[0] == ((a << 2) + b) & MASK for a in grid for b in grid)) + for n, op in ((1, 0x2e), (3, 0x30), (4, 0x31)): + _, text = lines([SOP2(op, 20, 21, 22)]) + check('s_lshl%d_add_u32 shifts by %d' % (n, n), text == 's20 = (s21 << %d) + s22;' % n) + w = 0xbe800000 | 20 << 16 | 0x34 << 8 | 21 + _, text = lines([w]) + e = SignedExpr(text.split(' = ', 1)[1].rstrip(';')) + check('s_abs_i32 is smax(x, -x): INT_MIN stays INT_MIN (LLVM selects it for that pattern)', + asm_of([w]) == 's_abs_i32 s20, s21' and + all(e.run({'s21': a})[0] == (abs(G_signed(a)) & MASK) for a in grid) and + e.run({'s21': 0x80000000})[0] == 0x80000000) + w = SOP2(0x32, 20, 21, 22) + _, text = lines([w]) + e = Expr(text.split(' = ', 1)[1].rstrip(';')) + check('s_pack_ll_b32_b16 puts S0[15:0] low and S1[15:0] high', + asm_of([w]) == 's_pack_ll_b32_b16 s20, s21, s22' and + all(e.run({'s21': a, 's22': b})[0] == (a & 0xffff) | (b & 0xffff) << 16 for a in grid for b in grid)) + for op, name, sym in ((0xf, 's_addk_i32', '+'), (0x10, 's_mulk_i32', '*')): + w = 0xb0000000 | op << 23 | 20 << 16 | 0xfff0 + _, text = lines([w]) + check('%s sign-extends its simm16 (0xfff0 is -16)' % name, + asm_of([w]) == '%s s20, 0xfff0' % name and text == 's20 = s20 %s 0xfffffff0u;' % sym) + w = 0xb0000000 | op << 23 | 20 << 16 | 0x150 + _, text = lines([w]) + check('%s with a positive simm16' % name, text == 's20 = s20 %s 0x00000150u;' % sym) + # SCC: refused only when an unmodelled SCC value can reach a reader + addk = 0xb0000000 | 0xf << 23 | 20 << 16 | 4 + mulk = 0xb0000000 | 0x10 << 23 | 20 << 16 | 4 + cases = [ + ('unmodelled SCC read straight after', [LSHL2_ADD, CSELECT], True), + ('SCC redefined by s_cmp before the read', [LSHL2_ADD, CMP_EQ, CSELECT], False), + ('no reader at all', [LSHL2_ADD, NOP], False), + ('s_cbranch_scc1 reads it', [LSHL2_ADD, SOPP(5, 0), NOP], True), + ('a branch around the redefinition reaches the reader', + [LSHL2_ADD, SOPP(6, 1), CMP_EQ, CSELECT], True), + ('both paths redefine it', [LSHL2_ADD, SOPP(6, 2), CMP_EQ, SOPP(2, 1), CMP_EQ, CSELECT], False), + ('a loop carries it back to a reader at the head', [CSELECT, LSHL2_ADD, SOPP(7, -3)], True), + ('a loop that redefines it at the head', [CMP_EQ, CSELECT, LSHL2_ADD, SOPP(7, -4)], False), + ('s_addk_i32 defines SCC (signed overflow, not modelled)', [addk, CSELECT], True), + ('s_mulk_i32 does not define SCC', [CMP_EQ, mulk, CSELECT], False), + ('src_scc as an operand is a reader', [LSHL2_ADD, SOP2(0x00, 23, 0xfd, 21)], True), + ] + for label, words, want_refused in cases: + reason = translates(words) + check('SCC liveness: %s -> %s%s' % (label, 'refused' if want_refused else 'translated', + (' (%s)' % reason) if reason else ''), + (reason is not None and 'SCC of' in reason) if want_refused else reason is None) + + +# ---- v_fma_mix_f32 and the f16 operands of the mix family ------------------------------------------------- +def mix_word(op, vdst, srcs, op_sel=0, op_sel_hi=0, neg=0, absolute=0, clamp=0): + return [0xcc000000 | op << 16 | (op_sel_hi >> 2 & 1) << 14 | op_sel << 11 | absolute << 8 | clamp << 15 | vdst, + srcs[0] | srcs[1] << 9 | srcs[2] << 18 | (op_sel_hi & 3) << 27 | neg << 29] + + +def mixes(): + # op_sel / op_sel_hi as [src0, src1, src2] bit 0, 1, 2 + cases = [ + (mix_word(0x20, 1, (258, 20, 128), op_sel=2, op_sel_hi=2, neg=4), + 'v_fma_mix_f32 v1, v2, s20, -0 op_sel:[0,1,0] op_sel_hi:[0,1,0]', + 'v1 = U(F(v2) * f16tof32(s20 >> 16) + (-0.0));', + 'f32 result; op_sel_hi makes src1 an f16 and op_sel takes its high half; -0 is +0 negated'), + (mix_word(0x20, 1, (242, 32, 268), op_sel_hi=2, neg=6), + 'v_fma_mix_f32 v1, 1.0, -s32, -v12 op_sel_hi:[0,1,0]', + 'v1 = U(1.0 * (-f16tof32(s32)) + (-F(v12)));', + 'neg applies to the converted f16 and to the f32 operand'), + (mix_word(0x20, 1, (258, 259, 260), op_sel_hi=1, absolute=1, clamp=1), + 'v_fma_mix_f32 v1, |v2|, v3, v4 op_sel_hi:[1,0,0] clamp', + 'v1 = U(saturate(abs(f16tof32(v2)) * F(v3) + F(v4)));', + 'abs on a low-half f16 source, clamp on the f32 result'), + (mix_word(0x21, 1, (242, 258, 240), op_sel_hi=4), + 'v_fma_mixlo_f16 v1, 1.0, v2, 0.5 op_sel_hi:[0,0,1]', + 'v1 = (v1 & 0xffff0000u) | x2w_f32tof16_rne(1.0 * F(v2) + f16tof32(0x3800u));', + 'an inline 0.5 read as f16 is 0x3800 (not the low half of the f32 0x3f000000)'), + ] + for words, want_asm, want_text, label in cases: + got_asm = asm_of(words) + _, text = lines(words) if got_asm == want_asm else (None, None) + check('fma_mix: %s' % label, got_asm == want_asm and text == want_text) + check('fma_mix: op_sel on an f32 operand refused', + refused(None, words=mix_word(0x20, 1, (258, 259, 260), op_sel=1))) + check('fma_mix: high half of an inline f16 constant refused', + refused(None, words=mix_word(0x20, 1, (240, 259, 260), op_sel=1, op_sel_hi=1))) + # A literal f16 operand reads the half op_sel selects (LLVM SIFoldOperands::tryFoldImmWithOpSel; + # tests/startup_literal_halves_check.py). Formerly refused here. + check('fma_mix: literal f16 operand reads its low half', + lines(mix_word(0x20, 1, (255, 259, 260), op_sel_hi=1) + [0x3c00])[1] + == 'v1 = U(f16tof32(0x3c00u) * F(v3) + F(v4));') + check('fma_mix: literal f16 operand with op_sel reads its high half', + lines(mix_word(0x20, 1, (255, 259, 260), op_sel=1, op_sel_hi=1) + [0x3c00])[1] + == 'v1 = U(f16tof32(0x0000u) * F(v3) + F(v4));') + check('fma_mix: inline 1/(2*pi) refused', refused(None, words=mix_word(0x20, 1, (248, 259, 260)))) + + +# ---- SDWA select and compare, null-export classification, a16 image addresses, entry VGPR reads ------------- +def sdwa_and_misc(): + w = [0x1 << 25 | 10 << 17 | 10 << 9 | 0xf9, 10 | 6 << 8 | 4 << 16 | 5 << 24] + _, text = lines(w) + check('v_cndmask_b32_sdwa selects between the source fields by vcc', + asm_of(w) == 'v_cndmask_b32_sdwa v10, v10, v10, vcc_lo dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 ' + 'src1_sel:WORD_1' and + text == 'v10 = (vcc & 1) ? ((v10 >> 16u) & 0xffffu) : ((v10 >> 0u) & 0xffffu);') + w = [0x7c000000 | 0x95 << 17 | 15 << 9 | 0xf9, 20 | 6 << 16 | 1 << 23 | 4 << 24] + _, text = lines(w) + check('v_cmpx_ne_i32_sdwa compares the selected fields and writes exec', + asm_of(w) == 'v_cmpx_ne_i32_sdwa s20, v15 src0_sel:DWORD src1_sel:WORD_0' and + text == 'exec = ((int(s20) != int(((v15 >> 0u) & 0xffffu))) ? 1u : 0u);') + w = [0x7c000000 | 0x85 << 17 | 15 << 9 | 0xf9, 20 | 6 << 16 | 1 << 23 | 4 << 24 | 1 << 27] + _, text = lines(w) + check('v_cmp_ne_i32_sdwa with sext() sign-extends the field into vcc', + asm_of(w) == 'v_cmp_ne_i32_sdwa vcc_lo, s20, sext(v15) src0_sel:DWORD src1_sel:WORD_0' and + text == 'vcc = ((int(s20) != int(asuint(asint(v15 << 16u) >> 16u))) ? 1u : 0u);') + check('v_cmp_lt_f32_sdwa (a float SDWA compare) refused', + refused(None, words=[0x7c000000 | 0x01 << 17 | 15 << 9 | 0xf9, 20 | 6 << 16 | 1 << 23 | 4 << 24])) + null = words_bytes([0xf8000000 | 9 << 4 | 1 << 11 | 1 << 12, 0, 0xbf810000]) + check('a stage whose only export is "exp null ... done vm" is a pixel stage', G.classify(null) == 'ps') + + load = [0xf0000000 | 3 << 8 | 1 << 3, 2 | 8 << 8 | (24 // 4) << 16 | 1 << 30] + _, text = lines(load, setup=gather_setup) + check('image_load a16 takes x and y from the halves of one address dword', + asm_of(load).endswith('dim:SQ_RSRC_IMG_2D a16') and + text == 't = r0.Load(int3((v2 & 0xffffu), (v2 >> 16), 0));\nv8 = U(t.x);\nv9 = U(t.y);') + sample = [0xf0000000 | 0x20 << 18 | 3 << 8 | 1 << 3, 2 | 8 << 8 | (24 // 4) << 16 | (16 // 4) << 21 | 1 << 30] + _, text = lines(sample, setup=gather_setup) + check('image_sample a16 takes binary16 u and v from the halves of one address dword', + 'f16tof32(v2), f16tof32(v2 >> 16)' in text and 'v3' not in text) + load1d = [0xf0000000 | 1 << 8, 2 | 8 << 8 | (24 // 4) << 16] + s, text = lines(load1d, setup=gather_setup) + check('image_load on a 1D image is Texture1D.Load(int2(x, 0)) with manifest kind tex1d', + asm_of(load1d).endswith('dmask:0x1 dim:SQ_RSRC_IMG_1D') and + text == 't = r0.Load(int2(v2, 0));\nv8 = U(t.x);' and list(s.pipe.resources.values())[0]['kind'] == 'tex1d') + _, text = lines([sample[0], sample[1] | 1 << 31], setup=gather_setup) + check('image_sample d16 packs two binary16 results into one VGPR (gfx9+ packed D16)', + text.endswith('v8 = f32tof16(t.x) | (f32tof16(t.y) << 16);') and 'v9' not in text) + check('image_sample unorm refused', refused(None, setup=gather_setup, words=[sample[0] | 1 << 12, sample[1]])) + check('image_load tfe refused', refused(None, setup=gather_setup, words=[load[0] | 1 << 16, load[1]])) + + mov = 0x7e000000 | 3 << 17 | 1 << 9 | (256 + 1) # v_mov_b32 v3, v1 + s = stage([0x7e000000 | 1 << 17 | 1 << 9 | 0x80, mov]) # v_mov_b32 v1, 0 first + t = stage([mov]) + check('a pixel read of a VGPR before any write is recorded as an entry (SPI input) read', + s.entry_reads == {} and t.entry_reads == {1: 0}) + # A whole request: the interpolated v0..v11 then four moves into the exported v12..v15. Reading v20, which no + # instruction writes, is a read of an SPI input: translate_to writes a .fail instead of a result. + import tempfile + import startup_gfx2hlsl_bit_alu_check as B + def moves(sources): + return words_bytes([0x7e000000 | (12 + i) << 17 | 1 << 9 | (256 + r) for i, r in enumerate(sources)]) + vs = B.vs_words([(0, 0, 0)] * 4) + results = {} + with tempfile.TemporaryDirectory() as directory: + for label, sources in (('control', (0, 1, 2, 3)), ('entry', (0, 1, 20, 3))): + ps = B.PRE_WORDS + moves(sources) + B.POST_WORDS + outcome = G.translate_to(directory, 1, vs, ps, B.root_blob(), check=False) + results[label] = (outcome, Path(directory, '%016x.txt' % 1).exists()) + for leftover in Path(directory).iterdir(): + leftover.unlink() + check('translate_to refuses a pixel stage that reads an entry VGPR (%s); its control translates' + % results['entry'][0], + results['control'] == ('ok', True) and results['entry'][1] is False and 'entry VGPR v20' in results['entry'][0]) + + +def main(): + exports() + output_modifiers() + selects_and_halves() + integer_helpers() + classes() + cubes() + gather() + typed_fetch() + joins() + pknorm() + scalar_alu() + mixes() + sdwa_and_misc() + if failures: + raise SystemExit('FAILED: %s' % '; '.join(failures)) + print('startup gfx2hlsl coverage checks: 0 failed') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_draw_descnum_check.py b/tests/startup_gfx2hlsl_draw_descnum_check.py new file mode 100644 index 0000000000..3a3985a9c7 --- /dev/null +++ b/tests/startup_gfx2hlsl_draw_descnum_check.py @@ -0,0 +1,126 @@ +"""Scalar arithmetic over table descriptor words in a draw stage is computed at run time (X2W_DRAW_FEATURES=descword). + +The title's vertex stages derive numbers from T# / V# words with SALU (an image's width from words 1 and 2 plus one, +shifted by the base level of word 3, clamped to 1 and to 0 for a null descriptor) and convert them to float. The +result was ('descnum',), refused at its numeric use ('numeric use of sN holding descnum', 240 sites in the 103 draw +requests that read table words). With descword each op is a lazy run-time node over the entry values `udsrc <n> +descword <param> <byte>` (Stage.tw_scalar, the draw form of mesh2hlsl's dwnum): only nodes a numeric read reaches are +emitted, so arithmetic nobody reads leaves the translation unchanged. + +Synthetic code (root parameter 0 a table, its pointer in s[8:9]; s_load_dwordx4 s[12:15], s[8:9], 0x20): + chain: s_bfe_u32 s16, s13, 0x10000e ; s_add_u32 s16, s16, 1 ; s_cmp_eq_i32 s13, 0 ; s_cselect_b32 s16, 0, s16 ; + v_cvt_f32_u32 v1, s16 -> one entry value `descword 0 36` (word 1), the three lines (no line for the load: + an unedited word reads its entry value); FXC compiles; + dead: the same plus s_bfe_u32 s17, s14, 0x10000e that nothing reads -> no `descword 0 40`, no s17 line; + inplace: s_bfe_u32 s13, s13, 0x10000e ; v_cvt_f32_u32 v1, s13 (the descriptor handling keeps the symbol) -> the + read takes the run-time node (the extract from ud<n>); + join: s_cmp_eq_u32 s2, 0 ; s_cbranch_scc1 +1 ; s_mov_b32 s13, 5 ; v_cvt_f32_u32 v1, s13 (s13 the loaded word on + one path, a number on the other: 'holding conflict' before) -> s13 = ud<n> at the load (the word's shadow), + a run-time number at the join; without the read nothing is added; + loop: s16 = 0, s17 = 0; L: v_cvt_f32_u32 v1, s16 ; s_add_u32 s16, s16, s13 ; s_add_u32 s17, s17, 1 ; + s_cmp_lt_u32 s17, 4 ; s_cbranch_scc1 L -> the add is kept (the head reads it through the back edge, where + no read marks the node); + off: without descword the chain is refused as before (its s_cmp reads word 1: 'holding desc'), the join + as 'holding conflict'. +""" +import os +import struct +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import PS_WORDS, root_blob # noqa: E402 + + +def sop2(op, dst, src1, src0): + return 0x80000000 | op << 23 | dst << 16 | src1 << 8 | src0 + + +LOAD = [0xf4080304, 0xfa000020, 0xbf8cc07f] # s_load_dwordx4 s[12:15], s[8:9], 0x20; s_waitcnt lgkmcnt(0) +CHAIN = [sop2(0x27, 16, 0xff, 13), 0x0010000e, # s_bfe_u32 s16, s13, 0x10000e + sop2(0x00, 16, 0x81, 16), # s_add_u32 s16, s16, 1 + 0xbf00800d, # s_cmp_eq_i32 s13, 0 + sop2(0x0a, 16, 16, 0x80)] # s_cselect_b32 s16, 0, s16 +DEAD = [sop2(0x27, 17, 0xff, 14), 0x0010000e] # s_bfe_u32 s17, s14, 0x10000e +INPLACE = [sop2(0x27, 13, 0xff, 13), 0x0010000e] # s_bfe_u32 s13, s13, 0x10000e +READ16, READ13 = [0x7e020c10], [0x7e020c0d] # v_cvt_f32_u32_e32 v1, s16 / s13 +LOOP = [0xbe900380, 0xbe910380, # s_mov_b32 s16, 0; s_mov_b32 s17, 0 + 0x7e020c10, sop2(0x00, 16, 13, 16), # L: v_cvt_f32_u32 v1, s16; s_add_u32 s16, s16, s13 + sop2(0x00, 17, 0x81, 17), 0xbf0a8411, # s_add_u32 s17, s17, 1; s_cmp_lt_u32 s17, 4 + 0xbf85fffb] # s_cbranch_scc1 L +JOIN = [0xbf068002, 0xbf850001, 0xbe8d0385] # s_cmp_eq_u32 s2, 0; s_cbranch_scc1 +1; s_mov_b32 s13, 5 +TAIL = [0x7e040d00, 0x7e0802f2, 0xf80008cf, 0x04040201, 0xbf810000] +FEATURES = ('heap', 'bufword3', 'uav', 'heapwords', 'descword') + + +def program(*parts): + words = [w for p in parts for w in p] + return struct.pack('<%dI' % len(words), *words) + + +def translate(code, features=FEATURES): + p = G.Pipeline(code, PS_WORDS, root_blob(), features=features) + return p.hlsl_vs(), p.manifest() + + +def entry(manifest, source): + lines = [ln for ln in manifest.splitlines() if ln.startswith('udsrc ') and ln.endswith(source)] + assert len(lines) == 1, manifest + return int(lines[0].split()[1]) + + +def main(): + asm = [x[3] for x in G.decode(program(LOAD, CHAIN, DEAD, INPLACE))] + assert asm[2:] == ['s_bfe_u32 s16, s13, 0x10000e', 's_add_u32 s16, s16, 1', 's_cmp_eq_i32 s13, 0', + 's_cselect_b32 s16, 0, s16', 's_bfe_u32 s17, s14, 0x10000e', 's_bfe_u32 s13, s13, 0x10000e'], asm + code = program(LOAD, CHAIN, READ16, TAIL) + hlsl, manifest = translate(code) + n = entry(manifest, ' descword 0 36') + for line in ('s16 = (ud%d >> (0x0010000eu & 31)) & ((1u << ((0x0010000eu >> 16) & 127)) - 1);' % n, + 'scc = int(ud%d) == int(0x00000000u);' % n, + 's16 = s16 + 0x00000001u;', 's16 = scc ? 0x00000000u : s16;', 'v1 = U(float(s16));'): + assert line in hlsl, (line, hlsl) + assert 'X2W_' not in hlsl and 'descword 0 40' not in manifest and 's13 = ' not in hlsl, (hlsl, manifest) + with tempfile.TemporaryDirectory() as d: + old = os.environ.get('X2W_DRAW_FEATURES') + os.environ['X2W_DRAW_FEATURES'] = ','.join(FEATURES) + try: + result = G.translate_to(d, 1, code, PS_WORDS, root_blob()) + finally: + if old is None: + os.environ.pop('X2W_DRAW_FEATURES') + else: + os.environ['X2W_DRAW_FEATURES'] = old + assert result == 'ok', result + assert os.path.getsize(os.path.join(d, '%016x.vs.cso' % 1)) > 0 + dead_hlsl, dead_manifest = translate(program(LOAD, CHAIN, DEAD, READ16, TAIL)) + assert dead_manifest == manifest and dead_hlsl == hlsl, (dead_manifest, dead_hlsl) + in_hlsl, in_manifest = translate(program(LOAD, INPLACE, READ13, TAIL)) + m = entry(in_manifest, ' descword 0 36') + assert in_hlsl.index('s13 = (ud%d >> (0x0010000eu & 31))' % m) < in_hlsl.index('v1 = U(float(s13));'), in_hlsl + join_hlsl, join_manifest = translate(program(LOAD, JOIN, READ13, TAIL)) + j = entry(join_manifest, ' descword 0 36') + assert (join_hlsl.index('s13 = ud%d;' % j) < join_hlsl.index('s13 = 0x00000005u;') + < join_hlsl.index('v1 = U(float(s13));')), join_hlsl + unread_hlsl, unread_manifest = translate(program(LOAD, JOIN, [0x7e020d00], TAIL)) # v1 from v0 + assert 'descword' not in unread_manifest and 's13 = ud' not in unread_hlsl, (unread_manifest, unread_hlsl) + loop_hlsl, loop_manifest = translate(program(LOAD, LOOP, TAIL)) + q = entry(loop_manifest, ' descword 0 36') + assert loop_hlsl.index('v1 = U(float(s16));') < loop_hlsl.index('s16 = s16 + ud%d;' % q), loop_hlsl + for case, reason in ((code, 'numeric use of s13 holding desc'), + (program(LOAD, JOIN, READ13, TAIL), 'numeric use of s13 holding conflict')): + try: + translate(case, ('heap', 'bufword3', 'uav', 'heapwords')) + except G.Unsupported as error: + assert reason in str(error), (reason, str(error)) + else: + raise AssertionError('accepted without descword: ' + reason) + print('draw descnum: T# word arithmetic at run time from udsrc descword 0 36, FXC ok; an unread op adds nothing; ' + 'an in-place field extract is read at run time; a join of the loaded word with a number is a run-time ' + 'number; a loop-carried node is kept; without descword refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_draw_descword_check.py b/tests/startup_gfx2hlsl_draw_descword_check.py new file mode 100644 index 0000000000..4cc26f1e60 --- /dev/null +++ b/tests/startup_gfx2hlsl_draw_descword_check.py @@ -0,0 +1,114 @@ +"""A word of a root-table descriptor that a draw stage reads as a number is the runtime's `udsrc <n> descword <p> <byte>`. + +The title's vertex stages test V# word 1 against 0 and convert NUM_RECORDS (word 2) to float straight from the +s_load_dwordx4 of a descriptor table entry (MEASURED at 542ffac61: 'numeric use of sN holding desc' in 103 draw +requests, 98 of them `s_cmp_eq_i32 <word 1>, 0`). With descword in X2W_DRAW_FEATURES the word is an entry constant +whose value the draw runtime reads from the table bound at root parameter <p> (d3d12_draw.inl draw_descword_value: +the title's dword, or the synthesized V# / T# word of a view token), as mesh2hlsl's descword does for mesh stages. + +Synthetic code (root parameter 0 a table, so its pointer is s[8:9]): + s_load_dwordx4 s[12:15], s[8:9], 0x20 ; s_waitcnt lgkmcnt(0) ; [edit] ; [reload] + v_cvt_f32_u32_e32 v1, s14 ; v_cvt_f32_u32_e32 v2, v0 ; v_mov_b32 v4, 1.0 ; exp pos0 v1, v2, v4, v4 done +Checks: + on: manifest `udsrc <n> descword 0 40` (entry +0x20, word 2), the HLSL reads ud<n> for v1, FXC compiles; + off: without the feature the read is refused as before ('numeric use of s14 holding desc'); + edited: `s_and_b32 s14, s14, 0xffff` (an in-place edit, the descriptor symbol is kept) before the read: the read + takes the edit's run-time value (the descnum rule's shadow); after `s_mov_b64 s[16:17], s[14:15]` of the + edited word (no shadow for a pair copy): refused; + clamp: `s_cselect_b32 s14, 0, s14` reads the word as a number and writes s14 at run time; the read takes that; + copied: the unedited word copied by s_mov_b64 is still the table's word; + reload: the same edit followed by a fresh s_load_dwordx4 of the entry: the read is the table's word again. +""" +import os +import struct +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import PS_WORDS, root_blob # noqa: E402 + +LOAD = [0xf4080304, 0xfa000020, 0xbf8cc07f] # s_load_dwordx4 s[12:15], s[8:9], 0x20; s_waitcnt lgkmcnt(0) +EDIT = [0x870eff0e, 0x0000ffff] # s_and_b32 s14, s14, 0xffff +SELECT = [0x850e0e80] # s_cselect_b32 s14, 0, s14 (the title's NUM_RECORDS clamp) +MOV64 = [0xbe90040e] # s_mov_b64 s[16:17], s[14:15] +READ16 = [0x7e020c10] # v_cvt_f32_u32_e32 v1, s16 +TAIL = [0x7e020c0e, 0x7e040d00, 0x7e0802f2, 0xf80008cf, 0x04040201, 0xbf810000] + + +def program(*parts): + words = [w for p in parts for w in p] + return struct.pack('<%dI' % len(words), *words) + + +def pipeline(code, features): + return G.Pipeline(code, PS_WORDS, root_blob(), features=features) + + +def refused(code, features, text): + try: + p = pipeline(code, features) + p.hlsl_vs() + p.manifest() + except G.Unsupported as error: + assert text in str(error), str(error) + else: + raise AssertionError('accepted: expected %r' % text) + + +def main(): + code = program(LOAD, TAIL) + asm = [x[3] for x in G.decode(code)] + assert asm[0] == 's_load_dwordx4 s[12:15], s[8:9], 0x20' and asm[2] == 'v_cvt_f32_u32_e32 v1, s14', asm + assert [x[3] for x in G.decode(program(EDIT))] == ['s_and_b32 s14, s14, 0xffff'], G.decode(program(EDIT)) + features = ('heap', 'bufword3', 'descword') + p = pipeline(code, features) + hlsl = p.hlsl_vs() + manifest = p.manifest() + lines = manifest.splitlines() if isinstance(manifest, str) else list(manifest) + src = [ln for ln in lines if ' descword ' in ln] + assert len(src) == 1 and src[0].endswith(' descword 0 40'), lines + n = int(src[0].split()[1]) + assert ('v1 = U(float(ud%d));' % n) in hlsl or ('float(ud%d)' % n) in hlsl, hlsl + with tempfile.TemporaryDirectory() as d: + old = os.environ.get('X2W_DRAW_FEATURES') + os.environ['X2W_DRAW_FEATURES'] = ','.join(features) + try: + result = G.translate_to(d, 1, code, PS_WORDS, root_blob()) + finally: + if old is None: + os.environ.pop('X2W_DRAW_FEATURES') + else: + os.environ['X2W_DRAW_FEATURES'] = old + assert result == 'ok', result + text = open(os.path.join(d, '%016x.txt' % 1)).read() + assert 'descword 0 40' in text, text + assert os.path.getsize(os.path.join(d, '%016x.vs.cso' % 1)) > 0 + refused(code, ('heap', 'bufword3'), 'numeric use of s14 holding desc') + edited = pipeline(program(LOAD, EDIT, TAIL), features) + text = edited.hlsl_vs() + n = int([ln for ln in edited.manifest().splitlines() if ' descword 0 40' in ln][0].split()[1]) + # the in-place edit's run-time value (Stage.tw_scalar shadow, the descnum rule) is what the read takes + assert ('s14 = ud%d & 0x0000ffffu;' % n) in text and 'v1 = U(float(s14));' in text, text + assert [x[3] for x in G.decode(program(SELECT, MOV64, READ16))] == [ + 's_cselect_b32 s14, 0, s14', 's_mov_b64 s[16:17], s[14:15]', 'v_cvt_f32_u32_e32 v1, s16'] + clamp = pipeline(program(LOAD, SELECT, TAIL), features) + text = clamp.hlsl_vs() + n = int([ln for ln in clamp.manifest().splitlines() if ' descword 0 40' in ln][0].split()[1]) + # s_cselect reads the word as a number and writes s14 at run time: the later read takes that run-time value + assert ('s14 = scc ? 0x00000000u : ud%d;' % n) in text and 'v1 = U(float(s14));' in text, text + refused(program(LOAD, EDIT, MOV64, READ16, TAIL[1:]), features, + 'numeric use of an edited table descriptor word (s16: table 0 +32 word 2)') + copied = pipeline(program(LOAD, MOV64, READ16, TAIL[1:]), features) + copied.hlsl_vs() + assert 'descword 0 40' in copied.manifest(), copied.manifest() + again = pipeline(program(LOAD, EDIT, LOAD, TAIL), features) + again.hlsl_vs() + assert 'descword 0 40' in again.manifest(), again.manifest() + print('draw descword: table word 2 -> udsrc descword 0 40, FXC ok; off: refused; clamp and in-place edit: run-time values; edited then copied by s_mov_b64: refused; ' + 'copied unedited: table word; reloaded after the edit: the table word again') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_exec_lane_facts_check.py b/tests/startup_gfx2hlsl_exec_lane_facts_check.py new file mode 100644 index 0000000000..5b009265a4 --- /dev/null +++ b/tests/startup_gfx2hlsl_exec_lane_facts_check.py @@ -0,0 +1,162 @@ +"""Conflict registers read where the value cannot matter, a back-edge-only loop head, and vcc as a spare pair for +descriptor words (tools/startup/gfx2hlsl.py). Pure Python. + +- ANDN2: on one path into a join s16 holds a descriptor word, on the other a lane mask; the join computes + `s_andn2_b64 s[32:33], s[16:17], exec` while this lane's exec bit is proven 1 (fall-through of s_cbranch_execz, + exec not written since), so bit 0 of the result is 0 whatever s16 holds. Controls: no execz proof, and an AND + (which exec 1 does not absorb), are refused. +- PRUNE: the lane-bit facts decide a branch condition (s_andn2 of a known 1 with exec 1 gives scc 0, so the + s_cbranch_scc1 edge is ruled out); a second scc1 edge into the join keeps the ANDN2 proof. +- LOOP: a loop rotated so its head is entered only by the back edge; the head reads s16, which the body writes as a + run-time number on every path. Controls: a body path that skips the write, and a body that reloads a descriptor. +- VCC: `s_mov_b64 vcc, s[20:21]` of descriptor words, s[20:21] reused, `s_mov_b64 s[20:21], vcc` back, then + image_load through s[16:23]. Controls: a vcc read in between, and a path into the copy back that skips the copy in. +""" +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_join_symbols_check import EXEC, S_AND_B64, S_ANDN2_B64, cmp_ne, root, sop2, sopp # noqa: E402 +from startup_flat_param_check import G, VS_WORDS # noqa: E402 + +LOAD = bytes.fromhex('04040cf4000000fa') # s_load_dwordx8 s[16:23], s[8:9], 0x0 +LOAD_BODY = bytes.fromhex('04040cf4200000fa') # s_load_dwordx8 s[16:23], s[8:9], 0x20 +ZERO_V = bytes.fromhex('8002007e' '8002027e') # v0 = 0, v1 = 0 +EXPORT = bytes.fromhex('0f1800f800000000' '000081bf') # exp mrt0 v0 x4 done vm; s_endpgm +SCC1, VCCZ, EXECZ, BRANCH = 5, 6, 8, 2 +VCC = 106 + + +def sop1(op, dst, src): + return struct.pack('<I', 0xbe800000 | dst << 16 | op << 8 | src) + + +def sopc(op, src0, src1): + return struct.pack('<I', 0xbf000000 | op << 16 | src1 << 8 | src0) + + +S_MOV_B32, S_MOV_B64 = 3, 4 +S_CMP_LG_U32, S_CMP_LT_U32 = 7, 10 +S_ADD_U32 = 0 + + +def ps(words): + return G.Pipeline(VS_WORDS, words, root('t', 1)).hlsl_ps().splitlines() + + +def refused(fragment, words): + try: + ps(words) + except G.Unsupported as reason: + assert fragment in str(reason), str(reason) + return + raise AssertionError('accepted, expected a refusal naming %r' % fragment) + + +def andn2(op=S_ANDN2_B64, execz=True, prune=False): + """s16 = desc; exec &= (v1 != 0); [execz -> end]; vcc = v1 != 0; vccz -> L; s16 = (v0 != 0); L: s32 = s16 op exec.""" + tail = sop2(op, 32, 16, EXEC) + bytes.fromhex('2002007e') + EXPORT # v0 = s32 + fall = cmp_ne(16, 0) + if prune: + # s[34:35] = exec; s34 = s34 & ~exec (0, scc 0); s_cbranch_scc1 into L (a second forward edge) + fall = cmp_ne(16, 0) + sop1(S_MOV_B64, 34, EXEC) + fall += sop2(S_ANDN2_B64, 34, 34, EXEC) + sopp(SCC1, 0) + head = LOAD + ZERO_V + cmp_ne(30, 1) + sop2(S_AND_B64, EXEC, EXEC, 30) + skip = cmp_ne(VCC, 1) + sopp(VCCZ, len(fall) // 4) + fall + body = skip + tail + end = bytes.fromhex('000081bf') + if execz: + return head + sopp(EXECZ, len(body) // 4) + body + end + return head + body + end + + +def check_andn2(): + words = andn2() + names = [asm for *_, asm in G.decode(words)] + assert names[5:10] == ['s_cbranch_execz label_0x48', 'v_cmp_ne_i32_e64 vcc_lo, 0, v1', 's_cbranch_vccz label_0x34', + 'v_cmp_ne_i32_e64 s16, 0, v0', 's_andn2_b64 s[32:33], s[16:17], exec'], names + hlsl = ps(words) + line, = (l for l in hlsl if l.startswith(' s32 = ')) + assert line == ' s32 = (s16 & ~exec) & 1;', hlsl + for word in (0, 1, 0xffffffff, 0x12345679): + assert eval(line.split('= ', 1)[1].rstrip(';'), {'s16': word, 'exec': 1}) == 0 + refused('numeric use of s16 holding conflict', andn2(execz=False)) + refused('numeric use of s16 holding conflict', andn2(op=S_AND_B64)) + + +def check_prune(): + words = andn2(prune=True) + assert 's_cbranch_scc1' in [name for _o, _n, name, _a in G.decode(words)] + assert ' s32 = (s16 & ~exec) & 1;' in ps(words) + # the facts themselves: scc is 0 after s34 = (s34 & ~exec) & 1 with s34 = exec = 1, so the scc1 edge is ruled out + facts = G.lane_facts_after(['s34 = exec;', 's34 = (s34 & ~exec) & 1;', 'scc = s34 != 0;'], {'exec': ('b', 1)}) + assert facts['s34'] == ('v', 0) and facts['scc'] == ('v', 0), facts + taken, fall = G.lane_branch_edges('scc', facts) + assert taken is None and fall is not None + taken, fall = G.lane_branch_edges('(exec & 1) == 0', {}) + assert taken == {'exec': ('b', 0)} and fall == {'exec': ('b', 1)} + # conditional and braced assignments forget, they are not evaluated + assert 's5' not in G.lane_facts_after(['if (exec & 1) s5 = 1;'], {'s5': ('v', 0)}) + assert 's5' not in G.lane_facts_after(['{ s5 = 1; }'], {'s5': ('v', 0)}) + assert 's5' not in G.lane_facts_after(['s5 = s6 + 1;'], {'s5': ('v', 0), 's6': ('v', 0)}) + assert G.lane_facts_merge([{'exec': ('v', 1)}, {'exec': ('b', 1)}, None]) == {'exec': ('b', 1)} + + +def loop(skip_write=False, reload=False): + """s16 = desc; s24 = 0; s_branch BODY; HEAD: s_cmp_lg_u32 s16, 0; BODY: s24 += 1; s16 = s24; s_cmp_lt_u32 s24, 4; + s_cbranch_scc1 HEAD; v0 = s16.""" + write = sop1(S_MOV_B32, 16, 24) + if skip_write: + write = sopc(S_CMP_LG_U32, 24, 129) + sopp(SCC1, 1) + write + if reload: + write = LOAD_BODY + bytes.fromhex('7fc08cbf') + body = sop2(S_ADD_U32, 24, 24, 129) + write + sopc(S_CMP_LT_U32, 24, 132) + back = -(len(body) // 4 + 1 + 1) # to HEAD, one word before BODY + return (LOAD + bytes.fromhex('7fc08cbf') + sop1(S_MOV_B32, 24, 128) + sopp(BRANCH, 1) + + sopc(S_CMP_LG_U32, 16, 128) + body + sopp(SCC1, back) + bytes.fromhex('1002007e') + EXPORT) + + +def check_loop(): + asm = [a for *_, a in G.decode(loop())] + assert asm[3:9] == ['s_branch label_0x18', 's_cmp_lg_u32 s16, 0', 's_add_u32 s24, s24, 1', 's_mov_b32 s16, s24', + 's_cmp_lt_u32 s24, 4', 's_cbranch_scc1 label_0x14'], asm + hlsl = ps(loop()) + assert any(l.strip().startswith('scc = s16 != 0') for l in hlsl), hlsl + refused('numeric use of s16 holding conflict', loop(skip_write=True)) + refused('numeric use of s16 holding', loop(reload=True)) + + +def vcc_copy(read_between=False, skip_copy_in=False): + """s[16:23] = desc; vcc = s[20:21]; s20 = 0; [v2 = vcc ? v1 : v0]; s[20:21] = vcc; image_load s[16:23].""" + middle = sop1(S_MOV_B32, 20, 128) + if read_between: + middle += struct.pack('<I', 0x02000000 | 2 << 17 | 1 << 9 | 256) # v_cndmask_b32_e32 v2, v0, v1, vcc_lo + copy_in = sop1(S_MOV_B64, VCC, 20) + pre = b'' + if skip_copy_in: + pre = cmp_ne(30, 1) + sopc(S_CMP_LG_U32, 30, 128) + sopp(SCC1, len(copy_in) // 4) + return (LOAD + bytes.fromhex('7fc08cbf') + ZERO_V + pre + copy_in + middle + sop1(S_MOV_B64, 20, VCC) + + bytes.fromhex('080f00f000040400' '703f8cbf' '0f1800f804050607' '000081bf')) + + +def check_vcc(): + asm = [a for *_, a in G.decode(vcc_copy())] + assert asm[4:7] == ['s_mov_b64 vcc, s[20:21]', 's_mov_b32 s20, 0', 's_mov_b64 s[20:21], vcc'], asm + hlsl = ps(vcc_copy()) + assert not any('vcc' in l for l in hlsl if l.startswith(' ') and 'uint vcc' not in l), hlsl + refused('mask from descriptor data', vcc_copy(read_between=True)) + refused('mask from descriptor data', vcc_copy(skip_copy_in=True)) + + +def main(): + check_andn2() + check_prune() + check_loop() + check_vcc() + print('conflict registers absorbed by a proven exec bit, a back-edge-only loop head and vcc descriptor copies pass;' + ' every control refuses') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_f16_arith_check.py b/tests/startup_gfx2hlsl_f16_arith_check.py new file mode 100644 index 0000000000..50d19efa4d --- /dev/null +++ b/tests/startup_gfx2hlsl_f16_arith_check.py @@ -0,0 +1,735 @@ +"""binary16 arithmetic and compares in tools/startup/gfx2hlsl.py, emulated in f32 (draws compile with fxc 5.1). + +usage: startup_gfx2hlsl_f16_arith_check.py [fxc <fxc.exe> | dispatch <fxc.exe> <offscreen_check> warp|hardware] + +Lowered: v_pk_add_f16 / v_pk_mul_f16 / v_pk_fma_f16 (op_sel, op_sel_hi, neg_lo, neg_hi, clamp), v_add / sub / subrev / +mul / fma / fmac_f16 (VOP2, VOP3 with neg, abs, op_sel and clamp, SDWA for add / sub / subrev / mul), the f16 compares +(e32, e64, SDWA), v_cvt_pk_u16_u32 and v_mad_u32_u16 with op_sel. + +No arguments: pure Python. + 1. The helper chain (x2w_f16_fma, then x2w_f32tof16_rne) is modelled step by step in exact binary32 arithmetic, with + HLSL f32tof16 modelled both toward zero (MEASURED on WARP, startup_round_mode_check) and to nearest, and compared + with the single nearest-even rounding of the exact a * b + c (fractions.Fraction) over constructed cases (ties, + subnormal results, overflow, signed zeros, large exponent gaps, fma near-midpoints) and random binary16 triples. + Control: the plain f32 `a * b + c` rounded once to binary16 differs from the exact result on some of them. + 2. Each instruction word is built here from the encodings tools/disasm_rdna2.py decodes, translated, and the emitted + HLSL statement is evaluated (the helpers through the models of 1) on random register words and compared with a + reference computed from the encoding fields alone. Refusals: toward-zero MODE, a constant's high half, 1/(2*pi), + dst_sel DWORD, omod. +`fxc`: every translated statement and the helpers compile for vs_5_1 (the draw profile). +`dispatch`: the helpers run on the device (fxc cs_5_1) over 4096 triples per batch and the words are compared with the +exact reference; control: the plain f32 expression differs from it on the device. +""" +import math +import os +import random +import re +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction + +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 = [] +INF = float('inf') + + +def check(label, condition, detail=''): + print('%s: %s' % (label, 'ok' if condition else 'MISMATCH')) + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +# ---- exact binary rounding ------------------------------------------------------------------------------------ +def rnd(x, p, emin, maxv, mode): + """x (a Fraction, nonzero) rounded to a binary format with p bits, minimum exponent emin, largest finite maxv.""" + s = -1 if x < 0 else 1 + a = abs(x) + e = a.numerator.bit_length() - a.denominator.bit_length() + if Fraction(2) ** e > a: + e -= 1 + e = max(e, emin) + q = Fraction(2) ** (e - p + 1) + n = a / q + fl = n.numerator // n.denominator + rem = n - fl + if mode == 'rne' and (rem > Fraction(1, 2) or (rem == Fraction(1, 2) and fl % 2)): + fl += 1 + r = fl * q + if r > maxv: + return s * (INF if mode == 'rne' else float(maxv)) + return s * float(r) + + +F32MAX = (2 - Fraction(2) ** -23) * Fraction(2) ** 127 + + +def r32(x): + return rnd(x, 24, -126, F32MAX, 'rne') + + +def add32(x, y): + if math.isnan(x) or math.isnan(y) or math.isinf(x) or math.isinf(y): + return x + y + exact = Fraction(x) + Fraction(y) + if exact == 0: + return -0.0 if (math.copysign(1, x) < 0 and math.copysign(1, y) < 0) else 0.0 + return r32(exact) + + +def mul32(x, y): + if math.isnan(x) or math.isnan(y) or math.isinf(x) or math.isinf(y): + return x * y + exact = Fraction(x) * Fraction(y) + if exact == 0: + return math.copysign(0.0, x) * math.copysign(1, y) + return r32(exact) + + +def f32_bits(x): + return struct.unpack('<I', struct.pack('<f', x))[0] + + +def f32_from(u): + return struct.unpack('<f', struct.pack('<I', u & 0xffffffff))[0] + + +def h2f(bits): + return struct.unpack('<e', struct.pack('<H', bits & 0xffff))[0] + + +def f2h(x): + """bits of a value exactly representable in binary16 (or inf).""" + if math.isinf(x): + return 0xfc00 if x < 0 else 0x7c00 + return struct.unpack('<H', struct.pack('<e', x))[0] + + +def hlsl_f32tof16(x, mode): + """HLSL f32tof16 as modelled: toward zero (MEASURED on WARP) or nearest even.""" + if math.isnan(x): + return 0x7fff + if math.isinf(x) or x == 0: + return f2h(x) if x != 0 else (0x8000 if math.copysign(1, x) < 0 else 0) + return f2h(rnd(Fraction(x), 11, -14, Fraction(65504), mode)) + + +def model_rne(x, mode): + """x2w_f32tof16_rne step by step (HELPERS text), binary32 arithmetic exact-rounded.""" + t = hlsl_f32tof16(x, mode) + a = abs(x) + if abs(h2f(t)) > a: + t -= 1 + if (t & 0x7c00) == 0x7c00: + return t + lo = abs(h2f(t)) + if a == lo: + return t + u = t + 1 + hi = 65536.0 if (u & 0x7fff) == 0x7c00 else abs(h2f(u)) + dl, dh = add32(a, -lo), add32(hi, -a) + return u if (dh < dl or (dh == dl and (t & 1))) else t + + +def model_fma(a, b, c): + """x2w_f16_fma step by step.""" + p = mul32(a, b) + s = add32(p, c) + if (f32_bits(s) & 0x7f800000) == 0x7f800000: + return s + bb = add32(s, -p) + e = add32(add32(p, -add32(s, -bb)), add32(c, -bb)) + u = f32_bits(s) + if (f32_bits(e) & 0x7fffffff) and not (u & 1): + u = (u + (0xffffffff if (f32_bits(e) ^ u) & 0x80000000 else 1)) & 0xffffffff + return f32_from(u) + + +def exact_f16(a, b, c): + """bits of the nearest-even binary16 rounding of the exact a * b + c (one rounding).""" + if any(math.isnan(v) or math.isinf(v) for v in (a, b, c)): + return None + exact = Fraction(a) * Fraction(b) + Fraction(c) + if exact == 0: + prod_neg = (math.copysign(1, a) * math.copysign(1, b)) < 0 + if Fraction(a) * Fraction(b) == 0 and c == 0: + return 0x8000 if (prod_neg and math.copysign(1, c) < 0) else 0 + return 0 + return f2h(rnd(exact, 11, -14, Fraction(65504), 'rne')) + + +def finite_f16(rng): + while True: + exp = rng.choice([0, 1, 2, 13, 14, 15, 16, 17, 25, 28, 29, 30] + list(range(31))) + bits = rng.getrandbits(1) << 15 | exp << 10 | rng.getrandbits(10) + if exp != 31: + return bits + + +def constructed(): + """(a, b, c) binary16 bit triples: ties, near-midpoints, subnormals, overflow, signed zeros, large gaps.""" + cases = [ + (0x3c01, 0x37fe, 0x6401), # 1025 + (0.5 - 2^-21): f32 rounds onto the tie, nearest even then goes up + (0x3c01, 0x37fe, 0x6400), + (0x3c01, 0x37fe, 0xe401), + (0x3c01, 0xb7fe, 0x6401), + (0x3c00, 0x3c00, 0x0001), # 1 + 2^-24: below half an ulp + (0x0001, 0x0001, 0x0000), # 2^-48: underflows to +0 + (0x8001, 0x0001, 0x0000), # -2^-48 + 0: -0 or +0 + (0x8001, 0x0001, 0x8000), + (0x0000, 0x8000, 0x8000), # -0 * ... + -0 = -0 + (0x3c00, 0x3c00, 0xbc00), # exact cancellation: +0 + (0x7bff, 0x3c00, 0x5000), # 65504 + 32: tie at the overflow threshold -> inf + (0x7bff, 0x3c00, 0x4fff), + (0x7bff, 0x7bff, 0x0000), # overflow of the product + (0x0200, 0x3c00, 0x0200), # subnormal sums + (0x0001, 0x3800, 0x0000), # 2^-25: tie between 0 and 2^-24 -> 0 + (0x0003, 0x3800, 0x0000), # 1.5 * 2^-24 -> 2^-23 + (0x3555, 0x3555, 0x8001), + (0x5bff, 0x5bff, 0xfbff), + (0x2001, 0x2001, 0x6c01), + ] + # fma near-midpoints: c with an odd last bit, product half an ulp of c minus a little (1 - 2^-20 times) + for e in range(-12, 15): + c = 0x400 | 1 | (e + 15) << 10 + ulp_half = 2.0 ** (e - 11) + if not 2.0 ** -14 <= ulp_half * 2 ** 1 <= 32768: + continue + a = 0x3c01 + b_val = ulp_half * (1 - 2.0 ** -10) + try: + b = f2h(b_val) + except (OverflowError, struct.error): + continue + if h2f(b) != b_val: + continue + for sa in (0, 0x8000): + for sc in (0, 0x8000): + cases.append((a ^ sa, b, (c & 0x7fff) | sc)) + return cases + + +def check_helpers(): + rng = random.Random(20261125) + cases = [tuple(c) for c in constructed()] + for _ in range(12000): + cases.append((finite_f16(rng), finite_f16(rng), finite_f16(rng))) + for _ in range(3000): # products near a fixed addend's half ulp + c = finite_f16(rng) + cases.append((finite_f16(rng), finite_f16(rng) & 0x83ff | (c >> 10 & 31) << 10, c)) + bad = {'tz': [], 'ne': []} + naive_bad = 0 + for a_bits, b_bits, c_bits in cases: + a, b, c = h2f(a_bits), h2f(b_bits), h2f(c_bits) + want = exact_f16(a, b, c) + for mode, tag in (('rtz', 'tz'), ('rne', 'ne')): + got = model_rne(model_fma(a, b, c), mode) + if got != want: + bad[tag].append((a_bits, b_bits, c_bits, got, want)) + naive = model_rne(add32(mul32(a, b), c), 'rtz') + naive_bad += naive != want + # add and mul as the handlers emit them + want_add = exact_f16(a, 1.0, c) + got_add = model_rne(model_fma(a, 1.0, c), 'rtz') + if got_add != want_add: + bad['tz'].append(('add', a_bits, c_bits, got_add, want_add)) + want_mul = exact_f16(a, b, -0.0) + if want_mul is not None and Fraction(a) * Fraction(b) == 0: + want_mul = 0x8000 if math.copysign(1, a) * math.copysign(1, b) < 0 else 0 + got_mul = model_rne(mul32(a, b), 'rtz') + if got_mul != want_mul: + bad['tz'].append(('mul', a_bits, b_bits, got_mul, want_mul)) + for tag in bad: + check('helper chain, f32tof16 modelled %s: %d cases equal the single rounding' + % ('toward zero' if tag == 'tz' else 'to nearest', len(cases)), not bad[tag], + 'first: %s' % (bad[tag][:3],)) + check('control: plain f32 a * b + c then rounding differs from the single rounding (%d cases)' % naive_bad, + naive_bad > 0) + # specials pass through the f32 result + for a, b, c in ((INF, 0.0, 1.0), (INF, 1.0, -INF), (float('nan'), 1.0, 1.0), (INF, 2.0, 1.0)): + got = model_fma(a, b, c) + ref = a * b + c + check('helper special %r * %r + %r' % (a, b, c), (math.isnan(got) and math.isnan(ref)) or got == ref) + return cases + + +# ---- instruction words ------------------------------------------------------------------------------------------ +V = 256 + + +def vop2(op, vdst, src0, vsrc1, literal=None): + w = struct.pack('<I', op << 25 | vdst << 17 | vsrc1 << 9 | src0) + return w + (struct.pack('<I', literal) if literal is not None else b'') + + +def vopc(op, src0, vsrc1): + return struct.pack('<I', 0x3e << 25 | op << 17 | vsrc1 << 9 | src0) + + +def vop3(op, vdst, srcs, *, op_sel=(0, 0, 0, 0), abs_bits=(0, 0, 0), neg=(0, 0, 0), clamp=0, omod=0): + srcs = list(srcs) + [0] * (3 - len(srcs)) + w0 = 0x35 << 26 | op << 16 | clamp << 15 | vdst + for i in range(4): + w0 |= op_sel[i] << (11 + i) + for i in range(3): + w0 |= abs_bits[i] << (8 + i) + w1 = srcs[0] | srcs[1] << 9 | srcs[2] << 18 | omod << 27 + for i in range(3): + w1 |= neg[i] << (29 + i) + return struct.pack('<II', w0, w1) + + +def vop3p(op, vdst, srcs, *, op_sel=(0, 0, 0), op_sel_hi=(1, 1, 1), neg_lo=(0, 0, 0), neg_hi=(0, 0, 0), clamp=0): + srcs = list(srcs) + [0] * (3 - len(srcs)) + w0 = 0b110011000 << 23 | op << 16 | clamp << 15 | op_sel_hi[2] << 14 | vdst + w1 = srcs[0] | srcs[1] << 9 | srcs[2] << 18 | op_sel_hi[0] << 27 | op_sel_hi[1] << 28 + for i in range(3): + w0 |= op_sel[i] << (11 + i) | neg_hi[i] << (8 + i) + w1 |= neg_lo[i] << (29 + i) + return struct.pack('<II', w0, w1) + + +SEL = {'BYTE_0': 0, 'WORD_0': 4, 'WORD_1': 5, 'DWORD': 6} +UNUSED = {'UNUSED_PAD': 0, 'UNUSED_SEXT': 1, 'UNUSED_PRESERVE': 2} + + +def sdwa2(op, vdst, src0, vsrc1, *, sel0, sel1, dst_sel='WORD_0', unused='UNUSED_PRESERVE', neg=(0, 0), + abs_bits=(0, 0), clamp=0, s0=0): + w0 = op << 25 | vdst << 17 | vsrc1 << 9 | 0xf9 + w1 = (src0 & 0xff) | SEL[dst_sel] << 8 | UNUSED[unused] << 11 | clamp << 13 | SEL[sel0] << 16 | \ + neg[0] << 20 | abs_bits[0] << 21 | s0 << 23 | SEL[sel1] << 24 | neg[1] << 28 | abs_bits[1] << 29 + return struct.pack('<II', w0, w1) + + +def sdwac(op, src0, vsrc1, *, sel0, sel1, sdst=None, s0=0, neg=(0, 0), abs_bits=(0, 0)): + w0 = 0x3e << 25 | op << 17 | vsrc1 << 9 | 0xf9 + w1 = (src0 & 0xff) | SEL[sel0] << 16 | neg[0] << 20 | abs_bits[0] << 21 | s0 << 23 | SEL[sel1] << 24 | \ + neg[1] << 28 | abs_bits[1] << 29 + if sdst is not None: + w1 |= (sdst & 0x7f) << 8 | 1 << 15 + return struct.pack('<II', w0, w1) + + +class Pipeline: + def __init__(self): + self.resources, self.notes, self.modified = {}, set(), set() + + +class Stage(G.Stage): + """A Stage with no pipeline: enough state for a decoded instruction to be translated.""" + def __init__(self, round16=0): + self.lines, self.sym = [], {} + self.low16_only_v = set() + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.exec_known = True + self.exports = {} + self.pipe = Pipeline() + self.masks = set() + self.round16 = round16 + + +def translate(code, round16=0): + decoded = G.decode(code) + stage = Stage(round16) + for _o, _s, name, asm in decoded: + stage.one(name, asm) + return ' | '.join(asm for _o, _s, _n, asm in decoded), stage.lines + + +# ---- evaluating an emitted statement ----------------------------------------------------------------------------- +def py_expr(text): + text = re.sub(r'\b(0x[0-9a-f]+)u\b', r'\1', text) + text = re.sub(r'\b(\d+)u\b', r'\1', text) + # `(C) ? 1 : 0` -> `(1 if (C) else 0)`, innermost first + while ' ? 1 : 0' in text: + at = text.index(' ? 1 : 0') + depth, i = 0, at - 1 + while True: + if text[i] == ')': + depth += 1 + elif text[i] == '(': + depth -= 1 + if depth == 0: + break + i -= 1 + text = text[:i] + '(1 if ' + text[i:at] + ' else 0)' + text[at + len(' ? 1 : 0'):] + text = text.replace('!(', ' not (').replace('&&', ' and ') + return text + + +def evaluate(expr, env, mode='rtz'): + names = dict(env) + names.update({ + 'f16tof32': h2f, 'x2w_f32tof16_rne': lambda x: model_rne(x, mode), 'x2w_f16_fma': model_fma, + 'saturate': lambda x: 0.0 if math.isnan(x) else min(max(x, 0.0), 1.0), 'min': min, 'asuint': int}) + return eval(py_expr(expr), {'__builtins__': {}}, names) & 0xffffffff + + +def statement(lines): + assert len(lines) == 1, lines + m = re.fullmatch(r'(\w+) = (.*);', lines[0]) + assert m, lines[0] + return m.group(1), m.group(2) + + +def lane(word, high): + return (word >> 16 if high else word) & 0xffff + + +def ref_f16(kind, a, b, c=None): + """bits of the exact single rounding of add / mul / fma on binary16 values; None for a NaN/inf case.""" + if kind == 'add': + return exact_f16(a, 1.0, b) if not (a == 0 and b == 0) else ( + 0x8000 if math.copysign(1, a) < 0 and math.copysign(1, b) < 0 else 0) + if kind == 'mul': + if any(math.isinf(v) or math.isnan(v) for v in (a, b)): + return None + if Fraction(a) * Fraction(b) == 0: + return 0x8000 if math.copysign(1, a) * math.copysign(1, b) < 0 else 0 + return f2h(rnd(Fraction(a) * Fraction(b), 11, -14, Fraction(65504), 'rne')) + return exact_f16(a, b, c) + + +def clamp16(bits): + x = h2f(bits) + return f2h(min(max(x, 0.0), 1.0)) if not math.isnan(x) else 0 + + +def run_words(label, code, asm, ref, trials=400, regs=('v2', 'v3', 'v4', 'v1', 's5')): + """Translate `code`, check the decode, then evaluate the statement on random words against ref(words).""" + rng = random.Random(label) + got_asm, lines = translate(code) + check(label + ' (decode)', got_asm == asm, 'got %r' % got_asm) + if got_asm != asm: + return lines + dst, expr = statement(lines) + bad = [] + for _ in range(trials): + words = {} + for r in regs: + lo, hi = finite_f16(rng), finite_f16(rng) + if rng.random() < 0.1: + lo = rng.choice([0, 0x8000, 0x3c00, 0x0001]) + words[r] = lo | hi << 16 + want = ref(words) + if want is None: + continue + got = evaluate(expr, words) + if got != want: + bad.append((words, got, want)) + check('%s: %d evaluated words equal the reference' % (label, trials), not bad, + 'first: %s\n %s' % (bad[:1], lines[0])) + return lines + + +def pk_ref(kind, fields, dst_reg='v1'): + def f(words): + out = 0 + n = 3 if kind == 'fma' else 2 + for li, (sel, neg) in enumerate(((fields['op_sel'], fields['neg_lo']), (fields['op_sel_hi'], fields['neg_hi']))): + vals = [] + for i in range(n): + src = fields['srcs'][i] + bits = fields['consts'][i] if isinstance(src, int) else lane(words[src], sel[i]) + vals.append(h2f(bits ^ (0x8000 if neg[i] else 0))) + r = ref_f16(kind, *vals) + if r is None: + return None + if fields.get('clamp'): + r = clamp16(r) + out |= r << (16 * li) + return out + return f + + +def main_checks(): + check_helpers() + v1, v2, v3, v4, s5 = V + 1, V + 2, V + 3, V + 4, 5 + PK_FMA, PK_ADD, PK_MUL = 0x0e, 0x0f, 0x10 + lines = [] + + # ---- VOP3P ---- + lines += run_words('v_pk_add_f16 neg_lo/neg_hi (a packed subtract)', + vop3p(PK_ADD, 1, (v2, v3), neg_lo=(0, 1, 0), neg_hi=(0, 1, 0)), + 'v_pk_add_f16 v1, v2, v3 neg_lo:[0,1] neg_hi:[0,1]', + pk_ref('add', dict(srcs=['v2', 'v3'], consts=[0, 0], op_sel=(0, 0), op_sel_hi=(1, 1), + neg_lo=(0, 1), neg_hi=(0, 1)))) + lines += run_words('v_pk_add_f16 plain', + vop3p(PK_ADD, 1, (v2, v3)), 'v_pk_add_f16 v1, v2, v3', + pk_ref('add', dict(srcs=['v2', 'v3'], consts=[0, 0], op_sel=(0, 0), op_sel_hi=(1, 1), + neg_lo=(0, 0), neg_hi=(0, 0)))) + lines += run_words('v_pk_add_f16 inline 0.5 low half only, neg on src1', + vop3p(PK_ADD, 1, (240, v3), op_sel_hi=(0, 1, 1), neg_lo=(0, 1, 0), neg_hi=(0, 1, 0)), + 'v_pk_add_f16 v1, 0.5, v3 op_sel_hi:[0,1] neg_lo:[0,1] neg_hi:[0,1]', + pk_ref('add', dict(srcs=[0, 'v3'], consts=[0x3800, 0], op_sel=(0, 0), op_sel_hi=(0, 1), + neg_lo=(0, 1), neg_hi=(0, 1)))) + lines += run_words('v_pk_fma_f16 op_sel_hi:[1,0,1]', + vop3p(PK_FMA, 1, (v2, v3, v4), op_sel_hi=(1, 0, 1)), + 'v_pk_fma_f16 v1, v2, v3, v4 op_sel_hi:[1,0,1]', + pk_ref('fma', dict(srcs=['v2', 'v3', 'v4'], consts=[0] * 3, op_sel=(0, 0, 0), + op_sel_hi=(1, 0, 1), neg_lo=(0, 0, 0), neg_hi=(0, 0, 0)))) + lines += run_words('v_pk_fma_f16 op_sel, neg_lo on src2, neg_hi on src0, clamp', + vop3p(PK_FMA, 1, (v2, v3, v4), op_sel=(1, 0, 1), op_sel_hi=(0, 1, 1), neg_lo=(0, 0, 1), + neg_hi=(1, 0, 0), clamp=1), + 'v_pk_fma_f16 v1, v2, v3, v4 op_sel:[1,0,1] op_sel_hi:[0,1,1] neg_lo:[0,0,1] neg_hi:[1,0,0] ' + 'clamp', + pk_ref('fma', dict(srcs=['v2', 'v3', 'v4'], consts=[0] * 3, op_sel=(1, 0, 1), + op_sel_hi=(0, 1, 1), neg_lo=(0, 0, 1), neg_hi=(1, 0, 0), clamp=1))) + lines += run_words('v_pk_mul_f16 op_sel:[1,1] op_sel_hi:[0,0]', + vop3p(PK_MUL, 1, (v2, v3), op_sel=(1, 1, 0), op_sel_hi=(0, 0, 1)), + 'v_pk_mul_f16 v1, v2, v3 op_sel:[1,1] op_sel_hi:[0,0]', + pk_ref('mul', dict(srcs=['v2', 'v3'], consts=[0, 0], op_sel=(1, 1), op_sel_hi=(0, 0), + neg_lo=(0, 0), neg_hi=(0, 0)))) + lines += run_words('v_pk_fma_f16 inline 2.0 and -1.0 through their low halves', + vop3p(PK_FMA, 1, (v2, 244, 243), op_sel_hi=(1, 0, 0)), + 'v_pk_fma_f16 v1, v2, 2.0, -1.0 op_sel_hi:[1,0,0]', + pk_ref('fma', dict(srcs=['v2', 0, 0], consts=[0, 0x4000, 0xbc00], op_sel=(0, 0, 0), + op_sel_hi=(1, 0, 0), neg_lo=(0, 0, 0), neg_hi=(0, 0, 0)))) + + # ---- VOP2 / VOP3 ---- + def keep_hi(words, bits): + return None if bits is None else (words['v1'] & 0xffff0000) | bits + + lines += run_words('v_sub_f16_e32', vop2(0x33, 1, v2, 3), 'v_sub_f16_e32 v1, v2, v3', + lambda w: keep_hi(w, ref_f16('add', h2f(lane(w['v2'], 0)), h2f(lane(w['v3'], 0) ^ 0x8000)))) + lines += run_words('v_subrev_f16_e32 with an SGPR', vop2(0x34, 1, s5, 3), 'v_subrev_f16_e32 v1, s5, v3', + lambda w: keep_hi(w, ref_f16('add', h2f(lane(w['v3'], 0)), h2f(lane(w['s5'], 0) ^ 0x8000)))) + lines += run_words('v_add_f16_e32 inline 1.0', vop2(0x32, 1, 242, 3), 'v_add_f16_e32 v1, 1.0, v3', + lambda w: keep_hi(w, ref_f16('add', 1.0, h2f(lane(w['v3'], 0))))) + lines += run_words('v_mul_f16_e32', vop2(0x35, 1, v2, 3), 'v_mul_f16_e32 v1, v2, v3', + lambda w: keep_hi(w, ref_f16('mul', h2f(lane(w['v2'], 0)), h2f(lane(w['v3'], 0))))) + lines += run_words('v_fmac_f16_e32', vop2(0x36, 1, v2, 3), 'v_fmac_f16_e32 v1, v2, v3', + lambda w: keep_hi(w, ref_f16('fma', h2f(lane(w['v2'], 0)), h2f(lane(w['v3'], 0)), + h2f(lane(w['v1'], 0))))) + lines += run_words('v_fma_f16 op_sel:[0,1,0]', vop3(0x34b, 1, (v2, v3, v4), op_sel=(0, 1, 0, 0)), + 'v_fma_f16 v1, v2, v3, v4 op_sel:[0,1,0]', + lambda w: keep_hi(w, ref_f16('fma', h2f(lane(w['v2'], 0)), h2f(lane(w['v3'], 1)), + h2f(lane(w['v4'], 0))))) + lines += run_words('v_fma_f16 src2 high, destination high, neg on src2', + vop3(0x34b, 1, (v2, v3, v4), op_sel=(0, 0, 1, 1), neg=(0, 0, 1)), + 'v_fma_f16 v1, v2, v3, -v4 op_sel:[0,0,1,1]', + lambda w: None if (r := ref_f16('fma', h2f(lane(w['v2'], 0)), h2f(lane(w['v3'], 0)), + h2f(lane(w['v4'], 1) ^ 0x8000))) is None + else (w['v1'] & 0xffff) | r << 16) + lines += run_words('v_add_f16_e64 abs, neg, clamp', vop3(0x132, 1, (v2, v3), abs_bits=(0, 1, 0), neg=(1, 1, 0), + clamp=1), + 'v_add_f16_e64 v1, -v2, -|v3| clamp', + lambda w: None if (r := ref_f16('add', h2f(lane(w['v2'], 0) ^ 0x8000), + h2f(lane(w['v3'], 0) | 0x8000))) is None + else keep_hi(w, clamp16(r))) + + # ---- SDWA ---- + lines += run_words('v_sub_f16_sdwa src1 WORD_1, dst WORD_0 preserve', + sdwa2(0x33, 1, 2, 3, sel0='DWORD', sel1='WORD_1'), + 'v_sub_f16_sdwa v1, v2, v3 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD ' + 'src1_sel:WORD_1', + lambda w: keep_hi(w, ref_f16('add', h2f(lane(w['v2'], 0)), h2f(lane(w['v3'], 1) ^ 0x8000)))) + lines += run_words('v_sub_f16_sdwa inline 1.0 WORD_0', + sdwa2(0x33, 1, 242, 3, sel0='WORD_0', sel1='WORD_1', s0=1), + 'v_sub_f16_sdwa v1, 1.0, v3 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 ' + 'src1_sel:WORD_1', + lambda w: keep_hi(w, ref_f16('add', 1.0, h2f(lane(w['v3'], 1) ^ 0x8000)))) + lines += run_words('v_mul_f16_sdwa dst WORD_1 preserve', + sdwa2(0x35, 1, 2, 3, sel0='WORD_1', sel1='WORD_0', dst_sel='WORD_1'), + 'v_mul_f16_sdwa v1, v2, v3 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 ' + 'src1_sel:WORD_0', + lambda w: None if (r := ref_f16('mul', h2f(lane(w['v2'], 1)), h2f(lane(w['v3'], 0)))) is None + else (w['v1'] & 0xffff) | r << 16) + + # ---- compares ---- + def cmp_ref(op, x, y): + if math.isnan(x) or math.isnan(y): + return {'lt': 0, 'neq': 1, 'nlt': 1, 'u': 1, 'o': 0, 'gt': 0, 'eq': 0}[op] + return int({'lt': x < y, 'neq': x != y, 'nlt': not x < y, 'u': False, 'o': True, 'gt': x > y, + 'eq': x == y}[op]) + + def nan_words(label): + rng = random.Random(label) + return lambda: rng.choice([0x7e00, 0x7c01, 0xfe00, 0x7c00, 0xfc00, 0x0000, 0x8000]) + + def run_cmp(label, code, asm, op, a, b, dst): + got_asm, out = translate(code) + check(label + ' (decode)', got_asm == asm, 'got %r' % got_asm) + if got_asm != asm: + return + reg, expr = statement(out) + check(label + ' destination', reg == dst, out[0]) + rng = random.Random(label) + special = nan_words(label) + bad = [] + for _ in range(400): + words = {r: (special() if rng.random() < 0.3 else finite_f16(rng)) | + (special() if rng.random() < 0.3 else finite_f16(rng)) << 16 for r in ('v2', 'v3', 's5')} + want = cmp_ref(op, a(words), b(words)) + got = evaluate(expr, words) + if got != want: + bad.append((words, got, want)) + check('%s: 400 evaluated compares (NaN, inf, zeros included)' % label, not bad, + 'first: %s\n %s' % (bad[:1], out[0])) + lines.extend(out) + + run_cmp('v_cmp_lt_f16_e64 into an SGPR', vop3(0xc9, 6, (128, v3)), 'v_cmp_lt_f16_e64 s6, 0, v3', 'lt', + lambda w: 0.0, lambda w: h2f(lane(w['v3'], 0)), 's6') + run_cmp('v_cmp_neq_f16_e32 inline 1.0', vopc(0xed, 242, 3), 'v_cmp_neq_f16_e32 vcc_lo, 1.0, v3', 'neq', + lambda w: 1.0, lambda w: h2f(lane(w['v3'], 0)), 'vcc') + run_cmp('v_cmp_nlt_f16_e64 -|v2| op_sel high halves', vop3(0xee, 6, (v2, v3), op_sel=(1, 1, 0, 0), + abs_bits=(1, 0, 0), neg=(1, 0, 0)), + 'v_cmp_nlt_f16_e64 s6, -|v2|, v3 op_sel:[1,1,0]', 'nlt', + lambda w: h2f(lane(w['v2'], 1) | 0x8000), lambda w: h2f(lane(w['v3'], 1)), 's6') + run_cmp('v_cmp_u_f16_e32', vopc(0xe8, v2, 3), 'v_cmp_u_f16_e32 vcc_lo, v2, v3', 'u', + lambda w: h2f(lane(w['v2'], 0)), lambda w: h2f(lane(w['v3'], 0)), 'vcc') + run_cmp('v_cmp_lt_f16_sdwa into an SGPR', sdwac(0xc9, 128, 3, sel0='WORD_0', sel1='WORD_1', sdst=6, s0=1), + 'v_cmp_lt_f16_sdwa s6, 0, v3 src0_sel:WORD_0 src1_sel:WORD_1', 'lt', + lambda w: 0.0, lambda w: h2f(lane(w['v3'], 1)), 's6') + run_cmp('v_cmp_neq_f16_sdwa inline 1.0', sdwac(0xed, 242, 3, sel0='WORD_0', sel1='WORD_1', s0=1), + 'v_cmp_neq_f16_sdwa vcc_lo, 1.0, v3 src0_sel:WORD_0 src1_sel:WORD_1', 'neq', + lambda w: 1.0, lambda w: h2f(lane(w['v3'], 1)), 'vcc') + + # ---- integer packing ---- + for label, code, asm, ref in ( + ('v_cvt_pk_u16_u32 saturates', vop3(0x36a, 1, (v2, 128)), 'v_cvt_pk_u16_u32 v1, v2, 0', + lambda w: min(w['v2'], 0xffff)), + ('v_cvt_pk_u16_u32 two registers', vop3(0x36a, 1, (v2, v3)), 'v_cvt_pk_u16_u32 v1, v2, v3', + lambda w: min(w['v2'], 0xffff) | min(w['v3'], 0xffff) << 16), + ('v_mad_u32_u16 op_sel:[0,1,0]', vop3(0x373, 1, (v2, v3, v4), op_sel=(0, 1, 0, 0)), + 'v_mad_u32_u16 v1, v2, v3, v4 op_sel:[0,1,0]', + lambda w: ((w['v2'] & 0xffff) * (w['v3'] >> 16) + w['v4']) & 0xffffffff)): + got_asm, out = translate(code) + check(label + ' (decode)', got_asm == asm, 'got %r' % got_asm) + _reg, expr = statement(out) + rng = random.Random(label) + bad = [] + for _ in range(300): + words = {r: rng.choice([rng.getrandbits(32), rng.getrandbits(16), 0xffff, 0x10000]) + for r in ('v2', 'v3', 'v4')} + if evaluate(expr, words) != ref(words): + bad.append(words) + check(label + ': 300 evaluated words', not bad, out[0]) + lines.extend(out) + check('control: v_mad_u32_u16 without op_sel keeps its table text', + translate(vop3(0x373, 1, (v2, v3, v4)))[1] == ['v1 = (v2 & 0xffffu) * (v3 & 0xffffu) + v4;']) + + # ---- refusals ---- + def refused(label, code, round16=0): + try: + _a, out = translate(code, round16) + except G.Unsupported as e: + check(label + ' refused', True) + return str(e) + check(label + ' refused', False, repr(out)) + refused('v_pk_add_f16 under MODE f16 toward zero', vop3p(PK_ADD, 1, (v2, v3)), round16=3) + refused('v_sub_f16 under MODE f16 toward zero', vop2(0x33, 1, v2, 3), round16=3) + refused('v_pk_add_f16 high half of an inline constant', vop3p(PK_ADD, 1, (240, v3))) + refused('v_add_f16 1/(2*pi)', vop2(0x32, 1, 248, 3)) + refused('v_add_f16_sdwa dst_sel DWORD', sdwa2(0x32, 1, 2, 3, sel0='WORD_0', sel1='WORD_0', dst_sel='DWORD')) + refused('v_add_f16_e64 omod', vop3(0x132, 1, (v2, v3), omod=1)) + refused('v_cmp_lt_f16_sdwa BYTE_0', sdwac(0xc9, 2, 3, sel0='BYTE_0', sel1='WORD_1')) + return lines + + +def compile_lines(fxc, lines): + """Every translated statement in one vs_5_1 shader with the helpers it calls.""" + regs = sorted(set(re.findall(r'\b([vs]\d+|vcc)\b', ' '.join(lines)))) + helpers = [t for n, t in G.HELPERS.items() if any(re.search(r'\b%s\(' % n, l) for l in lines)] + body = ['#define F asfloat', '#define U asuint', 'cbuffer c : register(b0) { uint4 inp[4]; };'] + helpers + [ + 'float4 main(uint id : SV_VertexID) : SV_Position {', + ' uint exec = 1u; ' + ' '.join('uint %s = inp[%d].x ^ id;' % (r, i % 4) for i, r in enumerate(regs))] + body += [' { %s }' % l for l in lines] + body += [' return float4(F(%s), 0, 0, 1);' % ' ^ '.join(regs), '}'] + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, 'f16.hlsl') + with open(src, 'w') as fh: + fh.write('\n'.join(body) + '\n') + r = subprocess.run([fxc, '/nologo', '/T', 'vs_5_1', '/E', 'main', '/Fo', os.path.join(d, 'f16.cso'), src], + capture_output=True, text=True) + check('fxc vs_5_1 compiles all %d translated statements' % len(lines), r.returncode == 0, r.stderr[-1500:]) + + +def raw_fill(index): + # Keep in step with raw_uav_fill_word in tests/spirv_window/raw_uav_dump.cpp. + return ((index + 1) * 0x9E3779B1 & 0xffffffff) | 1 + + +def dispatch(fxc, runner, adapter, cases): + """The helpers on the device: per thread one triple, four result words: fma | add << 16, mul, plain.""" + runner = os.path.abspath(runner) + batch = 2048 + out_dir = os.path.join(here, '..', 'out') + os.makedirs(out_dir, exist_ok=True) + total = bad = plain_diff = 0 + with tempfile.TemporaryDirectory(dir=out_dir) as d: + for start in range(0, len(cases), batch): + chunk = cases[start:start + batch] + chunk += [(0, 0, 0)] * (batch - len(chunk)) + table = [] + for i, (a, b, c) in enumerate(chunk): + table += [raw_fill(4 * i) ^ (a | b << 16), raw_fill(4 * i + 1) ^ c] + src = '\n'.join([ + '#define F asfloat', '#define U asuint', 'RWByteAddressBuffer data : register(u0);', + G.HELPERS['x2w_f32tof16_rne'], G.HELPERS['x2w_f16_fma'], + 'static const uint T[%d] = {%s};' % (len(table), ', '.join('0x%08xu' % t for t in table)), + '[numthreads(1024, 1, 1)]', + 'void main(uint3 g : SV_GroupID, uint3 t : SV_GroupThreadID) {', + ' uint i = g.x * 1024u + t.x;', + ' uint ab = data.Load(16u * i) ^ T[2u * i], cw = data.Load(16u * i + 4u) ^ T[2u * i + 1u];', + ' float a = f16tof32(ab), b = f16tof32(ab >> 16), c = f16tof32(cw);', + ' uint fma = x2w_f32tof16_rne(x2w_f16_fma(a, b, c));', + ' uint add = x2w_f32tof16_rne(x2w_f16_fma(a, 1.0, c));', + ' uint mul = x2w_f32tof16_rne(a * b);', + ' precise float p = a * b; precise float s = p + c;', + ' data.Store(16u * i, fma | (add << 16)); data.Store(16u * i + 4u, mul);', + ' data.Store(16u * i + 8u, x2w_f32tof16_rne(s));', + '}']) + '\n' + hlsl, cso, out = (os.path.join(d, 'f16%s' % e) for e in ('.hlsl', '.cso', '.bin')) + with open(hlsl, 'w') as fh: + fh.write(src) + subprocess.run([fxc, '/nologo', '/T', 'cs_5_1', '/E', 'main', '/Fo', cso, hlsl], check=True, + capture_output=True) + run = subprocess.run([runner, adapter, '--raw-uav-dump', cso, '2', str(batch * 16), out], + 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 'raw UAV dump exited with %d' % run.returncode) + words = struct.unpack('<%dI' % (batch * 4), open(out, 'rb').read()) + for i, (a_bits, b_bits, c_bits) in enumerate(cases[start:start + batch]): + a, b, c = h2f(a_bits), h2f(b_bits), h2f(c_bits) + want = exact_f16(a, b, c) + want_add = exact_f16(a, 1.0, c) + want_mul = ref_f16('mul', a, b) + got_fma, got_add, got_mul = words[4 * i] & 0xffff, words[4 * i] >> 16, words[4 * i + 1] + total += 1 + if (got_fma, got_add, got_mul) != (want, want_add, want_mul): + bad += 1 + if bad <= 3: + print(' %04x %04x %04x: got %04x %04x %04x want %04x %04x %04x' + % (a_bits, b_bits, c_bits, got_fma, got_add, got_mul, want, want_add, want_mul)) + plain_diff += words[4 * i + 2] != want + check('%s: fma, add and mul words of %d triples equal the single rounding (fxc cs_5_1)' % (adapter, total), + bad == 0, '%d differ' % bad) + check('%s: control: the plain f32 a * b + c rounds differently in %d triples' % (adapter, plain_diff), + plain_diff > 0) + + +if __name__ == '__main__': + if len(sys.argv) not in (1, 3, 5) or (len(sys.argv) > 1 and sys.argv[1] not in ('fxc', 'dispatch')): + print(__doc__) + sys.exit(2) + translated = main_checks() + if len(sys.argv) == 3: + compile_lines(sys.argv[2], translated) + elif len(sys.argv) == 5: + dispatch(sys.argv[2], sys.argv[3], sys.argv[4], [tuple(c) for c in constructed()] + [ + (finite_f16(r), finite_f16(r), finite_f16(r)) for r in [random.Random(7)] for _ in range(14000)]) + if failures: + print('FAILED: %d check(s): %s' % (len(failures), ', '.join(failures))) + sys.exit(1) + print('all checks passed') diff --git a/tests/startup_gfx2hlsl_f32_lg_local_check.py b/tests/startup_gfx2hlsl_f32_lg_local_check.py new file mode 100644 index 0000000000..c642f52e61 --- /dev/null +++ b/tests/startup_gfx2hlsl_f32_lg_local_check.py @@ -0,0 +1,747 @@ +"""f32 VOPC conditions in tools/startup/gfx2hlsl.py, lg and nlg on NaN operands among them (#1920). + + (no arguments) translation controls, pure Python + binary <llvm-mc> assemble the decoded text of every checked form and of the pixel fixtures with + llvm-mc and compare with the words built here + decode <libLLVM> disassemble the same words with LLVM's C API and compare with + tools/disasm_rdna2.py + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the pixel fixtures with FXC ps_5_1 when given and with DXC ps_6_0, + draw 16 x 16 pixels each and compare every pixel with the ISA reference + (needs tests/offscreen_check.cpp built as offscreen_check) + +In the gfx10 ISA V_CMP_LG_F32 is "less or greater": ordered and not equal, false when either source is NaN. +V_CMP_NLG_F32 is its negation, true when either source is NaN. HLSL != is unordered (true with a NaN), so the old +lowering `a != b` and `!(a != b)` gave the opposite result whenever a source was NaN. The lowering is now +`(ORDERED && (a < b || a > b))` and its negation, ORDERED testing both source words for NaN on their bits: DXC +marks float compares fast unless -Gis, and the draw records whether the same text without the bit test holds. + +The reference is written here from the ISA definitions with integer arithmetic on the bit patterns: a NaN is an +exponent of all ones with a non-zero mantissa; ordered sources compare by sign and magnitude, with +0 equal to -0 and +denormals kept; lt, eq, le, gt, lg and ge are false when a source is NaN; the n-forms are their negations; o is both +sources ordered and u either unordered; f and t are constant. + +Controls: every f32 condition in the compare table (v_cmp and v_cmpx; the e32 form and the e64 form under every +neg/abs combination on both sources) is decoded from words built here, translated, and the emitted HLSL is evaluated +on the CPU with IEEE binary32 comparisons over every pair of 16 source words: +-0, +-min denormal, +-1.0, +-max +finite, +-inf, +-quiet NaN, +-signalling NaN and +-NaN with a payload. The same forms with the old `!=` lowering +restored must disagree with the reference. The f32 SDWA compares stay refused. + +The draws: a source-built pixel program builds one of those 16 words from the pixel's x and one from its y with +integer operations, so 16 x 16 pixels cover every pair: finite unequal, equal (+0 and -0 among them), infinite and +NaN sources. Fixture `cmp` writes four v_cmp results as 1.0 or 0.0: v_cmp_lg_f32_e32, v_cmp_nlg_f32_e64 (-a, |b|), +v_cmp_lg_f32_e64 (-|a|, -b) and v_cmp_nlg_f32_e32. Each `cmpx_*` fixture keeps a pixel when its v_cmpx form holds +and exports the packed position; a discarded pixel keeps the clear value -1.0. D3D lets a backend flush binary32 +denormal sources of a compare to signed zero, so every fixture must match the reference image with denormals kept +or the one with them flushed, the same choice for all fixtures of one compiler and adapter. Each translation with +the old `!=` lowering restored must fail its draw against both images and match its own image. +""" +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_flat_param_check import assemble # noqa: E402 +from startup_gfx2hlsl_vopc_sdwa_check import COMPARES, Probe, source, vopc_sdwa # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +MASK = 0xffffffff +SIGN = 0x80000000 +SGPR_DST = 6 +# The 16 source words: each class with the sign bit clear and set. +CLASSES = [0x00000000, 0x00000001, 0x3f800000, 0x7f7fffff, 0x7f800000, 0x7fc00000, 0x7f800001, 0x7fc12345] +VALUES = [c | sign for c in CLASSES for sign in (0, SIGN)] +PAIRS = [(a, b) for a in VALUES for b in VALUES] +# Every f32 condition the compare table lowers; v_cmp_class_f32 and v_cmp_tru_f32 stay refused. +F32_OPS = sorted(op for op, (_, cond, typ) in COMPARES.items() if typ == 'f32' and cond not in ('class', 'tru')) +MODIFIERS = [(neg, absolute) for neg in (False, True) for absolute in (False, True)] + + +# ---- the ISA reference, on bit patterns ------------------------------------------------------------------------- +def is_nan(bits): + return (bits & 0x7fffffff) > 0x7f800000 + + +def key(bits): + """Order of an ordered binary32 word: sign and magnitude, +0 and -0 equal, denormals kept.""" + magnitude = bits & 0x7fffffff + return -magnitude if bits & SIGN else magnitude + + +def modified(bits, neg, absolute): + """The VOP3/SDWA source modifiers: abs clears the sign bit, then neg flips it.""" + if absolute: + bits &= 0x7fffffff + return bits ^ SIGN if neg else bits + + +ORDERED = {'lt': lambda x, y: x < y, 'eq': lambda x, y: x == y, 'le': lambda x, y: x <= y, + 'gt': lambda x, y: x > y, 'lg': lambda x, y: x != y, 'ge': lambda x, y: x >= y} + + +def reference(cond, a, b): + unordered = is_nan(a) or is_nan(b) + if cond in ('f', 't'): + return int(cond == 't') + if cond in ('o', 'u'): + return int(unordered == (cond == 'u')) + if cond in ORDERED: + return int(not unordered and ORDERED[cond](key(a), key(b))) + assert cond[0] == 'n' and cond[1:] in ORDERED, cond + return 1 - reference(cond[1:], a, b) + + +def old_reference(cond, a, b): + """The lowering before #1920: lg as unordered not-equal, nlg its negation.""" + if cond in ('lg', 'nlg'): + ne = is_nan(a) or is_nan(b) or key(a) != key(b) + return int(ne != (cond == 'nlg')) + return reference(cond, a, b) + + +# ---- a small evaluator for the compare HLSL the lowering emits (uint words, binary32 floats, bools) ------------- +TOKEN = re.compile(r'\s*(0x[0-9a-fA-F]+u?|\d+\.\d+|\d+u?|[A-Za-z_]\w*|<=|>=|==|!=|\|\||&&|[-&!<>?:(),])') +LEVELS = [['||'], ['&&'], ['&'], ['==', '!='], ['<', '>', '<=', '>=']] + + +def as_float(word): + return struct.unpack('<f', struct.pack('<I', word))[0] + + +class Expr: + """Values are ('u', int) for uint words, ('f', float) for binary32 and ('b', 0|1) for bools. Python float + comparisons follow IEEE 754: every ordered relation is false with a NaN and != is true.""" + + def __init__(self, text): + self.tokens = TOKEN.findall(text) + assert ''.join(self.tokens) == re.sub(r'\s+', '', text), text + self.pos = 0 + self.tree = self.ternary() + assert self.pos == len(self.tokens), text + + def peek(self): + return self.tokens[self.pos] if self.pos < len(self.tokens) else None + + def take(self): + self.pos += 1 + return self.tokens[self.pos - 1] + + def ternary(self): + cond = self.binary(0) + if self.peek() != '?': + return cond + self.take() + yes = self.ternary() + assert self.take() == ':' + return ('?', cond, yes, self.ternary()) + + def binary(self, level): + if level == len(LEVELS): + return self.unary() + node = self.binary(level + 1) + while self.peek() in LEVELS[level]: + node = (self.take(), node, self.binary(level + 1)) + return node + + def unary(self): + token = self.take() + if token in ('-', '!'): + return ('u' + token, self.unary()) + if token == '(': + node = self.ternary() + assert self.take() == ')' + return node + if '.' in token: + return ('const', ('f', float(token))) + if token[0].isdigit(): + return ('const', ('u', int(token.rstrip('u'), 0) & MASK)) + if token in ('true', 'false'): + return ('const', ('b', int(token == 'true'))) + if self.peek() != '(': + return ('var', token) + self.take() + args = [self.ternary()] + while self.peek() == ',': + self.take() + args.append(self.ternary()) + assert self.take() == ')' + return ('call', token, args) + + def run(self, env, node=None): + return self.eval(env, node or self.tree)[1] + + def eval(self, env, node): + kind = node[0] + if kind == 'const': + return node[1] + if kind == 'var': + return 'u', env[node[1]] + if kind == '?': + return self.eval(env, node[2] if self.truth(self.eval(env, node[1])) else node[3]) + if kind == 'call': + (k, v), = [self.eval(env, a) for a in node[2]] + if node[1] in ('F', 'asfloat'): + assert k == 'u' + return 'f', as_float(v) + assert node[1] == 'abs' and k == 'f', node + return 'f', math.fabs(v) + if kind == 'u-': + k, v = self.eval(env, node[1]) + assert k == 'f' + return 'f', -v + if kind == 'u!': + return 'b', int(not self.truth(self.eval(env, node[1]))) + if kind in ('||', '&&'): + a = self.truth(self.eval(env, node[1])) + b = self.truth(self.eval(env, node[2])) + return 'b', int(a or b) if kind == '||' else int(a and b) + (ka, a), (kb, b) = self.eval(env, node[1]), self.eval(env, node[2]) + if kind == '&': + assert 'f' not in (ka, kb) + return 'u', a & b + assert ka == kb and ka in ('f', 'u'), node + return 'b', int({'==': a == b, '!=': a != b, '<': a < b, '>': a > b, '<=': a <= b, '>=': a >= b}[kind]) + + @staticmethod + def truth(value): + kind, v = value + assert kind in ('b', 'u'), value + return v != 0 + + +# ---- encoding --------------------------------------------------------------------------------------------------- +VGPR = 256 +VCC_LO = 106 +INLINE = {0: 128, 1: 129, 15: 143, 16: 144, 31: 159, 0x3f800000: 242} # integers and 1.0 + + +def operand(value): + """(source code, literal or None) of a 32-bit constant.""" + if value in INLINE: + return INLINE[value], None + if 1 <= value <= 64: + return 128 + value, None + return 255, value + + +def vop1_mov(vdst, value): + code, literal = operand(value) + return struct.pack('<I', (0x3f << 25) | (vdst << 17) | (0x01 << 9) | code) + ( + struct.pack('<I', literal) if literal is not None else b'') + + +def vop2(op, vdst, src0, vsrc1): + """src0 is a constant (int) or ('v', n).""" + if isinstance(src0, tuple): + code, literal = VGPR + src0[1], None + else: + code, literal = operand(src0) + return struct.pack('<I', (op << 25) | (vdst << 17) | (vsrc1 << 9) | code) + ( + struct.pack('<I', literal) if literal is not None else b'') + + +V_CNDMASK, V_LSHRREV, V_LSHLREV, V_AND, V_XOR = 0x01, 0x16, 0x1a, 0x1b, 0x1d +V_CMP_NE_U32 = 0xc5 + + +def vopc_e32(op, src0, vsrc1): + """src0 is a constant (int) or ('v', n); vsrc1 a VGPR number.""" + code = VGPR + src0[1] if isinstance(src0, tuple) else operand(src0)[0] + return struct.pack('<I', (0b0111110 << 25) | (op << 17) | (vsrc1 << 9) | code) + + +def vop3_compare(op, sdst, src0, src1, neg=(False, False), absolute=(False, False)): + """VOP3 compare of two VGPRs. A v_cmpx keeps sdst 0, as llvm-mc encodes it for gfx10.""" + w0 = (0b110101 << 26) | (op << 16) | ((absolute[0] | absolute[1] << 1) << 8) | sdst + w1 = (VGPR + src0) | ((VGPR + src1) << 9) | ((neg[0] | neg[1] << 1) << 29) + return struct.pack('<II', w0, w1) + + +def cndmask_e64(vdst, mask): + """v_cndmask_b32_e64 vdst, 0, 1.0, mask: 1.0 where the lane's bit of mask is set.""" + return struct.pack('<II', (0b110101 << 26) | (0x101 << 16) | vdst, 128 | (242 << 9) | (mask << 18)) + + +def compare_code(op, form, mods=((False, False), (False, False))): + """One compare of v1 and v2. form is 'e32' (vcc_lo or EXEC) or 'e64' (s6, or EXEC for v_cmpx).""" + cmpx = COMPARES[op][0] + (neg0, abs0), (neg1, abs1) = mods + if form == 'e32': + return vopc_e32(op, ('v', 1), 2) + return vop3_compare(op, 0 if cmpx else SGPR_DST, 1, 2, (neg0, neg1), (abs0, abs1)) + + +def all_forms(): + """(op, form, mods, destination) for every checked compare form.""" + for op in F32_OPS: + cmpx = COMPARES[op][0] + yield op, 'e32', ((False, False), (False, False)), 'exec' if cmpx else 'vcc' + for mods in ((m, n) for m in MODIFIERS for n in MODIFIERS): + yield op, 'e64', mods, 'exec' if cmpx else 'sgpr' + + +def llvm_text(asm): + """tools/disasm_rdna2.py prints the unused sdst field of a gfx10 v_cmpx_*_e64; LLVM 15 prints no sdst there.""" + return re.sub(r'^(v_cmpx_\w+_e64) s0, ', r'\1 ', asm) + + +# ---- translation ------------------------------------------------------------------------------------------------ +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 decode_one(code): + decoded = G.decode(code) + assert len(decoded) == 1 and decoded[0][1] == len(code), decoded + return decoded[0][2], decoded[0][3] + + +def translate(code, exec_known=True): + name, asm = decode_one(code) + stage = Probe(exec_known) + stage.one(name, asm) + return asm, stage + + +# The new lg text, `(ORDERED && (X < Y || X > Y))` with ORDERED the bit test of both source words, and the old one, +# `(X != Y)`: X and Y are F(vN) under optional abs() and negation, so neither holds a ' < ', ' > ' or '||'. +ORDERED_TEXT = r'\((?P<w{0}>\w+) & 0x7fffffffu\) <= 0x7f800000u' +LG_TEXT = re.compile(r'\(%s && %s && \((?P<x>[^<>|]+?) < (?P<y>[^<>|]+?) \|\| (?P=x) > (?P=y)\)\)' % ( + ORDERED_TEXT.format(0), ORDERED_TEXT.format(1))) + + +def old_lowering(text): + """The same text with lg and nlg lowered as before #1920.""" + return LG_TEXT.sub(lambda m: '(%s != %s)' % (m.group('x'), m.group('y')), text) + + +def unguarded(text): + """lg as less or greater without the bit test: exact in HLSL, not under DXC's fast compares on every driver.""" + return LG_TEXT.sub(lambda m: '(%s < %s || %s > %s)' % (m.group('x'), m.group('y'), m.group('x'), m.group('y')), + text) + + +def first_mismatch(expr, cond, mods, model=reference): + (neg0, abs0), (neg1, abs1) = mods + for a, b in PAIRS: + want = model(cond, modified(a, neg0, abs0), modified(b, neg1, abs1)) + got = expr.run({'v1': a, 'v2': b}) + if got != want: + return a, b, got, want + return None + + +# The lowering of every other condition before #1920, for v_cmp_*_f32_e32 vcc_lo, v1, v2. nlt, nle, ngt, nge, o and u +# changed with #1936 and are checked in tests/startup_gfx2hlsl_f32_nan_check.py. +UNCHANGED = {'f': 'false', 'lt': 'F(v1) < F(v2)', 'eq': 'F(v1) == F(v2)', 'le': 'F(v1) <= F(v2)', + 'gt': 'F(v1) > F(v2)', 'ge': 'F(v1) >= F(v2)', 'neq': '!(F(v1) == F(v2))'} +NAN_FORMS = ('nlt', 'nle', 'ngt', 'nge', 'o', 'u') + + +def controls(): + # 1. The value set and the reference. + check('16 source words: +-0, +-min denormal, +-1.0, +-max finite, +-inf, +-quiet, signalling and payload NaN', + len(set(VALUES)) == 16 and sum(map(is_nan, VALUES)) == 6 + and sum(math.isnan(as_float(v)) for v in VALUES) == 6 + and {as_float(v) for v in VALUES if not is_nan(v)} == {0.0, 2.0 ** -149, -2.0 ** -149, 1.0, -1.0, + as_float(0x7f7fffff), -as_float(0x7f7fffff), + math.inf, -math.inf}) + ordered = [(a, b) for a, b in PAIRS if not is_nan(a) and not is_nan(b)] + check('reference: the ordered relations match IEEE binary32 on every ordered pair', all( + reference(cond, a, b) == int(ORDERED[cond](as_float(a), as_float(b))) for cond in ORDERED for a, b in ordered)) + check('reference: +0 and -0 are equal, the min denormals are not', + reference('eq', 0, SIGN) and not reference('lg', 0, SIGN) and reference('lg', 1, SIGN | 1) + and reference('lt', SIGN | 1, 0)) + nan_pairs = [(a, b) for a, b in PAIRS if is_nan(a) or is_nan(b)] + check('reference: %d pairs with a NaN: lg false, nlg true, u true, o false' % len(nan_pairs), all( + (reference('lg', a, b), reference('nlg', a, b), reference('u', a, b), reference('o', a, b)) == (0, 1, 1, 0) + for a, b in nan_pairs)) + check('reference: the old lowering differs on exactly the NaN pairs', all( + (old_reference(cond, a, b) != reference(cond, a, b)) == (is_nan(a) or is_nan(b)) + for cond in ('lg', 'nlg') for a, b in PAIRS)) + check('every f32 condition of the table is checked (%d opcodes)' % len(F32_OPS), len(F32_OPS) == 30 and sorted( + {COMPARES[op][1] for op in F32_OPS}) == sorted(set(UNCHANGED) | {'lg', 'nlg'} | set(NAN_FORMS))) + + # 2. The new lowering's text; every other condition keeps its text. + asm, stage = translate(compare_code(0x05, 'e32')) + ordered = '(v1 & 0x7fffffffu) <= 0x7f800000u && (v2 & 0x7fffffffu) <= 0x7f800000u' + check('v_cmp_lg_f32_e32: %s' % stage.lines, stage.lines == [ + 'vcc = (((%s && (F(v1) < F(v2) || F(v1) > F(v2)))) ? 1u : 0u);' % ordered]) + asm, stage = translate(compare_code(0x0a, 'e32')) + check('v_cmp_nlg_f32_e32: %s' % stage.lines, stage.lines == [ + 'vcc = ((!(%s && (F(v1) < F(v2) || F(v1) > F(v2)))) ? 1u : 0u);' % ordered]) + asm, stage = translate(compare_code(0x1a, 'e64', ((True, True), (False, True)))) + check('v_cmpx_nlg_f32_e64 tests the words under the modifiers: %s' % stage.lines, stage.lines == [ + 'exec = ((!(%s && ((-abs(F(v1))) < abs(F(v2)) || (-abs(F(v1))) > abs(F(v2))))) ? 1u : 0u);' % ordered]) + changed = [] + for op in F32_OPS: + cmpx, cond, _ = COMPARES[op] + if cmpx or cond in ('lg', 'nlg') + NAN_FORMS: + continue + asm, stage = translate(compare_code(op, 'e32')) + if stage.lines != ['vcc = ((%s) ? 1u : 0u);' % UNCHANGED[cond]]: + changed.append((asm, stage.lines)) + check('the %d other conditions keep their lowering' % len(UNCHANGED), not changed, str(changed)) + + # 3. Every form of every condition equals the reference on every pair; the old lg/nlg lowering does not. + forms = evaluations = 0 + wrong, caught, missed, first = [], 0, [], None + for op, form, mods, destination in all_forms(): + cmpx, cond, _ = COMPARES[op] + asm, stage = translate(compare_code(op, form, mods)) + target = {'exec': 'exec', 'vcc': 'vcc', 'sgpr': 's%d' % SGPR_DST}[destination] + if (len(stage.lines) != 1 or not stage.lines[0].startswith(target + ' = ') + or (destination == 'sgpr') != (SGPR_DST in stage.masks) or stage.exec_known == cmpx): + wrong.append((asm, stage.lines, 'destination')) + continue + text = stage.lines[0][len(target) + 3:-1] + forms += 1 + evaluations += len(PAIRS) + miss = first_mismatch(Expr(text), cond, mods) + if miss: + wrong.append((asm, ['%08x' % miss[0], '%08x' % miss[1]], miss[2:])) + if cond in ('lg', 'nlg'): + # Under IEEE comparisons the bit test changes nothing; it is there for fast compares. + loose = unguarded(text) + if loose == text or first_mismatch(Expr(loose), cond, mods): + wrong.append((asm, 'without the bit test', loose)) + old = old_lowering(text) + miss = first_mismatch(Expr(old), cond, mods) if old != text else None + if miss and not first_mismatch(Expr(old), cond, mods, old_reference): + caught += 1 + first = first or '%s with %s: a=%08x b=%08x gives %d, the ISA %d' % (asm, old, *miss) + else: + missed.append(asm) + check('%d f32 forms x %d pairs (%d evaluations) equal the ISA reference' % (forms, len(PAIRS), evaluations), + not wrong and forms == len(F32_OPS) * 17, str(wrong[:3])) + check('old != lowering fails %d of %d lg/nlg forms against the reference and matches its own model' % ( + caught, caught + len(missed)), caught == 4 * 17 and not missed, str(missed[:3])) + print(' first: ' + str(first)) + + # 4. EXEC already reduced: the compare result is masked by the lane's EXEC bit. + wrong = [] + for op in F32_OPS: + cmpx, cond, _ = COMPARES[op] + if cond not in ('lg', 'nlg'): + continue + for form in ('e32', 'e64'): + mods = ((True, False), (False, True)) + asm, stage = translate(compare_code(op, form, mods), exec_known=False) + expr = Expr(stage.lines[0].split(' = ', 1)[1][:-1]) + for a, b in PAIRS: + for lane in (0, 1): + want = lane & reference(cond, modified(a, True, False), modified(b, False, True)) + if form == 'e32': + want = lane & reference(cond, a, b) + if expr.run({'v1': a, 'v2': b, 'exec': lane}) != want: + wrong.append((asm, hex(a), hex(b), lane)) + check('inactive lane: lg/nlg results masked by EXEC in the e32 and e64 forms', not wrong, str(wrong[:3])) + + # 5. The f32 SDWA compares stay refused (#1906): lg and nlg, v_cmp and v_cmpx, with and without modifiers. + refused = [] + for op in F32_OPS: + cmpx, cond, _ = COMPARES[op] + if cond not in ('lg', 'nlg'): + continue + for neg, absolute in MODIFIERS: + name, asm = decode_one(vopc_sdwa(op, source('v', 1, neg=neg, absolute=absolute), source('v', 2), + None if cmpx else SGPR_DST)) + try: + Probe().one(name, asm) + refused.append((asm, None)) + except G.Unsupported as error: + refused.append((asm, str(error))) + check('f32 SDWA lg/nlg compares stay refused (%d forms)' % len(refused), len(refused) == 16 and all( + error == '%s: f32 SDWA compares are not lowered' % asm.split()[0] for asm, error in refused), str(refused[:3])) + + +# ---- the pixel fixtures ----------------------------------------------------------------------------------------- +WIDTH = HEIGHT = 16 +CLEAR = 0xbf800000 # -1.0, the target's clear value: a discarded pixel keeps it +ONE = 0x3f800000 +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 + + +def build_value(dst, index): + """dst = CLASSES[index >> 1] with the sign bit (index & 1), from integer operations; v5 is scratch.""" + text = 'v_lshrrev_b32_e32 v5, 1, v%d\nv_mov_b32_e32 v%d, 0\n' % (index, dst) + words = vop2(V_LSHRREV, 5, 1, index) + vop1_mov(dst, 0) + for k in range(1, 8): + constant = {1: '1', ONE: '1.0'}.get(CLASSES[k], '0x%x' % CLASSES[k]) + text += 'v_cmp_ne_u32_e32 vcc_lo, %d, v5\nv_cndmask_b32_e32 v%d, %s, v%d, vcc_lo\n' % (k, dst, constant, dst) + words += vopc_e32(V_CMP_NE_U32, k, 5) + vop2(V_CNDMASK, dst, CLASSES[k], dst) + text += 'v_lshlrev_b32_e32 v5, 31, v%d\nv_xor_b32_e32 v%d, v%d, v5\n' % (index, dst, dst) + words += vop2(V_LSHLREV, 5, 31, index) + vop2(V_XOR, dst, ('v', dst), 5) + return text, words + + +def prologue(): + """v3 = VALUES[x], v4 = VALUES[y] for the packed position x | y << 16 in v0.""" + text = 'v_and_b32_e32 v1, 15, v0\nv_lshrrev_b32_e32 v2, 16, v0\n' + words = vop2(V_AND, 1, 15, 0) + vop2(V_LSHRREV, 2, 16, 0) + for dst, index in ((3, 1), (4, 2)): + t, w = build_value(dst, index) + text, words = text + t, words + w + return text, words + + +EXPORT_PACKED = ('exp mrt0 v0, v0, v0, v0 done vm\ns_endpgm\n', struct.pack('<III', 0xf800180f, 0, 0xbf810000)) +NEG, ABS = (True, False), (False, True) +NEG_ABS, PLAIN = (True, True), (False, False) +# name -> (body text, body words, [(condition, src0 modifiers, src1 modifiers)] per exported word, or one for v_cmpx) +FIXTURES = { + 'cmp': ( + 'v_cmp_lg_f32_e32 vcc_lo, v3, v4\nv_cndmask_b32_e64 v6, 0, 1.0, vcc_lo\n' + 'v_cmp_nlg_f32_e64 s6, -v3, |v4|\nv_cndmask_b32_e64 v7, 0, 1.0, s6\n' + 'v_cmp_lg_f32_e64 s8, -|v3|, -v4\nv_cndmask_b32_e64 v8, 0, 1.0, s8\n' + 'v_cmp_nlg_f32_e32 vcc_lo, v3, v4\nv_cndmask_b32_e64 v9, 0, 1.0, vcc_lo\n' + 'exp mrt0 v6, v7, v8, v9 done vm\ns_endpgm\n', + vopc_e32(0x05, ('v', 3), 4) + cndmask_e64(6, VCC_LO) + + vop3_compare(0x0a, 6, 3, 4, (True, False), (False, True)) + cndmask_e64(7, 6) + + vop3_compare(0x05, 8, 3, 4, (True, True), (True, False)) + cndmask_e64(8, 8) + + vopc_e32(0x0a, ('v', 3), 4) + cndmask_e64(9, VCC_LO) + + struct.pack('<III', 0xf800180f, 0x09080706, 0xbf810000), + [('lg', PLAIN, PLAIN), ('nlg', NEG, ABS), ('lg', NEG_ABS, NEG), ('nlg', PLAIN, PLAIN)]), + 'cmpx_lg_e32': ('v_cmpx_lg_f32_e32 v3, v4\n', vopc_e32(0x15, ('v', 3), 4), [('lg', PLAIN, PLAIN)]), + 'cmpx_nlg_e32': ('v_cmpx_nlg_f32_e32 v3, v4\n', vopc_e32(0x1a, ('v', 3), 4), [('nlg', PLAIN, PLAIN)]), + 'cmpx_lg_e64': ('v_cmpx_lg_f32_e64 -v3, |v4|\n', vop3_compare(0x15, 0, 3, 4, (True, False), (False, True)), + [('lg', NEG, ABS)]), + 'cmpx_nlg_e64': ('v_cmpx_nlg_f32_e64 |v3|, -v4\n', vop3_compare(0x1a, 0, 3, 4, (False, True), (True, False)), + [('nlg', ABS, NEG)]), +} + + +def classify(a, b): + """The kind of a source pair: 'nan' when either is NaN, else 'equal' or 'unequal'.""" + if is_nan(a) or is_nan(b): + return 'nan' + return 'equal' if key(a) == key(b) else 'unequal' + + +def fixture(name): + """(source text, words) of one pixel program.""" + head_text, head_words = prologue() + body_text, body_words, _ = FIXTURES[name] + if name.startswith('cmpx'): + body_text, body_words = body_text + EXPORT_PACKED[0], body_words + EXPORT_PACKED[1] + return head_text + body_text, head_words + body_words + + +def flushed(bits): + """A binary32 denormal flushed to zero of the same sign; other words unchanged.""" + return bits & SIGN if bits & 0x7f800000 == 0 else bits + + +DENORMALS = ('ieee', 'flushed') + + +def image(name, model=reference, denormals='ieee'): + """The expected target words. D3D lets a backend flush binary32 denormal sources of a compare to signed zero; + denormals='flushed' is that image.""" + words = [] + results = FIXTURES[name][2] + prepare = flushed if denormals == 'flushed' else (lambda bits: bits) + for y in range(HEIGHT): + for x in range(WIDTH): + a, b = VALUES[x], VALUES[y] + got = [model(cond, prepare(modified(a, *m0)), prepare(modified(b, *m1))) for cond, m0, m1 in results] + if name == 'cmp': + words += [ONE if r else 0 for r in got] + else: + words += [x | y << 16] * 4 if got[0] else [CLEAR] * 4 + return words + + +def pixel_hlsl(name, old=False): + text = G.Pipeline(VS_WORDS, fixture(name)[1], root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + if old: + mutated = old_lowering(text) + assert mutated.count('!=') - text.count('!=') == len(FIXTURES[name][2]), (name, mutated) + text = mutated + return text + + +def check_fixtures(): + for name in FIXTURES: + text, words = fixture(name) + decoded = [llvm_text(asm) for _o, _s, _n, asm in G.decode(words)] + check('%s: fixture decodes to its source (%d instructions)' % (name, len(decoded)), + decoded == text.splitlines(), str([(a, b) for a, b in zip(decoded, text.splitlines()) if a != b][:3])) + hlsl = pixel_hlsl(name) + check('%s: %d lg/nlg compares lowered as less or greater' % (name, len(FIXTURES[name][2])), + len(LG_TEXT.findall(hlsl)) == len(FIXTURES[name][2]) and ' != F(' not in hlsl) + # What the image asserts, per result: lg is 1 on finite or infinite unequal sources and 0 on equal ones + # and on every NaN pair; nlg is the opposite. + for index, (cond, m0, m1) in enumerate(FIXTURES[name][2]): + seen = {} + for b in VALUES: + for a in VALUES: + a2, b2 = modified(a, *m0), modified(b, *m1) + seen.setdefault(classify(a2, b2), set()).add(reference(cond, a2, b2)) + want = {'unequal': {1}, 'equal': {0}, 'nan': {0}} if cond == 'lg' else { + 'unequal': {0}, 'equal': {1}, 'nan': {1}} + counts = {kind: sum(classify(modified(a, *m0), modified(b, *m1)) == kind for a, b in PAIRS) + for kind in ('unequal', 'equal', 'nan')} + check('%s result %d (%s): unequal -> %d, equal -> %d, NaN -> %d; pixels %s' % ( + name, index, cond, *(min(want[k]) for k in ('unequal', 'equal', 'nan')), counts), seen == want, + str(seen)) + for denormals in DENORMALS: + good, bad = image(name, denormals=denormals), image(name, old_reference, denormals) + differing = sum(good[i:i + 4] != bad[i:i + 4] for i in range(0, len(good), 4)) + check('%s (%s denormals): the old lowering changes %d of %d pixels' % ( + name, denormals, differing, WIDTH * HEIGHT), differing == 156) + ieee, flush = image(name), image(name, denormals='flushed') + differing = [(i // 4 % WIDTH, i // 4 // WIDTH) for i in range(0, len(ieee), 4) + if ieee[i:i + 4] != flush[i:i + 4]] + check('%s: flushing denormals changes %d pixels, each with a denormal source and no NaN' % ( + name, len(differing)), bool(differing) and all( + any(VALUES[c] & 0x7f800000 == 0 and VALUES[c] & 0x7fffff for c in (x, y)) + and not is_nan(VALUES[x]) and not is_nan(VALUES[y]) for x, y in differing)) + good = ieee + if name != 'cmp': + kept = sum(good[i] != CLEAR for i in range(0, len(good), 4)) + check('%s: reference keeps %d of %d pixels' % (name, kept, WIDTH * HEIGHT), 0 < kept < WIDTH * HEIGHT) + # The evaluator on each pixel stage's compare lines reads the same decisions as the images. + for name in FIXTURES: + for old in (False, True): + lines = [ln.strip() for ln in pixel_hlsl(name, old).splitlines() + if re.match(r'\s*(vcc|exec|s6|s8) = .*F\(v3\)', ln)] + model = old_reference if old else reference + results = FIXTURES[name][2] + ok = len(lines) == len(results) + for line, (cond, m0, m1) in zip(lines, results): + expr = Expr(line.split(' = ', 1)[1][:-1]) + ok = ok and all(expr.run({'v3': a, 'v4': b}) == model(cond, modified(a, *m0), modified(b, *m1)) + for a, b in PAIRS) + check('%s%s: evaluated compares equal the %s' % (name, ' (old)' if old else '', + 'old model' if old else 'ISA reference'), ok, str(lines)) + + +def all_codes(): + return [compare_code(op, form, mods) for op, form, mods, _ in all_forms()] + + +def check_binary(llvm_mc): + codes = all_codes() + source_text = ''.join(llvm_text(decode_one(code)[1]) + '\n' for code in codes) + built = assemble(llvm_mc, source_text) + check('llvm-mc assembles %d decoded f32 compare forms to the same words' % len(codes), built == b''.join(codes)) + for name in FIXTURES: + text, words = fixture(name) + check('llvm-mc assembles the %s fixture to the same words' % name, assemble(llvm_mc, text) == words) + + +def check_decode(library): + from pixel_aot import disassemble + codes = all_codes() + texts = disassemble(b''.join(codes), library) + ours = [llvm_text(decode_one(code)[1]) for code in codes] + wrong = [(a, b) for a, b in zip(texts, ours) if a != b] + check('LLVM disassembles %d f32 compare forms as tools/disasm_rdna2.py does' % len(codes), + len(texts) == len(codes) and not wrong, str(wrong[:3])) + for name in FIXTURES: + text, words = fixture(name) + check('LLVM disassembles the %s fixture as its source' % name, disassemble(words, library) == text.splitlines()) + + +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(77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + """Each fixture must match the ISA image with denormals kept or flushed (the same choice for every fixture of + one compiler and adapter); the old != lowering must match neither and must match its own image.""" + 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, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + modes = set() + for name in FIXTURES: + files = {d: words_file(directory, '%s_%s' % (name, d), image(name, denormals=d)) for d in DENORMALS} + ps = compile_hlsl(compiler, kind, pixel_hlsl(name), 'ps_%s_%s' % (name, kind), ps_profile, directory) + matched, report = None, [] + for denormals in DENORMALS: + run = draw(renderer, adapter, vs, ps, files[denormals]) + report.append(run.stdout + run.stderr) + if run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout: + matched = denormals + break + print(' ' + ' '.join(ln for ln in run.stdout.splitlines() + if ln.startswith(('backend=', 'adapter=', 'driver=', 'debug_errors=')))) + modes.add(matched) + check('%s %s %s: all %d pixels match the ISA reference (%s denormals)' % ( + kind, adapter, name, WIDTH * HEIGHT, matched), matched is not None, '\n'.join(report)) + bad = compile_hlsl(compiler, kind, pixel_hlsl(name, old=True), 'ps_%s_old_%s' % (name, kind), + ps_profile, directory) + for denormals in DENORMALS: + run = draw(renderer, adapter, vs, bad, files[denormals]) + lines = [ln for ln in run.stderr.splitlines() if 'pixel' in ln] + check('%s %s %s old != lowering fails against the %s image: %s' % ( + kind, adapter, name, denormals, ' / '.join(lines)), + run.returncode != 0 and lines and lines[0].startswith('pixel mismatch'), + run.stdout + run.stderr) + own = words_file(directory, name + '_old', image(name, old_reference, matched or 'ieee')) + run = draw(renderer, adapter, vs, bad, own) + check('%s %s %s old != lowering matches its own image' % (kind, adapter, name), + run.returncode == 0, run.stdout + run.stderr) + # Recorded, not checked: the same less-or-greater without the bit test of the source words. + loose = compile_hlsl(compiler, kind, unguarded(pixel_hlsl(name)), 'ps_%s_loose_%s' % (name, kind), + ps_profile, directory) + run = draw(renderer, adapter, vs, loose, files[matched or 'ieee']) + print(' recorded: %s %s %s without the NaN bit test: %s' % (kind, adapter, name, ' / '.join( + ln for ln in (run.stdout + run.stderr).splitlines() if 'pixel' in ln))) + check('%s %s: one denormal behaviour across the fixtures: %s' % (kind, adapter, sorted(map(str, modes))), + len(modes) == 1 and None not in modes) + +def main(): + if len(sys.argv) == 1: + controls() + check_fixtures() + else: + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'decode': + check_decode(*args) + elif mode == 'draw': + check_fixtures() + 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_ldexp_check.py b/tests/startup_gfx2hlsl_ldexp_check.py new file mode 100644 index 0000000000..c018e3a06e --- /dev/null +++ b/tests/startup_gfx2hlsl_ldexp_check.py @@ -0,0 +1,136 @@ +"""v_ldexp_f32 in draw stages: D = S0 * 2^S1 (S1 a signed 32-bit integer), under the launch FLOAT_MODE the lowering +matches (f32 denormals flushed on input and output, see Stage.LAUNCH_DENORM). + +usage: startup_gfx2hlsl_ldexp_check.py [fxc] + +Pure Python: the emitted statement for VOP2 and VOP3 (source neg/abs, clamp, omod) and the helper x2w_ldexp evaluated +on its integer text against an exact rational reference over normal, denormal, zero, infinity and NaN inputs and +exponents at the overflow and underflow boundaries and at the int32 extremes. Controls: a modifier on the exponent +operand refuses; HLSL ldexp(x, float(e)) (the naive form) fails the reference on the extremes. With fxc given, a vs_5_1 +stage compiles. Assumed, not measured: NaN inputs keep their bits (no quieting), and a result below 2^-126 is flushed +before rounding (only n == 0 with an all-ones mantissa could round up to 2^-126). +""" +import math +import os +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction + +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')) +sys.path.insert(0, here) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Probe # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print('%s: %s' % (label, 'ok' if condition else 'MISMATCH')) + if not condition: + failures.append(label) + if detail: + print(' ' + str(detail)[:1500]) + + +def lower(line): + stage = Probe() + stage.one(line.split(' ', 1)[0], line) + return '\n'.join(stage.lines) + + +def reference(bits, e): + """Exact v_ldexp_f32 with f32 denormals flushed: bits of the result.""" + e = e - (1 << 32) if e >= 1 << 31 else e + e = max(-1000, min(1000, e)) # beyond +-1000 every finite non-zero input over- or underflows either way + sign, ex, man = bits & 0x80000000, (bits >> 23) & 255, bits & 0x7fffff + if ex == 255: + return bits + if ex == 0: + return sign + value = Fraction(0x800000 | man, 1 << 23) * Fraction(2) ** (ex - 127 + e) + if value >= Fraction(2) ** 128: + return sign | 0x7f800000 + if value < Fraction(2) ** -126: + return sign + n = ex - 127 + e + while Fraction(2) ** n > value: + n -= 1 + while Fraction(2) ** (n + 1) <= value: + n += 1 + frac = value / Fraction(2) ** n - 1 + assert (frac * (1 << 23)).denominator == 1 # exact: a normal result needs no rounding + return sign | (n + 127) << 23 | int(frac * (1 << 23)) + + +def helper(bits, e): + """x2w_ldexp's integer text, evaluated the way HLSL evaluates it (int32 / uint32).""" + s, ex = bits & 0x80000000, (bits >> 23) & 255 + if ex == 255: + return bits + if ex == 0: + return s + ei = e - (1 << 32) if e >= 1 << 31 else e + n = ex + max(-512, min(512, ei)) + return (s | 0x7f800000) if n >= 255 else s if n <= 0 else (s | n << 23 | (bits & 0x7fffff)) + + +def naive(bits, e): + """HLSL ldexp(x, float(e)) = x * exp2(e) in binary32 with denormal flush: the control.""" + ei = e - (1 << 32) if e >= 1 << 31 else e + x = struct.unpack('<f', struct.pack('<I', bits))[0] + try: + p = struct.unpack('<f', struct.pack('<f', 2.0 ** ei))[0] + except OverflowError: + p = math.inf + except (struct.error,): + p = math.inf + r = x * p + try: + out = struct.unpack('<I', struct.pack('<f', r))[0] + except OverflowError: + out = 0x7f800000 | (bits & 0x80000000) + return out & 0x80000000 if (out >> 23) & 255 == 0 else out + + +INPUTS = [0x3f800000, 0xbf800000, 0x00800000, 0x80800000, 0x007fffff, 0x00000001, 0, 0x80000000, 0x7f7fffff, + 0x7f800000, 0xff800000, 0x7fc00000, 0x7f800001, 0x3fffffff, 0x40490fdb, 0xc2c80000] +EXPS = [0, 1, -1, 126, 127, 128, 254, 255, -126, -127, -149, -150, -254, -255, 300, -300, 0x7fffffff, 0x80000000, + 0xffffffff] +bad = [(hex(b), e) for b in INPUTS for e in EXPS if helper(b, e & 0xffffffff) != reference(b, e & 0xffffffff)] +check('x2w_ldexp matches the exact flushed reference on %d cases' % (len(INPUTS) * len(EXPS)), not bad, bad) +nbad = [(hex(b), e) for b in INPUTS for e in EXPS if naive(b, e & 0xffffffff) != reference(b, e & 0xffffffff)] +check('control: x * exp2(float(e)) misses the reference on the boundary cases', len(nbad) > 0, nbad) +text = G.HELPERS.get('x2w_ldexp', '') +for token in ('255u', '-512', '512', '0x7f800000u', '0x7fffffu', '<< 23'): + check('helper text has %s' % token, token in text, text) + +body = lower('v_ldexp_f32 v4, v1, v2') +check('VOP2 v_ldexp_f32 lowers through x2w_ldexp', 'v4 = U(x2w_ldexp(F(v1), v2));' in body, body) +body = lower('v_ldexp_f32_e64 v4, -|v1|, s3 clamp') +check('VOP3 source neg/abs and clamp', 'x2w_ldexp((-abs(F(v1))), s' in body and 'saturate' in body, body) +for line in ('v_ldexp_f32_e64 v4, v1, -v2', 'v_ldexp_f32_e64 v4, v1, |v2|'): + try: + lower(line) + check('%s refuses (modifier on the integer exponent)' % line, False) + except G.Unsupported: + check('%s refuses (modifier on the integer exponent)' % line, True) + +if len(sys.argv) > 1: + src = ('#define F(x) asfloat(x)\n#define U(x) asuint(x)\n%s\ncbuffer entry : register(b0) { uint ud0; uint ud1; };\n' + 'float4 main(uint vid : SV_VertexID) : SV_Position { uint v1 = ud0, v2 = ud1 + vid, v4;\n' + ' v4 = U(x2w_ldexp(F(v1), v2));\n return float4(F(v4), 0, 0, 1); }\n' % text) + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'ldexp.hlsl') + open(path, 'w').write(src) + r = subprocess.run([sys.argv[1], '/nologo', '/T', 'vs_5_1', '/E', 'main', '/Fo', path + '.cso', path], + capture_output=True, text=True, timeout=60) + check('fxc vs_5_1 compiles x2w_ldexp', r.returncode == 0, r.stdout + r.stderr) + +if failures: + print('FAIL') + sys.exit(1) +print('PASS') diff --git a/tests/startup_gfx2hlsl_mix_fma_check.py b/tests/startup_gfx2hlsl_mix_fma_check.py new file mode 100644 index 0000000000..015b44d1ce --- /dev/null +++ b/tests/startup_gfx2hlsl_mix_fma_check.py @@ -0,0 +1,115 @@ +"""v_fma_mix_f32 under X2W_DRAW_FEATURES=mixfma (tools/startup/gfx2hlsl.py Stage.mix). + +usage: startup_gfx2hlsl_mix_fma_check.py [fxc] + +v_fma_mix_f32 rounds once. The plain lowering, a * b + c, rounds the product and lets fxc reassociate a chain of +them. With the feature, a draw stage lowers v_fma_mix_f32 through x2w_fma_exact (the double fma behind the x2w_fz guard), except +that a signed-zero addend goes through x2w_mad_precise: fxc folds that zero into a d(...) immediate even behind the +guard, and fma(a, b, +-0) is the product rounded once plus that zero, which the precise multiply and add give. + +Pure Python: the emitted statements with and without the feature, the f16 results (mixlo/mixhi) unchanged, mesh and +compute pipelines unchanged. +(Why +-0 is exact: round(a * b) is a binary32 value; adding a signed zero to a nonzero value is exact, and for a zero +product IEEE 754 6.3 gives the same signed zero either way.) With fxc given: a vs_5_1 stage with every operand shape the +draw uses compiles with no d(...) immediate (the control, x2w_fma_exact with the -0.0 addend, has one). +""" +import os +import re +import subprocess +import sys +import tempfile + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +sys.path.insert(0, here) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Probe # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print('%s: %s' % (label, 'ok' if condition else 'MISMATCH')) + if not condition: + failures.append(label) + if detail: + print(' ' + str(detail)[:1500]) + + +class Pipe: + def __init__(self, features): + self.features = frozenset(features) + self.fma_rule = None + + +def lower(line, features, pipe=None): + stage = Probe() + stage.pipe = pipe or Pipe(features) + stage.one(line.split(' ', 1)[0], line) + return '\n'.join(stage.lines), stage.pipe + + +GENERAL = 'v_fma_mix_f32 v4, v1, v2, v3 op_sel_hi:[0,1,0]' +ONE = 'v_fma_mix_f32 v4, 1.0, v2, v3 op_sel_hi:[0,1,0]' +NEGZERO = 'v_fma_mix_f32 v4, v1, v2, -0 op_sel:[0,1,0] op_sel_hi:[0,1,0]' + +if G.DRAW_FMA != 'exact': + sys.exit('this check expects the default draw FMA rule (exact), got %s' % G.DRAW_FMA) +for line in (GENERAL, ONE): + off, _ = lower(line, ()) + on, pipe = lower(line, ('mixfma',)) + check('%s: plain without the feature' % line, 'x2w_fma' not in off and ' * ' in off, off) + check('%s: x2w_fma_exact with the feature' % line, re.search(r'v4 = U\(x2w_fma_exact\(', on) is not None, on) + check('%s: the feature sets the manifest fma rule' % line, pipe.fma_rule == 'exact', pipe.fma_rule) +on, _ = lower(NEGZERO, ('mixfma',)) +check('signed-zero addend goes through x2w_mad_precise', + 'x2w_mad_precise(F(v1), f16tof32(v2 >> 16), (-0.0))' in on, on) +for line in ('v_fma_mixlo_f16 v4, v1, v2, v3 op_sel_hi:[0,1,0]', 'v_fma_mixhi_f16 v4, v1, v2, v3 op_sel_hi:[0,1,0]'): + on, _ = lower(line, ('mixfma',)) + check('%s keeps the plain form' % line.split()[0], 'x2w_fma' not in on and 'x2w_mad' not in on, on) +mesh = G.MeshPipeline.__new__(G.MeshPipeline) +mesh.features = frozenset(('mixfma',)) +on, _ = lower(GENERAL, (), pipe=mesh) +check('mesh pipeline keeps the plain form', 'x2w_fma' not in on, on) +# v_fma_f32 with a zero constant operand (corpus 09f13eef69a075bb: x2w_fma_exact(F(0x00000000u), ...) compiled to +# dfma d(0, 0), ...): x2w_mad_precise, which is exact there; a nonzero constant keeps x2w_fma_exact. +for line, helper in (('v_fma_f32 v4, 0, v2, v3', 'x2w_mad_precise'), ('v_fma_f32 v4, v1, v2, 0', 'x2w_fma_exact'), ('v_fma_f32 v4, v1, v2, 0x80000000', 'x2w_mad_precise'), + ('v_fma_f32 v4, v1, -0, v3', 'x2w_mad_precise'), ('v_fma_f32 v4, v1, 0x80000000, v3', 'x2w_mad_precise'), + ('v_fma_f32 v4, 2.0, v2, -1.0', 'x2w_fma_exact'), ('v_fma_f32 v4, v1, 0x00000001, v3', 'x2w_fma_exact')): + on, _ = lower(line, ()) + check('%s -> %s' % (line, helper), helper + '(' in on, on) +for text, zero in (('0.0', True), ('(-0.0)', True), ('F(0x00000000u)', True), ('(-abs(F(0x80000000u)))', True), + ('F(0x00000001u)', False), ('F(v0)', False), ('1.0', False)): + check('zero_operand(%s) is %s' % (text, zero), G.zero_operand(text) == zero) +check('unknown feature names still refuse', 'mixfma' in G.KNOWN_DRAW_FEATURES) + +if len(sys.argv) > 1: + shapes = ['x2w_fma_exact(F(a), F(b), F(c))', 'x2w_fma_exact(1.0, f16tof32(b), F(c))', + 'x2w_fma_exact(1.0, (-f16tof32(b)), (-F(c)))', 'x2w_mad_precise(F(a), f16tof32(b >> 16), (-0.0))', + 'x2w_mad_precise(F(0x00000000u), F(b), F(c))'] + control = 'x2w_fma_exact(F(a), f16tof32(b >> 16), (-0.0))' + helpers = G.FMA_EXACT_FXC + '\n' + G.HELPERS['x2w_mad_precise'] + + def immediates(exprs): + body = ' '.join('r += asuint(%s);' % e for e in exprs) + src = ('#define F(x) asfloat(x)\n%s\ncbuffer cb : register(b0) { uint4 q; };\n' + 'uint4 main(uint vid : SV_VertexID) : P { x2w_fz = (vid * vid + vid) & 1u; uint a = q.x + vid, ' + 'b = q.y ^ vid, c = q.z * vid, r = 0; %s return uint4(r, a, b, c); }\n' % (helpers, body)) + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'mix.hlsl') + open(path, 'w').write(src) + r = subprocess.run([sys.argv[1], '/nologo', '/T', 'vs_5_1', '/E', 'main', '/Fo', path + '.cso', path], + capture_output=True, text=True, timeout=120) + if r.returncode: + return None, r.stdout + r.stderr + d = subprocess.run([sys.argv[1], '/nologo', '/dumpbin', path + '.cso'], capture_output=True, text=True) + return len([l for l in d.stdout.splitlines() if not l.lstrip().startswith('//') and 'd(' in l]), d.stdout + n, text = immediates(shapes) + check('fxc vs_5_1: the lowered shapes compile with no d(...) immediate', n == 0, text) + n, text = immediates([control]) + check('control: x2w_fma_exact with a -0.0 addend gets a d(...) immediate', n is not None and n > 0, text) + +if failures: + print('FAIL') + sys.exit(1) +print('PASS') diff --git a/tests/startup_gfx2hlsl_mul_hi_mad_half_check.py b/tests/startup_gfx2hlsl_mul_hi_mad_half_check.py new file mode 100644 index 0000000000..c1db816300 --- /dev/null +++ b/tests/startup_gfx2hlsl_mul_hi_mad_half_check.py @@ -0,0 +1,62 @@ +"""Arithmetic and refusal controls for signed multiply-high and selected halfword multiply-add.""" +from itertools import product +import random +import re + +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools/startup')) +import gfx2hlsl + + +def translate(asm): + stage = gfx2hlsl.Stage.__new__(gfx2hlsl.Stage) + stage.lines = [] + stage.used_v = set() + stage.uniform_v = set() + stage.exec_known = True + stage.one(asm.split()[0], asm) + return stage.lines + +MASK = 0xffffffff + + +def expression(instruction): + assignment, = translate(instruction) + assert assignment.startswith('v1 = ') and assignment.endswith(';') + return re.sub(r'\b(0x[0-9a-f]+|\d+)u\b', r'\1', assignment[5:-1]) + + +def signed(value): + return value - (1 << 32) if value >> 31 else value + + +def check(): + rng = random.Random(8614) + edges = [0, 1, 0xffff, 0x10000, 0x7fffffff, 0x80000000, MASK] + cases = list(product(edges, repeat=2)) + cases.extend((rng.getrandbits(32), rng.getrandbits(32)) for _ in range(1024)) + hi = compile(expression('v_mul_hi_i32 v1, v2, v3'), '<multiply-high>', 'eval') + functions = {'__builtins__': {}, 'x2w_mul_hi_u32': lambda a, b: a * b >> 32} + for a, b in cases: + got = eval(hi, functions, {'v2': a, 'v3': b}) & MASK + assert got == (signed(a) * signed(b) >> 32) & MASK + for left, right in product(range(2), repeat=2): + asm = 'v_mad_u32_u16 v1, v2, v3, v4 op_sel:[%d,%d,0]' % (left, right) + mad = compile(expression(asm), '<multiply-add>', 'eval') + for a, b in cases: + c = rng.getrandbits(32) + got = eval(mad, {'__builtins__': {}}, {'v2': a, 'v3': b, 'v4': c}) & MASK + assert got == (((a >> (16 * left)) & 0xffff) * ((b >> (16 * right)) & 0xffff) + c) & MASK + for operands in ('v2, v3, v4 op_sel:[0,0,1]', 'v2, v3, v4 op_sel:[0,0,0,1]', + 'v2, 12, v4 op_sel:[0,1,0]', 'v2, v3, v4 clamp'): + try: + translate('v_mad_u32_u16 v1, ' + operands) + except gfx2hlsl.Unsupported: + continue + raise AssertionError('unexpectedly accepted ' + operands) + print('PASS: signed high word and four unsigned half selections, %d operand pairs each' % len(cases)) + + +if __name__ == '__main__': + check() diff --git a/tests/startup_gfx2hlsl_root_local_check.py b/tests/startup_gfx2hlsl_root_local_check.py new file mode 100644 index 0000000000..bf1bf9f81a --- /dev/null +++ b/tests/startup_gfx2hlsl_root_local_check.py @@ -0,0 +1,85 @@ +"""A malformed root signature blob is refused per request by tools/startup/gfx2hlsl.py --pending. + +Each bad request gets a .fail file with a reason; the run exits 0 and still translates a valid +request that sorts after a bad one. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools/startup")) +import gfx2hlsl + + +def code(target): + # v_mov_b32 v0, 0, then one export of v0 followed by s_endpgm. LOCAL: v0 is written first because the + # local translator refuses a pixel stage that reads an entry VGPR (an SPI input) before writing it. + return struct.pack("<4I", 0x7e000280, 0xf800080f | target << 4, 0, 0xbf810000) + + +def container(parts): + """DXBC header (hash zeroed) followed by (fourcc, body) parts.""" + base = 32 + 4 * len(parts) + offsets, body = [], b"" + for fourcc, data in parts: + offsets.append(base + len(body)) + body += fourcc + struct.pack("<I", len(data)) + data + return (b"DXBC" + bytes(16) + struct.pack("<III", 1, base + len(body), len(parts)) + + struct.pack("<%dI" % len(offsets), *offsets) + body) + + +TRUNCATED = "root signature blob truncated" +VALID_ROOT = container([(b"RTS0", struct.pack("<6I", 1, 0, 24, 0, 24, 0))]) +# name -> (root blob, expected .fail text) +BAD = { + "empty": (b"", "root signature blob missing"), + "truncated header": (b"DXBC" + bytes(8), TRUNCATED), + "part count past end": (b"DXBC" + bytes(16) + struct.pack("<III", 1, 36, 1000), TRUNCATED), + "RTS0 without body": (container([(b"RTS0", b"")]), TRUNCATED), + "parameter table past end": (container([(b"RTS0", struct.pack("<6I", 1, 4, 24, 0, 24, 0))]), TRUNCATED), + "descriptor table past end": (container([(b"RTS0", struct.pack("<6I", 1, 1, 24, 0, 36, 0) + + struct.pack("<3I", 1, 0, 400))]), TRUNCATED), + "no RTS0": (container([(b"ABCD", bytes(8))]), "no RTS0 part"), +} +# One type-1 parameter (vis 0) whose table, at byte 36 of the part, is (register 5, space 2, count 3). +TABLE_ROOT = container([(b"RTS0", struct.pack("<6I", 1, 1, 24, 0, 36, 0) + + struct.pack("<3I", 1, 0, 36) + struct.pack("<3I", 5, 2, 3))]) + + +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) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + requests = {name: root for name, (root, _) in BAD.items()} + requests["valid"] = VALID_ROOT + keys = {} + for name, root in requests.items(): + keys[name] = gfx2hlsl.pipeline_key(vs, ps, root) + for ext, data in ((".a", vs), (".b", ps), (".root", root)): + (directory / ("req_%016x%s" % (keys[name], ext))).write_bytes(data) + # --pending visits requests in key order; the valid one must come after a bad one. + assert keys["valid"] > min(keys[name] for name in BAD), "valid request does not sort after a bad one" + # The empty X2W_FXC publishes the manifest without compiling, so the valid request is + # translated the same way on a host without fxc.exe. + result = subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", str(directory)], + capture_output=True, text=True, env=dict(os.environ, X2W_FXC="")) + output = result.stdout + result.stderr + assert result.returncode == 0, output + for name, (_, reason) in BAD.items(): + fail = directory / ("%016x.fail" % keys[name]) + assert fail.is_file(), "%s: no .fail file\n%s" % (name, output) + assert reason in fail.read_text(), (name, fail.read_text()) + assert not (directory / ("%016x.txt" % keys[name])).exists(), name + assert (directory / ("%016x.txt" % keys["valid"])).is_file(), \ + "valid request after bad ones was not translated\n" + output + assert not (directory / ("%016x.fail" % keys["valid"])).exists() + print("malformed root blobs refused per request, valid request still translated") + + +if __name__ == "__main__": + main() diff --git a/tests/startup_gfx2hlsl_scalar_named_dest_check.py b/tests/startup_gfx2hlsl_scalar_named_dest_check.py new file mode 100644 index 0000000000..a75042f008 --- /dev/null +++ b/tests/startup_gfx2hlsl_scalar_named_dest_check.py @@ -0,0 +1,31 @@ +"""A scalar ALU op whose destination is a named register half the translator does not model (vcc_hi) refuses with +Unsupported. The same operation into an SGPR still lowers.""" +import os +import sys + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +sys.path.insert(0, here) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Probe # noqa: E402 + + +def run(line): + stage = Probe() + stage.masks = set() + stage.one(line.split(' ', 1)[0], line) + return stage.lines + + +for line in ('s_lshl_b32 vcc_hi, vcc_lo, 7', 's_bfe_u32 vcc_hi, s2, 0x50010'): + try: + run(line) + except G.Unsupported as error: + assert 'vcc_hi' in str(error), error + print('%s: refused (%s)' % (line, error)) + else: + raise AssertionError('%s accepted' % line) +lines = run('s_lshl_b32 s4, s2, 7') +assert any(l.startswith('s4 = ') for l in lines), lines +print('control s_lshl_b32 s4, s2, 7: %s' % lines[0]) +print('PASS') diff --git a/tests/startup_gfx2hlsl_scc_carry_check.py b/tests/startup_gfx2hlsl_scc_carry_check.py new file mode 100644 index 0000000000..b82f670dbb --- /dev/null +++ b/tests/startup_gfx2hlsl_scc_carry_check.py @@ -0,0 +1,172 @@ +"""The SCC carry chain of s_add_u32 / s_addc_u32 and s_sub_u32 / s_subb_u32 in tools/startup/gfx2hlsl.py. + +usage: startup_gfx2hlsl_scc_carry_check.py + +Synthetic SOP2 words only; the spellings are asserted from the translator's decoder. +AMD RDNA 2 ISA SOP2: S_ADD_U32 D = S0 + S1, SCC = carry out; S_ADDC_U32 D = S0 + S1 + SCC, SCC = carry out; +S_SUB_U32 D = S0 - S1, SCC = borrow; S_SUBB_U32 D = S0 - S1 - SCC, SCC = borrow (all unsigned, 33-bit). +Checks: + values: the emitted lines, evaluated on a grid of words and both carry-in values (0xffffffff + 0 + 1 carries, + 0 - 0 - 1 borrows), equal a 64-bit reference for D and SCC, also with D equal to a source; + a 64-bit add and subtract built from the pairs equal the 64-bit result. + pre-pass: carry_scc_writers lists an add only where its SCC can reach a reader (straight line and through a + branch), not past an s_cmp, not for a carry nobody reads; those programs' lines carry no SCC (the HLSL + of programs whose carry is never read does not change). + refused: s_add_i32's SCC (signed overflow, not modelled) read by s_addc_u32; s_addc_u32 on exec or a lane mask. +""" +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_gfx2hlsl_bit_alu_check import Expr # noqa: E402 +from startup_scalar_bits_check import stage # noqa: E402 + +MASK = 0xffffffff +GRID = [0, 1, 2, 0x7fffffff, 0x80000000, 0xfffffffe, MASK, 0x12345678] +OPS = {'s_add_u32': 0, 's_sub_u32': 1, 's_add_i32': 2, 's_addc_u32': 4, 's_subb_u32': 5} + + +def sop2(name, d, a, b): + return 0x80000000 | OPS[name] << 23 | d << 16 | b << 8 | a + + +def decode(words): + return G.decode(struct.pack('<%dI' % len(words), *words)) + + +def split_top(text): + depth, parts, cur = 0, [], '' + for ch in text: + depth += ch == '(' + depth -= ch == ')' + if ch == ',' and depth == 0: + parts.append(cur) + cur = '' + else: + cur += ch + return parts + [cur] + + +def evaluate(lines, env): + env = dict(env) + for line in lines: + target, expr = line.rstrip(';').split(' = ', 1) + expr = expr.replace('q.x', 'qx').replace('q.y', 'qy') + if target == 'q': + inner = re.fullmatch(r'uint2\((.*)\)', expr).group(1) + env['qx'], env['qy'] = (Expr(p).run(env)[0] & MASK for p in split_top(inner)) + else: + env[target] = Expr(expr).run(env)[0] & (1 if target == 'scc' else MASK) + return env + + +def lines_of(name, text, carry=True): + s = stage([]) + s.lines, s.pc = [], 0 + s.carry_writes = {0} if carry else set() + s.one(name, text) + return s.lines + + +def ref(name, a, b, c): + if name.startswith('s_add'): + full = a + b + c + return full & MASK, int(full >> 32 != 0) + full = a - b - c + return full & MASK, int(full < 0) + + +def values(): + checked = 0 + for name in ('s_add_u32', 's_addc_u32', 's_sub_u32', 's_subb_u32'): + (_, _, dname, text), = decode([sop2(name, 24, 20, 22)]) + assert dname == name and text == '%s s24, s20, s22' % name, text + same = decode([sop2(name, 20, 20, 22)])[0][3] # D = S0 + same1 = decode([sop2(name, 22, 20, 22)])[0][3] # D = S1 + for form, dst in ((text, 's24'), (same, 's20'), (same1, 's22')): + lines = lines_of(name, form) + for a in GRID: + for b in GRID: + for c in (0, 1): # the incoming SCC; only addc / subb read it + cin = c if name in ('s_addc_u32', 's_subb_u32') else 0 + env = evaluate(lines, {'s20': a, 's22': b, 'scc': c}) + want = ref(name, a, b, cin) + assert (env[dst], env['scc']) == want, (name, form, a, b, c, env[dst], env['scc'], want) + checked += 1 + # 64-bit chains: s[20:21] + s[22:23] -> s[24:25], and the subtract. + for lo, hi in (('s_add_u32', 's_addc_u32'), ('s_sub_u32', 's_subb_u32')): + lines = lines_of(lo, decode([sop2(lo, 24, 20, 22)])[0][3]) + lines_of(hi, decode([sop2(hi, 25, 21, 23)])[0][3]) + for x in (0, 1, 0xffffffff, 0x100000000, 0xffffffffffffffff, 0x123456789abcdef0): + for y in (0, 1, 0xffffffff, 0xffffffffffffffff, 0x0fedcba987654321): + env = evaluate(lines, {'s20': x & MASK, 's21': x >> 32, 's22': y & MASK, 's23': y >> 32, 'scc': 0}) + full = x + y if lo == 's_add_u32' else x - y + assert env['s24'] | env['s25'] << 32 == full & 0xffffffffffffffff, (lo, hex(x), hex(y)) + assert env['scc'] == int(not 0 <= full < 1 << 64), (lo, hex(x), hex(y)) + checked += 1 + print('values: %d (D, SCC) results equal the 33-bit reference, incl. 0xffffffff + 0 + 1 and 0 - 0 - 1; ' + '64-bit add/sub chains exact' % checked) + + +def prepass(): + end = 0xbf810000 + add, addc = sop2('s_add_u32', 24, 20, 22), sop2('s_addc_u32', 25, 21, 23) + cmp = 0xbf000000 | 21 << 8 | 20 # s_cmp_eq_i32 s20, s21 + ins = decode([add, addc, end]) + assert ins[2][2] == 's_endpgm' + assert G.carry_scc_writers(ins, {}) == {0}, G.carry_scc_writers(ins, {}) + ins = decode([add, cmp, addc, end]) + assert ins[1][3] == 's_cmp_eq_i32 s20, s21', ins[1] + assert G.carry_scc_writers(ins, {}) == set() + ins = decode([add, end]) + assert G.carry_scc_writers(ins, {}) == set() + # through a branch: s_add_u32; s_cbranch_execz +1 (skips the s_cmp); s_cmp; s_addc_u32 + branch = 0xbf880001 + ins = decode([add, branch, cmp, addc, end]) + assert ins[1][3].startswith('s_cbranch_execz'), ins[1] + assert G.carry_scc_writers(ins, {}) == {0} + # the calculated-PC proof's arithmetic is neither writer nor reader here + ins = decode([add, addc, end]) + assert G.carry_scc_writers(ins, {0: None, 4: None}) == set() + # programs: the add whose carry is read emits scc, the one whose carry is not read does not + s = stage([add, addc]) + text = '\n'.join(line for _, lines, _ in s.blocks for line in lines) + assert 'scc = q.x < q.y;' in text and 'q.x <= q.y' in text, text + s = stage([add]) + text = '\n'.join(line for _, lines, _ in s.blocks for line in lines) + assert 'scc' not in text and 's24 = s20 + s22;' in text, text + print('pre-pass: carry emitted only where read (straight, through a branch); not past s_cmp, not unread, ' + 'not for calculated-PC arithmetic; an unread add keeps its old line') + + +def refused(words, why): + try: + stage(words) + except G.Unsupported as error: + assert why in str(error), (why, str(error)) + return + raise AssertionError('accepted: ' + why) + + +def refusals(): + refused([sop2('s_add_i32', 24, 20, 22), sop2('s_addc_u32', 25, 21, 23)], + 'SCC of s_add_i32 at 0x0 (not modelled) is read by s_addc_u32 at 0x4') + for text, why in (('s_addc_u32 s25, exec_lo, s23', 'not a plain number'), + ('s_addc_u32 exec_lo, s21, s23', 'destination exec_lo')): + try: + lines_of('s_addc_u32', text) + except G.Unsupported as error: + assert why in str(error), (why, str(error)) + continue + raise AssertionError('accepted ' + text) + print('refused: s_add_i32 SCC read by s_addc_u32; s_addc_u32 on exec') + + +if __name__ == '__main__': + values() + prepass() + refusals() diff --git a/tests/startup_gfx2hlsl_shift64_literal_check.py b/tests/startup_gfx2hlsl_shift64_literal_check.py new file mode 100644 index 0000000000..7496883e32 --- /dev/null +++ b/tests/startup_gfx2hlsl_shift64_literal_check.py @@ -0,0 +1,57 @@ +"""A 32-bit literal as S1 of v_lshrrev_b64 / v_lshlrev_b64 is zero-extended (S1.u64, RDNA 2 ISA 6.2.1 and 12.9). + +usage: startup_gfx2hlsl_shift64_literal_check.py + +Vertex programs materialize a 64-bit pair with `v_lshrrev_b64 v[a:b], 0, 0xffffffff` (and, next to it, all ones +with the inline `-1`); the literal was refused as a 64-bit literal operand. Signed or other 64-bit operand uses +keep the old rule (bit 31 set is refused). +""" +import os +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')) +sys.path.insert(0, here) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Probe # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print('%s: %s' % (label, 'ok' if condition else 'MISMATCH')) + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +def lower(line): + stage = Probe() + try: + stage.one(line.split(' ', 1)[0], line) + except G.Unsupported as reason: + return 'refused: %s' % reason + return ' '.join(stage.lines) + + +for line, lo, hi in (('v_lshrrev_b64 v[5:6], 0, 0xffffffff', '0xffffffffu', '0x00000000u'), + ('v_lshlrev_b64 v[5:6], 4, 0x80000001', '0x80000001u', '0x00000000u'), + ('v_lshrrev_b64 v[5:6], 0, -1', '0xffffffffu', '0xffffffffu'), + ('v_lshrrev_b64 v[5:6], 0, 0x7fffffff', '0x7fffffffu', '0x00000000u')): + text = lower(line) + check('%s reads (%s, %s)' % (line, lo, hi), ('(%s, %s, ' % (lo, hi)) in text, text) +try: + Probe().pair('0xffffffff') + kept = False +except G.Unsupported: + kept = True +check('the default 64-bit operand rule still refuses a literal with bit 31 set', kept) + +if failures: + print('FAIL') + for f in failures: + print(' ' + f) + sys.exit(1) +print('PASS') diff --git a/tests/startup_gfx2hlsl_wave_union_check.py b/tests/startup_gfx2hlsl_wave_union_check.py new file mode 100644 index 0000000000..33ae9910a2 --- /dev/null +++ b/tests/startup_gfx2hlsl_wave_union_check.py @@ -0,0 +1,357 @@ +"""X2W_PS_WAVE_UNION=1: wave64 reductions in a pixel stage over the host wave (tools/startup/gfx2hlsl.py, +wave_union_plan). + + (no arguments) translation controls, pure Python + draw <dxc> <dump.exe> <warp|hardware> + compile the translated pixel stage with DXC ps_6_0, draw 16 x 16 pixels with + a two-target dump tool (<adapter> <vs> <ps> <w> <h> <out.bin>: the words of + both R32G32B32A32 targets, row by row) and compare every pixel with a CPU + reference that takes the wave membership as a parameter + +The guest computes OP over the active lanes of its wave64 (s_or_saveexec -1, v_cndmask with the identity, four DPP +row steps, v_permlanex16, readlane 0, readlane 63). Which pixels share a wave is the hardware's choice, so the +guest result already depends on it; with the gate the HLSL takes OP over the active lanes of the host wave +(WaveActiveMin / WaveActiveMax / WaveActiveBitOr) and the manifest says `wavemembership host`. + +The fixture is built here from the instruction formats (checked against the decoder): v0 is the packed screen +position x | y << 16; v_cmpx_ne_u32 0, (v0 & 5) leaves the pixels with x & 5 != 0 active; three chains reduce v0 +with min (identity 0xffffffff), max and or (identity 0); exec is restored and mrt0 = (min, max, or, own position), +each masked to 21 bits and ORed with 0x40000000 so the words are normal binary32 values. + +A program that took a chain decides every branch per host wave. The branch fixture (branch_fixture) checks it: after +a min chain, exec is narrowed to the odd-x pixels and s_cbranch_execz skips a block that writes s20 = 1 (a scalar +write, run by the guest when any lane of the wave is active) and s21 = v_readfirstlane of (min + 7) computed in +that block from the uniform s10. mrt0 = (min, s20, s21, own position). The reference: s20 = 1 and s21 = min + 7 in +every pixel of a wave with an active odd-x pixel, else 0. An SCC branch on a mask (s_and_b64 with exec) and a +readfirstlane of a per-lane VGPR are refused. + +The draw mode adds an instrumentation output to the translated text (mrt1 = WaveReadLaneFirst of the position, +the lane index and the lane count, at the end of main) to learn the host's actual lane grouping, computes the +reference from that grouping, and requires every pixel to match. Negative controls: the reference computed with +each pixel in a wave of its own must differ, as must translations with the min chain lowered as WaveActiveMax, +the execz branch decided per lane, and the readfirstlane replaced by the lane's own value. WARP runs 4-lane waves +(2x2 quads, split where the full-screen triangle's edge cuts a quad), so on WARP the reduction does not cross a quad; +the hardware adapter mode runs the same checks on 32/64-lane waves. +""" +import os +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +WIDTH = HEIGHT = 16 +FLAG = 0x40000000 +KEEP = 0x001fffff +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 +OPS = {'min': (0x13, -1, 0xffffffff), 'max': (0x14, 0, 0), 'or': (0x1c, 0, 0)} # VOP2 opcode, identity token, value +CTRL = (0xb1, 0x4e, 0x141, 0x140) # quad_perm:[1,0,3,2], quad_perm:[2,3,0,1], row_half_mirror, row_mirror +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)[:3000]) + + +def inline(token): + return {-1: 193, 0: 128, 63: 191, 5: 133}[token] + + +def sop1(op, sdst, src): + return [0xbe800000 | sdst << 16 | op << 8 | src] + + +def vop2(op, vdst, src0, vsrc1, literal=None): + return [op << 25 | vdst << 17 | vsrc1 << 9 | src0] + ([literal] if literal is not None else []) + + +def vop2_dpp(op, v, ctrl, fi=1): + return [op << 25 | v << 17 | v << 9 | 250, v | ctrl << 8 | fi << 18 | 0xf << 24 | 0xf << 28] + + +def vop3(op, vdst, src0, src1=0, src2=0): + return [0xd4000000 | op << 16 | vdst, src0 | src1 << 9 | src2 << 18] + + +def chain(op, mask, k, src=0, controls=CTRL, ident=None, tail=True): + """s_or_saveexec_b64 s[mask], -1 ... v_readlane_b32 sK, v94, 63; v_mov_b32 v(dst), sK is added by fixture().""" + code, token, _ = OPS[op] + ident = token if ident is None else ident + w = sop1(0x25, mask, inline(-1)) # s_or_saveexec_b64 s[mask:mask+1], -1 + w += vop3(0x101, 94, inline(ident), 256 + src, mask) # v_cndmask_b32_e64 v94, IDENT, vS, s[mask] + for c in controls: + w += vop2_dpp(code, 94, c) # v_OP_dpp v94, v94, v94 <ctrl> fi:1 + w += vop3(0x378, 95, 256 + 94, 128, 128) # v_permlanex16_b32 v95, v94, 0, 0 + w += vop2(code, 94, 256 + 94, 95) # v_OP_e32 v94, v94, v95 + w += vop3(0x360, k, 256 + 94, 128) # v_readlane_b32 sK, v94, 0 + w += vop2(code, 94, k, 94) # v_OP_e32 v94, sK, v94 + w += sop1(0x04, 126, mask) # s_mov_b64 exec, s[mask:mask+1] + if tail: + w += vop3(0x360, k, 256 + 94, inline(63)) # v_readlane_b32 sK, v94, 63 + return w + + +def fixture(mutate=None): + w = sop1(0x04, 0, 126) # s_mov_b64 s[0:1], exec + w += [0x7e000000 | 9 << 17 | 1 << 9 | 244] # v_mov_b32 v9, 2.0 (0x40000000) + w += vop2(0x1b, 6, inline(5), 0) # v_and_b32 v6, 5, v0 + w += [0x7c000000 | 0xd5 << 17 | 6 << 9 | 128] # v_cmpx_ne_u32 0, v6 + for i, op in enumerate(('min', 'max', 'or')): + kwargs = (mutate or {}).get(op, {}) + w += chain(op, 2 + 2 * i, 10 + i, **kwargs) + w += [0x7e000000 | (1 + i) << 17 | 1 << 9 | (10 + i)] # v_mov_b32 v(1+i), sK + w += sop1(0x04, 126, 0) # s_mov_b64 exec, s[0:1] + for v in (1, 2, 3): + w += vop2(0x1b, v, 255, v, KEEP) # v_and_b32 vN, 0x1fffff, vN + w += vop2(0x1c, v, 256 + v, 9) # v_or_b32 vN, vN, v9 + w += vop2(0x1c, 4, 256 + 0, 9) # v_or_b32 v4, v0, v9 + w += [0xf800180f, 0x04030201, 0xbf810000] # exp mrt0 v1, v2, v3, v4 done vm; s_endpgm + return struct.pack('<%dI' % len(w), *w) + + +def branch_fixture(variant=None): + """See the module text. variant 'scc_mask': an s_and_b64 of exec and an s_cbranch_scc0 before the execz branch; + 'scc_vcmp': the same on an s_and_b32 of a v_cmp_e64 mask of a uniform value (a VALU result is per lane); + 'rfl_lane': the readfirstlane source is the lane's own position.""" + w = sop1(0x04, 0, 126) # s_mov_b64 s[0:1], exec + w += [0x7e000000 | 9 << 17 | 1 << 9 | 244] # v_mov_b32 v9, 2.0 + w += sop1(0x03, 20, 128) + sop1(0x03, 21, 128) # s_mov_b32 s20, 0; s_mov_b32 s21, 0 + w += vop2(0x1b, 6, inline(5), 0) # v_and_b32 v6, 5, v0 + w += [0x7c000000 | 0xd5 << 17 | 6 << 9 | 128] # v_cmpx_ne_u32 0, v6 + w += chain('min', 2, 10) + w += [0x7e000000 | 1 << 17 | 1 << 9 | 10] # v_mov_b32 v1, s10 + w += vop2(0x1b, 7, 129, 0) # v_and_b32 v7, 1, v0 + w += [0x7c000000 | 0xd5 << 17 | 7 << 9 | 128] # v_cmpx_ne_u32 0, v7 + if variant == 'scc_mask': + w += [0x80000000 | 0x0f << 23 | 30 << 16 | 0 << 8 | 126] # s_and_b64 s[30:31], exec, s[0:1] + w += [0xbf840000] # s_cbranch_scc0 (next instruction) + if variant == 'scc_vcmp': + w += [0x7e000000 | 8 << 17 | 1 << 9 | 10] # v_mov_b32 v8, s10 (uniform value) + w += [0xd4c5001e, 128 | (256 + 8) << 9] # v_cmp_ne_u32_e64 s30, 0, v8 (per-lane mask) + w += [0x80000000 | 0x0e << 23 | 31 << 16 | 30 << 8 | 30] # s_and_b32 s31, s30, s30 + w += [0xbf840000] # s_cbranch_scc0 (next instruction) + w += [0xbf880004] # s_cbranch_execz over the next 4 dwords + w += sop1(0x03, 20, 129) # s_mov_b32 s20, 1 + w += [0x7e000000 | 8 << 17 | 1 << 9 | (256 if variant == 'rfl_lane' else 10)] # v_mov_b32 v8, s10 (or v0) + w += vop2(0x25, 8, 135, 8) # v_add_nc_u32 v8, 7, v8 + w += [0x7e000000 | 21 << 17 | 2 << 9 | (256 + 8)] # v_readfirstlane_b32 s21, v8 + w += sop1(0x04, 126, 0) # s_mov_b64 exec, s[0:1] + w += [0x7e000000 | 2 << 17 | 1 << 9 | 20, 0x7e000000 | 3 << 17 | 1 << 9 | 21] # v_mov v2, s20; v_mov v3, s21 + for v in (1, 2, 3): + w += vop2(0x1b, v, 255, v, KEEP) + w += vop2(0x1c, v, 256 + v, 9) + w += vop2(0x1c, 4, 256 + 0, 9) + w += [0xf800180f, 0x04030201, 0xbf810000] + return struct.pack('<%dI' % len(w), *w) + + +def translate(words, gate=True): + saved = os.environ.get('X2W_PS_WAVE_UNION') + os.environ['X2W_PS_WAVE_UNION'] = '1' if gate else '0' + try: + return G.Pipeline(VS_WORDS, words, root_blob(), ps_hw_inputs=PACKED) + finally: + if saved is None: + os.environ.pop('X2W_PS_WAVE_UNION', None) + else: + os.environ['X2W_PS_WAVE_UNION'] = saved + + +def refused(words, gate=True): + try: + pipe = translate(words, gate) + pipe.hlsl_ps() + pipe.manifest() + except G.Unsupported as reason: + return str(reason) + return None + + +def controls(): + text = [a for _, _, _, a in G.decode(fixture())] + chain_text = [a for a in text if a.startswith(('s_or_saveexec', 'v_cndmask', 'v_permlane')) or '_dpp' in a] + check('the fixture decodes to three chains of the 14bb form', chain_text[:7] == [ + 's_or_saveexec_b64 s[2:3], -1', 'v_cndmask_b32_e64 v94, -1, v0, s2', + 'v_min_u32_dpp v94, v94, v94 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf fi:1', + 'v_min_u32_dpp v94, v94, v94 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf fi:1', + 'v_min_u32_dpp v94, v94, v94 row_half_mirror row_mask:0xf bank_mask:0xf fi:1', + 'v_min_u32_dpp v94, v94, v94 row_mirror row_mask:0xf bank_mask:0xf fi:1', + 'v_permlanex16_b32 v95, v94, 0, 0'], '\n'.join(text)) + pipe = translate(fixture()) + ps, manifest = pipe.hlsl_ps(), pipe.manifest() + for op, intrinsic, ident in (('min', 'WaveActiveMin', '0xffffffffu'), ('max', 'WaveActiveMax', '0x00000000u'), + ('or', 'WaveActiveBitOr', '0x00000000u')): + check('%s chain -> %s over the saved exec bit with identity %s' % (op, intrinsic, ident), + re.search(r'wu\d = %s\(\(s\d+ & 1u\) \? v0 : %s\);' % (intrinsic, ident), ps) is not None, ps) + check('no DPP, permlane or lane-0 readlane text is left', not re.search(r'permlane|QuadRead|_dpp', ps), ps) + check('the stage needs SM 6.0 and the manifest says wavemembership host', + pipe.ps.needs_sm6 and 'wavemembership host' in manifest.splitlines(), manifest) + check('gate off: the chain stays refused at the DPP', 'v_min_u32_dpp' in (refused(fixture(), gate=False) or ''), + refused(fixture(), gate=False)) + # Anything but the exact chain is left to the normal lowering, which refuses the DPP. + mutants = { + 'a row step out of order': {'min': {'controls': (0x4e, 0xb1, 0x141, 0x140)}}, + 'a missing row step': {'min': {'controls': (0xb1, 0x4e, 0x141, 0x141)}}, + 'the wrong identity (0 for min)': {'min': {'ident': 0}}, + 'no readlane of lane 63': {'min': {'tail': False}}, + } + for label, mutate in mutants.items(): + reason = refused(fixture(mutate)) + check('refused: %s (%s)' % (label, reason), reason is not None) + # v94 read outside the chains drops the whole plan + extra = fixture()[:-12] + struct.pack('<I', 0x7e000000 | 5 << 17 | 1 << 9 | (256 + 94)) + fixture()[-12:] + reason = refused(extra) + check('refused: v94 read outside the chains (%s)' % reason, reason is not None) + # The branch fixture: wave-level execz, a scalar write in the skipped block, readfirstlane of a uniform value. + pipe = translate(branch_fixture()) + ps = pipe.hlsl_ps() + check('branch fixture: the execz branch is decided per host wave', + 'pc = (!WaveActiveAnyTrue((exec & 1) != 0)) ?' in ps, ps) + check('branch fixture: readfirstlane of the uniform min + 7 -> x2w_readfirstlane', + re.search(r's21 = x2w_readfirstlane\(v8, \(exec & 1u\) != 0\);', ps) is not None, ps) + check('branch fixture: the scalar write in the block is unguarded', '\n s20 = 0x00000001u;' in ps, ps) + for variant, want in (('scc_mask', 'SCC not host-uniform'), ('scc_vcmp', 'SCC not host-uniform'), + ('rfl_lane', 'v_readfirstlane_b32')): + reason = refused(branch_fixture(variant)) + check('branch fixture refused: %s (%s)' % (variant, reason), reason is not None and want in reason) + check('a stage without such a chain is unchanged by the gate', + translate(VS_WORDS[:0] + struct.pack('<3I', 0xf800180f, 0, 0xbf810000), True).hlsl_ps() == + translate(struct.pack('<3I', 0xf800180f, 0, 0xbf810000), False).hlsl_ps()) + + +# ---- draw mode ------------------------------------------------------------------------------------------------- +INSTRUMENT = (' { uint x2w_pid = uint(i.pos.x) | (uint(i.pos.y) << 16); ' + 'o.mrt1 = float4(asfloat(0x40000000u | WaveReadLaneFirst(x2w_pid)), asfloat(0x40000000u | WaveGetLaneIndex()), ' + 'asfloat(0x40000000u | WaveGetLaneCount()), 2.0); }') + + +def instrument(ps): + out = ps.replace(' float4 mrt0 : SV_Target0;', ' float4 mrt0 : SV_Target0;\n float4 mrt1 : SV_Target1;', 1) + assert out != ps + last = out.rindex(' return o;') + return out[:last] + INSTRUMENT + '\n' + out[last:] + + +def reference(groups): + """Pixel words from a grouping: groups[(x, y)] = wave key; the reduction is over the active pixels of a group.""" + members = {} + for p, key in groups.items(): + members.setdefault(key, []).append(p) + out = {} + for p, key in groups.items(): + active = [q[0] | q[1] << 16 for q in members[key] if q[0] & 5] + mn = min(active) if active else 0xffffffff + mx = max(active) if active else 0 + orr = 0 + for a in active: + orr |= a + if not p[0] & 5: + mn = mx = orr = 0 # v1..v3 are written under the narrowed exec only: an inactive pixel keeps 0 + out[p] = [(v & KEEP) | FLAG for v in (mn, mx, orr)] + [(p[0] | p[1] << 16) | FLAG] + return out + + +def branch_reference(groups): + """branch_fixture words from a grouping: (min over the active pixels, s20, s21, own position).""" + members = {} + for p, key in groups.items(): + members.setdefault(key, []).append(p) + out = {} + for p, key in groups.items(): + active = [q[0] | q[1] << 16 for q in members[key] if q[0] & 5] + mn = min(active) if active else 0xffffffff + odd = any(q[0] & 1 for q in members[key]) + s20, s21 = (1, (mn + 7) & 0xffffffff) if odd else (0, 0) + v1 = mn if p[0] & 5 else 0 + out[p] = [(v & KEEP) | FLAG for v in (v1, s20, s21)] + [(p[0] | p[1] << 16) | FLAG] + return out + + +def check_draw(dxc, dump, adapter): + with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'vs', 'vs_6_0', d) + text = translate(fixture()).hlsl_ps() + + def run(source, name): + ps = compile_hlsl(dxc, 'dxc', instrument(source), name, 'ps_6_0', d) + out = d / (name + '.bin') + r = subprocess.run([dump, adapter, str(vs), str(ps), str(WIDTH), str(HEIGHT), str(out)], + capture_output=True, text=True) + if r.returncode == 77: + print(r.stdout + r.stderr) + sys.exit(77) + if r.returncode: + raise AssertionError('%s\n%s' % (r.stdout, r.stderr)) + words = struct.unpack('<%dI' % (WIDTH * HEIGHT * 8), out.read_bytes()) + rt0 = {(x, y): list(words[(y * WIDTH + x) * 4:(y * WIDTH + x) * 4 + 4]) + for y in range(HEIGHT) for x in range(WIDTH)} + base = WIDTH * HEIGHT * 4 + rt1 = {(x, y): list(words[base + (y * WIDTH + x) * 4:base + (y * WIDTH + x) * 4 + 4]) + for y in range(HEIGHT) for x in range(WIDTH)} + return rt0, rt1 + + rt0, rt1 = run(text, 'ps') + groups = {p: w[0] & ~FLAG for p, w in rt1.items()} + sizes = sorted({sum(1 for g in groups.values() if g == k) for k in set(groups.values())}) + lanes = sorted({w[2] & ~FLAG for w in rt1.values()}) + print('%s: host waves of %s pixels (WaveGetLaneCount %s), %d waves' % (adapter, sizes, lanes, + len(set(groups.values())))) + ref = reference(groups) + bad = [p for p in rt0 if rt0[p] != ref[p]] + check('%s: all %d pixels equal the reference over the host grouping' % (adapter, WIDTH * HEIGHT), not bad, + bad[:4] and ['%s got %s want %s' % (p, ['%08x' % v for v in rt0[p]], ['%08x' % v for v in ref[p]]) + for p in bad[:4]]) + solo = reference({p: p for p in rt0}) + check('%s: control: one pixel per wave would read a different image' % adapter, + any(rt0[p] != solo[p] for p in rt0)) + mutated = re.sub(r'WaveActiveMin\(', 'WaveActiveMax(', text) + assert mutated != text + rt0m, _ = run(mutated, 'ps_mutated') + check('%s: control: the min chain lowered as a max fails the reference' % adapter, + any(rt0m[p] != ref[p] for p in rt0m)) + + # branch fixture: same draw, its own grouping (measured again: a different shader may pack differently) + btext = translate(branch_fixture()).hlsl_ps() + bt0, bt1 = run(btext, 'ps_branch') + bgroups = {p: w[0] & ~FLAG for p, w in bt1.items()} + bref = branch_reference(bgroups) + bad = [p for p in bt0 if bt0[p] != bref[p]] + check('%s: branch fixture: all %d pixels equal the reference over the host grouping' % (adapter, WIDTH * HEIGHT), + not bad, bad[:4] and ['%s got %s want %s' % (p, ['%08x' % v for v in bt0[p]], + ['%08x' % v for v in bref[p]]) for p in bad[:4]]) + check('%s: branch fixture: some wave mixes taken and not-taken pixels (the per-lane rule would differ)' + % adapter, any(bref[p] != branch_reference({q: q for q in bt0})[p] for p in bt0)) + mutants = { + 'the execz branch decided per lane': ('!WaveActiveAnyTrue((exec & 1) != 0)', '(exec & 1) == 0'), + 'readfirstlane as the lane\'s own value': ('x2w_readfirstlane(v8, (exec & 1u) != 0)', 'v8'), + } + for n, (label, (old, new)) in enumerate(mutants.items()): + assert old in btext, old + m0, _ = run(btext.replace(old, new), 'ps_branch_m%d' % n) + check('%s: branch control: %s fails the reference' % (adapter, label), any(m0[p] != bref[p] for p in m0)) + + +def main(): + controls() + if len(sys.argv) > 1 and sys.argv[1] == 'draw': + check_draw(*sys.argv[2:5]) + if failures: + print('FAIL') + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gpu_abi_heap_start_check.cpp b/tests/startup_gpu_abi_heap_start_check.cpp new file mode 100644 index 0000000000..a6bcf75fbc --- /dev/null +++ b/tests/startup_gpu_abi_heap_start_check.cpp @@ -0,0 +1,131 @@ +#include <d3d12.h> +#include <dxgi1_6.h> +#include <windows.h> +#include <wrl/client.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <vector> + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Word = std::uint64_t; +template <class T> Word arg(T* value) { return reinterpret_cast<Word>(value); } +void** table_of(void* object) { return *static_cast<void***>(object); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0) +{ + using Slot = Word(WINAPI*)(void*, Word, Word, Word, Word, Word); + return reinterpret_cast<Slot>(table_of(object)[index])(object, a, b, c, d, e); +} +int failures = 0; +void check(bool ok, const char* what) +{ + std::printf("%s %s\n", ok ? "ok " : "FAIL", what); + if (!ok) ++failures; +} +struct TitleHeapDesc { + D3D12_DESCRIPTOR_HEAP_DESC desc; + std::uint64_t extra[2]; +}; +} // namespace + +int main() +{ + SetEnvironmentVariableA("X2W_GPU_ABI", "1"); + ComPtr<IDXGIFactory6> factory; + ComPtr<IDXGIAdapter> adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) return 3; + unsigned char parameters[64]{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters, __uuidof(ID3D12Device), &device))) return 4; + + // The title's order: a shader-visible view heap over title memory (32-byte records under ABI), then a 128-slot + // shader-visible sampler heap with no title memory (extra = 0, 0x800). + constexpr UINT views = 1024, view_step = 32, samplers = 128, sampler_step = 16; + std::vector<unsigned char> title(views * view_step + 0x10000); + const std::uint64_t title_cpu = (reinterpret_cast<std::uint64_t>(title.data()) + 0xffff) & ~std::uint64_t{0xffff}; + TitleHeapDesc view_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, views, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 1}, + {title_cpu, std::uint64_t{views} * view_step}}; + TitleHeapDesc sampler_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, samplers, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 1}, + {0, std::uint64_t{samplers} * sampler_step}}; + void* heaps[2] = {}; + const TitleHeapDesc* descs[2] = {&view_desc, &sampler_desc}; + const char* names[2] = {"view heap", "sampler heap"}; + for (int i = 0; i < 2; ++i) + if (FAILED(static_cast<HRESULT>(invoke(device, 14, arg(descs[i]), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&heaps[i])))) || + !heaps[i]) + return 5 + i; + + for (int i = 0; i < 2; ++i) { + void* heap = heaps[i]; + void** const table = table_of(heap); + char what[160]; + // A clean call (second argument 0) gives the expected answers. + const Word cpu = invoke(heap, 9); + const Word gpu = invoke(heap, 10); + std::printf("%s %p: cpu start 0x%llx, gpu start 0x%llx\n", names[i], heap, static_cast<unsigned long long>(cpu), + static_cast<unsigned long long>(gpu)); + if (i == 0) { + std::snprintf(what, sizeof(what), "%s: slot 9 returns the title memory", names[i]); + check(cpu == title_cpu, what); + } + // The title's call: the stale second argument is a wrapper (this heap, the other heap, the device). + void* stale[3] = {heap, heaps[1 - i], device}; + for (void* s : stale) { + void** const stale_table = table_of(s); + const Word cpu_stale = invoke(heap, 9, arg(s)); + std::snprintf(what, sizeof(what), "%s: slot 9 with a stale wrapper %p in rdx keeps both table pointers", names[i], s); + check(table_of(heap) == table && table_of(s) == stale_table, what); + if (table_of(heap) != table || table_of(s) != stale_table) return 1; // a call through it would execute data + std::snprintf(what, sizeof(what), "%s: slot 9 with a stale wrapper in rdx returns the start (0x%llx), not the object", + names[i], static_cast<unsigned long long>(cpu_stale)); + check(cpu_stale == cpu, what); + std::snprintf(what, sizeof(what), "%s: slot 10 is not null", names[i]); + check(table_of(heap)[10] != nullptr, what); + const Word gpu_stale = invoke(heap, 10, arg(s)); + std::snprintf(what, sizeof(what), "%s: slot 10 with a stale wrapper in rdx returns the GPU start (0x%llx)", names[i], + static_cast<unsigned long long>(gpu_stale)); + check(gpu_stale == gpu && gpu != 0 && table_of(heap) == table, what); + } + } + // The title stages a console sampler on the CPU, then copies it to the GPU-visible + // heap, both with no supplied address. Both starts must expose plain 16-byte records. + sampler_desc.desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; + void* staging = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(device, 14, arg(&sampler_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&staging)))) || + !staging) return 7; + const Word stage = invoke(staging, 9); + const Word visible = invoke(heaps[1], 9); + for (const Word start : {stage, visible}) { + MEMORY_BASIC_INFORMATION mem{}; + if (!VirtualQuery(reinterpret_cast<void*>(start), &mem, sizeof(mem)) || mem.State != MEM_COMMIT || + mem.Protect != PAGE_READWRITE || arg(mem.AllocationBase) != start) { + std::puts("FAIL unplaced sampler heap has no plain title memory"); + return 1; + } + } + constexpr Word from = 4 * sampler_step, to = 9 * sampler_step; + std::uint32_t words[27]{}; + words[1] = words[2] = 1; // linear min and mag + invoke(device, 61, arg(words), stage + from); + std::uint32_t record[4]{}; + std::memcpy(record, reinterpret_cast<const void*>(stage + from), sizeof(record)); + check(record[0] == 0x56573258 && record[2] == 22, "staged console sampler became a 16-byte sampler record"); + invoke(device, 24, 1, visible + to, stage + from, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + check(std::memcmp(record, reinterpret_cast<const void*>(visible + to), sizeof(record)) == 0, + "CopyDescriptorsSimple preserved the staged sampler at its visible index"); + void* allocator = nullptr; + void* list = nullptr; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast<HRESULT>(invoke(device, 9, 0, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator)))) || !allocator || + FAILED(static_cast<HRESULT>(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) || + !list || FAILED(static_cast<HRESULT>(invoke(list, 139, arg(allocator))))) return 8; + invoke(list, 32, 2, arg(heaps)); + if (FAILED(static_cast<HRESULT>(invoke(list, 9)))) return 9; + if (failures) std::printf("startup_gpu_abi_heap_start: %d failures\n", failures); + else std::printf("startup_gpu_abi_heap_start: pass\n"); + return failures ? 1 : 0; +} diff --git a/tests/startup_gpu_abi_off_check.cpp b/tests/startup_gpu_abi_off_check.cpp new file mode 100644 index 0000000000..4a482756fc --- /dev/null +++ b/tests/startup_gpu_abi_off_check.cpp @@ -0,0 +1,228 @@ +// The shader binding ABI switch (src/startup_stubs/gpu_abi.h, gpu_hooks.inl; PLAN.md WP0) through +// D3D12XboxCreateDevice on WARP. +// +// startup_gpu_abi_off_check off [--mutate] X2W_GPU_ABI unset (the test clears it) +// startup_gpu_abi_off_check on X2W_GPU_ABI=1 (the test sets it) +// +// The same call sequence in both modes: device slot 15 for the four desktop heap types, slot 14 (a CPU view heap), +// slot 18 (a null SRV into a title-memory heap), slot 57 (a zero description), slot 62 (a compute head with a synthetic container) and slot 86 (a stream with a mesh +// and a pixel stage). X2W_GPU_KEYLOG names a file in %TEMP% in both modes. +// - off: every answer is the old one (slot 15 = the desktop increments, 57 hands out a placeholder), no hook counter +// (x2w_gpu_counter) moves, and no key file is written. +// - on: slot 15 answers 32 for views and 16 for samplers (RTV and DSV as desktop), 57 refuses with E_NOTIMPL and a null +// out, 62 and 86 hand out placeholders, the counters show 2 pipelines, 3 keys, 1 refusal, 3 heaps, 1 view, 1 copy, the key file +// holds the blake3 keys (first 16 hex digits) of the three containers with their stages. +// - both: a view at slot 3 of a title-memory heap sized by the slot 15 answer lands 3 increments in (title_stride), and +// slot 24 copies it to slot 5 of a second such heap. +// --mutate sets the switch although the mode is "off" (the default flipped): the off checks must fail. +// +// Exit codes: 0 pass, 3 no WARP adapter, 4 no device, 10 + bits for failed checks. +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <sstream> +#include <string> +#include <tuple> +#include <vector> + +#include "startup_stubs/blake3/blake3.h" +#include "startup_stubs/gpu_abi.h" + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) long long x2w_gpu_counter(int which); + +namespace { +using Word = std::uint64_t; +void* slot(void* object, int n) { return (*static_cast<void***>(object))[n]; } + +std::string key_of(const void* bytes, std::size_t size) +{ + blake3_hasher hasher; + blake3_hasher_init(&hasher); + blake3_hasher_update(&hasher, bytes, size); + std::uint8_t hash[8]; + blake3_hasher_finalize(&hasher, hash, sizeof(hash)); + char text[17]; + for (int i = 0; i < 8; ++i) std::snprintf(text + 2 * i, 3, "%02x", hash[i]); + return text; +} + +std::vector<unsigned char> container(unsigned char seed, std::size_t size) +{ + std::vector<unsigned char> bytes(size); + std::memcpy(bytes.data(), "DXBC", 4); + for (std::size_t i = 4; i < size; ++i) bytes[i] = static_cast<unsigned char>(seed + i * 7); + return bytes; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2) return 2; + const bool on = std::strcmp(argv[1], "on") == 0; + const bool mutate = argc > 2 && std::strcmp(argv[2], "--mutate") == 0; + SetEnvironmentVariableA("X2W_GPU_ABI", on || mutate ? "1" : nullptr); + char temp[MAX_PATH]; + GetTempPathA(MAX_PATH, temp); + char keylog[MAX_PATH]; + std::snprintf(keylog, sizeof(keylog), "%sx2w_gpu_keys_%lu.txt", temp, GetCurrentProcessId()); + DeleteFileA(keylog); + SetEnvironmentVariableA("X2W_GPU_KEYLOG", keylog); + + int failed = 0; + const auto check = [&](bool ok, int bit, const char* what) { + std::printf("%s %s\n", ok ? "ok " : "FAIL", what); + if (!ok) failed |= bit; + }; + // The vendored hash: blake3("") = af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262. + check(key_of("", 0) == "af1349b9f5f9a1a6", 1, "blake3 of the empty input"); + + ComPtr<IDXGIFactory6> factory; + ComPtr<IDXGIAdapter> adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) return 3; + unsigned char parameters[64]{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters, __uuidof(ID3D12Device), &device))) return 4; + ComPtr<ID3D12Device> desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 4; + + // Slot 15. + using Increment = UINT(WINAPI*)(void*, Word); + for (UINT type = 0; type < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; ++type) { + const UINT want_desktop = desktop->GetDescriptorHandleIncrementSize(static_cast<D3D12_DESCRIPTOR_HEAP_TYPE>(type)); + const UINT got = reinterpret_cast<Increment>(slot(device, 15))(device, type); + UINT want = want_desktop; + if (on && type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) want = 32; + if (on && type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) want = 16; + char what[96]; + std::snprintf(what, sizeof(what), "slot 15 type %u: %u (want %u, desktop %u)", type, got, want, want_desktop); + check(got == want, 2, what); + } + + // Slot 14: a CPU-only view heap, followed by the (absent) title memory extension. + struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + std::uint64_t extra[2]; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}, {0, 0}}; + using CreateHeap = HRESULT(WINAPI*)(void*, const void*, const GUID*, void**); + void* heap = nullptr; + const HRESULT heap_hr = reinterpret_cast<CreateHeap>(slot(device, 14))(device, &heap_desc, &__uuidof(ID3D12DescriptorHeap), &heap); + check(SUCCEEDED(heap_hr) && heap, 4, "slot 14 view heap created"); + + // A view heap over title memory sized by the slot 15 answer: a view at slot 3 must land at 3 increments (title_stride + // follows slot 15), seen as the "X2WV" token X2W writes into title memory there. + const UINT view_increment = reinterpret_cast<Increment>(slot(device, 15))(device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + std::vector<unsigned char> title_views(16 * std::size_t{view_increment}); + struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + std::uint64_t extra[2]; + } title_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}, + {reinterpret_cast<std::uint64_t>(title_views.data()), title_views.size()}}; + void* title_heap = nullptr; + const HRESULT title_heap_hr = + reinterpret_cast<CreateHeap>(slot(device, 14))(device, &title_heap_desc, &__uuidof(ID3D12DescriptorHeap), &title_heap); + check(SUCCEEDED(title_heap_hr) && title_heap, 4, "slot 14 view heap over title memory created"); + D3D12_SHADER_RESOURCE_VIEW_DESC null_srv{}; + null_srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + null_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + null_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + null_srv.Texture2D.MipLevels = 1; + using CreateSrv = void(WINAPI*)(void*, void*, const void*, Word); + reinterpret_cast<CreateSrv>(slot(device, 18))(device, nullptr, &null_srv, + reinterpret_cast<Word>(title_views.data()) + 3 * Word{view_increment}); + std::uint32_t token = 0; + std::memcpy(&token, title_views.data() + 3 * std::size_t{view_increment}, sizeof(token)); + char token_what[96]; + std::snprintf(token_what, sizeof(token_what), "view token at slot 3 of a %u-byte-stride title heap: 0x%08x", view_increment, token); + check(token == 0x56573258u, 4, token_what); + // CopyDescriptorsSimple (slot 24) of that slot into slot 5 of a second title-memory heap: the token moves with the + // title stride (WARP: title 32 under ABI, desktop 64). + std::vector<unsigned char> title_views2(16 * std::size_t{view_increment}); + auto title_heap_desc2 = title_heap_desc; + title_heap_desc2.extra[0] = reinterpret_cast<std::uint64_t>(title_views2.data()); + void* title_heap2 = nullptr; + reinterpret_cast<CreateHeap>(slot(device, 14))(device, &title_heap_desc2, &__uuidof(ID3D12DescriptorHeap), &title_heap2); + using CopySimple = void(WINAPI*)(void*, UINT, Word, Word, D3D12_DESCRIPTOR_HEAP_TYPE); + reinterpret_cast<CopySimple>(slot(device, 24))(device, 1, reinterpret_cast<Word>(title_views2.data()) + 5 * Word{view_increment}, + reinterpret_cast<Word>(title_views.data()) + 3 * Word{view_increment}, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + std::uint32_t copied = 0; + std::memcpy(&copied, title_views2.data() + 5 * std::size_t{view_increment}, sizeof(copied)); + std::snprintf(token_what, sizeof(token_what), "copied view token at slot 5 of the second heap: 0x%08x", copied); + check(title_heap2 && copied == 0x56573258u, 4, token_what); + + // Slot 57 with a zero description. + using Create57 = HRESULT(WINAPI*)(void*, const void*, const GUID*, void**); + std::vector<unsigned char> zero(0x300); + void* refused = reinterpret_cast<void*>(1); + const HRESULT hr57 = reinterpret_cast<Create57>(slot(device, 57))(device, zero.data(), &__uuidof(ID3D12PipelineState), &refused); + if (on) check(hr57 == E_NOTIMPL && !refused, 8, "slot 57 refused with E_NOTIMPL, out null"); + else check(hr57 == S_OK && refused, 8, "slot 57 hands out a placeholder"); + + // Slot 62: a compute head with a synthetic container and no root. + const auto cs = container(1, 200); + D3D12_COMPUTE_PIPELINE_STATE_DESC compute{}; + compute.CS = {cs.data(), cs.size()}; + using Create62 = HRESULT(WINAPI*)(void*, const void*, Word, Word, const GUID*, void**); + void* pipeline62 = nullptr; + const HRESULT hr62 = reinterpret_cast<Create62>(slot(device, 62))(device, &compute, 0, 0, &__uuidof(ID3D12PipelineState), &pipeline62); + check(hr62 == S_OK && pipeline62, 16, "slot 62 hands out a pipeline"); + + // Slot 86: a stream with a mesh (console type 24) and a pixel stage (type 2), 24-byte subobjects. + const auto ms = container(2, 300), ps = container(3, 100); + unsigned char stream[48]{}; + const auto put = [&](std::size_t at, std::uint32_t type, const std::vector<unsigned char>& code) { + std::memcpy(stream + at, &type, 4); + const D3D12_SHADER_BYTECODE bytecode{code.data(), code.size()}; + std::memcpy(stream + at + 8, &bytecode, sizeof(bytecode)); + }; + put(0, 24, ms); + put(24, 2, ps); + const D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{sizeof(stream), stream}; + using Create86 = HRESULT(WINAPI*)(void*, const void*, const GUID*, void**); + void* pipeline86 = nullptr; + const HRESULT hr86 = reinterpret_cast<Create86>(slot(device, 86))(device, &stream_desc, &__uuidof(ID3D12PipelineState), &pipeline86); + check(hr86 == S_OK && pipeline86, 16, "slot 86 hands out a pipeline"); + + // The hook counters. + long long total = 0; + for (int i = 0; i < x2w_gpu::vc_count; ++i) total += x2w_gpu_counter(i); + if (on) { + check(x2w_gpu_counter(x2w_gpu::vc_pipelines) == 2, 32, "2 pipelines reached the ABI path"); + check(x2w_gpu_counter(x2w_gpu::vc_keys) == 3, 32, "3 keys logged"); + check(x2w_gpu_counter(x2w_gpu::vc_refused_57) == 1, 32, "1 refusal at slot 57"); + check(x2w_gpu_counter(x2w_gpu::vc_heaps) == 3, 32, "3 heaps reached the ABI path"); + check(x2w_gpu_counter(x2w_gpu::vc_copies) == 1, 32, "1 copy reached the ABI path"); + check(x2w_gpu_counter(x2w_gpu::vc_views) == 1, 32, "1 view reached the ABI path"); + } else { + char what[64]; + std::snprintf(what, sizeof(what), "no hook counter moved (sum %lld)", total); + check(total == 0, 32, what); + } + + // The key file. + std::ifstream file(keylog); + if (on) { + std::stringstream text; + text << file.rdbuf(); + const std::string keys = text.str(); + std::printf("key file:\n%s", keys.c_str()); + for (const auto& [code, stage, slot_name] : {std::make_tuple(&cs, "compute", "slot62"), std::make_tuple(&ms, "mesh", "slot86"), + std::make_tuple(&ps, "pixel", "slot86")}) { + const std::string line = key_of(code->data(), code->size()) + " " + stage + " " + slot_name + " " + std::to_string(code->size()); + check(keys.find(line) != std::string::npos, 64, line.c_str()); + } + } else { + check(!file.is_open(), 64, "no key file written"); + } + file.close(); + DeleteFileA(keylog); + return failed ? 10 + failed : 0; +} diff --git a/tests/startup_gpu_ambient.inl b/tests/startup_gpu_ambient.inl new file mode 100644 index 0000000000..6d67ede1d9 --- /dev/null +++ b/tests/startup_gpu_ambient.inl @@ -0,0 +1,106 @@ +// Uniform colored radiance has a known diffuse estimate. Seed conflicting probe pixels and a bright +// fog volume so the fixture distinguishes measured light, the resolve ceiling, and the air clamp. +bool ambient_lighting_test() +{ + using namespace x2w_gpu::ambient; + using namespace DirectX; + using namespace DirectX::PackedVector; + auto* device = fx.device.Get(); + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr<ID3D12DescriptorHeap> heap; + if (FAILED(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap)))) return false; + const UINT inc = device->GetDescriptorHandleIncrementSize(hd.Type); + const auto cpu = [&](UINT i){ return D3D12_CPU_DESCRIPTOR_HANDLE{heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T(i)*inc}; }; + const auto gpu = [&](UINT i){ return D3D12_GPU_DESCRIPTOR_HANDLE{heap->GetGPUDescriptorHandleForHeapStart().ptr + UINT64(i)*inc}; }; + struct Texture { + ComPtr<ID3D12Resource> gpu, upload, readback; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT foot{}; + UINT64 bytes{}; + }; + std::array<Texture,4> textures; + const auto location = [](ID3D12Resource* r, const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layout) { + D3D12_TEXTURE_COPY_LOCATION loc{}; + loc.pResource = r; + if (layout) { loc.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; loc.PlacedFootprint = *layout; } + else loc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + return loc; + }; + begin(); + const auto uav = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + const auto read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + for (UINT i=0; i<textures.size(); ++i) { + auto& t = textures[i]; + D3D12_RESOURCE_DESC d{}; + d.Dimension = i == 3 ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = 13; d.Height = 9; d.DepthOrArraySize = i == 3 ? 3 : 1; + d.MipLevels = d.SampleDesc.Count = 1; + d.Format = i == 0 ? DXGI_FORMAT_R32_FLOAT : i == 2 ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R11G11B10_FLOAT; + d.Flags = i == 0 ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_HEAP_PROPERTIES hp{D3D12_HEAP_TYPE_DEFAULT}; + if (FAILED(device->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&d,D3D12_RESOURCE_STATE_COPY_DEST, + nullptr,IID_PPV_ARGS(&t.gpu)))) return false; + if (!i) device->CreateShaderResourceView(t.gpu.Get(),nullptr,cpu(i)); + else device->CreateUnorderedAccessView(t.gpu.Get(),nullptr,nullptr,cpu(i)); + device->GetCopyableFootprints(&d,0,1,0,&t.foot,nullptr,nullptr,&t.bytes); + t.upload = buffer(t.bytes,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_FLAG_NONE,D3D12_RESOURCE_STATE_GENERIC_READ); + t.readback = buffer(t.bytes,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_FLAG_NONE,D3D12_RESOURCE_STATE_COPY_DEST); + void* mapped = nullptr; + if (!t.upload || !t.readback || FAILED(t.upload->Map(0,nullptr,&mapped))) return false; + for (UINT z=0; z<d.DepthOrArraySize; ++z) for (UINT y=0; y<d.Height; ++y) { + auto* row = reinterpret_cast<UINT*>(static_cast<BYTE*>(mapped)+(z*d.Height+y)*t.foot.Footprint.RowPitch); + for (UINT x=0; x<d.Width; ++x) { + if (i == 0) row[x] = 0x3f800000; + else if (i == 1) row[x] = XMFLOAT3PK(.25f,.5f,1.f).v; + else if (i == 2) row[x] = x == 0 ? XMFLOAT3SE(64.f,0.f,64.f).v : x == 2 ? XMFLOAT3SE(30.f,30.f,30.f).v : 0; + else row[x] = XMFLOAT3PK(8.f,8.f,8.f).v; + } + } + t.upload->Unmap(0,nullptr); + const auto dst=location(t.gpu.Get(),nullptr), src=location(t.upload.Get(),&t.foot); + fx.list->CopyTextureRegion(&dst,0,0,0,&src,nullptr); + x2w_gpu::transition_all(fx.list.Get(),t.gpu.Get(),D3D12_RESOURCE_STATE_COPY_DEST,i ? uav : read); + } + Pass pass; + Settings settings{}; + settings.level=.8f; settings.air=1; settings.strength=0; + ID3D12DescriptorHeap* heaps[] = {heap.Get()}; + fx.list->SetDescriptorHeaps(1,heaps); + const auto run=[&](Role r, UINT slot){ + const Views v{gpu(0),gpu(slot),13,9,slot==3 ? 3u : 1u}; + const auto ok=pass.record(device,fx.list.Get(),r,settings,v); + if (FAILED(pass.error())) std::printf("ambient error %08lx %s\n",pass.error(),pass.diagnostic().c_str()); + return ok; + }; + if (run(Role::resolve,2) || !run(Role::radiance,1) || !run(Role::resolve,2) || !run(Role::air,3)) return false; + const auto copy=[&](UINT i) { + auto& t=textures[i]; + x2w_gpu::transition_all(fx.list.Get(),t.gpu.Get(),uav,D3D12_RESOURCE_STATE_COPY_SOURCE); + const auto dst=location(t.readback.Get(),&t.foot),src=location(t.gpu.Get(),nullptr); + fx.list->CopyTextureRegion(&dst,0,0,0,&src,nullptr); + x2w_gpu::transition_all(fx.list.Get(),t.gpu.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE,uav); + }; + copy(2); copy(3); end_and_wait(); + const auto pixel=[&](UINT i,UINT x,UINT y,UINT z,XMFLOAT3& out){ + auto& t=textures[i]; void* mapped=nullptr; + if (FAILED(t.readback->Map(0,nullptr,&mapped))) return false; + const auto* row=reinterpret_cast<const UINT*>(static_cast<const BYTE*>(mapped)+(z*9+y)*t.foot.Footprint.RowPitch); + if (i==2) { const XMFLOAT3SE rgb(row[x]); XMStoreFloat3(&out,XMLoadFloat3SE(&rgb)); } + else { const XMFLOAT3PK rgb(row[x]); XMStoreFloat3(&out,XMLoadFloat3PK(&rgb)); } + const D3D12_RANGE none{}; t.readback->Unmap(0,&none); return true; + }; + const auto close_to=[](float a,float b){return std::abs(a-b)<.018f;}; + XMFLOAT3 rgb; + const float lum=.25f*.2126f+.5f*.7152f+.0722f; + for (UINT x : {0u,1u,12u}) { + if (!pixel(2,x,4,0,rgb) || !close_to(rgb.x,.2f) || !close_to(rgb.y,.4f) || !close_to(rgb.z,.8f)) return false; + } + if (!pixel(2,2,4,0,rgb) || !close_to(rgb.x,4*.8f*lum) || !close_to(rgb.y,rgb.x) || !close_to(rgb.z,rgb.x)) return false; + for (UINT z : {0u,2u}) + if (!pixel(3,12,8,z,rgb) || !close_to(rgb.x,lum) || !close_to(rgb.y,lum) || !close_to(rgb.z,lum)) return false; + begin(); + fx.list->SetDescriptorHeaps(1,heaps); + settings.constant=.3f; settings.level=0; + if (!run(Role::resolve,2) || run(Role::air,3)) return false; + copy(2); end_and_wait(); + return pixel(2,12,8,0,rgb) && close_to(rgb.x,.30f) && close_to(rgb.y,.294f) && close_to(rgb.z,.282f); +} diff --git a/tests/startup_gpu_bind.hlsl b/tests/startup_gpu_bind.hlsl new file mode 100644 index 0000000000..516d3accb4 --- /dev/null +++ b/tests/startup_gpu_bind.hlsl @@ -0,0 +1,35 @@ +// WP3 vbind: synthetic compute shaders for the binding ABI described in the upstream emitter, src/emit/mod.rs. +// user data: b0 space0, 32-bit root constants; tables: ResourceDescriptorHeap[byte offset / 32 + entry]; +// root SRV t3 space1 and root UAV u5 space1 as one-view tables of raw views, read at the bias the host passes. +struct Constants { + uint4 v; +}; +cbuffer UserData : register(b0, space0) +{ + uint ud_table; // the table's byte offset in its heap, console units (32 a view) + uint ud_srv_bias; // USER_VIEW_BIAS of root parameter 3 + uint ud_uav_bias; // USER_VIEW_BIAS of root parameter 5 + uint ud_count; // bounds: dwords to store +}; +ByteAddressBuffer root_srv : register(t3, space1); +RWByteAddressBuffer root_uav : register(u5, space1); + +// Entry 0 of the table: a raw SRV; entry 1: a CBV (made afresh: the title's is not on 256 bytes). +[numthreads(1, 1, 1)] +void bind_main() +{ + const uint base = ud_table / 32; + ByteAddressBuffer listed = ResourceDescriptorHeap[base + 0]; + ConstantBuffer<Constants> constants = ResourceDescriptorHeap[base + 1]; + const uint a = listed.Load(0); + const uint b = root_srv.Load(ud_srv_bias); + const uint4 c = constants.v; + root_uav.Store4(ud_uav_bias, uint4(a, b, c.x, c.w)); +} + +// ud_count dwords from the root UAV's address on: the view's bounds decide what lands. +[numthreads(64, 1, 1)] +void bounds_main(uint i : SV_DispatchThreadID) +{ + if (i < ud_count) root_uav.Store(ud_uav_bias + i * 4, 0xc0de0000u | i); +} diff --git a/tests/startup_gpu_bind_check.cpp b/tests/startup_gpu_bind_check.cpp new file mode 100644 index 0000000000..1b0a62a814 --- /dev/null +++ b/tests/startup_gpu_bind_check.cpp @@ -0,0 +1,440 @@ +// WP3 vbind on WARP: the root bindings that gpu_bind.inl makes, with the pure parts it uses +// (src/startup_stubs/gpu_roots.h: fill_user_data, raw_window, raw_elements, constant_view_bytes, find_bounded), run +// against our own ABI shaders (tests/startup_gpu_bind.hlsl, cs_6_6), not title shaders. +// +// startup_gpu_bind_check bind [--mutate] +// A table at title slot 10 (user-data dword = its byte offset in console units, 320) whose entry 0 is a raw SRV and +// entry 1 a CBV the title placed on 16 bytes (made afresh in 256-byte steps); a root SRV at t3 space1 whose title +// address is 8 bytes past 16 (raw view from the 16 bytes below, the bias in user data); the result through a root +// UAV at u5 space1, 4 bytes past 16. --mutate: the table dword as index x 64 (a desktop increment), the SRV bias +// left out, the CBV made in place on the 256 bytes below: the checks must fail. +// startup_gpu_bounds_check bounds [--mutate] +// A root UAV into a 256-byte title buffer of a 64 KiB window stores 512 bytes: what lies past the buffer's end (the +// canaries) must stay; a root UAV into memory no title buffer record holds gets a null view (nothing stored); a +// title buffer running past its window's end is cut there. --mutate: bounded by the window alone (the runs +// 129/132 hazard): the canaries must be overwritten, so the checks fail. +// +// Exit codes: 0 pass, 1 failed checks, 2 usage, 77 skipped (no WARP, no SM 6.6 or no resource binding tier 3). +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <vector> + +#include "startup_stubs/gpu_roots.h" +#include "startup_gpu_bind_bind_main.h" +#include "startup_gpu_bind_bounds_main.h" + +using Microsoft::WRL::ComPtr; +using namespace x2w_vbind; +using x2w_gpu::GpuUserData; + +namespace { +int failures = 0; +void check(bool ok, const char* what) +{ + std::printf("%s %s\n", ok ? "ok " : "FAIL", what); + if (!ok) ++failures; +} + +constexpr std::uint64_t window_bytes = 64 * 1024; +constexpr std::uint64_t title_read = 0x00007f0000000000ull; // title GPU address of the read window +constexpr std::uint64_t title_write = 0x00007f0100000000ull; // title GPU address of the write window +constexpr std::uint64_t title_heap = 0x00007e0000000000ull; // title GPU start of the view heap +constexpr std::uint32_t heap_slots = 64; +std::uint32_t pattern(std::uint64_t offset) { return 0x10000000u + static_cast<std::uint32_t>(offset / 4); } +constexpr std::uint32_t canary = 0xaaaaaaaau; + +struct Gpu { + ComPtr<ID3D12Device> device; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + ComPtr<ID3D12DescriptorHeap> heap; + ComPtr<ID3D12RootSignature> root; + UINT increment = 0; + D3D12_CPU_DESCRIPTOR_HANDLE cpu(std::uint32_t i) const + { + auto h = heap->GetCPUDescriptorHandleForHeapStart(); + h.ptr += std::size_t{i} * increment; + return h; + } + D3D12_GPU_DESCRIPTOR_HANDLE gpu(std::uint32_t i) const + { + auto h = heap->GetGPUDescriptorHandleForHeapStart(); + h.ptr += std::uint64_t{i} * increment; + return h; + } + ComPtr<ID3D12Resource> buffer(D3D12_HEAP_TYPE type, std::uint64_t bytes, bool uav) + { + D3D12_HEAP_PROPERTIES hp{}; + hp.Type = type; + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = bytes; + d.Height = d.DepthOrArraySize = d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = uav ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE; + const D3D12_RESOURCE_STATES state = type == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ + : type == D3D12_HEAP_TYPE_READBACK ? D3D12_RESOURCE_STATE_COPY_DEST + : D3D12_RESOURCE_STATE_COMMON; + ComPtr<ID3D12Resource> r; + if (FAILED(device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, IID_PPV_ARGS(&r)))) return nullptr; + return r; + } + // descriptor/host.rs raw_at: an R32_TYPELESS raw view of `bytes` from byte `first` (a multiple of 16). + void raw_srv(std::uint32_t slot, ID3D12Resource* b, std::uint64_t first, std::uint64_t bytes) + { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Buffer.FirstElement = first / 4; + v.Buffer.NumElements = raw_elements(bytes); + v.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(b, &v, cpu(slot)); + } + void raw_uav(std::uint32_t slot, ID3D12Resource* b, std::uint64_t first, std::uint64_t bytes) + { + D3D12_UNORDERED_ACCESS_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + v.Buffer.FirstElement = first / 4; + v.Buffer.NumElements = raw_elements(bytes); + v.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(b, nullptr, &v, cpu(slot)); + } + void null_raw_uav(std::uint32_t slot) + { + D3D12_UNORDERED_ACCESS_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + v.Buffer.NumElements = 1; + v.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(nullptr, nullptr, &v, cpu(slot)); + } + void cbv(std::uint32_t slot, D3D12_GPU_VIRTUAL_ADDRESS at, std::uint32_t bytes) + { + const D3D12_CONSTANT_BUFFER_VIEW_DESC v{at, bytes}; + device->CreateConstantBufferView(&v, cpu(slot)); + } + bool run() + { + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + static std::uint64_t value = 0; + ++value; + if (FAILED(queue->Signal(fence.Get(), value))) return false; + HANDLE e = CreateEventA(nullptr, FALSE, FALSE, nullptr); + fence->SetEventOnCompletion(value, e); + WaitForSingleObject(e, 30000); + CloseHandle(e); + if (fence->GetCompletedValue() < value) return false; + return SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.Get(), nullptr)); + } +}; + +void transition(ID3D12GraphicsCommandList* l, ID3D12Resource* r, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) +{ + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition.pResource = r; + b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + b.Transition.StateBefore = from; + b.Transition.StateAfter = to; + l->ResourceBarrier(1, &b); +} + +// 0 ok, 77 skip, 1 failure. +int make(Gpu& g) +{ + ComPtr<IDXGIFactory6> factory; + ComPtr<IDXGIAdapter> adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) return 77; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&g.device)))) return 77; + D3D12_FEATURE_DATA_SHADER_MODEL sm{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS o{}; + if (FAILED(g.device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &sm, sizeof(sm))) || sm.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(g.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &o, sizeof(o))) || + o.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) { + std::printf("skip: no SM 6.6 / resource binding tier 3\n"); + return 77; + } + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(g.device->CreateCommandQueue(&qd, IID_PPV_ARGS(&g.queue))) || + FAILED(g.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&g.allocator))) || + FAILED(g.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g.allocator.Get(), nullptr, IID_PPV_ARGS(&g.list))) || + FAILED(g.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&g.fence)))) + return 1; + const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, heap_slots, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + if (FAILED(g.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&g.heap)))) return 1; + g.increment = g.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + // The ABI's host root (WP2 builds it from the export): b0 space0 constants, then the one-view tables of t3 / u5 + // space1, the heap directly indexed. + D3D12_DESCRIPTOR_RANGE1 ranges[2]{}; + ranges[0] = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 3, 1, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE, 0}; + ranges[1] = {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 5, 1, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE, 0}; + D3D12_ROOT_PARAMETER1 params[3]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 4}; + for (int i = 0; i < 2; ++i) { + params[1 + i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1 + i].DescriptorTable = {1, &ranges[i]}; + } + D3D12_VERSIONED_ROOT_SIGNATURE_DESC rd{}; + rd.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + rd.Desc_1_1 = {3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED}; + ComPtr<ID3DBlob> blob, error; + if (FAILED(D3D12SerializeVersionedRootSignature(&rd, &blob, &error)) || + FAILED(g.device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&g.root)))) { + std::printf("root signature: %s\n", error ? static_cast<const char*>(error->GetBufferPointer()) : "?"); + return 1; + } + return 0; +} + +ComPtr<ID3D12PipelineState> pipeline(Gpu& g, const void* code, std::size_t bytes) +{ + D3D12_COMPUTE_PIPELINE_STATE_DESC d{}; + d.pRootSignature = g.root.Get(); + d.CS = {code, bytes}; + ComPtr<ID3D12PipelineState> p; + if (FAILED(g.device->CreateComputePipelineState(&d, IID_PPV_ARGS(&p)))) return nullptr; + return p; +} + +// A window of title memory: `fill(offset)` per dword, uploaded on the list (left in COPY_DEST). +ComPtr<ID3D12Resource> window(Gpu& g, ComPtr<ID3D12Resource>& upload, std::uint32_t (*fill)(std::uint64_t), bool uav) +{ + auto w = g.buffer(D3D12_HEAP_TYPE_DEFAULT, window_bytes, uav); + upload = g.buffer(D3D12_HEAP_TYPE_UPLOAD, window_bytes, false); + if (!w || !upload) return nullptr; + void* p = nullptr; + upload->Map(0, nullptr, &p); + for (std::uint64_t o = 0; o < window_bytes; o += 4) static_cast<std::uint32_t*>(p)[o / 4] = fill(o); + upload->Unmap(0, nullptr); + g.list->CopyBufferRegion(w.Get(), 0, upload.Get(), 0, window_bytes); + return w; +} +std::vector<std::uint32_t> read_back(Gpu& g, ID3D12Resource* w, D3D12_RESOURCE_STATES state) +{ + auto rb = g.buffer(D3D12_HEAP_TYPE_READBACK, window_bytes, false); + std::vector<std::uint32_t> out; + if (!rb) return out; + transition(g.list.Get(), w, state, D3D12_RESOURCE_STATE_COPY_SOURCE); + g.list->CopyBufferRegion(rb.Get(), 0, w, 0, window_bytes); + if (!g.run()) return out; + void* p = nullptr; + const D3D12_RANGE all{0, window_bytes}; + if (FAILED(rb->Map(0, &all, &p))) return out; + out.assign(static_cast<const std::uint32_t*>(p), static_cast<const std::uint32_t*>(p) + window_bytes / 4); + rb->Unmap(0, nullptr); + return out; +} + +// One window from `base` (title address), `buffer` its desktop resource: gpu_find's window lookup. +auto window_lookup(std::uint64_t base, ID3D12Resource* buffer) +{ + return [=](std::uint64_t a, std::uint64_t n, void** b, std::uint64_t* o) { + if (a < base || a + n > base + window_bytes || a + n < a) return false; + *b = buffer; + *o = a - base; + return true; + }; +} +// The title buffer records (resource_address_index): [first, end) pairs. +auto extent_lookup(std::vector<std::pair<std::uint64_t, std::uint64_t>> records, bool ignore) +{ + return [=](std::uint64_t a, std::uint64_t* base, std::uint64_t* end) { + if (ignore) return false; + for (const auto& r : records) + if (a >= r.first && a < r.second) return *base = r.first, *end = r.second, true; + return false; + }; +} + +int bind_mode(Gpu& g, bool mutate) +{ + auto pso = pipeline(g, startup_gpu_bind_bind_main, sizeof(startup_gpu_bind_bind_main)); + if (!pso) return 1; + ComPtr<ID3D12Resource> up_read, up_write; + auto read = window(g, up_read, pattern, false); + auto write = window(g, up_write, [](std::uint64_t) { return canary; }, true); + if (!read || !write) return 1; + transition(g.list.Get(), read.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + transition(g.list.Get(), write.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + const auto in_read = window_lookup(title_read, read.Get()); + const auto in_write = window_lookup(title_write, write.Get()); + + // The title's table at slot 10, mirrored in place (host slot = title slot): entry 0 a raw SRV of window offset + // 0x400; entry 1 the title's CBV at title_read + 0x2010 (16-aligned, not 256): made afresh in the upload buffer. + Roots roots; + roots.set_table(true, 0, title_heap + 10 * abi::view_increment); + g.raw_srv(10, read.Get(), 0x400, 256); + const std::uint64_t cbv_title = title_read + 0x2010; + auto copies = g.buffer(D3D12_HEAP_TYPE_UPLOAD, 64 * 1024, false); + if (!copies) return 1; + const std::uint32_t cbv_size = constant_view_bytes(16); + check(cbv_size == 256, "a 16-byte CBV is made in 256 bytes"); + { + void* p = nullptr; + copies->Map(0, nullptr, &p); + auto* d = static_cast<std::uint32_t*>(p) + 512 / 4; // the ring places at 512 bytes + for (std::uint32_t i = 0; i < cbv_size / 4; ++i) d[i] = i < 4 ? pattern(cbv_title - title_read + i * 4) : 0; + copies->Unmap(0, nullptr); + } + if (!mutate) g.cbv(11, copies->GetGPUVirtualAddress() + 512, cbv_size); + else g.cbv(11, read->GetGPUVirtualAddress() + ((cbv_title - title_read) & ~std::uint64_t{255}), 256); // in place, aligned down + // What the mutated table dword (index x 64) selects instead: other views, so the reads differ. + g.raw_srv(20, read.Get(), 0x800, 256); + g.cbv(21, copies->GetGPUVirtualAddress() + 4096, 256); + + // Root SRV, root parameter 3: title address 8 past 16 inside the title buffer [read+0x1000, read+0x1100). + const auto read_records = extent_lookup({{title_read + 0x1000, title_read + 0x1100}}, false); + Found f; + RawWindow srv_raw, uav_raw; + const bool srv_found = find_bounded(title_read + 0x1008, 1, ~0ull, 0, read_records, in_read, &f) && + raw_window(f.offset, f.left, true, &srv_raw); + check(srv_found && srv_raw.first == 0x1000 && srv_raw.bias == 8 && srv_raw.bytes == 0x100, + "root SRV: raw view from the 16 bytes below, bias 8, to the title buffer's end"); + if (!srv_found) return 1; + g.raw_srv(40, read.Get(), srv_raw.first, srv_raw.bytes); + roots.set_view(true, 3, title_read + 0x1008, GpuRootKind::srv); + // Root UAV, root parameter 5: 4 past 16 in [write+0x3000, write+0x3100). + const auto write_records = extent_lookup({{title_write + 0x3000, title_write + 0x3100}}, false); + const bool uav_found = find_bounded(title_write + 0x3004, 1, ~0ull, 0, write_records, in_write, &f) && + raw_window(f.offset, f.left, true, &uav_raw); + check(uav_found && uav_raw.first == 0x3000 && uav_raw.bias == 4, "root UAV: raw view from the 16 bytes below, bias 4"); + if (!uav_found) return 1; + g.raw_uav(41, write.Get(), uav_raw.first, uav_raw.bytes); + roots.set_view(true, 5, title_write + 0x3004, GpuRootKind::uav); + + // The user data as bind() fills it: the table's byte offset, the two biases of the bound views. + const HeapSpan spans[2] = {{title_heap, heap_slots, false}, {}}; + const GpuUserData words[] = { + {0, 0, GpuRootType::table, 0, 0}, + {1, 3, GpuRootType::other, abi::user_view_bias, 0}, + {2, 5, GpuRootType::other, abi::user_view_bias, 0}, + }; + const std::vector<BoundBias> biases = {{3, mutate ? 0u : srv_raw.bias}, {5, uav_raw.bias}}; + auto values = fill_user_data(roots, true, words, 3, 4, {}, spans, 2, biases, 0, + [](std::uint32_t, std::uint32_t) -> std::uint64_t { return 0; }); + check(values[0] == 320, "table dword = byte offset in console units (10 x 32)"); + if (mutate) values[0] = 10 * 64; + + ID3D12DescriptorHeap* heaps[] = {g.heap.Get()}; + g.list->SetDescriptorHeaps(1, heaps); + g.list->SetComputeRootSignature(g.root.Get()); + g.list->SetPipelineState(pso.Get()); + g.list->SetComputeRoot32BitConstants(0, 4, values.data(), 0); + g.list->SetComputeRootDescriptorTable(1, g.gpu(40)); + g.list->SetComputeRootDescriptorTable(2, g.gpu(41)); + g.list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER uav{}; + uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + g.list->ResourceBarrier(1, &uav); + const auto out = read_back(g, write.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (out.size() != window_bytes / 4) return 1; + const std::uint32_t* r = &out[0x3004 / 4]; + char what[160]; + std::snprintf(what, sizeof(what), "table entry 0 (raw SRV at 0x400): 0x%08x, want 0x%08x", r[0], pattern(0x400)); + check(r[0] == pattern(0x400), what); + std::snprintf(what, sizeof(what), "root SRV at the biased address: 0x%08x, want 0x%08x", r[1], pattern(0x1008)); + check(r[1] == pattern(0x1008), what); + std::snprintf(what, sizeof(what), "table entry 1 (CBV made afresh) x: 0x%08x, want 0x%08x; w: 0x%08x, want 0x%08x", r[2], + pattern(0x2010), r[3], pattern(0x201c)); + check(r[2] == pattern(0x2010) && r[3] == pattern(0x201c), what); + check(out[0x3000 / 4] == canary && out[0x3014 / 4] == canary, "root UAV stores at the title address, not the view's start"); + return 0; +} + +int bounds_mode(Gpu& g, bool mutate) +{ + auto pso = pipeline(g, startup_gpu_bind_bounds_main, sizeof(startup_gpu_bind_bounds_main)); + if (!pso) return 1; + ComPtr<ID3D12Resource> up; + auto write = window(g, up, [](std::uint64_t) { return canary; }, true); + if (!write) return 1; + transition(g.list.Get(), write.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + const auto in_write = window_lookup(title_write, write.Get()); + // Title buffers: [0x4000, 0x4100) and one running past the window's end [0xf000, 0x11000). Nothing at 0x8000. + // The mutation bounds by the window alone (no records; any length allowed). + const auto records = extent_lookup({{title_write + 0x4000, title_write + 0x4100}, {title_write + 0xf000, title_write + 0x11000}}, mutate); + const std::uint64_t unknown = mutate ? ~0ull : 0; // root UAVs: no allowance for unknown memory + ID3D12DescriptorHeap* heaps[] = {g.heap.Get()}; + g.list->SetDescriptorHeaps(1, heaps); + g.list->SetComputeRootSignature(g.root.Get()); + g.list->SetPipelineState(pso.Get()); + g.raw_srv(40, write.Get(), 0, 16); // t3 is not read here; a valid view all the same + struct Case { + std::uint64_t offset; + std::uint32_t slot; + }; + const Case cases[] = {{0x4008, 41}, {0x8000, 42}, {0xff00, 43}}; + char what[160]; + for (const Case& c : cases) { + Found f; + RawWindow raw; + const bool found = find_bounded(title_write + c.offset, 1, ~0ull, unknown, records, in_write, &f) && + raw_window(f.offset, f.left, true, &raw); + if (c.offset == 0x4008) { + std::snprintf(what, sizeof(what), "root UAV at 0x4008: %llu bytes left (want 248: the title buffer's end)", + static_cast<unsigned long long>(f.left)); + check(found && f.known_extent && f.left == 0xf8 && raw.bias == 8, what); + } else if (c.offset == 0x8000) { + check(!found, "root UAV in memory no title buffer holds: not found (a null view)"); + } else { + std::snprintf(what, sizeof(what), "root UAV at 0xff00: %llu bytes left, cut by the window (want 256)", + static_cast<unsigned long long>(f.left)); + check(found && f.left == 0x100 && f.cut_by_window, what); + } + if (found) g.raw_uav(c.slot, write.Get(), raw.first, raw.bytes); + else g.null_raw_uav(c.slot); + const std::uint32_t values[4] = {0, 0, found ? raw.bias : 0, 128}; // 128 dwords: 512 bytes + g.list->SetComputeRoot32BitConstants(0, 4, values, 0); + g.list->SetComputeRootDescriptorTable(1, g.gpu(40)); + g.list->SetComputeRootDescriptorTable(2, g.gpu(c.slot)); + g.list->Dispatch(2, 1, 1); + } + D3D12_RESOURCE_BARRIER uav{}; + uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + g.list->ResourceBarrier(1, &uav); + const auto out = read_back(g, write.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (out.size() != window_bytes / 4) return 1; + const auto stored = [&](std::uint64_t from, std::uint64_t to, std::uint64_t at) { + for (std::uint64_t o = from; o < to; o += 4) + if (out[o / 4] != (0xc0de0000u | static_cast<std::uint32_t>((o - at) / 4))) return false; + return true; + }; + const auto untouched = [&](std::uint64_t from, std::uint64_t to) { + for (std::uint64_t o = from; o < to; o += 4) + if (out[o / 4] != canary) return false; + return true; + }; + check(stored(0x4008, 0x4100, 0x4008), "the stores inside the title buffer landed"); + check(untouched(0x4000, 0x4008), "the 8 bytes below the title address (the bias) kept"); + check(untouched(0x4100, 0x4300), "the canaries past the title buffer's end kept (stores past it dropped)"); + check(untouched(0x8000, 0x8200), "nothing stored through the null view"); + check(stored(0xff00, 0x10000, 0xff00), "the stores up to the window's end landed"); + return 0; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2) return 2; + const bool bounds = std::strcmp(argv[1], "bounds") == 0; + if (!bounds && std::strcmp(argv[1], "bind") != 0) return 2; + const bool mutate = argc > 2 && std::strcmp(argv[2], "--mutate") == 0; + Gpu g; + if (const int rc = make(g)) return rc; + const int rc = bounds ? bounds_mode(g, mutate) : bind_mode(g, mutate); + std::printf("gpu %s%s: %d failure(s)%s\n", argv[1], mutate ? " (mutated control)" : "", failures, rc ? " (setup failed)" : ""); + return rc || failures ? 1 : 0; +} diff --git a/tests/startup_gpu_build_queue.cpp b/tests/startup_gpu_build_queue.cpp new file mode 100644 index 0000000000..180ea9f442 --- /dev/null +++ b/tests/startup_gpu_build_queue.cpp @@ -0,0 +1,84 @@ +#include "startup_stubs/gpu_build_queue.h" +#include <cstdio> +#include <future> +#include <stdexcept> + +int main() +{ + using namespace std::chrono_literals; + using Queue = x2w_gpu::VpBuildQueue<int>; + Queue queue(1, 1, 40ms, 1500ms); + int failures = 0; + auto check = [&](bool ok, const char* what) { + std::printf("%s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) ++failures; + }; + std::promise<void> release, started; + auto gate = release.get_future().share(); + auto state = std::make_shared<int>(0); + std::weak_ptr<int> lifetime = state; + std::atomic<int> builds{0}; + auto slow = queue.request("shader", state, false, [&](int& value) { + ++builds; + started.set_value(); + gate.wait(); + value = 42; + }); + started.get_future().wait(); + auto duplicate = queue.request("shader", std::make_shared<int>(7), false, [&](int&) { ++builds; }); + state.reset(); + check(slow == duplicate && !lifetime.expired(), "equal requests share a job that owns its input"); + // The next caller, on another title thread, must not reserve an already spent frame budget. + check(!queue.ready(slow, 10, false), "blocked compiler yields after its frame budget"); + auto start = Queue::Clock::now(); + check(!queue.ready(duplicate, 10, false) && Queue::Clock::now() - start < 30ms, "same frame cannot spend its budget twice"); + auto screen = queue.request("screen", std::make_shared<int>(0), true, [](int& value) { value = 99; }); + check(queue.ready(screen, 10, true) && *screen->state == 99, "screen completes with ordinary worker blocked"); + release.set_value(); + check(queue.ready(slow, 11, false) && *duplicate->state == 42 && builds == 1, "later call receives the actual shared result"); + auto bad = queue.request("throw", std::make_shared<int>(0), false, [](int&) { throw std::runtime_error("test compile"); }); + check(queue.ready(bad, 12, false) && bad->failure, "throwing compiler reports terminal failure"); + auto next = queue.request("next", std::make_shared<int>(0), false, [](int& value) { value = 123; }); + check(queue.ready(next, 13, false) && !next->failure && *next->state == 123, "worker remains available after failure"); + Queue guard(1, 0, 1500ms, 0ms); + std::thread::id retired; + auto lost = guard.request("driver", std::make_shared<int>(0), false, [&](int&) { + retired = std::this_thread::get_id(); + Queue::active->lost(std::make_exception_ptr(std::runtime_error("simulated worker loss"))); + }); + check(guard.ready(lost, 1, false) && lost->failure, "lost compile publishes terminal failure"); + auto repeated = guard.request("driver", std::make_shared<int>(0), false, [](int&) {}); + check(repeated == lost && repeated->failure, "same request receives the recorded failure"); + auto replacement = guard.request("other", std::make_shared<int>(0), false, [&](int& value) { + value = std::this_thread::get_id() != retired; + }); + check(guard.ready(replacement, 2, false) && *replacement->state == 1, "replacement worker completes the next compile"); + // The exposure reset draw was dropped when unrelated work reserved the shared screen budget. + // Reproduce that state and ensure the exact initializer gets the first available worker. + Queue init(1, 0, 0ms, 100ms); + std::promise<void> open, occupied; + auto opened = open.get_future().share(); + auto blocker = init.request("busy", std::make_shared<int>(), true, [&](int&) { + occupied.set_value(); + opened.wait(); + }); + occupied.get_future().wait(); + check(!init.ready(blocker, 20, true), "unrelated compile exhausted screen budget"); + std::promise<void> allow_background; + auto allowed = allow_background.get_future().share(); + auto background = init.request("ordinary-screen", std::make_shared<int>(), true, [&](int&) { allowed.wait(); }); + auto first_use = init.request("initialization-variant", std::make_shared<int>(), true, [](int& result) { result = 37; }, true); + check(!init.ready(first_use, 20, true), "ordinary caller cannot wait on the same frame"); + auto release_worker = std::async(std::launch::async, [&] { + std::this_thread::sleep_for(5ms); + open.set_value(); + }); + check(init.ready_initialization(first_use) && *first_use->state == 37, "first initialization draw receives prioritized native variant"); + check(!init.ready_initialization(background), "initializer wait on stalled driver is bounded"); + start = Queue::Clock::now(); + check(!init.ready_initialization(background) && Queue::Clock::now() - start < 50ms, "concurrent or later calls cannot extend the deadline"); + allow_background.set_value(); + check(init.ready(background, 21, true), "late completion remains usable"); + check(guard.ready_initialization(lost) && lost->failure, "a terminal compiler fault ends the wait"); + return failures ? 1 : 0; +} diff --git a/tests/startup_gpu_compute_trace.inl b/tests/startup_gpu_compute_trace.inl new file mode 100644 index 0000000000..b76383be98 --- /dev/null +++ b/tests/startup_gpu_compute_trace.inl @@ -0,0 +1,430 @@ +void material_feedback_test(HostHeap& heap, const u32 (&lazy)[8], ID3D12Resource* expected) +{ + constexpr UINT cpu_slot = 91, gpu_slot = 92, unused_slot = 93, source_slot = 94; + for (UINT slot : {cpu_slot, gpu_slot, unused_slot}) { + std::memcpy(fx.heap_memory + slot * 32, lazy, 32); + if (slot != gpu_slot) heap.mirror(slot, false); // a fresh title copy can precede the heap scan + } + auto srv = buffer_srv(DXGI_FORMAT_R32_TYPELESS, 4, 12, 0, true); + auto upload = buffer(128, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + auto wrapper = buffer_wrapper(128, 128); + fx.resources[wrapper - 1].desktop = upload.Get(); + fx.find_fails = true; + note(source_slot, 18, wrapper, &srv, sizeof(srv)); + CHECK(heap.mirror(source_slot)); + constexpr x2w_material::Mask fields = (1u << 0) | (1u << 4) | (1u << 6); + auto cpu_record = heap.material_record(source_slot, 8, fields); + fx.find_fails = false; + CHECK(cpu_record.source.Get() == upload.Get() && cpu_record.offset == 24 && cpu_record.bytes == 40); + CHECK(!heap.material_record(source_slot, 24, fields).source && !heap.material_record(source_slot, 1, fields).source); + CHECK(heap.material_record(source_slot, 24, 0x0004).source && !heap.material_record(source_slot, 8, 0xfeff).source); + x2w_material_trace::Words words{cpu_slot, cpu_slot, unused_slot, ~0u, cpu_slot, ~0u, cpu_slot}; + void* ptr{}; + CHECK(SUCCEEDED(upload->Map(0, nullptr, &ptr))); + if (!ptr) return; + std::memcpy(static_cast<char*>(ptr) + 24, words.data(), x2w_material::byte_count(cpu_record.fields)); + upload->Unmap(0, nullptr); + x2w_material_trace::Words read{}; + CHECK(x2w_material_trace::cpu_words(cpu_record, read) && read == words); + CHECK(heap.materialize(nullptr, read, fields) == 1 && heap.kept_at(cpu_slot) == expected); + CHECK(!heap.kept_at(unused_slot) && heap.materialize(nullptr, read, fields) == 0); + wrapper = buffer_wrapper(128, 128); + srv.Buffer.NumElements = 24; + note(source_slot, 18, wrapper, &srv, sizeof(srv)); + CHECK(heap.mirror(source_slot)); + constexpr x2w_material::Mask wide = 0xfeff; + auto gpu_record = heap.material_record(source_slot, 8, wide); + CHECK(gpu_record.source.Get() == fx.window.Get() && gpu_record.offset == window_offset + 128 + 24); + CHECK(!x2w_material_trace::cpu_words(gpu_record, read)); + if (!gpu_record.source) return; + constexpr UINT field12 = 2111, backlog = 501; + u32 streamed[8]; + std::copy_n(lazy, 8, streamed); + streamed[1] += 65536; + fixture_blocked_address = (u64{streamed[2]} << 32) | streamed[1]; + std::memcpy(fx.heap_memory + field12 * 32, streamed, 32); + heap.mirror(field12, false); + std::memcpy(fx.heap_memory + backlog * 32, lazy, 32); + heap.mirror(backlog, false); + words[3] = field12; + words[2] = cpu_slot; + words[8] = unused_slot; + words[15] = gpu_slot; + CHECK(SUCCEEDED(upload->Map(0, nullptr, &ptr))); + std::memcpy(ptr, words.data(), sizeof(words)); + upload->Unmap(0, nullptr); + begin(); + D3D12_RESOURCE_STATES before = D3D12_RESOURCE_STATE_COMMON; + auto transition = [&](D3D12_RESOURCE_STATES next) { + D3D12_RESOURCE_BARRIER b{}; + b.Transition = {fx.window.Get(), 0, before, next}; + fx.list->ResourceBarrier(1, &b); + before = next; + }; + transition(D3D12_RESOURCE_STATE_COPY_DEST); + fx.list->CopyBufferRegion(fx.window.Get(), gpu_record.offset, upload.Get(), 0, sizeof(words)); + x2w_material_trace::copy_record(fx.list.Get(), gpu_record, fx.readback.Get(), before, transition); + CHECK(before == D3D12_RESOURCE_STATE_COPY_DEST); + transition(D3D12_RESOURCE_STATE_COMMON); + end_and_wait(); + CHECK(SUCCEEDED(fx.readback->Map(0, nullptr, &ptr))); + std::memcpy(read.data(), ptr, sizeof(read)); + fx.readback->Unmap(0, nullptr); + CHECK(read == words && heap.materialize(nullptr, read, wide) == 1 && heap.kept_at(gpu_slot) == expected); + CHECK(pick(heap, 7, gpu_slot, 1)[0] == 204 && !heap.kept_at(unused_slot)); + std::vector<x2w_material_trace::Slot> slots; + heap.material_slots(slots); + const auto pending = std::find_if(slots.begin(), slots.end(), [field12](const auto& s) { return s.index == field12; }); + CHECK(pending != slots.end() && pending->lazy && !std::strcmp(pending->material_retry, "backing_unavailable")); + CHECK(!heap.kept_at(field12) && !heap.kept_at(backlog)); + fixture_blocked_address = 0; + fixture_room = 0; + fixture_needs_allocation = true; + CHECK(!heap.materialize(nullptr, read, 1u << 3) && !fixture_creations && !heap.kept_at(field12)); + ++fixture_epoch; + LazyBudget budget; + heap.warm_lazy(nullptr, 100, budget, 1, 1ull << 30, 1000); + CHECK(budget.visits == 1 && !budget.bytes && !fixture_creations && !heap.kept_at(field12)); + fixture_needs_allocation = false; + fixture_remap_on_probe = true; + CHECK(!heap.materialize(nullptr, read, 1u << 3) && !heap.kept_at(field12)); + partial_clamp = 0.5f; + ++fixture_epoch; + heap.warm_lazy(nullptr, 100, budget, 2, 1ull << 30, 1000); + CHECK(budget.visits == 2 && budget.bytes == 4096 && !fixture_creations); + CHECK(heap.kept_at(field12) == expected && !heap.kept_at(backlog)); + partial_clamp = 0; + ++fixture_epoch; + heap.warm_lazy(nullptr, 100, budget, 3, 1ull << 30, 1000); + CHECK(budget.visits == 3 && budget.bytes == 8192 && !fixture_creations && !heap.kept_at(backlog)); + fixture_room = UINT64_MAX; + CHECK(pick(heap, 7, field12, 1)[0] == 204); + // The title reuses the selected slot before its retry. The replacement has + // not appeared in a fenced record, so it returns to the regular rotation. + streamed[1] += 65536; + fixture_blocked_address = (u64{streamed[2]} << 32) | streamed[1]; + std::memcpy(fx.heap_memory + field12 * 32, streamed, 32); + heap.mirror(field12, false); + CHECK(!heap.materialize(nullptr, read, 1u << 3)); + streamed[1] += 65536; + std::memcpy(fx.heap_memory + field12 * 32, streamed, 32); + fixture_blocked_address = 0; + ++fixture_epoch; + heap.warm_lazy(nullptr, 101, budget, 1, 1ull << 30, 1000); + CHECK(!heap.kept_at(field12)); +} + +bool pixel_subresource_capture_test() +{ + using Image = x2w_compute_trace::Image; + const auto input = Image::color_box(2560,1440,{650,300}); + const auto output = Image::color_box(3840,2160,{650,300}); + const auto edge = Image::color_box(3840,2160,{1000,0}); + if (input.left != 1579 || input.top != 389 || output.left != 2368 || output.top != 584 || + edge.right != 3840 || edge.top != 0) return false; + auto* device = fx.device.Get(); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = desc.Height = 16; + desc.MipLevels = desc.DepthOrArraySize = 2; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_TYPELESS; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr<ID3D12Resource> source; + if (FAILED(device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&source)))) return false; + x2w_compute_trace::Image image; + if (!image.init(device, {source.Get(), 1, 32, true, false, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM}) || + image.width() != 8 || image.height() != 8 || image.footprint.Footprint.Format != DXGI_FORMAT_R8G8B8A8_UNORM) return false; + x2w_compute_trace::Image invalid; + if (invalid.init(device, {source.Get(), 1, 32, false, false, 1, 1, DXGI_FORMAT_R32_FLOAT})) return false; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + ComPtr<ID3D12DescriptorHeap> views; + if (FAILED(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&views)))) return false; + D3D12_RENDER_TARGET_VIEW_DESC rtv{}; + rtv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rtv.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; + rtv.Texture2DArray = {1, 1, 1, 0}; + const auto handle = views->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(source.Get(), &rtv, handle); + begin(); + for (UINT phase = 0; phase < 2; ++phase) { + float color[]{float(phase), 1.f-float(phase), 0, 1}; + fx.list->ClearRenderTargetView(handle, color, 0, nullptr); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Transition = {source.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE}; + fx.list->ResourceBarrier(1, &barrier); + image.record(fx.list.Get(), phase != 0); + std::swap(barrier.Transition.StateBefore, barrier.Transition.StateAfter); + fx.list->ResourceBarrier(1, &barrier); + } + end_and_wait(); + for (UINT phase = 0; phase < 2; ++phase) { + auto* readback = phase ? image.post.Get() : image.pre.Get(); + void* ptr{}; + if (FAILED(readback->Map(0, nullptr, &ptr))) return false; + const auto* pixel = static_cast<const unsigned char*>(ptr); + const bool ok = pixel[0] == 255 * phase && pixel[1] == 255 * (1 - phase); + readback->Unmap(0, nullptr); + if (!ok) return false; + } + return SUCCEEDED(device->GetDeviceRemovedReason()); +} + +bool material_record_test() +{ + std::istringstream rows("20 22 33 7b\n10 44 55 5\n20 66 77 f\nbad row\n"); + const auto entries = x2w_material::read_profile(rows); + if (entries.size() != 3) return false; + for (const auto& entry : entries) { + unsigned char header[20]{'D','X','B','C'}; + std::memcpy(header + 4, &entry.hash_low, 8); + std::memcpy(header + 12, &entry.hash_high, 8); + if (x2w_material::lookup(entries, entry.key, header, sizeof(header)) != entry.fields) return false; + header[19] ^= 0x80; + if (x2w_material::lookup(entries, entry.key, header, sizeof(header)) != 0) return false; + } + if (x2w_material::byte_count(4) != 12 || x2w_material::byte_count(0xfeff) != 64) return false; + x2w_material_trace::Probe probe; + if (!x2w_material_trace::init(fx.device.Get(), probe)) return false; + auto upload = buffer(64, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + auto gpu = buffer(64, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + if (!upload || !gpu) return false; + const UINT words[7]{4321, 0xf8001234, 17, 0x12345678, 0x80000020, 0, 0xffffffff}; + void* ptr = nullptr; + if (FAILED(upload->Map(0, nullptr, &ptr))) return false; + std::memcpy(ptr, words, sizeof(words)); + upload->Unmap(0, nullptr); + D3D12_DESCRIPTOR_HEAP_DESC heap{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr<ID3D12DescriptorHeap> table; + if (FAILED(fx.device->CreateDescriptorHeap(&heap, IID_PPV_ARGS(&table)))) return false; + D3D12_SHADER_RESOURCE_VIEW_DESC raw{}; + raw.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + raw.Format = DXGI_FORMAT_R32_TYPELESS; + raw.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + raw.Buffer.FirstElement = 4; + raw.Buffer.NumElements = 12; + raw.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + fx.device->CreateShaderResourceView(gpu.Get(), &raw, table->GetCPUDescriptorHandleForHeapStart()); + begin(); + probe.base = 8; + probe.fields = 1u << 6; + fx.list->CopyBufferRegion(gpu.Get(), 24, upload.Get(), 0, sizeof(words)); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Transition = {gpu.Get(), 0, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE}; + fx.list->ResourceBarrier(1, &barrier); + ID3D12DescriptorHeap* heaps[] = {table.Get()}; + fx.list->SetDescriptorHeaps(1, heaps); + x2w_material_trace::record(fx.list.Get(), probe, table->GetGPUDescriptorHandleForHeapStart()); + end_and_wait(); + if (FAILED(fx.device->GetDeviceRemovedReason()) || FAILED(probe.readback->Map(0, nullptr, &ptr))) return false; + const bool correct = std::memcmp(ptr, words, sizeof(words)) == 0 && + x2w_material_trace::index(words[1]) == 0x1234 && x2w_material_trace::index(words[3]) == 2097151 && + x2w_material_trace::index(words[4]) == 32; + probe.readback->Unmap(0, nullptr); + return correct; +} + +// Exercise the readback path on a compute queue with two different values from the same UAV. +bool compute_texture_capture_test(UINT volume_depth = 0) +{ + auto* device = fx.device.Get(); + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> alloc; + ComPtr<ID3D12GraphicsCommandList> list; + D3D12_COMMAND_QUEUE_DESC q{}; + q.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + if (FAILED(device->CreateCommandQueue(&q, IID_PPV_ARGS(&queue))) || + FAILED(device->CreateCommandAllocator(q.Type, IID_PPV_ARGS(&alloc))) || + FAILED(device->CreateCommandList(0, q.Type, alloc.Get(), nullptr, IID_PPV_ARGS(&list)))) return false; + D3D12_RESOURCE_DESC tex{}; + tex.Dimension = volume_depth ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; + tex.Width = volume_depth ? 33 : 271; + tex.Height = volume_depth ? 33 : 135; + tex.DepthOrArraySize = volume_depth ? static_cast<UINT16>(volume_depth) : 1; + tex.MipLevels = tex.SampleDesc.Count = 1; + tex.Format = volume_depth ? DXGI_FORMAT_R16G16B16A16_FLOAT : DXGI_FORMAT_R32_UINT; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr<ID3D12Resource> image; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &tex, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + nullptr, IID_PPV_ARGS(&image)))) return false; + + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr<ID3D12DescriptorHeap> views; + if (FAILED(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&views)))) return false; + device->CreateUnorderedAccessView(image.Get(), nullptr, nullptr, views->GetCPUDescriptorHandleForHeapStart()); + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1}; + D3D12_ROOT_PARAMETER root[2]{}; + root[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + root[0].DescriptorTable = {1, &range}; + root[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + root[1].Constants.Num32BitValues = 1; + D3D12_ROOT_SIGNATURE_DESC rs{2, root}; + ComPtr<ID3DBlob> serialized, cs; + ComPtr<ID3D12RootSignature> sig; + if (FAILED(D3D12SerializeRootSignature(&rs, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, nullptr)) || + FAILED(device->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), IID_PPV_ARGS(&sig)))) + return false; + constexpr char source[] = "RWTexture2D<uint> t:register(u0); cbuffer C:register(b0){uint d;} " + "[numthreads(1,1,1)] void main(uint3 p:SV_DispatchThreadID){t[p.xy]=d+p.x+1024*p.y;}"; + constexpr char volume_source[] = "RWTexture3D<float4> t:register(u0); cbuffer C:register(b0){uint d;} " + "[numthreads(1,1,1)] void main(uint3 p:SV_DispatchThreadID){t[p]=float4(p,d);}"; + const char* shader_source = volume_depth ? volume_source : source; + if (FAILED(D3DCompile(shader_source, std::strlen(shader_source), nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, &cs, nullptr))) return false; + D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = sig.Get(); + pso_desc.CS = {cs->GetBufferPointer(), cs->GetBufferSize()}; + ComPtr<ID3D12PipelineState> pso; + if (FAILED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso)))) return false; + + x2w_compute_trace::Bindings bindings; + bindings.add({image.Get(), 2, 8, true}); + bindings.add({image.Get(), 2, 8, true}); + x2w_compute_trace::Image sample; + if (bindings.count != 1 || !sample.init(device, bindings.values[0])) return false; + ID3D12DescriptorHeap* heaps[] = {views.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(sig.Get()); + list->SetPipelineState(pso.Get()); + list->SetComputeRootDescriptorTable(0, views->GetGPUDescriptorHandleForHeapStart()); + for (UINT phase = 0; phase < 2; ++phase) { + list->SetComputeRoot32BitConstant(1, volume_depth ? phase : phase * 0x200000, 0); + list->Dispatch(UINT(tex.Width), tex.Height, tex.DepthOrArraySize); + x2w_gpu::transition_all(list.Get(), image.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + sample.record(list.Get(), phase != 0); + x2w_gpu::transition_all(list.Get(), image.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + ComPtr<ID3D12Fence> fence; + if (FAILED(list->Close()) || FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) return false; + ID3D12CommandList* batch[] = {list.Get()}; + for (UINT replay = 1; replay <= 2; ++replay) { + queue->ExecuteCommandLists(1, batch); + if (FAILED(queue->Signal(fence.Get(), replay)) || FAILED(fence->SetEventOnCompletion(replay, nullptr)) || + fence->GetCompletedValue() != replay) return false; + for (UINT phase = 0; phase < 2; ++phase) { + auto* readback = phase ? sample.post.Get() : sample.pre.Get(); + void* data = nullptr; + const D3D12_RANGE read{0, SIZE_T(sample.size)}; + if (FAILED(readback->Map(0, &read, &data))) return false; + bool ok = true; + if (volume_depth) { + const auto& layout = sample.footprint.Footprint; + const UINT expected_depth = volume_depth == 33 ? 33u : 3u; + ok = layout.Width == 33 && layout.Height == 33 && layout.Depth == expected_depth; + for (UINT z = 0; ok && z < expected_depth; ++z) { + const UINT expected_z = expected_depth == 33 ? z : z * 32; + for (UINT y = 0; y < 33; ++y) { + const auto* row = reinterpret_cast<const UINT16*>(static_cast<const unsigned char*>(data) + + sample.footprint.Offset + SIZE_T(z * 33 + y) * layout.RowPitch); + for (UINT x = 0; x < 33; ++x) { + using DirectX::PackedVector::XMConvertHalfToFloat; + if (XMConvertHalfToFloat(row[x*4]) != x || XMConvertHalfToFloat(row[x*4+1]) != y || + XMConvertHalfToFloat(row[x*4+2]) != expected_z || XMConvertHalfToFloat(row[x*4+3]) != phase) + ok = false; + } + } + } + } else for (UINT y = 0; y < 128; ++y) { + const auto* row = reinterpret_cast<const UINT*>(static_cast<const unsigned char*>(data) + + sample.footprint.Offset + SIZE_T(y) * sample.footprint.Footprint.RowPitch); + for (UINT x = 0; x < 256; ++x) + if (row[x] != phase * 0x200000 + 7 + x + (3 + y) * 1024) ok = false; + } + const D3D12_RANGE none{0,0}; + readback->Unmap(0, &none); + if (!ok) return false; + } + } + return true; +} + +bool compute_priority_depth_capture_test() +{ + using namespace x2w_compute_trace; + auto* device = fx.device.Get(); + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = 271; + d.Height = 135; + d.DepthOrArraySize = d.MipLevels = d.SampleDesc.Count = 1; + d.Format = DXGI_FORMAT_R32G8X24_TYPELESS; + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr<ID3D12Resource> depth; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_DEPTH_WRITE, + nullptr, IID_PPV_ARGS(&depth)))) return false; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; + ComPtr<ID3D12DescriptorHeap> views; + if (FAILED(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&views)))) return false; + D3D12_DEPTH_STENCIL_VIEW_DESC dsv{}; + dsv.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + const auto handle = views->GetCPUDescriptorHandleForHeapStart(); + device->CreateDepthStencilView(depth.Get(), &dsv, handle); + + Bindings bindings; + d.Format = DXGI_FORMAT_R32_UINT; + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + std::array<ComPtr<ID3D12Resource>, 4> colors; + for (UINT i=0; i<colors.size(); ++i) { + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&colors[i])))) return false; + bindings.add({colors[i].Get(), 0, i * 8, false}); + bindings.add({colors[i].Get(), 1, i * 8, true}); + } + bindings.add({depth.Get(), 0, 464, false}, true); + bindings.add({colors[3].Get(), 1, 176, true}, true); + bindings.add({colors[0].Get(), 1, 32, true}, true); + UINT prioritized = 0; + bool picked_depth = false, picked_light = false, relabeled = false; + for (const auto& b : bindings.values) { + if (!b.priority) continue; + ++prioritized; + picked_depth |= b.texture == depth.Get() && b.offset == 464 && !b.write; + picked_light |= b.texture == colors[3].Get() && b.offset == 176 && b.write; + relabeled |= b.texture == colors[0].Get() && b.offset == 32 && b.write; + } + if (bindings.count != 6 || prioritized != 3 || !picked_depth || !picked_light || !relabeled) return false; + Image sample, stencil; + if (!sample.init(device, {depth.Get(),0,464,false,true,0,0,DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS}) || + !sample.full_depth_plane || !stencil.init(device, {depth.Get(),0,464,false,true,0,0,DXGI_FORMAT_X32_TYPELESS_G8X24_UINT,1}) || + !stencil.full_depth_plane || stencil.source_subresource != 1) return false; + begin(); + fx.list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.875f, 23, 0, nullptr); + const D3D12_RECT center{7,3,263,131}; + fx.list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.25f, 91, 1, ¢er); + x2w_gpu::transition_all(fx.list.Get(), depth.Get(), D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE); + sample.record(fx.list.Get(),false); + stencil.record(fx.list.Get(),false); + end_and_wait(); + void* data = nullptr; + if (FAILED(sample.pre->Map(0,nullptr,&data))) return false; + const auto* pixels = static_cast<const unsigned char*>(data) + sample.footprint.Offset; + const auto stride = sample.output_row_bytes() / sample.width(); + bool ok = sample.width() == 256 && sample.height() == 128 && stride >= sizeof(float); + for (UINT y = 0; ok && y < sample.height(); ++y) { + const auto* row = sample.row(pixels,y,0); + for (UINT x = 0; x < sample.width(); ++x) { + float value; + std::memcpy(&value, row + x * stride, sizeof(value)); + if (value != 0.25f) { ok = false; break; } + } + } + const D3D12_RANGE none{}; + sample.pre->Unmap(0,&none); + if (FAILED(stencil.pre->Map(0,nullptr,&data))) return false; + pixels = static_cast<const unsigned char*>(data) + stencil.footprint.Offset; + const auto bytes_per_texel = stencil.row_bytes / stencil.footprint.Footprint.Width; + for (UINT y = 0; ok && y < stencil.height(); ++y) { + const auto* row = stencil.row(pixels,y,0); + for (UINT x = 0; x < stencil.width(); ++x) { + const auto* first = row + x * bytes_per_texel; + if (std::find(first, first + bytes_per_texel, 91u) == first + bytes_per_texel) { ok = false; break; } + } + } + stencil.pre->Unmap(0,&none); + return ok; +} diff --git a/tests/startup_gpu_db_check.cpp b/tests/startup_gpu_db_check.cpp new file mode 100644 index 0000000000..87b7dfbfb6 --- /dev/null +++ b/tests/startup_gpu_db_check.cpp @@ -0,0 +1,83 @@ +// startup_gpu_db_check: the runtime's C5 lookup (src/startup_stubs/gpu_db.cpp) over a synthetic database. +// startup_gpu_db_check a record found by its bytecode and stage, converted to gpu_abi.h's types; +// another stage and other bytes miss; the manifest is reported. +// startup_gpu_db_check --mutate the database claims raw_views 0 (made without twins) while this run has +// twins: the load must be refused, so the lookup fails (WILL_FAIL). +#include <windows.h> + +#include <cstdio> +#include <cstring> +#include <string> +#include <vector> + +#include "shader_db/shader_db_writer.h" +#include "startup_stubs/gpu_db.h" + +using namespace x2w_gpu; + +int main(int argc, char** argv) +{ + const bool mutate = argc >= 2 && !std::strcmp(argv[1], "--mutate"); + int failures = 0; + const auto check = [&](bool ok, const char* what) { + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } + }; + const unsigned char title[] = "DXBC a title's container bytes"; + char key[17]; + gpu_key(title, sizeof(title), key); + + shader_db::ShaderRecord r; + r.key = std::strtoull(key, nullptr, 16); + r.stage = shader_db::Stage::ps; + r.container_bytes = sizeof(title); + r.dxil = {'D', 'X', 'B', 'C', 1, 2, 3}; + r.user_data = {{0, 2, shader_db::root_table, 0}, {4, 0, shader_db::root_other_base + abi::user_view_bias, 0}}; + r.user_data_dwords = 8; + r.samplers = {{1, 2, 3, 4}}; + r.static_samplers = {{0x15, {1, 2, 3}, 0.5f, 16, 0, 0, 0.0f, 13.0f}}; + r.root_srvs = {abi::slot_strides}; + r.root_indexed_views = {{1, 2, 3, 64, 4}}; + r.used = {{shader_db::resource_uav, shader_db::root_table, 8, 0, 16, 8, 2, 1}, {shader_db::resource_other_base + 9, shader_db::root_constants, 0, 0, 0, 4, 0, 0}}; + r.stores = true; + wchar_t dir[MAX_PATH]; + GetTempPathW(MAX_PATH, dir); + const std::wstring path = std::wstring(dir) + (mutate ? L"startup_gpu_db_check_mutate.vxdb" : L"startup_gpu_db_check.vxdb"); + const std::string manifest = std::string("format gpu-x2w-1\nview_heap_limit 2097151\nraw_views ") + (mutate ? "0" : "2097152") + + "\nmax_wave 64\nhost_rdna 15\nshader_opt 0x3f\ngroup_sync 2\nX2W_SHADERCFG_HELPER_OWN \ncommit abc123\n"; + std::string error; + check(shader_db::write_db(path, {r}, manifest, error), "write"); + SetEnvironmentVariableW(L"X2W_GPU_DB", path.c_str()); + SetEnvironmentVariableW(L"X2W_GPU_ABI", L"1"); + + const GpuShader* s = gpu_shader(title, sizeof(title), GpuStage::pixel); + check(s != nullptr, "the record is found by its bytecode and stage"); + if (s) { + check(!std::strcmp(s->key, key), "key"); + check(s->hw_stage == GpuHwStage::ps && s->stage == GpuStage::pixel, "stages"); + check(s->dxil_bytes == 7 && !std::memcmp(s->dxil, "DXBC", 4), "dxil"); + check(s->user_data.count == 2 && s->user_data[0].root == GpuRootType::table && s->user_data[0].slot == 2 && + s->user_data[1].root == GpuRootType::other && s->user_data[1].other == abi::user_view_bias && s->user_data[1].index == 4, + "user data and an Other root code"); + check(s->user_data_dwords() == 8, "user_data_dwords"); + check(s->samplers.count == 1 && s->samplers[0].words[3] == 4, "sampler words"); + check(s->static_samplers.count == 1 && s->static_samplers[0].max_lod == 13.0f && s->static_samplers[0].address[2] == 3, "static sampler"); + check(s->root_srvs.count == 1 && s->root_srvs[0] == abi::slot_strides && s->root_cbvs.empty(), "root views"); + check(s->root_indexed_views.count == 1 && s->root_indexed_views[0].byte_offset == 64, "root indexed views"); + check(s->used.count == 2 && s->used[0].kind == GpuResourceType::uav && s->used[0].stride == 16 && s->used[0].dwords == 8 && + s->used[1].kind == GpuResourceType::other && s->used[1].other_kind == 9, + "used resources"); + check(s->stores && !s->stores_by_address && !s->has_threads, "stores and threads"); + } + check(!gpu_shader(title, sizeof(title), GpuStage::vertex), "another stage misses"); + check(!gpu_shader(title, sizeof(title) - 1, GpuStage::pixel), "other bytes miss"); + check(gpu_shader_by_key(key, GpuStage::pixel) == s, "by key"); + const GpuManifest* m = gpu_manifest(); + check(m && m->view_heap_limit == abi::view_heap_limit && m->raw_views == abi::raw_views && m->max_wave == 64 && m->host_rdna && + m->opt_bits == 0x3f && m->group_sync && !m->helper_own && !std::strcmp(m->commit, "abc123"), + "manifest"); + std::printf("%s\n", failures ? "startup_gpu_db_check: FAILED" : "startup_gpu_db_check: ok"); + return failures ? 1 : 0; +} diff --git a/tests/startup_gpu_depth_twins.cpp b/tests/startup_gpu_depth_twins.cpp new file mode 100644 index 0000000000..099122d767 --- /dev/null +++ b/tests/startup_gpu_depth_twins.cpp @@ -0,0 +1,128 @@ +#include "startup_stubs/gpu_depth_twins.h" +#include <dxgi1_6.h> +#include <cstdio> +#include <cstring> +#include <map> + +using namespace x2w_depth_twins; +namespace { +ComPtr<ID3D12Resource> buffer(ID3D12Device* device, UINT64 size, D3D12_HEAP_TYPE kind, D3D12_RESOURCE_STATES initial) +{ + const D3D12_HEAP_PROPERTIES props{kind}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ComPtr<ID3D12Resource> r; + device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, initial, nullptr, IID_PPV_ARGS(&r)); + return r; +} +bool run(ID3D12Device* device, DXGI_FORMAT family, bool stencil) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 17; desc.Height = 7; desc.DepthOrArraySize = 2; desc.MipLevels = 3; + desc.Format = family; + desc.SampleDesc.Count = 1; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr<ID3D12Resource> original; + if (FAILED(device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&original)))) return false; + desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + Twins twins; + if (!twins.create(device, original.Get(), desc)) return false; + D3D12_UNORDERED_ACCESS_VIEW_DESC wanted{}, chosen{}; + wanted.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + wanted.Texture2DArray.ArraySize = 2; + wanted.Texture2DArray.PlaneSlice = stencil ? 1 : 0; + if (twins.view(&wanted, chosen) != twins.colour.Get() || chosen.Texture2DArray.PlaneSlice) return false; + if (stencil && (chosen.Format != DXGI_FORMAT_R8_UINT || twins.view(nullptr, chosen) != twins.depth_plane.Get())) return false; + + constexpr UINT n = 6; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT layout[n]{}; + UINT64 row[n]{}, bytes = 0; + auto colour = twins.colour->GetDesc(); + device->GetCopyableFootprints(&colour, 0, n, 0, layout, nullptr, row, &bytes); + auto upload = buffer(device, bytes * 2, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto readback = buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + if (!upload || !readback) return false; + BYTE* src = nullptr; + if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&src)))) return false; + std::memset(src, 0, static_cast<size_t>(bytes) * 2); + for (UINT i = 0; i < n; ++i) + for (UINT y = 0; y < layout[i].Footprint.Height; ++y) + std::memset(src + layout[i].Offset + y * layout[i].Footprint.RowPitch, 11 + i * 13 + y, static_cast<size_t>(row[i])); + upload->Unmap(0, nullptr); + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> alloc; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + const D3D12_COMMAND_QUEUE_DESC q{D3D12_COMMAND_LIST_TYPE_COMPUTE}; + if (FAILED(device->CreateCommandQueue(&q, IID_PPV_ARGS(&queue))) || + FAILED(device->CreateCommandAllocator(q.Type, IID_PPV_ARGS(&alloc))) || + FAILED(device->CreateCommandList(0, q.Type, alloc.Get(), nullptr, IID_PPV_ARGS(&list))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) return false; + std::map<ID3D12Resource*, D3D12_RESOURCE_STATES> states; + const auto set = [&](ID3D12Resource* r, D3D12_RESOURCE_STATES next) { + auto& current = states[r]; + if (current == next) return; + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, current, next}; + list->ResourceBarrier(1, &b); + current = next; + }; + auto copy = [&](ID3D12Resource* staging, bool write, bool clear) { + set(twins.colour.Get(), write ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COPY_SOURCE); + for (UINT i = 0; i < n; ++i) { + D3D12_TEXTURE_COPY_LOCATION host{staging, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + host.PlacedFootprint = layout[i]; + // All inputs are positive patterns, so replacing the source by zero before copying it back + // catches a missing transfer in either direction. + if (clear) host.PlacedFootprint.Offset = (bytes + 511) & ~UINT64{511}; + D3D12_TEXTURE_COPY_LOCATION tex{twins.colour.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + tex.SubresourceIndex = i; + list->CopyTextureRegion(write ? &tex : &host, 0, 0, 0, write ? &host : &tex, nullptr); + } + }; + copy(upload.Get(), true, false); + twins.copy_colour(list.Get(), false, set); + copy(upload.Get(), true, true); + twins.copy_colour(list.Get(), true, set); + copy(readback.Get(), false, false); + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), 1)) || FAILED(fence->SetEventOnCompletion(1, nullptr)) || + FAILED(device->GetDeviceRemovedReason())) return false; + BYTE* result = nullptr; + if (FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&result)))) return false; + bool ok = true; + for (UINT i = 0; i < n; ++i) + for (UINT y = 0; y < layout[i].Footprint.Height; ++y) + for (UINT x = 0; x < row[i]; ++x) + ok &= result[layout[i].Offset + y * layout[i].Footprint.RowPitch + x] == 11 + i * 13 + y; + readback->Unmap(0, nullptr); + return ok; +} +} +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + ComPtr<IDXGIFactory6> f; + ComPtr<IDXGIAdapter1> adapter; + ComPtr<ID3D12Device> device; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&f)))) return 77; + const bool warp = std::strcmp(argv[1], "warp") == 0; + if (FAILED(warp ? f->EnumWarpAdapter(IID_PPV_ARGS(&adapter)) + : f->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&adapter))) || + FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) return 77; + for (auto f : {DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R32G8X24_TYPELESS}) { + const bool ok = run(device.Get(), f, f == DXGI_FORMAT_R24G8_TYPELESS || f == DXGI_FORMAT_R32G8X24_TYPELESS); + std::printf("format %d, 3 mips x 2 slices, both copy directions: %s\n", f, ok ? "pass" : "fail"); + if (!ok) return 1; + } +} diff --git a/tests/startup_gpu_heap.cpp b/tests/startup_gpu_heap.cpp new file mode 100644 index 0000000000..b0e6a97ced --- /dev/null +++ b/tests/startup_gpu_heap.cpp @@ -0,0 +1,1181 @@ +// startup_gpu_heap: the descriptor mirror (src/startup_stubs/gpu_heap.inl) on a real device, with a fixture +// title heap, title memory and window of our own, read by our own SM 6.6 shader (startup_gpu_heap.hlsl). +// +// startup_gpu_heap <warp|hardware> twins the raw twin of a typed, a structured and a raw view reads the +// view's bytes, bounded; a UAV twin writes them and nothing else; a +// CBV's twin is the CBV; the twin of a texture slot, of an empty slot +// and of the last slot reads zero; a dynamic slot's twin +// startup_gpu_heap <warp|hardware> views a structured view is made raw (raw_window), the table of strides, +// an unaligned CBV is null at the title slot, a V# record is a view, +// a view off its window's elements reads a copy of its own bytes +// startup_gpu_heap <warp|hardware> submit records the title copied as bytes are mirrored by submit(), a +// cleared one goes null, own-byte copies follow title memory, the +// texture of a made slot is due for upload +// +// WARP takes no heap of 2^22 views (debug layer id 645), so the WARP fixture halves the production heap sizes +// (twins at 2^20 in a heap of 2^21: Limits{2^20, 2^20}); on hardware it is the probed one, which must be 2^22 with +// twins at 2^21 (exit 77 if the host takes no 2^22). +#include "startup_stubs/gpu_heap.inl" + +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <map> +#include <cstdio> +#include <cstring> +#include <string> +#include <vector> + +#include "startup_gpu_heap_cs.h" +#include "startup_gpu_memory_cs.h" +#include "startup_gpu_memory_store_cs.h" +#include "startup_stubs/gpu_memory_arena.h" +#include "startup_stubs/gpu_memory.h" +#include "startup_stubs/gpu_packed_light.h" +#include "startup_stubs/small_texture_heap.h" +#include "startup_stubs/gpu_list_states.h" +#include "startup_stubs/gpu_transition.h" +#include "startup_stubs/gpu_compute_trace.h" +#include "startup_stubs/gpu_ambient.h" +#include "startup_stubs/gpu_resident_mips.h" +#include "startup_stubs/slice_footprints.h" +#include <d3dcompiler.h> + +using Microsoft::WRL::ComPtr; +using namespace gpu_heap; +using namespace gpu_mirror; + +namespace { + +int failures = 0; +#define CHECK(c) \ + do { \ + if (!(c)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); \ + ++failures; \ + } \ + } while (0) + +constexpr u32 title_slots = 4096; +constexpr u64 memory_bytes = 1u << 20; +constexpr u64 window_offset = 256; // where title memory starts in the window + +struct Fixture { + ComPtr<ID3D12Device> device; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + u64 fence_value = 0; + ComPtr<ID3D12RootSignature> root; + ComPtr<ID3D12PipelineState> pso; + ComPtr<ID3D12Resource> window, result, readback, texture; + unsigned char* memory = nullptr; // title memory + unsigned char* heap_memory = nullptr; // the title's descriptor memory + std::vector<Record> records; + std::vector<ResourceFacts> resources; // wrapper = index + 1 + std::vector<u64> uploads; + bool coherent = false; + bool find_fails = false; // find answers nothing (a window not known yet) +}; + +Fixture fx; +u64 mapped_texture = 0; +unsigned deferred_probes = 0; +unsigned resolved_probes = 0; +unsigned fixture_decline = 8; +u64 fixture_room = UINT64_MAX, fixture_epoch = 0, fixture_blocked_address = 0; +unsigned allocation_probes = 0; +bool fixture_needs_allocation = false; +bool fixture_remap_on_probe = false; +UINT fixture_creations = 0; +float partial_clamp = 0; +UINT vendor = 0; + +u64 title(u64 offset) { return reinterpret_cast<u64>(fx.memory) + offset; } +std::uint32_t pattern(u64 dword) { return 0x10000u + static_cast<std::uint32_t>(dword); } + +bool find(void*, u64 address, u64 bytes, ID3D12Resource** resource, u64* offset, u64* left) +{ + const u64 base = reinterpret_cast<u64>(fx.memory); + if (fx.find_fails) return false; + if (address < base || address - base >= memory_bytes || bytes > memory_bytes - (address - base)) return false; + *resource = fx.window.Get(); + *offset = address - base + window_offset; + *left = memory_bytes - (address - base); + return true; +} +bool record(void*, u32 id, Record* out) +{ + if (id >= fx.records.size()) return false; + *out = fx.records[id]; + return true; +} +bool resource(void*, u64 wrapper, ResourceFacts* out) +{ + if (!wrapper || wrapper > fx.resources.size()) return false; + *out = fx.resources[wrapper - 1]; + return true; +} +bool upload(void*, void*, u64 wrapper, ID3D12Resource*) +{ + fx.uploads.push_back(wrapper); + return true; +} + +u64 buffer_wrapper(u64 offset, u64 bytes) +{ + ResourceFacts f; + f.desktop = fx.window.Get(); // (the window stands in for the buffer's own copy) + f.buffer = true; + f.title_memory = title(offset); + f.bytes = bytes; + fx.resources.push_back(f); + return fx.resources.size(); +} +u64 texture_wrapper() +{ + ResourceFacts f; + f.desktop = fx.texture.Get(); + fx.resources.push_back(f); + return fx.resources.size(); +} +// A view record and the token for it written into title slot `index` (note_view's). +u32 note(u32 index, u32 slot, u64 wrapper, const void* desc, u32 bytes) +{ + Record r; + r.id = static_cast<u32>(fx.records.size()); + r.slot = slot; + r.resource = wrapper; + r.desc_bytes = bytes; + std::memcpy(r.desc, desc, bytes); + fx.records.push_back(r); + const std::uint32_t token[8] = {token_magic, r.id, slot, 0, static_cast<std::uint32_t>(wrapper), + static_cast<std::uint32_t>(wrapper >> 32), 0, 0}; + std::memcpy(fx.heap_memory + u64{index} * 32, token, 32); + return r.id; +} +D3D12_SHADER_RESOURCE_VIEW_DESC buffer_srv(DXGI_FORMAT format, u64 first, u32 n, u32 stride, bool raw) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = format; + d.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + d.Buffer.FirstElement = first; + d.Buffer.NumElements = n; + d.Buffer.StructureByteStride = stride; + d.Buffer.Flags = raw ? D3D12_BUFFER_SRV_FLAG_RAW : D3D12_BUFFER_SRV_FLAG_NONE; + return d; +} + +void wait() +{ + fx.queue->Signal(fx.fence.Get(), ++fx.fence_value); + HANDLE e = CreateEventA(nullptr, FALSE, FALSE, nullptr); + fx.fence->SetEventOnCompletion(fx.fence_value, e); + WaitForSingleObject(e, 10000); + CloseHandle(e); +} +ComPtr<ID3D12Resource> buffer(u64 bytes, D3D12_HEAP_TYPE type, D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) +{ + D3D12_HEAP_PROPERTIES heap{type}; + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = bytes; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + ComPtr<ID3D12Resource> r; + if (FAILED(fx.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, IID_PPV_ARGS(&r)))) return nullptr; + return r; +} +void begin() +{ + fx.allocator->Reset(); + fx.list->Reset(fx.allocator.Get(), nullptr); +} +void end_and_wait() +{ + fx.list->Close(); + ID3D12CommandList* lists[] = {fx.list.Get()}; + fx.queue->ExecuteCommandLists(1, lists); + wait(); +} +// The window gets title memory's bytes (from `window_offset` on). +void fill_window() +{ + auto up = buffer(memory_bytes + window_offset, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + void* data = nullptr; + up->Map(0, nullptr, &data); + std::memset(data, 0xee, window_offset); + std::memcpy(static_cast<unsigned char*>(data) + window_offset, fx.memory, memory_bytes); + up->Unmap(0, nullptr); + begin(); + fx.list->CopyBufferRegion(fx.window.Get(), 0, up.Get(), 0, memory_bytes + window_offset); + end_and_wait(); +} +// The window's dwords from title offset `offset`. +std::vector<std::uint32_t> read_window(u64 offset, u32 dwords) +{ + auto back = buffer(u64{dwords} * 4, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + begin(); + fx.list->CopyBufferRegion(back.Get(), 0, fx.window.Get(), window_offset + offset, u64{dwords} * 4); + end_and_wait(); + std::vector<std::uint32_t> out(dwords); + void* data = nullptr; + back->Map(0, nullptr, &data); + std::memcpy(out.data(), data, out.size() * 4); + back->Unmap(0, nullptr); + return out; +} +// Runs the shader on `heap` slot `slot`: what it read (or wrote) of `count` dwords. +std::vector<std::uint32_t> pick(ID3D12DescriptorHeap* heap, u32 mode, u32 slot, u32 count, u32 mark = 0) +{ + begin(); + ID3D12DescriptorHeap* heaps[] = {heap}; + fx.list->SetDescriptorHeaps(1, heaps); + fx.list->SetComputeRootSignature(fx.root.Get()); + fx.list->SetPipelineState(fx.pso.Get()); + const std::uint32_t constants[4] = {mode, slot, count, mark}; + fx.list->SetComputeRoot32BitConstants(0, 4, constants, 0); + fx.list->SetComputeRootUnorderedAccessView(1, fx.result->GetGPUVirtualAddress()); + fx.list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition.pResource = fx.result.Get(); + b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + b.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + fx.list->ResourceBarrier(1, &b); + fx.list->CopyBufferRegion(fx.readback.Get(), 0, fx.result.Get(), 0, 256); + std::swap(b.Transition.StateBefore, b.Transition.StateAfter); + fx.list->ResourceBarrier(1, &b); + end_and_wait(); + std::vector<std::uint32_t> out(count); + void* data = nullptr; + fx.readback->Map(0, nullptr, &data); + std::memcpy(out.data(), data, u64{count} * 4); + fx.readback->Unmap(0, nullptr); + return out; +} +std::vector<std::uint32_t> pick(HostHeap& heap, u32 mode, u32 slot, u32 count, u32 mark = 0) +{ + return pick(heap.heap(), mode, slot, count, mark); +} +bool all_zero(const std::vector<std::uint32_t>& v) +{ + for (auto x : v) + if (x) return false; + return true; +} +// The title's dwords from byte `offset`, then zeros, `count` in all with `n` of them the title's. +bool title_then_zero(const std::vector<std::uint32_t>& v, u64 offset, u32 n) +{ + for (u32 i = 0; i < v.size(); ++i) { + std::uint32_t want = 0; + if (i < n) std::memcpy(&want, fx.memory + offset + u64{i} * 4, 4); + if (v[i] != want) { + std::printf(" dword %u: 0x%08x, expected 0x%08x\n", i, v[i], want); + return false; + } + } + return true; +} + +int setup(bool warp) +{ + if (warp) { + ComPtr<ID3D12Debug> debug; + if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) debug->EnableDebugLayer(); + } + ComPtr<IDXGIFactory6> factory; + if (FAILED(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory)))) return 77; + ComPtr<IDXGIAdapter1> adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + } else { + for (UINT i = 0; factory->EnumAdapterByGpuPreference(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&adapter)) == S_OK; ++i) { + DXGI_ADAPTER_DESC1 d; + adapter->GetDesc1(&d); + if (!(d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) break; + adapter.Reset(); + } + } + if (!adapter || FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&fx.device)))) return 77; + { + DXGI_ADAPTER_DESC1 d; + adapter->GetDesc1(&d); + vendor = d.VendorId; + std::printf("adapter=%ls\n", d.Description); + } + D3D12_FEATURE_DATA_SHADER_MODEL sm{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS o{}; + fx.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &o, sizeof(o)); + if (FAILED(fx.device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &sm, sizeof(sm))) || sm.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + o.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) { + std::printf("no SM 6.6 / binding tier 3: skipped\n"); + return 77; + } + D3D12_COMMAND_QUEUE_DESC q{D3D12_COMMAND_LIST_TYPE_DIRECT}; + fx.device->CreateCommandQueue(&q, IID_PPV_ARGS(&fx.queue)); + fx.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&fx.allocator)); + fx.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, fx.allocator.Get(), nullptr, IID_PPV_ARGS(&fx.list)); + fx.list->Close(); + fx.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fx.fence)); + + D3D12_ROOT_PARAMETER1 params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants.Num32BitValues = 4; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC rs{D3D_ROOT_SIGNATURE_VERSION_1_1}; + rs.Desc_1_1.NumParameters = 2; + rs.Desc_1_1.pParameters = params; + rs.Desc_1_1.Flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; + ComPtr<ID3DBlob> blob, error; + if (FAILED(D3D12SerializeVersionedRootSignature(&rs, &blob, &error)) || + FAILED(fx.device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&fx.root)))) { + std::printf("root signature refused\n"); + return 1; + } + D3D12_COMPUTE_PIPELINE_STATE_DESC p{}; + p.pRootSignature = fx.root.Get(); + p.CS = {startup_gpu_heap_cs, sizeof(startup_gpu_heap_cs)}; + if (FAILED(fx.device->CreateComputePipelineState(&p, IID_PPV_ARGS(&fx.pso)))) { + std::printf("pipeline refused\n"); + return 1; + } + fx.window = buffer(memory_bytes + window_offset, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COMMON); + fx.result = buffer(256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + fx.readback = buffer(256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + { + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC t{}; + t.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + t.Width = 4; + t.Height = 4; + t.DepthOrArraySize = 1; + t.MipLevels = 1; + t.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + t.SampleDesc.Count = 1; + fx.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &t, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&fx.texture)); + } + fx.memory = static_cast<unsigned char*>(VirtualAlloc(nullptr, memory_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + fx.heap_memory = static_cast<unsigned char*>(VirtualAlloc(nullptr, u64{title_slots} * 32, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + for (u64 i = 0; i < memory_bytes / 4; ++i) { + const std::uint32_t v = pattern(i); + std::memcpy(fx.memory + i * 4, &v, 4); + } + fill_window(); + return 0; +} + +Env env() +{ + Env e; + e.device = fx.device.Get(); + e.coherent_window = [](u64 address, u64 bytes, ID3D12Resource* expected, u64 offset) { + return fx.coherent && address >= title(0) && address - title(0) < memory_bytes && + bytes <= memory_bytes - (address - title(0)) && offset == address - title(0) + window_offset && + expected == fx.window.Get(); + }; + e.find = find; + e.record = record; + e.resource = resource; + e.placement = [](u64 wrapper, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, u32 (&words)[8]) { + if (!wrapper || wrapper > fx.resources.size()) return false; + const auto& placed = fx.resources[wrapper - 1]; + if (!placed.desktop || placed.buffer || !placed.title_memory) return false; + auto desc = placed.desktop->GetDesc(); + desc.Flags = D3D12_RESOURCE_FLAGS(0x300000); + desc.Layout = D3D12_TEXTURE_LAYOUT(0x105); + desc.Alignment = 0; + return x2w_late_texture::encode(desc, srv, placed.title_memory, words); + }; + e.local_room = [](ID3D12Device*) { return fixture_room; }; + e.copied_bytes = []() -> u64 { return fx.uploads.size() * 4096; }; + e.mapping_epoch = [] { return fixture_epoch; }; + e.allocation_size = [](ID3D12Device*, const u32*) -> u64 { ++allocation_probes; return 65536; }; + e.upload = upload; + e.late_texture = [](const u32* w, D3D12_SHADER_RESOURCE_VIEW_DESC& srv, bool& pending, bool allow_create) -> u64 { + D3D12_RESOURCE_DESC desc{}; + x2w_late_texture::decode(w, desc, srv); + if (fixture_remap_on_probe) { + ++fixture_epoch; + fixture_remap_on_probe = false; + } + if (fixture_needs_allocation) { + if (!allow_create) return 0; + ++fixture_creations; + } + if (fixture_blocked_address && (u64{w[2]} << 32 | w[1]) == fixture_blocked_address) { + pending = true; + return 0; + } + x2w_late_texture::Resolution why{}; + const auto resource = x2w_late_texture::resolve([] { return mapped_texture; }, + [] { ++deferred_probes; return fixture_decline; }, [] { return u64{}; }, why); + pending = why == x2w_late_texture::Resolution::unavailable || (resource && partial_clamp > 0); + if (resource) { + ++resolved_probes; + srv.Texture2D.ResourceMinLODClamp = partial_clamp; + } + return resource; + }; + return e; +} + +#include "startup_gpu_memory_store.inl" +#include "startup_gpu_compute_trace.inl" +#include "startup_gpu_ambient.inl" +#include "startup_gpu_resident_mips.inl" +#include "startup_gpu_small_texture_heap.inl" +#include "startup_gpu_list_states.inl" +bool packed_light_test(DXGI_FORMAT reader_format) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 17; + desc.Height = 7; + desc.MipLevels = desc.DepthOrArraySize = 2; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R32_UINT; + const bool render_target = reader_format == DXGI_FORMAT_R32_FLOAT; + const auto writer_state = render_target ? D3D12_RESOURCE_STATE_RENDER_TARGET : D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + desc.Flags = render_target ? D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr<ID3D12Resource> writer, other_writer, reader; + if (FAILED(fx.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&writer)))) return false; + if (FAILED(fx.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&other_writer)))) return false; + desc.Format = reader_format; + desc.Flags = D3D12_RESOURCE_FLAG_NONE; + if (FAILED(fx.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&reader)))) return false; + const auto writer_desc = writer->GetDesc(); + auto invalid = desc; + invalid.Format = DXGI_FORMAT_D32_FLOAT; + if (x2w_packed_light::compatible(writer_desc, invalid)) return false; + invalid.Format = DXGI_FORMAT_NV12; + if (x2w_packed_light::compatible(writer_desc, invalid)) return false; + invalid.Format = DXGI_FORMAT_R16_UNORM; + if (x2w_packed_light::compatible(writer_desc, invalid)) return false; + invalid = desc; + invalid.MipLevels = 1; + if (x2w_packed_light::compatible(writer_desc, invalid)) return false; + x2w_packed_light::Copy copy; + if (!copy.init(fx.device.Get(), writer.Get(), reader.Get()) || copy.init(fx.device.Get(), reader.Get(), writer.Get())) + return false; + const auto bytes = copy.scratch->GetDesc().Width; + auto tiny = buffer(4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON); + x2w_packed_light::Copy larger, shared, alternate; + if (!tiny || !larger.init(fx.device.Get(), writer.Get(), reader.Get(), tiny.Get()) || + larger.scratch.Get() == tiny.Get() || + !shared.init(fx.device.Get(), writer.Get(), reader.Get(), copy.scratch.Get()) || + shared.scratch.Get() != copy.scratch.Get()) return false; + if (!alternate.init(fx.device.Get(), other_writer.Get(), reader.Get(), copy.scratch.Get())) return false; + auto input = buffer(bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + auto output = buffer(bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + if (!input || !output) return false; + auto pattern = [](UINT part, UINT row, UINT x) { return 0x88402010u + part * 8192u + row * 32u + x; }; + void* cpu = nullptr; + if (FAILED(input->Map(0, nullptr, &cpu))) return false; + for (UINT i = 0; i < copy.source_rows.size(); ++i) { + const auto& r = copy.source_rows[i]; + for (UINT y = 0; y < r.Footprint.Height; ++y) { + auto* row = reinterpret_cast<UINT*>(static_cast<unsigned char*>(cpu) + r.Offset + y*r.Footprint.RowPitch); + for (UINT x = 0; x < r.Footprint.Width; ++x) row[x] = pattern(i,y,x); + } + } + input->Unmap(0, nullptr); + begin(); + std::map<ID3D12Resource*, D3D12_RESOURCE_STATES> states; + auto require = [&](ID3D12Resource* resource, D3D12_RESOURCE_STATES after) { + const auto before = states[resource]; + x2w_gpu::transition_all(fx.list.Get(), resource, before, after); + states[resource] = after; + }; + require(writer.Get(), D3D12_RESOURCE_STATE_COPY_DEST); + auto transfer = [&](bool upload) { + const auto& rows = upload ? copy.source_rows : copy.dest_rows; + for (UINT i = 0; i < rows.size(); ++i) { + D3D12_TEXTURE_COPY_LOCATION buf{}, tex{}; + buf.pResource = upload ? input.Get() : output.Get(); + buf.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + buf.PlacedFootprint = rows[i]; + tex.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + tex.pResource = upload ? writer.Get() : reader.Get(); + tex.SubresourceIndex = i; + if (upload) fx.list->CopyTextureRegion(&tex,0,0,0,&buf,nullptr); + else fx.list->CopyTextureRegion(&buf,0,0,0,&tex,nullptr); + } + }; + x2w_packed_light::BoundCopy bound; + const auto record = [&](x2w_packed_light::Copy& c) { + if (bound.contains(c.source.Get(), c.destination.Get())) return false; + c.record(fx.list.Get(), require, states[c.source.Get()]); + bound = {c.source.Get(), c.destination.Get()}; + return true; + }; + if (!record(alternate) || record(alternate)) return false; + if (!record(copy) || record(shared)) return false; + bound.invalidate(writer.Get()); + transfer(true); + require(writer.Get(), writer_state); + if (!record(copy) || record(shared)) return false; + if (states[writer.Get()] != writer_state) return false; + require(writer.Get(), D3D12_RESOURCE_STATE_COMMON); + bound.invalidate(reader.Get()); + if (!record(shared)) return false; + require(reader.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE); + transfer(false); + // At list close the packed-light source and scratch already rest in COMMON. + // Only the reader should need a return barrier. + unsigned close_barriers = 0; + for (const auto& entry : states) + if (x2w_gpu::transition_all(fx.list.Get(), entry.first, entry.second, D3D12_RESOURCE_STATE_COMMON)) + ++close_barriers; + if (close_barriers != 1) return false; + end_and_wait(); + if (FAILED(fx.device->GetDeviceRemovedReason()) || FAILED(output->Map(0, nullptr, &cpu))) return false; + bool match = states[writer.Get()] == D3D12_RESOURCE_STATE_COMMON; + for (UINT i = 0; i < copy.dest_rows.size(); ++i) { + const auto& r = copy.dest_rows[i]; + for (UINT y = 0; y < r.Footprint.Height; ++y) { + auto* row = reinterpret_cast<const UINT*>(static_cast<unsigned char*>(cpu) + r.Offset + y*r.Footprint.RowPitch); + for (UINT x = 0; x < r.Footprint.Width; ++x) match &= row[x] == pattern(i,y,x); + } + } + output->Unmap(0, nullptr); + if (FAILED(input->Map(0, nullptr, &cpu))) return false; + constexpr UINT replacement = 0x77ab1122u; + *static_cast<UINT*>(cpu) = replacement; + input->Unmap(0, nullptr); + begin(); + states.clear(); + x2w_packed_light::BoundCopy next_list; + if (next_list.contains(writer.Get(), reader.Get())) return false; + require(writer.Get(), D3D12_RESOURCE_STATE_COPY_DEST); + transfer(true); + require(writer.Get(), D3D12_RESOURCE_STATE_COMMON); + shared.record(fx.list.Get(), require, D3D12_RESOURCE_STATE_COMMON); + require(reader.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE); + transfer(false); + require(reader.Get(), D3D12_RESOURCE_STATE_COMMON); + end_and_wait(); + if (FAILED(fx.device->GetDeviceRemovedReason()) || FAILED(output->Map(0, nullptr, &cpu))) return false; + match &= *static_cast<const UINT*>(cpu) == replacement; + output->Unmap(0, nullptr); + if (reader_format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) { + x2w_compute_trace::Bindings capture; + x2w_compute_trace::Binding binding{reader.Get(), 1, 16}; + binding.slice = binding.mip = 1; + binding.view_format = reader_format; + capture.add(binding, false, true); + x2w_compute_trace::Image image; + if (capture.count != 1 || !image.init(fx.device.Get(), capture.values[0])) return false; + begin(); + require(reader.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE); + image.record(fx.list.Get(), false); + require(reader.Get(), D3D12_RESOURCE_STATE_COMMON); + end_and_wait(); + if (FAILED(fx.device->GetDeviceRemovedReason()) || FAILED(image.pre->Map(0, nullptr, &cpu))) return false; + for (UINT y = 0; y < image.height(); ++y) { + auto* words = reinterpret_cast<const UINT*>(image.row(static_cast<const unsigned char*>(cpu), y, 0)); + for (UINT x = 0; x < image.width(); ++x) match &= words[x] == pattern(3, y + image.box.top, x + image.box.left); + } + image.pre->Unmap(0, nullptr); + } + if (reader_format == DXGI_FORMAT_R32_FLOAT) { + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr<ID3D12DescriptorHeap> views; + if (FAILED(fx.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&views)))) return false; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = reader_format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2DArray.ArraySize = srv.Texture2DArray.MipLevels = 2; + fx.device->CreateShaderResourceView(reader.Get(), &srv, views->GetCPUDescriptorHandleForHeapStart()); + const auto observed = pick(views.Get(), 8, 0, 4); + for (UINT i = 0; i < observed.size(); ++i) match &= observed[i] == pattern(i, 1, 1); + } + return match; +} + +} // namespace + +int main(int argc, char** argv) +{ + const std::string backend = argc > 1 ? argv[1] : "warp"; + const std::string mode = argc > 2 ? argv[2] : "twins"; + const bool warp = backend == "warp"; + if (const int r = setup(warp)) return r; + if (mode == "small_texture_heap") return small_texture_heap_test() ? 0 : 1; + if (mode == "list_states") return list_states_test() ? 0 : 1; + if (mode == "resident_mips") return resident_mip_test() ? 0 : 1; + if (mode == "ambient") return ambient_lighting_test() ? 0 : 1; + if (mode == "compute_priority_depth_capture") return compute_priority_depth_capture_test() ? 0 : 1; + if (mode == "compute_volume_capture") return compute_texture_capture_test(33) ? 0 : 1; + if (mode == "compute_sparse_volume_capture") return compute_texture_capture_test(65) ? 0 : 1; + if (mode == "compute_texture_capture") return compute_texture_capture_test() ? 0 : 1; + if (mode == "material_record") return material_record_test() ? 0 : 1; + if (mode == "pixel_subresource_capture") return pixel_subresource_capture_test() ? 0 : 1; + if (mode == "packed_light") return packed_light_test(DXGI_FORMAT_R9G9B9E5_SHAREDEXP) && packed_light_test(DXGI_FORMAT_R32_FLOAT) ? 0 : 1; + if (mode == "views" && vendor == 0x1002) { + const D3D12_HEAP_PROPERTIES hp{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + D3D12_MEMORY_POOL_L0, 1, 1}; + const auto desc = fx.window->GetDesc(); + ComPtr<ID3D12Resource> shared; + if (FAILED(fx.device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&shared)))) return 1; + void* data = nullptr; + if (FAILED(shared->Map(0, nullptr, &data))) return 1; + auto* title_bytes = static_cast<unsigned char*>(data) + window_offset; + std::memcpy(title_bytes, fx.memory, memory_bytes); + VirtualFree(fx.memory, 0, MEM_RELEASE); + fx.memory = title_bytes; + fx.window = shared; + fx.coherent = true; + } + HostHeap::env_log() = [](const char* text) { std::printf("%s\n", text); }; + + Limits limits = probe_view_limit(fx.device.Get(), true); + std::printf("probe: views %u raw %u\n", limits.views, limits.raw); + if (warp) { + CHECK(limits.raw == 0); // WARP refuses 2^22 views + limits = Limits{1u << 20, 1u << 20}; // half the production heap sizes (fixtures only) + } else if (limits.raw != raw_twins_first) { + std::printf("the host takes no heap of 2^22 views: skipped\n"); + return 77; + } + auto heap = HostHeap::create(env(), false, title_slots, limits, reinterpret_cast<u64>(fx.heap_memory), 32); + if (!heap) { + std::printf("mirror heap refused\n"); + return 1; + } + const Layout& l = heap->layout(); + std::printf("layout: size %u count %u dynamic %u null %u raw %u twins %u\n", l.size, l.count, l.dynamic, l.null, l.raw, l.twins); + CHECK(l.size == 2 * limits.raw && l.null == limits.raw - 1 && l.count == title_slots); + if (!warp) CHECK(l.size == (1u << 22) && l.raw == (1u << 21)); + + // Fixture views, written as the title's view calls leave them (a token in the title slot), then mirrored. + const u64 b0 = buffer_wrapper(0, 4096), b1 = buffer_wrapper(0x10000, 4096), b2 = buffer_wrapper(0x4008, 48); + const u64 tex = texture_wrapper(); + D3D12_SHADER_RESOURCE_VIEW_DESC as{}; + as.ViewDimension = D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE; + as.RaytracingAccelerationStructure.Location = 0x123400000ull; + note(0, 18, 0, &as, sizeof(as)); + std::uint32_t words[8]; + std::memcpy(words, fx.heap_memory, sizeof(words)); + u64 address = 0; + CHECK(title_as_address(env(), words, &address) && address == as.RaytracingAccelerationStructure.Location); + View native{}; + CHECK(!view_of_record(env(), words, false, native)); + CHECK(x2w_as_address::annotate(words, 0x432100000ull)); + std::uint32_t copied[8]; + std::memcpy(copied, words, sizeof(copied)); + CHECK(title_as_address(env(), copied, &address) && address == 0x432100000ull); + CHECK(x2w_as_address::annotate(words, 0)); + CHECK(title_as_address(env(), words, &address) && address == 0); + auto d0 = buffer_srv(static_cast<DXGI_FORMAT>(42), 4, 10, 0, false); // R32_UINT, dwords 4..13 + note(0, 18, b0, &d0, sizeof(d0)); + std::memcpy(words, fx.heap_memory, sizeof(words)); + CHECK(!title_as_address(env(), words, &address)); + auto d1 = buffer_srv(static_cast<DXGI_FORMAT>(57), 8, 7, 0, false); // R16_UINT, bytes 16..29 + note(1, 18, b0, &d1, sizeof(d1)); + auto d2 = buffer_srv(DXGI_FORMAT_UNKNOWN, 2, 3, 24, false); // structured 24: bytes 48..119 + note(2, 18, b0, &d2, sizeof(d2)); + D3D12_SHADER_RESOURCE_VIEW_DESC dt{}; + dt.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + dt.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + dt.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + dt.Texture2D.MipLevels = 1; + note(3, 18, tex, &dt, sizeof(dt)); + D3D12_UNORDERED_ACCESS_VIEW_DESC du{}; + du.Format = DXGI_FORMAT_R32_TYPELESS; + du.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + du.Buffer.FirstElement = 16; + du.Buffer.NumElements = 16; + du.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + note(4, 19, b1, &du, sizeof(du)); // raw UAV: bytes 64..127 of b1 + D3D12_CONSTANT_BUFFER_VIEW_DESC c5{title(0x2000), 256}; + note(5, 17, 0, &c5, sizeof(c5)); // on 256 in the window + D3D12_CONSTANT_BUFFER_VIEW_DESC c6{title(0x2010), 256}; + note(6, 17, 0, &c6, sizeof(c6)); // not on 256: null + // slot 7: nothing + { + x2w_startup::BufferViewLayout bl = x2w_startup::buffer_view_layout(DXGI_FORMAT_R32_TYPELESS, 0, 16, 0, 1); + std::uint32_t w[8]; + x2w_startup::gfx10_buffer_words(bl, w); + const u64 base = title(0x3000); + w[0] = static_cast<std::uint32_t>(base); + w[1] |= static_cast<std::uint32_t>(base >> 32) & 0xffff; + std::memcpy(fx.heap_memory + 8 * 32, w, 32); // slot 8: a V# of 64 raw bytes + } + auto d9 = buffer_srv(DXGI_FORMAT_UNKNOWN, 0, 4, 12, false); // structured 12 at 0x4008: off elements + note(9, 18, b2, &d9, sizeof(d9)); + auto d10 = buffer_srv(static_cast<DXGI_FORMAT>(42), 1, 10, 0, false); // R32_UINT from byte 4: off 16 + note(10, 18, b0, &d10, sizeof(d10)); + for (u32 i = 0; i < 11; ++i) heap->mirror(i); + + if (mode == "memory_store") { + store_fixture(*heap); + } else if (mode == "memory" || mode == "memory_empty") { + // Raw misses at the front of GPU feedback must not consume the + // mapping budget before the first reachable page. + x2w_vmemory::FaultPages feedback; + std::vector<UINT> faults; + for (UINT page = 65536; page <= 65536 + 2048; ++page) faults.push_back(page); + CHECK(feedback.report(faults) == 0); + feedback.seed(1, [&](UINT page) { return page == faults.back(); }); + CHECK(feedback.report({}) == 1); + faults.resize(129); + feedback.report(faults); + feedback.seed(2, [](UINT) { return true; }); + CHECK(feedback.report({}) == 129); + x2w_vmemory::Recording memory; + if (!memory.create(fx.device.Get())) return 1; + memory.base = 48; + heap->null_raw_uav_at(memory.base); + ComPtr<ID3D12RootSignature> root; + CHECK(SUCCEEDED(fx.device->CreateRootSignature(0, startup_gpu_memory_cs, sizeof(startup_gpu_memory_cs), IID_PPV_ARGS(&root)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.Get(); + pd.CS = {startup_gpu_memory_cs, sizeof(startup_gpu_memory_cs)}; + ComPtr<ID3D12PipelineState> pso; + CHECK(SUCCEEDED(fx.device->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pso)))); + if (failures) return 1; + begin(); + std::unordered_map<ID3D12Resource*, D3D12_RESOURCE_STATES> states; + states[fx.result.Get()] = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + const auto state = [&](ID3D12Resource* r, D3D12_RESOURCE_STATES next) { + auto& before = states[r]; + if (before == next) return; + D3D12_RESOURCE_BARRIER b{}; + b.Transition = {r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, next}; + fx.list->ResourceBarrier(1, &b); + before = next; + }; + const UINT first = 65552; + // Simulate residue from a previous submission of this same native list. + auto previous = buffer(8, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + UINT* residue = nullptr; + CHECK(previous && SUCCEEDED(previous->Map(0, nullptr, reinterpret_cast<void**>(&residue)))); + if (!residue) return 1; + residue[0] = 0x80000001; + residue[1] = window_offset; + previous->Unmap(0, nullptr); + state(memory.directory.Get(), D3D12_RESOURCE_STATE_COPY_DEST); + fx.list->CopyBufferRegion(memory.directory.Get(), UINT64{first + 1} * 8, previous.Get(), 0, 8); + state(memory.faults.Get(), D3D12_RESOURCE_STATE_COPY_DEST); + fx.list->CopyBufferRegion(memory.faults.Get(), 4, previous.Get(), 0, 8); + if (mode == "memory") { + memory.map(fx.list.Get(), first, [&](UINT64 at, ID3D12Resource** w, UINT64* o) { + *w = fx.window.Get(); *o = window_offset; return at == UINT64{first} * 65536; + }, [&](UINT i, auto* w, UINT64 size) { heap->raw_uav_at(i, w, 0, size); }, state); + } + memory.ready(fx.list.Get(), state); + auto* descriptor_heap = heap->heap(); + fx.list->SetDescriptorHeaps(1, &descriptor_heap); + fx.list->SetComputeRootSignature(root.Get()); + fx.list->SetPipelineState(pso.Get()); + UINT params[]{memory.base, first}; + fx.list->SetComputeRoot32BitConstants(0, 2, params, 0); + fx.list->SetComputeRootShaderResourceView(1, memory.directory->GetGPUVirtualAddress()); + fx.list->SetComputeRootUnorderedAccessView(2, memory.faults->GetGPUVirtualAddress()); + fx.list->SetComputeRootUnorderedAccessView(3, fx.result->GetGPUVirtualAddress()); + fx.list->Dispatch(2, 1, 1); + memory.close(fx.list.Get(), state); + state(fx.result.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE); + fx.list->CopyBufferRegion(fx.readback.Get(), 0, fx.result.Get(), 0, 16); + end_and_wait(); + UINT* out = nullptr; + CHECK(SUCCEEDED(fx.readback->Map(0, nullptr, reinterpret_cast<void**>(&out)))); + if (!out) return 1; + CHECK(out[0] == (mode == "memory" ? pattern(4) : 0) && out[1] == 0); + CHECK(out[2] == (mode == "memory" ? 0x80000001u : 0u) && out[3] == 0); + fx.readback->Unmap(0, nullptr); + const std::vector<UINT> expected = mode == "memory" ? std::vector<UINT>{first + 1} + : std::vector<UINT>{first, first + 1}; + CHECK(memory.read_faults() == expected); + } else if (mode == "twins") { + CHECK(title_then_zero(pick(*heap, 0, l.twin(0), 16), 16, 10)); // typed R32: dwords 4..13, bounded + CHECK(title_then_zero(pick(*heap, 0, l.twin(1), 8), 16, 4)); // typed R16: 4 dwords from byte 16 + CHECK(title_then_zero(pick(*heap, 0, l.twin(2), 24), 48, 18)); // structured: its 72 bytes + CHECK(all_zero(pick(*heap, 0, l.twin(3), 8))); // a texture slot's twin + CHECK(all_zero(pick(*heap, 0, l.twin(7), 8))); // an empty slot's twin + CHECK(all_zero(pick(*heap, 0, l.size - 1, 8))); // the last slot (past every twin) + CHECK(all_zero(pick(*heap, 0, l.twin(title_slots + l.dynamic - 1), 8))); // the last twin, of no view + CHECK(title_then_zero(pick(*heap, 2, l.twin(5), 16), 0x2000, 16)); // a CBV's twin: the CBV + CHECK(title_then_zero(pick(*heap, 0, l.twin(8), 20), 0x3000, 16)); // a V#'s twin + // The UAV's twin writes its 16 dwords and nothing beside them. + const auto before = read_window(0x10000, 64); + pick(*heap, 1, l.twin(4), 16, 0xa0000000u); + const auto after = read_window(0x10000, 64); + u32 changed = 0, outside = 0; + for (u32 i = 0; i < 64; ++i) { + if (after[i] != before[i]) ++changed; + if (after[i] != before[i] && (i < 16 || i >= 32)) ++outside; + if (i >= 16 && i < 32) CHECK(after[i] == 0xa0000000u + (i - 16)); + } + std::printf("uav twin: %u dwords changed, %u outside the view\n", changed, outside); + CHECK(changed == 16 && outside == 0); + // A dynamic slot made from slot 0's view has its twin too. + const auto dyn = heap->dynamic(4); + CHECK(dyn && *dyn == title_slots); + if (dyn) { + View v; + std::uint32_t words[8]; + std::memcpy(words, fx.heap_memory, 32); + CHECK(view_of_record(env(), words, false, v)); + heap->make_at(*dyn + 1, v); + CHECK(title_then_zero(pick(*heap, 0, l.twin(*dyn + 1), 16), 16, 10)); + heap->raw_at(*dyn + 2, fx.window.Get(), window_offset + 0x100, 32); + CHECK(title_then_zero(pick(*heap, 0, *dyn + 2, 12), 0x100, 8)); // a root SRV with a size + CHECK(all_zero(pick(*heap, 0, l.twin(*dyn + 2), 4))); // bound by handle: no twin + heap->release(*dyn, 4); + CHECK(heap->dynamic(4).has_value()); + } + std::printf("twins %llu, moved %llu, unmoved %llu, null %llu\n", counted(c_twins), counted(c_twins_moved), + counted(c_twins_unmoved), counted(c_twins_null)); + // A view that begins between two multiples of 16 (slot 10, from byte 4): its twin is moved on where the + // host's raw descriptor is its address and bytes (host.rs move_raw: AMD), else null. + if (counted(c_twins_moved)) { + CHECK(title_then_zero(pick(*heap, 0, l.twin(10), 16), 4, 10)); + } else { + CHECK(vendor != 0x1002); // AMD must move it + CHECK(all_zero(pick(*heap, 0, l.twin(10), 16))); + } + } else if (mode == "views") { + // The structured view is raw (raw_window) at the title slot: read as bytes. + CHECK(title_then_zero(pick(*heap, 0, 2, 20), 48, 18)); + CHECK(title_then_zero(pick(*heap, 3, 0, 12), 16, 10)); // typed R32_UINT as it is + CHECK(title_then_zero(pick(*heap, 0, 8, 16), 0x3000, 16)); // the V# record: a raw view + CHECK(title_then_zero(pick(*heap, 2, 5, 16), 0x2000, 16)); // the aligned CBV + CHECK(all_zero(pick(*heap, 2, 6, 16))); // the unaligned CBV: null + CHECK(counted(c_cbv_unaligned) >= 1); + CHECK(title_then_zero(pick(*heap, 0, 9, 12), 0x4008, 12)); // off elements: its own bytes + if (counted(c_direct_offset)) { + CHECK(heap->kept_at(9) == fx.window.Get()); + // Write only the desktop buffer after mirroring. A snapshot of the title bytes + // would still show the pattern read above; both aliases must observe the GPU copy. + auto update = buffer(64, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + UINT* mapped = nullptr; + CHECK(update && SUCCEEDED(update->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))); + if (mapped) { + for (UINT i = 0; i < 16; ++i) mapped[i] = 0xaedd0000u + i; + update->Unmap(0, nullptr); + begin(); + fx.list->CopyBufferRegion(fx.window.Get(), window_offset + 0x4008, update.Get(), 0, 64); + end_and_wait(); + for (const auto slot : {9u, l.twin(9)}) { + const auto data = pick(*heap, 0, slot, 16); + for (UINT i = 0; i < 16; ++i) CHECK(data[i] == (i < 12 ? 0xaedd0000u + i : 0)); + } + const UINT cpu_write = 0xad008800; + std::memcpy(fx.memory + 0x4008, &cpu_write, sizeof(cpu_write)); + CHECK(pick(*heap, 0, 9, 1)[0] == cpu_write); + } + } else { + CHECK(vendor != 0x1002 && counted(c_exact) >= 1); + } + // A cache hit is a real resource lease. Destroying the heap's cache drops its ownership. + Microsoft::WRL::ComPtr<ID3D12Resource> lease; + { + Exacts local; + lease = local.get(env(), title(0x4008), 48, 1); + CHECK(lease && local.get(env(), title(0x4008), 48, 2).Get() == lease.Get()); + CHECK(!local.get(env(), title(0x4010), 64ull << 20, 3) && counted(c_exact_capacity)); + CHECK(!local.get(env(), 1, 32, 3) && counted(c_exact_unreadable)); + } + if (lease) { + lease->AddRef(); + CHECK(lease->Release() == 1); + } + // The table of strides: typed 4 (integer), R16 2 (integer), structured 24, raw UAV 1; none for others. + CHECK(heap->stride_word(0) == (4 | view_integer)); + CHECK(heap->stride_word(1) == (2 | view_integer)); + CHECK(heap->stride_word(2) == 24); + CHECK(heap->stride_word(4) == 1); + CHECK(heap->stride_word(3) == 0 && heap->stride_word(5) == 0 && heap->stride_word(7) == 0); + CHECK(heap->stride_word(8) == 1); + CHECK(heap->strides_gpu() != 0); + const auto slots = heap->buffer_slots(); + CHECK(slots.size() == 7); // 0, 1, 2, 4, 8, 9, 10 + } else if (mode == "typed_null") { + auto srv = D3D12_SHADER_RESOURCE_VIEW_DESC{}; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + srv.Format = DXGI_FORMAT_R32_UINT; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2DArray.MipLevels = 1; + srv.Texture2DArray.ArraySize = 1; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + uav.Format = DXGI_FORMAT_R32_UINT; + uav.Texture2DArray.ArraySize = 1; + note(20, 18, 0, &srv, sizeof(srv)); + const auto id = note(21, 19, 0, &uav, sizeof(uav)); + for (u32 i = 20; i <= 21; ++i) { + std::memcpy(words, fx.heap_memory + i * 32, sizeof(words)); + View v{}; + CHECK(view_of_record(env(), words, false, v) && v.explicit_null); + if (i == 20) CHECK(v.kind == Kind::shader && v.srv.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY); + else CHECK(v.kind == Kind::unordered && v.uav.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY); + CHECK(heap->mirror(i)); + CHECK(heap->make_listed(l.count + i, words).has_value()); + CHECK(all_zero(pick(*heap, i == 20 ? 4 : 5, i, 4))); + CHECK(all_zero(pick(*heap, i == 20 ? 4 : 5, l.count + i, 4))); + } + D3D12_UNORDERED_ACCESS_VIEW_DESC buffer_null{}; + buffer_null.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + buffer_null.Format = DXGI_FORMAT_R32_UINT; + buffer_null.Buffer.NumElements = 4; + note(22, 19, 0, &buffer_null, sizeof(buffer_null)); + CHECK(heap->mirror(22)); + CHECK(all_zero(pick(*heap, 6, l.twin(22), 4))); + fx.records[id].materialized = false; + View rejected{}; + CHECK(!view_of_record(env(), words, false, rejected)); + fx.records[id].materialized = true; + fx.records[id].resource = 0x2208759ad90ull; + CHECK(!view_of_record(env(), words, false, rejected)); + CHECK(SUCCEEDED(fx.device->GetDeviceRemovedReason())); + } else if (mode == "submit") { + // The title copies slot 0's record into slot 20 and slot 2's into 21 as bytes, and clears slot 1's. + std::memcpy(fx.heap_memory + 20 * 32, fx.heap_memory, 32); + std::memcpy(fx.heap_memory + 21 * 32, fx.heap_memory + 2 * 32, 32); + CHECK(all_zero(pick(*heap, 0, l.twin(20), 8))); // not mirrored yet + CHECK(title_then_zero(pick(*heap, 0, l.twin(1), 8), 16, 4)); + std::memset(fx.heap_memory + 1 * 32, 0, 32); + const u64 changed = heap->submit(); + std::printf("submit: %llu records changed\n", changed); + CHECK(changed == 3); // 20 and 21 copied, 1 cleared (the others were mirrored by their calls) + CHECK(title_then_zero(pick(*heap, 0, l.twin(20), 16), 16, 10)); + CHECK(title_then_zero(pick(*heap, 0, 21, 20), 48, 18)); + CHECK(all_zero(pick(*heap, 0, l.twin(1), 8))); + CHECK(heap->submit() == 0); // nothing new + // Title memory under the own-bytes copy of slot 9 changes: the next submit carries it. + const std::uint32_t mark = 0xc0ffee00u; + std::memcpy(fx.memory + 0x4008, &mark, 4); + heap->submit(); + CHECK(title_then_zero(pick(*heap, 0, 9, 12), 0x4008, 12)); + // Six submits on, with the record unchanged, the copy is still refreshed (a slot shows it). + for (int i = 0; i < 6; ++i) heap->submit(); + const std::uint32_t mark2 = 0xbeef0000u; + std::memcpy(fx.memory + 0x400c, &mark2, 4); + heap->submit(); + { + const auto got = pick(*heap, 0, 9, 12); + CHECK(got.size() >= 2 && got[0] == mark && got[1] == mark2); + } + // A V# whose memory has no window yet when mirrored (slot 11) shows null, and is made at a later submit. + { + x2w_startup::BufferViewLayout bl = x2w_startup::buffer_view_layout(DXGI_FORMAT_R32_TYPELESS, 0, 16, 0, 1); + std::uint32_t w[8]; + x2w_startup::gfx10_buffer_words(bl, w); + const u64 base = title(0x3100); + w[0] = static_cast<std::uint32_t>(base); + w[1] |= static_cast<std::uint32_t>(base >> 32) & 0xffff; + std::memcpy(fx.heap_memory + 11 * 32, w, 32); + } + fx.find_fails = true; + heap->mirror(11); + fx.find_fails = false; + CHECK(all_zero(pick(*heap, 0, 11, 16))); + CHECK(heap->shows_none(11)); + heap->submit(); + CHECK(!heap->shows_none(11)); + CHECK(title_then_zero(pick(*heap, 0, 11, 16), 0x3100, 16)); + // The texture of slot 3 is due for upload. + CHECK(heap->upload_due(nullptr, 16) >= 1); + bool texture_uploaded = false; + for (u64 w : fx.uploads) texture_uploaded |= w == tex; + CHECK(texture_uploaded); + // The texture isn't mapped until after its descriptor is copied. A slot the + // title clears before the mapping appears must remain empty. + D3D12_RESOURCE_DESC placed = fx.texture->GetDesc(); + placed.Flags = D3D12_RESOURCE_FLAGS(0x300000); + placed.Layout = D3D12_TEXTURE_LAYOUT(0x105); + placed.Alignment = 0; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = placed.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + u32 late[8]{}; + CHECK(x2w_late_texture::encode(placed, srv, title(0x7000), late)); + for (u32 index : {28u, 29u}) std::memcpy(fx.heap_memory + 32 * index, late, 32); + heap->submit(); + CHECK(heap->shows_none(28) && heap->shows_none(29)); + std::memset(fx.heap_memory + 32 * 29, 0, 32); + CHECK(deferred_probes == 2); // first attempt for each copied slot, once per submit + const unsigned before = deferred_probes; + mapped_texture = tex; + heap->submit(); + CHECK(heap->kept_at(28) == fx.texture.Get()); + CHECK(deferred_probes == before); + // The same title VA and unchanged descriptor can acquire a new host object. + // Re-reading the slot must replace the descriptor and its retained resource. + const auto replacement_desc = fx.texture->GetDesc(); + D3D12_HEAP_PROPERTIES props{}; + props.Type = D3D12_HEAP_TYPE_DEFAULT; + ComPtr<ID3D12Resource> replacement; + CHECK(SUCCEEDED(fx.device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &replacement_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&replacement)))); + if (replacement) { + const auto fill = [&](ID3D12Resource* texture, unsigned char red) { + auto pixels = buffer(1024, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + void* cpu = nullptr; + if (!pixels || FAILED(pixels->Map(0, nullptr, &cpu))) return false; + std::memset(cpu, red, 1024); + pixels->Unmap(0, nullptr); + D3D12_TEXTURE_COPY_LOCATION src{pixels.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + src.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, 4, 4, 1, 256}; + D3D12_TEXTURE_COPY_LOCATION dst{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + begin(); + x2w_gpu::transition_all(fx.list.Get(), texture, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + fx.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + x2w_gpu::transition_all(fx.list.Get(), texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + end_and_wait(); + return true; + }; + CHECK(fill(fx.texture.Get(), 51)); + CHECK(fill(replacement.Get(), 204)); + fx.resources[tex - 1].title_memory = title(0x7000); + note(28, 18, tex, &srv, sizeof(srv)); + CHECK(heap->mirror(28)); + std::memcpy(fx.heap_memory + 32 * 28, late, sizeof(late)); + const auto first_wrapper = mapped_texture; + mapped_texture = 0; + CHECK(heap->mirror(28)); + CHECK(heap->kept_at(28) == fx.texture.Get()); + CHECK(heap->make_listed(l.count + 28, late, 28).has_value()); + CHECK(heap->kept_at(l.count + 28) == fx.texture.Get()); + CHECK(pick(*heap, 7, 28, 1)[0] == 51); + CHECK(pick(*heap, 7, l.count + 28, 1)[0] == 51); + fixture_decline = 5; + CHECK(!heap->mirror(28)); + CHECK(!heap->kept_at(28)); + fixture_decline = 8; + mapped_texture = first_wrapper; + CHECK(heap->mirror(28)); + mapped_texture = 0; + // Change the address, resource dimensions, view format or selected mip. + for (unsigned field : {1u, 3u, 4u, 6u}) { + u32 changed[8]; + std::copy_n(late, 8, changed); + changed[field] ^= field == 4 ? 0x100 : 1; + CHECK(heap->make_listed(l.count + 29, changed, 28).has_value()); + CHECK(!heap->kept_at(l.count + 29)); + CHECK(!heap->mirror_words(28, changed)); + CHECK(!heap->kept_at(28)); + mapped_texture = first_wrapper; + CHECK(heap->mirror(28)); + mapped_texture = 0; + } + CHECK(heap->mirror(28)); + mapped_texture = first_wrapper; + fx.resources[mapped_texture - 1].desktop = replacement.Get(); + heap->submit(); + CHECK(heap->kept_at(28) == replacement.Get()); + CHECK(heap->make_listed(l.count + 28, late, 28).has_value()); + CHECK(heap->kept_at(l.count + 28) == replacement.Get()); + CHECK(pick(*heap, 7, 28, 1)[0] == 204); + CHECK(pick(*heap, 7, l.count + 28, 1)[0] == 204); + u32 lazy[8]; + std::copy_n(late, 8, lazy); + lazy[0] = x2w_late_texture::lazy; + { + u32 malformed[8]; + std::copy_n(lazy, 8, malformed); + malformed[3] = 2048u | (1024u << 16); + malformed[4] = (malformed[4] & 0xffffffu) | (193u << 24); + std::memcpy(fx.heap_memory + 32 * 29, malformed, sizeof(malformed)); + const unsigned allocated = allocation_probes, resolved = resolved_probes; + CHECK(!heap->mirror(29, false) && !heap->warm_slot(nullptr, 29, true, 1)); + CHECK(!heap->mirror(29, true) && !heap->kept_at(29)); + CHECK(allocated == allocation_probes && resolved == resolved_probes); + } + const unsigned before_stage = resolved_probes; + for (u32 slot : {30u, 31u, 32u, 33u}) { + std::memcpy(fx.heap_memory + slot * 32, lazy, 32); + heap->mirror(slot, false); + } + heap->submit(); + CHECK(resolved_probes == before_stage); + CHECK(!heap->kept_at(30)); + CHECK(heap->make_listed(l.count + 30, lazy, 30).has_value()); + CHECK(pick(*heap, 7, l.count + 30, 1)[0] == 204); + LazyBudget budget; + std::memset(fx.heap_memory + 32 * 32, 0, 32); + heap->warm_lazy(nullptr, 1, budget, 1); + CHECK(heap->kept_at(30) == replacement.Get() && !heap->kept_at(31)); + heap->warm_lazy(nullptr, 1, budget, 1); + CHECK(!heap->kept_at(31)); + heap->warm_lazy(nullptr, 2, budget, 4); + CHECK(pick(*heap, 7, 31, 1)[0] == 204 && !heap->kept_at(32)); + CHECK(heap->kept_at(33) == replacement.Get()); + // Resident textures can pass the old 16-slot ceiling. Empty budget and byte exhaustion + // preserve queued descriptors. A newly mapped page retries in the same presented frame. + for (u32 slot = 150; slot < 184; ++slot) { + std::memcpy(fx.heap_memory + slot * 32, lazy, 32); + heap->mirror(slot, false); + } + fixture_room = 0; + heap->warm_lazy(nullptr, 3, budget); + CHECK(!budget.visits && !heap->kept_at(150)); + fixture_room = 32768; + heap->warm_lazy(nullptr, 4, budget, 4096, 1ull << 30, 1000); + CHECK(budget.visits == 34 && !budget.bytes && !heap->kept_at(150)); + fixture_room = UINT64_MAX; + heap->warm_lazy(nullptr, 5, budget, 4096, 1ull << 30, 0); + CHECK(!budget.visits); + heap->warm_lazy(nullptr, 5, budget, 4096, 20 * 4096, 1000); + CHECK(budget.visits == 20 && budget.bytes == 20 * 4096); + CHECK(heap->kept_at(169) == replacement.Get() && !heap->kept_at(170)); + heap->warm_lazy(nullptr, 5, budget, 4096, 20 * 4096, 1000); + CHECK(budget.visits == 20); + const auto mapped = mapped_texture; + mapped_texture = 0; + heap->warm_lazy(nullptr, 6, budget, 4096, 1ull << 30, 1000); + CHECK(budget.visits == 14 && !heap->kept_at(183)); + mapped_texture = mapped; + heap->warm_lazy(nullptr, 6, budget, 4096, 1ull << 30, 1000); + CHECK(budget.visits == 14); + ++fixture_epoch; + heap->warm_lazy(nullptr, 6, budget, 4096, 1ull << 30, 1000); + CHECK(budget.visits == 28 && heap->kept_at(183) == replacement.Get()); + material_feedback_test(*heap, lazy, replacement.Get()); + partial_clamp = 0.5f; + CHECK(heap->mirror(28)); + View partial{}; + CHECK(heap->make_listed(l.count + 28, late, 28, &partial).has_value()); + CHECK(partial.pending && partial.srv.Texture2D.ResourceMinLODClamp == 0.5f); + const auto probes = resolved_probes; + heap->submit(); + CHECK(resolved_probes > probes); + partial_clamp = 0; + const auto before_completion = counted(c_mirrored); + heap->submit(); + CHECK(counted(c_mirrored) > before_completion); + View ready{}; + CHECK(heap->make_listed(l.count + 28, late, 28, &ready).has_value()); + CHECK(!ready.pending && ready.srv.Texture2D.ResourceMinLODClamp == 0 && ready.key != partial.key); + } + CHECK(heap->shows_none(29) && !heap->kept_at(29)); + } else { + std::printf("unknown mode %s\n", mode.c_str()); + return 2; + } + if (failures) { + std::printf("startup_gpu_heap %s %s: %d failures\n", backend.c_str(), mode.c_str(), failures); + return 1; + } + std::printf("startup_gpu_heap %s %s: pass\n", backend.c_str(), mode.c_str()); + return 0; +} diff --git a/tests/startup_gpu_heap.hlsl b/tests/startup_gpu_heap.hlsl new file mode 100644 index 0000000000..201812a86a --- /dev/null +++ b/tests/startup_gpu_heap.hlsl @@ -0,0 +1,53 @@ +// startup_gpu_heap: fixture shader using directly indexed descriptor heaps (ResourceDescriptorHeap by index, SM 6.6), +// reading or writing one slot of the mirror heap (tests/startup_gpu_heap.cpp). Not a title shader. +cbuffer Pick : register(b0) +{ + uint mode; // 0 raw read, 1 raw write, 2 constant read, 3 typed (uint) read + uint slot; // the heap slot + uint count; // dwords + uint mark; // mode 1: the first value written +}; +RWByteAddressBuffer result : register(u0); + +struct Sixteen { uint4 v[16]; }; + +[numthreads(1, 1, 1)] +void PickMain() +{ + for (uint i = 0; i < count; ++i) { + uint value = 0; + if (mode == 0) { + ByteAddressBuffer b = ResourceDescriptorHeap[slot]; + value = b.Load(i * 4); + } else if (mode == 1) { + RWByteAddressBuffer b = ResourceDescriptorHeap[slot]; + b.Store(i * 4, mark + i); + value = mark + i; + } else if (mode == 2) { + ConstantBuffer<Sixteen> c = ResourceDescriptorHeap[slot]; + value = c.v[i / 4][i % 4]; + } else if (mode == 8) { + Texture2DArray<float> t = ResourceDescriptorHeap[slot]; + value = asuint(t.Load(int4(1, 1, i >> 1, i & 1))); + } else if (mode == 7) { + Texture2D<float4> t = ResourceDescriptorHeap[slot]; + value = (uint)round(t.Load(int3(0, 0, 0)).r * 255); + } else if (mode == 6) { + RWByteAddressBuffer b = ResourceDescriptorHeap[slot]; + b.Store(i * 4, mark + i); + value = b.Load(i * 4); + } else if (mode == 4) { + Texture2DArray<uint> t = ResourceDescriptorHeap[slot]; + value = t.Load(int4(i, 0, 0, 0)); + } else if (mode == 5) { + RWTexture2DArray<uint> t = ResourceDescriptorHeap[slot]; + uint3 at = uint3(i, 0, 0); + t[at] = mark + i; + value = t[at]; + } else { + Buffer<uint> t = ResourceDescriptorHeap[slot]; + value = t[i]; + } + result.Store(i * 4, value); + } +} diff --git a/tests/startup_gpu_heap_fit_check.cpp b/tests/startup_gpu_heap_fit_check.cpp new file mode 100644 index 0000000000..085fc3f9e7 --- /dev/null +++ b/tests/startup_gpu_heap_fit_check.cpp @@ -0,0 +1,334 @@ +// Each case makes an invalid view description, puts it through the check, creates what the check lets through (or a null view, as the mirror does) +// and requires the device to stay. --mutate skips the checks: the device must then be removed (negative control). +// +// startup_gpu_heap_fit_check <warp|hardware> [--mutate] +// Exit 0 pass, 1 a check failed, 77 no adapter, other values a setup step. +#include "startup_stubs/gpu_heap.inl" +#include "startup_stubs/gpu_read_states.h" +#include <d3d12sdklayers.h> + +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <cstdio> +#include <cstring> +#include <string> + +using Microsoft::WRL::ComPtr; + +namespace { +int failures = 0; +void check(bool ok, const char* what) +{ + std::printf("%s %s\n", ok ? "ok " : "FAIL", what); + if (!ok) ++failures; +} +void print_line(const char* text) { std::printf(" log: %s\n", text); } +ComPtr<ID3D12Resource> make(ID3D12Device* device, D3D12_RESOURCE_DIMENSION dim, UINT64 width, UINT height, UINT16 depth, + UINT16 mips, DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags) +{ + D3D12_RESOURCE_DESC d{}; + d.Dimension = dim; + d.Width = width; + d.Height = height; + d.DepthOrArraySize = depth; + d.MipLevels = mips; + d.Format = format; + d.SampleDesc.Count = 1; + d.Layout = dim == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN; + d.Flags = flags; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr<ID3D12Resource> r; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&r)))) + return nullptr; + return r; +} +bool srgb_uav_roundtrip(ID3D12Device* device, ID3D12DescriptorHeap* visible) +{ + D3D12_RESOURCE_DESC original{}; + original.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + original.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + original.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const DXGI_FORMAT backing = x2w_srgb::backing_format(original); + if (backing != DXGI_FORMAT_R8G8B8A8_TYPELESS) return false; + auto texture = make(device, original.Dimension, 8, 8, 1, 1, backing, original.Flags); + if (!texture) return false; + const auto rd = texture->GetDesc(); + auto srv = x2w_srgb::srv(rd, original.Format); + auto uav = x2w_srgb::uav(rd, original.Format); + auto rtv = x2w_srgb::rtv(rd, original.Format); + uav.Format = original.Format; // an explicit sRGB UAV requests format normalization + if (!gpu_mirror::fits(texture.Get(), &uav.Format, true) || uav.Format != DXGI_FORMAT_R8G8B8A8_UNORM || + !gpu_mirror::fits(texture.Get(), &srv.Format, false) || srv.Format != original.Format || + rtv.Format != original.Format || x2w_srgb::uav(rd, original.Format).Format != uav.Format) return false; + ComPtr<ID3D12DescriptorHeap> cpu, targets; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2}; + if (FAILED(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&cpu)))) return false; + hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + if (FAILED(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&targets)))) return false; + auto hc = cpu->GetCPUDescriptorHandleForHeapStart(); + auto hs = hc; + hs.ptr += device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + device->CreateShaderResourceView(texture.Get(), &srv, hs); + device->CreateRenderTargetView(texture.Get(), &rtv, targets->GetCPUDescriptorHandleForHeapStart()); + device->CreateUnorderedAccessView(texture.Get(), nullptr, &uav, hc); + device->CopyDescriptorsSimple(1, visible->GetCPUDescriptorHandleForHeapStart(), hc, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (FAILED(device->GetDeviceRemovedReason())) return false; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + device->GetCopyableFootprints(&rd, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + D3D12_RESOURCE_DESC bd{}; + bd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; bd.Width = bytes; bd.Height = bd.DepthOrArraySize = bd.MipLevels = 1; + bd.SampleDesc.Count = 1; bd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + const D3D12_HEAP_PROPERTIES readback_props{D3D12_HEAP_TYPE_READBACK}; + ComPtr<ID3D12Resource> readback; + if (FAILED(device->CreateCommittedResource(&readback_props, D3D12_HEAP_FLAG_NONE, &bd, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback)))) return false; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> alloc; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + const D3D12_COMMAND_QUEUE_DESC q{}; + if (FAILED(device->CreateCommandQueue(&q, IID_PPV_ARGS(&queue))) || + FAILED(device->CreateCommandAllocator(q.Type, IID_PPV_ARGS(&alloc))) || + FAILED(device->CreateCommandList(0, q.Type, alloc.Get(), nullptr, IID_PPV_ARGS(&list))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) return false; + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {texture.Get(), 0, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS}; + list->ResourceBarrier(1, &barrier); + list->SetDescriptorHeaps(1, &visible); + const FLOAT color[4]{0, 1, 0, 1}; + list->ClearUnorderedAccessViewFloat(visible->GetGPUDescriptorHandleForHeapStart(), hc, texture.Get(), color, 0, nullptr); + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &barrier); + D3D12_TEXTURE_COPY_LOCATION dest{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dest.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION src{texture.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + list->CopyTextureRegion(&dest, 0, 0, 0, &src, nullptr); + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), 1)) || FAILED(fence->SetEventOnCompletion(1, nullptr)) || + FAILED(device->GetDeviceRemovedReason())) return false; + UINT* mapped = nullptr; + if (FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) return false; + bool pixels_match = true; + for (UINT y = 0; y < 8; ++y) + for (UINT x = 0; x < 8; ++x) + pixels_match &= mapped[y * footprint.Footprint.RowPitch / sizeof(UINT) + x] == 0xff00ff00u; + readback->Unmap(0, nullptr); + return pixels_match; +} +bool queue_read_states(ID3D12Device* device) +{ + auto texture = make(device, D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 1, 1, DXGI_FORMAT_R32_UINT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto buffer = make(device, D3D12_RESOURCE_DIMENSION_BUFFER, 4096, 1, 1, 1, DXGI_FORMAT_UNKNOWN, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + ComPtr<ID3D12InfoQueue> info; + ComPtr<ID3D12Fence> fence; + if (!texture || !buffer || FAILED(device->QueryInterface(IID_PPV_ARGS(&info))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) return false; + info->ClearStoredMessages(); + UINT64 sequence = 0; + for (auto type : {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_TYPE_COMPUTE}) { + const auto texture_read = x2w_gpu::texture_read_state(type); + const auto buffer_read = x2w_gpu::buffer_read_state(type); + D3D12_COMMAND_QUEUE_DESC q{}; + q.Type = type; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + if (FAILED(device->CreateCommandQueue(&q, IID_PPV_ARGS(&queue))) || + FAILED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator))) || + FAILED(device->CreateCommandList(0, type, allocator.Get(), nullptr, IID_PPV_ARGS(&list)))) return false; + const auto transition = [&](ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER b{}; + b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + list->ResourceBarrier(1, &b); + }; + transition(texture.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + transition(texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, texture_read); + transition(texture.Get(), texture_read, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition(texture.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + transition(buffer.Get(), D3D12_RESOURCE_STATE_COMMON, buffer_read); + transition(buffer.Get(), buffer_read, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition(buffer.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), ++sequence)) || FAILED(fence->SetEventOnCompletion(sequence, nullptr)) || + FAILED(device->GetDeviceRemovedReason())) return false; + } + for (UINT64 i = 0; i < info->GetNumStoredMessages(); ++i) { + SIZE_T size = 0; + info->GetMessage(i, nullptr, &size); + std::vector<unsigned char> storage(size); + auto* message = reinterpret_cast<D3D12_MESSAGE*>(storage.data()); + if (SUCCEEDED(info->GetMessage(i, message, &size)) && message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { + std::printf("D3D12: %s\n", message->pDescription); + return false; + } + } + return true; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2) return 2; + const bool warp = std::strcmp(argv[1], "warp") == 0; + const bool mutate = argc > 2 && std::strcmp(argv[2], "--mutate") == 0; + const bool states = argc > 2 && std::strcmp(argv[2], "--read-states") == 0; + if (states) { + ComPtr<ID3D12Debug> debug; + if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) return 77; + debug->EnableDebugLayer(); + } + ComPtr<IDXGIFactory6> factory; + ComPtr<IDXGIAdapter1> adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77; + if (warp ? FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) + : FAILED(factory->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&adapter)))) + return 77; + ComPtr<ID3D12Device> device; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) return 77; + if (states) { + check(queue_read_states(device.Get()), "direct/compute tracked upload, shader read, UAV write and return to COMMON"); + return failures ? 1 : 0; + } + gpu_mirror::fit_log() = print_line; + const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + ComPtr<ID3D12DescriptorHeap> heap; + if (FAILED(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap)))) return 3; + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + auto at = [&](UINT i) { auto c = heap->GetCPUDescriptorHandleForHeapStart(); c.ptr += SIZE_T{i} * step; return c; }; + + constexpr UINT64 bytes = 1 << 16; + auto buffer = make(device.Get(), D3D12_RESOURCE_DIMENSION_BUFFER, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto tex2d = make(device.Get(), D3D12_RESOURCE_DIMENSION_TEXTURE2D, 64, 64, 1, 2, DXGI_FORMAT_R32_UINT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto tex3d = make(device.Get(), D3D12_RESOURCE_DIMENSION_TEXTURE3D, 64, 64, 8, 2, DXGI_FORMAT_R32_UINT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + if (!buffer || !tex2d || !tex3d) return 4; + const auto removed = [&] { return device->GetDeviceRemovedReason() != S_OK; }; + const auto null_srv = [&](UINT i) { gpu_mirror::null_buffer_view(device.Get(), at(i)); }; + + if (!mutate) check(srgb_uav_roundtrip(device.Get(), heap.Get()), "sRGB SRV and RTV, linear UAV writes all 64 texels on a typeless backing"); + if (!mutate) { + auto depth = make(device.Get(), D3D12_RESOURCE_DIMENSION_TEXTURE2D, 64, 64, 1, 1, DXGI_FORMAT_R24G8_TYPELESS, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + gpu_mirror::Env env{}; + env.device = device.Get(); + auto host = gpu_mirror::HostHeap::create(env, false, 1, {64, 0}, 0, 32, 4); + if (!depth || !host) return 4; + gpu_mirror::View view{}; + view.kind = gpu_mirror::Kind::unordered; + view.has_desc = true; + view.uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + view.uav.Format = DXGI_FORMAT_R32_UINT; + view.resource = tex2d.Get(); + host->make_at(1, view); + check(host->kept_at(1) == tex2d.Get(), "writable texture slot targets materialized texture"); + view.resource = depth.Get(); + host->make_at(1, view); + check(!host->kept_at(1), "reusing a slot for a refused depth UAV leaves no resource to transition"); + } + // 1. A raw SRV 16 KiB past the buffer's end, from 1 KiB in: cut to the end. + { + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + d.Buffer.FirstElement = 256; + d.Buffer.NumElements = static_cast<UINT>((bytes + (16 << 10)) / 4) - 256; + d.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + const bool ok = mutate || gpu_mirror::fit_buffer(buffer.Get(), d, "case 1"); + if (!mutate) check(ok && d.Buffer.NumElements == bytes / 4 - 256, "raw SRV past the end: cut to the buffer's end"); + if (ok) gpu_view_trace::MirrorCall{device.Get(), "fit control"}.srv(buffer.Get(), &d, at(0)); + check(!removed(), "raw SRV past the end: device kept"); + } + // 2. A structured UAV that starts past the end: refused (null view). + if (!removed()) { + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_UNKNOWN; + d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d.Buffer.FirstElement = bytes / 16 + 4; + d.Buffer.NumElements = 8; + d.Buffer.StructureByteStride = 16; + const bool ok = mutate || gpu_mirror::fit_buffer(buffer.Get(), d, "case 2"); + if (!mutate) check(!ok, "structured UAV starting past the end: refused"); + if (ok) device->CreateUnorderedAccessView(buffer.Get(), nullptr, &d, at(1)); + else null_srv(1); + check(!removed(), "structured UAV starting past the end: device kept"); + } + // 3. A constant view of 64 KiB + 256 and one off 256 bytes: refused. + if (!removed()) { + D3D12_CONSTANT_BUFFER_VIEW_DESC big{buffer->GetGPUVirtualAddress(), (64u << 10) + 256}; + D3D12_CONSTANT_BUFFER_VIEW_DESC off{buffer->GetGPUVirtualAddress() + 16, 256}; + const bool ok_big = mutate || gpu_mirror::fit_cbv(big, "case 3"); + const bool ok_off = mutate || gpu_mirror::fit_cbv(off, "case 3"); + if (!mutate) check(!ok_big && !ok_off, "constant views over 64 KiB and off 256 bytes: refused"); + if (ok_big) device->CreateConstantBufferView(&big, at(2)); + if (ok_off) device->CreateConstantBufferView(&off, at(3)); + check(!removed(), "constant views: device kept"); + } + // 4. A 2D texture SRV of mips 1..4 of a 2-mip texture: cut to mip 1; a UAV of mip 3: refused. + if (!removed()) { + D3D12_SHADER_RESOURCE_VIEW_DESC s{}; + s.Format = DXGI_FORMAT_R32_UINT; + s.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + s.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + s.Texture2D.MostDetailedMip = 1; + s.Texture2D.MipLevels = 4; + const bool ok_s = mutate || gpu_mirror::fit_srv(tex2d.Get(), &s, "case 4"); + if (!mutate) check(ok_s && s.Texture2D.MipLevels == 1, "texture SRV of mips past the texture: cut"); + if (ok_s) device->CreateShaderResourceView(tex2d.Get(), &s, at(4)); + D3D12_UNORDERED_ACCESS_VIEW_DESC u{}; + u.Format = DXGI_FORMAT_R32_UINT; + u.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + u.Texture2D.MipSlice = 3; + const bool ok_u = mutate || gpu_mirror::fit_uav(tex2d.Get(), &u, "case 4"); + if (!mutate) check(!ok_u, "texture UAV of a mip the texture lacks: refused"); + if (ok_u) device->CreateUnorderedAccessView(tex2d.Get(), nullptr, &u, at(5)); + check(!removed(), "texture views: device kept"); + } + // 5. A 3D UAV of mip 1 (depth 4) with 8 W slices: cut to 4. + if (!removed()) { + D3D12_UNORDERED_ACCESS_VIEW_DESC u{}; + u.Format = DXGI_FORMAT_R32_UINT; + u.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + u.Texture3D = {1, 0, 8}; + const bool ok = mutate || gpu_mirror::fit_uav(tex3d.Get(), &u, "case 5"); + if (!mutate) check(ok && u.Texture3D.WSize == 4, "3D UAV with W slices past its mip's depth: cut"); + if (ok) device->CreateUnorderedAccessView(tex3d.Get(), nullptr, &u, at(6)); + check(!removed(), "3D UAV: device kept"); + } + // 6. Descriptions that fit are left as they are. + if (!removed()) { + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + d.Buffer.NumElements = bytes / 4; + d.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + D3D12_UNORDERED_ACCESS_VIEW_DESC u{}; + u.Format = DXGI_FORMAT_R32_UINT; + u.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + u.Texture3D = {0, 0, ~0u}; + const D3D12_CONSTANT_BUFFER_VIEW_DESC c{buffer->GetGPUVirtualAddress(), 256}; + const bool kept = gpu_mirror::fit_buffer(buffer.Get(), d, "case 6") && d.Buffer.NumElements == bytes / 4 && + gpu_mirror::fit_uav(tex3d.Get(), &u, "case 6") && u.Texture3D.WSize == ~0u && + gpu_mirror::fit_cbv(c, "case 6"); + if (!mutate) check(kept, "descriptions that fit: unchanged"); + } + std::printf("cut %llu, refused %llu\n", static_cast<unsigned long long>(gpu_mirror::counted(gpu_mirror::c_fit_cut)), + static_cast<unsigned long long>(gpu_mirror::counted(gpu_mirror::c_fit_refused))); + if (mutate && removed()) std::printf("--mutate: the device was removed without the checks (expected for the control)\n"); + if (failures) std::printf("startup_gpu_heap_fit_check: %d failures\n", failures); + else std::printf("startup_gpu_heap_fit_check: pass\n"); + return failures ? 1 : 0; +} diff --git a/tests/startup_gpu_heap_layout_check.cpp b/tests/startup_gpu_heap_layout_check.cpp new file mode 100644 index 0000000000..c1d6d43c22 --- /dev/null +++ b/tests/startup_gpu_heap_layout_check.cpp @@ -0,0 +1,377 @@ +// startup_gpu_heap_layout_check: the mirror heap layout and descriptor rules +// (src/startup_stubs/gpu_heap.h), without a device. The vectors are the upstream Rust tests in +// src/descriptor/host.rs where it has them. +// +// startup_gpu_heap_layout_check every check passes +// startup_gpu_heap_layout_check --mutate probe the host refuses 2^22 views: no twins, so the +// layout checks fail (negative control) +// startup_gpu_heap_layout_check --mutate most X2W_SHADERCFG_DYNAMIC_SLOTS = 2^18: the dynamic +// range of X2W's title heap is another one +#include "startup_stubs/gpu_heap.h" + +#include <cstdio> +#include <cstring> +#include <string> + +using namespace gpu_heap; + +static int failures = 0; +#define CHECK(c) \ + do { \ + if (!(c)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); \ + ++failures; \ + } \ + } while (0) + +static bool same(const std::optional<TwinWindow>& w, u64 first, u32 dwords, u32 by) +{ + return w && w->first == first && w->dwords == dwords && w->by == by; +} + +int main(int argc, char** argv) +{ + std::string mutate; + for (int i = 1; i + 1 < argc; ++i) + if (!std::strcmp(argv[i], "--mutate")) mutate = argv[i + 1]; + + // probe_view_limit: an AMD host takes 2^22 (the 9070 XT does); WARP takes 2^21 only. + const u32 host_most = mutate == "probe" ? (1u << 21) : (1u << 22); + const Limits amd = probe_view_limit(true, [&](u32 n) { return n <= host_most; }); + CHECK(amd.raw == (1u << 21)); + CHECK(amd.null() == (1u << 21) - 1); + const Limits warp = probe_view_limit(true, [](u32 n) { return n <= (1u << 21); }); + CHECK(warp.raw == 0 && warp.null() == (1u << 21) - 1); + const Limits nvidia = probe_view_limit(true, [](u32 n) { return n <= portable_views; }); + CHECK(nvidia.raw == 0 && nvidia.null() == portable_views - 1); + const Limits off = probe_view_limit(false, [](u32) { return true; }); + CHECK(off.raw == 0 && off.null() == (1u << 21) - 1); + + // dynamic_slots. + CHECK(dynamic_slots(4, portable_views - 1) == dynamic_base); + CHECK(dynamic_slots(4, (1u << 21) - 1) == dynamic_most_default); + CHECK(dynamic_slots(2'000'000, (1u << 21) - 1) == dynamic_base); // little room: at least 2^18 + + // A synthetic heap large enough to reduce dynamic capacity. + const u32 most = mutate == "most" ? dynamic_base : dynamic_most_default; + const u32 title = (1u << 20) + (1u << 18); + const Layout l = layout_for(false, title, amd, most); + CHECK(l.size == (1u << 22)); + CHECK(l.null == (1u << 21) - 1); + CHECK(l.raw == (1u << 21)); + CHECK(l.count == title && !l.capped); + CHECK(l.dynamic == (1u << 21) - 1 - title); // remaining space below the null slot + CHECK(l.count + l.dynamic <= l.null); + CHECK(l.twins == l.count + l.dynamic); + for (u32 i : {0u, 1u, 70u, title - 1, title, title + l.dynamic - 1}) { + CHECK(l.has_twin(i)); + CHECK(l.twin(i) == (1u << 21) + i); + CHECK(l.twin(i) < l.size); + } + CHECK(!l.has_twin(l.twins)); + CHECK(l.is_dynamic(title) && l.is_dynamic(title + l.dynamic - 1)); + CHECK(!l.is_dynamic(title - 1) && !l.is_dynamic(title + l.dynamic)); + CHECK(l.clamp(l.size + 17) == l.null); + CHECK(l.clamp(l.null) == l.null && l.clamp(5) == 5); + CHECK(l.null_views_end() == (1u << 21)); + + // A title heap over 2^21: indices beyond the limit resolve to the null slot. + const Layout big = layout_for(false, (1u << 21) + 1, amd, most); + CHECK(big.capped); + CHECK(big.count + big.dynamic == big.null); + CHECK(big.size == (1u << 22)); + // WARP / without twins: the heap ends at the null slot. + const Layout w = layout_for(false, 1000, warp, most); + CHECK(w.size == (1u << 21) && w.raw == 0 && w.twins == 0 && !w.has_twin(0)); + // Sampler heaps: no null slot, no dynamic, no twins. + const Layout s = layout_for(true, 2048, amd, most); + CHECK(s.size == 2048 && s.dynamic == 0 && s.raw == 0 && s.null == 0); + + // Increments 32 / 16 / 128 / 128. + CHECK(increment(0) == 32u && increment(1) == 16u && increment(2) == 128u && increment(3) == 128u); + CHECK(!increment(4)); + + // host.rs a_structured_view_made_raw_passes_the_host_check. + const auto rw = raw_window(32, 8, 100, 20); + CHECK(rw && rw->first == 48 && rw->dwords == 500); + CHECK(buffer_view_ok(format_r32_typeless, 48, 500, 0, true, 4096)); + CHECK(!buffer_view_ok(format_unknown, 48, 500, 0, true, 4096)); + CHECK(!buffer_view_ok(format_r32_typeless, 48, 500, 0, true, 2000)); + CHECK(!raw_window(4, 0, 100, 20)); + CHECK(!buffer_view_ok(format_r32_typeless, 0, 0, 0, true, 4096)); + CHECK(buffer_view_ok(format_unknown, 1, 10, 12, false, 4096)); + CHECK(!buffer_view_ok(format_unknown, 1, 10, 2052, false, 1 << 20)); // stride > 2048 + CHECK(!buffer_view_ok(27, 0, 4, 0, false, 4096)); // typeless R8G8B8A8 + CHECK(buffer_view_ok(28, 0, 4, 0, false, 16)); + CHECK(!buffer_view_ok(71, 0, 4, 0, false, 4096)); // BC1: blocks + + // host.rs raw_twins_show_the_views_bytes. + CHECK(same(twin_window(42, 4, 10, 0, false, 4096), 4, 10, 0)); + CHECK(same(twin_window(57, 8, 7, 0, false, 4096), 4, 4, 0)); + CHECK(same(twin_window(57, 8, 7, 0, false, 30), 4, 3, 0)); + CHECK(same(twin_window(0, 2, 3, 24, false, 4096), 12, 18, 0)); + CHECK(same(twin_window(39, 8, 5, 0, true, 4096), 8, 5, 0)); + CHECK(same(twin_window(0, 1, 3, 24, false, 4096), 4, 20, 8)); + CHECK(same(twin_window(42, 1, 10, 0, false, 4096), 0, 11, 4)); + CHECK(!twin_window(42, 1, 10, 0, false, 4)); + + // host.rs constant_bytes. + CHECK(constant_bytes(480) == 512); + CHECK(constant_bytes(64u << 10) == (64u << 10)); + CHECK(constant_bytes(~0u) == (64u << 10)); + + // host.rs off_elements vectors. + CHECK(off_elements(8, 0, true, 4)); + CHECK(!off_elements(0, 0, true, 4)); + CHECK(!off_elements(48, 0, true, 4)); + CHECK(!off_elements(456, 456, false, 0)); + CHECK(!off_elements(32, 456, false, 0)); + CHECK(off_elements(100, 456, false, 0)); + CHECK(off_elements(23'702'896, 0, false, 12)); + CHECK(!off_elements(48, 0, false, 12)); + CHECK(!off_elements(12, 0, false, 4)); + CHECK(off_elements(12, 0, false, 8)); + + // The table of strides: structured the stride, raw 1, typed the format's, integer kinds. + CHECK(stride_word(std::nullopt) == 0); + CHECK(stride_word(Elements{456, false, 0}) == 456); + CHECK(stride_word(Elements{0, true, 39}) == 1); + CHECK(stride_word(Elements{0, false, 2}) == 16); // R32G32B32A32_FLOAT + CHECK(stride_word(Elements{0, false, 42}) == (4 | view_integer)); // R32_UINT + CHECK(stride_word(Elements{0, false, 43}) == (4 | view_integer | view_signed)); // R32_SINT + CHECK(stride_word(Elements{0, false, 57}) == (2 | view_integer)); // R16_UINT + CHECK((stride_word(Elements{0, false, 62}) & view_stride_bits) == 1); // R8_UINT + CHECK(pc_format(118) == 45 && pc_format(28) == 28); + CHECK(family(29) == 27 && family(87) == 90 && family(100) == 100); + + // host.rs changed_records_are_those_that_differ_one_by_one. + for (std::size_t step : {16u, 32u}) { + const std::size_t count = 300; + u64 seed = 7; + auto random = [&]() { + seed = seed * 0x5851F42D4C957F2Dull + 0x14057B7EF767814Full; + return static_cast<std::size_t>(seed >> 33); + }; + std::vector<unsigned char> last(step * count); + for (auto& b : last) b = static_cast<unsigned char>(random()); + std::vector<unsigned char> now = last; + std::vector<u32> differ; + for (std::size_t slot = 0; slot < count; ++slot) + if (random() % 9 == 0) { + const std::size_t at = slot * step + random() % step; + now[at] ^= static_cast<unsigned char>(1 + random() % 255); + differ.push_back(1000 + static_cast<u32>(slot)); + } + std::vector<u32> out; + changed_records(last.data(), now.data(), now.size(), step, 1000, out); + CHECK(out == differ); + CHECK(last == now); + out.clear(); + changed_records(last.data(), now.data(), now.size(), step, 1000, out); + CHECK(out.empty()); + } + + // host.rs dynamic_slots_are_held_until_released, on a heap of 4 title slots. + { + DynamicRuns d(4, dynamic_base); + const u32 n = d.size(); + const auto a = d.take(n - 100); + const auto b = d.take(60); + CHECK(a == 4u && b == 4 + n - 100); + CHECK(!d.take(50)); + d.release(*a, 50); + CHECK(d.take(50) == 4u); + CHECK(d.take(40) == 4 + n - 40); + } + // host.rs dynamic_search_can_find_a_run_across_the_cursor. + { + DynamicRuns d(4, dynamic_base); + const u32 n = d.size(); + const auto first = d.take(1), left = d.take(2), right = d.take(2), rest = d.take(n - 5); + CHECK(first == 4u && left == 5u && right == 7u && rest == 9u); + d.release(*left, 2); + CHECK(d.take(2) == left); + d.release(*left, 2); + d.release(*right, 2); + CHECK(d.take(4) == left); + CHECK(!d.take(1)); + d.release(*first, 1); + d.release(*first + n - 1, 1); + CHECK(!d.take(2)); + } + + // sampler.rs console_descriptions_decode and its LOD and bounds vectors. + { + u32 w[27]{}; + const auto bits = [](float f) { u32 u; std::memcpy(&u, &f, 4); return u; }; + w[1] = 1; // bilinear magnification + w[2] = 0; // point minification + w[3] = 2; // linear mips + w[6] = w[7] = w[8] = 3; + w[10] = bits(1000.0f); + D3D12_SAMPLER_DESC d = console_sampler(w); + CHECK(d.Filter == 0x5 && d.AddressW == D3D12_TEXTURE_ADDRESS_MODE_CLAMP && d.MaxLOD == 1000.0f); + w[16] = 4; + CHECK(console_sampler(w).Filter == 0x85 && console_sampler(w).ComparisonFunc == D3D12_COMPARISON_FUNC_LESS_EQUAL); + w[16] = 1; + CHECK(console_sampler(w).Filter == 0x5); + u32 m[27]{}; + m[3] = 0; + m[9] = bits(3.0f); + m[10] = bits(8.0f); + d = console_sampler(m); + CHECK(d.MinLOD == 3.0f && d.MaxLOD == 3.0f); + m[3] = 2; + m[9] = bits(4.0f); + m[10] = bits(1.0f); + d = console_sampler(m); + CHECK(d.MinLOD == 4.0f && d.MaxLOD == 4.0f); + u32 b[27]{}; + b[6] = 0; + b[7] = 6; + b[8] = 3; + b[11] = bits(24.0f); + b[16] = 99; + d = console_sampler(b); + CHECK(d.MipLODBias == D3D12_MIP_LOD_BIAS_MAX); + CHECK(d.AddressU == D3D12_TEXTURE_ADDRESS_MODE_CLAMP && d.AddressV == D3D12_TEXTURE_ADDRESS_MODE_CLAMP); + CHECK(d.ComparisonFunc == D3D12_COMPARISON_FUNC_NEVER); + } + // The X2WP record of a placed buffer view. + { + PlacedRecord p; + p.address = 0x123456789a0ull; + p.first = 3; + p.elements = 40; + p.stride = 12; + p.raw = false; + p.unordered = true; + p.width = 4096; + u32 w[8]; + placed_words(p, w); + PlacedRecord q; + CHECK(placed_of(w, q) && q.address == p.address && q.first == 3 && q.elements == 40 && q.stride == 12 && q.unordered && + !q.raw && q.width == 4096); + w[0] = 0; + CHECK(!placed_of(w, q)); + } + // SlotSet. + { + SlotSet s; + s.resize(200); + CHECK(!s.put(3) && s.put(3) && !s.put(130)); + CHECK(s.has(130) && !s.has(131) && !s.has(1000)); + const auto t = s.take(); + CHECK(t.size() == 2 && t[0] == 3 && t[1] == 130 && !s.has(3)); + } + + // A copied 2D descriptor can ask for all levels from its first streamed mip. + { + D3D12_RESOURCE_DESC r{}; + r.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + r.Width = r.Height = 512; r.DepthOrArraySize = 1; r.MipLevels = 10; + r.Format = DXGI_FORMAT_BC7_UNORM; r.SampleDesc.Count = 1; + r.Layout = D3D12_TEXTURE_LAYOUT(0x105); r.Flags = D3D12_RESOURCE_FLAGS(0x300000); + D3D12_SHADER_RESOURCE_VIEW_DESC v{}, decoded{}; + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.Format = r.Format; v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Texture2D.MostDetailedMip = 3; + v.Texture2D.MipLevels = UINT32_MAX; + for (UINT width : {512u, 2048u}) { + auto invalid = r; + invalid.Width = width; + invalid.MipLevels = width == 512 ? 61 : 193; + UINT words[8]{}; + CHECK(!x2w_late_texture::encode(invalid, v, 1, words)); + CHECK(x2w_late_texture::encode(r, v, 1, words)); + words[3] = width | (r.Height << 16); + words[4] = (words[4] & 0xffffff) | (UINT(invalid.MipLevels) << 24); + D3D12_RESOURCE_DESC decoded_shape{}; + CHECK(!x2w_late_texture::decode(words, decoded_shape, decoded)); + words[4] = (words[4] & 0xffff00) | (UINT(r.MipLevels) << 24); + CHECK(!x2w_late_texture::decode(words, decoded_shape, decoded)); + } + auto limit = r; + limit.Width = 1; limit.Height = 1; limit.DepthOrArraySize = 2048; limit.MipLevels = 12; + CHECK(!x2w_late_texture::valid_shape(limit)); // array count does not extend the mip chain + limit.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + CHECK(x2w_late_texture::valid_shape(limit)); // volume depth does + ++limit.MipLevels; + CHECK(!x2w_late_texture::valid_shape(limit)); + limit = r; limit.Width = D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION + 1; + CHECK(!x2w_late_texture::valid_shape(limit)); + for (UINT count : {7u, 65535u, UINT32_MAX}) { + v.Texture2D.MipLevels = count; + UINT words[8]{}; + CHECK(x2w_late_texture::encode(r, v, (UINT64{3} << 32) + (1u << 20), words)); + D3D12_RESOURCE_DESC resource{}; + x2w_late_texture::decode(words, resource, decoded); + CHECK(decoded.Texture2D.MostDetailedMip == 3 && decoded.Texture2D.MipLevels == count && + decoded.Shader4ComponentMapping == v.Shader4ComponentMapping); + } + } + + // Array views spanning packed fields. + for (const auto format : {DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC5_UNORM, DXGI_FORMAT_BC7_UNORM}) { + D3D12_RESOURCE_DESC r{}; + r.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + r.Width = format == DXGI_FORMAT_BC7_UNORM ? 512 : 256; r.Height = UINT(r.Width); + r.DepthOrArraySize = format == DXGI_FORMAT_BC1_UNORM ? 64 : 32; + r.MipLevels = r.Width == 512 ? 10 : 9; r.Format = format; + r.SampleDesc.Count = 1; r.Layout = D3D12_TEXTURE_LAYOUT(0x10a); r.Flags = D3D12_RESOURCE_FLAGS(0x300000); + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = format; v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + for (int partial = 0; partial < 2; ++partial) { + if (partial) r.DepthOrArraySize = 2048; + auto& a = v.Texture2DArray; + a.FirstArraySlice = partial ? 1031 : 0; a.ArraySize = r.DepthOrArraySize - a.FirstArraySlice; + a.MostDetailedMip = partial ? 2 : 0; a.MipLevels = partial ? UINT32_MAX : r.MipLevels; + a.ResourceMinLODClamp = partial ? 1.5f : 0.f; + constexpr UINT64 address = (UINT64{3} << 32) + (1u << 20); + UINT words[8]{}, copied[8]{}; + CHECK(x2w_late_texture::encode(r, v, address, words)); + std::memcpy(copied, words, sizeof(copied)); + D3D12_RESOURCE_DESC got{}; + D3D12_SHADER_RESOURCE_VIEW_DESC shown{}; + x2w_late_texture::decode(copied, got, shown); + CHECK(got.Width == r.Width && got.Height == r.Height && got.Format == r.Format && + got.DepthOrArraySize == r.DepthOrArraySize && got.Layout == r.Layout && got.MipLevels == r.MipLevels); + CHECK(shown.ViewDimension == v.ViewDimension && shown.Format == v.Format && + shown.Shader4ComponentMapping == v.Shader4ComponentMapping && + !std::memcmp(&shown.Texture2DArray, &a, sizeof(a))); + CHECK(x2w_late_texture::encode(got, shown, address, copied) && !std::memcmp(words, copied, sizeof(words))); + ++a.ArraySize; + CHECK(!x2w_late_texture::encode(r, v, address, copied)); + } + } + + for (const bool volume : {false, true}) { + D3D12_RESOURCE_DESC r{}; + r.Dimension = volume ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; + r.Width = volume ? 32u : 64u; r.Height = 64; r.DepthOrArraySize = volume ? 32 : 6; + r.Format = volume ? DXGI_FORMAT_R16G16B16A16_FLOAT : DXGI_FORMAT_BC7_UNORM; + r.MipLevels = 1; r.SampleDesc.Count = 1; r.Layout = D3D12_TEXTURE_LAYOUT(0x105); + r.Flags = D3D12_RESOURCE_FLAGS(0x300000); + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = r.Format; v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.ViewDimension = volume ? D3D12_SRV_DIMENSION_TEXTURE3D : D3D12_SRV_DIMENSION_TEXTURECUBE; + if (volume) v.Texture3D = {0, UINT32_MAX, 0.25f}; + else v.TextureCube = {0, 1, 0}; + UINT marker[8]{}, repeat[8]{}; + CHECK(x2w_late_texture::encode(r, v, 0xb6a100000, marker)); + D3D12_RESOURCE_DESC got{}; + D3D12_SHADER_RESOURCE_VIEW_DESC recovered{}; + x2w_late_texture::decode(marker, got, recovered); + CHECK(got.Dimension == r.Dimension && got.DepthOrArraySize == r.DepthOrArraySize && got.Layout == r.Layout); + CHECK(recovered.ViewDimension == v.ViewDimension && recovered.Shader4ComponentMapping == v.Shader4ComponentMapping && + !std::memcmp(&recovered.Texture3D, &v.Texture3D, sizeof(v.Texture3D))); + CHECK(x2w_late_texture::encode(got, recovered, 0xb6a100000, repeat) && !std::memcmp(marker, repeat, sizeof(repeat))); + } + if (failures) { + std::printf("startup_gpu_heap_layout_check: %d failures\n", failures); + return 1; + } + std::printf("startup_gpu_heap_layout_check: pass\n"); + return 0; +} diff --git a/tests/startup_gpu_heap_shim.cpp b/tests/startup_gpu_heap_shim.cpp new file mode 100644 index 0000000000..b31dcc3912 --- /dev/null +++ b/tests/startup_gpu_heap_shim.cpp @@ -0,0 +1,188 @@ +// WP5 through the shim (X2W_GPU_ABI=1 X2W_D3D12_RENDER=1, WARP): a shader-visible view heap over title memory +// gets a mirror heap (gpu_heap_created), a view call into it is mirrored (gpu_heap_view), and a record the +// title copies there as bytes is found at the next submission (gpu_heap_submit). Read from the shim's log, which +// goes to standard error: here a file. +// +// startup_gpu_heap_shim [--mutate] --mutate: verify that a non-shader-visible heap has no mirror +// +// Exit codes: 0 pass, 1 a check failed, other values name the failing step. +#include <d3d12.h> +#include <dxgi1_6.h> +#include <windows.h> +#include <wrl/client.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <string> +#include <vector> + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Word = std::uint64_t; +template <class T> Word arg(T* value) { return reinterpret_cast<Word>(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0) +{ + using Slot = Word(WINAPI*)(void*, Word, Word, Word, Word, Word, Word); + return reinterpret_cast<Slot>((*static_cast<void***>(object))[index])(object, a, b, c, d, e, f); +} +} // namespace + +int main(int argc, char** argv) +{ + const bool mutate = argc > 1 && std::strcmp(argv[1], "--mutate") == 0; + const bool native = argc > 1 && std::strcmp(argv[1], "--native") == 0; + const bool lazy = argc > 1 && std::strcmp(argv[1], "--lazy") == 0; + char temp[MAX_PATH], log_path[MAX_PATH]; + GetTempPathA(MAX_PATH, temp); + std::snprintf(log_path, sizeof(log_path), "%sx2w_gpu_heap_shim_%lu.log", temp, GetCurrentProcessId()); + HANDLE log_file = CreateFileA(log_path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (log_file == INVALID_HANDLE_VALUE) return 2; + HANDLE old_error = GetStdHandle(STD_ERROR_HANDLE); + SetStdHandle(STD_ERROR_HANDLE, log_file); + + ComPtr<IDXGIFactory6> factory; + ComPtr<IDXGIAdapter> adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) return 3; + unsigned char parameters[64]{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters, __uuidof(ID3D12Device), &device))) return 4; + + // Slot 14: a shader-visible view heap of 64 over title memory (32-byte records). + constexpr UINT slots = 64; + const UINT step = native ? static_cast<UINT>(invoke(device, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)) : 32; + std::vector<unsigned char> title(slots * step); + struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + std::uint64_t extra[2]; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, slots, + mutate ? D3D12_DESCRIPTOR_HEAP_FLAG_NONE : D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}, + {reinterpret_cast<std::uint64_t>(title.data()), title.size()}}; + void* heap = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(device, 14, arg(&heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&heap)))) || !heap) + return 5; + + // Slot 18: a null-resource texture SRV at title slot 3 (X2W writes its token there), then the title copies the + // record to slot 9 as bytes. + 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; + invoke(device, 18, 0, arg(&srv), reinterpret_cast<Word>(title.data()) + 3 * step); + std::memcpy(title.data() + 9 * step, title.data() + 3 * step, step); + + unsigned char* row_pages = nullptr; + std::vector<unsigned char> staging(slots * step); + std::vector<unsigned char> texels(64 * 65536, 0x5a); + if (lazy || native) { + heap_desc.desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; + heap_desc.extra[0] = reinterpret_cast<Word>(staging.data()); + void* cpu_heap{}; + if (FAILED(static_cast<HRESULT>(invoke(device, 14, arg(&heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&cpu_heap))))) return 10; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = desc.Height = 32; + desc.MipLevels = desc.DepthOrArraySize = 1; + desc.SampleDesc.Count = 1; + desc.Format = srv.Format; + desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x105); + desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(0x300000); + struct { D3D12_SHADER_RESOURCE_VIEW_DESC view; Word address; } input{srv}; + for (UINT i = 0; i < 32; ++i) { + input.address = arg(texels.data() + i * 65536); + invoke(device, 70, arg(&desc), arg(&input), arg(staging.data() + i * step)); + UINT tag; + std::memcpy(&tag, staging.data() + i * step, sizeof(tag)); + if (tag != (native ? 0x56573258u : 0x4c573258u)) return 11; + } + if (native) { + row_pages = static_cast<unsigned char*>(VirtualAlloc(nullptr, 12288, MEM_RESERVE, PAGE_NOACCESS)); + if (!row_pages || !VirtualAlloc(row_pages, 8192, MEM_COMMIT, PAGE_READWRITE)) return 12; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D; + desc.Format = input.view.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + desc.Width = 1025; + desc.Height = 1; + desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x100); + input.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; + input.address = arg(row_pages + 8192 - desc.Width * 4); + invoke(device, 70, arg(&desc), arg(&input), arg(staging.data() + 41 * step)); + UINT tag{}; + std::memcpy(&tag, staging.data() + 41 * step, sizeof(tag)); + if (tag != 0x56573258u) return 13; + } + // One CPU-only API copy, one promotion via API, another via byte copy. + invoke(device, 24, 1, arg(staging.data() + 40 * step), arg(staging.data() + step), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + invoke(device, 24, 1, arg(title.data() + 20 * step), arg(staging.data() + 40 * step), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + std::memcpy(title.data() + 21 * step, staging.data() + 2 * step, step); + } + + // Record and submit an empty title command list. Slot 73 creates a closed list. + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void* queue = nullptr; + void* allocator = nullptr; + void* list = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue)))) || !queue) + return 6; + if (FAILED(static_cast<HRESULT>(invoke(device, 9, 0, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator)))) || !allocator) + return 7; + if (FAILED(static_cast<HRESULT>(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) || + !list) + return 8; + if (FAILED(static_cast<HRESULT>(invoke(list, 139, arg(allocator))))) return 9; + if (FAILED(static_cast<HRESULT>(invoke(list, 9)))) return 10; + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + + SetStdHandle(STD_ERROR_HANDLE, old_error); + CloseHandle(log_file); + std::string text; + if (FILE* f = std::fopen(log_path, "rb")) { + char buffer[4096]; + for (std::size_t n; (n = std::fread(buffer, 1, sizeof(buffer), f)) > 0;) text.append(buffer, n); + std::fclose(f); + } + DeleteFileA(log_path); + int failures = 0; + const auto check = [&](bool ok, const char* what) { + std::printf("%s %s\n", ok ? "ok " : "FAIL", what); + if (!ok) ++failures; + }; + const auto line_of = [&](const char* start) { + const auto at = text.find(start); + if (at == std::string::npos) return std::string(); + return text.substr(at, text.find('\n', at) - at); + }; + const std::string mirror = line_of("x2w-gpu heap: mirror of the title's view heap"); + const std::string submit = line_of("x2w-gpu heap submit 1:"); + std::printf("%s\n%s\n", mirror.c_str(), submit.c_str()); + if (native) { + VirtualFree(row_pages, 0, MEM_RELEASE); + check(!line_of("x2w-memsrv form 1d:").empty(), "1025-texel row ends at the last readable byte"); + check(mirror.empty(), "native descriptor handling has no translated heap"); + check(line_of("x2w-gpu detiled texture descriptors staged").empty(), "native reads do not use deferred descriptors"); + check(!line_of("x2w-memsrv detiled memory SRV at").empty(), "native detiled texture was created"); + return failures ? 1 : 0; + } + check(!line_of("x2w-gpu submits 1:").empty(), "the shim submitted one command list"); + if (lazy) { + check(!line_of("x2w-gpu detiled texture descriptors staged 32").empty(), "32 CPU staging writes were deferred"); + const std::string prefix = "x2w-memsrv linear texture at "; + size_t cursor = 0, allocations = 0; + while ((cursor = text.find(prefix, cursor)) != std::string::npos) { ++allocations; cursor += prefix.size(); } + check(allocations == 0, "creating and copying descriptors without a GPU consumer commits no texture"); + } + if (mutate) { + check(mirror.empty() && submit.empty(), "the non-shader-visible heap has no mirror to scan"); + } else { + check(!mirror.empty() && mirror.find(" 64 title slots") != std::string::npos, "a mirror heap of the title's 64 slots"); + check(submit.find(lazy ? "submit 1: 2 records changed" : "submit 1: 1 records changed") != std::string::npos, "submit 1 found the record copied as bytes"); + } + if (failures) std::printf("startup_gpu_heap_shim: %d failures\n", failures); + else std::printf("startup_gpu_heap_shim: pass\n"); + return failures ? 1 : 0; +} diff --git a/tests/startup_gpu_indirect.cpp b/tests/startup_gpu_indirect.cpp new file mode 100644 index 0000000000..9974efaafe --- /dev/null +++ b/tests/startup_gpu_indirect.cpp @@ -0,0 +1,845 @@ +// WP4 (vindirect): the indirect execution core (src/startup_stubs/gpu_indirect_clamp.h) on a +// desktop device, WARP or hardware. Ported from the upstream Rust tests in src/indirect.rs +// (rejects_unaligned_or_undersized_layouts, warp_count_buffer_ignores_garbage_tail_and_preserves_source, +// warp_window_leaves_unfilled_slots_empty_and_uncharged, warp_budget_saturates_without_wraparound_..., +// warp_a_group_charges_its_records_in_lane_order, warp_a_record_that_does_not_fit_may_take_nothing, +// host_list_budget_starts_empty_at_each_submission, card_runs_wide_indirect_dispatches), plus the console +// signature type 0x69 run as a dispatch and mesh records (kind 10) run as DispatchMesh(x, 1, 1). +// +// Usage: startup_gpu_indirect <warp|hardware> <case> [--mutate] +// cases: layout count window budget lanes restart restart-nozero pool dispatch69 mesh wide +// --mutate: the clamp's group-count bound is removed from the HLSL; `count` must then fail. +// restart-nozero: the budget slot is not zeroed after the reset; must fail (control). +// Exit 0 pass, 1 fail, 77 skipped (no such adapter, or it lacks mesh shaders, or `wide` off AMD). +#include "gpu_indirect_clamp.h" +#include "gpu_indirect_capture.h" + +#include "startup_gpu_indirect_ms.h" + +#include <d3d12.h> +#include <d3d12sdklayers.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <cstdio> +#include <cstring> +#include <string> +#include <vector> + +using Microsoft::WRL::ComPtr; +namespace vi = x2w_gpu_indirect; +using vi::u32; +using vi::u64; + +namespace { + +int failures = 0; +#define EXPECT(cond, ...) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL %s:%d: %s: ", __FILE__, __LINE__, #cond); \ + std::printf(__VA_ARGS__); \ + std::printf("\n"); \ + ++failures; \ + } \ + } while (0) + +constexpr char worker_cs[] = R"hlsl( +#define RS "UAV(u0)" +RWByteAddressBuffer hits : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main(uint3 group : SV_GroupID) { + uint was; + hits.InterlockedAdd(0, 1, was); + hits.InterlockedMax(4, group.x, was); +} +)hlsl"; + +struct Mapped { + ComPtr<ID3D12Resource> buffer; + unsigned char* data = nullptr; + u64 gpu = 0; + u32* words() const { return reinterpret_cast<u32*>(data); } +}; + +struct Gpu { + ComPtr<ID3D12Device> device; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + ComPtr<ID3D12InfoQueue> info; + HANDLE event = nullptr; + u64 submitted = 0; + vi::Clamp clamp; + vi::Clamp worker; + vi::HostSignatures signatures; + std::vector<ComPtr<ID3D12Resource>> kept; + + // A CPU-visible buffer the GPU may write as a UAV (custom heap, write-back, L0), mapped and zeroed. + Mapped shared(u64 size) + { + Mapped m; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&m.buffer))) || + FAILED(m.buffer->Map(0, nullptr, reinterpret_cast<void**>(&m.data)))) { + std::printf("FAIL: shared buffer of %llu bytes\n", static_cast<unsigned long long>(size)); + std::exit(1); + } + std::memset(m.data, 0, static_cast<std::size_t>(size)); + m.gpu = m.buffer->GetGPUVirtualAddress(); + return m; + } + ComPtr<ID3D12Resource> device_local(u64 size, D3D12_HEAP_TYPE type = D3D12_HEAP_TYPE_DEFAULT) + { + const D3D12_HEAP_PROPERTIES heap{type}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = type == D3D12_HEAP_TYPE_DEFAULT ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE; + const D3D12_RESOURCE_STATES state = type == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COMMON; + ComPtr<ID3D12Resource> r; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&r)))) { + std::printf("FAIL: buffer of %llu bytes\n", static_cast<unsigned long long>(size)); + std::exit(1); + } + return r; + } + // Closes, runs and waits for the list, then reopens it. Fails on any debug-layer error. + void run() + { + if (FAILED(list->Close())) { + std::printf("FAIL: list close\n"); + std::exit(1); + } + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + queue->Signal(fence.Get(), ++submitted); + if (fence->GetCompletedValue() < submitted) { + fence->SetEventOnCompletion(submitted, event); + WaitForSingleObject(event, 60000); + } + if (fence->GetCompletedValue() < submitted || FAILED(device->GetDeviceRemovedReason())) { + std::printf("FAIL: GPU did not finish (removed 0x%08lx)\n", static_cast<unsigned long>(device->GetDeviceRemovedReason())); + std::exit(1); + } + debug_errors(); + allocator->Reset(); + list->Reset(allocator.Get(), nullptr); + } + void debug_errors() + { + if (!info) return; + const UINT64 n = info->GetNumStoredMessages(); + for (UINT64 i = 0; i < n; ++i) { + SIZE_T size = 0; + info->GetMessage(i, nullptr, &size); + std::vector<char> bytes(size); + auto* m = reinterpret_cast<D3D12_MESSAGE*>(bytes.data()); + if (SUCCEEDED(info->GetMessage(i, m, &size)) && + (m->Severity == D3D12_MESSAGE_SEVERITY_ERROR || m->Severity == D3D12_MESSAGE_SEVERITY_CORRUPTION)) { + std::printf("FAIL debug layer: %.*s\n", static_cast<int>(m->DescriptionByteLength), m->pDescription); + ++failures; + } + } + info->ClearStoredMessages(); + } + void copy_out(ID3D12Resource* from, D3D12_RESOURCE_STATES state, u64 at, const Mapped& to, u64 bytes) + { + const D3D12_RESOURCE_BARRIER b = vi::transition(from, state, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &b); + list->CopyBufferRegion(to.buffer.Get(), 0, from, at, bytes); + const D3D12_RESOURCE_BARRIER back = vi::transition(from, D3D12_RESOURCE_STATE_COPY_SOURCE, state); + list->ResourceBarrier(1, &back); + } + void bind_worker(u64 hits_gpu) + { + list->SetComputeRootSignature(worker.root); + list->SetPipelineState(worker.pso); + list->SetComputeRootUnorderedAccessView(0, hits_gpu); + } +}; + +// 0 ok, 77 no adapter. +int open_gpu(Gpu& g, bool hardware) +{ + ComPtr<ID3D12Debug> debug; + char wanted[8]{}; + const bool debug_off = GetEnvironmentVariableA("X2W_TEST_NO_DEBUG_LAYER", wanted, sizeof(wanted)) && wanted[0] == '1'; + if (!debug_off && SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) debug->EnableDebugLayer(); + ComPtr<IDXGIFactory4> factory; + if (FAILED(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory)))) return 77; + ComPtr<IDXGIAdapter1> adapter; + if (hardware) { + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) { + DXGI_ADAPTER_DESC1 desc{}; + adapter->GetDesc1(&desc); + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&g.device)))) + break; + adapter.Reset(); + } + if (!g.device) return 77; + } else { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) || + FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&g.device)))) + return 77; + } + if (debug) g.device.As(&g.info); + std::printf("debug layer %s\n", g.info ? "on" : "off"); + const D3D12_COMMAND_QUEUE_DESC queue{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(g.device->CreateCommandQueue(&queue, IID_PPV_ARGS(&g.queue))) || + FAILED(g.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&g.allocator))) || + FAILED(g.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g.allocator.Get(), nullptr, IID_PPV_ARGS(&g.list))) || + FAILED(g.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&g.fence)))) { + std::printf("FAIL: device objects\n"); + return 1; + } + g.event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + std::string errors; + if (FAILED(vi::make_clamp(g.device.Get(), worker_cs, &g.worker, &errors))) { + std::printf("FAIL: worker: %s\n", errors.c_str()); + return 1; + } + return 0; +} + +bool make_clamp(Gpu& g, bool mutate, bool rest = true) +{ + std::string text = vi::clamp_text(vi::widest(vi::is_amd(g.device.Get())), rest); + if (mutate) { + const std::string bound = "g = min(g, uint3(g.x <= WIDEST ? WIDEST : 65535u, 65535u, 65535u));"; + const auto at = text.find(bound); + if (at == std::string::npos) { + std::printf("FAIL: the mutation found no bound to remove\n"); + return false; + } + text.erase(at, bound.size()); + } + std::string errors; + const HRESULT hr = vi::make_clamp(g.device.Get(), text, &g.clamp, &errors); + if (FAILED(hr)) std::printf("FAIL: the clamp did not build (0x%08lx): %s\n", static_cast<unsigned long>(hr), errors.c_str()); + return SUCCEEDED(hr); +} + +void put(unsigned char* at, std::initializer_list<u32> words) +{ + for (u32 w : words) { + std::memcpy(at, &w, 4); + at += 4; + } +} + +// ---- cases ----------------------------------------------------------------------------------------------- + +int case_draw_capture(Gpu& g, bool indexed) +{ + // A pixel UAV records the actual 16x16 pixel coordinates touched by the indirect draw. + constexpr char shaders[] = R"( + float4 vs(uint id:SV_VertexID):SV_Position { return float4(-0.5625,0.1875,0.5,1); } + RWByteAddressBuffer hits:register(u0); + void ps(float4 xy:SV_Position) { uint ignored; hits.InterlockedAdd(4*(uint(xy.x)+16*uint(xy.y)),1,ignored); } + )"; + ComPtr<ID3DBlob> vs, ps; + if (FAILED(D3DCompile(shaders, sizeof(shaders), nullptr, nullptr, nullptr, "vs", "vs_5_1", 0, 0, &vs, nullptr)) || + FAILED(D3DCompile(shaders, sizeof(shaders), nullptr, nullptr, nullptr, "ps", "ps_5_1", 0, 0, &ps, nullptr))) return 1; + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = g.worker.root; + pso.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; + pso.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; + pso.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso.RasterizerState.DepthClipEnable = TRUE; + pso.SampleMask = UINT_MAX; + pso.SampleDesc.Count = 1; + pso.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT; + ComPtr<ID3D12PipelineState> pipeline; + if (FAILED(g.device->CreateGraphicsPipelineState(&pso, IID_PPV_ARGS(&pipeline)))) return 1; + constexpr UINT stride = 32, records = 10; + auto args = g.shared(stride * records), count = g.shared(16), budget = g.shared(256), pixels = g.shared(1024); + auto indices = g.shared(32); + put(indices.data, {0,0,1,2,3}); + if (indexed) put(args.data, {3,2,2,UINT_MAX,5}); + else put(args.data, {3,2,7,5}); + put(args.data + stride, {9,1,0,0}); + put(count.data, {1}); + auto scratch = g.device_local(4096); + vi::ClampCall c; + c.kind = indexed ? vi::kind_indexed : vi::kind_draw; + c.stride = stride; c.records = records; c.dst_offset = 256; + c.src = args.buffer.Get(); c.count = count.buffer.Get(); c.count_out = true; + c.dst = scratch.Get(); c.budget_gpu = budget.gpu; + if (!vi::record_clamp(g.list.Get(), g.clamp, c)) return 1; + auto* signature = g.signatures.get(g.device.Get(), c.kind, stride); + if (!signature) return 1; + x2w_compute_trace::IndirectArguments capture; + if (!capture.record(g.device.Get(), g.list.Get(), c.dst, c.dst_offset, c.kind, stride, records, true)) return 1; + x2w_compute_trace::IndirectArguments uncounted; + if (!uncounted.record(g.device.Get(), g.list.Get(), c.dst, c.dst_offset, c.kind, stride, 1, false)) return 1; + g.list->SetGraphicsRootSignature(g.worker.root); + g.list->SetGraphicsRootUnorderedAccessView(0, pixels.gpu); + g.list->SetPipelineState(pipeline.Get()); + g.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_POINTLIST); + if (indexed) { + const D3D12_INDEX_BUFFER_VIEW view{indices.gpu, 32, DXGI_FORMAT_R32_UINT}; + g.list->IASetIndexBuffer(&view); + } + const D3D12_VIEWPORT viewport{0,0,16,16,0,1}; + const D3D12_RECT scissor{0,0,16,16}; + g.list->RSSetViewports(1, &viewport); + g.list->RSSetScissorRects(1, &scissor); + g.list->ExecuteIndirect(signature, records, c.dst, c.dst_offset, c.dst, c.dst_offset + records * stride); + g.run(); + x2w_compute_trace::IndirectArguments::Snapshot sample{}; + EXPECT(capture.read(sample) && sample.count == 1 && capture.copied == 8, "effective count and sample bound"); + const size_t bytes = indexed ? sizeof(D3D12_DRAW_INDEXED_ARGUMENTS) : sizeof(D3D12_DRAW_ARGUMENTS); + EXPECT(!std::memcmp(sample.records[0].data(), args.data, bytes), "counts, start locations and indexed base vertex"); + EXPECT(uncounted.read(sample) && !uncounted.counted && sample.count == 1 && + !std::memcmp(sample.records[0].data(), args.data, bytes), "draw without a count buffer"); + for (UINT i=0; i<256; ++i) + EXPECT(pixels.words()[i] == (i == 6*16+3 ? 6u : 0u), "indirect coverage pixel %u count %u", i, pixels.words()[i]); + return 0; +} + +int case_layout() +{ + u64 bytes = 0; + EXPECT(vi::validate_layout(0, 16, 4, 0, false, 0, &bytes) && bytes == 64, "draw"); + EXPECT(vi::validate_layout(1, 20, 4, 64, true, 128, &bytes) && bytes == 80, "indexed with count"); + EXPECT(vi::validate_layout(2, 12, 0, 0, true, 0, &bytes) && bytes == 0, "dispatch, no records"); + EXPECT(vi::validate_layout(10, 16, 2, 8, false, 0, &bytes) && bytes == 32, "mesh"); + EXPECT(!vi::validate_layout(0, 12, 1, 0, false, 0, nullptr), "undersized draw"); + EXPECT(!vi::validate_layout(1, 16, 1, 0, false, 0, nullptr), "undersized indexed"); + EXPECT(!vi::validate_layout(2, 8, 1, 0, false, 0, nullptr), "undersized dispatch"); + EXPECT(!vi::validate_layout(10, 8, 1, 0, false, 0, nullptr), "undersized mesh"); + EXPECT(!vi::validate_layout(3, 16, 1, 0, false, 0, nullptr), "unknown kind"); + EXPECT(!vi::validate_layout(0, 18, 1, 0, false, 0, nullptr), "unaligned stride"); + EXPECT(!vi::validate_layout(0, 16, 1, 2, false, 0, nullptr), "unaligned source"); + EXPECT(!vi::validate_layout(0, 16, 1, 0, true, 6, nullptr), "unaligned count"); + EXPECT(!vi::validate_layout(1, 20, 0xffffffffu, 0, false, 0, nullptr), "over 32 bits of bytes"); + u32 kind = 99; + const u32 single[] = {vi::console_single_dispatch}; + EXPECT(vi::signature_kind(single, 1, &kind) && kind == vi::kind_dispatch, "0x69 runs as a dispatch (kind %u)", kind); + for (u32 type : {0u, 1u, 2u, 10u}) { + const u32 one[] = {type}; + EXPECT(vi::signature_kind(one, 1, &kind) && kind == type, "type %u", type); + } + for (u32 type : {3u, 4u, 5u, 6u, 7u, 8u, 9u, 11u, 0x68u, 0x6au}) { + const u32 one[] = {type}; + EXPECT(!vi::signature_kind(one, 1, &kind), "type %u is not run", type); + } + const u32 constants_then_dispatch[] = {5, 2}; + EXPECT(!vi::signature_kind(constants_then_dispatch, 2, &kind), "a signature that changes root arguments is dropped"); + EXPECT(!vi::signature_kind(nullptr, 0, &kind), "no arguments"); + EXPECT(vi::mesh_groups(70000) == 65535 && vi::mesh_groups(12) == 12, "direct mesh dispatches are cut to 65,535"); + const u32 threads[3] = {8847, 1, 1}, size[3] = {64, 1, 1}; + u32 groups[3]; + vi::dispatch_groups(threads, size, groups); + EXPECT(groups[0] == 139 && groups[1] == 1 && groups[2] == 1, "threads in groups: %u %u %u", groups[0], groups[1], groups[2]); + const u32 threads2[3] = {0, 12, 9}, size2[3] = {64, 4, 4}; + vi::dispatch_groups(threads2, size2, groups); + EXPECT(groups[0] == 0 && groups[1] == 3 && groups[2] == 3, "threads in groups (2)"); + EXPECT(vi::widest(true) == (1u << 20) && vi::widest(false) == 65535 && vi::widest(true, false) == 65535, "widest"); + return 0; +} + +// The count bounds the records, the garbage tail is neither run nor charged, the source and count are left as +// they were, and whole strides are copied. The effective count is read from the scratch buffer (count_out). +int case_count(Gpu& g) +{ + constexpr u32 kind = vi::kind_dispatch, stride = 24, max = 4096; + constexpr std::size_t args_offset = 64, count_1 = 128, count_2 = 192; + const std::size_t src_bytes = args_offset + std::size_t{stride} * max + 64; + Mapped src = g.shared(src_bytes), count = g.shared(512), budget = g.shared(256), hits = g.shared(256); + Mapped back = g.shared(stride * 5 + 16); + const u64 dst_bytes = u64{stride} * max + 4; + ComPtr<ID3D12Resource> dst = g.device_local(dst_bytes); + ID3D12CommandSignature* sig = g.signatures.get(g.device.Get(), kind, stride); + std::memset(src.data, 0xa5, src_bytes); + auto record = [&](std::size_t i, std::initializer_list<u32> w) { put(src.data + args_offset + i * stride, w); }; + record(0, {3, 2, 1, 0x11112222, 0x33334444, 0x55556666}); + record(1, {5, 1, 1, 0x77778888, 0x9999aaaa, 0xbbbbcccc}); + record(2, {(1u << 20) + 1, 1, 1, 0xddddeeee, 0xffff0001, 0x01234567}); + for (std::size_t i = 3; i < max; ++i) record(i, {0xffffffffu, 16, 1, 0xdeadbeef, 0xbad0c0de, static_cast<u32>(i)}); + std::memset(count.data, 0x5a, 512); + put(count.data + count_1, {3}); + put(count.data + count_2, {2}); + const std::vector<unsigned char> src_before(src.data, src.data + src_bytes), count_before(count.data, count.data + 512); + + vi::ClampCall c; + c.kind = kind; + c.stride = stride; + c.records = max; + c.src = src.buffer.Get(); + c.src_offset = args_offset; + c.count = count.buffer.Get(); + c.count_offset = count_1; + c.dst = dst.Get(); + c.budget_gpu = budget.gpu; + c.count_out = true; + EXPECT(vi::record_clamp(g.list.Get(), g.clamp, c), "first clamp recorded"); + g.bind_worker(hits.gpu); + g.list->ExecuteIndirect(sig, max, dst.Get(), 0, dst.Get(), u64{stride} * max); + // Snapshot of the first five records and the count after the records. + const D3D12_RESOURCE_BARRIER b = vi::transition(dst.Get(), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE); + g.list->ResourceBarrier(1, &b); + g.list->CopyBufferRegion(back.buffer.Get(), 0, dst.Get(), 0, stride * 5); + g.list->CopyBufferRegion(back.buffer.Get(), stride * 5, dst.Get(), u64{stride} * max, 4); + const D3D12_RESOURCE_BARRIER b2 = vi::transition(dst.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + g.list->ResourceBarrier(1, &b2); + // A second execution in the same list, the scratch buffer straight from arguments back to unordered access. + c.count_offset = count_2; + c.dst_before = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + EXPECT(vi::record_clamp(g.list.Get(), g.clamp, c), "second clamp recorded"); + g.bind_worker(hits.gpu); + g.list->ExecuteIndirect(sig, max, dst.Get(), 0, dst.Get(), u64{stride} * max); + g.run(); + + const u32 expected = (6 + 5 + 65535) + (6 + 5); + EXPECT(hits.words()[0] == expected, "valid dispatches all run: %u groups, expected %u", hits.words()[0], expected); + EXPECT(budget.words()[0] == expected * 64, "budget charged %u, expected %u", budget.words()[0], expected * 64); + EXPECT(std::memcmp(src_before.data(), src.data, src_bytes) == 0, "source never written"); + EXPECT(std::memcmp(count_before.data(), count.data, 512) == 0, "count never written"); + const u32* w = back.words(); + const u32 r0[] = {3, 2, 1, 0x11112222, 0x33334444, 0x55556666}, r1[] = {5, 1, 1, 0x77778888, 0x9999aaaa, 0xbbbbcccc}, + r2[] = {65535, 1, 1, 0xddddeeee, 0xffff0001, 0x01234567}; + EXPECT(std::memcmp(w, r0, 24) == 0, "record 0: %u %u %u", w[0], w[1], w[2]); + EXPECT(std::memcmp(w + 6, r1, 24) == 0, "record 1: %u %u %u", w[6], w[7], w[8]); + EXPECT(std::memcmp(w + 12, r2, 24) == 0, "record 2 clamped to 65535: %u %u %u", w[12], w[13], w[14]); + EXPECT(w[21] != 0xdeadbeef, "inactive record 3 not copied"); + EXPECT(w[30] == 3, "effective count after the records: %u", w[30]); + return 0; +} + +// Mesh records clamped ahead and one by one: filled ones as they are, all-ones slots empty and free. +int case_window(Gpu& g) +{ + constexpr u32 stride = 32, records = 16; + const u32 filled[3] = {5, 0, 519}; + const std::size_t total = std::size_t{stride} * records; + for (bool ahead : {true, false}) { + Mapped src = g.shared(total), budget = g.shared(256), back = g.shared(total); + ComPtr<ID3D12Resource> dst = g.device_local(total); + std::memset(src.data, 0xff, total); + for (u32 i = 0; i < 3; ++i) put(src.data + i * stride, {filled[i], 1, 1, 0xab00 + i}); + vi::ClampCall c; + c.kind = vi::kind_mesh; + c.stride = stride; + c.records = records; + c.src = src.buffer.Get(); + c.dst = dst.Get(); + c.budget_gpu = budget.gpu; + c.ahead = ahead; + EXPECT(vi::record_clamp(g.list.Get(), g.clamp, c), "clamp recorded"); + g.copy_out(dst.Get(), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, 0, back, total); + g.run(); + const u32* out = back.words(); + for (u32 i = 0; i < 3; ++i) + EXPECT(out[i * 8] == filled[i] && out[i * 8 + 1] == 1 && out[i * 8 + 2] == 1 && out[i * 8 + 3] == 0xab00 + i, + "filled record %u (ahead %d): %u %u %u %x", i, ahead, out[i * 8], out[i * 8 + 1], out[i * 8 + 2], out[i * 8 + 3]); + for (u32 i = 3; i < records; ++i) { + EXPECT(out[i * 8] == 0 && out[i * 8 + 1] == 0 && out[i * 8 + 2] == 0, "unfilled slot %u empty (ahead %d)", i, ahead); + EXPECT(out[i * 8 + 3] == 0xffffffffu, "words after the record copied (slot %u)", i); + } + EXPECT(budget.words()[0] == (5 + 519) * 128, "unfilled slots charge nothing: %u", budget.words()[0]); + EXPECT(budget.words()[1] == 519, "largest asked %u", budget.words()[1]); + } + return 0; +} + +// The budget saturates at 2^27 without 32-bit wraparound; draw fields past the counts are kept. +int case_budget(Gpu& g) +{ + constexpr u32 stride = 24, records = 128; + const std::size_t total = std::size_t{stride} * records; + Mapped src = g.shared(total), budget = g.shared(256), back = g.shared(total); + ComPtr<ID3D12Resource> dst = g.device_local(total); + for (u32 i = 0; i < records; ++i) + put(src.data + i * stride, {i + 1 < records ? (1u << 22) : (1u << 23), 0xffffffffu, 1000 + i, static_cast<u32>(-200 + static_cast<int>(i)), + 5000 + i, 0xcafe0000u | i}); + const std::vector<unsigned char> before(src.data, src.data + total); + vi::ClampCall c; + c.kind = vi::kind_indexed; + c.stride = stride; + c.records = records; + c.src = src.buffer.Get(); + c.dst = dst.Get(); + c.budget_gpu = budget.gpu; + EXPECT(vi::record_clamp(g.list.Get(), g.clamp, c), "clamp recorded"); + g.copy_out(dst.Get(), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, 0, back, total); + g.run(); + EXPECT(budget.words()[0] == vi::budget, "saturates at the budget: %u", budget.words()[0]); + EXPECT(std::memcmp(before.data(), src.data, total) == 0, "source untouched"); + u32 kept = 0, zeroed = 0; + const u32* out = back.words(); + for (u32 i = 0; i < records; ++i) { + const u32* r = out + i * 6; + if (r[0] == (1u << 22) && r[1] == 16) ++kept; + else if (r[0] == 0 && r[1] == 0) ++zeroed; + EXPECT(r[2] == 1000 + i && r[3] == static_cast<u32>(-200 + static_cast<int>(i)) && r[4] == 5000 + i && r[5] == (0xcafe0000u | i), + "fields of record %u kept", i); + } + EXPECT(kept == 2 && zeroed == records - 2, "kept %u, zeroed %u", kept, zeroed); + return 0; +} + +// Draws of 100, 250, 50, 100 with 300 left: in lane order; with REST the one that does not fit takes the rest. +int case_lanes(Gpu& g, bool rest) +{ + vi::Clamp own; + std::string errors; + if (FAILED(vi::make_clamp(g.device.Get(), vi::clamp_text(vi::widest(vi::is_amd(g.device.Get())), rest), &own, &errors))) { + std::printf("FAIL: clamp (rest %d): %s\n", rest, errors.c_str()); + return 1; + } + constexpr u32 stride = 16; + const u32 counts[4] = {100, 250, 50, 100}; + Mapped src = g.shared(64), budget = g.shared(256), back = g.shared(64); + ComPtr<ID3D12Resource> dst = g.device_local(64); + for (u32 i = 0; i < 4; ++i) put(src.data + i * stride, {counts[i], 1, 7, 9}); + budget.words()[0] = vi::budget - 300; + vi::ClampCall c; + c.kind = vi::kind_draw; + c.stride = stride; + c.records = 4; + c.src = src.buffer.Get(); + c.dst = dst.Get(); + c.budget_gpu = budget.gpu; + EXPECT(vi::record_clamp(g.list.Get(), own, c), "clamp recorded"); + g.copy_out(dst.Get(), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, 0, back, 64); + g.run(); + own.release(); + const u32 left = vi::budget - budget.words()[0]; + const u32* out = back.words(); + const u32 expect_rest[4] = {100, 0, 0, 0}, expect_take_nothing[4] = {100, 0, 50, 100}; + const u32* expected = rest ? expect_rest : expect_take_nothing; + for (u32 i = 0; i < 4; ++i) + EXPECT(out[i * 4] == expected[i] && out[i * 4 + 1] == (expected[i] ? 1u : 0u) && out[i * 4 + 2] == 7 && out[i * 4 + 3] == 9, + "record %u (rest %d): %u %u", i, rest, out[i * 4], out[i * 4 + 1]); + EXPECT(left == (rest ? 0u : 50u), "left %u (rest %d)", left, rest); + return 0; +} + +// The budget restarts at each recording: zeroed on the GPU at the first clamp after the reset (as the glue +// does, from a pool slot). A recording whose clamps spend it all leaves a small record after them empty; the +// next recording's small record runs. `zero` false: the control, the slot is not zeroed again. +int case_restart(Gpu& g, bool zero) +{ + Mapped big = g.shared(64), little = g.shared(64), hits = g.shared(256); + // Three records of 65535 x 16 groups (67,107,840 threads each): two fit 2^27, the third takes the rest. + for (u32 i = 0; i < 3; ++i) put(big.data + i * 12, {65535, 16, 1}); + put(little.data, {1, 1, 1}); + ComPtr<ID3D12Resource> pool = g.device_local(64 * vi::budget_slot_bytes); + ComPtr<ID3D12Resource> zeros = g.device_local(256, D3D12_HEAP_TYPE_UPLOAD); + { + void* p = nullptr; + zeros->Map(0, nullptr, &p); + std::memset(p, 0, 256); + zeros->Unmap(0, nullptr); + } + const u64 slot = 5 * vi::budget_slot_bytes; + ComPtr<ID3D12Resource> dst = g.device_local(64 << 10); + ID3D12CommandSignature* sig = g.signatures.get(g.device.Get(), vi::kind_dispatch, 12); + for (int round = 0; round < 2; ++round) { + if (round == 0 || zero) vi::record_budget_zero(g.list.Get(), pool.Get(), slot, zeros.Get()); + vi::ClampCall c; + c.kind = vi::kind_dispatch; + c.stride = 12; + c.dst = dst.Get(); + c.budget_gpu = pool->GetGPUVirtualAddress() + slot; + c.budget_resource = pool.Get(); + if (round == 0) { + c.records = 3; + c.src = big.buffer.Get(); + EXPECT(vi::record_clamp(g.list.Get(), g.clamp, c), "big clamp"); + c.dst_before = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + } + c.records = 1; + c.src = little.buffer.Get(); + EXPECT(vi::record_clamp(g.list.Get(), g.clamp, c), "small clamp"); + g.bind_worker(hits.gpu); + g.list->ExecuteIndirect(sig, 1, dst.Get(), 0, nullptr, 0); + const D3D12_RESOURCE_BARRIER rest = vi::transition(dst.Get(), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + g.list->ResourceBarrier(1, &rest); + g.run(); + EXPECT(hits.words()[0] == static_cast<u32>(round), "round %d: the small record ran %u times, expected %d", round, + hits.words()[0], round); + } + return 0; +} + +// Two lists in one ExecuteCommandLists, each zeroing and charging its own slot of one budget pool, as the glue +// does: both run their record, and the debug layer finds no state the pool is not in (the pool rests in COMMON +// outside each clamp, since buffers decay only at the end of the whole call). +int case_pool(Gpu& g) +{ + Mapped one = g.shared(64), hits = g.shared(256); + put(one.data, {3, 1, 1}); + ComPtr<ID3D12Resource> pool = g.device_local(64 * vi::budget_slot_bytes); + ComPtr<ID3D12Resource> zeros = g.device_local(256, D3D12_HEAP_TYPE_UPLOAD); + { + void* p = nullptr; + zeros->Map(0, nullptr, &p); + std::memset(p, 0, 256); + zeros->Unmap(0, nullptr); + } + ComPtr<ID3D12Resource> dst = g.device_local(64 << 10); + ID3D12CommandSignature* sig = g.signatures.get(g.device.Get(), vi::kind_dispatch, 12); + ComPtr<ID3D12CommandAllocator> allocator2; + ComPtr<ID3D12GraphicsCommandList> list2; + if (FAILED(g.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator2))) || + FAILED(g.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator2.Get(), nullptr, IID_PPV_ARGS(&list2)))) { + std::printf("FAIL: second list\n"); + return 1; + } + ID3D12GraphicsCommandList* lists[2] = {g.list.Get(), list2.Get()}; + for (int i = 0; i < 2; ++i) { + ID3D12GraphicsCommandList* l = lists[i]; + const u64 slot = (7 + i) * vi::budget_slot_bytes; + vi::record_budget_zero(l, pool.Get(), slot, zeros.Get()); + for (int call = 0; call < 2; ++call) { + vi::ClampCall c; + c.kind = vi::kind_dispatch; + c.stride = 12; + c.records = 1; + c.src = one.buffer.Get(); + c.dst = dst.Get(); + c.dst_offset = 256 * (2 * i + call); + c.budget_gpu = pool->GetGPUVirtualAddress() + slot; + c.budget_resource = pool.Get(); + EXPECT(vi::record_clamp(l, g.clamp, c), "clamp %d.%d", i, call); + l->SetComputeRootSignature(g.worker.root); + l->SetPipelineState(g.worker.pso); + l->SetComputeRootUnorderedAccessView(0, hits.gpu); + l->ExecuteIndirect(sig, 1, dst.Get(), c.dst_offset, nullptr, 0); + const D3D12_RESOURCE_BARRIER rest = vi::transition(dst.Get(), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + l->ResourceBarrier(1, &rest); + } + } + list2->Close(); + // g.run() closes and runs g.list; list2 goes in the same call. + if (FAILED(g.list->Close())) return 1; + ID3D12CommandList* both[2] = {g.list.Get(), list2.Get()}; + g.queue->ExecuteCommandLists(2, both); + g.queue->Signal(g.fence.Get(), ++g.submitted); + g.fence->SetEventOnCompletion(g.submitted, g.event); + WaitForSingleObject(g.event, 60000); + g.debug_errors(); + EXPECT(hits.words()[0] == 12, "both lists ran both records: %u groups, expected 12", hits.words()[0]); + g.allocator->Reset(); + g.list->Reset(g.allocator.Get(), nullptr); + return 0; +} + +// A signature of the console's type 0x69 runs its records as dispatches through a host signature of kind 2. +int case_dispatch69(Gpu& g) +{ + const D3D12_INDIRECT_ARGUMENT_DESC title[1] = {{static_cast<D3D12_INDIRECT_ARGUMENT_TYPE>(0x69)}}; + u32 kind = 99; + EXPECT(vi::signature_kind_of(title, 1, &kind) && kind == vi::kind_dispatch, "0x69 decoded as %u", kind); + ID3D12CommandSignature* sig = g.signatures.get(g.device.Get(), kind, 12); + EXPECT(sig != nullptr, "host signature for kind 2, stride 12"); + EXPECT(sig == g.signatures.get(g.device.Get(), kind, 12), "made once"); + if (!sig) return 1; + Mapped src = g.shared(64), budget = g.shared(256), hits = g.shared(256); + put(src.data, {7, 2, 1, 0xffffffffu, 1, 1}); + ComPtr<ID3D12Resource> dst = g.device_local(64 << 10); + vi::ClampCall c; + c.kind = kind; + c.stride = 12; + c.records = 2; + c.src = src.buffer.Get(); + c.dst = dst.Get(); + c.dst_offset = 256; + c.budget_gpu = budget.gpu; + EXPECT(vi::record_clamp(g.list.Get(), g.clamp, c), "clamp recorded"); + g.bind_worker(hits.gpu); + g.list->ExecuteIndirect(sig, 2, dst.Get(), 256, nullptr, 0); + g.run(); + // (7, 2, 1) runs 14 groups; (2^32 - 1, 1, 1) is cut to 65,535 in x (past WIDEST on any card). + const u32 expected = 14 + 65535; + EXPECT(hits.words()[0] == expected, "groups run %u, expected %u", hits.words()[0], expected); + return 0; +} + +// Mesh records (kind 10) with a count: run as DispatchMesh(x, 1, 1); all-ones and over-65,535 records empty. +int case_mesh(Gpu& g) +{ + D3D12_FEATURE_DATA_D3D12_OPTIONS7 options{}; + if (FAILED(g.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &options, sizeof(options))) || + options.MeshShaderTier < D3D12_MESH_SHADER_TIER_1) { + std::printf("SKIP: no mesh shaders on this adapter\n"); + return 77; + } + ComPtr<ID3D12Device2> device2; + ComPtr<ID3D12GraphicsCommandList6> list6; + if (FAILED(g.device.As(&device2)) || FAILED(g.list.As(&list6))) { + std::printf("SKIP: no ID3D12Device2 / ID3D12GraphicsCommandList6\n"); + return 77; + } + ComPtr<ID3D12RootSignature> root; + if (FAILED(g.device->CreateRootSignature(0, startup_gpu_indirect_ms, sizeof(startup_gpu_indirect_ms), IID_PPV_ARGS(&root)))) { + std::printf("FAIL: mesh root signature\n"); + return 1; + } + struct alignas(void*) Stream { + struct alignas(void*) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE; + ID3D12RootSignature* value; + } root; + struct alignas(void*) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS; + D3D12_SHADER_BYTECODE value; + } ms; + struct alignas(void*) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER; + D3D12_RASTERIZER_DESC value; + } raster; + struct alignas(void*) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL; + D3D12_DEPTH_STENCIL_DESC value; + } depth; + } stream{}; + stream.root.value = root.Get(); + stream.ms.value = {startup_gpu_indirect_ms, sizeof(startup_gpu_indirect_ms)}; + stream.raster.value.FillMode = D3D12_FILL_MODE_SOLID; + stream.raster.value.CullMode = D3D12_CULL_MODE_NONE; + stream.raster.value.DepthClipEnable = TRUE; + stream.depth.value.DepthEnable = FALSE; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + ComPtr<ID3D12PipelineState> pso; + if (FAILED(device2->CreatePipelineState(&desc, IID_PPV_ARGS(&pso)))) { + std::printf("FAIL: mesh pipeline\n"); + return 1; + } + constexpr u32 stride = 12, max = 8; + Mapped src = g.shared(stride * max), count = g.shared(16), budget = g.shared(256), seen = g.shared(256); + std::memset(src.data, 0xff, stride * max); + put(src.data + 0 * stride, {5, 1, 1}); + // record 1 stays all ones (an unfilled slot) + put(src.data + 2 * stride, {70000, 1, 1}); + put(src.data + 3 * stride, {3, 7, 9}); + put(count.data, {4}); + ComPtr<ID3D12Resource> dst = g.device_local(64 << 10); + vi::ClampCall c; + c.kind = vi::kind_mesh; + c.stride = stride; + c.records = max; + c.src = src.buffer.Get(); + c.count = count.buffer.Get(); + c.dst = dst.Get(); + c.budget_gpu = budget.gpu; + c.count_out = true; + EXPECT(vi::record_clamp(g.list.Get(), g.clamp, c), "clamp recorded"); + ID3D12CommandSignature* sig = g.signatures.get(g.device.Get(), vi::kind_mesh, stride); + EXPECT(sig != nullptr, "mesh host signature"); + if (!sig) return 1; + g.list->SetGraphicsRootSignature(root.Get()); + g.list->SetPipelineState(pso.Get()); + g.list->SetGraphicsRootUnorderedAccessView(0, seen.gpu); + const D3D12_VIEWPORT viewport{0, 0, 16, 16, 0, 1}; + const D3D12_RECT scissor{0, 0, 16, 16}; + g.list->RSSetViewports(1, &viewport); + g.list->RSSetScissorRects(1, &scissor); + g.list->ExecuteIndirect(sig, max, dst.Get(), 0, dst.Get(), u64{stride} * max); + g.run(); + const u32* s = seen.words(); + EXPECT(s[0] == 5 + 3, "mesh groups run %u, expected 8", s[0]); + EXPECT(s[1] == 4 && s[2] == 0 && s[3] == 0, "one-dimensional: largest group %u %u %u", s[1], s[2], s[3]); + EXPECT(budget.words()[0] == 8 * 128, "charged %u", budget.words()[0]); + EXPECT(budget.words()[1] == 5, "largest asked %u (the over-65,535 and all-ones records are not counted)", budget.words()[1]); + return 0; +} + +// An AMD card runs every group of an indirect dispatch of more than 65,535 in x (the title's tile lists). +int case_wide(Gpu& g, bool hardware) +{ + if (!hardware || !vi::is_amd(g.device.Get())) { + std::printf("SKIP: wide dispatches are run as asked only on an AMD card\n"); + return 77; + } + Mapped src = g.shared(64), budget = g.shared(256), hits = g.shared(256); + ComPtr<ID3D12Resource> dst = g.device_local(64 << 10); + ID3D12CommandSignature* sig = g.signatures.get(g.device.Get(), vi::kind_dispatch, 12); + for (u32 asked : {67440u, 115200u, 1u << 20, (1u << 20) + 1}) { + const u32 runs = asked > (1u << 20) ? 65535 : asked; + std::memset(hits.data, 0, 256); + std::memset(budget.data, 0, 256); + put(src.data, {asked, 1, 1}); + vi::ClampCall c; + c.kind = vi::kind_dispatch; + c.stride = 12; + c.records = 1; + c.src = src.buffer.Get(); + c.dst = dst.Get(); + c.budget_gpu = budget.gpu; + EXPECT(vi::record_clamp(g.list.Get(), g.clamp, c), "clamp recorded"); + g.bind_worker(hits.gpu); + g.list->ExecuteIndirect(sig, 1, dst.Get(), 0, nullptr, 0); + const D3D12_RESOURCE_BARRIER rest = vi::transition(dst.Get(), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + g.list->ResourceBarrier(1, &rest); + g.run(); + EXPECT(hits.words()[0] == runs && hits.words()[1] == runs - 1, "asked %u: ran %u, largest group %u", asked, hits.words()[0], + hits.words()[1]); + } + return 0; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 3) { + std::printf("usage: startup_gpu_indirect <warp|hardware> <case> [--mutate]\n"); + return 2; + } + const std::string adapter = argv[1], name = argv[2]; + const bool mutate = argc > 3 && std::string(argv[3]) == "--mutate"; + if (name == "layout") { + case_layout(); + std::printf("%s layout\n", failures ? "FAIL" : "PASS"); + return failures ? 1 : 0; + } + Gpu g; + const int opened = open_gpu(g, adapter == "hardware"); + if (opened) { + if (opened == 77) std::printf("SKIP: no %s adapter\n", adapter.c_str()); + return opened; + } + if (!make_clamp(g, mutate)) return 1; + int result = 0; + if (name == "capture") result = case_draw_capture(g, false) | case_draw_capture(g, true); + else if (name == "count") result = case_count(g); + else if (name == "window") result = case_window(g); + else if (name == "budget") result = case_budget(g); + else if (name == "lanes") result = case_lanes(g, true) | case_lanes(g, false); + else if (name == "restart") result = case_restart(g, true); + else if (name == "restart-nozero") result = case_restart(g, false); + else if (name == "dispatch69") result = case_dispatch69(g); + else if (name == "pool") result = case_pool(g); + else if (name == "mesh") result = case_mesh(g); + else if (name == "wide") result = case_wide(g, adapter == "hardware"); + else { + std::printf("unknown case %s\n", name.c_str()); + return 2; + } + if (result == 77) return 77; + if (result || failures) { + std::printf("FAIL %s %s%s (%d failures)\n", adapter.c_str(), name.c_str(), mutate ? " --mutate" : "", failures); + return 1; + } + std::printf("PASS %s %s%s\n", adapter.c_str(), name.c_str(), mutate ? " --mutate" : ""); + return 0; +} diff --git a/tests/startup_gpu_indirect.hlsl b/tests/startup_gpu_indirect.hlsl new file mode 100644 index 0000000000..a4c988680d --- /dev/null +++ b/tests/startup_gpu_indirect.hlsl @@ -0,0 +1,24 @@ +// tests/startup_gpu_indirect.cpp: the mesh program the clamped mesh records run (our own, never a title's). +// Each group counts itself and notes the largest group number in each dimension; it emits one degenerate +// triangle (no pixels; the pipeline has no pixel shader or targets). +#define RS "UAV(u0)" +RWByteAddressBuffer seen : register(u0); + +struct Vertex { + float4 position : SV_Position; +}; + +[RootSignature(RS)] +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void MeshMain(uint3 group : SV_GroupID, out vertices Vertex verts[3], out indices uint3 tris[1]) +{ + SetMeshOutputCounts(3, 1); + for (uint i = 0; i < 3; ++i) verts[i].position = float4(0, 0, 0, 1); + tris[0] = uint3(0, 1, 2); + uint was; + seen.InterlockedAdd(0, 1, was); + seen.InterlockedMax(4, group.x, was); + seen.InterlockedMax(8, group.y, was); + seen.InterlockedMax(12, group.z, was); +} diff --git a/tests/startup_gpu_list_states.inl b/tests/startup_gpu_list_states.inl new file mode 100644 index 0000000000..eb15bd6b0e --- /dev/null +++ b/tests/startup_gpu_list_states.inl @@ -0,0 +1,61 @@ +bool list_states_test() +{ + constexpr UINT count = 64; + constexpr auto common = D3D12_RESOURCE_STATE_COMMON; + constexpr auto dest = D3D12_RESOURCE_STATE_COPY_DEST; + constexpr auto source = D3D12_RESOURCE_STATE_COPY_SOURCE; + auto input = buffer(count * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + auto output = buffer(count * 4, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, dest); + if (!input || !output) return false; + UINT* words = nullptr; + if (FAILED(input->Map(0, nullptr, reinterpret_cast<void**>(&words)))) return false; + for (UINT i = 0; i < count; ++i) words[i] = 5381 + i; + input->Unmap(0, nullptr); + std::array<ComPtr<ID3D12Resource>, count> buffers; + for (auto& item : buffers) { + item = buffer(4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_NONE, common); + if (!item) return false; + } + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = d.Height = 32; + d.MipLevels = d.DepthOrArraySize = 2; + d.SampleDesc.Count = 1; + d.Format = DXGI_FORMAT_R32G8X24_TYPELESS; + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr<ID3D12Resource> depth; + if (FAILED(fx.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, common, nullptr, + IID_PPV_ARGS(&depth)))) return false; + x2w_gpu::ListStates states; + begin(); + auto* list = fx.list.Get(); + for (UINT i = 0; i < count; ++i) { + auto* item = buffers[i].Get(); + states.require(list, item, dest, dest); + list->CopyBufferRegion(item, 0, input.Get(), i * 4, 4); + } + states.require(list, depth.Get(), D3D12_RESOURCE_STATE_DEPTH_READ, D3D12_RESOURCE_STATE_DEPTH_WRITE); + states.require(list, depth.Get(), D3D12_RESOURCE_STATE_DEPTH_READ, D3D12_RESOURCE_STATE_DEPTH_WRITE); + const auto* split = states.find(depth.Get()); + if (!split || split->depth != D3D12_RESOURCE_STATE_DEPTH_READ || split->stencil != D3D12_RESOURCE_STATE_DEPTH_WRITE || + states.size() != count + 1) return false; + for (const auto& item : buffers) if (states.state(item.Get()) != dest) return false; + states.close(list); + if (states.size() || states.find(depth.Get())) return false; + end_and_wait(); + begin(); + for (UINT i = count; i--;) { + auto* item = buffers[i].Get(); + states.require(list, item, source, source); + list->CopyBufferRegion(output.Get(), i * 4, item, 0, 4); + } + states.require(list, depth.Get(), D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_DEPTH_WRITE); + states.close(list); + end_and_wait(); + if (FAILED(fx.device->GetDeviceRemovedReason()) || FAILED(output->Map(0, nullptr, reinterpret_cast<void**>(&words)))) return false; + bool good = true; + for (UINT i = 0; i < count; ++i) good &= words[i] == 5381 + i; + output->Unmap(0, nullptr); + return good; +} diff --git a/tests/startup_gpu_memory.hlsl b/tests/startup_gpu_memory.hlsl new file mode 100644 index 0000000000..f6a7dddebe --- /dev/null +++ b/tests/startup_gpu_memory.hlsl @@ -0,0 +1,17 @@ +#define ROOT "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED),RootConstants(num32BitConstants=2,b0),SRV(t254,space=1),UAV(u253,space=1),UAV(u0)" +cbuffer Params : register(b0) { uint heapBase; uint page; }; +ByteAddressBuffer directory : register(t254, space1); +RWByteAddressBuffer faults : register(u253, space1); +RWByteAddressBuffer output : register(u0); +[RootSignature(ROOT)] +[numthreads(1,1,1)] +void MemoryMain(uint3 dt : SV_DispatchThreadID) +{ + uint p = page + dt.x; + uint2 e = directory.Load2(8 * p); + uint copy = e.x & 0x7fffffff; + if (!copy) faults.Store((1 + p % 4095) * 4, p); + RWByteAddressBuffer window = ResourceDescriptorHeap[NonUniformResourceIndex(heapBase + copy)]; + output.Store(dt.x * 4, window.Load(e.y + 16)); + output.Store((dt.x + 2) * 4, e.x); +} diff --git a/tests/startup_gpu_memory_store.hlsl b/tests/startup_gpu_memory_store.hlsl new file mode 100644 index 0000000000..53bc134ec6 --- /dev/null +++ b/tests/startup_gpu_memory_store.hlsl @@ -0,0 +1,24 @@ +#define ROOT "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED),RootConstants(num32BitConstants=3,b0),SRV(t254,space=1),UAV(u253,space=1),UAV(u0),SRV(t0)" +cbuffer Params : register(b0) { uint base; uint page; uint value; }; +ByteAddressBuffer directory : register(t254, space1); +RWByteAddressBuffer faults : register(u253, space1); +RWByteAddressBuffer result : register(u0); +ByteAddressBuffer ordinary : register(t0); +[RootSignature(ROOT)] +[numthreads(1,1,1)] +void StoreMain() { + uint2 e = directory.Load2(page*8); + uint number = e.x & 0x7fffffff; + if (!number) faults.Store((1+page%4095)*4,page); + RWByteAddressBuffer readWindow = ResourceDescriptorHeap[NonUniformResourceIndex(base + number)]; + if (value == 0x1234eeee) { + result.Store2(0, uint2(readWindow.Load(e.y + 16), ordinary.Load(0))); + return; + } + result.Store2(0,readWindow.Load2(e.y+16)); + if (value) { + uint writable = (int(e.x)<0) ? 0 : number; + RWByteAddressBuffer writeWindow = ResourceDescriptorHeap[NonUniformResourceIndex(base+writable)]; + writeWindow.Store(e.y+16,value); + } +} diff --git a/tests/startup_gpu_memory_store.inl b/tests/startup_gpu_memory_store.inl new file mode 100644 index 0000000000..2cc54916ca --- /dev/null +++ b/tests/startup_gpu_memory_store.inl @@ -0,0 +1,131 @@ +void store_fixture(HostHeap& heap) +{ + using namespace x2w_vmemory; + Arenas arenas; + Recording memory; + const UINT page = 65552; + CHECK(packed_bytes(0x0000000381000006ull) == 256); + CHECK(!packed_bytes(0x0000000381000007ull)); + CHECK(arenas.create(fx.device.Get()) && memory.create(fx.device.Get())); + if (failures) return; + Place p; + CHECK(arenas.place(page,fx.window.Get(),window_offset,p)); + memory.base = 72; + heap.null_raw_uav_at(memory.base); + ComPtr<ID3D12RootSignature> root; + CHECK(SUCCEEDED(fx.device->CreateRootSignature(0,startup_gpu_memory_store_cs,sizeof(startup_gpu_memory_store_cs),IID_PPV_ARGS(&root)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.Get(); + pd.CS = {startup_gpu_memory_store_cs,sizeof(startup_gpu_memory_store_cs)}; + ComPtr<ID3D12PipelineState> pso; + CHECK(SUCCEEDED(fx.device->CreateComputePipelineState(&pd,IID_PPV_ARGS(&pso)))); + if (failures) return; + auto updates = buffer(16,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_FLAG_NONE,D3D12_RESOURCE_STATE_GENERIC_READ); + UINT* mapped = nullptr; + CHECK(updates && SUCCEEDED(updates->Map(0,nullptr,reinterpret_cast<void**>(&mapped)))); + if (!mapped) return; + mapped[0] = 0x81000006; mapped[1] = 3; mapped[2] = 0x12345678; + updates->Unmap(0,nullptr); + std::unordered_map<ID3D12Resource*,D3D12_RESOURCE_STATES> states; + states[fx.result.Get()] = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + const auto state = [&](auto* r,D3D12_RESOURCE_STATES next) { + auto& before = states[r]; + if (before == next) return; + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Transition = {r,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,before,next}; + fx.list->ResourceBarrier(1,&barrier); + before = next; + }; + const auto store = [&](UINT which,UINT value,UINT sample,UINT64 ordinary = 0) { + memory.ready(fx.list.Get(),state); + state(fx.result.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + auto* h = heap.heap(); + fx.list->SetDescriptorHeaps(1,&h); + fx.list->SetPipelineState(pso.Get()); + fx.list->SetComputeRootSignature(root.Get()); + const UINT params[]{memory.base,which,value}; + fx.list->SetComputeRoot32BitConstants(0,3,params,0); + fx.list->SetComputeRootShaderResourceView(1,memory.directory->GetGPUVirtualAddress()); + fx.list->SetComputeRootUnorderedAccessView(2,memory.faults->GetGPUVirtualAddress()); + fx.list->SetComputeRootUnorderedAccessView(3,fx.result->GetGPUVirtualAddress()); + fx.list->SetComputeRootShaderResourceView(4, ordinary ? ordinary : memory.zeros->GetGPUVirtualAddress()); + fx.list->Dispatch(1,1,1); + state(fx.result.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE); + fx.list->CopyBufferRegion(fx.readback.Get(),sample*8,fx.result.Get(),0,8); + }; + const UINT slot = arenas.packed_slot(UINT64{page} << 16); + const auto packed = [&](UINT frame) { + arenas.run(fx.list.Get(),p,window_offset,slot*16,256,UINT32_MAX,frame,state); + arenas.merge(fx.list.Get(),p,0,256,slot+2,state); + }; + begin(); + state(fx.window.Get(),D3D12_RESOURCE_STATE_COPY_DEST); + fx.list->CopyBufferRegion(fx.window.Get(),window_offset,updates.Get(),0,8); + arenas.merge(fx.list.Get(),p,0,page_bytes,0,state); + const auto view = [&](UINT i,auto* w,UINT64 size) { heap.raw_uav_at(i,w,0,size); }; + MapError error{}; + CHECK(!memory.map_to(fx.list.Get(),0,p.arena->bytes.Get(),0,true,view,state,false,&error) && error == MapError::page); + CHECK(!memory.map_to(fx.list.Get(),page,p.arena->bytes.Get(),1,true,view,state,false,&error) && error == MapError::view); + { + Recording saturated; + saturated.windows.assign(slots-1, fx.window); + CHECK(!saturated.map_to(fx.list.Get(),page,p.arena->bytes.Get(),0,true,view,state,false,&error) && + error == MapError::slots); + saturated.windows.assign(1, p.arena->bytes); + saturated.updates = entries; + CHECK(!saturated.map_to(fx.list.Get(),page,p.arena->bytes.Get(),0,true,view,state,false,&error) && + error == MapError::updates); + } + CHECK(memory.map_to(fx.list.Get(),page,p.arena->bytes.Get(),p.offset,true,view,state,true)); + CHECK(memory.map_to(fx.list.Get(),page+1,p.arena->bytes.Get(),p.offset,false,view,state,true)); + packed(100); + store(page,0xfeed0123,0); + state(fx.window.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE); + fx.list->CopyBufferRegion(fx.readback.Get(),48,fx.window.Get(),window_offset+16,4); + state(fx.window.Get(),D3D12_RESOURCE_STATE_COPY_DEST); + fx.list->CopyBufferRegion(fx.window.Get(),window_offset+20,updates.Get(),8,4); + arenas.merge(fx.list.Get(),p,0,page_bytes,0,state); + packed(101); + store(page+1,0xbeefaaaa,1); // read succeeds; a store through a protected mapping goes to the null UAV + store(page,0,2); + packed(110); // the same packed bytes streamed again after eight frames + store(page,0,3); + store(page,0xabcdef01,4); + arenas.publish(fx.list.Get(),{p,16,4},state,memory.zeros.Get()); + state(fx.window.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE); + fx.list->CopyBufferRegion(fx.readback.Get(),56,fx.window.Get(),window_offset+12,12); + CHECK(memory.map_to(fx.list.Get(),page+2,fx.window.Get(),window_offset,false,view,state)); + const std::vector<ID3D12Resource*> shared{fx.window.Get()}; + const auto allow = [&](const std::vector<ID3D12Resource*>& writers) { + return memory.allow_ordinary_reads(fx.list.Get(),shared,writers,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,view,state); + }; + CHECK(!allow(shared)); + memory.writable_mode = true; + CHECK(!allow({})); + memory.writable_mode = false; + CHECK(allow({})); + const auto ordinary = fx.window->GetGPUVirtualAddress()+window_offset+16; + store(page+2,0x33333333,9); + store(page+2,0x1234eeee,10,ordinary); + memory.restore_read_aliases(fx.list.Get(),state); + state(fx.window.Get(),D3D12_RESOURCE_STATE_COPY_DEST); + fx.list->CopyBufferRegion(fx.window.Get(),window_offset+16,updates.Get(),8,4); + const UINT stable = memory.updates; + CHECK(allow({}) && memory.updates == stable); + store(page+2,0x1234eeee,11,ordinary); + memory.restore_read_aliases(fx.list.Get(),state); + store(page+2,0,12); + end_and_wait(); + CHECK(SUCCEEDED(fx.readback->Map(0,nullptr,reinterpret_cast<void**>(&mapped)))); + if (!mapped) return; + CHECK(mapped[0]==pattern(4) && mapped[1]==pattern(5)); + CHECK(mapped[2]==0xfeed0123 && mapped[3]==0x12345678); + CHECK(mapped[4]==0xfeed0123 && mapped[5]==0x12345678); + CHECK(mapped[6]==pattern(4) && mapped[7]==0x12345678); + CHECK(mapped[12]==pattern(4)); + CHECK(mapped[14]==pattern(3) && mapped[15]==0xabcdef01 && mapped[16]==0x12345678); + CHECK(mapped[20]==0xabcdef01 && mapped[21]==0xabcdef01); + CHECK(mapped[22]==0x12345678 && mapped[23]==0x12345678); + CHECK(mapped[24]==0x12345678 && mapped[25]==0x12345678); + fx.readback->Unmap(0,nullptr); +} diff --git a/tests/startup_gpu_pipeline.cpp b/tests/startup_gpu_pipeline.cpp new file mode 100644 index 0000000000..93488bca22 --- /dev/null +++ b/tests/startup_gpu_pipeline.cpp @@ -0,0 +1,728 @@ +// startup_gpu_pipeline <warp|hardware> <root|compute|graphics|mesh> [--mutate no-heap-flags] [--debug] +// +// The host root signatures and pipelines of src/startup_stubs/gpu_pipeline_build.h (WP2, adapted from the upstream +// HostPipeline::new) from synthetic HostShader records over fixture HLSL using the shader binding ABI +// (tests/startup_gpu_pipeline.hlsl, dxc SM 6.6): +// - root: the serialized root of a compute record (8 dwords of user data, root CBV b2, root SRVs t5 +// and t255, root UAV u7, one static sampler) and of a vertex+pixel record has the expected parameter +// list: b0 space0 constants sized user_data_dwords, a root CBV b2 space1, a one-view volatile SRV +// table t5 space1, a root SRV t255 space1 (the strides slot stays a root descriptor), a one-view UAV +// table u7 space1, the static sampler s0 space0, per-stage visibility, and the flags +// CBV_SRV_UAV/SAMPLER_HEAP_DIRECTLY_INDEXED (+ ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT for graphics). +// The anisotropic point-mip filter falls back to linear mip without OPTIONS19 support. +// - compute: the compute pipeline is made and a dispatch through the returned parameter indices +// reads user data, the root CBV, the root SRV table, the root SRV descriptor, a texture and a +// sampler from the heaps and the static sampler, and writes a heap UAV and the root UAV table. +// - graphics: a console stream (input layout, blend on an integer target, no depth) is parsed and +// made into a graphics pipeline; a draw writes the pixel stage's user data, root CBV and a heap +// view to an R32G32B32A32_UINT target. The vertex stage's own user data scales the positions. +// - mesh: the same with a console mesh stream (MS = 24): a mesh pipeline, DispatchMesh(1, 1, 1). +// --mutate no-heap-flags leaves the DIRECTLY_INDEXED flags off: the root check or the pipeline +// creation must fail (negative control, WILL_FAIL). +// Exit 0 pass, 77 capability skip (no adapter; no shader model 6.6 / resource binding tier 3; no +// mesh shaders), other values fail. +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <cstdio> +#include <cstring> +#include <string> +#include <vector> + +#include "startup_stubs/gpu_pipeline_pending.h" +#include "startup_gpu_pipeline_cs.h" +#include "startup_gpu_pipeline_ms.h" +#include "startup_gpu_pipeline_ps.h" +#include "startup_gpu_pipeline_vs.h" + +using Microsoft::WRL::ComPtr; +using namespace x2w_gpu; + +namespace { + +bool mutate = false; +bool reference_miss = false; +unsigned reference_attempts = 0; +int failures = 0; + +#define EXPECT(cond) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL line %d: %s\n", __LINE__, #cond); \ + ++failures; \ + } \ + } while (0) + +VpMakeOptions options() +{ + VpMakeOptions o; + o.root.heap_indexing = !mutate; + if (reference_miss) o.load_compute = [](ID3D12Device*, const std::vector<unsigned char>& blob, + const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc, ID3D12PipelineState** out) -> HRESULT { + ++reference_attempts; + EXPECT(!blob.empty() && desc.pRootSignature && desc.CS.BytecodeLength); + *out = nullptr; + return E_INVALIDARG; + }; + return o; +} + +const std::uint8_t cs_cbvs[] = {2}; +const std::uint8_t cs_srvs[] = {5, 255}; +const std::uint8_t cs_uavs[] = {7}; +const std::uint8_t ps_cbvs[] = {2}; +// Point filtering, clamp: D3D12_FILTER_MIN_MAG_MIP_POINT, ADDRESS_MODE_CLAMP, NEVER, opaque black. +const VpStaticSampler point_clamp{0, {3, 3, 3}, 0.f, 1, 1, 1, 0.f, 3.402823466e+38f}; + +VpShaderView compute_record() +{ + VpShaderView v; + v.stage = vp_stage_compute; + v.dxil = startup_gpu_pipeline_cs; + v.dxil_size = sizeof(startup_gpu_pipeline_cs); + const std::uint32_t used[] = {0, 1, 2, 4, 5}; // dwords the shader reads (ud[0].xyz, ud[1].xy) + v.user_data_dwords = vp_user_data_dwords(used, 5); + v.samplers = &point_clamp; + v.sampler_count = 1; + v.root_cbvs = cs_cbvs; + v.root_cbv_count = 1; + v.root_srvs = cs_srvs; + v.root_srv_count = 2; + v.root_uavs = cs_uavs; + v.root_uav_count = 1; + return v; +} + +VpShaderView stage_record(std::uint32_t stage, const void* dxil, std::size_t size, std::uint32_t dwords, bool cbv) +{ + VpShaderView v; + v.stage = stage; + v.dxil = dxil; + v.dxil_size = size; + v.user_data_dwords = dwords; + if (cbv) { + v.root_cbvs = ps_cbvs; + v.root_cbv_count = 1; + } + return v; +} + +VpShaderView pixel_record() { return stage_record(vp_stage_pixel, startup_gpu_pipeline_ps, sizeof(startup_gpu_pipeline_ps), 8, true); } + +bool open_device(const char* backend, ComPtr<ID3D12Device>& device, bool debug) +{ + ComPtr<IDXGIFactory6> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return false; + if (debug) { + ComPtr<ID3D12Debug> layer; + if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&layer)))) layer->EnableDebugLayer(); + } + ComPtr<IDXGIAdapter> adapter; + if (std::strcmp(backend, "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr<IDXGIAdapter1> candidate; + if (FAILED(factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)))) return false; + DXGI_ADAPTER_DESC1 desc{}; + candidate->GetDesc1(&desc); + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) { + std::printf("adapter=%ls\n", desc.Description); + return true; + } + } + } + if (std::strcmp(backend, "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) return false; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) return false; + std::printf("adapter=WARP\n"); + return true; +} + +// SM 6.6 dynamic resources need shader model 6.6 and resource binding tier 3. +bool heap_indexing_supported(ID3D12Device* device) +{ + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS o{}; + return SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model))) && + model.HighestShaderModel >= D3D_SHADER_MODEL_6_6 && + SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &o, sizeof(o))) && + o.ResourceBindingTier >= D3D12_RESOURCE_BINDING_TIER_3; +} + +// ---- root ---- + +int check_root(ID3D12Device* device) +{ + const VpShaderView cs = compute_record(); + EXPECT(cs.user_data_dwords == 8); + const VpRootLayout layout = vp_root_layout(&cs, 1, true, options().root); + std::vector<unsigned char> blob; + std::string why; + if (FAILED(vp_serialize_root(layout, blob, why))) { + std::printf("FAIL serialize: %s\n", why.c_str()); + return 1; + } + ComPtr<ID3D12RootSignature> root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root)))); + ComPtr<ID3D12VersionedRootSignatureDeserializer> reader; + if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(blob.data(), blob.size(), IID_PPV_ARGS(&reader)))) return 1; + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc = nullptr; + if (FAILED(reader->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &desc))) return 1; + const D3D12_ROOT_SIGNATURE_DESC1& d = desc->Desc_1_1; + EXPECT(d.Flags == (D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED)); + EXPECT(d.NumParameters == 5); + if (d.NumParameters == 5) { + const auto& p = d.pParameters; + EXPECT(p[0].ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS && p[0].Constants.ShaderRegister == 0 && + p[0].Constants.RegisterSpace == 0 && p[0].Constants.Num32BitValues == 8 && p[0].ShaderVisibility == D3D12_SHADER_VISIBILITY_ALL); + EXPECT(p[1].ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV && p[1].Descriptor.ShaderRegister == 2 && p[1].Descriptor.RegisterSpace == 1 && + p[1].Descriptor.Flags == D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE); + EXPECT(p[2].ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE && p[2].DescriptorTable.NumDescriptorRanges == 1); + if (p[2].DescriptorTable.NumDescriptorRanges == 1) { + const auto& r = p[2].DescriptorTable.pDescriptorRanges[0]; + EXPECT(r.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV && r.NumDescriptors == 1 && r.BaseShaderRegister == 5 && r.RegisterSpace == 1 && + r.Flags == (D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE) && + r.OffsetInDescriptorsFromTableStart == 0); + } + EXPECT(p[3].ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV && p[3].Descriptor.ShaderRegister == 255 && p[3].Descriptor.RegisterSpace == 1); + EXPECT(p[4].ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE && p[4].DescriptorTable.NumDescriptorRanges == 1); + if (p[4].DescriptorTable.NumDescriptorRanges == 1) { + const auto& r = p[4].DescriptorTable.pDescriptorRanges[0]; + EXPECT(r.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_UAV && r.BaseShaderRegister == 7 && r.RegisterSpace == 1); + } + } + EXPECT(d.NumStaticSamplers == 1); + if (d.NumStaticSamplers == 1) { + const auto& s = d.pStaticSamplers[0]; + EXPECT(s.ShaderRegister == 0 && s.RegisterSpace == 0 && s.AddressU == D3D12_TEXTURE_ADDRESS_MODE_CLAMP && + s.ComparisonFunc == D3D12_COMPARISON_FUNC_NEVER && s.ShaderVisibility == D3D12_SHADER_VISIBILITY_ALL); + } + // The binding record the bind package reads. + EXPECT(layout.stages.size() == 1); + if (layout.stages.size() == 1) { + const VpBoundStage& b = layout.stages[0]; + EXPECT(b.has_user_data && b.user_data_param == 0 && b.user_data_dwords == 8); + EXPECT(b.root_cbvs.size() == 1 && b.root_cbvs[0].slot == 2 && b.root_cbvs[0].param == 1 && !b.root_cbvs[0].table); + EXPECT(b.root_srvs.size() == 2 && b.root_srvs[0].param == 2 && b.root_srvs[0].table && b.root_srvs[1].slot == 255 && + b.root_srvs[1].param == 3 && !b.root_srvs[1].table); + EXPECT(b.root_uavs.size() == 1 && b.root_uavs[0].param == 4 && b.root_uavs[0].table); + } + // X2W_SHADERCFG_ROOT_SRV_DIRECT=1: every root view a root descriptor. + VpRootOptions direct = options().root; + direct.bounded_root_views = false; + const VpRootLayout plain = vp_root_layout(&cs, 1, true, direct); + EXPECT(plain.params.size() == 5 && plain.params[2].ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV && + plain.params[4].ParameterType == D3D12_ROOT_PARAMETER_TYPE_UAV && plain.ranges.empty()); + + // Vertex + pixel: per-stage visibility, the input-layout flag, ids in order. + const VpShaderView g[2] = {stage_record(vp_stage_vertex, startup_gpu_pipeline_vs, sizeof(startup_gpu_pipeline_vs), 8, false), + pixel_record()}; + const VpRootLayout gl = vp_root_layout(g, 2, false, options().root); + EXPECT(gl.params.size() == 3); + if (gl.params.size() == 3) { + EXPECT(gl.params[0].ShaderVisibility == D3D12_SHADER_VISIBILITY_VERTEX && gl.params[0].ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS); + EXPECT(gl.params[1].ShaderVisibility == D3D12_SHADER_VISIBILITY_PIXEL && gl.params[1].ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS); + EXPECT(gl.params[2].ShaderVisibility == D3D12_SHADER_VISIBILITY_PIXEL && gl.params[2].ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV); + } + EXPECT(gl.flags & D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT); + std::vector<unsigned char> gblob; + EXPECT(SUCCEEDED(vp_serialize_root(gl, gblob, why))); + ComPtr<ID3D12RootSignature> groot; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, gblob.data(), gblob.size(), IID_PPV_ARGS(&groot)))); + // No user data: no constants parameter. A mesh stage sees its own. + VpShaderView ms = stage_record(vp_stage_mesh, startup_gpu_pipeline_ms, sizeof(startup_gpu_pipeline_ms), 0, false); + const VpRootLayout ml = vp_root_layout(&ms, 1, false, options().root); + EXPECT(ml.params.empty() && !ml.stages[0].has_user_data); + ms.user_data_dwords = 4; + EXPECT(vp_root_layout(&ms, 1, false, options().root).params[0].ShaderVisibility == D3D12_SHADER_VISIBILITY_MESH); + + // Anisotropic point-mip (0x54) keeps its filter only with OPTIONS19 support; comparison and + // reduction bits stay. + EXPECT(vp_filter_for_host(0x54, false) == 0x55 && vp_filter_for_host(0x54, true) == 0x54); + EXPECT(vp_filter_for_host(0xd4, false) == 0xd5 && vp_filter_for_host(0x55, false) == 0x55 && vp_filter_for_host(0x15, false) == 0x15); + EXPECT(vp_user_data_dwords(nullptr, 0) == 0); + const std::uint32_t nine[] = {8}; + EXPECT(vp_user_data_dwords(nine, 1) == 12); + return failures ? 1 : 0; +} + +// ---- GPU helpers ---- + +struct Gpu { + ComPtr<ID3D12Device> device; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + UINT64 value = 0; + + bool open(D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT) + { + D3D12_COMMAND_QUEUE_DESC q{}; + q.Type = type; + return SUCCEEDED(device->CreateCommandQueue(&q, IID_PPV_ARGS(&queue))) && + SUCCEEDED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator))) && + SUCCEEDED(device->CreateCommandList(0, type, 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); + queue->Signal(fence.Get(), ++value); + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + fence->SetEventOnCompletion(value, event); + WaitForSingleObject(event, 10000); + CloseHandle(event); + return fence->GetCompletedValue() >= value && SUCCEEDED(device->GetDeviceRemovedReason()); + } + + ComPtr<ID3D12Resource> buffer(D3D12_HEAP_TYPE heap, UINT64 bytes, D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) + { + D3D12_HEAP_PROPERTIES hp{heap}; + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = bytes; + d.Height = d.DepthOrArraySize = d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + ComPtr<ID3D12Resource> r; + device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, IID_PPV_ARGS(&r)); + return r; + } + + ComPtr<ID3D12Resource> texture(DXGI_FORMAT format, UINT size, D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) + { + D3D12_HEAP_PROPERTIES hp{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = d.Height = size; + d.DepthOrArraySize = d.MipLevels = 1; + d.Format = format; + d.SampleDesc.Count = 1; + d.Flags = flags; + ComPtr<ID3D12Resource> r; + device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, IID_PPV_ARGS(&r)); + return r; + } +}; + +void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* r, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) +{ + D3D12_RESOURCE_BARRIER b{}; + b.Transition = {r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + list->ResourceBarrier(1, &b); +} + +void write(ID3D12Resource* upload, std::size_t at, const void* data, std::size_t bytes) +{ + void* p = nullptr; + upload->Map(0, nullptr, &p); + std::memcpy(static_cast<char*>(p) + at, data, bytes); + upload->Unmap(0, nullptr); +} + +void put32(ID3D12Resource* upload, std::size_t at, std::uint32_t v) { write(upload, at, &v, 4); } + +void raw_srv(ID3D12Device* device, ID3D12Resource* r, UINT64 first, D3D12_CPU_DESCRIPTOR_HANDLE at) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Buffer.FirstElement = first; + v.Buffer.NumElements = 64; + v.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(r, &v, at); +} + +void raw_uav(ID3D12Device* device, ID3D12Resource* r, UINT64 first, D3D12_CPU_DESCRIPTOR_HANDLE at) +{ + D3D12_UNORDERED_ACCESS_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + v.Buffer.FirstElement = first; + v.Buffer.NumElements = 64; + v.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(r, nullptr, &v, at); +} + +struct Heaps { + ComPtr<ID3D12DescriptorHeap> views, samplers; + UINT view_step = 0; + D3D12_CPU_DESCRIPTOR_HANDLE cpu(UINT i) const + { + auto h = views->GetCPUDescriptorHandleForHeapStart(); + h.ptr += static_cast<SIZE_T>(i) * view_step; + return h; + } + D3D12_GPU_DESCRIPTOR_HANDLE gpu(UINT i) const + { + auto h = views->GetGPUDescriptorHandleForHeapStart(); + h.ptr += static_cast<UINT64>(i) * view_step; + return h; + } + bool open(ID3D12Device* device) + { + D3D12_DESCRIPTOR_HEAP_DESC v{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + D3D12_DESCRIPTOR_HEAP_DESC s{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + view_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (FAILED(device->CreateDescriptorHeap(&v, IID_PPV_ARGS(&views))) || FAILED(device->CreateDescriptorHeap(&s, IID_PPV_ARGS(&samplers)))) + return false; + // Heap sampler 1: point, clamp. + D3D12_SAMPLER_DESC sd{}; + sd.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + sd.AddressU = sd.AddressV = sd.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sd.MaxLOD = D3D12_FLOAT32_MAX; + auto h = samplers->GetCPUDescriptorHandleForHeapStart(); + h.ptr += device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + device->CreateSampler(&sd, h); + return true; + } +}; + +// Root constants: a stage's user data, console byte offsets in the view and sampler heaps. +void constants(ID3D12GraphicsCommandList* list, bool compute, const VpBoundStage& stage, const std::uint32_t (&ud)[8]) +{ + if (!stage.has_user_data) return; + if (compute) list->SetComputeRoot32BitConstants(stage.user_data_param, stage.user_data_dwords, ud, 0); + else list->SetGraphicsRoot32BitConstants(stage.user_data_param, stage.user_data_dwords, ud, 0); +} + +constexpr std::uint32_t one_float = 0x3f800000u; + +// ---- compute ---- + +int check_compute(Gpu& gpu) +{ + ID3D12Device* device = gpu.device.Get(); + const VpShaderView cs = compute_record(); + VpHostPipeline host; + std::string why; + if (!vp_make_host_pipeline(device, vp_device_caps(device), &cs, 1, nullptr, options(), host, why)) { + std::printf("FAIL compute pipeline: %s\n", why.c_str()); + return 1; + } + EXPECT(host.compute && !host.mesh && host.stages.size() == 1); + Heaps heaps; + if (!heaps.open(device)) return 1; + auto ro = gpu.buffer(D3D12_HEAP_TYPE_UPLOAD, 0x10000, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + auto rw = gpu.buffer(D3D12_HEAP_TYPE_DEFAULT, 0x1000, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + auto back = gpu.buffer(D3D12_HEAP_TYPE_READBACK, 0x1000, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + auto tex = gpu.texture(DXGI_FORMAT_R32_FLOAT, 1, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + if (!ro || !rw || !back || !tex) return 1; + put32(ro.Get(), 0x000, 0x5a5a0005u); // root SRV table t5 + put32(ro.Get(), 0x200, 0x51515151u); // root SRV descriptor t255 + put32(ro.Get(), 0x1000, 0xcb000002u); // root CBV b2 + const float texel = 0.75f; + write(ro.Get(), 0x2000, &texel, 4); // texture upload (256-aligned row) + raw_uav(device, rw.Get(), 0, heaps.cpu(3)); // heap output view + raw_srv(device, ro.Get(), 0, heaps.cpu(5)); // root SRV table's view + raw_uav(device, rw.Get(), 0x400 / 4, heaps.cpu(7)); // root UAV table's view + D3D12_SHADER_RESOURCE_VIEW_DESC tv{}; + tv.Format = DXGI_FORMAT_R32_FLOAT; + tv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + tv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + tv.Texture2D.MipLevels = 1; + device->CreateShaderResourceView(tex.Get(), &tv, heaps.cpu(1)); + + auto* list = gpu.list.Get(); + D3D12_TEXTURE_COPY_LOCATION dst{tex.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + dst.SubresourceIndex = 0; + D3D12_TEXTURE_COPY_LOCATION src{ro.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + src.PlacedFootprint = {0x2000, {DXGI_FORMAT_R32_FLOAT, 1, 1, 1, 256}}; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + barrier(list, tex.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + ID3D12DescriptorHeap* both[] = {heaps.views.Get(), heaps.samplers.Get()}; + list->SetDescriptorHeaps(2, both); // before the root: its heaps are directly indexed + list->SetComputeRootSignature(host.root); + list->SetPipelineState(host.pso); + const VpBoundStage& stage = host.stages[0]; + const std::uint32_t ud[8] = {3 * 32, 1 * 32, 1 * 16, 0, 0x1234abcdu, 0x7777u, 0, 0}; + constants(list, true, stage, ud); + for (const auto& v : stage.root_cbvs) list->SetComputeRootConstantBufferView(v.param, ro->GetGPUVirtualAddress() + 0x1000); + for (const auto& v : stage.root_srvs) { + if (v.table) list->SetComputeRootDescriptorTable(v.param, heaps.gpu(5)); + else list->SetComputeRootShaderResourceView(v.param, ro->GetGPUVirtualAddress() + 0x200); + } + for (const auto& v : stage.root_uavs) { + if (v.table) list->SetComputeRootDescriptorTable(v.param, heaps.gpu(7)); + else list->SetComputeRootUnorderedAccessView(v.param, rw->GetGPUVirtualAddress() + 0x400); + } + list->Dispatch(1, 1, 1); + barrier(list, rw.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(back.Get(), 0, rw.Get(), 0, 0x1000); + if (!gpu.run()) { + std::printf("FAIL dispatch did not complete (device removed 0x%08lx)\n", static_cast<unsigned long>(gpu.device->GetDeviceRemovedReason())); + return 1; + } + std::uint32_t* out = nullptr; + back->Map(0, nullptr, reinterpret_cast<void**>(&out)); + float a = 0, b = 0; + std::memcpy(&a, out + 4, 4); + std::memcpy(&b, out + 5, 4); + std::printf("compute out %08x %08x %08x %08x %g %g root uav %08x\n", out[0], out[1], out[2], out[3], a, b, out[0x100]); + EXPECT(out[0] == 0x1234abcdu); // user data + EXPECT(out[1] == 0xcb000002u); // root CBV b2 space1 + EXPECT(out[2] == 0x5a5a0005u); // root SRV t5 space1 (one-view table) + EXPECT(out[3] == 0x51515151u); // root SRV t255 space1 (descriptor) + EXPECT(a == 0.75f && b == 0.75f); // static sampler s0 and heap sampler + EXPECT(out[0x100] == 0x7777u); // root UAV u7 space1 (one-view table) + back->Unmap(0, nullptr); + + // Lazy make: two title pipelines of the same stage share one host pipeline; a stage without a + // record is refused at first use. + VpPipelineCache cache; + VpPending pa, pb, missing; + pa.add(cs); + pb.add(cs); + VpShaderView none = cs; + none.dxil = nullptr; + none.dxil_size = 0; + missing.add(none); + const VpDeviceCaps caps = vp_device_caps(device); + const VpHostPipeline* ha = vp_ready(pa, device, caps, cache, options()); + const VpHostPipeline* hb = vp_ready(pb, device, caps, cache, options()); + EXPECT(ha && ha == hb && vp_ready(pa, device, caps, cache, options()) == ha); + EXPECT(cache.made_count == 1 && cache.shared_count == 1); + // The same DXIL from another record is a pipeline of its own: the bind path reads the record's mapping. + static const int other_record = 0; + VpShaderView other = cs; + other.tag = &other_record; + VpPending pc; + pc.add(other); + const VpHostPipeline* hc = vp_ready(pc, device, caps, cache, options()); + EXPECT(hc && hc != ha && hc->stages[0].tag == &other_record && ha->stages[0].tag == nullptr && cache.made_count == 2); + EXPECT(!vp_ready(missing, device, caps, cache, options()) && missing.why == "a stage has no translated record in the export"); + return failures ? 1 : 0; +} + +// ---- graphics and mesh ---- + +// A console stream builder: subobjects at 8-byte steps, the console's numbering. +struct StreamBytes { + std::vector<unsigned char> bytes; + template <class T> + void add(std::uint32_t kind, const T& value, std::size_t data_at = 4) + { + const std::size_t size = vp_subobject(kind).size; + const std::size_t at = bytes.size(); + bytes.resize(at + size, 0); + std::memcpy(&bytes[at], &kind, 4); + std::memcpy(&bytes[at + data_at], &value, sizeof(T)); + } +}; + +int check_draw(Gpu& gpu, bool mesh, bool rectangles = false) +{ + ID3D12Device* device = gpu.device.Get(); + const VpDeviceCaps caps = vp_device_caps(device); + if (mesh && !caps.mesh_shaders) { + std::printf("no mesh shaders (tier or shader model 6.6): capability skip\n"); + return 77; + } + // The title's stream (console numbering: the mesh stage is 24). + D3D12_INPUT_ELEMENT_DESC position{"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}; + StreamBytes s; + s.add<void*>(0, nullptr, 8); + if (mesh) s.add(24, D3D12_SHADER_BYTECODE{startup_gpu_pipeline_ms, sizeof(startup_gpu_pipeline_ms)}, 8); + else s.add(1, D3D12_SHADER_BYTECODE{startup_gpu_pipeline_vs, sizeof(startup_gpu_pipeline_vs)}, 8); + s.add(2, D3D12_SHADER_BYTECODE{startup_gpu_pipeline_ps, sizeof(startup_gpu_pipeline_ps)}, 8); + D3D12_BLEND_DESC blend = VpGraphicsState().blend; + blend.RenderTarget[0].BlendEnable = TRUE; // on an integer target: host_blend turns it off + s.add(8, blend); + D3D12_RASTERIZER_DESC raster = VpGraphicsState().rasterizer; + raster.CullMode = D3D12_CULL_MODE_NONE; + s.add(10, raster); + D3D12_DEPTH_STENCIL_DESC depth{}; + s.add(11, depth); + if (!mesh) s.add(12, D3D12_INPUT_LAYOUT_DESC{&position, 1}, 8); + s.add(14, rectangles ? static_cast<std::uint32_t>(vp_topology_rectangles) + : static_cast<std::uint32_t>(D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE)); + D3D12_RT_FORMAT_ARRAY targets{}; + targets.NumRenderTargets = 1; + targets.RTFormats[0] = DXGI_FORMAT_R32G32B32A32_UINT; + s.add(15, targets); + s.add(16, static_cast<std::uint32_t>(DXGI_FORMAT_UNKNOWN)); + const VpStream stream = vp_parse_stream(s.bytes.data(), s.bytes.size(), VpFormatMap{}); + EXPECT(!stream.stopped && !stream.truncated && stream.shaders.size() == 2); + if (stream.shaders.size() != 2) return 1; + std::vector<VpShaderView> views; + for (const auto& sh : stream.shaders) { + if (sh.stage == vp_stage_pixel) views.push_back(pixel_record()); + else views.push_back(stage_record(sh.stage, sh.code, sh.size, 8, false)); + } + VpHostPipeline host; + std::string why; + if (!vp_make_host_pipeline(device, caps, views.data(), views.size(), &stream.graphics, options(), host, why)) { + std::printf("FAIL %s pipeline: %s\n", mesh ? "mesh" : "graphics", why.c_str()); + return 1; + } + EXPECT(host.mesh == mesh && !host.compute && host.stages.size() == 2); + EXPECT(host.rects == rectangles); + if (rectangles && caps.depth_bounds) { + auto depth_state = stream.graphics; + depth_state.depth_bounds = true; + depth_state.depth_format = DXGI_FORMAT_D32_FLOAT; + depth_state.depth.DepthEnable = TRUE; + depth_state.depth.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + VpHostPipeline bounded; + EXPECT(vp_make_host_pipeline(device, caps, views.data(), views.size(), &depth_state, options(), bounded, why)); + EXPECT(bounded.depth_bounds && bounded.rects); + } + EXPECT(mesh ? host.slots == 0 && host.inputs.empty() : host.slots == 1 && host.inputs.size() == 1); + // X2W_GPU_MESH=0 refuses mesh pipelines. + if (mesh) { + VpMakeOptions off = options(); + off.allow_mesh = false; + VpHostPipeline refused; + std::string reason; + EXPECT(!vp_make_host_pipeline(device, caps, views.data(), views.size(), &stream.graphics, off, refused, reason) && + reason == "mesh pipelines are off (X2W_GPU_MESH=0)"); + } + // Reject a graphics pipeline description with no state. + VpHostPipeline none; + std::string plain; + EXPECT(!vp_make_host_pipeline(device, caps, views.data(), views.size(), nullptr, options(), none, plain) && + plain == "graphics state not kept (plain description)"); + + Heaps heaps; + if (!heaps.open(device)) return 1; + auto ro = gpu.buffer(D3D12_HEAP_TYPE_UPLOAD, 0x10000, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + auto back = gpu.buffer(D3D12_HEAP_TYPE_READBACK, 0x1000, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + auto target = gpu.texture(DXGI_FORMAT_R32G32B32A32_UINT, 4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_RENDER_TARGET); + if (!ro || !back || !target) return 1; + put32(ro.Get(), 0x000, 0xbeef0002u); // heap view read by the pixel stage + put32(ro.Get(), 0x1000, 0xcb000002u); // root CBV b2 + // Rectangle lists supply three corners; the GS must generate the top-right corner. + const float edge = rectangles ? 1.0f : 3.0f; + const float tri[6] = {-1, -1, -1, edge, edge, -1}; + write(ro.Get(), 0x2000, tri, sizeof(tri)); + raw_srv(device, ro.Get(), 0, heaps.cpu(2)); + ComPtr<ID3D12DescriptorHeap> rtvs; + D3D12_DESCRIPTOR_HEAP_DESC rd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + if (FAILED(device->CreateDescriptorHeap(&rd, IID_PPV_ARGS(&rtvs)))) return 1; + const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(target.Get(), nullptr, rtv); + + auto* list = gpu.list.Get(); + const float clear[4] = {0, 0, 0, 0}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + ID3D12DescriptorHeap* both[] = {heaps.views.Get(), heaps.samplers.Get()}; + list->SetDescriptorHeaps(2, both); + list->SetGraphicsRootSignature(host.root); + list->SetPipelineState(host.pso); + const std::uint32_t first_ud[8] = {0, 0, 0, 0, 0, 0, one_float, 0}; // the vertex or mesh stage: scale 1.0 + const std::uint32_t pixel_ud[8] = {2 * 32, 0, 0, 0, 0x9999abcdu, 0, 0, 0}; + constants(list, false, host.stages[0], first_ud); + constants(list, false, host.stages[1], pixel_ud); + for (const auto& stage : host.stages) + for (const auto& v : stage.root_cbvs) list->SetGraphicsRootConstantBufferView(v.param, ro->GetGPUVirtualAddress() + 0x1000); + D3D12_VIEWPORT viewport{0, 0, 4, 4, 0, 1}; + D3D12_RECT scissor{0, 0, 4, 4}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + if (mesh) { + ComPtr<ID3D12GraphicsCommandList6> list6; + if (FAILED(gpu.list.As(&list6))) return 1; + list6->DispatchMesh(1, 1, 1); + } else { + const D3D12_VERTEX_BUFFER_VIEW vb{ro->GetGPUVirtualAddress() + 0x2000, sizeof(tri), 8}; + list->IASetVertexBuffers(0, 1, &vb); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + } + barrier(list, target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION src{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.SubresourceIndex = 0; + D3D12_TEXTURE_COPY_LOCATION dst{back.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_UINT, 4, 4, 1, 256}}; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + if (!gpu.run()) { + std::printf("FAIL draw did not complete (device removed 0x%08lx)\n", static_cast<unsigned long>(gpu.device->GetDeviceRemovedReason())); + return 1; + } + std::uint32_t* out = nullptr; + back->Map(0, nullptr, reinterpret_cast<void**>(&out)); + // Pixel (3, 3): row 3 at 3 * 256 bytes, texel 3 at 48. + const std::uint32_t* corner = out + (3 * 256 + 3 * 16) / 4; + if (rectangles) { + for (UINT y = 0; y < 4; ++y) + for (UINT x = 0; x < 4; ++x) + EXPECT(out[(y * 256 + x * 16) / 4] == 0x9999abcdu); + } + std::printf("%s pixel (0,0) %08x %08x %08x %08x (3,3) %08x %08x %08x %08x\n", mesh ? "mesh" : "graphics", out[0], out[1], out[2], + out[3], corner[0], corner[1], corner[2], corner[3]); + for (const std::uint32_t* p : std::initializer_list<const std::uint32_t*>{out, corner}) { + EXPECT(p[0] == 0x9999abcdu); // the pixel stage's user data + EXPECT(p[1] == 0xcb000002u); // root CBV b2 space1 (pixel visibility) + EXPECT(p[2] == 0xbeef0002u); // heap view at the user data's offset + EXPECT(p[3] == 0x600du); + } + back->Unmap(0, nullptr); + return failures ? 1 : 0; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 3) return 2; + bool debug = false; + for (int i = 3; i < argc; ++i) { + if (std::strcmp(argv[i], "--mutate") == 0 && i + 1 < argc && std::strcmp(argv[i + 1], "no-heap-flags") == 0) { + mutate = true; + ++i; + } else if (std::strcmp(argv[i], "--reference-miss") == 0) { + reference_miss = true; + } else if (std::strcmp(argv[i], "--debug") == 0) { + debug = true; + } else { + return 2; + } + } + const std::string mode = argv[2]; + Gpu gpu; + if (!open_device(argv[1], gpu.device, debug)) { + std::printf("no %s adapter: capability skip\n", argv[1]); + return 77; + } + if (!heap_indexing_supported(gpu.device.Get())) { + std::printf("no shader model 6.6 or resource binding tier 3: capability skip\n"); + return 77; + } + int result = 2; + if (mode == "root") result = check_root(gpu.device.Get()); + else if (!gpu.open()) result = 4; + else if (mode == "compute") result = check_compute(gpu); + else if (mode == "graphics") result = check_draw(gpu, false); + else if (mode == "rectangles") result = check_draw(gpu, false, true); + else if (mode == "mesh") result = check_draw(gpu, true); + // --debug: the debug layer's errors fail the run too. + ComPtr<ID3D12InfoQueue> queue; + if (debug && result == 0 && SUCCEEDED(gpu.device.As(&queue))) { + int errors = 0; + for (UINT64 i = 0, n = queue->GetNumStoredMessages(); i < n; ++i) { + SIZE_T bytes = 0; + queue->GetMessage(i, nullptr, &bytes); + std::vector<char> buffer(bytes); + auto* m = reinterpret_cast<D3D12_MESSAGE*>(buffer.data()); + if (FAILED(queue->GetMessage(i, m, &bytes))) continue; + if (m->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { + std::printf("debug layer: %.*s\n", static_cast<int>(m->DescriptionByteLength), m->pDescription); + ++errors; + } + } + std::printf("debug layer errors: %d\n", errors); + if (errors) result = 1; + } + std::printf("startup_gpu_pipeline %s %s%s: %s (%d failed)\n", argv[1], mode.c_str(), mutate ? " --mutate no-heap-flags" : "", + result == 0 ? "pass" : result == 77 ? "skip" : "FAIL", failures); + if (reference_miss && result == 0 && reference_attempts == 0) return 1; + return result; +} diff --git a/tests/startup_gpu_pipeline.hlsl b/tests/startup_gpu_pipeline.hlsl new file mode 100644 index 0000000000..969c40baf7 --- /dev/null +++ b/tests/startup_gpu_pipeline.hlsl @@ -0,0 +1,66 @@ +// Fixture shaders for the binding ABI (the upstream emitter, src/emit/mod.rs), for +// startup_gpu_pipeline: user data at b0 space0, the title's root views in space1 (b2 a root +// CBV, t5 a root SRV, u7 a root UAV, t255 the strides slot), an immediate sampler at s0 +// space0, and views and samplers picked from the heaps by the user data (byte offsets: views 32 +// bytes apart, samplers 16, as the console's descriptor sizes). Not title shaders. +cbuffer UserData : register(b0, space0) +{ + uint4 ud[2]; +}; +struct RootData +{ + uint4 v; +}; +ConstantBuffer<RootData> root_cbv : register(b2, space1); +ByteAddressBuffer root_srv : register(t5, space1); +RWByteAddressBuffer root_uav : register(u7, space1); +ByteAddressBuffer strides : register(t255, space1); +SamplerState immediate : register(s0, space0); + +// ud[0].x: output view (bytes), ud[0].y: texture view, ud[0].z: heap sampler (bytes); +// ud[1].x: a value to store, ud[1].y: the root UAV's value. +[numthreads(1, 1, 1)] +void CsMain() +{ + RWByteAddressBuffer heap_out = ResourceDescriptorHeap[ud[0].x / 32]; + Texture2D<float4> tex = ResourceDescriptorHeap[ud[0].y / 32]; + SamplerState heap_sampler = SamplerDescriptorHeap[ud[0].z / 16]; + const float a = tex.SampleLevel(immediate, float2(0.5, 0.5), 0).x; + const float b = tex.SampleLevel(heap_sampler, float2(0.5, 0.5), 0).x; + heap_out.Store4(0, uint4(ud[1].x, root_cbv.v.x, root_srv.Load(0), strides.Load(0))); + heap_out.Store2(16, uint2(asuint(a), asuint(b))); + root_uav.Store(0, ud[1].y); +} + +struct VsOut +{ + float4 pos : SV_Position; +}; + +// ud[1].z: the scale of the position (1.0 as bits). The vertex stage's user data is its own. +VsOut VsMain(float2 p : POSITION) +{ + VsOut o; + o.pos = float4(p * asfloat(ud[1].z), 0, 1); + return o; +} + +// One triangle over the whole target, as VsMain draws it. +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void MsMain(out vertices VsOut v[3], out indices uint3 t[1]) +{ + SetMeshOutputCounts(3, 1); + const float s = asfloat(ud[1].z); + v[0].pos = float4(-1 * s, -1 * s, 0, 1); + v[1].pos = float4(-1 * s, 3 * s, 0, 1); + v[2].pos = float4(3 * s, -1 * s, 0, 1); + t[0] = uint3(0, 1, 2); +} + +// ud[0].x: a raw buffer view (bytes); ud[1].x: a value. The pixel stage's user data is its own. +uint4 PsMain() : SV_Target +{ + ByteAddressBuffer heap_in = ResourceDescriptorHeap[ud[0].x / 32]; + return uint4(ud[1].x, root_cbv.v.x, heap_in.Load(0), 0x600d); +} diff --git a/tests/startup_gpu_pipeline_state_check.cpp b/tests/startup_gpu_pipeline_state_check.cpp new file mode 100644 index 0000000000..423e229e6b --- /dev/null +++ b/tests/startup_gpu_pipeline_state_check.cpp @@ -0,0 +1,312 @@ +// Checks src/startup_stubs/gpu_pipeline_state.h without a device: the stream walk with the +// console's subobject numbering (MS = 24, AS = 23), the graphics state defaults, DEPTH_STENCIL1 +// folding, the stop on an unknown or truncated subobject, host_blend on integer targets and the +// offsets of appended input elements. The cases are the upstream Rust tests (vg/pipeline.rs +// streams_yield_their_shaders, vg/pipeline/host.rs integer_targets_do_not_blend, +// blend_states_without_integer_blending_are_kept, appended_elements_are_aligned, +// a_huge_explicit_offset_does_not_overflow) plus the stops. +// +// Negative controls: --mutate desktop-numbering writes the mesh stage with the desktop number 25, +// which the console walk does not know, so the shaders are not found; --mutate blend-kept expects +// the title's blend state back unchanged on an integer target. +#define X2W_GPU_PIPELINE_STATE_ONLY +#include "startup_stubs/gpu_pipeline_state.h" + +#include <cstdio> +#include <cstring> +#include <vector> + +#ifdef _MSC_VER +#pragma warning(disable : 4324) // the subobjects are padded to 8 on purpose +#endif + +using namespace x2w_gpu; + +namespace { + +enum class Mutation { none, desktop_numbering, blend_kept }; +Mutation mutation = Mutation::none; +int failures = 0; + +#define EXPECT(cond) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL line %d: %s\n", __LINE__, #cond); \ + ++failures; \ + } \ + } while (0) + +void put64(std::vector<unsigned char>& s, std::size_t at, std::uint64_t v) { std::memcpy(&s[at], &v, 8); } + +// The stream layout the title builds (upstream test, title+0x86f090): root signature, five shader +// slots (the first a mesh shader), blend, sample mask, rasterizer, depth-stencil 1, sample +// description, input layout, topology, render target and depth formats: 0x2b0 bytes. +void title_stream() +{ + const unsigned char ms[7] = {9, 9, 9, 9, 9, 9, 9}; + const unsigned char ps[5] = {4, 4, 4, 4, 4}; + std::vector<unsigned char> s(0x2b0, 0); + const std::uint64_t mesh_kind = mutation == Mutation::desktop_numbering ? 25 : 24; + const std::pair<std::size_t, std::uint64_t> kinds[] = { + {0x10, mesh_kind}, {0x28, 2}, {0x40, 3}, {0x58, 4}, {0x70, 5}, {0x88, 8}, {0x1d8, 9}, {0x1e0, 10}, + {0x210, 21}, {0x250, 17}, {0x260, 12}, {0x278, 14}, {0x280, 15}, {0x2a8, 16}}; + for (const auto& k : kinds) put64(s, k.first, k.second); + put64(s, 0x18, reinterpret_cast<std::uint64_t>(ms)); + put64(s, 0x20, sizeof(ms)); + put64(s, 0x30, reinterpret_cast<std::uint64_t>(ps)); + put64(s, 0x38, sizeof(ps)); + // Topology type 3 (triangles), one render target of format 28. + put64(s, 0x278, 14 | 3ull << 32); + put64(s, 0x280, 15 | 28ull << 32); + put64(s, 0x2a0, 1ull << 32); + // DEPTH_STENCIL1 at 0x210 with the depth bounds test on (data at +4: DepthBoundsTestEnable at +52). + const std::uint32_t one = 1; + std::memcpy(&s[0x210 + 4 + offsetof(D3D12_DEPTH_STENCIL_DESC1, DepthBoundsTestEnable)], &one, 4); + // Depth format 118 (console D24S8). + put64(s, 0x2a8, 16 | 118ull << 32); + const VpStream out = vp_parse_stream(s.data(), s.size(), VpFormatMap{}); + EXPECT(!out.stopped && !out.truncated); + EXPECT(out.shaders.size() == 2); + if (out.shaders.size() == 2) { + EXPECT(out.shaders[0].stage == vp_stage_mesh && out.shaders[0].code == ms && out.shaders[0].size == sizeof(ms)); + EXPECT(out.shaders[1].stage == vp_stage_pixel && out.shaders[1].code == ps && out.shaders[1].size == sizeof(ps)); + } + const VpGraphicsState& g = out.graphics; + EXPECT(g.topology == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE); + EXPECT(g.targets.NumRenderTargets == 1 && g.targets.RTFormats[0] == DXGI_FORMAT_R8G8B8A8_UNORM); + EXPECT(g.depth_bounds); + EXPECT(g.depth_format == DXGI_FORMAT_D24_UNORM_S8_UINT); + // The zeroed subobjects replaced the defaults (blend, mask, rasterizer, depth read as zero). + EXPECT(g.sample_mask == 0 && g.rasterizer.CullMode == 0 && !g.depth.DepthEnable); + // The input layout with a null pointer keeps none. + EXPECT(g.inputs.empty() && !g.bad_inputs); +} + +void defaults() +{ + const VpGraphicsState g; + EXPECT(g.sample_mask == 0xffffffffu); + EXPECT(g.rasterizer.FillMode == D3D12_FILL_MODE_SOLID && g.rasterizer.CullMode == D3D12_CULL_MODE_BACK && g.rasterizer.DepthClipEnable); + EXPECT(g.depth.DepthEnable && g.depth.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ALL && g.depth.DepthFunc == D3D12_COMPARISON_FUNC_LESS); + EXPECT(g.depth.StencilReadMask == 0xff && g.depth.StencilWriteMask == 0xff && !g.depth.StencilEnable); + EXPECT(g.depth.FrontFace.StencilFunc == D3D12_COMPARISON_FUNC_ALWAYS && g.depth.BackFace.StencilPassOp == D3D12_STENCIL_OP_KEEP); + for (const auto& t : g.blend.RenderTarget) { + EXPECT(!t.BlendEnable && t.SrcBlend == D3D12_BLEND_ONE && t.DestBlend == D3D12_BLEND_ZERO); + EXPECT(t.RenderTargetWriteMask == D3D12_COLOR_WRITE_ENABLE_ALL && t.LogicOp == D3D12_LOGIC_OP_NOOP); + } + EXPECT(g.samples.Count == 1 && g.samples.Quality == 0); + EXPECT(g.topology == D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED && g.depth_format == DXGI_FORMAT_UNKNOWN); + EXPECT(g.strip_cut == D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED && !g.depth_bounds); +} + +// Subobject 21 sets depth and the bounds flag; a later 11 clears the flag. +void depth_folding() +{ + struct alignas(8) Sub21 { + std::uint32_t type; + D3D12_DEPTH_STENCIL_DESC1 d; + } a{}; + a.type = 21; + a.d.DepthEnable = FALSE; + a.d.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + a.d.StencilEnable = TRUE; + a.d.StencilReadMask = 0x0f; + a.d.DepthBoundsTestEnable = TRUE; + VpGraphicsState g; + vp_read_subobject(g, 21, reinterpret_cast<const unsigned char*>(&a), VpFormatMap{}); + EXPECT(g.depth_bounds && !g.depth.DepthEnable && g.depth.StencilEnable && g.depth.StencilReadMask == 0x0f); + EXPECT(g.depth1().DepthBoundsTestEnable && g.depth1().DepthFunc == D3D12_COMPARISON_FUNC_ALWAYS); + struct alignas(8) Sub11 { + std::uint32_t type; + D3D12_DEPTH_STENCIL_DESC d; + } b{}; + b.type = 11; + b.d.DepthEnable = TRUE; + vp_read_subobject(g, 11, reinterpret_cast<const unsigned char*>(&b), VpFormatMap{}); + EXPECT(!g.depth_bounds && g.depth.DepthEnable); +} + +// A type of unknown size stops the walk (the rest ignored); a subobject past the end does too. +void stops() +{ + std::vector<unsigned char> s(0x40, 0); + put64(s, 0x00, 14 | 4ull << 32); // topology type 4 (patch): kept as given + put64(s, 0x08, 99); // unknown + put64(s, 0x10, 9 | 7ull << 32); // sample mask after it: not read + VpStream out = vp_parse_stream(s.data(), s.size(), VpFormatMap{}); + EXPECT(out.stopped && out.stopped_kind == 99 && out.stopped_at == 8 && !out.truncated); + EXPECT(out.graphics.topology == 4 && out.graphics.sample_mask == 0xffffffffu); + // A blend subobject (336 bytes) in a 0x40-byte stream. + std::vector<unsigned char> t(0x40, 0); + put64(t, 0x00, 8); + out = vp_parse_stream(t.data(), t.size(), VpFormatMap{}); + EXPECT(out.truncated && out.stopped_kind == 8 && out.stopped_at == 0); + EXPECT(out.graphics.blend.RenderTarget[0].SrcBlend == D3D12_BLEND_ONE); // untouched + // AS (23) is a stage; a null shader is left out. + std::vector<unsigned char> u(0x30, 0); + put64(u, 0x00, 23); + put64(u, 0x18, 6); + out = vp_parse_stream(u.data(), u.size(), VpFormatMap{}); + EXPECT(out.shaders.empty() && !out.stopped && !out.truncated); +} + +void topologies() +{ + EXPECT(vp_host_topology_type(static_cast<D3D12_PRIMITIVE_TOPOLOGY_TYPE>(19)) == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE); + EXPECT(vp_host_topology_type(static_cast<D3D12_PRIMITIVE_TOPOLOGY_TYPE>(32)) == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE); + EXPECT(vp_host_topology_type(D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE) == D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE); +} + +D3D12_RT_FORMAT_ARRAY targets(std::initializer_list<DXGI_FORMAT> formats) +{ + D3D12_RT_FORMAT_ARRAY t{}; + for (DXGI_FORMAT f : formats) t.RTFormats[t.NumRenderTargets++] = f; + return t; +} + +D3D12_BLEND_DESC blending(bool independent) +{ + D3D12_BLEND_DESC b = VpGraphicsState().blend; + b.IndependentBlendEnable = independent; + for (auto& t : b.RenderTarget) { + t.BlendEnable = TRUE; + t.SrcBlend = D3D12_BLEND_SRC_ALPHA; + t.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + } + return b; +} + +bool same(const D3D12_BLEND_DESC& a, const D3D12_BLEND_DESC& b) { return std::memcmp(&a, &b, sizeof(a)) == 0; } + +void blends() +{ + const auto t = targets({DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R8_UINT}); + for (bool independent : {false, true}) { + const D3D12_BLEND_DESC host = mutation == Mutation::blend_kept ? blending(independent) : vp_host_blend(blending(independent), t); + EXPECT(host.IndependentBlendEnable); + EXPECT(host.RenderTarget[0].BlendEnable && host.RenderTarget[1].BlendEnable && !host.RenderTarget[2].BlendEnable); + EXPECT(host.RenderTarget[2].SrcBlend == D3D12_BLEND_SRC_ALPHA && host.RenderTarget[0].DestBlend == D3D12_BLEND_INV_SRC_ALPHA); + } + // No integer target; an integer target that does not blend; integer formats past the targets in use. + D3D12_BLEND_DESC b = blending(false); + EXPECT(same(vp_host_blend(b, targets({DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R11G11B10_FLOAT})), b)); + b = blending(true); + b.RenderTarget[1].BlendEnable = FALSE; + EXPECT(same(vp_host_blend(b, targets({DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT})), b)); + auto past = targets({DXGI_FORMAT_R8G8B8A8_UNORM}); + past.RTFormats[1] = DXGI_FORMAT_R8_UINT; + EXPECT(same(vp_host_blend(blending(false), past), blending(false))); +} + +std::vector<std::uint32_t> offsets(std::initializer_list<std::pair<DXGI_FORMAT, UINT>> elements) +{ + VpGraphicsState g; + for (const auto& e : elements) { + D3D12_INPUT_ELEMENT_DESC d{}; + d.Format = e.first; + d.AlignedByteOffset = e.second; + g.inputs.push_back(d); + g.names.push_back("A"); + } + std::vector<std::uint32_t> out; + for (const auto& i : g.elements()) out.push_back(i.offset); + return out; +} + +void inputs() +{ + const UINT append = D3D12_APPEND_ALIGNED_ELEMENT; + EXPECT((offsets({{DXGI_FORMAT_R8G8_UNORM, 0}, {DXGI_FORMAT_R32G32_FLOAT, append}}) == std::vector<std::uint32_t>{0, 4})); + EXPECT((offsets({{DXGI_FORMAT_R8_UNORM, 0}, {DXGI_FORMAT_R16_FLOAT, append}, {DXGI_FORMAT_R8_UNORM, append}}) == + std::vector<std::uint32_t>{0, 2, 4})); + EXPECT((offsets({{DXGI_FORMAT_R8G8B8A8_UNORM, 0}, {DXGI_FORMAT_R32G32_FLOAT, append}, {DXGI_FORMAT_R32G32B32_FLOAT, append}}) == + std::vector<std::uint32_t>{0, 4, 12})); + const auto huge = offsets({{DXGI_FORMAT_R32G32B32A32_FLOAT, 0xffffffffu - 8}, {DXGI_FORMAT_R32_FLOAT, append}}); + EXPECT(huge.size() == 2 && huge[1] == 0xffffffffu); + + // An input layout subobject: names copied, formats mapped, slots and pointers. + D3D12_INPUT_ELEMENT_DESC e[2] = { + {"POSITION", 0, static_cast<DXGI_FORMAT>(116), 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"TEXCOORD", 3, DXGI_FORMAT_R16G16_FLOAT, 2, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1}}; + struct alignas(8) Sub12 { + std::uint32_t type, pad; + D3D12_INPUT_LAYOUT_DESC layout; + } sub{12, 0, {e, 2}}; + VpFormatMap map; + map.input = [](std::uint32_t f) { return f == 116 ? DXGI_FORMAT_R10G10B10A2_UNORM : static_cast<DXGI_FORMAT>(f); }; + VpGraphicsState g; + vp_read_subobject(g, 12, reinterpret_cast<const unsigned char*>(&sub), map); + EXPECT(g.inputs.size() == 2 && g.names.size() == 2 && !g.bad_inputs); + if (g.inputs.size() == 2) { + EXPECT(g.names[0] == "POSITION" && g.names[1] == "TEXCOORD"); + EXPECT(g.inputs[0].SemanticName == nullptr && g.inputs[0].Format == DXGI_FORMAT_R10G10B10A2_UNORM); + EXPECT(g.slots() == 0x5); + const auto layout = g.input_layout(); + EXPECT(std::strcmp(layout[1].SemanticName, "TEXCOORD") == 0 && layout[1].SemanticIndex == 3); + const auto el = g.elements(); + EXPECT(el[1].slot == 2 && el[1].offset == 0 && el[1].per_instance && !el[0].per_instance); + } + // More than 32 elements: refused. + Sub12 many{12, 0, {e, 33}}; + VpGraphicsState h; + vp_read_subobject(h, 12, reinterpret_cast<const unsigned char*>(&many), map); + EXPECT(h.bad_inputs && h.inputs.empty()); +} + +void formats() +{ + // Render targets and depth go through the caller's map; the default mapping uses pc_format. + EXPECT(vp_pc_format(118) == DXGI_FORMAT_D24_UNORM_S8_UINT && vp_pc_format(119) == DXGI_FORMAT_R24_UNORM_X8_TYPELESS && + vp_pc_format(120) == DXGI_FORMAT_X24_TYPELESS_G8_UINT && vp_pc_format(28) == DXGI_FORMAT_R8G8B8A8_UNORM); + struct alignas(8) Sub15 { + std::uint32_t type; + D3D12_RT_FORMAT_ARRAY t; + } sub{15, {}}; + sub.t.NumRenderTargets = 2; + sub.t.RTFormats[0] = static_cast<DXGI_FORMAT>(67); + sub.t.RTFormats[1] = DXGI_FORMAT_R8G8B8A8_UNORM; + VpFormatMap map; + map.target = [](std::uint32_t f) { return f == 67 ? DXGI_FORMAT_R11G11B10_FLOAT : static_cast<DXGI_FORMAT>(f); }; + VpGraphicsState g; + vp_read_subobject(g, 15, reinterpret_cast<const unsigned char*>(&sub), map); + EXPECT(g.targets.NumRenderTargets == 2 && g.targets.RTFormats[0] == DXGI_FORMAT_R11G11B10_FLOAT && + g.targets.RTFormats[1] == DXGI_FORMAT_R8G8B8A8_UNORM); +} + +void sizes() +{ + // The subobject sizes hold the desktop structures at +4 (+8 for pointers). + EXPECT(vp_subobject(8).size >= 4 + sizeof(D3D12_BLEND_DESC)); + EXPECT(vp_subobject(10).size >= 4 + sizeof(D3D12_RASTERIZER_DESC)); + EXPECT(vp_subobject(11).size >= 4 + sizeof(D3D12_DEPTH_STENCIL_DESC)); + EXPECT(vp_subobject(21).size >= 4 + sizeof(D3D12_DEPTH_STENCIL_DESC1)); + EXPECT(vp_subobject(12).size >= 8 + sizeof(D3D12_INPUT_LAYOUT_DESC)); + EXPECT(vp_subobject(15).size >= 4 + sizeof(D3D12_RT_FORMAT_ARRAY)); + EXPECT(vp_subobject(17).size >= 4 + sizeof(DXGI_SAMPLE_DESC)); + EXPECT(vp_subobject(24).stage == vp_stage_mesh && vp_subobject(23).stage == vp_stage_amplification); + EXPECT(vp_subobject(25).size == 0 && vp_subobject(26).size == 0); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0) { + if (std::strcmp(argv[2], "desktop-numbering") == 0) mutation = Mutation::desktop_numbering; + else if (std::strcmp(argv[2], "blend-kept") == 0) mutation = Mutation::blend_kept; + else return 2; + } else if (argc != 1) { + return 2; + } + title_stream(); + defaults(); + depth_folding(); + stops(); + topologies(); + blends(); + inputs(); + formats(); + sizes(); + std::printf("startup_gpu_pipeline_state_check: %d failed\n", failures); + return failures ? 1 : 0; +} diff --git a/tests/startup_gpu_reference_library.cpp b/tests/startup_gpu_reference_library.cpp new file mode 100644 index 0000000000..a396ad244d --- /dev/null +++ b/tests/startup_gpu_reference_library.cpp @@ -0,0 +1,69 @@ +#include "startup_stubs/gpu_db.h" +#include "startup_stubs/gpu_pipeline_record.h" +#include "startup_stubs/gpu_reference_library.h" +#include <dxgi1_6.h> +#include <cstdio> +#include <thread> + +using namespace x2w_gpu; +using Microsoft::WRL::ComPtr; +static int check_entry_locks() +{ + VpReferenceEntryLocks locks; + const std::wstring held_name = L"00000000000000000000000000000000"; + std::wstring other_name; + // Exercise two names that would have occupied the same legacy stripe. + for (unsigned i = 1; ; ++i) { + other_name = std::to_wstring(i); + if (std::hash<std::wstring>{}(other_name) % 32 == std::hash<std::wstring>{}(held_name) % 32) break; + } + std::unique_lock<std::mutex> held(locks.for_name(held_name)); + bool serialized = false, independent = false; + std::thread caller([&] { + std::unique_lock<std::mutex> duplicate(locks.for_name(held_name), std::try_to_lock); + std::unique_lock<std::mutex> unrelated(locks.for_name(other_name), std::try_to_lock); + serialized = !duplicate.owns_lock(); + independent = unrelated.owns_lock(); + }); + caller.join(); + return serialized && independent ? 0 : 1; +} +int wmain(int argc, wchar_t** argv) +{ + if (argc == 2 && wcscmp(argv[1], L"--entry-locks") == 0) return check_entry_locks(); + if (argc != 4 || wcslen(argv[3]) != 16) return 2; + SetEnvironmentVariableW(L"X2W_GPU_DB", argv[1]); + std::string key(argv[3], argv[3] + 16); + auto* record = gpu_shader_by_key(key.c_str(), GpuStage::compute); + if (!record) return 3; + ComPtr<IDXGIFactory6> factory; + ComPtr<IDXGIAdapter1> adapter; + ComPtr<ID3D12Device> device; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || + FAILED(factory->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&adapter))) || + FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) return 4; + auto view = vp_record_view(record, vp_stage_compute); + VpRootOptions options; + options.aniso_point_mip = vp_device_caps(device.Get()).aniso_point_mip; + auto layout = vp_root_layout(&view, 1, true, options); + std::vector<unsigned char> root_blob; + std::string error; + if (FAILED(vp_serialize_root(layout, root_blob, error))) return 5; + ComPtr<ID3D12RootSignature> root; + if (FAILED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root)))) return 6; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root.Get(); + desc.CS = {view.dxil, view.dxil_size}; + std::wstring name = vp_compute_library_name(root_blob, desc.CS); + std::printf("root=%zu dxil=%zu name=%ls\n", root_blob.size(), view.dxil_size, name.c_str()); + VpReferenceLibrary library; + HRESULT hr = library.open(device.Get(), argv[2]); + std::printf("CreatePipelineLibrary=0x%08lx\n", static_cast<unsigned long>(hr)); + if (FAILED(hr)) return 7; + ComPtr<ID3D12PipelineState> pso; + auto start = GetTickCount64(); + hr = library.load(name, desc, pso.GetAddressOf()); + std::printf("LoadComputePipeline=0x%08lx elapsed=%llu ms object=%d device=0x%08lx\n", static_cast<unsigned long>(hr), + GetTickCount64()-start, pso.Get()!=nullptr, static_cast<unsigned long>(device->GetDeviceRemovedReason())); + return SUCCEEDED(hr) && pso && SUCCEEDED(device->GetDeviceRemovedReason()) ? 0 : 8; +} diff --git a/tests/startup_gpu_resident_mips.inl b/tests/startup_gpu_resident_mips.inl new file mode 100644 index 0000000000..5d9bbadcd2 --- /dev/null +++ b/tests/startup_gpu_resident_mips.inl @@ -0,0 +1,206 @@ +// A protected gap in either array slice must clamp every sampled slice to the common resident +// suffix. Once the gap is committed, the original view becomes usable with the same mip numbering. +bool resident_mip_test() +{ + using namespace x2w_resident_mips; + using Layout = x2w_startup::gfx10_local::Layout; + auto* device = fx.device.Get(); + constexpr UINT side = 512, mips = 8, slices = 2; + const Layout layout(x2w_startup::gfx10_local::sw_4kb_s, false, 4, side, side, slices, mips); + if (!layout.valid) return false; + struct Memory { + unsigned char* p; + ~Memory() { if (p) VirtualFree(p, 0, MEM_RELEASE); } + } memory{static_cast<unsigned char*>(VirtualAlloc(nullptr, SIZE_T(layout.size), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))}; + if (!memory.p) return false; + for (UINT s = 0; s < slices; ++s) + for (UINT mip = 0; mip < mips; ++mip) { + const float color = float(10 + s * 100 + mip); + for (UINT y = 0; y < side >> mip; ++y) + for (UINT x = 0; x < side >> mip; ++x) + std::memcpy(memory.p + layout.address(mip, x, y, s), &color, sizeof(color)); + } + DWORD old = 0; + for (UINT s = 0; s < slices; ++s) { + const auto prefix = layout.level[1 + s].offset; + if (!VirtualProtect(memory.p + s * layout.slice_size + prefix, SIZE_T(layout.slice_size-prefix), PAGE_NOACCESS, &old)) + return false; + } + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = d.Height = side; + d.DepthOrArraySize = slices; d.MipLevels = mips; d.SampleDesc.Count = 1; d.Format = DXGI_FORMAT_R32_FLOAT; + const D3D12_HEAP_PROPERTIES hp{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr<ID3D12Resource> texture; + if (FAILED(device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&texture)))) return false; + x2w_startup::SliceFootprints plan(device, d, mips); + auto output = buffer(16, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + auto result = buffer(16, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + ComPtr<ID3D12DescriptorHeap> heap; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,1,D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + if (!output || !result || FAILED(device->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&heap)))) return false; + D3D12_ROOT_PARAMETER params[2]{}; + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV,1}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1,&range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + 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.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + D3D12_ROOT_SIGNATURE_DESC root_desc{2,params,1,&sampler}; + const char shader[] = "Texture2DArray<float> t:register(t0); SamplerState s:register(s0); RWByteAddressBuffer o:register(u0);" + "[numthreads(1,1,1)] void main(){uint w,h,a,n;t.GetDimensions(0,w,h,a,n);float3 uv=float3(.5,.5,0);" + "o.Store4(0,uint4(t.SampleLevel(s,uv,0),t.SampleLevel(s,uv,3),t.SampleLevel(s,uv,10),w));}"; + ComPtr<ID3D12RootSignature> root; + ComPtr<ID3DBlob> serialized, cs; + if (FAILED(D3D12SerializeRootSignature(&root_desc,D3D_ROOT_SIGNATURE_VERSION_1,&serialized,nullptr)) || + FAILED(device->CreateRootSignature(0,serialized->GetBufferPointer(),serialized->GetBufferSize(),IID_PPV_ARGS(&root))) || + FAILED(D3DCompile(shader,sizeof(shader)-1,nullptr,nullptr,nullptr,"main","cs_5_0",0,0,&cs,nullptr))) return false; + D3D12_COMPUTE_PIPELINE_STATE_DESC p{}; + p.pRootSignature=root.Get(); p.CS={cs->GetBufferPointer(),cs->GetBufferSize()}; + ComPtr<ID3D12PipelineState> pso; + if (FAILED(device->CreateComputePipelineState(&p,IID_PPV_ARGS(&pso)))) return false; + D3D12_SHADER_RESOURCE_VIEW_DESC requested{}; + requested.Format = d.Format; requested.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + requested.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + requested.Texture2DArray.MipLevels = 5; requested.Texture2DArray.FirstArraySlice = 1; requested.Texture2DArray.ArraySize = 1; + for (UINT promotion = 0; promotion < 2; ++promotion) { + if (promotion && !VirtualProtect(memory.p,SIZE_T(layout.size),PAGE_READWRITE,&old)) return false; + const auto suffix = x2w_resident_mips::find(layout,reinterpret_cast<std::uintptr_t>(memory.p),[](auto at,auto bytes) { + for (auto end=at+bytes; at<end;) { + MEMORY_BASIC_INFORMATION region{}; + if (!VirtualQuery(reinterpret_cast<void*>(at),®ion,sizeof(region)) || region.State!=MEM_COMMIT || + region.Protect!=PAGE_READWRITE) return false; + at=reinterpret_cast<std::uintptr_t>(region.BaseAddress)+region.RegionSize; + } + return true; + }); + const UINT expected = promotion ? 0 : 3; + auto selected = requested; + if (suffix.first != expected || !limit_view(selected,mips,suffix.first)) return false; + auto narrow = requested; + narrow.Texture2DArray.MipLevels=2; + if (!promotion && limit_view(narrow,mips,expected)) return false; + auto rebased=requested; + rebased.Texture2DArray.MostDetailedMip=1; + if (!promotion && limit_view(rebased,mips,expected)) return false; + auto covered=requested; + covered.Texture2DArray.MostDetailedMip=3; + if (!limit_view(covered,mips,expected) || covered.Texture2DArray.ResourceMinLODClamp!=0) return false; + device->CreateShaderResourceView(texture.Get(), &selected, heap->GetCPUDescriptorHandleForHeapStart()); + UINT64 bytes=0; + for (UINT mip=expected; mip<mips; ++mip) bytes += (plan.bytes(mip)+511)&~511ull; + auto upload=buffer(bytes*slices,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_FLAG_NONE,D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped=nullptr; + if (!upload || FAILED(upload->Map(0,nullptr,&mapped))) return false; + begin(); + x2w_gpu::transition_all(fx.list.Get(),texture.Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST); + UINT64 offset=0; + for (UINT s=0; s<slices; ++s) { + for (UINT mip=expected; mip<mips; ++mip) { + if (!stage_rows(layout,suffix,mip,memory.p+s*layout.slice_size,static_cast<unsigned char*>(mapped)+offset, + UINT(plan.row_bytes[mip]/4),plan.rows[mip],plan.placed[mip].Footprint.RowPitch)) return false; + plan.upload(fx.list.Get(),texture.Get(),upload.Get(),mips,slices,s,mip,offset); + offset+=(plan.bytes(mip)+511)&~511ull; + } + } + upload->Unmap(0,nullptr); + x2w_gpu::transition_all(fx.list.Get(),texture.Get(),D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + x2w_gpu::transition_all(fx.list.Get(),output.Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heaps[]={heap.Get()}; + fx.list->SetDescriptorHeaps(1,heaps); + fx.list->SetComputeRootSignature(root.Get()); fx.list->SetPipelineState(pso.Get()); + fx.list->SetComputeRootDescriptorTable(0,heap->GetGPUDescriptorHandleForHeapStart()); + fx.list->SetComputeRootUnorderedAccessView(1,output->GetGPUVirtualAddress()); + fx.list->Dispatch(1,1,1); + x2w_gpu::transition_all(fx.list.Get(),output.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COPY_SOURCE); + fx.list->CopyBufferRegion(result.Get(),0,output.Get(),0,16); + x2w_gpu::transition_all(fx.list.Get(),output.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON); + x2w_gpu::transition_all(fx.list.Get(),texture.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,D3D12_RESOURCE_STATE_COMMON); + end_and_wait(); + if (FAILED(result->Map(0,nullptr,&mapped))) return false; + const auto* vals=static_cast<const UINT*>(mapped); + const bool ok=vals[0]==110+expected && vals[1]==113 && vals[2]==114 && vals[3]==side; + if (!ok) std::printf("mip %u sampled %u %u %u width %u\n",expected,vals[0],vals[1],vals[2],vals[3]); + const D3D12_RANGE none{}; result->Unmap(0,&none); + if (!ok) return false; + } + // Sample an actual smaller texture, then the full replacement, through the same title view. + // Rebind the first native texture afterwards to check a retained descriptor's mip numbering. + d.DepthOrArraySize = 1; + const Layout one(layout.mode, false, 4, side, side, 1, mips); + auto view = D3D12_SHADER_RESOURCE_VIEW_DESC{}; + view.Format = d.Format; + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Texture2D.MostDetailedMip = 3; + view.Texture2D.MipLevels = 4; + const UINT base = host_base(d, view, one, false); + if (base != 3 || host_base(d, requested, one, false) != 0) return false; + const char sampled[] = + "Texture2D<float> t:register(t0); SamplerState s:register(s0); RWByteAddressBuffer o:register(u0);" + "[numthreads(1,1,1)] void main(){uint w,h,n;t.GetDimensions(0,w,h,n);" + "o.Store4(0,uint4(w,t.Load(int3(0,0,1)),t.SampleLevel(s,float2(.5,.5),0),n));}"; + cs.Reset(); + if (FAILED(D3DCompile(sampled, sizeof(sampled)-1, nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, &cs, nullptr))) return false; + p.CS = {cs->GetBufferPointer(), cs->GetBufferSize()}; + pso.Reset(); + if (FAILED(device->CreateComputePipelineState(&p, IID_PPV_ARGS(&pso)))) return false; + ComPtr<ID3D12Resource> held[2]; + const auto full_bytes = device->GetResourceAllocationInfo(0, 1, &d).SizeInBytes; + for (UINT pass = 0; pass < 3; ++pass) { + const UINT selected_base = pass == 1 ? 0 : base; + const auto native = host_desc(d, selected_base); + auto& host = held[pass == 1]; + auto selected = view; + rebase(selected, selected_base); + if (pass != 1 && device->GetResourceAllocationInfo(0, 1, &native).SizeInBytes >= full_bytes) return false; + if (!host && FAILED(device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &native, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&host)))) return false; + device->CreateShaderResourceView(host.Get(), &selected, heap->GetCPUDescriptorHandleForHeapStart()); + const x2w_startup::SliceFootprints native_plan(device, native, native.MipLevels); + const Suffix cut{selected_base, prefix_bytes(one, selected_base)}; + UINT64 bytes = 0; + for (UINT i = 0; i < native.MipLevels; ++i) bytes += (native_plan.bytes(i) + 511) & ~511ull; + auto upload = buffer(bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped = nullptr; + if (!upload || FAILED(upload->Map(0, nullptr, &mapped))) return false; + begin(); + if (pass < 2) { + x2w_gpu::transition_all(fx.list.Get(), host.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + UINT64 offset = 0; + for (UINT i = 0; i < native.MipLevels; ++i) { + if (!stage_rows(one, cut, selected_base + i, memory.p, static_cast<unsigned char*>(mapped) + offset, + UINT(native_plan.row_bytes[i] / 4), native_plan.rows[i], native_plan.placed[i].Footprint.RowPitch)) return false; + native_plan.upload(fx.list.Get(), host.Get(), upload.Get(), native.MipLevels, 1, 0, i, offset); + offset += (native_plan.bytes(i) + 511) & ~511ull; + } + x2w_gpu::transition_all(fx.list.Get(), host.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + } + upload->Unmap(0, nullptr); + ID3D12DescriptorHeap* heaps[] = {heap.Get()}; + fx.list->SetDescriptorHeaps(1, heaps); + fx.list->SetComputeRootSignature(root.Get()); + fx.list->SetPipelineState(pso.Get()); + fx.list->SetComputeRootDescriptorTable(0, heap->GetGPUDescriptorHandleForHeapStart()); + fx.list->SetComputeRootUnorderedAccessView(1, output->GetGPUVirtualAddress()); + x2w_gpu::transition_all(fx.list.Get(), output.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + fx.list->Dispatch(1, 1, 1); + x2w_gpu::transition_all(fx.list.Get(), output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + fx.list->CopyBufferRegion(result.Get(), 0, output.Get(), 0, 16); + x2w_gpu::transition_all(fx.list.Get(), output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + end_and_wait(); + if (FAILED(result->Map(0, nullptr, &mapped))) return false; + const auto* vals = static_cast<const UINT*>(mapped); + const bool ok = vals[0] == 64 && vals[1] == 14 && vals[2] == 13 && vals[3] == 4; + std::printf("held mip native_base=%u native_bytes=%llu full_bytes=%llu width=%u load=%u sample=%u levels=%u\n", + selected_base, device->GetResourceAllocationInfo(0, 1, &native).SizeInBytes, full_bytes, vals[0], vals[1], vals[2], vals[3]); + const D3D12_RANGE none{}; + result->Unmap(0, &none); + if (!ok) return false; + } + return true; +} diff --git a/tests/startup_gpu_roots_check.cpp b/tests/startup_gpu_roots_check.cpp new file mode 100644 index 0000000000..e3c26d2213 --- /dev/null +++ b/tests/startup_gpu_roots_check.cpp @@ -0,0 +1,141 @@ +// X2W_GPU_ABI (WP3 vbind): the per-list root record (src/startup_stubs/gpu_roots.h) stores the root arguments defined in the upstream +// State (vg/draw.rs :28-52, :955-1002): any number of root parameters and constant dwords, graphics and compute +// apart, 32 vertex slots; and the console topologies map as draw.rs set_topology does. +// +// --mutate is the negative control: the same checks against X2W's old Pass record limits (16 parameters of 8 dwords, +// 8 vertex slots), which must fail. +#include "startup_stubs/gpu_roots.h" + +#include <cstdio> +#include <cstring> +#include <vector> + +namespace { +int failures = 0; +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + ++failures; \ + } \ + } while (0) + +bool mutate = false; +using namespace x2w_vbind; + +// The record under test; with --mutate, X2W's old limits applied on top (what Pass.constants[16][8] / vb[8] keep). +void set_constants(Roots& r, bool compute, std::uint32_t slot, const std::uint32_t* v, std::uint32_t n, std::uint32_t offset) +{ + if (mutate) { + if (slot >= 16 || offset >= 8) return; + if (n > 8 - offset) n = 8 - offset; + } + r.set_constants(compute, slot, v, n, offset); +} +void set_vertex(Roots& r, std::uint32_t start, std::uint32_t n, const VertexView* v) +{ + if (mutate) { + if (start >= 8) return; + if (n > 8 - start) n = 8 - start; + } + r.set_vertex(start, n, v); +} +} // namespace + +int main(int argc, char** argv) +{ + mutate = argc > 1 && std::strcmp(argv[1], "--mutate") == 0; + Roots r; + + // More than 8 dwords, past parameter 16. + std::uint32_t values[40]; + for (std::uint32_t i = 0; i < 40; ++i) values[i] = 0x1000 + i; + set_constants(r, false, 20, values, 12, 3); + { + const GpuRoot* p = r.at(false, 20); + CHECK(p && p->kind == GpuRootKind::constants); + CHECK(p && p->dwords.size() == 15); + CHECK(p && p->dwords[0] == 0 && p->dwords[3] == 0x1000 && p->dwords[14] == 0x100b); + } + // 40 dwords at parameter 2 (the 64-dword capacity must retain entries beyond the first eight). + set_constants(r, false, 2, values, 40, 0); + CHECK(r.at(false, 2) && r.at(false, 2)->dwords.size() == 40 && r.at(false, 2)->dwords[39] == 0x1027); + // A later partial write keeps the rest (draw.rs: c[offset..end] = values). + const std::uint32_t one = 7; + set_constants(r, false, 2, &one, 1, 30); + CHECK(r.at(false, 2) && r.at(false, 2)->dwords[30] == 7 && r.at(false, 2)->dwords[29] == 0x101d); + + // Graphics and compute apart. + set_constants(r, true, 2, &one, 1, 0); + CHECK(r.at(true, 2) && r.at(true, 2)->dwords.size() == 1 && r.at(true, 2)->dwords[0] == 7); + CHECK(r.at(false, 2) && r.at(false, 2)->dwords.size() == 40); + r.set_table(true, 5, 0xabc000); + CHECK(!r.at(false, 5) || r.at(false, 5)->kind == GpuRootKind::none); + CHECK(r.at(true, 5) && r.at(true, 5)->kind == GpuRootKind::table && r.at(true, 5)->handle == 0xabc000); + + // A parameter that held a table becomes constants afresh (no stale dwords), and a view replaces constants. + r.set_table(false, 20, 0x5000); + set_constants(r, false, 20, &one, 1, 1); + CHECK(r.at(false, 20) && r.at(false, 20)->kind == GpuRootKind::constants && r.at(false, 20)->dwords.size() == 2 && + r.at(false, 20)->dwords[0] == 0); + r.set_view(false, 20, 0x123456789aull, GpuRootKind::uav); + CHECK(r.at(false, 20) && r.at(false, 20)->kind == GpuRootKind::uav && r.at(false, 20)->address == 0x123456789aull && + r.at(false, 20)->dwords.empty()); + + // 32 vertex slots; a null array clears (draw.rs clear_vertex_buffers). + VertexView vv[4] = {{0x1000, 64, 16}, {0x2000, 32, 8}, {0x3000, 16, 4}, {0x4000, 8, 4}}; + set_vertex(r, 28, 4, vv); + CHECK(r.vertex[31].address == 0x4000 && r.vertex[28].stride == 16); + set_vertex(r, 29, 2, nullptr); + CHECK(!mutate ? r.vertex[29].address == 0 && r.vertex[30].address == 0 && r.vertex[31].address == 0x4000 : true); + r.set_vertex(30, 10, vv); // past 32: cut, no write past the array + CHECK(r.vertex[31].address == 0x2000); + + // Topologies (draw.rs :923, :4356): rectangles and the other console-only ones draw as triangle lists. + CHECK(host_topology(topology_rectangles) == 4); + CHECK(host_topology(topology_quads) == 4 && host_topology(topology_quad_strip) == 4); + CHECK(host_topology(topology_triangle_fan) == 4 && host_topology(topology_line_loop) == 4); + CHECK(host_topology(5) == 5 && host_topology(1) == 1); + + // A reset forgets everything. + r.clear(); + CHECK(r.graphics.empty() && r.compute.empty() && r.vertex[31].address == 0); + + { + x2w_gpu::TableConstants pending; + unsigned char title[] = {1, 2, 3, 4}; + unsigned char upload[8]{}; + auto* revoked = static_cast<unsigned char*>(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + CHECK(revoked); + if (revoked) { + const auto keep = [&](const void* source, UINT at) { + upload[at] = *pending.remember(source, 1, {1, 3, at}); + }; + keep(title, 1); + keep(title + 1, 2); + keep(revoked, 3); + keep(title + 3, 4); + DWORD old = 0; + CHECK(VirtualProtect(revoked, 4096, PAGE_NOACCESS, &old)); + title[0] = 7; + title[3] = 9; + const auto write = [&](const x2w_gpu::TableConstantSlice& slice, const unsigned char* src, size_t len) { + if (slice.offset == 4) return false; // its ring generation has retired + CHECK(slice.chunk == 1 && slice.generation == 3 && len == 1); + upload[slice.offset] = *src; + return true; + }; + const auto first = pending.first_submit(write); + CHECK(first.checked == 4 && first.changed == 1 && first.unreadable == 1 && first.stale == 1); + CHECK(upload[0] == 0 && upload[1] == 7 && upload[2] == 2 && upload[3] == 0 && upload[4] == 4 && upload[5] == 0); + title[0] = 9; + CHECK(!pending.first_submit(write).checked && upload[1] == 7); + keep(title, 1); + pending.clear(); // reset without submission + CHECK(!pending.first_submit(write).checked); + VirtualFree(revoked, 0, MEM_RELEASE); + } + } + std::printf("%s: %d failure(s)\n", mutate ? "gpu roots (mutated control)" : "gpu roots", failures); + return failures ? 1 : 0; +} diff --git a/tests/startup_gpu_small_texture_heap.inl b/tests/startup_gpu_small_texture_heap.inl new file mode 100644 index 0000000000..5ada303b91 --- /dev/null +++ b/tests/startup_gpu_small_texture_heap.inl @@ -0,0 +1,86 @@ +bool small_texture_heap_test() +{ + std::vector<ComPtr<ID3D12Resource>> textures; + constexpr DXGI_FORMAT formats[] = {DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R32_FLOAT, + DXGI_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R8G8B8A8_UNORM}; + constexpr UINT count = 96; + auto upload = buffer(count * 512, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + auto readback = buffer(count * 512, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + if (!upload || !readback) return false; + unsigned char* data = nullptr; + if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&data)))) return false; + for (UINT i = 0; i < count; ++i) std::memset(data + i*512, i+1, 4); + upload->Unmap(0, nullptr); + + { + x2w_startup::SmallTextureHeap pool; + for (UINT i = 0; i < count; ++i) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 1u << (i % 5); + desc.Height = 1u << ((i / 5) % 4); + desc.MipLevels = 1; + desc.DepthOrArraySize = i % 3 == 0 ? 3 : 1; + desc.Format = formats[i % 4]; + desc.SampleDesc.Count = 1; + auto standard = fx.device->GetResourceAllocationInfo(0, 1, &desc); + ComPtr<ID3D12Resource> texture; + if (!pool.place(fx.device.Get(), desc, standard.SizeInBytes, &texture) || + texture->GetDesc().Alignment != D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT) return false; + textures.push_back(std::move(texture)); + } + std::printf("small textures: %llu allocations, %llu committed bytes, %llu reserved bytes, %llu occupied bytes\n", + pool.count, pool.committed_equivalent, pool.reserved, pool.occupied); + if (pool.count != count || pool.reserved >= pool.committed_equivalent || pool.occupied > pool.reserved) return false; + + // A held mip chain from a 1024-square texture begins at 128-square for base 3. + for (const auto format : {DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC7_UNORM}) { + auto bc = textures[0]->GetDesc(); + bc.DepthOrArraySize = 1; + bc.Width = bc.Height = 128; bc.Format = format; bc.MipLevels = 6; bc.Alignment = 0; + ComPtr<ID3D12Resource> texture; + const auto standard = fx.device->GetResourceAllocationInfo(0, 1, &bc); + const UINT64 before = pool.occupied; + if (!pool.place(fx.device.Get(), bc, standard.SizeInBytes, &texture)) return false; + std::printf("128x128 fmt %u six mips: %llu committed, %llu occupied\n", format, standard.SizeInBytes, pool.occupied-before); + } + auto denied = textures[1]->GetDesc(); + denied.Width = denied.Height = 1024; + denied.Alignment = 0; + ComPtr<ID3D12Resource> texture; + auto standard = fx.device->GetResourceAllocationInfo(0, 1, &denied); + if (pool.place(fx.device.Get(), denied, standard.SizeInBytes, &texture) || texture) return false; + denied.Width = denied.Height = 1; + if (pool.place(fx.device.Get(), denied, D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT, &texture) || texture) return false; + denied.Width = denied.Height = 4; + denied.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + if (pool.place(fx.device.Get(), denied, standard.SizeInBytes, &texture) || texture) return false; + } + + // The allocator is gone. Write every resource before reading any so duplicate placements corrupt the check. + begin(); + for (const bool read : {false, true}) { + for (UINT i = 0; i < count; ++i) { + auto* texture = textures[i].Get(); + D3D12_TEXTURE_COPY_LOCATION resource{}, footprint{}; + resource.pResource = texture; + resource.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + footprint.pResource = read ? readback.Get() : upload.Get(); + footprint.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + footprint.PlacedFootprint = {UINT64(i) * 512, {texture->GetDesc().Format, 1, 1, 1, 256}}; + if (read) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Transition = {texture, 0, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE}; + fx.list->ResourceBarrier(1, &barrier); + const D3D12_BOX pixel{0,0,0,1,1,1}; + fx.list->CopyTextureRegion(&footprint, 0,0,0, &resource, &pixel); + } else fx.list->CopyTextureRegion(&resource, 0,0,0, &footprint, nullptr); + } + } + end_and_wait(); + if (FAILED(fx.device->GetDeviceRemovedReason()) || FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&data)))) return false; + bool ok = true; + for (UINT i = 0; i < count; ++i) ok &= data[i*512] == i+1; + readback->Unmap(0, nullptr); + return ok; +} diff --git a/tests/startup_gpu_trace_request.cpp b/tests/startup_gpu_trace_request.cpp new file mode 100644 index 0000000000..dd1dacb70e --- /dev/null +++ b/tests/startup_gpu_trace_request.cpp @@ -0,0 +1,30 @@ +#include "startup_stubs/gpu_trace_request.h" + +int main() +{ + using x2w_gpu::parse_scene_request; + const auto plain = parse_scene_request(" \t+1\r\n"); + const auto keyed = parse_scene_request("2\t001abcDEF4321657\n"); + if (!plain || plain->id != 1 || !plain->stage_key.empty() || + !keyed || keyed->id != 2 || keyed->stage_key != "001abcDEF4321657") return 1; + for (const auto input : {"", "0", "-1", "999999999999999999999", "2abcd", "2 0123456789ABCDEX", + "2 0000", "2 001abcDEF4321657 extra"}) + if (parse_scene_request(input)) return 2; + if (parse_scene_request(std::string_view("1\0x", 3))) return 3; + const auto pair = parse_scene_request("3 001abcDEF4321657\t f000000000000000\r\n"); + if (!pair || pair->stage_key != keyed->stage_key || pair->second_key != "f000000000000000") return 4; + for (const auto input : {"4 001abcDEF4321657 001abcdef4321657", "4 f000000000000000 123", + "4 0000000000000001 0000000000000002 0000000000000003"}) + if (parse_scene_request(input)) return 5; + const auto focused = parse_scene_request("5 001abcDEF4321657 f000000000000000 @300,450"); + if (!focused || !focused->point || (*focused->point)[0] != 300 || (*focused->point)[1] != 450 || + !parse_scene_request("1 @0,1000") || parse_scene_request("1 @-1,0") || parse_scene_request("1 @0,1001") || + parse_scene_request("1@1,1") || parse_scene_request("1 @2,3junk")) return 9; + using x2w_gpu::stage_key_number; + x2w_gpu::CaptureSelection selection{3, {stage_key_number(pair->stage_key), stage_key_number(pair->second_key)}, true}; + if (selection.matches(2, pair->second_key) || !selection.matches(3, "F000000000000000")) return 6; + selection.complete(pair->second_key); + if (selection.matches(3, pair->second_key) || !selection.matches(3, pair->stage_key)) return 7; + selection.complete(pair->stage_key); + return selection.id ? 8 : 0; +} diff --git a/tests/startup_gpu_user_data_check.cpp b/tests/startup_gpu_user_data_check.cpp new file mode 100644 index 0000000000..fdde45bb25 --- /dev/null +++ b/tests/startup_gpu_user_data_check.cpp @@ -0,0 +1,270 @@ +// X2W_GPU_ABI (WP3 vbind): the user-data dwords translated DXIL reads at b0 space0 (gpu_roots.h, a port of +// vg/draw.rs user_value / host_word / bind :1527-1551), the fresh-table planning (draw.rs tables), raw-view bounding +// (root_srv_table / root_uav), the memory adapter's bounds (find_bounded), RecordHash and the mesh clamp. +// +// The ABI (the upstream emitter, src/emit/mod.rs): a table's dword is its byte offset in its heap in CONSOLE units, 32 bytes a +// view and 16 a sampler, whatever the desktop increment is. +// +// --mutate is the negative control: table offsets computed as index x a desktop increment (64), the bias found again +// from the address instead of taken from the bound view, and gpu_find bounded by the window alone. It must fail. +#include "startup_stubs/gpu_roots.h" + +#include <array> +#include <cstdio> +#include <cstring> +#include <set> +#include <vector> + +namespace { +int failures = 0; +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + ++failures; \ + } \ + } while (0) +bool mutate = false; +using namespace x2w_vbind; +using x2w_gpu::GpuRootIndexedView; +using x2w_gpu::GpuUsedResource; + +GpuUsedResource use(GpuResourceType kind, GpuRootType root, std::uint32_t offset_dwords, std::uint8_t slot) +{ + GpuUsedResource u{}; + u.kind = kind; + u.root = root; + u.table_offset_dwords = offset_dwords; + u.dwords = 8; + u.slot = slot; + return u; +} + +std::vector<std::uint32_t> fill(const Roots& r, bool compute, const std::vector<GpuUserData>& words, std::uint32_t dwords, + const std::vector<MadeTable>& made, const HeapSpan* heaps, const std::vector<BoundBias>& biases, + unsigned* misses = nullptr) +{ + auto v = fill_user_data(r, compute, words.data(), words.size(), dwords, made, heaps, 2, biases, 0x77, + [](std::uint32_t slot, std::uint32_t dword) -> std::uint64_t { return slot == 4 ? 0x1234500000ull + dword * 4 : 0; }, misses); + if (mutate) { + // The desktop-increment mistake: a table's dword as index x 64. + for (const GpuUserData& u : words) + if (u.root == GpuRootType::table && u.index < dwords) + if (const GpuRoot* p = r.at(compute, u.slot); p && p->kind == GpuRootKind::table) + if (const HeapSpan* h = heap_of(heaps, 2, p->handle)) + v[u.index] = static_cast<std::uint32_t>((p->handle - h->start) / h->step() * 64); + // Recover the bias from the address when decoding the bound view. + for (const GpuUserData& u : words) + if (u.root == GpuRootType::other && u.other == abi::user_view_bias && u.index < dwords) + if (const GpuRoot* p = r.at(compute, u.slot); p && is_view(p->kind)) v[u.index] = static_cast<std::uint32_t>(p->address & 15); + } + return v; +} + +void user_data() +{ + HeapSpan heaps[2] = {{0x10000000, 1000, false}, {0x20000000, 100, true}}; + Roots r; + r.set_table(false, 0, 0x10000000 + 5 * 32); // view table at descriptor 5 + r.set_table(false, 1, 0x20000000 + 3 * 16); // sampler table at descriptor 3 + const std::uint32_t c[6] = {10, 11, 12, 13, 14, 15}; + r.set_constants(false, 2, c, 6, 0); + r.set_view(false, 3, 0x0000004512345678ull, GpuRootKind::srv); // a root view at an address ending in 8 + r.set_table(false, 4, 0x10000000 + 7 * 32); + r.set_table(false, 6, 0x30000000); // outside both heaps + std::vector<GpuUserData> words = { + {0, 0, GpuRootType::table, 0, 0}, + {1, 1, GpuRootType::table, 0, 0}, + {2, 2, GpuRootType::constants, 0, 4}, + {3, 3, GpuRootType::other, abi::user_root_address, 0}, + {4, 3, GpuRootType::other, abi::user_root_address + 1, 0}, + {5, 3, GpuRootType::other, abi::user_view_bias, 0}, + {6, 4, GpuRootType::other, abi::user_view_address, 8}, + {7, 4, GpuRootType::other, abi::user_view_address + 1, 8}, + {8, 0, GpuRootType::other, abi::user_dispatch_threads_x, 64}, + {9, 0, GpuRootType::other, abi::user_memory_base, 0}, + {10, 6, GpuRootType::table, 0, 0}, // outside the heaps: 0, a miss + {11, 9, GpuRootType::constants, 0, 0}, // never set: 0, a miss + {12, 2, GpuRootType::constants, 0, 9}, // past the constants set: 0 + {13, 2, GpuRootType::table, 0, 0}, // the root is constants, the shader reads a table: 0, a miss + {20, 2, GpuRootType::constants, 0, 0}, // past `dwords`: left out + }; + // The bias as bound: the raw view was made from the 16 bytes below a window offset ending in 8. + const std::vector<BoundBias> biases = {{3, 8}}; + unsigned misses = 0; + const auto v = fill(r, false, words, 16, {}, heaps, biases, &misses); + CHECK(v.size() == 16); + CHECK(v[0] == 5 * 32); // console bytes, not index x desktop increment + CHECK(v[1] == 3 * 16); // samplers: 16 a descriptor + CHECK(v[2] == 14); + CHECK(v[3] == 0x12345678u && v[4] == 0x45u); + CHECK(v[5] == 8); + CHECK(v[6] == 0x34500020u && v[7] == 0x12u); + CHECK(v[8] == 0); // all threads of every group + CHECK(v[9] == 0x77); + CHECK(v[10] == 0 && v[11] == 0 && v[12] == 0 && v[13] == 0); + CHECK(misses == 3); + // The bias is the bound view's, not the address's: a view bound through a copy whose offset ends in 4. + const auto w = fill(r, false, words, 16, {}, heaps, {{3, 4}}); + CHECK(w[5] == 4); + // A table made afresh gives its new offset. + const auto f = fill(r, false, words, 16, {{0, 4096 * 32}}, heaps, biases); + CHECK(f[0] == 4096 * 32 && f[1] == 3 * 16); + // Compute roots are not graphics roots. + const auto g = fill(r, true, words, 16, {}, heaps, biases); + CHECK(g[0] == 0 && g[2] == 0); +} + +void tables() +{ + HeapSpan heaps[2] = {{0x10000000, 1000, false}, {0x20000000, 100, true}}; + Roots r; + r.set_table(false, 0, 0x10000000 + 10 * 32); // a table with a CBV: fresh + r.set_table(false, 1, 0x10000000 + 990 * 32); // reaches past 999 of the host's 995: fresh + r.set_table(false, 2, 0x10000000 + 20 * 32); // SRVs only: mirrored in place + r.set_table(false, 3, 0x20000000); // a sampler table with a CBV entry: skipped + const std::uint32_t c = 3; + r.set_constants(false, 5, &c, 1, 0); + std::vector<GpuUsedResource> used = { + use(GpuResourceType::cbv, GpuRootType::table, 0, 0), + use(GpuResourceType::srv, GpuRootType::table, 2 * 8, 0), + use(GpuResourceType::srv, GpuRootType::table, 6 * 8, 1), + use(GpuResourceType::srv, GpuRootType::table, 1 * 8, 2), + use(GpuResourceType::uav, GpuRootType::table, 0, 2), + use(GpuResourceType::cbv, GpuRootType::table, 0, 3), + use(GpuResourceType::srv, GpuRootType::descriptor, 0, 4), // a root SRV: no table + }; + // A descriptor root state selects: byte offset 32 + (3 << 5) = 128 -> entry 4 of table 0. + std::vector<GpuRootIndexedView> indexed = {{0, 5, 0, 32, 5}}; + const auto plan = plan_tables(r, false, used.data(), used.size(), indexed.data(), indexed.size(), heaps, 2, + [](const HeapSpan&) { return 995u; }); + CHECK(plan.fresh.size() == 2); + if (plan.fresh.size() == 2) { + CHECK(plan.fresh[0].slot == 0 && plan.fresh[0].n == 5 && plan.fresh[0].selected == std::vector<std::uint32_t>{4}); + CHECK(plan.fresh[1].slot == 1 && plan.fresh[1].n == 7); + } + CHECK(plan.mirrored == (std::vector<std::size_t>{3, 4})); + CHECK(plan.skipped.size() == 1 && plan.skipped[0].first == 3 && plan.skipped[0].second == PlanSkip::sampler_or_unaligned); + // Keep the title table when the requested span extends past the heap. + Roots distant; + distant.set_table(false, 0, 0x10000000 + 998 * 32); + std::vector<GpuUsedResource> long_cbv = {use(GpuResourceType::cbv, GpuRootType::table, 4 * 8, 0)}; + const auto p2 = plan_tables(distant, false, long_cbv.data(), 1, nullptr, 0, heaps, 2, [](const HeapSpan& h) { return h.count; }); + CHECK(p2.fresh.empty() && p2.skipped.size() == 1 && p2.skipped[0].second == PlanSkip::too_long); +} + +void raw_views() +{ + RawWindow w; + CHECK(raw_window(0x1008, 100, true, &w) && w.first == 0x1000 && w.bytes == 108 && w.bias == 8); + CHECK(!raw_window(0x1008, 100, false, &w)); // unbiased and not on 16: null ("reads zeros") + CHECK(raw_window(0x1010, 100, false, &w) && w.first == 0x1010 && w.bytes == 100 && w.bias == 0); + CHECK(!raw_window(0x1010, 0, true, &w)); + CHECK(raw_elements(2) == 1 && raw_elements(10) == 2 && raw_elements(1ull << 40) == 0xffffffffu); + CHECK(constant_view_bytes(16) == 256 && constant_view_bytes(257) == 512 && constant_view_bytes(1 << 20) == 65536); + CHECK(root_cbv_bytes(1 << 20) == 65536 && root_cbv_bytes(100) == 100); +} + +// find_bounded: a title buffer [0x100000, 0x140000) inside a window [0x0, 0x1000000) whose desktop pages run on +// contiguously only up to 0x120000 (the window is cut there). +void find() +{ + const auto extent = [](std::uint64_t a, std::uint64_t* base, std::uint64_t* end) { + if (a < 0x100000 || a >= 0x140000) return false; + *base = 0x100000; + *end = 0x140000; + return true; + }; + static int window_token; + const auto window = [](std::uint64_t a, std::uint64_t n, void** buffer, std::uint64_t* offset) { + if (a + n > 0x1000000) return false; + if (!mutate && a < 0x120000 && a + n > 0x120000) return false; // mutate: the window "allows" everything + *buffer = &window_token; + *offset = a; + return true; + }; + const auto bounded = [&](std::uint64_t a, std::uint64_t* base, std::uint64_t* end) { + if (mutate) { // mutate: no title buffer bound, the window's end instead + *base = 0; + *end = 0x1000000; + return a < 0x1000000; + } + return extent(a, base, end); + }; + TitleBufferExtent inner, span; + CHECK(inner.consider(0x1800, 1, 0x1000, 0x8000, 1)); + CHECK(inner.consider(0x1800, 1, 0x1800, 0x100, 2)); + CHECK(!inner.consider(0x1800, 1, 0x1000, 0x8000, 1) && inner.end == 0x1900); + CHECK(span.consider(0x1800, 0x200, 0x1800, 0x100, 2)); + CHECK(span.consider(0x1800, 0x200, 0x1000, 0x8000, 1) && span.end == 0x9000); + Found f; + // Inside the buffer, before the cut: bounded by the cut (0x120000), not the window end. + CHECK(find_bounded(0x110000, 1, ~0ull, 0, bounded, window, &f) && f.known_extent && f.left == 0x10000 && f.cut_by_window); + // After the cut: bounded by the buffer's end. + CHECK(find_bounded(0x130000, 1, ~0ull, 0, bounded, window, &f) && f.left == 0x10000 && !f.cut_by_window); + // A cap (X2W_SHADERCFG_ROOT_UAV_MB) applies. + CHECK(find_bounded(0x130000, 1, 0x100, 0, bounded, window, &f) && f.left == 0x100); + // Memory no title buffer holds: refused without an allowance, bounded by it with one. + CHECK(!find_bounded(0x500000, 1, ~0ull, 0, bounded, window, &f) && !f.known_extent); + CHECK(find_bounded(0x500000, 1, ~0ull, 0x4000, bounded, window, &f) && f.left == 0x4000); + // More than is left: refused. + CHECK(!find_bounded(0x13ff00, 0x200, ~0ull, 0, bounded, window, &f)); +} + +void hashes() +{ + const auto of = [](const std::vector<std::array<std::uint32_t, 3>>& records) { + RecordHash h; + for (const auto& r : records) h.add(r[0], r[1], r[2]); + return h.value; + }; + std::set<std::uint64_t> seen; + bool distinct = true; + for (std::uint32_t a = 0; a < 64; ++a) + for (std::uint32_t b = 0; b < 64; ++b) + for (std::uint32_t c : {0u, 1u, 0x80000000u, 0xffffffffu}) { + distinct &= seen.insert(of({{a, b, c}})).second; + distinct &= seen.insert(of({{1, 2, 3}, {a, b, c}})).second; + distinct &= seen.insert(of({{a, b, c}, {1, 2, 3}, {0, 0, 0}})).second; + } + distinct &= seen.insert(of({})).second; + for (int n = 2; n < 100; ++n) distinct &= seen.insert(of(std::vector<std::array<std::uint32_t, 3>>(n, {0, 0, 0}))).second; + CHECK(distinct); // draw.rs records_that_differ_hash_apart + std::uint32_t record[8]{}; + RecordHash original; + original.add_record(record); + for (auto& word : record) { + word = 1; + RecordHash changed; + changed.add_record(record); + CHECK(original.value != changed.value); + word = 0; + } +} + +void dispatch() +{ + const std::uint32_t size[3] = {64, 4, 4}; + std::uint32_t out[3]; + const std::uint32_t t1[3] = {8847, 1, 1}; + dispatch_groups(t1, size, out); + CHECK(out[0] == 139 && out[1] == 1 && out[2] == 1); + const std::uint32_t t2[3] = {0, 12, 9}; + dispatch_groups(t2, size, out); + CHECK(out[0] == 0 && out[1] == 3 && out[2] == 3); + CHECK(mesh_groups(70000) == 65535 && mesh_groups(12) == 12); +} +} // namespace + +int main(int argc, char** argv) +{ + mutate = argc > 1 && std::strcmp(argv[1], "--mutate") == 0; + user_data(); + tables(); + raw_views(); + find(); + hashes(); + dispatch(); + std::printf("%s: %d failure(s)\n", mutate ? "gpu user data (mutated control)" : "gpu user data", failures); + return failures ? 1 : 0; +} diff --git a/tests/startup_gpu_warm_bad.cpp b/tests/startup_gpu_warm_bad.cpp new file mode 100644 index 0000000000..a0888b02d0 --- /dev/null +++ b/tests/startup_gpu_warm_bad.cpp @@ -0,0 +1,62 @@ +#include "startup_stubs/gpu_warm_bad.h" +#include <cstdio> +#include <cstring> +#include <fstream> +#include <sstream> + +using namespace x2w_gpu; + +namespace { +GpuCreateDesc compute(std::string_view shader) +{ + GpuCreateDesc desc{}; + desc.stage_count = 1; + desc.stages[0].stage = GpuStage::compute; + std::memcpy(desc.stages[0].key, shader.data(), 16); + return desc; +} +} + +int main(int argc, char** argv) +{ + const auto shader = "0123456789abcdef"; + const auto id = gpu_compute_pending_key(shader); + const auto good = compute(shader); + GpuWarmBad bad; + if (bad.contains(good, false)) return 1; + std::istringstream rows(" # comment\n\n\t" + id + "\tcomment\r\n" + id + " duplicate\n" + + "truncated " + gpu_compute_pending_key("0123456789abcdee") + "\n"); + bad.read(rows); + if (bad.keys.size() != 1 || !bad.contains(good, false) || bad.contains(good, true)) return 2; + if (bad.contains(compute("0123456789abcdee"), false)) return 3; + auto other = good; + other.stages[0].stage = GpuStage::pixel; + if (bad.contains(other, false)) return 4; + other = good; + other.stage_count = 2; + if (bad.contains(other, false)) return 5; + + if (argc == 2) { + std::ifstream file(argv[1]); + if (!file) return 6; + int count = 0; + for (std::string line; std::getline(file, line); ) { + // The human-readable comments serve only as an independent reference fixture here. + constexpr std::string_view marker = "[compute "; + const auto pos = line.find(marker); + if (pos == std::string::npos) continue; + const auto end = line.find(']', pos); + if (end != pos + marker.size() + 16) return 7; + const auto desc = compute(std::string_view(line).substr(pos + marker.size(), 16)); + GpuWarmBad one; + std::istringstream input(line); + one.read(input); + if (!one.contains(desc, false) || one.contains(desc, true)) return 8; + ++count; + } + if (!count) return 9; + std::printf("%d Rust compute annotations matched their independently recorded keys\n", count); + } + std::puts("warm-bad key filtering passed"); + return 0; +} diff --git a/tests/startup_heap_texture_check.py b/tests/startup_heap_texture_check.py new file mode 100644 index 0000000000..c5b123d6d9 --- /dev/null +++ b/tests/startup_heap_texture_check.py @@ -0,0 +1,91 @@ +"""Heap (bindless) textures are uploaded: X2W_HEAP_TEXTURE_UPLOAD=1 (src/startup_stubs/d3d12_draw.inl, LOCAL textures). + +A heap draw (manifest `heap 1`, tests/startup_draw_uav.cpp mode heaptex) reads texel (x, y) of an 8x4 RGBA8 texture +that only the title's view heap references (no table binds it); its title memory holds (10 + 20x, 30 + 40y, 7, 255). +With the switch the draw returns those texels for columns 0 and 1 and the log names the heap texture upload. Negative +control: without the switch the texture is never uploaded (texture_view(..., prepare = false)) and the texels are not +those values. + +With the layout check (third argument): entry 0 is a memory SRV (slot 70) of a console-swizzled BC1 surface written at +addrlib's addresses (layout 0x105, 9 mips; tests/gfx10_layout_check.cpp --write-tiled bc1_256_9mips_4k_s --addrlib), +so X2W_MEMORY_SRV_DETILE reaches a heap draw. The shader checks all 4096 blocks of mip 0. With both switches every +block matches. With DETILE alone (control) the texture is published but never uploaded, so the blocks mismatch: +DETILE needs HEAP_TEXTURE_UPLOAD for heap draws. + +Heap draws need the console's 32-byte view slots: with another increment (WARP) the draws are skipped and the check +reports 77. +""" +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_draw_uav_check import run_mode + +CLEAR = (0, 0, 255, 255) + + +def expected(): + return bytes(c for y in range(4) for x in range(8) + for c in ((10 + 20 * x, 30 + 40 * y, 7, 255) if x < 2 else CLEAR)) + + +def expected_detile(): + return bytes(c for y in range(4) for x in range(8) for c in ((255, 255, 0, 255) if x < 2 else CLEAR)) + + +def surface(directory, layout_check): + path = directory / "bc1_256_9mips_4k_s.bin" + result = subprocess.run([layout_check, "--write-tiled", "bc1_256_9mips_4k_s", path, "--addrlib"], capture_output=True, text=True) + if result.returncode == 0: + return path, "addrlib" + if result.returncode != 77: + raise AssertionError(f"--write-tiled --addrlib failed ({result.returncode}): {result.stdout}{result.stderr}") + subprocess.run([layout_check, "--write-tiled", "bc1_256_9mips_4k_s", path], check=True, capture_output=True) + return path, "gfx10_layout.h (plumbing only: built without addrlib)" + + +def check(directory, consumer, backend, layout_check=None): + results = {} + for mode in ("heaptex", "heaptex-off"): + got = run_mode(directory, consumer, backend, mode) + if got is None: + print("no existing-heap support or no adapter: skip") + return 77 + results[mode] = got + _, image, log = results["heaptex"] + increment = int(re.search(r"^view increment (\d+)$", log, re.M).group(1)) + if increment != 32: + if "heap draw skipped: descriptor increment is not 32" not in log: + raise AssertionError(f"increment {increment}: the heap draw was not skipped") + print(f"{backend}: heap texture upload NOT exercised (view increment {increment}; heap draws skipped as required)") + return 77 + if image != expected(): + raise AssertionError(f"switch on: pixels {image.hex()}\n expected {expected().hex()}") + for needle in ("X2W_HEAP_TEXTURE_UPLOAD=1", "x2w-draw heap textures: frame", "x2w-draw-rt first heap draw"): + if needle not in log: + raise AssertionError(f"switch on: log lacks {needle!r}\n{log[-4000:]}") + _, off_image, off_log = results["heaptex-off"] + if off_image[:8] == expected()[:8] or "x2w-draw heap textures" in off_log or "X2W_HEAP_TEXTURE_UPLOAD" in off_log: + raise AssertionError(f"switch off: the heap texture was uploaded: {off_image[:16].hex()}") + print(f"{backend}: heap-only texture uploaded and sampled (16 texels exact); switch off: not uploaded " + f"(columns 0-1 read {off_image[:8].hex()})") + if not layout_check: + return 0 + path, source = surface(directory, layout_check) + extra = {"X2W_TEST_HEAPTEX_SURFACE": str(path)} + _, image, log = run_mode(directory, consumer, backend, "heaptex-detile", extra) + if image != expected_detile() or "x2w-memsrv detiled memory SRV" not in log or "x2w-draw heap textures: frame" not in log: + raise AssertionError(f"detile + heap upload: pixels {image[:64].hex()} (expected every block to match)\n{log[-3000:]}") + _, control, control_log = run_mode(directory, consumer, backend, "heaptex-detile-noupload", extra) + if control[:8] == expected_detile()[:8] or "x2w-memsrv detiled memory SRV" not in control_log: + raise AssertionError(f"detile without heap upload: pixels {control[:16].hex()} (expected mismatches)") + print(f"{backend}: memory SRV 0x105 BC1 9 mips through the heap: all 4096 mip-0 blocks match with DETILE + " + f"HEAP_TEXTURE_UPLOAD ({source}); DETILE alone: published, not uploaded, mismatches") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_image_3d_check.py b/tests/startup_image_3d_check.py index 0cfc30d79e..4c6fa29e42 100644 --- a/tests/startup_image_3d_check.py +++ b/tests/startup_image_3d_check.py @@ -103,10 +103,13 @@ def controls(): assert 'srv 0 tex2d table 0 0' in manifest, manifest print('dim 2D (same words, dim field changed): Texture2D r0, float2(F(v0), F(v1)); manifest srv 0 tex2d') + # dim:SQ_RSRC_IMG_1D is a Texture1D sampled at u alone, never as 2D (2D arrays: startup_image_2d_array_check.py). pipe = translate(WORDS_1D) - assert 'Texture1D<float4> r0' in pipe.hlsl_ps() - assert 'r0.Sample(q0, F(v0))' in pipe.hlsl_ps() - assert 'srv 0 tex1d table 0 0' in pipe.manifest() + ps, manifest = pipe.hlsl_ps(), pipe.manifest() + assert 'Texture1D<float4> r0 : register(t0);' in ps and 'Texture2D' not in ps and 'Texture3D' not in ps, ps + assert 't = r0.Sample(q0, F(v0));' in ps, ps + assert 'srv 0 tex1d table 0 0' in manifest, manifest + print('dim 1D (same words, dim field changed): Texture1D r0, Sample(q0, F(v0)); manifest srv 0 tex1d') unsupported = WORDS_1D.replace(bytes.fromhex('000f80f0'), bytes.fromhex('180f80f0')) try: translate(unsupported) diff --git a/tests/startup_image_d16_check.py b/tests/startup_image_d16_check.py new file mode 100644 index 0000000000..d90a98bdfc --- /dev/null +++ b/tests/startup_image_d16_check.py @@ -0,0 +1,87 @@ +"""Packed D16 results of image_sample / image_sample_lz in tools/startup/gfx2hlsl.py. + +Synthetic gfx1013 words: the 2D form of the startup_image_3d_check fixture with its image_sample word changed to +dmask 0x3 (0x7 for the three-channel case) and the D16 bit (MIMG gfx10 bit 63, LLVM MIMGInstructions.td +`Inst{63} = d16`) set, writing v0 (v[0:1] for three channels). + +Semantics (gfx9+ packed D16, LLVM GCNSubtarget::hasPackedD16VMem, SIISelLowering::adjustLoadValueType): every +enabled channel of the result is converted to binary16 and two channels share one VGPR, the first in bits 15:0. +After an odd channel count the high half of the last VGPR is undefined; the translation writes 0 there. +Checked on the emitted HLSL text (the binary16 conversion is HLSL f32tof16; its rounding against the hardware's is +NOT verified here). +Controls (refused): d16 on image_load (an integer texel format would be converted as a float); d16 on +image_sample_l (its own modifier list). +Negative control: the same words without the D16 bit give four unpacked VGPR writes, not the packed one. +""" +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 +import startup_image_3d_check as T # noqa: E402 + +BASE = bytes.fromhex('080f80f00000c400') # image_sample v[0:3], v[0:1], s[16:23], s[24:27] dmask:0xf 2D + + +def words(word0, word1): + return T.WORDS_2D.replace(BASE, struct.pack('<2I', word0, word1)) + + +def asm(ws): + return [x[3] for x in G.decode(ws) if x[3].startswith('image')][0] + + +def ps_of(ws): + return T.translate(ws).hlsl_ps() + + +def refused(ws, label): + try: + ps_of(ws) + except G.Unsupported as error: + return str(error) + raise AssertionError('accepted: %s (%s)' % (label, asm(ws))) + + +def main(): + two = words(0xf0800308, 0x80c40000) + assert asm(two) == 'image_sample v0, v[0:1], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_2D d16', asm(two) + ps = ps_of(two) + line = 'v0 = f32tof16(t.x) | (f32tof16(t.y) << 16);' + assert line in ps and 'v1 = U(t.y)' not in ps, ps + three = words(0xf0800708, 0x80c40000) + assert asm(three) == 'image_sample v[0:1], v[0:1], s[16:23], s[24:27] dmask:0x7 dim:SQ_RSRC_IMG_2D d16', asm(three) + ps3 = ps_of(three) + assert 'v0 = f32tof16(t.x) | (f32tof16(t.y) << 16);' in ps3 and 'v1 = f32tof16(t.z);' in ps3, ps3 + # lz form (image_sample_lz opcode 0x27): same packing + lz = words(0xf09c0308, 0x80c40000) + assert asm(lz) == 'image_sample_lz v0, v[0:1], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_2D d16', asm(lz) + assert 't = r0.SampleLevel(q0, float2(F(v0), F(v1)), 0);' in ps_of(lz) and line in ps_of(lz), ps_of(lz) + + # Controls. + load = words(0xf0001308, 0x80040000) # image_load v0, v[0:1], s[16:23] dmask:0x3 unorm d16 + assert asm(load).startswith('image_load v0, v[0:1], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D') and 'd16' in asm(load), asm(load) + assert 'modifier d16' in refused(load, 'image_load d16') + wide = words(0xf0800308, 0x80c40000).replace(struct.pack('<2I', 0xf0800308, 0x80c40000), + struct.pack('<2I', 0xf0800f08, 0x80c40000)) # dmask 0xf into v[0:1] ok + assert asm(wide) == 'image_sample v[0:1], v[0:1], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D d16', asm(wide) + ps4 = ps_of(wide) + assert 'v1 = f32tof16(t.z) | (f32tof16(t.w) << 16);' in ps4, ps4 + samplel = words(0xf0900308, 0x80c40000) # image_sample_l ... d16 + assert asm(samplel).startswith('image_sample_l ') and 'd16' in asm(samplel), asm(samplel) + assert 'image_sample_l modifier d16' in refused(samplel, 'image_sample_l d16') + + # Negative control: without D16 the result is four unpacked writes. + plain = words(0xf0800f08, 0x00c40000) + assert 'd16' not in asm(plain) + ps0 = ps_of(plain) + assert 'v0 = U(t.x);' in ps0 and 'f32tof16' not in ps0, ps0 + print('image d16: sample and sample_lz pack 2 and 3 and 4 channels into binary16 halves; ' + 'image_load d16 and image_sample_l d16 refused; plain words unpacked') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_get_lod_check.py b/tests/startup_image_get_lod_check.py new file mode 100644 index 0000000000..36527abb7b --- /dev/null +++ b/tests/startup_image_get_lod_check.py @@ -0,0 +1,116 @@ +"""image_get_lod on a 2D texture in tools/startup/gfx2hlsl.py. + +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). Lowered as HLSL CalculateLevelOfDetail / +CalculateLevelOfDetailUnclamped, which take implicit derivatives like Sample, so the stage must be straight-line +with every lane active, or X2W_PS_QUAD_DIVERGENT=1 (forward control flow; marked in the manifest). + +Fixture: 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) and, for the second form, dmask 0x3. +Checks: dmask 0x1 and 0x3 lower to the two calls on the sampler; controls (refused): dmask 0x4, a 2D array, the +stage after a branch without the switch (accepted with it, `quaddivergent 1`), and without op_image_get_lod +(negative control: refused as before). + draw <dxc> [fxc]: compile the dmask 0x3 stage with dxc ps_6_0 (and fxc ps_5_1). +""" +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE.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_sampler_heap_check import VS_WORDS, root_blob # noqa: E402 + +AT = 0x34 # the MIMG instruction of the c_lz fixture + + +def stage(dmask=1, dim=1, branch=False): + w = bytearray(C.WORDS['lz']) + w0, w1 = struct.unpack_from('<II', w, AT) + w0 = w0 & ~(0x7f << 18) & ~(0xf << 8) & ~(7 << 3) | 0x60 << 18 | dmask << 8 | dim << 3 + struct.pack_into('<II', w, AT, w0, w1) + if dmask == 3: # export v4, v5 + struct.pack_into('<II', w, 0x40, 0xf800180f, 4 | 5 << 8 | 4 << 16 | 5 << 24) + code = bytes(w) + if branch: # s_cbranch_scc0 to the next instruction first: control flow before the read + code = code[:0x34] + struct.pack('<I', 0xbf840000) + code[0x34:] + return code + + +def ps(code, switch=False): + saved = os.environ.pop('X2W_PS_QUAD_DIVERGENT', None) + if switch: + os.environ['X2W_PS_QUAD_DIVERGENT'] = '1' + try: + pipe = G.Pipeline(VS_WORDS, code, root_blob(flags=0)) + return pipe, pipe.hlsl_ps() + finally: + os.environ.pop('X2W_PS_QUAD_DIVERGENT', None) + if saved is not None: + os.environ['X2W_PS_QUAD_DIVERGENT'] = saved + + +def refused(code, text, switch=False): + try: + ps(code, switch) + except G.Unsupported as error: + assert text in str(error), str(error) + else: + raise AssertionError('accepted, expected %r' % text) + + +def controls(): + listing = [a for _, _, _, a in G.decode(stage())] + assert 'image_get_lod v4, v[0:1], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D' in listing, listing + _, text = ps(stage()) + call = 't = float4(r0.CalculateLevelOfDetail(q0, float2(F(v0), F(v1))), ' \ + 'r0.CalculateLevelOfDetailUnclamped(q0, float2(F(v0), F(v1))), 0.0, 0.0);' + assert call in text and 'v4 = U(t.x);' in text, text + _, text = ps(stage(dmask=3)) + assert 'v4 = U(t.x);' in text and 'v5 = U(t.y);' 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 outside straight-line code with every lane active') + pipe, text = ps(stage(branch=True), switch=True) + assert call in text and 'quaddivergent 1' in pipe.manifest(), pipe.manifest() + saved = G.Stage.op_image_get_lod + del G.Stage.op_image_get_lod + try: + refused(stage(), 'image_get_lod') + finally: + G.Stage.op_image_get_lod = saved + print('image_get_lod: CalculateLevelOfDetail / Unclamped for dmask 0x1 and 0x3; dmask 0x4, 2D array and a ' + 'branch without the switch refused, accepted with it (quaddivergent 1); refused without the handler') + + +def compile_check(dxc, fxc=None): + _, text = ps(stage(dmask=3)) + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / 'ps.hlsl' + path.write_text(text) + runs = [('dxc', [dxc, '-T', 'ps_6_0', '-E', 'main', '-Fo', str(Path(tmp) / 'a.cso'), str(path)])] + if fxc: + runs.append(('fxc', [fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', str(Path(tmp) / 'b.cso'), str(path)])) + for kind, args in runs: + r = subprocess.run(args, capture_output=True, text=True, timeout=60) + if r.returncode: + raise AssertionError('%s: %s' % (kind, r.stderr[-1500:])) + print('%s compiles the dmask 0x3 stage' % kind) + + +def main(): + controls() + if len(sys.argv) > 1: + if sys.argv[1] != 'draw': + raise SystemExit(__doc__) + compile_check(*sys.argv[2:]) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_invariant_check.py b/tests/startup_image_invariant_check.py new file mode 100644 index 0000000000..04cd70e107 --- /dev/null +++ b/tests/startup_image_invariant_check.py @@ -0,0 +1,99 @@ +"""Lane-invariant image reads and the s_brev_b32 constant fold (tools/startup/gfx2hlsl.py). + +1. image_load / image_sample_lz of a bound texture (rN) through a fixed sampler at lane-invariant coordinates gives + the same value in every lane (no implicit derivatives: same texel or same filtered value), so the destination + VGPRs join uniform_v and a later v_readfirstlane_b32 of them is exact (measured form: a 1x1 pass loading texel + (0, 0) with a16 and v0 = 0, then sampling a 1D texture at a coordinate computed from it). Controls: a + coordinate VGPR not proven invariant, and image_sample (implicit derivatives), leave the destination out. +2. s_brev_b32 of an inline constant or a constant SGPR is folded (RDNA 2 ISA SOP1 S_BREV_B32: D = S0 with bits + reversed; 40 -> 0x14000000, an inline sampler word); a run-time source keeps reversebits(). +""" +import os +import struct +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, '..', 'tools', 'startup')) +sys.path.insert(0, HERE) +import gfx2hlsl as G # noqa: E402 +from startup_scalar_bits_check import sop1 # noqa: E402 + + +class Pipe: + sampler_heap = False + root = {'params': [], 'flags': 0} + resource = G.Pipeline.resource + + def __init__(self): + self.features = frozenset() + self.resources, self.uds, self.modified, self.heapvars, self.notes = {}, [], set(), [], set() + self.samplers = {} + + def ud(self, source): + if source not in self.uds: + self.uds.append(source) + return self.uds.index(source) + + def sampler(self, key, comparison=False): + return 'q0' + + +def stage(): + s = G.Stage(Pipe(), 'ps', b'') + s.lines, s.pc = [], 0 + s.uniform_v, s.partial_uniform, s.lane_s, s.masks = set(), {}, set(), set() + s.exec_known = True + for i in range(8): + s.sym[24 + i] = ('desc', ('table', 1), 0x20, i) + for i in range(4): + s.sym[20 + i] = ('const', 0) + for i in range(8): + s.sym[32 + i] = ('desc', ('table', 1), 0x40, i) # a 1D texture + return s + + +def main(): + s = stage() + s.set_v(0, '0u') + assert 0 in s.uniform_v + s.one('image_load', 'image_load v[2:3], v[0:1], s[24:31] dmask:0xa dim:SQ_RSRC_IMG_2D unorm a16') + assert {2, 3} <= s.uniform_v, (s.lines, s.uniform_v) + s.one('image_sample_lz', 'image_sample_lz v1, v2, s[32:39], s[20:23] dmask:0x1 dim:SQ_RSRC_IMG_1D') + assert 1 in s.uniform_v, (s.lines, s.uniform_v) + s.one('v_readfirstlane_b32', 'v_readfirstlane_b32 s22, v1') + assert s.lines[-1] == 's22 = v1;', s.lines + t = stage() + t.one('image_load', 'image_load v[2:3], v[5:6], s[24:31] dmask:0xa dim:SQ_RSRC_IMG_2D unorm a16') + assert not {2, 3} & t.uniform_v, t.uniform_v + try: + t.one('v_readfirstlane_b32', 'v_readfirstlane_b32 s22, v2') + except G.Unsupported as error: + assert 'proven uniform' in str(error) + else: + raise AssertionError('readfirstlane of a lane-dependent load accepted') + u = stage() + u.set_v(0, '0u') + u.one('image_sample', 'image_sample v1, v0, s[32:39], s[20:23] dmask:0x1 dim:SQ_RSRC_IMG_1D') + assert 1 not in u.uniform_v, u.uniform_v + print('image_invariant: load and lz at invariant coordinates join uniform_v (readfirstlane exact); a ' + 'lane-dependent coordinate and an implicit-derivative sample do not') + + for words, want in (([sop1(0x0b, 10, 0x80 + 40)], ('const', 0x14000000)),): + _, _, name, text = G.decode(struct.pack('<I', words[0]))[0] + assert text == 's_brev_b32 s10, 40', text + v = stage() + v.one(name, text) + assert v.sym.get(10) == want, (v.sym.get(10), v.lines) + w = stage() + w.one('s_brev_b32', 's_brev_b32 s10, s3') + assert w.lines == ['s10 = reversebits(s3);'], w.lines + for x in (0, 1, 40, 0x80000000, 0x12345678, 0xffffffff): + v = stage() + v.sym[3] = ('const', x) + v.one('s_brev_b32', 's_brev_b32 s10, s3') + assert v.sym[10] == ('const', int('{:032b}'.format(x)[::-1], 2)), (x, v.sym[10]) + print('brev: constant sources folded (6 values + the inline 40 -> 0x14000000); run-time source unchanged') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_sample_b_local_check.py b/tests/startup_image_sample_b_local_check.py new file mode 100644 index 0000000000..553fc827e8 --- /dev/null +++ b/tests/startup_image_sample_b_local_check.py @@ -0,0 +1,82 @@ +"""image_sample_b (sample with an LOD bias) in tools/startup/gfx2hlsl.py. + +The fixture is the source-built pixel stage of startup_image_sample_l_check.py (v0 = 0.5, v1 = 0.25, v2 = 1.0, +v3 = 2.0; texture from descriptor table 0, all-zero constant sampler) with its MIMG opcode set to 0x25, which the +decoder names image_sample_b (LLVM MIMGInstructions.td, gfx10 IMAGE_SAMPLE_B). The bias is the FIRST address dword, +before the coordinates (LLVM AMDGPUImageDimIntrinsics: sample_b has ExtraAddrArgs [bias]), so v[0:2] is +bias v0, u v1, v v2 and the lowering must be SampleBias(q0, float2(F(v1), F(v2)), F(v0)). + +SampleBias needs implicit derivatives like Sample, so it is lowered only where Sample is (straight-line code with +every lane active); elsewhere it is refused, not sampled at level 0 (which would drop the bias). +Controls: before the change the stage refused `image_sample_b` (reproduced by removing the handler); a branch +before the sample and a16 are refused; the plain image_sample of the same words keeps its +Sample lowering. +""" +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_image_sample_l_check import WORDS # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, root_blob # noqa: E402 + +LWE = bytes.fromhex('080f92f0') # the sample_l lwe word of the fixture, at offset 0x30 + + +def program(op, flags=0, prefix_branch=False): + w = bytearray(WORDS['lwe']) + i = w.find(LWE) + assert i == 0x30, i + w[i:i + 4] = struct.pack('<I', 0xf0900f08 & ~(0x7f << 18) | op << 18 | flags) # opcode [24:18] + if prefix_branch: + # replace s_waitcnt lgkmcnt(0) (0x2c) by s_cbranch_scc0 +0 (to the next instruction): a block boundary + w[0x2c:0x30] = struct.pack('<I', 0xbf840000) + return bytes(w) + + +def ps_text(code): + return G.Pipeline(VS_WORDS, code, root_blob()).hlsl_ps() + + +def refused(code, text): + try: + ps_text(code) + except G.Unsupported as error: + assert text in str(error), (text, str(error)) + return + raise AssertionError('accepted, expected %r' % text) + + +def main(): + code = program(0x25) + asm = G.decode(code)[10][3] + assert asm == 'image_sample_b v[4:7], v[0:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D', asm + ps = ps_text(code) + assert 't = r0.SampleBias(q0, float2(F(v1), F(v2)), F(v0));' in ps, ps + for comp, reg in zip('xyzw', range(4, 8)): + assert 'v%d = U(t.%s);' % (reg, comp) in ps, ps + # the plain sample of the same address keeps its lowering (coordinates v0, v1) + plain = ps_text(program(0x20)) + assert 't = r0.Sample(q0, float2(F(v0), F(v1)));' in plain, plain + # negative control: without the handler the stage refuses as before + saved = G.Stage.op_image_sample_b + del G.Stage.op_image_sample_b + try: + refused(code, 'image_sample_b') + finally: + G.Stage.op_image_sample_b = saved + refused(program(0x25, prefix_branch=True), 'image_sample_b outside straight-line code') + assert G.decode(program(0x25, prefix_branch=True))[9][3].startswith('s_cbranch_scc0') + a16 = bytearray(program(0x25)) + a16[0x34:0x38] = struct.pack('<I', struct.unpack_from('<I', a16, 0x34)[0] | 1 << 30) # A16 (second dword bit 30) + assert G.decode(bytes(a16))[10][3].endswith(' a16'), G.decode(bytes(a16))[10][3] + refused(bytes(a16), 'image_sample_b form') + print('image_sample_b: SampleBias with the bias from the first address dword; controls: refused without the ' + 'handler, after a branch, with a16; plain sample unchanged') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_sample_d_check.py b/tests/startup_image_sample_d_check.py new file mode 100644 index 0000000000..2bcfef30bd --- /dev/null +++ b/tests/startup_image_sample_d_check.py @@ -0,0 +1,78 @@ +"""image_sample_d (sample with explicit derivatives) in tools/startup/gfx2hlsl.py. + +The fixture is the source-built pixel stage of startup_image_sample_l_check.py (v0 = 0.5, v1 = 0.25, v2 = 1.0, +v3 = 2.0; texture from descriptor table 0, all-zero constant sampler). Its MIMG opcode is set to 0x22, which the +decoder names image_sample_d; the 2D address is then six dwords, v[0:5]. + +LLVM IntrinsicsAMDGPU.td orders the address as GradientArgs and then CoordSliceArgs (AMDGPUDimProfile.AddrArgs). +For 2D, GradientArgs are dsdh, dtdh, dsdv, dtdv (AMDGPUDimProps: d<c>dh for each coordinate, then d<c>dv). So v0, +v1 are the horizontal (ddx) gradient, v2, v3 the vertical (ddy) one, and v4, v5 are u and v: +SampleGrad(q0, float2(F(v4), F(v5)), float2(F(v0), F(v1)), float2(F(v2), F(v3))). + +SampleGrad needs no implicit derivatives, so unlike Sample and SampleBias it is lowered after a branch too. +Controls: without the handler the stage refuses `image_sample_d` as before; a16 is refused (the gradients would be +packed too). The pixel HLSL compiles with dxc ps_6_0 and, when found, fxc ps_5_1. +""" +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_sample_b_local_check import program, ps_text, refused # noqa: E402 + +EXPECTED = 't = r0.SampleGrad(q0, float2(F(v4), F(v5)), float2(F(v0), F(v1)), float2(F(v2), F(v3)));' + + +def compile_ps(text): + results = [] + fxc = os.path.join(os.path.dirname(M.DXC), 'fxc.exe') + for tool, args in ((M.DXC, ['-nologo', '-T', 'ps_6_0']), (fxc, ['/nologo', '/T', 'ps_5_1'])): + if not os.path.isfile(tool): + results.append('%s not found' % os.path.basename(tool)) + continue + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'ps.hlsl') + open(path, 'w').write(text) + r = subprocess.run([tool] + args + ['-E' if tool == M.DXC else '/E', 'main', + '-Fo' if tool == M.DXC else '/Fo', path + '.cso', path], capture_output=True, text=True) + assert r.returncode == 0, (tool, r.stdout, r.stderr) + results.append('%s %s ok' % (os.path.basename(tool)[:3], args[-1])) + return ', '.join(results) + + +def main(): + code = program(0x22) + asm = G.decode(code)[10][3] + assert asm == 'image_sample_d v[4:7], v[0:5], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D', asm + ps = ps_text(code) + assert EXPECTED in ps, ps + for comp, reg in zip('xyzw', range(4, 8)): + assert 'v%d = U(t.%s);' % (reg, comp) in ps, ps + # after a branch (not straight-line): still SampleGrad, explicit derivatives + branched = ps_text(program(0x22, prefix_branch=True)) + assert EXPECTED in branched, branched + compiled = compile_ps(ps) + # controls + saved = G.Stage.op_image_sample_d + del G.Stage.op_image_sample_d + try: + refused(code, 'image_sample_d') + finally: + G.Stage.op_image_sample_d = saved + a16 = bytearray(code) + a16[0x34:0x38] = struct.pack('<I', struct.unpack_from('<I', a16, 0x34)[0] | 1 << 30) # A16 (second dword bit 30) + assert G.decode(bytes(a16))[10][3].endswith(' a16'), G.decode(bytes(a16))[10][3] + refused(bytes(a16), 'image_sample_d form') + print('image_sample_d: SampleGrad(uv = v4,v5; ddx = v0,v1; ddy = v2,v3), also after a branch; %s; controls: ' + 'refused without the handler, with a16' % compiled) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_sample_implicit_lod_check.py b/tests/startup_image_sample_implicit_lod_check.py new file mode 100644 index 0000000000..e0fe755c7f --- /dev/null +++ b/tests/startup_image_sample_implicit_lod_check.py @@ -0,0 +1,69 @@ +"""An implicit-LOD image_sample in branched pixel-stage code (X2W_PS_IMPLICIT_LOD=1). + +image_sample takes its LOD from derivatives of the quad's address VGPRs. Without the gate, a sample after a branch +(or with exec modified) is lowered as SampleLevel(..., 0): mip 0 whatever the derivatives say. With the gate it is +Sample in a pixel stage, never level 0: before the first branch as before; in branched code on the assumption +that the four lanes of each quad take one path (manifest `quaddivergent 1`, as image_sample_b under +X2W_PS_QUAD_DIVERGENT); in a loop that is not a proven waterfall it is refused (lanes of a quad can sit in +different iterations of the dispatch loop). + +Programs: tests/startup_image_3d_check.py WORDS_2D (straight line), the same with `s_cbranch_execz` to the next +instruction before the sample (branched, same result), and with `s_cmp_eq_u32 s9, 0; s_cbranch_scc0` back to the +sample (a loop). Negative control: gate off keeps every output as it was. +""" +import os +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_image_3d_check import WORDS_2D, VS_WORDS, root_blob # noqa: E402 + +SAMPLE = bytes.fromhex('080f80f00000c400') # image_sample v[0:3], v[0:1], s[16:23], s[24:27] dmask:0xf dim:2D +EXECZ = struct.pack('<I', 0xbf880000) # s_cbranch_execz to the next instruction +LOOPBACK = struct.pack('<II', 0xbf060000 | 128 << 8 | 9, 0xbf840000 | 0xfffc) # s_cmp_eq_u32 s9, 0; s_cbranch_scc0 back +BRANCH = WORDS_2D.replace(SAMPLE, EXECZ + SAMPLE) +LOOP = WORDS_2D.replace(SAMPLE, EXECZ + SAMPLE + LOOPBACK) +IMPLICIT = 't = r0.Sample(q0, float2(F(v0), F(v1)));' +LEVEL0 = 't = r0.SampleLevel(q0, float2(F(v0), F(v1)), 0);' + + +def translate(words, gate): + os.environ['X2W_PS_IMPLICIT_LOD'] = '1' if gate else '0' + try: + pipe = G.Pipeline(VS_WORDS, words, root_blob()) + return [line.strip() for line in pipe.hlsl_ps().splitlines() if line.strip().startswith('t = ')], \ + pipe.manifest().splitlines() + finally: + os.environ.pop('X2W_PS_IMPLICIT_LOD', None) + + +def main(): + text = [a for _, _, _, a in G.decode(LOOP)] + assert text[-6:-2] == ['image_sample v[0:3], v[0:1], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D', + 's_cmp_eq_u32 s9, 0', 's_cbranch_scc0 label_0x34', 's_waitcnt vmcnt(0)'], text + assert text[-7] == 's_cbranch_execz label_0x34', text + # gate off: unchanged (the level-0 fallback after a branch) + assert translate(WORDS_2D, False)[0] == [IMPLICIT] + assert translate(BRANCH, False)[0] == [LEVEL0] + assert translate(LOOP, False)[0] == [LEVEL0] + # gate on + calls, manifest = translate(WORDS_2D, True) + assert calls == [IMPLICIT] and 'quaddivergent 1' not in manifest, manifest + calls, manifest = translate(BRANCH, True) + assert calls == [IMPLICIT] and 'quaddivergent 1' in manifest, (calls, manifest) + try: + translate(LOOP, True) + except G.Unsupported as error: + assert 'image_sample at 0x34 with implicit derivatives in a loop' in str(error), str(error) + else: + raise AssertionError('implicit sample in a loop accepted') + print('implicit LOD: gate off unchanged (level 0 after a branch); gate on: Sample before and after a branch ' + '(quaddivergent 1 after it), refused in a loop') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_sample_l_check.py b/tests/startup_image_sample_l_check.py index d406e77dc8..7468b9edd0 100644 --- a/tests/startup_image_sample_l_check.py +++ b/tests/startup_image_sample_l_check.py @@ -251,11 +251,16 @@ def controls(): refused('d16', 'image_sample_l modifier d16') # half-precision result layout refused('r128', 'image_sample_l modifier r128') # four-dword resource descriptor refused('dmask0', 'empty dmask') - refused('dim1d', 'unverified 1D image sample address or modifiers') refused('msaa', 'image dimension SQ_RSRC_IMG_') + # dim:SQ_RSRC_IMG_1D is a Texture1D (manifest kind tex1d, bound as a Texture1D view by the draw path): the + # address is u and then the level, never sampled as 2D. + one = stage('dim1d') + assert 'Texture1D<float4> r0' in one and 'Texture2D' not in one, one + assert re.search(r'\w+\.SampleLevel\(\w+, F\(v0\), F\(v1\)\);', one), one 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; ' + '1D: Texture1D SampleLevel(u, level)') # 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_indirect_dispatch.hlsl b/tests/startup_indirect_dispatch.hlsl new file mode 100644 index 0000000000..7976cc94c3 --- /dev/null +++ b/tests/startup_indirect_dispatch.hlsl @@ -0,0 +1,19 @@ +// Shaders for tests/startup_indirect_dispatch.cpp. Root signature (built by the test): +// [0] root UAV u0 (raw buffer), [1] four 32-bit constants b0. +RWByteAddressBuffer target : register(u0); +cbuffer Values : register(b0) { uint4 values; }; + +// Writer: stores a Dispatch argument record (values.xyz) at byte offset values.w of u0. +[numthreads(1, 1, 1)] +void Writer() +{ + target.Store3(values.w, values.xyz); +} + +// Counter: every thread group adds 1 at byte offset values.w of u0. +[numthreads(1, 1, 1)] +void Counter() +{ + uint before; + target.InterlockedAdd(values.w, 1, before); +} diff --git a/tests/startup_indirect_dispatch_local.cpp b/tests/startup_indirect_dispatch_local.cpp new file mode 100644 index 0000000000..dbe92a6dd3 --- /dev/null +++ b/tests/startup_indirect_dispatch_local.cpp @@ -0,0 +1,353 @@ +// ExecuteIndirect (list slot 61) through the stand-in with GPU-written Dispatch arguments. +// +// startup_indirect_dispatch <warp|hardware> <gpu|no-writer|zero|off|huge|huge-product> +// (huge / huge-product: a first record over the argument guard's bounds, which must not execute) +// (X2W_D3D12_RENDER=1 X2W_D3D12_PERMISSIVE=1; "off" also X2W_INDIRECT_OFF=1) +// +// Title memory is one private VirtualAlloc block. The argument buffer is a slot-133 placed buffer at +// an address that is NOT 64 KiB-aligned, so the stand-in backs the wrapper with a private committed +// copy ("not aliased"): only the in-place window over the title pages holds what the GPU writes. The +// CPU puts a sentinel record {7, 1, 1} at offset 0 and {5, 1, 1} at offset 0x14 (4-aligned, like the +// title's DrawIndexed/DispatchMesh offsets). One list, recorded through the console slots: +// +// 1. Writer (container compute pipeline, slot 62 + <key>.cs.dxbc in X2W_SHADER_CACHE) stores +// {3, 2, 1} at offset 0 and {1, 1, 1} at offset 0x14 (mode zero: {0, 1, 1} and {0, 1, 1}; +// mode no-writer: no writer dispatch). +// 2. Counter pipeline bound, root UAV on the counter; ExecuteIndirect(Dispatch signature, 1, args, 0) +// and ExecuteIndirect(..., args, 0x14): every group adds 1 to the counter. +// +// Expected counter after the fence: gpu 3*2*1 + 1 = 7; zero 0; no-writer 7 + 5 = 12 (the sentinels); +// off 0 (nothing executed). +// +// LOCAL memcut, the argument ring (d3d12_upload_ring.inl, indirect instance) with a 1 KiB test ring +// (X2W_INDIRECT_RING_TEST_KIB=1, set here): gpu mode plus 40 more ExecuteIndirect calls on the second record, all in +// ONE list, so the 42 records (256 bytes each) need ten times the ring. +// wrap chain: counter 7 + 40 = 47; chunks made >= 10; no slot reused while held; would-have-wrapped > 0. +// wrap-legacy X2W_INDIRECT_RING=legacy, the negative control: "slots reused while a list holding them had not +// executed" > 0. The counter is still 47: on one queue each call copies its record right before it +// reads it, so a reused slot is rewritten in order (the hazard is two queues at once, not tested). +// wrap-cap X2W_INDIRECT_RING_TEST_CAP_CHUNKS=2 (8 slots): the calls past the cap are refused (skipped as +// no-ring): counter 7 + 6 = 13, refusals 34. +// +// LOCAL (scene), X2W_MESH_RECORD_TRACE (d3d12_record_trace.inl) in a traced frame (X2W_D3D12_TRACE_ALL=1): +// rectrace the title pattern behind a zero argument record. The CPU leaves {0, 1, 1} at offset 0. List 1: +// the writer resets the record to {0, 1, 1} (Dispatch 1x1x1). List 2: the counter shader on the +// record raises X by 3 (Dispatch 3x1x1, InterlockedAdd at offset 0), then ExecuteIndirect(args, 0) +// runs 3 groups of the counter on the counter word: counter 3. Both lists are recorded before +// either is submitted, so the record reads 0 at record time and 3 at frame end. The log must show +// both dispatches with a root UAV range over the record (x2w-frame cx-uav), the record line +// (at record 0 1 1, at end 3 1 1), the totals and the writers lines naming both pipelines. +// rectrace-off the same without X2W_MESH_RECORD_TRACE (the control): counter 3, and none of those lines. The records in title memory must read what the writer stored (sentinels +// for no-writer). Exit 0 pass, 77 capability skip (no adapter, or the adapter cannot open an +// existing heap over process memory), other values name the failing step. +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <iterator> +#include <string> +#include <vector> + +#include "startup_indirect_writer.h" +#include "startup_indirect_counter.h" + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) unsigned long long x2w_upload_ring_test(int what); // LOCAL memcut: ring counters +extern "C" __declspec(dllimport) void x2w_d3d12_record_trace_report(); // LOCAL scene: X2W_MESH_RECORD_TRACE + +namespace { +using Word = std::uint64_t; +template <class T> Word arg(T* value) { return reinterpret_cast<Word>(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word); + return reinterpret_cast<Slot>((*static_cast<void***>(object))[index])(object, a, b, c, d, e, f); +} +bool ok(Word hr) { return SUCCEEDED(static_cast<HRESULT>(hr)); } +std::uint64_t fnv(const void* data, std::size_t bytes, std::uint64_t hash = 1469598103934665603ull) +{ + for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ static_cast<const unsigned char*>(data)[i]) * 1099511628211ull; + return hash; +} +bool write_file(const std::wstring& path, const void* data, std::size_t bytes) +{ + FILE* f = _wfopen(path.c_str(), L"wb"); + if (!f) return false; + const bool written = std::fwrite(data, 1, bytes, f) == bytes; + return std::fclose(f) == 0 && written; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) return 2; + std::string mode = argv[2]; + const bool huge = mode == "huge", huge_product = mode == "huge-product"; + const bool wrap = mode == "wrap", wrap_legacy = mode == "wrap-legacy", wrap_cap = mode == "wrap-cap"; + const std::string ring_mode = mode; + if (wrap || wrap_legacy || wrap_cap) { + SetEnvironmentVariableA("X2W_INDIRECT_RING_TEST_KIB", "1"); + if (wrap_legacy) SetEnvironmentVariableA("X2W_INDIRECT_RING", "legacy"); + if (wrap_cap) SetEnvironmentVariableA("X2W_INDIRECT_RING_TEST_CAP_CHUNKS", "2"); + mode = "gpu"; // the gpu case, plus the extra calls below + } + const int extra_calls = wrap || wrap_legacy || wrap_cap ? 40 : 0; + const bool rectrace = mode == "rectrace", rectrace_off = mode == "rectrace-off"; + if (mode != "gpu" && mode != "no-writer" && mode != "zero" && mode != "off" && !huge && !huge_product && !rectrace && !rectrace_off) + return 2; + ComPtr<IDXGIFactory6> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr<IDXGIAdapter> adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr<IDXGIAdapter1> candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) 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 (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + std::printf("adapter=%ls mode=%s\n", adapter_desc.Description, mode.c_str()); + + // Capability: the stand-in's windows need OpenExistingHeapFromAddress on this adapter. + { + ComPtr<ID3D12Device3> probe; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&probe)))) return 4; + void* block = VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + ComPtr<ID3D12Heap> heap; + const HRESULT hr = block ? probe->OpenExistingHeapFromAddress(block, IID_PPV_ARGS(&heap)) : E_OUTOFMEMORY; + heap.Reset(); + if (block) VirtualFree(block, 0, MEM_RELEASE); + if (FAILED(hr)) { + std::printf("OpenExistingHeapFromAddress -> 0x%08lx: capability skip\n", static_cast<unsigned long>(hr)); + return 77; + } + } + + // Shader cache with the two container pipelines, keyed as the stand-in keys slot-62 pipelines. + wchar_t temp[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, temp)) return 5; + const std::wstring cache = std::wstring(temp) + L"x2w_indirect_" + std::to_wstring(GetCurrentProcessId()); + CreateDirectoryW(cache.c_str(), nullptr); + SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()); + const std::wstring log_path = cache + L"\\trap.log"; + if (rectrace || rectrace_off) SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + + D3D12_ROOT_PARAMETER parameters[2]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameters[1].Constants.Num32BitValues = 4; + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, parameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> root_blob; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &root_blob, nullptr))) return 5; + const auto cache_file = [&](const unsigned char* code, std::size_t bytes) { + wchar_t name[32]; + swprintf(name, 32, L"\\%016llx.cs.dxbc", static_cast<unsigned long long>(fnv(root_blob->GetBufferPointer(), root_blob->GetBufferSize(), fnv(code, bytes)))); + return write_file(cache + name, code, bytes); + }; + if (!cache_file(startup_indirect_writer, sizeof(startup_indirect_writer)) || + !cache_file(startup_indirect_counter, sizeof(startup_indirect_counter))) + return 5; + + std::array<unsigned char, 64> device_parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), device_parameters.data(), __uuidof(ID3D12Device), &device))) return 6; + + void* root = nullptr; + if (!ok(invoke(device, 16, 0, arg(root_blob->GetBufferPointer()), root_blob->GetBufferSize(), arg(&__uuidof(ID3D12RootSignature)), arg(&root)))) + return 7; + void *writer = nullptr, *counter = nullptr; + D3D12_COMPUTE_PIPELINE_STATE_DESC pipeline{}; + pipeline.pRootSignature = static_cast<ID3D12RootSignature*>(root); + pipeline.CS = {startup_indirect_writer, sizeof(startup_indirect_writer)}; + if (!ok(invoke(device, 62, arg(&pipeline), 0, 0, arg(&__uuidof(ID3D12PipelineState)), arg(&writer)))) return 8; + pipeline.CS = {startup_indirect_counter, sizeof(startup_indirect_counter)}; + if (!ok(invoke(device, 62, arg(&pipeline), 0, 0, arg(&__uuidof(ID3D12PipelineState)), arg(&counter)))) return 8; + + D3D12_INDIRECT_ARGUMENT_DESC argument{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH}; + const D3D12_COMMAND_SIGNATURE_DESC signature_desc{12, 1, &argument, 0}; + void* signature = nullptr; + if (!ok(invoke(device, 41, arg(&signature_desc), 0, arg(&__uuidof(ID3D12CommandSignature)), arg(&signature)))) return 9; + + // Title memory: arguments at +0x1c20 (not 64 KiB-aligned), counter at +0x10000. + auto* memory = static_cast<unsigned char*>(VirtualAlloc(nullptr, 2u << 20, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!memory) return 10; + unsigned char* const args_memory = memory + 0x1c20; + auto* const counter_word = reinterpret_cast<volatile std::uint32_t*>(memory + 0x10000); + const std::uint32_t sentinel[2][3] = {{rectrace || rectrace_off ? 0u : 7u, 1, 1}, {5, 1, 1}}; + std::memcpy(args_memory, sentinel[0], 12); + std::memcpy(args_memory + 0x14, sentinel[1], 12); + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 64, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + void* args = nullptr; + if (!ok(invoke(device, 133, arg(args_memory), arg(&buffer), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&args)))) + return 11; + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *queue = nullptr, *fence = nullptr, *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 12; + + if (rectrace || rectrace_off) { + const std::uint32_t reset[4] = {0, 1, 1, 0}, at_zero[4] = {0, 0, 0, 0}, at_counter[4] = {0, 0, 0, 0}; + void *allocator2 = nullptr, *list2 = nullptr; + if (!ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator2))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator2), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list2)))) + return 12; + invoke(list, 139, arg(allocator)); + invoke(list, 33, arg(root)); + invoke(list, 25, arg(writer)); + invoke(list, 45, 0, arg(args_memory)); // root UAV over the record + invoke(list, 39, 1, 4, arg(reset), 0); + invoke(list, 14, 1, 1, 1); // reset pass: {0, 1, 1} at offset 0 + invoke(list, 9); + invoke(list2, 139, arg(allocator2)); + invoke(list2, 33, arg(root)); + invoke(list2, 25, arg(counter)); + invoke(list2, 45, 0, arg(args_memory)); + invoke(list2, 39, 1, 4, arg(at_zero), 0); + invoke(list2, 14, 3, 1, 1); // raise pass: X += 3 + invoke(list2, 45, 0, arg(memory + 0x10000)); + invoke(list2, 39, 1, 4, arg(at_counter), 0); + invoke(list2, 61, arg(signature), 1, arg(args), 0, 0, 0); // ExecuteIndirect(sig, 1, args, 0) + invoke(list2, 9); + for (int n = 0; n < 2; ++n) { + void* one[] = {n ? list2 : list}; + invoke(queue, 10, 1, arg(one)); + if (!ok(invoke(queue, 14, arg(fence), n + 1))) return 13; + const auto until = GetTickCount64() + 10000; + while (invoke(fence, 8) < static_cast<Word>(n + 1)) { + if (GetTickCount64() >= until) return 14; + Sleep(1); + } + } + x2w_d3d12_record_trace_report(); + std::uint32_t record[3]; + std::memcpy(record, args_memory, 12); + const std::uint32_t got = *counter_word; + std::printf("record in title memory: {%u %u %u}; counter %u (expected 3)\n", record[0], record[1], record[2], got); + if (record[0] != 3 || record[1] != 1 || record[2] != 1) return 15; + if (got != 3) return 16; + std::ifstream log_file(log_path, std::ios::binary); + const std::string log{std::istreambuf_iterator<char>(log_file), {}}; + const auto count = [&](const std::string& text) { + std::size_t n = 0; + for (std::size_t at = log.find(text); at != std::string::npos; at = log.find(text, at + 1)) ++n; + return n; + }; + char args_hex[32], args_ptr[32], writer_ptr[32], counter_ptr[32]; + std::snprintf(args_hex, sizeof(args_hex), "0x%llx", static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(args_memory))); + std::snprintf(args_ptr, sizeof(args_ptr), "%p", static_cast<void*>(args_memory)); + std::snprintf(writer_ptr, sizeof(writer_ptr), "%p", writer); + std::snprintf(counter_ptr, sizeof(counter_ptr), "%p", counter); + const std::string range = std::string(": run: R p0+0x0 ") + args_hex + " "; + const std::string writers = std::string("x2w-frame record writers args ") + args_ptr + ": "; + const std::size_t reset_lines = count(std::string("(1, 1, 1) pipeline ") + writer_ptr + range); + const std::size_t raise_lines = count(std::string("(3, 1, 1) pipeline ") + counter_ptr + range); + const std::size_t record_lines = + count(std::string(" args ") + args_ptr + "+0x0 (wrapper ") == 1 && + count(": at record 00000000 00000001 00000001 00000000, at end 00000003 00000001 00000001 00000000") == 1; + const std::size_t totals = count("x2w-frame record totals type 2 dsv 0000000000000000: calls 1, X > 0 at record 0, at end 1, unreadable 0"); + const std::size_t writers_head = count(writers + "1 records (X > 0 at end 1), "); + const std::size_t writer_reset = count(std::string(" pipeline ") + writer_ptr + " R p0+0x0 " + args_hex + " ") >= 1 ? 1 : 0; + const std::size_t writer_raise = count(std::string(" pipeline ") + counter_ptr + " R p0+0x0 " + args_hex + " ") >= 1 ? 1 : 0; + const std::size_t any = count("x2w-frame cx-uav ") + count("x2w-frame record "); + std::printf("%s: reset lines %zu, raise lines %zu, record %zu, totals %zu, writers %zu (reset %zu, raise %zu), trace lines %zu\n", + mode.c_str(), reset_lines, raise_lines, record_lines, totals, writers_head, writer_reset, writer_raise, any); + if (rectrace && (reset_lines != 1 || raise_lines != 1 || !record_lines || totals != 1 || writers_head != 1 || !writer_reset || !writer_raise)) + return 20; + if (rectrace_off && any) return 21; + std::printf("PASS %s\n", mode.c_str()); + return 0; + } + // huge: the first record has 70000 groups in x (over the desktop's 65535); huge-product: 512*256*256 = + // 2^25 groups (each dimension legal, product over the guard's 2^24). The guard must zero the record on + // the GPU, so only the second record ({1, 1, 1}) runs: counter 1. + std::uint32_t written[2][4] = {{mode == "zero" ? 0u : 3u, mode == "zero" ? 1u : 2u, 1, 0}, + {mode == "zero" ? 0u : 1u, 1, 1, 0x14}}; + if (huge) written[0][0] = 70000, written[0][1] = 1, written[0][2] = 1; + if (huge_product) written[0][0] = 512, written[0][1] = 256, written[0][2] = 256; + const std::uint32_t count_at[4] = {0, 0, 0, 0}; + invoke(list, 139, arg(allocator)); // Reset + invoke(list, 33, arg(root)); // SetComputeRootSignature + if (mode != "no-writer") { + invoke(list, 25, arg(writer)); // SetPipelineState + invoke(list, 45, 0, arg(args_memory)); // SetComputeRootUnorderedAccessView(0, title address) + for (const auto& record : written) { + invoke(list, 39, 1, 4, arg(record), 0); // SetComputeRoot32BitConstants(1, 4, record, 0) + invoke(list, 14, 1, 1, 1); // Dispatch(1, 1, 1) + } + } + invoke(list, 25, arg(counter)); + invoke(list, 45, 0, arg(memory + 0x10000)); + invoke(list, 39, 1, 4, arg(count_at), 0); + invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); // ExecuteIndirect(sig, 1, args, 0, null, 0) + invoke(list, 61, arg(signature), 1, arg(args), 0x14, 0, 0); // ExecuteIndirect(sig, 1, args, 0x14, null, 0) + for (int i = 0; i < extra_calls; ++i) invoke(list, 61, arg(signature), 1, arg(args), 0x14, 0, 0); + invoke(list, 9); // Close + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), 1))) return 13; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < 1) { + if (GetTickCount64() >= deadline) return 14; + Sleep(1); + } + + std::uint32_t records[2][3]; + std::memcpy(records[0], args_memory, 12); + std::memcpy(records[1], args_memory + 0x14, 12); + const std::uint32_t got = *counter_word; + std::uint32_t wanted = mode == "gpu" ? 7 : mode == "no-writer" ? 12 : huge || huge_product ? 1 : 0; + if (extra_calls) wanted += wrap_cap ? 6 : extra_calls; + std::printf("records in title memory: {%u %u %u} {%u %u %u}\n", records[0][0], records[0][1], records[0][2], records[1][0], + records[1][1], records[1][2]); + std::printf("counter: %u (expected %u)\n", got, wanted); + bool records_ok = true; + for (int r = 0; r < 2; ++r) + for (int i = 0; i < 3; ++i) + records_ok &= records[r][i] == (mode == "no-writer" ? sentinel[r][i] : written[r][i]); + if (!records_ok) { + std::printf("the records in title memory are not what the %s wrote\n", mode == "no-writer" ? "CPU" : "writer"); + return 15; + } + ComPtr<ID3D12Device> desktop; + if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) + std::printf("device removed reason: 0x%08lx\n", static_cast<unsigned long>(desktop->GetDeviceRemovedReason())); + if (got != wanted) return 16; + if (extra_calls) { + // Indirect ring counters (x2w_upload_ring_test 100 + index): reserved bytes, refusals at the cap, slot bytes + // reused while held (legacy), would-have-wrapped bytes, chunks made, legacy flag. + const auto counter_of = [](int what) { return x2w_upload_ring_test(100 + what); }; + const unsigned long long reserved = counter_of(0), refused = counter_of(1), reused = counter_of(2), would = counter_of(3), + made = counter_of(8), legacy = counter_of(6); + std::printf("%s: indirect ring reserved %llu bytes, refused %llu, reused while held %llu bytes, would have wrapped %llu " + "bytes, chunks made %llu, legacy %llu\n", + ring_mode.c_str(), reserved, refused, reused, would, made, legacy); + if (wrap && (legacy || refused || reused || !would || made < 10 || reserved != 42 * 256)) return 17; + if (wrap_legacy && (!legacy || refused || !reused)) return 18; // the control: the old ring reuses held slots + if (wrap_cap && (legacy || refused != 34 || made != 2)) return 19; + std::printf("PASS %s\n", ring_mode.c_str()); + } + return 0; +} diff --git a/tests/startup_int_three_operand_check.py b/tests/startup_int_three_operand_check.py new file mode 100644 index 0000000000..6106233a81 --- /dev/null +++ b/tests/startup_int_three_operand_check.py @@ -0,0 +1,68 @@ +"""v_min3/v_max3/v_med3 _i32/_u32: the lowered HLSL expression against a sorted reference. + +Synthetic VOP3 words (gfx10 opcodes 0x152..0x159 except the f32 ones; the decoder's names are asserted). The +expression the translator emits is evaluated with 32-bit int()/uint() semantics on a grid of signed and unsigned +edge values. Reference: RDNA2 ISA (min/max/median of the three sources as signed or unsigned 32-bit integers). +Control: a mutated reference (median replaced by the maximum) must disagree. +""" +import itertools +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 + +MASK = 0xffffffff +OPS = {0x152: 'v_min3_i32', 0x153: 'v_min3_u32', 0x155: 'v_max3_i32', 0x156: 'v_max3_u32', + 0x158: 'v_med3_i32', 0x159: 'v_med3_u32'} +GRID = [0, 1, 2, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffffe, MASK, 0x12345678] + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def s32(x): + x &= MASK + return x - (1 << 32) if x >> 31 else x + + +def run(expr, env): + py = re.sub(r'\buint\(', 'U32(', re.sub(r'(?<![a-z])int\(', 'S32(', expr)) + return eval(py, {'__builtins__': {}, 'U32': lambda x: x & MASK, 'S32': s32, 'min': min, 'max': max}, env) & MASK + + +def ref(name, a, b, c): + conv = s32 if name.endswith('_i32') else (lambda x: x) + vals = sorted((conv(a), conv(b), conv(c))) + pick = {'min3': vals[0], 'max3': vals[2], 'med3': vals[1]}[name.split('_')[1]] + return pick & MASK + + +def main(): + for op, name in OPS.items(): + words = [0xd4000000 | op << 16 | 0, (256 + 1) | (256 + 2) << 9 | (256 + 3) << 18] + _, n, dname, text = G.decode(struct.pack('<2I', *words))[0] + assert text == '%s v0, v1, v2, v3' % name, text + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + s.pc = 0 + s.one(dname, text) + assert len(s.lines) == 1 and s.lines[0].startswith('v0 = ') and s.lines[0].endswith(';'), s.lines + expr = s.lines[0][5:-1] + bad = [(a, b, c) for a, b, c in itertools.product(GRID, repeat=3) + if run(expr, {'v1': a, 'v2': b, 'v3': c}) != ref(name, a, b, c)] + assert not bad, (name, expr, bad[:3]) + # Control: the median is not the maximum on this grid, so a wrong lowering would be caught. + assert any(ref('v_med3_i32', a, b, c) != ref('v_max3_i32', a, b, c) for a, b, c in itertools.product(GRID, repeat=3)) + print('int three-operand: %d forms match the sorted reference on %d inputs each; median/max control differs' + % (len(OPS), len(GRID) ** 3)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_interp_f16_check.py b/tests/startup_interp_f16_check.py new file mode 100644 index 0000000000..7e4e76262e --- /dev/null +++ b/tests/startup_interp_f16_check.py @@ -0,0 +1,193 @@ +"""Binary16 attribute interpolation (v_interp_p1ll_f16 + v_interp_p2_f16) in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + translate, compile (FXC vs_5_1/ps_5_1 when given, DXC vs_6_0/ps_6_0), + draw one pixel (the startup_flat_param renderer) and compare the words + +The vertex stage is startup_flat_param_check's full-screen triangle with four constant param0 words, each +holding two binary16 values. The pixel stage interpolates every half of attr0 (p1ll + p2_f16, `high` for bits +31:16) and packs the two results of a channel back into one VGPR: the low half with a plain p2_f16, the high half +with op_sel bit 3 set (Mesa aco_assembler.cpp emit_vintrp_instruction: v_interp_p2_hi_f16 is v_interp_p2_f16 with +opsel 0x8; LLVM 15 and the decoder do not print the bit). A constant attribute interpolates to itself, so mrt0 must +read the exported words. + +Encodings (hand-assembled, no llvm-mc here; the decoder reads them back): VOP3 word 0 = 0b110101 << 26 | +opcode << 16 | op_sel << 11 | vdst, word 1 = attribute | channel << 6 | high << 8 | src1 << 9 | src2 << 18 (Mesa +aco_assembler.cpp, gfx10 opcodes p1ll 0x342, p2 0x35a from aco_opcodes.py). + +Controls: without the p2 handler the stage refuses as before; with op_sel bit 3 cleared the high halves are lost +(text, and the draw mismatches); another op_sel bit, and clamp, are refused; a pixel stage that reads attr0 only +as f32 gets no half copies; the mesh pipeline drops the half copies of attributes the pixel stage does not read. +""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_flat_param_check import LINEAR_PS_WORDS, VS_WORDS as FLAT_VS, root_blob, compile_hlsl, draw # noqa: E402 + +# binary16 pairs (high, low): (-2.5, 1.0), (65504, 0.5), (2^-24 denormal, 2^-14), (0.333, -1.0) +WORDS = (0xc1003c00, 0x7bff3800, 0x00010400, 0x3555bc00) +EXPECTED = ','.join('%08x' % w for w in WORDS) + + +def v_mov_literal(reg, value): + return struct.pack('<II', 0x7e000000 | reg << 17 | 1 << 9 | 0xff, value) + + +def vertex_words(): + # the flat-param vertex stage up to v_mov_b32 v5, 0 (8 instructions, 0x28 bytes), then v6..v9 = WORDS + head = FLAT_VS[:0x28] + tail = FLAT_VS[FLAT_VS.find(bytes.fromhex('cf0800f8')):] + return head + b''.join(v_mov_literal(6 + i, w) for i, w in enumerate(WORDS)) + tail + + +def interp(op, vdst, attr, chan, high, src1, src2=0, opsel=0, clamp=0): + w0 = 0b110101 << 26 | op << 16 | opsel << 11 | clamp << 15 | vdst + w1 = attr | chan << 6 | high << 8 | (256 + src1) << 9 | ((256 + src2) << 18 if op == 0x35a else 0) + return struct.pack('<II', w0, w1) + + +def pixel_words(hi_opsel=8, clamp=0): + w = bytes.fromhex('0203fcbe') # s_mov_b32 m0, s2 + for chan in range(4): + d = 2 + chan + w += interp(0x342, 6, 0, chan, 0, 0) # v_interp_p1ll_f16 v6, v0, attr0.c + w += interp(0x35a, d, 0, chan, 0, 1, 6, clamp=clamp) # v_interp_p2_f16 vd, v1, attr0.c, v6 + w += interp(0x342, 7, 0, chan, 1, 0) # ... high + w += interp(0x35a, d, 0, chan, 1, 1, 7, opsel=hi_opsel) # ... high, to the high half of vd + return w + bytes.fromhex('0f1800f802030405') + bytes.fromhex('000081bf') # exp mrt0 v2..v5 done vm + + +def pipe(ps): + return G.Pipeline(vertex_words(), ps, root_blob(), ps_hw_inputs=(None, None, 0xc0)) # launch FLOAT_MODE 0xc0 + + +def refused(ps, text): + try: + pipe(ps).hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (text, str(error)) + return + raise AssertionError('accepted, expected %r' % text) + + +def controls(): + asm = [a for _, _, _, a in G.decode(pixel_words())] + assert asm[1:5] == ['v_interp_p1ll_f16 v6, v0, attr0.x', 'v_interp_p2_f16 v2, v1, attr0.x, v6', + 'v_interp_p1ll_f16 v7, v0, attr0.x high', 'v_interp_p2_f16 v2, v1, attr0.x, v7 high'], asm + vs_asm = [a for _, _, _, a in G.decode(vertex_words())] + assert vs_asm[7:12] == ['v_mov_b32_e32 v5, 0'] + [ + 'v_mov_b32_e32 v%d, 0x%x' % (6 + i, w) for i, w in enumerate(WORDS)], vs_asm + p = pipe(pixel_words()) + vs, ps = p.hlsl_vs(), p.hlsl_ps() + for text in (vs, ps): + assert 'float4 loparam0 : LOPARAM0;' in text and 'float4 hiparam0 : HIPARAM0;' in text, text + assert ' o.loparam0 = float4(f16tof32(v6), f16tof32(v7), f16tof32(v8), f16tof32(v9));' in vs, vs + assert ' o.hiparam0 = float4(f16tof32((v6) >> 16), f16tof32((v7) >> 16), f16tof32((v8) >> 16), ' \ + 'f16tof32((v9) >> 16));' in vs, vs + assert ' o.loparam0 = p.loparam0 + r.loparam0 - q.loparam0;' in vs, vs # the rectangle-list corner + for chan, d in zip('xyzw', range(2, 6)): + assert ' v%d = (v%d & 0xffff0000u) | x2w_f32tof16_rne(i.loparam0.%s);' % (d, d, chan) in ps, ps + assert ' v%d = (v%d & 0xffffu) | (x2w_f32tof16_rne(i.hiparam0.%s) << 16);' % (d, d, chan) in ps, ps + print('interp f16: VS exports loparam0/hiparam0 (f16tof32 of each half); PS packs both halves rounded to nearest even (x2w_f32tof16_rne)') + + # controls + saved = G.Stage.op_v_interp_p2_f16 + del G.Stage.op_v_interp_p2_f16 + try: + refused(pixel_words(), 'v_interp_p2_f16') + finally: + G.Stage.op_v_interp_p2_f16 = saved + lost = pipe(pixel_words(hi_opsel=0)).hlsl_ps() + assert '(x2w_f32tof16_rne(i.hiparam0.x) << 16)' not in lost and ' v2 = (v2 & 0xffff0000u) | x2w_f32tof16_rne(i.hiparam0.x);' \ + in lost, lost + refused(pixel_words(hi_opsel=1), 'v_interp_p2_f16 with op_sel 0x1') + refused(pixel_words(clamp=1), 'v_interp_p2_f16 with clamp') + # A compressed param export (upstream PR #2052's form, `exp param0 v6, v6, v7, v7 compr`) puts each half in its + # own channel, so the words are not halves: a binary16 read of it is refused, not read as halves of f32 bits. + plain_exp = bytes.fromhex('0f0200f806070809') + vs = vertex_words() + assert vs.count(plain_exp) == 1 + compr_vs = vs.replace(plain_exp, struct.pack('<I', 0xf800020f | 1 << 10) + bytes.fromhex('06070000')) + assert [a for _, _, _, a in G.decode(compr_vs)][-2] == 'exp param0 v6, v6, v7, v7 compr', G.decode(compr_vs) + try: + G.Pipeline(compr_vs, pixel_words(), root_blob(), ps_hw_inputs=(None, None, 0xc0)) + raise AssertionError('compr export read as halves accepted') + except G.Unsupported as error: + assert 'binary16 interpolation of attribute [0] exported with compr' in str(error), error + assert 'i.param0' in G.Pipeline(compr_vs, LINEAR_PS_WORDS, root_blob()).hlsl_ps() # f32 reads unaffected + linear = pipe(LINEAR_PS_WORDS) + assert 'loparam' not in linear.hlsl_vs() + linear.hlsl_ps() and 'hiparam' not in linear.hlsl_vs() + # mesh pipelines: the stage's half copies are kept only for attributes the pixel stage reads as halves + line = 'if (exec & 1) { o.param0 = float4(F(v6), 0.0, 0.0, 0.0); o.fparam0 = uint4(v6, 0u, 0u, 0u); ' \ + 'o.loparam0 = float4(f16tof32(v6), 0.0, 0.0, 0.0); o.hiparam0 = float4(f16tof32((v6) >> 16), 0.0, 0.0, 0.0); }' + + class StubMesh: + def __init__(self, pipe, code): + self.exports, self.exported_prim = {'pos': ['0'] * 4, 'param0': ['0'] * 4}, True + self.broadcasts, self.lds_used, self.wave_any, self.used_v = 0, False, [], set() + + def __getattr__(self, name): # other per-wave tables hlsl_ms reads (scc_any, ...): empty + return [] + + def body(self): + return [' ' + line] + + def declarations(self): + return [] + saved = M.MeshStage + M.MeshStage = StubMesh + try: + kept = M.MeshPipeline(b'', pixel_words(), root_blob(), ps_hw_inputs=(None, None, 0xc0)).hlsl_ms() + dropped = M.MeshPipeline(b'', LINEAR_PS_WORDS, root_blob()).hlsl_ms() + finally: + M.MeshStage = saved + assert 'o.loparam0 = ' in kept and 'o.hiparam0 = ' in kept and 'float4 loparam0 : LOPARAM0;' in kept, kept + assert 'loparam0' not in dropped and 'hiparam0' not in dropped and 'o.param0 = ' in dropped, dropped + print('controls: refused without the p2 handler; op_sel cleared loses the high halves; op_sel 0x1, clamp and a compr export ' + 'refused; no half copies for an f32-only reader; mesh stage keeps them only when read') + + +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')] + good, lost = pipe(pixel_words()), pipe(pixel_words(hi_opsel=0)) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + def build(name, source, profile): + return compile_hlsl(compiler, kind, source, '%s_%s' % (name, kind), profile, directory) + vs = build('vs', good.hlsl_vs(), vs_profile) + run = draw(renderer, adapter, vs, build('ps', good.hlsl_ps(), ps_profile), EXPECTED) + if run.returncode: + raise AssertionError('%s translated pair\n%s\n%s' % (kind, run.stdout, run.stderr)) + print('%s translated pair: %s' % (kind, EXPECTED), flush=True) + run = draw(renderer, adapter, build('vs_lost', lost.hlsl_vs(), vs_profile), + build('ps_lost', lost.hlsl_ps(), ps_profile), EXPECTED) + if run.returncode == 0: + raise AssertionError('%s control with op_sel cleared matched' % kind) + print('%s control, op_sel cleared: mismatches as expected (%s)' % (kind, run.stderr.strip()[-80:]), + flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_lane_invariant_check.py b/tests/startup_lane_invariant_check.py new file mode 100644 index 0000000000..8737daf9b0 --- /dev/null +++ b/tests/startup_lane_invariant_check.py @@ -0,0 +1,165 @@ +"""v_readfirstlane_b32 of a lane-invariant value, and the carry forms v_{add,sub,subrev}_co[_ci]_u32. + +Synthetic gfx1013 words only. The readfirstlane case is the shape LLVM AMDGPU emits for a 32-bit unsigned +division by a uniform divisor (AMDGPUCodeGenPrepare expandDivRem32: v_cvt_f32_u32 of the SGPR divisor, v_rcp, +v_mul by 0x4f7ffffe = 2^32 - 512, v_cvt_u32, then v_readfirstlane_b32 back to an SGPR), here behind a scalar +branch that is allowed now. Controls refuse: a source written from an SGPR assigned on only one side of a join, a +source behind a loop head, a source built from vcc, and a source read at a branch target. + +The carry forms are evaluated by the integer HLSL evaluator of startup_gfx2hlsl_bit_alu_check over an edge grid and +compared with 33-bit Python references written from the AMD RDNA 2 ISA description (V_ADD_CO_CI_U32: D = S0 + S1 + +CI, carry out; V_SUB_CO_CI_U32: D = S0 - S1 - CI, borrow when S1 + CI > S0; SUBREV swaps S0 and S1). +""" +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_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +LITERAL = 255 + + +class TestPipeline: + root = {'params': [{'type': 2}], 'flags': 0} + + def resource(self, key, kind): + assert key == (('root', 0), None) and kind == 'buf' + return 'r0' + + def ud(self, source): + return 0 + + +def vop1(op, dst, src): + return 0x7e000000 | dst << 17 | op << 9 | src + + +def vop2(op, dst, src0, vsrc1): + return op << 25 | dst << 17 | vsrc1 << 9 | src0 + + +SBL = [0xf4000000 | 8 << 18 | 7 << 6 | 4, 125 << 25 | 12] # s_buffer_load_dword s7, s[8:11], 12 + + +def udiv(divisor_sgpr): + # v_cvt_f32_u32 v1, sD; v_rcp_f32 v1, v1; v_mul_f32 v1, 0x4f7ffffe, v1; v_cvt_u32_f32 v1, v1; v_readfirstlane s10, v1 + return [vop1(6, 1, divisor_sgpr), vop1(0x2a, 1, 257), vop2(8, 1, LITERAL, 1), 0x4f7ffffe, vop1(7, 1, 257), + vop1(2, 10, 257)] + + +S_CMP_EQ_U32_S7_0 = 0xbf000000 | 6 << 16 | 128 << 8 | 7 +S_MOV_B32_S12_1 = 0xbe800000 | 12 << 16 | 3 << 8 | 129 + + +def stage(words): + return G.Stage(TestPipeline(), 'vs', struct.pack('<%dI' % (len(words) + 1), *words, 0xbf810000)) + + +def asm(words): + return [x[3] for x in G.decode(struct.pack('<%dI' % len(words), *words))] + + +def refused(words, label): + try: + stage(words) + except G.Unsupported as error: + assert 'requires a proven uniform source' in str(error), (label, str(error)) + return + raise AssertionError('accepted: ' + label) + + +def body(s): + return '\n'.join(line for block in s.blocks for line in block[1]) + + +def readfirstlane(): + words = SBL + udiv(7) + assert asm(udiv(7))[:3] == ['v_cvt_f32_u32_e32 v1, s7', 'v_rcp_f32_e32 v1, v1', 'v_mul_f32_e32 v1, 0x4f7ffffe, v1'], asm(udiv(7)) + assert asm(udiv(7))[-1] == 'v_readfirstlane_b32 s10, v1' + assert 's10 = v1;' in body(stage(words)) + # A scalar branch around an SGPR write before the division: the divisor s7 was loaded before the branch. + branchy = SBL + [S_CMP_EQ_U32_S7_0, 0xbf840001, S_MOV_B32_S12_1] + udiv(7) # s_cbranch_scc0 over the s_mov + assert asm([0xbf840001])[0].startswith('s_cbranch_scc0'), asm([0xbf840001]) + assert 's10 = v1;' in body(stage(branchy)) + # Controls. + refused(SBL + [S_CMP_EQ_U32_S7_0, 0xbf840001, S_MOV_B32_S12_1] + udiv(12), + 'divisor assigned on one side of a join') + refused(SBL + udiv(7) + [0xbf85fff9], 'divisor behind a loop head') # s_cbranch_scc1 back to udiv + assert G.decode(struct.pack('<%dI' % len(SBL + udiv(7) + [0xbf85fff9]), *SBL, *udiv(7), 0xbf85fff9))[-1][3] \ + == 's_cbranch_scc1 label_0x8', 'loop branch target' + refused(SBL + [vop2(1, 1, 128, 0x101 - 256)] + [vop1(2, 10, 257)], 'v_cndmask_b32 v1, 0, v1, vcc') + refused(SBL + [vop1(6, 1, 7), 0xbf820000, vop1(2, 10, 257)], 'read at a branch target') + refused(SBL + [vop1(6, 1, 256)] + udiv(7)[1:], 'per-lane source v0') + print('readfirstlane: lane-invariant division accepted with and without a scalar branch; 5 controls refused') + + +def ref(kind, a, b, c): + if kind == 'subrev': + a, b = b, a + if kind == 'add': + total = a + b + c + return total & MASK, total >> 32 + return (a - b - c) & MASK, int(b + c > a) + + +def carry_text(words): + s = stage([]) + s.lines = [] + _, n, name, text = G.decode(struct.pack('<%dI' % len(words), *words))[0] + s.pc = 0 + s.one(name, text) + return s, '\n'.join(s.lines) + + +def carries(): + grid = [0, 1, 2, 0x7fffffff, 0x80000000, 0xfffffffe, MASK, 0x12345678] + bad = [] + forms = [] + for kind, op32, op64 in (('add', 0x28, 0x128), ('sub', 0x29, 0x129), ('subrev', 0x2a, 0x12a)): + e32 = [vop2(op32, 2, 256 + 4, 3)] # v_X_co_ci_u32_e32 v2, vcc_lo, v4, v3, vcc_lo + assert asm(e32)[0] == 'v_%s_co_ci_u32_e32 v2, vcc_lo, v4, v3, vcc_lo' % kind, asm(e32) + e64 = [0xd4000000 | op64 << 16 | 18 << 8 | 2, (256 + 4) | (256 + 3) << 9 | 106 << 18] + assert asm(e64)[0] == 'v_%s_co_ci_u32_e64 v2, s18, v4, v3, vcc_lo' % kind, asm(e64) + co_op = {'add': 0x30f, 'sub': 0x310, 'subrev': 0x319}[kind] + co = [0xd4000000 | co_op << 16 | 18 << 8 | 2, (256 + 4) | (256 + 3) << 9] + assert asm(co)[0] == 'v_%s_co_u32 v2, s18, v4, v3' % kind, asm(co) + for words, carry_in, sdst in ((e32, True, 'vcc'), (e64, True, 's18'), (co, False, 's18')): + s, text = carry_text(words) + lines = text.split('\n') + assert lines[0].startswith('q = uint2(') and lines[1] == 'v2 = q.x;', text + assert lines[2] == ('vcc = q.y;' if sdst == 'vcc' else 's18 = q.y;'), text + if sdst == 's18': + assert 18 in s.masks, 'carry-out SGPR is a mask' + value, carry = G.split_top(lines[0][len('q = uint2('):-2]) + value, carry = Expr(value), Expr(carry) + for a in grid: + for b in grid: + for c in ((0, 1) if carry_in else (0,)): + env = {'v4': a, 'v3': b, 'vcc': c} + got = value.run(env)[0], carry.run(env)[0] + if got != ref(kind, a, b, c): + bad.append((kind, words, a, b, c, got, ref(kind, a, b, c))) + forms.append(asm(words)[0].split(' ')[0]) + assert not bad, bad[:5] + # Refusals: clamp, and a carry-in that is not a lane mask. + clamp = [0xd4000000 | 0x128 << 16 | 1 << 15 | 18 << 8 | 2, (256 + 4) | (256 + 3) << 9 | 106 << 18] + numeric_ci = [0xd4000000 | 0x128 << 16 | 18 << 8 | 2, (256 + 4) | (256 + 3) << 9 | 20 << 18] # CI = s20 + for words, why in ((clamp, 'clamp'), (numeric_ci, 'lane mask')): + try: + carry_text(words) + except G.Unsupported as error: + assert why in str(error), (why, str(error), asm(words)) + else: + raise AssertionError('accepted %s' % asm(words)) + print('carry forms: %d forms match the 33-bit references on %d inputs each; 2 controls refused' + % (len(forms), len(grid) ** 2 * 2)) + + +if __name__ == '__main__': + readfirstlane() + carries() diff --git a/tests/startup_list_copy_texture_warp.cpp b/tests/startup_list_copy_texture_warp.cpp index 4acdd6a4cc..f5607b1e46 100644 --- a/tests/startup_list_copy_texture_warp.cpp +++ b/tests/startup_list_copy_texture_warp.cpp @@ -16,6 +16,8 @@ // Exit codes: 0 pass, 77 no physical adapter, other values name the failing step. #include <windows.h> #include <d3d12.h> +#include <d3dcompiler.h> +#include "desktop_gpu.h" #include <dxgi1_6.h> #include <wrl/client.h> @@ -238,6 +240,178 @@ int main(int argc, char** argv) invoke(readback, 9, 0, 0); if (!block_ok) return 22; + // The title receives its metering samples directly in a placed buffer. The console + // footprint starts at a byte offset and has no desktop row padding. + auto* title = static_cast<unsigned char*>(VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!title) return 23; + auto place_desc = buffer_desc(1024); + void* placed{}; + if (!ok(invoke(device, 133, arg(title + 8), arg(&place_desc), D3D12_RESOURCE_STATE_COMMON, 0, + arg(&__uuidof(ID3D12Resource)), arg(&placed))) || !placed) return 24; + std::array<float, 20> meter{}; + for (UINT i = 0; i < meter.size(); ++i) meter[i] = 0.125f * (i + 1); + auto* bytes = reinterpret_cast<const unsigned char*>(meter.data()); + if (!ok(invoke(upload, 8, 0, 0, arg(&memory))) || !memory) return 25; + std::memcpy(memory, bytes, sizeof(meter)); + invoke(upload, 9); + if (!ok(invoke(list, 139, arg(allocator), 0))) return 26; + for (UINT w : {5u, 1u}) { + D3D12_RESOURCE_DESC meter_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, w, 1, 1, 1, + DXGI_FORMAT_R32G32B32A32_FLOAT, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN}; + void* meter_texture = make_resource(device, D3D12_HEAP_TYPE_DEFAULT, meter_desc, D3D12_RESOURCE_STATE_COMMON); + if (!meter_texture) return 27; + const auto tex = subresource(meter_texture, 0); + auto up = footprint(upload, 0); + up.PlacedFootprint.Footprint = {meter_desc.Format, w, 1, 1, pitch}; + copy(tex, up); + auto out = footprint(placed, w == 5 ? 7 : 110); + out.PlacedFootprint.Footprint = {meter_desc.Format, w, 1, 1, 16*w}; + invoke(list, 85, arg(&out), 0, 0, 0, arg(&tex), 0, 0); + } + if (!ok(invoke(list, 9))) return 28; + for (int replay = 0; replay < 2; ++replay) { + std::memset(title, sentinel, 1024); + if (!replay) { + void* gate{}; + if (!ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&gate))) || + !ok(invoke(queue, 17, arg(gate), 1))) return 29; + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 16, arg(fence), ++fence_value)) || title[15] != sentinel || + invoke(fence, 8) >= fence_value) return 29; + if (!ok(invoke(gate, 10, 1)) || !wait_for(fence, fence_value)) return 29; + } else if (!submit()) return 29; + for (UINT i=0; i<1024; ++i) { + const auto expected = i >= 15 && i < 95 ? bytes[i-15] : i >= 118 && i < 134 ? bytes[i-118] : sentinel; + if (title[i] != expected) { + std::printf("meter replay %d byte %u got %02x expected %02x\n", replay, i, title[i], expected); + return 30; + } + } + } + // Reset discards the recording. An empty submission must not land it a third time. + std::memset(title, sentinel, 1024); + if (!ok(invoke(list, 139, arg(allocator), 0)) || !ok(invoke(list, 9)) || !submit() || title[16] != sentinel) return 31; + // A typeless texture, a typed sRGB texture, and a linear UNORM footprint share + // one copy format family. Verify the actual bytes survive both transfers. + auto family_desc = texture_desc; + family_desc.MipLevels = family_desc.DepthOrArraySize = 1; + family_desc.Format = DXGI_FORMAT_R8G8B8A8_TYPELESS; + auto* raw_texture = make_resource(device, D3D12_HEAP_TYPE_DEFAULT, family_desc, D3D12_RESOURCE_STATE_COMMON); + family_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + auto* srgb_texture = make_resource(device, D3D12_HEAP_TYPE_DEFAULT, family_desc, D3D12_RESOURCE_STATE_COMMON); + if (!raw_texture || !srgb_texture || !ok(invoke(list, 139, arg(allocator), 0))) return 32; + const auto raw = subresource(raw_texture, 0), srgb = subresource(srgb_texture, 0); + copy(raw, b_up); + invoke(list, 85, arg(&srgb), 0, 0, 0, arg(&raw)); + copy(a_out, srgb); + if (!ok(invoke(list, 9)) || !submit() || !ok(invoke(readback, 8, 0, 0, arg(&memory))) || !memory) return 33; + const bool family_matches = image_matches(static_cast<const std::uint8_t*>(memory), 0, 1); + invoke(readback, 9); + if (!family_matches) return 34; + + for (auto bc : {DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC3_UNORM_SRGB, DXGI_FORMAT_BC7_UNORM_SRGB}) { + const UINT block_bytes = bc == DXGI_FORMAT_BC1_UNORM ? 8 : 16; + auto packed_desc = family_desc; + packed_desc.Format = block_bytes == 8 ? DXGI_FORMAT_R32G32_UINT : DXGI_FORMAT_R32G32B32A32_UINT; + auto bc_desc = packed_desc; + bc_desc.Format = bc; + bc_desc.Width *= 4; + bc_desc.Height *= 4; + auto* packed = make_resource(device, D3D12_HEAP_TYPE_DEFAULT, packed_desc, D3D12_RESOURCE_STATE_COMMON); + auto* compressed = make_resource(device, D3D12_HEAP_TYPE_DEFAULT, bc_desc, D3D12_RESOURCE_STATE_COMMON); + if (!packed || !compressed || !ok(invoke(upload, 8, 0, 0, arg(&memory))) || !memory) return 35; + for (UINT y = 0; y < side; ++y) + for (UINT i = 0; i < side * block_bytes; ++i) + static_cast<BYTE*>(memory)[y * pitch + i] = BYTE(17 * y + 3 * i + bc); + invoke(upload, 9); + if (!ok(invoke(list, 139, arg(allocator), 0))) return 36; + const auto blocks = subresource(packed, 0), material = subresource(compressed, 0); + copy(blocks, footprint(upload, 0, packed_desc.Format)); + invoke(list, 85, arg(&material), 0, 0, 0, arg(&blocks)); + auto bytes_out = footprint(readback, 0, bc); + bytes_out.PlacedFootprint.Footprint.Width = UINT(bc_desc.Width); + bytes_out.PlacedFootprint.Footprint.Height = bc_desc.Height; + copy(bytes_out, material); + if (!ok(invoke(list, 9)) || !submit() || !ok(invoke(readback, 8, 0, 0, arg(&memory))) || !memory) return 37; + bool intact = true; + for (UINT y = 0; y < side; ++y) + for (UINT i = 0; i < side * block_bytes; ++i) + intact &= static_cast<const BYTE*>(memory)[y * pitch + i] == BYTE(17 * y + 3 * i + bc); + invoke(readback, 9); + if (!intact) { std::printf("block payload mismatch, format %u\n", UINT(bc)); return 38; } + if (!ok(invoke(list, 139, arg(allocator), 0))) return 39; + const D3D12_BOX first_word{0, 0, 0, 1, 1, 1}, second_block{4, 4, 0, 8, 8, 1}; + invoke(list, 85, arg(&material), 4, 4, 0, arg(&blocks), arg(&first_word)); + invoke(list, 85, arg(&blocks), 2, 2, 0, arg(&material), arg(&second_block)); + copy(footprint(readback, 0, packed_desc.Format), blocks); + if (!ok(invoke(list, 9)) || !submit() || !ok(invoke(readback, 8, 0, 0, arg(&memory))) || !memory) return 40; + for (UINT y = 0; y < side; ++y) + for (UINT i = 0; i < side * block_bytes; ++i) { + const bool replaced = y == 2 && i / block_bytes == 2; + const auto expected = BYTE((replaced ? 3 * (i % block_bytes) : 17 * y + 3 * i) + bc); + intact &= static_cast<const BYTE*>(memory)[y * pitch + i] == expected; + } + invoke(readback, 9); + if (!intact) return 41; + } +#include "startup_bc_writer_srv.inl" + D3D12_RESOURCE_DESC planar_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 256, 16, 2, 2, + DXGI_FORMAT_R32G8X24_TYPELESS, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}; + void* planar = make_resource(device, D3D12_HEAP_TYPE_DEFAULT, planar_desc, D3D12_RESOURCE_STATE_COMMON); + if (!planar || !ok(invoke(list, 139, arg(allocator), 0))) return 42; + LONG forwarded_before{}, refused_before{}, forwarded_after{}, refused_after{}; + x2w_d3d12_list_copy_texture_stats(&forwarded_before, &refused_before); + for (UINT sub : {3u, 7u, 7u}) { + auto src = subresource(planar, sub); + auto dst = footprint(readback, 512, sub == 3 ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R8_UINT); + const D3D12_BOX region{1, 2, 0, 3, 4, 1}; + invoke(list, 85, arg(&dst), 2, 3, 0, arg(&src), arg(®ion), 0); + } + x2w_d3d12_list_copy_texture_stats(&forwarded_after, &refused_after); + if (forwarded_after != forwarded_before || refused_after - refused_before != 3 || !ok(invoke(list, 9))) return 43; + // Seed depth and stencil differently, copy only depth from mip 1, slice 1, and replay the recording. + if (!ok(invoke(list, 139, arg(allocator), 0))) return 44; + const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; Word backing, bytes; } + heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, 0, 0}; + void* dsv_heap{}; + if (!ok(invoke(device, 14, arg(&heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&dsv_heap))) || !dsv_heap) return 45; + const Word handle = invoke(dsv_heap, 9); + D3D12_DEPTH_STENCIL_VIEW_DESC dsv{}; + dsv.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; + dsv.Texture2DArray = {1, 1, 1}; + invoke(device, 21, arg(planar), arg(&dsv), handle); + using Clear = void (WINAPI*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, FLOAT, UINT8, UINT, const D3D12_RECT*); + reinterpret_cast<Clear>((*static_cast<void***>(list))[51])(list, {SIZE_T(handle)}, + D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.375f, 0xa5, 0, nullptr); + auto depth_desc = planar_desc; + constexpr UINT depth_width = 128, depth_pitch = depth_width * sizeof(float); + depth_desc.Width = depth_width; + depth_desc.Height = 8; + depth_desc.DepthOrArraySize = depth_desc.MipLevels = 1; + depth_desc.Format = DXGI_FORMAT_R32_TYPELESS; + void* depth_copy = make_resource(device, D3D12_HEAP_TYPE_DEFAULT, depth_desc, D3D12_RESOURCE_STATE_COMMON); + void* depth_out = make_resource(device, D3D12_HEAP_TYPE_READBACK, buffer_desc(8 * depth_pitch), D3D12_RESOURCE_STATE_COPY_DEST); + if (!depth_copy || !depth_out) return 46; + auto from_depth = subresource(planar, 3), to_depth = subresource(depth_copy, 0); + auto out_depth = footprint(depth_out, 0, DXGI_FORMAT_R32_TYPELESS); + out_depth.PlacedFootprint.Footprint.Width = depth_width; + out_depth.PlacedFootprint.Footprint.Height = 8; + out_depth.PlacedFootprint.Footprint.RowPitch = depth_pitch; + invoke(list, 85, arg(&to_depth), 0, 0, 0, arg(&from_depth), 0, 0); + copy(out_depth, to_depth); + x2w_d3d12_list_copy_texture_stats(&forwarded_before, &refused_before); + if (forwarded_before - forwarded_after != 2 || refused_before != refused_after || !ok(invoke(list, 9))) return 47; + for (unsigned replay = 0; replay < 2; ++replay) { + if (!submit() || !ok(invoke(depth_out, 8, 0, 0, arg(&memory))) || !memory) return 48; + bool intact = true; + for (unsigned y = 0; y < 8; ++y) for (unsigned x = 0; x < depth_width; ++x) + intact &= reinterpret_cast<const float*>(static_cast<const BYTE*>(memory) + y * depth_pitch)[x] == 0.375f; + invoke(depth_out, 9); + if (!intact) return 49; + } std::puts("ok"); return 0; } diff --git a/tests/startup_lit64_check.py b/tests/startup_lit64_check.py new file mode 100644 index 0000000000..eac30ba3d1 --- /dev/null +++ b/tests/startup_lit64_check.py @@ -0,0 +1,47 @@ +"""A 32-bit literal in a 64-bit integer operand: accepted when bit 31 is clear (high dword 0 under either extension). + +Synthetic VOP3 words: v_lshrrev_b64 v[5:6], 0, <literal> (op 0x300, src0 = inline 0, src1 = 255 + literal). LLVM +AMDGPUDisassembler::decodeLiteralConstant zero-extends a literal for OPERAND_REG_IMM_INT64 (with a ToDo on +signedness) and the assembler encodes Lo_32; zero- and sign-extension agree exactly when bit 31 is clear. +Controls: 0x80000000 zero-extends (an unsigned shift, see startup_gfx2hlsl_shift64_literal_check.py); the inline constant 1 keeps its old lowering. +""" +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 one(words): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + _, n, name, text = G.decode(struct.pack('<%dI' % len(words), *words))[0] + s.pc = 0 + s.one(name, text) + return text, '\n'.join(s.lines) + + +def main(): + text, body = one([0xd7000005, 128 | 255 << 9, 0x3f800000]) + assert text == 'v_lshrrev_b64 v[5:6], 0, 0x3f800000', text + assert 'x2w_lshr64_lo(0x3f800000u, 0x00000000u, 0x00000000u)' in body, body + assert 'x2w_lshr64_hi(0x3f800000u, 0x00000000u, 0x00000000u)' in body, body + # v_lshrrev_b64 reads S1.u64, so a literal with bit 31 set zero-extends too + # (startup_gfx2hlsl_shift64_literal_check.py; other 64-bit operands keep the refusal there). + text, body = one([0xd7000005, 128 | 255 << 9, 0x80000000]) + assert 'x2w_lshr64_lo(0x80000000u, 0x00000000u, 0x00000000u)' in body, body + text, body = one([0xd7000005, 128 | 129 << 9]) + assert text == 'v_lshrrev_b64 v[5:6], 0, 1' and 'x2w_lshr64_lo(0x00000001u, 0x00000000u, 0x00000000u)' in body, body + print('lit64: bit-31-clear literal -> high dword 0; 0x80000000 zero-extended; inline 1 unchanged') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_literal_halves_check.py b/tests/startup_literal_halves_check.py new file mode 100644 index 0000000000..b7a934f7a8 --- /dev/null +++ b/tests/startup_literal_halves_check.py @@ -0,0 +1,67 @@ +"""f16 halves of literals in VOP3P sources: v_fma_mix_* with a 32-bit literal, v_pk_* with the inline integer 0. + +Synthetic words. A VOP3P literal is read through op_sel like a register: LLVM SIFoldOperands::tryFoldImmWithOpSel +takes a packed operand's halves as ImmVal >> (OP_SEL_0 ? 16 : 0) and ImmVal >> (OP_SEL_1 ? 16 : 0), which is how a +compiler encodes two different f16 constants in the one literal (here 0x4600 = 6.0 low, 0xc200 = -3.0 high: +6 * |x| - 3). The inline integer 0 has no set bit, so every half selection of it reads +0.0. Controls: a literal +read as an f32 mix operand keeps its full 32 bits, and a non-zero inline constant in a packed f16 operand with a +high-half selection stays refused. +""" +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 one(words): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + _, n, name, text = G.decode(struct.pack('<%dI' % len(words), *words))[0] + s.pc = 0 + s.one(name, text) + return text, '\n'.join(s.lines) + + +def half(bits): + return struct.unpack('<e', struct.pack('<H', bits))[0] + + +def main(): + mix = [0xcc000000 | 0x20 << 16 | 1 << 14 | 1 << 13 | 1 << 9 | 20, 255 | (256 + 14) << 9 | 255 << 18 | 1 << 27, + 0xc2004600] + text, body = one(mix) + assert text == 'v_fma_mix_f32 v20, 0xc2004600, |v14|, 0xc2004600 op_sel:[0,0,1] op_sel_hi:[1,0,1]', text + assert body == 'v20 = U(f16tof32(0x4600u) * abs(F(v14)) + f16tof32(0xc200u));', body + assert (half(0x4600), half(0xc200)) == (6.0, -3.0) + # op_sel_hi[0] = 0: the literal is an f32 operand and keeps all 32 bits. + f32 = [mix[0], mix[1] & ~(1 << 27), mix[2]] + text, body = one(f32) + assert body.startswith('v20 = U(F(0xc2004600u) * '), (text, body) + + pk = [0xcc000000 | 0x12 << 16 | 14, (256 + 14) | 128 << 9 | 1 << 27] + text, body = one(pk) + assert text == 'v_pk_max_f16 v14, v14, 0 op_sel_hi:[1,0]', text + assert body == ('v14 = f32tof16(max(f16tof32(v14), f16tof32(0x00000000u))) | ' + '(f32tof16(max(f16tof32(v14 >> 16), f16tof32(0x00000000u))) << 16);'), body + # inline 1.0 (242) read through its high half: its packed layout is not pinned down here, so refused + one_hi = [0xcc000000 | 0x12 << 16 | 14, (256 + 14) | 242 << 9 | 1 << 27 | 1 << 28] + try: + one(one_hi) + except G.Unsupported as error: + assert 'packed f16 operand 1.0' in str(error), str(error) + else: + raise AssertionError('accepted %s' % one(one_hi)[0]) + print('literal halves: fma_mix literal halves 6.0 / -3.0, f32 literal control, pk inline 0, inline 1.0 refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_local_log_check.cpp b/tests/startup_local_log_check.cpp index daff26103b..7fb2a3fb0f 100644 --- a/tests/startup_local_log_check.cpp +++ b/tests/startup_local_log_check.cpp @@ -465,10 +465,10 @@ void test_probe_and_access(bool guard_drop_mutate) std::memset(raw, 0x5A, kPages * kPage); // Invalid addresses and zero-byte lengths. - check(x2w_local::probe_readable(0, 16) == 0, "probe_readable rejects null"); - check(x2w_local::probe_readable(0xFFFFu, 16) == 0, "probe_readable rejects < 0x10000"); - check(x2w_local::probe_readable(0x00007FFFFFFF0000ull, 16) == 0, "probe_readable rejects > user limit"); - check(x2w_local::probe_readable(base, 0) == 0, "probe_readable rejects 0 bytes"); + check(x2w_local::probe_descriptor_address(0, 16) == 0, "probe_readable rejects null"); + check(x2w_local::probe_descriptor_address(0xFFFFu, 16) == 0, "probe_readable rejects < 0x10000"); + check(x2w_local::probe_descriptor_address(0x00007FFFFFFF0000ull, 16) == 0, "probe_readable rejects > user limit"); + check(x2w_local::probe_descriptor_address(base, 0) == 0, "probe_readable rejects 0 bytes"); check(!x2w_local::readable(nullptr, 1) && !x2w_local::writable(nullptr, 1), "accessible rejects null"); const auto low_ptr = reinterpret_cast<const void*>(std::uintptr_t{0xFFFF}); @@ -478,8 +478,8 @@ void test_probe_and_access(bool guard_drop_mutate) check(!x2w_local::readable(raw, 0) && !x2w_local::writable(raw, 0), "accessible rejects 0 bytes"); // Multi-page readable range and unaligned slice. - check(x2w_local::probe_readable(base, kPages * kPage) == kPages * kPage, "probe_readable full 4 pages"); - check(x2w_local::probe_readable(base + 0xF00u, 0x2200u) == 0x2200u, "probe_readable unaligned across pages"); + check(x2w_local::probe_descriptor_address(base, kPages * kPage) == kPages * kPage, "probe_readable full 4 pages"); + check(x2w_local::probe_descriptor_address(base + 0xF00u, 0x2200u) == 0x2200u, "probe_readable unaligned across pages"); check(x2w_local::readable(raw, kPages * kPage) && x2w_local::writable(raw, kPages * kPage), "4-page RW region is readable and writable"); @@ -524,11 +524,11 @@ void test_probe_and_access(bool guard_drop_mutate) // PAGE_NOACCESS on page 2: truncates probe_readable prefix cleanly. check(VirtualProtect(reinterpret_cast<void*>(base + 2 * kPage), kPage, PAGE_NOACCESS, &old_prot) != 0, "VirtualProtect page 2 PAGE_NOACCESS"); - check(x2w_local::probe_readable(base, kPages * kPage) == 2 * kPage, + check(x2w_local::probe_descriptor_address(base, kPages * kPage) == 2 * kPage, "probe_readable truncates before PAGE_NOACCESS"); - check(x2w_local::probe_readable(base + 0x123u, kPages * kPage - 0x123u) == 2 * kPage - 0x123u, + check(x2w_local::probe_descriptor_address(base + 0x123u, kPages * kPage - 0x123u) == 2 * kPage - 0x123u, "probe_readable unaligned truncates before PAGE_NOACCESS"); - check(x2w_local::probe_readable(base + 2 * kPage, kPage) == 0, + check(x2w_local::probe_descriptor_address(base + 2 * kPage, kPage) == 0, "probe_readable on PAGE_NOACCESS returns 0"); check(!x2w_local::readable(reinterpret_cast<const void*>(base + 2 * kPage), 1) && !x2w_local::writable(reinterpret_cast<const void*>(base + 2 * kPage), 1), @@ -539,7 +539,7 @@ void test_probe_and_access(bool guard_drop_mutate) // PAGE_GUARD on page 1: probe stops before guard page and re-arms PAGE_GUARD. check(VirtualProtect(reinterpret_cast<void*>(base + kPage), kPage, PAGE_READWRITE | PAGE_GUARD, &old_prot) != 0, "VirtualProtect page 1 PAGE_GUARD"); - check(x2w_local::probe_readable(base, 2 * kPage) == kPage, + check(x2w_local::probe_descriptor_address(base, 2 * kPage) == kPage, "probe_readable stops at PAGE_GUARD page"); MEMORY_BASIC_INFORMATION mbi{}; check(VirtualQuery(reinterpret_cast<const void*>(base + kPage), &mbi, sizeof(mbi)) != 0, @@ -549,7 +549,7 @@ void test_probe_and_access(bool guard_drop_mutate) } else { check((mbi.Protect & PAGE_GUARD) != 0, "probe_readable re-arms PAGE_GUARD after trip"); // Second probe must hit the re-armed guard page at the same offset and keep it armed. - check(x2w_local::probe_readable(base, 2 * kPage) == kPage, + check(x2w_local::probe_descriptor_address(base, 2 * kPage) == kPage, "second probe_readable still stops at re-armed PAGE_GUARD"); MEMORY_BASIC_INFORMATION mbi2{}; check(VirtualQuery(reinterpret_cast<const void*>(base + kPage), &mbi2, sizeof(mbi2)) != 0 && @@ -574,7 +574,7 @@ void test_probe_and_access(bool guard_drop_mutate) void* const first_committed = VirtualAlloc(reserved, kPage, MEM_COMMIT, PAGE_READWRITE); check(first_committed == reserved, "commit first page of reserved range"); const auto rbase = reinterpret_cast<std::uintptr_t>(reserved); - check(x2w_local::probe_readable(rbase, 2 * kPage) == kPage, + check(x2w_local::probe_descriptor_address(rbase, 2 * kPage) == kPage, "probe_readable truncates before MEM_RESERVE"); check(x2w_local::readable(reserved, kPage) && x2w_local::writable(reserved, kPage), "committed head of reserved range is readable and writable"); @@ -613,6 +613,10 @@ int main(int argc, char** argv) two_args && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "cache-failure") == 0; // --mutate wrap: negative control running only the wrap-point case with the counting gate. const bool wrap_mutate = two_args && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "wrap") == 0; + if (argc == 2 && std::strcmp(argv[1], "--probe-only") == 0) { + test_probe_and_access(false); + return failures ? 1 : 0; + } if (argc > 1 && !guard_drop_mutate && !reopen_mutate && !cache_failure_mutate && !wrap_mutate) { std::printf("unknown mutation\n"); return 2; diff --git a/tests/startup_log_cap_check.cpp b/tests/startup_log_cap_check.cpp new file mode 100644 index 0000000000..2e4529a04b --- /dev/null +++ b/tests/startup_log_cap_check.cpp @@ -0,0 +1,71 @@ +// x2w_local::first_calls (src/startup_stubs/log_cap.h): a log cap that never wraps. Checks the first +// `limit` calls pass and no later one does, from several threads at once (exact count), that the counter +// stops at limit + 1, and that a counter near LONG_MAX stays closed. `--mutate wrap` runs the same +// checks against the old `InterlockedIncrement(&c) <= limit` pattern, which wraps: the negative control. +#include "startup_stubs/log_cap.h" + +#include <climits> +#include <cstdio> +#include <cstring> +#include <thread> +#include <vector> + +namespace { + +bool use_old = false; + +bool cap(volatile LONG& counter, LONG limit) +{ + return use_old ? InterlockedIncrement(&counter) <= limit : x2w_local::first_calls(counter, limit); +} + +int failures = 0; + +void expect(bool ok, const char* what) +{ + std::printf("%s %s\n", ok ? "ok " : "FAIL", what); + if (!ok) ++failures; +} + +} // namespace + +int main(int argc, char** argv) +{ + use_old = argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "wrap") == 0; + + { + volatile LONG counter = 0; + int passed = 0; + for (int i = 0; i < 100; ++i) passed += cap(counter, 4); + expect(passed == 4, "single thread: 4 of 100 calls pass a cap of 4"); + expect(use_old || counter == 5, "single thread: the counter stops at limit + 1"); + } + { + constexpr int threads = 8, calls = 200000; + constexpr LONG limit = 1000; + volatile LONG counter = 0; + std::vector<long> passed(threads, 0); + std::vector<std::thread> pool; + for (int t = 0; t < threads; ++t) + pool.emplace_back([&, t] { for (int i = 0; i < calls; ++i) passed[t] += cap(counter, limit); }); + for (auto& th : pool) th.join(); + long total = 0; + for (long p : passed) total += p; + expect(total == limit, "8 threads: exactly 1000 of 1.6 million calls pass a cap of 1000"); + expect(use_old || counter == limit + 1, "8 threads: the counter stops at limit + 1"); + } + { + // A counter that has already counted to LONG_MAX (2^31 - 1 calls): the next calls must stay closed. + volatile LONG counter = LONG_MAX; + int passed = 0; + for (int i = 0; i < 1000; ++i) passed += cap(counter, 4); + expect(passed == 0, "a counter at LONG_MAX stays closed (the old pattern wraps and passes here)"); + } + { + expect(x2w_local::first_of(1, 4) && x2w_local::first_of(4, 4), "first_of: counts 1..limit pass"); + expect(!x2w_local::first_of(5, 4) && !x2w_local::first_of(LONG_MIN, 4) && !x2w_local::first_of(-1, 4) && !x2w_local::first_of(0, 4), + "first_of: past the limit and wrapped counts do not"); + } + std::printf("%s\n", failures ? "FAILED" : "PASSED"); + return failures ? 1 : 0; +} diff --git a/tests/startup_loop_carried_check.py b/tests/startup_loop_carried_check.py new file mode 100644 index 0000000000..f5563178c7 --- /dev/null +++ b/tests/startup_loop_carried_check.py @@ -0,0 +1,117 @@ +"""Check that loop-carried scalar registers invalidate stale constant values.""" +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_scalar_bits_check import stage # noqa: E402 + + +def sop1(op, d, s): + return 0xbe800000 | d << 16 | op << 8 | s + + +def sop2(op, d, a, b): + return 0x80000000 | op << 23 | d << 16 | b << 8 | a + + +def sopc(op, a, b): + return 0xbf000000 | op << 16 | b << 8 | a + + +def sopp(op, words_back): + return 0xbf800000 | op << 16 | (-words_back) & 0xffff # target = next instruction - 4 * words_back bytes + + +MOV, ADD, CMP_LG, SCC1 = 3, 0, 7, 5 +INLINE = lambda n: 128 + n # noqa: E731 inline integer constants 0..64 +V_MOV_V0 = lambda s: 0x7e000200 | s # noqa: E731 v_mov_b32 v0, s<s> + + +def program(kind): + if kind == 'counter': + return [sop1(MOV, 14, INLINE(0)), sop1(MOV, 15, INLINE(0)), + sop2(ADD, 14, 14, INLINE(1)), sop2(ADD, 15, 15, 14), sopc(CMP_LG, 14, INLINE(5)), sopp(SCC1, 4), + V_MOV_V0(15)] + if kind == 'bound': + return [sop1(MOV, 20, INLINE(7)), sop1(MOV, 14, INLINE(0)), sop1(MOV, 15, INLINE(0)), + sop2(ADD, 14, 14, INLINE(1)), sop2(ADD, 15, 15, 14), sopc(CMP_LG, 14, 20), sopp(SCC1, 4), + V_MOV_V0(15)] + if kind == 'nested': + return [sop1(MOV, 10, INLINE(0)), sop1(MOV, 15, INLINE(0)), + sop1(MOV, 11, INLINE(0)), # O: inner counter reset + sop2(ADD, 11, 11, INLINE(1)), sop2(ADD, 15, 15, INLINE(1)), # I: inner pass, total += 1 + sopc(CMP_LG, 11, INLINE(3)), sopp(SCC1, 4), + sop2(ADD, 10, 10, INLINE(1)), sopc(CMP_LG, 10, INLINE(4)), sopp(SCC1, 8), + V_MOV_V0(15)] + raise ValueError(kind) + + +def c_to_py(expr): + expr = re.sub(r'\b(0x[0-9a-f]+|\d+)u\b', r'\1', expr) + expr = expr.replace('&&', ' and ').replace('||', ' or ') + expr = re.sub(r'!(?!=)', ' not ', expr) + m = re.fullmatch(r'\((.*)\) \? (.*) : (.*)', expr) + if m: + expr = '(%s if %s else %s)' % (m.group(2), m.group(1), m.group(3)) + return expr + + +def run(s, limit=1000): + env = {'exec': 1, 'scc': False, 'vcc': 0} + order = [b[0] for b in s.blocks] + i, visits = 0, 0 + while i is not None and i < len(s.blocks): + visits += 1 + if visits > limit: + return None, visits + off, lines, term = s.blocks[i] + for line in lines: + m = re.fullmatch(r'(?:if \(exec & 1\) )?(\w+) = (.*);', line.strip()) + assert m, line + value = eval(c_to_py(m.group(2)), {}, env) + env[m.group(1)] = value if isinstance(value, bool) else value & 0xffffffff + nxt = i + 1 + if term and term[0] == 'end': + break + if term and term[0] == 'jump': + nxt = order.index(term[1]) + elif term and term[0] == 'branch': + if eval(c_to_py(term[1]), {}, env): + nxt = order.index(term[2]) + i = nxt + return env.get('v0'), visits + + +def main(): + want = {'counter': 15, 'bound': 28, 'nested': 12} + for kind, value in want.items(): + s = stage(program(kind)) + got, visits = run(s) + assert got == value, (kind, got, visits, s.blocks) + bound = stage(program('bound')) + assert any('s14 != 0x00000007u' in line for _, lines, _ in bound.blocks for line in lines), bound.blocks + # A loop-written register whose entry value is symbolic only (a descriptor: its HLSL variable was never + # assigned) becomes a conflict that any use refuses; a run-time-backed constant is simply forgotten. + probe = stage(program('counter')) + probe.sym = {14: ('desc', 0, 0, 0), 15: ('const', 0), 20: ('desc', 0, 0, 0)} + probe.forget_loop_writes(8, 20) # loop head = word 2, back edge = word 5 + assert probe.sym == {14: ('conflict',), 20: ('desc', 0, 0, 0)}, probe.sym + saved = G.Stage.forget_loop_writes + G.Stage.forget_loop_writes = lambda self, head, last: None + try: + old = stage(program('counter')) + got, visits = run(old) + assert got is None, (got, visits, old.blocks) # the old form never leaves the loop + assert any('0x00000000u + 0x00000001u' in line for _, lines, _ in old.blocks for line in lines) + finally: + G.Stage.forget_loop_writes = saved + print('loop_carried: counter loop 15 (5 passes), constant bound not written in the loop still folds (28), ' + 'nested 4 x 3 = 12; old behaviour (entry constants kept at the head) never exits: negative control') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_loop_regions_check.py b/tests/startup_loop_regions_check.py new file mode 100644 index 0000000000..a1c43891fb --- /dev/null +++ b/tests/startup_loop_regions_check.py @@ -0,0 +1,184 @@ +"""Stage.body: only the back-edge regions of the block graph run inside a dispatch loop. + +The old form put every block of a program with any back edge in one `[loop] for` dispatch over pc; the new one +puts the blocks of each merged [loop head, back-edge source] interval in its own loop and tests the others once, in +offset order. Claim: the same blocks run in the same order. Checked on 3000 random block graphs (3..14 blocks; each +block falls through, ends, jumps or branches to any block; conditions drawn per visit from a seeded generator, so +both forms see the same values): the emitted text of body() is interpreted (block markers `if (pc == i)`, region +loops `pc >= lo && pc <= hi`, the pc assignments) and its block trace compared with the old form's semantics, a +plain dispatch loop. Traces are cut at 300 block visits in both. Negative control: an interpreter that skips the +region loops (one pass) differs on graphs with loops. Also: a loop-free graph emits no `[loop]`, and the measured +case (two short waterfall loops inside a long program) gets two small loops. +""" +import random +import re +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +LIMIT = 300 + + +class Fake: + body = G.Stage.body + LOOP_PASSES = 10 ** 6 # the trace comparison checks the control flow; the bound is checked on its own + + def __init__(self, blocks): + self.blocks = blocks + + +class Bounded(Fake): + LOOP_PASSES = G.Stage.LOOP_PASSES + + +def make(rng, n): + blocks = [] + for i in range(n): + kind = rng.random() + if i == n - 1 and kind < 0.3: + term = ('end',) + elif kind < 0.35: + term = None + elif kind < 0.45: + term = ('end',) + elif kind < 0.6: + term = ('jump', 0x10 * rng.randrange(n)) + else: + term = ('branch', 'c%d' % i, 0x10 * rng.randrange(n)) + blocks.append((0x10 * i, ['trace(%d);' % i], term)) + return blocks + + +class Conds: + def __init__(self, seed): + self.seed, self.visits = seed, {} + + def __call__(self, block): + k = self.visits[block] = self.visits.get(block, 0) + 1 + return random.Random(self.seed * 100003 + block * 1009 + k).random() < 0.5 + + +def reference(blocks, conds): + trace, pc = [], 0 + while pc != 0xffff and len(trace) < LIMIT: + _, _, term = blocks[pc] + trace.append(pc) + nxt = pc + 1 if pc + 1 < len(blocks) else 0xffff + if not term: + pc = nxt + elif term[0] == 'end': + pc = 0xffff + elif term[0] == 'jump': + pc = term[1] // 0x10 + else: + pc = term[2] // 0x10 if conds(pc) else nxt + return trace + + +def parse(lines): + """[('block', i, pc_line)] and [('loop', lo, hi, [blocks])] in order.""" + items, cur, loop = [], None, None + for line in lines: + s = line.strip() + m = re.match(r'\[loop\] for \(uint guard = 0; guard < (\d+)u && pc >= (\d+) && pc <= (\d+); \+\+guard\) \{', s) + if m: + loop = ('loop', int(m.group(2)), int(m.group(3)), [], int(m.group(1))) + items.append(loop) + continue + m = re.match(r'(?:else )?if \(pc == (\d+)\) \{', s) + if m: + cur = [int(m.group(1)), None] + (loop[3] if loop else items).append(('block', cur)) + continue + if s.startswith('pc = ') and cur is not None: + cur[1] = s + elif s == '}' and cur is None and loop is not None: + loop = None + elif s == '}': + cur = None + return items + + +def run_pc(line, i, conds): + m = re.fullmatch(r'pc = \((c\d+)\) \? (\d+) : (\d+);', line) + if m: + return int(m.group(2)) if conds(i) else int(m.group(3)) + return 0xffff if line == 'pc = 0xffffu;' else int(re.fullmatch(r'pc = (\d+);', line).group(1)) + + +def emitted(lines, conds, loops=True, limit=LIMIT): + trace, pc = [], 0 + + def block(b): + nonlocal pc + trace.append(b[0]) + pc = run_pc(b[1], b[0], conds) + for item in parse(lines): + if item[0] == 'block': + if pc == item[1][0] and len(trace) < limit: + block(item[1]) + else: + _, lo, hi, members, bound = item + guard = 0 + while lo <= pc <= hi and guard < bound and len(trace) < limit: + guard += 1 + for _, b in members: + if pc == b[0]: + block(b) + break + if not loops: + break + return trace + + +def main(): + rng = random.Random(11) + looped = differ = 0 + for seed in range(3000): + blocks = make(rng, rng.randrange(3, 15)) + lines = Fake(blocks).body() + want = reference(blocks, Conds(seed)) + got = emitted(lines, Conds(seed)) + assert got == want, (seed, blocks, lines, want[:20], got[:20]) + if any('[loop]' in x for x in lines): + looped += 1 + differ += emitted(lines, Conds(seed), loops=False) != want + assert looped > 500 and differ > 100, (looped, differ) + straight = [(0x10 * i, ['trace(%d);' % i], ('branch', 'c', 0x10 * (i + 2)) if i < 8 else None) for i in range(10)] + assert not any('[loop]' in x for x in Fake(straight).body()) + measured = [(0x10 * i, ['x;'], None) for i in range(40)] + measured[12] = (0xc0, ['x;'], ('branch', 'scc', 0xc0)) + measured[20] = (0x140, ['x;'], ('branch', 'scc', 0x130)) + lines = Fake(measured).body() + heads = [x.strip() for x in lines if '[loop]' in x] + assert heads == ['[loop] for (uint guard = 0; guard < 1000000u && pc >= 12 && pc <= 12; ++guard) {', + '[loop] for (uint guard = 0; guard < 2000000u && pc >= 19 && pc <= 20; ++guard) {'], heads + # The real bound: 64 passes through each region. Adversarial graphs whose loops never exit (a block jumping + # to itself, a two-block cycle, a branch that is always taken) end after at most 64 * blocks visits (pc is + # then still inside the region, so the later blocks are skipped: a wrong result, not a hang); negative + # control: without the bound the trace runs into the 10000-visit cut. + always = lambda block: True # noqa: E731 + spins = { + 'self jump': [(0x0, ['a;'], None), (0x10, ['b;'], ('jump', 0x10)), (0x20, ['c;'], ('end',))], + 'cycle': [(0x0, ['a;'], None), (0x10, ['b;'], None), (0x20, ['c;'], ('jump', 0x10)), (0x30, ['d;'], ('end',))], + 'taken branch': [(0x0, ['a;'], ('branch', 'c0', 0x0)), (0x10, ['d;'], ('end',))], + } + for name, graph in spins.items(): + lines = Bounded(graph).body() + bounds = [int(re.search(r'guard < (\d+)u', x).group(1)) for x in lines if '[loop]' in x] + size = len(graph) - (2 if name != 'taken branch' else 1) + assert bounds == [64 * size], (name, bounds) + trace = emitted(lines, always, limit=10 ** 7) + assert len(trace) <= 64 * size + 2, (name, len(trace)) + unbounded = emitted(Fake(graph).body(), always, limit=10 ** 4) + assert len(unbounded) == 10 ** 4, name + print('loop_regions: %d random graphs run the same block trace as one dispatch loop (%d with loops; the ' + 'one-pass negative control differs on %d); loop-free graph has no loop; two waterfall loops get two ' + 'loops of 1 and 2 blocks; 3 never-exiting loops stop after 64 passes (the unbounded control runs ' + 'into the cut)' % (3000, looped, differ)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_memory_srv_announced_check.py b/tests/startup_memory_srv_announced_check.py new file mode 100644 index 0000000000..3bcb918d28 --- /dev/null +++ b/tests/startup_memory_srv_announced_check.py @@ -0,0 +1,111 @@ +"""Memory SRVs of console-swizzled (layout 0x105) textures whose memory the XG stand-in filled. + +X2W_MEMORY_SRV_ANNOUNCED=1: views of announced addresses are drawn from the linear (desktop footprint) bytes, +both mips; a texture with the same description and bytes that XG did not announce is refused. Without the +switch every call is refused and the draws read a null view (negative control). +""" +from pathlib import Path +import sys +import tempfile + +from startup_address_srv_check import draw_texture + +HLSL = ("Texture2D<float4> t : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint2 q = uint2(p.xy);\n" + " if (q.y < 2) return t.Load(int3(q.x % 2, q.y, 0));\n" + " return t.Load(int3(0, 0, 1));\n}\n") + + +def texel(which, mip, x, y): + if mip: + return (9, 99, 199, 255) if which == 1 else (5, 6, 7, 255) + return (100 + 20 * x + 50 * y, 50, 150, 255) if which == 1 else (10 + 40 * x + 80 * y, 200, 30, 255) + + +def expected_on(): + # Columns publish A B C A B C A A; C is refused, so the previous view (B) stays. + effective = (0, 1, 1, 0, 1, 1, 0, 0) + return bytes(c for y in range(4) for x in range(8) + for c in (texel(effective[x], 0, x % 2, y) if y < 2 else texel(effective[x], 1, 0, 0))) + + +def run(directory, consumer, backend, switch, census=False): + # draw_texture sets X2W_D3D12_DEVICE_NOOP=1 (as title runs do): device slot 61, which the test calls last, is + # the no-op unless the census replaces it. + modes = {"X2W_TEST_ANNOUNCED_SRV": "1", "X2W_TRAP_LOG": str(directory / "trap.log")} + if switch: + modes["X2W_MEMORY_SRV_ANNOUNCED"] = "1" + if census: + modes["X2W_TEXTURE_CENSUS"] = "1" + modes["X2W_TEXTURE_CENSUS_EVERY"] = "1" + pixels = draw_texture(directory, consumer, backend, HLSL, modes) + return pixels, (directory / "trap.log").read_text(errors="replace") if pixels is not None else "" + + +def last_census(log, prefix): + lines = [line for line in log.splitlines() if line.startswith("x2w-texcensus " + prefix)] + return lines[-1] if lines else "" + + +def check_census(log, label, slot70, refusal_classes, draws): + """The last cumulative X2W_TEXTURE_CENSUS lines of a run (X2W_TEXTURE_CENSUS_EVERY=1).""" + want_calls = f"slot70 calls 8 (threshold, cumulative): {slot70}" + if want_calls not in last_census(log, "slot70 calls"): + raise AssertionError(f"{label}: last slot-70 census line {last_census(log, 'slot70 calls')!r}, expected {want_calls!r}") + lines = log.splitlines() + head = max(i for i, line in enumerate(lines) if line.startswith("x2w-texcensus slot70 refusals")) + classes = [line.removeprefix("x2w-texcensus ") for line in lines[head + 1:head + 1 + len(refusal_classes)]] + if classes != refusal_classes: + raise AssertionError(f"{label}: refusal classes {classes}, expected {refusal_classes}") + want_draws = f"draw textures binding (cumulative): {draws}" + if want_draws not in last_census(log, "draw textures"): + raise AssertionError(f"{label}: last draw census line {last_census(log, 'draw textures')!r}, expected {want_draws!r}") + words = " ".join(f"{0x61000000 + i:08x}" for i in range(16)) + slot61 = [line for line in lines if line.startswith("x2w-texcensus Device::slot61")] + if len(slot61) != 1 or "r8=0x5150 r9=0x1 words " + words not in slot61[0]: + raise AssertionError(f"{label}: slot-61 lines {slot61}") + + +def check(root, consumer, backend): + on_dir, off_dir, census_dir = root / "on", root / "off", root / "census" + on_dir.mkdir() + off_dir.mkdir() + census_dir.mkdir() + actual, log = run(on_dir, consumer, backend, True, census=True) + if actual is None: + return 77 + if actual != expected_on(): + raise AssertionError(f"switch on: actual {actual.hex()}\n expected {expected_on().hex()}") + if "X2W_MEMORY_SRV_ANNOUNCED=1" not in log: + raise AssertionError("switch on: no X2W_MEMORY_SRV_ANNOUNCED line") + refusals = [line for line in log.splitlines() if "Device::slot70" in line and "reason=" in line] + if len(refusals) != 2 or not all("layout=0x105" in line for line in refusals): + raise AssertionError("switch on: expected the two unannounced calls refused:\n" + "\n".join(refusals)) + unannounced = "2 x unsupported_description dim 3 layout 0x105 fmt 28 mips>1 not-announced nonzero" + check_census(log, "switch on, census", "linear 0, announced-linear 6, tiled/bc64 0, buffer 0, stand-in buffer 0, detiled 0, refused 2", + [unannounced], "real 8 (linear memory srv 8, tiled address 0, other 0, detiled 0), null; real by format 28:8") + # Census without the announced switch: all 8 calls refused (6 at announced addresses), 8 null bindings. + census_off, census_log = run(census_dir, consumer, backend, False, census=True) + if census_off != bytes(4 * 8 * 4): + raise AssertionError(f"census, switch off: expected null views (all zero), got {census_off.hex()}") + check_census(census_log, "census, switch off", "linear 0, announced-linear 0, tiled/bc64 0, buffer 0, stand-in buffer 0, detiled 0, refused 8", + ["6 x unsupported_description dim 3 layout 0x105 fmt 28 mips>1 announced nonzero", unannounced], + "real 0 (linear memory srv 0, tiled address 0, other 0, detiled 0), null cause2:8; real by format") + off, off_log = run(off_dir, consumer, backend, False) + if off != bytes(4 * 8 * 4): + raise AssertionError(f"switch off: expected null views (all zero), got {off.hex()}") + off_refusals = [line for line in off_log.splitlines() if "Device::slot70" in line and "reason=" in line] + if len(off_refusals) != 8: + raise AssertionError(f"switch off: {len(off_refusals)} refusal lines, expected 8") + if "x2w-texcensus" in off_log: + raise AssertionError("census off: x2w-texcensus lines logged") + print(f"{backend}: announced 0x105 views drawn (2 mips, 32 RGBA pixels exact), unannounced refused; " + "switch off: 8 refusals, null views; census counts exact (8 real / 8 null, refusal classes, slot 61), " + "census off: no census lines, slot 61 no-op") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_memory_srv_detile.ps1 b/tests/startup_memory_srv_detile.ps1 new file mode 100644 index 0000000000..70f9d13e49 --- /dev/null +++ b/tests/startup_memory_srv_detile.ps1 @@ -0,0 +1,118 @@ +param([string] $Consumer, [string] $Backend, [string] $Fxc, [string] $LayoutCheck) +. "$PSScriptRoot/startup_detile_draw.ps1" +$ErrorActionPreference = 'Stop' +$env:X2W_TEXTURE_CENSUS = '1' +$env:X2W_TEXTURE_CENSUS_EVERY = '1' + +# name, layout, dimension, DXGI format, width, height, depth/array size, mip count +$cases = @( + @('bc1_256_9mips_4k_s', 0x105, 3, 71, 256, 256, 1, 9), + @('bc1_256x128x2_8mips_64k_d', 0x10a, 3, 71, 256, 128, 2, 8), + @('bc3_256_9mips_4k_s', 0x105, 3, 77, 256, 256, 1, 9), + @('rgba16f_17cubed_3d_5mips', 0x105, 4, 10, 17, 17, 17, 5), + @('rgba16f_100x60_3mips_linear', 0x100, 3, 10, 100, 60, 1, 3), + @('bc1_132_8mips_4k_s', 0x105, 3, 71, 132, 132, 1, 8), + @('bc3_132x68x2_8mips_64k_d', 0x10a, 3, 77, 132, 68, 2, 8) +) + +function Test-Surface($spec, $mode, $override = 0) { + $name, $layout, $dim, $format, $width, $height, $depth, $mips = $spec + $dir = Join-Path $root "$name-$mode" + [IO.Directory]::CreateDirectory($dir) | Out-Null + $bc = $format -in 71, 77 + if ($dim -eq 4) { $kind = 'tex3d'; $type = 'Texture3D' } + elseif ($depth -gt 1) { $kind = 'tex2da'; $type = 'Texture2DArray' } + else { $kind = 'tex2d'; $type = 'Texture2D' } + $body = [Text.StringBuilder]::new() + $expected = 0 + for ($mip = 0; $mip -lt $mips; $mip++) { + $w = [Math]::Max(1, $width -shr $mip) + $h = [Math]::Max(1, $height -shr $mip) + if ($bc) { $w = ($w + 3) -shr 2; $h = ($h + 3) -shr 2 } + $slices = $depth; $d = 1 + if ($dim -eq 4) { $slices = 1; $d = [Math]::Max(1, $depth -shr $mip) } + $count = $w * $h * $d + for ($s = 0; $s -lt $slices; $s++) { + $expected += $count + $xy = if ($bc) { '4*x,4*y' } else { 'x,y' } + $coord = switch ($kind) { + 'tex3d' { "int4(x,y,z,$mip)" } + 'tex2da' { "int4($xy,$s,$mip)" } + 'tex2d' { "int3($xy,$mip)" } + } + $tag = $mip + 8 * $s + $test = if ($bc) { + $alpha = if ($format -eq 77) { " || uint(round(c.a*255)) != $(16*$tag+5)u" } else { '' } + "uint id=(uint(round(c.r*31))<<11)|(uint(round(c.g*63))<<5)|uint(round(c.b*31)); if (id!=(x|(y<<6)|(${tag}u<<12))$alpha) bad++;" + } else { "if(any(c!=float4(x,y,z,$($mip+1)))) bad++;" } + [void]$body.AppendLine("[loop] for(uint i=p; i<${count}u; i+=4096u){uint x=i%${w}u,y=(i/${w}u)%${h}u,z=i/$($w*$h)u;float4 c=t.Load($coord); $test n++;}") + } + } + $shader = @" +${type}<float4> t : register(t0); +float4 ps(float4 pos : SV_Position) : SV_Target { + uint p=uint(pos.y)*64u+uint(pos.x), bad=0, n=0; + $body + return float4(bad ? 0 : 1,n/255.0,0,1); +} +"@ + $env:X2W_MEMORY_SRV_DETILE = if ($mode -eq 'off') { $null } else { '1' } + if ($override) { $layout = $override } + $env:X2W_TEST_DETILE_DESC = '{0:x} {1} {2} {3} {4} {5} {6}' -f $layout,$dim,$format,$width,$height,$depth,$mips + $env:X2W_TEST_DETILE_SRV = "$root/$name.bin" + $pixels = Invoke-DetileDraw $dir $Consumer $Backend $Fxc $shader $kind + if ($pixels.Length -ne 16384) { throw "$name read back $($pixels.Length) bytes" } + $bad = 0; $checked = 0 + for ($i=0; $i -lt $pixels.Length; $i+=4) { + if ($pixels[$i] -ne 255) { $bad++ } + $checked += $pixels[$i+1] + } + $log = Get-Content "$dir/trap.log" + $detiled = @($log -like '*x2w-memsrv detiled memory SRV*') + $refused = @($log -like '*Device::slot70*reason=*') + if ($checked -ne $expected) { throw "$name ($mode) shader checked $checked of $expected elements" } + switch ($mode) { + 'on' { + $lastSlot = @($log -like 'x2w-texcensus slot70 calls*')[-1] + $lastDraw = @($log -like 'x2w-texcensus draw textures*')[-1] + $layoutTag = 'layout 0x{0:x}' -f $layout + if ($bad -or !$detiled.Count -or !($log -like "*$layoutTag*") -or + $lastSlot -notlike '*stand-in buffer 0, detiled 2, refused 0*' -or $lastDraw -notlike '*detiled 1)*') { + throw "$name mismatch pixels=$bad, slot=$lastSlot, draw=$lastDraw" + } + } + 'off' { if (!$bad -or $refused.Count -ne 2 -or $detiled.Count) { throw "$name switch-off control failed" } } + 'wrong' { if (!$bad -or !$detiled.Count) { throw "$name wrong-layout control failed" } } + 'declined' { + $classes = @($log -like 'x2w-texcensus 2 x *') + $counters = @($log -like 'x2w-texcensus detile declines of refused texture calls*') + $first = @($log -like '*new refusal class*') + if (!$bad -or $detiled.Count -or $classes[-1] -notlike '*detile: layout or element size*' -or + $counters[-1] -notlike '*layout or element size 2*' -or $first.Count -ne 1 -or + $first[0] -notlike '*detile: layout or element size;*') { throw "$name decline accounting failed" } + } + } + Write-Host "$Backend $name ($mode) checked $checked elements, mismatch pixels=$bad" +} + +$root = Join-Path ([IO.Path]::GetTempPath()) ('x2w-detile-' + [Guid]::NewGuid().ToString('N')) +[IO.Directory]::CreateDirectory($root) | Out-Null +try { + foreach ($case in $cases) { + $name = $case[0] + $surface = "$root/$name.bin" + & $LayoutCheck --write-tiled $name $surface --addrlib + if ($LASTEXITCODE -eq 77) { + Write-Host "$name uses native layout output (plumbing check only)" + & $LayoutCheck --write-tiled $name $surface + } + if ($LASTEXITCODE -ne 0) { throw "$name surface generation failed" } + Test-Surface $case 'on' + } + Test-Surface $cases[0] 'off' + foreach ($index in 0, 5, 6) { Test-Surface $cases[$index] 'wrong' 0x109 } + # XOR display tiling is outside the single-sample address equations. + Test-Surface @('bc1_132_8mips_4k_s', 0x11a, 3, 28, 64, 64, 1, 1) 'declined' +} finally { + [IO.Directory]::Delete($root, $true) +} diff --git a/tests/startup_mesh_barrier_ranges_check.py b/tests/startup_mesh_barrier_ranges_check.py new file mode 100644 index 0000000000..498731b9c8 --- /dev/null +++ b/tests/startup_mesh_barrier_ranges_check.py @@ -0,0 +1,105 @@ +"""Check that tools/startup/mesh2hlsl.py runs a group-uniform execz range that holds a phase barrier instead of +skipping it (MeshStage.translate; X2W_MESH_BARRIER_RANGES). + +usage: startup_mesh_barrier_ranges_check.py [--write <dir>] + +A group-uniform execz range (a range that writes a scalar live after it) publishes "some lane of this wave is +active" and ends its first block in a group barrier (MeshStage.group_branch). When such a range encloses another +one, the inner publish barrier lies inside the outer range: the edge that skips the outer range (no lane of the +group active) crosses one barrier fewer than the edge through it, and barrier_count() refused the program +("paths cross different numbers of barriers"). The skip is a group-uniform choice, but body() gives every block one +phase, so the outer range is now always run: with no lane active every vector write, export and LDS write is +guarded off, and each wave with no active lane gets the hit scalars back at the range end (the existing restore). + +Hand-assembled gfx1013 NGG program (no title bytes; encoder of tests/startup_mesh_exec_restore_check.py). Per group +g: N = 40 + 60 * (g & 1) (wave 1 has no lane with v0 < N when N = 40), T = 20 * (g & 3). + + s40 = 7; s41 = 3; exec = v0 < N; execz -> AFTER (outer: s40 written inside, read after) + s40 = 11; exec &= v0 < T; execz -> INNER (inner: s41 written inside, read after) + s41 = 13; v1 = 9 + INNER: + AFTER: exec = -1; v4 = s40; v6 = s41; param0 = (v1, v0, v4, v6) + +Hardware meaning (AMD RDNA 2 ISA, S_CBRANCH_EXECZ skips for a wave whose EXEC is 0, so its scalars keep their +values): per wave, s40 = 11 if some lane has v0 < N else 7; s41 = 13 if some lane has v0 < min(N, T) else 3; +v1 = 9 in lanes v0 < min(N, T), else 5. + +Checks: decodes to the intended text; translates with the rule on; the outer range has no skip branch and the inner +(which holds no barrier) keeps its skip; both restores are present; negative control X2W_MESH_BARRIER_RANGES=0 +refuses again with the f37ad9f8 reason. --write keeps the program for mesh_work/difftest.py. +""" +import os +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 (encoder, prologue, assembler) + +I, ins, exp = E.I, E.ins, E.exp + +PROGRAM = E.PROLOGUE + [ + I('s_mov_b32 s40, 7', 'sop1', 's_mov_b32', d=40, s0='7'), + I('s_mov_b32 s41, 3', 'sop1', 's_mov_b32', d=41, s0='3'), + E.CMPX_N, + ('s_cbranch_execz AFTER', 'execz'), + I('s_mov_b32 s40, 11', 'sop1', 's_mov_b32', d=40, s0='11'), + E.CMPX_T, + ('s_cbranch_execz INNER', 'execz'), + I('s_mov_b32 s41, 13', 'sop1', 's_mov_b32', d=41, s0='13'), + E.V1_9, + ('INNER:', None), + ('AFTER:', None), + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('s_mov_b32 m0, 0x80080', 'sop1', 's_mov_b32', d=124, s0='0x80080'), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + I('v_mov_b32_e32 v4, s40', 'vop1', 'v_mov_b32_e32', d=4, s0='s40'), + I('v_mov_b32_e32 v6, s41', 'vop1', 'v_mov_b32_e32', d=6, s0='s41'), + I('v_cvt_f32_u32_e32 v2, v0', 'vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0'), + I('v_mov_b32_e32 v3, 0', 'vop1', 'v_mov_b32_e32', d=3, s0='0'), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v1, v0, v4, v6', lambda: exp(32, ['v1', 'v0', 'v4', 'v6'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] + + +def translate(path, env): + return E.translate(path, dict({'X2W_MESH_BARRIER_RANGES': '1'}, **env)) + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_barrier_ranges') + os.makedirs(out_dir, exist_ok=True) + code, texts = E.assemble(PROGRAM) + path = os.path.join(out_dir, 'nested.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + E.check('decodes to the intended %d instructions' % len(texts), [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = translate(path, {}) + E.check('translates with the rule on', on.startswith('OK'), on[:300]) + skips = [k for k in range(4) if '(x2w_any[%d][0] | x2w_any[%d][1]) == 0u' % (k, k) in on] + E.check('two group-uniform ranges published', 'x2w_any[1][wave] = 1u' in on and 'x2w_any[2][wave]' not in on, '') + E.check('outer range (k 0, holds the inner publish barrier) is not skipped; inner (k 1) keeps its skip', + skips == [1], 'skip branches for k = %s' % skips) + E.check('s40 restored for a wave with no lane in the outer range', 'x2w_any[0][wave] == 0u) s40 = ' in on, '') + E.check('s41 restored for a wave with no lane in the inner range', 'x2w_any[1][wave] == 0u) s41 = ' in on, '') + off = translate(path, {'X2W_MESH_BARRIER_RANGES': '0'}) + E.check('negative control: X2W_MESH_BARRIER_RANGES=0 refuses again', + # f37ad9f8 refused in barrier_count; since 28020dea (uniform skips over translator barriers) the skip + # check in body() refuses first, because the inner range's publish barrier is not a lane-SCC one + off.startswith(('REFUSED paths cross different numbers of barriers', + 'REFUSED s_barrier inside a group-uniform execz range')), off[:200]) + print('program written to %s (difftest: python -B difftest.py %s <harness> --groups 4 --seed 1)' % (path, path)) + if E.failures: + print('%d check(s) failed' % len(E.failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_desc_numeric_check.py b/tests/startup_mesh_desc_numeric_check.py new file mode 100644 index 0000000000..0ec948930a --- /dev/null +++ b/tests/startup_mesh_desc_numeric_check.py @@ -0,0 +1,20 @@ +from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools/startup')) +import mesh2hlsl as M + + +def accepts(tail): + code = ['s_bfe_u32 s67, s67, 0x10000e', 's_add_u32 s67, s67, 1', 's_max_u32 s67, s67, 1', + 's_cbranch_scc0 label_0x14', 'v_cvt_f32_i32_e32 v1, s67', tail, 's_endpgm'] + stage = M.MeshStage.__new__(M.MeshStage) + stage.pc = 0 + stage.ins = [(i * 4, 4, line.split()[0], line) for i, line in enumerate(code)] + return stage.descriptor_numeric_field('s_bfe_u32', ['s67', 's67', '0x10000e']) + + +if __name__ == '__main__': + assert accepts('s_mov_b32 s67, 0') + assert not accepts('s_mov_b32 s11, s67') + assert not accepts('s_buffer_load_dword s12, s[64:67], 0') + print('PASS: numeric field use, escaped copy and descriptor use on another path') diff --git a/tests/startup_mesh_descword_check.py b/tests/startup_mesh_descword_check.py new file mode 100644 index 0000000000..8a486b3ec2 --- /dev/null +++ b/tests/startup_mesh_descword_check.py @@ -0,0 +1,106 @@ +"""Table descriptor words read as numbers in the mesh-stage translator (mesh2hlsl MeshStage.dw_*, +X2W_MESH_FEATURES=descword; runtime: d3d12_draw.inl `udsrc <n> descword <param> <byte>`, X2W_MESH_DESCWORD=1). + +Hand-assembled NGG mesh programs (no cache bytes), RDNA 2 ISA encodings; root parameter 0 is a descriptor table +(s16 = its pointer: the mesh stage's user SGPRs start at s16), parameter 1 a root constant: + + 0x00 s_load_dwordx4 s[20:23], s[16:17], 0x20 a V# from table 0 entry 1 (byte 0x20): s22 = word 2 (NUM_RECORDS) + 0x08 s_waitcnt lgkmcnt(0) + 0x0c s_mul_i32 s24, s22, 3 a number computed from word 2 (byte 0x28) + 0x10 s_lshr_b32 s25, s21, 16 from word 1 (byte 0x24), never read: dead + 0x14 v_cvt_f32_u32 v1, s24 the numeric use; then exp pos0 v1 / prim, s_endpgm + +Checks: + lazy translates; the manifest has `udsrc <n> descword 0 40` and no entry value for byte 36; the HLSL computes + s24 from that entry value (ud<n> * 3) and s25 from 0u + edit 0x0c-0x10 become s_or_b32 s22, s22, 1 (an in-place edit) then s_mul_i32 s24, s22, 3: refused ("edited + descriptor word": the table's word is no longer the register's value); the same with s_or_b32 s22, s22, s17 + (the other operand a root constant) + reload as edit, then the same s_load again before the multiply: translates (a fresh load is the table's word) +Negative control: without X2W_MESH_FEATURES=descword `lazy` is refused ("numeric use of s24 holding descnum"; run in +a child). +""" +import os +import re +import struct +import subprocess +import sys + +if os.environ.get('X2W_DESCWORD_CHILD') != '1': + os.environ['X2W_MESH_FEATURES'] = 'descword' + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import root_blob # noqa: E402 + +LOAD = (0xf4080508, 0xfa000020) # s_load_dwordx4 s[20:23], s[16:17], 0x20 +WAIT = (0xbf8cc07f,) # s_waitcnt lgkmcnt(0) +MUL = (0x93188316,) # s_mul_i32 s24, s22, 3 +DEAD = (0x90199015,) # s_lshr_b32 s25, s21, 16 +EDIT = (0x88168116,) # s_or_b32 s22, s22, 1 +EDIT_UD = (0x88161116,) # s_or_b32 s22, s22, s17 (s17 = the root constant) +USE = (0x7e020c18,) # v_cvt_f32_u32 v1, s24 +TAIL = (0x7e040280, # v_mov_b32 v2, 0 + 0xb07c1003, # s_movk_i32 m0, 0x1003 + 0xbf900009, # s_sendmsg 0x9 + 0xf80008cf, 0x02020201, # exp pos0 v1, v2, v2, v2 done + 0xf8000941, 0x00000002, # exp prim v2 done + 0xbf810000) # s_endpgm + + +def program(*parts): + words = [w for p in parts for w in p] + list(TAIL) + return struct.pack('<%dI' % len(words), *words) + + +LAZY = program(LOAD, WAIT, MUL, DEAD, USE) +EDITED = program(LOAD, WAIT, EDIT, MUL, USE) +EDITED_UD = program(LOAD, WAIT, EDIT_UD, MUL, USE) +RELOAD = program(LOAD, WAIT, EDIT, LOAD, WAIT, MUL, USE) +TEXT = ['s_load_dwordx4 s[20:23], s[16:17], 0x20', 's_waitcnt lgkmcnt(0)', 's_mul_i32 s24, s22, 3', + 's_lshr_b32 s25, s21, 16', 'v_cvt_f32_u32_e32 v1, s24'] + + +def translate(code): + try: + pipe = M.MeshPipeline(code, None, root_blob()) + return pipe.hlsl_ms(), pipe.manifest() + except G.Unsupported as e: + return str(e), None + + +def check(): + text = [x[3] for x in G.decode(LAZY)][:len(TEXT)] + assert text == TEXT, text + assert [x[3] for x in G.decode(EDITED)][2] == 's_or_b32 s22, s22, 1' + hlsl, manifest = translate(LAZY) + assert manifest is not None, ('lazy', hlsl) + used = re.search(r'^udsrc (\d+) descword 0 40$', manifest, re.M) + assert used and not re.search(r'descword 0 36$', manifest, re.M), manifest + assert re.search(r'\bs24 = ud%s \* 0x00000003u;' % used.group(1), hlsl), hlsl + assert re.search(r'\bs25 = 0u >> ', hlsl) and 'X2W_DW' not in hlsl, hlsl + assert [x[3] for x in G.decode(EDITED_UD)][2] == 's_or_b32 s22, s22, s17' + for name, code in (('edit', EDITED), ('edit by a root constant', EDITED_UD)): + got = translate(code) + assert got[1] is None and 'edited descriptor word' in got[0], (name, got[0][:200]) + got = translate(RELOAD) + assert got[1] is not None and re.search(r'^udsrc \d+ descword 0 40$', got[1], re.M), ('reload', got[0][:200]) + return 'word 2 an entry value, dead word 1 0u; in-place edit refused; reload after the edit translates' + + +def main(): + if os.environ.get('X2W_DESCWORD_CHILD') == '1': # child of the negative control: the feature is off + check() + return + summary = check() + env = dict(os.environ, X2W_DESCWORD_CHILD='1', X2W_MESH_FEATURES='') + r = subprocess.run([sys.executable, '-B', os.path.abspath(__file__)], env=env, capture_output=True, text=True) + assert r.returncode != 0 and 'holding descnum' in r.stderr, ('negative control passed', r.stdout, r.stderr) + print('mesh descword: %s; without X2W_MESH_FEATURES=descword refused (%s)' + % (summary, r.stderr.strip().splitlines()[-1][:100])) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_mesh_dispatch.cpp b/tests/startup_mesh_dispatch.cpp new file mode 100644 index 0000000000..2a7e769939 --- /dev/null +++ b/tests/startup_mesh_dispatch.cpp @@ -0,0 +1,1401 @@ +// DispatchMesh ExecuteIndirect (list slot 61) through a translated mesh pipeline (d3d12_mesh.inl). +// +// startup_mesh_dispatch <warp|hardware> <gpu|derived|zero|huge|off|missing|depth|words16|words32|wordsraw| +// fmaprecise|fmabad|notargets|rtvuint|smpheap|smpheapswap| +// statez|statezge|statezoff|statecull|stateculloff|statedepth|statecullflip| +// statecullnone|statezrepeat|statezuncleared|statezlateclear|async|asyncone| +// rtvvariant|uavtex|uavtexnoflag|rtvnops> +// state modes (X2W_MESH_STATE, see main): statez drawn + depth 0.25 over a 0.5 clear; statezge nothing drawn, depth +// 0.5; statezoff (switch unset) drawn, depth 0.5; statecull left (clockwise) culled, right (other winding) drawn; stateculloff +// both drawn; statedepth (depth-only, hardware) depth 0.25 over a 1.0 clear. +// smpheap / smpheapswap (`smpheap 2048 1 fallback 2047`, PixelSampler): a title sampler heap of 128 raw S# entries +// bound with SetDescriptorHeaps; the pixel stage samples entry 65 over a 2x1 texture (srv 1, placed on title memory: +// texel 0 red, texel 1 blue) at u = 0.375. smpheap: 65 point, 64 linear -> red ff0000ff; smpheapswap (control): 65 +// linear, 64 point -> 0.75 red + 0.25 blue (ff4000bf +-3). Both: the "x2w-draw sampler heap:" line has no unbound +// and no unreadable entry. +// fma line: derived has none ("fma unstated"), fmaprecise `fma precise` (drawn), fmabad `fma fused` (refused: +// translation failed), the other modes `fma exact` (needs DoublePrecisionFloatShaderOps). notargets: no +// OMSetRenderTargets; rtvuint: an R32_UINT target: both refused once with "call refused (...)", nothing drawn; +// rtvuint also checks that req_<variant>.rtv was published with "rtv1 <key> 42". rtvvariant (R32_UINT target): the +// cache also holds the RTV variant (key fnv("rtv1 <key> 42"), manifest with that line, pixel stage PixelUint which +// packs the colour into one uint): the PSO is built from the variant, drawn 0x00ff40c0, no refusal line. +// wordsoob (as words32, hardware): the 4-slot view heap is placed on test memory and slot 2's token + id are copied +// to slot 4, one past its end; the shader reads slot 4. heapmem is a bounded view (128 bytes), so the read gives 0: +// nothing drawn. (A root SRV, the earlier binding, has no bounds and would find the copied token and draw.) +// descword / descwordoff (LOCAL ind-meshps): manifest `udsrc 2 descword 1 8`, mesh stage MeshDescword: entry value 2 is +// dword 2 (NUM_RECORDS) of the hardware buffer descriptor in table parameter 1 entry 0, i.e. 48. descword (the test sets +// X2W_MESH_DESCWORD=1) draws with green 0x30 and logs the title word 0x30; descwordoff (the switch unset, the control) +// refuses the translation ("needs X2W_MESH_DESCWORD=1"): nothing drawn, no call issued. +// rtvnops: no pixel stage (as depth) with an R32_UINT render target: issued from the base, no variant request, no refusal (hardware; WARP: capability skip, as depth). +// uavtex / uavtexnoflag: `uav 0 tex2d table 1 <2 increments>` and pixel stage PixelStore (stores the colour to the texture +// UAV, returns it): uavtex (RGBA8 texture with unordered access + UAV) binds the UAV and draws; uavtexnoflag (control: no +// unordered access, an SRV) skips the call ("draw skipped: texture uav: ..." and the bind refusal). The stored texels +// are not read back (the placed texture's desktop resource is the stand-in's). +// (X2W_D3D12_RENDER=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_DEBUG=1; X2W_MESH=1 except mode off; +// the test sets X2W_SHADER_CACHE and X2W_TRAP_LOG itself) +// +// A fake slot-57 mesh record: [0] a title root signature, [5]/[6] fake pixel code (null in mode depth), [9]-[12] null, +// [13]/[14] fake mesh code. The test computes the mesh key exactly as the rule says (pipeline_key(a or empty, b = [13], +// root)) and writes <key>.txt (manifest with `stage mesh`), <key>.ms.cso and <key>.ps.cso (dxc-built DXIL of +// startup_mesh_dispatch.hlsl) into the shader cache (mode missing: nothing). +// One list through the console slots: a container compute writer stores the DispatchMesh record {X, 1, 1} in a +// not-aliased placed title buffer (the CPU sentinel there is {1, 1, 1}); then render target (32x32 RGBA8, cleared +// to 0) or depth target, viewport/scissor, view heap with a hardware buffer descriptor (6 vertices in title memory) +// in table parameter 1, root constant 2.0 = colour, the mesh pipeline, ExecuteIndirect(mesh signature, 1, args, 0). +// Topology is never set (0): a draw would be refused there, a mesh call must not be. +// +// Expected: gpu / derived (slot-55 pipeline over the record): X = 2, both triangles in the colour, alpha 1 (rect +// entry value 0); zero: X = 0, nothing drawn; huge: X = 70000 zeroed by indirect's guard, nothing drawn; off +// (X2W_MESH unset): nothing drawn, no x2w-mesh line; missing: nothing drawn, "no translation" for the key; depth: +// the depth-only pipeline (no pixel stage) is created and issued (depth value printed; today's default state has +// depth off, so it is not checked). words16 / words32 / wordsraw (`heap 1` + `heapwords 1`, MeshHeap): no srv line; +// a title buffer view (16_16_FLOAT / 32_32_FLOAT / raw) in heap slot 2, the slot in root constant 0.0; the shader +// reads the view id from the heap, the FORMAT from vdesc word 3 and decodes the positions by it: words16 drawn with +// green 0x1d, words32 with green 0x40, wordsraw (FORMAT 32_FLOAT) nothing; with a view increment other than 32 +// (WARP) the call must be skipped ("descriptor increment is not 32", no vdesc buffer) and the mode reports a +// capability skip after checking that. Every mode: no debug-layer error or +// corruption message, device not removed. +// Exit 0 pass, 77 capability skip (no adapter, no existing-heap support, MeshShaderTier 0, depth on WARP), other +// values name the step. +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <iterator> +#include <string> +#include <vector> + +#include "startup_mesh_descword_ms.h" +#include "startup_mesh_heap_ms.h" +#include "startup_mesh_ms.h" +#include "startup_mesh_ps.h" +#include "startup_mesh_smp_ps.h" +#include "startup_mesh_uint_ps.h" +#include "startup_mesh_store_ps.h" +#include "startup_mesh_writer.h" + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) unsigned x2w_d3d12_traced_targets(unsigned* out, unsigned capacity); +extern "C" __declspec(dllimport) int x2w_d3d12_summarise_traced_targets(); +extern "C" __declspec(dllimport) void x2w_d3d12_mesh_stats_report(); +extern "C" __declspec(dllimport) void x2w_d3d12_record_trace_report(); // LOCAL (scene): X2W_MESH_RECORD_TRACE +extern "C" __declspec(dllimport) void x2w_d3d12_mesh_frame_stats_report(); // X2W_MESH_STATS_FRAMES: close the frame, report +extern "C" __declspec(dllimport) void x2w_d3d12_mesh_frame_stats_present(); // X2W_MESH_STATS_FRAMES: what a present does + +namespace { +using Word = std::uint64_t; +template <class T> Word arg(T* value) { return reinterpret_cast<Word>(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word); + return reinterpret_cast<Slot>((*static_cast<void***>(object))[index])(object, a, b, c, d, e, f); +} +bool ok(Word hr) { return SUCCEEDED(static_cast<HRESULT>(hr)); } +std::uint64_t fnv(const void* data, std::size_t bytes, std::uint64_t hash = 1469598103934665603ull) +{ + for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ static_cast<const unsigned char*>(data)[i]) * 1099511628211ull; + return hash; +} +bool write_file(const std::wstring& path, const void* data, std::size_t bytes) +{ + FILE* f = _wfopen(path.c_str(), L"wb"); + if (!f) return false; + const bool written = std::fwrite(data, 1, bytes, f) == bytes; + return std::fclose(f) == 0 && written; +} +std::wstring hex_key(std::uint64_t key) +{ + wchar_t name[24]; + swprintf(name, 24, L"%016llx", static_cast<unsigned long long>(key)); + return name; +} +// A slot-55 patch record (kind 2 = blend description), as the title passes them. +struct Patch { UINT tag; D3D12_BLEND_DESC blend; }; +static_assert(sizeof(Patch) == 0x14c); + +// Desktop-side work on the test's own queue: clear the depth target, or read a texture back. +struct Observer { + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + UINT64 value = 0; + bool open(ID3D12Device* device) + { + 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 (const HRESULT hr = list->Close(); FAILED(hr)) { + std::printf("observer list Close -> 0x%08lx\n", static_cast<unsigned long>(hr)); + return false; + } + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), ++value))) return false; + const auto deadline = GetTickCount64() + 10000; + while (fence->GetCompletedValue() < value) { + if (GetTickCount64() >= deadline) return false; + Sleep(1); + } + return SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.Get(), nullptr)); + } +}; +void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* r, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) +{ + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + list->ResourceBarrier(1, &b); +} +// Copies subresource 0 of `texture` (in COMMON) and returns the first 4 bytes of each requested pixel. +bool read_pixels(ID3D12Device* device, Observer& o, ID3D12Resource* texture, bool depth, const std::vector<std::pair<UINT, UINT>>& at, + std::vector<std::uint32_t>& out) +{ + const D3D12_RESOURCE_DESC desc = texture->GetDesc(); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 total = 0; + device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, total, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + ComPtr<ID3D12Resource> readback; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback)))) + return false; + if (depth) barrier(o.list.Get(), texture, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION dst{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION src{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + o.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + if (depth) barrier(o.list.Get(), texture, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + if (!o.run()) return false; + void* mapped = nullptr; + if (FAILED(readback->Map(0, nullptr, &mapped))) return false; + for (const auto& p : at) { + std::uint32_t v = 0; + std::memcpy(&v, static_cast<const unsigned char*>(mapped) + footprint.Footprint.RowPitch * p.second + 4 * p.first, 4); + out.push_back(v); + } + readback->Unmap(0, nullptr); + return true; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) return 2; + const std::string mode = argv[2]; + const bool wide = mode == "srvwide" || mode == "srvwidecopy" || mode == "srvwideshort"; + constexpr std::uint32_t wide_offset = 16u << 20; + if (wide) SetEnvironmentVariableW(L"X2W_DRAW_SRV_IN_PLACE", mode == "srvwidecopy" ? nullptr : L"65536"); + if (!wide && mode != "gpu" && mode != "derived" && mode != "zero" && mode != "huge" && mode != "off" && mode != "missing" && mode != "depth" && + mode != "words16" && mode != "words32" && mode != "wordsraw" && mode != "wordsoob" && mode != "fmaprecise" && mode != "fmabad" && mode != "notargets" && + mode != "rtvuint" && mode != "smpheap" && mode != "smpheapswap" && mode != "statez" && mode != "statezge" && mode != "statezoff" && + mode != "statecull" && mode != "stateculloff" && mode != "statedepth" && mode != "statecullflip" && mode != "statecullnone" && + mode != "statezrepeat" && mode != "statezuncleared" && mode != "statezlateclear" && mode != "async" && mode != "asyncone" && mode != "rtvvariant" && + mode != "uavtex" && mode != "uavtexnoflag" && mode != "rtvnops" && mode != "stateclip" && mode != "stateclipon" && mode != "stateclipkeep" && + mode != "rectrace" && mode != "rectraceapart" && mode != "descword" && mode != "descwordoff") + return 2; + // LOCAL (scene) rectrace / rectraceapart (X2W_MESH_RECORD_TRACE=1 in a traced frame, d3d12_record_trace.inl): the + // gpu call plus, before it, a stand-in of the title's cull pass: a slot-62 pipeline with a descriptor-table argument + // (skipped: "c62 table argument"), dispatched twice. The view heap has 8 slots: 0 the vertex V# (the mesh srv), 1 a + // Texture2D SRV, 2 a raw gfx10 T# over the same 2x1 texture (placed on title memory), 3 a Texture2D UAV of it, 4 a V# + // over other memory. Root constant [0][1] of the mesh call = bit 28 + index 0 (a heap read of the vertices). + // rectrace: the cull table starts at slot 0 and its root constant names heap index 0: both mesh reads (srv 0 and + // heap 0) must be "INSIDE a skipped dispatch's range". rectraceapart (control): table at slot 1, heap index 4: no + // mesh read inside a skipped range. Both: cx-img lines for the SRV, the raw T# (matched to the texture by address) + // and the UAV; on the second dispatch the texture's content names the first as its texture uav writer; a cx-heap + // line for the named index. + const bool rectrace = mode == "rectrace" || mode == "rectraceapart"; + if (rectrace) SetEnvironmentVariableW(L"X2W_MESH_RECORD_TRACE", L"1"); + // stateclip / stateclipon / stateclipkeep (X2W_DRAW_STATE_DEPTHCLIP, without X2W_MESH_STATE): the triangles at z 1.5, + // beyond the far plane. stateclip: PA_CL_CLIP_CNTL ZCLIP_NEAR + FAR_DISABLE and the switch: depth clip off, drawn. + // stateclipon (control): the same words, switch unset: default depth clip on, dropped. stateclipkeep (control): + // switch set, clip bits clear: the decoded depth clip is on, dropped. + const bool clipmode = mode.compare(0, 9, "stateclip") == 0; + if (mode == "stateclip" || mode == "stateclipkeep") SetEnvironmentVariableW(L"X2W_DRAW_STATE_DEPTHCLIP", L"1"); + // statecullflip: X2W_MESH_STATE_CULL_FLIP=1, the other triangle culled; statecullnone: X2W_MESH_STATE_NOCULL=1, both + // drawn. statezrepeat: 32 calls with render target + depth, then 32 with the render target only: exactly two PSO + // lines (dsv 40, dsv 0), i.e. the calls after the first of each pass take the PSO kept with the binding. + // state modes: the slot-57 record carries a state block A in the mesh layout (A+0x004 = 6, fields 0x54 later). + // statez / statezge / statezoff: render target + D32 depth cleared to 0.5; DB_DEPTH_CONTROL test + write, LESS + // (statez, statezoff) or GEQUAL (statezge); the triangles are at z 0.25. statecull / stateculloff: cull back, the + // right triangle wound the other way. statedepth: the depth-only pipeline, LESS + write over a depth of 1.0. + // X2W_MESH_STATE=1 except in the *off modes. The UNSHIFTED offsets hold contradicting values (ZFUNC NEVER, cull + // front), so a decode that misses the shift fails. + const bool state_mode = mode.compare(0, 5, "state") == 0; + const bool state_on = state_mode && mode != "statezoff" && mode != "stateculloff" && mode.compare(0, 9, "stateclip") != 0; + const bool zmode = mode.compare(0, 6, "statez") == 0; // render target and depth target + const bool cullmode = mode.compare(0, 9, "statecull") == 0; + if (state_on) SetEnvironmentVariableW(L"X2W_MESH_STATE", L"1"); + if (mode == "statecullflip") SetEnvironmentVariableW(L"X2W_MESH_STATE_CULL_FLIP", L"1"); + if (mode == "statecullnone") SetEnvironmentVariableW(L"X2W_MESH_STATE_NOCULL", L"1"); + const bool repeat = mode == "statezrepeat"; + // async / asyncone: X2W_MESH_ASYNC=1, the first call hands its PSO to a worker and is skipped. async waits for the + // worker's PSO line, then records a second call: drawn. asyncone (control): only the first call: nothing drawn. + const bool async = mode.compare(0, 5, "async") == 0; + if (async) SetEnvironmentVariableW(L"X2W_MESH_ASYNC", L"1"); + // The depth target of the z modes and statedepth is initialised by a FORWARDED guest clear (list slot 51, + // X2W_DRAW_STATE_DEPTH_CLEAR=1) over a different desktop pre-clear: renderstate 7c0d4cae applies no depth test to a + // target no forwarded clear has marked. statezuncleared (the control): no slot 51 clear, so the decoded LESS test + // and write stay off: drawn, depth unchanged at the pre-clear 0.5. + const bool guest_clear = (mode.compare(0, 6, "statez") == 0 && mode != "statezuncleared") || mode == "statedepth"; + if (guest_clear) SetEnvironmentVariableW(L"X2W_DRAW_STATE_DEPTH_CLEAR", L"1"); + // smpheap / smpheapswap: the pixel stage samples title sampler-heap entry 65 (`smpheap 2048 1 fallback 2047`); + // entry 65 is point and 64 linear (smpheap), or the other way round (smpheapswap, the control). + const bool smp = mode.compare(0, 7, "smpheap") == 0; + const bool depth = mode == "depth" || mode == "statedepth"; // depth-only pipeline, depth target only + const bool no_ps = depth || mode == "rtvnops"; // no pixel stage (rtvnops: with an R32_UINT render target) + const bool words = mode.compare(0, 5, "words") == 0; // heap descriptor + vdesc (`heap 1`, `heapwords 1`) + const bool uavtex = mode.compare(0, 6, "uavtex") == 0; // `uav 0 tex2d table 1 <2 increments>`, PixelStore + const bool descword = mode.compare(0, 8, "descword") == 0; // `udsrc 2 descword 1 8`, MeshDescword + if (mode == "descword") SetEnvironmentVariableW(L"X2W_MESH_DESCWORD", L"1"); + UINT view_increment = 0; + ComPtr<IDXGIFactory6> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr<IDXGIAdapter> adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr<IDXGIAdapter1> candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) 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 (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + LARGE_INTEGER driver{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls driver=%u.%u.%u.%u mode=%s\n", adapter_desc.Description, HIWORD(driver.HighPart), LOWORD(driver.HighPart), + HIWORD(driver.LowPart), LOWORD(driver.LowPart), mode.c_str()); + + // Capabilities: mesh shaders (tier 1, shader model 6.5) and existing heaps over process memory (the windows). + // (A probe device only: the stand-in enables the debug layer before it creates its device.) + { + ComPtr<ID3D12Device3> desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 4; + D3D12_FEATURE_DATA_D3D12_OPTIONS7 options7{}; + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_5}; + const HRESULT hr7 = desktop->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &options7, sizeof(options7)); + const HRESULT hrm = desktop->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model)); + std::printf("MeshShaderTier %d (0x%08lx), highest shader model 0x%x (0x%08lx)\n", SUCCEEDED(hr7) ? static_cast<int>(options7.MeshShaderTier) : -1, + static_cast<unsigned long>(hr7), SUCCEEDED(hrm) ? static_cast<unsigned>(model.HighestShaderModel) : 0u, + static_cast<unsigned long>(hrm)); + if (FAILED(hr7) || options7.MeshShaderTier < D3D12_MESH_SHADER_TIER_1 || FAILED(hrm) || model.HighestShaderModel < D3D_SHADER_MODEL_6_5) { + std::printf("no mesh shader support: capability skip\n"); + return 77; + } + void* block = VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + ComPtr<ID3D12Heap> heap; + const HRESULT hr = block ? desktop->OpenExistingHeapFromAddress(block, IID_PPV_ARGS(&heap)) : E_OUTOFMEMORY; + heap.Reset(); + if (block) VirtualFree(block, 0, MEM_RELEASE); + if (FAILED(hr)) { + std::printf("OpenExistingHeapFromAddress -> 0x%08lx: capability skip\n", static_cast<unsigned long>(hr)); + return 77; + } + view_increment = desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + std::printf("view increment %u\n", view_increment); + } + // `heap 1` draws need the console's 32-byte view slots (d3d12_draw.inl draw_translated); with another increment + // (WARP) the words modes check that the call is skipped as required and then report a capability skip. + const bool words_skip = words && view_increment != 32; + // Measured on WARP 10.0.26100.9818 (2026-11-24): a mesh PSO without a pixel stage removes the device on its first + // DispatchMesh (with depth off and with depth test/write on; with the debug layer on and off; no debug-layer + // message before the removal). The same stream with a pixel stage draws, and hardware draws it without one. + if (no_ps && std::strcmp(argv[1], "warp") == 0) { // depth, statedepth and rtvnops + std::printf("WARP removes the device for a mesh pipeline without a pixel stage: capability skip\n"); + return 77; + } + + // Shader cache and log of this process. + wchar_t temp[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, temp)) return 5; + // Process id + tick count: a reused process id must not find an earlier run's manifest (mode missing failed so). + const std::wstring cache = std::wstring(temp) + L"x2w_mesh_" + std::to_wstring(GetCurrentProcessId()) + L"_" + + std::to_wstring(GetTickCount64()); + CreateDirectoryW(cache.c_str(), nullptr); + SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()); + const std::wstring log_path = cache + L"\\trap.log"; + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + + // The writer: a container compute pipeline, keyed as the stand-in keys slot-62 pipelines. + D3D12_ROOT_PARAMETER writer_params[2]{}; + writer_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + writer_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + writer_params[1].Constants = {1, 0, 4}; + const D3D12_ROOT_SIGNATURE_DESC writer_root_desc{2, writer_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> writer_blob; + if (FAILED(D3D12SerializeRootSignature(&writer_root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &writer_blob, nullptr))) return 5; + if (!write_file(cache + L"\\" + hex_key(fnv(writer_blob->GetBufferPointer(), writer_blob->GetBufferSize(), fnv(startup_mesh_writer, sizeof(startup_mesh_writer)))) + + L".cs.dxbc", startup_mesh_writer, sizeof(startup_mesh_writer))) + return 5; + // rectrace: the cull stand-in's root signature (the writer's two parameters, then a table and two constants): a + // cache file too, so its desktop pipeline exists; the table argument keeps it from running. + D3D12_DESCRIPTOR_RANGE cull_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 8, 0, 0, 0}; + D3D12_ROOT_PARAMETER cull_params[4]{writer_params[0], writer_params[1]}; + cull_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + cull_params[2].DescriptorTable = {1, &cull_range}; + cull_params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + cull_params[3].Constants = {2, 0, 2}; + const D3D12_ROOT_SIGNATURE_DESC cull_root_desc{4, cull_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> cull_blob; + if (rectrace) { + if (FAILED(D3D12SerializeRootSignature(&cull_root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &cull_blob, nullptr))) return 5; + if (!write_file(cache + L"\\" + hex_key(fnv(cull_blob->GetBufferPointer(), cull_blob->GetBufferSize(), fnv(startup_mesh_writer, sizeof(startup_mesh_writer)))) + + L".cs.dxbc", startup_mesh_writer, sizeof(startup_mesh_writer))) + return 5; + } + + // The title's graphics root signature of the mesh record: [0] constants, [1] a table, [2] constants. Its bytes go + // into the key; the translated root signature is built from the manifest. + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 4, 0, 0, 0}; + D3D12_ROOT_PARAMETER title_params[3]{}; + title_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + title_params[0].Constants = {0, 0, 4}; + title_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + title_params[1].DescriptorTable = {1, &range}; + title_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + title_params[2].Constants = {1, 0, 4}; + const D3D12_ROOT_SIGNATURE_DESC title_root_desc{3, title_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> title_blob; + if (FAILED(D3D12SerializeRootSignature(&title_root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &title_blob, nullptr))) return 5; + + // Fake console code blobs (the stand-in only hashes them). + static unsigned char mesh_code[256], pixel_code[128]; + for (int i = 0; i < 256; ++i) mesh_code[i] = static_cast<unsigned char>(0xA0 ^ i); + for (int i = 0; i < 128; ++i) pixel_code[i] = static_cast<unsigned char>(0x5C ^ (i * 7)); + // The key rule (board/msgs/195600_meshrt_mesh-key-rule.md): pipeline_key(a or empty, b = mesh code, root). + constexpr char revision[] = "x2w-startup-shader-3"; // d3d12_draw.inl pipeline_key (local merge) + std::uint64_t key = fnv(revision, sizeof(revision) - 1); + if (!no_ps) key = fnv(pixel_code, sizeof(pixel_code), key); + key = fnv(mesh_code, sizeof(mesh_code), key); + key = fnv(title_blob->GetBufferPointer(), title_blob->GetBufferSize(), key); + // trace_statez / trace_zero, and dump_statez / dump_zero (X2W_TEST_MESH_DUMP=1, NOT traced: the dump does not need + // the traced frame): X2W_MESH_DUMP_INPUTS lists this key (read by the stand-in at the first mesh call with groups). + char dump_env[8]{}; + const bool dump_test = (mode == "statez" || mode == "zero") && + ((GetEnvironmentVariableA("X2W_D3D12_TRACE_ALL", dump_env, sizeof(dump_env)) && dump_env[0] == '1') || + (GetEnvironmentVariableA("X2W_TEST_MESH_DUMP", dump_env, sizeof(dump_env)) && dump_env[0] == '1')); + { + char key_hex[24]; + if (dump_test) { + std::snprintf(key_hex, sizeof(key_hex), "%016llx", static_cast<unsigned long long>(key)); + // A list: another key first, then this one (each listed key is dumped once). + SetEnvironmentVariableA("X2W_MESH_DUMP_INPUTS", (std::string("0000000000000001, ") + key_hex).c_str()); + } + } + std::printf("mesh key %016llx\n", static_cast<unsigned long long>(key)); + if (mode != "missing") { + // words modes: no srv line; the vertices are reached through the title heap slot in entry value 2. + // The fma line (RUNTIME_NEEDS 8): derived has none (unstated), fmaprecise / fmabad name their rule, the rest exact. + const std::string fma = mode == "derived" ? "" : mode == "fmaprecise" ? "fma precise\n" : mode == "fmabad" ? "fma fused\n" : "fma exact\n"; + const std::string manifest = + words ? "x2w-manifest 1\nudsrc 0 rect\nudsrc 1 rootconst 2 0\nudsrc 2 rootconst 0 0\nheap 1\nheapwords 1\n" + fma + "stage mesh\nms 3 3 1\n" + // smp: srv 1 is the table's second descriptor (the table offset is in bytes: one view increment). + : smp ? "x2w-manifest 1\nudsrc 0 rect\nudsrc 1 rootconst 2 0\nsrv 0 buf table 1 0\nsrv 1 tex2d table 1 " + std::to_string(view_increment) + + "\nsmpheap 2048 1 fallback 2047\n" + fma + "stage mesh\nms 3 3 1\n" + : uavtex ? "x2w-manifest 1\nudsrc 0 rect\nudsrc 1 rootconst 2 0\nsrv 0 buf table 1 0\nuav 0 tex2d table 1 " + + std::to_string(2 * view_increment) + "\n" + fma + "stage mesh\nms 3 3 1\n" + : descword ? "x2w-manifest 1\nudsrc 0 rect\nudsrc 1 rootconst 2 0\nudsrc 2 descword 1 8\nsrv 0 buf table 1 0\n" + fma + "stage mesh\nms 3 3 1\n" + // statez: entry value 2 = root constant 0.1 (the dump's bit-28 heap reference; MeshMain ignores it). + : "x2w-manifest 1\nudsrc 0 rect\nudsrc 1 rootconst 2 0\n" + std::string(mode == "statez" || rectrace ? "udsrc 2 rootconst 0 1\n" : "") + + "srv 0 buf table 1 0\n" + fma + "stage mesh\nms 3 3 1\n"; + const std::wstring base = cache + L"\\" + hex_key(key); + if (!(words ? write_file(base + L".ms.cso", startup_mesh_heap_ms, sizeof(startup_mesh_heap_ms)) + : descword ? write_file(base + L".ms.cso", startup_mesh_descword_ms, sizeof(startup_mesh_descword_ms)) + : write_file(base + L".ms.cso", startup_mesh_ms, sizeof(startup_mesh_ms))) || + (!no_ps && !(smp ? write_file(base + L".ps.cso", startup_mesh_smp_ps, sizeof(startup_mesh_smp_ps)) + : uavtex ? write_file(base + L".ps.cso", startup_mesh_store_ps, sizeof(startup_mesh_store_ps)) + : write_file(base + L".ps.cso", startup_mesh_ps, sizeof(startup_mesh_ps)))) || + !write_file(base + L".txt", manifest.data(), manifest.size())) + return 5; + } + // RTV variant of the key for an R32_UINT target (the draw path's contract, d3d12_draw.inl translation_for_targets): + // request "rtv1 <key decimal> 42", variant key = fnv of the request text. rtvvariant publishes the variant (the same + // mesh stage, PixelUint, the manifest + the rtv1 line); rtvuint (control) publishes none and must find the + // stand-in's request req_<variant>.rtv with that text. + const std::string rtv_request = "rtv1 " + std::to_string(key) + " 42"; + const std::uint64_t variant_key = fnv(rtv_request.data(), rtv_request.size()); + if (mode == "rtvvariant") { + const std::string manifest = + "x2w-manifest 1\nudsrc 0 rect\nudsrc 1 rootconst 2 0\nsrv 0 buf table 1 0\nfma exact\nstage mesh\nms 3 3 1\n" + rtv_request + "\n"; + const std::wstring base = cache + L"\\" + hex_key(variant_key); + if (!write_file(base + L".ms.cso", startup_mesh_ms, sizeof(startup_mesh_ms)) || + !write_file(base + L".ps.cso", startup_mesh_uint_ps, sizeof(startup_mesh_uint_ps)) || + !write_file(base + L".txt", manifest.data(), manifest.size())) + return 5; + } + + std::array<unsigned char, 64> device_parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), device_parameters.data(), __uuidof(ID3D12Device), &device))) return 6; + ComPtr<ID3D12Device> desktop; // the same device object as the stand-in's (one device per adapter) + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 6; + + void *writer_root = nullptr, *title_root = nullptr, *writer = nullptr, *pipeline = nullptr; + if (!ok(invoke(device, 16, 0, arg(writer_blob->GetBufferPointer()), writer_blob->GetBufferSize(), arg(&__uuidof(ID3D12RootSignature)), arg(&writer_root))) || + !ok(invoke(device, 16, 0, arg(title_blob->GetBufferPointer()), title_blob->GetBufferSize(), arg(&__uuidof(ID3D12RootSignature)), arg(&title_root)))) + return 7; + D3D12_COMPUTE_PIPELINE_STATE_DESC compute{}; + compute.pRootSignature = static_cast<ID3D12RootSignature*>(writer_root); + compute.CS = {startup_mesh_writer, sizeof(startup_mesh_writer)}; + if (!ok(invoke(device, 62, arg(&compute), 0, 0, arg(&__uuidof(ID3D12PipelineState)), arg(&writer)))) return 8; + void *cull_root = nullptr, *cull = nullptr; // rectrace: the cull stand-in + if (rectrace) { + if (!ok(invoke(device, 16, 0, arg(cull_blob->GetBufferPointer()), cull_blob->GetBufferSize(), arg(&__uuidof(ID3D12RootSignature)), arg(&cull_root)))) + return 7; + compute.pRootSignature = static_cast<ID3D12RootSignature*>(cull_root); + if (!ok(invoke(device, 62, arg(&compute), 0, 0, arg(&__uuidof(ID3D12PipelineState)), arg(&cull)))) return 8; + } + // The slot-57 mesh record. + alignas(8) static unsigned char record[0x300]; + Word record_words[16] = {}; + record_words[0] = arg(title_root); + if (!no_ps) record_words[5] = arg(pixel_code), record_words[6] = sizeof(pixel_code); + record_words[13] = arg(mesh_code), record_words[14] = sizeof(mesh_code); + // state modes: state block A at [1]/[2] (pipeline_state_decode.h read_words; REG_LAYOUT 2a). + alignas(4) static unsigned char state_a[0x180]; + if (state_mode) { + const auto put = [](std::size_t at, std::uint32_t v) { std::memcpy(state_a + at, &v, 4); }; + constexpr std::size_t shift = 0x54; + put(0x004, 6); // mesh layout + put(0x078 + shift, 0xf); // CB_SHADER_MASK: target 0 all channels + put(0x0cc + shift, 0xf); // CB_TARGET_MASK + put(0x0d0 + shift, 0); // CB_BLEND0: blend off + // PA_CL_CLIP_CNTL: depth clip on; stateclip / stateclipon: ZCLIP_NEAR_DISABLE (26) + ZCLIP_FAR_DISABLE (27). + put(0x09c + shift, mode == "stateclip" || mode == "stateclipon" ? 0x0c000000u : 0u); + put(0x09c, mode == "stateclipkeep" ? 0x0c000000u : 0u); // unshifted: the opposite (a missed shift fails) + // DB_DEPTH_CONTROL: Z_ENABLE (1) | Z_WRITE_ENABLE (2) | ZFUNC (4-6): 1 LESS, 6 GEQUAL; none in the cull / clip modes. + put(0x0b8 + shift, cullmode || clipmode ? 0u : 0x2u | 0x4u | ((mode == "statezge" ? 6u : 1u) << 4)); + put(0x0a0 + shift, cullmode ? 0x2u : 0u); // PA_SU_SC_MODE_CNTL: CULL_BACK (bit 1), FACE 0 + put(0x0b8, 0x2u); // unshifted: Z on, ZFUNC NEVER (a missed shift draws nothing) + put(0x0a0, 0x1u); // unshifted: cull front + record_words[1] = arg(state_a), record_words[2] = sizeof(state_a); + } + std::memcpy(record, record_words, sizeof(record_words)); + if (!ok(invoke(device, 57, arg(record), arg(&__uuidof(ID3D12PipelineState)), arg(&pipeline)))) return 8; + if (mode == "derived") { + Patch patch{2}; + for (auto& t : patch.blend.RenderTarget) + t = {FALSE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, + D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; + void* derived = nullptr; + if (!ok(invoke(device, 55, arg(pipeline), 1, arg(&patch), arg(&__uuidof(ID3D12PipelineState)), arg(&derived))) || !derived) return 8; + pipeline = derived; + } + D3D12_INDIRECT_ARGUMENT_DESC argument{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; + const D3D12_COMMAND_SIGNATURE_DESC signature_desc{12, 1, &argument, 0}; + void* signature = nullptr; + if (!ok(invoke(device, 41, arg(&signature_desc), 0, arg(&__uuidof(ID3D12CommandSignature)), arg(&signature)))) return 9; + + // Title memory: arguments at +0x1c20 (not 64 KiB-aligned: a private copy backs the wrapper), vertices at +0x30000. + auto* memory = static_cast<unsigned char*>(VirtualAlloc(nullptr, wide ? 18u << 20 : 2u << 20, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!memory) return 10; + unsigned char* const args_memory = memory + 0x1c20; + // zero: X = 0 already at record time (the X2W_MESH_DUMP_INPUTS control: a call without groups is not dumped). + const std::uint32_t sentinel[3] = {mode == "zero" ? 0u : 1u, 1, 1}; + std::memcpy(args_memory, sentinel, 12); + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 64, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + void* args = nullptr; + if (!ok(invoke(device, 133, arg(args_memory), arg(&buffer), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&args)))) return 11; + // Group 0: a triangle over the left half; group 1: over the right half (clip space). + const float vertices[12] = {-0.9f, -0.9f, -0.9f, 0.9f, -0.1f, 0.0f, 0.1f, 0.0f, 0.9f, 0.9f, 0.9f, -0.9f}; + unsigned char* const vertex_memory = memory + 0x30000; + std::memcpy(vertex_memory + (wide ? wide_offset : 0), vertices, sizeof(vertices)); + if (cullmode) { // the right triangle's last two vertices swapped: the other winding + const float swapped[4] = {0.9f, -0.9f, 0.9f, 0.9f}; + std::memcpy(vertex_memory + 32, swapped, sizeof(swapped)); + } + if (mode == "words16") { // the same positions as half2 (all exactly representable: +-0.875, +-0.125, 0) + const float halves[12] = {-0.875f, -0.875f, -0.875f, 0.875f, -0.125f, 0.0f, 0.125f, 0.0f, 0.875f, 0.875f, 0.875f, -0.875f}; + std::uint16_t packed[12]; + for (int i = 0; i < 12; ++i) { + std::uint32_t b = 0; + std::memcpy(&b, &halves[i], 4); + packed[i] = halves[i] == 0.0f ? 0 : static_cast<std::uint16_t>(((b >> 16) & 0x8000) | ((((b >> 23) & 0xff) - 112) << 10) | ((b >> 13) & 0x3ff)); + } + std::memcpy(vertex_memory, packed, sizeof(packed)); + } + + // Targets: a desktop texture with a view made through the stand-in (as the title's views are wrapped). + constexpr UINT size = 32; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr<ID3D12Resource> target; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } target_heap_desc{{depth ? D3D12_DESCRIPTOR_HEAP_TYPE_DSV : D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}; + void* target_heap = nullptr; + if (!ok(invoke(device, 14, arg(&target_heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&target_heap)))) return 12; + const Word target_handle = invoke(target_heap, 9); + Observer observer; + if (!observer.open(desktop.Get())) return 12; + // A D32 depth texture with a view made through the stand-in at `handle`, cleared to `value` on the test's own + // queue (the stand-in drops depth clears by default). + const auto make_depth = [&](ComPtr<ID3D12Resource>& texture, Word handle, float value) { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, size, size, 1, 1, DXGI_FORMAT_D32_FLOAT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}; + const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_D32_FLOAT, {value, 0}}; + if (FAILED(desktop->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, &clear, + IID_PPV_ARGS(&texture)))) return false; + D3D12_DEPTH_STENCIL_VIEW_DESC view{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D}; + invoke(device, 21, arg(texture.Get()), arg(&view), handle); + ComPtr<ID3D12DescriptorHeap> own_dsv; + const D3D12_DESCRIPTOR_HEAP_DESC own_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; + if (FAILED(desktop->CreateDescriptorHeap(&own_desc, IID_PPV_ARGS(&own_dsv)))) return false; + desktop->CreateDepthStencilView(texture.Get(), &view, own_dsv->GetCPUDescriptorHandleForHeapStart()); + barrier(observer.list.Get(), texture.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE); + observer.list->ClearDepthStencilView(own_dsv->GetCPUDescriptorHandleForHeapStart(), D3D12_CLEAR_FLAG_DEPTH, value, 0, 0, nullptr); + barrier(observer.list.Get(), texture.Get(), D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COMMON); + return observer.run(); + }; + // z modes: a depth target next to the render target, cleared to 0.5. + ComPtr<ID3D12Resource> depth_target; + Word depth_handle = 0; + if (zmode) { + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } dsv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}, 0, 0}; + void* dsv_heap = nullptr; + if (!ok(invoke(device, 14, arg(&dsv_heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&dsv_heap)))) return 12; + depth_handle = invoke(dsv_heap, 9); + if (!make_depth(depth_target, depth_handle, guest_clear ? 0.0f : 0.5f)) return 12; // guest clear: slot 51 sets 0.5 + } + if (depth) { + if (!make_depth(target, target_handle, guest_clear ? 0.0f : 1.0f)) return 12; // statedepth: slot 51 sets 1.0 + } else { + // rtvuint: an integer target (R32_UINT, 4 bytes per pixel like RGBA8): the call must be refused ("rtv variant"). + const DXGI_FORMAT format = mode == "rtvuint" || mode == "rtvvariant" || mode == "rtvnops" ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R8G8B8A8_UNORM; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, size, size, 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}}; + if (FAILED(desktop->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, &clear, + IID_PPV_ARGS(&target)))) return 12; + D3D12_RENDER_TARGET_VIEW_DESC view{format, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + invoke(device, 20, arg(target.Get()), arg(&view), target_handle); + } + // The view heap with one hardware buffer descriptor: base, stride 0, 48 records (bytes), over the vertices. + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } view_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, rectrace ? 8u : 4u, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + mode == "wordsoob" ? arg(memory + 0x60000) : Word{0}, mode == "wordsoob" ? Word{4 * 32} : Word{0}}; + void* view_heap = nullptr; + if (!ok(invoke(device, 14, arg(&view_heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&view_heap)))) return 12; + const Word view_cpu = invoke(view_heap, 9), view_gpu = invoke(view_heap, 10); + if (!view_cpu || !view_gpu) return 12; + const Word vertex_address = arg(vertex_memory); + const std::uint32_t descriptor[8] = {static_cast<std::uint32_t>(vertex_address), static_cast<std::uint32_t>(vertex_address >> 32) & 0xffff, + static_cast<std::uint32_t>((wide ? wide_offset : 0) + (mode == "srvwideshort" ? 0 : sizeof(vertices))), 0}; + std::memcpy(reinterpret_cast<void*>(view_cpu), descriptor, sizeof(descriptor)); + // words modes: a title buffer view in heap slot 2 (the stand-in writes its view token there), over a placed + // buffer on the vertices: 16_16_FLOAT (words16), 32_32_FLOAT (words32) or raw (wordsraw: no typed format). + constexpr std::uint32_t heap_slot = 2; + // wordsoob: the shader indexes slot 4, one past the 4-slot heap, where the test copied slot 2's token and id. + const std::uint32_t shader_slot = mode == "wordsoob" ? 4u : heap_slot; + void* vertex_buffer = nullptr; + if (words) { + D3D12_RESOURCE_DESC vb{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + D3D12_RESOURCE_FLAG_NONE}; + if (!ok(invoke(device, 133, arg(vertex_memory), arg(&vb), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&vertex_buffer)))) + return 12; + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Format = mode == "words16" ? DXGI_FORMAT_R16G16_FLOAT : mode == "words32" || mode == "wordsoob" ? DXGI_FORMAT_R32G32_FLOAT : DXGI_FORMAT_R32_TYPELESS; + view.Buffer.NumElements = mode == "wordsraw" ? 12 : 6; + view.Buffer.Flags = mode == "wordsraw" ? D3D12_BUFFER_SRV_FLAG_RAW : D3D12_BUFFER_SRV_FLAG_NONE; + invoke(device, 18, arg(vertex_buffer), arg(&view), view_cpu + 32 * heap_slot); + std::uint32_t token[2] = {}; + std::memcpy(token, reinterpret_cast<const void*>(view_cpu + 32 * heap_slot), 8); + if (mode == "wordsoob") std::memcpy(reinterpret_cast<void*>(view_cpu + 32 * 4), reinterpret_cast<const void*>(view_cpu + 32 * heap_slot), 32); + std::printf("heap slot %u: %08x %08x (view token X2WV = 56573258 + view id)\n", heap_slot, token[0], token[1]); + } + // smp modes: a 2x1 RGBA8 texture placed on title memory (the stand-in backs it with a desktop texture and uploads + // it from that memory at the draw; texel 0 red, texel 1 blue), its SRV at the table's second descriptor, and a + // shader-visible title sampler heap of 128 raw 16-byte S# entries: 64 and 65 clamp, one point, one linear. + void *smp_texture = nullptr, *sampler_heap = nullptr; + if (smp) { + const std::uint32_t texels[2] = {0xff0000ffu, 0xffff0000u}; + std::memcpy(memory + 0x40000, texels, sizeof(texels)); + D3D12_RESOURCE_DESC tex{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 2, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + D3D12_RESOURCE_FLAG_NONE}; + if (!ok(invoke(device, 133, arg(memory + 0x40000), arg(&tex), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), + arg(&smp_texture)))) + return 12; + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Texture2D.MipLevels = 1; + invoke(device, 18, arg(smp_texture), arg(&view), view_cpu + view_increment); + constexpr UINT sampler_count = 128; + static std::uint32_t sampler_words[sampler_count][4]; + const std::uint32_t clamp = 2u | (2u << 3) | (2u << 6); + const auto filter = [](std::uint32_t f) { return (f << 20) | (f << 22); }; // mag, min; 0 point, 1 linear + sampler_words[64][0] = sampler_words[65][0] = clamp; + sampler_words[65][2] = filter(mode == "smpheap" ? 0 : 1); + sampler_words[64][2] = filter(mode == "smpheap" ? 1 : 0); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } sampler_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, sampler_count, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + arg(sampler_words), sizeof(sampler_words)}; + if (!ok(invoke(device, 14, arg(&sampler_heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&sampler_heap)))) return 12; + } + // uavtex modes: a 32x32 RGBA8 texture placed on title memory at the table's third descriptor. uavtex: the texture + // allows unordered access and has an RGBA8 UAV (slot 19); uavtexnoflag (control): no unordered access, an SRV there. + void* uav_texture = nullptr; + if (uavtex) { + const bool flag = mode == "uavtex"; + D3D12_RESOURCE_DESC tex{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 32, 32, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + flag ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE}; + if (!ok(invoke(device, 133, arg(memory + 0x50000), arg(&tex), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), + arg(&uav_texture)))) + return 12; + if (flag) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(device, 19, arg(uav_texture), 0, arg(&view), view_cpu + 2 * view_increment); + } else { + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Texture2D.MipLevels = 1; + invoke(device, 18, arg(uav_texture), arg(&view), view_cpu + 2 * view_increment); + } + } + // rectrace: heap slots 1-4 (see the mode comment at the top of main). + void* trace_texture = nullptr; + unsigned char* const trace_texels = memory + 0x40000; // 256-byte aligned: a T# base + unsigned char* const other_memory = memory + 0x70000; + if (rectrace) { + const std::uint32_t texels[2] = {0xff0000ffu, 0xffff0000u}; + std::memcpy(trace_texels, texels, sizeof(texels)); + D3D12_RESOURCE_DESC tex{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 2, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + if (!ok(invoke(device, 133, arg(trace_texels), arg(&tex), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&trace_texture)))) + return 12; + 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; + invoke(device, 18, arg(trace_texture), arg(&srv), view_cpu + view_increment); + // A raw T# (gfx10 SQ_IMG_RSRC words): base >> 8, FORMAT 56, WIDTH 2, HEIGHT 1, TYPE 9 (2D), levels 0-0. + const Word base = arg(trace_texels) >> 8; + const std::uint32_t tsharp[8] = {static_cast<std::uint32_t>(base), (static_cast<std::uint32_t>(base >> 32) & 0xff) | (56u << 20) | (1u << 30), 0, 9u << 28}; + std::memcpy(reinterpret_cast<void*>(view_cpu + 2 * view_increment), tsharp, sizeof(tsharp)); + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(device, 19, arg(trace_texture), 0, arg(&uav), view_cpu + 3 * view_increment); + const Word other = arg(other_memory); + const std::uint32_t vsharp[8] = {static_cast<std::uint32_t>(other), static_cast<std::uint32_t>(other >> 32) & 0xffff, 64, 0}; + std::memcpy(reinterpret_cast<void*>(view_cpu + 4 * view_increment), vsharp, sizeof(vsharp)); + const std::uint32_t integer[8] = {5}; // slot 5: "integer + 7 zero words" (neither buffer nor image: an `other` line) + std::memcpy(reinterpret_cast<void*>(view_cpu + 5 * view_increment), integer, sizeof(integer)); + } + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *queue = nullptr, *fence = nullptr, *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 13; + + const std::uint32_t x = mode == "zero" ? 0u : mode == "huge" ? 70000u : 2u; + const std::uint32_t record_values[4] = {x, 1, 1, 0}; + const std::uint32_t colour = wide ? 0x02ff40c0u : clipmode ? 0x01ff40c0u : 0x00ff40c0u; // R c0, G 40, B ff; bit 24: z 1.5 (MeshMain) + const float clear_colour[4] = {0, 0, 0, 0}; + invoke(list, 139, arg(allocator)); // Reset + invoke(list, 33, arg(writer_root)); // SetComputeRootSignature + invoke(list, 25, arg(writer)); // SetPipelineState (writer) + invoke(list, 45, 0, arg(args_memory)); // SetComputeRootUnorderedAccessView(0, title address) + invoke(list, 39, 1, 4, arg(record_values), 0); // SetComputeRoot32BitConstants(1, 4, record, 0) + invoke(list, 14, 1, 1, 1); // Dispatch: the writer stores {x, 1, 1} + if (rectrace) { // the cull stand-in, twice (skipped: c62 table argument) + const std::uint32_t far_values[4] = {0x100, 0x100, 0x100, 0x100}; // over the heap's 8 slots: no heap index + const std::uint32_t heap_index[2] = {mode == "rectrace" ? 0u : 4u, 0x100}; + void* const cull_heaps[1] = {view_heap}; + invoke(list, 33, arg(cull_root)); + invoke(list, 25, arg(cull)); + invoke(list, 32, 1, arg(cull_heaps)); // SetDescriptorHeaps + invoke(list, 45, 0, arg(memory + 0x80000)); // root UAV past the vertices and slot 4's memory + invoke(list, 39, 1, 4, arg(far_values), 0); + invoke(list, 35, 2, view_gpu + (mode == "rectrace" ? 0 : view_increment)); // SetComputeRootDescriptorTable(2, slot 0 / 1) + invoke(list, 39, 3, 2, arg(heap_index), 0); + invoke(list, 14, 1, 1, 1); + invoke(list, 14, 1, 1, 1); + } + if (depth) { + invoke(list, 50, 0, 0, 0, arg(&target_handle)); // OMSetRenderTargets(0, null, FALSE, &dsv) + } else { + invoke(list, 52, target_handle, arg(clear_colour)); // ClearRenderTargetView + if (zmode) invoke(list, 50, 1, arg(&target_handle), 0, arg(&depth_handle)); // OMSetRenderTargets(1, &rtv, FALSE, &dsv) + else if (mode != "notargets") invoke(list, 50, 1, arg(&target_handle)); // OMSetRenderTargets(1, &rtv); notargets: none + } + const bool late_clear = mode == "statezlateclear"; + const auto slot51_clear = [&] { + // List slot 51 ClearDepthStencilView, typed (the depth value is a float argument in xmm3, which invoke cannot pass). + using ClearDepth = void(WINAPI*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, FLOAT, UINT8, UINT, const D3D12_RECT*); + const D3D12_CPU_DESCRIPTOR_HANDLE dsv{static_cast<SIZE_T>(depth ? target_handle : depth_handle)}; + reinterpret_cast<ClearDepth>((*static_cast<void***>(list))[51])(list, dsv, D3D12_CLEAR_FLAG_DEPTH, depth ? 1.0f : 0.5f, 0, 0, nullptr); + }; + if (guest_clear && !late_clear) slot51_clear(); + const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(size), static_cast<float>(size), 0, 1}; + const D3D12_RECT scissor{0, 0, static_cast<LONG>(size), static_cast<LONG>(size)}; + invoke(list, 21, 1, arg(&viewport)); + invoke(list, 22, 1, arg(&scissor)); + invoke(list, 34, arg(title_root)); // SetGraphicsRootSignature + void* const heaps[2] = {view_heap, sampler_heap}; + invoke(list, 32, smp ? 2 : 1, arg(heaps)); // SetDescriptorHeaps (smp: and the sampler heap) + invoke(list, 36, 1, view_gpu); // SetGraphicsRootDescriptorTable(1, heap start) + invoke(list, 40, 2, 1, arg(&colour), 0); // SetGraphicsRoot32BitConstants(2, 1, &colour, 0) + if (words) invoke(list, 40, 0, 1, arg(&shader_slot), 0); // SetGraphicsRoot32BitConstants(0, 1, &slot, 0): entry value 2 + // statez: root constant [0][1] (read by the translation) = bit 28 + heap index 0 (srv 0's view, the vertices): the + // dump's heap buffer case. [0][2] = bit 28 + index 3 is NOT read by the translation (the control): no heap3 files. + const std::uint32_t heap_reference[2] = {0x10000000u, 0x10000003u}; + if (mode == "statez" || rectrace) invoke(list, 40, 0, 2, arg(heap_reference), 1); // SetGraphicsRoot32BitConstants(0, 2, refs, 1) + invoke(list, 25, arg(pipeline)); // SetPipelineState (the mesh pipeline) + invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); // ExecuteIndirect(mesh signature, 1, args, 0) + if (mode == "async") { // the worker's PSO line, then a second call + bool compiled = false; + for (const auto until = GetTickCount64() + 20000; !compiled && GetTickCount64() < until; Sleep(10)) { + std::ifstream f(log_path, std::ios::binary); + const std::string text{std::istreambuf_iterator<char>(f), {}}; + compiled = text.find("compiled in ") != std::string::npos && text.find("(X2W_MESH_ASYNC worker)") != std::string::npos; + } + std::printf("async: worker PSO line seen before the second call: %d\n", compiled); + invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); + } + if (late_clear) { // the first call ran against the uncleared target (depth off); now the clear, then a second call + slot51_clear(); + invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); + } + if (repeat) { + for (int i = 1; i < 32; ++i) invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); + invoke(list, 50, 1, arg(&target_handle)); // OMSetRenderTargets(1, &rtv): no depth view + for (int i = 0; i < 32; ++i) invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); + } + invoke(list, 9); // Close + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), 1))) return 14; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < 1) { + if (GetTickCount64() >= deadline) return 14; + Sleep(1); + } + + std::uint32_t stored[3]; + std::memcpy(stored, args_memory, 12); + std::printf("record in title memory: {%u %u %u} (writer stored {%u 1 1})\n", stored[0], stored[1], stored[2], x); + std::vector<std::uint32_t> pixels; + const std::vector<std::pair<UINT, UINT>> at = {{8, 16}, {24, 16}, {16, 2}}; // left triangle, right triangle, outside both + if (!read_pixels(desktop.Get(), observer, target.Get(), depth, at, pixels)) { + ComPtr<ID3D12InfoQueue> messages; + if (SUCCEEDED(desktop.As(&messages))) + for (UINT64 i = 0; i < messages->GetNumStoredMessages(); ++i) { + SIZE_T bytes = 0; + messages->GetMessage(i, nullptr, &bytes); + std::vector<char> storage(bytes); + auto* message = reinterpret_cast<D3D12_MESSAGE*>(storage.data()); + if (bytes && SUCCEEDED(messages->GetMessage(i, message, &bytes))) std::printf("debug: %s\n", message->pDescription); + } + return 15; + } + int failures = 0; + if (stored[0] != x || stored[1] != 1 || stored[2] != 1) { + std::printf("the record in title memory is not what the writer stored\n"); + ++failures; + } + const bool drawn_expected = mode == "srvwide" || mode == "gpu" || mode == "derived" || mode == "fmaprecise" || smp || mode == "statez" || mode == "statezoff" || + mode == "stateculloff" || mode == "statecullnone" || mode == "stateclip" || repeat || mode == "statezuncleared" || mode == "statezlateclear" || mode == "async" || mode == "rtvvariant" || mode == "uavtex" || rectrace || (!words_skip && (mode == "words16" || mode == "words32")) || mode == "descword"; + // RGBA8 little-endian: R c0, G 40, B ff, A ff. words modes: G = the FORMAT code in vdesc word 3 (29 = 0x1d, 64 = 0x40). + // smpheap: entry 65 point -> texel 0 (red ff0000ff); smpheapswap: entry 65 linear at u = 0.375 -> 0.75 red + 0.25 + // blue (R bf, B 40, A ff; filtering precision allows +-3 per channel). + // descword: G = the descriptor's NUM_RECORDS low byte (48 = 0x30). + const std::uint32_t drawn = mode == "rtvvariant" ? 0x00ff40c0u : mode == "words16" ? 0xffff1dc0u : mode == "descword" ? 0xffff30c0u : mode == "smpheap" ? 0xff0000ffu : mode == "smpheapswap" ? 0xff4000bfu : 0xffff40c0u; + const auto matches = [&](std::uint32_t got, std::uint32_t want) { + if (mode != "smpheapswap" || !want) return got == want; + for (int s = 0; s < 32; s += 8) { + const int d = static_cast<int>((got >> s) & 255) - static_cast<int>((want >> s) & 255); + if (d < -3 || d > 3) return false; + } + return true; + }; + // Depth values: left, right, outside, against what the mode wants (statez / statedepth: the triangles wrote 0.25). + const auto check_depth = [&](const float (&values)[3], float cleared, bool written) { + const float want = written ? 0.25f : cleared; + const bool good = std::fabs(values[0] - want) < 1e-4f && std::fabs(values[1] - want) < 1e-4f && values[2] == cleared; + std::printf("depth: left %g right %g outside %g (cleared %g; want %g under the triangles)\n", values[0], values[1], values[2], cleared, want); + if (!good) { + std::printf("FAIL: depth values do not match mode %s\n", mode.c_str()); + ++failures; + } + }; + if (depth) { + float values[3]; + std::memcpy(values, pixels.data(), sizeof(values)); + if (mode == "statedepth") check_depth(values, 1.0f, true); + else std::printf("depth: left %g right %g outside %g (cleared 1; the default state has depth off, so not checked)\n", values[0], + values[1], values[2]); + } else { + std::printf("pixels: left %08x right %08x outside %08x (drawn = %08x, cleared = 00000000)\n", pixels[0], pixels[1], pixels[2], drawn); + const std::uint32_t want = drawn_expected ? drawn : 0u; + // statecull: MODE CULL_BACK + FACE 0 decodes to D3D12_CULL_MODE_BACK + FrontCounterClockwise TRUE. As seen on + // the target (+y up), the left triangle (-0.9,-0.9) (-0.9,0.9) (-0.1,0) is clockwise = back face: culled; the + // right one (last two vertices swapped) is counter-clockwise = front: drawn. stateculloff draws both. + // statecullflip: front face inverted, so the left triangle is drawn and the right one culled. + const std::uint32_t want_right = mode == "statecull" ? drawn : mode == "statecullflip" ? 0u : want; + const std::uint32_t want_left = mode == "statecull" ? 0u : mode == "statecullflip" ? drawn : want; + if (!matches(pixels[0], want_left) || !matches(pixels[1], want_right) || pixels[2] != 0) { + std::printf("FAIL: expected left %08x right %08x, outside 00000000\n", want_left, want_right); + ++failures; + } + } + if (zmode) { + std::vector<std::uint32_t> depth_words; + if (!read_pixels(desktop.Get(), observer, depth_target.Get(), true, at, depth_words)) return 15; + float values[3]; + std::memcpy(values, depth_words.data(), sizeof(values)); + check_depth(values, 0.5f, mode == "statez" || repeat || late_clear); + } + + // The log: the per-key lines and the debug layer. + std::ifstream log_file(log_path, std::ios::binary); + const std::string log{std::istreambuf_iterator<char>(log_file), {}}; + char key_text[24]; + std::snprintf(key_text, sizeof(key_text), "%016llx", static_cast<unsigned long long>(key)); + const auto has = [&](const std::string& text) { return log.find(text) != std::string::npos; }; + if (wide && has("(16777264 bytes) bound in place") != (mode == "srvwide")) { + std::printf("FAIL: full-range in-place binding in mode %s\n", mode.c_str()); + ++failures; + } + const bool issued = has(std::string("x2w-mesh pipeline ") + key_text + ": first call issued"); + const bool missing = has(std::string("x2w-mesh pipeline ") + key_text + ": no translation"); + const bool any_mesh = has("x2w-mesh "); + // The coverage line (board/msgs/210900_mesh): "x2w-mesh key K first bound frame F (cache: ok|fail|missing)". + std::string bound_line; + if (const std::size_t p = log.find(std::string("x2w-mesh key ") + key_text + " first bound frame "); p != std::string::npos) + bound_line = log.substr(p, log.find('\n', p) - p); + const bool bound_ok = bound_line.find(mode == "missing" ? "(cache: missing)" : mode == "fmabad" ? "(cache: fail)" : "(cache: ok)") != std::string::npos; + // Refusal modes: the once-per-key reason line (d3d12_mesh.inl mesh_refusal_line / load_mesh_stages). + const std::string pipeline_line = std::string("x2w-mesh pipeline ") + key_text + ": "; + const bool refusal_mode = mode == "fmabad" || mode == "notargets" || mode == "rtvuint" || mode == "uavtexnoflag"; + const std::string reason = mode == "fmabad" ? "translation failed (unknown fma rule \"fused\")" + : mode == "notargets" ? "call refused (no targets: " + : mode == "rtvuint" ? "call refused (rtv variant: target formats 42;" + : mode == "uavtexnoflag" ? "call refused (bind refused by draw_translated" + : ""; + const bool reason_ok = refusal_mode && has(pipeline_line + reason); + if (refusal_mode) std::printf("log: refusal line \"%s%s\" %d\n", pipeline_line.c_str(), reason.c_str(), reason_ok); + // The fma rule each loaded translation reports, and the capability line for exact / unstated. + const char* fma_rule = mode == "derived" ? "fma unstated" : mode == "fmaprecise" ? "fma precise" : "fma exact"; + const bool fma_checked = mode != "off" && mode != "missing" && mode != "fmabad" && mode != "descwordoff"; + const bool fma_ok = !fma_checked || (has(std::string(", ") + fma_rule) && (mode == "fmaprecise" || has("x2w-mesh DoublePrecisionFloatShaderOps 1 "))); + if (fma_checked) std::printf("log: mesh stage line ends \"%s\" and capability line as required: %d\n", fma_rule, fma_ok); + if (!fma_ok) { + std::printf("FAIL: the fma lines do not match mode %s\n", mode.c_str()); + ++failures; + } + std::printf("log: issued %d, no translation %d, any x2w-mesh line %d, first bound line \"%s\"\n", issued, missing, any_mesh, + bound_line.c_str()); + // async: exactly one PSO line for the two calls (the second takes the worker's PSO; the PSO key is the same). + int async_pso_lines = 0; + for (std::size_t p = log.find("x2w-mesh desktop pipeline for "); p != std::string::npos; p = log.find("x2w-mesh desktop pipeline for ", p + 1)) ++async_pso_lines; + if (async) std::printf("log: async PSO lines %d\n", async_pso_lines); + // RTV variants (R32_UINT target): rtvvariant finds the variant translation (key fnv("rtv1 <key> 42")) and builds the + // PSO from it; the rtvuint control has none, so the call is refused and req_<variant>.rtv carries the request. + char variant_text[24]; + std::snprintf(variant_text, sizeof(variant_text), "%016llx", static_cast<unsigned long long>(variant_key)); + if (mode == "rtvvariant") { + const bool variant_line = has(std::string("x2w-mesh pipeline ") + key_text + ": RTV variant " + variant_text + " for target formats 42 (pixel stage yes)"); + const bool variant_pso = has(std::string("x2w-mesh desktop pipeline for ") + variant_text + ": 1 targets (format 42)"); + const bool refused = has(std::string("x2w-mesh pipeline ") + key_text + ": call refused"); + std::printf("log: RTV variant line %d, PSO from the variant %d, refusal line %d\n", variant_line, variant_pso, refused); + if (!variant_line || !variant_pso || refused) { + std::printf("FAIL: the RTV variant lines do not match\n"); + ++failures; + } + } + if (mode == "rtvnops") { // no variant asked for, no refusal: the call is issued with the base + const bool req = GetFileAttributesW((cache + L"\\req_" + hex_key(variant_key) + L".rtv").c_str()) != INVALID_FILE_ATTRIBUTES; + const bool refused = has(std::string("x2w-mesh pipeline ") + key_text + ": call refused"); + std::printf("log: req_%s.rtv exists %d, refusal line %d\n", variant_text, req, refused); + if (req || refused) { + std::printf("FAIL: a depth-only pipeline asked for an RTV variant\n"); + ++failures; + } + } + if (mode == "rtvuint") { + std::ifstream req_file(cache + L"\\req_" + hex_key(variant_key) + L".rtv", std::ios::binary); + std::string req{std::istreambuf_iterator<char>(req_file), {}}; + while (!req.empty() && (req.back() == '\n' || req.back() == '\r')) req.pop_back(); + std::printf("log: req_%s.rtv \"%s\" (want \"%s\")\n", variant_text, req.c_str(), rtv_request.c_str()); + if (req != rtv_request) { + std::printf("FAIL: the RTV variant request was not published\n"); + ++failures; + } + } + // uavtex: the translation has the uav table and the call binds the texture UAV (RGBA8 = format 28, mip 0); + // uavtexnoflag: the same line over a texture without unordered access skips the call. + if (uavtex) { + const bool table_line = has(std::string("x2w-draw-rt pipeline ") + key_text + ": 1 uavs in root parameter "); + const bool bound_uav = has(std::string("x2w-draw-rt ") + key_text + " uav 0 texture: ") && has("format 28 mip 0: bound"); + const bool skipped_uav = has(std::string("x2w-draw-rt ") + key_text + ": draw skipped: texture uav: texture without ALLOW_UNORDERED_ACCESS"); + std::printf("log: uav table line %d, texture uav bound %d, skipped (no unordered access) %d\n", table_line, bound_uav, skipped_uav); + if (!table_line || bound_uav != (mode == "uavtex") || skipped_uav != (mode == "uavtexnoflag")) { + std::printf("FAIL: the texture uav lines do not match mode %s\n", mode.c_str()); + ++failures; + } + } + const bool skipped_32 = has(std::string("x2w-draw-rt ") + key_text + ": heap draw skipped: descriptor increment is not 32"); + if (words && !words_skip) { // the heap views are bounded: heapmem = the 4-slot title heap (128 bytes) + const bool bounded = has(std::string("x2w-draw-rt ") + key_text + ": bounded heap views: heapmem 128 bytes (title heap 128), vinfo "); + std::printf("log: bounded heap views line (heapmem 128 bytes) %d\n", bounded); + if (!bounded) { + std::printf("FAIL: no bounded heap views line for the key\n"); + ++failures; + } + } + if (words_skip) std::printf("log: heap draw skipped (increment not 32) %d\n", skipped_32); + // descword: the entry value is the title's own dword 2 of table 1 entry 0 (48); descwordoff: the translation refused. + const bool descword_value_line = has(std::string("x2w-draw-rt ") + key_text + " descword 1 8: entry 0x") && has("title word = 0x00000030"); + const bool descword_refused = has(std::string("x2w-draw ") + key_text + ": `udsrc 2 descword 1 8` needs X2W_MESH_DESCWORD=1: translation refused"); + if (descword) { + std::printf("log: descword value line (title word 0x30) %d, refused without the switch %d\n", descword_value_line, descword_refused); + if (descword_value_line != (mode == "descword") || descword_refused != (mode == "descwordoff")) { + std::printf("FAIL: the descword lines do not match mode %s\n", mode.c_str()); + ++failures; + } + } + if (mode == "off" ? any_mesh + : mode == "descwordoff" ? issued + : mode == "missing" ? (!missing || issued || !bound_ok) + : refusal_mode ? (issued || !bound_ok || !reason_ok) + : words_skip ? (issued || !bound_ok || !skipped_32) + : async ? (issued != (mode == "async") || !bound_ok || (mode == "async" && (!has("(X2W_MESH_ASYNC worker)") || async_pso_lines != 1)) || + !has("x2w-mesh X2W_MESH_ASYNC=1: ")) + : (!issued || !bound_ok)) { + std::printf("FAIL: the x2w-mesh lines do not match mode %s\n", mode.c_str()); + ++failures; + } + if (smp) { // the translated sampler heap was built from the title's 128 entries (bound: none unbound) + std::string sampler_line; + if (const std::size_t p = log.find("x2w-draw sampler heap: "); p != std::string::npos) sampler_line = log.substr(p, log.find('\n', p) - p); + std::printf("log: sampler heap line \"%s\"\n", sampler_line.c_str()); + if (sampler_line.find("null_sampler_unbound=0 ") == std::string::npos || sampler_line.find("null_sampler_unreadable=0 ") == std::string::npos) { + std::printf("FAIL: the sampler heap was not built from the title's sampler heap\n"); + ++failures; + } + } + if (state_mode) { // the PSO line says which state it was made with; the switch line only with X2W_MESH_STATE=1 + const bool switch_line = has("x2w-mesh X2W_MESH_STATE=1: "); + const bool decoded_line = has(std::string("x2w-mesh desktop pipeline for ") + key_text) && has("; state decoded (X2W_MESH_STATE)"); + // The clip modes: the PSO line says depth clip alone was decoded (stateclip: off; stateclipkeep: on = the + // default, so no change and a "default" PSO), and the switch line exists when the switch is set. + const bool clip_line = has("; state default + depth clip decoded (X2W_DRAW_STATE_DEPTHCLIP): ") && + has(", cull 1 ccw 0 depthclip 0, "); + const bool clip_switch_line = has("x2w-mesh X2W_DRAW_STATE_DEPTHCLIP=1: "); + std::printf("log: X2W_MESH_STATE line %d, PSO with decoded state %d, depth clip alone %d (switch line %d)\n", switch_line, + decoded_line, clip_line, clip_switch_line); + if (switch_line != state_on || decoded_line != state_on || clip_line != (mode == "stateclip") || + clip_switch_line != (mode == "stateclip" || mode == "stateclipkeep")) { + std::printf("FAIL: the X2W_MESH_STATE lines do not match mode %s\n", mode.c_str()); + ++failures; + } + const bool flip_line = has("(X2W_MESH_STATE_CULL_FLIP: front face inverted)"); + const bool nocull_line = has("(X2W_MESH_STATE_NOCULL: rasterizer default)"); + if (flip_line != (mode == "statecullflip") || nocull_line != (mode == "statecullnone")) { + std::printf("FAIL: flip line %d / nocull line %d do not match mode %s\n", flip_line, nocull_line, mode.c_str()); + ++failures; + } + // PSO lines of the key: one per pass signature. statezrepeat: 64 calls in two passes -> exactly two lines. + const std::string pso_line = std::string("x2w-mesh desktop pipeline for ") + key_text + ": "; + int pso_lines = 0; + for (std::size_t p = log.find(pso_line); p != std::string::npos; p = log.find(pso_line, p + 1)) ++pso_lines; + const bool both_passes = has(pso_line + "1 targets (format 28), dsv 40,") && has(pso_line + "1 targets (format 28), dsv 0,"); + std::printf("log: PSO lines for the key %d%s\n", pso_lines, repeat ? (both_passes ? " (dsv 40 and dsv 0)" : " (not both passes)") : ""); + // The binding's PSO serves the calls after the first of a pass: the once-per-process line, only with repeats. + const bool reused = has(std::string("x2w-mesh pipeline ") + key_text + ": PSO kept with the binding reused"); + std::printf("log: binding PSO reused line %d\n", reused); + // Depth state of the PSO: on where a forwarded clear marked the target, off on the uncleared control; + // statezlateclear: one call before the slot 51 clear (depth off), one after (a second PSO, depth on). + const bool depth_on_line = has(pso_line + "1 targets (format 28), dsv 40, depth 1,"); + const bool depth_off_line = has(pso_line + "1 targets (format 28), dsv 40, depth 0,"); + const bool late = mode == "statezlateclear"; + if (zmode && state_on && !repeat) { + const bool want_on = mode != "statezuncleared", want_off = mode == "statezuncleared" || late; + std::printf("log: PSO depth on %d / off %d (want %d / %d)\n", depth_on_line, depth_off_line, want_on, want_off); + if (depth_on_line != want_on || depth_off_line != want_off) { + std::printf("FAIL: PSO depth state does not match mode %s\n", mode.c_str()); + ++failures; + } + } + if (pso_lines != (repeat || late ? 2 : 1) || (repeat && !both_passes) || reused != repeat) { + std::printf("FAIL: PSO lines do not match mode %s\n", mode.c_str()); + ++failures; + } + } + if (words) { // the vdesc root parameter and buffer, and the word the stand-in wrote for the view + const bool root = has(std::string("x2w-vdesc pipeline ") + key_text + ": heapwords 1, vdesc in root parameter "); + const bool buffer = has("x2w-vdesc buffer 90000 ids x 32 bytes"); + std::string view_line; + if (const std::size_t p = log.find("x2w-vdesc view "); p != std::string::npos) view_line = log.substr(p, log.find('\n', p) - p); + std::printf("log: vdesc root parameter %d, vdesc buffer %d, view words \"%s\"\n", root, buffer, view_line.c_str()); + // Skipped (increment not 32): the root parameter exists, but no buffer is made and no view is filled. + if (!root || (words_skip ? buffer || !view_line.empty() : !buffer || view_line.empty())) { + std::printf("FAIL: the x2w-vdesc lines do not match mode %s\n", mode.c_str()); + ++failures; + } + } + // Traced frame (the trace_* tests run with X2W_D3D12_TRACE_ALL=1 X2W_D3D12_TRACE_TARGETS=1): one "x2w-frame mesh" + // line per call with key, targets, depth target, viewport, scissor, depth state and record words, and the targets + // noted for the read-back. Every other run is the negative control: no such line. + std::string log_tail; // lines written by the read-back below (traced runs), for the debug-layer check + char traced_env[8]{}; + const bool traced = GetEnvironmentVariableA("X2W_D3D12_TRACE_ALL", traced_env, sizeof(traced_env)) && traced_env[0] == '1'; + { + std::string frame_line; + if (const std::size_t p = log.find("x2w-frame mesh "); p != std::string::npos) frame_line = log.substr(p, log.find('\n', p) - p); + unsigned noted[4 * 8]{}; + const unsigned notes = x2w_d3d12_traced_targets(noted, 8); + std::printf("log: traced %d, frame line \"%s\", targets noted %u", traced, frame_line.c_str(), notes); + for (unsigned i = 0; i < notes && i < 8; ++i) std::printf(" [%ux%u fmt %u draws %u]", noted[4 * i], noted[4 * i + 1], noted[4 * i + 2], noted[4 * i + 3]); + std::printf("\n"); + bool trace_ok; + if (!traced) { + trace_ok = frame_line.empty() && notes == 0; + } else if (mode == "notargets") { // refused before the bind: a NOT drawn line with the reason, nothing noted + trace_ok = frame_line.find(std::string("x2w-frame mesh NOT drawn key ") + key_text + " targets 0 dsv ") == 0 && + frame_line.find(" viewport 0.0 0.0 32.0 32.0 depth 0.00-1.00 scissor 0 0 32 32") != std::string::npos && + frame_line.find(": no targets") != std::string::npos && notes == 0; + } else if (mode == "statez") { // drawn: RGBA8 target and D32 depth target, LESS + write (decoded), both noted once + trace_ok = frame_line.find(std::string("x2w-frame mesh drawn key ") + key_text + " targets 1 [0 ") == 0 && + frame_line.find(" 32x32 fmt 28] dsv ") != std::string::npos && frame_line.find(" fmt 40 (32x32 res fmt 40, last clear depth 0.5 stencil 0 flags 0x1 frame ") != std::string::npos && + frame_line.find(") query #0 viewport 0.0 0.0 32.0 32.0 depth 0.00-1.00 scissor 0 0 32 32 depth 1 func 2 write 1 stencil ") != std::string::npos && + frame_line.find(" record (max count 1, stride ") != std::string::npos && + frame_line.find(" raster cull ") != std::string::npos && frame_line.find("(from the title; title PA_SU_SC_MODE_CNTL ") != std::string::npos && + notes == 2 && noted[0] == 32 && noted[1] == 32 && noted[2] == 28 && noted[3] == 1 && noted[4] == 32 && noted[6] == 40 && noted[7] == 1; + } else if (mode == "statecull") { // X2W_MESH_STATE: the decoded rasterizer (cull back) in the PSO, with the title's words + trace_ok = frame_line.find(std::string("x2w-frame mesh drawn key ") + key_text + " targets 1 [0 ") == 0 && + frame_line.find(" raster cull 3 ccw ") != std::string::npos && + frame_line.find("(from the title; title PA_SU_SC_MODE_CNTL ") != std::string::npos && notes == 1 && noted[3] == 1; + } else if (mode == "stateculloff") { // the control: X2W_MESH_STATE unset, the default rasterizer (cull none) + trace_ok = frame_line.find(std::string("x2w-frame mesh drawn key ") + key_text + " targets 1 [0 ") == 0 && + frame_line.find(" raster cull 1 ccw 0 depthclip 1 bias 0/") != std::string::npos && + frame_line.find("(default: X2W_MESH_STATE off or NOCULL; title PA_SU_SC_MODE_CNTL ") != std::string::npos && notes == 1 && noted[3] == 1; + } else if (rectrace) { // the gpu call drawn, its target noted + trace_ok = frame_line.find(std::string("x2w-frame mesh drawn key ") + key_text + " targets 1 [0 ") == 0 && notes == 1 && noted[3] == 1; + } else if (mode == "zero") { // issued with 0 groups (the stats control): a drawn line with a query, the target noted + trace_ok = frame_line.find(std::string("x2w-frame mesh drawn key ") + key_text + " targets 1 [0 ") == 0 && + frame_line.find(" query #0 ") != std::string::npos && notes == 1 && noted[2] == 28 && noted[3] == 1; + } else { + trace_ok = false; // no trace expectation for this mode + } + if (!trace_ok) { + std::printf("FAIL: the traced-frame mesh line / noted targets do not match mode %s (traced %d)\n", mode.c_str(), traced); + ++failures; + } + // The end-of-frame read-back of the noted targets (as at the traced frame's present), from the snapshots: + // statez: target 0 (RGBA8, drawn: some texels non-zero) and target 1 (D32, cleared to 0.5 and drawn at 0.25: + // non-zero); notargets: no target line. Then the debug-layer check below covers the read-back too. + if (traced) { + x2w_d3d12_record_trace_report(); // LOCAL (scene): no-op without X2W_MESH_RECORD_TRACE + x2w_d3d12_mesh_stats_report(); // the GPU work is complete (the pixels were read back above) + x2w_d3d12_summarise_traced_targets(); + std::ifstream again(log_path, std::ios::binary); + const std::string after{std::istreambuf_iterator<char>(again), {}}; + const auto line_of = [&](const std::string& start) { + const std::size_t p = after.find(start); + return p == std::string::npos ? std::string() : after.substr(p, after.find('\n', p) - p); + }; + const std::string t0 = line_of("x2w-frame target 0 "), t1 = line_of("x2w-frame target 1 "); + std::printf("log: read-back \"%s\" / \"%s\"\n", t0.c_str(), t1.c_str()); + const auto nonzero_share = [](const std::string& line) { + const std::size_t p = line.find("non-zero texels "); + return p == std::string::npos ? -1.0 : std::atof(line.c_str() + p + 16); + }; + const bool bad = after.find("not summarised") != std::string::npos || after.find("read-back timed out") != std::string::npos; + const bool read_ok = mode == "statez" + ? t0.find(" snapshot ") != std::string::npos && t0.find(" 32x32 fmt 28 draws 1:") != std::string::npos && nonzero_share(t0) > 0.0 && + t1.find(" snapshot ") != std::string::npos && t1.find(" 32x32 fmt 40 draws 1:") != std::string::npos && nonzero_share(t1) > 0.0 + : mode == "zero" ? t0.find(" snapshot ") != std::string::npos && t0.find(" 32x32 fmt 28 draws 1:") != std::string::npos && nonzero_share(t0) == 0.0 + : mode == "statecull" || mode == "stateculloff" ? t0.find(" snapshot ") != std::string::npos && nonzero_share(t0) > 0.0 + : rectrace ? true // not what these modes check + : t0.empty(); + if (!read_ok || bad) { + std::printf("FAIL: the traced-target read-back does not match mode %s\n", mode.c_str()); + ++failures; + } + // Pipeline statistics: statez's call has query #0 and a stats line with clipped primitives and pixel + // invocations (two triangles drawn); notargets is refused before the bind: no query, no stats line. + const std::string stats = line_of(std::string("x2w-frame mesh stats #0 key ") + key_text + ": "); + const auto number_after = [](const std::string& line, const char* label) -> long long { + const std::size_t p = line.find(label); + return p == std::string::npos ? -1 : std::atoll(line.c_str() + p + std::strlen(label)); + }; + const long long c_prims = number_after(stats, "clipper invocations "), ps = number_after(stats, "PS invocations "); + const std::size_t clip_at = stats.find("clipper invocations "); + const long long c_primitives = clip_at == std::string::npos ? -1 : number_after(stats.substr(clip_at), " primitives "); + const long long ms_primitives = stats.find("MS invocations ") != std::string::npos ? number_after(stats, " primitives ") : -2; + std::printf("log: stats \"%s\" (clipper invocations %lld primitives %lld, PS %lld, MS primitives %lld; -2: no MS counts)\n", + stats.c_str(), c_prims, c_primitives, ps, ms_primitives); + const bool stats_ok = mode == "statez" + ? frame_line.find(" query #0") != std::string::npos && c_primitives >= 1 && ps >= 1 && (ms_primitives == -2 || ms_primitives >= 1) + : mode == "zero" ? !stats.empty() && c_prims == 0 && c_primitives == 0 && ps == 0 && (ms_primitives == -2 || ms_primitives == 0) + // statecull: 2 triangles emitted, one back-facing and culled. Whether the clipper count includes the + // culled one is what this run measures (printed above); either 1 or 2 passes, one triangle's pixels. + : mode == "statecull" ? !stats.empty() && (ms_primitives == -2 || ms_primitives == 2) && (c_primitives == 1 || c_primitives == 2) && ps >= 1 + : mode == "stateculloff" ? !stats.empty() && (ms_primitives == -2 || ms_primitives == 2) && c_primitives == 2 && ps >= 1 + : rectrace ? !stats.empty() + : stats.empty() && after.find("x2w-frame mesh stats #") == std::string::npos; + if (!stats_ok) { + std::printf("FAIL: the pipeline statistics do not match mode %s\n", mode.c_str()); + ++failures; + } + // LOCAL (scene) rectrace / rectraceapart: the cx-img, cx-heap and mesh-read lines (see the top of main). + if (rectrace) { + const auto count_of = [&](const std::string& text) { + std::size_t n = 0; + for (std::size_t p = after.find(text); p != std::string::npos; p = after.find(text, p + 1)) ++n; + return n; + }; + char cull_ptr[32], tex_ptr[32], tsharp_text[96], vertex_text[48], other_text[48]; + std::snprintf(cull_ptr, sizeof(cull_ptr), "pipeline %p: skipped: c62 table argument:", cull); + std::snprintf(tex_ptr, sizeof(tex_ptr), "res %p title ", trace_texture); + std::snprintf(tsharp_text, sizeof(tsharp_text), ": T# 0x%llx 2x1 depth 1 fmt 56 levels 0-0 type 9 sw 0; ", + static_cast<unsigned long long>(arg(trace_texels))); + std::snprintf(vertex_text, sizeof(vertex_text), "buffer 0x%llx 48 bytes", static_cast<unsigned long long>(vertex_address)); + std::snprintf(other_text, sizeof(other_text), "buffer 0x%llx 64 bytes", static_cast<unsigned long long>(arg(other_memory))); + const bool apart = mode == "rectraceapart"; + // Image lines only (the writer's cx-heap lines also describe images: its record words 2, 1, 0 are taken + // as heap indexes, the ASSUMED rule). + const auto img_lines = [&](const std::string& text) { + std::size_t n = 0; + for (std::size_t p = after.find("x2w-frame cx-img #"); p != std::string::npos; p = after.find("x2w-frame cx-img #", p + 1)) { + const std::string line = after.substr(p, after.find('\n', p) - p); + n += line.find(text) != std::string::npos; + } + return n; + }; + const std::size_t cull_lines = count_of(cull_ptr); + const std::size_t srv_images = img_lines("(srv) dim 4 fmt 28 mip 0; " + std::string(tex_ptr)); + const std::size_t uav_images = img_lines(" (uav): view "); + const std::size_t raw_images = img_lines(tsharp_text + std::string(tex_ptr)); + const std::size_t no_writer = img_lines("; content: no writer seen in this frame before this dispatch"); + const std::size_t uav_writer = img_lines("; content: texture uav of key "); + const std::string heap_index = apart ? " index 4 (count 8, increment " : " index 0 (count 8, increment "; + const std::size_t heap_lines = count_of(heap_index) && count_of(apart ? other_text : vertex_text) ? 1 : 0; + // The mesh reads: srv 0 (table 1 + 0) and heap index 0 (root constant [0][1]). + char srv_read[160], heap_read[160]; + std::snprintf(srv_read, sizeof(srv_read), "x2w-frame mesh-read key %s S0 (source 0 1+0x0) 0x%llx 48 bytes, 1 calls: ", key_text, + static_cast<unsigned long long>(vertex_address)); + std::snprintf(heap_read, sizeof(heap_read), "x2w-frame mesh-read key %s H0 (heap index 0, root constant p0 w1) 0x%llx 48 bytes, 1 calls: ", + key_text, static_cast<unsigned long long>(vertex_address)); + const std::string verdict = apart ? "run dispatches only" : "INSIDE a skipped dispatch's range"; + const std::size_t srv_ok = count_of(srv_read + verdict), heap_ok = count_of(heap_read + verdict); + const std::size_t totals = count_of(apart ? "2 distinct ranges: 0 inside a skipped dispatch's range (0 inside a skipped table / heap entry, 0 only" + : "2 distinct ranges: 2 inside a skipped dispatch's range (2 inside a skipped table / heap entry, 0 only"); + // The reverse view: rectrace, the table V# entry and the heap entry of the cull pass, each with both reads; apart: none. + char by_entry[160], by_heap[160]; + std::snprintf(by_entry, sizeof(by_entry), " ? p2+0x0 0x%llx 48 bytes, skipped: c62 table argument, 2 dispatches (first #2): 2 distinct mesh reads, 2 calls", + static_cast<unsigned long long>(vertex_address)); + std::snprintf(by_heap, sizeof(by_heap), " H p3+0x0 0x%llx 48 bytes, skipped: c62 table argument, 2 dispatches (first #2): 2 distinct mesh reads, 2 calls", + static_cast<unsigned long long>(vertex_address)); + const std::size_t by_lines = count_of("x2w-frame mesh-read by-range "); + const bool by_ok = apart ? by_lines == 0 : by_lines == 2 && count_of(by_entry) == 1 && count_of(by_heap) == 1; + // cx-root: once per skipped dispatch, with the heap and the raw constants; the integer entry's `other` line. + const std::size_t root_lines = count_of(apart ? " p3 constants 2: 00000004 00000100;" : " p3 constants 2: 00000000 00000100;"); + const std::size_t root_heap = count_of(" count 8 increment " + std::to_string(view_increment) + "; p0 kind 4 "); + const std::size_t other_lines = img_lines(": other: words 00000005 00000000 00000000 00000000 00000000 00000000 00000000 00000000 (integer + 7 zero words"); + std::printf("log: rectrace cull lines %zu, images srv %zu uav %zu raw T# %zu, content none %zu / uav writer %zu, heap line %zu, " + "mesh reads srv %zu heap %zu, totals %zu, by-range %zu (%d), cx-root %zu (heap %zu), other %zu\n", + cull_lines, srv_images, uav_images, raw_images, no_writer, uav_writer, heap_lines, srv_ok, heap_ok, totals, by_lines, by_ok, + root_lines, root_heap, other_lines); + // Two dispatches x 3 image entries; the first sees no writer, the second names the first's UAV. + if (cull_lines != 2 || srv_images != 2 || uav_images != 2 || raw_images != 2 || no_writer != 3 || uav_writer != 3 || !heap_lines || + srv_ok != 1 || heap_ok != 1 || totals != 1 || !by_ok || root_lines != 2 || root_heap != 2 || other_lines != 2) { + std::printf("FAIL: the X2W_MESH_RECORD_TRACE lines do not match mode %s\n", mode.c_str()); + ++failures; + } + } + log_tail = after.substr(log.size() < after.size() ? log.size() : after.size()); + } + } + if (dump_test) { // X2W_MESH_DUMP_INPUTS, traced or not (the dump selects the first call with groups in any frame) + // X2W_MESH_DUMP_INPUTS (statez): the dump folder next to the log, the vertex srv bytes equal to the test's + // vertices, entry constants, root constants and the 12-byte record of an issued call. + if (mode == "statez") { + const std::wstring dump = cache + L"\\mesh_dump_" + std::wstring(key_text, key_text + 16) + L"\\"; + const auto read_all = [](const std::wstring& path) { + std::ifstream f(path, std::ios::binary); + return std::string{std::istreambuf_iterator<char>(f), {}}; + }; + const std::string index = read_all(dump + L"index.txt"); + bool vertices_found = false; + for (int s = 0; s < 8 && !vertices_found; ++s) { + const std::string bytes = read_all(dump + L"srv" + std::to_wstring(s) + L".bin"); + vertices_found = bytes.size() == sizeof(vertices) && std::memcmp(bytes.data(), vertices, sizeof(vertices)) == 0; + } + const std::string record = read_all(dump + L"record.bin"); + // The heap buffer named by root constant [0][1] (bit 28, index 0): the vertices again, and its descriptor. + const std::string heap0 = read_all(dump + L"heap0.bin"), heap0_desc = read_all(dump + L"heap0_desc.bin"); + const bool heap_ok = heap0.size() == sizeof(vertices) && std::memcmp(heap0.data(), vertices, sizeof(vertices)) == 0 && + heap0_desc.size() == 32 && index.find("(root constant [0][1] = 0x10000000)") != std::string::npos && + index.find("heap3") == std::string::npos; + // The list's other key (0000000000000001) matches no call: no folder for it. + const DWORD other = GetFileAttributesW((cache + L"\\mesh_dump_0000000000000001").c_str()); + const bool dump_ok = other == INVALID_FILE_ATTRIBUTES && has("x2w-mesh X2W_MESH_DUMP_INPUTS: 2 key(s)") && heap_ok && + vertices_found && index.find("entry.bin ") != std::string::npos && + index.find("root_constants.bin 512 bytes") != std::string::npos && record.size() == 12 && + index.find("call issued") != std::string::npos && has(std::string("x2w-mesh dump ") + key_text + ":"); + std::printf("log: dump index:\n%s(vertices found %d, record %zu bytes)\n", index.c_str(), vertices_found, record.size()); + if (!dump_ok) { + std::printf("FAIL: the X2W_MESH_DUMP_INPUTS files do not match (heap buffer %d)\n", heap_ok); + ++failures; + } + } + if (mode == "zero") { // the control: the key is listed, but its only call has X = 0 at record time: no dump + const DWORD folder = GetFileAttributesW((cache + L"\\mesh_dump_" + std::wstring(key_text, key_text + 16)).c_str()); + const bool none = folder == INVALID_FILE_ATTRIBUTES && !has(std::string("x2w-mesh dump ") + key_text + ":") && + has("x2w-mesh X2W_MESH_DUMP_INPUTS: 2 key(s)"); + std::printf("log: zero-group call dumped %d\n", !none); + if (!none) { + std::printf("FAIL: a call with X = 0 was dumped\n"); + ++failures; + } + } + } + // X2W_MESH_STATS_FRAMES=1 (framestats_* tests, not traced): the frame's mesh calls carry a statistics query; the + // frame is closed and reported here (the fixture has no present; the GPU work is complete). gpu: record-time X 1 > + // 0, so the frame counts: one target-set line with 1 call (1 with groups), the GPU's 2 groups = 6 MS invocations, 2 + // triangles; zero (control): X = 0 at record time, the frame does not count: no target-set line. + // X2W_TEST_FS_MULTI=1 (framestatsmulti_* tests, X2W_MESH_STATS_FRAMES=2): the present path, no report export. After + // the main frame (frame 0): a present; 20 frames of one call with record X = 0 (each presented: slots wrap past 16, + // more than 8 frames that do not count); frame 21: a call with record {1, 1, 1} and one with {1, 0, 1} (X > 0, no + // groups); frame 22: one {1, 1, 1} call (collection has stopped: 2 frames counted); 9 more presents (frame 21 is + // read 8 presents after it ends). gpu: frames 0 and 21 count; zero (control): every record has X = 0, nothing counts. + char frames_env[8]{}, multi_env[8]{}; + const bool fs_multi = GetEnvironmentVariableA("X2W_TEST_FS_MULTI", multi_env, sizeof(multi_env)) && multi_env[0] == '1'; + if (GetEnvironmentVariableA("X2W_MESH_STATS_FRAMES", frames_env, sizeof(frames_env)) && frames_env[0]) { + if (fs_multi) { + UINT64 fence_value = 1; + const auto fs_call = [&](std::uint32_t record_x, std::uint32_t record_y) { + const std::uint32_t record[3] = {record_x, record_y, 1}; + std::memcpy(args_memory, record, 12); // the record at record time, and what the GPU reads + invoke(list, 139, arg(allocator)); // Reset + invoke(list, 50, 1, arg(&target_handle)); + invoke(list, 21, 1, arg(&viewport)); + invoke(list, 22, 1, arg(&scissor)); + invoke(list, 34, arg(title_root)); + invoke(list, 32, smp ? 2 : 1, arg(heaps)); + invoke(list, 36, 1, view_gpu); + invoke(list, 40, 2, 1, arg(&colour), 0); + invoke(list, 25, arg(pipeline)); + invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); + invoke(list, 9); // Close + invoke(queue, 10, 1, arg(lists)); + invoke(queue, 14, arg(fence), ++fence_value); + for (const auto until = GetTickCount64() + 10000; invoke(fence, 8) < fence_value && GetTickCount64() < until;) Sleep(1); + }; + const std::uint32_t x1 = mode == "zero" ? 0u : 1u; + x2w_d3d12_mesh_frame_stats_present(); // frame 0 ends + for (int f = 1; f <= 20; ++f) { + fs_call(0, 1); + x2w_d3d12_mesh_frame_stats_present(); + } + fs_call(x1, 1); + fs_call(x1, 0); + x2w_d3d12_mesh_frame_stats_present(); // frame 21 ends + fs_call(x1, 1); + x2w_d3d12_mesh_frame_stats_present(); // frame 22 ends + for (int i = 0; i < 9; ++i) x2w_d3d12_mesh_frame_stats_present(); + } else { + x2w_d3d12_mesh_frame_stats_report(); + } + std::ifstream again(log_path, std::ios::binary); + const std::string after{std::istreambuf_iterator<char>(again), {}}; + std::string set_line, total_line; + for (std::size_t p = after.find("x2w-mesh stats frame "); p != std::string::npos && set_line.empty(); p = after.find("x2w-mesh stats frame ", p + 1)) { + const std::string line = after.substr(p, after.find('\n', p) - p); + if (line.find(" set ") != std::string::npos) set_line = line; // a target-set line (not "not counted") + } + if (const std::size_t p = after.find("x2w-mesh stats frames total "); p != std::string::npos) total_line = after.substr(p, after.find('\n', p) - p); + std::printf("log: frame stats \"%s\" / \"%s\"\n", set_line.c_str(), total_line.c_str()); + const auto line_of = [&](const std::string& start) { + const std::size_t p = after.find(start); + return p == std::string::npos ? std::string() : after.substr(p, after.find('\n', p) - p); + }; + std::size_t not_counted = 0; + for (std::size_t p = after.find(" not counted (no record with X > 0"); p != std::string::npos; p = after.find(" not counted (no record with X > 0", p + 1)) + ++not_counted; + const std::string set0 = line_of("x2w-mesh stats frame 0 set "), set21 = line_of("x2w-mesh stats frame 21 set "); + if (fs_multi) + std::printf("log: multi: frame 0 \"%s\", frame 21 \"%s\", not counted lines %zu, frame 22 lines %d\n", set0.c_str(), set21.c_str(), not_counted, + after.find("x2w-mesh stats frame 22 ") != std::string::npos); + const std::string targets = "set targets 1 [fmt 28 32x32] dsv none: "; + const bool set_ok = fs_multi + ? mode == "zero" + ? set_line.empty() && total_line.empty() && not_counted == 8 + : set0.find(targets + "calls 1 (1 with groups), ") != std::string::npos && + set21.find(targets + "calls 2 (1 with groups), ") != std::string::npos && set21.find("clipper invocations 0 ") == std::string::npos && + total_line.find("x2w-mesh stats frames total 1 of 2 frames (frame 0)") == 0 && + line_of("x2w-mesh stats frames total 2 ").find("x2w-mesh stats frames total 2 of 2 frames (frame 21): 1 target sets, calls 2 (1 with groups)") == 0 && + not_counted == 8 && after.find("x2w-mesh stats frame 22 ") == std::string::npos && + after.find("x2w-mesh stats frames total 3 ") == std::string::npos + : mode == "zero" + ? set_line.empty() && after.find("x2w-mesh stats frame 0 not counted (no record with X > 0") != std::string::npos + : set_line.find(" set targets 1 [fmt 28 32x32] dsv none: calls 1 (1 with groups), ") != std::string::npos && + (set_line.find("MS invocations 6 primitives 2, clipper invocations 2 primitives 2, PS invocations ") != std::string::npos || + set_line.find("(no MS counts) clipper invocations 2 primitives 2") != std::string::npos) && + total_line.find("x2w-mesh stats frames total 1 of 1 frames") == 0; + if (!set_ok) { + std::printf("FAIL: the X2W_MESH_STATS_FRAMES lines do not match mode %s\n", mode.c_str()); + ++failures; + } + log_tail += after.substr(log.size() < after.size() ? log.size() : after.size()); + } else if (has("X2W_MESH_STATS_FRAMES") || has("x2w-mesh stats frame")) { // every other run: the switch is off + std::printf("FAIL: frame statistics lines without X2W_MESH_STATS_FRAMES\n"); + ++failures; + } + const std::string debug_log = log + log_tail; + for (std::size_t p = debug_log.find("x2w-d3d12-debug"); p != std::string::npos; p = debug_log.find("x2w-d3d12-debug", p + 1)) { + const std::size_t end = debug_log.find('\n', p); + const std::string line = debug_log.substr(p, end == std::string::npos ? std::string::npos : end - p); + std::printf("%s\n", line.c_str()); + if (line.find("sev=0 ") != std::string::npos || line.find("sev=1 ") != std::string::npos) ++failures; + } + std::printf("device removed reason: 0x%08lx\n", static_cast<unsigned long>(desktop->GetDeviceRemovedReason())); + if (desktop->GetDeviceRemovedReason() != S_OK) ++failures; + if (!failures && words_skip) { + std::printf("view increment %u is not 32: skipped as required, vdesc not exercised: capability skip\n", view_increment); + return 77; + } + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; +} diff --git a/tests/startup_mesh_dispatch.hlsl b/tests/startup_mesh_dispatch.hlsl new file mode 100644 index 0000000000..3b25815e76 --- /dev/null +++ b/tests/startup_mesh_dispatch.hlsl @@ -0,0 +1,127 @@ +// Shaders for tests/startup_mesh_dispatch.cpp (a hand-written stand-in for a translated mesh pipeline). +// +// MeshMain / PixelMain use the translated draw root signature the stand-in builds from the manifest +// (x2w_startup::create_translated_root): b0 = the entry values (udsrc 0 rect, udsrc 1 rootconst), t0 = srv 0. +// One triangle per group: group g reads vertices 3g..3g+2 (float2 each) from t0. Colour from entry value 1 +// (0x00BBGGRR); alpha 1 when the rect entry value is 0 (a mesh call must bind 0 there), else 0.5. +ByteAddressBuffer positions : register(t0); +cbuffer Entry : register(b0) { uint rect; uint colour; }; + +struct Vertex { + float4 param0 : PARAM0; + float4 pos : SV_Position; +}; + +[numthreads(3, 1, 1)] +[outputtopology("triangle")] +void MeshMain(uint3 group : SV_GroupID, uint thread : SV_GroupThreadID, out vertices Vertex verts[3], out indices uint3 tris[1]) +{ + SetMeshOutputCounts(3, 1); + const float2 p = asfloat(positions.Load2(((colour & (1u << 25)) ? (16u << 20) : 0u) + (group.x * 3 + thread) * 8)); + // Colour bit 24 (the stateclip modes): z 1.5 = beyond the far plane (z / w > 1), drawn only with depth clip off. + verts[thread].pos = float4(p, (colour >> 24) & 1 ? 1.5 : 0.25, 1.0); + verts[thread].param0 = float4((colour & 255) / 255.0, ((colour >> 8) & 255) / 255.0, ((colour >> 16) & 255) / 255.0, + rect == 0 ? 1.0 : 0.5); + if (thread == 0) tris[0] = uint3(0, 1, 2); +} + +// MeshHeap (modes words16 / words32 / wordsraw): a typed buffer reached through a RESOURCE-HEAP descriptor, read with +// the format from its descriptor words (manifest `heap 1` + `heapwords 1`; mesh_work/RUNTIME_NEEDS.md 6.1 / 6.3), as +// mesh2hlsl emits it: heapmem (t0 space1, the title heap: view token X2WV + view id per 32-byte slot), the view-id +// region (raw buffer views at 8 + 8 * id + 4, t0 space6) and vdesc (t2 space1, 8 gfx10 words per view id). The heap +// slot comes from entry value 2 (a root constant). Word 3 FORMAT (bits 12-18): 29 = 16_16_FLOAT (positions read as +// half2), 64 = 32_32_FLOAT (float2); any other format draws nothing. Green = the FORMAT code / 255, so the read-back +// shows which word the shader saw. +cbuffer HeapEntry : register(b0) { uint heap_rect; uint heap_colour; uint heap_slot; }; +ByteAddressBuffer heapmem : register(t0, space1); +ByteAddressBuffer vdesc : register(t2, space1); +ByteAddressBuffer heapbuf[] : register(t0, space6); + +[numthreads(3, 1, 1)] +[outputtopology("triangle")] +void MeshHeap(uint3 group : SV_GroupID, uint thread : SV_GroupThreadID, out vertices Vertex verts[3], out indices uint3 tris[1]) +{ + const uint h = heap_slot * 32; + const uint id = heapmem.Load(h) == 0x56573258u ? heapmem.Load(h + 4) : 0xffffffffu; + const uint word3 = id < 90000u ? vdesc.Load(id * 32 + 12) : 0u; + const uint format = (word3 >> 12) & 127u; + const bool known = format == 29u || format == 64u; + SetMeshOutputCounts(known ? 3 : 0, known ? 1 : 0); + if (!known) return; + const uint e = group.x * 3 + thread; + const uint k = 8u + 8u * id + 4u; + float2 p; + if (format == 29u) { + const uint v = heapbuf[NonUniformResourceIndex(k)].Load(e * 4); + p = f16tof32(uint2(v & 0xffffu, v >> 16)); + } else { + p = asfloat(heapbuf[NonUniformResourceIndex(k)].Load2(e * 8)); + } + verts[thread].pos = float4(p, 0.25, 1.0); + verts[thread].param0 = float4((heap_colour & 255) / 255.0, format / 255.0, ((heap_colour >> 16) & 255) / 255.0, heap_rect == 0 ? 1.0 : 0.5); + if (thread == 0) tris[0] = uint3(0, 1, 2); +} + +// MeshDescword (modes descword / descwordoff; manifest `udsrc 2 descword 1 8`, mesh2hlsl X2W_MESH_FEATURES=descword): a +// word of a TABLE descriptor read as a number, as a translated mesh stage reads a V# NUM_RECORDS. Entry value 2 is +// dword 2 (byte 8) of the descriptor in table parameter 1 entry 0: the test's hardware buffer descriptor, NUM_RECORDS +// = 48 (0x30). Green = that word's low byte; the triangle is drawn only when the word is 48 (a group reads its +// vertices only within NUM_RECORDS bytes, as the console's bounds check would). +cbuffer DescEntry : register(b0) { uint desc_rect; uint desc_colour; uint desc_word2; }; + +[numthreads(3, 1, 1)] +[outputtopology("triangle")] +void MeshDescword(uint3 group : SV_GroupID, uint thread : SV_GroupThreadID, out vertices Vertex verts[3], out indices uint3 tris[1]) +{ + const uint e = group.x * 3 + thread; + const bool inside = desc_word2 == 48u && (group.x * 3 + 3) * 8 <= desc_word2; + SetMeshOutputCounts(inside ? 3 : 0, inside ? 1 : 0); + if (!inside) return; + const float2 p = asfloat(positions.Load2(e * 8)); + verts[thread].pos = float4(p, 0.25, 1.0); + verts[thread].param0 = float4((desc_colour & 255) / 255.0, (desc_word2 & 255) / 255.0, ((desc_colour >> 16) & 255) / 255.0, + desc_rect == 0 ? 1.0 : 0.5); + if (thread == 0) tris[0] = uint3(0, 1, 2); +} + +// PixelSampler (modes smpheap / smpheapswap; manifest `smpheap 2048 1 fallback 2047`, board/msgs/225000_mesh3): a +// FIXED entry of the title's sampler heap, as mesh3's translation emits it (qh[2048] in space1, entry 65), over a 2x1 +// texture (srv 1, texel 0 red, texel 1 blue) at u = 0.375: point sampling gives red, linear 0.75 red + 0.25 blue. +Texture2D smp_tex : register(t1); +SamplerState qh[2048] : register(s0, space1); +float4 PixelSampler(Vertex input) : SV_Target0 +{ + return smp_tex.SampleLevel(qh[65u], float2(0.375, 0.5), 0); +} + +float4 PixelMain(Vertex input) : SV_Target0 +{ + return input.param0; +} + +// PixelUint (mode rtvvariant): the RTV variant of PixelMain for an R32_UINT target, as a translator would emit it for +// `rtv1 <key> 42`: the colour bytes of param0 packed into one uint (0x00BBGGRR when alpha is 1). +uint4 PixelUint(Vertex input) : SV_Target0 +{ + const uint4 c = uint4(round(saturate(input.param0) * 255.0)); + return uint4(c.x | (c.y << 8) | (c.z << 16) | ((c.w == 255u ? 0u : c.w) << 24), 0, 0, 0); +} + +// PixelStore (modes uavtex / uavtexnoflag): an image_store as the translator lowers it (`uav 0 tex2d table 1 <off>`): +// the colour stored to texel (x, y) of the texture UAV u0 and also returned to the target. +RWTexture2D<float4> store0 : register(u0); +float4 PixelStore(Vertex input) : SV_Target0 +{ + store0[uint2(input.pos.xy)] = input.param0; + return input.param0; +} + +// Writer (a console compute pipeline, container path): root [0] UAV u0, [1] four constants b1. +// Stores the DispatchMesh record values.xyz at byte offset values.w of u0. +RWByteAddressBuffer target : register(u0); +cbuffer Values : register(b1) { uint4 values; }; +[numthreads(1, 1, 1)] +void Writer() +{ + target.Store3(values.w, values.xyz); +} diff --git a/tests/startup_mesh_exec_lineage_check.py b/tests/startup_mesh_exec_lineage_check.py new file mode 100644 index 0000000000..227a46e500 --- /dev/null +++ b/tests/startup_mesh_exec_lineage_check.py @@ -0,0 +1,111 @@ +"""Exec lineage in the mesh-stage translator (mesh2hlsl MeshStage.lineage_*, X2W_MESH_EXEC_LINEAGE). + +A VGPR written from uniform values while exec is E holds one value in every lane of E (the other lanes keep their +old value). The epoch rule forgets that at the first exec write that may widen exec; the compiler's usual shape +restores a SAVED copy of an earlier exec, after which only lanes of E can be active again. Hand-assembled NGG mesh +programs (no cache bytes), RDNA 2 ISA encodings, v5 = the vertex id (different in every lane): + + 0x00 v_cmp_lt_u32 vcc, 3, v5; 0x04 s_and_saveexec_b64 s[26:27], vcc E1 = lanes v5 > 3 (s26 = entry exec) + 0x08 v_mov_b32 v1, 1.0 v1 = 1.0 in every lane of E1 + 0x0c v_cmp_lt_u32 vcc, 7, v5; 0x10 s_and_saveexec_b64 s[18:19], vcc E2 = lanes v5 > 7 (s18 = E1) + 0x14 v_mov_b32 v2, 0; 0x18 s_mov_b64 exec, s[18:19] back to E1 (restore) + 0x1c v_cmp_lt_u32 vcc, 5, v5; 0x20 s_and_b64 exec, vcc, exec E3 = lanes v5 > 5, a subset of E1 + 0x24 v_cmp_lt_f32 vcc, 0, v1; 0x28 s_cbranch_vccz 0x30; 0x2c s_nop 0 vcc = 1 in every active lane + 0x30 s_mov_b64 exec, s[26:27]; then v1 = float(s0), exp pos0 / prim, s_endpgm + +Checks: + subset the program translates: v1 is the same in every lane of E3, so the per-lane vccz branch is the wave's + parent 0x18 restores s[26:27] (the entry exec, a superset of E1) instead: refused ("lane-dependent vcc"), + since lanes outside E1 may be active again and hold another v1 + copy 0x14 overwrites s18 (s_mov_b32 s18, 0) before the restore: refused (the restore no longer names E1) + half 0x14 overwrites only s19, the high half of the saved pair: refused as well +The rule is off by default; this check turns it on (X2W_MESH_EXEC_LINEAGE=1, set before the import). +Negative control: with X2W_MESH_EXEC_LINEAGE=0 (the epoch rule only) `subset` is refused (run in a child). +""" +import os +import struct +import subprocess +import sys + +os.environ.setdefault('X2W_MESH_EXEC_LINEAGE', '1') # the child of the negative control passes 0 + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import root_blob # noqa: E402 + +TAIL = (0x7e020c00, # v_cvt_f32_u32 v1, s0 + 0x7e040280, # v_mov_b32 v2, 0 + 0xb07c1003, # s_movk_i32 m0, 0x1003 + 0xbf900009, # s_sendmsg 0x9 + 0xf80008cf, 0x02020201, # exp pos0 v1, v2, v2, v2 done + 0xf8000941, 0x00000002, # exp prim v2 done + 0xbf810000) # s_endpgm +BODY = [0x7d820a83, # 0x00 v_cmp_lt_u32 vcc, 3, v5 + 0xbe9a246a, # 0x04 s_and_saveexec_b64 s[26:27], vcc + 0x7e0202f2, # 0x08 v_mov_b32 v1, 1.0 + 0x7d820a87, # 0x0c v_cmp_lt_u32 vcc, 7, v5 + 0xbe92246a, # 0x10 s_and_saveexec_b64 s[18:19], vcc + 0x7e040280, # 0x14 v_mov_b32 v2, 0 + 0xbefe0412, # 0x18 s_mov_b64 exec, s[18:19] + 0x7d820a85, # 0x1c v_cmp_lt_u32 vcc, 5, v5 + 0x87fe7e6a, # 0x20 s_and_b64 exec, vcc, exec + 0x7c020280, # 0x24 v_cmp_lt_f32 vcc, 0, v1 + 0xbf860001, # 0x28 s_cbranch_vccz 0x30 + 0xbf800000, # 0x2c s_nop 0 + 0xbefe041a] # 0x30 s_mov_b64 exec, s[26:27] +TEXT = ['v_cmp_lt_u32_e32 vcc_lo, 3, v5', 's_and_saveexec_b64 s[26:27], vcc', 'v_mov_b32_e32 v1, 1.0', + 'v_cmp_lt_u32_e32 vcc_lo, 7, v5', 's_and_saveexec_b64 s[18:19], vcc', 'v_mov_b32_e32 v2, 0', + 's_mov_b64 exec, s[18:19]', 'v_cmp_lt_u32_e32 vcc_lo, 5, v5', 's_and_b64 exec, vcc, exec', + 'v_cmp_lt_f32_e32 vcc_lo, 0, v1', 's_cbranch_vccz label_0x30', 's_nop 0', 's_mov_b64 exec, s[26:27]'] + + +def program(**at): + words = list(BODY) + for off, word in at.items(): + words[int(off[1:], 16) // 4] = word + return struct.pack('<%dI' % (len(words) + len(TAIL)), *(words + list(TAIL))) + + +SUBSET = program() +PARENT = program(x18=0xbefe041a) # 0x18 s_mov_b64 exec, s[26:27] +COPY = program(x14=0xbe920380) # 0x14 s_mov_b32 s18, 0 +HALF = program(x14=0xbe930380) # 0x14 s_mov_b32 s19, 0 + + +def translate(code): + try: + M.MeshPipeline(code, None, root_blob()).hlsl_ms() + return 'ok' + except G.Unsupported as e: + return str(e) + + +def check(): + text = [x[3] for x in G.decode(SUBSET)][:len(TEXT)] + assert text == TEXT, text + assert [x[3] for x in G.decode(PARENT)][6] == 's_mov_b64 exec, s[26:27]' + assert [x[3] for x in G.decode(COPY)][5] == 's_mov_b32 s18, 0' + assert [x[3] for x in G.decode(HALF)][5] == 's_mov_b32 s19, 0' + got = translate(SUBSET) + assert got == 'ok', ('subset', got) + for name, code in (('parent', PARENT), ('copy', COPY), ('half', HALF)): + got = translate(code) + assert 'lane-dependent vcc' in got, (name, got) + return 'subset translates; parent restore, overwritten copy and overwritten high half refused' + + +def main(): + if os.environ.get('X2W_MESH_EXEC_LINEAGE') == '0': # child of the negative control + check() + return + summary = check() + env = dict(os.environ, X2W_MESH_EXEC_LINEAGE='0') + r = subprocess.run([sys.executable, '-B', os.path.abspath(__file__)], env=env, capture_output=True, text=True) + assert r.returncode != 0 and 'AssertionError' in r.stderr, ('negative control passed', r.stdout, r.stderr) + print('mesh exec lineage: %s; X2W_MESH_EXEC_LINEAGE=0 fails (%s)' % (summary, r.stderr.strip().splitlines()[-1][:90])) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_mesh_exec_off_check.py b/tests/startup_mesh_exec_off_check.py new file mode 100644 index 0000000000..e54d7a0f8f --- /dev/null +++ b/tests/startup_mesh_exec_off_check.py @@ -0,0 +1,292 @@ +"""Check the exec-off rule of tools/startup/mesh2hlsl.py (MeshStage.merge_exec_off / exec_off_use): a register that +holds a symbolic value (here a descriptor-table pointer) before a group-uniform execz range and a lane mask written +inside it becomes ('conflict',) at the join; a 64-bit mask op with exec whose lane bit does not depend on it when +the lane's exec bit is 0 may still read it. + +usage: startup_mesh_exec_off_check.py [--write <dir>] + +Hand-assembled gfx1013 NGG programs (no title bytes; encoded field by field, opcode numbers found by decoding with +tools/disasm_rdna2.py, the decoded text compared with the intended text). Per group g: N = 60 * (g & 1) + +40 * ((g >> 1) & 1), T = 20 * (g & 3): g = 0 has no active lane at the branch (the whole group skips the range), +g = 1 and 2 a mixed wave 0 and a wave 1 with no active lane (it runs the range with exec 0 in the translation, +the hardware skips it), g = 3 a full wave 0 and a mixed wave 1. + +Shape (the run programs' lane-mask merge after a divergent if, census class "execz range ... changes sN from desc +to ('conflict',)"): s26 = s16 (table pointer); s[30:31] = exec; exec = v0 < N; execz -> J; +v_cmp_gt_u32_e64 s[26:27] = v0 < T; J: <op> s[26:27], s[26:27], exec; exec = s[30:31]; exec &= s[26:27]; +v1 = 9; (epilogue: exec = all, export v1 as param0.x). + +Hardware meaning (AMD RDNA 2 ISA): V_CMP_*_E64 with an SGPR destination writes the compare bit of each active lane +and 0 for inactive lanes; S_CBRANCH_EXECZ branches when the wave's EXEC is 0; S_NAND_B64 D = ~(S0 & S1), +S_ORN2_B64 D = S0 | ~S1, S_OR_B64 D = S0 | S1, S_AND_B64 D = S0 & S1. A lane with EXEC bit 0 at J gets +nand: 1, orn2: 1 whatever s26 held, so the stale pointer word is never observed. + + NAND (accept): expected v1 = 9.0 iff v0 >= N or v0 >= T, else 5.0 + ORN2 (accept): expected v1 = 9.0 iff v0 >= N or v0 < T, else 5.0 + (Float values: the differential test allows 4 ulp on attribute words, so the integers 5 and 9 would not differ.) + OR (refuse): s_or_b64 s[26:27], s[26:27], exec: a lane off at J would read the pointer word + EXECW (refuse): as NAND with `s_mov_b64 exec, s[30:31]` between J and the nand: the lanes that took the edge + are on again, so their bit of the stale word would matter + LOAD (refuse): s_load_dwordx4 through s[26:27] after J: a real descriptor use of the conflict register + +Checks: each program decodes to its intended text; the accepted ones translate and are refused again with +X2W_MESH_EXECOFF=0 (negative control: the f37ad9f8 rule "execz range ... changes s26 from ptr to ('conflict',)"); +the refused ones are refused with the rule on. --write keeps the programs (<dir>/<name>.bin) for the differential +test (mesh_work/difftest.py <bin> <harness>). +""" +import os +import struct +import subprocess +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 disasm_rdna2 as D # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +# ---- a minimal gfx10 encoder (as tests/startup_mesh_exec_restore_check.py): field layout per format, opcode +# found by decoding ----------------------------------------------------------------------------------------------- +def src(tok): + named = {'vcc_lo': 106, 'vcc_hi': 107, 'm0': 124, 'exec_lo': 126, 'exec_hi': 127} + if tok in named: + return named[tok], None + if tok[0] == 's': + return int(tok[1:]), None + if tok[0] == 'v': + return 256 + int(tok[1:]), None + v = int(tok, 0) + if 0 <= v <= 64: + return 128 + v, None + if -16 <= v < 0: + return 192 - v, None + return 255, v & 0xffffffff + + +def fmt_words(fmt, op, f): + if fmt == 'sop2': + return [(0b10 << 30) | (op << 23) | (f['d'] << 16) | (f['s1'] << 8) | f['s0']] + if fmt == 'sop1': + return [(0x17d << 23) | (f['d'] << 16) | (op << 8) | f['s0']] + if fmt == 'sopc': + return [(0x17e << 23) | (op << 16) | (f['s1'] << 8) | f['s0']] + if fmt == 'sopp': + return [(0x17f << 23) | (op << 16) | (f['imm'] & 0xffff)] + if fmt == 'vop1': + return [(0x3f << 25) | (f['d'] << 17) | (op << 9) | f['s0']] + if fmt == 'vopc': + return [(0x3e << 25) | (op << 17) | ((f['s1'] - 256) << 9) | f['s0']] + if fmt == 'vop3': + return [(0x35 << 26) | (op << 16) | f['d'], f['s0'] | (f['s1'] << 9) | (f.get('s2', 0) << 18)] + if fmt == 'smem': + # gfx10 SMEM: [31:26] 0x3d, [25:18] op, [12:6] sdata, [5:0] sbase / 2; word 1: [20:0] offset, [31:25] soffset + return [(0x3d << 26) | (op << 18) | (f['d'] << 6) | (f['s0'] >> 1), (f['imm'] & 0x1fffff) | (0x7d << 25)] + raise ValueError(fmt) + + +OP_RANGE = {'sop2': 128, 'sop1': 256, 'sopc': 128, 'sopp': 128, 'vop1': 256, 'vopc': 256, 'vop3': 1024, 'smem': 256} +_op_cache = {} + + +def find_op(fmt, mnemonic, fields): + key = (fmt, mnemonic) + if key in _op_cache: + return _op_cache[key] + for op in range(OP_RANGE[fmt]): + words = fmt_words(fmt, op, fields) + code = struct.pack('<%dI' % len(words), *words) + b'\0' * 8 + try: + _, name, _, _ = D.decode_instruction(code, 0) + except Exception: + continue + if name == mnemonic: + _op_cache[key] = op + return op + raise KeyError('%s %s: no opcode decodes to it' % (fmt, mnemonic)) + + +def ins(fmt, mnemonic, **ops): + fields, literal = {}, None + for k, tok in ops.items(): + if k in ('d', 'imm'): + fields[k] = tok if isinstance(tok, int) else src(tok)[0] + continue + code, lit = src(tok) + fields[k] = code + if lit is not None: + literal = lit + words = fmt_words(fmt, find_op(fmt, mnemonic, fields), fields) + return words + ([literal] if literal is not None else []) + + +def exp(target, vals, done=False): + en = sum(1 << i for i, v in enumerate(vals) if v is not None) + w0 = (0x3e << 26) | (int(done) << 11) | (target << 4) | en + w1 = 0 + for i, v in enumerate(vals): + if v is not None: + w1 |= int(v[1:]) << (8 * i) + return [w0, w1] + + +def assemble(items): + off, labels, sized = 0, {}, [] + for text, make in items: + if make is None: + labels[text[:-1]] = off + continue + words = make() if callable(make) else [0] + sized.append((off, text, make, len(words))) + off += 4 * len(words) + out, texts = [], [] + for off, text, make, n in sized: + if callable(make): + words = make() + else: + target = labels[text.split()[1]] + words = ins('sopp', 's_cbranch_' + make if make != 'branch' else 's_branch', imm=(target - off - 4) // 4) + text = '%s label_%#x' % (text.split()[0], target) + out += words + texts.append((off, text)) + return struct.pack('<%dI' % len(out), *out), texts + + +def decoded(code): + off, res = 0, [] + while off + 4 <= len(code): + n, name, asm, _ = D.decode_instruction(code, off) + res.append((off, asm)) + off += n + return res + + +def I(text, fmt, mnemonic, **ops): + return (text, lambda: ins(fmt, mnemonic, **ops)) + + +PROLOGUE = [ + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('v_readfirstlane_b32 s20, v5', 'vop1', 'v_readfirstlane_b32', d=20, s0='v5'), + I('s_lshr_b32 s20, s20, 7', 'sop2', 's_lshr_b32', d=20, s0='s20', s1='7'), + I('s_bfe_u32 s28, s3, 0x40018', 'sop2', 's_bfe_u32', d=28, s0='s3', s1='0x40018'), + I('s_lshl_b32 s29, s28, 6', 'sop2', 's_lshl_b32', d=29, s0='s28', s1='6'), + I('v_mbcnt_lo_u32_b32 v0, -1, s29', 'vop3', 'v_mbcnt_lo_u32_b32', d=0, s0='-1', s1='s29'), + I('v_mbcnt_hi_u32_b32 v0, -1, v0', 'vop3', 'v_mbcnt_hi_u32_b32', d=0, s0='-1', s1='v0'), + I('s_and_b32 s21, s20, 1', 'sop2', 's_and_b32', d=21, s0='s20', s1='1'), + I('s_mul_i32 s21, s21, 60', 'sop2', 's_mul_i32', d=21, s0='s21', s1='60'), + I('s_bfe_u32 s23, s20, 0x10001', 'sop2', 's_bfe_u32', d=23, s0='s20', s1='0x10001'), + I('s_mul_i32 s23, s23, 40', 'sop2', 's_mul_i32', d=23, s0='s23', s1='40'), + I('s_add_u32 s21, s21, s23', 'sop2', 's_add_u32', d=21, s0='s21', s1='s23'), + I('s_and_b32 s22, s20, 3', 'sop2', 's_and_b32', d=22, s0='s20', s1='3'), + I('s_mul_i32 s22, s22, 20', 'sop2', 's_mul_i32', d=22, s0='s22', s1='20'), + I('v_mov_b32_e32 v1, 0x40a00000', 'vop1', 'v_mov_b32_e32', d=1, s0='0x40a00000'), # 5.0 + I('v_mov_b32_e32 v4, 0', 'vop1', 'v_mov_b32_e32', d=4, s0='0'), + # the table pointer (root parameter 0 = user SGPR s16) and its zero high word, as the run programs build it + I('s_mov_b32 s27, 0', 'sop1', 's_mov_b32', d=27, s0='0'), + I('s_mov_b32 s26, s16', 'sop1', 's_mov_b32', d=26, s0='s16'), + # a load through it (its result unused) makes s16 a table for the synthesized root of the differential test + I('s_load_dwordx4 s[32:35], s[26:27], 0x0', 'smem', 's_load_dwordx4', d=32, s0='s26', imm=0), + I('s_mov_b64 s[30:31], exec', 'sop1', 's_mov_b64', d=30, s0='exec_lo'), + I('v_cmpx_gt_u32_e32 s21, v0', 'vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0'), + ('s_cbranch_execz J', 'execz'), + I('v_cmp_gt_u32_e64 s26, s22, v0', 'vop3', 'v_cmp_gt_u32_e64', d=26, s0='s22', s1='v0'), + ('J:', None), +] +EPILOGUE = [ + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('s_mov_b32 m0, 0x80080', 'sop1', 's_mov_b32', d=124, s0='0x80080'), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + I('v_cvt_f32_u32_e32 v2, v0', 'vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0'), + I('v_mov_b32_e32 v3, 0', 'vop1', 'v_mov_b32_e32', d=3, s0='0'), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v1, v0, v4, v0', lambda: exp(32, ['v1', 'v0', 'v4', 'v0'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] +RESTORE = I('s_mov_b64 exec, s[30:31]', 'sop1', 's_mov_b64', d=126, s0='s30') +TAIL = [RESTORE, I('s_and_b64 exec, s[26:27], exec', 'sop2', 's_and_b64', d=126, s0='s26', s1='exec_lo'), + I('v_mov_b32_e32 v1, 0x41100000', 'vop1', 'v_mov_b32_e32', d=1, s0='0x41100000')] # 9.0 + + +def merge_op(mnemonic): + return I('%s s[26:27], s[26:27], exec' % mnemonic, 'sop2', mnemonic, d=26, s0='s26', s1='exec_lo') + + +PROGRAMS = { + 'nand': (True, PROLOGUE + [merge_op('s_nand_b64')] + TAIL + EPILOGUE), + 'orn2': (True, PROLOGUE + [merge_op('s_orn2_b64')] + TAIL + EPILOGUE), + 'or': (False, PROLOGUE + [merge_op('s_or_b64')] + TAIL + EPILOGUE), + 'execw': (False, PROLOGUE + [RESTORE, merge_op('s_nand_b64')] + TAIL + EPILOGUE), + 'load': (False, PROLOGUE + [I('s_load_dwordx4 s[36:39], s[26:27], 0x0', 'smem', 's_load_dwordx4', d=36, + s0='s26', imm=0)] + [merge_op('s_nand_b64')] + TAIL + EPILOGUE), +} +REFUSAL = {'or': 'numeric use of s26 holding conflict', 'execw': 'numeric use of s26 holding conflict', + 'load': 's_load through s26 holding (\'conflict\',)'} + + +def translate(path, env): + """Run the translator in a child process (its switches are read at import): HLSL or the refusal text. Root: + parameter 0 a descriptor table (user SGPR s16), parameter 1 one root constant (s17).""" + child = ('import sys; sys.path[:0] = [%r, %r]\n' + 'import gfx2hlsl as G, mesh2hlsl as M\n' + 'code = open(sys.argv[1], "rb").read()\n' + 'try:\n' + ' p = M.MeshPipeline(code, None, M.synth_layout({16}, set(), {16, 17}, 16), user_sgpr=16)\n' + ' sys.stdout.write("OK\\n" + p.hlsl_ms())\n' + 'except G.Unsupported as e:\n' + ' sys.stdout.write("REFUSED %%s\\n" %% e)\n' + % (os.path.join(HERE, '..', 'tools'), os.path.join(HERE, '..', 'tools', 'startup'))) + e = dict(os.environ) + e.pop('X2W_MESH_EXECOFF', None) + e.update(env) + r = subprocess.run([sys.executable, '-B', '-c', child, path], capture_output=True, text=True, env=e) + if r.returncode: + return 'CRASH ' + (r.stderr.strip().splitlines() or ['?'])[-1] + return r.stdout + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_exec_off') + os.makedirs(out_dir, exist_ok=True) + refused_old = "REFUSED execz range 0x" + for name, (accept, items) in PROGRAMS.items(): + code, texts = assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = translate(path, {}) + if accept: + check('%s: translates with the rule on' % name, on.startswith('OK'), on[:300]) + formula = {'nand': 's26 = (~(s26 & exec)) & 1;', 'orn2': 's26 = (s26 | ~exec) & 1;'}[name] + check('%s: the merge reads the run-time s26 (%s)' % (name, formula), formula in on, + [l.strip() for l in on.splitlines() if 's26 =' in l][:4]) + off = translate(path, {'X2W_MESH_EXECOFF': '0'}) + check('%s: negative control X2W_MESH_EXECOFF=0 refuses again' % name, + off.startswith(refused_old) and "changes s26 from ptr to ('conflict',)" in off, off[:200]) + else: + check('%s: still refused with the rule on (%s)' % (name, REFUSAL[name]), + on.startswith('REFUSED ' + REFUSAL[name]), on[:200]) + print('programs written to %s (difftest: python -B difftest.py <dir>/nand.bin <harness> --groups 4 --seed 1)' + % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_exec_restore_check.py b/tests/startup_mesh_exec_restore_check.py new file mode 100644 index 0000000000..a68baa7c9c --- /dev/null +++ b/tests/startup_mesh_exec_restore_check.py @@ -0,0 +1,282 @@ +"""Check the exec-restore rule of tools/startup/mesh2hlsl.py for per-lane skipped ranges (MeshStage.exec_copies_at, +MeshStage.skipped_scalars): inside a range skipped per lane (s_cbranch_execz / vccz), `s_mov_b64 exec, sX` is +accepted when sX is proven to hold exactly the exec of the branch (on every path to it), or a copy of such a pair. + +usage: startup_mesh_exec_restore_check.py [--write <dir>] + +Hand-assembled gfx1013 NGG programs (no title bytes; encoded field by field, opcode numbers found by decoding with +tools/disasm_rdna2.py and the decoded text compared with the intended text). Per group g: N = 40 + 60 * (g & 1) +(wave 1 has no lane with v0 < N when N = 40), T = 20 * (g & 3), s23 = 10. + +Hardware meaning (AMD RDNA 2 ISA: V_CMPX writes EXEC = EXEC & compare; S_MOV_B64 EXEC, S writes all 64 bits; +S_CBRANCH_EXECZ / VCCZ branch on the whole wave's EXEC / VCC). Restoring a pair that equals EXEC at the branch +turns on exactly the lanes that entered the range; a lane that was off at the branch stays off, which is what the +one-lane model does when that lane skips the range. + + RESTORE (accept): exec = v0 < N; s[30:31] = exec; execz -> AFTER; exec &= v0 < T; v1 = 9; + exec = s[30:31]; v4 = 7. expected per lane: v1 = 9 if v0 < min(N, T) else 5; v4 = 7 if v0 < N else 0 + SHUFFLE (accept): as RESTORE, the saved pair moved to s[34:35] inside the range and restored from there. + VCCZ (accept): exec = v0 < N; s[30:31] = exec; vcc = (30 < T) & exec (uniform); vccz -> AFTER; exec &= v0 < s23; + v1 = 9; exec = s[30:31]; v4 = 7. expected: v1 = 9 if T > 30 and v0 < min(N, 10) else 5; v4 = 7 if T > 30 + and v0 < N else 0 + WIDER (refuse): s[30:31] = exec (all lanes); exec = v0 < N; execz; exec = s[30:31] would turn on lanes v0 >= N + that the one-lane model left at AFTER. + ONEPATH (refuse): s[30:31] = exec only when s22 != 0 (a uniform branch around the copy); the other path reaches + the execz branch with s[30:31] unrelated to exec. + CLOBBER (refuse): s[30:31] = exec, then v_cmp_gt_u32_e64 s29 (a wave64 mask: writes s[29:30]) before the branch. + +Checks: each program decodes to its intended text; the accepted ones translate with the restore of the saved pair +(`exec = (s30) & 1` / s34) and are refused again with X2W_MESH_EXEC_COPIES=0 (negative control: the f37ad9f8 rule, +"exec written by s_mov_b64 inside the per-lane skipped range"); the refused ones are refused with the rule on. +--write keeps the programs (<dir>/<name>.bin) for the differential test (mesh_work/difftest.py <bin> <harness>). +""" +import os +import struct +import subprocess +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 disasm_rdna2 as D # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +# ---- a minimal gfx10 encoder (as tests/startup_mesh_lane_scc_check.py): field layout per format, opcode found by +# decoding -------------------------------------------------------------------------------------------------------- +def src(tok): + named = {'vcc_lo': 106, 'vcc_hi': 107, 'm0': 124, 'exec_lo': 126, 'exec_hi': 127} + if tok in named: + return named[tok], None + if tok[0] == 's': + return int(tok[1:]), None + if tok[0] == 'v': + return 256 + int(tok[1:]), None + v = int(tok, 0) + if 0 <= v <= 64: + return 128 + v, None + if -16 <= v < 0: + return 192 - v, None + return 255, v & 0xffffffff + + +def fmt_words(fmt, op, f): + if fmt == 'sop2': + return [(0b10 << 30) | (op << 23) | (f['d'] << 16) | (f['s1'] << 8) | f['s0']] + if fmt == 'sop1': + return [(0x17d << 23) | (f['d'] << 16) | (op << 8) | f['s0']] + if fmt == 'sopc': + return [(0x17e << 23) | (op << 16) | (f['s1'] << 8) | f['s0']] + if fmt == 'sopp': + return [(0x17f << 23) | (op << 16) | (f['imm'] & 0xffff)] + if fmt == 'vop1': + return [(0x3f << 25) | (f['d'] << 17) | (op << 9) | f['s0']] + if fmt == 'vopc': + return [(0x3e << 25) | (op << 17) | ((f['s1'] - 256) << 9) | f['s0']] + if fmt == 'vop3': + return [(0x35 << 26) | (op << 16) | f['d'], f['s0'] | (f['s1'] << 9) | (f.get('s2', 0) << 18)] + raise ValueError(fmt) + + +OP_RANGE = {'sop2': 128, 'sop1': 256, 'sopc': 128, 'sopp': 128, 'vop1': 256, 'vopc': 256, 'vop3': 1024} +_op_cache = {} + + +def find_op(fmt, mnemonic, fields): + key = (fmt, mnemonic) + if key in _op_cache: + return _op_cache[key] + for op in range(OP_RANGE[fmt]): + words = fmt_words(fmt, op, fields) + code = struct.pack('<%dI' % len(words), *words) + b'\0' * 8 + try: + _, name, _, _ = D.decode_instruction(code, 0) + except Exception: + continue + if name == mnemonic: + _op_cache[key] = op + return op + raise KeyError('%s %s: no opcode decodes to it' % (fmt, mnemonic)) + + +def ins(fmt, mnemonic, **ops): + fields, literal = {}, None + for k, tok in ops.items(): + if k in ('d', 'imm'): + fields[k] = tok if isinstance(tok, int) else src(tok)[0] + continue + code, lit = src(tok) + fields[k] = code + if lit is not None: + literal = lit + words = fmt_words(fmt, find_op(fmt, mnemonic, fields), fields) + return words + ([literal] if literal is not None else []) + + +def exp(target, vals, done=False): + en = sum(1 << i for i, v in enumerate(vals) if v is not None) + w0 = (0x3e << 26) | (int(done) << 11) | (target << 4) | en + w1 = 0 + for i, v in enumerate(vals): + if v is not None: + w1 |= int(v[1:]) << (8 * i) + return [w0, w1] + + +def assemble(items): + off, labels, sized = 0, {}, [] + for text, make in items: + if make is None: + labels[text[:-1]] = off + continue + words = make() if callable(make) else [0] + sized.append((off, text, make, len(words))) + off += 4 * len(words) + out, texts = [], [] + for off, text, make, n in sized: + if callable(make): + words = make() + else: + target = labels[text.split()[1]] + words = ins('sopp', 's_cbranch_' + make if make != 'branch' else 's_branch', imm=(target - off - 4) // 4) + text = '%s label_%#x' % (text.split()[0], target) + out += words + texts.append((off, text)) + return struct.pack('<%dI' % len(out), *out), texts + + +def decoded(code): + off, res = 0, [] + while off + 4 <= len(code): + n, name, asm, _ = D.decode_instruction(code, off) + res.append((off, asm)) + off += n + return res + + +def I(text, fmt, mnemonic, **ops): + return (text, lambda: ins(fmt, mnemonic, **ops)) + + +PROLOGUE = [ + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('v_readfirstlane_b32 s20, v5', 'vop1', 'v_readfirstlane_b32', d=20, s0='v5'), + I('s_lshr_b32 s20, s20, 7', 'sop2', 's_lshr_b32', d=20, s0='s20', s1='7'), + I('s_bfe_u32 s28, s3, 0x40018', 'sop2', 's_bfe_u32', d=28, s0='s3', s1='0x40018'), + I('s_lshl_b32 s29, s28, 6', 'sop2', 's_lshl_b32', d=29, s0='s28', s1='6'), + I('v_mbcnt_lo_u32_b32 v0, -1, s29', 'vop3', 'v_mbcnt_lo_u32_b32', d=0, s0='-1', s1='s29'), + I('v_mbcnt_hi_u32_b32 v0, -1, v0', 'vop3', 'v_mbcnt_hi_u32_b32', d=0, s0='-1', s1='v0'), + I('s_and_b32 s21, s20, 1', 'sop2', 's_and_b32', d=21, s0='s20', s1='1'), + I('s_mul_i32 s21, s21, 60', 'sop2', 's_mul_i32', d=21, s0='s21', s1='60'), + I('s_add_u32 s21, s21, 40', 'sop2', 's_add_u32', d=21, s0='s21', s1='40'), + I('s_and_b32 s22, s20, 3', 'sop2', 's_and_b32', d=22, s0='s20', s1='3'), + I('s_mul_i32 s22, s22, 20', 'sop2', 's_mul_i32', d=22, s0='s22', s1='20'), + I('s_mov_b32 s23, 10', 'sop1', 's_mov_b32', d=23, s0='10'), + I('v_mov_b32_e32 v1, 5', 'vop1', 'v_mov_b32_e32', d=1, s0='5'), + I('v_mov_b32_e32 v4, 0', 'vop1', 'v_mov_b32_e32', d=4, s0='0'), +] +EPILOGUE = [ + ('AFTER:', None), + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('s_mov_b32 m0, 0x80080', 'sop1', 's_mov_b32', d=124, s0='0x80080'), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + I('v_cvt_f32_u32_e32 v2, v0', 'vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0'), + I('v_mov_b32_e32 v3, 0', 'vop1', 'v_mov_b32_e32', d=3, s0='0'), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v1, v0, v4, v0', lambda: exp(32, ['v1', 'v0', 'v4', 'v0'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] +CMPX_N = I('v_cmpx_gt_u32_e32 s21, v0', 'vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0') +CMPX_T = I('v_cmpx_gt_u32_e32 s22, v0', 'vopc', 'v_cmpx_gt_u32_e32', s0='s22', s1='v0') +SAVE = I('s_mov_b64 s[30:31], exec', 'sop1', 's_mov_b64', d=30, s0='exec_lo') +RESTORE = I('s_mov_b64 exec, s[30:31]', 'sop1', 's_mov_b64', d=126, s0='s30') +V1_9 = I('v_mov_b32_e32 v1, 9', 'vop1', 'v_mov_b32_e32', d=1, s0='9') +V4_7 = I('v_mov_b32_e32 v4, 7', 'vop1', 'v_mov_b32_e32', d=4, s0='7') + +PROGRAMS = { + 'restore': (True, PROLOGUE + [CMPX_N, SAVE, ('s_cbranch_execz AFTER', 'execz'), CMPX_T, V1_9, RESTORE, V4_7] + + EPILOGUE), + 'shuffle': (True, PROLOGUE + [CMPX_N, SAVE, ('s_cbranch_execz AFTER', 'execz'), + I('s_mov_b64 s[34:35], s[30:31]', 'sop1', 's_mov_b64', d=34, s0='s30'), + I('s_mov_b32 s30, 0', 'sop1', 's_mov_b32', d=30, s0='0'), + CMPX_T, V1_9, + I('s_mov_b64 exec, s[34:35]', 'sop1', 's_mov_b64', d=126, s0='s34'), V4_7] + + EPILOGUE), + 'vccz': (True, PROLOGUE + [CMPX_N, SAVE, + I('v_mov_b32_e32 v6, s22', 'vop1', 'v_mov_b32_e32', d=6, s0='s22'), + I('v_cmp_lt_u32_e32 vcc_lo, 30, v6', 'vopc', 'v_cmp_lt_u32_e32', s0='30', s1='v6'), + ('s_cbranch_vccz AFTER', 'vccz'), + I('v_cmpx_gt_u32_e32 s23, v0', 'vopc', 'v_cmpx_gt_u32_e32', s0='s23', s1='v0'), + V1_9, RESTORE, V4_7] + EPILOGUE), + 'wider': (False, PROLOGUE + [SAVE, CMPX_N, ('s_cbranch_execz AFTER', 'execz'), RESTORE, V4_7] + EPILOGUE), + 'onepath': (False, PROLOGUE + [CMPX_N, I('s_cmp_eq_u32 s22, 0', 'sopc', 's_cmp_eq_u32', s0='s22', s1='0'), + ('s_cbranch_scc1 J', 'scc1'), SAVE, ('J:', None), + ('s_cbranch_execz AFTER', 'execz'), CMPX_T, V1_9, RESTORE, V4_7] + EPILOGUE), + 'clobber': (False, PROLOGUE + [CMPX_N, SAVE, + I('v_cmp_gt_u32_e64 s29, s22, v0', 'vop3', 'v_cmp_gt_u32_e64', d=29, s0='s22', s1='v0'), + ('s_cbranch_execz AFTER', 'execz'), CMPX_T, V1_9, RESTORE, V4_7] + EPILOGUE), +} + + +def translate(path, env): + """Run the translator in a child process (its switches are read at import): HLSL or the refusal text.""" + child = ('import sys; sys.path[:0] = [%r, %r]\n' + 'import gfx2hlsl as G, mesh2hlsl as M\n' + 'code = open(sys.argv[1], "rb").read()\n' + 'try:\n' + ' p = M.MeshPipeline(code, None, M.synth_root(code), user_sgpr=16)\n' + ' sys.stdout.write("OK\\n" + p.hlsl_ms())\n' + 'except G.Unsupported as e:\n' + ' sys.stdout.write("REFUSED %%s\\n" %% e)\n' + % (os.path.join(HERE, '..', 'tools'), os.path.join(HERE, '..', 'tools', 'startup'))) + e = dict(os.environ) + e.pop('X2W_MESH_EXEC_COPIES', None) + e.update(env) + r = subprocess.run([sys.executable, '-B', '-c', child, path], capture_output=True, text=True, env=e) + if r.returncode: + return 'CRASH ' + (r.stderr.strip().splitlines() or ['?'])[-1] + return r.stdout + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_exec_restore') + os.makedirs(out_dir, exist_ok=True) + refused_old = 'REFUSED exec written by s_mov_b64 inside the per-lane skipped range' + for name, (accept, items) in PROGRAMS.items(): + code, texts = assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = translate(path, {}) + if accept: + reg = 's34' if name == 'shuffle' else 's30' + check('%s: translates with the rule on' % name, on.startswith('OK'), on[:300]) + check('%s: exec restored from the saved pair %s' % (name, reg), 'exec = (%s) & 1;' % reg in on, '') + off = translate(path, {'X2W_MESH_EXEC_COPIES': '0'}) + check('%s: negative control X2W_MESH_EXEC_COPIES=0 refuses again' % name, off.startswith(refused_old), off[:200]) + else: + check('%s: still refused with the rule on' % name, on.startswith(refused_old), on[:200]) + print('programs written to %s (difftest: python -B difftest.py <dir>/restore.bin <harness> --groups 4 --seed 1)' + % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_exec_walk_check.py b/tests/startup_mesh_exec_walk_check.py new file mode 100644 index 0000000000..f56069691c --- /dev/null +++ b/tests/startup_mesh_exec_walk_check.py @@ -0,0 +1,126 @@ +"""Check the path-aware exec walk of tools/startup/mesh2hlsl.py (MeshStage.exec_walk, with exec_copies_at tracking +32-bit halves): inside a per-lane skipped range, exec may be restored from a pair that is a copy of exec at the +branch on EVERY path to the restore, and from nothing else. + +usage: startup_mesh_exec_walk_check.py [--write <dir>] + +Hand-assembled gfx1013 NGG programs (no title bytes), built with the encoder of tests/startup_mesh_exec_restore_check.py. +Prologue as there (N = 40 + 60 * (g & 1), T = 20 * (g & 3), s22 = T); epilogue exports (v1, v0, v4, v0) as param0. +Every program: exec = v0 < N; s[30:31] = exec; execz -> AFTER; ...; restore; v4 = 7. + + CLOBBERSKIP (accept): s[34:35] = s[30:31]; scc1 (T == 0) -> R; s[34:35] = 0; exec &= v0 < T; v1 = 9; + s[34:35] = s[30:31]; R: exec = s[34:35]. On both paths to R the pair is a copy of exec at the branch; + a walk in program order sees the `s[34:35] = 0` before R. expected: v1 = 9 if v0 < min(N, T) and T != 0 + else 5; v4 = 7 if v0 < N else 0. + HALVES (accept): s34 = s30; s35 = s31 (two 32-bit copies); exec &= v0 < T; v1 = 9; exec = s[34:35]. + expected as CLOBBERSKIP with T != 0. + ONEPATH (refuse): as CLOBBERSKIP without the second copy: on the fall-through path s[34:35] = 0 reaches R. + SWAPPED (refuse): s34 = s31; s35 = s30 (halves crossed); exec &= v0 < T; exec = s[34:35]. + MIXED (refuse): s34 = s30; s35 = s22 (the high half is not a copy of exec); exec = s[34:35]. + XORSWAP64 (accept): s[34:35] = (T, 0); the register allocator's XOR swap of s[30:31] and s[34:35] + (three s_xor_b64); exec &= v0 < T; v1 = 9; exec = s[34:35]. expected as HALVES. + XORSWAP32 (accept): as XORSWAP64 with two s_xor_b32 swaps (s30 / s34 with a v_mov between the xors, then + s31 / s35). + XORWRONG (refuse): the XORSWAP64 swap, then exec = s[30:31] (the side that now holds the data (T, 0)). + XORBROKEN (refuse): s35 = 1 between the first and second s_xor_b64: s35 ends as exec_hi ^ 1, no exec copy. + +MEASURED: at 8fadd259 (before the walk commit) HALVES is refused ("exec written by s_mov_b64"); the other four +already behave as here (CLOBBERSKIP is accepted by the c16dae0c rule too). Before the XOR swap commit XORSWAP64 +and XORSWAP32 are refused ("exec written by s_mov_b64"); XORWRONG and XORBROKEN are refused with and without it. + +Checks: decode; CLOBBERSKIP / HALVES translate; with X2W_MESH_EXEC_COPIES=0 (negative control) CLOBBERSKIP is refused; +XORSWAP64 / XORSWAP32 translate; ONEPATH / SWAPPED / MIXED / XORWRONG / XORBROKEN are refused ("exec written"). --write keeps the programs for mesh_work/difftest.py. +""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 +from startup_mesh_exec_restore_check import I # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +def MOV32(d, s): + return I('s_mov_b32 s%d, %s' % (d, s), 'sop1', 's_mov_b32', d=d, s0=s) + + +def XOR(width, d, s0, s1): + """s_xor_b32 / s_xor_b64 on SGPRs (bases d, s0, s1).""" + t = (lambda r: 's%d' % r) if width == 32 else (lambda r: 's[%d:%d]' % (r, r + 1)) + return I('s_xor_b%d %s, %s, %s' % (width, t(d), t(s0), t(s1)), 'sop2', 's_xor_b%d' % width, d=d, s0='s%d' % s0, + s1='s%d' % s1) + + +def SWAP(width, a, b): + return [XOR(width, a, a, b), XOR(width, b, a, b), XOR(width, a, a, b)] + + +COPY34 = I('s_mov_b64 s[34:35], s[30:31]', 'sop1', 's_mov_b64', d=34, s0='s30') +CLEAR34 = I('s_mov_b64 s[34:35], 0', 'sop1', 's_mov_b64', d=34, s0='0') +REST34 = I('s_mov_b64 exec, s[34:35]', 'sop1', 's_mov_b64', d=126, s0='s34') +CMP_T0 = I('s_cmp_eq_u32 s22, 0', 'sopc', 's_cmp_eq_u32', s0='s22', s1='0') +HEAD = E.PROLOGUE + [E.CMPX_N, E.SAVE, ('s_cbranch_execz AFTER', 'execz')] +TAIL = [E.V4_7] + E.EPILOGUE +REFUSE = 'exec written' +PROGRAMS = { + 'clobberskip': ('ok', HEAD + [COPY34, CMP_T0, ('s_cbranch_scc1 R', 'scc1'), CLEAR34, E.CMPX_T, E.V1_9, COPY34, + ('R:', None), REST34] + TAIL), + 'halves': ('ok', HEAD + [MOV32(34, 's30'), MOV32(35, 's31'), E.CMPX_T, E.V1_9, REST34] + TAIL), + 'onepath': (REFUSE, HEAD + [COPY34, CMP_T0, ('s_cbranch_scc1 R', 'scc1'), CLEAR34, E.CMPX_T, E.V1_9, + ('R:', None), REST34] + TAIL), + 'swapped': (REFUSE, HEAD + [MOV32(34, 's31'), MOV32(35, 's30'), E.CMPX_T, E.V1_9, REST34] + TAIL), + 'mixed': (REFUSE, HEAD + [MOV32(34, 's30'), MOV32(35, 's22'), E.CMPX_T, E.V1_9, REST34] + TAIL), + # XOR swaps: s[34:35] = (T, 0) is data; the swap moves the exec copy from s[30:31] into s[34:35] + 'xorswap64': ('ok', HEAD + [MOV32(34, 's22'), MOV32(35, '0')] + SWAP(64, 30, 34) + + [E.CMPX_T, E.V1_9, REST34] + TAIL), + 'xorswap32': ('ok', HEAD + [MOV32(34, 's22'), MOV32(35, '0'), XOR(32, 30, 30, 34), E.V1_9, + XOR(32, 34, 30, 34), XOR(32, 30, 30, 34)] + SWAP(32, 31, 35) + + [E.CMPX_T, E.V1_9, REST34] + TAIL), + 'xorwrong': (REFUSE, HEAD + [MOV32(34, 's22'), MOV32(35, '0')] + SWAP(64, 30, 34) + + [E.CMPX_T, E.V1_9, I('s_mov_b64 exec, s[30:31]', 'sop1', 's_mov_b64', d=126, s0='s30')] + TAIL), + 'xorbroken': (REFUSE, HEAD + [MOV32(34, 's22'), MOV32(35, '0'), XOR(64, 30, 30, 34), MOV32(35, '1'), + XOR(64, 34, 30, 34), XOR(64, 30, 30, 34), E.CMPX_T, E.V1_9, REST34] + TAIL), +} + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_exec_walk') + os.makedirs(out_dir, exist_ok=True) + for name, (want, items) in PROGRAMS.items(): + code, texts = E.assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = E.translate(path, {}) + if want == 'ok': + check('%s: translates' % name, on.startswith('OK'), on[:300]) + if name == 'clobberskip': + off = E.translate(path, {'X2W_MESH_EXEC_COPIES': '0'}) + check('clobberskip: negative control X2W_MESH_EXEC_COPIES=0 refuses', off.startswith('REFUSED'), + off[:300]) + else: + check('%s: refused (%s)' % (name, want), on.startswith('REFUSED') and want in on.splitlines()[0], + on[:200]) + print('programs written to %s' % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_first_lane_check.py b/tests/startup_mesh_first_lane_check.py new file mode 100644 index 0000000000..d28cd58741 --- /dev/null +++ b/tests/startup_mesh_first_lane_check.py @@ -0,0 +1,98 @@ +"""Check the first-active-lane rule of tools/startup/mesh2hlsl.py (MeshStage.first_active_broadcast, NeedGroupRange): +v_readfirstlane_b32 of a lane-dependent VGPR under a partial exec reads the wave's lowest ACTIVE lane. + +usage: startup_mesh_first_lane_check.py [--write <dir>] + +Hand-assembled gfx1013 NGG programs (no title bytes), built with the encoder of tests/startup_mesh_exec_restore_check.py. +Prologue as there (T = 20 * (g & 3) in s22, N = 40 + 60 * (g & 1) in s21, v1 = 5, v4 = 0; v0 = the thread's index in +the group, 0..127); the epilogue sets exec = -1 and exports (v1, v0, v4, v0) as param0. + +Hardware meaning (RDNA 2 ISA V_READFIRSTLANE_B32: the value of the lowest lane whose EXEC bit is set; V_CMPX writes +EXEC = EXEC & compare; S_CBRANCH_EXECZ is taken by a wave whose EXEC is 0): + PARTIAL (accept): exec = (T <= v0); v7 = 2 * v0; s24 = readfirstlane(v7); v1 = s24. + expected: wave 0: active lanes v0 >= T, first = T, v1 = 2T; wave 1: first = lane 0 (v0 = 64), v1 = 128; + v1 = 5 in the inactive lanes. + RANGE (accept): exec = (v0 < N); execz -> AFTER; exec &= (T <= v0); v7 = 2 * v0; s24 = readfirstlane(v7); v1 = s24. + The read is inside a per-lane execz range: the range is run by the whole group (NeedGroupRange). + expected: active lanes T <= v0 < N; wave 0: v1 = 2T; wave 1 (v0 >= 64): v1 = 128 when N = 100, + the wave skips the range when N = 40; else 5. + LOOP (refuse): as PARTIAL with the read inside a two-trip loop (s_cbranch_scc1 back): a group barrier in a loop + is not reached the same number of times by every thread when the waves' trip counts differ (the + waterfall form is mesh4's lowering). + VCCZ (refuse): exec = (v0 < N); vcc = (30 < T) (uniform over the active lanes); vccz -> AFTER; then as RANGE: + only execz ranges are run by the whole group. + +Checks: decode; PARTIAL / RANGE translate with x2w_rfirst; negative control X2W_MESH_RFL_FIRST=0 refuses both +("lanes off"); LOOP and VCCZ refused. --write keeps the programs for mesh_work/difftest.py. +""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 +from startup_mesh_exec_restore_check import I # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +CMPX_LE_T = I('v_cmpx_le_u32_e32 s22, v0', 'vopc', 'v_cmpx_le_u32_e32', s0='s22', s1='v0') +V7 = I('v_lshlrev_b32_e64 v7, 1, v0', 'vop3', 'v_lshlrev_b32_e64', d=7, s0='1', s1='v0') +RFL = I('v_readfirstlane_b32 s24, v7', 'vop1', 'v_readfirstlane_b32', d=24, s0='v7') +V1 = I('v_mov_b32_e32 v1, s24', 'vop1', 'v_mov_b32_e32', d=1, s0='s24') +P, EP = E.PROLOGUE, E.EPILOGUE +PROGRAMS = { + 'rflpartial': ('ok', P + [CMPX_LE_T, V7, RFL, V1] + EP), + 'rflrange': ('ok', P + [E.CMPX_N, ('s_cbranch_execz AFTER', 'execz'), CMPX_LE_T, V7, RFL, V1] + EP), + 'rflloop': ('lanes off inside a loop', P + [CMPX_LE_T, I('s_mov_b32 s30, 0', 'sop1', 's_mov_b32', d=30, s0='0'), ('H:', None), + V7, RFL, I('s_add_u32 s30, s30, 1', 'sop2', 's_add_u32', d=30, s0='s30', s1='1'), + I('s_cmp_lt_u32 s30, 2', 'sopc', 's_cmp_lt_u32', s0='s30', s1='2'), + ('s_cbranch_scc1 H', 'scc1'), V1] + EP), + 'rflvccz': ('lanes off', P + [E.CMPX_N, I('v_mov_b32_e32 v6, s22', 'vop1', 'v_mov_b32_e32', d=6, s0='s22'), + I('v_cmp_lt_u32_e32 vcc_lo, 30, v6', 'vopc', 'v_cmp_lt_u32_e32', s0='30', s1='v6'), + ('s_cbranch_vccz AFTER', 'vccz'), CMPX_LE_T, V7, RFL, V1] + EP), +} + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_first_lane') + os.makedirs(out_dir, exist_ok=True) + for name, (want, items) in PROGRAMS.items(): + code, texts = E.assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = E.translate(path, {}) + if want == 'ok': + check('%s: translates with the first-active-lane read' % name, + on.startswith('OK') and 's24 = x2w_rfirst(0u, wbase);' in on and 'x2w_rfe[0][tid] = exec & 1u;' in on, + on[:3000]) + if name == 'rflrange': + check('rflrange: the execz range is run by the group (x2w_any publish)', 'x2w_any[0][wave] = 1u' in on, + on[:3000]) + off = E.translate(path, {'X2W_MESH_RFL_FIRST': '0'}) + check('%s: negative control X2W_MESH_RFL_FIRST=0 refuses (lanes off)' % name, + off.startswith('REFUSED') and 'lanes off' in off.splitlines()[0], off[:200]) + else: + check('%s: refused (%s)' % (name, want), on.startswith('REFUSED') and want in on.splitlines()[0], on[:200]) + print('programs written to %s' % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_heap_copy_check.py b/tests/startup_mesh_heap_copy_check.py new file mode 100644 index 0000000000..97b2688d5d --- /dev/null +++ b/tests/startup_mesh_heap_copy_check.py @@ -0,0 +1,26 @@ +from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools/startup')) +import mesh2hlsl as M + + +def proof(change=None): + assembly = ['s_nop 0', 's_load_dwordx8 s[88:95], s[12:13], s22', + 's_mov_b64 s[70:71], s[90:91]', 's_mov_b64 s[68:69], s[88:89]', + 's_mov_b64 s[72:73], s[92:93]', 's_mov_b64 s[74:75], s[94:95]', + 's_nop 0', 'image_load v0, v1, s[68:75] dmask:0x1 dim:SQ_RSRC_IMG_1D'] + if change: + assembly[change[0]] = change[1] + stage = M.MeshStage.__new__(M.MeshStage) + stage.ins = [(4*i,4,s.split()[0],s) for i,s in enumerate(assembly)] + stage.pc = 28 + stage._descriptor_loads = {4: 3} + return stage.copied_heap_descriptor(('s',68,75)) + + +if __name__ == '__main__': + assert proof() == (('heapdyn',3),0) + assert proof((6,'s_and_b32 s74, s74, 0xff')) is None + assert proof((4,'s_mov_b64 s[72:73], s[90:91]')) is None + assert proof((0,'s_cbranch_scc0 label_0xc')) is None + print('PASS: exact copied descriptor; edits, reordered words and alternate entries rejected') diff --git a/tests/startup_mesh_heap_sampler_check.py b/tests/startup_mesh_heap_sampler_check.py new file mode 100644 index 0000000000..988a70c2bc --- /dev/null +++ b/tests/startup_mesh_heap_sampler_check.py @@ -0,0 +1,187 @@ +"""Check the constant sampler-heap entry of tools/startup/mesh2hlsl.py (const_heap_sampler, MeshStage.heap_sampler, +MeshPixelStage): four sampler words loaded from the sampler heap at a constant byte offset become entry offset / 16 +of the table the draw path binds for run-time offsets (`SamplerState qh[2048] : register(s0, space1)`, manifest +`smpheap 2048 1 fallback 2047`), opt-in with X2W_SAMPLER_HEAP=1 like that form. + +usage: startup_mesh_heap_sampler_check.py + +Hand-assembled gfx1013 NGG mesh programs (no title bytes; encoded field by field, opcode numbers found by decoding +with tools/disasm_rdna2.py, the decoded text compared with the intended text). Root: parameter 0 a descriptor table, +parameter 1 one root constant, flag 0x800 (SAMPLER_HEAP_DIRECTLY_INDEXED): mesh user SGPRs s16 table, s17 constant, +s18 sampler heap. The run programs read their sampler heap the same way (`s_load_dwordx4 s[..], s[24:25], 0x410`). +Pixel stage of the pair: the source-built fixture of tests/startup_sampler_heap_check.py (CONST_WORDS: llvm-mc +words of `s_load_dwordx4 s[24:27], s[10:11], 0x10` + image_sample), whose s10 is the same sampler heap. + +Hardware meaning (AMD RDNA 2 ISA, S_LOAD_DWORDX4 / IMAGE_SAMPLE): the sampler state is the four dwords at +heap base + offset; the stand-in's table entry n holds the title's heap entry at byte 16 * n (gfx2hlsl contract). + + CONST (accept): offset 0x410 -> qh[65u] + UNALIGNED (accept): offset 0x418 -> qh[2047u] (the reserved fallback entry, as x2w_sampler_entry does) + PAIR (accept): CONST mesh stage + the fixture pixel stage (offset 0x10) -> qh[1u] in the pixel stage + EDITED (refuse): s_and_b32 s42, s42, 0xffff between the load and the sample (sampler word changed in the shader) + MIXED (refuse): s_mov_b32 s41, 0 between the load and the sample (words no longer one heap entry) + +Checks: each program decodes to its intended text; accepted ones translate with X2W_SAMPLER_HEAP=1, name the entry, +declare the table and write the smpheap line, and are refused without the switch (negative control: the switch off +gives the f37ad9f8 behaviour, a refusal, with the reason naming the offset); refused ones are refused with it. +""" +import os +import struct +import subprocess +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 disasm_rdna2 as D # noqa: E402 +from startup_mesh_exec_off_check import I, assemble, decoded, exp, ins # noqa: E402 (the same encoder) + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +def image_sample(vdata, vaddr, srsrc, ssamp): + """MIMG image_sample, dmask 0xf, dim 2D (word 0 as the fixture's llvm-mc encoding 080f80f0); word 1: vaddr [7:0], + vdata [15:8], srsrc / 4 [20:16], ssamp / 4 [25:21].""" + return [0xf0800f08, vaddr | (vdata << 8) | ((srsrc // 4) << 16) | ((ssamp // 4) << 21)] + + +def program(offset, between=()): + return [ + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('v_readfirstlane_b32 s20, v5', 'vop1', 'v_readfirstlane_b32', d=20, s0='v5'), + I('s_lshr_b32 s20, s20, 7', 'sop2', 's_lshr_b32', d=20, s0='s20', s1='7'), + I('s_bfe_u32 s28, s3, 0x40018', 'sop2', 's_bfe_u32', d=28, s0='s3', s1='0x40018'), + I('s_lshl_b32 s29, s28, 6', 'sop2', 's_lshl_b32', d=29, s0='s28', s1='6'), + I('v_mbcnt_lo_u32_b32 v0, -1, s29', 'vop3', 'v_mbcnt_lo_u32_b32', d=0, s0='-1', s1='s29'), + I('v_mbcnt_hi_u32_b32 v0, -1, v0', 'vop3', 'v_mbcnt_hi_u32_b32', d=0, s0='-1', s1='v0'), + I('s_mov_b32 s11, 0', 'sop1', 's_mov_b32', d=11, s0='0'), + I('s_mov_b32 s10, s16', 'sop1', 's_mov_b32', d=10, s0='s16'), + I('s_load_dwordx8 s[32:39], s[10:11], 0x0', 'smem', 's_load_dwordx8', d=32, s0='s10', imm=0), + I('s_mov_b32 s13, 0', 'sop1', 's_mov_b32', d=13, s0='0'), + I('s_mov_b32 s12, s18', 'sop1', 's_mov_b32', d=12, s0='s18'), + I('s_load_dwordx4 s[40:43], s[12:13], %#x' % offset, 'smem', 's_load_dwordx4', d=40, s0='s12', imm=offset), + ] + list(between) + [ + I('v_mov_b32_e32 v6, 0x3f000000', 'vop1', 'v_mov_b32_e32', d=6, s0='0x3f000000'), + I('v_mov_b32_e32 v7, 0x3f000000', 'vop1', 'v_mov_b32_e32', d=7, s0='0x3f000000'), + ('image_sample v[8:11], v[6:7], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D', + lambda: image_sample(8, 6, 32, 40)), + I('v_mov_b32_e32 v4, 0', 'vop1', 'v_mov_b32_e32', d=4, s0='0'), + I('s_mov_b32 m0, 0x80080', 'sop1', 's_mov_b32', d=124, s0='0x80080'), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + I('v_cvt_f32_u32_e32 v2, v0', 'vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0'), + I('v_mov_b32_e32 v3, 0', 'vop1', 'v_mov_b32_e32', d=3, s0='0'), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v8, v9, v10, v11', lambda: exp(32, ['v8', 'v9', 'v10', 'v11'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), + ] + + +EDIT = I('s_and_b32 s42, s42, 0xffff', 'sop2', 's_and_b32', d=42, s0='s42', s1='0xffff') +MIX = I('s_mov_b32 s41, 0', 'sop1', 's_mov_b32', d=41, s0='0') +PROGRAMS = { + 'const': (65, program(0x410)), + 'unaligned': (2047, program(0x418)), + 'edited': ('sampler heap entry at 0x410 edited in the shader', program(0x410, [EDIT])), + 'mixed': ('sampler operand s[40:43] mixes sampler heap words', program(0x410, [MIX])), +} +# tests/startup_sampler_heap_check.py CONST_WORDS (its PS_WORDS with the sampler load at the constant offset 0x10) +PS_CONST = bytes.fromhex('04040cf4000000fa' '050608f4100000fa' 'ff02007e0000a03f' 'f002027e' '7fc08cbf' + '080f80f00000c400' '703f8cbf' '0f1800f800010203' '000081bf') + + +def root_blob(): + """A DXBC container with one RTS0 part: parameter 0 a descriptor table, parameter 1 one root constant, flag 0x800 + (the layout of tests/startup_sampler_heap_check.py root_blob).""" + params = [(0, 0), (1, 0)] + poff = 24 + coff = poff + 12 * len(params) + rts0 = struct.pack('<6I', 2, len(params), poff, 0, 0, 0x800) + rts0 += struct.pack('<3I', 0, 0, coff + 12) + struct.pack('<3I', 1, 0, coff) + rts0 += struct.pack('<3I', 0, 0, 1) + rts0 += struct.pack('<5I', 0, 0, 0, 0, 0) + part = b'RTS0' + struct.pack('<I', len(rts0)) + rts0 + return b'DXBC' + bytes(16) + struct.pack('<III', 1, 32 + 4 + len(part), 1) + struct.pack('<I', 36) + part + + +def translate(ms_path, ps_path, heap): + """The translator in a child process (X2W_SAMPLER_HEAP is read per pipeline, X2W_MESH_* at import): 'OK' with + the mesh HLSL, the pixel HLSL and the manifest, or the refusal text.""" + child = ('import sys; sys.path[:0] = [%r, %r]\n' + 'import gfx2hlsl as G, mesh2hlsl as M\n' + 'ms = open(sys.argv[1], "rb").read(); ps = open(sys.argv[2], "rb").read() if sys.argv[2] != "-" else None\n' + 'root = open(sys.argv[3], "rb").read()\n' + 'try:\n' + ' p = M.MeshPipeline(ms, ps, root, user_sgpr=16)\n' + ' text = p.hlsl_ms() + "\\n=== ps\\n" + (p.hlsl_ps() if ps else "") + "\\n=== manifest\\n" + p.manifest()\n' + ' sys.stdout.write("OK\\n" + text)\n' + 'except G.Unsupported as e:\n' + ' sys.stdout.write("REFUSED %%s\\n" %% e)\n' + % (os.path.join(HERE, '..', 'tools'), os.path.join(HERE, '..', 'tools', 'startup'))) + e = dict(os.environ) + e.pop('X2W_SAMPLER_HEAP', None) + if heap: + e['X2W_SAMPLER_HEAP'] = '1' + r = subprocess.run([sys.executable, '-B', '-c', child, ms_path, ps_path or '-', translate.root], capture_output=True, + text=True, env=e) + if r.returncode: + return 'CRASH ' + (r.stderr.strip().splitlines() or ['?'])[-1] + return r.stdout + + +def main(): + out_dir = os.path.join(HERE, '..', 'out', 'startup_mesh_heap_sampler') + os.makedirs(out_dir, exist_ok=True) + translate.root = os.path.join(out_dir, 'root.bin') + with open(translate.root, 'wb') as f: + f.write(root_blob()) + ps_path = os.path.join(out_dir, 'ps_const.bin') + with open(ps_path, 'wb') as f: + f.write(PS_CONST) + decl = 'SamplerState qh[2048] : register(s0, space1);' + line = 'smpheap 2048 1 fallback 2047' + for name, (expect, items) in PROGRAMS.items(): + code, texts = assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = translate(path, None, True) + if isinstance(expect, int): + ms = on.split('=== ps')[0] + check('%s: translates with X2W_SAMPLER_HEAP=1' % name, on.startswith('OK'), on[:300]) + check('%s: samples entry qh[%du]' % (name, expect), '.SampleLevel(qh[%du], ' % expect in ms, + [l.strip() for l in ms.splitlines() if 'Sample' in l][:2]) + check('%s: declares the table and writes `%s`' % (name, line), decl in ms and '\n%s\n' % line in on, '') + off = translate(path, None, False) + check('%s: negative control (switch off) refuses' % name, + off.startswith('REFUSED sampler from the sampler heap at constant offset 0x41'), off[:200]) + if name == 'const': + pair = translate(path, ps_path, True) + ps = pair.split('=== ps')[-1].split('=== manifest')[0] if pair.startswith('OK') else '' + check('pair: translates (mesh entry 65, pixel stage at offset 0x10)', pair.startswith('OK'), pair[:300]) + check('pair: the pixel stage samples qh[1u]', 'qh[1u]' in ps and decl in ps, + [l.strip() for l in ps.splitlines() if 'Sample' in l][:2]) + off = translate(path, ps_path, False) + check('pair: negative control (switch off) refuses', off.startswith('REFUSED sampler from the sampler heap'), + off[:200]) + else: + check('%s: refused with X2W_SAMPLER_HEAP=1 (%s)' % (name, expect), on.startswith('REFUSED ' + expect), on[:200]) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_lane_scc_check.py b/tests/startup_mesh_lane_scc_check.py new file mode 100644 index 0000000000..897a1c3604 --- /dev/null +++ b/tests/startup_mesh_lane_scc_check.py @@ -0,0 +1,434 @@ +"""Check the lane-mask SCC lowering of tools/startup/mesh2hlsl.py (group-uniform execz range + wave "any lane" SCC). + +usage: startup_mesh_lane_scc_check.py [--write <dir>] + +A hand-assembled gfx1013 NGG program (no title bytes; encoded below field by field, opcode numbers found by +decoding with tools/disasm_rdna2.py and the decoded text compared with the intended text) does, per group g: + + N = 40 + 60 * (g & 1) vertices of the per-lane range (40: wave 1 has NO active lane in it) + T = 20 * (g & 3) lanes with v0 < T set vcc + s40 = 64 + exec = v0 < N; s_cbranch_execz after (group-uniform range: s40 is written inside and read after) + vcc = v0 < T + s_and_b64 s[12:13], vcc, exec SCC = (vcc & exec) != 0 over the WHOLE wave + s_cselect_b32 s40, 1, 33 s40 = SCC ? 1 : 33 + s_cbranch_scc0 skip branch on that SCC (the class refused before) + s_add_u32 s40, s40, 100 + skip/after: exec = -1; every thread exports param0 = (s40, v0, s40, v0) + +Hardware meaning (AMD RDNA 2 ISA, S_AND_B64: D = S0 & S1, SCC = D != 0; S_CBRANCH_SCC0 reads that one wave-wide +bit; S_CBRANCH_EXECZ skips the range for a wave whose exec is 0, so its s40 stays 7). Expected s40 per wave: + no lane of the wave in the range -> 64; some lane with v0 < T -> 101; else -> 33. +(Values at least 31 apart: difftest.py tolerates small differences in output words as float ulp noise.) +The translation runs one HLSL thread per lane: SCC must be the wave's value (published through groupshared +memory and a group barrier), and a wave with no active lane must get s40 = 64 back at the range end. + +Checks (pure Python; the differential run on WARP is mesh_work/difftest.py with --write's program): + 1. the program decodes back to the intended text; + 2. the translation succeeds and contains the publish, the wave read and the restore; + 3. negative controls: X2W_MESH_LANE_SCC=0 refuses the program again ("branch on an SCC that depends on lane + masks"); X2W_MESH_TEST_DROP=publish / restore remove the publish / restore statements (the WARP difftest + must then FAIL; see the --write output). +Program B (active-uniform SCC in a per-lane range, no publish) and program C (a lane-dependent SCC inside a +per-lane execz range, made group-uniform for the publish, with a vccz branch and an s_branch over the other side: +the taint at the join is merged; X2W_MESH_JOIN_TAINT=0, the linear scan, translates it WITHOUT the publish, which +the WARP difftest shows wrong) are described at their definitions. +""" +import os +import struct +import subprocess +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 disasm_rdna2 as D # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +# ---- a minimal gfx10 encoder: field layout per format, opcode found by decoding ----------------------------- +def src(tok): + """9-bit source operand code (VOP); SALU uses the low 8 bits of the same table.""" + named = {'vcc_lo': 106, 'vcc_hi': 107, 'm0': 124, 'exec_lo': 126, 'exec_hi': 127, 'src_scc': 253} + if tok in named: + return named[tok], None + if tok[0] == 's': + return int(tok[1:]), None + if tok[0] == 'v': + return 256 + int(tok[1:]), None + v = int(tok, 0) + if 0 <= v <= 64: + return 128 + v, None + if -16 <= v < 0: + return 192 - v, None + return 255, v & 0xffffffff + + +def fmt_words(fmt, op, f): + if fmt == 'sop2': + return [(0b10 << 30) | (op << 23) | (f['d'] << 16) | (f['s1'] << 8) | f['s0']] + if fmt == 'sop1': + return [(0x17d << 23) | (f['d'] << 16) | (op << 8) | f['s0']] + if fmt == 'sopc': + return [(0x17e << 23) | (op << 16) | (f['s1'] << 8) | f['s0']] + if fmt == 'sopp': + return [(0x17f << 23) | (op << 16) | (f['imm'] & 0xffff)] + if fmt == 'vop1': + return [(0x3f << 25) | (f['d'] << 17) | (op << 9) | f['s0']] + if fmt == 'vopc': + return [(0x3e << 25) | (op << 17) | ((f['s1'] - 256) << 9) | f['s0']] + if fmt == 'vop3': + return [(0x35 << 26) | (op << 16) | f['d'], f['s0'] | (f['s1'] << 9) | (f.get('s2', 0) << 18)] + raise ValueError(fmt) + + +OP_RANGE = {'sop2': 128, 'sop1': 256, 'sopc': 128, 'sopp': 128, 'vop1': 256, 'vopc': 256, 'vop3': 1024} +_op_cache = {} + + +def find_op(fmt, mnemonic, fields): + key = (fmt, mnemonic) + if key in _op_cache: + return _op_cache[key] + for op in range(OP_RANGE[fmt]): + words = fmt_words(fmt, op, fields) + code = struct.pack('<%dI' % len(words), *words) + b'\0' * 8 + try: + _, name, _, _ = D.decode_instruction(code, 0) + except Exception: + continue + if name == mnemonic: + _op_cache[key] = op + return op + raise KeyError('%s %s: no opcode decodes to it' % (fmt, mnemonic)) + + +def ins(fmt, mnemonic, **ops): + """One instruction: (words, literal or None). Operand values are register/constant spellings.""" + fields, literal = {}, None + for k, tok in ops.items(): + if k in ('d', 'imm'): + fields[k] = tok if isinstance(tok, int) else src(tok)[0] + continue + code, lit = src(tok) + fields[k] = code + if lit is not None: + literal = lit + words = fmt_words(fmt, find_op(fmt, mnemonic, fields), fields) + return words + ([literal] if literal is not None else []) + + +def exp(target, vals, done=False): + en = sum(1 << i for i, v in enumerate(vals) if v is not None) + w0 = (0x3e << 26) | (int(done) << 11) | (target << 4) | en + w1 = 0 + for i, v in enumerate(vals): + if v is not None: + w1 |= int(v[1:]) << (8 * i) + return [w0, w1] + + +PROLOGUE = [ + ('s_mov_b64 exec, -1', lambda: ins('sop1', 's_mov_b64', d=126, s0='-1')), + ('v_readfirstlane_b32 s20, v5', lambda: ins('vop1', 'v_readfirstlane_b32', d=20, s0='v5')), + ('s_lshr_b32 s20, s20, 7', lambda: ins('sop2', 's_lshr_b32', d=20, s0='s20', s1='7')), + ('s_bfe_u32 s28, s3, 0x40018', lambda: ins('sop2', 's_bfe_u32', d=28, s0='s3', s1='0x40018')), + ('s_lshl_b32 s29, s28, 6', lambda: ins('sop2', 's_lshl_b32', d=29, s0='s28', s1='6')), + ('v_mbcnt_lo_u32_b32 v0, -1, s29', lambda: ins('vop3', 'v_mbcnt_lo_u32_b32', d=0, s0='-1', s1='s29')), + ('v_mbcnt_hi_u32_b32 v0, -1, v0', lambda: ins('vop3', 'v_mbcnt_hi_u32_b32', d=0, s0='-1', s1='v0')), + ('s_and_b32 s21, s20, 1', lambda: ins('sop2', 's_and_b32', d=21, s0='s20', s1='1')), + ('s_mul_i32 s21, s21, 60', lambda: ins('sop2', 's_mul_i32', d=21, s0='s21', s1='60')), + ('s_add_u32 s21, s21, 40', lambda: ins('sop2', 's_add_u32', d=21, s0='s21', s1='40')), + ('s_and_b32 s22, s20, 3', lambda: ins('sop2', 's_and_b32', d=22, s0='s20', s1='3')), + ('s_mul_i32 s22, s22, 20', lambda: ins('sop2', 's_mul_i32', d=22, s0='s22', s1='20')), +] +EPILOGUE = [ + ('AFTER:', None), + ('s_mov_b64 exec, -1', lambda: ins('sop1', 's_mov_b64', d=126, s0='-1')), + ('s_mov_b32 m0, 0x80080', lambda: ins('sop1', 's_mov_b32', d=124, s0='0x80080')), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + ('v_cvt_f32_u32_e32 v2, v0', lambda: ins('vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0')), + ('v_mov_b32_e32 v3, 0', lambda: ins('vop1', 'v_mov_b32_e32', d=3, s0='0')), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v1, v0, v1, v0', lambda: exp(32, ['v1', 'v0', 'v1', 'v0'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] +# Program B: the SCC is the same in every active lane (vcc from a compare of uniform values, masked with exec) +# and the branch sits right inside a per-lane execz range that writes no scalar read after it, so every thread +# that runs there is an active lane: the per-lane branch is the wave's (no publish). Expected param0.x per lane: +# lanes v0 < N: 60 when T > 30 (groups 2, 3), else 5; lanes v0 >= N: 5. +UNIFORM_B = PROLOGUE + [ + ('v_mov_b32_e32 v1, 5', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='5')), + ('v_mov_b32_e32 v4, s22', lambda: ins('vop1', 'v_mov_b32_e32', d=4, s0='s22')), + ('v_cmpx_gt_u32_e32 s21, v0', lambda: ins('vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0')), + ('s_cbranch_execz AFTER', 'execz'), + ('v_cmp_lt_u32_e32 vcc_lo, 30, v4', lambda: ins('vopc', 'v_cmp_lt_u32_e32', s0='30', s1='v4')), + ('s_and_b64 s[12:13], vcc, exec', lambda: ins('sop2', 's_and_b64', d=12, s0='vcc_lo', s1='exec_lo')), + ('s_cbranch_scc0 AFTER', 'scc0'), + ('v_mov_b32_e32 v1, 60', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='60')), +] + EPILOGUE +# Program C: a lane-dependent SCC inside a per-lane execz range that writes no scalar read after it (a plain +# per-lane range before), then a per-lane vccz branch with an s_branch over the other side, both sides copying +# SCC to s20 (the shape of the run's programs). The publish needs every thread of the group at its barrier, so +# the range becomes group-uniform; the s_lshl on the first side leaves a lane-tainted SCC that the linear scan +# would carry into the other side (the join merge takes the state of the vccz branch instead). +# N = 40 + 60 * (g & 1), T = 30 * (g & 3). Expected param0.x: lanes v0 < N of a wave with a lane v0 < min(N, T): +# 60; every other lane 5. (g = 2: wave 1 has no lane in the range; g = 3: wave 1 lanes 64..99 get 60.) +# Program D: inside a per-lane execz range, an SCC from a saved exec copy and NOT exec (`s_andn2_b64 s, saved, +# exec`): the active lanes' own bits are all 0, the wave's SCC is 1 when the wave has a lane outside the range. Not +# an active-uniform SCC: it must be published. Expected param0.x: lanes v0 < N of a wave with a lane v0 >= N: 60; +# every other lane 5 (g even: lanes 0..39; g odd: lanes 64..99). +ANDN2_D = PROLOGUE + [ + ('v_mov_b32_e32 v1, 5', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='5')), + ('s_mov_b64 s[8:9], exec', lambda: ins('sop1', 's_mov_b64', d=8, s0='exec_lo')), + ('v_cmpx_gt_u32_e32 s21, v0', lambda: ins('vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0')), + ('s_cbranch_execz AFTER', 'execz'), + ('s_andn2_b64 s[12:13], s[8:9], exec', lambda: ins('sop2', 's_andn2_b64', d=12, s0='s8', s1='exec_lo')), + ('s_cbranch_scc0 AFTER', 'scc0'), + ('v_mov_b32_e32 v1, 60', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='60')), +] + EPILOGUE +# Program E: nested group-uniform execz ranges (both write a scalar read after them), so the outer skip jumps over +# the inner range's publish barrier (a barrier the translation adds). N = 50 * (g & 3): group 0 has no active lane +# at all (the group skips the outer range), group 1 has none in wave 1. Expected param0.x per wave (s40 + s41): +# no lane v0 < N: 300; lanes v0 < N but none < 20: 209; lanes v0 < 20 (and < N): 16. +NESTED_E = PROLOGUE[:7] + [ + ('s_and_b32 s21, s20, 3', lambda: ins('sop2', 's_and_b32', d=21, s0='s20', s1='3')), + ('s_mul_i32 s21, s21, 50', lambda: ins('sop2', 's_mul_i32', d=21, s0='s21', s1='50')), + ('s_mov_b32 s40, 0x64', lambda: ins('sop1', 's_mov_b32', d=40, s0='100')), + ('s_mov_b32 s41, 0xc8', lambda: ins('sop1', 's_mov_b32', d=41, s0='200')), + ('v_cmpx_gt_u32_e32 s21, v0', lambda: ins('vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0')), + ('s_cbranch_execz AFTER', 'execz'), + ('s_mov_b32 s40, 9', lambda: ins('sop1', 's_mov_b32', d=40, s0='9')), + ('v_cmpx_gt_u32_e32 20, v0', lambda: ins('vopc', 'v_cmpx_gt_u32_e32', s0='20', s1='v0')), + ('s_cbranch_execz AFTER', 'execz'), + ('s_mov_b32 s41, 7', lambda: ins('sop1', 's_mov_b32', d=41, s0='7')), + EPILOGUE[0], EPILOGUE[1], + ('s_add_u32 s42, s40, s41', lambda: ins('sop2', 's_add_u32', d=42, s0='s40', s1='s41')), + ('v_mov_b32_e32 v1, s42', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='s42')), +] + EPILOGUE[2:] +PROLOGUE_C = PROLOGUE[:-1] + [ + ('s_mul_i32 s22, s22, 30', lambda: ins('sop2', 's_mul_i32', d=22, s0='s22', s1='30')), +] +SPLIT_C = PROLOGUE_C + [ + ('v_mov_b32_e32 v1, 5', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='5')), + ('v_mov_b32_e32 v4, s22', lambda: ins('vop1', 'v_mov_b32_e32', d=4, s0='s22')), + ('v_cmpx_gt_u32_e32 s21, v0', lambda: ins('vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0')), + ('s_cbranch_execz AFTER', 'execz'), + ('v_cmp_gt_u32_e32 vcc_lo, s22, v0', lambda: ins('vopc', 'v_cmp_gt_u32_e32', s0='s22', s1='v0')), + ('s_and_b64 s[12:13], vcc, exec', lambda: ins('sop2', 's_and_b64', d=12, s0='vcc_lo', s1='exec_lo')), + ('v_cmp_lt_u32_e32 vcc_lo, 30, v4', lambda: ins('vopc', 'v_cmp_lt_u32_e32', s0='30', s1='v4')), + ('s_cbranch_vccz ELSE', 'vccz'), + ('s_mov_b32 s20, src_scc', lambda: ins('sop1', 's_mov_b32', d=20, s0='src_scc')), + ('s_lshl_b32 s23, vcc_lo, 2', lambda: ins('sop2', 's_lshl_b32', d=23, s0='vcc_lo', s1='2')), + ('s_branch JOIN', 'branch'), + ('ELSE:', None), + ('s_mov_b32 s20, src_scc', lambda: ins('sop1', 's_mov_b32', d=20, s0='src_scc')), + ('JOIN:', None), + ('s_cmp_lg_i32 s20, 0', lambda: ins('sopc', 's_cmp_lg_i32', s0='s20', s1='0')), + ('s_cbranch_scc0 AFTER', 'scc0'), + ('v_mov_b32_e32 v1, 60', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='60')), +] + EPILOGUE + + +def program(items=None): + """(code bytes, intended text per instruction). Branch targets are resolved in a second pass.""" + if items is not None: + return assemble(items) + items = [ + ('s_mov_b64 exec, -1', lambda: ins('sop1', 's_mov_b64', d=126, s0='-1')), + ('v_readfirstlane_b32 s20, v5', lambda: ins('vop1', 'v_readfirstlane_b32', d=20, s0='v5')), + ('s_lshr_b32 s20, s20, 7', lambda: ins('sop2', 's_lshr_b32', d=20, s0='s20', s1='7')), + ('s_bfe_u32 s28, s3, 0x40018', lambda: ins('sop2', 's_bfe_u32', d=28, s0='s3', s1='0x40018')), + ('s_lshl_b32 s29, s28, 6', lambda: ins('sop2', 's_lshl_b32', d=29, s0='s28', s1='6')), + ('v_mbcnt_lo_u32_b32 v0, -1, s29', lambda: ins('vop3', 'v_mbcnt_lo_u32_b32', d=0, s0='-1', s1='s29')), + ('v_mbcnt_hi_u32_b32 v0, -1, v0', lambda: ins('vop3', 'v_mbcnt_hi_u32_b32', d=0, s0='-1', s1='v0')), + ('s_and_b32 s21, s20, 1', lambda: ins('sop2', 's_and_b32', d=21, s0='s20', s1='1')), + ('s_mul_i32 s21, s21, 60', lambda: ins('sop2', 's_mul_i32', d=21, s0='s21', s1='60')), + ('s_add_u32 s21, s21, 40', lambda: ins('sop2', 's_add_u32', d=21, s0='s21', s1='40')), + ('s_and_b32 s22, s20, 3', lambda: ins('sop2', 's_and_b32', d=22, s0='s20', s1='3')), + ('s_mul_i32 s22, s22, 20', lambda: ins('sop2', 's_mul_i32', d=22, s0='s22', s1='20')), + ('s_mov_b32 s40, 64', lambda: ins('sop1', 's_mov_b32', d=40, s0='64')), + ('v_cmpx_gt_u32_e32 s21, v0', lambda: ins('vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0')), + ('s_cbranch_execz AFTER', 'execz'), + ('v_cmp_gt_u32_e32 vcc_lo, s22, v0', lambda: ins('vopc', 'v_cmp_gt_u32_e32', s0='s22', s1='v0')), + ('s_and_b64 s[12:13], vcc, exec', lambda: ins('sop2', 's_and_b64', d=12, s0='vcc_lo', s1='exec_lo')), + ('s_cselect_b32 s40, 1, 33', lambda: ins('sop2', 's_cselect_b32', d=40, s0='1', s1='33')), + ('s_cbranch_scc0 AFTER', 'scc0'), + ('s_add_u32 s40, s40, 0x64', lambda: ins('sop2', 's_add_u32', d=40, s0='s40', s1='100')), + ('AFTER:', None), + ('s_mov_b64 exec, -1', lambda: ins('sop1', 's_mov_b64', d=126, s0='-1')), + ('s_mov_b32 m0, 0x80080', lambda: ins('sop1', 's_mov_b32', d=124, s0='0x80080')), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + ('v_mov_b32_e32 v1, s40', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='s40')), + ('v_cvt_f32_u32_e32 v2, v0', lambda: ins('vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0')), + ('v_mov_b32_e32 v3, 0', lambda: ins('vop1', 'v_mov_b32_e32', d=3, s0='0')), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v1, v0, v1, v0', lambda: exp(32, ['v1', 'v0', 'v1', 'v0'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), + ] + return assemble(items) + + +def assemble(items): + # pass 1: sizes and label offsets + off, labels, sized = 0, {}, [] + for text, make in items: + if make is None: + labels[text[:-1]] = off + continue + words = make() if callable(make) else [0] + sized.append((off, text, make, len(words))) + off += 4 * len(words) + out, texts = [], [] + for off, text, make, n in sized: + if callable(make): + words = make() + else: + target = labels[text.split()[1]] + words = ins('sopp', 's_branch' if make == 'branch' else 's_cbranch_' + make, imm=(target - off - 4) // 4) + text = '%s label_%#x' % (text.split()[0], target) + out += words + texts.append((off, text)) + return struct.pack('<%dI' % len(out), *out), texts + + +def decoded(code): + off, res = 0, [] + while off + 4 <= len(code): + n, name, asm, _ = D.decode_instruction(code, off) + res.append((off, asm)) + off += n + return res + + +def translate(env): + """Run the translator in a child process (its switches are read at import): HLSL or the refusal text.""" + child = ('import sys; sys.path[:0] = [%r, %r]\n' + 'import gfx2hlsl as G, mesh2hlsl as M\n' + 'code = open(sys.argv[1], "rb").read()\n' + 'try:\n' + ' p = M.MeshPipeline(code, None, M.synth_root(code), user_sgpr=16)\n' + ' sys.stdout.write("OK\\n" + p.hlsl_ms())\n' + 'except G.Unsupported as e:\n' + ' sys.stdout.write("REFUSED %%s\\n" %% e)\n' + % (os.path.join(HERE, '..', 'tools'), os.path.join(HERE, '..', 'tools', 'startup'))) + e = dict(os.environ) + e.pop('X2W_MESH_LANE_SCC', None) + e.pop('X2W_MESH_TEST_DROP', None) + e.pop('X2W_MESH_JOIN_TAINT', None) + e.pop('X2W_MESH_CONFINED_SCC', None) + e.pop('X2W_MESH_SKIP_ADDED', None) + e.update(env) + r = subprocess.run([sys.executable, '-B', '-c', child, BIN], capture_output=True, text=True, env=e) + if r.returncode: + return 'CRASH ' + r.stderr.strip().splitlines()[-1] + return r.stdout + + +def main(): + global BIN + code, texts = program() + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_lane_scc') + os.makedirs(out_dir, exist_ok=True) + BIN = os.path.join(out_dir, 'lane_scc.bin') + with open(BIN, 'wb') as f: + f.write(code) + got = decoded(code) + check('decodes to the intended %d instructions' % len(texts), [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1] if i < len(got) else '?') for i, ((o, t), g) + in enumerate(zip(texts, got + [(0, '?')] * len(texts))) if i >= len(got) or got[i][1] != t)) + on = translate({}) + check('translates with the lowering on', on.startswith('OK'), on[:300]) + check('SCC published per wave and read back', 'x2w_sany[0][wave] = 1u' in on and 'scc = x2w_sany[0][wave]' in on, '') + check('hit scalar s40 restored for a wave with no active lane', 'x2w_any[0][wave] == 0u) s40 = ' in on, '') + off = translate({'X2W_MESH_LANE_SCC': '0'}) + check('negative control: X2W_MESH_LANE_SCC=0 refuses again', + off.startswith('REFUSED branch on an SCC that depends on lane masks'), off[:200]) + nopub = translate({'X2W_MESH_TEST_DROP': 'publish'}) + check('negative control switch: publish dropped', nopub.startswith('OK') and 'x2w_sany[0][wave] = 1u' not in nopub, nopub[:200]) + nores = translate({'X2W_MESH_TEST_DROP': 'restore'}) + check('negative control switch: restore dropped', nores.startswith('OK') and ') s40 = ' not in nores, nores[:200]) + print('program written to %s (difftest: python -B difftest.py %s <harness> --groups 4 --seed 1)' % (BIN, BIN)) + # program B: active-uniform SCC inside a per-lane range + code_b, texts_b = program(UNIFORM_B) + BIN = os.path.join(out_dir, 'lane_scc_uniform.bin') + with open(BIN, 'wb') as f: + f.write(code_b) + got = decoded(code_b) + check('B decodes to the intended %d instructions' % len(texts_b), [t for _, t in got] == [t for _, t in texts_b], + ' | '.join('%x %s / %s' % (o, t, g) for (o, t), (_, g) in zip(texts_b, got) if t != g)) + on = translate({}) + check('B translates as a per-lane branch, no publish', on.startswith('OK') and 'x2w_sany' not in on, on[:300]) + off = translate({'X2W_MESH_LANE_SCC': '0'}) + check('B negative control: X2W_MESH_LANE_SCC=0 refuses again', + off.startswith('REFUSED branch on an SCC that depends on lane masks'), off[:200]) + print('program B written to %s' % BIN) + # program C: publish inside a formerly per-lane range (made group-uniform) + taint merged at the join + code_c, texts_c = program(SPLIT_C) + BIN = os.path.join(out_dir, 'lane_scc_split.bin') + with open(BIN, 'wb') as f: + f.write(code_c) + got = decoded(code_c) + check('C decodes to the intended %d instructions' % len(texts_c), [t for _, t in got] == [t for _, t in texts_c], + ' | '.join('%x %s / %s' % (o, t, g) for (o, t), (_, g) in zip(texts_c, got) if t != g)) + on = translate({}) + check('C translates: range made group-uniform, SCC published', + on.startswith('OK') and 'x2w_any[0][wave] = 1u' in on and 'x2w_sany[0][wave] = 1u' in on + and 'scc = x2w_sany[0][wave]' in on, on[:300]) + off = translate({'X2W_MESH_LANE_SCC': '0'}) + check('C negative control: X2W_MESH_LANE_SCC=0 refuses again', + off.startswith('REFUSED branch on an SCC that depends on lane masks'), off[:200]) + lin = translate({'X2W_MESH_JOIN_TAINT': '0'}) + # the linear scan carries the s_lshl's active-uniform SCC into the ELSE side and takes the branch per lane + # without a publish: a WRONG translation (the WARP difftest of it must FAIL) + check('C negative control: X2W_MESH_JOIN_TAINT=0 (linear taint) translates WITHOUT the publish', + lin.startswith('OK') and 'x2w_sany' not in lin, lin[:200]) + print('program C written to %s (difftest also with X2W_MESH_TEST_DROP=publish: must FAIL)' % BIN) + # program D: an SCC of the inactive lanes' bits (saved exec & ~exec) is not active-uniform: published + code_d, texts_d = program(ANDN2_D) + BIN = os.path.join(out_dir, 'lane_scc_andn2.bin') + with open(BIN, 'wb') as f: + f.write(code_d) + got = decoded(code_d) + check('D decodes to the intended %d instructions' % len(texts_d), [t for _, t in got] == [t for _, t in texts_d], + ' | '.join('%x %s / %s' % (o, t, g) for (o, t), (_, g) in zip(texts_d, got) if t != g)) + on = translate({}) + check('D translates with the SCC published (not taken per lane)', on.startswith('OK') and 'x2w_sany' in on, on[:300]) + loose = translate({'X2W_MESH_CONFINED_SCC': '0'}) + check('D negative control: X2W_MESH_CONFINED_SCC=0 takes the branch per lane (no publish)', + loose.startswith('OK') and 'x2w_sany' not in loose, loose[:200]) + print('program D written to %s (difftest also with X2W_MESH_CONFINED_SCC=0: must FAIL)' % BIN) + # program E: nested group-uniform ranges; the outer skip jumps over the inner publish barrier + code_e, texts_e = program(NESTED_E) + BIN = os.path.join(out_dir, 'lane_scc_nested.bin') + with open(BIN, 'wb') as f: + f.write(code_e) + got = decoded(code_e) + check('E decodes to the intended %d instructions' % len(texts_e), [t for _, t in got] == [t for _, t in texts_e], + ' | '.join('%x %s / %s' % (o, t, g) for (o, t), (_, g) in zip(texts_e, got) if t != g)) + on = translate({}) + check('E translates: two group branches, s40 and s41 restored', + on.startswith('OK') and 'x2w_any[1][wave] = 1u' in on and ') s40 = ' in on and ') s41 = ' in on, on[:300]) + old = translate({'X2W_MESH_SKIP_ADDED': '0'}) + check('E negative control: X2W_MESH_SKIP_ADDED=0 refuses (barrier inside the outer range)', + old.startswith('REFUSED s_barrier inside a group-uniform execz range'), old[:200]) + print('program E written to %s (difftest also with X2W_MESH_TEST_DROP=restore: must FAIL)' % BIN) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_literal_flow_check.py b/tests/startup_mesh_literal_flow_check.py new file mode 100644 index 0000000000..65b6985b21 --- /dev/null +++ b/tests/startup_mesh_literal_flow_check.py @@ -0,0 +1,99 @@ +"""Offline proofs for scalar literal addressing and SCC-dead SGPR exchange lowering.""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import mesh2hlsl as M + + +def stage(*asm): + s = M.MeshStage.__new__(M.MeshStage) + s.ins = [(4 * i, 4, line.split()[0], line) for i, line in enumerate(asm)] + s.pc = s.ins[-1][0] + s.sym = {} + return s + + +def check_literals(): + prefix = ['s_movk_i32 s8, 0xffff', 's_mov_b32 s12, s8'] + end = 's_endpgm' + assert stage(*prefix, end).copied_constant(12) == 0xffffffff + assert stage(*prefix, 's_addk_i32 s12, 1', end).copied_constant(12) is None + assert stage('s_cbranch_scc0 label_0xc', *prefix, end).copied_constant(12) is None + assert stage('s_mov_b32 s8, 24', 's_cbranch_scc0 label_0x10', 's_mov_b32 s8, 16', + 's_branch label_0x10', end).copied_constant(8) is None + assert stage('s_mov_b32 s8, 24', 'v_cmp_gt_f32_e64 s7, 0, v5', end).copied_constant(8) is None + + extract = 's_bfe_u32 s8, s2, 0x30004' + shift = 's_lshl_b32 s8, s8, 2' + load = 's_buffer_load_dword s4, s[12:15], s8' + assert stage(extract, shift, load, load).scalar_literal_index_bits('s8') == 3 + assert stage('s_branch label_0x8', extract, shift, load).scalar_literal_index_bits('s8') is None + assert stage(extract, shift, load.replace('s4,', 's8,'), load).scalar_literal_index_bits('s8') is None + assert stage(extract, shift.replace(', 2', ', 4'), load).scalar_literal_index_bits('s8') is None + + +def check_exchanges(): + a = 's_xor_b32 s4, s4, s7' + b = 's_xor_b32 s7, s7, s4' + neutral = 'v_mul_f32_e32 v1, v3, v2' + s = stage(a, neutral, b, a, 's_endpgm') + assert s.lower_pair_swaps() == {12} + regs = {'s4': 0xcabb1e, 's7': 0xabcdef} + for _, _, name, asm in s.ins: + if name == 's_mov_b32': + d, source = M.parse(asm)[1] + regs[d] = regs[source] + assert regs['s4'] == 0xabcdef and regs['s7'] == 0xcabb1e + assert not stage(a, 's_mov_b32 s6, s7', b, a).lower_pair_swaps() + assert not stage('s_branch label_0x8', a, b, a).lower_pair_swaps() + assert not stage(a, 's_mov_b32 s5, src_scc', b, a).lower_pair_swaps() + s = stage(a, b, a, 's_cbranch_scc1 label_0x10', 's_endpgm') + s.swap_scc = s.lower_pair_swaps() + try: + s.check_scc(set(), set()) + except M.Unsupported: + pass + else: + raise AssertionError('exchange with live SCC was accepted') + + +def check_conflict_copy(): + s = stage('s_mov_b64 s[16:17], s[64:65]') + s.sym = {64: ('conflict',), 65: ('conflict',)} + s.masks, s.used_s, s.exec_off = set(), set(), {16, 17} + s.execzero = {16: 1, 17: 1} + lines = [] + s.emit = lines.append + s.scalar_inner('s_mov_b64', ['s[16:17]', 's[64:65]']) + assert lines == ['s16 = s64;', 's17 = s65;'] + assert not s.exec_off and not s.execzero + for reg in (16, 17): + assert s.sym[reg] == ('conflict',) + try: + s.S(reg) + except M.Unsupported as refusal: + assert 'holding conflict' in str(refusal) + else: + raise AssertionError('unresolved SGPR copy accepted as a number') + + s.sym = {65: ('conflict',)} + s.masks = {64} + lines.clear() + s.scalar_inner('s_mov_b64', ['s[16:17]', 's[64:65]']) + assert 16 in s.masks and s.sym[17] == ('conflict',) + assert lines[-1] == 's17 = s65;' + assert 's64' in lines[0] and '& 1' in lines[0] + + s.sym = {64: ('conflict',), 65: ('conflict',)} + s.masks.clear() + lines.clear() + s.scalar_inner('s_mov_b64', ['s[65:66]', 's[64:65]']) + assert lines == ['s66 = s65;', 's65 = s64;'] + + +if __name__ == '__main__': + check_literals() + check_exchanges() + check_conflict_copy() + print('Scalar literal copy/bounds and XOR exchange controls passed') diff --git a/tests/startup_mesh_loop_tail_check.py b/tests/startup_mesh_loop_tail_check.py new file mode 100644 index 0000000000..7c560c736d --- /dev/null +++ b/tests/startup_mesh_loop_tail_check.py @@ -0,0 +1,40 @@ +"""Check scalar values carried out of per-lane mesh loops.""" +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import mesh2hlsl as M + + +PROGRAM = ( + 's_branch label_0xc', + 's_mov_b64 exec, s[8:9]', + 's_mov_b32 s5, s4', + 's_mov_b32 s4, 1', + 's_mov_b32 s4, s5', + 's_and_b64 exec, s[12:13], exec', + 's_andn2_b64 s[8:9], s[8:9], exec', + 's_cbranch_scc1 label_0x4', + 's_mov_b32 s2, s4', + 's_mov_b64 exec, s[6:7]', + 'v_mov_b32_e32 v2, s2', + 's_endpgm', +) + + +def proof(changes=None): + scene = M.MeshStage.__new__(M.MeshStage) + instructions = [(changes or {}).get(i, asm) for i, asm in enumerate(PROGRAM)] + scene.ins = [(i * 4, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] + return scene.perlane_loop(4, 28) + + +if __name__ == '__main__': + assert proof() is None + assert 's4 written' in proof({0: 's_cbranch_scc0 label_0xc'}) + assert 's4 written' in proof({4: 's_mov_b32 s4, s3'}) + assert 's4 written' in proof({3: 's_xor_b32 s5, s5, 1'}) + assert 'no s_mov_b64 exec restore' in proof({8: 'v_mov_b32_e32 v4, s4'}) + assert 'no s_mov_b64 exec restore' in proof({8: 's_mov_b32 s2, exec_lo'}) + assert 'restored exec copy' in proof({8: 's_mov_b32 s6, s4'}) + print('Scalar-only loop tail and saved scalar checks passed.') diff --git a/tests/startup_mesh_output_budget_check.py b/tests/startup_mesh_output_budget_check.py new file mode 100644 index 0000000000..4072a08b56 --- /dev/null +++ b/tests/startup_mesh_output_budget_check.py @@ -0,0 +1,24 @@ +from pathlib import Path +from types import SimpleNamespace +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools/startup')) +import mesh2hlsl as M + + +def check(): + pipe = SimpleNamespace(ps=SimpleNamespace(attrs={0: {'flat'}, 1: {'half', 'linear'}})) + decl = (' float4 param0 : PARAM0;\n float4 param1 : PARAM1;\n' + ' nointerpolation uint4 fparam0 : FPARAM0;\n float4 hiparam1 : HIPARAM1;\n') + ms = decl + 'if (exec) { o.param0 = raw; o.fparam0 = flat; o.param1 = mixed; }' + ps = decl + 'return i.fparam0.x + i.hiparam1.y + i.param1.z;' + compact, pixel = M.compact_mesh_interface(pipe, ms, ps) + assert 'float4 param0 :' not in compact and 'o.param0 =' not in compact + assert 'float4 param0 :' not in pixel + assert 'o.fparam0 = flat;' in compact and 'o.param1 = mixed;' in compact + assert pixel.endswith('return i.fparam0.x + i.hiparam1.y + i.param1.z;') + + +if __name__ == '__main__': + check() + print('PASS: flat-only and mixed half/linear mesh outputs') diff --git a/tests/startup_mesh_padded_barriers_check.py b/tests/startup_mesh_padded_barriers_check.py new file mode 100644 index 0000000000..33819a7bef --- /dev/null +++ b/tests/startup_mesh_padded_barriers_check.py @@ -0,0 +1,52 @@ +"""Check mesh phase scheduling when only one wave enters the publisher.""" +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools/startup')) +import mesh2hlsl as M # noqa: E402 + + +def fixture(): + stage = M.MeshStage.__new__(M.MeshStage) + stage.blocks = [ + (0, [], ('branch', 'tid < 64u', 4)), + (1, ['++turns;'], ('branch', 'turns < 3u', 1)), + (2, ['if (tid == 64u) mailbox[1] = 91u;'], ('barrier', 'console')), + (3, [], ('jump', 7)), + (4, ['if (tid == 0u) mailbox[0] = 47u;'], ('barrier', 'lane-scc')), + (5, ['local = mailbox[0];'], ('barrier', 'console')), + (6, [], ('jump', 7)), + (7, ['dump.Store(4u * tid, local + turns + mailbox[tid < 64u ? 1u : 0u]);'], ('end',)), + ] + stage.uniform_skips = set() + return stage + + +def check(): + stage = fixture() + try: + stage.barrier_count() + except M.UnevenBarrierPaths: + pass + else: + raise AssertionError('the original scheduler unexpectedly accepted the uneven paths') + stage.barriers = stage.padded_barrier_count() + stage.padded_phases = True + assert stage.barriers == 2 + assert stage.phase_of[2] == stage.phase_of[5] == 1 + assert stage.phase_of[4] == 0 and stage.phase_of[7] == 2 + assert 'else { break; }' in '\n'.join(stage.body()) + for index, term in [(5, None), (4, ('branch', 'again', 1))]: + bad = fixture() + bad.blocks[index] = (index, [], term) + try: + bad.padded_barrier_count() + except M.Unsupported: + continue + raise AssertionError('unequal console counts or a barrier inside a loop must refuse') + return stage + + +if __name__ == '__main__': + check() + print('PASS: paired console barriers, one-arm publish, unequal counts and backward edges') diff --git a/tests/startup_mesh_restored_scalar_check.py b/tests/startup_mesh_restored_scalar_check.py new file mode 100644 index 0000000000..612c9694b1 --- /dev/null +++ b/tests/startup_mesh_restored_scalar_check.py @@ -0,0 +1,104 @@ +"""Check two refinements of the skipped-range scalar rule of tools/startup/mesh2hlsl.py (X2W_MESH_RESTORED_SCALARS): +a scalar written in a per-lane skipped range is not "live after it" when (a) every exit of the range gives it back +its value from before (MeshStage.restored_scalars: `s_mov_b32 sT, sR; ... sR = ...; ... s_mov_b32 sR, sT`), or +(b) the next access after the range is a v_cmp that writes it as the high half of a wave64 lane mask +(MeshStage.liveness with pair writes); and a v_cndmask that reads the mask pair keeps the high half live. + +usage: startup_mesh_restored_scalar_check.py [--write <dir>] + +Hand-assembled gfx1013 NGG programs (no title bytes; encoder of tests/startup_mesh_exec_restore_check.py). Each has +s35 = T, exec = v0 < N, an execz range to AFTER, and inside it a uniform vccz branch (vcc = exec & (50 < N)) over +an inner range that writes s35, ending at INNER (the class's shape: a vccz range inside a per-lane execz range): + + SHUFFLE (accept): s33 = s35; s35 = 0; v1 = 9; s35 = s33 INNER: v4 = s35 + MASKED (accept): s35 = 0; v1 = 9 INNER: v_cmp_gt_u32_e64 s34 (writes s[34:35]); + s[12:13] = s[34:35] & exec; v4 = s12 ? 1 : 0 + LIVE (refuse): s35 = 0; v1 = 9 INNER: v4 = s35 + READ (refuse): s[34:35] = a mask first; s35 = 0; v1 = 9 INNER: v_cndmask_b32_e64 v4, 0, 1, s34 (reads s[34:35]) + +Hardware meaning (AMD RDNA 2 ISA: S_MOV_B32 copies; a VOP3 compare in wave64 writes its SDST pair; V_CNDMASK_B32 +e64 reads SSRC2 as a wave64 mask pair): in SHUFFLE and MASKED the lanes that skip the inner range see the same s35 +as the wave afterwards (SHUFFLE: T; MASKED: rewritten before any read); in LIVE and READ they would not. + +Checks: decode; SHUFFLE and MASKED translate with the rule on and are refused with X2W_MESH_RESTORED_SCALARS=0 +(the f37ad9f8 reason); LIVE and READ are refused with the rule on. +""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 + +I, ins, exp = E.I, E.ins, E.exp + +HEAD = E.PROLOGUE + [ + I('s_mov_b32 s35, s22', 'sop1', 's_mov_b32', d=35, s0='s22'), + I('v_mov_b32_e32 v6, s21', 'vop1', 'v_mov_b32_e32', d=6, s0='s21'), + E.CMPX_N, + ('s_cbranch_execz AFTER', 'execz'), + I('v_cmp_lt_u32_e32 vcc_lo, 50, v6', 'vopc', 'v_cmp_lt_u32_e32', s0='50', s1='v6'), + ('s_cbranch_vccz INNER', 'vccz'), +] +ZERO = I('s_mov_b32 s35, 0', 'sop1', 's_mov_b32', d=35, s0='0') +TAIL = [ + ('AFTER:', None), + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('s_mov_b32 m0, 0x80080', 'sop1', 's_mov_b32', d=124, s0='0x80080'), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + I('v_cvt_f32_u32_e32 v2, v0', 'vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0'), + I('v_mov_b32_e32 v3, 0', 'vop1', 'v_mov_b32_e32', d=3, s0='0'), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v1, v0, v4, v0', lambda: exp(32, ['v1', 'v0', 'v4', 'v0'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] +V4_S35 = I('v_mov_b32_e32 v4, s35', 'vop1', 'v_mov_b32_e32', d=4, s0='s35') +CMP64 = I('v_cmp_gt_u32_e64 s34, s22, v0', 'vop3', 'v_cmp_gt_u32_e64', d=34, s0='s22', s1='v0') +CND = I('v_cndmask_b32_e64 v4, 0, 1, s34', 'vop3', 'v_cndmask_b32_e64', d=4, s0='0', s1='1', s2='s34') +SAVE_MASK = I('v_cmp_gt_u32_e64 s34, s23, v0', 'vop3', 'v_cmp_gt_u32_e64', d=34, s0='s23', s1='v0') + +PROGRAMS = { + 'shuffle': (True, HEAD + [I('s_mov_b32 s33, s35', 'sop1', 's_mov_b32', d=33, s0='s35'), ZERO, E.V1_9, + I('s_mov_b32 s35, s33', 'sop1', 's_mov_b32', d=35, s0='s33'), ('INNER:', None)] + + [V4_S35] + TAIL), + 'masked': (True, HEAD + [ZERO, E.V1_9, ('INNER:', None), CMP64, + I('s_and_b64 s[12:13], s[34:35], exec', 'sop2', 's_and_b64', d=12, s0='s34', s1='exec_lo'), + I('v_cndmask_b32_e64 v4, 0, 1, s12', 'vop3', 'v_cndmask_b32_e64', d=4, s0='0', s1='1', s2='s12')] + + TAIL), + 'live': (False, HEAD + [ZERO, E.V1_9, ('INNER:', None), V4_S35] + TAIL), + 'read': (False, E.PROLOGUE + [SAVE_MASK] + HEAD[len(E.PROLOGUE):] + [ZERO, E.V1_9, ('INNER:', None), CND] + TAIL), +} +OLD = 'REFUSED scalar s35 written in the per-lane skipped range' + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_restored_scalar') + os.makedirs(out_dir, exist_ok=True) + for name, (accept, items) in PROGRAMS.items(): + code, texts = E.assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + E.check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = E.translate(path, {'X2W_MESH_RESTORED_SCALARS': '1'}) + if accept: + E.check('%s: translates with the rule on' % name, on.startswith('OK'), on[:300]) + off = E.translate(path, {'X2W_MESH_RESTORED_SCALARS': '0'}) + E.check('%s: negative control X2W_MESH_RESTORED_SCALARS=0 refuses again' % name, off.startswith(OLD), off[:200]) + else: + E.check('%s: still refused with the rule on' % name, on.startswith(OLD), on[:200]) + print('programs written to %s' % out_dir) + if E.failures: + print('%d check(s) failed' % len(E.failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_rtv_variant_check.py b/tests/startup_mesh_rtv_variant_check.py new file mode 100644 index 0000000000..d6406e5a88 --- /dev/null +++ b/tests/startup_mesh_rtv_variant_check.py @@ -0,0 +1,188 @@ +"""Check the RTV variant request of tools/startup/mesh2hlsl.py translate_request: req_<V>.rtv holds +`rtv1 <base key> <DXGI formats>` with V = fnv(that text) (gfx2hlsl.translate_request's contract; the mesh runtime +publishes it for a bound integer or 32-bit float target, d3d12_mesh.inl). The variant takes the base request's +blobs, checked against the base key; its pixel exports follow the target formats (Pipeline.mrt_kind) and its +manifest carries the rtv1 line. + +usage: startup_mesh_rtv_variant_check.py [--dxc] + +Hand-assembled gfx1013 programs (no title bytes; encoded field by field with the encoder of +tests/startup_mesh_exec_off_check.py, the decoded text compared with the intended text): an NGG mesh stage +(GS_ALLOC_REQ, pos0, param0, primitive export) and a pixel stage `v_mov_b32 v0, 0x3f800000; v_mov_b32 v1, 0x40000000; +exp mrt0 v0, v1, off, off done vm`. Root: the RTS0 blob of tests/startup_mesh_heap_sampler_check.py. +Without --dxc the DXC step of translate_to is stubbed (pure Python); with --dxc both stages compile. + + BASE (accept): no .rtv -> exports F(x), no rtv1 line, no mrtbits source + R32_FLOAT (accept): `rtv1 <base> 41` -> mrt0 F((x) ^ udN), `udsrc N mrtbits`, the rtv1 line; mesh HLSL unchanged + R32_UINT (accept): `rtv1 <base> 42` -> mrt0 written as uint4 words + UNORM8 (accept): `rtv1 <base> 28` -> pixel HLSL identical to the base (only 32-bit targets change) + negative controls (refuse): file name not fnv(text); malformed text; base key not the blobs' key; + a variant of a depth-only base (no pixel stage) +""" +import os +import shutil +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 +import mesh2hlsl as M # noqa: E402 +from startup_mesh_exec_off_check import I, assemble, decoded, exp, ins # noqa: E402 (the same encoder) +from startup_mesh_heap_sampler_check import root_blob # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + str(detail)}") + if not condition: + failures.append(label) + + +MESH = [ + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('v_readfirstlane_b32 s20, v5', 'vop1', 'v_readfirstlane_b32', d=20, s0='v5'), + I('s_lshr_b32 s20, s20, 7', 'sop2', 's_lshr_b32', d=20, s0='s20', s1='7'), + I('s_bfe_u32 s28, s3, 0x40018', 'sop2', 's_bfe_u32', d=28, s0='s3', s1='0x40018'), + I('s_lshl_b32 s29, s28, 6', 'sop2', 's_lshl_b32', d=29, s0='s28', s1='6'), + I('v_mbcnt_lo_u32_b32 v0, -1, s29', 'vop3', 'v_mbcnt_lo_u32_b32', d=0, s0='-1', s1='s29'), + I('v_mbcnt_hi_u32_b32 v0, -1, v0', 'vop3', 'v_mbcnt_hi_u32_b32', d=0, s0='-1', s1='v0'), + I('v_mov_b32_e32 v4, 0', 'vop1', 'v_mov_b32_e32', d=4, s0='0'), + I('s_mov_b32 m0, 0x80080', 'sop1', 's_mov_b32', d=124, s0='0x80080'), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + I('v_cvt_f32_u32_e32 v2, v0', 'vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0'), + I('v_mov_b32_e32 v3, 0', 'vop1', 'v_mov_b32_e32', d=3, s0='0'), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v2, v2, v2, v2', lambda: exp(32, ['v2', 'v2', 'v2', 'v2'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] + + +def exp_vm(target, vals, done=False): + w = exp(target, vals, done) + return [w[0] | (1 << 12), w[1]] # VM (valid mask), bit 12 of word 0 + + +PIXEL = [ + I('v_mov_b32_e32 v0, 0x3f800000', 'vop1', 'v_mov_b32_e32', d=0, s0='0x3f800000'), + I('v_mov_b32_e32 v1, 0x40000000', 'vop1', 'v_mov_b32_e32', d=1, s0='0x40000000'), + ('exp mrt0 v0, v1, off, off done vm', lambda: exp_vm(0, ['v0', 'v1', None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] + + +def code_of(name, items): + code, texts = assemble(items) + got = decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + return code + + +def write_request(out_dir, key, a, b, root): + for ext, data in (('.a', a), ('.b', b), ('.root', root)): + with open(os.path.join(out_dir, 'req_%016x%s' % (key, ext)), 'wb') as f: + f.write(data) + return key + + +def write_rtv(out_dir, text, key=None): + key = G.fnv(text.encode('ascii')) if key is None else key + with open(os.path.join(out_dir, 'req_%016x.rtv' % key), 'w', encoding='ascii', newline='') as f: + f.write(text) + return key + + +def outputs(out_dir, key): + name = os.path.join(out_dir, '%016x' % key) + res = [] + for ext in ('.ms.hlsl', '.ps.hlsl', '.txt'): + res.append(open(name + ext).read() if os.path.isfile(name + ext) else '') + return res + + +def main(): + if '--dxc' not in sys.argv[1:]: + M.compile_hlsl = lambda path, profile, out: (0, '') # pure Python: the HLSL text is checked, not compiled + out_dir = os.path.join(HERE, '..', 'out', 'startup_mesh_rtv_variant') + shutil.rmtree(out_dir, ignore_errors=True) + os.makedirs(out_dir) + ms, ps, root = code_of('mesh', MESH), code_of('pixel', PIXEL), root_blob() + check('mesh: is_mesh', M.is_mesh(ms) and not M.is_mesh(ps), '') + base = write_request(out_dir, G.pipeline_key(ps, ms, root), ps, ms, root) # runtime order: .a pixel, .b mesh + + r = M.translate_request(out_dir, base) + b_ms, b_ps, b_txt = outputs(out_dir, base) + check('base: translates', r == 'ok', r) + check('base: mrt0 is a plain float export', 'F(' in b_ps and '^ ud' not in b_ps, + [l.strip() for l in b_ps.splitlines() if 'o.mrt0' in l]) + check('base: no rtv1 line, no mrtbits source', 'rtv1' not in b_txt and 'mrtbits' not in b_txt, b_txt) + + text = 'rtv1 %d 41' % base + v = write_rtv(out_dir, text) + r = M.translate_request(out_dir, v) + v_ms, v_ps, v_txt = outputs(out_dir, v) + src = [l for l in v_txt.splitlines() if l.startswith('udsrc ') and l.endswith(' mrtbits')] + ud = src[0].split()[1] if src else '?' + mrt0 = [l.strip() for l in v_ps.splitlines() if 'o.mrt0' in l] + check('R32_FLOAT: translates', r == 'ok', r) + check('R32_FLOAT: manifest carries `%s`' % text, v_txt.endswith('\n' + text + '\n'), v_txt[-200:]) + check('R32_FLOAT: manifest names the mrtbits source', len(src) == 1, v_txt) + check('R32_FLOAT: mrt0 exports the register bits F((x) ^ ud%s)' % ud, + len(mrt0) == 1 and mrt0[0].count('^ ud%s)' % ud) == 2 and 'F((' in mrt0[0], mrt0) + # the stages share one entry constant buffer: the mesh stage declares the added source, nothing else changes + grown = b_ms.replace(' uint ud%d; };' % (int(ud) - 1), ' uint ud%d; uint ud%s; };' % (int(ud) - 1, ud), 1) \ + if ud.isdigit() and int(ud) > 0 else None + check('R32_FLOAT: mesh HLSL equals the base but for the shared entry cbuffer gaining ud%s' % ud, + v_ms == grown and v_ms != b_ms, [l for l in v_ms.splitlines() if l.startswith('cbuffer entry')]) + check('R32_FLOAT: written under the variant key only', os.path.isfile(os.path.join(out_dir, '%016x.txt' % v)) + and outputs(out_dir, base)[2] == b_txt, '') + + v = write_rtv(out_dir, 'rtv1 %d 42' % base) + r = M.translate_request(out_dir, v) + u_ps = outputs(out_dir, v)[1] + mrt0 = [l.strip() for l in u_ps.splitlines() if 'o.mrt0' in l] + check('R32_UINT: translates', r == 'ok', r) + check('R32_UINT: mrt0 is a uint4 of the register words', len(mrt0) == 1 and 'uint4(' in mrt0[0] + and '^ ud' not in mrt0[0], mrt0) + + v = write_rtv(out_dir, 'rtv1 %d 28' % base) + r = M.translate_request(out_dir, v) + n_ps, n_txt = outputs(out_dir, v)[1:] + check('UNORM8: translates', r == 'ok', r) + check('UNORM8: pixel HLSL equals the base (negative control: only 32-bit targets change)', n_ps == b_ps, '') + check('UNORM8: manifest carries the rtv1 line, no mrtbits', n_txt.endswith('rtv1 %d 28\n' % base) + and 'mrtbits' not in n_txt, n_txt[-200:]) + + # negative controls + v = write_rtv(out_dir, text, key=G.fnv(text.encode('ascii')) ^ 1) + r = M.translate_request(out_dir, v) + check('negative: file name not fnv(text) refused', r == 'unsupported: invalid RTV variant request', r) + check('negative: nothing written for it', not any(os.path.isfile(os.path.join(out_dir, '%016x%s' % (v, e))) + for e in ('.txt', '.ps.hlsl', '.fail')), '') + v = write_rtv(out_dir, text + '\n') + r = M.translate_request(out_dir, v) + check('negative: malformed text (trailing newline) refused', r == 'unsupported: invalid RTV variant request', r) + other = write_request(out_dir, base ^ 0x5a5a, ps, ms, root) # the base blobs under a key that is not theirs + v = write_rtv(out_dir, 'rtv1 %d 41' % other) + r = M.translate_request(out_dir, v) + check('negative: base key not the blobs\' key refused', r == 'unsupported: RTV variant source key mismatch', r) + depth = write_request(out_dir, G.pipeline_key(b'', ms, root), b'', ms, root) + check('depth-only base: translates without a variant', M.translate_request(out_dir, depth) == 'ok', '') + v = write_rtv(out_dir, 'rtv1 %d 41' % depth) + r = M.translate_request(out_dir, v) + check('negative: variant of a depth-only base refused', + r == 'unsupported: RTV variant of a mesh pipeline without a pixel stage', r) + + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_salu_check.py b/tests/startup_mesh_salu_check.py new file mode 100644 index 0000000000..ac427fbb4c --- /dev/null +++ b/tests/startup_mesh_salu_check.py @@ -0,0 +1,145 @@ +"""Check plain scalar ALU forms of tools/startup/gfx2hlsl.py (SCA) on the mesh stage: s_sext_i32_i8 / s_sext_i32_i16, +s_bcnt1_i32_b32. + +usage: startup_mesh_salu_check.py [--write <dir>] + +Hand-assembled gfx1013 NGG programs (no title bytes), built with the encoder of tests/startup_mesh_exec_restore_check.py. +Prologue as there (T = 20 * (g & 3) in s22); the epilogue exports (v1, v0, v4, v0) as param0. + +Hardware meaning (LLVM SOPInstructions.td: S_SEXT_I32_I8 / S_SEXT_I32_I16 select sext_inreg of S0 to i8 / i16; +neither defines SCC): + SEXT (accept): s24 = T + 0x7ff0; s25 = sext16(s24); s26 = T + 0x70; s27 = sext8(s26); v1 = s25; v4 = s27. + expected (T = 0, 20, 40, 60): v1 = 0x7ff0, 0xffff8004, 0xffff8018, 0xffff802c; + v4 = 0x70, 0xffffff84, 0xffffff98, 0xffffffac. + BCNT (accept): s25 = popcount(T | 0xf00); s28 = popcount(T & 0x100) (= 0, so SCC = 0); s26 = SCC ? 7 : 9; + v1 = s25 << 16; v4 = s26. expected (T = 0, 20, 40, 60): v1 = 4, 6, 6, 8 (<< 16); v4 = 9. + (The shift keeps a wrong count more than 16 ulp away as an f32 word: difftest.py tolerates <= 16 ulp.) + (LLVM SOPInstructions.td S_BCNT1_I32_B32: ctpop of S0, Defs = [SCC], SCC = D != 0.) + BCNTMASK (refuse): s25 = popcount(s[30:31]) of a v_cmp lane mask: the one-lane model holds the lane's bit only. + +Checks: decode; SEXT translates to the arithmetic-shift form; the emitted expressions, evaluated here for the four T +values, give the expected words; negative control: with the SCA entries removed (the translator before this rule) +the program is refused with "s_sext_i32_i16". BCNT emits countbits and the SCC of its result, and is refused without +its SCA entry; BCNTMASK is refused ("lane mask"). --write keeps the programs for mesh_work/difftest.py. +""" +import os +import re +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 +from startup_mesh_exec_restore_check import I # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +def translate(path, prelude=''): + child = ('import sys; sys.path[:0] = [%r, %r]\n' + 'import gfx2hlsl as G, mesh2hlsl as M\n%s\n' + 'code = open(sys.argv[1], "rb").read()\n' + 'try:\n' + ' p = M.MeshPipeline(code, None, M.synth_root(code), user_sgpr=16)\n' + ' sys.stdout.write("OK\\n" + p.hlsl_ms())\n' + 'except G.Unsupported as e:\n' + ' sys.stdout.write("REFUSED %%s\\n" %% e)\n' + % (os.path.join(HERE, '..', 'tools'), os.path.join(HERE, '..', 'tools', 'startup'), prelude)) + r = subprocess.run([sys.executable, '-B', '-c', child, path], capture_output=True, text=True) + return 'CRASH ' + (r.stderr.strip().splitlines() or ['?'])[-1] if r.returncode else r.stdout + + +def hlsl_eval(expr, x): + """Evaluate the emitted `uint(int(sN << k) >> k)` for the 32-bit value x (int shifts are arithmetic in HLSL).""" + m = re.fullmatch(r'uint\(int\(\(?s\d+\)? << (\d+)\) >> (\d+)\)', expr) + if not m or m.group(1) != m.group(2): + return None + k = int(m.group(1)) + v = (x << k) & 0xffffffff + v = v - (1 << 32) if v & 0x80000000 else v + return (v >> k) & 0xffffffff + + +PROGRAMS = { + 'sext': E.PROLOGUE + [ + I('s_add_u32 s24, s22, 0x7ff0', 'sop2', 's_add_u32', d=24, s0='s22', s1='0x7ff0'), + I('s_sext_i32_i16 s25, s24', 'sop1', 's_sext_i32_i16', d=25, s0='s24'), + I('s_add_u32 s26, s22, 0x70', 'sop2', 's_add_u32', d=26, s0='s22', s1='0x70'), + I('s_sext_i32_i8 s27, s26', 'sop1', 's_sext_i32_i8', d=27, s0='s26'), + I('v_mov_b32_e32 v1, s25', 'vop1', 'v_mov_b32_e32', d=1, s0='s25'), + I('v_mov_b32_e32 v4, s27', 'vop1', 'v_mov_b32_e32', d=4, s0='s27')] + E.EPILOGUE, + 'bcnt': E.PROLOGUE + [ + I('s_or_b32 s24, s22, 0xf00', 'sop2', 's_or_b32', d=24, s0='s22', s1='0xf00'), + I('s_bcnt1_i32_b32 s25, s24', 'sop1', 's_bcnt1_i32_b32', d=25, s0='s24'), + I('s_and_b32 s27, s22, 0x100', 'sop2', 's_and_b32', d=27, s0='s22', s1='0x100'), + I('s_bcnt1_i32_b32 s28, s27', 'sop1', 's_bcnt1_i32_b32', d=28, s0='s27'), + I('s_cselect_b32 s26, 7, 9', 'sop2', 's_cselect_b32', d=26, s0='7', s1='9'), + I('s_lshl_b32 s29, s25, 16', 'sop2', 's_lshl_b32', d=29, s0='s25', s1='16'), + I('v_mov_b32_e32 v1, s29', 'vop1', 'v_mov_b32_e32', d=1, s0='s29'), + I('v_mov_b32_e32 v4, s26', 'vop1', 'v_mov_b32_e32', d=4, s0='s26')] + E.EPILOGUE, + 'bcntmask': E.PROLOGUE + [ + I('v_cmp_gt_u32_e64 s30, s21, v0', 'vop3', 'v_cmp_gt_u32_e64', d=30, s0='s21', s1='v0'), + I('s_bcnt1_i32_b32 s25, s30', 'sop1', 's_bcnt1_i32_b32', d=25, s0='s30'), + I('v_mov_b32_e32 v1, s25', 'vop1', 'v_mov_b32_e32', d=1, s0='s25')] + E.EPILOGUE, +} + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_salu') + os.makedirs(out_dir, exist_ok=True) + for name, items in PROGRAMS.items(): + code, texts = E.assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = translate(path) + if name == 'bcnt': + line = re.search(r'^\s*s25 = (.*);', on, re.M) if on.startswith('OK') else None + check('bcnt: translates, s25 = countbits(...)', bool(line) and line.group(1).startswith('countbits('), on[:3000]) + check('bcnt: SCC of the second count is set from its result', 'scc = (s28 != 0);' in on or 'scc = s28 != 0;' in on + or re.search(r'scc = .*countbits', on) is not None, on[:3000]) + off = translate(path, "del G.SCA['s_bcnt1_i32_b32']") + check('bcnt: negative control (no SCA entry) refuses s_bcnt1_i32_b32', + off.startswith('REFUSED') and 's_bcnt1_i32_b32' in off.splitlines()[0], off[:200]) + continue + if name == 'bcntmask': + check('bcntmask: refused (a count of a lane mask)', on.startswith('REFUSED') and 'lane mask' in on.splitlines()[0], + on[:200]) + continue + check('sext: translates', on.startswith('OK'), on[:300]) + e16 = re.search(r'^\s*s25 = (uint\(.*\));', on, re.M) + e8 = re.search(r'^\s*s27 = (uint\(.*\));', on, re.M) + check('sext: s25 / s27 are the arithmetic-shift forms', bool(e16 and e8), on[:3000]) + if e16 and e8: + want16 = [0x7ff0, 0xffff8004, 0xffff8018, 0xffff802c] + want8 = [0x70, 0xffffff84, 0xffffff98, 0xffffffac] + got16 = [hlsl_eval(e16.group(1), t + 0x7ff0) for t in (0, 20, 40, 60)] + got8 = [hlsl_eval(e8.group(1), t + 0x70) for t in (0, 20, 40, 60)] + check('sext: s_sext_i32_i16 gives %s' % [hex(w) for w in want16], got16 == want16, + '%s from %s' % (got16, e16.group(1))) + check('sext: s_sext_i32_i8 gives %s' % [hex(w) for w in want8], got8 == want8, + '%s from %s' % (got8, e8.group(1))) + off = translate(path, "del G.SCA['s_sext_i32_i16'], G.SCA['s_sext_i32_i8']") + check('sext: negative control (no SCA entries) refuses s_sext_i32_i16', + off.startswith('REFUSED') and 's_sext_i32_i16' in off.splitlines()[0], off[:200]) + print('programs written to %s (difftest: python -B difftest.py --program <dir>/sext.bin)' % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_spi_input_check.py b/tests/startup_mesh_spi_input_check.py new file mode 100644 index 0000000000..ca8e715319 --- /dev/null +++ b/tests/startup_mesh_spi_input_check.py @@ -0,0 +1,116 @@ +"""SPI pixel inputs in mesh pipelines, and the position inputs POS_X/Y/Z/W_FLOAT (gfx2hlsl spi_inputs/spi_reads). + +The mapping of entry VGPRs to SPI inputs (ps_input_layout, Mesa ac_shader_util.c order) used to live in +G.Pipeline.__init__, which MeshPipeline does not call, so a mesh pair's pixel stage refused every SPI input read. +Both pipelines now call the shared Pipeline.spi_inputs / spi_reads. + +Synthetic pixel stage `exp mrt0 vA, vB, vC, vD done vm` (entry reads only); the mesh stage is a stub (this checks +the pixel stage). ENA 0x8c02 is a layout that enables all three position forms: persp_center v0-v1, +pos_z_float v2, pos_w_float v3, pos_fixed_pt v4. +POS_W_FLOAT is SV_Position.w: Mesa ac_nir_lower_intrinsics_to_args.c loads frag_coord_w_rcp from it, +nir_builder.c sets gl_FragCoord.w = frcp(frag_coord_w_rcp), and vkd3d-shader spirv.c (frag_coord_fixup) gives +D3D SV_Position.w = 1 / gl_FragCoord.w. + +Controls: without ENA the mesh translate_to refuses the read (the old behaviour); the barycentric persp_center read +as a value is refused; with a per-sample barycentric enabled the position read is refused; the draw pipeline lowers +the same inputs. translate_request passes req_<key>.psin through (translate_to replaced by a recorder). +""" +import os +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import VS_WORDS, root_blob # noqa: E402 + + +def pixel_words(a, b, c, d): + return struct.pack('<III', 0xf800180f, a | b << 8 | c << 16 | d << 24, 0xbf810000) + + +class StubMesh: + def __init__(self, pipe, code): + self.exports = {'pos': ['0'] * 4} + self.exported_prim = True + + def body(self): + return [] + + +def mesh(ps, masks): + saved = M.MeshStage + M.MeshStage = StubMesh + try: + return M.MeshPipeline(b'', ps, root_blob(), ps_hw_inputs=masks) + finally: + M.MeshStage = saved + + +def refused(ps, masks, text): + try: + pipe = mesh(ps, masks) + if pipe.ps_entry_reads: # what mesh2hlsl.translate_to refuses + raise G.Unsupported('pixel stage reads entry VGPR (an SPI input; layout not in the request)') + pipe.hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (text, str(error)) + return + raise AssertionError('accepted %s' % (masks,)) + + +def main(): + ps = pixel_words(2, 3, 4, 4) + assert G.decode(ps)[0][3] == 'exp mrt0 v2, v3, v4, v4 done vm', G.decode(ps)[0][3] + assert G.ps_input_layout(0x8c02, 0x8c02) == {0: 1, 1: 1, 2: 10, 3: 11, 4: 15} + hlsl = mesh(ps, (0x8c02, 0x8c02)).hlsl_ps() + for line in (' v2 = U(i.pos.z); // SPI input pos_z_float', ' v3 = U(i.pos.w); // SPI input pos_w_float', + ' v4 = (uint(i.pos.x) & 0xffffu) | ((uint(i.pos.y) & 0xffffu) << 16);', + ' o.mrt0 = float4(F(v2), F(v3), F(v4), F(v4));'): + assert line in hlsl.split('\n'), (line, hlsl) + # x and y (ENA 0x0300: pos_x_float v0, pos_y_float v1), in the draw pipeline too + for build in (lambda p, m: mesh(p, m), lambda p, m: G.Pipeline(VS_WORDS, p, root_blob(), ps_hw_inputs=m)): + text = build(pixel_words(0, 1, 1, 0), (0x0300, 0x0300)).hlsl_ps() + assert ' v0 = U(i.pos.x); // SPI input pos_x_float' in text and ' v1 = U(i.pos.y); // SPI input pos_y_float' in text, text + compiled = 'dxc not found' + if os.path.isfile(M.DXC): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'ps.hlsl') + open(path, 'w').write(hlsl) + r = subprocess.run([M.DXC, '-nologo', '-T', 'ps_6_0', '-E', 'main', '-Fo', path + '.cso', path], + capture_output=True, text=True) + assert r.returncode == 0, r.stderr + compiled = 'dxc ps_6_0 ok' + # controls + refused(ps, None, 'layout not in the request') + refused(pixel_words(0, 0, 0, 0), (0x8c02, 0x8c02), 'persp_center (v0) at 0x0: not lowered') + refused(pixel_words(4, 4, 4, 4), (0x8c03, 0x8c03), 'per-sample barycentrics enabled (0x8c03)') + + # translate_request: req_<key>.psin reaches translate_to + seen = [] + saved_to, saved_is = M.translate_to, M.is_mesh + M.translate_to = lambda out, key, ms, p, root, **k: seen.append(k.get('ps_hw_inputs')) or 'recorded' + M.is_mesh = lambda code: code == b'MESH' + try: + with tempfile.TemporaryDirectory() as tmp: + base = os.path.join(tmp, 'req_%016x' % 1) + for ext, blob in (('.a', b'MESH'), ('.b', ps), ('.root', root_blob())): + open(base + ext, 'wb').write(blob) + assert M.translate_request(tmp, 1) == 'recorded' and seen[-1] is None, seen + with open(base + '.psin', 'w', newline='\n') as f: + f.write('spi_ps_input 1 00008c02 00008c02\n') + assert M.translate_request(tmp, 1) == 'recorded' and seen[-1] == (0x8c02, 0x8c02), seen + with open(base + '.psin', 'w', newline='\n') as f: + f.write('spi_ps_input 1 8c02 8c02\n') + assert M.translate_request(tmp, 1) == 'unsupported: invalid SPI input file' + finally: + M.translate_to, M.is_mesh = saved_to, saved_is + print('mesh SPI inputs: pos_z/pos_w/pos_fixed_pt (ENA 0x8c02) and pos_x/pos_y lowered in mesh and draw ' + 'pipelines; %s; 3 refusals; .psin passed through translate_request' % compiled) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_mesh_spill_check.py b/tests/startup_mesh_spill_check.py new file mode 100644 index 0000000000..ea2d32a41c --- /dev/null +++ b/tests/startup_mesh_spill_check.py @@ -0,0 +1,167 @@ +"""Check the SGPR spill lowering of tools/startup/mesh2hlsl.py (MeshStage.lower_spills): v_writelane_b32 / +v_readlane_b32 with a constant lane on a VGPR used for nothing else are per-wave scalar slots. + +usage: startup_mesh_spill_check.py [--write <dir>] + +Hand-assembled gfx1013 NGG programs (no title bytes), built with the encoder of tests/startup_mesh_exec_restore_check.py +(opcode numbers found by decoding with tools/disasm_rdna2.py; the decoded text is compared with the intended text). +Same prologue: per group g, N = 40 + 60 * (g & 1) (wave 1 has no lane with v0 < N when N = 40), T = 20 * (g & 3), +s23 = 10, v1 = 5, v4 = 0; the epilogue exports (v1, v0, v4, v0) as param0. + +Hardware meaning (LLVM VOP2Instructions.td: V_READLANE_B32 / V_WRITELANE_B32 "do not read the exec mask", Uses = []; +V_WRITELANE_B32 ties $vdst = $vdst_in, so the other lanes keep their value; LLVM SIRegisterInfo::spillSGPR spills a +scalar register to one lane per 32-bit part with an immediate lane index): lane k of the spill VGPR is one value per +wave, written and read whatever exec is. + + SPILL32 (accept): s24 = 3 * T; lane 5 = s24; lane 6 = 7; s24 = 0; s25 = lane 5; s26 = lane 6; v1 = s25; v4 = s26. + expected per lane: v1 = 3 * T, v4 = 7 + SPILLEXEC (accept): exec = v0 < N; s[30:31] = exec; execz -> AFTER; lanes 0, 1 = s30, s31; s[30:31] = 0; + exec &= v0 < T; v1 = 9; s30, s31 = lanes 0, 1; exec = s[30:31]; v4 = 7. + expected: v1 = 9 if v0 < min(N, T) else 5; v4 = 7 if v0 < N else 0 + SPILLPAIR (accept): s24 = 3T, s25 = T + 1; lanes 2, 3 = s24, s25 (one fused 64-bit spill); s[24:25] = 0; + s26, s27 = lanes 2, 3; v1 = s26; v4 = s27. expected: v1 = 3T, v4 = T + 1 + SPILLHALVES (accept): as SPILLEXEC with a label between the two reloads, so they stay two 32-bit moves + (s30 = lane 0, s31 = lane 1) and exec is restored from a pair rebuilt half by half. expected as SPILLEXEC + SPILLWAVE (accept): lane 2 = s23 (10); exec = v0 < N; execz -> J; lane 2 = 11; J: exec = -1; s25 = lane 2; v1 = s25. + expected: v1 = 11 in a wave with a lane v0 < N, else 10 (the slot is per wave: wave 1 of an even group + skips the write) + DATAUSE (refuse): lane 0 = s23, then v_mov_b32 v1, v40 reads the spill VGPR as per-lane data. + LANESGPR (refuse): the lane select is s22, not a constant. + UNWRITTEN (refuse): lane 3 is written only when s22 != 0; the read after the join can see an unwritten lane. + VCCHALF (refuse): vcc_lo spilled without vcc_hi (half of a 64-bit lane mask). + SPLITPAIR (refuse): as SPILLEXEC, but the high half is reloaded into s33: exec = s[30:31] is no longer the saved + mask, and the exec rule refuses it. + +Checks: each program decodes to its intended text; the accepted ones translate (SPILLEXEC with the restore +`exec = (s30) & 1`, SPILLWAVE through the group-uniform branch x2w_any) and are refused again with +X2W_MESH_SPILLS=0 (negative control: v_writelane_b32 has no lowering then); the refused ones are refused with the +expected reason with the lowering on. --write keeps the programs (<dir>/<name>.bin) for the differential test +(mesh_work/difftest.py <bin> <harness>). +""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 (encoder, prologue, epilogue, translate()) +from startup_mesh_exec_restore_check import I # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +def WL(v, s, lane): + return I('v_writelane_b32 v%d, %s, %s' % (v, s, lane), 'vop3', 'v_writelane_b32', d=v, s0=s, s1=str(lane)) + + +def RL(s, v, lane): + return I('v_readlane_b32 s%d, v%d, %s' % (s, v, lane), 'vop3', 'v_readlane_b32', d=s, s0='v%d' % v, s1=str(lane)) + + +def MOVS(d, s): + return I('s_mov_b32 s%d, %s' % (d, s), 'sop1', 's_mov_b32', d=d, s0=s) + + +def VMOV(d, s): + return I('v_mov_b32_e32 v%d, %s' % (d, s), 'vop1', 'v_mov_b32_e32', d=d, s0=s) + + +EXECZ_AFTER = ('s_cbranch_execz AFTER', 'execz') +CLEAR30 = I('s_mov_b64 s[30:31], 0', 'sop1', 's_mov_b64', d=30, s0='0') +P, EP = E.PROLOGUE, E.EPILOGUE +PROGRAMS = { + 'spill32': ('ok', P + [I('s_mul_i32 s24, s22, 3', 'sop2', 's_mul_i32', d=24, s0='s22', s1='3'), + WL(40, 's24', 5), WL(40, '7', 6), MOVS(24, '0'), RL(25, 40, 5), RL(26, 40, 6), + VMOV(1, 's25'), VMOV(4, 's26')] + EP), + 'spillpair': ('ok', P + [I('s_mul_i32 s24, s22, 3', 'sop2', 's_mul_i32', d=24, s0='s22', s1='3'), + I('s_add_u32 s25, s22, 1', 'sop2', 's_add_u32', d=25, s0='s22', s1='1'), + WL(40, 's24', 2), WL(40, 's25', 3), I('s_mov_b64 s[24:25], 0', 'sop1', 's_mov_b64', d=24, + s0='0'), + RL(26, 40, 2), RL(27, 40, 3), VMOV(1, 's26'), VMOV(4, 's27')] + EP), + 'spillexec': ('ok', P + [E.CMPX_N, E.SAVE, EXECZ_AFTER, WL(40, 's30', 0), WL(40, 's31', 1), CLEAR30, E.CMPX_T, + E.V1_9, RL(30, 40, 0), RL(31, 40, 1), E.RESTORE, E.V4_7] + EP), + 'spillwave': ('ok', P + [WL(40, 's23', 2), E.CMPX_N, ('s_cbranch_execz J', 'execz'), WL(40, '11', 2), ('J:', None), + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), RL(25, 40, 2), + VMOV(1, 's25')] + EP), + 'datause': ('also used by v_mov_b32', P + [WL(40, 's23', 0), VMOV(1, 'v40')] + EP), + 'lanesgpr': ('is not a constant lane', P + [WL(40, 's23', 's22'), RL(25, 40, 0), VMOV(1, 's25')] + EP), + 'unwritten': ('which no v_writelane_b32 writes', P + [ + I('s_cmp_eq_u32 s22, 0', 'sopc', 's_cmp_eq_u32', s0='s22', s1='0'), ('s_cbranch_scc1 J', 'scc1'), + WL(40, 's23', 3), ('J:', None), RL(25, 40, 3), VMOV(1, 's25')] + EP), + 'vcchalf': ('v_writelane_b32 of vcc_lo alone', P + [ + VMOV(6, 's22'), I('v_cmp_lt_u32_e32 vcc_lo, 30, v6', 'vopc', 'v_cmp_lt_u32_e32', s0='30', s1='v6'), + WL(40, 'vcc_lo', 0), RL(25, 40, 0), VMOV(1, 's25')] + EP), + 'spillhalves': ('ok', P + [E.CMPX_N, E.SAVE, EXECZ_AFTER, WL(40, 's30', 0), WL(40, 's31', 1), CLEAR30, E.CMPX_T, + E.V1_9, RL(30, 40, 0), ('K:', None), RL(31, 40, 1), E.RESTORE, E.V4_7] + EP), + 'splitpair': ('exec written by s_mov_b64 inside the per-lane skipped range', P + [ + E.CMPX_N, E.SAVE, EXECZ_AFTER, WL(40, 's30', 0), WL(40, 's31', 1), CLEAR30, E.CMPX_T, E.V1_9, + RL(30, 40, 0), RL(33, 40, 1), E.RESTORE, E.V4_7] + EP), +} +# the reason the translator gives without the lowering (the base has no v_writelane_b32 / v_readlane_b32) +NO_LOWERING = 'REFUSED v_writelane_b32' +NO_EXEC = 'REFUSED exec written by s_mov_b64 inside the per-lane skipped range' + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_spill') + os.makedirs(out_dir, exist_ok=True) + for name, (want, items) in PROGRAMS.items(): + code, texts = E.assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = E.translate(path, {'X2W_MESH_SPILLS': '1'}) + if want == 'ok': + check('%s: translates with the lowering on' % name, on.startswith('OK'), on[:300]) + check('%s: no v_writelane / v_readlane left in the HLSL' % name, 'lane_b32' not in on, '') + if name == 'spill32': + # (lane 6 holds a constant: the base translator's constant tracking carries it through the slot) + check('spill32: slots s1005 / s1006 assigned and read back', + 's1005 = s24;' in on and 's25 = s1005;' in on and 's1006 = 0x00000007u;' in on + and 's26 = 0x00000007u;' in on, on[:2000]) + if name == 'spillpair': + # a plain data pair, fused into one 64-bit spill and reload: both words survive (MeshStage.scalar_inner + # with X2W_MESH_DATA_PAIRS on; off, the high word is lost and the low word cut to bit 0) + check('spillpair: s[24:25] spilled to s[1002:1003] and reloaded into s[26:27] as two words', + 's1002 = s24;' in on and 's1003 = s25;' in on and 's26 = s1002;' in on and 's27 = s1003;' in on, + on[:3000]) + poff = E.translate(path, {'X2W_MESH_DATA_PAIRS': '0'}) + check('spillpair: negative control X2W_MESH_DATA_PAIRS=0 cuts the pair to the lane bit', + 's1002 = (s24) & 1;' in poff, poff[:300]) + if name == 'spillexec': + check('spillexec: the 64-bit spill and reload are one move each, exec restored from s30', + 's1000 = (s30) & 1;' in on and 's30 = (s1000) & 1;' in on and 'exec = (s30) & 1;' in on, + on[:3000]) + if name == 'spillwave': + check('spillwave: the slot written in the skipped range goes through the group-uniform branch', + 'x2w_any' in on and 's1002 = ' in on, on[:3000]) + off = E.translate(path, {'X2W_MESH_SPILLS': '0'}) + # without the lowering SPILLEXEC stops where the class's programs stopped: the skipped-range check sees + # the restore from s[30:31], which the unlowered v_readlane does not make a copy of the saved mask + expect = NO_EXEC if name in ('spillexec', 'spillhalves') else NO_LOWERING + check('%s: negative control X2W_MESH_SPILLS=0 refuses again (%s)' % (name, expect), + off.splitlines()[0].startswith(expect), off[:200]) + else: + check('%s: refused (%s) with the lowering on' % (name, want), + on.startswith('REFUSED') and want in on.splitlines()[0], on[:200]) + print('programs written to %s (difftest: python -B difftest.py <dir>/spillexec.bin <harness> --groups 4 --seed 1)' + % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_vcc_data_check.py b/tests/startup_mesh_vcc_data_check.py new file mode 100644 index 0000000000..bd6a6a691b --- /dev/null +++ b/tests/startup_mesh_vcc_data_check.py @@ -0,0 +1,169 @@ +"""Check the vcc-as-data rule of tools/startup/mesh2hlsl.py (MeshStage.lower_vcc_data): where vcc holds no lane mask, +the wave64 program uses VCC_LO / VCC_HI as the ordinary SGPRs 106 / 107, and the translation names them so. + +usage: startup_mesh_vcc_data_check.py [--write <dir>] + +Hand-assembled gfx1013 NGG programs (no title bytes), built with the encoder of tests/startup_mesh_exec_restore_check.py +(opcode numbers found by decoding with tools/disasm_rdna2.py; the decoded text is compared with the intended text). +Prologue as there: per group g, N = 40 + 60 * (g & 1), T = 20 * (g & 3), s23 = 10, v1 = 5, v4 = 0; the epilogue +exports (v1, v0, v4, v0) as param0. + +Hardware meaning (RDNA 2 ISA scalar operand encoding: 106 = VCC_LO, 107 = VCC_HI; a VOPC / VOP3 compare writes the +whole 64-bit VCC; s_mov_b32 to VCC_LO leaves VCC_HI as it was). + + VCCDATA (accept): vcc_lo = T + 7; vcc_hi = 3; v1 = vcc_lo; v4 = vcc_hi. Then a lane mask in vcc: + vcc = v0 < s23; v4 = vcc ? v4 : 9. expected: v1 = T + 7; v4 = 3 if v0 < 10 else 9 + VCCSPILL (accept): vcc_lo = T; vcc_hi = 5; both spilled to lanes 0, 1 of v40; vcc = 0; s25, s26 = lanes 0, 1; + v1 = s25; v4 = s26. expected: v1 = T, v4 = 5 + VCCZERO (accept): vcc = (v0 < N) (a mask, used by v_cndmask); exec = v0 < N; execz -> J; vcc_lo = T; J: v1 = vcc_lo. + The mask reaches the data use only along the taken execz edge, where no lane is active. + expected: v1 = T if v0 < N else 5 (v4 = 7 if v0 < N else 0 from the cndmask) + VCCLIVE (refuse): as VCCZERO with a uniform s_cbranch_scc1 (T == 0) instead of the execz: the mask reaches the + 32-bit read of vcc_lo on a path with lanes on. + VCCMIX (refuse): vcc = (v0 < N), then v1 = vcc_hi (the high half of a lane mask read as a number). + VCCDEAD (accept): as VCCMIX with `s_lshl_b32 s27, vcc_lo, 2` instead, and nothing reads s27 or its SCC: the web + keeps `vcc` (the cut value is never observed). expected as VCCZERO's v4; v1 = 5. + VCCDEADREG (refuse): VCCDEAD, then v1 = s27. VCCDEADSCC (refuse): VCCDEAD, then s_cselect reads its SCC. + (The shape of program C in tests/startup_mesh_lane_scc_check.py; refused at add01075 with the rule on.) + +Checks: decode; VCCDATA / VCCSPILL / VCCZERO translate with s106 / s107 and give the base's form again with +X2W_MESH_VCC_DATA=0 (negative control: `vcc = (...) & 1`, i.e. the 32-bit value cut to the lane bit, or the refusal +of vcc_hi); VCCLIVE / VCCMIX are refused with the reason. --write keeps the programs for the differential test +(mesh_work/difftest.py; with X2W_MESH_VCC_DATA=0 VCCDATA is refused (vcc_hi) and the difftest of VCCZERO must +mismatch). +""" +import os +import struct +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 (encoder, prologue, epilogue, translate()) +from startup_mesh_exec_restore_check import I # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +def WL(v, s, lane): + return I('v_writelane_b32 v%d, %s, %s' % (v, s, lane), 'vop3', 'v_writelane_b32', d=v, s0=s, s1=str(lane)) + + +def RL(s, v, lane): + return I('v_readlane_b32 s%d, v%d, %s' % (s, v, lane), 'vop3', 'v_readlane_b32', d=s, s0='v%d' % v, s1=str(lane)) + + +def VMOV(d, s): + return I('v_mov_b32_e32 v%d, %s' % (d, s), 'vop1', 'v_mov_b32_e32', d=d, s0=s) + + +VCCLO_T7 = I('s_add_u32 vcc_lo, s22, 7', 'sop2', 's_add_u32', d=106, s0='s22', s1='7') +VCCLO_T = I('s_mov_b32 vcc_lo, s22', 'sop1', 's_mov_b32', d=106, s0='s22') +CMP_N = I('v_cmp_gt_u32_e32 vcc_lo, s21, v0', 'vopc', 'v_cmp_gt_u32_e32', s0='s21', s1='v0') +P, EP = E.PROLOGUE, E.EPILOGUE + + +def vop2(text, mnemonic, d, s0, s1): + """VOP2 (v_cndmask_b32_e32: vdst = vcc ? vsrc1 : src0).""" + def make(): + fields = {'d': d, 's0': E.src(s0)[0], 's1': E.src(s1)[0]} + for op in range(64): + w = (op << 25) | (fields['d'] << 17) | ((fields['s1'] - 256) << 9) | fields['s0'] + code = struct.pack('<I', w) + b'\0' * 8 + try: + _, name, _, _ = E.D.decode_instruction(code, 0) + except Exception: + continue + if name == mnemonic: + return [w] + raise KeyError(mnemonic) + return (text, make) + + +V7 = VMOV(7, '7') +CND_V4 = vop2('v_cndmask_b32_e32 v4, 9, v4, vcc_lo', 'v_cndmask_b32_e32', 4, '9', 'v4') +CND_V4_7 = vop2('v_cndmask_b32_e32 v4, 0, v7, vcc_lo', 'v_cndmask_b32_e32', 4, '0', 'v7') +LSHL27 = I('s_lshl_b32 s27, vcc_lo, 2', 'sop2', 's_lshl_b32', d=27, s0='vcc_lo', s1='2') +CMP_10 = I('v_cmp_gt_u32_e32 vcc_lo, s23, v0', 'vopc', 'v_cmp_gt_u32_e32', s0='s23', s1='v0') +PROGRAMS = { + 'vccdata': ('ok', P + [VCCLO_T7, I('s_mov_b32 vcc_hi, 3', 'sop1', 's_mov_b32', d=107, s0='3'), + VMOV(1, 'vcc_lo'), VMOV(4, 'vcc_hi'), CMP_10, CND_V4] + EP), + 'vccspill': ('ok', P + [VCCLO_T, I('s_mov_b32 vcc_hi, 5', 'sop1', 's_mov_b32', d=107, s0='5'), + WL(40, 'vcc_lo', 0), WL(40, 'vcc_hi', 1), + I('s_mov_b64 vcc, 0', 'sop1', 's_mov_b64', d=106, s0='0'), + RL(25, 40, 0), RL(26, 40, 1), VMOV(1, 's25'), VMOV(4, 's26')] + EP), + 'vcczero': ('ok', P + [CMP_N, V7, CND_V4_7, E.CMPX_N, ('s_cbranch_execz J', 'execz'), VCCLO_T, ('J:', None), + VMOV(1, 'vcc_lo')] + EP), + 'vcclive': ('vcc used as a lane mask', P + [CMP_N, V7, CND_V4_7, + I('s_cmp_eq_u32 s22, 0', 'sopc', 's_cmp_eq_u32', s0='s22', s1='0'), + ('s_cbranch_scc1 J', 'scc1'), VCCLO_T, ('J:', None), + VMOV(1, 'vcc_lo')] + EP), + 'vccmix': ('vcc used as a lane mask', P + [CMP_N, V7, CND_V4_7, VMOV(1, 'vcc_hi')] + EP), + # a lane mask read as a 32-bit number by a scalar op whose result nothing reads (s27 and its SCC are dead) + 'vccdead': ('ok', P + [CMP_N, V7, CND_V4_7, LSHL27] + EP), + 'vccdeadreg': ('vcc used as a lane mask', P + [CMP_N, V7, CND_V4_7, LSHL27, VMOV(1, 's27')] + EP), + 'vccdeadscc': ('vcc used as a lane mask', P + [CMP_N, V7, CND_V4_7, LSHL27, + I('s_cselect_b32 s28, 1, 0', 'sop2', 's_cselect_b32', d=28, + s0='1', s1='0'), VMOV(1, 's28')] + EP), +} + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_vcc_data') + os.makedirs(out_dir, exist_ok=True) + for name, (want, items) in PROGRAMS.items(): + code, texts = E.assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = E.translate(path, {'X2W_MESH_VCC_DATA': '1'}) + off = E.translate(path, {'X2W_MESH_VCC_DATA': '0'}) + if want == 'ok': + check('%s: translates with the rule on' % name, on.startswith('OK'), on[:300]) + if name == 'vccdata': + check('vccdata: vcc_lo / vcc_hi are s106 / s107, the later lane mask stays vcc', + 's106 = s22 + 0x00000007u;' in on and 'v1 = s106;' in on and 's107 = 0x00000003u;' in on + and 'v4 = 0x00000003u;' in on and 'vcc = ((0x0000000au > v0)' in on, on[:4000]) + check('vccdata: negative control X2W_MESH_VCC_DATA=0 gives the base form (refused or cut to the bit)', + off.startswith('REFUSED') or off.startswith('CRASH') or 'vcc = (s22 + 0x00000007u) & 1;' in off, + off[:300]) + elif name == 'vccspill': + # the fused 64-bit spill of s[106:107] copies both words (not a lane mask: no `& 1`) + check('vccspill: the vcc pair is spilled and reloaded through s[1000:1001] as two words', + 's1000 = s106;' in on and 's1001 = 0x00000005u;' in on and 's25 = s1000;' in on + and 's26 = s1001;' in on, on[:4000]) + pairs_off = E.translate(path, {'X2W_MESH_DATA_PAIRS': '0'}) + check('vccspill: negative control X2W_MESH_DATA_PAIRS=0 cuts the 64-bit data move to the lane bit', + 's1000 = (s106) & 1;' in pairs_off, pairs_off[:300]) + check('vccspill: negative control X2W_MESH_VCC_DATA=0 refuses (vcc_hi as data)', + off.startswith('REFUSED') or off.startswith('CRASH'), off[:300]) + elif name == 'vccdead': + check('vccdead: the mask keeps vcc (no s106 rename)', 's106' not in on and 'vcc = ' in on, on[:4000]) + else: + check('vcczero: the data def is s106, the mask stays vcc', 's106 = s22;' in on and 'v1 = s106;' in on, + on[:4000]) + check('vcczero: negative control X2W_MESH_VCC_DATA=0 cuts the value to the lane bit', + 'vcc = (s22) & 1;' in off, off[:300]) + else: + check('%s: refused (%s) with the rule on' % (name, want), + on.startswith('REFUSED') and want in on.splitlines()[0], on[:200]) + print('programs written to %s (difftest: python -B difftest.py --program <dir>/vccdata.bin)' % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_vcc_vote_check.py b/tests/startup_mesh_vcc_vote_check.py new file mode 100644 index 0000000000..39e98cdabf --- /dev/null +++ b/tests/startup_mesh_vcc_vote_check.py @@ -0,0 +1,30 @@ +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools/startup')) +import mesh2hlsl as M + + +def stage(joined): + vote = M.MeshStage.__new__(M.MeshStage) + branch = ('branch', 'lane != 0', 3) + vote.lane_edges = {id(branch)} + vote.blocks = [ + (0, [], branch), + (1, [], ('jump', 4 if joined else 5)), + (3, [], None), + (4, [], ('barrier', 'vcc-vote')), + (5, [], ('end',)), + ] + return vote + + +if __name__ == '__main__': + stage(True).check_vote_participation({4}) + try: + stage(False).check_vote_participation({4}) + except M.Unsupported: + pass + else: + raise AssertionError('partial-wave vote accepted') + print('PASS: reconvergence and partial-wave bypass') diff --git a/tests/startup_mrt_wide_int_check.py b/tests/startup_mrt_wide_int_check.py new file mode 100644 index 0000000000..1235d4fb97 --- /dev/null +++ b/tests/startup_mrt_wide_int_check.py @@ -0,0 +1,59 @@ +"""Integer render targets with 32 bits per channel beyond R32: R32G32B32A32 / R32G32B32 / R32G32 _UINT and _SINT. + +Pure Python. The pixel fixture of tests/startup_mrt_check.py (v0..v3 = 1, 2, 0x7fc00001, 0x80000001, then +exp mrt0 v0, v1, v2, v3) is translated with each DXGI format as the slot-0 RTV. Expected: the 32-bit-per-channel +integer formats (3, 7, 17, 42 uint; 4, 8, 18, 43 sint) declare uint4 / int4 SV_Target0 and export the four +register words unconverted, exactly as the verified R32 forms do; narrower integer formats (12 R16G16B16A16_UINT, +30 R8G8B8A8_UINT, 57 R16_UINT, 14 R16G16B16A16_SINT) stay refused as "unverified". ASSUMED (not drawn): the colour +buffer stores the export words of these wider formats as it does for R32. +Negative control: the float target (2, R32G32B32A32_FLOAT) declares float4. +""" +import re +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import struct # noqa: E402 +from startup_mrt_check import FLOAT_WORDS # noqa: E402 +from startup_stream_check import gfx2hlsl as G # noqa: E402 +from startup_stream_draw_check import vop1 # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, root_blob # noqa: E402 + + +def pixel_words(values): + """startup_mrt_check.pixel's program without its container: v_mov_b32 vN, literal; exp mrt0 v0..v3 done vm.""" + words = [] + for reg, value in enumerate(values): + words += [vop1(1, reg, 255), value] + words += [0xf800180f, 0x03020100, 0xbf810000] + return struct.pack('<%dI' % len(words), *words) + + +def ps(fmt): + p = G.Pipeline(VS_WORDS, pixel_words(FLOAT_WORDS), root_blob(flags=0), rtv_formats=(fmt,)) + return p.hlsl_ps() + + +def main(): + for fmt, typ in ((3, 'uint4'), (7, 'uint4'), (17, 'uint4'), (42, 'uint4'), + (4, 'int4'), (8, 'int4'), (18, 'int4'), (43, 'int4')): + text = ps(fmt) + assert '%s mrt0 : SV_Target0;' % typ in text, (fmt, text) + line = [l.strip() for l in text.splitlines() if l.strip().startswith('o.mrt0 =')] + want = 'uint4(v0, v1, v2, v3)' + assert line == ['o.mrt0 = %s;' % (want if typ == 'uint4' else 'asint(%s)' % want)], (fmt, line) + for fmt in (12, 30, 57, 14): + try: + ps(fmt) + except G.Unsupported as error: + assert re.search(r'unverified [SU]INT RTV format %d' % fmt, str(error)), str(error) + else: + raise AssertionError('narrow integer format %d accepted' % fmt) + assert 'float4 mrt0 : SV_Target0;' in ps(2) + print('mrt_wide_int: formats 3/7/17/42 -> uint4 and 4/8/18/43 -> int4 with the raw words; 12/30/57/14 refused; ' + 'float control declares float4') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_pack_f16_check.py b/tests/startup_pack_f16_check.py new file mode 100644 index 0000000000..b577166f67 --- /dev/null +++ b/tests/startup_pack_f16_check.py @@ -0,0 +1,87 @@ +"""v_pack_b32_f16 (VOP3): 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 [14:11], abs [10:8], neg in word 1 [31:29]), names and +the printed op_sel / modifier forms asserted from the decoder. Measured forms: `v_pack_b32_f16 vD, vA, vB +op_sel:[1,0,0]` (14 title keys) and without op_sel (1). The emitted expression is evaluated in Python for every +op_sel[0..1] / neg / abs combination over sample register pairs and compared with a reference that selects the +half (op_sel[i] = high half of source i) and then applies abs (clear bit 15) and neg (flip bit 15). +Negative control: the halves swapped are caught. Refused: a destination op_sel bit, clamp. +""" +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): + return [0xd4000000 | 0x311 << 16 | clamp << 15 | opsel << 11 | absm << 8 | vdst, + (256 + s0) | (256 + s1) << 9 | neg << 29] + + +def one(words): + s = G.Stage(Pipe(), 'vs', b'') + s.lines, s.pc = [], 0 + _, n, 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): + out = [] + for i, x in enumerate((a, b)): + h = (x >> 16) & 0xffff if sel >> i & 1 else x & 0xffff + if absm >> i & 1: + h &= 0x7fff + if neg >> i & 1: + h ^= 0x8000 + out.append(h) + return out[0] | out[1] << 16 + + +def main(): + values = [0x00000000, 0x3c00bc00, 0x80017fff, 0xfc007e00, 0x12345678, 0xffff0001] + cases = 0 + for sel in range(4): + for absm in range(4): + for neg in range(4): + text, lines = one(vop3(3, 1, 2, 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: + assert ev(m.group(1), {'v1': a, 'v2': b}) == ref(a, b, sel, absm, neg), (text, hex(a), hex(b)) + cases += 1 + _, lines = one(vop3(3, 1, 2, 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) + for words, why in ((vop3(3, 1, 2, 4), 'form'), (vop3(3, 1, 2, clamp=1), 'modifier clamp')): + try: + one(words) + except G.Unsupported as error: + assert why in str(error), str(error) + else: + raise AssertionError('accepted: %s' % why) + print('pack_f16: %d (op_sel, abs, neg, value) cases match the reference; swapped halves caught; destination ' + 'op_sel and clamp refused' % cases) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_packed_position_check.py b/tests/startup_packed_position_check.py index 9836d28a5b..4f168c3f84 100644 --- a/tests/startup_packed_position_check.py +++ b/tests/startup_packed_position_check.py @@ -35,7 +35,15 @@ def main(dxc, renderer, adapter, fxc=None): ('wrong register', 1, (0x8002, 0x8002), False), ('packed position disabled', 1, (0x0100, 0x0100), False), ): - ps = compile_hlsl(compiler, kind, pixel_shader(reg, masks), 'ps', 'ps_' + profile, folder) + try: + text = pixel_shader(reg, masks) + except G.Unsupported as err: + # The translator maps every entry VGPR to its SPI input and refuses a read of one it does not + # lower (persp_center, an unallocated register): a stronger outcome than a wrong image. + assert not good and ('not lowered' in str(err) or 'past the SPI inputs' in str(err)), str(err) + print(f'{kind} {adapter} {label}: refused at translation ({err})') + continue + ps = compile_hlsl(compiler, kind, text, 'ps', 'ps_' + profile, folder) run = subprocess.run([renderer, adapter, '--startup-packed-position', vs, ps], capture_output=True, text=True) if run.returncode == 77: diff --git a/tests/startup_pipeline_state_local_check.cpp b/tests/startup_pipeline_state_local_check.cpp new file mode 100644 index 0000000000..56bca37ad5 --- /dev/null +++ b/tests/startup_pipeline_state_local_check.cpp @@ -0,0 +1,351 @@ +// Checks src/startup_stubs/pipeline_state_decode.h without a device: hand-built register words (field +// layouts of Mesa's gfx10.json) decoded to D3D12 depth-stencil, rasterizer and blend descriptions, +// the refusals, synthetic state blocks in both layouts, slot 55 records, the depth-target adjustments +// and the switches. No title data. +// +// --mutate winding: expects FACE 0 to mean clockwise front faces (the check must then fail). +// --mutate mesh-shift: expects mesh-layout fields at the vertex-layout offsets (must fail). +#include "startup_stubs/pipeline_state_decode.h" +#include "startup_stubs/state_block_blend.h" + +#include <cstdio> +#include <cstring> +#include <vector> + +namespace { +using namespace x2w_pipeline_state; +int failures, cases; +bool mutate_winding, mutate_shift; + +void check(bool ok, const char* name) +{ + ++cases; + if (!ok) { + std::printf("FAIL %s\n", name); + ++failures; + } +} + +// DB_DEPTH_CONTROL from its fields. +constexpr std::uint32_t depth_control(bool stencil, bool z, bool z_write, bool bounds, unsigned zfunc, bool backface, unsigned sfunc, + unsigned sfunc_bf) +{ + return std::uint32_t{stencil} | std::uint32_t{z} << 1 | std::uint32_t{z_write} << 2 | std::uint32_t{bounds} << 3 | (zfunc & 7) << 4 | + std::uint32_t{backface} << 7 | (sfunc & 7) << 8 | (sfunc_bf & 7) << 20; +} +constexpr std::uint32_t stencil_control(unsigned fail, unsigned zpass, unsigned zfail, unsigned fail_bf, unsigned zpass_bf, unsigned zfail_bf) +{ + return fail | zpass << 4 | zfail << 8 | fail_bf << 12 | zpass_bf << 16 | zfail_bf << 20; +} +constexpr std::uint32_t refmask(unsigned test, unsigned mask, unsigned write, unsigned opval) { return test | mask << 8 | write << 16 | opval << 24; } +constexpr std::uint32_t mode_cntl(bool cull_front, bool cull_back, bool face_cw, unsigned poly_mode, unsigned front_type, unsigned back_type, + bool offset_front, bool offset_back) +{ + return std::uint32_t{cull_front} | std::uint32_t{cull_back} << 1 | std::uint32_t{face_cw} << 2 | poly_mode << 3 | front_type << 5 | + back_type << 8 | std::uint32_t{offset_front} << 11 | std::uint32_t{offset_back} << 12 | 1u << 21; // MULTI_PRIM_IB_ENA +} + +void depth_stencil_cases() +{ + // Depth off: the function the word carries is ignored (canonical ALWAYS), stencil off. + auto d = decode_depth_stencil(depth_control(false, false, false, false, 1, true, 7, 7), 0, refmask(0, 0xff, 0, 1), refmask(0, 0xff, 0, 1)); + check(d.ok && !d.desc.DepthEnable && d.desc.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ZERO && d.desc.DepthFunc == D3D12_COMPARISON_FUNC_ALWAYS && + !d.desc.StencilEnable, "depth off"); + // Reversed depth: GEQUAL read-only. + d = decode_depth_stencil(depth_control(false, true, false, false, 6, true, 7, 7), 0, refmask(0, 0xff, 0, 1), refmask(0, 0xff, 0, 1)); + check(d.ok && d.desc.DepthEnable && d.desc.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ZERO && d.desc.DepthFunc == D3D12_COMPARISON_FUNC_GREATER_EQUAL, + "GEQUAL read"); + // Every compare function in order. + const D3D12_COMPARISON_FUNC funcs[8] = {D3D12_COMPARISON_FUNC_NEVER, D3D12_COMPARISON_FUNC_LESS, D3D12_COMPARISON_FUNC_EQUAL, + D3D12_COMPARISON_FUNC_LESS_EQUAL, D3D12_COMPARISON_FUNC_GREATER, D3D12_COMPARISON_FUNC_NOT_EQUAL, + D3D12_COMPARISON_FUNC_GREATER_EQUAL, D3D12_COMPARISON_FUNC_ALWAYS}; + for (unsigned f = 0; f < 8; ++f) { + d = decode_depth_stencil(depth_control(true, true, true, false, f, true, f, 7 - f), 0, refmask(0, 0xff, 0xff, 1), refmask(0, 0xff, 0xff, 1)); + check(d.ok && d.desc.DepthFunc == funcs[f] && d.desc.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ALL && d.desc.FrontFace.StencilFunc == funcs[f] && + d.desc.BackFace.StencilFunc == funcs[7 - f], "compare function order"); + } + // Stencil: replace on depth pass, both faces, masks. + d = decode_depth_stencil(depth_control(true, true, true, false, 6, true, 7, 7), stencil_control(0, 3, 0, 0, 3, 0), refmask(0, 0xff, 0xff, 1), + refmask(0, 0xff, 0xff, 1)); + check(d.ok && d.desc.StencilEnable && d.desc.StencilReadMask == 0xff && d.desc.StencilWriteMask == 0xff && + d.desc.FrontFace.StencilPassOp == D3D12_STENCIL_OP_REPLACE && d.desc.BackFace.StencilPassOp == D3D12_STENCIL_OP_REPLACE && + d.desc.FrontFace.StencilFailOp == D3D12_STENCIL_OP_KEEP && d.desc.FrontFace.StencilDepthFailOp == D3D12_STENCIL_OP_KEEP, + "stencil replace"); + // Every op with a D3D12 form, front fail / back depth-fail; the add / subtract ops by one. + const struct { unsigned op; D3D12_STENCIL_OP d3d; } ops[] = {{0, D3D12_STENCIL_OP_KEEP}, {1, D3D12_STENCIL_OP_ZERO}, + {3, D3D12_STENCIL_OP_REPLACE}, {5, D3D12_STENCIL_OP_INCR_SAT}, + {6, D3D12_STENCIL_OP_DECR_SAT}, {7, D3D12_STENCIL_OP_INVERT}, + {8, D3D12_STENCIL_OP_INCR}, {9, D3D12_STENCIL_OP_DECR}}; + for (const auto& o : ops) { + d = decode_depth_stencil(depth_control(true, false, false, false, 7, true, 2, 2), stencil_control(o.op, 0, 0, 0, 0, o.op), + refmask(0, 0x28, 0, 1), refmask(0, 0x28, 0, 1)); + check(d.ok && d.desc.FrontFace.StencilFailOp == o.d3d && d.desc.BackFace.StencilDepthFailOp == o.d3d && d.desc.StencilReadMask == 0x28 && + d.desc.StencilWriteMask == 0, "stencil op mapping"); + } + // No back-face state: back faces use the front state (the _BF words are ignored). + d = decode_depth_stencil(depth_control(true, false, false, false, 7, false, 3, 0), stencil_control(0, 8, 0, 9, 9, 9), refmask(0, 0x80, 0x80, 1), + refmask(0, 0, 0, 7)); + check(d.ok && d.desc.BackFace.StencilFunc == D3D12_COMPARISON_FUNC_LESS_EQUAL && d.desc.BackFace.StencilPassOp == D3D12_STENCIL_OP_INCR && + !d.masks_differ, "back faces follow the front"); + // Negative: ops without a form, add by two, colour writes on depth fail. + check(!decode_depth_stencil(depth_control(true, false, false, false, 7, true, 7, 7), stencil_control(2, 0, 0, 0, 0, 0), refmask(0, 0xff, 0xff, 1), + refmask(0, 0xff, 0xff, 1)).ok, "ONES refused"); + check(!decode_depth_stencil(depth_control(true, false, false, false, 7, true, 7, 7), stencil_control(0, 4, 0, 0, 4, 0), refmask(0, 0xff, 0xff, 1), + refmask(0, 0xff, 0xff, 1)).ok, "REPLACE_OP refused"); + check(!decode_depth_stencil(depth_control(true, false, false, false, 7, true, 7, 7), stencil_control(0, 8, 0, 0, 8, 0), refmask(0, 0xff, 0xff, 2), + refmask(0, 0xff, 0xff, 2)).ok, "add by two refused"); + check(!decode_depth_stencil(depth_control(true, false, false, false, 7, true, 7, 7), stencil_control(0, 0, 0, 0, 12, 0), refmask(0, 0xff, 0xff, 1), + refmask(0, 0xff, 0xff, 1)).ok, "back-face XOR refused"); + check(!decode_depth_stencil(depth_control(false, true, true, false, 6, false, 7, 7) | 1u << 30, 0, 0, 0).ok, "colour writes on depth fail refused"); + // An unusable op on a disabled stencil does not refuse the depth state. + check(decode_depth_stencil(depth_control(false, true, true, false, 1, true, 7, 7), stencil_control(2, 2, 2, 2, 2, 2), 0, 0).ok, + "ops of a disabled stencil ignored"); + // Flags. + d = decode_depth_stencil(depth_control(false, true, false, true, 3, false, 7, 7), 0, 0, 0); + check(d.ok && d.depth_bounds, "depth bounds flagged"); + d = decode_depth_stencil(depth_control(true, false, false, false, 7, true, 7, 7), 0, refmask(0, 0xff, 0xff, 1), refmask(0, 0x0f, 0xff, 1)); + check(d.ok && d.masks_differ && d.desc.StencilReadMask == 0xff, "back masks differ flagged, front kept"); +} + +void rasterizer_cases() +{ + const bool ccw_for_face0 = !mutate_winding; + auto r = decode_rasterizer(mode_cntl(false, false, false, 0, 2, 2, true, true), 0x00080000, 0, 0, 0, false); + check(r.ok && r.desc.CullMode == D3D12_CULL_MODE_NONE && (r.desc.FrontCounterClockwise != 0) == ccw_for_face0 && r.desc.DepthClipEnable && + r.desc.FillMode == D3D12_FILL_MODE_SOLID && r.desc.DepthBias == 0 && r.desc.SlopeScaledDepthBias == 0, "no cull, FACE 0"); + r = decode_rasterizer(mode_cntl(false, true, false, 0, 2, 2, true, true), 0x00080000, 0, 0, 0, false); + check(r.ok && r.desc.CullMode == D3D12_CULL_MODE_BACK, "cull back"); + r = decode_rasterizer(mode_cntl(true, false, false, 0, 2, 2, true, true), 0x00080000, 0, 0, 0, false); + check(r.ok && r.desc.CullMode == D3D12_CULL_MODE_FRONT, "cull front"); + r = decode_rasterizer(mode_cntl(false, true, true, 0, 2, 2, true, true), 0x00080000, 0, 0, 0, false); + check(r.ok && (r.desc.FrontCounterClockwise != 0) == !ccw_for_face0, "FACE 1"); + r = decode_rasterizer(mode_cntl(false, true, false, 0, 2, 2, true, true), 0x00080000, 0, 0, 0, true); + check(r.ok && (r.desc.FrontCounterClockwise != 0) == !ccw_for_face0, "flip switch"); + // Polygon offset: clamp, scale (slope * 16), offset in the hardware register order. + r = decode_rasterizer(mode_cntl(false, true, false, 0, 2, 2, true, true), 0x00080000, 0.003f, 29.0f, 1.0f, false); + check(r.ok && r.desc.DepthBias == 1 && r.desc.DepthBiasClamp == 0.003f && r.desc.SlopeScaledDepthBias == 29.0f / 16.0f && !r.bias_rounded, + "polygon offset"); + r = decode_rasterizer(mode_cntl(false, true, false, 0, 2, 2, false, false), 0x00080000, 0.003f, 29.0f, 1.0f, false); + check(r.ok && r.desc.DepthBias == 0 && r.desc.SlopeScaledDepthBias == 0 && r.desc.DepthBiasClamp == 0, "offset disabled ignores values"); + r = decode_rasterizer(mode_cntl(false, false, false, 0, 2, 2, true, true), 0x00080000, 0, 0, 2.5f, false); + check(r.ok && r.bias_rounded, "fractional offset flagged"); + // Depth clip. + r = decode_rasterizer(mode_cntl(false, false, false, 0, 2, 2, true, true), 0x0c080000, 0, 0, 0, false); + check(r.ok && !r.desc.DepthClipEnable && !r.clip_split, "zclip disabled"); + r = decode_rasterizer(mode_cntl(false, false, false, 0, 2, 2, true, true), 0x04080000, 0, 0, 0, false); + check(r.ok && r.desc.DepthClipEnable && r.clip_split, "one zclip plane flagged, clipping kept"); + // Polygon modes. + r = decode_rasterizer(mode_cntl(false, false, false, 1, 1, 1, true, true), 0x00080000, 0, 0, 0, false); + check(r.ok && r.desc.FillMode == D3D12_FILL_MODE_WIREFRAME, "line mode"); + check(!decode_rasterizer(mode_cntl(false, false, false, 1, 0, 0, true, true), 0x00080000, 0, 0, 0, false).ok, "point mode refused"); + check(!decode_rasterizer(mode_cntl(false, false, false, 1, 1, 2, true, true), 0x00080000, 0, 0, 0, false).ok, "mixed modes refused"); + check(!decode_rasterizer(mode_cntl(true, true, false, 0, 2, 2, true, true), 0x00080000, 0, 0, 0, false).ok, "both faces culled refused"); + check(!decode_rasterizer(mode_cntl(false, false, false, 0, 2, 2, true, false), 0x00080000, 0, 0, 0, false).ok, "one-face offset refused"); +} + +void blend_cases() +{ + using x2w_cb_blend::control_word; + const std::uint32_t straight = control_word(4, 0, 5, 1, 0, 5, true, true), off = 0x80000000; + const std::uint32_t dual = control_word(1, 0, 15, 1, 0, 17, true, true); + std::uint32_t words[8] = {straight, off, off, off, off, off, off, off}; + // Masks: CB_TARGET_MASK & CB_SHADER_MASK per target nibble. + auto b = decode_blend(words, 0x77777777, 0xff, true, false); + check(b.ok && b.desc.RenderTarget[0].RenderTargetWriteMask == 7 && b.desc.RenderTarget[1].RenderTargetWriteMask == 7 && + b.desc.RenderTarget[2].RenderTargetWriteMask == 0 && b.desc.RenderTarget[0].BlendEnable && !b.desc.RenderTarget[1].BlendEnable && + b.masked_targets == 0xff && !b.dual_source, "write masks"); + b = decode_blend(words, 0xffffffff, 0xf, true, false); + check(b.ok && b.desc.RenderTarget[0].RenderTargetWriteMask == 0xf && b.desc.RenderTarget[1].RenderTargetWriteMask == 0 && b.masked_targets == 0xfe, + "shader mask limits the targets"); + b = decode_blend(words, 0, 0xf, false, false); + check(b.ok && b.desc.RenderTarget[3].RenderTargetWriteMask == 0xf && !b.masked_targets, "masks not applied"); + for (auto& w : words) w = dual; + b = decode_blend(words, 0xf, 0xff, true, false); + check(b.ok && b.dual_source && b.desc.RenderTarget[0].DestBlend == D3D12_BLEND_SRC1_COLOR && b.desc.RenderTarget[0].DestBlendAlpha == D3D12_BLEND_SRC1_ALPHA, + "dual source"); + words[3] = control_word(11, 0, 1, 1, 0, 0, false, true); // BOTH_SRC_ALPHA + b = decode_blend(words, 0xffffffff, 0xffffffff, true, false); + check(!b.ok && b.refused_targets == 0x8 && b.reason, "refused target"); + // The unmasked form is what state_block_blend.h answered before: compare on a synthetic block. + std::vector<unsigned char> block(388, 0xA5); + const std::uint32_t mix[8] = {straight, off, control_word(1, 0, 1, 1, 0, 1, false, true), control_word(1, 3, 1, 1, 2, 1, true, true), off, off, straight, off}; + std::memcpy(block.data() + x2w_startup::state_block_blend_offset, mix, sizeof(mix)); + D3D12_BLEND_DESC old{}; + const bool old_ok = x2w_startup::state_block_blend(block.data(), block.size(), false, &old); + bool same = old_ok && old.IndependentBlendEnable && !old.AlphaToCoverageEnable; + for (unsigned t = 0; t < 8 && same; ++t) { + const auto ref = x2w_cb_blend::decode(mix[t], 0xF, false); + same = ref.ok && std::memcmp(&ref.desc, &old.RenderTarget[t], sizeof(ref.desc)) == 0; + } + check(same, "state_block_blend equals the per-target decoder"); +} + +void block_cases() +{ + // Vertex layout (+0x004 = 4) and mesh layout (+0x004 = 6, fields 0x54 later from +0x058). + for (int mesh = 0; mesh < 2; ++mesh) { + std::vector<unsigned char> a(mesh ? 0x1d0 : 0x184, 0x5a); + const std::uint32_t kind = mesh ? 6 : 4; + std::memcpy(a.data() + 4, &kind, 4); + const std::size_t s = mesh && !mutate_shift ? mesh_shift : 0; + auto put = [&](std::size_t off, std::uint32_t v) { std::memcpy(a.data() + off + s, &v, 4); }; + const float bias[3] = {0.5f, 32.0f, 3.0f}; + put(a_shader_mask, 0xff); + put(a_clip, 0x0c080000); + put(a_mode, 0x00201a42); + std::memcpy(a.data() + a_bias + s, bias, sizeof(bias)); + put(a_depth, 0x007007e7); + put(a_stencil, 0x00030030); + put(a_refmask, 0x0100ff00); + put(a_refmask_bf, 0x0100fe00); + put(a_target_mask, 0x77); + for (unsigned t = 0; t < 8; ++t) put(a_blend + 4 * t, 0x80000000u + t); + Words w; + const bool ok = read_words(a.data(), a.size(), w); + check(ok && w.mesh == (mesh != 0) && w.shader_mask == 0xff && w.clip == 0x0c080000 && w.mode == 0x00201a42 && w.depth == 0x007007e7 && + w.stencil == 0x00030030 && w.refmask == 0x0100ff00 && w.refmask_bf == 0x0100fe00 && w.target_mask == 0x77 && + w.blend[7] == 0x80000007 && w.bias_clamp == 0.5f && w.bias_scale == 32.0f && w.bias_offset == 3.0f, + mesh ? "mesh layout words" : "vertex layout words"); + Words short_words; + check(!read_words(a.data(), (mesh ? mesh_shift : 0) + a_blend + 31, short_words), "short block refused"); + } +} + +void add_record(std::vector<unsigned char>& list, std::uint32_t part, const void* desc, std::size_t bytes, unsigned char fill) +{ + const std::size_t at = list.size(); + list.resize(at + record_size, fill); + std::memcpy(list.data() + at, &part, 4); + std::memcpy(list.data() + at + 4, desc, bytes); +} + +void derived_cases() +{ + D3D12_DEPTH_STENCIL_DESC a{}, b{}; + a.DepthEnable = TRUE; + a.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + a.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + a.FrontFace = a.BackFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}; + b = a; + b.DepthFunc = D3D12_COMPARISON_FUNC_GREATER_EQUAL; + b.StencilEnable = 7; // a non-canonical TRUE + b.StencilReadMask = 0xff; + b.StencilWriteMask = 0x10; + b.FrontFace.StencilPassOp = D3D12_STENCIL_OP_REPLACE; + unsigned char with_pad[sizeof(D3D12_DEPTH_STENCIL_DESC)]; + std::memcpy(with_pad, &b, sizeof(b)); + with_pad[offsetof(D3D12_DEPTH_STENCIL_DESC, StencilWriteMask) + 1] = 0xcc; // garbage in the padding + D3D12_RASTERIZER_DESC r{D3D12_FILL_MODE_SOLID, D3D12_CULL_MODE_BACK, 9, 0, 0, 0, TRUE, FALSE, FALSE, 0, D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF}; + D3D12_BLEND_DESC blend{}; + std::vector<unsigned char> list; + add_record(list, part_depth_stencil, &a, sizeof(a), 0xee); + add_record(list, part_blend, &blend, sizeof(blend), 0xee); + add_record(list, part_depth_stencil, with_pad, sizeof(with_pad), 0xee); + add_record(list, part_rasterizer, &r, sizeof(r), 0xee); + D3D12_DEPTH_STENCIL_DESC got{}; + D3D12_RASTERIZER_DESC got_r{}; + check(derived_depth_stencil(list.data(), list.size(), got) && got.DepthFunc == D3D12_COMPARISON_FUNC_GREATER_EQUAL && got.StencilEnable == TRUE && + got.StencilWriteMask == 0x10 && got.FrontFace.StencilPassOp == D3D12_STENCIL_OP_REPLACE, "last depth-stencil part"); + D3D12_DEPTH_STENCIL_DESC canonical{}; + std::memcpy(&canonical, &got, sizeof(got)); + D3D12_DEPTH_STENCIL_DESC rebuilt{}; + rebuilt.DepthEnable = TRUE; + rebuilt.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + rebuilt.DepthFunc = D3D12_COMPARISON_FUNC_GREATER_EQUAL; + rebuilt.StencilEnable = TRUE; + rebuilt.StencilReadMask = 0xff; + rebuilt.StencilWriteMask = 0x10; + rebuilt.FrontFace = b.FrontFace; + rebuilt.BackFace = b.BackFace; + check(std::memcmp(&canonical, &rebuilt, sizeof(rebuilt)) == 0, "padding cleaned (state hash stable)"); + check(derived_rasterizer(list.data(), list.size(), got_r) && got_r.CullMode == D3D12_CULL_MODE_BACK && got_r.FrontCounterClockwise == TRUE, + "rasterizer part"); + check(last_part(list.data(), list.size(), part_blend) == record_size + 4, "blend part offset"); + check(last_part(list.data(), list.size() - 1, part_blend) == SIZE_MAX, "partial list refused"); + // Out-of-range fields refuse the part. + std::vector<unsigned char> bad; + D3D12_DEPTH_STENCIL_DESC c = a; + c.DepthFunc = static_cast<D3D12_COMPARISON_FUNC>(9); + add_record(bad, part_depth_stencil, &c, sizeof(c), 0); + D3D12_RASTERIZER_DESC rr = r; + rr.CullMode = static_cast<D3D12_CULL_MODE>(4); + add_record(bad, part_rasterizer, &rr, sizeof(rr), 0); + check(!derived_depth_stencil(bad.data(), bad.size(), got), "bad depth func refused"); + check(!derived_rasterizer(bad.data(), bad.size(), got_r), "bad cull mode refused"); + std::vector<unsigned char> none; + add_record(none, part_blend, &blend, sizeof(blend), 0); + check(!derived_depth_stencil(none.data(), none.size(), got) && !derived_rasterizer(none.data(), none.size(), got_r), "no part"); +} + +void target_cases() +{ + auto ds = decode_depth_stencil(depth_control(true, true, true, false, 6, true, 7, 7), stencil_control(0, 3, 0, 0, 3, 0), refmask(0, 0xff, 0xff, 1), + refmask(0, 0xff, 0xff, 1)).desc; + auto d = ds; + check(adjust_for_target(d, false, false, false) == adjust_no_target && !d.DepthEnable && !d.StencilEnable, "no depth target"); + d = ds; + check(adjust_for_target(d, true, false, false) == adjust_no_stencil && d.DepthEnable && !d.StencilEnable, "no stencil plane"); + d = ds; + check(adjust_for_target(d, true, true, true) == adjust_read_only && d.DepthEnable && d.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ZERO && + d.StencilWriteMask == 0, "read-only target"); + d = ds; + check(adjust_for_target(d, true, true, false) == 0 && std::memcmp(&d, &ds, sizeof(d)) == 0, "matching target unchanged"); +} + +void switch_cases() +{ + auto s = parse_switches(nullptr, nullptr, nullptr, nullptr, nullptr); + check(!s.depth && !s.cull && !s.flip && !s.blend, "defaults off"); + s = parse_switches(nullptr, "1", "1", "1", "1"); + check(s.depth && s.cull && s.flip && s.blend, "all on"); + s = parse_switches("0", "1", "1", "1", "1"); + check(!s.depth && !s.cull && !s.flip && !s.blend, "X2W_DRAW_STATE=0 wins"); + s = parse_switches("1", nullptr, nullptr, nullptr, "1"); + check(!s.cull && !s.flip, "flip needs cull"); + s = parse_switches(nullptr, "10", "yes", "", nullptr); + check(!s.depth && !s.cull && !s.blend, "only \"1\" turns a group on"); + check(!s.depth_clear, "depth clears default off"); + s = parse_switches(nullptr, nullptr, nullptr, nullptr, nullptr, "1"); + check(s.depth_clear && !s.depth, "depth clears on their own switch"); + s = parse_switches("0", nullptr, nullptr, nullptr, nullptr, "1"); + check(!s.depth_clear, "X2W_DRAW_STATE=0 turns depth clears off"); + check(!s.uncleared, "uncleared depth tests default off"); + s = parse_switches(nullptr, "1", nullptr, nullptr, nullptr, nullptr, "1"); + check(s.depth && s.uncleared, "uncleared depth tests on with depth"); + s = parse_switches(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "1"); + check(!s.uncleared, "uncleared depth tests need the depth group"); + s = parse_switches("0", "1", nullptr, nullptr, nullptr, nullptr, "1"); + check(!s.uncleared, "X2W_DRAW_STATE=0 turns uncleared depth tests off"); + check(!s.depthclip, "depth clip default off"); + s = parse_switches(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "1"); + check(s.depthclip && !s.cull && !s.depth && !s.blend, "depth clip on its own switch"); + s = parse_switches("0", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "1"); + check(!s.depthclip, "X2W_DRAW_STATE=0 turns depth clip off"); + s = parse_switches(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "yes"); + check(!s.depthclip, "only \"1\" turns depth clip on"); +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc > 2 && std::strcmp(argv[1], "--mutate") == 0) { + mutate_winding = std::strcmp(argv[2], "winding") == 0; + mutate_shift = std::strcmp(argv[2], "mesh-shift") == 0; + if (!mutate_winding && !mutate_shift) { + std::printf("unknown mutation\n"); + return 2; + } + } else if (argc > 1) { + std::printf("usage: startup_pipeline_state_check [--mutate winding|mesh-shift]\n"); + return 2; + } + depth_stencil_cases(); + rasterizer_cases(); + blend_cases(); + block_cases(); + derived_cases(); + target_cases(); + switch_cases(); + std::printf("%d of %d checks failed\n", failures, cases); + return failures ? 1 : 0; +} diff --git a/tests/startup_placed_buffer_range_check.cpp b/tests/startup_placed_buffer_range_check.cpp index 2b395c9456..f1ef39dd10 100644 --- a/tests/startup_placed_buffer_range_check.cpp +++ b/tests/startup_placed_buffer_range_check.cpp @@ -345,10 +345,19 @@ int main(int argc, char** argv) if (heap) HeapDestroy(heap); auto* reservation = static_cast<char*>(VirtualAlloc(nullptr, 2 * page, MEM_RESERVE, PAGE_READWRITE)); if (reservation && VirtualAlloc(reservation + page, page, MEM_COMMIT, PAGE_READWRITE)) { + if (x2w_startup::private_heap_importable(reservation)) + setup_fail("private heap import accepted a reserved prefix", reservation); current = partial; place(reservation + page, page, 0, "committed suffix after a reserved prefix"); place(reservation + page, 2 * page, 0, "committed suffix with buffer past the allocation"); current = other; + if (!VirtualAlloc(reservation, page, MEM_COMMIT, PAGE_READWRITE) || + !x2w_startup::private_heap_importable(reservation)) + setup_fail("private heap import rejected a newly completed allocation", reservation); + DWORD old = 0; + if (!VirtualProtect(reservation + page, page, PAGE_READONLY, &old) || + x2w_startup::private_heap_importable(reservation)) + setup_fail("private heap import accepted mixed page protection", reservation); } else { setup_fail("cannot construct an allocation with a reserved prefix", reservation); } diff --git a/tests/startup_placed_fast.cpp b/tests/startup_placed_fast.cpp new file mode 100644 index 0000000000..0a4530dc9b --- /dev/null +++ b/tests/startup_placed_fast.cpp @@ -0,0 +1,128 @@ +// LOCAL stall: device slot 133 (CreatePlacedResourceX) with and without X2W_PLACED_FAST. +// +// startup_placed_fast <warp|hardware> <fast|walk> +// (X2W_D3D12_RENDER=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1; fast also X2W_PLACED_FAST=1; +// the test sets X2W_TRAP_LOG itself) +// +// One private 4 MiB allocation, all committed. Buffers, in order: +// A base +0, 64 KiB (opens the allocation's heap: always walked) +// B base +1 MiB, 1 MiB (inside the heap) +// C base +3 MiB, 2 MiB (past the end of the allocation) +// Expected in both modes: A and B "aliased", C "not aliased" (the result the walk gives). fast: the +// "X2W_PLACED_FAST" line counts exactly 1 call (B; C is past the region queried at its address, so it is walked). +// Not covered: a buffer crossing a region boundary inside the allocation. A read-only page makes +// OpenExistingHeapFromAddress fail on WARP for the whole allocation, so that split cannot be built here; walk (control): no such line. +// Exit 0 pass, 77 capability skip (no adapter, no existing-heap support), other values name the step. +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <iterator> +#include <string> +#include <vector> + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Word = std::uint64_t; +template <class T> Word arg(T* value) { return reinterpret_cast<Word>(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word); + return reinterpret_cast<Slot>((*static_cast<void***>(object))[index])(object, a, b, c, d, e, f); +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) return 2; + const std::string mode = argv[2]; + if (mode != "fast" && mode != "walk") return 2; + ComPtr<IDXGIFactory6> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr<IDXGIAdapter> adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr<IDXGIAdapter1> candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) 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 (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + { + ComPtr<ID3D12Device3> desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 4; + void* block = VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + ComPtr<ID3D12Heap> heap; + const HRESULT hr = block ? desktop->OpenExistingHeapFromAddress(block, IID_PPV_ARGS(&heap)) : E_OUTOFMEMORY; + heap.Reset(); + if (block) VirtualFree(block, 0, MEM_RELEASE); + if (FAILED(hr)) { + std::printf("OpenExistingHeapFromAddress -> 0x%08lx: capability skip\n", static_cast<unsigned long>(hr)); + return 77; + } + } + wchar_t temp[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, temp)) return 5; + const std::wstring log_path = std::wstring(temp) + L"x2w_placed_fast_" + std::to_wstring(GetCurrentProcessId()) + L"_" + + std::to_wstring(GetTickCount64()) + L".log"; + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + + std::array<unsigned char, 64> device_parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), device_parameters.data(), __uuidof(ID3D12Device), &device))) return 6; + auto* memory = static_cast<unsigned char*>(VirtualAlloc(nullptr, 4u << 20, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!memory) return 7; + struct Place { const char* name; std::size_t offset, width; bool decommit_first; }; + const Place places[] = {{"A", 0, 64u << 10, false}, {"B", 1u << 20, 1u << 20, false}, {"C", 3u << 20, 2u << 20, false}}; + std::vector<void*> made; + for (const Place& p : places) { + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, p.width, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + void* resource = nullptr; + const Word hr = invoke(device, 133, arg(memory + p.offset), arg(&buffer), D3D12_RESOURCE_STATE_COMMON, 0, + arg(&__uuidof(ID3D12Resource)), arg(&resource)); + std::printf("%s: +0x%zx width 0x%zx -> 0x%08llx\n", p.name, p.offset, p.width, static_cast<unsigned long long>(hr)); + made.push_back(resource); + } + + std::ifstream file(log_path, std::ios::binary); + const std::string log{std::istreambuf_iterator<char>(file), {}}; + // The slot-133 lines in call order: their placement word. + std::vector<std::string> placement; + for (std::size_t p = log.find("Device::slot133(CreatePlacedResourceX?) address="); p != std::string::npos; + p = log.find("Device::slot133(CreatePlacedResourceX?) address=", p + 1)) { + const std::string line = log.substr(p, log.find('\n', p) - p); + placement.push_back(line.find(" not aliased") != std::string::npos ? "not aliased" : line.find(" aliased") != std::string::npos ? "aliased" : "?"); + } + int fast_calls = 0; + if (const std::size_t p = log.find("slot133 X2W_PLACED_FAST: "); p != std::string::npos) + for (std::size_t q = p; q != std::string::npos; q = log.find("slot133 X2W_PLACED_FAST: ", q + 1)) + fast_calls = std::atoi(log.c_str() + q + std::strlen("slot133 X2W_PLACED_FAST: ")); + int failures = 0; + const char* want[] = {"aliased", "aliased", "not aliased"}; + for (std::size_t i = 0; i < 3; ++i) { + const std::string got = i < placement.size() ? placement[i] : "missing"; + std::printf("%s placement: %s (want %s)\n", places[i].name, got.c_str(), want[i]); + if (got != want[i]) ++failures; + } + std::printf("X2W_PLACED_FAST calls logged: %d (want %d)\n", fast_calls, mode == "fast" ? 1 : 0); + if (fast_calls != (mode == "fast" ? 1 : 0)) ++failures; + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; +} diff --git a/tests/startup_present_producer.cpp b/tests/startup_present_producer.cpp index 32f6fe0b6e..5fa7c93a64 100644 --- a/tests/startup_present_producer.cpp +++ b/tests/startup_present_producer.cpp @@ -26,6 +26,13 @@ bool ok(Word result) { return SUCCEEDED(static_cast<HRESULT>(result)); } int main(int argc, char** argv) { + const bool title_mode = argc >= 2 && std::strcmp(argv[1], "title-window") == 0; + HWND title = nullptr; + if (title_mode) { + title = CreateWindowExW(WS_EX_NOACTIVATE, L"STATIC", L"Fixture title", WS_POPUP | WS_VISIBLE, + -31000, -31000, 120, 80, nullptr, nullptr, GetModuleHandleW(nullptr), nullptr); + if (!title) return 16; + } const bool reverse = argc >= 2 && std::strcmp(argv[1], "reverse") == 0; const bool use_magenta = argc >= 2 && std::strcmp(argv[1], "auto-magenta") == 0; const bool automatic = use_magenta || (argc >= 2 && std::strcmp(argv[1], "auto") == 0); @@ -148,6 +155,21 @@ int main(int argc, char** argv) if (!finish() || !present() || !present()) return 11; } } + if (title_mode) { + if (!SetWindowPos(title, nullptr, 0, 0, 160, 90, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER) || !present()) return 17; + unsigned output_windows = 0; + EnumWindows([](HWND window, LPARAM count) -> BOOL { + wchar_t name[64]{}; + DWORD pid = 0; + GetWindowThreadProcessId(window, &pid); + if (pid == GetCurrentProcessId() && GetClassNameW(window, name, 64) && !lstrcmpW(name, L"X2WOutputWindow")) + ++*reinterpret_cast<unsigned*>(count); + return TRUE; + }, reinterpret_cast<LPARAM>(&output_windows)); + wchar_t text[64]{}; + if (output_windows || !IsWindowVisible(title) || !GetWindowTextW(title, text, 64) || lstrcmpW(text, L"Fixture title")) return 18; + DestroyWindow(title); + } if (FAILED(desktop->GetDeviceRemovedReason())) return 12; ComPtr<ID3D12InfoQueue> messages; if (debug && SUCCEEDED(desktop.As(&messages))) { diff --git a/tests/startup_present_producer_check.py b/tests/startup_present_producer_check.py index 9307ffcddc..79076b2c10 100644 --- a/tests/startup_present_producer_check.py +++ b/tests/startup_present_producer_check.py @@ -12,6 +12,8 @@ def run(mode, rgb=""): env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", X2W_PRESENT_SIGNATURE_EVERY="1", X2W_RED_PRODUCER_FRAMES="", X2W_RED_PRODUCER_AUTO="", X2W_RED_PRODUCER_RGB=rgb) + if mode == "title-window": + env["X2W_PRESENT_IN_TITLE_WINDOW"] = "1" if mode.startswith("auto"): env["X2W_RED_PRODUCER_AUTO"] = "4,2" else: @@ -61,6 +63,10 @@ def check_barriers(): if __name__ == "__main__" and OPTIONS == ["barriers"]: check_barriers() +elif __name__ == "__main__" and OPTIONS == ["title-window"]: + logs, _, adapter = run("title-window") + assert "first flip on the original window" in logs, logs + print(f"Original window received the flip and retained its title after resize ({adapter})") elif __name__ == "__main__": check(False) check(True) diff --git a/tests/startup_probe_cache.cpp b/tests/startup_probe_cache.cpp new file mode 100644 index 0000000000..c04da1a845 --- /dev/null +++ b/tests/startup_probe_cache.cpp @@ -0,0 +1,184 @@ +// LOCAL stall: probe_readable with and without its unreadable-range cache (local_log.h, X2W_PROBE_CACHE). +// +// startup_probe_cache <cache|nocache> +// (cache: X2W_PROBE_CACHE=1 X2W_PROBE_CACHE_MS=100) +// +// A 1 MiB reservation with its first 64 KiB committed. First-chance access violations are counted by a vectored +// handler (each one is what costs a debugger round trip in a run). +// 1. 100 probes of [base, base + 128 KiB): 64 KiB readable every time. Violations: cache 1, nocache 100. +// 2. 100 probes at base + 512 KiB (reserved): 0 readable. Violations added: cache 0 (same region), nocache 100. +// 3. +64 KiB committed, no invalidation, within the expiry: cache still says 64 KiB (the stale direction is +// "unreadable", never "readable"); nocache 128 KiB. +// 4. invalidate_probe_cache(): cache 128 KiB. +// 5. Expiry: a probe at base + 512 KiB faults once (cached), again 0 faults, then after 150 ms faults once more. +// 6. The reservation released (free memory): 0 readable, no crash. +// Exit 0 pass, other values name the step. +#include "startup_stubs/local_log.h" + +#include <cstdio> +#include <cstring> +#include <string> + +namespace { +volatile LONG violations; +LONG CALLBACK count_violation(EXCEPTION_POINTERS* e) +{ + if (e->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) InterlockedIncrement(&violations); + return EXCEPTION_CONTINUE_SEARCH; +} +int failures; +void expect(const char* what, long long got, long long want) +{ + std::printf("%s: %lld (want %lld)%s\n", what, got, want, got == want ? "" : " <-- FAIL"); + if (got != want) ++failures; +} +} // namespace + +// More live textures than cache slots. Their bases are mapped, but full uploads cross a missing page. +bool streamed_texture_prefixes() +{ + constexpr SIZE_T page = 64u << 10, stride = 4 * page, count = 96; + auto* memory = static_cast<BYTE*>(VirtualAlloc(nullptr, stride * count, MEM_RESERVE, PAGE_READWRITE)); + if (!memory) return false; + bool ok = true; + for (SIZE_T i = 0; i < count; ++i) + ok &= VirtualAlloc(memory + i * stride, (1 + i % 3) * page, MEM_COMMIT, PAGE_READWRITE) != nullptr; + const auto sweep = [&](bool texture) { + const LONG before = violations; + for (SIZE_T i = 0; i < count; ++i) { + const auto at = reinterpret_cast<std::uintptr_t>(memory + i * stride); + const auto bytes = texture ? x2w_local::probe_descriptor_address(at, stride) + : x2w_local::probe_readable(at, stride); + ok &= bytes == (1 + i % 3) * page; + } + return violations - before; + }; + x2w_local::invalidate_probe_cache(); + if (ok) { + expect("ordinary first pass over sparse textures", sweep(false), count); + x2w_local::invalidate_probe_cache(); + expect("texture upload across missing interior pages", sweep(true), 0); + x2w_local::invalidate_probe_cache(); + expect("repeated texture uploads after cache eviction", sweep(true), 0); + ok &= VirtualAlloc(memory + page, page, MEM_COMMIT, PAGE_READWRITE) != nullptr; + x2w_local::invalidate_probe_cache(); + expect("new texture page included", x2w_local::probe_descriptor_address(reinterpret_cast<std::uintptr_t>(memory), stride), 2 * page); + } + VirtualFree(memory, 0, MEM_RELEASE); + x2w_local::invalidate_probe_cache(); + return ok; +} + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + const std::string mode = argv[1]; + if (mode != "cache" && mode != "nocache" && mode != "query" && mode != "lazy") return 2; + const bool cache = mode != "nocache"; + const bool query = mode == "query"; + expect("query-first eligibility", x2w_local::probe_query_first(), query); + if (x2w_local::probe_cache_on() != cache) { + std::printf("X2W_PROBE_CACHE is %s, mode %s\n", x2w_local::probe_cache_on() ? "on" : "off", mode.c_str()); + return 3; + } + AddVectoredExceptionHandler(1, count_violation); + auto* base = static_cast<unsigned char*>(VirtualAlloc(nullptr, 1u << 20, MEM_RESERVE, PAGE_READWRITE)); + if (!base || !VirtualAlloc(base, 64u << 10, MEM_COMMIT, PAGE_READWRITE)) return 4; + std::memset(base, 1, 64u << 10); + const auto b = reinterpret_cast<std::uintptr_t>(base); + + if (query) { + if (!streamed_texture_prefixes()) return 6; + violations = 0; + // A normal pointer still uses first-touch probing even with the switch on. + expect("ordinary reserved prefix", x2w_local::probe_readable(b + (512u << 10), 256), 0); + expect("ordinary probe retained", violations, 1); + x2w_local::invalidate_probe_cache(); + auto* candidate = base + (512u << 10); + bool missing = true; + for (int i = 0; i < 100; ++i) { + x2w_local::invalidate_probe_cache(); + missing &= x2w_local::probe_readable(b + (512u << 10), 256) == 0; + } + expect("ordinary repeated missing page", missing, true); + expect("ordinary retries after invalidation add no exceptions", violations, 1); + x2w_local::invalidate_probe_cache(); + expect("different page in the same reserved region", x2w_local::probe_readable(b + (640u << 10), 256), 0); + expect("ordinary first touch retained for a different page", violations, 2); + if (!VirtualAlloc(candidate, 4096, MEM_COMMIT, PAGE_READWRITE)) return 5; + x2w_local::invalidate_probe_cache(); + expect("ordinary newly committed page", x2w_local::probe_readable(b + (512u << 10), 256), 256); + DWORD old_protect = 0; + if (!VirtualProtect(candidate, 4096, PAGE_READWRITE | PAGE_GUARD, &old_protect)) return 5; + expect("guarded page is unreadable", x2w_local::probe_readable(b + (512u << 10), 256), 0); + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(candidate, &info, sizeof(info))) return 5; + expect("guard is restored", (info.Protect & PAGE_GUARD) != 0, true); + if (!VirtualFree(candidate, 4096, MEM_DECOMMIT)) return 5; + x2w_local::invalidate_probe_cache(); + violations = 0; + } + bool all = true; + for (int i = 0; i < 100; ++i) all = all && x2w_local::probe_descriptor_address(b, 128u << 10) == (64u << 10); + expect("1. 100 probes of 128 KiB, all 64 KiB readable", all, 1); + expect("1. access violations", violations, query ? 0 : cache ? 1 : 100); + + LONG before = violations; + all = true; + for (int i = 0; i < 100; ++i) all = all && x2w_local::probe_descriptor_address(b + (512u << 10), 4096) == 0; + expect("2. 100 probes in the reserved part, all 0", all, 1); + expect("2. access violations added", violations - before, cache ? 0 : 100); + + if (!VirtualAlloc(base + (64u << 10), 64u << 10, MEM_COMMIT, PAGE_READWRITE)) return 5; + expect("3. committed +64 KiB, no invalidation: readable", static_cast<long long>(x2w_local::probe_descriptor_address(b, 128u << 10)), + cache ? (64u << 10) : (128u << 10)); + x2w_local::invalidate_probe_cache(); + expect("4. after invalidate_probe_cache: readable", static_cast<long long>(x2w_local::probe_descriptor_address(b, 128u << 10)), 128u << 10); + + x2w_local::invalidate_probe_cache(); + before = violations; + x2w_local::probe_descriptor_address(b + (512u << 10), 4096); + expect("5. first probe after invalidation: violations", violations - before, query ? 0 : 1); + before = violations; + x2w_local::probe_descriptor_address(b + (512u << 10), 4096); + expect("5. second probe: violations", violations - before, cache ? 0 : 1); + Sleep(150); + before = violations; + x2w_local::probe_descriptor_address(b + (512u << 10), 4096); + expect("5. after 150 ms (expiry 100 ms): violations", violations - before, query ? 0 : 1); + + if (mode == "query" || mode == "cache") { + LARGE_INTEGER t0, t1, freq; + QueryPerformanceFrequency(&freq); + unsigned mismatches = 0; + const LONG initial_faults = violations; + QueryPerformanceCounter(&t0); + for (int i = 0; i < 20000; ++i) { + x2w_local::invalidate_probe_cache(); + if (x2w_local::probe_descriptor_address(b + (512u << 10), 256)) ++mismatches; + } + QueryPerformanceCounter(&t1); + expect("reserved candidate mismatches", mismatches, 0); + expect("reserved candidate exceptions", violations - initial_faults, query ? 0 : 20000); + std::printf("reserved candidate benchmark: 20000 queries %.2f ms\n", + 1000.0 * (t1.QuadPart - t0.QuadPart) / freq.QuadPart); + QueryPerformanceCounter(&t0); + for (int i = 0; i < 20000; ++i) { + if (x2w_local::probe_descriptor_address(b, 256) != 256) ++mismatches; + } + QueryPerformanceCounter(&t1); + expect("committed candidate mismatches", mismatches, 0); + std::printf("committed candidate benchmark: 20000 probes %.2f ms\n", + 1000.0 * (t1.QuadPart - t0.QuadPart) / freq.QuadPart); + } + VirtualFree(base, 0, MEM_RELEASE); + x2w_local::invalidate_probe_cache(); + expect("6. released: readable", static_cast<long long>(x2w_local::probe_descriptor_address(b, 4096)), 0); + + const x2w_local::ProbeCache& c = x2w_local::probe_cache(); + std::printf("cache counters: hits %lld faults %lld queries %lld (%.3f ms total) ranges kept %lld\n", c.hits, c.faults, c.queries, + [&] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return static_cast<double>(c.query_ticks) * 1000.0 / static_cast<double>(f.QuadPart); }(), + c.cached); + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; +} diff --git a/tests/startup_profile_check.py b/tests/startup_profile_check.py new file mode 100644 index 0000000000..ee35ef157e --- /dev/null +++ b/tests/startup_profile_check.py @@ -0,0 +1,76 @@ +"""Check the clock-driven sampling profiler of tools/startup/debug_launch.py (X2W_PROFILE). + +tests/startup_profile_probe.cpp is the only input: a thread named "spin" burns CPU in spin_work, one +named "waiter" blocks in wait_here, one named "faults" takes a caught access violation every +millisecond (a stream of debug events), for about 3 s. The profile must show the spinning thread busy +in spin_work, the waiter idle on its wait call at wait_here, and the process frozen only briefly per +sample. Controls: no profile without the switch, a malformed value is reported and ignored, and a +repeat interval writes a second batch. +""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +REPO = Path(__file__).resolve().parents[1] +DEBUG = REPO / "tools/startup/debug_launch.py" +ROW = re.compile(r"^\s*(\d+)\s+([\d.]+)\s+\d+\s+\d+\s+\d+\s+(\d+)/\s*(\d+)/\s*(\d+)\s+(\S+) /", re.M) + + +def run(probe, work, name, variables): + logdir = work / name + env = {k: v for k, v in os.environ.items() if not k.startswith("X2W_")} + env.update(variables) + command = [sys.executable, "-B", str(DEBUG), str(probe), str(work), str(logdir), "--timeout", "30", "--console", "0"] + result = subprocess.run(command, capture_output=True, text=True, timeout=100, env=env) + return result.stdout + result.stderr, logdir + + +def main(probe): + probe = Path(probe).resolve() + with tempfile.TemporaryDirectory() as temporary: + work = Path(temporary) + out, logdir = run(probe, work, "profile", {"X2W_PROFILE": "0.5,40,25"}) + assert "process exited with 0x00000000" in out, out + report = (logdir / "profile_0.5.txt").read_text(encoding="utf-8") + rows = {m.group(6): m for m in ROW.finditer(report)} + assert "spin" in rows and "waiter" in rows and "faults" in rows, report + spin, waiter = rows["spin"], rows["waiter"] + assert float(spin.group(2)) >= 50.0, report # a core, less the time the debugger froze it + assert float(waiter.group(2)) < 5.0, report + assert int(waiter.group(5)) >= 35, report # waiting in nearly every sample + block = report.split(f"thread {spin.group(1)} (spin")[1].split("\nthread ")[0] + assert "spin_work" in block.split("\n inclusive:")[0], block # the leaf is the spin loop + waits = [line for line in report.splitlines() if line.startswith(f"thread {waiter.group(1)}: ")] + # wait_here's call is a tail jump in an optimised build, so the site is wait_here or its caller. + assert waits and "NtWaitForSingleObject @ " in waits[0] and re.search(r"wait_(here|thread)", waits[0]), waits + frozen = float(re.search(r"frozen per sample: median ([\d.]+) ms", report).group(1)) + assert frozen < 50.0, report + # The fault thread sleeps a timer tick between faults. Samples taken right after a continue, or at + # the end of a timed wait (the same tick it wakes on), find it at the fault every time; samples + # taken >= 1 ms after the last continue with no event pending see it sleep. + faults = rows["faults"] + assert int(faults.group(5)) >= 20, report + quiet = re.search(r"after the last ContinueDebugEvent with no event pending: (\d+)/(\d+)", report) + assert quiet and int(quiet.group(1)) >= 30, report + assert "profile: 40 samples" in (logdir / "events.txt").read_text(encoding="utf-8") + print(f"spin {spin.group(2)}% cpu, waiter {waiter.group(2)}% ({waiter.group(5)} waiting samples), " + f"faults {faults.group(5)}/40 waiting, quiet samples {quiet.group(1)}/40, frozen median {frozen} ms per sample") + + # Repeat: a second batch one second later. + out, logdir = run(probe, work, "repeat", {"X2W_PROFILE": "0.3,5,20,1"}) + assert "process exited with 0x00000000" in out, out + assert (logdir / "profile_0.3.txt").exists() and (logdir / "profile_1.3.txt").exists(), os.listdir(logdir) + # Controls: no switch, no profile; a malformed value is reported and ignored. + out, logdir = run(probe, work, "off", {}) + assert "process exited with 0x00000000" in out and not list(logdir.glob("profile_*")), out + out, logdir = run(probe, work, "malformed", {"X2W_PROFILE": "1,x"}) + assert "process exited with 0x00000000" in out and "ignored" in out and not list(logdir.glob("profile_*")), out + print("startup_profile: PASS (busy thread and its loop, waiter and its wait site, short freeze; 3 controls)") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1])) diff --git a/tests/startup_profile_probe.cpp b/tests/startup_profile_probe.cpp new file mode 100644 index 0000000000..7e5f05fba5 --- /dev/null +++ b/tests/startup_profile_probe.cpp @@ -0,0 +1,73 @@ +// Input for the startup debugger's sampling-profiler check (tests/startup_profile_check.py). Three +// named threads run for about 3 s: "spin" burns CPU in spin_work, "waiter" blocks in wait_here on an +// event, and "faults" takes caught access violations in a loop (each one a debug event under the +// debugger, as the stand-ins' readability probe is in a title run). The main thread sleeps, then +// releases the waiter, joins all three and exits 0. No GPU and no other input is involved. +#include <windows.h> + +#include <cstdio> + +namespace { +volatile LONG stop; +volatile unsigned long long sink; +HANDLE release; + +__declspec(noinline) unsigned long long spin_work() +{ + unsigned long long x = 1; + while (!stop) { + for (int i = 0; i < 100000; ++i) x = x * 6364136223846793005ull + 1442695040888963407ull; + sink = x; + } + return x; +} + +__declspec(noinline) void wait_here() { WaitForSingleObject(release, INFINITE); } + +__declspec(noinline) int fault_once() +{ + __try { + return *reinterpret_cast<volatile int*>(sizeof(int)); // unmapped page: access violation + } __except (EXCEPTION_EXECUTE_HANDLER) { + return 0; + } +} + +DWORD WINAPI spin_thread(void*) +{ + SetThreadDescription(GetCurrentThread(), L"spin"); + spin_work(); + return 0; +} + +DWORD WINAPI wait_thread(void*) +{ + SetThreadDescription(GetCurrentThread(), L"waiter"); + wait_here(); + return 0; +} + +DWORD WINAPI fault_thread(void*) +{ + SetThreadDescription(GetCurrentThread(), L"faults"); + while (!stop) { + fault_once(); + Sleep(1); + } + return 0; +} +} // namespace + +int main() +{ + release = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE threads[] = {CreateThread(nullptr, 0, spin_thread, nullptr, 0, nullptr), + CreateThread(nullptr, 0, wait_thread, nullptr, 0, nullptr), + CreateThread(nullptr, 0, fault_thread, nullptr, 0, nullptr)}; + Sleep(3000); + InterlockedExchange(&stop, 1); + SetEvent(release); + WaitForMultipleObjects(3, threads, TRUE, INFINITE); + std::printf("profile-probe done %llu\n", sink & 1); + return 0; +} diff --git a/tests/startup_quad_divergent_check.py b/tests/startup_quad_divergent_check.py new file mode 100644 index 0000000000..906172e728 --- /dev/null +++ b/tests/startup_quad_divergent_check.py @@ -0,0 +1,86 @@ +"""X2W_PS_QUAD_DIVERGENT=1 in tools/startup/gfx2hlsl.py: quad reads and image_sample_b where a lane may skip them. + +Off (the default), a quad read (DPP quad_perm) on a path some lane avoids and an image_sample_b after a branch are +refused, as before. On, both are lowered in forward control flow. That is exact only where the four lanes of each +quad take the same path: D3D leaves quad reads and implicit derivatives undefined for lanes outside the control +flow, while the hardware reads inactive lanes (DPP fi:1). Loops stay refused either way, and a pipeline that used +the switch says `quaddivergent 1` in its manifest; one that did not use it has no such line even with the switch on. + +Fixtures: startup_quad_dpp_check's stage with s_cbranch_execz over the first quad read, and its backward-branch +loop; startup_image_sample_b_local_check's stage with an s_cbranch_scc0 before the sample, and a loop form of it. The +environment variable is read when the stage is built, so the test sets and clears it around each pipeline. +""" +import os +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 +import startup_quad_dpp_check as Q # noqa: E402 +import startup_image_sample_b_local_check as B # noqa: E402 + +FLAG = 'X2W_PS_QUAD_DIVERGENT' + + +def build(make, value): + saved = os.environ.pop(FLAG, None) + if value is not None: + os.environ[FLAG] = value + try: + return make() + finally: + os.environ.pop(FLAG, None) + if saved is not None: + os.environ[FLAG] = saved + + +def refused(make, value, text): + try: + build(make, value).hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (text, str(error)) + return + raise AssertionError('accepted with %s=%s, expected %r' % (FLAG, value, text)) + + +def main(): + skip = Q.program(prefix=struct.pack('<I', 0xbf880002)) # s_cbranch_execz over the first quad read + loop = Q.INTERP + Q.vop2(5, 4, 2, 2, 0) + struct.pack('<I', 0xbf84fffb) + Q.vop1(1, 5, 4, 0x55) \ + + Q.vop1(1, 6, 4, 0xaa) + Q.vop2(3, 7, 2, 2, Q.PERM_X, neg0=1) + Q.EXPORT + assert G.decode(skip)[2][3].startswith('s_cbranch_execz'), G.decode(skip)[2] + # quad reads: off (unset, '0') refused as before; on lowered and marked + for value in (None, '0', 'yes'): + refused(lambda: Q.mesh_pipeline(skip), value, 'quad read (DPP) at 0xc is skipped on a path to') + pipe = build(lambda: Q.mesh_pipeline(skip), '1') + body = pipe.ps.body() + assert ' uint dpp0 = QuadReadLaneAt(v2, 0u);' in body and ' if (pc == 1) {' in body, body + assert pipe.ps.quad_divergent_used and 'quaddivergent 1' in pipe.manifest().split('\n'), pipe.manifest() + refused(lambda: Q.mesh_pipeline(loop), '1', 'in a program with a loop') + straight = build(lambda: Q.mesh_pipeline(Q.program()), '1') + assert not straight.ps.quad_divergent_used and 'quaddivergent' not in straight.manifest() + assert 'quaddivergent' not in build(lambda: Q.mesh_pipeline(Q.program()), None).manifest() + + # image_sample_b after a branch + branched = B.program(0x25, prefix_branch=True) + refused(lambda: G.Pipeline(B.VS_WORDS, branched, B.root_blob()), None, + 'image_sample_b outside straight-line code with every lane active') + pipe = build(lambda: G.Pipeline(B.VS_WORDS, branched, B.root_blob()), '1') + assert 't = r0.SampleBias(q0, float2(F(v1), F(v2)), F(v0));' in pipe.hlsl_ps(), pipe.hlsl_ps() + assert 'quaddivergent 1' in pipe.manifest().split('\n'), pipe.manifest() + # a loop: the scc0 branch before the sample made backward (to offset 0) + words = bytearray(branched) + words[0x2c:0x30] = struct.pack('<I', 0xbf840000 | (-12 & 0xffff)) # s_cbranch_scc0 to 0x0 + assert G.decode(bytes(words))[9][3] == 's_cbranch_scc0 label_0x0', G.decode(bytes(words))[9] + refused(lambda: G.Pipeline(B.VS_WORDS, bytes(words), B.root_blob()), '1', + 'image_sample_b outside straight-line code with every lane active') + plain = build(lambda: G.Pipeline(B.VS_WORDS, B.program(0x25), B.root_blob()), '1') + assert 'quaddivergent' not in plain.manifest() + print('%s: off (unset, 0, yes) refuses as before; 1 lowers the skipped quad read and the branched ' + 'image_sample_b with `quaddivergent 1`; loops refused; no marker when unused' % FLAG) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_quad_dpp_check.py b/tests/startup_quad_dpp_check.py new file mode 100644 index 0000000000..fcb092f384 --- /dev/null +++ b/tests/startup_quad_dpp_check.py @@ -0,0 +1,178 @@ +"""DPP16 quad permutations in a mesh pipeline's pixel stage (gfx2hlsl Stage.quad_dpp). + +Synthetic words (VOP2 DPP16: op [30:25], vdst [24:17], vsrc1 [16:9], src0 = 250; second dword: src0 VGPR [7:0], +dpp_ctrl [16:8], fi 18, bound_ctrl 19, src0 neg 20 / abs 21, bank_mask [27:24], row_mask [31:28]; VOP1 DPP16 the same +with 0x3f in [31:25] and op [16:9]); names asserted from the decoder. The program is the coarse-derivative idiom Mesa +ACO emits (aco_select_nir_intrinsics.cpp ddx_coarse / ddy_coarse): + + v_interp_p1/p2_f32 v2, attr0.x + v_subrev_f32_dpp v4, v2, v2 quad_perm:[0,0,0,0] v4 = v2 - v2[lane 0 of the quad] + v_mov_b32_dpp v5, v4 quad_perm:[1,1,1,1] v5 = v4[lane 1] = ddx_coarse + v_mov_b32_dpp v6, v4 quad_perm:[2,2,2,2] v6 = v4[lane 2] = ddy_coarse + v_add_f32_dpp v7, -v2, v2 quad_perm:[1,0,3,2] v7 = v2 - v2[lane ^ 1] + exp mrt0 v5, v6, v7, v2 done vm + +The emitted HLSL is run on a model 2x2 quad (QuadReadLaneAt / QuadReadAcrossX of D3D: lane 0 top-left, 1 top-right, +2 bottom-left, 3 bottom-right) and compared with the reference in binary32. The mesh stage is a stub (this checks the +pixel stage only). With dxc present the pixel HLSL also compiles as ps_6_0. + +Controls: the draw pipeline (fxc ps_5_1, no quad reads) refuses `v_subrev_f32_dpp` as before; v_sub_f32_dpp (the +operands the other way round) gives the negated result on the model; row_mirror, fi:0, a branch around the DPP and +a loop are refused; with quad_ops off the mesh pipeline refuses as before the change. +""" +import os +import re +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import VS_WORDS, root_blob # noqa: E402 + +PERM_X = 0xb1 # quad_perm:[1,0,3,2] + + +def vop2(op, d, s1, s0, ctrl, fi=1, bc=1, neg0=0): + return struct.pack('<II', op << 25 | d << 17 | s1 << 9 | 250, + s0 | ctrl << 8 | fi << 18 | bc << 19 | neg0 << 20 | 0xf << 24 | 0xf << 28) + + +def vop1(op, d, s0, ctrl, fi=1, bc=1): + return struct.pack('<II', 0x3f << 25 | d << 17 | op << 9 | 250, s0 | ctrl << 8 | fi << 18 | bc << 19 | 0xf << 24 | 0xf << 28) + + +INTERP = struct.pack('<II', 0xc8080000, 0xc8090001) # v_interp_p1_f32 v2, v0, attr0.x; p2 v2, v1 +EXPORT = struct.pack('<III', 0xf800180f, 5 | 6 << 8 | 7 << 16 | 2 << 24, 0xbf810000) + + +def program(first_op=5, ctrl0=0, fi=1, prefix=b''): + return (INTERP + prefix + vop2(first_op, 4, 2, 2, ctrl0, fi=fi) + vop1(1, 5, 4, 0x55) + vop1(1, 6, 4, 0xaa) + + vop2(3, 7, 2, 2, PERM_X, neg0=1) + EXPORT) + + +class StubMesh: + def __init__(self, pipe, code): + self.exports = {'pos': ['0'] * 4, 'param0': ['0'] * 4} + self.exported_prim = True + + def body(self): + return [] + + +def mesh_pipeline(ps, quad_ops=True): + saved_stage = M.MeshStage + M.MeshStage = StubMesh + try: + if not quad_ops: + # the negative control: the pipeline's `self.quad_ops = True` has no effect (reads stay False) + M.MeshPipeline.quad_ops = property(lambda self: False, lambda self, v: None) + return M.MeshPipeline(b'', ps, root_blob()) + finally: + M.MeshStage = saved_stage + if not quad_ops: + del M.MeshPipeline.quad_ops + + +def f32(x): + return struct.unpack('<f', struct.pack('<f', x))[0] + + +def F(bits): + return struct.unpack('<f', struct.pack('<I', bits & 0xffffffff))[0] + + +def U(x): + return struct.unpack('<I', struct.pack('<f', x))[0] + + +def run_quad(lines, attr): + """Run the pixel body's statements on 4 lanes; attr[lane] is the float i.param0.x.""" + env = [{'ip0x': attr[k]} for k in range(4)] + quad = {'QuadReadLaneAt': lambda vals, k: [vals[k]] * 4, + 'QuadReadAcrossX': lambda vals: [vals[k ^ 1] for k in range(4)]} + for line in lines: + line = line.strip() + m = re.fullmatch(r'uint (dpp\d+) = (QuadRead\w+)\((v\d+)(?:, (\d)u)?\);', line) + if m: + vals = [e[m.group(3)] for e in env] + out = quad[m.group(2)](vals, int(m.group(4))) if m.group(4) else quad[m.group(2)](vals) + for k in range(4): + env[k][m.group(1)] = out[k] + continue + m = re.fullmatch(r'(v\d+|o\.mrt0) = (.*);', line) + assert m, line + expr = m.group(2).replace('U(i.param0.x)', 'U(ip0x)') + expr = re.sub(r'float4\((.*)\)', r'(\1)', expr) + for k in range(4): + env[k][m.group(1)] = eval(expr, {'F': F, 'U': U, '__builtins__': {}}, env[k]) + return [e['o.mrt0'] for e in env] + + +def refused(ps, text, build=mesh_pipeline): + try: + build(ps).hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (text, str(error)) + return str(error) + raise AssertionError('accepted: expected a refusal with %r' % text) + + +def main(): + ps = program() + names = [x[2] for x in G.decode(ps)] + assert names[2:7] == ['v_subrev_f32_dpp', 'v_mov_b32_dpp', 'v_mov_b32_dpp', 'v_add_f32_dpp', 'exp'], names + assert G.decode(ps)[5][3].startswith('v_add_f32_dpp v7, -v2, v2 quad_perm:[1,0,3,2]'), G.decode(ps)[5][3] + pipe = mesh_pipeline(ps) + hlsl = pipe.hlsl_ps() + body = pipe.ps.body() + assert ' uint dpp0 = QuadReadLaneAt(v2, 0u);' in body and ' v4 = U(F(v2) - F(dpp0));' in body, body + assert ' uint dpp3 = QuadReadAcrossX(v2);' in body and ' v7 = U((-F(dpp3)) + F(v2));' in body, body + quads = [(0.25, 1.5, -3.0, 7.75), (100.0, 100.0, 100.0, 100.0), (1e-3, 2e-3, 4e-3, 8e-3), (-0.0, 0.0, 5.0, -5.0)] + for a in quads: + a = [f32(x) for x in a] + got = run_quad(body, a) + for k in range(4): + want = (f32(a[1] - a[0]), f32(a[2] - a[0]), f32(a[k] - a[k ^ 1]), a[k]) + assert got[k] == want, (a, k, got[k], want) + # operands the other way round (v_sub_f32_dpp: D = S0' - S1) is the negated derivative on the model + sub = run_quad(mesh_pipeline(program(first_op=4)).ps.body(), (0.25, 1.5, -3.0, 7.75)) + assert sub[0][0] == -1.25 and sub[0][1] == 3.25, sub[0] + + compiled = 'dxc not found' + if os.path.isfile(M.DXC): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'ps.hlsl') + open(path, 'w').write(hlsl) + r = subprocess.run([M.DXC, '-nologo', '-T', 'ps_6_0', '-E', 'main', '-Fo', path + '.cso', path], + capture_output=True, text=True) + assert r.returncode == 0, r.stderr + compiled = 'dxc ps_6_0 ok' + + # controls + try: + G.Pipeline(VS_WORDS, ps, root_blob()).hlsl_ps() + except G.Unsupported as error: + assert str(error) == 'v_subrev_f32_dpp', str(error) + else: + raise AssertionError('the fxc draw pipeline accepted a quad read') + refused(ps, 'v_subrev_f32_dpp', lambda p: mesh_pipeline(p, quad_ops=False)) + refused(program(ctrl0=0x140), 'v_subrev_f32_dpp with row_mirror (not a quad permutation)') + refused(program(fi=0), 'v_subrev_f32_dpp with row_mask:0xf bank_mask:0xf bound_ctrl:1') + # s_cbranch_execz +1 instruction... over the first DPP: a lane with exec off would skip the quad read + skip = struct.pack('<I', 0xbf880002) + refused(program(prefix=skip), 'is skipped on a path to') + # a backward branch (s_cbranch_scc0 to the program start) makes a loop + loop = INTERP + vop2(5, 4, 2, 2, 0) + struct.pack('<I', 0xbf84fffb) + vop1(1, 5, 4, 0x55) + vop1(1, 6, 4, 0xaa) \ + + vop2(3, 7, 2, 2, PERM_X, neg0=1) + EXPORT + assert G.decode(loop)[3][3].startswith('s_cbranch_scc0'), G.decode(loop)[3] + refused(loop, 'in a program with a loop') + print('quad dpp: coarse ddx/ddy and AcrossX match binary32 on %d model quads; %s; 7 controls (fxc refuses, ' + 'sub reversed, quad_ops off, row_mirror, fi:0, skipped, loop)' % (len(quads), compiled)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_quad_uniform_check.py b/tests/startup_quad_uniform_check.py new file mode 100644 index 0000000000..a137ea0eef --- /dev/null +++ b/tests/startup_quad_uniform_check.py @@ -0,0 +1,105 @@ +"""Forward pixel-quad dispatch. Optional DXC and offscreen_check paths run partial-quad WARP draws.""" +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +import startup_quad_dpp_check as Q + +G = Q.G + + +def reference(x, y, skipped): + lane = (x & 1) + 2 * (y & 1) + if lane == skipped: + return 2000 + 8 * y + x + # On entered lanes write a new VGPR value before reading three neighbors. + # The skipped lane (including a helper across the triangle edge) retains its old value. + def source(neighbor): + px = (x & ~1) + (neighbor & 1) + py = (y & ~1) + (neighbor >> 1) + return 8 * py + px + (1000 if neighbor != skipped else 0) + return source(lane ^ 1) + 2 * source(lane ^ 2) + 4 * source(skipped) + + +def draw_fixture(directory, compiler, renderer, skipped, wrong): + s = G.Stage.__new__(G.Stage) + reads = ['uint a = QuadReadAcrossX(v);', 'uint b = QuadReadAcrossY(v);', + 'uint c = QuadReadLaneAt(v, %du);' % skipped] + s.uniform_dpp = set(reads) + s.blocks = [(0, [], ('branch', 'lane == %du' % skipped, 2)), + (1, ['v += 1000u;'] + reads + ['result = a + 2u * b + 4u * c;'], None), + (2, ['++visits;'], ('branch', 'visits < 1u + lane', 2)), + (3, [], ('end',))] + expected = [reference(x, y, skipped) for y in range(8) for x in range(8)] + src = directory / 'test.hlsl' + obj = directory / 'test.cso' + raw = directory / 'test.raw' + src.write_text('static const uint ref[64] = {%s};\n' % ','.join(map(str, expected)) + + 'float4 main(float4 uv : TEXCOORD0, float4 pos : SV_Position) : SV_Target {\n' + 'uint x = uint(pos.x), y = uint(pos.y), p = 8*y + x;\n' + 'uint lane = (x & 1u) + 2u*(y & 1u), v = p, result = 2000u + p, visits = 0u;\n' + + ('if (lane == %du) v += 3000u;\n' % skipped if wrong else '') + + '\n'.join(s.body()) + + '\nreturn result == ref[p] ? float4(0,1,0,1) : float4(1,0,0,1); }\n') + subprocess.run([compiler, '-nologo', '-T', 'ps_6_0', '-E', 'main', '-Fo', obj, src], check=True) + raw.unlink(missing_ok=True) + run = subprocess.run([renderer, 'warp', '--check-pixel-quad-lod', obj, raw], capture_output=True) + assert raw.exists(), (run.returncode, run.stdout, run.stderr) + pixels = list(struct.iter_unpack('<4f', raw.read_bytes())) + assert len(pixels) == 64 + for y in range(8): + for x in range(8): + lane = (x & 1) + 2 * (y & 1) + expected_pixel = (-1,-1,-1,-1) if x+y > 6 else (1,0,0,1) if wrong and lane != skipped else (0,1,0,1) + assert pixels[8*y+x] == expected_pixel, (skipped, wrong, x, y, pixels[8*y+x], expected_pixel) + assert bool(run.returncode) == wrong, (run.stdout, run.stderr) + + +def main(): + os.environ.pop('X2W_PS_QUAD_DIVERGENT', None) + os.environ['X2W_PS_QUAD_UNIFORM'] = '1' + stage = Q.mesh_pipeline(Q.program(prefix=struct.pack('<I', 0xbf880002))).ps + assert not stage.quad_divergent_used + body = stage.body() + assert all(' ' + stmt in body for stmt in stage.dpp_statements) + for stmt in stage.dpp_statements: + i = body.index(' ' + stmt) + assert body[i-1] == ' }' and body[i+1].startswith(' if (pc == ') + # Pixel termination before a shuffle can remove its source lane, even if all + # remaining lanes reach the read. Reject both this and a locally nested read. + for prefix in ('if (kill) discard;', 'if (mask) {'): + old = stage.blocks + stage.blocks = [(n, [prefix] + lines, term) for n, lines, term in old] + try: + stage.check_quad_ops() + except G.Unsupported as error: + assert 'after discard or inside a nested scope' in str(error), error + else: + raise AssertionError('accepted quad read after ' + prefix) + finally: + stage.blocks = old + end = stage.ins[-1][0] + 8 + last_quad = max(stage.dpp_at) + old_ins = stage.ins + for target in (end, last_quad): + stage.ins = old_ins + [(end, 4, 's_cbranch_scc1', 's_cbranch_scc1 label_0x%x' % target)] + try: + stage.check_quad_ops() + except G.Unsupported as error: + assert target == last_quad and 'loop' in str(error), error + else: + assert target == end + stage.ins = old_ins + if len(sys.argv) == 3: + with tempfile.TemporaryDirectory() as directory: + for skipped in range(4): + for wrong in (False, True): + draw_fixture(Path(directory), *sys.argv[1:], skipped, wrong) + print('Four lane masks, 28 covered and 36 clear pixels each, and four clobbered-lane controls passed.') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_readfirstlane_chain_check.py b/tests/startup_readfirstlane_chain_check.py new file mode 100644 index 0000000000..ef36aea9c9 --- /dev/null +++ b/tests/startup_readfirstlane_chain_check.py @@ -0,0 +1,145 @@ +"""v_readfirstlane_b32 of a VGPR computed under a partial exec by a chain of writes from one scalar. + +Synthetic gfx1013 words only. The shape is the unsigned-division reciprocal that compilers emit for a division by +an SGPR value inside a branch (the largest readfirstlane refusal in the translator census): + + s_and_saveexec_b64 s[20:21], vcc + v_cvt_f32_u32 v1, s22 ; v_rcp_f32 v1, v1 ; v_mul_f32 v1, 0x4f7ffffe, v1 ; v_cvt_u32_f32 v1, v1 + v_readfirstlane_b32 s23, v1 + +Every write of v1 changes only the active lanes, but each one reads only s22 and the v1 the previous write left in +those same lanes, so the first active lane holds the value computed from s22, as long as exec is not written +between the first write and the read. This is the scalar recompute of upstream PR #2203 (lower the read by +recomputing the scalar expression that defined the source) in the translator's one-lane model: each write of the +chain also assigns a shadow xv1 in every lane from the previous shadow, and the SGPR takes the last shadow. + +1. The chain above: four lines `xv1 = <shadow>; if (exec & 1) v1 = xv1;`, the first reading s22, each later one + reading xv1, and `s23 = xv1;`. The shadow is declared `uint xv1 = 0;`. +2. A two-register chain (v_cvt_f32_u32 v1, s22; v_rcp_f32 v2, v1): both v1 and v2 get shadows, xv2 reads xv1. +Controls (refused): a link that reads a per-lane value (v_mul_f32 v1, v0, v1); exec written inside the chain +(epoch changes); exec written between the chain and the read; a branch target inside the chain. +Negative control of the change: with partial_shadow limited to lane-invariant expressions (the earlier rule, which +accepted one write only), case 1 is refused again. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class TestPipeline: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def vop1(op, vdst, src0): + return 0x7e000000 | vdst << 17 | op << 9 | src0 + + +def vop2(op, vdst, src0, vsrc1): + return op << 25 | vdst << 17 | vsrc1 << 9 | src0 + + +V = lambda n: 256 + n # noqa: E731 VGPR source operand +CVT_F32_U32, CVT_U32_F32, RCP_F32, READFIRSTLANE, MOV = 6, 7, 0x2a, 2, 1 +MUL_F32 = 8 +LITERAL = 255 + +V_CMP_LT_U32_VCC_V0 = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 +AND_SAVEEXEC = 0xbe800000 | 20 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[20:21], vcc +AND_SAVEEXEC2 = 0xbe800000 | 24 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[24:25], vcc +RESTORE_EXEC = 0xbe800000 | 126 << 16 | 0x04 << 8 | 20 # s_mov_b64 exec, s[20:21] +NOP_BRANCH = 0xbf820000 # s_branch to the next instruction +READ = vop1(READFIRSTLANE, 23, V(1)) # v_readfirstlane_b32 s23, v1 (vdst is the SGPR) +READ_V2 = vop1(READFIRSTLANE, 23, V(2)) # v_readfirstlane_b32 s23, v2 +USE = vop1(MOV, 3, 23) # v_mov_b32 v3, s23 + +C1 = vop1(CVT_F32_U32, 1, 22) # v_cvt_f32_u32 v1, s22 +C2 = vop1(RCP_F32, 1, V(1)) # v_rcp_f32 v1, v1 +C3 = [vop2(MUL_F32, 1, LITERAL, 1), 0x4f7ffffe] # v_mul_f32 v1, 0x4f7ffffe, v1 +C3_LANE = vop2(MUL_F32, 1, V(0), 1) # v_mul_f32 v1, v0, v1 +C4 = vop1(CVT_U32_F32, 1, V(1)) # v_cvt_u32_f32 v1, v1 +ENTER = [V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC] +CHAIN = [C1, C2] + C3 + [C4] + + +def stage(words): + return G.Stage(TestPipeline(), 'vs', struct.pack('<%dI' % (len(words) + 1), *words, 0xbf810000)) + + +def asm(words): + return [x[3] for x in G.decode(struct.pack('<%dI' % len(words), *words))] + + +def body(s): + return [line for block in s.blocks for line in block[1]] + + +def refused(words, label): + try: + stage(words) + except G.Unsupported as error: + assert 'requires a proven uniform source' in str(error), (label, str(error)) + return + raise AssertionError('accepted: ' + label) + + +def main(): + got = asm(ENTER + CHAIN + [READ, USE, READ_V2, C3_LANE]) + assert got == ['v_cmp_lt_u32_e32 vcc_lo, 1, v0', 's_and_saveexec_b64 s[20:21], vcc', 'v_cvt_f32_u32_e32 v1, s22', + 'v_rcp_f32_e32 v1, v1', 'v_mul_f32_e32 v1, 0x4f7ffffe, v1', 'v_cvt_u32_f32_e32 v1, v1', + 'v_readfirstlane_b32 s23, v1', 'v_mov_b32_e32 v3, s23', 'v_readfirstlane_b32 s23, v2', + 'v_mul_f32_e32 v1, v0, v1'], got + + # 1. the reciprocal chain + s = stage(ENTER + CHAIN + [READ, USE]) + lines = body(s) + shadowed = [line for line in lines if line.startswith('xv1 = ')] + assert len(shadowed) == 4, lines + for line in shadowed: + assert line.endswith('; if (exec & 1) v1 = xv1;'), line + assert 's22' in shadowed[0] and not re.search(r'\bv\d+\b', shadowed[0].split(';')[0]), shadowed + for line in shadowed[1:]: + rhs = line.split(';')[0] + assert 'xv1' in rhs[len('xv1 = '):] and not re.search(r'\bv\d+\b', rhs), line + assert 's23 = xv1;' in lines, lines + assert lines.index(shadowed[-1]) < lines.index('s23 = xv1;'), lines + assert 'uint xv1 = 0;' in '\n'.join(s.declarations()), s.declarations() + + # 2. a chain through two registers + two = ENTER + [C1, vop1(RCP_F32, 2, V(1)), READ_V2, USE] + lines = body(stage(two)) + first = [line for line in lines if line.startswith('xv1 = ')] + second = [line for line in lines if line.startswith('xv2 = ')] + assert len(first) == 1 and len(second) == 1, lines + assert 'xv1' in second[0].split(';')[0][len('xv2 = '):], second + assert lines.index(first[0]) < lines.index(second[0]) < lines.index('s23 = xv2;'), lines + + # Controls. + refused(ENTER + [C1, C2, C3_LANE, C4, READ], 'a link reads a per-lane VGPR') + refused(ENTER + [C1, C2, V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC2] + C3 + [C4, READ], 'exec written inside the chain') + refused(ENTER + CHAIN + [RESTORE_EXEC, READ], 'exec written between the chain and the read') + refused(ENTER + [C1, C2, NOP_BRANCH] + C3 + [C4, READ], 'branch target inside the chain') + + # Negative control: the earlier rule (a shadow only for an expression with no VGPR at all). + original = G.Stage.partial_shadow + + def single(self, expr): + return (expr, []) if self.lane_invariant(expr) else None + G.Stage.partial_shadow = single + try: + refused(ENTER + CHAIN + [READ, USE], 'chain shadow disabled') + finally: + G.Stage.partial_shadow = original + print('readfirstlane_chain: 4-write reciprocal chain and a 2-register chain read via shadows xv1/xv2; ' + '4 controls refused; negative control (single-write rule) refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_readfirstlane_exec_check.py b/tests/startup_readfirstlane_exec_check.py new file mode 100644 index 0000000000..a7412d826e --- /dev/null +++ b/tests/startup_readfirstlane_exec_check.py @@ -0,0 +1,124 @@ +"""v_readfirstlane_b32 of a buffer word loaded from a lane-invariant address, also under a partial exec. + +Synthetic gfx1013 words only. The shape is what the run's pixel programs use for a constant read through a +typed or raw buffer inside a branch: `buffer_load_* vN, off, s[..]` (no VGPR address, so every lane reads the +same address) followed by `v_readfirstlane_b32 sM, vN` to move the word to an SGPR. + +AMD RDNA 2 ISA: V_READFIRSTLANE_B32 copies S0 of the first active lane (lane 0 when exec is zero) to the SGPR. +A VGPR write under a partial exec changes only the active lanes, so the first active lane holds the loaded value +as long as exec has not been written between the load and the read. The SGPR belongs to the wave, so the +translation gives every lane that value from a shadow variable assigned in all lanes at the load (lanes that are +inactive keep their own VGPR value). + +1. exec known (entry mask): a load with no VGPR address is lane-invariant, so readfirstlane reads it directly. +2. exec partial (after s_and_saveexec_b64): the load's line becomes `xv1 = ...; if (exec & 1) v1 = xv1;` and the + SGPR takes xv1. +Controls (refused): a VGPR address (offen v0); exec written between the load and the read; the read at a branch +target; a partial-exec value that is not lane-invariant (v0). Negative control of the whole change: with the +shadow record dropped after every VGPR write, case 2 is refused again. +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class TestPipeline: + root = {'params': [{'type': 2}], 'flags': 0} + + def resource(self, key, kind): + assert key == (('root', 0), None) and kind == 'buf', (key, kind) + return 'r0' + + def ud(self, source): + return 0 + + +def load_off(vdst, offset): # buffer_load_dword vD, off, s[8:11], 0 offset:N + return [0xe0000000 | 12 << 18 | offset, vdst << 8 | 2 << 16 | 128 << 24] + + +def load_offen(vdst, vaddr): # buffer_load_dword vD, vA, s[8:11], 0 offen + return [0xe0000000 | 12 << 18 | 1 << 12, vaddr | vdst << 8 | 2 << 16 | 128 << 24] + + +V_CMP_LT_U32_VCC_V0 = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 +AND_SAVEEXEC = 0xbe800000 | 20 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[20:21], vcc +RESTORE_EXEC = 0xbe800000 | 126 << 16 | 0x04 << 8 | 20 # s_mov_b64 exec, s[20:21] +READ = 0x7e000000 | 10 << 17 | 2 << 9 | 257 # v_readfirstlane_b32 s10, v1 +READ_V0 = 0x7e000000 | 10 << 17 | 2 << 9 | 256 # v_readfirstlane_b32 s10, v0 +V_MOV_V1_V0 = 0x7e000000 | 1 << 17 | 1 << 9 | 256 # v_mov_b32 v1, v0 +USE = 0x7e000000 | 2 << 17 | 1 << 9 | 10 # v_mov_b32 v2, s10 +NOP_BRANCH = 0xbf820000 # s_branch to the next instruction + + +def stage(words): + return G.Stage(TestPipeline(), 'vs', struct.pack('<%dI' % (len(words) + 1), *words, 0xbf810000)) + + +def asm(words): + return [x[3] for x in G.decode(struct.pack('<%dI' % len(words), *words))] + + +def body(s): + return '\n'.join(line for block in s.blocks for line in block[1]) + + +def refused(words, label): + try: + stage(words) + except G.Unsupported as error: + assert 'requires a proven uniform source' in str(error), (label, str(error)) + return + raise AssertionError('accepted: ' + label) + + +def main(): + assert asm(load_off(1, 16)) == ['buffer_load_dword v1, off, s[8:11], 0 offset:16'], asm(load_off(1, 16)) + assert asm(load_offen(1, 0)) == ['buffer_load_dword v1, v0, s[8:11], 0 offen'], asm(load_offen(1, 0)) + assert asm([V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC, RESTORE_EXEC, READ]) == [ + 'v_cmp_lt_u32_e32 vcc_lo, 1, v0', 's_and_saveexec_b64 s[20:21], vcc', 's_mov_b64 exec, s[20:21]', + 'v_readfirstlane_b32 s10, v1'], asm([V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC, RESTORE_EXEC, READ]) + + # 1. exec known + text = body(stage(load_off(1, 16) + [READ, USE])) + assert 's10 = v1;' in text, text + + # 2. exec partial + partial = [V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC] + load_off(1, 16) + [READ, RESTORE_EXEC, USE] + text = body(stage(partial)) + assert 'xv1 = r0.Load(a + 0); if (exec & 1) v1 = xv1;' in text, text + assert 's10 = xv1;' in text, text + lines = text.split('\n') + assert lines.index('a = 16;') < lines.index('xv1 = r0.Load(a + 0); if (exec & 1) v1 = xv1;'), text + s = stage(partial) + assert 'uint xv1 = 0;' in '\n'.join(s.declarations()), s.declarations() + + # Controls. + refused(load_offen(1, 0) + [READ], 'VGPR address, exec known') + refused([V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC] + load_offen(1, 0) + [READ], 'VGPR address, exec partial') + refused([V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC] + load_off(1, 16) + [RESTORE_EXEC, READ], + 'exec written between the load and the read') + refused([V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC] + load_off(1, 16) + [NOP_BRANCH, READ], 'read at a branch target') + refused([V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC, V_MOV_V1_V0, READ], 'per-lane value under partial exec') + + # Negative control: without the shadow the partial-exec case is the old refusal. + original = G.Stage.set_v + + def no_shadow(self, n, expr): + original(self, n, expr) + self.partial_uniform.clear() + G.Stage.set_v = no_shadow + try: + refused(partial, 'shadow disabled') + finally: + G.Stage.set_v = original + print('readfirstlane_exec: invariant-address load read with exec known and partial (shadow xv1); ' + '5 controls refused; negative control (shadow off) refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_resource_address_index_check.cpp b/tests/startup_resource_address_index_check.cpp index 60371877f1..1d09dbdc48 100644 --- a/tests/startup_resource_address_index_check.cpp +++ b/tests/startup_resource_address_index_check.cpp @@ -108,8 +108,16 @@ bool agree(const Index& index, const Model& model, std::uint64_t address, std::u // Every record is in the index and the index holds nothing else (the table is never pruned). bool synced(const Index& index, const Model& model) { - for (const auto& [key, r] : model) + for (const auto& [key, r] : model) { if (!index.contains(r.base, key)) return false; + bool found = false, wrong_base = false; + index.for_each_at(r.base, [&](auto candidate) { + found |= candidate == key; + wrong_base |= model.at(candidate).base != r.base; + return false; + }); + if (!found || wrong_base) return false; + } return index.size() == model.size(); } bool mutated(const char* name, int argc, char** argv) { return argc > 2 && !std::strcmp(argv[1], "--mutate") && !std::strcmp(argv[2], name); } diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index fa6fbaf4c5..4f32d7ab6f 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -55,6 +55,8 @@ extern "C" __declspec(dllimport) BOOL x2w_d3d12_written_probe(void*, unsigned lo extern "C" __declspec(dllimport) void x2w_d3d12_bc7_4k_s_written(void*, UINT, UINT); extern "C" __declspec(dllimport) void x2w_d3d12_list_copy_texture_stats(LONG*, LONG*); +extern "C" __declspec(dllimport) int WINAPI x2w_memory_counters(char*, int); + namespace { using namespace x2w_budget; @@ -371,7 +373,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-3"; // d3d12_draw.inl cached_translation constexpr char draw_vertex_shader[] = R"( struct Varying { float4 position : SV_Position; }; @@ -973,12 +975,68 @@ 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); } +// Count successful desktop priority changes and verify the same resource survives an observed reuse. +bool cold_texture_check(Context& c, void* address, bool enabled) +{ + auto expect = [&](unsigned cold, unsigned restored) { + char text[2048]{}; + if (!x2w_memory_counters(text, sizeof(text))) return false; + if (!enabled) return !std::strstr(text, "cold-priority"); + char expected[192]{}; + std::snprintf(expected, sizeof(expected), "cold-priority bytes/count %llu/%u, restored %llu/%u, failures 0", + c.texture_bytes * cold, cold, c.texture_bytes * restored, restored); + if (std::strstr(text, expected)) return true; + std::printf("FAIL: expected %s in %s\n", expected, text); + return false; + }; + Res& texture = c.make_slot133("cold texture", address); + IUnknown* guest = texture.guest.Get(); + auto original = desktop_object<ID3D12Resource>(c.guest, c.device, guest); + if (!original || !expect(0, 0)) return false; + c.release(texture); + if (!expect(1, 0)) return false; + guest->AddRef(); + if (!expect(0, 1)) return false; + auto same = desktop_object<ID3D12Resource>(c.guest, c.device, guest); + if (same.Get() != original.Get()) return false; + guest->Release(); + if (!expect(0, 1)) return false; + // An actual SRV creation is an observed reuse even when the guest never AddRefs the wrapper. + Res& viewed = c.make_slot133("cold sampled SRV", address); + auto* raw = viewed.guest.Get(); + c.release(viewed); + if (!expect(1, 1)) return false; + const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 address, bytes; } + heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}, 0, 0}; + ComPtr<IUnknown> heap; + if (!require(invoke(c.guest, 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap.GetAddressOf()), "cold test SRV heap")) return false; + const auto handle = invoke<UINT64>(heap.Get(), 9); + 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; + invoke<void>(c.guest, 18, raw, &srv, handle); + if (!expect(0, 2)) return false; + Res& ordinary = c.make_committed("ordinary committed texture"); + c.release(ordinary); + c.desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + Res& target = c.make_slot133("render target", address); + c.desc.Flags = D3D12_RESOURCE_FLAG_NONE; + c.release(target); + if (!expect(0, 2)) return false; + // A copy behind a held queue still reads the original pixels after the source's last guest Release. + if (!case1_slot133_copy_and_upload(c, false, address)) return false; + std::puts("cold texture priority: lower, restore, stable object and fenced texture readback passed"); + return true; +} + } // 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"))) + (argc == 3 && std::strcmp(argv[2], "off") && std::strcmp(argv[2], "cold") && std::strcmp(argv[2], "cold-off"))) return 2; ComPtr<IDXGIFactory4> factory; if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; @@ -1014,6 +1072,7 @@ int main(int argc, char** argv) char switch_value[2]{}; const bool switch_on = GetEnvironmentVariableA("X2W_D3D12_RELEASE_RETIRED", switch_value, sizeof(switch_value)) == 1 && switch_value[0] == '1'; + const bool cold_mode = argc == 3 && (!std::strcmp(argv[2], "cold") || !std::strcmp(argv[2], "cold-off")); const bool off_mode = argc == 3; if (switch_on == off_mode) return 2; const bool on = !off_mode; @@ -1048,22 +1107,26 @@ int main(int argc, char** argv) if (!c.make_queue(c.direct) || !c.make_queue(c.gated) || !c.make_list(c.drain_list) || !c.close(c.drain_list)) return 4; if (!x2w_d3d12_budget_snapshot(&c.base, sizeof(c.base))) return 4; - if (!case1_slot133_copy_and_upload(c, on, mem1)) return 5; - std::puts("1 slot 133 copy and upload: held across closed list and gated submit, readback ok, retired"); - if (!case2_same_address_and_slot70_reuse(c, on, mem1)) return 5; - std::puts("2 same-address and slot 70 reuse: existing_memory_texture + resource_address_index ok"); - if (!case3_written_textures_cleanup(c, on, mem1, mem2)) return 5; - std::puts("3 written_textures cleanup: stale bc7_width cleared on address reuse"); - if (!case4_descriptor_and_view_reuse(c, on, mem1, mem2)) return 5; - std::puts("4 descriptor and view reuse: tracked slot-18 SRV holds and retires on overwrite/heap release"); - if (!on) { - if (!case5_ordinary_upload_switch_off(c)) return 5; - std::puts("5 switch-off ordinary texture copy: upload still recorded for a resource outside the retire class"); + if (cold_mode) { + if (!cold_texture_check(c, mem1, !std::strcmp(argv[2], "cold"))) return 5; } else { - if (!case6_written_generation_preserved(c, mem3)) return 5; - std::puts("6 written_textures generation: newer generation of an address kept by the older one's retirement"); - 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 (!case1_slot133_copy_and_upload(c, on, mem1)) return 5; + std::puts("1 slot 133 copy and upload: held across closed list and gated submit, readback ok, retired"); + if (!case2_same_address_and_slot70_reuse(c, on, mem1)) return 5; + std::puts("2 same-address and slot 70 reuse: existing_memory_texture + resource_address_index ok"); + if (!case3_written_textures_cleanup(c, on, mem1, mem2)) return 5; + std::puts("3 written_textures cleanup: stale bc7_width cleared on address reuse"); + if (!case4_descriptor_and_view_reuse(c, on, mem1, mem2)) return 5; + std::puts("4 descriptor and view reuse: tracked slot-18 SRV holds and retires on overwrite/heap release"); + if (!on) { + if (!case5_ordinary_upload_switch_off(c)) return 5; + std::puts("5 switch-off ordinary texture copy: upload still recorded for a resource outside the retire class"); + } else { + if (!case6_written_generation_preserved(c, mem3)) return 5; + std::puts("6 written_textures generation: newer generation of an address kept by the older one's retirement"); + 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"); + } } } catch (int code) { VirtualFree(mem1, 0, MEM_RELEASE); @@ -1077,6 +1140,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 title checks passed" : "switch-off title checks passed"); + if (!cold_mode) std::puts(on ? "release-retired title checks passed" : "switch-off title checks passed"); return 0; } diff --git a/tests/startup_rgba8_dmode.ps1 b/tests/startup_rgba8_dmode.ps1 new file mode 100644 index 0000000000..a3c76cbb96 --- /dev/null +++ b/tests/startup_rgba8_dmode.ps1 @@ -0,0 +1,61 @@ +param( + [Parameter(Mandatory)] [string] $Consumer, + [Parameter(Mandatory)] [string] $Backend, + [Parameter(Mandatory)] [string] $Fxc +) +. "$PSScriptRoot/startup_detile_draw.ps1" +$ErrorActionPreference = 'Stop' +$dir = Join-Path ([IO.Path]::GetTempPath()) ('x2w-rgba8-' + [Guid]::NewGuid().ToString('N')) +[IO.Directory]::CreateDirectory($dir) | Out-Null +try { + # Fixed RGBA8 512x512 offsets from the RDNA2 RB+ 64 KiB display equation. + # Each row gives mip, x, y and byte offset. Mips 3 through 7 share the tail block. + $points = @( + @(0, 4, 1, 0x60050), @(0, 510, 511, 0x15fff8), + @(1, 4, 1, 0x20050), @(1, 254, 255, 0x5fff8), + @(2, 4, 1, 0x10050), @(2, 126, 127, 0x1fff8), + @(3, 4, 1, 0x8050), @(3, 62, 63, 0xbff8), + @(4, 4, 1, 0x4050), @(4, 30, 31, 0x4ff8), + @(5, 4, 1, 0x2050), @(5, 14, 15, 0x23f8), + @(6, 4, 1, 0x1050), @(6, 6, 7, 0x10f8), + @(7, 3, 1, 0x081c), @(7, 2, 3, 0x0838) + ) + $surface = New-Object byte[] 0x160000 + $colors = @() + $loads = for ($i = 0; $i -lt $points.Count; $i++) { + $mip, $x, $y, $offset = $points[$i] + $rgba = [byte[]]@((63 + 9 * $i), (253 - 11 * $i), (21 + 5 * $i), (240 - 7 * $i)) + $rgba.CopyTo($surface, $offset) + $colors += ,$rgba + "case ${i}u: return tex.Load(int3($x,$y,$mip));" + } + $env:X2W_TEST_DETILE_SRV = "$dir/surface" + [IO.File]::WriteAllBytes($env:X2W_TEST_DETILE_SRV, $surface) + $env:X2W_TEST_DETILE_DESC = '10a 3 28 512 512 1 8' + $env:X2W_MEMORY_SRV_DETILE = '1' + $shader = @" +Texture2D<float4> tex : register(t0); +float4 ps(float4 pos : SV_Position) : SV_Target { + switch (uint(pos.x) % 16) { + $($loads -join [Environment]::NewLine) + } + return 0; +} +"@ + $pixels = Invoke-DetileDraw $dir $Consumer $Backend $Fxc $shader 'tex2d' + if ($pixels.Length -ne 64 * 64 * 4) { throw "Unexpected readback size $($pixels.Length)" } + for ($i = 0; $i -lt 4096; $i++) { + $probe = $i % 16 + for ($channel = 0; $channel -lt 4; $channel++) { + $value = $pixels[4 * $i + $channel] + $expected = $colors[$probe][$channel] + if ($value -ne $expected) { + Get-Content "$dir/trap.log" | Select-String -Pattern 'memsrv|slot70|x2w-draw' | Select-Object -Last 18 | Out-Host + throw "pixel $i, mip/x/y/offset $($points[$probe]), channel $channel sampled $value, expected $expected" + } + } + } + Write-Output "$Backend sampled 16 RB+ addresses across all eight RGBA8 mips" +} finally { + [IO.Directory]::Delete($dir, $true) +} diff --git a/tests/startup_root_cbv.cpp b/tests/startup_root_cbv.cpp index 9af9dfb7de..1fd7ee260f 100644 --- a/tests/startup_root_cbv.cpp +++ b/tests/startup_root_cbv.cpp @@ -39,6 +39,8 @@ int draw_root_cbv(void* list) } else if (!std::strcmp(mode, "wrong_type")) { invoke(list, 42, 0, address); invoke(list, 42, 0, address); + } else if (!std::strcmp(mode, "root_srv")) { // LOCAL stall: list slot 44 on the SRV parameter (X2W_ROOT_SRV_LAZY) + invoke(list, 44, 0, address); } else if (std::strcmp(mode, "unbound")) { return 2; } diff --git a/tests/startup_root_srv_lazy_check.py b/tests/startup_root_srv_lazy_check.py new file mode 100644 index 0000000000..9c69936731 --- /dev/null +++ b/tests/startup_root_srv_lazy_check.py @@ -0,0 +1,46 @@ +"""LOCAL stall: a root SRV (list slot 44) read by a translated pixel shader, with and without X2W_ROOT_SRV_LAZY. + +The translated shader reads root parameter 0 through its root pointer (root_address), not through the desktop +root SRV that slot 44 uploads for real desktop pipelines. Both runs draw the colour the title bound (yellow over +the left half). Without the switch (control) slot 44 copies the range at record time ("x2w-render root SRV 0 at +title"); with X2W_ROOT_SRV_LAZY=1 it copies nothing ("X2W_ROOT_SRV_LAZY=1" line, no copy line). +Not covered here: the copy at a real-pipeline draw (bind_lazy_root_srvs); no fixture draws a real pipeline +with a root SRV. +""" +from pathlib import Path +import sys +import tempfile + +from startup_address_srv_check import draw_texture +from startup_root_cbv_check import CLEAR, HLSL + + +def check(directory, consumer, backend): + yellow = bytes((255, 255, 0, 255)) + expected = (yellow * 4 + CLEAR * 4) * 4 + for lazy in (False, True): + folder = directory / ("lazy" if lazy else "copy") + folder.mkdir() + log_path = folder / "trap.log" + env = {"X2W_TEST_ROOT_CBV": "root_srv", "X2W_TRAP_LOG": str(log_path)} + if lazy: + env["X2W_ROOT_SRV_LAZY"] = "1" + pixels = draw_texture(folder, consumer, backend, HLSL, env, binding="srv 0 buf root 0") + if pixels is None: + return 77 + log = log_path.read_text(errors="replace") if log_path.exists() else "" + copied = "x2w-render root SRV 0 at title" in log + deferred = "X2W_ROOT_SRV_LAZY=1: root SRVs are copied at a real-pipeline draw only" in log + print(f"{backend} lazy={int(lazy)}: pixels {'exact' if pixels == expected else 'DIFFER'}, record-time copy line {int(copied)}, " + f"deferred line {int(deferred)}") + if pixels != expected: + raise AssertionError(f"lazy={lazy}: actual {pixels.hex()} expected {expected.hex()}") + if copied == lazy or deferred != lazy: + raise AssertionError(f"lazy={lazy}: copy line {copied}, deferred line {deferred}") + print("PASS") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_round_mode_check.py b/tests/startup_round_mode_check.py new file mode 100644 index 0000000000..fb14d57b50 --- /dev/null +++ b/tests/startup_round_mode_check.py @@ -0,0 +1,395 @@ +"""s_round_mode (MODE[3:0], the f32 and f16/f64 rounding) in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + translate, compile (FXC ps_5_1 when given, DXC ps_6_0), draw one pixel (the + startup_flat_param renderer) and compare the words + +MODE[1:0] rounds f32 results and MODE[3:2] f16 and f64 results; 0 is nearest even, 3 toward zero (LLVM SIDefines.h +FP_ROUND_MODE_SP / FP_ROUND_MODE_DP and FP_ROUND_ROUND_TO_*; Mesa aco_ir.h struct float_mode round32 / round16_64). +The form the pixel stages use is 0xc: f32 to nearest even, f16/f64 toward zero. + +The pixel stage (hand-assembled, the decoder reads it back) starts with s_round_mode 0xc, rounds eight f32 values to +binary16 with v_fma_mixlo_f16 / v_fma_mixhi_f16 (x * 1.0 + 0, f32 operands) and v_cvt_f16_f32, and exports the four +packed words to mrt0. The expected words are computed here by truncating the f32 mantissa (an independent rule, not +the helper's step-back); three of the values round differently to nearest even. v_interp_p2_f16 (the stage of +startup_interp_f16_check with s_round_mode 0xc first) is checked as text. + +Without s_round_mode (MODE 0) the same stage rounds to nearest even through x2w_f32tof16_rne, and its draw must give +the nearest-even words. MEASURED (fxc ps_5_1 and dxc ps_6_0, WARP and an RX 9070 XT): HLSL f32tof16 alone rounds +these values toward zero (70000 -> 0x7bff), which is why both helpers exist; the draw prints that as information. +Controls: without the s_round_mode handler the stage refuses as before; the toward-zero stage does not match the +nearest-even words (the comparison separates the roundings); both helpers' rules are checked on the CPU over f32tof16 +modelled toward zero and nearest even (the draw cannot exercise the toward-zero helper's step-back there). s_round_mode 0x1 (f32 toward +inf), 0x4 (f16 toward ++inf) are refused; one after a branch is lowered when every path sets it, refused when a path skips it; an f16 instruction that rounds and is not lowered for the mode (the SDWA +v_cvt_f16_f32) is refused under 0xc and accepted without it. + +The launch FLOAT_MODE (SPI_SHADER_PGM_RSRC1_PS bits 19:12, the optional third .psin field) starts MODE: 0xcc rounds +f16 toward zero without any s_round_mode, 0xc0 and a request without the field round to nearest even; other modes are +refused. Control: with launch_mode disabled the 0xcc stage stays nearest even. The draw also checks the 0xcc stage. +""" +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, root_blob, compile_hlsl, draw # noqa: E402 + +# f32 inputs: 1 + 0.75 ulp(f16), its negative, 70000 (above the binary16 range), 1/3, 0.1, -1000.7, 1.5 * 2^-14, pi +VALUES = (0x3f801800, 0xbf801800, 0x4788b800, 0x3eaaaaab, 0x3dcccccd, 0xc47a2ccd, 0x38c00000, 0x40490fdb) + + +def f16_toward_zero(bits): + """binary16 of an f32 rounded toward zero, by truncation; only finite values whose result is normal or the + largest finite binary16 (overflow) are used here.""" + sign, exp, mant = bits >> 31, (bits >> 23) & 0xff, bits & 0x7fffff + e = exp - 127 + 15 + assert exp != 0xff and e >= 1, hex(bits) + h = 0x7bff if e >= 31 else e << 10 | mant >> 13 + return sign << 15 | h + + +def f16_nearest(bits): + try: + return struct.unpack('<H', struct.pack('<e', struct.unpack('<f', struct.pack('<I', bits))[0]))[0] + except OverflowError: + return (bits >> 31) << 15 | 0x7c00 + + +def words(rule): + h = [rule(v) for v in VALUES] + return [h[i] | h[i + 1] << 16 for i in range(0, 8, 2)] + + +EXPECTED = ','.join('%08x' % w for w in words(f16_toward_zero)) + + +def v_mov_literal(reg, value): + return struct.pack('<II', 0x7e000000 | reg << 17 | 1 << 9 | 0xff, value) + + +def mix(op, vdst, src0): + # VOP3P (gfx10 0b110011000 << 23): opcode [22:16], vdst [7:0]; src0 [8:0], src1 [17:9] = 1.0 (242), src2 [26:18] + # = 0 (128), op_sel_hi 0 (f32 operands). v_fma_mixlo_f16 0x21, v_fma_mixhi_f16 0x22 (LLVM VOP3PInstructions.td). + return struct.pack('<II', 0xcc000000 | op << 16 | vdst, (256 + src0) | 242 << 9 | 128 << 18) + + +ROUND_MODE = 0xbfa40000 # SOPP opcode 0x24 (rdna2_tools_check: 0900a4bf is s_round_mode 0x9) + + +def pixel_words(mode=0xc, branch=False, add_f16=False, pkrtz=False, skip=False): + w = b'' + if branch: + w += struct.pack('<I', 0xbf840000) # s_cbranch_scc0 to the next instruction: control flow before the mode + if skip: + w += struct.pack('<I', 0xbf850001) # s_cbranch_scc1 over the next dword (the s_round_mode): a path skips it + if mode is not None: + w += struct.pack('<I', ROUND_MODE | mode) + w += b''.join(v_mov_literal(6 + i, v) for i, v in enumerate(VALUES)) + w += mix(0x21, 2, 6) + mix(0x22, 2, 7) + mix(0x21, 3, 8) + mix(0x22, 3, 9) + w += mix(0x21, 4, 10) + mix(0x22, 4, 11) + w += struct.pack('<I', 0x7e000000 | 5 << 17 | 0x0a << 9 | 256 + 12) # v_cvt_f16_f32_e32 v5, v12 + w += mix(0x22, 5, 13) + if pkrtz: + w += struct.pack('<I', 0x2f << 25 | 15 << 17 | 7 << 9 | 256 + 6) # v_cvt_pkrtz_f16_f32_e32 v15, v6, v7 + if add_f16: + # v_cvt_f16_f32_sdwa v14, v12 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD (src0 0xf9 = SDWA; + # second dword: src0 [7:0], dst_sel [10:8], dst_unused [12:11], src0_sel [18:16]) + w += struct.pack('<II', 0x7e000000 | 14 << 17 | 0x0a << 9 | 0xf9, 12 | 4 << 8 | 2 << 11 | 6 << 16) + return w + bytes.fromhex('0f1800f802030405') + bytes.fromhex('000081bf') # exp mrt0 v2..v5 done vm + + +NOT_PASSED = 'not passed' +# SPI inputs: PERSP_SAMPLE/CENTER/CENTROID, LINEAR_SAMPLE/CENTER, POS_X..W, FRONT_FACE (v0..v14; the SDWA preserve of +# add_f16 reads v14, front_face). The stage overwrites the others before reading them. +ENA = 0x1f37 + + +def pipe(ps, launch=0xc0): + """launch: the pixel stage's FLOAT_MODE passed as the third SPI input field, or NOT_PASSED (two fields).""" + return G.Pipeline(VS_WORDS, ps, root_blob(), + ps_hw_inputs=(ENA, ENA) if launch == NOT_PASSED else (ENA, ENA, launch)) + + +def refused(ps, text, launch=0xc0): + try: + pipe(ps, launch).hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (text, str(error)) + return + raise AssertionError('accepted, expected %r' % text) + + +def f16_value(h): + return float('inf') * (-1 if h & 0x8000 else 1) if h & 0x7fff == 0x7c00 else struct.unpack('<e', struct.pack('<H', h))[0] + + +def rne_helper(bits, f32tof16): + """x2w_f32tof16_rne statement by statement, over a model of the adapter's f32tof16.""" + x = struct.unpack('<f', struct.pack('<I', bits))[0] + t, a = f32tof16(bits), abs(x) + if abs(f16_value(t)) > a: + t -= 1 + if t & 0x7c00 == 0x7c00: + return t + lo = abs(f16_value(t)) + if a == lo: + return t + u = t + 1 + hi = 65536.0 if u & 0x7fff == 0x7c00 else abs(f16_value(u)) + dl, dh = a - lo, hi - a + return u if dh < dl or (dh == dl and t & 1) else t + + +def check_rne_rule(): + """x2w_f32tof16_rne against Python's binary16 (struct 'e', round to nearest even, OverflowError past 65519.99) + for f32tof16 modelled both ways: toward zero (MEASURED on WARP and an RX 9070 XT) and nearest even. The cases + cover normal, subnormal (2^-24 .. 2^-14) and overflow (65504 .. 2^17) results and the exact ties.""" + import random + rng = random.Random(2) + def truncate(bits): # toward zero, for any finite value (subnormals and overflow included) + h = f16_nearest(bits) + x = struct.unpack('<f', struct.pack('<I', bits))[0] + return h - 1 if abs(f16_value(h)) > abs(x) else h + ties = [struct.unpack('<I', struct.pack('<f', (f16_value(h) + f16_value(h + 1)) / 2))[0] for h in range(1, 0x7bff, 97)] + cases = list(VALUES) + ties + [0x477fe000, 0x477ff000, 0xc77ff000] + [ + rng.getrandbits(1) << 31 | rng.randrange(103, 144) << 23 | rng.getrandbits(23) for _ in range(30000)] + for bits in cases: + want = f16_nearest(bits) + for name, base in (('toward zero', truncate), ('nearest even', f16_nearest)): + got = rne_helper(bits, base) + assert got == want, (hex(bits), name, hex(got), hex(want)) + print('x2w_f32tof16_rne rule: %d values (%d exact ties), f32tof16 modelled toward zero and nearest even, all ' + 'match binary16 nearest even' % (len(cases), len(ties))) + + +def controls(): + asm = [a for _, _, _, a in G.decode(pixel_words(add_f16=True))] + assert asm[0] == 's_round_mode 0xc', asm + assert asm[9:11] == ['v_fma_mixlo_f16 v2, v6, 1.0, 0', 'v_fma_mixhi_f16 v2, v7, 1.0, 0'], asm + assert asm[15:18] == ['v_cvt_f16_f32_e32 v5, v12', 'v_fma_mixhi_f16 v5, v13, 1.0, 0', 'v_cvt_f16_f32_sdwa v14, v12 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD'], asm + assert [f16_nearest(v) == f16_toward_zero(v) for v in VALUES].count(False) == 3 + ps = pipe(pixel_words()).hlsl_ps() + assert ' v2 = (v2 & 0xffff0000u) | x2w_f32tof16_rtz(F(v6) * 1.0 + F(0x00000000u));' in ps, ps + assert ' v2 = (v2 & 0xffffu) | (x2w_f32tof16_rtz(F(v7) * 1.0 + F(0x00000000u)) << 16);' in ps, ps + assert ' v5 = (v5 & 0xffff0000u) | x2w_f32tof16_rtz(F(v12));' in ps, ps + assert 'uint x2w_f32tof16_rtz(float x)' in ps and 'f32tof16(F(' not in ps, ps + plain = pipe(pixel_words(mode=None)).hlsl_ps() + assert ' v2 = (v2 & 0xffff0000u) | x2w_f32tof16_rne(F(v6) * 1.0 + F(0x00000000u));' in plain, plain + assert ' v5 = (v5 & 0xffff0000u) | x2w_f32tof16_rne(F(v12));' in plain and 'x2w_f32tof16_rtz' not in plain, plain + assert 'x2w_f32tof16_rtz' not in pipe(pixel_words(mode=0)).hlsl_ps() # 0: nearest even, as without it + check_rne_rule() + # v_cvt_pkrtz_f16_f32 rounds toward zero in every mode (its definition), through the helper + for m in (None, 0xc): + g = G.decode(pixel_words(mode=m, pkrtz=True)) + assert g[-3][3] == 'v_cvt_pkrtz_f16_f32_e32 v15, v6, v7', g[-3] + text = pipe(pixel_words(mode=m, pkrtz=True)).hlsl_ps() + assert ' v15 = x2w_f32tof16_rtz(F(v6)) | (x2w_f32tof16_rtz(F(v7)) << 16);' in text, text + # v_interp_p2_f16 rounds its f32 interpolant to binary16 too (startup_interp_f16_check's stage, mode first) + import startup_interp_f16_check as I + interp = I.pipe(struct.pack('<I', ROUND_MODE | 0xc) + I.pixel_words()).hlsl_ps() + assert ' v2 = (v2 & 0xffff0000u) | x2w_f32tof16_rtz(i.loparam0.x);' in interp, interp + assert ' v2 = (v2 & 0xffffu) | (x2w_f32tof16_rtz(i.hiparam0.x) << 16);' in interp, interp + # The helper's rule on the CPU, over both ways f32tof16 can round (WARP measured toward zero, see check_draw): + # nearest even (the step-back then fires) and toward zero (it never does), against the truncation above. + import random + rng = random.Random(1) + cases = list(VALUES) + [rng.getrandbits(1) << 31 | rng.randrange(113, 143) << 23 | rng.getrandbits(23) + for _ in range(20000)] + stepped = 0 + for bits in cases: + x = struct.unpack('<f', struct.pack('<I', bits))[0] + for base in (f16_nearest, f16_toward_zero): + h = base(bits) + back = struct.unpack('<e', struct.pack('<H', h))[0] if h & 0x7c00 != 0x7c00 else float('inf') + got = h - 1 if abs(back) > abs(x) else h + stepped += got != h + assert got == f16_toward_zero(bits), (hex(bits), base.__name__, hex(got)) + assert stepped > 5000, stepped + print('x2w_f32tof16_rtz rule: %d values, nearest-even and toward-zero f32tof16, %d step-backs, all match ' + 'truncation' % (len(cases), stepped)) + print('s_round_mode 0xc: f16 results of fma_mix and v_cvt_f16_f32 round toward zero (x2w_f32tof16_rtz); ' + 'without it, or with 0, nearest even (x2w_f32tof16_rne)') + saved = G.Stage.op_s_round_mode + del G.Stage.op_s_round_mode + try: + refused(pixel_words(), 's_round_mode') + finally: + G.Stage.op_s_round_mode = saved + refused(pixel_words(mode=0x1), 's_round_mode 0x1 (only f32 nearest even') + refused(pixel_words(mode=0x4), 's_round_mode 0x4 (only f32 nearest even') + assert G.decode(pixel_words(branch=True))[0][3].startswith('s_cbranch_scc0') + # after a branch that every path follows to the mode: the mode is known (round_mode_flow), lowered toward zero + assert 'x2w_f32tof16_rtz(F(v12))' in pipe(pixel_words(branch=True)).hlsl_ps() + # a path that skips the s_round_mode reaches the f16 ops with launch 0 and 3: refused + assert G.decode(pixel_words(skip=True))[0][3].startswith('s_cbranch_scc1') + refused(pixel_words(skip=True), 'v_fma_mixlo_f16 at 0x') + refused(pixel_words(skip=True), 'reached under MODE f16 roundings [0, 3] (the translation uses 3)') + # ... and with the launch mode 0xcc both paths bring toward zero: accepted + assert 'x2w_f32tof16_rtz(F(v12))' in pipe(pixel_words(skip=True), launch=0xcc).hlsl_ps() + # negative control: without round_mode_flow the skipped path is lowered as toward zero (wrong for it) + saved_flow = G.Stage.round_mode_flow + G.Stage.round_mode_flow = lambda self: {} + try: + assert 'x2w_f32tof16_rtz(F(v12))' in pipe(pixel_words(skip=True)).hlsl_ps() + finally: + G.Stage.round_mode_flow = saved_flow + # s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 4), 12 (SOPK 0x15) after the mode: a MODE write the tracking misses + setreg = struct.pack('<II', 0xb0000000 | 0x15 << 23 | (1 | 3 << 11), 0xc) + assert G.decode(setreg)[0][3] == 's_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 4), 12' + w = pixel_words() + refused(w[:4] + setreg + w[4:], 's_setreg_imm32_b32 writes MODE in a program that uses s_round_mode') + refused(pixel_words(add_f16=True),'v_cvt_f16_f32_sdwa under s_round_mode f16/f64 toward zero (not lowered)') + assert 'v14 = ' in pipe(pixel_words(mode=None, add_f16=True)).hlsl_ps() + print('controls: refused without the handler; 0x1, 0x4 refused; after a branch lowered, skipped on a path refused (control without the flow); the SDWA v_cvt_f16_f32 (not lowered for the mode) refused under 0xc, ' + 'accepted without it') + launch_controls() + + +def check_dumped_float_mode(): + """gfx2hlsl.dumped_float_mode: u32 at state block A + 0x04c, bits 19:12, from <name>.vsregs or the per-state + dumps <name>.<8 hex>.vsregs when they agree; and translate_request's use of it (.psin without the field).""" + def block(mode, size=0x100): + b = bytearray(size) + if size >= 0x50: + struct.pack_into('<I', b, 0x4c, mode << 12 | 0x2c0041) # other RSRC1 fields set, must not leak + return bytes(b) + with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + (d / 'a.vsregs').write_bytes(block(0xcc)) + (d / 'b.vsregs').write_bytes(block(0xc0)) + (d / 'c.vsregs').write_bytes(block(0xcc, 0x40)) # too short + (d / 'e.00000001.vsregs').write_bytes(block(0xcc)) + (d / 'e.00000002.vsregs').write_bytes(block(0xcc)) + (d / 'f.00000001.vsregs').write_bytes(block(0xcc)) + (d / 'f.00000002.vsregs').write_bytes(block(0xc0)) # disagreeing per-state dumps + got = {n: G.dumped_float_mode(str(d / n)) for n in 'abcefg'} + assert got == {'a': 0xcc, 'b': 0xc0, 'c': None, 'e': 0xcc, 'f': None, 'g': None}, got + print('dumped_float_mode: 0xcc, 0xc0, short block None, agreeing per-state dumps 0xcc, disagreeing None, none None') + + +def launch_controls(): + """The launch FLOAT_MODE (SPI_SHADER_PGM_RSRC1_PS bits 19:12, the optional third .psin field).""" + # 0xcc (the 262 measured mesh pairs): the stage WITHOUT s_round_mode rounds toward zero from launch + text = pipe(pixel_words(mode=None), launch=0xcc).hlsl_ps() + assert ' v5 = (v5 & 0xffff0000u) | x2w_f32tof16_rtz(F(v12));' in text and 'x2w_f32tof16_rne' not in text, text + # 0xc0 (the rest): nearest even + plain = pipe(pixel_words(mode=None), launch=0xc0).hlsl_ps() + assert 'x2w_f32tof16_rne(F(v12))' in plain and 'x2w_f32tof16_rtz(F(v12))' not in plain + # s_round_mode 0 after a 0xcc launch switches back to nearest even + assert 'x2w_f32tof16_rtz(F(v12))' not in pipe(pixel_words(mode=0), launch=0xcc).hlsl_ps() + # an f16 op not lowered for toward zero is refused under a 0xcc launch alone (no s_round_mode), accepted at 0xc0 + refused(pixel_words(mode=None, add_f16=True), 'v_cvt_f16_f32_sdwa under s_round_mode f16/f64 toward zero', + launch=0xcc) + assert 'v14 = ' in pipe(pixel_words(mode=None, add_f16=True), launch=0xc0).hlsl_ps() + # not passed (a two-field .psin): an f16 rounding before any s_round_mode is refused; after s_round_mode 0xc or 0 + # the mode is known; v_cvt_pkrtz_f16_f32 (toward zero by definition) needs no mode + refused(pixel_words(mode=None), 'v_fma_mixlo_f16: f16/f64 rounding with the launch FLOAT_MODE not passed', + launch=NOT_PASSED) + assert pipe(pixel_words(mode=0xc), launch=NOT_PASSED).hlsl_ps() == pipe(pixel_words(mode=0xc)).hlsl_ps() + assert pipe(pixel_words(mode=0), launch=NOT_PASSED).hlsl_ps() == pipe(pixel_words(mode=0)).hlsl_ps() + only_pkrtz = pixel_words(mode=None, pkrtz=True) + only_pkrtz = only_pkrtz[:only_pkrtz.index(mix(0x21, 2, 6))] + only_pkrtz[-16:] # v_movs, pkrtz, exp, s_endpgm + # (ENA PERSP_CENTER + POS_X..W: the export of v2..v5, not written here, reads the position) + assert 'x2w_f32tof16_rtz(F(v6)) | (x2w_f32tof16_rtz(F(v7)) << 16)' in G.Pipeline( + VS_WORDS, only_pkrtz, root_blob(), ps_hw_inputs=(0xf02, 0xf02)).hlsl_ps() + # negative control: without check_launch_known the not-passed stage is accepted (and lowered as nearest even) + saved = G.Stage.check_launch_known + G.Stage.check_launch_known = lambda self, name: None + try: + assert 'x2w_f32tof16_rne(F(v12))' in pipe(pixel_words(mode=None), launch=NOT_PASSED).hlsl_ps() + finally: + G.Stage.check_launch_known = saved + check_dumped_float_mode() + # a MODE write after a non-zero launch mode is refused (the tracking would miss it) + setreg = struct.pack('<II', 0xb0000000 | 0x15 << 23 | (1 | 3 << 11), 0xc) + refused(setreg + pixel_words(mode=None), 's_setreg_imm32_b32 writes MODE', launch=0xcc) + # refused launch modes: f32 not nearest even, f16 toward +inf, other denorm settings + for bad in (0xcd, 0xc4, 0xf0, 0x0c, 0x00): + refused(pixel_words(mode=None), 'launch FLOAT_MODE %#04x' % bad, launch=bad) + # negative control: without launch_mode the 0xcc stage is nearest even (the check above would fail) + saved = G.Stage.launch_mode + G.Stage.launch_mode = lambda self, mode: None + try: + assert 'x2w_f32tof16_rne(F(v12))' in pipe(pixel_words(mode=None), launch=0xcc).hlsl_ps() + finally: + G.Stage.launch_mode = saved + # the .psin line: two fields as before, a third FLOAT_MODE field, malformed ones refused + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / 'r.psin' + for text_in, want in (('spi_ps_input 1 00000002 00000002\n', (2, 2)), + ('spi_ps_input 1 00000002 00000002 000000cc\n', (2, 2, 0xcc)), + ('spi_ps_input 1 00008802 00008802 000000c0\nvs_input 1 0 00000000\n', (0x8802, 0x8802, 0xc0))): + path.write_text(text_in, newline='') + assert G.read_ps_inputs(str(path)) == want, (text_in, G.read_ps_inputs(str(path))) + for bad_in in ('spi_ps_input 1 00000002 00000002 cc\n', 'spi_ps_input 1 00000002 00000002 00000100\n', + 'spi_ps_input 1 00000002 00000002 000000cc\n'): + path.write_text(bad_in, newline='') + try: + G.read_ps_inputs(str(path)) + except G.Unsupported as error: + assert 'invalid SPI input file' in str(error) + else: + raise AssertionError('accepted %r' % bad_in) + print('launch FLOAT_MODE: 0xcc rounds f16 toward zero without s_round_mode, 0xc0 nearest even, not passed refused before s_round_mode; ' + '0xcd 0xc4 0xf0 0x0c 0x00 refused; without launch_mode 0xcc stays nearest even (control); .psin third field parsed') + + +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')] + nearest = ','.join('%08x' % w for w in words(f16_nearest)) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + def build(name, source, profile): + return compile_hlsl(compiler, kind, source, '%s_%s' % (name, kind), profile, directory) + good = pipe(pixel_words()) + vs = build('vs', good.hlsl_vs(), vs_profile) + run = draw(renderer, adapter, vs, build('ps', good.hlsl_ps(), ps_profile), EXPECTED) + if run.returncode: + raise AssertionError('%s translated stage\n%s\n%s' % (kind, run.stdout, run.stderr)) + print('%s s_round_mode 0xc: %s' % (kind, EXPECTED), flush=True) + # control: the comparison tells the two roundings apart (the same stage against nearest-even words) + run = draw(renderer, adapter, vs, build('ps_c', good.hlsl_ps(), ps_profile), nearest) + if run.returncode == 0: + raise AssertionError('%s control: the toward-zero stage matched the nearest-even words' % kind) + print('%s control against nearest-even words %s: mismatches as expected' % (kind, nearest), flush=True) + # the stage without s_round_mode (MODE 0): x2w_f32tof16_rne must draw the nearest-even words + plain_text = pipe(pixel_words(mode=None)).hlsl_ps() + run = draw(renderer, adapter, vs, build('ps_plain', plain_text, ps_profile), nearest) + if run.returncode: + raise AssertionError('%s stage without s_round_mode\n%s\n%s' % (kind, run.stdout, run.stderr)) + print('%s without s_round_mode (x2w_f32tof16_rne): %s' % (kind, nearest), flush=True) + # the stage without s_round_mode under launch FLOAT_MODE 0xcc: toward zero again + run = draw(renderer, adapter, vs, build('ps_launch', pipe(pixel_words(mode=None), launch=0xcc).hlsl_ps(), + ps_profile), EXPECTED) + if run.returncode: + raise AssertionError('%s launch FLOAT_MODE 0xcc\n%s\n%s' % (kind, run.stdout, run.stderr)) + print('%s launch FLOAT_MODE 0xcc, no s_round_mode: %s' % (kind, EXPECTED), flush=True) + # informational, not asserted: how this adapter's own f32tof16 rounds (the helpers replaced by it). + # MEASURED on WARP and an RX 9070 XT (fxc ps_5_1, dxc ps_6_0): toward zero. + raw = plain_text.replace('x2w_f32tof16_rne(F(', 'f32tof16(F(') + assert raw != plain_text + run = draw(renderer, adapter, vs, build('ps_raw', raw, ps_profile), EXPECTED) + print('%s HLSL f32tof16 alone: %s' % (kind, 'toward zero (matches the truncated words)' if run.returncode == 0 + else 'NOT toward zero'), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_rtv_bind_local.cpp b/tests/startup_rtv_bind_local.cpp new file mode 100644 index 0000000000..d78ce08b7d --- /dev/null +++ b/tests/startup_rtv_bind_local.cpp @@ -0,0 +1,247 @@ +// OMSetRenderTargets (list slot 50) with a single descriptor range, handles that hold no view, and the +// outcome counters behind the x2w-targets report line. +// +// startup_rtv_bind <warp|hardware> (X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_RENDER=1 X2W_D3D12_DEBUG=1) +// +// Through D3D12XboxCreateDevice the probe makes an RTV heap of three descriptors over two 1x1 RGBA8 targets, +// views 0 and 1 created, view 2 left empty, and records slot 50 calls on one list. After each call +// x2w_d3d12_target_bind_stats must show exactly one new outcome, the expected one: +// +// 1. one handle, array form bound +// 2. one handle, single range, count 1 single-range bound +// 3. one handle, single range, count 2 single-range bound (view 1 follows view 0 at the RTV stride) +// 4. two handles, array form bound +// 5. single range, count 3 refused: unresolved (view 2 holds nothing) +// 6. single range, count 4 refused: range past heap, or unresolved when the heap has no +// title-side range to measure against +// 7. view 2 alone refused: unresolved +// 8. single range, count 0, null handles refused: empty +// 9. count 9 refused: count over 8 +// 10. view 0 copied into slot 2 (CopyDescriptorsSimple), then slot 2 bound bound +// 11-13. the same heap shape over title memory (title handles map to other desktop handles): +// single range count 2 bound, count 3 unresolved, count 4 refused as range past heap +// +// Then the list is closed and submitted; the desktop device must not be removed and the debug layer must +// store no errors. Draws are not covered. +// +// Exit codes: 0 pass, 77 no physical adapter, other values name the failing step. +#include <d3d12.h> +#include <d3d12sdklayers.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <vector> + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) unsigned x2w_d3d12_target_bind_stats(unsigned* counts, unsigned capacity); + +namespace { +using Word = std::uint64_t; +template <class T> Word arg(T* value) { return reinterpret_cast<Word>(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word); + return reinterpret_cast<Slot>((*static_cast<void***>(object))[index])(object, a, b, c, d, e); +} +bool ok(Word hr) { return SUCCEEDED(static_cast<HRESULT>(hr)); } + +// TargetBind order in d3d12_xs_device.cpp. +enum Outcome { bound, single_bound, not_recording, over_8, unreadable, past_heap, wrong_kind, unresolved, empty, + depth_kind, depth_unknown, depth_plane, outcome_count }; +const char* const names[] = {"bound", "single-range bound", "not recording", "count over 8", "handles unreadable", + "range past heap", "wrong kind", "unresolved", "empty", "depth wrong kind", + "depth unknown", "depth one plane"}; + +struct Stats { + unsigned n[outcome_count] = {}; + static Stats read() + { + Stats s; + x2w_d3d12_target_bind_stats(s.n, outcome_count); + return s; + } +}; + +// Exactly one new outcome since `before`, and it is `want` (or `also`, when given). +bool step(const char* name, Outcome want, Stats& before, int also = -1) +{ + const Stats now = Stats::read(); + unsigned total = 0; + int got = -1; + for (int i = 0; i < outcome_count; ++i) { + const unsigned added = now.n[i] - before.n[i]; + total += added; + if (added) got = i; + } + before = now; + const bool good = total == 1 && (got == want || got == also); + std::printf("%s: %u new outcome(s), last %s (expected %s%s%s)\n", name, total, got >= 0 ? names[got] : "none", names[want], + also >= 0 ? " or " : "", also >= 0 ? names[also] : ""); + return good; +} + +UINT64 debug_errors(ID3D12Device* desktop) +{ + ComPtr<ID3D12InfoQueue> info; + if (FAILED(desktop->QueryInterface(IID_PPV_ARGS(&info)))) return 0; + UINT64 errors = 0; + for (UINT64 i = 0, n = info->GetNumStoredMessages(); i < n; ++i) { + SIZE_T bytes = 0; + if (FAILED(info->GetMessage(i, nullptr, &bytes))) continue; + std::vector<char> storage(bytes); + auto* message = reinterpret_cast<D3D12_MESSAGE*>(storage.data()); + if (FAILED(info->GetMessage(i, message, &bytes))) continue; + if (message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { + ++errors; + std::printf("debug layer: %.*s\n", static_cast<int>(message->DescriptionByteLength), message->pDescription); + } + } + return errors; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + ComPtr<IDXGIFactory6> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr<IDXGIAdapter> adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr<IDXGIAdapter1> candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) 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 (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + std::printf("adapter=%ls\n", adapter_desc.Description); + + std::array<unsigned char, 64> parameters{}; + void* device = nullptr; + ComPtr<ID3D12Device> desktop; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &device))) return 4; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 4; + + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC target_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0, 0, 0, 0}}; + ComPtr<ID3D12Resource> targets[2]; + for (auto& target : targets) + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_COMMON, + &clear, IID_PPV_ARGS(&target)))) return 5; + + // The RTV heap: views 0 and 1 over the two targets, slot 2 empty; and a one-descriptor staging heap. + const auto make_heap = [&](UINT count, void** out) { + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, count}, 0, 0}; + return ok(invoke(device, 14, arg(&desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(out))); + }; + void *rtv_heap = nullptr, *staging_heap = nullptr; + if (!make_heap(3, &rtv_heap) || !make_heap(1, &staging_heap)) return 6; + // The title's stride: the stand-in forwards GetDescriptorHandleIncrementSize (device slot 15). + const UINT stride = static_cast<UINT>(invoke(device, 15, D3D12_DESCRIPTOR_HEAP_TYPE_RTV)); + std::printf("RTV stride as the title sees it: %u (desktop %u)\n", stride, + desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)); + const D3D12_CPU_DESCRIPTOR_HANDLE first{static_cast<SIZE_T>(invoke(rtv_heap, 9))}; + const std::array<D3D12_CPU_DESCRIPTOR_HANDLE, 3> rtv{{first, {first.ptr + stride}, {first.ptr + 2 * stride}}}; + const D3D12_CPU_DESCRIPTOR_HANDLE staging{static_cast<SIZE_T>(invoke(staging_heap, 9))}; + D3D12_RENDER_TARGET_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + invoke(device, 20, arg(targets[0].Get()), arg(&view), rtv[0].ptr); + invoke(device, 20, arg(targets[1].Get()), arg(&view), rtv[1].ptr); + invoke(device, 20, arg(targets[0].Get()), arg(&view), staging.ptr); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *queue = nullptr, *fence = nullptr, *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 7; + if (!ok(invoke(list, 139, arg(allocator), 0))) return 8; + + const D3D12_CPU_DESCRIPTOR_HANDLE pair[] = {rtv[0], rtv[1]}; + Stats seen = Stats::read(); + invoke(list, 50, 1, arg(&rtv[0]), FALSE, 0); + if (!step("1 one handle", bound, seen)) return 10; + invoke(list, 50, 1, arg(&rtv[0]), TRUE, 0); + if (!step("2 single range, count 1", single_bound, seen)) return 11; + invoke(list, 50, 2, arg(&rtv[0]), TRUE, 0); + if (!step("3 single range, count 2", single_bound, seen)) return 12; + invoke(list, 50, 2, arg(pair), FALSE, 0); + if (!step("4 two handles", bound, seen)) return 13; + invoke(list, 50, 3, arg(&rtv[0]), TRUE, 0); + if (!step("5 single range reaching the empty view", unresolved, seen)) return 14; + invoke(list, 50, 4, arg(&rtv[0]), TRUE, 0); + if (!step("6 single range past the heap end", past_heap, seen, unresolved)) return 15; + invoke(list, 50, 1, arg(&rtv[2]), FALSE, 0); + if (!step("7 the empty view alone", unresolved, seen)) return 16; + invoke(list, 50, 0, 0, TRUE, 0); + if (!step("8 single range, count 0, null handles", empty, seen)) return 17; + invoke(list, 50, 9, arg(&rtv[0]), TRUE, 0); + if (!step("9 count above 8", over_8, seen)) return 18; + invoke(device, 24, 1, rtv[2].ptr, staging.ptr, D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + invoke(list, 50, 1, arg(&rtv[2]), FALSE, 0); + if (!step("10 copied view in the empty slot", bound, seen)) return 19; + + // An RTV heap over title memory: title handles differ from desktop ones and each target of a single range + // must be mapped on its own; the heap's end is known, so a range past it has its own reason. + void* backing = VirtualAlloc(nullptr, 3 * stride, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } backed_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 3}, reinterpret_cast<Word>(backing), Word{3} * stride}; + void* backed_heap = nullptr; + if (!backing || !ok(invoke(device, 14, arg(&backed_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&backed_heap)))) return 30; + const D3D12_CPU_DESCRIPTOR_HANDLE title_first{static_cast<SIZE_T>(invoke(backed_heap, 9))}; + std::printf("backed heap: title start 0x%llx, backing 0x%llx\n", static_cast<unsigned long long>(title_first.ptr), + static_cast<unsigned long long>(reinterpret_cast<Word>(backing))); + if (title_first.ptr != reinterpret_cast<SIZE_T>(backing)) return 31; + invoke(device, 20, arg(targets[0].Get()), arg(&view), title_first.ptr); + invoke(device, 20, arg(targets[1].Get()), arg(&view), title_first.ptr + stride); + invoke(list, 50, 2, arg(&title_first), TRUE, 0); + if (!step("11 backed heap, single range, count 2", single_bound, seen)) return 32; + invoke(list, 50, 3, arg(&title_first), TRUE, 0); + if (!step("12 backed heap, single range reaching the empty view", unresolved, seen)) return 33; + invoke(list, 50, 4, arg(&title_first), TRUE, 0); + if (!step("13 backed heap, single range past the heap end", past_heap, seen)) return 34; + const D3D12_CPU_DESCRIPTOR_HANDLE unmapped_dsv{1}, null_dsv{}; + invoke(list, 50, 0, 0, FALSE, arg(&unmapped_dsv)); + if (!step("14 unreadable depth-only target cannot form an empty UAV pass", depth_unknown, seen)) return 35; + invoke(list, 50, 0, 0, FALSE, arg(&null_dsv)); + if (!step("15 explicit zero depth handle clears the previous refusal", empty, seen)) return 36; + + if (!ok(invoke(list, 9))) return 20; + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), 1))) return 21; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < 1) { + if (GetTickCount64() >= deadline) return 22; + Sleep(1); + } + const HRESULT removed = desktop->GetDeviceRemovedReason(); + const UINT64 errors = debug_errors(desktop.Get()); + std::printf("device removed reason: 0x%08lx, debug layer errors: %llu\n", static_cast<unsigned long>(removed), + static_cast<unsigned long long>(errors)); + return removed == S_OK && errors == 0 ? 0 : 70; +} diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index 8d9c55a686..89cc5d8e94 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -189,7 +189,9 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), elif [line.strip() for line in decode(summary.read_bytes()).splitlines() if line.strip()] != STUB_LINES: found.append(f"stub exit {code}: {summary.name} does not hold the debugger's output") want = [str(exe), str(data), str(log), "--timeout", "9", "--memory-gib", "3", - "--trace-files", "1", "--continue-asserts", "4", *passed] + "--trace-files", "1", "--continue-asserts", "4", + # LOCAL run.ps1 switches -FastExit (off) and -LogRepeats (default 200) are always forwarded + "--fast-exit", "0", "--log-repeats", "200", *passed] record = startup / "debugger.json" got = json.loads(record.read_text(encoding="utf-8")) if record.is_file() else None expected = [want, "1" if "-TraceApi" in switches else trace_api_env] diff --git a/tests/startup_sample_c_border_check.py b/tests/startup_sample_c_border_check.py new file mode 100644 index 0000000000..8e4904e889 --- /dev/null +++ b/tests/startup_sample_c_border_check.py @@ -0,0 +1,80 @@ +"""image_sample_c_lz with SQ_TEX_CLAMP_BORDER (6) in sampler word 0 CLAMP_X / CLAMP_Y. + +Mesa src/amd/registers/gfx10-rsrc.json (bb59ce45): SQ_IMG_SAMP_WORD0 CLAMP_X [2:0], CLAMP_Y [5:3], CLAMP_Z [8:6]; +SQ_IMG_SAMP_WORD3 BORDER_COLOR_PTR [11:0], BORDER_COLOR_TYPE [31:30]. radv_sampler.c maps VK CLAMP_TO_BORDER to +SQ_TEX_CLAMP_BORDER and the static border colours to BORDER_COLOR_TYPE 0 (transparent black), 1 (opaque black), +2 (opaque white); 3 is a border colour table entry. + +The fixture constructs a comparison sampler with border addressing on both axes. +Check that its manifest preserves the original words and verify the refusal for a register border color. +""" +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.parent / 'tools')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import pixel_aot # noqa: E402 +import startup_image_sample_c_check as C # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, root_blob # noqa: E402 + +# Border X/Y, point sampling, EQUAL comparison, point mip filter and opaque white border. +SYNTHETIC = (6 | (6 << 3) | (2 << 12) | (1 << 27), 4 << 20, (1 << 26) | (1 << 28), 2 << 30) + + +def s_mov(reg, value): + return struct.pack('<II', 0xbe8003ff | reg << 16, value) + + +def stage(words): + code = C.WORDS['lz'] + start = code.index(bytes.fromhex('ff0398be')) # s_mov_b32 s24, literal + end = start + 8 + 3 * 4 # then s_mov_b32 s25, s26, s27 with inline 0 + assert [a for _, _, _, a in G.decode(code[start:end])] == [ + 's_mov_b32 s24, 0x8001012', 's_mov_b32 s25, 0', 's_mov_b32 s26, 0', 's_mov_b32 s27, 0'] + return code[:start] + b''.join(s_mov(24 + i, w) for i, w in enumerate(words)) + code[end:] + + +def ps(words): + pipe = G.Pipeline(VS_WORDS, stage(words), root_blob(flags=0)) + return pipe, pipe.hlsl_ps() + + +def refused(words, text): + try: + ps(words) + except G.Unsupported as error: + assert text in str(error), (hex(words[0]), str(error)) + else: + raise AssertionError('accepted: %s' % ' '.join('%#x' % w for w in words)) + + +def main(): + pipe, text = ps(SYNTHETIC) + method, u, v, ref, _, _ = C.lowered(text) + assert (method, u, v, ref) == ('SampleCmpLevelZero', 'v1', 'v2', 'v0'), (method, u, v, ref) + assert 'SamplerComparisonState q0 : register(s0);' in text, text + assert C.manifest_samplers(pipe) == ['smpc 0 ' + ' '.join(hex(word) for word in SYNTHETIC)], C.manifest_samplers(pipe) + x_only = (SYNTHETIC[0] & ~0x38 | 2 << 3,) + SYNTHETIC[1:] + for words in (x_only, SYNTHETIC[:3] + (0,), SYNTHETIC[:3] + (0x40000000,)): + ps(words) + refused(SYNTHETIC[:3] + (0xc0000000,), 'border colour from the border colour table (BORDER_COLOR_TYPE 3)') + refused((SYNTHETIC[0] & ~7 | 7,) + SYNTHETIC[1:], 'requires CLAMP_LAST_TEXEL in X and Y') + refused((SYNTHETIC[0] & ~7 | 4,) + SYNTHETIC[1:], 'requires CLAMP_LAST_TEXEL in X and Y') + refused((SYNTHETIC[0] | 1 << 9,) + SYNTHETIC[1:], 'anisotropy') + try: + pixel_aot.comparison_sampler_state((SYNTHETIC[0], SYNTHETIC[1], SYNTHETIC[2] & ~(1 << 28), SYNTHETIC[3])) + except ValueError as error: + assert 'CLAMP_LAST_TEXEL' in str(error) + else: + raise AssertionError('pixel_aot accepts CLAMP_BORDER: the negative control no longer shows the gap') + print('sample_c_border: synthetic CLAMP_BORDER opaque-white sampler lowered on c_lz with its words kept; X-only ' + 'border and types 0/1 accepted; type 3, MIRROR_ONCE_BORDER, CLAMP_HALF_BORDER and anisotropy refused; ' + 'pixel_aot still refuses CLAMP_BORDER (negative control)') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_sample_c_preclamp_check.py b/tests/startup_sample_c_preclamp_check.py new file mode 100644 index 0000000000..483e70da0c --- /dev/null +++ b/tests/startup_sample_c_preclamp_check.py @@ -0,0 +1,66 @@ +"""Check the preclamp flag on a synthetic point-filtered comparison sampler. + +An explicit level-zero sample may ignore preclamp. Implicit LOD and unsupported +filter flags must retain the decoder's refusal. +""" +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.parent / 'tools')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import pixel_aot # noqa: E402 +import startup_image_sample_c_check as C # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, root_blob # noqa: E402 + +# CLAMP_LAST_TEXEL in X and Y, point-filter truncation, GREATER comparison. +SYNTHETIC = (C.POINT | (4 << 12), 0, (1 << 26) | (1 << 28), 0) +S24 = bytes.fromhex('ff0398be') # s_mov_b32 s24, literal +S26_ZERO = bytes.fromhex('80039abe') # s_mov_b32 s26, 0 + + +def patched(name, w0, w2): + words = C.WORDS[name] + i = words.index(S24) + words = words[:i + 4] + struct.pack('<I', w0) + words[i + 8:] + assert words.count(S26_ZERO) == 1, name + return words.replace(S26_ZERO, bytes.fromhex('ff039abe') + struct.pack('<I', w2)) + + +def ps(name, w0, w2): + pipe = G.Pipeline(VS_WORDS, patched(name, w0, w2), root_blob(flags=0)) + return pipe, pipe.hlsl_ps() + + +def refused(name, w0, w2, text): + try: + ps(name, w0, w2) + except G.Unsupported as error: + assert text in str(error), (name, str(error)) + else: + raise AssertionError('accepted: %s %#x' % (name, w2)) + + +def main(): + pipe, text = ps('lz', SYNTHETIC[0], SYNTHETIC[2]) + method, u, v, ref, _, _ = C.lowered(text) + assert (method, u, v, ref) == ('SampleCmpLevelZero', 'v1', 'v2', 'v0'), (method, u, v, ref) + assert 'SamplerComparisonState q0 : register(s0);' in text, text + assert C.manifest_samplers(pipe) == ['smpc 0 ' + ' '.join(hex(word) for word in SYNTHETIC)], C.manifest_samplers(pipe) + refused('lz', SYNTHETIC[0], SYNTHETIC[2] | 1 << 29, 'word 2 bits 28-31') + refused('c', SYNTHETIC[0], SYNTHETIC[2], 'word 2 bits 28-31') + try: + pixel_aot.comparison_sampler_state(SYNTHETIC) + except ValueError as error: + assert 'word 2 bits 28-31' in str(error) + else: + raise AssertionError('pixel_aot accepts bit 28: the negative control no longer shows the gap') + print('sample_c_preclamp: synthetic comparison sampler (MIP_POINT_PRECLAMP) lowered on c_lz with its words kept; ' + 'bit 29 and implicit-LOD controls refused; pixel_aot still refuses bit 28 (negative control)') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_sampler_comparison_check.cpp b/tests/startup_sampler_comparison_check.cpp index 5608401c66..2b56e103d1 100644 --- a/tests/startup_sampler_comparison_check.cpp +++ b/tests/startup_sampler_comparison_check.cpp @@ -56,6 +56,31 @@ int main() expect(both[1].ShaderRegister == 1 && both[1].Filter == 0x80 && both[1].ComparisonFunc == D3D12_COMPARISON_FUNC_LESS, "comparison sampler at register 1", both[1].Filter, both[1].ComparisonFunc); } + // Signed 14-bit fixed-point LOD bias uses eight fractional bits. + { + using x2w_startup::decode_sampler; + const auto biased = decode_sampler({0, 0xfffu << 12, (1u << 26) | ((1u << 14) - 128), 0}, 0, false, false, true); + expect(biased.MipLODBias == -0.5f && biased.MinLOD == 0.0f && biased.MaxLOD == D3D12_FLOAT32_MAX, "bias -0.5"); + expect(decode_sampler({0, 0, 0x100, 0}, 0, false, false, true).MipLODBias == 1.0f, "bias +1"); + expect(decode_sampler({0, 0, 0x2000, 0}, 0, false, false, true).MipLODBias == D3D12_MIP_LOD_BIAS_MIN, "bias clamped low"); + expect(decode_sampler({0, 0, 0x1fff, 0}, 0, false, false, true).MipLODBias == D3D12_MIP_LOD_BIAS_MAX, "bias clamped high"); + const auto limited = decode_sampler({0, 0x180u | 0x280u << 12, 0, 1u << 30}, 0, false, false, true); + expect(limited.MinLOD == 1.5f && limited.MaxLOD == 2.5f, "min 1.5 max 2.5"); + expect(limited.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK, "border opaque black"); + expect(decode_sampler({0, 0, 0, 2u << 30}, 0, false, false, true).BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + "border opaque white"); + expect(decode_sampler({0, 0, 0, 3u << 30}, 0, false, false, true).BorderColor == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK, + "border register -> transparent black"); + expect(decode_sampler({0, 0x300u | 0x100u << 12, 0, 0}, 0, false, false, true).MaxLOD == 3.0f, "max below min raised to min"); + // Border color is decoded independently of the optional LOD fields. + const auto plain = decode_sampler({0, 0x180u | 0x280u << 12, (1u << 26) | ((1u << 14) - 128), 2u << 30}, 0, false, false, false); + expect(plain.MipLODBias == 0.0f && plain.MinLOD == 0.0f && plain.MaxLOD == D3D12_FLOAT32_MAX && + plain.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, "border retained with LOD fields off"); + const auto dynamic = x2w_startup::dynamic_sampler({0, 0, 0, 2u << 30}, true); + expect(dynamic.BorderColor[0] == 1.0f && dynamic.BorderColor[3] == 1.0f, "dynamic border white"); + const auto fallback = x2w_startup::border_sampler(); + expect(fallback.MaxLOD == D3D12_FLOAT32_MAX, "fallback sampler unlimited"); + } // An smpl line (image_sample_b) carries MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12), u4.8, to MinLOD and // MaxLOD; the same words on an smp line keep MinLOD 0 and an unbounded MaxLOD. x2w_startup::TranslatedSamplers limits; diff --git a/tests/startup_sampler_x.cpp b/tests/startup_sampler_x.cpp index a64ce2bd77..b9b58656d5 100644 --- a/tests/startup_sampler_x.cpp +++ b/tests/startup_sampler_x.cpp @@ -3,6 +3,7 @@ // translated sampler must reproduce: filter, per-axis address mode, border colour and LOD limits. #include "desktop_gpu.h" #include "startup_sampler_x_cs.h" +#include "startup_stubs/translated_sampler_bindings.h" #include <algorithm> #include <array> @@ -59,6 +60,15 @@ constexpr std::array<SamplerCase, 3> samplers{{ D3D12_FLOAT32_MAX}, }}; constexpr UINT word_count = static_cast<UINT>(2 * point_probes.size() + linear_probes.size()); +// The three samplers above as SQ_IMG_SAMP words (word 0: CLAMP_X 2:0, CLAMP_Y 5:3; word 1: MIN_LOD 11:0, MAX_LOD 23:12, +// u4.8; word 2: XY_MAG 21:20, XY_MIN 23:22, MIP 27:26; word 3: BORDER_COLOR_TYPE 31:30, 2 = opaque white), for the +// words variants: the desktop samplers are then the translation (translated_sampler_bindings.h dynamic_sampler). +constexpr std::uint32_t white = 2u << 30; +constexpr std::array<x2w_startup::SamplerWords, 3> sampler_words{{ + {0u | 1u << 3, 256u | 512u << 12, 0u, white}, // wrap / mirror, LOD 1..2 + {2u | 6u << 3, 0u, 0u, white}, // clamp / border, LOD 0..0 + {2u | 2u << 3, 0xfffu << 12, 1u << 20 | 1u << 22 | 2u << 26, white}, // trilinear, clamp, no limit +}}; bool is_linear(const SamplerCase& s) { @@ -219,7 +229,9 @@ ComPtr<ID3D12RootSignature> create_root(ID3D12Device* device) } } -bool check_startup_sampler_x(ID3D12Device* device, bool swapped) +// words: 0 desktop samplers; 1 translated from sampler_words with the LOD and border fields; 2 translated without +// them (the negative control: MIN_LOD, MAX_LOD and the white border are lost, so the readback must differ). +bool check_startup_sampler_x(ID3D12Device* device, bool swapped, int words) { check_probe_coverage(); D3D12_FEATURE_DATA_FORMAT_SUPPORT support{DXGI_FORMAT_R32_FLOAT}; @@ -272,7 +284,7 @@ bool check_startup_sampler_x(ID3D12Device* device, bool swapped) for (UINT i = 0; i < samplers.size(); ++i) { auto handle = sampler_heap->GetCPUDescriptorHandleForHeapStart(); handle.ptr += SIZE_T{bound_case(i)} * sampler_stride; - const auto desc = desktop_sampler(samplers[i]); + const auto desc = words ? x2w_startup::dynamic_sampler(sampler_words[i], words == 1) : desktop_sampler(samplers[i]); device->CreateSampler(&desc, handle); } @@ -345,8 +357,8 @@ bool check_startup_sampler_x(ID3D12Device* device, bool swapped) } std::printf("\n"); } - std::printf("startup_sampler_x swapped=%u mismatches=%u of %u\n", static_cast<unsigned>(swapped), mismatches, - word_count); + std::printf("startup_sampler_x swapped=%u words=%d mismatches=%u of %u\n", static_cast<unsigned>(swapped), words, + mismatches, word_count); if (mismatches) throw std::runtime_error("Sampler contract readback differs from reference"); return true; } diff --git a/tests/startup_saveexec_same_reg_check.py b/tests/startup_saveexec_same_reg_check.py new file mode 100644 index 0000000000..6dd47a5e3a --- /dev/null +++ b/tests/startup_saveexec_same_reg_check.py @@ -0,0 +1,67 @@ +"""s_and_saveexec_b64 whose destination is its own source: S0 is read before D is written. + +RDNA 2 ISA SOP1 S_AND_SAVEEXEC_B64: D = EXEC; EXEC = S0 & EXEC; SCC = (EXEC != 0), where S0 is the value at issue. +With D == S0 (s_and_saveexec_b64 s[6:7], s[6:7], seen in title vertex and pixel stages; found by the compute +agent's vs/ps review) the translation used to write s6 = exec first and then compute exec & s6 = exec & exec, so +the branch let the lane in whatever the condition. Synthetic words: v_cmp_lt_u32 vcc, 1, v0; s_mov_b64 s[6:7], vcc; +s_and_saveexec_b64 s[6:7], s[6:7]. The emitted lines are run as Python for v0 = 0 (condition false: exec must be +0, s6 the old exec 1) and v0 = 2 (exec 1). Control: with S0 = s[8:9] no temporary is used and the result is the +same. Negative control: the old line order (s6 = exec before the read) gives exec 1 for v0 = 0. +""" +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_scalar_bits_check import asm, sop1, stage # noqa: E402 + +CMP_VCC = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 + + +def lines(words): + s = stage([]) + s.lines = [] + for i, (_, n, name, text) in enumerate(G.decode(struct.pack('<%dI' % len(words), *words))): + s.pc = i + s.one(name, text) + return s, s.lines + + +def run(body, v0): + env = {'v0': v0, 'exec': 1} + for line in body: + for stmt in filter(None, (x.strip() for x in line.split(';'))): + py = re.sub(r'(0x[0-9a-f]+|\d+)u\b', r'\1', stmt) + py = re.sub(r'\(\((.*)\) \? 1 : 0\)', r'int(\1)', py) + name, expr = py.split(' = ', 1) + env[name] = eval(expr, {}, env) + return env + + +def main(): + same = [CMP_VCC, sop1(4, 6, 106), sop1(0x24, 6, 6)] + assert asm(same)[2] == 's_and_saveexec_b64 s[6:7], s[6:7]', asm(same) + s, body = lines(same) + assert 'xsave = s6;' in body and s.uses_xsave, body + assert ' uint xsave = 0;' in s.declarations(), s.declarations() + for v0, want in ((0, 0), (2, 1)): + env = run(body, v0) + assert env['exec'] == want and env['s6'] == 1, (v0, env) + other = [CMP_VCC, sop1(4, 8, 106), sop1(0x24, 6, 8)] + s2, body2 = lines(other) + assert not s2.uses_xsave and not any('xsave' in x for x in body2), body2 + for v0, want in ((0, 0), (2, 1)): + assert run(body2, v0)['exec'] == want + old = [x for x in body if not x.startswith('xsave')] + old = [x.replace('xsave', 's6') for x in old] + assert run(old, 0)['exec'] == 1 # the bug the fix removes: the lane enters with a false condition + print('saveexec_same_reg: S0 read before D (exec 0 / 1 for a false / true condition, s6 = old exec); ' + 'distinct-register control unchanged; the old order lets the lane in (negative control)') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scalar_bits_check.py b/tests/startup_scalar_bits_check.py new file mode 100644 index 0000000000..120fc69c16 --- /dev/null +++ b/tests/startup_scalar_bits_check.py @@ -0,0 +1,155 @@ +"""s_bitset0/1_b32, s_bcnt0/1_i32_b32 and v_xor3_b32. + +Synthetic gfx1013 words only. References written from the AMD RDNA 2 ISA descriptions: +- S_BITSET0_B32 / S_BITSET1_B32: D.u[S0.u[4:0]] = 0 / 1, the other bits of D kept; SCC not written (LLVM + SOPInstructions.td: D tied as an input, no SCC def). +- S_BCNT0_I32_B32 / S_BCNT1_I32_B32: D = number of zero / one bits in S0; SCC = (D != 0). +- V_XOR3_B32 (gfx10 VOP3 0x178): D = S0 ^ S1 ^ S2. +The emitted HLSL is evaluated with the integer evaluator of startup_gfx2hlsl_bit_alu_check over an edge grid. +Controls (refused): s_bitset1_b32 into a lane-mask SGPR; s_bcnt1_i32_b32 of exec_lo and of a mask SGPR (a lane +count the one-lane model cannot give). Constant folding: s_bitset1_b32 on a constant SGPR keeps a constant. +Negative control: the evaluator finds a mismatch for a deliberately wrong expression of each form. +""" +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_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +GRID = [0, 1, 2, 31, 32, 33, 0x7fffffff, 0x80000000, 0xfffffffe, MASK, 0x12345678, 0x0000ffff] + + +class TestPipeline: + root = {'params': [{'type': 2}], 'flags': 0} + + def resource(self, key, kind): + return 'r0' + + def ud(self, source): + return 0 + + +def sop1(op, dst, src): + return 0xbe800000 | dst << 16 | op << 8 | src + + +def stage(words): + return G.Stage(TestPipeline(), 'vs', struct.pack('<%dI' % (len(words) + 1), *words, 0xbf810000)) + + +def asm(words): + return [x[3] for x in G.decode(struct.pack('<%dI' % len(words), *words))] + + +def lines_of(words): + """The lines one instruction emits, on a bare stage with nothing known about its registers.""" + s = stage([]) + s.lines = [] + _, n, name, text = G.decode(struct.pack('<%dI' % len(words), *words))[0] + s.pc = 0 + s.one(name, text) + return s, s.lines + + +def rhs(line, reg): + assert line.startswith('%s = ' % reg) and line.endswith(';'), line + return line[len(reg) + 3:-1] + + +def refs(): + return { + 's_bitset0_b32': lambda d, s: d & ~(1 << (s & 31)) & MASK, + 's_bitset1_b32': lambda d, s: (d | 1 << (s & 31)) & MASK, + 's_bcnt0_i32_b32': lambda d, s: 32 - bin(s).count('1'), + 's_bcnt1_i32_b32': lambda d, s: bin(s).count('1'), + } + + +def mismatches(expr, ref, scc_expr=None): + bad = [] + for d in GRID: + for s in GRID: + got = expr.run({'s5': d, 's6': s})[0] & MASK + if got != ref(d, s): + bad.append((d, s, got, ref(d, s))) + if scc_expr is not None: + scc = bool(scc_expr.run({'s5': got})[0]) + if scc != (ref(d, s) != 0): + bad.append(('scc', d, s)) + return bad + + +def check_scalar(): + forms = 0 + for name, op in (('s_bcnt0_i32_b32', 0x0d), ('s_bcnt1_i32_b32', 0x0f), ('s_bitset0_b32', 0x1b), + ('s_bitset1_b32', 0x1d)): + words = [sop1(op, 5, 6)] + assert asm(words) == ['%s s5, s6' % name], asm(words) + _, lines = lines_of(words) + expr = rhs(lines[0], 's5') + scc = None + if name.startswith('s_bcnt'): + assert len(lines) == 2 and lines[1] == 'scc = s5 != 0;', lines + scc = Expr('s5 != 0') + else: + assert len(lines) == 1, lines # no SCC write + bad = mismatches(Expr(expr), refs()[name], scc) + assert not bad, (name, expr, bad[:4]) + # negative control: a wrong expression is caught + wrong = expr.replace('countbits', '31u - countbits') if 'countbits' in expr else expr.replace('& 31', '& 15') + assert wrong != expr and mismatches(Expr(wrong), refs()[name]), (name, wrong) + forms += 1 + # constant folding: s_mov_b32 s5, 0x10; s_bitset1_b32 s5, 3 -> constant 0x18 + words = [sop1(0x03, 5, 0x90), sop1(0x1d, 5, 0x83)] + assert asm(words) == ['s_mov_b32 s5, 16', 's_bitset1_b32 s5, 3'], asm(words) + s = stage(words) + assert s.sym.get(5) == ('const', 0x18), s.sym.get(5) + return forms + + +def check_xor3(): + words = [0xd4000000 | 0x178 << 16 | 2, 256 | 257 << 9 | 258 << 18] + assert asm(words) == ['v_xor3_b32 v2, v0, v1, v2'], asm(words) + _, lines = lines_of(words) + expr = Expr(rhs(lines[0], 'v2')) + for a in GRID: + for b in GRID: + for c in (0, 1, MASK, 0x5a5a5a5a): + assert expr.run({'v0': a, 'v1': b, 'v2': c})[0] & MASK == a ^ b ^ c, (a, b, c) + wrong = Expr(rhs(lines[0], 'v2').replace('^', '|', 1)) + assert any(wrong.run({'v0': a, 'v1': b, 'v2': 0})[0] != a ^ b for a in GRID for b in GRID) + + +def refused(words, why, label): + try: + stage(words) + except G.Unsupported as error: + assert why in str(error), (label, str(error)) + return + raise AssertionError('accepted: ' + label) + + +def controls(): + cmp_vcc = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 + save = 0xbe800000 | 20 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[20:21], vcc (s20 mask) + refused([cmp_vcc, save, sop1(0x1d, 20, 0x83)], 'destination', 's_bitset1_b32 into a mask SGPR') + refused([sop1(0x0f, 5, 126)], 'lane mask', 's_bcnt1_i32_b32 of exec_lo') + refused([cmp_vcc, save, sop1(0x0f, 5, 20)], 'lane mask', 's_bcnt1_i32_b32 of a mask SGPR') + assert asm([sop1(0x0f, 5, 126)]) == ['s_bcnt1_i32_b32 s5, exec_lo'], asm([sop1(0x0f, 5, 126)]) + + +def main(): + forms = check_scalar() + check_xor3() + controls() + print('scalar_bits: %d scalar forms and v_xor3_b32 match the ISA references on %d inputs; constant fold kept; ' + '3 controls refused; negative controls caught' % (forms, len(GRID) ** 2)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scalar_complement_mask_check.py b/tests/startup_scalar_complement_mask_check.py new file mode 100644 index 0000000000..b1fad05bf6 --- /dev/null +++ b/tests/startup_scalar_complement_mask_check.py @@ -0,0 +1,90 @@ +"""s_nand_b32, s_nor_b32, s_xnor_b32 on a lane mask or on descriptor data: refused. + +Synthetic gfx1013 SOP2 words only. AMD RDNA 2 ISA: D = ~(S0 op S1) on 32 bits, SCC = (D != 0). A vcc_lo/exec_lo +operand or destination, or an SGPR that holds a compare mask, is the whole wave's mask; SCC then depends on every +lane's bit of the complemented result, and the one-lane model keeps only this lane's bit, so these forms stay +refused. A source the translator holds as descriptor data (sym desc/descnum/ptr) takes the symbolic path, which +emits no SCC; the complement there is refused too. (Same rule as upstream 9b620015 and 34105de4, re-implemented.) + +Accepted control: numeric SGPR operands give ~(s11 op s12) and SCC = D != 0, checked with the integer evaluator of +startup_gfx2hlsl_bit_alu_check on an edge grid. Negative control: the evaluator catches the expression without ~. +""" +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 +from startup_scalar_bits_check import stage, asm, sop1 # noqa: E402 + +MASK = 0xffffffff +OPCODE = {name: op for op, (name, _) in D.SOP2_OPS.items()} +REF = {'s_nand_b32': lambda a, b: ~(a & b) & MASK, 's_nor_b32': lambda a, b: ~(a | b) & MASK, + 's_xnor_b32': lambda a, b: ~(a ^ b) & MASK} +GRID = [0, 1, 0x7fffffff, 0x80000000, 0xfffffffe, MASK, 0xaaaaaaaa, 0x55555555, 0x12345678] +VCC_LO, EXEC_LO = 106, 126 +CMP_VCC = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 +SAVE = 0xbe800000 | 20 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[20:21], vcc (s20 mask) + + +def sop2(name, sdst, s0, s1): + return 0x80000000 | OPCODE[name] << 23 | sdst << 16 | s1 << 8 | s0 + + +def one(words, sym=None): + s = stage([]) + s.lines = [] + s.sym.update(sym or {}) + for _, _, name, text in G.decode(struct.pack('<%dI' % len(words), *words)): + s.one(name, text) + return s.lines + + +def refused(words, why, label, sym=None): + try: + one(words, sym) if sym else stage(words) + except G.Unsupported as error: + assert why in str(error), (label, str(error)) + return 1 + raise AssertionError('accepted: ' + label) + + +def main(): + accepted = refusals = 0 + for name, ref in REF.items(): + words = [sop2(name, 13, 11, 12)] + assert asm(words) == ['%s s13, s11, s12' % name], asm(words) + lines = one(words) + assert len(lines) == 2 and lines[0].startswith('s13 = ') and lines[1] == 'scc = s13 != 0;', lines + expr = Expr(lines[0][len('s13 = '):-1]) + for a in GRID: + for b in GRID: + got = expr.run({'s11': a, 's12': b})[0] & MASK + assert got == ref(a, b), (name, a, b, got) + wrong = Expr(lines[0][len('s13 = '):-1].replace('~', '', 1)) + assert any(wrong.run({'s11': a, 's12': b})[0] & MASK != ref(a, b) for a in GRID for b in GRID), name + accepted += 1 + + assert asm([sop2(name, 13, VCC_LO, 12)]) == ['%s s13, vcc_lo, s12' % name] + refusals += refused([sop2(name, 13, VCC_LO, 12)], 'on a lane mask', name + ' of vcc_lo') + refusals += refused([sop2(name, 13, 11, EXEC_LO)], 'on a lane mask', name + ' of exec_lo') + refusals += refused([sop2(name, VCC_LO, 11, 12)], 'on a lane mask', name + ' into vcc_lo') + refusals += refused([sop2(name, EXEC_LO, 11, 12)], 'on a lane mask', name + ' into exec_lo') + refusals += refused([CMP_VCC, SAVE, sop2(name, 13, 20, 12)], 'on a lane mask', name + ' of a mask SGPR') + refusals += refused([sop2(name, 13, 6, 12)], 'scc from descriptor data', name + ' of a descriptor word', + sym={6: ('descnum',)}) + # the sibling s_and_b32 of a descriptor word keeps its symbolic path (not refused) + lines = one([sop2('s_and_b32', 13, 6, 12)], sym={6: ('descnum',)}) + assert lines == [], lines + print('scalar_complement_mask: %d numeric forms match ~(a op b) and SCC on %d inputs (negative control caught); ' + '%d lane-mask / descriptor forms refused; s_and_b32 of a descriptor word unchanged' + % (accepted, len(GRID) ** 2, refusals)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scalar_const_fold_check.py b/tests/startup_scalar_const_fold_check.py new file mode 100644 index 0000000000..fde3dbbacc --- /dev/null +++ b/tests/startup_scalar_const_fold_check.py @@ -0,0 +1,73 @@ +"""s_brev_b32 of a constant operand folds to a known word in tools/startup/gfx2hlsl.py (Stage.scalar). + +Scalar operations can construct inline sampler descriptors. Constant inputs should fold through a bit-mask +construction and a bit reversal. AMD RDNA ISA: S_BREV_B32 D[31:0] = S0[0:31], no SCC write. + +Hand-assembled pixel stage (SOP2 0b10 << 30 | op << 23 | sdst << 16 | ssrc1 << 8 | ssrc0, s_bfm_b32 0x24; SOP1 +0xbe800000 | sdst << 16 | op << 8 | ssrc0, s_brev_b32 0x0b; inline integers 128 + n), the decoder reads it back. +Expected values are computed here bit by bit, not with the translator's table. Controls: an operand that is not +known (the user SGPR s5) is not folded and keeps reversebits; a brev of the folded s_bfm_b32 chains; without the +fold table the brev results are not constants (the previous behaviour). +""" +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_image_3d_check import VS_WORDS, root_blob # noqa: E402 + + +def sop2(op, d, s0, s1): + return struct.pack('<I', 0x80000000 | op << 23 | d << 16 | s1 << 8 | s0) + + +def sop1(op, d, s0): + return struct.pack('<I', 0xbe800000 | d << 16 | op << 8 | s0) + + +def v_mov_s(v, s): + return struct.pack('<I', 0x7e000000 | v << 17 | 1 << 9 | s) # v_mov_b32_e32 vN, sM + + +def program(): + w = sop2(0x24, 0, 128 + 3, 128 + 9) # s_bfm_b32 s0, 3, 9 + w += sop1(0x0b, 1, 128 + 1) # s_brev_b32 s1, 1 + w += sop1(0x0b, 2, 5) # s_brev_b32 s2, s5 (s5 not known) + w += sop1(0x0b, 3, 0) # s_brev_b32 s3, s0 (a folded value) + w += b''.join(v_mov_s(i, i) for i in range(4)) + return w + struct.pack('<III', 0xf800180f, 0x03020100, 0xbf810000) # exp mrt0 v0, v1, v2, v3 done vm + + +def reverse(x): + return sum(((x >> i) & 1) << (31 - i) for i in range(32)) + + +def main(): + asm = [a for _, _, _, a in G.decode(program())] + assert asm[:4] == ['s_bfm_b32 s0, 3, 9', 's_brev_b32 s1, 1', 's_brev_b32 s2, s5', 's_brev_b32 s3, s0'], asm + bfm = sum(1 << i for i in range(9, 12)) + want = {0: bfm, 1: reverse(1), 3: reverse(bfm)} + assert (bfm, want[1], want[3]) == (0x00000e00, 0x80000000, 0x00700000) + pipe = G.Pipeline(VS_WORDS, program(), root_blob()) + ps = pipe.hlsl_ps() + for n, value in want.items(): + assert pipe.ps.is_const(n) == value, (n, pipe.ps.sym.get(n)) + assert ' s%d = 0x%08xu;' % (n, value) in ps.split('\n'), ps + assert pipe.ps.is_const(2) is None and ' s2 = reversebits(s5);' in ps.split('\n'), ps + saved = dict(G.SCALAR_CONST_FOLD) + G.SCALAR_CONST_FOLD.clear() + try: + old = G.Pipeline(VS_WORDS, program(), root_blob()) + old.hlsl_ps() + assert old.ps.is_const(0) == bfm and all(old.ps.is_const(n) is None for n in (1, 2, 3)), old.ps.sym + finally: + G.SCALAR_CONST_FOLD.update(saved) + print('scalar const fold: s_brev_b32 1 = 0x80000000, brev of the folded s_bfm_b32 3, 9 (0x00000e00) = ' + '0x00700000; controls: unknown operand keeps reversebits, no brev constants without the table') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scalar_ff_check.py b/tests/startup_scalar_ff_check.py new file mode 100644 index 0000000000..d651acafb6 --- /dev/null +++ b/tests/startup_scalar_ff_check.py @@ -0,0 +1,44 @@ +"""s_ff1_i32_b32 and s_ff0_i32_b32 on a value that is not a lane mask. + +Synthetic gfx1013 SOP1 words. Reference (AMD RDNA 2 ISA SOP1): S_FF1_I32_B32 D = the index of the lowest one bit +of S0, -1 if S0 has none; S_FF0_I32_B32 the same for the lowest zero bit; SCC is not written (LLVM +SOPInstructions.td: no SCC def). The emitted HLSL is evaluated with the integer evaluator of +startup_gfx2hlsl_bit_alu_check over an edge grid (its firstbitlow returns 0xffffffff for 0, as HLSL documents). +Controls (refused): s_ff1_i32_b32 of exec_lo and of a mask SGPR (a lane index the one-lane model cannot give). +Negative control: an expression without the -1 case (0 for no bit) is caught. +""" +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 +from startup_scalar_bits_check import GRID, MASK, asm, lines_of, refused, rhs, sop1 # noqa: E402 + + +def lowest(x): + return (x & -x).bit_length() - 1 if x else MASK + + +def main(): + grid = GRID + [1 << n for n in range(32)] + [MASK ^ (1 << n) for n in range(32)] + for name, op, ref in (('s_ff0_i32_b32', 0x11, lambda s: lowest(~s & MASK)), ('s_ff1_i32_b32', 0x13, lowest)): + words = [sop1(op, 5, 6)] + assert asm(words) == ['%s s5, s6' % name], asm(words) + _, lines = lines_of(words) + assert len(lines) == 1, lines # no SCC write + expr = rhs(lines[0], 's5') + bad = [s for s in grid if Expr(expr).run({'s6': s})[0] & MASK != ref(s)] + assert not bad, (name, expr, bad[:4]) + wrong = Expr('(%s == 0u ? 0u : %s)' % ('s6' if op == 0x13 else '~s6', expr)) + assert any(wrong.run({'s6': s})[0] & MASK != ref(s) for s in grid), name + cmp_vcc = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 + save = 0xbe800000 | 20 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[20:21], vcc (s20 mask) + refused([sop1(0x13, 5, 126)], 'lane mask', 's_ff1_i32_b32 of exec_lo') + refused([cmp_vcc, save, sop1(0x13, 5, 20)], 'lane mask', 's_ff1_i32_b32 of a mask SGPR') + print('scalar_ff: s_ff0/s_ff1_i32_b32 match the ISA reference on %d inputs (-1 for none, SCC kept); exec_lo and ' + 'mask-SGPR sources refused; negative control caught' % len(grid)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scalar_nand_check.py b/tests/startup_scalar_nand_check.py new file mode 100644 index 0000000000..df372bef76 --- /dev/null +++ b/tests/startup_scalar_nand_check.py @@ -0,0 +1,70 @@ +"""s_nand_b32 / s_nor_b32 / s_xnor_b32 (SOP2), the 32-bit forms of the existing b64 entries. + +Synthetic words (SOP2: op [29:23], sdst [22:16], ssrc1 [15:8], ssrc0 [7:0]; gfx10 opcodes 0x18, 0x1a, 0x1c, names +asserted from the decoder). RDNA2 ISA: D = ~(S0 & S1), ~(S0 | S1), ~(S0 ^ S1); SCC = (D != 0). The emitted +expression is evaluated on a value grid; a lane-mask source (vcc_lo) is refused (SCC would need every lane's bit). +Control: the existing s_and_b32 output is unchanged. +""" +import itertools +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 + +MASK = 0xffffffff +OPS = {0x18: ('s_nand_b32', lambda a, b: ~(a & b)), 0x1a: ('s_nor_b32', lambda a, b: ~(a | b)), + 0x1c: ('s_xnor_b32', lambda a, b: ~(a ^ b))} +GRID = [0, 1, 0x80000000, 0x0f0f0f0f, 0xfffffffe, MASK] + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def stage(): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + s.pc = 0 + return s + + +def run_one(s, word): + _, n, name, text = G.decode(struct.pack('<I', word))[0] + s.one(name, text) + return text + + +def main(): + for op, (name, ref) in OPS.items(): + s = stage() + text = run_one(s, 0x80000000 | op << 23 | 2 << 16 | 1 << 8 | 0) + assert text == '%s s2, s0, s1' % name, text + body = '\n'.join(s.lines) + m = re.search(r's2 = (.*);', body) + assert m and 'scc' in body, body + py = m.group(1).replace('~', 'MASK ^ ').replace('u', '') + for a, b in itertools.product(GRID, repeat=2): + got = eval(py, {'__builtins__': {}, 'MASK': MASK}, {'s0': a, 's1': b}) & MASK + assert got == ref(a, b) & MASK, (name, a, b, got) + s = stage() + try: # S0 = vcc_lo, a lane mask: SCC needs every lane's bit (startup_scalar_complement_mask_check) + run_one(s, 0x80000000 | op << 23 | 2 << 16 | 1 << 8 | 106) + except G.Unsupported as error: + assert 'on a lane mask' in str(error), str(error) + else: + raise AssertionError((name, 'lane-mask source accepted')) + s = stage() + assert run_one(s, 0x80000000 | 0x0e << 23 | 2 << 16 | 1 << 8) == 's_and_b32 s2, s0, s1' + assert re.search(r's2 = s0 & s1;', '\n'.join(s.lines)), s.lines + print('scalar nand/nor/xnor b32: %d forms match the reference on %d inputs; mask source refused' + % (len(OPS), len(GRID) ** 2)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scalar_pack_hh_check.py b/tests/startup_scalar_pack_hh_check.py new file mode 100644 index 0000000000..3e4062ab60 --- /dev/null +++ b/tests/startup_scalar_pack_hh_check.py @@ -0,0 +1,110 @@ +"""s_pack_hh_b32_b16 (SOP2) in the base translator: D = S0[31:16] in the low half, S1[31:16] in the high half. + +LLVM SIInstructions.td selects S_PACK_HH_B32_B16 for + (v2i16 (build_vector (i16 (trunc (srl_oneuse $src0, 16))), (i16 (trunc (srl_oneuse $src1, 16))))) +and build_vector puts its first operand in element 0 (bits 15:0). SOPInstructions.td defines it as SOP2_32 in no +`Defs = [SCC]` block, so it leaves SCC alone. Synthetic words (SOP2: op [29:23], sdst [22:16], ssrc1 [15:8], +ssrc0 [7:0]); the gfx10 opcode is taken from the decoder's name for it, not assumed. + +Checks: the emitted expression matches the reference on a value grid, writes no scc, and an SCC read after it +still sees the earlier compare. Negative controls: without the table entry the stage refuses s_pack_hh_b32_b16 +(what the pixel stage of mesh pairs did before), and the swapped-operand reading fails the grid (the grid tells +the two halves apart). +""" +import itertools +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 + +MASK = 0xffffffff +GRID = [0, 1, 0xffff, 0x10000, 0x80000000, 0x12345678, 0xdeadbeef, 0xfffffffe, MASK] + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def stage(): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + s.pc = 0 + return s + + +def find_opcode(): + for op in range(0x30, 0x40): + _, _, name, text = G.decode(struct.pack('<I', 0x80000000 | op << 23 | 2 << 16 | 1 << 8 | 0))[0] + if name == 's_pack_hh_b32_b16': + return op, text + raise AssertionError('decoder names no SOP2 opcode s_pack_hh_b32_b16') + + +def ref(a, b): + return (a >> 16) | (b & 0xffff0000) + + +def evaluate(expr, a, b): + py = expr.replace('u)', ')').replace('u ', ' ') + py = re.sub(r'(0x[0-9a-f]+)u', r'\1', py) + return eval(py, {'__builtins__': {}}, {'s0': a, 's1': b}) & MASK + + +def run(s, op): + _, _, name, text = G.decode(struct.pack('<I', 0x80000000 | op << 23 | 2 << 16 | 1 << 8 | 0))[0] + s.one(name, text) + return '\n'.join(s.lines) + + +def main(): + op, text = find_opcode() + assert text == 's_pack_hh_b32_b16 s2, s0, s1', text + s = stage() + body = run(s, op) + m = re.fullmatch(r's2 = (.*);', body) + assert m, body + assert 'scc' not in body, body + for a, b in itertools.product(GRID, repeat=2): + assert evaluate(m.group(1), a, b) == ref(a, b), (hex(a), hex(b), m.group(1)) + # swapped halves (S1 low, S0 high) is a different function on the grid + swapped = m.group(1).replace('s0', 'sX').replace('s1', 's0').replace('sX', 's1') + assert any(evaluate(swapped, a, b) != ref(a, b) for a, b in itertools.product(GRID, repeat=2)), swapped + # negative control: the stage without the entry refuses, as before the change + saved = G.SCA.pop('s_pack_hh_b32_b16') + try: + try: + run(stage(), op) + except G.Unsupported as e: + assert str(e) == 's_pack_hh_b32_b16', e + else: + raise AssertionError('no refusal without the table entry') + finally: + G.SCA['s_pack_hh_b32_b16'] = saved + # a lane-mask source (s0 written by a compare, or vcc_lo as ssrc1 = 106) is refused, not packed per lane + s = stage() + s.masks.add(0) + try: + run(s, op) + raise AssertionError('lane mask packed') + except G.Unsupported as e: + assert str(e) == 's_pack_hh_b32_b16 of a lane mask', e + _, _, name, vtext = G.decode(struct.pack('<I', 0x80000000 | op << 23 | 2 << 16 | 106 << 8 | 0))[0] + assert vtext == 's_pack_hh_b32_b16 s2, s0, vcc_lo', vtext + try: + stage().one(name, vtext) + raise AssertionError('vcc packed') + except G.Unsupported as e: + assert str(e) == 's_pack_hh_b32_b16 of a lane mask', e + print('s_pack_hh_b32_b16: opcode %#x, %d inputs match (S0 >> 16) | (S1 & 0xffff0000), no SCC write; ' + 'control refuses without the entry, swapped halves mismatch; lane-mask sources refused' + % (op, len(GRID) ** 2)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scmp_u64_check.py b/tests/startup_scmp_u64_check.py new file mode 100644 index 0000000000..abb2e220bd --- /dev/null +++ b/tests/startup_scmp_u64_check.py @@ -0,0 +1,115 @@ +"""s_cmp_eq_u64 / s_cmp_lg_u64 on 64-bit data pairs. + +Synthetic gfx1013 words only. The shape is a pixel program testing a 64-bit value read from a constant buffer +against zero before using it (`s_mov_b64 s[26:27], 0` ... `s_cmp_lg_u64 s[38:39], s[26:27]`; s_cbranch_scc0). +RDNA 2 ISA, SOPC: SCC = (S0 == S1) or (S0 != S1) on the 64-bit values. + +The emitted SCC is evaluated in Python for value pairs that differ in the low dword only, the high dword only, +both, and neither (an equality on the low dword alone would pass the first and fail the second). +Controls (refused): exec as an operand; a pair holding a copy of exec (s_mov_b64 s[26:27], exec); a pair holding +a lane mask (v_cmp into s[26:27]); a 64-bit literal. Negative control: without the handlers the compare is the +old refusal. +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class TestPipeline: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def sop1(op, d, s): + return 0xbe800000 | d << 16 | op << 8 | s + + +def sopc(op, a, b): + return 0xbf000000 | op << 16 | b << 8 | a + + +MOV_B32, MOV_B64 = 3, 4 +CMP_EQ_U64, CMP_LG_U64 = 0x12, 0x13 +EXEC = 126 +INLINE0 = 128 +V_CMP_LT_U32_S26 = [0xd4c10000 | 26, 0x00020081] # v_cmp_lt_u32_e64 s26, 1, v0 (wave32: the mask is s26) + + +def stage(words): + return G.Stage(TestPipeline(), 'vs', struct.pack('<%dI' % (len(words) + 1), *words, 0xbf810000)) + + +def asm(words): + return [x[3] for x in G.decode(struct.pack('<%dI' % len(words), *words))] + + +def scc_line(words): + s = stage(words) + lines = [line for block in s.blocks for line in block[1] if line.startswith('scc = ')] + assert len(lines) == 1, s.blocks + return lines[0][len('scc = '):-1] + + +def evaluate(expr, env): + py = expr.replace('&&', ' and ').replace('||', ' or ') + import re + py = re.sub(r'\b(0x[0-9a-f]+|\d+)u\b', r'\1', py) + return bool(eval(py, {}, env)) + + +def refused(words, label, text): + try: + stage(words) + except G.Unsupported as error: + assert text in str(error), (label, str(error)) + return + raise AssertionError('accepted: ' + label) + + +def main(): + zero = [sop1(MOV_B64, 26, INLINE0)] + lg = sopc(CMP_LG_U64, 38, 26) + eq = sopc(CMP_EQ_U64, 38, 26) + got = asm(zero + [lg, eq, sop1(MOV_B64, 26, EXEC), sopc(CMP_LG_U64, EXEC, 26)] + V_CMP_LT_U32_S26) + assert got == ['s_mov_b64 s[26:27], 0', 's_cmp_lg_u64 s[38:39], s[26:27]', 's_cmp_eq_u64 s[38:39], s[26:27]', + 's_mov_b64 s[26:27], exec', 's_cmp_lg_u64 exec, s[26:27]', 'v_cmp_lt_u32_e64 s26, 1, v0'], got + + # s[26:27] = 0 folds to constants; s38/s39 stay run-time registers. + lg_expr, eq_expr = scc_line(zero + [lg]), scc_line(zero + [eq]) + assert 's38' in lg_expr and 's39' in lg_expr, lg_expr + for lo, hi in ((0, 0), (5, 0), (0, 5), (5, 5), (0xffffffff, 0xffffffff)): + env = {'s38': lo, 's39': hi} + assert evaluate(lg_expr, env) == ((lo | hi << 32) != 0), (lg_expr, lo, hi) + assert evaluate(eq_expr, env) == ((lo | hi << 32) == 0), (eq_expr, lo, hi) + # Two run-time pairs. + both = scc_line([sopc(CMP_EQ_U64, 38, 40)]) + for a, b in (((1, 2), (1, 2)), ((1, 2), (1, 3)), ((1, 2), (0, 2))): + env = {'s38': a[0], 's39': a[1], 's40': b[0], 's41': b[1]} + assert evaluate(both, env) == (a == b), (both, a, b) + + # Controls. + refused([sopc(CMP_LG_U64, EXEC, 26)], 'exec operand', '64-bit operand') + refused([sop1(MOV_B64, 26, EXEC), lg], 'copy of exec', 'on a lane mask') + refused(V_CMP_LT_U32_S26 + [lg], 'v_cmp lane mask', 'on a lane mask') + # (a literal with bit 31 clear has high dword 0 under either extension and is accepted by Stage.pair) + refused([sopc(CMP_LG_U64, 38, 255), 0x92345678], '64-bit literal, bit 31 set', '64-bit literal operand') + + # Negative control: without the handlers the compare is refused as an unknown instruction. + saved = G.Stage.op_s_cmp_lg_u64, G.Stage.op_s_cmp_eq_u64 + del G.Stage.op_s_cmp_lg_u64, G.Stage.op_s_cmp_eq_u64 + try: + refused(zero + [lg], 'handlers removed', 's_cmp_lg_u64') + finally: + G.Stage.op_s_cmp_lg_u64, G.Stage.op_s_cmp_eq_u64 = saved + print('scmp_u64: eq/lg on data pairs evaluated for low-only, high-only, both and equal values; ' + 'exec, exec copy, v_cmp mask and literal refused; negative control (no handlers) refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_sdwa_cvt_check.py b/tests/startup_sdwa_cvt_check.py new file mode 100644 index 0000000000..5c90a25fe4 --- /dev/null +++ b/tests/startup_sdwa_cvt_check.py @@ -0,0 +1,68 @@ +"""SDWA forms of the float-result conversions (v_cvt_f32_u32, _i32, _ubyte*, _f16) after #1707 moved them out of VEC_U. + +Synthetic VOP1 SDWA words: v_cvt_f32_u32 v2, v1 with src0_sel BYTE_1 (op 6, src0 = 0xf9, SDWA dword: v1, dst_sel DWORD, +UNUSED_PAD, src0_sel BYTE_1). The lowering must be the expression VEC_U used to give, U(float(<selected field>)), as +before the integration merge; v_cvt_f32_f16 likewise with WORD_1. SDWA output modifiers (omod, clamp) on these +conversions are lowered with dst_sel DWORD (they used to be refused; that control is now an acceptance check) and +stay refused with a partial destination field. +""" +import os +import struct +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def one(words): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + _, n, name, text = G.decode(struct.pack('<%dI' % len(words), *words))[0] + s.pc = 0 + s.used_v.update((1, 2)) + s.one(name, text) + return text, '\n'.join(s.lines) + + +def sdwa(op, src_sel, omod=0): + return [0x7e000000 | 2 << 17 | op << 9 | 0xf9, 1 | 6 << 8 | omod << 14 | src_sel << 16] + + +def main(): + text, body = one(sdwa(6, 1)) + assert text.startswith('v_cvt_f32_u32_sdwa v2, v1') and 'src0_sel:BYTE_1' in text, text + assert body == 'v2 = U(float(((v1 >> 8u) & 0xffu)));', body + text, body = one(sdwa(0x0b, 5)) # v_cvt_f32_f16, WORD_1 + assert text.startswith('v_cvt_f32_f16_sdwa v2, v1') and 'src0_sel:WORD_1' in text, text + assert body == 'v2 = U(f16tof32(((v1 >> 16u) & 0xffffu)));', body + # Output modifiers (SDWA9 omod [15:14], clamp [13]) on a float-result conversion with dst_sel DWORD: the + # binary32 result is scaled, then clamped, as in VOP3 (set_vf). + for omod, factor in ((1, '2.0'), (2, '4.0'), (3, '0.5')): + text, body = one(sdwa(6, 4, omod=omod)) + assert text.startswith('v_cvt_f32_u32_sdwa v2, v1') and 'src0_sel:WORD_0' in text, text + assert body == 'v2 = U((float(((v1 >> 0u) & 0xffffu))) * %s);' % factor, body + text, body = one([sdwa(6, 4, omod=1)[0], sdwa(6, 4, omod=1)[1] | 1 << 13]) + assert 'clamp' in text, text + assert body == 'v2 = U(saturate((float(((v1 >> 0u) & 0xffffu))) * 2.0));', body + # Control: an output modifier with a partial destination field. (On an integer operation such as v_not_b32 + # the disassembler itself rejects the omod bits as an invalid SDWA encoding.) + for words, why in (([0x7e000000 | 2 << 17 | 6 << 9 | 0xf9, 1 | 4 << 8 | 1 << 14 | 4 << 16], 'dst_sel:WORD_0'),): + try: + one(words) + except G.Unsupported as error: + assert why in str(error), (why, str(error)) + else: + raise AssertionError('accepted %s' % one(words)[0]) + print('sdwa cvt: v_cvt_f32_u32 BYTE_1 and v_cvt_f32_f16 WORD_1 lowered as before; mul:2/mul:4/div:2/clamp ' + 'lowered with dst_sel DWORD; 1 control refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_sdwa_mov_check.py b/tests/startup_sdwa_mov_check.py new file mode 100644 index 0000000000..748fd64da9 --- /dev/null +++ b/tests/startup_sdwa_mov_check.py @@ -0,0 +1,122 @@ +"""v_mov_b32_sdwa: the selected source field, placed by dst_sel / dst_unused. + +Synthetic VOP1 SDWA words (VOP1 op 1, src0 = 0xf9; SDWA dword: [7:0] source, [10:8] dst_sel, [12:11] dst_unused, +[18:16] src0_sel, [19] sext, [23] source is an SGPR). Reference (AMD RDNA 2 ISA, SDWA section; LLVM +VOP1Instructions.td gives V_MOV_B32 an SDWA form with integer input modifiers, sext only): the source field at +src0_sel is zero- or sign-extended to 32 bits; dst_sel DWORD writes it; a partial dst_sel writes its low bits into +that field and the rest of the register is 0 (UNUSED_PAD) or kept (UNUSED_PRESERVE). + +The emitted expression is evaluated in Python for every src0_sel x dst_sel x {PAD, PRESERVE} x sext on a value +grid, against a reference written here from those rules. An SGPR source is accepted. A PRESERVE destination not yet written is recorded as an entry VGPR read. Refused: UNUSED_SEXT (no +lowering), the neg bit (not an integer input modifier; the decoder flags it). Negative control: a reference that +ignores sext (or PRESERVE) is caught. +""" +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_sdwa_cvt_check import one # noqa: E402 + +SEL = {0: (0, 8), 1: (8, 8), 2: (16, 8), 3: (24, 8), 4: (0, 16), 5: (16, 16), 6: (0, 32)} +GRID = [0, 0x80, 0x7f, 0x8000, 0xffffffff, 0x12345678, 0x89abcdef, 0x00ff00ff] +OLD = 0xa5a55a5a + + +def words(dsel, unused, ssel, sext=0, neg=0, sgpr=0, src=1): + return [0x7e000000 | 2 << 17 | 1 << 9 | 0xf9, + src | dsel << 8 | unused << 11 | ssel << 16 | sext << 19 | neg << 20 | sgpr << 23] + + +def s32(x): + x &= 0xffffffff + return x - (1 << 32) if x >> 31 else x + + +def evaluate(body, v1, v2): + m = re.fullmatch(r'v2 = (.*);', body) + assert m, body + expr = re.sub(r'(0x[0-9a-f]+|\d+)u\b', r'\1', m.group(1)).replace('asuint(', 'u32(').replace('asint(', 's32(') + return eval(expr, {'u32': lambda x: x & 0xffffffff, 's32': s32, '__builtins__': {}}, + {'v1': v1, 'v2': v2, 's3': v1}) & 0xffffffff + + +def reference(v1, old, dsel, unused, ssel, sext, ignore_sext=False, ignore_preserve=False): + off, width = SEL[ssel] + field = (v1 >> off) & ((1 << width) - 1) + if sext and not ignore_sext and width < 32 and field >> (width - 1): + field |= ~((1 << width) - 1) & 0xffffffff + doff, dwidth = SEL[dsel] + if dwidth == 32: + return field + placed = (field & ((1 << dwidth) - 1)) << doff + if unused == 2 and not ignore_preserve: + placed |= old & ~(((1 << dwidth) - 1) << doff) & 0xffffffff + return placed + + +def check_half_add_zero(): + from startup_sdwa_cvt_check import Pipe + stage = G.Stage(Pipe(), 'ps', b'') + stage.pc = 0 + stage.used_v.add(2) + mods = ['dst_sel:WORD_0', 'dst_unused:UNUSED_PRESERVE', 'src0_sel:WORD_0', 'src1_sel:DWORD'] + for value, bits in [('1.0', 0x3c00), ('-2.0', 0xc000), ('0.5', 0x3800)]: + stage.lines = [] + stage.sdwa('v_add_f16', ['v2', value, '0'], mods) + for old in GRID: + assert evaluate('\n'.join(stage.lines), 0, old) == (old & 0xffff0000) | bits + for args, fields in [(['v2', 'v1', '0'], mods), (['v2', '1.0', '1'], mods), + (['v2', '1.0', '0'], mods[:-2] + ['src0_sel:WORD_1', mods[-1]])]: + try: + stage.sdwa('v_add_f16', args, fields) + except G.Unsupported: + continue + raise AssertionError((args, fields)) + + +def main(): + check_half_add_zero() + forms = caught_sext = caught_preserve = 0 + for ssel in SEL: + for dsel in SEL: + for unused in (0, 2): + for sext in (0, 1): + text, body = one(words(dsel, unused, ssel, sext)) + assert text.startswith('v_mov_b32_sdwa v2, %sv1' % ('sext(' if sext else '')), text + for v in GRID: + want = reference(v, OLD, dsel, unused, ssel, sext) + assert evaluate(body, v, OLD) == want, (text, body, hex(v)) + caught_sext += any(evaluate(body, v, OLD) != reference(v, OLD, dsel, unused, ssel, sext, True) + for v in GRID) + caught_preserve += any(evaluate(body, v, OLD) != reference(v, OLD, dsel, unused, ssel, sext, + ignore_preserve=True) for v in GRID) + forms += 1 + assert caught_sext > 0 and caught_preserve > 0, (caught_sext, caught_preserve) + text, body = one(words(4, 0, 0, sgpr=1, src=3)) + assert text.startswith('v_mov_b32_sdwa v2, s3'), text + assert all(evaluate(body, v, OLD) == reference(v, OLD, 4, 0, 0, 0) for v in GRID), body + for label, w, why in (('UNUSED_SEXT', words(0, 1, 4), 'UNUSED_SEXT'), ('neg', words(6, 0, 1, neg=1), 'SDWA')): + try: + one(w) + except G.Unsupported as error: + assert why in str(error), (label, str(error)) + else: + raise AssertionError('accepted: ' + label) + # UNUSED_PRESERVE reads the destination: in a pixel stage a destination not yet written is an entry (SPI + # input) VGPR read and must be recorded; PAD does not read it. + from startup_scalar_bits_check import TestPipeline + import struct + for unused, want in ((2, {2: 4}), (0, {})): + code = [0x7e000000 | 1 << 17 | 1 << 9 | 128] + words(4, unused, 5) + [0xbf810000] + stage = G.Stage(TestPipeline(), 'ps', struct.pack('<%dI' % len(code), *code)) + assert stage.entry_reads == want, (unused, stage.entry_reads) + print('sdwa_mov: %d v_mov_b32_sdwa forms match the SDWA rules on %d values (sext caught in %d, PRESERVE in %d); ' + 'SGPR source accepted; UNUSED_SEXT and neg refused; PRESERVE records an entry read' % (forms, len(GRID), caught_sext, caught_preserve)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_shader_trace_misses_check.py b/tests/startup_shader_trace_misses_check.py new file mode 100644 index 0000000000..bbf7c8ceb7 --- /dev/null +++ b/tests/startup_shader_trace_misses_check.py @@ -0,0 +1,43 @@ +"""Exercise the native trace filter and selective translator through their CLI.""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +from startup_compute_request_offline_check import CODE, DATA, DESC, G, REASON, ROOT, STATE_A, STATE_B + +scanner = Path(sys.argv[1]).resolve() +translator = Path(__file__).resolve().parents[1] / "tools/startup/gfx2hlsl.py" +key = f"{G.compute_key(CODE, DATA, ROOT, DESC, STATE_A, STATE_B):016x}" +other = "1111111111111111" +draw = f"x2w-frame draw 3 NOT drawn target 1234 80x40 fmt 28 topology 0x4 key {other} " +compute = f"x2w-frame cx-uav #7 key {key} (1, 1, 1) pipeline 1234: " +with tempfile.TemporaryDirectory() as temp: + cache = Path(temp) + trace = cache / "trap.log" + trace.write_bytes(("\r\n".join([ + compute + "skipped: no translation, no manifest: data", + draw.replace("frame draw ", "frame draw-indexed ") + "no translation", + compute + "skipped: no translation, no manifest: data", + draw.replace(other, "0000000000000000") + "no translation record", + draw.replace(other, other + "1") + "no translation", + draw.replace("NOT drawn", "drawn") + "no translation", + compute + "skipped: heap", + ])).encode()) + rows = subprocess.check_output([scanner, trace], text=True).splitlines() + assert rows == [f"{key}\t2", f"{other}\t1"], rows + for suffix, data in dict(desc=DESC, sa=STATE_A, sb=STATE_B, data=DATA, root=ROOT, c67=CODE).items(): + (cache / f"req_{key}.{suffix}").write_bytes(data) + # A second pending request is absent from the trace and must be left alone. + (cache / "req_2222222222222222.a").touch() + cmd = [sys.executable, "-B", translator, "--warm-trace", cache, trace, scanner] + before = set(cache.iterdir()) + report = subprocess.check_output(cmd + ["--list"], text=True) + assert report.splitlines() == ["2 distinct missed keys, 1 pending translator requests", key], report + assert set(cache.iterdir()) == before + env = dict(os.environ, X2W_TRANSLATE_JOBS="1") + subprocess.run(cmd, check=True, env=env) + assert set(cache.iterdir()) - before == {cache / f"{key}.fail"} + assert (cache / f"{key}.fail").read_text().strip() == REASON +print("trace selection, CRLF, duplicate keys, preview and targeted translation passed") diff --git a/tests/startup_smem_overlap_mask_check.py b/tests/startup_smem_overlap_mask_check.py new file mode 100644 index 0000000000..60a6851f88 --- /dev/null +++ b/tests/startup_smem_overlap_mask_check.py @@ -0,0 +1,85 @@ +"""s_buffer_load with its offset register inside the destination range, an SGPR offset plus offset:N, and a load +into a register that held a lane mask (tools/startup/gfx2hlsl.py; reported by the mesh translator, board 191901). + +1. s_buffer_load_dwordx2 s[4:5], s[16:19], s4: both words address with the old s4 (the ISA reads the operands + before writing), so s5 must be written before s4. Control: s[6:7] with offset s4 keeps the plain order. +2. s_buffer_load_dword s0, s[16:19], s4 offset:0x10: the byte offset is s4 + 16. Another modifier is refused. +3. v_cmp into s6 makes s6 a lane mask; s_buffer_load_dword s6, ... replaces it with a buffer word, so a later + s_or_b32 s8, s6, s7 is an ordinary OR, not a mask OR cut to bit 0. Control: without the load it is a mask OR. +All inputs are synthetic register states; no title data. +""" +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 + + +class Pipe: + sampler_heap = False + root = {'params': [], 'flags': 0} + + def resource(self, key, kind): + return 'r0' + + def ud(self, source): + return 0 + + +DESC = {16: ('desc', ('table', 0), 0x20, 0), 17: ('desc', ('table', 0), 0x20, 1), + 18: ('desc', ('table', 0), 0x20, 2), 19: ('desc', ('table', 0), 0x20, 3)} + + +def stage(): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + s.sym.update(DESC) + s.pc = 0 + return s + + +def load(s, text): + ops, mods = text.split(' ', 1)[1], [] + parts = ops.split(', ') + last = parts[-1].split(' ') + parts[-1], mods = last[0], last[1:] + getattr(s, 'op_' + text.split(' ')[0])(parts, mods) + + +def main(): + s = stage() + load(s, 's_buffer_load_dwordx2 s[4:5], s[16:19], s4') + assert s.lines == ['s5 = r0.Load(s4 + 4);', 's4 = r0.Load(s4 + 0);'], s.lines + s = stage() + load(s, 's_buffer_load_dwordx2 s[6:7], s[16:19], s4') + assert s.lines == ['s6 = r0.Load(s4 + 0);', 's7 = r0.Load(s4 + 4);'], s.lines + print('overlap: offset register written last; control keeps the order') + + s = stage() + load(s, 's_buffer_load_dword s0, s[16:19], s4 offset:0x10') + assert s.lines == ['s0 = r0.Load(s4 + 16);'], s.lines + try: + load(stage(), 's_buffer_load_dword s0, s[16:19], s4 slc') + except G.Unsupported as error: + assert 'modifier slc' in str(error), str(error) + else: + raise AssertionError('unknown modifier accepted') + print('offset:N added to the SGPR offset; unknown modifier refused') + + for with_load in (True, False): + s = stage() + s.masks.add(6) # as after v_cmp_* s6, ... + if with_load: + load(s, 's_buffer_load_dword s6, s[16:19], 0x0') + s.lines = [] + s.one('s_or_b32', 's_or_b32 s8, s6, s7') + text = '\n'.join(s.lines) + if with_load: + assert '& 1' not in text and 8 not in s.masks and 6 not in s.masks, (text, s.masks) + else: + assert '& 1' in text and 8 in s.masks, (text, s.masks) + print('mask mark: cleared by a load into the register; control keeps the mask OR') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_sopk_sign_check.py b/tests/startup_sopk_sign_check.py new file mode 100644 index 0000000000..45e7961b67 --- /dev/null +++ b/tests/startup_sopk_sign_check.py @@ -0,0 +1,39 @@ +"""SOPK immediates: s_movk_i32 and s_cmpk_*_i32 sign-extend SIMM16, s_cmpk_*_u32 zero-extends (picked 56eee135). + +Synthetic SOPK words (0xb0000000 | op << 23 | sdst << 16 | simm16). Reference: RDNA 2 ISA SOPK; LLVM +SOPInstructions.td s16imm for s_movk_i32 / s_cmpk_*_i32, u16imm for s_cmpk_*_u32. The disassembler prints the field +unsigned, so 0xf000 / 0x8000 are the cases that differ. Negative control: a lowering that keeps the printed value +(the old behaviour) gives 0x0000f000 for s_movk_i32 0xf000. +""" +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_scalar_bits_check import asm, lines_of # noqa: E402 + + +def sopk(op, sdst, simm): + return [0xb0000000 | op << 23 | sdst << 16 | simm] + + +def main(): + cases = [ + (0, 0xf000, 's_movk_i32 s5, 0xf000', ['s5 = 0xfffff000u;']), + (0, 0x7fff, 's_movk_i32 s5, 0x7fff', ['s5 = 0x00007fffu;']), + (3, 0x8000, 's_cmpk_eq_i32 s5, 0x8000', ['scc = int(s5) == int(0xffff8000u);']), + (9, 0x8000, 's_cmpk_eq_u32 s5, 0x8000', ['scc = s5 == 0x00008000u;']), + ] + for op, simm, text, want in cases: + words = sopk(op, 5, simm) + assert asm(words) == [text], asm(words) + s, lines = lines_of(words) + assert lines == want, (text, lines) + s, _ = lines_of(sopk(0, 5, 0xf000)) + assert s.sym.get(5) == ('const', 0xfffff000), s.sym.get(5) + assert s.sym.get(5) != ('const', 0xf000) # the old, unsigned value + print('sopk_sign: s_movk_i32 / s_cmpk_eq_i32 sign-extend, s_cmpk_eq_u32 zero-extends; constant 0xfffff000 kept') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_spi_input_check.py b/tests/startup_spi_input_check.py new file mode 100644 index 0000000000..9cf92fc318 --- /dev/null +++ b/tests/startup_spi_input_check.py @@ -0,0 +1,96 @@ +"""Map pixel-stage entry VGPRs to SPI inputs from SPI_PS_INPUT_ENA/ADDR; lower only POS_FIXED_PT. + +Synthetic code only: a vertex stage that exports a position and a pixel stage `exp mrt0 vN, vN, vN, vN done vm` +that reads entry VGPR vN. Without the masks the read is refused (the request does not carry the layout); with +them, vN must be the enabled POS_FIXED_PT input, placed by the ADDR bits (Mesa ac_shader_util.c). +""" +import os +import struct +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import VS_WORDS, root_blob # noqa: E402 + + +def pixel_words(reg): + # exp mrt0 vN, vN, vN, vN done vm; s_endpgm + return struct.pack('<III', 0xf800180f, reg * 0x01010101, 0xbf810000) + + +def refused(reg, masks, text): + try: + G.Pipeline(VS_WORDS, pixel_words(reg), root_blob(), ps_hw_inputs=masks).hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (reg, masks, str(error)) + return + raise AssertionError('accepted v%d with %s' % (reg, masks)) + + +def packed(reg): + return 'v%d = (uint(i.pos.x) & 0xffffu) | ((uint(i.pos.y) & 0xffffu) << 16);' % reg + + +def main(): + # The lowering's arithmetic: SV_Position.xy is the pixel centre, so its integer part is the pixel. + for x, y in ((0, 0), (1, 0), (0, 1), (1919, 1079), (3839, 2159), (65535, 65535)): + assert (int(x + 0.5) & 0xffff) | ((int(y + 0.5) & 0xffff) << 16) == x | y << 16 + + assert G.decode(pixel_words(2))[0][3] == 'exp mrt0 v2, v2, v2, v2 done vm' + # Accepted: one earlier single-VGPR input, one earlier IJ pair, and an ADDR-only (allocated but not + # enabled) pair that still moves the position: persp_sample + persp_center allocated -> v4. + for reg, masks in ((1, (0x8100, 0x8100)), (2, (0x8002, 0x8002)), (4, (0x8002, 0x8003)), + (0, (0x8000, 0x8000)), (4, (0x8008, 0x8108))): # pull model (3) + pos_x_float (1) + ps = G.Pipeline(VS_WORDS, pixel_words(reg), root_blob(), ps_hw_inputs=masks).hlsl_ps() + assert packed(reg) in ps, (reg, masks, ps) + assert 'o.mrt0 = float4(F(v%d), F(v%d), F(v%d), F(v%d));' % ((reg,) * 4) in ps, ps + # Refused, each with its own reason. + refused(1, (0x8100, 0x8000), 'enable/address') # ENA outside ADDR (upstream #1634's control) + refused(1, (0x18000, 0x18000), 'enable/address') # not a 16-bit mask + refused(1, (0x8002, 0x8002), 'persp_center (v1) at 0x0: not lowered') + refused(0, (0x2000, 0x2000), 'ancillary (v0) at 0x0: not lowered') # packed position disabled + # (front_face, refused here before, is lowered as SV_IsFrontFace: tests/startup_front_face_check.py) + # (pos_x_float, refused here before, is lowered as SV_Position.x: tests/startup_mesh_spi_input_check.py) + refused(0, (0x8002, 0x8003), 'persp_sample (v0) at 0x0, allocated but not enabled') + refused(3, (0x0002, 0x0002), 'past the SPI inputs (ADDR allocates 2)') + try: + G.Pipeline(VS_WORDS, pixel_words(0), root_blob(), ps_hw_inputs=(0x0000, 0x8000)).hlsl_ps() + except G.Unsupported as error: + assert 'pos_fixed_pt (v0) at 0x0, allocated but not enabled' in str(error), str(error) + else: + raise AssertionError('read an allocated but disabled POS_FIXED_PT') + # Without masks nothing changes: no packed line, and translate_to still refuses the read. + assert 'i.pos.x' not in G.Pipeline(VS_WORDS, pixel_words(1), root_blob()).hlsl_ps() + + # Requests: the optional req_<key>.psin file (not part of the key) supplies the masks. + G.FXC = os.path.join(tempfile.gettempdir(), 'no-such-fxc.exe') # translation only, no compiler + with tempfile.TemporaryDirectory() as tmp: + ps_code = pixel_words(2) + key = G.pipeline_key(VS_WORDS, ps_code, root_blob()) + base = os.path.join(tmp, 'req_%016x' % key) + for ext, blob in (('.a', VS_WORDS), ('.b', ps_code), ('.root', root_blob())): + open(base + ext, 'wb').write(blob) + result = G.translate_request(tmp, key) + assert result == 'unsupported: pixel stage reads entry VGPR v2 (an SPI input; layout not in the request) at 0x0', result + for text, expect in (('spi_ps_input 1 00008002 00008002\n', 'ok'), + ('spi_ps_input 1 00008002 00008003\n', 'unsupported: pixel stage reads SPI input persp_center'), + ('spi_ps_input 1 00008002 00008002\nvs_input 1 1 00000000\n', 'ok'), + ('spi_ps_input 1 8002 8002\n', 'unsupported: invalid SPI input file'), + ('spi_ps_input 1 00008002 00008002', 'unsupported: invalid SPI input file'), + ('spi_ps_input 2 00008002 00008002\n', 'unsupported: invalid SPI input file')): + for ext in ('.txt', '.fail'): + if os.path.exists(os.path.join(tmp, '%016x%s' % (key, ext))): + os.remove(os.path.join(tmp, '%016x%s' % (key, ext))) + with open(base + '.psin', 'w', newline='\n') as file: + file.write(text) + result = G.translate_request(tmp, key) + assert result.startswith(expect), (text, result) + if expect == 'ok': + assert packed(2) in open(os.path.join(tmp, '%016x.ps.hlsl' % key)).read() + print('SPI input layout: 5 accepted layouts, 7 refusals, request .psin read (2 accepted, 4 refused)') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_stream_check.py b/tests/startup_stream_check.py index ce33bf935d..2239881b2b 100644 --- a/tests/startup_stream_check.py +++ b/tests/startup_stream_check.py @@ -11,10 +11,16 @@ import gfx2hlsl +V_MOV_V0_ONE = 0x7e0002f2 # v_mov_b32 v0, 1.0 + + def container(stage, words=None): - # One straight-line export (pos0 or mrt0) followed by s_endpgm and section padding. + # One straight-line export (pos0 or mrt0) followed by s_endpgm and section padding. The pixel stage first sets + # v0 = 1.0: its entry VGPRs are SPI inputs, and a stream request carries no SPI input layout, so a pixel stage + # that exports an entry VGPR is refused (gfx2hlsl 6f5a7071; the negative control below keeps that form). target = 12 if stage == 1 else 0 - words = words if words is not None else [0xf800080f | target << 4, 0, 0xbf810000] + if words is None: + words = ([] if stage == 1 else [V_MOV_V0_ONE]) + [0xf800080f | target << 4, 0, 0xbf810000] code = struct.pack("<%dI" % len(words), *words) extent = (40 + len(code) + 4 + 15) & ~15 image = bytearray(248 + extent) @@ -74,7 +80,15 @@ def translate(): translate() assert "Unexpected shader stage" in (cache / (bad + ".fail")).read_text() assert not (cache / (bad + ".txt")).exists() - print("WARP stream request, stage order, compiled VS/PS, truncated and swapped controls passed") + # Negative control: the pixel stage exporting its entry VGPR v0 directly is refused, not translated as 0. + entry = container(0, [0xf800080f, 0, 0xbf810000]) + raw = "%016x" % gfx2hlsl.pipeline_key(vs, entry, root.read_bytes()) + for ext, data in ((".a", vs), (".b", entry), (".root", root.read_bytes())): + (cache / ("req_" + raw + ext)).write_bytes(data) + translate() + assert "reads entry VGPR v0" in (cache / (raw + ".fail")).read_text() + assert not (cache / (raw + ".txt")).exists() + print("WARP stream request, stage order, compiled VS/PS, truncated, swapped and entry-VGPR controls passed") if __name__ == "__main__": diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index e7dcab0a22..fee48956ac 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -5,9 +5,11 @@ #include <cctype> #include <cstdlib> #include <cstring> +#include <cwchar> #include <wrl/client.h> #include <array> +#include <thread> #include <fstream> #include <iterator> #include <string> @@ -89,6 +91,12 @@ static bool create_slot57(void* device, const char* vs_path, const char* ps_path pipeline; } +static UINT env_uint(const wchar_t* name) +{ + wchar_t value[16] = L""; + return GetEnvironmentVariableW(name, value, 16) ? static_cast<UINT>(std::wcstoul(value, nullptr, 10)) : 0u; +} + // Binds the pipeline on a guest list and records `calls` ExecuteIndirect calls (list slot 61) with a Draw or a // Dispatch signature. No root or target is bound, so every call is refused and nothing is drawn. static bool bind_and_execute_indirect(void* device, void* pipeline, bool dispatch, int calls) @@ -310,6 +318,35 @@ int main(int argc, char** argv) if (!MoveFileW((std::wstring(manifest) + L".pending").c_str(), manifest)) return 61; Sleep(1100); } + // LOCAL stall (X2W_DRAW_ASYNC): X2W_TEST_HOLD_RELEASE=first|<ms> with X2W_CX_TEST_HOLD_EVENT=<name>. The + // pipeline compile of the first draw waits for the named event: "first" sets it after the first draw + // (<output>.first) returns, <ms> from another thread that many ms after the first draw starts. Then, 1.5 s + // after the release, a second draw to <output>. + wchar_t hold_name[128], release[16]; + const DWORD hold_length = GetEnvironmentVariableW(L"X2W_CX_TEST_HOLD_EVENT", hold_name, 128); + const DWORD release_length = GetEnvironmentVariableW(L"X2W_TEST_HOLD_RELEASE", release, 16); + if (hold_length && hold_length < 128 && release_length && release_length < 16) { + static HANDLE hold = CreateEventW(nullptr, TRUE, FALSE, hold_name); + static DWORD delay = 0; + if (!hold) return 62; + const bool after_first = std::wcscmp(release, L"first") == 0; + if (!after_first) { + delay = static_cast<DWORD>(std::wcstoul(release, nullptr, 10)); + const auto later = [](void*) -> DWORD { + Sleep(delay); + SetEvent(hold); + return 0; + }; + if (const HANDLE t = CreateThread(nullptr, 0, later, nullptr, 0, nullptr)) CloseHandle(t); + else return 62; + } + const std::string first = std::string(argv[5]) + ".first"; + if (const int rc = check_stream_draw(adapter.Get(), device, pso, first.c_str(), nullptr, format)) return rc; + if (after_first) SetEvent(hold); + else WaitForSingleObject(hold, 30000); + Sleep(1500); + return check_stream_draw(adapter.Get(), device, pso, argv[5], nullptr, format); + } if (GetEnvironmentVariableW(L"X2W_TEST_PLACED_VERTEX", nullptr, 0)) { extern void release_placed_vertices(bool); const std::string first = std::string(argv[5]) + ".first"; @@ -320,5 +357,38 @@ int main(int argc, char** argv) release_placed_vertices(true); return rc; } - return check_stream_draw(adapter.Get(), device, pso, argv[5], bc7.blocks ? &bc7 : nullptr, format, export_word, two_targets); + // LOCAL stall: X2W_TEST_THREADS=<n> (2-8) with X2W_TEST_REPEAT=<k>: n threads each record, submit and read back k + // frames on their own list and queue at the same time (one shared device and pipeline), pixels in <out>.t<thread> + // (the last frame); the first failing return code wins. With X2W_DRAW_LOCK_TIMES the lock-times report is + // written at the end (export x2w_draw_lock_times_test op 1). + if (const UINT threads = env_uint(L"X2W_TEST_THREADS"); threads >= 2 && threads <= 8 && !bc7.blocks) { + const UINT repeat = env_uint(L"X2W_TEST_REPEAT") ? env_uint(L"X2W_TEST_REPEAT") : 1; + std::vector<std::thread> workers; + std::vector<int> results(threads, 0); + for (UINT t = 0; t < threads; ++t) + workers.emplace_back([&, t] { + const std::string out = std::string(argv[5]) + ".t" + std::to_string(t); + for (UINT k = 0; k < repeat && !results[t]; ++k) + results[t] = check_stream_draw(adapter.Get(), device, pso, out.c_str(), nullptr, format, export_word, two_targets); + }); + for (auto& w : workers) w.join(); + using LockTimes = std::uint64_t(WINAPI*)(int, std::uint64_t, std::uint64_t); + if (const HMODULE xs = GetModuleHandleW(L"d3d12_xs.dll")) + if (const auto report = reinterpret_cast<LockTimes>(GetProcAddress(xs, "x2w_draw_lock_times_test"))) report(1, 0, 0); + for (int r : results) + if (r) return r; + return 0; + } + const int rc = check_stream_draw(adapter.Get(), device, pso, argv[5], bc7.blocks ? &bc7 : nullptr, format, export_word, two_targets); + // LOCAL lt-lead probe: with X2W_DRAW_DUMP_INPUTS the dump of the (waited-for) draw is written now (export op 1), + // since this program never presents. + if (!rc && GetEnvironmentVariableW(L"X2W_DRAW_DUMP_INPUTS", nullptr, 0)) { + using Flush = int(WINAPI*)(int); + const HMODULE xs = GetModuleHandleW(L"d3d12_xs.dll"); + const auto flush = xs ? reinterpret_cast<Flush>(GetProcAddress(xs, "x2w_draw_dump_inputs_test")) : nullptr; + const int written = flush ? flush(1) : -1; + std::printf("draw input dumps written: %d\n", written); + if (written < 1) return 63; + } + return rc; } diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 34a837861c..3641472c7d 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -289,8 +289,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* // The translated MRT formats draw one pixel; the other formats keep the 8x4 target. const bool single = typed; const bool legacy = !single; - const UINT width = bc_chain ? 384 : bc7 ? (bc7->small4k ? 48 : bc7->width) : bc ? 4 * 128 : single ? 1 : 8; - const UINT height = bc_chain ? 32 : bc7 ? bc7->height : bc ? 128 : single ? 1 : 4; + const bool detile = GetEnvironmentVariableW(L"X2W_TEST_DETILE_SRV", nullptr, 0) != 0; // a 64x64 check target + const UINT width = detile ? 64 : bc_chain ? 384 : bc7 ? (bc7->small4k ? 48 : bc7->width) : bc ? 4 * 128 : single ? 1 : 8; + const UINT height = detile ? 64 : bc_chain ? 32 : bc7 ? bc7->height : bc ? 128 : single ? 1 : 4; ComPtr<ID3D12Device> desktop; if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 20; Bc7Binding binding; @@ -302,7 +303,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* StreamTarget frame; if (two_targets) frame.count = 2; // a second RGBA8 target of the same size, written after the first if (const int rc = open_stream_target(desktop.Get(), guest, pso, width, height, format, - legacy && !bc7 && !bc_chain ? width / 2 : width, frame)) return rc; + legacy && !bc7 && !bc_chain && !detile ? width / 2 : width, frame)) return rc; auto* list = frame.list; auto* queue = frame.queue; auto* fence = frame.fence; @@ -326,6 +327,15 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (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 (detile) { + extern int draw_detile_srvs(void*, void*); + if (const int result = draw_detile_srvs(guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_ANNOUNCED_SRV", nullptr, 0)) { + extern int draw_announced_srvs(ID3D12Device*, void*, void*); + if (const int result = draw_announced_srvs(desktop.Get(), guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_DRAW_UAV", nullptr, 0)) { + extern int draw_uav_stores(ID3D12Device*, void*, void*); + if (const int result = draw_uav_stores(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_MEMORY_SRV_DIAG", nullptr, 0)) { extern int draw_memory_srv_diagnostics(ID3D12Device*, void*, void*); if (const int result = draw_memory_srv_diagnostics(desktop.Get(), guest, list)) return result; @@ -491,7 +501,32 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* invoke(list, 12, 3, 1); last = 2; } + // X2W_TEST_FRAME_COPY=reuse: execute the first list, wait, and record the second half of the frame on the same + // list after Reset (startup_frame_copy.cpp). + char copy_mode[8] = ""; + GetEnvironmentVariableA("X2W_TEST_FRAME_COPY", copy_mode, sizeof(copy_mode)); + const bool copy_reuse = std::strcmp(copy_mode, "reuse") == 0; + if (copy_reuse) { + if (const int rc = submit(1)) return rc; + D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast<SIZE_T>(invoke(frame.rtv_heap, 9))}; + if (FAILED(static_cast<HRESULT>(invoke(frame.allocator, 8))) || + FAILED(static_cast<HRESULT>(invoke(list, 139, arg(frame.allocator))))) return 35; + invoke(list, 50, 1, arg(&rtv)); + invoke(list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(list, 25, arg(pso)); + extern int draw_frame_copies_again(void*, UINT, UINT); + if (const int result = draw_frame_copies_again(list, width, height)) return result; + last = 2; + } if (const int rc = submit(last)) return rc; + if (copy_reuse) { + extern int write_ring_counters(); + if (const int result = write_ring_counters()) return result; + } + if (GetEnvironmentVariableW(L"X2W_TEST_DRAW_UAV", nullptr, 0)) { + extern void report_uav_stores(); + report_uav_stores(); + } 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_interface_check.py b/tests/startup_stream_interface_check.py index 740334e8d0..0f30875e9f 100644 --- a/tests/startup_stream_interface_check.py +++ b/tests/startup_stream_interface_check.py @@ -7,7 +7,12 @@ writes to red. Without arguments only the translator cases run (no consumer, device or compiler): - linked: attribute 0 reads vertex parameter 1; an interface whose order matches keeps parameter 0. + linked: attribute 0 reads vertex parameter 1; an interface whose order matches keeps parameter 0; a kind-7 + vertex record (the SV_ClipDistance register also exported as a parameter) links no attribute. + refused: a kind-7 record on a non-clip register, twice, out of order or with packing bytes; a kind-8 record. + clip: without a .vsout, pos1 is SV_ClipDistance0 when the output signature's system values are SV_Position + and SV_ClipDistance0 from x (CCDIST0 | CLIP_DIST_ENA = the mask); channels above the enabled distances + are not lowered; other signatures leave pos1 refused. refused: a packed pixel record, a vertex record with packing bytes, components that differ between the stages, a semantic the vertex stage does not output, a pixel header of another size, and an attribute read that the pixel table does not list. @@ -35,7 +40,7 @@ PS_RECORDS = [(6, 2, 3, 0, 0, 0, 2, 2)] # TEXCOORD -> attr0, mask 3, linear -def vertex_words(): +def vertex_words(clip=False): # x = 2 * ((2*i) & 2) - 1, y = 2 * (i & 2) - 1 (startup_stream_draw_check.vertex), v3 = 0, v4 = 1.0. words = [vop2(0x1a, 1, 129, 0), vop2(0x1b, 1, 130, 1), vop2(0x1b, 2, 130, 0)] for v in (1, 2): @@ -44,6 +49,7 @@ def vertex_words(): vop2(3, 5, 242, 1), vop2(8, 5, 240, 5), # v5 = (x + 1.0) * 0.5 vop1(1, 6, 240), # v6 = 0.5 0xf80000cf, 0x04030201, # exp pos0 v1, v2, v3, v4 + *((0xf80008df, 0x06060605) if clip else ()), # exp pos1 v5, v6, v6, v6 done (clip distances) 0xf800020f, 0x06060606, # exp param0 v6, v6, v6, v6 (COLOR) 0xf8000a1f, 0x06060505, # exp param1 v5, v5, v6, v6 done (TEXCOORD) 0xbf810000]) @@ -90,9 +96,9 @@ def container(stage, words, base, sections, table): return b"DXBC" + bytes(16) + struct.pack("<3I", 1, at, len(parts)) + struct.pack("<%dI" % len(parts), *offsets) + b"".join(parts) -def vertex(records=VS_RECORDS, outputs=(POSITION, COLOR, TEXCOORD), base=VS_BASE): +def vertex(records=VS_RECORDS, outputs=(POSITION, COLOR, TEXCOORD), base=VS_BASE, clip=False): table = {0x1dc: b"".join(bytes(r) for r in records), 0x29c: struct.pack("<I", len(records))} - return container(1, vertex_words(), base, [signature(b"OSG1", outputs)], table) + return container(1, vertex_words(clip), base, [signature(b"OSG1", outputs)], table) def pixel(records=PS_RECORDS, inputs=(POSITION, COLOR, TEXCOORD), base=PS_BASE, attr=0, count=None): @@ -128,7 +134,58 @@ def translate_cases(directory): pixel(inputs=(POSITION, ("TEXCOORD", 0, 1, 0, 0x3), ("TEXCOORD", 1, 2, 0, 0x3)))) assert status == "ok" and "U(i.param0.x)" in ps, (status, ps) print("translate: TEXCOORD1 links by semantic index, not by name alone") + # Kind 7: the SV_ClipDistance output (register 3) also exported as parameter 2. The pixel stage declares it as + # a system-value input and links only TEXCOORD, so attribute 0 still reads parameter 1. + clip = ("SV_CLIPDISTANCE", 0, 3, 2, 0x1) + clip_vs = dict(records=VS_RECORDS + [(7, 3, 2, 0, 0, 0)], outputs=(POSITION, COLOR, TEXCOORD, clip)) + status, ps = translate(directory / "clip_param", vertex(**clip_vs), pixel(inputs=(POSITION, COLOR, TEXCOORD, clip))) + assert status == "ok" and "U(i.param1.x)" in ps and "i.param2" not in ps, (status, ps) + print("translate: a kind-7 record (SV_ClipDistance also exported as a parameter) links nothing") + # pos1 of a stream vertex stage without a .vsout: PA_CL_VS_OUT_CNTL from the output signature (one clip distance + # in x: CCDIST0 | CLIP_DIST_ENA_0); the export's y, z and w are not clip distances. + status, _ = translate(directory / "clip_export", vertex(clip=True, **clip_vs), + pixel(inputs=(POSITION, COLOR, TEXCOORD, clip))) + vs = (directory / "clip_export").glob("*.vs.hlsl") + vs = next(vs).read_text() + assert status == "ok" and " float clip0 : SV_ClipDistance0;" in vs and "o.clip0 = F(v5);" in vs, (status, vs) + print("translate: stream pos1 -> SV_ClipDistance0 from the output signature (x only)") + for outputs, want in ((clip_vs["outputs"], 0x400001), + ((POSITION, ("SV_CLIPDISTANCE", 0, 3, 2, 0x3)), 0x400003), + ((POSITION, ("SV_CLIPDISTANCE", 0, 3, 2, 0xf)), 0x40000f), + ((POSITION, ("SV_CLIPDISTANCE", 0, 3, 2, 0x2)), None), # not from x + ((POSITION, ("SV_CLIPDISTANCE", 1, 3, 2, 0x1)), None), # second distance vector + ((POSITION, ("SV_CULLDISTANCE", 0, 3, 3, 0x1)), None), # cull distances + ((POSITION, ("SV_CLIPDISTANCE", 0, 3, 2, 0x1), ("SV_RENDERTARGETARRAYINDEX", 0, 4, 4, 0x1)), + None), # a misc vector before it + ((POSITION, COLOR), None)): + got = gfx2hlsl.stream_vs_out_cntl(vertex(outputs=outputs)) + assert got == want, (outputs, got, want) + assert gfx2hlsl.clip_vector_width(0x400001, ["v5", "v6", "v6", "v6"]) == 1 + assert gfx2hlsl.clip_vector_width(0x400003, ["v5", "v6", "off", "off"]) == 2 + for cntl, vals in ((0x400003, ["v5", "off", "v6", "v6"]), (0x400007, ["v5", "v6", "off", "off"]), + (0x400005, ["v5", "v6", "v6", "v6"])): + try: + gfx2hlsl.clip_vector_width(cntl, vals) + except gfx2hlsl.Unsupported: + continue + raise AssertionError("accepted pos1 %s with %#x" % (vals, cntl)) + status, _ = translate(directory / "clip_without_signature", vertex(clip=True), pixel()) + assert status == "unsupported: export target pos1", status + print("translate: signature forms other than SV_Position + SV_ClipDistance0 from x give no PA_CL_VS_OUT_CNTL;" + " an enabled distance not written is refused") for label, vs, ps, want in ( + ("kind 7 on a plain output", vertex(records=VS_RECORDS + [(7, 2, 2, 0, 0, 0)]), pixel(), + "unverified vertex output record 070202000000"), + ("kind 7 twice", vertex(records=VS_RECORDS + [(7, 3, 2, 0, 0, 0), (7, 3, 3, 0, 0, 0)], + outputs=clip_vs["outputs"]), pixel(), + "unverified vertex output record 070303000000"), + ("kind 7 out of order", vertex(records=VS_RECORDS + [(7, 3, 3, 0, 0, 0)], outputs=clip_vs["outputs"]), + pixel(), "unverified vertex output record 070303000000"), + ("kind 7 packing", vertex(records=VS_RECORDS + [(7, 3, 2, 1, 0, 0)], outputs=clip_vs["outputs"]), + pixel(), "unverified vertex output record 070302010000"), + ("kind 8 cull distance", vertex(records=VS_RECORDS + [(8, 3, 2, 0, 0, 0)], + outputs=(POSITION, COLOR, TEXCOORD, ("SV_CULLDISTANCE", 0, 3, 3, 0x1))), + pixel(), "unverified vertex output record 080302000000"), ("packed pixel record", vertex(), pixel(records=[(6, 2, 3, 0, 0, 1, 2, 26)]), "unverified pixel input record 0602030000010" + "21a"), ("vertex record packing", vertex(records=[(6, 1, 0, 0, 0, 0), (6, 2, 1, 3, 0, 3)]), pixel(), diff --git a/tests/startup_stream_pc_table_check.py b/tests/startup_stream_pc_table_check.py new file mode 100644 index 0000000000..18b48cb2b3 --- /dev/null +++ b/tests/startup_stream_pc_table_check.py @@ -0,0 +1,241 @@ +"""A stream vertex shader reads a constant table after its exit through S_GETPC_B64 and GLOBAL_LOAD. + +Source-built gfx1013 code only. The vertex shader is the full-screen triangle of startup_stream_interface_check. +It computes the signed word index i = 3 * vertex_id - 3, sign-extends it to 64 bits and shifts it left by 2, adds +the code address s_getpc_b64 + s_add_u32 / s_addc_u32 point at (four words into the table), and loads two words +with global_load_dwordx2 into param0 (TEXCOORD.xy). The table follows the exit: an alignment S_ENDPGM, a count, +then 12 words in which words 1, 4 and 7 are 0.75 and words 2, 5 and 8 are 0.25. Every other word differs (word 0 is +the S_ENDPGM word), so reading one word off, missing the carry of vertex 0's negative index, or taking the address +from the wrong instruction changes the colour. The pixel shader writes TEXCOORD.xy to red and green. + +Without arguments only the translator cases run (no consumer, device or compiler): + lowered: the address pair is the constant virtual address (the image at address 0) and the image is the HLSL + table; the expected words come from the fixture's bytes (the CPU reference below). + refused: the address read as data, a load whose high word comes from another addition, an EXEC write while a + VGPR holds an address word, s_getpc_b64 without the displacement pair, a global_load through an + address that is not the code address, a load offset modifier, and a stage given the code without the + data after its exit. +With a consumer and a backend the draw runs first on an 8x4 target (left half drawn): + draw: red 191 (0.75) and green 64 (0.25), each within 1. + shifted: the same pipeline with the address one word lower (a mutation) fails the colour check. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from startup_stream_draw_check import vop1, vop2 +from startup_stream_interface_check import (EMPTY_ROOT, HEIGHT, POSITION, PS_BASE, PS_RECORDS, VS_BASE, WIDTH, + container, gfx2hlsl, signature, vertex_words) + +ENDPGM = 0xbf810000 +TEXCOORD = ("TEXCOORD", 0, 2, 0, 0x3) +VS_RECORDS = [(6, 2, 0, 0, 0, 0)] # TEXCOORD -> param0 +F = lambda x: struct.unpack("<I", struct.pack("<f", x))[0] +TABLE = [ENDPGM if j == 0 else F(0.75) if j % 3 == 1 and j < 9 else F(0.25) if j % 3 == 2 and j < 9 + else F(0.5 + j / 64) for j in range(12)] # words 9-11 differ too: three words too high is caught +BIAS = 4 # the address the pair forms is table word 4 + + +def vop3(op, vdst, src0, src1, sdst=0): + return [0xd4000000 | op << 16 | sdst << 8 | vdst, src0 | src1 << 9] + + +GETPC = 0xbe901f00 # s_getpc_b64 s[16:17] +ADDC = 0x82118011 # s_addc_u32 s17, s17, 0 +LOAD_LO = [0xd70f6a07, 0x107 | 0x10 << 9] # v_add_co_u32 v7, vcc_lo, v7, s16 +LOAD_HI = [vop2(0x28, 8, 0x11, 8)] # v_add_co_ci_u32 v8, vcc_lo, s17, v8, vcc_lo +LOAD = [0xdc348000, 0x057d0007] # global_load_dwordx2 v[5:6], v[7:8], off + + +def vertex_code(variant="table"): + """-> (instruction words with the displacement filled in, offset of s_getpc_b64).""" + words = vertex_words()[:11] # v1..v4 = the clip position + words += [vop2(0x0b, 7, 0x83, 0), # v_mul_u32_u24 v7, 3, v0 + vop2(0x25, 7, 0xc3, 7), # v_add_nc_u32 v7, -3, v7 + vop2(0x18, 8, 0x9f, 7)] # v_ashrrev_i32 v8, 31, v7 + words += vop3(0x2ff, 7, 0x82, 256 + 7) # v_lshlrev_b64 v[7:8], 2, v[7:8] + getpc = 4 * len(words) + pair = [GETPC, 0x8010ff10, None, ADDC] # s_add_u32 s16, s16, <displacement> + address = LOAD_LO + LOAD_HI + if variant == "escape": + pair += [vop1(1, 9, 16)] # v_mov_b32 v9, s16 + elif variant == "no pair": + pair = [GETPC, 0xbf800000, 0xbf800000, 0xbf800000] # s_nop + elif variant == "other carry": + address = LOAD_LO + [0xd70f6a09, 0x109 | 0x10 << 9] + LOAD_HI # v_add_co_u32 v9, vcc_lo, v9, s16 + elif variant == "exec": + address += [0xbefe03c1] # s_mov_b32 exec_lo, -1 + elif variant == "plain load": + pair, address = [], [] + load = [LOAD[0] | 4, LOAD[1]] if variant == "offset" else LOAD # offset:4 + words += pair + address + load + [0xbf8c3f70, # s_waitcnt vmcnt(0) + 0xf80000cf, 0x04030201, # exp pos0 v1, v2, v3, v4 + 0xf8000a0f, 0x06060605, # exp param0 v5, v6, v6, v6 done + ENDPGM] + table = 4 * (len(words) + 2) # after the exit: alignment S_ENDPGM, count + if None in words: + words[words.index(None)] = (table + 4 * BIAS - (getpc + 4)) & 0xffffffff + return words, getpc + + +def vertex(variant="table"): + words, _ = vertex_code(variant) + image = {0x1dc: b"".join(bytes(r) for r in VS_RECORDS), 0x29c: struct.pack("<I", len(VS_RECORDS))} + return container(1, words + [ENDPGM, len(TABLE)] + TABLE + [ENDPGM], VS_BASE, + [signature(b"OSG1", (POSITION, TEXCOORD))], image) + + +def pixel(): + words = [0xc8080000, 0xc8090001, 0xc80c0100, 0xc80d0101, # v2, v3 = attr0.x, attr0.y + vop1(1, 4, 128), vop1(1, 5, 242), # v4 = 0, v5 = 1.0 + 0xf800180f, 0x05040302, ENDPGM] # exp mrt0 v2, v3, v4, v5 done vm + image = {0x138: b"".join(bytes(r) for r in PS_RECORDS), 0x238: struct.pack("<I", len(PS_RECORDS))} + return container(0, words, PS_BASE, [signature(b"ISG1", (POSITION, TEXCOORD))], image) + + +def reference(): + """The CPU reference: each vertex's 64-bit address, wrapped as the hardware adds it, read from the fixture.""" + words, getpc = vertex_code() + image = struct.pack("<%dI" % (len(words) + 2 + len(TABLE) + 1), *words, ENDPGM, len(TABLE), *TABLE, ENDPGM) + base = (getpc + 4 + struct.unpack("<i", struct.pack("<I", words[getpc // 4 + 2]))[0]) % 2 ** 64 + values = [] + for vertex_id in range(3): + index = 3 * vertex_id - 3 + address = (base + (index % 2 ** 64) * 4) % 2 ** 64 + values.append(tuple(struct.unpack_from("<f", image, address + 4 * k)[0] for k in range(2))) + return base, image, values + + +def translate(directory, vs, ps): + directory.mkdir(parents=True) + key = gfx2hlsl.pipeline_key(vs, ps, EMPTY_ROOT) + for ext, data in ((".a", vs), (".b", ps), (".root", EMPTY_ROOT)): + (directory / ("req_%016x%s" % (key, ext))).write_bytes(data) + status = gfx2hlsl.translate_request(str(directory), key) + hlsl = directory / ("%016x.vs.hlsl" % key) + return status, hlsl.read_text() if hlsl.exists() else "" + + +def translate_cases(directory): + base, image, values = reference() + assert values == [(0.75, 0.25)] * 3, values + status, vs = translate(directory / "table", vertex(), pixel()) + assert status == "ok", status + assert re.search(r"\bs16 = 0x%08xu;" % base, vs) and re.search(r"\bs17 = 0x00000000u;", vs), vs + table = re.search(r"static const uint x2w_pcimage\[(\d+)\] = \{([^}]*)\};", vs) + assert table and int(table.group(1)) == len(image) // 4, vs + assert [int(w, 16) for w in re.findall(r"0x([0-9a-f]+)u", table.group(2))] == list( + struct.unpack("<%dI" % (len(image) // 4), image)), "the HLSL table is not the image" + assert vs.count("x2w_pcimage[min(") == 2, vs + print("translate: the pair is virtual address %#x (table word %d); the HLSL holds the %d-word image" % ( + base, BIAS, len(image) // 4)) + words, getpc = vertex_code() + for label, want in ( + ("escape", "s_getpc_b64 data pointer: s16 (lo) is read by v_mov_b32_e32 at +0x%x" % (getpc + 16)), + ("other carry", "s_getpc_b64 data pointer: load global_load_dwordx2 v[5:6], v[7:8], off is not through " + "one proven image address at +0x%x" % (getpc + 36)), + ("exec", "s_getpc_b64 data pointer: s_mov_b32 writes EXEC while a VGPR holds an address word at +0x%x" + % (getpc + 28)), + ("no pair", "s_getpc_b64: the shader load address is only elided for a program that also calculates a " + "branch target"), + ("plain load", "global_load without a proven s_getpc_b64 image address"), + ("offset", "s_getpc_b64 data pointer: load global_load_dwordx2 v[5:6], v[7:8], off offset:4 is not " + "through one proven image address at +0x%x" % (getpc + 28))): + status, _ = translate(directory / label.replace(" ", "_"), vertex(label), pixel()) + assert status == "unsupported: " + want, (label, status) + print("translate: %s refused" % label) + # The table is only in the bounded section's .image: a loader that kept the code alone must refuse, not read 0. + original = gfx2hlsl.stream_stage_code + gfx2hlsl.stream_stage_code = lambda blob, stage: bytes(original(blob, stage)) + try: + status, _ = translate(directory / "lost image", vertex(), pixel()) + finally: + gfx2hlsl.stream_stage_code = original + assert status == "unsupported: global_load: the s_getpc_b64 address %#x is outside the %d-byte shader image" % ( + base, 4 * len(words)), status + print("translate: a stage without the image refused") + return 0 + + +def translate_checks(directory): + saved = os.environ.get("X2W_FXC") + os.environ["X2W_FXC"] = "" + try: + return translate_cases(directory) + finally: + if saved is None: + os.environ.pop("X2W_FXC", None) + else: + os.environ["X2W_FXC"] = saved + + +WANT = (191, 64, 0, 255) + + +def check_pixels(pixels): + for y in range(HEIGHT): + for x in range(WIDTH): + got = tuple(pixels[(y * WIDTH + x) * 4:(y * WIDTH + x) * 4 + 4]) + want = WANT if x < WIDTH // 2 else (0, 0, 255, 255) + if any(abs(g - w) > 1 for g, w in zip(got, want)): + return "pixel (%d, %d) is %s, expected %s" % (x, y, got, want) + return None + + +def draw(directory, consumer, backend, shifted): + cache = directory / "cache" + cache.mkdir(parents=True) + vs, ps, root, output = (directory / name for name in ("vs", "ps", "root", "pixels")) + vs.write_bytes(vertex()) + ps.write_bytes(pixel()) + args = [consumer, vs, ps, root] + env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_SHADER_CACHE=str(cache)) + env.setdefault("X2W_D3D12_DEBUG", "0") + subprocess.run(args, env=env, check=True) + key = int(sorted(cache.glob("req_*.a"))[0].name[4:20], 16) + original = gfx2hlsl.pc_data_proof + if shifted: + def lower(ins): + return {off: (r[0], r[1], r[2] - 4) if r[0] == 'lo' else r for off, r in original(ins).items()} + gfx2hlsl.pc_data_proof = lower + try: + status = gfx2hlsl.translate_request(str(cache), key) + finally: + gfx2hlsl.pc_data_proof = original + assert status == "ok", status + result = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True) + print(result.stdout, end="") + if backend == "hardware" and result.returncode == 77: + return None + if result.returncode or "-> drawn;" not in result.stderr: + raise RuntimeError(f"draw failed on {backend}: {result.returncode}\n{result.stderr}") + return output.read_bytes() + + +def check(directory, consumer, backend): + pixels = draw(directory / "table", consumer, backend, False) + if pixels is None: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + difference = check_pixels(pixels) + if difference: + raise AssertionError("table: " + difference) + print(f"{backend} draw: TEXCOORD.xy from the table, {WANT} within 1") + pixels = draw(directory / "shifted", consumer, backend, True) + if not check_pixels(pixels): + raise AssertionError("an address one word lower passed the colour check") + print(f"{backend} shifted address: the colour check fails ({tuple(pixels[:4])} at (0, 0))") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + result = translate_checks(Path(temp) / "translate") + if len(sys.argv) > 1: + result = check(Path(temp), *sys.argv[1:]) + sys.exit(result) diff --git a/tests/startup_stream_ps_inputs_check.py b/tests/startup_stream_ps_inputs_check.py new file mode 100644 index 0000000000..2bb268c018 --- /dev/null +++ b/tests/startup_stream_ps_inputs_check.py @@ -0,0 +1,138 @@ +"""A stream pixel shader that reads an SPI input VGPR takes its layout from the FSSM header's SPI_PS_INPUT_ENA. + +Source-built gfx1013 code only. The vertex shader is startup_stream_interface_check's full-screen triangle. The +pixel shader reads entry v2 and writes red = v2 / 8. Its header holds ENA 0xf02 at +0x248: PERSP_CENTER (v0, v1), +then POS_X..POS_W (v2..v5), so v2 is SV_Position.x. A slot-86 request carries no .psin, so before this the read was +refused. + +Without arguments only the translator cases run: + lowered: v2 reads the pixel position x. + same: a pixel stage that reads no SPI input translates byte for byte the same with and without the header + word (the layout is only used when a read would otherwise be refused). + refused: no header word; a word whose position bits miss the SV_Position read mask; FRONT_FACE without a + declared SV_IsFrontFace. +With a consumer and a backend the draw runs on an 8x4 target (left half drawn): + draw: red follows (x + 0.5) / 8 per column (16, 48, 80, 112, each within 1). This is the CPU reference: + SV_Position.x is the pixel centre. + shifted: the same shader with ENA 0xf00 (PERSP_CENTER dropped, so v2 becomes SV_Position.z; a mutation the + header check accepts) fails the gradient check. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from startup_stream_draw_check import vop1, vop2 +from startup_stream_interface_check import (COLOR, EMPTY_ROOT, POSITION, PS_BASE, PS_RECORDS, TEXCOORD, check_pixels, + container, expected_red, gfx2hlsl, pixel, pixel_words, signature, vertex) + +FRONT_FACE = ("SV_ISFRONTFACE", 0, 1, 9, 0x1) + + +def reading_pixel(ena=0xf02, inputs=(POSITION,)): + words = [vop2(8, 2, 255, 2), 0x3e000000, # v_mul_f32 v2, 0.125, v2 + vop1(1, 6, 128), vop1(1, 7, 242), # v6 = 0, v7 = 1.0 + 0xf800180f, 0x07060602, 0xbf810000] # exp mrt0 v2, v6, v6, v7 done vm + table = {0x238: struct.pack("<I", 0)} + if ena is not None: + table[0x248] = struct.pack("<I", ena) + return container(0, words, PS_BASE, [signature(b"ISG1", inputs)], table) + + +def translate(directory, vs, ps): + directory.mkdir(parents=True) + key = gfx2hlsl.pipeline_key(vs, ps, EMPTY_ROOT) + for ext, data in ((".a", vs), (".b", ps), (".root", EMPTY_ROOT)): + (directory / ("req_%016x%s" % (key, ext))).write_bytes(data) + status = gfx2hlsl.translate_request(str(directory), key) + hlsl = directory / ("%016x.ps.hlsl" % key) + return status, hlsl.read_text() if hlsl.exists() else "" + + +def pixel_with_ena(ena): + """startup_stream_interface_check.pixel() with the header word at +0x248 set.""" + table = {0x138: b"".join(bytes(r) for r in PS_RECORDS), 0x238: struct.pack("<I", len(PS_RECORDS)), + 0x248: struct.pack("<I", ena)} + return container(0, pixel_words(0), PS_BASE, [signature(b"ISG1", (POSITION, COLOR, TEXCOORD))], table) + + +def translate_cases(directory): + status, ps = translate(directory / "position", vertex(), reading_pixel()) + assert status == "ok", status + assert "v2 = U(i.pos.x); // SPI input pos_x_float" in ps, ps + print("translate: v2 reads SV_Position.x from header ENA 0xf02") + _, plain = translate(directory / "plain", vertex(), pixel()) + _, worded = translate(directory / "plain_word", vertex(), pixel_with_ena(0xf02)) + assert plain and plain == worded, "a stage without SPI input reads changed with the header word" + print("translate: a stage that reads no SPI input is unchanged by the header word") + refused = "unsupported: pixel stage reads entry VGPR v2 (an SPI input; layout not in the request) at 0x0" + for label, ps in (("no word", reading_pixel(ena=None)), ("position bits miss the read mask", reading_pixel(0x302)), + ("front face undeclared", reading_pixel(0x1f02))): + status, _ = translate(directory / label.replace(" ", "_"), vertex(), ps) + assert status == refused, (label, status) + print("translate: %s refused" % label) + status, _ = translate(directory / "front_face_declared", vertex(), reading_pixel(0x1f02, (POSITION, FRONT_FACE))) + assert status == "ok", status + print("translate: FRONT_FACE with a declared SV_IsFrontFace accepted") + return 0 + + +def translate_checks(directory): + saved = os.environ.get("X2W_FXC") + os.environ["X2W_FXC"] = "" + try: + return translate_cases(directory) + finally: + if saved is None: + os.environ.pop("X2W_FXC", None) + else: + os.environ["X2W_FXC"] = saved + + +def draw(directory, consumer, backend, ena): + cache = directory / "cache" + cache.mkdir(parents=True) + vs, ps, root, output = (directory / name for name in ("vs", "ps", "root", "pixels")) + vs.write_bytes(vertex()) + ps.write_bytes(reading_pixel(ena)) + args = [consumer, vs, ps, root] + env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_SHADER_CACHE=str(cache)) + env.setdefault("X2W_D3D12_DEBUG", "0") + subprocess.run(args, env=env, check=True) + key = int(sorted(cache.glob("req_*.a"))[0].name[4:20], 16) + status = gfx2hlsl.translate_request(str(cache), key) + assert status == "ok", status + result = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True) + print(result.stdout, end="") + if backend == "hardware" and result.returncode == 77: + return None + if result.returncode or "-> drawn;" not in result.stderr: + raise RuntimeError(f"draw failed on {backend}: {result.returncode}\n{result.stderr}") + return output.read_bytes() + + +def check(directory, consumer, backend): + pixels = draw(directory / "position", consumer, backend, 0xf02) + if pixels is None: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + difference = check_pixels(pixels) + if difference: + raise AssertionError("position: " + difference) + print(f"{backend} draw: red follows SV_Position.x, {[expected_red(x) for x in range(4)]} within 1") + pixels = draw(directory / "shifted", consumer, backend, 0xf00) + if not check_pixels(pixels): + raise AssertionError("ENA without PERSP_CENTER passed the gradient check") + print(f"{backend} shifted layout: the gradient check fails (red {pixels[0]} in column 0)") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + result = translate_checks(Path(temp) / "translate") + if len(sys.argv) > 1: + result = check(Path(temp), *sys.argv[1:]) + sys.exit(result) diff --git a/tests/startup_stream_setup.cpp b/tests/startup_stream_setup.cpp index 09a1ad6c00..3c812be1fe 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -163,7 +163,7 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char D3D12_ROOT_PARAMETER root_cbv{}; char cbv_mode[16]{}; if (!textured && GetEnvironmentVariableA("X2W_TEST_ROOT_CBV", cbv_mode, sizeof(cbv_mode))) { - root_cbv.ParameterType = std::strcmp(cbv_mode, "wrong_type") == 0 ? D3D12_ROOT_PARAMETER_TYPE_SRV + root_cbv.ParameterType = (std::strcmp(cbv_mode, "wrong_type") == 0 || std::strcmp(cbv_mode, "root_srv") == 0) ? D3D12_ROOT_PARAMETER_TYPE_SRV : D3D12_ROOT_PARAMETER_TYPE_CBV; root_cbv.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; root_desc.NumParameters = 1; diff --git a/tests/startup_stream_vertex_exit_check.py b/tests/startup_stream_vertex_exit_check.py new file mode 100644 index 0000000000..fadae83146 --- /dev/null +++ b/tests/startup_stream_vertex_exit_check.py @@ -0,0 +1,100 @@ +"""A stream vertex shader with data after its exit is bounded at its single reachable S_ENDPGM. + +Source-built gfx1013 code only. The fixture is the full-screen vertex shader of startup_stream_interface_check +followed by data words (an alignment S_ENDPGM, a count and a table with an S_ENDPGM-valued entry) and the final +S_ENDPGM, the layout a vertex program with a PC-relative constant table has. Translator cases only: + bounded: pixel_aot.container_code still refuses the section without vertex_data; stream_stage_code returns + the code up to the first S_ENDPGM, with the whole section as .image, and the pipeline translates to + the same HLSL as the shader without the data words (the reference). + refused: a branch around the first exit to a second reachable one, a reachable loop after the exit, and a + branch out of the section. A pixel stage with two exits stays refused. +""" +import os +from pathlib import Path +import struct +import sys +import tempfile + +from startup_stream_interface_check import (COLOR, POSITION, PS_BASE, TEXCOORD, VS_BASE, VS_RECORDS, gfx2hlsl, + container, pixel, pixel_words, signature, translate, vertex_words) + +ENDPGM = 0xbf810000 +DATA = [ENDPGM, 3, 0x3f800000, ENDPGM, 0x12345678, ENDPGM] + + +def vertex_container(words): + table = {0x1dc: b"".join(bytes(r) for r in VS_RECORDS), 0x29c: struct.pack("<I", len(VS_RECORDS))} + return container(1, words, VS_BASE, [signature(b"OSG1", (POSITION, COLOR, TEXCOORD))], table) + + +def body(): + words = vertex_words() + assert words[-1] == ENDPGM and ENDPGM not in words[:-1] + return words[:-1] + + +def sopp(op, simm): + return 0xbf800000 | op << 16 | (simm & 0xffff) + + +def hlsl_of(directory, vs): + status, _ = translate(directory, vs, pixel()) + assert status == "ok", (directory.name, status) + return {p.suffixes[-2]: p.read_text().replace(p.name.split(".")[0], "KEY") + for p in directory.glob("*.hlsl")} + + +def cases(directory): + from pixel_aot import container_code + from resource_inventory import parts + plain = vertex_container(body() + [ENDPGM]) + data = vertex_container(body() + [ENDPGM] + DATA) + program = parts(data)[b"DXIL"] + try: + container_code(program, stage=1) + except ValueError as error: + assert "multi-exit" in str(error), error + else: + raise AssertionError("container_code accepted a vertex section with three S_ENDPGM words") + code = gfx2hlsl.stream_stage_code(data, 1) + whole = container_code(program, stage=1, vertex_data=True) + assert isinstance(code, gfx2hlsl.VertexCode) and bytes(code) == whole[:4 * len(body()) + 4], len(code) + assert code.image == whole and whole[len(code):] == struct.pack("<%dI" % len(DATA), *DATA) + assert struct.unpack_from("<I", whole, len(whole) - 4)[0] == ENDPGM + print("bounded: the code ends at the first S_ENDPGM (+0x%x); the image keeps %d data words" + % (len(code) - 4, (len(whole) - len(code)) // 4)) + reference, bounded = hlsl_of(directory / "plain", plain), hlsl_of(directory / "data", data) + assert reference and reference == bounded, sorted(reference) + print("bounded: the pipeline translates to the HLSL of the shader without the data (%s)" % ", ".join(sorted(bounded))) + + pre, tail = body()[:-6], body()[-6:] # tail: the three exports + for label, words, want in ( + ("second exit", pre + [sopp(5, 1), ENDPGM] + tail + [ENDPGM] + DATA, + "vertex code: 2 reachable S_ENDPGM"), + ("loop after the exit", pre + [sopp(5, len(tail) + 1)] + tail + [ENDPGM, sopp(2, -1)] + DATA, + "vertex code: reachable instruction after the exit"), + ("branch out of the section", pre + [sopp(5, 0x4000)] + tail + [ENDPGM] + DATA, + "vertex code: transfer to +0x%x outside the section" % (4 * len(pre) + 4 + 4 * 0x4000))): + status, _ = translate(directory / label.replace(" ", "_"), vertex_container(words), pixel()) + assert status == "unsupported: " + want, (label, status) + print("refused: %s" % label) + two = container(0, pixel_words()[:-1] + [ENDPGM, ENDPGM] + DATA, PS_BASE, [], {}) + try: + container_code(parts(two)[b"DXIL"], stage=0, vertex_data=True) + except ValueError as error: + assert "multi-exit" in str(error), error + print("refused: a pixel stage with data after its exit (unchanged)") + else: + raise AssertionError("container_code accepted a pixel section with data after its exit") + return 0 + + +if __name__ == "__main__": + saved = os.environ.get("X2W_FXC") + os.environ["X2W_FXC"] = "" + try: + with tempfile.TemporaryDirectory() as temp: + sys.exit(cases(Path(temp))) + finally: + if saved is not None: + os.environ["X2W_FXC"] = saved diff --git a/tests/startup_tbuffer_uint_snorm_check.py b/tests/startup_tbuffer_uint_snorm_check.py new file mode 100644 index 0000000000..325c38c4be --- /dev/null +++ b/tests/startup_tbuffer_uint_snorm_check.py @@ -0,0 +1,136 @@ +"""tbuffer_load_format_* with BUF_FMT_8_8_8_8_UINT, 16_16_SNORM, 16_16_UINT, 2_10_10_10_UNORM (gfx10 60, 24, 27, 50). + +Synthetic gfx1013 words (the vertex stage of startup_vertex_fetch_formats_check: s_load_dwordx4 of vertex buffer 1, +tbuffer_load_format_xyzw v[4:7], v0, ... idxen offset:<o> format:<code>, exp pos0). References from the format +definitions, little-endian fields from the lowest byte: +- 8_8_8_8_UINT: four unsigned bytes, x first; the integer value itself (no conversion). +- 16_16_UINT: two unsigned 16-bit fields, missing z = 0, w = 1 (integer). +- 2_10_10_10_UNORM: x bits [9:0], y [19:10], z [29:20], w [31:30]; c / 1023 and w / 3. +- 16_16_SNORM: two signed 16-bit fields; float = max(c / 32767, -1.0) (D3D11.3 SNORM -> FLOAT, both -32768 and + -32767 give -1.0); missing z = 0, missing w = 1.0. That the console fetch clamps the same way is ASSUMED. +The emitted lines are run in Python (ldu = the unaligned little-endian dword at a) on 16 vertices of a byte +pattern at an odd stride, and on hand-picked edge fields (0, 1, 0x7fff, 0x8000, 0x8001, 0xffff). The float +division is rounded to binary32 once; the GPU's division is not modelled (documented tolerance: exact here). +Negative controls: a reference with x/y swapped, and a translation with the -1.0 clamp removed, both fail. +""" +import math +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_sampler_heap_check import root_blob # noqa: E402 +from startup_stream_check import gfx2hlsl # noqa: E402 + +DATA = bytearray(b''.join(struct.pack('<I', (0x8b02a7f1 + i * 0x413b1) & 0xffffffff) for i in range(64))) +FORMATS = {'BUF_FMT_16_SNORM': (8, 3, 1), 'BUF_FMT_8_8_8_8_UINT': (60, 5, 3), 'BUF_FMT_16_16_SNORM': (24, 6, 2), 'BUF_FMT_16_16_UINT': (27, 6, 2), + 'BUF_FMT_2_10_10_10_UNORM': (50, 7, 1)} # code, stride, offset + + +def f32(x): + return struct.unpack('<f', struct.pack('<f', x))[0] + + +def bits(x): + return struct.unpack('<I', struct.pack('<f', x))[0] + + +def s32(x): + x &= 0xffffffff + return x - (1 << 32) if x >> 31 else x + + +def ldu(a): + return int.from_bytes(DATA[a:a + 4], 'little') + + +def lines(name): + code, _, offset = FORMATS[name] + words = (0xf4080400, 0xfa000010, 0xe8032000 | offset | code << 19, 0x80040400, 0xf80008cf, 0x07060504, 0xbf810000) + pipe = gfx2hlsl.Pipeline(struct.pack('<7I', *words), struct.pack('<3I', 0xf800180f, 0, 0xbf810000), + root_blob(flags=0)) + text = [x[3] for x in gfx2hlsl.decode(struct.pack('<7I', *words))][1] + assert 'format:[%s]' % name in text, text + assert 'srv 0 buf vb 1' in pipe.manifest().splitlines() + out = [l.strip() for l in pipe.hlsl_vs().split('\n')] + return [l for l in out if re.match(r'(a|w|v[4-7]) = ', l)] + + +def to_py(expr): + expr = re.sub(r'(\d)u\b', r'\1', expr) + expr = expr.replace('ldu(r0, a)', 'ldu(a)').replace('asint(', 's32(').replace('U(', 'ubits(') + return expr.replace('float(', 'float(') + + +def ubits(x): + return bits(f32(x)) if isinstance(x, float) else x & 0xffffffff + + +def run(body, vertex, stride): + env = {'v0': vertex, 'ud4': stride} + g = {'ldu': ldu, 's32': s32, 'ubits': ubits, 'max': max, 'float': float, '__builtins__': {}} + for line in body: + m = re.fullmatch(r'(\w+) = (.*);', line) + expr = to_py(m.group(2)) + # binary32 division: the dividend is an exact integer, the quotient rounded once + expr = re.sub(r'float\((.*?)\) / 32767\.0', r'f32(float(\1) / 32767.0)', expr) + g['f32'] = f32 + env[m.group(1)] = eval(expr, g, env) & 0xffffffff if m.group(1) in ('a', 'w') else eval(expr, g, env) + return [ubits(env['v%d' % i]) for i in range(4, 8)] + + +def reference(name, vertex, swap=False): + _, stride, offset = FORMATS[name] + a = vertex * stride + offset + if name == 'BUF_FMT_8_8_8_8_UINT': + f = list(DATA[a:a + 4]) + if swap: + f[0], f[1] = f[1], f[0] + return f + if name == 'BUF_FMT_16_16_UINT': + f = [struct.unpack('<H', DATA[a + 2 * i:a + 2 * i + 2])[0] for i in range(2)] + return (f[::-1] if swap else f) + [0, 1] + if name == 'BUF_FMT_2_10_10_10_UNORM': + d = int.from_bytes(DATA[a:a + 4], 'little') + f = [(d >> s) & m for s, m in ((0, 1023), (10, 1023), (20, 1023), (30, 3))] + if swap: + f[0], f[1] = f[1], f[0] + return [bits(f32(c / float(m))) for c, m in zip(f, (1023, 1023, 1023, 3))] + if name == 'BUF_FMT_16_SNORM': + offset = a + 2 if swap else a + scalar = struct.unpack_from('<h', DATA, offset)[0] + return [bits(f32(max(scalar / 32767.0, -1.0))), 0, 0, bits(1.0)] + f = [struct.unpack('<h', DATA[a + 2 * i:a + 2 * i + 2])[0] for i in range(2)] + if swap: + f.reverse() + return [bits(f32(max(c / 32767.0, -1.0))) for c in f] + [0, bits(1.0)] + + +def main(): + checked = 0 + for name, (_, stride, _) in FORMATS.items(): + body = lines(name) + assert body[0] == 'a = v0 * ud4 + %d;' % FORMATS[name][2] and body[1] == 'w = ldu(r0, a);', body + for v in range(16): + got = run(body, v, stride) + assert got == reference(name, v), (name, v, got, reference(name, v)) + checked += 1 + assert any(run(body, v, stride) != reference(name, v, swap=True) for v in range(16)), name + # SNORM edge fields at vertex 0 + body = lines('BUF_FMT_16_16_SNORM') + for lo, hi in ((0, 1), (0x7fff, 0x8000), (0x8001, 0xffff), (0x8000, 0x7fff)): + DATA[2:6] = struct.pack('<HH', lo, hi) + got = run(body, 0, 6) + assert got == reference('BUF_FMT_16_16_SNORM', 0), (hex(lo), hex(hi), got) + DATA[2:6] = struct.pack('<HH', 0x8000, 0x8000) + assert run(body, 0, 6)[:2] == [bits(-1.0)] * 2 + unclamped = [l.replace('max(', '(').replace(', -1.0))', '))') for l in body] + assert run(unclamped, 0, 6)[0] != bits(-1.0) and math.isfinite(struct.unpack('<f', struct.pack('<I', run(unclamped, 0, 6)[0]))[0]) + print('tbuffer_uint_snorm: %d formats match the format definitions on %d vertices at odd ' + 'strides and 5 SNORM edge pairs; swapped-reference and unclamped-translation controls caught' % (len(FORMATS), checked)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_translator_check.py b/tests/startup_translator_check.py index 280c0811ef..ba029722e4 100644 --- a/tests/startup_translator_check.py +++ b/tests/startup_translator_check.py @@ -88,7 +88,7 @@ def check_negative_control(failures): class StubPipeline: def __init__(self, *args, **kwargs): - pass + self.ps_entry_reads = {} # LOCAL translate_to refuses a pixel stage that reads an SPI input first def hlsl_vs(self): return 'void main() {}\n' diff --git a/tests/startup_vopc_dpp_check.py b/tests/startup_vopc_dpp_check.py new file mode 100644 index 0000000000..dc41a7ce48 --- /dev/null +++ b/tests/startup_vopc_dpp_check.py @@ -0,0 +1,65 @@ +"""VOPC with a DPP16 / DPP8 second dword (src0 250 / 233 / 234) in tools/disasm_rdna2.py and gfx2hlsl. + +Build DPP16 and DPP8 compares from instruction fields. Check quad reads, source modifiers, +invalid controls and refusal when quad operations are disabled. +""" +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.parent / 'tools')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +import startup_quad_dpp_check as Q # noqa: E402 + +def vopc(op, vsrc1, src0, w1): + return struct.pack('<II', 0x7c000000 | op << 17 | vsrc1 << 9 | src0, w1) + + +def asm(words): + return D.decode_instruction(words, 0)[:3] + + +def main(): + comparison = vopc(0x04, 7, 250, 5 | (0x4e << 8) | (1 << 18) | (1 << 19) | (1 << 22) | (0xff << 24)) + assert asm(comparison) == (8, 'v_cmp_gt_f32_dpp', 'v_cmp_gt_f32_dpp vcc_lo, v5, -v7 quad_perm:[2,3,0,1] ' + 'row_mask:0xf bank_mask:0xf bound_ctrl:1 fi:1'), asm(comparison) + # v_cmp_eq_u32 (0xc2) row_shr:1; v_cmpx_gt_f32 (0x14) quad_perm:[1,0,3,2]; DPP8 lanes 1,0,3,2,5,4,7,6 + n, name, text = asm(vopc(0xc2, 3, 250, 4 | 0x111 << 8 | 0xff << 24)) + assert (name, text) == ('v_cmp_eq_u32_dpp', 'v_cmp_eq_u32_dpp vcc_lo, v4, v3 row_shr:1 row_mask:0xf bank_mask:0xf'), text + n, name, text = asm(vopc(0x14, 3, 250, 4 | 0xb1 << 8 | 1 << 18 | 0xff << 24)) + assert text == 'v_cmpx_gt_f32_dpp v4, v3 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf fi:1', text + lanes = sum(sel << 3 * k for k, sel in enumerate((1, 0, 3, 2, 5, 4, 7, 6))) + n, name, text = asm(vopc(0x04, 3, 233, 4 | lanes << 8)) + assert (n, text) == (8, 'v_cmp_gt_f32_dpp vcc_lo, v4, v3 dpp8:[1,0,3,2,5,4,7,6]'), text + # refused: v_cmp_lt_f64 (0x21), neg on v_cmp_eq_u32, DPP16 control 0x1ff + for words, why in ((vopc(0x21, 4, 250, 2 | 0x4e << 8 | 0xff << 24), 'not supported for this opcode'), + (vopc(0xc2, 3, 250, 4 | 0x4e << 8 | 1 << 20 | 0xff << 24), 'modifier'), + (vopc(0x04, 3, 250, 4 | 0x1ff << 8 | 0xff << 24), 'Invalid GFX10 DPP16 control')): + n, name, text = asm(words) + assert n == 8 and '<unsupported' in text and why in D.decode_instruction(words, 0)[3], (text, why) + # translation: v2 = interpolated attribute; v_cmp_gt_f32_dpp vcc, v2 (quad +y neighbour), -v2; v4 = vcc ? 1 : 0 + cmp = vopc(0x04, 2, 250, 2 | 0x4e << 8 | 1 << 18 | 1 << 19 | 1 << 22 | 0xff << 24) + cnd = struct.pack('<I', 0x01 << 25 | 4 << 17 | 242 << 9 | 128) # v_cndmask_b32_e32 v4, 0, 1.0, vcc_lo + ps = Q.INTERP + cmp + cnd + struct.pack('<III', 0xf800180f, 4 | 4 << 8 | 4 << 16 | 4 << 24, 0xbf810000) + listing = [a for _, _, _, a in G.decode(ps)] + assert listing[2].startswith('v_cmp_gt_f32_dpp vcc_lo, v2, -v2 quad_perm:[2,3,0,1]'), listing + text = Q.mesh_pipeline(ps).hlsl_ps() + assert 'uint dpp0 = QuadReadAcrossY(v2);' in text, text + assert 'F(dpp0) > -F(v2)' in text.replace('(-F(v2))', '-F(v2)'), text + try: + Q.mesh_pipeline(ps, quad_ops=False).hlsl_ps() + except G.Unsupported as error: + assert 'v_cmp_gt_f32_dpp' in str(error), error + else: + raise AssertionError('VOPC DPP accepted without quad_ops') + print('vopc dpp: synthetic v_cmp_gt_f32 DPP16 word decoded (quad_perm [2,3,0,1], src1 neg); u32 row_shr, cmpx and ' + 'DPP8 decoded; f64, integer modifiers and an invalid control refused; the pixel stage reads src0 through ' + 'QuadReadAcrossY; refused with quad_ops off (control)') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_vs_heap_check.py b/tests/startup_vs_heap_check.py new file mode 100644 index 0000000000..1213ee3a80 --- /dev/null +++ b/tests/startup_vs_heap_check.py @@ -0,0 +1,91 @@ +"""Resource-heap descriptors at a run-time offset in a VERTEX stage (manifest `heap 1`, X2W_DRAW_FEATURES=heap). + +Synthetic code: root flag 0x400 puts the resource-heap base in s8. The vertex stage loads a 4-dword buffer +descriptor with `s_load_dwordx4 s[16:19], s[8:9], s10` (s10 = 64, a register offset) and reads one dword through it +with buffer_load_dword offen. startup_draw_heap_check covers the pixel stage; this is the vertex form f5802183 +uses (seven such loads, waterfall-indexed). + +Checks: + lowered: the VS HLSL declares heapmem / vinfo / heapbuf, assigns h0 = 64 and reads heapbuf[x2w_hix(h0, 4)]. + CPU: the emitted x2w_vid / x2w_hix bodies are evaluated on a synthetic heap memory. A view token at byte 64 + names view id 7, so the buffer is index 8 + 8 * 7 + 4 = 68. A slot without the token (a raw title + descriptor, see msgs 031623) resolves to the empty view, index 4. + refused: the same stage with the feature off, and a heap descriptor word read as a number. +""" +import os +import re +import struct +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_draw_heap_check import S_MOV_S10_64, heap_root, words # noqa: E402 + +S_LOAD_X4 = [0xf4000000 | 2 << 18 | 16 << 6 | 8 >> 1, 10 << 25] # s_load_dwordx4 s[16:19], s[8:9], s10 +BUFFER_LOAD = [0xe0301000, 0x80040400] # buffer_load_dword v4, v0, s[16:19], 0 offen +EXPORT_POS = [0xf80008cf, 0x04040404] # exp pos0 v4, v4, v4, v4 done +PS = words(*[0x7e000000 | v << 17 | 1 << 9 | 242 for v in (4, 5, 6, 7)], [0xf800180f, 0x07060504]) + + +def helper(hlsl, name): + m = re.search(r'uint %s\(uint h(?:, uint k)?\) \{ return (.*?); \}' % name, hlsl) + assert m, (name, hlsl) + return m.group(1) + + +def evaluate(hlsl, heapmem, h, k): + """Evaluate the emitted x2w_vid / x2w_hix on a byte heap. Only their own forms are translated.""" + load = lambda a: struct.unpack_from('<I', heapmem, a)[0] # noqa: E731 + vid_text = helper(hlsl, 'x2w_vid') + m = re.fullmatch(r'heapmem\.Load\(h\) == 0x([0-9a-f]+)u \? heapmem\.Load\(h \+ 4\) : 0xffffffffu', vid_text) + assert m, vid_text + vid = load(h + 4) if load(h) == int(m.group(1), 16) else 0xffffffff + full = re.search(r'uint x2w_hix\(uint h, uint k\) \{ uint i = x2w_vid\(h\); return i < (\d+)u \? (\d+)u \+ (\d+)u ' + r'\* i \+ k : k; \}', hlsl) + assert full, hlsl + limit, first, step = map(int, full.groups()) + return first + step * vid + k if vid < limit else k + + +def main(): + vs = words(S_MOV_S10_64, S_LOAD_X4, BUFFER_LOAD, EXPORT_POS) + text = [x[3] for x in G.decode(vs)] + assert text[1:3] == ['s_load_dwordx4 s[16:19], s[8:9], s10', 'buffer_load_dword v4, v0, s[16:19], 0 offen'], text + try: + G.Pipeline(vs, PS, heap_root(), features=()) + except G.Unsupported as error: + assert "s_load with a register offset through ('resheap',)" in str(error), str(error) + else: + raise AssertionError('vertex heap load accepted with the feature off') + print('refused: the feature off') + + pipe = G.Pipeline(vs, PS, heap_root(), features=('heap',)) + hlsl, manifest = pipe.hlsl_vs(), pipe.manifest() + for line in ('ByteAddressBuffer heapmem : register(t0, space1);', 'ByteAddressBuffer vinfo : register(t1, space1);', + 'h0 = 0x00000040u;', 'v4 = heapbuf[NonUniformResourceIndex(x2w_hix(h0, 4u))].Load(a + 0);'): + assert line in hlsl, (line, hlsl) + assert re.search(r'ByteAddressBuffer heapbuf\[720008\] : register\(t0, space\d+\);', hlsl), hlsl + assert 'heap 1' in manifest.split('\n'), manifest + print('lowered: the vertex stage reads heapbuf[x2w_hix(h0, 4)] with h0 = 64; manifest heap 1') + + heapmem = bytearray(256) + struct.pack_into('<II', heapmem, 64, G.HEAP_TOKEN, 7) # a runtime view token: view id 7 + struct.pack_into('<II', heapmem, 96, 0x30016fac, 0x12345678) # a raw title descriptor (no token) + got = evaluate(hlsl, heapmem, 0x40, 4) + assert got == 8 + 8 * 7 + 4 == 68, got + assert evaluate(hlsl, heapmem, 96, 4) == 4, 'a raw slot is the empty view' + print('CPU: token slot -> heapbuf index %d (view 7, kind 4); a raw slot -> the empty view 4' % got) + + numeric = words(S_MOV_S10_64, S_LOAD_X4, 0x7e000000 | 4 << 17 | 1 << 9 | 17, EXPORT_POS) # v_mov_b32 v4, s17 + try: + G.Pipeline(numeric, PS, heap_root(), features=('heap',)).hlsl_vs() + except G.Unsupported as error: + assert 'holding desc' in str(error), str(error) + else: + raise AssertionError('a vertex heap descriptor word was read as a number') + print('refused: a heap descriptor word read as a number') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_vs_instance_id_check.py b/tests/startup_vs_instance_id_check.py new file mode 100644 index 0000000000..48de0e245a --- /dev/null +++ b/tests/startup_vs_instance_id_check.py @@ -0,0 +1,62 @@ +"""The vertex stage's entry v3 is the instance id (SV_InstanceID); v1 and v2 have no lowering. + +Synthetic code: v1 = float(v3), v2 = float(v0), v4 = 1.0; exp pos0 v1, v2, v4, v4 done. The title's vertex stages +read v3 before any write exactly when their input signature declares SV_INSTANCEID (measured on the archive's +distinct vertex containers: 441 of 441 with it, none without) and never read v1 or v2; v3 is the instance index +without the start instance (D3D SV_InstanceID; the title adds its own offsets from constants). +Checks: + v3 read: body(vid, iid) with v3 = iid, main takes SV_InstanceID and passes it on every rectangle-list path, + and FXC compiles the pair; + no v3: a stage that reads only v0 keeps the old text (body(uint vid), no SV_InstanceID); + refused: a read of entry v1 or v2. +""" +import os +import struct +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import PS_WORDS, root_blob # noqa: E402 + + +def cvt(dst, src): + return 0x7e000000 | dst << 17 | 6 << 9 | src # v_cvt_f32_u32_e32 v<dst>, <src> + + +def program(first_src): + words = [cvt(1, first_src), cvt(2, 256 + 0), 0x7e0802f2, 0xf80008cf, 0x04040201, 0xbf810000] + return struct.pack('<%dI' % len(words), *words) + + +def main(): + vs = program(256 + 3) + text = [x[3] for x in G.decode(vs)] + assert text[0] == 'v_cvt_f32_u32_e32 v1, v3' and text[3] == 'exp pos0 v1, v2, v4, v4 done', text + hlsl = G.Pipeline(vs, PS_WORDS, root_blob()).hlsl_vs() + for line in ('VSOut body(uint vid, uint iid) {', ' v3 = iid;', 'VSOut main(uint vid : SV_VertexID, uint iid : SV_InstanceID) {', + 'return body(vid, iid);', 'return body(first + corner, iid);', 'return body(first, iid);', + 'return body(first + 2, iid);', 'VSOut p = body(first, iid), q = body(first + 1, iid), r = body(first + 2, iid), o;'): + assert line in hlsl, (line, hlsl) + assert hlsl.index(' v0 = vid;') < hlsl.index(' v3 = iid;') < hlsl.index('float(v3)'), hlsl + with tempfile.TemporaryDirectory() as d: + result = G.translate_to(d, 1, vs, PS_WORDS, root_blob()) + assert result == 'ok', result + assert os.path.getsize(os.path.join(d, '%016x.vs.cso' % 1)) > 0 + plain = G.Pipeline(program(256 + 0), PS_WORDS, root_blob()).hlsl_vs() + assert 'VSOut body(uint vid) {' in plain and 'SV_InstanceID' not in plain and 'iid' not in plain, plain + for reg in (1, 2): + words = program(256 + reg) + try: + G.Pipeline(words, PS_WORDS, root_blob()).hlsl_vs() + except G.Unsupported as error: + assert 'vertex stage reads entry v%d' % reg in str(error), str(error) + else: + raise AssertionError('accepted an entry read of v%d' % reg) + print('vs instance id: v3 = SV_InstanceID through every rectangle-list path, FXC ok; a v0-only stage unchanged; ' + 'entry v1 and v2 refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_vsregs_state_check.py b/tests/startup_vsregs_state_check.py new file mode 100644 index 0000000000..9712c53f95 --- /dev/null +++ b/tests/startup_vsregs_state_check.py @@ -0,0 +1,87 @@ +"""Decode pixel input enables and vertex output controls from synthetic register snapshots.""" +import os +import struct +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import VS_WORDS, root_blob # noqa: E402 +from startup_clip_distance_check import VS as CLIP_VS # noqa: E402 +from startup_spi_input_check import pixel_words, packed # noqa: E402 + + +def dump(ena=0, cntl=0, size=0x184): + blob = bytearray(size) + if size >= 0x5a: + struct.pack_into('<H', blob, 0x58, ena) + if size >= 0x9c: + struct.pack_into('<I', blob, 0x98, cntl) + return bytes(blob) + + +class Request: + def __init__(self, tmp, vs, ps): + self.tmp, self.key = tmp, G.pipeline_key(vs, ps, root_blob()) + self.base = os.path.join(tmp, 'req_%016x' % self.key) + for ext, blob in (('.a', vs), ('.b', ps), ('.root', root_blob())): + open(self.base + ext, 'wb').write(blob) + + def side(self, ext, data): + mode = 'wb' if isinstance(data, bytes) else 'w' + with open(self.base + ext, mode, **({} if mode == 'wb' else {'newline': '\n'})) as f: + f.write(data) + + def drop(self, *exts): + for ext in exts: + for p in (self.base + ext, os.path.join(self.tmp, '%016x%s' % (self.key, ext))): + if os.path.exists(p): + os.remove(p) + + def run(self): + self.drop('.txt', '.fail') + return G.translate_request(self.tmp, self.key) + + def out(self, ext): + return open(os.path.join(self.tmp, '%016x%s' % (self.key, ext)), 'rb').read() + + +def main(): + G.FXC = os.path.join(tempfile.gettempdir(), 'no-such-fxc.exe') # translation only, no compiler + with tempfile.TemporaryDirectory() as tmp: + r = Request(tmp, VS_WORDS, pixel_words(2)) + assert r.run().startswith('unsupported: pixel stage reads entry VGPR v2'), 'no dump: refused as before' + r.side('.vsregs', dump(0x8002)) + assert r.run() == 'ok' and packed(2).encode() in r.out('.ps.hlsl'), 'ENA from the dump' + r.side('.psin', 'spi_ps_input 1 00008002 00008003\n') + assert r.run().startswith('unsupported: pixel stage reads SPI input persp_center'), '.psin wins' + r.drop('.psin', '.vsregs') + r.side('.0badf00d.vsregs', dump(0x8002)) + r.side('.12345678.vsregs', dump(0x8002)) + assert r.run() == 'ok', 'agreeing per-state dumps' + r.side('.12345678.vsregs', dump(0x8080)) + assert r.run().startswith('unsupported: pixel stage reads entry VGPR v2'), 'disagreeing dumps ignored' + r.drop('.0badf00d.vsregs', '.12345678.vsregs') + r.side('.vsregs', dump(0x8002, size=0x40)) + assert r.run().startswith('unsupported: pixel stage reads entry VGPR v2'), 'short dump ignored' + r.drop('.vsregs') + + # A stage that reads no entry VGPR: identical output with no dump and with a dump. + r2 = Request(tmp, VS_WORDS, struct.pack('<5I', 0x7e000280, 0xf800180f, 0, 0xbf810000, 0xbf810000)[:16]) + assert r2.run() == 'ok' + before = [r2.out(e) for e in ('.vs.hlsl', '.ps.hlsl', '.txt')] + r2.side('.vsregs', dump(0x0002, 0)) + assert r2.run() == 'ok' and [r2.out(e) for e in ('.vs.hlsl', '.ps.hlsl', '.txt')] == before, 'byte-identical' + + r3 = Request(tmp, CLIP_VS, pixel_words(2)) + r3.side('.vsregs', dump(0x8002, 0x01400303)) + assert r3.run() == 'ok' and b'SV_ClipDistance0' in r3.out('.vs.hlsl'), 'PA_CL_VS_OUT_CNTL from the dump' + r3.side('.vsout', 'pa_cl_vs_out_cntl 1 01600303\n') + assert r3.run().startswith('unsupported: pos1 export with PA_CL_VS_OUT_CNTL 0x01600303'), '.vsout wins' + print('vsregs state: ENA and PA_CL_VS_OUT_CNTL from the dump; side files win; per-state agreement; ' + 'short dump ignored; no-dump output unchanged') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_vswap_check.py b/tests/startup_vswap_check.py new file mode 100644 index 0000000000..17f2bd4407 --- /dev/null +++ b/tests/startup_vswap_check.py @@ -0,0 +1,99 @@ +"""v_swap_b32 (VOP1 0x65): tmp = D; D = S0; S0 = tmp, in the active lanes. + +Synthetic gfx1013 words only. Reference: AMD RDNA 2 ISA V_SWAP_B32 ("swap operands; input and output modifiers +not supported; this is an untyped operation"); LLVM VOP1Instructions.td defines V_SWAP_B32 for gfx9+ with outs +$vdst, $vdst1 and src0 tied to $vdst1, VOP1 only (no e64, DPP or SDWA form). + +The emitted statements are run by a small interpreter (assignments and `if (exec & 1)` guards only) on a grid of +register values, with exec known (every lane writes) and unknown (the guard is honoured: exec 1 swaps, exec 0 +leaves both registers). Checked: v_swap_b32 v1, v2 swaps; v_swap_b32 v3, v3 emits nothing; a swap whose source +is a lane-uniform constant leaves the destination uniform for v_readfirstlane_b32 while the temporary is not. +Refused (decoder): the VOP3A spelling, which llvm-mc rejects on gfx1013. +Negative control: the statements with their order changed (D written before tmp is taken) fail 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' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_scalar_bits_check import stage, asm # noqa: E402 + +GRID = [0, 1, 0x80000000, 0xffffffff, 0x12345678, 0x3f800000] + + +def vop1(op, d, s): + return 0x7e000000 | d << 17 | op << 9 | s + + +def lines_of(words, exec_known=True): + s = stage([]) + s.lines, s.pc, s.exec_known = [], 0, exec_known + for _, _, name, text in G.decode(struct.pack('<%dI' % len(words), *words)): + s.one(name, text) + return s, s.lines + + +def run(lines, regs): + regs = dict(regs) + for line in lines: + m = re.fullmatch(r'(if \(exec & 1\) )?(\w+) = (\w+);', line) + assert m, line + if m.group(1) and not regs['exec'] & 1: + continue + regs[m.group(2)] = regs[m.group(3)] + return regs + + +def check(lines, exec_value): + bad = 0 + for a in GRID: + for b in GRID: + got = run(lines, {'v1': a, 'v2': b, 'exec': exec_value, 'xswap': 0xdeadbeef}) + want = (b, a) if exec_value & 1 else (a, b) + bad += (got['v1'], got['v2']) != want + return bad + + +def main(): + swap = [vop1(0x65, 1, 256 + 2)] + assert asm(swap) == ['v_swap_b32 v1, v2'], asm(swap) + s, lines = lines_of(swap) + assert lines == ['xswap = v1;', 'v1 = v2;', 'v2 = xswap;'], lines + assert ' uint xswap = 0;' in s.declarations() + assert check(lines, 1) == 0 + s, lines = lines_of(swap, exec_known=False) + assert lines == ['xswap = v1;', 'if (exec & 1) v1 = v2;', 'if (exec & 1) v2 = xswap;'], lines + assert check(lines, 1) == 0 and check(lines, 0) == 0 + # negative control: D written before the temporary is taken + wrong = [lines[1], lines[0], lines[2]] + assert check(wrong, 1) > 0, wrong + + s, lines = lines_of([vop1(0x65, 3, 256 + 3)]) + assert lines == [] and not s.uses_swap, lines + + # uniformity: v2 = 7 is lane-uniform; after the swap v1 holds it, v2 holds the old (non-uniform) v1 + s = stage([]) + s.lines, s.pc = [], 0 + s.lane_s = set() + for _, _, name, text in G.decode(struct.pack('<2I', vop1(1, 2, 128 + 7), swap[0])): + s.one(name, text) + assert 1 in s.uniform_v and 2 not in s.uniform_v, s.uniform_v + + vop3 = [0xd5000000 | (0x180 + 0x65) << 16 | 1, 256 + 2] + assert asm(vop3) == ['v_swap_b32 <unsupported VOP3A encoding>'], asm(vop3) + try: + lines_of(vop3) + except G.Unsupported: + pass + else: + raise AssertionError('VOP3A v_swap_b32 accepted') + print('vswap: v_swap_b32 matches tmp/D/S0 on %d pairs with exec known, 1 and 0; self-swap emits nothing; ' + 'uniformity follows the moved value; VOP3A refused; reordered statements caught' % len(GRID) ** 2) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_waterfall_check.py b/tests/startup_waterfall_check.py new file mode 100644 index 0000000000..282e795696 --- /dev/null +++ b/tests/startup_waterfall_check.py @@ -0,0 +1,304 @@ +"""Waterfall loops (a VGPR descriptor index made scalar one value at a time) and s_nor_b32 of lane masks. + +1. The loop form (LLVM SIInstrInfo.cpp emitLoadScalarOpsFromVGPRLoop, wave32; measured in title pixel stages that + sample bindless textures): + H: v_readfirstlane_b32 s13, v46; v_cmpx_eq_i32 s13, v46; s_lshl_b32 s13, s13, 5; + s_load_dwordx8 s[32:39], s[10:11], s13; s_and_saveexec_b32 s13, s12; image_sample v44, ..., s[32:39]; + s_or_saveexec_b32 s26, s13; s_andn2_wrexec_b32 s25, s25; s_cbranch_scc1 H + RDNA 2 ISA: V_READFIRSTLANE_B32 reads the lowest active lane (lane 0 when exec is 0); V_CMPX writes EXEC with + the compare of the active lanes; S_AND_SAVEEXEC D = EXEC, EXEC = S0 & EXEC; S_OR_SAVEEXEC D = EXEC, + EXEC = S0 | EXEC; S_ANDN2_WREXEC EXEC = S0 & ~EXEC, D = EXEC, SCC = EXEC != 0. + A wave model (32 lanes) and the one-lane model (each lane alone, the readfirstlane giving its own index, as the + translation emits) are run on random index, exec and s12 patterns: every lane samples the same descriptor and + keeps the same v44. Negative control: a one-lane model whose readfirstlane takes lane 0's index differs. + The translation: the readfirstlane emits s13 = v46 at a loop head of this form (b32, and the wave64 b64 form + with an s_waitcnt head); refused without the v_cmpx_eq, with a loop-carried SGPR, with an SGPR read after the + loop, with another branch or a scalar store in the body, and without the wrexec close. + One pass: the emitted form runs the body once (the proven loop's s_cbranch_scc1 becomes fall-through). The + one-lane model with one pass equals the wave on every lane; with a wrong index (the negative control) the looped + one-lane form never exits, the one-pass form ends (a wrong value, not a hang). +2. s_nor_b32 of a mask SGPR: the lane's bit of ~(a | b) is ~(a_i | b_i) (value checked over the four bit pairs); + no SCC is written (inactive lanes are 1 after the complement), so a following s_cbranch_scc1 is refused. +""" +import random +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_scalar_bits_check import stage # noqa: E402 + +LOOP = ['v_readfirstlane_b32 s13, v46', 'v_cmpx_eq_i32_e32 s13, v46', 's_lshl_b32 s13, s13, 5', + 's_load_dwordx8 s[32:39], s[10:11], s13', 's_and_saveexec_b32 s13, s12', 's_waitcnt lgkmcnt(0)', + 'image_sample v44, v[40:41], s[32:39], s[20:23] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 's_or_saveexec_b32 s26, s13', 's_andn2_wrexec_b32 s25, s25', 's_cbranch_scc1 label_0x%x'] + + +def wave(index, exec_, s12, heap): + """The loop on a 32-lane wave: v44 per lane (None = not written).""" + v44 = [None] * 32 + s25, rounds = exec_, 0 + while True: + rounds += 1 + assert rounds <= 33 + first = (exec_ & -exec_).bit_length() - 1 if exec_ else 0 + s13 = index[first] + exec_ &= sum(1 << l for l in range(32) if index[l] == s13) + desc = heap[(s13 << 5) >> 5] + s13, exec_ = exec_, s12 & exec_ + for l in range(32): + if exec_ >> l & 1: + v44[l] = desc + exec_ |= s13 + exec_ = s25 & ~exec_ & 0xffffffff + s25 = exec_ + if not exec_: + return v44 + + +def one_lane(own, active, s12bit, heap, first_lane_index=None, passes=4): + """The same loop in the one-lane model: exec is this lane's bit; readfirstlane gives own (or a forced index). + passes=1 is the emitted form: the body once, the back edge dropped.""" + v44, exec_, s25 = None, active, active + for _ in range(passes): + if passes == 1: # as emitted: an inactive lane's index is 0 (its stale value never reaches a heap read) + s13 = (own if active else 0) if first_lane_index is None else first_lane_index + exec_ &= int(s13 == own) + desc = heap[(s13 << 5) >> 5] + s13, exec_ = exec_, s12bit & exec_ + if exec_: + v44 = desc + return v44 + s13 = own if first_lane_index is None else first_lane_index + exec_ &= int(s13 == own) + desc = heap[(s13 << 5) >> 5] + s13, exec_ = exec_, s12bit & exec_ + if exec_: + v44 = desc + exec_ |= s13 + exec_ = s25 & ~exec_ & 1 + s25 = exec_ + if not exec_: + return v44 + return 'no exit' # (only the negative control's forced index gets here) + + +def semantics(): + rng = random.Random(7) + heap = {i: 1000 + i for i in range(16)} + trials = 0 + for _ in range(400): + index = [rng.choice((0, 3, 3, 5, 9, 15)) for _ in range(32)] + exec_ = rng.getrandbits(32) | (1 << rng.randrange(32)) + s12 = rng.getrandbits(32) | rng.choice((0, 0xffffffff)) + hw = wave(index, exec_, s12, heap) + for l in range(32): + assert hw[l] == one_lane(index[l], exec_ >> l & 1, s12 >> l & 1, heap), (index, hex(exec_), l) + assert hw[l] == one_lane(index[l], exec_ >> l & 1, s12 >> l & 1, heap, passes=1), (index, l) + trials += 1 + # the looped one-lane form never exits under a wrong index (the hang shape); the one-pass form ends regardless + assert one_lane(5, 1, 1, heap, first_lane_index=3) == 'no exit' + assert one_lane(5, 1, 1, heap, first_lane_index=3, passes=1) is None + index = [3] + [5] * 31 + hw = wave(index, 0xffffffff, 0xffffffff, heap) + assert any(hw[l] != one_lane(index[l], 1, 1, heap, first_lane_index=index[0]) for l in range(32)) + return trials + + +def ins_of(text_lines, at=0x100): + out, off = [], at + for text in text_lines: + name = text.split(' ', 1)[0] + n = 8 if name.startswith(('s_load', 'image_', 'v_cmpx_eq_i32_e64')) else 4 + out.append((off, n, name, text)) + off += n + return out + + +def build(body, head=0x100, prefix=('s_mov_b32 s25, exec_lo',), after=('s_endpgm',)): + pre = ins_of(prefix, head - 4 * len(prefix)) + loop = ins_of([x % head if '%x' in x else x for x in body], head) + post = ins_of(after, loop[-1][0] + loop[-1][1]) + return pre + loop + post + + +def readfirstlane(ins, pc): + s = stage([]) + s.ins, s.pc, s.lines = ins, pc, [] + s.uniform_v, s.partial_uniform = set(), {} + s.one('v_readfirstlane_b32', [t for o, _, _, t in ins if o == pc][0]) + return s.lines + + +def refused(ins, pc, why): + try: + readfirstlane(ins, pc) + except G.Unsupported as error: + assert why in str(error), (why, str(error)) + return + raise AssertionError('accepted: ' + why) + + +def one_pass(): + """The proven loop's s_cbranch_scc1 is emitted as fall-through (no back edge, so no dispatch loop); an + s_cbranch_scc1 elsewhere, or in a stage where no waterfall was proven, is still a branch.""" + ins = build(LOOP) + back = [(o, t) for o, _, n, t in ins if n == 's_cbranch_scc1'][0] + s = stage([]) + s.ins, s.pc, s.lines = ins, 0x100, [] + s.uniform_v, s.partial_uniform = set(), {} + s.one('v_readfirstlane_b32', 'v_readfirstlane_b32 s13, v46') + s.pc, s.lines = back[0], [] + assert s.one('s_cbranch_scc1', back[1]) is None and 'not taken' in s.lines[0], s.lines + s.pc = back[0] + 8 + assert s.one('s_cbranch_scc1', back[1]) == ('branch', 'scc', 0x100) + fresh = stage([]) + fresh.pc, fresh.lines = back[0], [] + assert fresh.one('s_cbranch_scc1', back[1]) == ('branch', 'scc', 0x100) + + +def translation(): + one_pass() + assert readfirstlane(build(LOOP), 0x100) == ['s13 = ((exec & 1) != 0 ? v46 : 0u);'] + wide = ['s_waitcnt vmcnt(0)', 'v_readfirstlane_b32 s10, v28', 'v_cmpx_eq_i32_e32 s10, v28', + 's_lshl_b32 s10, s10, 5', 's_load_dwordx8 s[48:55], s[30:31], s10', 's_waitcnt lgkmcnt(0)', + 'image_sample_lz v21, v[21:22], s[48:55], s[32:35] dmask:0x8 dim:SQ_RSRC_IMG_2D', + 's_andn2_wrexec_b64 s[44:45], s[44:45]', 's_cbranch_scc1 label_0x%x'] + assert readfirstlane(build(wide), 0x104) == ['s10 = ((exec & 1) != 0 ? v28 : 0u);'] + controls = 0 + no_cmpx = [x for x in LOOP if not x.startswith('v_cmpx')] + refused(build(no_cmpx), 0x100, 'requires a proven uniform source'); controls += 1 + carried = LOOP[:2] + ['s_add_u32 s40, s40, 1'] + LOOP[2:] + refused(build(carried), 0x100, 'carries s40'); controls += 1 + refused(build(LOOP, after=('s_mov_b32 s5, s26', 's_endpgm')), 0x100, 's26 read after'); controls += 1 + # a read on the branch path only (loop exit at 0x130: the branch, s_endpgm, then the read at 0x138) + refused(build(LOOP, after=('s_cbranch_scc0 label_0x138', 's_endpgm', 's_lshl_b32 s5, s13, 1', 's_endpgm')), + 0x100, 's13 read after'); controls += 1 + branchy = LOOP[:3] + ['s_cbranch_execz label_0x200'] + LOOP[3:] + refused(build(branchy), 0x100, 'another branch'); controls += 1 + store = LOOP[:3] + ['s_store_dword s13, s[0:1], 0x0'] + LOOP[3:] + refused(build(store), 0x100, 'body with s_store_dword'); controls += 1 + unclosed = [x for x in LOOP if 'wrexec' not in x] + refused(build(unclosed), 0x100, 'not closed by s_andn2_wrexec'); controls += 1 + # written again before any read on every exit path: accepted + assert readfirstlane(build(LOOP, after=('s_mov_b32 s13, 0', 's_mov_b32 s26, 1', 's_mov_b32 s5, s13', + 's_endpgm')), 0x100) == ['s13 = ((exec & 1) != 0 ? v46 : 0u);'] + return controls + exit_forms(wide) + execnz_close(wide) + + +def execnz_close(wide): + """The wave64 loop closed by s_cbranch_execnz instead of s_cbranch_scc1 (measured in title vertex stages). + S_ANDN2_WREXEC writes one value to EXEC and to its destination and sets SCC = (value != 0), so directly after + it EXECNZ and SCC1 test the same bit pattern; the wave model above loops `while exec`, which is both. Accepted + and emitted as fall-through like the scc1 form; refused when another instruction separates the wrexec from the + branch (the branch then tests an EXEC the wrexec did not write last), and an execz back edge stays refused.""" + head, ok = 0x104, ['s10 = ((exec & 1) != 0 ? v28 : 0u);'] + loop = wide[:-1] + ['s_cbranch_execnz label_0x%x'] + ins = build(loop) + assert readfirstlane(ins, head) == ok + back = [(o, t) for o, _, n, t in ins if n == 's_cbranch_execnz'][0] + s = stage([]) + s.ins, s.pc, s.lines = ins, head, [] + s.uniform_v, s.partial_uniform = set(), {} + s.one('v_readfirstlane_b32', 'v_readfirstlane_b32 s10, v28') + s.pc, s.lines = back[0], [] + assert s.one('s_cbranch_execnz', back[1]) is None and 'not taken' in s.lines[0], s.lines + fresh = stage([]) + fresh.pc, fresh.lines = back[0], [] + assert fresh.one('s_cbranch_execnz', back[1]) == ('branch', '(exec & 1) != 0', 0x100) + controls = 0 + gap = wide[:-1] + ['s_nop 0', 's_cbranch_execnz label_0x%x'] + refused(build(gap), head, 'not closed by s_andn2_wrexec'); controls += 1 + other = wide[:-2] + ['s_andn2_wrexec_b64 s[44:45], s[46:47]', 's_cbranch_execnz label_0x%x'] + refused(build(other), head, 'not closed by s_andn2_wrexec'); controls += 1 + execz = wide[:-1] + ['s_cbranch_execz label_0x%x'] + refused(build(execz), head, 'without one s_cbranch_scc1 back edge'); controls += 1 + return controls + + +def exit_forms(wide): + """After a wave64 loop (closed by s_andn2_wrexec_b64) a VOPC lane mask is an SGPR pair printed as its low + register: `v_cmp_lt_f32_e64 s48, v1, v2` writes s[48:49] in hardware, the model the low word only. The loop + wrote s48..s55 (s_load_dwordx8). Accepted: the high word read only as the high half of a 64-bit mask + (s_or_b64, s_and_saveexec_b64, v_cndmask_b32_e64), and an SMEM load whose destination overlaps its own base + (the destination is not read). Refused: the high word read as a number, copied by s_mov_b64, or after a wave32 + loop (one register there); a load whose base is a loop-written SGPR.""" + head, ok = 0x104, ['s10 = ((exec & 1) != 0 ? v28 : 0u);'] + cmp = 'v_cmp_lt_f32_e64 s48, v1, v2' + for after in ((cmp, 's_or_b64 s[34:35], s[34:35], s[48:49]', 's_endpgm'), + (cmp, 's_and_saveexec_b64 s[2:3], s[48:49]', 's_endpgm'), + (cmp, 'v_cndmask_b32_e64 v0, v1, v2, s48', 's_endpgm'), + ('s_buffer_load_dwordx16 s[44:59], s[44:47], 0x1a0', 's_endpgm')): + assert readfirstlane(build(wide, after=after), head) == ok, after + controls = 0 + for after, why in (((cmp, 's_add_u32 s5, s49, 1', 's_endpgm'), 's49 read after'), + ((cmp, 's_mov_b64 s[2:3], s[48:49]', 's_endpgm'), 's49 read after'), + (('s_load_dwordx4 s[60:63], s[48:49], 0x0', 's_endpgm'), 's48 read after')): + refused(build(wide, after=after), head, why) + controls += 1 + narrow = ['v_readfirstlane_b32 s13, v46', 'v_cmpx_eq_i32_e32 s13, v46', 's_lshl_b32 s13, s13, 5', + 's_load_dwordx8 s[32:39], s[10:11], s13', 's_waitcnt lgkmcnt(0)', + 'image_sample v44, v[40:41], s[32:39], s[20:23] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 's_andn2_wrexec_b32 s25, s25', 's_cbranch_scc1 label_0x%x'] + refused(build(narrow, after=('v_cmp_lt_f32_e64 s32, v1, v2', 's_or_b64 s[34:35], s[34:35], s[32:33]', + 's_endpgm')), 0x100, 's33 read after') + return controls + 1 + + +def sop2(op, dst, a, b): + return 0x80000000 | op << 23 | dst << 16 | b << 8 | a + + +def nor(): + cmp_vcc = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 + save = 0xbe800000 | 20 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[20:21], vcc (s20 a mask) + words = [cmp_vcc, save, sop2(0x1a, 5, 20, 20)] # s_nor_b32 s5, s20, s20 + text = [x[3] for x in G.decode(struct.pack('<3I', *words))] + assert text[2] == 's_nor_b32 s5, s20, s20', text + s = stage(words) + body = [line for _, lines, _ in s.blocks for line in lines] + line = [x for x in body if x.startswith('s5 = ')] + assert line == ['s5 = (~(s20 | s20)) & 1;'], body + assert not any(x.startswith('scc') for x in body[body.index(line[0]):]), body + for a in (0, 1): + for b in (0, 1): + assert (~(a | b)) & 1 == int(not (a or b)) + # a 0 / 0xffffffff operand (s_cselect_b32 s10, -1, 0) has every lane's bit equal: accepted with a mask + splat = [cmp_vcc, sop2(0x0a, 10, 0xc1, 0x80), sop2(0x1a, 5, 106, 10)] + text = [x[3] for x in G.decode(struct.pack('<3I', *splat))] + assert text[1:] == ['s_cselect_b32 s10, -1, 0', 's_nor_b32 s5, vcc_lo, s10'], text + body = [line for _, lines, _ in stage(splat).blocks for line in lines] + assert 's5 = (~(vcc | s10)) & 1;' in body, body + for value, lane in ((0, 0), (0, 1), (0xffffffff, 0), (0xffffffff, 1)): + assert (~(lane | value)) & 1 == int(not (lane or value & 1)) + # a plain number with a mask (bit i is not lane i's) stays refused + try: + stage([cmp_vcc, sop2(0x1a, 5, 106, 11)]) + except G.Unsupported as error: + assert 'on a lane mask' in str(error), str(error) + else: + raise AssertionError('s_nor_b32 of vcc_lo and a number accepted') + branch = 0xbf850000 | 1 # s_cbranch_scc1 +1 + try: + stage(words + [branch, 0xbf800000]) + except G.Unsupported as error: + assert 'scc' in str(error).lower(), str(error) + else: + raise AssertionError('SCC of s_nor_b32 on a mask read') + + +def main(): + trials = semantics() + controls = translation() + nor() + print('waterfall: wave and one-lane models agree on %d random (index, exec, s12) patterns x 32 lanes; ' + 'lane-0 readfirstlane caught (negative control); b32 and b64 forms translate to sN = vM; %d controls ' + 'refused; one pass (back edge dropped) matches the wave on every lane and ends under a wrong index where the ' + 'looped form never exits; s_nor_b32 of a mask is the lane bit with no SCC (SCC read refused)' % (trials, controls)) + + +if __name__ == '__main__': + main() diff --git a/tests/tile_mapping_shared_heap_check.cpp b/tests/tile_mapping_shared_heap_check.cpp new file mode 100644 index 0000000000..3ebe42b505 --- /dev/null +++ b/tests/tile_mapping_shared_heap_check.cpp @@ -0,0 +1,205 @@ +#include <d3d12.h> +#include <d3d12sdklayers.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <cstdio> +#include <cstdlib> +#include <cstring> + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT64 page = 65536; +constexpr struct { int heap; UINT tile; } mapping[3] = {{0, 2}, {1, 0}, {0, 1}}; + +void drain(ID3D12Device* device) +{ + ComPtr<ID3D12InfoQueue> queue; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&queue)))) return; + for (UINT64 i = 0; i < queue->GetNumStoredMessages() && i < 8; ++i) { + SIZE_T bytes = 0; + queue->GetMessage(i, nullptr, &bytes); + auto* message = static_cast<D3D12_MESSAGE*>(std::malloc(bytes)); + if (message && SUCCEEDED(queue->GetMessage(i, message, &bytes))) + std::printf("debug sev=%d id=%d %s\n", message->Severity, message->ID, message->pDescription); + std::free(message); + } + queue->ClearStoredMessages(); +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) +{ + return {D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags}; +} + +ComPtr<ID3D12Resource> committed(ID3D12Device* device, D3D12_HEAP_TYPE type, UINT64 bytes, D3D12_RESOURCE_STATES state) +{ + const D3D12_HEAP_PROPERTIES properties{type}; + const D3D12_RESOURCE_DESC desc = buffer_desc(bytes); + ComPtr<ID3D12Resource> buffer; + device->CreateCommittedResource(&properties, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&buffer)); + return buffer; +} + +UINT pattern(int heap, UINT64 byte) { return (static_cast<UINT>(heap + 1) << 28) | static_cast<UINT>(byte); } +} // namespace + +int main(int argc, char** argv) +{ + std::setvbuf(stdout, nullptr, _IONBF, 0); + if (argc < 3) return 2; + const bool hardware = !std::strcmp(argv[1], "hardware"); + const bool shared = !std::strcmp(argv[2], "shared"); + if ((!hardware && std::strcmp(argv[1], "warp")) || (!shared && std::strcmp(argv[2], "plain"))) return 2; + const bool debug_layer = !(argc > 3 && !std::strcmp(argv[3], "nodebug")); + ComPtr<ID3D12Debug> debug; + if (debug_layer && SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) debug->EnableDebugLayer(); + ComPtr<IDXGIFactory6> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr<IDXGIAdapter> adapter; + if (hardware) { + for (UINT n = 0;; ++n) { + ComPtr<IDXGIAdapter1> candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(hr) || FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { + adapter = candidate; + break; + } + } + } else if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + LARGE_INTEGER driver{}; + adapter->GetDesc(&adapter_desc); + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls driver=%u.%u.%u.%u mode=%s debug layer %s\n", adapter_desc.Description, HIWORD(driver.HighPart), + LOWORD(driver.HighPart), HIWORD(driver.LowPart), LOWORD(driver.LowPart), argv[2], debug_layer ? "on" : "off"); + ComPtr<ID3D12Device3> device; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) return 77; + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)); + std::printf("tiled resources tier %d\n", static_cast<int>(options.TiledResourcesTier)); + if (options.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_1) return 77; + + ComPtr<ID3D12Heap> heaps[2]; + unsigned char* views[2] = {}; + for (int i = 0; i < 2; ++i) { + HRESULT hr; + if (shared) { + const HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 4 * page, nullptr); + views[i] = section ? static_cast<unsigned char*>(MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 4 * page)) : nullptr; + if (!views[i]) return 4; + for (UINT64 b = 0; b < 4 * page; b += 4) *reinterpret_cast<UINT*>(views[i] + b) = pattern(i, b); + hr = device->OpenExistingHeapFromFileMapping(section, IID_PPV_ARGS(&heaps[i])); + } else { + const D3D12_HEAP_DESC desc{4 * page, {D3D12_HEAP_TYPE_DEFAULT}, 0, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS}; + hr = device->CreateHeap(&desc, IID_PPV_ARGS(&heaps[i])); + } + const D3D12_HEAP_DESC got = SUCCEEDED(hr) ? heaps[i]->GetDesc() : D3D12_HEAP_DESC{}; + std::printf("heap %d (%s) -> 0x%08lx size 0x%llx flags 0x%x%s\n", i, shared ? "OpenExistingHeapFromFileMapping" : "CreateHeap", + static_cast<unsigned long>(hr), got.SizeInBytes, got.Flags, + got.Flags & D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER ? " (SHARED_CROSS_ADAPTER)" : ""); + if (FAILED(hr)) return 5; + if (shared && !(got.Flags & D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER)) { + std::printf("FAIL: an opened file-mapping heap without SHARED_CROSS_ADAPTER: the gate's assumption is wrong\n"); + return 6; + } + } + const D3D12_RESOURCE_DESC reserved_desc = buffer_desc(3 * page, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + ComPtr<ID3D12Resource> reserved; + HRESULT hr = device->CreateReservedResource(&reserved_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&reserved)); + std::printf("CreateReservedResource -> 0x%08lx\n", static_cast<unsigned long>(hr)); + if (FAILED(hr)) return 7; + ComPtr<ID3D12CommandQueue> queue; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + if (FAILED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)))) return 8; + for (UINT t = 0; t < 3; ++t) { + const D3D12_TILED_RESOURCE_COORDINATE coordinate{t, 0, 0, 0}; + const D3D12_TILE_REGION_SIZE region{1, FALSE, 0, 0, 0}; + const D3D12_TILE_RANGE_FLAGS flags = D3D12_TILE_RANGE_FLAG_NONE; + const UINT start = mapping[t].tile, count = 1; + queue->UpdateTileMappings(reserved.Get(), 1, &coordinate, ®ion, heaps[mapping[t].heap].Get(), 1, &flags, &start, &count, + D3D12_TILE_MAPPING_FLAG_NONE); + } + const HRESULT removed_after_mapping = device->GetDeviceRemovedReason(); + std::printf("after UpdateTileMappings: device removed reason 0x%08lx\n", static_cast<unsigned long>(removed_after_mapping)); + drain(device.Get()); + if (shared && removed_after_mapping != S_OK) { + std::printf("shared: tile mapping onto opened file-mapping heaps refused (device removed 0x%08lx): as measured; PASS\n", + static_cast<unsigned long>(removed_after_mapping)); + return 0; + } + + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + 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))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) + return 9; + ComPtr<ID3D12Resource> readback[2]; + ComPtr<ID3D12Resource> upload, placed[2]; + if (shared) { + readback[0] = committed(device.Get(), D3D12_HEAP_TYPE_READBACK, 3 * page, D3D12_RESOURCE_STATE_COPY_DEST); + if (!readback[0]) return 10; + list->CopyBufferRegion(readback[0].Get(), 0, reserved.Get(), 0, 3 * page); + } else { + upload = committed(device.Get(), D3D12_HEAP_TYPE_UPLOAD, 3 * page, D3D12_RESOURCE_STATE_GENERIC_READ); + UINT* words = nullptr; + if (!upload || FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&words)))) return 10; + for (UINT t = 0; t < 3; ++t) + for (UINT64 b = 0; b < page; b += 4) words[(t * page + b) / 4] = pattern(mapping[t].heap, mapping[t].tile * page + b); + upload->Unmap(0, nullptr); + list->CopyBufferRegion(reserved.Get(), 0, upload.Get(), 0, 3 * page); + D3D12_RESOURCE_BARRIER barrier{D3D12_RESOURCE_BARRIER_TYPE_ALIASING}; // the reserved buffer's writes reach the heaps + barrier.Aliasing = {nullptr, nullptr}; + list->ResourceBarrier(1, &barrier); + for (int i = 0; i < 2; ++i) { + const D3D12_RESOURCE_DESC desc = buffer_desc(4 * page); + if (FAILED(device->CreatePlacedResource(heaps[i].Get(), 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&placed[i])))) return 11; + readback[i] = committed(device.Get(), D3D12_HEAP_TYPE_READBACK, 4 * page, D3D12_RESOURCE_STATE_COPY_DEST); + if (!readback[i]) return 11; + list->CopyBufferRegion(readback[i].Get(), 0, placed[i].Get(), 0, 4 * page); + } + } + list->Close(); + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + queue->Signal(fence.Get(), 1); + for (const ULONGLONG deadline = GetTickCount64() + 30000; fence->GetCompletedValue() < 1;) { + if (GetTickCount64() >= deadline || device->GetDeviceRemovedReason() != S_OK) break; + Sleep(1); + } + drain(device.Get()); + const HRESULT removed = device->GetDeviceRemovedReason(); + std::printf("device removed reason 0x%08lx\n", static_cast<unsigned long>(removed)); + if (removed != S_OK) return 12; + int bad = 0; + for (UINT t = 0; t < 3; ++t) { + const int heap = mapping[t].heap; + const UINT* words = nullptr; + const D3D12_RANGE all{0, (shared ? 3 : 4) * page}; + ID3D12Resource* source = readback[shared ? 0 : heap].Get(); + if (FAILED(source->Map(0, &all, reinterpret_cast<void**>(const_cast<UINT**>(&words))))) return 13; + for (UINT64 b = 0; b < page; b += 4) { + const UINT got = shared ? words[(t * page + b) / 4] : words[(mapping[t].tile * page + b) / 4]; + const UINT want = pattern(heap, mapping[t].tile * page + b); + if (got != want && bad++ < 4) std::printf("tile %u (heap %d tile %u) +0x%llx: %08x, want %08x\n", t, heap, mapping[t].tile, b, got, want); + } + source->Unmap(0, nullptr); + } + if (shared) { + std::printf("FAIL: tile mapping onto opened file-mapping heaps WORKED (%s, %d bad dwords). Revisit X2W_RANGE_ALIAS's gate.\n", + bad ? "with wrong data" : "exact", bad); + return 14; + } + std::printf("plain: 3 tiles mapped out of order onto 2 CreateHeap heaps, written through the reserved buffer: %s (%d bad dwords)\n", + bad ? "MISMATCH" : "exact", bad); + std::printf("%s\n", bad ? "FAIL" : "PASS"); + return bad ? 15 : 0; +} diff --git a/tests/x2w_shader/archive_decode_check.cpp b/tests/x2w_shader/archive_decode_check.cpp new file mode 100644 index 0000000000..7b65f2775b --- /dev/null +++ b/tests/x2w_shader/archive_decode_check.cpp @@ -0,0 +1,355 @@ +// Real-program check of the vs-core port: decodes the GFX10 code of every native program listed in +// a reference file made by the upstream Rust implementation (a Rust helper that prints hashes only), and +// compares the decode listing, the SSA form and two IR passes hash for hash. +// +// archive_decode_check env X2W_VS_CORE_ARCHIVE (read only) and +// X2W_VS_CORE_REFERENCE (the helper's lines); without them the +// check is skipped (exit 77), so a plain ctest does not sweep. +// archive_decode_check --dump <label> <k> the full dumps of one program, to diff with the helper's. +// +// Locating the programs (SGD5 records, XDAT/XBCH/FSSM, FSPX) is a minimal stand-in for the upstream +// sgd5.rs and native.rs written for this test only; the vs-front port replaces it in the library. +#include <algorithm> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <fstream> +#include <map> +#include <sstream> +#include <string> +#include <vector> + +#include "startup_stubs/inflate.h" +#include "x2w_shader/gfx10/mod.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/lib.h" + +using namespace x2w::vs; + +namespace { + +using Bytes = std::span<const std::uint8_t>; + +std::uint64_t fnv(const std::string& s) { + std::uint64_t h = 0xcbf29ce484222325ull; + for (unsigned char b : s) { + h ^= b; + h *= 0x100000001b3ull; + } + return h; +} + +std::string hex(std::uint64_t v, int width = 0) { + char buf[32]; + std::snprintf(buf, sizeof buf, "%0*llx", width, static_cast<unsigned long long>(v)); + return buf; +} + +std::uint32_t le32(Bytes d, std::size_t at) { return dxbc::u32_at(d, at); } +std::uint64_t le64(Bytes d, std::size_t at) { return dxbc::u64_at(d, at); } + +// sgd5.rs `record`: the container packed at the marker `at`, or nullopt. +std::optional<std::vector<std::uint8_t>> sgd5_unpack(Bytes file, std::size_t at) { + auto u32 = [&](std::size_t o) -> std::optional<std::size_t> { + if (o + 4 > file.size()) return std::nullopt; + return le32(file, o); + }; + if (at < 6) return std::nullopt; + auto n = u32(at - 4), unpacked = u32(at + 8), n2 = u32(at + 4); + if (!n || !unpacked || !n2 || *n2 != *n || *n < 12 || *unpacked > (64u << 20)) return std::nullopt; + if (at + *n > file.size()) return std::nullopt; + std::vector<std::uint8_t> out(*unpacked); + x2w_inflate::Stream s{file.data() + at + 12, *n - 12, 0, out.data(), out.size()}; + if (!x2w_inflate::inflate_raw(s) || s.out_pos != out.size()) return std::nullopt; + return out; +} + +struct Native { + std::string stage; + bool wave64; + std::uint16_t vgprs; + std::vector<std::uint8_t> code; +}; + +std::optional<Bytes> sub(Bytes d, std::uint64_t offset, std::uint64_t len) { + if (offset > d.size() || len > d.size() - offset) return std::nullopt; + return d.subspan(std::size_t(offset), std::size_t(len)); +} + +// native.rs `native_programs`, the code-locating part only. Throws on what it cannot read. +std::vector<Native> native_programs(Bytes part) { + std::vector<Native> out; + if (part.size() >= 4 && std::memcmp(part.data(), "FSPX", 4) == 0) { + std::size_t count = le32(part, 8); + auto entry = [&](std::uint32_t kind) -> Bytes { + for (std::size_t i = 0; i < count; ++i) { + std::size_t at = 0x10 + 16 * i; + if (le32(part, at) == kind) { + auto b = sub(part, le32(part, at + 4), le32(part, at + 8)); + if (!b) throw ShaderError::malformed("FSPX entry out of bounds"); + return *b; + } + } + throw ShaderError::malformed("FSPX entry missing"); + }; + Bytes packet = entry(0), code = entry(6); + bool wave64 = (dxbc::u16_at(packet, 0x12) & (1 << 4)) == 0; + std::uint32_t granules = (le32(packet, 0x14) & 0x3F) + 1; + std::uint32_t vgprs = std::min<std::uint32_t>(granules * (wave64 ? 4 : 8), 256); + out.push_back({"Cs", wave64, std::uint16_t(vgprs), {code.begin(), code.end()}}); + return out; + } + if (part.size() < 0x1C || std::memcmp(part.data() + 0x18, "XDAT", 4) != 0) return out; + std::size_t count = le32(part, 0x1C); + for (std::size_t i = 0; i < count; ++i) { + std::size_t at = 0x18 + 12 + 12 * i; + if (le32(part, at) != 0x0d) continue; + auto blob = sub(part, le32(part, at + 4), le32(part, at + 8)); + if (!blob || blob->size() < 0x18 || std::memcmp(blob->data(), "XBCH", 4) != 0) { + throw ShaderError::malformed("XBCH"); + } + std::uint64_t packed = le64(*blob, 8), unpacked = le64(*blob, 16); + auto stream = sub(*blob, 0x18, packed); + if (!stream || unpacked > (16u << 20)) throw ShaderError::malformed("XBCH stream"); + std::vector<std::uint8_t> fssm(static_cast<std::size_t>(unpacked)); + std::size_t produced = 0; + if (!x2w_inflate::inflate_zlib(stream->data(), stream->size(), fssm.data(), fssm.size(), &produced) || + produced != fssm.size()) { + throw ShaderError::malformed("XBCH inflate"); + } + Bytes f(fssm); + if (f.size() < 0x10 || std::memcmp(f.data(), "FSSM", 4) != 0) throw ShaderError::malformed("FSSM"); + Bytes payload = f.subspan(0x10); + static const std::pair<const char*, std::size_t> SLOTS[] = { + {"Ls", 0x08}, {"Hs", 0x10}, {"Es", 0x18}, {"Gs", 0x20}, {"Vs", 0x28}, {"Ps", 0x30}, {"Ms", 0x48}, {"Cs", 0x60}, + }; + for (auto [stage, slot] : SLOTS) { + std::uint64_t start = le64(payload, slot); + if (start == 0xDEADBEEFDEADBEEFull) continue; + auto record = sub(payload, start, 0x54); + if (!record) throw ShaderError::malformed("FSSM record out of bounds"); + auto code = sub(payload, le64(*record, 0), le64(*record, 8)); + if (!code) throw ShaderError::malformed("native code out of bounds"); + Native n; + n.stage = stage; + n.vgprs = std::uint16_t(le32(*record, 0x50) & 0x3FF); + n.wave64 = (le32(*record, 0x14) & (1u << 5)) == 0; + n.code.assign(code->begin(), code->end()); + out.push_back(std::move(n)); + } + } + return out; +} + +// --- the dumps, line for line as the helper prints them + +std::string decode_dump(const std::vector<std::uint8_t>& code, bool wave64, std::size_t& ninst) { + ninst = 0; + std::vector<gfx10::Instruction> list; + try { + list = gfx10::decode(code); + } catch (const ShaderError& e) { + return "ERR " + e.to_string() + "\n"; + } + ninst = list.size(); + std::string out; + for (const auto& i : list) { + out += hex(i.offset) + " " + gfx10::debug(i.encoding) + " " + std::to_string(i.opcode); + for (std::uint32_t w : i.words) out += " " + hex(w, 8); + out += "|" + i.text(wave64) + "\n"; + } + return out; +} + +std::string ir_dump(const ir::Program& p) { + std::string out = "inputs"; + for (const auto& [r, v] : p.inputs) out += " " + r.debug() + "=" + std::to_string(v.n); + out += "\n"; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + const ir::Block& block = p.blocks[b]; + std::string preds; + for (std::size_t i = 0; i < block.preds.size(); ++i) preds += (i ? "," : "") + std::to_string(block.preds[i]); + out += "B" + std::to_string(b) + " @" + hex(block.offset) + " preds " + preds + " exit " + block.exit.debug() + "\n"; + for (const ir::Phi& phi : block.phis) { + std::string args; + for (std::size_t i = 0; i < phi.args.size(); ++i) args += (i ? "," : "") + std::to_string(phi.args[i].n); + out += " phi " + phi.reg.debug() + "=" + std::to_string(phi.value.n) + " <- " + args + "\n"; + } + for (const ir::Inst& inst : block.insts) { + out += " " + std::string(inst.name()); + for (std::uint32_t w : inst.machine.words) out += " " + hex(w, 8); + out += " r"; + for (const auto& [r, v] : inst.reads) out += " " + r.debug() + "=" + std::to_string(v.n); + out += " w"; + for (const auto& [r, v] : inst.writes) out += " " + r.debug() + "=" + std::to_string(v.n); + out += "\n"; + } + } + return out; +} + +struct Dumps { + std::string decode, ir, early, skips, status; + std::size_t ninst = 0; +}; + +Dumps dumps(const Native& n) { + Dumps d; + d.decode = decode_dump(n.code, n.wave64, d.ninst); + // Where Rust panics (an index out of range), the port throws a std::exception other than + // ShaderError: both sides record "PANIC" for that stage. + std::optional<ir::Program> p; + try { + p = ir::build(n.code, n.wave64, n.vgprs); + } catch (const ShaderError& e) { + d.ir = "ERR " + e.to_string() + "\n"; + d.status = e.to_string(); + return d; + } catch (const std::exception&) { + d.ir = "PANIC\n"; + d.status = "PANIC"; + return d; + } + d.ir = ir_dump(*p); + d.status = "ok"; + try { + auto early = ir::without_early_outs(*p); + d.early = early ? ir_dump(*early) : "none\n"; + } catch (const std::exception&) { + d.early = "PANIC\n"; + } + try { + auto skips = ir::without_skips(*p, true); + d.skips = skips ? ir_dump(*skips) : "none\n"; + } catch (const std::exception&) { + d.skips = "PANIC\n"; + } + return d; +} + +std::optional<std::vector<std::uint8_t>> container_at(Bytes file, const std::string& label) { + std::size_t at = std::stoull(label.substr(1), nullptr, 16); + if (label[0] == 'r') return sgd5_unpack(file, at); + if (at >= file.size()) return std::nullopt; + return std::vector<std::uint8_t>(file.begin() + at, file.end()); +} + +std::vector<Native> programs_of(Bytes file, const std::string& label) { + auto bytes = container_at(file, label); + if (!bytes) throw ShaderError::malformed("corrupt record"); + // The container borrows `bytes`; the programs are copies. + Container c = Container::parse(*bytes); + const Part* part = c.part(FourCC::DXIL); + if (!part) part = c.part(FourCC::ACCC); + if (!part) throw ShaderError::malformed("no DXIL part"); + return native_programs(part->data); +} + +std::vector<std::uint8_t> read_file(const char* path) { + std::ifstream f(path, std::ios::binary); + return std::vector<std::uint8_t>(std::istreambuf_iterator<char>(f), {}); +} + +std::vector<std::string> split_tabs(const std::string& line) { + std::vector<std::string> out; + std::stringstream ss(line); + std::string field; + while (std::getline(ss, field, '\t')) out.push_back(field); + return out; +} + +} // namespace + +int main(int argc, char** argv) { + const char* archive = std::getenv("X2W_VS_CORE_ARCHIVE"); + const char* reference = std::getenv("X2W_VS_CORE_REFERENCE"); + if (!archive || !*archive) { + std::printf("SKIP: X2W_VS_CORE_ARCHIVE is not set\n"); + return 77; + } + std::vector<std::uint8_t> file = read_file(archive); + if (file.empty()) { + std::printf("SKIP: archive unreadable\n"); + return 77; + } + if (argc == 4 && std::strcmp(argv[1], "--dump") == 0) { + auto progs = programs_of(file, argv[2]); + const Native& n = progs.at(std::stoul(argv[3])); + Dumps d = dumps(n); + std::printf("== decode\n%s== ir\n%s== early\n%s== skips\n%s", d.decode.c_str(), d.ir.c_str(), d.early.c_str(), + d.skips.c_str()); + return 0; + } + if (!reference || !*reference) { + std::printf("SKIP: X2W_VS_CORE_REFERENCE is not set\n"); + return 77; + } + std::ifstream ref(reference); + std::string line; + std::size_t programs = 0, instructions = 0, skipped = 0, mismatches = 0, ir_ok = 0; + std::map<std::string, std::size_t> statuses; // IR failures by text + std::string cached_label; + std::vector<Native> cached; + std::string cached_error; + while (std::getline(ref, line)) { + auto f = split_tabs(line); + if (f.size() < 3) continue; + if (f[1] == "-") { + ++skipped; + continue; + } + if (f.size() != 12) { + std::printf("bad reference line: %s\n", line.c_str()); + return 2; + } + const std::string& label = f[0]; + std::size_t k = std::stoul(f[1]); + if (label != cached_label) { + cached_label = label; + cached.clear(); + cached_error.clear(); + try { + cached = programs_of(file, label); + } catch (const std::exception& e) { + cached_error = e.what(); + } + } + ++programs; + auto report = [&](const std::string& what) { + if (++mismatches <= 30) std::printf("MISMATCH %s %zu: %s\n", label.c_str(), k, what.c_str()); + }; + if (k >= cached.size()) { + report("program not found (" + cached_error + ")"); + continue; + } + const Native& n = cached[k]; + std::string got_meta = n.stage + "\t" + (n.wave64 ? "1" : "0") + "\t" + std::to_string(n.vgprs) + "\t" + + std::to_string(n.code.size()); + std::string want_meta = f[2] + "\t" + f[3] + "\t" + f[4] + "\t" + f[5]; + if (got_meta != want_meta) { + report("program differs: " + got_meta + " vs " + want_meta); + continue; + } + Dumps d = dumps(n); + instructions += d.ninst; + if (std::to_string(d.ninst) != f[6]) report("instruction count " + std::to_string(d.ninst) + " vs " + f[6]); + if (hex(fnv(d.decode), 16) != f[7]) report("decode listing"); + if (hex(fnv(d.ir), 16) != f[8]) report("ir"); + if (hex(fnv(d.early), 16) != f[9]) report("without_early_outs"); + if (hex(fnv(d.skips), 16) != f[10]) report("without_skips"); + if (d.status != f[11]) report("ir status \"" + d.status + "\" vs \"" + f[11] + "\""); + if (d.status == "ok") { + ++ir_ok; + } else { + ++statuses[d.status.substr(d.status.find(": ") + 2)]; + } + } + std::printf("%zu programs (%zu instructions), %zu with IR, %zu container lines skipped, %zu mismatches\n", programs, + instructions, ir_ok, skipped, mismatches); + std::size_t shown = 0; + for (const auto& [why, count] : statuses) { + if (++shown > 15) break; + std::printf(" %6zu %s\n", count, why.c_str()); + } + return programs > 0 && mismatches == 0 ? 0 : 1; +} diff --git a/tests/x2w_shader/core_tests.cpp b/tests/x2w_shader/core_tests.cpp new file mode 100644 index 0000000000..d7d04ae70f --- /dev/null +++ b/tests/x2w_shader/core_tests.cpp @@ -0,0 +1,811 @@ +// Unit tests of the vs-core modules of x2w_shader, ported from the #[cfg(test)] blocks of the upstream Rust shader crate, +// specifically dxbc.rs, dxil.rs, gfx10/{mod,opcodes,sp3}.rs and ir.rs (same names, same cases). +// `x2w_shader_core_tests <name>` runs one test, no argument runs all, `--list` lists them. +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <string> +#include <vector> + +#include "x2w_shader/gfx10/mod.h" +#include "x2w_shader/gfx10/opcodes.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/lib.h" + +using namespace x2w::vs; + +namespace { + +struct TestCase { + const char* name; + void (*fn)(); +}; + +std::vector<TestCase>& registry() { + static std::vector<TestCase> r; + return r; +} + +struct Register { + Register(const char* name, void (*fn)()) { registry().push_back({name, fn}); } +}; + +int failures = 0; + +void fail(const char* file, int line, const std::string& what) { + std::fprintf(stderr, "%s:%d: check failed: %s\n", file, line, what.c_str()); + ++failures; +} + +#define TEST(name) \ + void name(); \ + const Register register_##name{#name, name}; \ + void name() + +#define CHECK(c) \ + do { \ + if (!(c)) fail(__FILE__, __LINE__, #c); \ + } while (0) + +#define CHECK_EQ(a, b) \ + do { \ + if (!((a) == (b))) fail(__FILE__, __LINE__, #a " == " #b); \ + } while (0) + +// A ShaderError of `expr`, or nullopt. +#define ERROR_OF(expr) catch_shader_error([&] { (void)(expr); }) + +std::vector<std::uint8_t> bytes(const std::vector<std::uint32_t>& words) { + std::vector<std::uint8_t> out; + for (std::uint32_t w : words) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(w >> (8 * i))); + } + return out; +} + +dxbc::Bytes span(const std::vector<std::uint8_t>& v) { return dxbc::Bytes(v.data(), v.size()); } + +// ---------------------------------------------------------------- dxbc.rs + +TEST(dxbc_round_trips_parts) { + std::vector<std::uint8_t> a = {1, 2, 3, 4}, h(20, 9); + auto data = dxbc::build({{FourCC::SFI0, span(a)}, {FourCC::HASH, span(h)}}); + Container c = Container::parse(span(data)); + CHECK_EQ(c.parts.size(), 2u); + CHECK(c.part(FourCC::SFI0) && std::vector<std::uint8_t>(c.part(FourCC::SFI0)->data.begin(), + c.part(FourCC::SFI0)->data.end()) == a); + CHECK(c.part(FourCC::HASH) && c.part(FourCC::HASH)->data.size() == 20); + CHECK(c.part(FourCC::DXIL) == nullptr); +} + +TEST(dxbc_rejects_bad_input) { + std::vector<std::uint8_t> nope = {'n', 'o', 'p', 'e'}; + CHECK(ERROR_OF(Container::parse(span(nope))) == ShaderError::not_dxbc()); + std::vector<std::uint8_t> z(8, 0); + auto data = dxbc::build({{FourCC::SFI0, span(z)}}); + std::size_t last = data.size() - 1; + data[0x20] = 0xFF; // corrupt the first part offset + CHECK(ERROR_OF(Container::parse(span(data))).has_value()); + data.resize(last); + CHECK(ERROR_OF(Container::parse(span(data))).has_value()); +} + +// ---------------------------------------------------------------- dxil.rs + +const std::uint8_t MAGIC[4] = {0x42, 0x43, 0xC0, 0xDE}; + +std::vector<std::uint8_t> fake_bitcode() { + std::vector<std::uint8_t> b(MAGIC, MAGIC + 4); + b.insert(b.end(), 12, 0xAA); + return b; +} + +TEST(dxil_parses_standard_layout) { + auto bc = fake_bitcode(); + auto data = dxil::build_standard(0, {6, 0}, 0x100, span(bc)); + DxilProgram p = DxilProgram::parse(span(data)); + CHECK(p.kind == ShaderKind::Pixel); + CHECK(p.shader_model == std::make_pair(std::uint8_t(6), std::uint8_t(0))); + CHECK(p.is_standard_layout()); + CHECK(p.xbox_extras() == XboxExtras{}); +} + +TEST(dxil_detects_xbox_layout) { + // Xbox layout: XDAT table before the bitcode, xbop blob after it. + auto bitcode = fake_bitcode(); + const std::uint8_t xdat[] = {'X', 'D', 'A', 'T', 1, 0, 0, 0}; + const std::uint8_t trailer[] = {'x', 'b', 'o', 'p', 2, 0, 0, 0}; + std::vector<std::uint8_t> data; + auto put32 = [&](std::uint32_t v) { + for (int i = 0; i < 4; ++i) data.push_back(std::uint8_t(v >> (8 * i))); + }; + std::size_t size = 24 + sizeof xdat + bitcode.size() + sizeof trailer; + put32((5u << 16) | 0x65); // cs_6_5 + put32(std::uint32_t(size / 4)); + data.insert(data.end(), {'D', 'X', 'I', 'L'}); + put32(0x105); + put32(16 + sizeof xdat); + put32(std::uint32_t(bitcode.size())); + data.insert(data.end(), std::begin(xdat), std::end(xdat)); + data.insert(data.end(), bitcode.begin(), bitcode.end()); + data.insert(data.end(), std::begin(trailer), std::end(trailer)); + + DxilProgram p = DxilProgram::parse(span(data)); + CHECK(p.kind == ShaderKind::Compute); + CHECK(p.shader_model == std::make_pair(std::uint8_t(6), std::uint8_t(5))); + CHECK(!p.is_standard_layout()); + CHECK((p.xbox_extras() == XboxExtras{true, true})); + CHECK(std::vector<std::uint8_t>(p.bitcode.begin(), p.bitcode.end()) == bitcode); +} + +TEST(dxil_rejects_missing_bitcode_magic) { + std::vector<std::uint8_t> z(16, 0); + auto data = dxil::build_standard(0, {6, 0}, 0x100, span(z)); + CHECK(ERROR_OF(DxilProgram::parse(span(data))).has_value()); +} + +// ---------------------------------------------------------------- gfx10/mod.rs + +constexpr std::uint32_t S_ENDPGM = 0xBF81'0000; + +// s_branch / s_cbranch_scc0 with a dword offset relative to the next instruction. +constexpr std::uint32_t sopp(std::uint32_t op, std::int16_t simm16) { + return 0xBF80'0000u | op << 16 | std::uint16_t(simm16); +} + +struct Summary { + std::size_t offset; + std::size_t words; + std::string name; + bool operator==(const Summary&) const = default; +}; + +std::vector<Summary> summary(const std::vector<std::uint32_t>& code) { + std::vector<Summary> out; + for (const auto& i : gfx10::decode(bytes(code))) { + out.push_back({i.offset, i.words.size(), std::string(i.name().value_or("?"))}); + } + return out; +} + +TEST(gfx10_flat_offsets_ignore_bit_eleven) { + auto offset = [](std::uint32_t word0) -> int { + auto code = bytes({word0, 0x0000'0001, S_ENDPGM}); + auto fields = gfx10::decode(code)[0].fields(false); + const auto* f = std::get_if<gfx10::Flat>(&fields); + if (!f) { + fail(__FILE__, __LINE__, "not FLAT fields"); + return -1; + } + return f->offset; + }; + // flat_load_dword v0, v[1:2]: the FLAT offset is 11-bit and unsigned, so bit 11 is ignored + // (0x800 -> 0, 0xfff -> 0x7ff). + CHECK_EQ(offset(0xDC30'0800), 0); + CHECK_EQ(offset(0xDC30'0FFF), 0x7FF); +} + +TEST(gfx10_tables_are_sorted) { + namespace o = gfx10::opcodes; + for (const o::Table& t : {o::SOP2, o::SOPK, o::SOP1, o::SOPC, o::SOPP, o::SMEM, o::VOP2, o::VOP1, o::VOPC, + o::VOP3, o::VOP3P, o::VINTRP, o::DS, o::MUBUF, o::MTBUF, o::MIMG, o::FLAT, o::GLOBAL, + o::SCRATCH}) { + CHECK(!t.empty()); + for (std::size_t i = 0; i + 1 < t.size(); ++i) CHECK(t[i].op < t[i + 1].op); + } +} + +TEST(gfx10_lengths_and_names) { + std::vector<std::uint32_t> code = { + 0xBE80'03FF, 0x3F80'0000, // s_mov_b32 s0, literal + 0x0600'0000, // v_add_f32 v0, s0, v0 + 0xD54B'0000, 0x03FE'0000, 0x4000'0000, // v_fma_f32 with a literal src2 + 0xF080'0F0A, 0, 0, // image_sample (2D) with one extra address dword + 0xF800'080F, 0, // exp + S_ENDPGM, + }; + std::vector<Summary> want = { + {0, 2, "s_mov_b32"}, {8, 1, "v_add_f32"}, {12, 3, "v_fma_f32"}, + {24, 3, "image_sample"}, {36, 2, "exp"}, {44, 1, "s_endpgm"}, + }; + CHECK(summary(code) == want); +} + +TEST(gfx10_follows_branches_and_skips_data) { + std::vector<std::uint32_t> code = { + sopp(0x04, 1), // s_cbranch_scc0 -> 8 + sopp(0x02, 1), // s_branch -> 12 + S_ENDPGM, S_ENDPGM, + S_ENDPGM, // data follows the program end + 0xFFFF'FFFF, + }; + std::vector<std::size_t> found; + for (const auto& s : summary(code)) found.push_back(s.offset); + CHECK((found == std::vector<std::size_t>{0, 4, 8, 12})); +} + +TEST(gfx10_follows_far_jumps) { + std::vector<std::uint32_t> code = { + 0xBE88'1F00, // s_getpc_b64 s[8:9] + 0x8008'FF08, 20, // s_add_u32 s8, s8, 20 -> 4 + 20 = 24 + 0x8209'8009, // s_addc_u32 s9, s9, 0 + 0xBE80'2008, // s_setpc_b64 s[8:9] + 0xFFFF'FFFF, // not code + S_ENDPGM, + }; + std::vector<Summary> got = summary(code); + std::vector<std::pair<std::size_t, std::string>> found; + for (const auto& s : got) found.push_back({s.offset, s.name}); + std::vector<std::pair<std::size_t, std::string>> want = { + {0, "s_getpc_b64"}, {4, "s_add_u32"}, {12, "s_addc_u32"}, {16, "s_setpc_b64"}, {24, "s_endpgm"}, + }; + CHECK(found == want); + // Through other registers (a handover to another stage): the path ends. + CHECK_EQ(summary({0xBE80'2018, S_ENDPGM}).size(), 1u); +} + +TEST(gfx10_follows_far_jumps_backward) { + // The compiler's backward far jump adds a negative offset: the low dword as a 32-bit literal, + // the high dword as -1 with the carry. + std::vector<std::uint32_t> code = { + sopp(0x02, 1), // s_branch -> 8, past the jump target + S_ENDPGM, // the far jump's target: only it reaches here + 0xBE88'1F00, // s_getpc_b64 s[8:9] + 0x8008'FF08, 0xFFFF'FFF8, // s_add_u32 s8, s8, -8 -> 12 - 8 = 4 + 0x8209'C109, // s_addc_u32 s9, s9, -1 + 0xBE80'2008, // s_setpc_b64 s[8:9] + }; + std::vector<std::pair<std::size_t, std::string>> found; + for (const auto& s : summary(code)) found.push_back({s.offset, s.name}); + std::vector<std::pair<std::size_t, std::string>> want = { + {0, "s_branch"}, {4, "s_endpgm"}, {8, "s_getpc_b64"}, {12, "s_add_u32"}, {20, "s_addc_u32"}, {24, "s_setpc_b64"}, + }; + CHECK(found == want); +} + +TEST(gfx10_rejects_bad_code) { + std::vector<std::uint8_t> three(3, 0); + CHECK(ERROR_OF(gfx10::decode(three)).has_value()); // size not a multiple of 4 + CHECK(ERROR_OF(gfx10::decode(bytes({sopp(0x02, 100)}))).has_value()); // branch out of range + CHECK(ERROR_OF(gfx10::decode(bytes({0xBE80'03FF}))).has_value()); // literal past the end + CHECK(ERROR_OF(gfx10::decode(bytes({0xE400'0000, 0}))).has_value()); // unknown encoding + // s_cbranch_scc0 into the literal of the s_mov_b32 at 4. + CHECK(ERROR_OF(gfx10::decode(bytes({sopp(0x04, 1), 0xBE80'03FF, S_ENDPGM, S_ENDPGM}))).has_value()); +} + +// ---------------------------------------------------------------- gfx10/opcodes.rs + +// `s_ttracedata_imm 0x1234` as LLVM's GFX10 disassembler tests have it (`gfx10_sopp.txt`: +// `0x34,0x12,0xa8,0xbf`), SOPP opcode 0x28 as in AMD's RDNA2 ISA. A thread-trace marker, which +// translation drops. +TEST(opcodes_s_ttracedata_imm_is_sopp_0x28) { + auto code = bytes({0xBFA8'1234, 0xBF81'0000}); + auto decoded = gfx10::decode(code); + CHECK(decoded[0].name() == "s_ttracedata_imm"); + CHECK(!ERROR_OF(ir::build(code, false, 1)).has_value()); +} + +// ---------------------------------------------------------------- gfx10/sp3.rs + +// Text of each instruction in `words` (a straight-line program). +std::vector<std::string> texts(std::vector<std::uint32_t> words, bool wave64) { + words.push_back(0xBF81'0000); // s_endpgm + auto insts = gfx10::decode(bytes(words)); + std::vector<std::string> out; + for (std::size_t i = 0; i + 1 < insts.size(); ++i) out.push_back(insts[i].text(wave64)); + return out; +} + +std::string one(const std::vector<std::uint32_t>& words, bool wave64) { + auto t = texts(words, wave64); + if (t.size() != 1) { + fail(__FILE__, __LINE__, "expected one instruction"); + return {}; + } + return t[0]; +} + +#define CHECK_TEXT(got, want) \ + do { \ + std::string g_ = (got); \ + if (g_ != (want)) fail(__FILE__, __LINE__, "got \"" + g_ + "\" want \"" + (want) + "\""); \ + } while (0) + +TEST(sp3_scalar) { + auto t = texts({0xBF88'0001, 0xBF8C'0070, 0xBE80'03FF, 0x1234'5678}, true); + CHECK_EQ(t.size(), 3u); + if (t.size() == 3) { + CHECK_TEXT(t[0], std::string("s_cbranch_execz label_0008")); + CHECK_TEXT(t[1], std::string("s_waitcnt vmcnt(0) & lgkmcnt(0)")); + CHECK_TEXT(t[2], std::string("s_mov_b32 s0, lit(0x12345678)")); + } + CHECK_TEXT(one({0x8782'027E}, true), std::string("s_and_b64 s[2:3], exec, s[2:3]")); + CHECK_TEXT(one({0xF408'0501, 0xFA00'0040}, true), std::string("s_load_dwordx4 s[20:23], s[2:3], 0x000040")); + CHECK_TEXT(one({0xF420'0144, 0x0400'0000}, true), std::string("s_buffer_load_dword s5, s[8:11], s2")); +} + +// `s_atc_probe` / `s_atc_probe_buffer`: SDATA is a 7-bit immediate, the buffer resource is 4 +// dwords, and GLC/DLC are not operands. Words checked with llvm-mc -mcpu=gfx1030. +TEST(sp3_atc_probe_immediate_is_not_a_register) { + struct Case { + std::vector<std::uint32_t> words; + std::string text; + gfx10::Operand data, base; + }; + using gfx10::Operand; + std::vector<Case> cases = { + {{0xF498'01C2, 0xFA00'0064}, "s_atc_probe 7, s[4:5], 0x000064", Operand::Literal(7), Operand::Scalar(4, 2)}, + {{0xF498'1FF4, 0x0A00'0001}, "s_atc_probe 0x7f, s[104:105], s5 offset:0x000001", Operand::Literal(0x7f), + Operand::Scalar(104, 2)}, + {{0xF498'0000, 0xFA00'0000}, "s_atc_probe 0, s[0:1], null", Operand::Literal(0), Operand::Scalar(0, 2)}, + {{0xF49C'01C4, 0xFA00'0020}, "s_atc_probe_buffer 7, s[8:11], 0x000020", Operand::Literal(7), + Operand::Scalar(8, 4)}, + {{0xF499'41C2, 0xFA00'0000}, "s_atc_probe 7, s[4:5], null", Operand::Literal(7), Operand::Scalar(4, 2)}, + }; + for (const Case& c : cases) { + CHECK_TEXT(one(c.words, false), c.text); + CHECK_TEXT(one(c.words, true), c.text); + auto w = c.words; + w.push_back(0xBF81'0000); + auto fields = gfx10::decode(bytes(w))[0].fields(false); + const auto* m = std::get_if<gfx10::Smem>(&fields); + CHECK(m != nullptr); + if (m) { + CHECK(m->data == c.data); + CHECK(m->base == c.base); + CHECK(m->cache == gfx10::Cache{}); + } + } +} + +TEST(sp3_lane_masks_follow_the_wave_size) { + std::vector<std::uint32_t> cmp = {0x7C08'06F0}; // v_cmp_gt_f32 with 0.5 and v3 + CHECK_TEXT(one(cmp, false), std::string("v_cmp_gt_f32 vcc_lo, 0.5, v3")); + CHECK_TEXT(one(cmp, true), std::string("v_cmp_gt_f32 vcc, 0.5, v3")); + std::vector<std::uint32_t> vop3 = {0xD401'0106, 0x0001'E501}; // v_cmp_lt_f32 to s6, |v1| < 1.0 + CHECK_TEXT(one(vop3, false), std::string("v_cmp_lt_f32 s6, abs(v1), 1.0")); + CHECK_TEXT(one(vop3, true), std::string("v_cmp_lt_f32 s[6:7], abs(v1), 1.0")); + CHECK_TEXT(one({0x0202'0480}, false), std::string("v_cndmask_b32 v1, 0, v2, vcc_lo")); + CHECK_TEXT(one({0x5006'0801}, true), std::string("v_add_co_ci_u32 v3, vcc, s1, v4, vcc")); +} + +TEST(sp3_vector_modifiers) { + CHECK_TEXT(one({0x1004'0AFF, 0x3F00'0001}, true), std::string("v_mul_f32 v2, lit(0x3f000001), v5")); + CHECK_TEXT(one({0xD54B'8004, 0x2BC0'0501}, true), std::string("v_fma_f32 v4, -v1, s2, 0.5 mul:2 clamp")); + CHECK_TEXT(one({0x7E02'16F9, 0x0605'0602}, true), std::string("v_cvt_f32_f16 v1, v2 src0_sel:WORD_1")); + CHECK_TEXT(one({0x7E06'02E9, 0x0539'7701}, true), std::string("v_mov_b32 v3, v1 dpp8:[7,6,5,4,3,2,1,0]")); + CHECK_TEXT(one({0x7E0A'02FA, 0xFF08'B106}, true), + std::string("v_mov_b32 v5, v6 quad_perm:[1,0,3,2] bound_ctrl:1")); + CHECK_TEXT(one({0xCC20'0C01, 0x2C10'0702}, true), std::string("v_fma_mix_f32 v1, -sel_hi(v2), s3, abs(v4)")); +} + +TEST(sp3_memory_and_export) { + CHECK_TEXT(one({0xE034'7010, 0x0102'0402}, true), + std::string("buffer_load_dwordx2 v[4:5], v[2:3], s[8:11], s1 idxen offen offset:16 glc")); + CHECK_TEXT(one({0xD8DC'0302, 0x0600'0001}, true), std::string("ds_read2_b32 v[6:7], v1 offset0:2 offset1:3")); + CHECK_TEXT(one({0xF800'1C0F, 0x0000'0302}, true), std::string("exp mrt0, v2, v2, v3, v3 done compr vm")); +} + +TEST(sp3_one_sided_packed_negation_is_printed) { + // Encodings from llvm-mc -mcpu=gfx1030. A source negated in both halves keeps the `-` prefix; + // one-sided bits get LLVM's suffixes. + CHECK_TEXT(one({0xCC0F'4001, 0x1A02'0702}, true), std::string("v_pk_add_f16 v1, v2, v3")); + CHECK_TEXT(one({0xCC0F'4001, 0x3A02'0702}, true), std::string("v_pk_add_f16 v1, v2, v3 neg_lo:[1,0]")); + CHECK_TEXT(one({0xCC0F'4201, 0x1A02'0702}, true), std::string("v_pk_add_f16 v1, v2, v3 neg_hi:[0,1]")); + CHECK_TEXT(one({0xCC0F'4101, 0x7A02'0702}, true), std::string("v_pk_add_f16 v1, -v2, v3 neg_lo:[0,1]")); +} + +TEST(sp3_fields_the_instruction_lacks_are_not_printed) { + // Encodings from llvm-mc -mcpu=gfx1030; s_get_waveid_in_workgroup is gfx1010 only. + CHECK_TEXT(one({0xF490'0500, 0}, true), std::string("s_memtime s[20:21]")); + CHECK_TEXT(one({0xF4A8'0140, 0}, true), std::string("s_get_waveid_in_workgroup s5")); + CHECK_TEXT(one({0xDC30'8000, 0x007D'0002}, true), std::string("global_load_dword v0, v[2:3], off")); + CHECK_TEXT(one({0xE031'1000, 0x0001'0001}, true), std::string("buffer_load_dword v1, s[4:7], s0 offen lds")); + CHECK_TEXT(one({0x7E02'02F9, 0x0005'0602}, true), std::string("v_mov_b32 v1, v2 src0_sel:WORD_1")); +} + +TEST(sp3_image_d16_data_is_packed) { + // Three f16 channels occupy two VGPRs; NSA lists the addresses. + std::vector<std::uint32_t> words = {0xF09C'070A, 0x8024'0801, 0x0000'0005}; + CHECK_TEXT(one(words, true), + std::string("image_sample_lz v[8:9], [v1,v5], s[16:23], s[4:7] dmask:0x7 dim:SQ_RSRC_IMG_2D d16")); + auto w = words; + w.push_back(0xBF81'0000); + auto fields = gfx10::decode(bytes(w))[0].fields(true); + const auto* im = std::get_if<gfx10::Image>(&fields); + CHECK(im != nullptr); + if (im) { + CHECK(im->data == gfx10::Operand::Vector(8, 2)); + CHECK_EQ(im->addr.size(), 2u); + } +} + +// ---------------------------------------------------------------- ir.rs + +using ir::Block; +using ir::Exit; +using ir::Inst; +using ir::Phi; +using ir::Program; +using ir::Reg; +using ir::Value; + +ir::Program build_words(const std::vector<std::uint32_t>& words, bool wave64) { + return ir::build(bytes(words), wave64, 256); +} + +Value input(const Program& p, Reg reg) { + for (const auto& i : p.inputs) { + if (i.first == reg) return i.second; + } + fail(__FILE__, __LINE__, "input " + reg.debug()); + return Value{0xFFFF'FFFF}; +} + +// `if (v0 < s0) { ... }` whose body changes s6: `body` are its words, `after` what follows the join. +Program skip(const std::vector<std::uint32_t>& body, const std::vector<std::uint32_t>& after) { + std::vector<std::uint32_t> w = { + 0xBE94'0306, // s_mov_b32 s20, s6 + 0x7D88'0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C'246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88'0000u | std::uint32_t(body.size()), // s_cbranch_execz past the body + }; + w.insert(w.end(), body.begin(), body.end()); + w.push_back(0xBEFE'040C); // s_mov_b64 exec, s[12:13] + w.insert(w.end(), after.begin(), after.end()); + w.push_back(S_ENDPGM); + return build_words(w, true); +} + +std::size_t skips(const Program& p) { + std::size_t n = 0; + for (const Block& b : p.blocks) { + if (!b.insts.empty() && b.insts.back().name() == "s_cbranch_execz") ++n; + } + return n; +} + +TEST(ir_a_skip_is_left_out_when_the_scalars_it_changes_come_back_or_are_not_read) { + const std::uint32_t SET = 0xBE86'0385; // s_mov_b32 s6, 5 + const std::uint32_t USE = 0x7E02'0206; // v_mov_b32 v1, s6 + const std::uint32_t BACK = 0xBE86'0314; // s_mov_b32 s6, s20 + const std::uint32_t READ = 0x7E04'0206; // v_mov_b32 v2, s6 + // s6 is changed in the body and read after the join: the branch stays + Program kept = skip({SET, USE}, {READ}); + CHECK_EQ(skips(kept), 1u); + CHECK(!ir::without_skips(kept, false)); + CHECK(!ir::without_skips(kept, true)); + // ... put back by a copy of what it held (as a scalar parked in a VGPR lane comes back): every + // lane may walk the body + Program back = skip({SET, USE, BACK}, {READ}); + CHECK(!ir::without_skips(back, false)); + auto b = ir::without_skips(back, true); + CHECK(b && skips(*b) == 0); + // ... or not read after the join at all + Program unread = skip({SET, USE}, {}); + auto u0 = ir::without_skips(unread, false); + CHECK(u0 && skips(*u0) == 0); + auto u1 = ir::without_skips(unread, true); + CHECK(u1 && skips(*u1) == 0); + // ... or read only by a restore of EXEC that nothing uses before the next one + // (s_mov_b64 exec, s[6:7]; s_mov_b64 exec, s[12:13]; v_mov_b32 v2, s0) + Program idle = skip({SET, USE}, {0xBEFE'0406, 0xBEFE'040C, 0x7E04'0200}); + CHECK(!ir::without_skips(idle, false)); + auto i1 = ir::without_skips(idle, true); + CHECK(i1 && skips(*i1) == 0); +} + +TEST(ir_joins_get_phis_only_where_values_differ) { + std::vector<std::uint32_t> code = { + 0xBF06'0100, // s_cmp_eq_u32 s0, s1 + 0xBF85'0001, // s_cbranch_scc1 -> 12 + 0xBE82'0380, // s_mov_b32 s2, 0 + 0x7E00'0202, // 12: v_mov_b32 v0, s2 + 0x7E02'0200, // v_mov_b32 v1, s0 + S_ENDPGM, + }; + for (bool wave64 : {false, true}) { + Program p = build_words(code, wave64); + CHECK_EQ(p.blocks.size(), 3u); + if (p.blocks.size() != 3) continue; + const Block &b0 = p.blocks[0], &b1 = p.blocks[1], &b2 = p.blocks[2]; + CHECK(b0.exit == Exit::Branch(2, 1)); + CHECK(b1.exit == Exit::Jump(2)); + CHECK((b2.preds == std::vector<std::size_t>{0, 1})); + CHECK(b0.insts[1].read(Reg::Scc) == b0.insts[0].write(Reg::Scc)); + + // s2 differs per path; s0, EXEC, v0 and v1 do not. + CHECK_EQ(b2.phis.size(), 1u); + if (b2.phis.size() != 1) continue; + const Phi& phi = b2.phis[0]; + CHECK(phi.reg == Reg::S(2)); + CHECK((phi.args == std::vector<Value>{input(p, Reg::S(2)), *b1.insts[0].write(Reg::S(2))})); + CHECK_EQ(b2.insts.size(), 3u); + if (b2.insts.size() != 3) continue; + const Inst &mov0 = b2.insts[0], &mov1 = b2.insts[1], &end = b2.insts[2]; + CHECK(mov0.read(Reg::S(2)) == phi.value); + CHECK(mov1.read(Reg::S(0)) == input(p, Reg::S(0))); + // The old v1 is read: lanes outside EXEC keep it. + CHECK(mov1.read(Reg::V(1)) == input(p, Reg::V(1))); + CHECK(mov1.read(Reg::S(ir::EXEC)) == input(p, Reg::S(ir::EXEC))); + CHECK_EQ(mov1.read(Reg::S(ir::EXEC + 1)).has_value(), wave64); + CHECK(end.name() == "s_endpgm"); + CHECK(b2.exit == Exit::End); + } +} + +TEST(ir_in_place_scalar_ops_read_their_destination) { + Program p = build_words( + { + 0xBE8D'1D94, // s_bitset1_b32 s13, 20 + 0xB78E'0010, // s_addk_i32 s14, 0x10 + 0xBE8F'0380, // s_mov_b32 s15, 0 + S_ENDPGM, + }, + false); + const auto& insts = p.blocks[0].insts; + CHECK_EQ(insts.size(), 4u); + if (insts.size() != 4) return; + CHECK(insts[0].read(Reg::S(13)) == input(p, Reg::S(13))); + CHECK(insts[1].read(Reg::S(14)) == input(p, Reg::S(14))); + CHECK(insts[2].read(Reg::S(15)) == std::nullopt); +} + +TEST(ir_loops_carry_values_through_phis) { + Program p = build_words( + { + 0xBE80'0380, // s_mov_b32 s0, 0 + 0x8000'8100, // 4: s_add_u32 s0, s0, 1 + 0xBF07'8400, // s_cmp_lg_u32 s0, 4 + 0xBF85'FFFD, // s_cbranch_scc1 -> 4 + S_ENDPGM, + }, + true); + CHECK(p.inputs.empty()); + CHECK_EQ(p.blocks.size(), 3u); + if (p.blocks.size() != 3) return; + const Block &b0 = p.blocks[0], &b1 = p.blocks[1], &b2 = p.blocks[2]; + CHECK((b1.preds == std::vector<std::size_t>{0, 1})); + CHECK(b1.exit == Exit::Branch(1, 2)); + CHECK_EQ(b1.phis.size(), 1u); + if (b1.phis.size() != 1) return; + const Phi& phi = b1.phis[0]; + const Inst& add = b1.insts[0]; + CHECK(phi.reg == Reg::S(0)); + CHECK((phi.args == std::vector<Value>{*b0.insts[0].write(Reg::S(0)), *add.write(Reg::S(0))})); + CHECK(add.read(Reg::S(0)) == phi.value); + CHECK(b1.insts[1].read(Reg::S(0)) == add.write(Reg::S(0))); + CHECK(b2.insts[0].name() == "s_endpgm"); +} + +TEST(ir_drops_scheduling_and_follows_far_jumps) { + Program p = build_words( + { + 0xBF80'0000, // s_nop 0 + 0xBE88'1F00, // s_getpc_b64 s[8:9] + 0x8008'FF08, 20, // s_add_u32 s8, s8, 20 -> 8 + 20 = 28 + 0x8209'8009, // s_addc_u32 s9, s9, 0 + 0xBE80'2008, // s_setpc_b64 s[8:9] + 0xFFFF'FFFF, // not code + S_ENDPGM, + }, + false); + std::vector<std::string> names; + for (const Inst& i : p.blocks[0].insts) names.push_back(std::string(i.name())); + CHECK((names == std::vector<std::string>{"s_getpc_b64", "s_add_u32", "s_addc_u32", "s_setpc_b64"})); + CHECK(p.blocks[0].exit == Exit::Jump(1)); + CHECK_EQ(p.blocks[1].offset, 28u); + // s_addc_u32 reads the carry s_add_u32 left in SCC. + const auto& i = p.blocks[0].insts; + CHECK(i[2].read(Reg::Scc) == i[1].write(Reg::Scc)); +} + +TEST(ir_reports_what_it_cannot_express) { + auto code = bytes({0xBE80'2E01, S_ENDPGM}); // s_movrels_b32 s0, s1 + auto e = ERROR_OF(ir::build(code, false, 256)); + CHECK(e == ShaderError::unsupported(0, "s_movrels_b32")); + if (e) CHECK_TEXT(e->to_string(), std::string("GFX10 code at 0x0: s_movrels_b32 is not supported")); +} + +TEST(ir_relative_vgpr_access_spans_up_to_the_vgpr_count) { + auto code = bytes({ + 0x7E04'8501, // v_movreld_b32 v2, v1: v[2 + m0] = v1 + 0x7E00'8704, // v_movrels_b32 v0, v4: v0 = v[4 + m0] + S_ENDPGM, + }); + Program p = ir::build(code, false, 6); + CHECK_EQ(p.blocks[0].insts.size(), 3u); + if (p.blocks[0].insts.size() != 3) return; + const Inst &movreld = p.blocks[0].insts[0], &movrels = p.blocks[0].insts[1]; + auto vgprs = [](const std::vector<std::pair<Reg, Value>>& regs) { + std::vector<int> out; + for (const auto& r : regs) { + if (r.first.is_v()) out.push_back(r.first.n); + } + return out; + }; + CHECK((vgprs(movreld.writes) == std::vector<int>{2, 3, 4, 5})); + // v1 is the source; v2-v5 are read for the lanes and indices not written. + CHECK((vgprs(movreld.reads) == std::vector<int>{1, 2, 3, 4, 5})); + CHECK(movreld.read(Reg::S(ir::M0)).has_value()); + CHECK((vgprs(movrels.writes) == std::vector<int>{0})); + CHECK((vgprs(movrels.reads) == std::vector<int>{4, 5, 0})); + CHECK(movrels.read(Reg::V(4)) == movreld.write(Reg::V(4))); + CHECK(ERROR_OF(ir::build(code, false, 4)).has_value()); // v4 is past 4 VGPRs +} + +constexpr std::uint32_t s_branch(std::int16_t simm16) { return 0xBF82'0000u | std::uint16_t(simm16); } +constexpr std::uint32_t s_cbranch_scc1(std::int16_t simm16) { return 0xBF85'0000u | std::uint16_t(simm16); } + +TEST(ir_reverse_order_diamond_chain_eliminates_trivial_phis) { + const std::size_t LAYERS = 4096; + std::vector<std::uint32_t> reverse = { + 0xBE81'0381, // s_mov_b32 s1, 1 + 0xBE82'0382, // s_mov_b32 s2, 2 + s_branch(std::int16_t((LAYERS - 1) * 4)), + }; + for (std::size_t k = 0; k < LAYERS; ++k) { + reverse.insert(reverse.end(), { + 0xBF06'0201, // s_cmp_eq_u32 s1, s2 + s_cbranch_scc1(1), + 0xBF80'0000, // s_nop 0 + k == 0 ? s_branch(std::int16_t(LAYERS * 4 - 4)) : s_branch(-8), + }); + } + reverse.insert(reverse.end(), {0x8000'0201, S_ENDPGM}); // s_add_u32 s0, s1, s2 + + std::vector<std::uint32_t> forward = { + 0xBE81'0381, // s_mov_b32 s1, 1 + 0xBE82'0382, // s_mov_b32 s2, 2 + s_branch(0), + }; + for (std::size_t k = 0; k < LAYERS; ++k) { + forward.insert(forward.end(), {0xBF06'0201, s_cbranch_scc1(1), 0xBF80'0000, s_branch(0)}); + } + forward.insert(forward.end(), {0x8000'0201, S_ENDPGM}); + + Program rev = build_words(reverse, false); + Program fwd = build_words(forward, false); + CHECK(rev.inputs.empty()); + CHECK(fwd.inputs.empty()); + for (const Block& b : rev.blocks) CHECK(b.phis.empty()); + for (const Block& b : fwd.blocks) CHECK(b.phis.empty()); + CHECK_EQ(rev.blocks.size(), fwd.blocks.size()); + + for (const Program* p : {&rev, &fwd}) { + Value s1 = *p->blocks[0].insts[0].write(Reg::S(1)); + Value s2 = *p->blocks[0].insts[1].write(Reg::S(2)); + const Block& exit = p->blocks.back(); + CHECK(exit.insts[0].name() == "s_add_u32"); + CHECK(exit.insts[0].read(Reg::S(1)) == s1); + CHECK(exit.insts[0].read(Reg::S(2)) == s2); + } +} + +TEST(ir_remove_trivial_phis_compresses_reverse_chain_in_bounded_steps) { + const std::size_t CHAIN = 4096; + Inst tmpl = build_words({0xBE80'0380, S_ENDPGM}, false).blocks[0].insts[0]; + tmpl.writes.clear(); + std::vector<Block> blocks; + blocks.reserve(CHAIN); + for (std::size_t k = 0; k < CHAIN; ++k) { + Value v1{std::uint32_t(2 + 2 * k)}, v2{std::uint32_t(3 + 2 * k)}; + Value n1{0}, n2{1}; + if (k + 1 < CHAIN) { + n1 = Value{std::uint32_t(2 + 2 * (k + 1))}; + n2 = Value{std::uint32_t(3 + 2 * (k + 1))}; + } + Inst inst = tmpl; + inst.reads = {{Reg::S(1), v1}, {Reg::S(2), v2}}; + Block b; + b.offset = k * 4; + b.phis = {Phi{Reg::S(1), v1, {n1, n1}}, Phi{Reg::S(2), v2, {n2, n2}}}; + b.insts = {inst}; + b.exit = Exit::End; + blocks.push_back(std::move(b)); + } + std::size_t steps = ir::detail::remove_trivial_phis_steps(blocks, std::uint32_t(2 + 2 * CHAIN)); + std::vector<std::pair<Reg, Value>> want = {{Reg::S(1), Value{0}}, {Reg::S(2), Value{1}}}; + bool all_empty = true, all_reads = true; + for (const Block& b : blocks) { + all_empty = all_empty && b.phis.empty(); + all_reads = all_reads && b.insts[0].reads == want; + } + CHECK(all_empty); + CHECK(all_reads); + if (!(steps < 100'000)) fail(__FILE__, __LINE__, "steps = " + std::to_string(steps)); +} + +TEST(ir_non_trivial_phis_preserve_compressed_representatives) { + const std::size_t LAYERS = 4; + std::vector<std::uint32_t> code = { + 0xBE81'0381, // s_mov_b32 s1, 1 + 0xBE82'0382, // s_mov_b32 s2, 2 + 0xBF06'8000, // s_cmp_eq_u32 s0, 0 + s_cbranch_scc1(std::int16_t(2 + (LAYERS - 1) * 4)), + 0xBE81'0383, // s_mov_b32 s1, 3 + s_branch(std::int16_t(LAYERS * 4)), + }; + for (std::size_t k = 0; k < LAYERS; ++k) { + code.insert(code.end(), {0xBF06'0201, s_cbranch_scc1(1), 0xBF80'0000, + k == 0 ? s_branch(std::int16_t(LAYERS * 4 - 4)) : s_branch(-8)}); + } + code.insert(code.end(), {0x8000'0201, S_ENDPGM}); // s_add_u32 s0, s1, s2 + + Program p = build_words(code, false); + Value entry_s1 = *p.blocks[0].insts[0].write(Reg::S(1)); + Value entry_s2 = *p.blocks[0].insts[1].write(Reg::S(2)); + Value arm_s1 = *p.blocks[1].insts[0].write(Reg::S(1)); + const Block& merge = p.blocks.back(); + for (std::size_t b = 0; b + 1 < p.blocks.size(); ++b) CHECK(p.blocks[b].phis.empty()); + CHECK_EQ(merge.phis.size(), 1u); + if (merge.phis.size() == 1) { + const Phi& phi = merge.phis[0]; + CHECK(phi.reg == Reg::S(1)); + CHECK((phi.args == std::vector<Value>{arm_s1, entry_s1})); + CHECK(merge.insts[0].read(Reg::S(1)) == phi.value); + CHECK(merge.insts[0].read(Reg::S(2)) == entry_s2); + } + + std::vector<std::uint32_t> loop_code = { + 0xBE81'0381, // s_mov_b32 s1, 1 + 0xBE82'0382, // s_mov_b32 s2, 2 + s_branch(std::int16_t((LAYERS - 1) * 4)), + }; + for (std::size_t k = 0; k < LAYERS; ++k) { + loop_code.insert(loop_code.end(), {0xBF06'0201, s_cbranch_scc1(1), 0xBF80'0000, + k == 0 ? s_branch(std::int16_t(LAYERS * 4 - 4)) : s_branch(-8)}); + } + loop_code.insert(loop_code.end(), { + 0x8001'0201, // s_add_u32 s1, s1, s2 + 0xBF07'8401, // s_cmp_lg_u32 s1, 4 + s_cbranch_scc1(-3), + 0x8000'0201, // s_add_u32 s0, s1, s2 + S_ENDPGM, + }); + + Program lp = build_words(loop_code, false); + Value lp_s1 = *lp.blocks[0].insts[0].write(Reg::S(1)); + Value lp_s2 = *lp.blocks[0].insts[1].write(Reg::S(2)); + const Block& header = lp.blocks[lp.blocks.size() - 2]; + const Block& exit = lp.blocks.back(); + for (std::size_t b = 0; b + 2 < lp.blocks.size(); ++b) CHECK(lp.blocks[b].phis.empty()); + CHECK(exit.phis.empty()); + CHECK_EQ(header.phis.size(), 1u); + if (header.phis.size() == 1) { + const Phi& loop_phi = header.phis[0]; + Value next_s1 = *header.insts[0].write(Reg::S(1)); + CHECK(loop_phi.reg == Reg::S(1)); + CHECK((loop_phi.args == std::vector<Value>{lp_s1, next_s1})); + CHECK(header.insts[0].read(Reg::S(1)) == loop_phi.value); + CHECK(header.insts[0].read(Reg::S(2)) == lp_s2); + CHECK(exit.insts[0].read(Reg::S(1)) == next_s1); + CHECK(exit.insts[0].read(Reg::S(2)) == lp_s2); + } +} + +} // namespace + +int main(int argc, char** argv) { + if (argc > 1 && std::strcmp(argv[1], "--list") == 0) { + for (const auto& t : registry()) std::printf("%s\n", t.name); + return 0; + } + int ran = 0; + for (const auto& t : registry()) { + if (argc > 1 && std::strcmp(argv[1], t.name) != 0) continue; + ++ran; + int before = failures; + try { + t.fn(); + } catch (const std::exception& e) { + fail(__FILE__, __LINE__, std::string(t.name) + " threw: " + e.what()); + } + std::printf("%s %s\n", failures == before ? "PASS" : "FAIL", t.name); + } + if (ran == 0) { + std::fprintf(stderr, "no test named %s\n", argc > 1 ? argv[1] : "(any)"); + return 2; + } + return failures == 0 ? 0 : 1; +} diff --git a/tests/x2w_shader/emit/atomic_test.cpp b/tests/x2w_shader/emit/atomic_test.cpp new file mode 100644 index 0000000000..38335a8534 --- /dev/null +++ b/tests/x2w_shader/emit/atomic_test.cpp @@ -0,0 +1,122 @@ +// Port of the test in the upstream Rust module emit/mod.rs `mod atomic_tests` (rs:2408). +// +// A test that throws (a Rust panic or `.unwrap()` of an error) fails; dxil.dll checks the modules +// where it is installed, as in Rust. + +#include <array> +#include <cstdint> +#include <cstdio> +#include <exception> +#include <optional> +#include <span> +#include <stdexcept> +#include <string> +#include <vector> + +#include "test_util.h" +#include "x2w_shader/dxbc.h" +#include "x2w_shader/emit/emit.h" +#include "x2w_shader/emit/lower.h" +#include "x2w_shader/emit/validator.h" +#include "x2w_shader/error.h" +#include "x2w_shader/io.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/native.h" +#include "x2w_shader/resource.h" +#include "x2w_shader/structure.h" + +namespace vs = x2w::vs; +using vs::dxbc::Container; +using vs::dxbc::FourCC; +using vs::native::ComputeIo; +using vs::native::HwStage; +using vs::native::NativeProgram; +using vs::native::RootParam; +using vs::native::RootType; +using vs::validator::Validator; + +namespace { + +std::vector<std::uint8_t> le_bytes(std::span<const std::uint32_t> words) { + std::vector<std::uint8_t> code; + code.reserve(words.size() * 4); + for (std::uint32_t w : words) + for (int k = 0; k < 4; ++k) code.push_back(static_cast<std::uint8_t>(w >> (8 * k))); + return code; +} + +// ---- rs:2413 ------------------------------------------------------------------------------------ +void heap_texture_atomic_widths() { + // A synthetic compute shader loads a 2D UAV from a root table, compares or adds at (0, 0), then + // uses the returned register(s). + struct Case { + std::uint32_t opcode; + std::uint32_t mask; + bool wide; + }; + for (const Case& k : {Case{16, 3, false}, Case{16, 15, true}, Case{17, 1, false}, Case{17, 3, true}}) { + const std::uint32_t opcode = k.opcode; + const std::uint32_t mask = k.mask; + const bool wide = k.wide; + const std::array<std::uint32_t, 14> words = { + 0xBE81'0380u, // s_mov_b32 s1, 0 (table address high) + 0xF40C'0200, + 0xFA00'0000, // s_load_dwordx8 s[8:15], s[0:1], 0 + 0x7E00'0280, + 0x7E02'0280, // v0, v1 = coordinates + 0x7E04'0281, + 0x7E06'0282, + 0x7E08'0283, + 0x7E0A'0284, // v2..v5 = 1..4 + 0xF000'2008u | opcode << 18 | mask << 8, + 0x0002'0200, + // Use the old value in a second atomic at the same location. + 0xF044'0008u | (wide ? 3u : 1u) << 8, + 0x0002'0200, + 0xBF81'0000, + }; + NativeProgram native; + native.stage = HwStage::Cs; + native.wave64 = false; + native.vgprs = 6; + native.layout = {RootParam{RootType::Table(), 0, 1, 0, 0, 0}}; + native.io = ComputeIo{2, {32, 1, 1}}; + native.code = le_bytes(words); + const vs::ir::Program p = vs::ir::build(native.code, false, native.vgprs); + const std::vector<std::uint8_t> bytes = vs::dxbc::build({}); + // emit's arguments in Rust order. + const Container c = Container::parse(bytes); + const vs::structure::Structured st = vs::structure::structure(p); + const vs::io::Io io = vs::io::raise(p, native); + const vs::resource::Resources res = vs::resource::track(p, native.layout, native.stage, nullptr); + const vs::HostShader shader = vs::emit(c, native, p, st, io, res); + const Container container = Container::parse(shader.dxil); + const vs::dxbc::Part* sfi0 = container.part(FourCC::SFI0); + if (!sfi0) throw std::logic_error("no SFI0 part"); + if (sfi0->data.size() != 8) throw std::logic_error("SFI0 is not 8 bytes"); + std::uint64_t features = 0; + for (std::size_t b = 0; b < 8; ++b) features |= std::uint64_t(sfi0->data[b]) << (8 * b); + const std::uint64_t required = 0x1040'8000; // heap atomics, typed atomics, Int64Ops + CHECK((features & required) == (wide ? required : 0)); + if (std::optional<Validator> v = Validator::load(Validator::default_path())) { + std::vector<std::uint8_t> copy = shader.dxil; + if (std::optional<std::string> e = v->validate(copy)) { + std::fprintf(stderr, " validator: %s\n", e->c_str()); + CHECK(!e); + } + } + } +} + +} // namespace + +int main() { + x2w::vs::lower::test::set_dump_name("emit__atomic_tests__heap_texture_atomic_widths"); + try { + heap_texture_atomic_widths(); + } catch (const std::exception& e) { + std::fprintf(stderr, "heap_texture_atomic_widths: panicked: %s\n", e.what()); + ++test_util::failures(); + } + return test_util::finish("atomic_test"); +} diff --git a/tests/x2w_shader/emit/barycentric_test.cpp b/tests/x2w_shader/emit/barycentric_test.cpp new file mode 100644 index 0000000000..829f71e7f7 --- /dev/null +++ b/tests/x2w_shader/emit/barycentric_test.cpp @@ -0,0 +1,594 @@ +// Port of the tests in the upstream Rust module emit/mod.rs `mod barycentric_tests` (rs:2491), in Rust order. +// +// Each Rust #[test] is a function; main runs them all, each under its own dump name +// ("emit__barycentric_tests__<name>"). A test that throws (a Rust panic or `.unwrap()` of an error) +// fails and the others still run. first_half_values_render_on_hardware_and_warp (Rust +// #[cfg(windows)]) skips, and says so, without an SM 6.6 device with barycentrics. The upstream +// valu_tests::ONE_AT_A_TIME lock is not needed: the tests run one after another on one thread. + +#include <windows.h> + +#include <algorithm> +#include <array> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <exception> +#include <optional> +#include <span> +#include <stdexcept> +#include <string> +#include <utility> +#include <vector> + +#include "test_util.h" +#include "x2w_shader/dxbc.h" +#include "x2w_shader/emit/bitcode.h" +#include "x2w_shader/emit/container.h" +#include "x2w_shader/emit/emit.h" +#include "x2w_shader/emit/host.h" +#include "x2w_shader/emit/lower.h" +#include "x2w_shader/emit/shader.h" +#include "x2w_shader/emit/signature.h" +#include "x2w_shader/emit/validator.h" +#include "x2w_shader/error.h" +#include "x2w_shader/io.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/native.h" +#include "x2w_shader/resource.h" +#include "x2w_shader/structure.h" + +namespace vs = x2w::vs; +using vs::HostShader; +using vs::ShaderError; +using vs::container::SigElement; +using vs::dxbc::Bytes; +using vs::dxbc::Container; +using vs::dxbc::FourCC; +using vs::native::HwStage; +using vs::native::NativeProgram; +using vs::native::PsInput; +using vs::native::PsIo; +using vs::native::Usage; +using vs::validator::Validator; + +#define CHECK_MSG(expr, msg) \ + do { \ + const bool check_ok_ = static_cast<bool>(expr); \ + if (!check_ok_) std::fprintf(stderr, " %s\n", std::string(msg).c_str()); \ + ::test_util::check(check_ok_, #expr, __FILE__, __LINE__); \ + } while (0) + +namespace { + +std::vector<std::uint8_t> le_bytes(std::span<const std::uint32_t> words) { + std::vector<std::uint8_t> code; + code.reserve(words.size() * 4); + for (std::uint32_t w : words) + for (int k = 0; k < 4; ++k) code.push_back(static_cast<std::uint8_t>(w >> (8 * k))); + return code; +} + +// Rust `.unwrap()` of a Result<_, ShaderError>: the error is a panic. +template <class F> +auto unwrap(F&& f) -> decltype(f()) { + try { + return f(); + } catch (const ShaderError& e) { + throw std::logic_error("called `Result::unwrap()` on an `Err` value: " + e.to_string()); + } +} + +Bytes part_data(const Container& c, FourCC fourcc) { + const vs::dxbc::Part* p = c.part(fourcc); + if (!p) throw std::logic_error("no " + fourcc.to_string() + " part"); + return p->data; +} + +// `haystack.windows(needle.len()).any(|w| w == needle)` / `.position(..)`. +std::optional<std::size_t> find_window(Bytes haystack, std::span<const std::uint8_t> needle) { + if (needle.size() > haystack.size()) return std::nullopt; + for (std::size_t at = 0; at + needle.size() <= haystack.size(); ++at) + if (std::equal(needle.begin(), needle.end(), haystack.begin() + at)) return at; + return std::nullopt; +} + +std::string describe(const std::vector<SigElement>& elements) { + std::string s = "["; + for (const SigElement& e : elements) { + s += "{" + e.name + " index " + std::to_string(e.index) + " kind " + std::to_string(e.kind) + " row " + + (e.row ? std::to_string(*e.row) : std::string("None")) + " col " + std::to_string(e.col) + + " cols " + std::to_string(e.cols) + "} "; + } + return s + "]"; +} + +// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER. +constexpr std::uint32_t PERSP_CENTER = 1u << 1; +constexpr std::uint32_t LINEAR_CENTER = 1u << 5; + +// `exp mrt0, v<r>, v<r>, v<r>, v<r> done vm`. +std::array<std::uint32_t, 2> exp_mrt0(std::uint32_t r) { return {0xF800'180Fu, r * 0x0101'0101u}; } + +// VOP2 `v_add_f32 v<dst>, v<a>, v<b>`. +std::uint32_t v_add_f32(std::uint32_t dst, std::uint32_t a, std::uint32_t b) { + return 3u << 25 | dst << 17 | b << 9 | (256 + a); +} + +SigElement element(const char* name, std::uint8_t kind, std::uint32_t row) { + SigElement e; + e.name = name; + e.index = 0; + e.kind = kind; + e.comp = 9; + e.interp = 0; + e.row = row; + e.col = 0; + e.cols = 4; + e.usage = 0; + e.half = false; + return e; +} + +// Translates a pixel program with these input signature elements and one float4 TEXCOORD0 +// attribute (attr 0, row 0) in the stage data. Throws ShaderError (Rust `?`). +HostShader pixel_with_inputs(std::span<const std::uint32_t> words, std::uint32_t input_addr, + std::span<const SigElement> inputs) { + NativeProgram native; + native.stage = HwStage::Ps; + native.wave64 = false; + native.vgprs = 8; + PsInput in; + in.usage = Usage::Generic(); + in.row = 0; + in.mask = 0b1111; + in.attr = 0; + in.flat = false; + in.fp16 = false; + in.pack2 = false; + in.row2 = 0; + PsIo io_data; + io_data.inputs = {in}; + io_data.input_addr = input_addr; + io_data.db_shader_control = 0; + native.io = io_data; + native.code = le_bytes(words); + SigElement target = element("SV_Target", 16, 0); + target.usage = 15; + const std::vector<std::uint8_t> isg1 = vs::container::signature(inputs, true); + const std::vector<SigElement> outs = {target}; + const std::vector<std::uint8_t> osg1 = vs::container::signature(outs, false); + const std::vector<std::uint8_t> bytes = vs::dxbc::build({{FourCC::ISG1, isg1}, {FourCC::OSG1, osg1}}); + const Container c = unwrap([&] { return Container::parse(bytes); }); + const std::vector<std::uint8_t> code = native.patched_code(); + const vs::ir::Program p = vs::ir::build(code, native.wave64, native.vgprs); + const vs::resource::Resources res = vs::resource::track(p, native.layout, native.stage, nullptr); + const vs::io::Io io = vs::io::raise(p, native); + const vs::structure::Structured st = vs::structure::structure(p); + return vs::emit(c, native, p, st, io, res); +} + +// Translates a pixel program with the input VGPRs `input_addr` enables and one float4 TEXCOORD0 +// attribute (attr 0, row 0). Throws ShaderError. +HostShader pixel(std::span<const std::uint32_t> words, std::uint32_t input_addr) { + const std::array<SigElement, 1> inputs = {element("TEXCOORD", 0, 0)}; + return pixel_with_inputs(words, input_addr, inputs); +} + +// The translation's `SFI0` features and `ISG1` rows. +std::pair<std::uint64_t, std::vector<SigElement>> parts(const HostShader& shader) { + const Container c = unwrap([&] { return Container::parse(shader.dxil); }); + const Bytes sfi0 = part_data(c, FourCC::SFI0); + if (sfi0.size() != 8) throw std::logic_error("SFI0 is not 8 bytes"); + std::uint64_t features = 0; + for (std::size_t b = 0; b < 8; ++b) features |= std::uint64_t(sfi0[b]) << (8 * b); + std::vector<SigElement> inputs = unwrap([&] { return vs::signature(part_data(c, FourCC::ISG1)); }); + return {features, std::move(inputs)}; +} + +void validate(const HostShader& shader) { + std::optional<Validator> v = Validator::load(Validator::default_path()); + if (!v) return; + std::vector<std::uint8_t> copy = shader.dxil; + if (std::optional<std::string> e = v->validate(copy)) CHECK_MSG(!e, "validator: " + *e); +} + +// The `PSV0` interpolation mode of TEXCOORD0 (row 0, x-w, float). +std::uint8_t texcoord_mode(const HostShader& shader) { + const Container c = unwrap([&] { return Container::parse(shader.dxil); }); + const Bytes psv = part_data(c, FourCC::PSV0); + const std::array<std::uint8_t, 5> row = {1, 0, 0x44, 0, 3}; + const std::optional<std::size_t> at = find_window(psv, row); + if (!at) throw std::logic_error("called `Option::unwrap()` on a `None` value: no TEXCOORD0 row in PSV0"); + if (*at + 5 >= psv.size()) throw std::logic_error("PSV0 ends in the TEXCOORD0 row"); + return psv[*at + 5]; +} + +constexpr std::uint32_t S_ENDPGM = 0xBF81'0000; + +std::size_t count_barycentrics(const std::vector<SigElement>& inputs) { + return static_cast<std::size_t>( + std::count_if(inputs.begin(), inputs.end(), [](const SigElement& e) { return e.kind == 28; })); +} + +// ---- rs:2569 ------------------------------------------------------------------------------------ +void an_unused_packed_input_matches_its_provoking_vertex_sibling() { + const auto [e0, e1] = exp_mrt0(3); + // v_interp_mov_f32 v3, p0, attr0.z followed by exp mrt0. + const std::array<std::uint32_t, 4> words = {0xC80E'0202u, e0, e1, 0xBF81'0000}; + SigElement xy = element("TEXCOORD", 0, 0); + xy.cols = 2; + SigElement zw = element("NORMAL", 0, 0); + zw.col = 2; + zw.cols = 2; + const std::array<SigElement, 2> inputs = {xy, zw}; + const HostShader shader = unwrap([&] { return pixel_with_inputs(words, PERSP_CENTER, inputs); }); + const Container c = unwrap([&] { return Container::parse(shader.dxil); }); + const Bytes psv = part_data(c, FourCC::PSV0); + for (std::uint8_t columns : {std::uint8_t{0x42}, std::uint8_t{0x62}}) { + const std::array<std::uint8_t, 6> record = {1, 0, columns, 0, 3, 1}; + CHECK(find_window(psv, record).has_value()); + } + const Bytes in = part_data(c, FourCC::ISG1); + if (in.size() <= 8 + 32 + 25) throw std::logic_error("ISG1 shorter than two rows"); + CHECK(in[8 + 25] == 0); + CHECK(in[8 + 32 + 25] == 4); + validate(shader); +} + +// ---- rs:2588 ------------------------------------------------------------------------------------ +// A pixel program's first-lane loop (no table entry in it, so not a waterfall the tracker knows) +// asks for helper lanes, which is valid DXIL (upstream #946's program). +void a_pixel_first_lane_loop_serves_helper_lanes() { + const std::array<std::uint32_t, 16> words = { + 0xD765'0000u, 0x0001'00C1, // v_mbcnt_lo_u32_b32 v0, -1, 0 + 0x7E02'0280, // v_mov_b32 v1, 0 + 0xBE97'037E, // s_mov_b32 s23, exec_lo + 0x7E18'0500, // v_readfirstlane_b32 s12, v0 + 0x7D84'000C, // v_cmp_eq_u32 vcc, s12, v0 + 0xBE95'3C6A, // s_and_saveexec_b32 s21, vcc_lo + 0xBF80'0000, // s_nop 0 + 0x7E02'02FF, 0x3F80'0000, // v_mov_b32 v1, 1.0 + 0x897E'157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89'FFF8, // s_cbranch_execnz loop + 0xBEFE'0317, // s_mov_b32 exec_lo, s23 + 0xF800'180F, 0x0101'0101, // exp mrt0 v1 v1 v1 v1 done vm + 0xBF81'0000, // s_endpgm + }; + const HostShader shader = unwrap([&] { return pixel(words, 0); }); + validate(shader); +} + +// ---- rs:2634 ------------------------------------------------------------------------------------ +// Custom interpolation reads I and J (v0, v1 with PERSP_CENTER) as plain floats: they are channels +// y and z of `SV_Barycentrics`, the weights of vertices 1 and 2. +void barycentrics_read_as_values_are_sv_barycentrics() { + const auto [e0, e1] = exp_mrt0(2); + const std::array<std::uint32_t, 4> words = {v_add_f32(2, 0, 1), e0, e1, 0xBF81'0000}; + const HostShader shader = unwrap([&] { return pixel(words, PERSP_CENTER); }); + const auto [features, inputs] = parts(shader); + CHECK_MSG((features & 0x2'0000) != 0, "no Barycentrics feature"); + std::vector<const SigElement*> bary; + for (const SigElement& e : inputs) + if (e.kind == 28) bary.push_back(&e); + CHECK_MSG(bary.size() == 1, describe(inputs)); + if (bary.empty()) throw std::logic_error("index out of bounds: no SV_Barycentrics row"); + CHECK(bary[0]->index == 0); + CHECK(bary[0]->col == 0); + CHECK(bary[0]->cols == 3); + // Not packed: the validator wants packing location -1. + CHECK(bary[0]->row == std::nullopt); + // Only y and z (I and J) are read. + const Container isg1_c = unwrap([&] { return Container::parse(shader.dxil); }); + const Bytes isg1 = part_data(isg1_c, FourCC::ISG1); + if (isg1.size() <= 8 + 32 + 25) throw std::logic_error("ISG1 shorter than two rows"); + std::vector<std::uint8_t> rw; + for (std::size_t k = 0; k < 2; ++k) rw.push_back(isg1[8 + 32 * k + 25]); + CHECK_MSG(std::find(rw.begin(), rw.end(), std::uint8_t{0b110}) != rw.end(), + "[" + std::to_string(rw[0]) + ", " + std::to_string(rw[1]) + "]"); + validate(shader); +} + +// ---- rs:2657 ------------------------------------------------------------------------------------ +// Two kinds of barycentrics read directly: one element per mode. +void two_barycentric_modes_get_two_elements() { + // v0-v1 perspective i, j; v2-v3 linear i, j. + const auto [e0, e1] = exp_mrt0(4); + const std::array<std::uint32_t, 4> words = {v_add_f32(4, 0, 3), e0, e1, 0xBF81'0000}; + const HostShader shader = unwrap([&] { return pixel(words, PERSP_CENTER | LINEAR_CENTER); }); + const auto [features, inputs] = parts(shader); + (void)features; + std::vector<std::uint32_t> indices; + for (const SigElement& e : inputs) + if (e.kind == 28) indices.push_back(e.index); + std::sort(indices.begin(), indices.end()); + CHECK_MSG((indices == std::vector<std::uint32_t>{0, 1}), describe(inputs)); + validate(shader); +} + +// ---- rs:2675 ------------------------------------------------------------------------------------ +// I and J only fed to `v_interp_*` stay host interpolation: no barycentrics are declared. +void interpolation_alone_declares_no_barycentrics() { + const auto [e0, e1] = exp_mrt0(2); + const std::array<std::uint32_t, 5> words = { + 0xC808'0000u, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809'0001, // v_interp_p2_f32 v2, v1, attr0.x + e0, + e1, + 0xBF81'0000, + }; + const HostShader shader = unwrap([&] { return pixel(words, PERSP_CENTER); }); + const auto [features, inputs] = parts(shader); + CHECK((features & 0x2'0000) == 0); + CHECK_MSG(count_barycentrics(inputs) == 0, describe(inputs)); + validate(shader); +} + +HostShader first_half_pixel(bool paired) { + const auto [e0, e1] = exp_mrt0(2); + std::vector<std::uint32_t> words = {0xC808'0000u}; // v_interp_p1_f32 v2, v0, attr0.x + if (paired) { + words.push_back(0x7E06'0302); // v_mov_b32 v3, v2 (keep the partial value) + words.push_back(0xC809'0001); // v_interp_p2_f32 v2, v1, attr0.x + words.push_back(v_add_f32(2, 2, 3)); + } + words.push_back(e0); + words.push_back(e1); + words.push_back(0xBF81'0000); + return unwrap([&] { return pixel(words, PERSP_CENTER); }); +} + +// ---- rs:2694 ------------------------------------------------------------------------------------ +void a_standalone_first_half_reads_the_vertices() { + const HostShader shader = first_half_pixel(false); + const auto [features, inputs] = parts(shader); + (void)features; + CHECK(count_barycentrics(inputs) == 1); + CHECK(texcoord_mode(shader) == 1); + validate(shader); +} + +// ---- rs:2703 ------------------------------------------------------------------------------------ +void a_first_half_read_beside_its_pair_keeps_its_partial_value() { + const HostShader shader = first_half_pixel(true); + CHECK(texcoord_mode(shader) == 1); + validate(shader); +} + +// ---- rs:2724 ------------------------------------------------------------------------------------ +void first_half_values_render_on_hardware_and_warp() { + using vs::bitcode::Attr; + using vs::bitcode::Term; + using vs::host::Draw; + using vs::host::Host; + // Pass POSITION and TEXCOORD through, with TEXCOORD in the same output row as the translated + // pixel shader's input signature. + vs::shader::Shader s(false); + s.inputs = {element("POSITION", 0, 0), element("TEXCOORD", 0, 1)}; + for (SigElement& e : s.inputs) e.usage = 15; + s.outputs = {element("TEXCOORD", 0, 0), element("SV_Position", 3, 1)}; + for (std::size_t i = 0; i < s.outputs.size(); ++i) { + s.outputs[i].usage = 15; + s.outputs[i].interp = static_cast<std::uint8_t>(i == 1 ? 4 : 2); + } + for (std::uint32_t row = 0; row < 2; ++row) { + for (std::uint8_t col = 0; col < 4; ++col) { + // Braced: evaluated left to right, as Rust's array. + const std::array<vs::bitcode::V, 4> args = {s.m.i32(row), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)}; + const vs::bitcode::V v = + s.op(s.entry, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, std::span<const vs::bitcode::V>(args)); + const std::array<vs::bitcode::V, 4> store = {s.m.i32(1 - row), s.m.i32(0), s.m.i8(col), v}; + s.op(s.entry, "storeOutput.f32", Attr::NoUnwind, s.t.void_, 5, std::span<const vs::bitcode::V>(store)); + } + } + s.m.terminate(s.entry, Term::ret()); + HostShader vertex; + vertex.stage = HwStage::Vs; + vertex.dxil = s.finish(); + validate(vertex); + // One triangle covers an 8x8 target, with attribute values 2, 6, 10. + const std::array<float, 24> vertices = { + -1.0f, 1.0f, 0.5f, 1.0f, 2.0f, 0.0f, 0.0f, 0.0f, -1.0f, -3.0f, 0.5f, 1.0f, + 6.0f, 0.0f, 0.0f, 0.0f, 3.0f, 1.0f, 0.5f, 1.0f, 10.0f, 0.0f, 0.0f, 0.0f, + }; + int ran = 0; + for (const auto& [backend, warp] : {std::pair<const char*, bool>{"hardware", false}, {"WARP", true}}) { + std::optional<Host> host; + try { + host.emplace(warp); + } catch (const vs::host::Error&) { + continue; + } + D3D12_FEATURE_DATA_D3D12_OPTIONS3 options{}; + const HRESULT hr = host->device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, &options, + static_cast<UINT>(sizeof options)); + if (FAILED(hr)) throw std::logic_error("CheckFeatureSupport(OPTIONS3): " + vs::host::message(hr)); + if (!options.BarycentricsSupported) { + std::fprintf(stderr, "no barycentrics on %s; skipped\n", backend); + continue; + } + for (bool paired : {false, true}) { + const HostShader ps = first_half_pixel(paired); + validate(ps); + vs::host::Pipeline pipeline; + try { + pipeline = host->pipeline(vertex, ps); + } catch (const vs::host::Error& e) { + throw std::logic_error(std::string("interpolation pipeline: ") + e.what()); + } + Draw d; + d.vertices = vertices; + d.stride = 32; + d.size = {8, 8}; + d.mesh_groups = 0; + std::vector<std::array<float, 4>> out; + try { + out = host->draw(pipeline.first.Get(), pipeline.second.Get(), d); + } catch (const vs::host::Error& e) { + throw std::logic_error(std::string("draw partial interpolation: ") + e.what()); + } + for (std::size_t n = 0; n < out.size(); ++n) { + const float i = static_cast<float>(n / 8) / 16.0f + 0.5f / 16.0f; + const float j = static_cast<float>(n % 8) / 16.0f + 0.5f / 16.0f; + const float partial = 2.0f + i * 4.0f; + const float want = paired ? partial + 2.0f + i * 4.0f + j * 8.0f : partial; + for (float got : out[n]) { + char msg[160]; + std::snprintf(msg, sizeof msg, "%s paired=%s pixel=%zu: got %g, want %g", backend, + paired ? "true" : "false", n, static_cast<double>(got), static_cast<double>(want)); + CHECK_MSG(std::fabs(got - want) < 1e-5f, msg); + } + } + } + ran += 1; + std::fprintf(stderr, "partial interpolation renders correctly on %s\n", backend); + } + if (ran == 0) std::fprintf(stderr, "no SM 6.6 host with barycentrics; GPU checks skipped\n"); +} + +// ---- rs:2841 ------------------------------------------------------------------------------------ +// Both: the attribute is interpolated and J is used as a value. +void interpolation_and_a_barycentric_value_together() { + const auto [e0, e1] = exp_mrt0(3); + const std::array<std::uint32_t, 6> words = { + 0xC808'0000u, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809'0001, // v_interp_p2_f32 v2, v1, attr0.x + v_add_f32(3, 2, 1), // v3 = attribute + j + e0, + e1, + 0xBF81'0000, + }; + const HostShader shader = unwrap([&] { return pixel(words, PERSP_CENTER); }); + const auto [features, inputs] = parts(shader); + CHECK((features & 0x2'0000) != 0); + CHECK(count_barycentrics(inputs) == 1); + validate(shader); +} + +// ---- rs:2870 ------------------------------------------------------------------------------------ +// An interpolation whose i is computed (`v_mul_f32 v3, 0.5, v0`) reads the attribute's vertices: +// TEXCOORD0 becomes constant, read with `attributeAtVertex`; i and j are `SV_Barycentrics` values. +void computed_barycentrics_read_the_vertices() { + const auto [e0, e1] = exp_mrt0(2); + const std::array<std::uint32_t, 6> words = { + 0x1006'00F0u, // v_mul_f32 v3, 0.5, v0 + 0xC808'0003, // v_interp_p1_f32 v2, v3, attr0.x + 0xC809'0001, // v_interp_p2_f32 v2, v1, attr0.x + e0, + e1, + S_ENDPGM, + }; + const HostShader shader = unwrap([&] { return pixel(words, PERSP_CENTER); }); + const auto [features, inputs] = parts(shader); + CHECK_MSG((features & 0x2'0000) != 0, "no Barycentrics feature"); + CHECK(count_barycentrics(inputs) == 1); + CHECK(texcoord_mode(shader) == 1); + validate(shader); +} + +// ---- rs:2892 ------------------------------------------------------------------------------------ +// Weights from constants alone: the vertices, no `SV_Barycentrics`. +void constant_weights_need_no_barycentrics() { + const auto [e0, e1] = exp_mrt0(2); + const std::array<std::uint32_t, 6> words = { + 0x7E06'02F0u, // v_mov_b32 v3, 0.5 + 0xC808'0003, // v_interp_p1_f32 v2, v3, attr0.x + 0xC809'0003, // v_interp_p2_f32 v2, v3, attr0.x + e0, + e1, + S_ENDPGM, + }; + const HostShader shader = unwrap([&] { return pixel(words, PERSP_CENTER); }); + const auto [features, inputs] = parts(shader); + CHECK_MSG((features & 0x2'0000) != 0, "no Barycentrics feature"); + CHECK_MSG(count_barycentrics(inputs) == 0, describe(inputs)); + CHECK(texcoord_mode(shader) == 1); + validate(shader); +} + +// ---- rs:2912 ------------------------------------------------------------------------------------ +// The same attribute interpolated with the loaded i and j and with a computed j: both from its +// vertices, the first weighed with `SV_Barycentrics`. +void computed_and_loaded_barycentrics_on_one_attribute() { + const auto [e0, e1] = exp_mrt0(2); + const std::array<std::uint32_t, 9> words = { + 0xC810'0100u, // v_interp_p1_f32 v4, v0, attr0.y + 0xC811'0101, // v_interp_p2_f32 v4, v1, attr0.y + 0x1006'02F0, // v_mul_f32 v3, 0.5, v1 + 0xC808'0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809'0003, // v_interp_p2_f32 v2, v3, attr0.x + v_add_f32(2, 2, 4), + e0, + e1, + S_ENDPGM, + }; + const HostShader shader = unwrap([&] { return pixel(words, PERSP_CENTER); }); + const auto [features, inputs] = parts(shader); + (void)features; + CHECK(count_barycentrics(inputs) == 1); + CHECK(texcoord_mode(shader) == 1); + validate(shader); +} + +// ---- rs:2936 ------------------------------------------------------------------------------------ +// P10 of an attribute the program interpolates is P1 - P0. +void p10_of_an_interpolated_attribute() { + { + const auto [e0, e1] = exp_mrt0(2); + const std::array<std::uint32_t, 7> words = { + 0xC808'0000u, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809'0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xC812'0000, // v_interp_mov_f32 v4, p10, attr0.x + v_add_f32(2, 2, 4), + e0, + e1, + S_ENDPGM, + }; + const HostShader shader = unwrap([&] { return pixel(words, PERSP_CENTER); }); + CHECK(texcoord_mode(shader) == 1); + validate(shader); + } + // Alone, what the hardware holds is not known. + const auto [e0, e1] = exp_mrt0(4); + const std::array<std::uint32_t, 4> words = {0xC812'0000u, e0, e1, S_ENDPGM}; + CHECK(vs::catch_shader_error([&] { (void)pixel(words, PERSP_CENTER); }).has_value()); +} + +int run_failed = 0; + +void run(const char* name, void (*test)()) { + x2w::vs::lower::test::set_dump_name(std::string("emit__barycentric_tests__") + name); + const int before = test_util::failures(); + try { + test(); + } catch (const std::exception& e) { + std::fprintf(stderr, "%s: panicked: %s\n", name, e.what()); + ++test_util::failures(); + } + if (test_util::failures() != before) { + ++run_failed; + std::fprintf(stderr, "%s: FAILED\n", name); + } +} + +} // namespace + +#define RUN(test) run(#test, test) + +int main() { + RUN(an_unused_packed_input_matches_its_provoking_vertex_sibling); + RUN(a_pixel_first_lane_loop_serves_helper_lanes); + RUN(barycentrics_read_as_values_are_sv_barycentrics); + RUN(two_barycentric_modes_get_two_elements); + RUN(interpolation_alone_declares_no_barycentrics); + RUN(a_standalone_first_half_reads_the_vertices); + RUN(a_first_half_read_beside_its_pair_keeps_its_partial_value); + RUN(first_half_values_render_on_hardware_and_warp); + RUN(interpolation_and_a_barycentric_value_together); + RUN(computed_barycentrics_read_the_vertices); + RUN(constant_weights_need_no_barycentrics); + RUN(computed_and_loaded_barycentrics_on_one_attribute); + RUN(p10_of_an_interpolated_attribute); + if (run_failed) std::fprintf(stderr, "barycentric_test: %d test(s) failed\n", run_failed); + return test_util::finish("barycentric_test"); +} diff --git a/tests/x2w_shader/emit/bitcode_test.cpp b/tests/x2w_shader/emit/bitcode_test.cpp new file mode 100644 index 0000000000..309c0d6b8f --- /dev/null +++ b/tests/x2w_shader/emit/bitcode_test.cpp @@ -0,0 +1,218 @@ +// Port of the tests in the upstream Rust module emit/bitcode.rs (#[cfg(test)] mod tests). + +#include <cstdio> +#include <cstdlib> +#include <string> +#include <vector> + +#include "x2w_shader/emit/bitcode.h" +#include "test_util.h" + +using namespace x2w::vs::bitcode; + +namespace { + +// A structured shader's shape: `stages` if/else diamonds in a row, each merge with one phi per +// register (as the lowering makes them), then a loop, and a tail that reads only the first `read` +// registers. +Module synthetic(std::size_t regs, std::size_t stages, std::size_t read) { + Module m; + Ty i32t = m.int_(32); + Ty voidt = m.void_(); + Ty fty = m.func_ty(i32t, {i32t, i32t}); + V f = m.function("dx.op.synthetic", fty, Attr::ReadNone, false); + Ty main_ty = m.func_ty(voidt, {}); + m.function("main", main_ty, std::nullopt, true); + std::size_t b = m.new_block(); + std::vector<V> cur; + for (std::size_t r = 0; r < regs; ++r) cur.push_back(m.i32(std::uint32_t(r))); + for (std::size_t s = 0; s < stages; ++s) { + V c = m.cmp(b, pred::EQ, cur[0], cur[s % regs]); + std::size_t t = m.new_block(); + std::size_t e = m.new_block(); + std::size_t j = m.new_block(); + m.terminate(b, Term::cond_br(c, t, e)); + V x = m.call(t, f, {cur[s % regs], cur[(s + 1) % regs]}); + m.terminate(t, Term::br(j)); + m.terminate(e, Term::br(j)); + std::vector<V> next; + for (std::size_t r = 0; r < regs; ++r) { + V p = m.phi(j, i32t); + V tv = r == s % regs ? x : cur[r]; + m.set_phi(p, {{tv, t}, {cur[r], e}}); + next.push_back(p); + } + cur = next; + b = j; + } + // A loop: header phis fed back from an empty latch (which is folded). + std::size_t head = m.new_block(); + std::size_t body = m.new_block(); + std::size_t latch = m.new_block(); + std::size_t exit = m.new_block(); + m.terminate(b, Term::br(head)); + std::vector<V> phis; + for (std::size_t r = 0; r < regs; ++r) phis.push_back(m.phi(head, i32t)); + V one = m.i32(1); + std::vector<V> stepped; + for (V p : phis) stepped.push_back(m.bin(body, Bin::Add, p, one)); + V c = m.cmp(body, pred::IULT, stepped[0], cur[0]); + m.terminate(head, Term::br(body)); + m.terminate(body, Term::cond_br(c, latch, exit)); + m.terminate(latch, Term::br(head)); + for (std::size_t r = 0; r < regs; ++r) m.set_phi(phis[r], {{cur[r], b}, {stepped[r], latch}}); + V acc = stepped[0]; + for (std::size_t k = 1; k < std::max<std::size_t>(read, 1); ++k) acc = m.bin(exit, Bin::Add, acc, stepped[k]); + (void)m.call(exit, f, {acc, cur[0]}); + m.terminate(exit, Term::ret()); + return m; +} + +// Liveness as write computed it before the worklist: whole passes over the instructions until +// one changes nothing. +std::vector<bool> live_by_passes(const Module& m) { + std::vector<bool> live(m.insts.size(), false); + for (const Block& b : m.blocks) { + for (std::uint32_t i : b.body) live[i] = true; + if (b.term && b.term->kind == Term::CondBr && b.term->cond.kind == V::Inst) live[b.term->cond.i] = true; + } + bool changed = true; + while (changed) { + changed = false; + for (std::size_t i = 0; i < m.insts.size(); ++i) { + if (!live[i]) continue; + for_each_operand(m.insts[i].op, [&](V v) { + if (v.kind == V::Inst && !live[v.i]) { + live[v.i] = true; + changed = true; + } + }); + } + } + return live; +} + +void vbr_and_blocks() { + Writer w; + w.vbr(5, 6); + w.vbr(100, 6); + CHECK(w.cur == (5 | (0b100100ull << 6) | (3ull << 12))); + Writer w2; + w2.enter(8, 3); + w2.record(1, {1}); + w2.exit(); + auto bytes = w2.finish(); + CHECK(bytes.size() % 4 == 0); + CHECK(test_util::u32le(bytes, 4) == 1); + CHECK(signed_vbr(-3) == 7); + CHECK(signed_vbr(2) == 4); +} + +void worklist_liveness_matches_passes() { + const std::size_t cases[][3] = {{1, 0, 1}, {1, 1, 1}, {4, 3, 1}, {8, 17, 3}, {16, 40, 16}}; + for (auto& c : cases) { + Module m = synthetic(c[0], c[1], c[2]); + CHECK(m.live() == live_by_passes(m)); + } +} + +void unread_phis_are_dropped() { + Module m; + Ty i32t = m.int_(32); + std::size_t entry = m.new_block(); + std::size_t join = m.new_block(); + V a = m.i32(1); + V b = m.i32(2); + m.terminate(entry, Term::br(join)); + V read = m.phi(join, i32t); + V unread = m.phi(join, i32t); + // A cycle of phis that only feed each other stays dead. + V cyc_a = m.phi(join, i32t); + V cyc_b = m.phi(join, i32t); + m.set_phi(read, {{a, entry}}); + m.set_phi(unread, {{b, entry}}); + m.set_phi(cyc_a, {{cyc_b, entry}}); + m.set_phi(cyc_b, {{cyc_a, entry}}); + V sum = m.bin(join, Bin::Add, read, b); + m.terminate(join, Term::ret()); + auto live = m.live(); + CHECK(live[read.i] && live[sum.i]); + CHECK(!live[unread.i] && !live[cyc_a.i] && !live[cyc_b.i]); + CHECK(live == live_by_passes(m)); +} + +std::vector<std::uint8_t> latch_loop(bool with_dead_phi) { + Module m; + Ty i32t = m.int_(32); + Ty voidt = m.void_(); + Ty fty = m.func_ty(voidt, {i32t}); + V f = m.function("sink", fty, Attr::NoUnwind, false); + Ty main_ty = m.func_ty(voidt, {}); + m.function("main", main_ty, std::nullopt, true); + std::size_t entry = m.new_block(); + std::size_t head = m.new_block(); + std::size_t body = m.new_block(); + std::size_t latch = m.new_block(); + std::size_t exit = m.new_block(); + V z = m.i32(0); + V one = m.i32(1); + V ten = m.i32(10); + m.terminate(entry, Term::br(head)); + V i = m.phi(head, i32t); + m.terminate(head, Term::br(body)); + V next = m.bin(body, Bin::Add, i, one); + V cond = m.cmp(body, pred::IULT, next, ten); + m.terminate(body, Term::cond_br(cond, latch, exit)); + if (with_dead_phi) { + V dead = m.phi(latch, i32t); + m.set_phi(dead, {{next, body}}); + } + m.terminate(latch, Term::br(head)); + m.set_phi(i, {{z, entry}, {next, latch}}); + (void)m.call(exit, f, {next}); + m.terminate(exit, Term::ret()); + return m.write(); +} + +void empty_latch_with_dead_phis_is_folded() { + // Two identical loops except one has an unread phi in its empty latch; both must fold the + // latch and emit identical bitcode. + CHECK(latch_loop(false) == latch_loop(true)); +} + +void successors_of_each_terminator() { + CHECK(successors(std::nullopt).empty()); + CHECK(successors(Term::ret()).empty()); + auto s = successors(Term::br(7)); + CHECK(s.size() == 1 && s.to[0] == 7); + auto c = successors(Term::cond_br(V::constant(0), 3, 5)); + CHECK(c.size() == 2 && c.to[0] == 3 && c.to[1] == 5); +} + +// The written bytes are pinned to what the reference writer produces (its written_bytes_unchanged). +void written_bytes_unchanged() { + struct Case { + std::size_t regs, stages, read, len; + std::uint64_t hash; + }; + const Case cases[] = {{64, 64, 64, 38916, 0x9586730cf9534a45ull}, {128, 256, 32, 295952, 0x89e5de2d64f08785ull}}; + for (const Case& c : cases) { + auto bytes = synthetic(c.regs, c.stages, c.read).write(); + std::printf("synthetic %zux%zu: %zu bytes, fnv %016llx\n", c.regs, c.stages, bytes.size(), + (unsigned long long)test_util::fnv(bytes)); + CHECK(bytes.size() == c.len); + CHECK(test_util::fnv(bytes) == c.hash); + } +} + +} // namespace + +int main() { + vbr_and_blocks(); + worklist_liveness_matches_passes(); + unread_phis_are_dropped(); + empty_latch_with_dead_phis_is_folded(); + successors_of_each_terminator(); + written_bytes_unchanged(); + return test_util::finish("bitcode_test"); +} diff --git a/tests/x2w_shader/emit/container_test.cpp b/tests/x2w_shader/emit/container_test.cpp new file mode 100644 index 0000000000..c71a45b380 --- /dev/null +++ b/tests/x2w_shader/emit/container_test.cpp @@ -0,0 +1,156 @@ +// Port of the upstream Rust module emit/container.rs tests and emit/rect.rs tests (the ones without a device; the +// validator checks of the rectangle stage are in rect_test). + +#include <array> +#include <cstdio> +#include <string> +#include <vector> + +#include "test_util.h" +#include "x2w_shader/dxbc.h" +#include "x2w_shader/emit/container.h" +#include "x2w_shader/emit/rect.h" +#include "x2w_shader/emit/signature.h" +#include "x2w_shader/error.h" + + + +using namespace x2w::vs; +using container::SigElement; + +namespace { + +template <class F> +bool throws(F&& f) { + try { + f(); + } catch (const ShaderError&) { + return true; + } + return false; +} + +void packed_vertex_outputs_preserve_name_order_and_declared_interpolation() { + SigElement integer; + integer.name = "TEXCOORD"; + integer.index = 1; + integer.kind = 0; + integer.comp = 5; + integer.interp = 1; + integer.row = 0; + integer.col = 2; + integer.cols = 2; + integer.usage = 3; + integer.half = false; + SigElement flat_float = integer; + flat_float.name = "COLOR"; + flat_float.index = 0; + flat_float.comp = 9; + flat_float.col = 0; + SigElement smooth_float = integer; + smooth_float.index = 2; + smooth_float.row = 1; + smooth_float.interp = 2; + smooth_float.comp = 9; + const std::vector<SigElement> outputs = {integer, flat_float, smooth_float}; + std::vector<SigElement> recovered = signature(container::signature(outputs, false)); + // DXC orders the row by semantic-name offset even though TEXCOORD occupies z/w and COLOR x/y. + CHECK(recovered[0].name == "TEXCOORD"); + CHECK(recovered[1].name == "COLOR"); + // PSV records can be in a different order again. + const std::vector<SigElement> reordered = {outputs[2], outputs[1], outputs[0]}; + container::Psv p; + p.stage = 1; + p.flag = false; + p.outputs = reordered; + const std::vector<std::uint8_t> psv = container::psv(p); + recovered[1].interp = 2; + vertex_output_interpolation(psv, recovered); + CHECK(recovered.size() == 3 && recovered[0].interp == 1 && recovered[1].interp == 1 && recovered[2].interp == 2); + CHECK(throws([&] { + vertex_output_interpolation(std::span<const std::uint8_t>(psv.data(), psv.size() - 1), recovered); + })); +} + +void md5_core_matches_the_standard() { + std::vector<std::uint8_t> block = {'a', 'b', 'c', 0x80}; + block.resize(56, 0); + for (int k = 0; k < 8; ++k) block.push_back(std::uint8_t(std::uint64_t(24) >> (8 * k))); + std::array<std::uint32_t, 4> state = {0x67452301u, 0xefcdab89u, 0x98badcfeu, 0x10325476u}; + container::md5_block_for_test(state, block.data()); + std::string hex; + for (std::uint32_t s : state) + for (int k = 0; k < 4; ++k) { + char b[3]; + std::snprintf(b, sizeof b, "%02x", unsigned((s >> (8 * k)) & 0xff)); + hex += b; + } + CHECK(hex == "900150983cd24fb0d6963f7d28e17f72"); +} + +SigElement element(const char* name, std::uint32_t index, std::uint8_t kind, std::uint8_t comp, std::uint32_t row, + std::uint8_t cols) { + SigElement e; + e.name = name; + e.index = index; + e.kind = kind; + e.comp = comp; + e.interp = 0; + e.row = row; + e.col = 0; + e.cols = cols; + e.usage = 0; + e.half = false; + return e; +} + +std::vector<SigElement> outputs() { + return {element("SV_Position", 0, 3, 9, 0, 4), element("TEXCOORD", 0, 0, 9, 1, 4), element("TEXCOORD", 1, 0, 5, 2, 2)}; +} + +void the_rectangle_stage_is_a_geometry_shader() { + const std::vector<SigElement> wanted = {element("SV_PrimitiveID", 0, 10, 5, 3, 1)}; + const std::vector<std::uint8_t> gs = rect_build(outputs(), wanted); + const dxbc::Container c = dxbc::Container::parse(gs); + auto data = c.part(dxbc::FourCC::DXIL)->data; + // Program version: geometry (2), shader model 6.6. + CHECK(data[0] == 0x66 && data[1] == 0 && data[2] == 2 && data[3] == 0); + auto psv = c.part(dxbc::FourCC::PSV0)->data; + const std::uint8_t a[] = {3, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 1}; + bool same = true; + for (int k = 0; k < 13; ++k) same = same && psv[4 + k] == a[k]; + CHECK(same); + const std::uint8_t b[] = {2, 0, 6, 0, 3, 4}; + same = true; + for (int k = 0; k < 6; ++k) same = same && psv[28 + k] == b[k]; + CHECK(same); + const auto ins = signature(c.part(dxbc::FourCC::ISG1)->data); + const auto outs = signature(c.part(dxbc::FourCC::OSG1)->data); + CHECK(ins.size() == 3); + CHECK(outs.size() == 4); + for (std::size_t k = 0; k < ins.size() && k < outs.size(); ++k) { + CHECK(ins[k].name == outs[k].name && ins[k].index == outs[k].index && ins[k].row == outs[k].row); + CHECK(ins[k].col == outs[k].col && ins[k].cols == outs[k].cols && ins[k].comp == outs[k].comp); + } + if (outs.size() == 4) CHECK(outs[3].kind == 10 && outs[3].row == std::optional<std::uint32_t>(3)); +} + +void rectangle_stages_that_cannot_be_made_are_refused() { + auto o = outputs(); + CHECK(throws([&] { rect_build(std::vector<SigElement>(o.begin() + 1, o.end()), {}); })); + const std::vector<SigElement> taken = {element("SV_PrimitiveID", 0, 10, 5, 1, 1)}; + CHECK(throws([&] { rect_build(outputs(), taken); })); + std::vector<SigElement> many = {element("SV_Position", 0, 3, 9, 0, 4)}; + for (std::uint32_t row = 1; row <= 43; ++row) many.push_back(element("TEXCOORD", row - 1, 0, 9, row, 4)); + CHECK(throws([&] { rect_build(many, {}); })); +} + +} // namespace + +int main() { + packed_vertex_outputs_preserve_name_order_and_declared_interpolation(); + md5_core_matches_the_standard(); + the_rectangle_stage_is_a_geometry_shader(); + rectangle_stages_that_cannot_be_made_are_refused(); + return test_util::finish("container_test"); +} diff --git a/tests/x2w_shader/emit/diff_test.cpp b/tests/x2w_shader/emit/diff_test.cpp new file mode 100644 index 0000000000..16a81cff67 --- /dev/null +++ b/tests/x2w_shader/emit/diff_test.cpp @@ -0,0 +1,1238 @@ +// Port of the upstream Rust module emit/diff_tests.rs. Differential tests: HLSL compiled by the console's shader +// compiler and translated, against the same HLSL compiled for PC, both drawn (or dispatched) on +// the host GPU with the same inputs. +// +// Needs X2W_SHADERCFG_CONSOLE_DXC (the console SDK's dxc.exe) and a PC dxc.exe (X2W_SHADERCFG_PC_DXC, else the +// newest Windows SDK's); skipped without them. Set X2W_SHADERCFG_WARP=1 to draw on WARP. +// X2W_SHADERCFG_DIFF_ONLY=<case name> runs one case; X2W_SHADERCFG_EMIT_DUMP=<dir> writes the console and +// translated containers there. +// +// Each Rust #[test] is a function here; a Rust panic (unwrap, expect, assert) is an exception +// that fails that function (main catches it) and the others still run. + +#include <windows.h> + +#include <algorithm> +#include <array> +#include <bit> +#include <charconv> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <exception> +#include <filesystem> +#include <fstream> +#include <iterator> +#include <limits> +#include <optional> +#include <stdexcept> +#include <string> +#include <string_view> +#include <utility> +#include <vector> + +#include "test_util.h" +#include "x2w_shader/emit/emit.h" +#include "x2w_shader/emit/host.h" +#include "x2w_shader/emit/validator.h" +#include "x2w_shader/error.h" + +namespace fs = std::filesystem; +using namespace x2w::vs; +using host::Dispatch; +using host::Draw; +using host::Host; +using host::Root; +using host::Stride; +using host::View; +using validator::Validator; + +namespace { + +struct Case { + const char* name; + const char* src; +}; + +struct MeshCase { + const char* name; + std::uint32_t groups; + const char* src; +}; + +// Pixel shaders, each `ps` (CASES). Compute shaders, each `cs`, dispatched as 2x2 groups of 8x8 +// threads over a 16x16 texture and a 256-dword buffer (CS_CASES). Mesh shaders, each `ms` (the +// console runs one thread per output lane, so groups of 32 run as 64 lanes there), with their +// group counts, drawn with `mps` into 16x16 targets (MS_CASES). The 2020 compiler's containers +// do not record the thread count, so cases reading the group id keep max(threads, vertices, +// primitives) at the lane count (see emit). +const char* const RS = R"hlsl(RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), RootConstants(num32BitConstants=4, b0), DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), StaticSampler(s1, filter=FILTER_MIN_MAG_MIP_POINT, addressU=TEXTURE_ADDRESS_WRAP, addressV=TEXTURE_ADDRESS_MIRROR), StaticSampler(s2, filter=FILTER_MIN_MAG_LINEAR_MIP_POINT, addressU=TEXTURE_ADDRESS_BORDER, addressV=TEXTURE_ADDRESS_CLAMP, borderColor=STATIC_BORDER_COLOR_OPAQUE_WHITE, mipLODBias=0.5))hlsl"; +const char* const COMMON = R"hlsl( +cbuffer K : register(b0) { float4 k; }; +Texture2D tex : register(t0); +SamplerState smp : register(s0); +struct V { float4 pos : SV_Position; float2 uv : TEXCOORD0; float4 col : COLOR0; }; +[RootSignature(RS)] +V vs(float4 p : POSITION, float2 uv : TEXCOORD0) { + V o; + o.pos = p; + o.uv = uv; + o.col = float4(uv * k.xy, p.x * k.z, 1); + return o; +} +)hlsl"; +const char* const CS_RS = R"hlsl(RootConstants(num32BitConstants=4, b0), DescriptorTable(SRV(t0, numDescriptors=4)), DescriptorTable(Sampler(s0)), DescriptorTable(UAV(u0, numDescriptors=4)), CBV(b1), SRV(t4), DescriptorTable(SRV(t0, space=2, numDescriptors=9)), StaticSampler(s3, filter=FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, comparisonFunc=COMPARISON_LESS_EQUAL, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP))hlsl"; +const char* const CS_COMMON = R"hlsl( +cbuffer K : register(b0) { float4 k; }; +Texture2D tex : register(t0); +Buffer<float4> typed : register(t1); +struct S { float a; uint b; float2 c; }; +StructuredBuffer<S> structured : register(t2); +ByteAddressBuffer raw : register(t3); +SamplerState smp : register(s0); +SamplerComparisonState cmp : register(s3); +RWByteAddressBuffer outb : register(u0); +RWTexture2D<float4> outt : register(u1); +cbuffer R : register(b1) { float4 table[16]; }; +ByteAddressBuffer rootraw : register(t4); +// `raw`'s bytes in typed views (the formats the console's typed loads name). +Buffer<float4> unorm8x4 : register(t0, space2); +Buffer<float4> snorm16x2 : register(t1, space2); +Buffer<uint4> uint8x4 : register(t2, space2); +Buffer<float4> unorm10x3_2 : register(t3, space2); +Buffer<uint4> uint16x4 : register(t4, space2); +Buffer<float> unorm8 : register(t5, space2); +Buffer<float> half16 : register(t6, space2); +Buffer<float4> snorm8x4 : register(t7, space2); +RWTexture2D<uint> ut : register(u2); +TextureCube cubet : register(t8, space2); +#define FMT(numeric, data) ((numeric) << 4 | (data)) +#define CS [RootSignature(RS)] [numthreads(8, 8, 1)] \ + void cs(uint3 g : SV_GroupID, uint3 t : SV_GroupThreadID, \ + uint3 d : SV_DispatchThreadID, uint i : SV_GroupIndex) +)hlsl"; +const char* const MS_COMMON = R"hlsl( +#define RS "RootConstants(num32BitConstants=4, b0)" +cbuffer K : register(b0) { float4 k; }; +struct V { float4 pos : SV_Position; float4 col : COLOR0; float2 uv : TEXCOORD0; }; +[RootSignature(RS)] float4 mps(V i) : SV_Target { return i.col + float4(i.uv, 0, 0); } +#define MS_ATTR [RootSignature(RS)] [outputtopology("triangle")] +)hlsl"; + +const Case CASES[] = { + {"constant", R"hlsl([RootSignature(RS)] float4 ps(V i) : SV_Target { return float4(0.25, 0.5, 1, 0.75); })hlsl"}, + {"interpolated", R"hlsl([RootSignature(RS)] float4 ps(V i) : SV_Target { return i.col * 2 - float4(i.uv, 0, 0); })hlsl"}, + {"sample and branch", R"hlsl([RootSignature(RS)] float4 ps(V i) : SV_Target { + float4 t = tex.Sample(smp, i.uv); + float4 r = t * i.col + k.w; + if (i.uv.x > 0.5) r.xy = sin(r.yx * 3.0); + else r.z = rcp(r.z + 2.0); + return r; + })hlsl"}, + // A wave-wide range scalarises a per-pixel loop (as the title's light + // lists do): the console's 64-lane sections become host wave operations; + // the result is the same for any wave the pixel lands in. + {"wave range", R"hlsl([RootSignature(RS)] float4 ps(V i) : SV_Target { + uint idx = uint(i.pos.x * 0.37 + i.pos.y * 0.21) & 15; + uint lo = WaveActiveMin(idx), hi = WaveActiveMax(idx); + float s = 0; + for (uint n = lo; n <= hi; n++) if (n == idx) s += n * k.x; + return float4(s, lo <= idx, hi >= idx, WaveActiveCountBits(true) > 0); + })hlsl"}, + {"uniform loop", R"hlsl([RootSignature(RS)] float4 ps(V i) : SV_Target { + float s = 0; + for (uint n = 0; n < (asuint(k.x) & 7); n++) s += i.uv.y * n; + return float4(s, 0, 0, 1); + })hlsl"}, + {"bit loop", R"hlsl([RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + uint s = p.y; + for (uint n = 0; n < (p.x & 7); n++) s = (s ^ (s << 3)) + n; + return float4(s & 255, 0, 0, 1); + })hlsl"}, + {"integer loop", R"hlsl([RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + uint s = 0; + for (uint n = 0; n < (p.x & 7); n++) s += n; + return float4(s, 0, 0, 1); + })hlsl"}, + {"loop", R"hlsl([RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + float s = 0; + for (uint n = 0; n < (p.x & 7); n++) s += i.uv.y * n + k.x; + return float4(s, 0, 0, 1); + })hlsl"}, + {"discard", R"hlsl([RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + if ((p.x ^ p.y) & 1) discard; + return i.col; + })hlsl"}, + {"immediate samplers", R"hlsl(SamplerState point_wrap : register(s1); + SamplerState linear_border : register(s2); + [RootSignature(RS)] float4 ps(V i) : SV_Target { + return tex.Sample(point_wrap, i.uv * 3 - 1) + 2 * tex.Sample(linear_border, i.uv * 2.5 - 0.7); + })hlsl"}, + {"loop, discard and loads", R"hlsl([RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + if ((p.x ^ p.y) & 1) discard; + float s = 0; + for (uint n = 0; n < (p.x & 7); n++) s += i.uv.y * n + k.x; + float4 t = tex.Load(int3(p & 3, 0)); + return float4(s, frac(i.uv.x * 7.3), max(t.x, t.y) * k.y, sqrt(abs(i.col.x)) + exp2(i.uv.y)); + })hlsl"}, + {"level of detail", R"hlsl([RootSignature(RS)] float4 ps(V i) : SV_Target { + return float4(tex.CalculateLevelOfDetail(smp, i.uv * 4), + tex.CalculateLevelOfDetailUnclamped(smp, i.uv * 7), 0, 1); + })hlsl"}, + // 16-bit outputs and inputs (one value per dword with the 2020 + // compiler; the title's two per dword cannot be compiled + // here) and the front face. + {"16-bit varyings and front face", R"hlsl(struct V16 { float4 pos : SV_Position; half2 uv : TEXCOORD0; float4 col : COLOR0; half4 h : TEXCOORD1; }; + [RootSignature(RS)] V16 vs16(float4 p : POSITION, float2 uv : TEXCOORD0) { + V16 o; + o.pos = p; + o.uv = half2(uv * k.xy); + o.col = float4(uv, p.x * k.z, 1); + o.h = half4(uv.yx * 3 - 1, k.w, p.y); + return o; + } + [RootSignature(RS)] float4 ps(V16 i, bool f : SV_IsFrontFace) : SV_Target { + float4 c = i.col * float4(i.uv, i.h.xy) + float4(i.h.zw, 0, 0); + return f ? c : -c; + })hlsl"}, +}; + +const Case CS_CASES[] = { + {"ids and stores", R"hlsl(CS { + outb.Store(4 * (d.y * 16 + d.x), asuint(d.x * k.x + d.y)); + outt[d.xy] = float4(g.x, g.y, t.x, t.y + i); + })hlsl"}, + {"shared memory and barrier", R"hlsl(groupshared float lds[64]; + groupshared uint cnt; + CS { + if (i == 0) cnt = 0; + lds[i] = d.x * k.x + d.y; + GroupMemoryBarrierWithGroupSync(); + InterlockedAdd(cnt, i); + float v = lds[63 - i] + lds[(i + 9) & 63]; + GroupMemoryBarrierWithGroupSync(); + outb.Store(4 * (d.y * 16 + d.x), asuint(v)); + outt[d.xy] = float4(v, cnt, 0, 1); + })hlsl"}, + {"sample and divergent store", R"hlsl(CS { + float4 s = tex.SampleLevel(smp, (d.xy + 0.5) / 16.0, 0); + if ((d.x ^ d.y) & 1) outt[d.xy] = s * k.y; + else outb.Store(4 * (d.y * 16 + d.x), asuint(s.x + s.w)); + })hlsl"}, + {"buffers and root views", R"hlsl(CS { + float4 a = typed[i & 15]; + S s = structured[(i * 3) & 7]; + uint r = raw.Load(4 * (i & 31)); + float4 c = table[d.x & 15]; + uint q = rootraw.Load(4 * ((i + 5) & 31)); + outb.Store(4 * (d.y * 16 + d.x), asuint(a.x + a.w * s.a) ^ s.b ^ r ^ q); + outt[d.xy] = c + float4(s.c, a.yz); + })hlsl"}, + // (The 2020 compiler branches around every narrowed region, so these + // become branches, not guards.) + {"conditional memory access", R"hlsl(CS { + float v = d.x * k.x + d.y; + if (i & 1) v = v * 3 + 1; + if (i & 4) v += tex.Load(int3(d.xy & 3, 0)).y; + if (i & 2) outb.Store(4 * (d.y * 16 + d.x), asuint(v)); + if (i & 8) outt[d.xy] = float4(v, 0, 0, 1); + })hlsl"}, + // Each side of a per-group branch leaves a compare in VCC; the select + // after the join reads the joined mask (as `postfx_splines` does). + {"select on joined compares", R"hlsl(CS { + float v = d.x * k.x + d.y; + float r; + bool ok; + [branch] if ((g.x ^ g.y) & 1) { + r = sqrt(v) * k.z + sin(v * k.w); + ok = r < 5; + } else { + r = v * k.y + 1; + ok = r > -4; + } + float o = ok ? r : -1; + outb.Store(4 * (d.y * 16 + d.x), asuint(o)); + outt[d.xy] = float4(o, r, v, 1); + })hlsl"}, + // One host wave of 32 lanes holds the group, as the console's wave of 64 + // does, so lane numbers agree with the PC compile. + {"lane reads", R"hlsl([RootSignature(RS)] [numthreads(8, 4, 1)] + void cs(uint3 d : SV_DispatchThreadID) { + float v = d.x * k.x + d.y; + float w = WaveReadLaneAt(v, 5); + uint lane = WaveGetLaneIndex(); + uint q = QuadReadAcrossX(lane * 10) + QuadReadAcrossDiagonal(lane); + outb.Store(4 * (d.y * 16 + d.x), q); + outt[d.xy] = float4(v, w, QuadReadAcrossY(v), lane); + })hlsl"}, + // Bytes and halves: SDWA operand and result selection, byte permutes, + // f16 conversions. + {"sub-dword operations", R"hlsl(CS { + uint n = d.y * 16 + d.x; + uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 7) & 31)); + float a = float(x >> 16) + float((y >> 8) & 255) * k.x; + float b = f16tof32(x >> 16) + f16tof32(y); + uint p = (x & 0xff) | ((y & 0xff) << 8) | (x & 0xff0000) | ((y >> 8) << 24); + uint q = f32tof16(a) | (f32tof16(b) << 16); + int s = int(x << 24) >> 24; + uint u = (x & 0xffff) + (y >> 16) + ((x >> 24) ^ (y & 0xffff)) + asuint(k.w) * 1000 + 77; + outb.Store4(16 * n, uint4(asuint(a), asuint(b) ^ p, q, asuint(float(s)) + u)); + })hlsl"}, + // 64-bit additions (VALU carries as lane masks) and explicit gradients. + {"carries and gradients", R"hlsl(CS { + uint n = d.y * 16 + d.x; + uint64_t a = (uint64_t(raw.Load(4 * (n & 31))) << 32) | raw.Load(4 * ((n * 3) & 31)); + uint64_t b = (uint64_t(raw.Load(4 * ((n * 5) & 31))) << 32) | raw.Load(4 * ((n * 7) & 31)); + uint64_t s = a + b, u = a - b; + float4 gr = tex.SampleGrad(smp, (d.xy + 0.5) / 16.0, float2(k.x, 0) * 0.1, float2(0, k.z) * 0.1); + outb.Store4(16 * n, uint4(uint(s), uint(s >> 32) ^ uint(u), uint(u >> 32), asuint(gr.x + gr.y * 3))); + })hlsl"}, + // Comparison sampling at level 0 with an immediate comparison sampler. + {"comparison sampling", R"hlsl(CS { + float r = tex.SampleCmpLevelZero(cmp, (d.xy + 0.25) / 15.0, k.x * d.x / 16.0); + outb.Store(4 * (d.y * 16 + d.x), asuint(r)); + })hlsl"}, + // 16-bit texture results, two channels per register (`d16`). + {"16-bit texture reads", R"hlsl(Texture2D<half4> htex : register(t0); + CS { + half4 a = htex.SampleLevel(smp, (d.xy + 0.5) / 16.0, 0); + half3 b = htex.Load(int3(d.xy & 3, 0)).xyz; + outb.Store4(16 * (d.y * 16 + d.x), uint4(asuint(float(a.x) + a.w), + asuint(float(a.y) * a.z), asuint(float(b.x)), asuint(float(b.y) - b.z))); + })hlsl"}, + // Sizes: the console compiler computes them from descriptor bits + // (width, height, levels, record counts). + {"sizes from descriptors", R"hlsl(CS { + uint w, h, l, n, b, ns, st; + tex.GetDimensions(0, w, h, l); + typed.GetDimensions(n); + raw.GetDimensions(b); + structured.GetDimensions(ns, st); + // Read too: the translation takes the views' kinds from those reads. + float r = tex.Load(int3(d.xy & 3, 0)).x + typed[i & 15].y + structured[i & 7].a; + outb.Store4(16 * (d.y * 16 + d.x), + uint4(w * 7 + h, l + asuint(r), n * 5 + ns * 3 + st, b + raw.Load(4 * (i & 31)))); + })hlsl"}, + // Typed loads (`tbuffer_load_format_*`, the title's vertex + // fetch) convert by the format the instruction names: the PC reads the + // same bytes through typed views in those formats. Channels past the + // format's read (0, 0, 0, 1); a byte format at unaligned offsets. + {"typed loads", R"hlsl(CS { + uint n = d.y * 16 + d.x, e = n & 31, f = n >> 5; + uint4 a, b, c, dd, ee, ff, gg, hh; + #ifdef CONSOLE + a = raw.XB_TypedLoad4(4 * e, FMT(0, 10)); + b = raw.XB_TypedLoad4(4 * e, FMT(1, 5)); + c = raw.XB_TypedLoad4(4 * e, FMT(4, 10)); + dd = raw.XB_TypedLoad4(4 * e, FMT(0, 9)); + ee = raw.XB_TypedLoad4(8 * (e & 15), FMT(4, 12)); + ff = uint4(raw.XB_TypedLoad((3 * e) & 127, FMT(0, 1)), 0, 0, 0); + gg = uint4(raw.XB_TypedLoad2(2 * e, FMT(7, 2)), 0, 0); + hh = raw.XB_TypedLoad4(4 * e, FMT(1, 10)); + #else + a = asuint(unorm8x4[e]); + b = asuint(snorm16x2[e]); + c = uint8x4[e]; + dd = asuint(unorm10x3_2[e]); + ee = uint16x4[e & 15]; + ff = uint4(asuint(unorm8[(3 * e) & 127]), 0, 0, 0); + gg = uint4(asuint(half16[e]), 0, 0, 0); + hh = asuint(snorm8x4[e]); + #endif + uint4 v = f == 0 ? a : f == 1 ? b : f == 2 ? c : f == 3 ? dd + : f == 4 ? ee : f == 5 ? ff : f == 6 ? gg : hh; + outb.Store4(16 * n, v); + })hlsl"}, + // Wave operations: the console expands them into whole-wave sections + // (DPP, `v_permlanex16`, lane reads) and lane masks read as numbers + // (`s_bcnt1`, `s_ff1`, `v_mbcnt`). 32 threads: one wave on the console + // (lanes 32-63 inactive) and on the host; the branch leaves lanes out. + {"wave operations", R"hlsl([RootSignature(RS)] [numthreads(8, 4, 1)] + void cs(uint3 d : SV_DispatchThreadID, uint i : SV_GroupIndex) { + uint n = d.y * 16 + d.x; + float v = d.x * k.x + d.y; + uint u = raw.Load(4 * (i & 31)); + uint4 o = 0; + if (u & 3) { + o.x = WaveActiveSum(u >> 8) + WaveActiveCountBits((u & 4) != 0); + o.y = asuint(WaveActiveMax(v)) ^ WaveActiveMin(u) ^ WaveActiveBitOr(u) + ^ WaveActiveBitAnd(u | 1) ^ asuint(WaveActiveMin(v)) ^ WaveActiveMax(int(u)); + o.z = WavePrefixSum(u & 255) + WavePrefixCountBits(v > 2) * 1000; + // (The PC compile evaluates a wave operation in a `?:` arm + // in that arm's lanes only, so it stays outside.) + o.w = asuint(WaveActiveSum(v)) + (WaveIsFirstLane() ? WaveReadLaneFirst(u) : 0); + } + outb.Store4(16 * n, o); + })hlsl"}, + // Atomics the console aggregates per wave (one add of the lane count, + // each lane's offset from `v_mbcnt`), and texture atomics. Results + // that depend on the lanes' order are left out. + {"aggregated and texture atomics", R"hlsl(CS { + uint u = raw.Load(4 * (i & 31)), r, q; + outb.InterlockedAdd(0, 1, r); + outb.InterlockedAdd(4 * (1 + r % 8), 1); + if (u & 1) outb.InterlockedAdd(64, u & 255); + uint2 p = d.xy & 3; + InterlockedMax(ut[p], u); + InterlockedOr(ut[p + uint2(4, 0)], u >> (i & 7)); + InterlockedMin(ut[p + uint2(8, 0)], u); + InterlockedAdd(ut[p + uint2(12, 0)], u & 15, q); + InterlockedXor(ut[p + uint2(0, 4)], u); + })hlsl"}, + // A loop whose count comes from a view that reads zeros (as a null or + // not yet mirrored one does) runs four billion times on the console; + // the translation leaves it after `LOOP_LIMIT` iterations. Run on WARP + // only (`X2W_SHADERCFG_WARP=1`), ours only: without the limit it would hang + // the GPU. + {"terminates on zero data", R"hlsl(CS { + uint cnt = outb.Load(4 * 1000), s = d.x; + for (uint j = 0; j != cnt - 1; j++) s = s * 3 + raw.Load(4 * (j & 31)); + outb.Store(4 * (d.y * 16 + d.x), s); + })hlsl"}, + // Cube sampling: the console computes face coordinates (`v_cube*`) + // and samples the face; the host samples the direction rebuilt from + // them. Every face and texel: a major axis of +-2 and the others at + // texel centres, so both sides compute them exactly. + {"cube sampling", R"hlsl(CS { + float sg = (i & 8) ? -2 : 2; + float a = (d.x & 3) - 1.5, b = (d.y & 3) - 1.5; + uint ax = i % 3; + float3 dir = ax == 0 ? float3(sg, a, b) : ax == 1 ? float3(a, sg, b) : float3(a, b, sg); + float4 p = cubet.SampleLevel(smp, dir, 0); + float4 q = cubet.SampleLevel(smp, -dir.zxy, 0); + outb.Store4(16 * (d.y * 16 + d.x), asuint(p + q * 3)); + })hlsl"}, + // A local array indexed per lane (M0-relative VGPR moves), bit fields + // and first bits from the top. + {"indexed registers and bit fields", R"hlsl(CS { + uint n = d.y * 16 + d.x; + uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 5) & 31)); + uint arr[24]; + [unroll] for (uint j = 0; j < 24; j++) arr[j] = x ^ (j * 0x01010101); + [loop] for (uint m = 0; m < (y & 3); m++) arr[(y >> (m * 5)) % 24] = y + m; + uint v = arr[(x >> 3) % 24]; + uint w = asuint(k.x) & 31, o = n & 15; + uint bf = (x & ((1u << w) - 1)) << o; + uint fb = firstbithigh(asuint(k.y)) + firstbithigh(x) * 3 + firstbithigh(int(y)) * 7; + outb.Store4(16 * n, uint4(v, bf, fb, arr[n % 24])); + })hlsl"}, + // Size queries at a level known per lane (`image_get_resinfo`). + {"size queries", R"hlsl(CS { + uint w, h, l, cw, ch, cl; + tex.GetDimensions(d.x >> 4, w, h, l); + cubet.GetDimensions(d.y >> 4, cw, ch, cl); + float r = tex.Load(int3(d.xy & 3, 0)).x; + outb.Store4(16 * (d.y * 16 + d.x), uint4(w * 7 + h, l + asuint(r), cw * 3 + ch, cl)); + })hlsl"}, + // Gathers with offsets computed per lane (programmable offsets). + {"gather with offsets", R"hlsl(CS { + int2 o = int2(int(d.x & 7) - 4, int(d.y % 5) - 2); + float4 r = tex.GatherRed(smp, (d.xy + 0.5) / 16.0, o); + float4 q = tex.GatherGreen(smp, (d.yx + 0.25) / 16.0, -o); + outb.Store4(16 * (d.y * 16 + d.x), asuint(r + q * 3)); + })hlsl"}, + // Constant arrays: the console compiler appends them to the code and + // reads them through `s_getpc_b64` (scalar loads for a uniform index, + // global loads per lane, 16-bit ones too). + {"constant tables", R"hlsl(static const uint tbl[16] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3 }; + static const float ftbl[8] = { 0.5, -1, 2.25, 3, -4.5, 6, 7.75, -8 }; + // (16-bit types: compiled with half precision enabled.) + static const uint16_t stbl[12] = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 65535 }; + CS { + uint n = d.y * 16 + d.x; + uint u = asuint(k.x) & 15; + uint a = tbl[i & 15] ^ tbl[u] << 8; + float f = ftbl[(i * 3) & 7] * ftbl[u & 7]; + uint h = stbl[(n * 5) % 12] + stbl[u % 12]; + outb.Store4(16 * n, uint4(a, asuint(f), h, tbl[(n + u) & 15])); + })hlsl"}, + // 16-bit arithmetic (scalar and packed), 16-bit compares, typed stores + // of halves (`buffer_store_format_d16`), 64-bit shifts and compares. + {"16-bit and 64-bit arithmetic", R"hlsl(RWBuffer<half4> hb : register(u3); + CS { + uint n = d.y * 16 + d.x; + uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 7) & 31)); + half a = half(d.x * k.x - 2), b = half(d.y + k.y), c = half(k.z); + half2 p = half2(a, b) * half2(b, c) + half2(c, a); + half m = max(a, b) - min(a, c) * a; + bool lt = a < b, ge = p.x >= p.y; + hb[n] = half4(p.x, m, lt ? a : b, ge ? p.y : a - b); + uint64_t q = (uint64_t(x) << (n & 31)) | y, w = uint64_t(y) << 3; + uint z = q < w ? 1 : q == w ? 2 : 3; + outb.Store2(8 * n, uint2(uint(q >> 7) ^ z, uint(w >> (n & 15)))); + })hlsl"}, +}; + +const MeshCase MS_CASES[] = { + {"one triangle", 1, R"hlsl(MS_ATTR [numthreads(32, 1, 1)] + void ms(uint i : SV_GroupIndex, out vertices V verts[3], out indices uint3 tris[1]) { + SetMeshOutputCounts(3, 1); + if (i < 3) { + verts[i].pos = float4(i == 1 ? 3 : -1, i == 2 ? 3 : -1, 0.5, 1); + verts[i].col = float4(k.x * i, k.y, k.z * (i == 2), 1); + verts[i].uv = float2(i * 0.5, k.w); + } + if (i == 0) tris[0] = uint3(0, 1, 2); + })hlsl"}, + // A quad per group in its quadrant; a run-time vertex count, and a + // primitive count per group whose third triangle is culled. + {"groups, counts and culling", 4, R"hlsl(struct P { bool cull : SV_CullPrimitive; }; + MS_ATTR [numthreads(64, 1, 1)] + void ms(uint i : SV_GroupIndex, uint3 g : SV_GroupID, out vertices V verts[8], + out indices uint3 tris[4], out primitives P prims[4]) { + uint nv = 4 + (k.z > 1); + uint np = 2 + (g.x & 1); + SetMeshOutputCounts(nv, np); + float2 o = float2(g.x & 1, g.x >> 1) - 1; + if (i < nv) { + float2 p = i < 4 ? float2(i & 1, i >> 1) : float2(-0.75, 0.5); + verts[i].pos = float4(o + p, 0.5, 1); + verts[i].col = float4(k.x * i, g.x * 0.25, k.z, 1); + verts[i].uv = float2(i, g.x); + } + if (i < np) { + tris[i] = i == 0 ? uint3(0, 1, 2) : i == 1 ? uint3(1, 3, 2) : uint3(1, 4, 3); + prims[i].cull = i == 2; + } + })hlsl"}, + // Two waves per group, as the title's mesh programs run: the + // second wave's lanes are threads 64-127. + {"two waves", 1, R"hlsl(MS_ATTR [numthreads(128, 1, 1)] + void ms(uint i : SV_GroupIndex, out vertices V verts[81], out indices uint3 tris[128]) { + SetMeshOutputCounts(81, 128); + if (i < 81) { + float2 p = float2(i % 9, i / 9) / 8.0; + verts[i].pos = float4(p * 2 - 1, 0.5, 1); + verts[i].col = float4(p.x * k.x, p.y, (i & 7) * 0.125, 1); + verts[i].uv = float2(i, k.y); + } + uint c = i / 2 % 8 + i / 16 * 9; + tris[i] = i & 1 ? uint3(c + 1, c + 10, c + 9) : uint3(c, c + 1, c + 9); + })hlsl"}, + // Quad reads (DPP quad permutations on the console; the title's + // tessellating mesh programs swizzle within quads too). + {"quad reads", 1, R"hlsl(MS_ATTR [numthreads(128, 1, 1)] + void ms(uint i : SV_GroupIndex, out vertices V verts[81], out indices uint3 tris[128]) { + SetMeshOutputCounts(81, 128); + float w = i * k.x + k.y; + float a = QuadReadLaneAt(w, 0); + float b = QuadReadLaneAt(w, 2); + float c = QuadReadAcrossX(w); + if (i < 81) { + float2 p = float2(i % 9, i / 9) / 8.0; + verts[i].pos = float4(p * 2 - 1, 0.5, 1); + verts[i].col = float4(a, b, c, 1); + verts[i].uv = float2(i, k.y); + } + uint cc = i / 2 % 8 + i / 16 * 9; + tris[i] = i & 1 ? uint3(cc + 1, cc + 10, cc + 9) : uint3(cc, cc + 1, cc + 9); + })hlsl"}, + // Vertices and indices written by other threads than their lanes: the + // console passes them through shared memory, with a loop and barriers. + {"grid through shared memory", 2, R"hlsl(MS_ATTR [numthreads(32, 1, 1)] + void ms(uint i : SV_GroupIndex, uint3 g : SV_GroupID, out vertices V verts[36], + out indices uint3 tris[64]) { + SetMeshOutputCounts(36, 50); + for (uint v = i; v < 36; v += 32) { + float2 p = float2(v % 6, v / 6) / 5.0; + verts[v].pos = float4(p.x - g.x, p.y * 2 - 1, 0.5, 1); + verts[v].col = float4(p * k.x, k.z * g.x, 1); + verts[v].uv = float2(v, k.y); + } + if (i < 25) { + uint c = i % 5 + i / 5 * 6; + tris[2 * i] = uint3(c, c + 1, c + 6); + tris[2 * i + 1] = uint3(c + 1, c + 7, c + 6); + } + })hlsl"}, +}; + +// A Rust panic: fails the test function. +[[noreturn]] void panic(const std::string& what) { throw std::logic_error(what); } + +std::optional<std::string> env(const char* name) { + if (const char* v = std::getenv(name)) return std::string(v); + return std::nullopt; +} + +bool is_warp() { return env("X2W_SHADERCFG_WARP") == std::optional<std::string>("1"); } + +// Rust's `{}` (Display) of an f32: the shortest decimal that reads back, never an exponent. +std::string display(float x) { + if (std::isnan(x)) return "NaN"; + if (std::isinf(x)) return x < 0 ? "-inf" : "inf"; + char b[128]; + auto r = std::to_chars(b, b + sizeof b, x, std::chars_format::fixed); + return std::string(b, r.ptr); +} + +// Rust's `{:?}` (Debug) of an f32: as Display with ".0" on whole numbers, in exponent form +// below 1e-4 and from 1e16. +std::string f32_debug(float x) { + if (std::isnan(x) || std::isinf(x)) return display(x); + const float a = std::fabs(x); + if (a != 0.0f && (a < 1e-4f || a >= 1e16f)) { + char b[64]; + auto r = std::to_chars(b, b + sizeof b, x, std::chars_format::scientific); + std::string s(b, r.ptr); + // "1.5e-05" -> "1.5e-5", "1e+30" -> "1e30". + const std::size_t e = s.find('e'); + std::string mant = s.substr(0, e), ex = s.substr(e + 1); + bool neg = !ex.empty() && ex[0] == '-'; + if (!ex.empty() && (ex[0] == '-' || ex[0] == '+')) ex.erase(0, 1); + while (ex.size() > 1 && ex[0] == '0') ex.erase(0, 1); + return mant + "e" + (neg ? "-" : "") + ex; + } + std::string s = display(x); + if (s.find('.') == std::string::npos) s += ".0"; + return s; +} + +// Rust's `{:.2e}` of an f32. +std::string rust_exp(float x) { + if (std::isnan(x)) return "NaN"; + if (std::isinf(x)) return x < 0 ? "-inf" : "inf"; + char b[64]; + std::snprintf(b, sizeof b, "%.2e", double(x)); + std::string s(b); + const std::size_t e = s.find('e'); + std::string mant = s.substr(0, e), ex = s.substr(e + 1); + bool neg = ex[0] == '-'; + ex.erase(0, 1); + while (ex.size() > 1 && ex[0] == '0') ex.erase(0, 1); + return mant + "e" + (neg ? "-" : "") + ex; +} + +std::string hex(std::uint32_t v) { + char b[16]; + std::snprintf(b, sizeof b, "0x%x", v); + return b; +} + +// f32::total_cmp's key: -NaN < -inf < ... < -0 < +0 < ... < +inf < +NaN. +std::int32_t total_key(float x) { + std::int32_t v = std::bit_cast<std::int32_t>(x); + v ^= std::int32_t(std::uint32_t(v >> 31) >> 1); + return v; +} + +// f32::max(1.0): NaN gives the other. +float max1(float x) { return std::isnan(x) ? 1.0f : std::max(x, 1.0f); } + +std::optional<std::pair<fs::path, fs::path>> tools() { + const std::optional<std::string> c = env("X2W_SHADERCFG_CONSOLE_DXC"); + if (!c) return std::nullopt; + const fs::path console(*c); + fs::path pc; + if (const std::optional<std::string> p = env("X2W_SHADERCFG_PC_DXC")) { + pc = *p; + } else { + std::optional<fs::path> d = Validator::default_path(); + if (!d) return std::nullopt; + pc = d->replace_filename("dxc.exe"); + } + if (fs::exists(console) && fs::exists(pc)) return std::pair{console, pc}; + return std::nullopt; +} + +std::vector<std::uint8_t> read_file(const fs::path& p) { + std::ifstream in(p, std::ios::binary); + if (!in) panic("cannot read " + p.string()); + return std::vector<std::uint8_t>((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); +} + +void write_file(const fs::path& p, std::span<const std::uint8_t> bytes) { + std::ofstream out(p, std::ios::binary); + out.write(reinterpret_cast<const char*>(bytes.data()), std::streamsize(bytes.size())); + if (!out) panic("cannot write " + p.string()); +} + +std::vector<std::uint8_t> compile(const fs::path& dxc, const fs::path& dir, std::string_view src, std::string_view entry, + const char* profile) { + const fs::path input = dir / "t.hlsl"; + const fs::path output = dir / (std::string(entry) + ".bin"); + const fs::path log = dir / "dxc.log"; + std::string text; + if (entry == "cs") { + text = std::string("#define RS \"") + CS_RS + "\"\n" + CS_COMMON + "\n" + std::string(src) + "\n"; + } else if (entry.starts_with('m')) { + text = std::string(MS_COMMON) + "\n" + std::string(src) + "\n"; + } else { + text = std::string("#define RS \"") + RS + "\"\n" + COMMON + "\n" + std::string(src) + "\n"; + } + write_file(input, std::span(reinterpret_cast<const std::uint8_t*>(text.data()), text.size())); + std::string cmd = "\"\"" + dxc.string() + "\" -T " + profile + " -E " + std::string(entry) + " -Fo \"" + + output.string() + "\" \"" + input.string() + "\""; + if (src.find("half") != std::string_view::npos) cmd += " -enable-16bit-types"; + // `CONSOLE` marks the console compile (cases spell console-only intrinsics there). + if (const std::optional<std::string> c = env("X2W_SHADERCFG_CONSOLE_DXC"); c && fs::path(*c) == dxc) cmd += " -DCONSOLE"; + // The whole command quoted once more: cmd.exe strips the outer pair. Output captured, as + // Rust's Command::output. + cmd += " > \"" + log.string() + "\" 2>&1\""; + const int rc = std::system(cmd.c_str()); + if (rc != 0) { + std::ifstream in(log, std::ios::binary); + std::string err((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); + panic(err); + } + return read_file(output); +} + +// Root arguments for a translated stage: user data from the root values. +std::vector<std::uint32_t> user_data(const HostShader& s, const std::array<std::uint32_t, 4>& k) { + std::vector<std::uint32_t> data(std::max<std::size_t>(s.user_data_dwords(), 1), 0); + using Kd = native::RootType::Kind; + for (const UserData& u : s.user_data) { + std::uint32_t v; + if (u.root.kind == Kd::Constants && u.slot == 0) { + v = k.at(u.dword); + } else if (u.root.kind == Kd::Table && u.slot == 1) { + // The texture and sampler tables start at heap index 1, the UAV table (compute) at + // 5, in the console's units. + v = 32; + } else if (u.root.kind == Kd::Table && u.slot == 2) { + v = 16; + } else if (u.root.kind == Kd::Table && u.slot == 3) { + v = 5 * 32; + } else if (u.root.kind == Kd::Table && u.slot == 6) { + // The typed views of `raw` (compute) from 9. + v = 9 * 32; + } else { + panic("unexpected user data (root kind " + std::to_string(int(u.root.kind)) + ", other " + + std::to_string(u.root.other) + ", slot " + std::to_string(u.slot) + ")"); + } + data.at(u.index) = v; + } + return data; +} + +// Rust's `name.replace([' ', ','], "_")`. +std::string stem_of(const char* name) { + std::string s(name); + for (char& c : s) + if (c == ' ' || c == ',') c = '_'; + return s; +} + +// Validates a copy of dxil when the validator is there; a rejection panics. +void validate_if_there(const std::vector<std::uint8_t>& dxil, const char* name) { + if (std::optional<Validator> v = Validator::load(Validator::default_path())) { + std::vector<std::uint8_t> copy = dxil; + if (std::optional<std::string> e = v->validate(copy)) panic(std::string(name) + ": " + *e); + } +} + +host::ComPtr<ID3D12RootSignature> pc_root(const Host& host, const std::vector<std::uint8_t>& container) { + // The PC container carries its root signature. + host::ComPtr<ID3D12RootSignature> root; + const HRESULT hr = host.device->CreateRootSignature(0, container.data(), container.size(), IID_PPV_ARGS(&root)); + if (FAILED(hr)) throw host::Error(host::message(hr)); + return root; +} + +std::uint32_t bits(float f) { return std::bit_cast<std::uint32_t>(f); } + +const std::array<std::uint32_t, 4> K = {bits(0.75f), bits(-1.5f), bits(2.0f), bits(0.125f)}; + +// (relative difference, index, ours, theirs) of the worst texel channel: Rust's max_by with +// total_cmp (NaN highest, the last of equal ones). +struct Worst { + float rel; + std::size_t at; + float a, b; + std::string debug() const { + return "(" + f32_debug(rel) + ", " + std::to_string(at) + ", " + f32_debug(a) + ", " + f32_debug(b) + ")"; + } +}; + +Worst worst_of(const std::vector<std::array<float, 4>>& ours, const std::vector<std::array<float, 4>>& theirs) { + std::optional<Worst> w; + const std::size_t n = std::min(ours.size(), theirs.size()) * 4; + for (std::size_t i = 0; i < n; ++i) { + const float a = ours[i / 4][i % 4], b = theirs[i / 4][i % 4]; + const float rel = std::fabs(a - b) / max1(std::fabs(b)); + if (!w || total_key(rel) >= total_key(w->rel)) w = Worst{rel, i, a, b}; + } + if (!w) panic("no texels"); + return *w; +} + +bool selected(const std::optional<std::string>& only, const char* name) { return !only || *only == name; } + +void report(const std::vector<std::string>& failures) { + for (const std::string& f : failures) std::fprintf(stderr, " %s\n", f.c_str()); + CHECK(failures.empty()); +} + +void translated_shaders_draw_as_pc_ones() { + const auto t = tools(); + if (!t) { + std::fprintf(stderr, "no console or PC compiler; skipped\n"); + return; + } + const auto& [console, pc] = *t; + std::optional<Host> h; + try { + h.emplace(false); + } catch (const host::Error& e) { + std::fprintf(stderr, "no SM 6.6 device (%s); skipped\n", e.what()); + return; + } + const Host& host = *h; + const fs::path dir = fs::temp_directory_path() / ("gpu-diff-" + std::to_string(GetCurrentProcessId())); + fs::create_directories(dir); + std::vector<std::array<float, 4>> texels; + for (int i = 0; i < 16; ++i) + texels.push_back({float(i) / 16.0f, float(i % 4) * 0.3f, 1.0f - float(i) / 20.0f, 0.5f}); + const std::array<float, 4> dummy[] = {{9.0f, 9.0f, 9.0f, 9.0f}}; + auto sampler = [](D3D12_FILTER filter, D3D12_TEXTURE_ADDRESS_MODE address) { + D3D12_SAMPLER_DESC d{}; + d.Filter = filter; + d.AddressU = address; + d.AddressV = address; + d.AddressW = address; + d.MaxAnisotropy = 1; + d.MaxLOD = std::numeric_limits<float>::max(); + return d; + }; + const D3D12_SAMPLER_DESC samplers[] = { + sampler(D3D12_FILTER_MIN_MAG_MIP_POINT, D3D12_TEXTURE_ADDRESS_MODE_CLAMP), + sampler(D3D12_FILTER_MIN_MAG_MIP_LINEAR, D3D12_TEXTURE_ADDRESS_MODE_WRAP), + }; + // A full-screen triangle: POSITION (4 floats), TEXCOORD0 (2 floats). + const float vertices[] = { + -1.0f, -1.0f, 0.5f, 1.0f, 0.0f, 1.0f, // + -1.0f, 3.0f, 0.5f, 1.0f, 0.0f, -1.0f, // + 3.0f, -1.0f, 0.5f, 1.0f, 2.0f, 1.0f, + }; + const host::Texture textures[] = {{1, 1, dummy}, {4, 4, texels}}; + auto draw = [&](std::vector<std::pair<std::uint32_t, Root>> roots) { + Draw d; + d.roots = std::move(roots); + d.textures = textures; + d.samplers = samplers; + d.vertices = vertices; + d.stride = 24; + d.size = {16, 16}; + d.mesh_groups = 0; + return d; + }; + std::vector<std::string> failures; + const std::optional<std::string> only = env("X2W_SHADERCFG_DIFF_ONLY"); + for (const Case& c : CASES) { + if (!selected(only, c.name)) continue; + const char* name = c.name; + const std::string_view src = c.src; + // A case may bring its own vertex shader. + const char* vs = src.find(" vs16(") != std::string_view::npos ? "vs16" : "vs"; + const HostShader vs_c = translate(compile(console, dir, src, vs, "vs_6_5")); + HostShader ps_c; + try { + ps_c = translate(compile(console, dir, src, "ps", "ps_6_5")); + } catch (const ShaderError& e) { + failures.push_back(std::string(name) + ": " + e.what()); + continue; + } + if (const std::optional<std::string> out = env("X2W_SHADERCFG_EMIT_DUMP")) { + const std::string stem = stem_of(name); + write_file(fs::path(*out) / (stem + ".ps.cdxil"), compile(console, dir, src, "ps", "ps_6_5")); + write_file(fs::path(*out) / (stem + ".ps.dxil"), ps_c.dxil); + } + if (std::optional<Validator> v = Validator::load(Validator::default_path())) { + for (const HostShader* s : std::array<const HostShader*, 2>{&vs_c, &ps_c}) { + std::vector<std::uint8_t> copy = s->dxil; + if (std::optional<std::string> e = v->validate(copy)) panic(std::string(name) + ": " + *e); + } + } + const auto [root_t, pso_t] = host.pipeline(vs_c, ps_c); + std::vector<std::pair<std::uint32_t, Root>> roots_t; + roots_t.emplace_back(0, Root::constants(user_data(vs_c, K))); + roots_t.emplace_back(1, Root::constants(user_data(ps_c, K))); + const auto ours = host.draw(root_t.Get(), pso_t.Get(), draw(std::move(roots_t))); + + const std::vector<std::uint8_t> vs_p = compile(pc, dir, src, vs, "vs_6_5"); + const std::vector<std::uint8_t> ps_p = compile(pc, dir, src, "ps", "ps_6_5"); + const auto root_p = pc_root(host, ps_p); + const auto pso_p = host.pipeline_with(root_p.Get(), vs_p, ps_p); + std::vector<std::pair<std::uint32_t, Root>> roots_p; + roots_p.emplace_back(0, Root::constants(std::vector<std::uint32_t>(K.begin(), K.end()))); + roots_p.emplace_back(1, Root::table(false, 1)); + roots_p.emplace_back(2, Root::table(true, 1)); + const auto theirs = host.draw(root_p.Get(), pso_p.Get(), draw(std::move(roots_p))); + + const Worst worst = worst_of(ours, theirs); + std::fprintf(stderr, "%s: worst relative difference %s (at %zu: %s vs %s)\n", name, rust_exp(worst.rel).c_str(), + worst.at, display(worst.a).c_str(), display(worst.b).c_str()); + if (std::isnan(worst.rel) || worst.rel > 1e-3f) failures.push_back(std::string(name) + ": " + worst.debug()); + } + std::error_code ec; + fs::remove_all(dir, ec); + report(failures); +} + +void translated_mesh_shaders_draw_as_pc_ones() { + const auto t = tools(); + if (!t) { + std::fprintf(stderr, "no console or PC compiler; skipped\n"); + return; + } + const auto& [console, pc] = *t; + std::optional<Host> h; + try { + h.emplace(false); + } catch (const host::Error& e) { + std::fprintf(stderr, "no SM 6.6 device (%s); skipped\n", e.what()); + return; + } + const Host& host = *h; + const fs::path dir = fs::temp_directory_path() / ("gpu-diff-ms-" + std::to_string(GetCurrentProcessId())); + fs::create_directories(dir); + auto draw = [&](std::vector<std::pair<std::uint32_t, Root>> roots, std::uint32_t mesh_groups) { + Draw d; + d.roots = std::move(roots); + d.stride = 0; + d.size = {16, 16}; + d.mesh_groups = mesh_groups; + return d; + }; + std::vector<std::string> failures; + const std::optional<std::string> only = env("X2W_SHADERCFG_DIFF_ONLY"); + for (const MeshCase& c : MS_CASES) { + if (!selected(only, c.name)) continue; + const char* name = c.name; + const std::uint32_t groups = c.groups; + const std::string_view src = c.src; + const std::vector<std::uint8_t> console_ms = compile(console, dir, src, "ms", "ms_6_5"); + HostShader ms_c; + try { + ms_c = translate(console_ms); + } catch (const ShaderError& e) { + failures.push_back(std::string(name) + ": " + e.what()); + continue; + } + const HostShader ps_c = translate(compile(console, dir, src, "mps", "ps_6_5")); + if (const std::optional<std::string> out = env("X2W_SHADERCFG_EMIT_DUMP")) { + const std::string stem = stem_of(name); + write_file(fs::path(*out) / (stem + ".ms.cdxil"), console_ms); + write_file(fs::path(*out) / (stem + ".ms.dxil"), ms_c.dxil); + } + validate_if_there(ms_c.dxil, name); + const auto [root_t, pso_t] = host.mesh_pipeline(ms_c, ps_c); + std::vector<std::pair<std::uint32_t, Root>> roots_t; + roots_t.emplace_back(0, Root::constants(user_data(ms_c, K))); + roots_t.emplace_back(1, Root::constants(user_data(ps_c, K))); + const auto ours = host.draw(root_t.Get(), pso_t.Get(), draw(std::move(roots_t), groups)); + const std::vector<std::uint8_t> ms_p = compile(pc, dir, src, "ms", "ms_6_5"); + const std::vector<std::uint8_t> ps_p = compile(pc, dir, src, "mps", "ps_6_5"); + const auto root_p = pc_root(host, ms_p); + const auto pso_p = host.mesh_pipeline_with(root_p.Get(), ms_p, ps_p); + std::vector<std::pair<std::uint32_t, Root>> roots_p; + roots_p.emplace_back(0, Root::constants(std::vector<std::uint32_t>(K.begin(), K.end()))); + const auto theirs = host.draw(root_p.Get(), pso_p.Get(), draw(std::move(roots_p), groups)); + const Worst worst = worst_of(ours, theirs); + const std::size_t drawn = std::size_t(std::count_if(theirs.begin(), theirs.end(), [](const auto& x) { return x[3] != 0.0f; })); + std::fprintf(stderr, "%s: %zu texels drawn; worst relative difference %s (at %zu: %s vs %s)\n", name, drawn, + rust_exp(worst.rel).c_str(), worst.at, display(worst.a).c_str(), display(worst.b).c_str()); + if (std::isnan(worst.rel) || worst.rel > 1e-3f || drawn == 0) { + // Which texels each drew (alpha set), row by row. + auto row = [](const std::vector<std::array<float, 4>>& v, std::size_t from) { + std::string s; + for (std::size_t i = from; i < from + 16 && i < v.size(); ++i) s += v[i][3] != 0.0f ? '#' : '.'; + return s; + }; + for (std::size_t r = 0; r < ours.size() && r < theirs.size(); r += 16) + std::fprintf(stderr, " %s %s\n", row(ours, r).c_str(), row(theirs, r).c_str()); + failures.push_back(std::string(name) + ": " + worst.debug()); + } + } + std::error_code ec; + fs::remove_all(dir, ec); + report(failures); +} + +// Where PC code and the console differ by design, the translation must give the console's +// results: float-to-int conversions saturate and give 0 for NaN (v_cvt_i32/u32_f32), the legacy +// multiply the compiler uses for `*` gives 0 for 0 x NaN, `frac` never reaches 1.0 (it gives the +// largest value below; some hosts' own `frac` gives 1.0), and sine and cosine take turns: the +// sine of a half turn and the cosine of a quarter turn are exactly +0 (the host's functions of +// the rounded angle give about 1e-7). The compiler takes whole turns off itself, so large angles +// cannot be tried from here. +void float_semantics_are_the_consoles() { + const auto t = tools(); + if (!t) { + std::fprintf(stderr, "no console compiler; skipped\n"); + return; + } + const fs::path& console = t->first; + std::optional<Host> h; + try { + h.emplace(false); + } catch (const host::Error& e) { + std::fprintf(stderr, "no SM 6.6 device (%s); skipped\n", e.what()); + return; + } + const Host& host = *h; + const fs::path dir = fs::temp_directory_path() / ("gpu-float-" + std::to_string(GetCurrentProcessId())); + fs::create_directories(dir); + const char* src = R"hlsl([RootSignature(RS)] [numthreads(4, 1, 1)] + void cs(uint i : SV_GroupIndex) { + float x = i == 0 ? k.x : i == 1 ? -k.x : i == 2 ? k.y : k.z; + outb.Store(4 * i, asuint(int(x))); + outb.Store(16 + 4 * i, uint(x)); + outb.Store(32 + 4 * i, asuint(x * k.w)); + float y = i == 0 ? k.w - 1e-10 : i == 1 ? k.z : i == 2 ? k.w - 1e-8 : k.z + 0.25; + outb.Store(48 + 4 * i, asuint(frac(y))); + float r = i == 0 ? k.w + 3.14159274 : i == 1 ? k.w + 1.0 + : i == 2 ? k.w - 3.14159274 : k.w + 1.57079637; + outb.Store(64 + 4 * i, asuint(i == 3 ? cos(r) : sin(r))); + })hlsl"; + const HostShader cs = translate(compile(console, dir, src, "cs", "cs_6_5")); + const auto [root, pso] = host.compute_pipeline(cs); + // 1e30, NaN, 3.5, 0. + const std::array<std::uint32_t, 4> k = {bits(1e30f), 0x7FC0'0000u, bits(3.5f), 0}; + const std::array<float, 4> zero[] = {{0.0f, 0.0f, 0.0f, 0.0f}}; + const View views[] = { + View::texture(1, 1, zero), View::texture(1, 1, zero), View::texture(1, 1, zero), + View::texture(1, 1, zero), View::texture(1, 1, zero), View::raw_uav(20), + View::texture_uav(1, 1), + }; + Dispatch d; + d.roots.emplace_back(0, Root::constants(user_data(cs, k))); + d.views = views; + d.groups = {1, 1, 1}; + const auto out = host.dispatch(root.Get(), pso.Get(), d); + std::error_code ec; + fs::remove_all(dir, ec); + if (out.empty() || out[0].size() < 20) panic("float_semantics_are_the_consoles: short output"); + const std::vector<std::uint32_t> want = { + 0x7FFF'FFFFu, 0x8000'0000u, 0, 3, // int + 0xFFFF'FFFFu, 0, 0, 3, // uint + 0, 0, 0, 0, // x * 0, NaN included + 0x3F7F'FFFFu, bits(0.5f), 0x3F7F'FFFFu, bits(0.75f), // frac + }; + const std::vector<std::uint32_t> got(out[0].begin(), out[0].begin() + 16); + if (got != want) { + for (std::size_t i = 0; i < 16; ++i) + if (got[i] != want[i]) std::fprintf(stderr, "word %zu: %s, want %s\n", i, hex(got[i]).c_str(), hex(want[i]).c_str()); + } + CHECK(got == want); + // sin(pi), sin(-pi) and cos(pi/2): the compiler turns radians into exactly 0.5, -0.5 and 0.25 + // turns. + CHECK(out[0][16] == 0 && out[0][18] == 0 && out[0][19] == 0); + // An ordinary angle is untouched: sin(1 rad). + const float one = std::bit_cast<float>(out[0][17]); + if (!(std::fabs(one - 0.841'470'96f) < 1e-4f)) std::fprintf(stderr, "sin(1) = %s\n", display(one).c_str()); + CHECK(std::fabs(one - 0.841'470'96f) < 1e-4f); +} + +// Equal bits, both zero (the console's legacy multiply gives +0 where PC code gives -0), or two +// normal floats within 1e-3 relative. +bool close_bits(std::uint32_t a, std::uint32_t b) { + const float x = std::bit_cast<float>(a), y = std::bit_cast<float>(b); + return a == b || (x == 0.0f && y == 0.0f) || + (std::isnormal(x) && std::isnormal(y) && std::fabs(x - y) <= 1e-3f * std::max(std::fabs(y), 1.0f)); +} + +void translated_compute_matches_pc() { + const auto t = tools(); + if (!t) { + std::fprintf(stderr, "no console or PC compiler; skipped\n"); + return; + } + const auto& [console, pc] = *t; + std::optional<Host> h; + try { + h.emplace(false); + } catch (const host::Error& e) { + std::fprintf(stderr, "no SM 6.6 device (%s); skipped\n", e.what()); + return; + } + const Host& host = *h; + const fs::path dir = fs::temp_directory_path() / ("gpu-diff-cs-" + std::to_string(GetCurrentProcessId())); + fs::create_directories(dir); + std::vector<std::array<float, 4>> texels; + for (int i = 0; i < 16; ++i) texels.push_back({float(i) / 16.0f, float(i % 4) * 0.3f, 0.5f, 1.0f}); + const std::array<float, 4> dummy[] = {{9.0f, 9.0f, 9.0f, 9.0f}}; + std::vector<std::array<float, 4>> cube_texels; + for (int i = 0; i < 96; ++i) + cube_texels.push_back({float(i / 16), float(i % 4) * 0.25f, float(i / 4 % 4) * 0.25f, 1.0f}); + // Buffers: 16 float4, 8 structures of 16 bytes, 32 raw dwords; the root CBV's 16 float4 and + // the root SRV's 32 dwords. + auto floats = [](std::size_t n, float scale) { + std::vector<std::uint32_t> v; + for (std::size_t i = 0; i < n; ++i) v.push_back(bits(float(i) * scale - 3.0f)); + return v; + }; + const std::vector<std::uint32_t> typed_data = floats(64, 0.25f); + std::vector<std::uint32_t> structured_data; + for (std::uint32_t i = 0; i < 32; ++i) + structured_data.push_back(i % 4 == 1 ? i * 0x0101'0101u : bits(float(i) * 0.5f)); + std::vector<std::uint32_t> raw_data; + for (std::uint32_t i = 0; i < 32; ++i) raw_data.push_back(i * 0x9E37'79B9u); // wrapping + auto typed_view = [&](DXGI_FORMAT format, std::uint32_t bytes) { + return View::buffer(raw_data, Stride::format_of(format, bytes)); + }; + const std::vector<View> views = { + View::texture(1, 1, dummy), + View::texture(4, 4, texels), + View::buffer(typed_data, Stride::typed()), + View::buffer(structured_data, Stride::structured(16)), + View::buffer(raw_data, Stride::raw()), + View::raw_uav(1024), + View::texture_uav(16, 16), + View::uint_texture_uav(16, 16), + View::half_uav(256), + typed_view(DXGI_FORMAT_R8G8B8A8_UNORM, 4), + typed_view(DXGI_FORMAT_R16G16_SNORM, 4), + typed_view(DXGI_FORMAT_R8G8B8A8_UINT, 4), + typed_view(DXGI_FORMAT_R10G10B10A2_UNORM, 4), + typed_view(DXGI_FORMAT_R16G16B16A16_UINT, 8), + typed_view(DXGI_FORMAT_R8_UNORM, 1), + typed_view(DXGI_FORMAT_R16_FLOAT, 2), + typed_view(DXGI_FORMAT_R8G8B8A8_SNORM, 4), + View::cube(4, 1, cube_texels), + }; + const std::vector<std::uint32_t> root_cbv = floats(64, -0.125f); + std::vector<std::uint32_t> root_srv; + for (std::uint32_t i = 0; i < 32; ++i) root_srv.push_back(i * 0x0001'0003u + 7); + D3D12_SAMPLER_DESC sd{}; + sd.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + sd.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sd.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sd.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sd.MaxAnisotropy = 1; + sd.MaxLOD = std::numeric_limits<float>::max(); + const D3D12_SAMPLER_DESC samplers[] = {sd, sd}; + auto dispatch = [&](std::vector<std::pair<std::uint32_t, Root>> roots) { + Dispatch d; + d.roots = std::move(roots); + d.views = views; + d.samplers = samplers; + d.groups = {2, 2, 1}; + return d; + }; + std::vector<std::string> failures; + const std::optional<std::string> only = env("X2W_SHADERCFG_DIFF_ONLY"); + const bool warp = is_warp(); + for (const Case& c : CS_CASES) { + const std::string_view cname = c.name; + if (!selected(only, c.name)) continue; + if (!(warp || !cname.starts_with("terminates"))) continue; + const char* name = c.name; + const std::string_view src = c.src; + const std::vector<std::uint8_t> console_cs = compile(console, dir, src, "cs", "cs_6_5"); + if (const std::optional<std::string> out = env("X2W_SHADERCFG_EMIT_DUMP")) + write_file(fs::path(*out) / (stem_of(name) + ".cs.cdxil"), console_cs); + HostShader cs_c; + try { + cs_c = translate(console_cs); + } catch (const ShaderError& e) { + failures.push_back(std::string(name) + ": " + e.what()); + continue; + } + if (const std::optional<std::string> out = env("X2W_SHADERCFG_EMIT_DUMP")) + write_file(fs::path(*out) / (stem_of(name) + ".cs.dxil"), cs_c.dxil); + validate_if_there(cs_c.dxil, name); + host::Pipeline pt; + try { + pt = host.compute_pipeline(cs_c); + } catch (const host::Error& e) { + // WARP runs no fixed wave size of 64. + if (is_warp()) { + std::fprintf(stderr, "%s: skipped on WARP (%s)\n", name, e.what()); + continue; + } + panic(std::string(name) + ": " + e.what()); + } + const auto& [root_t, pso_t] = pt; + // Our root views follow the user data in root parameter order. + std::vector<std::pair<std::uint32_t, Root>> roots; + roots.emplace_back(0, Root::constants(user_data(cs_c, K))); + std::vector<std::pair<std::uint8_t, bool>> root_views; + for (std::uint8_t s : cs_c.root_cbvs) root_views.emplace_back(s, false); + for (std::uint8_t s : cs_c.root_srvs) root_views.emplace_back(s, true); + std::sort(root_views.begin(), root_views.end()); + for (std::size_t n = 0; n < root_views.size(); ++n) { + const auto [slot, srv] = root_views[n]; + if (slot != 4 + std::uint8_t(srv)) + panic(std::string(name) + ": root view: slot " + std::to_string(slot) + ", not " + + std::to_string(4 + int(srv))); + roots.emplace_back(std::uint32_t(1 + n), Root::view(srv, srv ? root_srv : root_cbv)); + } + std::optional<std::vector<std::vector<std::uint32_t>>> ours; + std::string ours_error; + try { + ours = host.dispatch(root_t.Get(), pso_t.Get(), dispatch(std::move(roots))); + } catch (const host::Error& e) { + ours_error = e.what(); + } + if (cname.starts_with("terminates")) { + if (ours) + std::fprintf(stderr, "%s: finished\n", name); + else + failures.push_back(std::string(name) + ": " + ours_error); + continue; + } + if (!ours) panic(ours_error); + const std::vector<std::uint8_t> cs_p = compile(pc, dir, src, "cs", "cs_6_5"); + const auto root_p = pc_root(host, cs_p); + const auto pso_p = host.compute_pipeline_with(root_p.Get(), cs_p); + std::vector<std::pair<std::uint32_t, Root>> roots_p; + roots_p.emplace_back(0, Root::constants(std::vector<std::uint32_t>(K.begin(), K.end()))); + roots_p.emplace_back(1, Root::table(false, 1)); + roots_p.emplace_back(2, Root::table(true, 1)); + roots_p.emplace_back(3, Root::table(false, 5)); + roots_p.emplace_back(4, Root::view(false, root_cbv)); + roots_p.emplace_back(5, Root::view(true, root_srv)); + roots_p.emplace_back(6, Root::table(false, 9)); + const auto theirs = host.dispatch(root_p.Get(), pso_p.Get(), dispatch(std::move(roots_p))); + // The first word that differs, over every UAV in order (Rust: flatten, zip, find). + std::vector<std::uint32_t> a, b; + for (const auto& u : *ours) a.insert(a.end(), u.begin(), u.end()); + for (const auto& u : theirs) b.insert(b.end(), u.begin(), u.end()); + std::optional<std::size_t> mismatch; + for (std::size_t i = 0; i < a.size() && i < b.size(); ++i) + if (!close_bits(a[i], b[i])) { + mismatch = i; + break; + } + if (!mismatch) { + std::fprintf(stderr, "%s: equal\n", name); + } else { + const std::size_t at = *mismatch; + failures.push_back(std::string(name) + ": word " + std::to_string(at) + ": " + hex(a[at]) + " (" + + display(std::bit_cast<float>(a[at])) + ") vs " + hex(b[at]) + " (" + + display(std::bit_cast<float>(b[at])) + ")"); + } + } + std::error_code ec; + fs::remove_all(dir, ec); + report(failures); +} + +template <class F> +void run(const char* name, F&& f) { + try { + f(); + } catch (const std::exception& e) { + std::fprintf(stderr, "%s: %s\n", name, e.what()); + CHECK(false); + } +} + +} // namespace + +int main() { + run("translated_shaders_draw_as_pc_ones", translated_shaders_draw_as_pc_ones); + run("translated_mesh_shaders_draw_as_pc_ones", translated_mesh_shaders_draw_as_pc_ones); + run("float_semantics_are_the_consoles", float_semantics_are_the_consoles); + run("translated_compute_matches_pc", translated_compute_matches_pc); + return test_util::finish("diff_test"); +} diff --git a/tests/x2w_shader/emit/host_test.cpp b/tests/x2w_shader/emit/host_test.cpp new file mode 100644 index 0000000000..176b854d85 --- /dev/null +++ b/tests/x2w_shader/emit/host_test.cpp @@ -0,0 +1,272 @@ +// host.cpp (port of emit/host.rs) smoke test. host.rs has no tests of its own (its #[cfg(test)] +// parts are the draw/dispatch API the emit tests use); this runs that API on shaders dxc.exe +// compiles at test time: a compute dispatch with root constants, a root SRV, heap views (raw UAV, +// raw buffer SRV, texture UAV), a refused pipeline, a draw through Host::pipeline and one +// through Host::mesh_pipeline, and the stub shaders. Skips (and says so) without a hardware SM 6.6 device or dxc.exe. + +#include "x2w_shader/emit/host.h" + +#include <windows.h> + +#include <array> +#include <bit> +#include <cstdio> +#include <cstdlib> +#include <filesystem> +#include <fstream> +#include <iterator> +#include <optional> +#include <string> +#include <vector> + +#include "test_util.h" +#include "x2w_shader/emit/validator.h" + +namespace fs = std::filesystem; +using namespace x2w::vs::host; + +namespace { + +std::optional<std::vector<std::uint8_t>> dxc(const fs::path& dxc_exe, const char* hlsl, const char* profile) { + const fs::path dir = fs::temp_directory_path() / ("x2w_vs_host_test_" + std::to_string(GetCurrentProcessId())); + fs::create_directories(dir); + const fs::path src = dir / "shader.hlsl"; + const fs::path out = dir / "shader.dxil"; + std::ofstream(src, std::ios::binary) << hlsl; + // The whole command quoted once more: cmd.exe strips the outer pair. + const std::string cmd = "\"\"" + dxc_exe.string() + "\" -nologo -T " + profile + " -E main -Fo \"" + + out.string() + "\" \"" + src.string() + "\"\""; + const int rc = std::system(cmd.c_str()); + std::ifstream in(out, std::ios::binary); + std::vector<std::uint8_t> bytes((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); + in.close(); + std::error_code ec; + fs::remove_all(dir, ec); + if (rc != 0 || bytes.empty()) return std::nullopt; + return bytes; +} + +// What a HostShader offers the host (Stage converts from it implicitly). +struct FakeShader { + std::vector<std::uint8_t> dxil; + std::uint32_t dwords = 0; + std::vector<x2w::vs::sampler::StaticSampler> static_samplers; + std::vector<std::uint8_t> root_cbvs, root_srvs, root_uavs; + std::uint32_t user_data_dwords() const { return dwords; } +}; + +// User data at b0 space 0 (root parameter 0), a root SRV t2 in ROOT_CBV_SPACE (space 1), the +// view heap directly indexed: [0] raw UAV, [1] raw SRV, [2] RGBA32F texture UAV. +const char* CS = R"( +cbuffer U : register(b0, space0) { uint4 k; }; +ByteAddressBuffer root_srv : register(t2, space1); +[numthreads(4, 1, 1)] +void main(uint i : SV_DispatchThreadID) { + RWByteAddressBuffer o = ResourceDescriptorHeap[0]; + ByteAddressBuffer b = ResourceDescriptorHeap[1]; + RWTexture2D<float4> t = ResourceDescriptorHeap[2]; + o.Store(i * 4, i * k.x + k.y + root_srv.Load(i * 4) + b.Load(i * 4)); + t[uint2(i & 1, i >> 1)] = float4(i, k.x, 0.5, 1); +} +)"; + +const char* VS = R"( +float4 main(uint id : SV_VertexID) : SV_Position { + float2 uv = float2((id << 1) & 2, id & 2); + return float4(uv * float2(2, -2) + float2(-1, 1), 0, 1); +} +)"; + +const char* PS = R"( +cbuffer U : register(b0, space0) { float4 c; }; +float4 main(float4 pos : SV_Position) : SV_Target { return c + float4(0, 0, 0, pos.x > 2 ? 1 : 0); } +)"; + +const char* MS = R"( +struct V { float4 pos : SV_Position; }; +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void main(out vertices V v[3], out indices uint3 t[1]) { + SetMeshOutputCounts(3, 1); + v[0].pos = float4(-1, 1, 0, 1); + v[1].pos = float4(3, 1, 0, 1); + v[2].pos = float4(-1, -3, 0, 1); + t[0] = uint3(0, 1, 2); +} +)"; + +} // namespace + +int main() { + std::optional<fs::path> dxil = x2w::vs::validator::Validator::default_path(); + if (!dxil) { + std::printf("host_test: skipped (no Windows SDK dxc)\n"); + return 0; + } + fs::path dxc_exe = *dxil; + dxc_exe.replace_filename("dxc.exe"); + std::optional<Host> host; + try { + host.emplace(false); + } catch (const Error& e) { + std::printf("host_test: skipped (no device: %s)\n", e.what()); + return 0; + } + { + DXGI_ADAPTER_DESC1 desc{}; + Microsoft::WRL::ComPtr<IDXGIFactory4> f; + Microsoft::WRL::ComPtr<IDXGIAdapter1> a; + if (SUCCEEDED(CreateDXGIFactory2(0, IID_PPV_ARGS(&f))) && + SUCCEEDED(f->EnumAdapterByLuid(host->device->GetAdapterLuid(), IID_PPV_ARGS(&a)))) + a->GetDesc1(&desc); + std::printf("host_test: device %ls\n", desc.Description); + } + + // Compute: root constants, a root SRV, heap views. + auto cs_bytes = dxc(dxc_exe, CS, "cs_6_6"); + CHECK(cs_bytes.has_value()); + if (cs_bytes) { + FakeShader cs{*cs_bytes, 4, {}, {}, {2}, {}}; + try { + auto [root, pso] = host->compute_pipeline(cs); + const std::uint32_t srv_words[4] = {1000, 2000, 3000, 4000}; + const View views[] = { + View::raw_uav(4), + View::buffer(srv_words, Stride::raw()), + View::texture_uav(2, 2), + }; + Dispatch d; + d.roots.emplace_back(0, Root::constants({10, 7, 0, 0})); + // Root parameter 1: the root SRV t2 (after the user data). + d.roots.emplace_back(1, Root::view(true, {100, 200, 300, 400})); + d.views = views; + d.groups = {1, 1, 1}; + auto out = host->dispatch(root.Get(), pso.Get(), d); + CHECK(out.size() == 2); + if (out.size() == 2) { + const std::vector<std::uint32_t> want = {1107, 2217, 3327, 4437}; + CHECK(out[0] == want); + CHECK(out[1].size() == 16); + for (std::uint32_t i = 0; i < 4 && out[1].size() == 16; ++i) { + const std::size_t at = 4 * ((i >> 1) * 2 + (i & 1)); + CHECK(std::bit_cast<float>(out[1][at]) == float(i)); + CHECK(std::bit_cast<float>(out[1][at + 1]) == 10.0f); + CHECK(std::bit_cast<float>(out[1][at + 2]) == 0.5f); + CHECK(std::bit_cast<float>(out[1][at + 3]) == 1.0f); + } + std::printf("host_test: dispatch raw UAV = %u %u %u %u\n", out[0][0], out[0][1], out[0][2], out[0][3]); + } + // A container the runtime refuses: the pipeline call reports it. + std::vector<std::uint8_t> broken = *cs_bytes; + broken[0] = 'X'; + bool refused = false; + try { + host->compute_pipeline_with(root.Get(), broken); + } catch (const Error& e) { + refused = true; + std::printf("host_test: broken container refused: %s\n", e.what()); + } + CHECK(refused); + } catch (const Error& e) { + std::fprintf(stderr, "compute: %s\n", e.what()); + CHECK(false); + } + } + + // Draw: Host::pipeline (the root signature translated shaders expect, user data of VS at 0, + // PS at 1; targets from the pixel shader's OSG1), the full-screen triangle. + auto vs_bytes = dxc(dxc_exe, VS, "vs_6_6"); + auto ps_bytes = dxc(dxc_exe, PS, "ps_6_6"); + CHECK(vs_bytes && ps_bytes); + const Root colour = Root::constants({std::bit_cast<std::uint32_t>(0.25f), std::bit_cast<std::uint32_t>(0.5f), + std::bit_cast<std::uint32_t>(0.75f), 0}); + auto check_texels = [](const char* what, const std::vector<std::array<float, 4>>& texels) { + CHECK(texels.size() == 8); + for (std::size_t i = 0; i < texels.size(); ++i) { + const float a = (i % 4) >= 2 ? 1.0f : 0.0f; // pixel centres x = 2.5, 3.5 + CHECK((texels[i] == std::array<float, 4>{0.25f, 0.5f, 0.75f, a})); + } + if (texels.size() > 3) + std::printf("host_test: %s texel 3 = %g %g %g %g\n", what, texels[3][0], texels[3][1], texels[3][2], + texels[3][3]); + }; + if (vs_bytes && ps_bytes) { + FakeShader vs{*vs_bytes, 0, {}, {}, {}, {}}; + FakeShader ps{*ps_bytes, 4, {}, {}, {}, {}}; + try { + auto [root, pso] = host->pipeline(vs, ps); + Draw d; + d.roots.emplace_back(1, colour); + d.size = {4, 2}; + check_texels("draw", host->draw(root.Get(), pso.Get(), d)); + } catch (const Error& e) { + std::fprintf(stderr, "draw: %s\n", e.what()); + CHECK(false); + } + + // The stub shaders (built with shader::Shader): the validator accepts them, and each + // makes a pipeline with the other side's real shader. + try { + std::vector<std::uint8_t> svs = stub_vs_dxil(ps.dxil); + std::vector<std::uint8_t> sps = stub_ps_dxil(); + std::string error; + auto v = x2w::vs::validator::Validator::load(x2w::vs::validator::Validator::default_path(), &error); + CHECK(v.has_value()); + if (v) { + auto r1 = v->validate(svs); + auto r2 = v->validate(sps); + CHECK(!r1); + CHECK(!r2); + if (r1) std::fprintf(stderr, "stub_vs rejected: %s\n", r1->c_str()); + if (r2) std::fprintf(stderr, "stub_ps rejected: %s\n", r2->c_str()); + } + FakeShader stub_vs_s{svs, 0, {}, {}, {}, {}}; + FakeShader stub_ps_s{sps, 0, {}, {}, {}, {}}; + auto [root1, pso1] = host->pipeline(stub_vs_s, ps); + CHECK(pso1 != nullptr); + auto [root2, pso2] = host->pipeline(vs, stub_ps_s); + CHECK(pso2 != nullptr); + // The stub pixel shader writes zeros to target 0. + Draw d; + d.size = {4, 2}; + auto texels = host->draw(root2.Get(), pso2.Get(), d); + CHECK(texels.size() == 8); + for (const auto& t : texels) CHECK((t == std::array<float, 4>{0, 0, 0, 0})); + std::printf("host_test: stub_vs %zu bytes, stub_ps %zu bytes: validated, pipelines made\n", svs.size(), + sps.size()); + } catch (const std::exception& e) { + std::fprintf(stderr, "stubs: %s\n", e.what()); + CHECK(false); + } + + // Mesh: Host::mesh_pipeline and a draw with mesh_groups, where the device has mesh + // shaders. + D3D12_FEATURE_DATA_D3D12_OPTIONS7 o7{}; + const bool mesh = SUCCEEDED(host->device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &o7, sizeof o7)) && + o7.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED; + std::optional<std::vector<std::uint8_t>> ms_bytes; + if (!mesh) { + std::printf("host_test: mesh skipped (no mesh shaders)\n"); + } else { + ms_bytes = dxc(dxc_exe, MS, "ms_6_6"); + CHECK(ms_bytes.has_value()); + } + if (ms_bytes) { + FakeShader ms{*ms_bytes, 0, {}, {}, {}, {}}; + try { + auto [root, pso] = host->mesh_pipeline(ms, ps); + Draw d; + d.roots.emplace_back(1, colour); + d.size = {4, 2}; + d.mesh_groups = 1; + check_texels("mesh", host->draw(root.Get(), pso.Get(), d)); + } catch (const Error& e) { + std::fprintf(stderr, "mesh: %s\n", e.what()); + CHECK(false); + } + } + } + + std::printf("host_test: ran on the GPU\n"); + return test_util::finish("host_test"); +} diff --git a/tests/x2w_shader/emit/intersect_test.cpp b/tests/x2w_shader/emit/intersect_test.cpp new file mode 100644 index 0000000000..5017bac25b --- /dev/null +++ b/tests/x2w_shader/emit/intersect_test.cpp @@ -0,0 +1,722 @@ +// Port of the upstream Rust module emit/intersect_tests.rs. The ray-tracing node test end to end: a synthetic +// compute program that runs image_bvh64_intersect_ray (or the 32-bit form) once per thread, +// lowered to DXIL, validated by dxil.dll when present, run on the host GPU and WARP, and compared +// dword for dword with the CPU reference (bvh.h). +// +// The nodes are in a raw buffer. Two ways to name it are run: the buffer's descriptor from the +// program's table (a resource of the host, BvhNodes::Resource), and the title's way, a descriptor +// of numbers over title memory with the structure's address in the node pointer or in the +// descriptor. These tests have no host that keeps copies of title memory and their directory, +// so for the second they put a stand-in under the node reader (lower::test::set_memory, Rust's +// lower::intersect::TEST_MEMORY); without it the same program reads through the directory, which +// is only checked to lower and validate. +// +// Each Rust #[test] is a function here, run one after the other (Rust's ONE_AT_A_TIME lock has +// nothing to serialise); a Rust panic is an exception that fails that function. + +#include <algorithm> +#include <array> +#include <bit> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <exception> +#include <limits> +#include <optional> +#include <stdexcept> +#include <string> +#include <utility> +#include <vector> + +#include "test_util.h" +#include "x2w_shader/bvh.h" +#include "x2w_shader/emit/emit.h" +#include "x2w_shader/emit/host.h" +#include "x2w_shader/emit/lower.h" +#include "x2w_shader/emit/validator.h" +#include "x2w_shader/error.h" +#include "x2w_shader/io.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/native.h" +#include "x2w_shader/resource.h" +#include "x2w_shader/structure.h" + +using namespace x2w::vs; +using bvh::Ray; +using host::Dispatch; +using host::Host; +using host::Root; +using host::Stride; +using host::View; +using native::ComputeIo; +using native::HwStage; +using native::NativeProgram; +using native::ResourceType; +using native::RootParam; +using native::RootType; +using native::UsedResource; +using resource::BvhNodes; +namespace nodes = bvh::testing; + +namespace { + +[[noreturn]] void panic(const std::string& what) { throw std::logic_error(what); } + +// Threads of one group, each with its own record. +constexpr std::uint32_t THREADS = 32; +// Bytes of a thread's record: the node pointer (two dwords), the ray's extent, origin, direction +// and inverse direction, and whether the thread runs the instruction. +constexpr std::uint32_t RECORD = 64; +// Where the nodes start in the buffer. +constexpr std::uint32_t NODES = THREADS * RECORD; +// What the result registers hold before the instruction. +constexpr bvh::Result4 BEFORE = {1, 2, 3, 4}; + +// How the program names the nodes' memory (Rust enum Descriptor). +struct Descriptor { + // Table: the buffer's descriptor from the table. Else Numbers, as the title builds it: + // dwords 0 and 1 (the base address in 256-byte units and the box sorting bit); the size and + // the rest of the flags as the title sets them. + bool table = true; + std::uint32_t word0 = 0; + std::uint32_t word1 = 0; + + static Descriptor Table() { return {true, 0, 0}; } + static Descriptor Numbers(std::uint32_t w0, std::uint32_t w1) { return {false, w0, w1}; } +}; + +// The descriptor the title builds for the 64-bit form: the whole address space, sorted boxes, +// barycentrics returned. +const Descriptor WHOLE = Descriptor::Numbers(0, bvh::BOX_SORT); + +// The program: per thread, the record's twelve operand dwords in v1-v12, the instruction's +// result in v13-v16 (under a lane mask of the threads whose record says so), stored to the UAV at +// 16 bytes a thread. +std::vector<std::uint32_t> program(bool wide, Descriptor descriptor) { + std::vector<std::uint32_t> w = { + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xF408'0202, + 0xFA00'0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 + 0xF408'0302, + 0xFA00'0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 + 0x3428'0086, // v_lshlrev_b32 v20, 6, v0 + 0xE038'1000, + 0x8002'0114, // buffer_load_dwordx4 v[1:4], v20, s[8:11], 0 offen + 0xE038'1010, + 0x8002'0514, // buffer_load_dwordx4 v[5:8], v20, s[8:11], 0 offen offset:16 + 0xE038'1020, + 0x8002'0914, // buffer_load_dwordx4 v[9:12], v20, s[8:11], 0 offen offset:32 + 0xE030'1030, + 0x8002'1114, // buffer_load_dword v17, v20, s[8:11], 0 offen offset:48 + }; + for (std::uint32_t k = 0; k < 4; ++k) { + // v_mov_b32 v13+k, 1+k + w.push_back(0x7E00'0200u | ((13 + k) << 17) | (0x81 + k)); + } + std::uint32_t rsrc; + if (descriptor.table) { + rsrc = 8; + } else { + // s_mov_b32 s24, word0 + w.insert(w.end(), {0xBE98'03FFu, descriptor.word0}); + if (descriptor.word1 == bvh::BOX_SORT) { + // As the title makes it. + w.push_back(0xBE99'0B81); // s_brev_b32 s25, 1 + } else { + w.insert(w.end(), {0xBE99'03FFu, descriptor.word1}); // s_mov_b32 s25, word1 + } + w.insert(w.end(), { + 0xBE9A'03C1u, // s_mov_b32 s26, -1 + 0xBE9B'03FFu, + 0x8900'03FFu, // s_mov_b32 s27, 0x890003ff + }); + rsrc = 24; + } + w.insert(w.end(), { + 0xBE94'037Eu, // s_mov_b32 s20, exec_lo + 0x7DAA'2280u, // v_cmpx_ne_u32 exec_lo, 0, v17 + }); + const std::uint32_t first = 0x0000'0D01u | ((rsrc >> 2) << 16); + if (wide) { + // image_bvh64_intersect_ray v[13:16], [v1 .. v12], s[rsrc:rsrc+3] + w.insert(w.end(), {0xF19C'9F07u, first, 0x0504'0302u, 0x0908'0706u, 0x000C'0B0Au}); + } else { + // image_bvh_intersect_ray v[13:16], [v1, v3 .. v12], s[rsrc:rsrc+3] + w.insert(w.end(), {0xF198'9F07u, first, 0x0605'0403u, 0x0A09'0807u, 0x0000'0C0Bu}); + } + w.insert(w.end(), { + 0xBEFE'0314u, // s_mov_b32 exec_lo, s20 + 0x342A'0084u, // v_lshlrev_b32 v21, 4, v0 + 0xE078'1000u, + 0x8003'0D15u, // buffer_store_dwordx4 v[13:16], v21, s[12:15], 0 offen + 0xBF81'0000u, // s_endpgm + }); + return w; +} + +NativeProgram make_native(const std::vector<std::uint32_t>& words) { + auto table = [](ResourceType kind, std::uint32_t at) { + UsedResource u; + u.kind = kind; + u.root = RootType::Table(); + u.table_offset_dwords = at; + u.lower_bound = 0; + u.stride = 4; + u.dwords = 4; + u.user_data = 4; + u.slot = 1; + return u; + }; + NativeProgram n; + n.stage = HwStage::Cs; + n.wave64 = false; + n.vgprs = 22; + RootParam constants; + constants.root = RootType::Constants(); + constants.table_offset_dwords = 0; + constants.sgprs = 4; + constants.base_register = 0; + constants.user_data = 0; + constants.slot = 0; + RootParam tbl; + tbl.root = RootType::Table(); + tbl.table_offset_dwords = 0; + tbl.sgprs = 1; + tbl.base_register = 0; + tbl.user_data = 4; + tbl.slot = 1; + n.layout = {constants, tbl}; + n.used = {table(ResourceType::Srv(), 0), table(ResourceType::Uav(), 8)}; + ComputeIo io; + io.rsrc2 = 5 << 1; + io.threads = {THREADS, 1, 1}; + n.io = io; + for (std::uint32_t x : words) + for (int b = 0; b < 4; ++b) n.code.push_back(std::uint8_t(x >> (8 * b))); + return n; +} + +// `native`, a compute program, translated (the tests' own way: no container). Rust: +// build_compute_shader. +std::pair<HostShader, resource::Resources> build_compute_shader(const NativeProgram& native) { + const ir::Program p = ir::build(native.code, native.wave64, native.vgprs); + const structure::Structured st = structure::structure(p); + resource::Resources res = resource::track(p, native.layout, native.stage, &st); + const io::Io io = io::raise(p, native); + lower::Parts parts; + parts.native = &native; + parts.p = &p; + parts.st = &st; + parts.io = &io; + parts.res = &res; + parts.mesh_stride = 0; + lower::Lowered lowered = lower::lower(parts); + HostShader shader; + shader.stage = HwStage::Cs; + shader.dxil = std::move(lowered.dxil); + shader.user_data = std::move(lowered.user_data); + shader.samplers = std::move(lowered.samplers); + shader.root_cbvs = std::move(lowered.root_cbvs); + shader.root_srvs = std::move(lowered.root_srvs); + shader.root_uavs = std::move(lowered.root_uavs); + shader.root_indexed_views = res.root_indexed_views; + if (std::optional<validator::Validator> v = validator::Validator::load(validator::Validator::default_path())) { + std::vector<std::uint8_t> copy = shader.dxil; + if (std::optional<std::string> e = v->validate(copy)) panic("DXIL validation failed: " + *e); + } + return {std::move(shader), std::move(res)}; +} + +// Lowers the program; the DXIL is validated when the validator is there. +std::pair<HostShader, resource::Resources> build(bool wide, Descriptor descriptor) { + return build_compute_shader(make_native(program(wide, descriptor))); +} + +// One thread's test: a node (by its index in the node list), the kind its pointer carries, and +// the ray; nullopt leaves the thread masked out. +struct Test { + std::size_t n; + std::uint32_t kind; + Ray ray; +}; +using Case = std::optional<Test>; + +// The scene: node dwords (a 32-bit box node takes 32, the others 16) and where each node starts, +// in dwords from the first node. +struct Scene { + std::vector<std::uint32_t> words; + std::vector<std::size_t> starts; + + // Adds a node of `dwords` (16 or 32) and returns its index. + std::size_t add(const bvh::Words& node, std::size_t dwords) { + starts.push_back(words.size()); + std::array<std::uint32_t, 32> padded{}; + std::copy(node.begin(), node.end(), padded.begin()); + // Bytes the instruction must not read as part of the node: what follows a 64-byte node, + // and a box node's last 16 bytes. + for (std::size_t k = dwords == 16 ? 16 : 28; k < 32; ++k) padded[k] = 0x7fc0'dead; + words.insert(words.end(), padded.begin(), padded.begin() + std::ptrdiff_t(dwords)); + return starts.size() - 1; + } + + // The pointer of node `n` with `kind`, counted from the first node. + std::uint32_t pointer(std::size_t n, std::uint32_t kind) const { + return ((4 * std::uint32_t(starts.at(n))) >> 3) | kind; + } + + // What the instruction reads of node `n`. + bvh::Words node(std::size_t n) const { + bvh::Words w{}; + for (std::size_t k = 0; k < w.size(); ++k) { + const std::size_t at = starts.at(n) + k; + w[k] = at < words.size() ? words[at] : 0; + } + return w; + } +}; + +// A small generator of repeatable numbers. +struct Numbers { + std::uint64_t state; + + std::uint32_t next() { + state = state * 6364136223846793005ull + 1442695040888963407ull; // wrapping + return std::uint32_t(state >> 33); + } + + // A float in -1..1 in steps of 1/4096 (exactly representable). + float unit() { return float(next() % 8193) / 4096.0f - 1.0f; } + + bvh::Vec3 vector(float scale) { + // In order: x, y, z. + const float x = unit() * scale; + const float y = unit() * scale; + const float z = unit() * scale; + return {x, y, z}; + } +}; + +bvh::Vec3 vabs(bvh::Vec3 v) { return {std::fabs(v[0]), std::fabs(v[1]), std::fabs(v[2])}; } + +// The scene and batches of cases over it. +std::pair<Scene, std::vector<std::vector<Case>>> scene() { + Scene s; + Numbers g{0x5eed}; + constexpr bvh::Box UNIT = {-1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f}; + auto moved = [](bvh::Box b, bvh::Vec3 by) { + bvh::Box r; + for (std::size_t k = 0; k < 6; ++k) r[k] = b[k] + by[k % 3]; + return r; + }; + const float nan = std::numeric_limits<float>::quiet_NaN(); + const float inf = std::numeric_limits<float>::infinity(); + const bvh::Box off = {nan, nan, nan, nan, nan, nan}; + std::vector<std::pair<std::size_t, std::uint32_t>> box_nodes; + // The boxes of the reference's own tests, in both widths. + const bvh::Boxes lined = { + moved(UNIT, {30.0f, 0.0f, 0.0f}), + moved(UNIT, {10.0f, 0.0f, 0.0f}), + moved(UNIT, {10.0f, 5.0f, 0.0f}), + moved(UNIT, {20.0f, 0.0f, 0.0f}), + }; + const bvh::Result4 ids = {0x105, 0x20c, 0x304, 0x400}; + box_nodes.emplace_back(s.add(nodes::box32(ids, lined), 32), 5); + box_nodes.emplace_back(s.add(nodes::box16(ids, lined), 16), 4); + // Boxes around the origin, one switched off, one child missing. + const bvh::Boxes around = { + UNIT, + moved(UNIT, {0.5f, 0.5f, 0.5f}), + off, + bvh::Box{-4.0f, -0.25f, -0.25f, 4.0f, 0.25f, 0.25f}, + }; + const bvh::Result4 ids2 = {8, bvh::NONE, 24, 0x1fff'fffc}; + box_nodes.emplace_back(s.add(nodes::box32(ids2, around), 32), 5); + box_nodes.emplace_back(s.add(nodes::box16(ids2, around), 16), 4); + // A child that is not there with inverted infinite bounds (the title's builder leaves such + // slots): every ray "enters" it at minus infinity. + bvh::Boxes empty = lined; + empty[1] = {inf, inf, inf, -inf, -inf, -inf}; + const bvh::Result4 ids3 = {0x105, bvh::NONE, 0x304, 0x400}; + box_nodes.emplace_back(s.add(nodes::box32(ids3, empty), 32), 5); + // Random boxes. + for (std::uint32_t n = 0; n < 6; ++n) { + bvh::Boxes boxes; + for (std::size_t b = 0; b < 4; ++b) { + const bvh::Vec3 c = g.vector(8.0f); + const bvh::Vec3 h = vabs(g.vector(2.0f)); + for (std::size_t k = 0; k < 6; ++k) boxes[b][k] = c[k % 3] + (k < 3 ? -h[k] : h[k - 3]); + } + bvh::Result4 rids; + for (std::uint32_t k = 0; k < 4; ++k) rids[k] = 0x1000 * (n + 1) + 8 * k + 5; + if (n % 2 == 0) + box_nodes.emplace_back(s.add(nodes::box32(rids, boxes), 32), 5); + else + box_nodes.emplace_back(s.add(nodes::box16(rids, boxes), 16), 4); + } + // Triangles: one of the reference's tests, a pair as the title's builder stores it, all four + // triangles of a full node with turned ids, random ones. + std::vector<std::pair<std::size_t, std::uint32_t>> triangle_nodes; + const bvh::Vec3 front[3] = {{0.0f, 2.0f, 5.0f}, {2.0f, -2.0f, 5.0f}, {-2.0f, -2.0f, 5.0f}}; + triangle_nodes.emplace_back(s.add(nodes::triangles(front, 3, 9), 16), 0); + const bvh::Vec3 pair_v[4] = {front[0], front[1], front[2], {2.0f, 2.0f, 5.0f}}; + const std::size_t pair = s.add(nodes::triangles(pair_v, 4, 9 | 0x80 | (6 << 8)), 16); + triangle_nodes.emplace_back(pair, 0); + triangle_nodes.emplace_back(pair, 1); + const bvh::Vec3 five[5] = { + {-3.0f, -1.0f, 6.0f}, {-1.0f, 2.0f, 6.5f}, {1.0f, -1.0f, 6.0f}, {3.0f, 2.0f, 6.5f}, {5.0f, -1.0f, 7.0f}, + }; + // I and J per triangle: (1, 2), (2, 0), (0, 1), (1, 2). + const std::size_t full = s.add(nodes::triangles(five, 5, 9 | (2 << 8) | (4 << 16) | (9u << 24)), 16); + for (std::uint32_t k = 0; k < 4; ++k) triangle_nodes.emplace_back(full, k); + for (int r = 0; r < 5; ++r) { + const bvh::Vec3 c = g.vector(6.0f); + bvh::Vec3 v[3]; + for (auto& vert : v) { + const bvh::Vec3 d = g.vector(3.0f); + vert = {c[0] + d[0], c[1] + d[1], c[2] + d[2]}; + } + triangle_nodes.emplace_back(s.add(nodes::triangles(v, 3, 9), 16), 0); + } + std::vector<Case> cases; + // Rays of the reference's tests against the lined-up boxes. + struct R { + bvh::Vec3 origin, direction; + float extent; + }; + const R reference_rays[] = { + {{0.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 1000.0f}, + {{0.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 19.5f}, + {{0.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 19.0f}, + {{0.0f, 0.0f, 0.0f}, {-1.0f, 0.0f, 0.0f}, 1000.0f}, + {{40.0f, 0.0f, 0.0f}, {-2.0f, 0.0f, 0.0f}, 1000.0f}, + {{0.0f, -1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 1000.0f}, + {{0.0f, 1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 1000.0f}, + {{0.0f, 0.5f, 0.25f}, {1.0f, -0.0f, 0.0f}, 1000.0f}, + {{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, 1000.0f}, + }; + for (std::size_t i = 0; i < 2; ++i) { + const auto [n, kind] = box_nodes[i]; + for (const R& r : reference_rays) cases.push_back(Test{n, kind, Ray::make(r.origin, r.direction, r.extent)}); + } + // Random rays at every box node, half of them aimed at a box. + for (const auto& [n, kind] : box_nodes) { + const bvh::Words words = s.node(n); + const bvh::Boxes boxes = kind == 5 ? bvh::boxes32(words) : bvh::boxes16(words); + for (std::size_t k = 0; k < 12; ++k) { + const bvh::Vec3 origin = g.vector(12.0f); + bvh::Vec3 direction; + if (k % 2 == 0) { + const bvh::Box b = boxes[(k / 2) % 4]; + if (std::isnan(b[0])) { + direction = g.vector(1.0f); + } else { + for (std::size_t a = 0; a < 3; ++a) + direction[a] = (b[a] + b[3 + a]) / 2.0f - origin[a] + g.unit() / 2.0f; + } + } else { + direction = g.vector(1.0f); + } + const float extent = k % 3 == 0 ? 6.0f : 100.0f; + cases.push_back(Test{n, kind, Ray::make(origin, direction, extent)}); + } + } + // Rays at every triangle: aimed inside, at an edge, at a vertex, past it, from both sides, + // along each axis. + for (const auto& [n, kind] : triangle_nodes) { + const bvh::Triangle p = bvh::triangle_vertices(s.node(n), kind); + auto at = [&p](bvh::Vec3 w) { + bvh::Vec3 r; + for (std::size_t a = 0; a < 3; ++a) r[a] = w[0] * p[0][a] + w[1] * p[1][a] + w[2] * p[2][a]; + return r; + }; + const bvh::Vec3 weights[] = { + {0.5f, 0.25f, 0.25f}, {0.125f, 0.75f, 0.125f}, {0.5f, 0.5f, 0.0f}, {0.0f, 0.5f, 0.5f}, + {1.0f, 0.0f, 0.0f}, {0.75f, 0.75f, -0.5f}, {-0.25f, 0.5f, 0.75f}, {0.25f, 0.25f, 0.5f}, + }; + for (std::size_t k = 0; k < 8; ++k) { + const bvh::Vec3 target = at(weights[k]); + const bvh::Vec3 origin = k % 2 == 0 ? bvh::Vec3{0.0f, 0.0f, 0.0f} : g.vector(16.0f); + bvh::Vec3 direction; + for (std::size_t a = 0; a < 3; ++a) direction[a] = target[a] - origin[a]; + if (k == 7) { + // The triangle lies behind. + for (float& d : direction) d = -d; + } + cases.push_back(Test{n, kind, Ray::make(origin, direction, 100.0f)}); + } + for (std::size_t axis = 0; axis < 3; ++axis) { + for (float sign : {1.0f, -1.0f}) { + const bvh::Vec3 target = at({0.25f, 0.5f, 0.25f}); + bvh::Vec3 origin = target; + origin[axis] -= 8.0f * sign; + bvh::Vec3 direction = {0.0f, 0.0f, 0.0f}; + direction[axis] = sign; + cases.push_back(Test{n, kind, Ray::make(origin, direction, 100.0f)}); + } + } + } + // Kinds the instruction does not read, and threads masked out. + const Ray ray = Ray::make({0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}, 100.0f); + cases.push_back(Test{triangle_nodes[0].first, 6, ray}); + cases.push_back(Test{triangle_nodes[0].first, 7, ray}); + cases.push_back(std::nullopt); + cases.push_back(Test{box_nodes[0].first, 5, Ray::make({0.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 1000.0f)}); + cases.push_back(std::nullopt); + std::vector<std::vector<Case>> batches; + for (std::size_t i = 0; i < cases.size(); i += THREADS) + batches.emplace_back(cases.begin() + std::ptrdiff_t(i), + cases.begin() + std::ptrdiff_t(std::min<std::size_t>(i + THREADS, cases.size()))); + return {std::move(s), std::move(batches)}; +} + +// The buffer for one batch: the threads' records, then the nodes. Node pointers count from +// `base` before the first node, in bytes. +std::vector<std::uint32_t> buffer(const Scene& scene, const std::vector<Case>& batch, std::uint64_t base) { + std::vector<std::uint32_t> data(NODES / 4, 0); + for (std::size_t t = 0; t < batch.size(); ++t) { + if (!batch[t]) continue; + const Test& c = *batch[t]; + std::uint32_t* r = &data.at(t * (RECORD / 4)); + const std::uint64_t pointer = (base >> 3) + std::uint64_t(scene.pointer(c.n, c.kind)); + r[0] = std::uint32_t(pointer); + r[1] = std::uint32_t(pointer >> 32); + r[2] = std::bit_cast<std::uint32_t>(c.ray.extent); + for (std::size_t a = 0; a < 3; ++a) { + r[3 + a] = std::bit_cast<std::uint32_t>(c.ray.origin[a]); + r[6 + a] = std::bit_cast<std::uint32_t>(c.ray.direction[a]); + r[9 + a] = std::bit_cast<std::uint32_t>(c.ray.inverse[a]); + } + r[12] = 1; + } + data.insert(data.end(), scene.words.begin(), scene.words.end()); + return data; +} + +bvh::Result4 expected(const Scene& scene, const Case& c, bool sort) { + if (c) return bvh::intersect(scene.node(c->n), c->kind, c->ray, sort); + return BEFORE; +} + +// Sets the tests' title memory for this thread until destroyed. +struct Memory { + explicit Memory(std::uint64_t base) { + // Heap slot 0: the buffer of records and nodes. + lower::test::set_memory(std::pair<std::uint32_t, std::uint64_t>{0, base}); + } + ~Memory() { lower::test::set_memory(std::nullopt); } + Memory(const Memory&) = delete; + Memory& operator=(const Memory&) = delete; +}; + +std::string words4(const std::uint32_t* w) { + char b[160]; + std::snprintf(b, sizeof b, "[%x, %x, %x, %x] = [%g, %g, %g, %g]", w[0], w[1], w[2], w[3], + double(std::bit_cast<float>(w[0])), double(std::bit_cast<float>(w[1])), + double(std::bit_cast<float>(w[2])), double(std::bit_cast<float>(w[3]))); + return b; +} + +// Runs every batch on the hardware adapter and WARP and compares with the reference. `pointers` +// is what node pointers count from, in bytes before the first node. +void run(bool wide, Descriptor descriptor, std::uint64_t pointers, bool sort) { + auto [shader, res] = build(wide, descriptor); + if (res.bvh.size() != 1) panic("res.bvh.len() is " + std::to_string(res.bvh.size()) + ", not 1"); + auto [scene_v, batches] = scene(); + const Scene& sc = scene_v; + // The reference must see a bit of everything, or the comparison proves little. + std::vector<const Case*> all; + for (const auto& b : batches) + for (const Case& c : b) all.push_back(&c); + std::vector<bvh::Result4> results; + for (const Case* c : all) results.push_back(expected(sc, *c, sort)); + auto boxes = [&](std::size_t hits) { + std::size_t n = 0; + for (std::size_t i = 0; i < all.size(); ++i) { + const Case& c = *all[i]; + if (c && (c->kind == 4 || c->kind == 5) && + std::size_t(std::count_if(results[i].begin(), results[i].end(), + [](std::uint32_t x) { return x != bvh::NONE; })) == hits) + ++n; + } + return n; + }; + auto triangles = [&](bool hit) { + std::size_t n = 0; + const std::uint32_t inf = std::bit_cast<std::uint32_t>(std::numeric_limits<float>::infinity()); + for (std::size_t i = 0; i < all.size(); ++i) { + const Case& c = *all[i]; + if (c && c->kind <= 3 && (results[i][0] != inf) == hit) ++n; + } + return n; + }; + if (!(boxes(0) > 5 && boxes(1) > 5 && boxes(2) > 5 && boxes(3) > 0)) panic("box cases"); + if (!(triangles(true) > 30 && triangles(false) > 30)) panic("triangle cases"); + // Sorting must matter to some case, or the unsorted run proves nothing. + if (!std::any_of(all.begin(), all.end(), + [&](const Case* c) { return expected(sc, *c, true) != expected(sc, *c, false); })) + panic("no case tells sorted from unsorted"); + int ran = 0; + const std::pair<const char*, bool> devices[] = {{"hardware", false}, {"warp", true}}; + for (const auto& [label, warp] : devices) { + std::optional<Host> h; + try { + h.emplace(warp); + } catch (const host::Error&) { + std::fprintf(stderr, "no SM 6.6 %s device; skipped\n", label); + continue; + } + const Host& host = *h; + host::Pipeline pl; + try { + pl = host.compute_pipeline(shader); + } catch (const host::Error& e) { + panic(std::string(label) + ": compute_pipeline failed: " + e.what()); + } + for (std::size_t b = 0; b < batches.size(); ++b) { + const std::vector<Case>& batch = batches[b]; + const std::vector<std::uint32_t> data = buffer(sc, batch, pointers); + const View views[] = {View::buffer(data, Stride::raw()), View::raw_uav(4 * THREADS)}; + Dispatch d; + d.roots.emplace_back(0, Root::constants(std::vector<std::uint32_t>(5, 0))); + d.views = views; + d.groups = {1, 1, 1}; + std::vector<std::vector<std::uint32_t>> out; + try { + out = host.dispatch(pl.first.Get(), pl.second.Get(), d); + } catch (const host::Error& e) { + panic(std::string(label) + ": dispatch failed: " + e.what()); + } + if (out.empty() || out[0].size() < 4 * THREADS) panic(std::string(label) + ": short output"); + for (std::size_t t = 0; t < THREADS; ++t) { + // A thread past the batch: its record is zeros, so it is masked out. + const bvh::Result4 want = t < batch.size() ? expected(sc, batch[t], sort) : BEFORE; + const std::uint32_t* got = &out[0][4 * t]; + if (!std::equal(want.begin(), want.end(), got)) { + std::string c = "None"; + if (t < batch.size() && batch[t]) { + const Test& x = *batch[t]; + c = "Some(node " + std::to_string(x.n) + ", kind " + std::to_string(x.kind) + ")"; + } + panic(std::string(label) + ", batch " + std::to_string(b) + " thread " + std::to_string(t) + ": " + + c + "\n got " + words4(got) + "\nwant " + words4(want.data())); + } + } + } + ++ran; + } + if (ran == 0) panic("no SM 6.6 device available"); +} + +void the_64_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() { + // Pointers count from the buffer's start. + run(true, Descriptor::Table(), NODES, true); + CHECK(build(true, Descriptor::Table()).second.bvh.at(0).second == BvhNodes::Resource()); +} + +void the_32_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() { + run(false, Descriptor::Table(), NODES, true); +} + +// Where the tests' title memory puts the buffer: past 4 GiB, on 256 bytes. +constexpr std::uint64_t BASE = 0x12'3456'7800ull; + +void the_64_bit_node_test_over_title_memory_matches_the_reference_on_the_card() { + // The title's way: one descriptor for all of memory, the structure's address folded into a + // 64-bit pointer. + const Memory memory(BASE); + run(true, WHOLE, BASE + NODES, true); +} + +void the_32_bit_node_test_over_title_memory_matches_the_reference_on_the_card() { + // The title's other way: the structure's address in the descriptor (in 256-byte units, 40 + // bits), a 32-bit pointer from there. Here with an address past 2^40 bytes, and without box + // sorting. + const std::uint64_t base = 0x312'3456'7800ull; + const std::uint64_t structure = base + NODES; + const Memory memory(base); + // Rust's `as u32`: the low 32 bits. + const std::uint32_t word0 = std::uint32_t((structure >> 8) & 0xFFFF'FFFFu); + const std::uint32_t word1 = std::uint32_t(structure >> 40); + run(false, Descriptor::Numbers(word0, word1), 0, false); + // And sorted. + run(false, Descriptor::Numbers(word0, word1 | bvh::BOX_SORT), 0, true); +} + +void a_descriptor_of_numbers_is_title_memory_read_through_the_directory() { + for (bool wide : {true, false}) { + const NativeProgram native = make_native(program(wide, WHOLE)); + const ir::Program p = ir::build(native.code, native.wave64, native.vgprs); + const structure::Structured st = structure::structure(p); + const resource::Resources res = resource::track(p, native.layout, native.stage, &st); + // The flags the title sets: sorted boxes, barycentrics, a ray-tracing structure. No + // resource is taken for it: the buffer loads' and the store's descriptors are all there is. + CHECK(res.bvh.size() == 1); + if (!res.bvh.empty()) CHECK(res.bvh[0].second == BvhNodes::Memory(0x8000'0000u, 0x8900'03ffu)); + CHECK(res.descriptors.size() == 5); + // Without the tests' stand-in the nodes are read as the title's programs will read them: + // through the host's directory of title memory. The program lowers and validates, and + // asks the host for the directory and for the list of pages it found no copy of. + const auto [shader, unused] = build(wide, WHOLE); + CHECK(std::find(shader.root_srvs.begin(), shader.root_srvs.end(), SLOT_MEMORY) != shader.root_srvs.end()); + CHECK(std::find(shader.root_uavs.begin(), shader.root_uavs.end(), SLOT_FAULTS) != shader.root_uavs.end()); + } +} + +void a_structure_that_returns_triangle_ids_is_refused_by_name() { + // Triangle return mode 0 (bit 24 of dword 3 clear): the last two result dwords would be a + // triangle id and a hit status. + std::vector<std::uint32_t> words = program(true, WHOLE); + auto flags = std::find(words.begin(), words.end(), 0x8900'03FFu); + if (flags == words.end()) panic("no flags word"); + *flags = 0x8800'03FF; + const NativeProgram native = make_native(words); + const ir::Program p = ir::build(native.code, native.wave64, native.vgprs); + const structure::Structured st = structure::structure(p); + const resource::Resources res = resource::track(p, native.layout, native.stage, &st); + const io::Io io = io::raise(p, native); + lower::Parts parts; + parts.native = &native; + parts.p = &p; + parts.st = &st; + parts.io = &io; + parts.res = &res; + parts.mesh_stride = 0; + try { + lower::lower(parts); + std::fprintf(stderr, "lowered: Ok(())\n"); + CHECK(false); + } catch (const ShaderError& e) { + if (e.kind != ShaderError::Kind::Unsupported) std::fprintf(stderr, "%s\n", e.debug().c_str()); + CHECK(e.kind == ShaderError::Kind::Unsupported); + CHECK(std::strcmp(e.reason, "a ray-tracing structure that returns triangle ids") == 0); + } +} + +template <class F> +void run_test(const char* name, F&& f) { + try { + f(); + } catch (const std::exception& e) { + std::fprintf(stderr, "%s: %s\n", name, e.what()); + CHECK(false); + } +} + +} // namespace + +int main() { + run_test("the_64_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card", + the_64_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card); + run_test("the_32_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card", + the_32_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card); + run_test("the_64_bit_node_test_over_title_memory_matches_the_reference_on_the_card", + the_64_bit_node_test_over_title_memory_matches_the_reference_on_the_card); + run_test("the_32_bit_node_test_over_title_memory_matches_the_reference_on_the_card", + the_32_bit_node_test_over_title_memory_matches_the_reference_on_the_card); + run_test("a_descriptor_of_numbers_is_title_memory_read_through_the_directory", + a_descriptor_of_numbers_is_title_memory_read_through_the_directory); + run_test("a_structure_that_returns_triangle_ids_is_refused_by_name", + a_structure_that_returns_triangle_ids_is_refused_by_name); + return test_util::finish("intersect_test"); +} diff --git a/tests/x2w_shader/emit/lower_card_util.h b/tests/x2w_shader/emit/lower_card_util.h new file mode 100644 index 0000000000..bae6ed327e --- /dev/null +++ b/tests/x2w_shader/emit/lower_card_util.h @@ -0,0 +1,423 @@ +#pragma once + +// Helpers shared by the card tests of the upstream Rust emitter (waterfall_tests.rs, wave64_tests.rs, +// permlane_tests.rs, cube_lod_tests.rs, probe_tests.rs, size_tests.rs): the front end run over a +// synthetic NativeProgram, the HostShader made from what lowering gives, the validator, and the +// host (hardware device and WARP). +// +// Every use of the host and validator ports (vs-emit's host.h / validator.h) goes through the +// wrappers here. Uses of vs-front's test fixtures are marked `// FRONT?`. +// +// Error mapping: Rust `.expect(..)` / `panic!` / `assert!` failing inside a test abort that test; +// here they throw (TestFail via `fail` / `require`, or the ShaderError / host error as is), and +// `guarded` in each file's main counts the test failed and goes on to the next, as cargo test does. +// +// Dumps: each test calls `x2w::vs::lower::test::set_dump_name("emit__<module>__<fn>")` first, the +// Rust thread name with `::` as `__`, so VS_DUMP files line up with GMR/vs_port/lower/dump_rs. + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> +#include <d3d12.h> + +#include <algorithm> +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <exception> +#include <limits> +#include <mutex> +#include <optional> +#include <set> +#include <span> +#include <stdexcept> +#include <string> +#include <string_view> +#include <utility> +#include <vector> + +#include "x2w_shader/emit/emit.h" +#include "x2w_shader/emit/host.h" vs-emit: x2w::vs::host (host.rs) +#include "x2w_shader/emit/lower.h" +#include "x2w_shader/emit/shader.h" // set_raw_views_here +#include "x2w_shader/emit/validator.h" vs-emit: x2w::vs::validator (validator.rs) +#include "x2w_shader/error.h" +#include "x2w_shader/io.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/native.h" +#include "x2w_shader/resource.h" +#include "x2w_shader/structure.h" +#include "test_util.h" + +namespace card { + +namespace vs = ::x2w::vs; +using vs::HostShader; +using vs::ShaderError; +using vs::UserData; +using vs::lower::Lowered; +using vs::lower::Parts; +using vs::native::ComputeIo; +using vs::native::HwStage; +using vs::native::NativeProgram; +using vs::native::ResourceType; +using vs::native::RootParam; +using vs::native::RootType; +using vs::native::StageIo; +using vs::native::UsedResource; + +// ---- failures ---------------------------------------------------------------------------------- + +// A Rust panic (`expect`, `panic!`, a failed `assert!`) inside a test. +struct TestFail : std::runtime_error { + using std::runtime_error::runtime_error; +}; + +[[noreturn]] inline void fail(const std::string& what) { throw TestFail(what); } + +// Rust `assert!(cond, msg)`: stops the test. +inline void require(bool ok, const std::string& what) { + if (!ok) fail(what); +} + +// Runs one test: a throw counts as a failure (Rust: the test panicked), and the next test runs. +template <class F> +void guarded(const char* name, F&& f) { + try { + f(); + } catch (const ShaderError& e) { + std::fprintf(stderr, "%s: ShaderError: %s\n", name, e.to_string().c_str()); + ++test_util::failures(); + } catch (const std::exception& e) { + std::fprintf(stderr, "%s: %s\n", name, e.what()); + ++test_util::failures(); + } +} + +// Rust `matches!(r, Err(ShaderError::Unsupported { what, .. }) if what == want)`. +inline bool is_unsupported(const ShaderError& e, std::string_view want) { + return e.kind == ShaderError::Kind::Unsupported && std::string_view(e.reason) == want; +} + +// ---- words ------------------------------------------------------------------------------------- + +// Rust `words.iter().flat_map(|w| w.to_le_bytes()).collect()`. +inline std::vector<std::uint8_t> le_bytes(std::span<const std::uint32_t> words) { + std::vector<std::uint8_t> code; + code.reserve(words.size() * 4); + for (std::uint32_t w : words) + for (int k = 0; k < 4; ++k) code.push_back(static_cast<std::uint8_t>(w >> (8 * k))); + return code; +} + +// Rust `code.chunks_exact(4).map(u32::from_le_bytes).collect()`. +inline std::vector<std::uint32_t> le_words(std::span<const std::uint8_t> code) { + std::vector<std::uint32_t> words; + for (std::size_t i = 0; i + 4 <= code.size(); i += 4) words.push_back(test_util::u32le(code, i)); + return words; +} + +// Rust `[a, b, c].concat()` of word slices. +inline std::vector<std::uint32_t> concat(std::initializer_list<std::span<const std::uint32_t>> parts) { + std::vector<std::uint32_t> out; + for (auto p : parts) out.insert(out.end(), p.begin(), p.end()); + return out; +} + +inline std::uint32_t f32_bits(float f) { + std::uint32_t u; + std::memcpy(&u, &f, 4); + return u; +} + +inline float f32_from_bits(std::uint32_t u) { + float f; + std::memcpy(&f, &u, 4); + return f; +} + +// Rust `{:#x}`. +inline std::string hex(std::uint64_t v) { + char b[24]; + std::snprintf(b, sizeof b, "0x%llx", static_cast<unsigned long long>(v)); + return b; +} + +// ---- the front end and lowering ---------------------------------------------------------------- + +// Rust `lower::TEST_HOST_WAVE.replace(Some(n))` ... `.set(was)`: the tests' `was` is always None +// (nothing else sets it on the test thread), so the guard restores None. +struct HostWave { + explicit HostWave(std::optional<std::uint32_t> lanes) { vs::lower::test::set_host_wave(lanes); } + ~HostWave() { vs::lower::test::set_host_wave(std::nullopt); } + HostWave(const HostWave&) = delete; + HostWave& operator=(const HostWave&) = delete; +}; + +// Rust `lower::TEST_F16_NEAREST.replace(Some(b))` ... `.set(was)` (was: None). +struct F16Nearest { + explicit F16Nearest(std::optional<bool> on) { vs::lower::test::set_f16_nearest(on); } + ~F16Nearest() { vs::lower::test::set_f16_nearest(std::nullopt); } + F16Nearest(const F16Nearest&) = delete; + F16Nearest& operator=(const F16Nearest&) = delete; +}; + +// Rust `super::shader::RAW_VIEWS_HERE.set(Some(n))` ... `.set(None)`. +struct RawViewsHere { + explicit RawViewsHere(std::optional<std::uint32_t> first) { vs::shader::set_raw_views_here(first); } + ~RawViewsHere() { vs::shader::set_raw_views_here(std::nullopt); } + RawViewsHere(const RawViewsHere&) = delete; + RawViewsHere& operator=(const RawViewsHere&) = delete; +}; + +// The Parts of a compute program: no signature elements, mesh_stride 0. +inline Parts parts_of(const NativeProgram& native, const vs::ir::Program& p, const vs::structure::Structured& st, + const vs::io::Io& io, const vs::resource::Resources& res) { + Parts parts; + parts.native = &native; + parts.p = &p; + parts.st = &st; + parts.io = &io; + parts.res = &res; + parts.mesh_stride = 0; + return parts; +} + +// The HostShader of a lowered compute program (Rust's struct literal in each test file). +inline HostShader host_shader(Lowered&& lowered, std::vector<vs::resource::RootIndexedView> root_indexed_views, + std::vector<vs::StaticSampler> static_samplers = {}) { + HostShader shader; + shader.stage = HwStage::Cs; + shader.dxil = std::move(lowered.dxil); + shader.user_data = std::move(lowered.user_data); + shader.samplers = std::move(lowered.samplers); + shader.static_samplers = std::move(static_samplers); + shader.root_cbvs = std::move(lowered.root_cbvs); + shader.root_srvs = std::move(lowered.root_srvs); + shader.root_uavs = std::move(lowered.root_uavs); + shader.root_indexed_views = std::move(root_indexed_views); + return shader; +} + +// ---- the validator --------------------------------------------------------------------- + +// Rust `validator::Validator::load(validator::Validator::default_path().as_deref())`: none when +// dxil.dll does not load (the reason in *why). +inline std::optional<vs::validator::Validator> load_validator(std::string* why = nullptr) { + return vs::validator::Validator::load(vs::validator::Validator::default_path(), why); +} + +// Rust `if let Ok(mut v) = Validator::load(..) { v.validate(&mut dxil.clone()).expect(..) }`, +// with `skipped_line`: `else { eprintln!("no dxil.dll; validation skipped") }`. Returns the +// validated copy (the validator rewrites the container hash), or none without a validator. +inline std::optional<std::vector<std::uint8_t>> validate(const HostShader& shader, bool skipped_line = false) { + std::string why; + auto v = load_validator(&why); + if (!v) { + if (skipped_line) std::fprintf(stderr, "no dxil.dll; validation skipped\n"); + return std::nullopt; + } + std::vector<std::uint8_t> copy = shader.dxil; + if (auto rejected = v->validate(copy)) fail("DXIL validation failed: " + *rejected); + return copy; +} + +// ---- the host -------------------------------------------------------------------------- + +using Host = vs::host::Host; +using View = vs::host::View; // Rust enum View<'a> (borrows its data) +using Stride = vs::host::Stride; +using Root = vs::host::Root; +using Texel = std::array<float, 4>; + +// Rust `View::Texture(w, h, &texels)`. +inline View texture(std::uint32_t w, std::uint32_t h, std::span<const Texel> texels) { + return View::texture(w, h, texels); +} +// Rust `View::Cube(size, mips, &texels)`. +inline View cube(std::uint32_t size, std::uint16_t mips, std::span<const Texel> texels) { + return View::cube(size, mips, texels); +} +// Rust `View::RawUav(dwords)`. +inline View raw_uav(std::uint32_t dwords) { return View::raw_uav(dwords); } +// Rust `View::UintTextureUav(w, h)`. +inline View uint_texture_uav(std::uint32_t w, std::uint32_t h) { return View::uint_texture_uav(w, h); } +// Rust `View::Buffer { data, stride }`. +inline View buffer(std::span<const std::uint32_t> data, Stride stride) { return View::buffer(data, stride); } +// Rust `Stride::Raw` / `Stride::Structured(n)`. +inline Stride stride_raw() { return Stride::raw(); } +inline Stride stride_structured(std::uint32_t bytes) { return Stride::structured(bytes); } + +// Rust `Host::new(warp)`: none (and `why`) without an SM 6.6 device. Host::create(bool) +// throws host::Error (Rust Result<Self, String>). +inline std::optional<Host> new_host(bool warp, std::string* why = nullptr) { + try { + return Host::create(warp); + } catch (const std::exception& e) { + if (why) *why = e.what(); + return std::nullopt; + } +} + +// What `Host::compute_pipeline` gives: Rust `(ID3D12RootSignature, ID3D12PipelineState)`. +using Pipeline = vs::host::Pipeline; + +// Rust `host.compute_pipeline(&shader)`: none (and `why`) when the device refuses it. +// compute_pipeline(Stage) throws host::Error. +inline std::optional<Pipeline> compute_pipeline(const Host& host, const HostShader& shader, std::string* why = nullptr) { + try { + return host.compute_pipeline(shader); + } catch (const std::exception& e) { + if (why) *why = e.what(); + return std::nullopt; + } +} + +// Rust `host.dispatch(&root, &pso, &Dispatch { roots: vec![(0, Root::Constants(ud))], views, +// samplers, groups }).unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"))`: each UAV's +// dwords in heap order. +inline std::vector<std::vector<std::uint32_t>> dispatch(const Host& host, const Pipeline& pipe, + std::vector<std::uint32_t> constants, + std::span<const View> views, + std::span<const D3D12_SAMPLER_DESC> samplers, + std::array<std::uint32_t, 3> groups, + const std::string& label = "") { + vs::host::Dispatch d; + d.roots.emplace_back(0u, Root::constants(std::move(constants))); + d.views = views; + d.samplers = samplers; + d.groups = groups; + try { + const auto& [root, pso] = pipe; + return host.dispatch(root.Get(), pso.Get(), d); + } catch (const TestFail&) { + throw; + } catch (const std::exception& e) { + fail((label.empty() ? std::string() : label + ": ") + "dispatch failed: " + e.what()); + } +} + +// Rust `options.WaveLaneCountMin`, `options.WaveLaneCountMax` of +// D3D12_FEATURE_D3D12_OPTIONS1 (permlane_tests.rs: `host.device.CheckFeatureSupport`). +// host.device: a public ID3D12Device (ComPtr or windows-crate-like wrapper with ->). +inline std::pair<std::uint32_t, std::uint32_t> wave_lane_counts(const Host& host) { + D3D12_FEATURE_DATA_D3D12_OPTIONS1 options{}; + HRESULT hr = host.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &options, + static_cast<UINT>(sizeof options)); + if (FAILED(hr)) fail("wave capabilities"); + return {options.WaveLaneCountMin, options.WaveLaneCountMax}; +} + +// Rust `super::valu_tests::ONE_AT_A_TIME`: one GPU test at a time (here each test file is an +// executable running its tests in order, so the lock never waits; kept to mirror the Rust). +inline std::mutex& one_at_a_time() { + static std::mutex m; + return m; +} + +// ---- waterfall_tests::run ---------------------------------------------------------------------- + +// Rust waterfall_tests::run: runs `shader` with `views` at heap indices 0.. (the UAV last) on the +// hardware GPU and on WARP (each skipped without a device) and returns, per one that ran, the +// first UAV's dwords. +inline std::vector<std::pair<const char*, std::vector<std::uint32_t>>> run(const HostShader& shader, + std::span<const View> views) { + D3D12_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.MaxAnisotropy = 1; + sampler.MaxLOD = std::numeric_limits<float>::max(); + const D3D12_SAMPLER_DESC samplers[] = {sampler}; + std::vector<std::pair<const char*, std::vector<std::uint32_t>>> out; + std::lock_guard one(one_at_a_time()); + const std::pair<const char*, bool> devices[] = {{"hardware", false}, {"warp", true}}; + for (auto [label, warp] : devices) { + std::string why; + auto host = new_host(warp, &why); + if (!host) { + std::fprintf(stderr, "no SM 6.6 %s device (%s); skipped\n", label, why.c_str()); + continue; + } + auto pipe = compute_pipeline(*host, shader, &why); + if (!pipe) fail(std::string(label) + ": compute_pipeline failed: " + why); + // Both tables start at heap index 0. + std::vector<std::uint32_t> ud(std::max<std::uint32_t>(shader.user_data_dwords(), 1), 0); + for (const UserData& u : shader.user_data) { + require(u.root == RootType::Table(), "user data not a table"); + ud[u.index] = 0; + } + auto words = dispatch(*host, *pipe, std::move(ud), views, samplers, {1, 1, 1}, label); + out.emplace_back(label, words[0]); + } + return out; +} + +// ---- intersect_tests::build_compute_shader ----------------------------------------------------- + +// Rust intersect_tests::build_compute_shader: `native`, a compute program, translated (no +// container). Throws ShaderError from resource::track and lowering (Rust `?`); the other stages' +// errors are the Rust `.expect(..)`s (they throw too). +inline std::pair<HostShader, vs::resource::Resources> build_compute_shader(const NativeProgram& native) { + vs::ir::Program p = vs::ir::build(native.code, native.wave64, native.vgprs); + vs::structure::Structured st = vs::structure::structure(p); + vs::resource::Resources res = vs::resource::track(p, native.layout, native.stage, &st); + vs::io::Io io = vs::io::raise(p, native); + Lowered lowered = vs::lower::lower(parts_of(native, p, st, io, res)); + HostShader shader = host_shader(std::move(lowered), res.root_indexed_views); + validate(shader); + return {std::move(shader), std::move(res)}; +} + +// ---- programs ---------------------------------------------------------------------------------- + +// RootParam { root, table_offset_dwords, sgprs, base_register, user_data, slot }. +inline RootParam root_param(RootType root, std::uint32_t table_offset_dwords, std::uint32_t sgprs, + std::uint32_t base_register, std::uint8_t user_data, std::uint8_t slot) { + RootParam r; + r.root = root; + r.table_offset_dwords = table_offset_dwords; + r.sgprs = sgprs; + r.base_register = base_register; + r.user_data = user_data; + r.slot = slot; + return r; +} + +// UsedResource { kind, root, table_offset_dwords, lower_bound, stride, dwords, user_data, slot }. +inline UsedResource used_resource(ResourceType kind, RootType root, std::uint32_t table_offset_dwords, + std::uint32_t lower_bound, std::uint32_t stride, std::uint8_t dwords, + std::uint8_t user_data, std::uint8_t slot) { + UsedResource u; + u.kind = kind; + u.root = root; + u.table_offset_dwords = table_offset_dwords; + u.lower_bound = lower_bound; + u.stride = stride; + u.dwords = dwords; + u.user_data = user_data; + u.slot = slot; + return u; +} + +// StageIo::Cs(ComputeIo { rsrc2, threads }). +inline StageIo compute_io(std::uint32_t rsrc2, std::array<std::uint32_t, 3> threads) { + ComputeIo cs; + cs.rsrc2 = rsrc2; + cs.threads = threads; + return cs; +} + +// Rust `p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == name).count()`. +inline std::size_t count_insts(const vs::ir::Program& p, std::string_view name) { + std::size_t n = 0; + for (const auto& b : p.blocks) + for (const auto& i : b.insts) + if (i.name() == name) ++n; + return n; +} + +} // namespace card diff --git a/tests/x2w_shader/emit/lower_cube_lod_test.cpp b/tests/x2w_shader/emit/lower_cube_lod_test.cpp new file mode 100644 index 0000000000..c043d2986d --- /dev/null +++ b/tests/x2w_shader/emit/lower_cube_lod_test.cpp @@ -0,0 +1,125 @@ +// Port of the upstream Rust module emit/cube_lod_tests.rs. +// +// Cube samples with gradients select their level by the footprint (after upstream commit 921d8d3b). + +#include "lower_card_util.h" + +using namespace card; + +namespace { + +// ---- rs:11 -------------------------------------------------------------------------------------- +// The level is the red channel on all six faces so every sample returns its selected mip directly +// (including the fraction with trilinear filtering). +void guest_cube_gradient_selects_mip_by_footprint() { + x2w::vs::lower::test::set_dump_name("emit__cube_lod_tests__guest_cube_gradient_selects_mip_by_footprint"); + constexpr std::size_t SIZE = 64; + constexpr std::uint16_t MIPS = 7; + std::vector<std::uint32_t> words = { + 0xBE81'0380, + 0xBE83'0380, // s1, s3 = 0 (upper halves of the tables) + 0xF40C'0400, + 0xFA00'0000, // cube SRV to s[16:23] from s[0:1] + 0xF408'0300, + 0xFA00'0020, // raw output UAV to s[12:15] from s[0:1]+32 + 0xF408'0601, + 0xFA00'0000, // sampler to s[24:27] from s[2:3] + 0x7E1E'0280, // v15 = 0 for output byte offsets + }; + struct Case { + std::uint32_t op; + float footprint, lod, mip; + }; + const Case cases[] = { + // image_sample_d: successive XY footprints (in texels). + {0x22, 1.0f, 0.0f, 0.0f}, + {0x22, 2.0f, 0.0f, 1.0f}, + {0x22, 16.0f, 0.0f, 4.0f}, + {0x22, 0.000001f, 0.0f, 0.0f}, + {0x22, 0.0f, 0.0f, 0.0f}, + // image_sample_d_cl: an instruction-specified minimum level. + {0x23, 1.0f, 3.0f, 3.0f}, + {0x23, 16.0f, 2.0f, 4.0f}, + {0x23, 0.0f, 2.0f, 2.0f}, + // image_sample_l and image_sample_lz: the level is given directly. + {0x24, 0.0f, 2.0f, 2.0f}, + {0x27, 0.0f, 0.0f, 0.0f}, + }; + constexpr std::uint32_t CASES = sizeof cases / sizeof cases[0]; + for (std::uint32_t i = 0; i < CASES; ++i) { + const Case& c = cases[i]; + float delta = c.footprint / static_cast<float>(SIZE); + std::vector<float> addr; + if (c.op == 0x22 || c.op == 0x23) + for (float f : {delta, 0.0f, 0.0f, delta}) addr.push_back(f); // derivatives along the face + for (float f : {1.5f, 1.5f, 0.0f}) addr.push_back(f); // positive X face, center + if (c.op == 0x23 || c.op == 0x24) addr.push_back(c.lod); + for (std::size_t reg = 0; reg < addr.size(); ++reg) { + words.push_back(0x7E00'02FFu | (static_cast<std::uint32_t>(reg) << 17)); + words.push_back(f32_bits(addr[reg])); + } + // MIMG, CUBE, dmask:R, v0... inputs, SRV s16, sampler s24, result v10. + words.push_back(0xF000'0118u | (c.op << 18)); + words.push_back(0x00C4'0A00u); + // buffer_store_dword v10, v15, s[12:15], 0 offen offset:i*4 + words.push_back(0xE070'1000u | (i * 4)); + words.push_back(0x8003'0A0Fu); + } + words.push_back(0xBF81'0000u); // s_endpgm + auto table = [](std::uint8_t slot, std::uint8_t user_data) { + return root_param(RootType::Table(), 0, 1, 0, user_data, slot); + }; + auto range = [](ResourceType kind, std::uint32_t at, std::uint8_t dwords, std::uint8_t slot, std::uint8_t user_data) { + return used_resource(kind, RootType::Table(), at, 0, 0, dwords, user_data, slot); + }; + NativeProgram native; + native.stage = HwStage::Cs; + native.wave64 = false; + native.vgprs = 16; + native.layout = {table(0, 0), table(1, 2)}; + native.used = {range(ResourceType::Srv(), 0, 8, 0, 0), range(ResourceType::Uav(), 8, 4, 0, 0), + range(ResourceType::Sampler(), 0, 4, 1, 2)}; + native.io = compute_io(3 << 1, {1, 1, 1}); + native.code = le_bytes(words); + HostShader shader = build_compute_shader(native).first; + std::vector<Texel> texels; + for (int face = 0; face < 6; ++face) + for (std::uint16_t mip = 0; mip < MIPS; ++mip) { + std::size_t n = (SIZE >> mip) * (SIZE >> mip); + float level = static_cast<float>(mip); + texels.insert(texels.end(), n, Texel{level, level, level, level}); + } + D3D12_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; + sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.MaxLOD = std::numeric_limits<float>::max(); + sampler.MaxAnisotropy = 1; + const D3D12_SAMPLER_DESC samplers[] = {sampler}; + const std::pair<const char*, bool> devices[] = {{"WARP", true}, {"hardware", false}}; + for (auto [name, warp] : devices) { + auto host = new_host(warp); + if (!host) { + std::fprintf(stderr, "no SM 6.6 %s device; skipped\n", name); + continue; + } + std::string why; + auto pipe = compute_pipeline(*host, shader, &why); + if (!pipe) fail(std::string(name) + ": compute_pipeline: " + why); + const View views[] = {cube(static_cast<std::uint32_t>(SIZE), MIPS, texels), raw_uav(CASES)}; + auto out = dispatch(*host, *pipe, std::vector<std::uint32_t>(shader.user_data_dwords(), 0), views, samplers, + {1, 1, 1}, name); + std::vector<float> levels, expected; + for (std::uint32_t w : out[0]) levels.push_back(f32_from_bits(w)); + for (const Case& c : cases) expected.push_back(c.mip); + require(levels == expected, name); + } +} + +} // namespace + +int main() { + guarded("guest_cube_gradient_selects_mip_by_footprint", guest_cube_gradient_selects_mip_by_footprint); + return test_util::finish("lower_cube_lod_test"); +} diff --git a/tests/x2w_shader/emit/lower_permlane_test.cpp b/tests/x2w_shader/emit/lower_permlane_test.cpp new file mode 100644 index 0000000000..26e74f863e --- /dev/null +++ b/tests/x2w_shader/emit/lower_permlane_test.cpp @@ -0,0 +1,189 @@ +// Port of the upstream Rust module emit/permlane_tests.rs, in Rust order. +// +// Synthetic row permutations on hosts supporting waves of at least 32 lanes. + +#include "lower_card_util.h" + +using namespace card; + +namespace { + +constexpr std::uint32_t THREADS = 128; +constexpr std::uint32_t OLD = 42; +constexpr std::uint32_t BASE = 0x1234'0000; + +NativeProgram native(bool cross, bool fi, bool bc, bool alias, bool wave64) { + auto mov = [](std::uint32_t dst, std::uint32_t src) { return 0x7E00'0200u | dst << 17 | src; }; + auto smov = [](std::uint32_t dst, std::uint32_t src) { return 0xBE80'0300u | dst << 16 | src; }; + std::vector<std::uint32_t> words = { + smov(5, 128), + 0x3Du << 26 | 0x02u << 18 | 8u << 6 | 2u, + 125u << 25, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0x340E'0082, // v_lshlrev_b32 v7, 2, v0 (output byte offset) + 0x4A0A'00FF, + BASE, // v_add_nc_u32 v5, BASE, v0 + mov(6, alias ? 256 + 5 : 128 + OLD), + }; + words.push_back(wave64 ? 0xBEFE'0402u : smov(126, 2)); // exec = s[2:3] / s2 + words.push_back(0xD400'0006u | (cross ? 0x378u : 0x377u) << 16 | std::uint32_t(fi) << 11 | + std::uint32_t(bc) << 12); + words.push_back((256u + (alias ? 6u : 5u)) | (1u << 18)); // v_permlane[x]16_b32 v6, v5/v6, s0, s1 + words.push_back(wave64 ? 0xBEFE'04C1u : smov(126, 193)); // restore EXEC + words.push_back(0x38u << 26 | 0x1Cu << 18 | 1u << 12); + words.push_back(0x80u << 24 | 2u << 16 | 6u << 8 | 7u); // buffer_store_dword v6, v7, s[8:11], 0 offen + words.push_back(0xBF81'0000u); + NativeProgram n; + n.stage = HwStage::Cs; + n.wave64 = wave64; + n.vgprs = 8; + n.layout = {root_param(RootType::Constants(), 0, 4, 0, 0, 0), root_param(RootType::Table(), 0, 1, 0, 4, 1)}; + n.used = {used_resource(ResourceType::Uav(), RootType::Table(), 0, 0, 0, 4, 4, 1)}; + n.io = compute_io(5 << 1, {THREADS, 1, 1}); + n.code = le_bytes(words); + return n; +} + +// Throws ShaderError from lowering (Rust `result?`). +HostShader lowered(const NativeProgram& native, std::uint32_t host_wave) { + vs::ir::Program p = vs::ir::build(native.code, native.wave64, native.vgprs); + vs::structure::Structured st = vs::structure::structure(p); + vs::resource::Resources res = vs::resource::track(p, native.layout, native.stage, &st); + vs::io::Io io = vs::io::raise(p, native); + Lowered result; + { + HostWave was(host_wave); + result = vs::lower::lower(parts_of(native, p, st, io, res)); + } + HostShader shader = host_shader(std::move(result), res.root_indexed_views); + std::string why; + if (auto v = load_validator(&why)) { + std::vector<std::uint8_t> copy = shader.dxil; + try { + v->validate(copy); + } catch (const std::exception& e) { + fail(std::string("DXIL validation: ") + e.what()); + } + require(copy.size() >= 20 && shader.dxil.size() >= 20 && + std::equal(copy.begin() + 4, copy.begin() + 20, shader.dxil.begin() + 4), + "container hash"); + } else { + std::fprintf(stderr, "DXIL validator unavailable: %s\n", why.c_str()); + } + return shader; +} + +// ---- rs:121 ------------------------------------------------------------------------------------- +void permlane_fetch_inactive_outside_the_host_branch_is_rejected() { + x2w::vs::lower::test::set_dump_name( + "emit__permlane_tests__permlane_fetch_inactive_outside_the_host_branch_is_rejected"); + NativeProgram n = native(true, true, false, false, false); + std::vector<std::uint32_t> words = le_words(n.code); + // Skip the permutation when EXEC is empty. Structurisation turns this into a host lane branch, + // so FI cannot read lanes that took the skip. + words.insert(words.begin() + 8, 0xBF88'0002u); // s_cbranch_execz +2 (to the EXEC restore) + n.code = le_bytes(words); + bool refused = false; + try { + lowered(n, 32); + } catch (const ShaderError& e) { + refused = is_unsupported(e, "a permlane fetch from lanes outside the host branch"); + } + require(refused, "Err(Unsupported { what: \"a permlane fetch from lanes outside the host branch\" })"); +} + +// ---- rs:142 ------------------------------------------------------------------------------------- +void permlane_rows_and_inactive_sources() { + x2w::vs::lower::test::set_dump_name("emit__permlane_tests__permlane_rows_and_inactive_sources"); + std::lock_guard one(one_at_a_time()); + int ran = 0; + const std::pair<const char*, bool> backends[] = {{"hardware", false}, {"WARP", true}}; + for (auto [backend, warp] : backends) { + auto host = new_host(warp); + if (!host) { + std::fprintf(stderr, "no SM 6.6 %s; skipped\n", backend); + continue; + } + auto [lanes_min, lanes_max] = wave_lane_counts(*host); + std::fprintf(stderr, "%s waves %u..%u\n", backend, lanes_min, lanes_max); + if (lanes_max < 32) { + std::fprintf(stderr, "%s cannot hold two 16-lane rows; GPU checks skipped\n", backend); + continue; + } + ran += 1; + std::fprintf(stderr, "permlane: testing row and EXEC cases on %s\n", backend); + for (bool wave64 : {false, true}) { + if (lanes_min > (wave64 ? 64u : 32u)) { + std::fprintf(stderr, "%s does not support the requested console wave size; skipped\n", backend); + continue; + } + for (bool cross : {false, true}) { + for (bool fi : {false, true}) { + for (bool bc : {false, true}) { + for (bool alias : {false, true}) { + HostShader shader; + try { + shader = lowered(native(cross, fi, bc, alias, wave64), lanes_max); + } catch (const ShaderError& e) { + fail("lower permlane: " + e.to_string()); + } + std::string why; + auto pipe = compute_pipeline(*host, shader, &why); + if (!pipe) fail("permlane pipeline: " + why); + const std::array<std::uint32_t, 2> selector_cases[] = { + {0x7654'3210u, 0xFEDC'BA98u}, // identity + {0x89AB'CDEFu, 0x0123'4567u}, // reverse + {0u, 0u}, // broadcast lane 0 + {0xFFFF'FFFFu, 0xFFFF'FFFFu}, // broadcast lane 15 + {0xF10E'2D3Cu, 0x4B5A'6978u}, // arbitrary; both selector words + }; + for (const auto& selectors : selector_cases) { + for (std::uint32_t mask : {0xFFFF'FFFFu, 0x5555'5555u, 0xFFFF'0000u, 1u, 0u}) { + const std::array<std::uint32_t, 4> constants = {selectors[0], selectors[1], + mask, mask}; + std::vector<std::uint32_t> ud(shader.user_data_dwords(), 0); + for (const UserData& u : shader.user_data) + ud.at(u.index) = u.root == RootType::Constants() ? constants.at(u.dword) : 0; + const View views[] = {raw_uav(THREADS)}; + auto out = dispatch(*host, *pipe, std::move(ud), views, {}, {1, 1, 1}, + "dispatch permlane"); + for (std::uint32_t t = 0; t < THREADS; ++t) { + std::uint32_t pos = t % 16; + std::uint64_t packed = + std::uint64_t(selectors[0]) | std::uint64_t(selectors[1]) << 32; + std::uint32_t pick = static_cast<std::uint32_t>(packed >> (4 * pos)) & 15; + std::uint32_t src = ((t & ~15u) ^ (cross ? 16u : 0u)) | pick; + std::uint32_t old = alias ? BASE + t : OLD; + std::uint32_t want = ((mask >> (t % 32)) & 1) == 0 ? old + : (fi || ((mask >> (src % 32)) & 1) != 0) ? BASE + src + : bc ? 0 + : old; + std::uint32_t got = out[0][t]; + if (got != want) + fail(std::string(backend) + " wave64=" + (wave64 ? "true" : "false") + + " cross=" + (cross ? "true" : "false") + + " fi=" + (fi ? "true" : "false") + " bc=" + (bc ? "true" : "false") + + " alias=" + (alias ? "true" : "false") + " selectors=[" + + hex(selectors[0]) + ", " + hex(selectors[1]) + "] mask=" + hex(mask) + + " lane=" + std::to_string(t) + ": got " + hex(got) + ", want " + + hex(want)); + } + } + } + } + } + } + } + } + std::fprintf(stderr, "permlane: all row and EXEC cases passed on %s\n", backend); + } + if (ran == 0) std::fprintf(stderr, "no SM 6.6 device with 32-lane rows; GPU checks skipped\n"); +} + +} // namespace + +int main() { + guarded("permlane_fetch_inactive_outside_the_host_branch_is_rejected", + permlane_fetch_inactive_outside_the_host_branch_is_rejected); + guarded("permlane_rows_and_inactive_sources", permlane_rows_and_inactive_sources); + return test_util::finish("lower_permlane_test"); +} diff --git a/tests/x2w_shader/emit/lower_probe_test.cpp b/tests/x2w_shader/emit/lower_probe_test.cpp new file mode 100644 index 0000000000..54ce5f4afa --- /dev/null +++ b/tests/x2w_shader/emit/lower_probe_test.cpp @@ -0,0 +1,103 @@ +// Port of the upstream Rust module emit/probe_tests.rs. +// +// Not a test of the translator: what the host's compiler makes of DXIL. X2W_SHADERCFG_PROBE=<folder> +// and `--ignored` (Rust `#[ignore]`, `--ignored probe`): each `.dxil` there (a compute program +// with a constant buffer b0 of four dwords and a raw buffer, slot 0 of the view heap) is run on the +// card. `sem*` programs are given the bits of 0.0, infinity, -0.0 and a NaN and what they store is +// printed; of the others the time is (several runs of 4096 groups). + +#include <algorithm> +#include <charconv> +#include <chrono> +#include <cmath> +#include <cstdlib> +#include <filesystem> +#include <fstream> +#include <iterator> + +#include "lower_card_util.h" + +using namespace card; + +namespace { + +// Rust `{}` of an f32 (shortest round trip; "inf", "NaN"). +std::string display(float f) { + if (std::isnan(f)) return "NaN"; + char b[64]; + auto r = std::to_chars(b, b + sizeof b, f); + return std::string(b, r.ptr); +} + +// ---- rs:11 -------------------------------------------------------------------------------------- +void probe() { + x2w::vs::lower::test::set_dump_name("emit__probe_tests__probe"); + const char* folder = std::getenv("X2W_SHADERCFG_PROBE"); + if (!folder) return; + std::string why; + auto host = new_host(false, &why); + if (!host) fail("a card: " + why); + std::vector<std::filesystem::path> files; + std::error_code ec; + std::filesystem::directory_iterator dir(folder, ec); + if (ec) fail("the folder: " + ec.message()); + for (const auto& e : dir) + if (e.path().extension() == ".dxil") files.push_back(e.path()); + std::sort(files.begin(), files.end()); + for (const auto& file : files) { + std::string name = file.stem().string(); + HostShader shader; + shader.stage = HwStage::Cs; + std::ifstream in(file, std::ios::binary); + if (!in) fail("the file"); + shader.dxil.assign(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()); + for (std::uint32_t n = 0; n < 4; ++n) { + UserData u; + u.index = n; + u.slot = 0; + u.root = RootType::Constants(); + u.dword = n; + shader.user_data.push_back(u); + } + auto pipe = compute_pipeline(*host, shader, &why); + if (!pipe) { + std::printf("%s: %s\n", name.c_str(), why.c_str()); + continue; + } + auto run_once = [&](std::array<std::uint32_t, 4> constants, std::uint32_t groups) { + auto began = std::chrono::steady_clock::now(); + const View views[] = {raw_uav(64)}; + auto out = dispatch(*host, *pipe, std::vector<std::uint32_t>(constants.begin(), constants.end()), views, + {}, {groups, 1, 1}, "a dispatch"); + double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - began).count(); + return std::pair{out[0], ms}; + }; + if (name.starts_with("sem")) { + auto [out, ms] = run_once({0, 0x7F80'0000, 0x8000'0000, 0x7FC0'0000}, 1); + (void)ms; + for (std::size_t n = 0; n < out.size() && n < 40; ++n) + std::printf("%s %2zu: %08x %s\n", name.c_str(), n, out[n], display(f32_from_bits(out[n])).c_str()); + continue; + } + const std::array<std::uint32_t, 4> constants = {f32_bits(0.37f), f32_bits(0.11f), 16384, 0}; + run_once(constants, 64); + std::vector<double> times; + for (int k = 0; k < 9; ++k) times.push_back(run_once(constants, 4096).second); + // Rust sort_by(f64::total_cmp): the times are finite and non-negative here. + std::sort(times.begin(), times.end()); + std::printf("%s: %.2f ms (least %.2f)\n", name.c_str(), times[times.size() / 2], times[0]); + } +} + +} // namespace + +int main(int argc, char** argv) { + // Rust #[ignore]: runs only with --ignored. + bool ignored = false; + for (int i = 1; i < argc; ++i) ignored |= std::string_view(argv[i]) == "--ignored"; + if (ignored) + guarded("probe", probe); + else + std::printf("probe: ignored (a tool: X2W_SHADERCFG_PROBE=<folder>, --ignored)\n"); + return test_util::finish("lower_probe_test"); +} diff --git a/tests/x2w_shader/emit/lower_size_test.cpp b/tests/x2w_shader/emit/lower_size_test.cpp new file mode 100644 index 0000000000..8f7c8addbb --- /dev/null +++ b/tests/x2w_shader/emit/lower_size_test.cpp @@ -0,0 +1,356 @@ +// Port of the upstream Rust module emit/size_tests.rs, in Rust order. +// +// End-to-end tests of what a program tells about a view by how it uses it: descriptors read for +// sizes (the dwords of a view no instruction uses) and counters, lowered to DXIL, validated by +// dxil.dll when present, and run on the host GPU and WARP. +// +// (In the Rust reference run, the_record_count_of_a_structured_buffer_read_by_index killed the +// test process without a message; see GMR/vs_port/lower/NOTES.md. Ported all the same.) + +#include "lower_card_util.h" + +using namespace card; + +namespace { + +// Lowers a wave32 compute program of one thread with the table of views at s0 and the view heap +// at s1; `srv`: the dwords and the stride of the used resource at the table's first entry (the +// third is a raw UAV). Throws ShaderError (Rust `?` on every stage). +HostShader build(std::span<const std::uint32_t> words, std::pair<std::uint8_t, std::uint32_t> srv) { + auto param = [](RootType root, std::uint8_t user_data) { return root_param(root, 0, 1, 0, user_data, 0); }; + auto range = [](ResourceType kind, std::uint32_t table_offset_dwords, std::uint8_t dwords, std::uint32_t stride) { + return used_resource(kind, RootType::Table(), table_offset_dwords, 0, stride, dwords, 0, 0); + }; + NativeProgram native; + native.stage = HwStage::Cs; + native.wave64 = false; + native.vgprs = 32; + native.layout = {param(RootType::Table(), 0), param(RootType::ResourceHeap(), 1)}; + native.used = {range(ResourceType::Srv(), 0, srv.first, srv.second), range(ResourceType::Uav(), 16, 4, 0)}; + native.io = compute_io(2 << 1, {1, 1, 1}); + native.code = le_bytes(words); + vs::ir::Program p = vs::ir::build(native.code, native.wave64, native.vgprs); + vs::structure::Structured st = vs::structure::structure(p); + vs::resource::Resources res = vs::resource::track(p, native.layout, native.stage, &st); + vs::io::Io io = vs::io::raise(p, native); + Lowered lowered = vs::lower::lower(parts_of(native, p, st, io, res)); + HostShader shader = host_shader(std::move(lowered), {}); + validate(shader, true); + return shader; +} + +// Rust `build(..).is_ok()`: a ShaderError is an Err; a panic (validation) stays a failure. +bool builds(std::span<const std::uint32_t> words, std::pair<std::uint8_t, std::uint32_t> srv) { + try { + build(words, srv); + return true; + } catch (const ShaderError&) { + return false; + } +} + +// Rust `build(..).expect("translates")`. +HostShader translates(std::span<const std::uint32_t> words, std::pair<std::uint8_t, std::uint32_t> srv) { + try { + return build(words, srv); + } catch (const ShaderError& e) { + fail("translates: " + e.to_string()); + } +} + +// Rust `got[..n] == want`. +bool starts(const std::vector<std::uint32_t>& got, std::initializer_list<std::uint32_t> want) { + return got.size() >= want.size() && std::equal(want.begin(), want.end(), got.begin()); +} + +// The table at s[2:3], its raw UAV's descriptor in s[20:23]. +const std::uint32_t TABLE[] = { + 0xBE82'0300, // s_mov_b32 s2, s0 + 0xBE83'0380, // s_mov_b32 s3, 0 + 0xF408'0501, // s_load_dwordx4 s[20:23], s[2:3], 64 + 0xFA00'0040, +}; + +// Stores s4 and s5 at bytes 0 and 4 of the UAV. +const std::uint32_t STORE[] = { + 0x7E08'0204, // v_mov_b32 v4, s4 + 0x7E0A'0205, // v_mov_b32 v5, s5 + 0xE070'0000, // buffer_store_dword v4, off, s[20:23], 0 + 0x8005'0400, + 0xE070'0004, // buffer_store_dword v5, off, s[20:23], 0 offset:4 + 0x8005'0500, + 0xBF81'0000, // s_endpgm +}; + +// `GetDimensions` of a texture as the console compiler expands it, from the descriptor in +// s[8:15]: width in s4, height in s5, base level in s6. +const std::uint32_t SIZES[] = { + 0x9004'9E09, // s_lshr_b32 s4, s9, 30 + 0x8F05'820A, // s_lshl_b32 s5, s10, 2 + 0x8804'0504, // s_or_b32 s4, s4, s5 + 0x8704'FF04, // s_and_b32 s4, s4, 0xffff + 0x0000'FFFF, + 0x9385'FF0A, // s_bfe_u32 s5, s10, 0x10000e + 0x0010'000E, + 0x9386'FF0B, // s_bfe_u32 s6, s11, 0x4000c + 0x0004'000C, + 0x8104'8104, // s_add_i32 s4, s4, 1 + 0x8105'8105, // s_add_i32 s5, s5, 1 + 0x9004'0604, // s_lshr_b32 s4, s4, s6 + 0x9005'0605, // s_lshr_b32 s5, s5, s6 +}; + +// s_load_dwordx8 s[8:15], s[6:7], s12: entry 1 of the view heap. +const std::uint32_t FROM_HEAP[] = { + 0xBE86'0301, // s_mov_b32 s6, s1 + 0xBE87'0380, // s_mov_b32 s7, 0 + 0xBE8C'03A0, // s_mov_b32 s12, 32 + 0xF40C'0203, + 0x1800'0000, +}; + +// `s_load_dwordx4 s[8:11], s[2:3], 0`, then the record count in s4 and 0 in s5. +const std::uint32_t COUNT[] = { + 0xF408'0201, + 0xFA00'0000, + 0xBE84'030A, // s_mov_b32 s4, s10 + 0xBE85'0380, // s_mov_b32 s5, 0 +}; + +// ---- rs:141 ------------------------------------------------------------------------------------- +// A puddle pass of the title picks three textures from the view heap, reads the first one's size +// and samples the other two. +void the_size_of_a_heap_texture_nothing_reads() { + x2w::vs::lower::test::set_dump_name("emit__size_tests__the_size_of_a_heap_texture_nothing_reads"); + std::vector<std::uint32_t> words = concat({TABLE, FROM_HEAP, SIZES, STORE}); + HostShader shader = translates(words, {8, 0}); + const Texel one[1] = {}; + const Texel texels[15] = {}; + const View views[] = {texture(1, 1, one), texture(5, 3, texels), raw_uav(2)}; + for (auto& [label, got] : run(shader, views)) require(starts(got, {5, 3}), label); +} + +// ---- rs:158 ------------------------------------------------------------------------------------- +// Without the height nothing tells a 2D texture from the others: taken for one, as most are. A +// volume's depth or an array's layers are no 2D texture's. +void sizes_of_a_volume_or_an_array_stay_untranslated() { + x2w::vs::lower::test::set_dump_name("emit__size_tests__sizes_of_a_volume_or_an_array_stay_untranslated"); + const std::uint32_t width[] = { + 0x9004'9E09, // s_lshr_b32 s4, s9, 30 + 0x8F05'820A, // s_lshl_b32 s5, s10, 2 + 0x8804'0504, // s_or_b32 s4, s4, s5 + }; + require(builds(concat({TABLE, FROM_HEAP, width, STORE}), {8, 0}), "width alone translates"); + const std::uint32_t depth[] = { + 0x8805'0C05, // s_or_b32 s5, s5, s12 + }; + require(!builds(concat({TABLE, FROM_HEAP, SIZES, depth, STORE}), {8, 0}), "a depth stays untranslated"); +} + +// ---- rs:177 ------------------------------------------------------------------------------------- +// A water simulation step runs only while a structured buffer is bound: it tests the record count +// of a view it never reads. +void the_record_count_of_a_structured_buffer_nothing_reads() { + x2w::vs::lower::test::set_dump_name("emit__size_tests__the_record_count_of_a_structured_buffer_nothing_reads"); + std::vector<std::uint32_t> words = concat({TABLE, COUNT, STORE}); + HostShader shader = translates(words, {4, 16}); + const std::uint32_t data[12] = {}; + const Texel texel[1] = {}; + // The runtime makes structured views raw. + const View views[] = {buffer(data, stride_raw()), texture(1, 1, texel), raw_uav(2)}; + for (auto& [label, got] : run(shader, views)) require(starts(got, {3, 0}), label); + // A stride of 4 or less may be a typed view's component count. + require(!builds(words, {4, 4}), "stride 4 refused"); + require(!builds(words, {4, 0}), "stride 0 refused"); +} + +// ---- rs:201 ------------------------------------------------------------------------------------- +// As the_record_count_of_a_structured_buffer_nothing_reads, of one the program also reads by +// index. +void the_record_count_of_a_structured_buffer_read_by_index() { + x2w::vs::lower::test::set_dump_name("emit__size_tests__the_record_count_of_a_structured_buffer_read_by_index"); + const std::uint32_t load[] = { + 0x7E06'0280, // v_mov_b32 v3, 0 + 0xE030'2000, // buffer_load_dword v5, v3, s[8:11], 0 idxen + 0x8002'0503, + 0x7E0A'0505, // v_readfirstlane_b32 s5, v5 + }; + std::vector<std::uint32_t> words = concat({TABLE, COUNT, load, STORE}); + HostShader shader = translates(words, {4, 16}); + std::uint32_t data[12] = {}; + data[0] = 77; + const Texel texel[1] = {}; + const View views[] = {buffer(data, stride_raw()), texture(1, 1, texel), raw_uav(2)}; + for (auto& [label, got] : run(shader, views)) require(starts(got, {3, 77}), label); +} + +// ---- rs:228 ------------------------------------------------------------------------------------- +// An upscaler counts its groups in a texture with atomics and sets the counter back with a store +// of one channel, 16 bits wide. +std::vector<std::uint32_t> counter_program(std::array<std::uint32_t, 2> store, std::uint32_t value) { + const std::uint32_t words[] = { + 0xF40C'0201u, // s_load_dwordx8 s[8:15], s[2:3], 0 + 0xFA00'0000, + 0x7E00'0280, // v_mov_b32 v0, 0 + 0x7E02'0280, // v_mov_b32 v1, 0 + 0x7E04'0283, // v_mov_b32 v2, 3 + 0xF044'3108, // image_atomic_add v2, v[0:1], s[8:15] dmask:0x1 2D glc + 0x0002'0200, + value, // v_mov_b32 v3, .. + store[0], + store[1], + 0x7E08'0281, // v_mov_b32 v4, 1 + 0xF044'3108, // image_atomic_add v4, v[0:1], s[8:15] dmask:0x1 2D glc + 0x0002'0400, + 0xBE84'0380, // s_mov_b32 s4, 0 + 0xBE85'0380, // s_mov_b32 s5, 0 + }; + return concat({TABLE, words, STORE}); +} + +void a_counter_texture_is_set_by_a_store_of_one_channel() { + x2w::vs::lower::test::set_dump_name("emit__size_tests__a_counter_texture_is_set_by_a_store_of_one_channel"); + // image_store v3, v[0:1], s[8:15] dmask:0x1 2D, with and without d16 + const std::array<std::uint32_t, 2> stores[] = {{0xF020'1108, 0x0002'0300}, {0xF020'1108, 0x8002'0300}}; + for (const auto& store : stores) { + HostShader shader = translates(counter_program(store, 0x7E06'0289), {8, 0}); // v3 = 9 + const Texel texel[1] = {}; + const View views[] = {uint_texture_uav(1, 1), texture(1, 1, texel), raw_uav(2)}; + for (auto& [label, got] : run(shader, views)) require(!got.empty() && got[0] == 10, label); + } + // Sixteen bits of a number only the card knows may be signed. + require(!builds(counter_program({0xF020'1108, 0x8002'0300}, 0x7E06'0302), {8, 0}), "v3 = v2 refused"); // v3 = v2 + // A store of two channels says nothing about the view. + require(!builds(counter_program({0xF020'1308, 0x0002'0300}, 0x7E06'0289), {8, 0}), "two channels refused"); +} + +// ---- rs:271 ------------------------------------------------------------------------------------- +// A load past the wave's cache (GLC) of a buffer other groups write: its view is globally coherent +// on the host, as is every access to it. +void a_buffer_loaded_past_the_cache_is_coherent() { + x2w::vs::lower::test::set_dump_name("emit__size_tests__a_buffer_loaded_past_the_cache_is_coherent"); + auto program = [](std::uint32_t load) { + const std::uint32_t words[] = { + 0x7E04'028Bu, // v_mov_b32 v2, 11 + 0xE070'0008, // buffer_store_dword v2, off, s[20:23], 0 offset:8 + 0x8005'0200, + load, // buffer_load_dword v3, off, s[20:23], 0 offset:8 + 0x8005'0300, + 0x7E08'0503, // v_readfirstlane_b32 s4, v3 + 0xBE85'0380, // s_mov_b32 s5, 0 + }; + return translates(concat({TABLE, words, STORE}), {8, 0}); + }; + // (Rust evaluates the tuple left to right: plain first.) + HostShader plain = program(0xE030'0008); + HostShader coherent = program(0xE030'C008); + // the annotations of the store's and the load's handles + require(plain.dxil != coherent.dxil, "plain.dxil != coherent.dxil"); + const Texel texel[1] = {}; + const View views[] = {texture(1, 1, texel), texture(1, 1, texel), raw_uav(3)}; + for (const HostShader* shader : {&plain, &coherent}) + for (auto& [label, got] : run(*shader, views)) require(starts(got, {11, 0, 11}), label); +} + +// ---- rs:303 ------------------------------------------------------------------------------------- +// A buffer picked from the view heap and read as raw bytes is read at the host's raw twin of its +// slot, when the host keeps some; an index past the title's slots reads the last twin, not a slot +// of something else. +void a_picked_buffer_is_read_at_its_raw_twin() { + x2w::vs::lower::test::set_dump_name("emit__size_tests__a_picked_buffer_is_read_at_its_raw_twin"); + auto program = [](std::uint32_t at) { + const std::uint32_t words[] = { + 0xBE86'0301, // s_mov_b32 s6, s1 + 0xBE87'0380, // s_mov_b32 s7, 0 + 0xBE8C'03FF, // s_mov_b32 s12, at + at, + 0xF408'0203, // s_load_dwordx4 s[8:11], s[6:7], s12 + 0x1800'0000, + 0xE030'0004, // buffer_load_dword v5, off, s[8:11], 0 offset:4 + 0x8002'0500, + 0x7E0A'0505, // v_readfirstlane_b32 s5, v5 + 0xBE84'0380, // s_mov_b32 s4, 0 + }; + return concat({TABLE, words, STORE}); + }; + const std::uint32_t title[] = {1, 2, 3, 4}; + const std::uint32_t twin[] = {5, 6, 7, 8}; + const std::uint32_t last[] = {9, 10, 11, 12}; + const Texel texel[1] = {}; + auto raw = [](std::span<const std::uint32_t> data) { return buffer(data, stride_raw()); }; + // (The store goes through the table's third entry: its twin, too.) + auto views = [&](bool twins) { + auto uav = [&](bool here) { return here ? raw_uav(2) : texture(1, 1, texel); }; + return std::vector<View>{ + texture(1, 1, texel), raw(title), uav(!twins), texture(1, 1, texel), + texture(1, 1, texel), raw(twin), uav(twins), raw(last), + }; + }; + const std::array<std::uint32_t, 3> cases[] = {{0, 32, 2}, {4, 32, 6}, {4, 32 * 1000, 10}}; + for (auto [first, at, expected] : cases) { + HostShader shader; + { + RawViewsHere here(first); // Rust RAW_VIEWS_HERE.set(Some(first)) ... .set(None) + shader = translates(program(at), {8, 0}); + } + std::vector<View> v = views(first != 0); + for (auto& [label, got] : run(shader, v)) + require(starts(got, {0, expected}), std::string(label) + ": twins from " + std::to_string(first) + + ", byte " + std::to_string(at)); + } +} + +// ---- rs:349 ------------------------------------------------------------------------------------- +// A table's buffer read as raw bytes is read at its raw twin too. +void a_tables_raw_buffer_is_read_at_its_raw_twin() { + x2w::vs::lower::test::set_dump_name("emit__size_tests__a_tables_raw_buffer_is_read_at_its_raw_twin"); + const std::uint32_t load[] = { + 0xF408'0201u, // s_load_dwordx4 s[8:11], s[2:3], 0 + 0xFA00'0000, + 0xE030'0004, // buffer_load_dword v5, off, s[8:11], 0 offset:4 + 0x8002'0500, + 0x7E0A'0505, // v_readfirstlane_b32 s5, v5 + 0xBE84'0380, // s_mov_b32 s4, 0 + }; + std::vector<std::uint32_t> words = concat({TABLE, load, STORE}); + const std::uint32_t title[] = {1, 2, 3, 4}; + const std::uint32_t twin[] = {5, 6, 7, 8}; + const Texel texel[1] = {}; + HostShader shader; + { + RawViewsHere here(4); + shader = translates(words, {4, 0}); + } + auto other = [&] { return texture(1, 1, texel); }; + const View views[] = {buffer(title, stride_raw()), other(), other(), other(), buffer(twin, stride_raw()), + other(), raw_uav(2)}; + for (auto& [label, got] : run(shader, views)) require(starts(got, {0, 6}), label); +} + +} // namespace + +int main(int argc, char** argv) { + // `--skip <name>` leaves a test out (as cargo test's --skip; the Rust run skipped + // the_record_count_of_a_structured_buffer_read_by_index, which ended the process there). + std::vector<std::string_view> skip; + for (int i = 1; i + 1 < argc; ++i) + if (std::string_view(argv[i]) == "--skip") skip.push_back(argv[++i]); + auto guarded = [&](const char* name, void (*f)()) { + if (std::find(skip.begin(), skip.end(), std::string_view(name)) != skip.end()) { + std::fprintf(stderr, "%s: skipped\n", name); + return; + } + card::guarded(name, f); + }; + guarded("the_size_of_a_heap_texture_nothing_reads", the_size_of_a_heap_texture_nothing_reads); + guarded("sizes_of_a_volume_or_an_array_stay_untranslated", sizes_of_a_volume_or_an_array_stay_untranslated); + guarded("the_record_count_of_a_structured_buffer_nothing_reads", + the_record_count_of_a_structured_buffer_nothing_reads); + guarded("the_record_count_of_a_structured_buffer_read_by_index", + the_record_count_of_a_structured_buffer_read_by_index); + guarded("a_counter_texture_is_set_by_a_store_of_one_channel", a_counter_texture_is_set_by_a_store_of_one_channel); + guarded("a_buffer_loaded_past_the_cache_is_coherent", a_buffer_loaded_past_the_cache_is_coherent); + guarded("a_picked_buffer_is_read_at_its_raw_twin", a_picked_buffer_is_read_at_its_raw_twin); + guarded("a_tables_raw_buffer_is_read_at_its_raw_twin", a_tables_raw_buffer_is_read_at_its_raw_twin); + return test_util::finish("lower_size_test"); +} diff --git a/tests/x2w_shader/emit/lower_test.cpp b/tests/x2w_shader/emit/lower_test.cpp new file mode 100644 index 0000000000..e85209c5ef --- /dev/null +++ b/tests/x2w_shader/emit/lower_test.cpp @@ -0,0 +1,685 @@ +// Port of the tests in the upstream Rust module emit/lower.rs (#[cfg(test)] mod tests), in Rust order. +// +// None of these runs on a GPU: they lower synthetic GFX10 compute programs and check that the +// lowering succeeds or what it reports (features, handle counts), and test lower.rs's private +// helpers (packing, buffer formats, small floats) directly. + +#include <algorithm> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <limits> +#include <optional> +#include <span> +#include <string> +#include <string_view> +#include <utility> +#include <vector> + +#include "x2w_shader/dxbc.h" +#include "x2w_shader/emit/container.h" +#include "x2w_shader/emit/lower.h" +#include "x2w_shader/emit/lower_impl.h" // buffer_format, half_shift, packed_half, half_input_partners +#include "x2w_shader/io.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/native.h" +#include "x2w_shader/resource.h" +#include "resource_fixtures.h" // vs-front: tests/x2w_shader/resource_fixtures.h +#include "x2w_shader/structure.h" +#include "test_util.h" + +namespace vs = x2w::vs; +using vs::container::SigElement; +using vs::lower::Lowered; +using vs::lower::Numeric; +using vs::lower::Parts; +using vs::native::ComputeIo; +using vs::native::HwStage; +using vs::native::NativeProgram; +using vs::native::ResourceType; +using vs::native::RootParam; +using vs::native::RootType; +using vs::native::StageIo; +using vs::native::UsedResource; + +namespace { + +constexpr std::uint32_t S_ENDPGM = 0xBF81'0000; + +std::vector<std::uint8_t> le_bytes(std::span<const std::uint32_t> words) { + std::vector<std::uint8_t> code; + code.reserve(words.size() * 4); + for (std::uint32_t w : words) + for (int k = 0; k < 4; ++k) code.push_back(static_cast<std::uint8_t>(w >> (8 * k))); + return code; +} + +// Rust `lower(&Parts { native, p, st, io, res, inputs: vec![], outputs: vec![], prims: vec![], +// mesh_stride: 0 })` over the front end's results for `native`. `track_may_fail`: Rust's `?` on +// resource::track (lower_wave) vs. `.unwrap()` (lowers): both throw ShaderError here. +Lowered lower_native(const NativeProgram& native) { + vs::ir::Program p = vs::ir::build(native.code, native.wave64, 256); + vs::structure::Structured st = vs::structure::structure(p); + // FRONT? resource::track(p, layout, stage, Option<&Structured>) -> Resources (throws) + vs::resource::Resources res = vs::resource::track(p, native.layout, native.stage, &st); + // FRONT? io::raise(p, native) -> Io (throws) + vs::io::Io io = vs::io::raise(p, native); + Parts parts; + parts.native = &native; + parts.p = &p; + parts.st = &st; + parts.io = &io; + parts.res = &res; + parts.mesh_stride = 0; + return vs::lower::lower(parts); +} + +// ---- rs:12722 ----------------------------------------------------------------------------------- +void packed_pixel_inputs_find_their_second_row() { + auto entry = [](std::uint8_t row, std::uint8_t row2, bool pack2) { + vs::native::PsInput e; + e.usage = vs::native::Usage::Generic(); + e.row = row; + e.mask = 0xF; + e.attr = row; + e.flat = false; + e.fp16 = true; + e.pack2 = pack2; + e.row2 = row2; + return e; + }; + auto element = [](std::uint32_t row) { + SigElement e; + e.name = "TEXCOORD"; + e.index = row; + e.kind = 0; + e.comp = 9; + e.interp = 2; + e.row = row; + e.col = 0; + e.cols = 4; + e.usage = 0; + e.half = true; + return e; + }; + // Rows 0 and 3 pack and leave their second row out; 5 names its own (6). Unnamed 16-bit + // rows: 1, 4, 6, 7. + vs::native::PsIo ps; + ps.inputs = {entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)}; + ps.input_addr = 0; + ps.db_shader_control = 0; + StageIo io = ps; + std::vector<SigElement> sig; + for (std::uint32_t r : {0u, 1u, 3u, 4u, 5u, 6u, 7u}) sig.push_back(element(r)); + auto p = vs::lower::half_input_partners(io, sig); + auto get = [&](std::uint8_t k) -> std::optional<std::uint8_t> { + auto it = p.find(k); + if (it == p.end()) return std::nullopt; + return it->second; + }; + CHECK(get(0) == std::optional<std::uint8_t>(1)); + CHECK(get(3) == std::optional<std::uint8_t>(4)); + CHECK(get(5) == std::nullopt); +} + +// ---- rs:12767 ----------------------------------------------------------------------------------- +// Each element starts on a whole dword, even when it shares a source register. +void packed_elements_behind_another_take_the_first_free_dword() { + auto element = [](std::uint32_t index, std::uint32_t row, std::uint8_t col, std::uint8_t cols) { + SigElement e; + e.name = "TEXCOORD"; + e.index = index; + e.kind = 0; + e.comp = 9; + e.interp = 2; + e.row = row; + e.col = col; + e.cols = cols; + e.usage = 0; + e.half = true; + return e; + }; + using Pack = std::pair<std::uint8_t, std::optional<std::uint8_t>>; + using Got = std::optional<std::pair<std::uint8_t, std::uint8_t>>; + auto some = [](std::uint8_t a, std::uint8_t b) { return Got(std::pair<std::uint8_t, std::uint8_t>(a, b)); }; + // Rows 8 and 13 occupy four dwords. The trailing scalar from row 8 + // must move to the spare dword in a separate, unpaired parameter. + { + std::vector<SigElement> sig = { + element(0, 8, 0, 3), element(1, 8, 3, 1), + element(2, 13, 0, 3), element(3, 17, 0, 2), + }; + std::vector<Pack> packs = {{8, 13}, {17, std::nullopt}}; + auto at = [&](std::uint8_t a, std::uint8_t h) { return vs::lower::packed_half(sig, packs, a, h); }; + CHECK(at(8, 2) == some(8, 2)); + CHECK(at(8, 3) == std::nullopt); + CHECK(at(8, 4) == some(13, 0)); + CHECK(at(8, 7) == std::nullopt); + CHECK(at(17, 1) == some(17, 1)); + CHECK(at(17, 2) == some(8, 3)); + CHECK(at(17, 3) == std::nullopt); + } + // A scalar lead leaves half a dword unused. Its three-component + // neighbor starts only after the partner row, even with shuffled inputs. + { + std::vector<SigElement> sig = { + element(2, 23, 0, 2), element(1, 21, 1, 3), element(0, 21, 0, 1), + }; + std::vector<Pack> packs = {{34, std::nullopt}, {21, 23}}; + auto at = [&](std::uint8_t a, std::uint8_t h) { return vs::lower::packed_half(sig, packs, a, h); }; + CHECK(at(21, 0) == some(21, 0)); + CHECK(at(21, 1) == std::nullopt); + CHECK(at(21, 2) == some(23, 0)); + CHECK(at(21, 3) == some(23, 1)); + CHECK(at(21, 4) == some(21, 1)); + CHECK(at(21, 6) == some(21, 3)); + CHECK(at(21, 7) == std::nullopt); + CHECK(at(34, 0) == std::nullopt); + } +} + +// ---- rs:12844 ----------------------------------------------------------------------------------- +// Whether a synthetic compute program translates with these input registers. Throws ShaderError. +void lowers(std::span<const std::uint32_t> words, std::uint32_t rsrc2) { + NativeProgram native; + native.stage = HwStage::Cs; + native.wave64 = false; + native.vgprs = 256; + ComputeIo cs; + cs.rsrc2 = rsrc2; + cs.threads = {1, 1, 1}; + native.io = cs; + native.code = le_bytes(words); + (void)lower_native(native); +} + +// rs:12887: lower_with in wave64 if `wave64`. Throws ShaderError. +Lowered lower_wave(std::span<const std::uint32_t> words, std::vector<RootParam> layout, + std::vector<UsedResource> used, bool wave64) { + std::uint32_t sgprs = 0; + for (const RootParam& p : layout) sgprs += p.sgprs; + NativeProgram native; + native.stage = HwStage::Cs; + native.wave64 = wave64; + native.vgprs = 256; + native.layout = std::move(layout); + native.used = std::move(used); + ComputeIo cs; + // The layout's user SGPRs (at least two), 512 bytes of LDS. + cs.rsrc2 = 1u << 15 | (sgprs > 2 ? sgprs : 2) << 1; + cs.threads = {1, 1, 1}; + native.io = cs; + native.code = le_bytes(words); + return lower_native(native); +} + +// rs:12878: lowers a compute program with the root parameters `layout` (in user SGPRs from s0 on) +// and the used resources `used`. +Lowered lower_with(std::span<const std::uint32_t> words, std::vector<RootParam> layout, + std::vector<UsedResource> used) { + return lower_wave(words, std::move(layout), std::move(used), false); +} + +// rs:12926: root parameter `slot` in user SGPRs from `user_data` on. +RootParam root(RootType root, std::uint8_t user_data, std::uint8_t slot) { + RootParam p; + p.root = root; + p.table_offset_dwords = 0; + p.sgprs = root == RootType::Descriptor() ? 2 : 1; + p.base_register = 0; + p.user_data = user_data; + p.slot = slot; + return p; +} + +// rs:12940: lowers a one-thread compute program that copies four root constants (s0..s3) into +// v1..v4, runs `body`, and stores v0 to a raw buffer from a descriptor table, so the vector +// instructions in `body` have an effect. Throws ShaderError. +void lowers_valu(std::span<const std::uint32_t> body) { + std::vector<std::uint32_t> words = { + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xF408'0202, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xFA00'0000, + }; + // v_mov_b32 v1..v4, s0..s3 + for (std::uint32_t i = 0; i < 4; ++i) words.push_back(0x7E00'0200u | (i + 1) << 17 | i); + words.insert(words.end(), body.begin(), body.end()); + for (std::uint32_t w : {0xE070'0000u, // buffer_store_dword v0, off, s[8:11], 0 + 0x8002'0000u, S_ENDPGM}) + words.push_back(w); + RootParam constants = root(RootType::Constants(), 0, 0); + constants.sgprs = 4; + UsedResource buffer; + buffer.kind = ResourceType::Uav(); + buffer.root = RootType::Table(); + buffer.table_offset_dwords = 0; + buffer.lower_bound = 0; + buffer.stride = 0; + buffer.dwords = 4; + buffer.user_data = 4; + buffer.slot = 1; + (void)lower_with(words, {constants, root(RootType::Table(), 4, 1)}, {buffer}); +} + +// Rust `.unwrap_or_else(|e| panic!(...))` / `.unwrap()` / `.is_ok()` for a throwing call. +template <class F> +bool succeeds(F&& f, const char* what) { + try { + f(); + return true; + } catch (const vs::ShaderError& e) { + std::fprintf(stderr, "%s: %s\n", what, e.to_string().c_str()); + return false; + } +} + +// ---- rs:12977 ----------------------------------------------------------------------------------- +void the_24_bit_multiplies_lower_both_halves() { + // VOP2 `op v0, v1, v2`: v_mul_i32_i24 and v_mul_u32_u24 (the low dword) and v_mul_hi_i32_i24 + // and v_mul_hi_u32_u24 (the high one). + for (std::uint32_t op : {0x09u, 0x0Au, 0x0Bu, 0x0Cu}) { + std::uint32_t word = op << 25 | 2u << 9 | 0x101u; + char what[32]; + std::snprintf(what, sizeof what, "VOP2 %#x", op); + CHECK(succeeds([&] { lowers_valu(std::span<const std::uint32_t>(&word, 1)); }, what)); + } +} + +// ---- rs:12987 ----------------------------------------------------------------------------------- +void buffer_cache_invalidations_lower_as_no_ops() { + // MUBUF opcode 0x071/0x072 with no data operand: the title asks the host to invalidate its + // cached view of a buffer. + const std::uint32_t gl0[] = {0xE1C4'0000, 0, S_ENDPGM}; + const std::uint32_t gl1[] = {0xE1C8'0000, 0, S_ENDPGM}; + CHECK(succeeds([&] { lowers(gl0, 0); }, "buffer_gl0_inv")); + CHECK(succeeds([&] { lowers(gl1, 0); }, "buffer_gl1_inv")); +} + +// ---- rs:12995 ----------------------------------------------------------------------------------- +void sums_of_absolute_differences_lower() { + // VOP3 `op v0, v1, v2, v3`: v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32 and v_msad_u8. + for (std::uint32_t op : {0x15Au, 0x15Bu, 0x15Cu, 0x15Du, 0x171u}) { + const std::uint32_t words[] = {0xD400'0000u | op << 16, 0x101u | 0x102u << 9 | 0x103u << 18}; + char what[32]; + std::snprintf(what, sizeof what, "VOP3 %#x", op); + CHECK(succeeds([&] { lowers_valu(words); }, what)); + } +} + +// ---- rs:13005 ----------------------------------------------------------------------------------- +void a_scalar_carry_chain_reaches_the_select() { + // The high dword of a 64-bit add or subtract, then a select on the carry (borrow) the high + // half leaves in SCC, and a branch on it (only code with an effect needs its operands). + const std::uint32_t add[] = { + 0xBE80'03C1, // s_mov_b32 s0, -1 + 0xBE81'0380, // s_mov_b32 s1, 0 + 0x8000'8100, // s_add_u32 s0, s0, 1 + 0x8201'8001, // s_addc_u32 s1, s1, 0 + 0x8502'0001, // s_cselect_b32 s2, s1, s0 + 0xBF07'8002, // s_cmp_lg_u32 s2, 0 + 0xBF85'0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83'0380, // s_mov_b32 s3, 0 + S_ENDPGM, + }; + const std::uint32_t sub[] = { + 0xBE80'0380, // s_mov_b32 s0, 0 + 0xBE81'0380, // s_mov_b32 s1, 0 + 0x8080'8100, // s_sub_u32 s0, s0, 1 + 0x8281'8001, // s_subb_u32 s1, s1, 0 + 0x8502'0001, // s_cselect_b32 s2, s1, s0 + 0xBF07'8002, // s_cmp_lg_u32 s2, 0 + 0xBF85'0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83'0380, // s_mov_b32 s3, 0 + S_ENDPGM, + }; + CHECK(succeeds([&] { lowers(add, 0); }, "add")); + CHECK(succeeds([&] { lowers(sub, 0); }, "sub")); +} + +// ---- rs:13037 ----------------------------------------------------------------------------------- +std::uint64_t perm_features(std::uint32_t selector) { + // Synthetic compute shader: v0 is the thread ID and can supply a dynamic selector. Store the + // result in LDS to keep the permutation live. + const std::uint32_t words[] = { + 0x7E02'02FFu, 0x817F'34AB, 0x7E04'02FF, 0xFE01'56CD, 0xD744'0003, + 257u | (258u << 9) | (selector << 18), 0x3408'0082, 0xD834'0000, 0x0000'0304, S_ENDPGM, + }; + NativeProgram native; + native.stage = HwStage::Cs; + native.wave64 = false; + native.vgprs = 256; + ComputeIo cs; + cs.rsrc2 = 1u << 15; + cs.threads = {64, 1, 1}; + native.io = cs; + native.code = le_bytes(words); + + vs::ir::Program p = vs::ir::build(native.code, false, 256); + bool perm = false; + for (const auto& b : p.blocks) + for (const auto& i : b.insts) perm = perm || i.name() == "v_perm_b32"; + CHECK(perm); + + Lowered emitted = lower_native(native); + vs::dxbc::Container container = vs::dxbc::Container::parse(emitted.dxil); + const vs::dxbc::Part* features = container.part(vs::dxbc::FourCC::SFI0); + CHECK(features != nullptr); + if (!features) return ~std::uint64_t{0}; + CHECK(features->data.size() == 8); // Rust `try_into().unwrap()` of 8 bytes + if (features->data.size() != 8) return ~std::uint64_t{0}; + std::uint64_t v = 0; + for (int k = 0; k < 8; ++k) v |= std::uint64_t(features->data[k]) << (8 * k); + return v; +} + +// ---- rs:13104 ----------------------------------------------------------------------------------- +void perm_constant_selector_needs_no_int64() { CHECK((perm_features(128) & 0x8000) == 0); } + +// ---- rs:13109 ----------------------------------------------------------------------------------- +void perm_dynamic_selector_needs_no_int64() { + // dynamic v_perm_b32 must not require INT64 + CHECK((perm_features(256) & 0x8000) == 0); +} + +// ---- rs:13118 ----------------------------------------------------------------------------------- +void a_descriptor_selected_by_scc_picks_its_heap_index() { + // Two buffer descriptors loaded from the table at s0, one picked by a root constant (s1) with + // s_cselect_b64 per half, and loaded through by index and stored to LDS so the load is needed. + const std::uint32_t words[] = { + 0xBE84'0300, // s_mov_b32 s4, s0 + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xF408'0202, + 0xFA00'0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xF408'0302, + 0xFA00'0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 + 0xBF06'8001, // s_cmp_eq_u32 s1, 0 + 0x8590'0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] + 0x8592'0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] + 0xE030'2000, + 0x8004'0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen + 0xD834'0000, + 0x0000'0100, // ds_write_b32 v0, v1 + S_ENDPGM, + }; + std::vector<RootParam> layout = {root(RootType::Table(), 0, 0), root(RootType::Constants(), 1, 1)}; + // Both are structured buffers of dwords in the table's range. + UsedResource u; + u.kind = ResourceType::Srv(); + u.root = RootType::Table(); + u.table_offset_dwords = 0; + u.lower_bound = 0; + u.stride = 4; + u.dwords = 4; + u.user_data = 0; + u.slot = 0; + CHECK(succeeds([&] { (void)lower_with(words, layout, {u}); }, "scc-selected descriptor")); +} + +// ---- rs:13156 ----------------------------------------------------------------------------------- +// Tables of 2D textures at s0 and samplers at s1. +std::pair<std::vector<RootParam>, std::vector<UsedResource>> texture_tables() { + auto range = [](ResourceType kind, std::uint8_t user_data, std::uint8_t slot) { + UsedResource u; + u.kind = kind; + u.root = RootType::Table(); + u.table_offset_dwords = 0; + u.lower_bound = 0; + u.stride = 0; + u.dwords = kind == ResourceType::Sampler() ? 4 : 8; + u.user_data = user_data; + u.slot = slot; + return u; + }; + return { + {root(RootType::Table(), 0, 0), root(RootType::Table(), 1, 1)}, + {range(ResourceType::Srv(), 0, 0), range(ResourceType::Sampler(), 1, 1)}, + }; +} + +// ---- rs:13177 ----------------------------------------------------------------------------------- +void waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { + namespace fx = vs::resource::fixtures; + const std::pair<std::span<const std::uint32_t>, bool> cases[] = { + {fx::WATERFALL_FETCHED_WAVE32, false}, + {fx::WATERFALL_FETCHED_WAVE64, true}, + {fx::WATERFALL_PICKED_WAVE32, false}, + }; + for (const auto& [words, wave64] : cases) { + auto [layout, used] = texture_tables(); + std::optional<Lowered> l; + CHECK(succeeds([&] { l = lower_wave(words, layout, used, wave64); }, "waterfall")); + if (!l) continue; + // The loop's reads of the first lane became each lane's own dwords: no wave operation is + // left. + CHECK(l->nonuniform_handles == 1); + CHECK(!l->wave_ops); + } +} + +// ---- rs:13196 ----------------------------------------------------------------------------------- +// texture_tables with a raw buffer UAV at dword 16 of the first (pub(crate) in Rust: the +// waterfall/size tests use it too). +std::pair<std::vector<RootParam>, std::vector<UsedResource>> texture_and_uav_tables() { + auto [layout, used] = texture_tables(); + UsedResource u; + u.kind = ResourceType::Uav(); + u.root = RootType::Table(); + u.table_offset_dwords = 16; + u.lower_bound = 0; + u.stride = 0; + u.dwords = 4; + u.user_data = 0; + u.slot = 0; + used.push_back(u); + return {layout, used}; +} + +// ---- rs:13212 ----------------------------------------------------------------------------------- +void waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { + namespace fx = vs::resource::fixtures; + const std::span<const std::uint32_t> cases[] = {fx::WATERFALL_JOINED_WAVE32, + fx::WATERFALL_JOINED_MIXED_WAVE32}; + for (const auto& words : cases) { + auto [layout, used] = texture_and_uav_tables(); + std::optional<Lowered> l; + CHECK(succeeds([&] { l = lower_wave(words, layout, used, false); }, "joined waterfall")); + if (!l) continue; + // One image handle, from the join's per-lane heap index. + CHECK(l->nonuniform_handles == 1); + CHECK(!l->wave_ops); + } +} + +// ---- rs:13224 ----------------------------------------------------------------------------------- +void scalar_bit_tests_lower() { + // Each tests one bit of a constant into SCC and branches on it (only code with an effect + // needs its operands). + const std::uint32_t tail[] = { + 0xBF85'0001, // s_cbranch_scc1 -> s_endpgm + 0xBE84'0380, // s_mov_b32 s4, 0 + S_ENDPGM, + }; + const std::vector<std::vector<std::uint32_t>> bit_tests = { + {0xBE81'0387, 0xBF0C'8301}, // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 + {0xBE81'0387, 0xBF0D'8301}, // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 + { + 0xBE80'0387, // s_mov_b32 s0, 7 + 0xBE81'0380, // s_mov_b32 s1, 0 + 0xBF0E'8300, // s_bitcmp0_b64 s[0:1], 3 + }, + { + 0xBE80'0387, // s_mov_b32 s0, 7 + 0xBE81'0380, // s_mov_b32 s1, 0 + 0xBF0F'8300, // s_bitcmp1_b64 s[0:1], 3 + }, + }; + for (const auto& head : bit_tests) { + std::vector<std::uint32_t> words = head; + words.insert(words.end(), std::begin(tail), std::end(tail)); + CHECK(succeeds([&] { lowers(words, 0); }, "bit test")); + } +} + +// ---- rs:13254 ----------------------------------------------------------------------------------- +// #[ignore = "ours marks joins read through joins only with X2W_SHADERCFG_STRICT_JOINS (40 programs stop +// otherwise)"]: compiled, run only with the argument `--ignored`. +void a_missing_value_stays_missing_through_two_live_joins() { + std::uint32_t words[] = { + 0xF490'0180, + 0, // s_memtime s[6:7] + 0xBF06'8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85'0001, // skip the first overwrite + 0xBE86'0380, // s_mov_b32 s6, 0 + 0xBF06'8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) + 0xBF85'0001, // skip the second overwrite + 0xBE86'0381, // s_mov_b32 s6, 1 + 0xBF07'8006, // s_cmp_lg_u32 s6, 0 + 0xBF85'0001, // use the result to branch + 0xBE83'0380, + S_ENDPGM, + }; + const std::uint32_t group_ids_xy = 3u << 7; + // Compare to a direct read so future timestamp support works in both cases. Rust panics on + // any error other than Unsupported; that is a failed CHECK here. + bool other_error = false; + auto refusal = [&](std::span<const std::uint32_t> code) -> std::optional<std::string> { + try { + lowers(code, group_ids_xy); + return std::nullopt; + } catch (const vs::ShaderError& e) { + if (e.kind == vs::ShaderError::Kind::Unsupported) return std::string(e.reason); + std::fprintf(stderr, "%s\n", e.to_string().c_str()); + other_error = true; + return std::nullopt; + } + }; + std::vector<std::uint32_t> direct(words, words + 2); + direct.insert(direct.end(), words + 8, std::end(words)); + CHECK(refusal(words) == refusal(direct)); + CHECK(!other_error); + words[8] = 0xBF07'8000; // read the group id instead; the timestamp is dead + CHECK(succeeds([&] { lowers(words, group_ids_xy); }, "dead timestamp")); +} + +// ---- rs:13283 ----------------------------------------------------------------------------------- +bool format_is(std::uint8_t format, std::initializer_list<std::uint32_t> bits, Numeric numeric) { + auto f = vs::lower::buffer_format(format); + if (!f) return false; + if (f->second != numeric || f->first.size() != bits.size()) return false; + return std::equal(f->first.begin(), f->first.end(), bits.begin()); +} + +void buffer_formats_by_number() { + // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, 2_10_10_10_UNORM, 16_FLOAT, + // 32_32_32_32_FLOAT. + CHECK(format_is(56, {8, 8, 8, 8}, Numeric::Unorm)); + CHECK(format_is(24, {16, 16}, Numeric::Snorm)); + CHECK(format_is(50, {10, 10, 10, 2}, Numeric::Unorm)); + CHECK(format_is(13, {16}, Numeric::Float)); + CHECK(format_is(77, {32, 32, 32, 32}, Numeric::Float)); + // Invalid, past the table. + CHECK(!vs::lower::buffer_format(0)); + CHECK(!vs::lower::buffer_format(78)); +} + +// ---- rs:13303 ----------------------------------------------------------------------------------- +void packed_buffer_formats_by_number() { + // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, 10_10_10_2 44-49. Channels from the + // lowest bits: R11G11B10_FLOAT is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. + CHECK(format_is(30, {11, 11, 10}, Numeric::Unorm)); + CHECK(format_is(36, {11, 11, 10}, Numeric::Float)); + CHECK(format_is(37, {10, 11, 11}, Numeric::Unorm)); + CHECK(format_is(43, {10, 11, 11}, Numeric::Float)); + CHECK(format_is(44, {2, 10, 10, 10}, Numeric::Unorm)); + CHECK(format_is(45, {2, 10, 10, 10}, Numeric::Snorm)); + CHECK(format_is(46, {2, 10, 10, 10}, Numeric::Uscaled)); + CHECK(format_is(47, {2, 10, 10, 10}, Numeric::Sscaled)); + CHECK(format_is(48, {2, 10, 10, 10}, Numeric::Uint)); + CHECK(format_is(49, {2, 10, 10, 10}, Numeric::Sint)); +} + +// rs:13339: a half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as legacyF16ToF32 +// widens it. 2f32.powi(n) is exact for these n: std::ldexp(1.0f, n). +float half(std::uint32_t h) { + std::uint32_t s = (h >> 15) & 1, e = (h >> 10) & 31, m = h & 1023; + float v; + if (e == 0) { + v = static_cast<float>(m) * std::ldexp(1.0f, -24); + } else if (e == 31 && m == 0) { + v = std::numeric_limits<float>::infinity(); + } else if (e == 31) { + v = std::numeric_limits<float>::quiet_NaN(); + } else { + v = static_cast<float>(1024 + m) * std::ldexp(1.0f, static_cast<int>(e) - 25); + } + return s == 1 ? -v : v; +} + +// ---- rs:13351 ----------------------------------------------------------------------------------- +void small_floats_widen_as_halves() { + // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a 6- or 5-bit mantissa, no + // sign; values from the D3D/GL spec. + auto f11 = [](std::uint32_t x) { return half(x << vs::lower::half_shift(11)); }; + auto f10 = [](std::uint32_t x) { return half(x << vs::lower::half_shift(10)); }; + const float inf = std::numeric_limits<float>::infinity(); + CHECK(f11(0) == 0.0f); + CHECK(f11(0x001) == std::ldexp(1.0f, -20)); // smallest denormal + CHECK(f11(0x03F) == 63.0f * std::ldexp(1.0f, -20)); // largest denormal + CHECK(f11(0x040) == std::ldexp(1.0f, -14)); // smallest normal + CHECK(f11(0x3C0) == 1.0f); + CHECK(f11(0x3E0) == 1.5f); + CHECK(f11(0x7BF) == 65024.0f); // largest + CHECK(f11(0x7C0) == inf); + CHECK(std::isnan(f11(0x7C1))); + CHECK(f10(0x001) == std::ldexp(1.0f, -19)); + CHECK(f10(0x020) == std::ldexp(1.0f, -14)); + CHECK(f10(0x1E0) == 1.0f); + CHECK(f10(0x3DF) == 64512.0f); + CHECK(f10(0x3E0) == inf); + CHECK(std::isnan(f10(0x3FF))); + // A 16-bit float is a half already, sign included. + CHECK(half(0xBC00u << vs::lower::half_shift(16)) == -1.0f); +} + +} // namespace + +int main(int argc, char** argv) { + bool ignored = argc > 1 && std::string_view(argv[1]) == "--ignored"; + if (ignored) { + x2w::vs::lower::test::set_dump_name("emit__lower__tests__a_missing_value_stays_missing_through_two_live_joins"); + a_missing_value_stays_missing_through_two_live_joins(); + return test_util::finish("lower_test --ignored"); + } + x2w::vs::lower::test::set_dump_name("emit__lower__tests__packed_pixel_inputs_find_their_second_row"); + packed_pixel_inputs_find_their_second_row(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__packed_elements_behind_another_take_the_first_free_dword"); + packed_elements_behind_another_take_the_first_free_dword(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__the_24_bit_multiplies_lower_both_halves"); + the_24_bit_multiplies_lower_both_halves(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__buffer_cache_invalidations_lower_as_no_ops"); + buffer_cache_invalidations_lower_as_no_ops(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__sums_of_absolute_differences_lower"); + sums_of_absolute_differences_lower(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__a_scalar_carry_chain_reaches_the_select"); + a_scalar_carry_chain_reaches_the_select(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__perm_constant_selector_needs_no_int64"); + perm_constant_selector_needs_no_int64(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__perm_dynamic_selector_needs_no_int64"); + perm_dynamic_selector_needs_no_int64(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__a_descriptor_selected_by_scc_picks_its_heap_index"); + a_descriptor_selected_by_scc_picks_its_heap_index(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own"); + waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own"); + waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__scalar_bit_tests_lower"); + scalar_bit_tests_lower(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__buffer_formats_by_number"); + buffer_formats_by_number(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__packed_buffer_formats_by_number"); + packed_buffer_formats_by_number(); + x2w::vs::lower::test::set_dump_name("emit__lower__tests__small_floats_widen_as_halves"); + small_floats_widen_as_halves(); + return test_util::finish("lower_test"); +} diff --git a/tests/x2w_shader/emit/lower_valu_test.cpp b/tests/x2w_shader/emit/lower_valu_test.cpp new file mode 100644 index 0000000000..c2ab8dfa9d --- /dev/null +++ b/tests/x2w_shader/emit/lower_valu_test.cpp @@ -0,0 +1,1952 @@ +// Port of the upstream Rust module emit/valu_tests.rs, the tests in Rust order. +// +// End-to-end tests of synthetic GFX10 VALU shaders lowered to DXIL, validated by dxil.dll when +// present, and executed on the host GPU and WARP. +// +// Covers RDNA2 hardware semantics that differ from naive DXIL lowering: v_med3_f32/v_med3_f16 +// with NaN operands, v_fract_f32/v_fract_f16 near 1.0, turn-range reduction for v_sin_*/v_cos_*, +// and the LDS float atomics ds_min_f32/ds_max_f32. +// +// A Rust assert! inside a check is a non-fatal CHECK here (the test goes on); a Rust panic!/expect +// outside one throws, and main counts the test as failed. `#[ignore]` tests run only with +// --ignored. Each test names its lowered modules for VS_DUMP after the Rust test thread +// (emit::valu_tests::<name>, `::` as `__`). + +#ifndef NOMINMAX +#define NOMINMAX // windows.h (through d3d12.h) would make std::max a macro +#endif + +#include <algorithm> +#include <array> +#include <bit> +#include <cfloat> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <exception> +#include <format> +#include <functional> +#include <limits> +#include <mutex> +#include <optional> +#include <initializer_list> +#include <numbers> +#include <span> +#include <stdexcept> +#include <string> +#include <string_view> +#include <tuple> +#include <utility> +#include <vector> + +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include "x2w_shader/emit/emit.h" // HostShader +#include "x2w_shader/emit/host.h" +#include "x2w_shader/emit/lower.h" +#include "x2w_shader/emit/settings.h" // rdna::ALL +#include "x2w_shader/emit/validator.h" +#include "x2w_shader/io.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/native.h" +#include "x2w_shader/resource.h" +#include "x2w_shader/structure.h" +#include "test_util.h" + +namespace vs = x2w::vs; +using vs::HostShader; +using vs::native::ComputeIo; +using vs::native::HwStage; +using vs::native::NativeProgram; +using vs::native::ResourceType; +using vs::native::RootParam; +using vs::native::RootType; +using vs::native::StageIo; +using vs::native::UsedResource; + +namespace { + +using u8 = std::uint8_t; +using u16 = std::uint16_t; +using u32 = std::uint32_t; +using u64 = std::uint64_t; +using i32 = std::int32_t; +using i64 = std::int64_t; +using Words = std::vector<u32>; +using In = std::array<u32, 4>; + +// A failed Rust assert!/assert_eq! in a check: reported, counted, the test goes on. +void ensure(bool ok, const std::string& what, const char* file, int line) { + if (!ok) { + std::fprintf(stderr, "%s:%d: %s\n", file, line, what.c_str()); + ++test_util::failures(); + } +} +#define ENSURE(ok, ...) ensure(static_cast<bool>(ok), std::format(__VA_ARGS__), __FILE__, __LINE__) + +u32 f2b(float x) { return std::bit_cast<u32>(x); } +float b2f(u32 b) { return std::bit_cast<float>(b); } +u64 d2b(double x) { return std::bit_cast<u64>(x); } +double b2d(u64 b) { return std::bit_cast<double>(b); } + +// Rust {:08x?} of a slice of words. +std::string hex_words(std::span<const u32> w) { + std::string s = "["; + for (std::size_t i = 0; i < w.size(); ++i) s += std::format("{}{:08x}", i ? ", " : "", w[i]); + return s + "]"; +} +// Rust {:x?} of an input set. +std::string hex_in(const In& w) { + return std::format("[{:x}, {:x}, {:x}, {:x}]", w[0], w[1], w[2], w[3]); +} + +void append(Words& to, std::span<const u32> w) { to.insert(to.end(), w.begin(), w.end()); } + +constexpr u32 S_ENDPGM = 0xBF81'0000; + +// SOP1 s_mov_b32 sdst, src0. +constexpr u32 s_mov_b32(u8 sdst, u8 src0) { return 0xBE80'0000u | u32(sdst) << 16 | 0x03u << 8 | u32(src0); } + +// SOP2 op sdst, src0, src1. +constexpr u32 sop2(u8 op, u8 sdst, u8 src0, u8 src1) { + return 0x8000'0000u | (u32(op) & 0x7F) << 23 | (u32(sdst) & 0x7F) << 16 | u32(src1) << 8 | u32(src0); +} + +// SMEM s_load_dwordx4 s[dst:dst+3], s[base:base+1], 0 (soffset = null). +constexpr std::array<u32, 2> s_load_dwordx4(u8 dst, u8 base) { + return {0x3Du << 26 | 0x02u << 18 | u32(dst) << 6 | (u32(base) >> 1), 125u << 25}; +} + +// VOP1 op vdst, src0 (src0: 0..105 = SGPR, 256..511 = VGPR). +constexpr u32 vop1(u16 op, u8 vdst, u16 src0) { + return 0x7E00'0000u | u32(vdst) << 17 | u32(op) << 9 | (u32(src0) & 0x1FF); +} + +// VOP3 op vdst, src0, src1, src2 with explicit abs, neg, omod, clamp. +constexpr std::array<u32, 2> vop3_mod(u16 op, u8 vdst, u16 src0, u16 src1, u16 src2, u8 abs, u8 neg, u8 omod, + bool clamp) { + return {0x35u << 26 | (u32(op) & 0x3FF) << 16 | u32(clamp) << 15 | (u32(abs) & 7) << 8 | u32(vdst), + (u32(neg) & 7) << 29 | (u32(omod) & 3) << 27 | (u32(src0) & 0x1FF) | (u32(src1) & 0x1FF) << 9 | + (u32(src2) & 0x1FF) << 18}; +} + +// VOP3 op vdst, src0, src1, src2 (no modifiers). +constexpr std::array<u32, 2> vop3(u16 op, u8 vdst, u16 src0, u16 src1, u16 src2) { + return vop3_mod(op, vdst, src0, src1, src2, 0, 0, 0, false); +} + +// MUBUF buffer_store_dword vdata, off, s[srsrc:srsrc+3], 0 offset:byte_off. +constexpr std::array<u32, 2> buffer_store_dword(u8 vdata, u8 srsrc, u16 byte_off) { + return {0x38u << 26 | 0x1Cu << 18 | (u32(byte_off) & 0xFFF), + 0x80u << 24 | ((u32(srsrc) >> 2) & 0x1F) << 16 | u32(vdata) << 8}; +} + +constexpr u16 sgpr(u8 n) { return u16(n); } +constexpr u16 vgpr(u8 n) { return u16(256 + n); } + +std::vector<u8> le_bytes(std::span<const u32> words) { + std::vector<u8> code; + code.reserve(words.size() * 4); + for (u32 w : words) + for (int k = 0; k < 4; ++k) code.push_back(u8(w >> (8 * k))); + return code; +} + +// The layout and resources of the synthetic compute programs: 4 root constants in s0..s3, a table +// in s4 holding one raw UAV. +NativeProgram synthetic_cs(std::vector<u8> code, std::uint16_t vgprs, u32 rsrc2, std::array<u32, 3> threads) { + NativeProgram native; + native.stage = HwStage::Cs; + native.wave64 = false; + native.vgprs = vgprs; + RootParam constants; + constants.root = RootType::Constants(); + constants.table_offset_dwords = 0; + constants.sgprs = 4; + constants.base_register = 0; + constants.user_data = 0; + constants.slot = 0; + RootParam table; + table.root = RootType::Table(); + table.table_offset_dwords = 0; + table.sgprs = 1; + table.base_register = 0; + table.user_data = 4; + table.slot = 1; + native.layout = {constants, table}; + UsedResource uav; + uav.kind = ResourceType::Uav(); + uav.root = RootType::Table(); + uav.table_offset_dwords = 0; + uav.lower_bound = 0; + uav.stride = 0; + uav.dwords = 4; + uav.user_data = 4; + uav.slot = 1; + native.used = {uav}; + ComputeIo cs; + cs.rsrc2 = rsrc2; + cs.threads = threads; + native.io = StageIo{cs}; + native.code = std::move(code); + return native; +} + +// The front end and lower over `native`, as a HostShader; `indexed_views`: Rust takes +// res.root_indexed_views (build_cs) or none (whole_wave_f64_sum_and_cvt_f32_f64). +HostShader lower_cs(const NativeProgram& native, bool indexed_views) { + vs::ir::Program p = vs::ir::build(native.code, native.wave64, native.vgprs); // expect("ir::build") + vs::structure::Structured st = vs::structure::structure(p); // expect("structure") + vs::resource::Resources res = vs::resource::track(p, native.layout, native.stage, &st); + vs::io::Io io = vs::io::raise(p, native); + vs::lower::Parts parts; + parts.native = &native; + parts.p = &p; + parts.st = &st; + parts.io = &io; + parts.res = &res; + parts.mesh_stride = 0; + vs::lower::Lowered lowered = vs::lower::lower(parts); // expect("lower") + + HostShader shader; + shader.stage = HwStage::Cs; + shader.dxil = std::move(lowered.dxil); + shader.user_data = std::move(lowered.user_data); + shader.samplers = std::move(lowered.samplers); + shader.static_samplers = {}; + shader.root_cbvs = std::move(lowered.root_cbvs); + shader.root_srvs = std::move(lowered.root_srvs); + shader.root_uavs = std::move(lowered.root_uavs); + if (indexed_views) shader.root_indexed_views = res.root_indexed_views; + return shader; +} + +// Validator::load returns std::optional (Rust `if let Ok(mut v) = ...`), validate returns +// the error text or nothing. +void validate(const HostShader& shader, bool check_hash) { + auto v = vs::validator::Validator::load(vs::validator::Validator::default_path()); + if (!v) return; + std::vector<u8> copy = shader.dxil; + std::vector<u8> ours(copy.begin() + 4, copy.begin() + 20); + if (auto e = v->validate(copy)) throw std::runtime_error("DXIL validation failed: " + *e); + if (check_hash) ENSURE(std::equal(ours.begin(), ours.end(), copy.begin() + 4), "container hash mismatch"); +} + +// build_valu_cs with `threads` threads in x (thread index in v0 on entry, before `body`) and +// `lds_bytes` of LDS (a multiple of 512). +HostShader build_cs(std::span<const u32> body, u32 threads, u32 lds_bytes) { + Words words; + // s[4:5] = descriptor table address (heap index 0 -> byte offset 0). + words.push_back(s_mov_b32(5, 0x80)); // inline constant 0 + append(words, s_load_dwordx4(8, 4)); + // Copy root constants s0..s3 into v1..v4 so VALU instructions operate on VGPRs just as they + // do in real shaders. + for (u8 i = 0; i < 4; ++i) words.push_back(vop1(0x001, u8(i + 1), sgpr(i))); // v_mov_b32 + append(words, body); + append(words, buffer_store_dword(0, 8, 0)); + words.push_back(S_ENDPGM); + + NativeProgram native = + synthetic_cs(le_bytes(words), 8, (5u << 1) | ((lds_bytes / 512) << 15), {threads, 1, 1}); // 5 user SGPRs: s0..s4 + HostShader shader = lower_cs(native, true); + validate(shader, true); + return shader; +} + +// Builds and lowers a 1-thread synthetic RDNA2 compute shader that receives 4 dwords of root +// constants in s0..s3, runs `body` (leaving its result in v0), and stores v0 to dword 0 of the raw +// UAV at heap index 0. +HostShader build_valu_cs(std::span<const u32> body) { return build_cs(body, 1, 0); } +HostShader build_valu_cs(std::initializer_list<u32> body) { return build_cs(std::span(body.begin(), body.size()), 1, 0); } + +// One GPU test at a time (Rust's ONE_AT_A_TIME: dispatches from several test threads at once on +// the hardware adapter and WARP now and then never complete, and two at once on WARP can end the +// process). Each C++ test binary runs its tests one after another; this only guards this binary. +std::mutex ONE_AT_A_TIME; + +using Check = std::function<void(const char*, std::size_t, In, u32)>; +using Devices = std::vector<std::pair<const char*, bool>>; + +// The user-data dwords for `inputs`, as Rust's run_cases_on and whole_wave_f64_sum_and_cvt_f32_f64 +// fill them. +std::vector<u32> user_data_for(const HostShader& shader, const In& inputs) { + std::vector<u32> ud(std::max<u32>(shader.user_data_dwords(), 1), 0); + for (const auto& u : shader.user_data) { + if (u.root == RootType::Constants() && u.slot == 0) + ud[u.index] = inputs[u.dword]; + else if (u.root == RootType::Table() && u.slot == 1) + ud[u.index] = 0; + else + throw std::runtime_error(std::format("unexpected user data (root kind {}, slot {})", int(u.root.kind), u.slot)); + } + return ud; +} + +// one dispatch of `shader` with root constants `ud` and one raw UAV dword; the UAV's dword 0. +u32 dispatch_one(const vs::host::Host& host, ID3D12RootSignature* root, ID3D12PipelineState* pso, std::vector<u32> ud, + const char* label) { + std::array<vs::host::View, 1> views{vs::host::View::raw_uav(1)}; + vs::host::Dispatch d; + d.roots.emplace_back(0u, vs::host::Root::constants(std::move(ud))); + d.views = views; + d.samplers = {}; + d.groups = {1, 1, 1}; + std::vector<std::vector<u32>> out; + try { + out = host.dispatch(root, pso, d); + } catch (const std::exception& e) { + throw std::runtime_error(std::format("{}: dispatch failed: {}", label, e.what())); + } + return out[0][0]; +} + +void run_cases_on(const HostShader& shader, std::span<const In> cases, const Devices& devices, const Check& check) { + std::lock_guard one(ONE_AT_A_TIME); + int ran = 0; + for (const auto& [label, warp] : devices) { + std::optional<vs::host::Host> host; + try { + host.emplace(warp); + } catch (const std::exception& e) { + std::fprintf(stderr, "no SM 6.6 %s device (%s); skipped\n", label, e.what()); + continue; + } + Microsoft::WRL::ComPtr<ID3D12RootSignature> root; + Microsoft::WRL::ComPtr<ID3D12PipelineState> pso; + try { + auto [r, p] = host->compute_pipeline(shader); + root = r; + pso = p; + } catch (const std::exception& e) { + throw std::runtime_error(std::format("{}: compute_pipeline failed: {}", label, e.what())); + } + for (std::size_t i = 0; i < cases.size(); ++i) { + In inputs = cases[i]; + u32 got = dispatch_one(*host, root.Get(), pso.Get(), user_data_for(shader, inputs), label); + check(label, i, inputs, got); + } + ++ran; + } + bool all_hardware = std::all_of(devices.begin(), devices.end(), [](const auto& d) { return !d.second; }); + if (ran == 0 && all_hardware) { + // A case for the hardware adapter alone, on a machine without one. + std::fprintf(stderr, "no SM 6.6 hardware device; a hardware-only case not run\n"); + return; + } + if (ran == 0) throw std::runtime_error("no SM 6.6 device available"); +} + +const Devices HARDWARE_AND_WARP{{"hardware", false}, {"warp", true}}; +const Devices HARDWARE_ONLY{{"hardware", false}}; + +// Runs `shader` on every available SM 6.6 host (hardware GPU and WARP) for each 4-dword input set +// and invokes check(backend, case_index, inputs, result_dword). +void run_cases(const HostShader& shader, std::span<const In> cases, const Check& check) { + run_cases_on(shader, cases, HARDWARE_AND_WARP, check); +} +void run_cases(const HostShader& shader, std::initializer_list<In> cases, const Check& check) { + run_cases_on(shader, std::span(cases.begin(), cases.size()), HARDWARE_AND_WARP, check); +} + +bool is_f16_nan(u16 bits) { return (bits & 0x7FFF) > 0x7C00; } + +float f16_to_f32(u16 bits) { + u32 sign = u32(bits >> 15) << 31; + u32 exp = (bits >> 10) & 0x1F; + u32 mant = bits & 0x3FF; + u32 f32_bits; + if (exp == 0) { + if (mant == 0) { + f32_bits = sign; + } else { + u32 m = mant; + u32 e = 127 - 14; + while ((m & 0x400) == 0) { + m <<= 1; + e -= 1; + } + f32_bits = sign | (e << 23) | ((m & 0x3FF) << 13); + } + } else if (exp == 0x1F) { + f32_bits = sign | (0xFFu << 23) | (mant << 13); + } else { + f32_bits = sign | ((exp + 112) << 23) | (mant << 13); + } + return b2f(f32_bits); +} + +// MTBUF op vdata, off, s[srsrc:srsrc+3], 0 format:format (at byte 0). +constexpr std::array<u32, 2> mtbuf(u8 op, u8 vdata, u8 srsrc, u8 format) { + return {0x3Au << 26 | (u32(format) & 0x7F) << 19 | (u32(op) & 7) << 16, + 0x80u << 24 | (u32(op) >> 3 & 1) << 21 | (u32(srsrc) >> 2 & 0x1F) << 16 | u32(vdata) << 8}; +} + +// Stores v1 to the buffer, then reads it back into v0 with the tbuffer load `op` in buffer format +// `format`. +HostShader tbuffer_load_of_v1(u8 op, u8 format) { + Words body; + append(body, buffer_store_dword(1, 8, 0)); + append(body, mtbuf(op, 0, 8, format)); + return build_valu_cs(body); +} + +// ---- rs:265 ------------------------------------------------------------------------------------- +void scalar_quad_masks_pack_nibbles_and_set_scc() { + auto pack_words = [](u32 opcode) { + return std::array<u32, 5>{ + 0xBE90'0000u | opcode << 8, // s_quadmask s16, s0 (pairs for b64) + sop2(0x0a, 18, 129, 128), // s_cselect_b32 s18, 1, 0 + sop2(0x1e, 18, 18, 144), // s_lshl_b32 s18, s18, 16 + sop2(0x10, 16, 16, 18), // s_or_b32 s16, s16, s18 + vop1(1, 0, sgpr(16)), // v_mov_b32 v0, s16 + }; + }; + const std::array<std::pair<In, std::array<u32, 2>>, 4> cases{{ + {{0, 0, 0, 0}, {0, 0}}, + {{0x8000'0420, 0x0100'0001, 0, 0}, {0x1'0086, 0x1'4186}}, + {{0, 0x8000'0000, 0, 0}, {0, 0x1'8000}}, + {{UINT32_MAX, UINT32_MAX, 0, 0}, {0x1'00ff, 0x1'ffff}}, + }}; + std::array<In, 4> inputs; + for (std::size_t k = 0; k < 4; ++k) inputs[k] = cases[k].first; + const std::array<u32, 2> opcodes{0x2c, 0x2d}; + for (std::size_t wide = 0; wide < opcodes.size(); ++wide) { + u32 opcode = opcodes[wide]; + HostShader shader = build_valu_cs(pack_words(opcode)); + run_cases(shader, inputs, [&](const char* backend, std::size_t i, In, u32 got) { + ENSURE(got == cases[i].second[wide], "{}, opcode {:#x}: {} != {}", backend, opcode, got, cases[i].second[wide]); + }); + } + HostShader high = build_valu_cs({ + 0xBE90'2D00u, // s_quadmask_b64 s[16:17], s[0:1] + vop1(1, 0, sgpr(17)), + }); + run_cases(high, inputs, [&](const char* backend, std::size_t, In, u32 got) { + ENSURE(got == 0, "{}: high dword: {}", backend, got); + }); +} + +// ---- rs:302 ------------------------------------------------------------------------------------- +void a_branch_to_fallthrough_keeps_both_values_at_a_join() { + HostShader shader = build_valu_cs({ + 0xBF06'0100u, // s_cmp_eq_u32 s0, s1 + 0xBF85'0002u, // s_cbranch_scc1 -> the s2 = 1 path + s_mov_b32(2, 128), // s2 = 0 + 0xBF82'0002u, // s_branch -> the join + s_mov_b32(2, 129), // s2 = 1 + 0xBF85'0000u, // s_cbranch_scc1 -> the following instruction + vop1(0x001, 0, sgpr(2)), // join: v0 = s2 + }); + run_cases(shader, {In{7, 7, 0, 0}, In{7, 5, 0, 0}}, [&](const char* backend, std::size_t, In inputs, u32 actual) { + u32 want = u32(inputs[0] == inputs[1]); + ENSURE(actual == want, "{}: {} != {}", backend, actual, want); + }); +} + +// ---- rs:365 ------------------------------------------------------------------------------------- +void tbuffer_d16_loads_pack_two_channels_per_dword() { + // tbuffer_load_format_d16_x and tbuffer_load_format_d16_xy. + const u8 x = 8, xy = 9; + // (opcode, format, dword stored, dword loaded) + const std::array<std::tuple<u8, u8, u32, u32>, 4> cases{{ + // 16_16_FLOAT: the f16 pair (1.0, 2.0) as it was stored. + {xy, 29, 0x4000'3C00, 0x4000'3C00}, + // 16_16_UINT: the 16-bit integers as they were stored. + {xy, 27, 0xBEEF'1234, 0xBEEF'1234}, + // 16_16_UNORM: 0.0 and 1.0, as f16. + {xy, 23, 0xFFFF'0000, 0x3C00'0000}, + // 16_FLOAT, one channel: the high half is 0. + {x, 13, 0x4000'3C00, 0x0000'3C00}, + }}; + for (const auto& [op, format, stored, want] : cases) { + HostShader shader = tbuffer_load_of_v1(op, format); + run_cases(shader, {In{stored, 0, 0, 0}}, [&](const char* backend, std::size_t, In, u32 got) { + ENSURE(got == want, "{}: d16 opcode {} format {} of {:#010x} = {:#010x}, want {:#010x}", backend, op, format, + stored, got, want); + }); + } +} + +// ---- rs:391 ------------------------------------------------------------------------------------- +void normalized_buffer_formats_load_their_ends_exactly() { + // tbuffer_load_format_x. + const u8 x = 0; + // (format, dword stored, value loaded) + const std::array<std::tuple<u8, u32, float>, 8> cases{{ + {1, 0xFF, 1.0f}, // 8_UNORM + {7, 0xFFFF, 1.0f}, // 16_UNORM + {2, 0x7F, 1.0f}, // 8_SNORM: the top, the one above the lowest, the lowest + {2, 0x81, -1.0f}, + {2, 0x80, -1.0f}, + {8, 0x7FFF, 1.0f}, // 16_SNORM + {8, 0x8001, -1.0f}, + {8, 0x8000, -1.0f}, + }}; + for (const auto& [format, stored, want] : cases) { + HostShader shader = tbuffer_load_of_v1(x, format); + run_cases(shader, {In{stored, 0, 0, 0}}, [&](const char* backend, std::size_t, In, u32 got) { + ENSURE(got == f2b(want), "{}: format {} of {:#x} = {:#010x}, want {}", backend, format, stored, got, want); + }); + } +} + +// Codes of the normalized formats sampled below: every 8-bit code; for 16 bits a stride, the +// RX 6700 XT's division misses (257, 261, ...) and the ends. +std::vector<u32> normalized_codes(u32 bits) { + std::vector<u32> out; + if (bits <= 10) { + for (u32 a = 0; a < (1u << bits); ++a) out.push_back(a); + return out; + } + const u32 edges[] = {1, 2, 3, 255, 256, 257, 261, 265, 269, 511, 512, 1000, 0x7FFF, 0x8000, 0x8001, 0xFFFE}; + for (u32 a = 0; a <= 0xFFFF; a += 257) out.push_back(a); + for (u32 e : edges) out.push_back(e); + return out; +} + +std::vector<In> first_inputs(const std::vector<u32>& codes) { + std::vector<In> cases; + for (u32 a : codes) cases.push_back(In{a, 0, 0, 0}); + return cases; +} + +// ---- rs:434 ------------------------------------------------------------------------------------- +// Every normalized code loads as the float nearest its exact quotient, as the console's buffer unit +// converts it, not as the host divides (the RX 6700 XT gave 125 of the 8-bit codes one ulp high and +// 16-bit codes such as 257 one ulp low): unsigned and signed, 8, 10 (the x channel of 2_10_10_10) +// and 16 bits, the signed formats' two lowest codes -1.0. +void normalized_buffer_formats_load_correctly_rounded_quotients() { + const u8 x = 0; + // (format, bits, signed): 8_UNORM, 16_UNORM, 8_SNORM, 16_SNORM, 2_10_10_10_UNORM and _SNORM. + const std::array<std::tuple<u8, u32, bool>, 6> formats{{ + {1, 8, false}, {7, 16, false}, {2, 8, true}, {8, 16, true}, {50, 10, false}, {51, 10, true}}}; + for (const auto& [format, bits, is_signed] : formats) { + HostShader shader = tbuffer_load_of_v1(x, format); + std::vector<In> cases = first_inputs(normalized_codes(bits)); + run_cases(shader, cases, [&](const char* backend, std::size_t, In in, u32 got) { + u32 a = in[0]; + u32 want; + if (is_signed) { + i32 top = (i32(1) << (bits - 1)) - 1; + i32 s = i32(a << (32 - bits)) >> (32 - bits); + want = f2b(float(std::max(s, -top)) / float(top)); + } else { + want = f2b(float(a) / float((1u << bits) - 1)); + } + const char* sign = is_signed ? "signed" : "unsigned"; + ENSURE(got == want, "{}: {}-bit {} normalized {:#x} loads as {:#010x}, want {:#010x}", backend, bits, sign, a, + got, want); + }); + } +} + +// ---- rs:460 ------------------------------------------------------------------------------------- +// A title truncates x * (2^n - 1) back to the code it stored (the material index a mesh program +// reads from a vertex colour's alpha, as v_mul_legacy_f32 by 255.0 then v_cvt_u32_f32): every code +// comes back as itself, on hardware and WARP, which a quotient one ulp low breaks. +void normalized_codes_truncate_back_to_themselves() { + const u8 x = 0; + const std::array<std::pair<u8, u32>, 2> formats{{{1, 8}, {7, 16}}}; + for (const auto& [format, bits] : formats) { + u32 scale = f2b(float((1u << bits) - 1)); + Words body; + append(body, buffer_store_dword(1, 8, 0)); + append(body, mtbuf(x, 0, 8, format)); + // v_mul_legacy_f32 v0, literal, v0; v_cvt_u32_f32 v0, v0. + body.push_back(0x07u << 25 | 0xFF); + body.push_back(scale); + body.push_back(vop1(0x07, 0, vgpr(0))); + HostShader shader = build_valu_cs(body); + std::vector<In> cases = first_inputs(normalized_codes(bits)); + run_cases(shader, cases, [&](const char* backend, std::size_t, In in, u32 got) { + u32 a = in[0]; + ENSURE(got == a, "{}: {}-bit code {} comes back as {}", backend, bits, a, got); + }); + } +} + +// ---- rs:478 ------------------------------------------------------------------------------------- +void packed_add_selects_halves_of_inline_constants() { + // Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves. The same GFX10 + // source field (248) has a different bit pattern for a packed floating-point and a packed + // integer instruction. + const std::array<std::pair<std::array<u32, 2>, u32>, 3> cases{{ + // v_pk_add_f16 v0, 0x3118, v1 + {{0xcc0f4000, 0x1a0202f8}, 0x0000'3118}, + // v_pk_add_f16 v0, 0x3118, v1 op_sel_hi:[0,1] (use low twice) + {{0xcc0f4000, 0x120202f8}, 0x3118'3118}, + // v_pk_add_u16 v0, 0x3e22f983, v1 + {{0xcc0a4000, 0x1a0202f8}, 0x3e22'f983}, + }}; + for (const auto& [words, expected] : cases) { + HostShader shader = build_valu_cs(words); + run_cases(shader, {In{0, 0, 0, 0}}, [&](const char* backend, std::size_t, In, u32 got) { + ENSURE(got == expected, "{}: {}: {:#x} != {:#x}", backend, hex_words(words), got, expected); + }); + } +} + +// The float v_cvt_f32_f64 gives for x: Rust's rounding (to nearest even), with results below the +// smallest normal float flushed to signed zero as the console's default float mode does. +u32 cvt_f32_f64_reference(double x) { + float r = static_cast<float>(x); + bool subnormal = std::fpclassify(r) == FP_SUBNORMAL; + if (subnormal || (r == 0.0f && x != 0.0)) return f2b(r) & 0x8000'0000; + return f2b(r); +} + +std::vector<In> f64_inputs(std::span<const double> values) { + std::vector<In> inputs; + for (double x : values) { + u64 b = d2b(x); + inputs.push_back(In{u32(b), u32(b >> 32), 0, 0}); + } + return inputs; +} + +// ---- rs:511 ------------------------------------------------------------------------------------- +// #[ignore = "expects results below the smallest normal float flushed to zero; the IEEE lowering +// (v_cvt_f32_f64_matches_ieee754) is kept until the console's mode is checked"] +void v_cvt_f32_f64_rounds_to_nearest_even() { + // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x0f) + HostShader shader = build_valu_cs({vop1(0x00f, 0, vgpr(1))}); + double tie_even = 1.0 + double(FLT_EPSILON) / 2.0; // ties to 1.0 + double tie_odd = 1.0 + 1.5 * double(FLT_EPSILON); // ties up to 1 + 2 ulp + const std::vector<double> values{ + 0.0, + -0.0, + 1.0, + -2.5, + std::numbers::pi, + 1.0e-3, + 123'456'789.123, + tie_even, + tie_odd, + 1.0 + double(FLT_EPSILON) * 0.75, + double(FLT_MAX), + double(FLT_MAX) * 1.000'000'1, // rounds to infinity + 1.0e300, + -1.0e300, + 1.0e-40, // a float denormal: flushed + -1.0e-300, + double(FLT_MIN), + std::numeric_limits<double>::infinity(), + -std::numeric_limits<double>::infinity(), + std::numeric_limits<double>::quiet_NaN(), + }; + std::vector<In> inputs = f64_inputs(values); + run_cases(shader, inputs, [&](const char* backend, std::size_t i, In, u32 got) { + double x = values[i]; + if (std::isnan(x)) { + ENSURE(std::isnan(b2f(got)), "{}: cvt({}) = {:#010x}, want NaN", backend, x, got); + return; + } + u32 want = cvt_f32_f64_reference(x); + ENSURE(got == want, "{}: cvt({:e}) = {:#010x}, want {:#010x}", backend, x, got, want); + }); +} + +// The lane v_permlane16_b32 (cross false) or v_permlanex16_b32 reads for `lane`, with selector +// dwords s1 (lanes 0-7 of a row) and s2. +u32 permlane_source(u32 lane, u32 s1, u32 s2, bool cross) { + u64 sel = u64(s1) | u64(s2) << 32; + u32 pick = u32(sel >> (4 * (lane & 15)) & 15); + u32 row = cross ? ((lane & ~31u) | ((lane & 16) ^ 16)) : (lane & ~15u); + return row | pick; +} + +// ---- rs:571 ------------------------------------------------------------------------------------- +void v_permlane16_and_x16_read_the_lanes_their_selectors_pick() { + // 32 lanes, each with its lane number in v0; v1 = permute(v0, s0, s1); lane `read` of v1 into + // s12, then into v0 for the store. + const std::array<std::pair<u32, u32>, 3> selectors{{ + {0x7654'3210, 0xfedc'ba98}, // identity within the row + {0x89ab'cdef, 0x0123'4567}, // reversed + {0x1111'1111, 0xf0f0'f0f0}, // repeats + }}; + const std::array<std::pair<u16, bool>, 2> ops{{{0x377, false}, {0x378, true}}}; + for (const auto& [op, cross] : ops) { + for (u8 read : {u8(0), u8(5), u8(15), u8(16), u8(22), u8(31)}) { + Words body; + append(body, vop3(op, 1, vgpr(0), sgpr(0), sgpr(1))); + // v_readlane_b32 s12, v1, read (inline constant 128 + read) + append(body, vop3(0x360, 12, vgpr(1), u16(128 + u16(read)), 0)); + body.push_back(vop1(0x001, 0, sgpr(12))); // v_mov_b32 v0, s12 + HostShader shader = build_cs(body, 32, 0); + std::vector<In> inputs; + for (const auto& [a, b] : selectors) inputs.push_back(In{a, b, 0, 0}); + // Cross-lane code declares WaveSize(32), which WARP's pipeline creation refuses: + // hardware only. + run_cases_on(shader, inputs, HARDWARE_ONLY, [&](const char* backend, std::size_t i, In inp, u32 got) { + u32 want = permlane_source(u32(read), inp[0], inp[1], cross); + ENSURE(got == want, "{}: op {:#x} selectors [{:08x}, {:08x}], lane {}: {:#x} != {:#x}", backend, op, + selectors[i].first, selectors[i].second, read, got, want); + }); + } + } +} + +// ---- rs:603 ------------------------------------------------------------------------------------- +void v_med3_f32_matches_rdna2_with_nan() { + // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157) + HostShader shader = build_valu_cs(vop3(0x157, 0, vgpr(1), vgpr(2), vgpr(3))); + const u32 nan = f2b(std::numeric_limits<float>::quiet_NaN()); + auto f = f2b; + + const std::vector<std::pair<In, std::optional<float>>> cases{ + // Normal medians (all orderings). + {{f(1.0f), f(2.0f), f(3.0f), 0}, 2.0f}, + {{f(3.0f), f(1.0f), f(2.0f), 0}, 2.0f}, + {{f(-5.0f), f(0.0f), f(5.0f), 0}, 0.0f}, + {{f(1.0f), f(1.0f), f(2.0f), 0}, 1.0f}, + // One NaN: RDNA2 returns min3 of the non-NaN operands. + {{f(1.0f), f(2.0f), nan, 0}, 1.0f}, + {{nan, f(1.0f), f(0.0f), 0}, 0.0f}, + {{nan, f(0.0f), f(1.0f), 0}, 0.0f}, + {{f(2.0f), nan, f(1.0f), 0}, 1.0f}, + {{f(-3.0f), nan, f(4.0f), 0}, -3.0f}, + // Two NaNs: returns the sole non-NaN operand. + {{nan, f(5.0f), nan, 0}, 5.0f}, + {{nan, nan, f(-2.0f), 0}, -2.0f}, + {{f(7.0f), nan, nan, 0}, 7.0f}, + // Three NaNs: returns NaN. + {{nan, nan, nan, 0}, std::nullopt}, + }; + + std::vector<In> inputs; + for (const auto& c : cases) inputs.push_back(c.first); + run_cases(shader, inputs, [&](const char* backend, std::size_t i, In inp, u32 got) { + std::optional<float> expect = cases[i].second; + float got_f = b2f(got); + if (expect) { + float want = *expect; + ENSURE(got_f == want, "{}: v_med3_f32({}, {}, {}) = {} ({:#010x}), want {}", backend, b2f(inp[0]), + b2f(inp[1]), b2f(inp[2]), got_f, got, want); + } else { + ENSURE(std::isnan(got_f), "{}: v_med3_f32(NaN, NaN, NaN) = {} ({:#010x}), want NaN", backend, got_f, got); + } + }); +} + +// ---- rs:651 ------------------------------------------------------------------------------------- +// RDNA2 orders -0 below +0 in its maximums and minimums; DXIL's FMax and FMin compare and select, +// which can give either zero. +void max_and_min_order_negative_zero_below_positive_zero() { + const u32 pz = 0, nz = 0x8000'0000; + // Each case has a -0 and a +0 among its first two operands. + const std::array<In, 4> cases{{ + {nz, pz, nz, 0}, + {pz, nz, nz, 0}, + {nz, pz, pz, 0}, + {pz, nz, pz, 0}, + }}; + const std::array<std::tuple<const char*, u16, u32>, 4> ops{{ + {"v_max_f32", 0x110, pz}, + {"v_min_f32", 0x10F, nz}, + {"v_max3_f32", 0x154, pz}, + {"v_min3_f32", 0x151, nz}, + }}; + for (const auto& [name, op, want] : ops) { + HostShader shader = build_valu_cs(vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(shader, cases, [&](const char* backend, std::size_t, In inp, u32 got) { + ENSURE(got == want, "{}: {} {}: {:#x} != {:#x}", backend, name, hex_in(inp), got, want); + }); + } +} + +// ---- rs:677 ------------------------------------------------------------------------------------- +// The f16 forms go through the same max_min helper, after widening to f32. +void f16_max_and_min_order_negative_zero_below_positive_zero() { + const u32 pz = 0, nz = 0x8000; + const std::array<In, 4> cases{{ + {nz, pz, nz, 0}, + {pz, nz, nz, 0}, + {nz, pz, pz, 0}, + {pz, nz, pz, 0}, + }}; + const std::array<std::tuple<const char*, u16, u32>, 4> ops{{ + {"v_max_f16", 0x139, pz}, + {"v_min_f16", 0x13A, nz}, + {"v_max3_f16", 0x354, pz}, + {"v_min3_f16", 0x351, nz}, + }}; + for (const auto& [name, op, want] : ops) { + HostShader shader = build_valu_cs(vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(shader, cases, [&](const char* backend, std::size_t, In inp, u32 got) { + // The f16 result is the low half of v0. + ENSURE((got & 0xFFFF) == want, "{}: {} {}: {:#x} != {:#x}", backend, name, hex_in(inp), got & 0xFFFF, want); + }); + } +} + +// ---- rs:702 ------------------------------------------------------------------------------------- +void v_min3_max3_med3_integer_forms_match_rdna2() { + // v_{min3,max3,med3}_{i32,u32} v0, v1, v2, v3 (VOP3 0x152..0x159). + using Pick = u32 (*)(std::array<u32, 3>); + const std::array<std::tuple<const char*, u16, Pick>, 6> ops{{ + {"v_min3_i32", 0x152, + [](std::array<u32, 3> t) { + return *std::min_element(t.begin(), t.end(), [](u32 a, u32 b) { return i32(a) < i32(b); }); + }}, + {"v_min3_u32", 0x153, [](std::array<u32, 3> t) { return *std::min_element(t.begin(), t.end()); }}, + // Rust max_by_key takes the last of equal maxima; equal keys are equal values here. + {"v_max3_i32", 0x155, + [](std::array<u32, 3> t) { + return *std::max_element(t.begin(), t.end(), [](u32 a, u32 b) { return i32(a) < i32(b); }); + }}, + {"v_max3_u32", 0x156, [](std::array<u32, 3> t) { return *std::max_element(t.begin(), t.end()); }}, + {"v_med3_i32", 0x158, + [](std::array<u32, 3> t) { + std::stable_sort(t.begin(), t.end(), [](u32 a, u32 b) { return i32(a) < i32(b); }); + return t[1]; + }}, + {"v_med3_u32", 0x159, + [](std::array<u32, 3> t) { + std::sort(t.begin(), t.end()); + return t[1]; + }}, + }}; + // Every ordering of three values, with the sign bit set on some so that the signed and unsigned + // answers differ. + const std::array<u32, 5> values{0u, 1, 0x7FFF'FFFF, 0x8000'0000, 0xFFFF'FFFF}; + std::vector<In> cases; + for (u32 a : values) + for (u32 b : values) + for (u32 c : values) cases.push_back(In{a, b, c, 0}); + for (const auto& [name, op, pick] : ops) { + HostShader shader = build_valu_cs(vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(shader, cases, [&](const char* backend, std::size_t, In inp, u32 got) { + u32 want = pick({inp[0], inp[1], inp[2]}); + ENSURE(got == want, "{}: {}({:#010x}, {:#010x}, {:#010x}) = {:#010x}, want {:#010x}", backend, name, inp[0], + inp[1], inp[2], got, want); + }); + } +} + +// ---- rs:748 ------------------------------------------------------------------------------------- +void v_med3_f16_matches_rdna2_with_nan() { + // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357) + HostShader shader = build_valu_cs(vop3(0x357, 0, vgpr(1), vgpr(2), vgpr(3))); + const u32 h0 = 0x0000; // 0.0 + const u32 h1 = 0x3C00; // 1.0 + const u32 h2 = 0x4000; // 2.0 + const u32 h3 = 0x4200; // 3.0 + const u32 h5 = 0x4500; // 5.0 + const u32 hn2 = 0xC000; // -2.0 + const u32 nan = 0x7E00; + + const std::vector<std::pair<In, std::optional<u16>>> cases{ + {{h1, h2, h3, 0}, u16(h2)}, + {{hn2, h0, h3, 0}, u16(h0)}, + {{h1, h2, nan, 0}, u16(h1)}, + {{nan, h1, h0, 0}, u16(h0)}, + {{nan, h0, h1, 0}, u16(h0)}, + {{h2, nan, h1, 0}, u16(h1)}, + {{nan, h5, nan, 0}, u16(h5)}, + {{nan, nan, nan, 0}, std::nullopt}, + }; + + std::vector<In> inputs; + for (const auto& c : cases) inputs.push_back(c.first); + run_cases(shader, inputs, [&](const char* backend, std::size_t i, In inp, u32 got) { + std::optional<u16> expect = cases[i].second; + u16 got_h = u16(got); + if (expect) { + u16 want = *expect; + ENSURE(got_h == want, "{}: v_med3_f16({:#06x}, {:#06x}, {:#06x}) = {:#06x}, want {:#06x}", backend, inp[0], + inp[1], inp[2], got_h, want); + } else { + ENSURE(is_f16_nan(got_h), "{}: v_med3_f16(NaN, NaN, NaN) = {:#06x}, want NaN", backend, got_h); + } + }); +} + +// ---- rs:789 ------------------------------------------------------------------------------------- +// v_cmp_lg_* is "less or greater": ordered and not equal, so false when either operand is a NaN +// (RDNA2 ISA; the same on gfx1036 hardware). +void v_cmp_lg_is_false_for_nan() { + // v_cmp_lg_{f32,f16}_e64 s20, v1, v2 (VOPC 0x005 / 0x0cd in VOP3); + // v_cndmask_b32_e64 v0, 0, 1, s20 (VOP3 0x101) + const u32 nan = f2b(std::numeric_limits<float>::quiet_NaN()); + const u32 inf = f2b(std::numeric_limits<float>::infinity()); + const u32 ninf = f2b(-std::numeric_limits<float>::infinity()); + auto f = f2b; + using Cases = std::vector<std::pair<In, u32>>; + const Cases f32_cases{ + {{f(1.0f), f(2.0f), 0, 0}, 1}, + {{f(2.0f), f(1.0f), 0, 0}, 1}, + {{f(1.0f), f(1.0f), 0, 0}, 0}, + {{f(0.0f), f(-0.0f), 0, 0}, 0}, + {{inf, ninf, 0, 0}, 1}, + {{inf, inf, 0, 0}, 0}, + {{nan, f(1.0f), 0, 0}, 0}, + {{f(1.0f), nan, 0, 0}, 0}, + {{nan, nan, 0, 0}, 0}, + {{0x7F80'0001, f(0.0f), 0, 0}, 0}, // a signalling NaN + }; + const Cases f16_cases{ + {{0x3C00, 0x4000, 0, 0}, 1}, + {{0x4000, 0x3C00, 0, 0}, 1}, + {{0x3C00, 0x3C00, 0, 0}, 0}, + {{0x0000, 0x8000, 0, 0}, 0}, + {{0x7C00, 0xFC00, 0, 0}, 1}, + {{0x7E00, 0x3C00, 0, 0}, 0}, + {{0x3C00, 0x7E00, 0, 0}, 0}, + {{0x7E00, 0x7E00, 0, 0}, 0}, + {{0x7C01, 0x0000, 0, 0}, 0}, // a signalling NaN + {{0xABCD'3C00, 0x1234'7E00, 0, 0}, 0}, // only the low halves are read + }; + const std::array<std::tuple<u16, const char*, const Cases*>, 2> forms{{ + {0x005, "v_cmp_lg_f32", &f32_cases}, + {0x0cd, "v_cmp_lg_f16", &f16_cases}, + }}; + for (const auto& [op, what, cases_ptr] : forms) { + const Cases& cases = *cases_ptr; + Words body; + append(body, vop3(op, 20, vgpr(1), vgpr(2), 0x80)); + append(body, vop3(0x101, 0, 0x80, 0x81, sgpr(20))); + HostShader shader = build_valu_cs(body); + std::vector<In> inputs; + for (const auto& c : cases) inputs.push_back(c.first); + run_cases(shader, inputs, [&](const char* backend, std::size_t i, In inp, u32 got) { + u32 want = cases[i].second; + ENSURE(got == want, "{}: {}({:#010x}, {:#010x}) = {}, want {}", backend, what, inp[0], inp[1], got, want); + }); + } +} + +// ---- rs:841 ------------------------------------------------------------------------------------- +void v_cvt_off_f32_i4_uses_the_signed_low_nibble() { + // v_cvt_off_f32_i4 v0, v1 (VOP1 opcode 0x00e) + HostShader shader = build_valu_cs({vop1(0x00e, 0, vgpr(1))}); + // C++20: << of a signed value wraps as Rust's does; >> of a negative one is arithmetic. + auto nibble = [](u32 n) { return float((i32(n) << 28) >> 28) / 16.0f; }; + + std::vector<u32> cases; + for (u32 k = 0; k < 16; ++k) cases.push_back(k); + // Bits above the low nibble are ignored. + for (u32 k : {0xABCD'EF05u, 0xFFFF'FFF8u, 0x1234'5670u, 0x8000'000Fu, 0x0000'00F7u}) cases.push_back(k); + std::vector<In> inputs = first_inputs(cases); + run_cases(shader, inputs, [&](const char* backend, std::size_t i, In inp, u32 got) { + u32 want = f2b(nibble(cases[i])); + ENSURE(got == want, "{}: v_cvt_off_f32_i4({:#010x}) = {:#010x} ({}), want {:#010x}", backend, inp[0], got, b2f(got), + want); + }); + // Spot-check the reference itself: 0x5 -> 0.3125, 0x8 -> -0.5, 0xF -> -0.0625. + CHECK(nibble(0xABCD'EF05) == 0.3125f); + CHECK(nibble(8) == -0.5f); + CHECK(nibble(0xF) == -0.0625f); +} + +// ---- rs:866 ------------------------------------------------------------------------------------- +void v_fract_f32_never_returns_one() { + // v_fract_f32 v0, v1 (VOP1 opcode 0x020) + HostShader shader = build_valu_cs({vop1(0x020, 0, vgpr(1))}); + auto f = f2b; + const u32 below_one = 0x3F7F'FFFF; + + const std::vector<std::pair<u32, std::optional<u32>>> cases{ + // Tiny negatives: must clamp strictly below 1.0 (not 0x3f800000). + {f(-1e-10f), below_one}, + {f(-1e-8f), below_one}, + {f(-std::ldexp(1.0f, -25)), below_one}, + {f(-std::ldexp(1.0f, -24)), below_one}, + // Normal values. + {f(0.0f), f(0.0f)}, + {f(-0.0f), f(0.0f)}, + {f(0.25f), f(0.25f)}, + {f(3.75f), f(0.75f)}, + {f(-0.25f), f(0.75f)}, + {f(-3.25f), f(0.75f)}, + {f(1.0f), f(0.0f)}, + {f(-1.0f), f(0.0f)}, + // Non-finite inputs yield NaN. + {f(std::numeric_limits<float>::quiet_NaN()), std::nullopt}, + {f(std::numeric_limits<float>::infinity()), std::nullopt}, + {f(-std::numeric_limits<float>::infinity()), std::nullopt}, + }; + + std::vector<In> inputs; + for (const auto& [x, _] : cases) inputs.push_back(In{x, 0, 0, 0}); + run_cases(shader, inputs, [&](const char* backend, std::size_t i, In inp, u32 got) { + std::optional<u32> expect = cases[i].second; + if (expect) { + u32 want = *expect; + ENSURE(got == want, "{}: v_fract_f32({} / {:#010x}) = {:#010x} ({}), want {:#010x}", backend, b2f(inp[0]), + inp[0], got, b2f(got), want); + } else { + ENSURE(std::isnan(b2f(got)), "{}: v_fract_f32({}) = {:#010x}, want NaN", backend, b2f(inp[0]), got); + } + }); +} + +// ---- rs:915 ------------------------------------------------------------------------------------- +void v_fract_f16_never_returns_one() { + // v_fract_f16 v0, v1 (VOP1 opcode 0x05f) + HostShader shader = build_valu_cs({vop1(0x05f, 0, vgpr(1))}); + const u16 below_one = 0x3BFF; // 1.0 - 2^-11 + + CHECK(f16_to_f32(0x9400) == -std::ldexp(1.0f, -10)); + CHECK(f16_to_f32(0x9000) == -std::ldexp(1.0f, -11)); + CHECK(f16_to_f32(0x8C00) == -std::ldexp(1.0f, -12)); + + const std::vector<std::pair<u16, std::optional<u16>>> cases{ + // Negatives in (-2^-11, 0): must clamp to 0x3BFF, never 0x3C00 (1.0). + {0x8C00, below_one}, // -2^-12 + {0x8400, below_one}, // -2^-14 + {0x8001, below_one}, // -2^-24 (smallest negative f16 subnormal) + {0x9000, below_one}, // -2^-11 (exact 1 - 2^-11 = 0x3BFF) + {0x9400, u16(0x3BFE)}, // -2^-10 (exact 1 - 2^-10 = 0x3BFE) + // Normal values. + {0x0000, u16(0x0000)}, // 0.0 -> 0.0 + {0x3400, u16(0x3400)}, // 0.25 -> 0.25 + {0xB400, u16(0x3A00)}, // -0.25 -> 0.75 + {0x4300, u16(0x3800)}, // 3.5 -> 0.5 + {0x3C00, u16(0x0000)}, // 1.0 -> 0.0 + // Non-finite inputs yield NaN. + {0x7E00, std::nullopt}, // NaN + {0x7C00, std::nullopt}, // +inf + {0xFC00, std::nullopt}, // -inf + }; + + std::vector<In> inputs; + for (const auto& [x, _] : cases) inputs.push_back(In{u32(x), 0, 0, 0}); + run_cases(shader, inputs, [&](const char* backend, std::size_t i, In inp, u32 got) { + std::optional<u16> expect = cases[i].second; + u16 got_h = u16(got); + if (expect) { + u16 want = *expect; + ENSURE(got_h == want, "{}: v_fract_f16({:#06x}) = {:#06x}, want {:#06x}", backend, inp[0], got_h, want); + } else { + ENSURE(is_f16_nan(got_h), "{}: v_fract_f16({:#06x}) = {:#06x}, want NaN", backend, inp[0], got_h); + } + }); +} + +// RDNA2's flt16_to_snorm16 / flt16_to_unorm16: clamp, scale by 32767 or 65535, round the exact +// product to nearest even; NaN gives 0. +u16 cvt_norm16_reference(u16 bits, bool is_signed) { + float x = f16_to_f32(bits); + if (std::isnan(x)) return 0; + float lo = is_signed ? -1.0f : 0.0f; + double scale = is_signed ? 32767.0 : 65535.0; + // f64 holds the product of an f16 and a 16-bit scale exactly. + double p = double(std::clamp(x, lo, 1.0f)) * scale; + // round_ties_even: nearbyint in the default rounding mode (to nearest even); `as i32` of a value + // within [-32767, 65535], then `as u16` wraps. + return u16(i32(std::nearbyint(p))); +} + +// ---- rs:983 ------------------------------------------------------------------------------------- +void v_cvt_norm_i16_and_u16_f16_round_the_exact_product() { + // Every 251st f16 pattern, plus the values where an f32 product would round before the rounding + // to an integer, ties, and the edges. + std::vector<u16> bits; + for (u32 b = 0; b <= 0xFFFF; b += 251) bits.push_back(u16(b)); + for (u16 b : {0x0000, 0x8000, 0x0001, 0x8001, 0x03FF, 0x0400, 0x3800, 0xB800, 0x3801, 0xB801, 0x37FF, + 0x3BFF, 0xBBFF, 0x3C00, 0xBC00, 0x3C01, 0x7BFF, 0x7C00, 0xFC00, 0x7E00, 0xFE00, 0x7C01, + 0x3A9B, 0xBA9B, 0x2E66, 0x1400}) + bits.push_back(b); + const std::array<std::tuple<u16, bool, const char*>, 2> ops{{ + {0x063, true, "v_cvt_norm_i16_f16"}, + {0x064, false, "v_cvt_norm_u16_f16"}, + }}; + for (const auto& [op, is_signed, what] : ops) { + // v_cvt_norm_*16_f16 v0, v1 (VOP1); v0's high half starts at 0. + HostShader shader = build_valu_cs({vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))}); + std::vector<In> inputs; + for (u16 b : bits) inputs.push_back(In{u32(b), 0, 0, 0}); + run_cases(shader, inputs, [&](const char* backend, std::size_t i, In, u32 got) { + u16 want = cvt_norm16_reference(bits[i], is_signed); + ENSURE(got == u32(want), "{}: {}({:#06x}) = {:#010x}, want {:#06x}", backend, what, bits[i], got, want); + }); + } +} + +// The approximate checks of the sin/cos tests: within `tol` of the value or NaN. +void check_near(const char* backend, const char* what, std::optional<float> expect, In inp, float got_f, float tol, + const char* file, int line) { + if (expect) { + float want = *expect; + ensure(std::fabs(got_f - want) < tol, + std::format("{}: {}({}) = {}, want {} (err = {})", backend, what, b2f(inp[0]), got_f, want, + std::fabs(got_f - want)), + file, line); + } else { + ensure(std::isnan(got_f), std::format("{}: {}({}) = {}, want NaN", backend, what, b2f(inp[0]), got_f), file, line); + } +} + +// ---- rs:1012 ------------------------------------------------------------------------------------ +void v_sin_and_v_cos_f32_reduce_large_turns() { + HostShader sin_shader = build_valu_cs({vop1(0x035, 0, vgpr(1))}); + HostShader cos_shader = build_valu_cs({vop1(0x036, 0, vgpr(1))}); + auto f = f2b; + const float half_sqrt2 = 0.707106781186547524400844362104849039f; // Rust std::f32::consts::FRAC_1_SQRT_2 + const float NaN = std::numeric_limits<float>::quiet_NaN(); + const float INF = std::numeric_limits<float>::infinity(); + using Cases = std::vector<std::pair<float, std::optional<float>>>; + + const Cases sin_cases{ + {0.0f, 0.0f}, + {0.25f, 1.0f}, + {255.0f, 0.0f}, + {255.25f, 1.0f}, + {255.5f, 0.0f}, + {-255.25f, -1.0f}, + {10'000.125f, half_sqrt2}, + {NaN, std::nullopt}, + {INF, std::nullopt}, + {-INF, std::nullopt}, + }; + std::vector<In> sin_inputs; + for (const auto& [x, _] : sin_cases) sin_inputs.push_back(In{f(x), 0, 0, 0}); + run_cases(sin_shader, sin_inputs, [&](const char* backend, std::size_t i, In inp, u32 got) { + check_near(backend, "v_sin_f32", sin_cases[i].second, inp, b2f(got), 1e-5f, __FILE__, __LINE__); + }); + + const Cases cos_cases{ + {0.0f, 1.0f}, + {0.25f, 0.0f}, + {255.0f, 1.0f}, + {255.25f, 0.0f}, + {255.5f, -1.0f}, + {-255.5f, -1.0f}, + {10'000.125f, half_sqrt2}, + {NaN, std::nullopt}, + {INF, std::nullopt}, + {-INF, std::nullopt}, + }; + std::vector<In> cos_inputs; + for (const auto& [x, _] : cos_cases) cos_inputs.push_back(In{f(x), 0, 0, 0}); + run_cases(cos_shader, cos_inputs, [&](const char* backend, std::size_t i, In inp, u32 got) { + check_near(backend, "v_cos_f32", cos_cases[i].second, inp, b2f(got), 1e-5f, __FILE__, __LINE__); + }); + + // Main's trig_turns preserves sin(-0.0) = -0.0 and produces exact +0.0 at half-turns (sin) and + // quarter-turns (cos). + const std::vector<std::pair<u32, u32>> exact_sin{ + {0x8000'0000, 0x8000'0000}, // sin(-0.0) = -0.0 + {f(255.0f), 0}, // sin(255.0) = +0.0 + {f(255.5f), 0}, // sin(255.5) = +0.0 + }; + std::vector<In> exact_sin_in; + for (const auto& [x, _] : exact_sin) exact_sin_in.push_back(In{x, 0, 0, 0}); + run_cases(sin_shader, exact_sin_in, [&](const char* backend, std::size_t i, In inp, u32 got) { + u32 want = exact_sin[i].second; + ENSURE(got == want, "{}: v_sin_f32({:#010x}) = {:#010x}, want {:#010x}", backend, inp[0], got, want); + }); + const std::vector<std::pair<u32, u32>> exact_cos{ + {f(0.25f), 0}, // cos(0.25) = +0.0 + {f(255.25f), 0}, // cos(255.25) = +0.0 + }; + std::vector<In> exact_cos_in; + for (const auto& [x, _] : exact_cos) exact_cos_in.push_back(In{x, 0, 0, 0}); + run_cases(cos_shader, exact_cos_in, [&](const char* backend, std::size_t i, In inp, u32 got) { + u32 want = exact_cos[i].second; + ENSURE(got == want, "{}: v_cos_f32({:#010x}) = {:#010x}, want {:#010x}", backend, inp[0], got, want); + }); +} + +// ---- rs:1112 ------------------------------------------------------------------------------------ +void v_cvt_u16_and_i16_f16_saturate() { + // v_mov_b32 v0, 0; v_cvt_u16_f16 / v_cvt_i16_f16 v0, v1 (VOP1 0x052 / 0x053). + const std::vector<std::tuple<u16, u16, u16>> cases{ + // (f16 input, u16 result, i16 result) + {0x0000, 0, 0}, // 0 + {0x8000, 0, 0}, // -0 + {0x3E00, 1, 1}, // 1.5 -> 1 (toward zero) + {0xBE00, 0, 0xFFFF}, // -1.5 -> 0 / -1 + {0x57D0, 125, 125}, // 125.0 + {0x7800, 32768, 32767}, // 32768 saturates i16 + {0x77FF, 32752, 32752}, // 32752, the largest f16 below 32768 + {0xF800, 0, 0x8000}, // -32768 fits i16 + {0xF801, 0, 0x8000}, // -32800 saturates i16 + {0x7BFF, 65504, 32767}, // max finite f16 + {0xFBFF, 0, 0x8000}, // -65504 + {0x7C00, 0xFFFF, 32767}, // +inf + {0xFC00, 0, 0x8000}, // -inf + {0x7E00, 0, 0}, // NaN + {0xFE00, 0, 0}, // -NaN + {0x0001, 0, 0}, // smallest subnormal + }; + const std::array<std::tuple<u16, const char*, std::size_t>, 2> ops{{ + {0x052, "v_cvt_u16_f16", 0}, + {0x053, "v_cvt_i16_f16", 1}, + }}; + for (const auto& [op, what, pick] : ops) { + HostShader shader = build_valu_cs({vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))}); + std::vector<In> inputs; + for (const auto& c : cases) inputs.push_back(In{u32(std::get<0>(c)), 0, 0, 0}); + run_cases(shader, inputs, [&](const char* backend, std::size_t i, In, u32 got) { + u16 want = pick == 0 ? std::get<1>(cases[i]) : std::get<2>(cases[i]); + ENSURE(got == u32(want), "{}: {}({:#06x}) = {:#010x}, want {:#06x}", backend, what, std::get<0>(cases[i]), got, + want); + }); + } +} + +// ---- rs:1152 ------------------------------------------------------------------------------------ +void v_cvt_f16_u16_and_i16_widen_the_integer_first() { + // v_mov_b32 v0, 0; v_cvt_f16_u16 / v_cvt_f16_i16 v0, v1 (VOP1 0x050 / 0x051). + // Only integers f16 holds exactly: how the others round is the narrowing's business, not this + // conversion's. nullopt: the result depends on rounding. + using O = std::optional<u16>; + const std::vector<std::tuple<u16, O, O>> cases{ + // (u16 / i16 input bits, f16 of the unsigned value, f16 of the signed value) + {0x0000, O(0x0000), O(0x0000)}, // 0 + {0x0001, O(0x3C00), O(0x3C00)}, // 1.0 + {0x07FF, O(0x67FF), O(0x67FF)}, // 2047, the last integer below 2048 that f16 holds + {0x8000, O(0x7800), O(0xF800)}, // 32768 / -32768 + {0xFC00, O(0x7BE0), O(0xE400)}, // 64512 / -1024 + {0xFFFE, std::nullopt, O(0xC000)}, // 65534 does not fit f16 / -2 + {0xFFFF, std::nullopt, O(0xBC00)}, // 65535 does not fit f16 / -1 + }; + const std::array<std::tuple<u16, const char*, std::size_t>, 2> ops{{ + {0x050, "v_cvt_f16_u16", 0}, + {0x051, "v_cvt_f16_i16", 1}, + }}; + for (const auto& [op, what, pick] : ops) { + HostShader shader = build_valu_cs({vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))}); + std::vector<In> inputs; + for (const auto& c : cases) inputs.push_back(In{u32(std::get<0>(c)), 0, 0, 0}); + run_cases(shader, inputs, [&](const char* backend, std::size_t i, In, u32 got) { + O want = pick == 0 ? std::get<1>(cases[i]) : std::get<2>(cases[i]); + if (!want) return; + ENSURE(got == u32(*want), "{}: {}({:#06x}) = {:#010x}, want {:#06x}", backend, what, std::get<0>(cases[i]), + got, *want); + }); + } +} + +// The f16 forms of check_near: the result is the low half, compared as f32. +void check_near_f16(const char* backend, const char* what, std::optional<float> expect, In inp, u32 got, + const char* file, int line) { + u16 got_h = u16(got); + if (expect) { + float want = *expect; + float got_f = f16_to_f32(got_h); + ensure(std::fabs(got_f - want) < 1e-3f, + std::format("{}: {}({:#06x} = {}) = {} ({:#06x}), want {}", backend, what, inp[0], f16_to_f32(u16(inp[0])), + got_f, got_h, want), + file, line); + } else { + ensure(is_f16_nan(got_h), std::format("{}: {}({:#06x}) = {:#06x}, want NaN", backend, what, inp[0], got_h), file, + line); + } +} + +// ---- rs:1186 ------------------------------------------------------------------------------------ +void v_sin_and_v_cos_f16_reduce_large_turns() { + HostShader sin_shader = build_valu_cs({vop1(0x060, 0, vgpr(1))}); + HostShader cos_shader = build_valu_cs({vop1(0x061, 0, vgpr(1))}); + + // Sanity-check the f16 bit encodings of large turns. + CHECK(f16_to_f32(0x5BF8) == 255.0f); + CHECK(f16_to_f32(0x5BFA) == 255.25f); + CHECK(f16_to_f32(0x5BFC) == 255.5f); + CHECK(f16_to_f32(0x7BFF) == 65504.0f); + + using Cases = std::vector<std::pair<u16, std::optional<float>>>; + const Cases sin_cases{ + {0x5BF8, 0.0f}, // 255.0 + {0x5BFA, 1.0f}, // 255.25 + {0x5BFC, 0.0f}, // 255.5 + {0xDBFA, -1.0f}, // -255.25 + {0x7BFF, 0.0f}, // 65504.0 (largest finite f16, exact integer) + {0x7E00, std::nullopt}, // NaN + {0x7C00, std::nullopt}, // +inf + {0xFC00, std::nullopt}, // -inf + }; + std::vector<In> sin_inputs; + for (const auto& [x, _] : sin_cases) sin_inputs.push_back(In{u32(x), 0, 0, 0}); + run_cases(sin_shader, sin_inputs, [&](const char* backend, std::size_t i, In inp, u32 got) { + check_near_f16(backend, "v_sin_f16", sin_cases[i].second, inp, got, __FILE__, __LINE__); + }); + + const Cases cos_cases{ + {0x5BF8, 1.0f}, // 255.0 + {0x5BFA, 0.0f}, // 255.25 + {0x5BFC, -1.0f}, // 255.5 + {0x7BFF, 1.0f}, // 65504.0 (largest finite f16, exact integer) + {0x7E00, std::nullopt}, // NaN + {0x7C00, std::nullopt}, // +inf + {0xFC00, std::nullopt}, // -inf + }; + std::vector<In> cos_inputs; + for (const auto& [x, _] : cos_cases) cos_inputs.push_back(In{u32(x), 0, 0, 0}); + run_cases(cos_shader, cos_inputs, [&](const char* backend, std::size_t i, In inp, u32 got) { + check_near_f16(backend, "v_cos_f16", cos_cases[i].second, inp, got, __FILE__, __LINE__); + }); +} + +// ---- rs:1267 ------------------------------------------------------------------------------------ +// A 32-bit literal in a signed 64-bit operand is sign-extended (an unsigned one's is +// zero-extended): -100 compared with v[1:2], and shifted by s_ashr_i64. +void signed_64_bit_operands_sign_extend_their_literal() { + constexpr u32 MINUS_100 = u32(-100); + using Cases = std::vector<std::pair<In, u32>>; + auto check = [](const char* name, std::span<const u32> body, const Cases& cases) { + HostShader shader = build_valu_cs(body); + std::vector<In> inputs; + for (const auto& c : cases) inputs.push_back(c.first); + run_cases(shader, inputs, [&](const char* backend, std::size_t i, In inp, u32 got) { + u32 want = cases[i].second; + ENSURE(got == want, "{}: {} {}: {:#x} != {:#x}", backend, name, hex_in(inp), got, want); + }); + }; + // v_cmp_*_i64 s6, v[1:2], -100 (VOP3, literal src1), then v_cndmask_b32 v0, 0, 1, s6. + auto compare = [](u16 op) { + auto [a, b] = vop3(op, 6, vgpr(1), 255, 0); + auto [c, d] = vop3(0x101, 0, 0x80, 0x81, sgpr(6)); + return std::array<u32, 5>{a, b, MINUS_100, c, d}; + }; + // An i64 as the two input dwords of v[1:2]. + auto pair = [](i64 n) { return In{u32(n), u32(n >> 32), 0, 0}; }; + const Cases eq{{pair(-100), 1}, {In{MINUS_100, 0, 0, 0}, 0}, {pair(0), 0}}; + check("v_cmp_eq_i64", compare(0x0A2), eq); + const Cases lt{{pair(-200), 1}, {pair(-50), 0}, {pair(0), 0}}; + check("v_cmp_lt_i64", compare(0x0A1), lt); + // s_ashr_i64 s[6:7], -100, 4; v_mov_b32 v0, s7: the high dword. + const std::array<u32, 3> ashr{sop2(0x23, 6, 255, 0x84), MINUS_100, vop1(0x001, 0, sgpr(7))}; + check("s_ashr_i64", ashr, Cases{{In{0, 0, 0, 0}, UINT32_MAX}}); +} + +// ---- rs:1299 ------------------------------------------------------------------------------------ +void bfe_signed_and_unsigned_match_rdna2() { + // v_bfe_i32 v0, v1, v2, v3 (VOP3 opcode 0x149) + HostShader v_signed = build_valu_cs(vop3(0x149, 0, vgpr(1), vgpr(2), vgpr(3))); + // v_bfe_u32 v0, v1, v2, v3 (VOP3 opcode 0x148) + HostShader v_unsigned = build_valu_cs(vop3(0x148, 0, vgpr(1), vgpr(2), vgpr(3))); + // s_bfe_i32 s6, s0, s1 (SOP2 opcode 0x28: s1 = off[4:0] | width[22:16]); v_mov_b32 v0, s6 + HostShader s_signed = build_valu_cs({sop2(0x28, 6, 0, 1), vop1(0x001, 0, sgpr(6))}); + + using Cases = std::vector<std::pair<In, u32>>; + const Cases signed_cases{ + // Field crosses bit 31: extends from bit 31. + {{0xd2f9'0159, 28, 16, 0}, 0xffff'fffd}, + {{0x8000'0000, 31, 4, 0}, 0xffff'ffff}, + {{0x7000'0000, 28, 8, 0}, 0x0000'0007}, + // Normal fields inside 32 bits. + {{0x0000'0080, 4, 4, 0}, 0xffff'fff8}, + {{0x0000'0070, 4, 4, 0}, 0x0000'0007}, + // Edge widths: 0 yields 0; v_bfe masks width to 5 bits (32 -> 0), while 31 extracts all + // remaining bits from offset 4. + {{0xffff'ffff, 4, 0, 0}, 0}, + {{0x8000'0000, 4, 31, 0}, 0xf800'0000}, + }; + std::vector<In> v_in; + for (const auto& c : signed_cases) v_in.push_back(c.first); + run_cases(v_signed, v_in, [&](const char* backend, std::size_t i, In inp, u32 got) { + u32 want = signed_cases[i].second; + ENSURE(got == want, "{}: v_bfe_i32({:#010x}, {}, {}) = {:#010x}, want {:#010x}", backend, inp[0], inp[1], inp[2], + got, want); + }); + // v_bfe_i32 width is 5-bit (src2[4:0]), so width=32 wraps to 0. + run_cases(v_signed, {In{0x8000'0000, 4, 32, 0}}, [&](const char* backend, std::size_t, In, u32 got) { + ENSURE(got == 0, "{}: v_bfe_i32 width 32 should mask to 0", backend); + }); + + // s_bfe_i32 width is 7-bit (src1[22:16]), so width=32 keeps all 32 bits. + Cases s_cases = signed_cases; + s_cases.push_back({In{0x8000'0000, 4, 32, 0}, 0xf800'0000}); + std::vector<In> s_in; + for (const auto& [inp, _] : s_cases) s_in.push_back(In{inp[0], (inp[1] & 31) | ((inp[2] & 0x7F) << 16), 0, 0}); + run_cases(s_signed, s_in, [&](const char* backend, std::size_t i, In inp, u32 got) { + u32 want = s_cases[i].second; + ENSURE(got == want, "{}: s_bfe_i32({:#010x}, {:#010x}) = {:#010x}, want {:#010x}", backend, inp[0], inp[1], got, + want); + }); + + const Cases unsigned_cases{ + {{0xd2f9'0159, 28, 16, 0}, 0x0000'000d}, + {{0x8000'0000, 31, 4, 0}, 0x0000'0001}, + {{0xffff'ffff, 4, 0, 0}, 0}, + {{0x8000'0000, 4, 31, 0}, 0x0800'0000}, + }; + std::vector<In> u_in; + for (const auto& c : unsigned_cases) u_in.push_back(c.first); + run_cases(v_unsigned, u_in, [&](const char* backend, std::size_t i, In inp, u32 got) { + u32 want = unsigned_cases[i].second; + ENSURE(got == want, "{}: v_bfe_u32({:#010x}, {}, {}) = {:#010x}, want {:#010x}", backend, inp[0], inp[1], inp[2], + got, want); + }); +} + +// ---- rs:1372 ------------------------------------------------------------------------------------ +void f16_omod_applies_before_clamp() { + // VOP3 v_add_f16 (0x132 = 0x100 + VOP2 0x32): v0 = (v1 + v2) * omod [clamp] + HostShader mul2 = build_valu_cs(vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 1, false)); + HostShader mul4 = build_valu_cs(vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 2, false)); + HostShader div2 = build_valu_cs(vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, false)); + HostShader div2_clamp = build_valu_cs(vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, true)); + + // f16 constants: 0.25=0x3400, 0.5=0x3800, 0.75=0x3A00, 1.0=0x3C00, 1.5=0x3E00, 2.0=0x4000, + // -0.5=0xB800 + run_cases(mul2, {In{0x3400, 0x3800, 0, 0}}, // (0.25 + 0.5) * 2 = 1.5 (0x3E00) + [&](const char* backend, std::size_t, In, u32 got) { + ENSURE(u16(got) == 0x3E00, "{}: v_add_f16 mul:2", backend); + }); + run_cases(mul4, {In{0x3400, 0x3400, 0, 0}}, // (0.25 + 0.25) * 4 = 2.0 (0x4000) + [&](const char* backend, std::size_t, In, u32 got) { + ENSURE(u16(got) == 0x4000, "{}: v_add_f16 mul:4", backend); + }); + run_cases(div2, {In{0x3E00, 0x3E00, 0, 0}}, // (1.5 + 1.5) / 2 = 1.5 (0x3E00) + [&](const char* backend, std::size_t, In, u32 got) { + ENSURE(u16(got) == 0x3E00, "{}: v_add_f16 div:2", backend); + }); + // Ordering check: (0.75 + 0.75) = 1.5; div:2 before clamp gives 0.75 (0x3A00), whereas clamp + // before div:2 would give 0.5 (0x3800). + const std::vector<std::tuple<u16, u16, u16>> clamp_cases{ + {0x3A00, 0x3A00, 0x3A00}, // (0.75 + 0.75) / 2 = 0.75 -> 0.75 + {0x3E00, 0x3E00, 0x3C00}, // (1.5 + 1.5) / 2 = 1.5 -> clamped to 1.0 + {0xB800, 0xB800, 0x0000}, // (-0.5 + -0.5) / 2 = -0.5 -> clamped to 0.0 + }; + std::vector<In> inputs; + for (const auto& [a, b, _] : clamp_cases) inputs.push_back(In{u32(a), u32(b), 0, 0}); + run_cases(div2_clamp, inputs, [&](const char* backend, std::size_t i, In, u32 got) { + u16 want = std::get<2>(clamp_cases[i]); + ENSURE(u16(got) == want, "{}: v_add_f16 div:2 clamp case {}: got {:#06x}, want {:#06x}", backend, i, u16(got), + want); + }); +} + +// ---- rs:1423 ------------------------------------------------------------------------------------ +void cvt_16bit_int_from_f16_saturates_and_honors_modifiers() { + // VOP3 v_cvt_u16_f16 = 0x1D2 (0x180 + VOP1 0x52) + // VOP3 v_cvt_i16_f16 = 0x1D3 (0x180 + VOP1 0x53) + HostShader cvt_u16 = build_valu_cs(vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 0, 0, 0, false)); + HostShader cvt_u16_abs = build_valu_cs(vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 1, 0, 0, false)); + HostShader cvt_i16 = build_valu_cs(vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 0, 0, false)); + HostShader cvt_i16_neg = build_valu_cs(vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 1, 0, false)); + + using Cases = std::vector<std::pair<u16, u16>>; + const Cases u16_cases{ + {0xBC00, 0}, // -1.0 -> 0 + {0xFC00, 0}, // -inf -> 0 + {0x7E00, 0}, // NaN -> 0 + {0x57BC, 123}, // 123.75 -> 123 + {0x7BFF, 65504}, // 65504.0 (max finite f16) -> 65504 + {0x7C00, 0xFFFF}, // +inf -> 65535 (saturated) + }; + std::vector<In> u16_in; + for (const auto& [x, _] : u16_cases) u16_in.push_back(In{u32(x), 0, 0, 0}); + run_cases(cvt_u16, u16_in, [&](const char* backend, std::size_t i, In inp, u32 got) { + u16 want = u16_cases[i].second; + ENSURE(u16(got) == want, "{}: v_cvt_u16_f16({:#06x}) = {:#06x}, want {:#06x}", backend, inp[0], u16(got), want); + }); + run_cases(cvt_u16_abs, {In{0xD7BC, 0, 0, 0}}, // |-123.75| -> 123 + [&](const char* backend, std::size_t, In, u32 got) { + ENSURE(u16(got) == 123, "{}: v_cvt_u16_f16 |src0|", backend); + }); + + const Cases i16_cases{ + {0xFC00, 0x8000}, // -inf -> -32768 + {0xF8E2, 0x8000}, // -40000.0 -> -32768 (saturated, not wrapped) + {0xD7BC, u16(-123)}, // -123.75 -> -123 + {0x7E00, 0}, // NaN -> 0 + {0x57BC, 123}, // 123.75 -> 123 + {0x78E2, 0x7FFF}, // +40000.0 -> 32767 (saturated, not wrapped) + {0x7C00, 0x7FFF}, // +inf -> 32767 + }; + std::vector<In> i16_in; + for (const auto& [x, _] : i16_cases) i16_in.push_back(In{u32(x), 0, 0, 0}); + run_cases(cvt_i16, i16_in, [&](const char* backend, std::size_t i, In inp, u32 got) { + u16 want = i16_cases[i].second; + ENSURE(u16(got) == want, "{}: v_cvt_i16_f16({:#06x}) = {:#06x}, want {:#06x}", backend, inp[0], u16(got), want); + }); + run_cases(cvt_i16_neg, {In{0x57BC, 0, 0, 0}, In{0x78E2, 0, 0, 0}}, // -(123.75) -> -123; -(40000.0) -> -32768 + [&](const char* backend, std::size_t i, In, u32 got) { + const std::array<u16, 2> wants{u16(-123), 0x8000}; + u16 want = wants[i]; + ENSURE(u16(got) == want, "{}: v_cvt_i16_f16 -src0 case {}", backend, i); + }); +} + +constexpr u32 S_BARRIER = 0xBF8A'0000; + +// VOP2 op vdst, src0, vsrc1. +constexpr u32 vop2(u8 op, u8 vdst, u16 src0, u8 vsrc1) { + return (u32(op) & 0x3F) << 25 | u32(vdst) << 17 | u32(vsrc1) << 9 | (u32(src0) & 0x1FF); +} + +// DS op vdst, addr, data0 at offset 0. +constexpr std::array<u32, 2> ds(u8 op, u8 vdst, u8 addr, u8 data0) { + return {0x36u << 26 | u32(op) << 18, u32(vdst) << 24 | u32(data0) << 8 | u32(addr)}; +} + +constexpr u8 DS_WRITE_B32 = 0x0D; +constexpr u8 DS_MIN_F32 = 0x12; +constexpr u8 DS_MAX_F32 = 0x13; +constexpr u8 DS_MIN_RTN_F32 = 0x32; +constexpr u8 DS_MAX_RTN_F32 = 0x33; +constexpr u8 DS_READ_B32 = 0x36; + +// What RDNA2 writes for ds_max_f32 / ds_min_f32 over a dword holding `old` with `data` (bits), as +// measured on gfx1036 with f32 denormals kept: an sNaN, data first, then memory, is written +// quieted; otherwise a NaN loses to a number (two quiet NaNs give the data); numbers compare as +// floats with -0 below +0. +u32 lds_min_max_ref(u32 old, u32 data, bool max) { + auto nan = [](u32 x) { return (x & 0x7FFF'FFFF) > 0x7F80'0000; }; + auto snan = [&](u32 x) { return nan(x) && (x & 0x40'0000) == 0; }; + auto key = [](u32 x) { + i32 b = i32(x); + return b < 0 ? (b ^ 0x7FFF'FFFF) : b; + }; + if (snan(data)) return data | 0x40'0000; + if (snan(old)) return old | 0x40'0000; + bool nd = nan(data), no = nan(old); + if (no) return data; // (true, true) | (false, true) + if (nd) return old; // (true, false) + bool take = max ? key(data) > key(old) : key(data) < key(old); + return take ? data : old; +} + +// ---- rs:1538 ------------------------------------------------------------------------------------ +void ds_min_max_f32_order_floats_and_return_the_old_value() { + const std::array<float, 14> values{ + 0.0f, + -0.0f, + 1.0f, + -1.0f, + 2.5f, + -2.5f, + 1e-30f, + -1e-30f, + b2f(1), // denormal + b2f(0x8000'0001), + std::numeric_limits<float>::infinity(), + -std::numeric_limits<float>::infinity(), + FLT_MAX, + -FLT_MAX, + }; + // Quiet and signalling NaNs of both signs, in memory and as data. + const std::array<u32, 5> nans{0x7FC0'0000u, 0xFFC0'0000, 0x7F80'0001, 0xFFA0'0000, 0x7FBF'FFFF}; + std::vector<u32> bits; + for (float v : values) bits.push_back(f2b(v)); + for (u32 n : nans) bits.push_back(n); + std::vector<In> cases; + for (u32 old : bits) + for (u32 data : bits) cases.push_back(In{old, data, 0, 0}); + const std::array<std::tuple<u8, u8, bool, const char*>, 2> forms{{ + {DS_MAX_RTN_F32, DS_MAX_F32, true, "ds_max"}, + {DS_MIN_RTN_F32, DS_MIN_F32, false, "ds_min"}, + }}; + for (const auto& [rtn, plain, max, what] : forms) { + // v5 = 0; LDS[v5] = v1; the atomic with v2; v0 = the old value (rtn) or the dword afterwards + // (read back). + Words returns_old{vop1(0x001, 5, 0x80)}; + append(returns_old, ds(DS_WRITE_B32, 0, 5, 1)); + append(returns_old, ds(rtn, 0, 5, 2)); + Words returns_new{vop1(0x001, 5, 0x80)}; + append(returns_new, ds(DS_WRITE_B32, 0, 5, 1)); + append(returns_new, ds(plain, 0, 5, 2)); + append(returns_new, ds(DS_READ_B32, 0, 5, 0)); + const std::array<std::pair<const Words*, bool>, 2> bodies{{{&returns_old, true}, {&returns_new, false}}}; + for (const auto& [body, old_result] : bodies) { + // One thread with LDS declares WaveSize(32), which WARP's pipeline creation refuses: + // hardware only (the 64-thread test below runs on WARP too). + HostShader shader = build_cs(*body, 1, 512); + run_cases_on(shader, cases, HARDWARE_ONLY, [&](const char* backend, std::size_t, In inp, u32 got) { + float old = b2f(inp[0]), data = b2f(inp[1]); + u32 want = old_result ? inp[0] : lds_min_max_ref(inp[0], inp[1], max); + ENSURE(got == want, "{}: {}_f32 on {:e} [{:#010x}] with {:e} [{:#010x}] gave {:#010x}, want {:#010x} ({})", + backend, what, old, inp[0], data, inp[1], got, want, old_result ? "old value" : "dword after"); + }); + } + } +} + +// ---- rs:1618 ------------------------------------------------------------------------------------ +void ds_min_max_f32_are_atomic_across_waves() { + // 64 threads (two host waves of 32 or one of 64): LDS[0] = v1, then every thread applies + // (thread - 32) as a float; v0 = LDS[0]. + const float INF = std::numeric_limits<float>::infinity(); + const std::array<std::tuple<u8, bool, float, float>, 4> forms{{ + {DS_MAX_F32, true, -INF, 31.0f}, + {DS_MAX_F32, true, 100.0f, 100.0f}, + {DS_MIN_F32, false, INF, -32.0f}, + {DS_MIN_F32, false, -0.0f, -32.0f}, + }}; + for (const auto& [op, max, init, want] : forms) { + Words body{vop1(0x001, 5, 0x80)}; + append(body, ds(DS_WRITE_B32, 0, 5, 1)); + body.push_back(S_BARRIER); + body.push_back(vop2(0x26, 6, vgpr(0), 3)); // v_sub_nc_u32 v6, v0, v3 + body.push_back(vop1(0x005, 6, vgpr(6))); // v_cvt_f32_i32 + append(body, ds(op, 0, 5, 6)); + body.push_back(S_BARRIER); + append(body, ds(DS_READ_B32, 0, 5, 0)); + HostShader shader = build_cs(body, 64, 512); + run_cases(shader, {In{f2b(init), 0, 32, 0}}, [&](const char* backend, std::size_t, In, u32 got) { + ENSURE(b2f(got) == want, "{}: {} from {} over 64 threads: {} != {}", backend, max ? "max" : "min", init, + b2f(got), want); + }); + } +} + +// ---- rs:1652 ------------------------------------------------------------------------------------ +void v_cmp_class_f16_matches_rdna2() { + // v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6 + HostShader cmp_lo = build_valu_cs({ + vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[0], + vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[1], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + }); + // Same with op_sel:[1,0] (high half of v1) + neg on src0 (bit 29 of w1). + auto [w0, w1] = vop3(0x08f, 6, vgpr(1), vgpr(2), 0); + w0 |= 1u << 11; // opsel[0] = 1 (high half) + w1 |= 1u << 29; // neg[0] = 1 + HostShader cmp_hi_neg = build_valu_cs({ + w0, + w1, + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + }); + + // All 10 IEEE-754 binary16 classes: bit k corresponds to class k. + const std::vector<std::pair<u32, u32>> classes{ + {0x7C01, 0}, // sNaN (+sNaN, quiet bit 0x0200 clear) + {0xFDFF, 0}, // -sNaN (sign ignored for NaNs) + {0x7E00, 1}, // +qNaN + {0xFE01, 1}, // -qNaN + {0xFC00, 2}, // -inf + {0xBC00, 3}, // -normal (-1.0) + {0x8001, 4}, // -denormal + {0x8000, 5}, // -0.0 + {0x0000, 6}, // +0.0 + {0x0001, 7}, // +denormal + {0x3C00, 8}, // +normal (+1.0) + {0x7C00, 9}, // +inf + }; + std::vector<std::pair<In, u32>> cases; + for (const auto& [bits, cls] : classes) { + // Exact class bit -> true; complement of class bit across all 10 bits -> false. + cases.push_back({In{bits, 1u << cls, 0, 0}, 1u}); + cases.push_back({In{bits, 0x3FFu & ~(1u << cls), 0, 0}, 0u}); + } + std::vector<In> inputs; + for (const auto& c : cases) inputs.push_back(c.first); + run_cases(cmp_lo, inputs, [&](const char* backend, std::size_t i, In inp, u32 got) { + u32 want = cases[i].second; + ENSURE(got == want, "{}: v_cmp_class_f16({:#06x}, {:#05x}) = {}, want {}", backend, inp[0], inp[1], got, want); + }); + + // High half with neg: high half 0x3C00 (+1.0) negated -> -normal (class 3); high half 0x7C01 + // (+sNaN) negated -> still sNaN (class 0, not quieted). + const std::vector<std::pair<In, u32>> hi_cases{ + {{0x3C00'0000, 1u << 3, 0, 0}, 1}, + {{0x3C00'0000, 1u << 8, 0, 0}, 0}, + {{0x7C01'FFFF, 1u << 0, 0, 0}, 1}, + {{0x7C01'FFFF, 1u << 1, 0, 0}, 0}, + }; + std::vector<In> hi_in; + for (const auto& c : hi_cases) hi_in.push_back(c.first); + run_cases(cmp_hi_neg, hi_in, [&](const char* backend, std::size_t i, In inp, u32 got) { + u32 want = hi_cases[i].second; + ENSURE(got == want, "{}: v_cmp_class_f16(-hi({:#010x}), {:#05x}) = {}, want {}", backend, inp[0], inp[1], got, + want); + }); +} + +// ---- rs:1722 ------------------------------------------------------------------------------------ +void v_cvt_f32_f64_matches_ieee754() { + // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x00f -> VOP3 opcode 0x18f). + HostShader plain = build_valu_cs({vop1(0x00f, 0, vgpr(1))}); + // Same with abs + neg on src0 (VOP3: abs[0] = bit 8 of w0, neg[0] = bit 29 of w1). + auto [w0, w1] = vop3(0x18f, 0, vgpr(1), 0, 0); + w0 |= 1u << 8; + w1 |= 1u << 29; + HostShader neg_abs = build_valu_cs({w0, w1}); + + const double INF = std::numeric_limits<double>::infinity(); + const std::vector<double> values{ + 0.0, + -0.0, + 1.0, + -1.0, + 3.5, + -123456.75, + // Tie-to-even: even mantissa stays, odd mantissa rounds up. + b2d(0x3FF0'0000'1000'0000), // 1.0 + 0.5 ulp(f32) -> 1.0 + b2d(0x3FF0'0000'3000'0000), // (1.0 + 1 ulp) + 0.5 ulp -> 1.0 + 2 ulp + b2d(0x3FF0'0000'1000'0001), // > 0.5 ulp -> rounds up + // Largest finite f32 and overflow to +Inf / -Inf. + double(FLT_MAX), + double(FLT_MAX) * 1.000'001, + -double(FLT_MAX) * 1.000'001, + 1e300, + // Subnormal range (exp64 in [874, 896]), including carry into smallest normal. + double(FLT_MIN), + double(FLT_MIN) * 0.5, + double(FLT_MIN) * 0.75, + double(b2f(0x007F'FFFF)), + b2d(0x380F'FFFF'F000'0000), // max subnormal + 0.5 ulp -> min normal + // exp64 == 873: exact 2^-150 ties to 0; strictly greater rounds to min subnormal (1). + b2d(0x3690'0000'0000'0000), + b2d(0x3690'0000'0000'0001), + b2d(0xB690'0000'0000'0001), + // Deep underflow -> +/-0.0. + 1e-200, + -1e-200, + // Infinities and NaNs. + INF, + -INF, + b2d(0x7FF8'0000'0000'0000), // +qNaN + b2d(0x7FF0'0000'0000'0001), // +sNaN -> quieted + }; + std::vector<In> inputs = f64_inputs(values); + run_cases(plain, inputs, [&](const char* backend, std::size_t i, In, u32 got) { + double x = values[i]; + // Rust `x as f32`: round to nearest even, NaN stays a NaN (its quiet bit is not checked + // here, only on the result). + u32 want = f2b(static_cast<float>(x)); + if (std::isnan(x)) { + ENSURE(std::isnan(b2f(got)) && (got & 0x0040'0000) != 0, "{}: v_cvt_f32_f64({:#018x}) = {:#010x}, expected qNaN", + backend, d2b(x), got); + } else { + ENSURE(got == want, "{}: v_cvt_f32_f64({} / {:#018x}) = {:#010x}, want {:#010x}", backend, x, d2b(x), got, + want); + } + }); + + // -|x| via VOP3 abs + neg modifiers. + const std::vector<double> mod_values{2.5, -2.5, 0.0, INF}; + std::vector<In> mod_in = f64_inputs(mod_values); + run_cases(neg_abs, mod_in, [&](const char* backend, std::size_t i, In, u32 got) { + double x = mod_values[i]; + u32 want = f2b(static_cast<float>(-std::fabs(x))); + ENSURE(got == want, "{}: v_cvt_f32_f64(-|{}|) = {:#010x}, want {:#010x}", backend, x, got, want); + }); +} + +// ---- rs:1811 ------------------------------------------------------------------------------------ +void whole_wave_f64_sum_and_cvt_f32_f64() { + auto s_or_saveexec_b32 = [](u8 sdst, u8 src0) { return 0xBE80'0000u | u32(sdst) << 16 | 0x3Du << 8 | u32(src0); }; + auto v_mov_dpp8 = [](u8 vdst, u8 vsrc, u32 sel) { + return std::array<u32, 2>{vop1(0x001, vdst, 0xE9), u32(vsrc) | (sel << 8)}; + }; + auto v_mov_row_mirror = [](u8 vdst, u8 vsrc) { + return std::array<u32, 2>{vop1(0x001, vdst, 0xFA), + u32(vsrc) | (0x140u << 8) | (1u << 19) | (0xFu << 24) | (0xFu << 28)}; + }; + + Words words; + words.push_back(s_mov_b32(5, 0x80)); + append(words, s_load_dwordx4(8, 4)); + // Per-lane f64 input in v[6:7] = (s0, s1). + words.push_back(vop1(0x001, 6, sgpr(0))); + words.push_back(vop1(0x001, 7, sgpr(1))); + // Whole-wave f64 sum over Wave32 with s_mov_b32 copy before EXEC restore. + words.push_back(s_or_saveexec_b32(12, 0xC1)); + append(words, vop3(0x101, 2, 0x80, vgpr(6), sgpr(12))); + append(words, vop3(0x101, 3, 0x80, vgpr(7), sgpr(12))); + for (u32 sel : {14570689u, 9658386u, 2340u}) { + append(words, v_mov_dpp8(4, 2, sel)); + append(words, v_mov_dpp8(5, 3, sel)); + append(words, vop3(0x164, 2, vgpr(4), vgpr(2), 0)); // v_add_f64 + } + append(words, v_mov_row_mirror(4, 2)); + append(words, v_mov_row_mirror(5, 3)); + append(words, vop3(0x164, 2, vgpr(4), vgpr(2), 0)); + append(words, vop3(0x378, 4, vgpr(2), 0x80, 0x80)); // v_permlanex16_b32 + append(words, vop3(0x378, 5, vgpr(3), 0x80, 0x80)); + append(words, vop3(0x164, 2, vgpr(4), vgpr(2), 0)); + append(words, vop3(0x360, 14, vgpr(2), 0x80, 0)); // v_readlane_b32 s14, v2, 0 + append(words, vop3(0x360, 15, vgpr(3), 0x80, 0)); // v_readlane_b32 s15, v3, 0 + words.push_back(s_mov_b32(16, 14)); + words.push_back(s_mov_b32(17, 15)); + words.push_back(s_mov_b32(126, 12)); // restore exec_lo + words.push_back(vop1(0x00f, 0, sgpr(16))); // v_cvt_f32_f64 v0, s[16:17] + append(words, buffer_store_dword(0, 8, 0)); + words.push_back(S_ENDPGM); + + NativeProgram native = synthetic_cs(le_bytes(words), 12, 5u << 1, {4, 1, 1}); + HostShader shader = lower_cs(native, false); + validate(shader, false); + + const std::array<std::pair<double, float>, 2> cases{{{1.25, 5.0f}, {-0.75, -3.0f}}}; + std::lock_guard one(ONE_AT_A_TIME); + for (const auto& [label, warp] : HARDWARE_AND_WARP) { + std::optional<vs::host::Host> host; + try { + host.emplace(warp); + } catch (const std::exception&) { + continue; + } + Microsoft::WRL::ComPtr<ID3D12RootSignature> root; + Microsoft::WRL::ComPtr<ID3D12PipelineState> pso; + try { + auto [r, p] = host->compute_pipeline(shader); + root = r; + pso = p; + } catch (const std::exception& e) { + // WARP does not support fixed WaveSize(32) on SM 6.6. + if (warp) { + std::fprintf(stderr, "%s: compute_pipeline skipped (%s)\n", label, e.what()); + continue; + } + throw std::runtime_error(std::format("{}: compute_pipeline failed: {}", label, e.what())); + } + for (const auto& [x, want] : cases) { + u64 b = d2b(x); + In inputs{u32(b), u32(b >> 32), 0, 0}; + u32 got = dispatch_one(*host, root.Get(), pso.Get(), user_data_for(shader, inputs), label); + ENSURE(got == f2b(want), "{}: wave f64 sum({}) = {:#010x}, want {:#010x}", label, x, got, f2b(want)); + } + } +} + +// Whether the hardware adapter is an AMD RDNA card's: what the translator writes for one +// (emit::rdna) holds there. +bool rdna_card() { + std::optional<vs::host::Host> host; + try { + host.emplace(false); + } catch (const std::exception&) { + return false; + } + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + bool amd = false; + Microsoft::WRL::ComPtr<IDXGIFactory4> factory; + if (SUCCEEDED(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory)))) { + Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter; + if (SUCCEEDED(factory->EnumAdapterByLuid(host->device->GetAdapterLuid(), IID_PPV_ARGS(&adapter)))) { + DXGI_ADAPTER_DESC1 desc{}; + amd = SUCCEEDED(adapter->GetDesc1(&desc)) && desc.VendorId == 0x1002; + } + } + return amd && SUCCEEDED(host->device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof(waves))) && + waves.WaveLaneCountMin == 32 && waves.WaveLaneCountMax == 64; +} + +// ---- rs:2002 ------------------------------------------------------------------------------------ +// The forms written for the console's own kind of hardware give, on such a card, what the ones +// spelled out for every host give; a legacy product's zero may have the other sign. +void rdna_forms_give_what_the_spelled_out_ones_give() { + if (!rdna_card()) { + std::fprintf(stderr, "no RDNA card; skipped\n"); + return; + } + constexpr u16 ONE = 242; + constexpr u16 MINUS_ONE = 243; + const u16 a = vgpr(1), b = vgpr(2), c = vgpr(3); + auto saturated = vop3_mod(0x110, 5, vgpr(1), vgpr(1), 0, 0, 0, 0, true); + auto two = [](std::array<u32, 2> x, std::array<u32, 2> y) { return Words{x[0], x[1], y[0], y[1]}; }; + auto vec = [](std::array<u32, 2> x) { return Words{x[0], x[1]}; }; + const std::vector<std::tuple<const char*, Words, bool>> bodies{ + {"max", vec(vop3(0x110, 0, a, b, 0)), true}, + {"min", vec(vop3(0x10F, 0, a, b, 0)), true}, + {"max3", vec(vop3(0x154, 0, a, b, c)), true}, + {"min3", vec(vop3(0x151, 0, a, b, c)), true}, + {"med3 0 1", vec(vop3(0x157, 0, a, 128, ONE)), true}, + {"med3 1 0", vec(vop3(0x157, 0, ONE, a, 128)), true}, + {"med3 1 -1", vec(vop3(0x157, 0, ONE, MINUS_ONE, a)), true}, + {"fract", Words{vop1(0x020, 0, a)}, true}, + {"mul_legacy", vec(vop3(0x107, 0, a, b, 0)), false}, + {"mul_legacy by itself", vec(vop3(0x107, 0, a, a, 0)), false}, + {"mul_legacy by a constant", vec(vop3(0x107, 0, a, MINUS_ONE, 0)), false}, + {"mul_legacy of a saturated", two(saturated, vop3(0x107, 0, vgpr(5), b, 0)), false}, + {"mad_legacy", vec(vop3(0x140, 0, a, b, c)), false}, + {"max of a mul_legacy", two(vop3(0x107, 5, a, b, 0), vop3(0x110, 0, vgpr(5), c, 0)), false}, + }; + const std::array<float, 10> numbers{0.0f, + -0.0f, + 1.0f, + -1.0f, + 0.3f, + -2.5e-7f, + 3e38f, + std::numeric_limits<float>::infinity(), + -std::numeric_limits<float>::infinity(), + std::numeric_limits<float>::quiet_NaN()}; + std::vector<In> cases; + for (std::size_t i = 0; i < numbers.size(); ++i) { + for (std::size_t j = 0; j < numbers.size(); ++j) { + float z = numbers[(3 * i + j) % numbers.size()]; + cases.push_back(In{f2b(numbers[i]), f2b(numbers[j]), f2b(z), 0}); + } + } + for (const auto& [name, body, exact] : bodies) { + std::vector<std::vector<u32>> got; + std::vector<std::vector<u8>> written; + for (u32 bits : {0u, vs::rdna::ALL}) { + vs::lower::test::set_rdna(bits); + HostShader shader = build_valu_cs(body); + vs::lower::test::set_rdna(std::nullopt); + written.push_back(shader.dxil); + std::vector<u32> all; + run_cases_on(shader, cases, HARDWARE_ONLY, [&](const char*, std::size_t, In, u32 r) { all.push_back(r); }); + got.push_back(std::move(all)); + } + ENSURE(written[0] != written[1], "{}: written alike", name); + for (std::size_t k = 0; k < cases.size() && k < got[0].size() && k < got[1].size(); ++k) { + u32 was = got[0][k], is = got[1][k]; + float x = b2f(was), y = b2f(is); + bool same = was == is || (std::isnan(x) && std::isnan(y)) || (!exact && x == 0.0f && y == 0.0f); + const In& cs = cases[k]; + ENSURE(same, "{} of [{}, {}, {}, {}]: {} ({:#x}), now {} ({:#x})", name, b2f(cs[0]), b2f(cs[1]), b2f(cs[2]), + b2f(cs[3]), x, was, y, is); + } + } +} + +// Runs one test as the Rust test thread `emit::valu_tests::<name>` would: VS_DUMP names its modules +// after it, and a panic (here: an exception) fails it. +void run(const char* name, void (*test)()) { + x2w::vs::lower::test::set_dump_name(std::string("emit__valu_tests__") + name); + try { + test(); + } catch (const std::exception& e) { + std::fprintf(stderr, "%s: panicked: %s\n", name, e.what()); + ++test_util::failures(); + } +} + +} // namespace + +#define RUN(name) run(#name, name) + +int main(int argc, char** argv) { + bool ignored = argc > 1 && std::string_view(argv[1]) == "--ignored"; + if (ignored) { + RUN(v_cvt_f32_f64_rounds_to_nearest_even); + return test_util::finish("lower_valu_test --ignored"); + } + RUN(scalar_quad_masks_pack_nibbles_and_set_scc); + RUN(a_branch_to_fallthrough_keeps_both_values_at_a_join); + RUN(tbuffer_d16_loads_pack_two_channels_per_dword); + RUN(normalized_buffer_formats_load_their_ends_exactly); + RUN(normalized_buffer_formats_load_correctly_rounded_quotients); + RUN(normalized_codes_truncate_back_to_themselves); + RUN(packed_add_selects_halves_of_inline_constants); + RUN(v_permlane16_and_x16_read_the_lanes_their_selectors_pick); + RUN(v_med3_f32_matches_rdna2_with_nan); + RUN(max_and_min_order_negative_zero_below_positive_zero); + RUN(f16_max_and_min_order_negative_zero_below_positive_zero); + RUN(v_min3_max3_med3_integer_forms_match_rdna2); + RUN(v_med3_f16_matches_rdna2_with_nan); + RUN(v_cmp_lg_is_false_for_nan); + RUN(v_cvt_off_f32_i4_uses_the_signed_low_nibble); + RUN(v_fract_f32_never_returns_one); + RUN(v_fract_f16_never_returns_one); + RUN(v_cvt_norm_i16_and_u16_f16_round_the_exact_product); + RUN(v_sin_and_v_cos_f32_reduce_large_turns); + RUN(v_cvt_u16_and_i16_f16_saturate); + RUN(v_cvt_f16_u16_and_i16_widen_the_integer_first); + RUN(v_sin_and_v_cos_f16_reduce_large_turns); + RUN(signed_64_bit_operands_sign_extend_their_literal); + RUN(bfe_signed_and_unsigned_match_rdna2); + RUN(f16_omod_applies_before_clamp); + RUN(cvt_16bit_int_from_f16_saturates_and_honors_modifiers); + RUN(ds_min_max_f32_order_floats_and_return_the_old_value); + RUN(ds_min_max_f32_are_atomic_across_waves); + RUN(v_cmp_class_f16_matches_rdna2); + RUN(v_cvt_f32_f64_matches_ieee754); + RUN(whole_wave_f64_sum_and_cvt_f32_f64); + RUN(rdna_forms_give_what_the_spelled_out_ones_give); + return test_util::finish("lower_valu_test"); +} diff --git a/tests/x2w_shader/emit/lower_waterfall_test.cpp b/tests/x2w_shader/emit/lower_waterfall_test.cpp new file mode 100644 index 0000000000..5feb8f6491 --- /dev/null +++ b/tests/x2w_shader/emit/lower_waterfall_test.cpp @@ -0,0 +1,261 @@ +// Port of the upstream Rust module emit/waterfall_tests.rs, in Rust order. +// +// End-to-end tests of waterfall loops over per-lane descriptors: the synthetic GFX10 programs of +// `resource::tests` lowered to DXIL, validated by dxil.dll when present, and run on the host GPU +// and WARP, each lane reading the resource its own descriptor names. + +#include "lower_card_util.h" +#include "resource_fixtures.h" // FRONT? vs-front: tests/x2w_shader/resource_fixtures.h (resource::tests) + +using namespace card; +namespace fx = vs::resource::fixtures; // FRONT? + +namespace { + +// Lowers a wave32 compute program of 32 threads with the table of views at s0 (textures, or with +// `buffers` structured buffers of dwords, at entries 0 and 1, a raw UAV at entry 2) and the table +// of samplers at s1. +HostShader build(std::span<const std::uint32_t> words, bool buffers) { + auto table = [](std::uint8_t user_data) { return root_param(RootType::Table(), 0, 1, 0, user_data, user_data); }; + auto range = [](ResourceType kind, std::uint32_t table_offset_dwords, std::uint8_t dwords, std::uint32_t stride, + std::uint8_t user_data) { + return used_resource(kind, RootType::Table(), table_offset_dwords, 0, stride, dwords, user_data, user_data); + }; + UsedResource views = buffers ? range(ResourceType::Srv(), 0, 4, 4, 0) : range(ResourceType::Srv(), 0, 8, 0, 0); + NativeProgram native; + native.stage = HwStage::Cs; + native.wave64 = false; + native.vgprs = 32; + native.layout = {table(0), table(1)}; + native.used = {views, range(ResourceType::Uav(), 16, 4, 0, 0), range(ResourceType::Sampler(), 0, 4, 0, 1)}; + native.io = compute_io(2 << 1, {32, 1, 1}); + native.code = le_bytes(words); + vs::ir::Program p = vs::ir::build(native.code, native.wave64, native.vgprs); + vs::structure::Structured st = vs::structure::structure(p); + vs::resource::Resources res = vs::resource::track(p, native.layout, native.stage, &st); + vs::io::Io io = vs::io::raise(p, native); + Lowered lowered = vs::lower::lower(parts_of(native, p, st, io, res)); + // One access with each lane's own heap index, no wave operation. + require(lowered.nonuniform_handles == 1, "nonuniform_handles == 1"); + require(!lowered.wave_ops, "!wave_ops"); + HostShader shader = host_shader(std::move(lowered), {}); + validate(shader, true); + return shader; +} + +// The red channel each lane sampled from two 1x1 textures, red 1.0 at heap index 0 and 2.0 at 1. +std::vector<std::pair<const char*, std::vector<float>>> sampled(const HostShader& shader) { + const Texel first[] = {{1.0f, 0.0f, 0.0f, 1.0f}}; + const Texel second[] = {{2.0f, 0.0f, 0.0f, 1.0f}}; + const View views[] = {texture(1, 1, first), texture(1, 1, second), raw_uav(32)}; + std::vector<std::pair<const char*, std::vector<float>>> out; + for (auto& [label, words] : run(shader, views)) { + std::vector<float> red; + for (std::uint32_t w : words) red.push_back(f32_from_bits(w)); + out.emplace_back(label, std::move(red)); + } + return out; +} + +// ---- rs:168 ------------------------------------------------------------------------------------- +void lanes_sample_the_texture_their_if_else_arm_chose() { + x2w::vs::lower::test::set_dump_name("emit__waterfall_tests__lanes_sample_the_texture_their_if_else_arm_chose"); + HostShader shader = build(fx::WATERFALL_JOINED_WAVE32, false); // FRONT? + for (auto& [label, red] : sampled(shader)) { + // Lanes below 16 took the first texture, the others the second. + std::vector<float> want; + for (int l = 0; l < 32; ++l) want.push_back(l < 16 ? 1.0f : 2.0f); + require(red == want, label); + } +} + +// ---- rs:179 ------------------------------------------------------------------------------------- +void lanes_sample_the_texture_their_arm_loaded_or_picked() { + x2w::vs::lower::test::set_dump_name("emit__waterfall_tests__lanes_sample_the_texture_their_arm_loaded_or_picked"); + HostShader shader = build(fx::WATERFALL_JOINED_MIXED_WAVE32, false); // FRONT? + for (auto& [label, red] : sampled(shader)) { + // Lanes below 16 loaded entry (lane & 1); of the others, lanes below 24 picked the first, + // the rest the second. + std::vector<float> want; + for (int l = 0; l < 32; ++l) { + const float pair[] = {1.0f, 2.0f}; + want.push_back(l < 16 ? pair[l & 1] : l < 24 ? 1.0f : 2.0f); + } + require(red == want, label); + } +} + +// ---- rs:197 ------------------------------------------------------------------------------------- +void lanes_load_from_the_buffer_their_nested_arms_chose() { + x2w::vs::lower::test::set_dump_name("emit__waterfall_tests__lanes_load_from_the_buffer_their_nested_arms_chose"); + HostShader shader = build(fx::WATERFALL_JOINED_BUFFER_WAVE32, true); // FRONT? + std::vector<std::uint32_t> first, second; + for (std::uint32_t i = 0; i < 32; ++i) { + first.push_back(100 + i); + second.push_back(200 + i); + } + const View views[] = {buffer(first, stride_structured(4)), buffer(second, stride_structured(4)), raw_uav(32)}; + for (auto& [label, got] : run(shader, views)) { + // Dword `lane` of the first buffer below 16, of the second from 16 to 23; lanes from 24 + // on load and store nothing. + std::vector<std::uint32_t> want; + for (std::uint32_t l = 0; l < 32; ++l) want.push_back(l < 16 ? 100 + l : l < 24 ? 200 + l : 0); + require(got == want, label); + } +} + +// ---- rs:228 ------------------------------------------------------------------------------------- +void lanes_sample_the_entry_their_offset_names_in_the_console_waterfall() { + x2w::vs::lower::test::set_dump_name( + "emit__waterfall_tests__lanes_sample_the_entry_their_offset_names_in_the_console_waterfall"); + HostShader shader = build(fx::WATERFALL_INDEXED_WAVE32, false); // FRONT? + auto results = sampled(shader); + require(!results.empty(), "!results.is_empty()"); + for (auto& [label, red] : results) { + // Even lanes hold entry 0's offset, odd lanes entry 1's. + std::vector<float> want; + for (int l = 0; l < 32; ++l) want.push_back((l & 1) ? 2.0f : 1.0f); + require(red == want, label); + } +} + +// ---- rs:241 ------------------------------------------------------------------------------------- +void lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx() { + x2w::vs::lower::test::set_dump_name( + "emit__waterfall_tests__lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx"); + // Lanes below 16 hold the first descriptor, the others the second. + std::vector<float> want; + for (int l = 0; l < 32; ++l) want.push_back(l < 16 ? 1.0f : 2.0f); + for (bool folded : {false, true}) { + std::vector<std::uint32_t> words = fx::cmpx_waterfall(false, folded); // FRONT? -> std::vector<std::uint32_t> + HostShader shader = build(words, false); + auto results = sampled(shader); + require(!results.empty(), "!results.is_empty()"); + for (auto& [label, red] : results) + require(red == want, std::string(label) + ", folded " + (folded ? "true" : "false")); + } +} + +// ---- rs:256 ------------------------------------------------------------------------------------- +void immediate_sampler_chosen_by_control_flow() { + x2w::vs::lower::test::set_dump_name("emit__waterfall_tests__immediate_sampler_chosen_by_control_flow"); + using W2 = std::array<std::uint32_t, 2>; + auto s_mov_lit = [](std::uint8_t dst, std::uint32_t lit) { return W2{0xBE80'03FFu | std::uint32_t(dst) << 16, lit}; }; + auto s_mov_zero = [](std::uint8_t dst) { return 0xBE80'0380u | std::uint32_t(dst) << 16; }; + auto s_load_x8 = [](std::uint8_t dst, std::uint8_t base) { + return W2{0x3Du << 26 | 0x03u << 18 | std::uint32_t(dst) << 6 | (std::uint32_t(base) >> 1), 125u << 25}; + }; + auto s_load_x4_off = [](std::uint8_t dst, std::uint8_t base, std::uint32_t off) { + return W2{0x3Du << 26 | 0x02u << 18 | std::uint32_t(dst) << 6 | (std::uint32_t(base) >> 1), 125u << 25 | off}; + }; + // image_sample_lz v4, v[2:3], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D + const W2 image_sample_lz = { + 0x3Cu << 26 | 0x21u << 18 | 1u << 8 | 1u << 3, // dmask=1, dim=2D(1) + (16u >> 2) << 21 | (8u >> 2) << 16 | 4u << 8 | 2u, + }; + // buffer_store_dword v4, off, s[20:23], 0 + const W2 buf_store = {0x38u << 26 | 0x1Cu << 18, 0x80u << 24 | (20u >> 2) << 16 | 4u << 8}; + + // Two distinct valid immediate sampler descriptors (different wrap/filter bits). + const std::array<std::uint32_t, 4> samp_a = {0x0000'0092, 0x00C0'0000, 0x1850'0000, 0}; + const std::array<std::uint32_t, 4> samp_b = {0x0000'0092, 0x00C0'0000, 0x1850'0001, 0}; + + const std::pair<const char*, std::array<std::uint32_t, 4>> cases[] = {{"same_sampler", samp_a}, + {"different_samplers", samp_b}}; + for (const auto& [case_name, alt] : cases) { + std::vector<std::uint32_t> words; + auto extend = [&](const W2& w) { words.insert(words.end(), w.begin(), w.end()); }; + // s[2:3] = view table base (s0, 0). + words.push_back(0xBE80'0300u | (2u << 16)); // s_mov_b32 s2, s0 + words.push_back(s_mov_zero(3)); + extend(s_load_x8(8, 2)); // s[8:15] = texture SRV (offset 0) + extend(s_load_x4_off(20, 2, 64)); // s[20:23] = raw UAV (offset 16 dwords = 64B) + // v2 = 0.5, v3 = 0.5 (sample coordinates). + words.push_back(0x7E00'02F0u | (2u << 17)); // v_mov_b32 v2, 0.5 + words.push_back(0x7E00'02F0u | (3u << 17)); // v_mov_b32 v3, 0.5 + // s_cmp_eq_u32 s1, 0; s_cbranch_scc0 else_arm + words.push_back(0xBF00'8001u); // s_cmp_eq_u32 s1, 0 (const 128) + std::size_t br_else = words.size(); + words.push_back(0); // placeholder s_cbranch_scc0 + // then arm: load samp_a into s[16:19] + for (std::size_t i = 0; i < samp_a.size(); ++i) extend(s_mov_lit(std::uint8_t(16 + i), samp_a[i])); + std::size_t br_join = words.size(); + words.push_back(0); // placeholder s_branch + std::size_t else_pc = words.size(); + // else arm: load alt into s[16:19] + for (std::size_t i = 0; i < alt.size(); ++i) extend(s_mov_lit(std::uint8_t(16 + i), alt[i])); + std::size_t join_pc = words.size(); + words[br_else] = 0xBF84'0000u | (std::uint32_t(else_pc - br_else - 1) & 0xFFFF); + words[br_join] = 0xBF82'0000u | (std::uint32_t(join_pc - br_join - 1) & 0xFFFF); + extend(image_sample_lz); + extend(buf_store); + words.push_back(0xBF81'0000u); // s_endpgm + + NativeProgram native; + native.stage = HwStage::Cs; + native.wave64 = false; + native.vgprs = 8; + native.layout = {root_param(RootType::Table(), 0, 1, 0, 0, 0), root_param(RootType::Constants(), 0, 1, 0, 1, 1)}; + native.used = {used_resource(ResourceType::Srv(), RootType::Table(), 0, 0, 0, 8, 0, 0), + used_resource(ResourceType::Uav(), RootType::Table(), 16, 0, 0, 4, 0, 0)}; + native.io = compute_io(2 << 1, {1, 1, 1}); + native.code = le_bytes(words); + + vs::ir::Program p = vs::ir::build(native.code, false, native.vgprs); + vs::structure::Structured st = vs::structure::structure(p); + vs::resource::Resources res = vs::resource::track(p, native.layout, native.stage, &st); + vs::io::Io io = vs::io::raise(p, native); + Lowered lowered; + try { + lowered = vs::lower::lower(parts_of(native, p, st, io, res)); + } catch (const ShaderError& e) { + fail(std::string(case_name) + ": lower failed: " + e.to_string()); + } + + std::vector<vs::StaticSampler> static_samplers; + for (const auto& w : lowered.samplers) static_samplers.push_back(vs::StaticSampler::from_words(w)); + HostShader shader = host_shader(std::move(lowered), {}, std::move(static_samplers)); + validate(shader); + + std::lock_guard one(one_at_a_time()); + const std::pair<const char*, bool> devices[] = {{"hardware", false}, {"warp", true}}; + for (auto [label, warp] : devices) { + auto host = new_host(warp); + if (!host) continue; + std::string why; + auto pipe = compute_pipeline(*host, shader, &why); + if (!pipe) fail(std::string(case_name) + "/" + label + ": compute_pipeline failed: " + why); + for (std::uint32_t branch : {0u, 1u}) { + std::vector<std::uint32_t> ud(std::max<std::uint32_t>(shader.user_data_dwords(), 1), 0); + for (const UserData& u : shader.user_data) { + if (u.root == RootType::Table() && u.slot == 0) + ud[u.index] = 0; + else if (u.root == RootType::Constants() && u.slot == 1) + ud[u.index] = branch; + else + fail("unexpected user data"); + } + const Texel texels[] = {{1.0f, 0.0f, 0.0f, 1.0f}}; + const View views[] = {texture(1, 1, texels), texture(1, 1, texels), raw_uav(1)}; + auto out = dispatch(*host, *pipe, std::move(ud), views, {}, {1, 1, 1}, + std::string(case_name) + "/" + label); + float got = f32_from_bits(out[0][0]); + require(got == 1.0f, std::string(case_name) + "/" + label + " branch=" + std::to_string(branch)); + } + } + } +} + +} // namespace + +int main() { + guarded("lanes_sample_the_texture_their_if_else_arm_chose", lanes_sample_the_texture_their_if_else_arm_chose); + guarded("lanes_sample_the_texture_their_arm_loaded_or_picked", lanes_sample_the_texture_their_arm_loaded_or_picked); + guarded("lanes_load_from_the_buffer_their_nested_arms_chose", lanes_load_from_the_buffer_their_nested_arms_chose); + guarded("lanes_sample_the_entry_their_offset_names_in_the_console_waterfall", + lanes_sample_the_entry_their_offset_names_in_the_console_waterfall); + guarded("lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx", + lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx); + guarded("immediate_sampler_chosen_by_control_flow", immediate_sampler_chosen_by_control_flow); + return test_util::finish("lower_waterfall_test"); +} diff --git a/tests/x2w_shader/emit/lower_wave64_test.cpp b/tests/x2w_shader/emit/lower_wave64_test.cpp new file mode 100644 index 0000000000..d77589b029 --- /dev/null +++ b/tests/x2w_shader/emit/lower_wave64_test.cpp @@ -0,0 +1,640 @@ +// Port of the upstream Rust module emit/wave64_tests.rs, in Rust order. +// +// A console wave64 compute program on a host of 32-lane waves: a wave reduction inside a per-lane +// branch, with that branch taken wave-wide (structure::structure_wide) so that the two host waves +// can exchange their halves inside it. Lowered, validated by dxil.dll when present, and run on the +// host GPU when it takes waves of 32. + +#include "lower_card_util.h" +#include "x2w_shader/emit/wave.h" // WAVE_OR_V7_TO_S7 + +using namespace card; + +namespace { + +constexpr std::uint32_t S_ENDPGM = 0xBF81'0000; + +// Rust HashSet<usize> of branch blocks: structure_wide takes an ordered set here. +using Wide = std::set<std::size_t>; + +NativeProgram native_of(std::span<const std::uint32_t> body, bool wave64, std::uint32_t threads); + +// A wave64 compute program of 64 threads (one console wave; the thread index in v0) with 4 root +// constants in s0..s3 and a raw UAV's descriptor in s[8:11], then `body`. +NativeProgram native(std::span<const std::uint32_t> body) { return native_of(body, true, 64); } + +// 64 threads in one console wave. Each thread t holds the bit `1 << (t >> 1)`; the threads below +// s0 (a root constant) OR theirs over the wave inside `if (t < s0) { ... }` and store the result +// to dword 0 of the raw UAV. `skip`: the branch past the body when no thread is below s0: +// `s_cbranch_execz`, or `s_cbranch_scc0` on the SCC `s_and_saveexec` sets ("some lane is left"). +NativeProgram program(std::uint32_t skip) { + std::vector<std::uint32_t> words = { + 0x7E0A'0281, // v_mov_b32 v5, 1 + 0x2C0C'0081, // v_lshrrev_b32 v6, 1, v0 + 0x340E'0B06, // v_lshlrev_b32 v7, v6, v5 + 0x7D88'0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C'246A, // s_and_saveexec_b64 s[12:13], vcc + skip | 23, // the branch to the restore of EXEC + }; + words.insert(words.end(), vs::wave::WAVE_OR_V7_TO_S7.begin(), vs::wave::WAVE_OR_V7_TO_S7.end()); + for (std::uint32_t w : { + 0x7E00'0207u, // v_mov_b32 v0, s7 + 0x38u << 26 | 0x1Cu << 18, + 0x80u << 24 | 2u << 16, // buffer_store_dword v0, off, s[8:11], 0 + 0xBEFE'040Cu, // s_mov_b64 exec, s[12:13] + }) + words.push_back(w); + return native(words); +} + +// The same for a console of 32-lane waves when `wave64` is not set, with `threads` threads. +NativeProgram native_of(std::span<const std::uint32_t> body, bool wave64, std::uint32_t threads) { + std::vector<std::uint32_t> words = { + 0xBE85'0380, // s_mov_b32 s5, 0 + 0x3Du << 26 | 0x02u << 18 | 8u << 6 | 2u, + 125u << 25, // s_load_dwordx4 s[8:11], s[4:5], 0 + }; + words.insert(words.end(), body.begin(), body.end()); + words.push_back(S_ENDPGM); + NativeProgram n; + n.stage = HwStage::Cs; + n.wave64 = wave64; + n.vgprs = 16; + n.layout = {root_param(RootType::Constants(), 0, 4, 0, 0, 0), root_param(RootType::Table(), 0, 1, 0, 4, 1)}; + n.used = {used_resource(ResourceType::Uav(), RootType::Table(), 0, 0, 0, 4, 4, 1)}; + n.io = compute_io(5 << 1, {threads, 1, 1}); // 5 user SGPRs: s0..s4 + n.code = le_bytes(words); + return n; +} + +HostShader lowered_counted(const NativeProgram& native, const vs::ir::Program& p, const Wide& wide, + std::uint32_t host_wave, bool counted) { + vs::structure::Structured st = vs::structure::structure_wide(p, wide); + vs::resource::Resources res = vs::resource::track(p, native.layout, native.stage, &st); + vs::io::Io io = vs::io::raise(p, native); + Lowered lowered; + { + HostWave was(host_wave); + lowered = vs::lower::lower_counted(parts_of(native, p, st, io, res), counted); // throws ShaderError + } + return host_shader(std::move(lowered), res.root_indexed_views); +} + +// `lowered` for a host whose waves have at most `host_wave` lanes. Throws ShaderError. +HostShader lowered_on(const NativeProgram& native, const vs::ir::Program& p, const Wide& wide, + std::uint32_t host_wave) { + return lowered_counted(native, p, wide, host_wave, false); +} + +// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide. +HostShader lowered(const NativeProgram& native, const vs::ir::Program& p, const Wide& wide) { + return lowered_on(native, p, wide, 32); +} + +// The wave OR's words with v_add_f16 for v_or_b32 (opcode 50 for 28). +void extend_wave_sum(std::vector<std::uint32_t>& words) { + for (std::uint32_t w : vs::wave::WAVE_OR_V7_TO_S7) + words.push_back(w >> 25 == 28 ? (w & 0x01FF'FFFFu) | 50u << 25 : w); +} + +// The half's float (normal numbers; with `zero`, 0 is +0). +float wide_half(std::uint16_t h) { + return f32_from_bits(((std::uint32_t(h >> 10) + 112) << 23) | (std::uint32_t(h & 0x3FF) << 13)); +} + +// To the nearest half, ties to even (normal numbers). +std::uint16_t narrow_half(float f) { + std::uint32_t b = f32_bits(f); + std::uint32_t h = (((b >> 23) - 112) << 10) | ((b >> 13) & 0x3FF); + std::uint32_t rest = b & 0x1FFF; + return static_cast<std::uint16_t>(h + std::uint32_t(rest > 0x1000 || (rest == 0x1000 && (h & 1) == 1))); +} + +// The same, 0 for +0. +float wide_half_or_zero(std::uint16_t h) { return h == 0 ? 0.0f : wide_half(h); } +std::uint16_t narrow_half_or_zero(float f) { return f == 0.0f ? 0 : narrow_half(f); } + +// Pairs, then pairs of pairs, ... (Rust `tree.chunks(2).map(|c| add(c[0], c[1]))` to one). +template <class Add> +std::uint16_t tree_of(std::vector<std::uint16_t> tree, Add add) { + while (tree.size() > 1) { + std::vector<std::uint16_t> next; + for (std::size_t i = 0; i + 1 < tree.size(); i += 2) next.push_back(add(tree[i], tree[i + 1])); + tree = std::move(next); + } + return tree[0]; +} + +// Dword 0 of the raw UAV after one group, root constants from `ud`. +std::vector<std::vector<std::uint32_t>> dispatch_one(const Host& host, const Pipeline& pipe, + std::vector<std::uint32_t> ud) { + const View views[] = {raw_uav(1)}; + return dispatch(host, pipe, std::move(ud), views, {}, {1, 1, 1}); +} + +// ---- rs:148 ------------------------------------------------------------------------------------- +void a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { + x2w::vs::lower::test::set_dump_name( + "emit__wave64_tests__a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit"); + // thread t holds the 16-bit float with bits 0x3C00 + 37 t (1.0 and up, with odd mantissas, so + // that additions round); all of them store the wave's sum + std::vector<std::uint32_t> words = { + 0x340C'0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E'0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E'0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E'0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E'0EFF, + 0x0000'3C00, // v_add_nc_u32 v7, 0x3c00, v7 + }; + extend_wave_sum(words); + for (std::uint32_t w : { + 0x7E00'0207u, // v_mov_b32 v0, s7 + 0x38u << 26 | 0x1Cu << 18, + 0x80u << 24 | 2u << 16, // buffer_store_dword v0, off, s[8:11], 0 + }) + words.push_back(w); + NativeProgram n = native(words); + vs::ir::Program p = vs::ir::build(n.code, n.wave64, n.vgprs); + require(count_insts(p, "v_add_f16") == 6, "six v_add_f16"); + HostShader shader = lowered(n, p, {}); + validate(shader); + // the console's sum: lanes 2k and 2k+1, then pairs, ... each addition rounded to 16 bits (to + // nearest, ties to even); values here are normal numbers + auto add = [](std::uint16_t a, std::uint16_t b) { return narrow_half(wide_half(a) + wide_half(b)); }; + std::vector<std::uint16_t> terms; + for (std::uint16_t t = 0; t < 64; ++t) terms.push_back(static_cast<std::uint16_t>(0x3C00 + 37 * t)); + std::uint16_t tree = tree_of(terms, add); + std::uint16_t in_a_row = terms[0]; + for (std::size_t i = 1; i < terms.size(); ++i) in_a_row = add(in_a_row, terms[i]); + require(tree != in_a_row, "these terms tell the tree from another order"); + std::lock_guard one(one_at_a_time()); + auto host = new_host(false); + if (!host) { + std::fprintf(stderr, "no SM 6.6 hardware device; not run\n"); + return; + } + std::string why; + auto pipe = compute_pipeline(*host, shader, &why); + if (!pipe) { + std::fprintf(stderr, "the hardware device does not take this program (waves of 32?): %s; not run\n", + why.c_str()); + return; + } + std::vector<std::uint32_t> ud(std::max<std::uint32_t>(shader.user_data_dwords(), 1), 0); + auto out = dispatch_one(*host, *pipe, std::move(ud)); + // (the high half is lane 0's term's: zero) + require(out[0][0] == std::uint32_t(tree), "tree " + hex(tree) + ", in a row " + hex(in_a_row)); + std::fprintf(stderr, "ran on the hardware device: the sum %s of the console's tree\n", hex(tree).c_str()); +} + +// `native` for a host of 64-lane waves. +HostShader on_64_lanes(const NativeProgram& native, const vs::ir::Program& p) { + vs::structure::Structured st = vs::structure::structure(p); + vs::resource::Resources res = vs::resource::track(p, native.layout, native.stage, &st); + vs::io::Io io = vs::io::raise(p, native); + Lowered lowered; + { + HostWave was(64); + lowered = vs::lower::lower(parts_of(native, p, st, io, res)); + } + require(lowered.wave_size == std::optional<std::uint32_t>(64), "wave_size == Some(64)"); + HostShader shader = host_shader(std::move(lowered), res.root_indexed_views); + validate(shader); + return shader; +} + +// Dword 0 of the UAV after `shader` ran with root constants `constants`; none without a device +// that takes it. +std::optional<std::uint32_t> dispatched(const HostShader& shader, std::span<const std::uint32_t> constants) { + std::lock_guard one(one_at_a_time()); + auto host = new_host(false); + if (!host) { + std::fprintf(stderr, "no SM 6.6 hardware device; not run\n"); + return std::nullopt; + } + std::string why; + auto pipe = compute_pipeline(*host, shader, &why); + if (!pipe) { + std::fprintf(stderr, "the hardware device does not take this program (waves of 64?): %s; not run\n", + why.c_str()); + return std::nullopt; + } + std::vector<std::uint32_t> ud(std::max<std::uint32_t>(shader.user_data_dwords(), 1), 0); + for (const UserData& u : shader.user_data) + if (u.root == RootType::Constants()) ud[u.index] = u.dword < constants.size() ? constants[u.dword] : 0; + auto out = dispatch_one(*host, *pipe, std::move(ud)); + return out[0][0]; +} + +// ---- rs:222 ------------------------------------------------------------------------------------- +// "Some lane is left" of a mask operation as a number: an upscaler's programs wait for other +// groups in a loop that ends when every lane saw its flag, or after enough rounds: both tests +// become -1 or 0 and SCC of `timeout | ~waiting` ends it. +void some_lane_of_a_mask_is_a_number_the_whole_wave_agrees_on() { + x2w::vs::lower::test::set_dump_name("emit__wave64_tests__some_lane_of_a_mask_is_a_number_the_whole_wave_agrees_on"); + const std::uint32_t body[] = { + 0xD765'0001, + 0x0001'00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0xD766'0001, + 0x0002'02C1, // v_mbcnt_hi_u32_b32 v1, -1, v1 + 0x7D84'0200, // v_cmp_eq_u32 vcc, s0, v1 + 0x8792'7E6A, // s_and_b64 s[18:19], vcc, exec + 0x8592'80C1, // s_cselect_b64 s[18:19], -1, 0 + 0xBF09'8501, // s_cmp_ge_u32 s1, 5 + 0x8594'80C1, // s_cselect_b64 s[20:21], -1, 0 + 0x8B92'1214, // s_orn2_b64 s[18:19], s[20:21], s[18:19] + 0x8506'8081, // s_cselect_b32 s6, 1, 0 + 0x7E04'0206, // v_mov_b32 v2, s6 + 0xE070'0000, + 0x8002'0200, // buffer_store_dword v2, off, s[8:11], 0 + }; + NativeProgram n = native(body); + vs::ir::Program p = vs::ir::build(n.code, n.wave64, n.vgprs); + HostShader shader = on_64_lanes(n, p); + // (lane s0 waits, if there is one; s1 rounds) + const std::array<std::uint32_t, 3> cases[] = {{0, 0, 0}, {37, 4, 0}, {63, 4, 0}, + {64, 0, 1}, {37, 5, 1}, {64, 9, 1}}; + for (auto [wait, rounds, done] : cases) { + const std::uint32_t constants[] = {wait, rounds}; + auto out = dispatched(shader, constants); + if (!out) return; + require(*out == done, "lane " + std::to_string(wait) + " after " + std::to_string(rounds) + " rounds"); + } +} + +// ---- rs:328 ------------------------------------------------------------------------------------- +// The same sum inside `if (t >= s0) { ... }` on a host of 64-lane waves: the lanes below s0 are +// elsewhere, and count as +0 in the console's tree. +void a_sum_of_halves_where_not_every_lane_runs_on_a_wave_of_64() { + x2w::vs::lower::test::set_dump_name( + "emit__wave64_tests__a_sum_of_halves_where_not_every_lane_runs_on_a_wave_of_64"); + std::vector<std::uint32_t> words = { + 0x340C'0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E'0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E'0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E'0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E'0EFF, + 0x0000'3C00, // v_add_nc_u32 v7, 0x3c00, v7 + 0x7D86'0000, // v_cmp_le_u32 vcc, s0, v0 + 0xBE8C'246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88'0000 | 23, // s_cbranch_execz to the restore of EXEC + }; + extend_wave_sum(words); + for (std::uint32_t w : { + 0x7E00'0207u, // v_mov_b32 v0, s7 + 0x38u << 26 | 0x1Cu << 18, + 0x80u << 24 | 2u << 16, // buffer_store_dword v0, off, s[8:11], 0 + 0xBEFE'040Cu, // s_mov_b64 exec, s[12:13] + }) + words.push_back(w); + NativeProgram n = native(words); + vs::ir::Program p = vs::ir::build(n.code, n.wave64, n.vgprs); + HostShader shader = on_64_lanes(n, p); + auto add = [](std::uint16_t a, std::uint16_t b) { + return narrow_half_or_zero(wide_half_or_zero(a) + wide_half_or_zero(b)); + }; + for (std::uint32_t from : {0u, 1u, 5u, 31u, 32u, 37u, 63u}) { + std::vector<std::uint16_t> terms; + for (std::uint16_t t = 0; t < 64; ++t) + terms.push_back(std::uint32_t(t) < from ? 0 : static_cast<std::uint16_t>(0x3C00 + 37 * t)); + std::uint16_t tree = tree_of(terms, add); + const std::uint32_t constants[] = {from}; + auto out = dispatched(shader, constants); + if (!out) return; + require(*out == std::uint32_t(tree), "lanes from " + std::to_string(from)); + } +} + +// Runs `shader` on the hardware device with the root constants `s0`, `s1` and gives dword 0 of the +// UAV; none (and a line) without a device that takes it. +std::optional<std::uint32_t> on_the_card(const HostShader& shader, std::array<std::uint32_t, 2> constants) { + auto host = new_host(false); + if (!host) { + std::fprintf(stderr, "no SM 6.6 hardware device; not run\n"); + return std::nullopt; + } + auto pipe = compute_pipeline(*host, shader); + if (!pipe) { + std::fprintf(stderr, "the hardware device does not take this program; not run\n"); + return std::nullopt; + } + std::vector<std::uint32_t> ud(std::max<std::uint32_t>(shader.user_data_dwords(), 1), 0); + for (const UserData& u : shader.user_data) + if (u.root == RootType::Constants() && u.slot == 0 && u.dword <= 1) ud[u.index] = constants[u.dword]; + auto out = dispatch_one(*host, *pipe, std::move(ud)); + return out[0][0]; +} + +// ---- rs:378 ------------------------------------------------------------------------------------- +// The console's 16-bit wave sum where the lanes at or past s0 have left the program (a thread past +// the end of the data): on the console they add +0, and after each step of the tree they hold +// their run's partial sum all the same. On a host of 64-lane waves (AMD) the lanes that are here +// read each partner run's sum from a lane of it that is here. +void a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() { + x2w::vs::lower::test::set_dump_name( + "emit__wave64_tests__a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit"); + std::vector<std::uint32_t> words = { + 0x7DA8'0000, // v_cmpx_gt_u32 exec, s0, v0: the lanes below s0 stay + 0, // s_cbranch_execz to the end (filled in below) + 0x340C'0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E'0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E'0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E'0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E'0EFF, + 0x0000'3C00, // v_add_nc_u32 v7, 0x3c00, v7 + }; + extend_wave_sum(words); + for (std::uint32_t w : { + 0x7E00'0207u, // v_mov_b32 v0, s7 + 0x38u << 26 | 0x1Cu << 18, + 0x80u << 24 | 2u << 16, // buffer_store_dword v0, off, s[8:11], 0 + }) + words.push_back(w); + // past every word after it, to the program's end + words[1] = 0xBF88'0000u | (static_cast<std::uint32_t>(words.size()) - 2); + NativeProgram n = native(words); + vs::ir::Program p = vs::ir::build(n.code, n.wave64, n.vgprs); + HostShader shader = lowered_on(n, p, {}, 64); + validate(shader); + auto add = [](std::uint16_t a, std::uint16_t b) { + return narrow_half_or_zero(wide_half_or_zero(a) + wide_half_or_zero(b)); + }; + std::lock_guard one(one_at_a_time()); + bool ran = false; + for (std::uint32_t stay : {64u, 63u, 40u, 33u, 32u, 17u, 5u, 1u}) { + std::vector<std::uint16_t> terms; + for (std::uint32_t t = 0; t < 64; ++t) terms.push_back(t < stay ? static_cast<std::uint16_t>(0x3C00 + 37 * t) : 0); + std::uint16_t tree = tree_of(terms, add); + auto got = on_the_card(shader, {stay, 0}); + if (!got) return; + ran = true; + // (the high half is lane 0's term's: zero) + require(*got == std::uint32_t(tree), std::to_string(stay) + " lanes stay: got " + hex(*got) + + ", the console's tree " + hex(tree)); + } + if (ran) std::fprintf(stderr, "ran on the hardware device: the console's tree with lanes gone, in every case\n"); +} + +// ---- rs:448 ------------------------------------------------------------------------------------- +// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 (0x4000) +// is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The host's `f32tof16` +// may give 0x4201 (toward zero); with X2W_SHADERCFG_F16_NEAREST=1 the translation gives the console's +// whatever the host does. +void a_16_bit_sum_rounds_to_nearest_when_asked_to() { + x2w::vs::lower::test::set_dump_name("emit__wave64_tests__a_16_bit_sum_rounds_to_nearest_when_asked_to"); + const std::uint32_t words[] = { + 0x7E0E'02FF, + 0x0000'3C03, // v_mov_b32 v7, 0x3c03 + 0x7E0C'02FF, + 0x0000'4000, // v_mov_b32 v6, 0x4000 + 0x6400'0D07, // v_add_f16 v0, v7, v6 + 0x38u << 26 | 0x1Cu << 18, + 0x80u << 24 | 2u << 16, // buffer_store_dword v0, off, s[8:11], 0 + }; + NativeProgram n = native(words); + vs::ir::Program p = vs::ir::build(n.code, n.wave64, n.vgprs); + require(count_insts(p, "v_add_f16") > 0, "a v_add_f16"); + std::lock_guard one(one_at_a_time()); + for (bool nearest : {false, true}) { + HostShader shader; + { + F16Nearest was(nearest); + shader = lowered(n, p, {}); + } + validate(shader); + auto host = new_host(false); + if (!host) { + std::fprintf(stderr, "no SM 6.6 hardware device; not run\n"); + return; + } + auto pipe = compute_pipeline(*host, shader); + if (!pipe) { + std::fprintf(stderr, "the hardware device does not take this program; not run\n"); + return; + } + std::vector<std::uint32_t> ud(std::max<std::uint32_t>(shader.user_data_dwords(), 1), 0); + auto out = dispatch_one(*host, *pipe, std::move(ud)); + std::uint32_t got = out[0][0] & 0xFFFF; + std::fprintf(stderr, "v_add_f16 0x3c03 + 0x4000 on the hardware device, nearest %s: %s\n", + nearest ? "true" : "false", hex(got).c_str()); + if (nearest) + require(got == 0x4202, hex(got)); + else + require(got == 0x4201 || got == 0x4202, hex(got)); + } +} + +// ---- rs:507 ------------------------------------------------------------------------------------- +void a_wave_or_inside(std::uint32_t skip, const char* name) { + NativeProgram n = program(skip); + vs::ir::Program p = vs::ir::build(n.code, n.wave64, n.vgprs); + std::optional<std::size_t> found; + for (std::size_t b = 0; b < p.blocks.size() && !found; ++b) + if (!p.blocks[b].insts.empty() && p.blocks[b].insts.back().name() == name) found = b; + require(found.has_value(), "the branch"); + std::size_t branch = *found; + // per lane, the two host waves cannot meet inside the branch + vs::lower::take_needs(); + try { + lowered(n, p, {}); + fail("lowered per lane"); + } catch (const ShaderError& e) { + require(is_unsupported(e, "a wave reduction where not every lane runs"), e.to_string()); + } + // ... and the lowering names the block, around which that branch is the one to widen + std::vector<std::size_t> needs = vs::lower::take_needs(); + vs::structure::Structured st = vs::structure::structure(p); + require(vs::lower::branches_around(st, needs) == std::optional<std::vector<std::size_t>>({branch}), + "branches_around == Some([branch])"); + // (taken, past the body, when every lane's bit is clear) + require(st.wave_any[branch] == std::optional<bool>(false), "wave_any[branch] == Some(false)"); + // wave-wide, every lane runs the reduction (EXEC stays a guard on what it does there) + const Wide wide = {branch}; + vs::structure::Structured st_wide = vs::structure::structure_wide(p, wide); + require(p.blocks[branch].exit.is_branch(), "unreachable"); + std::size_t inside = p.blocks[branch].exit.not_taken; + bool guarded_inside = false; + for (const auto& g : st_wide.guards[inside]) guarded_inside |= g.has_value(); + require(guarded_inside, "a guard inside"); + HostShader shader = lowered(n, p, wide); + validate(shader); + // On a GPU that takes waves of 32 (two host waves for the console's one): the OR is of both + // halves, whichever half's lanes take the branch. + std::lock_guard one(one_at_a_time()); + auto host = new_host(false); + if (!host) { + std::fprintf(stderr, "no SM 6.6 hardware device; not run\n"); + return; + } + std::string why; + auto pipe = compute_pipeline(*host, shader, &why); + if (!pipe) { + std::fprintf(stderr, "the hardware device does not take this program (waves of 32?): %s; not run\n", + why.c_str()); + return; + } + // (threads below s0 take the branch; thread t gives bit t >> 1) + const std::pair<std::uint32_t, std::uint32_t> cases[] = { + {64, 0xFFFF'FFFF}, {40, 0x000F'FFFF}, {33, 0x0001'FFFF}, {10, 0x1F}, {1, 1}}; + for (auto [below, expected] : cases) { + std::vector<std::uint32_t> ud(std::max<std::uint32_t>(shader.user_data_dwords(), 1), 0); + for (const UserData& u : shader.user_data) + if (u.root == RootType::Constants() && u.slot == 0 && u.dword == 0) ud[u.index] = below; + auto out = dispatch_one(*host, *pipe, std::move(ud)); + require(out[0][0] == expected, std::string(name) + ": " + std::to_string(below) + " threads in the branch"); + } + std::fprintf(stderr, "ran on the hardware device (%s): the OR of both halves in every case\n", name); +} + +void a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide() { + x2w::vs::lower::test::set_dump_name( + "emit__wave64_tests__a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide"); + const std::pair<std::uint32_t, const char*> cases[] = {{0xBF88'0000, "s_cbranch_execz"}, + {0xBF84'0000, "s_cbranch_scc0"}}; + for (auto [skip, name] : cases) a_wave_or_inside(skip, name); +} + +// ---- rs:618 ------------------------------------------------------------------------------------- +// A 32-lane console wave. A register holds a lane mask on one path (the lanes below s0) and a +// number on the other, and is read as a number after the join when a stack holds both masks and node numbers. The mask +// arrives as the ballot of its lanes. +void a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is() { + x2w::vs::lower::test::set_dump_name( + "emit__wave64_tests__a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is"); + const std::uint32_t words[] = { + 0x7D88'0000, // v_cmp_gt_u32 vcc_lo, s0, v0 + 0xBE94'036A, // s_mov_b32 s20, vcc_lo + 0xBF06'8001, // s_cmp_eq_u32 s1, 0 + 0xBF85'0001, // s_cbranch_scc1 over the next + 0xBE94'0385, // s_mov_b32 s20, 5 + 0x7E00'0214, // v_mov_b32 v0, s20 + 0x38u << 26 | 0x1Cu << 18, + 0x80u << 24 | 2u << 16, // buffer_store_dword v0, off, s[8:11], 0 + }; + NativeProgram n = native_of(words, false, 32); + vs::ir::Program p = vs::ir::build(n.code, n.wave64, n.vgprs); + HostShader shader = lowered(n, p, {}); + validate(shader); + std::lock_guard one(one_at_a_time()); + const std::array<std::uint32_t, 3> cases[] = {{32, 0, 0xFFFF'FFFF}, {10, 0, 0x3FF}, {0, 0, 0}, {10, 1, 5}}; + for (auto [below, other, expected] : cases) { + auto got = on_the_card(shader, {below, other}); + if (!got) return; + require(*got == expected, + std::to_string(below) + " lanes in the mask, s1 = " + std::to_string(other)); + } + std::fprintf(stderr, "ran on the hardware device: the mask's bits, or the number\n"); +} + +// ---- rs:650 ------------------------------------------------------------------------------------- +// A 32-lane console wave. `if (t < s0) { ... SCC = (s1 == 7) }` and a branch on SCC after the +// join: the skip brings the SCC of `s_and_saveexec` ("some lane is left") along. On the console the +// skip is taken by the wave, so with some lane inside every lane sees the inner test. A lane that +// skipped on its own would see "some lane is left" instead: refused per lane, right with the +// branch taken wave-wide. Lane 31 stores what it saw. +void scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() { + x2w::vs::lower::test::set_dump_name( + "emit__wave64_tests__scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide"); + const std::uint32_t words[] = { + 0x7D88'0000, // v_cmp_gt_u32 vcc_lo, s0, v0 + 0xBE8D'3C6A, // s_and_saveexec_b32 s13, vcc_lo + 0xBF88'0001, // s_cbranch_execz over the next + 0xBF06'8701, // s_cmp_eq_u32 s1, 7 + 0xBEFE'030D, // s_mov_b32 exec_lo, s13 + 0xBF85'0002, // s_cbranch_scc1 to "seven" + 0x7E0A'0281, // v_mov_b32 v5, 1 + 0xBF82'0001, // s_branch over the next + 0x7E0A'0282, // seven: v_mov_b32 v5, 2 + 0x7DA4'009F, // v_cmpx_eq_u32 exec_lo, 31, v0 + 0x38u << 26 | 0x1Cu << 18, + 0x80u << 24 | 2u << 16 | 5u << 8, // buffer_store_dword v5, off, s[8:11], 0 + }; + NativeProgram n = native_of(words, false, 32); + vs::ir::Program p = vs::ir::build(n.code, n.wave64, n.vgprs); + std::optional<std::size_t> found; + for (std::size_t b = 0; b < p.blocks.size() && !found; ++b) + if (!p.blocks[b].insts.empty() && p.blocks[b].insts.back().name() == "s_cbranch_execz") found = b; + require(found.has_value(), "the skip"); + std::size_t branch = *found; + vs::lower::take_needs(); + try { + lowered(n, p, {}); + fail("lowered per lane"); + } catch (const ShaderError& e) { + require(is_unsupported(e, "a lane mask read as data"), e.to_string()); + } + vs::structure::Structured st = vs::structure::structure(p); + require(vs::lower::branches_around(st, vs::lower::take_needs()) == std::optional<std::vector<std::size_t>>({branch}), + "branches_around == Some([branch])"); + HostShader shader = lowered(n, p, Wide{branch}); + validate(shader); + std::lock_guard one(one_at_a_time()); + // (lanes below s0 inside, s1) -> what lane 31 stores: 2 if SCC was set at the branch + const std::array<std::uint32_t, 3> cases[] = {{0, 7, 1}, {10, 7, 2}, {10, 3, 1}, {32, 3, 1}, {32, 7, 2}}; + for (auto [below, s1, expected] : cases) { + auto got = on_the_card(shader, {below, s1}); + if (!got) return; + require(*got == expected, std::to_string(below) + " lanes inside, s1 = " + std::to_string(s1)); + } + std::fprintf(stderr, + "ran on the hardware device: the inner test's SCC for every lane once some lane is inside\n"); +} + +// ---- rs:700 ------------------------------------------------------------------------------------- +// A dispatch counted in threads: of the last group only the lanes below the count store (after +// upstream commit bc3cd4b0). +void the_lanes_past_a_count_of_threads_do_not_run() { + x2w::vs::lower::test::set_dump_name("emit__wave64_tests__the_lanes_past_a_count_of_threads_do_not_run"); + // Each lane that runs adds 1 to counter[local x]. + const std::uint32_t body[] = { + 0x3402'0082, // v_lshlrev_b32 v1, 2, v0 + 0x7e04'0281, // v_mov_b32 v2, 1 + 0xe0c8'1000, 0x8002'0201, // buffer_atomic_add v2, v1, s[8:11], 0 offen + }; + NativeProgram n = native(body); + vs::ir::Program p = vs::ir::build(n.code, n.wave64, n.vgprs); + HostShader shader = lowered_counted(n, p, {}, 64, true); + const UserData* limit = nullptr; + for (const UserData& u : shader.user_data) + if (!limit && u.root == RootType::Other(vs::USER_DISPATCH_THREADS_X)) limit = &u; + require(limit != nullptr, "the thread count's user data"); + require(limit->slot == 0 && limit->dword == 64, "(slot, dword) == (0, 64)"); + std::lock_guard one(one_at_a_time()); + auto host = new_host(true); + if (!host) return; + auto pipe = compute_pipeline(*host, shader); + if (!pipe) return; + for (std::uint32_t count : {0u, 1u, 7u, 63u, 64u, 65u, 74u, 77u, 127u, 128u}) { + std::vector<std::uint32_t> constants(shader.user_data_dwords(), 0); + constants[limit->index] = count; + const View views[] = {raw_uav(68)}; + auto result = dispatch(*host, *pipe, std::move(constants), views, {}, {2, 1, 1}); + std::uint32_t active = count == 0 ? 128 : count; + for (std::uint32_t i = 0; i < 64 && i < result[0].size(); ++i) { + std::uint32_t want = std::uint32_t(i < active) + std::uint32_t(i + 64 < active); + require(result[0][i] == want, "count " + std::to_string(count) + ", word " + std::to_string(i)); + } + } +} + +} // namespace + +int main() { + guarded("a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit", + a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit); + guarded("some_lane_of_a_mask_is_a_number_the_whole_wave_agrees_on", + some_lane_of_a_mask_is_a_number_the_whole_wave_agrees_on); + guarded("a_sum_of_halves_where_not_every_lane_runs_on_a_wave_of_64", + a_sum_of_halves_where_not_every_lane_runs_on_a_wave_of_64); + guarded("a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit", + a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit); + guarded("a_16_bit_sum_rounds_to_nearest_when_asked_to", a_16_bit_sum_rounds_to_nearest_when_asked_to); + guarded("a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide", + a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide); + guarded("a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is", + a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is); + guarded("scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide", + scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide); + guarded("the_lanes_past_a_count_of_threads_do_not_run", the_lanes_past_a_count_of_threads_do_not_run); + return test_util::finish("lower_wave64_test"); +} diff --git a/tests/x2w_shader/emit/mod_test.cpp b/tests/x2w_shader/emit/mod_test.cpp new file mode 100644 index 0000000000..bbcb66d4af --- /dev/null +++ b/tests/x2w_shader/emit/mod_test.cpp @@ -0,0 +1,1266 @@ +// Port of the tests in the upstream Rust module emit/mod.rs (#[cfg(test)] mod tests, rs:956), in Rust order. +// +// Each Rust #[test] is a function here; main runs them all, each under its own dump name +// (lower::test::set_dump_name, "emit__tests__<name>", as lower_test.cpp names its own). A test +// that throws (a Rust panic or `.unwrap()` of an error) counts as failed and the others still run. +// +// Rust `.unwrap()` of a ShaderError is a panic, `?` a returned error: where a test looks at an +// error (is_err, unwrap_err), the steps Rust unwraps go through unwrap() below, which turns a +// ShaderError into std::logic_error so that it fails the test instead of passing as the error. +// +// The GPU tests (Rust #[cfg(windows)]) skip, and say so, without dxc.exe / dxil.dll / an SM 6.6 +// device as the Rust ones do. The upstream valu_tests::ONE_AT_A_TIME lock is not needed: the tests of +// this executable run one after another on one thread. + +#include <windows.h> + +#include <algorithm> +#include <array> +#include <bit> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <exception> +#include <filesystem> +#include <fstream> +#include <iterator> +#include <optional> +#include <span> +#include <stdexcept> +#include <string> +#include <string_view> +#include <utility> +#include <vector> + +#include "test_util.h" +#include "x2w_shader/dxbc.h" +#include "x2w_shader/emit/bitcode.h" +#include "x2w_shader/emit/container.h" +#include "x2w_shader/emit/emit.h" +#include "x2w_shader/emit/host.h" +#include "x2w_shader/emit/lower.h" +#include "x2w_shader/emit/opt.h" +#include "x2w_shader/emit/sampler.h" +#include "x2w_shader/emit/settings.h" +#include "x2w_shader/emit/shader.h" +#include "x2w_shader/emit/validator.h" +#include "x2w_shader/error.h" +#include "x2w_shader/io.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/native.h" +#include "x2w_shader/resource.h" +#include "x2w_shader/structure.h" + +namespace fs = std::filesystem; +namespace vs = x2w::vs; +using vs::HostShader; +using vs::ShaderError; +using vs::container::SigElement; +using vs::dxbc::Bytes; +using vs::dxbc::Container; +using vs::dxbc::FourCC; +using vs::native::ComputeIo; +using vs::native::HwStage; +using vs::native::MeshIo; +using vs::native::NativeProgram; +using vs::native::PsInput; +using vs::native::PsIo; +using vs::native::ResourceType; +using vs::native::RootParam; +using vs::native::RootType; +using vs::native::UsedResource; +using vs::native::Usage; +using vs::validator::Validator; + +// CHECK with a message printed when it fails (Rust assert!'s format arguments). +#define CHECK_MSG(expr, msg) \ + do { \ + const bool check_ok_ = static_cast<bool>(expr); \ + if (!check_ok_) std::fprintf(stderr, " %s\n", std::string(msg).c_str()); \ + ::test_util::check(check_ok_, #expr, __FILE__, __LINE__); \ + } while (0) + +namespace { + +std::vector<std::uint8_t> le_bytes(std::span<const std::uint32_t> words) { + std::vector<std::uint8_t> code; + code.reserve(words.size() * 4); + for (std::uint32_t w : words) + for (int k = 0; k < 4; ++k) code.push_back(static_cast<std::uint8_t>(w >> (8 * k))); + return code; +} + +// Rust `.unwrap()` of a Result<_, ShaderError>: the error is a panic. +template <class F> +auto unwrap(F&& f) -> decltype(f()) { + try { + return f(); + } catch (const ShaderError& e) { + throw std::logic_error("called `Result::unwrap()` on an `Err` value: " + e.to_string()); + } +} + +std::string hex(std::uint64_t v) { + char b[32]; + std::snprintf(b, sizeof b, "%#llx", static_cast<unsigned long long>(v)); + return b; +} + +bool contains(std::string_view s, std::string_view what) { return s.find(what) != std::string_view::npos; } + +// `c.part(fourcc).unwrap().data`. +Bytes part_data(const Container& c, FourCC fourcc) { + const vs::dxbc::Part* p = c.part(fourcc); + if (!p) throw std::logic_error("no " + fourcc.to_string() + " part"); + return p->data; +} + +// `u64::from_le_bytes(data.try_into().unwrap())`. +std::uint64_t u64_exact(Bytes d) { + if (d.size() != 8) throw std::logic_error("not 8 bytes: " + std::to_string(d.size())); + std::uint64_t v = 0; + for (std::size_t k = 0; k < 8; ++k) v |= std::uint64_t(d[k]) << (8 * k); + return v; +} + +// The SFI0 features of a translated container. +std::uint64_t sfi0_of(const std::vector<std::uint8_t>& dxil) { + const Container host = unwrap([&] { return Container::parse(dxil); }); + return u64_exact(part_data(host, FourCC::SFI0)); +} + +// `v.validate(&mut dxil).unwrap()`: in place. +void validate_in_place(Validator& v, std::vector<std::uint8_t>& dxil) { + if (std::optional<std::string> e = v.validate(dxil)) CHECK_MSG(!e, "validator: " + *e); +} + +// `if let Ok(mut v) = Validator::load(Validator::default_path()) { v.validate(&mut dxil.clone()).unwrap() }`. +void validate_if_loaded(const std::vector<std::uint8_t>& dxil) { + std::optional<Validator> v = Validator::load(Validator::default_path()); + if (!v) return; + std::vector<std::uint8_t> copy = dxil; + validate_in_place(*v, copy); +} + +// `if let Some(path) = Validator::default_path() { Validator::load(Some(&path)).unwrap().validate(...).unwrap() }`. +void validate_if_sdk(const std::vector<std::uint8_t>& dxil) { + std::optional<fs::path> path = Validator::default_path(); + if (!path) return; + std::string why; + std::optional<Validator> v = Validator::load(path, &why); + if (!v) throw std::logic_error("Validator::load: " + why); + std::vector<std::uint8_t> copy = dxil; + validate_in_place(*v, copy); +} + +SigElement sig(std::string name, std::uint8_t kind, std::uint8_t comp, std::uint8_t interp, + std::optional<std::uint32_t> row, std::uint8_t col, std::uint8_t cols, std::uint8_t usage, + bool half) { + SigElement e; + e.name = std::move(name); + e.index = 0; + e.kind = kind; + e.comp = comp; + e.interp = interp; + e.row = row; + e.col = col; + e.cols = cols; + e.usage = usage; + e.half = half; + return e; +} + +// The usual SV_Target element of the tests. +SigElement sv_target() { return sig("SV_Target", 16, 9, 0, 0u, 0, 4, 15, false); } + +PsInput generic_input(std::uint8_t mask, bool fp16) { + PsInput i; + i.usage = Usage::Generic(); + i.row = 0; + i.mask = mask; + i.attr = 0; + i.flat = false; + i.fp16 = fp16; + i.pack2 = false; + i.row2 = 0; + return i; +} + +PsIo ps_io(std::vector<PsInput> inputs, std::uint32_t input_addr) { + PsIo io; + io.inputs = std::move(inputs); + io.input_addr = input_addr; + io.db_shader_control = 0; + return io; +} + +NativeProgram program(HwStage stage, bool wave64, std::uint16_t vgprs, std::vector<RootParam> layout, + std::vector<UsedResource> used, vs::native::StageIo io, std::span<const std::uint32_t> words) { + NativeProgram n; + n.stage = stage; + n.wave64 = wave64; + n.vgprs = vgprs; + n.layout = std::move(layout); + n.used = std::move(used); + n.io = std::move(io); + n.code = le_bytes(words); + return n; +} + +RootParam table_param() { return RootParam{RootType::Table(), 0, 1, 0, 0, 0}; } + +// The front end as most tests run it: ir::build of the patched code, structure, resource::track +// with the structure, io::raise; then emit. Throws ShaderError (Rust `?`). +HostShader translate_front(const Container& c, const NativeProgram& native) { + const std::vector<std::uint8_t> code = native.patched_code(); + const vs::ir::Program p = vs::ir::build(code, native.wave64, native.vgprs); + const vs::structure::Structured st = vs::structure::structure(p); + const vs::resource::Resources res = vs::resource::track(p, native.layout, native.stage, &st); + const vs::io::Io io = vs::io::raise(p, native); + return vs::emit(c, native, p, st, io, res); +} + +std::vector<std::uint8_t> read_file(const fs::path& path) { + std::ifstream in(path, std::ios::binary); + if (!in) throw std::logic_error("cannot read " + path.string()); + return std::vector<std::uint8_t>((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); +} + +std::optional<std::string> env_var(const char* name) { + const char* v = std::getenv(name); + if (!v) return std::nullopt; + return std::string(v); +} + +// The LLVM text `dxc -dumpbin` prints for a DXIL container, when dxc is installed. +std::optional<std::string> dump_dxil(const std::vector<std::uint8_t>& container) { + fs::path dxc; + if (std::optional<std::string> p = env_var("X2W_SHADERCFG_PC_DXC")) { + dxc = *p; + } else { + std::optional<fs::path> d = Validator::default_path(); + if (!d) return std::nullopt; + dxc = d->replace_filename("dxc.exe"); + } + std::error_code ec; + if (!fs::exists(dxc, ec)) return std::nullopt; + const std::string pid = std::to_string(GetCurrentProcessId()); + const fs::path file = fs::temp_directory_path() / ("gpu-interp-" + pid + ".dxil"); + const fs::path out = fs::temp_directory_path() / ("gpu-interp-" + pid + ".out"); + const fs::path err = fs::temp_directory_path() / ("gpu-interp-" + pid + ".err"); + { + std::ofstream f(file, std::ios::binary); + if (!f) return std::nullopt; + f.write(reinterpret_cast<const char*>(container.data()), static_cast<std::streamsize>(container.size())); + if (!f) return std::nullopt; + } + // The whole command quoted once more: cmd.exe strips the outer pair. + const std::string cmd = "\"\"" + dxc.string() + "\" -dumpbin \"" + file.string() + "\" > \"" + out.string() + + "\" 2> \"" + err.string() + "\"\""; + const int rc = std::system(cmd.c_str()); + fs::remove(file, ec); + std::vector<std::uint8_t> text; + std::vector<std::uint8_t> errors; + try { + text = read_file(out); + } catch (const std::logic_error&) { + } + try { + errors = read_file(err); + } catch (const std::logic_error&) { + } + fs::remove(out, ec); + fs::remove(err, ec); + if (rc != 0) + throw std::logic_error("dxc -dumpbin failed: " + std::string(errors.begin(), errors.end())); + return std::string(text.begin(), text.end()); +} + +// ---- rs:989 ------------------------------------------------------------------------------------- +void interpolated_f16_writes_the_op_sel_half_with_modifiers() { + // p1_f32 v2, v0, attr0.x; then a p2_f16 completing it into v3, which holds a value + // (v2's own is no number here: a first half is evaluated with its second). + auto p2 = [](bool dst_high, std::uint32_t omod, bool clamp) -> std::array<std::uint32_t, 2> { + auto vgpr = [](std::uint32_t n) { return 256 + n; }; + std::uint32_t w0 = 0x35u << 26 | 0x35au << 16 | 3; + if (dst_high) w0 |= 1u << 14; // op_sel[3]: the high destination half. + if (clamp) w0 |= 1u << 15; + const std::uint32_t w1 = vgpr(1) << 9 | vgpr(2) << 18; + return {w0, w1 | omod << 27}; + }; + auto dump = [&](bool dst_high, std::uint32_t omod, bool clamp) { + const auto [w0, w1] = p2(dst_high, omod, clamp); + const std::array<std::uint32_t, 7> words = { + 0x7E06'0301u, // v_mov_b32 v3, v1 + 0xC808'0000, // v_interp_p1_f32 v2, v0, attr0.x + w0, + w1, // v_interp_p2_f16 v3, attr0, v1, v2 + 0xF800'180F, + 0x0303'0303, // exp mrt0, v3, v3, v3, v3 done vm + 0xBF81'0000, + }; + const NativeProgram native = + program(HwStage::Ps, false, 4, {}, {}, ps_io({generic_input(0b1111, true)}, 2), words); + auto el = [](const char* name, std::uint8_t kind, std::uint8_t usage, bool half) { + return sig(name, kind, 9, 0, 0u, 0, 4, usage, half); + }; + const std::vector<SigElement> in = {el("TEXCOORD", 0, 0, true)}; + const std::vector<SigElement> outs = {el("SV_Target", 16, 15, false)}; + const std::vector<std::uint8_t> isg1 = vs::container::signature(in, true); + const std::vector<std::uint8_t> osg1 = vs::container::signature(outs, false); + const std::vector<std::uint8_t> bytes = vs::dxbc::build({{FourCC::ISG1, isg1}, {FourCC::OSG1, osg1}}); + return unwrap([&] { + const Container c = Container::parse(bytes); + return translate_front(c, native).dxil; + }); + }; + const std::optional<std::string> low = dump_dxil(dump(false, 0, false)); + const std::optional<std::string> high = dump_dxil(dump(true, 1, true)); + if (!low || !high) { + std::fprintf(stderr, "no dxc.exe; DXIL check skipped\n"); + return; + } + // The low-half write keeps the destination's high half. + CHECK_MSG(contains(*low, "-65536"), "low write keeps the high half"); + // The high-half write shifts the result up by 16. + CHECK_MSG(contains(*high, "shl i32"), "op_sel[3] writes the high half"); + // omod mul:2 and clamp (dx.op.unary.f32, opcode 7) are applied. + CHECK_MSG(contains(*high, "2.000000e+00"), "omod multiplies by two"); + CHECK_MSG(contains(*high, "dx.op.unary.f32(i32 7"), "clamp saturates the result"); + CHECK(!contains(*low, "dx.op.unary.f32(i32 7")); +} + +// ---- rs:1083 ------------------------------------------------------------------------------------ +void the_clean_up_switch_parses_or_runs_every_pass() { + const std::uint32_t all = vs::bitcode::opt::ALL; + const std::uint32_t usual = vs::bitcode::opt::DEFAULT; + CHECK_MSG(usual == 63, "the passes of the builds before the wide loads"); + CHECK(vs::parse_shader_opt(std::nullopt) == usual); + CHECK(vs::parse_shader_opt("0") == 0); + CHECK(vs::parse_shader_opt(" 1 ") == 1); + CHECK(vs::parse_shader_opt("0x1") == 1); + CHECK(vs::parse_shader_opt("127") == all); + CHECK(vs::parse_shader_opt("0xffffffff") == all); + CHECK(vs::parse_shader_opt("on") == usual); +} + +// ---- rs:1096 ------------------------------------------------------------------------------------ +void the_loop_limit_switch_parses_or_falls_back() { + using vs::lower::LOOP_LIMIT; + CHECK(vs::parse_loop_limit(std::nullopt) == LOOP_LIMIT); + CHECK(vs::parse_loop_limit("4096") == 4096); + CHECK(vs::parse_loop_limit(" 0x1000 ") == 4096); + CHECK(vs::parse_loop_limit("1") == 1); + for (const char* bad : {"", "0", "-5", "lots", "0x", "4294967296"}) + CHECK_MSG(vs::parse_loop_limit(bad) == LOOP_LIMIT, std::string("\"") + bad + "\""); +} + +// ---- rs:1111 ------------------------------------------------------------------------------------ +// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`). DXC sets ShaderFlags.StencilRef +// (bit 11) for a pixel shader whose output signature has SV_StencilRef, and the feature bit +// D3D_SHADER_FEATURE_STENCIL_REF (0x200) in SFI0; the validator checks both against the module. +void a_stencil_export_declares_the_stencil_ref_feature() { + const std::array<std::uint32_t, 5> words = { + 0x7E00'02F2u, // v_mov_b32 v0, 1.0 + 0x7E02'0285, // v_mov_b32 v1, 5 + 0xF800'1883, + 0x0000'0100, // exp mrtz v0, v1, off, off done vm + 0xBF81'0000, + }; + const NativeProgram native = program(HwStage::Ps, false, 2, {}, {}, ps_io({}, 0), words); + auto el = [](const char* name, std::uint8_t kind, std::uint8_t comp) { + return sig(name, kind, comp, 0, std::nullopt, 0, 1, 1, false); + }; + const std::vector<SigElement> outs = {el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)}; + const std::vector<std::uint8_t> osg1 = vs::container::signature(outs, false); + const std::vector<std::uint8_t> bytes = vs::dxbc::build({{FourCC::OSG1, osg1}}); + const HostShader out = unwrap([&] { + const Container c = Container::parse(bytes); + return translate_front(c, native); + }); + // dxil.dll, where there is one, checks the flags against the module. + validate_if_loaded(out.dxil); + const std::uint64_t features = sfi0_of(out.dxil); + CHECK_MSG((features & 0x200) != 0, "SFI0 " + hex(features) + ": no StencilRef"); +} + +// ---- rs:1173 ------------------------------------------------------------------------------------ +// A pixel program with an ordered section, as the console compiler makes one of rasterizer ordered +// views (the title's hair cards keep their nearest layers that way): the wait for overlapped waves +// is skipped, the views inside the section are the host's ordered ones, the one after it is not. +void an_ordered_section_uses_rasterizer_ordered_views() { + const std::array<std::uint32_t, 37> section = { + 0xBE82'0300u, // s_mov_b32 s2, s0 + 0xBE83'0380, // s_mov_b32 s3, 0 + 0xF40C'0201, // s_load_dwordx8 s[8:15], s[2:3], 0 + 0xFA00'0000, + 0x9390'FF01, // s_bfe_u32 s16, s1, 0x2001c + 0x0002'001C, + 0x9391'FF01, // s_bfe_u32 s17, s1, 0xa0000 + 0x000A'0000, + 0x8F10'8110, // s_lshl_b32 s16, s16, 1 + 0x9392'FF01, // s_bfe_u32 s18, s1, 0xa0010 + 0x000A'0010, + 0xBE91'0711, // s_not_b32 s17, s17 + 0x9013'9F01, // s_lshr_b32 s19, s1, 31 + 0x8810'8110, // s_or_b32 s16, s16, 1 + 0x8112'1112, // s_add_i32 s18, s18, s17 + 0xBF06'8013, // s_cmp_eq_u32 s19, 0 + 0xB990'1019, // s_setreg_b32 hwreg(HW_REG_POPS_PACKER, 0, 3), s16 + 0x8514'807E, // s_cselect_b32 s20, exec_lo, 0 + 0x8115'11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17 + 0xBF08'1215, // s_cmp_gt_u32 s21, s18 + 0x8516'807E, // s_cselect_b32 s22, exec_lo, 0 + 0x8814'1614, // s_or_b32 s20, s20, s22 + 0x876A'147E, // s_and_b32 vcc_lo, exec_lo, s20 + 0xBF87'0004, // s_cbranch_vccnz past the wait + 0xBF8E'FFFF, // s_sleep 0xffff + 0x8115'11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17 + 0xBF0A'1512, // s_cmp_lt_u32 s18, s21 + 0xBF84'FFFC, // s_cbranch_scc0 back to the sleep + 0x7E00'0280, // v_mov_b32 v0, 0 + 0x7E02'0280, // v_mov_b32 v1, 0 + 0xF000'3F88, // image_load v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc dlc + 0x0002'0200, + 0x0604'04F2, // v_add_f32 v2, 1.0, v2 + 0xF020'3F08, // image_store v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc + 0x0002'0200, + 0xBEFC'0380, // s_mov_b32 m0, 0 + 0xBF90'0007, // s_sendmsg sendmsg(MSG_ORDERED_PS_DONE) + }; + const std::array<std::uint32_t, 3> end = { + 0xF800'180Fu, // exp mrt0 v2, v2, v2, v2 done vm + 0x0202'0202, + 0xBF81'0000, // s_endpgm + }; + // A store after the section, through an ordinary view. + const std::array<std::uint32_t, 2> after = {0xF020'3F08u, 0x0002'0200}; + // Throws ShaderError where Rust's closure returns Err. + auto lower_words = [](const std::vector<std::uint32_t>& words) -> std::uint64_t { + const NativeProgram native = program(HwStage::Ps, false, 8, {table_param()}, + {UsedResource{ResourceType::Uav(), RootType::Table(), 0, 0, 4, 8, 0, 0}}, + ps_io({}, 0), words); + const std::vector<SigElement> outs = {sv_target()}; + const std::vector<std::uint8_t> osg1 = vs::container::signature(outs, false); + const std::vector<std::uint8_t> bytes = vs::dxbc::build({{FourCC::OSG1, osg1}}); + const Container c = unwrap([&] { return Container::parse(bytes); }); + const HostShader out = translate_front(c, native); + { + std::optional<Validator> v = Validator::load(Validator::default_path()); + if (v) { + std::vector<std::uint8_t> copy = out.dxil; + if (std::optional<std::string> e = v->validate(copy)) + throw std::logic_error("validator: " + *e); + } + } + return sfi0_of(out.dxil); + }; + auto concat = [](std::initializer_list<std::span<const std::uint32_t>> parts) { + std::vector<std::uint32_t> v; + for (std::span<const std::uint32_t> p : parts) v.insert(v.end(), p.begin(), p.end()); + return v; + }; + const std::span<const std::uint32_t> all(section); + // D3D_SHADER_REQUIRES_ROVS + std::uint64_t features = unwrap([&] { return lower_words(concat({all, end})); }); + CHECK_MSG((features & 0x1000) != 0, "SFI0 " + hex(features) + ": no ROVs"); + unwrap([&] { return lower_words(concat({all, after, end})); }); + // The same accesses outside a section: ordinary views, no feature. + const std::vector<std::uint32_t> plain = concat({all.subspan(0, 4), all.subspan(28, 35 - 28), end}); + features = unwrap([&] { return lower_words(plain); }); + CHECK_MSG((features & 0x1000) == 0, "SFI0 " + hex(features) + ": ROVs"); + // Without the section's start the wait stays unknown. + std::vector<std::uint32_t> unmarked = concat({all, end}); + unmarked.erase(unmarked.begin() + 16); + CHECK(vs::catch_shader_error([&] { lower_words(unmarked); }).has_value()); +} + +// ---- rs:1301 ------------------------------------------------------------------------------------ +void immediate_sampler_slots_distinguish_comparison_uses() { + const std::array<std::uint32_t, 23> words = { + 0xBE81'0380u, // s_mov_b32 s1, 0 + 0xF40C'0000, + 0xFA00'0000, // s_load_dwordx8 s[0:7], s[0:1], null + 0xBE88'0380, // s_mov_b32 s8, 0 + 0xBE89'0380, // s_mov_b32 s9, 0 + 0xBE8A'0380, // s_mov_b32 s10, 0 + 0xBE8B'0380, // s_mov_b32 s11, 0 + 0x7E00'02F0, // v_mov_b32 v0, 0.5 (comparison reference) + 0x7E02'02F0, // v_mov_b32 v1, 0.5 (u) + 0x7E04'02F0, // v_mov_b32 v2, 0.5 (v) + 0xBF8C'0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xF080'0108, + 0x0040'0301, // image_sample v3, v[1:2], s[0:7], s[8:11] + 0xF0A0'0108, + 0x0040'0400, // image_sample_c v4, v[0:2], s[0:7], s[8:11] + 0xF0BC'0108, + 0x0040'0500, // image_sample_c_lz v5, v[0:2], s[0:7], s[8:11] + 0xF080'0108, + 0x0040'0601, // image_sample v6, v[1:2], s[0:7], s[8:11] + 0xBF8C'3F70, // s_waitcnt vmcnt(0) + 0xF800'180F, + 0x0605'0403, // exp mrt0, v3, v4, v5, v6 done vm + 0xBF81'0000, + }; + const NativeProgram native = program(HwStage::Ps, false, 7, {table_param()}, + {UsedResource{ResourceType::Srv(), RootType::Table(), 0, 0, 0, 8, 0, 0}}, + ps_io({}, 0), words); + const std::vector<SigElement> outs = {sv_target()}; + const std::vector<std::uint8_t> osg1 = vs::container::signature(outs, false); + const std::vector<std::uint8_t> bytes = vs::dxbc::build({{FourCC::OSG1, osg1}}); + const HostShader out = unwrap([&] { + const Container c = Container::parse(bytes); + return translate_front(c, native); + }); + + const vs::StaticSampler sampler = vs::StaticSampler::from_words({0, 0, 0, 0}); + vs::StaticSampler comparison = sampler; + comparison.filter = sampler.filter | 0x80; + const std::vector<std::array<std::uint32_t, 4>> zeros(2, std::array<std::uint32_t, 4>{}); + CHECK(out.samplers == zeros); + CHECK((out.static_samplers == std::vector<vs::StaticSampler>{sampler, comparison})); + validate_if_sdk(out.dxil); +} + +// ---- rs:1393 ------------------------------------------------------------------------------------ +// A wave64 compute program that writes only EXEC's high dword (`s_mov_b32 exec_hi, 0`) before a +// vector instruction. The new mask was opaque and keyed by the unchanged low dword, so building its +// lane bit needed the mask's own value: lowering recursed until the stack overflowed, which takes +// the whole process down (found by random-input testing). Now that low dword, seen with two high +// dwords, has no mask, and the instruction fails like any other that cannot be expressed: its +// result is missing, and only a side effect that uses it would stop the translation. +void an_exec_high_write_does_not_overflow_the_stack() { + // s_mov_b32 exec_hi, 0; v_mov_b32 v1, v0; s_endpgm + const std::array<std::uint32_t, 3> words = {0xBEFF'0380u, 0x7E02'0300, 0xBF81'0000}; + const NativeProgram native = program(HwStage::Cs, true, 2, {}, {}, ComputeIo{0, {64, 1, 1}}, words); + const std::vector<std::uint8_t> code = native.patched_code(); + const vs::ir::Program p = unwrap([&] { return vs::ir::build(code, native.wave64, native.vgprs); }); + const vs::structure::Structured st = unwrap([&] { return vs::structure::structure(p); }); + const vs::resource::Resources res = + unwrap([&] { return vs::resource::track(p, native.layout, native.stage, &st); }); + const vs::io::Io io = unwrap([&] { return vs::io::raise(p, native); }); + const std::vector<std::uint8_t> container = vs::dxbc::build({}); + const Container c = unwrap([&] { return Container::parse(container); }); + try { + (void)vs::emit(c, native, p, st, io, res); + } catch (const ShaderError& e) { + CHECK_MSG(contains(e.to_string(), "its own value"), e.to_string()); + } +} + +// rs:1429: a wave64 compute program: `body`, then a store of v1 to a UAV. The error of emit (Rust's +// Result); the front end's errors are panics. +std::optional<ShaderError> stores_v1(std::span<const std::uint32_t> body) { + // s_mov_b32 s1, 0; s_load_dwordx4 s[8:11], s[0:1], 0 + std::vector<std::uint32_t> words = {0xBE81'0380, 0xF408'0200, 0xFA00'0000}; + words.insert(words.end(), body.begin(), body.end()); + // v_lshlrev_b32 v3, 2, v0; buffer_store_dword v1, v3, s[8:11], 0 offen; s_endpgm + for (std::uint32_t w : {0x3406'0082u, 0xE070'1000u, 0x8002'0103u, 0xBF81'0000u}) words.push_back(w); + const NativeProgram native = program(HwStage::Cs, true, 4, {table_param()}, + {UsedResource{ResourceType::Uav(), RootType::Table(), 0, 0, 0, 4, 0, 0}}, + ComputeIo{2, {64, 1, 1}}, words); + const std::vector<std::uint8_t> code = native.patched_code(); + const vs::ir::Program p = unwrap([&] { return vs::ir::build(code, native.wave64, native.vgprs); }); + const vs::resource::Resources res = + unwrap([&] { return vs::resource::track(p, native.layout, native.stage, nullptr); }); + const vs::io::Io io = unwrap([&] { return vs::io::raise(p, native); }); + const vs::structure::Structured st = unwrap([&] { return vs::structure::structure(p); }); + const std::vector<std::uint8_t> container = vs::dxbc::build({}); + const Container c = unwrap([&] { return Container::parse(container); }); + return vs::catch_shader_error([&] { (void)vs::emit(c, native, p, st, io, res); }); +} + +std::string words_hex(std::span<const std::uint32_t> body) { + std::string s = "["; + for (std::size_t k = 0; k < body.size(); ++k) s += (k ? ", " : "") + hex(body[k]); + return s + "]"; +} + +// ---- rs:1476 ------------------------------------------------------------------------------------ +// The high dword of a wave64 mask rewritten alone (`s_mov_b32 vcc_hi` or `exec_hi`): lanes 32-63 +// took the mask the low dword was first written with (the compare's, EXEC's on entry). Now the +// store refuses; without the write it translates. +void a_mask_whose_high_dword_is_rewritten_is_refused() { + // v_cmp_eq_u32 vcc, 0, v0; v_mov_b32 v2, 11; v_cndmask_b32 v1, 0, v2, vcc + const std::vector<std::uint32_t> select = {0x7D84'0080, 0x7E04'028B, 0x0202'0480}; + // The same with v_add_co_ci_u32 v1, vcc, 0, v2, vcc. + const std::vector<std::uint32_t> carry = {0x7D84'0080, 0x7E04'028B, 0x5002'0480}; + // v_mov_b32 v1, 7 + const std::vector<std::uint32_t> mov = {0x7E02'0287}; + for (const std::vector<std::uint32_t>* body : {&select, &carry, &mov}) { + const std::optional<ShaderError> e = stores_v1(*body); + if (e) throw std::logic_error("called `Result::unwrap()` on an `Err` value: " + e->to_string()); + } + // s_mov_b32 vcc_hi, 0 after the compare. + const std::vector<std::uint32_t> select_hi = {0x7D84'0080, 0xBEEB'0380, 0x7E04'028B, 0x0202'0480}; + const std::vector<std::uint32_t> carry_hi = {0x7D84'0080, 0xBEEB'0380, 0x7E04'028B, 0x5002'0480}; + // s_mov_b32 exec_hi, 0; v_mov_b32 v1, 7, then the same after s_mov_b64 s[2:3], exec. + const std::vector<std::uint32_t> exec_hi = {0xBEFF'0380, 0x7E02'0287}; + const std::vector<std::uint32_t> exec_hi_saved = {0xBE82'047E, 0xBEFF'0380, 0x7E02'0287}; + for (const std::vector<std::uint32_t>* body : {&select_hi, &carry_hi, &exec_hi, &exec_hi_saved}) + CHECK_MSG(stores_v1(*body).has_value(), words_hex(*body)); +} + +// ---- rs:1503 ------------------------------------------------------------------------------------ +// `ds_bpermute_b32` stores nothing: each lane reads the lane its address names. It stopped as "LDS +// the program does not allocate" (sticky lips) or "an LDS operation" (the checkerboard shadow +// masks). +void a_backward_permute_reads_the_lane_its_address_names() { + // v_mov_b32 v2, 11; ds_bpermute_b32 v1, v0, v2 + const std::array<std::uint32_t, 3> body = {0x7E04'028B, 0xDACC'0000, 0x0100'0200}; + const std::optional<ShaderError> e = stores_v1(body); + if (e) throw std::logic_error("called `Result::unwrap()` on an `Err` value: " + e->to_string()); +} + +// ---- rs:1512 ------------------------------------------------------------------------------------ +// A carry-in reading a join of compares after a divergent branch. A lane that skipped the inner +// compare has VCC clear there (VOPC clears inactive lanes), not the first compare's bit, so the +// join is no per-lane phi: lowering refuses it. +void a_carry_in_from_a_divergent_join_is_refused() { + const std::array<std::uint32_t, 7> body = { + 0x7E04'028B, // v_mov_b32 v2, 11 + 0x7D84'0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBE82'376A, // s_andn1_saveexec_b64 s[2:3], vcc + 0xBF88'0001, // s_cbranch_execz 1 + 0x7D84'0081, // v_cmp_eq_u32 vcc, 1, v0 + 0x88FE'027E, // s_or_b64 exec, exec, s[2:3] + 0x5002'0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc + }; + const std::optional<ShaderError> err = stores_v1(body); + if (!err) throw std::logic_error("called `Result::unwrap_err()` on an `Ok` value"); + const std::string e = err->to_string(); + CHECK_MSG(contains(e, "a carry-in from an untracked mask"), e); +} + +// rs:1531: a pixel shader writing a constant colour. +std::vector<std::uint8_t> constant_color() { + vs::shader::Shader s(true); + s.outputs.push_back(sv_target()); + const std::size_t b = s.entry; + const std::array<float, 4> colour = {1.0f, 0.5f, 0.25f, 1.0f}; + for (std::size_t c = 0; c < colour.size(); ++c) { + const float v = colour[c]; + // Braced: evaluated left to right, as Rust's array. + const std::array<vs::bitcode::V, 4> args = { + s.m.i32(0), + s.m.i32(0), + s.m.i8(static_cast<std::uint8_t>(c)), + s.m.f32(std::bit_cast<std::uint32_t>(v)), + }; + s.op(b, "storeOutput.f32", vs::bitcode::Attr::NoUnwind, s.t.void_, 5, std::span<const vs::bitcode::V>(args)); + } + s.m.terminate(b, vs::bitcode::Term::ret()); + return s.finish(); +} + +HostShader host_shader(HwStage stage, std::vector<std::uint8_t> dxil) { + HostShader h; + h.stage = stage; + h.dxil = std::move(dxil); + return h; +} + +// ---- rs:1561 ------------------------------------------------------------------------------------ +void stub_pipeline_is_created() { + std::optional<vs::host::Host> host; + try { + host.emplace(false); + } catch (const vs::host::Error& e) { + std::fprintf(stderr, "no SM 6.6 device (%s); skipped\n", e.what()); + return; + } + const HostShader fallback = host_shader(HwStage::Ps, constant_color()); + auto file = [](const char* var, HwStage stage) -> std::optional<HostShader> { + std::optional<std::string> p = env_var(var); + if (!p) return std::nullopt; + return host_shader(stage, read_file(*p)); + }; + const HostShader ps = file("X2W_SHADERCFG_REF_PS", HwStage::Ps).value_or(fallback); + std::optional<HostShader> vs_file = file("X2W_SHADERCFG_REF_VS", HwStage::Vs); + const HostShader vertex = vs_file ? std::move(*vs_file) : vs::host::stub_vs(ps); + validate_if_loaded(vertex.dxil); + (void)host->pipeline(vertex, ps); + // The runtime checks the container hash: no hash or a wrong one is refused. (Recent runtimes + // also take sixteen 0x01 bytes, a bypass value; ours works with older ones too.) + if (ps.dxil.size() < 20) throw std::logic_error("container shorter than its header"); + std::vector<std::uint8_t> wrong(ps.dxil.begin() + 4, ps.dxil.begin() + 20); + wrong[0] ^= 1; + const std::vector<std::uint8_t> zero(16, 0); + for (const std::vector<std::uint8_t>* digest : std::array<const std::vector<std::uint8_t>*, 2>{&zero, &wrong}) { + HostShader other = ps; + std::copy(digest->begin(), digest->end(), other.dxil.begin() + 4); + bool refused = false; + try { + (void)host->pipeline(vertex, other); + } catch (const vs::host::Error&) { + refused = true; + } + std::string text = "digest"; + for (std::uint8_t b : *digest) { + char h[4]; + std::snprintf(h, sizeof h, " %02x", b); + text += h; + } + CHECK_MSG(refused, text + " accepted"); + } +} + +// ---- rs:1619 ------------------------------------------------------------------------------------ +void constant_color_validates() { + std::vector<std::uint8_t> c = constant_color(); + const std::optional<fs::path> path = Validator::default_path(); + std::optional<Validator> v = Validator::load(path); + if (!v) { + std::fprintf(stderr, "no dxil.dll; skipped\n"); + return; + } + const std::vector<std::uint8_t> ours(c.begin() + 4, c.begin() + 20); + validate_in_place(*v, c); + CHECK_MSG(std::equal(ours.begin(), ours.end(), c.begin() + 4), "our hash differs from the validator's"); +} + +// rs:1633: a pixel program of `words` with no user data. +NativeProgram emit_native(std::span<const std::uint32_t> words, std::uint32_t input_addr) { + return program(HwStage::Ps, false, 4, {}, {}, ps_io({}, input_addr), words); +} + +// Triangle (0, 1, 2), each corner's 9-bit index in its 10-bit field. +constexpr std::uint32_t TRIANGLE = 1u << 10 | 2u << 20; +// The edge flags of the three corners (bits 9, 19 and 29). +constexpr std::uint32_t EDGE_FLAGS = 1u << 9 | 1u << 19 | 1u << 29; +// The culling bit. +constexpr std::uint32_t CULL = 1u << 31; + +// rs:1784: the triangle with its far corners at `reach` - 1. Throws ShaderError. +HostShader triangle_mesh_to(std::uint32_t prim, float reach) { + // (the second corner's y comes out as 2 x its lane bit: half of it) + const std::uint32_t x = std::bit_cast<std::uint32_t>(reach); + const std::uint32_t y = std::bit_cast<std::uint32_t>(reach / 2.0f); + const std::array<std::uint32_t, 21> words = { + 0xD765'0001u, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0x0001'00C1, + 0x3604'0281, // v_and_b32 v2, 1, v1 + 0x3606'0282, // v_and_b32 v3, 2, v1 + 0x7E04'0D02, // v_cvt_f32_u32 v2, v2 + 0x7E06'0D03, // v_cvt_f32_u32 v3, v3 + 0x1008'04FF, // v_mul_f32 v4, reach, v2 + x, + 0x0608'08F3, // v_add_f32 v4, -1.0, v4 + 0x100A'06FF, // v_mul_f32 v5, reach / 2, v3 + y, + 0x060A'0AF3, // v_add_f32 v5, -1.0, v5 + 0x7E0C'02F0, // v_mov_b32 v6, 0.5 + 0x7E0E'02F2, // v_mov_b32 v7, 1.0 + 0x7E12'02FF, // v_mov_b32 v9, prim + prim, + 0xF800'0941, // exp prim v9, off, off, off done + 0x0000'0009, + 0xF800'08CF, // exp pos0 v4, v5, v6, v7 done + 0x0706'0504, + 0xBF81'0000, // s_endpgm + }; + MeshIo mesh; + mesh.clip_cntl = 0; + mesh.threads = 32; + mesh.max_vertices = 32; + mesh.max_primitives = 32; + mesh.topology = 2; + mesh.lds_bytes = 0; + const NativeProgram native = program(HwStage::Ms, false, 10, {}, {}, mesh, words); + const std::vector<SigElement> outs = {sig("SV_Position", 3, 9, 0, 0u, 0, 4, 0xF, false)}; + const std::vector<std::uint8_t> osg1 = vs::container::signature(outs, false); + const std::vector<std::uint8_t> bytes = vs::dxbc::build({{FourCC::OSG1, osg1}}); + const Container c = Container::parse(bytes); + return translate_front(c, native); +} + +// rs:1776: a one-wave (32-lane) triangle mesh program whose lanes all export primitive `prim` +// and, as vertex `lane`, the position (lane & 1 ? 3 : -1, lane & 2 ? 3 : -1, 0.5, 1): triangle +// (0, 1, 2) covers the whole target. +HostShader triangle_mesh(std::uint32_t prim) { return triangle_mesh_to(prim, 4.0f); } + +// ---- rs:1651 ------------------------------------------------------------------------------------ +// A pixel program that takes its neighbour's position across its quad (`ds_swizzle_b32`, as the +// console's compiler makes derivatives) and exports the differences in x and y: 1 and -1 in every +// pixel of a triangle, those at its edges too, whose neighbours are helpers. +void quad_neighbours_at_a_triangles_edge_are_read() { + using vs::host::Draw; + using vs::host::Host; + using vs::host::Root; + // v2, v3: position x, y (input address: POS_X and POS_Y after the two perspective barycentrics). + auto swizzle = [](std::uint32_t dst, std::uint32_t src, std::uint32_t pattern) -> std::array<std::uint32_t, 2> { + return {0xD800'0000u | 0x35u << 18 | 0x8000u | pattern, dst << 24 | src}; + }; + std::vector<std::uint32_t> words = {0xBEFC'0380u}; // s_mov_b32 m0, 0 + for (const auto& pair : {swizzle(4, 2, 0xB1), // lanes 1 0 3 2 + swizzle(5, 3, 0x4E), // lanes 2 3 0 1 + swizzle(6, 2, 0xA0)}) // lanes 0 0 2 2 + words.insert(words.end(), pair.begin(), pair.end()); + for (std::uint32_t w : { + 0x0808'0504u, // v_sub_f32 v4, v4, v2 + 0x080A'0705u, // v_sub_f32 v5, v5, v3 + 0x080C'0506u, // v_sub_f32 v6, v6, v2 + 0xF800'180Fu, + 0x0302'0504u, // exp mrt0 v4, v5, v2, v3 done vm + 0xBF81'0000u, + }) + words.push_back(w); + NativeProgram native = emit_native(words, 1u << 1 | 1u << 8 | 1u << 9); + native.vgprs = 8; + const std::vector<SigElement> outs = {sv_target()}; + const std::vector<SigElement> ins = {sig("SV_Position", 3, 9, 4, 0u, 0, 4, 3, false)}; + const std::vector<std::uint8_t> isg1 = vs::container::signature(ins, true); + const std::vector<std::uint8_t> osg1 = vs::container::signature(outs, false); + const std::vector<std::uint8_t> bytes = vs::dxbc::build({{FourCC::ISG1, isg1}, {FourCC::OSG1, osg1}}); + const HostShader ps = unwrap([&] { + const Container c = Container::parse(bytes); + return translate_front(c, native); + }); + validate_if_sdk(ps.dxil); + const HostShader ms = unwrap([&] { return triangle_mesh_to(TRIANGLE, 1.3f); }); + for (const auto& [label, warp] : {std::pair<const char*, bool>{"hardware", false}, {"warp", true}}) { + std::optional<Host> host; + try { + host.emplace(warp); + } catch (const vs::host::Error&) { + continue; + } + vs::host::ComPtr<ID3D12RootSignature> root; + try { + root = host->root_signature_for({{ms, D3D12_SHADER_VISIBILITY_MESH}, {ps, D3D12_SHADER_VISIBILITY_PIXEL}}); + } catch (const vs::host::Error&) { + continue; + } + vs::host::ComPtr<ID3D12PipelineState> pso; + try { + pso = host->mesh_pipeline_with(root.Get(), ms.dxil, ps.dxil); + } catch (const vs::host::Error&) { + std::fprintf(stderr, "no mesh pipeline on %s; skipped\n", label); + continue; + } + Draw d; + d.roots.emplace_back(0u, Root::constants({0})); + d.roots.emplace_back(1u, Root::constants({0})); + d.stride = 0; + d.size = {16, 16}; + d.mesh_groups = 1; + std::vector<std::array<float, 4>> texels; + try { + texels = host->draw(root.Get(), pso.Get(), d); + } catch (const vs::host::Error& e) { + throw std::logic_error(std::string(label) + ": draw: " + e.what()); + } + std::vector<std::pair<std::size_t, std::array<float, 4>>> lit; + for (std::size_t n = 0; n < texels.size(); ++n) + if (texels[n][2] != 0.0f) lit.emplace_back(n, texels[n]); + CHECK_MSG(lit.size() >= 20 && lit.size() < 240, + std::string(label) + ": " + std::to_string(lit.size()) + " texels lit"); + std::vector<std::pair<std::size_t, std::array<float, 4>>> bad; + for (const auto& [n, t] : lit) { + const float x = n % 2 == 0 ? 1.0f : -1.0f; + const float y = n / 16 % 2 == 0 ? 1.0f : -1.0f; + if (t[0] != x || t[1] != y) bad.emplace_back(n, t); + } + if (!bad.empty()) { + char first[160]; + std::snprintf(first, sizeof first, "(%zu, [%g, %g, %g, %g])", bad[0].first, bad[0].second[0], + bad[0].second[1], bad[0].second[2], bad[0].second[3]); + CHECK_MSG(bad.empty(), std::string(label) + ": " + std::to_string(bad.size()) + " of " + + std::to_string(lit.size()) + " texels: " + first); + } + } +} + +// ---- rs:1850 ------------------------------------------------------------------------------------ +// A primitive export's corners are 9-bit indices: the edge flag above each (bits 9, 19, 29) is no +// part of it. Masking ten bits made a flagged corner index 512 or more, past any mesh program's +// vertices (the draw test below shows the triangle). Flagged, unflagged and culled exports +// translate, and dxil.dll, where there is one, takes each module. +void primitive_export_indices_drop_the_edge_flags() { + std::optional<Validator> validator = Validator::load(Validator::default_path()); + for (std::uint32_t prim : {TRIANGLE, TRIANGLE | EDGE_FLAGS, TRIANGLE | EDGE_FLAGS | CULL}) { + HostShader ms; + try { + ms = triangle_mesh(prim); + } catch (const ShaderError& e) { + throw std::logic_error(hex(prim) + ": " + e.to_string()); + } + if (validator) { + std::vector<std::uint8_t> copy = ms.dxil; + if (std::optional<std::string> e = validator->validate(copy)) + throw std::logic_error(hex(prim) + ": " + *e); + } + } +} + +// ---- rs:1877 ------------------------------------------------------------------------------------ +// A triangle mesh program on the host GPU and on WARP (where they have mesh shaders): triangle +// (0, 1, 2) covers the target with its corners' edge flags set as without them; with the culling +// bit, nothing is lit. +void edge_flagged_triangles_draw_as_unflagged_ones() { + using vs::host::Draw; + using vs::host::Host; + using vs::host::Root; + const std::vector<std::uint8_t> ps = constant_color(); + int ran = 0; + for (const auto& [label, warp] : {std::pair<const char*, bool>{"hardware", false}, {"warp", true}}) { + std::optional<Host> host; + try { + host.emplace(warp); + } catch (const vs::host::Error&) { + std::fprintf(stderr, "no SM 6.6 %s device; skipped\n", label); + continue; + } + D3D12_FEATURE_DATA_D3D12_OPTIONS7 options{}; + const HRESULT queried = host->device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &options, + static_cast<UINT>(sizeof options)); + if (FAILED(queried) || options.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED) { + std::fprintf(stderr, "no mesh shaders on the %s device; skipped\n", label); + continue; + } + for (const auto& [prim, culled] : {std::pair<std::uint32_t, bool>{TRIANGLE, false}, + {TRIANGLE | EDGE_FLAGS, false}, + {TRIANGLE | EDGE_FLAGS | CULL, true}}) { + const HostShader ms = unwrap([&] { return triangle_mesh(prim); }); + const vs::host::ComPtr<ID3D12RootSignature> root = + host->root_signature_for({{ms, D3D12_SHADER_VISIBILITY_MESH}}); + vs::host::ComPtr<ID3D12PipelineState> pso; + try { + pso = host->mesh_pipeline_with(root.Get(), ms.dxil, ps); + } catch (const vs::host::Error& e) { + throw std::logic_error(std::string(label) + ": mesh pipeline: " + e.what()); + } + Draw d; + d.roots.emplace_back(0u, Root::constants({0})); + d.stride = 0; + d.size = {16, 16}; + d.mesh_groups = 1; + std::vector<std::array<float, 4>> texels; + try { + texels = host->draw(root.Get(), pso.Get(), d); + } catch (const vs::host::Error& e) { + throw std::logic_error(std::string(label) + ": draw: " + e.what()); + } + const auto lit = std::count_if(texels.begin(), texels.end(), [](const auto& t) { return t[3] != 0.0f; }); + if (culled) { + CHECK_MSG(lit == 0, std::string(label) + ", " + hex(prim) + ": a culled triangle lit texels"); + continue; + } + const std::array<float, 4> colour = {1.0f, 0.5f, 0.25f, 1.0f}; + CHECK_MSG(std::all_of(texels.begin(), texels.end(), [&](const auto& t) { return t == colour; }), + std::string(label) + ", " + hex(prim) + ": " + std::to_string(lit) + " of 256 texels lit"); + } + std::fprintf(stderr, "%s: edge-flagged triangles drew\n", label); + ran += 1; + } + if (ran == 0) std::fprintf(stderr, "no device with mesh shaders; skipped\n"); +} + +// ---- rs:1956 ------------------------------------------------------------------------------------ +// A pixel shader interpolating at sample positions (PERSP_SAMPLE barycentrics, `SPI_PS_INPUT_ADDR` +// bit 0) runs at sample frequency: DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte +// 1) whenever an input is interpolated per sample. +void sample_interpolated_inputs_set_psv_sample_frequency() { + const std::array<std::uint32_t, 5> words = { + 0xC808'0000u, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809'0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xF800'180F, + 0x0202'0202, // exp mrt0, v2, v2, v2, v2 done vm + 0xBF81'0000, + }; + auto psv_of = [&](std::uint32_t input_addr) { + const NativeProgram native = + program(HwStage::Ps, false, 4, {}, {}, ps_io({generic_input(0b1111, false)}, input_addr), words); + auto el = [](const char* name, std::uint8_t kind, std::uint8_t usage) { + return sig(name, kind, 9, 0, 0u, 0, 4, usage, false); + }; + const std::vector<SigElement> in = {el("TEXCOORD", 0, 0)}; + const std::vector<SigElement> outs = {el("SV_Target", 16, 15)}; + const std::vector<std::uint8_t> isg1 = vs::container::signature(in, true); + const std::vector<std::uint8_t> osg1 = vs::container::signature(outs, false); + const std::vector<std::uint8_t> bytes = vs::dxbc::build({{FourCC::ISG1, isg1}, {FourCC::OSG1, osg1}}); + const HostShader out = unwrap([&] { + const Container c = Container::parse(bytes); + return translate_front(c, native); + }); + // dxil.dll, where there is one, checks PSV0 against the module. + validate_if_loaded(out.dxil); + const Container host = unwrap([&] { return Container::parse(out.dxil); }); + const Bytes psv = part_data(host, FourCC::PSV0); + return std::vector<std::uint8_t>(psv.begin(), psv.end()); + }; + // Runtime info starts after its size; PSInfo is {DepthOutput, SampleFrequency}. + const std::vector<std::uint8_t> center = psv_of(1u << 1); + if (center.size() <= 5) throw std::logic_error("PSV0 too short"); + CHECK_MSG(center[4 + 1] == 0, "center interpolation is per pixel"); + const std::vector<std::uint8_t> sample = psv_of(1u << 0); + if (sample.size() <= 5) throw std::logic_error("PSV0 too short"); + CHECK_MSG(sample[4 + 1] == 1, "PSInfo.SampleFrequency"); +} + +// ---- rs:2033 ------------------------------------------------------------------------------------ +// A pixel shader reading channel z of an input whose element starts at w. Looking the channel up +// subtracted the element's first channel before checking the channel lies in it, so in a build with +// overflow checks (tests, debug) any read below an element that starts at z or w panicked, +// whichever row it was in (found by random-input testing). +void reading_a_channel_below_an_input_element_does_not_underflow() { + // v_interp_mov_f32 v3, p0, attr0.z; s_endpgm + const std::array<std::uint32_t, 2> words = {0xC80E'0202u, 0xBF81'0000}; + const NativeProgram native = + program(HwStage::Ps, false, 4, {}, {}, ps_io({generic_input(0b1000, false)}, 0), words); + const std::vector<SigElement> in = {sig("TEXCOORD", 0, 9, 0, 0u, 3, 1, 0, false)}; + const std::vector<std::uint8_t> isg1 = vs::container::signature(in, true); + const std::vector<std::uint8_t> bytes = vs::dxbc::build({{FourCC::ISG1, isg1}}); + const Container c = unwrap([&] { return Container::parse(bytes); }); + const std::vector<std::uint8_t> code = native.patched_code(); + const vs::ir::Program p = unwrap([&] { return vs::ir::build(code, native.wave64, native.vgprs); }); + const vs::structure::Structured st = unwrap([&] { return vs::structure::structure(p); }); + const vs::resource::Resources res = + unwrap([&] { return vs::resource::track(p, native.layout, native.stage, &st); }); + const vs::io::Io io = unwrap([&] { return vs::io::raise(p, native); }); + // Translated or refused with a reason; it must not panic. + (void)vs::catch_shader_error([&] { (void)vs::emit(c, native, p, st, io, res); }); +} + +// The `Parts` of a compute program without signatures (rs:2167, rs:2324). +vs::lower::Lowered lower_compute(const NativeProgram& native, const vs::ir::Program& p, + const vs::structure::Structured& st, const vs::io::Io& io, + const vs::resource::Resources& res) { + vs::lower::Parts parts; + parts.native = &native; + parts.p = &p; + parts.st = &st; + parts.io = &io; + parts.res = &res; + parts.mesh_stride = 0; + return vs::lower::lower(parts); +} + +// ---- rs:2088 ------------------------------------------------------------------------------------ +// `s_buffer_load_dwordx4`, `x8` and `x16` from a raw SRV read the dwords the console's +// range-checked load reads, a call a dword or (`X2W_SHADERCFG_SHADER_OPT` with 64) a call for every four: +// also where a call's four dwords lie across the view's end (the dwords out of it are 0, the others +// are read). On the software adapter only: run the test once plain and once with +// `X2W_SHADERCFG_SHADER_OPT=127`. +void scalar_buffer_loads_read_the_same_dwords_one_call_or_four() { + // (first register, dwords) of the three loads, in order. + constexpr std::array<std::pair<std::uint32_t, std::uint32_t>, 3> LOADS = {{{16, 8}, {24, 4}, {32, 16}}}; + std::vector<std::uint32_t> words = { + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xF408'0202, + 0xFA00'0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 (the SRV) + 0xF408'0302, + 0xFA00'0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 (the UAV) + 0xF42C'0404, + 0x0000'0000, // s_buffer_load_dwordx8 s[16:23], s[8:11], s0 + 0xF428'0604, + 0xFA00'0008, // s_buffer_load_dwordx4 s[24:27], s[8:11], 0x8 + 0xF430'0804, + 0x0200'0004, // s_buffer_load_dwordx16 s[32:47], s[8:11], s1, 0x4 + }; + std::uint32_t out_dword = 0; + for (const auto& [first, n] : LOADS) { + for (std::uint32_t k = 0; k < n; ++k) { + // v_mov_b32 v1, s<first + k> + words.push_back(0x7E00'0000u | 1u << 17 | 0x001u << 9 | (first + k)); + // buffer_store_dword v1, s[12:15], offset 4 * out_dword + words.push_back(0x38u << 26 | 0x1Cu << 18 | (4 * out_dword)); + words.push_back(0x80u << 24 | (12u >> 2) << 16 | 1u << 8); + out_dword += 1; + } + } + words.push_back(0xBF81'0000); // s_endpgm + auto table = [](ResourceType kind, std::uint32_t at) { + return UsedResource{kind, RootType::Table(), at, 0, 4, 4, 4, 1}; + }; + const NativeProgram native = program( + HwStage::Cs, false, 4, {RootParam{RootType::Constants(), 0, 4, 0, 0, 0}, RootParam{RootType::Table(), 0, 1, 0, 4, 1}}, + {table(ResourceType::Srv(), 0), table(ResourceType::Uav(), 8)}, ComputeIo{5u << 1, {1, 1, 1}}, words); + const vs::ir::Program p = unwrap([&] { return vs::ir::build(native.code, native.wave64, native.vgprs); }); + const vs::resource::Resources res = + unwrap([&] { return vs::resource::track(p, native.layout, native.stage, nullptr); }); + const vs::io::Io io = unwrap([&] { return vs::io::raise(p, native); }); + const vs::structure::Structured st = unwrap([&] { return vs::structure::structure(p); }); + vs::lower::Lowered l = unwrap([&] { return lower_compute(native, p, st, io, res); }); + // The calls that read the SRV: 28 a dword, 7 with four a call. + const bool wide = (vs::shader_opt() & vs::bitcode::opt::WIDE) != 0; + std::vector<std::uint8_t> dxil = std::move(l.dxil); + if (std::optional<Validator> v = Validator::load(Validator::default_path())) validate_in_place(*v, dxil); + std::optional<vs::host::Host> host; + try { + host.emplace(true); + } catch (const vs::host::Error&) { + std::fprintf(stderr, "no software adapter; the dispatch is skipped\n"); + return; + } + HostShader cs = host_shader(HwStage::Cs, std::move(dxil)); + cs.user_data = l.user_data; + cs.root_cbvs = l.root_cbvs; + cs.root_srvs = l.root_srvs; + cs.root_uavs = l.root_uavs; + const auto [root, pso] = host->compute_pipeline(cs); + // Twelve dwords: the loads below run across the view's end. + std::vector<std::uint32_t> data; + for (std::uint32_t i = 0; i < 12; ++i) data.push_back(0x1111'1111u * (i + 1) ^ 0x8000'0000u); + auto dword = [&](std::uint64_t byte) -> std::uint32_t { + if (byte % 4 == 0 && byte + 4 <= 4 * std::uint64_t(data.size())) return data[static_cast<std::size_t>(byte / 4)]; + return 0; + }; + const std::array<std::pair<std::uint32_t, std::uint32_t>, 6> offsets = { + {{0, 0}, {16, 0}, {24, 4}, {40, 28}, {48, 44}, {8, 12}}}; + for (const auto& [s0, s1] : offsets) { + const std::array<vs::host::View, 2> views = {vs::host::View::buffer(data, vs::host::Stride::raw()), + vs::host::View::raw_uav(32)}; + vs::host::Dispatch d; + d.roots.emplace_back(0u, vs::host::Root::constants({s0, s1, 0, 0, 0})); + d.views = views; + d.groups = {1, 1, 1}; + const std::vector<std::vector<std::uint32_t>> out = host->dispatch(root.Get(), pso.Get(), d); + const std::array<std::uint64_t, 3> starts = {std::uint64_t(s0), 8, std::uint64_t(s1) + 4}; + std::vector<std::uint32_t> want; + for (std::size_t m = 0; m < LOADS.size(); ++m) + for (std::uint64_t k = 0; k < LOADS[m].second; ++k) want.push_back(dword(starts[m] + 4 * k)); + if (out.empty() || out[0].size() < 28) throw std::logic_error("the UAV holds fewer than 28 dwords"); + const std::vector<std::uint32_t> got(out[0].begin(), out[0].begin() + 28); + std::string text = "offsets " + std::to_string(s0) + " and " + std::to_string(s1) + + ", four dwords a call: " + (wide ? "true" : "false"); + std::fprintf(stderr, "%s: %s\n", text.c_str(), words_hex(got).c_str()); + CHECK_MSG(got == want, text); + } +} + +// ---- rs:2238 ------------------------------------------------------------------------------------ +void valu_div_f32_sequence_executes_on_gpu() { + const std::array<std::uint32_t, 28> words = { + 0xBE85'0380u, // s_mov_b32 s5, 0 + 0xF408'0202, + 0xFA00'0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 + 0xF408'0302, + 0xFA00'0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 + 0x340E'0083, // v_lshlrev_b32 v7, 3, v0 + 0xE034'1000, + 0x8002'0107, // buffer_load_dwordx2 v[1:2], v7, s[8:11], 0 offen + 0xD56D'6A03, + 0x0406'0502, // v_div_scale_f32 v3, vcc_lo, v2, v2, v1 + 0xD56D'1008, + 0x0406'0501, // v_div_scale_f32 v8, s16, v1, v2, v1 + 0x7E08'5503, // v_rcp_f32 v4, v3 + 0xD54B'0005, + 0x23CA'0903, // v_fma_f32 v5, -v3, v4, 1.0 + 0xD54B'0004, + 0x0412'0905, // v_fma_f32 v4, v5, v4, v4 + 0x100A'0908, // v_mul_f32 v5, v8, v4 + 0xD54B'0006, + 0x2422'0B03, // v_fma_f32 v6, -v3, v5, v8 + 0xD56F'0004, + 0x0416'0906, // v_div_fmas_f32 v4, v6, v4, v5 + 0xD55F'0001, + 0x0406'0504, // v_div_fixup_f32 v1, v4, v2, v1 + 0x340E'0082, // v_lshlrev_b32 v7, 2, v0 + 0xE070'1000, + 0x8003'0107, // buffer_store_dword v1, v7, s[12:15], 0 offen + 0xBF81'0000, // s_endpgm + }; + const NativeProgram native = program( + HwStage::Cs, false, 9, {RootParam{RootType::Constants(), 0, 4, 0, 0, 0}, RootParam{RootType::Table(), 0, 1, 0, 4, 1}}, + {UsedResource{ResourceType::Srv(), RootType::Table(), 0, 0, 4, 4, 4, 1}, + UsedResource{ResourceType::Uav(), RootType::Table(), 8, 0, 4, 4, 4, 1}}, + ComputeIo{5u << 1, {7, 1, 1}}, words); + const vs::ir::Program p = unwrap([&] { return vs::ir::build(native.code, native.wave64, native.vgprs); }); + const vs::resource::Resources res = + unwrap([&] { return vs::resource::track(p, native.layout, native.stage, nullptr); }); + const vs::io::Io io = unwrap([&] { return vs::io::raise(p, native); }); + const vs::structure::Structured st = unwrap([&] { return vs::structure::structure(p); }); + vs::lower::Lowered l = unwrap([&] { return lower_compute(native, p, st, io, res); }); + std::vector<std::uint8_t> dxil = std::move(l.dxil); + if (std::optional<Validator> v = Validator::load(Validator::default_path())) validate_in_place(*v, dxil); + std::optional<vs::host::Host> host; + try { + host.emplace(false); + } catch (const vs::host::Error& e) { + // (Rust skips this silently.) + std::fprintf(stderr, "no SM 6.6 device (%s); the dispatch is skipped\n", e.what()); + return; + } + HostShader cs = host_shader(HwStage::Cs, std::move(dxil)); + cs.user_data = l.user_data; + cs.root_cbvs = l.root_cbvs; + cs.root_srvs = l.root_srvs; + cs.root_uavs = l.root_uavs; + const auto [root, pso] = host->compute_pipeline(cs); + std::vector<std::uint32_t> inputs; + for (float f : {7.0f, 3.0f, -1.0f, 1e-40f, 1.0f, 1e35f, 1e-35f, 1e-36f, 0.0f, 0.0f, -1.0f, 0.0f, -1e35f, 1e35f}) + inputs.push_back(std::bit_cast<std::uint32_t>(f)); + const std::array<vs::host::View, 2> views = {vs::host::View::buffer(inputs, vs::host::Stride::raw()), + vs::host::View::raw_uav(64)}; + vs::host::Dispatch d; + d.roots.emplace_back(0u, vs::host::Root::constants({0, 0, 0, 0, 0})); + d.views = views; + d.groups = {1, 1, 1}; + const std::vector<std::vector<std::uint32_t>> out = host->dispatch(root.Get(), pso.Get(), d); + if (out.empty() || out[0].size() < 7) throw std::logic_error("the UAV holds fewer than 7 dwords"); + std::array<float, 7> got{}; + for (std::size_t k = 0; k < 7; ++k) got[k] = std::bit_cast<float>(out[0][k]); + auto lane = [&](std::size_t k) { + char b[96]; + std::snprintf(b, sizeof b, "lane %zu got %g (%#x)", k, static_cast<double>(got[k]), out[0][k]); + return std::string(b); + }; + // Computed at run time (Rust's f32 arithmetic; MSVC folds a constant overflow with a warning). + volatile float minus_one = -1.0f; + volatile float tiny = 1e-40f; + volatile float zero = 0.0f; + CHECK_MSG(std::fabs(got[0] - 7.0f / 3.0f) < 1e-6f, lane(0)); + CHECK(out[0][1] == std::bit_cast<std::uint32_t>(static_cast<float>(minus_one / tiny))); + CHECK_MSG(std::fabs(got[2] - 1e-35f) <= 1e-40f, lane(2)); + CHECK_MSG(std::fabs(got[3] - 10.0f) < 1e-5f, lane(3)); + CHECK(out[0][4] == 0xFFC0'0000u); + CHECK(out[0][5] == std::bit_cast<std::uint32_t>(static_cast<float>(minus_one / zero))); + CHECK_MSG(std::fabs(got[6] - (-1.0f)) < 1e-6f, lane(6)); +} + +int run_failed = 0; + +void run(const char* name, void (*test)()) { + x2w::vs::lower::test::set_dump_name(std::string("emit__tests__") + name); + const int before = test_util::failures(); + try { + test(); + } catch (const std::exception& e) { + std::fprintf(stderr, "%s: panicked: %s\n", name, e.what()); + ++test_util::failures(); + } + if (test_util::failures() != before) { + ++run_failed; + std::fprintf(stderr, "%s: FAILED\n", name); + } +} + +} // namespace + +#define RUN(test) run(#test, test) + +int main() { + RUN(interpolated_f16_writes_the_op_sel_half_with_modifiers); + RUN(the_clean_up_switch_parses_or_runs_every_pass); + RUN(the_loop_limit_switch_parses_or_falls_back); + RUN(a_stencil_export_declares_the_stencil_ref_feature); + RUN(an_ordered_section_uses_rasterizer_ordered_views); + RUN(immediate_sampler_slots_distinguish_comparison_uses); + RUN(an_exec_high_write_does_not_overflow_the_stack); + RUN(a_mask_whose_high_dword_is_rewritten_is_refused); + RUN(a_backward_permute_reads_the_lane_its_address_names); + RUN(a_carry_in_from_a_divergent_join_is_refused); + RUN(stub_pipeline_is_created); + RUN(constant_color_validates); + RUN(quad_neighbours_at_a_triangles_edge_are_read); + RUN(primitive_export_indices_drop_the_edge_flags); + RUN(edge_flagged_triangles_draw_as_unflagged_ones); + RUN(sample_interpolated_inputs_set_psv_sample_frequency); + RUN(reading_a_channel_below_an_input_element_does_not_underflow); + RUN(scalar_buffer_loads_read_the_same_dwords_one_call_or_four); + RUN(valu_div_f32_sequence_executes_on_gpu); + if (run_failed) std::fprintf(stderr, "mod_test: %d test(s) failed\n", run_failed); + return test_util::finish("mod_test"); +} diff --git a/tests/x2w_shader/emit/opt_test.cpp b/tests/x2w_shader/emit/opt_test.cpp new file mode 100644 index 0000000000..4b4aca3516 --- /dev/null +++ b/tests/x2w_shader/emit/opt_test.cpp @@ -0,0 +1,1148 @@ +// Port of the tests in the upstream Rust module emit/bitcode/opt.rs (#[cfg(test)] mod tests). + +#include <algorithm> +#include <bit> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <exception> +#include <iterator> +#include <optional> +#include <string> +#include <utility> +#include <vector> + +#include "x2w_shader/emit/bitcode.h" +#include "x2w_shader/emit/opt.h" +#include "test_util.h" + +using namespace x2w::vs::bitcode; +using namespace x2w::vs::bitcode::opt; + +namespace { + +using Stores = std::vector<std::vector<V>>; + +// The FNV-1a of each module a test writes, printed to compare with the Rust tests' modules. +const char* current_test = ""; + +// What the Rust tests' modules hash to (cargo test of the upstream shader crate with opt.rs's tests +// printing them), in the order the tests below write them. +constexpr std::uint64_t RUST_WRITTEN[] = { + 0xf684d713293b47f7ull, 0xb05de7565dfe5bdaull, 0x625329b87e8b0c77ull, 0xd741149b576b7948ull, + 0x542e0847305d4c96ull, 0xd0f74cd9b590bd05ull, 0x5d54e661dd1f406dull, 0xe98644c9c0828d03ull, + 0x9569fe82dd5dadc4ull, 0x99daecdb13de1ba1ull, 0xd3a8b267281a6ae0ull, + // mixed_cross_check (added here, see there). + 0x81618006d371acd7ull, +}; +std::size_t written_count = 0; + +void write_and_note(const Module& m) { + std::vector<std::uint8_t> bytes = m.write(); + const std::uint64_t h = test_util::fnv(bytes); + std::printf("%s: written %016llx\n", current_test, (unsigned long long)h); + CHECK(written_count < std::size(RUST_WRITTEN) && RUST_WRITTEN[written_count] == h); + ++written_count; +} + +std::uint64_t mask(std::uint32_t bits) { return bits >= 64 ? ~std::uint64_t(0) : (std::uint64_t(1) << bits) - 1; } + +std::int64_t signed_(std::uint32_t bits, std::uint64_t x) { + if (bits < 64 && ((x >> (bits - 1)) & 1) != 0) return std::int64_t(x | ~mask(bits)); + return std::int64_t(x); +} + +std::optional<std::uint32_t> int_bits(const Module& m, Ty ty) { + const TypeDef& d = m.types.at(ty.id); + if (d.kind == TypeDef::Int) return d.n; + return std::nullopt; +} + +// `main` with one block and a function of each kind of effect. +struct Kit { + Module m; + std::size_t b = 0; + V pure, reads, writes; +}; + +Kit kit() { + Kit k; + Module& m = k.m; + Ty i32t = m.int_(32); + Ty voidt = m.void_(); + Ty fty = m.func_ty(i32t, {i32t, i32t}); + m.ptr(fty); + k.pure = m.function("dx.op.binary.i32", fty, Attr::ReadNone, false); + k.reads = m.function("dx.op.bufferLoad.i32", fty, Attr::ReadOnly, false); + k.writes = m.function("dx.op.bufferStore.i32", fty, Attr::NoUnwind, false); + Ty main_ty = m.func_ty(voidt, {}); + m.ptr(main_ty); + m.function("main", main_ty, std::nullopt, true); + k.b = m.new_block(); + return k; +} + +std::size_t body(const Module& m, std::size_t b) { return m.blocks[b].body.size(); } + +// The operands of each store left in block `b`. +Stores stores(const Module& m, std::size_t b) { + Stores r; + for (std::uint32_t i : m.blocks[b].body) { + const Op& op = m.insts[i].op; + if (op.kind == Op::Call && m.funcs[op.index].name.find("Store") != std::string::npos) r.push_back(op.list); + } + return r; +} + +void unread_results_without_effect_are_dropped() { + Kit k = kit(); + Module& m = k.m; + std::size_t b = k.b; + V one = m.i32(1); + V two = m.i32(2); + V used = m.call(b, k.reads, {one, two}); + V dead = m.call(b, k.reads, {two, one}); + V chain = m.bin(b, Bin::Add, dead, one); + (void)m.call(b, k.pure, {chain, two}); + // A store's result is unread and stays, with what it reads. + V kept = m.bin(b, Bin::Add, used, two); + m.call(b, k.writes, {kept, one}); + m.terminate(b, Term::ret()); + m.optimise(DEAD); + CHECK(body(m, b) == 3); // the load, the add and the store + write_and_note(m); +} + +void branch_conditions_and_phi_cycles() { + Kit k = kit(); + Module& m = k.m; + std::size_t b = k.b; + Ty i32t = m.int_(32); + V zero = m.i32(0); + V one = m.i32(1); + std::size_t head = m.new_block(); + std::size_t exit = m.new_block(); + m.terminate(b, Term::br(head)); + // A counter that decides the branch, and a register that only feeds itself round the loop. + V count = m.phi(head, i32t); + V idle = m.phi(head, i32t); + V next = m.bin(head, Bin::Add, count, one); + V idle_next = m.call(head, k.reads, {idle, one}); + V more = m.cmp(head, pred::IULT, next, one); + m.terminate(head, Term::cond_br(more, head, exit)); + m.set_phi(count, {{zero, b}, {next, head}}); + m.set_phi(idle, {{zero, b}, {idle_next, head}}); + m.call(exit, k.writes, {zero, one}); + m.terminate(exit, Term::ret()); + m.optimise(DEAD); + CHECK(m.blocks[head].phis.size() == 1); // the counter + CHECK(body(m, head) == 2); // the step and the test + CHECK(body(m, exit) == 1); + write_and_note(m); +} + +void wave_operations_have_no_effect_of_their_own() { + Kit k = kit(); + Ty i32t = k.m.int_(32); + Ty fty = k.m.func_ty(i32t, {i32t, i32t}); + V first = k.m.function("dx.op.waveReadLaneFirst.i32", fty, Attr::NoUnwind, false); + V barrier = k.m.function("dx.op.barrier", fty, Attr::NoDuplicate, false); + V one = k.m.i32(1); + k.m.call(k.b, first, {one, one}); + k.m.call(k.b, barrier, {one, one}); + k.m.terminate(k.b, Term::ret()); + k.m.optimise(DEAD); + CHECK(body(k.m, k.b) == 1); // the barrier + // The declarations nothing calls any more are gone, and the call that stayed names its + // function by the new number. + std::vector<std::string> names; + for (const Func& f : k.m.funcs) names.push_back(f.name); + CHECK((names == std::vector<std::string>{"main", "dx.op.barrier"})); + const Op& op = k.m.insts[k.m.blocks[k.b].body[0]].op; + CHECK(op.kind == Op::Call); + if (op.kind == Op::Call) CHECK(k.m.funcs[op.index].name == "dx.op.barrier"); + write_and_note(k.m); +} + +void constants_and_identities_fold() { + Kit kt = kit(); + Module& m = kt.m; + std::size_t b = kt.b; + Ty i32t = m.int_(32); + Ty f32t = m.float_(); + V zero = m.i32(0); + V one = m.i32(1); + V all = m.i32(0xFFFFFFFFu); + V x = m.call(b, kt.reads, {one, one}); + // x + 0, -1 & x, x >> 0, x * 1, x | x: all x. + V a = m.bin(b, Bin::Add, x, zero); + a = m.bin(b, Bin::And, all, a); + a = m.bin(b, Bin::LShr, a, zero); + a = m.bin(b, Bin::Mul, a, one); + a = m.bin(b, Bin::Or, a, a); + // There and back. + V f = m.cast(b, Cast::Bitcast, a, f32t); + a = m.cast(b, Cast::Bitcast, f, i32t); + // Constants: (262168 >> 16) & 127 = 4, 7 & 31 = 7, -8 >>s 1 = -4. + V k = m.i32(262168); + V sixteen = m.i32(16); + k = m.bin(b, Bin::LShr, k, sixteen); + V k127 = m.i32(127); + k = m.bin(b, Bin::And, k, k127); + V minus8 = m.i32(std::uint32_t(-8)); + V s = m.bin(b, Bin::AShr, minus8, one); + // A shift by the width is left alone. + V k32 = m.i32(32); + V wide = m.bin(b, Bin::Shl, one, k32); + // A select between a value and itself, and on a constant. + V c = m.cmp(b, pred::IULT, zero, one); + V sel = m.select(b, c, a, wide); + V same = m.select(b, c, sel, sel); + m.call(b, kt.writes, {same, k}); + m.call(b, kt.writes, {s, wide}); + m.terminate(b, Term::ret()); + m.optimise(FOLD | DEAD); + CHECK(body(m, b) == 4); // the read, the wide shift and two stores + V four = m.i32(4); + V minus4 = m.i32(std::uint32_t(-4)); + CHECK((stores(m, b) == Stores{{x, four}, {minus4, wide}})); + write_and_note(m); +} + +void float_arithmetic_is_not_folded() { + Kit kt = kit(); + Module& m = kt.m; + std::size_t b = kt.b; + Ty f32t = m.float_(); + Ty fty = m.func_ty(f32t, {f32t, f32t}); + V input = m.function("dx.op.loadInput.f32", fty, Attr::ReadNone, false); + V zero = m.f32(0); + V one = m.f32(std::bit_cast<std::uint32_t>(1.0f)); + V two = m.f32(std::bit_cast<std::uint32_t>(2.0f)); + V x = m.call(b, input, {zero, zero}); + V y = m.call(b, input, {one, one}); + V a = m.bin(b, Bin::Add, x, zero); + V p = m.bin(b, Bin::Mul, a, one); + // The same sum the other way round is another instruction. + V xy = m.bin(b, Bin::Add, x, y); + V yx = m.bin(b, Bin::Add, y, x); + // Constants compare here: 1 < 2, and nothing equals a NaN. + V nan = m.f32(0x7FC00000u); // f32::NAN.to_bits() + V lt = m.cmp(b, pred::OLT, one, two); + V eq = m.cmp(b, pred::OEQ, nan, nan); + V une = m.cmp(b, pred::UNE, nan, one); + V sel = m.select(b, lt, xy, yx); + sel = m.select(b, eq, p, sel); + sel = m.select(b, une, sel, p); + m.call(b, kt.writes, {sel, p}); + m.terminate(b, Term::ret()); + m.optimise(ALL); + // Two inputs, x + 0.0, * 1.0, x + y and the store: y + x and the selects are gone. + CHECK(body(m, b) == 6); + CHECK((stores(m, b) == Stores{{xy, p}})); + write_and_note(m); +} + +// entry: `c = x < y`, branch to `then` or `other`, which join. +struct Diamond { + Kit k; + V x, y, c; + std::size_t then = 0, other = 0, join = 0; +}; + +Diamond diamond() { + Diamond d; + d.k = kit(); + Kit& k = d.k; + V one = k.m.i32(1); + V two = k.m.i32(2); + d.x = k.m.call(k.b, k.reads, {one, one}); + d.y = k.m.call(k.b, k.reads, {two, two}); + d.c = k.m.cmp(k.b, pred::IULT, d.x, d.y); + d.then = k.m.new_block(); + d.other = k.m.new_block(); + d.join = k.m.new_block(); + k.m.terminate(k.b, Term::cond_br(d.c, d.then, d.other)); + k.m.terminate(d.then, Term::br(d.join)); + k.m.terminate(d.other, Term::br(d.join)); + k.m.terminate(d.join, Term::ret()); + return d; +} + +void a_value_is_reused_below_its_block_and_not_beside_it() { + Diamond d = diamond(); + Module& m = d.k.m; + std::size_t b = d.k.b; + V x = d.x, y = d.y; + // The entry's value again in a branch; a branch's value again in the other branch and in the + // join (neither is on every path). + V top = m.call(b, d.k.pure, {x, y}); + m.call(b, d.k.writes, {top, top}); + V again = m.call(d.then, d.k.pure, {x, y}); + V side = m.bin(d.then, Bin::Add, y, x); + m.call(d.then, d.k.writes, {again, side}); + V beside = m.bin(d.other, Bin::Add, x, y); + m.call(d.other, d.k.writes, {beside, beside}); + V after = m.bin(d.join, Bin::Add, x, y); + m.call(d.join, d.k.writes, {after, after}); + m.optimise(REUSE); + CHECK((stores(m, d.then) == Stores{{top, side}})); + CHECK(body(m, d.then) == 2); + CHECK(body(m, d.other) == 2); + CHECK(body(m, d.join) == 2); + write_and_note(m); +} + +void a_branch_taken_says_what_its_condition_is() { + { + Diamond dm = diamond(); + Module& m = dm.k.m; + std::size_t b = dm.k.b; + V x = dm.x, y = dm.y, c = dm.c; + V three = m.i32(3); + V d = m.call(b, dm.k.reads, {three, three}); + d = m.cmp(b, pred::NE, d, three); + V both = m.bin(b, Bin::And, c, d); + // Behind the branch: the condition again (a guard), its opposite comparison, and a + // guarded write. + V guard = m.bin(dm.then, Bin::And, c, d); + V old = m.select(dm.then, guard, x, y); + V not_ = m.cmp(dm.then, pred::IUGE, x, y); + V nw = m.select(dm.then, not_, y, old); + m.call(dm.then, dm.k.writes, {nw, nw}); + V kept = m.select(dm.other, c, x, y); + m.call(dm.other, dm.k.writes, {kept, kept}); + // After the join nothing is known. + V open = m.select(dm.join, c, x, y); + m.call(dm.join, dm.k.writes, {open, open}); + m.optimise(FOLD | FACTS); + // then: select(d, x, y) and the store; other: y is stored. + CHECK(body(m, dm.then) == 2); + Stores st = stores(m, dm.then); + CHECK(!st.empty() && st[0][0].kind == V::Inst); + if (!st.empty() && st[0][0].kind == V::Inst) { + const Op& op = m.insts[st[0][0].i].op; + CHECK(op.kind == Op::Select && op.a == d && op.b == x && op.c == y); + } + CHECK((stores(m, dm.other) == Stores{{y, y}})); + CHECK(body(m, dm.join) == 2); + (void)both; + write_and_note(m); + } + // Both terms of an `and` that held hold behind it. + { + Diamond dm = diamond(); + Module& m = dm.k.m; + std::size_t b = dm.k.b; + V x = dm.x, y = dm.y, c = dm.c; + V three = m.i32(3); + V d = m.call(b, dm.k.reads, {three, three}); + d = m.cmp(b, pred::NE, d, three); + V both = m.bin(b, Bin::And, c, d); + std::size_t inner = m.new_block(); + std::size_t out = m.new_block(); + m.terminate(b, Term::cond_br(both, inner, out)); + V a = m.select(inner, c, x, y); + V z = m.select(inner, d, a, y); + m.call(inner, dm.k.writes, {z, z}); + m.terminate(inner, Term::br(out)); + // Where the `and` did not hold either term may. + V w = m.select(out, d, x, y); + m.call(out, dm.k.writes, {w, w}); + m.terminate(out, Term::ret()); + m.optimise(FOLD | FACTS); + CHECK((stores(m, inner) == Stores{{x, x}})); + CHECK(body(m, out) == 2); + write_and_note(m); + } +} + +void a_branch_on_a_constant_goes_one_way() { + Diamond dm = diamond(); + Module& m = dm.k.m; + V x = dm.x, y = dm.y, c = dm.c; + Ty i32t = m.int_(32); + // Behind the branch the same test again: its other side is never run, and the join behind it + // has one value. + std::size_t deep = m.new_block(); + std::size_t never = m.new_block(); + std::size_t meet = m.new_block(); + m.terminate(dm.then, Term::cond_br(c, deep, never)); + m.terminate(deep, Term::br(meet)); + m.call(never, dm.k.writes, {y, y}); + m.terminate(never, Term::br(meet)); + V p = m.phi(meet, i32t); + m.set_phi(p, {{x, deep}, {y, never}}); + m.call(meet, dm.k.writes, {p, p}); + m.terminate(meet, Term::br(dm.join)); + V q = m.phi(dm.join, i32t); + m.set_phi(q, {{p, meet}, {y, dm.other}}); + m.call(dm.join, dm.k.writes, {q, q}); + m.optimise(ALL); + const auto& t = m.blocks[dm.then].term; + CHECK(t && t->kind == Term::Br && t->t == deep); + CHECK((stores(m, meet) == Stores{{x, x}})); + CHECK(m.blocks[meet].phis.empty()); + CHECK(body(m, never) == 0); // emptied: nothing reaches it + CHECK(!m.blocks[dm.join].phis.empty()); + if (!m.blocks[dm.join].phis.empty()) { + const Op& op = m.insts[m.blocks[dm.join].phis[0]].op; + CHECK(op.kind == Op::Phi); + std::vector<std::pair<V, std::size_t>> want = {{x, meet}, {y, dm.other}}; + CHECK(op.incoming == want); + } + write_and_note(m); +} + +void a_read_is_reused_within_its_block_until_a_store() { + Diamond dm = diamond(); + Module& m = dm.k.m; + std::size_t b = dm.k.b; + V x = dm.x, y = dm.y; + std::size_t then = dm.then; + Ty i32t = m.int_(32); + // The entry reads (1, 1) for x: again in the entry it is x; in the next block it is read + // again. + V one = m.i32(1); + V again = m.call(b, dm.k.reads, {one, one}); + m.call(b, dm.k.writes, {again, y}); + V after = m.call(b, dm.k.reads, {one, one}); + V twice = m.call(b, dm.k.reads, {one, one}); + V sum = m.bin(b, Bin::Add, after, twice); + m.call(b, dm.k.writes, {sum, sum}); + V below = m.call(then, dm.k.reads, {one, one}); + m.call(then, dm.k.writes, {below, below}); + // A constant buffer cannot change: one load for the function. + Ty cfty = m.func_ty(i32t, {i32t, i32t}); + V cb = m.function("dx.op.cbufferLoadLegacy.i32", cfty, Attr::ReadOnly, false); + V top = m.call(b, cb, {one, one}); + m.call(b, dm.k.writes, {top, top}); + V under = m.call(then, cb, {one, one}); + m.call(then, dm.k.writes, {under, under}); + m.optimise(REUSE | LOADS); + Stores st = stores(m, b); + CHECK(st.size() == 3); + if (st.size() == 3) { + CHECK((st[0] == std::vector<V>{x, y})); // the second read is the first + CHECK(st[1][0].kind == V::Inst); + if (st[1][0].kind == V::Inst) { + // Read again after the store, once. + const Op& op = m.insts[st[1][0].i].op; + CHECK(op.kind == Op::Bin && op.code == std::uint8_t(Bin::Add) && op.a == after && op.b == after); + } + CHECK((st[2] == std::vector<V>{top, top})); + } + CHECK((stores(m, then) == Stores{{below, below}, {top, top}})); + write_and_note(m); +} + +void a_join_of_one_value_and_two_equal_joins() { + Diamond dm = diamond(); + Module& m = dm.k.m; + V x = dm.x, y = dm.y; + Ty i32t = m.int_(32); + V one = m.phi(dm.join, i32t); + m.set_phi(one, {{x, dm.then}, {x, dm.other}}); + V p = m.phi(dm.join, i32t); + m.set_phi(p, {{x, dm.then}, {y, dm.other}}); + V q = m.phi(dm.join, i32t); + m.set_phi(q, {{y, dm.other}, {x, dm.then}}); + m.call(dm.join, dm.k.writes, {one, p}); + V sum = m.bin(dm.join, Bin::Add, p, q); + m.call(dm.join, dm.k.writes, {sum, q}); + m.optimise(FOLD | REUSE); + CHECK((m.blocks[dm.join].phis == std::vector<std::uint32_t>{p.i})); + Stores st = stores(m, dm.join); + CHECK(st.size() == 2); + if (st.size() == 2) { + CHECK((st[0] == std::vector<V>{x, p})); + CHECK(st[1][1] == p); + } + write_and_note(m); +} + +// Not in opt.rs: a module through the paths the tests above do not reach (constant tables, shared +// memory, loads, stores, atomics, i64 and i8 folds, metadata, bounded, float_k, usage), with the +// values the same module gives in Rust (the identical test added to a scratch copy of opt.rs). +std::string bits_line(const std::vector<std::optional<float>>& fs) { + std::string line; + char buf[16]; + for (const auto& f : fs) { + if (f) { + std::snprintf(buf, sizeof buf, " %08x", std::bit_cast<std::uint32_t>(*f)); + line += buf; + } else { + line += " none"; + } + } + return line; +} + +std::string usage_line(const Usage& u) { + std::string s; + for (bool x : {u.wave_ops, u.rovs, u.int64, u.typed_uav_loads, u.heap_views, u.heap_samplers, u.atomic64}) + s += x ? '1' : '0'; + return s; +} + +void mixed_cross_check() { + Kit kt = kit(); + std::size_t b = kt.b; + Module& m = kt.m; + Ty i32t = m.int_(32); + Ty i64t = m.int_(64); + Ty i8t = m.int_(8); + Ty f32t = m.float_(); + Ty arr = m.array(4, i32t); + V one = m.i32(1); + V two = m.i32(2); + V three = m.i32(3); + V table_init = m.aggregate(arr, {one, two, three, one}); + V table = m.constant_global("table", table_init); + V unused_init = m.aggregate(arr, {two, two, two, two}); + (void)m.constant_global("unused", unused_init); + V shared = m.global("shared", arr, 3); + V x = m.call(b, kt.reads, {one, two}); + V e = m.element(b, table, x); + V l1 = m.load(b, e); + V e2 = m.element(b, table, x); + V l2 = m.load(b, e2); + V s = m.element(b, shared, one); + V sl = m.load(b, s); + m.store(b, s, l1); + V sl2 = m.load(b, s); + V at = m.atomic(b, Rmw::Add, s, l2); + V cx = m.cmpxchg(b, s, at, sl); + V k64a = m.int_const(i64t, -5); + V k64b = m.int_const(i64t, 3); + V q = m.bin(b, Bin::UDiv, k64a, k64b); + V r = m.bin(b, Bin::URem, k64a, k64b); + V k8 = m.i8(200); + V sx = m.cast(b, Cast::SExt, k8, i32t); + V tr = m.cast(b, Cast::Trunc, sx, i8t); + V zx = m.cast(b, Cast::ZExt, tr, i32t); + V w = m.cast(b, Cast::Trunc, q, i32t); + V w2 = m.cast(b, Cast::Trunc, r, i32t); + V z64 = m.cast(b, Cast::ZExt, x, i64t); + V t32 = m.cast(b, Cast::Trunc, z64, i32t); + V sum = m.bin(b, Bin::Add, sl2, cx); + sum = m.bin(b, Bin::Add, sum, zx); + sum = m.bin(b, Bin::Add, sum, w); + sum = m.bin(b, Bin::Add, sum, w2); + sum = m.bin(b, Bin::Add, sum, t32); + m.call(b, kt.writes, {sum, sl}); + Ty fty1 = m.func_ty(f32t, {i32t, f32t}); + Ty fty2 = m.func_ty(f32t, {i32t, f32t, f32t}); + Ty fty3 = m.func_ty(f32t, {i32t, f32t, f32t, f32t}); + V unary = m.function("dx.op.unary.f32", fty1, Attr::ReadNone, false); + V binary = m.function("dx.op.binary.f32", fty2, Attr::ReadNone, false); + V tertiary = m.function("dx.op.tertiary.f32", fty3, Attr::ReadNone, false); + Ty wty = m.func_ty(i32t, {i32t, i32t}); + V wave = m.function("dx.op.waveActiveOp.i32", wty, Attr::NoUnwind, false); + V half = m.f32(std::bit_cast<std::uint32_t>(0.5f)); + V big = m.f32(std::bit_cast<std::uint32_t>(1000.0f)); + V fx = m.cast(b, Cast::UiToFp, x, f32t); + V c6 = m.i32(6); + V c7 = m.i32(7); + V c13 = m.i32(13); + V c35 = m.i32(35); + V c36 = m.i32(36); + V c46 = m.i32(46); + V sat = m.call(b, unary, {c7, fx}); + V ab = m.call(b, unary, {c6, fx}); + V sin = m.call(b, unary, {c13, ab}); + V mx = m.call(b, binary, {c35, fx, half}); + V mn = m.call(b, binary, {c36, mx, big}); + V mad = m.call(b, tertiary, {c46, fx, half, big}); + V mul = m.bin(b, Bin::Mul, mad, sat); + V add = m.bin(b, Bin::Add, mul, mn); + V bi = m.cast(b, Cast::Bitcast, sin, i32t); + V bf = m.cast(b, Cast::Bitcast, bi, f32t); + V ldf = m.cast(b, Cast::Bitcast, x, f32t); + V mx2 = m.call(b, binary, {c35, ldf, half}); + V mn2 = m.call(b, binary, {c36, mx2, big}); + V kf = m.cast(b, Cast::Bitcast, three, f32t); + V sel = m.select(b, sl, add, mn2); + V wv = m.call(b, wave, {x, one}); + V out = m.cast(b, Cast::Bitcast, sel, i32t); + V out2 = m.cast(b, Cast::Bitcast, bf, i32t); + m.call(b, kt.writes, {out, out2}); + m.call(b, kt.writes, {wv, wv}); + Md mv1 = m.md_value(table); + Md mv2 = m.md_value(kt.pure); + Md node = m.md_node({mv1, mv2}); + m.named_md("cross", {node}); + m.terminate(b, Term::ret()); + std::vector<std::optional<float>> bounds; + for (V v : {sat, ab, sin, mx, mn, mad, mul, add, bf, mn2, fx, ldf, kf, sel, half, big}) bounds.push_back(m.bounded(v, 8)); + std::string line = bits_line(bounds); + std::printf("mixed bounded:%s\n", line.c_str()); + CHECK(line == " 00000000 42000000 00000000 42000000 42000000 42000000 42000000 42040000 00000000 41200000 " + "42000000 none c2c60000 42040000 bf800000 41200000"); + std::vector<std::optional<float>> ks; + for (V v : {half, big, kf, ldf, three}) ks.push_back(m.float_k(v)); + line = bits_line(ks); + std::printf("mixed float_k:%s\n", line.c_str()); + CHECK(line == " 3f000000 447a0000 00000003 none none"); + CHECK(usage_line(m.usage()) == "1011000"); + m.optimise(ALL); + CHECK(usage_line(m.usage()) == "1001000"); + CHECK(m.globals.size() == 2); + CHECK(m.funcs.size() == 8); + CHECK(body(m, b) == 34); + write_and_note(m); +} + +// ---- the passes against an interpreter, on random programs ---- + +using Trace = std::vector<std::pair<std::string, std::vector<std::uint64_t>>>; + +// Runs `m` on `inputs`: the stores it makes, in order (and how it ended). Reads a value before its +// definition ran: a panic. +Trace run(const Module& m, const std::vector<std::uint32_t>& inputs) { + std::vector<std::optional<std::uint64_t>> vals(m.insts.size()); + std::uint64_t memory[16] = {}; + Trace trace; + auto eval = [&](V v) -> std::uint64_t { + switch (v.kind) { + case V::Inst: { + const auto& x = vals.at(v.i); + if (!x) bug("a value defined before its use"); + return *x; + } + case V::Const: { + const auto& [ty, c] = m.consts.at(v.i); + auto bits = int_bits(m, ty); + if (c.kind == Const::Int && bits) return std::uint64_t(c.value) & mask(*bits); + if (c.kind == Const::Float) return std::uint64_t(c.bits); + return 0; + } + default: + bug("a global or function as a value"); + } + }; + std::size_t b = 0, from = ~std::size_t(0); + for (int step = 0; step < 4000; ++step) { + const Block& blk = m.blocks.at(b); + // Joins take their values together, before any is assigned. + std::vector<std::pair<std::uint32_t, std::uint64_t>> joined; + for (std::uint32_t p : blk.phis) { + const Op& op = m.insts[p].op; + if (op.kind != Op::Phi) bug("a join"); + auto it = std::find_if(op.incoming.begin(), op.incoming.end(), [&](const auto& x) { return x.second == from; }); + if (it == op.incoming.end()) bug("a value for the edge taken"); + joined.emplace_back(p, eval(it->first)); + } + for (const auto& [p, x] : joined) vals[p] = x; + for (std::uint32_t i : blk.body) { + const Inst& inst = m.insts[i]; + const auto bits = int_bits(m, inst.ty); + auto fl = [](std::uint64_t x) { return std::bit_cast<float>(std::uint32_t(x)); }; + std::uint64_t r = 0; + const Op& op = inst.op; + switch (op.kind) { + case Op::Bin: { + std::uint64_t x = eval(op.a); + std::uint64_t y = eval(op.b); + if (bits) { + std::uint64_t z; + switch (Bin(op.code)) { + case Bin::Add: + z = x + y; + break; + case Bin::Sub: + z = x - y; + break; + case Bin::Mul: + z = x * y; + break; + case Bin::And: + z = x & y; + break; + case Bin::Or: + z = x | y; + break; + case Bin::Xor: + z = x ^ y; + break; + case Bin::Shl: + if (y >= 64) bug("shift overflow"); + z = x << y; + break; + case Bin::LShr: + if (y >= 64) bug("shift overflow"); + z = x >> y; + break; + case Bin::AShr: + if (y >= 64) bug("shift overflow"); + z = std::uint64_t(signed_(*bits, x) >> y); + break; + default: + bug("no divisions here"); + } + r = z & mask(*bits); + } else { + float fx = fl(x), fy = fl(y); + float z; + switch (Bin(op.code)) { + case Bin::Add: + z = fx + fy; + break; + case Bin::Sub: + z = fx - fy; + break; + default: + z = fx * fy; + break; + } + r = std::uint64_t(std::bit_cast<std::uint32_t>(z)); + } + break; + } + case Op::Cmp: { + const auto wide = int_bits(m, m.type_of(op.a)); + std::uint64_t x = eval(op.a); + std::uint64_t y = eval(op.b); + const std::uint8_t p = op.code; + bool holds; + if (wide) { + std::int64_t sx = signed_(*wide, x), sy = signed_(*wide, y); + switch (p) { + case pred::EQ: + holds = x == y; + break; + case pred::NE: + holds = x != y; + break; + case pred::IUGT: + holds = x > y; + break; + case pred::IUGE: + holds = x >= y; + break; + case pred::IULT: + holds = x < y; + break; + case pred::IULE: + holds = x <= y; + break; + case pred::SGT: + holds = sx > sy; + break; + case pred::SGE: + holds = sx >= sy; + break; + case pred::SLT: + holds = sx < sy; + break; + default: + holds = sx <= sy; + break; + } + } else { + float fx = fl(x), fy = fl(y); + if (std::isnan(fx) || std::isnan(fy)) + holds = (p & 8) != 0; + else + holds = ((p & 1) != 0 && fx == fy) || ((p & 2) != 0 && fx > fy) || ((p & 4) != 0 && fx < fy); + } + r = holds ? 1 : 0; + break; + } + case Op::Select: + r = eval(op.a) != 0 ? eval(op.b) : eval(op.c); + break; + case Op::Cast: { + const auto from_bits = int_bits(m, m.type_of(op.a)); + std::uint64_t x = eval(op.a); + const Cast co = Cast(op.code); + if (co == Cast::Bitcast || co == Cast::ZExt) + r = x; + else if (co == Cast::SExt && from_bits && bits) + r = std::uint64_t(signed_(*from_bits, x)) & mask(*bits); + else if (co == Cast::Trunc && bits) + r = x & mask(*bits); + else + bug("a cast the generator does not make"); + break; + } + case Op::Call: { + std::vector<std::uint64_t> a; + for (V v : op.list) a.push_back(eval(v)); + const std::string& name = m.funcs.at(op.index).name; + if (name == "dx.op.loadInput.i32") { + r = inputs[std::size_t(a.at(0) ^ a.at(1)) % inputs.size()]; + } else if (name == "dx.op.binary.i32") { + r = std::min(a.at(0), a.at(1)); + } else if (name == "dx.op.cbufferLoadLegacy.i32") { + r = std::rotl(inputs[std::size_t(a.at(0)) % inputs.size()], int(std::uint32_t(a.at(1)) & 31)); + } else if (name == "dx.op.bufferLoad.i32") { + r = memory[std::size_t(a.at(0) ^ a.at(1)) % 16]; + } else if (name == "dx.op.waveReadLaneFirst.i32") { + r = a.at(0) ^ a.at(1); + } else { + memory[std::size_t(a.at(0)) % 16] = a.at(1); + trace.emplace_back(name, a); + r = 0; + } + break; + } + default: + bug("an instruction the generator does not make"); + } + vals[i] = r; + } + from = b; + if (!blk.term) bug("a terminator"); + const Term& t = *blk.term; + switch (t.kind) { + case Term::Ret: + trace.emplace_back("ret", std::vector<std::uint64_t>{}); + return trace; + case Term::Br: + b = t.t; + break; + case Term::CondBr: + b = eval(t.cond) != 0 ? t.t : t.f; + break; + } + } + trace.emplace_back("still running", std::vector<std::uint64_t>{}); + return trace; +} + +// A random structured program over a few registers, as the lowering makes them: every register +// joined at every join, conditions tested again behind their branch, values computed again. +struct Gen { + Kit k; + std::uint64_t rng = 0; + std::vector<V> regs; + std::vector<V> conds; + std::size_t cur = 0; + V input, table, wave; + // The operands of the block's last read (to read the place again, and to store to it). + std::optional<std::pair<V, V>> last; + + std::uint64_t next(std::uint64_t n) { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + return (rng >> 11) % n; + } + + V reg() { + std::size_t n = std::size_t(next(regs.size())); + return regs[n]; + } + + // A register or a small constant. + V value() { + if (next(4) == 0) { + static constexpr std::uint32_t ks[] = {0u, 1, 2, 31, 0xFFFFFFFFu, 0x80000000u, 7}; + std::uint32_t kv = ks[next(7)]; + return k.m.i32(kv); + } + return reg(); + } + + V cond() { + const std::size_t c = cur; + V made; + const std::uint64_t pick = next(6); + if (pick == 0 && !conds.empty()) { + std::size_t n = std::size_t(next(conds.size())); + return conds[n]; + } else if (pick == 1 && conds.size() > 1) { + std::uint64_t a = next(conds.size()); + std::uint64_t b = next(conds.size()); + static constexpr Bin ops[] = {Bin::And, Bin::Or, Bin::Xor}; + Bin op = ops[next(3)]; + made = k.m.bin(c, op, conds[a], conds[b]); + } else if (pick == 2 && !conds.empty()) { + std::size_t n = std::size_t(next(conds.size())); + V t = k.m.bool_(true); + made = k.m.bin(c, Bin::Xor, conds[n], t); + } else { + std::uint8_t p = std::uint8_t(pred::EQ + std::uint8_t(next(10))); + V x = reg(); + V y = value(); + made = k.m.cmp(c, p, x, y); + } + conds.push_back(made); + return made; + } + + void statement() { + const std::size_t c = cur; + const std::size_t d = std::size_t(next(regs.size())); + Ty i32t = k.m.int_(32); + Ty f32t = k.m.float_(); + V r; + const std::uint64_t pick = next(14); + if (pick <= 3) { + static constexpr Bin ops[] = {Bin::Add, Bin::Sub, Bin::Mul, Bin::And, Bin::Or, Bin::Xor}; + Bin op = ops[next(6)]; + V x = value(); + V y = value(); + r = k.m.bin(c, op, x, y); + } else if (pick == 4) { + static constexpr Bin ops[] = {Bin::Shl, Bin::LShr, Bin::AShr}; + Bin op = ops[next(3)]; + V x = value(); + std::uint32_t by = std::uint32_t(next(32)); + V byv = k.m.i32(by); + r = k.m.bin(c, op, x, byv); + } else if (pick == 5 || pick == 6) { + // A guarded write: the old value where the guard fails. + V g = cond(); + V x = value(); + r = k.m.select(cur, g, x, regs[d]); + } else if (pick == 7) { + V x = value(); + V y = value(); + const V fs[] = {k.pure, input, table, wave}; + V f = fs[next(4)]; + r = k.m.call(c, f, {x, y}); + } else if (pick == 8 || pick == 9) { + const bool again = next(2) == 0; + V x, y; + if (last && again) { + x = last->first; + y = last->second; + } else { + x = value(); + y = value(); + } + last = std::make_pair(x, y); + r = k.m.call(c, k.reads, {x, y}); + } else if (pick == 10) { + // A store, half the time to the place read last. + V x = value(); + V y = value(); + const bool there = next(2) == 0; + if (last && there) x = k.m.bin(c, Bin::Xor, last->first, last->second); + k.m.call(c, k.writes, {x, y}); + return; + } else if (pick == 11) { + // Float arithmetic, read back as bits. + V x = value(); + V y = value(); + V fx = k.m.cast(c, Cast::Bitcast, x, f32t); + V fy = k.m.cast(c, Cast::Bitcast, y, f32t); + static constexpr Bin ops[] = {Bin::Add, Bin::Sub, Bin::Mul}; + Bin op = ops[next(3)]; + V f = k.m.bin(c, op, fx, fy); + if (next(2) == 0) { + std::uint8_t p = std::uint8_t(next(16)); + V t = k.m.cmp(c, p, f, fy); + conds.push_back(t); + } + r = k.m.cast(c, Cast::Bitcast, f, i32t); + } else if (pick == 12) { + V g = cond(); + r = k.m.cast(cur, Cast::ZExt, g, i32t); + } else { + V x = value(); + V f = k.m.cast(c, Cast::Bitcast, x, f32t); + r = k.m.cast(c, Cast::Bitcast, f, i32t); + } + regs[d] = r; + } + + void code(std::uint32_t depth) { + const std::uint64_t n = 1 + next(6); + for (std::uint64_t s = 0; s < n; ++s) { + const std::uint64_t pick = next(8); + if ((pick == 0 || pick == 1) && depth > 0) + branch(depth - 1); + else if (pick == 2 && depth > 0) + repeat(depth - 1); + else + statement(); + } + } + + // if / else, every register joined. + void branch(std::uint32_t depth) { + V c = cond(); + Ty i32t = k.m.int_(32); + std::size_t then = k.m.new_block(); + std::size_t other = k.m.new_block(); + std::size_t join = k.m.new_block(); + k.m.terminate(cur, Term::cond_br(c, then, other)); + std::vector<V> before = regs; + const std::size_t known = conds.size(); + cur = then; + last.reset(); + code(depth); + std::vector<V> then_regs = std::exchange(regs, before); + const std::size_t then_end = cur; + k.m.terminate(then_end, Term::br(join)); + conds.resize(std::min(conds.size(), known)); + cur = other; + last.reset(); + if (next(3) != 0) code(depth); + const std::size_t other_end = cur; + k.m.terminate(other_end, Term::br(join)); + conds.resize(std::min(conds.size(), known)); + for (std::size_t r = 0; r < then_regs.size(); ++r) { + V p = k.m.phi(join, i32t); + k.m.set_phi(p, {{then_regs[r], then_end}, {regs[r], other_end}}); + regs[r] = p; + } + cur = join; + last.reset(); + } + + // A loop that runs at most a few times, every register joined at its head. + void repeat(std::uint32_t depth) { + Ty i32t = k.m.int_(32); + std::size_t head = k.m.new_block(); + std::size_t exit = k.m.new_block(); + const std::size_t before = cur; + k.m.terminate(before, Term::br(head)); + std::vector<V> entering = regs; + std::vector<V> joins; + for (std::size_t r = 0; r < regs.size(); ++r) joins.push_back(k.m.phi(head, i32t)); + V count = k.m.phi(head, i32t); + regs = joins; + const std::size_t known = conds.size(); + cur = head; + last.reset(); + code(depth); + V one = k.m.i32(1); + V nx = k.m.bin(cur, Bin::Add, count, one); + std::uint32_t limit = 1 + std::uint32_t(next(3)); + V limitv = k.m.i32(limit); + V more = k.m.cmp(cur, pred::IULT, nx, limitv); + if (next(2) == 0) { + V c = cond(); + more = k.m.bin(cur, Bin::And, more, c); + } + const std::size_t latch = cur; + k.m.terminate(latch, Term::cond_br(more, head, exit)); + for (std::size_t r = 0; r < joins.size(); ++r) k.m.set_phi(joins[r], {{entering[r], before}, {regs[r], latch}}); + V zero = k.m.i32(0); + k.m.set_phi(count, {{zero, before}, {nx, latch}}); + conds.resize(std::min(conds.size(), known)); + cur = exit; + last.reset(); + } +}; + +Module random_program(std::uint64_t seed) { + Gen g; + g.k = kit(); + Ty i32t = g.k.m.int_(32); + Ty fty = g.k.m.func_ty(i32t, {i32t, i32t}); + g.input = g.k.m.function("dx.op.loadInput.i32", fty, Attr::ReadNone, false); + g.table = g.k.m.function("dx.op.cbufferLoadLegacy.i32", fty, Attr::ReadOnly, false); + g.wave = g.k.m.function("dx.op.waveReadLaneFirst.i32", fty, Attr::NoUnwind, false); + const std::size_t b = g.k.b; + g.rng = (seed * 0x9E3779B97F4A7C15ull) | 1; + g.cur = b; + for (std::uint32_t r = 0; r < 5; ++r) { + V x = g.k.m.i32(r); + V y = g.k.m.i32(r * 3); + V v = g.k.m.call(b, g.input, {x, y}); + g.regs.push_back(v); + } + g.code(3); + g.code(2); + // Every register is read at the end. + for (std::size_t r = 0; r < g.regs.size(); ++r) { + V at = g.k.m.i32(std::uint32_t(r)); + g.k.m.call(g.cur, g.k.writes, {at, g.regs[r]}); + } + g.k.m.terminate(g.cur, Term::ret()); + return std::move(g.k.m); +} + +void every_pass_leaves_what_random_programs_store() { + std::size_t removed = 0; + std::uint64_t hash = 0xcbf29ce484222325ull; + for (std::uint64_t seed = 1; seed <= 400; ++seed) { + Module plain = random_program(seed); + std::vector<std::vector<std::uint32_t>> inputs; + for (std::uint32_t n = 0; n < 6; ++n) { + std::vector<std::uint32_t> in; + for (std::uint32_t i = 0; i < 7; ++i) { + switch (n) { + case 0: + in.push_back(0); + break; + case 1: + in.push_back(i); + break; + case 2: + in.push_back(0xFFFFFFFFu - i); + break; + default: + in.push_back(std::rotl((std::uint32_t(seed) ^ n) * 0x9E3779B9u, int(i * 5)) ^ (i << 28)); + break; + } + } + inputs.push_back(std::move(in)); + } + std::vector<Trace> expected; + for (const auto& in : inputs) expected.push_back(run(plain, in)); + std::size_t written = 0; + for (const Block& blk : plain.blocks) written += blk.body.size() + blk.phis.size(); + for (std::uint32_t passes : {DEAD, FOLD, REUSE, FACTS, LOADS, FOLD | FACTS, FOLD | REUSE | DEAD, ALL}) { + Module m = random_program(seed); + m.optimise(passes); + for (std::size_t n = 0; n < inputs.size(); ++n) { + bool same = run(m, inputs[n]) == expected[n]; + if (!same) std::fprintf(stderr, "seed %llu, passes %u\n", (unsigned long long)seed, passes); + CHECK(same); + } + if (passes == ALL) { + std::size_t left = 0; + for (const Block& blk : m.blocks) left += blk.body.size() + blk.phis.size(); + removed += written - left; + } + std::vector<std::uint8_t> bytes = m.write(); + hash = (hash ^ test_util::fnv(bytes)) * 0x00000100000001b3ull; + } + } + // The programs are of the wasteful kind: the passes find work. + std::printf("random programs: %zu instructions removed, written hash %016llx\n", removed, (unsigned long long)hash); + CHECK(removed > 4000); + // The same as Rust's: the generator and the passes made the same modules, byte for byte. + CHECK(removed == 44159); + CHECK(hash == 0x7efd5f13281dc929ull); +} + +int run_test(const char* name, void (*f)()) { + int before = test_util::failures(); + current_test = name; + try { + f(); + } catch (const std::exception& e) { + std::fprintf(stderr, "%s: threw %s\n", name, e.what()); + ++test_util::failures(); + } + if (test_util::failures() != before) std::fprintf(stderr, "%s: FAILED\n", name); + return 0; +} + +} // namespace + +int main() { +#define T(f) run_test(#f, f) + T(unread_results_without_effect_are_dropped); + T(branch_conditions_and_phi_cycles); + T(wave_operations_have_no_effect_of_their_own); + T(constants_and_identities_fold); + T(float_arithmetic_is_not_folded); + T(a_value_is_reused_below_its_block_and_not_beside_it); + T(a_branch_taken_says_what_its_condition_is); + T(a_branch_on_a_constant_goes_one_way); + T(a_read_is_reused_within_its_block_until_a_store); + T(a_join_of_one_value_and_two_equal_joins); + T(mixed_cross_check); + T(every_pass_leaves_what_random_programs_store); +#undef T + CHECK(written_count == std::size(RUST_WRITTEN)); + return test_util::finish("opt_test"); +} diff --git a/tests/x2w_shader/emit/own_bits_test.cpp b/tests/x2w_shader/emit/own_bits_test.cpp new file mode 100644 index 0000000000..cb1a87ef63 --- /dev/null +++ b/tests/x2w_shader/emit/own_bits_test.cpp @@ -0,0 +1,167 @@ +// Port of the tests in the upstream Rust module emit/own_bits.rs (needs vs-core's ir, vs-front's structure and +// vs-lower's lower::reads_mask_as_data). + +#include <algorithm> +#include <cstdint> +#include <set> +#include <string_view> +#include <vector> + +#include "test_util.h" +#include "x2w_shader/emit/own_bits.h" +#include "x2w_shader/emit/wave.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/structure.h" + +using namespace x2w::vs; +using ir::Program; +using ir::Reg; +using own_bits::OwnBits; + +namespace { + +constexpr std::uint32_t ADD_BIT_NUMBER = 0x4A0A'0A0A; // v_add_nc_u32 v5, s10, v5 + +// A synthetic scalarised loop takes the wave OR of v7 in s7, a loop over its bits with the lowest one's number in s10 and +// the bit in s11, and `body` for the lanes whose v7 has the bit (`own`) or for every lane; `latch` +// runs in every lane after the body, `after` after the loop. +Program light_loop(bool own, const std::vector<std::uint32_t>& body, const std::vector<std::uint32_t>& latch, + const std::vector<std::uint32_t>& after) { + std::vector<std::uint32_t> w(wave::WAVE_OR_V7_TO_S7.begin(), wave::WAVE_OR_V7_TO_S7.end()); + const std::vector<std::uint32_t> test = own ? std::vector<std::uint32_t>{ + 0x3608'0E0B, // v_and_b32 v4, s11, v7 + 0xBE8C'047E, // s_mov_b64 s[12:13], exec + 0x7DAA'0880, // v_cmpx_ne_u32 exec, 0, v4 + } + : std::vector<std::uint32_t>{0xBE8C'047E}; // s_mov_b64 s[12:13], exec + // from the loop's head to its last branch + const std::size_t head = 3 + test.size() + std::size_t(own) + body.size() + 1 + latch.size() + 3; + w.insert(w.end(), { + 0xBF06'8007, // s_cmp_eq_u32 s7, 0 + 0xBF85'0000u | static_cast<std::uint32_t>(3 + head), // s_cbranch_scc1 past the loop + 0x7E06'0207, // v_mov_b32 v3, s7 + 0xBF82'0001, // s_branch to the loop's head + 0x7E06'0209, // again: v_mov_b32 v3, s9 + 0x7E10'0503, // head: v_readfirstlane_b32 s8, v3 + 0xBE8A'1308, // s_ff1_i32_b32 s10, s8 + 0x8F0B'0A81, // s_lshl_b32 s11, 1, s10 + }); + w.insert(w.end(), test.begin(), test.end()); + if (own) w.push_back(0xBF88'0000u | static_cast<std::uint32_t>(body.size())); // s_cbranch_execz past the body + w.insert(w.end(), body.begin(), body.end()); + w.push_back(0xBEFE'040C); // s_mov_b64 exec, s[12:13] + w.insert(w.end(), latch.begin(), latch.end()); + w.insert(w.end(), { + 0x8909'080B, // s_xor_b32 s9, s11, s8 + 0xBF06'0B08, // s_cmp_eq_u32 s8, s11 + 0xBF84'0000u | static_cast<std::uint32_t>(0x1'0000 - head - 1), // s_cbranch_scc0 again + }); + w.insert(w.end(), after.begin(), after.end()); + w.push_back(0xBF81'0000); // s_endpgm + std::vector<std::uint8_t> code; + for (std::uint32_t x : w) { + for (int k = 0; k < 4; ++k) code.push_back(static_cast<std::uint8_t>(x >> (8 * k))); + } + return ir::build(code, true, 256); +} + +OwnBits found(const Program& p) { + const auto st = structure::structure(p); + return own_bits::find(p, st, false); +} + +std::vector<const ir::Inst*> insts(const Program& p) { + std::vector<const ir::Inst*> out; + for (const auto& b : p.blocks) { + for (const auto& i : b.insts) out.push_back(&i); + } + return out; +} + +bool has(const Program& p, std::string_view name) { + const auto all = insts(p); + return std::any_of(all.begin(), all.end(), [&](const ir::Inst* i) { return i->name() == name; }); +} + +void a_wave_or_that_only_steers_a_loop_over_own_bits_is_found() { + const Program p = light_loop(true, {ADD_BIT_NUMBER}, {}, {}); + for (std::string_view n : {"s_ff1_i32_b32", "s_lshl_b32", "v_and_b32", "v_cmpx_ne_u32", "s_xor_b32", + "v_readfirstlane_b32", "s_cbranch_execz"}) { + CHECK(has(p, n)); + } + // a loop: its last branch goes back to the copy of the bits still to visit + bool back = false; + for (std::size_t b = 0; b < p.blocks.size(); ++b) { + for (std::size_t s : p.blocks[b].exit.successors()) back |= s < b; + } + CHECK(back); + const OwnBits own = found(p); + // the OR is the section's last lane read, and the bits still to visit (v3) are alike + const auto all = insts(p); + std::optional<ir::Value> total; + for (auto it = all.rbegin(); it != all.rend(); ++it) { + if ((*it)->name() == "v_readlane_b32") { + total = (*it)->write(Reg::S(7)); + break; + } + } + CHECK(total.has_value()); + CHECK(total && own.totals == std::set<ir::Value>{*total}); + const ir::Inst* first = nullptr; + for (const ir::Inst* i : all) { + if (i->name() == "v_readfirstlane_b32") { + first = i; + break; + } + } + CHECK(first != nullptr); + CHECK(first && first->read(Reg::V(3)) && own.alike.contains(*first->read(Reg::V(3)))); +} + +void a_loop_whose_lanes_all_work_at_every_bit_needs_the_whole_waves_or() { + // (the same title's volume loops, 0xa668 on: no test of the lane's own mask) + const Program p = light_loop(false, {ADD_BIT_NUMBER}, {}, {}); + CHECK(found(p).totals.empty()); +} + +void a_bit_number_read_after_the_loop_is_not_the_lanes_own() { + // v_mov_b32 v6, s10: the last bit of the OR, which another lane may have set + const Program p = light_loop(true, {ADD_BIT_NUMBER}, {}, {0x7E0C'020A}); + CHECK(found(p).totals.empty()); +} + +void the_bits_still_to_visit_read_in_the_body_are_not_the_lanes_own() { + // v_add_nc_u32 v5, s8, v5: s8 holds the other lanes' bits too + const Program p = light_loop(true, {0x4A0A'0A08}, {}, {}); + CHECK(found(p).totals.empty()); +} + +void a_count_of_the_rounds_is_not_the_lanes_own() { + // s_add_i32 s14, s14, 1 where every lane passes, read after the loop (v_mov_b32 v6, s14): one + // round for each bit any lane has + Program p = light_loop(true, {ADD_BIT_NUMBER}, {0x810E'810E}, {0x7E0C'020E}); + CHECK(has(p, "s_add_i32")); + CHECK(found(p).totals.empty()); + // (reading s14 there without counting in it is nothing of the loop's) + p = light_loop(true, {ADD_BIT_NUMBER}, {}, {0x7E0C'020E}); + CHECK(found(p).totals.size() == 1); +} + +void an_effect_where_every_lane_passes_is_not_the_lanes_own() { + // ds_write_b32 v5, v5 after the body: once for each bit any lane has + const Program p = light_loop(true, {ADD_BIT_NUMBER}, {0xD834'0000, 0x0000'0505}, {}); + CHECK(has(p, "ds_write_b32")); + CHECK(found(p).totals.empty()); +} + +} // namespace + +int main() { + a_wave_or_that_only_steers_a_loop_over_own_bits_is_found(); + a_loop_whose_lanes_all_work_at_every_bit_needs_the_whole_waves_or(); + a_bit_number_read_after_the_loop_is_not_the_lanes_own(); + the_bits_still_to_visit_read_in_the_body_are_not_the_lanes_own(); + a_count_of_the_rounds_is_not_the_lanes_own(); + an_effect_where_every_lane_passes_is_not_the_lanes_own(); + return test_util::finish("own_bits_test"); +} diff --git a/tests/x2w_shader/emit/rect_test.cpp b/tests/x2w_shader/emit/rect_test.cpp new file mode 100644 index 0000000000..bc4ecba2bc --- /dev/null +++ b/tests/x2w_shader/emit/rect_test.cpp @@ -0,0 +1,238 @@ +// Port of the upstream Rust module emit/rect.rs's device tests that container_test.cpp does not cover: the +// validator part of the_rectangle_stage_is_a_geometry_shader, and rectangles_are_drawn_whole +// (with pass_through). Skips the validator checks without dxil.dll and the draw without a +// hardware SM 6.6 device (and says so). +// +// pass_through returns two FakeShaders (what the host reads of a HostShader, as in host_test): +// HostShader needs the front end's native.h, which this test does not link. + +#include <windows.h> + +#include <array> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <exception> +#include <optional> +#include <string> +#include <utility> +#include <vector> + +#include "test_util.h" +#include "x2w_shader/emit/container.h" +#include "x2w_shader/emit/host.h" +#include "x2w_shader/emit/rect.h" +#include "x2w_shader/emit/shader.h" +#include "x2w_shader/emit/validator.h" +#include "x2w_shader/error.h" + +using namespace x2w::vs; +using container::SigElement; +using shader::Shader; +using validator::Validator; + +namespace { + +SigElement element(const char* name, std::uint32_t index, std::uint8_t kind, std::uint8_t comp, std::uint32_t row, + std::uint8_t cols) { + SigElement e; + e.name = name; + e.index = index; + e.kind = kind; + e.comp = comp; + e.interp = 0; + e.row = row; + e.col = 0; + e.cols = cols; + e.usage = 0; + e.half = false; + return e; +} + +// A position, a float interpolant and an integer one. +std::vector<SigElement> outputs() { + return {element("SV_Position", 0, 3, 9, 0, 4), element("TEXCOORD", 0, 0, 9, 1, 4), + element("TEXCOORD", 1, 0, 5, 2, 2)}; +} + +std::optional<Validator> load_validator() { + std::string error; + std::optional<Validator> v = Validator::load(Validator::default_path(), &error); + if (!v) std::printf("rect_test: no validator (%s); validator checks skipped\n", error.c_str()); + return v; +} + +// Validates a copy of container; a rejection fails the test (Rust's unwrap). +void validate(Validator& v, const std::vector<std::uint8_t>& container, const char* what) { + std::vector<std::uint8_t> copy = container; + std::optional<std::string> r = v.validate(copy); + CHECK(!r); + if (r) std::fprintf(stderr, "%s rejected: %s\n", what, r->c_str()); +} + +// The stage is a geometry shader of triangles in and six strip vertices out, with the vertex +// shader's outputs on both sides and the primitive id the pixel shader declares; the validator, +// where there is one, accepts it. (The container checks are in container_test.) +void the_rectangle_stage_is_a_geometry_shader() { + const std::vector<SigElement> wanted = {element("SV_PrimitiveID", 0, 10, 5, 3, 1)}; + const std::vector<std::uint8_t> gs = rect_build(outputs(), wanted); + if (std::optional<Validator> v = load_validator()) { + validate(*v, gs, "rectangle stage"); + const std::vector<std::uint8_t> plain = rect_build(outputs(), {}); + validate(*v, plain, "rectangle stage without a primitive id"); + std::printf("rect_test: rectangle stages validated (%zu and %zu bytes)\n", gs.size(), plain.size()); + } +} + +// What the host reads of a HostShader (Stage converts from it). +struct FakeShader { + std::vector<std::uint8_t> dxil; + std::vector<sampler::StaticSampler> static_samplers; + std::vector<std::uint8_t> root_cbvs, root_srvs, root_uavs; + // No user data (Rust: user_data empty). + std::uint32_t user_data_dwords() const { return 0; } +}; + +// A vertex shader that passes a position and a float4 through, and a pixel shader that writes +// the float4. +std::pair<FakeShader, FakeShader> pass_through() { + SigElement position = element("SV_Position", 0, 3, 9, 0, 4); + position.interp = 4; + position.usage = 15; + SigElement coord = element("TEXCOORD", 0, 0, 9, 1, 4); + coord.interp = 2; + coord.usage = 15; + Shader vs(false); + SigElement vs_pos = element("POSITION", 0, 0, 9, 0, 4); + vs_pos.usage = 15; + SigElement vs_coord = coord; + vs_coord.interp = 0; + vs.inputs = {vs_pos, vs_coord}; + vs.outputs = {position, coord}; + Shader ps(true); + SigElement ps_pos = position; + ps_pos.usage = 0; + ps.inputs = {ps_pos, coord}; + SigElement target = element("SV_Target", 0, 16, 9, 0, 4); + target.usage = 15; + ps.outputs = {target}; + // Vertex: output id from input id. Pixel: target 0 from input 1. + const std::vector<std::pair<std::uint32_t, std::uint32_t>> vs_copies = {{0, 0}, {1, 1}}; + const std::vector<std::pair<std::uint32_t, std::uint32_t>> ps_copies = {{1, 0}}; + const std::pair<Shader*, const std::vector<std::pair<std::uint32_t, std::uint32_t>>*> stages[] = { + {&vs, &vs_copies}, {&ps, &ps_copies}}; + for (auto [s, copies] : stages) { + const std::size_t b = s->entry; + for (auto [from, to] : *copies) { + for (std::uint8_t col = 0; col < 4; ++col) { + // In Rust's order (each call numbers a value). + const bitcode::V a0 = s->m.i32(from); + const bitcode::V a1 = s->m.i32(0); + const bitcode::V a2 = s->m.i8(col); + const bitcode::V a3 = s->m.undef(s->t.i32); + const bitcode::V v = s->op(b, "loadInput.f32", bitcode::Attr::ReadNone, s->t.f32, 4, {a0, a1, a2, a3}); + const bitcode::V b0 = s->m.i32(to); + const bitcode::V b1 = s->m.i32(0); + const bitcode::V b2 = s->m.i8(col); + s->op(b, "storeOutput.f32", bitcode::Attr::NoUnwind, s->t.void_, 5, {b0, b1, b2, v}); + } + } + s->m.terminate(b, bitcode::Term::ret()); + } + FakeShader vs_h; + vs_h.dxil = vs.finish(); + FakeShader ps_h; + ps_h.dxil = ps.finish(); + return {std::move(vs_h), std::move(ps_h)}; +} + +// Three corners of the whole target, the corner between the other two first (as the tiled +// lighting sends its tiles), second (as full-screen rectangles come) or third: with the stage +// every texel is drawn and the interpolant continues into the fourth corner's half; without it +// part of the target is not drawn. +void rectangles_are_drawn_whole() { + std::optional<host::Host> h; + try { + h.emplace(false); + } catch (const host::Error& e) { + std::printf("rect_test: no SM 6.6 device (%s); rectangles_are_drawn_whole skipped\n", e.what()); + return; + } + host::Host& hst = *h; + { + DXGI_ADAPTER_DESC1 desc{}; + Microsoft::WRL::ComPtr<IDXGIFactory4> f; + Microsoft::WRL::ComPtr<IDXGIAdapter1> a; + if (SUCCEEDED(CreateDXGIFactory2(0, IID_PPV_ARGS(&f))) && + SUCCEEDED(f->EnumAdapterByLuid(hst.device->GetAdapterLuid(), IID_PPV_ARGS(&a)))) + a->GetDesc1(&desc); + std::printf("rect_test: device %ls\n", desc.Description); + } + auto [vs, ps] = pass_through(); + if (std::optional<Validator> v = load_validator()) { + validate(*v, vs.dxil, "pass-through vertex shader"); + validate(*v, ps.dxil, "pass-through pixel shader"); + } + const std::vector<std::uint8_t> gs = rect_list_gs(vs.dxil, std::span<const std::uint8_t>(ps.dxil)); + auto root = hst.root_signature(vs, ps); + // Position (z 0.5, w 1) and an interpolant that is the position. + using Corner = std::pair<float, float>; + const std::pair<const char*, std::array<Corner, 3>> cases[] = { + {"corner first", {{{-1.0f, 1.0f}, {-1.0f, -1.0f}, {1.0f, 1.0f}}}}, + {"corner second", {{{-1.0f, 1.0f}, {-1.0f, -1.0f}, {1.0f, -1.0f}}}}, + {"corner third", {{{-1.0f, -1.0f}, {1.0f, 1.0f}, {-1.0f, 1.0f}}}}, + }; + for (const auto& [name, corners] : cases) { + std::vector<float> vertices; + for (auto [x, y] : corners) vertices.insert(vertices.end(), {x, y, 0.5f, 1.0f, x, y, 0.0f, 1.0f}); + auto draw = [&](std::span<const std::uint8_t> with_gs) { + auto pso = hst.pipeline_with_gs(root.Get(), vs.dxil, with_gs, ps.dxil); + host::Draw d; + d.vertices = vertices; + d.stride = 32; + d.size = {8, 8}; + d.mesh_groups = 0; + return hst.draw(root.Get(), pso.Get(), d); + }; + const std::vector<std::array<float, 4>> whole = draw(gs); + CHECK(whole.size() == 64); + bool all = true; + for (std::size_t i = 0; i < whole.size(); ++i) { + const float x = float(i % 8), y = float(i / 8); + const std::array<float, 4> want = {(x + 0.5f) / 4.0f - 1.0f, 1.0f - (y + 0.5f) / 4.0f, 0.0f, 1.0f}; + bool ok = true; + for (int c = 0; c < 4; ++c) ok = ok && std::fabs(whole[i][c] - want[c]) < 1e-4f; + if (!ok) { + std::fprintf(stderr, "%s: texel %zu is [%g, %g, %g, %g], not [%g, %g, %g, %g]\n", name, i, whole[i][0], + whole[i][1], whole[i][2], whole[i][3], want[0], want[1], want[2], want[3]); + all = false; + break; // Rust's assert! stops at the first + } + } + CHECK(all); + const std::vector<std::array<float, 4>> half = draw({}); + std::size_t missing = 0; + for (std::size_t i = 0; i < half.size() && i < whole.size(); ++i) missing += half[i] != whole[i]; + if (missing < 24) std::fprintf(stderr, "%s: only %zu texels need the stage\n", name, missing); + CHECK(missing >= 24); + std::printf("rect_test: %s: every texel drawn with the stage, %zu missing without\n", name, missing); + } +} + +template <class F> +void run(const char* name, F&& f) { + try { + f(); + } catch (const std::exception& e) { + std::fprintf(stderr, "%s: %s\n", name, e.what()); + CHECK(false); + } +} + +} // namespace + +int main() { + run("the_rectangle_stage_is_a_geometry_shader", the_rectangle_stage_is_a_geometry_shader); + run("rectangles_are_drawn_whole", rectangles_are_drawn_whole); + return test_util::finish("rect_test"); +} diff --git a/tests/x2w_shader/emit/ref/README.txt b/tests/x2w_shader/emit/ref/README.txt new file mode 100644 index 0000000000..0517a9ad64 --- /dev/null +++ b/tests/x2w_shader/emit/ref/README.txt @@ -0,0 +1,28 @@ +Rust emitter reference outputs + +ref_test.cpp builds fixed inputs in C++ and compares every output byte. The +fixture set was introduced in commit 7154f8c0b80682a153d38264a14b5833615c1b3b. +Both optimizer baselines in this directory were regenerated from upstream Rust +revision e9f435f9821ee8e03316367766c1551438aafec5 with the Xbox2Windows LLVM +producer identifier. + +To reproduce in a temporary checkout of that revision: + +1. Set SHADER_CRATE_MANIFEST to the absolute path of the Cargo.toml for the + crate containing src/emit/mod.rs. Set REF_DIR to an absolute output directory. + Copy ref_dump.rs beside mod.rs, add #[cfg(test)] mod ref_dump; there, and + make build in src/emit/rect.rs visible as pub(super). +2. In src/emit/shader.rs, find the llvm.ident named metadata node. Set its + producer to Xbox2Windows by changing the string argument in the preceding + let ident = self.m.md_str(...) assignment. Keep the metadata node and the + other DXIL version and shader-model fields intact. +3. Set SHADER_OPT_VAR to the environment variable name read by shader_opt() + in src/emit/mod.rs. The default selects the normal optimization passes, + and zero disables them. With the Rust dependencies available locally, run: + + mkdir -p "$REF_DIR/out" "$REF_DIR/out_opt0" + (unset "$SHADER_OPT_VAR"; X2W_REF_OUT="$REF_DIR/out" cargo test --offline --manifest-path "$SHADER_CRATE_MANIFEST" --lib ref_dump) + env "$SHADER_OPT_VAR=0" X2W_REF_OUT="$REF_DIR/out_opt0" cargo test --offline --manifest-path "$SHADER_CRATE_MANIFEST" --lib ref_dump + +Each directory contains 12 binary files. Compare all 12 against the C++ emitter +using the matching optimizer setting. diff --git a/tests/x2w_shader/emit/ref/out/build.bin b/tests/x2w_shader/emit/ref/out/build.bin new file mode 100644 index 0000000000000000000000000000000000000000..e4bc1f9238ac5b0dd24c01fc46fc1c2d6716e4c6 GIT binary patch literal 108 zcmZ>XaB^0N6La42{OPYhB3#AUM^$?n85kIHfS4JGb%59$h*N+#*v-=bB*w_Z903HX QKqe<Kz|}V(1gMq)0Dc`0KmY&$ literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out/cs_basic.bin b/tests/x2w_shader/emit/ref/out/cs_basic.bin new file mode 100644 index 0000000000000000000000000000000000000000..791e5b37a9069e25238d6a0f2cfe3490753bf2c5 GIT binary patch literal 2812 zcmZ`)e{2)i9l!Hk?k>sse8K5zuoEr~jZ&7WFEI)>c974PwxKfWO~6Daww|Lw(~>af z$3g<tbpBCnq*OCov_^<(30t?YKh~_}k4ViV+m|sbc&)c(G}9<^ScrziAcC+lsoM5^ z7pGH^_N4E7-}imr@8|pD-F;u@;h^%$jfRfNpC@h4wx9d3<y_Z?Bta0LRS^UOs|TnH z=rB+ZkOK~P0UdaLAL3w71PBXW_8oYk)!YM**OwmKs|UV@ra_K?9v>12FjW9;jsP$? z4oozV1ITm)>*lbQ87#+oc*V3S$97mwm8lw5JXjzs$Nn&F%CY|D=#md~)oyMcTRRW$ z3uP(^;uu&*z#-l<04RdqG{}QW=0*cg5U;{nbxf+l{;?0|Sm{47*nnl)npnduCH0{* znAuKLPPaSeF>52JE~qCYjP2|(EhvS!GnFJsoRtV-5X<OZWI->8g&Jv)))0kK65;Mx z(QPLJwto?}TgY}ouUak%D;ePy8YgPqeP1|}szKwPYP*kwTSWE!HDOH^?gwnQRp9|z zBzPkvdP{L<QQ4bOyoI<kAB4I2CvjieP%980NA~B0M<r%GZ3DXpCFaLc)k95qUlrC% z%x%ODpo1iDpu(<m)ZSULV}<gM8~)j73(SC2j5{X`S3avU0g-MEJxye!oF#OWxT5n} zDM*D55mz)<oU@@r<c@eN|5Rt@AdPrK%F&@Wi3JV3^G_Yjv{+Jnocjc&5Z`Fch+uCZ zE+^#}jD%=FVne?sG8)8TTD$=kZH2^Q&OaXar-PoN;^Chr!caE`PPm{EO18`yzM|2b zig&=tw@^xDGNC1ZG45Y9JP>p$xVNZy6Bchej`M+nEXKVPiZ^el76|DAiGI*-TbFDP z5iY~~k?M<S+qx=D1%wp|U&sTqNUKn2xDbf_HKI_X<8ReoJCI2ZY037U<Y*5Cy!Aa* z=qn1RU?yy*pq`WLpv3m2h5k)uWRvOFSgcSq%f2Zb4zQ;*cBsg#itO-)P!j-QLvt05 zCRxzwD+z#8MldD5v8$v`I&QW=R2w5B{*1Ip<;@w7O*H=+*rWNgy7@-}uQz-|(}A)Q z-@j8b+Xn2l)CVLfl@F8)0;iXG$IUkaW{-e<;7iafe8AXgLnM(b@in5I&bty9o3GL` z>LfxUuh0YT&Pi(xZ>N9b${CEQdY!LXGQ{XN`5H-~uZU686i~qQ=r@+=Eb7$ui>^WL ze4C64fWj$s&XhJP^uOJmrFw;)#}1I`V94F6#q)HwH5p(Qu$m5P3pClr_A{?WzB4F> zMdlMg;%juND}-^sx6L%1L~^9i;O|8;V%*^V82pX0ZnCdqc7{=Cjf*ujo7z%qX9jW| zg@5}ftkrsDZZafZ$yl4Xc$@4PugpdEi%k2H&MAS~D`ZGKb3CRo-$t_I7nM1Yu_u<# zOZ@9I<i2q&yp3Iwq>t&a+Qjt`?8ebGIy?(d?Eq!nx1+*-=;bG88Zu3s?8e}+ZSz@E z!PsgdqaNoE->TkokD~VfLAT0|Ua75B-w5eiKxpC&*M`~=C*$@|yCx+5k94@$#8J*( zZb^&F%+X2awHc-l$y%(U)0a^8%o=BIT1$k3+I=`vih1U!z4`1{%+BGvZuon-6)lF2 z*b`Bqof}fw>O}uU(rVN#%5`H}p4@&tP`?nazcE$65_SReQ@R@k!|d=(aySwnl9B@v z_SD3de3pCDwU)KsnR2a!>wmvocRl=~$~JBp$gsO-k`awP-OP?oY+1~5NvyU?*5#tE z1-bs~%XRrF*HZY!2;1nw%FXP_Np>{P9v(>!VdUg9q^o>4L0H|K?wVhA9jhffQi>;G zj0JUebc7w8=;v1n+uucDT^HPZus)Zq`)JB_3{{wFac6<*$SWOVR7YWC3~*0#>}Xdq z0uCb7@JKQuCASu8gga?r8JaY*{nc!~ZgIZuMuTgqp)MD$KZefw=Hfo+HkT>?T-=|a ze1)~zVMwfp-QANMfLTvQ(m2)OW_I{d1;C!vldo{een)a(A~`w{ZMnN9+${+YGr}E2 zbwk=KQ?7zJUx&&zxaOmE3t{G38rqj)HZjFJYk0;LPm1!58_$B%&tkqs$~OZKP`^YF zUxj+uMFJiGe@LYv_uD1GK4QVI#2n?H&3XVPL3NB%I}`9q07m?oyy3gN@o3<$!W&Yp z_z8k+OAI_r5Z^jfP!*;{;ch^<qYCy2{Xe*r(lHVDLaUz1`4W_OCg{DOc*c~yv+|xo z)D=Qce2xW|a9<Uc1Hz?%a3YP{oLyr!fujC|(UA&%0c$qu#SoFY&msOP3jcsc4ShR} znfC}=8K{@r1p0poQahn$8H0W~h#$mzU@6&_BesjGZB-L)NwyCHwtLY1H=aePVHj!| z#<is9Q=~<g9J>Z1_z&tq-4R0Kn2%j)S!Eg-mWXNMZ^^B6A3876jSK^O^gDU$T$WQ* zCRer{Ei&CIbE0hfQvI|nf^8M(s-I?`<iiBuo)-x>pPd;)G>39}D%y5jCEji>$*4C# z8wCFxOk-OeL6LYKozVFx;fRuBO?0O0;oUU5-SM|<DoaAF{&zJt>lkxL1Q(MBt4;%a zhTVvD?SiGA{!5FD)YcTOTB#=}=7<rAtLL&UhD0~=L8sKna1dDW9gCB`SS+Wwb~(14 zK8_4kyvi%^k~0FRtX&E^`9IasCnM}hjr}g_F5$}jXy@hZ_dm_{vmhQWmEDTJvNZ3w x1UYhL(_iMCyX1O$G|i6c>?Eo}xyeT)>eeyBpTE2my~&QEoY+}tk>L_x{1*YnK<xkk literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out/hashes.bin b/tests/x2w_shader/emit/ref/out/hashes.bin new file mode 100644 index 0000000000000000000000000000000000000000..cba03f0a96494eca0c41d81fc9fd82005af93151 GIT binary patch literal 3216 zcmV;B3~%!k4Pf@Sb>g~CO1{(qvgx4)`Ao8b(U=<a`KcQ>3gZa%FV`U2AvTpdPfX{p zIncM1=L6u%x>raV0L-$FsKIQIZB17ZEok?G#7@)LOWrOS{|5pX3aa#J&TPsN8ov-4 z?yo=H!Xr&_S?XI;e>iCf<cRVy#nSE+^1R{N9q;(gS}Rv~E8~}mG*ePa+f=}k-yg?p zaKjZ{$~J-F&>&><iFhN458lMM!fP8Sv~9<iYb=!2p96$zhJz;x#rxQOCw|{}??!w5 zcK+rhvf@<BZ%8%Ok_UGQ>NpPNk;~tBRECVAv@Rp#Roz8jb|8XyY#z~Z*0vYAseWaN za`(WH%n#06^%uesbgO!PdDJSmxSY+_2BRrn<hNrk%59Fx%D$^G>)@WT{<8UMr|x-n zT9KM6@zqB{>R>{)=^rIRIm)GW;nN38i8!zGYw?)rlaSDttcC2EMZ73;2Y%IJnh?*I z9>mO(gd*ocyd;EW7`2cU77vcRG*Py2#H;H;PHO2f8el<d;O5?^z!Fg>vHnPFJ;1`e zc_Gh`{6~jkx$<*UZoS`Lc`ujJR`y;8LGP7b`eEzipGb`oi7*=9-q*0!KQg?NHhMHc zA+yP`mlW~3W4!6i69D70Z!&q@JS7lkE8jodx+94IC=45TYbL6<pOIY$`wf<(?>_Qf z<Z-Mf*TqGx*07BW5yu^v^Bz&d46cx+>Q2j2j`e*lQ6gO8vf|A4UEFA$vj~+y$Jbu* zghb=+Pg|(uWC&pSua3A;jR3b<qkVThcYEA4o-k{H1?T}l``jrsJM>2C!8gs@PXjcT zIvG?M1{g0uWs@DxLs^g%E2F}~xpFc8`ZB!N#K4*MerV^-=kSEuR{2O7X7n^NU*t(l z%_90ctbHT!yml)Zz)HsK_y?I^FwWYCE~!Q+e|wBj|B;@dp_A(PjzxHxxn8fT0zWUg z4HLB*zE`@9+Xxfjmp>ckI+v>I-OF}7w*H|(7~Lc9+&VS;B>BaObIRq`(w&nibuHSQ zjmK{0IP{m1w<Ll%h?cCSv;zcOHy@H_RaftV(%CD0y0MsbM7JhkML(^nmid~s0SIVj zI7AE#8hR3CMYW5<!{rd}*z_WtgFeQJT_c0eU!_<{qRFXPh^rNyYEI}S^+qjpCsWyq zgrshowl$J=KNidR`mMnTakJc(G39lDoPX>m;isH!zXt^JGx;b?XPmgT$b-{;sus<{ zOr3D;aNqO8Ig0Gxl!%`I9(zQDANIFgwZgbGM~+OWqcm;t_c`l`HjC&XcRWphPep&W zmK!Sj5Mi3&q|6j71o&0&VQySv_EenUEO^3c$Z$9aYX+_ZYD86l)hGaPD<xwvEtZk( zq)ggh?@MSXcP*=?sh~uk5o4H(#IRs;jK{veN(%S&6H@!Vfb!f39N~Jsz?cNa2`hdt zTBIlE>{kuT9MCF5=x&Kz^4PmYu)3m|%a!~q4p^LcoX=KRXsWh8Q3?CZBKwlKR|Wt* z2jA0KM-|UMgzqu+FKK1r@uyn1x>>T5gywLx=^^?QG8^{nBj(uHe}T~tb=dFMaNP9~ z*JsR``MtDQi`Zngz1tt*+O2M&8^h@#w`zZ-tA)Z8?)cnzjfZ<D{8A>@{c(8z18F!7 zExtWQhb=v;H5wAdTg7ZYS1R)hP|otH;VF&;Y*oJGEl^YBTNeN+b?(m3ui>qW`p<%8 z5ae<{B~{p6-iOU6ygm&<F=3f|E4(E22IhifkZ+)a9J{T#(Zx#4y^xnG@8%`#m**@= zG`a<%_vTrP?7Tf@T#2d-B(O(Lrj42=T&LZ$e<qw-rrz+(`)?ZNUq@&JJEkqvMW4gZ zn&yQ;DvrPp8v?G6{w4$BmW4JfJsQ~KgeaiF`QqIU7YK)#S8<Cl7mbTpD2l6G@t_Mi z|3uLO4?<1`2LYhhF^p6ZDO~D;iS@2rgisbgd3fDAAsihJ2=AhV=!RjntN66YQrSd6 zB$awILJIOt4{xiu;Zt-c%(TGS<9qvQ%u?-RxjBDfbdQFJG(QYiT&9;JG=Xy-YBU(o z#~D^tlNc)&`d9S)b~H_>lD@gIA{!hpDz;{SIO-*=##-hNE+%@3^$5!wv+D^wLrU4c z)^fE!R76)7h8nb~eUtyu`14oWrHf?~lW^zvz>SbdoWrKau!+acR*T8of1}ay+EIMU zRF$v(HZ0Le_cRfLG(s(DTezHAE%cqTvPn2QTTToLtzGS6FFkUCJdzG&rz8n<+;EvC zW?gt<nq(qT{Qv-NR0T|9;NF|A6eG?t@mG;f@nl6EU=j9`%ANz2f}H9v>asV-D}B}5 ziZCiTQTstEV#MDG-SbNBlCyInW@Gf#ac^MgCys2yEU-@<J5rU9JvO;b%kY@bMhcMX z6_50AK91P~(;?_#HgPc6i_c_T@_p#Ho<Iuxb*l@ODn(*(0ZIh*Tv;+4f0Q9CvCi7b zN)KddMjp7`9C?dX;;sSpO|fu4YVzl7$re1tkkb^gKr)_gm2ni6JpLR>SqQ}voYkhT z2%gPx@J+0{poZ11_cQ`<L@<mv82i<v8g>a&q_ij`a@B&BMd`Liy!H2!j2OiaAFf~& za_V(aWX>vI`Y(^|IwF{iwwkz3=Zjp(f{U+?pNp#-by`q(uCbrzQ-Kj1lUJRe*uj@v zCt5(0^0(|Lk$qD8K(Fy;e9WS;sBMI3)<9kxRvnO}a}$H-$RKOe;Eh<DwfMg4TR#qm z8(*y!sPzUu_yGyeQZm<*ZtoA}8Dh*{*=%Qp{n5fF#=1mZ7rbkX6f8PFRrB*z5Y)GH zC$<LPNhdF7(8U`L%4+1(U1&gOO;ewb*=8CG!oS>}1lQc3sBB@1GzuR@hY>fV__`KV z6Tv9mauPlTKWUM!V8tbIwdQ)yj{+oC2a$C9e8@MQ^8k**Bx}33U$|hsGIc?zD$vr$ zXy<pC7D-?{3U;KM^9L7PA(aiOdqBf@XBA5Xref2W*wha?07R|lB<FWQzYfHggssF) z^#=ZVPyagHS)k48sHYLa=O{*c*^5*g2+TK*RobBeGT=T*p#eYHR3XAiT)iX7Fkc^n zaE@Bmxj^<W@1~KmMPya+NsEIyFiFKh0Yv35{ZD1Wla_7_Jw&3w_BDevt{m!4z>XCB z)5oVOnd>$0?pox8___$SeJDwZ=+l8BryitHZwcs9CpRW^`nu|fQZ-u{%+oyZYhzZT zI8WW-MSIRaRkI>~1fR5x`zNesHGIxp?a$x`Ap|PsM$(H7d8bd-d~b@wv9o0RIS;AB z@8}_;!AmnHo?sNt7Hn^LIMkT6@5C-s^lHapt!plOW%$fIOY1d<1FYk0_^O?XTd2F> z>w&~LQbeiF>nS(#C>^zv;oJMoH+%vv(`-V774BnO?ar<fry3ziFcXWHv3x@BohW)i z8jY2t>x#K>Q3ekx{iICAoo2Oou6hj*<fJS~1?fhN@4i9-a9bm=XS;2-Ac=LO7w<4e zhB0;uFt(Um*KaAU9o1D|D(;xLelzS5+n8&LkFkMpI!Qv3L>cJ1bH=-q-sVi~D&kwK z)cv7F&>=7DR#v&gm~3ROUtGnyS2doc@h=L%Kanvzw*tP;nV#)+tNl-uFXKS`_x?dF zRb#r_0r&Rtx-A!LpOYlB=<o`+`6-h`t~XRY%w!o}n&<jbC)<2oL@p1?@)Gz3W<!a3 zV1Ewlc4lYE#?Z7TV5UK%Mp;vVHFrytb?4~mU=p^QtiEX7-QHfPP7e51RY{R&o9(zJ zZ+uto<jD=Z^Ddsa6TxX_O1uKGGt>_|4=9e0Zn<Ndy2O#@@P40VF|D^Vz+Xg`pA2TC z83u=5RtyFx@Sz{+@n9k|U@Ugv2I%oTY@k?l_?Vd8Q_OUJ9~#>hm>MATtLXx@bdJ4* zH&1|HPU%B=EVOnIIBl_b35Z}VrR5&-+!^BA%ui#@G^<V-DrAd3kH>`xVP|N2{M^At zLD<Q})?bGfUiVUnEZLSzGmbHXP6M%!36H0^=~zFIUbla-%a3+GE?>vXN07<F-!$+| z9}hG-{w)ibq`zyPGl~K0rF~v<L{Y)a*$I^%^gyO_(D-fg8clopp&;p>=uxA^*)fZB zm@k2b;#>99c`Kh|#wj4INcZoX0>hAd)1|pjbMacc&uvN57U2nXEM{AgvjA%gkuAPJ z<MHgQ39Lf(m`6u#DijBl;i2Nk4DZ1#S>tGk1E{g&cmhRRRG%mhM!eFDSI>4AE<2^) CBTEMW literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out/ps_basic.bin b/tests/x2w_shader/emit/ref/out/ps_basic.bin new file mode 100644 index 0000000000000000000000000000000000000000..501fe17d6932b25c5430beb99a7a8681a2f6caae GIT binary patch literal 3222 zcmb7Ge{2)i9e<a*++B!scc~NRkaIW}hC&r}FPH@fC+sfgwgGv=Ytk;8Xt5d4&;d0e z3kjXJ^N++vOC^t{Q(CbpSs6l8rCO9p(S$UgjhKrJ^4h9P8Eca^Fgo!gqG4iF_v8Eg zgHp7A_T=~O`@TOu-yiRnJ$+sJYvGRHcyCUxbsg7x55MxTk3tCj+=37bUl;Ul=$}Jx z1Hn)QLPw$ZJiZz8z=H-egf{m)(fS5_8R#WGiW31ef=3r9gv2rd^NA9Vd<eUscc1*k z19IX>ypQ*bk_};%eUL9{Jx_1<y>M{P;GP%uqu$5*^sQT;^n5|+TfJMKL|Y-|b)ZXZ z$}u++V`wV$awuh=fY}=ucy8Aq^7TB8U0{ZZ>i=l}fkxO2MSfpy1l0z;P`3L-H6{8% zec=H<k&|BLOGJJz#bRb<Y@%0?6CG$2^3XIaQP~GYbs-v*%a|0cAqpnTit31}@D${w zDY2JG{G=lPZ!cqzZ@1RdU3Wj@KHAf_+534FLc4+Y6Nrt>S%`_`u>kxoJ@ugjb|=}1 z)nR2BiKiNR<M<pYJEvBhtcflXl2-QNF+!|FRVUkQX9+1Hx*K*YEC8{yhW%ZNmmjNw zq>m^FZ6`ct7p}lhNV!_&Amhh0jw{I7xnPL<Rq-E4yn@C3#<KZ2VId`4!4s&?x$jFd zr5ZGD`NZ2;xPq#0FA9r3;kGJ%>JvW0?;%UZE49x>8uR+5l-{0;G-kVCY(5@wCo;ZD zY>8m&W5V4zb}1o(-Dh*`>&mh_e&Li)Sej!$#oPeyr7RhoTmLh9(+t(QKzB@JI%YyG zFalCO(m0usv!;(#C8pK;Rg_ZF72Y4Bv)Gcx@jU8jFj^HI#}`pgz0qp>gVM!#pF(f@ zEfL;|U!iOniHY#__$j(M5|9|pl2I)WZ%g%Z5Vj&k_y+t_)#7yg7K>LD@wg-`NrGOL zYKy0+w|IrGaoSHU3b$18bw&6)6lOTWuf*@J7nc<A4kqEhB?&i>cpb`ttHE^1N33yN zVpA<?XRg+O^|aOvq+)~qSX+N=q@M=5=1rflFE1R15s8N(|0(XE!tF~42g<~7nK<C* zh(f+lrZRI#<qrF~!906a;)aS$zW@kD&8r}q;y`ELoB%i_gaSuDRtbBd*lZuKR|^*# zOjFWdsS2ee7<1K1<+Fs(zG@WCHOLIdw<;O6q+~hps8YB}VeXH=Oi@Zn@LdIc14t{A zkwVymyb`Z7DaM2y=P?SCv_!RPMowG3`D3rd6onpTgU(!%OsoZSj_&Vc4O?nc7o<?9 zr8a*-qN=Pqv#!}I$p`tqHcheA+N?}g_8eXPX8`u3zDWentkcvSxU=ZYU973&wT8l{ zKO*ueORZrtW@}7&$z(L_!Cq<52?3H*peZaNA=V8VW)F5e^fJ3A@!+o@ZzX=abtX$7 z)j}rcCCcWN5~f7)VTE5t)F^WPM&KO&4!+e!RXX97HaaI2%iBz#dks&o(`@Jb^ureF z+cqxgP}lJKI!&V2e@WqJP5cz&{iGws1VCYj!CIq^R~1XPFr`mXM~?e{^+@%sqW+1k zKo9K=WA^!^BM(rg9CK^<%nGkG_Vrn1_#^PRyyY!__3u&jEi8Ttr*%=di8X1~A6E8S zndzEBJklk97_YW6+6T#K$Tm(j4DRx?&l&6<MErgry<swezDQL%$u>sYf<PE8YX5Xy zFi`jGeErT)-5S245!P{6SaDgS)T;`Au@GnYR3H>_B_i#9dgDpjJwta46WhJ~61bZ& zE27J{P+xg`zW!Nld3PYJoPm|`t>L?znk`Wk&XW`-75@C#sQAy6_;0_cI_f-ux^9XT zYAgj#Gb>t}!MqP*0P|$gJX|t|$W6!&V$eo=eWOpgDxdDJ{LXM?A8M1HPjJ7Mstc** z(#6ygklOc>qp(;l-Mh`@KMpNVYfTrY<!dEmBT^Nf@=EN^uyPuz0qY3J=IFNk=rdE5 z&t9wCez!6>Gg_m$_S$x8a&ghKiqOU{_yjA%_Nk|J7u<z=n=exKa}H;$((-6L<DQGi zm%BF3(Cue3ow>}IYA<e&1%D(Z+(@cMY-ARn(cPyr{FuCG)+|iRSLf}2)0)l!5!hn9 z6wFd9FQ=N`nU-%l>a&66*BtV-Y54?mi66DknoXC?ns-9-dDDI^uw_bE1y>NaAsHJ; z#74Sfhk~)SntQyvh>#B1uTRShfh~Dql}ywoxj~*AXy!)xM-M5n0e@_*=^ih*o02bw znid=@{qy#B2y)X2=2~&Tcfo#l@`ikNUfx|tb;fm9G&A01a3jOq!N~)bt4O>7m!ly# zEnQ7%(+<_$jVlXkk;WX|nbkYT>CW8n_+XHGk>?=BV30c;q=$xMK_%9Zs}-&%gn4+R zu=q*g@o`FL?H@YiS%*CxXxfdBxX(n~dA<EK-Ek(;5vAR^#kwIs_hLV{p+7bNqY(=x zVnIJQ)XWXttpwOZMr=DDJ79|qOvXkgLoGMqaLfsJQo?mi@5n+ursZ5=yd03vJLIz= z`}qL-enM~0>g|(-aVF!M&|PubJ(2kuIQ=~Aevfu1;Q~0IAf!V*taYk8s&AahFuf{y z{%#?0e@eI|2@8p3H<5Tp755jeZR>Cac|Fh29W$m2;G=Zs1pP=9UQfV|tj%WJr;Cp% z!D{#VYRJ<JRhVPp!G^et&(29nxTy;85LtuF7jSXCb28FC5$Q;#-BG$d+0}kbca7_t zX0(mDknBy?-^2Pu5w8^9uX{iz6!BJGIO!ASk!ba>_dq+Mx;sTeE56Ij`&v0WEG{hy zw|&B!K5^;31fdoIsL3W$6UK~d6^3G4KM-VpFvadM*i~#53j6apYDLmqaZFn=Zc`8+ zHl5r~KfBilVh+U81<l6nz&nCS;n{cPs0M!`swlj}AoF^AT!UM?B>kg(LPKE2gW2Lj zXvL2Pl4X!9W&`tK+@!((wnO=v(9z*v%Gr=SOrX-zaJm@U&XKvlnD$u>zlNDr7RtsK vBTU?&Yztb`d%*Yct1O{={5v7rb+d`+2Q8rAP}ct!)v%<kd_%*fKc4>u8qs?z literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out/psv_cs.bin b/tests/x2w_shader/emit/ref/out/psv_cs.bin new file mode 100644 index 0000000000000000000000000000000000000000..ecd597530468ce56aa438d6047e0627fd24cc958 GIT binary patch literal 120 zcmXqDzyuCJArNK-Vi@26GC-ISh?#&`0*G0le0CrW!rVX%0w6X>9VZmS#6jv|003V& B0Vn_f literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out/psv_gs.bin b/tests/x2w_shader/emit/ref/out/psv_gs.bin new file mode 100644 index 0000000000000000000000000000000000000000..ee945a540822c21ef0e266bf7f087d78e038de84 GIT binary patch literal 216 zcmXqDU|?VdVpbq#gkm7Y@E-`67}yw?nHiXvKmurh2gDC?jd1q&4{`xAVQN5T2!Q0E ofRVw4nVAJ*Hb{t((TRZ>s2FA!BV!U!45k_+PMrGxKrQ$%0Nk?>$^ZZW literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out/psv_ms.bin b/tests/x2w_shader/emit/ref/out/psv_ms.bin new file mode 100644 index 0000000000000000000000000000000000000000..1091e610c6c0809fb1ec7ba2e3074bf40821aebc GIT binary patch literal 184 zcmYj}Q3`}G3`A#Izk~%3;2}JM+WH|VmEwordyvJO?@p@1KFBo5G}A#eCKo+ErTK~% zoI^!;ZB7;M(u3AypN^1HjtFT<8C#y$IP8O2&P3SFU%ck%eRb`N&k<gqpKS6CYN*W= Mbg}qP1{sR~1BXZrtN;K2 literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out/psv_ps.bin b/tests/x2w_shader/emit/ref/out/psv_ps.bin new file mode 100644 index 0000000000000000000000000000000000000000..bdb0aaa7cea2209212fc0c1df7e132f527f732ee GIT binary patch literal 400 zcmbVI%MQXY42zcu#AB%3_zeC4v6UNArHKP){{J5!E(wAjvE)j&GiU8lL;yP)JPouK zDt*^vz3GFo^#`AeIyFu1+~;@9md=g))bv-*@Duaf<vx`%XPL^i%%7c{uQ_K7kgRG8 zVmB~~+7D7!;!*FpuG8jqx#lhfdLF*t0fKFGamM-+??Sx$#`K$G&;0ZU*%^2NT`UfK literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out/rect_plain.bin b/tests/x2w_shader/emit/ref/out/rect_plain.bin new file mode 100644 index 0000000000000000000000000000000000000000..ea2792b499e894fb11e5212b05f3999ad06de30a GIT binary patch literal 4928 zcmb7`4{+O79ml0ekrZ2&l{)Jj+i6wOm8{EcFKO2%bzJPo%Q8q?Z!M#+vDy6-(x&O0 zH0#oig8wznz&p$>gOv5afeu2iTeH=$zy;2>vMg5&WNR4#lFeaRH@N+AS>XosHh#~x zaMIgxLuX0v>Gyk|_x=6eKRb6e%ewtn8<(yB>Z7Z7{P4SvIlF&O5(Hs45CjA72Dn?{ zei`mPVAxSY5MH>qx7>j^_@-WWY`?v(A1V~w>i3R<5%chOeChT1H-7dOi#a>?TWmiD zb^Hxq_zm3>Q~|X8?)zO29NO2r?}3BFj@x$1+qT{1EEcwXTs0V7xIR*iYJ~Sks^Rkv z|67e~``zeGa71up`K55<c+}WFgsTLy4Y8@=fwg$$I{9yq`8;4NZZ8(ypzfq7y2vF- zCqY5d)V|1)W`a~Z&9(n{{vU$qk8`V1S{>V4E7Zz0Z|BZC+NMBsJB(&MXvK8~G~qZ# z;n6H7URebJ-v~BsK+@oRY2h|UGB{1Fy<|ie%Hkp=b)kM-SV@$PY%osXqMo2y3E~c8 zKF@}LyIE@E`pY2bM<iea$3V|;35x^W?n{^Zl6*o65a}yXYV#OrTcDZ-m8LOrZ767s zQr1DmRpLs=zq#1vuLX~B**2v#3{tgIiZvlOPEoc~a${O?QHWpXSn%l&+V%e=^sgiR zK}ieG??;7q?1Fq<0`aM~ipEUPJS}gAcIluw5~#TtY@BLtoDP~#DVC|Es}%7Hy5JPv z&oEb_`m9TMFT*?wPaxU#2i?LUiIpn}hd6;ACx{@YMZY6O1#ybhOtn2oD9{BO$P(MD z2*d~N{3o1=9W22s5+CFY=sJ=Jq5&6qj{7a-p`s@d?sbPZbcBy|P*B#LbqQV5!clk< z`lE>LiLuaGS5)X$3w>&#+s$H!Y347B+z#8>qi(i$nz<yhhx48}xp~h^V2ZKe)0Gi` zQy}EN$S3i7$X~`kueTF0^7u-KZ;&NYu1FC54dr5P{X-p1obajh-nVLNDeWsb@!e}B zwY8+BiB<63Kr14N91>riFV;JuC>rRL=toXFUv4ze6Gm_l`Enln`oX~@)2Hg3F&+N$ zf~Dla^eWd2v;#SbHj$U<i=zKS)<FN>vh7>@zVk!;`(w8y*R;-=*&=c>{gO!5J7YQL z+|oS)^D&OKggXBu(uUCdjK~{8{wE}Uju}R4IOQ4liPC%CFWuP}KGMn_Z4E!<4VMLg zMSm$Eec2FloRGLzX-~r%uH;#dW7*zSLz72hy93B#F4-4AUPEa3Pm=3*w8ynvin}yp zNOLx;dDgBm(8(txZi;qvtl@(74)K>|DG){PQF=TlHgw(l#<7>7$p+ek9LBM-RH93q z^zk6(Sz`G3U5Vp&_8tFRwDhhaiE~4CqGf?Zo5<`9Nb3zD59pcdf1dvhp?k^BUv%qc zV!GKFzX7s2o&=p6=<Ymox=Xy|6aLQtp9xwM!KNr>o1r$pNquT0SeEi0;OrhX(t%VB zRzfywpY&;ekky=(w5LGfcv-;LCWhJrsK!9gLvGL04*Q1MC*7JK`82~(&FN9inQ0Ap z8V7aBn}Bc-facK7=<%}DXsx|txWenHxNrWtJ^l*Fvk@mMAfbHne@%OK=8`{r{0pPU z@9~x1J5~C{nbP})j_Z__W6if5FlG|h`*P{U*bpSawT6?|<GyZd7*HCba^nFpk+iJg z_)%X+*xSlJG~<fNo35641+DR3G5k=1Z5%t^>t%cT!VeFHb;(V+Yy*lJuA24uy~2B= z9v=%6qg=pS$c(&cP_dmVX-t>cLX>S#8I+8}qm*?<wvIVAL3d-6t*z{3PpBDhCI4^< ze?$7eWQBLo4L~T%6B<T?w!vUiTiL89BxASte8Rk4cwN#zl@%6T!dvJDU!l9fpmjRf zv_RF4%bS3lhVH5e0?%u_r>^6CmWg>wdj)A5kQ+iuq}j(F>0=KKb@P`9{oA5&#V4%e zn^&ZgRlgaww4>6TThN@QY*Vr=0=&Kmg#Iwc9%&7Gz3fphb+|9=mBN+ja^bD0Fb`WP z(!Z7!U_V?ZPE@_J$}+R6D&<+xjvld&gEYA@PBo1On?jT|ovk?RW*_cgH+F=3;OPr{ zqhYU`JzT>ce!mp35Bb9PbK!1dxMwJQWXNCp4rC=G{5=8TQoE*xEepezbnZFpv7BFJ znebPg_b@L*MyKS)q1<x}Hh;Nc0G|-IK&Mv&){B&N6b`Cxi6H9mI<K%>Ly#zi-eJdi zeV5Q5ObG9a!a`K@4x#_Mx|17RC3qypDL8bj<1);WwPRG%Mal+4nD$%R+&X-kK-e%e zcKy4O{`IT|8fRVlD;eez?7hf;8$P;{uwZa9LCm0X6SPmrHuXfI?{ugVT*BK?;R@1T z0gx!XjmSO!Z5)9HN-YdA1Qy3fF5!^~;&%A&0Gr5wqr@i}*L$K}PyF;z<7$EnII0=b z3tfLG7<P|7SoQ6KL1s?AvG<jNVej;@?@bmAyO|Y6UsA0dV(vGFlFONDri=)<r(>jX zz;E=vT4=XVWOgHFZsV>fA#u#3rU9}t>bPBXK9e*KIx72ip}bjVj`}NylAlz~aYtn| z2_GsWd8w~4?JlOn%j_-q|Jr=gUwMi&4XSZ@eax3)%-)y^m~fb4Nz)K%Dgdh4{ZZzC zm+4RemNR}+JXsl60lf*PGsAR@s(_0Q^Jvn1Dyaf?vj?XcZ<O(>fU0r7dBSfRQvrPh z`+&p(BcG0J#$g#x!oLAaUP1CPwufMQ5!+n=d}Br0VYx_FO%wo458K%uH$GGgfUKh` zovfN7s|tV%_~h+Fz?gMC?}x|dlUz`&QFP0fM-b<)pGC|rk>401jdV5N9E%{jFA+f% zVDK^RU>G7RRl~7@0b&Njh{L2BzMnUwva8Q?%HL{$GYXtg{j9_u0?(Ob6?lFf*xc9a zQxg3vPL6?7_$GvV<TqyhD``b{bd*hcgDbB(&}@SJiWos+us(&j^Psl2nkSzG;@9d^ zv4xU#fH==lYfqM-lsM9i=EO6BTT?O383J6+h;18bd3`FYc^X%r&Q<H@#6<JPIZ+$9 zbxzWr%Wl~yk{eQz_8IIF$1XoXOf?^OYZIL8)+T#p)K|^_%!jMKTy^IKo&V;MWUq2F zw;RnRw7*C&7j#Y+G#VepUK#9_)p}7Xqs?Gy22&MN1Vw@kL^bbkpfBi>2pW-%v*6mu zdC{C(cq7UJMq;b^OD+L-CV(v}978Fe@K=oaE5=YOA}CH-0Yh3bhJZ$XYc$oXSh-_p zj?iCrYXFl4Og4)#k{*YkKaEn7{tCui$)(}O2$~Jruo@f2Oaq48Jdx^^H*=@aTulFO zqy<buQ_cS?ss~I0W2W`bp;SWu0mgiQF~Qmh3el}tO)JL4pl^Tc`=F+kdk)Rnm)$@L zfQf3W`PFsH0OMW;81J$LlyWbtApuiUj&pNM1f2<e8msv<#(1G`@-t_YUimZJ0-DP# zyX8fUaSPS_%`ajMVE~M1xQtSSp&n!EF@~~6&_#L+R<i|T?9j-+C8P8zTe!<;&Sz*G z)&mB?qp{m?6@S@uC$0<|K7fHVByDXQ-=w$tCVJ(qZ#g$ZWn$|9RJPIoF08ongCk7W z^yGns=kr^Xb8OfYcbLz5uFtPHalU{5G}ARUd2eCU2$@ei%<&gZ-n#rQ1%Q?V0EjOF zJOhB?<wd{*27JB<D93<31;B-_5e5T71wh+#!=_OH%p0m12KG?bA6oXOCzq%@=U=LB zyyc5UIH;R9^%T`XcrBgdOVyoAE>$<)@`WM*)XkgPivS3(r8BZr-8r%VKy&^36HM25 z%eIKoh!2px<{#IYi=jjA(vyuvIH<d9`uURN_jkrqOTv4K)D!`byYysXzjQ$ILEU9j zdl3NY`aAb5@sBg>@?)c>R?3@ItxVl6H$HzJ?>aSkpdkCR=8<b<x7>G)?8C*JKvMfV z(~FV{bLJ^>(WqeAE%y`wIobP*fSl};ivTcZo^mWrYPw}-9+2!cpC)nKo0lrjo!I#a zS!cdf%n6>+oeN8o`gC$pQejl$lPi~~t26f$0ibTOQ$0uVk^ps2`wItteh^+X{VG3b zh534}`x>pvfS-ha7dw9XP1Ctz+_}XTRhEqR*=}ud{P1GyUt5%xTWrUcN;{A!oR0-* pXX^?FEMBd6vGw1&cyYFLu3j<$(k%r&h56A*FJ5Ui_)ijC{{gEA?&<&l literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out/rect_prim.bin b/tests/x2w_shader/emit/ref/out/rect_prim.bin new file mode 100644 index 0000000000000000000000000000000000000000..e4298504efb75d0c557f9079ae57177da74de789 GIT binary patch literal 5255 zcmdUxdr%wKy~lU8%kCPa)yg8aj09fdjtASsUOxc?ww6^~NaR?p-ITng)FIdgEI`JF zG#R}t(HZrQI-z&)9p9;FoeY^K6Zuhxw#-D@<$4rH(@~0>kOuogiXD81IGUEGWTv<2 z@8}Uhdgng=ygTgSoc;aI=X`&^^OB{tN&5ZNk!?pFez(Vaw)_q5ol^&K48ww@7)HVW zT6mk`eIMSJ!SJ#Q!`_7V@PQVAfp7Vz<?uJR2cSW~oB!UPGa?@PjvlQx`yZ9ALN#MY ze#`AILK}TU5Bd+oVnhyf_|a!<Cwq^%j-Bknjy%{Z9Xj-FOQCWI)cgXxNqF;W2BD6g z6>74dGUd>+IvOOSX4$uY&3!|kzEYzuIJ}yx(m8vE!Dc`H_iB-~=U68M)AwA91+yJ~ zR9J$30=x)P1TPv8z3BN89u-UuL88BZd@`E8%1JhD$P4x7mbv4Yg+PEj7so9a0Xfc( zg{zt{Ja5eO|3CT@VlnFf<@*2Ko0rxs9&U!!_g_Ai))s3@hhc577+jzowJ8__#We=s zo21ySN=U#7u$6fEVwArUc#WYMls4L|8rAsIs7mmiLI73PW2;8@7$#6vixJHj)?&!! zUGKFw@m40V3WE3n4`TsGPyU{XnMC26?xfBgSI2lSmRt-I`^NCbIig`mX&A#d`+fCc zqJBuRscgwBKU!|{RD;L3)R<6ehluKgQXiA*5=7$#sV=G52tmD5oO5ft%-Sz7?QKEZ z#g{<&(=dC_%u4sg1hs4}t()-~Q_?=@m-HD!-l`kEx<pf5%4fWwm=bYYk)T$DNejC) zLoJ52X&d{e8R`<0Kr(B)>})SjOY1O^n-G4CVLqlr_#MtE0;BLvg!L4rz!1V<8au3k z!S1)jj?kD|;W;0p2S2bPzar~{Sd3TS|75IM-U<0A?TH0l_TZlOV1GLSb<LYLwll>J zK#6Gw1iB|e!=RmEwmV-rldp8!Y2=Wi?k;odGt&ch+Lfa2aCBeRGb20ec?V1p8hkou zSm5LcnJ?0Lv`?~+;p1KA%-)A)jQa#v@i{}FR>$SnyD)Lio!<}c%14Swcg{)Oy_L`R zwh#8=IG-~-#$)$GRZl7$E{MEZm#yxwK$X*zGUpL2X0^_sCnpTxz^QfWjBl4(S0$0x zI8VD;7lwa(EP|CY^)hRB1f7+7GLC41T4$5UzkO-tj`lW8|L)XNAD}<RYvt4ud5Z)x zuhH=md7Z;|BWE}q`eB_Wksg2YBaYPj@eet*-tYMrUj6UXh_I0%F4@l&J+V~OdM4Q4 zOb;{%PdkIFycne?XV3ABLl6!ByvoZ_&=H#N1d3XQ&f3d9@%+;&+1<fhSS6bea)FaR z^LO-q$7AkP)211@YFyruP;Ihuq%aI!NYS~GQFe%&Z1)P)db0Av=##Cl9yET?|C8MS z*N6ryM;-SHHlu$#?^`9us?F^qrA|lb)3f&-^^|U8yx`zJ>g9LA5TM~Vq{F_EX}aXt z?%Qeh?c#{tt;C*oqNd8Hkx1$!2o7sRQ<nLCqrWZ!Om}r_TYSw+_?laeir;!Femh$} z?eOyMI4Pb16z~Jjd3k@FbeJ>bi@y4puOUn{P7(X&iT$I9(7~7;AX4w2{fHlwt56rb zspJ)R$<NZoZ}KG<U?yXBFaHggsdK#gT~cJAR}?8%zFqvPvv`y%el1e`^H}j4=3)rs zLvCCq9TCX?FT}y3$A)=zQsrOs5We=n?0rv*YnnmcAjoS5Jv%c~Far^_0pGah@zJ6u z#)?{FXP-=+eQM?`>YE6})&eS%PgSj70rHyK%l4ADv64TA*-yjlVwnBh#=ZtalcIVf zBcqhIWu{{U)ZT!B_Ei7D%-*)MZ#&ufF#8`-_T#8$iTLh(QQwph6YF99K=Q%Uf#wL} z3LJy(#^N)BbpJ3tFvY`xW#tTZ{5^IS&Z6kZ82x=G9jjO)jPdMeZf%dV<n9bRmuCMW zXpO2DLG!x^rBUr)R8+I3I}RnS{m+zkgQ+J**F=M^s^AOFMLoks0}MS-72G5WO%A#* z8tilWTzs&{Ne>LKo>!Q&rgU7hFk+g6X+?AT5D->p2~IoxLKSFRy{Irj<aP%ymp!KI zV#VXL<%to~l;fdvZn!G?bcF6t(69wuh#cI6@5}6)CfGMS8MkR-*3?#tHx5dW+EA05 z?mt8K4tJ~XVA@YPcG1o5R5w+~@$%n{nA(J*jGNDxBpMS^V~A)>o(Tc<1%~c#4mttv zB>K(-oqTXzQpYZY*;zQk1??ZwES$qTxry>ym8Pl6a@kSQCj6j&+*hBH>aGwC<Guzz zQJ+kg_CZ+fbWMA(2TFI)84g0AeN}YdQW0QJyMxa#!EQsaXE@kD?5Vz&X7A0ge~z&W z0`V*aJvU-XX3A-Y>3XGU!c%_TLA@V_`$ei7&Xi+t=}5JM=w{jmgZ|Z9e}kxx!UfsQ zV^|$JM@r50erfNRLLM=r8{{)g+ZAI!<Jh@y@jXoY=ll(#x2e!IG)}-}S3fS*hNaD8 zM8gfDaZKEs^q8!64Z6i3>=`P}YwxDmyJqcOyY_at_`*!)tQR~FqAN2FTM;D_#0)80 zpnptigqv&_-DKpWVqSuvT}-oow6Sm6w2N64VRVn_EmU5GSa(I*n^LM%0Fr92C}gV8 znFZOG&06R`n}Q!>4v6)8@EZsA@}Q`4^M+kVqo>M0_@Ut&7~>TWQ|CW9^-<2ymU{6g zZ{-ZVRE5DEr>G6oD$Hw7MdE8IN31{Bx_}!7JqFjUT)*QS^*w>QX$WPRm#JsX)X|x< z`SCgg>Ny+rOx`?69ko+!>2rB=myLSfN!iW$p~gMyB6yh}UzfuX^z(M=n43B#JR8P% zhB|19#Mh0AW#{vNo-oxOrH(uEfTXAF0&YBy8*>1OJ`tfh-PG|spgbBc8xzY$^MJk- z)sd!-rSpJkkMRm_8Wr;ZAANF$>W)&Kc|b)hZcN0>5_!M?M>_?&1EX{KS@4)9@N!^e z6~r&oy&QeYOrOdDwChtI)09}A%mEr+w9&mzx=+Xf(o3H56kd_UD{_E8(Wh;6zZpET zInY+kc*^I+@~OB}+D*$&>A9i}>ZXXgrnOa&dGfkbF${{rG)LLFkid9$$lN@>Q?`MD zC>sWYojRH~{55Ydz7B>6bu4cPt1>+p<>jgk>UVzzoH%f}>rS63i4gQ@@T~UkkooHC zjE}3{p!WPUB$%SH%!t!5`Xx?XGas)Y70pX&I_@OaFNuO|R$qr7RX}Wth6Hj5h*i-0 zQb`gJ@O9K#9Al(Naoi<Ei{EE_o1-d0=Auo)O-}tDqih*N&9O}L9hZca+;mCR%=<21 zbyBXmX(p!_U-blXNg<aTvLPg-yboX??E!L96QB8^FsIrIO?)eA+7H%{zlu<knqTvw zxQp1fs4`k>IB{J_NXy8}vkiG|i^Un=Ha7uOw}f<@5M+V<7z6nqbJiMCF+efrq$f4E z`B>cLt2-}M0LEhq32+Rd!S(`1+`AZOh`pl-Gn&Di5#$uRfG`UPLztkrXD*)9e8w+= znuZDACcwnkhlH3?kJL0EH4URO<7-GEOe%wUMUb7^&k^Qxgpt-mvBZ^3YQEq{WtVT? zf>I3_d`n1}m-Znw`;nUc(=tQsUqYCr4CWHlR`WPucpVUYo1wUW7BCwsr)3w>GDOw_ zM%)?_!V}F%O$$=f5>^;rON4~Z5ev%A+kzZjy%}LPBaHF@6xA2mNzDV5Va4Tpc-&Ht za#I%)#w-sbHCCj?I-xLxHGwdR3}!))ZTejZvkPH}Iw<ydw3C{e$_d3qJTm9shjP<k zt(luRm_}dbEsfCdKe7akL*!qCn-P62zIswqcTxWZYSdRkqfxh@42n1$f|g&$%d(qQ z_>?*^eXVmU@N{mkT`|7iZG5ZJczSzwuT6GEuXRoz=t%ur_PDb`*SETjQQg`CAcX)= z6aXRuoG1V&1c)pHTmith)?@*;yVQv!0<>lU;w#42w<Ey*9N@>G;P`Z)liWa2a2Pvp z2aZo&TOsD^kCusnXcB>^3SuA{ow2td2BM)lVk^a5eJ>{lr30c#1RgH{AR3+V`2ql< zp*q4jz>#0Y%Pw~tuj*DtlL#CtM02t1Er&5a=s}r(@|PoJR|_l<6X=Y<te~qYm)c7g zOA4ulXeI(%3SuA{+&Gdu2VrhNOrSHBJ4g`#QhTX8ca-O%nF#FpYA!S4cdg9)fgM>h zN_59`prf>4ejO&}fbgsx-8|pz8Vz)Y3<kJ3<7bVpIgBe*{y$$q-Rz2J5`nENa;`JJ zQOG$=8r9*J3zG&pzq&nld408lau;|UHdJN>eYnCu8ZWF5SnUpDB5TgAr%PhN{68(9 zp|33;&)1gEwaqI+!Hq8!Ldh(jiLWgm@oUTH+U}Lhr>d|%G8=c<K1IuiDVYCp`M^)H G%=35r6>DDr literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out/sig_in.bin b/tests/x2w_shader/emit/ref/out/sig_in.bin new file mode 100644 index 0000000000000000000000000000000000000000..18dfeb6f9550c69dd52da660c9cf1e7ee49b2350 GIT binary patch literal 266 zcmZQ$U|`??Vh}h1p%@r}G&7XV&ktn)sVfL3SRSknrVuE17l=V(AONC4n1=<#gMeo+ z29O46V*+9%;~CyS<vD>g*lZ9DGZ4uB4VCAD%Krxfn0#<pd_aD2W=Up#9z%$0gtNbY pkPCw0?C;|r!~j&|S?pGnpI73Rn4AjY1}Ekg<fMA$rKDCc007FA9|`~f literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out/sig_out.bin b/tests/x2w_shader/emit/ref/out/sig_out.bin new file mode 100644 index 0000000000000000000000000000000000000000..68b1bf3be026a0cb3891a48d6bc027f923ac7541 GIT binary patch literal 123 zcmZQ(U|`??Vi3rHPz(-0ni<OGhtePlB+m%M4p17zX66ABP*4P=9f34R|9>E0<bwzX VhsB2^7Nw__FaTLDsRbn&3;<!d46OhF literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out_opt0/build.bin b/tests/x2w_shader/emit/ref/out_opt0/build.bin new file mode 100644 index 0000000000000000000000000000000000000000..e4bc1f9238ac5b0dd24c01fc46fc1c2d6716e4c6 GIT binary patch literal 108 zcmZ>XaB^0N6La42{OPYhB3#AUM^$?n85kIHfS4JGb%59$h*N+#*v-=bB*w_Z903HX QKqe<Kz|}V(1gMq)0Dc`0KmY&$ literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out_opt0/cs_basic.bin b/tests/x2w_shader/emit/ref/out_opt0/cs_basic.bin new file mode 100644 index 0000000000000000000000000000000000000000..6fa3da91b509157de10f6dac4b2b827bb43a49c3 GIT binary patch literal 2836 zcmZ`*e@q+K9e>9icNaLHkC-k73>>A6NJ_N_j);j(<nz&%WX^h1k}8?H<&2h;wvd@0 zqmXoxjosLhT+P$igrZC$*|f3!vARwFKoftQeKbR<*Lo{U_#=x<M%Xg31SMqaq^jHZ z9i~$w?MdJFzVG|K-_Q5Q`F)?ej|J2g-;ZB<_P3v}H2?j?yS3HF4^arA>Pm!ISUo^J zK*xakfSho+2k7wg2QUwN<VR&>IdJ%eHfs+&Szml?uN{5~&wv~QJw9X*5Gn`S8h&6% z9E2DkCy?a`)~#VHF+@)E$VzBSPV9)BE)k?;4Gv}^C;kX+$%+2f=ur;$RBvq_Tf2`P z2rg|y=oDCwf<v-r0Z;-x1LOhKxYZ;eGyrFn6LJOdPkhv+ivNMZ`O9W(@pZz|@&G<Z zm`1d1ro%Z;SUaM7pq`L0v2#r50XfK@+eT67yo}H=kum+a48I`dtK?xu$23mL$lbLP zv7h$a|BdW-u>EwTV!0@;7~&l~iK^WLUpkX3LF2w=e}Kh1sPe(OxUPv0{Pw$=_z*85 z!3;{B#aLZI-EXL!`B>dT0OppT$GmA%E5||%JDw9iEwUSFJJ>xevOkk69_iwHnz&J9 z?_zEUAE5*j=lA@O-akuqt<b(n(>EJ!g&B|vvAQYKwUE_Vzr?f!pGJn9D+``PS0h4J z4$#4)=&J6D@pgQadMef?JlSm=VX$DzIVSiPx~7A7;mIRLYgtl=@i%Z13(Yn|0(%ql zIXTA?B+LL37yJMjI>cdFya^WV`S@baHyQJ#1D=BF5uQdNs2d9>e83DQTIWn}!E8y! zy5QtHIH|ElaLHGQ`4&wN1f2}*FQ}dIvd(mj<O2m+jCD?_oeQQ`1|eOf@Q*s|8?yZo zCS`apTzNTd-_XQMesM)6ALOA`q*W+1d=QBJRg|xakl(7KddNtO=!uTL#CRVKyzL!L z94LrqU`F;cP|s;@Smp-O;@}oDw#5wU98oA(W#1Bx`nfYYH&S3%C2n+6sEdHGsksVA z(;Vmw6h*)(Ay^V`>O(3*Id8W@RGY()eo2+drOi2yU9xTs?D72hh;<`@k2HP6F#eK~ zFt}T`+6L_P<Q0mNO9$#jk&l#k=j}KBR*!(a|0~ceyudgZQ=+gU3ssVXS#ZTKw|vMb zxElo}L1l*A-P5)z!NL5_l`~mO^`=m@WJ=L*3sthpT$Q4hDWHJq$!{$&S=_B3l3c_5 zg?0t!0fkqYoF#2mna|zb#Rip`Cl0XXV8q?6#}=4uTf)y?BWe*)yT(xM+#vf(_<O@r zNMdgQl28?qdx8Y_2ep>rG*-g-CSN~RFzW{Qr{Fd!5sQ6|uo+fmbbg|##nP7Bx( z9Pai>SSusja??TSs$tv7$J!O=<hES+ki>Q@MR?U;eU%DI=U$)C+3#Y-`I~JyiFL%6 zFUZ1c8S22K9;)S*Wcgzzr0wMU5Vv`Boe9kXR0lxW4m?%vIC^|XrpegJD{cZlQ9GZt z6wDe68TZxw<n79R_i6gjClQ<C?3dfyBAX#y_lrAu)3vGgavkgT(0it2;ZIDcu#>0j z`uQb2rm!cc*;g~{09N#g@@{Wj-8XBVyKO5XC%yNWQJnD1(fb#&&sv?sd(-sw^DFuU ze%TR^iXHrj##P1#rxG@^eo?7U=?hfjO@G6+P{XZD4J#oRFu!1WaUjHvW)h>}*od4M z3Ug<swl8G)w_NL4+u9}9N~qzF%k?)y2Q{vF`;fuy%_PD)ceaHapW42d<r740m8#E0 zUDuR`Z!Xs_Tyiai4u-jA7g28E-k9db7r0|%i4lUF*hRTY-zEU7n~%8WmtCi-sjj5z ziJPfFgc~2@hNlLFRb>B%ByL1Rw-9K^W$Qn><T{1REwxx(p6*&uyHa#lek=vJXL)YC zClLk*VS02d5tb7*`6_WOEiOZo#`eEh&DSl>*WYS#Ej88WLJg<zdGB1z3*F{@+BX;T z#c6MTy?PW9>*MzJC5B**B*JNu>Szl$`e`}9z7a{B;1h$+#L!e?d@9;{Z(Y1s6dxJl z8m4<8?UhTeyfxp1$~L*?qxIK9?DaIXFV$*dYUix!nN&SV+B<1}6`X!H;a#M?8F+vO zWrV%~^>9cC9splZV<7jtMbR-<MqY_I+Bci^08E_jnxuEf;gtZ4*scZB`~K#mL4FmT zLCr><Ajr1J!ovjdZ9oMzaYhpF`NcI&bcC7z!6ntMsaPkp>P*fXr#mx&&WoxirS6|q z_T{6lAb#QtEcgfyG;!H4{>m?&PLnq0(Ah1Zs4s4IB?Di=nvHf6h;aQE5dV_Ie?p^% zzMUq_JIG!F>gTtB{$GOhZm5}IGRFhtLA(!^vVA#hzpU9;b@7gDzv8#whwi`mEJ6)K zP|H_HEt&ZwRThz*dxpd02KC|IFp_!pV^><y*k+bP6T0+!s)iZB7bK>cWnqv1pw!G| zc~xU`CEM`=+pDpsOSUgI%qSArR)DVd=j;w4gaG$~gxo?llfn#-b78I@r7$1Gx#@JY z{dEoP*!4FB_xqU-P`<X>I9hR57M^2Fl&WzCB=kH!9TB3)8KqJ?8KdNL#^8D}`~8wn z`|cG*2cJCnEX+(arn0r4Ws_M7GV}d9!$qC>?F{_{eGuKiTHBbvL)gnZYx3<v0Ow?b zYVVDZq<^}5PSGmDTac~sK#_F|<?rS(W8&T-Q91F9ku~lr)7%-ju~Nk+wrnWn^dNpB z``3y=W8|!~mTg#zHY9VKzPqpZD-J#bQRk9T8e(}fgSoF4IHhqzX<VmvrOHyc^)gC1 XWrEOAc_xz#G(v^8yT3;Mz`^)0rGZKk literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out_opt0/hashes.bin b/tests/x2w_shader/emit/ref/out_opt0/hashes.bin new file mode 100644 index 0000000000000000000000000000000000000000..cba03f0a96494eca0c41d81fc9fd82005af93151 GIT binary patch literal 3216 zcmV;B3~%!k4Pf@Sb>g~CO1{(qvgx4)`Ao8b(U=<a`KcQ>3gZa%FV`U2AvTpdPfX{p zIncM1=L6u%x>raV0L-$FsKIQIZB17ZEok?G#7@)LOWrOS{|5pX3aa#J&TPsN8ov-4 z?yo=H!Xr&_S?XI;e>iCf<cRVy#nSE+^1R{N9q;(gS}Rv~E8~}mG*ePa+f=}k-yg?p zaKjZ{$~J-F&>&><iFhN458lMM!fP8Sv~9<iYb=!2p96$zhJz;x#rxQOCw|{}??!w5 zcK+rhvf@<BZ%8%Ok_UGQ>NpPNk;~tBRECVAv@Rp#Roz8jb|8XyY#z~Z*0vYAseWaN za`(WH%n#06^%uesbgO!PdDJSmxSY+_2BRrn<hNrk%59Fx%D$^G>)@WT{<8UMr|x-n zT9KM6@zqB{>R>{)=^rIRIm)GW;nN38i8!zGYw?)rlaSDttcC2EMZ73;2Y%IJnh?*I z9>mO(gd*ocyd;EW7`2cU77vcRG*Py2#H;H;PHO2f8el<d;O5?^z!Fg>vHnPFJ;1`e zc_Gh`{6~jkx$<*UZoS`Lc`ujJR`y;8LGP7b`eEzipGb`oi7*=9-q*0!KQg?NHhMHc zA+yP`mlW~3W4!6i69D70Z!&q@JS7lkE8jodx+94IC=45TYbL6<pOIY$`wf<(?>_Qf z<Z-Mf*TqGx*07BW5yu^v^Bz&d46cx+>Q2j2j`e*lQ6gO8vf|A4UEFA$vj~+y$Jbu* zghb=+Pg|(uWC&pSua3A;jR3b<qkVThcYEA4o-k{H1?T}l``jrsJM>2C!8gs@PXjcT zIvG?M1{g0uWs@DxLs^g%E2F}~xpFc8`ZB!N#K4*MerV^-=kSEuR{2O7X7n^NU*t(l z%_90ctbHT!yml)Zz)HsK_y?I^FwWYCE~!Q+e|wBj|B;@dp_A(PjzxHxxn8fT0zWUg z4HLB*zE`@9+Xxfjmp>ckI+v>I-OF}7w*H|(7~Lc9+&VS;B>BaObIRq`(w&nibuHSQ zjmK{0IP{m1w<Ll%h?cCSv;zcOHy@H_RaftV(%CD0y0MsbM7JhkML(^nmid~s0SIVj zI7AE#8hR3CMYW5<!{rd}*z_WtgFeQJT_c0eU!_<{qRFXPh^rNyYEI}S^+qjpCsWyq zgrshowl$J=KNidR`mMnTakJc(G39lDoPX>m;isH!zXt^JGx;b?XPmgT$b-{;sus<{ zOr3D;aNqO8Ig0Gxl!%`I9(zQDANIFgwZgbGM~+OWqcm;t_c`l`HjC&XcRWphPep&W zmK!Sj5Mi3&q|6j71o&0&VQySv_EenUEO^3c$Z$9aYX+_ZYD86l)hGaPD<xwvEtZk( zq)ggh?@MSXcP*=?sh~uk5o4H(#IRs;jK{veN(%S&6H@!Vfb!f39N~Jsz?cNa2`hdt zTBIlE>{kuT9MCF5=x&Kz^4PmYu)3m|%a!~q4p^LcoX=KRXsWh8Q3?CZBKwlKR|Wt* z2jA0KM-|UMgzqu+FKK1r@uyn1x>>T5gywLx=^^?QG8^{nBj(uHe}T~tb=dFMaNP9~ z*JsR``MtDQi`Zngz1tt*+O2M&8^h@#w`zZ-tA)Z8?)cnzjfZ<D{8A>@{c(8z18F!7 zExtWQhb=v;H5wAdTg7ZYS1R)hP|otH;VF&;Y*oJGEl^YBTNeN+b?(m3ui>qW`p<%8 z5ae<{B~{p6-iOU6ygm&<F=3f|E4(E22IhifkZ+)a9J{T#(Zx#4y^xnG@8%`#m**@= zG`a<%_vTrP?7Tf@T#2d-B(O(Lrj42=T&LZ$e<qw-rrz+(`)?ZNUq@&JJEkqvMW4gZ zn&yQ;DvrPp8v?G6{w4$BmW4JfJsQ~KgeaiF`QqIU7YK)#S8<Cl7mbTpD2l6G@t_Mi z|3uLO4?<1`2LYhhF^p6ZDO~D;iS@2rgisbgd3fDAAsihJ2=AhV=!RjntN66YQrSd6 zB$awILJIOt4{xiu;Zt-c%(TGS<9qvQ%u?-RxjBDfbdQFJG(QYiT&9;JG=Xy-YBU(o z#~D^tlNc)&`d9S)b~H_>lD@gIA{!hpDz;{SIO-*=##-hNE+%@3^$5!wv+D^wLrU4c z)^fE!R76)7h8nb~eUtyu`14oWrHf?~lW^zvz>SbdoWrKau!+acR*T8of1}ay+EIMU zRF$v(HZ0Le_cRfLG(s(DTezHAE%cqTvPn2QTTToLtzGS6FFkUCJdzG&rz8n<+;EvC zW?gt<nq(qT{Qv-NR0T|9;NF|A6eG?t@mG;f@nl6EU=j9`%ANz2f}H9v>asV-D}B}5 ziZCiTQTstEV#MDG-SbNBlCyInW@Gf#ac^MgCys2yEU-@<J5rU9JvO;b%kY@bMhcMX z6_50AK91P~(;?_#HgPc6i_c_T@_p#Ho<Iuxb*l@ODn(*(0ZIh*Tv;+4f0Q9CvCi7b zN)KddMjp7`9C?dX;;sSpO|fu4YVzl7$re1tkkb^gKr)_gm2ni6JpLR>SqQ}voYkhT z2%gPx@J+0{poZ11_cQ`<L@<mv82i<v8g>a&q_ij`a@B&BMd`Liy!H2!j2OiaAFf~& za_V(aWX>vI`Y(^|IwF{iwwkz3=Zjp(f{U+?pNp#-by`q(uCbrzQ-Kj1lUJRe*uj@v zCt5(0^0(|Lk$qD8K(Fy;e9WS;sBMI3)<9kxRvnO}a}$H-$RKOe;Eh<DwfMg4TR#qm z8(*y!sPzUu_yGyeQZm<*ZtoA}8Dh*{*=%Qp{n5fF#=1mZ7rbkX6f8PFRrB*z5Y)GH zC$<LPNhdF7(8U`L%4+1(U1&gOO;ewb*=8CG!oS>}1lQc3sBB@1GzuR@hY>fV__`KV z6Tv9mauPlTKWUM!V8tbIwdQ)yj{+oC2a$C9e8@MQ^8k**Bx}33U$|hsGIc?zD$vr$ zXy<pC7D-?{3U;KM^9L7PA(aiOdqBf@XBA5Xref2W*wha?07R|lB<FWQzYfHggssF) z^#=ZVPyagHS)k48sHYLa=O{*c*^5*g2+TK*RobBeGT=T*p#eYHR3XAiT)iX7Fkc^n zaE@Bmxj^<W@1~KmMPya+NsEIyFiFKh0Yv35{ZD1Wla_7_Jw&3w_BDevt{m!4z>XCB z)5oVOnd>$0?pox8___$SeJDwZ=+l8BryitHZwcs9CpRW^`nu|fQZ-u{%+oyZYhzZT zI8WW-MSIRaRkI>~1fR5x`zNesHGIxp?a$x`Ap|PsM$(H7d8bd-d~b@wv9o0RIS;AB z@8}_;!AmnHo?sNt7Hn^LIMkT6@5C-s^lHapt!plOW%$fIOY1d<1FYk0_^O?XTd2F> z>w&~LQbeiF>nS(#C>^zv;oJMoH+%vv(`-V774BnO?ar<fry3ziFcXWHv3x@BohW)i z8jY2t>x#K>Q3ekx{iICAoo2Oou6hj*<fJS~1?fhN@4i9-a9bm=XS;2-Ac=LO7w<4e zhB0;uFt(Um*KaAU9o1D|D(;xLelzS5+n8&LkFkMpI!Qv3L>cJ1bH=-q-sVi~D&kwK z)cv7F&>=7DR#v&gm~3ROUtGnyS2doc@h=L%Kanvzw*tP;nV#)+tNl-uFXKS`_x?dF zRb#r_0r&Rtx-A!LpOYlB=<o`+`6-h`t~XRY%w!o}n&<jbC)<2oL@p1?@)Gz3W<!a3 zV1Ewlc4lYE#?Z7TV5UK%Mp;vVHFrytb?4~mU=p^QtiEX7-QHfPP7e51RY{R&o9(zJ zZ+uto<jD=Z^Ddsa6TxX_O1uKGGt>_|4=9e0Zn<Ndy2O#@@P40VF|D^Vz+Xg`pA2TC z83u=5RtyFx@Sz{+@n9k|U@Ugv2I%oTY@k?l_?Vd8Q_OUJ9~#>hm>MATtLXx@bdJ4* zH&1|HPU%B=EVOnIIBl_b35Z}VrR5&-+!^BA%ui#@G^<V-DrAd3kH>`xVP|N2{M^At zLD<Q})?bGfUiVUnEZLSzGmbHXP6M%!36H0^=~zFIUbla-%a3+GE?>vXN07<F-!$+| z9}hG-{w)ibq`zyPGl~K0rF~v<L{Y)a*$I^%^gyO_(D-fg8clopp&;p>=uxA^*)fZB zm@k2b;#>99c`Kh|#wj4INcZoX0>hAd)1|pjbMacc&uvN57U2nXEM{AgvjA%gkuAPJ z<MHgQ39Lf(m`6u#DijBl;i2Nk4DZ1#S>tGk1E{g&cmhRRRG%mhM!eFDSI>4AE<2^) CBTEMW literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out_opt0/ps_basic.bin b/tests/x2w_shader/emit/ref/out_opt0/ps_basic.bin new file mode 100644 index 0000000000000000000000000000000000000000..fcbb5ff88fad8f74e04c8b25e92888de91976046 GIT binary patch literal 3214 zcmb7Fe{2)i9e<a*++B!scbNk-a1Q6fqO^*-7s7&r6LgnL+km{`HMGm7w%FlU=zuyQ zqzUb+v(JfL%}j2aX+i3=WH7`ZOpPd$q6%sLk<ozM%3>W$JJco+SULfTXqf0!ZTr4+ zOexwwd%Ab`ecvCS?~nKHeOua_^|mk1_WWLXBk-$hk5H%4x=R#7=odDGSopeOw!-`h zW<3acix7GfX4{inFb_N!utI1{+f%it;mg2W;-eT5z#w?EMIj^>2v`p-@yLg;ExiZi zCm)g%N8$s#UoY7ZR>24PlF|0;4&O_M_Vw(0=^)zvM7zFi+tV#y6Z$sqwx`iHh<QEe z5}QKI)x;Qv3bPPO!6#sD4|MO{-Gh8>&tf;2VWRp!#(!WCHbar;n}eV_U|MB+KvcFw zKddi2#3ynx3w(*l@28m0tbk4QEIHAEL7^6!hAk@ipr~d<gK`0rqBTUpVp(1tQAI75 zd}&GSB@#cW$p1SF806ckwY63}$asKmY2V^qEJ0`w@O}odku?i3kvy&dzgbUy>VnhR z1G3VvvW&!23UhUQnv|VWi%ykA76?fz2k;;v)}WG8^^OTbiimE7(+V3v?CfEGv*P6k zOCagj6@+#W9<v)4;isf*xpIi{V;aX4RM#|XhzC{iOC(;$;z48C%(O6@6t3eTR8e=} z8#1L7H0FKc9V}c&rFRyD1)p$76+ib0U*M0BE#s9Mrp?tkeREQ8$eODso8eu3!t^9E zzG7@MvHc0*-ZZ<I5W((?Y4*6X?5<xp;}aIA+0QZ8jki;_49;$NgWfz&HO<nELz%|$ zPz}5RDQB)8&d8G~AFE1Ct@k@9sicd%htUMKrEx5W+EyC1ijHFosBO7X>v&&jX1vd! z3x1o)+wm_cM@C{yemQ=It~LV_quDa5?UCn_+c^kZkxYIi{<&(abNvB}*A?-EBrHmT zUXrYjC8>9Lg)ggfo>>s)Rq?nY{1Xb(XYy<CpErn$ig*{3@ZXh$TS&YK<-nz2y67X; zI3}^lnsi;Z+<^VGS9B+%J^pBYXSBbQ2D<DWpKu^29Dz3yk3jw-+#!WKkPx~GL|=jE z@^eHXXO*eI>{YoVey%6S-jKN7Jku`#LSFL*h(<WjIWR2%&Ju#f(cdnHvydN-s~c47 zVuNK;`a4ymEC~kP<x=5a!V|{~>%Rt>;rc-_qb@1gx*k`os}$D$*jp5(ED3(Bpe7*g zOhyXf7UY$9ok=n&IB_k8wMa`;t!8Akbz81_B_=OyQ8wz#CsGP)!K|xwC)Tj7Jo$kX zYO<B*K9HyqyUwhy_Db?0zP(;kY~>C+Gby*cx$bWO+>-o05j?+MQ?uaCrZe}jrpC(+ zg-?G*<Ri9nBgLd@qsq|~qiv+IhS)j?umfTuj{5A(PW=Ab+D?Og__5^REG>mLknjO~ zf`PR1kkm>*R`~FUrG`;I{D1F3?xjXaI^mVxTR*JWE--=CDxO}iInMj(M{Lv&9o(2p zt>X3dnq<~}L*dP`*crxqtue_2K%pbZ+9R%Gifz(b(r2jGPxycPSm~6a{*^64-`XF> z?7lHq4xrAsrmJ{!l~-cFH>LD_1|C<`yz4LhBPyN8;^**}E(o`=CSCT2mHl=mRA$8^ zP5Hxkot@D>9*cw=acX7HZa=%%VD};7_hadFiV674lJp3>I#M45!l+R@M=OGXiWg>< z?+R5^@oDhL><%k#dxScs@E=-nhR*~-raNIa_~}ijXwNv^*hg&l^NZl_Y^o@-Vk`CS zCuf$wpsi>Pgq3mF5nmPGT&Fn_CE*-NVOZfW4i1R_N{avXi>j-lB~Z~ykwOh7!Kt~b zrW(xKAqFsqAc=W6Z=Qt6M<F|iK^xfa8+gWD{A_3OkNS$+QN8qHg8Q9RYNeJ<=TkEv zwV#X)z-HC7?n$k9Ewm!7Rem@s&n+QC<lzwrX;)YogKEG&0&;5Lx!l0>BgHSw74NuL z92_4g)7<+VyEHk!>61vP=VyI_onhP6v$`AZ!2Q)9QqJ?Px@fWO@mR()ZOT`gH;vN` z=Q2&%%%JMbACIekGb!8}Q;lf<6h5bW&Sv;Qc_CFcJ1XCpasETAJP$-*t8p|qNv*k( zth_WT-*zpZ46K-Q$#bLfN#+xNz&Vww{3KO&DI{M^Ip+dfM})O-^>7=<qTPvTe{1yR zVDwSV6K~BUq(jb|qw;KEYfe}z6SZNkhv&Mhx&F?9mz8L@Kl*6O6Sv%r$X7y@v#vG% z8RsQ}TzQh2L)Lk3hVx#>8}h`Ayr+U{is|l1Cf;mt{e9e_;V#<^B;JBc(Gcov&6Vkt z6RNuh7h7uP>MY$fsW-*xrfgrlC&<0Ra}Z-N$Q=pNy?xQ35?z@s7j7nm8E8&eyk<3> zI%&fBsY{-6In#m4J@|FcIn$HV8_v>==gh_k?a3}w^!mA1I=PLV(QbGf(O@DP^mDz{ zT<^VNfPLAB?%<<cj%fFAw0}5Ma~pn+Y2j{CxQXeGNvOxDoVDIp0`f(dJP~qU46v6I zdc&mNFl@cYGwvbX9iu%%neT$rufm>>XwMil-Yx|po!osDswbjv8qYA>Rnqq6k$5mE z%uB*-V%cpZ-c`ke)^%;~D<WO<9NjpcaszyXZW^K=i$K=|Z1d5{jOT2=i4v>^udj@> zWT?V43ym7$&bOOWl5krUpaI!~%-3)+y=mBN7&05j(w+$2FxK4gw(gGWo5!_H*^ulV zTYewwnj&7e`qq7*lZrT>6HfVr86?_U*!!T35#5s{q2>EAb6G27hsDJO;f_yu$0sg6 zkRa3|05#c6YQm&qT9KhRHgx&f7ZYq}kX_4`ps+tTnOb=|v}%}I6?Z6z52x00JALd= zRS<I^mM%~ZCV)GFNa5MHWJAlb$4e;OVUYD-<cJ2B_LB4sXF^*zng=ntebavm0i+C& zT7=sp^{iz@zzcp%ZDh7yI@~33UAd!GOp@1gCHY7aGumFR*T<zg(^4EWzrh^|;^bK6 vt9=I7BgLyK(!4IQ>3kl$UX|D*Biv!&%NbtB_xZ13_SGc!q7;YDpCA7PtR8jq literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out_opt0/psv_cs.bin b/tests/x2w_shader/emit/ref/out_opt0/psv_cs.bin new file mode 100644 index 0000000000000000000000000000000000000000..ecd597530468ce56aa438d6047e0627fd24cc958 GIT binary patch literal 120 zcmXqDzyuCJArNK-Vi@26GC-ISh?#&`0*G0le0CrW!rVX%0w6X>9VZmS#6jv|003V& B0Vn_f literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out_opt0/psv_gs.bin b/tests/x2w_shader/emit/ref/out_opt0/psv_gs.bin new file mode 100644 index 0000000000000000000000000000000000000000..ee945a540822c21ef0e266bf7f087d78e038de84 GIT binary patch literal 216 zcmXqDU|?VdVpbq#gkm7Y@E-`67}yw?nHiXvKmurh2gDC?jd1q&4{`xAVQN5T2!Q0E ofRVw4nVAJ*Hb{t((TRZ>s2FA!BV!U!45k_+PMrGxKrQ$%0Nk?>$^ZZW literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out_opt0/psv_ms.bin b/tests/x2w_shader/emit/ref/out_opt0/psv_ms.bin new file mode 100644 index 0000000000000000000000000000000000000000..1091e610c6c0809fb1ec7ba2e3074bf40821aebc GIT binary patch literal 184 zcmYj}Q3`}G3`A#Izk~%3;2}JM+WH|VmEwordyvJO?@p@1KFBo5G}A#eCKo+ErTK~% zoI^!;ZB7;M(u3AypN^1HjtFT<8C#y$IP8O2&P3SFU%ck%eRb`N&k<gqpKS6CYN*W= Mbg}qP1{sR~1BXZrtN;K2 literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out_opt0/psv_ps.bin b/tests/x2w_shader/emit/ref/out_opt0/psv_ps.bin new file mode 100644 index 0000000000000000000000000000000000000000..bdb0aaa7cea2209212fc0c1df7e132f527f732ee GIT binary patch literal 400 zcmbVI%MQXY42zcu#AB%3_zeC4v6UNArHKP){{J5!E(wAjvE)j&GiU8lL;yP)JPouK zDt*^vz3GFo^#`AeIyFu1+~;@9md=g))bv-*@Duaf<vx`%XPL^i%%7c{uQ_K7kgRG8 zVmB~~+7D7!;!*FpuG8jqx#lhfdLF*t0fKFGamM-+??Sx$#`K$G&;0ZU*%^2NT`UfK literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out_opt0/rect_plain.bin b/tests/x2w_shader/emit/ref/out_opt0/rect_plain.bin new file mode 100644 index 0000000000000000000000000000000000000000..b3ddcf6f922d506798e17c66d26f124427cddafc GIT binary patch literal 4960 zcmb7`e^498702&%$K3(P>98CkEXh7f>!G&eEOu(ZfUDEV6xT{32R9{gen|dRoB|dO zvB62E`UP@ll&L(W9n$y@Xqnc3q+=RW2WMzUrz3=V)K-&_6gS|Ame{nD*f=3mXX<JC zRzD(0GM)5>TW;^Y{p|O>+kGp0vrVy`vrT@-e69AetDjuhxckXsk{}3|fgl+8Uk!I7 z+;72s5Da^D1mS_ZsbLr5;9d6G)%2~(Ug%J8XWzGEjF^Yt<4dnk|Ho}-?lEP@e#`C8 zLLa}w7yb{^5>y7%^x)&pqfZ{`JaV+1*t@e?x&QtL?74^gzpNUJ&Rk!pCToQMU#Nyp zJN$1o&ZY;^0yrYLvHU!^aXi`BK7mUI*@oD%;ej=Gr6&0_$aEgC6^|ElZqT<=6rJOe zq@AE3Y1z3*osA%~lcvUhIsZ>U^q0A_QX1u^#?{%*Xa3upcR3b7^kMj#+d(VtGoT5_ zk$}dgM6Z-Vz?EPt^h*UeUxjd+!bzMa)~Y*O6kNoQl+=cL@xwYI|Liv7IDXU<R3ky` zGN$uv@Vji1gX_(QpnoU<8#o4fnv0rc^eu0^*sJnU$xp<WBGisivVNYb>(lB+$qm6k zZG@`r)0{eIeB|_Un{N|%j4Ab#T6G__X;Q0=Dm9Z-{g6@<*PImMx61QgeY;ivF`<7K z>D#43Xn!6Nu3H7=jws?|j@32EfGMHufN}AFDeSM93e-&6Y7zm{kY=7#oq34Y&>ME) zR+3qY=og*Bhe_roXn|zax4VQVB~~dVWN{q*gdhT3A$pS(HN<I>jdDCiXfOpjwMaBs z2*d}h{8#MJy)40N5+C3U=nj$ypi@rrJojhF!|G$vP^T-jttHgmLcw#<Ij7K;5Kcl% z=uaZ{*Z>QYwMB%E>_b=fp~J;uhXnJFWp2l<>`52fnP9Gp?D4c`N^aWoDwqaX@M%j5 zz{wC&Z<I55Kcp|?-|n#z@a6Fp6|a#xDfLJYz178HYX3tYjX&?ru6u9UeR;Gu<HUDt zkg}ttLYi0y?+vsjl1P^L;`HMdJ3NX8Iwty%-O3jm4fMDX97MjD$G$#rSfkKGmG*%m z{N^>Y?x}d0^EFxp_oCukKR~kQk2hV-KRxsi{<FMRDI=gL^c5O_Qc<y_(3h}tlpwlc z9gbiP!QF3*v>`Y*E%Jt-`vr-gVFuB9PWz4P`MiC%@|wFs-Hq(Y#?T2*DBqvBSERq^ zm%0o=`FV-ELc6QibGnz@@~T5+{S(~-2mHuv(jD=mRzuMDw&Z-1b~{U?5of_DDmb@T z@RGH_Ko7nkag(&%vYrcUk;Sq6*nmT%4{FEU&u?pc<l3`u!H{jV8_C8C`LW?Pal*@k zn3ssbo(G~md%AkQ8_9d1U*g`OWh+d*RW|m4Du>v6$S+BzlC9O$J&jbQGw=;pV4Ekf zWg6LCi%crIag}yYuji<j<$h{=zr?@hKUC5>cc*L4a<$B|P-eNJTGn&6Dp@>}?@!(< zG5~}y=U}eM-dBa|g#H7ou;kL;8qnV!5O99Vh#pV~p6vmt;1?jcFOR#cPq#T7+c@Um z6p7LD0w{zSf0mB%s2^1rX!7!Kpa1J;bQ^-U4QFE;hHV?c6Nh~6(~$SeCI3gr51-B3 zH=5TR?Rg~8^Juc?p=os6w{a=fOA61B5ay+H)J6x62-)GoU3LZo)nTfpPh&`P-0hDN zg{O{lp-xYzC~y0ab~kZt*sJDsbg|Dw0{a@-6H@5JXsCNyd{G0PkU(Rr_*d0Z!d*jp z6Vv5kPZ;NLjq>42Gox&XXqysBbwa6e<ok;YYKH^$BTztKx<GA0>vLHeDsUNc>ED&~ zA4Y^5Nuf!1!gxAO2vW7vP_(qZsHLGAyCMC8D9k&B4-y48tirodaPCS^C)bQp^^;Jn zVzon<T<6Gt9UmWfUE^B1mGhd%=gfy!ll7;R>Yx_3dD-qR_R0PZ{wkq=Ulf+S!dBk4 zHl|wsG-y7I@=|UAQyf$4!&H5|E8OW}pXS)^#*oLup7c=1yFwl*R2nZ9-iruxP(qRZ z?~4M|!L8!B<w}`(y37)DuRV-@SUU!al$sH$ZY)p-F~t{GA9t}&x3E<$p<~c`L!L;; z<6@6ju*YxZ0rrG9^f(vlFourxhr0WHo31Yk*OS6WQQ<vA?VlVp&kvg8sdmO~zEox& z_gOBvnYSX4Dy61B)s8~ZSE^6pli_Zd^tQitimDxk1FA!U^9t|t)z;devVBye_gZlU zzd`8RqrwfyZlnMf_ea?ZZgA@GF)&8KVN*M%R7aEzqg34#RX-|kkNeCHR}ua$5O$LJ z(5k;7>EB%}fWeDS{Zf*-3N;t`cH)nz)<#pw1TlTuMi?Je>a!;ay+_VUa0>57ge6qC z1Rzm(ACU(?9UO)Mu$ExFQayr?TEZ<6#2)y~V4&4gvd$|R?{RsLJp9Y&j9(=<ziePG zUpO+IG3+1cnCZ<Jwle$v;-1YI4o15lyO1$7F|+?V@^;2>IO!veEiSY_LP#9*$I@rq zBJ)C3x>vNu>ocAruVu#lm~kWKK=iq+iYFxIpp|*l7)}d0&m3?vhmt*6bE}m(;9?HB zm~tkc@VgQta%n^@?I%k!{(ol<JDC;_b1*x%>5Q**h%6n-0z6*kdjrfNPZlsPuNhF+ z^s8AwIr~I}X>~EJS%CRP-<lD%^lTQ;8D+koWLgHYfGOEDteOT?Q%1o7wmrdkB1~Hr zU>Wn7#xWzEoVpVP+b*#k5}OWTF)5qJRP!WhP6N~*v&RUw6S1BQ;74oYvU!R$Ph|m5 zTiIhSwgY7Wi?SuIS|(L9U$xgGLGvJrN%SR8peL`Kw+--BVV{xKirfUFasjcToL4QV zoZktC0beN?4qLMZa$UwStgZnAWFj*{uE-cBWiuE&Nk;WhmPr}SKqO)qiGeLK#9adX zrgEPAIbStTt_8mnURL#JYZt*U!ghVmZzznudOjLPoNvpFR4^p+RbE>K3>$J5sGdMY z#D-#4{u2D?0nN7IFrt43vwWo6ilgJS4+`VyaLy$QqMRZYs-22dc$rf+#dRnq#%*X; z<X`6kcTM5$RI2-jPQ_E`LbKk&*f(Y)g|A4=8%6fWb7)?-nSi`(rr#(c@9tMQZSxWy zw3Hh34o6kr#@*Yg?pvLTD72wjNzj!#s-XCfshw0Y9t1T5y!sTFxL-4eQJ+?WsWm`V zqf9yf&xim*BLWCTVQ7YhlV~<7*vyWqkwEPt#>7=lfm#EYF^q{)6=5`{)B#4W!<YzL z&MzT7V2~bTqR=??ze2Mvy?>pfYKGb|6a$Pm#%cA_7&DJC3(CeYn%8z<H9IiIRZ!0V zCxJ1E6lMu9i~12XORS1*a8w0@jnf!2662IcFAbQm9WasL<}eD|cVRWVFa{Nt^A#Pd z0OMJO)trrWDv?!lXm((gZnLB6MS6Ew1Iz-b`Sw|i8Nry*@tQCi8Q+c7?8X>EDCf5n z8vr93FlGiY$Z#FaS`D@uN7YpD-YCYL(KzMa1jfu@Op>k-qZ#{sSj~MHlK@QJZ!l&! zg^6gLO2Y7OG@CT|>l{_L>E<PjNkG$lYy6w=#@;-QJHefe@F914^=}lpZyL%gXNi*i zgSb;x^0mrYYYF+y%-)_i4G)@LIc*xKOxLp0N29&%3k_{cucr65{r9Bll|j?U;GOBc zEq=_jF7&p?CmziKIxwI!2bgFB!1yx2%K(@w$pL0C;NeVhm@*B!F`y*_XaWTo(D&*o z9|=`_@7T>X7jtl|uKo5hIH>!rx>8-D;jx@L2(Qv~JO{w)+T+UrpzgQiG61McH0;X( zAiPS`6D!rVpUD6mzavc-03btn43ux@&57^NPprt@#SS4CI^=GucXJL7>SWWeGj%bY z{E1d?EC&E}7b`P$5howiP4#9=JA6G*Cz~#>@ISA9Cbg4k^QT(FMk78FUp1XOZOX`g zzxQ*p$u%owH$46s*(Y;Jg|9NvI<qpV7v+^nooaX_2S~|o&jH}8OtikZGN~7RnKgqx zVp^vm?uLg}D#zz#W<k#P*5u%j)IFw)E0W5z4KGV7teNvSS0;77H*;Fa>7?#49m)Yf z9n<E@r6aX~x1@JWX1%tX)8?$!3AEpZe=6K@bgZF$g|ySA`5Za5*=ANs8yPIfO@%jG z!@3+Gwb`-<DJ&SgoZG^ggB0&pyxH8DpCai{DouY_u>daaN#oS?*4txJm+!O!{96iN F{{;cA8kGP5 literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out_opt0/rect_prim.bin b/tests/x2w_shader/emit/ref/out_opt0/rect_prim.bin new file mode 100644 index 0000000000000000000000000000000000000000..2df65e1d7f6d92a6d69572501a3fbcd866c78ab2 GIT binary patch literal 5287 zcmdUxe{dVsoxpds^6o}jtyWfW6eOEfmB~2}=wc_49mhc{Dc~@oh=y_wzbfIx*u_62 z$8q8SbNUs_o$*aY8^CnZj$K?DuCxdez-7!u(z>oL=<bx-Z4FJR3{IMK0uil&(86%v zC#@<wy}4=sydCY^_ulvWKJWYezVCZa&Q`l)?&-*F>&$ESKlPWlpYHG3{ZBZCVLw`p zVI+JT;BA5T*YJJ^1m96$*o*M)x^<^OLtp9Hx$Cx@hoC{gTk7wSg@}jx(WBKCzo_gl zR||5aw_N@>v{4^=&=;n~2pP2Np0B%m_jUGn_V!?R?`U=0dFNN1<;tC4%`2d-gtuhP zFx1hr!kS`Np**szjwUHsv#jrXav$pYt2Inn;W@cV$?^h&Eq4Cj)*@+NXE!)Auy>~u zbMLxGxB}w@coC!mUNj+k(enj73RoOMiGF|k6m0ryOp0McT4+4COdZFZ1Ok+}IPSy< zh;eByTw%xXlCUuTAJivA6&nA=b${PmGOb12)dJb~zdp{^ovyqN!`dMk9s}D^n}j)# zU-Qs!cO>31Ljd-HOdaA?D1K^qjUzb}Hp-?rritWHmEgODAyl~zTXk%UVH#Dn7}0`Z zI}OFS>q8zp@1loRffL{4VJ_h4m2cAtlPKI4$mjw|Cc%fW%u<ZlK8ZIk65EbQ+a~er zBjKhP(R4&|E8LkAPb`-OH-g5Lqd6@#93eKQrKW_VF-<g2I2tpOn-G|KaWSCnv1vcW zwC4nE53h#u2Ql^o8|%0xAuuV|>c(8yn00K2ahb4jBvd;WZcN)7vti?eWJ)L96#^p( zvrhI(j$Ddq^KSM}Ir3#Ffn?M6c-VbB<yeb}+_dl{hJ|Uh@GG2?1X|+lglj)0!4$%9 z9^0jX$-d-F+)ZJO#B*U<4|*U)dKIo6Sb}H1bbn%FsvhF8x-Sv!_e8gJL<c(vsB2zy zv)x(t5R{nqkU;f~Q7~zDjP;i)2TK*dhe8Tj^5QbJ0ULG5L-l9L^Bgr$)GU}?)I1NO zF$#3Lb1ZOVLZQcT6z!AZV|aIyt+4l@nc#kpD|lHj)S%-^`7TU96DaM6fcYyG%7CoI z_;2D%qdmj>aGaL~yLrqERlQQ;a6#l5U9no{ges?3rnsQsv@tq^UO8<51&+}%1>GJ- zSL;yDaKR2n7lY3hr{LmD`{*@wQJ=Y>vDumX;=h&RmR}ry!1N10`bGJ)GATH7cW|^r z`AZJ3bB-}OcR?BD^dRJD2H6sM;kTSpAHm<^7=0x8U7mS|92eHp#LJ#%D(<^d(RwgC z*g_p@i5~DpSB3I-aFK^Yd?2axwyviY1{X)}3GwTURqO7m3UwZ(wxWUN7?hhu!<0tx zwL7?>y|`Wd!+`qPyy`_>Jpo?*`>IgP#VH>S2^;lFoLNsxbt3m|&6|h!zJ0>~y-#-Q zBi^^T2uv{soL58xQ8&sn8AYV(c6`mP3)eg-R<(FTJSd1Q>uGzvXn1N>C<m6b7c8l7 zAU3rSH@m}|J>f0BaNWG%^yJBcgVRN3_%(5q*b2;aXm3^5!Wz#)^?7sk1#|T~$?ElV z$|`c-Ulqb&i1!(u_6VXO1_pPvUdpj~Ub|@1ejL#LIidZ7CnWGjg&R0?N^gD({R2S- zLv{zU_6@mI?NsW9v|@vci}Zq3dS&t%o_SL#V&PS(ICSojzN&i8r#i-|o*z^FIHCH9 z4UK(^n@W|u9<JE^k9d9Wv5Na9D_RqW@6R57Aa@vzO%Em36c^$tjiMnU0lBK-xJP{w zQ~xo>z8_<kV(iCm_Ia3EX@*q@!D>d@3yU%i*3LnAw`_dR#-8)ACw=UN82g7f`))jV zh4|+S6$A4^LTrNMfe<104Mo3(I$^j`b#Ry(9HkD;^KeqRID-d2%`U(p6d#|Y9`jL& znkr$EXD<h|eLnTY9J`ojKM}M>#p7V}n+T;*+_EGo7EI^8QeOLcR%<c!B`9k=+Fu)e zw56hNwBis=9jc9P5CyxJ8i+>+eBpjR+UKJVjaFWe=)<ObQgdnCwCJt*<wErt@9jXS zEE0Sk>d{)Tt#V1Cqe$&MUY!b>PKh=5E>x$-P4nK{^YV1H)PXT-Fik=J_akz21HK*Y zVzh7U@U5o<rs)M!`)a&-*a6WUu?MKZgVerJKXV?_zR$5s0k)p8*QAow|21xE7b*&B zVPl49PCJ@Mh~~_}5dc3*Q-dv0AI#t*1`bAjd~|I_$6kuD3vhf3+V}D-oWb?nboD!C z)4aJl<*jKKzS%StZpu0uPY~Ot!rLN5QzpN906goUtR2xlC<9SnEDF93)KUXiDgb*R z5dAtG^&6snqtU_9;KmQ~><2maqXc_NARYq07spMRLV3n(I%PIZ2dhtc$zR9dZgDh@ z7RpJua2yT8=vMkNO!`@<X^v=$!$IQbF{}~dp<iulia54TO3J%!==QjbX?qgvWsY5p zsXoB8AC+zoy<35<peX__x~3^dL(FmgB(ZIdXr2_eW`ZV{M}uxKa63oBZo8OeFWR&h zJ=$|I)kLmv&I`dE=(<ccB?`d=V~$8S!1#ot8E&yrbc-qP5lbcr+NC`EM>qSTTf0=W zB8KiTy^}0iAvT_HY|Tm=vjB25oRE~+@?aLsK5o;(_=PO|5%YqtUGV<~w)3#42=InY zZDam3GyiH>htVO?LEiTp|J$-)Z({JlAIX9?^6V#_zmo+I=YqJQ>#W@B$R8FBzEZ0b zBOl_)qlS?p@LAF;kZsvuX|hLna*vIyDTyVr%}wsjJy{ZW+sJkg`MZ+%J#w#)d>A9! zgok1nPm}*?92M7&CE+K}?emfCF|xx$TF6yc$djGMuRR*Pb|Sb|p58)r2FOP|<Rc}3 z>6mzJJh^tF1n7^G-^h|3u@YboH@*-wjs=Y}ppEKIki9Xos|2W?6pe`>Fk}l3=E)w8 z`UXeI7A)eXsi5hFWC`#r<;SRfz>opos!8LfY!ZG&z_v#P%I~K7c^Qz;<JIY4^<2<Y zv>-W4?H8y6JawQ1xNaV=&LvHACBVP<sQodj-%UxHCrvaI*Ng~su<ne<o20{Bt)yw= z$)wL=2#7+8SDvCBF)BklbRdAZC4J$wv63KH5_H9p;M$3jKv2me`Zy}-BTSQ`aK=XU zaf~%Bnv@o1dTc~sLUn+DlXe7vJQx5ysX7OGaq2P9Tf}Rw*26Yfn4LEY7REltScerG zl#*tQQvrU%5xa1PS50su0vE1J3G^xOW21!$J~tw`P9_T8rQ#8yzTl2@!=yq;anp9; zESI)#Npb4q*odG!&bh40@TQbU{R(Qnf|`!Hv)mcD@U6L!?+)u?=%(RhKcU-WVSW}+ zCum1po$Plc)a^nlu6_dzdIJrTtSO8=iJB)1$jxWDh{Ncz4u@^ztOo9uUg4}w34;Xo zU8HpmX`L4+3v<rL0@cR?Rfxk{Y@Hy$&<O_^%Ctf8Lb%3djfXjER`Y(2eGFmt38^f5 z31KcHOdeBNn9H0NFq{@)7Lzobx(JggV0?g?lQy`l^Whv|J_%@_N0>1o<<owQFrOmK zpR<7ZG>$Ow0%kNthi_Rzn56>dalm{=+~~3fB5~EM#%!*96=8k?3Y9z#7>f=t>&Dd< z#&TCBVBD3+noNo&Za=C7t)oul)W1P7;cReOk3|CNS<MZ}%J&fFbqHwX^$2q#!rbI% zEzFG{B22!32}pF<HH|RS1<Y%J$wZo5)@;Ph&T2M$^?8K(y^wP2HzAA_VH!lOg|R-N z2TV+ltT`dk#GRKA=28K(2$-em?Jnz;2(O*h+=5qqjxbBYS*&XNhp0za^)YIAb(OQ4 zHeF8YceH*s-2zcK+<E~uhIj0ASz|jAS_@eLrweyD+9hww)ip1lHolQGj^A87n06gZ z-`cxG_FVaSaaX$*%*HoP8(({AP4QR|VCd4Vz4PRQWxzNB>@Nd`dH|4K26!C+A6AtC z7ZBh+`CzK3dHD$h=#&B1fCUIJDg*A$nT;=<HcshA3<fyalOGx5Nn@D>#^lM4vN7OI z(D-=S81QDM`@%9~z?)b7%e(<&^5g?$0C*EL`pW?DW~O^`834R_^(EOGcQD$uhyeGl z@Fr;7yUd%eC9+p(AxVh5?{l&%KeHmVQ$coxH@TUc%Eo{<e&bK&1GBg`L*0>7834vi ziSmhy)&{)E&B&KV5*8P{@f+oP5UnLL{`3l4lg9rj;!vP}cG@_3S6Qq>3zHlU;&8p* ze-bxN-TaUTU0+Z4PLaJUto(nTK{Jgjya^g#UlH?}?i0&mjxq>Wl@|?V&`jx;E5<x% zY%c=}8MJ4G{ybS<+;4KW_wq%toKHFO?@yn*u1X*B>h$?>*%H_cL)};8`&LeeDcx1+ jLtdRezgdxPua1}Vqp)%1bS|Zjxh($M^ijc|Q+WOdnVM`- literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out_opt0/sig_in.bin b/tests/x2w_shader/emit/ref/out_opt0/sig_in.bin new file mode 100644 index 0000000000000000000000000000000000000000..18dfeb6f9550c69dd52da660c9cf1e7ee49b2350 GIT binary patch literal 266 zcmZQ$U|`??Vh}h1p%@r}G&7XV&ktn)sVfL3SRSknrVuE17l=V(AONC4n1=<#gMeo+ z29O46V*+9%;~CyS<vD>g*lZ9DGZ4uB4VCAD%Krxfn0#<pd_aD2W=Up#9z%$0gtNbY pkPCw0?C;|r!~j&|S?pGnpI73Rn4AjY1}Ekg<fMA$rKDCc007FA9|`~f literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/out_opt0/sig_out.bin b/tests/x2w_shader/emit/ref/out_opt0/sig_out.bin new file mode 100644 index 0000000000000000000000000000000000000000..68b1bf3be026a0cb3891a48d6bc027f923ac7541 GIT binary patch literal 123 zcmZQ(U|`??Vi3rHPz(-0ni<OGhtePlB+m%M4p17zX66ABP*4P=9f34R|9>E0<bwzX VhsB2^7Nw__FaTLDsRbn&3;<!d46OhF literal 0 HcmV?d00001 diff --git a/tests/x2w_shader/emit/ref/ref_dump.rs b/tests/x2w_shader/emit/ref/ref_dump.rs new file mode 100644 index 0000000000..6455831f17 --- /dev/null +++ b/tests/x2w_shader/emit/ref/ref_dump.rs @@ -0,0 +1,254 @@ +//! Generate the reference bytes for the C++ emitter tests in a temporary +//! checkout of the upstream Rust emitter. The adjacent README.txt identifies +//! the crate, test invocation, and optimizer settings. + +use super::bitcode::{Attr, Bin, Cast, Rmw, Term, pred}; +use super::container::{self, Binding, Psv, SigElement}; +use super::shader::{Mesh, Shader}; + +fn out_dir() -> std::path::PathBuf { + std::path::PathBuf::from(std::env::var("X2W_REF_OUT").expect("X2W_REF_OUT")) +} + +fn put(name: &str, bytes: &[u8]) { + let dir = out_dir(); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(format!("{name}.bin")), bytes).unwrap(); +} + +fn el(name: &str, index: u32, kind: u8, comp: u8, row: Option<u32>, col: u8, cols: u8, interp: u8, usage: u8) -> SigElement { + SigElement { name: name.into(), index, kind, comp, interp, row, col, cols, usage, half: false } +} + +/// Signature, PSV0, build and hash of fixed inputs. +fn containers() { + let ins = vec![ + el("SV_Position", 0, 3, 9, Some(0), 0, 4, 4, 0xf), + el("TEXCOORD", 0, 0, 9, Some(1), 0, 2, 2, 3), + el("TEXCOORD", 1, 0, 5, Some(1), 2, 2, 1, 1), + el("COLOR", 0, 0, 9, Some(2), 0, 4, 2, 0), + el("SV_IsFrontFace", 0, 13, 5, Some(3), 0, 1, 1, 1), + el("SV_SampleIndex", 0, 12, 5, None, 0, 1, 0, 1), + ]; + let outs = vec![ + el("SV_Target", 0, 16, 9, Some(0), 0, 4, 0, 0xf), + el("SV_Target", 1, 16, 5, Some(1), 0, 2, 0, 3), + el("SV_Depth", 0, 17, 9, None, 0, 1, 0, 1), + ]; + put("sig_in", &container::signature(&ins, true)); + put("sig_out", &container::signature(&outs, false)); + let bindings = [ + Binding { kind: 2, space: 0, register: 0, dxil_kind: 13 }, + Binding { kind: 1, space: 0, register: 3, dxil_kind: 14 }, + Binding { kind: 4, space: 1, register: 7, dxil_kind: 11 }, + Binding { kind: 7, space: 1, register: 9, dxil_kind: 11 }, + ]; + put( + "psv_ps", + &container::psv(&Psv { + stage: 0, + flag: true, + inputs: &ins, + outputs: &outs, + prims: &[], + mesh: None, + geometry: None, + bindings: &bindings, + threads: [0; 3], + wave_size: None, + }), + ); + let prims = vec![el("PRIMDATA", 0, 0, 5, Some(1), 0, 3, 1, 7)]; + put( + "psv_ms", + &container::psv(&Psv { + stage: 13, + flag: false, + inputs: &[], + outputs: &ins[..4], + prims: &prims, + mesh: Some((Mesh { max_vertices: 64, max_primitives: 126, topology: 2 }, 4096)), + geometry: None, + bindings: &[], + threads: [128, 1, 1], + wave_size: None, + }), + ); + put( + "psv_cs", + &container::psv(&Psv { + stage: 5, + flag: false, + inputs: &[], + outputs: &[], + prims: &[], + mesh: None, + geometry: None, + bindings: &bindings[2..], + threads: [8, 8, 1], + wave_size: Some(64), + }), + ); + put( + "psv_gs", + &container::psv(&Psv { + stage: 2, + flag: true, + inputs: &ins[..3], + outputs: &ins[..3], + prims: &[], + mesh: None, + geometry: Some(6), + bindings: &[], + threads: [0; 3], + wave_size: None, + }), + ); + // The container hash of every length 0..=200 (pattern bytes), concatenated. + let mut hashes = Vec::new(); + for n in 0..=200usize { + let data: Vec<u8> = (0..n).map(|i| (i * 7 + 3) as u8).collect(); + hashes.extend(container::hash(&data)); + } + put("hashes", &hashes); + let a = [1u8, 2, 3]; + let b = [9u8; 37]; + put("build", &container::build(&[(b"SFI0", &a), (b"XXXX", &b), (b"EMPT", &[])])); +} + +/// A compute shader through the Shader API: user data, root views, LDS, a loop, a branch, wave +/// operations, a heap handle, atomics. +fn cs_basic() -> Vec<u8> { + let mut s = Shader::new(false); + s.threads = Some([64, 1, 1]); + s.wave_size = Some(32); + s.lds_dwords = 256; + s.user_data = 6; + let b = s.entry; + let i32t = s.t.i32; + let ud = s.user_data_handle(); + let zero = s.m.i32(0); + let row = s.op(b, "cbufferLoadLegacy.i32", Attr::ReadOnly, s.t.cbuf_ret, 59, &[ud, zero]); + let x = s.m.extract(b, row, 1); + let tid = s.op(b, "threadId.i32", Attr::ReadNone, i32t, 93, &[zero]); + let four = s.m.i32(4); + let off = s.m.bin(b, Bin::Mul, tid, four); + let srv = s.root_srv_handle(3); + let undef = s.m.undef(i32t); + let one8 = s.m.i8(1); + let ld = s.op(b, "rawBufferLoad.f32", Attr::ReadOnly, s.t.res_ret, 139, &[srv, off, undef, one8, four]); + let vf = s.m.extract(b, ld, 0); + let v = s.m.cast(b, Cast::Bitcast, vf, i32t); + let sum = s.m.bin(b, Bin::Add, v, x); + // A dead value and a constant fold for the clean-up. + let k = s.m.bin(b, Bin::Add, zero, four); + let _dead = s.m.bin(b, Bin::Mul, sum, k); + let lds = s.lds(); + let k255 = s.m.i32(255); + let idx = s.m.bin(b, Bin::And, tid, k255); + let p = s.m.element(b, lds, idx); + s.m.store(b, p, sum); + let p2 = s.m.element(b, lds, idx); + let back = s.m.load(b, p2); + let old = s.m.atomic(b, Rmw::Add, p2, back); + let exch = s.m.cmpxchg(b, p2, old, back); + // A loop: i from 0 while i < x. + let (head, body, exit) = (s.m.new_block(), s.m.new_block(), s.m.new_block()); + s.m.terminate(b, Term::Br(head)); + let i = s.m.phi(head, i32t); + let acc = s.m.phi(head, i32t); + let c = s.m.cmp(head, pred::IULT, i, x); + s.m.terminate(head, Term::CondBr(c, body, exit)); + let one = s.m.i32(1); + let i2 = s.m.bin(body, Bin::Add, i, one); + let zero8 = s.m.i8(0); + let wsum = s.op(body, "waveActiveOp.i32", Attr::NoUnwind, i32t, 119, &[acc, zero8, one8]); + let acc2 = s.m.bin(body, Bin::Xor, wsum, exch); + s.m.terminate(body, Term::Br(head)); + s.m.set_phi(i, vec![(zero, b), (i2, body)]); + s.m.set_phi(acc, vec![(sum, b), (acc2, body)]); + s.flags |= super::shader::flags::WAVE_OPS; + let two = s.m.i32(2); + let heap_index = s.m.bin(exit, Bin::LShr, acc, two); + let h = s.heap_handle(exit, heap_index, false, true, (11 | 0x1000, 0)); + let f = s.m.cast(exit, Cast::Bitcast, acc, s.t.f32); + let fi = s.m.cast(exit, Cast::FpToUi, f, i32t); + s.op(exit, "rawBufferStore.i32", Attr::NoUnwind, s.t.void, 140, &[h, off, undef, fi, undef, undef, undef, one8, four]); + let uav = s.root_uav_handle(5); + let sel = s.m.select(exit, c, fi, acc); + s.op(exit, "rawBufferStore.i32", Attr::NoUnwind, s.t.void, 140, &[uav, off, undef, sel, undef, undef, undef, one8, four]); + let cbv = s.root_cbv_handle(2); + let crow = s.op(exit, "cbufferLoadLegacy.i32", Attr::ReadOnly, s.t.cbuf_ret, 59, &[cbv, zero]); + let cx = s.m.extract(exit, crow, 2); + s.op(exit, "rawBufferStore.i32", Attr::NoUnwind, s.t.void, 140, &[uav, cx, undef, cx, undef, undef, undef, one8, four]); + s.m.terminate(exit, Term::Ret); + s.finish() +} + +/// A pixel shader: inputs read, outputs written, an immediate sampler and a heap texture. +fn ps_basic() -> Vec<u8> { + let mut s = Shader::new(true); + s.inputs = vec![ + el("SV_Position", 0, 3, 9, Some(0), 0, 4, 4, 0x3), + el("TEXCOORD", 0, 0, 9, Some(1), 0, 2, 2, 3), + el("TEXCOORD", 1, 0, 5, Some(3), 0, 1, 1, 0), + el("COLOR", 0, 0, 9, Some(2), 0, 4, 2, 0), + ]; + s.outputs = vec![el("SV_Target", 0, 16, 9, Some(0), 0, 4, 0, 0xf)]; + s.samplers = 2; + s.cmp_samplers = 2; + s.user_data = 1; + let b = s.entry; + let f32t = s.t.f32; + let mut uv = Vec::new(); + for col in 0..2u8 { + let ty = s.t.i32; + let args = [s.m.i32(1), s.m.i32(0), s.m.i8(col), s.m.undef(ty)]; + uv.push(s.op(b, "loadInput.f32", Attr::ReadNone, f32t, 4, &args)); + } + let ud = s.user_data_handle(); + let zero = s.m.i32(0); + let row = s.op(b, "cbufferLoadLegacy.i32", Attr::ReadOnly, s.t.cbuf_ret, 59, &[ud, zero]); + let slot = s.m.extract(b, row, 0); + let tex = s.heap_handle(b, slot, false, false, (2 | (9 << 8), 0x0409)); + let smp = s.sampler_handle(b, 0); + let undef = s.m.undef(f32t); + let i32t = s.t.i32; + let ui = s.m.undef(i32t); + let r = s.op( + b, + "sample.f32", + Attr::ReadOnly, + s.t.res_ret, + 60, + &[tex, smp, uv[0], uv[1], undef, undef, ui, ui, ui, undef], + ); + let half = s.m.f32(0x3f00_0000); + for col in 0..4u32 { + let v = s.m.extract(b, r, col); + let m = s.m.bin(b, Bin::Mul, v, half); + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col as u8), m]; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.m.terminate(b, Term::Ret); + s.finish() +} + +fn rect_outputs() -> Vec<SigElement> { + vec![ + el("SV_Position", 0, 3, 9, Some(0), 0, 4, 0, 0), + el("TEXCOORD", 0, 0, 9, Some(1), 0, 4, 0, 0), + el("TEXCOORD", 1, 0, 5, Some(2), 0, 2, 0, 0), + ] +} + +#[test] +fn ref_dump() { + containers(); + put("cs_basic", &cs_basic()); + put("ps_basic", &ps_basic()); + let wanted = [el("SV_PrimitiveID", 0, 10, 5, Some(3), 0, 1, 0, 0)]; + put("rect_prim", &super::rect::build(rect_outputs(), &wanted).unwrap()); + put("rect_plain", &super::rect::build(rect_outputs(), &[]).unwrap()); + println!("ref_dump wrote {}", out_dir().display()); +} diff --git a/tests/x2w_shader/emit/ref_test.cpp b/tests/x2w_shader/emit/ref_test.cpp new file mode 100644 index 0000000000..fbb2f8e581 --- /dev/null +++ b/tests/x2w_shader/emit/ref_test.cpp @@ -0,0 +1,272 @@ +// Byte-for-byte comparison with the upstream Rust emitter: the same fixed inputs as the reference dump +// (ref/ref_dump.rs, run in a temporary checkout of the upstream crate), +// whose outputs are read from the directory in X2W_REF_DIR (out/ for the default clean-up passes, +// out_opt0/ for X2W_SHADERCFG_SHADER_OPT=0; the test must run with the same setting). + +#include <cstdio> +#include <cstdlib> +#include <fstream> +#include <iterator> +#include <string> +#include <vector> + +#include "x2w_shader/emit/container.h" +#include "x2w_shader/emit/rect.h" +#include "x2w_shader/emit/shader.h" +#include "test_util.h" + +using namespace x2w::vs; +using namespace x2w::vs::bitcode; +using container::Binding; +using container::Psv; +using container::SigElement; +using shader::Shader; + +namespace { + +std::string dir() { + const char* d = std::getenv("X2W_REF_DIR"); + return d ? d : ""; +} + +std::vector<std::uint8_t> read(const std::string& name) { + std::ifstream f(dir() + "/" + name + ".bin", std::ios::binary); + return std::vector<std::uint8_t>(std::istreambuf_iterator<char>(f), {}); +} + +void same(const char* name, const std::vector<std::uint8_t>& got) { + const auto want = read(name); + if (want.empty()) { + std::fprintf(stderr, "%s: no reference\n", name); + CHECK(!"reference missing"); + return; + } + if (got == want) { + std::printf("%s: identical (%zu bytes)\n", name, got.size()); + return; + } + std::size_t at = 0; + while (at < got.size() && at < want.size() && got[at] == want[at]) ++at; + std::fprintf(stderr, "%s: DIFFERS (got %zu bytes, want %zu; first difference at %zu)\n", name, got.size(), + want.size(), at); + std::string path = dir() + "/" + name + ".cpp.bin"; + std::ofstream(path, std::ios::binary).write(reinterpret_cast<const char*>(got.data()), std::streamsize(got.size())); + CHECK(!"bytes differ"); +} + +SigElement el(const char* name, std::uint32_t index, std::uint8_t kind, std::uint8_t comp, std::optional<std::uint32_t> row, + std::uint8_t col, std::uint8_t cols, std::uint8_t interp, std::uint8_t usage) { + SigElement e; + e.name = name; + e.index = index; + e.kind = kind; + e.comp = comp; + e.interp = interp; + e.row = row; + e.col = col; + e.cols = cols; + e.usage = usage; + return e; +} + +void containers() { + const std::vector<SigElement> ins = { + el("SV_Position", 0, 3, 9, 0, 0, 4, 4, 0xf), el("TEXCOORD", 0, 0, 9, 1, 0, 2, 2, 3), + el("TEXCOORD", 1, 0, 5, 1, 2, 2, 1, 1), el("COLOR", 0, 0, 9, 2, 0, 4, 2, 0), + el("SV_IsFrontFace", 0, 13, 5, 3, 0, 1, 1, 1), el("SV_SampleIndex", 0, 12, 5, std::nullopt, 0, 1, 0, 1), + }; + const std::vector<SigElement> outs = { + el("SV_Target", 0, 16, 9, 0, 0, 4, 0, 0xf), + el("SV_Target", 1, 16, 5, 1, 0, 2, 0, 3), + el("SV_Depth", 0, 17, 9, std::nullopt, 0, 1, 0, 1), + }; + same("sig_in", container::signature(ins, true)); + same("sig_out", container::signature(outs, false)); + const Binding bindings[] = {{2, 0, 0, 13}, {1, 0, 3, 14}, {4, 1, 7, 11}, {7, 1, 9, 11}}; + { + Psv p; + p.stage = 0; + p.flag = true; + p.inputs = ins; + p.outputs = outs; + p.bindings = bindings; + same("psv_ps", container::psv(p)); + } + const std::vector<SigElement> prims = {el("PRIMDATA", 0, 0, 5, 1, 0, 3, 1, 7)}; + { + shader::Mesh mesh{64, 126, 2}; + Psv p; + p.stage = 13; + p.outputs = std::span<const SigElement>(ins).first(4); + p.prims = prims; + p.mesh = &mesh; + p.mesh_lds_bytes = 4096; + p.threads = {128, 1, 1}; + same("psv_ms", container::psv(p)); + } + { + Psv p; + p.stage = 5; + p.bindings = std::span<const Binding>(bindings).subspan(2); + p.threads = {8, 8, 1}; + p.wave_size = 64; + same("psv_cs", container::psv(p)); + } + { + Psv p; + p.stage = 2; + p.flag = true; + p.inputs = std::span<const SigElement>(ins).first(3); + p.outputs = std::span<const SigElement>(ins).first(3); + p.geometry = 6; + same("psv_gs", container::psv(p)); + } + std::vector<std::uint8_t> hashes; + for (std::size_t n = 0; n <= 200; ++n) { + std::vector<std::uint8_t> data(n); + for (std::size_t i = 0; i < n; ++i) data[i] = std::uint8_t(i * 7 + 3); + auto h = container::hash(data); + hashes.insert(hashes.end(), h.begin(), h.end()); + } + same("hashes", hashes); + const std::uint8_t a[3] = {1, 2, 3}; + std::uint8_t b[37]; + std::fill(std::begin(b), std::end(b), std::uint8_t(9)); + const container::Part parts[] = { + {{'S', 'F', 'I', '0'}, a}, {{'X', 'X', 'X', 'X'}, b}, {{'E', 'M', 'P', 'T'}, {}}}; + same("build", container::build(parts)); +} + +std::vector<std::uint8_t> cs_basic() { + Shader s(false); + s.threads = std::array<std::uint32_t, 3>{64, 1, 1}; + s.wave_size = 32; + s.lds_dwords = 256; + s.user_data = 6; + const std::size_t b = s.entry; + const Ty i32t = s.t.i32; + V ud = s.user_data_handle(); + V zero = s.m.i32(0); + V row = s.op(b, "cbufferLoadLegacy.i32", Attr::ReadOnly, s.t.cbuf_ret, 59, {ud, zero}); + V x = s.m.extract(b, row, 1); + V tid = s.op(b, "threadId.i32", Attr::ReadNone, i32t, 93, {zero}); + V four = s.m.i32(4); + V off = s.m.bin(b, Bin::Mul, tid, four); + V srv = s.root_srv_handle(3); + V undef = s.m.undef(i32t); + V one8 = s.m.i8(1); + V ld = s.op(b, "rawBufferLoad.f32", Attr::ReadOnly, s.t.res_ret, 139, {srv, off, undef, one8, four}); + V vf = s.m.extract(b, ld, 0); + V v = s.m.cast(b, Cast::Bitcast, vf, i32t); + V sum = s.m.bin(b, Bin::Add, v, x); + // A dead value and a constant fold for the clean-up. + V k = s.m.bin(b, Bin::Add, zero, four); + (void)s.m.bin(b, Bin::Mul, sum, k); + V lds = s.lds(); + V k255 = s.m.i32(255); + V idx = s.m.bin(b, Bin::And, tid, k255); + V p = s.m.element(b, lds, idx); + s.m.store(b, p, sum); + V p2 = s.m.element(b, lds, idx); + V back = s.m.load(b, p2); + V old = s.m.atomic(b, Rmw::Add, p2, back); + V exch = s.m.cmpxchg(b, p2, old, back); + // A loop: i from 0 while i < x. + std::size_t head = s.m.new_block(); + std::size_t body = s.m.new_block(); + std::size_t exit = s.m.new_block(); + s.m.terminate(b, Term::br(head)); + V i = s.m.phi(head, i32t); + V acc = s.m.phi(head, i32t); + V c = s.m.cmp(head, pred::IULT, i, x); + s.m.terminate(head, Term::cond_br(c, body, exit)); + V one = s.m.i32(1); + V i2 = s.m.bin(body, Bin::Add, i, one); + V zero8 = s.m.i8(0); + V wsum = s.op(body, "waveActiveOp.i32", Attr::NoUnwind, i32t, 119, {acc, zero8, one8}); + V acc2 = s.m.bin(body, Bin::Xor, wsum, exch); + s.m.terminate(body, Term::br(head)); + s.m.set_phi(i, {{zero, b}, {i2, body}}); + s.m.set_phi(acc, {{sum, b}, {acc2, body}}); + s.flags |= shader::flags::WAVE_OPS; + V two = s.m.i32(2); + V heap_index = s.m.bin(exit, Bin::LShr, acc, two); + V h = s.heap_handle(exit, heap_index, false, true, {11 | 0x1000, 0}); + V f = s.m.cast(exit, Cast::Bitcast, acc, s.t.f32); + V fi = s.m.cast(exit, Cast::FpToUi, f, i32t); + s.op(exit, "rawBufferStore.i32", Attr::NoUnwind, s.t.void_, 140, {h, off, undef, fi, undef, undef, undef, one8, four}); + V uav = s.root_uav_handle(5); + V sel = s.m.select(exit, c, fi, acc); + s.op(exit, "rawBufferStore.i32", Attr::NoUnwind, s.t.void_, 140, {uav, off, undef, sel, undef, undef, undef, one8, four}); + V cbv = s.root_cbv_handle(2); + V crow = s.op(exit, "cbufferLoadLegacy.i32", Attr::ReadOnly, s.t.cbuf_ret, 59, {cbv, zero}); + V cx = s.m.extract(exit, crow, 2); + s.op(exit, "rawBufferStore.i32", Attr::NoUnwind, s.t.void_, 140, {uav, cx, undef, cx, undef, undef, undef, one8, four}); + s.m.terminate(exit, Term::ret()); + return s.finish(); +} + +std::vector<std::uint8_t> ps_basic() { + Shader s(true); + s.inputs = { + el("SV_Position", 0, 3, 9, 0, 0, 4, 4, 0x3), + el("TEXCOORD", 0, 0, 9, 1, 0, 2, 2, 3), + el("TEXCOORD", 1, 0, 5, 3, 0, 1, 1, 0), + el("COLOR", 0, 0, 9, 2, 0, 4, 2, 0), + }; + s.outputs = {el("SV_Target", 0, 16, 9, 0, 0, 4, 0, 0xf)}; + s.samplers = 2; + s.cmp_samplers = 2; + s.user_data = 1; + const std::size_t b = s.entry; + const Ty f32t = s.t.f32; + std::vector<V> uv; + for (std::uint8_t col = 0; col < 2; ++col) { + Ty ty = s.t.i32; + const V args[4] = {s.m.i32(1), s.m.i32(0), s.m.i8(col), s.m.undef(ty)}; + uv.push_back(s.op(b, "loadInput.f32", Attr::ReadNone, f32t, 4, args)); + } + V ud = s.user_data_handle(); + V zero = s.m.i32(0); + V row = s.op(b, "cbufferLoadLegacy.i32", Attr::ReadOnly, s.t.cbuf_ret, 59, {ud, zero}); + V slot = s.m.extract(b, row, 0); + V tex = s.heap_handle(b, slot, false, false, {2 | (9 << 8), 0x0409}); + V smp = s.sampler_handle(b, 0); + V undef = s.m.undef(f32t); + Ty i32t = s.t.i32; + V ui = s.m.undef(i32t); + V r = s.op(b, "sample.f32", Attr::ReadOnly, s.t.res_ret, 60, {tex, smp, uv[0], uv[1], undef, undef, ui, ui, ui, undef}); + V half = s.m.f32(0x3f000000); + for (std::uint32_t col = 0; col < 4; ++col) { + V v = s.m.extract(b, r, col); + V m = s.m.bin(b, Bin::Mul, v, half); + const V args[4] = {s.m.i32(0), s.m.i32(0), s.m.i8(std::uint8_t(col)), m}; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void_, 5, args); + } + s.m.terminate(b, Term::ret()); + return s.finish(); +} + +std::vector<SigElement> rect_outputs() { + return { + el("SV_Position", 0, 3, 9, 0, 0, 4, 0, 0), + el("TEXCOORD", 0, 0, 9, 1, 0, 4, 0, 0), + el("TEXCOORD", 1, 0, 5, 2, 0, 2, 0, 0), + }; +} + +} // namespace + +int main() { + if (dir().empty()) { + std::fprintf(stderr, "ref_test: set X2W_REF_DIR\n"); + return 1; + } + containers(); + same("cs_basic", cs_basic()); + same("ps_basic", ps_basic()); + const SigElement wanted[] = {el("SV_PrimitiveID", 0, 10, 5, 3, 0, 1, 0, 0)}; + same("rect_prim", rect_build(rect_outputs(), wanted)); + same("rect_plain", rect_build(rect_outputs(), {})); + return test_util::finish("ref_test"); +} diff --git a/tests/x2w_shader/emit/ref_validate_test.cpp b/tests/x2w_shader/emit/ref_validate_test.cpp new file mode 100644 index 0000000000..32d5f317f8 --- /dev/null +++ b/tests/x2w_shader/emit/ref_validate_test.cpp @@ -0,0 +1,43 @@ +// The DXIL containers of the reference byte comparison (ref_test: the same bytes as the C++ port +// writes) pass dxc's validator. X2W_REF_DIR: the reference folder. Skipped without dxil.dll. + +#include <cstdio> +#include <cstdlib> +#include <fstream> +#include <iterator> +#include <string> +#include <vector> + +#include "test_util.h" +#include "x2w_shader/emit/validator.h" + +int main() { + const char* dir = std::getenv("X2W_REF_DIR"); + if (!dir) { + std::fprintf(stderr, "X2W_REF_DIR not set\n"); + return 1; + } + std::string why; + auto v = x2w::vs::validator::Validator::load(x2w::vs::validator::Validator::default_path(), &why); + if (!v) { + std::printf("ref_validate_test: no validator (%s); skipped\n", why.c_str()); + return 0; + } + for (const char* name : {"cs_basic", "ps_basic", "rect_prim", "rect_plain"}) { + std::ifstream f(std::string(dir) + "/" + name + ".bin", std::ios::binary); + std::vector<std::uint8_t> bytes((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); + if (bytes.empty()) { + std::fprintf(stderr, "%s: missing\n", name); + ++test_util::failures(); + continue; + } + auto err = v->validate(bytes); + if (err) { + std::fprintf(stderr, "%s: refused: %s\n", name, err->c_str()); + ++test_util::failures(); + } else { + std::printf("%s: valid (%zu bytes)\n", name, bytes.size()); + } + } + return test_util::finish("ref_validate_test"); +} diff --git a/tests/x2w_shader/emit/sampler_test.cpp b/tests/x2w_shader/emit/sampler_test.cpp new file mode 100644 index 0000000000..4e3b42b9c2 --- /dev/null +++ b/tests/x2w_shader/emit/sampler_test.cpp @@ -0,0 +1,87 @@ +// Port of the tests in the upstream Rust module emit/sampler.rs. + +#include "x2w_shader/emit/sampler.h" +#include "test_util.h" + +using x2w::vs::sampler::StaticSampler; +using A3 = std::array<std::uint32_t, 3>; + +namespace { + +void console_compiled_samplers_decode() { + // Words the console compiler wrote for static samplers of known descriptions. + auto point = StaticSampler::from_words({0x3088, 0x00540100, 0x14000080, 0x80000000}); + StaticSampler want; + want.filter = 0; + want.address = {1, 2, 3}; + want.mip_lod_bias = 0.5f; + want.max_anisotropy = 1; + want.comparison = 4; + want.border = 2; + want.min_lod = 1.0f; + want.max_lod = 5.25f; + CHECK(point == want); + auto aniso = StaticSampler::from_words({0x369E, 0x00FFF000, 0x18F03E00, 0x80000000}); + CHECK(aniso.filter == 0x55 && (aniso.address == A3{4, 5, 3}) && aniso.max_anisotropy == 8); + CHECK(aniso.mip_lod_bias == -2.0f && aniso.max_lod == 4095.0f / 256.0f); + auto compare = StaticSampler::from_words({0x3006, 0x00FFF000, 0x14500000, 0x40000000}); + CHECK(compare.filter == 0x14 && (compare.address == A3{4, 1, 1}) && compare.border == 1); + auto minimum = StaticSampler::from_words({0x20003003, 0x00FFF000, 0x18500000, 0x80000000}); + CHECK(minimum.filter == 0x115 && minimum.address[0] == 5); + auto mag_mip = StaticSampler::from_words({0x3002, 0, 0x18100000, 0x80000000}); + CHECK(mag_mip.filter == 0x05 && mag_mip.max_lod == 0.0f); + auto max_aniso = StaticSampler::from_words({0x40003800, 0x00FFF000, 0x18F00F00, 0x80000000}); + CHECK(max_aniso.filter == 0x1D5 && max_aniso.max_anisotropy == 16 && max_aniso.mip_lod_bias == 15.0f); +} + +void anisotropic_samplers_preserve_mip_point_filtering() { + const std::uint32_t cases[][2] = {{0, 0x54}, {1, 0x154}, {2, 0x1D4}}; + for (auto& c : cases) { + std::uint32_t w0 = c[0] << 29; + for (std::uint32_t mip : {0u, 1u}) { + std::uint32_t w2 = (mip << 26) | 0x00F00000; + CHECK(StaticSampler::from_words({w0, 0x00FFF000, w2, 0}).filter == c[1]); + } + std::uint32_t w2 = (2u << 26) | 0x00F00000; + CHECK(StaticSampler::from_words({w0, 0x00FFF000, w2, 0}).filter == (c[1] | 1)); + } + auto mixed = StaticSampler::from_words({0, 0, (1u << 26) | (1u << 22) | (2u << 20), 0}); + CHECK(mixed.filter == 0x54); +} + +void host_filter_falls_back_without_changing_reduction_or_lod() { + const std::uint32_t cases[][2] = {{0x54, 0x55}, {0xD4, 0xD5}, {0x154, 0x155}, {0x1D4, 0x1D5}}; + for (auto& c : cases) { + for (std::uint32_t mip : {0u, 1u}) { + StaticSampler s = StaticSampler::from_words({0, 0x00540100, (mip << 26) | 0x00F00000, 0}); + s.filter = c[0]; + CHECK(s.filter_for_host(false) == c[1]); + CHECK(s.filter_for_host(true) == c[0]); + if (mip == 0) + CHECK(s.min_lod == 0.0f && s.max_lod == 0.0f); + else + CHECK(s.min_lod == 1.0f && s.max_lod == 5.25f); + } + } +} + +void host_filter_keeps_other_filters_unchanged() { + for (std::uint32_t reduction : {0u, 0x80u, 0x100u, 0x180u}) { + for (std::uint32_t base : {0u, 1u, 4u, 5u, 0x10u, 0x11u, 0x14u, 0x15u, 0x55u}) { + StaticSampler s = StaticSampler::from_words({0, 0, 0, 0}); + s.filter = base | reduction; + CHECK(s.filter_for_host(false) == s.filter); + CHECK(s.filter_for_host(true) == s.filter); + } + } +} + +} // namespace + +int main() { + console_compiled_samplers_decode(); + anisotropic_samplers_preserve_mip_point_filtering(); + host_filter_falls_back_without_changing_reduction_or_lod(); + host_filter_keeps_other_filters_unchanged(); + return test_util::finish("sampler_test"); +} diff --git a/tests/x2w_shader/emit/test_util.h b/tests/x2w_shader/emit/test_util.h new file mode 100644 index 0000000000..849b02f2af --- /dev/null +++ b/tests/x2w_shader/emit/test_util.h @@ -0,0 +1,48 @@ +#pragma once + +// Minimal test helpers for the x2w_shader/emit tests (no framework: each test is an executable +// that returns nonzero on failure). + +#include <cstdint> +#include <cstdio> +#include <span> +#include <vector> + +namespace test_util { + +inline int& failures() { + static int n = 0; + return n; +} + +inline void check(bool ok, const char* expr, const char* file, int line) { + if (!ok) { + std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", file, line, expr); + ++failures(); + } +} + +inline int finish(const char* name) { + if (failures()) { + std::fprintf(stderr, "%s: %d failure(s)\n", name, failures()); + return 1; + } + std::printf("%s: ok\n", name); + return 0; +} + +inline std::uint32_t u32le(std::span<const std::uint8_t> b, std::size_t at) { + return std::uint32_t(b[at]) | std::uint32_t(b[at + 1]) << 8 | std::uint32_t(b[at + 2]) << 16 | + std::uint32_t(b[at + 3]) << 24; +} + +// FNV-1a, to pin a written module's exact bytes. +inline std::uint64_t fnv(std::span<const std::uint8_t> bytes) { + std::uint64_t h = 0xcbf29ce484222325ull; + for (std::uint8_t b : bytes) h = (h ^ b) * 0x00000100000001b3ull; + return h; +} + +} // namespace test_util + +#define CHECK(expr) ::test_util::check(static_cast<bool>(expr), #expr, __FILE__, __LINE__) diff --git a/tests/x2w_shader/emit/threading_test.cpp b/tests/x2w_shader/emit/threading_test.cpp new file mode 100644 index 0000000000..e8773ce7fa --- /dev/null +++ b/tests/x2w_shader/emit/threading_test.cpp @@ -0,0 +1,79 @@ +// Port of the tests in the upstream Rust module emit/threading.rs (needs vs-core's ir and vs-front's structure). + +#include <array> +#include <cstdint> +#include <tuple> +#include <vector> + +#include "test_util.h" +#include "x2w_shader/emit/threading.h" +#include "x2w_shader/ir.h" +#include "x2w_shader/structure.h" + +using namespace x2w::vs; +using ir::Exit; +using ir::Program; +using ir::Reg; +using threading::constant_edges; + +namespace { + +// s8 initially holds a descriptor address. One arm overwrites it with a buffer load and sets v1. +// Only that arm can use s8 as the stored value. +constexpr std::array<std::uint32_t, 19> WORDS = { + 0xbe810380, // s1 = 0 (table address high) + 0xf4080200, 0xfa000000, // load SRV into s[8:11] + 0xf4080300, 0xfa000020, // load UAV into s[12:15] + 0x7e020280, // v1 = 0 + 0xbf068002, 0xbf850003, // if s2 == 0, jump to join + 0xf4200204, 0xfa00000c, // s8 = buffer.Load(12) + 0x7e020281, // v1 = 1 + 0x7d840280, 0xbf870002, // join: if v1 == 0, jump to constant + 0x7e060208, 0xbf820001, // v3 = s8, jump to store + 0x7e060293, // constant: v3 = 19 + 0xe0700000, 0x80030300, // store v3 at byte 0 + 0xbf810000, // end +}; + +Program program(const std::array<std::uint32_t, 19>& words) { + std::vector<std::uint8_t> code; + for (std::uint32_t w : words) { + for (int k = 0; k < 4; ++k) code.push_back(static_cast<std::uint8_t>(w >> (8 * k))); + } + return ir::build(code, false, 4); +} + +void only_the_buffer_load_reaches_the_numeric_read() { + Program p = program(WORDS); + const auto st = structure::structure(p); + const auto edges = constant_edges(p, st); + using E = std::tuple<std::size_t, std::size_t, std::size_t>; + CHECK((edges == std::vector<E>{E{0, 2, 4}})); + p = ir::thread_edges(p, edges); + const auto& load = p.blocks.at(1).insts.at(0); + CHECK(p.blocks.at(3).insts.at(0).read(Reg::S(8)) == load.write(Reg::S(8))); + CHECK(p.blocks.at(0).exit == Exit::Branch(6, 1)); + CHECK(p.blocks.at(6).exit == Exit::Jump(4)); + CHECK(p.blocks.at(6).insts.size() == p.blocks.at(2).insts.size()); +} + +void leaves_unknown_flags_and_divergent_forks_alone() { + auto words = WORDS; + words[5] = 0x7e020202; // v1 = s2 + words[10] = 0x7e020203; // v1 = s3 + Program p = program(words); + CHECK(constant_edges(p, structure::structure(p)).empty()); + words = WORDS; + words[6] = 0x7d840080; // compare 0 with lane-dependent v0 + words[7] = 0xbf870003; // branch on VCC + p = program(words); + CHECK(constant_edges(p, structure::structure(p)).empty()); +} + +} // namespace + +int main() { + only_the_buffer_load_reaches_the_numeric_read(); + leaves_unknown_flags_and_divergent_forks_alone(); + return test_util::finish("threading_test"); +} diff --git a/tests/x2w_shader/emit/validator_test.cpp b/tests/x2w_shader/emit/validator_test.cpp new file mode 100644 index 0000000000..f95ce732c3 --- /dev/null +++ b/tests/x2w_shader/emit/validator_test.cpp @@ -0,0 +1,148 @@ +// validator.cpp (port of emit/validator.rs): the validator accepts and signs a container dxc.exe +// compiled at test time, and refuses a corrupted one. Skips (and says so) without dxil.dll or +// dxc.exe. + +#include "x2w_shader/emit/validator.h" + +#include <windows.h> + +#include <algorithm> +#include <cstdio> +#include <cstdlib> +#include <filesystem> +#include <fstream> +#include <iterator> +#include <optional> +#include <string> +#include <vector> + +#include "test_util.h" + +namespace fs = std::filesystem; +using x2w::vs::validator::Validator; + +namespace { + +// Compiles hlsl with dxc.exe (next to dxil.dll, as diff_tests.rs finds it); nullopt when it +// fails. +std::optional<std::vector<std::uint8_t>> dxc(const fs::path& dxc_exe, const char* hlsl, const char* profile) { + const fs::path dir = fs::temp_directory_path() / ("x2w_vs_validator_test_" + std::to_string(GetCurrentProcessId())); + fs::create_directories(dir); + const fs::path src = dir / "shader.hlsl"; + const fs::path out = dir / "shader.dxil"; + std::ofstream(src, std::ios::binary) << hlsl; + // The whole command quoted once more: cmd.exe strips the outer pair. + const std::string cmd = "\"\"" + dxc_exe.string() + "\" -nologo -T " + profile + " -E main -Fo \"" + + out.string() + "\" \"" + src.string() + "\"\""; + const int rc = std::system(cmd.c_str()); + std::ifstream in(out, std::ios::binary); + std::vector<std::uint8_t> bytes((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); + in.close(); + std::error_code ec; + fs::remove_all(dir, ec); + if (rc != 0 || bytes.empty()) return std::nullopt; + return bytes; +} + +// The offset of the data of the container's first part with this tag, or 0. +std::size_t part_data(const std::vector<std::uint8_t>& c, const char (&tag)[5]) { + const std::uint32_t count = test_util::u32le(c, 28); + for (std::uint32_t i = 0; i < count; ++i) { + const std::uint32_t at = test_util::u32le(c, 32 + 4 * i); + if (std::equal(tag, tag + 4, c.begin() + at)) return at + 8; + } + return 0; +} + +const char* CS = R"( +RWByteAddressBuffer o : register(u0); +[numthreads(4, 1, 1)] +void main(uint i : SV_DispatchThreadID) { o.Store(i * 4, i * 3 + 1); } +)"; + +} // namespace + +int main() { + const std::optional<fs::path> path = Validator::default_path(); + if (!path) { + std::printf("validator_test: skipped (no dxil.dll)\n"); + return 0; + } + std::printf("validator_test: dxil.dll at %s\n", path->string().c_str()); + + // A missing DLL is an error, not a crash. + { + std::string error; + auto none = Validator::load(fs::path("C:/no/such/dir/dxil.dll"), &error); + CHECK(!none); + CHECK(error.find("cannot load") == 0); + } + + std::string error; + std::optional<Validator> v = Validator::load(path, &error); + CHECK(v.has_value()); + if (!v) { + std::fprintf(stderr, "load: %s\n", error.c_str()); + return test_util::finish("validator_test"); + } + + fs::path dxc_exe = *path; + dxc_exe.replace_filename("dxc.exe"); + std::optional<std::vector<std::uint8_t>> compiled = dxc(dxc_exe, CS, "cs_6_6"); + if (!compiled) { + std::printf("validator_test: dxc.exe unavailable, container checks skipped\n"); + return test_util::finish("validator_test"); + } + CHECK(compiled->size() > 32 && std::equal(compiled->begin(), compiled->begin() + 4, "DXBC")); + const std::vector<std::uint8_t> original_digest(compiled->begin() + 4, compiled->begin() + 20); + CHECK(std::any_of(original_digest.begin(), original_digest.end(), [](std::uint8_t b) { return b != 0; })); + + // Accepted as dxc wrote it. + { + std::vector<std::uint8_t> c = *compiled; + auto r = v->validate(c); + CHECK(!r); + if (r) std::fprintf(stderr, "rejected: %s\n", r->c_str()); + CHECK(c == *compiled); + } + + // With the digest cleared, validation signs it in place: dxc's digest comes back. + { + std::vector<std::uint8_t> c = *compiled; + std::fill(c.begin() + 4, c.begin() + 20, std::uint8_t{0}); + auto r = v->validate(c); + CHECK(!r); + if (r) std::fprintf(stderr, "rejected: %s\n", r->c_str()); + CHECK(std::vector<std::uint8_t>(c.begin() + 4, c.begin() + 20) == original_digest); + CHECK(c == *compiled); + } + + // A broken bitcode magic in the DXIL part is refused, with the validator's text. + { + std::vector<std::uint8_t> c = *compiled; + const std::size_t dxil = part_data(c, "DXIL"); + CHECK(dxil != 0); + // Program header: version, size in dwords, "DXIL", DXIL version, bitcode offset, size. + const std::size_t bitcode = dxil + 8 + test_util::u32le(c, dxil + 16); + CHECK(c[bitcode] == 'B' && c[bitcode + 1] == 'C'); + c[bitcode] = 'X'; + c[bitcode + 1] = 'Y'; + auto r = v->validate(c); + CHECK(r.has_value()); + if (r) std::printf("validator_test: corrupted bitcode refused: %.120s\n", r->c_str()); + } + + // A PSV0 that disagrees with the module is refused: the validator rebuilds the part from the + // module and compares. (PSV0: the runtime-info size, then the info; byte 4 is in the info.) + { + std::vector<std::uint8_t> c = *compiled; + const std::size_t psv = part_data(c, "PSV0"); + CHECK(psv != 0); + c[psv + 4] ^= 0x40; + auto r = v->validate(c); + CHECK(r.has_value()); + if (r) std::printf("validator_test: corrupted PSV0 refused: %.120s\n", r->c_str()); + } + + return test_util::finish("validator_test"); +} diff --git a/tests/x2w_shader/emit/wave_test.cpp b/tests/x2w_shader/emit/wave_test.cpp new file mode 100644 index 0000000000..1f6fd99685 --- /dev/null +++ b/tests/x2w_shader/emit/wave_test.cpp @@ -0,0 +1,399 @@ +// Port of the tests in the upstream Rust module emit/wave.rs. +// +// The tests that build programs need vs-core's ir::build (X2W_VS_HAVE_IR, set by wave.cmake when +// the ir implementation is in the tree); the others run without it. + +#include <algorithm> +#include <array> +#include <cstdint> +#include <optional> +#include <vector> + +#include "test_util.h" +#include "x2w_shader/emit/bitcode.h" +#include "x2w_shader/emit/wave.h" + +using namespace x2w::vs; +using wave::Op; +using wave::Shape; +using wave::Sym; +using wave::detail::dpp_lane; +using wave::detail::per_lane; + +namespace { + +void dpp_lanes_follow_the_isa() { + // row_shr:1 with bound_ctrl: lane 16 reads 0, lane 17 lane 16. + const gfx10::Dpp shr = gfx10::DppRow{0x111, 0xF, 0xF, true, false}; + CHECK((dpp_lane(shr, 16) == std::tuple{16u, true, true})); + CHECK((dpp_lane(shr, 17) == std::tuple{16u, false, true})); + // row_mirror: lane 3 reads lane 12. + const gfx10::Dpp mirror = gfx10::DppRow{0x140, 0xF, 0xF, true, false}; + CHECK((dpp_lane(mirror, 3) == std::tuple{12u, false, true})); + // dpp8 [1,0,3,2,5,4,7,6] swaps neighbours. + const gfx10::Dpp swap = gfx10::DppLanes{1 | 3 << 6 | 2 << 9 | 5 << 12 | 4 << 15 | 7 << 18 | 6 << 21, false}; + CHECK((dpp_lane(swap, 8) == std::tuple{9u, false, true})); +} + +void prefixes_are_recognised() { + const ir::Value x{1}, m{2}; + auto red = [&](std::uint64_t lanes) { return Sym::red(Op::AddU, x, m, 0, lanes); }; + std::vector<Sym> inclusive; + for (std::uint32_t l = 0; l < 64; ++l) inclusive.push_back(red(~std::uint64_t{0} >> (63 - l))); + CHECK(per_lane(inclusive, ~std::uint64_t{0}) == Shape::prefix(Op::AddU, x, m, 0, true)); + std::vector<Sym> exclusive; + for (std::uint32_t l = 0; l < 64; ++l) exclusive.push_back(red((std::uint64_t{1} << l) - 1)); + exclusive[0] = Sym::konst(0); + CHECK(per_lane(exclusive, ~std::uint64_t{0}) == Shape::prefix(Op::AddU, x, m, 0, false)); + CHECK(per_lane(std::vector<Sym>(64, red(~std::uint64_t{0})), ~std::uint64_t{0}) == + Shape::active(Op::AddU, x, m, 0)); +} + +void buddies_are_the_two_halves_of_an_aligned_run() { + using wave::buddies; + CHECK(buddies(0b01, 0b10)); + CHECK(buddies(0b1100, 0b0011)); + CHECK(buddies(0xF0, 0x0F)); + CHECK(buddies(std::uint64_t{0xFFFF'FFFFu}, std::uint64_t{0xFFFF'FFFFu} << 32)); + CHECK(!buddies(0b010, 0b100)); // lanes 1 and 2: not one pair + CHECK(!buddies(0b0011, 0b110000)); // pairs 0 and 2 + CHECK(!buddies(0b0101, 0b1010)); // not runs + CHECK(!buddies(0b01, 0b1100)); // unequal + CHECK(!buddies(0b11, 0b11)); +} + +void per_lane_prefix_soundness() { + const ir::Value v0{1}, v_other{2}, m0{3}, m_other{4}; + auto red = [](std::optional<Op> op, ir::Value src, ir::Value mask, std::uint32_t ident, std::uint64_t lanes) { + return Sym::red(op, src, mask, ident, lanes); + }; + for (const auto& [wave, all] : {std::pair<std::size_t, std::uint64_t>{32, 0xFFFF'FFFFu}, + std::pair<std::size_t, std::uint64_t>{64, ~std::uint64_t{0}}}) { + auto below_mask = [](std::size_t l) { return l == 0 ? std::uint64_t{0} : (std::uint64_t{1} << l) - 1; }; + + std::vector<Sym> valid_inc; + for (std::size_t l = 0; l < wave; ++l) + valid_inc.push_back(red(Op::AddU, v0, m0, 0, below_mask(l) | (std::uint64_t{1} << l))); + valid_inc[0] = red(std::nullopt, v0, m0, 0, 1); + CHECK(per_lane(valid_inc, all) == Shape::prefix(Op::AddU, v0, m0, 0, true)); + + std::vector<Sym> valid_exc; + for (std::size_t l = 0; l < wave; ++l) valid_exc.push_back(red(Op::AddU, v0, m0, 0, below_mask(l))); + valid_exc[0] = Sym::konst(0); + valid_exc[1] = red(std::nullopt, v0, m0, 0, 1); + CHECK(per_lane(valid_exc, all) == Shape::prefix(Op::AddU, v0, m0, 0, false)); + + auto mixed_other_src = valid_exc; + mixed_other_src[0] = red(std::nullopt, v_other, m0, 0, 1); + CHECK(per_lane(mixed_other_src, all) == std::nullopt); + + auto mixed_same_src = valid_exc; + mixed_same_src[0] = red(std::nullopt, v0, m0, 0, 1); + CHECK(per_lane(mixed_same_src, all) == std::nullopt); + + auto exc_bad_lane1_src = valid_exc; + exc_bad_lane1_src[1] = red(std::nullopt, v_other, m0, 0, 1); + CHECK(per_lane(exc_bad_lane1_src, all) == std::nullopt); + + auto exc_bad_lane1_set = valid_exc; + exc_bad_lane1_set[1] = red(std::nullopt, v0, m0, 0, 0b11); + CHECK(per_lane(exc_bad_lane1_set, all) == std::nullopt); + + for (const Sym& bad0 : {red(std::nullopt, v0, m0, 1, 1), red(std::nullopt, v_other, m0, 0, 1), + red(std::nullopt, v0, m_other, 0, 1), red(std::nullopt, v0, m0, 0, 0), Sym::konst(0)}) { + auto bad_inc = valid_inc; + bad_inc[0] = bad0; + CHECK(per_lane(bad_inc, all) == std::nullopt); + } + + std::vector<Sym> bad_ident; + for (std::size_t l = 0; l < wave; ++l) + bad_ident.push_back(red(Op::AddU, v0, m0, 1, below_mask(l) | (std::uint64_t{1} << l))); + bad_ident[0] = red(std::nullopt, v0, m0, 1, 1); + CHECK(per_lane(bad_ident, all) == std::nullopt); + } +} + +#ifdef X2W_VS_HAVE_IR + +using ir::EXEC; +using ir::Program; +using ir::Reg; + +constexpr std::uint32_t S_ENDPGM = 0xBF81'0000; + +constexpr std::uint32_t sop1(std::uint8_t sdst, std::uint8_t op, std::uint8_t ssrc0) { + return 0xBE80'0000u | std::uint32_t(sdst) << 16 | std::uint32_t(op) << 8 | std::uint32_t(ssrc0); +} + +constexpr std::uint32_t vop1(std::uint8_t vdst, std::uint8_t op, std::uint16_t src0) { + return (0x3Fu << 25) | std::uint32_t(vdst) << 17 | std::uint32_t(op) << 9 | (std::uint32_t(src0) & 0x1FF); +} + +constexpr std::uint32_t vop2(std::uint8_t vdst, std::uint8_t op, std::uint16_t src0, std::uint8_t vsrc1) { + return std::uint32_t(op) << 25 | std::uint32_t(vdst) << 17 | std::uint32_t(vsrc1) << 9 | (std::uint32_t(src0) & 0x1FF); +} + +constexpr std::uint32_t dpp16(std::uint8_t vsrc0, std::uint16_t ctrl, std::uint8_t row_mask, std::uint8_t bank_mask, + bool bound_ctrl) { + return std::uint32_t(row_mask) << 28 | std::uint32_t(bank_mask) << 24 | std::uint32_t(bound_ctrl) << 19 | + std::uint32_t(ctrl) << 8 | std::uint32_t(vsrc0); +} + +constexpr std::array<std::uint32_t, 2> vop3(std::uint8_t vdst, std::uint16_t op, std::uint16_t src0, std::uint16_t src1, + std::uint16_t src2) { + return {0xD400'0000u | std::uint32_t(op) << 16 | std::uint32_t(vdst), + (std::uint32_t(src0) & 0x1FF) | ((std::uint32_t(src1) & 0x1FF) << 9) | ((std::uint32_t(src2) & 0x1FF) << 18)}; +} + +Program build(const std::vector<std::uint32_t>& words, bool wave64) { + std::vector<std::uint8_t> code; + auto put = [&](std::uint32_t w) { + for (int k = 0; k < 4; ++k) code.push_back(static_cast<std::uint8_t>(w >> (8 * k))); + }; + for (std::uint32_t w : words) put(w); + put(S_ENDPGM); + return ir::build(code, wave64, 256); +} + +ir::Value input(const Program& p, Reg r) { + for (const auto& [reg, v] : p.inputs) { + if (reg == r) return v; + } + x2w::vs::bitcode::bug("no such input"); +} + +void constant_decodes_width_and_inline_kinds() { + const std::uint8_t b64 = 0x04; + const std::uint8_t b32 = 0x03; + auto check = [](const std::vector<std::uint32_t>& words, bool wave64) { + const Program p = build(words, wave64); + return wave::detail::constant(p.blocks[0].insts[0]); + }; + using O = std::optional<std::uint64_t>; + CHECK(check({sop1(EXEC, b64, 194)}, true) == O{0xFFFF'FFFF'FFFF'FFFEull}); + CHECK(check({sop1(EXEC, b64, 196)}, true) == O{0xFFFF'FFFF'FFFF'FFFCull}); + CHECK(check({sop1(EXEC, b64, 208)}, true) == O{0xFFFF'FFFF'FFFF'FFF0ull}); + CHECK(check({sop1(EXEC, b64, 193)}, true) == O{~std::uint64_t{0}}); + CHECK(check({sop1(EXEC, b64, gfx10::NULL_CODE)}, true) == O{0}); + CHECK(check({sop1(EXEC, b64, 243)}, true) == std::nullopt); + CHECK(check({sop1(EXEC, b64, 255), 0x1234'5678}, true) == O{0x1234'5678}); + + CHECK(check({sop1(EXEC, b32, 194)}, false) == O{0xFFFF'FFFE}); + CHECK(check({sop1(EXEC, b32, 243)}, false) == O{0xBF80'0000}); + CHECK(check({sop1(EXEC, b32, gfx10::NULL_CODE)}, false) == O{0}); + CHECK(check({sop1(EXEC, b32, 255), 0x1234'5678}, false) == O{0x1234'5678}); + CHECK(check({sop1(EXEC, b32, 0)}, false) == std::nullopt); +} + +void exec_minus_two_masks_lane_zero_and_enforces_dpp_guard() { + for (bool wave64 : {false, true}) { + std::vector<std::uint32_t> w; + const std::uint8_t save_op = wave64 ? 0x25 : 0x3D; + const std::uint8_t mov_exec = wave64 ? 0x04 : 0x03; + auto push_exec = [&](std::uint8_t k) { w.push_back(sop1(EXEC, mov_exec, k)); }; + auto push_exec_lit = [&](std::uint32_t lit) { + w.push_back(sop1(EXEC, mov_exec, 255)); + w.push_back(lit); + }; + auto extend = [&](std::array<std::uint32_t, 2> a) { w.insert(w.end(), a.begin(), a.end()); }; + + w.push_back(sop1(0, save_op, 193)); + extend(vop3(1, 0x101, 128, 256, 0)); + for (int shift : {1, 2, 4, 8}) { + w.push_back(vop2(1, 0x25, 0xFA, 1)); + w.push_back(dpp16(1, static_cast<std::uint16_t>(0x110 + shift), 0xF, 0xF, false)); + } + extend(vop3(2, 0x360, 257, 128 + 15, 0)); + push_exec_lit(0xFFFF'0000); + w.push_back(vop2(1, 0x25, 2, 1)); + + if (wave64) { + extend(vop3(2, 0x360, 257, 128 + 31, 0)); + w.push_back(sop1(EXEC, 0x03, 128)); + w.push_back(sop1(EXEC + 1, 0x03, 255)); + w.push_back(0x0000'FFFF); + w.push_back(vop2(1, 0x25, 2, 1)); + + extend(vop3(2, 0x360, 257, 128 + 47, 0)); + w.push_back(sop1(EXEC, 0x03, 128)); + w.push_back(sop1(EXEC + 1, 0x03, 255)); + w.push_back(0xFFFF'0000); + w.push_back(vop2(1, 0x25, 2, 1)); + } + + push_exec(193); + w.push_back(vop1(3, 0x01, 257)); + w.push_back(vop1(3, 0x01, 0xFA)); + w.push_back(dpp16(1, 0x111, 0xF, 0xF, false)); + + extend(vop3(2, 0x360, 257, 128 + 15, 0)); + push_exec_lit(0x0001'0000); + w.push_back(vop1(3, 0x01, 2)); + + if (wave64) { + extend(vop3(2, 0x360, 257, 128 + 31, 0)); + w.push_back(sop1(EXEC, 0x03, 128)); + w.push_back(sop1(EXEC + 1, 0x03, 129)); + w.push_back(vop1(3, 0x01, 2)); + + extend(vop3(2, 0x360, 257, 128 + 47, 0)); + w.push_back(sop1(EXEC, 0x03, 128)); + w.push_back(sop1(EXEC + 1, 0x03, 255)); + w.push_back(0x0001'0000); + w.push_back(vop1(3, 0x01, 2)); + } + + push_exec(193); + w.push_back(vop1(2, 0x01, 128)); + w.push_back(vop1(5, 0x01, 135)); + push_exec(194); + w.push_back(vop1(2, 0x01, 259)); + w.push_back(vop1(4, 0x01, 0xFA)); + w.push_back(dpp16(5, 0xE4, 0xF, 0xF, false)); + w.push_back(sop1(EXEC, mov_exec, 0)); + + const Program p = build(w, wave64); + const auto& insts = p.blocks[0].insts; + const auto saved = *insts[0].write(Reg::S(0)); + const auto v0_in = input(p, Reg::V(0)); + const auto v2_val = *insts[insts.size() - 4].write(Reg::V(2)); + const auto v4_val = *insts[insts.size() - 3].write(Reg::V(4)); + const auto secs = wave::sections(p, 0); + const auto& sec = secs.at(0); + const auto s2 = sec.shapes.find(v2_val); + CHECK(s2 != sec.shapes.end() && s2->second == Shape::prefix(Op::AddU, v0_in, saved, 0, false)); + CHECK(!sec.shapes.contains(v4_val)); + } +} + +// A wave OR whose last step stays in the section's VGPR: the lower lanes add the first half's to +// themselves, so only the upper ones hold the whole, and the last lane is read after the section +// (an upscaler's programs). +void one_lane_of_what_a_section_leaves_is_read_after_it() { + auto words = [](std::uint32_t lane) { + std::vector<std::uint32_t> w(wave::WAVE_OR_V7_TO_S7.begin(), wave::WAVE_OR_V7_TO_S7.begin() + 14); + w.insert(w.end(), { + 0xD760'0007, + 0x0001'0101, // v_readlane_b32 s7, v1, 0 + 0x3802'0207, // v_or_b32 v1, s7, v1 + 0xBEFE'0404, // s_mov_b64 exec, s[4:5] + 0xD760'0006, + 0x0001'0101 | lane << 9, // v_readlane_b32 s6, v1, lane + S_ENDPGM, + }); + return w; + }; + auto read = [&](std::uint32_t lane) { + const Program p = build(words(lane), true); + const auto& insts = p.blocks[0].insts; + const auto saved = *insts[0].write(Reg::S(4)); + const auto v7 = input(p, Reg::V(7)); + const auto got = *insts[insts.size() - 2].write(Reg::S(6)); + const auto secs = wave::sections(p, 0); + const auto& sec = secs.at(0); + std::optional<Shape> found; + if (const auto it = sec.reads.find(got); it != sec.reads.end()) found = it->second; + return std::pair{found, Shape::active(Op::Or, v7, saved, 0)}; + }; + const auto [found, whole] = read(63); + CHECK(found == whole); + // Lane 0 has the first half's alone: still a lane read. + CHECK(read(0).first == std::nullopt); +} + +// A 16-bit floating-point wave sum uses the tree the lowering +// reproduces. A tree in another order is not followed. +void a_sum_of_halves_over_the_wave_is_followed_in_the_order_of_its_tree() { + using W2 = std::array<std::uint32_t, 2>; + auto words = [](W2 first, W2 second) { + return std::vector<std::uint32_t>{ + 0xBE84'25C1, // s_or_saveexec_b64 s[4:5], -1 + 0xD501'0001, + 0x0012'0E80, // v_cndmask_b32 v1, 0, v7, s[4:5] + first[0], + first[1], + second[0], + second[1], + 0x6402'02E9, + 0x0009'2401, // v_add_f16 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0] + 0x6402'02FA, + 0xFF09'4001, // v_add_f16 v1, v1, v1 row_mirror bound_ctrl:1 + 0xD778'0002, + 0x0201'0101, // v_permlanex16_b32 v2, v1, 0, 0 + 0x6402'0302, // v_add_f16 v1, v2, v1 + 0xD760'0007, + 0x0001'4101, // v_readlane_b32 s7, v1, 32 + 0x6402'0207, // v_add_f16 v1, s7, v1 + 0xD760'0007, + 0x0001'0101, // v_readlane_b32 s7, v1, 0 + 0xBEFE'0404, // s_mov_b64 exec, s[4:5] + }; + }; + const W2 pairs = {0x6402'02E9, 0xDE54'C101}; // v_add_f16 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6] + const W2 quads = {0x6402'02E9, 0x9360'1201}; // v_add_f16 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4] + auto shape = [](const std::vector<std::uint32_t>& w) { + const Program p = build(w, true); + const auto& insts = p.blocks[0].insts; + const auto saved = *insts[0].write(Reg::S(4)); + const auto v7 = input(p, Reg::V(7)); + // ..., v_readlane_b32 s7, v1, 0; s_mov_b64 exec, s[4:5]; s_endpgm + const auto total = *insts[insts.size() - 3].write(Reg::S(7)); + const auto secs = wave::sections(p, 0); + const auto& sec = secs.at(0); + std::optional<Shape> found; + if (const auto it = sec.shapes.find(total); it != sec.shapes.end()) found = it->second; + return std::pair{found, Shape::active(Op::AddH, v7, saved, 0)}; + }; + const auto [found, want] = shape(words(pairs, quads)); + CHECK(found == want); + // lanes two apart first, neighbours second: every lane counted once, but + // (x0 + x2) + (x1 + x3) rounds differently from (x0 + x1) + (x2 + x3) + CHECK(shape(words(quads, pairs)).first == std::nullopt); +} + +void wave32_mov_b64_all_lanes_keeps_exec_masked_for_dpp() { + const std::vector<std::uint32_t> w = { + sop1(0, 0x3D, 193), + vop1(1, 0x01, 135), + sop1(EXEC, 0x04, 193), + vop1(2, 0x01, 0xFA), + dpp16(1, 0xE4, 0xF, 0xF, false), + sop1(EXEC + 1, 0x03, 193), + vop1(3, 0x01, 0xFA), + dpp16(1, 0xE4, 0xF, 0xF, false), + sop1(EXEC, 0x03, 0), + }; + const Program p = build(w, false); + const auto& insts = p.blocks[0].insts; + const auto v2_val = *insts[3].write(Reg::V(2)); + const auto v3_val = *insts[5].write(Reg::V(3)); + const auto secs = wave::sections(p, 0); + const auto& sec = secs.at(0); + const auto a = sec.shapes.find(v2_val); + const auto b = sec.shapes.find(v3_val); + CHECK(a != sec.shapes.end() && a->second == Shape::konst(7)); + CHECK(b != sec.shapes.end() && b->second == Shape::konst(7)); +} + +#endif // X2W_VS_HAVE_IR + +} // namespace + +int main() { + dpp_lanes_follow_the_isa(); + prefixes_are_recognised(); + buddies_are_the_two_halves_of_an_aligned_run(); + per_lane_prefix_soundness(); +#ifdef X2W_VS_HAVE_IR + constant_decodes_width_and_inline_kinds(); + exec_minus_two_masks_lane_zero_and_enforces_dpp_guard(); + one_lane_of_what_a_section_leaves_is_read_after_it(); + a_sum_of_halves_over_the_wave_is_followed_in_the_order_of_its_tree(); + wave32_mov_b64_all_lanes_keeps_exec_masked_for_dpp(); + std::printf("wave_test: 9 of 9 tests ran\n"); +#else + std::printf("wave_test: 4 of 9 tests ran (no ir::build: X2W_VS_HAVE_IR unset)\n"); +#endif + return test_util::finish("wave_test"); +} diff --git a/tests/x2w_shader/resource_fixtures.h b/tests/x2w_shader/resource_fixtures.h new file mode 100644 index 0000000000..a449b83b13 --- /dev/null +++ b/tests/x2w_shader/resource_fixtures.h @@ -0,0 +1,570 @@ +// Fixtures of the upstream Rust shader tests in src/resource.rs that other test suites +// reuse (`pub(crate)` there): waterfall-loop programs, wave32 and wave64, as GFX10 words. +#pragma once + +#include <algorithm> +#include <cstddef> +#include <cstdint> +#include <stdexcept> +#include <vector> + +namespace x2w::vs::resource::fixtures { + +namespace fixtures_detail { +// The index of `word` in `words` (Rust: tests::word_at; panics there when absent). +inline std::size_t word_at(const std::vector<std::uint32_t>& words, std::uint32_t word) +{ + const auto it = std::find(words.begin(), words.end(), word); + if (it == words.end()) throw std::logic_error("word_at: word not in the program"); + return static_cast<std::size_t>(it - words.begin()); +} +} // namespace fixtures_detail + +// A waterfall loop over an image descriptor each lane loads from the +// table at s0 (wave32, assembled with llvm-mc for gfx1030): lane i +// reads entry i with two `global_load_dwordx4`, the loop reads the +// first active lane's descriptor into s[12:19], samples with the lanes +// whose descriptor it is, and repeats for the others. The sampler comes +// from the table at s1; the result goes to LDS so the sample is needed. +inline const std::vector<std::uint32_t> WATERFALL_FETCHED_WAVE32 = { + 0xBE84'0300, // s_mov_b32 s4, s0 + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xBE86'0301, // s_mov_b32 s6, s1 + 0xBE87'0380, // s_mov_b32 s7, 0 + 0x3402'0085, // v_lshlrev_b32 v1, 5, v0 + 0xDC38'8000, + 0x0404'0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38'8010, + 0x0804'0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xF408'0203, + 0xFA00'0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04'0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06'0302, // v_mov_b32 v3, v2 + 0xBF8C'0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94'037E, // s_mov_b32 s20, exec_lo + 0x7E18'0504, // 0x3c: v_readfirstlane_b32 s12, v4 + 0x7E1A'0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C'0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E'0507, // v_readfirstlane_b32 s15, v7 + 0x7E20'0508, // v_readfirstlane_b32 s16, v8 + 0x7E22'0509, // v_readfirstlane_b32 s17, v9 + 0x7E24'050A, // v_readfirstlane_b32 s18, v10 + 0x7E26'050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2'0015, + 0x0002'080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2'0016, + 0x0002'0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xD4E2'0016, + 0x0002'1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xD4E2'0016, + 0x0002'1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xBE95'3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80'0000, // s_nop 0 + 0xF09C'0F08, + 0x0043'0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C'3F70, // s_waitcnt vmcnt(0) + 0x897E'157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89'FFE6, // s_cbranch_execnz -> 0x3c + 0xBEFE'0314, // s_mov_b32 exec_lo, s20 + 0xD834'0000, + 0x0000'0C00, // ds_write_b32 v0, v12 + 0xBF81'0000, // s_endpgm +}; + +// WATERFALL_FETCHED_WAVE32 in wave64: 64-bit lane masks. +inline const std::vector<std::uint32_t> WATERFALL_FETCHED_WAVE64 = { + 0xBE84'0300, // s_mov_b32 s4, s0 + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xBE86'0301, // s_mov_b32 s6, s1 + 0xBE87'0380, // s_mov_b32 s7, 0 + 0x3402'0085, // v_lshlrev_b32 v1, 5, v0 + 0xDC38'8000, + 0x0404'0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38'8010, + 0x0804'0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xF408'0203, + 0xFA00'0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04'0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06'0302, // v_mov_b32 v3, v2 + 0xBF8C'0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94'047E, // s_mov_b64 s[20:21], exec + 0x7E18'0504, // 0x3c: v_readfirstlane_b32 s12, v4 + 0x7E1A'0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C'0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E'0507, // v_readfirstlane_b32 s15, v7 + 0x7E20'0508, // v_readfirstlane_b32 s16, v8 + 0x7E22'0509, // v_readfirstlane_b32 s17, v9 + 0x7E24'050A, // v_readfirstlane_b32 s18, v10 + 0x7E26'050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2'0016, + 0x0002'080C, // v_cmp_eq_u64_e64 s[22:23], s[12:13], v[4:5] + 0xD4E2'0018, + 0x0002'0C0E, // v_cmp_eq_u64_e64 s[24:25], s[14:15], v[6:7] + 0x8796'1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xD4E2'0018, + 0x0002'1010, // v_cmp_eq_u64_e64 s[24:25], s[16:17], v[8:9] + 0x8796'1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xD4E2'0018, + 0x0002'1412, // v_cmp_eq_u64_e64 s[24:25], s[18:19], v[10:11] + 0x8796'1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xBE96'2416, // s_and_saveexec_b64 s[22:23], s[22:23] + 0xBF80'0000, // s_nop 0 + 0xF09C'0F08, + 0x0043'0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C'3F70, // s_waitcnt vmcnt(0) + 0x89FE'167E, // s_xor_b64 exec, exec, s[22:23] + 0xBF89'FFE6, // s_cbranch_execnz -> 0x3c + 0xBEFE'0414, // s_mov_b64 exec, s[20:21] + 0xD834'0000, + 0x0000'0C00, // ds_write_b32 v0, v12 + 0xBF81'0000, // s_endpgm +}; + +// The same waterfall over one of two image descriptors loaded from the +// table at s0, picked per lane by `v_cndmask_b32` (lanes below 16 take +// the first). +inline const std::vector<std::uint32_t> WATERFALL_PICKED_WAVE32 = { + 0xBE84'0300, // s_mov_b32 s4, s0 + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xBE86'0301, // s_mov_b32 s6, s1 + 0xBE87'0380, // s_mov_b32 s7, 0 + 0xF40C'0602, + 0xFA00'0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C'0802, + 0xFA00'0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408'0203, + 0xFA00'0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04'0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06'0302, // v_mov_b32 v3, v2 + 0x7D88'0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C'C07F, // s_waitcnt lgkmcnt(0) + 0x7E08'0218, // v_mov_b32 v4, s24 + 0x0208'0820, // v_cndmask_b32 v4, s32, v4, vcc_lo + 0x7E0A'0219, // v_mov_b32 v5, s25 + 0x020A'0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo + 0x7E0C'021A, // v_mov_b32 v6, s26 + 0x020C'0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo + 0x7E0E'021B, // v_mov_b32 v7, s27 + 0x020E'0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo + 0x7E10'021C, // v_mov_b32 v8, s28 + 0x0210'1024, // v_cndmask_b32 v8, s36, v8, vcc_lo + 0x7E12'021D, // v_mov_b32 v9, s29 + 0x0212'1225, // v_cndmask_b32 v9, s37, v9, vcc_lo + 0x7E14'021E, // v_mov_b32 v10, s30 + 0x0214'1426, // v_cndmask_b32 v10, s38, v10, vcc_lo + 0x7E16'021F, // v_mov_b32 v11, s31 + 0x0216'1627, // v_cndmask_b32 v11, s39, v11, vcc_lo + 0xBE94'037E, // s_mov_b32 s20, exec_lo + 0x7E18'0504, // 0x7c: v_readfirstlane_b32 s12, v4 + 0x7E1A'0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C'0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E'0507, // v_readfirstlane_b32 s15, v7 + 0x7E20'0508, // v_readfirstlane_b32 s16, v8 + 0x7E22'0509, // v_readfirstlane_b32 s17, v9 + 0x7E24'050A, // v_readfirstlane_b32 s18, v10 + 0x7E26'050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2'0015, + 0x0002'080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2'0016, + 0x0002'0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xD4E2'0016, + 0x0002'1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xD4E2'0016, + 0x0002'1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xBE95'3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80'0000, // s_nop 0 + 0xF09C'0F08, + 0x0043'0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C'3F70, // s_waitcnt vmcnt(0) + 0x897E'157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89'FFE6, // s_cbranch_execnz -> 0x7c + 0xBEFE'0314, // s_mov_b32 exec_lo, s20 + 0xD834'0000, + 0x0000'0C00, // ds_write_b32 v0, v12 + 0xBF81'0000, // s_endpgm +}; + +// The waterfall loop of WATERFALL_PICKED_WAVE32 over one of two +// image descriptors loaded from the table at s0, chosen by control flow +// as the compiler lowers an if/else on a per-lane condition: lanes below +// 16 move the first into v[4:11], the others the second, each arm +// skipped when no lane takes it. The sample goes to the buffer at dword +// 16 of the table, at lane * 4. +inline const std::vector<std::uint32_t> WATERFALL_JOINED_WAVE32 = { + 0xBE84'0300, // s_mov_b32 s4, s0 + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xBE86'0301, // s_mov_b32 s6, s1 + 0xBE87'0380, // s_mov_b32 s7, 0 + 0xF40C'0602, + 0xFA00'0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C'0802, + 0xFA00'0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408'0203, + 0xFA00'0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408'0A02, + 0xFA00'0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04'0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06'0302, // v_mov_b32 v3, v2 + 0x3420'0082, // v_lshlrev_b32 v16, 2, v0 + 0x7D88'0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C'C07F, // s_waitcnt lgkmcnt(0) + 0xBE94'3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914'147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88'0008, // s_cbranch_execz -> 0x70 + 0x7E08'0218, // v_mov_b32 v4, s24 + 0x7E0A'0219, // v_mov_b32 v5, s25 + 0x7E0C'021A, // v_mov_b32 v6, s26 + 0x7E0E'021B, // v_mov_b32 v7, s27 + 0x7E10'021C, // v_mov_b32 v8, s28 + 0x7E12'021D, // v_mov_b32 v9, s29 + 0x7E14'021E, // v_mov_b32 v10, s30 + 0x7E16'021F, // v_mov_b32 v11, s31 + 0xBE94'3D14, // 0x70: s_or_saveexec_b32 s20, s20 + 0x897E'147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88'0008, // s_cbranch_execz -> 0x9c + 0x7E08'0220, // v_mov_b32 v4, s32 + 0x7E0A'0221, // v_mov_b32 v5, s33 + 0x7E0C'0222, // v_mov_b32 v6, s34 + 0x7E0E'0223, // v_mov_b32 v7, s35 + 0x7E10'0224, // v_mov_b32 v8, s36 + 0x7E12'0225, // v_mov_b32 v9, s37 + 0x7E14'0226, // v_mov_b32 v10, s38 + 0x7E16'0227, // v_mov_b32 v11, s39 + 0x887E'147E, // 0x9c: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97'037E, // s_mov_b32 s23, exec_lo + 0x7E18'0504, // 0xa4: v_readfirstlane_b32 s12, v4 + 0x7E1A'0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C'0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E'0507, // v_readfirstlane_b32 s15, v7 + 0x7E20'0508, // v_readfirstlane_b32 s16, v8 + 0x7E22'0509, // v_readfirstlane_b32 s17, v9 + 0x7E24'050A, // v_readfirstlane_b32 s18, v10 + 0x7E26'050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2'0015, + 0x0002'080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2'0016, + 0x0002'0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xD4E2'0016, + 0x0002'1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xD4E2'0016, + 0x0002'1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xBE95'3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80'0000, // s_nop 0 + 0xF09C'0F08, + 0x0043'0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C'3F70, // s_waitcnt vmcnt(0) + 0x897E'157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89'FFE6, // s_cbranch_execnz -> 0xa4 + 0xBEFE'0317, // s_mov_b32 exec_lo, s23 + 0xE070'1000, + 0x800A'0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81'0000, // s_endpgm +}; + +// The console compiler's waterfall (the title's ray-tracing +// resolve and others): each lane holds its entry's byte offset in the +// table at s0 (v7 = (lane & 1) * 32); the loop reads the first active +// lane's offset, narrows EXEC to the lanes with the same one +// (`v_cmpx_eq_u32`), loads that entry with `s_load_dwordx8` and samples, +// then drops those lanes (`s_andn2_wrexec_b32`). The sample goes to the +// buffer at dword 16 of the table, at lane * 4. +inline const std::vector<std::uint32_t> WATERFALL_INDEXED_WAVE32 = { + 0xBE84'0300, // s_mov_b32 s4, s0 + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xBE86'0301, // s_mov_b32 s6, s1 + 0xBE87'0380, // s_mov_b32 s7, 0 + 0xF408'0203, + 0xFA00'0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408'0A02, + 0xFA00'0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04'0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06'0302, // v_mov_b32 v3, v2 + 0x3420'0082, // v_lshlrev_b32 v16, 2, v0 + 0x360E'0081, // v_and_b32 v7, 1, v0 + 0x340E'0E85, // v_lshlrev_b32 v7, 5, v7 + 0xBF8C'C07F, // s_waitcnt lgkmcnt(0) + 0xBE97'037E, // s_mov_b32 s23, exec_lo + 0xBE95'037E, // s_mov_b32 s21, exec_lo + 0x7E28'0507, // 0x40: v_readfirstlane_b32 s20, v7 + 0x7DA4'0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 + 0xF40C'0302, + 0x2800'0000, // s_load_dwordx8 s[12:19], s[4:5], s20 + 0xBF8C'C07F, // s_waitcnt lgkmcnt(0) + 0xF09C'0F08, + 0x0043'0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C'3F70, // s_waitcnt vmcnt(0) + 0xBE95'4715, // s_andn2_wrexec_b32 s21, s21 + 0xBF89'FFF6, // s_cbranch_execnz -> 0x40 + 0xBEFE'0317, // s_mov_b32 exec_lo, s23 + 0xE070'1000, + 0x800A'0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81'0000, // s_endpgm +}; + +// WATERFALL_JOINED_WAVE32 with other sources on each path: lanes +// below 16 load table entry (lane & 1) with two `global_load_dwordx4`, +// the others pick per lane with `v_cndmask_b32` (lanes below 24 the +// first entry, the rest the second). +inline const std::vector<std::uint32_t> WATERFALL_JOINED_MIXED_WAVE32 = { + 0xBE84'0300, // s_mov_b32 s4, s0 + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xBE86'0301, // s_mov_b32 s6, s1 + 0xBE87'0380, // s_mov_b32 s7, 0 + 0xF40C'0602, + 0xFA00'0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C'0802, + 0xFA00'0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408'0203, + 0xFA00'0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408'0A02, + 0xFA00'0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04'0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06'0302, // v_mov_b32 v3, v2 + 0x3420'0082, // v_lshlrev_b32 v16, 2, v0 + 0x3602'0081, // v_and_b32 v1, 1, v0 + 0x3402'0285, // v_lshlrev_b32 v1, 5, v1 + 0x7D88'0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C'C07F, // s_waitcnt lgkmcnt(0) + 0xBE94'3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914'147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88'0004, // s_cbranch_execz -> 0x68 + 0xDC38'8000, + 0x0404'0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38'8010, + 0x0804'0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xBE94'3D14, // 0x68: s_or_saveexec_b32 s20, s20 + 0x897E'147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88'0011, // s_cbranch_execz -> 0xb8 + 0x7D88'0098, // v_cmp_gt_u32 vcc_lo, 24, v0 + 0x7E08'0218, // v_mov_b32 v4, s24 + 0x0208'0820, // v_cndmask_b32 v4, s32, v4, vcc_lo + 0x7E0A'0219, // v_mov_b32 v5, s25 + 0x020A'0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo + 0x7E0C'021A, // v_mov_b32 v6, s26 + 0x020C'0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo + 0x7E0E'021B, // v_mov_b32 v7, s27 + 0x020E'0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo + 0x7E10'021C, // v_mov_b32 v8, s28 + 0x0210'1024, // v_cndmask_b32 v8, s36, v8, vcc_lo + 0x7E12'021D, // v_mov_b32 v9, s29 + 0x0212'1225, // v_cndmask_b32 v9, s37, v9, vcc_lo + 0x7E14'021E, // v_mov_b32 v10, s30 + 0x0214'1426, // v_cndmask_b32 v10, s38, v10, vcc_lo + 0x7E16'021F, // v_mov_b32 v11, s31 + 0x0216'1627, // v_cndmask_b32 v11, s39, v11, vcc_lo + 0x887E'147E, // 0xb8: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97'037E, // s_mov_b32 s23, exec_lo + 0xBF8C'3F70, // s_waitcnt vmcnt(0) + 0x7E18'0504, // 0xc4: v_readfirstlane_b32 s12, v4 + 0x7E1A'0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C'0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E'0507, // v_readfirstlane_b32 s15, v7 + 0x7E20'0508, // v_readfirstlane_b32 s16, v8 + 0x7E22'0509, // v_readfirstlane_b32 s17, v9 + 0x7E24'050A, // v_readfirstlane_b32 s18, v10 + 0x7E26'050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2'0015, + 0x0002'080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2'0016, + 0x0002'0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xD4E2'0016, + 0x0002'1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xD4E2'0016, + 0x0002'1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xBE95'3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80'0000, // s_nop 0 + 0xF09C'0F08, + 0x0043'0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C'3F70, // s_waitcnt vmcnt(0) + 0x897E'157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89'FFE6, // s_cbranch_execnz -> 0xc4 + 0xBEFE'0317, // s_mov_b32 exec_lo, s23 + 0xE070'1000, + 0x800A'0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81'0000, // s_endpgm +}; + +// A waterfall loop whose descriptor changes on each pass: v[4:11] holds +// the first table entry on entry and the second after every pass, so +// the first lane's dwords are phis of the loop header. +inline const std::vector<std::uint32_t> WATERFALL_LOOPED_WAVE32 = { + 0xBE84'0300, // s_mov_b32 s4, s0 + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xBE86'0301, // s_mov_b32 s6, s1 + 0xBE87'0380, // s_mov_b32 s7, 0 + 0xF40C'0602, + 0xFA00'0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C'0802, + 0xFA00'0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408'0203, + 0xFA00'0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408'0A02, + 0xFA00'0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04'0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06'0302, // v_mov_b32 v3, v2 + 0x3420'0082, // v_lshlrev_b32 v16, 2, v0 + 0x7E08'0218, // v_mov_b32 v4, s24 + 0x7E0A'0219, // v_mov_b32 v5, s25 + 0x7E0C'021A, // v_mov_b32 v6, s26 + 0x7E0E'021B, // v_mov_b32 v7, s27 + 0x7E10'021C, // v_mov_b32 v8, s28 + 0x7E12'021D, // v_mov_b32 v9, s29 + 0x7E14'021E, // v_mov_b32 v10, s30 + 0x7E16'021F, // v_mov_b32 v11, s31 + 0xBF8C'C07F, // s_waitcnt lgkmcnt(0) + 0xBE97'037E, // s_mov_b32 s23, exec_lo + 0x7E18'0504, // 0x64: v_readfirstlane_b32 s12, v4 + 0x7E1A'0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C'0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E'0507, // v_readfirstlane_b32 s15, v7 + 0x7E20'0508, // v_readfirstlane_b32 s16, v8 + 0x7E22'0509, // v_readfirstlane_b32 s17, v9 + 0x7E24'050A, // v_readfirstlane_b32 s18, v10 + 0x7E26'050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2'0015, + 0x0002'080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2'0016, + 0x0002'0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xD4E2'0016, + 0x0002'1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xD4E2'0016, + 0x0002'1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xBE95'3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80'0000, // s_nop 0 + 0xF09C'0F08, + 0x0043'0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C'3F70, // s_waitcnt vmcnt(0) + 0x897E'157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0x7E08'0220, // v_mov_b32 v4, s32 + 0x7E0A'0221, // v_mov_b32 v5, s33 + 0x7E0C'0222, // v_mov_b32 v6, s34 + 0x7E0E'0223, // v_mov_b32 v7, s35 + 0x7E10'0224, // v_mov_b32 v8, s36 + 0x7E12'0225, // v_mov_b32 v9, s37 + 0x7E14'0226, // v_mov_b32 v10, s38 + 0x7E16'0227, // v_mov_b32 v11, s39 + 0xBF89'FFDE, // s_cbranch_execnz -> 0x64 + 0xBEFE'0317, // s_mov_b32 exec_lo, s23 + 0xE070'1000, + 0x800A'0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81'0000, // s_endpgm +}; + +// A waterfall loop over one of two buffer descriptors (four dwords) +// loaded from the table at s0, chosen by nested if/else: lanes below 16 +// move the first into v[4:7], lanes from 16 to 23 the second, and the +// others keep what v[4:7] held. Only lanes below 24 (the same mask) +// run the loop, which loads dword `lane` of the chosen buffer, and +// store it to the buffer at dword 16 of the table. +inline const std::vector<std::uint32_t> WATERFALL_JOINED_BUFFER_WAVE32 = { + 0xBE84'0300, // s_mov_b32 s4, s0 + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xF408'0602, + 0xFA00'0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0 + 0xF408'0802, + 0xFA00'0020, // s_load_dwordx4 s[32:35], s[4:5], 0x20 + 0xF408'0A02, + 0xFA00'0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x3420'0082, // v_lshlrev_b32 v16, 2, v0 + 0xD4C4'001E, + 0x0002'0098, // v_cmp_gt_u32_e64 s30, 24, v0 + 0x7D88'0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C'C07F, // s_waitcnt lgkmcnt(0) + 0xBE94'3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914'147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88'0004, // s_cbranch_execz -> 0x50 + 0x7E08'0218, // 0x40: v_mov_b32 v4, s24 + 0x7E0A'0219, // v_mov_b32 v5, s25 + 0x7E0C'021A, // v_mov_b32 v6, s26 + 0x7E0E'021B, // v_mov_b32 v7, s27 + 0xBE94'3D14, // 0x50: s_or_saveexec_b32 s20, s20 + 0x897E'147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88'0007, // s_cbranch_execz -> 0x78 + 0xBE9F'3C1E, // s_and_saveexec_b32 s31, s30 + 0xBF88'0004, // s_cbranch_execz -> 0x74 + 0x7E08'0220, // 0x64: v_mov_b32 v4, s32 + 0x7E0A'0221, // v_mov_b32 v5, s33 + 0x7E0C'0222, // v_mov_b32 v6, s34 + 0x7E0E'0223, // v_mov_b32 v7, s35 + 0x887E'1F7E, // 0x74: s_or_b32 exec_lo, exec_lo, s31 + 0x887E'147E, // 0x78: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97'3C1E, // s_and_saveexec_b32 s23, s30 + 0xBF88'0013, // s_cbranch_execz -> 0xd0 + 0xBE9D'037E, // s_mov_b32 s29, exec_lo + 0x7E18'0504, // 0x88: v_readfirstlane_b32 s12, v4 + 0x7E1A'0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C'0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E'0507, // v_readfirstlane_b32 s15, v7 + 0xD4E2'0015, + 0x0002'080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2'0016, + 0x0002'0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xBE95'3C15, // s_and_saveexec_b32 s21, s21 + 0xE030'1000, + 0x8003'0C10, // buffer_load_dword v12, v16, s[12:15], 0 offen + 0xBF8C'3F70, // s_waitcnt vmcnt(0) + 0x897E'157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89'FFF1, // s_cbranch_execnz -> 0x88 + 0xBEFE'031D, // s_mov_b32 exec_lo, s29 + 0xE070'1000, + 0x800A'0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0x887E'177E, // 0xd0: s_or_b32 exec_lo, exec_lo, s23 + 0xBF81'0000, // s_endpgm +}; +// The waterfall with `v_cmpx_eq` narrowing EXEC itself, and the retry as `todo & !EXEC` (`folded`: +// in one `s_andn2_wrexec`), as LLVM's AMDGPU backend writes it for GFX10 and later. +inline std::vector<std::uint32_t> cmpx_waterfall(bool wave64, bool folded) +{ + using fixtures_detail::word_at; + const std::vector<std::uint32_t>& base = wave64 ? WATERFALL_FETCHED_WAVE64 : WATERFALL_JOINED_WAVE32; + const std::uint32_t todo = wave64 ? 0xBE94'047E : 0xBE97'037E; + const std::uint32_t restore = wave64 ? 0xBEFE'0414 : 0xBEFE'0317; + const std::size_t reads = word_at(base, 0x7E18'0504); + const std::size_t sample = word_at(base, 0xF09C'0F08); + std::vector<std::uint32_t> w(base.begin(), base.begin() + static_cast<std::ptrdiff_t>(word_at(base, todo) + 1)); + // s_mov_b32 s21, exec_lo / s_mov_b64 s[22:23], exec + w.push_back(wave64 ? 0xBE96'047E : 0xBE95'037E); + w.insert(w.end(), base.begin() + static_cast<std::ptrdiff_t>(reads), + base.begin() + static_cast<std::ptrdiff_t>(reads + 8)); // v_readfirstlane_b32 s12..s19 + w.insert(w.end(), { + 0x7DE4'080C, // v_cmpx_eq_u64 s[12:13], v[4:5] + 0x7DE4'0C0E, // v_cmpx_eq_u64 s[14:15], v[6:7] + 0x7DE4'1010, // v_cmpx_eq_u64 s[16:17], v[8:9] + 0x7DE4'1412, // v_cmpx_eq_u64 s[18:19], v[10:11] + }); + w.insert(w.end(), base.begin() + static_cast<std::ptrdiff_t>(sample), + base.begin() + static_cast<std::ptrdiff_t>(sample + 2)); // image_sample_lz + if (!wave64 && folded) { + // s_andn2_wrexec_b32 s21, s21; s_cbranch_execnz + w.insert(w.end(), {0xBE95'4715, 0xBF89'FFF0}); + } else if (!wave64 && !folded) { + // s_andn2_b32 s21, s21, exec_lo; s_mov_b32 exec_lo, s21 + w.insert(w.end(), {0x8A15'7E15, 0xBEFE'0315, 0xBF89'FFEF}); + } else if (wave64 && folded) { + // s_andn2_wrexec_b64 s[22:23], s[22:23] + w.insert(w.end(), {0xBE96'3A16, 0xBF89'FFF0}); + } else { + // s_andn2_b64 s[22:23], s[22:23], exec; s_mov_b64 exec, s[22:23] + w.insert(w.end(), {0x8A96'7E16, 0xBEFE'0416, 0xBF89'FFEF}); + } + w.insert(w.end(), base.begin() + static_cast<std::ptrdiff_t>(word_at(base, restore)), base.end()); + return w; +} + +} // namespace x2w::vs::resource::fixtures diff --git a/tests/x2w_shader/vs_bvh_test.cpp b/tests/x2w_shader/vs_bvh_test.cpp new file mode 100644 index 0000000000..99472e3b7d --- /dev/null +++ b/tests/x2w_shader/vs_bvh_test.cpp @@ -0,0 +1,295 @@ +// Port of the upstream Rust shader tests in src/bvh.rs. +#include "x2w_shader/bvh.h" + +#include "vs_front_test.h" + +#include <bit> +#include <cmath> +#include <limits> +#include <optional> +#include <tuple> + +using namespace x2w::vs::bvh; +using namespace x2w::vs::bvh::testing; + +namespace { + +constexpr float INF = std::numeric_limits<float>::infinity(); +const float NaN = std::numeric_limits<float>::quiet_NaN(); + +constexpr Box UNIT{-1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f}; + +Box moved(Box b, Vec3 by) +{ + Box out{}; + for (int k = 0; k < 6; ++k) out[k] = b[k] + by[k % 3]; + return out; +} + +Box off() { return {NaN, NaN, NaN, NaN, NaN, NaN}; } + +Ray with_extent(Ray r, float extent) +{ + r.extent = extent; + return r; +} + +struct Hit { + float t, i, j; + bool front; +}; + +// The hit a result describes: distance, I, J, front face. +std::optional<Hit> hit(Result4 r) +{ + const float t = std::bit_cast<float>(r[0]), det = std::bit_cast<float>(r[1]); + const float i = std::bit_cast<float>(r[2]), j = std::bit_cast<float>(r[3]); + if (t == INF) return std::nullopt; + return Hit{t / det, i / det, j / det, det > 0.0f}; +} + +// Clockwise seen from the origin looking down +z in a left-handed system (x +// right, y up): the front face. +const Triangle TRIANGLE{{{0.0f, 2.0f, 5.0f}, {2.0f, -2.0f, 5.0f}, {-2.0f, -2.0f, 5.0f}}}; + +Words tri_node(const Triangle& t, std::uint32_t id) { return triangles(t.data(), 3, id); } + +const Result4 MISS_BITS = to_bits(MISS); + +} // namespace + +// An empty slot's inverted infinite bounds do not come before the children a +// ray enters. +VS_TEST(an_empty_slot_is_never_entered) +{ + auto inside = [](float x) { return Box{x - 1.0f, -1.0f, -1.0f, x + 1.0f, 1.0f, 1.0f}; }; + const float up = INF, down = -INF; + const Box empty{up, up, up, down, down, down}; + const Boxes bounds{inside(30.0f), empty, inside(10.0f), empty}; + const Ray ray = Ray::make({0, 0, 0}, {1.0f, 0.0f, 0.0f}, 100.0f); + VS_CHECK((boxes({8, NONE, 16, NONE}, bounds, ray, true) == Result4{16, 8, NONE, NONE})); +} + +VS_TEST(node_pointers_name_64_byte_nodes_past_the_descriptors_base) +{ + const std::uint64_t structure = 0x12'3456'7800ull; + const std::uint64_t pointer = ((structure >> 8) << 5) + ((0x40 >> 3) | 5); + VS_CHECK(kind(pointer) == 5); + VS_CHECK(node_address(0, BOX_SORT, pointer) == structure + 0x40); + const auto word0 = static_cast<std::uint32_t>(structure >> 8); + const auto word1 = static_cast<std::uint32_t>(structure >> 40) | BOX_SORT; + VS_CHECK(node_address(word0, word1, (0x1000 >> 3) | 4) == structure + 0x1000); + VS_CHECK(node_address(0, 0x8000'0001u, 8) == (1ull << 40) + 64); +} + +VS_TEST(halves_convert_exactly) +{ + VS_CHECK(half_to_f32(0x3c00) == 1.0f); + VS_CHECK(half_to_f32(0xc000) == -2.0f); + VS_CHECK(half_to_f32(0x7c00) == INF); + VS_CHECK(half_to_f32(0x0001) == std::ldexp(1.0f, -24)); + VS_CHECK(half_to_f32(0x03ff) == 1023.0f * std::ldexp(1.0f, -24)); + VS_CHECK(half_to_f32(0x7bff) == 65504.0f); + VS_CHECK(std::isnan(half_to_f32(0x7e00))); + VS_CHECK(std::bit_cast<std::uint32_t>(half_to_f32(0x8000)) == 0x8000'0000u); + VS_CHECK(half_to_f32(f32_to_half(0.1f, true)) >= 0.1f); + VS_CHECK(half_to_f32(f32_to_half(0.1f, false)) <= 0.1f); +} + +VS_TEST(boxes_are_returned_nearest_first_and_misses_last) +{ + const Result4 kids{0x105, 0x20c, 0x304, 0x400}; + const Words node = box32(kids, {moved(UNIT, {30.0f, 0.0f, 0.0f}), moved(UNIT, {10.0f, 0.0f, 0.0f}), + moved(UNIT, {10.0f, 5.0f, 0.0f}), moved(UNIT, {20.0f, 0.0f, 0.0f})}); + const Ray ray = Ray::make({0, 0, 0}, {1.0f, 0.0f, 0.0f}, 1000.0f); + VS_CHECK((intersect(node, 5, ray, true) == Result4{0x20c, 0x400, 0x105, NONE})); + VS_CHECK((intersect(node, 5, ray, false) == Result4{0x105, 0x20c, NONE, 0x400})); + VS_CHECK((intersect(node, 5, with_extent(ray, 19.5f), true) == Result4{0x20c, 0x400, NONE, NONE})); + VS_CHECK((intersect(node, 5, with_extent(ray, 19.0f), true) == Result4{0x20c, NONE, NONE, NONE})); + const Ray back = Ray::make({0, 0, 0}, {-1.0f, 0.0f, 0.0f}, 1000.0f); + VS_CHECK((intersect(node, 5, back, true) == Result4{NONE, NONE, NONE, NONE})); +} + +VS_TEST(a_ray_starting_inside_a_box_enters_it_at_its_origin) +{ + const Words node = box32({8, 16, NONE, NONE}, {UNIT, moved(UNIT, {3.0f, 0.0f, 0.0f}), off(), off()}); + const Ray ray = Ray::make({0, 0, 0}, {1.0f, 0.0f, 0.0f}, 100.0f); + VS_CHECK((intersect(node, 5, ray, true) == Result4{8, 16, NONE, NONE})); + VS_CHECK((intersect(node, 5, with_extent(ray, 1e-6f), true) == Result4{8, NONE, NONE, NONE})); +} + +VS_TEST(axis_aligned_rays_and_origins_on_a_face_make_no_nan) +{ + const Words node = box32({8, 16, 24, 32}, {UNIT, off(), off(), off()}); + const Ray ray = Ray::make({-5.0f, -1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 100.0f); + VS_CHECK(std::isinf(ray.inverse[1])); + VS_CHECK((intersect(node, 5, ray, true) == Result4{8, NONE, NONE, NONE})); + const Ray top = Ray::make({-5.0f, 1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 100.0f); + VS_CHECK((intersect(node, 5, top, true) == Result4{NONE, NONE, NONE, NONE})); + const Ray outside = Ray::make({-5.0f, 1.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, 100.0f); + VS_CHECK((intersect(node, 5, outside, true) == Result4{NONE, NONE, NONE, NONE})); + const Ray minus = Ray::make({-5.0f, 0.5f, 0.0f}, {1.0f, -0.0f, 0.0f}, 100.0f); + VS_CHECK(minus.inverse[1] == -INF); + VS_CHECK((intersect(node, 5, minus, true) == Result4{8, NONE, NONE, NONE})); +} + +VS_TEST(a_box_switched_off_and_a_missing_child_return_none) +{ + const Words node = box32({8, NONE, 24, 32}, {UNIT, UNIT, Box{NaN, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f}, off()}); + const Ray ray = Ray::make({-5.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 100.0f); + VS_CHECK((intersect(node, 5, ray, true) == Result4{8, NONE, NONE, NONE})); +} + +VS_TEST(equal_distances_keep_child_order) +{ + const Words node = box32({8, 16, 24, 32}, {UNIT, UNIT, UNIT, UNIT}); + const Ray ray = Ray::make({-5.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 100.0f); + VS_CHECK((intersect(node, 5, ray, true) == Result4{8, 16, 24, 32})); +} + +VS_TEST(half_float_boxes_test_like_their_widened_values) +{ + const Boxes bounds{moved(UNIT, {30.0f, 0.1f, 0.0f}), moved(UNIT, {10.0f, 0.0f, 0.3f}), + moved(UNIT, {10.0f, 5.0f, 0.0f}), moved(UNIT, {20.7f, 0.0f, 0.0f})}; + const Result4 kids{0x105, 0x20c, 0x304, 0x400}; + const Words node = box16(kids, bounds); + const Boxes wide = boxes16(node); + for (int b = 0; b < 4; ++b) + for (int k = 0; k < 3; ++k) VS_CHECK(wide[b][k] <= bounds[b][k] && wide[b][3 + k] >= bounds[b][3 + k]); + const Ray ray = Ray::make({0, 0, 0}, {1.0f, 0.0f, 0.0f}, 1000.0f); + VS_CHECK((intersect(node, 4, ray, true) == Result4{0x20c, 0x400, 0x105, NONE})); + VS_CHECK(intersect(node, 4, ray, true) == intersect(box32(kids, wide), 5, ray, true)); +} + +VS_TEST(a_triangle_returns_distance_and_weights_over_one_denominator) +{ + const Words node = tri_node(TRIANGLE, 9); + auto h = hit(intersect(node, 0, Ray::make({0, 0, 0}, {0.0f, 0.0f, 1.0f}, 100.0f), true)); + VS_REQUIRE(h.has_value()); + VS_CHECK(h->t == 5.0f); + VS_CHECK(h->i == 0.25f && h->j == 0.25f); + VS_CHECK(h->front); + h = hit(intersect(node, 0, Ray::make({1.75f, -1.75f, 0.0f}, {0.0f, 0.0f, 1.0f}, 100.0f), true)); + VS_REQUIRE(h.has_value()); + VS_CHECK(h->i > 0.85f && h->j < 0.1f); + h = hit(intersect(node, 0, Ray::make({0.0f, 0.0f, 10.0f}, {0.0f, 0.0f, -1.0f}, 100.0f), true)); + VS_REQUIRE(h.has_value()); + VS_CHECK(h->t == 5.0f && h->i == 0.25f && h->j == 0.25f && !h->front); + h = hit(intersect(node, 0, Ray::make({0, 0, 0}, {0.0f, 0.0f, 4.0f}, 100.0f), true)); + VS_REQUIRE(h.has_value()); + VS_CHECK(h->t == 1.25f); +} + +VS_TEST(a_triangle_is_missed_beside_behind_and_edge_on) +{ + const Words node = tri_node(TRIANGLE, 9); + VS_CHECK(intersect(node, 0, Ray::make({3.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}, 100.0f), true) == MISS_BITS); + VS_CHECK(intersect(node, 0, Ray::make({0.0f, 0.0f, 6.0f}, {0.0f, 0.0f, 1.0f}, 100.0f), true) == MISS_BITS); + VS_CHECK(intersect(node, 0, Ray::make({-5.0f, 0.0f, 5.0f}, {1.0f, 0.0f, 0.0f}, 100.0f), true) == MISS_BITS); + const Words flat = tri_node({{{0.0f, 0.0f, 5.0f}, {1.0f, 1.0f, 5.0f}, {2.0f, 2.0f, 5.0f}}}, 9); + VS_CHECK(intersect(flat, 0, Ray::make({1.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}, 100.0f), true) == MISS_BITS); + const Words nan = tri_node({{{NaN, 2.0f, 5.0f}, TRIANGLE[1], TRIANGLE[2]}}, 9); + VS_CHECK(intersect(nan, 0, Ray::make({0, 0, 0}, {0.0f, 0.0f, 1.0f}, 100.0f), true) == MISS_BITS); + VS_CHECK(intersect(node, 0, Ray::make({0, 0, 0}, {0, 0, 0}, 100.0f), true) == MISS_BITS); + VS_CHECK(hit(intersect(node, 0, Ray::make({0, 0, 0}, {0.0f, 0.0f, 1.0f}, 1.0f), true)).has_value()); +} + +VS_TEST(a_ray_through_a_shared_edge_misses_neither_triangle) +{ + const Vec3 quad[4] = {{-1.0f, -1.0f, 4.0f}, {-1.0f, 1.0f, 4.0f}, {1.0f, 1.0f, 4.0f}, {1.0f, -1.0f, 4.0f}}; + const Words first = tri_node({{quad[0], quad[1], quad[2]}}, 9); + const Words second = tri_node({{quad[0], quad[2], quad[3]}}, 9); + const Vec3 dirs[3] = {{0.0f, 0.0f, 1.0f}, {0.125f, -0.0625f, 1.0f}, {0.25f, 0.5f, 2.0f}}; + for (int n = -40; n <= 40; ++n) { + const float x = static_cast<float>(n) / 64.0f; + const std::pair<float, float> origins[3] = { + {x, x}, {x, x + 1.0f / 1024.0f}, {x + 1.0f / 1024.0f, x}}; + for (auto [ox, oy] : origins) { + for (const Vec3& d : dirs) { + const float s = 4.0f / d[2]; + const Ray ray = Ray::make({ox - d[0] * s, oy - d[1] * s, 0.0f}, d, 100.0f); + const auto a = hit(intersect(first, 0, ray, true)); + const auto b = hit(intersect(second, 0, ray, true)); + VS_CHECK(a.has_value() || b.has_value()); + for (const auto& h : {a, b}) { + if (h) VS_CHECK(std::fabs(h->t - s) < 1e-5f && h->front); + } + } + } + } +} + +VS_TEST(the_id_dword_says_which_vertices_the_weights_belong_to) +{ + const Vec3 a = TRIANGLE[0], b = TRIANGLE[1], c = TRIANGLE[2]; + const Ray ray = Ray::make({0.5f, -0.25f, 0.0f}, {0.0f, 0.0f, 1.0f}, 100.0f); + const Result4 plain = intersect(tri_node({{a, b, c}}, 9), 0, ray, true); + const std::pair<std::uint32_t, std::uint32_t> ids[6] = {{1, 2}, {2, 0}, {0, 1}, {2, 1}, {0, 2}, {1, 0}}; + for (auto [i, j] : ids) { + Triangle stored{}; + stored[3 - i - j] = a; + stored[i] = b; + stored[j] = c; + VS_CHECK(intersect(tri_node(stored, i | (j << 2)), 0, ray, true) == plain); + } + VS_CHECK(intersect(tri_node({{a, b, c}}, 9 | 0x80), 0, ray, true) == plain); +} + +VS_TEST(triangles_one_to_three_take_their_vertices_and_their_id_byte) +{ + const Vec3 a = TRIANGLE[0], b = TRIANGLE[1], c = TRIANGLE[2]; + const Vec3 far_{50.0f, 50.0f, 50.0f}; + const Ray ray = Ray::make({0.5f, -0.25f, 0.0f}, {0.0f, 0.0f, 1.0f}, 100.0f); + const Result4 plain = intersect(tri_node({{a, b, c}}, 9), 0, ray, true); + for (std::uint32_t k = 1; k < 4; ++k) { + Vec3 vertices[5] = {far_, far_, far_, far_, far_}; + const auto& at = TRIANGLE_VERTICES[k]; + vertices[at[0]] = a; + vertices[at[1]] = b; + vertices[at[2]] = c; + const Words node = triangles(vertices, 5, 9u << (8 * k)); + VS_CHECK(intersect(node, k, ray, true) == plain); + } + const Vec3 d{2.0f, 2.0f, 5.0f}; + const Vec3 four[4] = {a, b, c, d}; + const Words node = triangles(four, 4, 9 | ((1 | (2 << 2)) << 8)); + VS_CHECK((triangle_vertices(node, 1) == Triangle{{b, d, c}})); +} + +VS_TEST(instances_and_procedural_nodes_return_a_triangle_miss) +{ + const Words node = tri_node(TRIANGLE, 9); + const Ray ray = Ray::make({0, 0, 0}, {0.0f, 0.0f, 1.0f}, 100.0f); + for (std::uint32_t k : {6u, 7u}) VS_CHECK(intersect(node, k, ray, true) == MISS_BITS); +} + +VS_TEST(the_largest_axis_and_its_sign_do_not_change_the_answer) +{ + auto turn = [](Vec3 v, int axis, bool flip) { + Vec3 r = v; + for (int n = 0; n < axis; ++n) r = {r[2], r[0], r[1]}; + if (flip) { + const int largest = (2 + axis) % 3; + r[largest] = -r[largest]; + r[(largest + 1) % 3] = -r[(largest + 1) % 3]; + } + return r; + }; + const Ray ray = Ray::make({0.25f, -0.5f, 0.0f}, {0.0625f, 0.125f, 1.0f}, 100.0f); + const auto base = hit(to_bits(triangle(TRIANGLE, ray))); + VS_REQUIRE(base.has_value()); + for (int axis = 0; axis < 3; ++axis) { + for (bool flip : {false, true}) { + Triangle p{}; + for (int v = 0; v < 3; ++v) p[v] = turn(TRIANGLE[v], axis, flip); + const Ray r = Ray::make(turn(ray.origin, axis, flip), turn(ray.direction, axis, flip), 100.0f); + const auto h = hit(to_bits(triangle(p, r))); + VS_REQUIRE(h.has_value()); + VS_CHECK(std::fabs(h->t - base->t) < 1e-5f); + VS_CHECK(std::fabs(h->i - base->i) < 1e-5f && std::fabs(h->j - base->j) < 1e-5f); + VS_CHECK(h->front == base->front); + } + } +} + +VS_TEST_MAIN() diff --git a/tests/x2w_shader/vs_front_test.h b/tests/x2w_shader/vs_front_test.h new file mode 100644 index 0000000000..8256c62d19 --- /dev/null +++ b/tests/x2w_shader/vs_front_test.h @@ -0,0 +1,91 @@ +// A minimal test harness for the vs-front ports' ctest executables: each +// TEST registers a case; main runs every case (or those named on the command +// line) and fails if any check failed. +#pragma once + +#include <cstdio> +#include <cstring> +#include <exception> +#include <functional> +#include <string> +#include <vector> + +namespace vs_front_test { + +struct Case { + const char* name; + void (*run)(); +}; + +inline std::vector<Case>& cases() +{ + static std::vector<Case> all; + return all; +} + +inline int& failures() +{ + static int n = 0; + return n; +} + +struct Register { + Register(const char* name, void (*run)()) { cases().push_back({name, run}); } +}; + +inline void fail(const char* file, int line, const std::string& what) +{ + std::fprintf(stderr, "%s:%d: check failed: %s\n", file, line, what.c_str()); + ++failures(); +} + +struct Abort {}; + +inline int run_all(int argc, char** argv) +{ + int ran = 0; + for (const Case& c : cases()) { + bool wanted = argc <= 1; + for (int i = 1; i < argc; ++i) wanted |= std::strcmp(argv[i], c.name) == 0; + if (!wanted) continue; + ++ran; + const int before = failures(); + try { + c.run(); + } catch (const Abort&) { + } catch (const std::exception& e) { + std::fprintf(stderr, "%s: exception: %s\n", c.name, e.what()); + ++failures(); + } + std::fprintf(stderr, "%s %s\n", failures() == before ? "ok " : "FAIL", c.name); + } + if (ran == 0) { + std::fprintf(stderr, "no test case matched\n"); + return 1; + } + return failures() == 0 ? 0 : 1; +} + +} // namespace vs_front_test + +#define VS_TEST(name) \ + static void name(); \ + static ::vs_front_test::Register name##_registered(#name, &name); \ + static void name() + +#define VS_CHECK(cond) \ + do { \ + if (!(cond)) ::vs_front_test::fail(__FILE__, __LINE__, #cond); \ + } while (0) + +// A check the rest of the case depends on. +#define VS_REQUIRE(cond) \ + do { \ + if (!(cond)) { \ + ::vs_front_test::fail(__FILE__, __LINE__, #cond); \ + throw ::vs_front_test::Abort{}; \ + } \ + } while (0) + +#define VS_TEST_MAIN() \ + int main(int argc, char** argv) { return ::vs_front_test::run_all(argc, argv); } diff --git a/tests/x2w_shader/vs_io_test.cpp b/tests/x2w_shader/vs_io_test.cpp new file mode 100644 index 0000000000..c185d910a4 --- /dev/null +++ b/tests/x2w_shader/vs_io_test.cpp @@ -0,0 +1,254 @@ +// Port of the upstream Rust shader tests in src/io.rs. +#include "x2w_shader/io.h" + +#include "vs_front_test.h" + +#include <algorithm> +#include <cstdio> +#include <stdexcept> + +using namespace x2w::vs; +using namespace x2w::vs::io; +using native::HwStage; +using native::NativeProgram; +using native::PsInput; +using native::Usage; +using ir::Program; +using ir::Reg; + +namespace { + +constexpr std::uint32_t S_ENDPGM = 0xBF81'0000; + +std::vector<std::uint8_t> bytes(const std::vector<std::uint32_t>& words) +{ + std::vector<std::uint8_t> code; + for (std::uint32_t w : words) + for (int i = 0; i < 4; ++i) code.push_back(static_cast<std::uint8_t>(w >> (8 * i))); + return code; +} + +Program program(const std::vector<std::uint32_t>& words) { return ir::build(bytes(words), false, 256); } + +NativeProgram pixel(std::vector<PsInput> inputs, std::uint32_t input_addr) +{ + NativeProgram n; + n.stage = HwStage::Ps; + n.wave64 = false; + n.vgprs = 256; + native::PsIo ps; + ps.inputs = std::move(inputs); + ps.input_addr = input_addr; + ps.db_shader_control = 0; + n.io = ps; + return n; +} + +PsInput texcoord() +{ + PsInput i; + i.usage = Usage::Generic(); + i.row = 1; + i.mask = 3; + i.attr = 0; + i.flat = false; + i.fp16 = false; + i.pack2 = false; + i.row2 = 1; + return i; +} + +const Attribute ATTRIBUTE{Usage::Generic(), 1, 0, false}; + +bool fails(const Program& p, const NativeProgram& n) +{ + return catch_shader_error([&] { raise(p, n); }).has_value(); +} + +} // namespace + +VS_TEST(interpolation_pairs_and_color_exports) +{ + // Blit's pixel shader: TEXCOORD.xy from the perspective-center i/j in v0/v1, then exported + // unconverted to MRT0. + const Program p = program({ + 0xC808'0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809'0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xF800'180F, + 0x0302'0102, // exp mrt0, v2, v1, v2, v3 done vm + S_ENDPGM, + }); + const Io io = raise(p, pixel({texcoord()}, 2)); + auto input = [&](std::uint8_t reg) { + for (const auto& i : p.inputs) + if (i.first == Reg::V(reg)) return i.second; + throw std::runtime_error("no input"); + }; + auto center = [](std::uint8_t index) { return Input::Bary(Barycentric::PerspectiveCenter, index); }; + auto has = [&](const std::pair<ir::Value, Input>& e) { + return std::find(io.inputs.begin(), io.inputs.end(), e) != io.inputs.end(); + }; + VS_CHECK(has({input(0), center(0)})); + VS_CHECK(has({input(1), center(1)})); + // v2 and v3 are read before written but hold nothing. + const ir::Value v3 = input(3); + VS_CHECK(std::none_of(io.inputs.begin(), io.inputs.end(), [&](const auto& i) { return i.first == v3; })); + const std::vector<std::pair<Site, Interp>> want{ + {{0, 1}, Interp::Interpolated(ATTRIBUTE, Barycentric::PerspectiveCenter, {{0, 0}})}}; + VS_CHECK(io.interps == want); + VS_REQUIRE(io.exports.size() == 1); + const Export& e = io.exports[0]; + VS_CHECK(e.target == Target::Color(0) && e.done && !e.compressed); + VS_CHECK(e.values[0] == p.blocks[0].insts[1].write(Reg::V(2))); +} + +VS_TEST(unpaired_or_unknown_interpolation_fails) +{ + // p2 alone: its old dst is no p1's result. + const Program lone = program({0xC809'0001, S_ENDPGM}); // v_interp_p2_f32 v2, v1, attr0.x + VS_CHECK(fails(lone, pixel({texcoord()}, 2))); + // attr1 is not in the stage data. + const Program other = program({0xC808'0400, S_ENDPGM}); // v_interp_p1_f32 v2, v0, attr1.x + VS_CHECK(fails(other, pixel({texcoord()}, 2))); +} + +VS_TEST(computed_barycentrics_evaluate_each_half) +{ + // i scaled before the first half: both halves stand on their own. + const Program p = program({ + 0x1006'00F0, // v_mul_f32 v3, 0.5, v0 + 0xC808'0003, // v_interp_p1_f32 v2, v3, attr0.x + 0xC809'0001, // v_interp_p2_f32 v2, v1, attr0.x + S_ENDPGM, + }); + const Io io = raise(p, pixel({texcoord()}, 2)); + auto interps = io.interps; + std::stable_sort(interps.begin(), interps.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); + const std::vector<std::pair<Site, Interp>> want{ + {{0, 1}, Interp::Weighted(ATTRIBUTE)}, + {{0, 2}, Interp::Weighted(ATTRIBUTE)}, + }; + VS_CHECK(interps == want); +} + +VS_TEST(first_halves_read_through_a_phi_keep_their_partial_values) +{ + const Program p = program({ + 0xBF06'8000, // s_cmp_eq_u32 s0, 0 + 0xBF85'0002, // s_cbranch_scc1 -> second first half + 0xC808'0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xBF82'0001, // s_branch -> export + 0xC808'0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xF800'180F, + 0x0202'0202, // exp mrt0, v2, v2, v2, v2 done vm + S_ENDPGM, + }); + const Io io = raise(p, pixel({texcoord()}, 2)); + VS_CHECK(io.interps.size() == 2); + VS_CHECK(std::all_of(io.interps.begin(), io.interps.end(), + [](const auto& i) { return i.second.kind == Interp::Kind::Weighted; })); +} + +VS_TEST(a_standalone_f16_first_half_is_weighted) +{ + const Program p = program({ + 0xD742'0002, + 0x0002'0000, // v_interp_p1ll_f16 v2, v0, attr0.x + 0xF800'180F, + 0x0202'0202, + S_ENDPGM, + }); + PsInput in = texcoord(); + in.fp16 = true; + const Io io = raise(p, pixel({in}, 2)); + VS_CHECK(io.interps.size() == 1 && io.interps[0].second.kind == Interp::Kind::Weighted); +} + +VS_TEST(mesh_inputs_and_primitive_export) +{ + // Rust's `mesh(..)`: Ok(io) or Err. + auto mesh = [](const std::vector<std::uint32_t>& words) -> std::optional<Io> { + const auto code = bytes(words); + const Program p = ir::build(code, true, 256); + NativeProgram n; + n.stage = HwStage::Ms; + n.wave64 = true; + n.vgprs = 256; + native::MeshIo ms; + ms.clip_cntl = 0; + ms.threads = 128; + ms.max_vertices = 128; + ms.max_primitives = 128; + ms.topology = 2; + ms.lds_bytes = 0; + n.io = ms; + n.code = code; + return try_shader([&] { return raise(p, n); }); + }; + const auto io = mesh({ + 0x7E04'0505, // v_readfirstlane_b32 s2, v5 + 0xF800'0941, + 0x0000'0009, // exp prim, v9, off, off, off done + S_ENDPGM, + }); + VS_REQUIRE(io.has_value()); + VS_CHECK(std::any_of(io->inputs.begin(), io->inputs.end(), + [](const auto& i) { return i.second == Input::Simple(Input::Kind::MeshGroup); })); + VS_REQUIRE(!io->exports.empty()); + VS_CHECK(io->exports[0].target == Target::Simple(Target::Kind::Primitive)); + // The group input is uniform only as the first lane reads it. + VS_CHECK(!mesh({0x7E02'0305, S_ENDPGM}).has_value()); // v_mov_b32 v1, v5 + // Also as an operand of a write to v5, or after a join. + const std::vector<std::vector<std::uint32_t>> per_lane = { + {0x4A0A'0305, S_ENDPGM}, // v_add_nc_u32 v5, v5, v1 + {0x7E0A'0D05, S_ENDPGM}, // v_cvt_f32_u32 v5, v5 + {0xDC30'8000, 0x0500'0005, S_ENDPGM}, // global_load_dword v5, v5, s[0:1] + {0x7E0A'CB01, S_ENDPGM}, // v_swap_b32 v5, v1 + { + 0xBF06'8001, // s_cmp_eq_u32 s1, 0 + 0xBF85'0001, // s_cbranch_scc1 -> 0xc + 0x7E0A'0280, // v_mov_b32 v5, 0 + 0x7E02'0305, // 0xc: v_mov_b32 v1, v5 + S_ENDPGM, + }, + }; + for (std::size_t k = 0; k < per_lane.size(); ++k) { + const bool accepted = mesh(per_lane[k]).has_value(); + if (accepted) std::fprintf(stderr, "accepted per_lane[%zu]\n", k); + VS_CHECK(!accepted); + } + // Overwriting v5 reads the group input only for lanes outside EXEC: v_mov_b32 v5, 0; + // v_mov_b32 v1, v5. + VS_CHECK(mesh({0x7E0A'0280, 0x7E02'0305, S_ENDPGM}).has_value()); + // Skipping that write with s_cbranch_execz is the same case: under the same mask, the read sees + // only the 0. + const std::vector<std::uint32_t> reuse = { + 0x7E04'0505, // v_readfirstlane_b32 s2, v5 + 0x7D88'0084, // v_cmp_gt_u32 vcc, 4, v0 + 0xBE86'246A, // s_and_saveexec_b64 s[6:7], vcc + 0xBF88'0001, // s_cbranch_execz -> 0x14 + 0x7E0A'0280, // v_mov_b32 v5, 0 + 0x88FE'067E, // 0x14: s_or_b64 exec, exec, s[6:7] + 0xBE86'246A, // s_and_saveexec_b64 s[6:7], vcc + 0xBF88'0001, // s_cbranch_execz -> 0x24 + 0x7E02'0305, // v_mov_b32 v1, v5 + 0x88FE'067E, // 0x24: s_or_b64 exec, exec, s[6:7] + S_ENDPGM, + }; + VS_CHECK(mesh(reuse).has_value()); +} + +VS_TEST(pixel_vgprs_follow_the_input_address) +{ + // Linear center (bit 5), then position x and y (bits 8, 9). + const auto v = detail::ps_vgprs((1u << 5) | (1u << 8) | (1u << 9)); + const std::vector<std::pair<std::uint8_t, Input>> want{ + {std::uint8_t{0}, Input::Bary(Barycentric::LinearCenter, 0)}, + {std::uint8_t{1}, Input::Bary(Barycentric::LinearCenter, 1)}, + {std::uint8_t{2}, Input::Position(0)}, + {std::uint8_t{3}, Input::Position(1)}, + }; + VS_CHECK(v == want); +} + +VS_TEST_MAIN() diff --git a/tests/x2w_shader/vs_native_test.cpp b/tests/x2w_shader/vs_native_test.cpp new file mode 100644 index 0000000000..58df5e0226 --- /dev/null +++ b/tests/x2w_shader/vs_native_test.cpp @@ -0,0 +1,450 @@ +// Port of the upstream Rust shader tests in src/native.rs. +// +// The Rust tests compress with zlib-rs; the repository has no deflate compressor, so xbch() here +// writes a zlib stream of stored blocks (header, stored blocks, Adler-32), which inflates the same. +#include "x2w_shader/native.h" + +#include "vs_front_test.h" + +#include <cstring> + +#include "x2w_shader/dxbc.h" + +using namespace x2w::vs; +using namespace x2w::vs::native; + +namespace { + +using Buf = std::vector<std::uint8_t>; + +constexpr std::size_t XDAT_OFFSET = 0x18; +constexpr std::uint32_t KIND_NATIVE = 0x0d; +constexpr std::uint32_t XBCH_VERSION = 3; +constexpr std::size_t XBCH_HEADER = 0x18; +constexpr std::uint32_t FSSM_VERSION = 0x101; +constexpr std::size_t FSSM_HEADER = 0x10; +constexpr std::uint64_t GRAPHICS_SLOT_COUNT = 6; +constexpr std::pair<HwStage, std::size_t> SLOTS[8] = { + {HwStage::Ls, 0x08}, {HwStage::Hs, 0x10}, {HwStage::Es, 0x18}, {HwStage::Gs, 0x20}, + {HwStage::Vs, 0x28}, {HwStage::Ps, 0x30}, {HwStage::Ms, 0x48}, {HwStage::Cs, 0x60}, +}; +constexpr std::uint64_t ABSENT = 0xDEAD'BEEF'DEAD'BEEFull; +constexpr std::size_t RECORD_SIZE = 0x54; +constexpr std::uint32_t FLAG_WAVE32 = 1u << 5; +constexpr std::size_t RECORD_REGS = 0x50; +constexpr std::size_t RECORD_LAYOUT = 0x28; +constexpr std::size_t RECORD_USED = 0x30; +constexpr std::size_t RECORD_COUNTS = 0x38; +constexpr std::uint64_t ENTRY_SIZE = 20; +constexpr std::size_t PS_INPUTS = 0x24; +constexpr std::size_t PS_INPUT_COUNT = 0x124; +constexpr std::size_t PS_INPUT_ADDR = 0x134; +constexpr std::size_t PS_PATCH_SIZE = 0x148; +constexpr std::size_t PS_PATCHES = 0x14c; +constexpr std::size_t PATCH_SLOT_DWORDS = 10; +constexpr std::size_t PATCH_FULL = 9; +constexpr std::size_t PATCH_BYTES = 4 + 10 * PATCH_SLOT_DWORDS * 4; +constexpr std::size_t MRTS = 8; +constexpr std::size_t VS_INPUT_COUNT = 0xc4; +constexpr std::size_t VS_OUTPUTS = 0xc8; +constexpr std::size_t VS_OUTPUT_COUNT = 0x188; +constexpr std::size_t RECORD_LDS = 0x4c; +constexpr std::size_t MS_CLIP_CNTL = 0x194; +constexpr std::size_t MS_INFO = 0x448; + +const Buf VS_CODE{1, 2, 3, 4, 5, 6, 7, 8}; +const Buf PS_CODE{9, 10, 11, 12}; +constexpr std::uint32_t VGPRS = 28; + +std::size_t slot(HwStage stage) +{ + for (const auto& s : SLOTS) + if (s.first == stage) return s.second; + return 0; +} + +void put32(Buf& b, std::size_t at, std::uint32_t v) +{ + for (int i = 0; i < 4; ++i) b[at + i] = static_cast<std::uint8_t>(v >> (8 * i)); +} +void put64(Buf& b, std::size_t at, std::uint64_t v) +{ + for (int i = 0; i < 8; ++i) b[at + i] = static_cast<std::uint8_t>(v >> (8 * i)); +} +void push32(Buf& b, std::uint32_t v) +{ + for (int i = 0; i < 4; ++i) b.push_back(static_cast<std::uint8_t>(v >> (8 * i))); +} +void push64(Buf& b, std::uint64_t v) +{ + for (int i = 0; i < 8; ++i) b.push_back(static_cast<std::uint8_t>(v >> (8 * i))); +} +void push_bytes(Buf& b, std::initializer_list<std::uint8_t> v) { b.insert(b.end(), v.begin(), v.end()); } +void set_bytes(Buf& b, std::size_t at, std::initializer_list<std::uint8_t> v) +{ + std::size_t i = 0; + for (auto x : v) b[at + i++] = x; +} +std::uint64_t get64(const Buf& b, std::size_t at) +{ + std::uint64_t v = 0; + for (int i = 0; i < 8; ++i) v |= std::uint64_t{b[at + i]} << (8 * i); + return v; +} + +// Stage data: no semantics, and every export patch absent. +constexpr std::size_t STAGE_DATA = PS_PATCHES + MRTS * PATCH_BYTES; + +Buf empty_stage_data() +{ + Buf data(STAGE_DATA, 0); + for (std::size_t mrt = 0; mrt < MRTS; ++mrt) put32(data, PS_PATCHES + mrt * PATCH_BYTES, 0xFFFF'FFFFu); + return data; +} + +// Where a one-program blob's stage data starts. +std::size_t stage_data_at(const Buf& blob, HwStage stage) +{ + return FSSM_HEADER + static_cast<std::size_t>(get64(blob, FSSM_HEADER + slot(stage))) + RECORD_SIZE; +} + +// FSSM blob with `programs` as (stage, code) pairs. +Buf fssm(const std::vector<std::pair<HwStage, Buf>>& programs) +{ + Buf payload; + push64(payload, GRAPHICS_SLOT_COUNT); + payload.resize(slot(HwStage::Cs) + 8, 0); + for (const auto& s : SLOTS) put64(payload, s.second, ABSENT); + for (const auto& [stage, code] : programs) { + const std::size_t at = slot(stage); + const std::uint64_t record = payload.size(); + put64(payload, at, record); + const std::uint64_t code_at = record + RECORD_SIZE + STAGE_DATA; + push64(payload, code_at); + push64(payload, code.size()); + const std::uint32_t flags = stage == HwStage::Ps ? FLAG_WAVE32 : 0; + push32(payload, 0); + push32(payload, flags); + payload.resize(record + RECORD_REGS, 0); + push32(payload, VGPRS | (31u << 20)); + const Buf data = empty_stage_data(); + payload.insert(payload.end(), data.begin(), data.end()); + payload.insert(payload.end(), code.begin(), code.end()); + } + Buf out{'F', 'S', 'S', 'M'}; + push32(out, FSSM_VERSION); + push64(out, payload.size()); + out.insert(out.end(), payload.begin(), payload.end()); + return out; +} + +std::uint32_t adler32(const Buf& data) +{ + std::uint32_t a = 1, b = 0; + for (std::uint8_t x : data) { + a = (a + x) % 65521; + b = (b + a) % 65521; + } + return (b << 16) | a; +} + +// A zlib stream of stored blocks. +Buf zlib_stored(const Buf& data) +{ + Buf out{0x78, 0x01}; + std::size_t at = 0; + do { + const std::size_t n = std::min<std::size_t>(data.size() - at, 65535); + const bool last = at + n == data.size(); + out.push_back(last ? 1 : 0); + out.push_back(static_cast<std::uint8_t>(n)); + out.push_back(static_cast<std::uint8_t>(n >> 8)); + out.push_back(static_cast<std::uint8_t>(~n)); + out.push_back(static_cast<std::uint8_t>(~n >> 8)); + out.insert(out.end(), data.begin() + at, data.begin() + at + n); + at += n; + } while (at < data.size()); + const std::uint32_t adler = adler32(data); + for (int i = 3; i >= 0; --i) out.push_back(static_cast<std::uint8_t>(adler >> (8 * i))); + return out; +} + +Buf xbch(const Buf& unpacked) +{ + const Buf stream = zlib_stored(unpacked); + Buf out{'X', 'B', 'C', 'H'}; + push32(out, XBCH_VERSION); + push64(out, stream.size()); + push64(out, unpacked.size()); + out.insert(out.end(), stream.begin(), stream.end()); + return out; +} + +// `DXIL` part data: program header, XDAT index, then the blobs. +Buf part(const std::vector<std::pair<std::uint32_t, Buf>>& blobs) +{ + Buf out(XDAT_OFFSET, 0); + push_bytes(out, {'X', 'D', 'A', 'T'}); + push32(out, static_cast<std::uint32_t>(blobs.size())); + push32(out, 0x24); + std::size_t offset = out.size() + 12 * blobs.size(); + for (const auto& [kind, blob] : blobs) { + push32(out, kind); + push32(out, static_cast<std::uint32_t>(offset)); + push32(out, static_cast<std::uint32_t>(blob.size())); + offset += blob.size(); + } + for (const auto& b : blobs) out.insert(out.end(), b.second.begin(), b.second.end()); + return out; +} + +bool fails(const Buf& data) +{ + return catch_shader_error([&] { native_programs(data); }).has_value(); +} + +const Buf XBOP{'x', 'b', 'o', 'p'}; + +} // namespace + +VS_TEST(finds_graphics_programs) +{ + const Buf native = xbch(fssm({{HwStage::Vs, VS_CODE}, {HwStage::Ps, PS_CODE}})); + const Buf data = part({{0x0a, XBOP}, {KIND_NATIVE, native}}); + const auto found = native_programs(data); + NativeProgram vs; + vs.stage = HwStage::Vs; + vs.wave64 = true; + vs.vgprs = 28; + vs.io = VsIo{}; + vs.code = VS_CODE; + NativeProgram ps; + ps.stage = HwStage::Ps; + ps.wave64 = false; + ps.vgprs = 28; + ps.io = PsIo{}; + ps.code = PS_CODE; + VS_CHECK((found == std::vector<NativeProgram>{vs, ps})); +} + +VS_TEST(reads_root_tables) +{ + Buf blob = fssm({{HwStage::Ps, PS_CODE}}); + const std::size_t record = FSSM_HEADER + static_cast<std::size_t>(get64(blob, FSSM_HEADER + slot(HwStage::Ps))); + const std::uint64_t tables = blob.size() - FSSM_HEADER; + // A table range in s9 (root slot 1), and an SRV read from it. + for (std::uint32_t v : {3u, 2u, 1u, 5u}) push32(blob, v); + push_bytes(blob, {9, 1, 0, 0, 0, 3, 0, 0}); + for (std::uint32_t v : {2u, 5u, 4u}) push32(blob, v); + push_bytes(blob, {8, 9, 1, 0}); + const std::uint64_t payload = blob.size() - FSSM_HEADER; + put64(blob, 8, payload); + put64(blob, record + RECORD_LAYOUT, tables); + put64(blob, record + RECORD_USED, tables + ENTRY_SIZE); + set_bytes(blob, record + RECORD_COUNTS, {1, 0, 0, 0, 1, 0, 0, 0}); + + const auto found = native_programs(part({{KIND_NATIVE, xbch(blob)}})); + VS_REQUIRE(!found.empty()); + const NativeProgram& p = found[0]; + RootParam r; + r.root = RootType::Table(); + r.table_offset_dwords = 2; + r.sgprs = 1; + r.base_register = 5; + r.user_data = 9; + r.slot = 1; + VS_CHECK(p.layout == std::vector<RootParam>{r}); + UsedResource u; + u.kind = ResourceType::Srv(); + u.root = RootType::Table(); + u.table_offset_dwords = 2; + u.lower_bound = 5; + u.stride = 4; + u.dwords = 8; + u.user_data = 9; + u.slot = 1; + VS_CHECK(p.used == std::vector<UsedResource>{u}); + + blob[record + RECORD_COUNTS] = 9; + VS_CHECK(fails(part({{KIND_NATIVE, xbch(blob)}}))); +} + +VS_TEST(reads_pixel_io_and_applies_the_full_export_patch) +{ + Buf bytes; + for (int i = 0; i < 4; ++i) push32(bytes, 0xBF80'0000u); // s_nop + Buf blob = fssm({{HwStage::Ps, bytes}}); + const std::size_t e = stage_data_at(blob, HwStage::Ps); + // TEXCOORD in row 1 (xy), read as attr0, flat. + set_bytes(blob, e + PS_INPUTS, {6, 1, 3, 0, 0, 0, 1, 1}); + put32(blob, e + PS_INPUT_COUNT, 1); + put32(blob, e + PS_INPUT_ADDR, 2); + put32(blob, e + PS_PATCH_SIZE, 2); + // MRT1 at dword 1: the 32_ABGR variant is `exp mrt1 v0-v3 done`. + const std::size_t patch = e + PS_PATCHES + PATCH_BYTES; + put32(blob, patch, 1); + const std::size_t full = patch + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4; + set_bytes(blob, full, {0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3}); + + const auto found = native_programs(part({{KIND_NATIVE, xbch(blob)}})); + VS_REQUIRE(!found.empty()); + const NativeProgram& p = found[0]; + const auto* ps = std::get_if<PsIo>(&p.io); + VS_REQUIRE(ps != nullptr); + PsInput input; + input.usage = Usage::Generic(); + input.row = 1; + input.mask = 3; + input.attr = 0; + input.flat = true; + VS_CHECK(ps->inputs == std::vector<PsInput>{input}); + VS_CHECK(ps->input_addr == 2); + VS_REQUIRE(ps->patches.size() == 1); + VS_CHECK(ps->patches[0].mrt == 1 && ps->patches[0].offset == 1); + const Buf patched = p.patched_code(); + VS_CHECK(std::equal(patched.begin(), patched.begin() + 4, p.code.begin())); + VS_CHECK((Buf(patched.begin() + 4, patched.begin() + 12) == Buf{0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3})); + VS_CHECK(std::equal(patched.begin() + 12, patched.end(), p.code.begin() + 12)); + + put32(blob, patch, 3); + VS_CHECK(fails(part({{KIND_NATIVE, xbch(blob)}}))); +} + +VS_TEST(finds_mesh_and_compute_programs) +{ + for (HwStage stage : {HwStage::Ms, HwStage::Cs}) { + const auto found = native_programs(part({{KIND_NATIVE, xbch(fssm({{stage, VS_CODE}}))}})); + VS_REQUIRE(found.size() == 1); + VS_CHECK(found[0].stage == stage); + } +} + +VS_TEST(reads_mesh_outputs_and_limits) +{ + Buf blob = fssm({{HwStage::Ms, VS_CODE}}); + const std::size_t e = stage_data_at(blob, HwStage::Ms); + // param0 is row 1 per vertex, param2 row 0 of the primitive signature. + set_bytes(blob, e + VS_OUTPUTS, {6, 1, 0, 0, 0, 0, 6, 0, 0x82, 0, 0, 0}); + put32(blob, e + VS_OUTPUT_COUNT, 2); + put32(blob, e + MS_CLIP_CNTL, 0x0040'000Fu); + // 128 lanes, 128 vertices, 64 primitives, 13 user SGPRs, triangles. + set_bytes(blob, e + MS_INFO, {0x80, 0, 0x80, 0, 0x40, 0, 13, 2}); + const std::size_t record = e - RECORD_SIZE; + put32(blob, record + RECORD_LDS, 16); + const auto found = native_programs(part({{KIND_NATIVE, xbch(blob)}})); + VS_REQUIRE(!found.empty()); + auto out = [](std::uint8_t row, std::uint8_t param) { + VsOutput o; + o.usage = Usage::Generic(); + o.row = row; + o.param = param; + return o; + }; + MeshIo want; + want.outputs = {out(1, 0), out(0, 0x82)}; + want.clip_cntl = 0x0040'000F; + want.threads = 128; + want.max_vertices = 128; + want.max_primitives = 64; + want.topology = 2; + want.lds_bytes = 16; + VS_CHECK(found[0].io == StageIo{want}); +} + +VS_TEST(mesh_stage_io_ignores_unused_vs_input_count) +{ + Buf blob = fssm({{HwStage::Ms, VS_CODE}}); + const std::size_t e = stage_data_at(blob, HwStage::Ms); + // Mesh stage data has no vertex inputs; E+0xc4 is unused by MS. + put32(blob, e + VS_INPUT_COUNT, 0xFFFF'FFFFu); + const auto found = native_programs(part({{KIND_NATIVE, xbch(blob)}})); + VS_REQUIRE(!found.empty()); + VS_CHECK(std::holds_alternative<MeshIo>(found[0].io)); +} + +VS_TEST(compute_dispatch_settings) +{ + // 5 user SGPRs, group id x and y, thread ids in v0-v1, 1 KiB LDS. + ComputeIo cs{0x1098A, {16, 16, 1}}; + VS_CHECK(cs.user_sgprs() == 5); + auto [ids, info] = cs.system_sgprs(); + VS_CHECK(ids[0] == std::optional<std::uint8_t>(std::uint8_t{5}) && ids[1] == std::optional<std::uint8_t>(std::uint8_t{6}) && !ids[2] && !info); + VS_CHECK(cs.thread_id_vgprs() == 2 && cs.lds_bytes() == 1024); + // 6 user SGPRs, all three group ids, v0-v2, no LDS. + cs = ComputeIo{0x138C, {8, 8, 1}}; + auto [ids2, info2] = cs.system_sgprs(); + VS_CHECK(ids2[0] == std::optional<std::uint8_t>(std::uint8_t{6}) && ids2[1] == std::optional<std::uint8_t>(std::uint8_t{7}) && + ids2[2] == std::optional<std::uint8_t>(std::uint8_t{8}) && !info2); + VS_CHECK(cs.thread_id_vgprs() == 3 && cs.lds_bytes() == 0); +} + +VS_TEST(initialized_sgprs_covers_user_system_and_scratch) +{ + VS_CHECK((ComputeIo{0x1098A, {16, 16, 1}}.initialized_sgprs() == 7)); + VS_CHECK((ComputeIo{0x78C, {8, 8, 1}}.initialized_sgprs() == 10)); + VS_CHECK((ComputeIo{0x78D, {8, 8, 1}}.initialized_sgprs() == 11)); +} + +VS_TEST(reads_every_native_blob) +{ + const Buf es = xbch(fssm({{HwStage::Es, VS_CODE}})); + const Buf vs = xbch(fssm({{HwStage::Vs, VS_CODE}})); + const Buf data = part({{0x12, Buf(16, 0)}, {KIND_NATIVE, es}, {KIND_NATIVE, vs}}); + std::vector<HwStage> stages; + for (const auto& p : native_programs(data)) stages.push_back(p.stage); + VS_CHECK((stages == std::vector<HwStage>{HwStage::Es, HwStage::Vs})); +} + +VS_TEST(pc_layout_has_none) +{ + VS_CHECK(native_programs(Buf(64, 0)).empty()); + VS_CHECK(native_programs(part({{0x0a, XBOP}})).empty()); +} + +VS_TEST(rejects_corrupt_blobs) +{ + const Buf good = xbch(fssm({{HwStage::Ls, VS_CODE}})); + auto corrupt = [&](std::size_t at, std::uint8_t byte) { + Buf blob = good; + blob[at] = byte; + return fails(part({{KIND_NATIVE, blob}})); + }; + VS_CHECK(corrupt(4, 9)); // unknown version + VS_CHECK(corrupt(16, 0xFF)); // stated size + VS_CHECK(corrupt(XBCH_HEADER + 2, 0xFF)); // zlib stream + VS_CHECK(fails(part({{KIND_NATIVE, Buf(good.begin(), good.begin() + 20)}}))); + + Buf bad_record = fssm({{HwStage::Ls, VS_CODE}}); + put64(bad_record, FSSM_HEADER + slot(HwStage::Ls), ~std::uint64_t{0}); + VS_CHECK(fails(part({{KIND_NATIVE, xbch(bad_record)}}))); +} + +VS_TEST(rejects_truncated_oversized_and_bad_checksum_xbch_streams) +{ + const Buf plain = fssm({{HwStage::Vs, VS_CODE}}); + const Buf good = xbch(plain); + VS_CHECK(detail::unpack(good) == plain); + auto unpack_fails = [](const Buf& b) { return catch_shader_error([&] { detail::unpack(b); }).has_value(); }; + + // Truncated zlib stream (drop last byte, update packed length). + Buf truncated(good.begin(), good.end() - 1); + put64(truncated, 8, truncated.size() - XBCH_HEADER); + VS_CHECK(unpack_fails(truncated)); + + // Stated unpacked size smaller than the inflated output. + Buf oversized = good; + put64(oversized, 16, plain.size() - 1); + VS_CHECK(unpack_fails(oversized)); + + // Stated unpacked size larger than the inflated output. + Buf underfilled = good; + put64(underfilled, 16, plain.size() + 1); + VS_CHECK(unpack_fails(underfilled)); + + // Corrupt Adler-32 trailer. + Buf bad_adler = good; + bad_adler.back() ^= 1; + VS_CHECK(unpack_fails(bad_adler)); +} + +VS_TEST_MAIN() diff --git a/tests/x2w_shader/vs_resource_test.cpp b/tests/x2w_shader/vs_resource_test.cpp new file mode 100644 index 0000000000..a7fe535fad --- /dev/null +++ b/tests/x2w_shader/vs_resource_test.cpp @@ -0,0 +1,1066 @@ +// Port of the upstream Rust shader tests in src/resource.rs. +#include "x2w_shader/resource.h" + +#include "resource_fixtures.h" +#include "vs_front_test.h" + +#include <algorithm> +#include <cstdint> +#include <cstdio> +#include <initializer_list> +#include <optional> +#include <span> +#include <string_view> +#include <utility> +#include <vector> + +using namespace x2w::vs; +using namespace x2w::vs::native; +using namespace x2w::vs::resource; +using fixtures::cmpx_waterfall; +using fixtures::WATERFALL_FETCHED_WAVE32; +using fixtures::WATERFALL_FETCHED_WAVE64; +using fixtures::WATERFALL_INDEXED_WAVE32; +using fixtures::WATERFALL_JOINED_BUFFER_WAVE32; +using fixtures::WATERFALL_JOINED_MIXED_WAVE32; +using fixtures::WATERFALL_JOINED_WAVE32; +using fixtures::WATERFALL_LOOPED_WAVE32; +using fixtures::WATERFALL_PICKED_WAVE32; +using ir::Program; +using Words = std::vector<std::uint32_t>; +using Scalar = std::vector<std::pair<Site, Address>>; + +namespace { + +constexpr std::uint32_t S_ENDPGM = 0xBF81'0000; + +std::vector<std::uint8_t> bytes(std::span<const std::uint32_t> words) +{ + std::vector<std::uint8_t> code; + for (std::uint32_t w : words) + for (int i = 0; i < 4; ++i) code.push_back(static_cast<std::uint8_t>(w >> (8 * i))); + return code; +} + +// Rust `[a, b, ..].concat()` of word slices. +Words concat(std::initializer_list<std::span<const std::uint32_t>> parts) +{ + Words w; + for (const auto& part : parts) w.insert(w.end(), part.begin(), part.end()); + return w; +} + +// `p` as one lane runs it, if it structures. +std::optional<structure::Structured> lanes(const Program& p) +{ + return try_shader([&] { return structure::structure(p); }); +} + +Resources track_words(const Words& words, const std::vector<RootParam>& layout, HwStage stage) +{ + const Program p = ir::build(bytes(words), false, 256); + const auto l = lanes(p); + return track(p, layout, stage, l ? &*l : nullptr); +} + +RootParam param(RootType root, std::uint8_t user_data, std::uint32_t sgprs) +{ + RootParam r; + r.root = root; + r.table_offset_dwords = 0; + r.sgprs = sgprs; + r.base_register = 0; + r.user_data = user_data; + r.slot = 0; + return r; +} + +Address at(std::size_t param, std::uint32_t offset) +{ + Address a; + a.param = param; + a.offset = offset; + a.dynamic = std::nullopt; + return a; +} + +// The address of the scalar access at `load` (Rust: `r.scalar.iter().find(|s| s.0 == load).unwrap().1`). +Address scalar_at(const Resources& r, Site load) +{ + const auto it = std::find_if(r.scalar.begin(), r.scalar.end(), [&](const auto& s) { return s.first == load; }); + VS_REQUIRE(it != r.scalar.end()); + return it->second; +} + +// Rust `ShaderError::Unsupported { offset, what }` (`offset` nullopt: `..`), `what` by content. +bool is_unsupported(const std::optional<ShaderError>& e, std::optional<std::size_t> offset, std::string_view what) +{ + if (!e) { + std::fprintf(stderr, "no error\n"); + return false; + } + const bool ok = e->kind == ShaderError::Kind::Unsupported && (!offset || e->offset == *offset) && + std::string_view(e->reason) == what; + if (!ok) std::fprintf(stderr, "%s\n", e->debug().c_str()); + return ok; +} + +std::size_t moves_anywhere(const Words& words); + +} // namespace + +VS_TEST(table_descriptors_are_loaded_from_their_range) +{ + const Resources r = track_words( + { + 0xBE82'0309, // s_mov_b32 s2, s9 + 0xBE89'0380, // s_mov_b32 s9, 0 + 0xBE83'0380, // s_mov_b32 s3, 0 + 0xF408'0204, + 0xFA00'0000, // s_load_dwordx4 s[8:11], s[8:9], null + 0xF40C'0001, + 0xFA00'0000, // s_load_dwordx8 s[0:7], s[2:3], null + 0xF080'0F08, + 0x0040'0002, // image_sample v[0:3], v[2:3], s[0:7], s[8:11] + S_ENDPGM, + }, + {param(RootType::Table(), 8, 1), param(RootType::Table(), 9, 1)}, HwStage::Ps); + VS_CHECK((r.scalar == Scalar{{{0, 3}, at(0, 0)}, {{0, 4}, at(1, 0)}})); + std::vector<std::pair<Role, Source>> roles; + for (const auto& d : r.descriptors) roles.emplace_back(d.role, d.source); + VS_CHECK((roles == std::vector<std::pair<Role, Source>>{ + {Role::Resource, Source::Loaded({0, 4}, 0)}, + {Role::Sampler, Source::Loaded({0, 3}, 0)}, + })); +} + +VS_TEST(root_descriptors_are_built_in_code) +{ + const Resources r = track_words( + { + 0x8801'FF0B, + 0x0010'0000, // s_or_b32 s1, s11, 0x100000 + 0xBE80'030A, // s_mov_b32 s0, s10 + 0xBE82'03C1, // s_mov_b32 s2, -1 + 0xBE83'03FF, + 0x1101'4FAC, // s_mov_b32 s3, 0x11014fac + 0xF430'0000, + 0xFA00'0000, // s_buffer_load_dwordx16 s[0:15], s[0:3], null + S_ENDPGM, + }, + {param(RootType::Descriptor(), 10, 2)}, HwStage::Vs); + VS_REQUIRE(!r.descriptors.empty()); + VS_CHECK((r.descriptors[0].source == Source::Built(at(0, 0), 0x10'0000, {UINT32_MAX, 0x1101'4FAC}))); + std::vector<std::pair<std::size_t, std::uint32_t>> params; + for (const auto& p : r.params) params.emplace_back(std::get<1>(p), std::get<2>(p)); + VS_CHECK((params == std::vector<std::pair<std::size_t, std::uint32_t>>{{0, 0}, {0, 1}})); +} + +VS_TEST(heap_indices_from_root_constants_in_a_merged_stage) +{ + // User data starts at s8: the constant (index 6) is s14, the heap + // (index 10) s18. + const Words code = { + 0x8F08'850E, // s_lshl_b32 s8, s14, 5 + 0xBE93'0380, // s_mov_b32 s19, 0 + 0xF408'0209, + 0x1000'0000, // s_load_dwordx4 s[8:11], s[18:19], s8 + 0xE000'2000, + 0x8002'0400, // buffer_load_format_x v4, v0, s[8:11], 0 idxen + S_ENDPGM, + }; + const Resources r = + track_words(code, {param(RootType::Constants(), 6, 1), param(RootType::ResourceHeap(), 10, 1)}, HwStage::Ms); + const auto found = std::find_if(r.params.begin(), r.params.end(), [](const auto& p) { return std::get<1>(p) == 0; }); + VS_REQUIRE(found != r.params.end()); + const ir::Value index = std::get<0>(*found); + VS_REQUIRE(!r.scalar.empty()); + VS_REQUIRE(r.scalar[0].second.dynamic.has_value()); + const ir::Value shift = *r.scalar[0].second.dynamic; + VS_CHECK(r.scalar[0].second.param == 1); + // The computed term is the shifted constant, not the constant itself. + VS_CHECK(shift != index); + VS_REQUIRE(!r.descriptors.empty()); + VS_CHECK((r.descriptors[0].source == Source::Loaded({0, 2}, 0))); + VS_CHECK(r.root_indexed_views.empty()); + RootParam table = param(RootType::Table(), 10, 1); + table.slot = 7; + const Resources indexed = track_words(code, {param(RootType::Constants(), 6, 1), table}, HwStage::Ms); + VS_CHECK((indexed.root_indexed_views == std::vector<RootIndexedView>{RootIndexedView{ + .table_slot = 7, + .constant_slot = 0, + .constant_dword = 0, + .byte_offset = 0, + .shift = 5, + }})); + const Resources nonconstant = track_words(code, {param(RootType::Table(), 6, 1), table}, HwStage::Ms); + VS_CHECK(nonconstant.root_indexed_views.empty()); +} + +VS_TEST(spilled_sgprs_are_followed_through_vgpr_lanes) +{ + const Resources r = track_words( + { + 0xD761'0000, + 0x0001'0609, // v_writelane_b32 v0, s9, 3 + 0xD760'0002, + 0x0001'0700, // v_readlane_b32 s2, v0, 3 + 0xBE83'0380, // s_mov_b32 s3, 0 + 0xF40C'0001, + 0xFA00'0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20 + S_ENDPGM, + }, + {param(RootType::Table(), 9, 1)}, HwStage::Ps); + VS_CHECK((r.scalar == Scalar{{{0, 3}, at(0, 0x20)}})); +} + +// A VGPR a wave reduction used is free again after it: from the first +// save on it holds parked scalars alone (an upscaler program parks a +// constant buffer's descriptor that way). +VS_TEST(a_vgpr_used_before_holds_spilled_sgprs_from_its_first_save) +{ + const Words before = { + 0x7E00'0281, // v_mov_b32 v0, 1 + 0x7E02'0300, // v_mov_b32 v1, v0 + }; + const Words park = { + 0xD761'0000, + 0x0001'0609, // v_writelane_b32 v0, s9, 3 + 0xD760'0002, + 0x0001'0700, // v_readlane_b32 s2, v0, 3 + 0xBE83'0380, // s_mov_b32 s3, 0 + }; + const Words load = { + 0xF40C'0001, + 0xFA00'0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20 + S_ENDPGM, + }; + const std::span<const std::uint32_t> b(before), k(park), l(load); + const Words words = concat({b, k, l}); + const Resources r = track_words(words, {param(RootType::Table(), 9, 1)}, HwStage::Ps); + VS_CHECK((r.scalar == Scalar{{{0, 5}, at(0, 0x20)}})); + // Still lane reads: a lane restored before it is saved, and a + // register with an ordinary use after the first save. + const Words restored_first = concat({b, k.subspan(2, 2), k.first(2), l}); + const Words used_after = concat({b, k, b.subspan(1), l}); + for (const Words& w : {restored_first, used_after}) { + const Program p = ir::build(bytes(w), true, 8); + std::size_t n = 0; + for (const auto& blk : p.blocks) + for (const auto& i : blk.insts) n += i.name() == "v_readlane_b32"; + VS_CHECK(n == 1); + } +} + +// Two lanes hold a pair (a lane mask, say) and later one of them a +// scalar, as in a water volume program that parks more than the lanes +// of one VGPR hold: the pair still moves as one. +VS_TEST(a_lane_spilled_to_again_later_does_not_split_an_earlier_pair) +{ + const Words pair = { + 0xD761'0000, + 0x0001'0004, // v_writelane_b32 v0, s4, 0 + 0xD761'0000, + 0x0001'0205, // v_writelane_b32 v0, s5, 1 + 0xBE84'0380, // s_mov_b32 s4, 0 + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xD760'0004, + 0x0001'0100, // v_readlane_b32 s4, v0, 0 + 0xD760'0005, + 0x0001'0300, // v_readlane_b32 s5, v0, 1 + }; + const Words scalar = { + 0xD761'0000, + 0x0001'0006, // v_writelane_b32 v0, s6, 0 + 0xBE86'0380, // s_mov_b32 s6, 0 + 0xD760'0006, + 0x0001'0100, // v_readlane_b32 s6, v0, 0 + S_ENDPGM, + }; + const auto moves = [](const Words& words) { + const Program p = ir::build(bytes(words), true, 8); + std::vector<std::string_view> names; + for (const auto& i : p.blocks[0].insts) names.push_back(i.name()); + VS_CHECK(std::none_of(names.begin(), names.end(), + [](std::string_view n) { return n.find("lane") != std::string_view::npos; })); + return static_cast<std::size_t>(std::count(names.begin(), names.end(), std::string_view("s_mov_b64"))); + }; + const std::span<const std::uint32_t> pr(pair), sc(scalar); + VS_CHECK(moves(concat({pr, sc})) == 2); + // A restore both saves reach keeps the lane one scalar. + const Words branch = {0xBF84'0002}; // s_cbranch_scc0 past the second save + const Words joined = concat({ + pr.first(4), + branch, + sc.first(2), + pr.subspan(4), + sc.subspan(2), + }); + VS_CHECK(moves_anywhere(joined) == 0); +} + +namespace { + +std::size_t moves_anywhere(const Words& words) +{ + const Program p = ir::build(bytes(words), true, 8); + std::size_t n = 0; + for (const auto& b : p.blocks) + for (const auto& i : b.insts) n += i.name() == "s_mov_b64"; + return n; +} + +} // namespace + +VS_TEST(descriptors_joined_by_control_flow_are_traced_per_edge) +{ + const Resources r = track_words( + { + 0xBE82'0309, // s_mov_b32 s2, s9 + 0xBE83'0380, // s_mov_b32 s3, 0 + 0xBF06'8001, // s_cmp_eq_u32 s1, 0 + 0xBF85'0003, // s_cbranch_scc1 -> 0x1c + 0xF408'0001, + 0xFA00'0000, // s_load_dwordx4 s[0:3], s[2:3], null + 0xBF82'0002, // s_branch -> 0x24 + 0xF408'0001, + 0xFA00'0010, // 0x1c: s_load_dwordx4 s[0:3], s[2:3], 0x10 + 0xF420'0100, + 0xFA00'0000, // 0x24: s_buffer_load_dword s4, s[0:3], null + S_ENDPGM, + }, + {param(RootType::Table(), 9, 1)}, HwStage::Ps); + VS_REQUIRE(!r.descriptors.empty()); + VS_REQUIRE(r.descriptors[0].source.kind == Source::Kind::Phi); + std::vector<std::uint32_t> offsets; + for (const Source& a : r.descriptors[0].source.args) { + VS_REQUIRE(a.kind == Source::Kind::Loaded); + offsets.push_back(scalar_at(r, a.load).offset); + } + VS_CHECK(offsets.size() == 2); + VS_CHECK(std::find(offsets.begin(), offsets.end(), 0u) != offsets.end() && + std::find(offsets.begin(), offsets.end(), 0x10u) != offsets.end()); +} + +// Two paths add an index to one table in the code and meet before one load; the join is the computed term, counted +// from the `s_getpc_b64`. +VS_TEST(two_paths_into_one_code_table_load) +{ + const Resources r = track_words( + { + 0xBE82'1F00, // 0x00: s_getpc_b64 s[2:3] + 0x8002'FF02, + 0x0000'0040, // s_add_u32 s2, s2, 0x40 + 0x8203'8003, // s_addc_u32 s3, s3, 0 + 0xBF06'8001, // 0x10: s_cmp_eq_u32 s1, 0 + 0xBF85'0005, // 0x14: s_cbranch_scc1 -> 0x2c + 0xD70F'0457, + 0x0000'054A, // 0x18: v_add_co_u32 v87, s4, v74, s2 + 0xD528'0458, + 0x0010'0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0xBF82'0004, // 0x28: s_branch -> 0x3c + 0xD70F'0457, + 0x0000'054B, // 0x2c: v_add_co_u32 v87, s4, v75, s2 + 0xD528'0458, + 0x0010'0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0xDC34'8000, + 0x577D'0057, // 0x3c: global_load_dwordx2 v[87:88], v[87:88], null + S_ENDPGM, + }, + {}, HwStage::Cs); + VS_REQUIRE(r.scalar.size() == 1); + const Address a = r.scalar[0].second; + VS_CHECK(a.param == CODE && a.offset == 0); + // The join is the computed term, the byte in the code. + VS_CHECK(a.dynamic.has_value()); +} + +// An address into a table in the code computed per lane and taken from +// the first lane (`avgLuminanceCompute` `ColorDownsample`): the per-lane +// sum carries the `s_getpc_b64` base, so the first-lane read is looked +// through and the lane's index is the computed term. (A first-lane read +// of an index alone stays the computed term itself; see +// `the_console_waterfall_over_a_first_lane_offset_is_one`.) +VS_TEST(a_code_table_address_taken_from_the_first_lane) +{ + const Resources r = track_words( + { + 0xBE82'1F00, // 0x00: s_getpc_b64 s[2:3] + 0xD70F'0457, + 0x0000'054A, // v_add_co_u32 v87, s4, v74, s2 + 0xD528'0458, + 0x0010'0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0x7E0C'0557, // v_readfirstlane_b32 s6, v87 + 0x7E0E'0558, // v_readfirstlane_b32 s7, v88 + 0xF400'0203, + 0xFA00'0000, // s_load_dword s8, s[6:7], 0x0 + S_ENDPGM, + }, + {}, HwStage::Cs); + VS_REQUIRE(r.scalar.size() == 1); + const Address a = r.scalar[0].second; + VS_CHECK(a.param == CODE && a.offset == 4); + // The lane's index is the computed term. + VS_CHECK(a.dynamic.has_value()); +} + +VS_TEST(a_descriptor_kept_per_lane_is_its_load_and_needs_no_waterfall) +{ + // The console compiler's way with a descriptor it joins per lane: + // the dwords go to VGPRs and come back from the first lane. Every + // lane holds the one load's dwords, so the descriptor is that load + // (`lane_copied`), and no waterfall is asked for. + Words words = { + 0xBE82'0309, // s_mov_b32 s2, s9 + 0xBE83'0380, // s_mov_b32 s3, 0 + 0xF40C'0001, + 0xFA00'0000, // s_load_dwordx8 s[0:7], s[2:3], null + }; + // v_mov_b32 v10.., s0..; v_readfirstlane_b32 s16.., v10.. + for (std::uint32_t k = 0; k < 8; ++k) words.push_back(0x7E00'0200 | ((10 + k) << 17) | k); + for (std::uint32_t k = 0; k < 8; ++k) words.push_back(0x7E00'0400 | ((16 + k) << 17) | (0x100 + 10 + k)); + words.insert(words.end(), { + 0xF000'1700, + 0x0004'0D06, // image_load v[13:15], v6, s[16:23] + S_ENDPGM, + }); + const Resources r = track_words(words, {param(RootType::Table(), 9, 1)}, HwStage::Ps); + const Site load = {0, 2}; + VS_CHECK((r.scalar == Scalar{{load, at(0, 0)}})); + std::vector<Source> sources; + for (const auto& d : r.descriptors) sources.push_back(d.source); + VS_CHECK((sources == std::vector<Source>{Source::Loaded(load, 0)})); + VS_CHECK((r.lane_copied == std::vector<Site>{load})); + VS_CHECK(r.waterfall == Waterfall{}); +} + +VS_TEST(loads_at_one_first_lane_offset_have_one_address) +{ + // Two loads of the table entry at the offset v4 holds, each with + // its own first-lane read, as the console compiler loads a + // descriptor again wherever it needs it: one address, by which + // lowering knows them for the same descriptor. + const Resources r = track_words( + { + 0xBE82'0309, // s_mov_b32 s2, s9 + 0xBE83'0380, // s_mov_b32 s3, 0 + 0x7E08'0504, // v_readfirstlane_b32 s4, v4 + 0xF40C'0201, + 0x0800'0000, // s_load_dwordx8 s[8:15], s[2:3], s4 + 0x7E0A'0504, // v_readfirstlane_b32 s5, v4 + 0xF40C'0401, + 0x0A00'0000, // s_load_dwordx8 s[16:23], s[2:3], s5 + 0xF000'1700, + 0x0004'0D06, // image_load v[13:15], v6, s[16:23] + S_ENDPGM, + }, + {param(RootType::Table(), 9, 1)}, HwStage::Ps); + VS_REQUIRE(r.scalar.size() == 2); + const Address a = r.scalar[0].second; + const Address b = r.scalar[1].second; + VS_CHECK(a == b); + VS_CHECK(a.param == 0 && a.offset == 0); + // The lane's offset is the computed term. + VS_CHECK(a.dynamic.has_value()); +} + +VS_TEST(descriptors_selected_by_scc_are_traced_per_outcome) +{ + // Two buffer descriptors loaded from the table at s9 and one + // picked with s_cselect_b64 per half, as the compiler makes a + // conditional choice of resources without a branch. + const Resources r = track_words( + { + 0xBE8C'0309, // s_mov_b32 s12, s9 + 0xBE8D'0380, // s_mov_b32 s13, 0 + 0xF408'0006, + 0xFA00'0000, // s_load_dwordx4 s[0:3], s[12:13], null + 0xF408'0106, + 0xFA00'0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10 + 0xBF06'800E, // s_cmp_eq_u32 s14, 0 + 0x8588'0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5] + 0x858A'0602, // s_cselect_b64 s[10:11], s[2:3], s[6:7] + 0xF420'0404, + 0xFA00'0000, // s_buffer_load_dword s16, s[8:11], null + S_ENDPGM, + }, + {param(RootType::Table(), 9, 1)}, HwStage::Ps); + VS_REQUIRE(!r.descriptors.empty()); + VS_REQUIRE(r.descriptors[0].source.kind == Source::Kind::Select); + const std::vector<Source>& args = r.descriptors[0].source.args; + // SCC set picks the first operand. + VS_CHECK((args == std::vector<Source>{ + Source::Loaded({0, 2}, 0), + Source::Loaded({0, 3}, 0), + })); + VS_CHECK((r.scalar == Scalar{{{0, 2}, at(0, 0)}, {{0, 3}, at(0, 0x10)}})); +} + +// An upscaler's byte accesses make a loaded buffer +// descriptor raw first (stride cleared, records times stride, bounds +// in bytes): the access reads the loaded descriptor. Any other change +// still fails. +VS_TEST(a_descriptor_made_raw_is_the_loaded_one) +{ + const auto words = [](std::uint32_t mask) -> std::vector<std::uint8_t> { + const Words w = { + 0xBE88'0304, // s_mov_b32 s8, s4 + 0xBE89'0380, // s_mov_b32 s9, 0 + 0xF408'0204, + 0xFA00'0160, // s_load_dwordx4 s[8:11], s[8:9], 0x160 + 0xBF8C'C07F, // s_waitcnt lgkmcnt(0) + 0x938C'FF09, + 0x000E'0010, // s_bfe_u32 s12, s9, 0x000e0010 + 0x848C'810C, // s_max_u32 s12, s12, 1 + 0x8709'FF09, + mask, // s_and_b32 s9, s9, mask + 0x870B'FF0B, + 0xCFFF'FFFF, // s_and_b32 s11, s11, 0xcfffffff + 0x930A'0C0A, // s_mul_i32 s10, s10, s12 + 0x880B'FF0B, + 0x3000'0000, // s_or_b32 s11, s11, 0x30000000 + 0xE078'1000, + 0x8002'0007, // buffer_store_dwordx4 v[0:3], v7, s[8:11], 0 offen + S_ENDPGM, + }; + return bytes(w); + }; + const auto run = [&](std::uint32_t mask) { + return catch_shader_error([&] { + const Program p = ir::build(words(mask), false, 256); + const std::vector<RootParam> layout = {param(RootType::Table(), 4, 1)}; + const auto l = lanes(p); + return track(p, layout, HwStage::Cs, l ? &*l : nullptr); + }); + }; + VS_CHECK(!run(0xC000'FFFF).has_value()); + VS_CHECK(is_unsupported(run(0xC000'FFFE), 0x3c, "a descriptor changed after loading")); +} + +// Construct immediate words from a bit mask and a wide literal move. +VS_TEST(sampler_words_from_bit_masks_and_wide_literals_are_constants) +{ + const Words w = { + 0xB010'0007, // s_movk_i32 s16, 7 + 0x9211'8583, // s_bfm_b32 s17, 3, 5 + 0xBE92'04FF, + 0x1234'5678, // s_mov_b64 s[18:19], 0x12345678 + S_ENDPGM, + }; + const std::vector<std::uint8_t> code = bytes(w); + const Program p = ir::build(code, false, 256); + const std::vector<RootParam> layout = {param(RootType::Table(), 4, 1)}; + const std::vector<resource::detail::Term> t = resource::detail::origins(p, layout, HwStage::Cs); + const ir::Block& block = p.blocks[0]; + const auto value = [&](std::size_t n, std::size_t k) { + const std::uint32_t v = block.insts.at(n).writes.at(k).second.n; + VS_REQUIRE(v < t.size()); + return t[v]; + }; + VS_CHECK(value(1, 0) == resource::detail::Term::Const(7u << 5)); + VS_CHECK(value(2, 0) == resource::detail::Term::Const(0x1234'5678)); + VS_CHECK(value(2, 1) == resource::detail::Term::Const(0)); +} + +VS_TEST(a_selection_that_mixes_two_descriptors_fails) +{ + // The high half picked from the first load whatever SCC is: when + // clear, the descriptor is half of one load and half of the other. + const Words w = { + 0xBE8C'0309, // s_mov_b32 s12, s9 + 0xBE8D'0380, // s_mov_b32 s13, 0 + 0xF408'0006, + 0xFA00'0000, // s_load_dwordx4 s[0:3], s[12:13], null + 0xF408'0106, + 0xFA00'0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10 + 0xBF06'800E, // s_cmp_eq_u32 s14, 0 + 0x8588'0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5] + 0x858A'0202, // s_cselect_b64 s[10:11], s[2:3], s[2:3] + 0xF420'0404, + 0xFA00'0000, // s_buffer_load_dword s16, s[8:11], null + S_ENDPGM, + }; + const std::vector<std::uint8_t> code = bytes(w); + const Program p = ir::build(code, false, 256); + const std::vector<RootParam> layout = {param(RootType::Table(), 9, 1)}; + const auto l = lanes(p); + const auto err = catch_shader_error([&] { return track(p, layout, HwStage::Ps, l ? &*l : nullptr); }); + VS_CHECK(is_unsupported(err, 36, "a descriptor changed after loading")); +} + +VS_TEST(untraceable_addresses_fail_with_a_reason) +{ + const Words w = {0xF408'0001, 0xFA00'0000, S_ENDPGM}; // s_load_dwordx4 s[0:3], s[2:3] + const std::vector<std::uint8_t> code = bytes(w); + const Program p = ir::build(code, false, 256); + const std::vector<RootParam> layout = {param(RootType::Table(), 9, 1)}; + const auto l = lanes(p); + const auto err = catch_shader_error([&] { return track(p, layout, HwStage::Ps, l ? &*l : nullptr); }); + VS_CHECK(is_unsupported(err, 0, "an address in an SGPR that is no root parameter")); +} + +// WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, +// WATERFALL_JOINED_WAVE32 and WATERFALL_INDEXED_WAVE32 are in resource_fixtures.h. + +namespace { + +Resources waterfall(const Words& words, bool wave64) +{ + const Program p = ir::build(bytes(words), wave64, 256); + const std::vector<RootParam> layout = {param(RootType::Table(), 0, 1), param(RootType::Table(), 1, 1)}; + const auto l = lanes(p); + return track(p, layout, HwStage::Cs, l ? &*l : nullptr); +} + +// The ShaderError waterfall(words, wave64) throws, if any. +std::optional<ShaderError> waterfall_error(const Words& words, bool wave64) +{ + return catch_shader_error([&] { return waterfall(words, wave64); }); +} + +} // namespace + +VS_TEST(the_console_waterfall_over_a_first_lane_offset_is_one) +{ + const Resources r = waterfall(WATERFALL_INDEXED_WAVE32, false); + const auto image = std::find_if(r.descriptors.begin(), r.descriptors.end(), + [](const Descriptor& d) { return d.role == Role::Resource; }); + VS_REQUIRE(image != r.descriptors.end()); + VS_REQUIRE(image->source.kind == Source::Kind::Loaded && image->source.first == 0); + const Site load = image->source.load; + const Address address = scalar_at(r, load); + VS_CHECK(address.dynamic.has_value()); + VS_CHECK(r.waterfall.compares.size() == 1); + VS_CHECK(r.waterfall.reads.size() == 1); + VS_CHECK((r.waterfall.loads == std::vector<Site>{load})); +} + +// WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_LOOPED_WAVE32 and WATERFALL_JOINED_BUFFER_WAVE32 are in +// resource_fixtures.h; the `waterfall` helper that follows them in Rust is above. + +VS_TEST(descriptors_read_from_the_first_lane_of_per_lane_loads_are_traced_to_them) +{ + const std::pair<const Words*, bool> cases[] = { + {&WATERFALL_FETCHED_WAVE32, false}, + {&WATERFALL_FETCHED_WAVE64, true}, + }; + for (const auto& [words, wave64] : cases) { + const Resources r = waterfall(*words, wave64); + const auto image = std::find_if(r.descriptors.begin(), r.descriptors.end(), + [](const Descriptor& d) { return d.role == Role::Resource; }); + VS_REQUIRE(image != r.descriptors.end()); + VS_REQUIRE(image->source.kind == Source::Kind::Fetched && image->source.first == 0); + const Site load = image->source.load; + // The first of the two loads: entry v0 * 32 of the table at s0. + const Address a = scalar_at(r, load); + VS_CHECK(a.param == 0 && a.offset == 0); + VS_CHECK(a.dynamic.has_value()); + // The sampler is the same for every lane. + const auto sampler = std::find_if(r.descriptors.begin(), r.descriptors.end(), + [](const Descriptor& d) { return d.role == Role::Sampler; }); + VS_REQUIRE(sampler != r.descriptors.end()); + VS_CHECK(sampler->source.kind == Source::Kind::Loaded && sampler->source.first == 0); + // Four 64-bit compares of the first lane's dwords with the lane's + // own; the eight reads become the lane's own dwords. + VS_CHECK(r.waterfall.compares.size() == 4); + VS_CHECK(r.waterfall.reads.size() == 8); + } +} + +VS_TEST(descriptors_read_from_the_first_lane_of_a_per_lane_choice_are_traced_per_lane) +{ + const Resources r = waterfall(WATERFALL_PICKED_WAVE32, false); + VS_REQUIRE(!r.descriptors.empty()); + const Descriptor& image = r.descriptors[0]; + VS_REQUIRE(image.source.kind == Source::Kind::Lanes); + // Lanes with their bit set take the first load (offset 0), the + // others the second (0x20). + std::vector<std::uint32_t> offsets; + for (const Source& a : image.source.args) { + VS_REQUIRE(a.kind == Source::Kind::Loaded && a.first == 0); + offsets.push_back(scalar_at(r, a.load).offset); + } + VS_CHECK((offsets == std::vector<std::uint32_t>{0, 0x20})); + VS_CHECK(r.waterfall.compares.size() == 4); +} + +VS_TEST(a_first_lane_read_outside_a_loop_is_no_waterfall) +{ + // The waterfall without its back edge: the s_cbranch_execnz is an + // s_nop, so lanes the first one does not match never get a pass. + Words words = WATERFALL_FETCHED_WAVE32; + const auto back = std::find(words.begin(), words.end(), 0xBF89'FFE6u); + VS_REQUIRE(back != words.end()); + *back = 0xBF80'0000; + const auto err = waterfall_error(words, false); + VS_CHECK(is_unsupported(err, std::nullopt, "a descriptor read from the first lane outside a waterfall loop")); +} + +namespace { + +// Why resource tracking refuses `words`. +std::string_view refusal(const Words& words, bool wave64) +{ + const auto err = waterfall_error(words, wave64); + if (err && err->kind != ShaderError::Kind::Unsupported) + std::fprintf(stderr, "not refused: %s\n", err->debug().c_str()); + // Not refused otherwise. + VS_REQUIRE(err.has_value() && err->kind == ShaderError::Kind::Unsupported); + return err->reason; +} + +constexpr std::string_view NO_LOOP = "a descriptor read from the first lane outside a waterfall loop"; +constexpr std::string_view NOT_SELECTED = "a waterfall loop whose compares do not select the access's lanes"; +constexpr std::string_view BAD_RETRY = "a waterfall loop whose retry does not keep the lanes still waiting"; +constexpr std::string_view SPLIT = "a waterfall loop nested in another or split over blocks"; + +// The index of `word` in `words`. +std::size_t word_at(const Words& words, std::uint32_t word) +{ + const auto it = std::find(words.begin(), words.end(), word); + VS_REQUIRE(it != words.end()); + return static_cast<std::size_t>(it - words.begin()); +} + +} // namespace + +VS_TEST(a_first_lane_read_without_its_compare_is_no_waterfall) +{ + // The loop without the compare of dwords 0 and 1: nothing makes + // the first lane's dwords the lane's own there. + Words words = WATERFALL_FETCHED_WAVE32; + const std::size_t cmp = word_at(words, 0x0002'080C); + words[cmp - 1] = 0xBF80'0000; + words[cmp] = 0xBF80'0000; + VS_CHECK(refusal(words, false) == NOT_SELECTED); +} + +VS_TEST(a_compare_that_does_not_mask_the_access_is_no_waterfall) +{ + // The compares are all there, but their result never narrows EXEC: + // every lane samples with the first lane's descriptor (reported by + // ifBars on upstream PR #566). + Words words = WATERFALL_JOINED_WAVE32; + const std::size_t save = word_at(words, 0xBE95'3C15); + words[save] = 0xBE95'037E; // s_mov_b32 s21, exec_lo + VS_CHECK(refusal(words, false) == NOT_SELECTED); +} + +VS_TEST(an_access_under_a_further_mask_is_no_waterfall) +{ + // The access runs for the matching lanes that VCC also holds, yet + // the retry removes every matching lane. + Words words = WATERFALL_JOINED_WAVE32; + const std::size_t nop = word_at(words, 0xBE95'3C15) + 1; + VS_REQUIRE(nop < words.size()); + VS_CHECK(words[nop] == 0xBF80'0000); + words[nop] = 0x877E'6A7E; // s_and_b32 exec_lo, exec_lo, vcc_lo + VS_CHECK(refusal(words, false) == NOT_SELECTED); +} + +VS_TEST(a_loop_that_drops_unmatched_lanes_is_no_waterfall) +{ + Words words = WATERFALL_JOINED_WAVE32; + const std::size_t retry = word_at(words, 0x897E'157E); + words[retry] = 0xBEFE'0380; // s_mov_b32 exec_lo, 0 + VS_CHECK(refusal(words, false) == BAD_RETRY); +} + +VS_TEST(a_retry_that_keeps_other_lanes_than_those_waiting_is_no_waterfall) +{ + // The retry keeps the lanes of VCC that did not just sample, not + // the waiting ones: lanes 16 and up never sample on the console. + Words words = WATERFALL_JOINED_WAVE32; + const std::size_t retry = word_at(words, 0x897E'157E); + words[retry] = 0x8A7E'7E6A; // s_andn2_b32 exec_lo, vcc_lo, exec_lo + VS_CHECK(refusal(words, false) == BAD_RETRY); +} + +VS_TEST(a_wave64_retry_of_one_half_is_no_waterfall) +{ + // Only the low half of EXEC loses the lanes just served. + Words words = WATERFALL_FETCHED_WAVE64; + const std::size_t retry = word_at(words, 0x89FE'167E); + words[retry] = 0x897E'167E; // s_xor_b32 exec_lo, exec_lo, s22 + VS_CHECK(refusal(words, true) == BAD_RETRY); +} + +VS_TEST(a_descriptor_used_after_exec_is_restored_is_no_waterfall) +{ + Words words = WATERFALL_JOINED_WAVE32; + const std::size_t sample = word_at(words, 0xF09C'0F08); + const std::size_t restore = word_at(words, 0xBEFE'0317); + const Words image = {words[sample], words[sample + 1]}; + std::fill(words.begin() + static_cast<std::ptrdiff_t>(sample), + words.begin() + static_cast<std::ptrdiff_t>(sample + 2), 0xBF80'0000u); // Keep the branch offsets. + words.insert(words.begin() + static_cast<std::ptrdiff_t>(restore + 1), image.begin(), image.end()); + VS_CHECK(refusal(words, false) == NO_LOOP); +} + +VS_TEST(a_wave64_access_with_exec_hi_overwritten_is_no_waterfall) +{ + Words words = WATERFALL_FETCHED_WAVE64; + const std::size_t save = word_at(words, 0xBE96'2416); + words[save + 1] = 0xBEFF'03C1; // s_mov_b32 exec_hi, -1 + VS_CHECK(refusal(words, true) == NOT_SELECTED); +} + +// cmpx_waterfall is in resource_fixtures.h. + +VS_TEST(a_waterfall_narrowed_by_v_cmpx_is_one) +{ + for (const bool wave64 : {false, true}) { + for (const bool folded : {false, true}) { + const Words words = cmpx_waterfall(wave64, folded); + std::optional<Resources> r; + const auto err = catch_shader_error([&] { r = waterfall(words, wave64); }); + if (err) std::fprintf(stderr, "wave64 %d folded %d: %s\n", wave64, folded, err->debug().c_str()); + VS_REQUIRE(r.has_value()); + if (r->waterfall.compares.size() != 4 || r->waterfall.reads.size() != 8) + std::fprintf(stderr, "%d %d\n", wave64, folded); + VS_CHECK(r->waterfall.compares.size() == 4); + VS_CHECK(r->waterfall.reads.size() == 8); + } + } +} + +VS_TEST(a_v_cmpx_waterfall_whose_retry_drops_lanes_is_none) +{ + Words words = cmpx_waterfall(false, false); + const std::size_t retry = word_at(words, 0x8A15'7E15); + words[retry] = 0x8A15'7E6A; // s_andn2_b32 s21, vcc_lo, exec_lo + VS_CHECK(refusal(words, false) == BAD_RETRY); +} + +VS_TEST(a_waterfall_nested_in_another_is_refused_by_name) +{ + // An image whose resource and sampler are both per lane, with one + // loop per operand, the one for the sampler inside the one for the + // resource (what the SelectionDAG legalisation in LLVM would give). + // The console gives each lane its own pair. Refused for now: the + // access of the inner loop reads the first-lane dwords of the outer + // loop, which another block holds. + const Words words = { + 0xBE84'0300, // s_mov_b32 s4, s0 + 0xBE85'0380, // s_mov_b32 s5, 0 + 0xBE86'0301, // s_mov_b32 s6, s1 + 0xBE87'0380, // s_mov_b32 s7, 0 + 0xF408'0A02, + 0xFA00'0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04'0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06'0302, // v_mov_b32 v3, v2 + 0x3420'0082, // v_lshlrev_b32 v16, 2, v0 + 0x3602'0081, // v_and_b32 v1, 1, v0 + 0x3402'0285, // v_lshlrev_b32 v1, 5, v1 + 0x3622'0080, // v_and_b32 v17, 0, v0 + 0x3422'2284, // v_lshlrev_b32 v17, 4, v17 + 0xDC38'8000, + 0x0404'0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38'8010, + 0x0804'0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xDC38'8000, + 0x1406'0011, // global_load_dwordx4 v[20:23], v17, s[6:7] + 0xBF8C'0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94'037E, // s_mov_b32 s20, exec_lo + // L1, the loop over the resource: + 0x7E18'0504, // v_readfirstlane_b32 s12, v4 + 0x7E1A'0505, + 0x7E1C'0506, + 0x7E1E'0507, + 0x7E20'0508, + 0x7E22'0509, + 0x7E24'050A, + 0x7E26'050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2'0015, + 0x0002'080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2'0016, + 0x0002'0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xD4E2'0016, + 0x0002'1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xD4E2'0016, + 0x0002'1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715'1615, // s_and_b32 s21, s21, s22 + 0xBE95'3C15, // s_and_saveexec_b32 s21, s21 + 0xBE9A'037E, // s_mov_b32 s26, exec_lo + // L2, the loop over the sampler: + 0x7E10'0514, // v_readfirstlane_b32 s8, v20 + 0x7E12'0515, // v_readfirstlane_b32 s9, v21 + 0x7E14'0516, // v_readfirstlane_b32 s10, v22 + 0x7E16'0517, // v_readfirstlane_b32 s11, v23 + 0xD4E2'0018, + 0x0002'2808, // v_cmp_eq_u64_e64 s24, s[8:9], v[20:21] + 0xD4E2'0019, + 0x0002'2C0A, // v_cmp_eq_u64_e64 s25, s[10:11], v[22:23] + 0x8718'1918, // s_and_b32 s24, s24, s25 + 0xBE98'3C18, // s_and_saveexec_b32 s24, s24 + 0xF09C'0F08, + 0x0043'0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] + 0x897E'187E, // s_xor_b32 exec_lo, exec_lo, s24 + 0xBF89'FFF2, // s_cbranch_execnz L2 + 0xBEFE'031A, // s_mov_b32 exec_lo, s26 + 0x897E'157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89'FFDA, // s_cbranch_execnz L1 + 0xBEFE'0314, // s_mov_b32 exec_lo, s20 + 0xE070'1000, + 0x800A'0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81'0000, // s_endpgm + }; + VS_CHECK(refusal(words, false) == SPLIT); +} + +VS_TEST(descriptors_read_from_the_first_lane_of_lds_fail_naming_it) +{ + // The waterfall over descriptors each lane read from LDS: + // ds_read_b128 v[4:7], v1 and ds_read_b128 v[8:11], v1 offset:16 + // in place of the global loads. + Words words = WATERFALL_FETCHED_WAVE32; + const Words lds = {0xDBFC'0000, 0x0400'0001, 0xDBFC'0010, 0x0800'0001}; + std::copy(lds.begin(), lds.end(), words.begin() + 5); + const auto err = waterfall_error(words, false); + VS_CHECK(is_unsupported(err, std::nullopt, "a descriptor read from the first lane of an LDS read")); +} + +namespace { + +// The block of `p` at byte `offset`. +std::size_t block_at(const Words& words, std::size_t offset) +{ + const Program p = ir::build(bytes(words), false, 256); + const auto it = std::find_if(p.blocks.begin(), p.blocks.end(), [&](const ir::Block& b) { return b.offset == offset; }); + VS_REQUIRE(it != p.blocks.end()); + return static_cast<std::size_t>(it - p.blocks.begin()); +} + +// The table offset of what the scalar load of `s` reads. +std::uint32_t table_offset(const Resources& r, const Source& s) +{ + VS_REQUIRE(s.kind == Source::Kind::Loaded && s.first == 0); + return scalar_at(r, s.load).offset; +} + +} // namespace + +VS_TEST(descriptors_read_from_the_first_lane_of_an_if_else_join_are_traced_per_path) +{ + const Words& words = WATERFALL_JOINED_WAVE32; + const Resources r = waterfall(words, false); + const auto image = std::find_if(r.descriptors.begin(), r.descriptors.end(), + [](const Descriptor& d) { return d.source.kind == Source::Kind::LanePhi; }); + VS_REQUIRE(image != r.descriptors.end()); + // The join after the else arm: lanes that ran it (lanes from 16 on) + // take the second entry (0x20); the others come through the flow + // block, whose join gives lanes that ran the then arm the first one + // (0). No lane that skipped the then arm comes that way, so the + // dwords they held before (the inputs) are not traced. + VS_REQUIRE(image->source.kind == Source::Kind::LanePhi); + { + const std::size_t block = image->source.block; + const auto& args = image->source.lane_args; + VS_CHECK(block == block_at(words, 0x9c)); + VS_REQUIRE(args.size() == 2 && args[0].has_value() && args[1].has_value()); + const Source& flow = *args[0]; + const Source& other = *args[1]; + VS_CHECK(table_offset(r, other) == 0x20); + VS_REQUIRE(flow.kind == Source::Kind::LanePhi); + VS_CHECK(flow.block == block_at(words, 0x70)); + const auto& flow_args = flow.lane_args; + VS_REQUIRE(flow_args.size() == 2 && !flow_args[0].has_value() && flow_args[1].has_value()); + const Source& then = *flow_args[1]; + VS_CHECK(table_offset(r, then) == 0); + } + // The loop's compares are of the joined dwords; still recognised. + VS_CHECK(r.waterfall.compares.size() == 4); + VS_CHECK(r.waterfall.reads.size() == 8); + // Without the lanes' paths the join is refused. + const std::vector<std::uint8_t> code = bytes(words); + const Program p = ir::build(code, false, 256); + const std::vector<RootParam> layout = {param(RootType::Table(), 0, 1), param(RootType::Table(), 1, 1)}; + const auto err = catch_shader_error([&] { return track(p, layout, HwStage::Cs, nullptr); }); + VS_CHECK(is_unsupported(err, std::nullopt, + "a descriptor read from the first lane of a phi, without the lanes' paths")); +} + +VS_TEST(descriptors_joined_from_a_per_lane_load_and_a_per_lane_choice_are_traced_per_path) +{ + const Words& words = WATERFALL_JOINED_MIXED_WAVE32; + const Resources r = waterfall(words, false); + const auto image = std::find_if(r.descriptors.begin(), r.descriptors.end(), + [](const Descriptor& d) { return d.source.kind == Source::Kind::LanePhi; }); + VS_REQUIRE(image != r.descriptors.end()); + VS_REQUIRE(image->source.kind == Source::Kind::LanePhi); + const std::size_t block = image->source.block; + const auto& args = image->source.lane_args; + VS_CHECK(block == block_at(words, 0xb8)); + VS_REQUIRE(args.size() == 2 && args[0].has_value() && args[1].has_value()); + VS_REQUIRE(args[0]->kind == Source::Kind::LanePhi && args[1]->kind == Source::Kind::Lanes); + const auto& flow = args[0]->lane_args; + const std::vector<Source>& picked = args[1]->args; + // The then arm loads each lane's entry from the table at s0. + VS_REQUIRE(flow.size() == 2 && !flow[0].has_value() && flow[1].has_value()); + VS_REQUIRE(flow[1]->kind == Source::Kind::Fetched && flow[1]->first == 0); + const Site load = flow[1]->load; + const Address a = scalar_at(r, load); + VS_CHECK(a.param == 0 && a.offset == 0); + VS_CHECK(a.dynamic.has_value()); + // The else arm picks the first entry where vcc is set. + std::vector<std::uint32_t> offsets; + for (const Source& s : picked) offsets.push_back(table_offset(r, s)); + VS_CHECK((offsets == std::vector<std::uint32_t>{0, 0x20})); + VS_CHECK(r.waterfall.compares.size() == 4); +} + +VS_TEST(a_descriptor_read_from_the_first_lane_of_a_loop_phi_fails_naming_it) +{ + const auto err = waterfall_error(WATERFALL_LOOPED_WAVE32, false); + VS_CHECK(is_unsupported(err, std::nullopt, "a descriptor read from the first lane of a phi at a loop header")); +} + +VS_TEST(a_per_lane_descriptor_some_lanes_do_not_write_fails) +{ + // The else arm of WATERFALL_JOINED_WAVE32 not skipped (its + // s_cbranch_execz an s_nop): it runs with EXEC clear in the lanes + // of the then arm, which keep the first entry; the second is not + // every lane's. + Words words = WATERFALL_JOINED_WAVE32; + const auto skip = std::find(words.rbegin(), words.rend(), 0xBF88'0008u); + VS_REQUIRE(skip != words.rend()); + *skip = 0xBF80'0000; + const auto err = waterfall_error(words, false); + VS_CHECK(is_unsupported(err, std::nullopt, + "a per-lane descriptor written where some lanes may keep the old one")); +} + +VS_TEST(a_buffer_descriptor_joined_per_lane_is_traced_on_the_paths_of_lanes_that_load) +{ + const Words& words = WATERFALL_JOINED_BUFFER_WAVE32; + const Resources r = waterfall(words, false); + const auto buffer = std::find_if(r.descriptors.begin(), r.descriptors.end(), + [](const Descriptor& d) { return d.source.kind == Source::Kind::LanePhi; }); + VS_REQUIRE(buffer != r.descriptors.end()); + // The outer join: lanes from the else arm's inner join, or (below + // 16) through the flow block. + VS_REQUIRE(buffer->source.kind == Source::Kind::LanePhi); + const std::size_t block = buffer->source.block; + const auto& args = buffer->source.lane_args; + VS_CHECK(block == block_at(words, 0x78)); + VS_REQUIRE(args.size() == 2 && args[0].has_value() && args[1].has_value()); + VS_REQUIRE(args[0]->kind == Source::Kind::LanePhi && args[1]->kind == Source::Kind::LanePhi); + const auto& flow = args[0]->lane_args; + const std::size_t inner = args[1]->block; + const auto& nested = args[1]->lane_args; + VS_REQUIRE(flow.size() == 2 && !flow[0].has_value() && flow[1].has_value()); + const Source& then = *flow[1]; + VS_CHECK(table_offset(r, then) == 0); + // Lanes from 24 on skip the inner arm and keep the inputs, but do + // not load: that edge is not traced. + VS_CHECK(inner == block_at(words, 0x74)); + VS_REQUIRE(nested.size() == 2 && !nested[0].has_value() && nested[1].has_value()); + const Source& other = *nested[1]; + VS_CHECK(table_offset(r, other) == 0x20); + VS_CHECK(r.waterfall.compares.size() == 2); + VS_CHECK(r.waterfall.reads.size() == 4); +} + +VS_TEST_MAIN() diff --git a/tests/x2w_shader/vs_spill_test.cpp b/tests/x2w_shader/vs_spill_test.cpp new file mode 100644 index 0000000000..f3f18c5880 --- /dev/null +++ b/tests/x2w_shader/vs_spill_test.cpp @@ -0,0 +1,98 @@ +// Port of the upstream Rust shader tests in src/spill.rs. +#include "x2w_shader/spill.h" + +#include "vs_front_test.h" + +#include <algorithm> + +using namespace x2w::vs; +using namespace x2w::vs::native; +using ir::Reg; + +namespace { + +RootParam param(RootType root, std::uint8_t user_data, std::uint32_t sgprs, std::uint8_t slot) +{ + RootParam r; + r.root = root; + r.table_offset_dwords = 0; + r.sgprs = sgprs; + r.base_register = 0; + r.user_data = user_data; + r.slot = slot; + return r; +} + +// A compute program with `registers` user SGPRs and the group id after them. +NativeProgram native_program(const std::vector<std::uint32_t>& words, std::uint32_t registers, + std::vector<RootParam> layout) +{ + NativeProgram n; + n.stage = HwStage::Cs; + n.wave64 = false; + n.vgprs = 256; + n.layout = std::move(layout); + n.io = ComputeIo{(registers << 1) | (1u << 7), {1, 1, 1}}; + for (std::uint32_t w : words) + for (int i = 0; i < 4; ++i) n.code.push_back(static_cast<std::uint8_t>(w >> (8 * i))); + return n; +} + +// s_and_b32 s3, s1, 0xff; s_mov_b32 s2, s0; s_load_dword s5, s[2:3], 0x10; +// s_load_dwordx2 s[0:1], s[2:3], 0; s_endpgm. +const std::vector<std::uint32_t> TABLE = { + 0x8703'FF01, 0x0000'00FF, 0xBE82'0300, 0xF400'0141, 0xFA00'0010, 0xF404'0001, 0xFA00'0000, 0xBF81'0000, +}; + +std::size_t loads(const ir::Program& p) +{ + std::size_t n = 0; + for (const auto& b : p.blocks) + for (const auto& i : b.insts) + if (i.name().starts_with("s_load_")) ++n; + return n; +} + +} // namespace + +VS_TEST(loads_of_the_spilled_table_become_entry_registers) +{ + const NativeProgram n = native_program(TABLE, 4, + {param(RootType::Descriptor(), 16, 2, 0), param(RootType::Descriptor(), 18, 2, 1), + param(RootType::Constants(), 20, 16, 2)}); + ir::Program p = ir::build(n.code, false, 256); + VS_CHECK(spill::user_data(p, n) == 2); + VS_CHECK(loads(p) == 0); + // The pointer is gone with the loads; byte 0x10 is index 20, the first root constant, and bytes + // 0-7 are the first root view. + std::vector<Reg> regs; + for (const auto& i : p.inputs) regs.push_back(i.first); + std::sort(regs.begin(), regs.end()); + VS_CHECK((regs == std::vector<Reg>{Reg::S(16), Reg::S(17), Reg::S(20)})); +} + +VS_TEST(parameters_in_registers_are_left_alone) +{ + // The same code where s0 and s1 are a root view the layout declares. + const NativeProgram n = native_program(TABLE, 6, {param(RootType::Descriptor(), 0, 2, 0)}); + ir::Program p = ir::build(n.code, false, 256); + const ir::Program before = p; + VS_CHECK(spill::user_data(p, n) == 0); + VS_CHECK(p == before); +} + +VS_TEST(a_used_dword_no_parameter_declares_keeps_its_load) +{ + // As above with `s_mov_b32 s6, s5` before the end: the dword at byte 0x10 (index 20) is read, + // and here nothing declares it. + std::vector<std::uint32_t> words = TABLE; + words.insert(words.begin() + 7, 0xBE86'0305); + const NativeProgram n = native_program(words, 4, {param(RootType::Descriptor(), 16, 2, 0)}); + ir::Program p = ir::build(n.code, false, 256); + VS_CHECK(spill::user_data(p, n) == 1); + VS_CHECK(loads(p) == 1); + // The pointer is still read, by the load that stays. + VS_CHECK(std::any_of(p.inputs.begin(), p.inputs.end(), [](const auto& i) { return i.first == Reg::S(0); })); +} + +VS_TEST_MAIN() diff --git a/tests/x2w_shader/vs_structure_test.cpp b/tests/x2w_shader/vs_structure_test.cpp new file mode 100644 index 0000000000..866d215fb1 --- /dev/null +++ b/tests/x2w_shader/vs_structure_test.cpp @@ -0,0 +1,454 @@ +// Port of the upstream Rust shader tests in src/structure.rs. +#include "x2w_shader/structure.h" + +#include "vs_front_test.h" + +#include <algorithm> +#include <limits> + +using namespace x2w::vs; +using namespace x2w::vs::structure; +using ir::Program; +using ir::Reg; + +namespace { + +constexpr std::uint32_t S_ENDPGM = 0xBF81'0000; + +Program build(const std::vector<std::uint32_t>& words, bool wave64) +{ + std::vector<std::uint8_t> code; + for (std::uint32_t w : words) + for (int i = 0; i < 4; ++i) code.push_back(static_cast<std::uint8_t>(w >> (8 * i))); + return ir::build(code, wave64, 256); +} + +std::size_t guarded(const Structured& s) +{ + std::size_t n = 0; + for (const auto& row : s.guards) + for (const auto& g : row) n += g.has_value(); + return n; +} + +using Node = std::optional<std::tuple<Atom, Bool, Bool>>; +Node node(Atom a, Bool lo, Bool hi) { return std::tuple<Atom, Bool, Bool>{a, lo, hi}; } + +bool support_is(const Structured& s, Bool b, Atom::Kind kind) +{ + const auto sup = s.bools.support(b); + return sup.size() == 1 && sup[0].kind == kind; +} + +Node mask_node(const Structured& s, ir::Value v) +{ + const auto it = s.masks.find(v); + if (it == s.masks.end()) return std::nullopt; + return s.bools.node(it->second); +} + +const ir::Phi* phi_of(const Program& p, Reg reg) +{ + for (const auto& b : p.blocks) + for (const auto& phi : b.phis) + if (phi.reg == reg) return φ + return nullptr; +} + +bool contains(const std::vector<Bool>& v, Bool b) { return std::find(v.begin(), v.end(), b) != v.end(); } + +// The search of Bools::meet with every case split made anew, as it was before Meets. +bool meet_anew(const Bools& b, std::vector<std::pair<Bool, bool>> all, std::size_t& budget) +{ + for (const auto& [x, holds] : all) + if (x == (holds ? Bool::False : Bool::True)) return false; + std::erase_if(all, [](const auto& e) { return e.first == Bool::False || e.first == Bool::True; }); + if (all.empty() || budget == 0) return true; + budget -= 1; + std::uint32_t v = std::numeric_limits<std::uint32_t>::max(); + for (const auto& e : all) v = std::min(v, b.top(e.first)); + for (const bool value : {false, true}) { + std::vector<std::pair<Bool, bool>> next; + for (const auto& [x, holds] : all) { + const auto [lo, hi] = b.split(x, v); + next.push_back({value ? hi : lo, holds}); + } + if (meet_anew(b, next, budget)) return true; + } + return false; +} + +} // namespace + +VS_TEST(a_search_that_remembers_answers_as_one_made_anew) +{ + // Functions of 12 variables put together at random, and conditions of two to five of them + // (repeats and constants among them), under budgets that run out early, late and never: the + // answer, and where no lane is found the budget left, are those of the search that remembers + // nothing; with what one Meets gathered over all of them, and with an empty one. + Bools b; + std::uint64_t state = 0x9E37'79B9'7F4A'7C15ull; + auto random = [&state](std::size_t n) { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + return static_cast<std::size_t>(state % static_cast<std::uint64_t>(n)); + }; + std::vector<Bool> f; + for (std::uint64_t i = 0; i < 12; ++i) f.push_back(b.atom(Atom::Constant(i + 2), 0)); + f.push_back(Bool::False); + f.push_back(Bool::True); + for (int k = 0; k < 120; ++k) { + const Bool x = f[random(f.size())]; + const Bool y = f[random(f.size())]; + Bool made; + switch (random(4)) { + case 0: made = b.and_(x, y); break; + case 1: made = b.or_(x, y); break; + case 2: made = b.xor_(x, y); break; + default: made = b.not_(x); break; + } + f.push_back(made); + } + Meets seen; + int none = 0, some = 0, gave_up = 0; + for (int k = 0; k < 1500; ++k) { + const std::size_t count = 2 + random(4); + std::vector<std::pair<Bool, bool>> all; + for (std::size_t j = 0; j < count; ++j) { + const Bool x = f[random(f.size())]; + const bool holds = random(2) == 0; + all.push_back({x, holds}); + } + for (const std::size_t budget : {std::size_t{0}, std::size_t{1}, std::size_t{2}, std::size_t{3}, std::size_t{5}, + std::size_t{9}, std::size_t{20}, std::size_t{60}, std::size_t{250}, + std::size_t{1000}, MAX_MEET}) { + std::size_t left = budget; + const bool anew = meet_anew(b, all, left); + for (const bool fresh : {false, true}) { + Meets empty; + Meets& use = fresh ? empty : seen; + std::vector<std::uint32_t> work; + for (const auto& [x, holds] : all) work.push_back((x.n << 1) | (holds ? 1u : 0u)); + std::size_t mine = budget; + const bool found = b.meet_in(0, work, mine, use); + VS_CHECK(found == anew); + VS_CHECK(work.empty()); + if (!found) VS_CHECK(mine == left); + } + VS_CHECK(b.meet_within(all, budget, seen) == anew); + if (!anew) { + ++none; + } else { + std::size_t unlimited = std::numeric_limits<std::size_t>::max(); + if (meet_anew(b, all, unlimited)) + ++some; + else + ++gave_up; + } + } + } + // All three outcomes came up, and searches were remembered. + VS_CHECK(none > 100 && some > 100 && gave_up > 100); + VS_CHECK(seen.none.size() > 100); +} + +VS_TEST(divergent_if_becomes_a_lane_branch) +{ + const Program p = build( + { + 0x7D84'0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBE80'3C6A, // s_and_saveexec_b32 s0, vcc_lo + 0xBF88'0001, // s_cbranch_execz -> 16 + 0x7E02'0280, // v_mov_b32 v1, 0 + 0x887E'007E, // 16: s_or_b32 exec_lo, exec_lo, s0 + 0x7E04'0280, // v_mov_b32 v2, 0 + S_ENDPGM, + }, + false); + const Structured s = structure::structure(p); + VS_REQUIRE(s.exits[0].is_branch() && s.exits[0].taken == 2 && s.exits[0].not_taken == 1); + const Bool when = s.exits[0].when; + // Skipped exactly where the compare fails. + const ir::Value cmp = *p.blocks[0].insts[0].write(Reg::S(ir::VCC)); + VS_CHECK(s.bools.node(when) == node(Atom::Lane(cmp), Bool::True, Bool::False)); + VS_CHECK(guarded(s) == 0); +} + +VS_TEST(exec_narrowed_without_a_branch_leaves_a_guard) +{ + const Program p = build( + { + 0x7DA4'0080, // v_cmpx_eq_u32 exec, 0, v0 + 0x7E02'0280, // v_mov_b32 v1, 0 + S_ENDPGM, + }, + true); + const Structured s = structure::structure(p); + VS_CHECK(!s.guards[0][0].has_value()); // the compare runs in every lane + VS_REQUIRE(s.guards[0][1].has_value()); + VS_CHECK(support_is(s, *s.guards[0][1], Atom::Kind::Lane)); +} + +VS_TEST(guards_follow_exec_and_block_reachability) +{ + const Program p = build( + { + 0x7DA4'0080, // v_cmpx_eq_u32 exec, 0, v0 + 0x7E02'0280, // v_mov_b32 v1, 0 + 0x7E04'0280, // v_mov_b32 v2, 0 + 0xBF88'0005, // s_cbranch_execz -> end + 0x7E06'0280, // v_mov_b32 v3, 0 + 0x7DA4'0880, // v_cmpx_eq_u32 exec, 0, v4 + 0x7E06'0280, // v_mov_b32 v3, 0 + 0xBE82'0480, // s_mov_b64 s[2:3], 0 + 0x7E0A'0280, // v_mov_b32 v5, 0 + S_ENDPGM, + }, + true); + const Structured s = structure::structure(p); + auto lane = [&](std::size_t block, std::size_t i) { + return Atom::Lane(*p.blocks[block].insts[i].write(Reg::S(ir::EXEC))); + }; + VS_REQUIRE(s.guards[0][1].has_value() && s.guards[1][2].has_value()); + const Bool a = *s.guards[0][1]; + const Bool b = *s.guards[1][2]; + VS_CHECK(s.bools.node(a) == node(lane(0, 0), Bool::False, Bool::True)); + VS_CHECK((s.guards[0] == std::vector<std::optional<Bool>>{std::nullopt, a, a, std::nullopt})); + // The fallthrough already implies the first compare. Only the second compare needs testing, and + // the scalar move never needs a guard. + VS_CHECK(s.bools.node(b) == node(lane(1, 1), Bool::False, Bool::True)); + VS_CHECK((s.guards[1] == + std::vector<std::optional<Bool>>{std::nullopt, std::nullopt, b, std::nullopt, b})); +} + +VS_TEST(divergent_loop_exits_per_lane) +{ + const Program p = build( + { + 0xBE82'0480, // s_mov_b64 s[2:3], 0 + 0x4A00'0081, // 4: v_add_nc_u32 v0, 1, v0 + 0x7D84'0080, // v_cmp_eq_u32 vcc, 0, v0 + 0x8882'026A, // s_or_b64 s[2:3], vcc, s[2:3] + 0x8AFE'027E, // s_andn2_b64 exec, exec, s[2:3] + 0xBF89'FFFB, // s_cbranch_execnz -> 4 + 0x88FE'027E, // s_or_b64 exec, exec, s[2:3] + 0x7E02'0280, // v_mov_b32 v1, 0 + S_ENDPGM, + }, + true); + const Structured s = structure::structure(p); + VS_CHECK(guarded(s) == 0); + VS_REQUIRE(s.exits[1].is_branch() && s.exits[1].taken == 1 && s.exits[1].not_taken == 2); + // Back while the lane's compare fails. + const auto n = s.bools.node(s.exits[1].when); + VS_REQUIRE(n.has_value()); + VS_CHECK(std::get<0>(*n).kind == Atom::Kind::Lane && std::get<1>(*n) == Bool::True && + std::get<2>(*n) == Bool::False); +} + +// `s_cselect` on the SCC a lane loop ended with (the blend-shape skinning programs): the loop is left +// when no lane remains, so the select takes its second operand; it was a uniform atom whose value no +// lane has. +VS_TEST(a_select_on_the_condition_a_lane_loop_ended_with_takes_its_second_operand) +{ + const std::uint32_t cnd = 256 | (256 << 9) | (3 << 18); + const Program p = build( + { + 0xBE83'037E, // 0: s_mov_b32 s3, exec_lo + 0xBE9C'037E, // s_mov_b32 s28, exec_lo + 0x7E3A'0507, // 8: v_readfirstlane_b32 s29, v7 + 0x7DA4'0E1D, // v_cmpx_eq_u32 exec_lo, s29, v7 + 0xBE9C'471C, // s_andn2_wrexec_b32 s28, s28 + 0xBF89'FFFC, // s_cbranch_execnz -> 8 + 0xBEFE'0303, // s_mov_b32 exec_lo, s3 + 0x8503'807E, // s_cselect_b32 s3, exec_lo, 0 + 0xD501'0001, + cnd, // v_cndmask_b32 v1, v0, v0, s3 + S_ENDPGM, + }, + false); + const Structured s = structure::structure(p); + const ir::Inst* select = nullptr; + for (const auto& b : p.blocks) + for (const auto& i : b.insts) + if (!select && i.name() == "s_cselect_b32") select = &i; + VS_REQUIRE(select != nullptr); + const ir::Value mask = *select->write(Reg::S(3)); + const auto it = s.masks.find(mask); + VS_CHECK(it != s.masks.end() && it->second == Bool::False); +} + +VS_TEST(scalar_branches_stay_uniform) +{ + const Program p = build( + { + 0xBF06'0100, // s_cmp_eq_u32 s0, s1 + 0xBF85'0001, // s_cbranch_scc1 -> 12 + 0x7E02'0280, // v_mov_b32 v1, 0 + S_ENDPGM, // 12 + }, + true); + const Structured s = structure::structure(p); + VS_REQUIRE(s.exits[0].is_branch()); + VS_CHECK(support_is(s, s.exits[0].when, Atom::Kind::Uniform)); + VS_CHECK(guarded(s) == 0); +} + +VS_TEST(a_mask_whose_high_dword_is_rewritten_is_not_the_compare) +{ + for (const std::uint32_t reader : { + 0x0202'0480u, // v_cndmask_b32 v1, 0, v2, vcc + 0x5002'0480u, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc + }) { + const Program p = build( + { + 0x7D84'0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBEEB'0380, // s_mov_b32 vcc_hi, 0 + reader, + S_ENDPGM, + }, + true); + const Structured s = structure::structure(p); + const ir::Value lo = *p.blocks[0].insts[2].read(Reg::S(ir::VCC)); + VS_CHECK(p.blocks[0].insts[0].write(Reg::S(ir::VCC)) == lo); + // The reader sees (compare low dword, 0): lanes 32-63 are clear. The mask exported for that + // low dword must not be the compare. + VS_CHECK(mask_node(s, lo) != node(Atom::Lane(lo), Bool::False, Bool::True)); + } +} + +VS_TEST(a_mask_joined_over_a_back_edge_with_a_rewritten_high_dword_is_not_the_compare) +{ + const Program p = build( + { + 0x7D84'0080, // v_cmp_eq_u32 vcc, 0, v0 + 0x0202'0480, // 4: v_cndmask_b32 v1, 0, v2, vcc + 0x7D84'0280, // v_cmp_eq_u32 vcc, 0, v1 + 0xBEEB'0380, // s_mov_b32 vcc_hi, 0 + 0xBF85'FFFC, // s_cbranch_scc1 -> 4 + S_ENDPGM, + }, + true); + const Structured s = structure::structure(p); + // The select reads the loop header's join; over the back edge it takes (compare low dword, 0), + // which only the join sees. + const ir::Value lo = *p.blocks[1].insts[1].write(Reg::S(ir::VCC)); + VS_CHECK(mask_node(s, lo) != node(Atom::Lane(lo), Bool::False, Bool::True)); +} + +VS_TEST(irreducible_loops_are_split) +{ + const Program p = build( + { + 0xBF06'0100, // s_cmp_eq_u32 s0, s1 + 0xBF85'0001, // s_cbranch_scc1 -> 12, into the loop's middle + 0x8002'8102, // 8: s_add_u32 s2, s2, 1 + 0xBF84'FFFE, // 12: s_cbranch_scc0 -> 8 + S_ENDPGM, + }, + false); + // The loop keeps 12 as its header; the entry into 8 gets a copy of it. + VS_REQUIRE(p.blocks.size() > 4); + const ir::Block& copy = p.blocks[4]; + VS_CHECK(copy.offset == 8 && copy.exit == ir::Exit::Jump(2)); + VS_CHECK((p.blocks[0].exit.successors() == std::vector<std::size_t>{2, 4})); + VS_CHECK((p.blocks[1].preds == std::vector<std::size_t>{2})); + VS_CHECK(try_shader([&] { return structure::structure(p); }).has_value()); +} + +VS_TEST(mask_phi_joining_constant_and_compare_records_edge_bools) +{ + const std::uint32_t cnd = 258 | (259 << 9) | (2 << 18); + const Program p = build( + { + 0xBF06'8000, // 0: s_cmp_eq_u32 s0, 0 + 0xBF85'0002, // 4: s_cbranch_scc1 -> 16 + 0xBE82'0380, // 8: s_mov_b32 s2, 0 + 0xBF82'0002, // 12: s_branch -> 24 + 0xD4C2'0002, + 0x0002'0080, // 16: v_cmp_eq_u32 s2, 0, v0 + 0xD501'0001, + cnd, // 24: v_cndmask_b32 v1, v2, v3, s2 + S_ENDPGM, + }, + false); + const Structured s = structure::structure(p); + const ir::Phi* phi = phi_of(p, Reg::S(2)); + VS_REQUIRE(phi != nullptr); + VS_CHECK(mask_node(s, phi->value) == node(Atom::Phi(phi->value), Bool::False, Bool::True)); + const auto it = s.phi_masks.find(phi->value); + VS_REQUIRE(it != s.phi_masks.end()); + const auto& edges = it->second; + VS_CHECK(edges.size() == 2); + VS_CHECK(contains(edges, Bool::False)); + VS_CHECK(std::any_of(edges.begin(), edges.end(), [&](Bool e) { return support_is(s, e, Atom::Kind::Lane); })); +} + +VS_TEST(loop_mask_accumulator_from_zero_tracks_phi_and_edges) +{ + const std::uint32_t cnd = 258 | (259 << 9) | (2 << 18); + const Program p = build( + { + 0xBE82'0480, // 0: s_mov_b64 s[2:3], 0 + 0xBE84'0380, // 4: s_mov_b32 s4, 0 + 0xD501'0001, + cnd, // 8: v_cndmask_b32 v1, v2, v3, s[2:3] + 0x7D84'0080, // 16: v_cmp_eq_u32 vcc, 0, v0 + 0x8882'026A, // 20: s_or_b64 s[2:3], vcc, s[2:3] + 0x8004'8104, // 24: s_add_u32 s4, s4, 1 + 0xBF0A'8404, // 28: s_cmp_lt_u32 s4, 4 + 0xBF85'FFF9, // 32: s_cbranch_scc1 -> 8 + 0xD501'0004, + cnd, // 36: v_cndmask_b32 v4, v2, v3, s[2:3] + S_ENDPGM, + }, + true); + const Structured s = structure::structure(p); + const ir::Phi* phi = phi_of(p, Reg::S(2)); + VS_REQUIRE(phi != nullptr); + VS_CHECK(s.masks.count(phi->value) == 1); + const auto it = s.phi_masks.find(phi->value); + VS_REQUIRE(it != s.phi_masks.end()); + const auto& edges = it->second; + VS_CHECK(edges.size() == 2); + VS_CHECK(contains(edges, Bool::False)); + VS_CHECK(std::any_of(edges.begin(), edges.end(), [&](Bool e) { + const auto sup = s.bools.support(e); + const bool has_phi = std::find(sup.begin(), sup.end(), Atom::Phi(phi->value)) != sup.end(); + const bool has_lane = + std::any_of(sup.begin(), sup.end(), [](const Atom& a) { return a.kind == Atom::Kind::Lane; }); + return has_phi && has_lane; + })); +} + +VS_TEST(loop_mask_phi_reset_to_constant_on_back_edge) +{ + const std::uint32_t cnd = 258 | (259 << 9) | (2 << 18); + const Program p = build( + { + 0xD4C2'0002, + 0x0002'0080, // 0: v_cmp_eq_u32 s2, 0, v0 + 0xBE84'0380, // 8: s_mov_b32 s4, 0 + 0xD501'0001, + cnd, // 12: v_cndmask_b32 v1, v2, v3, s2 + 0xBE82'0380, // 20: s_mov_b32 s2, 0 + 0x8004'8104, // 24: s_add_u32 s4, s4, 1 + 0xBF0A'8404, // 28: s_cmp_lt_u32 s4, 4 + 0xBF85'FFFA, // 32: s_cbranch_scc1 -> 12 + S_ENDPGM, + }, + false); + const Structured s = structure::structure(p); + const ir::Phi* phi = phi_of(p, Reg::S(2)); + VS_REQUIRE(phi != nullptr); + VS_CHECK(s.masks.count(phi->value) == 1); + const auto it = s.phi_masks.find(phi->value); + VS_REQUIRE(it != s.phi_masks.end()); + const auto& edges = it->second; + VS_CHECK(edges.size() == 2); + VS_CHECK(contains(edges, Bool::False)); + VS_CHECK(std::any_of(edges.begin(), edges.end(), [&](Bool e) { return support_is(s, e, Atom::Kind::Lane); })); +} + +VS_TEST_MAIN() diff --git a/tests/x2w_tool/blake3_test.cpp b/tests/x2w_tool/blake3_test.cpp new file mode 100644 index 0000000000..05a0afadad --- /dev/null +++ b/tests/x2w_tool/blake3_test.cpp @@ -0,0 +1,99 @@ +// BLAKE3 against the reference: the Rust `blake3` crate 1.8.7, run over the official +// test-vector input (byte i is i % 251) at lengths around block, chunk and tree edges, "abc", and +// an incremental update in 7-byte pieces of 10000 bytes. +#include <algorithm> +#include <cstring> +#include <string> +#include <vector> + +#include "blake3.h" +#include "test_util.h" + +using x2w::tool::Blake3; +using x2w::tool::blake3; +using x2w::tool::to_hex; + +namespace { + +struct Vector { + std::size_t len; + const char* hex; +}; + +const Vector VECTORS[] = { + {0, "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"}, + {1, "2d3adedff11b61f14c886e35afa036736dcd87a74d27b5c1510225d0f592e213"}, + {2, "7b7015bb92cf0b318037702a6cdd81dee41224f734684c2c122cd6359cb1ee63"}, + {3, "e1be4d7a8ab5560aa4199eea339849ba8e293d55ca0a81006726d184519e647f"}, + {63, "e9bc37a594daad83be9470df7f7b3798297c3d834ce80ba85d6e207627b7db7b"}, + {64, "4eed7141ea4a5cd4b788606bd23f46e212af9cacebacdc7d1f4c6dc7f2511b98"}, + {65, "de1e5fa0be70df6d2be8fffd0e99ceaa8eb6e8c93a63f2d8d1c30ecb6b263dee"}, + {127, "d81293fda863f008c09e92fc382a81f5a0b4a1251cba1634016a0f86a6bd640d"}, + {128, "f17e570564b26578c33bb7f44643f539624b05df1a76c81f30acd548c44b45ef"}, + {129, "683aaae9f3c5ba37eaaf072aed0f9e30bac0865137bae68b1fde4ca2aebdcb12"}, + {1023, "10108970eeda3eb932baac1428c7a2163b0e924c9a9e25b35bba72b28f70bd11"}, + {1024, "42214739f095a406f3fc83deb889744ac00df831c10daa55189b5d121c855af7"}, + {1025, "d00278ae47eb27b34faecf67b4fe263f82d5412916c1ffd97c8cb7fb814b8444"}, + {2047, "58830fbf51a4423c573b164471690570e544cfe793bead46225664796b4b1467"}, + {2048, "e776b6028c7cd22a4d0ba182a8bf62205d2ef576467e838ed6f2529b85fba24a"}, + {2049, "5f4d72f40d7a5f82b15ca2b2e44b1de3c2ef86c426c95c1af0b6879522563030"}, + {3072, "b98cb0ff3623be03326b373de6b9095218513e64f1ee2edd2525c7ad1e5cffd2"}, + {3073, "7124b49501012f81cc7f11ca069ec9226cecb8a2c850cfe644e327d22d3e1cd3"}, + {4096, "015094013f57a5277b59d8475c0501042c0b642e531b0a1c8f58d2163229e969"}, + {4097, "9b4052b38f1c5fc8b1f9ff7ac7b27cd242487b3d890d15c96a1c25b8aa0fb995"}, + {5120, "9cadc15fed8b5d854562b26a9536d9707cadeda9b143978f319ab34230535833"}, + {5121, "628bd2cb2004694adaab7bbd778a25df25c47b9d4155a55f8fbd79f2fe154cff"}, + {6144, "3e2e5b74e048f3add6d21faab3f83aa44d3b2278afb83b80b3c35164ebeca205"}, + {6145, "f1323a8631446cc50536a9f705ee5cb619424d46887f3c376c695b70e0f0507f"}, + {7168, "61da957ec2499a95d6b8023e2b0e604ec7f6b50e80a9678b89d2628e99ada77a"}, + {7169, "a003fc7a51754a9b3c7fae0367ab3d782dccf28855a03d435f8cfe74605e7817"}, + {8192, "aae792484c8efe4f19e2ca7d371d8c467ffb10748d8a5a1ae579948f718a2a63"}, + {8193, "bab6c09cb8ce8cf459261398d2e7aef35700bf488116ceb94a36d0f5f1b7bc3b"}, + {16384, "f875d6646de28985646f34ee13be9a576fd515f76b5b0a26bb324735041ddde4"}, + {31744, "62b6960e1a44bcc1eb1a611a8d6235b6b4b78f32e7abc4fb4c6cdcce94895c47"}, + {65536, "68d647e619a930e7b1082f74f334b0c65a315725569bdc123f0ee11881717bfe"}, + {102400, "bc3e3d41a1146b069abffad3c0d44860cf664390afce4d9661f7902e7943e085"}, + {1048577, "2f053cd7472cf0cd2f9adaf45c1180255b91b9a865404a63671a0ee5f792ed33"}, +}; + +std::vector<std::uint8_t> input(std::size_t n) { + std::vector<std::uint8_t> v(n); + for (std::size_t i = 0; i < n; ++i) v[i] = std::uint8_t(i % 251); + return v; +} + +} // namespace + +int main() { + for (const auto& v : VECTORS) { + const auto data = input(v.len); + const std::string got = to_hex(blake3(data)); + if (got != v.hex) std::fprintf(stderr, "length %zu: %s\n", v.len, got.c_str()); + CHECK(got == v.hex); + // The same in pieces that cross block and chunk edges. + for (std::size_t piece : {std::size_t{1}, std::size_t{63}, std::size_t{64}, std::size_t{1000}, std::size_t{1024}}) { + if (v.len > 70000 && piece < 64) continue; + Blake3 h; + for (std::size_t at = 0; at < data.size(); at += piece) + h.update(std::span<const std::uint8_t>(data).subspan(at, std::min(piece, data.size() - at))); + CHECK(to_hex(h.finalize()) == v.hex); + } + } + const char* abc = "abc"; + CHECK(to_hex(blake3(std::span<const std::uint8_t>(reinterpret_cast<const std::uint8_t*>(abc), 3))) == + "6437b3ac38465133ffb63b75273a8db548c558465d79db03fd359c6cd5bd9d85"); + { + const auto data = input(10000); + Blake3 h; + for (std::size_t at = 0; at < data.size(); at += 7) + h.update(std::span<const std::uint8_t>(data).subspan(at, std::min<std::size_t>(7, data.size() - at))); + CHECK(to_hex(h.finalize()) == "5f81f9e4ab67627b6b036d5d4e3bc40d9d3daa6fcc2b6dd07ab2bbf0a877da54"); + // finalize() does not change the state: more input continues the same hash. + Blake3 g; + g.update(std::span<const std::uint8_t>(data).first(5000)); + (void)g.finalize(); + g.update(std::span<const std::uint8_t>(data).subspan(5000)); + CHECK(to_hex(g.finalize()) == to_hex(blake3(data))); + } + return test_util::finish("x2w_tool_blake3_test"); +} diff --git a/tests/x2w_tool/scan_test.cpp b/tests/x2w_tool/scan_test.cpp new file mode 100644 index 0000000000..06436123cf --- /dev/null +++ b/tests/x2w_tool/scan_test.cpp @@ -0,0 +1,353 @@ +// scan.h on synthetic files: fnv64 and bounded (the tests in the upstream export_x2w.rs), the export's +// text helpers against Rust's output, sources() over raw and SGD5-packed containers, the walk, and +// dump() with a stand-in translator (files, rows, sorting, deduplication, failures, threads). +#include <algorithm> +#include <bit> +#include <filesystem> +#include <fstream> +#include <mutex> +#include <process.h> +#include <sstream> +#include <string> +#include <vector> + +#include "scan.h" +#include "test_util.h" +#include "x2w_shader/dxbc.h" + +namespace fs = std::filesystem; +using namespace x2w::tool; +using x2w::vs::dxbc::FourCC; + +namespace { + +using Buf = std::vector<std::uint8_t>; + +Buf container(std::uint8_t fill, std::size_t n) { + const Buf data(n, fill); + return x2w::vs::dxbc::build({{FourCC::DXIL, x2w::vs::dxbc::Bytes(data)}}); +} + +void put32(Buf& out, std::uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); +} + +// An SGD5 record holding `payload` in one stored deflate block. +Buf record(const std::string& name, std::uint8_t kind, const Buf& payload) { + Buf packed = {0x01, std::uint8_t(payload.size()), std::uint8_t(payload.size() >> 8), + std::uint8_t(~payload.size()), std::uint8_t(~payload.size() >> 8)}; + packed.insert(packed.end(), payload.begin(), payload.end()); + const auto n = std::uint32_t(packed.size() + 12); + Buf out = {std::uint8_t(name.size() + 1)}; + out.insert(out.end(), name.begin(), name.end()); + out.push_back(0); + out.push_back(kind); + for (std::uint32_t v : {n, 0x000DDCE7u, n, std::uint32_t(payload.size())}) put32(out, v); + out.insert(out.end(), packed.begin(), packed.end()); + return out; +} + +void append(Buf& a, const Buf& b) { a.insert(a.end(), b.begin(), b.end()); } + +std::string read(const fs::path& p) { + std::ifstream f(p, std::ios::binary); + std::stringstream s; + s << f.rdbuf(); + return s.str(); +} + +void write(const fs::path& p, const Buf& b) { + fs::create_directories(p.parent_path()); + std::ofstream f(p, std::ios::binary); + f.write(reinterpret_cast<const char*>(b.data()), std::streamsize(b.size())); +} + +std::vector<std::string> lines(const std::string& text) { + std::vector<std::string> out; + std::size_t at = 0; + while (at < text.size()) { + const std::size_t nl = text.find('\n', at); + out.push_back(text.substr(at, nl - at)); + at = nl == std::string::npos ? text.size() : nl + 1; + } + return out; +} + +void fnv_and_bounded() { + // X2W's basis. + CHECK(fnv64({}) == 0x14650fb0739d0383ull); + const std::uint8_t a = 'a'; + CHECK(fnv64(Bytes(&a, 1)) == 0x44bd8ad473cd9906ull); + + // Containers are cut to their size. + Buf c = {'D', 'X', 'B', 'C'}; + c.resize(24, 0); + put32(c, 40); + c.resize(48, 7); + CHECK(bounded(c).size() == 40); + // A size below the header or past the bytes leaves them as they are. + Buf small = c; + small[24] = 31; + CHECK(bounded(small).size() == 48); + Buf big = c; + big[24] = 49; + CHECK(bounded(big).size() == 48); + CHECK(bounded(Bytes(c).first(27)).size() == 27); + + Blake3Hash h{}; + h[0] = 0x01; + h[7] = 0xef; + h[8] = 0xff; + CHECK(key_of(h) == 0x01000000000000efull); + CHECK(hex16(key_of(h)) == "01000000000000ef"); +} + +void text_helpers() { + // Rust `{:?}` of these f32 values (printed by a scratch Rust program). + const struct { + std::uint32_t bits; + const char* text; + } floats[] = { + {0x00000000u, "0.0"}, + {0x80000000u, "-0.0"}, + {0x3f800000u, "1.0"}, + {0xbf800000u, "-1.0"}, + {0x3dcccccdu, "0.1"}, + {0x3f000000u, "0.5"}, + {0x447a0000u, "1000.0"}, + {0x41800000u, "16.0"}, + {0x7f7fffffu, "3.4028235e38"}, + {0xff7fffffu, "-3.4028235e38"}, + {0x00800000u, "1.1754944e-38"}, + {0x00000001u, "1e-45"}, + {0x38d1b717u, "0.0001"}, + {0x38d1b68eu, "9.9999e-5"}, + {0x3727c5acu, "1e-5"}, + {0x377ba882u, "1.5e-5"}, + {0x5a0e1bcau, "1e16"}, + {0x5a0e1bc9u, "9999999000000000.0"}, + {0x58635fa9u, "1000000000000000.0"}, + {0x4ceb79a3u, "123456790.0"}, + {0x3b449ba6u, "0.003"}, + {0xc1540000u, "-13.25"}, + }; + for (const auto& f : floats) { + const std::string got = json_float(std::bit_cast<float>(f.bits)); + if (got != f.text) std::fprintf(stderr, "%08x: %s, Rust %s\n", f.bits, got.c_str(), f.text); + CHECK(got == f.text); + } + CHECK(json_float(std::bit_cast<float>(0x7f800000u)) == "null"); + CHECK(json_float(std::bit_cast<float>(0xff800000u)) == "null"); + CHECK(json_float(std::bit_cast<float>(0x7fc00000u)) == "null"); + + CHECK(json_text("a\"b\\c") == "\"a\\\"b\\\\c\""); + CHECK(json_text(std::string("x\ty\n\x01", 5)) == "\"x\\u0009y\\u000a\\u0001\""); + CHECK(json_text("\xc3\xa9") == "\"\xc3\xa9\""); + + auto lossy = [](std::initializer_list<std::uint8_t> b) { return utf8_lossy(Buf(b)); }; + CHECK(lossy({'D', 'X', 'I', 'L'}) == "DXIL"); + CHECK(lossy({0xff, 'a'}) == "\xEF\xBF\xBD" "a"); + CHECK(lossy({0xe2, 0x82, 'a'}) == "\xEF\xBF\xBD" "a"); // a cut sequence: one U+FFFD + CHECK(lossy({0xe0, 0x80, 'a'}) == "\xEF\xBF\xBD\xEF\xBF\xBD" "a"); // overlong: lead, then 0x80 + CHECK(lossy({0xed, 0xa0, 0x80}) == "\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD"); // a surrogate + CHECK(lossy({0xf0, 0x9f, 0x98, 0x80}) == "\xF0\x9F\x98\x80"); + CHECK(lossy({0xf0, 0x9f, 0x98}) == "\xEF\xBF\xBD"); + + const std::vector<int> v = {1, 2, 3}; + CHECK(json_list(v, [](int x) { return std::to_string(x); }) == "[1,2,3]"); + CHECK(json_list(std::vector<int>{}, [](int x) { return std::to_string(x); }) == "[]"); +} + +void finds_sources() { + const Buf a = container(0xA1, 8), b = container(0xB2, 12), packed = container(0xC3, 20); + Buf file = {'x', 'y'}; + append(file, a); + // "DXBC" that does not parse is not a container. + append(file, {'D', 'X', 'B', 'C', 0, 0}); + append(file, {'S', 'G', 'D', '5'}); + append(file, record("PS_one_Wrapped", 0x32, packed)); + append(file, b); + + const auto found = sources(file); + // (The record's stored block holds its container as is: the scan finds that copy too, as + // the reference scan does.) + CHECK(found.size() == 4); + if (found.size() != 4) return; + // The records first, then the containers stored as is, in file order. + CHECK(found[0].packed); + Buf storage; + auto bytes = found[0].bytes(storage); + CHECK(bytes && Buf(bytes->begin(), bytes->end()) == packed); + CHECK(!found[1].packed && found[1].offset == 2); + bytes = found[1].bytes(storage); + CHECK(bytes && bounded(*bytes).size() == a.size()); + CHECK(Buf(bounded(*bytes).begin(), bounded(*bytes).end()) == a); + // Raw bytes run to the end of the file. + CHECK(bytes->size() == file.size() - 2); + const std::size_t b_at = file.size() - b.size(); + CHECK(!found[2].packed && found[2].offset == found[0].record.offset + 12 + 5); + CHECK(!found[3].packed && found[3].offset == b_at); + + char label[64]; + std::snprintf(label, sizeof label, "@%#zx PS_one_Wrapped", found[0].record.offset); + CHECK(found[0].label() == label); + CHECK(found[1].label() == "@0x2"); + std::snprintf(label, sizeof label, "@%#zx", b_at); + CHECK(found[3].label() == label); + // The SGD5 container that holds a raw container too: the packed one's bytes are not raw. + // A record without a name is labelled "?"; a corrupt record has no bytes. + Buf unnamed = {'S', 'G', 'D', '5'}; + Buf r = record("PS_x", 0x32, packed); + r[0] = 9; // the length byte disagrees + append(unnamed, r); + auto u = sources(unnamed); + CHECK(u.size() == 2 && u[0].packed && u[0].label().ends_with(" ?")); + Buf corrupt = {'S', 'G', 'D', '5'}; + Buf rc = record("PS_x", 0x32, packed); + rc[1 + 4 + 2 + 16] = 0x07; // first packed byte: BFINAL 1, reserved block type + append(corrupt, rc); + u = sources(corrupt); + CHECK(u.size() == 2 && u[0].packed && !u[0].bytes(storage) && !u[1].packed); + // Without "SGD5" the records are not looked for (only the stored copy is found). + CHECK(sources(r).size() == 1 && !sources(r)[0].packed); + // "0x0" for a container at the start. + CHECK(sources(a).size() == 1 && sources(a)[0].label() == "@0x0"); +} + +fs::path scratch(const char* name) { + const fs::path p = fs::temp_directory_path() / ("x2w_tool_scan_test_" + std::to_string(_getpid()) + name); + std::error_code ec; + fs::remove_all(p, ec); + fs::create_directories(p); + return p; +} + +void walks() { + const fs::path root = scratch("_walk"); + write(root / "a.bin", {1}); + write(root / "sub" / "b.bin", {2, 3}); + write(root / "sub" / "deeper" / "c.bin", {4, 5, 6}); + write(root / "z.bin", {}); + std::vector<std::pair<std::string, std::size_t>> seen; + walk_files({root}, [&](const std::string& file, Bytes data) { seen.emplace_back(file, data.size()); }); + CHECK(seen.size() == 4); + const std::string r = root.u8string().size() ? reinterpret_cast<const char*>(root.u8string().c_str()) : ""; + auto has = [&](const std::string& name, std::size_t n) { + return std::find(seen.begin(), seen.end(), std::make_pair(r + name, n)) != seen.end(); + }; + CHECK(has("\\a.bin", 1)); + CHECK(has("\\sub\\b.bin", 2)); + CHECK(has("\\sub\\deeper\\c.bin", 3)); + CHECK(has("\\z.bin", 0)); + // A root that is a file is itself; a missing root is nothing. + seen.clear(); + walk_files({root / "sub" / "b.bin", root / "missing"}, [&](const std::string& file, Bytes data) { + seen.emplace_back(file, data.size()); + }); + CHECK(seen.size() == 1 && seen[0].first == r + "\\sub\\b.bin"); + std::error_code ec; + fs::remove_all(root, ec); +} + +void dumps() { + const fs::path in = scratch("_in"), out = scratch("_out") / "export"; + // Twenty containers in one file (threads share it), one of them twice; the same container in a + // second file; one the stand-in translator refuses. + Buf one = {'S', 'G', 'D', '5'}; + std::vector<Buf> cs; + for (std::uint8_t i = 0; i < 20; ++i) cs.push_back(container(i, 4 + i)); + for (const auto& c : cs) append(one, c); + append(one, record("PS_again", 0x32, cs[3])); + write(in / "one.bin", one); + Buf two = cs[5]; + // Bytes after the container's size do not make it another container. + append(two, {9, 9, 9}); + write(in / "two" / "two.bin", two); + const Buf refused = container(0xEE, 6); + write(in / "two" / "three.bin", refused); + const Bytes refused_bytes(refused); + const std::uint64_t refused_key = key_of(blake3(refused_bytes)); + + DumpOptions o; + o.out = out; + o.paths = {in}; + o.jobs = 3; + o.build = "b"; + o.manifest = [](std::size_t records) { return "records " + std::to_string(records) + "\n"; }; + std::mutex m; + std::size_t calls = 0; + const DumpCounts c = dump(o, [&](const Found& f) { + { + std::lock_guard<std::mutex> lock(m); + ++calls; + } + Made made; + if (f.key == refused_key) { + made.failed = "no\tgood\nat all"; + return made; + } + made.dxil.assign(f.bytes.begin(), f.bytes.end()); + made.dxil.push_back(0x5A); + made.json = "{\"key\": " + json_text(f.name) + "}\n"; + made.index_line = f.name + "\t" + hex16(f.fnv) + "\t" + to_hex(f.full) + "\t" + f.file; + made.program_lines = {hex16(f.fnv) + "\tcode\t" + f.name}; + return made; + }); + CHECK(calls == 21); + CHECK(c.containers == 21 && c.translated == 20 && c.failed == 1 && c.collisions == 0); + + const auto index = lines(read(out / "index.tsv")); + CHECK(index.size() == 21 && index[0] == INDEX_HEADER); + CHECK(std::is_sorted(index.begin() + 1, index.end())); + for (const auto& cb : cs) { + const Blake3Hash full = blake3(cb); + const std::string name = hex16(key_of(full)); + const std::string dxil = read(out / (name + ".dxil")); + CHECK(dxil.size() == cb.size() + 1 && std::equal(cb.begin(), cb.end(), dxil.begin())); + CHECK(read(out / (name + ".json")) == "{\"key\": \"" + name + "\"}\n"); + const auto row = std::find_if(index.begin(), index.end(), [&](const std::string& l) { return l.starts_with(name); }); + CHECK(row != index.end()); + // cs[5] is first found in one.bin (walked first: "one.bin" before "two"). + if (row != index.end()) CHECK(row->ends_with("one.bin")); + if (row != index.end()) CHECK(row->find(to_hex(full)) != std::string::npos); + } + const auto sources_rows = lines(read(out / "sources.tsv")); + // 20 raw + 1 packed (and its stored copy, raw) in one.bin, 1 in two.bin, 1 in three.bin. + CHECK(sources_rows.size() == 1 + 24 && sources_rows[0] == SOURCES_HEADER); + CHECK(std::is_sorted(sources_rows.begin() + 1, sources_rows.end())); + const std::string again = hex16(key_of(blake3(cs[3]))); + CHECK(std::count_if(sources_rows.begin(), sources_rows.end(), [&](const std::string& l) { + return l.starts_with(again) && l.ends_with(" PS_again"); + }) == 1); + const auto failed = lines(read(out / "failed.tsv")); + CHECK(failed.size() == 2 && failed[0] == FAILED_HEADER); + if (failed.size() == 2) { + CHECK(failed[1].starts_with(hex16(refused_key) + "\t" + hex16(fnv64(refused)) + "\t" + + std::to_string(refused.size()) + "\t")); + CHECK(failed[1].ends_with("three.bin\tno good at all")); + } + CHECK(read(out / "collisions.tsv") == std::string(COLLISIONS_HEADER) + "\n"); + const auto programs = lines(read(out / "programs.tsv")); + CHECK(programs.size() == 21 && programs[0] == PROGRAMS_HEADER); + CHECK(read(out / "manifest.txt") == "records 20\n"); + const std::string summary = read(out / "summary.txt"); + CHECK(summary.starts_with("build b\ncontainers 21\ncached 0\ntranslated 20\nmissing 0\nfailed 1\nseconds ")); + CHECK(summary == c.summary); + // No carriage returns anywhere. + CHECK(read(out / "index.tsv").find('\r') == std::string::npos); + CHECK(!fs::exists(out / "orphans.tsv") && !fs::exists(out / "orphans")); + std::error_code ec; + fs::remove_all(in, ec); + fs::remove_all(out.parent_path(), ec); +} + +} // namespace + +int main() { + fnv_and_bounded(); + text_helpers(); + finds_sources(); + walks(); + dumps(); + return test_util::finish("x2w_tool_scan_test"); +} diff --git a/tests/x2w_tool/sgd5_test.cpp b/tests/x2w_tool/sgd5_test.cpp new file mode 100644 index 0000000000..0113809370 --- /dev/null +++ b/tests/x2w_tool/sgd5_test.cpp @@ -0,0 +1,217 @@ +// Port of the upstream Rust game-format tests in src/sgd5.rs. The raw deflate streams are what +// zlib-rs makes there (level 6, window bits -15); they were made with Python's zlib +// (compressobj(6, DEFLATED, -15)), which writes the same format, and are embedded as hex. +#include <string> +#include <vector> + +#include "sgd5.h" +#include "test_util.h" + +using x2w::tool::sgd5::is_sgd5; +using x2w::tool::sgd5::MAGIC; +using x2w::tool::sgd5::records; + +namespace { + +const char* const FIRST = + "4bcb2c2a2e5148cecf2b49cccc4b2d0200" + ; +const char* const SEVENS = + "63671f05c40200" + ; +const char* const ONES = + "6364a40c0000" + ; +const char* const EMPTY = + "0300" + ; +const char* const BIG = + "ed996357e06d18c473ad6de516b53673cbd6566e6d33d76eadeddcda666e6d33b7b6f9dcd739d7f566bec173ceff13cccc6fe6dde8d4e938" + "7cdea6930fbe5769d97fdaaa8337de9769d8635ce4ce0bcf8dad5d7c82635372fed6693f7ccea6e30fbe5669de7fcaaafd37de96b1ed3126" + "72fb8542634b17afe0e8d427bfeb741c3c6bd3c93b9fabb4ec3d69d5c12bafcb34ec322a726746beb1b5834770dce9277febb41e3c67d3e1" + "3b5fab34ee3d65d5ee2b6fcbd4ed3226323ea3d0d8d4c12b84b4c903699307d2260f4a3b5b79f0256df240dae481b4c983d24e511e5c499b" + "3c903679206df2a0b46395071bd2260fa44d1e489b3c28ed60e5c144720b07ce9dcd1c5e486ee1c0b95398c345c92d1c38772c73d825b985" + "03e70e660e51925b38706e1fe6305e720b07ceedc21cdc25b770e0dcd6cca191e4160e9cdb98399485beb3610f1fa0ef14d8c34de83b16f6" + "7008fa0e863dac86be7d600fd3a16f17d8c300e8db1af6d00afa36863d5485be9fc31e7e40df17600f0fa1ef9db08753d07724ec6133f43d" + "0ef6301ffaee017b18017d37843d7482becbc01e4c3bd59e3fecd4c61ff75b559edeefd0ca0fd71b951edf7dd7e217e76d8c7c9de3827252" + "9e76aa397fc8a9f53feeb6aa38bdcfa1e51fae362a39beebae8817993606be8e7101b97f1e77aa3d7bd0a98d5f6eb7aa3cb9d7a1956f2e37" + "2a3dbaf3aec505e936469ef671c19bff3ced5475f69053abbfdc6d5576729f43516fae363219dd75574841a68d8ea7633c699307d2260fa4" + "4d1e9476b2f2e042dae481b4c903699307a59da33cf8913679206df240dae4416907290fc6a44d1e489b3c90367950da71ca435dc92d1c38" + "773273b820b98503e7ce610e2f25b770e0dc41cc2152720b07ce1dc71c764b6ee1c0b99d99430fc92d1c38b72f739820b98503e736620e65" + "24b770e0dc36cca131f49d0c7bb8017de7c01e3e42df41b08755d0771cece130f4ed0c7be80f7dfbc21e6640df46b0872ad0b70deca135f4" + "7d1ef6f000fa7e017bf8097d2f863d6c82be77c11e4e43dfdd610fc3a1eff1b08705d07769d8431de8bb11ecc17ee4825aed1ffddc707ce0" + "8c4acd6f7d5cb1bfe78452b6975e2edaeee6676899961b187376e4bc5a6d1f7ddf7074e0b44a4d6fbd5fb1b7e7b852f52f3d5f94e8e66368" + "9e961db4e5f4c805d55a3ffab9e6f0c019e51adffab86477cf09c5ea5e7a191aefe6a76b9a96f77bcbd991b3aab57df479cdd18193ca35bd" + "f57ac9de9ea38ad5bf941f9ae8e6a16b9e4edae481b4c903699307a51dad3c58913679206df240dae44169072a0f46a44d1e489b3c903679" + "50dab9ca833f699307d2260fa44d1e94769af2d059720b07ce1dcd1c76486ee1c0b90399c362c92d1c38772e737825b98503e74e630e9725" + "b770e0dc96ccc14e720b07ce6dc81c4a4b6ee1c0b9fd98c344c92d1c38b71b73e8057d47c31e0e40df81b08795d0772eece113f49d067bb8" + "0d7d5bc21e5a40df86b087cad0b71fec6126f4ed067b18047d6f873d9c80be17c11e3642df2f610fbfa0ef4bb087c7d0b72deca103f45d0a" + "f6501bfa9e007b58087df7843d782c1cd1a1e6af8727d6cf1cd0a2e2a79b07964f74b72bf9eae28e087f572b83bcd498c0ad0b8775a8feeb" + "fe89b533fbb528ffe9fa81a513bbdb157f757e4798bfb3955e5e72ec99cd0b47b4a9faebe191d533073429fbe9e69ea889eef54c5e5d4c08" + "f17735d3c94b7b7c66ebc2416daaffba7d64edcc5e4dca7fbabc67e9c4cef58abf4a4f08f3b737d3cb276df240dae481b4c983d20e501e0c" + "499b3c903679206df2a0b46394076bd2260fa44d1e489b3c28ed54e5c18db4c903699307d2260f4a3b4f791825b98503e70e600e8b24b770" + "e0dc31cc61a7e4160e9c3b95395c92dcc28173e73187d7925b38706e03e6504a720b07ce6dc51c1a4a6ee1c0b95d99434fc92d1c38b73f73" + "98047d07c01e5640df31b08783d0772aece116f49d077bf80c7d1bc01e2a41df56b08796d0b72bec6120f4ed0f7b98057d47c01e3640df3b" + "600f27a1ef8bb08747d0f72bd8c36fe8bb24eca116f46d077be8087dbbc31e4642df13610f01dbce3ef95da3ede059eb8edef95ca169ef49" + "cbf65e795da27e9751e18919f9fae60e9e0bb69d7ef2b346ebc133d61dbef3b142e3de1396edbef2b244dd2e7ee1f119b9faa68ec3e76d3b" + "fbe07b8db6fda7ad3b7ae37d85a63dc62ddb7be17989fa2e3ee18929d9fa16ed872fd876fcc1cf1acdfbcf58b7ffc6c70ab63d262cdb7ee1" + "65094b17bff0e8945c03d2260fa44d1e489b3c286d0fe5a180b4c903699307d2260f4adb4179c8246df240dae481b4c983d236571e92489b" + "3c903679206df2a0b4f5958708c92d1c38b70773182db98503e776600e5d25b770e0dce6cca181e4160e9c5b9f399494dcc28173e7338737" + "925b3870ee0ce67055720b07ce9dc81cf6496ee1c0b9c399c372e8db03f63019fa76803df481becd610fcda06f7dd84345e83b1ff6f005fa" + "ce803ddc85be13610fc7a0ef70d8c37ae87b14ec6136f4dd05f63004faae0f7b68077d97803dd484be5fc31efe40df57600f4fa1efbdb087" + "73d0f732d843f4b9ad7f1eb7ab3e7bd0b1b55f6e372b3fb9d7bea56f2e37283eba73525841ba859ea7c388739bff3c6c5775f68063abbfdc" + "6c5676b2fbbea837171b988c764d0a2948b5d0f19a3fecdcd61ff7db559fdeefd8da0fd79b951fdf7ddfd217e71b14f7754e0acb49b6d0af" + "397fc4b9f53f1eb6ab387dc0b1e51f6e362b39de7d5fc48b8b0d0c7c5d930272522d499b3c903679206df2a0b4ed95870cd2260fa44d1e48" + "9b3c286d4fe5a190b4c903699307d2260f4a5b4f7908276df240dae481b4c983d2b6501eb64b6ee1c0b9ed994317c92d1c38b727731823b9" + "8503e7d6630e2524b770e0dc16ccc156720b07ce9dce1cae486ee1c0b90b98c35bc92d1c387718735826b98503e74e620efba16f7bd8436f" + "e8db13f63005fad6833d5480be2d600fcda1ef74d8c31de8bb00f6f015fa0e833dac83be93600fc7a1efceb087c1d0f768d8c31ce8bb38ec" + "a106f4dd00f6d01efabe0c7b78027dbf813dfc85be97c21eb641dffb600fc9cffe6e393d744eb5d6f7beae39dc774ab9c6d7de2ed9dd6d4c" + "b1ba5985a1f14e5eba661d9ffdde7272e8ac6a2def7d5e73b0efa4720dafbd5eb2b3dba862d659f9a1b14e1e7ab5da3ffbbbe1f8d039959a" + "dffbba627fdf29a56cafbd5db4bddb1843cbacc2c06827ef79b53a3efbbee1e4d069955ade7bbfe260df71a51a5e7bbe6867371f43ebacec" + "c05867d2260fa44d1e489b3c286d53e52181b4c903699307d2260f4a5b577908236df240dae481b4c983d2f6521e8a489b3c903679206df2" + "a0b49d9487f3925b38706e53e6504f720b07ceadcb1c8a4b6ee1c0b9bd98c358c92d1c38b71373e82eb98503e78e670e7b24b770e0dca1cc" + "61a9e4160e9cbb9039bc93dcc28173673187ebd0b729eca109f4ad0b7b280f7d7bc11ea642df4eb0877ed0773cece108f41d0a7b580b7d17" + "c21ebe41df59b087fbd0775dd8431be8bb18eca13af43d06f63017faee067b18067def863d9c81be97c01eb642df6f610fffa0ef6bb087ec" + "7f4fcf6c9e3ba44dd56f778fac9edaa749d97757f7448ded5acfa4283321c4dbd14cb7f6bfc76736ce1dd4a6f2b7db47564eedd5a4f4bbcb" + "7b168fed5ccfa8283d21c8dbdebc43cd7f4f4fac9f3ba445c56f770f2c9fdac7aee4bbab3b22c676b53228ca8c09f0761ad6a1f6bffb2736" + "ceedd7a2f2b7eb07564eed6e57faddf91d8bc73a5b191525c704f9903679206df240dae44169eb280fa1a44d1e489b3c90367950da66ca43" + "22699307d2260fa44d1e94b6a3f29045dae481b4c903699307a5edad3c3c97dcc28173eb308762925b38706e33e6505f720b07ceedc81cba" + "496ee1c0b9bd99c338c92d1c387708735822b98503e74e600e7b25b770e0dc99cce19ae4160e9cbb8839bc87be75600fe5a06f33d84353e8" + "db11f6d017faf6863d4c83be43600f6ba0ef04d8c351e83b13f6700ffa2e823d7c87be4d600fd5a0ef7ab087b6d07757d8c350e87b2cec61" + "1ef41d057bd8027def813d9c85beafc21e9e41dfef600f3adaffaffdffdaffaffdffdaffaffdffdaffaffdffdaffaffdffdaffaffdffdaff" + "affdffdaffaffdffdaffaffdffdaffaffdffdaffaffdffdaffaffdffdaffaffdffdaffaffdffdaffaffdffdaffffbfffffff03" + ; + +std::vector<std::uint8_t> unhex(const char* h) { + std::vector<std::uint8_t> out; + for (std::size_t i = 0; h[i] && h[i + 1]; i += 2) out.push_back(std::uint8_t(std::stoi(std::string(h + i, 2), nullptr, 16))); + return out; +} + +void put32(std::vector<std::uint8_t>& out, std::uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); +} + +std::vector<std::uint8_t> record_bytes(const std::string& name, std::uint8_t kind, std::size_t payload_len, + const std::vector<std::uint8_t>& packed) { + const auto n = std::uint32_t(packed.size() + 12); + std::vector<std::uint8_t> out = {0xF4, 0x01, 0, 0, std::uint8_t(name.size() + 1)}; + out.insert(out.end(), name.begin(), name.end()); + out.push_back(0); + out.push_back(kind); + for (std::uint32_t v : {n, 0x000DDCE7u, n, std::uint32_t(payload_len)}) put32(out, v); + out.insert(out.end(), packed.begin(), packed.end()); + return out; +} + +void set32(std::vector<std::uint8_t>& b, std::size_t at, std::uint32_t v) { + for (int i = 0; i < 4; ++i) b[at + i] = std::uint8_t(v >> (8 * i)); +} + +void reads_records() { + const std::string long_name = "PS_" + std::string(40, 'x') + "_Wrapped"; + std::vector<std::uint8_t> file(MAGIC, MAGIC + 4); + file.insert(file.end(), {1, 2, 3, 4}); + const auto first = record_bytes("VS_Blit_0011aabb_Wrapped", 0x32, 15, unhex(FIRST)); + file.insert(file.end(), first.begin(), first.end()); + // A marker whose sizes disagree is not a record. + file.insert(file.end(), {9, 0, 0, 0, 0xE7, 0xDC, 0x0D, 0, 8, 0, 0, 0}); + const auto second = record_bytes(long_name, 0x41, 300, unhex(SEVENS)); + file.insert(file.end(), second.begin(), second.end()); + + CHECK(is_sgd5(file)); + const auto found = records(file); + CHECK(found.size() == 2); + if (found.size() != 2) return; + CHECK(found[0].name && *found[0].name == "VS_Blit_0011aabb_Wrapped"); + CHECK(found[0].kind == 0x32); + const std::string text = "first container"; + CHECK(found[0].unpack() == std::vector<std::uint8_t>(text.begin(), text.end())); + CHECK(found[1].name && *found[1].name == long_name); + CHECK(found[1].unpack() == std::vector<std::uint8_t>(300, 7)); + + // The same file inside an archive. + std::vector<std::uint8_t> archive(0x1000, 0x5A); + archive.insert(archive.end(), file.begin(), file.end()); + CHECK(is_sgd5(archive)); + CHECK(records(archive).size() == 2); + CHECK(!is_sgd5(std::span<const std::uint8_t>(archive).first(0x1000))); +} + +void corrupt_stream_does_not_unpack() { + auto file = record_bytes("CS_x", 0x3c, 64, unhex(ONES)); + // (The stream itself is good.) + CHECK(records(file).at(0).unpack() == std::vector<std::uint8_t>(64, 1)); + file[27] = 0xFF; // first packed byte: reserved block type + const auto r = records(file); + CHECK(r.size() == 1); + CHECK(!r.at(0).unpack()); +} + +void handles_empty_and_rejects_mismatched_or_truncated_streams() { + const auto empty = record_bytes("CS_empty", 0x3c, 0, unhex(EMPTY)); + CHECK(records(empty).at(0).unpack() == std::vector<std::uint8_t>()); + + std::vector<std::uint8_t> payload; + for (std::uint32_t i = 0; i < 16384; ++i) payload.push_back(std::uint8_t((i * 31u) ^ (i >> 5))); + const auto good = record_bytes("PS_big", 0x32, payload.size(), unhex(BIG)); + const auto r = records(good).at(0); + CHECK(r.unpack() == payload); + + // Oversized stream (declared unpacked_size smaller than actual output). + auto smaller = good; + set32(smaller, r.offset + 8, std::uint32_t(payload.size() - 1)); + CHECK(!records(smaller).at(0).unpack()); + + // Under-filled stream (declared unpacked_size larger than actual output). + auto larger = good; + set32(larger, r.offset + 8, std::uint32_t(payload.size() + 1)); + CHECK(!records(larger).at(0).unpack()); + + // Truncated raw deflate stream. + std::vector<std::uint8_t> truncated(good.begin(), good.end() - 1); + const auto new_n = std::uint32_t(truncated.size() - r.offset); + set32(truncated, r.offset - 4, new_n); + set32(truncated, r.offset + 4, new_n); + CHECK(!records(truncated).at(0).unpack()); +} + +// Additions: a name without its length byte, a stored block with bytes after the stream's end, a +// marker at the very start or end of the file, and a record whose data runs past the file. +void edges() { + // Stored block: BFINAL 1, BTYPE 00, LEN 3, NLEN, "abc"; then trailing bytes (ignored). + const std::vector<std::uint8_t> stored = {0x01, 3, 0, 0xFC, 0xFF, 'a', 'b', 'c', 0xAA, 0xBB}; + auto rec = record_bytes("PS_s", 0x40, 3, stored); + CHECK(records(rec).at(0).unpack() == std::vector<std::uint8_t>({'a', 'b', 'c'})); + CHECK(records(rec).at(0).kind == 0x40); + // The length byte disagrees: no name, the record is still read. + rec[4] = 9; + CHECK(records(rec).size() == 1 && !records(rec).at(0).name); + // No NUL before the kind byte: no name. + rec = record_bytes("PS_s", 0x40, 3, stored); + rec[9] = 'z'; + CHECK(records(rec).size() == 1 && !records(rec).at(0).name); + // The marker at offset 0 (nothing before it) and data that runs past the file. + const std::vector<std::uint8_t> head = {0xE7, 0xDC, 0x0D, 0, 20, 0, 0, 0, 1, 0, 0, 0}; + CHECK(records(head).empty()); + auto cut = record_bytes("PS_s", 0x40, 3, stored); + cut.pop_back(); + cut.pop_back(); + cut.pop_back(); + // (n still claims the 3 bytes the file no longer has.) + CHECK(records(cut).empty()); + // An empty name ("length" 1, just the NUL). + rec = record_bytes("", 0x32, 3, stored); + CHECK(records(rec).at(0).name && records(rec).at(0).name->empty()); + CHECK(!is_sgd5(std::vector<std::uint8_t>{'S', 'G', 'D'})); +} + +} // namespace + +int main() { + reads_records(); + corrupt_stream_does_not_unpack(); + handles_empty_and_rejects_mismatched_or_truncated_streams(); + edges(); + return test_util::finish("x2w_tool_sgd5_test"); +} diff --git a/tests/xmem_linear_placement.cpp b/tests/xmem_linear_placement.cpp new file mode 100644 index 0000000000..8937d43926 --- /dev/null +++ b/tests/xmem_linear_placement.cpp @@ -0,0 +1,180 @@ +#include "xmem_test_device.h" +#include "desktop_gpu.h" +#include "xmem_section_lease.h" +#include "xmem_page_batch.h" +#include <thread> + +#include <array> +#include <cstring> +#include <stdexcept> +#include <vector> + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void* WINAPI XMemVirtualAlloc(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +extern "C" __declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(ULONG_PTR, ULONG_PTR*, ULONG_PTR*); +extern "C" __declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR, ULONG_PTR*); +extern "C" __declspec(dllimport) void* WINAPI XMemMapPhysicalPages(void*, ULONG_PTR, const ULONG_PTR*); +extern "C" __declspec(dllimport) BOOL WINAPI XMemMapPhysicalPagesScatter(void* const*, ULONG_PTR, const ULONG_PTR*); +extern "C" __declspec(dllimport) ULONG64 WINAPI x2w_xmem_gpu_mapping_generation(); +extern "C" __declspec(dllimport) BOOL WINAPI x2w_xmem_gpu_location(const void*, HANDLE*, ULONG64*); +extern "C" __declspec(dllimport) BOOL WINAPI x2w_xmem_lease_section(UINT, ULONG_PTR, SIZE_T, X2WXMemSectionLease*, SIZE_T); +extern "C" __declspec(dllimport) BOOL WINAPI x2w_xmem_release_section(UINT, ULONG64); +extern "C" __declspec(dllimport) UINT64 x2w_gpu_find_address_test(UINT64, UINT64); +extern "C" __declspec(dllimport) BOOL x2w_desktop_range_test(UINT64, UINT64, ID3D12Resource**, UINT64*); + +using Microsoft::WRL::ComPtr; +constexpr SIZE_T page = 65536, mib = 1 << 20; + +void require(bool ok, const char* what) +{ + if (!ok) throw std::runtime_error(what); +} + +HRESULT create_wrapper(IUnknown* adapter, REFIID iid, void** out) +{ + unsigned char params[64]{}; + return D3D12XboxCreateDevice(adapter, params, iid, out); +} + +int main(int argc, char** argv) try +{ + if (argc < 2 || argc > 3) return 2; + const bool hardware = argc == 3 && !std::strcmp(argv[2], "hardware"); + if (argc == 3 && !hardware) return 2; + const bool linear = std::strcmp(argv[1], "linear") == 0; + if (!linear && std::strcmp(argv[1], "baseline")) return 2; + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_D3D12_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_XMEM_LINEAR_PLACEMENT", linear ? "1" : "0"); + SetEnvironmentVariableA("X2W_XMEM_GPU_POOL", "0"); + SetEnvironmentVariableA("X2W_XMEM_SLAB_DIR", nullptr); + const std::array<SIZE_T, 6> boundaries{0, 10, 11, 38, 85, 185}; + auto* root = static_cast<unsigned char*>(XMemVirtualAlloc(nullptr, 185 * mib, 0x42000, 7, PAGE_NOACCESS)); + require(root != nullptr, "reserve parent"); + for (unsigned i = 0; i < 5; ++i) { + auto* child = root + boundaries[i] * mib; + const SIZE_T bytes = (boundaries[i + 1] - boundaries[i]) * mib; + if (i < 4) require(VirtualFree(child, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), "split child"); + require(XMemVirtualAlloc(child, bytes, 0x20406000, 0x27, PAGE_READWRITE) == child, "register child"); + } + ULONG_PTR count = 185 * mib / page; + std::vector<ULONG_PTR> tokens(count); + require(XMemAllocatePhysicalPages(0x280, &count, tokens.data()) && count == tokens.size(), "initial grant"); + for (unsigned i : {3u, 4u, 0u, 1u, 2u}) { + void* child = root + boundaries[i] * mib; + const ULONG_PTR pages = (boundaries[i + 1] - boundaries[i]) * mib / page; + require(XMemMapPhysicalPages(child, pages, tokens.data() + boundaries[i] * mib / page) == child, "map child"); + } + auto* start = root + 11 * mib; + HANDLE section{}; + ULONG64 base_at{}; + require(x2w_xmem_gpu_location(start, §ion, &base_at), "arena location"); + unsigned mismatches = 0; + for (SIZE_T at = 0; at < 174 * mib; at += page) { + HANDLE h{}; + ULONG64 offset{}; + require(x2w_xmem_gpu_location(start + at, &h, &offset), "page location"); + if (h != section || offset != base_at + at) ++mismatches; + } + require((mismatches == 0) == linear, "physical continuity control"); + std::printf("physical pages %zu, noncontiguous %u\n", 174 * mib / page, mismatches); + bool unmatched = false; + auto wrapper = create_device(!hardware, unmatched, create_wrapper); + if (hardware && !wrapper) return 77; + require(wrapper.Get() != nullptr, "create device wrapper"); + ComPtr<ID3D12Resource> window; + UINT64 at{}; + const BOOL bound = x2w_desktop_range_test(reinterpret_cast<UINT64>(start), 174 * mib, window.GetAddressOf(), &at); + require(!!bound == linear, "full 174 MiB desktop_range control"); + if (bound) { + ComPtr<ID3D12Device> device; + check(window->GetDevice(IID_PPV_ARGS(&device)), "window device"); + const auto readback = make_buffer(device.Get(), 16, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands commands(device.Get(), nullptr); + const SIZE_T offsets[]{0, 27 * mib, 74 * mib, 174 * mib - 4}; + for (unsigned j = 0; j < 4; ++j) { + *reinterpret_cast<UINT*>(start + offsets[j]) = 100 + j; + commands.list->CopyBufferRegion(readback.Get(), j * 4, window.Get(), at + offsets[j], 4); + } + commands.submit_and_wait(device.Get()); + UINT* actual = nullptr; + check(readback->Map(0, nullptr, reinterpret_cast<void**>(&actual)), "read GPU results"); + for (unsigned j = 0; j < 4; ++j) require(actual[j] == 100 + j, "GPU readback across child boundaries"); + readback->Unmap(0, nullptr); + } + ULONG_PTR token = tokens[11 * mib / page], hole = 0; + void* address = start; + void* alias = XMemVirtualAlloc(nullptr, 2 * page, 0x20402000, 0x21, PAGE_READWRITE); + require(alias != nullptr, "reserve alias"); + const auto address_of = [](void* pointer) -> UINT64 { + ComPtr<ID3D12Resource> buffer; + UINT64 offset{}; + return x2w_desktop_range_test(reinterpret_cast<UINT64>(pointer), 4, buffer.GetAddressOf(), &offset) + ? buffer->GetGPUVirtualAddress() + offset : 0; + }; + // A fresh thread cannot have a TLS hit: it consults the shared cache before + // the original thread is allowed to replace either result. + const auto verify_caches = [&](UINT64 expected) { + UINT64 fresh{}; + std::thread lookup([&] { fresh = address_of(alias); }); + lookup.join(); + require(fresh == expected && address_of(alias) == expected, "current GPU address on both cache paths"); + require(x2w_gpu_find_address_test(reinterpret_cast<UINT64>(alias), 4) == expected, "translated buffer binding tracks remaps"); + }; + require(address_of(alias) == 0, "cache negative before first mapping"); + require(XMemMapPhysicalPagesScatter(&alias, 1, &token), "map original grant alias"); + const UINT64 original = address_of(start); + const UINT64 other = address_of(start + page); + require(original && other && original != other, "two distinct GPU backing addresses"); + verify_caches(original); + X2WPageRange range{0, 1, 1}; + X2WPageBatch batch{reinterpret_cast<UINT64>(alias), 1, &range}; + X2WPageBatchStats stats{}; + require(SUCCEEDED(X2WMapPageBatch(1, &batch, reinterpret_cast<UINT64>(start), 2, 0, &stats)) && stats.pagesChanged == 1, + "batch remap alias to next page"); + verify_caches(other); + const auto before = x2w_xmem_gpu_mapping_generation(); + require(SUCCEEDED(X2WMapPageBatch(1, &batch, reinterpret_cast<UINT64>(start), 2, 0, &stats)) && + !stats.pagesChanged && x2w_xmem_gpu_mapping_generation() == before, "unchanged batch keeps the cache warm"); + // The first edit can be installed. The second page is inside the same reservation + // but is now privately committed, forcing the OS placement to fail and roll back. + auto* occupied = static_cast<unsigned char*>(alias) + page; + require(VirtualAlloc2(GetCurrentProcess(), occupied, page, MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, nullptr, 0) == occupied, "occupy rollback control page"); + X2WPageRange move{1, 0, 2}; + X2WPageBatch rejected{reinterpret_cast<UINT64>(alias), 1, &move}; + require(FAILED(X2WMapPageBatch(1, &rejected, reinterpret_cast<UINT64>(start), 2, 0, &stats)) && + x2w_xmem_gpu_mapping_generation() > before, "failed native transaction invalidates cached bindings"); + verify_caches(other); + require(XMemMapPhysicalPages(alias, 1, nullptr) == alias, "unmap alias with cached hit"); + verify_caches(0); + require(XMemMapPhysicalPages(alias, 1, &token) == alias, "map original grant again"); + verify_caches(original); + *static_cast<UINT*>(alias) = 0x12345678; + require(*reinterpret_cast<UINT*>(start) == 0x12345678, "coherent CPU alias"); + X2WXMemSectionLease lease{}; + constexpr UINT version = x2w_xmem_single_page_lease_version; + require(x2w_xmem_lease_section(version, reinterpret_cast<ULONG_PTR>(start), 4, &lease, sizeof(lease)), "pin old slot"); + auto* old = static_cast<UINT*>(MapViewOfFile(lease.section, FILE_MAP_READ, 0, static_cast<DWORD>(lease.section_offset), page)); + require(old != nullptr, "leased bytes"); + require(XMemMapPhysicalPagesScatter(&alias, 1, &hole), "unmap alias"); + require(XMemMapPhysicalPages(root, tokens.size(), nullptr) == root, "unmap complete grant"); + require(XMemFreePhysicalPages(tokens.size(), tokens.data()), "retire complete grant"); + count = 1; + require(XMemAllocatePhysicalPages(0x280, &count, &token) && XMemMapPhysicalPagesScatter(&address, 1, &token), "replacement grant"); + require(*reinterpret_cast<UINT*>(start) == 0, "replacement zero"); + *reinterpret_cast<UINT*>(start) = 0x87654321; + require(*old == 0x12345678, "retired slot unchanged"); + require(UnmapViewOfFile(old) && CloseHandle(lease.section) && x2w_xmem_release_section(version, lease.id), "release retired lease"); + require(XMemMapPhysicalPagesScatter(&address, 1, &hole) && XMemFreePhysicalPages(1, &token) + && XMemAllocatePhysicalPages(0x280, &count, &token) && XMemMapPhysicalPagesScatter(&address, 1, &token), "reuse grant"); + HANDLE reused{}; + ULONG64 reused_at{}; + require(x2w_xmem_gpu_location(start, &reused, &reused_at) && (!linear || (reused == section && reused_at == base_at)) && + *reinterpret_cast<UINT*>(start) == 0, "replacement zeroed and preferred slot reusable after lease release"); + std::printf("desktop_range %s; alias, pin, retirement, reuse passed\n", bound ? "bound; GPU readback 4/4" : "NULL"); + return 0; +} catch (const std::exception& error) { + std::fprintf(stderr, "FAILED: %s, Win32 %lu\n", error.what(), GetLastError()); + return 1; +} diff --git a/tests/xmem_scatter_refusal_check.py b/tests/xmem_scatter_refusal_check.py new file mode 100644 index 0000000000..67900458f8 --- /dev/null +++ b/tests/xmem_scatter_refusal_check.py @@ -0,0 +1,296 @@ +"""Refused scatter maps in the permissive xmem shim (X2W_XMEM_PERMISSIVE=1): the run-shaped batch, two threads +naming the same addresses, and the loud line a refusal must leave behind. + +usage: xmem_scatter_refusal_check.py <xmem.dll> [--control] +Each case runs in a child process (--child <case> <xmem.dll> <log>) with X2W_XMEM_PERMISSIVE=1, +X2W_XMEM_GPU_POOL=0 (no pool section is opened) and X2W_TRAP_LOG=<log>. No D3D12. +Cases: + shape a 717-page batch of 25 scattered ranges in unsorted order, every page already mapped at another + address (a second view, as the startup run's streaming batches): maps, and both views show the same bytes. + race thread A maps and unmaps that batch, thread B maps and unmaps one of its addresses with another page, + for a few seconds. The console applies every call; none may fail. + foreign the target page is a view that the shim did not make: the call fails with error 87, and an + "x2w-xmem REFUSED" line names the entry, each Windows call's error and what VirtualQuery shows there. + unowned a token for a page that was never granted: fails with 87 and a REFUSED line that says so. + remap thread A remaps one address between two pages (each call unmaps and maps it again), thread B checks it: + a plain VirtualQuery sometimes sees it uncommitted (the gap; must be seen, or the case proves nothing), + x2w_xmem_write_settled never refuses it, and x2w_xmem_page_event reports the last map / unmap. + wait x2w_xmem_write_settled_wait with a 250 ms bound: a destination that a second thread maps 50 ms after the + write started is written (after >= 45 ms); the negative control, a destination never mapped, fails after + the bound (>= 250 ms) and writes nothing. +--control: the same cases against a build without the fix (e.g. 08d2ca72): passes when the race case fails and + the foreign / unowned cases leave no REFUSED line (the negative control trips); remap there only shows + the gap (the build has no x2w_xmem_write_settled). +""" +import ctypes as C +import os +from pathlib import Path +import subprocess +import sys +import threading +import time + +PAGE = 0x10000 +PHYSICAL_64K = 0x20400000 +STARTUP_RESERVE = 0x20402000 +MEM_RELEASE = 0x8000 +MEM_REPLACE_PLACEHOLDER, MEM_PRESERVE_PLACEHOLDER = 0x4000, 0x2 +# The 25 destination ranges (pages) of the refused batch of the startup run, in its order; offsets are synthetic. +RANGES = [1, 13, 6, 3, 7, 1, 9, 2, 5, 5, 8, 117, 7, 120, 8, 119, 6, 1, 17, 7, 112, 7, 132, 3, 1] +assert sum(RANGES) == 717 + + +class Shim: + def __init__(self, path): + lib = C.WinDLL(str(Path(path).resolve()), use_last_error=True, winmode=0x900) + k = C.WinDLL("kernelbase.dll", use_last_error=True) + vp, n, dw = C.c_void_p, C.c_size_t, C.c_ulong + def bind(owner, name, args, res): + f = getattr(owner, name) + f.argtypes, f.restype = args, res + return f + self.allocate = bind(lib, "XMemAllocatePhysicalPages", [n, C.POINTER(n), C.POINTER(n)], C.c_int) + self.scatter_raw = bind(lib, "XMemMapPhysicalPagesScatter", [C.POINTER(vp), n, C.POINTER(n)], C.c_int) + self.virtual_alloc = bind(lib, "XMemVirtualAlloc", [vp, n, dw, n, dw], vp) + self.map3 = bind(k, "MapViewOfFile3", [vp, vp, vp, C.c_ulonglong, n, dw, dw, vp, dw], vp) + self.unmap2 = bind(k, "UnmapViewOfFile2", [vp, vp, dw], C.c_int) + self.mapping = bind(k, "CreateFileMappingW", [vp, vp, dw, dw, dw, vp], vp) + self.process = bind(k, "GetCurrentProcess", [], vp)() + self.base = self.virtual_alloc(None, 16 << 30, STARTUP_RESERVE, 0x21, 4) + assert self.base, C.get_last_error() + + def pages(self, count): + got, tokens = C.c_size_t(count), (C.c_size_t * count)() + assert self.allocate(PHYSICAL_64K, C.byref(got), tokens) and got.value == count, C.get_last_error() + return list(tokens) + + def scatter(self, addresses, tokens): + a = (C.c_void_p * len(addresses))(*addresses) + t = (C.c_size_t * len(tokens))(*tokens) + ok = self.scatter_raw(a, len(addresses), t) + return ok, C.get_last_error() + + +def batch_addresses(base): + """717 page addresses in 25 ranges spread over the reservation, in the run's (unsorted) range order.""" + order = [5, 1, 14, 22, 9, 13, 15, 2, 8, 17, 12, 19, 7, 20, 0, 18, 10, 3, 6, 11, 21, 23, 4, 16, 24] + addresses = [] + for slot, pages in zip(order, RANGES): + start = base + 0x10000000 + slot * 0x18000000 # 384 MiB apart, 256 MiB in + addresses += [start + i * PAGE for i in range(pages)] + return addresses + + +def word(address): + return C.c_uint32.from_address(address) + + +def child(case, dll, log): + shim = Shim(dll) + addresses = batch_addresses(shim.base) + tokens = shim.pages(len(addresses) + 16) + pages = tokens[:len(addresses)] + if case == "shape": + home = shim.base + 0x3F0000000 # the pages' first view, as the title's contiguous mapping + ok, err = shim.scatter([home + i * PAGE for i in range(len(pages))], pages) + assert ok, f"first views refused: {err}" + for i in range(len(pages)): + word(home + i * PAGE).value = 0xA5000000 + i + ok, err = shim.scatter(addresses, pages) + assert ok, f"the run-shaped batch was refused: error {err}" + bad = [i for i, a in enumerate(addresses) if word(a).value != 0xA5000000 + i] + assert not bad, f"second views do not show the pages' bytes at entries {bad[:5]}" + word(addresses[0]).value = 0x12345678 + assert word(home).value == 0x12345678, "a write through the second view is not seen through the first" + print("shape ok: 717 pages, 25 ranges, unsorted, second views agree") + return 0 + if case == "race": + other = tokens[len(addresses):] + target = addresses[400] + stop = time.perf_counter() + float(os.environ.get("RACE_SECONDS", "6")) + result = {"a_calls": 0, "a_fail": [], "b_calls": 0, "b_fail": []} + def a(): + while time.perf_counter() < stop: + for toks in (pages, [0] * len(pages)): + ok, err = shim.scatter(addresses, toks) + result["a_calls"] += 1 + if not ok: result["a_fail"].append(err) + def b(): + i = 0 + while time.perf_counter() < stop: + ok, err = shim.scatter([target], [other[i % len(other)] if i % 2 == 0 else 0]) + result["b_calls"] += 1 + if not ok: result["b_fail"].append(err) + i += 1 + threads = [threading.Thread(target=a), threading.Thread(target=b)] + for t in threads: t.start() + for t in threads: t.join() + fails = result["a_fail"] + result["b_fail"] + print(f"race calls A={result['a_calls']} B={result['b_calls']} failures A={len(result['a_fail'])} " + f"B={len(result['b_fail'])} errors={sorted(set(fails))}") + return 3 if fails else 0 + if case == "foreign": + target = addresses[0] + # A view elsewhere in the reservation keeps the shim from coalescing its placeholders after the unmap below. + ok, err = shim.scatter([shim.base + 0x3F0000000], [pages[5]]) + assert ok, err + ok, err = shim.scatter([target], [pages[0]]) + assert ok, err + ok, err = shim.scatter([target], [0]) # unmapped again: a 64 KiB placeholder stays + assert ok, err + section = shim.mapping(C.c_void_p(-1), None, 4, 0, PAGE, None) + assert section + view = shim.map3(section, shim.process, target, 0, PAGE, MEM_REPLACE_PLACEHOLDER, 4, None, 0) + assert view == target, f"the test could not put its own view there: {C.get_last_error()}" + second = target + 0x1000000 # above the target: the target is entry 0 of the sorted call + ok, err = shim.scatter([second, target], [pages[1], pages[0]]) + print(f"foreign view at the target: ok={ok} error={err}") + assert not ok and err == 87, (ok, err) + assert shim.unmap2(shim.process, target, MEM_PRESERVE_PLACEHOLDER) + ok, err = shim.scatter([second, target], [pages[1], pages[0]]) + assert ok, f"after the foreign view is gone the same call must map: {err}" + return 0 + if case == "remap": + lib = C.WinDLL(str(Path(dll).resolve()), use_last_error=True, winmode=0x900) + k = C.WinDLL("kernelbase.dll", use_last_error=True) + k.VirtualQuery.argtypes = [C.c_void_p, C.c_void_p, C.c_size_t] + k.VirtualQuery.restype = C.c_size_t + settled = getattr(lib, "x2w_xmem_write_settled", None) + event = getattr(lib, "x2w_xmem_page_event", None) + if settled: + settled.argtypes, settled.restype = [C.c_void_p, C.c_void_p, C.c_size_t, C.c_size_t], C.c_int + u32, u64 = C.POINTER(C.c_ulong), C.POINTER(C.c_ulonglong) + event.argtypes, event.restype = [C.c_void_p, u32, u64, u32, u64, u64, u64], C.c_int + target = addresses[200] + ok, err = shim.scatter([shim.base + 0x3F0000000], [pages[5]]) # keeps the reservation from coalescing + assert ok, err + ok, err = shim.scatter([target], [pages[0]]) + assert ok, err + stop = time.perf_counter() + float(os.environ.get("RACE_SECONDS", "4")) + counts = {"remaps": 0, "remap_fail": 0, "checks": 0, "gap": 0, "settled": 0, "settled_fail": 0} + def a(): + i = 0 + while time.perf_counter() < stop: + ok, _ = shim.scatter([target], [pages[1 + (i % 2)]]) # P -> Q -> P ...: unmap + map in one call + counts["remaps"] += 1 + counts["remap_fail"] += not ok + i += 1 + def b(): + info = (C.c_ubyte * 48)() + payload = (C.c_ubyte * 16)(*range(16)) + while time.perf_counter() < stop: + assert k.VirtualQuery(target, info, 48) == 48 + state = int.from_bytes(bytes(info[32:36]), "little") + counts["checks"] += 1 + counts["gap"] += state != 0x1000 + if settled: + counts["settled"] += 1 + counts["settled_fail"] += not settled(target, payload, 16, PAGE) + threads = [threading.Thread(target=a), threading.Thread(target=b)] + for t in threads: t.start() + for t in threads: t.join() + line = " ".join(f"{key}={value}" for key, value in counts.items()) + if not settled: + print(f"remap (no x2w_xmem_write_settled in this build): {line}") + return 0 if counts["gap"] else 4 + kind, thread = C.c_ulong(), C.c_ulong() + page, age, serial, remaps = C.c_ulonglong(), C.c_ulonglong(), C.c_ulonglong(), C.c_ulonglong() + view = event(target, C.byref(kind), C.byref(page), C.byref(thread), C.byref(age), C.byref(serial), C.byref(remaps)) + ok, err = shim.scatter([target], [0]) + assert ok, err + view_after = event(target, C.byref(kind), C.byref(page), C.byref(thread), C.byref(age), C.byref(serial), None) + never = C.c_ulong() + view_never = event(shim.base + 0x3E0000000, C.byref(never), None, None, None, None, None) + print(f"remap: {line}; page_event mapped={view} remaps={remaps.value}; after unmap view={view_after} " + f"kind={kind.value} page=0x{page.value:x}; untouched address view={view_never} kind={never.value}") + good = (counts["gap"] > 0 and counts["settled_fail"] == 0 and counts["remap_fail"] == 0 and view == 1 and + remaps.value >= counts["remaps"] - 1 and view_after == 0 and kind.value == 2 and page.value == pages[1 + ((counts["remaps"] - 1) % 2)] >> 4 + and view_never == 0 and never.value == 0) + return 0 if good else 5 + if case == "wait": + lib = C.WinDLL(str(Path(dll).resolve()), use_last_error=True, winmode=0x900) + wait = lib.x2w_xmem_write_settled_wait + wait.argtypes = [C.c_void_p, C.c_void_p, C.c_size_t, C.c_size_t, C.c_ulong, C.POINTER(C.c_ulong)] + wait.restype = C.c_int + ok, err = shim.scatter([shim.base + 0x3F0000000], [pages[5]]) # keeps the reservation from coalescing + assert ok, err + target, never = addresses[300], addresses[301] + payload = (C.c_ubyte * 16)(*range(0xA0, 0xB0)) + def late_map(): + time.sleep(0.05) + ok, err = shim.scatter([target], [pages[2]]) + assert ok, err + mapper = threading.Thread(target=late_map) + waited = C.c_ulong() + mapper.start() + served = wait(target, payload, 16, PAGE, 250, C.byref(waited)) + mapper.join() + content = bytes((C.c_ubyte * 16).from_address(target)) if served else b"" + waited_never = C.c_ulong() + refused = not wait(never, payload, 16, PAGE, 250, C.byref(waited_never)) + print(f"wait: late-mapped destination served={served} after {waited.value} ms content_ok={content == bytes(payload)}; " + f"never-mapped destination refused={refused} after {waited_never.value} ms") + good = served and 45 <= waited.value < 250 and content == bytes(payload) and refused and waited_never.value >= 250 + return 0 if good else 6 + if case == "unowned": + ok, err = shim.scatter([addresses[0], addresses[1]], [pages[0], (max(tokens) >> 4 << 4) + (1000 << 4)]) + print(f"unowned token: ok={ok} error={err}") + assert not ok and err == 87, (ok, err) + return 0 + raise SystemExit(f"unknown case {case}") + + +def run(case, dll, log): + if log.exists(): log.unlink() + env = dict(os.environ, X2W_XMEM_PERMISSIVE="1", X2W_XMEM_GPU_POOL="0", X2W_TRAP_LOG=str(log)) + for name in ("X2W_XMEM_SLAB_DIR", "X2W_XMEM_SLAB_BUDGET_MIB", "X2W_XMEM_SHARED_VIEWS", "X2W_XMEM_GPU_MIRROR"): + env.pop(name, None) + done = subprocess.run([sys.executable, "-B", __file__, "--child", case, str(dll), str(log)], env=env, + capture_output=True, text=True, timeout=180) + text = log.read_text(errors="replace") if log.exists() else "" + return done.returncode, done.stdout.strip(), text + + +def main(): + if sys.argv[1] == "--child": + return child(sys.argv[2], sys.argv[3], sys.argv[4]) + dll = Path(sys.argv[1]).resolve() + control = "--control" in sys.argv + logs = Path(os.environ.get("XMEM_CHECK_LOGS", Path(dll).parent)) + results = {} + cases = ["shape", "race", "foreign", "unowned", "remap"] + ([] if control else ["wait"]) + for case in cases: + code, out, text = run(case, dll, logs / f"scatter_{case}.log") + refused = [line for line in text.splitlines() if "x2w-xmem REFUSED" in line] + results[case] = (code, out, refused, text) + print(f"[{case}] exit {code}: {out}") + for line in refused[:2]: + print(f" {line[:700]}") + failures = [] + if not control: + if results["shape"][0]: failures.append("shape refused") + if results["race"][0]: failures.append("race: a call failed") + code, out, refused, _ = results["foreign"] + if code: failures.append("foreign: wrong outcome") + need = ("entry 0 of 2", "MapViewOfFile3 err 487", "split err 87", "state 0x1000", "type 0x40000", "no view") + if not refused or not all(n in refused[0] for n in need): + failures.append(f"foreign: REFUSED line missing or incomplete (needs {need})") + code, out, refused, _ = results["unowned"] + if code: failures.append("unowned: wrong outcome") + if not refused or "NOT granted" not in refused[0] or "not granted (era_physical::owns)" not in refused[0]: + failures.append("unowned: REFUSED line missing or does not name the check") + if results["remap"][0]: failures.append("remap: gap not seen, or a settled write / page event was wrong") + if results["wait"][0]: failures.append("wait: late map not served after the wait, or never-mapped not refused after the bound") + print("FAIL: " + "; ".join(failures) if failures else "PASS xmem_scatter_refusal (shape, race, foreign, unowned, remap, wait)") + else: + if results["shape"][0]: failures.append("shape refused on the control build too") + if not results["race"][0]: failures.append("race did not fail on the control build") + if results["foreign"][2] or results["unowned"][2]: failures.append("control build printed REFUSED lines") + if results["remap"][0]: failures.append("remap: the gap was not seen on the control build") + print("FAIL control: " + "; ".join(failures) if failures else + "PASS control: the build without the fix fails the race and logs no cause") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/bcpack_bcn.py b/tools/bcpack_bcn.py new file mode 100644 index 0000000000..69b089225c --- /dev/null +++ b/tools/bcpack_bcn.py @@ -0,0 +1,235 @@ +"""Reference BCPack block reconstruction for BC3, BC4 and BC5, kept in step with bcpack_decoder.h. + +The lane layouts below were checked against the entropy layer: with them, every BC3, BC4 and BC5 +interval of the local test archives decodes to exactly its logical size, consumes exactly its +compressed bytes and ends every lane in a legal rANS state. The same layouts are published by +bcpack-rs (https://github.com/Ahmet-Dedeler/bcpack-rs, revision c55c5fad, MIT OR Apache-2.0). + +Block reconstruction follows the bcpack-rs reference rules as adapted into +src/startup_stubs/bcpack_decoder.h: a block's endpoint reference is x + unzigzag(d) and its index +reference is x (lanes 0 and 1), references beyond the decoded history read a 255-entry dictionary, +residuals are unzigzagged modulo the field width, pair and quadrant symbols are ranks into the +tables of src/startup_stubs/bcpack_tables_bcn.inl (read here, not duplicated), and an alpha +endpoint is stored as its state XOR 0x80. + +The rank tables and dictionaries are fitted by bcpack-rs and are not independently verified; see +docs in the C++ header. The BC6H entry is a lane layout only (no block reconstruction). +""" +import ast +import re +from pathlib import Path + +from _bcpack_rans import BCPackError, decode_lanes + +ROOT = Path(__file__).resolve().parents[1] +TABLES = ROOT / "src" / "startup_stubs" / "bcpack_tables_bcn.inl" + +# format: (alphabet bits per lane = symbol width - 1, block bytes, symbols per lane per block) +LAYOUTS = { + 3: ((3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7), 16, 2), + 4: ((7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5), 8, 1), + 5: ((3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5), 16, 2), + 6: ((3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4), 16, 2), +} + +ALPHA_CODE = (0, 2, 3, 4, 5, 6, 7, 1) # ramp position -> BC4 index code +COLOUR_CODE = (0, 2, 3, 1) # ramp position -> BC1 index code +ALPHA_POSITION = tuple(ALPHA_CODE.index(c) for c in range(8)) +COLOUR_POSITION = tuple(COLOUR_CODE.index(c) for c in range(4)) + +_TABLE_CACHE = {} + + +def _array(text, name): + m = re.search(r"\b" + re.escape(name) + r"\s*(?:\[[^\]]*\])*\s*=\s*\{", text) + if not m: + raise ValueError("table %s not found in %s" % (name, TABLES.name)) + depth = 0 + for i in range(m.end() - 1, len(text)): + if text[i] == "{": + depth += 1 + elif text[i] == "}": + depth -= 1 + if not depth: + body = text[m.end() - 1:i + 1] + break + else: + raise ValueError("table %s: unbalanced braces" % name) + return ast.literal_eval(body.replace("{", "[").replace("}", "]")) + + +def tables(): + """Rank tables and dictionaries parsed from bcpack_tables_bcn.inl (cached).""" + if not _TABLE_CACHE: + text = re.sub(r"//[^\n]*", "", TABLES.read_text(encoding="utf-8")) + for name in ("RANK_PAIR_BC4", "RANK_PAIR_BC5", "RANK_PAIR_BC3_ALPHA", "RANK_QUAD_BC3_COLOUR", + "BC4_DICTIONARY", "BC5_DICTIONARY", "BC3_DICTIONARY"): + _TABLE_CACHE[name] = _array(text, name) + return _TABLE_CACHE + + +def zigzag(v): + return 2 * v if v >= 0 else -2 * v - 1 + + +def unzigzag(v): + return -((v + 1) >> 1) if v & 1 else v >> 1 + + +def residual(sym, bits): + return unzigzag(sym) & ((1 << bits) - 1) + + +def interleave(even, odd): + out = 0 + for k in range(4): + out |= ((even >> k) & 1) << (2 * k) | ((odd >> k) & 1) << (2 * k + 1) + return out + + +def deinterleave(byte): + even = odd = 0 + for k in range(4): + even |= ((byte >> (2 * k)) & 1) << k + odd |= ((byte >> (2 * k + 1)) & 1) << k + return even, odd + + +def pack_alpha(e0, e1, positions): + v = (e0 ^ 0x80) | (e1 ^ 0x80) << 8 + for p in range(16): + v |= ALPHA_CODE[positions[p] & 7] << (16 + 3 * p) + return v.to_bytes(8, "little") + + +def pack_colour(ep, positions): + c0 = ep[0] << 11 | ep[1] << 5 | ep[2] + c1 = ep[3] << 11 | ep[4] << 5 | ep[5] + w = 0 + for p in range(16): + w |= COLOUR_CODE[positions[p] & 3] << (2 * p) + return c0.to_bytes(2, "little") + c1.to_bytes(2, "little") + w.to_bytes(4, "little") + + +def _source(hist, dictionary, i, r, n_ep, n_ix): + if r == 0: + return [0] * n_ep, [0] * n_ix + if r <= i: + return hist[i - r] + k = r - i - 1 + if k < len(dictionary): + ep, ix = dictionary[k] + return list(ep), list(ix) + return [0] * n_ep, [0] * n_ix + + +def _references(syms, i, per): + if per == 1: + d, x = syms[0][i] & 0xFF, syms[1][i] & 0xFF + else: + d = interleave(syms[0][2 * i], syms[0][2 * i + 1]) + x = interleave(syms[1][2 * i], syms[1][2 * i + 1]) + return (x + unzigzag(d)) & 0xFF, x + + +def blocks_bc4(syms, n): + t = tables() + pairs, dic = t["RANK_PAIR_BC4"], t["BC4_DICTIONARY"] + hist, out = [], bytearray() + for i in range(n): + er, xr = _references(syms, i, 1) + ep_ref, _ = _source(hist, dic, i, er, 2, 16) + _, ix_ref = _source(hist, dic, i, xr, 2, 16) + ep = [(ep_ref[e] + residual(syms[2 + e][i], 8)) & 0xFF for e in range(2)] + ix = [0] * 16 + for k in range(8): + a, b = pairs[syms[4 + k][i] & 63] + ix[2 * k] = (ix_ref[2 * k] + a) & 7 + ix[2 * k + 1] = (ix_ref[2 * k + 1] + b) & 7 + hist.append((ep, ix)) + out += pack_alpha(ep[0], ep[1], ix) + return bytes(out) + + +def blocks_bc5(syms, n): + t = tables() + pairs, dic = t["RANK_PAIR_BC5"], t["BC5_DICTIONARY"] + hist, out = [], bytearray() + for i in range(n): + er, xr = _references(syms, i, 2) + ep_ref, _ = _source(hist, dic, i, er, 4, 32) + _, ix_ref = _source(hist, dic, i, xr, 4, 32) + ep, ix = [0] * 4, [0] * 32 + for c in range(2): + for e in range(2): + ep[2 * c + e] = (ep_ref[2 * c + e] + residual(syms[2 + c][2 * i + e], 8)) & 0xFF + for l in range(4): + for h in range(2): + a, b = pairs[syms[4 + 4 * c + l][2 * i + h] & 63] + p = 16 * c + 4 * l + 2 * h + ix[p] = (ix_ref[p] + a) & 7 + ix[p + 1] = (ix_ref[p + 1] + b) & 7 + hist.append((ep, ix)) + out += pack_alpha(ep[0], ep[1], ix[:16]) + pack_alpha(ep[2], ep[3], ix[16:]) + return bytes(out) + + +QUAD_ORIGIN = ((0, 0), (2, 0), (0, 2), (2, 2)) # TL, TR, BL, BR +QUAD_STEP = ((0, 0), (1, 0), (0, 1), (1, 1)) + + +def blocks_bc3(syms, n): + t = tables() + pairs, quads, dic = t["RANK_PAIR_BC3_ALPHA"], t["RANK_QUAD_BC3_COLOUR"], t["BC3_DICTIONARY"] + widths = (5, 6, 5) + hist, out = [], bytearray() + for i in range(n): + er, xr = _references(syms, i, 2) + ep_ref, _ = _source(hist, dic, i, er, 8, 32) + _, ix_ref = _source(hist, dic, i, xr, 8, 32) + ep, ix = [0] * 8, [0] * 32 + for e in range(2): + ep[e] = (ep_ref[e] + residual(syms[2][2 * i + e], 8)) & 0xFF + for l in range(4): + for h in range(2): + a, b = pairs[syms[3 + l][2 * i + h] & 63] + p = 4 * l + 2 * h + ix[p] = (ix_ref[p] + a) & 7 + ix[p + 1] = (ix_ref[p + 1] + b) & 7 + for c in range(3): + mask = (1 << widths[c]) - 1 + ep[2 + c] = (ep_ref[2 + c] + residual(syms[7 + c][2 * i], widths[c])) & mask + ep[5 + c] = (ep_ref[5 + c] + residual(syms[7 + c][2 * i + 1], widths[c])) & mask + for q in range(4): + sym = syms[10 + (q >> 1)][2 * i + (q & 1)] & 0xFF + ox, oy = QUAD_ORIGIN[q] + for k in range(4): + dx, dy = QUAD_STEP[k] + p = 16 + 4 * (oy + dy) + ox + dx + ix[p] = (ix_ref[p] + quads[sym][k]) & 3 + hist.append((ep, ix)) + out += pack_alpha(ep[0], ep[1], ix[:16]) + pack_colour(ep[2:8], ix[16:]) + return bytes(out) + + +RECONSTRUCT = {3: blocks_bc3, 4: blocks_bc4, 5: blocks_bc5} + + +def lane_symbols(data, fmt, output_size): + """Entropy-decode one interval into per-lane symbols for `output_size` bytes of blocks.""" + ab, block, per = LAYOUTS[fmt] + if output_size <= 0 or output_size % block: + raise ValueError("output size is not a whole number of %d-byte blocks" % block) + n = output_size // block + result = decode_lanes(data, list(ab), [n * per] * len(ab)) + if any(data[result["consumed"]:]): + raise BCPackError("non-zero trailing data after byte %d" % result["consumed"]) + return result["syms"], n + + +def decode(data, fmt, output_size): + """Decode a BCPack BC3/BC4/BC5 stream into `output_size` bytes of BCn blocks.""" + if fmt not in RECONSTRUCT: + raise ValueError("BCPack format %d has no block reconstruction here" % fmt) + syms, n = lane_symbols(data, fmt, output_size) + return RECONSTRUCT[fmt](syms, n) diff --git a/tools/disasm_rdna2.py b/tools/disasm_rdna2.py index 131cb807fe..849d98bad6 100644 --- a/tools/disasm_rdna2.py +++ b/tools/disasm_rdna2.py @@ -1687,6 +1687,49 @@ def _decode_vop2_dpp(w1: int, vdst: int, vsrc1: int, src0: int, op: int, op_name return (8, dpp_name, asm, comment) +def _decode_vopc_dpp(w1: int, vsrc1: int, src0: int, op_name: str, comment: str) -> tuple[int, str, str, str]: + """Decode a GFX10 VOPC DPP8 (src0=233/234) or DPP16 (src0=250) 8-byte instruction. + + The second dword has the VOP2 DPP layout (src0 VGPR [7:0], DPP16 control [16:8], fi 18, bound_ctrl 19, src0 + neg/abs 20/21, src1 neg/abs 22/23, bank_mask [27:24], row_mask [31:28]; DPP8 lane selects [31:8]); the result + goes to VCC (v_cmp) or EXEC (v_cmpx), as in the e32 form. LLVM 15 does not decode VOPC DPP for GFX10 (LLVM has + VOPC DPP from GFX11 on, printed `v_cmp_<op>_dpp vcc_lo, ...`, the spelling used here). Evidence for GFX10: + compiled pixel programs carry VOPC words with src0 250 followed by a dword of this layout (fi and bound_ctrl + set, row/bank masks 0xf, a quad_perm control) and read VCC afterwards. 64-bit compares are refused, as are + float modifiers on integer compares and src1 modifiers on v_cmp_class.""" + is_dpp8 = src0 in (233, 234) + form = "DPP8" if is_dpp8 else "DPP16" + kind = "vopc_dpp8" if is_dpp8 else "vopc_dpp16" + if op_name.startswith("v_vopc_") or op_name.endswith(("_f64_e32", "_i64_e32", "_u64_e32")): + return (8, kind, f"{op_name} <unsupported {form}>", f"VOPC {form} is not supported for this opcode") + base = op_name[:-4] if op_name.endswith("_e32") else op_name + dpp_name = f"{base}_dpp" + is_float = base.endswith(("_f32", "_f16")) and "_class_" not in base + src0_vgpr = w1 & 0xff + if is_dpp8: + ctrl = _format_dpp8_ctrl(w1, 1 if src0 == 234 else 0) + src0_str, src1_str = f"v{src0_vgpr}", f"v{vsrc1}" + else: + dpp_ctrl_str = _format_dpp16_ctrl((w1 >> 8) & 0x1ff) + if dpp_ctrl_str is None: + return (8, kind, f"{op_name} <unsupported DPP16>", "Invalid GFX10 DPP16 control") + fi, bound_ctrl = (w1 >> 18) & 1, (w1 >> 19) & 1 + src0_neg, src0_abs, src1_neg, src1_abs = ((w1 >> b) & 1 for b in (20, 21, 22, 23)) + if not is_float and (src0_neg or src0_abs or src1_neg or src1_abs): + return (8, kind, f"{op_name} <unsupported DPP16>", "Invalid VOPC DPP16 modifier") + if "_class_" in base and (src1_neg or src1_abs): + return (8, kind, f"{op_name} <unsupported DPP16>", "Invalid VOPC DPP16 modifier") + src0_str = _format_operand_modifiers(f"v{src0_vgpr}", src0_abs, src0_neg) + src1_str = _format_operand_modifiers(f"v{vsrc1}", src1_abs, src1_neg) + ctrl = (f"{dpp_ctrl_str} row_mask:0x{(w1 >> 28) & 0xf:x} bank_mask:0x{(w1 >> 24) & 0xf:x}" + f"{' bound_ctrl:1' if bound_ctrl else ''}{' fi:1' if fi else ''}") + if base.startswith("v_cmpx_"): + asm = f"{dpp_name} {src0_str}, {src1_str} {ctrl}" + else: + asm = f"{dpp_name} vcc_lo, {src0_str}, {src1_str} {ctrl}" + return (8, dpp_name, asm, comment) + + def _vop_extension(data: bytes, offset: int, encoding: str, op_name: str, src0: int) -> tuple[int, str, str, str]: """Consume a DPP8, DPP16 or SDWA instruction as one 8-byte record; its operands are not decoded.""" form = VOP_EXTENSION_FORMS[src0] @@ -2556,8 +2599,7 @@ def sopc_operand(reg_id: int, wide: bool) -> str: op_name, comment = op_info length = 4 literal = None - if src0 in (233, 234, 250): - return _vop_extension(data, offset, "vopc", op_name, src0) + # LOCAL: VOPC DPP16/DPP8 is decoded by _decode_vopc_dpp below (upstream returns _vop_extension here). if src0 in (249, 255): extension = "SDWA" if src0 == 249 else "literal" if offset + 8 > len(data): @@ -2567,6 +2609,11 @@ def sopc_operand(reg_id: int, wide: bool) -> str: return _decode_vopc_sdwa(w1, vsrc1, op_name, comment) literal, = struct.unpack_from("<I", data, offset + 4) length = 8 + if src0 in (233, 234, 250): + if offset + 8 > len(data): + return (4, "vopc_truncated", f"{op_name} <truncated>", "Incomplete VOPC DPP") + w1, = struct.unpack_from("<I", data, offset + 4) + return _decode_vopc_dpp(w1, vsrc1, src0, op_name, comment) wide0 = op_name.endswith(("_f64_e32", "_i64_e32", "_u64_e32")) wide1 = wide0 and "_class_" not in op_name if literal is not None: diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index cf6e459b48..56a385466a 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -176,8 +176,12 @@ def container_image(program, *, stage): return image -def container_code(program, *, stage, llvm=None, cpu=b"gfx1013", features=b""): - """Extract the stage-specific instruction stream from a DXIL program part.""" +def container_code(program, *, stage, llvm=None, cpu=b"gfx1013", features=b"", vertex_data=False): + """Extract the stage-specific instruction stream from a DXIL program part. + + vertex_data: a vertex stage (1) whose bounded section holds more than one S_ENDPGM word is returned whole + instead of refused; the caller must prove its single reachable exit (gfx2hlsl.bound_vertex_code), the + words after it being data such as a PC-relative table.""" image = container_image(program, stage=stage) start = struct.unpack_from("<I", image, 192)[0] + 40 if start < 196 or start % 4 or start + 4 > len(image): @@ -191,6 +195,8 @@ def container_code(program, *, stage, llvm=None, cpu=b"gfx1013", features=b""): if (stage in (0, 5) or mesh) and markers == 2 and llvm is not None: _check_two_exits(code, llvm, cpu=cpu, features=features, mesh=mesh) return code + if stage == 1 and vertex_data: + return code raise ValueError("Unverified multi-exit program") # Older fixtures lack the section extent; preserve their unique-marker rule. if stage != 0: diff --git a/tools/shader_material_fields.mjs b/tools/shader_material_fields.mjs new file mode 100644 index 0000000000..8d82f0f2c4 --- /dev/null +++ b/tools/shader_material_fields.mjs @@ -0,0 +1,65 @@ +// node tools/shader_material_fields.mjs path/to/dxc.exe path/to/<shader-key>.dxil [...] +// Save stdout to a text file and set X2W_MATERIAL_FIELDS_PROFILE to its path before launch. +// Writes C++ rows for fields that feed resource handles of actual texture-sampling instructions. +import { readFileSync } from "node:fs"; +import { basename } from "node:path"; +import { execFileSync } from "node:child_process"; + +function sampleFields(ir) { + const definitions = new Map(); + for (const m of ir.matchAll(/^ %(\d+) = ([^;\r\n]+)/gm)) definitions.set(m[1], m[2].trim()); + function match(id, pattern) { return pattern.exec(definitions.get(id) ?? ""); } + function input(id, pattern) { return match(id, pattern)?.[1]; } + function handle(id) { + return input(id, /^call %dx.types.Handle @dx\.op\.annotateHandle\(i32 216, %dx.types.Handle %(\d+),/); + } + function heapIndex(id) { + return input(handle(id), /^call %dx.types.Handle @dx\.op\.createHandleFromHeap\(i32 218, i32 %(\d+), i1 false, i1 false\)$/); + } + function unclamp(id) { + return input(id, /^call i32 @dx\.op\.binary\.i32\(i32 40, i32 %(\d+), i32 2097151\)$/); + } + function unshift(id) { return input(id, /^lshr i32 %(\d+), 5$/); } + function rootWord(id) { + const field = match(id, /^extractvalue %dx.types.CBufRet.i32 %(\d+), (\d+)$/); + if (!field) return; + const load = match(field[1], /^call %dx.types.CBufRet.i32 @dx\.op\.cbufferLoadLegacy.i32\(i32 59, %dx.types.Handle %(\d+), i32 (\d+)\)$/); + if (load && match(handle(load[1]), /^call %dx.types.Handle @dx\.op\.createHandleFromBinding\(i32 217, %dx.types.ResBind \{ i32 0, i32 0, i32 0, i8 2 \}, i32 0, i1 false\)$/)) + return 4 * Number(load[2]) + Number(field[2]); + } + function materialOffset(sampleHandle) { + const shifted = unshift(unclamp(heapIndex(sampleHandle))); + let word = input(shifted, /^shl i32 %(\d+), 5$/); + word = input(word, /^bitcast float %(\d+) to i32$/) ?? word; + const raw = input(word, /^extractvalue %dx.types.ResRet.(?:f32|i32) %(\d+), 0$/); + const load = match(raw, /^call %dx.types.ResRet.(?:f32|i32) @dx\.op\.rawBufferLoad\.(?:f32|i32)\(i32 139, %dx.types.Handle %(\d+), i32 %(\d+), i32 undef, i8 1, i32 4\)$/); + if (!load) return; + const regularIndex = input(heapIndex(load[1]), /^or i32 %(\d+), 2097152$/); + const tableBase = input(unshift(unclamp(regularIndex)), /^add i32 %(\d+), 2752$/); + if (rootWord(tableBase) !== 8) return; + const offset = match(load[2], /^add i32 %(\d+), (\d+)$/); + if (rootWord(offset ? offset[1] : load[2]) !== 14) return; + return offset ? Number(offset[2]) : 0; + } + let mask = 0; + for (const expression of definitions.values()) { + const sample = /@dx\.op\.sample\w*\.f32\(i32 \d+, %dx.types.Handle %(\d+),/.exec(expression); + if (!sample) continue; + const offset = materialOffset(sample[1]); + if (offset >= 0 && offset < 64 && offset % 4 === 0) mask |= 1 << (offset / 4); + } + return mask; +} + +const [dxc, ...files] = process.argv.slice(2); +if (!dxc || !files.length) throw Error("Expected a DXC executable and one or more keyed DXIL files"); +for (const path of files.sort((a, b) => basename(a).localeCompare(basename(b)))) { + const key = basename(path, ".dxil"); + const code = readFileSync(path); + if (!/^[0-9a-f]{16}$/.test(key) || code.toString("ascii", 0, 4) !== "DXBC") throw Error(path); + const ir = execFileSync(dxc, ["-dumpbin", path], { encoding: "utf8", maxBuffer: 32 << 20 }); + const mask = sampleFields(ir); + if (!mask) continue; + const hex = (v, width) => v.toString(16).padStart(width, "0"); + console.log([key, hex(code.readBigUInt64LE(4), 16), hex(code.readBigUInt64LE(12), 16), hex(mask, 4)].join(" ")); +} diff --git a/tools/startup/compute_harness.cpp b/tools/startup/compute_harness.cpp new file mode 100644 index 0000000000..39805d29eb --- /dev/null +++ b/tools/startup/compute_harness.cpp @@ -0,0 +1,401 @@ +// Offline harness for translated compute shaders (startup tools): runs one compiled compute shader with Dispatch on +// WARP ONLY (there is no hardware option: a hang of a translated shader on a GPU can take the desktop down), with +// the root layout the runtime uses for translated dispatches (src/startup_stubs/d3d12_compute.inl load_compute): +// [0] 32-bit constants b0 (the manifest's entry values; at least one) +// non-heap: [1] table: n SRVs t0..t(n-1), then n UAVs u0..u(n-1) +// heap: [1] table: t0, t1 space1 (heapmem, vinfo), [2] the n+n table, root flag CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; +// title view id i, kind k (gfx2hlsl HEAP kinds: 4 buffer SRV, 7 buffer UAV) at heap index 262152 + 8 i + k, +// empty views at 262144 + k. +// The runtime binds heapmem and vinfo as ROOT SRVs; here they are bounded raw views in a table (a root SRV has no +// bounds check, and the translation's vfmt() calls vinfo.GetDimensions). Every buffer is one default-heap resource in +// UNORDERED_ACCESS state; SRVs and UAVs are raw (R32_TYPELESS) views of it. All resources are written back. +// +// usage: compute_harness <cfg.txt> [--debug] (also: compute_harness --caps) +// cfg lines: +// cs <cso> groups <x> <y> <z> consts <n> <v0> ... <v(n-1)> +// nres <n> (table views; every slot not given by a view line is a null raw view) +// res <k> <file> buffer resource k with the file's bytes (size rounded up to 16) +// view <i> srv|uav <k> <byte offset, 16-aligned> <bytes> table slot i +// heap <heapmem file> <vinfo file> +// vdesc <file> (isa-gaps, `heapwords 1`) the 32-byte-per-view-id gfx10 words at t3 space1; t2 space1 +// (the runtime's raw V# table, `heapraw 1`) is then a null view +// hview <id> <kind 4|7> <k> <byte offset, 16-aligned> <bytes> +// out <prefix> writes <prefix>.res<k> for every resource +// Exit: 0 ok, 1 D3D12 failure, 2 bad cfg, 3 the GPU did not finish within 60 s (fatal; nothing written), 77 no SM 6.6 +// when the cfg needs it. +// +// Build (x64 Developer prompt): cl /nologo /EHsc /O2 /std:c++17 compute_harness.cpp d3d12.lib dxgi.lib +#include <windows.h> +#include <d3d12.h> +#include <dxgi1_6.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <map> +#include <sstream> +#include <string> +#include <vector> + +static ID3D12InfoQueue* g_info = nullptr; + +static void dump_messages() { + if (!g_info) return; + UINT64 n = g_info->GetNumStoredMessages(); + for (UINT64 i = 0; i < n && i < 64; ++i) { + SIZE_T size = 0; + g_info->GetMessage(i, nullptr, &size); + std::vector<char> buf(size); + auto* m = reinterpret_cast<D3D12_MESSAGE*>(buf.data()); + g_info->GetMessage(i, m, &size); + std::printf("debug-layer: severity %d id %d: %.*s\n", (int)m->Severity, (int)m->ID, (int)m->DescriptionByteLength, + m->pDescription); + } + std::printf("debug-layer messages: %llu\n", (unsigned long long)n); +} + +#define CHECK(x) \ + do { \ + HRESULT hr_ = (x); \ + if (FAILED(hr_)) { \ + std::fprintf(stderr, "%s failed: 0x%08lx (line %d)\n", #x, hr_, __LINE__); \ + dump_messages(); \ + return 1; \ + } \ + } while (0) + +template <typename T> struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T** operator&() { return &p; } + T* operator->() const { return p; } + operator T*() const { return p; } +}; + +static std::vector<char> read_file(const std::string& path) { + std::ifstream f(path, std::ios::binary); + return std::vector<char>((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); +} + +static D3D12_RESOURCE_DESC buffer_desc(UINT64 size, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = size < 16 ? 16 : (size + 15) & ~15ull; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + return d; +} + +static D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3D12_RESOURCE_STATES b) { + D3D12_RESOURCE_BARRIER x{}; + x.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + x.Transition.pResource = r; + x.Transition.StateBefore = a; + x.Transition.StateAfter = b; + x.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + return x; +} + +typedef LONG(WINAPI* RtlGetVersionFn)(OSVERSIONINFOW*); + +struct View { UINT slot = 0; bool uav = false; UINT res = 0; UINT64 offset = 0, bytes = 0; }; +struct HView { UINT id = 0, kind = 4, res = 0; UINT64 offset = 0, bytes = 0; }; + +int main(int argc, char** argv) { + if (argc < 2) { + std::fprintf(stderr, "usage: compute_harness <cfg.txt> [--debug] | --caps\n"); + return 2; + } + std::setvbuf(stdout, nullptr, _IONBF, 0); // a crash must not lose the progress lines + const bool caps_only = std::string(argv[1]) == "--caps"; + bool debug = false; + for (int i = 2; i < argc; ++i) debug |= std::string(argv[i]) == "--debug"; + std::string cs_path, out; + UINT groups[3] = {1, 1, 1}, nres = 0; + std::vector<UINT> consts; + std::map<UINT, std::string> res_files; + std::vector<View> views; + std::vector<HView> hviews; + std::string heapmem_path, vinfo_path, vdesc_path; + if (!caps_only) { + std::ifstream cfg(argv[1]); + if (!cfg) { std::fprintf(stderr, "cfg: cannot read %s\n", argv[1]); return 2; } + std::string line; + while (std::getline(cfg, line)) { + std::istringstream s(line); + std::string key; + s >> key; + if (key == "cs") std::getline(s >> std::ws, cs_path); + else if (key == "groups") s >> groups[0] >> groups[1] >> groups[2]; + else if (key == "consts") { UINT n = 0; s >> n; consts.resize(n); for (auto& c : consts) s >> c; } + else if (key == "nres") s >> nres; + else if (key == "res") { UINT k; std::string p; s >> k; std::getline(s >> std::ws, p); res_files[k] = p; } + else if (key == "view") { View v; std::string t; s >> v.slot >> t >> v.res >> v.offset >> v.bytes; v.uav = t == "uav"; views.push_back(v); } + else if (key == "heap") s >> heapmem_path >> vinfo_path; + else if (key == "vdesc") std::getline(s >> std::ws, vdesc_path); + else if (key == "hview") { HView v; s >> v.id >> v.kind >> v.res >> v.offset >> v.bytes; hviews.push_back(v); } + else if (key == "out") std::getline(s >> std::ws, out); + else if (!key.empty() && key[0] != '#') { std::fprintf(stderr, "cfg: unknown line '%s'\n", line.c_str()); return 2; } + } + if (cs_path.empty() || out.empty()) { std::fprintf(stderr, "cfg: needs cs and out\n"); return 2; } + for (const auto& v : views) + if (v.slot >= nres || !res_files.count(v.res) || (v.offset & 15)) { std::fprintf(stderr, "cfg: bad view slot %u\n", v.slot); return 2; } + for (const auto& v : hviews) + if (v.id >= 90000 || (v.kind != 4 && v.kind != 7) || !res_files.count(v.res) || (v.offset & 15)) { + std::fprintf(stderr, "cfg: bad hview %u\n", v.id); + return 2; + } + if (consts.empty()) consts.push_back(0); + } + const bool heap = !heapmem_path.empty(); + + OSVERSIONINFOW os{sizeof(os)}; + if (auto fn = (RtlGetVersionFn)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion")) fn(&os); + std::printf("windows %lu.%lu.%lu\n", os.dwMajorVersion, os.dwMinorVersion, os.dwBuildNumber); + if (debug) { + Ref<ID3D12Debug> dbg; + if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&dbg)))) dbg->EnableDebugLayer(); + } + std::printf("debug layer: %s\n", debug ? "on" : "off"); + Ref<IDXGIFactory6> factory; + CHECK(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory))); + Ref<IDXGIAdapter1> adapter; + CHECK(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))); // WARP ONLY + DXGI_ADAPTER_DESC1 ad{}; + adapter->GetDesc1(&ad); + if (!(ad.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { std::fprintf(stderr, "not a software adapter: refusing\n"); return 1; } + LARGE_INTEGER umd{}; + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &umd); + std::printf("adapter: %ls (vendor %04x device %04x) driver %u.%u.%u.%u\n", ad.Description, ad.VendorId, ad.DeviceId, + HIWORD(umd.HighPart), LOWORD(umd.HighPart), HIWORD(umd.LowPart), LOWORD(umd.LowPart)); + Ref<ID3D12Device> device; + CHECK(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device))); + if (debug && SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&g_info)))) g_info->SetMuteDebugOutput(FALSE); + D3D12_FEATURE_DATA_D3D12_OPTIONS1 o1{}; + device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &o1, sizeof(o1)); + D3D12_FEATURE_DATA_D3D12_OPTIONS opt{}; + device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &opt, sizeof(opt)); + D3D12_FEATURE_DATA_SHADER_MODEL sm{D3D_SHADER_MODEL_6_7}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &sm, sizeof(sm)))) { + sm.HighestShaderModel = D3D_SHADER_MODEL_6_6; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &sm, sizeof(sm)))) sm.HighestShaderModel = D3D_SHADER_MODEL_5_1; + } + std::printf("caps: wave ops %d lanes %u-%u, shader model 0x%x, resource binding tier %d\n", (int)o1.WaveOps, + o1.WaveLaneCountMin, o1.WaveLaneCountMax, (unsigned)sm.HighestShaderModel, (int)opt.ResourceBindingTier); + if (caps_only) return 0; + if (heap && sm.HighestShaderModel < D3D_SHADER_MODEL_6_6) { std::printf("capability skip: no SM 6.6\n"); return 77; } + + // root signature (d3d12_compute.inl load_compute layout, bounded space1 views: see the header) + const UINT n = nres; + D3D12_DESCRIPTOR_RANGE1 ranges[2] = {}; + ranges[0] = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, n, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, 0}; + ranges[1] = {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, n, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, n}; + const bool vdesc = !vdesc_path.empty(); + if (vdesc && !heap) { std::fprintf(stderr, "cfg: vdesc without heap\n"); return 2; } + D3D12_DESCRIPTOR_RANGE1 space1{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, vdesc ? 4u : 2u, 0, 1, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, 0}; + std::vector<D3D12_ROOT_PARAMETER1> params; + D3D12_ROOT_PARAMETER1 p{}; + p.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + p.Constants.Num32BitValues = (UINT)consts.size(); + params.push_back(p); + UINT space1_param = 0, table_param = 0; + if (heap) { + D3D12_ROOT_PARAMETER1 q{}; + q.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + q.DescriptorTable = {1, &space1}; + space1_param = (UINT)params.size(); + params.push_back(q); + } + if (n) { + D3D12_ROOT_PARAMETER1 q{}; + q.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + q.DescriptorTable = {2, ranges}; + table_param = (UINT)params.size(); + params.push_back(q); + } + D3D12_VERSIONED_ROOT_SIGNATURE_DESC rsd{}; + rsd.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + rsd.Desc_1_1 = {(UINT)params.size(), params.data(), 0, nullptr, + heap ? D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED : D3D12_ROOT_SIGNATURE_FLAG_NONE}; + Ref<ID3DBlob> rs_blob, rs_err; + if (FAILED(D3D12SerializeVersionedRootSignature(&rsd, &rs_blob, &rs_err))) { + std::fprintf(stderr, "root signature: %s\n", rs_err ? (const char*)rs_err->GetBufferPointer() : "?"); + return 1; + } + Ref<ID3D12RootSignature> root; + CHECK(device->CreateRootSignature(0, rs_blob->GetBufferPointer(), rs_blob->GetBufferSize(), IID_PPV_ARGS(&root))); + auto cs = read_file(cs_path); + if (cs.empty()) { std::fprintf(stderr, "missing %s\n", cs_path.c_str()); return 2; } + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root; + pd.CS = {cs.data(), cs.size()}; + Ref<ID3D12PipelineState> pso; + HRESULT pso_hr = device->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pso)); + std::printf("pipeline: 0x%08lx\n", (unsigned long)pso_hr); + if (FAILED(pso_hr)) { dump_messages(); return 1; } + + // resources + D3D12_HEAP_PROPERTIES up{D3D12_HEAP_TYPE_UPLOAD}, def{D3D12_HEAP_TYPE_DEFAULT}, rb{D3D12_HEAP_TYPE_READBACK}; + std::map<UINT, Ref<ID3D12Resource>> res, staging, back; + std::map<UINT, UINT64> res_size; + auto upload = [&](const std::vector<char>& data, UINT64 at_least, Ref<ID3D12Resource>& r) -> HRESULT { + auto d = buffer_desc(data.size() > at_least ? data.size() : at_least); + HRESULT hr = device->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&r)); + if (FAILED(hr)) return hr; + void* m = nullptr; + if (FAILED(hr = r->Map(0, nullptr, &m))) return hr; + std::memset(m, 0, (size_t)d.Width); + if (!data.empty()) std::memcpy(m, data.data(), data.size()); + r->Unmap(0, nullptr); + return S_OK; + }; + for (const auto& kv : res_files) { + auto data = read_file(kv.second); + if (data.empty()) { std::fprintf(stderr, "missing or empty %s\n", kv.second.c_str()); return 2; } + auto d = buffer_desc(data.size(), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + res_size[kv.first] = d.Width; + CHECK(device->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&res[kv.first]))); + CHECK(upload(data, d.Width, staging[kv.first])); + auto r = buffer_desc(d.Width); + CHECK(device->CreateCommittedResource(&rb, D3D12_HEAP_FLAG_NONE, &r, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&back[kv.first]))); + } + Ref<ID3D12Resource> heapmem_res, vinfo_res, vdesc_res; + std::vector<char> heapmem_data, vinfo_data, vdesc_data; + if (heap) { + heapmem_data = read_file(heapmem_path); + vinfo_data = read_file(vinfo_path); + CHECK(upload(heapmem_data, 16, heapmem_res)); + CHECK(upload(vinfo_data, 16, vinfo_res)); + if (vdesc) { + vdesc_data = read_file(vdesc_path); + CHECK(upload(vdesc_data, 16, vdesc_res)); + } + } + + // one shader-visible heap: [0, 2n) the table, [2n, 2n + 2) space1, the view-id region from 262144 + const UINT region = 262144, heap_size = heap ? region + 8 + 8 * 90000 : (2 * n ? 2 * n : 1); + Ref<ID3D12DescriptorHeap> dheap; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, heap_size, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + CHECK(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&dheap))); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + auto at = [&](UINT i) { D3D12_CPU_DESCRIPTOR_HANDLE h = dheap->GetCPUDescriptorHandleForHeapStart(); h.ptr += SIZE_T{i} * step; return h; }; + auto srv_view = [&](ID3D12Resource* r, UINT64 offset, UINT64 bytes, D3D12_CPU_DESCRIPTOR_HANDLE h) { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Buffer.FirstElement = offset / 4; + v.Buffer.NumElements = (UINT)((bytes + 3) / 4); + v.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(v.Buffer.NumElements ? r : nullptr, &v, h); + }; + auto uav_view = [&](ID3D12Resource* r, UINT64 offset, UINT64 bytes, D3D12_CPU_DESCRIPTOR_HANDLE h) { + D3D12_UNORDERED_ACCESS_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + v.Buffer.FirstElement = offset / 4; + v.Buffer.NumElements = (UINT)((bytes + 3) / 4); + v.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(v.Buffer.NumElements ? r : nullptr, nullptr, &v, h); + }; + for (UINT i = 0; i < n; ++i) { + srv_view(nullptr, 0, 0, at(i)); + uav_view(nullptr, 0, 0, at(n + i)); + } + for (const auto& v : views) { + if (v.offset + v.bytes > res_size[v.res]) { std::fprintf(stderr, "view %u past its resource\n", v.slot); return 2; } + if (v.uav) uav_view(res[v.res], v.offset, v.bytes, at(n + v.slot)); + else srv_view(res[v.res], v.offset, v.bytes, at(v.slot)); + } + if (heap) { + srv_view(heapmem_res, 0, heapmem_data.size(), at(2 * n)); + srv_view(vinfo_res, 0, vinfo_data.size(), at(2 * n + 1)); + if (vdesc) { + srv_view(nullptr, 0, 0, at(2 * n + 2)); + srv_view(vdesc_res, 0, vdesc_data.size(), at(2 * n + 3)); + } + // empty views (kinds 4 and 7 only: the harness builds buffer heaps) and the listed ids' views + for (UINT k = 0; k < 8; ++k) srv_view(nullptr, 0, 0, at(region + k)); + uav_view(nullptr, 0, 0, at(region + 7)); + // every id's buffer slots start null: the translation indexes the heap with whatever id heapmem holds (any + // id < 90000), and an unwritten descriptor is undefined (WARP crashed with an access violation on one) + for (UINT id = 0; id < 90000; ++id) { + srv_view(nullptr, 0, 0, at(region + 8 + 8 * id + 4)); + uav_view(nullptr, 0, 0, at(region + 8 + 8 * id + 7)); + } + for (const auto& v : hviews) { + if (v.offset + v.bytes > res_size[v.res]) { std::fprintf(stderr, "hview %u past its resource\n", v.id); return 2; } + if (v.kind == 7) uav_view(res[v.res], v.offset, v.bytes, at(region + 8 + 8 * v.id + 7)); + else srv_view(res[v.res], v.offset, v.bytes, at(region + 8 + 8 * v.id + 4)); + } + } + std::printf("bound: %u table slots (%zu views), %zu resources, heap %s (%zu views)\n", n, views.size(), res.size(), + heap ? "yes" : "no", hviews.size()); + + D3D12_COMMAND_QUEUE_DESC qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + Ref<ID3D12CommandQueue> queue; + CHECK(device->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&queue))); + Ref<ID3D12CommandAllocator> alloc; + CHECK(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc))); + Ref<ID3D12GraphicsCommandList> list; + CHECK(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc, nullptr, IID_PPV_ARGS(&list))); + for (auto& kv : res) { + list->CopyBufferRegion(kv.second, 0, staging[kv.first], 0, res_size[kv.first]); + auto b = transition(kv.second, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->ResourceBarrier(1, &b); + } + ID3D12DescriptorHeap* heaps[] = {dheap}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(root); + list->SetPipelineState(pso); + list->SetComputeRoot32BitConstants(0, (UINT)consts.size(), consts.data(), 0); + if (heap) { + D3D12_GPU_DESCRIPTOR_HANDLE g = dheap->GetGPUDescriptorHandleForHeapStart(); + g.ptr += UINT64{2 * n} * step; + list->SetComputeRootDescriptorTable(space1_param, g); + } + if (n) list->SetComputeRootDescriptorTable(table_param, dheap->GetGPUDescriptorHandleForHeapStart()); + list->Dispatch(groups[0], groups[1], groups[2]); + D3D12_RESOURCE_BARRIER ub{}; + ub.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &ub); + for (auto& kv : res) { + auto b = transition(kv.second, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &b); + list->CopyBufferRegion(back[kv.first], 0, kv.second, 0, res_size[kv.first]); + } + CHECK(list->Close()); + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + Ref<ID3D12Fence> fence; + CHECK(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); + CHECK(queue->Signal(fence, 1)); + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + CHECK(fence->SetEventOnCompletion(1, ev)); + const DWORD t0 = GetTickCount(); + const DWORD waited = WaitForSingleObject(ev, 60000); + std::printf("gpu wait: %s after %lu ms, fence %llu\n", waited == WAIT_OBJECT_0 ? "done" : "TIMEOUT", + (unsigned long)(GetTickCount() - t0), (unsigned long long)fence->GetCompletedValue()); + std::fflush(stdout); + if (waited != WAIT_OBJECT_0) { + std::fprintf(stderr, "the GPU did not finish within 60 s (fatal)\n"); + ExitProcess(3); + } + CHECK(device->GetDeviceRemovedReason()); + for (auto& kv : back) { + void* m = nullptr; + D3D12_RANGE r{0, (SIZE_T)res_size[kv.first]}; + CHECK(kv.second->Map(0, &r, &m)); + std::ofstream f(out + ".res" + std::to_string(kv.first), std::ios::binary); + f.write((const char*)m, (std::streamsize)res_size[kv.first]); + kv.second->Unmap(0, nullptr); + } + dump_messages(); + std::printf("ok\n"); + return 0; +} diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 5bc7afa6e9..b98dee851f 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -6,9 +6,8 @@ the stopping exception, the integer registers, the stack words and the code bytes around RIP. Stops at a second-chance exception, an uncontinued main-image breakpoint, or the timeout. A timeout of zero disables the timer. An assertion continuation limit of -1 removes that limit. -A file named `stop` created in <logdir> during the run ends it as the timeout does (checked twice a -second; a stop file left from an earlier run is removed at start). """ +import bisect import ctypes import ctypes.wintypes as wt import os @@ -59,6 +58,84 @@ def read_qword(read, address): return int.from_bytes(data, "little") if len(data) == 8 else None +# Breakpoint sites whose first instruction is one of these few forms are not stepped: the +# debugger performs the instruction on the stopped thread's context and continues after it, so +# the int3 stays in place (one debug event per hit instead of a breakpoint, a single step and two +# code writes; and no window in which another thread passes the site unseen). Anything else is +# stepped as before. X2W_DEBUG_EMULATE=0 turns this off. +NOPS = (bytes.fromhex("90"), bytes.fromhex("6690"), bytes.fromhex("0f1f00"), bytes.fromhex("0f1f4000"), + bytes.fromhex("0f1f440000"), bytes.fromhex("660f1f440000"), bytes.fromhex("0f1f8000000000"), + bytes.fromhex("0f1f840000000000")) +GPR = 0x78 # CONTEXT.Rax; Rcx, Rdx, Rbx, Rsp, Rbp, Rsi, Rdi, R8-R15 follow in encoding order +EFLAGS, RIP = 0x44, 0xF8 + + +def plan_emulation(code): + """The emulation for the instruction at the start of code, or None when it must be stepped.""" + if len(code) < 8: + return None + for nop in NOPS: + if code.startswith(nop): + return ("nop", len(nop)) + if code[:3] == b"\x4c\x8b\xd1": # mov r10, rcx (every ntdll system-call stub) + return ("mov", 3, 10, 1, 64) + if code[:3] == b"\x48\x8b\xc4": # mov rax, rsp + return ("mov", 3, 0, 4, 64) + if code[0] == 0xC3: # ret + return ("ret", 1) + if code[0] == 0xE9: # jmp rel32 + return ("jmp", 5, int.from_bytes(code[1:5], "little", signed=True)) + if code[0] == 0xEB: # jmp rel8 + return ("jmp", 2, int.from_bytes(code[1:2], "little", signed=True)) + # mov [rsp+disp8], r64: REX.W (+R) 89, modrm 01 reg 100, sib 0x24 + if code[0] in (0x48, 0x4C) and code[1] == 0x89 and code[2] & 0xC7 == 0x44 and code[3] == 0x24: + return ("store", 5, ((code[2] >> 3) & 7) + (8 if code[0] == 0x4C else 0), code[4]) + # test r, r with the same register (32- or 64-bit; optional REX) + rex = code[0] if 0x40 <= code[0] <= 0x4F else 0 + body = code[1:] if rex else code + if body[0] == 0x85 and body[1] >> 6 == 3 and (body[1] >> 3) & 7 == body[1] & 7 and (rex & 0x5) in (0, 0x5): + return ("test", 2 + (1 if rex else 0), (body[1] & 7) + (8 if rex & 1 else 0), 64 if rex & 8 else 32) + return None + + +def apply_emulation(plan, address, ctx, read, write): + """Performs plan on ctx (a writable CONTEXT view) for the instruction at address; False when it cannot.""" + def gpr(n): + return struct.unpack_from("<Q", ctx, GPR + 8 * n)[0] + + def set_gpr(n, value): + struct.pack_into("<Q", ctx, GPR + 8 * n, value & 0xFFFFFFFFFFFFFFFF) + + kind, length = plan[0], plan[1] + rip = address + length + if kind == "mov": + _, _, dst, src, width = plan + set_gpr(dst, gpr(src) if width == 64 else gpr(src) & 0xFFFFFFFF) + elif kind == "ret": + target = read_qword(read, gpr(4)) + if target is None: + return False + set_gpr(4, gpr(4) + 8) + rip = target + elif kind == "jmp": + rip = address + length + plan[2] + elif kind == "store": + if not write(gpr(4) + plan[3], struct.pack("<Q", gpr(plan[2]))): + return False + elif kind == "test": + value = gpr(plan[2]) & (0xFFFFFFFFFFFFFFFF if plan[3] == 64 else 0xFFFFFFFF) + flags = struct.unpack_from("<I", ctx, EFLAGS)[0] & ~(0x1 | 0x4 | 0x40 | 0x80 | 0x800) # CF PF ZF SF OF + if bin(value & 0xFF).count("1") % 2 == 0: + flags |= 0x4 + if value == 0: + flags |= 0x40 + if value >> (plan[3] - 1): + flags |= 0x80 + struct.pack_into("<I", ctx, EFLAGS, flags) # AF is undefined after TEST and is left as it was + struct.pack_into("<Q", ctx, RIP, rip) + return True + + def parse_log_at(value, log): points = {} for entry in value.split(",") if value else (): @@ -104,9 +181,11 @@ def read_stack(read, rsp, words): return data.ljust(size, b"\0") -def final_path(handle): +def final_path(handle, full=False): buf = ctypes.create_unicode_buffer(1024) n = k32.GetFinalPathNameByHandleW(wt.HANDLE(handle), buf, 1024, 0) + if full: + return buf.value[4:] if n and buf.value.startswith("\\\\?\\") else (buf.value if n else "") return os.path.basename(buf.value) if n else "?" @@ -137,18 +216,85 @@ def print(*args, **kwargs): stub_area = [0, 0] # next free address and end of the block the stubs go to os.makedirs(logdir, exist_ok=True) trap_log = os.path.join(logdir, "trap.log") - stop_file = os.path.join(logdir, "stop") # created from outside: end the run as at the timeout - for stale in (trap_log, os.path.join(logdir, "finished.txt"), stop_file): # a reused run directory starts clean + stop_file = os.path.join(logdir, "stop") # created from outside: end the run as at a timeout + snapshot_file = os.path.join(logdir, "snapshot") # created from outside: write threads_<s>.txt, go on + for stale in (trap_log, os.path.join(logdir, "finished.txt"), stop_file, snapshot_file): # a reused run directory starts clean if os.path.exists(stale): os.remove(stale) if os.path.exists(trap_log): os.remove(trap_log) events = open(os.path.join(logdir, "events.txt"), "w", encoding="utf-8") + # The logs are written through Python's buffer and flushed at most every half second (the + # live console tails them), at a stop and at the end, instead of once per line. + # X2W_DEBUG_FLUSH_EACH=1 restores a flush per line. + flush_each = os.environ.get("X2W_DEBUG_FLUSH_EACH") == "1" + open_logs = [events] + last_flush = [time.time()] + + def flush_logs(force=False): + now = time.time() + if force or flush_each or now - last_flush[0] >= 0.5: + last_flush[0] = now + for handle in open_logs: + if not handle.closed: + handle.flush() def log(text): events.write(text + "\n") - events.flush() + if flush_each: + events.flush() + # --log-repeats N: an exception, continued assert or diagnostic hook (runtime API, movie + # player) that repeats from the same place is logged N times, then only counted; the counts + # go to finished.txt. 0 logs every one, as before. File and network hooks are never capped. + log_repeats = int(opts.get("--log-repeats", "200")) + repeat_counts = {} + + def repeat_ok(key): + """True while key has been seen at most --log-repeats times (always true with 0).""" + seen = repeat_counts.get(key, 0) + 1 + repeat_counts[key] = seen + return not log_repeats or seen <= log_repeats + emulate_on = os.environ.get("X2W_DEBUG_EMULATE", "1") != "0" + fast_exit = opts.get("--fast-exit") == "1" + + pool_mode = os.environ.get("X2W_XMEM_GPU_POOL", "") + pool_all = pool_mode == "all" + pooled_bytes = 0 + if pool_all or (os.environ.get("X2W_XMEM_SLAB_DIR") and pool_mode != "0"): + try: # a pool failure must never cost a run: xmem then falls back to fresh sections + import gpu_slab_pool + count = (int(os.environ.get("X2W_XMEM_GPU_POOL_SLABS") or "32") if pool_all + else max(1, int(os.environ.get("X2W_XMEM_SLAB_BUDGET_MIB") or "3072") // 256)) + pooled_bytes = gpu_slab_pool.ensure(count) << 28 + except Exception as error: + count = 0 + print(f"GPU slab pool not started: {error}") + print(f"GPU slab pool: {pooled_bytes >> 20} MiB reachable (X2W_XMEM_GPU_POOL={pool_mode or 'on'})") + if pool_all and pooled_bytes < count << 28: + # =all is an explicit opt-in: a short pool would push the title onto the (small) beyond-pool budget and + # make its page maps fail (err 1455) mid-run. Refuse instead. + print(f"refused to launch: X2W_XMEM_GPU_POOL=all needs {count} pool sections, {pooled_bytes >> 28} reachable") + return 3 + # Host safety (runtime_work/NOTES.md): the job limit covers private commit only. Pagefile page + # slabs are capped by X2W_XMEM_SLAB_BUDGET_MIB; a launch whose job limit plus slab budget does not + # fit in the host's commit headroom minus 2 GiB is refused. X2W_ALLOW_UNBUDGETED=1 skips this. + if os.environ.get("X2W_XMEM_PERMISSIVE") == "1" and os.environ.get("X2W_ALLOW_UNBUDGETED") != "1": # title runs (run.ps1) + class _PI(ctypes.Structure): + _fields_ = [("cb", wt.DWORD)] + [(n, ctypes.c_size_t) for n in ( + "CommitTotal", "CommitLimit", "CommitPeak", "PhysicalTotal", "PhysicalAvailable", "SystemCache", + "KernelTotal", "KernelPaged", "KernelNonpaged", "PageSize")] + [(n, wt.DWORD) for n in ( + "HandleCount", "ProcessCount", "ThreadCount")] + info0 = _PI() + info0.cb = ctypes.sizeof(info0) + ctypes.WinDLL("psapi").GetPerformanceInfo(ctypes.byref(info0), info0.cb) + headroom = (info0.CommitLimit - info0.CommitTotal) * info0.PageSize + budget = int(os.environ.get("X2W_XMEM_SLAB_BUDGET_MIB") or "0") << 20 + beyond_pool = budget if pool_all else max(0, budget - pooled_bytes) # the pool is already in CommitTotal + if not budget or memory + beyond_pool > headroom - (2 << 30): + print(f"refused to launch: job limit {memory >> 20} MiB + pagefile slab budget {budget >> 20} MiB " + f"(X2W_XMEM_SLAB_BUDGET_MIB) must be set and fit in the commit headroom {headroom >> 20} MiB - 2048") + return 3 log_at = parse_log_at(os.environ.get("X2W_LOG_AT", ""), log) logged_hits = {} @@ -181,6 +327,9 @@ def log(text): k32.AssignProcessToJobObject(wt.HANDLE(job), wt.HANDLE(pi.hProcess)) k32.DebugSetProcessKillOnExit(True) k32.ResumeThread(wt.HANDLE(pi.hThread)) + if env.get("X2W_PRESENT_IN_TITLE_WINDOW") == "1": + import window_status + window_status.start(pi.dwProcessId, trap_log) if opts.get("--console", "1") == "1": # Live debug console in its own window: follows this run's logs (live_view.py). import subprocess @@ -191,6 +340,7 @@ def log(text): builtins.print(f"live console not started: {error}") modules = {} # base -> name + module_paths = {} # base -> full path (symbol search for the sampling profiler) main_base = None event = (ctypes.c_ubyte * 176)() start = time.time() @@ -198,12 +348,17 @@ def log(text): stop = None exit_code = None + module_index = [[], 0] # sorted bases, and the module count they were built from + def where(addr): - best = None - for base, name in modules.items(): - if base <= addr and (best is None or base > best[0]): - best = (base, name) - return f"{best[1]}+{addr - best[0]:#x}" if best and addr - best[0] < 0x20000000 else f"{addr:#x}" + if module_index[1] != len(modules) or len(module_index[0]) != len(modules): + module_index[0] = sorted(modules) + module_index[1] = len(modules) + bases = module_index[0] + i = bisect.bisect_right(bases, addr) - 1 + if i >= 0 and addr - bases[i] < 0x20000000: + return f"{modules[bases[i]]}+{addr - bases[i]:#x}" + return f"{addr:#x}" def read(addr, size): buf = (ctypes.c_ubyte * size)() @@ -291,7 +446,7 @@ def xmm(n): except ImportError: done = None if not done: - k32.CloseHandle(wt.HANDLE(thread)) + release(thread) return False length, dest, value = done struct.pack_into("<16s", ctx, 0x1A0 + 16 * dest, value.to_bytes(16, "little")) @@ -305,19 +460,34 @@ def xmm(n): ctx_error = [0] # GetLastError of the last failed get_ctx - def get_ctx(tid): - thread = k32.OpenThread(0x0008 | 0x0010 | 0x0002, False, tid) # GET | SET_CONTEXT | SUSPEND - struct.pack_into("<I", ctx_view, 0x30, 0x10000B) + # Thread handles from the CREATE_PROCESS and CREATE_THREAD events (they carry get/set context + # access and stay valid until the thread's exit event), so a breakpoint needs no OpenThread. + thread_handles = {} + opened = set() + + def get_ctx(tid, flags=0x10000B): + """The thread's context: flags 0x100003 (control, integer) for breakpoints, 0x10000B adds FP state.""" + thread = thread_handles.get(tid) + if not thread: + thread = k32.OpenThread(0x0008 | 0x0010 | 0x0002, False, tid) # GET | SET_CONTEXT | SUSPEND + if thread: + opened.add(thread) + struct.pack_into("<I", ctx_view, 0x30, flags) if not thread or not k32.GetThreadContext(wt.HANDLE(thread), ctypes.c_void_p(ctx_addr)): ctx_error[0] = k32.GetLastError() # before CloseHandle can change it - if thread: - k32.CloseHandle(wt.HANDLE(thread)) + release(thread) return None, None return thread, ctx_view + def release(thread): + """Closes a handle get_ctx opened itself; the event-owned handles are left to the system.""" + if thread in opened: + opened.discard(thread) + k32.CloseHandle(wt.HANDLE(thread)) + def set_ctx(thread): k32.SetThreadContext(wt.HANDLE(thread), ctypes.c_void_p(ctx_addr)) - k32.CloseHandle(wt.HANDLE(thread)) + release(thread) def ustr(addr): # UNICODE_STRING* raw = read(addr, 16) @@ -373,6 +543,11 @@ def oa_name(addr): # OBJECT_ATTRIBUTES* "\\device\\rawip", "\\device\\ws2ifsl") denied = {} + # X2W_BINK_PER_HANDLE=1: per movie handle, every NextFrame count 1-3 and each 100th, only pause + # changes (not the per-frame repeats), and a frame count on close and in the exit report. + bink_per_handle = os.environ.get("X2W_BINK_PER_HANDLE") == "1" + bink_handles = {} # handle -> {"frames", "paused", "opened"} + def bink_call(name, regs, ret): """Counts the call, remembers the movie handle and frame buffers; returns a log line or None.""" bink_counts[name] = bink_counts.get(name, 0) + 1 @@ -380,18 +555,44 @@ def bink_call(name, regs, ret): bink_state["bink"], bink_state["buffers"] = regs["Rcx"], regs["Rdx"] if name == "BinkNextFrame": bink_state["bink"] = regs["Rcx"] + if bink_per_handle and name != "BinkOpenWithOptions": + movie = bink_handles.setdefault(regs["Rcx"], {"frames": 0, "paused": None, "opened": False}) + if name == "BinkNextFrame": + movie["frames"] += 1 + if movie["frames"] > 3 and movie["frames"] % 100: + return None + return f"BinkNextFrame rcx={regs['Rcx']:#x} handle frame call {movie['frames']} from {where(ret)}" + if name == "BinkPause": + paused = regs["Rdx"] != 0 + if movie["paused"] == paused: + return None + movie["paused"] = paused + return (f"BinkPause rcx={regs['Rcx']:#x} -> {'paused' if paused else 'playing'} after " + f"{movie['frames']} NextFrame calls from {where(ret)}") + if name == "BinkClose": + frames = movie["frames"] + bink_handles.pop(regs["Rcx"], None) + return f"BinkClose rcx={regs['Rcx']:#x} after {frames} NextFrame calls from {where(ret)}" if name in ("BinkNextFrame", "BinkShouldSkip") and bink_counts[name] > 3: return None text = "" if name == "BinkOpenWithOptions": text = repr((read(regs["Rcx"], 200) or b"").split(bytes(1))[0].decode("latin-1", "replace")) + # LOCAL (scene): post-setup movies pass a stack structure in rcx, not a name. With + # X2W_BINK_PER_HANDLE=1 also log its first 32 bytes and the string its first word points at. + head = read(regs["Rcx"], 32) if bink_per_handle else None + if head and len(head) == 32: + inner = read(struct.unpack_from("<Q", head, 0)[0], 160) or b"" + text += f" [rcx]={head.hex(' ', 8)} [[rcx]]={inner.split(bytes(1))[0].decode('latin-1', 'replace')!r}" return f"{name} rcx={regs['Rcx']:#x} rdx={regs['Rdx']:#x} r8={regs['R8']:#x} {text} from {where(ret)}" - def bink_report(): - """Call counts, the movie header and a PNG of the current frame's luma plane.""" + def bink_report(luma=True): + """Call counts, the movie header and (luma=True) a PNG of the current frame's luma plane.""" if not bink_counts: return print(" bink calls: " + ", ".join(f"{k} x{v}" for k, v in sorted(bink_counts.items()))) + for handle, movie in sorted(bink_handles.items()): + print(f" bink handle {handle:#x} still open: {movie['frames']} NextFrame calls, paused={movie['paused']}") header = read(bink_state["bink"], 32) if bink_state.get("bink") else None if header: print(" bink header (width, height, frames, frame, ...): " + " ".join(str(v) for v in struct.unpack("<8I", header))) @@ -400,7 +601,7 @@ def bink_report(): return total, ya_w, ya_h, c_w, c_h, current = struct.unpack_from("<iIIIII", buffers, 0) print(f" bink frame buffers: total={total} luma={ya_w}x{ya_h} chroma={c_w}x{c_h} current={current}") - if not (0 < ya_w <= 8192 and 0 < ya_h <= 8192): + if not luma or not (0 < ya_w <= 8192 and 0 < ya_h <= 8192): return plane = 24 + (current % 2) * 5 * 24 # header, then two plane sets of five 24-byte planes; luma first pointer = struct.unpack_from("<Q", buffers, plane + 8)[0] @@ -428,21 +629,37 @@ def chunk(kind, payload): print(f" bink luma plane -> bink_luma.png (pointer {pointer:#x}, pitch {pitch})") breakpoints = {} # addr -> original byte + emulations = {} # addr -> plan_emulation() result for breakpoints that are not stepped retired = set() # X2W_LOG_AT breakpoints removed at their hit limit late_hits = {} # retired addr -> INT3 events that arrived after the removal returns = {} # addr -> list of (tid, rsp after return, description) stepping = {} # tid -> addr to re-arm + capped = {} # diagnostic hook -> calls not logged because of --log-repeats + trace_callers = "CALLERS" in os.environ.get("X2W_TRACE", "") + ever_armed = set() # addresses that have held one of our int3s file_log = open(os.path.join(logdir, "files.txt"), "w", encoding="utf-8") if trace or log_at else None + if file_log: + open_logs.append(file_log) def arm(addr, *, skip_int3=False): if addr not in breakpoints: - original = read(addr, 1) - if original and (not skip_int3 or original != b"\xcc") and write(addr, b"\xcc"): - breakpoints[addr] = original + original = read(addr, 16) + if original and (not skip_int3 or original[:1] != b"\xcc") and write(addr, b"\xcc"): + breakpoints[addr] = original[:1] + ever_armed.add(addr) + plan = plan_emulation(original) if emulate_on else None + if plan: + emulations[addr] = plan return addr in breakpoints and (not skip_int3 or breakpoints[addr] != b"\xcc") + def disarm(addr): + """Removes a return-site breakpoint that nothing waits for and that cannot be emulated.""" + if write(addr, breakpoints[addr]): + del breakpoints[addr] + emulations.pop(addr, None) + def handle_breakpoint(tid, addr): - thread, ctx = get_ctx(tid) + thread, ctx = get_ctx(tid, 0x100003) if not thread: return False regs = dict(zip(REGS, struct.unpack_from("<16Q", ctx, 0x78) + struct.unpack_from("<Q", ctx, 0xF8))) @@ -477,7 +694,6 @@ def handle_breakpoint(tid, addr): chain = [c for c in chain if not c.lower().startswith(("ntdll", "kernelbase", "kernel32"))] file_log.write(f"{time.time() - start:7.3f} VALLOC {name} requested={requested} size={size:#x} " f"type={kind & 0xffffffff:#x} protect={protect & 0xffffffff:#x} callers: {' '.join(chain[:10])}\n") - file_log.flush() desc = None elif arg == "count": # Title function hit counter: first hits are logged with registers and the caller. @@ -487,7 +703,6 @@ def handle_breakpoint(tid, addr): target = redirects[name][1] file_log.write(f"{time.time() - start:7.3f} REDIRECT {name} hit {hit_counts[name]} -> {where(target)} " f"(experiment)\n") - file_log.flush() struct.pack_into("<Q", ctx, 0xF8, target) set_ctx(thread) return True @@ -495,7 +710,6 @@ def handle_breakpoint(tid, addr): file_log.write(f"{time.time() - start:7.3f} HIT {name} rcx={regs['Rcx']:#x} rdx={regs['Rdx']:#x} " f"r8={regs['R8']:#x} r9={regs['R9']:#x} [rdx]={(read(regs['Rdx'], 32) or b'').hex(' ')} " f"from {where(ret)}\n") - file_log.flush() elif arg == "runtime": def guid(address): raw = read(address, 16) if address else None @@ -505,8 +719,14 @@ def guid(address): return f"{a:08x}-{b:04x}-{c:04x}-{raw[8:10].hex()}-{raw[10:].hex()}" desc = f"{name} " + (f"provider={guid(regs['Rcx'])} iid={guid(regs['Rdx'])}" if name == "QueryApiImpl" else f"rcx={regs['Rcx']:#x} rdx={regs['Rdx']:#x}") + f" from {where(ret)}" + if not repeat_ok(desc): + capped[name] = capped.get(name, 0) + 1 + desc = None elif arg == "bink": desc = bink_call(name, regs, ret) + if desc and not repeat_ok(f"{name} from {where(ret)}"): + capped[name] = capped.get(name, 0) + 1 + desc = None else: if arg.startswith("ustr:"): target = ustr(regs[arg[5:].capitalize()]) @@ -517,13 +737,13 @@ def guid(address): # Offline mode: the call never runs. Return STATUS_ACCESS_DENIED to the caller. denied[target] = denied.get(target, 0) + 1 file_log.write(f"{time.time() - start:7.3f} DENIED (offline) {desc}\n") - file_log.flush() + file_log.flush() # a refusal is written at once struct.pack_into("<Q", ctx, 0x78, 0xC0000022) # rax struct.pack_into("<Q", ctx, 0x98, rsp + 8) # rsp: pop the return address struct.pack_into("<Q", ctx, 0xF8, ret) # rip set_ctx(thread) return True - if desc and ("memory:" in desc or "CALLERS" in os.environ.get("X2W_TRACE", "")): + if desc and ("memory:" in desc or trace_callers): # Title-level callers: module addresses on the stack outside the system DLLs. words = struct.unpack_from("<160Q", (read(rsp, 8 * 160) or b"").ljust(8 * 160, b"\0")) chain = [where(w) for w in words if any(b <= w < b + 0x10000000 for b in modules)] @@ -532,11 +752,26 @@ def guid(address): if desc: returns.setdefault(ret, []).append((tid, rsp + 8, desc)) arm(ret) - for item in list(returns.get(addr, [])): - if item[0] == tid and item[1] == rsp: - returns[addr].remove(item) - file_log.write(f"{time.time() - start:7.3f} {item[2]} -> {regs['Rax'] & 0xFFFFFFFF:#010x}\n") - file_log.flush() + pending = returns.get(addr) + if pending: + for item in list(pending): + if item[0] == tid and item[1] == rsp: + pending.remove(item) + file_log.write(f"{time.time() - start:7.3f} {item[2]} -> {regs['Rax'] & 0xFFFFFFFF:#010x}\n") + # An X2W_LOG_AT site (point) is neither emulated nor treated as a bare return site: it is stepped + # and re-armed until its hit limit, then restored (upstream's retire below). + plan = None if point else emulations.get(addr) + if plan and apply_emulation(plan, addr, ctx, read, write): + # Performed here; the int3 stays in place. + set_ctx(thread) + return True + if addr not in hooks and not returns.get(addr) and not point: + # A return site nothing waits for: continue at the original instruction without a step. + struct.pack_into("<Q", ctx, 0xF8, addr) + set_ctx(thread) + disarm(addr) + return True + # Step over the original instruction, then re-arm. struct.pack_into("<Q", ctx, 0xF8, addr) # After the final logged hit, let the restored instruction run at full speed unless # another hook still owns this breakpoint. @@ -556,12 +791,17 @@ def guid(address): live_threads = set() - def dump_threads(path): - """At a timeout: every thread's rip and the module addresses found on its stack.""" + def dump_threads(path, walk=True): + """At a timeout: every thread's rip and the module addresses found on its stack. + + walk=False (--fast-exit) writes the rip of each thread only, in the same line shape.""" lines = [] dbghelp = ctypes.WinDLL("dbghelp", use_last_error=True) dbghelp.SymSetOptions(0x00000004 | 0x00000200) # DEFERRED_LOADS | FAIL_CRITICAL_ERRORS - dbghelp.SymInitializeW(wt.HANDLE(pi.hProcess), None, True) + # Frames are printed as module+offset; no symbols are used. The search path is the log + # folder so that dbghelp does not look for symbol files (or ask a symbol server) per module. + if walk: + dbghelp.SymInitializeW(wt.HANDLE(pi.hProcess), ctypes.c_wchar_p(logdir), True) dbghelp.StackWalk64.argtypes = [ctypes.c_uint32, wt.HANDLE, wt.HANDLE, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] table_access = ctypes.cast(dbghelp.SymFunctionTableAccess64, ctypes.c_void_p) @@ -585,7 +825,7 @@ def dump_threads(path): struct.pack_into("<Q", frame, offset, value) struct.pack_into("<I", frame, offset + 12, 3) # AddrModeFlat frames = [] - for _ in range(28): + for _ in range(28 if walk else 0): if not dbghelp.StackWalk64(0x8664, wt.HANDLE(pi.hProcess), wt.HANDLE(thread), frame, ctypes.c_void_p(ctx_addr), None, table_access, module_base, None): break @@ -596,6 +836,8 @@ def dump_threads(path): lines.append(f"thread {thread_id} rip={where(rip)} stack: " + " ".join(frames[1:])) k32.ResumeThread(wt.HANDLE(thread)) k32.CloseHandle(wt.HANDLE(thread)) + if walk: + dbghelp.SymCleanup(wt.HANDLE(pi.hProcess)) with open(path, "w", encoding="utf-8") as handle: handle.write("\n".join(lines) + "\n") return lines @@ -617,163 +859,296 @@ def poll_watches(): watch_values[rva] = blob log(f"{time.time() - start:7.3f} watch +{rva:#x} = {blob.hex(' ')}") + # Host safety (runtime_work/NOTES.md): the job memory limit counts private commit only, so the + # title's page slabs (pagefile-backed sections) and driver allocations are not limited by it. + # Every second the system commit headroom is read; below X2W_HEADROOM_STOP_MIB (default 1536) + # the run ends as at a timeout. commit.txt gets a sample every 2 s: seconds, system committed, + # commit limit, the title's private commit, this debugger's private commit (MiB). + class PERF_INFO(ctypes.Structure): + _fields_ = [("cb", wt.DWORD)] + [(n, ctypes.c_size_t) for n in ( + "CommitTotal", "CommitLimit", "CommitPeak", "PhysicalTotal", "PhysicalAvailable", "SystemCache", + "KernelTotal", "KernelPaged", "KernelNonpaged", "PageSize")] + [(n, wt.DWORD) for n in ( + "HandleCount", "ProcessCount", "ThreadCount")] + + class PROC_MEM(ctypes.Structure): + _fields_ = [("cb", wt.DWORD), ("PageFaultCount", wt.DWORD)] + [(n, ctypes.c_size_t) for n in ( + "PeakWorkingSetSize", "WorkingSetSize", "QuotaPeakPagedPoolUsage", "QuotaPagedPoolUsage", + "QuotaPeakNonPagedPoolUsage", "QuotaNonPagedPoolUsage", "PagefileUsage", "PeakPagefileUsage")] + psapi = ctypes.WinDLL("psapi") + psapi.GetProcessMemoryInfo.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD] + k32.GetCurrentProcess.restype = wt.HANDLE + headroom_stop_mib = int(os.environ.get("X2W_HEADROOM_STOP_MIB") or "3072") + headroom_stop = None + commit_log = open(os.path.join(logdir, "commit.txt"), "w", encoding="utf-8") + commit_log.write("# seconds system_committed_MiB commit_limit_MiB title_private_MiB debugger_private_MiB\n") + open_logs.append(commit_log) + commit_next = [0.0, 0.0] # next check, next commit.txt line + + def private_mib(handle): + counters = PROC_MEM() + counters.cb = ctypes.sizeof(counters) + if not psapi.GetProcessMemoryInfo(handle, ctypes.byref(counters), counters.cb): + return -1 + return counters.PagefileUsage >> 20 + + def commit_check(): + """Samples the commit; returns (committed, limit) MiB when the headroom is below the stop.""" + now = time.time() + if now < commit_next[0]: + return None + commit_next[0] = now + 0.1 + perf = PERF_INFO() + perf.cb = ctypes.sizeof(perf) + if not psapi.GetPerformanceInfo(ctypes.byref(perf), perf.cb): + return None + committed, limit = (perf.CommitTotal * perf.PageSize) >> 20, (perf.CommitLimit * perf.PageSize) >> 20 + if now >= commit_next[1]: + commit_next[1] = now + 2.0 + commit_log.write(f"{now - start:7.1f} {committed} {limit} {private_mib(wt.HANDLE(pi.hProcess))} " + f"{private_mib(k32.GetCurrentProcess())}\n") + return (committed, limit) if limit - committed < headroom_stop_mib else None + + # X2W_PROFILE=<start s>,<samples>,<interval ms>[,<repeat every s>]: clock-driven samples of every + # thread (CPU time, rip, return addresses) between debug events -> profile_<s>.txt (sample_profile.py). + profiler = None + last_event = (0.0, 0) # (seconds, tid) of the last debug event, for the profiler + if os.environ.get("X2W_PROFILE"): + import sample_profile + plan = sample_profile.parse(os.environ["X2W_PROFILE"]) + if plan: + profiler = sample_profile.Profiler(plan, wt.HANDLE(pi.hProcess), logdir, lambda a: where(a), modules, + module_paths, log) + else: + print(f"X2W_PROFILE={os.environ['X2W_PROFILE']} ignored: expected <start s>,<samples>,<interval ms>[,<repeat s>]") + interrupted = False stop_requested = False stop_next = 0.0 - while not timeout or time.time() - start < timeout: - if time.time() >= stop_next: - stop_next = time.time() + 0.5 - if os.path.exists(stop_file): - stop_requested = True - log(f"{time.time() - start:7.3f} stop file found: ending the run") + asserts_total = 0 + exception_repeats = {} # (code, address) -> events not logged because of --log-repeats + try: + while not timeout or time.time() - start < timeout: + flush_logs() + low = commit_check() + if low: + headroom_stop = low + log(f"{time.time() - start:7.3f} host commit headroom {low[1] - low[0]} MiB < {headroom_stop_mib} MiB " + f"(committed {low[0]} / limit {low[1]} MiB): ending the run (X2W_HEADROOM_STOP_MIB)") break - if dump_at and time.time() - start >= dump_at[0]: - dump_threads(os.path.join(logdir, f"threads_{dump_at.pop(0):g}.txt")) - if watches and time.time() >= watch_next: - watch_next = time.time() + 1.0 - poll_watches() - if not k32.WaitForDebugEvent(event, 200): - continue - code, pid, tid = struct.unpack_from("<III", event, 0) - status = DBG_CONTINUE - if code == CREATE_PROCESS: - live_threads.add(tid) - h_file, _, _, base = struct.unpack_from("<QQQQ", event, 16) - main_base = base - for item in filter(None, os.environ.get("X2W_COUNT", "").split(",")): - hooks[base + int(item, 16)] = (f"+{item}", "count") - # Experiment switch X2W_REDIRECT=<rva>@<n>:<target rva>[,...]: on the n-th hit of a title - # address, execution continues at another address instead. Used to force one code path. - for item in filter(None, os.environ.get("X2W_REDIRECT", "").split(",")): - source, _, target = item.partition(":") - rva, _, nth = source.partition("@") - hooks[base + int(rva, 16)] = (f"+{rva}", "count") - redirects[f"+{rva}"] = (int(nth or "1"), base + int(target, 16)) - modules[base] = os.path.basename(exe) - log(f"{time.time() - start:7.3f} process {os.path.basename(exe)} at {base:#x}") - if h_file: - k32.CloseHandle(wt.HANDLE(h_file)) - elif code == LOAD_DLL: - h_file, base = struct.unpack_from("<QQ", event, 16) - name = final_path(h_file) if h_file else "?" - modules[base] = name - log(f"{time.time() - start:7.3f} load {name} at {base:#x}") - if trace_calls and name.lower() == RUNTIME_MODULE: - # Gaming runtime: log which API interfaces the title asks for and the result. - k32.LoadLibraryExW.restype = wt.HMODULE - local = k32.LoadLibraryExW(r"C:\Windows\System32\xgameruntime.dll", None, 1) - for export in RUNTIME_CALL_HOOKS: - address = k32.GetProcAddress(local, export.encode()) if local else 0 - if address: - hooks[base + (address - local)] = (export, "runtime") - if loader_break_seen: - arm(base + (address - local)) - if trace_calls and name.lower() == MOVIE_MODULE: - # Movie player: log opens/closes/frames and remember the registered frame buffers. - k32.LoadLibraryExW.restype = wt.HMODULE - local = k32.LoadLibraryExW(os.path.join(os.path.dirname(exe), name), None, 1) - for export in MOVIE_CALL_HOOKS: - address = k32.GetProcAddress(local, export.encode()) if local else 0 - if address: - hooks[base + (address - local)] = (export, "bink") - if loader_break_seen: - arm(base + (address - local)) - if h_file: - k32.CloseHandle(wt.HANDLE(h_file)) - elif code == CREATE_THREAD: - log(f"{time.time() - start:7.3f} thread {tid} created") - live_threads.add(tid) - elif code == 4: # EXIT_THREAD - live_threads.discard(tid) - elif code == EXIT_PROCESS: - exit_code = struct.unpack_from("<I", event, 16)[0] - log(f"{time.time() - start:7.3f} exit {exit_code:#010x}") - k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE) - break - elif code == OUTPUT_STRING: - addr, unicode, length = struct.unpack_from("<QHH", event, 16) - raw = read(addr, length * (2 if unicode else 1)) - text = raw.decode("utf-16-le" if unicode else "latin-1", errors="replace").rstrip("\0\r\n") - log(f"{time.time() - start:7.3f} debug-output {text[:300]}") - elif code == EXCEPTION: - ex_code, ex_flags, _, ex_addr, nparams = struct.unpack_from("<IIQQI", event, 16) - params = struct.unpack_from("<" + "Q" * min(nparams, 15), event, 16 + 32) if nparams else () - first = struct.unpack_from("<I", event, 16 + 152)[0] - label = NAMES.get(ex_code, "") - if ex_code == 0x80000003 and ex_addr in breakpoints: - handle_breakpoint(tid, ex_addr) - k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE) + if time.time() >= stop_next: + stop_next = time.time() + 0.5 + if os.path.exists(stop_file): + stop_requested = True + log(f"{time.time() - start:7.3f} stop file {stop_file} found: ending the run") + break + # <logdir>/snapshot asks for every thread's full stack now, in threads_<seconds>.txt; + # the run continues. For a run that stops making progress without faulting. + if os.path.exists(snapshot_file): + os.remove(snapshot_file) + when = time.time() - start + taken = dump_threads(os.path.join(logdir, f"threads_{when:.0f}.txt")) + log(f"{when:7.3f} snapshot: {len(taken)} threads -> threads_{when:.0f}.txt " + f"({time.time() - start - when:.2f} s)") + if dump_at and time.time() - start >= dump_at[0]: + dump_threads(os.path.join(logdir, f"threads_{dump_at.pop(0):g}.txt")) + if watches and time.time() >= watch_next: + watch_next = time.time() + 1.0 + poll_watches() + # A due profile sample is taken here, >= 1 ms after the last continue; an event that arrives + # meanwhile is handled first (pending). + pending = bool(profiler) and profiler.run(time.time() - start, live_threads, last_event, + lambda: k32.WaitForDebugEvent(event, 0)) + if not pending and not k32.WaitForDebugEvent(event, profiler.timeout_ms(time.time() - start) if profiler else 200): continue - if ex_code == 0x80000003 and ex_addr in retired: - # Another thread executed this INT3 before the hit limit restored the original byte, - # and its event arrived after that. Rewind and run the restored instruction. - thread, ctx = get_ctx(tid) - if thread: - struct.pack_into("<Q", ctx, 0xF8, ex_addr) - set_ctx(thread) - late_hits[ex_addr] = late_hits.get(ex_addr, 0) + 1 - k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE) - continue - log(f"{time.time() - start:7.3f} X2W_LOG_AT late hit at {where(ex_addr)} on thread {tid}: " - f"thread context unavailable (error {ctx_error[0]}), handled as a breakpoint") - if ex_code == 0x80000004 and tid in stepping: - addr = stepping.pop(tid) - if addr in breakpoints: - write(addr, b"\xcc") + code, pid, tid = struct.unpack_from("<III", event, 0) + if profiler: + last_event = (time.time() - start, tid) + profiler.event_seen() + status = DBG_CONTINUE + if code == CREATE_PROCESS: + live_threads.add(tid) + h_file, _, h_thread, base = struct.unpack_from("<QQQQ", event, 16) + if h_thread: + thread_handles[tid] = h_thread + main_base = base + for item in filter(None, os.environ.get("X2W_COUNT", "").split(",")): + hooks[base + int(item, 16)] = (f"+{item}", "count") + # Experiment switch X2W_REDIRECT=<rva>@<n>:<target rva>[,...]: on the n-th hit of a title + # address, execution continues at another address instead. Used to force one code path. + for item in filter(None, os.environ.get("X2W_REDIRECT", "").split(",")): + source, _, target = item.partition(":") + rva, _, nth = source.partition("@") + hooks[base + int(rva, 16)] = (f"+{rva}", "count") + redirects[f"+{rva}"] = (int(nth or "1"), base + int(target, 16)) + modules[base] = os.path.basename(exe) + log(f"{time.time() - start:7.3f} process {os.path.basename(exe)} at {base:#x}") + if h_file: + k32.CloseHandle(wt.HANDLE(h_file)) + elif code == LOAD_DLL: + h_file, base = struct.unpack_from("<QQ", event, 16) + name = final_path(h_file) if h_file else "?" + modules[base] = name + module_paths[base] = final_path(h_file, True) if h_file else "" + log(f"{time.time() - start:7.3f} load {name} at {base:#x}") + if trace and name.lower() == "xgameruntime.dll": + # Gaming runtime: log which API interfaces the title asks for and the result. + k32.LoadLibraryExW.restype = wt.HMODULE + local = k32.LoadLibraryExW(r"C:\Windows\System32\xgameruntime.dll", None, 1) + for export in ("QueryApiImpl", "InitializeApiImpl", "InitializeApiImplEx", "InitializeApiImplEx2", "XErrorReport"): + address = k32.GetProcAddress(local, export.encode()) if local else 0 + if address: + hooks[base + (address - local)] = (export, "runtime") + if loader_break_seen: + arm(base + (address - local)) + if trace and name.lower() == "bink2scarlett.dll": + # Movie player: log opens/closes/frames and remember the registered frame buffers. + k32.LoadLibraryExW.restype = wt.HMODULE + local = k32.LoadLibraryExW(os.path.join(os.path.dirname(exe), name), None, 1) + for export in ("BinkOpenWithOptions", "BinkClose", "BinkNextFrame", "BinkRegisterFrameBuffers", + "BinkPause", "BinkShouldSkip"): + address = k32.GetProcAddress(local, export.encode()) if local else 0 + if address: + hooks[base + (address - local)] = (export, "bink") + if loader_break_seen: + arm(base + (address - local)) + if h_file: + k32.CloseHandle(wt.HANDLE(h_file)) + elif code == CREATE_THREAD: + log(f"{time.time() - start:7.3f} thread {tid} created") + live_threads.add(tid) + h_thread = struct.unpack_from("<Q", event, 16)[0] + if h_thread: + thread_handles[tid] = h_thread + elif code == 4: # EXIT_THREAD + live_threads.discard(tid) + thread_handles.pop(tid, None) # the system closes it when the event is continued + elif code == EXIT_PROCESS: + exit_code = struct.unpack_from("<I", event, 16)[0] + log(f"{time.time() - start:7.3f} exit {exit_code:#010x}") k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE) - continue - if (ex_code == 0xC000001D and first and host_cpu_on and not stop_first and main_base - and main_base <= ex_addr < main_base + 0x10000000): - name = rewrite_for_host(ex_addr) - if name: - host_cpu_rewritten.add(ex_addr) - elif sha_for_host(tid, ex_addr): - name = "sha (per hit)" - elif ex_addr in host_cpu_rewritten and (ex_addr, tid) not in host_cpu_resumed: - # Another thread ran the old instruction before the rewrite and its fault arrived after: - # continued, it runs the replacement. Once per thread, so a fault that stays is reported. - host_cpu_resumed.add((ex_addr, tid)) + break + elif code == OUTPUT_STRING: + addr, unicode, length = struct.unpack_from("<QHH", event, 16) + raw = read(addr, length * (2 if unicode else 1)) + text = raw.decode("utf-16-le" if unicode else "latin-1", errors="replace").rstrip("\0\r\n") + log(f"{time.time() - start:7.3f} debug-output {text[:300]}") + elif code == EXCEPTION: + ex_code, ex_flags, _, ex_addr, nparams = struct.unpack_from("<IIQQI", event, 16) + params = struct.unpack_from("<" + "Q" * min(nparams, 15), event, 16 + 32) if nparams else () + first = struct.unpack_from("<I", event, 16 + 152)[0] + label = NAMES.get(ex_code, "") + if ex_code == 0x80000003 and ex_addr in breakpoints: + handle_breakpoint(tid, ex_addr) k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE) continue - if name: - host_cpu_sites[name] = host_cpu_sites.get(name, 0) + 1 - if sum(host_cpu_sites.values()) <= 40: - log(f"{time.time() - start:7.3f} host-cpu {name} at {where(ex_addr)} rewritten") + if ex_code == 0x80000003 and ex_addr in retired: + # Another thread executed this INT3 before the hit limit restored the original byte, + # and its event arrived after that. Rewind and run the restored instruction. + thread, ctx = get_ctx(tid) + if thread: + struct.pack_into("<Q", ctx, 0xF8, ex_addr) + set_ctx(thread) + late_hits[ex_addr] = late_hits.get(ex_addr, 0) + 1 + k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE) + continue + log(f"{time.time() - start:7.3f} X2W_LOG_AT late hit at {where(ex_addr)} on thread {tid}: " + f"thread context unavailable (error {ctx_error[0]}), handled as a breakpoint") + if ex_code == 0x80000003 and ex_addr in ever_armed and read(ex_addr, 1) != b"\xcc": + # A thread that reached one of our int3s just before it was removed (its event was + # queued behind the removal): run the original instruction there. + thread, ctx = get_ctx(tid, 0x100003) + if thread: + struct.pack_into("<Q", ctx, 0xF8, ex_addr) + set_ctx(thread) + k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE) + continue + if ex_code == 0x80000004 and tid in stepping: + addr = stepping.pop(tid) + if addr in breakpoints: + write(addr, b"\xcc") k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE) continue - log(f"{time.time() - start:7.3f} exception {ex_code:#010x} {label} at {where(ex_addr)} " - f"{'first' if first else 'second'}-chance params={[hex(p) for p in params]}") - if ex_code == 0x80000003 and not loader_break_seen: - loader_break_seen = True # the loader's initial breakpoint - for addr in hooks: - arm(addr) - for rva in tuple(log_at): - addr = main_base + rva - region = query_region(addr) - # PAGE_EXECUTE variants use bits 4–7. Leave guard pages and other images alone. - if (region and region.AllocationBase == main_base and region.Protect & 0xf0 - and not region.Protect & 0x100 and arm(addr, skip_int3=True)): + if (ex_code == 0xC000001D and first and host_cpu_on and not stop_first and main_base + and main_base <= ex_addr < main_base + 0x10000000): + name = rewrite_for_host(ex_addr) + if name: + host_cpu_rewritten.add(ex_addr) + elif sha_for_host(tid, ex_addr): + name = "sha (per hit)" + elif ex_addr in host_cpu_rewritten and (ex_addr, tid) not in host_cpu_resumed: + # Another thread ran the old instruction before the rewrite and its fault arrived after: + # continued, it runs the replacement. Once per thread, so a fault that stays is reported. + host_cpu_resumed.add((ex_addr, tid)) + k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE) continue - log(f"X2W_LOG_AT ignored {rva:#x}: cannot arm a main-image instruction breakpoint") - del log_at[rva] - elif (ex_code == 0x80000003 and first and main_base and main_base <= ex_addr < main_base + 0x10000000 - and (skip_asserts == -1 or sum(asserts_seen.values()) < skip_asserts) - and (ex_addr - main_base) not in stop_at): - asserts_seen[ex_addr] = asserts_seen.get(ex_addr, 0) + 1 - status = DBG_CONTINUE # rip is already past the int3 - elif (not first) or stop_first or (ex_code == 0x80000003 and main_base and - main_base <= ex_addr < main_base + 0x10000000): - stop = (ex_code, ex_addr, tid, first, params) - log(f"debugger stop {ex_code:#010x} {'first' if first else 'second'}-chance") - break - elif ex_code in (0x406D1388, 0x40010006): - status = DBG_CONTINUE - else: - status = DBG_EXCEPTION_NOT_HANDLED - k32.ContinueDebugEvent(pid, tid, status) + if name: + host_cpu_sites[name] = host_cpu_sites.get(name, 0) + 1 + if sum(host_cpu_sites.values()) <= 40: + log(f"{time.time() - start:7.3f} host-cpu {name} at {where(ex_addr)} rewritten") + k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE) + continue + # A first-chance exception that repeats from one address is logged --log-repeats times, + # then counted (finished.txt). The stopping exception is always logged. + if not first or stop_first or repeat_ok((ex_code, ex_addr)): + log(f"{time.time() - start:7.3f} exception {ex_code:#010x} {label} at {where(ex_addr)} " + f"{'first' if first else 'second'}-chance params={[hex(p) for p in params]}") + else: + exception_repeats[(ex_code, ex_addr)] = exception_repeats.get((ex_code, ex_addr), 0) + 1 + if ex_code == 0x80000003 and not loader_break_seen: + loader_break_seen = True # the loader's initial breakpoint + for addr in hooks: + arm(addr) + for rva in tuple(log_at): + addr = main_base + rva + region = query_region(addr) + # PAGE_EXECUTE variants use bits 4–7. Leave guard pages and other images alone. + if (region and region.AllocationBase == main_base and region.Protect & 0xf0 + and not region.Protect & 0x100 and arm(addr, skip_int3=True)): + continue + log(f"X2W_LOG_AT ignored {rva:#x}: cannot arm a main-image instruction breakpoint") + del log_at[rva] + elif (ex_code == 0x80000003 and first and main_base and main_base <= ex_addr < main_base + 0x10000000 + and (skip_asserts == -1 or asserts_total < skip_asserts) and (ex_addr - main_base) not in stop_at): + asserts_seen[ex_addr] = asserts_seen.get(ex_addr, 0) + 1 + asserts_total += 1 + status = DBG_CONTINUE # rip is already past the int3 + elif (not first) or stop_first or (ex_code == 0x80000003 and main_base and + main_base <= ex_addr < main_base + 0x10000000): + if (ex_code, ex_addr) in exception_repeats: # make sure the stop itself is in events.txt + log(f"{time.time() - start:7.3f} exception {ex_code:#010x} {label} at {where(ex_addr)} " + f"{'first' if first else 'second'}-chance params={[hex(p) for p in params]}") + stop = (ex_code, ex_addr, tid, first, params) + log(f"debugger stop {ex_code:#010x} {'first' if first else 'second'}-chance") + break + elif ex_code in (0x406D1388, 0x40010006): + status = DBG_CONTINUE + else: + status = DBG_EXCEPTION_NOT_HANDLED + k32.ContinueDebugEvent(pid, tid, status) + except KeyboardInterrupt: + # Ctrl+C or a closed console: end the run as at a timeout, but with --fast-exit's + # short close, so the reports are still written. + interrupted = True + fast_exit = True + finally: + if profiler: + profiler.close() + # Also on an unexpected error in the loop: the buffered last half second is the part + # that explains a crash. + flush_logs(force=True) elapsed = time.time() - start - if stop and stop_at: - dump_threads(os.path.join(logdir, "threads_stop.txt")) + close_phases = [] # (name, seconds): how long each step of the close took, for finished.txt + + def timed(name, function, *args): + began = time.time() + try: + return function(*args) + finally: + close_phases.append((name, time.time() - began)) + if stop and (stop_at or not stop[3]): + # At an X2W_STOP_AT breakpoint and at a second-chance exception: every thread's full stack. + dumped = timed("threads_stop.txt", dump_threads, os.path.join(logdir, "threads_stop.txt")) + print(f" {len(dumped)} threads -> threads_stop.txt") if stop: ex_code, ex_addr, tid, first, params = stop print(f"stopped at {NAMES.get(ex_code, hex(ex_code))} ({ex_code:#010x}) at {where(ex_addr)} after {elapsed:.2f} s " @@ -851,9 +1226,15 @@ def poll_watches(): elif exit_code is not None: print(f"process exited with {exit_code:#010x} after {elapsed:.2f} s") else: - print(f"stopped by request after {elapsed:.2f} s (stop file)" if stop_requested - else f"timeout after {elapsed:.2f} s") - dumped = dump_threads(os.path.join(logdir, "threads.txt")) + if headroom_stop: + print(f"stopped: host commit headroom {headroom_stop[1] - headroom_stop[0]} MiB below {headroom_stop_mib} MiB " + f"(committed {headroom_stop[0]} / limit {headroom_stop[1]} MiB) after {elapsed:.2f} s") + fast_exit = True + if stop_requested: + print(f"stopped by request after {elapsed:.2f} s (stop file {stop_file})") + print(f"{'interrupted' if interrupted else 'headroom stop' if headroom_stop else 'stop requested' if stop_requested else 'timeout'} after {elapsed:.2f} s") + # --fast-exit: each thread's rip only (no stack walk); the full walk otherwise. + dumped = timed("threads.txt", dump_threads, os.path.join(logdir, "threads.txt"), not fast_exit) for item in filter(None, os.environ.get("X2W_DUMP", "").split(",")): rva, _, size = item.partition(":") blob = read(main_base + int(rva, 16), int(size or "64", 16)) or b"" @@ -864,13 +1245,18 @@ def poll_watches(): tops[top] = tops.get(top, 0) + 1 print(f" {len(dumped)} threads -> threads.txt; rip histogram: " + ", ".join(f"{k} x{v}" for k, v in sorted(tops.items(), key=lambda kv: -kv[1])[:8])) - if asserts_seen: - print(" asserts continued: " + ", ".join(f"{where(a)} x{n}" for a, n in asserts_seen.items())) + if asserts_seen: + print(" asserts continued: " + ", ".join(f"{where(a)} x{n}" for a, n in asserts_seen.items())) if host_cpu_sites: print(" host-cpu sites rewritten: " + ", ".join(f"{name} x{n}" for name, n in sorted(host_cpu_sites.items()))) + if capped or exception_repeats: + top = sorted(exception_repeats.items(), key=lambda kv: -kv[1])[:8] + print(f" not logged after {log_repeats} repeats (--log-repeats): " + + ", ".join([f"{name} x{n}" for name, n in sorted(capped.items())] + + [f"{NAMES.get(c, hex(c))} at {where(a)} x{n}" for (c, a), n in top])) if host_cpu_resumed: print(f" host-cpu threads resumed at a site another thread had rewritten: {len(host_cpu_resumed)}") - bink_report() + timed("bink", bink_report, not fast_exit) if os.environ.get("X2W_COUNT"): print(" hit counts: " + ", ".join(f"+{item} x{hit_counts.get('+' + item, 0)}" for item in os.environ["X2W_COUNT"].split(",") if item)) @@ -926,10 +1312,10 @@ def visit(hwnd, _): pixels = (ctypes.c_ubyte * (width * height * 4))() gdi32.GetDIBits(wt.HDC(memory), wt.HBITMAP(bitmap), 0, height, pixels, header, 0) raw = bytes(pixels) - rows = [] - for y in range(height): - line = raw[y * width * 4:(y + 1) * width * 4] - rows.append(bytes(1) + bytes(b for i in range(0, len(line), 4) for b in (line[i + 2], line[i + 1], line[i]))) + rgb = bytearray(width * height * 3) + rgb[0::3], rgb[1::3], rgb[2::3] = raw[2::4], raw[1::4], raw[0::4] + stride = width * 3 + rows = [bytes(1) + bytes(rgb[y * stride:(y + 1) * stride]) for y in range(height)] def chunk(kind, payload): body = kind + payload @@ -944,22 +1330,27 @@ def chunk(kind, payload): user32.GetWindowTextW(wt.HWND(hwnd), title, 128) print(f" window capture: {width}x{height} -> window.png (client area as on screen; title text length {len(title.value)})") - if exit_code is None: + if exit_code is None and not fast_exit: try: - capture_window() + timed("window", capture_window) except Exception as error: # diagnostics only print(f" window capture failed: {error}") - k32.TerminateJobObject(wt.HANDLE(job), 0xDEAD0002) + timed("terminate", k32.TerminateJobObject, wt.HANDLE(job), 0xDEAD0002) for h in (out, err, pi.hThread, pi.hProcess): k32.CloseHandle(wt.HANDLE(h)) - events.close() + for handle in open_logs: + handle.close() print(f"modules loaded: {len(modules)}") + print(f" close: {time.time() - start - elapsed:.2f} s after the run ended" + + (" (fast exit)" if fast_exit else "") + "".join(f", {name} {seconds:.2f} s" for name, seconds in close_phases)) with open(os.path.join(logdir, "finished.txt"), "w", encoding="utf-8") as handle: handle.write("\n".join(summary) + "\n") for name in ("stderr.txt", "trap.log"): path = os.path.join(logdir, name) if os.path.exists(path) and os.path.getsize(path): - print(f"--- {name}\n" + open(path, encoding="utf-8", errors="replace").read()[-3000:]) + with open(path, "rb") as handle: # only the end is shown: read the last 64 KiB, not the whole log + handle.seek(max(0, os.path.getsize(path) - 65536)) + print(f"--- {name}\n" + handle.read().decode("utf-8", errors="replace").replace("\r\n", "\n")[-3000:]) return 0 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 70f6d47670..81031fae9f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4,6 +4,13 @@ Scalar registers are also tracked symbolically at translation time so that pointer and descriptor values (tables, vertex-buffer table, root buffers) turn into HLSL resources instead of arithmetic. The output is HLSL for both stages plus a manifest that tells the runtime what to bind where. + +Offline trace warm-up: build the shader_trace_misses target, then run + gfx2hlsl.py --warm-trace CACHE TRACE SCANNER [--list] +Use --list to preview. Without it, pending requests are translated in CACHE +using the normal worker settings. Pass a staging cache to evaluate candidates. +The scanner ranks explicit logged misses by count; counts cover sampled trace +records only. Keys without a recognized request marker cannot be translated. """ import bisect from contextlib import suppress @@ -25,6 +32,14 @@ class Unsupported(Exception): pass +class StoredSrv(Unsupported): + """A descriptor first read as an SRV and later stored to; translate_to retries with it in rw_keys.""" + + def __init__(self, key, message): + super().__init__(message) + self.key = key + + PREFETCH = bytes.fromhex('0300a0bf') # DPP16 quad pair broadcasts (quad_perm of one lane of every horizontal or vertical pair into the other). The lanes of @@ -219,6 +234,76 @@ def starts_with_fetch_call(code): return len(code) >= 4 and struct.unpack_from('<I', code)[0] == FETCH_CALL +class VertexCode(bytes): + """Vertex instructions up to the one reachable S_ENDPGM; .image is the whole bounded section (code and the + data after the exit) in the same byte order, so code offset k is image offset k.""" + image = b'' + + +VERTEX_TRANSFERS = ('s_setpc_b64', 's_swappc_b64', 's_call_b64', 's_rfe_b64', 's_trap', 's_rfe_restore_b64', + 's_subvector_loop_begin', 's_subvector_loop_end') + + +def bound_vertex_code(code): + """Bound a vertex section that holds more than one S_ENDPGM word (pixel_aot.container_code, vertex_data). + + The instructions reachable from offset 0 are decoded one at a time, following fall-through and the + S_BRANCH / S_CBRANCH_* targets (the only transfers accepted, apart from the entry fetch call at offset 0, + which returns to offset 4). Exactly one S_ENDPGM may be reachable, and every reachable instruction must end + at or before it; the bytes after it are data. The linear decode of the bounded code (what Stage translates) + must start an instruction at every reachable offset, so both readings agree. -> VertexCode, or Unsupported. + """ + reachable, pending, exits = {}, [0], set() + while pending: + off = pending.pop() + if off in reachable: + continue + if off % 4 or not 0 <= off <= len(code) - 4: + raise Unsupported('vertex code: transfer to +0x%x outside the section' % off) + try: + n, name, asm, _ = D.decode_instruction(code, off) + except Exception as error: + raise Unsupported('vertex code: undecodable reachable word at +0x%x' % off) from error + reachable[off] = (n, name) + if name == 's_endpgm': + exits.add(off) + continue + if name == 's_swappc_b64' and off == 0 and starts_with_fetch_call(code): + pending.append(off + n) + continue + if name in VERTEX_TRANSFERS or name.startswith('s_endpgm_'): + raise Unsupported('vertex code: %s at +0x%x' % (name, off)) + if name == 's_branch' or name.startswith('s_cbranch_'): + if n != 4: + raise Unsupported('vertex code: branch form %s at +0x%x' % (asm, off)) + pending.append(off + 4 + 4 * struct.unpack_from('<h', code, off)[0]) + if name == 's_branch': + continue + pending.append(off + n) + if len(exits) != 1: + raise Unsupported('vertex code: %d reachable S_ENDPGM' % len(exits)) + end = max(exits) + 4 + if any(off + n > end for off, (n, _) in reachable.items()): + raise Unsupported('vertex code: reachable instruction after the exit') + bounded = VertexCode(code[:end]) + linear = {off for off, _, _, _ in decode(bounded)} + if not set(reachable) <= linear: + raise Unsupported('vertex code: linear decode disagrees with the reachable boundaries') + bounded.image = bytes(code) + return bounded + + +def stream_stage_code(blob, stage): + """The bounded native code of one stream stage container (slot 86): a vertex stage with data after its single + reachable exit comes back as VertexCode (bound_vertex_code).""" + from pixel_aot import container_code + from resource_inventory import parts + code = container_code(parts(blob)[b'DXIL'], stage=stage, vertex_data=stage == 1) + if stage == 1 and sum(w == 0xbf810000 for w, in struct.iter_unpack('<I', code[:len(code) // 4 * 4])) > 1: + return bound_vertex_code(code) + return code + + def parse_input_layout(text): """'ia1 <n>' then one '<semantic> <index> <format> <slot> <offset> <class> <step>' line per element.""" lines = text.split('\n') @@ -304,8 +389,12 @@ def stream_fetch(vs_container, layout_text): # 0, 0, 0), count at +0x29c. Pixel (header 0xef8 bytes): from +0x138 one 8-byte record per attribute (kind 6, # input-signature register, component mask, attribute index, 0, 0, the register again, interpolation 1 or 2), count # at +0x238. Records with other values pack two signature registers into one parameter or attribute; that form is -# refused here. +# refused here. A vertex record of kind 7 names an SV_ClipDistance output register that the stage also exports as +# a parameter (measured: in the archive's 2191 distinct vertex containers all 29 kind-7 records name the +# SV_CLIPDISTANCE register, and each of the 29 containers with that output has one; kind 8 names SV_CULLDISTANCE +# and stays refused). No pixel attribute links to a system-value output, so the parameter is not linked. IFACE_VS_RECORDS, IFACE_VS_COUNT, IFACE_PS_HEADER_BASE, IFACE_PS_RECORDS, IFACE_PS_COUNT = 0x1dc, 0x29c, 0xef8, 0x138, 0x238 +D3D_NAME_POSITION, D3D_NAME_CLIP_DISTANCE = 1, 2 # signature system-value codes (D3D_NAME) def signature_entries(part): @@ -353,13 +442,19 @@ def stream_interface(vs_container, ps_container): count = struct.unpack_from('<I', vs_image, IFACE_VS_COUNT)[0] if count > (IFACE_VS_COUNT - IFACE_VS_RECORDS) // 6: raise Unsupported('vertex output table exceeds its header range') + vs_outputs = signature_entries(vs[b'OSG1']) + clip_registers = {entry[0] for entry in vs_outputs if entry[3] == D3D_NAME_CLIP_DISTANCE} + system_params = set() for i in range(count): kind, register, param, *rest = vs_image[IFACE_VS_RECORDS + 6 * i:IFACE_VS_RECORDS + 6 * i + 6] + if kind == 7 and param == i and not any(rest) and register in clip_registers - system_params: + system_params.add(register) + continue if kind != 6 or param != i or any(rest) or register in params: raise Unsupported('unverified vertex output record %s' % vs_image[IFACE_VS_RECORDS + 6 * i:IFACE_VS_RECORDS + 6 * i + 6].hex()) params[register] = param outputs = {} - for register, name, index, system, mask in signature_entries(vs[b'OSG1']): + for register, name, index, system, mask in vs_outputs: if system: continue if (name, index) in outputs: @@ -388,6 +483,14 @@ def stream_interface(vs_container, ps_container): INTERP_DST_HIGH = 'op_sel:[0,0,0,1]' +LDS_UNUSED_W1_MASK = { + 'ds_write2_b32': 0xff000000, 'ds_write2st64_b32': 0xff000000, 'ds_read2st64_b32': 0x00ffff00, + **dict.fromkeys(('ds_add_u32', 'ds_min_u32', 'ds_max_u32', 'ds_and_b32', 'ds_or_b32'), 0xffff0000), + **dict.fromkeys(('ds_add_rtn_u32', 'ds_min_rtn_u32', 'ds_max_rtn_u32', 'ds_and_rtn_b32', + 'ds_or_rtn_b32', 'ds_wrxchg_rtn_b32'), 0x00ff0000), +} + + def check_encoding(code, off, n, name, asm): # These SOP1 forms have an unused field that the disassembler does not print. # Only the ordinary four-byte encodings (no literal or hidden operand) are used @@ -397,18 +500,8 @@ def check_encoding(code, off, n, name, asm): unused = word & (0xff if name == 's_getpc_b64' else 0x7f0000) if n != 4 or unused: raise Unsupported('s_setpc_b64: unsupported %s encoding at +0x%x' % (name, off)) - if name in ('v_interp_p1ll_f16', 'v_interp_p2_f16'): - # The shared disassembler ignores op_sel (w0[14:11]) here, as LLVM 15 does (its VOP3Interp_gfx10 encoding - # leaves bits 14:11 undefined). Only Mesa ACO states a meaning: v_interp_p2_hi_f16 is p2 with op_sel 0x8 (bit - # 14, aco_assembler.cpp), which writes the high half of the destination; register allocation turns p2 into it - # for a 16-bit value at byte 2 of a register that holds another 16-bit value. It is passed on as the printed - # LLVM modifier `op_sel:[0,0,0,1]`. The attribute half `high` is a different bit (w1[8]) and is printed. - sel = struct.unpack_from('<I', code, off)[0] >> 11 & 15 - if sel == 8 and name == 'v_interp_p2_f16': - return asm + ' ' + INTERP_DST_HIGH - if sel: - raise Unsupported('%s with op_sel 0x%x: only the plain form and, on v_interp_p2_f16, op_sel 0x8 ' - '(destination high half) are lowered' % (name, sel)) + # LOCAL: v_interp_p1ll_f16 / v_interp_p2_f16 op_sel is read by the local interp lowering from the raw words + # (interp_f16_mods), so upstream's decode-time op_sel refusal is not taken. if name == 'image_load_mip': # The shared disassembler does not expose these gfx10 MIMG flags. word0, word1 = struct.unpack_from('<2I', code, off) @@ -821,6 +914,112 @@ def smem_offset(tok): return '0' if tok == 'off' else tok +SGPR_NAMES = {'vcc_lo': (106,), 'vcc_hi': (107,), 'vcc': (106, 107), 'm0': (124,)} +# SALU forms whose first operand is written and not read (D = f(S0, S1)); others that name D first also read it +# (s_addk_i32, s_mulk_i32, s_cmovk_i32, s_cmov_*, s_bitset*, s_movrel*) or do not write it (compares, stores). +SALU_NO_DST = ('s_cmp', 's_bitcmp', 's_cbranch', 's_branch', 's_store', 's_buffer_store', 's_atomic', 's_buffer_atomic', + 's_scratch_store', 's_waitcnt', 's_nop', 's_setpc', 's_setreg', 's_sendmsg', 's_endpgm', 's_clause', + 's_inst_prefetch', 's_dcache', 's_barrier', 's_sleep', 's_set', 's_ttrace', 's_icache', 's_denorm', + 's_round', 's_trap', 's_decperflevel', 's_incperflevel', 's_code_end') +SALU_READS_DST = ('s_addk', 's_mulk', 's_cmovk', 's_cmov_', 's_bitset', 's_movrel', 's_getreg') + + +def sgpr_access(name, asm): + """(SGPRs read, SGPRs written) by one instruction, vcc and m0 included, exec and SCC left out. + + Conservative where the form is not listed: a register operand that is not known to be written only counts as + read, so a caller that refuses on a read never misses one.""" + def regs(tok): + r = reg_range(tok) + if r: + return set(range(r[1], r[2] + 1)) if r[0] == 's' else set() + return set(SGPR_NAMES.get(tok, ())) + _, ops, _ = parse(asm) + reads, writes = set(), set() + for t in ops: + reads |= regs(t) + first = regs(ops[0]) if ops else set() + base = re.sub(r'_(e32|e64|sdwa|dpp)$', '', name) + if name.startswith('s_'): + if not name.startswith(SALU_NO_DST) and not name.startswith(SALU_READS_DST): + writes, reads = first, reads - first if ops[1:] and not any(regs(t) & first for t in ops[1:]) else reads + elif (base in ('v_readfirstlane_b32', 'v_readlane_b32') or + (base.startswith('v_cmp_') and name.endswith(('_e64', '_sdwa')))) and first: + writes = first + reads = set().union(*(regs(t) for t in ops[1:])) if ops[1:] else set() + if name.startswith('v_cmp_') and name.endswith('_e32'): + writes |= {106} + if name.startswith('v_') and name.endswith('_e32') and re.search(r'cndmask|addc|subb|_co_|div_fmas', name): + reads |= {106, 107} + if name.startswith('s_cbranch_vcc'): + reads |= {106, 107} + return reads, writes + + +WATERFALL_MASK64 = re.compile(r'^s_(and|or|xor|andn2|orn2|nand|nor|xnor|not|cselect)_b64$|^s_\w+_saveexec_b64$') + + +def waterfall_sgpr_access(name, asm, wave64): + """(reads, writes, mask_high, high_reads) for the waterfall checks: sgpr_access, with an SMEM load writing only + its destination and a VOPC with an implicit vcc destination not reading it. + + In wave64 code (the loop closed by s_andn2_wrexec_b64) a VALU lane mask is an SGPR pair printed as its low + register. The model computes the low register only: a VOPC writes the high one in hardware (mask_high) but not + in the model, so it is not counted as written. high_reads: registers read only as the high half of a lane-mask + pair (64-bit mask SALU sources, VALU mask operands), where the model reads the low half alone.""" + reads, writes = sgpr_access(name, asm) + _, ops, _ = parse(asm) + mask_high, high_reads = set(), set() + + def regs(tok): + r = reg_range(tok) + if r: + return set(range(r[1], r[2] + 1)) if r[0] == 's' else set() + return set(SGPR_NAMES.get(tok, ())) + if name.startswith(('s_load_', 's_buffer_load_')) and ops: + reads, writes = set().union(*(regs(t) for t in ops[1:])), regs(ops[0]) + if name.startswith('v_cmp_') and name.endswith('_e32') and ops and ops[0] in ('vcc_lo', 'vcc'): + reads = set().union(*(regs(t) for t in ops[1:])) # the VOPC destination is implicit, not read + if not wave64: + return reads, writes, mask_high, high_reads + if name.startswith('v_'): + if name.startswith('v_cmp_') and len(writes) == 1: + mask_high = {min(writes) + 1} + if name.endswith('_e64') and re.search(r'cndmask|addc|subb|_co_ci', name) and ops: + mask = regs(ops[-1]) + if len(mask) == 1: + high_reads = {min(mask) + 1} + if name.endswith('_e32') and re.search(r'cndmask|addc|subb|div_fmas', name): + high_reads = {107} + if 106 in reads and 'vcc_lo' in ops[1:]: + high_reads = high_reads | {107} + reads = reads | high_reads + elif WATERFALL_MASK64.match(name): + for t in ops[1:]: + pair = sorted(regs(t)) + if len(pair) == 2 and pair[1] == pair[0] + 1: + high_reads.add(pair[1]) + return reads, writes, mask_high, high_reads + + +def sopk_simm(tok): + """A SOPK SIMM16 operand sign-extended to 32 bits, as a hex token (upstream #2116, open). Refuses anything that + is not a 16-bit literal.""" + if not re.fullmatch(r'0x[0-9a-f]{1,4}|\d+', tok) or int(tok, 0) > 0xffff: + raise Unsupported('SOPK immediate %s' % tok) + value = int(tok, 0) + return '0x%08x' % ((value - 0x10000 if value & 0x8000 else value) & 0xffffffff) + + +def smem_imm_refuse(base, ops, mods): + """Refuse a negative SMEM immediate offset (upstream #1984 / ed7d09a4). OFFSET[20:0] is signed on RDNA 2: + disasm_rdna2 prints a negative one as -0x.., an older decoder as 0x100000..0x1fffff; either would otherwise + be added as a positive byte offset.""" + toks = [ops[2]] if len(ops) > 2 else [] + toks += [m[7:] for m in mods if m.startswith('offset:')] + for tok in toks: + if re.fullmatch(r'-?(0[xX][0-9a-fA-F]+|\d+)', tok) and not 0 <= int(tok, 0) <= 0xfffff: + raise Unsupported('%s: SMEM immediate offset %s' % (base, tok)) def smem_mods(mods): """Non-negative 21-bit signed immediate byte offset from SMEM modifiers, refusing unknown or negative forms.""" imm = None @@ -1118,6 +1317,184 @@ def clobber(written): return lowered +PC_DATA_LOAD = re.compile(r'global_load_dword(x[234])?$') +# Conservatively: forms whose first operand may also be read (tied, partial or packed writes, sources, stores). +PC_DATA_TIED = re.compile(r'mac|_sdwa|_dpp|writelane|movrel|cmpx|_f16|_b16|_u16|_i16|d16|pk_|interp|swap|bitset|cmov' + r'|^s_\w+k_|^s_cmp|^s_bitcmp|store|atomic|^exp|ds_write|^s_cbranch|^s_branch|^s_set' + r'|^s_sendmsg|^s_wait|^s_nop|^s_inst|^v_nop|_lo$|_hi$') +PC_DATA_VCC_READERS = ('v_cndmask_b32', 'v_add_co_ci_u32', 'v_sub_co_ci_u32', 'v_subrev_co_ci_u32', 'v_addc_u32', + 'v_subb_u32', 'v_subbrev_u32', 'v_div_fmas_f32', 'v_div_fmas_f64', 's_cbranch_vccz', + 's_cbranch_vccnz') + + +def pc_data_registers(text): + """The SGPR and VGPR words an operand text names (('s', n) / ('v', n)); vcc and exec as s106-107 / s126-127.""" + out = set() + for kind, low, high, single in re.findall(r'\b([sv])(?:\[(\d+):(\d+)\]|(\d+)\b)', text): + out.update((kind, n) for n in (range(int(low), int(high) + 1) if not single else (int(single),))) + # vcc_lo and vcc_hi are one unit: a wave64 carry is printed as vcc_lo, so a tag covers both halves. + for name, regs in (('vcc', (106, 107)), ('vcc_lo', (106, 107)), ('vcc_hi', (106, 107)), ('src_vccz', (106, 107)), + ('exec', (126, 127)), ('exec_lo', (126,)), ('exec_hi', (127,)), ('src_execz', (126, 127))): + if re.search(r'\b%s\b' % name, text): + out.update(('s', n) for n in regs) + return out + + +def pc_data_proof(ins): + """A code address read by S_GETPC_B64 that only addresses words of the shader's own image (a constant table + after the exit, see bound_vertex_code) -> {offset: role}, or {} for a program without S_GETPC_B64. + + Lowering. The image is placed at virtual address 0: code offset k is address k. RDNA 2 GETPC returns the + address of its successor, so the exact triple + s_getpc_b64 s[p:p+1]; s_add_u32 sp, sp, D; s_addc_u32 sp+1, sp+1, (D < 0 ? -1 : 0) + leaves the virtual address getpc + 4 + D in s[p:p+1]; roles 'getpc' (emits nothing), ('lo', p, word) and + ('hi', p + 1, word). Every later 64-bit addition of an ordinary integer gives the same offset from the image + start on hardware and here, so a GLOBAL_LOAD_DWORD{,X2,X3,X4} whose address is such a sum reads the image word + at that offset (role ('load', getpc)). The SCC of the low add is consumed by the ADDC; the ADDC's own SCC + depends on the real load address, so the caller treats it as not modelled (check_scc). + + Proof (forward data flow over fall-through and direct branches, joins merged, loops to a fixed point). The + address words are tagged: the GETPC pair (lo/hi), V_ADD_CO_U32 of exactly one tagged low word and an untagged + operand (a new lo, and a carry in its SGPR destination), V_ADD_CO_CI_U32 of exactly one tagged high word, an + untagged operand and the carry of the addition that produced that high word's low partner (a new hi). The + load's address pair must be the lo and hi of the same addition on every path. Any other read of a tagged + word, including the high carry, is refused, as is a join where a word is tagged on only some paths and then + read. A write clears a tag: SALU and SGPR destinations are whole writes; a VALU write only reaches active lanes, + so an EXEC write while any VGPR is tagged is refused (every lane then holds the tag the analysis has). No + S_SETPC_B64 may be present (calculated_pc_proof owns those programs). A GETPC that is not the triple, or a + program in which no load reads the pair, is not claimed ({}): lower() then refuses GETPC with its reason. + """ + if not any(name == 's_getpc_b64' for _, _, name, _ in ins): + return {} + if any(name == 's_setpc_b64' for _, _, name, _ in ins): + return {} + index = {off: i for i, (off, _, _, _) in enumerate(ins)} + + def refuse(off, reason): + raise Unsupported('s_getpc_b64 data pointer: %s at +0x%x' % (reason, off)) + + targets, succ = set(), [] + for i, (off, n, name, asm) in enumerate(ins): + nxt = [i + 1] if i + 1 < len(ins) and name not in ('s_branch', 's_endpgm') else [] + if name == 's_branch' or name.startswith('s_cbranch_'): + try: + target = int(parse(asm)[1][0].split('_0x')[1], 16) + except (IndexError, ValueError): + refuse(off, 'unsupported branch operand') + if target not in index: + refuse(off, 'branch target %#x outside the decoded program' % target) + targets.add(target) + nxt.append(index[target]) + succ.append(nxt) + + roles, bases = {}, {} + for i, (off, n, name, asm) in enumerate(ins): + if name != 's_getpc_b64': + continue + _, ops, mods = parse(asm) + p = pc_pair(ops[0]) if len(ops) == 1 and not mods else None + if p is None or i + 2 >= len(ins): + return {} + (add_off, _, add_name, add_asm), (addc_off, _, addc_name, addc_asm) = ins[i + 1], ins[i + 2] + _, add_ops, add_mods = parse(add_asm) + _, addc_ops, addc_mods = parse(addc_asm) + disp = pc_word(add_ops[2]) if len(add_ops) == 3 else None + if (add_name != 's_add_u32' or add_mods or add_ops[:2] != ['s%d' % p] * 2 or disp is None + or addc_name != 's_addc_u32' or addc_mods or len(addc_ops) != 3 + or addc_ops[:2] != ['s%d' % (p + 1)] * 2 or pc_word(addc_ops[2]) != (-1 if disp < 0 else 0)): + return {} # not this form: the GETPC refusal in lower() names the reason + if add_off in targets or addc_off in targets: + refuse(off, 'branch into the address calculation') + value = (off + 4 + disp) & 0xffffffffffffffff + roles[off] = ('getpc',) + bases[off] = value + roles[add_off] = ('lo', p, value & 0xffffffff) + roles[addc_off] = ('hi', p + 1, value >> 32) + + def merged(a, b): + out = {} + for reg in a.keys() | b.keys(): + out[reg] = a.get(reg) if a.get(reg) == b.get(reg) else ('mixed',) + return out + + def transfer(off, name, asm, state): + base = re.sub(r'_e(32|64)$', '', name) + _, ops, mods = parse(asm) + role = roles.get(off) + if role is not None and role[0] != 'load': + if role[0] == 'getpc': + p = pc_pair(ops[0]) + return {**state, ('s', p): ('lo', off, None), ('s', p + 1): ('hi', off, None)} + return state # the add and addc of the triple: the pair already holds its final tags + tag = lambda tok: [state[r] for r in sorted(pc_data_registers(tok)) if r in state] + if base in ('v_add_co_u32', 'v_add_co_ci_u32') and any(tag(t) for t in ops[2:]): + carry_in = base == 'v_add_co_ci_u32' + d = reg_range(ops[0]) if ops else None + if mods or len(ops) != (5 if carry_in else 4) or not d or d[0] != 'v' or d[1] != d[2]: + refuse(off, 'address addition %s' % asm) + a, b = tag(ops[2]), tag(ops[3]) + want = 'hi' if carry_in else 'lo' + if len(a + b) != 1 or len((a + b)[0]) != 3 or (a + b)[0][0] != want or \ + len(pc_data_registers(ops[2] if a else ops[3])) != 1: + refuse(off, 'address addition %s does not add one untagged word to one %s word' % (asm, want)) + word = (a + b)[0] + out = {reg: t for reg, t in state.items() if reg not in pc_data_registers(ops[0] + ' ' + ops[1])} + sdst = pc_data_registers(ops[1]) + if carry_in: + carry = tag(ops[4]) + if len(set(carry)) != 1 or len(pc_data_registers(ops[4])) != len(carry) or \ + carry[0][:2] != ('carry', word[1]) or carry[0][3] != word[2]: + refuse(off, 'high address word %s without the carry of its low word' % asm) + out[('v', d[1])] = ('hi', word[1], carry[0][2]) + out.update((reg, ('dead',)) for reg in sdst) + else: + out[('v', d[1])] = ('lo', word[1], off) + out.update((reg, ('carry', word[1], off, word[2])) for reg in sdst) + return out + if PC_DATA_LOAD.match(base): + a = reg_range(ops[1]) if len(ops) == 3 else None + words = [state.get(('v', a[1])), state.get(('v', a[1] + 1))] if a and a[0] == 'v' else [] + if any(words): + lo, hi = words + if (a[2] != a[1] + 1 or ops[2] != 'off' or not lo or not hi or lo[0] != 'lo' or hi[0] != 'hi' + or lo[1:] != hi[1:] or lo[2] is None + or any(m not in ('glc', 'slc', 'dlc') for m in mods)): + refuse(off, 'load %s is not through one proven image address' % asm) + roles[off] = ('load', lo[1], bases[lo[1]]) + d = reg_range(ops[0]) + return {reg: t for reg, t in state.items() if not (reg[0] == 'v' and d[1] <= reg[1] <= d[2])} + if 'movrel' in name and state: + refuse(off, '%s (indirect through m0) while an address word is live' % name) + tied = not name.startswith(('v_', 's_', 'buffer_load', 'tbuffer_load', 'global_load', 'image_', 'ds_read')) \ + or PC_DATA_TIED.search(name) or set(mods) & {'tfe', 'lwe', 'd16'} + read = pc_data_registers(', '.join(ops if tied else ops[1:]) + ' ' + ' '.join(mods)) + if base in PC_DATA_VCC_READERS: + read |= {('s', 106), ('s', 107)} + hit = sorted(reg for reg in read if reg in state) + if hit: + refuse(off, '%s%d (%s) is read by %s' % (hit[0][0], hit[0][1], state[hit[0]][0], name)) + if writes_exec(name, ops) and any(reg[0] == 'v' for reg in state): + refuse(off, '%s writes EXEC while a VGPR holds an address word' % name) + written = set() + for tok in destinations(name, ops): + written |= pc_data_registers(tok) + return {reg: t for reg, t in state.items() if reg not in written} + + states = {0: {}} + pending = [0] + while pending: + i = pending.pop() + off, _, name, asm = ins[i] + out = transfer(off, name, asm, states[i]) + for j in succ[i]: + new = out if j not in states else merged(states[j], out) + if states.get(j) != new: + states[j] = new + pending.append(j) + # A pair no load reads keeps the GETPC refusal (lower()); only the table form above is claimed. + return roles if any(role[0] == 'load' for role in roles.values()) else {} + + def _lds_single(tok): """Single hardware VGPR vN (v0..v255) for bounded LDS exchange validation.""" m = re.fullmatch(r'v(\d+)', tok) @@ -1614,8 +1991,213 @@ def lands(key, index, what): return out +# Lane-bit facts: what the emitted HLSL has assigned to its scalar variables, as ('v', word) for a known word or +# ('b', bit) for a known bit 0 (the one-lane model keeps a lane mask as bit 0). They are read off the emitted lines +# only, so they describe the variables the HLSL computes with, whatever the register's symbolic state. +LANE_FACT_NAMES = re.compile(r'(s\d+|exec|vcc|scc|xsave)$') +LANE_FACT_ASSIGN = re.compile(r'\b(s\d+|exec|vcc|scc|xsave)\s*(?:<<|>>|[-+*/%&|^])?=(?!=)') +LANE_FACT_TOKEN = re.compile(r'\s*(0x[0-9a-fA-F]+u?|\d+u?|[A-Za-z_]\w*|==|!=|&&|\|\||<<|>>|.)') + + +def lane_fact_eval(expr, facts): + """(word, bit) of an HLSL uint expression over ~ & | ^, literals and fact names; None for an unknown part. + A parenthesised part the grammar does not cover is an unknown value; anything else outside one makes the + whole expression unknown.""" + toks = [t for t in LANE_FACT_TOKEN.findall(expr) if t.strip()] + pos = [0] + unknown = (None, None) + + class Bad(Exception): + pass + + def peek(): + return toks[pos[0]] if pos[0] < len(toks) else None + + def take(): + pos[0] += 1 + return toks[pos[0] - 1] + + def atom(): + t = peek() + if t is None: + raise Bad + if t == '~': + take() + w, b = atom() + return (~w & 0xffffffff if w is not None else None, 1 - b if b is not None else None) + if t == '(': + take() + start = pos[0] + try: + value = binary(0) + if peek() != ')': + raise Bad + take() + return value + except Bad: + pos[0], depth = start, 1 + while depth: + t = take() if peek() is not None else None + if t is None: + raise Bad + depth += {'(': 1, ')': -1}.get(t, 0) + return unknown + take() + m = re.fullmatch(r'(0x[0-9a-fA-F]+|\d+)u?', t) + if m: + w = int(m.group(1), 0) & 0xffffffff + return w, w & 1 + if LANE_FACT_NAMES.match(t) or re.fullmatch(r'[A-Za-z_]\w*', t): + if peek() in ('(', '.', '['): + raise Bad + f = facts.get(t) + if f is None: + return unknown + return (f[1], f[1] & 1) if f[0] == 'v' else (None, f[1]) + raise Bad + + def combine(op, a, b): + (wa, ba), (wb, bb) = a, b + if op == '&': + w = wa & wb if wa is not None and wb is not None else 0 if 0 in (wa, wb) else None + if w is None and (wa == 1 or wb == 1): + w = bb if wa == 1 else ba # x & 1 is bit 0 of x + bit = 0 if 0 in (ba, bb) else 1 if ba == bb == 1 else None + elif op == '|': + w = wa | wb if wa is not None and wb is not None else 0xffffffff if 0xffffffff in (wa, wb) else None + bit = 1 if 1 in (ba, bb) else 0 if ba == bb == 0 else None + else: + w = wa ^ wb if wa is not None and wb is not None else None + bit = ba ^ bb if ba is not None and bb is not None else None + return (w, bit if w is None else w & 1) + + levels = ('|', '^', '&') + + def binary(level): + if level == len(levels): + return atom() + value = binary(level + 1) + while peek() == levels[level]: + take() + value = combine(levels[level], value, binary(level + 1)) + return value + + try: + value = binary(0) + if peek() is not None: + return unknown + return value + except Bad: + return unknown + + +def lane_fact_statement(name, expr, facts): + """Update facts for the HLSL statement `name = expr`.""" + m = re.fullmatch(r'(.*?)\s*(==|!=)\s*(0x0+u?|0u?)', expr) + if m: + w, b = lane_fact_eval(m.group(1), facts) + if w is None: + facts.pop(name, None) + return + facts[name] = ('v', int((w != 0) == (m.group(2) == '!='))) + return + w, b = lane_fact_eval(expr, facts) + if w is not None: + facts[name] = ('v', w) + elif b is not None: + facts[name] = ('b', b) + else: + facts.pop(name, None) + + +def lane_facts_after(lines, facts): + """The facts after the emitted lines run. Only an unconditional top-level `name = expr;` is evaluated; any other + assignment to a fact name (inside braces, after an if or else, a compound assignment) forgets that name.""" + if facts is None: + return None + facts = dict(facts) + text = '\n'.join(re.sub(r'//.*', '', line) for line in lines) + depth, start = 0, 0 + pieces = [] + for i, c in enumerate(text + ';'): + if c in ';{}': + pieces.append((text[start:i], depth)) + depth += {'{': 1, '}': -1}.get(c, 0) + start = i + 1 + for piece, level in pieces: + s = piece.strip() + m = re.fullmatch(r'(s\d+|exec|vcc|scc|xsave)\s*=(?!=)\s*(.+)', s, re.S) + if m and level == 0: + lane_fact_statement(m.group(1), m.group(2), facts) + continue + for n in LANE_FACT_ASSIGN.findall(s): + facts.pop(n, None) + return facts + + +def lane_facts_merge(states): + """Facts at a join: those every reachable incoming edge agrees on (None: no edge is reachable).""" + live = [s for s in states if s is not None] + if not live: + return None + out = {} + for name, fact in live[0].items(): + if all(s.get(name) == fact for s in live[1:]): + out[name] = fact + continue + bits = {(f[1] & 1) if f and f[0] == 'v' else f[1] if f else None for f in (s.get(name) for s in live)} + if len(bits) == 1 and None not in bits: + out[name] = ('b', bits.pop()) + return out + + +def lane_fact_bit(facts, name): + f = facts.get(name) if facts is not None else None + return None if f is None else f[1] & 1 + + +def lane_branch_edges(cond, facts): + """(facts on the taken edge, facts on the fall-through) of an emitted branch condition; None for an edge the + known condition rules out.""" + if facts is None: + return None, None + forms = {'(exec & 1) == 0': ('exec', 0), '(exec & 1) != 0': ('exec', 1), '(vcc & 1) == 0': ('vcc', 0), + '(vcc & 1) != 0': ('vcc', 1), 'scc': ('scc', 1), '!scc': ('scc', 0)} + if cond not in forms: + return dict(facts), dict(facts) + name, want = forms[cond] + known = lane_fact_bit(facts, name) + if name == 'scc': + f = facts.get('scc') + known = None if f is None or f[0] != 'v' else int(f[1] != 0) + taken, fall = dict(facts), dict(facts) + if name == 'scc': + taken['scc'], fall['scc'] = ('v', want), ('v', 1 - want) + else: + taken[name], fall[name] = ('b', want), ('b', 1 - want) + if facts.get(name) and facts[name][0] == 'v': + taken[name], fall[name] = facts[name], facts[name] + if known is not None: + return (taken if known == want else None), (fall if known != want else None) + return taken, fall + + +# Symbols vcc_descriptor_copy carries through vcc. +VCC_WORD_KINDS = ('desc', 'descnum', 'ptr', 'ptrhi') +# Mask ops whose bit 0 does not depend on S when this lane's exec bit is the given value: +# base -> (operand positions exec may take, that exec bit). +EXEC_ABSORB = { + 's_and_b32': ((0, 1), 0), 's_and_b64': ((0, 1), 0), 's_or_b32': ((0, 1), 1), 's_or_b64': ((0, 1), 1), + 's_andn2_b32': ((1,), 1), 's_andn2_b64': ((1,), 1), 's_orn2_b32': ((1,), 0), 's_orn2_b64': ((1,), 0), + 's_nand_b64': ((0, 1), 0), 's_nor_b64': ((0, 1), 1), +} + + class Stage: """Translates one stage. Shares the resource and entry-constant registries of its pipeline.""" + uses_q = False + uses_swap = False + uses_xsave = False # Immutable fallbacks for unit probes that bypass __init__; __init__ and translate() assign fresh # per-instance sets, so nothing is shared across Stage instances. @@ -1638,51 +2220,44 @@ class Stage: def __init__(self, pipe, kind, code, refusals=None, decoded=None): self.pipe, self.kind = pipe, kind + self.raw = strip_header(code) # instruction words, for encoding bits the decoder does not print self.refusals = refusals self.raw_code = strip_header(code) + image = getattr(code, 'image', b'') # bound_vertex_code: the words after the exit (pc_data_proof) + self.pc_image = image[len(code) - len(self.raw):] if image else self.raw if refusals is None: - self.ins = decode(self.raw_code) + self.ins = decode(self.raw) else: - self.ins = decode(self.raw_code, refusals) if decoded is None else decoded - if kind == 'ms': - self.mesh_vcc_branches = {} - self.ins = mesh_skeleton(self.ins, self.mesh_vcc_branches) - # A loop header is translated before the back edges into it, so whether a back edge brings the symbol kept - # there is known only afterwards: translate again with that register read at run time or refused there. A - # register only moves from kept to 'run' to 'refuse', so this ends. - self.force_joined = {} # branch target -> register -> 'run' | 'refuse' - first_refusal = len(refusals) if refusals is not None else 0 - while True: - self.lines = [] # body statements (per block) - self.sym = {} # scalar register -> symbolic value - self.used_s, self.used_v = set(), set() - self.used_atomic = set() - self.exec_known = True # exec still equals the entry mask (the lane is active) - self.wqm_exec = False # exec is proven whole-quad: an s_wqm of exec into itself ran while exec_known - self.exports = {} # 'pos0' / 'paramN' / 'mrtN' -> [4 expressions] - self.write_masks = {} # 'mrtN' -> channels the export writes (bit c = channel c), see export() - self.attrs = {} # pixel: attr index -> 'linear' | 'flat' | 'f16' - self.compr_params = set() # vertex: param indices exported with the compr flag (packed binary16 pairs) - self.plain_params = {} # vertex: param index -> channels exported as `off` by its latest plain export - self.f16_plain = {} # pixel: attr index -> channels read as binary16 halves of a plain export - self.uses_pos = False - self.masks = set() # scalar registers currently holding lane masks - self.fetched = False # vertex: the entry call into the fetch routine was translated as loads - self.defined_uniform_s = set() - self.bad_sgprs = set() - self._uniform_written = set() - self.setup_entry() - self.translate() - grown = False - for t, regs in self.back_force.items(): - have = self.force_joined.setdefault(t, {}) - for reg, kind in regs.items(): - if have.get(reg) not in (kind, 'refuse'): - have[reg], grown = kind, True - if not grown: - break - if refusals is not None: - del refusals[first_refusal:] + self.ins = decode(self.raw, refusals) if decoded is None else decoded + if kind == 'ms' and getattr(pipe, 'uses_mesh_skeleton', False): + self.ins = mesh_skeleton(self.ins) + self.lines = [] # body statements (per block) + self.sym = {} # scalar register -> symbolic value + self.used_s, self.used_v = set(), set() + self.exec_known = True # exec still equals the entry mask (the lane is active) + self.wqm_exec = False # exec is proven whole-quad: an s_wqm of exec into itself ran while exec_known + self.exports = {} # 'pos0' / 'paramN' / 'mrtN' -> [4 expressions] + self.write_masks = {} # 'mrtN' -> channels the export writes (bit c = channel c), see export() + self.attrs = {} # pixel: attr index -> 'linear' | 'flat' | 'half' + self.compr_params = set() # vertex: param indices exported with the compr flag (packed binary16 pairs) + self.plain_params = {} # vertex: param index -> channels exported as `off` by its latest plain export + self.f16_plain = {} # pixel: attr index -> channels read as binary16 halves of a plain export + self.uses_pos = False + self.masks = set() # scalar registers currently holding lane masks + self.splat = set() # scalar registers holding 0 or 0xffffffff, a value every lane's bit agrees on + self.uses_q = False # the uint2 temporary of the 64-bit operations + self.used_h = set() # heap descriptor offsets h<k> this stage assigns (manifest `heap 1`) + self.written_v = set() # VGPRs assigned so far in program order + self.entry_reads = {} # VGPR read before any write (its entry value) -> offset of the first such read + self.pc = 0 + # MODE.round[3:2], the f16/f64 rounding (see op_s_round_mode). A pixel stage starts it from the launch + # FLOAT_MODE when the request passes it (launch_mode); otherwise 0 (nearest even) at launch is ASSUMED. + self.round16 = 0 + if kind == 'ps': + self.launch_mode(getattr(pipe, 'ps_float_mode', None)) + self.fetched = False # vertex: the entry call into the fetch routine was translated as loads + self.setup_entry() + self.translate() # ---- entry state --------------------------------------------------------------------- def setup_entry(self): @@ -1750,6 +2325,8 @@ def setup_compute_entry(self, root_end): def S(self, n): """Runtime expression of scalar register n (uint).""" s = self.sym.get(n) + if getattr(self, '_tw_loops', None): + self.tw_loop_read(n) if s: if s[0] == 'const': return '0x%08xu' % (s[1] & 0xffffffff) @@ -1758,10 +2335,259 @@ def S(self, n): if s[0] in ('execcopy', 'fixed_buffer_word'): self.used_s.add(n) return 's%d' % n + if self.heap_word(s): + self.pipe.draw_heapwords = True + return 'x2w_hword(h%d, %du)' % (s[1][1], s[3]) + if s[0] == 'loopback': + self.loopback_reads.add((s[1], n)) + self.used_s.add(n) + return 's%d' % n + shadow = self.sym.get(self.tw_shadow_key(n)) if s[0] in ('desc', 'descnum') else None + if s[0] == 'desc' and not self.sym.get(self.table_edit_key(n)): + shadow = None # an unedited table word reads its entry value directly (table_word) + if shadow and type(getattr(self, 'pipe', None)) is Pipeline: + self.tw_use(shadow[1]) # the run-time value of a word the descriptor handling keeps symbolic + self.used_s.add(n) + return 's%d' % n + word = self.table_word(s, n) + if word is not None: + return 'ud%d' % word + if s[0] == 'dwnum' and type(getattr(self, 'pipe', None)) is Pipeline: + self.tw_use(s[1]) + self.used_s.add(n) + return 's%d' % n raise Unsupported('numeric use of s%d holding %s' % (n, s[0])) self.used_s.add(n) return 's%d' % n + def heap_word(self, s): + """Whether symbol s is a word of a resource-heap descriptor, unmodified, that a draw stage reads as a number: + the runtime's synthesized word of the view (x2w_hword, vdesc; RUNTIME_NEEDS.md 6.3), with heap and + heapwords in X2W_DRAW_FEATURES.""" + return (s is not None and len(s) == 4 and s[0] == 'desc' and isinstance(s[1], tuple) and s[1][0] == 'heapdyn' + and s[2] == 0 and getattr(self, 'kind', None) in ('vs', 'ps') + and type(getattr(self, 'pipe', None)) is Pipeline + and {'heap', 'heapwords'} <= set(self.pipe.features) and desc_key(s) not in self.pipe.modified) + + def table_word(self, s, n): + """Entry-constant index for symbol s when it is a word of a descriptor loaded from a root descriptor table, + unmodified, that a draw stage reads as a number (a null test of word 1, NUM_RECORDS in word 2 converted to + float), with descword in X2W_DRAW_FEATURES: manifest `udsrc <n> descword <param> <byte>`, the dword at <byte> + of the table bound at root parameter <param> (d3d12_draw.inl draw_descword_value, which reads 32-byte entries: + the title's dword, or for a view token the synthesized V# / T# word of the view; mesh2hlsl's descword). Else + None. A word edited in place since its load is refused here, by + the register's edit mark (table_mark_edit).""" + if (s is None or len(s) != 4 or s[0] != 'desc' or not isinstance(s[1], tuple) or s[1][0] != 'table' + or not isinstance(s[2], int) or not isinstance(s[3], int) + or getattr(self, 'kind', None) not in ('vs', 'ps') or type(getattr(self, 'pipe', None)) is not Pipeline + or 'descword' not in self.pipe.features): + return None + if s[2] % 32 or not 0 <= s[3] < 8: + raise Unsupported('numeric use of table descriptor word %d at +%d (not in one 32-byte entry)' % (s[3], s[2])) + if self.sym.get(self.table_edit_key(n)): + # edited in place since it was loaded (or on some path into a join): the table's word is not its value + raise Unsupported('numeric use of an edited table descriptor word (s%d: table %d +%d word %d)' + % (n, s[1][1], s[2], s[3])) + return self.pipe.ud(('descword', s[1][1], s[2] + 4 * s[3])) + + @staticmethod + def table_edit_key(n): + return 'x2w_twedit_%d' % n # a key of the symbolic state, so snapshots and joins carry it (a join where + # only some paths edited gives ('conflict',), which counts as edited) + + def table_mark_edit(self, n): + """s<n> holding a descriptor word was edited in place (the symbol is kept for the descriptor uses): marked + until an instruction writes s<n> otherwise (see translate: a fresh load of the entry is the table's word).""" + if 'descword' not in getattr(getattr(self, 'pipe', None), 'features', ()): + return + self.sym[self.table_edit_key(n)] = ('dwedit',) + self._tw_keep = getattr(self, '_tw_keep', set()) | {n} + + # ---- scalar arithmetic over table descriptor words (descword; the draw form of mesh2hlsl's dwnum) ------------- + # The title computes numbers from descriptor words with SALU (an image's width and height from T# words 1-3 and + # its base level, a buffer's element count from NUM_RECORDS and the stride), which made the result ('descnum',) + # or kept the word's descriptor symbol (an in-place edit), refused at the numeric use. With descword each such + # op is also a lazy run-time node: its line (tagged /*X2W_TWN<m>*/) computes the value from placeholders + # X2W_DW<k>, one per table word, and from earlier nodes. A plain result register holds ('dwnum', {m}); a result + # the descriptor handling keeps symbolic (in-place edit, structured-to-raw store forms) gets the node as its + # shadow (tw_shadow_key), which a numeric read takes instead. A numeric read (S()), a join where paths disagree + # and a loop head that drops a node mark it and the nodes it reads used; Stage.body keeps the lines of used nodes + # only and makes their words entry values (`udsrc <n> descword <param> <byte>`, as Stage.table_word), so + # arithmetic nobody reads leaves the translation as it was. An op whose SCC can reach a reader is used at once. + @staticmethod + def tw_shadow_key(n): + return 'x2w_twshadow_%d' % n + + def tw_use(self, deps): + pipe = self.pipe + todo = list(deps) + while todo: + m = todo.pop() + if m not in pipe.tw_used: + pipe.tw_used.add(m) + _, ups, stage, reg = pipe.tw_nodes[m] + stage.used_s.add(reg) + todo.extend(ups) + + def tw_word(self, s, n): + """Placeholder index for symbol s of s<n> when it is an unedited table descriptor word in one 32-byte entry.""" + if (s is None or len(s) != 4 or s[0] != 'desc' or not isinstance(s[1], tuple) or s[1][0] != 'table' + or not isinstance(s[2], int) or not isinstance(s[3], int) or s[2] % 32 or s[3] < 0 + or self.sym.get(self.table_edit_key(n))): + return None + src = ('descword', s[1][1], s[2] + 4 * s[3]) # word s[3] of a wide load: the runtime's next 32-byte entry + if src not in self.pipe.tw_src: + self.pipe.tw_src.append(src) + return self.pipe.tw_src.index(src) + + def tw_node(self, n, expr, words, nodes, shadow=False): + """Emit s<n> = expr as the lazy line of a new node (see above); the caller sets n's symbol afterwards.""" + pipe = self.pipe + m = len(pipe.tw_nodes) + pipe.tw_nodes.append((frozenset(words), frozenset(nodes), self, n)) + # Until the node is used its line is dropped, so the declaration (used_s) waits for tw_use. The lane facts + # set_s records (uniformity, lane dependence, write sites) are kept: they describe the run-time value the + # register holds, which is what any later read of the node sees. + had = n in self.used_s + before = len(self.lines) + self.set_s(n, expr) + for i in range(before, len(self.lines)): + self.lines[i] = '/*X2W_TWN%d*/%s' % (m, self.lines[i]) + if not had: + self.used_s.discard(n) + if not shadow: + self.tw_loop_value(n, {m}) + return m + + def tw_loops_at(self, n): + """The loops (forget_loop_writes) the current instruction is in whose body writes s<n>.""" + return [loop for loop in getattr(self, '_tw_loops', ()) if loop[0] <= self.pc <= loop[1] and n in loop[2]] + + def tw_loop_value(self, n, deps): + """A run-time number of nodes deps left in s<n> inside a loop whose body writes n can be read at the head + through the back edge, where no read marks the nodes. They are used when anything in that loop reads n as a + number (tw_loop_read, resolved by tw_substitute): a superset of the head's reads. A shadow does not count: + at the head its register is a conflict (or a checked loopback) whatever the shadow holds.""" + for loop in self.tw_loops_at(n): + self.pipe.tw_loop_pending.append((id(self), loop, n, frozenset(deps), self)) + + def tw_loop_read(self, n): + for loop in self.tw_loops_at(n): + self.pipe.tw_loop_reads.add((id(self), loop, n)) + + def tw_load_shadow(self, n): + """A table descriptor word just loaded into s<n>: its run-time value as n's shadow, so a join with a path where + n holds a run-time number, or a numeric read, finds the variable assigned.""" + if (getattr(self, 'kind', None) not in ('vs', 'ps') or type(getattr(self, 'pipe', None)) is not Pipeline + or 'descword' not in self.pipe.features or n > 105): + return + sym = self.sym.get(n) + k = self.tw_word(sym, n) + if k is None: + return + m = self.tw_node(n, 'X2W_DW%d' % k, {k}, (), shadow=True) + self.sym[n] = sym + self.sym[self.tw_shadow_key(n)] = ('dwnum', frozenset({m})) + self._tw_shadow_keep = getattr(self, '_tw_shadow_keep', set()) | {n} + + def tw_scc_live(self): + """Offsets of the stage's SCA ops with an SCC rule whose SCC can reach a reader (carry_scc_writers' walk).""" + if getattr(self, '_tw_scc', None) is None: + names = frozenset(name for name, (_, scc) in SCA.items() if scc) + self._tw_scc = carry_scc_writers(self.ins, getattr(self, 'calculated_pc', None) or {}, names) + return self._tw_scc + + def tw_scalar(self, base, srcs, syms, dname, pair): + """The run-time node of a 32-bit SCA op over table descriptor words and numbers (see above). True when the + result is a plain number ('dwnum'); False leaves the op to the descriptor handling (copies, in-place edits, + the structured-to-raw store forms), with the node as the result's shadow when one could be built.""" + if (getattr(self, 'kind', None) not in ('vs', 'ps') or type(getattr(self, 'pipe', None)) is not Pipeline + or 'descword' not in self.pipe.features or pair or base not in SCA or base.endswith('_b64') + or base == 's_movk_i32'): + return False + if base == 's_mov_b32': + # a copy keeps the descriptor meaning (the handling below); the run-time value follows as a shadow + r, d = reg_range(srcs[0]), reg_range(dname) + shadow = self.sym.get(self.tw_shadow_key(r[1])) if r and r[0] == 's' and r[1] == r[2] else None + if shadow and d and d[0] == 's' and d[1] == d[2] and d[1] <= 105 and d[1] not in self.masks: + own = self.sym.get(d[1]) + m = self.tw_node(d[1], 's%d' % r[1], (), shadow[1], shadow=True) + if own is not None: + self.sym[d[1]] = own + self.sym[self.tw_shadow_key(d[1])] = ('dwnum', frozenset({m})) + self._tw_shadow_keep = getattr(self, '_tw_shadow_keep', set()) | {d[1]} + return False + d = reg_range(dname) + if not d or d[0] != 's' or d[1] != d[2] or d[1] > 105 or d[1] in self.masks: + return False + values, nodes, words, kinds = [], set(), set(), [] + for t, sym in zip(srcs, syms): + r = reg_range(t) + if r and (r[0] != 's' or r[1] != r[2] or r[1] > 105 or r[1] in self.masks): + return False + if not r and self.const_u32(t) is None: + return False + kind = sym[0] if sym else None + kinds.append(kind) + shadow = self.sym.get(self.tw_shadow_key(r[1])) if r else None + if kind == 'dwnum': + nodes |= sym[1] + values.append('s%d' % r[1]) + elif kind == 'desc' and self.tw_word(sym, r[1]) is not None: + k = self.tw_word(sym, r[1]) + words.add(k) + values.append('X2W_DW%d' % k) + elif kind in ('desc', 'descnum') and shadow: + nodes |= shadow[1] + values.append('s%d' % r[1]) + elif kind in (None, 'const', 'ud', 'fixed_buffer_word'): + values.append(self.u(t)) + else: + return False + if not (words or nodes): + return False + own = self.sym.get(d[1]) + symbolic = bool(own and own[0] == 'desc' and own in syms) or ( + getattr(self, 'kind', None) == 'vs' and len(syms) == 2 + and raw_descriptor_alu(base, syms, [self.const_u32(t) for t in srcs]) is not None) + if symbolic and any(k == 'dwnum' for k in kinds): + return False + text, scc = SCA[base] + m = self.tw_node(d[1], text.format(*values), words, nodes, shadow=symbolic) + if scc and self.pc in self.tw_scc_live(): + self.tw_use({m}) + self.set_scc(scc.replace('$', 's%d' % d[1])) + if symbolic: + self.sym[self.tw_shadow_key(d[1])] = ('dwnum', frozenset({m})) + self._tw_shadow_keep = getattr(self, '_tw_shadow_keep', set()) | {d[1]} + if own is not None: + self.sym[d[1]] = own # the descriptor handling below still sees the in-place edit + return False + self.sym[d[1]] = ('dwnum', frozenset({m})) + return True + + def tw_substitute(self): + """Keep the lines of used nodes (Stage.body) and make their words entry values; drop the others.""" + pipe = getattr(self, 'pipe', None) + if type(pipe) is not Pipeline or not pipe.tw_nodes: + return + if pipe.tw_text is None: + for key, loop, n, deps, stage in pipe.tw_loop_pending: + if (key, loop, n) in pipe.tw_loop_reads: + stage.tw_use(deps) + used_words = set().union(*(pipe.tw_nodes[m][0] for m in pipe.tw_used)) + pipe.tw_text = {k: 'ud%d' % pipe.ud(src) for k, src in enumerate(pipe.tw_src) if k in used_words} + for _, lines, _ in self.blocks: + out = [] + for line in lines: + tag = re.match(r'/\*X2W_TWN(\d+)\*/(.*)$', line, re.S) + if tag: + if int(tag.group(1)) not in pipe.tw_used: + continue + line = re.sub(r'\bX2W_DW(\d+)\b', lambda w: pipe.tw_text[int(w.group(1))], tag.group(2)) + out.append(line) + lines[:] = out + def note_whole_read(self, reg): if reg in self.low16_only_v: raise Unsupported('whole-word read of v%d after odd d16 image_load' % reg) @@ -1779,12 +2605,20 @@ def u(self, tok, *, low16_only=False): if m: raise Unsupported('numeric use of m0 holding %s' % m[0]) return 'm0' + if tok == 'src_scc': + # SCC read as a 32-bit operand (0 or 1) + return '(scc ? 1u : 0u)' + if tok in getattr(self, 'dpp_names', ()): + return tok # the quad-read source of a DPP instruction (quad_dpp) r = reg_range(tok) if r: if r[0] == 'v': - for reg in range(r[1], r[2] + 1): - self.used_v.add(reg) - if not low16_only: + written = getattr(self, 'written_v', None) # absent on the tests' bare one-instruction stages + if written is not None and r[1] not in written: + self.entry_reads.setdefault(r[1], self.pc) + self.used_v.add(r[1]) + if not low16_only: + for reg in range(r[1], r[2] + 1): self.note_whole_read(reg) return 'v%d' % r[1] return self.S(r[1]) @@ -1836,6 +2670,27 @@ def f(self, tok): text = 'abs(%s)' % text return '(-%s)' % text if neg else text + def u_mod(self, tok, sign=0x80000000): + """uint expression for an operand with VOP3 neg/abs applied as sign-bit operations (no float rounding).""" + neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) + if neg: + tok = tok[1:] + absolute = tok.startswith('|') and tok.endswith('|') + if absolute: + tok = tok[1:-1] + text = self.u(tok) + if absolute: + text = '(%s & %#xu)' % (text, ~sign & 0xffffffff) + if neg: + text = '(%s ^ %#xu)' % (text, sign) + return text + + def h(self, tok): + """uint expression whose low 16 bits are a binary16 operand: inline float constants take their half form.""" + if tok in FLOATS: + return '0x%04xu' % struct.unpack('<H', struct.pack('<e', FLOATS[tok]))[0] + return self.u(tok) + def is_const(self, n): s = self.sym.get(n) return s[1] if s and s[0] == 'const' else None @@ -1855,17 +2710,57 @@ def const_u32(self, tok): return None def emit(self, text): + # The address temporary `a` is lane-invariant while its last assignment was an unconditional one from a + # lane-invariant expression (a buffer load with no VGPR address, or one computed from uniform values). + if hasattr(self, 'lane_s') and re.search(r'\ba = ', text): + m = re.fullmatch(r'a = (.*);', text) + self.a_invariant = bool(m) and self.lane_invariant(m.group(1)) + if re.search(r'\bexec = ', text): + self.exec_writes = getattr(self, 'exec_writes', 0) + 1 + if re.search(r'\bt = ', text): + self.t_invariant = False # image() marks its own result again (see there) self.lines.append(text) def clear_low16(self, n): if isinstance(self.low16_only_v, set) and self.exec_known and n not in self.pinned_low16_v: self.low16_only_v.discard(n) + def lane_invariant(self, expr): + """True when the HLSL expression has the same value in every lane of the wave. + + It may name only entry constants (udN), resources (rN, read at any address the expression itself + computes), pure functions and literals, SGPR variables that hold a scalar number (not a lane mask: the + one-lane model keeps only the lane's bit of a mask) and VGPRs proven lane-invariant. vcc, exec, scc, m0, + the temporaries (a, w, t, q) and the interpolants (i.) depend on the lane or on state not tracked here. + """ + for m in re.finditer(r'\b[A-Za-z_]\w*', expr): + name = m.group(0) + if name in ('x', 'y', 'z', 'w') and expr[m.start() - 1:m.start()] == '.' and \ + re.search(r'\bt\.$', expr[:m.start()]): + continue # a component of the image result t (lane-invariant only when t is, checked as 't') + if name in LANE_INVARIANT_NAMES or name.startswith('x2w_') or re.fullmatch(r'X2W_DW\d+', name): + continue + if name == 'a' and getattr(self, 'a_invariant', False): + continue + if name == 't' and getattr(self, 't_invariant', False): + continue + if re.fullmatch(r'xv\d+', name): # assigned in every lane from a lane-invariant value (readfirstlane) + continue + reg = re.fullmatch(r'(ud|r|s|v)(\d+)', name) + if reg and reg.group(1) in ('ud', 'r'): + continue + if reg and reg.group(1) == 's' and int(reg.group(2)) not in self.lane_s and int(reg.group(2)) not in self.masks: + continue + if reg and reg.group(1) == 'v' and int(reg.group(2)) in self.uniform_v: + continue + return False + return True + def set_v(self, n, expr, *, low16_only=False): + if hasattr(self, 'written_v'): + self.written_v.add(n) if getattr(self, 'interp_p1', None): self.interp_p1.pop(n, None) - if hasattr(self, 'uniform_v'): - self.uniform_v.discard(n) self.last_v = (n, expr) if low16_only: if not isinstance(self.low16_only_v, set): @@ -1873,8 +2768,64 @@ def set_v(self, n, expr, *, low16_only=False): self.low16_only_v.add(n) else: self.clear_low16(n) + # A VGPR written in every lane (exec still the entry mask) from lane-invariant values holds one value in + # all of them, so a later v_readfirstlane_b32 reads that value whatever exec is then. + invariant = self.exec_known and hasattr(self, 'lane_s') and self.lane_invariant(expr) + self.uniform_v.discard(n) + if invariant: + self.uniform_v.add(n) + partial = getattr(self, 'partial_uniform', None) + if partial is not None: + shadow = None if self.exec_known else self.partial_shadow(expr) + partial.pop(n, None) self.used_v.add(n) self.emit('v%d = %s;' % (n, expr) if self.exec_known else 'if (exec & 1) v%d = %s;' % (n, expr)) + if partial is not None and shadow is not None: + # Written in the active lanes only, from a lane-invariant value: every lane active now holds that value. + # Kept with the emitted line so v_readfirstlane_b32 can take the value for every lane (see there). + partial[n] = {'lines': self.lines, 'at': len(self.lines) - 1, 'n': n, 'expr': shadow[0], 'deps': shadow[1], + 'epoch': getattr(self, 'exec_writes', 0), 'done': False} + + def partial_shadow(self, expr): + """(shadow expression, entries it reads) when expr has one value in every lane active now; else None. + + Lane-invariant names qualify, and so does a VGPR written in the active lanes from such a value with exec + not written since (partial_uniform, same epoch): that VGPR is replaced by its shadow xvN, which holds the + value in every lane (a lane inactive at the write kept an older VGPR value; its shadow is computed from + the same scalars). This is the scalar recompute of upstream PR #2203 in the one-lane model: the value the + first active lane reads is rebuilt from the scalar expression chain that defined it, so a chain such as + the unsigned-division reciprocal (v_cvt_f32_u32 v1, sN; v_rcp_f32 v1, v1; v_mul_f32 v1, k, v1; + v_cvt_u32_f32 v1, v1; v_readfirstlane_b32) under a narrowed exec is read by every lane.""" + partial = self.partial_uniform + epoch = getattr(self, 'exec_writes', 0) + deps = [] + + def sub(m): + k = int(m.group(1)) + if k in self.uniform_v: + return m.group(0) + entry = partial.get(k) + if entry is None or entry['epoch'] != epoch: + raise Unsupported('not partial') + deps.append(entry) + return 'xv%d' % k + try: + shadow = re.sub(r'\bv(\d+)\b', sub, expr) + except Unsupported: + return None + return (shadow, deps) if self.lane_invariant(shadow) else None + + def materialize_shadow(self, entry): + """Rewrite a partial_uniform write (and the writes its shadow reads) to also assign its shadow xvN in every + lane, in program order, at the write itself.""" + if entry['done']: + return + for dep in entry['deps']: + self.materialize_shadow(dep) + n = entry['n'] + entry['lines'][entry['at']] = 'xv%d = %s; if (exec & 1) v%d = xv%d;' % (n, entry['expr'], n, n) + self.shadow_v.add(n) + entry['done'] = True def f_mods(self, expr, mods=()): # The hardware applies the output modifier before the clamp, but the disassembler prints `clamp` @@ -1950,13 +2901,19 @@ def set_s(self, n, expr, sym=None, scc=None, uniform=None): if getattr(self, 'since_join', None) is not None: (self.since_join.add if uniform else self.since_join.discard)(n) getattr(self, 'masks', set()).discard(n) # unit probes build a Stage without __init__ - getattr(self, 'float_const_s', {}).pop(n, None) + getattr(self, 'splat', set()).discard(n) if sym is not None: self.sym[n] = sym if sym[0] != 'const': return else: self.sym.pop(n, None) + if hasattr(self, 'lane_s'): + if self.lane_invariant(expr): + self.lane_s.discard(n) + else: + self.lane_s.add(n) + self.s_written_at.setdefault(self.pc, set()).add(n) self.used_s.add(n) self.emit('s%d = %s;' % (n, expr)) if scc: @@ -2152,135 +3109,117 @@ def per_lane_read(self, i, key): return False # ---- instruction translation ------------------------------------------------------------- - def joined_registers(self, with_cfg=False): - """{branch target: registers whose program-order symbol may not hold on every path into it}. - - Program order carries the state after every instruction above the target into it. That state holds on every - path only for a register whose writes above the target are all in blocks that dominate it (in dominance - order), and which no block that reaches it from at or below it writes (a loop body, or a later block that - branches back). Computed over the basic blocks, so a path that leaves a loop's textual range and comes back - counts. - - With ``with_cfg=True``, returns ``(joined, forward_splits, div_targets)`` where ``forward_splits`` keeps only - writes on non-dominating forward arms between a target's dominators and the target (excluding loop back edges) - and ``div_targets`` maps each ``s_cbranch_*`` offset to ``(writes, affected_targets)`` inside its divergent - CFG region (between the branch and its immediate post-dominator, or over the loop range for a backward edge).""" - ins = self.ins - if not ins: - return ({}, {}, {}) if with_cfg else {} - index = {off: i for i, (off, *_) in enumerate(ins)} - calculated = getattr(self, 'calculated_pc', {}) # unit probes build a Stage without translate() - branch = lambda name: name.startswith('s_cbranch') or name in ('s_branch', 's_setpc_b64') - target_of = lambda off, name, asm: (calculated.get(off) if name == 's_setpc_b64' # None: no proven target - else int(parse(asm)[1][0].split('_')[1], 16)) - leaders = {0} | {target_of(off, name, asm) for off, _, name, asm in ins if branch(name)} - {None} - for i, (off, n, name, asm) in enumerate(ins[:-1]): - if branch(name) or name == 's_endpgm': - leaders.add(ins[i + 1][0]) - starts = sorted(index[o] for o in leaders if o in index) - bounds = list(zip(starts, starts[1:] + [len(ins)])) - off_of = [ins[lo][0] for lo, _ in bounds] - block_of = {} - for b, (lo, hi) in enumerate(bounds): - for i in range(lo, hi): - block_of[i] = b - succ = [] - for lo, hi in bounds: - off, n, name, asm = ins[hi - 1] - out = [] if name in ('s_branch', 's_setpc_b64', 's_endpgm') or hi == len(ins) else [block_of[hi]] - if branch(name) and target_of(off, name, asm) in index: - out.append(block_of[index[target_of(off, name, asm)]]) - succ.append(out) - pred = [[a for a in range(len(bounds)) if b in succ[a]] for b in range(len(bounds))] - writes = [set().union(*(scalar_destinations(*ins[i][2:]) for i in range(lo, hi))) for lo, hi in bounds] - everything = set(range(106)) | {'m0'} - writes = [everything if 'any' in w else w for w in writes] - # Dominators of each block (iterative; the entry block is block 0). - dom = [set(range(len(bounds))) for _ in bounds] - dom[0] = {0} - changed = True - while changed: - changed = False - for b in range(1, len(bounds)): - new = ({b} | set.intersection(*(dom[p] for p in pred[b]))) if pred[b] else {b} - if new != dom[b]: - dom[b], changed = new, True - all_targets = leaders - {0} | ({0} if any(0 in s for s in succ) else set()) - joined, forward_splits = {}, {} - for target in all_targets: - if target not in index: - continue - t = block_of[index[target]] - reach, todo = set(), list(pred[t]) # blocks with a path of length >= 1 into the target - while todo: - b = todo.pop() - if b not in reach: - reach.add(b) - todo += pred[b] - regs = set() - above_dominators = sorted(b for b in dom[t] - {t} if b < t) - for b in range(len(bounds)): - if b < t and b not in dom[t]: - regs |= writes[b] # above the target but not on every path into it - if b in reach and b >= t: - regs |= writes[b] # a loop body or a later block that comes back - # Writes in dominating blocks hold on every path only if their textual order is their execution order. - non_chain = any(not (a in dom[c]) for a, c in zip(above_dominators, above_dominators[1:])) - if non_chain: - regs |= set().union(*(writes[b] for b in above_dominators)) - joined[target] = regs - if with_cfg: - above_set = dom[t] - {t} - split_blks, stodo = set(), [p for p in pred[t] if p < t and p not in above_set] - while stodo: - b = stodo.pop() - if b not in split_blks: - split_blks.add(b) - stodo += [p for p in pred[b] if p < t and p not in above_set] - fwd = set().union(*(writes[b] for b in split_blks)) if split_blks else set() - if non_chain: - fwd |= set().union(*(writes[b] for b in above_dominators)) - forward_splits[target] = fwd - if not with_cfg: - return joined - pdom = [set(range(len(bounds))) if succ[b] else {b} for b in range(len(bounds))] - changed = True - while changed: - changed = False - for b in range(len(bounds) - 1, -1, -1): - if not succ[b]: - continue - new = {b} | set.intersection(*(pdom[s] for s in succ[b])) - if new != pdom[b]: - pdom[b], changed = new, True - div_targets = {} - for b, (lo, hi) in enumerate(bounds): - off, _n, name, asm = ins[hi - 1] - if not name.startswith('s_cbranch'): - continue - tgt = target_of(off, name, asm) - if tgt is None: + # Symbolic values that are also assigned to their HLSL variable, so a path where the register holds one of them + # and a path where it holds a plain run-time number agree on the variable's value. + RUNTIME_BACKED = ('const', 'fixed_buffer_word', 'execcopy', 'dwnum') + + def snapshot(self, facts=False): + facts = getattr(self, 'lane_facts', None) if facts is False else facts + return dict(self.sym), set(self.masks), self.exec_known, set(self.lane_s), facts + + def merge(self, states): + """The symbolic state at a join of forward edges: what every incoming path agrees on. + + A register whose paths disagree keeps working as a number when every path also assigned it at run time; + otherwise it becomes ('conflict',), which any later use refuses (a descriptor on one path and a loaded + word on the other has no single translation). A mask on any path stays a mask, and exec is the entry + mask only when it is on every path. + """ + sym = {} + runtime_joined = set() + self.execzero = {} # conflict registers symbolic only on s_cbranch_execz edges -> exec_writes at the join + for reg in set().union(*(s[0] for s in states)): + values = [s[0].get(reg) for s in states] + if all(v == values[0] for v in values): + sym[reg] = values[0] + elif (isinstance(reg, int) and type(getattr(self, 'pipe', None)) is Pipeline + and any(v and v[0] == 'dwnum' or s[0].get(self.tw_shadow_key(reg)) for s, v in zip(states, values)) + and all(v is None or v[0] in self.RUNTIME_BACKED or s[0].get(self.tw_shadow_key(reg)) + for s, v in zip(states, values))): + # descword: every path assigned the variable (the symbolic ones through their shadow), so the join is + # a run-time number that depends on those nodes, marked used only by a later numeric read (S()) + deps = set() + for s, v in zip(states, values): + if v and v[0] == 'dwnum': + deps |= v[1] + elif v is not None and v[0] not in self.RUNTIME_BACKED: + deps |= s[0][self.tw_shadow_key(reg)][1] + sym[reg] = ('dwnum', frozenset(deps)) + self.tw_loop_value(reg, deps) # as tw_node: the head may read it through the back edge + runtime_joined.add(reg) + elif not all(v is None or v[0] in self.RUNTIME_BACKED for v in values): + # Symbolic only on s_cbranch_execz edges: the run-time variable is right wherever exec is 1, so an + # AND with exec before exec is written again may read it (see scalar); any other use refuses. + symbolic = [s for s, v in zip(states, values) if not (v is None or v[0] in self.RUNTIME_BACKED)] + sym[reg] = ('conflict',) + if all(any(s is e for e in getattr(self, 'execz_snaps', ())) for s in symbolic): + self.execzero[reg] = getattr(self, 'exec_writes', 0) + # For each conflict register: this lane's exec bit on every reachable edge where its variable may be stale + # (None where not proven), for exec_absorbed_source. + self.conflict_exec = {} + if all(len(s) > 4 for s in states): + for reg, value in sym.items(): + if value == ('conflict',): + bits = frozenset(lane_fact_bit(s[4], 'exec') for s in states if s[4] is not None and + not (s[0].get(reg) is None or s[0][reg][0] in self.RUNTIME_BACKED)) + self.conflict_exec[reg] = (bits, getattr(self, 'exec_writes', 0)) + for reg in runtime_joined: + sym.pop(self.tw_shadow_key(reg), None) + self.sym = sym + self.masks = set().union(*(s[1] for s in states)) + self.exec_known = all(s[2] for s in states) + self.lane_s = set().union(*(s[3] for s in states)) # lane-dependent on any incoming path + + # Instructions whose SGPR result is a lane mask (bit i = lane i): compares into an SGPR pair, save-exec forms, + # wrexec forms and a copy of exec. + LOOP_MASK_WRITER = re.compile(r'^v_cmpx?_|saveexec|wrexec') + + def loop_writes(self, head, last): + """(SGPRs written, SGPRs written by something other than a lane-mask writer, exec written) over the + instructions at offsets [head, last].""" + written, non_mask, exec_written = set(), set(), False + for off, n, name, asm in self.ins: + if not head <= off <= last: continue - if tgt <= off: - t_blk = block_of[index[tgt]] if tgt in index else b - loop_blks = range(min(t_blk, b), b + 1) - regs = set().union(*(writes[w] for w in loop_blks)) - affected = {off_of[w] for w in loop_blks} & all_targets - else: - stop = pdom[b] - {b} - ipd = max(stop, key=lambda x: len(pdom[x])) if stop else None - div, dtodo = set(), list(succ[b]) - while dtodo: - w = dtodo.pop() - if w == ipd or w in div: - continue - div.add(w) - dtodo += succ[w] - regs = set().union(*(writes[w] for w in div)) if div else set() - affected = ({off_of[w] for w in div} | ({off_of[ipd]} if ipd is not None else set())) & all_targets - div_targets[off] = (regs, affected) - self.flow = (index, block_of, succ, dom, writes, {}) - return joined, forward_splits, div_targets + _, writes = sgpr_access(name, asm) + ops = parse(asm)[1] + first = ops[0] if ops else '' + if writes: + written |= writes + mask = self.LOOP_MASK_WRITER.search(name) or ( + name.startswith('s_mov_b') and len(ops) > 1 and ops[1].startswith('exec')) + if not mask: + non_mask |= writes + if (first.startswith('exec') and name.startswith('s_')) or re.search(r'saveexec|wrexec|^v_cmpx_', name): + exec_written = True + return written, non_mask, exec_written + + def forget_loop_writes(self, head, last, back_only=False): + """At a loop head: drop what the entry state says about registers the loop body writes (see translate). + + back_only: no edge enters the head except its back edges (each an s_cbranch or s_branch), so the state left + above is not one of its paths. A register the body writes is then assumed to hold its value in its variable + (('loopback', head)); a read under that assumption is checked at every back edge (check_loopback).""" + written, non_mask, exec_written = self.loop_writes(head, last) + # descword: a node the body writes to one of these registers can be read at the head through the back edge, + # where no read marks it, so tw_node marks it used at once + if (getattr(self, 'kind', None) in ('vs', 'ps') and type(getattr(self, 'pipe', None)) is Pipeline + and 'descword' in self.pipe.features): + self._tw_loops = getattr(self, '_tw_loops', []) + [(head, last, frozenset(written))] + for reg in written: + value = self.sym.pop(reg, None) + getattr(self, 'conflict_exec', {}).pop(reg, None) + self.sym.pop(self.tw_shadow_key(reg), None) # a symbolic value becomes a conflict below + if value is not None and value[0] == 'dwnum' and type(getattr(self, 'pipe', None)) is Pipeline: + self.sym[reg] = value # still a run-time number; a read in the loop marks its nodes (S()) + if value is not None and value[0] not in self.RUNTIME_BACKED: + # The entry value lives only in the symbolic state (a descriptor, a pointer): its HLSL variable was + # never assigned, so a first-pass read of the run-time variable would be wrong. As at a forward + # join of a symbolic and a run-time value, any use refuses. + self.sym[reg] = ('loopback', head) if back_only else ('conflict',) + self.masks -= non_mask + if exec_written: + self.exec_known = False def unjoined(self, target, last_write, regs): """The registers of regs whose program-order state is not proven at a branch target. A lane-mask mark or a @@ -2318,274 +3257,250 @@ def translate(self): raise refusals.append((str(reason), self.kind)) self.calculated_pc = {} - targets = set() + try: + self.pc_data = pc_data_proof(self.ins) + except Unsupported as reason: + if refusals is None: + raise + refusals.append((str(reason), self.kind)) + self.pc_data = {} + # Address arithmetic another proof absorbs (calculated_pc; pc_data, the s_getpc data-pointer proof, when it + # has run before this line) is neither a carry writer nor a reader. + self.carry_writes = carry_scc_writers( + self.ins, {**dict.fromkeys(getattr(self, 'pc_data', None) or ()), **self.calculated_pc}) + targets, sources = set(), {} + skipped = [] # compute: (branch, target) of each s_cbranch_execz targets.update(target for target in self.calculated_pc.values() if target is not None) - # (branch, target) of every branch, the proven s_setpc_b64 jumps included - branches = [(pc, target) for pc, target in self.calculated_pc.items() if target is not None] + # A proven calculated branch (lower() returns it as a jump) is an incoming edge for the local join merge. + for at, target in self.calculated_pc.items(): + if target is not None: + sources.setdefault(target, []).append(at) for off, n, name, asm in self.ins: if name.startswith('s_cbranch') or name == 's_branch': target = int(parse(asm)[1][0].split('_')[1], 16) targets.add(target) - branches.append((off, target)) - # Targets that only forward s_cbranch_execz branches (and the fall-through) enter: on a taken edge the lane's - # exec bit is 0 at the target. Compute stages have their own execz handling and are left out. - names = {off: name for off, _n, name, _asm in self.ins} - execz_targets = set() if getattr(self, 'kind', None) == 'cs' else { - t for t in targets if all(pc < t and names[pc] == 's_cbranch_execz' for pc, to in branches if to == t)} - self.mesh_allocation_block = None - splits = set(targets) - if getattr(self, 'kind', None) == 'ms' and targets: - at = next(i for i, item in enumerate(self.ins) if item[2] == 'x2w_mesh_counts') - self.mesh_allocation_block = self.ins[at][0] - # The exchange and its EXEC restore always run. Keep the group barrier and allocation outside - # the pc dispatch even when the preceding region took different paths. - splits.update((self.mesh_allocation_block, self.ins[at + 2][0])) - join_writes = self.join_writes(branches) - refused = self.execz_refusals() if getattr(self, 'kind', None) == 'cs' else {} # probes skip __init__ - joined, forward_splits, div_targets = self.joined_registers(with_cfg=True) - init_sym = dict(self.sym) - init_exec_known = getattr(self, 'exec_known', True) - init_wqm_exec = getattr(self, 'wqm_exec', False) - init_masks = set(getattr(self, 'masks', ())) - init_attrs = dict(getattr(self, 'attrs', {})) - init_used_s = set(getattr(self, 'used_s', ())) - init_used_v = set(getattr(self, 'used_v', ())) - init_entry_uniform = set(getattr(self, 'entry_uniform_s', ())) | { - k for k, v in init_sym.items() - if isinstance(k, int) and v and ( - (v[0] == 'const' and len(v) == 2) or v[0] in ('ud', 'fixed_buffer_word') - ) - } - entry_ud = {reg: sym for reg, sym in init_sym.items() if sym[0] == 'ud'} - forced = getattr(self, 'force_joined', {}) - force_unproven = set() - force_at = {} - first_refusal = len(refusals) if refusals is not None else 0 - every_sgpr = set(range(106)) | {'m0'} - init_entry = [r for r in set(init_sym) | init_used_s if isinstance(r, int)] - init_written = set(range(max(init_entry + [-1 if getattr(self, 'kind', None) == 'cs' else 15]) + 1)) | {'m0'} - - for _ in range(max(4, len(self.ins) + 2)): - scc_effects = {} - uniform_vcc_compares = set() - self.lines = [] - self.blocks = [] # (offset, [lines], terminator) - self.sym = dict(init_sym) - self.exec_known = init_exec_known - self.wqm_exec = init_wqm_exec - self.masks = set(init_masks) - self.join_masks = set() # marked SGPRs whose mark is not proven on every path (unjoined) - last_write = {} # SGPR -> offset of its last write in program order - self.attrs = dict(init_attrs) - self.used_s, self.used_v = set(init_used_s), set(init_used_v) - self.exports = {} - self.write_masks = {} - self.compr_params = set() - self.plain_params = {} - self.f16_plain = {} - self.uses_pos = False - self.fetched = False - self.uniform_v = set() - self.varying_s = set() - self.scc_uniform = True - self.low16_only_v = set() # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load - self.pinned_low16_v = set() # low16_only_v live across basic-block boundaries - self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer - self.float_const_s = {} # SGPR -> 32-bit pattern from s_mov_b32 of an inline float constant - self.has_branches = bool(targets) - self.entry_table_pointers = { - reg: sym[1] for reg, sym in init_sym.items() - if isinstance(reg, int) and sym[0] == 'ptr' and sym[1][0] == 'table' - } - self.descriptor_block_first = 0 - self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it - self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) - self.defined_uniform_s = set(init_entry_uniform) - self.bad_sgprs = set() - bad_at_target = {} - tentative_kept = set() - materialize = {} - incoming = {} - kept = {} - self.back_force = {} - written = set(init_written) - falls = True - start = 0 - raised_unsupported = None - - for instruction_index, (off, n, name, asm) in enumerate(self.ins): - if off in splits and off != start: - self.pinned_low16_v.update(self.low16_only_v) - self.blocks.append((start, self.lines, None)) - self.lines, start = [], off - self.descriptor_block_first = instruction_index - self.pc = off - self.descriptor_instruction_index = instruction_index - self.scc_effect = None - # Before the first branch target or terminator every path has run exactly the instructions above, so - # the program-order tracking is exact there even in a program with branches. Code after s_endpgm in a - # branch-free program is past it too (dead code). - self.past_entry = bool(self.blocks) or 0 in targets - if off in targets: - pre_uniform = { - r for r in (self.defined_uniform_s if self.since_join is None else self.since_join) - if r not in self.varying_s and r not in self.masks - } - kept[off] = {} - here = joined.get(off, set()) - arriving = ([({reg: self.sym.get(reg) for reg in here}, written & here)] if falls else []) + \ - incoming.get(off, []) - written = (written - here) | set().union(*(w for _, w in arriving)) - for reg in here: - paths = [s[reg] for s, w in arriving if reg in w] - force = forced.get(off, {}).get(reg) - if any(reg not in w for _, w in arriving) and any(p and not run_time_symbol(p) for p in paths): - self.sym[reg] = ('joined at a branch target',) - continue - if force is None and paths and names_one_value(paths[0]) and all(p == paths[0] for p in paths): - self.sym[reg] = kept[off][reg] = paths[0] - continue - if force == 'refuse' or any(p and not run_time_symbol(p) for p in paths): - self.sym[reg] = ('joined at a branch target',) - continue - if reg in entry_ud: - materialize[reg] = 'ud%d' % entry_ud[reg][1] - self.sym.pop(reg, None) - if reg != 'm0': - self.used_s.add(reg) - # A joined register the fall-through wrote as a plain run-time number: every other path into - # this target has exec bit 0, so the instruction at the target may AND it with exec (scalar()). A register that still holds a plain - # variable reads the same either way. - self.exec_zero_join = (off, { - reg for reg in here - if falls and off in execz_targets and reg in arriving[0][1] and arriving[0][0][reg] is None}) - clobber = here if off in joined else every_sgpr - self.join_masks |= self.unjoined(off, last_write, self.masks) - fwd_clobber = forward_splits.get(off, clobber) - blocked = force_unproven | force_at.get(off, set()) - kept_u = { - r for r in pre_uniform - if r not in clobber or (r not in fwd_clobber and r not in blocked) - } - tentative_kept.update((kept_u & clobber) - blocked) - self.uniform_v.clear() - self.since_join, self.scc_uniform = kept_u, False - # A constant is only known here if no other path into the join writes the register: a loop counter - # set before the loop and incremented in it reaches the loop head with a new value on every pass. - # set_s also assigns constants at run time, so the register reads its real value once it is dropped. - # clobber also holds the writes of every earlier block off the dominator chain; a constant written - # after those, by a block every path runs, with no later write on any path, is still known. - consts = {reg for reg in join_writes.get(off, set()) | (clobber & every_sgpr) - if (self.sym.get(reg) or ('',))[0] == 'const'} - for reg in self.unjoined(off, last_write, consts): - del self.sym[reg] - fconsts = (join_writes.get(off, set()) | (clobber & every_sgpr)) & set(self.float_const_s) - for reg in self.unjoined(off, last_write, fconsts): - self.float_const_s.pop(reg, None) - self.defined_uniform_s = set(kept_u) | { - k for k, v in self.sym.items() - if isinstance(k, int) and v and ( - (v[0] == 'const' and len(v) == 2) or v[0] in ('ud', 'fixed_buffer_word') - ) - } - if name.startswith('s_cbranch') or name == 's_branch' or ( - name == 's_setpc_b64' and self.calculated_pc.get(off) is not None): - b_target = self.calculated_pc[off] if name == 's_setpc_b64' else int(parse(asm)[1][0].split('_')[1], 16) - there = joined.get(b_target, set()) - if b_target > off: - incoming.setdefault(b_target, []).append(({reg: self.sym.get(reg) for reg in there}, written & there)) - else: - for reg in there & written: - back, sym = self.sym.get(reg), kept.get(b_target, {}).get(reg) - if back and not run_time_symbol(back) and back != sym: - self.back_force.setdefault(b_target, {})[reg] = 'refuse' - elif sym is not None and back != sym: - self.back_force.setdefault(b_target, {}).setdefault( - reg, 'run' if run_time_symbol(sym) else 'refuse') - falls = name not in ('s_branch', 's_setpc_b64', 's_endpgm') - dests = scalar_destinations(name, asm) - written |= every_sgpr if 'any' in dests else dests - last_write.update(dict.fromkeys(every_sgpr if 'any' in dests else dests, off)) - self._pre_fconst = dict(self.float_const_s) - if 'any' in dests: - self.float_const_s.clear() + sources.setdefault(target, []).append(off) + if name == 's_cbranch_execz' and self.kind == 'cs': + skipped.append((off, target)) + # The first branch or branch target: before it the program is one straight-line path (op_s_round_mode). + self.uses_round_mode = any(name == 's_round_mode' for off, n, name, asm in self.ins) + # X2W_PS_QUAD_DIVERGENT=1 (default off, read when the stage is built): quad reads (DPP quad_perm) and + # image_sample_b are also lowered where a lane may skip them in forward control flow. That is exact only + # where the four lanes of each quad take the same path (D3D leaves quad reads and implicit derivatives + # undefined otherwise, while the hardware reads the inactive lanes, fi:1); loops stay refused. Each use is + # listed in quad_divergent_used and the manifest says `quaddivergent 1`. + self.quad_divergent = self.kind == 'ps' and os.environ.get('X2W_PS_QUAD_DIVERGENT') == '1' + self.quad_divergent_used = [] + self.has_loop = any(src >= t for t, srcs in sources.items() for src in srcs) + self.back_edges = {src for t, srcs in sources.items() for src in srcs if src >= t} + # X2W_PS_IMPLICIT_LOD=1 (default off, read when the stage is built): an implicit-LOD image_sample in a pixel + # stage is always Sample (implicit derivatives), never the level-0 fallback. In branched code that assumes + # the four lanes of each quad reach it together (quad_divergent_used, `quaddivergent 1`); inside a loop + # other than a proven waterfall (one pass) it is refused. + self.implicit_lod = self.kind == 'ps' and os.environ.get('X2W_PS_IMPLICIT_LOD') == '1' + self.implicit_samples = [] + self.cf_first = min([off for off, n, name, asm in self.ins if name.startswith('s_cbranch') or name == 's_branch'] + + list(targets) + [1 << 32]) + if self.kind == 'ms' and self.uses_round_mode: + # A mesh request supplies no launch FLOAT_MODE. Limit the first supported profile to + # the common mixed-precision emitters that consult round16. Mesh-specific d16 image + # packing and the other half-precision forms require their own audit. + for _, _, op, _ in self.ins: + if re.search(r'[fd]16|f64', op) and op not in ('v_fma_mixlo_f16', 'v_fma_mixhi_f16'): + raise Unsupported('mesh round mode with %s' % op) + self.launch_unknown = True + self.mode_at = self.round_mode_flow() if self.kind in ('ps', 'ms') and self.uses_round_mode else {} + self.blocks = [] # (offset, [lines], terminator) + self.waterfall_back = set() # back edges of proven waterfall loops, emitted as fall-through (waterfall) + self.execz_snaps = [] # the snapshots on taken s_cbranch_execz edges (see merge) + self.uniform_v = set() # VGPRs proven to hold one value in every lane (see set_v) + self.partial_uniform = {} # VGPRs holding one value in every lane active at their write (see set_v) + self.shadow_v = set() # shadow variables xvN that v_readfirstlane_b32 introduced + self.lane_s = set() # SGPR variables that may differ between lanes in the one-lane model (see set_s) + self.s_written_at = {} # instruction offset -> SGPRs it assigns at run time + self.varying_s = set() + self.scc_uniform = True + self.low16_only_v = set() # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load + self.pinned_low16_v = set() # low16_only_v live across basic-block boundaries + self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer + self.has_branches = bool(targets) + self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it + self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) + start = 0 + incoming = {} # branch target -> symbolic states of the forward branches seen so far + previous = None + self.execz_fallthrough_epoch = None + scc_written, scc_unknown = set(), set() + self.entry_table_pointers = {reg: sym[1] for reg, sym in self.sym.items() + if isinstance(reg, int) and sym[0] == 'ptr' and sym[1][0] == 'table'} + self.descriptor_block_first = 0 + # Lane-bit facts of the emitted HLSL (lane_facts_after); None where no edge reaches. Every lane starts + # with exec = 1 (the declaration in the stage's variable list). Kept for draw vertex and pixel stages only + # (lane_track); the proofs that read them (exec_absorbed_source, back_only, vcc_descriptor_copy) are off + # elsewhere. + track = self.lane_track = (getattr(self, 'kind', None) in ('vs', 'ps') and + type(self).snapshot is Stage.snapshot) + self.lane_facts = lane_facts_after(getattr(self, 'entry', None) or [], {'exec': ('v', 1)}) if track else {} + self.conflict_exec = {} + self.loopback_reads = set() # (head, SGPR) read under the back-edge-only head assumption (forget_loop_writes) + facts_in = {} # branch target -> lane facts on the forward edges seen so far + names = {o: nm for o, _n, nm, _a in self.ins} + fall_dead = False # no fall-through reaches here: an unconditional jump or s_endpgm, no target since + calculated_targets = {t for t in self.calculated_pc.values() if t is not None} + for instruction_index, (off, n, name, asm) in enumerate(self.ins): + self.descriptor_instruction_index = instruction_index + if off in targets or off == start: + self.descriptor_block_first = instruction_index + if off in targets and off != start: + self.pinned_low16_v.update(self.low16_only_v) + self.blocks.append((start, self.lines, None)) + self.lines, start = [], off + # The scan is linear, so at a join the state left by the instruction above is only one of the + # incoming paths (and none after an unconditional branch). Merge the states of every incoming + # edge when they are all forward; a loop head merges its entry edges and forgets the body's writes. + if off in targets and all(src < off for src in sources[off]): + states = list(incoming.get(off, [])) + if previous not in (None, 's_branch', 's_endpgm'): + states.append(self.snapshot()) + if states: + self.merge(states) + elif off in targets: + # A loop head: the entry edges (fall-through and forward branches) are merged as at any join, and + # the back edges carry whatever the loop body left. Every SGPR the body writes anywhere in + # [head, last back-edge source] loses its symbolic value (a constant known on entry is the first + # pass's value only: a counter `s14 = 0` must not fold into `0 + 1` on every pass), a register the + # body writes with anything but a lane mask stops being a mask, and exec is no longer the entry + # mask if the body writes it. + states = list(incoming.get(off, [])) + if previous not in (None, 's_branch', 's_endpgm'): + states.append(self.snapshot()) + if states: + self.merge(states) + # No forward edge, and the code above ends in an unconditional jump or s_endpgm with no target since. + back_only = track and fall_dead and not incoming.get(off) and all( + names.get(src, '').startswith('s_cbranch') or names.get(src) == 's_branch' for src in sources[off]) + if back_only: + self.forget_loop_writes(off, max(sources[off]), True) else: - for reg in dests: - self.float_const_s.pop(reg, None) - try: - if off in refused: - raise Unsupported(refused[off]) - base = re.sub(r'_e(32|64)$', '', name) - if off in vcc_compares and all( - not mesh_vregs([tok]) and self.uniform_source(tok) - for tok in parse(asm)[1][1:] - ): - uniform_vcc_compares.add(off) - if base.startswith('s_cbranch_'): - cond = base[10:] - cond_uniform = cond in ('scc0', 'scc1') and self.scc_uniform - if off in vcc_branches: - if not vcc_branches[off] <= uniform_vcc_compares: - raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) - cond_uniform = True - if not cond_uniform: - b_target = int(parse(asm)[1][0].split('_')[1], 16) - regs, affected = div_targets.get(off, (set(), set())) - regs = {r for r in regs if isinstance(r, int)} - if b_target <= off: - regs.update(r for r in joined.get(b_target, ()) if isinstance(r, int)) - for tgt_off in affected: - bad_at_target.setdefault(tgt_off, set()).update(regs) - term = self.one(name, asm) - except Unsupported as reason: - if refusals is None: - if not hasattr(reason, 'instruction'): - reason.instruction = name # for fail_reason(); the message itself is unchanged - raised_unsupported = reason - break - refusals.append((str(reason), self.kind)) - continue - except Exception as error: - if refusals is None: - raise - refusals.append((handler_error(name, error, refusals), self.kind)) - continue - # A write proves the mark again: every path from here on runs it. s_movreld can write any SGPR. - self.join_masks = (self.join_masks | every_sgpr) if 'any' in dests else self.join_masks - dests - if self.scc_effect: - scc_effects[off] = self.scc_effect - if term: - self.pinned_low16_v.update(self.low16_only_v) - self.blocks.append((start, self.lines, term)) - self.lines, start = [], off + n - self.descriptor_block_first = instruction_index + 1 - - new_bad = self.bad_sgprs - force_unproven - new_at = {k: v - force_at.get(k, set()) for k, v in bad_at_target.items() if v - force_at.get(k, set())} - if (new_bad or new_at) and tentative_kept: - force_unproven.update(new_bad) - for k, v in new_at.items(): - force_at.setdefault(k, set()).update(v) - if refusals is not None: - del refusals[first_refusal:] + self.forget_loop_writes(off, max(sources[off])) + if off in targets and track: + fall_dead = False + if all(src < off for src in sources[off]): + self.lane_facts = lane_facts_merge(list(facts_in.get(off, [])) + [self.lane_facts]) + else: + # A loop head: only exec survives, when nothing in the body can write it. + head = lane_facts_merge(list(facts_in.get(off, [])) + [self.lane_facts]) or {} + body = [(nm, parse(a)[1]) for o, _n, nm, a in self.ins if off <= o <= max(sources[off])] + self.lane_facts = {k: v for k, v in head.items() if k == 'exec' and + not any(writes_exec(nm, ops) for nm, ops in body)} + if off in calculated_targets: + self.lane_facts = {} + # Lane invariance is not merged across edges for VGPRs; at a loop head the linear state misses the + # back edges, so every SGPR becomes suspect until it is written again. + self.uniform_v.clear() + self.splat.clear() + self.partial_uniform.clear() + self.a_invariant = False + self.t_invariant = False + if not all(src < off for src in sources[off]): + self.lane_s = set(range(128)) + else: + # In the one-lane model a branch condition (scc, vccz, execz) may differ between lanes, so an + # SGPR assigned on only some paths into this join may too, however invariant each value is. + first = min(sources[off]) + for at, regs in self.s_written_at.items(): + if first <= at < off: + self.lane_s |= regs + if off in targets: + self.execz_fallthrough_epoch = None + self.pc = off + # Upstream: before the first branch target or terminator every path has run exactly the instructions + # above (past_entry). At a join its scalar proofs end; the local VGPR proofs (uniform_v, see set_v) + # keep the local rule, and the upstream skipped-execz-block refusal is not taken (local merge()). + self.past_entry = bool(self.blocks) or 0 in targets + if off in targets: + self.since_join, self.scc_uniform = set(), False + before = len(self.lines) + self._tw_keep, self._tw_shadow_keep = set(), set() + if 'vccwords' in self.sym and scalar_effects(name, asm)[1] & {'vcc', 'vcc_hi'}: + del self.sym['vccwords'] + try: + term = self.one(name, asm) + if 'descword' in getattr(self.pipe, 'features', ()): + # an SGPR this instruction wrote other than by an in-place descriptor edit holds a new value + written_now = sgpr_access(name, asm)[1] + for r in written_now - self._tw_keep: + self.sym.pop(self.table_edit_key(r), None) + for r in written_now - self._tw_shadow_keep: + self.sym.pop(self.tw_shadow_key(r), None) + except Unsupported as reason: + if refusals is None: + raise + refusals.append((str(reason), self.kind)) + if track: + self.lane_facts = {} if self.lane_facts is not None else None continue - if raised_unsupported is not None: - raise raised_unsupported - break - else: - reason = 'v_readfirstlane_b32 uniformity proof exceeded pass limit' - if refusals is None: - raise Unsupported(reason) - refusals.append((reason, self.kind)) + except Exception as error: + if refusals is None: + raise + refusals.append((handler_error(name, error, refusals), self.kind)) + if track: + self.lane_facts = {} if self.lane_facts is not None else None + continue + if track: + self.lane_facts = lane_facts_after(self.lines[before:], self.lane_facts) + pc_word = getattr(self, 'pc_data', {}).get(off, ('',))[0] + if pc_word == 'lo': + scc_written.add(off) # its carry is consumed by the high word's s_addc_u32 (pc_data_proof) + elif pc_word == 'hi': + scc_unknown.add(off) # depends on the real load address + elif any('scc = ' in line for line in self.lines[before:]): + scc_written.add(off) + elif re.sub(r'_e(32|64)$', '', name) in SCC_UNMODELLED or (name in SCA and SCA[name][1]): + # a hardware SCC write the HLSL did not make (or, for an SCA op with an SCC rule, one that a + # descriptor or m0 path skipped) + scc_unknown.add(off) + previous = name + if term and term[0] == 'branch' and track: + taken, fall = lane_branch_edges(term[1], self.lane_facts) + else: + taken, fall = self.lane_facts, self.lane_facts + if name.startswith('s_cbranch') or name == 's_branch': + snap = self.snapshot(taken) if track else self.snapshot() + if name == 's_cbranch_execz' and not getattr(self, 'wave_plan', None): + self.execz_snaps.append(snap) # the taken edge: this lane's exec bit is 0 there (merge) + incoming.setdefault(int(parse(asm)[1][0].split('_')[1], 16), []).append(snap) + facts_in.setdefault(int(parse(asm)[1][0].split('_')[1], 16), []).append(taken) + if track: + self.lane_facts = None if term and term[0] in ('jump', 'end') else fall + if term and term[0] in ('jump', 'end'): + fall_dead = True + if term: + self.pinned_low16_v.update(self.low16_only_v) + # The pixel emitter's EXECZ fall-through runs only in lanes with EXEC set. + # A different predecessor or a later EXEC write invalidates that fact. + self.execz_fallthrough_epoch = (getattr(self, 'exec_writes', 0) + if self.kind == 'ps' and name == 's_cbranch_execz' + and not getattr(self, 'wave_plan', None) else None) + self.blocks.append((start, self.lines, term)) + self.lines, start = [], off + n if self.lines: self.blocks.append((start, self.lines, None)) - self.materialized = materialize # declarations() assigns these before the body (and before any loop) - if set(scc_effects.values()) - {'emitted'}: - for kind, name in self.descriptor_scc_reads(dict(branches), scc_effects): - reason = 'scc from %s in %s' % ('descriptor data' if kind == 'descriptor' else kind, name) + for head, reg in sorted(self.loopback_reads): + # every edge into the head is a back edge: each must bring a value the variable holds + if any(not (snap[0].get(reg) is None or snap[0][reg][0] in self.RUNTIME_BACKED) + for snap in incoming.get(head, [])): + reason = 'numeric use of s%d holding conflict' % reg if refusals is None: raise Unsupported(reason) refusals.append((reason, self.kind)) + if self.implicit_samples and self.back_edges - self.waterfall_back: + reason = 'image_sample at %#x with implicit derivatives in a loop' % self.implicit_samples[0] + if refusals is None: + raise Unsupported(reason) + refusals.append((reason, self.kind)) + self.check_scc(scc_written, scc_unknown) + self.check_quad_ops() self.pinned_low16_v.update(self.low16_only_v) leak = self.pinned_low16_v & self.whole_read_v if leak: @@ -2594,46 +3509,51 @@ def translate(self): raise Unsupported(reason) refusals.append((reason, self.kind)) - def descriptor_scc_reads(self, branches, effects): - """Find reads reachable with an elided SCC write, including through joins and back edges.""" - instructions = {off: (size, name, asm) for off, size, name, asm in self.ins} - pending = [(0, None)] # stale: None, or the scc_effect of the write that left the emitted scc behind - seen = set() - while pending: - off, stale = pending.pop() - if (off, stale) in seen or off not in instructions: + def check_scc(self, written, unknown): + """Refuse when an SCC value the translation does not compute can be read. + + The instructions in `unknown` write SCC in hardware but the HLSL leaves `scc` as it was. That is only + a wrong translation if some path from one of them reaches an SCC reader before an instruction whose + translation assigns `scc` (one in `written`). Paths follow fall-through and branch targets, loops + included; s_endpgm and s_branch end the fall-through. + """ + if not unknown: + return + order = [ins[0] for ins in self.ins] + info = {off: (name, asm) for off, n, name, asm in self.ins} + following = dict(zip(order, order[1:])) + # Upstream's calculated-branch proof (calculated_pc): its address arithmetic (s_add_u32 / s_addc_u32) is + # not emitted, so its SCC is neither an unmodelled write nor a read here, and a proven s_setpc jumps. + calc = getattr(self, 'calculated_pc', None) or {} + + def successors(off): + name, asm = info[off] + if off in calc: + return [calc[off]] if calc[off] in info else [following[off]] if off in following else [] + if name == 's_endpgm': + return [] + nxt = [following[off]] if off in following else [] + if name == 's_branch': + nxt = [] + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + return [o for o in nxt if o in info] + for start in sorted(unknown): + if start in calc: continue - seen.add((off, stale)) - size, name, asm = instructions[off] - if stale and off not in self.calculated_pc and reads_scc(name, asm): - yield stale, name - if off in effects: - stale = effects[off] if effects[off] != 'emitted' else None - if off in branches: - pending.append((branches[off], stale)) - if name not in ('s_branch', 's_setpc_b64', 's_endpgm'): - pending.append((off + size, stale)) - - def join_writes(self, branches): - """Branch target -> the scalar registers another path can write before it reaches the target: the loop body - [target, branch] for a backward branch, and the skipped instructions (branch, target) for a forward one.""" - offs, written = [], [] # per instruction, once: a program has hundreds of branches over thousands of instructions - for off, _n, name, asm in self.ins: - regs = set(range(128)) if name.startswith('s_movreld') else set() # M0 picks the destination - for tok in destinations(name, parse(asm)[1]): - r = reg_range(tok) - if r and r[0] == 's': - regs.update(range(r[1], r[2] + 1)) - elif tok == 'm0': - regs.add('m0') - offs.append(off) - written.append(regs) - writes = {} - for branch, target in branches: - lo, hi = ((bisect.bisect_left(offs, target), bisect.bisect_right(offs, branch)) if target <= branch else - (bisect.bisect_right(offs, branch), bisect.bisect_left(offs, target))) - writes.setdefault(target, set()).update(*written[lo:hi]) - return writes + seen, todo = set(), list(successors(start)) + while todo: + off = todo.pop() + if off in seen: + continue + seen.add(off) + name, asm = info[off] + if reads_scc(name, asm) and off not in calc: + raise Unsupported('SCC of %s at %#x (not modelled) is read by %s at %#x' + % (info[start][0], start, name, off)) + if off in written or off in unknown: + continue + todo.extend(successors(off)) def tracks_uniformity(self): return all(hasattr(self, name) for name in ('uniform_v', 'varying_s', 'scc_uniform')) @@ -2665,54 +3585,15 @@ def uniform_source(self, tok): def one(self, name, asm): _, ops, mods = parse(asm) base = re.sub(r'_e(32|64)$', '', name) - # Compute the proof before lowering, since a destination can also be a source. - dst = None - self._uniform_written = set() + if base.startswith('s_setreg') and 'HW_REG_MODE' in asm and (self.uses_round_mode or self.round16): + # a MODE write the tracking of op_s_round_mode / launch_mode would miss (none in the measured programs) + raise Unsupported('%s writes MODE in a program that uses s_round_mode or a non-zero launch mode' % base) + # Upstream proves VGPR uniformity per instruction here (UNIFORM_VALU); the local proof in set_v stays the + # only one, so uniform_v keeps its local meaning (written in every lane from lane-invariant values). if self.tracks_uniformity() and hasattr(self, 'uniform_expr'): - wrote_s = {r for r in self.forget_writes(name, ops, drop_since=False) if isinstance(r, int)} - else: - wrote_s = set() - # Unit probes build a Stage without __init__: without the tracking state, prove nothing. - # Past the entry block of a program with branches the read recomputes the defining expression, so the - # proof no longer needs a known exec (see op_v_readfirstlane_b32). - if (base in UNIFORM_VALU and ops and self.tracks_uniformity() and - (getattr(self, 'past_entry', False) and hasattr(self, 'uniform_expr') or - not getattr(self, 'past_entry', True) and getattr(self, 'exec_known', False)) and - (not mods or (base in VEC_F or base in VEC_U_TO_F) and - all(m in ('clamp', 'mul:2', 'mul:4', 'div:2') for m in mods))): - candidate = reg_range(ops[0]) - if candidate and candidate[0] == 'v' and candidate[1] == candidate[2]: - sources = ops[1:] - if base in VEC_F: - sources = [re.sub(r'^-(?=[^\d.])', '', tok).strip('|') for tok in sources] - if sources and all(self.uniform_source(tok) for tok in sources): - dst = candidate[1] + self.forget_writes(name, ops) self.last_v = None - term = self.lower(base, asm, ops, mods) - uniform_written = self._uniform_written - if self.tracks_uniformity() and getattr(self, 'since_join', None) is not None and wrote_s: - self.since_join -= (wrote_s - uniform_written) - if wrote_s and self.bad_sgprs is not None: - for r in wrote_s - uniform_written: - sym = self.sym.get(r) - if (r in self.varying_s or r in getattr(self, 'masks', ()) or - (sym is not None and sym[0] not in ('const', 'ud', 'fixed_buffer_word')) or - (self.defined_uniform_s is not None and r not in self.defined_uniform_s)): - if self.defined_uniform_s is not None: - self.defined_uniform_s.discard(r) - self.bad_sgprs.add(r) - if dst is not None: - self.uniform_v.add(dst) - if hasattr(self, 'uniform_expr'): - # Proven sources are scalars, constants and VGPRs; each VGPR needs its own current expression. - expr = self.last_v[1] if self.last_v and self.last_v[0] == dst else None - vs = [int(n) for n in re.findall(r'\bv(\d+)\b', expr or '')] - if expr is None or any(n not in self.uniform_expr for n in vs): - self.uniform_expr.pop(dst, None) - else: - self.uniform_expr[dst] = re.sub(r'\bv(\d+)\b', lambda m: '(%s)' % self.uniform_expr[int(m[1])], - expr) - return term + return self.lower(base, asm, ops, mods, name) def dpp_pair(self, base, asm, ops, mods): """A DPP16 spelling whose SRC0 is a quad pair broadcast (#2125 item C). @@ -2780,8 +3661,17 @@ def forget_writes(self, name, ops, drop_since=True): del self.uniform_expr[v] return regs - def lower(self, base, asm, ops, mods): + def lower(self, base, asm, ops, mods, name=None): + if name is None: + name = base pc = getattr(self, 'pc', None) + if getattr(self, 'kind', None) == 'ps' and os.environ.get('X2W_PS_WAVE_UNION') == '1' and getattr(self, 'ins', None): + if not hasattr(self, 'wave_plan'): + self.wave_plan = wave_union_plan(self.ins) + self.wave_uniform = wave_union_uniform(self.ins, self.wave_plan) if self.wave_plan else None + step = self.wave_plan.get(pc) + if step is not None: + return self.wave_union_step(step) calculated = getattr(self, 'calculated_pc', {}) if pc in calculated: target = calculated[pc] @@ -2797,6 +3687,14 @@ def lower(self, base, asm, ops, mods): if base in ('s_add_u32', 's_addc_u32'): self.scc_uniform = False return None + data = getattr(self, 'pc_data', {}).get(pc) + if data is not None and data[0] in ('getpc', 'lo', 'hi'): + # pc_data_proof: the image at virtual address 0; s_getpc_b64 itself is overwritten by the pair below. + if data[0] != 'getpc': + self.set_s(data[1], '0x%08xu' % data[2], ('const', data[2])) + if hasattr(self, 'scc_uniform'): + self.scc_uniform = False + return None if getattr(self, 'fetched', False): # unit probes build a Stage without __init__ # Behind a fetch call the definite-assignment guard relies on exec_known: every exec write must clear it. # s_wqm of exec into itself only adds lanes, so it stays a no-op; other s_wqm forms (a no-op here) and @@ -2810,64 +3708,64 @@ def lower(self, base, asm, ops, mods): if base in ('s_wqm_b32', 's_wqm_b64'): if ops[0] in ('exec', 'exec_lo') and ops[1:] == ops[:1] and getattr(self, 'exec_known', False): self.wqm_exec = True # every lane of a touched quad is now active, helper lanes included - if hasattr(self, 'uniform_v'): - self.uniform_v.clear() if hasattr(self, 'scc_uniform'): self.scc_uniform = False # the hardware SCC result is not modelled - return None - if base == 's_setreg_imm32_b32': - # The write itself changes nothing the lowering models, except MODE[1:0] (the binary32 rounding mode): - # v_cvt_pk_u8_f32 and the other conversions are lowered for round-to-nearest-even, and the hardware - # follows MODE.round (round toward zero truncates). s_round_mode and s_setreg_b32 are refused already. - field = re.fullmatch(r'hwreg\((HW_REG_MODE|1)(?:,\s*(\d+),\s*(\d+))?\)', ops[0].strip()) if ops else None - if field and int(field.group(2) or 0) < 2: # shortcut: an offset >= 2 cannot reach MODE[1:0] - # The immediate is known: the write is harmless when it leaves MODE[1:0] at 0 (nearest even). - offset, width = int(field.group(2) or 0), int(field.group(3) or 32) - try: - value = int(ops[1], 0) & 0xffffffff - except IndexError: - value = None - except ValueError: - # The disassembler prints some inline constants as floats (1.0, 0.5): take their binary32 bits. - try: - value = struct.unpack('<I', struct.pack('<f', float(ops[1])))[0] - except (ValueError, OverflowError): - raise Unsupported('%s %s: immediate not decoded' % (base, ', '.join(ops))) - if value is None: - raise Unsupported('%s %s: immediate not decoded' % (base, ', '.join(ops))) - if ((value & ((1 << width) - 1)) << offset) & 3: - raise Unsupported('%s %s writes the binary32 rounding mode MODE[1:0]' % (base, ', '.join(ops))) - if not ops or not ops[0].strip().startswith('hwreg('): - raise Unsupported('%s %s: hardware register not decoded' % (base, ', '.join(ops))) - return None - # s_waitcnt_depctr only delays the wave until the named dependency counters reach their thresholds. LLVM - # defines it with one immediate and no register definition, use or side effect (SOPInstructions.td, - # S_WAITCNT_DEPCTR) and inserts it only as a hazard delay (GCNHazardRecognizer.cpp, - # fixVMEMtoScalarWriteHazards). This model has no outstanding operation a counter could count. - if base in ('s_inst_prefetch', 's_waitcnt', 's_waitcnt_depctr', 's_nop', 'v_nop', 's_clause', 's_sopp_0f', - 's_code_end', 's_setprio'): + # LOCAL: uniform_v is kept (upstream clears it here) and s_wqm stays the no-op below. + if base in ('s_inst_prefetch', 's_waitcnt', 's_nop', 'v_nop', 's_clause', 's_sopp_0f', 's_wqm_b64', 's_wqm_b32', + 's_setreg_imm32_b32', 's_code_end', 's_setprio'): return None if base == 's_endpgm': return ('end',) if base == 's_branch': return ('jump', int(ops[0].split('_')[1], 16)) - if base == 's_barrier' and getattr(self, 'kind', None) == 'cs' and self._lds_general_barrier_ok(): - if mods or ops not in ([], ['0'], ['0x0']): - raise Unsupported('s_barrier with unexpected operands or modifiers') - self._lds_require_alloc(base) - self.emit('GroupMemoryBarrierWithGroupSync();') + if (base in ('s_cbranch_scc1', 's_cbranch_execnz') + and getattr(self, 'pc', None) in getattr(self, 'waterfall_back', ())): + if getattr(self, 'wave_plan', None): + raise Unsupported('waterfall loop in a wave-union program (its one-pass form is per lane)') + self.lines.append('// waterfall back edge: not taken for this lane (one pass, see waterfall)') return None if base.startswith('s_cbranch_'): - if getattr(self, 'kind', None) == 'ms' and base in ('s_cbranch_scc0', 's_cbranch_scc1') and not self.scc_uniform: + if (getattr(getattr(self, 'pipe', None), 'uses_mesh_skeleton', False) and self.kind == 'ms' + and base in ('s_cbranch_scc0', 's_cbranch_scc1') and not self.scc_uniform): raise Unsupported('slot 57 mesh: a branch reads SCC that is not proven wave-uniform') cond = {'scc0': '!scc', 'scc1': 'scc', 'vccz': '(vcc & 1) == 0', 'vccnz': '(vcc & 1) != 0', 'execz': '(exec & 1) == 0', 'execnz': '(exec & 1) != 0'}[base[10:]] + if getattr(self, 'wave_plan', None): + # X2W_PS_WAVE_UNION=1 took wave reductions here, so the lanes of a host wave must reach them together: + # every conditional branch is decided once for the host wave, as the guest decides it for the wave64. + # execz / vccz test the whole mask: no lane's bit set (WaveActiveAnyTrue of the lane's bit). An SCC + # branch is taken only when wave_union_uniform proves its SCC host-uniform (computed from user data, + # constants, uniform loads and wave results only): every lane then holds the wave's SCC. Lanes whose + # own exec bit is 0 run a block with exec 0, as the lanes of a guest wave that does not skip it do + # (the execz lane facts are not recorded under the plan, see blocks). + kind = base[10:] + if kind in ('scc0', 'scc1'): + why = self.wave_uniform[0].get(self.pc) if self.wave_uniform else 'no analysis' + if why is not None: + raise Unsupported('%s in a wave-union program: SCC not host-uniform (%s)' % (base, why)) + else: + reg = 'exec' if kind.startswith('exec') else 'vcc' + any_set = 'WaveActiveAnyTrue((%s & 1) != 0)' % reg + cond = any_set if kind.endswith('nz') else '!' + any_set return ('branch', cond, int(ops[0].split('_')[1], 16)) if base == 'exp': return self.export(asm) - if base in (*LDS_EXCHANGE_OPS, 's_barrier'): - if getattr(self, 'kind', None) != 'cs': - raise Unsupported(base) + modes = self.mode_at.get(self.pc) if self.mode_at else None + if modes is not None and self.rounds16(name): + # the MODE[3:2] values that reach this instruction on every path (round_mode_flow) + if '?' in modes: + raise Unsupported('%s: f16/f64 rounding with the launch FLOAT_MODE not passed (.psin third field)' + % name) + if modes != {self.round16}: + raise Unsupported('%s at %#x reached under MODE f16 roundings %s (the translation uses %d)' + % (name, self.pc, sorted(modes, key=str), self.round16)) + if self.round16: + self.check_round16(name) + elif self.launch_unknown and modes is None: + self.check_launch_known(name) + if base.endswith('_dpp'): + return self.quad_dpp(base[:-len('_dpp')], ops, mods) + if base in (*LDS_EXCHANGE_OPS, 's_barrier') and getattr(self, 'kind', None) == 'cs': # The refusal census continues past failed instructions. Scan this program only once. if not hasattr(self, 'lds_error'): self.lds_error = None @@ -2910,21 +3808,19 @@ def lower(self, base, asm, ops, mods): for k in range(dwords): self.set_v(lo + k, 'lds[%s]' % ('a' if k == 0 else 'a + %du' % k)) return None - if base.endswith('_dpp'): - return self.dpp(base[:-len('_dpp')], ops, mods) + if base == 's_ff1_i32_b32' and ops[1:] == ['exec_lo'] and getattr(self, 'kind', None) == 'cs': + dst = reg_range(ops[0]) + if mods or not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('s_ff1_i32_b32 requires one unmodified SGPR destination') + if self.past_entry or not self.exec_known: + raise Unsupported('s_ff1_i32_b32 requires the compute entry EXEC mask') + # Even the final partial group starts with lane zero active. FF1 preserves SCC. + self.set_s(dst[1], '0u', ('const', 0)) + return None handler = getattr(self, 'op_' + base, None) if handler: return handler(ops, mods) - if base in MUBUF_ATOMIC_OPS: - return self.buffer_atomic(base, ops, mods) - if base in LDS_DUAL_OPS: - return self.lds_dual(base, ops, mods) - if base in LDS_ATOMIC_OPS: - return self.lds_atomic(base, ops, mods) - if base.endswith('_dpp'): - return self.dpp(base[:-len('_dpp')], ops, mods) if base.startswith('v_cmp'): - # Before the VOP1/VOP2 SDWA route below: VOPC SDWA names also end in _sdwa. return self.compare(base, ops, mods) if base.endswith('_sdwa'): return self.sdwa(base[:-len('_sdwa')], ops, mods) @@ -2936,6 +3832,18 @@ def lower(self, base, asm, ops, mods): args = [self.f(o) for o in ops[1:1 + arity]] if base in ('v_fmac_f32', 'v_mac_f32'): args.append(self.f(ops[0])) + if base in FMA_FUSED or base in FMA_UNFUSED: + # The multiply-add rule (lead 000800 answer; the same rule as mesh2hlsl's): a fused op is one + # rounding, an unfused one rounds the product first; both made deterministic so a depth pre-pass and + # a colour pass of the same geometry agree bit for bit. Recorded in the manifest as `fma <rule>`. + pipe = getattr(self, 'pipe', None) # the tests' bare stages have none + if hasattr(pipe, 'fma_rule'): + pipe.fma_rule = DRAW_FMA + helper = 'x2w_fma_exact' if base in FMA_FUSED and DRAW_FMA == 'exact' else 'x2w_mad_precise' + if helper == 'x2w_fma_exact' and exact_with_zero(args): + helper = 'x2w_mad_precise' # exact here, and keeps fxc's d(0, 0) out (see zero_operand) + if DRAW_FMA != 'legacy': + return self.set_vf(reg_range(ops[0])[1], '%s(%s, %s, %s)' % ((helper,) + tuple(args)), mods) return self.set_vf(reg_range(ops[0])[1], text.format(*args), mods) if base in VEC_U_TO_F: arity, text_f = VEC_U_TO_F[base] @@ -2951,21 +3859,48 @@ def lower(self, base, asm, ops, mods): return None if base in VEC_U: arity, text = VEC_U[base] - if mods: - raise Unsupported('%s with %s' % (base, mods)) if len(ops) != arity + 1: raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), arity + 1)) + if base == 'v_mad_u32_u16' and mods and all(m.startswith('op_sel:[') for m in mods): + # VOP3 op_sel[i] reads S_i[31:16] for the two 16-bit sources; S2 is 32-bit and D has no half. + sel = [int(x) for x in mods[-1][len('op_sel:['):-1].split(',')] + if len(mods) != 1 or len(sel) != 3 or sel[2] or any(x not in (0, 1) for x in sel): + raise Unsupported('%s with %s' % (base, mods)) + halves = [] + for tok, high in zip(ops[1:3], sel): + r = reg_range(tok) + if high and not (r and r[1] == r[2]): + raise Unsupported('%s op_sel on %s' % (base, tok)) + halves.append('(%s >> 16)' % self.u(tok) if high else '(%s & 0xffffu)' % self.u(tok)) + return self.set_v(reg_range(ops[0])[1], '%s * %s + %s' % (halves[0], halves[1], self.u(ops[3]))) if base == 'v_and_b32': c0, c1 = self.const_u32(ops[1]), self.const_u32(ops[2]) - args = [self.u(ops[1], low16_only=c1 is not None and (c1 & 0xffff0000) == 0), - self.u(ops[2], low16_only=c0 is not None and (c0 & 0xffff0000) == 0)] + values = [self.u(ops[1], low16_only=c1 is not None and (c1 & 0xffff0000) == 0), + self.u(ops[2], low16_only=c0 is not None and (c0 & 0xffff0000) == 0)] else: - args = [self.u(o) for o in ops[1:1 + arity]] + values = [self.u(o) for o in ops[1:1 + arity]] + if base == 'v_mad_u32_u16' and len(mods) == 1: + which = re.fullmatch(r'op_sel:\[([01]),([01]),0\]', mods[0]) + if which: + for i, high in enumerate(which.groups()): + if high == '1': + reg = reg_range(ops[i + 1]) + if not reg or reg[1] != reg[2]: + raise Unsupported('v_mad_u32_u16 high half of %s' % ops[i + 1]) + values[i] = '(%s >> 16u)' % values[i] + mods = [] if base in ('v_sad_u8', 'v_sad_u16', 'v_sad_u32'): pipe = getattr(self, 'pipe', None) if pipe is not None and isinstance(getattr(pipe, 'uses_sad', None), set): pipe.uses_sad.add(base) - return self.set_v(reg_range(ops[0])[1], text.format(*args)) + result = text.format(*values) + if mods: + # VOP3 output modifiers (omod, clamp) act on a binary32 result, so they are only taken on the + # integer-source conversions that produce one; set_vf applies omod and then the clamp. + if base not in FLOAT_RESULT_U or any(m not in ('clamp', 'mul:2', 'mul:4', 'div:2') for m in mods): + raise Unsupported('%s with %s' % (base, mods)) + return self.set_vf(reg_range(ops[0])[1], 'F(%s)' % result, mods) + return self.set_v(reg_range(ops[0])[1], result) if base in SCA: return self.scalar(base, ops) if base == 's_getpc_b64': @@ -2976,6 +3911,100 @@ def lower(self, base, asm, ops, mods): raise Unsupported('%s: the shader load address is only elided for a program that also calculates a branch target' % base) raise Unsupported(base) + # DPP16 quad permutations in a pixel stage: src0 is read from lane perm[lane & 3] of the lane's 2x2 quad, the + # rest of the instruction is the plain VOP1/VOP2 operation. LLVM AMDGPUModifierSyntax.md: quad_perm is a "full + # permute of 4 threads"; fi:1 "fetch pre-existing values from inactive lanes"; bound_ctrl only acts on invalid + # lanes, which a quad permutation never names. Quad lane 1 is +x and lane 2 is +y (Mesa ACO + # aco_select_nir_intrinsics.cpp: ddx_coarse = v_subrev_f32 with quad_perm(0,0,0,0) then v_mov_b32 + # quad_perm(1,1,1,1), ddy_coarse with (2,2,2,2)), the order of D3D QuadReadLaneAt (0 top-left, 1 top-right, + # 2 bottom-left, 3 bottom-right). The HLSL quad reads need SM 6.0 (the mesh pipelines' dxc ps_6_0, which sets + # pipe.quad_ops; draws compile with fxc ps_5_1 and refuse), and every lane of the quad must execute them: + # each read is its own statement outside the exec guard, and check_quad_ops refuses one that a lane can skip. + QUAD_READS = {(1, 0, 3, 2): 'QuadReadAcrossX({0})', (2, 3, 0, 1): 'QuadReadAcrossY({0})', + (3, 2, 1, 0): 'QuadReadAcrossDiagonal({0})'} + + def quad_dpp(self, base, ops, mods): + if self.kind != 'ps' or not getattr(self.pipe, 'quad_ops', False): + raise Unsupported('%s_dpp' % base) # as before: no lane reads outside an SM 6.0 pixel stage + control = mods[0] if mods else 'no control' + m = re.fullmatch(r'quad_perm:\[([0-3]),([0-3]),([0-3]),([0-3])\]', control) + if not m: + raise Unsupported('%s_dpp with %s (not a quad permutation)' % (base, control)) + rest = set(mods[1:]) + if len(rest) != len(mods) - 1 or not {'row_mask:0xf', 'bank_mask:0xf', 'fi:1'} <= rest \ + or rest - {'row_mask:0xf', 'bank_mask:0xf', 'fi:1', 'bound_ctrl:1'}: + raise Unsupported('%s_dpp with %s' % (base, ' '.join(mods[1:]))) + perm = tuple(int(x) for x in m.groups()) + src = re.fullmatch(r'(-?\|?)(v\d+)(\|?)', ops[1]) if len(ops) > 1 else None + if not src: + raise Unsupported('%s_dpp source %s' % (base, ops[1] if len(ops) > 1 else None)) + value = self.u(src.group(2)) + if len(set(perm)) == 1: + expr = 'QuadReadLaneAt(%s, %du)' % (value, perm[0]) + elif perm in self.QUAD_READS: + expr = self.QUAD_READS[perm].format(value) + else: + raise Unsupported('%s_dpp with %s' % (base, control)) + names = self.__dict__.setdefault('dpp_names', []) + name = 'dpp%d' % len(names) + names.append(name) + self.__dict__.setdefault('dpp_at', []).append(self.pc) + statement = 'uint %s = %s;' % (name, expr) + self.__dict__.setdefault('dpp_statements', set()).add(statement) + self.emit(statement) + return self.one(base, '%s %s' % (base, ', '.join([ops[0], src.group(1) + name + src.group(3)] + ops[2:]))) + + def check_quad_ops(self): + """Refuse a quad read (quad_dpp) that some lane of the HLSL may not execute: the program has a loop (the + dispatch loop lets lanes reach a block in different iterations), or a path from the entry to the end + avoids the instruction (a per-lane branch around it).""" + at = getattr(self, 'dpp_at', ()) + if not at: + return + info = {off: (name, asm) for off, n, name, asm in self.ins} + order = [ins[0] for ins in self.ins] + following = dict(zip(order, order[1:])) + def successors(off): + name, asm = info[off] + if name == 's_endpgm': + return [] + nxt = [] if name == 's_branch' else [following[off]] if off in following else [] + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + return [o for o in nxt if o in info] + uniform = os.environ.get('X2W_PS_QUAD_UNIFORM') == '1' + last_quad = max(at) + for off in order: + if any(t <= off and (not uniform or t <= last_quad) for t in successors(off) if t != following.get(off)): + raise Unsupported('quad read (DPP) at %#x in a program with a loop (branch at %#x)' % (at[0], off)) + if uniform: + # Forward dispatch visits each block once, in guest instruction order. Leave + # VGPR writes and consumers predicated, but read every lane's retained VGPR + # outside the guest PC guard (fi:1). A prior discard can disable a source lane. + killed = False + for _, lines, _ in self.blocks: + depth = 0 + for line in lines: + if line in self.dpp_statements and (killed or depth): + raise Unsupported('uniform quad read after discard or inside a nested scope') + killed |= bool(re.search(r'\b(discard|return)\b', line)) + depth += line.count('{') - line.count('}') + self.uniform_dpp = self.dpp_statements + return + for target in at: + seen, todo = set(), [order[0]] + while todo: + off = todo.pop() + if off in seen or off == target: + continue + seen.add(off) + nxt = successors(off) + if not nxt: + if self.quad_divergent: + self.quad_divergent_used.append(target) + break + raise Unsupported('quad read (DPP) at %#x is skipped on a path to %#x' % (target, off)) + todo.extend(nxt) # VOP1/VOP2 with DPP16 quad broadcast (#2125 item A): quad_perm:[k,k,k,k] makes every lane read SRC0 from # lane k of its own quad (RDNA 2 ISA, "DPP": a lane reads lane (lane & ~3) | perm[lane & 3] of the row; LLVM 15 # AMDGPU DPP quad_perm). A pixel stage's four consecutive lanes are a 2x2 pixel quad (lane = x & 1 | (y & 1) << 1), @@ -3120,28 +4149,40 @@ def sdwa(self, base, ops, mods): if base == 'v_cvt_off_f32_i4': raise Unsupported('SDWA form of %s' % base) fields = {} - out_mods = [] - float_result = base in VEC_U_TO_F + outmods = [] for m in mods: - if float_result and m in ('clamp', 'mul:2', 'mul:4', 'div:2'): - out_mods.append(m) + key, _, value = m.partition(':') + if key in ('src0_sel', 'src1_sel', 'src2_sel', 'dst_sel', 'dst_unused') and value: + fields[key] = value + elif m in ('clamp', 'mul:2', 'mul:4', 'div:2') and base in VEC_U_TO_F: + # The SDWA9 encoding (gfx9+, LLVM VOPInstructions.td VOP_SDWA9 has omod and clamp for VOP1/VOP2) + # carries the output modifiers; on a float-result conversion they act on the binary32 result as + # in VOP3. Taken only with dst_sel:DWORD (below), where no field placement follows them. + outmods.append(m) else: - key, _, value = m.partition(':') - if key in ('src0_sel', 'src1_sel', 'src2_sel', 'dst_sel', 'dst_unused') and value: - fields[key] = value - else: - raise Unsupported('%s with SDWA modifier %s' % (base, m)) - if float_result: - arity, text = VEC_U_TO_F[base] - elif base in VEC_U: - arity, text = VEC_U[base] + raise Unsupported('%s with SDWA modifier %s' % (base, m)) + if base == 'v_cndmask_b32': + # VOP2 SDWA select: the mask is always vcc; the selected source fields are moved as bits. + if len(ops) != 4 or ops[3] not in ('vcc', 'vcc_lo'): + raise Unsupported('SDWA v_cndmask_b32 form %s' % ops) + arity, text = 2, '(vcc & 1) ? {1} : {0}' + elif base == 'v_add_f16' and len(ops) == 3 and ops[1] in FLOATS and ops[2] == '0': + if fields.get('src0_sel') not in ('WORD_0', 'DWORD') or fields.get('src1_sel') != 'DWORD': + raise Unsupported('SDWA inline half add source selection') + arity, text = 1, '{0}' elif base == 'v_mov_b32': + # VOP1 SDWA move (LLVM VOP1Instructions.td V_MOV_B32 has an SDWA form): the selected source field, + # placed by dst_sel / dst_unused like every integer SDWA result. arity, text = 1, '{0}' - # A lane mask is one bit per lane here, so a byte or word of it is not the hardware's field. - if fields.get('src0_sel') != 'DWORD' and self.is_lane_mask(ops[1].removeprefix('sext(').removesuffix(')')): - raise Unsupported('v_mov_b32 SDWA %s of lane mask %s' % (fields.get('src0_sel'), ops[1])) - else: + elif base in VEC_U_TO_F: + # The float-result conversions moved out of VEC_U (#1707) keep their SDWA form: the same expression + # as the bits, as VEC_U had it ('U(float({0}))' and so on). No output modifier is accepted above. + arity, text_f = VEC_U_TO_F[base] + text = 'U(%s)' % text_f + elif base not in VEC_U: raise Unsupported('SDWA form of %s' % base) + else: + arity, text = VEC_U[base] sources = [] for index in range(arity): token = ops[1 + index] @@ -3153,23 +4194,28 @@ def sdwa(self, base, ops, mods): raise Unsupported('%s SDWA without src%d_sel' % (base, index)) low16 = selection in ('BYTE_0', 'BYTE_1', 'WORD_0') or ( selection == 'DWORD' and not sext and base in ('v_cvt_f32_f16', 'v_cvt_f32_ubyte0', 'v_cvt_f32_ubyte1')) - sources.append(sdwa_source(self.u(token, low16_only=low16), selection, sext)) + word = self.h(token) if base == 'v_add_f16' else self.u(token, low16_only=low16) + sources.append(sdwa_source(word, selection, sext)) result = text.format(*sources) - if float_result: - # Output modifiers scale and then clamp the float value; dst_sel writes its bit pattern. - result = 'U(%s)' % self.f_mods(result, out_mods) select = fields.get('dst_sel') if not select: raise Unsupported('%s SDWA without dst_sel' % base) + if outmods: + if select != 'DWORD': + raise Unsupported('%s SDWA with %s and dst_sel:%s' % (base, ' '.join(outmods), select)) + return self.set_vf(reg_range(ops[0])[1], text_f.format(*sources), outmods) # The operation's HLSL carries its own operators, so it has to be grouped before the # destination field masks it: "v7 | v8 & 0xffff" would otherwise bind as "v7 | (v8 & 0xffff)". if SDWA_SEL[select][1] < 32: result = '(%s)' % result destination = reg_range(ops[0])[1] unused = fields.get('dst_unused', 'UNUSED_PAD') + # UNUSED_PRESERVE reads the destination's other bits: read it as an operand, so a pixel stage's entry + # (SPI input) VGPR read is recorded like any other read + old = self.u(ops[0]) if unused == 'UNUSED_PRESERVE' and SDWA_SEL[select][1] < 32 else 'v%d' % destination keep_low16 = (unused == 'UNUSED_PRESERVE' and select not in ('DWORD', 'WORD_1') and destination in self.low16_only_v) - self.set_v(destination, sdwa_dest(result, select, unused, 'v%d' % destination), low16_only=keep_low16) + self.set_v(destination, sdwa_dest(result, select, unused, old), low16_only=keep_low16) # scalar ALU with descriptor-word bookkeeping def exec_absorbed_source(self, base, srcs): @@ -3182,14 +4228,87 @@ def exec_absorbed_source(self, base, srcs): is 0 on exactly the paths where the variable of S may not hold the register's value, and there the result is 0 (or 1 for orn2) whatever S holds. Only the instruction at the target qualifies: exec is unchanged.""" off, regs = getattr(self, 'exec_zero_join', (None, ())) - if off is None or off != getattr(self, 'pc', None) or len(srcs) != 2: + if off is not None and off == getattr(self, 'pc', None) and len(srcs) == 2: + for i in {'s_and_b64': (0, 1), 's_orn2_b64': (0,)}.get(base, ()): + reg = reg_range(srcs[i]) + if srcs[1 - i] == 'exec' and reg and reg[0] == 's' and reg[1] in regs: + return i + # A conflict source S (stale on some edge) of `S op exec` whose result bit 0 is fixed by this lane's exec + # bit e (EXEC_ABSORB): exact when exec is e now, or when exec is e on every reachable edge of the join + # where S's variable may be stale and the HLSL has not assigned exec since (on the other edges S's + # variable holds the register). + rule = EXEC_ABSORB.get(base) + if rule is None or len(srcs) != 2 or not getattr(self, 'lane_track', False): return None - for i in {'s_and_b64': (0, 1), 's_orn2_b64': (0,)}.get(base, ()): + positions, e = rule + for i in (0, 1): reg = reg_range(srcs[i]) - if srcs[1 - i] == 'exec' and reg and reg[0] == 's' and reg[1] in regs: + if (srcs[1 - i] not in ('exec', 'exec_lo') or (1 - i) not in positions or not reg or reg[0] != 's' or + self.sym.get(reg[1]) != ('conflict',)): + continue + record = getattr(self, 'conflict_exec', {}).get(reg[1]) + if lane_fact_bit(getattr(self, 'lane_facts', None), 'exec') == e or ( + record is not None and record[1] == getattr(self, 'exec_writes', 0) and record[0] <= {e}): return i return None + def vcc_descriptor_copy(self, dname, ops, syms): + """`s_mov_b64 vcc, s[N:N+1]` / `s_mov_b32 vcc_lo, sN` of descriptor words, with vcc used as a spare pair: + the words are kept as the symbols of s106 / s107 (read by a descriptor operand such as s[104:107]), and the + HLSL vcc is not assigned. Taken only when, on every path from here until a must-write of each half, no + instruction reads that half of vcc by name except an `s_mov_b64 D, vcc` / `s_mov_b32 D, vcc_lo` copy (the + copy takes the symbols again, and refuses unless vcc still holds descriptor words there).""" + if not getattr(self, 'lane_track', False): + return False + lo = syms[0] + r = reg_range(ops[1]) + words = [lo] + ([self.sym.get(r[2])] if dname == 'vcc' and r else []) + if dname == 'vcc' and (not r or r[2] != r[1] + 1): + return False + if not all(w and w[0] in VCC_WORD_KINDS for w in words): + return False + live0 = frozenset(('vcc', 'vcc_hi')[:len(words)]) + order = [ins[0] for ins in self.ins] + info = {off: (name, asm) for off, _n, name, asm in self.ins} + following = dict(zip(order, order[1:])) + calc = getattr(self, 'calculated_pc', None) or {} + copyouts = set() + seen = set() + todo = [(following.get(self.pc), live0)] + while todo: + off, live = todo.pop() + if off is None or (off, live) in seen: + continue + seen.add((off, live)) + name, asm = info[off] + if off in calc: + return False + reads, must, _may = scalar_effects(name, asm) + base = re.sub(r'_e(32|64)$', '', name) + if reads & live: + ops2 = parse(asm)[1] + if (base, tuple(ops2[1:])) in (('s_mov_b64', ('vcc',)), ('s_mov_b32', ('vcc_lo',))) and \ + reg_range(ops2[0]) and reg_range(ops2[0])[0] == 's' and \ + reads & {'vcc', 'vcc_hi'} <= live: + copyouts.add(off) + else: + return False + live = live - must + if not live or name == 's_endpgm': + continue + nxt = [] if name == 's_branch' else [following.get(off)] + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + todo += [(o, live) for o in nxt if o in info] + for w, sym in zip((106, 107), words): + self.sym[w] = sym + # Every path into a copy must come from this copy-in with vcc not written since (translate drops the tag). + self.sym['vccwords'] = ('vccwords', self.pc) + self.vcc_copyouts = getattr(self, 'vcc_copyouts', {}) + for off in copyouts: + self.vcc_copyouts.setdefault(off, set()).add(self.pc) + return True + def scalar(self, base, ops): # Every SALU form in SCA is dst, src (the two templates below use {0} and {1}); a short list would # index past the end and leave `translator crash in <op>: IndexError` in the census instead of a @@ -3198,6 +4317,8 @@ def scalar(self, base, ops): raise Unsupported('%s with %d operands, expected 2' % (base, len(ops))) if base == 's_movk_i32' and len(ops) != 2: raise Unsupported('s_movk_i32 with %d operands, expected 2' % len(ops)) + if base in CARRY_OUT and getattr(self, 'pc', None) in getattr(self, 'carry_writes', ()): + return self.scalar_carry(base, ops) text, scc = SCA[base] if base in SCC_UNMODELLED and self.tracks_uniformity(): self.scc_uniform = False @@ -3209,63 +4330,97 @@ def low(tok): r = reg_range(tok) return ('s%d' % r[1]) if r and r[0] == 's' and r[1] != r[2] else tok srcs = [low(t) for t in srcs] - dname = low(ops[0]) if base == 's_movk_i32': - srcs = [str(sopk_imm(srcs[0], True))] # D.i32 = signext(SIMM16) - shift_add = base in SHIFT_ADD - word_complement = base in ('s_nand_b32', 's_nor_b32', 's_xnor_b32') - lane_complement = False - # s_mul_hi_u32 needs the whole 32-bit word of each source, like the halfword pack. - word_pack = base in PACK_B16 or base in ('s_sext_i32_i8', 's_sext_i32_i16', 's_mul_hi_u32') - word_absdiff = base == 's_absdiff_i32' - if shift_add or word_complement or word_pack or word_absdiff: - # The per-lane mask cannot supply the full word needed by these operations. s_mul_hi_u32 into an - # SGPR that held a mask replaces it with a plain word (set_s drops the mark), so only vcc/exec count. - mask_dest = (dname in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') if base == 's_mul_hi_u32' - else self.is_lane_mask(dname)) - # Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask the lane's - # bit of the result is exact. Only an SGPR destination is taken; a mixed mask and plain word is not. - def mask_source(tok): - r = reg_range(tok) - return tok in ('vcc', 'vcc_lo', 'exec', 'exec_lo') or bool( - r and r[0] == 's' and r[1] == r[2] and r[1] in self.masks) - lane_complement = (word_complement and bool(dst) and dst[0] == 's' and dst[1] == dst[2] and dst[1] <= 105 - and all(mask_source(t) for t in srcs)) - if not lane_complement and (mask_dest or any(self.is_lane_mask(t) for t in srcs)): + # D.i32 = signext(SIMM16) (RDNA 2 ISA SOPK; LLVM s16imm); disasm_rdna2 prints the field unsigned. + srcs = [sopk_simm(srcs[0])] + dname = low(ops[0]) + # Upstream: s_sext_i32_i8 / s_sext_i32_i16 (SCA) need the whole word of their source, not a lane mask. + pack_or_absdiff = base in PACK_B16 or base == 's_absdiff_i32' + if pack_or_absdiff or base in ('s_sext_i32_i8', 's_sext_i32_i16'): + if self.is_lane_mask(dname) or any(self.is_lane_mask(t) for t in srcs): raise Unsupported('%s on a lane mask' % base) - if lane_complement and any(reg_range(t) and reg_range(t)[1] in getattr(self, 'join_masks', ()) - for t in srcs): - raise Unsupported('%s on a lane mask joined at a branch target' % base) - if shift_add and dname != 'm0' and (not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105): - raise Unsupported('%s destination %s' % (base, dname)) - if word_pack: if dname != 'm0' and (dst is None or dst[0] != 's' or dst[1] > 105): raise Unsupported('%s destination %s' % (base, dname)) for source in srcs: reg = reg_range(source) if reg and (reg[0] != 's' or reg[1] > 105): raise Unsupported('%s source %s' % (base, source)) - if pair and ('m0' in srcs or dname == 'm0'): - raise Unsupported('64-bit scalar operand m0') - def src_sym(t): - if t == 'm0': - return self.sym.get('m0') - r = reg_range(t) - return self.sym.get(r[1]) if r and r[0] == 's' else None - syms = [src_sym(t) for t in srcs] - if any(s and s[0] in ('desc', 'descnum', 'ptr', 'ptrhi') for s in syms): - if scc or base in SCC_UNMODELLED: - self.scc_effect = 'descriptor' - if self.tracks_uniformity(): - self.scc_uniform = False - if shift_add or word_complement or word_absdiff: - raise Unsupported('scc from descriptor data') - if word_pack: + word_complement = base in ('s_nand_b32', 's_nor_b32', 's_xnor_b32') + if word_complement: + # A lane mask operand or destination is the whole wave's mask, and SCC is set when any bit of the + # complemented 32-bit result is set; the one-lane projection keeps only this lane's bit. + def lane_mask(t): + r = reg_range(t) + return t in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or bool(r and r[0] == 's' and r[1] in self.masks) + def per_lane(t): + # a value whose bit i is lane i's: a mask, or 0 / 0xffffffff (every bit the same) + r = reg_range(t) + return (lane_mask(t) or t in ('0', '-1') or + bool(r and r[0] == 's' and r[1] in getattr(self, 'splat', ()))) + if lane_mask(dname) or any(lane_mask(t) for t in srcs): + if not all(per_lane(t) for t in srcs): + raise Unsupported('%s on a lane mask' % base) + # Every operand's bit i is lane i's, so the lane's own bit of ~(a op b) is ~(a_i op b_i), which the + # one-lane value below gives (as for s_not_b32). SCC is not: lanes outside the wave's active set + # (0 in a compare result) are 1 after the complement. No SCC is written, so check_scc refuses any + # read of it. + scc = None + if dname == 'm0' and not pack_or_absdiff: + return None + if (base == 's_andn2_b64' and dst and dst[0] == 's' and dst[2] == dst[1] + 1 + and ops[0] == ops[1] and ops[2] == 'exec' and self.sym.get(dst[1]) == ('conflict',) + and getattr(self, 'execz_fallthrough_epoch', None) == getattr(self, 'exec_writes', 0)): + # Each executing lane computes D_i & ~1. Lanes skipping the block already retain + # their old bit. Leave the wave-wide SCC unmodelled; check_scc rejects a live read. + self.set_s(dst[1], '0u') + self.set_s(dst[2], '0u') + self.masks.add(dst[1]) + return None + if base in ('s_and_b32', 's_and_b64') and any(t in ('exec', 'exec_lo') for t in srcs) and reg_range(dname): + # D = D & exec where D is symbolic only on s_cbranch_execz edges into a join (merge) and exec has not + # been written since: on those paths this lane's exec bit is 0, so the result is 0 whatever D held, + # and on the others D's run-time variable is its value. + d0 = reg_range(dname)[1] + regs = (d0, d0 + 1) if pair else (d0,) + def execzero(r): + return (self.sym.get(r) == ('conflict',) and + getattr(self, 'execzero', {}).get(r, -1) == getattr(self, 'exec_writes', 0)) + if dname in srcs and all(self.sym.get(r) is None or self.sym[r][0] in self.RUNTIME_BACKED + or execzero(r) for r in regs): + for r in regs: + if execzero(r): + self.sym.pop(r) + syms = [self.sym.get(reg_range(t)[1]) if reg_range(t) and reg_range(t)[0] == 's' else None for t in srcs] + if getattr(self, 'pc', None) in getattr(self, 'vcc_copyouts', ()): + # A copy of vcc while it holds descriptor words (vcc_descriptor_copy): the words' symbols move on. + words = (106, 107) if pair else (106,) + tag = self.sym.get('vccwords') + if not (tag and tag[0] == 'vccwords' and tag[1] in self.vcc_copyouts[self.pc]) or not all( + self.sym.get(w) and self.sym[w][0] in VCC_WORD_KINDS for w in words): + raise Unsupported('mask from descriptor data') + d = reg_range(dname)[1] + for k, w in enumerate(words): + self.sym[d + k] = self.sym[w] + self.masks.discard(d + k) + return None + # Words of a resource-heap descriptor in arithmetic that is not a copy or a recognized descriptor edit: + # numbers (heap_word). + hwords = [self.heap_word(s) for s in syms] + numeric = (any(hwords) and dname not in ('exec', 'vcc', 'exec_lo', 'vcc_lo', 'm0') and not pair + and not base.startswith(('s_mov', 's_cmov')) + and all(h or not (s and s[0] in ('desc', 'descnum', 'ptr', 'ptrhi')) for h, s in zip(hwords, syms)) + and raw_descriptor_alu(base, syms, [self.const_u32(t) for t in srcs]) is None) + if (not numeric and any(s and s[0] in ('desc', 'descnum', 'dwnum') for s in syms) + and self.tw_scalar(base, srcs, syms, dname, pair)): + return None + if not numeric and any(s and s[0] in ('desc', 'descnum', 'ptr', 'ptrhi') for s in syms): + if pack_or_absdiff: raise Unsupported('%s on descriptor data' % base) - if dname == 'm0': - if scc: - raise Unsupported('scc from descriptor data') - self.sym['m0'] = syms[0] if base == 's_mov_b32' else ('descnum',) + if word_complement: + # the descriptor path below records the word symbolically and emits no SCC + raise Unsupported('scc from descriptor data') + if (dname in ('vcc', 'vcc_lo') and base == ('s_mov_b64' if dname == 'vcc' else 's_mov_b32') and + self.vcc_descriptor_copy(dname, ops, syms)): return None if dname in ('exec', 'vcc', 'exec_lo', 'vcc_lo'): raise Unsupported('mask from descriptor data') @@ -3275,10 +4430,14 @@ def src_sym(t): if getattr(self, 'kind', None) in ('cs', 'vs') and len(syms) == 2 else None) if base in ('s_mov_b32', 's_mov_b64'): self.sym[d] = syms[0] + source = reg_range(srcs[0]) + for i in range(source[2] - source[1] + 1 if source and source[0] == 's' else 0): + if self.sym.get(self.table_edit_key(source[1] + i)): + self.table_mark_edit(d + i) # a copy of an edited word is not the table's word (table_word) if pair: high = reg_range(ops[1])[2] hi = self.sym.get(high) - if hi and not run_time_symbol(hi): + if hi and not run_time_symbol(hi) and hi[0] != 'loopback': self.sym[d + 1] = hi # a descriptor word, a pointer or an unassigned constant: symbol only else: # A value the high word holds at run time is copied at run time too, so a join that later @@ -3294,15 +4453,20 @@ def src_sym(t): self.pipe.modified.add(desc_key(raw)) elif own and own[0] in ('desc', 'ptr', 'ptrhi') and any(s == own for s in syms): if own[0] == 'desc': - self.pipe.modified.add(desc_key(own)) - # Keep the resource identity for loads; stores refuse the unproved value. - self.sym[d] = own[:4] + ('modified',) - getattr(self.pipe, 'other_modified', set()).add(desc_key(own)) - else: - self.sym[d] = own if len(own) > 2 else own + ('added',) # the added offset is not tracked + self.pipe.modified.add((own[1], own[2])) + self.table_mark_edit(d) + # which word changed and how (buffer_store accepts edits that keep the base address) + other = [t for t, s in zip(srcs, syms) if s != own] + self.pipe.__dict__.setdefault('modified_words', {}).setdefault((own[1], own[2]), []).append( + (own[3], base, tuple(other))) else: self.sym[d] = ('descnum',) return None + if base.startswith(('s_bcnt', 's_ff0', 's_ff1')) and any(t in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or + (reg_range(t) and reg_range(t)[0] == 's' and reg_range(t)[1] in self.masks) + for t in srcs): + # a lane count or a lane index: the one-lane model keeps only this lane's bit of a mask + raise Unsupported('%s of a lane mask' % base) # The table templates name their sources as {0}, {1}, ...; a short operand list would make # str.format raise IndexError, which the single-shader path records as a translator crash # rather than a refusal. The arity guards above cover the table entries that spell a count, so @@ -3316,10 +4480,7 @@ def src_sym(t): self.used_s.add(reg_range(srcs[absorbed])[1]) values = [t if i == absorbed else self.u(t) for i, t in enumerate(srcs)] expr = text.format(*values) - if shift_add: - # carry = bits shifted out of S0, or a wrap of the 32-bit sum; read before the destination is written - n = SHIFT_ADD[base] - self.set_scc('(%s >> %d) != 0 || (%s) < %s' % (values[0], 32 - n, expr, values[1])) + # LOCAL: s_lshlN_add_u32 keeps the local SOP2 lowering (SCC not modelled); upstream's SHIFT_ADD carry is not taken. if dname == 'm0': self.sym.pop('m0', None) self.emit('m0 = %s;' % expr) @@ -3343,6 +4504,9 @@ def src_sym(t): if scc: self.set_scc(scc.replace('$', var)) return None + if reg_range(dname) is None: + # vcc_hi, ttmp, flat_scratch and the other named halves are not modelled as a destination. + raise Unsupported('%s writes %s' % (base, dname)) d = reg_range(dname)[1] is_mask = pair or any(t in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or (reg_range(t) and reg_range(t)[0] == 's' and reg_range(t)[1] in self.masks) for t in srcs) and base.split('_')[1] in ('mov', 'and', 'or', 'xor', 'andn2', 'orn2', 'nand', 'nor', 'xnor', 'not', 'cselect') @@ -3354,8 +4518,8 @@ def src_sym(t): self.masks.discard(d) return None if base in SCALAR_CONST_FOLD: - # Constant operands give a known word, so a descriptor built from them (an inline sampler from - # s_movk_i32, s_bfm_b32, s_mov_b32 and s_brev_b32 into s[N:N+3]) is a constant descriptor. + # Constant operands give a known word, so a descriptor built from them (an inline sampler: s_movk_i32, + # s_bfm_b32 (op_s_bfm_b32), s_mov_b32, s_brev_b32 into s[N:N+3]) is a constant descriptor. def known(tok): r = reg_range(tok) if r and r[0] == 's' and r[1] == r[2]: @@ -3370,7 +4534,6 @@ def known(tok): if None not in operands: value = SCALAR_CONST_FOLD[base](*operands) & 0xffffffff self.set_s(d, '0x%08xu' % value, ('const', value)) - self.masks.discard(d) return None if base in ('s_mov_b64', 's_mov_b32') and srcs[0] in ('exec', 'exec_lo') and self.exec_known: self.set_s(d, 'exec') @@ -3390,17 +4553,7 @@ def known(tok): high_source = 's%d' % high if high is not None else srcs[0] high_uniform = (self.tracks_uniformity() and high != d and self.uniform_source(high_source)) - self.set_s(d, expr, scc=None if lane_complement else scc) - if base == 's_mov_b32' and srcs[0] in FLOATS and not is_mask: - # Keep the runtime SGPR assignment intact while letting const_words() read inline float patterns - # such as 0x40000000 (OPAQUE_BLACK, encoded as inline 244 / '2.0'). - self.__dict__.setdefault('float_const_s', {})[d] = fbits(FLOATS[srcs[0]]) - if lane_complement: - # The guest SCC is (the whole complemented word != 0), which the bits of every other lane decide (an - # idle lane's bit is set). It is not emitted: translate() refuses a program that can read it. - self.scc_effect = 'a lane-mask complement' - if self.tracks_uniformity(): - self.scc_uniform = False + self.set_s(d, expr, scc=scc) if is_mask: self.masks.add(d) if pair and base != 's_mov_b64': @@ -3423,19 +4576,21 @@ def op_s_and_saveexec_b64(self, ops, mods, text='exec & {0}'): if not dst or dst[0] != 's': raise Unsupported('saveexec destination %s' % ops[0]) d = dst[1] - src_reg = reg_range(ops[1]) - src = ops[1] if not src_reg else 's%d' % src_reg[1] - # S0 is read at issue, before D is written (RDNA 2 ISA SOP1 S_AND_SAVEEXEC: D = EXEC; EXEC = S0 & EXEC). - # With D == S0 (s_and_saveexec_b64 s[6:7], s[6:7]) writing D first would make the new exec exec & exec, so - # S0 is copied to the scratch word w before D is written. - if src_reg and src_reg[0] == 's' and src_reg[1] == d: - self.emit('w = %s;' % self.u(src)) - value = 'w' + src = ops[1] if not reg_range(ops[1]) else 's%d' % reg_range(ops[1])[1] + # S0 is read before D is written: with D == S0 (s_and_saveexec_b64 s[6:7], s[6:7]) the new exec is + # exec & old S0, not exec & exec (RDNA 2 ISA SOP1: D = EXEC; EXEC = S0 & EXEC, with S0 the value read at issue). + if reg_range(ops[1]) and reg_range(ops[1])[0] == 's' and reg_range(ops[1])[1] == d: + self.uses_xsave = True + self.lines.append('xsave = %s;' % self.u(src)) # every lane: a temporary read only below + value = 'xsave' else: value = self.u(src) self.set_s(d, 'exec') self.masks.add(d) - self.set_exec_scc(text.format(value)) + self.exec_known = False + self.emit('exec = (%s) & 1; scc = exec != 0;' % text.format(value)) + if hasattr(self, 'scc_uniform'): + self.scc_uniform = False op_s_and_saveexec_b32 = op_s_and_saveexec_b64 @@ -3447,6 +4602,52 @@ def op_s_or_saveexec_b64(self, ops, mods): def op_s_andn2_saveexec_b64(self, ops, mods): self.op_s_and_saveexec_b64(ops, mods, '{0} & ~exec') + def scalar_carry(self, base, ops, mods=()): + """s_add_u32 / s_sub_u32 whose SCC can reach a reader (carry_scc_writers), and s_addc_u32 / s_subb_u32. + + AMD RDNA 2 ISA SOP2: S_ADD_U32 D = S0 + S1, SCC = carry out (the 33rd bit); S_SUB_U32 D = S0 - S1, SCC = + borrow (S1 > S0 unsigned); S_ADDC_U32 D = S0 + S1 + SCC, SCC = carry out; S_SUBB_U32 D = S0 - S1 - SCC, SCC + = borrow (S1 + SCC > S0 as 33-bit values). With D = S0 + S1 + c wrapped to 32 bits, the carry is D < S0 for + c = 0 and D <= S0 for c = 1; with D = S0 - S1 - c the borrow is S0 < S1 for c = 0 and S0 <= S1 for c = 1. + Both results go through q, so D may be a source. Plain numbers only: a descriptor word, pointer or lane mask + operand is refused (the calculated-PC proof absorbs its own address arithmetic before this point).""" + if mods: + raise Unsupported('%s with %s' % (base, ' '.join(mods))) + if len(ops) != 3: + raise Unsupported('%s with %d operands, expected 3' % (base, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('%s destination %s' % (base, ops[0])) + for tok in ops[1:]: + r = reg_range(tok) + if r and (r[0] != 's' or r[1] != r[2] or r[1] > 105): + raise Unsupported('%s source %s' % (base, tok)) + if tok in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi', 'm0', 'src_scc') or ( + r and (r[1] in self.masks or (self.sym.get(r[1]) or ('',))[0] in ('desc', 'descnum', 'ptr', 'ptrhi'))): + raise Unsupported('%s on %s (not a plain number)' % (base, tok)) + a, b = self.u(ops[1]), self.u(ops[2]) + carry_in = base in ('s_addc_u32', 's_subb_u32') + c = '(scc ? 1u : 0u)' if carry_in else '0u' + if base.startswith('s_add'): + value = '%s + %s + %s' % (a, b, c) if carry_in else '%s + %s' % (a, b) + out = '(scc ? q.x <= q.y : q.x < q.y)' if carry_in else 'q.x < q.y' + else: + value = '%s - %s - %s' % (a, b, c) if carry_in else '%s - %s' % (a, b) + out = '(scc ? %s <= %s : %s < %s)' % ('q.y', b, 'q.y', b) if carry_in else 'q.y < %s' % b + uniform = self.scalar_expr_uniform(value) if self.tracks_uniformity() else None + self.uses_q = True + # q.y holds S0 and q.x the result; the carry/borrow reads the old SCC before it is replaced. + self.emit('q = uint2(%s, %s);' % (value, a)) + self.set_scc(out, proof=value) + self.set_s(dst[1], 'q.x', uniform=uniform) + return None + + def op_s_addc_u32(self, ops, mods): + return self.scalar_carry('s_addc_u32', ops, mods) + + def op_s_subb_u32(self, ops, mods): + return self.scalar_carry('s_subb_u32', ops, mods) + def op_s_andn2_wrexec_b64(self, ops, mods): if len(ops) != 2: raise Unsupported('wrexec with %d operands, expected 2' % len(ops)) @@ -3461,55 +4662,65 @@ def op_s_andn2_wrexec_b64(self, ops, mods): op_s_andn2_wrexec_b32 = op_s_andn2_wrexec_b64 - def scalar_accumulate(self, base, ops, mods): - """s_addk_i32 / s_mulk_i32: D = D op signext(SIMM16), the destination is also the source. + # SOPK s_addk_i32 / s_mulk_i32: D = D op sext(simm16). LLVM's SIShrinkInstructions forms them from s_add_i32 / + # s_mul_i32 only when isInt<16> of the constant, so the immediate is signed. s_addk_i32 defines SCC (signed + # overflow, not modelled: see SCC_UNMODELLED); s_mulk_i32 does not. + def sopk_arith(self, ops, op): + d = reg_range(ops[0]) + if not d or d[0] != 's' or d[1] != d[2]: + raise Unsupported('SOPK destination %s' % ops[0]) + imm = int(ops[1], 0) & 0xffff + imm = (imm - 0x10000 if imm & 0x8000 else imm) & 0xffffffff + self.masks.discard(d[1]) + self.set_s(d[1], '%s %s 0x%08xu' % (self.S(d[1]), op, imm)) + + # s_bitset0_b32 / s_bitset1_b32: D[S0[4:0]] = 0 / 1, the other bits of D kept (AMD RDNA 2 ISA SOP1; LLVM + # SOPInstructions.td defines them with D tied as an input and no SCC def). A lane mask or symbolic D is refused. + def bitset(self, ops, one): + d = reg_range(ops[0]) + if not d or d[0] != 's' or d[1] != d[2] or d[1] in self.masks: + raise Unsupported('s_bitset%d_b32 destination %s' % (one, ops[0])) + bit = '(1u << (%s & 31))' % self.u(ops[1]) + old = self.S(d[1]) + expr = '%s | %s' % (old, bit) if one else '%s & ~%s' % (old, bit) + a, b = self.is_const(d[1]), self.is_const(reg_range(ops[1])[1]) if reg_range(ops[1]) else None + if b is None and re.fullmatch(r'(0x[0-9a-f]+|\d+)', ops[1]): + b = int(ops[1], 0) + if a is not None and b is not None: # both known: keep the constant (descriptor words are built this way) + value = (a | 1 << (b & 31)) if one else (a & ~(1 << (b & 31))) + self.set_s(d[1], '0x%08xu' % (value & 0xffffffff), ('const', value & 0xffffffff)) + return + self.set_s(d[1], expr) - RDNA 2 ISA 12.2 (SOPK 15, 16): addk sets SCC to the signed overflow of the sum, mulk leaves SCC - alone. LLVM 15 SOPInstructions.td declares Defs = [SCC] for both, so after mulk the SCC proof is - dropped (the emitted scc keeps its value, which is the ISA meaning). - """ - if mods or len(ops) != 2: - raise Unsupported('%s with %d operands' % (base, len(ops))) - dst = reg_range(ops[0]) - if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: - raise Unsupported('%s destination %s' % (base, ops[0])) - if not re.fullmatch(r'0x[0-9a-f]{1,4}', ops[1]): - raise Unsupported('%s immediate %s' % (base, ops[1])) - d = dst[1] - # D is read before it is written: refuse a mask or descriptor source while the old state is intact. - if d in self.masks or self.sym.get(d, ('',))[0] == 'execcopy': - raise Unsupported('%s on a lane mask' % base) - sym = self.sym.get(d) - if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): - raise Unsupported('%s on %s data' % (base, sym[0])) - simm = int(ops[1], 16) - imm = (simm - 0x10000 if simm & 0x8000 else simm) & 0xffffffff - imm_text = '0x%08xu' % imm - old = self.S(d) - add = base == 's_addk_i32' - result = '%s %s %s' % (old, '+' if add else '*', imm_text) - if add: - # signed overflow: the operands share a sign that the sum does not keep - overflow = '((%s ^ (%s)) & ~(%s ^ %s) & 0x80000000u) != 0u' % (old, result, old, imm_text) - if sym and sym[0] == 'const': - total = (sym[1] + imm) & 0xffffffff - overflow = 'true' if ((sym[1] ^ total) & ~(sym[1] ^ imm) & 0x80000000) else 'false' - self.set_scc(overflow) - elif self.tracks_uniformity(): - self.scc_uniform = False - if sym and sym[0] == 'const': - value = (sym[1] + imm if add else sym[1] * imm) & 0xffffffff - self.set_s(d, '0x%08xu' % value, ('const', value)) + def op_s_flbit_i32_b32(self, ops, mods): + if len(ops) != 2 or mods: + raise Unsupported('s_flbit_i32_b32 operands') + dst, src = ops + r = reg_range(src) + if self.is_lane_mask(src) or (r and (r[0] != 's' or r[1] != r[2] or r[1] > 105)): + raise Unsupported('s_flbit_i32_b32 source %s' % src) + d = reg_range(dst) + if dst != 'm0' and (not d or d[0] != 's' or d[1] != d[2] or d[1] > 105): + raise Unsupported('s_flbit_i32_b32 destination %s' % dst) + word = self.u(src) + expr = VEC_U['v_ffbh_u32'][1].format(word) + if dst == 'm0': + self.sym.pop('m0', None) + self.emit('m0 = %s;' % expr) else: - self.set_s(d, result) - self.masks.discard(d) - return None + self.set_s(d[1], expr) + + def op_s_bitset0_b32(self, ops, mods): + self.bitset(ops, 0) + + def op_s_bitset1_b32(self, ops, mods): + self.bitset(ops, 1) def op_s_addk_i32(self, ops, mods): - return self.scalar_accumulate('s_addk_i32', ops, mods) + self.sopk_arith(ops, '+') def op_s_mulk_i32(self, ops, mods): - return self.scalar_accumulate('s_mulk_i32', ops, mods) + self.sopk_arith(ops, '*') def op_s_cselect_b32(self, ops, mods): self.scalar_select(ops, False) @@ -3564,22 +4775,20 @@ def scalar_select(self, ops, pair): if pair and 'm0' in low: raise Unsupported('64-bit scalar operand m0') expr = 'scc ? %s : %s' % (self.u(low[1]), self.u(low[2])) - if low[0] == 'm0': - self.sym.pop('m0', None) - self.emit('m0 = %s;' % expr) - return + # LOCAL: s_cselect into m0 stays refused (startup_cselect_vcc_lo_check); upstream's m0 select is not taken. if low[0] in ('exec', 'vcc', 'exec_lo', 'vcc_lo'): - # In wave32, exec_lo and vcc_lo hold the whole lane mask, as the generic scalar path reads them. - mask = 'exec' if low[0].startswith('exec') else 'vcc' - if mask == 'exec': + # wave32: vcc_lo / exec_lo are the whole lane mask, as in the generic scalar path + var = low[0][:4].rstrip('_') if low[0].startswith('exec') else 'vcc' + if var == 'exec': self.exec_known = False - self.emit('%s = (%s) & 1;' % (mask, expr)) + self.emit('%s = (%s) & 1;' % (var, expr)) return - r = reg_range(low[0]) - if not r or r[0] != 's': + if not reg_range(low[0]) or reg_range(low[0])[0] != 's': raise Unsupported('s_cselect into %s' % low[0]) - d = r[1] + d = reg_range(low[0])[1] self.set_s(d, '(%s) & 1' % expr if pair else expr) + if not pair and {low[1], low[2]} <= {'-1', '0'} and hasattr(self, 'splat'): + self.splat.add(d) if pair: self.masks.add(d) self.set_s(d + 1, '0u') @@ -3614,80 +4823,50 @@ def const_soffset(self, tok): return None def op_s_load_dwordx4(self, ops, mods, count=4): - imm = smem_mods(mods) - if len(ops) != 3: - raise Unsupported('s_load with %d operands' % len(ops)) + smem_imm_refuse('s_load', ops, mods) dst, base = reg_range(ops[0]), reg_range(ops[1]) - if not dst or dst[0] != 's' or dst[2] - dst[1] + 1 != count or dst[2] > 105: - raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) - if not base or base[0] != 's' or base[2] - base[1] != 1 or base[2] > 105: - raise Unsupported('s_load base %s' % ops[1]) - # A loaded descriptor or word is not a lane mask; some forms below only record a symbol, not set_s. for n in range(dst[1], dst[2] + 1): - getattr(self, 'masks', set()).discard(n) + getattr(self, 'masks', set()).discard(n) # a loaded descriptor or value is not a lane mask (some paths below skip set_s) p = self.sym.get(base[1]) if not p or p[0] != 'ptr': raise Unsupported('s_load through s%d holding %s' % (base[1], p)) - # 'off' names no offset operand at all, so the byte offset is zero, as for the literal 0. - token = smem_offset(ops[2]) - known = self.const_soffset(token) if p[1] != ('smpheap',) else None - if known is not None: - # A register offset that holds a known constant (s_movk before the load) is that literal byte - # offset; the modifier adds to it. This reaches descriptors in a bindless heap (#1723). - total = known + (imm or 0) - if total > 0xfffff: - raise Unsupported('SMEM register offset %#x' % total) - token, imm = str(total), None - if re.fullmatch(r'-?(?:0[xX][0-9a-fA-F]+|\d+)', token): - off = int(token, 0) - if off < 0 or off > 0xfffff: - raise Unsupported('SMEM immediate offset %s' % ops[2]) - if imm is not None: - raise Unsupported('SMEM literal offset %s with offset:%#x' % (ops[2], imm)) - if p[1][0] == 'root': - buf = self.pipe.resource((p[1], None), 'buf') - for i in range(count): - self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, off + 4 * i)) - return - # The pointer symbol does not record an addend or a rewritten high word, so two loads through such a - # pointer may read different words under the same (source, offset). In a compute or vertex stage (the - # stages that accept a raw descriptor conversion before a store) those loads are told apart by the - # offset of the s_load; loads through the untouched pair keep one identity. - # A 32-bit table pointer carries a high word the program sets to a constant: loads through the same - # untouched low word and the same constant read the same words (tag -1 - constant). - hi = self.sym.get(base[1] + 1) - if getattr(self, 'kind', None) not in ('cs', 'vs') or (p == ('ptr', p[1]) and hi == ('ptrhi', p[1])): - load = () - elif p == ('ptr', p[1]) and hi and hi[0] == 'const' and len(hi) == 2: - load = (-1 - hi[1],) - else: - load = (self.pc,) + if p[1] == ('resheap',) and 'heap' in getattr(self.pipe, 'features', ()) and count in (4, 8) and not mods: + k = len(self.pipe.heapvars) + self.pipe.heapvars.append(None) + self.used_h.add(k) + self.emit('h%d = %s;' % (k, self.u(ops[2]) if reg_range(ops[2]) else '0x%xu' % (int(ops[2], 0) & 0xffffffff))) for i in range(count): - self.sym[dst[1] + i] = ('desc', p[1], off, i) + load + self.sym[dst[1] + i] = ('desc', ('heapdyn', k), 0, i) return - if p[1] == ('smpheap',): - if self.pipe.sampler_heap and count == 4: + try: + # 'off' names no offset operand at all, so the byte offset is zero, as for the literal 0. + off = int(smem_offset(ops[2]), 0) + except ValueError: + if p[1] == ('smpheap',) and self.pipe.sampler_heap and count == 4: # A sampler picked at run time from the sampler heap: keep the byte offset in the # first destination register; image() indexes the heap table with it. d = dst[1] self.used_s.add(d) - expr = self.smem_soffset(token) - if imm: - expr = '%s + %d' % (expr, imm) - self.emit('s%d = %s;' % (d, expr)) + self.emit('s%d = %s;' % (d, self.u(ops[2]))) for i in range(count): self.sym[d + i] = ('smpheap', d, i) return - self.smem_soffset(token, record_use=False) - if count != 4: - raise Unsupported('s_load of %d dwords from %s' % (count, p[1])) - # Shortcut (default unless X2W_SAMPLER_HEAP=1): a fixed default sampler. + if p[1] == ('smpheap',): + # Shortcut (default unless X2W_SAMPLER_HEAP=1): a fixed default sampler. + for i in range(count): + self.sym[dst[1] + i] = ('const', 0) + self.pipe.notes.add('dynamic sampler index replaced by a default sampler') + return + raise Unsupported('s_load with a register offset through %s' % (p[1],)) + if p[1][0] == 'root': + buf = self.pipe.resource((p[1], None), 'buf') for i in range(count): - # Never assigned at run time (the third field says so): a join that reads it refuses (run_time_symbol). - self.sym[dst[1] + i] = ('const', 0, 'unassigned') - self.pipe.notes.add('dynamic sampler index replaced by a default sampler') + self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, off + 4 * i)) return - raise Unsupported('s_load with a register offset through %s' % (p[1],)) + for i in range(count): + self.sym[dst[1] + i] = ('desc', p[1], off, i) + for i in range(count): + self.tw_load_shadow(dst[1] + i) def op_s_bfm_b32(self, ops, mods): """Fold constant bitfield masks: titles build inline sampler words with them.""" @@ -3720,91 +4899,36 @@ def op_s_bfm_b32(self, ops, mods): self.set_s(d, '(((1u << (%s & 31)) - 1) << (%s & 31))' % (self.u(ops[1]), self.u(ops[2]))) return None - def scalar_const(self, tok): - """Value of a 32-bit scalar source that is known at translation time, else None.""" - r = reg_range(tok) - if r: - return self.is_const(r[1]) if r[0] == 's' and r[1] == r[2] else None - try: - return int(tok, 0) & 0xffffffff - except ValueError: - return None - - def scalar_wide_op(self, name, ops, mods, wide_src, wide_dst, helper, signed=None): - """SOP2 shifts and bitfield extracts with a 64-bit source and/or result. - - D = f(S0, S1) with S1 a 32-bit word; SCC = (D != 0). Every source is read before any destination - register is written, so an overlapping destination cannot feed a half-written value back.""" - if mods or len(ops) != 3: - raise Unsupported('%s with %d operands and modifiers %s' % (name, len(ops), mods)) - dst = reg_range(ops[0]) - width = 1 + wide_dst - if (not dst or dst[0] != 's' or dst[2] != dst[1] + wide_dst or dst[2] > 105 - or (wide_dst and dst[1] % 2)): - raise Unsupported('%s destination %s' % (name, ops[0])) - s1 = reg_range(ops[2]) - if ('m0' in ops[1:] or any(self.is_lane_mask(t) for t in ops[1:]) - or any(r[0] == 's' and any(w in self.masks for w in range(r[1], r[2] + 1)) - for r in map(reg_range, ops[1:]) if r) or ops[2] in FLOATS or ops[1] in FLOATS - or (s1 and (s1[0] != 's' or s1[1] != s1[2] or s1[1] > 105))): - raise Unsupported('%s source %s' % (name, ', '.join(ops[1:]))) - if wide_src: - r0 = reg_range(ops[1]) - if r0 and r0[0] != 's': - raise Unsupported('%s source %s' % (name, ops[1])) - low, high = self.i64_words(ops[1]) - known = [self.scalar_const('s%d' % r0[1]), self.scalar_const('s%d' % r0[2])] if r0 else [ - int(low[:-1]), int(high[:-1])] - else: - low, high = self.u(ops[1]), None - known = [self.scalar_const(ops[1])] - amount = self.u(ops[2]) - amount_known = self.scalar_const(ops[2]) - d = dst[1] - self.masks.difference_update(range(d, d + width)) - if None not in known and amount_known is not None: - x = known[0] | (known[1] << 32 if wide_src else 0) - value = scalar_wide_fold(helper, x, amount_known, signed) - for i in range(width): - word = (value >> (32 * i)) & 0xffffffff - self.set_s(d + i, '0x%08xu' % word, ('const', word)) - self.set_scc('true' if value else 'false') - return None - uniform = (self.tracks_uniformity() - and self.scalar_expr_uniform('%s %s %s' % (low, high or '', amount))) - sg = '' if signed is None else ', %du' % (1 if signed else 0) - if wide_dst: - call = '%s(%s, %s, %s%s)' % (helper, low, high if wide_src else '0u', amount, sg) - self.emit('{ uint2 t = %s; s%d = t.x; s%d = t.y; scc = (t.x | t.y) != 0u; }' % (call, d, d + 1)) - else: - self.emit('{ uint t = %s(%s, %s%s); s%d = t; scc = t != 0u; }' % (helper, low, amount, sg, d)) - for r in range(d, d + width): - self.sym.pop(r, None) - self.used_s.add(r) - if self.tracks_uniformity(): - (self.varying_s.discard if uniform else self.varying_s.add)(r) - self.scc_effect = 'emitted' - if self.tracks_uniformity(): - self.scc_uniform = uniform + def op_s_bfm_b64(self, ops, mods): + """D[63:0] = ((1 << S0[5:0]) - 1) << S1[5:0]; SCC unchanged. Folded when both counts are constant.""" + d = reg_range(ops[0])[1] + vals = [] + for o in ops[1:3]: + r = reg_range(o) + if r and r[0] == 's': + vals.append(self.is_const(r[1])) + else: + try: + vals.append(int(o, 0)) + except ValueError: + vals.append(None) + if None in vals: + raise Unsupported('s_bfm_b64 with a run-time count') + value = (((1 << (vals[0] & 63)) - 1) << (vals[1] & 63)) & 0xffffffffffffffff + self.masks.discard(d) + self.set_s(d, '0x%08xu' % (value & 0xffffffff), ('const', value & 0xffffffff)) + self.set_s(d + 1, '0x%08xu' % (value >> 32), ('const', value >> 32)) return None - def op_s_lshl_b64(self, ops, mods): - return self.scalar_wide_op('s_lshl_b64', ops, mods, True, True, 'shl64') - - def op_s_lshr_b64(self, ops, mods): - return self.scalar_wide_op('s_lshr_b64', ops, mods, True, True, 'shr64u') - - def op_s_ashr_i64(self, ops, mods): - return self.scalar_wide_op('s_ashr_i64', ops, mods, True, True, 'shr64i') + def bitcmp(self, ops, want): + """s_bitcmp{0,1}_b32: SCC = (S0[S1[4:0]] == want); no register is written.""" + self.emit('scc = ((%s >> (%s & 31u)) & 1u) == %du;' % (self.u(ops[0]), self.u(ops[1]), want)) - def op_s_bfe_i32(self, ops, mods): - return self.scalar_wide_op('s_bfe_i32', ops, mods, False, False, 'bfe32', True) + def op_s_bitcmp0_b32(self, ops, mods): + self.bitcmp(ops, 0) - def op_s_bfe_u64(self, ops, mods): - return self.scalar_wide_op('s_bfe_u64', ops, mods, True, True, 'bfe64', False) - - def op_s_bfe_i64(self, ops, mods): - return self.scalar_wide_op('s_bfe_i64', ops, mods, True, True, 'bfe64', True) + def op_s_bitcmp1_b32(self, ops, mods): + self.bitcmp(ops, 1) def op_s_load_dwordx8(self, ops, mods): self.op_s_load_dwordx4(ops, mods, 8) @@ -3819,35 +4943,31 @@ def op_s_load_dword(self, ops, mods): self.op_s_load_dwordx4(ops, mods, 1) def op_s_buffer_load_dword(self, ops, mods, count=1): - imm = smem_mods(mods) - if len(ops) != 3: - raise Unsupported('s_buffer_load with %d operands' % len(ops)) + smem_imm_refuse('s_buffer_load', ops, mods) dst = reg_range(ops[0]) if not dst or dst[0] != 's' or dst[2] - dst[1] + 1 != count or dst[2] > 105: raise Unsupported('s_buffer_load destination %s for %d dwords' % (ops[0], count)) buf = self.pipe.resource(self.descriptor(ops[1]), 'buf') token = smem_offset(ops[2]) - is_lit = bool(re.fullmatch(r'-?(?:0[xX][0-9a-fA-F]+|\d+)', token)) - if is_lit: - val = int(token, 0) - if val < 0 or val > 0xfffff: - raise Unsupported('SMEM immediate offset %s' % ops[2]) - if imm is not None: - raise Unsupported('SMEM literal offset %s with offset:%#x' % (ops[2], imm)) - offset = self.u(token) - extra = 0 - else: - offset = self.smem_soffset(token) - extra = imm or 0 - sreg = reg_range(token) - if sreg and offset == ('s%d' % sreg[1]) and dst[1] <= sreg[1] < dst[2]: - self.emit('a = %s;' % offset) - offset = 'a' - # All words use the original offset, even when a destination overwrites its register. - uniform = self.tracks_uniformity() and self.uniform_source(token) - for i in range(count): - self.set_s(dst[1] + i, '%s.Load(%s + %d)' % (buf, offset, extra + 4 * i), uniform=uniform) - if is_lit: + offset = self.u(token) + # An SGPR offset can carry an immediate as well (disasm_rdna2 prints "s4 offset:0x10"): the byte offset is + # the sum. glc/dlc are cache policy. Anything else is refused. + extra = 0 + for m in mods: + if m.startswith('offset:'): + extra += int(m[7:], 0) + elif m not in ('glc', 'dlc'): + raise Unsupported('s_buffer_load modifier %s' % m) + # Every word's address uses the offset register as it was before the load, so when the destination range + # holds that register it is written last (s_buffer_load_dwordx2 s[4:5], s[16:19], s4). + order = list(range(count)) + r = reg_range(token) + if r and r[0] == 's' and dst[1] <= r[1] < dst[1] + count: + order.remove(r[1] - dst[1]) + order.append(r[1] - dst[1]) + for i in order: + self.set_s(dst[1] + i, '%s.Load(%s + %d)' % (buf, offset, extra + 4 * i)) + if not mods and re.fullmatch(r'0x[0-9a-f]+|\d+', token): self.sym[dst[1] + i] = ('fixed_buffer_word',) def op_s_buffer_load_dwordx2(self, ops, mods): @@ -3862,59 +4982,57 @@ def op_s_buffer_load_dwordx8(self, ops, mods): def op_s_buffer_load_dwordx16(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 16) - def buffer_address(self, ops, mods): - # MUBUF and MTBUF share the same address calculation: optional index * stride (idxen), - # optional byte VGPR offset (offen), scalar byte offset (soffset) and 12-bit immediate - # offset. Cache-policy flags (glc, slc, dlc) do not change the loaded bytes; lds, tfe - # and any other modifier change the destination or operand layout and are refused first. - offset = 0 - for m in mods: - if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): - offset += int(m[7:], 0) - elif m not in ('idxen', 'offen', 'glc', 'slc', 'dlc'): - raise Unsupported('buffer modifier %s' % m) + @staticmethod + def check_buffer_load_arity(ops, mods): + for modifier in mods: + if modifier in ('lds', 'tfe', 'lwe'): + raise Unsupported('buffer modifier %s' % modifier) if len(ops) != 4: raise Unsupported('buffer load with %d operands, expected 4' % len(ops)) + + def buffer_address(self, ops, mods): + Stage.check_buffer_load_arity(ops, mods) key = self.descriptor(ops[2]) - buf = self.pipe.resource(key, 'buf') - soffset = None - if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): - offset += int(ops[3], 0) + rw = key in getattr(self.pipe, 'rw_keys', ()) or key in getattr(self.pipe, 'uavs', {}) + if rw: + # A buffer this program also stores to: read through its UAV (in place, so the program sees its own + # stores), at the same uavbase-shifted address the stores use. No stride source for a UAV. + if 'idxen' in mods: + raise Unsupported('indexed load through a buffer the program stores to') + buf = self.pipe.uav(key) else: - sreg = reg_range(ops[3]) - if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: - raise Unsupported('buffer soffset %s' % ops[3]) - soffset = self.S(sreg[1]) + buf = self.pipe.resource(key, 'buf') + soff = ops[3] + if re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', soff): + offset, extra = int(soff, 0), '' + else: + offset, extra = 0, '%s + ' % self.u(soff) # an SGPR soffset adds its value + for m in mods: + if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): + offset += int(m[7:], 0) + if rw: + extra = 'ud%d + %s' % (self.pipe.ud(('uavbase', int(buf[1:]))), extra) idxen, offen = 'idxen' in mods, 'offen' in mods + if idxen or offen: + regs = reg_range(ops[1]) + mode = 'idxen offen' if idxen and offen else 'idxen' if idxen else 'offen' + if not regs or regs[0] != 'v' or regs[2] > 255 or regs[2] - regs[1] != int(idxen and offen): + raise Unsupported('buffer vaddr %s for %s' % (ops[1], mode)) + elif ops[1] != 'off': + raise Unsupported('buffer vaddr %s without idxen or offen' % ops[1]) terms = [] - if idxen and offen: - if key in self.pipe.modified: - raise Unsupported('indexed load through a modified descriptor') - r = reg_range(ops[1]) - if not r or r[0] != 'v' or r[2] - r[1] != 1 or r[2] > 255: - raise Unsupported('buffer vaddr %s for idxen offen' % ops[1]) - stride = self.pipe.ud(('stride', self.pipe.resources[key]['index'])) - terms.append('%s * ud%d' % (self.u('v%d' % r[1]), stride)) - terms.append(self.u('v%d' % r[2])) - elif idxen: + if idxen: if key in self.pipe.modified: raise Unsupported('indexed load through a modified descriptor') - r = reg_range(ops[1]) - if not r or r[0] != 'v' or r[1] != r[2] or r[1] > 255: - raise Unsupported('buffer vaddr %s for idxen' % ops[1]) - stride = self.pipe.ud(('stride', self.pipe.resources[key]['index'])) - terms.append('%s * ud%d' % (self.u(ops[1]), stride)) - elif offen: - r = reg_range(ops[1]) - if not r or r[0] != 'v' or r[1] != r[2] or r[1] > 255: - raise Unsupported('buffer vaddr %s for offen' % ops[1]) - terms.append(self.u(ops[1])) - elif ops[1] != 'off': - raise Unsupported('buffer vaddr %s without idxen or offen' % ops[1]) - if soffset is not None: - terms.append(soffset) - terms.append('%d' % offset) - return buf, ' + '.join(terms) + if key[0][0] == 'heapdyn': + stride = 'x2w_vstride(h%d)' % key[0][1] + else: + stride = 'ud%d' % self.pipe.ud(('stride', self.pipe.resources[key]['index'])) + terms.append('%s * %s' % (self.u('v%d' % regs[1]), stride)) + if offen: + terms.append(self.u('v%d' % regs[2])) + address = ' + '.join(terms + [str(offset)]) + return buf, extra + address def op_buffer_load_dword(self, ops, mods, count=1): # ops[0] is read before buffer_address() can refuse a short operand list, so an instruction with no @@ -3937,279 +5055,49 @@ def op_buffer_load_dwordx3(self, ops, mods): def op_buffer_load_dwordx4(self, ops, mods): self.op_buffer_load_dword(ops, mods, 4) - def op_buffer_store_vs(self, ops, mods, count): - # Vertex-stage store in the `off` form: scalar byte offset plus the 12-bit immediate, through a - # descriptor read from a fixed root-table slot, written to a RWByteAddressBuffer (issue #1723). - # The manifest carries the `uav` line the runtime binds; a descriptor may not also be loaded. - if self.kind != 'vs': - raise Unsupported('buffer store in the %s stage' % self.kind) - offset = 0 - for m in mods: - if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): - offset += int(m[7:], 0) - else: - raise Unsupported('buffer store modifier %s' % m) - if len(ops) != 4 or ops[1] != 'off': - raise Unsupported('buffer store without the off address form') - src = reg_range(ops[0]) - if not src or src[0] != 'v' or src[2] - src[1] != count - 1 or src[2] > 255: - raise Unsupported('buffer store data %s' % ops[0]) - key = self.descriptor(ops[2]) - if key[0][0] != 'table' or key[1] is None: - raise Unsupported('buffer store through %s' % (key,)) - if key in self.pipe.modified: - # Only the modifications a compute store accepts: the stride clear or the structured-to-raw conversion. - self.store_descriptor(ops[2], 4, 'buffer store', stride0_ok=True, raw_conversion_ok=True) - if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): - offset += int(ops[3], 0) - soffset = '' - if offset % 4: - raise Unsupported('buffer store at unaligned byte offset %d' % offset) - else: - sreg = reg_range(ops[3]) - if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: - raise Unsupported('buffer soffset %s' % ops[3]) - if offset % 4: - raise Unsupported('buffer store at unaligned immediate offset %d' % offset) - soffset = '%s + ' % self.S(sreg[1]) - uav = self.pipe.uav(key, 'raw') - words = ', '.join(self.u('v%d' % n) for n in range(src[1], src[2] + 1)) - store = '%s.Store%s(a, %s);' % (uav, '' if count == 1 else str(count), 'uint%d(%s)' % (count, words) if count > 1 else words) - # Store* needs a multiple of four: the immediate is checked above; a register offset is rounded down. - self.emit('a = (%s%d) & 0xfffffffcu;' % (soffset, offset) if soffset else 'a = %d;' % offset) - self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) - - def store_descriptor(self, tok, words, what, stride0_ok=False, raw_conversion_ok=False): - """Resource key for a single loaded descriptor or a proven raw transformation of it.""" - rsrc = reg_range(tok) - first = self.sym.get(rsrc[1]) if rsrc and rsrc[0] == 's' and rsrc[2] - rsrc[1] == words - 1 else None - if not first or first[0] != 'desc' or first[1][0] != 'table' or first[2] is None or first[3] % 4: - raise Unsupported('%s through %s holding %s' % (what, tok, first)) - key = desc_key(first) - loaded = tuple(desc_word(first, first[3] + k) for k in range(words)) - actual = tuple(self.sym.get(rsrc[1] + k) for k in range(words)) - valid = names_one_value(first) and actual == loaded - if names_one_value(first) and stride0_ok and words == 4: - cleared = loaded[1] + ('stride0',) - valid = valid or actual == (loaded[0], cleared, *loaded[2:]) - if not valid and raw_conversion_ok: - valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',)) - if (not valid or key in getattr(self.pipe, 'other_modified', ()) - or (key in self.pipe.modified and not stride0_ok)): - raise Unsupported('%s through a modified descriptor' % what) - return key - - def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=False, allow_scalar_address=False, - raw_conversion_ok=False): - """Validate a fixed-table raw UAV descriptor, data range, byte address, and 4-byte alignment.""" - offset = 0 - glc = False - for m in mods: - if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): - offset += int(m[7:], 0) - elif m == 'glc' and allow_glc: - glc = True - elif m != 'offen': - raise Unsupported('%s modifier %s' % (kind_label, m)) - offen = 'offen' in mods - if len(ops) != 4 or (not offen and not (allow_scalar_address and glc and ops[1] == 'off')): - raise Unsupported('%s without the offen address form' % kind_label) - data = reg_range(ops[0]) - if not data or data[0] != 'v' or data[2] - data[1] != data_count - 1 or data[2] > 255: - raise Unsupported('%s data %s' % (kind_label, ops[0])) - if offen: - vaddr = reg_range(ops[1]) - if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: - raise Unsupported('%s vaddr %s for offen' % (kind_label, ops[1])) - key = self.store_descriptor(ops[2], 4, kind_label, stride0_ok=True, raw_conversion_ok=raw_conversion_ok) - terms = [self.u(ops[1])] if offen else [] - if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): - if not offen: - raise Unsupported('%s off requires a scalar register soffset' % kind_label) - offset += int(ops[3], 0) - else: - sreg = reg_range(ops[3]) - if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: - raise Unsupported('buffer soffset %s' % ops[3]) - terms.append(self.S(sreg[1])) - if offset % 4: - raise Unsupported('%s at unaligned immediate offset %d' % (kind_label, offset)) - terms.append(str(offset)) - return data, self.pipe.uav(key), '(%s) & 0xfffffffcu' % ' + '.join(terms), glc - - def op_buffer_store_dword(self, ops, mods, count=1): - # Compute-stage store in the offen form: per-lane byte VGPR plus the scalar offset and the 12-bit immediate, - # through a descriptor read from a fixed root-table slot, to a RWByteAddressBuffer (manifest `uav` line). - # Like the loads, this assumes a raw descriptor (no swizzle or stride). Out-of-range stores: assumes a future - # runtime sizes the view to the descriptor's range so both sides drop them; nothing binds or checks that yet. - if self.kind == 'vs': - return self.op_buffer_store_vs(ops, mods, count) - if self.kind != 'cs': - raise Unsupported('buffer_store_dword' + ('x%d' % count if count > 1 else '')) # the unknown-op refusal - src, uav, address, _ = self.raw_table_uav_store('buffer store', ops, mods, count, raw_conversion_ok=True) - words = [self.u('v%d' % n) for n in range(src[1], src[2] + 1)] - data = words[0] if count == 1 else 'uint%d(%s)' % (count, ', '.join(words)) - # Store* needs a multiple of four. As in #2059, the run-time part (VGPR and register soffset) is rounded down: - # an assumption that a dword access ignores the low two address bits, not a measurement. + def tbuffer(self, ops, mods, count): + dst = reg_range(ops[0]) + formats = [m for m in mods if m.startswith('format:')] + fmt = formats[0][8:-1] if formats else 'BUF_FMT_8_UNORM' # the disassembler omits the default format + buf, address = self.buffer_address(ops, [m for m in mods if not m.startswith('format:')]) + if buf.startswith('u'): + raise Unsupported('typed load through a buffer the program stores to') # ldu() takes a ByteAddressBuffer self.emit('a = %s;' % address) - store = '%s.Store%s(a, %s);' % (uav, '' if count == 1 else count, data) - self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) - - def buffer_atomic(self, name, ops, mods): - """Lower 32-bit compute MUBUF atomics with optional glc pre-atomic return.""" - if self.kind != 'cs': - raise Unsupported(name) - method, signed, is_sub, data_count = MUBUF_ATOMIC_OPS[name] - data, uav, address, glc = self.raw_table_uav_store( - 'buffer atomic', ops, mods, data_count, allow_glc=True, allow_scalar_address=name == 'buffer_atomic_add') - words = [self.u('v%d' % n) for n in range(data[1], data[2] + 1)] - self.emit('a = %s;' % address) - if not isinstance(getattr(self, 'used_atomic', None), set): - self.used_atomic = set() - if name == 'buffer_atomic_cmpswap': - # RDNA 2 puts replacement in vdata[0] and compare in vdata[1]; HLSL takes compare first. - if glc: - self.used_atomic.add('uint') - call = '%s.InterlockedCompareExchange(a, %s, %s, ao);' % (uav, words[1], words[0]) - else: - call = '%s.InterlockedCompareStore(a, %s, %s);' % (uav, words[1], words[0]) - elif name == 'buffer_atomic_swap': - # HLSL RWByteAddressBuffer.InterlockedExchange always requires an output operand. - self.used_atomic.add('uint') - call = '%s.InterlockedExchange(a, %s, ao);' % (uav, words[0]) - else: - arg = 'asint(%s)' % words[0] if signed else ('(0u - %s)' % words[0] if is_sub else words[0]) - if glc: - out_var = 'ai' if signed else 'ao' - self.used_atomic.add('int' if signed else 'uint') - call = '%s.Interlocked%s(a, %s, %s);' % (uav, method, arg, out_var) - else: - call = '%s.Interlocked%s(a, %s);' % (uav, method, arg) - self.emit(call if self.exec_known else 'if (exec & 1) %s' % call) - if glc: - self.set_v(data[1], 'asuint(ai)' if signed else 'ao') - - def _lds_general_barrier_ok(self): - """True when a compute stage uses dual/atomic LDS ops in straight-line code without legacy exchange ops.""" - ins = getattr(self, 'ins', None) - if not ins: - return False - has_general = False - for i, (_, _, name, _) in enumerate(ins): - op = re.sub(r'_e(32|64)$', '', name) - if op in LEGACY_LDS_EXCHANGE_OPS: - return False - if op in LDS_DUAL_ATOMIC_OPS: - has_general = True - if op.startswith(('s_branch', 's_cbranch', 's_setpc', 's_swappc')) or (op == 's_endpgm' and i + 1 < len(ins)): - return False - return has_general - - def _lds_require_alloc(self, base): - if getattr(self, 'pipe', None) is None: - raise Unsupported('%s needs pipeline metadata' % base) - words = self.pipe.lds_words - if not 0 < words <= 8192: - raise Unsupported('%s needs a nonzero LDS allocation of at most 32 KiB' % base) - self.uses_lds = True - return words * 4 - - def lds_dual(self, name, ops, mods): - """Lower 32-bit dual-offset and stride-64 LDS ops (ds_write2_b32, ds_write2st64_b32, ds_read2st64_b32).""" - if getattr(self, 'kind', None) != 'cs': - raise Unsupported(name) - is_write, stride = LDS_DUAL_OPS[name] - if is_write: - if (len(ops) != 3 or _lds_single(ops[0]) is None - or _lds_single(ops[1]) is None or _lds_single(ops[2]) is None): - raise Unsupported('%s needs three single VGPRs (addr, data0, data1)' % name) - else: - if len(ops) != 2 or _lds_pair(ops[0]) is None or _lds_single(ops[1]) is None: - raise Unsupported('%s needs a 2-VGPR pair and a byte address VGPR' % name) - # Reuse ds_read2_b32 modifier/aliasing validation (offset0/offset1 in 0..255, distinct, no gds/unknown mods). - off0, off1 = lds_byte_offsets('ds_read2_b32', mods) - scale = stride // 4 - off0, off1 = off0 * scale, off1 * scale - lds_bytes = self._lds_require_alloc(name) - exec_prefix = '' if self.exec_known else '(exec & 1) && ' - if is_write: - addr = self.u(ops[0]) - d0, d1 = self.u(ops[1]), self.u(ops[2]) - self.emit('a = %s;' % addr) - for off, val in ((off0, d0), (off1, d1)): - if off < lds_bytes: - self.emit('if (%s((a & 3u) == 0u) && a < %du) lds[(a + %du) >> 2] = %s;' - % (exec_prefix, lds_bytes - off, off, val)) - else: - dst = _lds_pair(ops[0]) - addr = self.u(ops[1]) - self.emit('a = %s;' % addr) - for idx, off in enumerate((off0, off1)): - if off < lds_bytes: - self.emit('w = 0u;') - self.emit('if (%s((a & 3u) == 0u) && a < %du) w = lds[(a + %du) >> 2];' - % (exec_prefix, lds_bytes - off, off)) - self.set_v(dst + idx, 'w') - else: - self.set_v(dst + idx, '0u') - - def lds_atomic(self, name, ops, mods): - """Lower 32-bit unsigned/bitwise compute LDS atomics (non-rtn and _rtn forms) onto groupshared uint lds[N].""" - if getattr(self, 'kind', None) != 'cs': - raise Unsupported(name) - method, has_rtn = LDS_ATOMIC_OPS[name] - if has_rtn: - if (len(ops) != 3 or _lds_single(ops[0]) is None - or _lds_single(ops[1]) is None or _lds_single(ops[2]) is None): - raise Unsupported('%s needs three single VGPRs (dst, addr, data)' % name) - dst, addr_op, data_op = _lds_single(ops[0]), ops[1], ops[2] - else: - if len(ops) != 2 or _lds_single(ops[0]) is None or _lds_single(ops[1]) is None: - raise Unsupported('%s needs two single VGPRs (addr, data)' % name) - dst, addr_op, data_op = None, ops[0], ops[1] - # Reuse ds_write_b32 single-offset validation (optional 16-bit byte offset, no gds/unknown mods). - off, = lds_byte_offsets('ds_write_b32', mods) - if off % 4: - raise Unsupported('%s requires 4-byte aligned immediate offset, got %d' % (name, off)) - lds_bytes = self._lds_require_alloc(name) - addr = self.u(addr_op) - data = self.u(data_op) - self.emit('a = %s;' % addr) - exec_prefix = '' if self.exec_known else '(exec & 1) && ' - if off < lds_bytes: - if has_rtn: - if not isinstance(getattr(self, 'used_atomic', None), set): - self.used_atomic = set() - self.used_atomic.add('uint') - self.emit('ao = 0u;') - self.emit('if (%s((a & 3u) == 0u) && a < %du) Interlocked%s(lds[(a + %du) >> 2], %s, ao);' - % (exec_prefix, lds_bytes - off, method, off, data)) - self.set_v(dst, 'ao') - else: - self.emit('if (%s((a & 3u) == 0u) && a < %du) Interlocked%s(lds[(a + %du) >> 2], %s);' - % (exec_prefix, lds_bytes - off, method, off, data)) - elif has_rtn: - self.set_v(dst, '0u') - - def op_buffer_store_dwordx2(self, ops, mods): - self.op_buffer_store_dword(ops, mods, 2) - - def op_buffer_store_dwordx3(self, ops, mods): - self.op_buffer_store_dword(ops, mods, 3) - - def op_buffer_store_dwordx4(self, ops, mods): - self.op_buffer_store_dword(ops, mods, 4) - - def tbuffer(self, ops, mods, count): - if not ops: - raise Unsupported('buffer load with 0 operands, expected 4') - dst = reg_range(ops[0]) - formats = [m for m in mods if m.startswith('format:')] - fmt = formats[0][8:-1] if formats else 'BUF_FMT_8_UNORM' # the disassembler omits the default format - buf, address = self.buffer_address(ops, [m for m in mods if not m.startswith('format:')]) - self.emit('a = %s;' % address) - self.load_format(fmt, buf, dst[1], count) + table = {'BUF_FMT_8_8_8_8_UNORM': ('ldu({0}, a)', ['U((w & 255) / 255.0)', 'U(((w >> 8) & 255) / 255.0)', 'U(((w >> 16) & 255) / 255.0)', 'U((w >> 24) / 255.0)']), + 'BUF_FMT_8_8_UNORM': ('ldu({0}, a)', ['U((w & 255) / 255.0)', 'U(((w >> 8) & 255) / 255.0)', '0u', 'U(1.0)']), + 'BUF_FMT_8_UNORM': ('ldu({0}, a)', ['U((w & 255) / 255.0)', '0u', '0u', 'U(1.0)']), + 'BUF_FMT_8_UINT': ('{0}.Load(a & ~3u) >> ((a & 3u) * 8u)', ['w & 255u', '0u', '0u', '1u']), + # integer fields as unsigned values; a missing component of an integer format reads 1 + 'BUF_FMT_8_8_8_8_UINT': ('ldu({0}, a)', ['w & 255u', '(w >> 8) & 255u', '(w >> 16) & 255u', 'w >> 24']), + 'BUF_FMT_16_16_UINT': ('ldu({0}, a)', ['w & 65535u', 'w >> 16', '0u', '1u']), + # x in bits [9:0], y [19:10], z [29:20], w [31:30] (the R10G10B10A2 layout, x lowest). ASSUMED from + # the GCN data-format naming; not checked against a source or a console readback. + 'BUF_FMT_2_10_10_10_UNORM': ('ldu({0}, a)', ['U((w & 1023) / 1023.0)', 'U(((w >> 10) & 1023) / 1023.0)', + 'U(((w >> 20) & 1023) / 1023.0)', 'U((w >> 30) / 3.0)']), + 'BUF_FMT_16_16_UNORM': ('ldu({0}, a)', ['U((w & 65535) / 65535.0)', 'U((w >> 16) / 65535.0)', '0u', 'U(1.0)']), + # SNORM n: max(c / (2^(n-1) - 1), -1.0), so both -32768 and -32767 read -1.0 (the D3D11.3 functional + # spec's SNORM -> FLOAT rule; that the console's buffer fetch clamps the same way is ASSUMED) + 'BUF_FMT_16_SNORM': ('ldu({0}, a)', ['U(max(float(asint(w << 16) >> 16) / 32767.0, -1.0))', + '0u', '0u', 'U(1.0)']), + 'BUF_FMT_16_16_SNORM': ('ldu({0}, a)', ['U(max(float(asint(w << 16) >> 16) / 32767.0, -1.0))', + 'U(max(float(asint(w) >> 16) / 32767.0, -1.0))', '0u', 'U(1.0)']), + 'BUF_FMT_16_16_FLOAT': ('ldu({0}, a)', ['U(f16tof32(w))', 'U(f16tof32(w >> 16))', '0u', 'U(1.0)']), + # four binary16 values in eight bytes: x, y in the first dword (low half first), z, w in the second + 'BUF_FMT_16_16_16_16_FLOAT': ('ldu({0}, a)', ['U(f16tof32(w))', 'U(f16tof32(w >> 16))', + 'U(f16tof32(ldu({0}, a + 4)))', 'U(f16tof32(ldu({0}, a + 4) >> 16))']), + 'BUF_FMT_32_32_32_32_FLOAT': (None, ['{0}.Load(a)', '{0}.Load(a + 4)', '{0}.Load(a + 8)', '{0}.Load(a + 12)']), + 'BUF_FMT_32_32_32_FLOAT': (None, ['{0}.Load(a)', '{0}.Load(a + 4)', '{0}.Load(a + 8)', 'U(1.0)']), + 'BUF_FMT_32_32_FLOAT': (None, ['{0}.Load(a)', '{0}.Load(a + 4)', '0u', 'U(1.0)']), + 'BUF_FMT_32_FLOAT': (None, ['{0}.Load(a)', '0u', '0u', 'U(1.0)'])} + if fmt not in table: + raise Unsupported('buffer format %s' % fmt) + load, comps = table[fmt] + if load: + self.emit('w = %s;' % load.format(buf)) + for i in range(count): + self.set_v(dst[1] + i, comps[i].format(buf)) + # Upstream: typed loads from FETCH_FORMATS, used by the vertex fetch routine below (the local tbuffer keeps its table). def load_format(self, fmt, buf, first, count): if fmt not in FETCH_FORMATS: raise Unsupported('buffer format %s' % fmt) @@ -4234,6 +5122,18 @@ def op_s_swappc_b64(self, ops, mods): self.load_format(FETCH_DXGI[e['format']][0], buf, e['vgpr'], e['count']) self.fetched = True + def op_tbuffer_load_format_x(self, ops, mods): + self.tbuffer(ops, mods, 1) + + def op_tbuffer_load_format_xy(self, ops, mods): + self.tbuffer(ops, mods, 2) + + def op_tbuffer_load_format_xyz(self, ops, mods): + self.tbuffer(ops, mods, 3) + + def op_tbuffer_load_format_xyzw(self, ops, mods): + self.tbuffer(ops, mods, 4) + @staticmethod def descriptor_scalar_writes(name, ops): regs = set() @@ -4390,131 +5290,297 @@ def mubuf_format(self, ops, mods, count): % (sel, sel, sel, sel, sel)) self.emit('}') - def op_buffer_load_format_x(self, ops, mods): - self.mubuf_format(ops, mods, 1) + def format_load(self, ops, mods, count, name): + """buffer_load_format_*: the format and swizzle are in the descriptor's word 3, known only at draw time. - def op_buffer_load_format_xy(self, ops, mods): - self.mubuf_format(ops, mods, 2) + Behind X2W_DRAW_FEATURES=bufword3: the draw runtime passes srv i's word 3 as an entry constant (manifest + `udsrc <n> bufword3 <i>`: the real word of a title-written descriptor, the synthesized one of a typed + buffer view, 0 for raw-copy, vertex and root sources) and x2w_fmt_load decodes the element. The idxen + stride is `udsrc stride` (element size of a typed view, descriptor stride otherwise; d3d12_draw.inl).""" + if self.kind == 'cs': + return self.mubuf_format(ops, mods, count) + if 'bufword3' not in getattr(self.pipe, 'features', ()): + raise Unsupported(name) + for m in mods: + if not (m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:')): + raise Unsupported('%s modifier %s' % (name, m)) + key = self.descriptor(ops[2]) + if key[0][0] == 'heapdyn' and {'heap', 'heapwords'} <= set(getattr(self.pipe, 'features', ())): + # A resource-heap buffer view: word 3 is the runtime's synthesized V# word of the view (manifest + # `heapwords 1`: vdesc, 32 bytes per view id, root SRV t2 space1; mesh_work/RUNTIME_NEEDS.md 6.3, the + # same contract and helper as mesh2hlsl's format_load). 0 for an unknown slot or id: every channel 0. + for m in mods: + if not (m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:')): + raise Unsupported('%s modifier %s' % (name, m)) + dst = reg_range(ops[0]) + buf, address = self.buffer_address(ops, mods) + if buf.startswith('u'): + raise Unsupported('%s through a buffer the program stores to' % name) + self.pipe.draw_heapwords = True + self.emit('a = %s;' % address) + for i in range(count): + self.set_v(dst[1] + i, 'x2w_fmt_load(%s, a, x2w_hword(h%d, 3u), %du)' % (buf, key[0][1], i)) + return + if key[0][0] != 'table': + # word 3 reaches the shader only for table entries (root and vertex sources give 0) + raise Unsupported('%s through %s' % (name, key[0][0])) + dst = reg_range(ops[0]) + buf, address = self.buffer_address(ops, mods) + if buf.startswith('u'): + raise Unsupported('%s through a buffer the program stores to' % name) # bufword3 names an srv + w3 = self.pipe.ud(('bufword3', self.pipe.resources[key]['index'])) + self.emit('a = %s;' % address) + for i in range(count): + self.set_v(dst[1] + i, 'x2w_fmt_load(%s, a, ud%d, %du)' % (buf, w3, i)) - def op_buffer_load_format_xyz(self, ops, mods): - self.mubuf_format(ops, mods, 3) + def buffer_store(self, ops, mods, count, name): + """buffer_store_dword{,x2,x3,x4} to a raw buffer UAV, behind X2W_DRAW_FEATURES=uav. - def op_buffer_load_format_xyzw(self, ops, mods): - self.mubuf_format(ops, mods, 4) - - def op_buffer_store_format_d16_x(self, ops, mods): - """Lower compute MUBUF buffer_store_format_d16_x (opcode 0x84) using V# word 3, stride and num_records. - - Writes one converted 16-bit component from the low 16 bits of vdata into a raw UAV buffer: - - BUF_FMT_32_FLOAT (22): binary16 -> binary32, 4-byte aligned Store. - - BUF_FMT_16_FLOAT (13), BUF_FMT_16_UINT (11), BUF_FMT_16_SINT (12): low 16 bits stored at a - 2-byte aligned offset via a lock-free InterlockedCompareExchange CAS loop on the enclosing dword. - - BUF_FMT_16_UNORM (7), BUF_FMT_16_SNORM (8): binary16 -> binary32 -> D3D half-away-from-zero - 16-bit UNORM/SNORM (NaN -> 0), stored via the same 2-byte atomic CAS loop. - Per RDNA 2 ISA §8.1.5 Table 35, OOB_SELECT 0 (structured, stride != 0) checks index < num_records - and (voff + imm_off) + elem_bytes <= stride while soffset adds to the base address; OOB_SELECT 3 - (raw, stride == 0) checks (soffset + voff + imm_off) + elem_bytes <= num_records. OOB_SELECT 1/2, - mismatched stride/OOB_SELECT, nonzero DW1[31:30] swizzle flags (uav_stride carries DW1 >> 16), - unsupported formats/flags, misaligned addresses and out-of-bounds lanes are no-ops. + The descriptor becomes `uav <i> buf table|root ...` (RWByteAddressBuffer u<i>, draw-rt RUNTIME_DONE.md) and the + address adds `udsrc <n> uavbase <i>` (the bytes between the 16-aligned view start the runtime binds and the + descriptor base; without it a misaligned buffer would get a null UAV). Refused: idxen (no stride line for a + UAV), a descriptor this program also reads as an SRV (D3D12 has no SRV + UAV on one buffer in a draw), and + any modifier other than offen, offset:N and the cache-policy bits. The lane's store runs only where exec holds. """ - name = 'buffer_store_format_d16_x' - if self.kind != 'cs': + if 'uav' not in getattr(getattr(self, 'pipe', None), 'features', ()): raise Unsupported(name) - raw = getattr(self, 'raw_code', b'') - pc = getattr(self, 'pc', None) - if raw and pc is not None and pc + 8 <= len(raw): - w0, w1 = struct.unpack_from('<II', raw, pc) - if (w0 & 0x00030000) or (w1 & 0x00200000): - raise Unsupported('%s illegal MUBUF encoding bits (lds/reserved)' % name) - if len(ops) != 4: - raise Unsupported('%s with %d operands, expected 4' % (name, len(ops))) - idxen = offen = False - imm_offset = None for m in mods: - if m == 'idxen' and not idxen: - idxen = True - elif m == 'offen' and not offen: - offen = True - elif m.startswith('offset:') and imm_offset is None and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): - val = int(m[7:], 0) - if val > 0xfff: - raise Unsupported('%s modifier %s' % (name, m)) - imm_offset = val + if not (m in ('offen', 'glc', 'slc', 'dlc') or m.startswith('offset:')): + raise Unsupported('%s modifier %s' % (name, m)) + key = self.descriptor(ops[2]) + if key[0][0] not in ('table', 'root'): + raise Unsupported('%s through %s' % (name, key[0][0])) + if key in self.pipe.modified: + # A raw store uses only the base address (word 0, word 1 [15:0]); the runtime binds the entry's bytes in + # place. Accepted edits: words 2 and 3 (record count, format, OOB select: bounds and typing a raw + # store ignores; assumed in range) and an AND of word 1 that keeps [15:0] (clearing the stride). + for word, op, other in getattr(self.pipe, 'modified_words', {}).get(key, [('?', '?', ())]): + keeps_base = word == 1 and op == 's_and_b32' and len(other) == 1 and \ + re.fullmatch(r'0x[0-9a-f]+', other[0]) and int(other[0], 16) & 0xffff == 0xffff + if word not in (2, 3) and not keeps_base: + raise Unsupported('%s through a modified descriptor' % name) + u = self.pipe.uav(key) + base = self.pipe.ud(('uavbase', int(u[1:]))) + offset = sum(int(m[7:], 0) for m in mods if m.startswith('offset:')) + soff = ops[3] + if re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', soff): + offset += int(soff, 0) + parts = [] + else: + parts = [self.u(soff)] # an SGPR soffset adds its value + if 'offen' in mods: + parts.insert(0, self.u(ops[1])) + address = ' + '.join(['ud%d' % base] + parts + ['%d' % offset]) + data = reg_range(ops[0]) + if data[2] - data[1] + 1 != count: + raise Unsupported('%s data %s' % (name, ops[0])) + values = ', '.join(self.u('v%d' % (data[1] + i)) for i in range(count)) + call = '%s.Store%s(a, %s);' % (u, '' if count == 1 else count, values if count == 1 else 'uint%d(%s)' % (count, values)) + self.emit('a = %s;' % address) + self.emit(call if self.exec_known else 'if (exec & 1) %s' % call) + + def op_v_pack_b32_f16(self, ops, mods): + """D[15:0] = S0.f16, D[31:16] = S1.f16 (AMD RDNA 2 ISA VOP3 V_PACK_B32_F16). op_sel[i] picks the high half of + source i (LLVM VOP3Instructions.td V_PACK_B32_F16, VOP3_OPSEL); the neg / abs source modifiers act on the + selected half's sign bit (bit 15). The halves are copied as bits: ASSUMED no f16 denormal flush (FLOAT_MODE + keeps f16 denormals in the measured programs) and no NaN quieting. A destination op_sel, clamp and an + op_sel on a constant are refused.""" + sel = [0, 0, 0] + for m in mods: + if m.startswith('op_sel:[') and m.endswith(']'): + sel = [int(x) for x in m[len('op_sel:['):-1].split(',')] + else: + raise Unsupported('v_pack_b32_f16 modifier %s' % m) + if len(sel) != 3 or sel[2] or len(ops) != 3: + raise Unsupported('v_pack_b32_f16 form %s %s' % (', '.join(ops), ' '.join(mods))) + halves = [] + for i, tok in enumerate(ops[1:3]): + neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) + if neg: + tok = tok[1:] + absolute = tok.startswith('|') and tok.endswith('|') + if absolute: + tok = tok[1:-1] + if reg_range(tok) and reg_range(tok)[1] == reg_range(tok)[2]: + half = '(%s >> 16)' % self.u(tok) if sel[i] else '(%s & 0xffffu)' % self.u(tok) + elif sel[i]: + raise Unsupported('v_pack_b32_f16 op_sel on %s' % tok) else: + half = '(%s & 0xffffu)' % self.h(tok) + if absolute: + half = '(%s & 0x7fffu)' % half + if neg: + half = '(%s ^ 0x8000u)' % half + halves.append(half) + self.set_v(reg_range(ops[0])[1], '%s | (%s << 16)' % (halves[0], halves[1])) + + def format_store(self, ops, mods, count, name): + """buffer_store_format_{x,xy,xyz,xyzw} to a typed buffer UAV, behind X2W_DRAW_FEATURES=uav,uavfmt. + + The format is in the V# word 3 [18:12], known only at draw time: `udsrc <n> uavword3 <i>` gives it, and + `udsrc <n> uavstride <i>` the V# stride (word 1 [29:16]) that idxen multiplies the index by (RDNA 2 ISA, + MUBUF addressing: base + soffset + offset + stride * index (+ the offen VGPR)). x2w_fmt_store writes data + component c to format channel c; only formats whose channels are all 32 bits (codes 20-22, 62-64, 72-77: + the bits are stored as given) are written, any other format stores nothing. ASSUMED, not measured: DST_SEL + does not reorder a store (LLVM lowers the store intrinsic with the data in channel order), and the index + is in range (num_records not checked, as for the raw stores). The lane's store runs only where exec holds.""" + if not {'uav', 'uavfmt'} <= set(getattr(self.pipe, 'features', ())): + raise Unsupported(name) + for m in mods: + if not (m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:')): raise Unsupported('%s modifier %s' % (name, m)) - imm_offset = 0 if imm_offset is None else imm_offset - src = reg_range(ops[0]) - if not src or src[0] != 'v' or src[1] != src[2] or src[1] > 255: + key = self.descriptor(ops[2]) + if key[0][0] not in ('table', 'root'): + raise Unsupported('%s through %s' % (name, key[0][0])) + if key in self.pipe.modified: + raise Unsupported('%s through a modified descriptor' % name) + u = self.pipe.uav(key) + index = int(u[1:]) + base, w3 = self.pipe.ud(('uavbase', index)), self.pipe.ud(('uavword3', index)) + offset = sum(int(m[7:], 0) for m in mods if m.startswith('offset:')) + soff = ops[3] + parts = ['ud%d' % base] + if re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', soff): + offset += int(soff, 0) + else: + parts.append(self.u(soff)) + vaddr = reg_range(ops[1]) + if 'idxen' in mods and 'offen' in mods: + if not vaddr or vaddr[2] != vaddr[1] + 1: + raise Unsupported('%s idxen offen address %s' % (name, ops[1])) + parts += ['v%d * ud%d' % (vaddr[1], self.pipe.ud(('uavstride', index))), self.u('v%d' % vaddr[2])] + elif 'idxen' in mods: + parts.append('%s * ud%d' % (self.u(ops[1]), self.pipe.ud(('uavstride', index)))) + elif 'offen' in mods: + parts.append(self.u(ops[1])) + data = reg_range(ops[0]) + if not data or data[2] - data[1] + 1 != count: raise Unsupported('%s data %s' % (name, ops[0])) - if idxen and offen: - vaddr = reg_range(ops[1]) - if not vaddr or vaddr[0] != 'v' or vaddr[2] - vaddr[1] != 1 or vaddr[2] > 255: - raise Unsupported('%s vaddr %s for idxen offen' % (name, ops[1])) - idx_expr, voff_expr = self.u('v%d' % vaddr[1]), self.u('v%d' % vaddr[2]) - elif idxen: - vaddr = reg_range(ops[1]) - if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: - raise Unsupported('%s vaddr %s for idxen' % (name, ops[1])) - idx_expr, voff_expr = self.u(ops[1]), '0u' - elif offen: + values = [self.u('v%d' % (data[1] + i)) for i in range(count)] + ['0u'] * (4 - count) + self.pipe.notes.add('typed UAV store (x2w_fmt_store: 32-bit channel formats only)') + call = 'x2w_fmt_store(%s, a, ud%d, uint4(%s), %du);' % (u, w3, ', '.join(values), count) + self.emit('a = %s;' % ' + '.join(parts + ['%d' % offset])) + self.emit(call if self.exec_known else 'if (exec & 1) %s' % call) + + def op_buffer_store_format_x(self, ops, mods): + self.format_store(ops, mods, 1, 'buffer_store_format_x') + + def op_buffer_store_format_xy(self, ops, mods): + self.format_store(ops, mods, 2, 'buffer_store_format_xy') + + def op_buffer_store_format_xyz(self, ops, mods): + self.format_store(ops, mods, 3, 'buffer_store_format_xyz') + + def op_buffer_store_format_xyzw(self, ops, mods): + self.format_store(ops, mods, 4, 'buffer_store_format_xyzw') + + def store_descriptor(self, tok, words, what, stride0_ok=False, raw_conversion_ok=False): + """Resource key for a single loaded descriptor or a proven raw transformation of it.""" + rsrc = reg_range(tok) + first = self.sym.get(rsrc[1]) if rsrc and rsrc[0] == 's' and rsrc[2] - rsrc[1] == words - 1 else None + if not first or first[0] != 'desc' or first[1][0] != 'table' or first[2] is None or first[3] % 4: + raise Unsupported('%s through %s holding %s' % (what, tok, first)) + key = desc_key(first) + loaded = tuple(desc_word(first, first[3] + k) for k in range(words)) + actual = tuple(self.sym.get(rsrc[1] + k) for k in range(words)) + valid = names_one_value(first) and actual == loaded + if names_one_value(first) and stride0_ok and words == 4: + cleared = loaded[1] + ('stride0',) + valid = valid or actual == (loaded[0], cleared, *loaded[2:]) + if not valid and raw_conversion_ok: + valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',)) + if (not valid or key in getattr(self.pipe, 'other_modified', ()) + or (key in self.pipe.modified and not stride0_ok)): + raise Unsupported('%s through a modified descriptor' % what) + return key + + def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=False, allow_scalar_address=False, + raw_conversion_ok=False): + """Validate a fixed-table raw UAV descriptor, data range, byte address, and 4-byte alignment.""" + offset = 0 + glc = False + for m in mods: + if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): + offset += int(m[7:], 0) + elif m == 'glc' and allow_glc: + glc = True + elif m != 'offen': + raise Unsupported('%s modifier %s' % (kind_label, m)) + offen = 'offen' in mods + if len(ops) != 4 or (not offen and not (allow_scalar_address and glc and ops[1] == 'off')): + raise Unsupported('%s without the offen address form' % kind_label) + data = reg_range(ops[0]) + if not data or data[0] != 'v' or data[2] - data[1] != data_count - 1 or data[2] > 255: + raise Unsupported('%s data %s' % (kind_label, ops[0])) + if offen: vaddr = reg_range(ops[1]) if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: - raise Unsupported('%s vaddr %s for offen' % (name, ops[1])) - idx_expr, voff_expr = '0u', self.u(ops[1]) - else: - if ops[1] != 'off': - raise Unsupported('%s vaddr %s without idxen or offen' % (name, ops[1])) - idx_expr, voff_expr = '0u', '0u' + raise Unsupported('%s vaddr %s for offen' % (kind_label, ops[1])) + key = self.store_descriptor(ops[2], 4, kind_label, stride0_ok=True, raw_conversion_ok=raw_conversion_ok) + terms = [self.u(ops[1])] if offen else [] if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): - soff_imm = int(ops[3], 0) - if soff_imm > 0xffffffff: - raise Unsupported('%s soffset %s' % (name, ops[3])) - soff_expr = '%du' % soff_imm + if not offen: + raise Unsupported('%s off requires a scalar register soffset' % kind_label) + offset += int(ops[3], 0) else: - if self.is_lane_mask(ops[3]): - raise Unsupported('%s soffset %s is a lane mask' % (name, ops[3])) sreg = reg_range(ops[3]) if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: - raise Unsupported('%s soffset %s' % (name, ops[3])) - soff_expr = self.S(sreg[1]) - rsrc = reg_range(ops[2]) - if not rsrc or rsrc[0] != 's' or rsrc[2] - rsrc[1] != 3 or rsrc[2] > 105: - raise Unsupported('%s descriptor %s' % (name, ops[2])) - key = self.store_descriptor(ops[2], 4, name, stride0_ok=False) - first = self.sym.get(rsrc[1]) - if getattr(self, 'past_entry', False) and not self.formatted_descriptor_from_block(rsrc, first): - raise Unsupported('%s requires descriptor words proven in the entry block or a local table load' % name) - uav = self.pipe.uav(key, 'raw') - uav_index = self.pipe.uavs[key]['index'] - word3 = 'ud%d' % self.pipe.ud(('uav_descword3', uav_index)) - stride = 'ud%d' % self.pipe.ud(('uav_stride', uav_index)) - num_records = 'ud%d' % self.pipe.ud(('uav_numrecords', uav_index)) - val_expr = self.u(ops[0], low16_only=True) - self.pipe.uses_store_d16_x = True - call = 'store_format_d16_x(%s, %s, %s, %s, %s, %s, %s, %du, %s);' % ( - uav, word3, stride, num_records, idx_expr, voff_expr, soff_expr, imm_offset, val_expr) - self.emit(call if self.exec_known else 'if (exec & 1) ' + call) + raise Unsupported('buffer soffset %s' % ops[3]) + terms.append(self.S(sreg[1])) + if offset % 4: + raise Unsupported('%s at unaligned immediate offset %d' % (kind_label, offset)) + terms.append(str(offset)) + return data, self.pipe.uav(key), '(%s) & 0xfffffffcu' % ' + '.join(terms), glc - def op_tbuffer_load_format_x(self, ops, mods): - self.tbuffer(ops, mods, 1) + def compute_buffer_store(self, ops, mods, count=1): + # Compute-stage store in the offen form: per-lane byte VGPR plus the scalar offset and the 12-bit immediate, + # through a descriptor read from a fixed root-table slot, to a RWByteAddressBuffer (manifest `uav` line). + # Like the loads, this assumes a raw descriptor (no swizzle or stride). Out-of-range stores: assumes a future + # runtime sizes the view to the descriptor's range so both sides drop them; nothing binds or checks that yet. + if self.kind != 'cs': + raise Unsupported('buffer_store_dword' + ('x%d' % count if count > 1 else '')) # the unknown-op refusal + src, uav, address, _ = self.raw_table_uav_store('buffer store', ops, mods, count, raw_conversion_ok=True) + words = [self.u('v%d' % n) for n in range(src[1], src[2] + 1)] + data = words[0] if count == 1 else 'uint%d(%s)' % (count, ', '.join(words)) + # Store* needs a multiple of four. As in #2059, the run-time part (VGPR and register soffset) is rounded down: + # an assumption that a dword access ignores the low two address bits, not a measurement. + self.emit('a = %s;' % address) + store = '%s.Store%s(a, %s);' % (uav, '' if count == 1 else count, data) + self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) - def op_tbuffer_load_format_xy(self, ops, mods): - self.tbuffer(ops, mods, 2) + def op_buffer_store_dword(self, ops, mods, count=1): + if getattr(self, 'kind', None) == 'cs': + return self.compute_buffer_store(ops, mods, count) + Stage.buffer_store(self, ops, mods, count, 'buffer_store_dword' + ('x%d' % count if count > 1 else '')) - def op_tbuffer_load_format_xyz(self, ops, mods): - self.tbuffer(ops, mods, 3) + def op_buffer_store_dwordx2(self, ops, mods): + if getattr(self, 'kind', None) == 'cs': + return self.compute_buffer_store(ops, mods, 2) + self.buffer_store(ops, mods, 2, 'buffer_store_dwordx2') - def op_tbuffer_load_format_xyzw(self, ops, mods): - self.tbuffer(ops, mods, 4) + def op_buffer_store_dwordx3(self, ops, mods): + if getattr(self, 'kind', None) == 'cs': + return self.compute_buffer_store(ops, mods, 3) + self.buffer_store(ops, mods, 3, 'buffer_store_dwordx3') + + def op_buffer_store_dwordx4(self, ops, mods): + if getattr(self, 'kind', None) == 'cs': + return self.compute_buffer_store(ops, mods, 4) + self.buffer_store(ops, mods, 4, 'buffer_store_dwordx4') + + def op_buffer_load_format_x(self, ops, mods): + self.format_load(ops, mods, 1, 'buffer_load_format_x') + + def op_buffer_load_format_xy(self, ops, mods): + self.format_load(ops, mods, 2, 'buffer_load_format_xy') + + def op_buffer_load_format_xyz(self, ops, mods): + self.format_load(ops, mods, 3, 'buffer_load_format_xyz') + + def op_buffer_load_format_xyzw(self, ops, mods): + self.format_load(ops, mods, 4, 'buffer_load_format_xyzw') def image(self, ops, mods, how): - if getattr(self, 'kind', None) == 'cs' and 'd16' in mods: - raise Unsupported('compute d16 image load requires validated SRV formats') - # Every image form reads vdata, an address and a descriptor, so a shorter operand list would reach - # ops[1] or ops[2] as an index error rather than a refusal. Samplers are checked further down, where - # the form decides whether one is required. - if len(ops) < 3: - raise Unsupported('image instruction with %d operands, expected at least 3' % len(ops)) dst = reg_range(ops[0]) dims = [m for m in mods if m.startswith('dim:')] dmasks = [m for m in mods if m.startswith('dmask:')] @@ -4522,181 +5588,186 @@ def image(self, ops, mods, how): raise Unsupported('image instruction without %s' % ('dim:' if not dims else 'dmask:')) dim = dims[0][4:] dmask = int(dmasks[0][6:], 0) - kinds = {'SQ_RSRC_IMG_1D': 'tex1d', 'SQ_RSRC_IMG_2D': 'tex2d', 'SQ_RSRC_IMG_3D': 'tex3d', 'SQ_RSRC_IMG_2D_ARRAY': 'tex2da'} + kinds = {'SQ_RSRC_IMG_1D': 'tex1d', 'SQ_RSRC_IMG_2D': 'tex2d', 'SQ_RSRC_IMG_3D': 'tex3d', + 'SQ_RSRC_IMG_2D_ARRAY': 'tex2da'} if dim not in kinds: raise Unsupported('image dimension %s' % dim) # A 2D array takes the slice as its third address component, where a volume takes z. Sample and - # Load on a Texture2DArray take it in the same place, so only the declared type differs. - one = dim == 'SQ_RSRC_IMG_1D' - three = dim in ('SQ_RSRC_IMG_3D', 'SQ_RSRC_IMG_2D_ARRAY') + # Load on a Texture2DArray take it in the same place, so only the declared type differs. A 1D image has + # the one coordinate (x for a load, u for a sample), bound as a Texture1D (manifest kind tex1d). + axes = {'SQ_RSRC_IMG_1D': 1, 'SQ_RSRC_IMG_2D': 2}.get(dim, 3) coords = ops[1] if coords.startswith('['): cs = [c.strip() for c in coords[1:-1].split(',')] else: r = reg_range(coords) cs = ['v%d' % n for n in range(r[1], r[2] + 1)] - if one and (how != 'sample' or len(cs) != 1 or not dmask or any(not m.startswith(('dim:', 'dmask:')) for m in mods)): - raise Unsupported('unverified 1D image sample address or modifiers') - lod = bias = None - if how in ('l', 'b'): - # image_sample_l: the address dwords are the coordinates and then the explicit level. image_sample_b: - # the RDNA 2 ISA (section 8.2.5, "{ offset } { bias } { z-compare } { derivative } { body }") puts one - # float bias dword BEFORE the coordinates. Offsets, clamp and derivatives would add dwords or modifiers - # this lowering does not read, so they are refused. Only the cache-policy + # Every form takes only dim, dmask, the cache-policy bits and, for the loads, unorm (a load addresses texels by + # integer coordinates either way) and a16. a16 packs the 16-bit address components two to a dword, the first + # in the low half (LLVM SIISelLowering packImage16bitOpsToDwords): unsigned texel coordinates for a load and + # binary16 coordinates for a sample. d16, tfe, lwe and r128 change the result or resource layout and are + # refused, as is any modifier not named here. + # (image_sample_l and image_load_mip check their own modifier lists below.) + allowed = ('dlc', 'glc', 'slc', 'a16') + (('unorm',) if how == 'load' else ('d16',) if how in ('sample', 'lz') else ()) + if how == 'get_lod': + allowed = ('dlc', 'glc', 'slc') + for m in mods: + if how in ('sample', 'lz', 'load', 'b', 'd', 'get_lod') and not (m.startswith(('dim:', 'dmask:')) or m in allowed): + raise Unsupported('image_%s modifier %s' % (how, m)) + a16 = 'a16' in mods + bias = None + if how == 'b': + # image_sample_b: the LOD bias is the first address dword, before the coordinates (LLVM + # AMDGPUImageDimIntrinsics sample_b: ExtraAddrArgs [bias]). With a16 it would be a 16-bit value packed + # into its own dword, not modelled here. + if a16 or dmask == 0 or len(cs) != axes + 1: + raise Unsupported('image_sample_b form %s %s' % (', '.join(ops), ' '.join(mods))) + bias, cs = cs[0], cs[1:] + grads = None + if how == 'd': + # image_sample_d: the gradients come first, d<c>dh for each coordinate c (s, t, r) then d<c>dv, and then + # the coordinates and the slice (LLVM IntrinsicsAMDGPU.td AMDGPUDimProps.GradientArgs, AddrArgs order + # ExtraAddrArgs, GradientArgs, CoordSliceArgs). h is the horizontal (x) and v the vertical (y) screen + # direction: SampleGrad's ddx and ddy. A 2D array has 2D gradients. With a16 the gradients would be + # packed too, not modelled here. + n = {'SQ_RSRC_IMG_1D': 1, 'SQ_RSRC_IMG_2D': 2, 'SQ_RSRC_IMG_3D': 3, 'SQ_RSRC_IMG_2D_ARRAY': 2}[dim] + if a16 or dmask == 0 or len(cs) != 2 * n + axes: + raise Unsupported('image_sample_d form %s %s' % (', '.join(ops), ' '.join(mods))) + grads, cs = (cs[:n], cs[n:2 * n]), cs[2 * n:] + if a16: + if len(cs) < (axes + 1) // 2: + raise Unsupported('a16 image address with %d registers' % len(cs)) + # component i is the (i % 2) half of address dword i // 2; unpacked to one 32-bit value each + cs = [('a16', cs[i // 2], i % 2) for i in range(axes)] + lod = None + if how == 'l': + # Address dwords are the coordinates and then the explicit level; offsets, bias, clamp and derivatives + # would add dwords or modifiers this lowering does not read, so they are refused. Only the cache-policy # bits (glc, slc, dlc), which never change the sampled value, are accepted next to dim and dmask; # unorm, r128, tfe, lwe, a16, d16 and reserved bits would each change the address, resource or result # layout and are refused by name. - name = 'image_sample_' + how for m in mods: if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): - raise Unsupported('%s modifier %s' % (name, m)) + raise Unsupported('image_sample_l modifier %s' % m) if dmask == 0: - raise Unsupported('%s with an empty dmask' % name) - if len(cs) != (4 if three else 3): - raise Unsupported('%s with %d address registers' % (name, len(cs))) - if how == 'l': - lod, cs = cs[-1], cs[:-1] - else: - # The bias is added to the LOD derived from the coordinate derivatives of the pixel quad: only a - # pixel stage that still runs with its entry mask has them. Elsewhere the plain sample is lowered - # to level 0, which would drop the bias, so the bias form is refused instead. - if self.kind != 'ps' or not self.exec_known or len(self.blocks) > 0: - raise Unsupported('image_sample_b needs implicit derivatives: pixel stage, entry mask, no branches') - bias, cs = cs[0], cs[1:] - if how == 'get_lod': - # image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp - # (Mesa nir_texop_lod, which ACO emits as image_get_lod; GLSL textureQueryLod x/y). Only the 2D form with - # two address registers and dmask 0x1-0x3 is lowered; the cache-policy bits are the only other modifiers. - for m in mods: - if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): - raise Unsupported('image_get_lod modifier %s' % m) - if self.kind != 'ps' or dim != 'SQ_RSRC_IMG_2D' or not dmask or dmask & ~3 or len(cs) != 2: - raise Unsupported('image_get_lod form %s %s' % (', '.join(ops), ' '.join(mods))) - # Both HLSL calls take implicit derivatives, so the rule of image_sample_b applies. - if not self.exec_known or len(self.blocks) > 0: - raise Unsupported('image_get_lod needs implicit derivatives: pixel stage, entry mask, no branches') - desc_key = self.descriptor(ops[2]) - tex = self.pipe.resource(desc_key, kinds[dim]) + raise Unsupported('image_sample_l with an empty dmask') + if len(cs) != axes + 1: + raise Unsupported('image_sample_l with %d address registers' % len(cs)) + lod, cs = cs[-1], cs[:-1] + tex = self.pipe.resource(self.descriptor(ops[2]), kinds[dim]) if how in ('load', 'load_mip'): # image_load_mip addresses x, y, [slice or z] and then the mip, so a 2D array is four registers - # and Texture2DArray.Load takes int4(x, y, slice, mip) like a volume's int4(x, y, z, mip). - axes = 3 if three else 2 - packed_2d = how == 'load' and dim == 'SQ_RSRC_IMG_2D' and 'a16' in mods - packed_d16 = how in ('load', 'load_mip') and 'd16' in mods - allowed = ('unorm', 'glc', 'slc', 'dlc') - if packed_2d: - allowed += ('a16',) - if packed_d16: - allowed += ('d16',) - unsupported = any(not m.startswith(('dim:', 'dmask:')) and m not in allowed for m in mods) - expected_addr = 1 if packed_2d else (axes + 1 if how == 'load_mip' else axes) - wrong_address = len(cs) != expected_addr - if unsupported or wrong_address or not dmask: - raise Unsupported('image_%s address or modifiers: %s' % (how, ' '.join(mods))) - if packed_d16: - op_name = 'image_' + how - expected_dst = (bin(dmask).count('1') + 1) // 2 - if not dst or dst[0] != 'v' or dst[2] - dst[1] + 1 != expected_dst or dst[2] > 255: - raise Unsupported('%s d16 destination %s for dmask %#x' % (op_name, ops[0], dmask)) - res = self.pipe.resources[desc_key] - if res['index'] in self.pipe.srv_formats: - fmt = self.pipe.srv_formats[res['index']] - if fmt not in D16_EXACT_SRV_FORMATS: - raise Unsupported('%s d16 unsupported SRV format %d' % (op_name, fmt)) - if packed_2d: - packed = self.u(cs[0]) - address = ['%s & 0xffffu' % packed, '%s >> 16' % packed] - else: - address = [self.u(c) for c in cs[:axes]] - mip = self.u(cs[axes]) if how == 'load_mip' else '0' - call = '%s.Load(int%d(%s))' % (tex, axes + 1, ', '.join(address + [mip])) + # and Texture2DArray.Load takes int4(x, y, slice, mip) like a volume's int4(x, y, z, mip); a Texture1D + # takes int2(x, mip). + mip = '0' + if how == 'load_mip': + unsupported = [m for m in mods if not m.startswith(('dim:', 'dmask:')) + and m not in ('unorm', 'glc', 'slc', 'dlc')] + if unsupported or len(cs) != axes + 1 or not dmask: + raise Unsupported('image_load_mip address or modifiers: %s' % ' '.join(mods)) + mip = self.u(cs[axes]) + if len(cs) < axes: + raise Unsupported('image_%s with %d address registers' % (how, len(cs))) + address = [self.a16_u(c) if isinstance(c, tuple) else self.u(c) for c in cs[:axes]] + [mip] + call = '%s.Load(int%d(%s))' % (tex, axes + 1, ', '.join(address)) else: - packed_2d = False - if not one and how in ('sample', 'lz'): - op_name = 'image_sample' if how == 'sample' else 'image_sample_lz' - packed_2d = dim == 'SQ_RSRC_IMG_2D' and 'a16' in mods - allowed = ('dlc', 'glc', 'slc') + (('a16',) if packed_2d else ()) - for m in mods: - if not (m.startswith(('dim:', 'dmask:')) or m in allowed): - raise Unsupported('%s modifier %s' % (op_name, m)) - if not dmask: - raise Unsupported('%s with an empty dmask' % op_name) - expected = 1 if packed_2d else (3 if three else 2) - if len(cs) != expected: - raise Unsupported('%s with %d address registers' % (op_name, len(cs))) heap = self.heap_sampler(ops[3]) words = None if heap else self.const_words(ops[3]) - name = 'image_sample' + ('' if how == 'sample' else '_' + how) - if how == 'b': - # The guest clamps the biased LOD to the sampler's MIN_LOD and MAX_LOD. Only a constant descriptor - # can be read here, and only its limits are carried to the static sampler (line smpl), so a sampler - # from the heap or from a register is refused: its limits and bias cannot be shown to be irrelevant. - words = self.sample_b_sampler(heap, words) - smp = self.pipe.sampler(tuple(words), lod_limits=True) - elif how == 'get_lod': - # The clamped result depends on the sampler's MIN_LOD, MAX_LOD and bias, so the sampler must be a - # constant descriptor under the same validation as image_sample_b, with its limits carried. - if heap or not words or self.default_sampler_words(words): - raise Unsupported('image_get_lod with a sampler that is not constant (LOD limits and bias unknown)') - smp = self.pipe.sampler(tuple(self.lod_sampler_words('image_get_lod', words)), lod_limits=True) - elif how in ('sample', 'l', 'lz') and (heap or (words and self.default_sampler_words(words))): - # A heap sampler, or the fixed default that stands in for one, keeps its unbounded static LOD range: the - # descriptor is read at run time, so its MIN_LOD, MAX_LOD and bias are not validated here (#2221). - self.pipe.lod_unvalidated.add(name) - smp = heap or self.pipe.sampler(tuple(words)) - elif how in ('sample', 'l', 'lz') and words: - # A constant descriptor carries its LOD limits like image_sample_b, under the same bias and range - # validation. A mip filter of 0 (base level only) keeps the ordinary sampler, as before: refusing it - # would drop every pipeline with an all-zero inline sampler, and only the bias form needs it refused. - self.lod_sampler_words(name, words, mip_filter_none_ok=True) - smp = self.pipe.sampler(tuple(words), lod_limits=bool((words[2] >> 26) & 3)) - else: - smp = heap or self.pipe.sampler(tuple(words) if words else self.descriptor(ops[3])) - if packed_2d: - packed = self.u(cs[0]) - uv = 'float2(f16tof32(%s), f16tof32(%s >> 16))' % (packed, packed) - elif one: - uv = self.f(cs[0]) - elif three: - uv = 'float3(%s, %s, %s)' % (self.f(cs[0]), self.f(cs[1]), self.f(cs[2])) - else: - uv = 'float2(%s, %s)' % (self.f(cs[0]), self.f(cs[1])) - if how == 'sample' and self.kind == 'cs': - # A compute lane has no pixel quad to supply derivatives; level 0 would be a guess. - raise Unsupported('image_sample with implicit LOD in a compute program') + smp = heap or self.pipe.sampler(tuple(words) if words else self.descriptor(ops[3])) + if len(cs) < axes: + raise Unsupported('image_%s with %d address registers' % (how, len(cs))) + fs = [self.a16_f(c) if isinstance(c, tuple) else self.f(c) for c in cs[:axes]] + uv = fs[0] if axes == 1 else 'float%d(%s)' % (axes, ', '.join(fs)) if how == 'l': call = '%s.SampleLevel(%s, %s, %s)' % (tex, smp, uv, self.f(lod)) elif how == 'b': - # SampleBias adds the bias to the implicit LOD, like the ISA's _B suffix ("Add this BIAS to the LOD - # computed"). The sampler's LOD limits are carried by the smpl line; its LOD bias is refused in - # sample_b_sampler. + # SampleBias takes implicit derivatives like Sample, so it is lowered only where Sample is (below); + # the level-0 fallback Sample uses elsewhere would ignore the bias. + if self.kind != 'ps': + raise Unsupported('image_sample_b outside straight-line code with every lane active') + if not self.exec_known or len(self.blocks) > 0: + # X2W_PS_QUAD_DIVERGENT=1 (see quad_divergent): taken in forward control flow, not in a loop + if not self.quad_divergent or self.has_loop: + raise Unsupported('image_sample_b outside straight-line code with every lane active') + self.quad_divergent_used.append(self.pc) call = '%s.SampleBias(%s, %s, %s)' % (tex, smp, uv, self.f(bias)) elif how == 'get_lod': - # HLSL CalculateLevelOfDetail (clamped) and CalculateLevelOfDetailUnclamped (SM 4.1+). Which clamps - # each side applies besides the sampler's (the view's mip range) is assumed to agree. + # image_get_lod: [0] the LOD the sample would use, clamped, [1] the computed LOD before the clamp + # (Mesa nir_texop_lod, which ACO emits as image_get_lod and returns as is; GLSL textureQueryLod x/y). + # HLSL CalculateLevelOfDetail / CalculateLevelOfDetailUnclamped (HLSL intrinsics, SM 4.1+). Both use implicit + # derivatives, so the control-flow rule of image_sample_b applies. Which clamps each side applies + # (sampler MIN/MAX_LOD, the view's mip range) is ASSUMED to agree; the runtime carries the sampler's + # LOD fields with X2W_SAMPLER_LOD=1. + if self.kind != 'ps' or dim != 'SQ_RSRC_IMG_2D' or dmask & ~3 or not dmask or len(cs) != 2 or a16: + raise Unsupported('image_get_lod form %s %s' % (', '.join(ops), ' '.join(mods))) + if not self.exec_known or len(self.blocks) > 0: + if not self.quad_divergent or self.has_loop: + raise Unsupported('image_get_lod outside straight-line code with every lane active') + self.quad_divergent_used.append(self.pc) call = 'float4(%s.CalculateLevelOfDetail(%s, %s), %s.CalculateLevelOfDetailUnclamped(%s, %s), 0.0, 0.0)' % ( tex, smp, uv, tex, smp, uv) + elif how == 'd': + # explicit gradients: no implicit derivatives, so any control flow and any exec state + ddx, ddy = (', '.join(self.f(c) for c in g) for g in grads) + if len(grads[0]) > 1: + ddx, ddy = 'float%d(%s)' % (len(grads[0]), ddx), 'float%d(%s)' % (len(grads[0]), ddy) + call = '%s.SampleGrad(%s, %s, %s, %s)' % (tex, smp, uv, ddx, ddy) + elif how == 'sample' and self.kind == 'ps' and getattr(self, 'require_counted_search', False): + if os.environ.get('X2W_PS_QUAD_UNIFORM') != '1': + raise Unsupported('pixel search needs uniform implicit samples') + temp = 'sample_at_%x' % self.pc + statement = 'float4 %s = %s.Sample(%s, %s);' % (temp, tex, smp, uv) + self.__dict__.setdefault('dpp_statements', set()).add(statement) + self.__dict__.setdefault('dpp_at', []).append(self.pc) + self.emit(statement) + call = temp + elif how == 'sample' and getattr(self, 'implicit_lod', False) and (not self.exec_known or self.blocks): + # The hardware takes the derivatives from the quad's address VGPRs (whole quads under s_wqm), which + # HLSL Sample reads where the quad's lanes run it together: always before the first branch, and + # in branched code where the quad's lanes take one path (assumed, quad_divergent_used). + if self.blocks: + self.implicit_samples.append(self.pc) + self.quad_divergent_used.append(self.pc) + call = '%s.Sample(%s, %s)' % (tex, smp, uv) elif how == 'lz' or not self.exec_known or self.kind != 'ps' or len(self.blocks) > 0: call = '%s.SampleLevel(%s, %s, 0)' % (tex, smp, uv) else: call = '%s.Sample(%s, %s)' % (tex, smp, uv) self.emit('t = %s;' % call) - if how in ('load', 'load_mip') and 'd16' in mods: - res = self.pipe.resources[desc_key] - res['d16_exact'] = True - mode_arg = 'ud%d' % self.pipe.ud(('d16unorm16', res['index'])) - self.pipe.uses_pack16_rne = True - halves = ['pack16_d16(t.%s, %s)' % (comp, mode_arg) for bit, comp in enumerate('xyzw') if dmask & (1 << bit)] - for i in range(0, len(halves), 2): - odd_tail = i + 1 == len(halves) - expr = halves[i] if odd_tail else '%s | (%s << 16)' % (halves[i], halves[i + 1]) - self.set_v(dst[1] + i // 2, expr, low16_only=odd_tail) - else: - n = dst[1] - for bit, comp in enumerate('xyzw'): - if dmask & (1 << bit): - self.set_v(n, 'U(t.%s)' % comp) - n += 1 + # An image read with no implicit derivatives (load, level 0, explicit level) of a bound texture (rN) through a + # fixed sampler (qN), at lane-invariant coordinates, returns the same texel or filtered value in every lane. + if how in ('load', 'load_mip', 'lz', 'l') and hasattr(self, 'lane_s') and re.match(r'r\d+\b', call): + expr = re.sub(r'\bq\d+\b', '0', call) + expr = re.sub(r'\.(Load|SampleLevel)\(', '(', expr) + expr = re.sub(r'\b(int|uint|float)[234]\(', '(', expr) + self.t_invariant = self.lane_invariant(expr) + n = dst[1] + if 'd16' in mods: + if self.round16: + raise Unsupported('image_%s d16 under s_round_mode f16/f64 toward zero' % how) + # Packed D16 (gfx9+, LLVM GCNSubtarget hasPackedD16VMem; SIISelLowering adjustLoadValueType): each enabled + # channel of the filtered result is converted to binary16 and two go in one VGPR, the first channel in + # the low half; the high half after an odd channel count is written as 0 here (undefined in hardware). + # Only the sampling forms take it: their result is a float whatever the texel format. + comps = ['f32tof16(t.%s)' % c for bit, c in enumerate('xyzw') if dmask & (1 << bit)] + if not comps or dst[2] - dst[1] + 1 != (len(comps) + 1) // 2: + raise Unsupported('image_%s d16 with dmask %#x into %s' % (how, dmask, ops[0])) + for i in range(0, len(comps), 2): + self.set_v(n, comps[i] if i + 1 == len(comps) else '%s | (%s << 16)' % (comps[i], comps[i + 1])) + n += 1 + return + for bit, comp in enumerate('xyzw'): + if dmask & (1 << bit): + self.set_v(n, 'U(t.%s)' % comp) + n += 1 + + def a16_u(self, component): + _, reg, half = component + return '(%s >> 16)' % self.u(reg) if half else '(%s & 0xffffu)' % self.u(reg) + + def a16_f(self, component): + _, reg, half = component + return 'f16tof32(%s)' % ('%s >> 16' % self.u(reg) if half else self.u(reg)) def image_compare(self, ops, mods, how): """image_sample_c and image_sample_c_lz: a 2D or 2D-array depth comparison returning one float. @@ -4741,8 +5812,30 @@ def image_compare(self, ops, mods, how): if words is None: raise Unsupported('%s with a sampler that is not constant' % base) import pixel_aot + checked = list(words) + if how == 'c_lz' and (words[2] >> 28) == 1: + # Word 2 bit 28 is MIP_POINT_PRECLAMP (Mesa gfx10-rsrc.json SQ_IMG_SAMP_WORD2): it changes how a point + # mip filter clamps the LOD before rounding it to a level. c_lz samples level zero with MIN_LOD 0 (the + # decoder refuses any other MIN_LOD), so no LOD reaches the mip selection and the bit cannot change the + # result (ASSUMED from the field name and placement; not measured on hardware). Bits 29-31 stay refused. + # Mesa (bb59ce45 ac_build_sampler_descriptor) never sets the bit, so no open driver documents more. + checked[2] &= ~(1 << 28) + clamp_xy = (words[0] & 7, words[0] >> 3 & 7) + if 6 in clamp_xy and set(clamp_xy) <= {2, 6}: + # SQ_TEX_CLAMP_BORDER (6, Mesa radv_sampler.c maps VK CLAMP_TO_BORDER to it) in X and/or Y: outside + # [0, 1] the texel is the border colour, BORDER_COLOR_TYPE (word 3 bits 31:30; 0 transparent black, + # 1 opaque black, 2 opaque white, Mesa ac_descriptors.c) and the comparison runs against its red + # channel; D3D12 BORDER with that static colour does the same (Vulkan orders texel replacement before + # the depth compare as well). Type 3 (a border colour table entry, BORDER_COLOR_PTR) is refused. The + # runtime carries the colour with X2W_SAMPLER_LOD=1 (sampler_lod_fields); without it the static + # sampler's border is transparent black, which is exact for type 0 only. The smpc manifest line keeps + # the original words (the runtime's decode_sampler maps 6 to D3D12_TEXTURE_ADDRESS_MODE_BORDER); the + # other fields of the contract (filters, compare, LOD, TRUNC_COORD) are checked with CLAMP_LAST_TEXEL. + if words[3] >> 30 == 3: + raise Unsupported('%s sampler: border colour from the border colour table (BORDER_COLOR_TYPE 3)' % base) + checked[0] = checked[0] & ~0x3f | 2 | 2 << 3 try: - pixel_aot.comparison_sampler_state(tuple(words), level_zero=how == 'c_lz', allow_border=True) + pixel_aot.comparison_sampler_state(tuple(checked)) except ValueError as error: raise Unsupported('%s sampler: %s' % (base, error)) tex = self.pipe.resource(self.descriptor(ops[2]), 'tex2da' if array else 'tex2d') @@ -4760,6 +5853,44 @@ def image_compare(self, ops, mods, how): call = '%s.SampleCmpLevelZero(%s)' % (tex, args) self.set_v(reg_range(ops[0])[1], 'U(%s)' % call) + def op_image_gather4_lz(self, ops, mods): + """image_gather4_lz on a 2D texture: the one channel dmask names, from the 2x2 footprint at level 0. + + The four result dwords are the texels in the order Gather*() returns them, (u0,v1), (u1,v1), (u1,v0), + (u0,v0): gather4 is the D3D Gather operation, and compilers map Gather's four results straight onto the + four destination VGPRs. Gather always reads the most detailed level, which is what _lz names. Offsets + (_o), compare (_c), an explicit or biased level, other dimensions and result-layout modifiers (d16, tfe, + lwe, a16, unorm, r128) would change the address or the result and are refused by name. + """ + for m in mods: + if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): + raise Unsupported('image_gather4_lz modifier %s' % m) + dims = [m[4:] for m in mods if m.startswith('dim:')] + masks = [int(m[6:], 0) for m in mods if m.startswith('dmask:')] + if dims != ['SQ_RSRC_IMG_2D'] or len(masks) != 1: + raise Unsupported('image_gather4_lz on %s' % (dims or 'no dim')) + channel = {1: 'Red', 2: 'Green', 4: 'Blue', 8: 'Alpha'}.get(masks[0]) + if channel is None: + raise Unsupported('image_gather4_lz dmask %#x: gather reads exactly one channel' % masks[0]) + dst = reg_range(ops[0]) + if len(ops) != 4 or not dst or dst[0] != 'v' or dst[2] - dst[1] != 3: + raise Unsupported('image_gather4_lz operands %s' % ', '.join(ops)) + coords = ops[1] + if coords.startswith('['): + cs = [c.strip() for c in coords[1:-1].split(',')] + else: + r = reg_range(coords) + cs = ['v%d' % n for n in range(r[1], r[2] + 1)] + if len(cs) != 2: + raise Unsupported('image_gather4_lz with %d address registers' % len(cs)) + tex = self.pipe.resource(self.descriptor(ops[2]), 'tex2d') + heap = self.heap_sampler(ops[3]) + words = None if heap else self.const_words(ops[3]) + smp = heap or self.pipe.sampler(tuple(words) if words else self.descriptor(ops[3])) + self.emit('t = %s.Gather%s(%s, float2(%s, %s));' % (tex, channel, smp, self.f(cs[0]), self.f(cs[1]))) + for i, comp in enumerate('xyzw'): + self.set_v(dst[1] + i, 'U(t.%s)' % comp) + def op_image_sample_c(self, ops, mods): self.image_compare(ops, mods, 'c') @@ -4772,9 +5903,18 @@ def op_image_sample_c_l(self, ops, mods): def op_image_sample(self, ops, mods): self.image(ops, mods, 'sample') + def op_image_sample_b(self, ops, mods): + self.image(ops, mods, 'b') + + def op_image_sample_d(self, ops, mods): + self.image(ops, mods, 'd') + def op_image_sample_lz(self, ops, mods): self.image(ops, mods, 'lz') + def op_image_get_lod(self, ops, mods): + self.image(ops, mods, 'get_lod') + def op_image_sample_l(self, ops, mods): self.image(ops, mods, 'l') @@ -4813,12 +5953,6 @@ def lod_sampler_words(self, name, words, mip_filter_none_ok=False): % (name, words[1] & 0xfff, (words[1] >> 12) & 0xfff)) return words - def op_image_sample_b(self, ops, mods): - self.image(ops, mods, 'b') - - def op_image_get_lod(self, ops, mods): - self.image(ops, mods, 'get_lod') - def op_image_load(self, ops, mods): self.image(ops, mods, 'load') @@ -4886,98 +6020,32 @@ def op_image_store(self, ops, mods): cs = ['v%d' % n for n in range(r[1], r[2] + 1)] if r and r[0] == 'v' else [] if len(cs) != 2: raise Unsupported('%s with %d address registers: x and y expected' % (name, len(cs))) - words = [self.u('v%d' % n) for n in range(data[1], data[2] + 1)] - if self.kind == 'cs': - if not all(re.fullmatch(r'v\d+', c) and int(c[1:]) <= 255 for c in cs): - raise Unsupported('compute image_store requires full-width VGPR coordinates') - key = self.fixed_table_image(ops[2], name) - else: - key = self.descriptor(ops[2]) - if d16: - # RDNA 2 ISA §8.2.5: RG occupy VDATA, BA occupy VDATA+1, low half first. - rgba = ['f16tof32(%s & 0xffffu), f16tof32(%s >> 16)' % (word, word) for word in words] - value = 'float4(%s)' % ', '.join(rgba) - else: - value = 'asfloat(uint4(%s))' % ', '.join(words) - image = self.pipe.uav(key, 'tex2d') + image = self.pipe.image_uav(self.descriptor(ops[2]), 'tex2d') + value = 'asfloat(uint4(%s))' % ', '.join(self.u('v%d' % n) for n in range(data[1], data[1] + 4)) body = '%s[uint2(%s, %s)] = %s;' % (image, self.u(cs[0]), self.u(cs[1]), value) self.emit(body if self.exec_known else 'if (exec & 1) ' + body) - def gather_2d_setup(self, name, ops, mods, addr_count, addr_label, *, mip_preclamp): - if self.kind not in ('ps', 'cs') or len(ops) != 4: - raise Unsupported('%s requires a pixel or compute stage and four operands' % name) + def op_image_gather4_c_lz(self, ops, mods): + """image_gather4_c_lz: four red-channel depth comparisons at view mip zero. + + The address dwords are the reference, then u and v, as on the hardware gather. The comparison + function and the depth compare live in the constant sampler, so the guest words are bound as a + SamplerComparisonState and the sample profile is the one pixel_aot.check_gather_sampler already + checks for comparison gathers. Only red is in contract: gather4_c compares the resource's red + component and D3D's gather4_c takes a single-component view. + """ + name = 'image_gather4_c_lz' + if self.kind != 'ps' or len(ops) != 4: + raise Unsupported('%s requires a pixel stage and four operands' % name) for modifier in mods: if not (modifier.startswith(('dim:', 'dmask:')) or modifier in ('dlc', 'glc', 'slc')): raise Unsupported('%s modifier %s' % (name, modifier)) if [m for m in mods if m.startswith('dim:')] != ['dim:SQ_RSRC_IMG_2D']: raise Unsupported('%s requires a 2D texture' % name) - channels = {'dmask:0x1': ('Red', 0), 'dmask:0x2': ('Green', 1), 'dmask:0x4': ('Blue', 2), 'dmask:0x8': ('Alpha', 3)} masks = [m for m in mods if m.startswith('dmask:')] - if len(masks) != 1 or masks[0] not in channels: - raise Unsupported('%s requires a one-hot dmask' % name) - dst, addr, sampler = (reg_range(ops[i]) for i in (0, 1, 3)) - if not dst or dst[0] != 'v' or dst[2] - dst[1] != 3 or dst[2] > 255: - raise Unsupported('%s requires four destination registers' % name) - if not addr or addr[0] != 'v' or addr[2] - addr[1] + 1 != addr_count or addr[2] > 255: - raise Unsupported('%s requires %s' % (name, addr_label)) - words = self.const_words(ops[3]) if sampler and sampler[0] == 's' and sampler[2] - sampler[1] == 3 else None - if words is None: - raise Unsupported('%s requires a constant sampler' % name) - from pixel_aot import check_gather_sampler - profiled = gather_2d_profile_words(words) - if not mip_preclamp and (words[2] & (1 << 28)): - profiled = (profiled[0], profiled[1], profiled[2] | (1 << 28), profiled[3]) - try: - # _lz reads mip zero of the bound view; _l checks all other sampler fields against - # the 2D gather profile and enforces words[1] MAX_LOD plus view mip bounds in HLSL. - check_gather_sampler(profiled, 1, comparison=False) - except ValueError as error: - raise Unsupported('%s sampler: %s' % (name, error)) from error - key = self.fixed_table_image(ops[2], name) if self.kind == 'cs' else self.descriptor(ops[2]) - tex = self.pipe.resource(key, 'tex2d') - return dst, addr, words, channels[masks[0]], tex - - def op_image_gather4_lz(self, ops, mods): - dst, addr, words, (channel_name, _), tex = self.gather_2d_setup( - 'image_gather4_lz', ops, mods, 2, 'two contiguous address registers', mip_preclamp=True) - smp = self.pipe.sampler(tuple(words)) - u, v = (self.f('v%d' % i) for i in range(addr[1], addr[2] + 1)) - self.emit('t = %s.Gather%s(%s, float2(%s, %s));' % (tex, channel_name, smp, u, v)) - for i, component in enumerate('xyzw', dst[1]): - self.set_v(i, 'U(t.%s)' % component) - - def op_image_gather4_l(self, ops, mods): - """image_gather4_l on a 2D texture with explicit LOD and a validated constant sampler.""" - dst, addr, words, (_, channel_index), tex = self.gather_2d_setup( - 'image_gather4_l', ops, mods, 3, 'three contiguous address registers', mip_preclamp=False) - self.pipe.uses_gather_2d_lod = True - max_lod = ((words[1] >> 12) & 0xfff) / 256.0 - u, v, lod = (self.f('v%d' % i) for i in range(addr[1], addr[2] + 1)) - self.emit('t = gather_2d_lod(%s, float2(%s, %s), %s, %d, %sf);' % (tex, u, v, lod, channel_index, repr(max_lod))) - for i, component in enumerate('xyzw', dst[1]): - self.set_v(i, 'U(t.%s)' % component) - - def op_image_gather4_c_lz(self, ops, mods): - """image_gather4_c_lz: four red-channel depth comparisons at view mip zero. - - The address dwords are the reference, then u and v, as on the hardware gather. The comparison - function and the depth compare live in the constant sampler, so the guest words are bound as a - SamplerComparisonState and the sample profile is the one pixel_aot.check_gather_sampler already - checks for comparison gathers. Only red is in contract: gather4_c compares the resource's red - component and D3D's gather4_c takes a single-component view. - """ - name = 'image_gather4_c_lz' - if self.kind != 'ps' or len(ops) != 4: - raise Unsupported('%s requires a pixel stage and four operands' % name) - for modifier in mods: - if not (modifier.startswith(('dim:', 'dmask:')) or modifier in ('dlc', 'glc', 'slc')): - raise Unsupported('%s modifier %s' % (name, modifier)) - if [m for m in mods if m.startswith('dim:')] != ['dim:SQ_RSRC_IMG_2D']: - raise Unsupported('%s requires a 2D texture' % name) - masks = [m for m in mods if m.startswith('dmask:')] - if masks != ['dmask:0x1']: - raise Unsupported('%s requires red dmask 0x1' % name) - dst, addr, image, sampler = (reg_range(ops[i]) for i in (0, 1, 2, 3)) + if masks != ['dmask:0x1']: + raise Unsupported('%s requires red dmask 0x1' % name) + dst, addr, image, sampler = (reg_range(ops[i]) for i in (0, 1, 2, 3)) if not dst or dst[0] != 'v' or dst[2] - dst[1] != 3 or dst[2] > 255: raise Unsupported('%s requires four destination registers' % name) if not addr or addr[0] != 'v' or addr[2] - addr[1] != 2 or addr[2] > 255: @@ -5042,17 +6110,116 @@ def op_v_cvt_pk_u8_f32(self, ops, mods): self.set_v(dst[1], '((%s & ~(0xffu << %s)) | (((((%s - 1u) < 0x7f800000u) ? uint(round(min(%s, 255.0))) : 0u) & 0xffu) << %s))' % (rest, shift, bits, value, shift)) - def op_s_ff1_i32_b32(self, ops, mods): - if self.kind != 'cs' or mods or len(ops) != 2 or ops[1] != 'exec_lo': - raise Unsupported('s_ff1_i32_b32 requires compute exec_lo') - dst = reg_range(ops[0]) - if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: - raise Unsupported('s_ff1_i32_b32 requires one SGPR destination') - if self.past_entry or not self.exec_known: - raise Unsupported('s_ff1_i32_b32 requires the compute entry EXEC mask') - # At dispatch entry even the last partial wave starts at lane zero. - # FF1 reports its index and leaves SCC unchanged. - self.set_s(dst[1], '0u', ('const', 0)) + WATERFALL_CROSS_LANE = re.compile(r'_dpp$|permlane|readlane|writelane|readfirstlane|^s_store|^s_buffer_store|' + r'^s_atomic|^s_buffer_atomic|^s_scratch|^s_sendmsg|^s_endpgm|^s_setpc|^s_getpc|' + r'^s_swappc|^s_dcache|^exp|^s_movrel|^v_movrel|^s_setreg|^ds_gws|^s_barrier') + + def waterfall(self, s, v): + """Check that the v_readfirstlane_b32 s<s>, v<v> at self.pc heads a waterfall loop the one-lane model runs + exactly as the hardware runs it for this lane; raise Unsupported otherwise. + + The form (LLVM SIInstrInfo.cpp emitLoadScalarOpsFromVGPRLoop, wave32), measured in the title's bindless + texture reads: + H: v_readfirstlane_b32 sN, vM + v_cmpx_eq_u32/i32 sN, vM exec = the lanes holding that value + ...body... + s_andn2_wrexec_b32 sX, sX exec = sX & ~exec (sX: lanes not done yet), SCC = exec != 0 + s_cbranch_scc1 H + Hardware runs the body once per distinct vM value; a lane is active in exactly the iteration whose sN is + its own vM. The one-lane model takes sN = this lane's vM, so its single active iteration is that one, and + the wrexec then leaves this lane's exec bit 0 as hardware does. That holds when: + - the body is straight-line (no other branch, no branch into it) and makes no cross-lane read or scalar + side effect (scalar stores, messages, exports): iterations for other lanes only run SALU work; + - every SGPR the body writes, sX apart, is written before it is read in the body (no loop-carried value; + sX's own bit is this lane's pending bit in both models); + - none of those SGPRs is read after the loop before it is written again: their hardware values belong to + the last lane serviced, the model's to this lane. + """ + index = {off: i for i, (off, _, _, _) in enumerate(self.ins)} + h = index[self.pc] + if h + 1 >= len(self.ins): + raise Unsupported('v_readfirstlane_b32 requires a proven uniform source') + _, _, cname, casm = self.ins[h + 1] + _, cops, cmods = parse(casm) + if (not re.fullmatch(r'v_cmpx_eq_[iu]32_e(32|64)', cname) or cmods or + sorted(cops) != sorted(['s%d' % s, 'v%d' % v])): + raise Unsupported('v_readfirstlane_b32 requires a proven uniform source') + # The loop head is the readfirstlane or a run of waits / nops just above it (LLVM places the wait for the + # index VGPR's load at the head when the load is outstanding). + t = h + while t > 0 and self.ins[t - 1][2] in ('s_waitcnt', 's_nop'): + t -= 1 + heads = {off for off, _, _, _ in self.ins[t:h + 1]} + back = [i for i, (off, _, name, asm) in enumerate(self.ins) + if i > h and name.startswith(('s_cbranch', 's_branch')) + and int(parse(asm)[1][0].split('_')[1], 16) in heads] + # s_andn2_wrexec writes the same value to exec and to its destination and sets SCC = (value != 0), so + # directly after it s_cbranch_execnz tests exactly what s_cbranch_scc1 tests (checked below: the wrexec + # is the instruction just before the back edge). The title's vertex shaders close the loop with execnz. + if len(back) != 1 or self.ins[back[0]][2] not in ('s_cbranch_scc1', 's_cbranch_execnz'): + raise Unsupported('waterfall loop without one s_cbranch_scc1 back edge') + b = back[0] + t = index[int(parse(self.ins[b][3])[1][0].split('_')[1], 16)] + wname, wasm = self.ins[b - 1][2], self.ins[b - 1][3] + wops = parse(wasm)[1] + wide = wname == 's_andn2_wrexec_b64' + if (wname not in ('s_andn2_wrexec_b32', 's_andn2_wrexec_b64') or len(wops) != 2 or wops[0] != wops[1] or + not reg_range(wops[0]) or reg_range(wops[0])[0] != 's' or + reg_range(wops[0])[2] - reg_range(wops[0])[1] != int(wide)): + raise Unsupported('waterfall loop not closed by s_andn2_wrexec') + pending = set(range(reg_range(wops[0])[1], reg_range(wops[0])[2] + 1)) + inner = {off for off, _, _, _ in self.ins[t + 1:b + 1]} + for off, _, name, asm in self.ins: + if name.startswith(('s_cbranch', 's_branch')): + target = int(parse(asm)[1][0].split('_')[1], 16) + if target in inner or (off in inner and off != self.ins[b][0]): + raise Unsupported('waterfall loop with another branch') + body = self.ins[t:b + 1] + body_writes = set().union(*(waterfall_sgpr_access(n, a, wide)[1] for _, _, n, a in body)) + written, high = set(), set() + for off, _, name, asm in body: + if off != self.pc and self.WATERFALL_CROSS_LANE.search(name): + raise Unsupported('waterfall loop body with %s' % name) + reads, writes, mask_high, _ = waterfall_sgpr_access(name, asm, wide) + if 124 in reads | writes: + raise Unsupported('waterfall loop body uses m0') + carried = (reads - written) & body_writes + if carried - pending: + raise Unsupported('waterfall loop carries s%d' % min(carried - pending)) + written |= writes + high = (high - writes) | mask_high + live = (written | high) - pending + # Every path from the loop exit: each of these SGPRs is written before any read. A wave64 mask's high half + # (hardware-only, see waterfall_sgpr_access) may only be read as the high half of a mask. + stack, seen = [(b + 1, frozenset(live), frozenset(high - pending))], set() + while stack: + i, regs, high = stack.pop() + while regs and i < len(self.ins) and (i, regs, high) not in seen: + seen.add((i, regs, high)) + off, _, name, asm = self.ins[i] + reads, writes, mask_high, high_reads = waterfall_sgpr_access(name, asm, wide) + bad = (reads - (high_reads & high)) & regs + if bad: + raise Unsupported('s%d read after its waterfall loop' % min(bad)) + regs = regs - writes + high = (high - writes) | (mask_high & regs) + if name == 's_endpgm' or name.startswith(('s_setpc', 's_swappc')): + break + if name.startswith(('s_cbranch', 's_branch')): + target = index.get(int(parse(asm)[1][0].split('_')[1], 16)) + if target is None: + raise Unsupported('waterfall exit path leaves the program') + stack.append((target, regs, high)) + if name == 's_branch': + break + i += 1 + # One pass: the lane's own iteration is the only one in which it is active, and it leaves the loop with its + # exec bit 0, so for this lane the back edge is never taken. Emitting it as a branch would leave a loop + # whose model condition repeats the first pass exactly (the one-lane state is the same each time), so a + # body that does not restore exec would spin until a guard; without the edge it runs once. + if not hasattr(self, 'waterfall_back'): + self.waterfall_back = set() + self.waterfall_back.add(self.ins[b][0]) # ---- slot 57 mesh stage: instructions mesh_skeleton() puts in place of the group-memory exchanges ---- def op_x2w_mesh_lane0(self, ops, mods): @@ -5142,21 +6309,50 @@ def op_v_mbcnt_hi_u32_b32(self, ops, mods): self.op_v_mbcnt_lo_u32_b32(ops, mods, high=True) def op_v_readfirstlane_b32(self, ops, mods): + # D = S0 of the first active lane (AMD RDNA 2 ISA; LLVM selects it for a VGPR-to-SGPR copy of a value the + # divergence analysis found uniform, SIFixSGPRCopies). With a lane-invariant source (see set_v) every + # lane's own value is that value. Branches are allowed: invariance is cleared at every branch target. src, dst = reg_range(ops[1]), reg_range(ops[0]) - past_entry = getattr(self, 'past_entry', True) - # Past the entry block of a branch-free program is only dead code after s_endpgm: nothing to recompute. - if (mods or not self.tracks_uniformity() or not dst or dst[0] != 's' or dst[1] != dst[2] or - not src or src[0] != 'v' or src[1] != src[2] or src[1] not in self.uniform_v or - (src[1] not in getattr(self, 'uniform_expr', {}) or not getattr(self, 'has_branches', False) - if past_entry else not getattr(self, 'exec_known', False))): + offsets = [off for off, _, _, _ in getattr(self, 'ins', ())] + here = getattr(self, 'pc', None) + following = self.ins[offsets.index(here) + 1][2] if here in offsets[:-1] else '' + if (not mods and dst and dst[0] == 's' and dst[1] == dst[2] and src and src[0] == 'v' and src[1] == src[2] + and src[1] not in self.uniform_v and getattr(self, 'partial_uniform', {}).get(src[1]) is None + and following.startswith('v_cmpx_eq_')): + # a waterfall loop head (see waterfall): this lane's own value + self.waterfall(dst[1], src[1]) + # An inactive lane's vM is stale (hardware never uses it: no iteration serves that lane), but the HLSL + # evaluates the body's descriptor reads in every lane, and the heap memory is a root SRV with no bounds + # check; index 0 keeps that read inside the heap. Active lanes read their own vM as hardware does. + self.set_s(dst[1], '((exec & 1) != 0 ? %s : 0u)' % self.u(ops[1])) + return + partial = getattr(self, 'partial_uniform', {}).get(src[1]) if src and src[0] == 'v' else None + if (not mods and dst and dst[0] == 's' and partial is not None and + partial['epoch'] == getattr(self, 'exec_writes', 0)): + # The source was written, in the lanes active then, from a lane-invariant value (or a chain of such + # writes, see partial_shadow), and exec has not been written since: the first active lane holds that + # value. Lanes inactive now kept an older VGPR value, but the SGPR is the wave's, so every lane takes the + # value itself, from shadows assigned in all lanes at the writes. (With no active lane the hardware + # reads lane 0; that case is not modelled.) + self.materialize_shadow(partial) + self.set_s(dst[1], 'xv%d' % src[1]) + return + if (mods or not self.exec_known or not dst or dst[0] != 's' or + not src or src[0] != 'v' or src[1] not in self.uniform_v): + if (not mods and getattr(self, 'kind', None) == 'ps' and os.environ.get('X2W_PS_WAVE_UNION') == '1' + and dst and dst[0] == 's' + and dst[1] == dst[2] and src and src[0] == 'v' and src[1] == src[2] + and getattr(self, 'wave_plan', None) and self.wave_uniform + and getattr(self, 'pc', None) in self.wave_uniform[1]): + # X2W_PS_WAVE_UNION=1, in a program whose wave reductions it took: the source is written only by + # VALU ops of host-uniform scalars (wave_union_uniform), so every lane whose guest exec bit is set + # holds the same value; x2w_readfirstlane reads it from the first such host lane. + self.set_s(dst[1], 'x2w_readfirstlane(%s, (exec & 1u) != 0)' % self.u(ops[1]), uniform=True) + self.needs_sm6 = True + self.wave_union_used = True + return raise Unsupported('v_readfirstlane_b32 requires a proven uniform source') - if past_entry: - # The first active lane ran the definition: no join, EXEC write or overwrite of the VGPR and no write - # of a scalar it read lies between them. A lane inactive at the definition kept an older VGPR value, - # so the read recomputes the definition from the scalars instead of reading this lane's copy. - self.set_s(dst[1], self.uniform_expr[src[1]]) - else: - self.set_s(dst[1], self.u(ops[1])) + self.set_s(reg_range(ops[0])[1], self.u(ops[1])) # ---- SGPR spill to VGPR lanes (#2125, item E) -------------------------------------------- # The compiler parks a scalar in one lane of a VGPR: `v_writelane_b32 vN, sM, k` writes sM into lane k @@ -5211,62 +6407,564 @@ def op_v_writelane_b32(self, ops, mods): value = self.S(src[1]) sym = self.sym.get(src[1]) if (self.sym.get(src[1]) or ('',))[0] == 'const' else None uniform = self.uniform_source(ops[1]) - slots = self.__dict__.setdefault('spill_slots', {}) + slots = self.__dict__.setdefault('lane_spill_slots', {}) slots[(n, lane)] = (sym, uniform) self.emit('sp%d_%d = %s;' % (n, lane, value)) + def op_v_ldexp_f32(self, ops, mods): + """V_LDEXP_F32 D, S0, S1: D = S0 * 2^S1, S1 a signed integer (x2w_ldexp). S0 takes neg/abs, the result the + output modifiers; a modifier on S1 (an integer) is refused.""" + if len(ops) != 3: + raise Unsupported('v_ldexp_f32 with %d operands, expected 3' % len(ops)) + if ops[2].startswith(('-', '|')) and not re.fullmatch(r'-\d+', ops[2]): + raise Unsupported('v_ldexp_f32 with a modifier on the exponent %s' % ops[2]) + if any(m not in ('clamp', 'mul:2', 'mul:4', 'div:2') for m in mods): + raise Unsupported('v_ldexp_f32 with %s' % mods) + return self.set_vf(reg_range(ops[0])[1], 'x2w_ldexp(%s, %s)' % (self.f(ops[1]), self.u(ops[2])), mods) + + def wave_union_step(self, step): + """One instruction of a recognised wave64 reduction (wave_union_plan, X2W_PS_WAVE_UNION=1).""" + kind = step[0] + if kind == 'skip': + return None + if kind == 'reduce': + _, var, op, src, ident, mask = step + wave_vars = self.__dict__.setdefault('wave_vars', []) + if var not in wave_vars: + wave_vars.append(var) + # Every HLSL lane of this block runs the statement; a lane whose guest exec bit (the saved mask) is 0 + # gives the identity, as the guest's v_cndmask does. The reduction is over the host wave's lanes here. + self.emit('%s = %s((%s & 1u) ? %s : %su);' % (var, WAVE_UNION_OPS[op], self.u('s%d' % reg_range(mask)[1]), + self.u(src), ident)) + self.needs_sm6 = True + self.wave_union_used = True + return None + _, var, dst = step # 'read': v_readlane_b32 dst, vR, 63 of the reduction held in var + self.set_s(reg_range(dst)[1], var, uniform=True) + return None + def op_v_readlane_b32(self, ops, mods): if len(ops) != 3 or reg_range(ops[1]) is None or reg_range(ops[1])[0] != 'v': raise Unsupported('v_readlane_b32 requires a VGPR source') n, dst, lane = self.spill_operands('v_readlane_b32', ops, mods) if dst is None: raise Unsupported('v_readlane_b32 requires an SGPR destination') - slot = getattr(self, 'spill_slots', {}).get((n, lane)) + slot = getattr(self, 'lane_spill_slots', {}).get((n, lane)) if slot is None: raise Unsupported('v_readlane_b32 reads v%d lane %d before any v_writelane_b32 wrote it' % (n, lane)) sym, uniform = slot self.set_s(dst[1], 'sp%d_%d' % (n, lane), sym=sym, uniform=uniform) + def pair(self, tok, *, unsigned_valu=False): + """(low, high) uint expressions of a 64-bit integer operand: a register pair or an inline integer constant + (sign-extended to 64 bits). Unsigned VALU sources zero-extend a 32-bit literal.""" + r = reg_range(tok) + if r: + if r[2] != r[1] + 1: + raise Unsupported('64-bit operand %s' % tok) + if r[0] == 'v': + self.used_v.update((r[1], r[2])) + return 'v%d' % r[1], 'v%d' % r[2] + return self.S(r[1]), self.S(r[2]) + try: + value = int(tok, 0) + except ValueError: + raise Unsupported('64-bit operand %r' % tok) + if tok.startswith('0x') and 0 <= value <= (0xffffffff if unsigned_valu else 0x7fffffff): + # RDNA 2 ISA 6.2.1, Literal Expansion to 64 bits. Both logical shifts read S1.u64 (12.9). + return '0x%08xu' % value, '0x00000000u' + if not -16 <= value <= 64 or tok.startswith('0x'): + raise Unsupported('64-bit literal operand %s' % tok) + value &= 0xffffffffffffffff + return '0x%08xu' % (value & 0xffffffff), '0x%08xu' % (value >> 32) + + def shift64(self, ops, mods, helper): + """v_l{sh,sh}rrev_b64 D, S0, S1: D = S1 shifted by S0[5:0]; the shift count comes first ("rev").""" + if mods: + raise Unsupported('64-bit shift with %s' % mods) + d = reg_range(ops[0]) + if not d or d[0] != 'v' or d[2] != d[1] + 1: + raise Unsupported('64-bit shift destination %s' % ops[0]) + low, high = self.pair(ops[2], unsigned_valu=True) + count = self.u(ops[1]) + self.uses_q = True + # Read both source words into q before either destination word is written: D and S1 may overlap. + self.emit('q = uint2(%s_lo(%s, %s, %s), %s_hi(%s, %s, %s));' % (helper, low, high, count, helper, low, high, count)) + self.set_v(d[1], 'q.x') + self.set_v(d[1] + 1, 'q.y') + + def carry_op(self, ops, mods, kind, carry_in): + """v_{add,sub,subrev}_co[_ci]_u32 D, SDST, S0, S1[, CI]: 32-bit add or subtract with a carry or borrow out. + + AMD RDNA 2 ISA: V_ADD_CO_CI_U32 D = S0 + S1 + CI, carry = the 33rd bit; V_SUB_CO_CI_U32 D = S0 - S1 - CI, + borrow = S1 + CI > S0 (as 33-bit values); SUBREV swaps S0 and S1; the _co forms have no carry-in. LLVM + VOP2Instructions.td defines V_ADD_CO_CI_U32 as gfx10's name for v_addc_u32 (VOP2b, carry-out an SGPR mask). + The carry is the lane's bit of SDST, as v_cmp writes it; CI must be a lane mask (vcc, exec or an SGPR the + translation holds as a mask). Both results go through q, so D or SDST may overlap a source. + """ + if mods: + raise Unsupported('v_%s_co%s_u32 with %s' % (kind, '_ci' if carry_in else '', ' '.join(mods))) + if len(ops) != (5 if carry_in else 4): + raise Unsupported('v_%s_co%s_u32 with %d operands' % (kind, '_ci' if carry_in else '', len(ops))) + d = reg_range(ops[0]) + if not d or d[0] != 'v' or d[1] != d[2]: + raise Unsupported('carry operation destination %s' % ops[0]) + a, b = self.u(ops[2]), self.u(ops[3]) + if kind == 'subrev': + a, b = b, a + c = '0u' + if carry_in: + r = reg_range(ops[4]) + if not (ops[4] in ('vcc', 'vcc_lo', 'exec', 'exec_lo') or (r and r[0] == 's' and r[1] in self.masks)): + raise Unsupported('carry-in %s is not a lane mask' % ops[4]) + c = '(%s & 1u)' % self.u(ops[4] if not r else 's%d' % r[1]) + if kind == 'add': + value, carry = '%s + %s + %s' % (a, b, c), '((%s + %s) < %s || (%s + %s + %s) < (%s + %s))' % ( + a, b, a, a, b, c, a, b) + else: + value, carry = '%s - %s - %s' % (a, b, c), '(%s > %s || (%s - %s) < %s)' % (b, a, a, b, c) + self.uses_q = True + self.emit('q = uint2(%s, %s ? 1u : 0u);' % (value, carry)) + self.set_v(d[1], 'q.x') + sdst = ops[1] + r = reg_range(sdst) + self.write_compare(False, sdst if not r else 's%d' % r[1], 'q.y') + + def pc_data_load(self, ops, mods, count): + """GLOBAL_LOAD_DWORD{,X2,X3,X4} through an address pc_data_proof traced to this stage's image (virtual + address 0). Each dword's 64-bit address (VADDR, no offset modifier) reads image word address / 4; an + address that is not word-aligned or lies outside the image reads 0 (hardware would read other memory).""" + role = getattr(self, 'pc_data', {}).get(getattr(self, 'pc', None), ('',)) + if role[0] != 'load': + raise Unsupported('global_load without a proven s_getpc_b64 image address') + d, a = reg_range(ops[0]), reg_range(ops[1]) + if any(m not in ('glc', 'slc', 'dlc') for m in mods): + raise Unsupported('global_load with %s' % ' '.join(mods)) + if not d or d[0] != 'v' or d[2] - d[1] + 1 != count: + raise Unsupported('global_load destination %s' % ops[0]) + # The pair itself must point into the image this stage holds: a lost bound_vertex_code image (code only) + # would otherwise read 0 everywhere without a refusal. + if not role[2] < len(self.pc_image) // 4 * 4: + raise Unsupported('global_load: the s_getpc_b64 address %#x is outside the %d-byte shader image' + % (role[2], len(self.pc_image))) + words = len(self.pc_image) // 4 + self.pc_image_used = True + self.emit('w = %s;' % self.u('v%d' % a[1])) + self.emit('a = %s;' % self.u('v%d' % (a[1] + 1))) + values = [] + for k in range(count): + at = 'w + %du' % (4 * k) if k else 'w' + high = '(a + (%s < w ? 1u : 0u))' % at if k else 'a' + values.append('(%s == 0u && %s < %du && ((%s) & 3u) == 0u ? x2w_pcimage[min((%s) >> 2, %du)] : 0u)' + % (high, at, 4 * words, at, at, words - 1)) + for k, value in enumerate(values): + self.set_v(d[1] + k, value) + + def op_global_load_dword(self, ops, mods): + self.pc_data_load(ops, mods, 1) + + def op_global_load_dwordx2(self, ops, mods): + self.pc_data_load(ops, mods, 2) + + def op_global_load_dwordx3(self, ops, mods): + self.pc_data_load(ops, mods, 3) + + def op_global_load_dwordx4(self, ops, mods): + self.pc_data_load(ops, mods, 4) + + def op_v_add_co_ci_u32(self, ops, mods): + self.carry_op(ops, mods, 'add', True) + + def op_v_sub_co_ci_u32(self, ops, mods): + self.carry_op(ops, mods, 'sub', True) + + def op_v_subrev_co_ci_u32(self, ops, mods): + self.carry_op(ops, mods, 'subrev', True) + + def op_v_add_co_u32(self, ops, mods): + self.carry_op(ops, mods, 'add', False) + + def op_v_sub_co_u32(self, ops, mods): + self.carry_op(ops, mods, 'sub', False) + + def op_v_subrev_co_u32(self, ops, mods): + self.carry_op(ops, mods, 'subrev', False) + + def op_v_lshrrev_b64(self, ops, mods): + self.shift64(ops, mods, 'x2w_lshr64') + + def op_v_lshlrev_b64(self, ops, mods): + self.shift64(ops, mods, 'x2w_lshl64') + + def half_op(self, ops, mods, fn): + """v_{min,max}_f16: the binary16 result goes to D[15:0]; gfx10 keeps D[31:16] (LLVM + GCNSubtarget::zeroesHigh16BitsOfDest: "On gfx10, all 16-bit instructions preserve the high bits").""" + if mods: + raise Unsupported('f16 operation with %s' % mods) + if any(t.startswith(('-', '|')) and not re.match(r'-[\d.]', t) for t in ops[1:3]): + raise Unsupported('f16 operation with source modifiers') + d = reg_range(ops[0])[1] + self.used_v.add(d) + a, b = ('f16tof32(%s)' % self.h(t) for t in ops[1:3]) + self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(%s(%s, %s))' % (d, fn, a, b)) + + def half_arithmetic(self, ops, mods, form, arity): + if len(ops) != arity + 1 or mods: + raise Unsupported('binary16 arithmetic operands or modifiers: %s %s' % (ops, mods)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[1] != dst[2]: + raise Unsupported('binary16 arithmetic destination %s' % ops[0]) + d = dst[1] + self.used_v.add(d) + args = ['f16tof32(%s)' % self.h(t) for t in ops[1:]] + expr = form.format(*args, dest='f16tof32(v%d)' % d) + self.set_v(d, '(v%d & 0xffff0000u) | %s' % (d, self.to_f16(expr))) + + def op_v_mul_f16(self, ops, mods): + # A finite binary16 product fits exactly in binary32 before rounding. + self.half_arithmetic(ops, mods, '{0} * {1}', 2) + + def op_v_fmac_f16(self, ops, mods): + self.half_arithmetic(ops, mods, 'x2w_half_madd_odd({0}, {1}, {dest})', 2) + + def op_v_rsq_f16(self, ops, mods): + self.half_arithmetic(ops, mods, 'rsqrt({0})', 1) + + def op_v_min_f16(self, ops, mods): + self.half_op(ops, mods, 'min') + + def op_v_max_f16(self, ops, mods): + self.half_op(ops, mods, 'max') + + def packed_half(self, ops, mods, fn): + """v_pk_{min,max}_f16: two binary16 lanes. Result half i reads, from each source, the half picked by + op_sel (low result) or op_sel_hi (high result); the disassembler prints only non-default selections.""" + sel, sel_hi = [0, 0], [1, 1] + for m in mods: + if m.startswith('op_sel:['): + sel = [int(x) for x in m[8:-1].split(',')] + elif m.startswith('op_sel_hi:['): + sel_hi = [int(x) for x in m[11:-1].split(',')] + else: + raise Unsupported('packed f16 operation with %s' % m) + if len(sel) != 2 or len(sel_hi) != 2: + raise Unsupported('packed f16 selection %s' % mods) + words = [] + for index, tok in enumerate(ops[1:3]): + r = reg_range(tok) + if r: + words.append(self.u(tok)) + elif re.fullmatch(r'0x[0-9a-f]+', tok) and not sel[index] and not sel_hi[index]: + words.append(self.u(tok)) # a literal read only through its low half + elif tok == '0': + words.append('0x00000000u') # the inline integer 0: every bit is 0, so each half reads +0.0 + else: + raise Unsupported('packed f16 operand %s with selection %s/%s' % (tok, sel[index], sel_hi[index])) + def half(word, high): + return 'f16tof32(%s >> 16)' % word if high else 'f16tof32(%s)' % word + low = 'f32tof16(%s(%s, %s))' % (fn, half(words[0], sel[0]), half(words[1], sel[1])) + high = 'f32tof16(%s(%s, %s))' % (fn, half(words[0], sel_hi[0]), half(words[1], sel_hi[1])) + self.set_v(reg_range(ops[0])[1], '%s | (%s << 16)' % (low, high)) + + def op_v_pk_min_f16(self, ops, mods): + self.packed_half(ops, mods, 'min') + + def op_v_pk_max_f16(self, ops, mods): + self.packed_half(ops, mods, 'max') + + # ---- binary16 arithmetic, emulated in f32 (draws compile with fxc 5.1: no native float16) ---- + # Every binary16 value is exact in f32 and so is a product of two (22 bits, exponents 2^-48..2^32). The sum + # p + c is taken with its exact error (TwoSum, all steps `precise`), the f32 result is rounded to odd when inexact + # (x2w_f16_fma), and to_f16 rounds that once: rounding to odd at 24 bits and then to 11 bits gives the single + # rounding of the exact value (24 >= 11 + 2). Every intermediate is a multiple of 2^-48, so no f32 denormal + # (flushed by D3D) arises; inf and NaN return the plain f32 result. Only MODE[3:2] = 0 (nearest even) is taken: + # these names are not in ROUND16_LOWERED, so check_round16 refuses them under toward zero. + def f16_bits(self, tok, high=False, what='f16 operation', mods=True, literal_high=False): + """uint expression whose bits 15:0 are a binary16 source: half `high` of a register, or a constant's binary16 + form (inline floats as binary16, inline integers and literals as raw bits), with abs then neg on bit 15.""" + neg, body = self.split_neg(tok) + m = re.fullmatch(r'\|(.+)\|', body) or re.fullmatch(r'abs\((.+)\)', body) + absolute = bool(m) + if m: + body = m.group(1) + if (neg or absolute) and not mods: + raise Unsupported('%s source modifier on %s' % (what, tok)) + r = reg_range(body) + if r: + if r[1] != r[2] or body in ('exec_hi', 'vcc_hi'): + raise Unsupported('%s source %s' % (what, tok)) + word = self.u(body, low16_only=not high) + bits = '(%s >> 16)' % word if high else word + else: + value = None + if body in FLOATS and body != '0.15915494' and not high: + value = struct.unpack('<H', struct.pack('<e', FLOATS[body]))[0] + elif re.fullmatch(r'0x[0-9a-f]{1,8}', body) and (literal_high or not high): + value = (int(body, 16) >> 16) if high else int(body, 16) & 0xffff + elif re.fullmatch(r'-?\d+', body) and -16 <= int(body) <= 64 and not high: + value = int(body) & 0xffff + if value is None: + raise Unsupported('%s source %s%s' % (what, tok, ' (high half)' if high else '')) + if absolute: + value &= 0x7fff + if neg: + value ^= 0x8000 + return '0x%04xu' % value + if absolute: + bits = '(%s & 0x7fffu)' % bits + if neg: + bits = '(%s ^ 0x8000u)' % bits + return bits + + @staticmethod + def f16_flip(bits): + """bits with bit 15 (the binary16 sign) flipped.""" + if re.fullmatch(r'0x[0-9a-f]{4}u', bits): + return '0x%04xu' % (int(bits[:-1], 16) ^ 0x8000) + return '(%s ^ 0x8000u)' % bits + + def f16_result(self, kind, srcs, clamp): + """The binary16 result bits of add / mul / fma over binary16 source bits (see f16_bits).""" + a, b = ('f16tof32(%s)' % s for s in srcs[:2]) + if kind == 'add': + expr = 'x2w_f16_fma(%s, 1.0, %s)' % (a, b) + elif kind == 'mul': + expr = '(%s * %s)' % (a, b) # exact in f32 + else: + expr = 'x2w_f16_fma(%s, %s, f16tof32(%s))' % (a, b, srcs[2]) + if clamp: + expr = 'saturate(%s)' % expr # VOP3 clamp to [0, 1], NaN to 0 (DX10_CLAMP, as mix() takes it) + if self.round16: + raise Unsupported('f16 %s under MODE f16 rounding %d' % (kind, self.round16)) + return self.to_f16(expr) + + @staticmethod + def sel_list(m, name, n): + sel = [int(x) for x in m[len(name) + 2:-1].split(',')] + if len(sel) != n or any(x not in (0, 1) for x in sel): + raise Unsupported('%s with %d entries, expected %d' % (name, len(sel), n)) + return sel + + def packed_f16(self, base, ops, mods, kind): + """v_pk_{add,mul,fma}_f16: two binary16 lanes. Lane 0 reads, from source i, the half op_sel[i] with neg_lo[i] + flipping its sign bit; lane 1 the half op_sel_hi[i] with neg_hi[i] (AMD RDNA 2 ISA VOP3P; LLVM + SIInstrInfo/VOP3PInstructions.td). Defaults op_sel 0, op_sel_hi 1, neg 0 (the disassembler prints only other + values). A constant is read only through its low half (its high half refused). clamp saturates each lane.""" + n = 3 if kind == 'fma' else 2 + sel, sel_hi, neg_lo, neg_hi, clamp = [0] * n, [1] * n, [0] * n, [0] * n, False + for m in mods: + name = m.split(':', 1)[0] + if m == 'clamp': + clamp = True + elif name == 'op_sel': + sel = self.sel_list(m, name, n) + elif name == 'op_sel_hi': + sel_hi = self.sel_list(m, name, n) + elif name == 'neg_lo': + neg_lo = self.sel_list(m, name, n) + elif name == 'neg_hi': + neg_hi = self.sel_list(m, name, n) + else: + raise Unsupported('%s with %s' % (base, m)) + dst = reg_range(ops[0]) if ops else None + if len(ops) != n + 1 or not dst or dst[0] != 'v' or dst[1] != dst[2]: + raise Unsupported('%s form %s' % (base, ', '.join(ops))) + lanes = [] + for s, ng in ((sel, neg_lo), (sel_hi, neg_hi)): + srcs = [] + for i in range(n): + bits = self.f16_bits(ops[1 + i], high=bool(s[i]), what=base, mods=False, literal_high=True) + srcs.append(self.f16_flip(bits) if ng[i] else bits) + lanes.append(self.f16_result(kind, srcs, clamp)) + self.set_v(dst[1], '%s | (%s << 16)' % tuple(lanes)) + + def op_v_pk_add_f16(self, ops, mods): + self.packed_f16('v_pk_add_f16', ops, mods, 'add') + + def op_v_pk_mul_f16(self, ops, mods): + self.packed_f16('v_pk_mul_f16', ops, mods, 'mul') + + def op_v_pk_fma_f16(self, ops, mods): + self.packed_f16('v_pk_fma_f16', ops, mods, 'fma') + + def write_f16(self, d, bits, high=False): + """A 16-bit result into D[15:0] (or D[31:16] for a destination op_sel); gfx10 keeps the other half + (LLVM GCNSubtarget::zeroesHigh16BitsOfDest, see half_op).""" + self.used_v.add(d) + if high: + self.set_v(d, '(v%d & 0xffffu) | (%s << 16)' % (d, bits)) + else: + self.set_v(d, '(v%d & 0xffff0000u) | %s' % (d, bits), low16_only=d in self.low16_only_v) + + def scalar_f16(self, base, ops, mods, kind, order, accumulate=False): + """v_{add,sub,subrev,mul,fma,fmac}_f16, VOP2 or VOP3: `order` maps the source operands onto (a, b[, c]) with + a sign flip ('-1' negates source 1). VOP3 op_sel[i] reads the high half of source i, op_sel[3] writes + D[31:16]; neg/abs act on the selected half's sign bit; clamp saturates. fmac accumulates into D[15:0].""" + n = 3 if kind == 'fma' and not accumulate else 2 + sel, clamp = [0] * 4, False + for m in mods: + if m == 'clamp': + clamp = True + elif m.startswith('op_sel:[') and m.endswith(']') and not accumulate: + given = [int(x) for x in m[len('op_sel:['):-1].split(',')] + if len(given) not in (3, 4) or any(x not in (0, 1) for x in given) or any(given[n:3]): + raise Unsupported('%s with %s' % (base, m)) + sel = given + [0] * (4 - len(given)) + else: + raise Unsupported('%s with %s' % (base, m)) + dst = reg_range(ops[0]) if ops else None + if len(ops) != n + 1 or not dst or dst[0] != 'v' or dst[1] != dst[2]: + raise Unsupported('%s form %s' % (base, ', '.join(ops))) + bits = [self.f16_bits(ops[1 + i], high=bool(sel[i]), what=base) for i in range(n)] + if accumulate: + bits.append(self.u(ops[0], low16_only=True)) + srcs = [] + for k in order: + b = bits[int(k.lstrip('-')) - 1] + srcs.append(self.f16_flip(b) if k.startswith('-') else b) + self.write_f16(dst[1], self.f16_result(kind, srcs, clamp), high=bool(sel[3])) + + def op_v_add_f16(self, ops, mods): + self.scalar_f16('v_add_f16', ops, mods, 'add', ('1', '2')) + + def op_v_sub_f16(self, ops, mods): + self.scalar_f16('v_sub_f16', ops, mods, 'add', ('1', '-2')) + + def op_v_subrev_f16(self, ops, mods): + self.scalar_f16('v_subrev_f16', ops, mods, 'add', ('2', '-1')) + + def op_v_mul_f16(self, ops, mods): + self.scalar_f16('v_mul_f16', ops, mods, 'mul', ('1', '2')) + + def op_v_fma_f16(self, ops, mods): + self.scalar_f16('v_fma_f16', ops, mods, 'fma', ('1', '2', '3')) + + def op_v_fmac_f16(self, ops, mods): + # D.f16 = S0.f16 * S1.f16 + D.f16, fused (VOP2 V_FMAC_F16) + self.scalar_f16('v_fmac_f16', ops, mods, 'fma', ('1', '2', '3'), accumulate=True) + + def sdwa_f16(self, base, ops, mods, kind, order): + """SDWA v_{add,sub,subrev,mul}_f16: each source is the binary16 in bits 15:0 of its selected field (WORD_0, + WORD_1, or DWORD: the low half); a constant only through WORD_0 / DWORD, in its binary16 form (LLVM decodes + SDWA sources of 16-bit operations with the 16-bit operand width). The result is placed by dst_sel WORD_0 / + WORD_1 with dst_unused; dst_sel DWORD (bits 31:16 of a 16-bit result) and sext are refused.""" + fields, clamp = {}, False + for m in mods: + key, _, value = m.partition(':') + if key in ('src0_sel', 'src1_sel', 'dst_sel', 'dst_unused') and value: + fields[key] = value + elif m == 'clamp': + clamp = True + else: + raise Unsupported('%s with SDWA modifier %s' % (base, m)) + dst = reg_range(ops[0]) if ops else None + if len(ops) != 3 or not dst or dst[0] != 'v' or dst[1] != dst[2]: + raise Unsupported('%s_sdwa form %s' % (base, ', '.join(ops))) + bits = [] + for i in range(2): + select = fields.get('src%d_sel' % i) + if select not in ('WORD_0', 'WORD_1', 'DWORD') or 'sext(' in ops[1 + i]: + raise Unsupported('%s_sdwa source %s src%d_sel %s' % (base, ops[1 + i], i, select)) + bits.append(self.f16_bits(ops[1 + i], high=select == 'WORD_1', what=base + '_sdwa')) + select, unused = fields.get('dst_sel'), fields.get('dst_unused', 'UNUSED_PAD') + if select not in ('WORD_0', 'WORD_1'): + raise Unsupported('%s_sdwa dst_sel %s' % (base, select)) + srcs = [self.f16_flip(bits[int(k.lstrip('-')) - 1]) if k.startswith('-') else bits[int(k.lstrip('-')) - 1] + for k in order] + result = self.f16_result(kind, srcs, clamp) + d = dst[1] + old = self.u(ops[0]) if unused == 'UNUSED_PRESERVE' else 'v%d' % d + keep_low16 = unused == 'UNUSED_PRESERVE' and select == 'WORD_0' and d in self.low16_only_v + self.set_v(d, sdwa_dest(result, select, unused, old), low16_only=keep_low16) + + def op_v_add_f16_sdwa(self, ops, mods): + self.sdwa_f16('v_add_f16', ops, mods, 'add', ('1', '2')) + + def op_v_sub_f16_sdwa(self, ops, mods): + self.sdwa_f16('v_sub_f16', ops, mods, 'add', ('1', '-2')) + + def op_v_subrev_f16_sdwa(self, ops, mods): + self.sdwa_f16('v_subrev_f16', ops, mods, 'add', ('2', '-1')) + + def op_v_mul_f16_sdwa(self, ops, mods): + self.sdwa_f16('v_mul_f16', ops, mods, 'mul', ('1', '2')) + + def compare_f16(self, base, writes_exec, cond, ops, mods, sdwa): + """v_cmp[x]_<cond>_f16 (e32, e64 with neg/abs and op_sel, SDWA): both sources widened exactly to f32 and + compared as f32 (no rounding); the ordered test of compare_result is taken on the binary16 bits.""" + if len(ops) == 3: + dst, a, b = ops + elif len(ops) == 2: + dst, (a, b) = ('exec' if writes_exec else 'vcc'), ops + else: + raise Unsupported('%s with %d operands' % (base, len(ops))) + high = [False, False] + if sdwa: + fields = dict(mod.partition(':')[::2] for mod in mods) + if set(fields) != {'src0_sel', 'src1_sel'}: + raise Unsupported('%s with %s' % (base, mods)) + for i, (tok, key) in enumerate(((a, 'src0_sel'), (b, 'src1_sel'))): + if fields[key] not in ('WORD_0', 'WORD_1', 'DWORD') or 'sext(' in tok: + raise Unsupported('%s source %s %s:%s' % (base, tok, key, fields[key])) + high[i] = fields[key] == 'WORD_1' + else: + for m in mods: + sel = [int(x) for x in m[len('op_sel:['):-1].split(',')] if m.startswith('op_sel:[') else None + if not sel or len(sel) != 3 or sel[2] or any(x not in (0, 1) for x in sel): + raise Unsupported('%s with %s' % (base, m)) + high = [bool(sel[0]), bool(sel[1])] + words = [self.f16_bits(t, high=h, what=base) for t, h in ((a, high[0]), (b, high[1]))] + x, y = ('f16tof32(%s)' % w for w in words) + ordered = ' && '.join('(%s & 0x7fffu) <= 0x7c00u' % w for w in words) + return self.compare_result(base, cond, writes_exec, dst, x, y, ordered) + + def op_v_cvt_pk_u16_u32(self, ops, mods): + """D = {sat16(S1.u32), sat16(S0.u32)}: each source clamped to 0xffff (Mesa ACO lowers nir pack_uint_2x16, + which saturates through _mesa_unsigned_to_unsigned, to this instruction).""" + dst = reg_range(ops[0]) if ops else None + if mods or len(ops) != 3 or not dst or dst[0] != 'v' or dst[1] != dst[2]: + raise Unsupported('v_cvt_pk_u16_u32 form %s %s' % (', '.join(ops), ' '.join(mods))) + a, b = (self.u(t) for t in ops[1:3]) + self.set_v(dst[1], 'min(%s, 0xffffu) | (min(%s, 0xffffu) << 16)' % (a, b)) + + def op_v_cvt_f16_f32(self, ops, mods): + # gfx10 keeps D[31:16] for 16-bit results (see half_op); the SDWA form keeps its own dst_sel handling. + if mods: + raise Unsupported('v_cvt_f16_f32 with %s' % mods) + if len(ops) != 2: # the VEC_U operand-count rule (#1716); this local handler bypasses the table + raise Unsupported('v_cvt_f16_f32 with %d operands, expected 2' % len(ops)) + d = reg_range(ops[0])[1] + self.used_v.add(d) + self.set_v(d, '(v%d & 0xffff0000u) | %s' % (d, self.to_f16('F(%s)' % self.u(ops[1])))) + def op_v_mov_b32(self, ops, mods): if len(ops) != 2: raise Unsupported('v_mov_b32 with %d operands, expected 2' % len(ops)) self.set_v(reg_range(ops[0])[1], self.u(ops[1])) def op_v_swap_b32(self, ops, mods): - # VOP1 only (llvm-mc rejects the e64, DPP and SDWA spellings for gfx1013). Both registers exchange - # their old values, so one is read into a temporary before either is written. The ISA allows no - # input or output modifier and no scalar or constant operand: both operands are plain VGPRs. - if mods: - raise Unsupported('v_swap_b32 with %s' % mods) - if len(ops) != 2: - raise Unsupported('v_swap_b32 with %d operands, expected 2' % len(ops)) - regs = [reg_range(o) for o in ops] - if any(not r or r[0] != 'v' or r[1] != r[2] or r[1] > 255 for r in regs): - raise Unsupported('v_swap_b32 operands %s, %s: expected two single VGPRs' % (ops[0], ops[1])) - dst, src = regs[0][1], regs[1][1] - for reg in (dst, src): - self.note_whole_read(reg) - body = '{ uint t = v%d; v%d = v%d; v%d = t; }' % (dst, dst, src, src) - # Uniformity travels with the value; under an unknown exec mask neither register keeps the proof. - uniform = (dst in self.uniform_v and self.exec_known, src in self.uniform_v and self.exec_known) - for reg, flag in zip((src, dst), uniform): - (self.uniform_v.add if flag else self.uniform_v.discard)(reg) - exprs = getattr(self, 'uniform_expr', {}) - moved = {src: exprs.pop(dst, None), dst: exprs.pop(src, None)} - exprs.update({reg: e for reg, e in moved.items() if e is not None and reg in self.uniform_v}) - self.used_v.update((dst, src)) - self.emit(body if self.exec_known else 'if (exec & 1) ' + body) + # RDNA 2 ISA V_SWAP_B32 (VOP1 0x65, LLVM VOP1Instructions.td: outs $vdst, $vdst1 tied to $src0): + # tmp = D; D = S0; S0 = tmp, in the active lanes. Both operands are single VGPRs; there is no VOP3, + # DPP or SDWA form (the decoder reports those as unsupported). + d, s = reg_range(ops[0]) if ops else None, reg_range(ops[1]) if len(ops) == 2 else None + if mods or len(ops) != 2 or not d or not s or d[0] != 'v' or s[0] != 'v' or d[1] != d[2] or s[1] != s[2]: + raise Unsupported('v_swap_b32 form %s %s' % (ops, mods)) + if d[1] == s[1]: + return # a register swapped with itself keeps its value + self.uses_swap = True + self.lines.append('xswap = %s;' % self.u(ops[0])) # every lane: a temporary read only below + self.set_v(d[1], self.u(ops[1])) + self.set_v(s[1], 'xswap') def op_v_cndmask_b32(self, ops, mods): - # The select takes no output modifier: a clamp or mul on it would change the value, so a - # modifier that reaches here is refused rather than dropped from the emitted text. + # The VOP3 form takes neg/abs on its two data operands; the select moves bits, so they are sign-bit + # operations on the selected word. if mods: raise Unsupported('v_cndmask_b32 with %s' % mods) if len(ops) not in (3, 4): raise Unsupported('v_cndmask_b32 with %d operands, expected 3 or 4' % len(ops)) mask = self.u(ops[3]) if len(ops) > 3 else 'vcc' - self.set_v(reg_range(ops[0])[1], - '(%s & 1) ? %s : %s' % (mask, self.u_src(ops[2]), self.u_src(ops[1]))) + self.set_v(reg_range(ops[0])[1], '(%s & 1) ? %s : %s' % (mask, self.u_mod(ops[2]), self.u_mod(ops[1]))) def op_v_interp_p1_f32(self, ops, mods): if hasattr(self, 'uniform_v'): @@ -5285,180 +6983,43 @@ def op_v_interp_mov_f32(self, ops, mods): attr, comp = self.note_attr(ops[2], 'flat') self.set_v(reg_range(ops[0])[1], 'i.fparam%d.%s' % (attr, comp)) - def interp_f16(self, op, ops, mods, vsrc, n_ops): - """Common checks of v_interp_p1ll_f16 / v_interp_p2_f16: -> (attr, field, high). - - The attribute channel holds two binary16 values; `field` is the interpolated float the pair reads - (`param0.x`, `hparam0_lo.z`). Two vertex exports exist, with different mappings: - - compr (see export()): the pair is split into float channels, so half h of attribute channel c is float - channel 2 * c + h of the parameter: attrN.x = (param.x, param.y), attrN.y = (param.z, param.w). Channels - z and w have no such pair. - - plain (a 32-bit export, e.g. halves packed by v_cvt_pkrtz_f16_f32): half h of channel c is - f16tof32(word_c >> 16 * h), carried by the extra outputs hparamN_lo (h = 0) and hparamN_hi (h = 1), - channel c of each. All four channels exist. - """ - allowed = ('high', INTERP_DST_HIGH) if op == 'v_interp_p2_f16' else ('high',) - extra = [m for m in mods if m not in allowed] - if extra: - raise Unsupported('%s with %s: only the plain form and high are lowered' % (op, ' '.join(extra))) - if len(ops) != n_ops: - raise Unsupported('%s with %d operands, expected %d' % (op, len(ops), n_ops)) - for tok in (ops[0], ops[1]) + tuple(ops[3:]): - if not re.fullmatch(r'v\d+', tok): - raise Unsupported('%s operand %s: only plain VGPRs are lowered' % (op, tok)) - m = re.fullmatch(r'attr(\d+)\.([xyzw])', ops[2]) - if not m: - raise Unsupported('%s interpolant %s: expected attrN.x/.y/.z/.w' % (op, ops[2])) - attr, component = self.note_attr(ops[2], 'f16') - chan, high = 'xyzw'.index(component), int('high' in mods) - vs = getattr(getattr(self, 'pipe', None), 'vs', None) - if vs is not None and attr in vs.plain_params and attr not in vs.compr_params: - self.f16_plain.setdefault(attr, set()).add(chan) - return attr, 'hparam%d_%s.%s' % (attr, ('lo', 'hi')[high], component), high - if chan > 1: - raise Unsupported('%s on channel %s: a compr export fills only the x and y channels' % (op, m.group(2))) - return attr, 'param%d.%s' % (attr, 'xyzw'[2 * chan + high]), high - - def interp_f16_pair(self, op, ops): - """The entry I/J registers: the PERSP_CENTER pair of the pixel inputs, I in the first, J in the second.""" - base = getattr(getattr(self, 'pipe', None), 'persp_center_vgpr', 0) - if base is None: - raise Unsupported('%s: the pixel inputs do not enable the PERSP_CENTER barycentrics' % op) - want = 'v%d' % (base + (0 if op == 'v_interp_p1ll_f16' else 1)) - if ops[1] != want: - raise Unsupported('%s barycentric operand %s: only the PERSP_CENTER entry %s (%s) is lowered' % ( - op, ops[1], 'I' if op == 'v_interp_p1ll_f16' else 'J', want)) - return base - - def interp_f16_scan(self): - """Whole-program proof for the f16 interpolation pair (no fixed-point analysis: any doubt is a refusal). - - The lowering reads the rasterizer's interpolant, so it is only faithful if (1) the entry I/J registers are - never written (they still hold the entry barycentrics wherever the pair reads them), (2) v_interp_p1ll_f16, - which emits nothing, has no consumer but the v_interp_p2_f16 that follows it in the same straight-line run - and nothing reads the destination it leaves stale when p2 writes elsewhere, and (3) nothing reads the - upper 16 bits of a plain p2 destination: whether gfx10 keeps or clears them is not established by a source - (LLVM 15 SIInstrInfo/VOP3Instructions.td model the result as f16 only; the encoding states no - high-half behaviour), so only a plain v_cvt_f32_f16 reading the low half may consume it, until a p2 with - op_sel 0x8 writes the high half of that register (Mesa ACO keeps the other half, see check_encoding). - """ - if self.interp_scanned: - return - pair = None - targets = set() - rows = [] - for off, _, name, asm in self.ins: - n, ops, mods = parse(asm) - n = re.sub(r'_e(32|64)$', '', n) - rows.append((off, n, ops, mods)) - target = getattr(self, 'calculated_pc', {}).get(off) - if n.startswith('s_cbranch') or n == 's_branch': - target = int(ops[0].split('_')[1], 16) - if target is not None: - if target <= off: - raise Unsupported('a backward branch in a program with v_interp_p1ll_f16 / v_interp_p2_f16') - targets.add(target) - - def regs(tok): - r = reg_range(tok) - return set(range(r[1], r[2] + 1)) if r and r[0] == 'v' else set() - - pending, stale, high_undefined = {}, set(), set() - for off, n, ops, mods in rows: - branch_boundary = off in targets or n.startswith('s_cbranch') or n in ('s_branch', 's_setpc_b64') - if branch_boundary and pending: - raise Unsupported('a branch between v_interp_p1ll_f16 %s and its v_interp_p2_f16: p2 could be ' - 'reached without the matching p1ll' % ', '.join('v%d' % r for r in sorted(pending))) - if branch_boundary and (stale or high_undefined): - raise Unsupported('unmodelled v_interp_p2_f16 result across a branch') - store = n == 'exp' or n.startswith(INTERP_STORE_PREFIXES) - # A malformed pair member is refused by its own handler; the scan models only the plain spelling. - interp = (n in ('v_interp_p1ll_f16', 'v_interp_p2_f16') and len(ops) == (3 if n[10] == '1' else 4) and - all(re.fullmatch(r'v\d+', o) for o in ops[:2] + ops[3:])) - if n in ('v_interp_p1ll_f16', 'v_interp_p2_f16') and not interp: - return # its own handler refuses the program; nothing after it is worth proving - written = regs(ops[0]) if ops and not store else set() - if interp: - read = regs(ops[1]) - pair = self.interp_f16_pair(n, ops) - else: - read = set().union(*(regs(o) for o in ops)) if ops else set() - low_reader = (n == 'v_cvt_f32_f16' and not mods and len(ops) == 2 and - all(re.fullmatch(r'v\d+', o) for o in ops)) - for r in sorted(read): - if r in pending: - raise Unsupported('v%d is the v_interp_p1ll_f16 result, which emits nothing: %s reads it before ' - 'the matching v_interp_p2_f16' % (r, n)) - if r in stale: - raise Unsupported('v%d is the v_interp_p1ll_f16 result, which emits nothing: %s reads it after ' - 'a v_interp_p2_f16 that wrote another register' % (r, n)) - if r in high_undefined and not (low_reader and r == int(ops[1][1:])): - raise Unsupported('%s reads the upper 16 bits of the v_interp_p2_f16 result v%d: not modelled' % - (n, r)) - if n == 'v_interp_p1ll_f16' and interp: - pending[int(ops[0][1:])] = (ops[2], 'high' in mods) - elif n == 'v_interp_p2_f16' and interp: - d, out = int(ops[3][1:]), int(ops[0][1:]) - if pending.get(d) != (ops[2], 'high' in mods): - raise Unsupported('v_interp_p2_f16 source %s is not the v_interp_p1ll_f16 result of %s' % - (ops[3], ops[2])) - del pending[d] - if out in pending: - raise Unsupported('v_interp_p2_f16 overwrites the pending v_interp_p1ll_f16 result v%d' % out) - stale.discard(out) - if out != d: - stale.add(d) - if INTERP_DST_HIGH in mods: - # Completes a 16-bit pair: the low half it keeps must be a plain p2 result still waiting for its - # upper half (no other writer is modelled), after which every reader sees defined halves. - if out not in high_undefined: - raise Unsupported('v_interp_p2_f16 op_sel 0x8 into v%d, which holds no v_interp_p2_f16 low ' - 'half: the half it keeps is not modelled' % out) - high_undefined.discard(out) - else: - high_undefined.add(out) - elif low_reader: - high_undefined.discard(int(ops[0][1:])) - stale.discard(int(ops[0][1:])) - # I and J: never written anywhere - base = pair if pair is not None else (getattr(getattr(self, 'pipe', None), 'persp_center_vgpr', 0) or 0) - for off, n, ops, mods in rows: - store = n == 'exp' or n.startswith(INTERP_STORE_PREFIXES) - if ops and not store and regs(ops[0]) & {base, base + 1}: - raise Unsupported('%s writes v%d: the entry barycentric registers must still hold the entry values ' - 'where v_interp_p1ll_f16 / v_interp_p2_f16 read them' % (n, min( - regs(ops[0]) & {base, base + 1}))) - if n == 'v_swap_b32' and len(ops) == 2 and regs(ops[1]) & {base, base + 1}: - raise Unsupported('v_swap_b32 writes the entry barycentric registers') - self.interp_scanned = True + def interp_f16_mods(self, name, mods): + if any(m != 'high' for m in mods): + raise Unsupported('%s with %s' % (name, ' '.join(mods))) + return 'hi' if 'high' in mods else 'lo' def op_v_interp_p1ll_f16(self, ops, mods): - # P0 + I * P10 in f32 from a binary16 attribute. The rasterizer interpolates the float channel, so the - # statement itself emits nothing; p2 reads the interpolated value. The destination is remembered so that - # p2 can be checked to continue this very pass. - attr, field, high = self.interp_f16('v_interp_p1ll_f16', ops, mods, 1, 3) - self.interp_f16_pair('v_interp_p1ll_f16', ops) - self.interp_f16_scan() - if self.interp_p1 is None: - self.interp_p1 = {} - self.interp_p1[int(ops[0][1:])] = (attr, field, high) + # First pass of a binary16 attribute (Mesa ACO emit_interp_instr: p1ll then p2_f16). Like p1_f32 it + # produces no value of its own here: the interpolated half comes from p2. + self.interp_f16_mods('v_interp_p1ll_f16', mods) + if len(ops) != 3: + raise Unsupported('v_interp_p1ll_f16 with %d operands' % len(ops)) + self.note_attr(ops[2], 'half') def op_v_interp_p2_f16(self, ops, mods): - # P1 + J * P20, converted to binary16 into one half of the destination, the other half kept (LLVM: the - # result is f16, the high bit selects the attribute half only). The plain form writes the low half; with - # op_sel 0x8 (ACO's v_interp_p2_hi_f16) the high half. interp_f16_scan refuses every consumer of a half the - # pair has not written, so a half that is never written is never observed. - attr, field, high = self.interp_f16('v_interp_p2_f16', ops, mods, 1, 4) - self.interp_f16_pair('v_interp_p2_f16', ops) - self.interp_f16_scan() - if (self.interp_p1 or {}).get(int(ops[3][1:])) != (attr, field, high): - raise Unsupported('v_interp_p2_f16 source %s is not the v_interp_p1ll_f16 result of %s' % (ops[3], ops[2])) + """The f16 attribute half (`high`: bits 31:16 of the exported word) interpolated, rounded to binary16. + + The vertex/mesh stage exports a second and third interpolated copy of the attribute, each half converted to + f32 (loparamN / hiparamN, see export); the result is f32tof16 of the interpolant. The hardware + interpolates in f32 and rounds once, as this does (LLVM SIInstrInfo / ACO: p1ll is f32 out, p2 f16 out). + A 16-bit write: the other half of the VGPR is kept (Mesa aco_ir.cpp instr_is_16bit lists v_interp_p2_f16 + and v_interp_p2_hi_f16 for GFX9+). op_sel bit 3 (VOP3 word 0 bit 14, which LLVM 15 and the decoder do not + print) writes the high half: Mesa aco_assembler.cpp emits v_interp_p2_hi_f16 as v_interp_p2_f16 with + opsel 0x8. Other op_sel bits are refused.""" + half = self.interp_f16_mods('v_interp_p2_f16', mods) + if len(ops) != 4: + raise Unsupported('v_interp_p2_f16 with %d operands' % len(ops)) + attr, comp = self.note_attr(ops[2], 'half') + opsel = struct.unpack_from('<I', self.raw, self.pc)[0] >> 11 & 15 + if opsel not in (0, 8): + raise Unsupported('v_interp_p2_f16 with op_sel %#x' % opsel) d = reg_range(ops[0])[1] self.used_v.add(d) - if INTERP_DST_HIGH in mods: - self.set_v(d, '(v%d & 0xffffu) | (f32tof16(i.%s) << 16)' % (d, field)) + value = self.to_f16('i.%sparam%d.%s' % (half, attr, comp)) + if opsel: + self.set_v(d, '(v%d & 0xffffu) | (%s << 16)' % (d, value)) else: - self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(i.%s)' % (d, field)) + self.set_v(d, '(v%d & 0xffff0000u) | %s' % (d, value)) def note_attr(self, tok, how): m = re.fullmatch(r'attr(\d+)\.([xyzw])', tok) @@ -5475,75 +7036,190 @@ def note_attr(self, tok, how): return attr, component def mix(self, ops, mods, dest): - """v_fma_mix_f32 / v_fma_mix{lo,hi}_f16: fma of sources that are binary32 words or binary16 halves. + """v_fma_mix{_f32,lo_f16,hi_f16}: fma of operands that are f32 or f16 halves. - Per source (LLVM 15 SelectVOP3PMadMixModsImpl): op_sel_hi set means the source is binary16, and - op_sel set picks its high half. abs, then neg, apply after widening. dest is 'f32', 'lo' or 'hi'. + LLVM AMDGPUISelDAGToDAG::SelectVOP3PMadMixModsImpl: op_sel_hi[i] makes operand i an f16 converted to f32 + and op_sel[i] then picks its high half; abs and neg act on the converted value (abs first). The result is + f32 (dest 'f32') or rounds to f16 in the low or high half, the other half kept. """ - half, hi, clamp = [0, 0, 0], [0, 0, 0], False + sel, high = [0, 0, 0], [0, 0, 0] for m in mods: - if m.startswith('op_sel_hi:['): - half = [int(x) for x in m[11:-1].split(',')] - elif m.startswith('op_sel:['): - hi = [int(x) for x in m[8:-1].split(',')] - elif m == 'clamp': - clamp = True - else: - raise Unsupported('fma_mix modifier %s' % m) - - def operand(tok, is_half, is_hi): - if not is_half and is_hi: - raise Unsupported('op_sel on a binary32 fma_mix source %s' % tok) - if tok == '-0': - # neg on inline 0 is -0.0 in either format; f() would print +0.0, which changes a -0 product. - return '(-0.0)' + if m.startswith('op_sel_hi:'): + sel = [int(x) for x in m[len('op_sel_hi:['):-1].split(',')] + elif m.startswith('op_sel:'): + high = [int(x) for x in m[len('op_sel:['):-1].split(',')] + elif m != 'clamp': + raise Unsupported('modifier %s on fma_mix' % m) + if len(ops) != 4 or len(sel) != 3 or len(high) != 3: + raise Unsupported('fma_mix form %s %s' % (ops, mods)) + def operand(tok, is_half, is_high): if not is_half: - if tok.startswith('--') and tok[1:] in FLOATS: - # neg on a negative inline float prints as `--0.5`; `(--0.5)` is an HLSL decrement. - return '(-(%s))' % self.f(tok[1:]) - if re.fullmatch(r'-(\d+|0x[0-9a-fA-F]+)', tok): - # The decoder prints neg on inline 1..64 or a literal as a negative integer, which f() - # reads without the sign-bit flip. Refuse until the decoder resolves it from the encoding. - raise Unsupported('negated integer or literal fma_mix source %s' % tok) - return self.f(tok) - neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) - if neg: - tok = tok[1:] - absolute = tok.startswith('|') and tok.endswith('|') + if is_high: + raise Unsupported('op_sel on an f32 fma_mix operand') + if tok.lstrip('-') == '0.15915494': + raise Unsupported('fma_mix inline constant 1/(2*pi)') + # "-0" is the inline 0 with the neg modifier: -0.0 (f() reads it as +0.0) + return '(-0.0)' if tok == '-0' else self.f(tok) + if tok in ('0', '-0'): + return '0.0' if tok == '0' else '(-0.0)' + if tok in FLOATS and not is_high and tok != '0.15915494': + # An inline float constant read as an f16 operand is that constant's binary16 form: 0.5 is 0x3800, + # not the low half of the f32 0x3f000000 (LLVM VOP3PInstructions.td, VOP3P_Mix_Profile: "The inline + # immediate values are really f16 converted to f32"; its fadd pattern passes FP16_ONE with op_sel_hi). + # 1/(2*pi) is refused: its f16 and f32 forms differ and only the f16 one is documented here. + return 'f16tof32(%s)' % self.h(tok) + neg = tok.startswith('-') + body = tok[1:] if neg else tok + absolute = body.startswith('|') and body.endswith('|') if absolute: - tok = tok[1:-1] - r = reg_range(tok) - if tok == '0': - text = '0.0' - elif re.fullmatch(r'0x[0-9a-fA-F]{1,8}', tok): - word = (int(tok, 16) >> (16 if is_hi else 0)) & 0xffff - text = 'f16tof32(0x%04xu)' % word - elif tok == '0.5' and not is_hi: - text = '0.5' - elif r and r[1] == r[2]: - # Only a high-half read needs the upper 16 bits defined. - text = 'f16tof32(%s%s)' % (self.u(tok, low16_only=not is_hi), ' >> 16' if is_hi else '') + body = body[1:-1] + r = reg_range(body) + if re.fullmatch(r'0x[0-9a-f]{1,8}', body): + # A 32-bit literal read as an f16 operand: op_sel picks its half as for a register (LLVM + # SIFoldOperands::tryFoldImmWithOpSel reads VOP3P literal halves as ImmVal >> (OP_SEL_0 ? 16 : 0)). + value = int(body, 16) + text = 'f16tof32(0x%04xu)' % ((value >> 16) if is_high else (value & 0xffff)) + elif not r or r[1] != r[2]: + raise Unsupported('f16 fma_mix operand %s' % tok) else: - raise Unsupported('binary16 fma_mix source %s' % tok) + text = 'f16tof32(%s%s)' % (self.u(body), ' >> 16' if is_high else '') if absolute: text = 'abs(%s)' % text return '(-%s)' % text if neg else text - - # v_fma_mix* is fused, but HLSL may round `a * b` before the add, so binary32 sources with long - # mantissas can differ from the hardware by 1 ULP (same as v_fma_f32 in VEC_F). - expr = '%s * %s + %s' % tuple(operand(*a) for a in zip(ops[1:4], half, hi)) - if clamp: + args = tuple(operand(t, s, h) for t, s, h in zip(ops[1:4], sel, high)) + pipe = getattr(self, 'pipe', None) + if dest == 'f32' and DRAW_FMA == 'exact' and 'mixfma' in getattr(pipe, 'features', ()) and not isinstance(pipe, (MeshPipeline, ComputePipeline)): + # X2W_DRAW_FEATURES=mixfma: v_fma_mix_f32 is one fused rounding, so it takes the exact-FMA helper like + # v_fma_f32 (FMA_FUSED). The plain a * b + c rounds the product, and fxc reassociates chains of them + # (1.0 * -h + -x, then 1.0 * h + that, folds to -x). The f16 results keep the plain form. + if hasattr(pipe, 'fma_rule'): + pipe.fma_rule = DRAW_FMA + # A signed-zero addend: fxc folds it into a d(...) immediate even behind x2w_fz, and the publisher + # refuses those. fma(a, b, +-0) is the product rounded once and then the exact sum with that zero, which is + # what the precise multiply and add give. + expr = ('x2w_mad_precise(%s, %s, %s)' if exact_with_zero(args) else + 'x2w_fma_exact(%s, %s, %s)') % args + else: + expr = '%s * %s + %s' % args + if 'clamp' in mods: expr = 'saturate(%s)' % expr d = reg_range(ops[0])[1] if dest == 'f32': - self.set_v(d, 'U(%s)' % expr) - return + return self.set_v(d, 'U(%s)' % expr) self.used_v.add(d) if dest == 'hi': - self.set_v(d, '(v%d & 0xffffu) | (f32tof16(%s) << 16)' % (d, expr)) + self.set_v(d, '(v%d & 0xffffu) | (%s << 16)' % (d, self.to_f16(expr))) else: - keep_low16 = d in self.low16_only_v - self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(%s)' % (d, expr), low16_only=keep_low16) + self.set_v(d, '(v%d & 0xffff0000u) | %s' % (d, self.to_f16(expr)), low16_only=d in self.low16_only_v) + + # s_round_mode writes MODE[3:0] from its immediate: bits 1:0 round f32 results, bits 3:2 round f16 and f64 results + # (LLVM SIDefines.h FP_ROUND_MODE_SP / FP_ROUND_MODE_DP; Mesa aco_ir.h struct float_mode, round32 : 2 then + # round16_64 : 2, "matches encoding of the MODE register"), each 0 nearest even, 1 +inf, 2 -inf, 3 toward zero + # (FP_ROUND_ROUND_TO_*, aco fp_round_*). The denorm bits are s_denorm_mode's and stay refused. Taken: f32 to + # nearest even (what the HLSL arithmetic does) with f16/f64 to nearest even or toward zero, in the straight-line + # entry of the program, so the mode at every later instruction is known. Under a nonzero f16/f64 mode the + # instructions that round an f16 result go through to_f16; check_round16 refuses every other f16/f64 one. + ROUND16_EXACT = ('v_cvt_f32_f16', 'v_cmp_', 'v_cmpx_', 'v_interp_p1ll_f16', 'v_fma_mix_f32', 'v_min_f16', + 'v_max_f16', 'v_pk_min_f16', 'v_pk_max_f16', 'v_cvt_pkrtz_f16_f32') + ROUND16_LOWERED = ('v_mul_f16', 'v_fmac_f16', 'v_rsq_f16', 'v_fma_mixlo_f16', 'v_fma_mixhi_f16', 'v_cvt_f16_f32', 'v_interp_p2_f16') + round16 = 0 # the class defaults, for a Stage built without __init__ (the operand-count probe) + uses_round_mode = False + launch_unknown = False # a pixel stage built without its launch FLOAT_MODE (launch_mode) + mode_at = {} # offset -> MODE[3:2] values reaching it (round_mode_flow), for stages with s_round_mode + quad_divergent = has_loop = False + + def op_s_round_mode(self, ops, mods): + value = int(ops[0], 0) if ops and re.fullmatch(r'(0x[0-9a-f]+|\d+)', ops[0]) else None + if value is None or mods: + raise Unsupported('s_round_mode %s' % ' '.join(ops + mods)) + if self.kind not in ('ps', 'ms') or (self.kind == 'ms' and not self.mode_at): + raise Unsupported('s_round_mode in a %s stage' % self.kind) + # After control flow the layout-order value set here can differ from what some path brings to a later + # instruction; round_mode_flow finds the values per instruction and one() refuses a mismatch. + if value & ~0xf or value & 3 or (value >> 2) not in (0, 3): + raise Unsupported('s_round_mode %#x (only f32 nearest even with f16/f64 nearest even or toward zero)' + % value) + self.round16 = value >> 2 + self.launch_unknown = False # MODE[3:2] is known from here on + + # FLOAT_MODE denorm bits [7:4] the lowering matches: f32 denormals flushed ([5:4] = 0), f16/f64 kept ([7:6] = 3). + # D3D flushes f32 denormals in shader arithmetic and keeps f16 ones; the 1,500 measured mesh sets are all 0xc_. + LAUNCH_DENORM = 0xc0 + + def launch_mode(self, mode): + """Start the pixel stage's MODE from its launch FLOAT_MODE (SPI_SHADER_PGM_RSRC1_PS bits 19:12; the layout + of MODE[7:0]: round f32 [1:0], round f16/f64 [3:2], denorm f32 [5:4], denorm f16/f64 [7:6], LLVM SIDefines.h + FP_ROUND_* / FP_DENORM_*, Mesa aco_ir.h float_mode). None (not passed): f16/f64 rounding before an + s_round_mode is refused (check_launch_known).""" + if mode is None: + self.launch_unknown = True + return + if mode & 0xf0 != self.LAUNCH_DENORM or mode & 3 or (mode >> 2 & 3) not in (0, 3): + raise Unsupported('launch FLOAT_MODE %#04x (only f32 nearest even, f16/f64 nearest even or toward zero, ' + 'denorm %#04x)' % (mode, self.LAUNCH_DENORM)) + self.round16 = mode >> 2 & 3 + + def round_mode_flow(self): + """offset -> the set of MODE[3:2] values (0, 3, or '?' for the unknown launch value, 'x' after an + s_round_mode op_s_round_mode refuses) that reach it on some path from the entry. Paths follow fall-through + and branch targets, loops included; only s_round_mode changes the value (s_setreg of MODE is refused).""" + info = {off: (name, asm) for off, n, name, asm in self.ins} + order = [ins[0] for ins in self.ins] + following = dict(zip(order, order[1:])) + at = {order[0]: {'?' if self.launch_unknown else self.round16}} if order else {} + todo = list(at) + while todo: + off = todo.pop() + name, asm = info[off] + out = at[off] + if name == 's_round_mode': + ops = parse(asm)[1] + value = int(ops[0], 0) if ops and re.fullmatch(r'(0x[0-9a-f]+|\d+)', ops[0]) else -1 + out = {value >> 2} if 0 <= value <= 0xf and not value & 3 and value >> 2 in (0, 3) else {'x'} + if name == 's_endpgm': + continue + nxt = [] if name == 's_branch' else [following[off]] if off in following else [] + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + for t in nxt: + if t in info and not out <= at.get(t, set()): + at[t] = at.get(t, set()) | out + todo.append(t) + return at + + def check_round16(self, name): + """Under f16/f64 round toward zero: refuse an f16/f64 instruction that rounds and is not lowered for it. + + Exact whatever the mode: the f16 -> f32 widening, compares (no result rounding), v_interp_p1ll_f16 and + v_fma_mix_f32 (f32 results, MODE[1:0]), f16 min/max (the result is an operand), v_cvt_pkrtz_f16_f32 (its + rounding is toward zero by definition).""" + if not self.rounds16(name): + return + if re.sub(r'_(e32|e64)$', '', name) in self.ROUND16_LOWERED: + return + raise Unsupported('%s under s_round_mode f16/f64 toward zero (not lowered)' % name) + + def rounds16(self, name): + """An f16/f64 instruction whose result depends on MODE[3:2] (not in ROUND16_EXACT).""" + if not re.search(r'f16|f64', name): + return False + return not re.sub(r'_(e32|e64|sdwa|dpp)$', '', name).startswith(self.ROUND16_EXACT) + + def check_launch_known(self, name): + """A pixel stage whose launch FLOAT_MODE was not passed: refuse an instruction whose result depends on + MODE[3:2] before an s_round_mode sets it. The launch value is not 0 in general (MEASURED: 0xcc, f16 toward + zero, in 262 of 1412 mesh pixel stages and 1015 of 3124 draw requests), so neither rounding can be assumed.""" + if self.rounds16(name): + raise Unsupported('%s: f16/f64 rounding with the launch FLOAT_MODE not passed (.psin third field)' % name) + + def to_f16(self, expr): + """An f32 value rounded to binary16 under the current MODE[3:2] (see op_s_round_mode).""" + # HLSL f32tof16 rounds toward zero on WARP and on an RX 9070 XT (MEASURED, startup_round_mode_check), so + # nearest even (MODE[3:2] = 0) needs its own helper. + return ('x2w_f32tof16_rtz(%s)' if self.round16 == 3 else 'x2w_f32tof16_rne(%s)') % expr + + def op_v_fma_mix_f32(self, ops, mods): + self.mix(ops, mods, 'f32') def op_v_fma_mix_f32(self, ops, mods): self.mix(ops, mods, 'f32') @@ -5554,51 +7230,6 @@ def op_v_fma_mixlo_f16(self, ops, mods): def op_v_fma_mixhi_f16(self, ops, mods): self.mix(ops, mods, 'hi') - def cube(self, kind, ops, mods): - """v_cube{id,sc,tc,ma}_f32: LLVM's ConstantFoldAMDGCNCubeIntrinsic. - - The major axis is z when |z| is at least |x| and |y|, otherwise y when |y| is at - least |x|, otherwise x. A face is negative only for a nonzero, non-NaN negative - coordinate. cubema returns twice the signed major coordinate. - """ - if len(ops) != 4: - raise Unsupported('v_cube%s_f32 with %d operands, expected 4' % (kind, len(ops))) - if any(m != 'clamp' for m in mods): - raise Unsupported('v_cube%s_f32 with %s' % (kind, ', '.join(mods))) - dst = reg_range(ops[0]) - if not dst or dst[0] != 'v' or dst[2] != dst[1] or dst[2] > 255: - raise Unsupported('v_cube%s_f32 destination %s' % (kind, ops[0])) - x, y, z = [self.f(o) for o in ops[1:4]] - temp = 'cube%d' % getattr(self, 'cube_temps', 0) - self.cube_temps = getattr(self, 'cube_temps', 0) + 1 - self.emit('float3 %s = float3(%s, %s, %s);' % (temp, x, y, z)) - c = temp - a = 'abs(%s)' % c - zmajor = '(%s.z >= %s.x && %s.z >= %s.y)' % (a, a, a, a) - ymajor = '(%s.y >= %s.x)' % (a, a) - expression = { - 'id': '(%s ? (%s.z < 0.0f ? 5.0f : 4.0f) : %s ? (%s.y < 0.0f ? 3.0f : 2.0f) ' - ': (%s.x < 0.0f ? 1.0f : 0.0f))' % (zmajor, c, ymajor, c, c), - 'sc': '(%s ? (%s.z < 0.0f ? -%s.x : %s.x) : %s ? %s.x ' - ': (%s.x < 0.0f ? %s.z : -%s.z))' % (zmajor, c, c, c, ymajor, c, c, c, c), - 'tc': '(%s ? -%s.y : %s ? (%s.y < 0.0f ? -%s.z : %s.z) : -%s.y)' % ( - zmajor, c, ymajor, c, c, c, c), - 'ma': '((%s ? %s.z : %s ? %s.y : %s.x) * 2.0f)' % (zmajor, c, ymajor, c, c), - }[kind] - self.set_vf(dst[1], expression, mods) - - def op_v_cubeid_f32(self, ops, mods): - self.cube('id', ops, mods) - - def op_v_cubesc_f32(self, ops, mods): - self.cube('sc', ops, mods) - - def op_v_cubetc_f32(self, ops, mods): - self.cube('tc', ops, mods) - - def op_v_cubema_f32(self, ops, mods): - self.cube('ma', ops, mods) - def i64_words(self, tok): """(low, high) uint expressions of a 64-bit integer source: a VGPR/SGPR pair or an inline int.""" pair = reg_range(tok) @@ -5613,30 +7244,6 @@ def i64_words(self, tok): return '%du' % (value & 0xffffffff), '%du' % (value >> 32) raise Unsupported('64-bit source %s' % tok) - def shift64(self, ops, mods, helper): - if mods: - raise Unsupported('64-bit shift with %s' % mods) - if len(ops) != 3: - raise Unsupported('64-bit shift with %d operands, expected 3' % len(ops)) - dst = reg_range(ops[0]) - if not dst or dst[0] != 'v' or dst[2] != dst[1] + 1 or dst[2] > 255: - raise Unsupported('64-bit shift destination %s' % ops[0]) - sr = reg_range(ops[1]) - if (sr and (sr[1] != sr[2] or (sr[0] == 'v' and sr[1] > 255) or (sr[0] == 's' and sr[1] > 105)) - or ops[1] in ('vcc', 'exec') or ops[1] in FLOATS): - raise Unsupported('64-bit shift amount %s' % ops[1]) - amount = self.u(ops[1]) - low, high = self.i64_words(ops[2]) - body = '{ uint2 t = %s(%s, %s, %s); v%d = t.x; v%d = t.y; }' % ( - helper, low, high, amount, dst[1], dst[2]) - if hasattr(self, 'uniform_v'): - self.uniform_v.discard(dst[1]) - self.uniform_v.discard(dst[2]) - self.clear_low16(dst[1]) - self.clear_low16(dst[2]) - self.used_v.update((dst[1], dst[2])) - self.emit(body if self.exec_known else 'if (exec & 1) ' + body) - def carry_out_op(self, ops, mods, kind): """v_{add,sub,subrev}_co_u32 D, SDST, S0, S1: a 32-bit add or subtract with a carry or borrow out. @@ -5674,138 +7281,57 @@ def carry_out_op(self, ops, mods, kind): self.set_s(sdst[1], predicate, uniform=False) self.masks.add(sdst[1]) - def op_v_add_co_u32(self, ops, mods): - self.carry_out_op(ops, mods, 'add') - - def op_v_sub_co_u32(self, ops, mods): - self.carry_out_op(ops, mods, 'sub') - - def op_v_subrev_co_u32(self, ops, mods): - self.carry_out_op(ops, mods, 'subrev') - - def carry_in_out_op(self, ops, mods, kind): - """v_{add,sub,subrev}_co_ci_u32 D, SDST, S0, S1, S2: 32-bit add/sub with carry or borrow in and out. - - AMD RDNA 2 ISA: V_ADD_CO_CI_U32 D = S0 + S1 + S2[lane] with carry out to SDST[lane]; - V_SUB_CO_CI_U32 D = S0 - S1 - S2[lane] with borrow out to SDST[lane]; V_SUBREV_CO_CI_U32 swaps S0 and S1. - Both VOP2 (_e32, implicit vcc_lo) and VOP3b (_e64) forms arrive with five operands. Results go through - scratch a and w first so D or SDST may overlap any source. - """ - name = 'v_%s_co_ci_u32' % kind - if mods: - raise Unsupported('%s with %s' % (name, ' '.join(mods))) - if len(ops) != 5: - raise Unsupported('%s with %d operands' % (name, len(ops))) - d = reg_range(ops[0]) - if not d or d[0] != 'v' or d[1] != d[2] or d[1] > 255: - raise Unsupported('%s destination %s' % (name, ops[0])) - sdst = reg_range(ops[1]) - if ops[1] not in ('vcc', 'vcc_lo') and not (sdst and sdst[0] == 's' and sdst[1] == sdst[2] and sdst[1] <= 105): - raise Unsupported('%s carry-out destination %s' % (name, ops[1])) - cin_tok = ops[4] - if cin_tok in ('vcc_hi', 'exec_hi'): - raise Unsupported('%s carry-in %s' % (name, cin_tok)) - cin_const = self.const_u32(cin_tok) - if cin_const in (0, 0xffffffff): - ci = '1u' if cin_const else '0u' - elif self.is_lane_mask(cin_tok): - ci = '(%s & 1u)' % self.u(cin_tok) - else: - raise Unsupported('%s carry-in %s' % (name, cin_tok)) - a, b = self.u(ops[2]), self.u(ops[3]) - if kind == 'subrev': - a, b = b, a - if kind == 'add': - self.emit('a = %s + %s;' % (a, b)) - self.emit('w = a < %s ? 1u : 0u;' % a) - self.emit('a = a + %s;' % ci) - self.emit('w = w | (a < %s ? 1u : 0u);' % ci) - else: - self.emit('a = %s - %s;' % (a, b)) - self.emit('w = %s > %s ? 1u : 0u;' % (b, a)) - self.emit('w = w | (%s > a ? 1u : 0u);' % ci) - self.emit('a = a - %s;' % ci) - self.set_v(d[1], 'a') - predicate = 'w' if self.exec_known else '(exec & w)' - if ops[1] in ('vcc', 'vcc_lo'): - self.emit('vcc = %s;' % predicate) - else: - self.set_s(sdst[1], predicate, uniform=False) - self.masks.add(sdst[1]) - - def op_v_add_co_ci_u32(self, ops, mods): - self.carry_in_out_op(ops, mods, 'add') - - def op_v_sub_co_ci_u32(self, ops, mods): - self.carry_in_out_op(ops, mods, 'sub') - - def op_v_subrev_co_ci_u32(self, ops, mods): - self.carry_in_out_op(ops, mods, 'subrev') - - def op_v_lshlrev_b64(self, ops, mods): - self.shift64(ops, mods, 'shl64') - - def op_v_lshrrev_b64(self, ops, mods): - self.shift64(ops, mods, 'shr64u') - def op_v_ashrrev_i64(self, ops, mods): - self.shift64(ops, mods, 'shr64i') + # LOCAL merge: upstream's handler passes its 'shr64i' helper to shift64, but the local shift64 emits + # <name>_lo/_hi calls that have no 'shr64i' definition, so the HLSL would not compile. Refused, as before. + raise Unsupported('v_ashrrev_i64 (local shift64 has no arithmetic 64-bit form)') def op_v_cvt_pkrtz_f16_f32(self, ops, mods): + # Round toward zero whatever MODE says (the "rtz" of the name; LLVM int_amdgcn_cvt_pkrtz; Mesa + # nir_opt_algebraic.py turns pack_half_2x16_split into pack_half_2x16_rtz_split only for backends with + # has_pack_half_2x16_rtz, the rounding being the difference). HLSL f32tof16 does not promise that rounding (MEASURED toward zero + # on WARP, startup_round_mode_check), so both halves go through x2w_f32tof16_rtz. if len(ops) != 3: raise Unsupported('v_cvt_pkrtz_f16_f32 with %d operands, expected 3' % len(ops)) - self.set_v(reg_range(ops[0])[1], 'f32tof16(%s) | (f32tof16(%s) << 16)' % (self.f(ops[1]), self.f(ops[2]))) - - # VOPC with sub-dword addressing (tools/disasm_rdna2.py _decode_vopc_sdwa prints it): each source - # reads its src0_sel/src1_sel field, zero-extended or, under sext(), sign-extended, and the - # compare then reads that 32-bit value as its type. A binary32 class compare reads the whole - # float in SRC0 and selects an integer field in SRC1 for the mask. - # - # An f32 source (#1906) with a DWORD selection reads the register as binary32 with neg/abs as in - # the e64 form. A BYTE or WORD selection is refused: LLVM's SIPeepholeSDWA models it as the field - # zero-extended and read as binary32 bits (the RDNA 2 ISA guide gives SDWAB only its fields), so - # the field is always +0 or a denormal and the result depends on the binary32 denormal mode, which - # this translator does not read (pixel_aot refuses the same forms). sext() is valid for integer - # operands only (LLVM AMDGPUModifierSyntax; LLVM 15 does not decode the bit on a float source). - def compare_sdwa_sources(self, base, typ, ops, mods, *, float_src0=False, float_sources=False): - fields = {} - for m in mods: - key, _, value = m.partition(':') - if key not in ('src0_sel', 'src1_sel') or value not in SDWA_SEL or key in fields: - raise Unsupported('%s with SDWA modifier %s' % (base, m)) - fields[key] = value - sources = [] - for index, token in enumerate(ops): - selection = fields.get('src%d_sel' % index) - if not selection: - raise Unsupported('%s SDWA without src%d_sel' % (base, index)) - sext = token.startswith('sext(') and token.endswith(')') - if float_src0 and index == 0: - if selection != 'DWORD' or sext: - raise Unsupported('%s requires a DWORD float source' % base) - sources.append(self.f(token)) - continue - if float_sources: - if 'sext(' in token: - raise Unsupported('%s: sext() on a float source' % base) - if selection != 'DWORD': - raise Unsupported('%s: f32 SDWA byte/word selection depends on the binary32 denormal mode' - % base) - # The whole word: the same text as the e64 form with the same modifiers. - sources.append(self.f(token)) - continue - if sext: - token = token[len('sext('):-1] - word = sdwa_source(self.u(token, low16_only=selection in ('BYTE_0', 'BYTE_1', 'WORD_0')), selection, sext) - sources.append('int(%s)' % word if typ == 'i32' else word) - return sources + self.set_v(reg_range(ops[0])[1], 'x2w_f32tof16_rtz(%s) | (x2w_f32tof16_rtz(%s) << 16)' + % (self.f(ops[1]), self.f(ops[2]))) - def check_compare_sdwa_destination(self, base, writes_exec, ops): - # v_cmpx_*_sdwa prints just its sources. v_cmp_*_sdwa prints the scalar destination first. - if len(ops) != (2 if writes_exec else 3): - raise Unsupported('%s with %d operands' % (base, len(ops))) - if not writes_exec and ops[0] not in ('vcc', 'vcc_lo', 'exec', 'exec_lo') and not ( - reg_range(ops[0]) and reg_range(ops[0])[0] == 's'): - raise Unsupported('%s into %s' % (base, ops[0])) + def pknorm(self, ops, mods, kind): + # S0 packs into D[15:0] and S1 into D[31:16] (per Mesa ACO selection: pack_[us]norm_2x16 of (x, y) is + # v_cvt_pknorm_[ui]16_f32 x, y); each half is x2w_pknorm_[ui]16, see HELPERS. Source neg/abs apply first. + if mods or len(ops) != 3: + raise Unsupported('v_cvt_pknorm_%s16_f32 with %s' % (kind, mods or ops)) + helper = 'x2w_pknorm_%s16' % kind + self.set_v(reg_range(ops[0])[1], '%s(%s) | (%s(%s) << 16)' % (helper, self.f(ops[1]), helper, self.f(ops[2]))) + + def op_v_cvt_pknorm_u16_f32(self, ops, mods): + self.pknorm(ops, mods, 'u') + + def op_v_cvt_pknorm_i16_f32(self, ops, mods): + self.pknorm(ops, mods, 'i') + + def _low16_source(self, base, tok, signed): + """A source of a 16-bit integer compare: bits 15:0 of the operand, sign- or zero-extended (RDNA 2 VOPC + S0.i16 / S0.u16). A float token is refused: on a 16-bit operand the inline constants 240-248 are binary16 + values (LLVM 15 prints inline 1.0 there as 0x3c00), while u() would give the binary32 word.""" + if tok in FLOATS: + raise Unsupported('%s source %s: inline float constants are binary16 on 16-bit operands' % (base, tok)) + reg = reg_range(tok) + if reg: + if reg[1] != reg[2]: + raise Unsupported('%s source %s' % (base, tok)) + x = self.u(tok, low16_only=True) + return '(asint(%s << 16u) >> 16u)' % x if signed else '(%s & 0xffffu)' % x + try: + value = int(tok, 0) + except ValueError: + # vcc, exec, m0 and modifier spellings: not a source this lowering reads. + raise Unsupported('%s source %s' % (base, tok)) + # The decoder prints inline integers -16..64 in decimal and a literal in hex; LLVM 15 accepts only 16-bit + # literals on these operands. + if not -16 <= value <= 0xffff: + raise Unsupported('%s source %s: wider than 16 bits' % (base, tok)) + low = value & 0xffff + return '%d' % (low - 0x10000 if low & 0x8000 else low) if signed else '0x%04xu' % low def _low16_source(self, base, tok, signed): """A source of a 16-bit integer compare: bits 15:0 of the operand, sign- or zero-extended (RDNA 2 VOPC @@ -5832,88 +7358,113 @@ def _low16_source(self, base, tok, signed): return '%d' % (low - 0x10000 if low & 0x8000 else low) if signed else '0x%04xu' % low def compare(self, base, ops, mods=()): - # A comparison reads its two operands directly, so a modifier that arrives here is one this - # lowering does not model (op_sel selects a packed half, clamp/omod have no place in a compare): - # refuse it rather than emit a predicate computed from the unselected operands. - if mods and not base.endswith('_sdwa'): + m = re.fullmatch(r'v_cmp(x?)_(\w+?)_(f32|u32|i32|f16|u16|i16)(_sdwa)?', base) + if m and m.group(3) == 'f16' and m.group(2) != 'class': + return self.compare_f16(base, m.group(1) == 'x', m.group(2), ops, mods, bool(m.group(4))) + if not m or (m.group(4) and m.group(3) not in ('i32', 'u32') and m.group(2) != 'class') \ + or (m.group(3) == 'f16' and m.group(2) not in ('class', 'gt', 'lt')): + if m and m.group(4) and m.group(3) == 'f32': + # The f32 predicates are verified on the plain and e64 forms only (#1920); the SDWA forms + # stay refused until they are verified too. + raise Unsupported('%s: f32 SDWA compares are not lowered' % base) + raise Unsupported(base) + writes_exec, cond, typ = m.group(1) == 'x', m.group(2), m.group(3) + if typ in ('u16', 'i16'): + if m.group(4) or cond not in ('lt', 'eq', 'le', 'gt', 'ne', 'ge'): + raise Unsupported(base) + if mods: + raise Unsupported('%s with %s' % (base, mods)) + if len(ops) == 3: + dst, a, b = ops + elif len(ops) == 2: + dst, (a, b) = ('exec' if writes_exec else 'vcc'), ops + else: + raise Unsupported('%s with %d operands' % (base, len(ops))) + if m.group(4): + # VOPC SDWA on integers: each source is its selected field (zero- or, with sext(), sign-extended) + # compared as a 32-bit value; the result goes to vcc, an SGPR mask or (cmpx) exec as for e32. + fields = dict(mod.partition(':')[::2] for mod in mods) + if set(fields) != {'src0_sel', 'src1_sel'} or any(v not in SDWA_SEL for v in fields.values()): + raise Unsupported('%s with %s' % (base, mods)) + if cond == 'class' and typ == 'f16': + # v_cmp_class_f16 SDWA: S0 is the selected field of a VGPR or SGPR, zero-extended, of which the op + # reads bits [15:0] as the binary16 value (SDWA source selection, AMD RDNA ISA 6.3.3; for WORD_1 that + # is the high half); neg()/abs() act on bit 15 of the selected value. S1 is the integer class mask + # through its own selection, as for f32. A constant S0 is refused: its f16 inline form is not modelled. + # The disassembly spells the modifiers -vN and |vN| on registers (neg(N)/abs(N) on constants). + # -|vN| is abs then neg (SDWA applies abs before neg, as VOP3): bit 15 set. + mm = re.fullmatch(r'(-)?(?:\|(\w+)\||(\w+))', a) + src = (mm.group(2) or mm.group(3)) if mm else a + if src.startswith('sext(') or not reg_range(src): + raise Unsupported('%s with f16 value operand %s' % (base, a)) + value = sdwa_source(self.u(src), fields['src0_sel'], False) + if mm and mm.group(2): + value = '(%s %s)' % (value, '| 0x8000u' if mm.group(1) else '& 0x7fffu') + elif mm and mm.group(1): + value = '(%s ^ 0x8000u)' % value + if b.startswith(('sext(', 'neg(', 'abs(')): + raise Unsupported('%s with a modified class mask %s' % (base, b)) + expr = 'x2w_class_f16(%s, %s)' % (value, sdwa_source(self.u(b), fields['src1_sel'], False)) + return self.write_compare(writes_exec, dst, expr) + if cond == 'class': + # v_cmp_class_f32 SDWA: S0 is the f32 value (whole dword only; neg()/abs() act on its sign bit as + # for the e64 form), S1 the integer class mask read through its selection (a compiler uses + # src1_sel:BYTE_n to test bits of one byte against constant classes such as -0.0). + if fields['src0_sel'] != 'DWORD': + raise Unsupported('%s with a sub-dword f32 value' % base) + mm = re.fullmatch(r'(neg|abs)\((.*)\)', a) + value = self.u(mm.group(2) if mm else a) + if mm: + value = '(%s %s)' % (value, '^ 0x80000000u' if mm.group(1) == 'neg' else '& 0x7fffffffu') + if b.startswith(('sext(', 'neg(', 'abs(')): + raise Unsupported('%s with a modified class mask %s' % (base, b)) + expr = 'x2w_class_f32(%s, %s)' % (value, sdwa_source(self.u(b), fields['src1_sel'], False)) + return self.write_compare(writes_exec, dst, expr) + words = [] + for token, key in ((a, 'src0_sel'), (b, 'src1_sel')): + sext = token.startswith('sext(') and token.endswith(')') + words.append(sdwa_source(self.u(token[5:-1] if sext else token), fields[key], sext)) + x, y = words if typ == 'u32' else ['int(%s)' % w for w in words] + return self.compare_result(base, cond, writes_exec, dst, x, y) + elif mods: raise Unsupported('%s with %s' % (base, mods)) - # v_cmp_class_f32 / v_cmpx_class_f32 test the binary32 class of the value in SRC0 against the - # class-bit mask in SRC1 (the ISA order: the float operand first, the integer mask second). - name = base.removesuffix('_sdwa') - if name in ('v_cmp_class_f32', 'v_cmpx_class_f32', 'v_cmp_class_f16', 'v_cmpx_class_f16'): - # The half form (issue #1855) takes the raw binary16 pattern in the low half of the operand - # word: its classes follow the half layout (exponent 5 bits, mantissa 10, quiet bit 0x0200) - # and abs/neg act on bit 15, so the value is never converted to float here. - f16 = name.endswith('_f16') - writes_exec = name in ('v_cmpx_class_f32', 'v_cmpx_class_f16') - sdwa = name != base - if f16 and sdwa: - raise Unsupported('SDWA form of %s' % name) - if sdwa: - self.check_compare_sdwa_destination(base, writes_exec, ops) - if len(ops) == 3: - dst, value, mask = ops - elif writes_exec and len(ops) == 2: - # The e32 and SDWA spellings write EXEC implicitly and print no destination. - dst, (value, mask) = 'exec', ops - else: - raise Unsupported('%s with %d operands' % (base, len(ops))) - if sdwa: - value, mask = self.compare_sdwa_sources(base, 'u32', [value, mask], mods, float_src0=True) - elif f16: - # abs() and - apply to bit 15 of the half, before the class test. - # The decoder prints an absolute source as |v4| and a negated one as -v4, so both - # spellings are accepted here as well as abs(...). - token = value - if re.fullmatch(r'-[1-9]\d*', token): - raise Unsupported('%s source %s: ambiguous signed inline half' % (base, value)) - negative = token.startswith('-') - if negative: - token = token[1:] - absolute = (token.startswith('|') and token.endswith('|')) or ( - token.startswith('abs(') and token.endswith(')')) - if absolute: - token = token[4:-1] if token.startswith('abs(') else token[1:-1] - if token in FLOATS or re.fullmatch(r'-[1-9]\d*', token): - # A float-printed operand would otherwise be lowered as its binary32 bit pattern. - raise Unsupported('%s source %s: f16 class compares need the raw half' % (base, value)) - bits = self.u(token, low16_only=True) - if absolute: - bits = '(%s & 0x7fffu)' % bits - if negative: - bits = '(%s ^ 0x8000u)' % bits - if mask in FLOATS: - raise Unsupported('%s mask %s: expected an integer class mask' % (base, mask)) - value, mask = bits, self.u(mask) - else: - value, mask = self.f(value), self.u(mask) - cond = '(%s(%s) & %s) != 0u' % ('class16' if f16 else 'class32', value, mask) - predicate = '((%s) ? 1u : 0u)' % cond - # A narrowed EXEC must stay narrowed: intersect with it, as the generic compare path does. - if not self.exec_known: - predicate = '(exec & %s)' % predicate - if writes_exec or dst in ('exec', 'exec_lo'): - self.exec_known = False - self.emit('exec = %s;' % predicate) - elif dst in ('vcc', 'vcc_lo'): - self.emit('vcc = %s;' % predicate) + if cond == 'class': + # v_cmp_class: S0 is the value, S1 the class mask (llvm.amdgcn.class(x, mask)); neg/abs on S0 act on + # its sign bit, and an f16 value sits in the low half with inline float constants in half form. + if typ == 'f16': + value = self.u_mod(a, 0x8000) if reg_range(a.strip('-|')) else self.h(a) + expr = 'x2w_class_f16(%s, %s)' % (value, self.u(b)) else: - reg = reg_range(dst) - if not reg or reg[0] != 's': - raise Unsupported('%s into %s' % (base, dst)) - d = reg[1] - self.set_s(d, predicate) - self.masks.add(d) - return None + expr = 'x2w_class_f32(%s, %s)' % (self.u_mod(a), self.u(b)) + return self.write_compare(writes_exec, dst, expr) + if typ == 'f16': + words = [self.u_mod(t, 0x8000) if reg_range(t.strip('-|')) else self.h(t) for t in (a, b)] + op = '>' if cond == 'gt' else '<' + expr = '((%s & 0x7fffu) <= 0x7c00u && (%s & 0x7fffu) <= 0x7c00u && f16tof32(%s) %s f16tof32(%s))' + return self.write_compare(writes_exec, dst, expr % (words[0], words[1], words[0], op, words[1])) + if typ == 'f32': + x, y = self.f(a), self.f(b) + elif typ in ('i16', 'u16'): + if not writes_exec and dst not in ('vcc', 'vcc_lo') and not re.fullmatch(r's[0-9]+', dst): + raise Unsupported('%s into %s' % (base, dst)) + x, y = (self._low16_source(base, t, typ == 'i16') for t in (a, b)) + elif typ == 'i32': + x, y = 'int(%s)' % self.u(a), 'int(%s)' % self.u(b) + else: + x, y = self.u(a), self.u(b) + ordered = '' + if typ == 'f32': + def word(tok): + # A float source's word before its neg/abs modifiers, as f() reads them; they keep a NaN a NaN. + if tok.startswith('-') and not re.match(r'-[\d.]', tok): + tok = tok[1:] + if tok.startswith('|') and tok.endswith('|'): + tok = tok[1:-1] + return self.u(tok) + ordered = ' && '.join('(%s & 0x7fffffffu) <= 0x7f800000u' % word(t) for t in (a, b)) + return self.compare_result(base, cond, writes_exec, dst, x, y, ordered) - m = re.fullmatch(r'v_cmp(x?)_(\w+?)_(f32|u32|i32|i16|u16)(_sdwa)?', base) - if not m: - raise Unsupported(base) - writes_exec, cond, typ, sdwa = m.group(1) == 'x', m.group(2), m.group(3), bool(m.group(4)) - # The 16-bit integer compares have the six relations only (gfx10 has no 16-bit f or t). Their SDWA forms - # are not lowered here (tools/pixel_aot.py has its own lowering of them). - if typ in ('i16', 'u16') and (sdwa or cond not in ('lt', 'eq', 'le', 'gt', 'ne', 'ge')): - raise Unsupported(base) + def compare_result(self, base, cond, writes_exec, dst, x, y, ordered=''): # f32 lg is ordered and not equal (false when either source is NaN) and nlg its negation (#1920). # HLSL != is unordered, so lg reads as less or greater, behind {2}: both source words not NaN, # tested on their bits. DXC marks float compares fast unless -Gis, and a driver may then fold @@ -5927,36 +7478,15 @@ def compare(self, base, ops, mods=()): 'nle': '!({2} && {0} <= {1})', 'ngt': '!({2} && {0} > {1})', 'nge': '!({2} && {0} >= {1})', 'nlg': '!({2} && ({0} < {1} || {0} > {1}))', 'o': '({2})', 'u': '!({2})', 't': 'true', 'f': 'false'} - # Conditions outside the table or dedicated lowering stay refused in both forms. if cond not in table: raise Unsupported(base) - if sdwa: - self.check_compare_sdwa_destination(base, writes_exec, ops) - if len(ops) == 3: - dst, a, b = ops - else: - dst, (a, b) = ('exec' if writes_exec else 'vcc'), ops - if sdwa: - # f32 sources: DWORD selections only, read as in the e64 form, so {2} tests the registers. - x, y = self.compare_sdwa_sources(base, typ, [a, b], mods, float_sources=typ == 'f32') - elif typ == 'f32': - x, y = self.f(a), self.f(b) - elif typ == 'i32': - x, y = 'int(%s)' % self.u(a), 'int(%s)' % self.u(b) - elif typ in ('i16', 'u16'): - x, y = (self._low16_source(base, t, typ == 'i16') for t in (a, b)) - else: - x, y = self.u(a), self.u(b) - def word(tok): - # A float source's word before its neg/abs modifiers, as f() reads them; they keep a NaN a NaN. - tok = self.split_neg(tok)[1] - if tok.startswith('|') and tok.endswith('|'): - tok = tok[1:-1] - return self.u(tok) - ordered = '' - if '{2}' in table[cond]: - ordered = ' && '.join('(%s & 0x7fffffffu) <= 0x7f800000u' % word(t) for t in (a, b)) - expr = '((%s) ? 1u : 0u)' % table[cond].format(x, y, ordered) + if '{2}' in table[cond] and not ordered: + # Only the plain and e64 f32 forms supply the source words the ordered test needs. + raise Unsupported('%s: no f32 source words for the ordered test' % base) + return self.write_compare(writes_exec, dst, '((%s) ? 1u : 0u)' % table[cond].format(x, y, ordered)) + + def write_compare(self, writes_exec, dst, expr): + """Store a 0/1 compare result as the lane's bit of exec, vcc or an SGPR mask.""" if not self.exec_known: expr = '(exec & %s)' % expr if writes_exec or dst in ('exec', 'exec_lo'): @@ -5965,20 +7495,18 @@ def word(tok): elif dst in ('vcc', 'vcc_lo'): self.emit('vcc = %s;' % expr) else: - # vcc_hi, exec_hi, m0 or a literal are not an SGPR the one-lane model holds a mask in; reg_range - # returned None for them and the index raised TypeError, which ended the whole translation. - reg = reg_range(dst) - if not reg or reg[0] != 's': - raise Unsupported('%s into %s' % (base, dst)) - d = reg[1] + r = reg_range(dst) + if not r or r[0] != 's': + # e.g. vcc_hi or exec_hi as a carry-out / compare destination: not an SGPR the one-lane model holds + raise Unsupported('compare or carry destination %s' % dst) + d = r[1] self.set_s(d, expr) self.masks.add(d) def export(self, asm): - # disasm_rdna2 prints a compressed EN that is not a whole channel pair (0x0, 0x3, 0xC or 0xF) as - # an explicit en:0x.. flag. As in pixel_aot, such a mask is refused rather than guessed. - m = re.fullmatch(r'exp (\w+) (.*?)((?: done| compr| vm| en:0x[0-9a-f]+)*)', asm) + m = re.fullmatch(r'exp (\w+) (.*?)((?: done| compr| vm)*)', asm) if not m: + # e.g. a compressed export with an unpaired enable mask, which the disassembler prints as en:<mask> raise Unsupported('export form %r' % asm) target, vals, flags = m.group(1), [v.strip() for v in m.group(2).split(',')], m.group(3).split() if getattr(self, 'kind', None) == 'ms' and not getattr(self, 'in_mesh_export', False): @@ -5988,13 +7516,28 @@ def export(self, asm): % next(f for f in flags if f.startswith('en:'))[3:]) if 'vm' in flags and not self.exec_known: self.emit('if (!(exec & 1)) discard;') + if target == 'null': + # The null target carries no data; titles use it to end a pixel stage (done, vm) that exports nothing + # else, so only the valid-mask discard above applies. + if any(v != 'off' for v in vals) or self.kind != 'ps': + raise Unsupported('null export with data: %s' % asm) + return None if target == 'mrtz': - if (self.kind != 'ps' or self.has_branches or self.blocks or not self.exec_known or 'depth' in self.exports - or 'compr' in flags or len(vals) != 4 or not re.fullmatch(r'v\d+', vals[0]) - or vals[1:] != ['off', 'off', 'off']): - raise Unsupported('MRTZ requires one uncompressed depth export in a straight-line pixel shader with entry EXEC') + # Z export: x is depth, y stencil, z the sample mask, w alpha for alpha-to-coverage. Only a depth-only + # export (SPI_SHADER_32_R) has an HLSL output, SV_Depth; the others are refused by channel. + if self.kind != 'ps' or 'compr' in flags or vals[0] == 'off' or any(v != 'off' for v in vals[1:]): + raise Unsupported('mrtz export other than depth alone: %s' % asm) self.exports['depth'] = True - self.emit('o.depth = %s;' % self.f(vals[0])) + self.emit('o.depth = F(%s);' % self.u(vals[0])) + return None + if target == 'pos1' and self.kind == 'vs' and getattr(self.pipe, 'vs_out_cntl', None) is not None \ + and 'compr' not in flags: + # With VS_OUT_MISC_VEC_ENA clear and VS_OUT_CCDIST0_VEC_ENA set, the export after pos0 is the first + # clip/cull distance vector (see clip_vector_width); D3D: SV_ClipDistance0. + n = clip_vector_width(self.pipe.vs_out_cntl, vals) + self.exports['clip'] = n + parts = ', '.join('F(%s)' % self.u(v) for v in vals[:n]) + self.emit('o.clip0 = %s;' % (parts if n == 1 else 'float%d(%s)' % (n, parts))) return None name = {'pos0': 'pos'}.get(target, target) if not re.fullmatch(r'pos|param\d+|mrt[0-7]', name): @@ -6007,20 +7550,21 @@ def export(self, asm): mask = sum(1 << c for c, v in enumerate(vals) if v != 'off') if 'compr' in flags: if name.startswith('param'): - self.compr_params.add(int(name[5:])) + self.__dict__.setdefault('compr_params', set()).add(int(name[5:])) if kind in ('uint', 'int'): raise Unsupported('packed integer export %s' % name) - # Two binary16 channels per register: the low pair (0, 1) from the first, the high pair - # (2, 3) from the second, each printed twice or as 'off', 'off'. - if vals[1] != vals[0] or vals[3] != vals[2]: + # A compressed export takes x, y from the two halves of its first register and z, w from the second. + # The enable mask is per pair (0x3 and 0xc), and the disassembler prints each enabled register twice + # and a disabled pair as "off, off"; a disabled pair reads 0 like an "off" channel of a plain export. + if vals[0] != vals[1] or vals[2] != vals[3]: raise Unsupported('compressed export operands %s' % ', '.join(vals)) - if mask != 0xF and not name.startswith('mrt'): - raise Unsupported('partial compressed export to %s' % name) - pairs = [] + exprs = [] for v in (vals[0], vals[2]): - r = self.u(v) if v != 'off' else None - pairs += ['f16tof32(%s)' % r, 'f16tof32(%s >> 16)' % r] if r else ['0.0', '0.0'] - exprs = pairs + if v == 'off': + exprs += ['0.0', '0.0'] + else: + word = self.u(v) + exprs += ['f16tof32(%s)' % word, 'f16tof32(%s >> 16)' % word] words = ['0u' if e == '0.0' else 'U(%s)' % e for e in exprs] elif kind in ('uint', 'int'): exprs = ['0u' if v == 'off' else self.u(v) for v in vals] @@ -6033,13 +7577,13 @@ def export(self, asm): exprs = ['0.0' if v == 'off' else 'F(%s)' % self.u(v) for v in vals] words = ['0u' if v == 'off' else self.u(v) for v in vals] if name.startswith('param'): - self.plain_params[int(name[5:])] = {c for c, v in enumerate(vals) if v == 'off'} + self.__dict__.setdefault('plain_params', {})[int(name[5:])] = {c for c, v in enumerate(vals) if v == 'off'} if name.startswith('mrt'): # One pipeline write mask per target: an export of no channel, or two exports of one target # with different channels, cannot be represented and is refused. if not mask: raise Unsupported('export to %s writes no channel' % name) - known = self.write_masks.setdefault(name, mask) + known = self.__dict__.setdefault('write_masks', {}).setdefault(name, mask) if known != mask: raise Unsupported('exports to %s write channel masks 0x%x and 0x%x' % (name, known, mask)) self.exports[name] = True @@ -6051,21 +7595,48 @@ def export(self, asm): # denormals (#1259). hlsl_vs() drops the line for attributes the pixel stage reads only # interpolated. self.emit('o.f%s = uint4(%s);' % (name, ', '.join(words))) - if 'compr' not in flags and kind not in ('uint', 'int', 'bits'): - # The binary16 halves of each word for v_interp_p1ll_f16 / v_interp_p2_f16 (see interp_f16); - # interpolated like param, and dropped by hlsl_vs() unless the pixel stage reads them. - for half, shift in (('lo', ''), ('hi', ' >> 16')): - self.emit('o.h%s_%s = float4(%s);' % (name, half, ', '.join( - '0.0' if v == 'off' else 'f16tof32(%s%s)' % (self.u(v), shift) for v in vals))) + if 'compr' in flags: + # The words of a compressed export are not the registers' halves (each half went to its own + # channel), so a binary16 read of this attribute is refused (Pipeline.check_half_reads). + self.__dict__.setdefault('compr_params', set()).add(int(name[5:])) + return None + # The binary16 halves of each word as f32, interpolated for v_interp_p2_f16 (the hardware interpolates + # each half of the parameter word). Dropped like the flat copy when the pixel stage does not read them. + self.emit('o.lo%s = float4(%s);' % (name, ', '.join( + '0.0' if w == '0u' else 'f16tof32(%s)' % w for w in words))) + self.emit('o.hi%s = float4(%s);' % (name, ', '.join( + '0.0' if w == '0u' else 'f16tof32((%s) >> 16)' % w for w in words))) return None # ---- output ------------------------------------------------------------------------------ + LOOP_PASSES = 64 + + def counted_search(self, lo, hi): + if hi != lo + 3: + return False + (head, compare, test), (_, _, exhausted), (body, work, done), (_, latch, back) = self.blocks[lo:hi + 1] + if len(compare) != 1 or not (comparison := re.fullmatch(r'scc = (s\d+) >= (s\d+);', compare[0])): + return False + index, count = comparison.groups() + if index == count or test != ('branch', '!scc', body) or back != ('jump', head): + return False + if not exhausted or exhausted[0] != 'jump' or exhausted[-1] <= self.blocks[hi][0]: + return False + if not done or done[:2] != ('branch', '!scc') or done[-1] != exhausted[-1]: + return False + increment = '%s = %s + 0x00000001u;' % (index, index) + operands = re.compile(r'\b(?:%s|%s)\b' % (index, count)) + read_index = re.compile(r's\d+ = s\d+ \+ %s;' % index) + return bool(latch.count(increment) == 1 and all( + not operands.search(line) or (read_index.fullmatch(line) and line.split()[0] not in (index, count)) + for line in work + [line for line in latch if line != increment])) + def body(self): """Statements of the whole program as structured HLSL.""" + self.tw_substitute() out = [] offsets = [b[0] for b in self.blocks] index = {off: i for i, off in enumerate(offsets)} - loops = any(t and t[0] in ('jump', 'branch') and t[-1] <= b[0] for b in self.blocks for t in [b[2]]) if len(self.blocks) == 1: return [' ' + line for line in self.blocks[0][1]] @@ -6074,26 +7645,57 @@ def goto(off): raise Unsupported('branch into the middle of a block (+0x%x)' % off) return index[off] out.append(' uint pc = 0;') - if loops: - out.append(' [loop] for (uint guard = 0; guard < 65536 && pc != 0xffffu; ++guard) {') - for i, (off, lines, term) in enumerate(self.blocks): - if off == getattr(self, 'mesh_allocation_block', None): - out.append(' {') + # Only the blocks between a loop head and its back edge run inside a dispatch loop: the intervals + # [head, source] of the back edges, merged where they overlap. A branch out of a region goes forward (a + # backward one would be a back edge inside the region), so the blocks outside the regions, tested in offset + # order, run each at most once like the loop-free form. Same execution as one loop over all blocks; FXC + # takes minutes on a large dispatch loop, so the loop is kept as small as the control flow allows. + regions = [] + for j, (_, _, term) in enumerate(self.blocks): + if term and term[0] in ('jump', 'branch') and goto(term[-1]) <= j: + regions.append([goto(term[-1]), j]) + regions.sort() + merged = [] + for lo, hi in regions: + if merged and lo <= merged[-1][1]: + merged[-1][1] = max(merged[-1][1], hi) else: - out.append(' %sif (pc == %d) {' % ('else ' if loops and i else '', i)) - out += [' ' + line for line in lines] + merged.append([lo, hi]) + starts = {lo: hi for lo, hi in merged} + inside = None + for i, (off, lines, term) in enumerate(self.blocks): + if i in starts: + inside = starts[i] + # A hard bound so that a wrong lowering costs a wrong pixel, never a GPU timeout: LOOP_PASSES + # passes through the region (one block visit per guard step). ASSUMED enough for the title's loops. + if getattr(self, 'require_counted_search', False): + if not self.counted_search(i, inside): + raise Unsupported('pixel search has no proven unsigned iteration bound') + out.append(' [loop] while (pc >= %d && pc <= %d) {' % (i, inside)) + else: + out.append(' [loop] for (uint guard = 0; guard < %du && pc >= %d && pc <= %d; ++guard) {' + % (self.LOOP_PASSES * (inside - i + 1), i, inside)) + indent = ' ' if inside is not None else '' + first = inside is not None and i in starts + out.append(' %s%sif (pc == %d) {' % (indent, 'else ' if inside is not None and not first else '', i)) + for line in lines: + if line in getattr(self, 'uniform_dpp', ()): + out.extend([' }', ' ' + line, ' if (pc == %d) {' % i]) + else: + out.append(' ' + indent + line) nxt = i + 1 if i + 1 < len(self.blocks) else 0xffff if not term: - out.append(' pc = %d;' % nxt) + out.append(' %spc = %d;' % (indent, nxt)) elif term[0] == 'end': - out.append(' pc = 0xffffu;') + out.append(' %spc = 0xffffu;' % indent) elif term[0] == 'jump': - out.append(' pc = %d;' % goto(term[1])) + out.append(' %spc = %d;' % (indent, goto(term[1]))) else: - out.append(' pc = (%s) ? %d : %d;' % (term[1], goto(term[2]), nxt)) - out.append(' }') - if loops: - out.append(' }') + out.append(' %spc = (%s) ? %d : %d;' % (indent, term[1], goto(term[2]), nxt)) + out.append(' %s}' % indent) + if inside is not None and i == inside: + out.append(' }') + inside = None return out def declarations(self): @@ -6102,89 +7704,70 @@ def declarations(self): lines.append(' uint %s;' % ', '.join('s%d = 0' % n for n in sorted(self.used_s))) if self.used_v: lines.append(' uint %s;' % ', '.join('v%d = 0' % n for n in sorted(self.used_v))) - packed = self.pipe.packed_position_vgpr - if self.kind == 'ps' and packed in self.used_v: + if getattr(self, 'shadow_v', None): + lines.append(' uint %s;' % ', '.join('xv%d = 0' % n for n in sorted(self.shadow_v))) + packed = getattr(self.pipe, 'packed_position_vgpr', None) # the tests' bare pipelines have none + if self.kind == 'ps' and packed is not None and packed in self.used_v: lines.append(' v%d = (uint(i.pos.x) & 0xffffu) | ((uint(i.pos.y) & 0xffffu) << 16);' % packed) - if getattr(self, 'spill_slots', None): - lines.append(' uint %s;' % ', '.join('sp%d_%d = 0' % k for k in sorted(self.spill_slots))) + if self.kind == 'ps': + for reg, bit in sorted(getattr(self.pipe, 'ps_input_vgprs', {}).items()): + lines.append(' v%d = %s; // SPI input %s' % (reg, PS_INPUT_HLSL[bit], PS_INPUTS[bit][0])) + if getattr(self, 'lane_spill_slots', None): + lines.append(' uint %s;' % ', '.join('sp%d_%d = 0' % k for k in sorted(self.lane_spill_slots))) + if getattr(self, 'wave_vars', None): + lines.append(' uint %s;' % ', '.join('%s = 0' % v for v in self.wave_vars)) lines.append(' uint vcc = 0, exec = 1, m0 = 0, a = 0, w = 0; bool scc = false; float4 t = 0;') - if getattr(self, 'used_atomic', None): - if 'uint' in self.used_atomic: - lines.append(' uint ao = 0;') - if 'int' in self.used_atomic: - lines.append(' int ai = 0;') - lines += [' s%d = %s;' % kv for kv in sorted(getattr(self, 'materialized', {}).items())] + if getattr(self, 'pc_image_used', False): # pc_data_load: the stage's image words + image = self.pc_image[:len(self.pc_image) // 4 * 4] + lines.append(' static const uint x2w_pcimage[%d] = {%s};' % (len(image) // 4, ', '.join( + '0x%08xu' % w for w, in struct.iter_unpack('<I', image)))) + if self.used_h: + lines.append(' uint %s;' % ', '.join('h%d = 0' % k for k in sorted(self.used_h))) + if self.uses_q: + lines.append(' uint2 q = 0;') + if self.uses_swap: + lines.append(' uint xswap = 0;') + if self.uses_xsave: + lines.append(' uint xsave = 0;') return lines -# 32-bit raw MUBUF atomics: opcode_name -> (RWByteAddressBuffer method suffix, signed, is_sub, data_vgprs) -MUBUF_ATOMIC_OPS = { - 'buffer_atomic_swap': ('Exchange', False, False, 1), - 'buffer_atomic_cmpswap': ('CompareExchange', False, False, 2), - 'buffer_atomic_add': ('Add', False, False, 1), - 'buffer_atomic_sub': ('Add', False, True, 1), - 'buffer_atomic_smin': ('Min', True, False, 1), - 'buffer_atomic_umin': ('Min', False, False, 1), - 'buffer_atomic_smax': ('Max', True, False, 1), - 'buffer_atomic_umax': ('Max', False, False, 1), - 'buffer_atomic_and': ('And', False, False, 1), - 'buffer_atomic_or': ('Or', False, False, 1), - 'buffer_atomic_xor': ('Xor', False, False, 1), -} - -# Legacy straight-line LDS exchange ops checked by check_lds_exchange(). -LEGACY_LDS_EXCHANGE_OPS = frozenset(( - 'ds_write_b32', 'ds_read_b32', 'ds_read2_b32', 'ds_write_b64', 'ds_read_b64', 'ds_write_b128', 'ds_read_b128', -)) - -# Dual-offset & stride-64 32-bit LDS ops: name -> (is_write, offset_stride_bytes) -LDS_DUAL_OPS = { - 'ds_write2_b32': (True, 4), - 'ds_write2st64_b32': (True, 256), - 'ds_read2st64_b32': (False, 256), -} - -# 32-bit unsigned/bitwise LDS atomics: name -> (HLSL Interlocked* suffix, has_rtn) -LDS_ATOMIC_OPS = { - 'ds_add_u32': ('Add', False), - 'ds_min_u32': ('Min', False), - 'ds_max_u32': ('Max', False), - 'ds_and_b32': ('And', False), - 'ds_or_b32': ('Or', False), - 'ds_add_rtn_u32': ('Add', True), - 'ds_min_rtn_u32': ('Min', True), - 'ds_max_rtn_u32': ('Max', True), - 'ds_and_rtn_b32': ('And', True), - 'ds_or_rtn_b32': ('Or', True), - 'ds_wrxchg_rtn_b32': ('Exchange', True), -} - -LDS_DUAL_ATOMIC_OPS = frozenset((*LDS_DUAL_OPS, *LDS_ATOMIC_OPS)) - -# Unused w1 register field masks in RDNA 2 DS encoding (must be zero): -# w1[7:0]=ADDR, w1[15:8]=DATA0, w1[23:16]=DATA1, w1[31:24]=VDST. -LDS_UNUSED_W1_MASK = { - 'ds_write2_b32': 0xff000000, - 'ds_write2st64_b32': 0xff000000, - 'ds_read2st64_b32': 0x00ffff00, - **{op: (0x00ff0000 if has_rtn else 0xffff0000) for op, (_, has_rtn) in LDS_ATOMIC_OPS.items()}, -} - +# Identifiers Stage.lane_invariant accepts in an expression besides registers: pure HLSL functions and the +# translation's own pure helpers (x2w_* are accepted by prefix), the buffer Load method and literals. +LANE_INVARIANT_NAMES = frozenset(( + 'F', 'U', 'asuint', 'asfloat', 'asint', 'uint', 'int', 'float', 'uint2', 'float2', 'float3', 'float4', + 'min', 'max', 'abs', 'saturate', 'sqrt', 'rsqrt', 'exp2', 'log2', 'floor', 'ceil', 'trunc', 'frac', 'round', + 'sin', 'cos', 'countbits', 'firstbitlow', 'firstbithigh', 'reversebits', 'f16tof32', 'f32tof16', + 'mul_legacy', 'med3', 'clamp', 'Load', 'true', 'false')) +# The multiply-add rule for draw stages, X2W_DRAW_FMA: exact (default) = fused ops through fma in binary64 then one +# rounding (the binary32 product is exact in binary64, so this is the fused result except in rare double-rounding +# cases; needs DoublePrecisionFloatShaderOps), unfused ops as a `precise` multiply then add; precise = both through +# the precise multiply-add (deterministic, not the console's fused value); legacy = `a * b + c` as before (the +# compiler may fuse or not). Names differ from mesh2hlsl's x2w_fma/x2w_madp (same bodies) so a mesh pipeline, which +# emits its own, never gets two definitions. +FMA_FUSED = ('v_fma_f32', 'v_fmac_f32', 'v_fmamk_f32', 'v_fmaak_f32') +FMA_UNFUSED = ('v_mad_f32', 'v_mac_f32', 'v_madmk_f32', 'v_madak_f32') +DRAW_FMA = os.environ.get('X2W_DRAW_FMA', 'exact') +if DRAW_FMA not in ('exact', 'precise', 'legacy'): + raise SystemExit('X2W_DRAW_FMA: exact, precise or legacy, not %r' % DRAW_FMA) # name -> (source operand count, expression); operands are floats VEC_F = { 'v_add_f32': (2, '{0} + {1}'), 'v_sub_f32': (2, '{0} - {1}'), 'v_subrev_f32': (2, '{1} - {0}'), 'v_mul_f32': (2, '{0} * {1}'), 'v_mul_legacy_f32': (2, 'mul_legacy({0}, {1})'), 'v_min_f32': (2, 'min({0}, {1})'), 'v_max_f32': (2, 'max({0}, {1})'), - 'v_fmac_f32': (2, '{0} * {1} + {2}'), 'v_mac_f32': (2, 'mad32({0}, {1}, {2}, false)'), - 'v_fma_f32': (3, '{0} * {1} + {2}'), 'v_mad_f32': (3, 'mad32({0}, {1}, {2}, false)'), - 'v_mad_legacy_f32': (3, 'mad32({0}, {1}, {2}, true)'), + # LOCAL: the multiply-adds keep the local text (FMA_FUSED / FMA_UNFUSED rule in lower()); upstream's mad32 is not used. + 'v_fmac_f32': (2, '{0} * {1} + {2}'), 'v_mac_f32': (2, '{0} * {1} + {2}'), + 'v_fma_f32': (3, '{0} * {1} + {2}'), 'v_mad_f32': (3, '{0} * {1} + {2}'), 'v_mad_legacy_f32': (3, 'mul_legacy({0}, {1}) + {2}'), 'v_fmamk_f32': (3, '{0} * {1} + {2}'), 'v_fmaak_f32': (3, '{0} * {1} + {2}'), - 'v_madmk_f32': (3, 'mad32({0}, {1}, {2}, false)'), 'v_madak_f32': (3, 'mad32({0}, {1}, {2}, false)'), + 'v_madmk_f32': (3, '{0} * {1} + {2}'), 'v_madak_f32': (3, '{0} * {1} + {2}'), 'v_rcp_f32': (1, '1.0 / {0}'), 'v_rcp_iflag_f32': (1, '1.0 / {0}'), 'v_rsq_f32': (1, 'rsqrt({0})'), 'v_sqrt_f32': (1, 'sqrt({0})'), 'v_exp_f32': (1, 'exp2({0})'), 'v_log_f32': (1, 'log2({0})'), 'v_floor_f32': (1, 'floor({0})'), 'v_ceil_f32': (1, 'ceil({0})'), 'v_trunc_f32': (1, 'trunc({0})'), 'v_fract_f32': (1, 'fract32({0})'), 'v_rndne_f32': (1, 'round({0})'), 'v_sin_f32': (1, 'sin({0} * 6.283185307)'), 'v_cos_f32': (1, 'cos({0} * 6.283185307)'), - 'v_med3_f32': (3, 'med3_32({0}, {1}, {2})'), 'v_min3_f32': (3, 'min({0}, min({1}, {2}))'), 'v_max3_f32': (3, 'max({0}, max({1}, {2}))'), + 'v_med3_f32': (3, 'med3({0}, {1}, {2})'), 'v_min3_f32': (3, 'min({0}, min({1}, {2}))'), 'v_max3_f32': (3, 'max({0}, max({1}, {2}))'), + # Cube-map face selection; x2w_cube() returns (face id, sc, tc, 2 * major axis), see HELPERS. + 'v_cubeid_f32': (3, 'x2w_cube({0}, {1}, {2}).x'), 'v_cubesc_f32': (3, 'x2w_cube({0}, {1}, {2}).y'), + 'v_cubetc_f32': (3, 'x2w_cube({0}, {1}, {2}).z'), 'v_cubema_f32': (3, 'x2w_cube({0}, {1}, {2}).w'), } # Conversions whose result is binary32. The expression is the float value, so an output modifier # (clamp, mul:2, mul:4, div:2) can wrap it the way it wraps any other float result. The uint-result @@ -6203,20 +7786,23 @@ def declarations(self): 'v_not_b32': (1, '~{0}'), 'v_lshlrev_b32': (2, '{1} << ({0} & 31)'), 'v_lshrrev_b32': (2, '{1} >> ({0} & 31)'), 'v_ashrrev_i32': (2, 'uint(int({1}) >> ({0} & 31))'), 'v_min_u32': (2, 'min({0}, {1})'), 'v_max_u32': (2, 'max({0}, {1})'), 'v_min_i32': (2, 'uint(min(int({0}), int({1})))'), 'v_max_i32': (2, 'uint(max(int({0}), int({1})))'), - 'v_min3_u32': (3, 'min(min({0}, {1}), {2})'), - 'v_max3_u32': (3, 'max(max({0}, {1}), {2})'), + # Three-operand integer forms (RDNA2 ISA: V_MIN3/V_MAX3/V_MED3 _I32/_U32; median = max(min(a, b), min(max(a, b), c)), + # the identity the f32 med3 helper uses). + 'v_min3_u32': (3, 'min({0}, min({1}, {2}))'), 'v_max3_u32': (3, 'max({0}, max({1}, {2}))'), + 'v_min3_i32': (3, 'uint(min(int({0}), min(int({1}), int({2}))))'), + 'v_max3_i32': (3, 'uint(max(int({0}), max(int({1}), int({2}))))'), 'v_med3_u32': (3, 'max(min({0}, {1}), min(max({0}, {1}), {2}))'), - 'v_min3_i32': (3, 'uint(min(min(int({0}), int({1})), int({2})))'), - 'v_max3_i32': (3, 'uint(max(max(int({0}), int({1})), int({2})))'), 'v_med3_i32': (3, 'uint(max(min(int({0}), int({1})), min(max(int({0}), int({1})), int({2}))))'), 'v_cvt_u32_f32': (1, 'uint(max(F({0}), 0.0))'), - 'v_cvt_f16_f32': (1, 'f32tof16(F({0}))'), + 'v_cvt_f16_f32': (1, 'x2w_f32tof16_rne(F({0}))'), # nearest even (MODE 0; check_round16 refuses other modes) 'v_bfe_u32': (3, '({0} >> ({1} & 31)) & ((1u << ({2} & 31)) - 1)'), 'v_mad_u32_u24': (3, '({0} & 0xffffffu) * ({1} & 0xffffffu) + {2}'), 'v_mad_i32_i24': (3, 'asuint(asint({0} << 8) >> 8) * asuint(asint({1} << 8) >> 8) + {2}'), 'v_lshl_add_u32': (3, '({0} << ({1} & 31)) + {2}'), 'v_add_lshl_u32': (3, '({0} + {1}) << ({2} & 31)'), 'v_add3_u32': (3, '{0} + {1} + {2}'), - 'v_or3_b32': (3, '{0} | {1} | {2}'), 'v_xor3_b32': (3, '{0} ^ {1} ^ {2}'), 'v_and_or_b32': (3, '({0} & {1}) | {2}'), 'v_lshl_or_b32': (3, '({0} << ({1} & 31)) | {2}'), + 'v_or3_b32': (3, '{0} | {1} | {2}'), 'v_xor3_b32': (3, '{0} ^ {1} ^ {2}'),'v_and_or_b32': (3, '({0} & {1}) | {2}'), 'v_lshl_or_b32': (3, '({0} << ({1} & 31)) | {2}'), 'v_xad_u32': (3, '({0} ^ {1}) + {2}'), 'v_bfi_b32': (3, '({0} & {1}) | (~{0} & {2})'), 'v_mul_u32_u24': (2, '({0} & 0xffffffu) * ({1} & 0xffffffu)'), + # v_bfm_b32: a mask of S0[4:0] ones shifted left by S1[4:0] (RDNA 2 ISA VOP3; same formula as s_bfm_b32). + 'v_bfm_b32': (2, '(((1u << ({0} & 31)) - 1) << ({1} & 31))'), 'v_mul_i32_i24': (2, 'asuint(asint({0} << 8) >> 8) * asuint(asint({1} << 8) >> 8)'), # Per-lane bit operations (AMD RDNA 2 ISA reference). The bitscan results count from the most significant # bit for the "h" forms and read 0xffffffff when no bit qualifies; firstbitlow(0) is already 0xffffffff. @@ -6228,10 +7814,570 @@ def declarations(self): 'v_ffbh_u32': (1, '({0} == 0u ? 0xffffffffu : 31u - firstbithigh({0}))'), 'v_ffbh_i32': (1, '({0} == 0u || {0} == 0xffffffffu ? 0xffffffffu : 31u - firstbithigh(asint({0}) < 0 ? ~{0} : {0}))'), 'v_bfrev_b32': (1, 'reversebits({0})'), + # The high word of the unsigned 64-bit product; shader model 5.1 has no 64-bit integers (see HELPERS). + 'v_mul_hi_u32': (2, 'x2w_mul_hi_u32({0}, {1})'), + 'v_mul_hi_i32': (2, 'x2w_mul_hi_u32({0}, {1}) - ((0u - ({0} >> 31u)) & {1}) - ((0u - ({1} >> 31u)) & {0})'), + # D = S0[15:0] * S1[15:0] + S2 (op_sel, which picks other halves, arrives as a modifier and is refused). + 'v_mad_u32_u16': (3, '({0} & 0xffffu) * ({1} & 0xffffu) + {2}'), 'v_sad_u8': (3, 'sad_u8({0}, {1}, {2})'), 'v_sad_u16': (3, 'sad_u16({0}, {1}, {2})'), 'v_sad_u32': (3, 'sad_u32({0}, {1}, {2})'), } +# HLSL helpers, each emitted only by pipelines whose code calls it. The integer helpers are single expressions so +# tests/startup_gfx2hlsl_coverage_check.py can evaluate their text against plain integer references. +# x2w_mul_hi_u32: bits 63:32 of the unsigned product, from four 16-bit partial products; the carry into bit 32 +# comes from the high half of the low product plus the low halves of the two cross products (each sum < 2^18). +MUL_HI_U32 = ('(a >> 16) * (b >> 16) + (((a & 0xffffu) * (b >> 16)) >> 16) + (((a >> 16) * (b & 0xffffu)) >> 16) + ' + '(((((a & 0xffffu) * (b & 0xffffu)) >> 16) + (((a & 0xffffu) * (b >> 16)) & 0xffffu) + ' + '(((a >> 16) * (b & 0xffffu)) & 0xffffu)) >> 16)') +# v_cmp_class: the bit index of the IEEE class of x in the S1 mask (LLVM SIDefines.h ClassFlags): 0 signaling NaN, +# 1 quiet NaN, 2 -inf, 3 -normal, 4 -subnormal, 5 -0, 6 +0, 7 +subnormal, 8 +normal, 9 +inf. Classified on the bits, +# so no float compare or denormal flush can change the answer. +CLASS_F32 = ('(((x >> 23) & 255u) == 255u ? ((x & 0x7fffffu) != 0u ? ((x >> 22) & 1u) : ((x >> 31) != 0u ? 2u : 9u)) : ' + '((x >> 23) & 255u) != 0u ? ((x >> 31) != 0u ? 3u : 8u) : ' + '(x & 0x7fffffu) != 0u ? ((x >> 31) != 0u ? 4u : 7u) : ((x >> 31) != 0u ? 5u : 6u))') +CLASS_F16 = ('(((x >> 10) & 31u) == 31u ? ((x & 0x3ffu) != 0u ? ((x >> 9) & 1u) : (((x >> 15) & 1u) != 0u ? 2u : 9u)) : ' + '((x >> 10) & 31u) != 0u ? (((x >> 15) & 1u) != 0u ? 3u : 8u) : ' + '(x & 0x3ffu) != 0u ? (((x >> 15) & 1u) != 0u ? 4u : 7u) : (((x >> 15) & 1u) != 0u ? 5u : 6u))') +LSHR64_LO = ('((n & 63u) == 0u ? l : (n & 63u) < 32u ? (l >> (n & 63u)) | (h << (32u - (n & 63u))) : ' + 'h >> ((n & 63u) - 32u))') +LSHR64_HI = '((n & 63u) < 32u ? h >> (n & 63u) : 0u)' +LSHL64_LO = '((n & 63u) < 32u ? l << (n & 63u) : 0u)' +LSHL64_HI = ('((n & 63u) == 0u ? h : (n & 63u) < 32u ? (h << (n & 63u)) | (l >> (32u - (n & 63u))) : ' + 'l << ((n & 63u) - 32u))') +# SCA operations folded when every operand is a known constant (Stage.scalar), as their SCA texts compute them +# (AMD RDNA ISA: S_BREV_B32 D.u[31:0] = S0.u[0:31], no SCC write). s_bfm_b32 has its own folding handler. +SCALAR_CONST_FOLD = { + 's_brev_b32': lambda a: int('{:032b}'.format(a)[::-1], 2), +} + +HELPERS = { + # The product of binary16 inputs is exact in f32. Use FastTwoSum for the addition + # residual, then round to odd at f32 precision. The final conversion to f16 can + # decide ties and directed rounding without double rounding. + 'x2w_half_madd_odd': '''float x2w_half_madd_odd(float a, float b, float c) { + precise float p = a * b; + precise float sum = p + c; + if (!isfinite(sum)) return sum; + precise float hi = abs(p) >= abs(c) ? p : c; + precise float lo = abs(p) >= abs(c) ? c : p; + precise float tail = lo - (sum - hi); + uint u = asuint(sum); + if (tail == 0.0 || (u & 1u)) return sum; + return asfloat((tail > 0.0) == (sum > 0.0) ? u + 1u : u - 1u); + }''', + 'x2w_mul_hi_u32': 'uint x2w_mul_hi_u32(uint a, uint b) { return %s; }' % MUL_HI_U32, + 'x2w_class_f32': 'uint x2w_class_f32(uint x, uint mask) { return (mask >> %s) & 1u; }' % CLASS_F32, + # binary16 rounding toward zero (MODE[3:2] = 3, see Stage.op_s_round_mode): f32tof16, then one step toward zero + # when that rounded away from zero. Exact if f32tof16 rounds to nearest or toward zero: overflow to inf steps + # back to 0x7bff; a NaN or an exactly representable value stays (the compare is false). + 'x2w_f32tof16_rtz': ('uint x2w_f32tof16_rtz(float x) { uint h = f32tof16(x); ' + 'return abs(f16tof32(h)) > abs(x) ? h - 1u : h; }'), + # binary16 rounding to nearest even (MODE[3:2] = 0): t = the toward-zero result (as x2w_f32tof16_rtz, inlined so + # the helper stands alone), u = the next value away from zero (0x7c00 counts as 65536, the first value past the + # range, so 65520 and above round to inf); the nearer wins, a tie goes to the even one. The two distances are + # exact in f32 (Sterbenz: |x| lies within [lo, 2 lo] of the f16 neighbours, or lo is 0). inf and NaN stay. + 'x2w_f32tof16_rne': ('uint x2w_f32tof16_rne(float x) { uint t = f32tof16(x); float a = abs(x); ' + 'if (abs(f16tof32(t)) > a) t -= 1u; if ((t & 0x7c00u) == 0x7c00u) return t; ' + 'float lo = abs(f16tof32(t)); if (a == lo) return t; uint u = t + 1u; ' + 'float hi = (u & 0x7fffu) == 0x7c00u ? 65536.0 : abs(f16tof32(u)); ' + 'float dl = a - lo, dh = hi - a; return (dh < dl || (dh == dl && (t & 1u) != 0u)) ? u : t; }'), + # a * b + c for binary16 a, b, c (exact in f32): the f32 sum rounded to odd when inexact, so that one later + # rounding to binary16 is the fused result (see Stage.f16_bits). TwoSum error e; inf/NaN pass through. + 'x2w_f16_fma': ('float x2w_f16_fma(float a, float b, float c) { precise float p = a * b; ' + 'precise float s = p + c; if ((asuint(s) & 0x7f800000u) == 0x7f800000u) return s; ' + 'precise float bb = s - p; precise float e = (p - (s - bb)) + (c - bb); uint u = asuint(s); ' + 'if ((asuint(e) & 0x7fffffffu) != 0u && (u & 1u) == 0u) ' + 'u += ((asuint(e) ^ u) & 0x80000000u) != 0u ? 0xffffffffu : 1u; return asfloat(u); }'), + 'x2w_class_f16':'uint x2w_class_f16(uint x, uint mask) { return (mask >> %s) & 1u; }' % CLASS_F16, + # The words of a 64-bit shift of (l, h) by n[5:0]. HLSL masks shift counts to five bits, so a count of 0 + # (where 32 - n would wrap to a shift by 0) and counts of 32..63 are separate cases. + 'x2w_lshr64_lo': 'uint x2w_lshr64_lo(uint l, uint h, uint n) { return %s; }' % LSHR64_LO, + 'x2w_lshr64_hi': 'uint x2w_lshr64_hi(uint l, uint h, uint n) { return %s; }' % LSHR64_HI, + 'x2w_lshl64_lo': 'uint x2w_lshl64_lo(uint l, uint h, uint n) { return %s; }' % LSHL64_LO, + 'x2w_lshl64_hi': 'uint x2w_lshl64_hi(uint l, uint h, uint n) { return %s; }' % LSHL64_HI, + # v_cube{id,sc,tc,ma}_f32 as LLVM's constant folder defines them (ConstantFoldAMDGCNCubeIntrinsic): the + # major axis is z when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|, else x; a negative major axis is one + # that is below zero (not -0, not NaN). ma is twice the major-axis component. + 'x2w_cube': ('float4 x2w_cube(float a, float b, float c) { ' + 'if (abs(c) >= abs(a) && abs(c) >= abs(b)) return float4(c < 0.0 ? 5.0 : 4.0, c < 0.0 ? -a : a, -b, c + c); ' + 'if (abs(b) >= abs(a)) return float4(b < 0.0 ? 3.0 : 2.0, a, b < 0.0 ? -c : c, b + b); ' + 'return float4(a < 0.0 ? 1.0 : 0.0, a < 0.0 ? c : -c, -b, a + a); }'), + # One 16-bit half of v_cvt_pknorm_{u16,i16}_f32, per Mesa ACO selection (Mesa main 13ebbc00, + # src/amd/compiler/instruction_selection/aco_select_nir_alu.cpp selects nir pack_[us]norm_2x16 to these + # opcodes) with the NIR definition (src/compiler/nir/nir_constant_expressions.py pack_[us]norm_1x16): + # (uint16_t)(int)roundeven(CLAMP(x, lo, 1) * 65535 or 32767). Mesa's CLAMP (src/util/macros.h) is + # "X > MIN ? (X > MAX ? MAX : X) : MIN", so NaN gives MIN: unorm 0, snorm -32767 (0x8001). The NaN case is + # decided on the bits so no compiler min/max rewrite can change it; HLSL round() rounds half to even. + 'x2w_pknorm_u16': ('uint x2w_pknorm_u16(float x) { if ((asuint(x) & 0x7fffffffu) > 0x7f800000u) return 0u; ' + 'return uint(round(clamp(x, 0.0, 1.0) * 65535.0)); }'), + 'x2w_pknorm_i16': ('uint x2w_pknorm_i16(float x) { if ((asuint(x) & 0x7fffffffu) > 0x7f800000u) return 0x8001u; ' + 'return uint(int(round(clamp(x, -1.0, 1.0) * 32767.0))) & 0xffffu; }'), +} + +# gfx10 buffer FORMAT codes (V# word 3 [18:12]) the draw runtime can synthesize for a typed buffer view +# (gfx10_view_words.h gfx10_buffer_words; raw and structured views get 22, 32_FLOAT) and their channels, x first +# from bit 0: (bit widths, numeric kind). Mixed widths list x, y, z, w as the bits rise: 10_11_11_FLOAT is x 11, y +# 11, z 10; 2_10_10_10 is x 10, y 10, z 10, w 2. Codes from Mesa's gfx10 format table, as in gfx10_view_words.h. +BUF_FORMATS = { + 1: ((8,), 'unorm'), 2: ((8,), 'snorm'), 5: ((8,), 'uint'), 6: ((8,), 'sint'), + 7: ((16,), 'unorm'), 8: ((16,), 'snorm'), 11: ((16,), 'uint'), 12: ((16,), 'sint'), 13: ((16,), 'float'), + 14: ((8, 8), 'unorm'), 15: ((8, 8), 'snorm'), 18: ((8, 8), 'uint'), 19: ((8, 8), 'sint'), + 20: ((32,), 'uint'), 21: ((32,), 'sint'), 22: ((32,), 'float'), + 23: ((16, 16), 'unorm'), 24: ((16, 16), 'snorm'), 27: ((16, 16), 'uint'), 28: ((16, 16), 'sint'), + 29: ((16, 16), 'float'), + 36: ((11, 11, 10), 'float'), + 50: ((10, 10, 10, 2), 'unorm'), 54: ((10, 10, 10, 2), 'uint'), + 56: ((8, 8, 8, 8), 'unorm'), 57: ((8, 8, 8, 8), 'snorm'), 60: ((8, 8, 8, 8), 'uint'), 61: ((8, 8, 8, 8), 'sint'), + 62: ((32, 32), 'uint'), 63: ((32, 32), 'sint'), 64: ((32, 32), 'float'), + 65: ((16,) * 4, 'unorm'), 66: ((16,) * 4, 'snorm'), 69: ((16,) * 4, 'uint'), 70: ((16,) * 4, 'sint'), + 71: ((16,) * 4, 'float'), + 72: ((32,) * 3, 'uint'), 73: ((32,) * 3, 'sint'), 74: ((32,) * 3, 'float'), + 75: ((32,) * 4, 'uint'), 76: ((32,) * 4, 'sint'), 77: ((32,) * 4, 'float'), +} + + +def buf_format_channel(widths, kind, k): + """HLSL for channel k (a Python int) of an element at byte address a of ByteAddressBuffer b, as a uint.""" + pos, n = sum(widths[:k]), widths[k] + field = 'b.Load(a + %du)' % (pos // 8) if n == 32 else \ + '((ldu(b, a + %du) >> %du) & 0x%xu)' % (4 * (pos // 32), pos % 32, (1 << n) - 1) + if kind == 'uint' or (kind == 'float' and n == 32): + return field + if kind == 'sint': + return field if n == 32 else 'uint(int(%s << %du) >> %du)' % (field, 32 - n, 32 - n) + if kind == 'unorm': + return 'U(float(%s) / %d.0)' % (field, (1 << n) - 1) + if kind == 'snorm': + return 'U(max(float(int(%s << %du) >> %du) / %d.0, -1.0))' % (field, 32 - n, 32 - n, (1 << (n - 1)) - 1) + # binary16, and the unsigned 11-bit (5-bit exponent, 6-bit mantissa) and 10-bit (5, 5) floats, which are the + # upper bits of a binary16 without its sign + return 'U(f16tof32(%s))' % (field if n == 16 else '(%s << %du)' % (field, 15 - n)) + + +def buf_format_helper(): + """x2w_fmt_load(b, a, w3, c): channel c of a buffer_load_format_* result, from V# word 3 w3 (udsrc bufword3). + + DST_SEL_X/Y/Z/W ([2:0] [5:3] [8:6] [11:9]): 0 -> 0, 1 -> 1 (1.0 for a float format, 1 for an integer one), + 4..7 -> element channel x..w. A channel the format lacks reads 0 (w reads 1, as the fill 0001); a FORMAT code + not in BUF_FORMATS (0 = invalid, which the runtime gives for raw-copy, vertex and root sources) reads 0 in + every channel, as do selectors 2 and 3. These fills are assumptions, not measured.""" + lines = ['uint x2w_fmt_chan(ByteAddressBuffer b, uint a, uint f, uint k, uint one) {'] + for code, (widths, kind) in sorted(BUF_FORMATS.items()): + chans = ' '.join('if (k == %du) return %s;' % (k, buf_format_channel(widths, kind, k)) for k in range(len(widths))) + lines.append(' if (f == %du) { %s return k == 3u ? one : 0u; }' % (code, chans)) + lines.append(' return 0u; }') + known = ' || '.join('f == %du' % c for c in sorted(BUF_FORMATS)) + ints = ' || '.join('f == %du' % c for c, (_, kind) in sorted(BUF_FORMATS.items()) if kind in ('uint', 'sint')) + lines.append('uint x2w_fmt_load(ByteAddressBuffer b, uint a, uint w3, uint c) {') + lines.append(' uint f = (w3 >> 12) & 127u, s = (w3 >> (3u * c)) & 7u;') + lines.append(' if (!(%s) || s == 0u || s == 2u || s == 3u) return 0u;' % known) + lines.append(' uint one = (%s) ? 1u : 0x3f800000u;' % ints) + lines.append(' return s == 1u ? one : x2w_fmt_chan(b, a, f, s - 4u, one); }') + return '\n'.join(lines) + + +FMT_KIND = {'uint': 0, 'sint': 1, 'unorm': 2, 'snorm': 3, 'float': 4} + + +def buf_format_word(code): + """x2w_fmt_tab entry: channel widths x, y, z, w in 6-bit fields [5:0] [11:6] [17:12] [23:18] (0 = absent), kind + in [26:24] (FMT_KIND); 0 for a code not in BUF_FORMATS.""" + if code not in BUF_FORMATS: + return 0 + widths, kind = BUF_FORMATS[code] + word = FMT_KIND[kind] << 24 + for k, n in enumerate(widths): + word |= n << (6 * k) + return word + + +def buf_format_helper_table(): + """The same x2w_fmt_load as buf_format_helper, written once for every format: the format code indexes a constant + table of channel widths and kind, and one channel decoder serves all formats. Values are the same as the per-format + chain's (same field, sign extension, UNORM/SNORM divisor, binary16 widening), except that the UNORM/SNORM divisor + is a run-time value here rather than a literal, so the compiler cannot replace the division by a multiply.""" + size = max(BUF_FORMATS) + 1 + table = ', '.join('0x%08xu' % buf_format_word(c) for c in range(size)) + return '\n'.join([ + 'static const uint x2w_fmt_tab[%d] = { %s };' % (size, table), + 'uint x2w_fmt_chan(ByteAddressBuffer b, uint a, uint d, uint k, uint one) {', + ' uint n = (d >> (6u * k)) & 63u;', + ' if (n == 0u) return k == 3u ? one : 0u;', + ' uint pos = (k > 0u ? (d & 63u) : 0u) + (k > 1u ? ((d >> 6) & 63u) : 0u) + (k > 2u ? ((d >> 12) & 63u) : 0u);', + ' uint kind = (d >> 24) & 7u, sh = 32u - n;', + ' uint raw = n == 32u ? b.Load(a + pos / 8u) : ((ldu(b, a + 4u * (pos / 32u)) >> (pos % 32u)) & ((1u << n) - 1u));', + ' int sv = int(raw << sh) >> sh;', + ' if (kind == 0u || (kind == 4u && n == 32u)) return raw;', + ' if (kind == 1u) return uint(sv);', + ' if (kind == 2u) return U(float(raw) / float((1u << n) - 1u));', + ' if (kind == 3u) return U(max(float(sv) / float((1u << (n - 1u)) - 1u), -1.0));', + ' return U(f16tof32(n == 16u ? raw : raw << (15u - n))); }', + 'uint x2w_fmt_load(ByteAddressBuffer b, uint a, uint w3, uint c) {', + ' uint f = (w3 >> 12) & 127u, s = (w3 >> (3u * c)) & 7u;', + ' uint d = f < %du ? x2w_fmt_tab[f] : 0u;' % size, + ' if (d == 0u || s == 0u || s == 2u || s == 3u) return 0u;', + ' uint one = ((d >> 24) & 7u) <= 1u ? 1u : 0x3f800000u;', + ' return s == 1u ? one : x2w_fmt_chan(b, a, d, s - 4u, one); }']) + + +# The table form: fxc 10.0.26100 took 432.6 s for a vertex stage with two calls of the per-format chain and 0.6 s with +# this one (translator_work NOTES round 5). buf_format_helper stays as the reference the check compares against. +HELPERS['x2w_fmt_load'] = buf_format_helper_table() +HELPERS['x2w_fmt_store'] = '\n'.join([ + 'void x2w_fmt_store(RWByteAddressBuffer b, uint a, uint w3, uint4 v, uint m) {', + ' uint f = (w3 >> 12) & 127u;', + ' uint n = (f >= 20u && f <= 22u) ? 1u : (f >= 62u && f <= 64u) ? 2u : (f >= 72u && f <= 74u) ? 3u :', + ' (f >= 75u && f <= 77u) ? 4u : 0u;', + ' n = min(n, m);', + ' if (n > 0u) b.Store(a, v.x);', + ' if (n > 1u) b.Store(a + 4u, v.y);', + ' if (n > 2u) b.Store(a + 8u, v.z);', + ' if (n > 3u) b.Store(a + 12u, v.w); }']) +# v_ldexp_f32: S0 * 2^S1.i with f32 denormals flushed (the launch FLOAT_MODE the lowering matches, LAUNCH_DENORM), so +# a normal result is exact (no rounding), a denormal input reads as a signed zero and a result below 2^-126 flushes to +# one; infinity and NaN pass through. The exponent is clamped first so the sum cannot wrap. +HELPERS['x2w_ldexp'] = ('float x2w_ldexp(float x, uint e) { uint b = asuint(x), s = b & 0x80000000u, ' + 'ex = (b >> 23) & 255u; if (ex == 255u) return x; if (ex == 0u) return asfloat(s); ' + 'int n = int(ex) + clamp(asint(e), -512, 512); return asfloat(n >= 255 ? (s | 0x7f800000u) : ' + 'n <= 0 ? s : (s | (uint(n) << 23) | (b & 0x7fffffu))); }') +HELPERS['x2w_fma_exact'] = ('float x2w_fma_exact(float a, float b, float c) ' + '{ return (float)fma((double)a, (double)b, (double)c); }') +# The draw stages compile with fxc, which folds constant operands of the double fma into d(a, b) immediates and, +# when it packs two calls into one register, writes the second through .zw with the constant in the immediate's +# second half. WARP and the RX 9070 XT driver read that half as the first one (`dfma r0.zw, r1.xyxy, r1.zwzw, +# d(0.0, 1.5)` adds 0.0), so the result is wrong. The draw stages therefore XOR every operand with x2w_fz, a static +# that main() sets to (p * p + p) & 1 of an input word p: always 0 (p(p + 1) is even, also mod 2^32), and fxc does +# not prove it, so no operand reaches the double ops as an immediate and the result bits are unchanged. +# The publisher refuses any stage whose bytecode still has a double op with a non-zero immediate second half. +FMA_EXACT_FXC = ('static uint x2w_fz;\n' + 'float x2w_fma_exact(float a, float b, float c) { return (float)fma((double)asfloat(asuint(a) ^ x2w_fz), ' + '(double)asfloat(asuint(b) ^ x2w_fz), (double)asfloat(asuint(c) ^ x2w_fz)); }') +# X2W_PS_WAVE_UNION=1 (default off): a wave64 reduction lowered to the SM 6.0 wave intrinsic over the host wave. +# s_or_saveexec_b64 sM, -1 (exec = all lanes; sM = the lanes that were active) +# ... (no branch, and nothing that names sM or exec) +# v_cndmask_b32_e64 vR, IDENT, vS, sM (inactive lanes give the identity: -1 for min, 0 for max and or) +# v_OP_dpp vR, vR, vR quad_perm:[1,0,3,2] / quad_perm:[2,3,0,1] / row_half_mirror / row_mirror +# (each with row_mask:0xf bank_mask:0xf fi:1) +# v_permlanex16_b32 vT, vR, 0, 0 +# v_OP_e32 vR, vR, vT +# v_readlane_b32 sK, vR, 0 +# v_OP_e32 vR, sK, vR +# s_mov_b64 exec, sM +# then exactly one read before vR or vT is touched again: v_readlane_b32 sZ, vR, 63 (the full 64-lane result). +# The guest result is OP over the wave64's active lanes, so it depends on which lanes the hardware packed into the +# wave. With the gate the HLSL takes OP over the active lanes of the host wave instead (WaveActiveMin / Max / +# BitOr), which is a wave membership too; the manifest says `wavemembership host`. Only this exact chain is taken: +# other DPP forms keep their refusals, and the plan is dropped if vR or vT is named anywhere else in the program. +WAVE_UNION_OPS = {'min_u32': 'WaveActiveMin', 'max_u32': 'WaveActiveMax', 'or_b32': 'WaveActiveBitOr'} +WAVE_UNION_IDENT = {'min_u32': '0xffffffff', 'max_u32': '0x00000000', 'or_b32': '0x00000000'} +WAVE_UNION_IDENT_TOKEN = {'min_u32': '-1', 'max_u32': '0', 'or_b32': '0'} +WAVE_UNION_CONTROLS = ('quad_perm:[1,0,3,2]', 'quad_perm:[2,3,0,1]', 'row_half_mirror', 'row_mirror') + + +def wave_union_regs(ops): + out = set() + for t in ops: + t = t.strip('-|') + r = reg_range(t) + if r: + out.update('%s%d' % (r[0], k) for k in range(r[1], r[2] + 1)) + elif t in ('exec', 'exec_lo', 'exec_hi'): + out.add('exec') + return out + + +def wave_union_chain(rows, j, mask_tok): + """(vR, vT, op, vS, sK, member indices) when rows[j] starts the exact reduction chain (see WAVE_UNION_OPS). + + The ten chain instructions may be interleaved with others that name none of vR, vT, sK, sM or exec and do not + branch; those keep their normal lowering.""" + off, name, cops, cmods = rows[j] + mask = reg_range(mask_tok) + if name != 'v_cndmask_b32_e64' or cmods or len(cops) != 4 or reg_range(cops[3]) != ('s', mask[1], mask[1]): + return None + vr, src = reg_range(cops[0]), reg_range(cops[2]) + if not vr or vr[0] != 'v' or vr[1] != vr[2] or not src or src[0] != 'v' or src[1] != src[2]: + return None + R = 'v%d' % vr[1] + members, seq, k = [j], [], j + 1 + while len(seq) < 9 and k < len(rows): + named = wave_union_regs(rows[k][2]) + if rows[k][1].startswith(('s_cbranch', 's_branch', 's_endpgm')): + return None + if R in named or 'exec' in named or rows[k][1].endswith(('_dpp', 'permlanex16_b32')): + seq.append(rows[k]) + members.append(k) + k += 1 + if len(seq) != 9 or not seq[0][1].endswith('_dpp'): + return None + op = seq[0][1][2:-4] + if op not in WAVE_UNION_OPS or cops[1] != WAVE_UNION_IDENT_TOKEN[op]: + return None + for n in range(4): + if seq[n][1] != 'v_%s_dpp' % op or seq[n][2] != [R, R, R] or seq[n][3][:1] != [WAVE_UNION_CONTROLS[n]] or sorted(seq[n][3][1:]) != sorted(['row_mask:0xf', 'bank_mask:0xf', 'fi:1']): + return None + perm = seq[4] + vt = reg_range(perm[2][0]) if perm[2] else None + if perm[1] != 'v_permlanex16_b32' or not vt or vt[0] != 'v' or vt[1] != vt[2] or perm[2][1:] != [R, '0', '0'] or perm[3]: + return None + T = 'v%d' % vt[1] + rl = reg_range(seq[6][2][0]) if len(seq[6][2]) == 3 else None + if seq[5][1] != 'v_%s_e32' % op or seq[5][2] != [R, R, T] or seq[6][1] != 'v_readlane_b32' or seq[6][2][1:] != [R, '0'] or not rl or rl[0] != 's' or rl[1] != rl[2] or seq[7][1] != 'v_%s_e32' % op or seq[7][2] != [R, 's%d' % rl[1], R] or seq[8][1] != 's_mov_b64' or seq[8][2] != ['exec', mask_tok]: + return None + K = 's%d' % rl[1] + mreg = {'s%d' % mask[1], 's%d' % mask[2]} + for n in range(j + 1, members[-1]): + if n not in members and wave_union_regs(rows[n][2]) & ({R, T, K, 'exec'} | mreg): + return None + return R, T, op, 'v%d' % src[1], K, members + + +WAVE_SCC_WRITERS = ('s_cmp_', 's_bitcmp', 's_and_', 's_or_', 's_xor_', 's_andn2_', 's_orn2_', 's_nand_', 's_nor_', + 's_xnor_', 's_add_', 's_sub_', 's_addc_', 's_subb_', 's_lshl_', 's_lshr_', 's_ashr_', 's_min_', + 's_max_', 's_bfe_', 's_not_', 's_abs_', 's_bcnt0_', 's_bcnt1_', 's_absdiff_', 's_lshl1_add', + 's_lshl2_add', 's_lshl3_add', 's_lshl4_add', 's_and_saveexec', 's_or_saveexec', 's_xor_saveexec', + 's_andn2_saveexec', 's_orn2_saveexec', 's_nand_saveexec', 's_nor_saveexec', 's_xnor_saveexec', + 's_wqm_', 's_quadmask_', 's_cmpk_') +# scalar instructions that do not write SCC (RDNA 2 ISA SOP1/SOP2/SOPK/SMEM tables) +WAVE_SCC_KEEP = ('s_mov_', 's_movk_', 's_cmov_', 's_cmovk_', 's_cselect_', 's_load_', 's_buffer_load_', 's_waitcnt', + 's_nop', 's_getpc_', 's_bfm_', 's_mul_i32', 's_mulk_', 's_mul_hi', 's_pack_', 's_ff0_', 's_ff1_', + 's_flbit_', 's_brev_', 's_sext_', 's_bitset', 's_inst_prefetch', 's_clause', 's_setprio', + 's_dcache', 's_sendmsg', 's_branch', 's_cbranch', 's_endpgm') +WAVE_NO_DST = ('s_cmp_', 's_bitcmp', 's_cmpk_', 's_waitcnt', 's_nop', 's_branch', 's_cbranch', 's_endpgm', + 's_inst_prefetch', 's_clause', 's_setprio', 's_dcache', 's_sendmsg', 's_buffer_store', 's_store') + + +def wave_union_tokens(ops): + """Operand tokens: 'sN' / 'm0' (tracked scalars), 'V' (a VGPR), 'T' (exec, vcc, a src_* mask: per lane).""" + out = set() + for t in ops: + t = t.strip('-|') + if t.startswith(('exec', 'vcc', 'src_')): + out.add('T') + continue + if t == 'm0': + out.add('m0') + continue + r = reg_range(t) + if r and r[0] == 's': + out.update('s%d' % k for k in range(r[1], r[2] + 1)) + elif r and r[0] == 'v': + out.add('V') + return out + + +def wave_union_uniform(ins, plan): + """({s_cbranch_scc offset: None when its SCC is host-uniform, else the reason}, {offsets of v_readfirstlane_b32 + whose source is uniform among the lanes whose guest exec bit is set}) for X2W_PS_WAVE_UNION=1. + + Host-uniform: in the HLSL every lane holds the same value. With every branch decided per host wave, all lanes run + the same scalar statements, so a scalar computed from constants, user data, scalar loads of uniform addresses and + other host-uniform scalars is host-uniform; so is a wave result (the plan's readlane 63) and an accepted + v_readfirstlane. Forward may-analysis over the blocks (a register is non-uniform at a block start when it is on + some incoming edge): a write from exec, vcc, m0, a VGPR or a non-uniform scalar (or SCC) makes the destination + non-uniform, any other write makes it uniform. SCC follows its writers; a scalar op not known to keep SCC is + taken as a writer that may also keep the old SCC. A readfirstlane is accepted when its source was written in the + same block by a VALU op (not DPP, lane or interpolation) of host-uniform scalars and constants, with no exec write + between: every lane whose exec bit is set then computed the same value.""" + rows = [(off, name, parse(asm)[1]) for off, n, name, asm in ins] + targets = set() + for off, name, ops in rows: + if name.startswith(('s_branch', 's_cbranch')) and ops and ops[0].startswith('label_'): + targets.add(int(ops[0].split('_')[1], 16)) + leaders = sorted({0} | {k for k, r in enumerate(rows) if r[0] in targets} | + {k + 1 for k, r in enumerate(rows) + if r[1].startswith(('s_branch', 's_cbranch', 's_endpgm')) and k + 1 < len(rows)}) + at = {r[0]: k for k, r in enumerate(rows)} + blocks = list(zip(leaders, leaders[1:] + [len(rows)])) + start_of = {s: i for i, (s, e) in enumerate(blocks)} + succ = [] + for s, e in blocks: + off, name, ops = rows[e - 1] + out = [] + if name.startswith(('s_branch', 's_cbranch')) and ops and ops[0].startswith('label_'): + t = at.get(int(ops[0].split('_')[1], 16)) + if t is not None: + out.append(start_of[t]) + if not name.startswith(('s_branch', 's_endpgm')) and e < len(rows): + out.append(start_of[e]) + succ.append(out) + + def dsts_srcs(name, ops): + if name.startswith('s_'): + if name.startswith(WAVE_NO_DST) or not ops: + return set(), wave_union_tokens(ops) + return wave_union_tokens(ops[:1]), wave_union_tokens(ops[1:]) | ({'T'} if 'saveexec' in name else set()) + if name.startswith('v_') and ops: + d = wave_union_tokens(ops[:1]) + if '_co_' in name or 'div_scale' in name: + d |= wave_union_tokens(ops[1:2]) + return d, wave_union_tokens(ops[1:]) | ({'T'} if 'cmpx' in name else set()) + return set(), set() + + rfl_ok, scc_at = set(), {} + + def run(b, bad, record): + bad = set(bad) + fresh = set() # VGPRs written in this block by a VALU op of uniform scalars, exec unchanged since + s, e = blocks[b] + for k in range(s, e): + off, name, ops = rows[k] + step = plan.get(off) + if step is not None: + if step[0] == 'read': + bad -= wave_union_tokens([step[2]]) + continue + if name in ('s_cbranch_scc0', 's_cbranch_scc1') and record: + scc_at[off] = 'scc' in bad + d, srcs = dsts_srcs(name, ops) + if name == 'v_readfirstlane_b32': + good = len(ops) > 1 and ops[1] in fresh + if record and good: + rfl_ok.add(off) + bad = (bad - d) if good else (bad | d) + continue + # a VGPR source counts as uniform only when it is fresh (and only for a VALU op) + vin = {t for t in wave_union_regs(ops[1:]) if t.startswith('v')} if name.startswith('v_') else set() + stale_v = bool(vin - fresh) if vin else 'V' in srcs + nonuni = stale_v or bool(srcs & {'T', 'm0'}) or bool(srcs & bad) or ( + name.startswith(('s_cselect', 's_cmov', 's_addc', 's_subb')) and 'scc' in bad) + if name.startswith('s_') and not name.startswith(WAVE_SCC_KEEP): + if name.startswith(WAVE_SCC_WRITERS): + bad.discard('scc') + if nonuni: + bad.add('scc') + sd = {t for t in d if t != 'V'} + # A VALU op's SGPR result (a compare mask, a carry-out, a readlane) is per lane in the HLSL + # (exec & cond): never host-uniform. The plan's reads and accepted readfirstlanes are handled above. + bad = (bad | sd) if (nonuni or name.startswith('v_')) else (bad - sd) + if 'T' in d or 'saveexec' in name or 'cmpx' in name: + fresh.clear() + if name.startswith('v_') and ops: + r = reg_range(ops[0].strip('-|')) + if r and r[0] == 'v': + regs = {'v%d' % q for q in range(r[1], r[2] + 1)} + if (r[1] == r[2] and not nonuni and not name.endswith('_dpp') and 'lane' not in name + and 'interp' not in name + and not name.startswith(('v_cndmask', 'v_addc', 'v_subb', 'v_div_fmas'))): + fresh |= regs + else: + fresh -= regs + return bad + + entry = [None] * len(blocks) + entry[0] = frozenset({'m0'}) + work = [0] + while work: + b = work.pop() + out = frozenset(run(b, entry[b], False)) + for t in succ[b]: + new = out if entry[t] is None else entry[t] | out + if new != entry[t]: + entry[t] = new + work.append(t) + for b in range(len(blocks)): + if entry[b] is not None: + run(b, entry[b], True) + scc = {off: ('SCC from exec, vcc, a VGPR or a non-uniform scalar' if v else None) for off, v in scc_at.items()} + for off, name, ops in rows: + if name in ('s_cbranch_scc0', 's_cbranch_scc1') and off not in scc: + scc[off] = 'unreachable in the analysis' + return scc, rfl_ok + + +def wave_union_plan(ins): + """{pc: step} for the recognised reduction chains of ins: ('reduce', var, op, vS, ident, sM) at the v_cndmask, + ('skip',) for the eight DPP / permlane / combine / readlane-0 instructions, ('read', var, sZ) at the readlane of + lane 63, which must write the readlane-0 register sK (so the partial value it held is never read). Empty when + anything about vR / vT / sK is outside the pattern; the normal lowering then refuses the DPP.""" + rows = [(off, name, parse(asm)[1], parse(asm)[2]) for off, n, name, asm in ins] + chains = [] + for i, (off, name, ops, mods) in enumerate(rows): + if name != 's_or_saveexec_b64' or len(ops) != 2 or ops[1] != '-1' or mods: + continue + mask = reg_range(ops[0]) + if not mask or mask[0] != 's' or mask[2] != mask[1] + 1: + continue + mreg = {'s%d' % mask[1], 's%d' % mask[2], 'exec'} + j = i + 1 + while j < len(rows) and rows[j][1] != 'v_cndmask_b32_e64': + if rows[j][1].startswith(('s_cbranch', 's_branch', 's_endpgm')) or wave_union_regs(rows[j][2]) & mreg: + break + j += 1 + if j < len(rows): + found = wave_union_chain(rows, j, ops[0]) + if found: + chains.append((j,) + found + (ops[0],)) + if not chains: + return {} + plan, covered = {}, set() + starts = {j for j, *_ in chains} + for c, (j, R, T, op, src, K, members, mask) in enumerate(chains): + read = None + for k in range(members[-1] + 1, len(rows)): + if k in starts: + break + name, ops = rows[k][1], rows[k][2] + if read is None and name == 'v_readlane_b32' and len(ops) == 3 and ops[1:] == [R, '63']: + if ops[0] != K: + return {} + read = k + continue + named = wave_union_regs(ops) + if named & {R, T} or (read is None and K in named): + return {} + if read is None: + return {} + var = 'wu%d' % c + plan[rows[j][0]] = ('reduce', var, op, src, WAVE_UNION_IDENT[op], mask) + for k in members[1:-1]: + plan[rows[k][0]] = ('skip',) + plan[rows[read][0]] = ('read', var, rows[read][2][0]) + covered.update(members) + covered.add(read) + names = set().union(*({R, T} for _j, R, T, *_ in chains)) + for k, (off, name, ops, mods) in enumerate(rows): + if k not in covered and wave_union_regs(ops) & names: + return {} + return plan + + +def zero_operand(text): + """True when an emitted f32 operand is the constant +0 or -0 (with or without neg/abs). + + fxc folds such an operand of x2w_fma_exact into a d(0, 0) double immediate even behind x2w_fz (asfloat(0 ^ x2w_fz) + is 0 or a denormal, and the conversion to double flushes it), and the publisher refuses every d(...) immediate. + With a zero factor the fused result needs no wide product (the product is an exact signed zero, or NaN for an + infinite or NaN other factor), and a -0 addend adds exactly to the once-rounded product, so x2w_mad_precise + (round(a * b), then round(p + c)) is bit-identical to the fma there; see exact_with_zero.""" + core = text.replace('(', '').replace(')', '').replace('-', '').replace('abs', '').replace(' ', '') + return core in ('0.0', '0', 'F0x00000000u', 'F0x80000000u') + + +def negative_zero(text): + """True for an emitted -0 constant: (-0.0), F(0x80000000u), (-F(0x00000000u)) (not under abs).""" + return 'abs' not in text and text.replace(' ', '') in ('(-0.0)', '-0.0', 'F(0x80000000u)', '(-F(0x00000000u))') + + +def exact_with_zero(args): + """x2w_mad_precise equals the fma for these three operands: a zero factor, or a -0 addend. A +0 addend is not + taken: a negative product that rounds to -0 gives fma -0 + +0 = +0 too, but one that the host flushes after + the multiply gives -0 before the add and the precise add then gives +0 where a fused result could keep -0.""" + return zero_operand(args[0]) or zero_operand(args[1]) or negative_zero(args[2]) + + +# v_readfirstlane_b32 under X2W_PS_WAVE_UNION=1: S0 of the lowest host-wave lane whose guest exec bit is set (the +# ballot names it). With no such lane the hardware reads lane 0; here the first HLSL lane running the statement. +HELPERS['x2w_readfirstlane'] = ('uint x2w_readfirstlane(uint v, bool active) { uint4 b = WaveActiveBallot(active); ' + 'uint i = b.x != 0u ? firstbitlow(b.x) : b.y != 0u ? 32u + firstbitlow(b.y) : ' + 'b.z != 0u ? 64u + firstbitlow(b.z) : b.w != 0u ? 96u + firstbitlow(b.w) : 0xffffffffu; ' + 'return i == 0xffffffffu ? WaveReadLaneFirst(v) : WaveReadLaneAt(v, i); }') +HELPERS['x2w_mad_precise'] = ('float x2w_mad_precise(float a, float b, float c) ' + '{ precise float p = a * b; precise float r = p + c; return r; }') +# VEC_U conversions whose result is a binary32 value, so the VOP3 output modifiers apply to it. +FLOAT_RESULT_U = frozenset(('v_cvt_f32_u32', 'v_cvt_f32_i32', 'v_cvt_f32_ubyte0', 'v_cvt_f32_ubyte1', + 'v_cvt_f32_ubyte2', 'v_cvt_f32_ubyte3', 'v_cvt_f32_f16')) # scalar ops: (expression over uint sources, SCC rule with $ for the result or None) # Scalar ops that write SCC on the hardware (carry, overflow, or which source was selected) but have # no SCC template here: the emitted scc keeps its previous value, so the uniformity proof stops @@ -6253,32 +8399,107 @@ def declarations(self): 's_add_i32': ('{0} + {1}', None), 's_add_u32': ('{0} + {1}', None), 's_sub_i32': ('{0} - {1}', None), 's_sub_u32': ('{0} - {1}', None), 's_mul_i32': ('{0} * {1}', None), 's_min_u32': ('min({0}, {1})', None), 's_max_u32': ('max({0}, {1})', None), 's_min_i32': ('uint(min(int({0}), int({1})))', None), 's_max_i32': ('uint(max(int({0}), int({1})))', None), - 's_bfe_u32': ('({0} >> ({1} & 31)) & ((({1} >> 16) & 127) >= 32 ? 0xffffffffu : ((1u << (({1} >> 16) & 31)) - 1))', '$ != 0'), + 's_bfe_u32': ('({0} >> ({1} & 31)) & ((1u << (({1} >> 16) & 127)) - 1)', '$ != 0'), # LOCAL (upstream: width >= 32 guard) 's_brev_b32': ('reversebits({0})', None), - # s_mul_hi_u32: high 32 bits of the unsigned 64-bit product; SCC unchanged. - 's_mul_hi_u32': ('mul_hi_u32({0}, {1})', None), + # s_bcnt0/1_i32_b32: the count of zero / one bits of S0; SCC = (D != 0) (AMD RDNA 2 ISA SOP1, LLVM + # SOPInstructions.td: Defs = [SCC]). + 's_bcnt1_i32_b32': ('countbits({0})', '$ != 0'), 's_bcnt0_i32_b32': ('32u - countbits({0})', '$ != 0'), + # s_ff1/s_ff0_i32_b32: the index of the lowest one / zero bit of S0, -1 when there is none; SCC unchanged (AMD + # RDNA 2 ISA SOP1; LLVM SOPInstructions.td has no SCC def; it selects AMDGPUffbl_b32 = cttz_zero_undef with + # the -1 result). HLSL firstbitlow returns 0xffffffff for 0 as well. + 's_ff1_i32_b32': ('firstbitlow({0})', None), 's_ff0_i32_b32': ('firstbitlow(~{0})', None), # s_sext_i32_iN: sign-extend the low N bits of S0; SCC unchanged. 's_sext_i32_i8': ('uint(int({0} << 24) >> 24)', None), 's_sext_i32_i16': ('uint(int({0} << 16) >> 16)', None), - # s_pack_*_b32_b16: two halfwords of the sources into one word; SCC unchanged. - 's_pack_ll_b32_b16': ('({0} & 0xffffu) | ({1} << 16)', None), 's_pack_lh_b32_b16': ('({0} & 0xffffu) | ({1} & 0xffff0000u)', None), - 's_pack_hh_b32_b16': ('({0} >> 16) | ({1} & 0xffff0000u)', None), - # s_absdiff_i32: D = S0 - S1 wrapped to 32 bits, negated if negative (INT_MIN stays); SCC = result != 0. - 's_absdiff_i32': ('asuint(abs(asint({0} - {1})))', '$ != 0'), # s_bfm_b32: a mask of S0[4:0] ones shifted left by S1[4:0]; SCC unchanged. 's_bfm_b32': ('(((1u << ({0} & 31)) - 1) << ({1} & 31))', None), - # s_lshlN_add_u32: low 32 bits of (S0 << N) + S1. SHIFT_ADD also supplies SCC for wide overflow. + # s_absdiff_i32: D = |S0 - S1| with the 32-bit wrapping difference (|INT_MIN| stays INT_MIN); SCC = (D != 0) + # (RDNA 2 ISA SOP2; LLVM SOPInstructions.td Defs = [SCC]). + 's_absdiff_i32': ('uint(abs(int({0} - {1})))', '$ != 0'), + 's_mul_hi_u32': ('x2w_mul_hi_u32({0}, {1})', None), + # LLVM SOPInstructions.td: s_lshlN_add_u32 selects shlN_add, (S0 << N) + S1; it defines SCC, not modelled. 's_lshl1_add_u32': ('({0} << 1) + {1}', None), 's_lshl2_add_u32': ('({0} << 2) + {1}', None), 's_lshl3_add_u32': ('({0} << 3) + {1}', None), 's_lshl4_add_u32': ('({0} << 4) + {1}', None), + # s_abs_i32 is what LLVM selects for smax(x, -x) (so abs(INT_MIN) stays INT_MIN); it defines SCC, not modelled. + 's_abs_i32': ('uint(max(int({0}), -int({0})))', None), + # s_pack_ll_b32_b16 selects build_vector(src0, src1): S0[15:0] in the low half, S1[15:0] in the high half. + # It does not define SCC. + 's_pack_ll_b32_b16': ('({0} & 0xffffu) | ({1} << 16)', None), + # s_pack_hh_b32_b16 selects build_vector(trunc(src0 >> 16), trunc(src1 >> 16)) (LLVM SIInstructions.td): + # S0[31:16] in the low half, S1[31:16] in the high half. No SCC (SOP2_32 outside the Defs = [SCC] block). + 's_pack_hh_b32_b16': ('({0} >> 16) | ({1} & 0xffff0000u)', None), + # LLVM SOPInstructions.td S_SEXT_I32_I8 / S_SEXT_I32_I16: sext_inreg of S0 to i8 / i16; no SCC def. + 's_sext_i32_i8': ('uint(int({0} << 24) >> 24)', None), 's_sext_i32_i16': ('uint(int({0} << 16) >> 16)', None), } -# SCA operations folded when every operand is a known constant (Stage.scalar), computing what their SCA text -# computes (AMD RDNA 2 ISA: S_BREV_B32 D.u[31:0] = S0.u[0:31], no SCC write). s_bfm_b32 has its own handler. -SCALAR_CONST_FOLD = { - 's_brev_b32': lambda a: int('{:032b}'.format(a)[::-1], 2), -} -# shift amount of the scalar shift-and-add forms; their SCC is a carry from the sources, not a rule over the result -SHIFT_ADD = {'s_lshl1_add_u32': 1, 's_lshl2_add_u32': 2, 's_lshl3_add_u32': 3, 's_lshl4_add_u32': 4} +# Scalar ops whose SCC result the translation does not compute (LLVM SOPInstructions.td lists SCC in their Defs). +# Stage.check_scc refuses a program only when that SCC can reach a reader. +SCC_UNMODELLED = frozenset(('s_add_u32', 's_add_i32', 's_sub_u32', 's_sub_i32', 's_min_u32', 's_max_u32', 's_min_i32', + 's_max_i32', 's_abs_i32', 's_addk_i32', 's_lshl1_add_u32', 's_lshl2_add_u32', + 's_lshl3_add_u32', 's_lshl4_add_u32', 's_lshl_b64', 's_lshr_b64', 's_ashr_i64')) +SCC_READERS = ('s_cbranch_scc0', 's_cbranch_scc1', 's_cselect_b32', 's_cselect_b64', 's_cmov_b32', 's_cmov_b64', + 's_cmovk_i32', 's_addc_u32', 's_subb_u32') + + +def reads_scc(name, asm): + return re.sub(r'_e(32|64)$', '', name) in SCC_READERS or 'src_scc' in parse(asm)[1] + + +# Carry-out SALU forms whose SCC the translation computes only where it can be read (Stage.scalar_carry), so the +# HLSL of programs whose carry is never read does not change. s_add_i32 / s_sub_i32 (signed overflow) stay out. +CARRY_OUT = frozenset(('s_add_u32', 's_sub_u32')) +CARRY_CHAIN = CARRY_OUT | {'s_addc_u32', 's_subb_u32'} + + +def writes_scc_static(name): + """Whether a scalar instruction writes SCC in hardware (LLVM SOPInstructions.td Defs = [SCC]), as far as the + carry pre-pass needs it: stopping a walk early only leaves a carry unemitted, which check_scc then refuses.""" + base = re.sub(r'_e(32|64)$', '', name) + return (base in SCC_UNMODELLED or base in CARRY_CHAIN or (base in SCA and SCA[base][1] is not None) + or base.startswith(('s_cmp_', 's_cmpk_', 's_bitcmp')) or 'saveexec' in base or 'wrexec' in base) + + +def carry_scc_writers(ins, calculated, names=None): + """Offsets of s_add_u32 / s_sub_u32 / s_addc_u32 / s_subb_u32 whose SCC can reach an SCC reader before + another SCC write, over fall-through and branch edges (as Stage.check_scc walks them). Instructions of the + calculated-PC proof are neither writers nor readers here.""" + info = {off: (name, asm) for off, n, name, asm in ins} + order = [off for off, n, name, asm in ins] + following = dict(zip(order, order[1:])) + + def successors(off): + name, asm = info[off] + if off in calculated: + target = calculated[off] + return [target] if target in info else [following[off]] if off in following else [] + if name == 's_endpgm': + return [] + nxt = [] if name == 's_branch' else [following[off]] if off in following else [] + if name.startswith('s_cbranch') or name == 's_branch': + try: + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + except (IndexError, ValueError): + return [] + return [o for o in nxt if o in info] + out = set() + for start, (name, asm) in info.items(): + if name not in (CARRY_CHAIN if names is None else names) or start in calculated: + continue + seen, todo = set(), list(successors(start)) + while todo: + off = todo.pop() + if off in seen: + continue + seen.add(off) + name2, asm2 = info[off] + if off not in calculated and reads_scc(name2, asm2): + out.add(start) + break + if off not in calculated and writes_scc_static(name2): + continue + todo.extend(successors(off)) + return out + for _name, _op in (('eq', '=='), ('lg', '!='), ('gt', '>'), ('ge', '>='), ('lt', '<'), ('le', '<=')): for _typ, _cast in (('i32', 'int({0}) %s int({1})'), ('u32', '{0} %s {1}')): def _make(op=_op, cast=_cast, name='s_cmp_%s_%s' % (_name, _typ)): @@ -6290,27 +8511,45 @@ def handler(self, ops, mods): self.set_scc((cast % op).format(self.u(ops[0]), self.u(ops[1]))) return handler setattr(Stage, 'op_s_cmp_%s_%s' % (_name, _typ), _make()) - for _typ, _cast in (('i32', 'int({0}) %s int({1})'), ('u32', '{0} %s {1}')): - def _make_cmpk(op=_op, cast=_cast, signed=_typ == 'i32', name='s_cmpk_%s_%s' % (_name, _typ)): + + def _make_k(op=_op, cast=_cast, signed=_typ == 'i32', name='s_cmpk_%s_%s' % (_name, _typ)): + # s_cmpk_*_i32 compares with signext(SIMM16), s_cmpk_*_u32 with SIMM16 zero-extended (LLVM s16imm / + # u16imm); the disassembler prints the field unsigned either way. def handler(self, ops, mods): + # A wrong operand count is refused by count, like s_cmp_* (upstream handler arity check). if len(ops) != 2: raise Unsupported('%s with %d operands, expected 2' % (name, len(ops))) if mods: - raise Unsupported('%s with modifiers' % name) - self.set_scc((cast % op).format(self.u(ops[0]), '0x%08xu' % sopk_imm(ops[1], signed))) + raise Unsupported('s_cmpk with %s %s' % (ops, mods)) + imm = sopk_simm(ops[1]) if signed else ops[1] + self.emit('scc = %s;' % (cast % op).format(self.u(ops[0]), self.u(imm))) return handler - setattr(Stage, 'op_s_cmpk_%s_%s' % (_name, _typ), _make_cmpk()) -# s_bitcmp1_b32 / s_bitcmp0_b32: SCC = S0[S1[4:0]] == 1 / == 0. -for _bit in (0, 1): - def _make_bitcmp(bit=_bit): - def handler(self, ops, mods): - if len(ops) != 2 or mods: - raise Unsupported('scalar bit test requires two unmodified operands') - if any(self.is_lane_mask(tok) for tok in ops): - raise Unsupported('scalar bit test on a lane mask') - self.set_scc('((%s >> (%s & 31)) & 1u) == %du' % (self.u(ops[0]), self.u(ops[1]), bit)) - return handler - setattr(Stage, 'op_s_bitcmp%d_b32' % _bit, _make_bitcmp()) + setattr(Stage, 'op_s_cmpk_%s_%s' % (_name, _typ), _make_k()) + + +def _cmp_u64(equal): + # s_cmp_eq_u64 / s_cmp_lg_u64: SCC = (S0 == S1) / (S0 != S1) on 64-bit values (RDNA 2 ISA, SOPC). Lowered on + # data pairs only (a 64-bit pointer or constant read from memory, an inline constant): a lane mask compared + # with anything is a question about the whole wave, which this one-lane model holds as this lane's bit only, + # so exec, vcc and any pair holding a lane mask (or a copy of exec) are refused. + def handler(self, ops, mods): + if len(ops) != 2 or mods: + raise Unsupported('s_cmp_%s_u64 form %s %s' % ('eq' if equal else 'lg', ops, mods)) + for tok in ops: + r = reg_range(tok) + if r and r[0] == 's' and any(n in getattr(self, 'masks', ()) or (self.sym.get(n) or ('',))[0] == 'execcopy' + for n in (r[1], r[2])): + raise Unsupported('s_cmp_%s_u64 on a lane mask' % ('eq' if equal else 'lg')) + (a0, a1), (b0, b1) = self.pair(ops[0]), self.pair(ops[1]) + if equal: + self.emit('scc = %s == %s && %s == %s;' % (a0, b0, a1, b1)) + else: + self.emit('scc = %s != %s || %s != %s;' % (a0, b0, a1, b1)) + return handler + + +Stage.op_s_cmp_eq_u64 = _cmp_u64(True) +Stage.op_s_cmp_lg_u64 = _cmp_u64(False) def scalar_wide_fold(helper, x, amount, signed): @@ -6373,6 +8612,35 @@ def read(fmt, data, offset): SAMPLER_HEAP_FALLBACK = SAMPLER_HEAP_SIZE - 1 +# Draw lowerings that need the draw runtime to parse a manifest line, named in X2W_DRAW_FEATURES (comma list): +# heap (`heap 1`), bufword3 (`udsrc <n> bufword3 <srv>` for buffer_load_format_*), uav (`uav <i> buf table ...` +# with `udsrc <n> uavbase <i>` for buffer stores), heapwords (`heapwords 1`: a resource-heap view's synthesized +# descriptor words from vdesc, for buffer_load_format_* through a heap descriptor; needs heap and bufword3), +# descword (`udsrc <n> descword <param> <byte>`: a table descriptor word read as a number, Stage.table_word; the +# runtime takes the line only with X2W_MESH_DESCWORD=1 and otherwise refuses the translation at draw time). +# Off by default until a build with the runtime side is announced. +KNOWN_DRAW_FEATURES = frozenset(('heap', 'bufword3', 'uav', 'heapwords', 'uavfmt', 'descword', 'mixfma')) + + +def draw_features(): + named = frozenset(f for f in os.environ.get('X2W_DRAW_FEATURES', '').replace(' ', '').split(',') if f) + unknown = named - KNOWN_DRAW_FEATURES + if unknown: + raise SystemExit('X2W_DRAW_FEATURES: unknown %s' % ', '.join(sorted(unknown))) + return named + + +# Resource-heap views of a draw (manifest `heap 1`, layout agreed with draw-rt): the title heap memory heapmem +# (t0 space1, a view token per 32-byte slot: HEAP_TOKEN then the view id), vinfo (t1 space1, 16 bytes per view id, +# dword 0 the buffer stride), and one array per kind over the view-id region, index 8 + 8 * id + kind for ids below +# HEAP_IDS and kind alone (an empty view) otherwise. Bounded arrays, so FXC needs no unbounded-table flag. +HEAP_TOKEN = 0x56573258 +HEAP_IDS = 90000 +HEAP_KINDS = {'tex2d': ('heaptex2d', 0, 'Texture2D<float4>'), 'tex2da': ('heaptex2da', 1, 'Texture2DArray<float4>'), + 'tex3d': ('heaptex3d', 2, 'Texture3D<float4>'), 'tex1d': ('heaptex1d', 3, 'Texture1D<float4>'), + 'buf': ('heapbuf', 4, 'ByteAddressBuffer')} + + # DXGI_FORMAT values for integer RTVs and the binary32 float targets. UINT_RTVS = frozenset((3, 7, 12, 17, 25, 30, 36, 42, 50, 57, 62)) SINT_RTVS = frozenset((4, 8, 14, 18, 32, 38, 43, 52, 59, 64)) @@ -6389,6 +8657,51 @@ def read(fmt, data, offset): VERIFIED_SINT_RTVS = frozenset((4, 14, 18, 32, 38, 43, 52, 59, 64)) +# SPI pixel-stage inputs in SPI_PS_INPUT_ENA/ADDR bit order and the VGPRs each takes (Mesa +# src/amd/common/ac_shader_util.c ac_get_fs_input_vgpr_cnt): the IJ pairs, the pull model's three, then +# one VGPR each for line stipple, POS_X/Y/Z/W_FLOAT, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT. +PS_INPUTS = (('persp_sample', 2), ('persp_center', 2), ('persp_centroid', 2), ('persp_pull_model', 3), + ('linear_sample', 2), ('linear_center', 2), ('linear_centroid', 2), ('line_stipple', 1), + ('pos_x_float', 1), ('pos_y_float', 1), ('pos_z_float', 1), ('pos_w_float', 1), + ('front_face', 1), ('ancillary', 1), ('sample_coverage', 1), ('pos_fixed_pt', 1)) +POS_FIXED_PT = 15 +# SPI inputs lowered besides POS_FIXED_PT (bit -> HLSL uint expression over PSIn i). Mesa +# ac_nir_lower_intrinsics_to_args.c reads frag_coord x/y/z from POS_X/Y/Z_FLOAT and frag_coord_w_rcp from +# POS_W_FLOAT; nir_builder.c nir_build_frag_coord makes gl_FragCoord.w = frcp(frag_coord_w_rcp), and D3D +# SV_Position.w is 1 / gl_FragCoord.w (vkd3d-shader spirv.c frag_coord_fixup), so POS_W_FLOAT is SV_Position.w. +PS_INPUT_HLSL = {8: 'U(i.pos.x)', 9: 'U(i.pos.y)', 10: 'U(i.pos.z)', 11: 'U(i.pos.w)', + # FRONT_FACE is the float +1.0 (front) or -1.0 (back): Mesa nir_intrinsics.py front_face_fsign + # "front_face ? 1.0 : -1.0", which ac_nir_lower_intrinsics_to_args.c loads as the front_face argument + # itself (and load_front_face as fgt(arg, 0)). SV_IsFrontFace follows the PSO's FrontCounterClockwise, + # which the runtime sets from the cull register (pipeline_state_decode.h); the manifest says + # `frontface 1` so these keys can be found if that convention changes (X2W_DRAW_STATE_CULL_FLIP). + 12: 'U(i.ff ? 1.0 : -1.0)'} +FRONT_FACE = 12 +# The SPI position inputs, which a per-sample stage would read at the sample (see PS_SAMPLE_RATE). +PS_POSITION_INPUTS = (8, 9, 10, 11) +# The *_sample barycentrics: the stage runs per sample and the position inputs are at the sample, which a plain +# SV_Position input is not. +PS_SAMPLE_RATE = (1 << 0) | (1 << 4) + + +def ps_input_layout(ena, addr): + """VGPR -> SPI input bit for the given SPI_PS_INPUT_ENA/ADDR, or Unsupported. + + The VGPRs follow ADDR, the inputs the code was compiled for; ENA names the ones the hardware initializes + and must lie inside ADDR (Mesa ac_print_spi_ps_input_vgpr_list walks the ADDR bits to number v0, v1, ... and + marks an input "initialized" only when its ENA bit is also set). Both are 16-bit masks. + """ + if not 0 <= ena <= 0xffff or not 0 <= addr <= 0xffff or ena & ~addr: + raise Unsupported('unverified pixel input enable/address combination %#x/%#x' % (ena, addr)) + layout, vgpr = {}, 0 + for bit, (_, width) in enumerate(PS_INPUTS): + if addr >> bit & 1: + for _ in range(width): + layout[vgpr] = bit + vgpr += 1 + return layout + + class Pipeline: vertex_kind = 'vs' uses_pack16_rne = False @@ -6396,27 +8709,33 @@ class Pipeline: uses_store_d16_x = False uses_sad = () srv_formats = () - uavs = None # key -> dict(index, kind): images a pixel stage stores to (u registers); None until the first store - - def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), ps_hw_inputs=None, vs_fetch=None, - refusals=None, decoded=None, ps_attr_map=None, srv_formats=()): + f16_plain = () # mesh2hlsl's MeshPipeline (local) reuses interface() without Pipeline.__init__ + + def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), ps_hw_inputs=None, + features=None, vs_out_cntl=None, rw_keys=(), vs_fetch=None, refusals=None, decoded=None, + ps_attr_map=None, srv_formats=(), pk_u8_s0_contract=False): + # pk_u8_s0_contract: the caller guarantees that every v_cvt_pk_u8_f32 S0 register not proven in domain + # holds +0.0 or an integer in 1..255 (fixtures only; ordinary translation never selects it). + self.pk_u8_s0_contract = pk_u8_s0_contract self.root = parse_root(root_blob) + self.rw_keys = frozenset(rw_keys) # buffers the program stores to and reads: every access through the UAV + # PA_CL_VS_OUT_CNTL of the vertex stage (request .vsout), or None: says what a pos1 export carries. + self.vs_out_cntl = vs_out_cntl + # Lowerings whose manifest lines need draw-runtime support (DRAW_FEATURES); off unless named, so a + # --requests pass never publishes a result the runtime cannot bind yet. + self.features = draw_features() if features is None else frozenset(features) + self.heapvars = [] # heap descriptor k -> resource kind it is used as (None until used) + self.fma_rule = None # set by the first multiply-add lowered (manifest `fma exact|precise`) + self.draw_heapwords = False # x2w_hword read (X2W_DRAW_FEATURES heapwords, manifest `heapwords 1`) + self.spi_inputs(ps_hw_inputs) self.ps_attr_map = ps_attr_map # stream_interface(): pixel attribute -> (vertex parameter, component mask); None pairs by number self.vs_fetch = vs_fetch # stream_fetch(): the loads the vertex stage's entry call stands for - self.packed_position_vgpr = None + # (packed_position_vgpr is set by spi_inputs above.) # First VGPR of the PERSP_CENTER I/J entry pair (SPI_PS_INPUT_ADDR bit 1, after the PERSP_SAMPLE pair when that # one is enabled). Without hardware inputs the model assumes the center pair alone: v0, v1. self.persp_center_vgpr = 0 - if ps_hw_inputs is not None: - ena, addr = ps_hw_inputs - if ena != addr or not 0 <= ena <= 0xffff: - raise Unsupported('unverified pixel input enable/address combination') - self.persp_center_vgpr = (2 if addr & 1 else 0) if addr & 2 else None - if ena & (1 << 15): - # SPI PS inputs 0..6 supply IJ pairs (the pull model supplies three); - # line stipple through sample coverage each occupy one VGPR. - widths = (2, 2, 2, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1) - self.packed_position_vgpr = sum(w for bit, w in enumerate(widths) if addr & (1 << bit)) + # LOCAL: ps_hw_inputs is read by spi_inputs above; upstream's PERSP_CENTER / packed position decode of it + # (and its refusal of ENA != ADDR) is not taken, so its f16 interpolation keeps the v0, v1 default. self.rtv_formats = rtv_formats self.srv_formats = dict(srv_formats) if isinstance(srv_formats, dict) else dict(enumerate(srv_formats)) self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap @@ -6430,7 +8749,10 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.uds = [] # entry-constant sources self.notes = set() # shortcuts taken (written to the manifest as comments) self.lod_unvalidated = set() # image_sample forms read through a heap sampler (LOD fields unchecked, #2221) - self.modified, self.other_modified = set(), set() # other: unproved descriptor writes + self.modified = set() + self.tw_src, self.tw_nodes, self.tw_used, self.tw_text = [], [], set(), None # descword nodes (Stage.tw_scalar) + self.tw_loop_pending, self.tw_loop_reads = [], set() # loop-carried nodes (Stage.tw_loop_value) + self.helper_text = None # both stage bodies, read once by common() to pick the HELPERS to emit self.rect = self.ud(('rect',)) if refusals is None: self.vs = Stage(self, self.vertex_kind, vs_code) @@ -6440,12 +8762,16 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.vs = Stage(self, self.vertex_kind, vs_code, refusals=refusals, decoded=decoded.get('vs')) self.ps = Stage(self, 'ps', ps_code, refusals=refusals, decoded=decoded.get('ps')) if ps_code is not None else None if self.ps is None: - self.params, self.flat, self.f16_plain = [], [], [] + self.params, self.flat, self.half, self.f16_plain = [], [], [], [] + self.ps_entry_reads = {} if 'pos' not in self.vs.exports: raise Unsupported('vertex stage exports no position') return + self.spi_reads() self.params = sorted(int(k[5:]) for k in self.vs.exports if k.startswith('param')) self.flat = sorted(a for a, how in self.ps.attrs.items() if 'flat' in how) + self.half = sorted(a for a, how in self.ps.attrs.items() if 'half' in how) + self.check_half_reads() for a, how in self.ps.attrs.items(): if 'f16' not in how: continue @@ -6465,16 +8791,86 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( if 'pos' not in self.vs.exports: raise Unsupported('vertex stage exports no position') + def spi_inputs(self, ps_hw_inputs): + """Before the pixel stage is built: the SPI input layout from its SPI_PS_INPUT_ENA/ADDR, or none. + + Shared by the draw and mesh pipelines. With (ENA, ADDR), entry VGPRs map to SPI inputs. Only POS_FIXED_PT + is lowered: the integer pixel X in [15:0] and Y in [31:16] (Mesa nir_intrinsics.py pixel_coord, "16-bit + integer vec2 of the pixel X/Y in the framebuffer", which ac_nir_lower_intrinsics_to_args.c builds as + unpack_32_2x16 of the pos_fixed_pt argument). D3D SV_Position.xy is the pixel centre, so its integer part + is that pixel.""" + self.packed_position_vgpr = None + self.ps_input_layout = None + # The pixel stage's launch FLOAT_MODE (SPI_SHADER_PGM_RSRC1_PS bits 19:12), the third .psin field, or None + # when the request does not carry it (then f16 rounding before s_round_mode is refused; Stage.launch_mode). + # (None, None, mode) passes the mode without an SPI input layout. + self.ps_float_mode = ps_hw_inputs[2] if ps_hw_inputs is not None and len(ps_hw_inputs) > 2 else None + if ps_hw_inputs is not None and ps_hw_inputs[0] is None: + ps_hw_inputs = None + if ps_hw_inputs is not None: + ena, addr = ps_hw_inputs[:2] + self.ps_input_layout = layout = ps_input_layout(ena, addr) + self.ps_input_ena = ena + if ena >> POS_FIXED_PT & 1: + self.packed_position_vgpr = [v for v, bit in layout.items() if bit == POS_FIXED_PT][0] + + def spi_reads(self): + """After the pixel stage is built: check its entry-VGPR reads against the SPI input layout. + + A pixel stage starts with its SPI inputs in the VGPRs (barycentrics, position, face, ancillary data). The + interpolation instructions name them without reading them (they take the attribute); any other read before + a write sees 0 in the HLSL instead of the hardware input. Without the layout this is reported, not refused + (existing fixtures read entry VGPRs as zero): ps_entry_reads, VGPR -> offset of the first read; the + translate_to callers refuse a pipeline that has any. With the layout, a read of an input that is not + lowered is kept in ps_input_refusal and raised by hlsl_ps(), so a pipeline can still be built to ask for its + layout (packed_position_vgpr), but no pixel HLSL is ever written for it.""" + self.ps_entry_reads = dict(self.ps.entry_reads) + self.ps_input_refusal = None + self.ps_input_vgprs = {} # entry VGPR -> PS_INPUT_HLSL bit, initialized by Stage.declarations() + if self.ps_input_layout is None: + return + for reg, off in sorted(self.ps_entry_reads.items(), key=lambda item: item[1]): + bit = self.ps_input_layout.get(reg) + if bit is None: + self.ps_input_refusal = ('pixel stage reads entry VGPR v%d at %#x, past the SPI inputs (ADDR allocates %d)' + % (reg, off, len(self.ps_input_layout))) + elif not self.ps_input_ena >> bit & 1: + self.ps_input_refusal = ('pixel stage reads SPI input %s (v%d) at %#x, allocated but not enabled' + % (PS_INPUTS[bit][0], reg, off)) + elif bit in PS_POSITION_INPUTS and self.ps_input_ena & PS_SAMPLE_RATE: + self.ps_input_refusal = ('pixel stage reads SPI input %s (v%d) at %#x with per-sample barycentrics ' + 'enabled (%#x)' % (PS_INPUTS[bit][0], reg, off, self.ps_input_ena)) + elif bit in PS_INPUT_HLSL: + self.ps_input_vgprs[reg] = bit + elif bit != POS_FIXED_PT: + self.ps_input_refusal = ('pixel stage reads SPI input %s (v%d) at %#x: not lowered' + % (PS_INPUTS[bit][0], reg, off)) + if self.ps_input_refusal: + break + self.ps_entry_reads = {} # every entry read is a lowered input (or refused above) + + def check_half_reads(self): + """Refuse a binary16 read (v_interp_p2_f16) of an attribute the vertex/mesh stage exports with compr: its + loparam/hiparam copies are not written (Stage.export).""" + compr = sorted(set(self.half) & set(getattr(self.vs, 'compr_params', ()))) + if compr: + raise Unsupported('binary16 interpolation of attribute %s exported with compr' % compr) + def mrt_kind(self, slot): if slot >= len(self.rtv_formats): return 'float' fmt = self.rtv_formats[slot] + # R32_UINT / R32_SINT (42 / 43) are verified by a draw (tests/startup_mrt_check.py). The other formats with + # 32 bits per channel (R32G32B32A32 3 / 4, R32G32B32 7 / 8, R32G32 17 / 18) take the same uncompressed + # export words unconverted, only with more channels (D3D drops the components a format lacks, as the + # colour buffer does): ASSUMED equal, not drawn. Narrower integer targets convert in the colour buffer + # (clamp or wrap, not checked) and stay refused. if fmt in UINT_RTVS: - if fmt not in VERIFIED_UINT_RTVS: + if fmt not in (3, 7, 17, 42): raise Unsupported('unverified UINT RTV format %d' % fmt) return 'uint' if fmt in SINT_RTVS: - if fmt not in VERIFIED_SINT_RTVS: + if fmt not in (4, 8, 18, 43): raise Unsupported('unverified SINT RTV format %d' % fmt) return 'int' return 'bits' if fmt in FLOAT32_RTVS else 'float' @@ -6485,22 +8881,50 @@ def ud(self, source): return self.uds.index(source) def resource(self, key, kind): - if key in self.stored_images(): + if key[0][0] == 'heapdyn': + k = key[0][1] + if key[1] not in (0, None): + raise Unsupported('heap descriptor at word offset %s' % key[1]) + if self.heapvars[k] not in (None, kind): + raise Unsupported('heap descriptor used as %s and %s' % (self.heapvars[k], kind)) + if kind not in HEAP_KINDS: + raise Unsupported('heap %s' % kind) + self.heapvars[k] = kind + return '%s[NonUniformResourceIndex(x2w_hix(h%d, %du))]' % (HEAP_KINDS[kind][0], k, HEAP_KINDS[kind][1]) + if key in getattr(self, 'uavs', {}) or key in getattr(self, 'rw_keys', ()): + raise Unsupported('descriptor %s read as an SRV and stored to as a UAV' % (key,)) + if key in Pipeline.stored_images(self): raise Unsupported('resource %s is both read and stored to' % (key,)) r = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) if r['kind'] != kind: raise Unsupported('resource %s used as %s and %s' % (key, r['kind'], kind)) return 'r%d' % r['index'] + def uav(self, key): + """u<i> for a raw buffer UAV (manifest `uav <i> buf ...`); indices count from 0 apart from the SRVs.""" + if key in self.resources: + # translate_to builds the pipeline again with the key in rw_keys, so its vector loads go through the UAV + raise StoredSrv(key, 'descriptor %s read as an SRV and stored to as a UAV' % (key,)) + if getattr(self, 'image_uavs', None): + raise Unsupported('buffer UAV %s in a program with stored images (u registers are shared)' % (key,)) + uavs = self.__dict__.setdefault('uavs', {}) + if key not in uavs: + if len(uavs) == 8: + raise Unsupported('more than 8 UAVs') + uavs[key] = len(uavs) + return 'u%d' % uavs[key] + def stored_images(self): - return self.uavs or {} + return getattr(self, 'image_uavs', None) or {} - def uav(self, key, kind): + def image_uav(self, key, kind): if key in self.resources: raise Unsupported('resource %s is both read and stored to' % (key,)) - if self.uavs is None: - self.uavs = {} - r = self.uavs.setdefault(key, dict(index=len(self.uavs), kind=kind)) + if getattr(self, 'uavs', None): + raise Unsupported('stored image %s in a program with buffer UAVs (u registers are shared)' % (key,)) + if getattr(self, 'image_uavs', None) is None: + self.image_uavs = {} + r = self.image_uavs.setdefault(key, dict(index=len(self.image_uavs), kind=kind)) if r['kind'] != kind: raise Unsupported('stored image %s used as %s and %s' % (key, r['kind'], kind)) return ('u%d' if kind == 'raw' else 'w%d') % r['index'] @@ -6522,40 +8946,37 @@ def sampler_lines(self): ' '.join('0x%x' % w for w in key[prefixed:]))) return lines + def fma_guard(self): + """True when the fxc-compiled draw stages call x2w_fma_exact (see FMA_EXACT_FXC). Mesh pipelines compile with + dxc and keep the plain helper; compute and mesh stages have no draw main() here to set x2w_fz.""" + if hasattr(self, 'hlsl_ms') or isinstance(self, ComputePipeline) or getattr(self, 'vs', None) is None \ + or getattr(self, 'ps', None) is None: + return False + if getattr(self, 'helper_text', None) is None: + self.helper_text = '\n'.join(self.vs.body() + self.ps.body()) + return re.search(r'\bx2w_fma_exact\(', self.helper_text) is not None + + def fma_guard_init(self, word): + return [' x2w_fz = (%s * %s + %s) & 1u; // always 0, see FMA_EXACT_FXC' % (word, word, word)] \ + if self.fma_guard() else [] + def common(self): out = ['#define F(x) asfloat(x)', '#define U(x) asuint(x)', 'float mul_legacy(float a, float b) { return (a == 0.0 || b == 0.0) ? 0.0 : a * b; }', - # Match pixel_aot: round the product before adding and flush denormals to signed zero. - 'float ftz32(float value) {', - ' uint bits = asuint(value);', - # Select the mask as an integer so FXC preserves the sign of a flushed zero. - ' uint mask = (bits & 0x7fffffffu) < 0x00800000u ? 0x80000000u : 0xffffffffu;', - ' return asfloat(bits & mask);', - '}', - 'float mad32(float a, float b, float c, bool legacy) {', - ' a = ftz32(a);', - ' b = ftz32(b);', - ' precise float product = ftz32(legacy ? mul_legacy(a, b) : a * b);', - ' precise float sum = product + ftz32(c);', - ' return ftz32(sum);', - '}', + # (LOCAL: upstream's ftz32 / mad32 helpers are not emitted; the multiply-adds keep the local rule.) + 'float med3(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); }', # Match pixel_aot: x - floor(x) capped at 0x3f7fffff, so a tiny negative input cannot round up to # 1.0. The cap is a comparison, not min: min returns its other operand for a NaN. # The comparison is on the bits because FXC folds `frac(value) >= 1.0f` to false and emits a bare # frc for it, which loses the cap on an adapter whose frac returns 1.0. frac can only reach the cap # by rounding to exactly +1.0, so the equality covers the same case, and a NaN misses it and passes. + # (LOCAL: upstream 207256225 switched VEC_F v_fract_f32 to fract32 and added this helper; the local + # preamble kept the table change without the helper, so every v_fract_f32 stage failed dxc with + # "use of undeclared identifier 'fract32'".) 'float fract32(float value) {', ' float f = frac(value);', ' return asuint(f) == 0x3f800000u ? asfloat(0x3f7fffffu) : f;', '}', - # v_med3_f32 with a NaN source is the minimum of the three (ISA "343 V_MED3_F32"), so the test is - # on the encoding: a float isnan() may be folded away by the compiler. D3D min() returns the - # other operand, so min(min(a, b), c) over a NaN source is the smallest of the non-NaN ones. - # Same body as med3_32 in tools/pixel_aot.py. - 'float med3_32(float a, float b, float c) {', - ' uint top = max(max(asuint(a) & 0x7fffffffu, asuint(b) & 0x7fffffffu), asuint(c) & 0x7fffffffu);', - ' return top > 0x7f800000u ? min(min(a, b), c) : max(min(a, b), min(max(a, b), c));', - '}', # High half of an unsigned 32x32 product, by halfword products so it fits 32-bit HLSL. 'uint mul_hi_u32(uint a, uint b) { uint la = a & 0xffffu, lb = b & 0xffffu;' ' uint middle = (a >> 16) * lb + ((la * lb) >> 16);' @@ -6597,19 +9018,41 @@ def common(self): ' uint e = (x >> (s1 & 31u)) & (w >= 32u ? 0xffffffffu : ((1u << (w & 31u)) - 1u));' ' uint sh = (32u - w) & 31u; return sg != 0u ? asuint(asint(e << sh) >> sh) : e; }', 'uint ldu(ByteAddressBuffer b, uint a) { uint k = (a & 3) * 8, lo = b.Load(a & ~3u); if (k == 0) return lo; ' - 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }', - 'cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))] + 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }'] + if getattr(self, 'helper_text', None) is None: # upstream unit probes build a Pipeline without __init__ + # The draw stages, or the compute stage of upstream's ComputePipeline (slot 67). + stages = [getattr(self, k) for k in ('vs', 'ps', 'cs') if getattr(self, k, None) is not None] + self.helper_text = '\n'.join(line for s in stages for line in s.body()) + out += [FMA_EXACT_FXC if name == 'x2w_fma_exact' and self.fma_guard() else text + for name, text in HELPERS.items() if re.search(r'\b%s\(' % name, self.helper_text)] + out += ['cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))] for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'tex1d': 'Texture1D<float4>', 'tex2d': 'Texture2D<float4>', 'tex2da': 'Texture2DArray<float4>', 'tex3d': 'Texture3D<float4>'}[r['kind']], r['index'], r['index'])) - for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): - out.append('%s %s%d : register(u%d);' % ({'tex2d': 'RWTexture2D<float4>', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) + for key, i in getattr(self, 'uavs', {}).items(): + out.append('RWByteAddressBuffer u%d : register(u%d);' % (i, i)) + for key, r in sorted(Pipeline.stored_images(self).items(), key=lambda kv: kv[1]['index']): + out.append('%s w%d : register(u%d);' % ({'tex2d': 'RWTexture2D<float4>'}[r['kind']], r['index'], r['index'])) for key, i in self.samplers.items(): out.append('%s q%d : register(s%d);' % ('SamplerComparisonState' if key[0] == 'cmp' else 'SamplerState', i, i)) + if any(getattr(self, 'heapvars', ())) or getattr(self, 'draw_heapwords', False): # tests build bare pipelines without __init__ + out += ['ByteAddressBuffer heapmem : register(t0, space1);', 'ByteAddressBuffer vinfo : register(t1, space1);', + 'uint x2w_vid(uint h) { return heapmem.Load(h) == 0x%08xu ? heapmem.Load(h + 4) : 0xffffffffu; }' + % HEAP_TOKEN, + 'uint x2w_hix(uint h, uint k) { uint i = x2w_vid(h); return i < %du ? 8u + 8u * i + k : k; }' % HEAP_IDS, + 'uint x2w_vstride(uint h) { uint i = x2w_vid(h); return i < %du ? vinfo.Load(i * 16u) : 0u; }' % HEAP_IDS] + for kind in sorted(set(k for k in self.heapvars if k), key=lambda k: HEAP_KINDS[k][1]): + name, slot, hlsl_type = HEAP_KINDS[kind] + out.append('%s %s[%d] : register(t0, space%d);' % (hlsl_type, name, 8 + 8 * HEAP_IDS, 2 + slot)) + if getattr(self, 'draw_heapwords', False): + # vdesc: the gfx10 descriptor words per view id (RUNTIME_NEEDS.md 6.3.1; text as mesh2hlsl's x2w_hword) + out += ['ByteAddressBuffer x2w_vdesc : register(t2, space1);', + 'uint x2w_hword(uint h, uint i) { uint id = x2w_vid(h); return id < %du ? ' + 'x2w_vdesc.Load(id * 32u + 4u * i) : 0u; }' % HEAP_IDS] if self.uses_sampler_heap: out.append('SamplerState qh[%d] : register(s0, space%d);' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE)) out.append('uint x2w_sampler_entry(uint offset) { return (offset & 15u) != 0 || offset >= %du ? %du : offset >> 4; }' % (16 * SAMPLER_HEAP_FALLBACK, SAMPLER_HEAP_FALLBACK)) - if self.uses_pack16_rne: + if getattr(self, 'uses_pack16_rne', False): # IEEE binary32 to binary16 round-to-nearest-even (quieting NaN while preserving its sign, # matching RDNA 2 hardware on binary32 inputs), plus exact UNORM16 ratio-to-half conversion # (avoiding binary32 double-rounding at 0xffaf -> 0x3bfd and 0xffef -> 0x3bff). @@ -6770,27 +9213,49 @@ def interface(self, for_pixel): # Attributes read without interpolation get a second, flat copy of the vertex output. for p in self.flat: fields.append(' nointerpolation uint4 fparam%d : FPARAM%d;' % (p, p)) + # Attributes read as binary16 halves (v_interp_p2_f16) get the two halves as interpolated f32 copies. + for p in getattr(self, 'half', ()): + fields.append(' float4 loparam%d : LOPARAM%d;' % (p, p)) + fields.append(' float4 hiparam%d : HIPARAM%d;' % (p, p)) for p in self.f16_plain: fields.append(' float4 hparam%d_lo : HPARAML%d;' % (p, p)) fields.append(' float4 hparam%d_hi : HPARAMH%d;' % (p, p)) fields.append(' float4 pos : SV_Position;') + if for_pixel and FRONT_FACE in getattr(self, 'ps_input_vgprs', {}).values(): + fields.append(' bool ff : SV_IsFrontFace;') # system-generated: pixel input only + clip = self.vs.exports.get('clip') + if clip: + fields.append(' float%s clip0 : SV_ClipDistance0;' % ('' if clip == 1 else clip)) return fields def hlsl_vs(self): s = self.vs - out = self.common() + ['struct VSOut {'] + self.interface(False) + ['};', 'VSOut body(uint vid) {', ' VSOut o = (VSOut)0;'] + # Entry VGPRs of the title's vertex stage: v0 the vertex id, v3 the instance id (D3D SV_InstanceID: start + # instance not included). Measured on the archive's distinct vertex containers: v3 is read before any write + # in all 441 whose input signature declares SV_INSTANCEID and in none without it; v1 and v2 are read in none. + # v3 is passed only to a stage that reads it, so other stages keep their HLSL; v1 / v2 have no lowering. + unknown = sorted({1, 2} & set(s.entry_reads)) + if unknown: + raise Unsupported('vertex stage reads entry v%d (no lowering for that input)' % unknown[0]) + iid = 3 in s.entry_reads + arg = ', iid' if iid else '' + out = self.common() + ['struct VSOut {'] + self.interface(False) + ['};', + 'VSOut body(uint vid%s) {' % (', uint iid' if iid else ''), + ' VSOut o = (VSOut)0;'] s.used_v.add(0) - flat = re.compile(r'\s*o\.fparam(\d+) = ') - half = re.compile(r'\s*o\.hparam(\d+)_(?:lo|hi) = ') - body = [line for line in s.body() if not (flat.match(line) and int(flat.match(line).group(1)) not in self.flat) - and not (half.match(line) and int(half.match(line).group(1)) not in self.f16_plain)] + flat = re.compile(r'\s*o\.(f|lo|hi)param(\d+) = ') + + def unread(line): + m = flat.match(line) + return m and int(m.group(2)) not in (self.flat if m.group(1) == 'f' else getattr(self, 'half', ())) + body = [line for line in s.body() if not unread(line)] if s.fetched: # Behind a fetch call a register read as 0 by default would hide a missing input, so every read must be # of a register defined on all paths. Proven here only for the entry block (straight-line code from the # call to the first branch or branch target): v0, the fetched registers, and registers an unpredicated # write in that block assigned before the read. A write under an exec predicate or in any later block # does not define a register. - written = {0} + written = {0, 3} if iid else {0} for index, (start, lines, term) in enumerate(s.blocks): for line in lines + ([term[1]] if term and term[0] == 'branch' else []): target = re.match(r'v(\d+) = (.*)', line) @@ -6800,18 +9265,22 @@ def hlsl_vs(self): 'before the first branch defines' % min(unwritten)) if target and index == 0 and start == 0: written.add(int(target.group(1))) - out += s.declarations() + [' v0 = vid;'] + body + [' return o;', '}', + out += s.declarations() + [' v0 = vid;'] + ([' v3 = iid;'] if iid else []) + body + [' return o;', '}', '// Rectangle lists arrive as six vertices per rectangle: corners 0 1 2, 0 2 and the fourth corner 0 + 2 - 1.', - 'VSOut main(uint vid : SV_VertexID) {', - ' if (ud%d == 0) return body(vid);' % self.rect, + 'VSOut main(uint vid : SV_VertexID%s) {' % (', uint iid : SV_InstanceID' if iid else '')] + self.fma_guard_init('vid') + [ + ' if (ud%d == 0) return body(vid%s);' % (self.rect, arg), ' uint first = (vid / 6) * 3, corner = vid % 6;', - ' if (corner < 3) return body(first + corner);', - ' if (corner == 3) return body(first);', - ' if (corner == 4) return body(first + 2);', - ' VSOut p = body(first), q = body(first + 1), r = body(first + 2), o;'] + ' if (corner < 3) return body(first + corner%s);' % arg, + ' if (corner == 3) return body(first%s);' % arg, + ' if (corner == 4) return body(first + 2%s);' % arg, + ' VSOut p = body(first%s), q = body(first + 1%s), r = body(first + 2%s), o;' % (arg, arg, arg)] for p in range(max(self.params) + 1 if self.params else 0): out.append(' o.param%d = p.param%d + r.param%d - q.param%d;' % (p, p, p, p)) out += [' o.fparam%d = p.fparam%d;' % (p, p) for p in self.flat] + for p in getattr(self, 'half', ()): + out += [' o.%sparam%d = p.%sparam%d + r.%sparam%d - q.%sparam%d;' % ((h, p) * 4) for h in ('lo', 'hi')] + if self.vs.exports.get('clip'): + out.append(' o.clip0 = p.clip0 + r.clip0 - q.clip0;') # linear in the corner, like the params for p in self.f16_plain: out += [' o.hparam%d_%s = p.hparam%d_%s + r.hparam%d_%s - q.hparam%d_%s;' % (p, h, p, h, p, h, p, h) for h in ('lo', 'hi')] @@ -6823,26 +9292,29 @@ def ps_profile(self): return 'ps_6_0' if self.ps.needs_sm6 else 'ps_5_1' def hlsl_ps(self): + refusal = getattr(self, 'ps_input_refusal', None) # the tests' bare pipelines have none + if refusal: + raise Unsupported(refusal) s = self.ps targets = sorted(int(k[3:]) for k in s.exports if k.startswith('mrt')) - depth = 'depth' in s.exports out = self.common() + ['struct PSIn {'] + self.interface(True) + ['};'] - if not targets and not depth: - out += ['void main(PSIn i) {'] + s.declarations() + s.body() + ['}'] + depth = 'depth' in s.exports + if not targets and not depth: # depth-only: no output struct, so the pipeline declares no SV_Target + out += ['void main(PSIn i) {'] + self.fma_guard_init('asuint(i.pos.x)') + s.declarations() + s.body() + ['}'] return '\n'.join(out) + '\n' out.append('struct PSOut {') - if depth: - out.append(' float depth : SV_Depth;') for t in targets: kind = self.mrt_kind(t) out.append(' %s mrt%d : SV_Target%d;' % ({'int': 'int4', 'uint': 'uint4'}.get(kind, 'float4'), t, t)) - out += ['};', 'PSOut main(PSIn i) {', ' PSOut o = (PSOut)0;'] + if depth: + out.append(' float depth : SV_Depth;') + out += ['};', 'PSOut main(PSIn i) {', ' PSOut o = (PSOut)0;'] + self.fma_guard_init('asuint(i.pos.x)') out += s.declarations() + s.body() + [' return o;', '}'] return '\n'.join(out) + '\n' def manifest(self): # A manifest that names a writable view is version 2, so a runtime that reads only version 1 lines can tell. - lines = ['x2w-manifest %d' % (2 if self.stored_images() else 1), 'ud %d' % len(self.uds)] + lines = ['x2w-manifest %d' % (2 if Pipeline.stored_images(self) else 1), 'ud %d' % len(self.uds)] for i, source in enumerate(self.uds): lines.append('udsrc %d %s' % (i, ' '.join(str(x) for x in source))) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): @@ -6854,7 +9326,18 @@ def manifest(self): lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) if r.get('d16_exact'): lines.append('d16srv %d exact' % r['index']) - for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): + for (source, off), i in sorted(getattr(self, 'uavs', {}).items(), key=lambda kv: kv[1]): + if source[0] == 'table': + lines.append('uav %d buf table %d %d' % (i, source[1] if len(source) > 1 else 0, off or 0)) + elif source[0] == 'root' and not off: + lines.append('uav %d buf root %d 0' % (i, source[1] if len(source) > 1 else 0)) + else: + raise Unsupported('uav through %s at %s' % (source, off)) + if any(getattr(self, 'heapvars', ())) or getattr(self, 'draw_heapwords', False): + lines.append('heap 1') + if getattr(self, 'draw_heapwords', False): + lines.append('heapwords 1') + for key, r in sorted(Pipeline.stored_images(self).items(), key=lambda kv: kv[1]['index']): source, off = key if source[0] != 'table': raise Unsupported('stored image through %s' % (source,)) @@ -6862,6 +9345,16 @@ def manifest(self): lines += self.sampler_lines() if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) + if getattr(self, 'fma_rule', None) and self.fma_rule != 'legacy': + lines.append('fma %s' % self.fma_rule) + if getattr(self.ps, 'wave_union_used', False): + # X2W_PS_WAVE_UNION=1 lowered a wave64 reduction over the host wave's lanes (wave_union_plan) + lines.append('wavemembership host') + if getattr(self.ps, 'quad_divergent_used', None): + # X2W_PS_QUAD_DIVERGENT lowered a quad read or image_sample_b a lane may skip (Stage.translate) + lines.append('quaddivergent 1') + if FRONT_FACE in getattr(self, 'ps_input_vgprs', {}).values(): + lines.append('frontface 1') # reads SV_IsFrontFace: depends on the PSO winding (see PS_INPUT_HLSL) lines.append('params %d' % (max(self.params) + 1 if self.params else 0)) if self.ps is None: lines.append('ps none') @@ -6869,7 +9362,7 @@ def manifest(self): lines.append('targets %s' % ' '.join(k[3:] for k in sorted(self.ps.exports) if k.startswith('mrt'))) # 'wmask <target> <mask>': the export leaves the channels outside the mask unwritten, so the # runtime keeps them out of that target's RenderTargetWriteMask. Full masks are not written. - for name, mask in sorted(self.ps.write_masks.items(), key=lambda kv: int(kv[0][3:])): + for name, mask in sorted(getattr(self.ps, 'write_masks', {}).items(), key=lambda kv: int(kv[0][3:])): if mask != 0xF: lines.append('wmask %d 0x%x' % (int(name[3:]), mask)) return '\n'.join(lines) + '\n' @@ -6909,17 +9402,12 @@ def resource(self, key, kind): def uav(self, key, kind='raw'): if key in self.resources: raise Unsupported('descriptor %s used for a load and a store' % (key,)) - return super().uav(key, kind) - - def stored_images(self): - return {key: r for key, r in self.uavs.items() if r['kind'] != 'raw'} + return super().uav(key) if kind == 'raw' else self.image_uav(key, kind) def common(self): - out = [line for line in super().common() if self.uds or not line.startswith('cbuffer entry')] - for r in self.uavs.values(): - if r['kind'] == 'raw': - out.append('RWByteAddressBuffer u{0} : register(u{0});'.format(r['index'])) - return out + # LOCAL merge: the local Pipeline.common already declares every self.uavs entry (u<i>, register u<i>); + # declaring them again here was a redefinition (dxc: "redefinition of 'u0'"). + return [line for line in super().common() if self.uds or not line.startswith('cbuffer entry')] def hlsl_cs(self): s = self.cs @@ -6943,12 +9431,10 @@ def manifest(self): else: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) - for (source, off), r in self.uavs.items(): - where = 'table %d %d' % (source[1], off) - if r['kind'] == 'raw': - lines.append('uav %d %s' % (r['index'], where)) - else: - lines.append('uav %d tex2d float %s channels 4' % (r['index'], where)) + for (source, off), index in self.uavs.items(): + lines.append('uav %d table %d %d' % (index, source[1], off)) + for (source, off), r in self.stored_images().items(): + lines.append('uav %d tex2d float table %d %d channels 4' % (r['index'], source[1], off)) lines += self.sampler_lines() if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) @@ -6958,10 +9444,15 @@ def manifest(self): class MeshPipeline(Pipeline): """A slot 57 mesh pipeline with an optional pixel stage. The mesh stage is self.vs.""" vertex_kind = 'ms' + uses_mesh_skeleton = True def hlsl_ms(self): s = self.vs - lines = [re.sub(r' o\.fparam(\d+) = [^;]*;', lambda m: m[0] if int(m[1]) in self.flat else '', + outputs = {'f': self.flat, 'lo': self.half, 'hi': self.half} + def linked_output(match): + return match[0] if int(match[2]) in outputs[match[1]] else '' + + lines = [re.sub(r' o\.(f|lo|hi)param(\d+) = [^;]*;', linked_output, re.sub(r' o\.hparam(\d+)_(?:lo|hi) = [^;]*;', lambda m: m[0] if int(m[1]) in self.f16_plain else '', line)) for line in s.body()] @@ -6986,7 +9477,9 @@ def fnv(data, h=1469598103934665603): def pipeline_key(vs_code, ps_code, root_blob, layout=b''): """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-17')))) + # LOCAL (local merge): revision 3, as in d3d12_draw.inl pipeline_key, so the published cache keeps + # resolving (docs/experiments.md "Shader cache revision (local merge)"). compute_key uses 3cs, the graphics revision plus cs. + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-3')))) return fnv(layout, key) if layout else key @@ -6995,7 +9488,7 @@ def compute_key(cs_code, data, root_blob, desc, state_a=b'', state_b=b''): graphics revision followed by "cs", then each part preceded by its length as a little-endian u64: the code, the words 7-8 blob, the root signature, the 12 description words with their pointers zeroed and the two state blocks.""" - key = fnv(b'x2w-startup-shader-17cs') + key = fnv(b'x2w-startup-shader-3cs') for part in (cs_code, data, root_blob, desc, state_a, state_b): key = fnv(part, fnv(struct.pack('<Q', len(part)), key)) return key @@ -7176,15 +9669,45 @@ def has_complete_mesh57_bytecode(path): return False -def translate_to(out_dir, key, vs_code, ps_code, root_blob, check=True, rtv_formats=(), rtv_request='', vs_fetch=None, - ps_attr_map=None): +def translate_to(out_dir, key, vs_code, ps_code, root_blob, check=True, rtv_formats=(), rtv_request='', + ps_hw_inputs=None, vs_out_cntl=None, vs_fetch=None, ps_attr_map=None, ps_stream_inputs=None): """Writes <key>.vs.hlsl, <key>.ps.hlsl and <key>.txt (last), or <key>.fail with the reason. With check, the pair is compiled to .vs.cso and .ps.cso first and a missing fxc is a failure. check=False, or X2W_FXC set to the empty string, publishes the manifest without bytecode.""" name = os.path.join(out_dir, '%016x' % key) try: - pipe = Pipeline(vs_code, ps_code, root_blob, rtv_formats=rtv_formats, vs_fetch=vs_fetch, ps_attr_map=ps_attr_map) + rw_keys = set() + while True: + try: + pipe = Pipeline(vs_code, ps_code, root_blob, rtv_formats=rtv_formats, ps_hw_inputs=ps_hw_inputs, + vs_out_cntl=vs_out_cntl, rw_keys=rw_keys, + vs_fetch=vs_fetch, ps_attr_map=ps_attr_map) + break + except StoredSrv as conflict: + # read before the first store: build again with every access to that buffer through its UAV + if conflict.key in rw_keys or len(rw_keys) == 8: + raise + rw_keys.add(conflict.key) + if pipe.ps_entry_reads and ps_stream_inputs and (ps_hw_inputs is None or ps_hw_inputs[0] is None): + # A stream pixel stage reads an SPI input: build again with the layout of its header (stream_ps_inputs). + mode = ps_hw_inputs[2:] if ps_hw_inputs is not None else () + while True: + try: + pipe = Pipeline(vs_code, ps_code, root_blob, rtv_formats=rtv_formats, + ps_hw_inputs=tuple(ps_stream_inputs) + tuple(mode), vs_out_cntl=vs_out_cntl, + rw_keys=rw_keys, vs_fetch=vs_fetch, ps_attr_map=ps_attr_map) + break + except StoredSrv as conflict: + if conflict.key in rw_keys or len(rw_keys) == 8: + raise + rw_keys.add(conflict.key) + if pipe.ps_entry_reads: + # A request does not carry the SPI input layout, so the HLSL would read that input as 0 (for example + # the packed pixel position a dither or a full-screen copy addresses with). Not written as a result. + reg, off = min(pipe.ps_entry_reads.items(), key=lambda item: item[1]) + raise Unsupported('pixel stage reads entry VGPR v%d (an SPI input; layout not in the request) at %#x' + % (reg, off)) vs, ps, manifest = pipe.hlsl_vs(), pipe.hlsl_ps(), pipe.manifest() if rtv_request: manifest += rtv_request + '\n' @@ -7215,46 +9738,69 @@ def translate_to(out_dir, key, vs_code, ps_code, root_blob, check=True, rtv_form compiler, profiles = fxc, (('vs', 'vs_5_1'), ('ps', 'ps_5_1')) if fxc: import subprocess - # An existing manifest can already point at these paths. Publish only bytecode from a successful pair. - with tempfile.TemporaryDirectory(prefix='.fxc-', dir=out_dir) as staging: + # X2W_FXC_FLAGS: extra fxc options, for example /Od for a stage the default optimiser takes minutes on + # (the bytecode then runs unoptimised; the HLSL and so the result are the same). Default: none. + extra = os.environ.get('X2W_FXC_FLAGS', '').split() + if any(not re.fullmatch(r'/(Od|O[0-3]|Gfp)', flag) for flag in extra): + # (options that change results or layouts, /Gis /Gpp /Zpr /Zpc, are not taken) + raise SystemExit('X2W_FXC_FLAGS: only /Od, /O0-/O3 and /Gfp') + if not sm6: # LOCAL: fxc straight to the published paths, with X2W_FXC_FLAGS for stage, profile in profiles: - bytecode = os.path.join(staging, stage + '.cso') - if sm6: - command = [compiler, '-Gis', '-T', profile, '-E', 'main', '-Fo', bytecode, name + '.%s.hlsl' % stage] - else: - command = [compiler, '/nologo', '/T', profile, '/E', 'main', '/Fo', bytecode, name + '.%s.hlsl' % stage] - r = subprocess.run(command, capture_output=True, text=True) - if r.returncode or not has_bytecode(bytecode): - detail = r.stderr.strip() or ('?' if r.returncode else 'no bytecode produced') - open(name + '.fail', 'w').write('fxc %s: %s\n' % (stage, detail[-2000:])) - return 'fxc %s failed: %s' % (stage, detail.splitlines()[-1]) - with suppress(FileNotFoundError, UnicodeError): - with open(manifest_path) as existing: - write_manifest = existing.read() != manifest - # If the bindings changed, withdraw the old manifest before publishing new bytecode. - if write_manifest: + r = subprocess.run([fxc, '/nologo', '/T', profile, '/E', 'main'] + extra + + ['/Fo', name + '.%s.cso' % stage, name + '.%s.hlsl' % stage], + capture_output=True, text=True) + if r.returncode: + open(name + '.fail', 'w').write('fxc %s: %s\n' % (stage, r.stderr[-2000:])) + return 'fxc %s failed: %s' % (stage, r.stderr.strip().splitlines()[-1] if r.stderr.strip() else '?') + else: # upstream: a shader model 6.0 pair (dxc), staged and published together + # An existing manifest can already point at these paths. Publish only bytecode from a successful pair. + with tempfile.TemporaryDirectory(prefix='.fxc-', dir=out_dir) as staging: + for stage, profile in profiles: + bytecode = os.path.join(staging, stage + '.cso') + if sm6: + command = [compiler, '-Gis', '-T', profile, '-E', 'main', '-Fo', bytecode, name + '.%s.hlsl' % stage] + else: + command = [compiler, '/nologo', '/T', profile, '/E', 'main', '/Fo', bytecode, name + '.%s.hlsl' % stage] + r = subprocess.run(command, capture_output=True, text=True) + if r.returncode or not has_bytecode(bytecode): + detail = r.stderr.strip() or ('?' if r.returncode else 'no bytecode produced') + open(name + '.fail', 'w').write('fxc %s: %s\n' % (stage, detail[-2000:])) + return 'fxc %s failed: %s' % (stage, detail.splitlines()[-1]) + with suppress(FileNotFoundError, UnicodeError): + with open(manifest_path) as existing: + write_manifest = existing.read() != manifest + # If the bindings changed, withdraw the old manifest before publishing new bytecode. + if write_manifest: + with suppress(FileNotFoundError): + os.remove(manifest_path) + for stage in ('vs', 'ps'): + os.replace(os.path.join(staging, stage + '.cso'), name + '.%s.cso' % stage) + if not sm6: + temporary = '%s.txt.%d.tmp' % (name, os.getpid()) + with open(temporary, 'w') as result: + result.write(manifest) + os.replace(temporary, name + '.txt') + else: + if write_manifest: + temporary = '%s.%d.tmp' % (manifest_path, os.getpid()) + try: + with open(temporary, 'w') as result: + result.write(manifest) + os.replace(temporary, manifest_path) + finally: with suppress(FileNotFoundError): - os.remove(manifest_path) - for stage in ('vs', 'ps'): - os.replace(os.path.join(staging, stage + '.cso'), name + '.%s.cso' % stage) - if write_manifest: - temporary = '%s.%d.tmp' % (manifest_path, os.getpid()) - try: - with open(temporary, 'w') as result: - result.write(manifest) - os.replace(temporary, manifest_path) - finally: + os.remove(temporary) + if fxc: with suppress(FileNotFoundError): - os.remove(temporary) - if fxc: - with suppress(FileNotFoundError): - os.remove(name + '.fail') + os.remove(name + '.fail') return 'ok' def classify_decoded(ins): text = ' '.join(x[3] for x in ins if x[2] == 'exp') - return 'vs' if 'pos' in text else 'ps' if 'mrt' in text or not text else 'other' # no export: a depth-only pixel shader + # No export: a depth-only pixel shader. Only a pixel stage exports to the null target (a stage that ends with + # "exp null ... done vm" and writes no colour, e.g. for its discards or depth). (LOCAL rule; upstream's split.) + return 'vs' if 'pos' in text else 'ps' if 'mrt' in text or 'null' in text or not text else 'other' def classify(blob): @@ -7294,7 +9840,7 @@ def classify_stage(blob): layout = open(name + '.ia', 'rb').read() if os.path.isfile(name + '.ia') else b'' if request and pipeline_key(a, b, root, layout) != base: raise Unsupported('RTV variant source key mismatch') - fetch = attr_map = None + fetch = attr_map = vs_out_cntl = None if a.startswith(b'DXBC') or b.startswith(b'DXBC'): # Slot 86 records complete containers in canonical (VS, PS) order. # Keep the container bytes in the cache key; translate only the bounded native code. @@ -7303,11 +9849,15 @@ def classify_stage(blob): from resource_inventory import parts try: container, ps_container = a, b - a, b = (container_code(parts(blob)[b'DXIL'], stage=stage) - for blob, stage in ((a, 1), (b, 0))) + a, b = (stream_stage_code(blob, stage) for blob, stage in ((a, 1), (b, 0))) attr_map = stream_interface(container, ps_container) if starts_with_fetch_call(a): fetch = stream_fetch(container, layout.decode('ascii') if layout else None) + # As translate_request for a stream: a .vsout wins, else the PA_CL_VS_OUT_CNTL the output signature + # implies. (Raw requests keep no value here, as before: the .vsregs lookup scans the cache folder.) + vs_out_cntl = read_vs_out(name + '.vsout') + if vs_out_cntl is None: + vs_out_cntl = stream_vs_out_cntl(container) except (KeyError, ValueError, IndexError, struct.error, zlib.error) as error: raise Unsupported('invalid stream shader: %s' % error) from error if classify_stage(a) != 'vs' or classify_stage(b) != 'ps': @@ -7315,11 +9865,11 @@ def classify_stage(blob): kinds = {'vs': a, 'ps': b} else: kinds = {classify_stage(a): a, classify_stage(b): b} - return kinds, root, formats, request, fetch, decoded, attr_map + return kinds, root, formats, request, fetch, decoded, attr_map, vs_out_cntl def mesh57_key(ms, ps, root): - value = fnv(b'x2w-startup-mesh-57-2') + value = fnv(b'x2w-startup-mesh-57-1') for part in (ms, ps, root): value = fnv(part, fnv(struct.pack('<Q', len(part)), value)) return value @@ -7393,16 +9943,249 @@ def translate_request(out_dir, key): except (Unsupported, OSError, UnicodeError, struct.error) as reason: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason + name = os.path.join(out_dir, 'req_%016x' % key) + request = '' + formats = () try: - kinds, root, formats, request, fetch, _, attr_map = load_request(out_dir, key) + base = key + if os.path.isfile(name + '.rtv'): + with open(name + '.rtv', encoding='ascii') as file: + request = file.read(256) + if not re.fullmatch(r'rtv1 [0-9]{1,20}(?: [0-9]{1,10}){1,8}', request) or fnv(request.encode('ascii')) != key: + raise Unsupported('invalid RTV variant request') + base, *formats = map(int, request.split()[1:]) + if base > 0xffffffffffffffff or any(fmt > 0xffffffff for fmt in formats): + raise Unsupported('invalid RTV variant values') + name = os.path.join(out_dir, 'req_%016x' % base) + a, b, root = (open(name + ext, 'rb').read() for ext in ('.a', '.b', '.root')) + # Upstream: a stream pipeline's input layout (.ia) is part of its key (pipeline_key, draw.inl). + layout = open(name + '.ia', 'rb').read() if os.path.isfile(name + '.ia') else b'' + if request and pipeline_key(a, b, root, layout) != base: + raise Unsupported('RTV variant source key mismatch') + fetch = attr_map = stream_inputs = None + ps_hw_inputs = read_ps_inputs(name + '.psin') + vs_out_cntl = read_vs_out(name + '.vsout') + dumped = dumped_state(name) if ps_hw_inputs is None or vs_out_cntl is None else (None, None) + if ps_hw_inputs is None and dumped[0] is not None: + ps_hw_inputs = (dumped[0], dumped[0]) # ADDR assumed equal to ENA (no ADDR field located) + if ps_hw_inputs is None or len(ps_hw_inputs) == 2: + mode = dumped_float_mode(name) # the launch FLOAT_MODE, when the .psin does not carry it + if mode is not None: + ps_hw_inputs = tuple(ps_hw_inputs or (None, None)) + (mode,) + if vs_out_cntl is None: + vs_out_cntl = dumped[1] + if a.startswith(b'DXBC') or b.startswith(b'DXBC'): + # Slot 86 records complete containers in canonical (VS, PS) order. + # Keep the container bytes in the cache key; translate only the bounded native code. + import zlib + from pixel_aot import container_code + from resource_inventory import parts + try: + container, ps_container = a, b + a, b = (stream_stage_code(blob, stage) for blob, stage in ((a, 1), (b, 0))) + # Upstream: the stream's attribute pairing and the loads its vertex fetch call stands for. + attr_map = stream_interface(container, ps_container) + if starts_with_fetch_call(a): + fetch = stream_fetch(container, layout.decode('ascii') if layout else None) + if vs_out_cntl is None: # a dumped register (.vsout, .vsregs) wins + vs_out_cntl = stream_vs_out_cntl(container) + try: + stream_inputs = stream_ps_inputs(ps_container) + except (KeyError, ValueError, IndexError, struct.error, zlib.error): + stream_inputs = None # only a fallback: never a new refusal for a pair that translates + except (KeyError, ValueError, IndexError, struct.error, zlib.error) as error: + raise Unsupported('invalid stream shader: %s' % error) from error + if classify(a) != 'vs' or classify(b) != 'ps': + raise Unsupported('stream stage and shader export disagree') + kinds = {'vs': a, 'ps': b} + else: + kinds = {classify(a): a, classify(b): b} except (Unsupported, OSError, UnicodeError) as reason: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason if set(kinds) != {'vs', 'ps'}: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write('stages %s\n' % sorted(kinds)) return 'stages %s' % sorted(kinds) - return translate_to(out_dir, key, kinds['vs'], kinds['ps'], root, rtv_formats=formats, rtv_request=request, vs_fetch=fetch, - ps_attr_map=attr_map) + return translate_to(out_dir, key, kinds['vs'], kinds['ps'], root, rtv_formats=formats, rtv_request=request, + ps_hw_inputs=ps_hw_inputs, vs_out_cntl=vs_out_cntl, vs_fetch=fetch, ps_attr_map=attr_map, + ps_stream_inputs=stream_inputs) + + +VSREGS_PS_INPUT_ENA = 0x58 +VSREGS_VS_OUT_CNTL = 0x98 + + +def dumped_state(name): + """(ENA or None, PA_CL_VS_OUT_CNTL or None) from <name>.vsregs, else from the per-state dumps + <name>.<8 hex>.vsregs when they all agree. (None, None) when nothing is dumped.""" + paths = [name + '.vsregs'] if os.path.isfile(name + '.vsregs') else [] + if not paths: + folder, base = os.path.split(name) + try: + paths = [os.path.join(folder, n) for n in os.listdir(folder or '.') + if re.fullmatch(re.escape(os.path.basename(base)) + r'\.[0-9a-f]{8}\.vsregs', n)] + except OSError: + paths = [] + enas, cntls = set(), set() + for path in paths: + with open(path, 'rb') as file: + blob = file.read(0x400) + enas.add(struct.unpack_from('<H', blob, VSREGS_PS_INPUT_ENA)[0] if len(blob) >= VSREGS_PS_INPUT_ENA + 2 else None) + cntls.add(struct.unpack_from('<I', blob, VSREGS_VS_OUT_CNTL)[0] if len(blob) >= VSREGS_VS_OUT_CNTL + 4 else None) + return (enas.pop() if len(enas) == 1 else None), (cntls.pop() if len(cntls) == 1 else None) + + +# The pixel stage's SPI_SHADER_PGM_RSRC1 at block A + 0x04c (the second RSRC1/RSRC2 pair; the first, +0x038, is the +# vertex stage's). FLOAT_MODE = bits 19:12. Measured on the dumps, not documented: in the mesh layout FLOAT_MODE is 0 +# exactly for the 88 sets without a pixel stage; in the draw layout (+0x004 == 4, 3124 requests) +0x038 is 0xc0 in +# all of them, and +0x04c is 0xcc in 1015 pixel stages, every one with f16 rounding and none with s_round_mode, and +# 0xc0 in the rest, among them all 424 that execute s_round_mode themselves (the mesh sets show the same split). +VSREGS_PS_RSRC1 = 0x4c + + +def dumped_float_mode(name): + """The pixel stage's launch FLOAT_MODE from <name>.vsregs (or the agreeing per-state dumps), else None.""" + paths = [name + '.vsregs'] if os.path.isfile(name + '.vsregs') else [] + if not paths: + folder, base = os.path.split(name) + try: + paths = [os.path.join(folder, n) for n in os.listdir(folder or '.') + if re.fullmatch(re.escape(os.path.basename(base)) + r'\.[0-9a-f]{8}\.vsregs', n)] + except OSError: + paths = [] + modes = set() + for path in paths: + with open(path, 'rb') as file: + blob = file.read(0x400) + modes.add(struct.unpack_from('<I', blob, VSREGS_PS_RSRC1)[0] >> 12 & 0xff if len(blob) >= VSREGS_PS_RSRC1 + 4 + else None) + return modes.pop() if len(modes) == 1 else None + + +def read_vs_out(path): + """PA_CL_VS_OUT_CNTL from a request's optional .vsout file, 'pa_cl_vs_out_cntl 1 <hex8>', or None.""" + if not os.path.isfile(path): + return None + with open(path, encoding='ascii') as file: + text = file.read(64) + m = re.fullmatch(r'pa_cl_vs_out_cntl 1 ([0-9a-f]{8})\n', text) + if not m: + raise Unsupported('invalid vertex output control file') + return int(m.group(1), 16) + + +# PA_CL_VS_OUT_CNTL fields (Mesa src/amd/registers/gfx10.json): CLIP_DIST_ENA_0..7 [7:0], CULL_DIST_ENA_0..7 [15:8], +# USE_VTX_POINT_SIZE 16, _EDGE_FLAG 17, _RENDER_TARGET_INDX 18, _VIEWPORT_INDX 19, _KILL_FLAG 20, +# VS_OUT_MISC_VEC_ENA 21, VS_OUT_CCDIST0_VEC_ENA 22, VS_OUT_CCDIST1_VEC_ENA 23, VS_OUT_MISC_SIDE_BUS_ENA 24, +# USE_VTX_GS_CUT_FLAG 25, USE_VTX_SHD_OBJPRIM_ID 26, USE_VTX_LINE_WIDTH 27. +VS_OUT_CCDIST0 = 1 << 22 +VS_OUT_SIDE_BUS = 1 << 24 + + +def stream_vs_out_cntl(vs_container): + """PA_CL_VS_OUT_CNTL for a stream vertex stage without a dumped value, from its output signature, or None. + + A slot-86 request carries the container but not the register. When the signature's system values are exactly + SV_Position and one SV_ClipDistance0 whose components are x.. contiguously, the stage exports no misc vector + (point size, layer, viewport index and cull distances are all signature system values), so its pos1 export is + the first clip/cull distance vector holding exactly those clip distances: CCDIST0 on, CLIP_DIST_ENA = the mask, + no cull. clip_vector_width then requires the export to write exactly those channels. Every other form gives + None, so a pos1 export stays refused.""" + from resource_inventory import parts + sections = parts(vs_container) + if b'OSG1' not in sections: + return None + system = [entry for entry in signature_entries(sections[b'OSG1']) if entry[3]] + clip = [entry for entry in system if entry[3] == D3D_NAME_CLIP_DISTANCE] + position = [entry for entry in system if entry[3] == D3D_NAME_POSITION] + if (len(clip) != 1 or len(position) != 1 or len(system) != 2 or clip[0][2] != 0 or position[0][2] != 0 + or clip[0][4] not in (0x1, 0x3, 0x7, 0xf)): + return None + return VS_OUT_CCDIST0 | clip[0][4] + + +# The stream pixel header (IFACE_PS_HEADER_BASE) holds the pixel stage's SPI_PS_INPUT_ENA as a u32 at +0x248. +# ENA bits 8..11 indicate position components. FRONT_FACE selects SV_IsFrontFace. +STREAM_PS_INPUT_ENA = 0x248 +D3D_NAME_IS_FRONT_FACE = 9 + + +def stream_ps_inputs(ps_container): + """(ENA, ADDR) for a stream pixel stage without a dumped layout, from its FSSM header, or None. + + Used only for a pixel stage that reads an SPI input VGPR (translate_to retries with it; every other stage keeps + its translation). ADDR is taken equal to ENA, the rule the dumped ENA uses (dumped_state, meshrt .psin). The + word must be a 16-bit ENA whose position bits cover the SV_Position read mask and lie inside its declared mask, + and whose FRONT_FACE bit needs a declared SV_IsFrontFace; otherwise None and the read stays refused.""" + from pixel_aot import container_image + from resource_inventory import parts + sections = parts(ps_container) + image = container_image(sections[b'DXIL'], stage=0) + if struct.unpack_from('<Q', image, 192)[0] != IFACE_PS_HEADER_BASE or b'ISG1' not in sections: + return None + ena = struct.unpack_from('<I', image, STREAM_PS_INPUT_ENA)[0] + if not 0 < ena < 0x10000: + return None + part = sections[b'ISG1'] + count, first = struct.unpack_from('<II', part, 0) + declared = read = 0 + front_face = False + for i in range(count): + _, _, _, system, _, _, mask, used = struct.unpack_from('<6IBB', part, first + 32 * i) + if system == D3D_NAME_POSITION: + declared, read = declared | mask, read | used + front_face |= system == D3D_NAME_IS_FRONT_FACE + position = ena >> 8 & 0xf + if read & ~position or position & ~declared or (ena >> 12 & 1 and not front_face): + return None + return ena, ena + + +def clip_vector_width(cntl, vals): + """Channels of a pos1 export that are clip distances 0..n-1; refuses every other PA_CL_VS_OUT_CNTL use. + + Accepted only when pos1 is the first clip/cull distance vector (no misc vector, CCDIST0 on, CCDIST1 off, + no per-vertex misc values), the enabled clip distances are 0..n-1 contiguously and the export writes each of + those channels, and the cull enables are either none or the same channels. A channel above n is not a clip + distance (its CLIP_DIST_ENA bit is clear, so the clipper does not read it): the title's stream vertex stages + write all four channels with one or two distances enabled, and such a channel is not lowered. A distance that + is both clip and cull distance is lowered as SV_ClipDistance alone: the cull removes a primitive only when + every vertex is below 0, which the clip at 0 removes already. VS_OUT_MISC_SIDE_BUS_ENA (a transport choice) is + allowed. + """ + clip, cull = cntl & 0xff, cntl >> 8 & 0xff + n = clip.bit_length() + if (cntl & ~(0xffff | VS_OUT_CCDIST0 | VS_OUT_SIDE_BUS) or not cntl & VS_OUT_CCDIST0 or not n or n > 4 + or clip != (1 << n) - 1 or cull not in (0, clip) or len(vals) != 4 or 'off' in vals[:n]): + raise Unsupported('pos1 export with PA_CL_VS_OUT_CNTL %#010x (channels %s)' + % (cntl, [i for i, v in enumerate(vals) if v != 'off'])) + return n + + +def read_ps_inputs(path): + """(ENA, ADDR[, FLOAT_MODE]) from a request's optional .psin file, + 'spi_ps_input 1 <ENA hex8> <ADDR hex8>[ <FLOAT_MODE hex8>]', or None. FLOAT_MODE is the pixel stage's launch + MODE[7:0] (SPI_SHADER_PGM_RSRC1_PS bits 19:12; for a mesh pipeline u32 at state block A + 0x04c, bits 19:12); + without it MODE 0 rounding is assumed (Stage.launch_mode). + + The runtime writes it beside the request (it is not part of the key); without one the pixel stage's SPI + input layout is unknown and a read of an input VGPR is refused. + """ + if not os.path.isfile(path): + return None + with open(path, encoding='ascii') as file: + text = file.read(256) + m = re.fullmatch(r'spi_ps_input 1 ([0-9a-f]{8}) ([0-9a-f]{8})( [0-9a-f]{8})?\n(?:vs_input 1 [0-3] [0-9a-f]{8}\n)?', + text) + if not m: + raise Unsupported('invalid SPI input file') + if m.group(3) is None: + return int(m.group(1), 16), int(m.group(2), 16) + # optional third field: the pixel stage's launch FLOAT_MODE (SPI_SHADER_PGM_RSRC1_PS bits 19:12), 8 hex digits + mode = int(m.group(3), 16) + if mode > 0xff: + raise Unsupported('invalid SPI input file') + return int(m.group(1), 16), int(m.group(2), 16), mode REFUSALS_CAVEAT = ('Counts after the first refusal are approximate. Skipped instructions leave later state ' @@ -7453,7 +10236,7 @@ def request_refusals(out_dir, key, pair_info=None): """Collect reached refusal sites for one request without publishing a translation.""" refusals = [] try: - kinds, root, formats, _, fetch, decoded, attr_map = load_request(out_dir, key, refusals, pair_info) + kinds, root, formats, _, fetch, decoded, attr_map, vs_out_cntl = load_request(out_dir, key, refusals, pair_info) except Unsupported as reason: refusals.append((str(reason), 'pipeline')) return refusals @@ -7473,7 +10256,7 @@ def request_refusals(out_dir, key, pair_info=None): if set(kinds) != {'vs', 'ps'}: raise Unsupported('stages %s' % sorted(kinds)) pipe = Pipeline(kinds['vs'], kinds['ps'], root, rtv_formats=formats, vs_fetch=fetch, - refusals=refusals, decoded=decoded, ps_attr_map=attr_map) + refusals=refusals, decoded=decoded, ps_attr_map=attr_map, vs_out_cntl=vs_out_cntl) op = 'hlsl_vs' pipe.hlsl_vs() op = 'hlsl_ps' @@ -7582,6 +10365,24 @@ def refusals_main(argv): def main(): if any(arg == '--refusals' or arg.startswith('--refusals=') for arg in sys.argv[1:]): return refusals_main(sys.argv[1:]) + if sys.argv[1:2] == ['--warm-trace']: + # --warm-trace CACHE TRACE NATIVE_SCANNER [--list] + import subprocess + if len(sys.argv) not in (5, 6) or (len(sys.argv) == 6 and sys.argv[5] != '--list'): + raise SystemExit('usage: --warm-trace CACHE TRACE NATIVE_SCANNER [--list]') + cache, trace, scanner = sys.argv[2:5] + if not os.path.isdir(cache): + raise SystemExit('missing shader request directory: ' + cache) + rows = subprocess.check_output([scanner, trace], text=True).splitlines() + wanted = [int(row.split()[0], 16) for row in rows] + keys = pending_keys(cache, False, wanted) + print('%d distinct missed keys, %d pending translator requests' % (len(wanted), len(keys))) + if '--list' in sys.argv[5:]: + for key in keys: + print('%016x' % key) + else: + translate_keys(cache, keys) + return out_dir = sys.argv[2] os.makedirs(out_dir, exist_ok=True) if sys.argv[1] == '--capture': @@ -7698,7 +10499,10 @@ def translate_pending(out_dir, skip_failed=False, jobs=None): Requests are independent (each writes only its own <key>.* files), so several run in parallel processes; X2W_TRANSLATE_JOBS (default: the processor count, at most 61 on Windows) sets how many. """ - keys = pending_keys(out_dir, skip_failed) + translate_keys(out_dir, pending_keys(out_dir, skip_failed), jobs) + + +def translate_keys(out_dir, keys, jobs=None): jobs = min(jobs or translation_jobs(), len(keys)) if jobs < 2: for key in keys: @@ -7711,10 +10515,21 @@ def translate_pending(out_dir, skip_failed=False, jobs=None): print('%016x: %s' % (key, result), flush=True) -def pending_keys(out_dir, skip_failed): +def pending_keys(out_dir, skip_failed, wanted=None): keys = [] manifest_only = os.environ.get('X2W_FXC') == '' - for name in sorted(os.listdir(out_dir)): + if wanted is None: + names = sorted(os.listdir(out_dir)) + else: + # Match translate_request dispatch precedence if multiple markers exist. + names = [] + for key in dict.fromkeys(wanted): + for ext in ('c67', 'm57', 'rtv', 'a'): + name = 'req_%016x.%s' % (key, ext) + if os.path.isfile(os.path.join(out_dir, name)): + names.append(name) + break + for name in names: m = re.fullmatch(r'req_([0-9a-f]{16})\.(a|rtv|c67|m57)', name) if not m: continue diff --git a/tools/startup/gpu_slab_pool.py b/tools/startup/gpu_slab_pool.py new file mode 100644 index 0000000000..6fcf2db1ef --- /dev/null +++ b/tools/startup/gpu_slab_pool.py @@ -0,0 +1,140 @@ +"""gpu_slab_pool.py: holds a fixed set of named pagefile sections that the memory stand-in (xmem) uses for slabs it +moves to the pagefile for the GPU. LOCAL ONLY. + +A pagefile-backed section that has been opened as a D3D12 heap +(ID3D12Device3::OpenExistingHeapFromFileMapping) keeps its whole commit charge after the process that opened it is +gone, until the next reboot, however that process ended. When the sections come from this long-lived holder +instead, the same section objects are used run after run, so the charge stays fixed at the pool size instead of +growing by every moved slab of every run. + + python -B gpu_slab_pool.py ensure [--count N] [--mib M] start the holder unless it is running (detached) + python -B gpu_slab_pool.py status + python -B gpu_slab_pool.py quit end the holder (its sections stay charged if leaked) + python -B gpu_slab_pool.py hold --count N --mib M (the holder itself) + +Names: Local\\x2w-gpu-slab-<i> (i = 0..N-1), events Local\\x2w-gpu-slab-pool-ready / -quit. Each section is +SEC_COMMIT, M MiB (xmem's slab size is 256 MiB). xmem opens them in order (X2W_XMEM_GPU_POOL, default on: only slabs +moved for the GPU; =all: every slab from the start, X2W_XMEM_GPU_POOL_SLABS sections, default 32); a run that needs +more falls back to fresh sections (logged). xmem claims the pool with the named event Local\\x2w-gpu-slab-pool-owner, +so a second process never shares it. ensure with a larger count than the running holder has starts a second holder that +holds the existing sections too and creates the missing ones (quit ends both). +""" +import ctypes +import os +import subprocess +import sys +import time +from ctypes import wintypes as wt + +PREFIX = "Local\\x2w-gpu-slab-" +READY = "Local\\x2w-gpu-slab-pool-ready" +QUIT = "Local\\x2w-gpu-slab-pool-quit" +k32 = ctypes.WinDLL("kernel32", use_last_error=True) +k32.CreateFileMappingW.restype = wt.HANDLE +k32.CreateFileMappingW.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.DWORD, wt.LPCWSTR] +k32.OpenEventW.restype = wt.HANDLE +k32.OpenEventW.argtypes = [wt.DWORD, wt.BOOL, wt.LPCWSTR] +k32.CreateEventW.restype = wt.HANDLE +k32.CreateEventW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.BOOL, wt.LPCWSTR] +k32.OpenFileMappingW.restype = wt.HANDLE +k32.OpenFileMappingW.argtypes = [wt.DWORD, wt.BOOL, wt.LPCWSTR] +PAGE_READWRITE, SEC_COMMIT, SYNCHRONIZE, EVENT_MODIFY_STATE, FILE_MAP_READ = 0x04, 0x8000000, 0x100000, 0x2, 0x4 + + +def opt(name, default): + return int(sys.argv[sys.argv.index(name) + 1]) if name in sys.argv else default + + +def running(): + h = k32.OpenEventW(SYNCHRONIZE, False, READY) + if not h: + return False + k32.CloseHandle(h) + return True + + +def hold(count, mib): + quit_event = k32.CreateEventW(None, True, False, QUIT) + handles = [] + size = mib << 20 + for i in range(count): + h = k32.CreateFileMappingW(wt.HANDLE(-1), None, PAGE_READWRITE | SEC_COMMIT, size >> 32, size & 0xFFFFFFFF, PREFIX + str(i)) + if not h: + print(f"section {i} failed: {ctypes.get_last_error()}", flush=True) + break + handles.append(h) # an existing section (a second holder growing the pool) is just held once more + ready = k32.CreateEventW(None, True, True, READY) + print(f"holding {len(handles)} x {mib} MiB sections ({PREFIX}0..{len(handles) - 1})", flush=True) + k32.WaitForSingleObject(wt.HANDLE(quit_event), 0xFFFFFFFF) + for h in handles: + k32.CloseHandle(wt.HANDLE(h)) + k32.CloseHandle(wt.HANDLE(ready)) + return 0 + + +def reachable(): + """How many pool sections can be opened by name now.""" + n = 0 + while True: + h = k32.OpenFileMappingW(FILE_MAP_READ, False, PREFIX + str(n)) + if not h: + return n + k32.CloseHandle(wt.HANDLE(h)) + n += 1 + + +def ensure(count, mib=256): + """Starts the holder unless it runs with at least count sections; returns the number of pool sections reachable + (0 if it failed). A holder with fewer sections is not ended (its used sections stay charged anyway): a second + holder is started that opens the existing sections and creates the missing ones; quit ends both.""" + have = reachable() if running() else 0 + if have >= count: + return have + # Detached, outside any job of the caller, no console: it must outlive the run that started it. + flags = 0x00000008 | 0x00000200 | 0x01000000 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB + out_dir = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "out")) + os.makedirs(out_dir, exist_ok=True) + args = [sys.executable, "-B", os.path.abspath(__file__), "hold", "--count", str(count), "--mib", str(mib)] + # Neutral working directory: the holder must not keep the caller's (e.g. the title's data drive) in use. + cwd = os.environ.get("SystemRoot", out_dir) + with open(os.path.join(out_dir, "gpu_slab_pool.log"), "a") as log: + try: + subprocess.Popen(args, creationflags=flags, stdout=log, stderr=log, stdin=subprocess.DEVNULL, close_fds=True, + cwd=cwd) + except OSError: # the caller's job may refuse breakaway: start without it + print("gpu_slab_pool: the holder could not leave the caller's job and ends with it; the pool then " + "only helps within that job's lifetime", flush=True) + subprocess.Popen(args, creationflags=flags & ~0x01000000, stdout=log, stderr=log, stdin=subprocess.DEVNULL, + close_fds=True, cwd=cwd) + for _ in range(100): + if running() and reachable() >= count: + return reachable() + time.sleep(0.1) + return reachable() if running() else 0 + + +def main(): + what = sys.argv[1] if len(sys.argv) > 1 else "status" + count, mib = opt("--count", 12), opt("--mib", 256) + if what == "hold": + return hold(count, mib) + if what == "status": + print(f"holder {'running' if running() else 'not running'}; {reachable()} pool section(s) reachable") + return 0 + if what == "quit": + h = k32.OpenEventW(EVENT_MODIFY_STATE, False, QUIT) + if h: + k32.SetEvent(wt.HANDLE(h)) + k32.CloseHandle(wt.HANDLE(h)) + print("quit signalled" if h else "holder not running") + return 0 + if what == "ensure": + n = ensure(count, mib) + print(f"{n} pool section(s) reachable" if n else "holder did not report ready within 10 s") + return 0 if n else 1 + print(__doc__) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/startup/mesh2hlsl.py b/tools/startup/mesh2hlsl.py new file mode 100644 index 0000000000..d88054849d --- /dev/null +++ b/tools/startup/mesh2hlsl.py @@ -0,0 +1,4018 @@ +"""gfx1013 NGG mesh-stage machine code -> HLSL mesh shader (SM 6.5) for a mesh + pixel pipeline (startup tools). + +The console compiles a mesh shader to an NGG primitive shader (wave64, 128 threads, one thread per output vertex and +one per output primitive). This module translates that program with the pipeline translator's one-lane model +(gfx2hlsl.Stage: registers are uint variables, exec/vcc/masks hold the lane's bit) and wraps it in an HLSL mesh +shader: + + * one HLSL thread per console lane: SV_GroupIndex = the console's thread index in the group + (wave id from merged_wave_info bits 27:24 times 64, plus v_mbcnt lane); + * s_sendmsg 0x9 (GS_ALLOC_REQ) records m0 = vertices | primitives << 12 (Mesa ac_nir_prerast_utils.c + ac_nir_ngg_alloc_vertices_and_primitives) in groupshared memory; after the program a barrier publishes it and + SetMeshOutputCounts runs once, in uniform control flow; + * `exp pos0` / `exp paramN` from thread t define output vertex t, `exp prim` (target 20) primitive t, with the + gfx10 primitive export word: index i in bits [10*i+8 : 10*i], bit 31 = null primitive (Mesa ac_nir_lower_ngg.c + "nir_ubfe_imm(..., 10 * v, 9)" and the "1u << 31" null export). A null or out-of-range primitive is emitted + with SV_CullPrimitive; + * the workgroup index: the console reads v5 (first ES input VGPR, the vertex id in a fast-launch NGG + dispatch) of its first lane and shifts it right by 7. This translation sets v5 = SV_GroupID.x * 128 + + SV_GroupIndex (INFERRED: consistent with every one of the 9282 archive shaders reading v5 >> 7 in each wave + without LDS; a register dump of a mesh pipeline's GE/SPI state would settle it). + +Cross-lane facts the one-lane model cannot see are checked and refused (Unsupported), never guessed: + * v_readfirstlane_b32 needs a source that is the same in every lane (taint analysis over the emitted HLSL); + * a per-lane branch (execz/execnz/vccz/vccnz) is taken per lane; that equals the wave-level branch only when + no scalar register written in the skipped range is read after it, and, for vcc, when vcc is uniform over the + active lanes (`exec & uniform`); + * a branch on an SCC that depends on lane masks (the hardware sets SCC from the whole 64-bit result) is taken + per lane only when that SCC is the same in every active lane and every running thread is an active lane; + otherwise the wave's SCC is published through groupshared memory and a group barrier (MeshStage.lane_scc), + or the program is refused where a barrier cannot be placed (X2W_MESH_LANE_SCC=0 refuses all of them). +LDS, DPP and permlane are not lowered (refused by the base translator); v_writelane / v_readlane only as the SGPR +spill idiom (per-wave scalar slots, MeshStage.lower_spills). +""" +import copy +import os +import re +import struct +import subprocess +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from gfx2hlsl import Unsupported, reg_range, parse # noqa: E402 + +GROUP = 128 # PSV0 numthreads (128, 1, 1) in all 9282 archive mesh records +MAX_VERTICES = 128 # PSV0 MaxOutputVertices +MAX_PRIMITIVES = 128 # PSV0 MaxOutputPrimitives +ALL_LANES = (1 << 64) - 1 +# User SGPRs of the mesh stage start at s16 (MEASURED: in all 4045 distinct run programs the SGPRs read before any +# write lie in s16..s24, and the real root signatures (regblob g57_*.root) give 9 = 3 tables + 1 root SRV + 2 +# constants + resource heap + sampler heap; s8..s15 are written first. Pixel and vertex stages start at s8.) +MESH_USER_SGPR = 16 +FUSED = ('v_fma_f32', 'v_fmac_f32', 'v_fmamk_f32', 'v_fmaak_f32') +UNFUSED = ('v_mad_f32', 'v_mac_f32', 'v_madmk_f32', 'v_madak_f32') +# Multiply-add rule (MESH.md 4.5; the same rule is asked of the vertex-stage translator): positions must come out +# bit-equal in every pipeline that computes them (depth pre-pass vs colour pass with depth EQUAL), so no lowering +# may leave the choice "fuse or not" to the compiler, which decides per shader. +# * v_fma / v_fmac / v_fmamk / v_fmaak are fused on the console (one rounding). Default (X2W_MESH_FMA unset or +# `exact`): x2w_fma, fma in binary64 then one rounding to binary32. The product is exact in binary64; the result +# is the fused one except in rare double-rounding cases, and it is deterministic in every shader. Needs +# double-precision shader ops (D3D12_FEATURE_DATA_D3D12_OPTIONS.DoublePrecisionFloatShaderOps). +# * X2W_MESH_FMA=precise: `precise` multiply then add (two roundings): deterministic and cheap, but not the +# console's value (measured up to 1239 ulp on a position z after cancellation). +# * v_mad / v_mac / v_madmk / v_madak are unfused on the console: always the precise multiply then add. +FMA_MODE = os.environ.get('X2W_MESH_FMA', 'exact') +if os.environ.get('X2W_MESH_EXACT_FMA') == '0': + FMA_MODE = 'precise' # the round-1 switch, kept +if FMA_MODE not in ('exact', 'precise'): + raise SystemExit('X2W_MESH_FMA: exact or precise, not %r' % FMA_MODE) +EXACT_FMA = FMA_MODE == 'exact' +LDS_DWORDS = 1024 # groupshared x2w_lds (4 KB of the 28 KB a D3D12 mesh shader may use); addresses are clamped +TOKEN = re.compile(r'\b(v\d+|s\d+|exec|vcc|m0|scc|a|w|t|q|tid|lane)\b') +SIMPLE = re.compile(r'^\s*(?:if \(exec & 1\) )?(v\d+|s\d+|exec|vcc|m0|scc|a|w|t|q)\s*=\s*(.*)$') + +MESH_HELPERS = { + # v_perm_b32 D, S0, S1, S2: byte i of D = selector byte i of S2 over the eight bytes {S0 (bytes 4-7), S1 (0-3)}; + # 8..11 replicate the sign bit of S1[15], S1[31], S0[15], S0[31]; 12 gives 0x00, 13..15 give 0xff + # (RDNA 2 ISA, V_PERM_B32). + 'x2w_perm': ('uint x2w_perm_byte(uint s0, uint s1, uint sel) { if (sel < 4u) return (s1 >> (8u * sel)) & 255u; ' + 'if (sel < 8u) return (s0 >> (8u * (sel - 4u))) & 255u; if (sel == 8u) return ((s1 >> 15) & 1u) * 255u; ' + 'if (sel == 9u) return ((s1 >> 31) & 1u) * 255u; if (sel == 10u) return ((s0 >> 15) & 1u) * 255u; ' + 'if (sel == 11u) return ((s0 >> 31) & 1u) * 255u; if (sel == 12u) return 0u; return 255u; }\n' + 'uint x2w_perm(uint s0, uint s1, uint s2) { uint r = 0; [unroll] for (uint i = 0; i < 4u; ++i) ' + 'r |= x2w_perm_byte(s0, s1, (s2 >> (8u * i)) & 255u) << (8u * i); return r; }'), + # v_mbcnt_{lo,hi}_u32_b32 D, S0, S1 in a 64-lane wave: S1 + the number of set S0 bits below this lane in the + # low (lanes 0-31) or high (lanes 32-63) half of the wave mask. + 'x2w_fclass': ('uint x2w_fclass(uint u) { uint e = (u >> 23) & 255u, m = u & 0x7fffffu, s = u >> 31; ' + 'if (e == 255u) return m != 0u ? ((m >> 22) != 0u ? 1u : 0u) : (s != 0u ? 2u : 9u); ' + 'if (e == 0u) return m == 0u ? (s != 0u ? 5u : 6u) : (s != 0u ? 4u : 7u); ' + 'return s != 0u ? 3u : 8u; }'), + 'x2w_fma':'float x2w_fma(float a, float b, float c) { return (float)fma((double)a, (double)b, (double)c); }', + 'x2w_madp': 'float x2w_madp(float a, float b, float c) { precise float p = a * b; precise float r = p + c; return r; }', + 'x2w_mbcnt_lo':'uint x2w_mbcnt_lo(uint m, uint lane) { return countbits(m & (lane >= 32u ? 0xffffffffu : ((1u << lane) - 1u))); }', + 'x2w_mbcnt_hi': 'uint x2w_mbcnt_hi(uint m, uint lane) { return lane < 32u ? 0u : countbits(m & ((1u << (lane - 32u)) - 1u)); }', + # word i of a resource-heap descriptor: the runtime's synthesized gfx10 V#/T# words of the view (PROPOSED + # runtime buffer, manifest `heapwords 1`, RUNTIME_NEEDS.md 6.3: 32 bytes per view id, root SRV t2 space1; + # 0 for an unknown slot or view id, so a null descriptor reads as all zero words) + 'x2w_hword': ('ByteAddressBuffer x2w_vdesc : register(t2, space1);\n' + 'uint x2w_hword(uint h, uint i) { uint id = x2w_vid(h); return id < %du ? x2w_vdesc.Load(id * 32u + 4u * i) : 0u; }' + % getattr(G, 'HEAP_IDS', 90000)), +} +# Mesh-only lowerings whose manifest lines need runtime support not in the draw path yet (comma list): +# heapwords = numeric reads of resource-heap descriptor words (x2w_hword, manifest `heapwords 1`). +# Exec-off conflicts (MeshStage.merge_exec_off): on by default; X2W_MESH_EXECOFF=0 restores the earlier refusals. +EXEC_OFF = os.environ.get('X2W_MESH_EXECOFF', '1') != '0' +# X2W_MESH_EXEC_COPIES=0: per-lane skipped ranges accept only exec copies taken inside the range (the f37ad9f8 rule); +# default on: also a pair proven equal to exec at the branch, and copies of copies (MeshStage.exec_copies_at). +EXEC_COPIES = os.environ.get('X2W_MESH_EXEC_COPIES', '1') != '0' +# X2W_MESH_BARRIER_RANGES=0: a group-uniform execz range is skipped when no lane of the group is active even when it +# holds a phase barrier (the f37ad9f8 form; barrier_count then refuses "paths cross different numbers of barriers"). +BARRIER_RANGES = os.environ.get('X2W_MESH_BARRIER_RANGES', '1') != '0' +# X2W_MESH_RESTORED_SCALARS=0: a scalar written in a per-lane skipped range counts as live after it even when every +# exit of the range gives it back its value from before, and liveness reads VALU lane masks by their low SGPR only +# (the f37ad9f8 rule). +RESTORED_SCALARS = os.environ.get('X2W_MESH_RESTORED_SCALARS', '1') != '0' +# X2W_MESH_SPILLS=0: v_writelane_b32 / v_readlane_b32 stay refused (the 9eacac67 behaviour); default on: the SGPR +# spill idiom is lowered to per-wave scalar slots (MeshStage.lower_spills). +SPILLS = os.environ.get('X2W_MESH_SPILLS', '1') != '0' +# X2W_MESH_VCC_DATA=0: vcc stays the one-lane mask variable everywhere (32-bit data in vcc_lo is cut to bit 0, vcc_hi +# is refused); default on: vcc holding no lane mask is the SGPR pair s[106:107] (MeshStage.lower_vcc_data). +VCC_DATA = os.environ.get('X2W_MESH_VCC_DATA', '1') != '0' +# X2W_MESH_DATA_PAIRS=0: every s_mov_b64 between SGPR pairs is a lane-mask move (the base: bit 0 of the low word); +# default on: a pair that holds no lane mask is copied as its two 32-bit registers (MeshStage.scalar_inner). +DATA_PAIRS = os.environ.get('X2W_MESH_DATA_PAIRS', '1') != '0' +SLOT_BASE = 1000 # spill slot (i-th spill VGPR, lane k) = pseudo-SGPR s<SLOT_BASE + 64 * i + k> +# X2W_MESH_RFL_FIRST=0: v_readfirstlane_b32 of a lane-dependent value under a partial exec is refused (as before); +# default on: the wave's first ACTIVE lane is found through groupshared memory and a group barrier +# (MeshStage.first_active_broadcast), and an execz range holding such a read is run by the whole group. +RFL_FIRST = os.environ.get('X2W_MESH_RFL_FIRST', '1') != '0' +RFL_FIRST_SLOTS = 8 # first-active-lane reads per program (each: 2 x 128 groupshared words) +MESH_FEATURES = frozenset(f for f in os.environ.get('X2W_MESH_FEATURES', '').replace(' ', '').split(',') if f) +# descword (MeshStage.dw_*): a word of a TABLE descriptor read as a number becomes the runtime's entry value +# `udsrc <n> descword <param> <byte>` (d3d12_draw.inl, needs X2W_MESH_DESCWORD=1 there), computed lazily: only words +# some numeric use reaches get an entry value; arithmetic nobody reads stays dead (0u). +if MESH_FEATURES - {'heapwords', 'descword'}: + raise SystemExit('X2W_MESH_FEATURES: unknown %s' % ', '.join(sorted(MESH_FEATURES - {'heapwords', 'descword'}))) +# Lane-mask SCC (wave "any lane" value through groupshared memory, MeshStage.lane_scc): on unless +# X2W_MESH_LANE_SCC=0. X2W_MESH_TEST_DROP=publish|restore (TESTS ONLY, negative controls) leaves out the wave +# publish of such an SCC / the restore of hit scalars after a group-uniform execz range: both give wrong results. +LANE_SCC = os.environ.get('X2W_MESH_LANE_SCC', '1') != '0' +TEST_DROP = frozenset(os.environ.get('X2W_MESH_TEST_DROP', '').replace(' ', '').split(',')) - {''} +# Lane taint merged at joins of forward edges (MeshStage.merge): on unless X2W_MESH_JOIN_TAINT=0 (the linear scan). +JOIN_TAINT = os.environ.get('X2W_MESH_JOIN_TAINT', '1') != '0' +# The per-lane shortcut for an active-uniform lane-mask SCC with lanes off needs a mask result confined to the +# active lanes (MeshStage.one_body): on unless X2W_MESH_CONFINED_SCC=0 (tests only: the unrestricted shortcut). +CONFINED_SCC = os.environ.get('X2W_MESH_CONFINED_SCC', '1') != '0' +# A group-uniform execz skip may jump over every barrier the translation added (readfirstlane broadcasts, inner +# group-branch publishes, lane-mask SCC publishes), never over the program's s_barrier: on unless +# X2W_MESH_SKIP_ADDED=0 (then only lane-mask SCC publishes may be skipped, as at 135ee723). +SKIP_ADDED = os.environ.get('X2W_MESH_SKIP_ADDED', '1') != '0' +# Exec lineage (MeshStage.emit, lineage_ok): a value written from uniform values while exec was E stays the same in +# every active lane wherever exec is E or a narrowing of E (also after a restore to a saved copy of E or of a +# narrowing of it), not only until the next exec widening. OFF unless X2W_MESH_EXEC_LINEAGE=1: it moves no request key +# to ok yet (the keys it unblocks stop at a numeric descriptor word next) and no difftest covers a program needing it. +EXEC_LINEAGE = os.environ.get('X2W_MESH_EXEC_LINEAGE', '0') == '1' + + +class UnevenBarrierPaths(Unsupported): + """Forward paths differ in their counts of translated synchronization points.""" + + +class LaneScc(Unsupported): + """A branch on an SCC computed from lane masks; `origins` = offsets of the SALU mask instructions it comes from + (MeshPipeline translates again with those publishing the wave's value).""" + + def __init__(self, text, origins): + super().__init__(text) + self.origins = origins + + +class NeedFirstValue(Unsupported): + def __init__(self, reg, pc): + super().__init__('%s (from v_readfirstlane under a partial exec) read after exec was widened at %#x' % (reg, pc)) + self.reg = reg + + +class NeedGroupRange(Unsupported): + """A lane-dependent v_readfirstlane_b32 inside the per-lane execz range at `off`: MeshPipeline translates again + with that range run by the whole group (MeshStage.group_branches), so the read can use a group barrier.""" + + def __init__(self, off, text): + super().__init__(text) + self.off = off + +# Loop heads take the join of their entry and back edges, iterated until it settles (MeshStage.loop_one). +# X2W_MESH_LOOP_JOIN=0 restores the linear state at loop heads (the old behaviour: wrong for loop-carried values). +LOOP_JOIN = os.environ.get('X2W_MESH_LOOP_JOIN', '1') != '0' +LOOP_PASSES = 8 +BOTTOM = 'x2w_bottom' # key in a symbolic state: no path reaches this code in the current loop pass +# Waterfall loops (MeshStage.waterfalls): one pass per lane with the lane's own value. X2W_MESH_WATERFALL=0 refuses +# them as before (v_readfirstlane of a lane-dependent value with lanes off). +WATERFALL = os.environ.get('X2W_MESH_WATERFALL', '1') != '0' +# Instructions a waterfall body may not contain: cross-lane, wave-level, exec, memory ordering across lanes. +# Per-lane loops (MeshStage.perlane_loop): a back edge on "some lane still loops" becomes each thread's own loop. +# X2W_MESH_PERLANE_LOOPS=0 refuses them as before (branch on an SCC that depends on lane masks). +PERLANE_LOOPS = os.environ.get('X2W_MESH_PERLANE_LOOPS', '1') != '0' +PERLANE_BODY_REFUSED = re.compile(r'(v_readlane|v_writelane|v_permlane|ds_|s_barrier|s_sendmsg|exp$|s_setreg|s_store|' + r's_atomic|s_buffer_store|s_buffer_atomic|.*_dpp$|s_endpgm)') +WATERFALL_BODY_REFUSED = re.compile(r'(v_readlane|v_readfirstlane|v_writelane|v_permlane|ds_|s_barrier|s_sendmsg|exp$|' + r's_setreg|s_cbranch|s_branch|s_endpgm|.*_dpp$|.*_saveexec|.*_wrexec|v_cmpx)') + + +class LoopRetry(Exception): + """A loop head's state was not the join of its edges; carries the back-edge states for the next pass.""" + + def __init__(self, backs): + super().__init__('loop state not settled') + self.backs = backs + + +def scalar_regs(text): + """SGPR numbers named in an operand string (s7, s[4:7]).""" + out = set() + for m in re.finditer(r'\bs\[(\d+):(\d+)\]|\bs(\d+)\b', text): + if m.group(3): + out.add(int(m.group(3))) + else: + out.update(range(int(m.group(1)), int(m.group(2)) + 1)) + return out + + +CARRY = re.compile(r'v_(add|sub|subrev)_co(_ci)?_u32') + +NO_DEST = ('s_cmp', 's_bitcmp', 's_cbranch', 's_branch', 's_waitcnt', 's_sendmsg', 's_barrier', 's_nop', 's_setreg', + 's_inst_prefetch', 's_endpgm', 's_clause', 's_setprio', 's_code_end', 's_sopp') + + +def reads_writes(name, asm): + """(scalar registers read, scalar registers written, writes vcc, reads vcc) of one instruction (approximate: + writes are only what the destination operand names).""" + _, ops, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', name) + writes, reads = set(), set() + wvcc = rvcc = False + if base.startswith('s_') and not base.startswith(NO_DEST) and ops: + writes = scalar_regs(ops[0]) + wvcc = ops[0].startswith('vcc') + rest = ops[1:] + if base.startswith(('s_load', 's_buffer_load')): + rest = ops[1:] + elif (base.startswith('v_cmp') and len(ops) == 3) or base == 'v_readfirstlane_b32' or base == 'v_readlane_b32': + writes = scalar_regs(ops[0]) + wvcc = ops[0].startswith('vcc') + rest = ops[1:] + elif CARRY.fullmatch(base) and len(ops) >= 4: + # VOP2/VOP3b carry-out: the disassembler names one SGPR (or vcc_lo); in wave64 the mask is the pair + writes = scalar_regs(ops[1]) + writes |= {n + 1 for n in writes} + wvcc = ops[1].startswith('vcc') + rest = ops[2:] + else: + rest = ops + if base.startswith('v_cmp') and len(ops) == 2: + wvcc = not base.startswith('v_cmpx') + for o in rest: + reads |= scalar_regs(o) + rvcc |= o.startswith('vcc') + if base in ('v_cndmask_b32', 'v_addc_co_u32') and len(ops) == 3: + rvcc = True + if base in ('s_cbranch_vccz', 's_cbranch_vccnz'): + rvcc = True + return reads, writes, wvcc, rvcc + + +class MeshStage(G.Stage): + """One NGG mesh stage. kind 'ms'.""" + + def __init__(self, pipe, code): + self.tainted = {'tid', 'lane', 'v5'} + self.au, self.epoch = {}, 0 + # exec lineage: exec states form a tree (a narrowing is a child of the state it narrows); xs = the current + # state, au_xs[reg] = (state, write serial) of an active-uniform value, xs_copy[sgpr] = the state it copies + self.xs, self.xs_parent, self.au_xs, self.xs_copy, self.xs_serial = 0, {0: None}, {}, {}, 0 + self._xs_exec_seen = False + self.au_scalars = {} + self.broadcasts = 0 + self.literal_tables = {} + self.first_slots = 0 # first-active-lane reads (x2w_rfv / x2w_rfe slots) + self.divergent_until = -1 + self.exported_vertex = False + self.exported_prim = False + self.alloc_seen = False + self.wave = 64 + self.exec_static = ALL_LANES # exec as a known 64-bit lane mask (the same in every wave), else None + self.static_copies = {} # SGPR -> the static exec mask it holds + self._static_set = False + self.shadow = {} # VGPR -> (unguarded variable, exec mask at the write); straight-line code only + self.shadow_vars = [] + self.pending = [] # statements that start the next block (after a broadcast barrier) + self.scc_from = {} # register -> offsets of lane-mask SCC definitions its value derives from + self.vcc_votes = set() + self.lane_edges = set() + self.scc_any = [] # lane-mask SCCs published per wave (offsets): x2w_sany[k][wave] + self.join_from = {} # branch target -> scc_from union over the branches to it + self.fell_off = False # the previous instruction does not fall through (jump, end) + self.running_active = False # inside a per-lane execz range, no exec write since: running threads = active lanes + self.scc_confined = set() # lane-mask SCC offsets whose mask result is inside the active lanes (`x & exec`) + self.lds_used = False + self.lds_written_in_phase = False + self.exec_off = set() # conflict SGPRs whose conflicting paths all came with this lane's exec bit 0 + self._execz_edge = False + self._execz_snaps = [] # snapshots of taken s_cbranch_execz edges (compared by identity) + super().__init__(pipe, 'ms', code) + if not self.alloc_seen: + raise Unsupported('no GS_ALLOC_REQ (s_sendmsg 0x9): not an NGG mesh stage') + self.padded_phases = False + try: + self.barriers = self.barrier_count() + except UnevenBarrierPaths: + if not SKIP_ADDED or os.environ.get('X2W_MESH_PAD_PUBLISH') != '1': + raise + self.barriers = self.padded_barrier_count() + self.padded_phases = True + + def translate(self): + # The program ends at the s_code_end padding; the words after it are data, not code. + for i, x in enumerate(self.ins): + if x[2] == 's_code_end': + self.ins = self.ins[:i] + break + self.vcc_renamed = self.lower_vcc_data() + self.spill_vgprs, self.spill_slots = self.lower_spills() + self.swap_scc = self.lower_pair_swaps() + self.has_lds = any(x[2].startswith('ds_') for x in self.ins) + self.wave_any = [] # group-uniform execz branches (offsets): x2w_any[k][wave] = some lane active + self.group_restore = {} # range end -> statements restoring hit scalars in a wave that had no lane on + self.group_checks = {} # range end -> (register, symbolic value before the range, branch offset) + self.uniform_skips = set() # offsets of the inserted group-uniform skip blocks + if LOOP_JOIN and self.loop_heads(): + self.loop_prepare() + self.one = self.loop_one # instance attribute: the base's scan calls it for every instruction + result = super().translate() + if LOOP_JOIN and self.loop_heads(): + self.loop_settled() + for n in sorted(self.spill_vgprs): + if n in self.used_v or n in self.written_v: + raise Unsupported('v%d holds spilled scalars (v_writelane) and is also used as a VGPR' % n) + # A group-uniform branch block ends in a barrier (the lanes publish their exec bit); the block after it + # skips the range when no lane of the group was active (group_branch). + # A range with a phase barrier inside (a console s_barrier, a broadcast or a nested group branch) is never + # skipped: the skip is group-uniform, but a block after the range would then start in two different phases + # (body() gives each block one). Running it with every lane off is what skipping does: vector writes, + # exports, LDS writes and stores stay guarded by exec, and the restore gives each wave with no active lane + # its scalars from before the range back. + # (lane-mask SCC publish barriers are left out: 28020dea lets the uniform skip jump over those) + barrier_at = [b[0] for b in self.blocks if b[2] and b[2][0] == 'barrier' and b[2][1:2] != ('lane-scc',)] + blocks = [] + votes = set() + for b in self.blocks: + if b[2] and b[2][0] == 'branch' and b[2][1] in self.vcc_votes: + votes.add(b[0]) + blocks.append((b[0], self.group_restore.get(b[0], []) + b[1], ('barrier', 'vcc-vote'))) + blocks.append((b[0] + 0.5, [], b[2])) + elif b[2] and b[2][:2] == ('barrier', 'rfl-edge'): + votes.add(b[0]) + blocks.append((b[0], self.group_restore.get(b[0], []) + b[1], ('barrier',))) + blocks.append((b[0] + 0.5, [b[2][2]], None)) + elif b[2] and b[2][0] == 'barrier' and len(b[2]) > 1 and b[2][1] == 'wave-branch': + k = b[2][2] + blocks.append((b[0], self.group_restore.get(b[0], []) + b[1], ('barrier',))) + if not (BARRIER_RANGES and any(b[0] < o < b[2][3] for o in barrier_at)): + blocks.append((b[0] + 0.5, [], ('branch', '(x2w_any[%d][0] | x2w_any[%d][1]) == 0u' % (k, k), b[2][3]))) + self.uniform_skips.add(b[0] + 0.5) + elif b[0] in self.group_restore: + blocks.append((b[0], self.group_restore[b[0]] + b[1], b[2])) + else: + blocks.append(b) + missing = set(self.group_restore) - {b[0] for b in self.blocks} + if missing: + raise Unsupported('execz range end %#x is not a block start' % min(missing)) + self.blocks = blocks + if votes: + self.check_vote_participation(votes) + return result + + def check_vote_participation(self, votes): + """Every lane of a guest wave must reach the vote when the wave takes this path.""" + index = {off: i for i, (off, _, _) in enumerate(self.blocks)} + end = len(index) + successors = [] + for i, (_, _, term) in enumerate(self.blocks): + out = [] if term and term[0] in ('end', 'jump') else [i + 1] + if term and term[0] in ('branch', 'jump'): + out.append(index[term[-1]]) + successors.append(out or [end]) + post = [(1 << (end + 1)) - 1] * end + [1 << end] + while True: + changed = False + for i in reversed(range(end)): + common = post[successors[i][0]] & post[successors[i][-1]] + updated = common | (1 << i) + if updated != post[i]: + post[i] = updated + changed = True + if not changed: + break + vote_nodes = {index[off] for off in votes} + for i, (_, _, term) in enumerate(self.blocks): + if not term or term[0] != 'branch' or id(term) not in self.lane_edges: + continue + pending = list(successors[i]) + seen = set() + while pending: + node = pending.pop() + if node in seen or (post[i] >> node) & 1: + continue + if node in vote_nodes: + raise Unsupported('VCC vote in lane-divergent control flow') + seen.add(node) + pending.extend(successors[node]) + + def lower_pair_swaps(self): + """A ^= B; B ^= A; A ^= B swaps two disjoint SGPR pairs, including descriptors. + Keep the original offsets for branches. No edge may enter the middle. The final + XOR's wave-wide SCC must be dead because the three replacement moves leave it alone. + """ + targets = {int(parse(asm)[1][0].split('_')[1], 16) for _, _, name, asm in self.ins + if name == 's_branch' or name.startswith('s_cbranch')} + scc = set() + for i, first in enumerate(self.ins): + _, _, xor, _ = first + if xor not in ('s_xor_b32', 's_xor_b64'): + continue + first_ops = parse(first[3])[1] + if len(first_ops) != 3: + continue + touched = set().union(*(scalar_regs(o) for o in first_ops)) + sites = [i] + for j in range(i + 1, min(i + 16, len(self.ins))): + off, _, name, asm = self.ins[j] + if off in targets: + break + if name == xor: + sites.append(j) + if len(sites) == 3: + break + else: + if not (name in ('s_mov_b32', 's_mov_b64') or + re.fullmatch(r'v_(?:add_f32|sub_f32|mul_f32|mov_b32)_e(?:32|64)', name)): + break + regs = set().union(*G.sgpr_access(name, asm)) + if regs & touched or 'src_scc' in parse(asm)[1]: + break + if len(sites) != 3: + continue + operands = [parse(self.ins[j][3])[1] for j in sites] + if any(len(o) != 3 for o in operands): + continue + a, b = operands[0][0], operands[1][0] + ra, rb = reg_range(a), reg_range(b) + width = 2 if xor.endswith('64') else 1 + if not all(r and r[0] == 's' and r[2] == r[1] + width - 1 and r[2] < 128 for r in (ra, rb)): + continue + if abs(ra[1] - rb[1]) < width or operands[2][0] != a or any(set(o[1:]) != {a, b} for o in operands): + continue + # The architectural SGPRs are below 128; private lane spill slots start at SLOT_BASE. + tmp = 's[%d:%d]' % (SLOT_BASE-2, SLOT_BASE-1) if width == 2 else 's%d' % (SLOT_BASE-2) + move = 's_mov_b64' if width == 2 else 's_mov_b32' + for j, (dst, src) in zip(sites, ((tmp, a), (a, b), (b, tmp))): + off, n, _, _ = self.ins[j] + self.ins[j] = (off, n, move, '%s %s, %s' % (move, dst, src)) + scc.add(self.ins[sites[-1]][0]) + return scc + + def check_scc(self, written, unknown): + return super().check_scc(written, unknown | self.swap_scc) + + # ---- SGPR spills to VGPR lanes -------------------------------------------------------------- + # v_writelane_b32 vN, S, k writes the scalar S into lane k of vN and keeps the other lanes; v_readlane_b32 sD, vN, k + # copies lane k of vN into sD. Neither reads exec (LLVM VOP2Instructions.td: "These are special and do not read + # the exec mask", Uses = []; V_WRITELANE_B32 ties $vdst = $vdst_in). LLVM SIRegisterInfo::spillSGPR / + # restoreSGPR and Mesa ACO spill a scalar register to one lane per 32-bit part with an immediate lane index, so + # the 64 lanes of such a VGPR are 64 wave scalars: lane k is written and read only as a whole-wave value. In the + # one-lane model that is a scalar register like any other; lower_spills renames it to the pseudo-SGPR + # s<SLOT_BASE + 64 * i + k> and the instructions to scalar moves, so liveness, the per-lane skipped-range rules, + # group-uniform branches, lane masks, symbolic descriptors and exec copies treat a slot exactly as an SGPR. + @staticmethod + def _half(tok): + """(pair name for s_mov_b64, 0 = low / 1 = high half) of a 32-bit operand that is half of a 64-bit pair.""" + if tok in ('vcc_lo', 'vcc_hi'): + return 'vcc', int(tok == 'vcc_hi') + if tok in ('exec_lo', 'exec_hi'): + return 'exec', int(tok == 'exec_hi') + r = reg_range(tok) + if r and r[0] == 's' and r[1] == r[2] and r[1] < SLOT_BASE: + low = r[1] & ~1 # 64-bit SGPR operands are even-aligned + return 's[%d:%d]' % (low, low + 1), r[1] & 1 + return None + + # ---- vcc as two 32-bit scalar registers ---------------------------------------------------------- + # VCC_LO / VCC_HI are SGPRs 106 / 107 (RDNA 2 ISA, scalar operand encoding); in wave64 the compiler uses them as + # an ordinary SGPR pair when no lane mask needs them (32-bit loads, moves, float operands, spills). The one-lane + # model keeps a lane MASK in the variable `vcc` (the lane's bit), so a 32-bit value there is cut to bit 0. + @staticmethod + def vcc_roles(name, asm): + """[(operand index or None, halves, is_def, kind)] for each vcc operand; kind 'mask' (the wave64 lane mask + the one-lane model keeps in `vcc`), 'data' (a 32-bit value) or 'any' (a 64-bit scalar move or logic op, + a spill of a half: right either way).""" + _, ops, mods = parse(asm) + base = re.sub(r'_(e32|e64|sdwa|dpp)$', '', name) + out = [] + if base in ('s_cbranch_vccz', 's_cbranch_vccnz'): + return [(None, (0, 1), False, 'mask')] + if base in ('v_div_fmas_f32', 'v_div_fmas_f64', 'v_div_scale_f32', 'v_div_scale_f64'): + out.append((None, (0, 1), base.startswith('v_div_scale'), 'mask')) # implicit vcc + carry = re.fullmatch(r'v_(add|sub|subrev)_co(_ci)?_u32|v_(add|sub|subrev)c_co_u32', base) + for i, tok in enumerate(ops): + t = tok.lstrip('-|').rstrip('|') + r = reg_range(t) + if r and r[0] == 's' and r[1] <= 107 and r[2] >= 106: + # the disassembler names vcc by number inside a register range (s_buffer_load_dwordx2 s[106:107]) + halves = tuple(h for h in (0, 1) if r[1] <= 106 + h <= r[2]) + elif t not in ('vcc', 'vcc_lo', 'vcc_hi'): + continue + else: + halves = (0, 1) if t == 'vcc' else ((1,) if t == 'vcc_hi' else (0,)) + if base.startswith('s_'): + is_def = i == 0 and not base.startswith(NO_DEST) + kind = 'any' if (base.endswith('_b64') or 'saveexec' in base) else 'data' + elif base.startswith('v_cmp') and not base.startswith('v_cmpx') and i == 0: + is_def, kind, halves = True, 'mask', (0, 1) # wave64 SDST: the disassembler names vcc_lo + elif base == 'v_cndmask_b32' and i == len(ops) - 1: + is_def, kind, halves = False, 'mask', (0, 1) + elif carry and i == 1 and len(ops) >= 4: + is_def, kind, halves = True, 'mask', (0, 1) + elif carry and i == len(ops) - 1 and len(ops) >= 5: + is_def, kind, halves = False, 'mask', (0, 1) + elif base in ('v_writelane_b32', 'v_readlane_b32'): + is_def, kind = base == 'v_readlane_b32' and i == 0, 'any' + elif base in ('v_readfirstlane_b32',) and i == 0: + is_def, kind = True, 'data' + else: + is_def, kind = False, 'data' + out.append((i, halves, is_def, kind)) + # forms whose vcc the disassembler might leave implicit (VOPC / VOP2 carry / cndmask e32 without a vcc + # operand): the lane mask + if not any(j is not None for j, _, _, _ in out) and name.endswith('_e32'): + if base.startswith('v_cmp') and not base.startswith('v_cmpx'): + out.append((None, (0, 1), True, 'mask')) + elif base == 'v_cndmask_b32' or (carry and '_ci' in base) or re.fullmatch(r'v_(add|sub|subrev)c_co_u32', base): + out.append((None, (0, 1), False, 'mask')) + if carry: + out.append((None, (0, 1), True, 'mask')) + return out + + def lower_vcc_data(self): + """Rename vcc to the SGPR pair s[106:107] where it does not hold a lane mask. Webs of definitions and uses of + each half (reaching definitions over the branch graph) are classified by their instructions: a web with a + lane-mask use or definition keeps `vcc`; any other web (32-bit data, or only 64-bit moves) is renamed, which + is exact (an SGPR pair takes every scalar form, including a lane mask moved through it). A web that is + both a lane mask and 32-bit data is refused, unless its only 32-bit uses are scalar reads whose results + nothing reads (dead_use; the web then keeps `vcc`, as before the rename). Returns the number of renamed + operands.""" + if not VCC_DATA: + return 0 + roles = {i: self.vcc_roles(x[2], x[3]) for i, x in enumerate(self.ins)} + roles = {i: r for i, r in roles.items() if r} + if not any(k == 'data' or (j is not None and k == 'any') for r in roles.values() for (j, h, d, k) in r): + return 0 + parent = {} + + def find(a): + parent.setdefault(a, a) + while parent[a] != a: + parent[a] = parent[parent[a]] + a = parent[a] + return a + + def union(a, b): + parent[find(a)] = find(b) + kind_of = {} + for i, r in roles.items(): + for n, (j, halves, is_def, kind) in enumerate(r): + nodes = [(i, n, h) for h in halves] + for a in nodes: + kind_of[a] = kind + find(a) + for a in nodes[1:]: + union(nodes[0], a) + offs = [x[0] for x in self.ins] + at = {x[0]: i for i, x in enumerate(self.ins)} + # Reaching definitions, with each path marked "exec is zero" after the taken edge of s_cbranch_execz (the + # fall-through of execnz) until an exec write that can turn lanes on. A vector instruction does nothing in a + # lane whose exec bit is off (in the one-lane model: its writes are guarded), so a definition that reaches a + # vector data use only along such paths does not join that use's value. + entry = (('entry', 0), ('entry', 1)) + for a in entry: + kind_of[a] = 'any' + find(a) + + def zero_edges(i): + """(successor, path becomes exec-zero) pairs.""" + name, asm = self.ins[i][2], self.ins[i][3] + out = [] + t = int(parse(asm)[1][0].split('_')[1], 16) if (name.startswith('s_cbranch') or name == 's_branch') else None + if name not in ('s_endpgm', 's_branch') and i + 1 < len(self.ins): + out.append((i + 1, name == 's_cbranch_execnz')) + if t is not None and t in at: + out.append((at[t], name == 's_cbranch_execz')) + return out + + def narrows(name, asm): + ops = parse(asm)[1] + if name.startswith('v_cmpx') or name == 's_and_saveexec_b64': + return True + return bool(re.match(r's_(and|andn2)_b64$', name) and ops and ops[0] == 'exec' and 'exec' in ops[1:2] + or re.match(r's_and_b64$', name) and ops and ops[0] == 'exec' and 'exec' in ops[1:]) + # facts: (frozenset of path flags reaching, defs of half 0, defs of half 1); a def is (node, exec-zero flag) + reach = {0: (frozenset([False]), frozenset([(entry[0], False)]), frozenset([(entry[1], False)]))} if self.ins else {} + work = [0] if self.ins else [] + while work: + i = work.pop() + flags, d0, d1 = reach[i] + facts = [d0, d1] + name, asm = self.ins[i][2], self.ins[i][3] + for n, (j, halves, is_def, kind) in enumerate(roles.get(i, ())): + if not is_def: + vector_data = kind == 'data' and name.startswith('v_') + for h in halves: + for d, z in facts[h]: + if not (z and vector_data): + union((i, n, h), d) + for n, (j, halves, is_def, kind) in enumerate(roles.get(i, ())): + if is_def: + for h in halves: + facts[h] = frozenset(((i, n, h), z) for z in flags) + if self.exec_written(name, parse(asm)[1]) and not narrows(name, asm): + flags = frozenset([False]) + facts = [frozenset((d, False) for d, z in f) for f in facts] + for s, zero in zero_edges(i): + if zero: + out = (frozenset([True]),) + tuple(frozenset((d, True) for d, z in f) for f in facts) + else: + out = (flags, facts[0], facts[1]) + old = reach.get(s) + new = out if old is None else tuple(a | b for a, b in zip(old, out)) + if new != old: + reach[s] = new + work.append(s) + webs = {} + for a, k in kind_of.items(): + webs.setdefault(find(a), set()).add((k, a)) + all_reads = set() + for x in self.ins: + all_reads |= set(reads_writes(x[2], x[3])[0]) + + def dead_use(i): + """A scalar instruction reading vcc as data whose results nothing reads: its destination SGPRs are read + by no instruction of the program, it writes no vcc / exec / m0, and its SCC (assumed written) is not + read on any path before an s_cmp / s_bitcmp sets SCC again.""" + name, asm = self.ins[i][2], self.ins[i][3] + if not name.startswith('s_') or name.startswith(('s_cbranch', 's_branch', 's_setpc', 's_swappc')): + return False + rd, wr, wv, rv = reads_writes(name, asm) + ops = parse(asm)[1] + if wv or (ops and ops[0].startswith(('exec', 'm0'))) or set(wr) & all_reads: + return False + seen, work = set(), [s for s, _ in zero_edges(i)] + while work: + k = work.pop() + if k in seen: + continue + seen.add(k) + kn, ka = self.ins[k][2], self.ins[k][3] + if G.reads_scc(kn, ka): + return False + if kn.startswith(('s_cmp', 's_bitcmp')): + continue + work += [s for s, _ in zero_edges(k)] + return True + rename = set() + for root, members in webs.items(): + kinds = {k for k, _ in members} + if 'mask' in kinds and 'data' in kinds: + data = [a for k, a in members if k == 'data' and a[0] != 'entry'] + if all(not roles[a[0]][a[1]][2] and dead_use(a[0]) for a in data): + continue # only dead 32-bit reads of a lane mask: nothing observes the cut value + m = next(offs[a[0]] for k, a in members if k == 'mask' and a[0] != 'entry') + d = next(offs[a[0]] for k, a in members if k == 'data' and a[0] != 'entry') + raise Unsupported('vcc used as a lane mask (%#x) and as 32-bit data (%#x) in one value' % (m, d)) + if 'mask' not in kinds: + rename |= {(a[0], a[1]) for k, a in members if a[0] != 'entry'} + count = 0 + for i, n in sorted(rename): + j = roles[i][n][0] + if j is None: + continue + off, size, name, asm = self.ins[i] + _, ops, mods = parse(asm) + tok = ops[j] + t = tok.lstrip('-|').rstrip('|') + if t not in ('vcc', 'vcc_lo', 'vcc_hi'): + continue # already named s106 / s107 by number + ops[j] = tok.replace(t, {'vcc': 's[106:107]', 'vcc_lo': 's106', 'vcc_hi': 's107'}[t]) + text = '%s %s' % (asm.split(' ', 1)[0], ', '.join(ops)) + if mods: + text += ' ' + ' '.join(mods) + self.ins[i] = (off, size, name, text) + count += 1 + return count + + def lower_spills(self): + """Rewrite the spill idiom in self.ins (before the translation and every analysis reads it) into scalar + moves to pseudo-SGPR slots; refuse whatever is not that idiom. Returns (spill VGPR numbers, slot numbers). + + * v_writelane_b32 vN, S, k -> s_mov_b32 slot(N, k), S; v_readlane_b32 sD, vN, k -> s_mov_b32 sD, slot(N, k). + * The two halves of a 64-bit pair (sX/sX+1, vcc_lo/hi, exec_lo/hi) spilled to lanes k, k+1, or reloaded from + them, in one basic block with nothing in between reading or writing the registers or slots involved, + become one s_mov_b64 at the later instruction (the earlier is a no-op): the value moved is the same, and + the lane-mask and exec-copy rules see the pair. A half of vcc or exec on its own is refused (the one-lane + model keeps only the lane's bit of a mask; vcc as 32-bit data is not modelled). + * Refused: a lane select that is not a constant 0..63, a spill VGPR named by any other instruction (also + checked against the translation's VGPR use afterwards), a slot read on some path before any write.""" + idx = [i for i, x in enumerate(self.ins) if x[2] in ('v_writelane_b32', 'v_readlane_b32')] + if not idx or not SPILLS: + return set(), set() + info = {} + vgprs = set() + for i in idx: + off, n, name, asm = self.ins[i] + _, ops, mods = parse(asm) + if mods or len(ops) != 3: + raise Unsupported('%s form %s at %#x' % (name, asm, off)) + vtok = ops[0] if name == 'v_writelane_b32' else ops[1] + v = reg_range(vtok) + if not v or v[0] != 'v' or v[1] != v[2]: + raise Unsupported('%s on %s at %#x' % (name, vtok, off)) + if not re.fullmatch(r'0x[0-9a-f]+|\d+', ops[2]) or int(ops[2], 0) > 63: + raise Unsupported('%s lane select %s is not a constant lane at %#x' % (name, ops[2], off)) + info[i] = (name, v[1], int(ops[2], 0), ops[1] if name == 'v_writelane_b32' else ops[0]) + vgprs.add(v[1]) + order = sorted(vgprs) + slot = {(v, k): SLOT_BASE + 64 * j + k for j, v in enumerate(order) for k in range(64)} + # any other instruction naming a spill VGPR (single or in a range) uses it as per-lane data + for i, (off, n, name, asm) in enumerate(self.ins): + if i in info: + continue + for m in re.finditer(r'\bv(\d+)\b|\bv\[(\d+):(\d+)\]', asm): + lo, hi = (int(m.group(1)),) * 2 if m.group(1) else (int(m.group(2)), int(m.group(3))) + hit = [v for v in order if lo <= v <= hi] + if hit: + raise Unsupported('v%d holds spilled scalars (v_writelane) and is also used by %s at %#x' + % (hit[0], name, off)) + targets = self.branch_targets() + + def regs_of(name, asm): + """(scalar registers read, written) with vcc = -1 and exec = -2.""" + r, w, wv, rv = reads_writes(name, asm) + r, w = set(r), set(self.pair_writes(name, asm)) + ops = parse(asm)[1] + if wv: + w.add(-1) + if rv: + r.add(-1) + if self.exec_written(name, ops): + w.add(-2) + if not name.startswith('s_') or any(t.startswith('exec') for t in ops[1:]) or 'saveexec' in name: + r.add(-2) # every vector instruction reads exec + return r, w + + def tok_regs(tok): + if tok.startswith('vcc'): + return {-1} + if tok.startswith('exec'): + return {-2} + r = reg_range(tok) + return set(range(r[1], r[2] + 1)) if r and r[0] == 's' else set() + + def partner(i): + """Index of the other half's instruction that may be fused with i, or None.""" + name, v, k, tok = info[i] + half = self._half(tok) + if not half: + return None + pair, h = half + want_k = k + 1 if h == 0 else k - 1 + regs = tok_regs(tok) | tok_regs(pair) + slots = {slot[(v, k)], slot.get((v, want_k), -9)} + for j in range(i + 1, len(self.ins)): + off, n, nm, asm = self.ins[j] + if off in targets: + return None + if j in info and info[j][0] == name and info[j][1] == v and info[j][2] == want_k: + other = self._half(info[j][3]) + return j if other == (pair, 1 - h) else None + if j in info: + jn, jv, jk, jt = info[j] + if slot[(jv, jk)] in slots: + return None + r, w = (tok_regs(jt), set()) if jn == 'v_writelane_b32' else (set(), tok_regs(jt)) + else: + r, w = regs_of(nm, asm) + if w & regs or (name == 'v_readlane_b32' and r & regs): + return None + if nm.startswith('s_cbranch') or nm in ('s_branch', 's_endpgm', 's_setpc_b64'): + return None + return None + + new = list(self.ins) + done = set() + for i in idx: + if i in done: + continue + name, v, k, tok = info[i] + off, n = self.ins[i][0], self.ins[i][1] + j = partner(i) + if j is not None: + pair, h = self._half(tok) + lo_k = k if h == 0 else k - 1 + spair = 's[%d:%d]' % (slot[(v, lo_k)], slot[(v, lo_k)] + 1) + asm = 's_mov_b64 %s, %s' % ((spair, pair) if name == 'v_writelane_b32' else (pair, spair)) + new[i] = (off, n, 's_nop', 's_nop 0') + new[j] = (self.ins[j][0], self.ins[j][1], 's_mov_b64', asm) + done |= {i, j} + continue + s = 's%d' % slot[(v, k)] + if name == 'v_writelane_b32': + if tok.startswith(('vcc', 'exec')) or (reg_range(tok) and reg_range(tok)[0] != 's'): + raise Unsupported('v_writelane_b32 of %s alone at %#x (half of a 64-bit pair)' % (tok, off)) + new[i] = (off, n, 's_mov_b32', 's_mov_b32 %s, %s' % (s, tok)) + else: + r = reg_range(tok) + if not r or r[0] != 's': + raise Unsupported('v_readlane_b32 into %s alone at %#x (half of a 64-bit pair)' % (tok, off)) + new[i] = (off, n, 's_mov_b32', 's_mov_b32 %s, %s' % (tok, s)) + done.add(i) + self.ins = new + slots = {s for (v, k), s in slot.items()} + entry = self.liveness().get(self.ins[0][0], frozenset()) if self.ins else frozenset() + unset = sorted(r for r in entry if isinstance(r, int) and r >= SLOT_BASE) + if unset: + j, k = divmod(unset[0] - SLOT_BASE, 64) + raise Unsupported('v_readlane_b32 of v%d lane %d, which no v_writelane_b32 writes on some path to it' + % (order[j], k)) + return set(vgprs), slots + # ---- loops: the state at a loop head is the join of every edge into it ----------------------------------- + # The base scan is linear and keeps, at a loop head, the state of the instruction above it: the back edges are + # never seen (a constant before the loop was folded into the loop body: `s0 = 0; loop: s0 += 1` became + # `s0 = 0u + 1u` on every iteration), and after an s_branch that state belongs to no path at all. Here the + # stage is translated again until the state used at each loop head equals the join of its entry edges and + # its back edges from the pass before (MeshPipeline retries on LoopRetry). A head no entry reaches in a pass + # (entered through a forward branch into the body) is `bottom`: what is translated from it is not used and + # its edges are left out of joins, and the next pass seeds it with the back edges. + def loop_prepare(self): + heads = self.loop_heads() + self._loop_edges = {} # head -> offsets of the branches to it + targets = set() + for off, _, name, asm in self.ins: + if name.startswith('s_cbranch') or name == 's_branch': + t = int(parse(asm)[1][0].split('_')[1], 16) + targets.add(t) + if t in heads: + self._loop_edges.setdefault(t, []).append(off) + # Unreachable alignment NOPs after a jump do not introduce another + # entry edge into the following loop head. + self._loop_fallthrough = set() + falls_through = False + for off, _, name, _ in self.ins: + if falls_through and off in heads: + self._loop_fallthrough.add(off) + reachable = falls_through or off in targets or off == self.ins[0][0] + falls_through = reachable and name not in ('s_branch', 's_endpgm') + self._loop_branch = {o for v in self._loop_edges.values() for o in v} + self._loop_after = {} # branch offset -> loop state after it (this pass) + self._loop_entry = {} # head -> loop states of its entries (forward edges, fall-through), this pass + self._loop_used = {} # head -> the joined state used at the head, this pass + self._loop_bottom = False + + def loop_state(self): + return (self.snapshot(), frozenset(self.tainted), dict(self.au_scalars)) + + def loop_join(self, states): + """Sets the stage to the join of loop states (snapshot, tainted, au_scalars).""" + self.merge([s[0] for s in states]) + self.tainted = set().union(*(s[1] for s in states)) + # values known uniform only over the active lanes are not followed around a loop: lane-dependent + self.au = {} + self.lineage_reset() + stale = {r for s in states for r in s[2]} + current = states[0][2] + self.au_scalars = {r: (current[r] if all(s[2].get(r) == current.get(r) for s in states) else -1) + for r in stale} + self.lane_s = set(range(128)) # the base marks every SGPR suspect at a loop head; keep it so + + @staticmethod + def loop_key(state): + snap, tainted, au_scalars = state + return (snap[0], snap[1], snap[2], tainted, tuple(sorted(au_scalars.items()))) + + def loop_one(self, name, asm): + head = self.pc if self.pc in self._loop_edges else None + if head is not None: + entries = [self._loop_after[o] for o in self._loop_edges[head] if o < head and o in self._loop_after] + if head in self._loop_fallthrough and BOTTOM not in self.sym: + entries.append(self.loop_state()) + entries = [s for s in entries if BOTTOM not in s[0][0]] + self._loop_entry[head] = entries + seeds = [s for s in self.pipe.loop_seed.get(head, []) if BOTTOM not in s[0][0]] + if entries or seeds: + self.loop_join(entries + seeds) + else: + self.sym[BOTTOM] = True + self._loop_bottom = True + self._loop_used[head] = self.loop_state() + if BOTTOM in self.sym: + # not reached by any path in this pass: translated only to carry on the scan + try: + term = MeshStage.one(self, name, asm) + except Unsupported: + term = None + else: + term = MeshStage.one(self, name, asm) + if self.pc in self._loop_branch: + self._loop_after[self.pc] = self.loop_state() + return term + + def loop_settled(self): + """Raises LoopRetry with the back edges of this pass when some loop head's state was not the join.""" + backs = {h: [self._loop_after[o] for o in srcs if o >= h and o in self._loop_after] + for h, srcs in self._loop_edges.items()} + saved = self.loop_state() + settled = not self._loop_bottom + for head, used in self._loop_used.items(): + states = [s for s in self._loop_entry.get(head, []) + backs[head] if BOTTOM not in s[0][0]] + if not states: + settled = False + continue + self.loop_join(states) + if self.loop_key(self.loop_state()) != self.loop_key(used): + settled = False + self.loop_join([saved]) + if not settled: + raise LoopRetry(backs) + + def next_offset(self): + for off, n, _, _ in self.ins: + if off == self.pc: + return off + n + return None + + def loop_heads(self): + if getattr(self, '_heads', None) is None: + self._heads = set() + for off, _, name, asm in self.ins: + if name.startswith('s_cbranch') or name == 's_branch': + t = int(parse(asm)[1][0].split('_')[1], 16) + if t <= off: + self._heads.add(t) + # a waterfall is translated as one pass per lane (no loop): its head takes no loop join + self._heads -= {h for h, info in self.waterfalls().items() if not info['refuse']} + return self._heads + + # ---- waterfall loops: one pass per lane with the lane's own value ---------------------------------------- + # The compiler's idiom for a resource index that differs between lanes (LLVM AMDGPU SIInstrInfo + # loadMBUFScalarOperandsFromVGPR / emitLoadScalarOpsFromVGPRLoop, "waterfall loop"): + # s_mov_b64 s[a], exec; s_mov_b64 s[m], exec (copies of exec before the loop) + # H: v_readfirstlane_b32 sX, vY (the first remaining lane's value) + # v_cmpx_eq_u32/i32 sX, vY (exec = the remaining lanes holding that value) + # ... body using sX as a uniform value ... + # s_andn2_wrexec_b64 s[m], s[m] (m &= ~exec; exec = m; SCC = m != 0) + # s_cbranch_scc1 H (again while lanes remain) + # s_mov_b64 exec, s[a] (restore) + # Each lane that is active at H runs the body exactly once, with exec holding it (and the other lanes of its + # value), and sX equal to its own vY. In the one-lane model that is: sX = vY, the body under the lane's entry + # exec bit, then on: s[m] = 0, SCC = 0, exec back to s[a] (RDNA 2 ISA S_ANDN2_WREXEC_B64, V_CMPX_EQ_U32, + # V_READFIRSTLANE_B32). The hardware leaves sX, the body's scalar results and vcc with the LAST pass's values; + # here every lane holds its own, so such a register must not be read after the loop (refused). + def waterfalls(self): + """head -> {role offset: role} plus 'refuse' (a reason) for each loop that has the waterfall's shape.""" + if getattr(self, '_wf', None) is not None: + return self._wf + self._wf = {} + if not WATERFALL: + return self._wf + ins = self.ins + index = {x[0]: i for i, x in enumerate(ins)} + sources = {} + for off, _, name, asm in ins: + if name.startswith('s_cbranch') or name == 's_branch': + sources.setdefault(int(parse(asm)[1][0].split('_')[1], 16), []).append(off) + skip = ('s_nop', 's_waitcnt', 's_waitcnt_vmcnt', 's_waitcnt_lgkmcnt', 's_waitcnt_depctr') + for i, (off, _, name, asm) in enumerate(ins): + if name != 's_cbranch_scc1': + continue + head = int(parse(asm)[1][0].split('_')[1], 16) + if head > off or head not in index or sources.get(head) != [off]: + continue + j = index[head] + k = j + while k < i and ins[k][2] in skip: + k += 1 + if k + 2 >= i - 1 or ins[k][2] != 'v_readfirstlane_b32': + continue + rops = parse(ins[k][3])[1] + cname, cops = ins[k + 1][2], parse(ins[k + 1][3])[1] + wname, wops = ins[i - 1][2], parse(ins[i - 1][3])[1] + sx, vy = reg_range(rops[0]), reg_range(rops[1]) + if not (sx and sx[0] == 's' and vy and vy[0] == 'v' and sx[2] == sx[1] and vy[2] == vy[1]): + continue + if not (re.fullmatch(r'v_cmpx_eq_[ui]32_e32', cname) and sorted(cops) == sorted(rops)): + continue + mr = reg_range(wops[0]) if wops else None + if not (wname == 's_andn2_wrexec_b64' and len(wops) == 2 and wops[0] == wops[1] and mr and mr[0] == 's'): + continue + m = mr[1] + info = {'head': head, 'rfl': ins[k][0], 'cmpx': ins[k + 1][0], 'wrexec': ins[i - 1][0], 'branch': off, + 's': sx[1], 'v': vy[1], 'm': m} + self._wf[head] = info + info['refuse'] = self.waterfall_check(info, ins, index, sources, i, j, k) + return self._wf + + def waterfall_check(self, info, ins, index, sources, i, j, k): + """None when the matched loop is translatable as one pass per lane, else the reason.""" + m, vy = info['m'], info['v'] + body = ins[k + 2:i - 1] + for off, _, name, asm in body: + if WATERFALL_BODY_REFUSED.match(name) or self.exec_written(name, parse(asm)[1]): + return '%s at %#x' % (name, off) + if any(t in ('exec', 'exec_lo', 'exec_hi') for t in parse(asm)[1]): + return 'exec read at %#x (the pass\'s lanes, not one lane)' % off + if off in sources: + return 'branch target %#x inside it' % off + _, w, _, _ = reads_writes(name, asm) + if w & {m, m + 1}: + return 'the remaining-lanes mask s%d written at %#x' % (m, off) + ops = parse(asm)[1] + if name.startswith(('v_', 'buffer_', 'image_', 'global_', 'flat_', 'scratch_')) and ops: + d = reg_range(ops[0]) + if d and d[0] == 'v' and d[1] <= vy <= d[2]: + return 'v%d (the index) written at %#x' % (vy, off) + # before the head: s[m] = exec, and a copy s[a] = exec that the instruction after the loop restores, with + # no exec write and no other way in between + nxt = i + 1 + while nxt < len(ins) and ins[nxt][2] in ('s_nop',): + nxt += 1 + if nxt >= len(ins): + return 'no exec restore after it' + rname, rops = ins[nxt][2], parse(ins[nxt][3])[1] + ar = reg_range(rops[1]) if rname == 's_mov_b64' and len(rops) == 2 and rops[0] == 'exec' else None + if not (ar and ar[0] == 's'): + return 'no s_mov_b64 exec restore after it (%s)' % ins[nxt][3] + a = ar[1] + found = set() + p = j - 1 + while p >= 0 and found != {'m', 'a'}: + off, _, name, asm = ins[p] + ops = parse(asm)[1] + if ins[p + 1][0] in sources and ins[p + 1][0] != info['head']: + return 'branch target %#x between the exec copies and the head' % ins[p + 1][0] + if name == 's_mov_b64' and len(ops) == 2 and ops[1] == 'exec': + r = reg_range(ops[0]) + if r and r[1] == m: + found.add('m') + elif r and r[1] == a: + found.add('a') + p -= 1 + continue + if self.exec_written(name, ops) or name.startswith(('s_cbranch', 's_branch', 's_endpgm')): + return 'exec written or a branch at %#x before the head' % off + _, w, _, _ = reads_writes(name, asm) + if w & {m, m + 1, a, a + 1}: + return 'an exec copy overwritten at %#x' % off + p -= 1 + if found != {'m', 'a'}: + return 'no exec copies before the head' + for off, _, name, asm in ins[j:nxt]: + _, w, _, _ = reads_writes(name, asm) + if w & {a, a + 1}: + return 'the restored copy s%d written at %#x' % (a, off) + # what the body leaves in scalar registers (each lane's own here, the last pass's on the hardware) + written = set() + for off, _, name, asm in ins[k:i - 1]: + _, w, wv, _ = reads_writes(name, asm) + written |= w | ({-1} if wv else set()) + live = self.liveness()[ins[nxt][0]] - {m, m + 1} + hit = written & live + if hit: + return '%s written in it is live after it' % ('vcc' if min(hit) == -1 else 's%d' % min(hit)) + info['restore'] = ins[nxt][0] + return None + + def waterfall_role(self): + """(info, role) of the instruction at self.pc in a waterfall loop, else None.""" + if getattr(self, '_wf_roles', None) is None: + self._wf_roles = {} + for info in self.waterfalls().values(): + for role in ('rfl', 'cmpx', 'wrexec', 'branch'): + self._wf_roles[info[role]] = (info, role) + return self._wf_roles.get(self.pc) + + def waterfall_step(self, info, role, ops): + """The translation of a waterfall instruction; NotImplemented: translate it as any other instruction (a + refused waterfall stays a loop, as before, unless its index is lane-dependent: then the reason is given).""" + if info['refuse']: + if role == 'rfl' and self.lane_dependent('v%d' % info['v']): + raise Unsupported('waterfall loop %#x-%#x: %s' % (info['head'], info['branch'], info['refuse'])) + return NotImplemented + if role == 'rfl': + # this lane's pass: the value is its own (threads with exec 0 compute it too; their body is guarded) + self.set_s(info['s'], self.u(ops[1])) + self.au_scalars.pop(info['s'], None) + return None + if role == 'cmpx': + return None # sX == vY in this lane: exec keeps its bit + if role == 'wrexec': + # the lane's pass is over: s[m] holds no lane any more (all passes done), SCC = 0 + self.set_s(info['m'], '0u', sym=('const', 0)) + self.set_s(info['m'] + 1, '0u', sym=('const', 0)) + self.emit('scc = false;') + self.scc_from.pop('scc', None) + return None + return None # the back edge: no further pass for this lane + + # ---- per-lane loops: a back edge on "some lane still loops" --------------------------------------------- + # The compiler keeps the lanes that still loop in a mask M (LLVM AMDGPU SIAnnotateControlFlow / + # SILowerControlFlow loop lowering; the forms measured in the title's mesh programs): + # M = exec ... H: [exec = M] ... body ... exec &= done; M &= ~exec (s_andn2_b64 M, M, exec) + # s_cbranch_scc1 H; s_mov_b64 exec, saved + # or ... s_and_saveexec_b64 M, leaving; s_andn2_wrexec_b64 M, M (exec = M = the lanes that go on); + # s_cbranch_scc1 H; s_mov_b64 exec, saved + # SCC = M != 0 (RDNA 2 ISA S_ANDN2_B64 / S_ANDN2_WREXEC_B64): the wave loops while some lane does. Each lane + # makes its own iterations: the scalar instructions of an iteration compute the same values whichever lanes + # are on (no exec read but the masks), and a lane that has left runs no vector instruction. So in the + # one-lane model every thread iterates while its own bit of M is set (the SCC it computes), which is exact + # when nothing in the loop crosses lanes and no scalar the loop writes is read after it (the hardware leaves + # the wave's last iteration there, a thread its own). M itself is 0 after the loop on both. + def perlane_loop(self, head, off): + """None when the loop head..off (an scc1 back edge on a lane-mask SCC) is translatable per lane, else the + reason.""" + cache = self.__dict__.setdefault('_perlane', {}) + if off in cache: + return cache[off] + ins = self.ins + index = {x[0]: i for i, x in enumerate(ins)} + i, j = index[off], index.get(head) + why = None + prev = parse(ins[i - 1][3])[1] if i else [] + pname = ins[i - 1][2] if i else '' + if ins[i][2] != 's_cbranch_scc1': + why = '%s back edge' % ins[i][2] + elif not ((pname == 's_andn2_b64' and len(prev) == 3 and prev[0] == prev[1] and prev[2] == 'exec') or + (pname == 's_andn2_wrexec_b64' and len(prev) == 2 and prev[0] == prev[1])): + why = 'SCC not from the remaining-lanes mask (%s)' % ins[i - 1][3] + mr = reg_range(prev[0]) if prev else None + if why is None and not (mr and mr[0] == 's'): + why = 'mask %s' % (prev[0] if prev else '?') + if why is None: + m = mr[1] + written = set() + for o, _, name, asm in ins[j:i + 1]: + ops = parse(asm)[1] + if PERLANE_BODY_REFUSED.match(name): + why = '%s at %#x' % (name, o) + break + # the first active lane differs between a thread's iteration and the wave's: only a translated + # waterfall (each lane's own value) may read one + if name == 'v_readfirstlane_b32' and not any( + info['rfl'] == o and not info['refuse'] for info in self.waterfalls().values()): + why = 'v_readfirstlane_b32 at %#x' % o + break + if name.startswith('s_cbranch') or name == 's_branch': + t = int(ops[0].split('_')[1], 16) + if not head <= t <= off + 4: + why = 'a branch out of the loop at %#x' % o + break + _, w, wv, _ = reads_writes(name, asm) + written |= w | ({-1} if wv else set()) + nxt = i + 1 + restore_at = nxt + corridor_writes = set() + while restore_at < len(ins): + _, _, name, asm = ins[restore_at] + if (name not in ('s_nop', 's_mov_b32', 's_mov_b64', 's_xor_b32', 's_load_dwordx8') + or re.search(r'\b(exec(?:_lo|_hi)?|src_scc)\b', asm)): + break + corridor_writes.update(self.pair_writes(name, asm)) + restore_at += 1 + if why is None: + rops = parse(ins[restore_at][3])[1] if restore_at < len(ins) else [] + ar = reg_range(rops[1]) if (restore_at < len(ins) and ins[restore_at][2] == 's_mov_b64' and len(rops) == 2 + and rops[0] == 'exec') else None + if not (ar and ar[0] == 's'): + why = 'no s_mov_b64 exec restore after it' + elif (written | corridor_writes) & {ar[1], ar[1] + 1}: + why = 'the restored exec copy s%d written before the restore' % ar[1] + if why is None: + hit = written & (self.liveness()[ins[nxt][0]] - {m, m + 1}) + if hit: + stable = self.restored_scalars(head - 1, off, hit) + successors = self.range_successors() + outside, cold = set(), set() + todo = [ins[0][0]] + while todo: + pc = todo.pop() + if head <= pc <= off: + cold.add(pc) + elif pc not in outside: + outside.add(pc) + todo.extend(successors[pc]) + if len(cold) == 1: + stable &= self.restored_scalars(head - 1, off, stable, entry=next(iter(cold)), allow_copy=True) + else: + stable.clear() + hit -= stable + if hit: + why = '%s written in it is live after it' % ('vcc' if min(hit) == -1 else 's%d' % min(hit)) + cache[off] = why + return why + + def branch_targets(self): + if getattr(self, '_targets', None) is None: + self._targets = {int(parse(asm)[1][0].split('_')[1], 16) for _, _, name, asm in self.ins + if name.startswith('s_cbranch') or name == 's_branch'} + return self._targets + + def body(self): + """With barriers: the program runs as barriers + 1 phases, written out one after the other with a group + barrier between them in straight-line code (no barrier inside a loop). barrier_count() put every block in + exactly one phase; within a phase a thread runs its blocks until it reaches a barrier (pc gets + 0x10000 | the block after it) or the end (0x20000). Each console barrier is thus the phase boundary every + wave of the group reaches.""" + if not any(b[2] and b[2][0] == 'barrier' for b in self.blocks): + return super().body() + index = {b[0]: i for i, b in enumerate(self.blocks)} + + def goto(off): + if off not in index: + raise Unsupported('branch into the middle of a block (+0x%x)' % off) + return index[off] + out = [' uint pc = 0;'] + for phase in range(self.barriers + 1): + members = [i for i in range(len(self.blocks)) if self.phase_of.get(i) == phase] + loop = any(t and t[0] in ('jump', 'branch') and goto(t[-1]) <= i + for i in members for t in [self.blocks[i][2]]) + out.append(' // phase %d' % phase) + ind = ' ' + if loop: + out.append(' [loop] for (uint guard = 0; guard < 65536 && pc < 0x10000u; ++guard) {') + ind = ' ' + for k, i in enumerate(members): + off, lines, term = self.blocks[i] + if (loop and not self.padded_phases and term and term[0] in ('jump', 'branch') + and self.phase_of.get(goto(term[-1])) != phase): + # (a group-uniform skip into a later phase: the loop would spin on that pc until its guard) + raise Unsupported('jump from a looping phase into another phase at %#x' % int(off)) + out.append('%s%sif (pc == %d) {' % (ind, 'else ' if loop and k else '', i)) + out += [ind + ' ' + line for line in lines] + last = i + 1 >= len(self.blocks) + nxt = '0x20000u' if last else '%d' % (i + 1) + if not term: + out.append('%s pc = %s;' % (ind, nxt)) + elif term[0] == 'end': + out.append('%s pc = 0x20000u;' % ind) + elif term[0] == 'barrier': + out.append('%s pc = %s;' % (ind, '0x20000u' if last else '0x10000u | %d' % (i + 1))) + elif term[0] == 'jump': + out.append('%s pc = %d;' % (ind, goto(term[1]))) + else: + out.append('%s pc = (%s) ? %d : %s;' % (ind, term[1], goto(term[2]), nxt)) + out.append('%s}' % ind) + if loop: + if self.padded_phases: + # A thread with a PC in a later phase idles until the group gets there. + out.append(' else { break; }') + out.append(' }') + if phase < self.barriers: + out += [' GroupMemoryBarrierWithGroupSync();', + ' if (pc < 0x20000u) pc &= 0xffffu;'] + return out + + def padded_barrier_count(self): + """Schedule each original S_BARRIER at its group-wide ordinal. Between consecutive + original barriers, each static translator publish gets its own phase. A path skipping + a publish executes an empty phase at the corresponding GroupMemoryBarrierWithGroupSync. + """ + blocks = self.blocks + index = {off: i for i, (off, _, _) in enumerate(blocks)} + console = {i for i, (_, _, term) in enumerate(blocks) if term and term[:2] == ('barrier', 'console')} + added = {i for i, (_, _, term) in enumerate(blocks) if term and term[0] == 'barrier' and i not in console} + barriers = console | added + ordinal = {0: 0} + pending = [0] + exits = set() + while pending: + i = pending.pop() + term = blocks[i][2] + after = ordinal[i] + (i in console) + successors = [] + if (not term or term[0] not in ('jump', 'end')) and i + 1 < len(blocks): + successors.append(i + 1) + if term and term[0] in ('jump', 'branch'): + target = index[term[-1]] + if target <= i and any(target <= site <= i for site in barriers): + raise Unsupported('a loop crosses a synchronization point') + successors.append(target) + if not successors: + exits.add(after) + for dst in successors: + if dst not in ordinal: + ordinal[dst] = after + pending.append(dst) + elif ordinal[dst] != after: + raise Unsupported('paths with different console barrier counts meet at %#x' % blocks[dst][0]) + if len(exits) != 1: + raise Unsupported('paths end after different numbers of console barriers') + total_console, = exits + self.phase_of = {} + phase = 0 + for n in range(total_console + 1): + sites = sorted(i for i in added if ordinal.get(i) == n) + for i, before in ordinal.items(): + if before == n: + self.phase_of[i] = phase + (len(sites) if i in console else sum(site < i for site in sites)) + phase += len(sites) + (n < total_console) + return phase + + def barrier_count(self): + """Every path from the entry to s_endpgm must cross the same number of barriers (the hardware needs every + wave to arrive at each barrier). Returns that number; the body runs as that many + 1 phases.""" + blocks = self.blocks + index = {b[0]: i for i, b in enumerate(blocks)} + memo = {} + cmemo = {} + + def console(i, depth=0): + """Sorted counts of console barriers (not lane-mask SCC publishes) from block i to the end.""" + if i in cmemo: + return cmemo[i] + if depth > 10000: + raise Unsupported('block graph too deep') + cmemo[i] = () + off, lines, term = blocks[i] + # only the program's s_barrier: the translation's own barriers (lane-mask SCC publish, readfirstlane + # broadcast, group-branch publish) are reached or skipped by the whole group together + here = 1 if term and term[0] == 'barrier' and term[1:2] == ('console',) and SKIP_ADDED else 0 + if term and term[0] == 'barrier' and not SKIP_ADDED and term[1:2] != ('lane-scc',): + here = 1 + nxt = [i + 1] if (term is None or term[0] in ('barrier', 'branch')) and i + 1 < len(blocks) else [] + if term and term[0] in ('jump', 'branch'): + if term[0] == 'jump': + nxt = [] + if term[-1] > off: + nxt.append(index[term[-1]]) + got = sorted({here + c for k in nxt for c in console(k, depth + 1)}) if nxt else [here] + cmemo[i] = tuple(got) + return cmemo[i] + + def counts(i, depth=0): + if i in memo: + return memo[i] + if depth > 10000: + raise Unsupported('block graph too deep') + off, lines, term = blocks[i] + here = 1 if term and term[0] == 'barrier' else 0 + if off in self.uniform_skips: + # group-uniform skip of an execz range (group_branch): every thread of the group goes the same + # way, so the skip may jump over barriers inside the range (body() runs the target in its later + # phase; the threads still pass every phase barrier in between, doing nothing) + through, skip = counts(i + 1, depth + 1), counts(index[term[-1]], depth + 1) + if len(through) != 1 or len(skip) != 1 or min(skip) > min(through): + raise UnevenBarrierPaths('group-uniform execz range at %#x: barrier counts %s / %s' + % (int(off), sorted(through), sorted(skip))) + # only barriers this translation added (lane-mask SCC publishes) may be skipped: a console + # s_barrier inside the range would be skipped by a wave without active lanes on the hardware + if console(i + 1) != console(index[term[-1]]): + raise Unsupported('s_barrier inside a group-uniform execz range at %#x (console barriers ahead %s ' + 'through, %s skipping)' % (int(off), list(console(i + 1)), + list(console(index[term[-1]])))) + memo[i] = through + return through + nxt = [] + if term is None or term[0] in ('barrier', 'branch'): + if i + 1 < len(blocks): + nxt.append(i + 1) + if term and term[0] in ('jump', 'branch'): + if term[-1] <= off: + if any(blocks[k][2] and blocks[k][2][0] == 'barrier' for k in range(index[term[-1]], i + 1)): + raise Unsupported('barrier inside a loop') + nxt = [k for k in nxt if k != index[term[-1]]] # loop back edge: counted once + else: + nxt.append(index[term[-1]]) + result = set() + for k in nxt: + result |= {here + c for c in counts(k, depth + 1)} + if not nxt: + result = {here} + memo[i] = result + return result + found = counts(0) + if len(found) != 1: + raise UnevenBarrierPaths('paths cross different numbers of barriers: %s' % sorted(found)) + total = min(found) + # Every reachable block then has one count of barriers still ahead (two would give two totals), so it runs + # in exactly one phase: total - that count. + self.phase_of = {} + for i, c in memo.items(): + if len(c) != 1: + raise UnevenBarrierPaths('block %#x reaches the end across different numbers of barriers' % blocks[i][0]) + self.phase_of[i] = total - min(c) + return total + + # ---- entry --------------------------------------------------------------------------------- + def setup_entry(self): + root = self.pipe.root + reg = self.pipe.user_sgpr + for index, p in enumerate(root['params']): + if p['type'] == 0: + self.sym[reg] = ('ptr', ('table', index)) + reg += 1 + elif p['type'] == 1: + for i in range(p['count']): + self.sym[reg] = ('ud', self.pipe.ud(('rootconst', index, i))) + reg += 1 + else: + self.sym[reg] = ('ptr', ('root', index)) + self.sym[reg + 1] = ('ptrhi', ('root', index)) + reg += 2 + if root['flags'] & 0x400: + self.sym[reg] = ('ptr', ('resheap',)) + reg += 1 + if root['flags'] & 0x800: + self.sym[reg] = ('ptr', ('smpheap',)) + reg += 1 + self.user_end = reg + # s3: merged_wave_info (bits 27:24 = wave index in the group, Mesa radv_shader_args.c / ac_unpack_param). + self.sym[3] = ('waveinfo',) + + # ---- taint (lane dependence) --------------------------------------------------------------- + # Three levels per register: uniform (not in `tainted`: the same in every lane of the wave), active-uniform + # (in `tainted` and au[reg] == epoch: the same in every lane active since the last widening of exec; e.g. a + # value computed from uniform values under a partial exec, or `exec & uniform`), and lane-dependent. + # `epoch` counts exec writes that can turn lanes back on (restores); narrowing writes (v_cmpx, `exec & x`, any + # write while every lane was active) keep active-uniform values valid. + def emit(self, text): + self.lines.append(text) + for stmt in text.split(';'): + m = SIMPLE.match(stmt) + if not m: + continue + target, expr = m.group(1), m.group(2) + deps = set(TOKEN.findall(expr)) + if stmt.strip().startswith('if (exec & 1)'): + deps.add('exec') + origins = frozenset().union(*(self.scc_from.get(d, ()) for d in deps)) + if stmt.strip().startswith('if '): + origins |= self.scc_from.get(target, frozenset()) # a guarded write keeps the old value elsewhere + if origins: + self.scc_from[target] = origins + else: + self.scc_from.pop(target, None) + if target == 'exec': + narrow = expr.startswith('(exec & ') or getattr(self, '_known_at_start', True) + if not narrow: + self.epoch += 1 + self.xs = self.lineage_exec(expr) + self._xs_exec_seen = True + elif self.LINEAGE_COPY.match(expr.strip()) and not stmt.strip().startswith('if '): + self.xs_copy[target] = self.xs + else: + self.xs_copy.pop(target, None) + # (a scalar computed inside a per-lane region from uniform values is what the wave computes there: the + # lanes that skip the region never see it, and check_skipped_scalars refuses it being live after) + if not deps & self.tainted: + self.tainted.discard(target) + self.au.pop(target, None) + self.au_xs.pop(target, None) + continue + # (the sources as they were before this statement: `s12 = scc ? s12 : s24` reads the old, untainted s12) + lane = {d for d in deps & self.tainted + if d != 'exec' and self.au.get(d) != self.epoch and not self.lineage_ok(d)} + self.tainted.add(target) + if lane or target == 'exec': + self.au.pop(target, None) + self.au_xs.pop(target, None) + else: + self.au[target] = self.epoch + self.xs_serial += 1 + self.au_xs[target] = (self.xs, self.xs_serial) + + def is_tainted(self, expr): + return bool(set(TOKEN.findall(expr)) & self.tainted) + + def lane_dependent(self, name): + """Neither uniform nor uniform over the active lanes.""" + return name in self.tainted and self.au.get(name) != self.epoch and not self.lineage_ok(name) + + # ---- exec lineage ------------------------------------------------------------------------------ + # The epoch rule above forgets every active-uniform value at the first exec write that may widen exec. The + # compiler's usual shape restores a SAVED exec instead: `s[26:27] = exec ... exec = s26 & x (narrow) ... exec = + # s26 (restore) ... exec = s26 & y`. A value written from uniform values under E is the same in every lane of E; + # every later exec that is E or a subset of E (a narrowing of E or of a restore of E) has only such lanes active. + # States: 0 at entry (all lanes), a child per narrowing, the saved state per restore of an unchanged copy, a + # fresh root for any other exec write, at loop heads, and where joined paths have no common ancestor. + def lineage_new(self, parent): + n = len(self.xs_parent) + self.xs_parent[n] = parent + return n + + def lineage_reset(self): + self.xs = self.lineage_new(None) + self.au_xs, self.xs_copy = {}, {} + + def lineage_chain(self, x): + out = [] + while x is not None: + out.append(x) + x = self.xs_parent.get(x) # (a loop seed's state from an earlier pass: loop_join resets after it) + return out + + def lineage_ok(self, name): + """name's active-uniform value was written under the current exec state or an ancestor of it.""" + got = self.au_xs.get(name) if EXEC_LINEAGE else None + return got is not None and got[0] in self.lineage_chain(self.xs) + + LINEAGE_COPY = re.compile(r'^\(?exec\)?(?: & 1)?$') + LINEAGE_INNER = re.compile(r'^\((.+)\) & 1$') + + def lineage_exec(self, expr): + """The exec state after `exec = expr` (the one-lane forms: `(s26) & 1`, `(s18 & exec) & 1`, + `(exec & xsave) & 1`, `(s18 & ~exec) & 1`).""" + e = expr.strip() + m = self.LINEAGE_INNER.match(e) + terms = [t.strip() for t in m.group(1).split(' & ')] if m else [e] + if len(terms) == 1 and terms[0] in self.xs_copy: + return self.xs_copy[terms[0]] # a restore of an unchanged copy + if len(terms) >= 2 and all(re.fullmatch(r'~?\w+', t) for t in terms): + if 'exec' in terms: + return self.lineage_new(self.xs) # exec & x: a narrowing of the current state + for t in terms: + if t in self.xs_copy: + return self.lineage_new(self.xs_copy[t]) # copy & x (x may be ~exec): inside the copy's lanes + return self.lineage_new(None) + + def lineage_merge(self, states): + """Join of the lineage fields (xs, au_xs, xs_copy) of the incoming paths.""" + chains = [self.lineage_chain(s[0]) for s in states] + common = [x for x in chains[0] if all(x in c for c in chains[1:])] + self.xs = common[0] if common else self.lineage_new(None) + first = states[0] + self.xs_copy = {r: v for r, v in first[2].items() if all(s[2].get(r) == v for s in states)} + self.au_xs = {r: v for r, v in first[1].items() if all(s[1].get(r) == v for s in states)} + + # ---- instructions -------------------------------------------------------------------------- + def one(self, name, asm): + """one_body, plus the lane-mask SCC provenance (scc_from) carried along branch edges: the scan is linear, + so a branch target gets the union of the states at the branches to it (and at its fall-through when the + previous instruction falls through). Backward edges are not followed (a missed origin only refuses).""" + if self.pc in self.join_from: + saved = self.join_from.pop(self.pc) + if self.fell_off: + self.scc_from = dict(saved) + else: + for k, v in saved.items(): + self.scc_from[k] = self.scc_from.get(k, frozenset()) | v + self._xs_exec_seen = False + self._dw_keep = set() + before = len(self.lines) + term = self.one_body(name, asm) + if 'descword' in MESH_FEATURES: + # an SGPR this instruction wrote other than by an in-place descriptor edit (dw_mark_edit) holds a new value + for r in G.sgpr_access(name, asm)[1] - self._dw_keep: + self.sym.pop(self.dw_edit_key(r), None) + if term and term[0] == 'branch' and self.is_tainted(term[1]): + self.lane_edges.add(id(term)) + if not self._xs_exec_seen and (self.exec_written(name, parse(asm)[1]) or + any(re.search(r'exec = ', l) for l in self.lines[before:])): + self.xs = self.lineage_new(None) # an exec write emit() did not see: no lineage across it + self.fell_off = bool(term) and term[0] in ('jump', 'end') + target = None + if term and term[0] in ('jump', 'branch'): + target = term[-1] + elif term and term[0] == 'barrier' and len(term) > 3: + target = term[3] # group-uniform execz: the skip edge + if target is not None and target > self.pc: + into = self.join_from.setdefault(target, {}) + for k, v in self.scc_from.items(): + into[k] = into.get(k, frozenset()) | v + return term + + def one_body(self, name, asm): + _, ops, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', name) + if self.pending: + self.lines.extend(self.pending) + self.pending = [] + if base == 's_cbranch_execz': + self._execz_edge = True # the snapshot of this branch's taken edge (base translate) is an execz edge + if self.pc in self.loop_heads(): + self.exec_off = set() + for r, before, at in self.group_checks.get(self.pc, ()): + # A merge that left ('conflict',) is refused by any later use (exec_off_use: an exec-masked mask op + # excepted), so only another change is refused here. + if self.sym.get(r) != before and not (EXEC_OFF and self.sym.get(r) == ('conflict',)): + raise Unsupported('execz range %#x-%#x changes s%d from %s to %s' % (at, self.pc, r, before[0], self.sym.get(r))) + if self.pc in self.branch_targets(): + self.shadow.clear() # another path may arrive here without the shadow assignments + if self.pc >= self.divergent_until or self.pc in self.loop_heads(): + self.running_active = False + if self.pc in self.loop_heads(): + # the linear scan reaches a loop head with the state from before the loop; a later iteration can + # arrive with any exec + self.exec_static = None + self.static_copies.clear() + self.lineage_reset() # a back edge may arrive with any exec + # the base marks s0..s127 lane-suspect at a loop head; spill slots are scalars too + self.lane_s |= self.spill_slots + if base in ('s_waitcnt_depctr',): + return None + if base.startswith('s_cbranch_exec') and self.exec_static is not None: + # exec is a known mask (the same in every wave): the wave-level branch is decided here + taken = (self.exec_static == 0) == (base == 's_cbranch_execz') + return ('jump', int(ops[0].split('_')[1], 16)) if taken else None + if base.startswith('ds_'): + return self.lds(base, ops, mods) + if base in FUSED or base in UNFUSED: + # the multiply-add rule at FMA_MODE: fused ops exact (x2w_fma) or precise; unfused ops always precise + arity, _ = G.VEC_F[base] + args = [self.f(o) for o in ops[1:1 + arity]] + if base in ('v_fmac_f32', 'v_mac_f32'): + args.append(self.f(ops[0])) + helper = 'x2w_fma' if base in FUSED and EXACT_FMA else 'x2w_madp' + return self.set_vf(reg_range(ops[0])[1], '%s(%s, %s, %s)' % ((helper,) + tuple(args)), mods) + if base == 's_sendmsg': + if ops != ['0x9']: + raise Unsupported('s_sendmsg %s' % ops) + self.alloc_seen = True + if self.au_scalars.get('m0', self.epoch) != self.epoch: + raise Unsupported('m0 (from v_readfirstlane under a partial exec) sent after exec was widened') + # Wave-level message: the wave sends it when it reaches it. Lanes active here all hold the same m0. + self.emit('if (exec & 1) x2w_alloc = m0;') + self.alloc_guarded = True + return None + if base == 's_barrier': + if not self.has_lds: + # A barrier orders LDS (and memory) traffic between the waves; a program without LDS instructions + # writes nothing another wave reads here (the archive form's barriers sit in per-lane regions + # around the allocation, which the one-lane model could not place anyway) + return None + # s_barrier runs whatever exec is; a lane that skipped it per lane would arrive at a different one + if self.pc < self.divergent_until: + raise Unsupported('s_barrier inside a per-lane skipped range at %#x' % self.pc) + self.lds_written_in_phase = False + return ('barrier', 'console') # the program's own barrier (others are added by the translation) + if base in ('s_waitcnt_vmcnt', 's_waitcnt_lgkmcnt', 's_waitcnt_expcnt', 's_waitcnt_vscnt'): + return None + # Every scalar destination stops being a lane mask unless the handler marks it again (the base + # translator only updates the mask set in its ALU paths, so a load into a former mask register kept + # the mark and a later s_or of it was cut to bit 0). + reads, writes, _, _ = reads_writes(name, asm) + masks_before = set(self.masks) + for r in writes: + if isinstance(r, int): + # a copy is named by its low SGPR: a write to either half ends it (a copy this instruction makes is + # entered again by emit) + self.xs_copy.pop('s%d' % r, None) + self.xs_copy.pop('s%d' % (r - 1), None) + self.masks -= writes + if base == 's_sendmsg' or 'm0' in ops[1:]: + reads = reads | {'m0'} + if ops and ops[0] == 'm0': + writes = writes | {'m0'} + # A scalar read from the first active lane while some lanes were off holds, in the one-lane model, each + # lane's own value: right in the lanes that were active, stale in the others. Once exec has been widened + # those other lanes run again, so such a register must not be read any more. + stale = [r for r in reads if r in self.au_scalars and self.au_scalars[r] != self.epoch] + if stale: + raise NeedFirstValue(stale[0], self.pc) + derived = any(r in self.au_scalars for r in reads) + for r in writes: + if derived and base.startswith('s_'): + self.au_scalars[r] = self.epoch # computed from such a value: the same caveat + else: + self.au_scalars.pop(r, None) + self._known_at_start = self.exec_known + self._static_set = False + for r in writes: + self.static_copies.pop(r, None) + if isinstance(r, int): + self.static_copies.pop(r - 1, None) # the high half of a 64-bit copy + role = self.waterfall_role() + if role is not None: + term = self.waterfall_step(role[0], role[1], ops) + if term is not NotImplemented: + return term + before = len(self.lines) + term = super().one(name, asm) + if self.exec_written(name, ops) or any(re.search(r'\bexec = ', l) for l in self.lines[before:]): + self.exec_off = set() # lanes may have been turned on: an exec-off register is plain conflict again + if not self._static_set and (self.exec_written(name, ops) or + any(re.search(r'\bexec = ', l) for l in self.lines[before:])): + self.exec_static = None # exec changed in a way not modelled as a constant mask + if self.exec_written(name, ops) or any(re.search(r'\bexec = ', l) for l in self.lines[before:]): + self.running_active = False # threads with exec 0 may run on from here + mask_read = any(t in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or (reg_range(t) and reg_range(t)[0] == 's' and + reg_range(t)[1] in masks_before) + for t in ops[1:]) + if self.mask_scc(base, ops, masks_before, self.lines[before:]): + self.scc_from['scc'] = frozenset([self.pc]) + if re.match(r's_and_b(32|64)$', base) and ('exec' in ops[1:] or 'exec_lo' in ops[1:]): + self.scc_confined.add(self.pc) # result inside the active lanes (see the per-lane shortcut below) + if self.pc in getattr(self.pipe, 'scc_publish', ()): + if term is not None: + raise Unsupported('lane-mask SCC at %#x ends a block' % self.pc) + return self.lane_scc() + elif (base.startswith('s_') and mask_read and 'scc' in self.tainted + and any(re.search(r'\bscc = ', l) for l in self.lines[before:])): + # SCC of a non-mask SALU op on a lane mask (e.g. s_lshl_b32 of vcc_lo): the one-lane bit has no + # per-wave rule here (an OR of the threads' results is not the op on the 64-bit mask): origin -(pc+1) + self.scc_from['scc'] = frozenset([-(self.pc + 1)]) + if term and term[0] == 'branch': + cond = term[1] + off = self.pc + target = term[2] + per_lane = base[10:] in ('execz', 'execnz', 'vccz', 'vccnz') + lane_cond = self.is_tainted(cond) + if base[10:] in ('scc0', 'scc1') and lane_cond: + tokens = TOKEN.findall(cond) + origins = frozenset().union(*(self.scc_from.get(d, ()) for d in tokens)) + # with lanes off, a lane-mask SCC is the active lanes' value only when its mask result was confined + # to them (`x & exec`): `saved & ~exec` has 0 in every active lane and the wave's SCC is 1 + confined = self.exec_known or origins <= self.scc_confined or not CONFINED_SCC + if (LANE_SCC and not any(self.lane_dependent(t) for t in tokens) + and (self.exec_known or self.running_active) and confined): + # SCC the same in every active lane (e.g. `vcc & exec` with vcc from a uniform compare), and + # every thread that runs here is an active lane (all lanes on, or right inside a per-lane + # skipped range with no exec write since): each thread's SCC is the wave's, so the per-lane + # branch is the wave's branch + return term + if target <= off and PERLANE_LOOPS: + why = self.perlane_loop(target, off) + if why is None: + return term # per-lane loop: each thread iterates until its own lane leaves + raise Unsupported('per-lane loop %#x-%#x: %s' % (target, off, why)) + raise LaneScc('branch on an SCC that depends on lane masks at %#x' % off, origins) + if per_lane and lane_cond: + if target <= off: + raise Unsupported('per-lane loop branch %s at %#x' % (base, off)) + # vcc must be the same in every active lane (vcc = exec & uniform): inactive lanes then read 0 and + # take the branch the way execz would, which the skipped-range check below covers + if base[10:] in ('vccz', 'vccnz') and (self.lane_dependent('vcc') or self.pipe.wave_vcc): + if off < self.divergent_until: + ranges = [o for o, t in self.execz_ranges() if o < off < t and o not in self.group_branches()] + if self.pipe.wave_vcc and ranges: + raise NeedGroupRange(max(ranges), 'VCC vote at %#x needs full-wave participation' % off) + raise Unsupported('%s on a lane-dependent vcc at %#x' % (base, off)) + if len(self.scc_any) >= GROUP // 2: + raise Unsupported('no shared VCC vote slots left at %#x' % off) + k = len(self.scc_any) + self.scc_any.append(off) + self.emit('if (vcc & 1u) InterlockedOr(x2w_sany[%d][wave], 1u);' % k) + cond = 'x2w_sany[%d][wave] %s 0u' % (k, '==' if base.endswith('vccz') else '!=') + self.vcc_votes.add(cond) + self.running_active = False + return ('branch', cond, target) + if base == 's_cbranch_execz' and off in self.group_branches(): + return self.group_branch(off, target) + self.check_skipped_scalars(off, target) + self.divergent_until = max(self.divergent_until, target) + if base == 's_cbranch_execz': + self.running_active = True # the threads that go on are exactly the active lanes + elif base[10:] in ('execnz', 'vccnz'): + self.running_active = False # the threads that go on may be inactive lanes + return term + + def group_branch(self, off, target): + """s_cbranch_execz over a range that writes a scalar live at its end (or encloses such a range). + + Per lane, the lanes that skip would keep the old scalar where the wave computed a new one. Instead every + lane publishes its exec bit (x2w_any[k][wave]), a group barrier follows, and the range is skipped only when + no lane of the GROUP is active; otherwise all 128 threads run it, the inactive lanes with exec 0 (vector + writes, exports, LDS and buffer stores stay guarded by exec; inner per-lane branches still skip per lane). + A whole wave with no active lane (which the hardware skips) then gets back, at the end of the range, the + values the hit scalars had before it. Because every thread of the group runs the range, barriers inside + it are allowed. Refused: exec writes the per-lane model cannot follow (as before), the branch inside a + per-lane range, a hit scalar holding a descriptor before the range, and other ways into the target.""" + if off < self.divergent_until or self.exec_known or self.pending: + raise Unsupported('group-uniform execz at %#x inside a per-lane range' % off) + hits = self.skipped_scalars(off, target) + restore = [] + # the end may also be reached by other branches: only a lane that came through this branch restores + # (x2w_u<seen> = 1 here, cleared at the end) + seen = 'x2w_u%d' % len(self.shadow_vars) + self.shadow_vars.append(seen) + k = len(self.wave_any) + self.wave_any.append(off) + for r in sorted(hits): + reg = 'vcc' if r == -1 else 's%d' % r + if r != -1 and r not in self.sym and r not in self.used_s: + continue # no value before the range: a wave that skips it reads an undefined register + before = self.sym.get(r) if r != -1 else None + if before is not None and before[0] not in ('const', 'fixed_buffer_word'): + # a symbolic value (descriptor, pointer): no run-time copy exists. Right only when the range leaves + # the same symbolic value (a reload of the same descriptor): checked at the target. + self.group_checks.setdefault(target, []).append((r, before, off)) + continue + try: + value = self.u(reg) + except Unsupported: + raise Unsupported('execz range %#x-%#x writes %s, which holds %s before it' % (off, target, reg, before)) + var = 'x2w_u%d' % len(self.shadow_vars) + self.shadow_vars.append(var) + self.emit('%s = %s;' % (var, value)) + if r != -1: + self.used_s.add(r) + restore.append('if (%s != 0u && x2w_any[%d][wave] == 0u) %s = %s;' % (seen, k, reg, var)) + if restore: + self.emit('%s = 1u;' % seen) + restore.append('%s = 0u;' % seen) + self.emit('if (exec & 1) x2w_any[%d][wave] = 1u;' % k) + if 'restore' not in TEST_DROP: + self.group_restore.setdefault(target, []).extend(restore) + return ('barrier', 'wave-branch', k, target) + + MASK_OPS = ('and', 'or', 'xor', 'andn2', 'orn2', 'nand', 'nor', 'xnor', 'not') + + def mask_scc(self, base, ops, masks_before, lines): + """The SALU instruction just translated set SCC from a lane mask, lane-dependently: SCC = (64-bit result + != 0) is one bit for the whole wave (RDNA 2 ISA: S_AND_B64 etc. "SCC = (D != 0)"; S_*_SAVEEXEC_B64 + "SCC = (EXEC != 0)"), while the one-lane model computed it from this lane's bit only.""" + if not base.startswith('s_') or not any(re.search(r'\bscc = ', l) for l in lines): + return False + if 'scc' not in self.tainted: + return False + if 'saveexec' in base or 'wrexec' in base: + return True + if base.split('_')[1] not in self.MASK_OPS: + return False + for t in ops[1:]: + r = reg_range(t) + if t in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or (r and r[0] == 's' and r[1] in masks_before): + return True + return False + + def lane_scc(self): + """Publish the wave's SCC of a lane-mask instruction: every thread whose bit of the result is set marks + x2w_sany[k][wave], a group barrier follows (a phase boundary, as the readfirstlane broadcast), and the next + block starts with scc = the wave's value, which is then the same in every lane of the wave (not tainted). + Inactive lanes take part with their own bits: in a group-uniform execz range they run with exec 0, so a + result masked with exec has 0 there, as on the hardware. Every thread of the group must reach the barrier: + refused inside a per-lane skipped range, before a branch target, and (barrier_count) inside loops or on one + side of a branch only.""" + if self.pc < self.divergent_until: + raise Unsupported('lane-mask SCC at %#x inside a per-lane skipped range' % self.pc) + if self.pending: + raise Unsupported('lane-mask SCC at %#x right after a broadcast' % self.pc) + if self.next_offset() in self.branch_targets(): + raise Unsupported('lane-mask SCC at %#x followed by a branch target' % self.pc) + self.scc_from.pop('scc', None) + self.tainted.discard('scc') + self.au.pop('scc', None) + self.au_xs.pop('scc', None) + if 'publish' in TEST_DROP: + return None # negative control: the lane's own bit is taken as the wave's SCC + k = len(self.scc_any) + if 2 * (k + 1) > GROUP: + raise Unsupported('more than %d lane-mask SCCs (the slots are cleared by one thread each)' % (GROUP // 2)) + self.scc_any.append(self.pc) + self.lines.append('if (scc) x2w_sany[%d][wave] = 1u;' % k) + self.pending.append('scc = x2w_sany[%d][wave] != 0u;' % k) + self.lds_written_in_phase = False + return ('barrier', 'lane-scc') + + @staticmethod + def exec_written(name, ops): + base = re.sub(r'_e(32|64)$', '', name) + return ('saveexec' in base or 'wrexec' in base or base.startswith('v_cmpx') or + (base.startswith('s_') and ops and ops[0] in ('exec', 'exec_lo'))) + + def exec_mask_expr(self, mask): + """This lane's bit of a constant 64-bit exec mask.""" + lo, hi = mask & 0xffffffff, mask >> 32 + if hi == 0 and lo == 1: + return '(lane == 0u ? 1u : 0u)' + return '((lane < 32u ? (0x%08xu >> lane) : (0x%08xu >> (lane - 32u))) & 1u)' % (lo, hi) + + def set_v(self, n, expr, *, low16_only=False): + # Shadow: under a constant partial exec, a value computed only from wave-uniform inputs is also kept in an + # unguarded variable, so a later v_readfirstlane can read it although the HLSL thread's lane was off + # (the hardware reads the first active lane, which held that same value if it was active at the write). + sub = expr + if self.exec_static is not None and not self.exec_known: + for v in set(re.findall(r'\bv(\d+)\b', expr)): + if int(v) in self.shadow: + sub = re.sub(r'\bv%s\b' % v, self.shadow[int(v)][0], sub) + super().set_v(n, expr, low16_only=low16_only) + self.shadow.pop(n, None) + if self.exec_static is None or self.exec_known or self.exec_static == 0: + return + if set(TOKEN.findall(sub)) & (self.tainted | {'exec', 'lane', 'tid'}): + return + var = 'x2w_u%d' % len(self.shadow_vars) + self.shadow_vars.append(var) + self.lines.append('%s = %s;' % (var, sub)) + self.shadow[n] = (var, self.exec_static) + + def declarations(self): + lines = super().declarations() + for (offset, size), name in self.literal_tables.items(): + words = struct.unpack_from('<%dI' % (size // 4), self.raw, offset) + values = ', '.join('0x%08xu' % word for word in words) + lines.append(' static const uint %s[%d] = {%s};' % (name, len(words), values)) + if self.shadow_vars: + lines.append(' uint %s;' % ', '.join('%s = 0' % v for v in self.shadow_vars)) + return lines + + def snapshot(self): + snap = super().snapshot() + ((self.xs, dict(self.au_xs), dict(self.xs_copy)), + self.exec_static, dict(self.static_copies)) + if JOIN_TAINT: + snap += (frozenset(self.tainted), dict(self.au), self.epoch) + if self._execz_edge: + self._execz_edge = False + self._execz_snaps.append(snap) + return snap + + def merge(self, states): + # edges from code no path reaches in this loop pass (loop_one) do not count, unless all are + states = [s for s in states if BOTTOM not in s[0]] or states + dw_join = {} + if 'descword' in MESH_FEATURES: + # a value computed from table descriptor words on some path, where the paths disagree: when every path + # holds a run-time number there (None / RUNTIME_BACKED), the join is a run-time number that may depend on + # those words: ('dwnum', union), marked used only by a later numeric read. Otherwise (a conflict, which an + # exec-off read may still take as its variable) the words are needed now (conservative). + for reg in set().union(*(s[0] for s in states)): + values = [s[0].get(reg) for s in states] + if all(v == values[0] for v in values) or not any(v and v[0] == 'dwnum' for v in values): + continue + deps = frozenset().union(*(v[1] for v in values if v and v[0] == 'dwnum')) + if all(v is None or v[0] in self.RUNTIME_BACKED for v in values): + dw_join[reg] = ('dwnum', deps) + else: + self.dw_use(deps) + n_base = len(G.Stage.snapshot(self)) + super().merge(states) + self.sym.update(dw_join) + self.lineage_merge([s[n_base] for s in states]) # right after the base fields + # the mesh fields are the last ones of the snapshot, whatever the base snapshot holds before them + n = 5 if JOIN_TAINT else 2 + statics = [s[-n] for s in states] + self.exec_static = statics[0] if all(x == statics[0] for x in statics) else None + copies = [s[-n + 1] for s in states] + self.static_copies = {r: m for r, m in copies[0].items() if all(c.get(r) == m for c in copies)} + if JOIN_TAINT: + # Taint at a join of forward edges (the base merges only its own fields; the linear scan otherwise kept + # the state of the instruction above, which after an unconditional jump is no incoming path at all): + # tainted on any incoming path; active-uniform only where every path that taints the register has it + # active-uniform at the current epoch (no exec widening the linear scan saw since that branch). + self.tainted = set().union(*(s[-3] for s in states)) + au = {} + for r in self.tainted: + if all(r not in s[-3] or (s[-2].get(r) == s[-1] == self.epoch) for s in states): + au[r] = self.epoch + self.au = au + self.merge_exec_off(states) + + def merge_exec_off(self, states): + """Registers that the merge made ('conflict',) only because of taken s_cbranch_execz edges. + + A lane takes an execz edge only with its exec bit 0 (per lane: `(exec & 1) == 0`; group-uniform: no lane of + the group active), so on those paths the lane's bit is 0 at the join; every other path assigned the + register at run time. The run programs use this for a lane mask merged after a divergent if (v_cmp_e64 + into a reused SGPR inside the range, then `s_nand_b64 / s_orn2_b64 sX, sX, exec` after it; INFERRED to be the + compiler's i1 phi, whose skipped side is undefined). Until exec is written again + (exec_off_use), a mask op whose lane bit does not depend on the register when exec is 0 may read its HLSL + variable.""" + self.exec_off = set() + if not EXEC_OFF: + return + backed = self.RUNTIME_BACKED + for reg, value in self.sym.items(): + if value != ('conflict',): + continue + bad = [s for s in states if s[0].get(reg) is not None and s[0].get(reg)[0] not in backed] + if bad and len(bad) < len(states) and all(any(s is e for e in self._execz_snaps) for s in bad): + self.exec_off.add(reg) + + def exec_off_use(self, base, ops): + """Exec-off conflict registers (merge_exec_off) a 64-bit mask op may read: the op takes exec as the other + operand and its lane bit is the same for both values of the register's bit when the lane's exec bit is 0 + (s_and X, exec = 0; s_nand = 1; s_andn2 exec, X = 0; s_orn2 X, exec = 1). Empty when it does not apply.""" + if not self.exec_off or base not in G.SCA or len(ops) != 3 or not base.endswith('_b64'): + return set() + srcs = ops[1:] + if 'exec' not in srcs: + return set() + k = 1 - srcs.index('exec') + r = reg_range(srcs[k]) + if not r or r[0] != 's' or r[1] not in self.exec_off or self.sym.get(r[1]) != ('conflict',): + return set() + text = G.SCA[base][0] + if '{2}' in text or not re.fullmatch(r'[~(){}01&|^ ]+', text): + return set() + bits = set() + for x in (0, 1): + args = ['0', '0'] + args[k] = str(x) + bits.add(eval(text.format(*args)) & 1) # noqa: S307 (a fixed SCA formula over two constant bits) + return {r[1]} if len(bits) == 1 else set() + + def format_load(self, ops, mods, count, name): + """buffer_load_format_* through a resource-heap descriptor (X2W_DRAW_FEATURES heap + bufword3): the format + and swizzle come from the view's word 3 (x2w_hword, X2W_MESH_FEATURES=heapwords); table descriptors take + the base path.""" + key = self.descriptor(ops[2]) + if key[0][0] != 'heapdyn': + return super().format_load(ops, mods, count, name) + if not {'heap', 'bufword3'} <= set(getattr(self.pipe, 'features', ())) or 'heapwords' not in MESH_FEATURES: + raise Unsupported('%s through heapdyn' % name) + self.pipe.heapwords = True + for m in mods: + if not (m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:')): + raise Unsupported('%s modifier %s' % (name, m)) + dst = reg_range(ops[0]) + buf, address = self.buffer_address(ops, mods) + self.emit('a = %s;' % address) + for i in range(count): + self.set_v(dst[1] + i, 'x2w_fmt_load(%s, a, x2w_hword(h%d, 3u), %du)' % (buf, key[0][1], i)) + + # ---- table descriptor words read as numbers (X2W_MESH_FEATURES=descword) --------------------------------------- + # A word of a descriptor loaded from a root descriptor TABLE (('desc', ('table', p), off, w)) is known only at draw + # time: the runtime passes it as entry value `udsrc <n> descword <p> <off + 4 w>` (d3d12_draw.inl draw_descword_value: + # the title's dword, or the synthesized T# / V# word of a view token, as compute's descword). Scalar arithmetic over + # such words is emitted with a placeholder X2W_DW<k> per word and the result register holds ('dwnum', {k, ...}) + # (a run-time number). Only a numeric use (S(), or a join where paths disagree) marks its words used; build() + # then makes used placeholders entry values and the others 0u (their arithmetic is dead code, as before: a V# + # NUM_RECORDS x STRIDE bounds computation nobody reads adds no entry value). + RUNTIME_BACKED = G.Stage.RUNTIME_BACKED + ('dwnum',) + + @staticmethod + def dw_edit_key(n): + return 'x2w_dwedit_%d' % n # key in the symbolic state (snapshotted and merged with it), as BOTTOM + + def dw_mark_edit(self, n): + """s<n> holding a descriptor word was edited in place (the base keeps its symbol): marked until an instruction + writes s<n> otherwise (one(): a fresh load of the same entry is the table's word again).""" + self.sym[self.dw_edit_key(n)] = ('dwedit',) + self._dw_keep = getattr(self, '_dw_keep', set()) | {n} + + def dw_word(self, s, n): + """Placeholder index for symbol s of s<n> when it is a table descriptor word the runtime can pass, else None.""" + if 'descword' not in MESH_FEATURES or not s or s[0] != 'desc' or not isinstance(s[1], tuple): + return None + if s[1][0] != 'table' or s[2] is None or not isinstance(s[2], int) or not isinstance(s[3], int): + return None + if self.sym.get(self.dw_edit_key(n)): + # edited in place since it was loaded (or on some path into a join): the table's word is not its value + raise Unsupported('numeric use of an edited descriptor word (s%d: table %d +%d word %d)' % (n, s[1][1], s[2], s[3])) + src = ('descword', s[1][1], s[2] + 4 * s[3]) + if src not in self.pipe.dw_src: + self.pipe.dw_src.append(src) + return self.pipe.dw_src.index(src) + + def descriptor_numeric_field(self, base, ops): + if base not in ('s_bfe_u32', 's_and_b32') or not re.fullmatch(r'0x[0-9a-f]+', ops[2]): + return False + if base == 's_bfe_u32' and not 0 < ((int(ops[2], 16) >> 16) & 127) < 32: + return False + reg = reg_range(ops[0])[1] + succ = self.range_successors() + if not hasattr(self, '_field_inputs'): + self._field_inputs = {off: (op, asm) for off, _, op, asm in self.ins} + pending = list(succ[self.pc]) + seen = set() + used = False + while pending: + off = pending.pop() + if off in seen: + continue + seen.add(off) + op, asm = self._field_inputs[off] + carries = False + if reg in reads_writes(op, asm)[0]: + args = parse(asm)[1] + carries = (op in ('s_add_u32', 's_lshr_b32', 's_lshl2_add_u32', 's_max_u32', 's_cselect_b32') + and args[0] == ops[0] and ops[0] in args[1:]) + shift = op == 's_lshr_b32' and args[2] == ops[0] and args[1] != ops[0] + convert = op in ('v_cvt_f32_i32_e32', 'v_cvt_f32_u32_e32') and args[1] == ops[0] + if not (carries or shift or convert): + return False + used |= shift or convert + if carries or reg not in self.pair_writes(op, asm): + pending.extend(succ[off]) + return used + + def dw_scalar(self, base, ops): + """A 32-bit scalar op over table descriptor words (and numbers): emitted with placeholders, result ('dwnum', + deps). None when the op is not one (the caller goes on as before).""" + if 'descword' not in MESH_FEATURES or base not in G.SCA or base.endswith('_b64') or len(ops) < 2: + return None + d = reg_range(ops[0]) + if not d or d[0] != 's' or d[1] != d[2]: + return None + syms = [] + for t in ops[1:]: + r = reg_range(t) + if r and r[0] == 's' and r[1] != r[2]: + return None + syms.append(self.sym.get(r[1]) if r and r[0] == 's' else None) + kinds = [s[0] if s else None for s in syms] + if not any(k in ('desc', 'dwnum') for k in kinds): + return None + if base == 's_mov_b32' and kinds[0] == 'desc': + # a descriptor word moved: it keeps its descriptor meaning (a resource operand, as before), and its edit mark + if self.sym.get(self.dw_edit_key(reg_range(ops[1])[1])): + self.dw_mark_edit(d[1]) + return None + if any(k not in (None, 'const', 'ud', 'fixed_buffer_word', 'desc', 'dwnum') for k in kinds): + return None + own = self.sym.get(d[1]) + if own and own[0] == 'desc' and own in syms and not self.descriptor_numeric_field(base, ops): + # an in-place edit of a descriptor word: the base records it (and keeps the symbol); noted for dw_word + self.dw_mark_edit(d[1]) + return None + if base == 's_movk_i32': + return None + regs = [reg_range(t) for t in ops[1:]] + if any(k == 'desc' and self.dw_word(s, r[1]) is None for k, s, r in zip(kinds, syms, regs)): + return None + deps, values = set(), [] + for t, s in zip(ops[1:], syms): + r = reg_range(t) + if s and s[0] == 'desc': + k = self.dw_word(s, r[1]) + deps.add(k) + values.append('X2W_DW%d' % k) + elif s and s[0] == 'dwnum': + deps |= s[1] + self.used_s.add(r[1]) + values.append('s%d' % r[1]) + else: + values.append(self.u(t)) + text, scc = G.SCA[base] + self.set_s(d[1], text.format(*values)) + self.sym[d[1]] = ('dwnum', frozenset(deps)) + if scc: + self.emit('scc = %s;' % scc.replace('$', 's%d' % d[1])) + return True + + def dw_use(self, deps): + self.pipe.dw_used |= set(deps) + + def S(self, n): + """A word of a resource-heap descriptor read as a number (an image's width bits, a null test): the + runtime's synthesized word (x2w_hword), with X2W_MESH_FEATURES=heapwords; a table descriptor word or a + value computed from such words (X2W_MESH_FEATURES=descword): its entry value / variable, marked used; + otherwise as the base.""" + s = self.sym.get(n) + if s and s[0] == 'hword': + return 'x2w_hword(h%d, %du)' % (s[1], s[2]) + if s and s[0] == 'dwnum': + self.dw_use(s[1]) + self.used_s.add(n) + return 's%d' % n + k = self.dw_word(s, n) + if k is not None: + self.dw_use({k}) + return 'X2W_DW%d' % k + if (s and s[0] == 'desc' and isinstance(s[1], tuple) and s[1][0] == 'heapdyn' and s[2] == 0 + and 'heapwords' in MESH_FEATURES and 'heap' in getattr(self.pipe, 'features', ())): + self.pipe.heapwords = True + return 'x2w_hword(h%d, %du)' % (s[1][1], s[3]) + return super().S(n) + + def heap_sampler(self, tok): + # run-time offset (base) or a constant entry of the sampler heap (const_heap_sampler) + return super().heap_sampler(tok) or const_heap_sampler(self, tok) + + def set_exec_static(self, mask): + """exec = a constant lane mask (s_mov_b64 exec, <constant> or a copy of one).""" + mask &= ALL_LANES + self._static_set = True + self.exec_static = mask + if mask == ALL_LANES: + self.emit('exec = 1;') + self.exec_known = True + else: + self.emit('exec = %s;' % self.exec_mask_expr(mask)) + self.exec_known = False + + def op_s_cselect_b32(self, ops, mods): + # the base handles register / exec / vcc destinations; the run form also selects into m0 + if ops[0] == 'm0': + low = [('s%d' % reg_range(t)[1]) if reg_range(t) and reg_range(t)[0] == 's' else t for t in ops[1:3]] + self.emit('m0 = scc ? %s : %s;' % (self.u(low[0]), self.u(low[1]))) + return None + if not reg_range(ops[0]) and ops[0] not in ('exec', 'exec_lo', 'vcc', 'vcc_lo'): + raise Unsupported('s_cselect_b32 to %s' % ops[0]) + return super().op_s_cselect_b32(ops, mods) + + def op_s_and_b32(self, ops, mods): + # merged_wave_info & mask: the wave index field (bits 27:24) is the only part this translation models + for i, j in ((1, 2), (2, 1)): + src = reg_range(ops[i]) + if src and src[0] == 's' and self.sym.get(src[1]) == ('waveinfo',): + if not re.fullmatch(r'0x[0-9a-f]+|\d+', ops[j]) or int(ops[j], 0) & ~0x0f000000: + raise Unsupported('merged_wave_info & %s' % ops[j]) + d = reg_range(ops[0]) + if not d or d[0] != 's': + raise Unsupported('s_and_b32 of merged_wave_info to %s' % ops[0]) + self.masks.discard(d[1]) + self.set_s(d[1], '((wave << 24) & 0x%08xu)' % int(ops[j], 0), scc='$ != 0u') + return None + return self.scalar('s_and_b32', ops) + + def lds(self, base, ops, mods): + """ds_read_b32 / ds_write_b32 / _b64 with offset:N as groupshared uint x2w_lds[] (byte address / 4). + Lanes of one wave run independently between barriers here, so an LDS read after an LDS write in the same + barrier phase (lane-to-lane traffic inside a wave) is refused.""" + size = {'ds_read_b32': 1, 'ds_write_b32': 1, 'ds_read_b64': 2, 'ds_write_b64': 2}.get(base) + if size is None: + raise Unsupported(base) + off = 0 + for m in mods: + if m.startswith('offset:'): + off = int(m[7:], 0) + else: + raise Unsupported('%s with %s' % (base, m)) + if off + 4 * size > 4 * LDS_DWORDS: + raise Unsupported('%s offset %d beyond the modelled LDS' % (base, off)) + self.lds_used = True + if base.startswith('ds_write'): + addr, data = ops[0], reg_range(ops[1]) + # Several lanes storing to one address are ordered on the console (the highest lane wins) but race in + # HLSL: a uniform address is only taken under a constant single-lane exec. + single = self.exec_static is not None and bin(self.exec_static).count('1') == 1 + ar = reg_range(addr) + shared = not single and not (ar and ar[0] == 'v' and self.lane_dependent('v%d' % ar[1])) + if shared and (size != 1 or self.lane_dependent('v%d' % data[1])): + raise Unsupported('%s to a wave-uniform address with more than one lane active at %#x' % (base, self.pc)) + self.emit('a = (%s + %du) >> 2;' % (self.u(addr), off)) + for i in range(size): + address = 'x2w_lds[min(a + %du, %du)]' % (i, LDS_DWORDS - 1) + store = '{ uint old; InterlockedExchange(%s, v%d, old); }' if shared else '%s = v%d;' + self.emit('if (exec & 1) ' + store % (address, data[1] + i)) + self.used_v.add(data[1] + i) + self.lds_written_in_phase = True + return None + if self.lds_written_in_phase: + raise Unsupported('LDS read after an LDS write without a barrier at %#x' % self.pc) + dst, addr = reg_range(ops[0]), ops[1] + ar = reg_range(addr) + if ar and ar[0] == 'v' and dst[1] <= ar[1] < dst[1] + size - 1: # a later word would read the new value + raise Unsupported('%s overwrites its address register' % base) + for i in range(size): + # the address expression is repeated (no temporary), so a shadow (see set_v) can substitute into it + self.set_v(dst[1] + i, 'x2w_lds[min(((%s + %du) >> 2) + %du, %du)]' % (self.u(addr), off, i, LDS_DWORDS - 1)) + return None + + def liveness(self): + """Scalar registers (numbers; -1 = vcc) live on entry to each instruction offset (backward dataflow over + fall-through and branch edges).""" + if getattr(self, '_live', None) is not None: + return self._live + order = [x[0] for x in self.ins] + info = {x[0]: (x[2], x[3]) for x in self.ins} + following = dict(zip(order, order[1:])) + rw = {} + succ = {} + for off in order: + name, asm = info[off] + r, w, wv, rv = reads_writes(name, asm) + if RESTORED_SCALARS: + # wave64 lane masks that a VALU op names by their low SGPR: a v_cmp SDST writes the pair; a + # v_cndmask / carry-in mask operand reads it (AMD RDNA 2 ISA, VOP3 SDST / SSRC2 in wave64) + w = self.pair_writes(name, asm) + base = re.sub(r'_e(32|64)$', '', name) + last = parse(asm)[1][-1:] if base.startswith('v_cndmask') or (CARRY.fullmatch(base) and '_ci' in base) else [] + if last and re.fullmatch(r's\d+', last[0]): + r = set(r) | {int(last[0][1:]) + 1} + rw[off] = (frozenset(r | ({-1} if rv else set())), frozenset(w | ({-1} if wv else set()))) + nxt = [] if name in ('s_endpgm', 's_branch') else ([following[off]] if off in following else []) + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + succ[off] = [o for o in nxt if o in info] + live = {off: frozenset() for off in order} + changed = True + while changed: + changed = False + for off in reversed(order): + out = frozenset().union(*(live[s] for s in succ[off])) if succ[off] else frozenset() + r, w = rw[off] + new = r | (out - w) + if new != live[off]: + live[off], changed = new, True + self._live = live + return live + + def check_skipped_scalars(self, off, target): + """Refuse when a scalar register written in (off, target) is live at target (some path reads it before a + write): lanes that skip the range would see the old value where the wave saw the new one.""" + hit = self.skipped_scalars(off, target) + if hit: + raise Unsupported('scalar %s written in the per-lane skipped range %#x-%#x is live at its end' + % ('vcc' if min(hit) == -1 else 's%d' % min(hit), off, target)) + + def range_successors(self): + if getattr(self, '_succ', None) is None: + order = [x[0] for x in self.ins] + info = {x[0]: (x[2], x[3]) for x in self.ins} + following = dict(zip(order, order[1:])) + self._succ = {} + for o in order: + name, asm = info[o] + nxt = [] if name in ('s_endpgm', 's_branch') else ([following[o]] if o in following else []) + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + self._succ[o] = [x for x in nxt if x in info] + return self._succ + + def restored_scalars(self, off, target, hits, *, entry=None, allow_copy=False): + """Of the SGPRs in `hits` (written in the range (off, target)), those that hold their value from before the + range again on every exit of the range: the register-allocator shuffle `s_mov_b32 sT, sR; ... sR = ...; + ... s_mov_b32 sR, sT`. Forward copy tracking over the range's own paths (state: register -> the register + whose entry value it holds, None = unknown; a register not in the state holds its own entry value), + intersected at joins; s_mov_b32 / s_mov_b64 copy, any other write ends what the destination held.""" + if not RESTORED_SCALARS: + return set() + succ = self.range_successors() + info = {x[0]: (x[2], x[3]) for x in self.ins} + inside = [o for o, _, _, _ in self.ins if off < o < target] + if not inside: + return set() + start = inside[0] if entry is None else entry + state = {start: {}} + exits = [] + work = [start] + seen_edges = 0 + while work: + seen_edges += 1 + if seen_edges > 100000: + return set() + o = work.pop() + st = dict(state[o]) + name, asm = info[o] + ops = parse(asm)[1] + w = self.pair_writes(name, asm) + d = reg_range(ops[0]) if ops else None + s = reg_range(ops[1]) if len(ops) == 2 else None + if name in ('s_mov_b32', 's_mov_b64') and d and d[0] == 's' and s and s[0] == 's': + n = 2 if name == 's_mov_b64' else 1 + vals = [st.get(s[1] + i, s[1] + i) for i in range(n)] + for i in range(n): + st[d[1] + i] = vals[i] + else: + for r in w: + if isinstance(r, int): + st[r] = None + for nx in succ[o]: + if not off < nx < target: + if nx <= off: + return set() # a loop back above the branch: not modelled + exits.append(st) + continue + if nx not in state: + state[nx] = st + work.append(nx) + else: + merged = {r: v for r, v in state[nx].items()} + for r in set(merged) | set(st): + a, b = merged.get(r, r), st.get(r, r) + merged[r] = a if a == b else None + if merged != state[nx]: + state[nx] = merged + work.append(nx) + if not exits: + return set() + return {r for r in hits if isinstance(r, int) and r >= 0 + and (exits[0].get(r, r) == r or (allow_copy and exits[0].get(r, r) is not None)) + and all(e.get(r, r) == exits[0].get(r, r) for e in exits)} + + def group_branches(self): + """execz branches (offsets) translated as group-uniform branches: those whose range writes a scalar that + is live at its end or holds a published lane-mask SCC (pipe.scc_publish), and every execz range enclosing + one of them (the inner barrier needs every thread of the group to reach it). Exec-write refusals are left + to the translation.""" + if getattr(self, '_group', None) is None: + ranges = [] + for o, n, name, asm in self.ins: + if name == 's_cbranch_execz': + t = int(parse(asm)[1][0].split('_')[1], 16) + if t > o: + ranges.append((o, t)) + # ranges that hold a lane-dependent v_readfirstlane_b32 (NeedGroupRange, set by MeshPipeline) + need = set(o for o, t in ranges if o in getattr(self.pipe, 'force_group', ())) + for o, t in ranges: + try: + if self.skipped_scalars(o, t): + need.add(o) + except Unsupported: + pass + # a lane-mask SCC published inside the range: the publish barrier needs every thread of the group, and + # the wave's SCC is then the OR over all 64 lanes' bits (the SALU op reads every bit, whatever exec is; + # the inactive lanes run the range with exec 0, their compare bits 0, as VOPC writes them) + publish = getattr(self.pipe, 'scc_publish', ()) if LANE_SCC else () + for o, t in ranges: + if any(o < p < t for p in publish): + need.add(o) + for o, t in ranges: + if any(o < o2 < t for o2 in need): + need.add(o) + self._group = {o: t for o, t in ranges if o in need} + return self._group + + @staticmethod + def pair_writes(name, asm): + """SGPRs an instruction writes, with the high half of a wave64 lane mask that a compare names by its low + register only (v_cmp / v_cmp_class SDST: the disassembler prints one SGPR; carry-outs are already pairs in + reads_writes; readlane / readfirstlane write one SGPR).""" + w = set(reads_writes(name, asm)[1]) + if name.startswith('v_cmp'): + w |= {x + 1 for x in w} + return w + + def exec_copies_at(self): + """Offset -> SGPR pairs (low register numbers) that hold exactly the wave's exec on entry to that + instruction on EVERY path from the entry: `s_mov_b64 sX, exec`, `s_mov_b64 exec, sX` and moves of such a + pair. Forward dataflow over fall-through and branch edges (loops included), intersected at joins; any other + exec write, or a write to the pair, ends the fact. Static (no translation state), so the pre-pass of + group_branches sees the same facts as the translation.""" + if not EXEC_COPIES: + return {} + if getattr(self, '_exec_copies', None) is None: + order = [x[0] for x in self.ins] + info = {x[0]: (x[2], x[3]) for x in self.ins} + following = dict(zip(order, order[1:])) + succ = {} + for off in order: + name, asm = info[off] + nxt = [] if name in ('s_endpgm', 's_branch') else ([following[off]] if off in following else []) + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + succ[off] = [o for o in nxt if o in info] + + def transfer(off, eq): + # eq: 32-bit halves (register, 0 = exec_lo / 1 = exec_hi) holding that half of the current exec + name, asm = info[off] + ops = parse(asm)[1] + w = self.pair_writes(name, asm) + hv = [self.mask_halves(t) for t in ops[:2]] + if ops and ops[0] in ('exec', 'exec_lo', 'exec_hi') or self.exec_written(name, ops): + if name == 's_mov_b64' and ops[0] == 'exec' and isinstance(hv[1], list) and len(hv[1]) == 2: + return frozenset(hv[1]) + return frozenset() + add = set() + d = hv[0] if hv and isinstance(hv[0], list) else None + if d and len(ops) == 2 and name in ('s_mov_b64', 's_mov_b32'): + s = hv[1] + if name == 's_mov_b64' and len(d) == 2: + if s == 'exec': + add = set(d) + elif isinstance(s, list) and len(s) == 2: + add = {(d[i][0], s[i][1]) for i in range(2) if s[i] in eq} + elif name == 's_mov_b32' and len(d) == 1: + if isinstance(s, tuple): + add = {(d[0][0], s[1])} + elif isinstance(s, list) and len(s) == 1: + add = {(d[0][0], h) for (rr, h) in eq if rr == s[0][0]} + return frozenset({x for x in eq if x[0] not in w} | add) + facts = {order[0]: frozenset()} if order else {} # None (absent) = not reached yet + work = list(order[:1]) + while work: + off = work.pop() + out = transfer(off, facts[off]) + for s in succ[off]: + new = out if s not in facts else facts[s] & out + if facts.get(s) != new: + facts[s] = new + work.append(s) + self._exec_copies = {o: frozenset(r for (r, h) in eq if h == 0 and (r + 1, 1) in eq) for o, eq in facts.items()} + return self._exec_copies + + def skipped_scalars(self, off, target): + """Scalar registers (-1 = vcc) written in (off, target) and live at target; Unsupported for exec writes + the per-lane model cannot follow.""" + if EXEC_COPIES: + written = self.exec_walk(off, target) + hits = written & self.liveness().get(target, frozenset()) + return hits - self.restored_scalars(off, target, hits) if hits else hits + written = set() + copies = set() # registers holding exec as it was inside the range (nested if/else masks) + for o, n, name, asm in self.ins: + if off < o < target: + r, w, wv, _ = reads_writes(name, asm) + written |= w | ({-1} if wv else set()) + ops = parse(asm)[1] + low = [reg_range(t)[1] if reg_range(t) and reg_range(t)[0] == 's' else t for t in ops] + if name.startswith('s_') and 'saveexec' in name: + copies.add(low[0]) + continue + if name in ('s_mov_b64', 's_mov_b32') and len(ops) == 2 and ops[1] in ('exec', 'exec_lo'): + copies.add(low[0]) + continue + if (re.match(r's_(and|andn2)_b(32|64)$', name) and len(ops) == 3 and ops[0] not in ('exec', 'exec_lo') + and low[1] in copies): + copies.add(low[0]) # a subset of a copy taken in the range (`copy & ~exec`: the else lanes) + continue + if name.startswith('s_') and ops and ops[0] in ('exec', 'exec_lo'): + # A wave-level exec write can turn on lanes the per-lane model left behind, unless it only + # narrows exec (and / andn2 with exec) or restores / complements a copy taken in the range. + srcs = low[1:] + if re.match(r's_(and|andn2)_b(32|64)$', name) and 'exec' in ops[1:]: + pass + elif name in ('s_mov_b64', 's_mov_b32') and srcs[0] in copies: + pass + elif re.match(r's_andn2_b(32|64)$', name) and srcs[0] in copies: + pass # else branch: copy & ~exec is inside the copy + else: + raise Unsupported('exec written by %s inside the per-lane skipped range %#x-%#x' + % (name, off, target)) + for t in w: + copies.discard(t) + return written & self.liveness().get(target, frozenset()) + + @staticmethod + def mask_halves(tok): + """A scalar operand as 32-bit halves of a wave64 mask: 's[30:31]' -> [(30, 0), (31, 1)], 's30' -> [(30, None)] + (a 32-bit move keeps whichever half it holds), 'exec' -> 'exec', 'exec_lo' / 'exec_hi' -> ('exec', h).""" + if tok == 'exec': + return 'exec' + if tok in ('exec_lo', 'exec_hi'): + return ('exec', 0 if tok == 'exec_lo' else 1) + r = reg_range(tok) + if not r or r[0] != 's': + return None + if r[2] == r[1] + 1: + return [(r[1], 0), (r[1] + 1, 1)] + if r[2] == r[1]: + return [(r[1], None)] + return None + + def xor_swaps(self): + """XOR swaps of two SGPRs or two disjoint SGPR pairs: `s_xor_b32 sA, sA, sB; s_xor_b32 sB, sA, sB; + s_xor_b32 sA, sA, sB` (or the s_xor_b64 form; sources in either order) inside one basic block, where the + instructions between them touch neither A nor B. Afterwards A holds B's old value and B holds A's + (x ^ y ^ y = x). Returns ({offset of the first: {register: register it moves to}}, {offsets of the other + two}): exec_walk exchanges the facts of A and B at the first and leaves them alone at the others.""" + if getattr(self, '_xor_swaps', None) is None: + swaps, rest = {}, set() + targets = self.branch_targets() + + def form(x): + """(width, destination base, {source bases}) of an s_xor_b32 / s_xor_b64 on SGPRs.""" + ops = parse(x[3])[1] + width = {'s_xor_b32': 1, 's_xor_b64': 2}.get(x[2]) + if not width or len(ops) != 3: + return None + # vcc is s[106:107] on the console (the register allocator swaps through it as a data pair) + r = [('s', 106, 107) if t == 'vcc' else reg_range(t) for t in ops] + if not all(rr and rr[0] == 's' and rr[2] - rr[1] + 1 == width for rr in r): + return None + return width, r[0][1], {r[1][1], r[2][1]} + for i in range(len(self.ins) - 2): + f0 = form(self.ins[i]) + if not f0 or len(f0[2]) != 2 or f0[1] not in f0[2]: + continue + width, a = f0[0], f0[1] + b = (f0[2] - {a}).pop() + if abs(a - b) < width: + continue # overlapping pairs are no swap + regs = set(range(a, a + width)) | set(range(b, b + width)) + # the next two instructions that touch sA or sB must be the other two xors; instructions between + # them touch neither, and none of them is a branch or a branch target (one basic block) + found = [] + for x in self.ins[i + 1:i + 17]: + if x[0] in targets or x[2].startswith(('s_branch', 's_cbranch', 's_setpc', 's_endpgm')): + break + rd, wr, wv, rv = reads_writes(x[2], x[3]) + touched = set(rd) | set(wr) | ({106, 107} if wv or rv else set()) + if not (regs & touched): + continue + want = (width, b, {a, b}) if not found else (width, a, {a, b}) + if form(x) != want: + break + found.append(x[0]) + if len(found) == 2: + swaps[self.ins[i][0]] = {a + k: b + k for k in range(width)} | \ + {b + k: a + k for k in range(width)} + rest |= set(found) + break + self._xor_swaps = (swaps, rest) + return self._xor_swaps + + def exec_walk(self, off, target): + """The exec rule of skipped_scalars as a forward dataflow over the paths inside (off, target): returns the + scalar registers (-1 = vcc) written there, or raises Unsupported for an exec write that could turn on a lane + that was off at the branch (the one-lane model left that lane at the target). + + State: the 32-bit halves (register, 0 = lanes 0-31 / 1 = lanes 32-63) that hold part of a lane mask inside + the lanes active at the branch ("in-range masks"). Exec itself always is one (every accepted exec write keeps + it inside). Seeded with the pairs equal to exec at the branch (exec_copies_at); saveexec destinations, + copies of exec, moves (64- and 32-bit: register shuffles and SGPR spill slots), `and` with an in-range mask, + `andn2` of one and `or` of two are in-range masks; any other write ends what the register held. Intersected + at joins (a register is an in-range mask only if it is one on every path). Accepted exec writes: v_cmpx + (narrows), s_and with exec or an in-range mask, s_andn2 / andn2_saveexec / andn2_wrexec of an in-range mask + (an else mask), s_or / or_saveexec of in-range masks, and moves of an in-range pair or half.""" + info = {x[0]: (x[2], x[3]) for x in self.ins} + succ = self.range_successors() + inside = [o for o, _, _, _ in self.ins if off < o < target] + written = set() + if not inside: + return written + seed = set() + for x in self.exec_copies_at().get(off, ()): + seed |= {(x, 0), (x + 1, 1)} + state = {inside[0]: frozenset(seed)} + work = [inside[0]] + steps = 0 + swaps, swap_rest = self.xor_swaps() + + def refuse(name): + raise Unsupported('exec written by %s inside the per-lane skipped range %#x-%#x (at %#x)' + % (name, off, target, o)) + while work: + steps += 1 + if steps > 200000: + raise Unsupported('exec dataflow of the per-lane range %#x-%#x does not settle' % (off, target)) + o = work.pop() + st = set(state[o]) + name, asm = info[o] + ops = parse(asm)[1] + halves = [self.mask_halves(t) for t in ops] + + def inrange(h): + """Operand h (from mask_halves) is an in-range 64-bit mask.""" + return h == 'exec' or (isinstance(h, list) and len(h) == 2 and all(x in st for x in h)) + add = set() + base = name + if base.startswith('s_') and ops and ops[0] in ('exec', 'exec_lo', 'exec_hi'): + src = halves[1:] + if base in ('s_mov_b64',) and inrange(src[0]): + pass + elif base == 's_mov_b32' and isinstance(src[0], list) and src[0][0][1] is None and \ + any((src[0][0][0], h) in st for h in (0, 1)) and \ + (src[0][0][0], 0 if ops[0] == 'exec_lo' else 1) in st: + pass # a half restored into its own half of exec + elif base == 's_and_b64' and (inrange(src[0]) or inrange(src[1])): + pass + elif base == 's_andn2_b64' and inrange(src[0]): + pass # else mask: an in-range mask & ~exec + elif base == 's_or_b64' and inrange(src[0]) and inrange(src[1]): + pass + else: + refuse(name) + elif base.startswith('s_') and ('saveexec' in base or 'wrexec' in base): + src = halves[1] + if not (base.startswith('s_and_') or inrange(src)): + refuse(name) # or / andn2 forms take lanes from the source + d = halves[0] + if isinstance(d, list) and len(d) == 2: + add = set(d) # the old exec (saveexec) or the new one (wrexec): inside the branch's lanes + elif base.startswith('s_') and len(ops) >= 2 and isinstance(halves[0], list): + d = halves[0] + if base == 's_mov_b64' and len(d) == 2: + s = halves[1] + if s == 'exec': + add = set(d) + elif isinstance(s, list) and len(s) == 2: + add = {(d[i][0], s[i][1]) for i in range(2) if s[i] in st} + elif base == 's_mov_b32' and len(d) == 1: + s = halves[1] + if isinstance(s, tuple): + add = {(d[0][0], s[1])} # exec_lo / exec_hi + elif isinstance(s, list) and len(s) == 1: + add = {(d[0][0], h) for (rr, h) in st if rr == s[0][0]} + elif base == 's_and_b64' and len(d) == 2 and (inrange(halves[1]) or inrange(halves[2])): + add = set(d) + elif base == 's_andn2_b64' and len(d) == 2 and inrange(halves[1]): + add = set(d) + elif base == 's_or_b64' and len(d) == 2 and inrange(halves[1]) and inrange(halves[2]): + add = set(d) + if o in swaps: + # the register allocator's XOR swap (three s_xor): A and B exchange their values + st = {(swaps[o].get(r, r), h) for (r, h) in st} + elif o not in swap_rest: + pw = self.pair_writes(name, asm) + st = {x for x in st if x[0] not in pw} | add + out = frozenset(st) + for nx in succ[o]: + if not off < nx < target: + continue + new = out if nx not in state else state[nx] & out + if state.get(nx) != new: + state[nx] = new + work.append(nx) + for o in inside: + name, asm = info[o] + _, w, wv, _ = reads_writes(name, asm) + written |= w | ({-1} if wv else set()) + ops = parse(asm)[1] + # an instruction the walk did not reach from the branch (entered from elsewhere): no exec write there + if o not in state and name.startswith('s_') and (ops and ops[0] in ('exec', 'exec_lo', 'exec_hi') or + 'saveexec' in name or 'wrexec' in name): + refuse(name) + return written + + def scalar(self, base, ops): + """With X2W_MESH_FEATURES=heapwords, words of a resource-heap descriptor that a scalar op reads as numbers + (not an in-place edit of the descriptor) are the runtime's synthesized words (x2w_hword): they are + swapped for a numeric symbol for this instruction, so the base computes the result at run time + instead of keeping a symbolic `descnum`.""" + swapped = {} + off_regs = self.exec_off_use(base, ops) + for n in off_regs: + # (merge_exec_off) the register's run-time variable: right on the paths that assigned it, and the + # result does not depend on it in a lane that came with exec 0 + self.sym.pop(n) + if 'heapwords' in MESH_FEATURES and 'heap' in getattr(self.pipe, 'features', ()): + d = reg_range(ops[0]) + own = self.sym.get(d[1]) if d and d[0] == 's' else None + for t in ops[1:]: + r = reg_range(t) + if not r or r[0] != 's': + continue + for n in range(r[1], r[2] + 1): + s = self.sym.get(n) + if (s and s[0] == 'desc' and isinstance(s[1], tuple) and s[1][0] == 'heapdyn' and s[2] == 0 + and s != own): + swapped[n] = s + self.sym[n] = ('hword', s[1][1], s[3]) + if swapped: + self.pipe.heapwords = True + edits = sum(len(v) for v in getattr(self.pipe, 'modified_words', {}).values()) + try: + term = self.scalar_inner(base, ops) + if 'descword' in MESH_FEATURES and sum(len(v) for v in getattr(self.pipe, 'modified_words', {}).values()) > edits: + # the base recorded an in-place edit of a descriptor word (whatever the other operands): s<d> keeps the + # symbol but not the table's value (dw_word refuses its numeric use until it is written otherwise) + d = reg_range(ops[0]) + if d and d[0] == 's': + for n in range(d[1], d[2] + 1): + self.dw_mark_edit(n) + return term + finally: + for n, s in swapped.items(): + if self.sym.get(n) == ('hword', s[1][1], s[3]): + self.sym[n] = s + for n in off_regs: + if n not in scalar_regs(ops[0]): + self.sym[n] = ('conflict',) + + def scalar_inner(self, base, ops): + dst = reg_range(ops[0]) + src = reg_range(ops[1]) if len(ops) >= 2 else None + if (base == 's_mov_b32' and len(ops) == 2 and dst and src and dst[0] == src[0] == 's' + and dst[1] == dst[2] and src[1] == src[2] and self.sym.get(src[1]) == ('conflict',)): + # Also used for either dword of an SGPR pair. Copy its numeric backing where it + # exists, retaining the conflict so numeric users still need a proof on every path. + masked = src[1] in self.masks + self.used_s.add(src[1]) + self.set_s(dst[1], 's%d' % src[1]) + self.sym[dst[1]] = ('conflict',) + self.exec_off.discard(dst[1]) + getattr(self, 'execzero', {}).pop(dst[1], None) + if masked: + self.masks.add(dst[1]) + return None + symbol = self.sym.get(src[1]) if src and src[0] == 's' else None + if dst and dst[0] == 's' and symbol and symbol[0] in ('code_lo', 'code_hi'): + if base == 's_mov_b32': + self.set_s(dst[1], None, symbol) + return + if base == 's_add_u32' and symbol[0] == 'code_lo' and re.fullmatch(r'0x[0-9a-f]+|\d+', ops[2]): + self.set_s(dst[1], None, ('code_lo', symbol[1] + int(ops[2], 0))) + return + if base == 's_bcnt1_i32_b32' and len(ops) == 2 and self.is_tainted(ops[1]): + # a scalar that depends on lane masks holds this lane's share of a wave value: its count is not the wave's + raise Unsupported('s_bcnt1_i32_b32 of a value that depends on lane masks') + dname = ops[0] + r0 = reg_range(dname) + if dname == 'm0': + text, _ = G.SCA[base] + srcs = [('s%d' % reg_range(t)[1]) if reg_range(t) and reg_range(t)[0] == 's' else t for t in ops[1:]] + self.emit('m0 = %s;' % text.format(*[self.u(t) for t in srcs])) + return None + # restoring exec from a copy taken while every lane was active makes every lane active again; + # s_mov_b64 exec, -1 (the program's first instruction) activates all 64 lanes, which all exist + # (128 threads = two full waves) + if dname == 'exec' and base == 's_mov_b64': + if re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', ops[1]): + self.set_exec_static(int(ops[1], 0)) + return None + src = reg_range(ops[1]) + if src and src[0] == 's' and src[1] in self.static_copies: + self.set_exec_static(self.static_copies[src[1]]) + return None + if src and src[0] == 's' and self.sym.get(src[1]) == ('execcopy',): + self.set_exec_static(ALL_LANES) + return None + if base == 's_mov_b64' and len(ops) == 2 and ops[1] == 'exec' and self.exec_static is not None: + d = reg_range(dname) + if d and d[0] == 's': + mask = self.exec_static + term = super().scalar(base, ops) + self.static_copies[d[1]] = mask + return term + if r0 and r0[0] == 's': + for t in ops[1:]: + rr = reg_range(t) + if rr and rr[0] == 's' and self.sym.get(rr[1]) == ('waveinfo',): + raise Unsupported('merged_wave_info used by %s' % base) + if dname == 'null': + # the null destination discards the result; only SCC would change, and the moves seen write none + if base not in ('s_mov_b32', 's_mov_b64'): + raise Unsupported('%s to null' % base) + return None + if not r0 and dname not in ('exec', 'exec_lo', 'vcc', 'vcc_lo'): + raise Unsupported('%s to %s' % (base, dname)) + if self.dw_scalar(base, ops): + return None + if base == 's_mov_b32' and r0 and r0[0] == 's': + src = reg_range(ops[1]) + if src and src[0] == 's' and src[1] == src[2] and src[1] not in self.masks: + value = self.is_const(src[1]) + if value is not None: + self.set_s(r0[1], '0x%08xu' % value, ('const', value)) + return None + if DATA_PAIRS and base == 's_mov_b64' and r0 and r0[0] == 's' and len(ops) == 2: + src = reg_range(ops[1]) + if (src and src[0] == 's' and src[2] == src[1] + 1 and r0[2] == r0[1] + 1 + and (src[1] not in self.masks or self.sym.get(src[2]) == ('conflict',))): + # Copy both halves. A modeled lane mask keeps its lane bit in the low register; + # an unresolved upper half remains unreadable as numeric data after the move. + # If the ranges overlap, read the shared source before overwriting it. + order = (1, 0) if r0[1] == src[2] else (0, 1) + for offset in order: + self.scalar_inner('s_mov_b32', ['s%d' % (r0[1] + offset), 's%d' % (src[1] + offset)]) + return None + return super().scalar(base, ops) + + def op_s_getpc_b64(self, ops, mods): + # Keep the two address halves symbolic. Numeric uses remain unsupported, + # since the guest code's original GPU virtual address is unknown. + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[2] != dst[1] + 1: + raise Unsupported('getpc destination is not a scalar register pair') + self.set_s(dst[1], None, ('code_lo', self.pc + 4)) + self.set_s(dst[2], None, ('code_hi',)) + + def copied_constant(self, reg): + """Follow SGPR copies over every predecessor to the load. Every reaching + definition must agree on a literal. An entry input or other definition is unknown. + """ + if self.is_const(reg) is not None: + return self.is_const(reg) + if not hasattr(self, '_literal_predecessors'): + if any(name.startswith(('s_call', 's_setpc', 's_swappc', 's_rfe', 's_movrel')) + for _, _, name, _ in self.ins): + return None + self._literal_index = {off: i for i, (off, _, _, _) in enumerate(self.ins)} + self._literal_predecessors = {off: [] for off in self._literal_index} + self._literal_predecessors[self.ins[0][0]].append(None) + for off, targets in self.range_successors().items(): + for target in targets: + self._literal_predecessors[target].append(off) + todo = [(off, reg) for off in self._literal_predecessors[self.pc]] + seen, values = set(), set() + while todo: + off, source = todo.pop() + if off is None: + return None + if (off, source) in seen: + continue + seen.add((off, source)) + _, _, name, asm = self.ins[self._literal_index[off]] + if source in (106, 107) and reads_writes(name, asm)[2]: + return None + if source in self.pair_writes(name, asm): + ops = parse(asm)[1] + if name not in ('s_mov_b32', 's_mov_b64', 's_movk_i32') or len(ops) != 2: + return None + dst, src = map(reg_range, ops) + if not dst or not dst[1] <= source <= dst[2]: + return None + if src and src[0] == 's' and src[2] - src[1] == dst[2] - dst[1]: + source = src[1] + source - dst[1] + elif name != 's_mov_b64' and re.fullmatch(r'0x[0-9a-f]+|-?[0-9]+', ops[1]): + literal = G.sopk_simm(ops[1]) if name == 's_movk_i32' else ops[1] + values.add(int(literal, 0) & 0xffffffff) + if len(values) > 1: + return None + continue + else: + return None + todo.extend((previous, source) for previous in self._literal_predecessors[off]) + return next(iter(values)) if len(values) == 1 else None + + def scalar_literal_index_bits(self, index): + """Accept a contiguous BFE, LSHL-by-two, DWORD-load sequence with no + intervening index writes or branches into the sequence after the BFE. + """ + targets = self.branch_targets() + i = next(i for i, ins in enumerate(self.ins) if ins[0] == self.pc) + if self.pc in targets: + return None + i -= 1 + while i >= 0 and self.ins[i][2] == 's_buffer_load_dword': + off, _, _, asm = self.ins[i] + if off in targets or index == parse(asm)[1][0]: + return None + i -= 1 + if i < 1: + return None + off, _, shift, asm = self.ins[i] + if off in targets or shift != 's_lshl_b32' or parse(asm)[1] != [index, index, '2']: + return None + _, _, extract, asm = self.ins[i - 1] + ops = parse(asm)[1] + if extract != 's_bfe_u32' or ops[0] != index or not re.fullmatch(r'0x[0-9a-f]+', ops[2]): + return None + return (int(ops[2], 0) >> 16) & 0x7f + + def scalar_literal_load(self, ops, mods, count, desc, base): + register = desc[1] + size = self.copied_constant(register + 2) + if (count != 1 or desc[2] != register + 3 or self.sym.get(register + 1) != ('code_hi',) + or self.copied_constant(register + 3) != 0x31016fac or not size or size % 4 + or base < 0 or base % 4 or base + size > len(self.raw)): + raise Unsupported('incomplete scalar PC-relative raw buffer descriptor at %#x' % self.pc) + if len(mods) > 1 or any(not re.fullmatch(r'offset:0x[0-9a-f]+', m) for m in mods): + raise Unsupported('unsupported scalar literal table modifiers') + extra = int(mods[0][7:], 0) if mods else 0 + bits = self.scalar_literal_index_bits(ops[2]) + if bits is None or bits > 30 or extra % 4 or extra + (1 << bits) * 4 > size: + raise Unsupported('scalar literal table index unproven or outside descriptor at %#x' % self.pc) + table = self.literal_tables.setdefault((base, size), 'x2w_literals_%x_%x' % (base, size)) + self.set_s(reg_range(ops[0])[1], '%s[(%s >> 2u) + %du]' % (table, self.u(ops[2]), extra // 4)) + + def op_buffer_load_dword(self, ops, mods, count=1): + desc = reg_range(ops[2]) + low = self.sym.get(desc[1]) if desc else None + if not low or low[0] != 'code_lo': + return super().op_buffer_load_dword(ops, mods, count) + reg = desc[1] + size = self.is_const(reg + 2) + if (self.sym.get(reg + 1) != ('code_hi',) or self.is_const(reg + 3) != 0x31016fac + or not size or size % 4 or low[1] % 4 or low[1] < 0 or low[1] + size > len(self.raw)): + raise Unsupported('incomplete PC-relative raw buffer descriptor at %#x' % self.pc) + offsets = [int(m[7:], 0) for m in mods if m.startswith('offset:')] + if (count != 1 or ops[3] != '0' or 'offen' not in mods + or any(m != 'offen' and not m.startswith('offset:') for m in mods)): + raise Unsupported('PC-relative buffer load uses unsupported addressing') + key = (low[1], size) + table = self.literal_tables.setdefault(key, 'x2w_literals_%x_%x' % key) + offset = sum(offsets) + if offset % 4: + raise Unsupported('unaligned literal table instruction offset') + # RDNA2 raw DWORD addressing ignores the low two address bits. + # Compare before adding the immediate so a large VGPR cannot wrap. + self.emit('a = %s >> 2u;' % self.u(ops[1])) + value = '0u' if offset >= size else '(a < %du ? %s[min(a, %du) + %du] : 0u)' % ( + (size - offset) // 4, table, (size - offset) // 4 - 1, offset // 4) + self.set_v(reg_range(ops[0])[1], value) + + def op_s_bfe_u32(self, ops, mods): + src = reg_range(ops[1]) + if src and src[0] == 's' and self.sym.get(src[1]) == ('waveinfo',): + if ops[2] != '0x40018': + raise Unsupported('merged_wave_info field %s' % ops[2]) + self.set_s(reg_range(ops[0])[1], 'wave') + return None + return self.scalar('s_bfe_u32', ops) + + def op_s_bfe_i32(self, ops, mods): + # D = sext(S0 >> S1[4:0]) of width S1[22:16]; a width of 0 gives 0 (RDNA 2 ISA, S_BFE_I32). + a, b = self.u(ops[1]), self.u(ops[2]) + expr = ('((({1} >> 16) & 127u) == 0u ? 0u : asuint(asint({0} << (32u - min(({1} & 31u) + (({1} >> 16) & 127u), 32u))) ' + '>> (32u - min(({1} & 31u) + (({1} >> 16) & 127u), 32u) + ({1} & 31u))))').format(a, b) + self.set_s(reg_range(ops[0])[1], expr, scc='$ != 0') + + def op_s_bitset1_b32(self, ops, mods): + d = reg_range(ops[0])[1] + own = self.sym.get(d) + if own and own[0] in ('ptrhi', 'descnum'): + # a descriptor word built from a root pointer (stride / swizzle bits): keeps its descriptor meaning + self.sym[d] = ('descnum',) if own[0] == 'descnum' else own + return None + self.set_s(d, '%s | (1u << (%s & 31u))' % (self.S(d), self.u(ops[1]))) + + def op_s_bitset0_b32(self, ops, mods): + # RDNA 2 ISA S_BITSET0_B32: D.u[S0.u[4:0]] = 0 (no SCC); a descriptor word is refused (no rule for it) + d = reg_range(ops[0])[1] + own = self.sym.get(d) + if own and own[0] not in ('const', 'fixed_buffer_word'): + raise Unsupported('s_bitset0_b32 on s%d holding %s' % (d, own[0])) + self.set_s(d, '%s & ~(1u << (%s & 31u))' % (self.S(d), self.u(ops[1]))) + + # s_pack_{lh,hl,hh}_b32_b16: D = low half from S0 (l = bits 15:0, h = bits 31:16), high half from S1 + # (RDNA 2 ISA, S_PACK_*). s_pack_ll is in the base table. + def pack(self, ops, text): + d = reg_range(ops[0]) + if not d or d[0] != 's': + raise Unsupported('s_pack to %s' % ops[0]) + self.masks.discard(d[1]) + self.set_s(d[1], text.format(self.u(ops[1]), self.u(ops[2]))) + + def op_s_pack_lh_b32_b16(self, ops, mods): + self.pack(ops, '(({0} & 0xffffu) | ({1} & 0xffff0000u))') + + def op_s_pack_hl_b32_b16(self, ops, mods): + self.pack(ops, '(({0} >> 16) | ({1} << 16))') + + def op_s_pack_hh_b32_b16(self, ops, mods): + self.pack(ops, '(({0} >> 16) | ({1} & 0xffff0000u))') + + # v_min3 / v_max3 / v_med3 on integers (RDNA 2 ISA): three-way min, max, median + def three(self, ops, fn, signed): + a, b, c = [self.u(o) for o in ops[1:4]] + if signed: + a, b, c = ['asint(%s)' % x for x in (a, b, c)] + expr = {'min': 'min(min({0}, {1}), {2})', 'max': 'max(max({0}, {1}), {2})', + 'med': 'max(min({0}, {1}), min(max({0}, {1}), {2}))'}[fn].format(a, b, c) + self.set_v(reg_range(ops[0])[1], 'asuint(%s)' % expr if signed else expr) + + def op_v_min3_u32(self, ops, mods): + self.three(ops, 'min', False) + + def op_v_max3_u32(self, ops, mods): + self.three(ops, 'max', False) + + def op_v_med3_u32(self, ops, mods): + self.three(ops, 'med', False) + + def op_v_min3_i32(self, ops, mods): + self.three(ops, 'min', True) + + def op_v_max3_i32(self, ops, mods): + self.three(ops, 'max', True) + + def op_v_med3_i32(self, ops, mods): + self.three(ops, 'med', True) + + SEL = {'BYTE_0': (0, 8), 'BYTE_1': (8, 8), 'BYTE_2': (16, 8), 'BYTE_3': (24, 8), 'WORD_0': (0, 16), + 'WORD_1': (16, 16), 'DWORD': (0, 32)} + + def sdwa_src(self, tok, sel): + sx = tok.startswith('sext(') and tok.endswith(')') + u = self.u(tok[5:-1] if sx else tok) + sh, w = self.SEL[sel] + if w == 32: + return u + if sx: + return 'asuint(asint(%s << %du) >> %du)' % (u, 32 - sh - w, 32 - w) + return '((%s >> %du) & 0x%xu)' % (u, sh, (1 << w) - 1) + + def op_v_mov_b32_sdwa(self, ops, mods): + """D = the selected field of S0 placed at dst_sel; other bits zero (UNUSED_PAD) or kept (UNUSED_PRESERVE) + (RDNA 2 ISA, SDWA).""" + f = dict(m.partition(':')[::2] for m in mods) + if set(f) - {'dst_sel', 'dst_unused', 'src0_sel'} or len(ops) != 2: + raise Unsupported('v_mov_b32_sdwa with %s' % mods) + d = reg_range(ops[0])[1] + sh, w = self.SEL[f.get('dst_sel', 'DWORD')] + val = '((%s & 0x%xu) << %du)' % (self.sdwa_src(ops[1], f.get('src0_sel', 'DWORD')), (1 << w) - 1 if w < 32 else 0xffffffff, sh) + unused = f.get('dst_unused', 'UNUSED_PAD') + if unused == 'UNUSED_PRESERVE': + keep = 0xffffffff & ~((((1 << w) - 1) << sh)) + val = '(%s | (v%d & 0x%08xu))' % (val, d, keep) + self.used_v.add(d) + elif unused != 'UNUSED_PAD': + raise Unsupported('v_mov_b32_sdwa %s' % unused) + self.set_v(d, val) + + def op_v_cmp_class_f32_sdwa(self, ops, mods): + """V_CMP_CLASS_F32 (SDWA, VOPC into an SGPR mask): bit class(S0) of the selected S1 field; class bits 0 sNaN, + 1 qNaN, 2 -inf, 3 -normal, 4 -denormal, 5 -0, 6 +0, 7 +denormal, 8 +normal, 9 +inf (RDNA 2 ISA).""" + f = dict(m.partition(':')[::2] for m in mods) + if set(f) - {'src0_sel', 'src1_sel'} or f.get('src0_sel', 'DWORD') != 'DWORD' or len(ops) != 3: + raise Unsupported('v_cmp_class_f32_sdwa with %s %s' % (ops, mods)) + x = self.u(ops[1]) + mask = self.sdwa_src(ops[2], f.get('src1_sel', 'DWORD')) + return self.write_compare(False, ops[0], '((%s >> x2w_fclass(%s)) & 1u)' % (mask, x)) + + def op_v_cmp_class_f16_sdwa(self, ops, mods): + """V_CMP_CLASS_F16 (SDWA, VOPC into an SGPR mask): the selected 16-bit field of S0 with its abs/neg applied + to bit 15 (as the e64 form, base x2w_class_f16), S1 the class mask (DWORD).""" + f = dict(m.partition(':')[::2] for m in mods) + if set(f) - {'src0_sel', 'src1_sel'} or f.get('src1_sel', 'DWORD') != 'DWORD' or len(ops) != 3: + raise Unsupported('v_cmp_class_f16_sdwa with %s %s' % (ops, mods)) + tok = ops[1] + neg, ab = tok.startswith('-'), '|' in tok + reg = tok.strip('-|') + if not reg_range(reg) or f.get('src0_sel', 'DWORD') not in ('WORD_0', 'WORD_1', 'DWORD'): + raise Unsupported('v_cmp_class_f16_sdwa source %s %s' % (tok, mods)) + x = '(%s & 0xffffu)' % self.sdwa_src(reg, f.get('src0_sel', 'DWORD')) + if ab: + x = '(%s & 0x7fffu)' % x + if neg: + x = '(%s ^ 0x8000u)' % x + return self.write_compare(False, ops[0], 'x2w_class_f16(%s, %s)' % (x, self.u(ops[2]))) + + def compare(self, base, ops, mods=()): + """16-bit integer compares (v_cmp[x]_<cond>_{i16,u16}, e32/e64 without modifiers): the low halves, + sign- or zero-extended, compared as 32-bit integers; everything else as the base translator.""" + m = re.fullmatch(r'v_cmp(x?)_(\w+?)_(i16|u16)', base) + if not m: + return super().compare(base, ops, mods) + if mods or any(t.startswith(('-', '|')) for t in ops): + raise Unsupported('%s with modifiers %s' % (base, mods)) + writes_exec, cond, typ = m.group(1) == 'x', m.group(2), m.group(3) + if len(ops) == 3: + dst, a, b = ops + elif len(ops) == 2: + dst, (a, b) = ('exec' if writes_exec else 'vcc'), ops + else: + raise Unsupported('%s with %d operands' % (base, len(ops))) + if typ == 'i16': + x, y = ('(asint(%s << 16u) >> 16)' % self.u(t) for t in (a, b)) + else: + x, y = ('(%s & 0xffffu)' % self.u(t) for t in (a, b)) + return self.compare_result(base.replace(typ, 'i32' if typ == 'i16' else 'u32'), cond, writes_exec, dst, x, y) + + def image(self, ops, mods, how): + """d16 image results: the channels the base computes as binary32 are packed two per VGPR as binary16, + the first in the low half, the unused half of an odd last register 0 (gfx10 packed D16). Only for the + float views the base binds (Texture*<float4>); the base refuses the other result modifiers.""" + if 'd16' not in mods: + return super().image(ops, mods, how) + dmask = int([m for m in mods if m.startswith('dmask:')][0][6:], 0) + n = bin(dmask & 15).count('1') + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[2] - dst[1] + 1 != (n + 1) // 2: + raise Unsupported('d16 image result %s for dmask %#x' % (ops[0], dmask)) + tmp = 1000 # HLSL-only scratch VGPRs (the console has 256) + super().image([('v[%d:%d]' % (tmp, tmp + n - 1)) if n > 1 else 'v%d' % tmp] + list(ops[1:]), [m for m in mods if m != 'd16'], how) + for j in range((n + 1) // 2): + lo = 'f32tof16(asfloat(v%d))' % (tmp + 2 * j) + hi = '(f32tof16(asfloat(v%d)) << 16)' % (tmp + 2 * j + 1) if 2 * j + 1 < n else '0u' + self.set_v(dst[1] + j, '(%s | %s)' % (lo, hi)) + + def op_v_bfm_b32(self, ops, mods): + """V_BFM_B32: D = ((1 << S0[4:0]) - 1) << S1[4:0] (RDNA 2 ISA).""" + if mods or len(ops) != 3: + raise Unsupported('v_bfm_b32 form %s %s' % (ops, mods)) + self.set_v(reg_range(ops[0])[1], '(((1u << (%s & 31u)) - 1u) << (%s & 31u))' % (self.u(ops[1]), self.u(ops[2]))) + + def carry_op(self, base, ops, mods): + """v_add_co_u32 / v_sub_co_u32 / v_subrev_co_u32 and the _ci forms: D, carry-out mask, S0, S1[, carry-in mask]. + Add: sum = S0 + S1 + cin (mod 2^32), carry = cin ? sum <= S0 : sum < S0. Sub: d = S0 - S1 - bin, borrow = + bin ? d >= S0 : d > S0 (subrev swaps the sources). Both read only S0, the result and the carry-in, so the + carry-in may be the destination mask. The carry is the lane's bit of the destination mask.""" + m = CARRY.fullmatch(base) + if mods or len(ops) != (5 if m.group(2) else 4): + raise Unsupported('%s form %s %s' % (base, ops, mods)) + x, y = self.u(ops[2]), self.u(ops[3]) + if m.group(1) == 'subrev': + x, y = y, x + cin = '(%s & 1u)' % self.u(ops[4]) if m.group(2) else '0u' + if m.group(1) == 'add': + self.emit('a = %s; w = a + %s + %s;' % (x, y, cin)) + carry = '((%s != 0u ? w <= a : w < a) ? 1u : 0u)' % cin + else: + self.emit('a = %s; w = a - %s - %s;' % (x, y, cin)) + carry = '((%s != 0u ? w >= a : w > a) ? 1u : 0u)' % cin + dst = ops[1] + if dst.startswith('vcc'): + dst = 'vcc' + else: + r = reg_range(dst) + if not r or r[0] != 's': + raise Unsupported('%s carry to %s' % (base, dst)) + dst = 's%d' % r[1] + self.write_compare(False, dst, carry) + self.set_v(reg_range(ops[0])[1], 'w') + + def op_v_mbcnt_lo_u32_b32(self, ops, mods): + self.set_v(reg_range(ops[0])[1], 'x2w_mbcnt_lo(%s, lane) + %s' % (self.u(ops[1]), self.u(ops[2]))) + + def op_v_mbcnt_hi_u32_b32(self, ops, mods): + self.set_v(reg_range(ops[0])[1], 'x2w_mbcnt_hi(%s, lane) + %s' % (self.u(ops[1]), self.u(ops[2]))) + + def op_v_perm_b32(self, ops, mods): + if mods: + raise Unsupported('v_perm_b32 with %s' % mods) + self.set_v(reg_range(ops[0])[1], 'x2w_perm(%s, %s, %s)' % (self.u(ops[1]), self.u(ops[2]), self.u(ops[3]))) + + def op_v_pack_b32_f16(self, ops, mods): + sel = [0, 0, 0] + for m in mods: + if m.startswith('op_sel:['): + sel = [int(x) for x in m[8:-1].split(',')] + else: + raise Unsupported('v_pack_b32_f16 with %s' % m) + if any(t.startswith(('-', '|')) for t in ops[1:3]): + raise Unsupported('v_pack_b32_f16 with source modifiers') + lo = '(%s >> 16)' % self.h(ops[1]) if sel[0] else self.h(ops[1]) + hi = '(%s >> 16)' % self.h(ops[2]) if sel[1] else self.h(ops[2]) + self.set_v(reg_range(ops[0])[1], '(%s & 0xffffu) | ((%s & 0xffffu) << 16)' % (lo, hi)) + + def op_v_readfirstlane_b32(self, ops, mods): + src, dst = reg_range(ops[1]), reg_range(ops[0]) + if mods or not dst or dst[0] != 's' or not src or src[0] != 'v': + raise Unsupported('v_readfirstlane_b32 form %s' % ops) + self.masks.discard(dst[1]) # a number now, not a lane mask (s_or of it must not be masked to bit 0) + if src[1] == 5 and 5 not in self.written_v: + # v5 = group * 128 + thread (inferred fast-launch vertex id); the wave's first lane is its thread & ~63 + # (`wbase` = the wave's first thread: the same in every lane of a wave, so not lane-tainted) + self.set_s(dst[1], '(gid * %du + wbase)' % GROUP) + return None + shadow = self.shadow.get(src[1]) + read_mask = ALL_LANES if self.exec_known else self.exec_static + if shadow and read_mask: + first = (read_mask & -read_mask).bit_length() - 1 + if (shadow[1] >> first) & 1: + # the first active lane wrote this wave-uniform value: every thread takes it from the shadow + self.set_s(dst[1], shadow[0]) + return None + # A source that is the same in every active lane: each active lane's own value is the first active lane's + # (the result is then active-uniform itself, through emit). + if self.lane_dependent('v%d' % src[1]) or ( + dst[1] in self.pipe.force_first and self.is_tainted('v%d' % src[1])): + # Lane-dependent source: the console wave reads its first active lane. With every lane active and + # no per-lane region open (so every thread of the group reaches this statement, a group barrier is + # legal), that lane is the wave's first thread: broadcast through groupshared memory. + if not self.exec_known or self.pc < self.divergent_until: + text = 'v_readfirstlane_b32 of a lane-dependent v%d with lanes off at %#x (%s)' % ( + src[1], self.pc, 'in a per-lane range' if self.pc < self.divergent_until else 'partial exec') + if not RFL_FIRST: + raise Unsupported(text) + if any(t <= self.pc < o for o, t in self.backward_branches()): + # inside a loop: the trip count may differ between the waves of a group, so a group barrier + # there is not reached by every thread the same number of times (a waterfall loop over a + # per-lane index is mesh4's lowering, without a barrier) + raise Unsupported(text.replace('lanes off at', 'lanes off inside a loop at')) + if self.pc < self.divergent_until: + # not every thread reaches the read: ask for the innermost execz range around it to be run by + # the whole group (once; a range already run so, or a per-lane range of another kind, refuses) + around = [o for o, t in self.execz_ranges() if o < self.pc < t] + if around and max(around) not in self.group_branches(): + raise NeedGroupRange(max(around), text) + raise Unsupported(text) + return self.first_active_broadcast(src, dst, ops) + # The group barrier is a phase boundary of the body (see body()): the read starts the next block, so + # that block must not also be entered by a branch. + nxt = self.next_offset() + if nxt in self.branch_targets(): + raise Unsupported('v_readfirstlane_b32 broadcast followed by a branch target at %#x' % self.pc) + slot = self.broadcasts + self.broadcasts += 1 + self.emit('if (lane == 0u) x2w_rfl[%d][wave] = %s;' % (slot, self.u(ops[1]))) + self.sym.pop(dst[1], None) + self.used_s.add(dst[1]) + self.pending.append('s%d = x2w_rfl[%d][wave];' % (dst[1], slot)) + self.tainted.discard('s%d' % dst[1]) + self.au.pop('s%d' % dst[1], None) + self.au_xs.pop('s%d' % dst[1], None) + self.lds_written_in_phase = False + return ('barrier',) + self.set_s(dst[1], self.u(ops[1])) + if self.is_tainted('v%d' % src[1]): + self.au_scalars[dst[1]] = self.epoch + + def backward_branches(self): + """(branch offset, target) of every branch whose target is not after it (the loops of the program).""" + out = [] + for o, n, name, asm in self.ins: + if name.startswith(('s_branch', 's_cbranch_')): + args = parse(asm)[1] + if args and args[0].startswith('label_'): + t = int(args[0].split('_')[1], 16) + if t <= o: + out.append((o, t)) + return out + + def execz_ranges(self): + """(branch offset, target) of the forward s_cbranch_execz ranges of the program.""" + out = [] + for o, n, name, asm in self.ins: + if name == 's_cbranch_execz': + t = int(parse(asm)[1][0].split('_')[1], 16) + if t > o: + out.append((o, t)) + return out + + def first_active_broadcast(self, src, dst, ops): + """v_readfirstlane_b32 sD, vS of a lane-dependent vS under a partial exec, reached by every thread of the + group (no per-lane range open). The console wave reads the lane with the lowest index whose EXEC bit is set + (RDNA 2 ISA V_READFIRSTLANE_B32; with EXEC = 0 it reads lane 0 [ASSUMED from the ISA text, not measured]). + Every thread stores its vS (an inactive lane's VGPR keeps its old value, as here) and its exec bit in + groupshared memory, a group barrier follows, and the next block reads the first set bit's value of the + thread's own wave (x2w_rfirst). Refused: more than RFL_FIRST_SLOTS such reads, and a branch target right + after the read (the barrier is a phase boundary of the body, as for the lane-0 broadcast).""" + nxt = self.next_offset() + edge = nxt in self.branch_targets() + if edge and dst[1] not in self.pipe.force_first: + raise Unsupported('v_readfirstlane_b32 broadcast followed by a branch target at %#x' % self.pc) + if self.first_slots >= RFL_FIRST_SLOTS: + raise Unsupported('more than %d first-active-lane v_readfirstlane_b32 reads' % RFL_FIRST_SLOTS) + k = self.first_slots + self.first_slots += 1 + self.emit('x2w_rfv[%d][tid] = %s;' % (k, self.u(ops[1]))) + self.emit('x2w_rfe[%d][tid] = exec & 1u;' % k) + self.sym.pop(dst[1], None) + self.used_s.add(dst[1]) + read = 's%d = x2w_rfirst(%du, wbase);' % (dst[1], k) + if not edge: + self.pending.append(read) + self.tainted.discard('s%d' % dst[1]) + self.au.pop('s%d' % dst[1], None) + self.au_xs.pop('s%d' % dst[1], None) + self.lds_written_in_phase = False + return ('barrier', 'rfl-edge', read) if edge else ('barrier',) + + def op_s_load_dwordx4(self, ops, mods, count=4): + first = len(self.pipe.heapvars) + result = super().op_s_load_dwordx4(ops, mods, count) + if len(self.pipe.heapvars) == first + 1: + self.__dict__.setdefault('_descriptor_loads', {})[self.pc] = first + return result + + def copied_heap_descriptor(self, regs): + sources = list(range(regs[1], regs[2] + 1)) + if len(sources) not in (4, 8) or max(sources) >= 106: + return None + if not hasattr(self, '_copy_pc'): + self._copy_pc = {off: i for i, (off, _, _, _) in enumerate(self.ins)} + targets = self.branch_targets() + for i in range(self._copy_pc[self.pc] - 1, -1, -1): + off, _, name, asm = self.ins[i] + if self.ins[i + 1][0] in targets or name.startswith(('s_branch', 's_cbranch', 's_endpgm')): + break + writes = self.pair_writes(name, asm) + if writes.isdisjoint(sources): + continue + ops = parse(asm)[1] + dst = reg_range(ops[0]) + if off in getattr(self, '_descriptor_loads', {}): + if dst and sources == list(range(dst[1], dst[2] + 1)): + return ('heapdyn', self._descriptor_loads[off]), 0 + break + if name not in ('s_mov_b32', 's_mov_b64') or not dst or dst[0] != 's': + break + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[2] >= 106 or src[2] - src[1] != dst[2] - dst[1]: + break + sources = [src[1] + n - dst[1] if n in writes else n for n in sources] + return None + + def descriptor(self, tok): + try: + return super().descriptor(tok) + except Unsupported: + regs = reg_range(tok) + copied = self.copied_heap_descriptor(regs) if regs and regs[0] == 's' else None + if copied is None: + raise + return copied + + def op_s_buffer_load_dword(self, ops, mods, count=1): + """As the pipeline translator, plus: the offset is read once before the destination is written (the + title's `s_buffer_load_dwordx2 s[4:5], s[16:19], s4` overwrote s4 before the second word), the + instruction's offset:N is added, and the address is dword aligned (the hardware ignores bits 1:0).""" + G.smem_imm_refuse('s_buffer_load', ops, mods) + desc = reg_range(ops[1]) + origin = self.sym.get(desc[1]) if desc else None + if origin and origin[0] == 'code_lo': + return self.scalar_literal_load(ops, mods, count, desc, origin[1]) + extra = 0 + for m in mods: + if m.startswith('offset:'): + extra += int(m[7:], 0) + else: + raise Unsupported('s_buffer_load with %s' % m) + dst = reg_range(ops[0]) + buf = self.pipe.resource(self.descriptor(ops[1]), 'buf') + fixed = re.fullmatch(r'0x[0-9a-f]+|\d+', ops[2]) + if fixed: + base = '%du' % ((int(ops[2], 0) + extra) & ~3) + else: + self.emit('a = (%s + %du) & ~3u;' % (self.u(ops[2]), extra)) + base = 'a' + for i in range(count): + self.set_s(dst[1] + i, '%s.Load(%s + %d)' % (buf, base, 4 * i)) + if fixed: + self.sym[dst[1] + i] = ('fixed_buffer_word',) + + # Typed buffer formats the pipeline translator's table lacks. SNORM: max(x / (2^(n-1) - 1), -1) (RDNA 2 ISA + # data-format conversion). 2_10_10_10 lists fields from the most significant: x is bits 9:0 and w bits 31:30 + # (Mesa gfx10_format_table.py maps R10G10B10A2 to 2_10_10_10). + MESH_FORMATS = { + 'BUF_FMT_16_16_SNORM': ('ldu({0}, a)', ['U(max(float(asint(w << 16) >> 16) / 32767.0, -1.0))', + 'U(max(float(asint(w) >> 16) / 32767.0, -1.0))', '0u', 'U(1.0)']), + 'BUF_FMT_16_16_16_16_SNORM': ('ldu({0}, a)', ['U(max(float(asint(w << 16) >> 16) / 32767.0, -1.0))', + 'U(max(float(asint(w) >> 16) / 32767.0, -1.0))', + 'U(max(float(asint(ldu({0}, a + 4) << 16) >> 16) / 32767.0, -1.0))', + 'U(max(float(asint(ldu({0}, a + 4)) >> 16) / 32767.0, -1.0))']), + 'BUF_FMT_16_16_16_16_UNORM': ('ldu({0}, a)', ['U((w & 65535) / 65535.0)', 'U((w >> 16) / 65535.0)', + 'U((ldu({0}, a + 4) & 65535) / 65535.0)', + 'U((ldu({0}, a + 4) >> 16) / 65535.0)']), + 'BUF_FMT_8_8_8_8_SNORM': ('ldu({0}, a)', ['U(max(float(asint(w << 24) >> 24) / 127.0, -1.0))', + 'U(max(float(asint(w << 16) >> 24) / 127.0, -1.0))', + 'U(max(float(asint(w << 8) >> 24) / 127.0, -1.0))', + 'U(max(float(asint(w) >> 24) / 127.0, -1.0))']), + 'BUF_FMT_2_10_10_10_UNORM': ('ldu({0}, a)', ['U((w & 1023) / 1023.0)', 'U(((w >> 10) & 1023) / 1023.0)', + 'U(((w >> 20) & 1023) / 1023.0)', 'U((w >> 30) / 3.0)']), + # integer formats: the register gets the integer; missing components read 0, w reads 1 (as the float + # formats' 1.0) + 'BUF_FMT_8_8_8_8_UINT': ('ldu({0}, a)', ['w & 255u', '(w >> 8) & 255u', '(w >> 16) & 255u', 'w >> 24']), + 'BUF_FMT_8_8_UINT': ('ldu({0}, a)', ['w & 255u', '(w >> 8) & 255u', '0u', '1u']), + 'BUF_FMT_16_16_UINT': ('ldu({0}, a)', ['w & 65535u', 'w >> 16', '0u', '1u']), + 'BUF_FMT_16_UINT': ('ldu({0}, a)', ['w & 65535u', '0u', '0u', '1u']), + 'BUF_FMT_16_16_16_16_UINT': ('ldu({0}, a)', ['w & 65535u', 'w >> 16', 'ldu({0}, a + 4) & 65535u', + 'ldu({0}, a + 4) >> 16']), + 'BUF_FMT_32_UINT': ('ldu({0}, a)', ['w', '0u', '0u', '1u']), + 'BUF_FMT_32_32_UINT': ('ldu({0}, a)', ['w', 'ldu({0}, a + 4)', '0u', '1u']), + 'BUF_FMT_32_32_32_32_UINT': ('ldu({0}, a)', ['w', 'ldu({0}, a + 4)', 'ldu({0}, a + 8)', 'ldu({0}, a + 12)']), + } + + def tbuffer(self, ops, mods, count): + formats = [m for m in mods if m.startswith('format:')] + fmt = formats[0][8:-1] if formats else None + if fmt not in self.MESH_FORMATS: + return super().tbuffer(ops, mods, count) + dst = reg_range(ops[0]) + buf, address = self.buffer_address(ops, [m for m in mods if not m.startswith('format:')]) + self.emit('a = %s;' % address) + load, comps = self.MESH_FORMATS[fmt] + self.emit('w = %s;' % load.format(buf)) + for i in range(count): + self.set_v(dst[1] + i, comps[i].format(buf)) + + def export(self, asm): + m = re.fullmatch(r'exp (\w+) (.*?)((?: done| compr| vm)*)', asm) + if not m: + raise Unsupported('export form %r' % asm) + target, vals = m.group(1), [v.strip() for v in m.group(2).split(',')] + if target in ('prim', 'target_20'): + if vals[0] == 'off' or any(v != 'off' for v in vals[1:]) or 'compr' in m.group(3): + raise Unsupported('primitive export form %r' % asm) + self.exported_prim = True + self.emit('if (exec & 1) { x2w_prim = %s; }' % self.u(vals[0])) + return None + if target == 'pos1' and self.pipe.vs_out_cntl is None: + # what pos1 carries (misc vector or clip/cull distances, and which channels) is pipeline state + raise Unsupported('mesh export target pos1 without PA_CL_VS_OUT_CNTL (request .vsout)') + if target not in ('pos0', 'pos1') and not target.startswith('param'): + raise Unsupported('mesh export target %s' % target) + before = len(self.lines) + self.kind = 'vs' # the base export only accepts pos/param outside a pixel stage + try: + super().export(asm) + finally: + self.kind = 'ms' + body = self.lines[before:] + del self.lines[before:] + self.lines.append('if (exec & 1) { %s }' % ' '.join(body)) + self.exported_vertex = True + return None + + +for _op in ('add', 'sub', 'subrev'): + for _ci in ('', '_ci'): + _name = 'v_%s_co%s_u32' % (_op, _ci) + setattr(MeshStage, 'op_' + _name, lambda self, ops, mods, _n=_name: self.carry_op(_n, ops, mods)) + + +def const_heap_sampler(stage, tok): + """'qh[<entry>]' for a sampler operand whose four words are one sampler-heap entry loaded at a constant byte + offset (`s_load_dwordx4 s[..], s[<sampler heap>], 0x410`: a fixed entry of the title's bound sampler heap, as + the run programs read it), else None. + + The same table and manifest contract as the run-time offset form (gfx2hlsl heap_sampler; `smpheap 2048 1 + fallback 2047`: entry n = the title's heap entry at byte 16 * n, an unaligned or out-of-range offset takes the + fallback entry), so the stand-in binds it as for a draw. Opt-in with X2W_SAMPLER_HEAP=1 as that form is. + Refused: words edited in place after the load, or words from different loads.""" + r = reg_range(tok) + if not r or r[0] != 's' or r[2] - r[1] != 3: + return None + first = stage.sym.get(r[1]) + if not first or first[0] != 'desc' or first[1] != ('smpheap',) or first[2] is None: + return None + if not stage.pipe.sampler_heap: + raise Unsupported('sampler from the sampler heap at constant offset %#x (X2W_SAMPLER_HEAP=1 binds the heap)' + % (first[2] + 4 * first[3])) + if any(stage.sym.get(r[1] + i) != ('desc', first[1], first[2], first[3] + i) for i in range(4)): + raise Unsupported('sampler operand %s mixes sampler heap words' % tok) + if (first[1], first[2]) in stage.pipe.modified: + raise Unsupported('sampler heap entry at %#x edited in the shader' % (first[2] + 4 * first[3])) + offset = first[2] + 4 * first[3] + entry = offset >> 4 if offset % 16 == 0 and offset < 16 * G.SAMPLER_HEAP_FALLBACK else G.SAMPLER_HEAP_FALLBACK + stage.pipe.uses_sampler_heap = True + return 'qh[%du]' % entry + + +class MeshPixelStage(G.Stage): + """The pixel stage of a mesh pipeline: the base pixel stage plus constant sampler-heap entries.""" + + def __init__(self, pipe, kind, code): + self.require_counted_search = os.environ.get('X2W_PS_COUNTED_SEARCH') == '1' + super().__init__(pipe, kind, code) + + def translate(self): + self.resolve_loaded_vcc_words() + super().translate() + + def resolve_loaded_vcc_words(self): + targets = {int(parse(asm)[1][0].split('_')[1], 16) for _, _, name, asm in self.ins + if name.startswith('s_cbranch') or name == 's_branch'} + loaded = set() + for index, (pc, size, name, asm) in enumerate(self.ins): + if pc in targets: + loaded.clear() + if name in ('s_buffer_load_dwordx4', 's_buffer_load_dwordx8', 's_buffer_load_dwordx16'): + dst = reg_range(parse(asm)[1][0]) + loaded = {half for half in (106, 107) if dst and dst[0] == 's' and dst[1] <= half <= dst[2]} + continue + if not loaded: + continue + # Only single-vector-destination arithmetic preserves both scalar words. + if re.fullmatch(r'v_(rcp|mul|add|sub|subrev|fma)_f32(?:_e32|_e64)?', name): + def word(match): + reg = 106 if match[0] == 'vcc_lo' else 107 + return 's%d' % reg if reg in loaded else match[0] + self.ins[index] = pc, size, name, re.sub(r'\bvcc_(?:lo|hi)\b', word, asm) + elif name not in ('s_waitcnt', 's_nop', 's_and_saveexec_b32', 's_or_saveexec_b32', 'image_sample_lz'): + loaded.clear() + elif 'saveexec' in name: + dst = reg_range(parse(asm)[1][0]) + if not dst or dst[0] != 's' or dst[2] >= 106: + loaded.clear() + + def heap_sampler(self, tok): + return super().heap_sampler(tok) or const_heap_sampler(self, tok) + + +class MeshPipeline(G.Pipeline): + """Mesh + pixel pipeline. ps_code None: the mesh stage alone (coverage runs; params = what it exports).""" + + def __init__(self, ms_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), user_sgpr=MESH_USER_SGPR, + ps_hw_inputs=None, vs_out_cntl=None): + self.root = G.parse_root(root_blob) + # First user SGPR: s16 for the run programs (measured, real roots). Archive programs (offline, synthesized + # root) may start at s8: callers pass entry_sgpr(code) together with synth_root(code). + self.user_sgpr = user_sgpr + # PA_CL_VS_OUT_CNTL of the pipeline (request .vsout; regblob .vsregs u32 at +0x98, +0x54 in mesh blocks), + # or None: what a pos1 export carries (G.clip_vector_width). None refuses pos1. + self.vs_out_cntl = vs_out_cntl + # Lane-mask SCCs to publish per wave: found by translating, refusing at the branch with the offsets of the + # mask instructions the SCC comes from (LaneScc), and translating again with those published. + self.wave_vcc = os.environ.get('X2W_MESH_WAVE_VCC') == '1' + self.scc_publish = frozenset() + for _ in range(8): + try: + self.build(ms_code, ps_code, sampler_heap, rtv_formats, ps_hw_inputs) + return + except LaneScc as refusal: + if not LANE_SCC or not refusal.origins or refusal.origins <= self.scc_publish: + raise Unsupported(str(refusal)) + if min(refusal.origins) < 0: + raise Unsupported('%s (through a non-mask op on a lane mask at %#x)' + % (refusal, -min(refusal.origins) - 1)) + self.scc_publish |= refusal.origins + raise Unsupported('lane-mask SCC: no fixed point after 8 translations') + + def build(self, ms_code, ps_code, sampler_heap, rtv_formats, ps_hw_inputs=None): + # Fields of G.Pipeline.__init__ (which this does not call: it builds a vertex stage) that newer base + # translators read. The draw lowerings (manifest `heap 1`, `udsrc bufword3`, `uav`) are named in + # X2W_DRAW_FEATURES as for draws (pstrans gfx2hlsl.draw_features); a base without them keeps refusing. + self.features = G.draw_features() if hasattr(G, 'draw_features') else frozenset() + self.heapvars = [] + self.heapwords = False # x2w_hword used (manifest `heapwords 1`) + self.rw_keys = frozenset() + # the pixel stage's SPI inputs (SPI_PS_INPUT_ENA/ADDR, request .psin), as for draws + self.spi_inputs(ps_hw_inputs) + self.quad_ops = True # the pixel stage compiles with dxc ps_6_0: DPP quad reads (gfx2hlsl Stage.quad_dpp) + self.rtv_formats = rtv_formats + self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap + self.uses_sampler_heap = False + self.resources, self.samplers, self.uds = {}, {}, [] + self.notes = set() + self.modified = set() + self.helper_text = None + self.rect = self.ud(('rect',)) + self.dw_src, self.dw_used, self.dw_text = [], set(), {} # descword placeholders (MeshStage.dw_word) + # A lane-dependent v_readfirstlane_b32 inside a per-lane execz range asks for that range to be run by the + # whole group (NeedGroupRange): translate again from the same state with it added (bounded: each range once). + self.force_group = frozenset() + self.force_first = frozenset() + fresh = copy.deepcopy(self.__dict__) + while True: + try: + self.vs = self.mesh_stage(ms_code) + break + except (NeedGroupRange, NeedFirstValue) as e: + groups, first = self.force_group, self.force_first + if isinstance(e, NeedGroupRange) and e.off not in groups: + groups |= {e.off} + elif isinstance(e, NeedFirstValue) and e.reg not in first and RFL_FIRST: + first |= {e.reg} + else: + raise Unsupported(str(e)) + self.__dict__.clear() + self.__dict__.update(copy.deepcopy(fresh)) + self.force_group, self.force_first = groups, first + # descword placeholders: a word some numeric use reached is an entry value (`udsrc <n> descword <p> <byte>`), + # any other is dead arithmetic and reads 0u + self.dw_text = {k: ('ud%d' % self.ud(src) if k in self.dw_used else '0u') for k, src in enumerate(self.dw_src)} + self.ps = MeshPixelStage(self, 'ps', ps_code) if ps_code is not None else None + self.params = sorted(int(k[5:]) for k in self.vs.exports if k.startswith('param')) + if self.ps is not None: + self.spi_reads() + self.flat = sorted(a for a, how in self.ps.attrs.items() if 'flat' in how) + self.half = sorted(a for a, how in self.ps.attrs.items() if 'half' in how) + self.check_half_reads() + missing = [a for a in self.ps.attrs if a not in self.params] + if missing: + raise Unsupported('pixel stage reads attributes %s the mesh stage does not export' % missing) + else: + self.ps_entry_reads, self.flat, self.half = {}, [], [] + if 'pos' not in self.vs.exports: + raise Unsupported('mesh stage exports no position') + if not self.vs.exported_prim: + raise Unsupported('mesh stage exports no primitive') + + def mesh_stage(self, ms_code): + """The mesh stage, translated again (from the same pipeline state) until every loop head's state is the + join of its edges (MeshStage.loop_settled); refused when that does not settle within LOOP_PASSES.""" + self.loop_seed = {} + before = copy.deepcopy(self.__dict__) + for _ in range(LOOP_PASSES): + try: + return MeshStage(self, ms_code) + except LoopRetry as retry: + seeds = retry.backs + self.__dict__.clear() + self.__dict__.update(copy.deepcopy(before)) + self.loop_seed = seeds + raise Unsupported('loop state does not settle in %d passes' % LOOP_PASSES) + + def dw_sub(self, lines): + """The mesh stage's lines with the descword placeholders replaced (build()).""" + dw = getattr(self, 'dw_text', {}) + if not dw: + return lines + out = [re.sub(r'\bX2W_DW(\d+)\b', lambda m: dw[int(m.group(1))], line) for line in lines] + if any('X2W_DW' in line for line in out): + raise Unsupported('descword placeholder left in the mesh stage') + return out + + def common(self): + if self.helper_text is None: + self.helper_text = '\n'.join(self.dw_sub(self.vs.body()) + (self.ps.body() if self.ps else [])) + return super().common() + + def hlsl_ms(self, dump=False): + """The mesh shader. dump=True (tests only): also store each thread's outputs and the group's allocation + word in RWByteAddressBuffer u0 (per group: 16 bytes header [alloc], then per thread pos, param0..N-1, + primitive word, then the clip distances when pos1 is exported) and give each primitive SV_PrimitiveID = + group * 128 + index.""" + s = self.vs + nparams = max(self.params) + 1 if self.params else 0 + nclip = s.exports.get('clip') or 0 + stride = 4 * (4 + 4 * nparams + 1 + nclip) + out = self.common() + body_text = self.helper_text + if self.heapwords and not any(self.heapvars): + # descriptor words read, but no heap view used as a resource: the base emitted no heap declarations + out += ['ByteAddressBuffer heapmem : register(t0, space1);', + 'uint x2w_vid(uint h) { return heapmem.Load(h) == 0x%08xu ? heapmem.Load(h + 4) : 0xffffffffu; }' + % G.HEAP_TOKEN] + out += [text for name, text in MESH_HELPERS.items() if re.search(r'\b%s\(' % name, body_text)] + out += ['struct MSOut {'] + self.interface(False) + ['};', + 'struct MSPrim { bool cull : SV_CullPrimitive;%s };' % (' uint pid : SV_PrimitiveID;' if dump else '')] + ( + ['RWByteAddressBuffer x2w_dump : register(u0);'] if dump else []) + [ + 'groupshared uint x2w_alloc;'] + ( + ['groupshared uint x2w_rfl[%d][2]; // v_readfirstlane broadcasts, one slot per instruction' % s.broadcasts] + if s.broadcasts else []) + ( + ['groupshared uint x2w_rfv[%d][%d]; // first-active-lane reads: each thread\'s value' % (s.first_slots, GROUP), + 'groupshared uint x2w_rfe[%d][%d]; // ... and its exec bit' % (s.first_slots, GROUP), + '// v_readfirstlane_b32 under a partial exec: the lowest lane of the wave (first thread w0) with its', + '// exec bit set, lane 0 when none is (MeshStage.first_active_broadcast)', + 'uint x2w_rfirst(uint k, uint w0) {', + ' for (uint i = 0u; i < 64u; i++) { if (x2w_rfe[k][w0 + i] != 0u) return x2w_rfv[k][w0 + i]; }', + ' return x2w_rfv[k][w0];', + '}'] if s.first_slots else []) + ( + ['groupshared uint x2w_lds[%d]; // LDS (ds_read / ds_write), dword addressed' % LDS_DWORDS] + if s.lds_used else []) + ( + ['groupshared uint x2w_any[%d][2]; // wave-level execz branches: some lane of the wave active' + % len(s.wave_any)] if s.wave_any else []) + ( + ['groupshared uint x2w_sany[%d][2]; // lane-mask SCCs: some lane of the wave has its result bit set' + % len(s.scc_any)] if s.scc_any else []) + [ + '[outputtopology("triangle")]', + '[numthreads(%d, 1, 1)]' % GROUP, + 'void main(uint tid : SV_GroupIndex, uint3 group : SV_GroupID,', + ' out vertices MSOut verts[%d], out indices uint3 tris[%d], out primitives MSPrim prims[%d]) {' + % (MAX_VERTICES, MAX_PRIMITIVES, MAX_PRIMITIVES), + ' uint gid = group.x, lane = tid & 63u, wave = tid >> 6, wbase = tid & ~63u;', + ' if (tid == 0) x2w_alloc = 0;'] + ( + [' if (tid < %du) x2w_any[tid >> 1][tid & 1u] = 0u;' % (2 * len(s.wave_any))] if s.wave_any else []) + ( + [' if (tid < %du) x2w_sany[tid >> 1][tid & 1u] = 0u;' % (2 * len(s.scc_any))] if s.scc_any else []) + [ + ' GroupMemoryBarrierWithGroupSync();', + ' MSOut o = (MSOut)0;', + ' uint x2w_prim = 0x80000000u;'] + s.used_v.add(5) + flat = re.compile(r'.*o\.fparam(\d+) = ') + body = [] + for line in self.dw_sub(s.body()): + # attributes the pixel stage reads only interpolated: drop the flat copy (as hlsl_vs), and the + # binary16 half copies unless it reads them (v_interp_p2_f16) + line = re.sub(r'o\.(f|lo|hi)param(\d+) = [^;]*;', lambda mm: mm.group(0) if int(mm.group(2)) in ( + self.flat if mm.group(1) == 'f' else self.half) else '', line) + body.append(line) + if dump: + # progress markers (tests only): header word 1 = 1 at entry, word 2 = phases completed + marked, phase = [], 0 + for line in body: + marked.append(line) + if line.strip() == 'GroupMemoryBarrierWithGroupSync();' and line.startswith(' G'): + phase += 1 + marked.append(' if (tid == 0) x2w_dump.Store(gid * %du + 8u, %du);' % (16 + GROUP * stride, phase)) + body = [' if (tid == 0) x2w_dump.Store(gid * %du + 4u, 1u);' % (16 + GROUP * stride)] + marked + out += s.declarations() + [' v5 = gid * %du + tid; // inferred fast-launch vertex id' % GROUP] + body + out += [' GroupMemoryBarrierWithGroupSync();', + ' uint nv = min(x2w_alloc & 0x7ffu, %du), np = min((x2w_alloc >> 12) & 0x7ffu, %du);' % (MAX_VERTICES, MAX_PRIMITIVES), + ' SetMeshOutputCounts(nv, np);', + ' if (tid < nv) verts[tid] = o;', + ' if (tid < np) {', + ' uint3 t = uint3(x2w_prim & 0x1ffu, (x2w_prim >> 10) & 0x1ffu, (x2w_prim >> 20) & 0x1ffu);', + ' bool cull = (x2w_prim >> 31) != 0u || t.x >= nv || t.y >= nv || t.z >= nv;', + ' tris[tid] = cull ? uint3(0, 0, 0) : t;', + ' prims[tid].cull = cull;'] + ( + [' prims[tid].pid = gid * %du + tid;' % GROUP] if dump else []) + [ + ' }'] + if dump: + out += [' uint db = gid * %du, tb = db + 16u + tid * %du;' % (16 + GROUP * stride, stride), + ' if (tid == 0) x2w_dump.Store(db, x2w_alloc);', + ' x2w_dump.Store4(tb, asuint(o.pos));'] + out += [' x2w_dump.Store4(tb + %du, asuint(o.param%d));' % (16 + 16 * p, p) for p in range(nparams)] + out += [' x2w_dump.Store(tb + %du, x2w_prim);' % (16 + 16 * nparams)] + if nclip: + out += [' x2w_dump.Store%s(tb + %du, asuint(o.clip0));' % (nclip if nclip > 1 else '', 20 + 16 * nparams)] + out += ['}'] + return '\n'.join(out) + '\n' + + def manifest(self): + text = super().manifest() if self.ps else self.manifest_ms_only() + if self.heapwords: + if not re.search(r'^heap 1$', text, re.M): + text += 'heap 1\n' + text += 'heapwords 1\n' + # the multiply-add rule the result was built with (RUNTIME_NEEDS 8), so mixed caches are detectable + text += 'fma %s\n' % ('exact' if EXACT_FMA else 'precise') + return text + 'stage mesh\nms %d %d %d\n' % (GROUP, MAX_VERTICES, MAX_PRIMITIVES) + + def manifest_ms_only(self): + class _P: # base manifest() reads self.ps.exports for the targets line + exports = {} + saved, self.ps = self.ps, _P() + try: + return G.Pipeline.manifest(self) + finally: + self.ps = saved + + +DXC = os.environ.get('X2W_DXC', r'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\dxc.exe') + + +def compile_hlsl(path, profile, out): + r = subprocess.run([DXC, '-nologo', '-T', profile, '-E', 'main', '-Fo', out, path], capture_output=True, text=True) + return r.returncode, r.stderr + + +def compact_mesh_interface(pipe, ms, ps): + linear = {n for n, uses in pipe.ps.attrs.items() if 'linear' in uses} + fields = re.compile(r'^ float4 param(\d+) : PARAM\1;\n', re.M) + unused = {int(n) for n in fields.findall(ms)} - linear + if not unused: + return ms, ps + def keep(match): + return '' if int(match[1]) in unused else match[0] + ms = re.sub(r'\bo\.param(\d+) = [^;\n]+;', keep, fields.sub(keep, ms)) + return ms, fields.sub(keep, ps) + + +def translate_to(out_dir, key, ms_code, ps_code, root_blob, check=True, rtv_formats=(), rtv_request='', + user_sgpr=MESH_USER_SGPR, ps_hw_inputs=None, vs_out_cntl=None): + """Writes <key>.ms.hlsl, <key>.ps.hlsl, the .cso files and <key>.txt (last), or <key>.fail. + ps_hw_inputs: the pixel stage's (SPI_PS_INPUT_ENA, SPI_PS_INPUT_ADDR[, launch FLOAT_MODE]), or None (entry-VGPR + reads refused). The FLOAT_MODE (SPI_SHADER_PGM_RSRC1_PS bits 19:12) is the optional third .psin field. + vs_out_cntl: the pipeline's PA_CL_VS_OUT_CNTL (what a pos1 export carries), or None (pos1 refused).""" + name = os.path.join(out_dir, '%016x' % key) + try: + pipe = MeshPipeline(ms_code, ps_code, root_blob, rtv_formats=rtv_formats, user_sgpr=user_sgpr, + ps_hw_inputs=ps_hw_inputs if ps_code is not None else None, vs_out_cntl=vs_out_cntl) + if pipe.ps_entry_reads: + reg, off = min(pipe.ps_entry_reads.items(), key=lambda item: item[1]) + raise Unsupported('pixel stage reads entry VGPR v%d (an SPI input; layout not in the request) at %#x' % (reg, off)) + ms = pipe.hlsl_ms() + ps = pipe.hlsl_ps() if ps_code is not None else None + manifest = pipe.manifest() + (rtv_request + '\n' if rtv_request else '') + except Unsupported as reason: + open(name + '.fail', 'w').write(str(reason) + '\n') + return 'unsupported: %s' % reason + open(name + '.ms.hlsl', 'w').write(ms) + if ps is not None: + open(name + '.ps.hlsl', 'w').write(ps) + if check: + # The pixel stage is compiled with dxc too: a pipeline with a DXIL mesh stage takes DXIL stages only. + for stage, profile, present in (('ms', 'ms_6_5', True), ('ps', 'ps_6_0', ps is not None)): + if not present: + continue + code, err = compile_hlsl(name + '.%s.hlsl' % stage, profile, name + '.%s.cso' % stage) + if code and stage == 'ms' and ps is not None and 'vertex plus primitive output size' in err: + ms, ps = compact_mesh_interface(pipe, ms, ps) + open(name + '.ms.hlsl', 'w').write(ms) + open(name + '.ps.hlsl', 'w').write(ps) + code, err = compile_hlsl(name + '.ms.hlsl', profile, name + '.ms.cso') + if code: + open(name + '.fail', 'w').write('dxc %s: %s\n' % (stage, err[-2000:])) + return 'dxc %s failed: %s' % (stage, err.strip().splitlines()[0] if err.strip() else '?') + temporary = '%s.txt.%d.tmp' % (name, os.getpid()) + with open(temporary, 'w') as result: + result.write(manifest) + os.replace(temporary, name + '.txt') + return 'ok' + + +def is_mesh(code): + """NGG mesh stage: it sends GS_ALLOC_REQ and exports a primitive.""" + text = [x[3] for x in G.decode(G.strip_header(code))] + return any(t == 's_sendmsg 0x9' for t in text) and any(re.match(r'exp (prim|target_20)', t) for t in text) + + +def translate_request(out_dir, key): + """A mesh pipeline request req_<key>.{a,b,root}: whichever blob is the mesh stage, the other the pixel stage. + + An RTV variant (the draw path's contract, gfx2hlsl.translate_request; the mesh runtime publishes it when a bound + target is integer or 32-bit float, d3d12_mesh.inl): req_<key>.rtv holds `rtv1 <base key> <DXGI formats>` with + key = fnv(that text); the blobs are the base request's, checked against the base key; the pixel exports take + the target formats (Pipeline.mrt_kind) and the manifest carries the rtv1 line. A variant of a depth-only + pipeline is refused (the runtime takes the base translation for any target there).""" + base = os.path.join(out_dir, 'req_%016x' % key) + request, formats, base_key = '', (), key + if os.path.isfile(base + '.rtv'): + try: + with open(base + '.rtv', encoding='ascii') as file: + request = file.read(256) + except (OSError, UnicodeError) as error: + return 'unreadable: %s' % error + if not re.fullmatch(r'rtv1 [0-9]{1,20}(?: [0-9]{1,10}){1,8}', request) or G.fnv(request.encode('ascii')) != key: + return 'unsupported: invalid RTV variant request' + base_key, *formats = map(int, request.split()[1:]) + if base_key > 0xffffffffffffffff or any(fmt > 0xffffffff for fmt in formats): + return 'unsupported: invalid RTV variant values' + formats = tuple(formats) + base = os.path.join(out_dir, 'req_%016x' % base_key) + try: + a, b, root = (open(base + ext, 'rb').read() for ext in ('.a', '.b', '.root')) + except OSError as error: + return 'unreadable: %s' % error + if request: + if G.pipeline_key(a, b, root) != base_key: + return 'unsupported: RTV variant source key mismatch' + if not (a and b): + return 'unsupported: RTV variant of a mesh pipeline without a pixel stage' + rtv = {'rtv_formats': formats, 'rtv_request': request} if request else {} + # optional req_<key>.vsout `pa_cl_vs_out_cntl 1 <hex8>` (not part of the key): what a pos1 export carries + try: + cntl = G.read_vs_out(base + '.vsout') + except Unsupported as reason: + return 'unsupported: %s' % reason + if not a and b and is_mesh(b): + return translate_to(out_dir, key, b, None, root, vs_out_cntl=cntl) # depth-only mesh pipeline (no pixel stage) + try: + # the pixel stage's SPI inputs: req_<key>.psin (gfx2hlsl.read_ps_inputs format), else none + ps_hw_inputs = G.read_ps_inputs(base + '.psin') + except Unsupported as reason: + return 'unsupported: %s' % reason + if a and b and is_mesh(b) and not is_mesh(a): + return translate_to(out_dir, key, b, a, root, ps_hw_inputs=ps_hw_inputs, vs_out_cntl=cntl, **rtv) + if a and b and is_mesh(a) and not is_mesh(b): + return translate_to(out_dir, key, a, b, root, ps_hw_inputs=ps_hw_inputs, vs_out_cntl=cntl, **rtv) + return 'not a mesh pipeline' + + +# ---- root signature synthesis for coverage runs over the archive (no real root blob there) ---------------------- +def synth_root(*codes): + """A root signature blob whose SGPR layout from s16 (MESH_USER_SGPR) matches how the programs (the stages of one pipeline, which + share the layout) use their entry SGPRs: a register read as a 32-bit table pointer (with a zero high word) + becomes a descriptor table, a pair used as a 64-bit base a root SRV, everything else 32-bit constants. + COVERAGE ONLY: the title's real root signature comes with the request.""" + tables, pairs, used = set(), set(), set() + for code in codes: + if code: + synth_scan(code, tables, pairs, used) + return synth_layout(tables, pairs, used, min(entry_sgpr(c) for c in codes if c)) + + +def entry_sgpr(code): + """First user SGPR for a program without a real root: 8 if it reads any of s8..s15 before writing it (the + archive programs), else MESH_USER_SGPR (16, the run programs: s8..s15 are written first). Straight-line scan + up to the first branch; COVERAGE ONLY.""" + written = set() + for off, n, name, asm in G.decode(G.strip_header(code)): + _, ops, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', name) + for t in ops[1:]: + if any(8 <= r < MESH_USER_SGPR and r not in written for r in scalar_regs(t)): + return 8 + if base.startswith(('s_branch', 's_cbranch', 's_endpgm')): + break + dst = reg_range(ops[0]) if ops else None + if dst and dst[0] == 's' and not base.startswith(NO_DEST): + written.update(range(dst[1], dst[2] + 1)) + return MESH_USER_SGPR + + +def synth_scan(code, tables, pairs, used): + ins = G.decode(G.strip_header(code)) + origin = {} # current register -> entry register it holds + zero = set() + for r in range(8, 64): + origin[r] = r + for off, n, name, asm in ins: + _, ops, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', name) + for t in ops[1:]: + for r in scalar_regs(t): + if r in origin: + used.add(origin[r]) + if base.startswith(('s_load', 's_buffer_load', 'buffer_', 'tbuffer_', 'image_')): + sb = ops[1] if base.startswith(('s_load', 's_buffer_load')) else (ops[2] if len(ops) > 2 else '') + rr = reg_range(sb) + if rr and rr[0] == 's': + lo = origin.get(rr[1]) + if lo is not None and (rr[1] + 1) in zero and base.startswith('s_load'): + tables.add(lo) + elif lo is not None and origin.get(rr[1] + 1) == lo + 1: + pairs.add(lo) + dst = reg_range(ops[0]) if ops else None + if dst and dst[0] == 's' and base.startswith('s_') and not base.startswith(NO_DEST): + src = reg_range(ops[1]) if len(ops) > 1 else None + if base == 's_bitset1_b32': + continue # sets one bit in place (descriptor word 1 from a pointer's high word): same origin + for r in range(dst[1], dst[2] + 1): + origin.pop(r, None) + zero.discard(r) + if base == 's_mov_b32' and src and src[0] == 's' and src[1] in origin: + origin[dst[1]] = origin[src[1]] + elif base in ('s_or_b32', 's_bitset1_b32') and src and src[0] == 's' and src[1] in origin: + origin[dst[1]] = origin[src[1]] # descriptor word 1 built from a pointer's high word + elif base == 's_mov_b32' and ops[1] == '0': + zero.add(dst[1]) + + +def synth_layout(tables, pairs, used, start=MESH_USER_SGPR): + params, r = [], start + used = {u for u in used if u >= start} + if start == MESH_USER_SGPR and used & {23, 24}: + # s23/s24 are the resource and sampler heaps after the dominant real layout (sampled real roots: 3 tables, + # a root SRV, 2 constants, heap flags 0xc00 in ~87%); such a program cannot be expressed by the scan below + return root_blob([(0, None), (0, None), (0, None), (3, None), (1, 2)], 0xc00) + top = max(used | {start - 1}) + 1 + while r < top: + if r in tables: + params.append((0, None)) + r += 1 + elif r in pairs: + params.append((3, None)) + r += 2 + else: + n = 1 + while r + n < top and r + n not in tables and r + n not in pairs: + n += 1 + params.append((1, n)) + r += n + return root_blob(params) + + +def root_blob(params, flags=0): + """DXBC container with an RTS0 part (version 2) for params [(type, count)]: type 0 table (no ranges), 1 constants, + 3 root SRV.""" + head = 24 + body = bytearray() + extra = bytearray() + poff = head + eoff = head + 12 * len(params) + for i, (t, count) in enumerate(params): + if t == 1: + body += struct.pack('<3I', t, 0, eoff + len(extra)) + extra += struct.pack('<3I', i, 0, count) + elif t == 0: + body += struct.pack('<3I', t, 0, eoff + len(extra)) + extra += struct.pack('<2I', 0, eoff + len(extra) + 8) + else: + body += struct.pack('<3I', t, 0, eoff + len(extra)) + extra += struct.pack('<3I', i, 0, 0) + rts = struct.pack('<6I', 2, len(params), poff, 0, eoff + len(extra), flags) + bytes(body) + bytes(extra) + part = b'RTS0' + struct.pack('<I', len(rts)) + rts + total = 32 + 4 + len(part) + return b'DXBC' + b'\0' * 16 + struct.pack('<III', 1, total, 1) + struct.pack('<I', 36) + part + + +def main(): + if len(sys.argv) >= 3 and sys.argv[1] == '--requests': + out_dir = sys.argv[2] + for name in sorted(os.listdir(out_dir)): + m = re.fullmatch(r'req_([0-9a-f]{16})\.a', name) + if not m or os.path.exists(os.path.join(out_dir, '%s.txt' % m.group(1))): + continue + result = translate_request(out_dir, int(m.group(1), 16)) + if result != 'not a mesh pipeline': + print('%s: %s' % (m.group(1), result)) + return + if len(sys.argv) >= 4 and sys.argv[1] == '--ms-only': + # --ms-only <out_dir> <ms.bin> [...]: the mesh stage alone with a synthesized root (coverage) + out_dir = sys.argv[2] + os.makedirs(out_dir, exist_ok=True) + for i, path in enumerate(sys.argv[3:]): + code = open(path, 'rb').read() + print('%s: %s' % (os.path.basename(path), translate_to(out_dir, i, code, None, synth_root(code), + user_sgpr=entry_sgpr(code)))) + return + print(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/mesh_harness.cpp b/tools/startup/mesh_harness.cpp new file mode 100644 index 0000000000..61963aea94 --- /dev/null +++ b/tools/startup/mesh_harness.cpp @@ -0,0 +1,560 @@ +// Offline harness for translated mesh shaders (startup tools): runs one ms_6_5 + ps_6_x pair with DispatchMesh on +// WARP (default) or the first hardware adapter (--hw), with root constants b0, root SRVs t0..tN-1, a dump UAV u0 and +// a primitive-hit UAV u1 as described by a small text file, and writes the two UAVs back. +// +// usage: mesh_harness <cfg.txt> [--hw] [--debug] +// cfg lines: ms <cso> | ps <cso> | groups <n> | consts <n> <v0> ... | srv <file> (t0, t1, ... in order) | +// dump <bytes> | hits <bytes> | out <prefix> -> writes <prefix>.dump, <prefix>.hits +// Exit 77 (capability skip) when the adapter has no mesh shader support. +// +// Resource-heap programs (manifest `heap 1`, `heapwords 1`; gfx2hlsl HEAP_KINDS, RUNTIME_NEEDS.md 6.3) add: +// heapmem <file> | vinfo <file> | vdesc <file> t0, t1, t2 in space1 (title heap memory with the X2WV token +// + view id per 32-byte slot; 16 bytes per id; 32 bytes per id) +// blob <file> bytes the view lines below point into +// hbuf <id> <offset> <bytes> raw buffer view of blob[offset, offset + bytes) (offset 16-aligned) +// htex1d <id> <dxgi> <width> <offset> Texture1D of blob texels from offset, one level +// htex2d <id> <dxgi> <width> <height> <offset> Texture2D, rows packed (width * texel bytes apart) +// The three space1 buffers are bounded raw views in ONE descriptor table (the runtime binds them as root SRVs; a +// root SRV has no bounds check, MESH.md 4.4). The view-id region is a second table: 8 + 8 * 90000 descriptors, +// the five arrays t0 in spaces 2..6 (Texture2D, Texture2DArray, Texture3D, Texture1D, raw buffer) all start at +// offset 0, as the runtime's create_draw_root (each array is indexed 8 + 8 * id + kind, so the kinds never meet). +// Slots 0..7 (the empty views x2w_hix falls back to) and all kinds of every listed id hold null views; the +// listed views overwrite theirs. The region range is DESCRIPTORS_VOLATILE: the slots of unlisted ids stay unset. +// +// Build (x64 Developer prompt): cl /nologo /EHsc /O2 /std:c++17 mesh_harness.cpp d3d12.lib dxgi.lib +#include <windows.h> +#include <d3d12.h> +#include <dxgi1_6.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <sstream> +#include <string> +#include <vector> + +#define CHECK(x) \ + do { \ + HRESULT hr_ = (x); \ + if (FAILED(hr_)) { \ + std::fprintf(stderr, "%s failed: 0x%08lx (line %d)\n", #x, hr_, __LINE__); \ + dump_messages(); \ + return 1; \ + } \ + } while (0) + +template <typename T> struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T** operator&() { return &p; } + T* operator->() const { return p; } + operator T*() const { return p; } +}; + +static ID3D12InfoQueue* g_info = nullptr; + +static void dump_messages() { + if (!g_info) return; + UINT64 n = g_info->GetNumStoredMessages(); + for (UINT64 i = 0; i < n; ++i) { + SIZE_T size = 0; + g_info->GetMessage(i, nullptr, &size); + std::vector<char> buf(size); + auto* m = reinterpret_cast<D3D12_MESSAGE*>(buf.data()); + g_info->GetMessage(i, m, &size); + std::printf("debug-layer: severity %d id %d: %.*s\n", (int)m->Severity, (int)m->ID, + (int)m->DescriptionByteLength, m->pDescription); + } + std::printf("debug-layer messages: %llu\n", (unsigned long long)n); +} + +static std::vector<char> read_file(const std::string& path) { + std::ifstream f(path, std::ios::binary); + return std::vector<char>((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); +} + +template <D3D12_PIPELINE_STATE_SUBOBJECT_TYPE T, typename D> struct alignas(void*) Sub { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = T; + D data{}; +}; + +struct MeshStream { + Sub<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, ID3D12RootSignature*> root; + Sub<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE> ms; + Sub<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE> ps; + Sub<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, D3D12_BLEND_DESC> blend; + Sub<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, D3D12_RASTERIZER_DESC> raster; + Sub<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_DEPTH_STENCIL_DESC> depth; + Sub<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, D3D12_RT_FORMAT_ARRAY> rtv; + Sub<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC> sample; + Sub<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, UINT> mask; +}; + +static D3D12_RESOURCE_DESC buffer_desc(UINT64 size, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = size < 16 ? 16 : (size + 15) & ~15ull; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + return d; +} + +static D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3D12_RESOURCE_STATES b) { + D3D12_RESOURCE_BARRIER x{}; + x.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + x.Transition.pResource = r; + x.Transition.StateBefore = a; + x.Transition.StateAfter = b; + x.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + return x; +} + +typedef LONG(WINAPI* RtlGetVersionFn)(OSVERSIONINFOW*); + +int main(int argc, char** argv) { + if (argc < 2) { + std::fprintf(stderr, "usage: mesh_harness <cfg.txt> [--hw] [--debug]\n"); + return 2; + } + bool hw = false, debug = false; + for (int i = 2; i < argc; ++i) { + hw |= std::string(argv[i]) == "--hw"; + debug |= std::string(argv[i]) == "--debug"; + } + std::string ms_path, ps_path, out; + UINT groups = 1; + std::vector<UINT> consts; + std::vector<std::string> srvs; + UINT64 dump_bytes = 16, hits_bytes = 16; + std::string heap_files[3], blob_path; // heapmem, vinfo, vdesc + struct HeapView { + UINT id = 0, kind = 4; // gfx2hlsl HEAP_KINDS slot: 0 tex2d, 3 tex1d, 4 buf + UINT dxgi = 0, width = 0, height = 1; + UINT64 offset = 0, bytes = 0; + }; + std::vector<HeapView> hviews; + { + std::ifstream cfg(argv[1]); + std::string line; + while (std::getline(cfg, line)) { + std::istringstream s(line); + std::string key; + s >> key; + if (key == "ms") std::getline(s >> std::ws, ms_path); + else if (key == "ps") std::getline(s >> std::ws, ps_path); + else if (key == "groups") s >> groups; + else if (key == "consts") { UINT n; s >> n; consts.resize(n); for (auto& c : consts) s >> c; } + else if (key == "srv") { std::string p; std::getline(s >> std::ws, p); srvs.push_back(p); } + else if (key == "dump") s >> dump_bytes; + else if (key == "hits") s >> hits_bytes; + else if (key == "out") std::getline(s >> std::ws, out); + else if (key == "heapmem") std::getline(s >> std::ws, heap_files[0]); + else if (key == "vinfo") std::getline(s >> std::ws, heap_files[1]); + else if (key == "vdesc") std::getline(s >> std::ws, heap_files[2]); + else if (key == "blob") std::getline(s >> std::ws, blob_path); + else if (key == "hbuf") { HeapView v; s >> v.id >> v.offset >> v.bytes; hviews.push_back(v); } + else if (key == "htex1d") { HeapView v; v.kind = 3; s >> v.id >> v.dxgi >> v.width >> v.offset; hviews.push_back(v); } + else if (key == "htex2d") { HeapView v; v.kind = 0; s >> v.id >> v.dxgi >> v.width >> v.height >> v.offset; hviews.push_back(v); } + else if (!key.empty() && key[0] != '#') { std::fprintf(stderr, "cfg: unknown line '%s'\n", line.c_str()); return 2; } + } + } + const bool heap = !heap_files[0].empty(); + if (heap && (heap_files[1].empty() || heap_files[2].empty())) { std::fprintf(stderr, "cfg: heapmem needs vinfo and vdesc\n"); return 2; } + constexpr UINT heap_ids = 90000, region_size = 8 + 8 * heap_ids; // gfx2hlsl HEAP_IDS, array size 8 + 8 * HEAP_IDS + for (const auto& v : hviews) + if (v.id >= heap_ids || (v.kind == 4 && (v.offset & 15))) { std::fprintf(stderr, "cfg: bad view id %u / offset %llu\n", v.id, v.offset); return 2; } + if (consts.empty()) consts.push_back(0); + + OSVERSIONINFOW os{sizeof(os)}; + if (auto fn = (RtlGetVersionFn)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion")) fn(&os); + std::printf("windows %lu.%lu.%lu\n", os.dwMajorVersion, os.dwMinorVersion, os.dwBuildNumber); + + if (debug) { + Ref<ID3D12Debug> dbg; + if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&dbg)))) dbg->EnableDebugLayer(); + } + std::printf("debug layer: %s\n", debug ? "on" : "off"); + Ref<IDXGIFactory6> factory; + CHECK(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory))); + Ref<IDXGIAdapter1> adapter; + if (hw) CHECK(factory->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&adapter))); + else CHECK(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))); + DXGI_ADAPTER_DESC1 ad{}; + adapter->GetDesc1(&ad); + LARGE_INTEGER umd{}; + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &umd); + std::printf("adapter: %ls (vendor %04x device %04x) driver %u.%u.%u.%u\n", ad.Description, ad.VendorId, ad.DeviceId, + HIWORD(umd.HighPart), LOWORD(umd.HighPart), HIWORD(umd.LowPart), LOWORD(umd.LowPart)); + Ref<ID3D12Device2> device; + CHECK(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device))); + if (debug && SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&g_info)))) g_info->SetMuteDebugOutput(FALSE); + D3D12_FEATURE_DATA_D3D12_OPTIONS7 o7{}; + device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &o7, sizeof(o7)); + D3D12_FEATURE_DATA_SHADER_MODEL sm{D3D_SHADER_MODEL_6_5}; + device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &sm, sizeof(sm)); + std::printf("mesh shader tier %d, shader model 0x%x\n", (int)o7.MeshShaderTier, (unsigned)sm.HighestShaderModel); + if (o7.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED || sm.HighestShaderModel < D3D_SHADER_MODEL_6_5) { + std::printf("capability skip: no mesh shaders\n"); + return 77; + } + D3D12_FEATURE_DATA_D3D12_OPTIONS9 o9{}; + bool stats_ok = SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS9, &o9, sizeof(o9))) && + o9.MeshShaderPipelineStatsSupported; + + // root signature: b0 constants, t0..tN-1 as ONE descriptor table of raw buffer views (bounded: a load past + // the end reads 0, as the console's V# range check; root SRVs have no bounds check and an out-of-range load + // there is undefined, which hung a GPU), u0 dump, u1 hits + std::vector<D3D12_ROOT_PARAMETER1> params; + D3D12_ROOT_PARAMETER1 p{}; + p.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + p.Constants.Num32BitValues = (UINT)consts.size(); + params.push_back(p); + D3D12_DESCRIPTOR_RANGE1 srv_range{}; + srv_range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + srv_range.NumDescriptors = (UINT)srvs.size(); + srv_range.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC; + if (!srvs.empty()) { + D3D12_ROOT_PARAMETER1 q{}; + q.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + q.DescriptorTable.NumDescriptorRanges = 1; + q.DescriptorTable.pDescriptorRanges = &srv_range; + params.push_back(q); + } + // heap: t0..t2 space1 (bounded raw views) and the view-id region (spaces 2..6, overlaid at offset 0) + D3D12_DESCRIPTOR_RANGE1 space1_range{}; + space1_range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + space1_range.NumDescriptors = 3; + space1_range.RegisterSpace = 1; + space1_range.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC; + D3D12_DESCRIPTOR_RANGE1 region_ranges[5]{}; + for (UINT k = 0; k < 5; ++k) { + region_ranges[k].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + region_ranges[k].NumDescriptors = region_size; + region_ranges[k].RegisterSpace = 2 + k; + region_ranges[k].OffsetInDescriptorsFromTableStart = 0; + region_ranges[k].Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE; + } + UINT heap_param = 0; + if (heap) { + heap_param = (UINT)params.size(); + D3D12_ROOT_PARAMETER1 q{}; + q.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + q.DescriptorTable.NumDescriptorRanges = 1; + q.DescriptorTable.pDescriptorRanges = &space1_range; + params.push_back(q); + q.DescriptorTable.NumDescriptorRanges = 5; + q.DescriptorTable.pDescriptorRanges = region_ranges; + params.push_back(q); + } + const UINT uav_param = (UINT)params.size(); + for (UINT i = 0; i < 2; ++i) { + D3D12_ROOT_PARAMETER1 q{}; + q.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + q.Descriptor.ShaderRegister = i; + params.push_back(q); + } + D3D12_VERSIONED_ROOT_SIGNATURE_DESC rsd{}; + rsd.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + rsd.Desc_1_1.NumParameters = (UINT)params.size(); + rsd.Desc_1_1.pParameters = params.data(); + Ref<ID3DBlob> rs_blob, rs_err; + if (FAILED(D3D12SerializeVersionedRootSignature(&rsd, &rs_blob, &rs_err))) { + std::fprintf(stderr, "root signature: %s\n", rs_err ? (const char*)rs_err->GetBufferPointer() : "?"); + return 1; + } + Ref<ID3D12RootSignature> root; + CHECK(device->CreateRootSignature(0, rs_blob->GetBufferPointer(), rs_blob->GetBufferSize(), IID_PPV_ARGS(&root))); + + auto ms = read_file(ms_path), ps = read_file(ps_path); + if (ms.empty() || ps.empty()) { std::fprintf(stderr, "missing shader file\n"); return 1; } + MeshStream st{}; + st.root.data = root; + st.ms.data = {ms.data(), ms.size()}; + st.ps.data = {ps.data(), ps.size()}; + st.blend.data.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + st.raster.data.FillMode = D3D12_FILL_MODE_SOLID; + st.raster.data.CullMode = D3D12_CULL_MODE_NONE; + st.raster.data.DepthClipEnable = TRUE; + st.depth.data.DepthEnable = FALSE; + st.rtv.data.NumRenderTargets = 1; + st.rtv.data.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + st.sample.data.Count = 1; + st.mask.data = 0xffffffff; + D3D12_PIPELINE_STATE_STREAM_DESC sd{sizeof(st), &st}; + Ref<ID3D12PipelineState> pso; + CHECK(device->CreatePipelineState(&sd, IID_PPV_ARGS(&pso))); + + D3D12_HEAP_PROPERTIES up{D3D12_HEAP_TYPE_UPLOAD}, def{D3D12_HEAP_TYPE_DEFAULT}, rb{D3D12_HEAP_TYPE_READBACK}; + std::vector<Ref<ID3D12Resource>> srv_res(srvs.size()); + for (size_t i = 0; i < srvs.size(); ++i) { + auto data = read_file(srvs[i]); + auto d = buffer_desc(data.size()); + CHECK(device->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&srv_res[i]))); + void* m = nullptr; + CHECK(srv_res[i]->Map(0, nullptr, &m)); + std::memset(m, 0, (size_t)d.Width); + std::memcpy(m, data.data(), data.size()); + srv_res[i]->Unmap(0, nullptr); + } + // one shader-visible heap: [0, n) the srv table, then (heap) 3 space1 views, then the view-id region + const UINT n_srv = (UINT)srvs.size(), space1_at = n_srv, region_at = n_srv + 3; + const UINT heap_size = heap ? region_at + region_size : (n_srv ? n_srv : 1u); + Ref<ID3D12DescriptorHeap> srv_heap; + D3D12_DESCRIPTOR_HEAP_DESC shd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, heap_size, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + CHECK(device->CreateDescriptorHeap(&shd, IID_PPV_ARGS(&srv_heap))); + UINT srv_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + auto cpu_at = [&](UINT i) { + D3D12_CPU_DESCRIPTOR_HANDLE h = srv_heap->GetCPUDescriptorHandleForHeapStart(); + h.ptr += SIZE_T{i} * srv_step; + return h; + }; + auto upload = [&](const std::vector<char>& data, UINT64 at_least, Ref<ID3D12Resource>& res) -> HRESULT { + auto d = buffer_desc(data.size() > at_least ? data.size() : at_least); + HRESULT hr = device->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&res)); + if (FAILED(hr)) return hr; + void* m = nullptr; + if (FAILED(hr = res->Map(0, nullptr, &m))) return hr; + std::memset(m, 0, (size_t)d.Width); + if (!data.empty()) std::memcpy(m, data.data(), data.size()); + res->Unmap(0, nullptr); + return S_OK; + }; + auto raw_view = [&](ID3D12Resource* res, UINT64 offset, UINT64 bytes, D3D12_CPU_DESCRIPTOR_HANDLE h) { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Buffer.FirstElement = offset / 4; + v.Buffer.NumElements = (UINT)(bytes / 4); + v.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(v.Buffer.NumElements ? res : nullptr, &v, h); + }; + auto null_view = [&](UINT kind, D3D12_CPU_DESCRIPTOR_HANDLE h) { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + switch (kind) { + case 0: v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; v.Texture2D.MipLevels = 1; break; + case 1: v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; v.Texture2DArray.MipLevels = 1; v.Texture2DArray.ArraySize = 1; break; + case 2: v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; v.Texture3D.MipLevels = 1; break; + case 3: v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; v.Texture1D.MipLevels = 1; break; + default: raw_view(nullptr, 0, 0, h); return; + } + device->CreateShaderResourceView(nullptr, &v, h); + }; + Ref<ID3D12Resource> heap_res[3], blob_res; + std::vector<Ref<ID3D12Resource>> tex_res(hviews.size()), tex_up(hviews.size()); + std::vector<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> tex_fp(hviews.size()); + if (heap) { + // space1: exact sizes, so a load past the end reads 0 (heapmem: the title heap; vinfo 16 and vdesc 32 bytes per id) + const UINT64 min_bytes[3] = {16, 16ull * heap_ids, 32ull * heap_ids}; + for (int i = 0; i < 3; ++i) { + auto data = read_file(heap_files[i]); + if (data.empty() && i == 0) { std::fprintf(stderr, "missing %s\n", heap_files[i].c_str()); return 1; } + CHECK(upload(data, min_bytes[i], heap_res[i])); + raw_view(heap_res[i], 0, data.size() > min_bytes[i] ? data.size() : min_bytes[i], cpu_at(space1_at + i)); + } + auto blob = read_file(blob_path); + CHECK(upload(blob, 16, blob_res)); + for (UINT k = 0; k < 8; ++k) null_view(k, cpu_at(region_at + k)); + for (const auto& v : hviews) + for (UINT k = 0; k < 5; ++k) null_view(k, cpu_at(region_at + 8 + 8 * v.id + k)); + UINT counts[5] = {}; + for (size_t i = 0; i < hviews.size(); ++i) { + const auto& v = hviews[i]; + const D3D12_CPU_DESCRIPTOR_HANDLE h = cpu_at(region_at + 8 + 8 * v.id + v.kind); + ++counts[v.kind]; + if (v.kind == 4) { + if (v.offset + v.bytes > blob.size()) { std::fprintf(stderr, "hbuf %u past the blob\n", v.id); return 1; } + raw_view(blob_res, v.offset, v.bytes, h); + continue; + } + D3D12_RESOURCE_DESC td{}; + td.Dimension = v.kind == 3 ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = v.width; + td.Height = v.kind == 3 ? 1 : v.height; + td.DepthOrArraySize = 1; + td.MipLevels = 1; + td.Format = (DXGI_FORMAT)v.dxgi; + td.SampleDesc.Count = 1; + CHECK(device->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&tex_res[i]))); + UINT rows = 0; + UINT64 row_bytes = 0, total = 0; + device->GetCopyableFootprints(&td, 0, 1, 0, &tex_fp[i], &rows, &row_bytes, &total); + if (v.offset + row_bytes * rows > blob.size()) { std::fprintf(stderr, "htex %u past the blob\n", v.id); return 1; } + std::vector<char> staged((size_t)total); + for (UINT r = 0; r < rows; ++r) + std::memcpy(staged.data() + tex_fp[i].Offset + (size_t)r * tex_fp[i].Footprint.RowPitch, blob.data() + v.offset + r * row_bytes, (size_t)row_bytes); + CHECK(upload(staged, total, tex_up[i])); + D3D12_SHADER_RESOURCE_VIEW_DESC sv{}; + sv.Format = td.Format; + sv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (v.kind == 3) { sv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; sv.Texture1D.MipLevels = 1; } + else { sv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; sv.Texture2D.MipLevels = 1; } + device->CreateShaderResourceView(tex_res[i], &sv, h); + } + std::printf("heap: heapmem %zu bytes, region %u descriptors at %u, views tex2d %u tex1d %u buf %u\n", + read_file(heap_files[0]).size(), region_size, region_at, counts[0], counts[3], counts[4]); + } + for (size_t i = 0; i < srvs.size(); ++i) { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Buffer.NumElements = (UINT)(read_file(srvs[i]).size() / 4); + v.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + D3D12_CPU_DESCRIPTOR_HANDLE h = srv_heap->GetCPUDescriptorHandleForHeapStart(); + h.ptr += i * srv_step; + device->CreateShaderResourceView(srv_res[i], &v, h); + } + Ref<ID3D12Resource> uav[2], back[2], zero; + UINT64 sizes[2] = {dump_bytes, hits_bytes}; + UINT64 zmax = dump_bytes > hits_bytes ? dump_bytes : hits_bytes; + { + auto d = buffer_desc(zmax); + CHECK(device->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&zero))); + void* m = nullptr; + CHECK(zero->Map(0, nullptr, &m)); + std::memset(m, 0, (size_t)d.Width); + zero->Unmap(0, nullptr); + } + for (int i = 0; i < 2; ++i) { + auto d = buffer_desc(sizes[i], D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + CHECK(device->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&uav[i]))); + auto r = buffer_desc(sizes[i]); + CHECK(device->CreateCommittedResource(&rb, D3D12_HEAP_FLAG_NONE, &r, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&back[i]))); + } + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = 256; + td.Height = 256; + td.DepthOrArraySize = 1; + td.MipLevels = 1; + td.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + td.SampleDesc.Count = 1; + td.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + D3D12_CLEAR_VALUE cv{DXGI_FORMAT_R8G8B8A8_UNORM, {0, 0, 0, 0}}; + Ref<ID3D12Resource> rt; + CHECK(device->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_RENDER_TARGET, &cv, + IID_PPV_ARGS(&rt))); + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + Ref<ID3D12DescriptorHeap> rtv_heap; + CHECK(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtv_heap))); + auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(rt, nullptr, rtv); + + Ref<ID3D12QueryHeap> qheap; + Ref<ID3D12Resource> qback; + if (stats_ok) { + D3D12_QUERY_HEAP_DESC qd{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS1, 1}; + if (FAILED(device->CreateQueryHeap(&qd, IID_PPV_ARGS(&qheap)))) stats_ok = false; + auto r = buffer_desc(sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS1)); + CHECK(device->CreateCommittedResource(&rb, D3D12_HEAP_FLAG_NONE, &r, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&qback))); + } + + D3D12_COMMAND_QUEUE_DESC qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + Ref<ID3D12CommandQueue> queue; + CHECK(device->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&queue))); + Ref<ID3D12CommandAllocator> alloc; + CHECK(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc))); + Ref<ID3D12GraphicsCommandList6> list; + CHECK(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc, nullptr, IID_PPV_ARGS(&list))); + + D3D12_RESOURCE_BARRIER b[2]; + for (int i = 0; i < 2; ++i) b[i] = transition(uav[i], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->ResourceBarrier(2, b); + for (int i = 0; i < 2; ++i) list->CopyBufferRegion(uav[i], 0, zero, 0, buffer_desc(sizes[i]).Width); + for (int i = 0; i < 2; ++i) b[i] = transition(uav[i], D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->ResourceBarrier(2, b); + for (size_t i = 0; i < hviews.size(); ++i) { + if (!tex_res[i]) continue; + D3D12_TEXTURE_COPY_LOCATION dst{tex_res[i], D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}, src{tex_up[i], D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.SubresourceIndex = 0; + src.PlacedFootprint = tex_fp[i]; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + D3D12_RESOURCE_BARRIER t = transition(tex_res[i], D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list->ResourceBarrier(1, &t); + } + const float clear[4] = {0, 0, 0, 0}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + D3D12_VIEWPORT vp{0, 0, 256, 256, 0, 1}; + D3D12_RECT sc{0, 0, 256, 256}; + list->RSSetViewports(1, &vp); + list->RSSetScissorRects(1, &sc); + list->SetGraphicsRootSignature(root); + list->SetPipelineState(pso); + list->SetGraphicsRoot32BitConstants(0, (UINT)consts.size(), consts.data(), 0); + ID3D12DescriptorHeap* heaps[] = {srv_heap}; + list->SetDescriptorHeaps(1, heaps); + if (!srvs.empty()) list->SetGraphicsRootDescriptorTable(1, srv_heap->GetGPUDescriptorHandleForHeapStart()); + if (heap) { + D3D12_GPU_DESCRIPTOR_HANDLE g = srv_heap->GetGPUDescriptorHandleForHeapStart(); + g.ptr += UINT64{space1_at} * srv_step; + list->SetGraphicsRootDescriptorTable(heap_param, g); + g.ptr += UINT64{3} * srv_step; + list->SetGraphicsRootDescriptorTable(heap_param + 1, g); + } + for (UINT i = 0; i < 2; ++i) list->SetGraphicsRootUnorderedAccessView(uav_param + i, uav[i]->GetGPUVirtualAddress()); + if (stats_ok) list->BeginQuery(qheap, D3D12_QUERY_TYPE_PIPELINE_STATISTICS1, 0); + list->DispatchMesh(groups, 1, 1); + if (stats_ok) { + list->EndQuery(qheap, D3D12_QUERY_TYPE_PIPELINE_STATISTICS1, 0); + list->ResolveQueryData(qheap, D3D12_QUERY_TYPE_PIPELINE_STATISTICS1, 0, 1, qback, 0); + } + for (int i = 0; i < 2; ++i) b[i] = transition(uav[i], D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(2, b); + for (int i = 0; i < 2; ++i) list->CopyBufferRegion(back[i], 0, uav[i], 0, buffer_desc(sizes[i]).Width); + CHECK(list->Close()); + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + Ref<ID3D12Fence> fence; + CHECK(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); + CHECK(queue->Signal(fence, 1)); + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + CHECK(fence->SetEventOnCompletion(1, ev)); + DWORD t0 = GetTickCount(); + DWORD waited = WaitForSingleObject(ev, 60000); + printf("gpu wait: %s after %lu ms, fence %llu\n", waited == WAIT_OBJECT_0 ? "done" : "TIMEOUT", + (unsigned long)(GetTickCount() - t0), (unsigned long long)fence->GetCompletedValue()); + CHECK(device->GetDeviceRemovedReason()); + if (waited != WAIT_OBJECT_0) { + fprintf(stderr, "the GPU did not finish within 60 s\n"); + return 3; + } + + const char* ext[2] = {".dump", ".hits"}; + for (int i = 0; i < 2; ++i) { + void* m = nullptr; + D3D12_RANGE r{0, (SIZE_T)sizes[i]}; + CHECK(back[i]->Map(0, &r, &m)); + std::ofstream f(out + ext[i], std::ios::binary); + f.write((const char*)m, (std::streamsize)sizes[i]); + back[i]->Unmap(0, nullptr); + } + if (stats_ok) { + void* m = nullptr; + CHECK(qback->Map(0, nullptr, &m)); + auto* q = (D3D12_QUERY_DATA_PIPELINE_STATISTICS1*)m; + std::printf("stats: MSInvocations %llu MSPrimitives %llu CInvocations %llu CPrimitives %llu PSInvocations %llu\n", + q->MSInvocations, q->MSPrimitives, q->CInvocations, q->CPrimitives, q->PSInvocations); + qback->Unmap(0, nullptr); + } else { + std::printf("stats: mesh pipeline statistics not supported\n"); + } + dump_messages(); + std::printf("ok\n"); + return 0; +} diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index 8132b595e2..ea62b3d964 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -17,7 +17,12 @@ param( [Parameter(Mandatory)] [string]$LogDir, [int]$Seconds = 120, [string]$BuildDir = "out/build/release", + [string]$NativeLauncher = "", [int]$MemoryGiB = 14, + # Host safety (runtime_work/NOTES.md): pagefile page-slab cap in MiB (X2W_XMEM_SLAB_BUDGET_MIB) and a + # directory for file-backed slabs, which carry no commit charge (X2W_XMEM_SLAB_DIR, absolute, off G:/S:). + [int]$SlabBudgetMiB = 0, + [string]$SlabDir = "", [int]$ContinueAsserts = 0, # main-image int3s to log and step over (title soft asserts) [string]$InputScript = "", # X2W_INPUT_SCRIPT, e.g. "4@70" = A at 70 s [string]$StoragePath = "", # X2W_STORAGE_PATH: persistent local storage root (a trailing \ is added when missing) @@ -26,6 +31,9 @@ param( [switch]$FakeUser, # answer the user API for one local user [switch]$GpuMirror, # map CPU-view pages into the paired GPU-view reservation [switch]$HostCpu, # rewrite instructions the host processor lacks (X2W_HOST_CPU) + [switch]$FastExit, # at a timeout or Ctrl+C: rip-only threads.txt, no window capture or movie frame + [int]$LogRepeats = 200, # log a repeating exception or runtime/movie hook this often, then only count it (0 = all) + [switch]$SharedViews, # X2W_XMEM_SHARED_VIEWS=1: adjacent mapped pages share one view (faster map and exit) [switch]$Translate, # with -Render: translate new shader requests during the run (gfx2hlsl.py --watch) [switch]$StartupBelow40, # place the 0x283 large-page startup blocks below 2^40 (X2W_XMEM_STARTUP_BELOW_40) [switch]$TraceCalls, # also break on runtime and movie-player calls (--trace-calls 1; slows the process) @@ -33,9 +41,14 @@ param( ) $ErrorActionPreference = "Stop" $repo = Resolve-Path (Join-Path $PSScriptRoot "..\..") +$build = if ([IO.Path]::IsPathRooted($BuildDir)) { $BuildDir } else { Join-Path $repo $BuildDir } +if ($NativeLauncher) { + $NativeLauncher = (Resolve-Path -LiteralPath $NativeLauncher).Path + if ($Translate) { throw "The native launcher takes precompiled shaders. Omit -Translate." } +} $runDir = Split-Path -Parent (Resolve-Path $Exe) foreach ($dll in "xmem", "d3d12_xs", "AcpHal", "XCRDAPI", "chad", "xapu", "xg_xs", "GameInput") { - Copy-Item (Join-Path $repo "$BuildDir\$dll.dll") $runDir -Force + Copy-Item (Join-Path $build "$dll.dll") $runDir -Force } $env:X2W_AUDIO_PERMISSIVE = "1"; $env:X2W_D3D12_DEVICE_NOOP = "1"; $env:X2W_D3D12_LIST_NOOP = "1" $env:X2W_D3D12_PERMISSIVE = "1"; $env:X2W_XMEM_PERMISSIVE = "1"; $env:X2W_RUNTIME_PROXY = "1" @@ -52,15 +65,27 @@ if (-not $FakeUser -and $env:X2W_FAKE_USER -ne "1") { Write-Warning "Without -FakeUser, user API calls go to the host gaming runtime (docs/startup-runtime.md)." } if ($GpuMirror) { $env:X2W_XMEM_GPU_MIRROR = "1" } +if ($SlabBudgetMiB -gt 0) { $env:X2W_XMEM_SLAB_BUDGET_MIB = "$SlabBudgetMiB" } +if ($SlabDir) { $env:X2W_XMEM_SLAB_DIR = $SlabDir } if ($HostCpu) { $env:X2W_HOST_CPU = "1" } +if ($SharedViews) { $env:X2W_XMEM_SHARED_VIEWS = "1" } if ($TraceApi) { $env:X2W_TRACE_API = "1" } if ($StartupBelow40) { $env:X2W_XMEM_STARTUP_BELOW_40 = "1" } if ($Render) { New-Item -ItemType Directory -Force $ShaderCache | Out-Null + if (-not (Test-Path Env:X2W_PRESENT_IN_TITLE_WINDOW)) { $env:X2W_PRESENT_IN_TITLE_WINDOW = "1" } $env:X2W_D3D12_RENDER = "1"; $env:X2W_DRAW_NULL_IDENTITY = "1" $env:X2W_SHADER_CACHE = (Resolve-Path $ShaderCache).Path } New-Item -ItemType Directory -Force $LogDir | Out-Null +if ($NativeLauncher) { + & $NativeLauncher $Exe $DataDir $LogDir --timeout $Seconds --memory-gib $MemoryGiB --offline 1 ` + --trace-files 1 --continue-asserts $ContinueAsserts --fast-exit ([int]$FastExit.IsPresent) ` + --trace-calls ([int]$TraceCalls.IsPresent) --log-repeats $LogRepeats *> "$LogDir.out" + $debuggerExit = $LASTEXITCODE + Get-Content "$LogDir.out" -TotalCount 5 + exit $debuggerExit +} $python = Join-Path $repo "out\pe-env\Scripts\python.exe" if (-not (Test-Path -LiteralPath $python)) { $python = "python" } $translator = $null @@ -74,7 +99,8 @@ $traceArgs = @() if ($TraceCalls) { $traceArgs = @("--trace-calls", "1") } try { & $python -B (Join-Path $PSScriptRoot "debug_launch.py") $Exe $DataDir $LogDir --timeout $Seconds --memory-gib $MemoryGiB ` - --trace-files 1 --continue-asserts $ContinueAsserts @traceArgs *> "$LogDir.out" + --trace-files 1 --continue-asserts $ContinueAsserts --fast-exit $(if ($FastExit) { 1 } else { 0 }) ` + --log-repeats $LogRepeats @traceArgs *> "$LogDir.out" $debuggerExit = $LASTEXITCODE } finally { # taskkill /T needs a live parent PID to reach the watcher's workers. diff --git a/tools/startup/sample_profile.py b/tools/startup/sample_profile.py new file mode 100644 index 0000000000..3d9403f5ff --- /dev/null +++ b/tools/startup/sample_profile.py @@ -0,0 +1,429 @@ +"""Clock-driven sampling profiler for debug_launch.py (startup diagnostics; off unless X2W_PROFILE is set). + +X2W_PROFILE=<start s>,<samples>,<interval ms>[,<repeat every s>] takes <samples> samples, <interval ms> +apart, from <start s> after launch (again every <repeat every s> when given), and writes +profile_<start>.txt per batch into the log folder. + +A sample is taken from the debugger's loop when the clock says so, between debug events (never at +one): every live thread is suspended, and its CPU times, integer context and the top of its stack are +copied. Then all threads are resumed and the stacks are walked afterwards from the copies (dbghelp +StackWalk64 with a read routine that serves the copied stack). The target only gets memory reads and +thread queries; nothing runs in it, so a thread suspended inside the loader lock or a heap lock cannot +stall the debugger. Each report states how long the process was frozen per sample. +""" +import ctypes +import ctypes.wintypes as wt +import os +import random +import struct +import time + +k32 = ctypes.WinDLL("kernel32", use_last_error=True) +ntdll = ctypes.WinDLL("ntdll") +dbghelp = ctypes.WinDLL("dbghelp", use_last_error=True) + +k32.OpenThread.restype = wt.HANDLE +k32.OpenThread.argtypes = [wt.DWORD, wt.BOOL, wt.DWORD] +k32.SuspendThread.argtypes = k32.ResumeThread.argtypes = [wt.HANDLE] +k32.SuspendThread.restype = k32.ResumeThread.restype = wt.DWORD +k32.GetThreadContext.argtypes = [wt.HANDLE, ctypes.c_void_p] +k32.GetThreadTimes.argtypes = [wt.HANDLE] + [ctypes.POINTER(ctypes.c_uint64)] * 4 +k32.ReadProcessMemory.argtypes = [wt.HANDLE, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_size_t, + ctypes.POINTER(ctypes.c_size_t)] +k32.CloseHandle.argtypes = [wt.HANDLE] +k32.GetCurrentProcess.restype = wt.HANDLE +k32.DuplicateHandle.argtypes = [wt.HANDLE, wt.HANDLE, wt.HANDLE, ctypes.POINTER(wt.HANDLE), wt.DWORD, wt.BOOL, wt.DWORD] +k32.VirtualQueryEx.argtypes = [wt.HANDLE, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_size_t] +k32.LocalFree.argtypes = [ctypes.c_void_p] +if hasattr(k32, "GetThreadDescription"): + k32.GetThreadDescription.argtypes = [wt.HANDLE, ctypes.POINTER(ctypes.c_void_p)] + k32.GetThreadDescription.restype = ctypes.c_long +ntdll.NtQueryInformationThread.argtypes = [wt.HANDLE, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p] + +FRAMES = 12 # return addresses kept per sample (after the leaf) +STACK_BYTES = 0x8000 # stack copied per thread per sample +WAIT_WORDS = ("Wait", "Delay", "Remove", "ReplyWait", "Alert", "GetMessage") +SYSTEM = ("ntdll.dll", "kernelbase.dll", "kernel32.dll", "win32u.dll", "user32.dll") +CONTEXT_CONTROL_INTEGER = 0x100003 + +READ_MEMORY = ctypes.WINFUNCTYPE(wt.BOOL, wt.HANDLE, ctypes.c_uint64, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD)) + + +class MBI(ctypes.Structure): + _fields_ = [("BaseAddress", ctypes.c_uint64), ("AllocationBase", ctypes.c_uint64), + ("AllocationProtect", ctypes.c_uint32), ("PartitionId", ctypes.c_uint16), + ("RegionSize", ctypes.c_uint64), ("State", ctypes.c_uint32), + ("Protect", ctypes.c_uint32), ("Type", ctypes.c_uint32)] + + +class SYMBOL_INFOW(ctypes.Structure): + _fields_ = [("SizeOfStruct", wt.ULONG), ("TypeIndex", wt.ULONG), ("Reserved", ctypes.c_uint64 * 2), + ("Index", wt.ULONG), ("Size", wt.ULONG), ("ModBase", ctypes.c_uint64), ("Flags", wt.ULONG), + ("Value", ctypes.c_uint64), ("Address", ctypes.c_uint64), ("Register", wt.ULONG), + ("Scope", wt.ULONG), ("Tag", wt.ULONG), ("NameLen", wt.ULONG), ("MaxNameLen", wt.ULONG), + ("Name", ctypes.c_wchar * 512)] + + +class IMAGEHLP_LINEW64(ctypes.Structure): + _fields_ = [("SizeOfStruct", wt.DWORD), ("Key", ctypes.c_void_p), ("LineNumber", wt.DWORD), + ("FileName", ctypes.c_wchar_p), ("Address", ctypes.c_uint64)] + + +dbghelp.SymInitializeW.argtypes = [wt.HANDLE, ctypes.c_wchar_p, wt.BOOL] +dbghelp.SymRefreshModuleList.argtypes = [wt.HANDLE] +dbghelp.SymCleanup.argtypes = [wt.HANDLE] +dbghelp.SymFromAddrW.argtypes = [wt.HANDLE, ctypes.c_uint64, ctypes.POINTER(ctypes.c_uint64), ctypes.POINTER(SYMBOL_INFOW)] +dbghelp.SymGetLineFromAddrW64.argtypes = [wt.HANDLE, ctypes.c_uint64, ctypes.POINTER(wt.DWORD), ctypes.POINTER(IMAGEHLP_LINEW64)] +dbghelp.SymGetModuleInfoW64.argtypes = [wt.HANDLE, ctypes.c_uint64, ctypes.c_void_p] +dbghelp.StackWalk64.argtypes =[wt.DWORD, wt.HANDLE, wt.HANDLE, ctypes.c_void_p, ctypes.c_void_p, + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] + + +def parse(spec): + """(start s, samples, interval s, repeat s) from X2W_PROFILE, or None when it is unset or malformed.""" + try: + parts = [float(p) for p in spec.split(",")] + if len(parts) < 3 or parts[1] < 2 or parts[2] <= 0: + return None + return parts[0], int(parts[1]), parts[2] / 1000.0, parts[3] if len(parts) > 3 else 0.0 + except ValueError: + return None + + +class Profiler: + def __init__(self, plan, process, logdir, where, modules, module_paths, log): + self.first, self.count, self.interval, self.repeat = plan + self.logdir, self.where, self.modules, self.module_paths, self.log = logdir, where, modules, module_paths, log + # A handle of our own for dbghelp: its sessions are keyed by handle value, and the debugger's + # thread dumps open and close a session on the process handle itself. + own = wt.HANDLE() + k32.DuplicateHandle(k32.GetCurrentProcess(), process, k32.GetCurrentProcess(), ctypes.byref(own), 0, False, 2) + self.process = own + self.next = self.first + self.batch = self.first + self.done = False + self.samples = [] # (seconds, {tid: (kernel 100ns, user 100ns, frames)}, quiet, ms since last event, its tid) + self.previous = {} # tid -> (rip, rsp, kernel, user, frames): an unchanged thread is not copied or walked again + self.reused = 0 + self.awaiting_continue = False + self.last_continue = 0.0 + self.freeze = [] # seconds each process freeze lasted + self.walk_cost = [] + self.handles = {} # tid -> handle (SUSPEND_RESUME | GET_CONTEXT | QUERY_INFORMATION) + self.info = {} # tid -> (description, start address) + self.session = False + self.snapshot = (0, b"") + self.reader = READ_MEMORY(self._read) + self.table_access = ctypes.cast(dbghelp.SymFunctionTableAccess64, ctypes.c_void_p) + self.module_base = ctypes.cast(dbghelp.SymGetModuleBase64, ctypes.c_void_p) + self.symbols = {} + self.pdb = {} + + def timeout_ms(self, now): + """How long the debugger may wait for an event: until the next sample is due (run() then takes it).""" + if self.done: + return 200 + return max(1, min(200, int((self.next - now) * 1000))) + + def event_seen(self): + """The debugger received an event; it is continued before the loop comes back to run().""" + self.awaiting_continue = True + + def run(self, now, live, last_event, peek): + """Called at the top of the debugger loop. Returns True when peek() received a debug event that the + caller must handle now (the sample waits). + + A due sample is taken only 1 ms or more after the last ContinueDebugEvent, with pending events + handled first (peek: WaitForDebugEvent with no wait). Sampling right after a continue, or at the + end of a timed wait, finds the thread whose event was just continued, or one woken on the same + timer tick, at its event site every time. A sample overdue by a whole interval (no 1 ms gap) is + taken anyway and counted as forced. last_event: (seconds, tid) of the last debug event.""" + if self.awaiting_continue: + self.last_continue = time.perf_counter() + self.awaiting_continue = False + if self.done or now < self.next: + return False + forced = now >= self.next + max(self.interval, 0.1) + if not forced: + settle = self.last_continue + 0.001 + while time.perf_counter() < settle: + if peek(): + return True + if peek(): + return True + self.poll(now, live, not forced, last_event) + return False + + def poll(self, now, live, quiet, last_event): + """Takes the due sample (run() decides when); writes the batch when it is complete.""" + try: + self.sample(now, live, quiet, last_event) + # Jitter (+-25 %, mean = the interval) keeps samples off any period of the title or the timer. + self.next += self.interval * random.uniform(0.75, 1.25) + if self.next < now: + self.next = now # late (a long debug event): no catch-up burst + if len(self.samples) >= self.count: + self.write() + self.samples, self.freeze, self.walk_cost = [], [], [] + if self.repeat > 0: + self.batch += self.repeat + self.next = max(self.batch, now) + else: + self.done = True + except Exception as error: # a profiler fault must never cost the run + self.done = True + self.log(f"{now:7.3f} profile: stopped after an error: {error!r}") + + def _read(self, _process, base, buffer, size, got): + low, data = self.snapshot + if low <= base and base + size <= low + len(data): + ctypes.memmove(buffer, data[base - low:base - low + size], size) + got[0] = size + return True + n = ctypes.c_size_t() + ok = k32.ReadProcessMemory(self.process, base, buffer, size, ctypes.byref(n)) + got[0] = n.value + return bool(ok or n.value) + + def thread_info(self, handle): + text = "" + try: + pointer = ctypes.c_void_p() + if k32.GetThreadDescription(handle, ctypes.byref(pointer)) >= 0 and pointer.value: + text = ctypes.wstring_at(pointer.value) + k32.LocalFree(pointer) + except AttributeError: + pass + start = ctypes.c_uint64() + ntdll.NtQueryInformationThread(handle, 9, ctypes.byref(start), 8, None) # ThreadQuerySetWin32StartAddress + return text, start.value + + def sample(self, now, live, quiet=True, last_event=(0.0, 0)): + for tid in [t for t in self.handles if t not in live]: + k32.CloseHandle(self.handles.pop(tid)) + self.previous.pop(tid, None) + if not self.session: + dbghelp.SymSetOptions(0x2 | 0x4 | 0x10 | 0x200 | 0x80000) # UNDNAME DEFERRED LINES FAIL_CRITICAL NO_PROMPTS + folders = [self.logdir] + sorted({os.path.dirname(p) for p in self.module_paths.values() if p}) + self.session = bool(dbghelp.SymInitializeW(self.process, ";".join(folders), True)) + elif len(self.samples) == 0: + dbghelp.SymRefreshModuleList(self.process) # modules loaded since the last batch + began = time.perf_counter() + suspended = [] + for tid in sorted(live): + handle = self.handles.get(tid) + if handle is None: + handle = k32.OpenThread(0x0002 | 0x0008 | 0x0040, False, tid) + if not handle: + continue + self.handles[tid] = handle + self.info[tid] = self.thread_info(handle) + if k32.SuspendThread(handle) != 0xFFFFFFFF: + suspended.append((tid, handle)) + copies = [] + raw = (ctypes.c_ubyte * (1232 + 16))() + ctx_addr = (ctypes.addressof(raw) + 15) & ~15 + ctx_view = (ctypes.c_ubyte * 1232).from_address(ctx_addr) + for tid, handle in suspended: + times = [ctypes.c_uint64() for _ in range(4)] + k32.GetThreadTimes(handle, *[ctypes.byref(t) for t in times]) + struct.pack_into("<I", ctx_view, 0x30, CONTEXT_CONTROL_INTEGER) + if not k32.GetThreadContext(handle, ctx_addr): + continue + ctx = bytes(ctx_view) + rsp = struct.unpack_from("<Q", ctx, 0x98)[0] + rip = struct.unpack_from("<Q", ctx, 0xF8)[0] + before = self.previous.get(tid) + if before and before[:4] == (rip, rsp, times[2].value, times[3].value): + copies.append((tid, handle, times[2].value, times[3].value, ctx, rsp, None)) # still in the same wait + continue + info = MBI() + size = STACK_BYTES + if k32.VirtualQueryEx(self.process, rsp, ctypes.byref(info), ctypes.sizeof(info)): + size = max(0, min(size, info.BaseAddress + info.RegionSize - rsp)) + buffer = (ctypes.c_ubyte * max(size, 1))() + got = ctypes.c_size_t() + k32.ReadProcessMemory(self.process, rsp, buffer, size, ctypes.byref(got)) + copies.append((tid, handle, times[2].value, times[3].value, ctx, rsp, bytes(buffer[:got.value]))) + for _, handle in suspended: + k32.ResumeThread(handle) + resumed = time.perf_counter() + threads = {} + for tid, handle, kernel, user, ctx, rsp, stack in copies: + if stack is None: + frames = self.previous[tid][4] + self.reused += 1 + else: + frames = self.walk(handle, ctx, rsp, stack) + self.previous[tid] = (struct.unpack_from("<Q", ctx, 0xF8)[0], rsp, kernel, user, frames) + threads[tid] = (kernel, user, frames) + self.freeze.append(resumed - began) + self.walk_cost.append(time.perf_counter() - resumed) + self.samples.append((now, threads, quiet, (now - last_event[0]) * 1000.0, last_event[1])) + + def walk(self, handle, ctx, rsp, stack): + raw = (ctypes.c_ubyte * (1232 + 16))() + ctx_addr = (ctypes.addressof(raw) + 15) & ~15 + ctypes.memmove(ctx_addr, ctx, 1232) + rip = struct.unpack_from("<Q", ctx, 0xF8)[0] + if not self.session: + return (rip,) + frame = (ctypes.c_ubyte * 512)() + for offset, value in ((0, rip), (32, struct.unpack_from("<Q", ctx, 0xA0)[0]), (48, rsp)): + struct.pack_into("<Q", frame, offset, value) + struct.pack_into("<I", frame, offset + 12, 3) # AddrModeFlat + self.snapshot = (rsp, stack) + frames = [] + for _ in range(FRAMES + 1): + if not dbghelp.StackWalk64(0x8664, self.process, handle, frame, ctx_addr, self.reader, + self.table_access, self.module_base, None): + break + pc = struct.unpack_from("<Q", frame, 0)[0] + if not pc: + break + frames.append(pc) + return tuple(frames) or (rip,) + + def module_of(self, address): + name = self.where(address) + return name.split("+")[0].lower() if "+" in name else "" + + def name(self, address): + """module+offset, with the function (and line) when dbghelp has a pdb or an export close by.""" + if address in self.symbols: + return self.symbols[address] + text = self.where(address) + module = self.module_of(address) + if self.session and module: + info = SYMBOL_INFOW(SizeOfStruct=88, MaxNameLen=511) # sizeof(SYMBOL_INFOW) with Name[1]; 90 is refused + displacement = ctypes.c_uint64() + # Names from a pdb (the stand-ins, source-built probes), and export names in the system + # modules (the system call stubs); an image without a pdb gets none (an export nearby would mislead). + if dbghelp.SymFromAddrW(self.process, address, ctypes.byref(displacement), ctypes.byref(info)) \ + and displacement.value < 0x1000 and (module in SYSTEM or self.has_pdb(info.ModBase)): + text += f" {info.Name}+{displacement.value:#x}" + line = IMAGEHLP_LINEW64(SizeOfStruct=ctypes.sizeof(IMAGEHLP_LINEW64)) + d32 = wt.DWORD() + if dbghelp.SymGetLineFromAddrW64(self.process, address, ctypes.byref(d32), ctypes.byref(line)): + text += f" [{os.path.basename(line.FileName)}:{line.LineNumber}]" + self.symbols[address] = text + return text + + def has_pdb(self, base): + """True when dbghelp loaded a pdb for the module at base (IMAGEHLP_MODULEW64.SymType == SymPdb).""" + if base not in self.pdb: + info = (ctypes.c_ubyte * 0xCC0)() + struct.pack_into("<I", info, 0, 0xCC0) + ok = dbghelp.SymGetModuleInfoW64(self.process, ctypes.c_uint64(base), info) + self.pdb[base] = bool(ok) and struct.unpack_from("<I", info, 32)[0] == 3 + return self.pdb[base] + + def state(self, frames): + """('wait', call) / ('syscall', call) / ('run', '') for a sample's leaf.""" + leaf = frames[0] + if self.module_of(leaf) in ("ntdll.dll", "win32u.dll"): + label = self.name(leaf) + call = label.split(" ")[1].split("+")[0] if " " in label else "" + if call.startswith(("Nt", "Zw")): + return ("wait" if any(w in call for w in WAIT_WORDS) else "syscall"), call + return "run", "" + + def site(self, frames): + """The first two frames outside the system modules: where a thread waits or calls the system.""" + outside = [f for f in frames if self.module_of(f) not in SYSTEM] + return " < ".join(self.name(f) for f in outside[:2]) or "?" + + def write(self): + samples = self.samples + if len(samples) < 2: + return + t0, t1 = samples[0][0], samples[-1][0] + wall = max(t1 - t0, 1e-6) + dbghelp.SymSetOptions(0x2 | 0x4 | 0x10 | 0x200 | 0x80000) # the thread dumps reset the options + if self.session: + dbghelp.SymRefreshModuleList(self.process) + tids = sorted({tid for s in samples for tid in s[1]}) + rows = [] + for tid in tids: + seen = [s[1][tid] for s in samples if tid in s[1]] + first, last = seen[0], seen[-1] + kernel, user = (last[0] - first[0]) / 1e4, (last[1] - first[1]) / 1e4 # ms + events = sum(1 for s in samples if s[4] == tid and s[3] < 5.0) + rows.append((kernel + user, kernel, user, tid, seen, events)) + rows.sort(key=lambda r: -r[0]) + ms = sorted(self.freeze) + quiet = [s[3] for s in samples if s[2]] + since = sorted(s[3] for s in samples) + out = [f"# profile {t0:.1f}-{t1:.1f} s: {len(samples)} samples, {self.interval * 1000:g} ms apart on average " + f"(+-25 % jitter), {len(tids)} threads", + f"# process frozen per sample: median {ms[len(ms) // 2] * 1000:.1f} ms, max {ms[-1] * 1000:.1f} ms " + f"(suspend, context, {STACK_BYTES // 1024} KiB stack copy); stack walks afterwards " + f"{sum(self.walk_cost) / len(self.walk_cost) * 1000:.1f} ms per sample; unchanged threads reused " + f"{self.reused} times", + f"# taken >= 1 ms after the last ContinueDebugEvent with no event pending: {len(quiet)}/{len(samples)}, forced " + f"{len(samples) - len(quiet)}; ms since the last debug event: median {since[len(since) // 2]:.1f}, " + f"min {since[0]:.1f}", + "# CPU time (cpu%) is the arbiter. 'ev' = samples taken < 5 ms after this thread's own debug event;", + "# a thread with many 'run' samples but little CPU is blocked in a debug event or waiting for a CPU", + "", f"## (a) CPU per thread between the first and the last sample ({wall:.2f} s wall)", + " tid cpu% user_ms kernel_ms ev run/sys/wait name / start address / most frequent leaf"] + total = 0.0 + for cpu, kernel, user, tid, seen, events in rows: + total += cpu + states = [self.state(s[2])[0] for s in seen] + leaves = {} + for s in seen: + leaves[s[2][0]] = leaves.get(s[2][0], 0) + 1 + top = max(leaves.items(), key=lambda kv: kv[1])[0] + text, begin = self.info.get(tid, ("", 0)) + flag = " RUN>>CPU" if states.count("run") > 0.5 * len(seen) and cpu / 10 / wall < 10 else "" + out.append(f"{tid:6d} {cpu / 10 / wall:5.1f} {user:8.0f} {kernel:9.0f} {events:3d} " + f"{states.count('run'):3d}/{states.count('syscall'):3d}/{states.count('wait'):3d} " + f"{text or '-'} / {self.where(begin) if begin else '-'} / {self.name(top)}{flag}") + out.append(f"total: {total / 1000 / wall:.2f} cores") + out += ["", "## (b) per thread, busiest first: leaf and inclusive frame histograms, top stacks"] + for cpu, kernel, user, tid, seen, _ in rows: + states = [self.state(s[2]) for s in seen] + if cpu / 10 / wall < 1.0 and all(k == "wait" for k, _ in states): + continue # idle waiters: section (c) + text, begin = self.info.get(tid, ("", 0)) + out.append(f"thread {tid} ({text or '-'}, start {self.where(begin) if begin else '-'}): cpu " + f"{cpu / 10 / wall:.1f}%, samples {len(seen)}: " + + ", ".join(f"{k}{' ' + c if c else ''} x{n}" for (k, c), n in _count(states)[:6])) + out.append(" leaf: " + ", ".join(f"{self.name(f)} x{n}" for f, n in _count([s[2][0] for s in seen])[:8])) + inclusive = _count([f for s in seen for f in set(s[2][1:])]) + out.append(" inclusive: " + ", ".join(f"{self.name(f)} x{n}" for f, n in inclusive[:12])) + for stack, n in _count([s[2][:6] for s in seen])[:4]: + out.append(f" x{n}: " + " < ".join(self.name(f) for f in stack)) + out += ["", "## (c) wait sites (waiting samples: wait call @ first two frames outside the system modules)"] + for cpu, kernel, user, tid, seen, _ in rows: + waits =[f"{self.state(s[2])[1]} @ {self.site(s[2])}" for s in seen if self.state(s[2])[0] == "wait"] + if waits: + out.append(f"thread {tid}: " + ", ".join(f"{w} x{n}" for w, n in _count(waits)[:3]) + + f" ({len(waits)}/{len(seen)} samples waiting)") + path = os.path.join(self.logdir, f"profile_{self.batch:g}.txt") + with open(path, "w", encoding="utf-8") as handle: + handle.write("\n".join(out) + "\n") + self.log(f"{t1:7.3f} profile: {len(samples)} samples of {len(tids)} threads -> {os.path.basename(path)} " + f"(frozen median {ms[len(ms) // 2] * 1000:.1f} ms per sample)") + + def close(self): + """At the end of the run: a batch cut short is still written.""" + if not self.done and len(self.samples) >= 2: + try: + self.write() + except Exception as error: # diagnostics only + self.log(f"profile: partial batch not written: {error}") + for handle in self.handles.values(): + k32.CloseHandle(handle) + self.handles.clear() + if self.session: + dbghelp.SymCleanup(self.process) + self.session = False + + +def _count(items): + counts = {} + for item in items: + counts[item] = counts.get(item, 0) + 1 + return sorted(counts.items(), key=lambda kv: -kv[1]) diff --git a/tools/startup/shader_cache_rekey.py b/tools/startup/shader_cache_rekey.py index 2e49127a82..80fdf27a51 100644 --- a/tools/startup/shader_cache_rekey.py +++ b/tools/startup/shader_cache_rekey.py @@ -189,6 +189,11 @@ def rekey(src, dst, jobs=None, out=None): def main(argv=None) -> int: argv = sys.argv[1:] if argv is None else argv + # LOCAL merge: the local cache keeps revision 3, so re-keying is not part of the local workflow. The tool runs + # only with X2W_UPSTREAM_SHADER_CACHE_REKEY=1 (its CTest check sets it); it never writes the old cache. + if os.environ.get('X2W_UPSTREAM_SHADER_CACHE_REKEY') != '1': + print('shader_cache_rekey: disabled here; set X2W_UPSTREAM_SHADER_CACHE_REKEY=1 to run it', file=sys.stderr) + return 2 if len(argv) != 2 or argv[0].startswith('-'): print(__doc__.split('\n\n')[1], file=sys.stderr) return 2 diff --git a/tools/startup/shader_trace_misses.cpp b/tools/startup/shader_trace_misses.cpp new file mode 100644 index 0000000000..4180f975ec --- /dev/null +++ b/tools/startup/shader_trace_misses.cpp @@ -0,0 +1,64 @@ +#include <algorithm> +#include <charconv> +#include <cstdint> +#include <fstream> +#include <iomanip> +#include <iostream> +#include <map> +#include <string> +#include <string_view> +#include <vector> + +// Extract the runtime's explicit translation misses. Other skipped work (bad +// heap, missing PSO, no targets, etc.) cannot be fixed by warming a shader. +static std::uint64_t missed_key(std::string_view line) +{ + const bool draw = line.rfind("x2w-frame draw ", 0) == 0 || line.rfind("x2w-frame draw-indexed ", 0) == 0; + const bool compute = line.rfind("x2w-frame cx-uav #", 0) == 0; + if (!draw && !compute) return 0; + auto pos = line.find(" key "); + if (pos == line.npos) return 0; + if (draw && line.substr(0, pos).find(" NOT drawn target ") == line.npos) return 0; + auto field = line.substr(pos + 5); + if (field.size() < 17 || field[16] != ' ') return 0; + auto tail = field.substr(17); + if (draw && tail != "no translation" && tail != "translation failed") return 0; + if (compute && tail.find(": skipped: no translation,") == tail.npos) return 0; + std::uint64_t key = 0; + auto end = field.data() + 16; + auto result = std::from_chars(field.data(), end, key, 16); + return result.ec == std::errc{} && result.ptr == end ? key : 0; +} + +int main(int argc, char** argv) +{ + if (argc != 2) { + std::cerr << "usage: shader_trace_misses <trap.log>\n"; + return 2; + } + std::ifstream input(argv[1], std::ios::binary); + if (!input) { + std::cerr << "cannot open trace: " << argv[1] << '\n'; + return 1; + } + std::map<std::uint64_t, std::uint64_t> counts; + std::string line; + while (std::getline(input, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (auto key = missed_key(line)) ++counts[key]; + } + if (input.bad() || !input.eof()) { + std::cerr << "error reading trace\n"; + return 1; + } + using Entry = std::pair<std::uint64_t, std::uint64_t>; + std::vector<Entry> ranked(counts.begin(), counts.end()); + std::sort(ranked.begin(), ranked.end(), [](const Entry& a, const Entry& b) { + return a.second != b.second ? a.second > b.second : a.first < b.first; + }); + for (auto [key, count] : ranked) { + std::cout << std::hex << std::setfill('0') << std::setw(16) << key + << '\t' << std::dec << count << '\n'; + } + return std::cout ? 0 : 1; +} diff --git a/tools/startup/window_status.py b/tools/startup/window_status.py new file mode 100644 index 0000000000..fac8f85e9d --- /dev/null +++ b/tools/startup/window_status.py @@ -0,0 +1,96 @@ +"""Keep the launched executable's own window at its requested initial size and update its caption.""" +import ctypes +from ctypes import wintypes as wt +import os +import re +import threading + + +def follow_window(pid, trap_log): + user = ctypes.WinDLL('user32', use_last_error=True) + kernel = ctypes.WinDLL('kernel32', use_last_error=True) + user.SetThreadDpiAwarenessContext.argtypes = [wt.HANDLE] + user.SetThreadDpiAwarenessContext(wt.HANDLE(-4)) + user.SendMessageTimeoutW.argtypes = (wt.HWND, wt.UINT, wt.WPARAM, wt.LPCWSTR, wt.UINT, wt.UINT, + ctypes.POINTER(ctypes.c_size_t)) + user.GetWindow.argtypes = (wt.HWND, wt.UINT) + user.GetWindow.restype = wt.HWND + user.GetMenu.argtypes = [wt.HWND] + user.GetMenu.restype = wt.HMENU + kernel.OpenProcess.restype = wt.HANDLE + process = kernel.OpenProcess(0x100000, False, pid) # SYNCHRONIZE + if not process: + return + window = None + caption = '' + position = 0 + remainder = b'' + previous = None + status = 'Xbox2Windows' + displayed = None + + @ctypes.WINFUNCTYPE(wt.BOOL, wt.HWND, wt.LPARAM) + def candidate(hwnd, unused): + nonlocal window + owner = wt.DWORD() + user.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + if owner.value != pid or not user.IsWindowVisible(hwnd) or user.GetWindow(hwnd, 4): + return True + name = ctypes.create_unicode_buffer(256) + user.GetClassNameW(hwnd, name, len(name)) + if name.value in ('#32770', 'X2WOutputWindow') or user.GetWindowLongW(hwnd, -20) & 0x80: + return True + window = hwnd + return False + + try: + while kernel.WaitForSingleObject(wt.HANDLE(process), 300) == 258: + if not window or not user.IsWindow(window): + window = None + user.EnumWindows(candidate, 0) + if not window: + continue + title = ctypes.create_unicode_buffer(512) + user.GetWindowTextW(window, title, len(title)) + caption = title.value + displayed = None + rect = wt.RECT(0, 0, 1280, 720) + if user.IsZoomed(window): + user.ShowWindowAsync(window, 9) + if user.AdjustWindowRectExForDpi(ctypes.byref(rect), user.GetWindowLongW(window, -16), + bool(user.GetMenu(window)), user.GetWindowLongW(window, -20), + user.GetDpiForWindow(window)): + # Size once, keep position, z-order and activation, let the owner process the request. + user.SetWindowPos(window, None, 0, 0, rect.right - rect.left, rect.bottom - rect.top, 0x4016) + try: + with open(trap_log, 'rb') as log: + size = os.fstat(log.fileno()).st_size + if position > size or size - position > 2**21: + position = max(0, size - 2**21) + remainder = b'' + log.seek(position) + chunk = log.read(2**21) + position = log.tell() + except OSError: + chunk = b'' + if chunk: + lines = (remainder + chunk).split(b'\n') + remainder = lines.pop()[-4096:] + for line in lines: + match = re.search(rb'heartbeat: (\d+) frames presented in ([\d.]+) s', line) + if match: + frame, seconds = int(match[1]), float(match[2]) + if previous and seconds > previous[1]: + fps = (frame - previous[0]) / (seconds - previous[1]) + status = f'Xbox2Windows | Frame {frame} | {fps:.1f} FPS' + previous = frame, seconds + if displayed != status: + text = f'{caption} | {status}' if caption else status + if user.SendMessageTimeoutW(window, 12, 0, text, 2, 150, ctypes.byref(ctypes.c_size_t())): + displayed = status + finally: + kernel.CloseHandle(wt.HANDLE(process)) + + +def start(pid, trap_log): + threading.Thread(target=follow_window, args=(pid, trap_log), name='title-window-status', daemon=True).start() diff --git a/tools/x2w/blake3.cpp b/tools/x2w/blake3.cpp new file mode 100644 index 0000000000..bd32f40fdc --- /dev/null +++ b/tools/x2w/blake3.cpp @@ -0,0 +1,176 @@ +// BLAKE3 hash mode, after the spec's reference implementation (reference_impl.rs): chunks of +// 1024 bytes in 64-byte blocks, a binary tree of parent nodes merged as chunks complete, the root +// node compressed with ROOT for the output. +#include "blake3.h" + +#include <algorithm> + +namespace x2w::tool { +namespace { + +constexpr std::array<std::uint32_t, 8> IV = {0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, + 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19}; +constexpr std::array<std::size_t, 16> MSG_PERMUTATION = {2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8}; +constexpr std::uint32_t CHUNK_START = 1; +constexpr std::uint32_t CHUNK_END = 2; +constexpr std::uint32_t PARENT = 4; +constexpr std::uint32_t ROOT = 8; +constexpr std::size_t CHUNK_LEN = 1024; +constexpr std::size_t BLOCK_LEN = 64; + +using Words16 = std::array<std::uint32_t, 16>; +using Cv = std::array<std::uint32_t, 8>; + +constexpr std::uint32_t rotr(std::uint32_t x, int n) { return (x >> n) | (x << (32 - n)); } + +void g(Words16& s, std::size_t a, std::size_t b, std::size_t c, std::size_t d, std::uint32_t mx, std::uint32_t my) { + s[a] = s[a] + s[b] + mx; + s[d] = rotr(s[d] ^ s[a], 16); + s[c] = s[c] + s[d]; + s[b] = rotr(s[b] ^ s[c], 12); + s[a] = s[a] + s[b] + my; + s[d] = rotr(s[d] ^ s[a], 8); + s[c] = s[c] + s[d]; + s[b] = rotr(s[b] ^ s[c], 7); +} + +void rounds_one(Words16& s, const Words16& m) { + g(s, 0, 4, 8, 12, m[0], m[1]); + g(s, 1, 5, 9, 13, m[2], m[3]); + g(s, 2, 6, 10, 14, m[4], m[5]); + g(s, 3, 7, 11, 15, m[6], m[7]); + g(s, 0, 5, 10, 15, m[8], m[9]); + g(s, 1, 6, 11, 12, m[10], m[11]); + g(s, 2, 7, 8, 13, m[12], m[13]); + g(s, 3, 4, 9, 14, m[14], m[15]); +} + +Words16 compress(const Cv& cv, const Words16& block, std::uint64_t counter, std::uint32_t block_len, + std::uint32_t flags) { + Words16 s = {cv[0], cv[1], cv[2], cv[3], cv[4], cv[5], cv[6], cv[7], IV[0], IV[1], IV[2], IV[3], + static_cast<std::uint32_t>(counter), static_cast<std::uint32_t>(counter >> 32), block_len, flags}; + Words16 m = block; + for (int r = 0; r < 7; ++r) { + rounds_one(s, m); + if (r == 6) break; + Words16 p{}; + for (std::size_t i = 0; i < 16; ++i) p[i] = m[MSG_PERMUTATION[i]]; + m = p; + } + for (std::size_t i = 0; i < 8; ++i) { + s[i] ^= s[i + 8]; + s[i + 8] ^= cv[i]; + } + return s; +} + +Words16 words_of(const std::array<std::uint8_t, 64>& block) { + Words16 w{}; + for (std::size_t i = 0; i < 16; ++i) + w[i] = std::uint32_t{block[4 * i]} | std::uint32_t{block[4 * i + 1]} << 8 | + std::uint32_t{block[4 * i + 2]} << 16 | std::uint32_t{block[4 * i + 3]} << 24; + return w; +} + +Cv first8(const Words16& w) { + Cv cv{}; + std::copy_n(w.begin(), 8, cv.begin()); + return cv; +} + +// A node not yet compressed: the root's output, or a chaining value. +struct Output { + Cv input_cv; + Words16 block; + std::uint64_t counter; + std::uint32_t block_len; + std::uint32_t flags; + Cv chaining_value() const { return first8(compress(input_cv, block, counter, block_len, flags)); } +}; + +Output parent_output(const Cv& left, const Cv& right) { + Words16 block{}; + std::copy(left.begin(), left.end(), block.begin()); + std::copy(right.begin(), right.end(), block.begin() + 8); + return Output{IV, block, 0, static_cast<std::uint32_t>(BLOCK_LEN), PARENT}; +} + +} // namespace + +Blake3::Blake3() { chunk_.cv = IV; } + +void Blake3::chunk_update(std::span<const std::uint8_t> data) { + while (!data.empty()) { + // A full block is compressed only once more input follows: the last one is the output's. + if (chunk_.block_len == BLOCK_LEN) { + const std::uint32_t start = chunk_.blocks_compressed == 0 ? CHUNK_START : 0; + chunk_.cv = first8(compress(chunk_.cv, words_of(chunk_.block), chunk_.counter, + static_cast<std::uint32_t>(BLOCK_LEN), start)); + ++chunk_.blocks_compressed; + chunk_.block.fill(0); + chunk_.block_len = 0; + } + const std::size_t take = std::min(BLOCK_LEN - chunk_.block_len, data.size()); + std::copy_n(data.begin(), take, chunk_.block.begin() + static_cast<std::ptrdiff_t>(chunk_.block_len)); + chunk_.block_len += take; + data = data.subspan(take); + } +} + +void Blake3::push_cv(Cv cv, std::uint64_t total_chunks) { + // Each trailing zero bit of the chunk count completes a subtree. + while ((total_chunks & 1) == 0) { + cv = parent_output(stack_.back(), cv).chaining_value(); + stack_.pop_back(); + total_chunks >>= 1; + } + stack_.push_back(cv); +} + +void Blake3::update(std::span<const std::uint8_t> data) { + while (!data.empty()) { + if (chunk_.len() == CHUNK_LEN) { + const Output out{chunk_.cv, words_of(chunk_.block), chunk_.counter, + static_cast<std::uint32_t>(chunk_.block_len), + (chunk_.blocks_compressed == 0 ? CHUNK_START : 0) | CHUNK_END}; + const std::uint64_t total = chunk_.counter + 1; + push_cv(out.chaining_value(), total); + chunk_ = Chunk{}; + chunk_.cv = IV; + chunk_.counter = total; + } + const std::size_t take = std::min(CHUNK_LEN - chunk_.len(), data.size()); + chunk_update(data.first(take)); + data = data.subspan(take); + } +} + +Blake3Hash Blake3::finalize() const { + Output out{chunk_.cv, words_of(chunk_.block), chunk_.counter, static_cast<std::uint32_t>(chunk_.block_len), + (chunk_.blocks_compressed == 0 ? CHUNK_START : 0) | CHUNK_END}; + for (std::size_t i = stack_.size(); i-- > 0;) out = parent_output(stack_[i], out.chaining_value()); + const Words16 w = compress(out.input_cv, out.block, 0, out.block_len, out.flags | ROOT); + Blake3Hash h{}; + for (std::size_t i = 0; i < 8; ++i) + for (std::size_t k = 0; k < 4; ++k) h[4 * i + k] = static_cast<std::uint8_t>(w[i] >> (8 * k)); + return h; +} + +Blake3Hash blake3(std::span<const std::uint8_t> data) { + Blake3 h; + h.update(data); + return h.finalize(); +} + +std::string to_hex(const Blake3Hash& h) { + static const char digits[] = "0123456789abcdef"; + std::string s; + s.reserve(64); + for (std::uint8_t b : h) { + s.push_back(digits[b >> 4]); + s.push_back(digits[b & 15]); + } + return s; +} + +} // namespace x2w::tool diff --git a/tools/x2w/blake3.h b/tools/x2w/blake3.h new file mode 100644 index 0000000000..d8c1bb935a --- /dev/null +++ b/tools/x2w/blake3.h @@ -0,0 +1,45 @@ +// BLAKE3 (https://github.com/BLAKE3-team/BLAKE3-specs), the plain hash mode with 32-byte output: a compact, +// portable, single-threaded implementation of the spec for the `x2w shaders` keys (A shader key uses the +// first 16 hex digits of the BLAKE3 of its container). +#pragma once + +#include <array> +#include <cstddef> +#include <cstdint> +#include <span> +#include <string> +#include <vector> + +namespace x2w::tool { + +using Blake3Hash = std::array<std::uint8_t, 32>; + +// Incremental hashing: update() any number of times, then finalize(). +class Blake3 { +public: + Blake3(); + void update(std::span<const std::uint8_t> data); + Blake3Hash finalize() const; + +private: + struct Chunk { + std::array<std::uint32_t, 8> cv{}; + std::uint64_t counter = 0; + std::array<std::uint8_t, 64> block{}; + std::size_t block_len = 0; + std::uint8_t blocks_compressed = 0; + std::size_t len() const { return 64 * std::size_t{blocks_compressed} + block_len; } + }; + void chunk_update(std::span<const std::uint8_t> data); + void push_cv(std::array<std::uint32_t, 8> cv, std::uint64_t total_chunks); + + Chunk chunk_; + // Chaining values of completed subtrees (at most 54 for 2^64 bytes). + std::vector<std::array<std::uint32_t, 8>> stack_; +}; + +Blake3Hash blake3(std::span<const std::uint8_t> data); +// Lowercase hexadecimal encoding of all 32 bytes. +std::string to_hex(const Blake3Hash& h); + +} // namespace x2w::tool diff --git a/tools/x2w/main.cpp b/tools/x2w/main.cpp new file mode 100644 index 0000000000..adfad50450 --- /dev/null +++ b/tools/x2w/main.cpp @@ -0,0 +1,39 @@ +// x2w: X2W's command-line tool. +// +// x2w shaders <paths...> --out <dir> [--jobs N] translates every shader container under the input paths, +// including SGD5 records and standalone containers. Output files are described in shaders_dump.h. +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> + +#include <iostream> +#include <string> +#include <vector> + +#include "shaders_dump.h" + +namespace { + +std::string utf8(const wchar_t* w) { + const int n = WideCharToMultiByte(CP_UTF8, 0, w, -1, nullptr, 0, nullptr, nullptr); + if (n <= 1) return {}; + std::string s(static_cast<std::size_t>(n), '\0'); + WideCharToMultiByte(CP_UTF8, 0, w, -1, s.data(), n, nullptr, nullptr); + s.pop_back(); // the NUL + return s; +} + +} // namespace + +// Wide arguments, as UTF-8 (paths outside the ANSI code page). +int wmain(int argc, wchar_t** argv) { + std::vector<std::string> args; + for (int i = 1; i < argc; ++i) args.push_back(utf8(argv[i])); + if (!args.empty() && args[0] == "shaders") { + args.erase(args.begin()); + return x2w::tool::shaders_main(args); + } + std::cerr << "usage: x2w shaders <paths...> --out <dir> [--jobs N]\n"; + return 2; +} diff --git a/tools/x2w/scan.cpp b/tools/x2w/scan.cpp new file mode 100644 index 0000000000..dbcae2509b --- /dev/null +++ b/tools/x2w/scan.cpp @@ -0,0 +1,424 @@ +// Shader discovery, naming, serialization and export scheduling. See scan.h. +#include "scan.h" + +#include <algorithm> +#include <atomic> +#include <charconv> +#include <chrono> +#include <cmath> +#include <cstdio> +#include <fstream> +#include <map> +#include <mutex> +#include <set> +#include <stdexcept> +#include <system_error> +#include <thread> + +#include "x2w_shader/dxbc.h" + +namespace x2w::tool { + +namespace fs = std::filesystem; + +std::uint64_t fnv64(Bytes bytes) { + std::uint64_t h = 1469598103934665603ull; + for (std::uint8_t b : bytes) h = (h ^ std::uint64_t{b}) * 0x00000100000001b3ull; + return h; +} + +Bytes bounded(Bytes bytes) { + if (bytes.size() < 28) return bytes; + const std::size_t total = std::size_t{bytes[24]} | std::size_t{bytes[25]} << 8 | std::size_t{bytes[26]} << 16 | + std::size_t{bytes[27]} << 24; + return total >= 32 && total <= bytes.size() ? bytes.first(total) : bytes; +} + +std::uint64_t key_of(const Blake3Hash& full) { + std::uint64_t k = 0; + for (std::size_t i = 0; i < 8; ++i) k = k << 8 | full[i]; + return k; +} + +std::string hex16(std::uint64_t v) { + char buf[17]; + std::snprintf(buf, sizeof buf, "%016llx", static_cast<unsigned long long>(v)); + return buf; +} + +namespace { + +// `{:#x}` of a usize. +std::string hex_alt(std::uint64_t v) { + char buf[24]; + std::snprintf(buf, sizeof buf, "0x%llx", static_cast<unsigned long long>(v)); + return buf; +} + +} // namespace + +std::optional<Bytes> Source::bytes(std::vector<std::uint8_t>& storage) const { + if (!packed) return data; + auto unpacked = record.unpack(); + if (!unpacked) return std::nullopt; + storage = std::move(*unpacked); + return Bytes(storage); +} + +std::string Source::label() const { + if (!packed) return "@" + hex_alt(offset); + return "@" + hex_alt(record.offset) + " " + std::string(record.name ? *record.name : std::string_view("?")); +} + +std::vector<Source> sources(Bytes data) { + std::vector<Source> out; + if (sgd5::is_sgd5(data)) { + for (const auto& r : sgd5::records(data)) { + Source s; + s.packed = true; + s.record = r; + out.push_back(s); + } + } + static constexpr std::uint8_t DXBC[4] = {'D', 'X', 'B', 'C'}; + for (std::size_t offset : sgd5::find_all(data, DXBC)) { + const Bytes rest = data.subspan(offset); + try { + (void)vs::dxbc::Container::parse(rest); + } catch (const std::exception&) { + continue; + } + Source s; + s.offset = offset; + s.data = rest; + out.push_back(s); + } + return out; +} + +namespace { + +void push_utf8(std::string& o, std::uint32_t c) { + if (c < 0x80) { + o.push_back(static_cast<char>(c)); + } else if (c < 0x800) { + o.push_back(static_cast<char>(0xC0 | c >> 6)); + o.push_back(static_cast<char>(0x80 | (c & 0x3F))); + } else if (c < 0x10000) { + o.push_back(static_cast<char>(0xE0 | c >> 12)); + o.push_back(static_cast<char>(0x80 | (c >> 6 & 0x3F))); + o.push_back(static_cast<char>(0x80 | (c & 0x3F))); + } else { + o.push_back(static_cast<char>(0xF0 | c >> 18)); + o.push_back(static_cast<char>(0x80 | (c >> 12 & 0x3F))); + o.push_back(static_cast<char>(0x80 | (c >> 6 & 0x3F))); + o.push_back(static_cast<char>(0x80 | (c & 0x3F))); + } +} + +// Encode the UTF-16 path for display, replacing unpaired surrogates with U+FFFD. +std::string display(const fs::path& p) { +#ifdef _WIN32 + const std::wstring& w = p.native(); + std::string o; + for (std::size_t i = 0; i < w.size(); ++i) { + std::uint32_t c = static_cast<std::uint16_t>(w[i]); + if (c >= 0xD800 && c < 0xDC00 && i + 1 < w.size()) { + const std::uint32_t d = static_cast<std::uint16_t>(w[i + 1]); + if (d >= 0xDC00 && d < 0xE000) { + push_utf8(o, 0x10000 + ((c - 0xD800) << 10) + (d - 0xDC00)); + ++i; + continue; + } + } + if (c >= 0xD800 && c < 0xE000) c = 0xFFFD; + push_utf8(o, c); + } + return o; +#else + const auto& n = p.native(); + return utf8_lossy(Bytes(reinterpret_cast<const std::uint8_t*>(n.data()), n.size())); +#endif +} + +bool read_file(const fs::path& p, std::vector<std::uint8_t>& out) { + std::ifstream f(p, std::ios::binary); + if (!f) return false; + f.seekg(0, std::ios::end); + const std::streamoff size = f.tellg(); + if (size < 0) return false; + f.seekg(0, std::ios::beg); + out.resize(static_cast<std::size_t>(size)); + if (size > 0 && !f.read(reinterpret_cast<char*>(out.data()), size)) return false; + return true; +} + +void visit(const fs::path& path, std::uintmax_t size, + const std::function<void(const std::string& file, Bytes data)>& f) { + if (size > MAX_FILE) return; + std::vector<std::uint8_t> data; + if (!read_file(path, data)) return; + f(display(path), Bytes(data)); +} + +} // namespace + +void walk_files(const std::vector<fs::path>& roots, const std::function<void(const std::string&, Bytes)>& f) { + for (const auto& root : roots) { + std::error_code ec; + // walkdir follows a root that is a link; it yields a root that is a file as itself. + const fs::file_status st = fs::status(root, ec); + if (ec) continue; + if (fs::is_regular_file(st)) { + const std::uintmax_t size = fs::file_size(root, ec); + visit(root, ec ? 0 : size, f); + continue; + } + if (!fs::is_directory(st)) continue; + fs::recursive_directory_iterator it(root, fs::directory_options::skip_permission_denied, ec); + if (ec) continue; + for (; it != fs::recursive_directory_iterator(); it.increment(ec)) { + if (ec) break; + std::error_code e2; + if (it->symlink_status(e2).type() != fs::file_type::regular || e2) continue; + const std::uintmax_t size = it->file_size(e2); + visit(it->path(), e2 ? 0 : size, f); + } + } +} + +std::string json_float(float v) { + if (!std::isfinite(v)) return "null"; + char buf[64]; + // Generate the shortest round-trip digits in d[.ddd]e[+-]XX form. + const auto r = std::to_chars(buf, buf + sizeof buf, v, std::chars_format::scientific); + std::string s(buf, r.ptr); + std::string sign; + if (!s.empty() && s[0] == '-') { + sign = "-"; + s.erase(0, 1); + } + const std::size_t e = s.find('e'); + std::string digits; + for (std::size_t i = 0; i < e; ++i) + if (s[i] != '.') digits.push_back(s[i]); + const int exp = std::stoi(s.substr(e + 1)); + const float a = std::fabs(v); + if ((a != 0.0f && a < 1e-4f) || a >= 1e16f) { + std::string o = sign + digits.substr(0, 1); + if (digits.size() > 1) o += "." + digits.substr(1); + return o + "e" + std::to_string(exp); + } + if (a == 0.0f) return sign + "0.0"; + std::string o = sign; + if (exp >= 0) { + const std::size_t whole = static_cast<std::size_t>(exp) + 1; + if (digits.size() <= whole) { + o += digits + std::string(whole - digits.size(), '0') + ".0"; + } else { + o += digits.substr(0, whole) + "." + digits.substr(whole); + } + } else { + o += "0." + std::string(static_cast<std::size_t>(-exp - 1), '0') + digits; + } + return o; +} + +std::string json_text(std::string_view s) { + std::string o = "\""; + for (char ch : s) { + const auto c = static_cast<unsigned char>(ch); + if (c == '"') { + o += "\\\""; + } else if (c == '\\') { + o += "\\\\"; + } else if (c < 0x20) { + char buf[8]; + std::snprintf(buf, sizeof buf, "\\u%04x", c); + o += buf; + } else { + o.push_back(ch); + } + } + o += "\""; + return o; +} + +std::string utf8_lossy(Bytes b) { + std::string o; + std::size_t i = 0; + while (i < b.size()) { + const std::uint8_t c = b[i]; + if (c < 0x80) { + o.push_back(static_cast<char>(c)); + ++i; + continue; + } + // The sequence's length and the range of its second byte (Unicode table 3-7). + std::size_t need = 0; + std::uint8_t lo = 0x80, hi = 0xBF; + if (c >= 0xC2 && c <= 0xDF) { + need = 2; + } else if (c >= 0xE0 && c <= 0xEF) { + need = 3; + if (c == 0xE0) lo = 0xA0; + if (c == 0xED) hi = 0x9F; + } else if (c >= 0xF0 && c <= 0xF4) { + need = 4; + if (c == 0xF0) lo = 0x90; + if (c == 0xF4) hi = 0x8F; + } + // Invalid: the lead byte and the continuation bytes that fit so far become one U+FFFD. + std::size_t got = 1; + bool ok = need != 0; + while (ok && got < need) { + if (i + got >= b.size()) { + ok = false; + break; + } + const std::uint8_t n = b[i + got]; + const std::uint8_t l = got == 1 ? lo : 0x80, h = got == 1 ? hi : 0xBF; + if (n < l || n > h) { + ok = false; + break; + } + ++got; + } + if (ok) { + o.append(reinterpret_cast<const char*>(b.data() + i), need); + } else { + o += "\xEF\xBF\xBD"; + } + i += got; + } + return o; +} + +namespace { + +std::string sanitize(std::string why) { + for (char& c : why) + if (c == '\t' || c == '\n' || c == '\r') c = ' '; + return why; +} + +bool write_bytes(const fs::path& p, const void* data, std::size_t n) { + std::ofstream f(p, std::ios::binary | std::ios::trunc); + if (!f) return false; + if (n) f.write(static_cast<const char*>(data), static_cast<std::streamsize>(n)); + return static_cast<bool>(f); +} + +void write_tsv(const fs::path& p, const char* header, std::vector<std::string> lines) { + std::sort(lines.begin(), lines.end()); + std::string text = header; + text += "\n"; + for (const auto& l : lines) text += l + "\n"; + if (!write_bytes(p, text.data(), text.size())) throw std::runtime_error("writing " + display(p)); +} + +struct Shared { + // Key -> BLAKE3 of the first container with it (collisions). + std::map<std::uint64_t, Blake3Hash> keys; + std::set<Blake3Hash> seen; + std::vector<std::string> index, programs, sources, failed, collisions; +}; + +} // namespace + +DumpCounts dump(const DumpOptions& o, const std::function<Made(const Found&)>& make) { + std::error_code ec; + fs::create_directories(o.out, ec); + if (ec || !fs::is_directory(o.out)) throw std::runtime_error("creating " + display(o.out)); + const std::size_t threads = std::max<std::size_t>(o.jobs, 1); + const auto started = std::chrono::steady_clock::now(); + std::mutex mutex; + Shared sh; + std::atomic<std::size_t> translated{0}, failed{0}; + walk_files(o.paths, [&](const std::string& file, Bytes data) { + const std::vector<Source> jobs = sources(data); + std::atomic<std::size_t> next{0}; + auto work = [&] { + for (std::size_t i; (i = next.fetch_add(1, std::memory_order_relaxed)) < jobs.size();) { + const Source& job = jobs[i]; + std::vector<std::uint8_t> storage; + const auto raw = job.bytes(storage); + if (!raw) continue; + Found found; + found.bytes = bounded(*raw); + found.full = blake3(found.bytes); + found.key = key_of(found.full); + found.name = hex16(found.key); + found.fnv = fnv64(found.bytes); + found.file = file; + { + std::lock_guard<std::mutex> lock(mutex); + sh.sources.push_back(found.name + "\t" + hex16(found.fnv) + "\t" + file + "\t" + job.label()); + if (!sh.seen.insert(found.full).second) continue; + const auto it = sh.keys.find(found.key); + if (it != sh.keys.end() && it->second != found.full) { + sh.collisions.push_back(found.name + "\t" + to_hex(it->second) + "\t" + to_hex(found.full)); + continue; + } + sh.keys[found.key] = found.full; + } + Made made; + try { + made = make(found); + } catch (const std::exception& e) { + // Record a failed container and continue exporting. + made = Made{}; + made.failed = std::string("panic: ") + e.what(); + } + if (made.failed) { + failed.fetch_add(1, std::memory_order_relaxed); + const std::string line = found.name + "\t" + hex16(found.fnv) + "\t" + + std::to_string(found.bytes.size()) + "\t" + file + "\t" + + sanitize(*made.failed); + std::lock_guard<std::mutex> lock(mutex); + sh.failed.push_back(line); + continue; + } + translated.fetch_add(1, std::memory_order_relaxed); + const bool ok = write_bytes(o.out / (found.name + ".dxil"), made.dxil.data(), made.dxil.size()) && + write_bytes(o.out / (found.name + ".json"), made.json.data(), made.json.size()); + if (!ok) continue; + std::lock_guard<std::mutex> lock(mutex); + sh.index.push_back(made.index_line); + for (auto& l : made.program_lines) sh.programs.push_back(std::move(l)); + } + }; + const std::size_t n = std::min(threads, jobs.size()); + std::vector<std::thread> pool; + pool.reserve(n); + for (std::size_t t = 0; t < n; ++t) pool.emplace_back(work); + for (auto& t : pool) t.join(); + }); + DumpCounts c; + c.containers = sh.seen.size(); + c.translated = translated.load(); + c.failed = failed.load(); + c.collisions = sh.collisions.size(); + write_tsv(o.out / "index.tsv", INDEX_HEADER, std::move(sh.index)); + write_tsv(o.out / "programs.tsv", PROGRAMS_HEADER, std::move(sh.programs)); + write_tsv(o.out / "sources.tsv", SOURCES_HEADER, std::move(sh.sources)); + write_tsv(o.out / "failed.tsv", FAILED_HEADER, std::move(sh.failed)); + write_tsv(o.out / "collisions.tsv", COLLISIONS_HEADER, std::move(sh.collisions)); + const double seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - started).count(); + char secs[64]; + std::snprintf(secs, sizeof secs, "%.0f", seconds); + // No cache: nothing is cached or missing, and there are no orphan entries (no orphans/ and + // orphans.tsv, and no orphan_entries line). + c.summary = "build " + o.build + "\ncontainers " + std::to_string(c.containers) + "\ncached 0\ntranslated " + + std::to_string(c.translated) + "\nmissing 0\nfailed " + std::to_string(c.failed) + "\nseconds " + + secs + "\n"; + if (!write_bytes(o.out / "summary.txt", c.summary.data(), c.summary.size())) + throw std::runtime_error("writing summary.txt"); + if (o.manifest) { + const std::string m = o.manifest(c.translated); + if (!write_bytes(o.out / "manifest.txt", m.data(), m.size())) throw std::runtime_error("writing manifest.txt"); + } + return c; +} + +} // namespace x2w::tool diff --git a/tools/x2w/scan.h b/tools/x2w/scan.h new file mode 100644 index 0000000000..bed1a3336a --- /dev/null +++ b/tools/x2w/scan.h @@ -0,0 +1,141 @@ +// Discover and name containers, format export data, and schedule per-container work across worker threads. +// A mutex protects shared state and TSV output is sorted. +#pragma once + +#include <array> +#include <cstddef> +#include <cstdint> +#include <filesystem> +#include <functional> +#include <optional> +#include <span> +#include <string> +#include <utility> +#include <vector> + +#include "blake3.h" +#include "sgd5.h" + +namespace x2w::tool { + +using Bytes = std::span<const std::uint8_t>; + +// Files above this size are skipped (read whole into memory). +inline constexpr std::uint64_t MAX_FILE = std::uint64_t{2} << 30; + +// X2W's `fnv_bytes` (d3d12_draw.inl): FNV-1a 64's prime, but its basis is 1469598103934665603, the +// standard basis (14695981039346656037) without its last digit. Kept as X2W computes it. +std::uint64_t fnv64(Bytes bytes); + +// The container at the start of `bytes`, cut to its header's size. +Bytes bounded(Bytes bytes); + +// Interpret the first 16 hexadecimal digits of the container's BLAKE3 hash as a big-endian u64. +std::uint64_t key_of(const Blake3Hash& full); + +// `{:016x}`. +std::string hex16(std::uint64_t v); + +// A shader container in a file: as is, or packed in an SGD5 record. Borrows the file's bytes. +struct Source { + bool packed = false; + // Raw: the offset of "DXBC" and the bytes from there to the end of the file. + std::size_t offset = 0; + Bytes data; + // Packed. + sgd5::Record record; + + // The container bytes; nullopt if a packed record is corrupt. `storage` holds unpacked bytes. + std::optional<Bytes> bytes(std::vector<std::uint8_t>& storage) const; + // "@0x1f" or "@0x1f PS_name" ("?" for a record without a name). + std::string label() const; +}; + +// The packed records of SGD5 data, and every container stored as is (the executable keeps some +// records uncompressed), found by its magic and kept where dxbc::Container::parse accepts it. +std::vector<Source> sources(Bytes data); + +// Visit roots depth first in directory order without following links. Include readable regular files up to +// MAX_FILE bytes, including roots that are themselves files. Path names are formatted for display. +void walk_files(const std::vector<std::filesystem::path>& roots, + const std::function<void(const std::string& file, Bytes data)>& f); + +// Format a finite float with its shortest round-trip digits. Use exponent form below 1e-4 and from 1e16 +// upwards. Emit "null" for nonfinite values. +std::string json_float(float v); +// A JSON string of `s`: `"` and `\` escaped, controls as \u00XX. +std::string json_text(std::string_view s); +// String::from_utf8_lossy. +std::string utf8_lossy(Bytes bytes); +// Format a JSON array with commas between items. +template <class Items, class F> +std::string json_list(const Items& items, F f) { + std::string o = "["; + bool first = true; + for (const auto& item : items) { + if (!first) o += ","; + first = false; + o += f(item); + } + o += "]"; + return o; +} + +// One container, as the export loop hands it to the translator side. +struct Found { + std::uint64_t key = 0; + // hex16(key). + std::string name; + std::uint64_t fnv = 0; + Blake3Hash full{}; + // bounded() of the source's bytes. + Bytes bytes; + // The file it was first found in. + std::string file; +}; + +// What the translator side made of a container. +struct Made { + // nullopt: translated; else why not (one line of failed.tsv; tabs and newlines are replaced). + std::optional<std::string> failed; + std::vector<std::uint8_t> dxil; + std::string json; + // index.tsv's row and programs.tsv's rows for it. + std::string index_line; + std::vector<std::string> program_lines; +}; + +struct DumpOptions { + std::filesystem::path out; + std::vector<std::filesystem::path> paths; + // Worker threads per file (export_x2w: default 4, at least 1). + std::size_t jobs = 4; + // summary.txt's `build` line. + std::string build; + // manifest.txt, whole, given the number of records written (none: no manifest). + std::function<std::string(std::size_t records)> manifest; +}; + +struct DumpCounts { + std::size_t containers = 0; + std::size_t translated = 0; + std::size_t failed = 0; + std::size_t collisions = 0; + std::string summary; +}; + +// Every container found (once by its BLAKE3) goes through `make` on the worker threads; writes <key>.dxil, +// <key>.json, index.tsv, programs.tsv, sources.tsv, failed.tsv, collisions.tsv, summary.txt and +// manifest.txt into `out`. Throws std::runtime_error when `out` cannot be made or a tsv cannot be written. +DumpCounts dump(const DumpOptions& o, const std::function<Made(const Found&)>& make); + +// The header line of each tsv file dump() writes. +inline constexpr const char* INDEX_HEADER = + "key\tstage\tcontainer_fnv64\tcontainer_blake3\tcontainer_bytes\tdxil_bytes\tcache\tthreads\tstores\t" + "stores_by_address\tbuilder\tprograms\tfirst_source"; +inline constexpr const char* PROGRAMS_HEADER = "code_fnv64\tcode_bytes\tnative_stage\twave\tform\tcontainer_key"; +inline constexpr const char* SOURCES_HEADER = "key\tcontainer_fnv64\tfile\tlabel"; +inline constexpr const char* FAILED_HEADER = "key\tcontainer_fnv64\tcontainer_bytes\tfirst_source\treason"; +inline constexpr const char* COLLISIONS_HEADER = "key\tkept_blake3\tdropped_blake3"; + +} // namespace x2w::tool diff --git a/tools/x2w/sgd5.cpp b/tools/x2w/sgd5.cpp new file mode 100644 index 0000000000..eb5ea96172 --- /dev/null +++ b/tools/x2w/sgd5.cpp @@ -0,0 +1,115 @@ +// The raw deflate decoder is X2W's own (startup_stubs/inflate.h, written from RFC 1951) in place of +// zlib-rs. +#include "sgd5.h" + +#include <cstring> + +#include "startup_stubs/inflate.h" + +namespace x2w::tool::sgd5 { +namespace { + +constexpr std::uint8_t MARKER[4] = {0xE7, 0xDC, 0x0D, 0x00}; // 0x000D_DCE7 little endian +// Containers are at most a few MiB; refuse to allocate for absurd sizes. +constexpr std::size_t MAX_UNPACKED = std::size_t{64} << 20; + +std::optional<std::size_t> u32_at(std::span<const std::uint8_t> file, std::size_t o) { + if (o > file.size() || file.size() - o < 4) return std::nullopt; + return std::size_t{file[o]} | std::size_t{file[o + 1]} << 8 | std::size_t{file[o + 2]} << 16 | + std::size_t{file[o + 3]} << 24; +} + +bool is_ascii_graphic(std::uint8_t b) { return b >= 0x21 && b <= 0x7E; } + +// The printable name that ends at `nul` and follows its length byte. +std::optional<std::string_view> name_before(std::span<const std::uint8_t> file, std::size_t nul) { + std::size_t run = 0; + for (std::size_t p = nul; p-- > 0;) { + if (!is_ascii_graphic(file[p])) { + run = p + 1; + break; + } + } + // From 32 characters on, the length byte is printable too. + for (std::size_t l = run == 0 ? 0 : run - 1; l < nul; ++l) { + if (std::size_t{file[l]} == nul - l) { + // (Every byte after the length byte is printable ASCII: valid UTF-8.) + return std::string_view(reinterpret_cast<const char*>(file.data() + l + 1), nul - l - 1); + } + } + return std::nullopt; +} + +std::optional<Record> record(std::span<const std::uint8_t> file, std::size_t at) { + if (at < 4) return std::nullopt; + const auto n = u32_at(file, at - 4); + if (!n) return std::nullopt; + const auto unpacked_size = u32_at(file, at + 8); + if (!unpacked_size) return std::nullopt; + const auto n2 = u32_at(file, at + 4); + if (!n2 || *n2 != *n || *n < 12 || *unpacked_size > MAX_UNPACKED) return std::nullopt; + if (at < 6) return std::nullopt; + const std::size_t nul = at - 6; + Record r; + r.offset = at; + r.name = file[nul] == 0 ? name_before(file, nul) : std::nullopt; + r.kind = file[at - 5]; + if (at + *n > file.size()) return std::nullopt; + r.packed = file.subspan(at + 12, *n - 12); + r.unpacked_size = *unpacked_size; + return r; +} + +} // namespace + +std::optional<std::vector<std::uint8_t>> Record::unpack() const { + // Decode raw deflate with a 15-bit window. Require an end marker and exactly unpacked_size output bytes. + // Ignore trailing input. + std::vector<std::uint8_t> out(unpacked_size); + std::uint8_t none = 0; + x2w_inflate::Stream s{packed.data(), packed.size(), 0, out.empty() ? &none : out.data(), out.size()}; + if (!x2w_inflate::inflate_raw(s) || s.out_pos != unpacked_size) return std::nullopt; + return out; +} + +std::vector<std::size_t> find_all(std::span<const std::uint8_t> hay, std::span<const std::uint8_t> needle) { + std::vector<std::size_t> out; + if (needle.empty() || hay.size() < needle.size()) return out; + const std::uint8_t* base = hay.data(); + const std::size_t last = hay.size() - needle.size(); + std::size_t at = 0; + while (at <= last) { + const void* hit = std::memchr(base + at, needle[0], last - at + 1); + if (!hit) break; + at = static_cast<std::size_t>(static_cast<const std::uint8_t*>(hit) - base); + if (std::memcmp(base + at, needle.data(), needle.size()) == 0) { + out.push_back(at); + at += needle.size(); + } else { + ++at; + } + } + return out; +} + +bool is_sgd5(std::span<const std::uint8_t> file) { + const std::uint8_t* end = file.data() + file.size(); + if (file.size() < 4) return false; + for (const std::uint8_t* p = file.data(); p + 4 <= end;) { + const void* hit = std::memchr(p, MAGIC[0], static_cast<std::size_t>(end - p) - 3); + if (!hit) return false; + p = static_cast<const std::uint8_t*>(hit); + if (std::memcmp(p, MAGIC, 4) == 0) return true; + ++p; + } + return false; +} + +std::vector<Record> records(std::span<const std::uint8_t> file) { + std::vector<Record> out; + for (std::size_t at : find_all(file, MARKER)) + if (auto r = record(file, at)) out.push_back(*r); + return out; +} + +} // namespace x2w::tool::sgd5 diff --git a/tools/x2w/sgd5.h b/tools/x2w/sgd5.h new file mode 100644 index 0000000000..2ea6d7cb91 --- /dev/null +++ b/tools/x2w/sgd5.h @@ -0,0 +1,46 @@ +// `SGD5`: the engine's shader file. Each record holds one shader container, deflate-packed. The header +// tables are not decoded yet, so records are found by their marker and cross-checked by their sizes: +// +// u8 name length (with NUL), name, NUL, u8 kind, +// u32 n, u32 0x000DDCE7, u32 n, u32 unpacked size, raw deflate (n - 12 bytes) +#pragma once + +#include <cstddef> +#include <cstdint> +#include <optional> +#include <span> +#include <string_view> +#include <vector> + +namespace x2w::tool::sgd5 { + +inline constexpr std::uint8_t MAGIC[4] = {'S', 'G', 'D', '5'}; + +// Borrows the file it was found in. +struct Record { + // Offset of the marker in the file. + std::size_t offset = 0; + // Like `PS_<name>_<hash>_Wrapped`; nullopt if the bytes before the record do not read as one. + std::optional<std::string_view> name; + // Record type, meaning unknown (0x32 most shaders, 0x41 mesh shaders and some material + // families, 0x3c compute, 0x40, 0x42). + std::uint8_t kind = 0; + std::span<const std::uint8_t> packed; + std::size_t unpacked_size = 0; + + // The container, or nullopt if the stream is corrupt (does not end, or does not inflate to + // exactly the stated size). + std::optional<std::vector<std::uint8_t>> unpack() const; +}; + +// An SGD5 file, or a file holding one (an archive: records are found by their marker, so no index +// is needed). +bool is_sgd5(std::span<const std::uint8_t> file); + +// Every record in an SGD5 file, in file order. +std::vector<Record> records(std::span<const std::uint8_t> file); + +// Offsets of every occurrence of `needle` (non-overlapping, as memchr::memmem::find_iter). +std::vector<std::size_t> find_all(std::span<const std::uint8_t> hay, std::span<const std::uint8_t> needle); + +} // namespace x2w::tool::sgd5 diff --git a/tools/x2w/shaders_dump.cpp b/tools/x2w/shaders_dump.cpp new file mode 100644 index 0000000000..3474e033fd --- /dev/null +++ b/tools/x2w/shaders_dump.cpp @@ -0,0 +1,497 @@ +// Shader export, manifest generation, and D3D12 capability probing. See shaders_dump.h. +#include "shaders_dump.h" + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <cstdio> +#include <cstdlib> +#include <iostream> +#include <stdexcept> +#include <variant> + +#include "x2w_shader/dxbc.h" +#include "x2w_shader/emit/lower.h" +#include "x2w_shader/emit/shader.h" +#include "x2w_shader/gfx10/mod.h" +#include "x2w_shader/spill.h" + +#ifndef X2W_TOOL_SOURCE_DIR +#define X2W_TOOL_SOURCE_DIR "." +#endif + +namespace x2w::tool { + +namespace native = vs::native; +using native::HwStage; + +namespace { + +bool translated_stage(HwStage s) { + return s == HwStage::Vs || s == HwStage::Ps || s == HwStage::Cs || s == HwStage::Ms; +} + +std::string u(std::uint64_t v) { return std::to_string(v); } +const char* b(bool v) { return v ? "true" : "false"; } + +// The console programs of a container's DXIL (or ACCC) part; empty when there are none or they do +// not read. +std::vector<native::NativeProgram> native_of(Bytes container) { + try { + const auto c = vs::dxbc::Container::parse(container); + const auto* part = c.part(vs::dxbc::FourCC::DXIL); + if (!part) part = c.part(vs::dxbc::FourCC::ACCC); + if (!part) return {}; + return native::native_programs(part->data); + } catch (const vs::ShaderError&) { + return {}; + } +} + +std::string used_json(const native::UsedResource& x) { + return "{\"kind\":" + json_text(debug(x.kind)) + ",\"root\":" + json_text(debug(x.root)) + + ",\"table_offset_dwords\":" + u(x.table_offset_dwords) + ",\"lower_bound\":" + u(x.lower_bound) + + ",\"stride\":" + u(x.stride) + ",\"dwords\":" + u(x.dwords) + ",\"user_data\":" + u(x.user_data) + + ",\"slot\":" + u(x.slot) + "}"; +} + +std::string threads3(const std::array<std::uint32_t, 3>& t, const char* open, const char* close) { + return open + u(t[0]) + "," + u(t[1]) + "," + u(t[2]) + close; +} + +} // namespace + +const char* debug(HwStage s) { + switch (s) { + case HwStage::Ls: return "Ls"; + case HwStage::Hs: return "Hs"; + case HwStage::Es: return "Es"; + case HwStage::Gs: return "Gs"; + case HwStage::Vs: return "Vs"; + case HwStage::Ps: return "Ps"; + case HwStage::Ms: return "Ms"; + case HwStage::Cs: return "Cs"; + } + return "?"; +} + +std::string debug(const native::RootType& r) { + using K = native::RootType::Kind; + switch (r.kind) { + case K::Constants: return "Constants"; + case K::Descriptor: return "Descriptor"; + case K::Table: return "Table"; + case K::ImmediateSampler: return "ImmediateSampler"; + case K::ResourceHeap: return "ResourceHeap"; + case K::SamplerHeap: return "SamplerHeap"; + case K::Other: return "Other(" + u(r.other) + ")"; + } + return "?"; +} + +std::string debug(const native::ResourceType& r) { + using K = native::ResourceType::Kind; + switch (r.kind) { + case K::Srv: return "Srv"; + case K::Sampler: return "Sampler"; + case K::Cbv: return "Cbv"; + case K::Uav: return "Uav"; + case K::Other: return "Other(" + u(r.other) + ")"; + } + return "?"; +} + +std::vector<Program> programs_of(Bytes container) { + std::vector<Program> out; + for (auto& p : native_of(container)) { + const std::vector<std::uint8_t> patched = p.patched_code(); + if (patched != p.code) { + Program q; + q.fnv = fnv64(patched); + q.bytes = patched.size(); + q.stage = p.stage; + q.wave64 = p.wave64; + q.form = "patched"; + q.native = p; + out.push_back(std::move(q)); + } + Program q; + q.fnv = fnv64(p.code); + q.bytes = p.code.size(); + q.stage = p.stage; + q.wave64 = p.wave64; + q.form = "code"; + q.native = std::move(p); + out.push_back(std::move(q)); + } + return out; +} + +bool stores(const native::NativeProgram& program) { + using vs::gfx10::Encoding; + std::vector<vs::gfx10::Instruction> code; + try { + code = vs::gfx10::decode(program.code); + } catch (const vs::ShaderError&) { + return true; + } + for (const auto& i : code) { + const auto name = i.name(); + switch (i.encoding) { + case Encoding::Mubuf: + case Encoding::Mtbuf: + case Encoding::Smem: + case Encoding::Flat: + case Encoding::Global: + if (!name || ((name->find("store") != std::string_view::npos || + name->find("atomic") != std::string_view::npos) && + name->find("scratch") == std::string_view::npos)) + return true; + break; + case Encoding::Sop1: + if (!name || *name == "s_setpc_b64" || *name == "s_swappc_b64") return true; + break; + default: break; + } + } + return false; +} + +bool stores_by_address(const native::NativeProgram& program) { + using vs::gfx10::Encoding; + std::vector<vs::gfx10::Instruction> code; + try { + code = vs::gfx10::decode(program.code); + } catch (const vs::ShaderError&) { + return true; + } + for (const auto& i : code) { + if (i.encoding != Encoding::Flat && i.encoding != Encoding::Global) continue; + const auto name = i.name(); + if (!name || ((name->find("store") != std::string_view::npos || + name->find("atomic") != std::string_view::npos) && + name->find("scratch") == std::string_view::npos)) + return true; + } + return false; +} + +Extras extras(Bytes container) { + const std::vector<native::NativeProgram> programs = native_of(container); + Extras e; + for (const auto& p : programs) { + if (const auto* cs = std::get_if<native::ComputeIo>(&p.io)) { + if (cs->threads[0] > 0 && cs->threads[1] > 0 && cs->threads[2] > 0) { + e.threads = cs->threads; + break; + } + } + } + for (const auto& p : programs) { + if (translated_stage(p.stage)) { + e.used = p.used; + break; + } + } + e.stores = programs.empty(); + e.stores_by_address = programs.empty(); + for (const auto& p : programs) e.stores = e.stores || stores(p); + for (const auto& p : programs) e.stores_by_address = e.stores_by_address || stores_by_address(p); + for (const auto& p : programs) e.builder = e.builder || vs::spill::is_spilled(p); + return e; +} + +std::string json(const vs::HostShader& s, const std::vector<Program>& programs, const Extras* extras, + const std::string& key, std::uint64_t fnv, const Blake3Hash& full, std::size_t size, + const char* cache) { + std::string o = "{\n"; + o += " \"key\": " + json_text(key) + ",\n"; + o += " \"container_fnv64\": \"" + hex16(fnv) + "\",\n"; + o += " \"container_blake3\": " + json_text(to_hex(full)) + ",\n"; + o += " \"container_bytes\": " + u(size) + ",\n"; + o += " \"cache\": " + json_text(cache) + ",\n"; + o += " \"stage\": " + json_text(debug(s.stage)) + ",\n"; + o += " \"dxil_bytes\": " + u(s.dxil.size()) + ",\n"; + o += " \"user_data_dwords\": " + u(s.user_data_dwords()) + ",\n"; + const std::string ud = json_list(s.user_data, [](const vs::UserData& x) { + return "{\"index\":" + u(x.index) + ",\"slot\":" + u(x.slot) + ",\"root\":" + json_text(debug(x.root)) + + ",\"dword\":" + u(x.dword) + "}"; + }); + o += " \"user_data\": " + ud + ",\n"; + o += " \"samplers\": " + + json_list(s.samplers, [](const std::array<std::uint32_t, 4>& w) { + return json_list(w, [](std::uint32_t v) { return u(v); }); + }) + + ",\n"; + const std::string ss = json_list(s.static_samplers, [](const vs::StaticSampler& t) { + return "{\"filter\":" + u(t.filter) + ",\"address\":[" + u(t.address[0]) + "," + u(t.address[1]) + "," + + u(t.address[2]) + "],\"mip_lod_bias\":" + json_float(t.mip_lod_bias) + + ",\"max_anisotropy\":" + u(t.max_anisotropy) + ",\"comparison\":" + u(t.comparison) + + ",\"border\":" + u(t.border) + ",\"min_lod\":" + json_float(t.min_lod) + + ",\"max_lod\":" + json_float(t.max_lod) + "}"; + }); + o += " \"static_samplers\": " + ss + ",\n"; + auto bytes = [](const std::vector<std::uint8_t>& v) { return json_list(v, [](std::uint8_t x) { return u(x); }); }; + o += " \"root_cbvs\": " + bytes(s.root_cbvs) + ",\n"; + o += " \"root_srvs\": " + bytes(s.root_srvs) + ",\n"; + o += " \"root_uavs\": " + bytes(s.root_uavs) + ",\n"; + const std::string riv = json_list(s.root_indexed_views, [](const vs::resource::RootIndexedView& v) { + return "{\"table_slot\":" + u(v.table_slot) + ",\"constant_slot\":" + u(v.constant_slot) + + ",\"constant_dword\":" + u(v.constant_dword) + ",\"byte_offset\":" + u(v.byte_offset) + + ",\"shift\":" + u(v.shift) + "}"; + }); + o += " \"root_indexed_views\": " + riv + ",\n"; + // Pipeline creation's own reading of the programs (`pipeline::translate`). + if (extras) { + const std::string threads = extras->threads ? threads3(*extras->threads, "[", "]") : "null"; + o += " \"threads\": " + threads + ",\n"; + o += " \"used\": " + json_list(extras->used, used_json) + ",\n"; + o += std::string(" \"stores\": ") + b(extras->stores) + ",\n"; + o += std::string(" \"stores_by_address\": ") + b(extras->stores_by_address) + ",\n"; + o += std::string(" \"builder\": ") + b(extras->builder) + ",\n"; + } + // Derived, not HostShader fields: the emitted container's parts, and the console program the + // translation is made from. + std::string parts = "[]"; + try { + const auto c = vs::dxbc::Container::parse(s.dxil); + parts = json_list(c.parts, [](const vs::dxbc::Part& p) { + return "{\"fourcc\":" + json_text(utf8_lossy(Bytes(p.fourcc.b))) + ",\"bytes\":" + u(p.data.size()) + + "}"; + }); + } catch (const vs::ShaderError&) { + } + o += " \"derived_dxil_parts\": " + parts + ",\n"; + const Program* translated = nullptr; + for (const auto& p : programs) { + if (std::string_view(p.form) == "code" && translated_stage(p.stage)) { + translated = &p; + break; + } + } + if (translated) { + const native::NativeProgram& n = translated->native; + std::string threads = "null"; + if (const auto* cs = std::get_if<native::ComputeIo>(&n.io)) threads = threads3(cs->threads, "[", "]"); + else if (const auto* ms = std::get_if<native::MeshIo>(&n.io)) threads = "[" + u(ms->threads) + ",1,1]"; + const std::string layout = json_list(n.layout, [](const native::RootParam& r) { + return "{\"root\":" + json_text(debug(r.root)) + ",\"table_offset_dwords\":" + u(r.table_offset_dwords) + + ",\"sgprs\":" + u(r.sgprs) + ",\"base_register\":" + u(r.base_register) + + ",\"user_data\":" + u(r.user_data) + ",\"slot\":" + u(r.slot) + "}"; + }); + const std::string used = json_list(n.used, used_json); + o += " \"derived_native\": {\"stage\":" + json_text(debug(n.stage)) + + ",\"wave_size\":" + (n.wave64 ? "64" : "32") + ",\"vgprs\":" + u(n.vgprs) + ",\"threads\":" + threads + + ",\"code_bytes\":" + u(translated->bytes) + ",\"code_fnv64\":\"" + hex16(translated->fnv) + + "\",\"layout\":" + layout + ",\"used\":" + used + "},\n"; + } else { + o += " \"derived_native\": null,\n"; + } + const std::string progs = json_list(programs, [](const Program& p) { + return "{\"stage\":" + json_text(debug(p.stage)) + ",\"form\":" + json_text(p.form) + + ",\"wave_size\":" + (p.wave64 ? "64" : "32") + ",\"code_bytes\":" + u(p.bytes) + + ",\"code_fnv64\":\"" + hex16(p.fnv) + "\"}"; + }); + o += " \"derived_programs\": " + progs + "\n"; + o += "}\n"; + return o; +} + +Made make(const Found& f) { + Made m; + const std::vector<Program> programs = programs_of(f.bytes); + vs::HostShader shader; + try { + shader = vs::translate(f.bytes); + } catch (const vs::ShaderError& e) { + m.failed = e.to_string(); + return m; + } + const char* cache_word = "translated"; + const Extras ex = extras(f.bytes); + m.json = json(shader, programs, &ex, f.name, f.fnv, f.full, f.bytes.size(), cache_word); + const std::string threads = ex.threads ? threads3(*ex.threads, "", "") : "-"; + m.index_line = f.name + "\t" + debug(shader.stage) + "\t" + hex16(f.fnv) + "\t" + to_hex(f.full) + "\t" + + u(f.bytes.size()) + "\t" + u(shader.dxil.size()) + "\t" + cache_word + "\t" + threads + "\t" + + (ex.stores ? "1" : "0") + "\t" + (ex.stores_by_address ? "1" : "0") + "\t" + + (ex.builder ? "1" : "0") + "\t" + u(programs.size()) + "\t" + f.file; + for (const auto& p : programs) + m.program_lines.push_back(hex16(p.fnv) + "\t" + u(p.bytes) + "\t" + debug(p.stage) + "\t" + + (p.wave64 ? "64" : "32") + "\t" + p.form + "\t" + f.name); + m.dxil = std::move(shader.dxil); + return m; +} + +namespace { + +using Microsoft::WRL::ComPtr; + +constexpr std::uint32_t PORTABLE_VIEWS = 1'000'000; +constexpr std::uint32_t UNCAPPED_VIEWS = 1u << 21; +constexpr std::uint32_t RAW_TWINS = 1u << 21; + +std::optional<std::string> env(const char* name) { + const char* v = std::getenv(name); + if (!v) return std::nullopt; + return std::string(v); +} + +} // namespace + +std::string probe_host() { + // Create the default adapter device at feature level 12_0. + ComPtr<ID3D12Device> device; + if (FAILED(D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) + return "no host D3D12 device: the translator keeps its defaults"; + std::string log; + D3D12_FEATURE_DATA_D3D12_OPTIONS1 o1{}; + if (SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &o1, sizeof o1))) { + vs::lower::set_host_max_wave(o1.WaveLaneCountMax); + // Identify the device adapter by its LUID. + bool amd = false; + ComPtr<IDXGIFactory4> factory; + if (SUCCEEDED(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory)))) { + ComPtr<IDXGIAdapter1> adapter; + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(factory->EnumAdapterByLuid(device->GetAdapterLuid(), IID_PPV_ARGS(&adapter))) && + SUCCEEDED(adapter->GetDesc1(&desc))) + amd = desc.VendorId == 0x1002; + } + // (RDNA has waves of 32 and 64, the vendor's older cards of 64 alone.) + vs::lower::set_host_rdna(amd && o1.WaveLaneCountMin == 32 && o1.WaveLaneCountMax == 64); + log += "host wave lanes " + u(o1.WaveLaneCountMin) + ".." + u(o1.WaveLaneCountMax) + (amd ? ", AMD" : ""); + } + // Probe the supported view heap limit. + auto fits = [&](std::uint32_t count) { + D3D12_DESCRIPTOR_HEAP_DESC d{}; + d.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + d.NumDescriptors = count; + d.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + ComPtr<ID3D12DescriptorHeap> heap; + return SUCCEEDED(device->CreateDescriptorHeap(&d, IID_PPV_ARGS(&heap))); + }; + const auto raw = env("X2W_SHADERCFG_RAW_VIEWS"); + const bool raw_twins = !raw || *raw != "0"; + const bool twins = raw_twins && fits(2 * RAW_TWINS); + if (twins) vs::shader::set_raw_views(RAW_TWINS); + // (The twins lie past the null slot.) + const std::uint32_t views = twins ? RAW_TWINS : fits(UNCAPPED_VIEWS) ? UNCAPPED_VIEWS : PORTABLE_VIEWS; + vs::shader::set_view_heap_limit(views - 1); + log += "; host view heaps hold " + u(views) + " views" + (twins ? ", raw twins" : ""); + return log; +} + +std::vector<std::pair<std::string, std::string>> settings() { + const auto host = vs::lower::host_settings(); + std::string translator; + for (std::uint8_t x : vs::translation_fingerprint()) { + char buf[3]; + std::snprintf(buf, sizeof buf, "%02x", x); + translator += buf; + } + std::vector<std::pair<std::string, std::string>> out = { + {"translator", translator}, + {"max_wave", u(host[0])}, + {"view_heap_limit", u(host[1])}, + {"raw_views", u(host[2])}, + {"host_rdna", u(host[3])}, + {"loop_limit", u(vs::loop_limit())}, + {"group_sync", u(vs::group_sync())}, + {"shader_opt", vs::hex_alt(vs::shader_opt())}, + }; + for (const char* name : + {"X2W_SHADERCFG_WAVE_WIDE", "X2W_SHADERCFG_WAVE_DEEP_SKIPS", "X2W_SHADERCFG_WAVE_OWN_BITS", "X2W_SHADERCFG_WAVE_LOCAL", + "X2W_SHADERCFG_F16_NEAREST", "X2W_SHADERCFG_HELPER_OWN", "X2W_SHADERCFG_FIRSTLANE_OWN", "X2W_SHADERCFG_FIRST_HALF", + "X2W_SHADERCFG_STRICT_JOINS", "X2W_SHADERCFG_MESH_OUTPUT_STRICT", "X2W_SHADERCFG_BVH_FENCES", "X2W_SHADERCFG_BVH_BOUNDS"}) + out.emplace_back(name, env(name).value_or("")); + return out; +} + +namespace { + +std::string build_hex() { + const auto fp = vs::translation_fingerprint(); + return to_hex(blake3(fp)); +} + +// Record the source tree commit and whether the working tree has changes. +std::string commit() { + auto git = [](const std::string& args) { + const std::string cmd = std::string("git -C \"") + X2W_TOOL_SOURCE_DIR + "\" " + args + " 2>NUL"; + std::string out; + if (FILE* p = _popen(cmd.c_str(), "r")) { + char buf[256]; + while (std::fgets(buf, sizeof buf, p)) out += buf; + _pclose(p); + } + while (!out.empty() && (out.back() == '\n' || out.back() == '\r' || out.back() == ' ')) out.pop_back(); + return out; + }; + const std::string head = git("rev-parse HEAD"); + const bool dirty = !git("status --porcelain --untracked-files=no").empty(); + return dirty ? head + "+changes" : head; +} + +} // namespace + +std::string manifest(std::size_t records) { + // What every translation here depends on: a reader refuses an export made for another host + // layout. + std::string m = "format gpu-x2w-1\nkey blake3-16 of the D3D12_SHADER_BYTECODE bytes\n"; + m += "producer x2w-shaders\n"; + // Hash x2w::vs::translation_fingerprint(), which includes the host settings. + m += "build " + build_hex() + "\n"; + m += "commit " + commit() + "\n"; + for (const auto& [name, value] : settings()) m += name + " " + value + "\n"; + m += "cache none: every container is translated by X2W's translator, so nothing is cached or missing and there " + "are no orphan entries\n"; + m += "records " + u(records) + "\n"; + return m; +} + +int shaders_main(const std::vector<std::string>& args) { + DumpOptions o; + bool have_out = false; + for (std::size_t i = 0; i < args.size(); ++i) { + const std::string& a = args[i]; + if (a == "--out" && i + 1 < args.size()) { + o.out = std::filesystem::path(std::u8string(args[i + 1].begin(), args[i + 1].end())); ++i; + have_out = true; + } else if (a == "--jobs" && i + 1 < args.size()) { + const std::string& v = args[++i]; + char* end = nullptr; + const unsigned long long n = std::strtoull(v.c_str(), &end, 10); + if (v.empty() || *end) { + std::cerr << "x2w shaders: --jobs takes a number\n"; + return 2; + } + o.jobs = static_cast<std::size_t>(n); + } else if (a.rfind("--", 0) == 0) { + std::cerr << "x2w shaders: unknown option " << a << "\n"; + return 2; + } else { + o.paths.push_back(std::filesystem::path(std::u8string(a.begin(), a.end()))); + } + } + if (!have_out || o.paths.empty()) { + std::cerr << "usage: x2w shaders <paths...> --out <dir> [--jobs N]\n"; + return 2; + } + std::cerr << probe_host() << "\n"; + o.build = build_hex(); + o.manifest = [](std::size_t records) { return manifest(records); }; + try { + const DumpCounts c = dump(o, make); + std::cout << c.summary; + } catch (const std::exception& e) { + std::cerr << "x2w shaders: " << e.what() << "\n"; + return 1; + } + return 0; +} + +} // namespace x2w::tool diff --git a/tools/x2w/shaders_dump.h b/tools/x2w/shaders_dump.h new file mode 100644 index 0000000000..a9ef420bd9 --- /dev/null +++ b/tools/x2w/shaders_dump.h @@ -0,0 +1,81 @@ +// x2w shaders <paths...> --out <dir> [--jobs N] translates each distinct container found under the paths +// (scan.h) with x2w::vs::translate. It writes <key>.dxil, <key>.json, index.tsv, programs.tsv, sources.tsv, +// failed.tsv, collisions.tsv, summary.txt and manifest.txt. Each result has cache status "translated". +// There is no orphan directory or index. +// +// Needs the translator (x2w_vs_emit) and the front end's native.h: built only with them. +#pragma once + +#include <cstddef> +#include <cstdint> +#include <string> +#include <utility> +#include <vector> + +#include "scan.h" +#include "x2w_shader/emit/emit.h" +#include "x2w_shader/native.h" + +namespace x2w::tool { + +// One console program of a container: what a runtime that receives its machine code alone can hash. +struct Program { + std::uint64_t fnv = 0; + std::size_t bytes = 0; + vs::native::HwStage stage{}; + bool wave64 = false; + // "code" as stored; "patched" with the full-format export patch. + const char* form = "code"; + vs::native::NativeProgram native; +}; + +std::vector<Program> programs_of(Bytes container); + +// Additional pipeline creation data from the console programs. +struct Extras { + // A compute program's thread group, when every size is known. + std::optional<std::array<std::uint32_t, 3>> threads; + // The descriptors the translated program reads, by root parameter. + std::vector<vs::native::UsedResource> used; + // Whether any program can store to buffer memory. + bool stores = false; + // Whether any program can store through raw addresses. + bool stores_by_address = false; + // A program of the ray-tracing structure builder (spilled user data). + bool builder = false; +}; + +Extras extras(Bytes container); + +// Whether a console program can store to buffer memory (a buffer, typed-buffer, scalar-memory, flat or +// global store or atomic, or code not all known), and whether it can store through raw addresses (flat or +// global, or code that does not decode). +bool stores(const vs::native::NativeProgram& program); +bool stores_by_address(const vs::native::NativeProgram& program); + +const char* debug(vs::native::HwStage s); +std::string debug(const vs::native::RootType& r); +std::string debug(const vs::native::ResourceType& r); + +// Serialize the HostShader fields, pipeline extras, and console program metadata. +std::string json(const vs::HostShader& s, const std::vector<Program>& programs, const Extras* extras, + const std::string& key, std::uint64_t fnv, const Blake3Hash& full, std::size_t size, + const char* cache); + +// One container through the translator: the files and rows dump() writes for it. +Made make(const Found& found); + +// Probe the D3D12 device before translation to detect WaveLaneCountMax, AMD RDNA, the null heap slot and +// raw view twins. Without a device, leave these settings unchanged. Return a log line. +std::string probe_host(); + +// Return translator settings as name/value pairs. +std::vector<std::pair<std::string, std::string>> settings(); + +// manifest.txt for `records` translations. +std::string manifest(std::size_t records); + +// `x2w shaders ...` (argv after the subcommand). Returns the exit code. +int shaders_main(const std::vector<std::string>& args); + +} // namespace x2w::tool