upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 09:48:16 -0500
committerItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 09:48:16 -0500
commit3b7cd5e4bf771061885d6b8bcd8a3610e68aaae7 (patch)
tree8518b7c431cd824a07a43b2f87fe03b3e72085ae /runtime
parentcd6d8ac35a2a73db77885df2d3aa20afc407a171 (diff)
parent2d2eec9a75e3f98cf26b6a55df58d0bd90366ba3 (diff)
Merge pull request #1791 from AlxcBTW
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt31
-rw-r--r--runtime/shims/d3d12_com.cpp8
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp47
-rw-r--r--runtime/src/command_list.h5
-rw-r--r--runtime/src/vulkan_backend.h57
-rw-r--r--runtime/src/vulkan_replay.h19
-rw-r--r--runtime/test/d3d12_m4_compute_test.cpp395
-rw-r--r--runtime/test/shaders/build.py29
-rw-r--r--runtime/test/shaders/cs_m4_fill.asm51
-rw-r--r--runtime/test/shaders/cs_m4_indirect.asm28
-rw-r--r--runtime/test/vk_test_device.h18
11 files changed, 677 insertions, 11 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index c9bd10a3a..24d58b604 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -1222,8 +1222,37 @@ if(TARGET Vulkan::Headers)
1222 target_compile_options(d3d12_m3_frame_test PRIVATE /W4 /permissive- /utf-8) 1222 target_compile_options(d3d12_m3_frame_test PRIVATE /W4 /permissive- /utf-8)
1223 add_test(NAME d3d12_m3_frame COMMAND d3d12_m3_frame_test) 1223 add_test(NAME d3d12_m3_frame COMMAND d3d12_m3_frame_test)
1224 set_tests_properties(d3d12_m3_frame PROPERTIES SKIP_RETURN_CODE 77) 1224 set_tests_properties(d3d12_m3_frame PROPERTIES SKIP_RETURN_CODE 77)
1225
1226 # M4 (synthetic part): compute PSOs, a UAV table (structured and raw buffers, an R32_UINT storage image), an indirect
1227 # dispatch from arguments a first dispatch wrote, and a copy queue that streams the input in and reads the results
1228 # back across queue fences. cs_m4_fill.asm and cs_m4_indirect.asm go through the same build; build.py publishes
1229 # their synthetic FSSM programs (the compute header and the words their "fssm-data" comments give), which the
1230 # test wraps in shader containers.
1231 set(LEONIDA_M4_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m4_shaders)
1232 set(LEONIDA_M4_FILES ${LEONIDA_M4_DIR}/spirv/index.json ${LEONIDA_M4_DIR}/fssm/cs_m4_fill.fssm
1233 ${LEONIDA_M4_DIR}/fssm/cs_m4_indirect.fssm)
1234 add_custom_command(
1235 OUTPUT ${LEONIDA_M4_FILES}
1236 COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M4_DIR}
1237 COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}"
1238 $<TARGET_FILE:Python3::Interpreter> -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1239 ${LEONIDA_M4_DIR} cs_m4_fill cs_m4_indirect
1240 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1241 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/compute_fixture.py
1242 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_fill.asm
1243 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_indirect.asm
1244 ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py
1245 COMMENT "Translating cs_m4_fill and cs_m4_indirect for the compute test"
1246 VERBATIM)
1247 add_executable(d3d12_m4_compute_test test/d3d12_m4_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M4_FILES})
1248 target_link_libraries(d3d12_m4_compute_test PRIVATE gta6rt_d3d12_com)
1249 target_compile_definitions(d3d12_m4_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
1250 LEONIDA_TEST_M4_DIR="${LEONIDA_M4_DIR}")
1251 target_compile_options(d3d12_m4_compute_test PRIVATE /W4 /permissive- /utf-8)
1252 add_test(NAME d3d12_m4_compute COMMAND d3d12_m4_compute_test)
1253 set_tests_properties(d3d12_m4_compute PROPERTIES SKIP_RETURN_CODE 77)
1225 else() 1254 else()
1226 message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test and d3d12_m3_frame_test are not built") 1255 message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test, d3d12_m3_frame_test and d3d12_m4_compute_test are not built")
1227 endif() 1256 endif()
1228 # ID3D12Resource::GetHeapProperties and ID3D12DescriptorHeap::GetDesc (node masks, resolved heap flags) against the 1257 # ID3D12Resource::GetHeapProperties and ID3D12DescriptorHeap::GetDesc (node masks, resolved heap flags) against the
1229 # host runtime and WARP; run explicitly on a Vulkan GPU. 1258 # host runtime and WARP; run explicitly on a Vulkan GPU.
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp
index 581bc0fa9..a87197130 100644
--- a/runtime/shims/d3d12_com.cpp
+++ b/runtime/shims/d3d12_com.cpp
@@ -601,6 +601,11 @@ public:
601 cmd.argument_offset = argument_buffer_offset; 601 cmd.argument_offset = argument_buffer_offset;
602 cmd.count_buffer = count_buffer ? resource_id(count_buffer) : 0; 602 cmd.count_buffer = count_buffer ? resource_id(count_buffer) : 0;
603 cmd.count_offset = count_buffer ? count_buffer_offset : 0; 603 cmd.count_offset = count_buffer ? count_buffer_offset : 0;
604 if (kind == leonida::IndirectKind::dispatch && max_command_count) { // the pipeline and root arguments a Dispatch would record
605 if (!compute_pipeline_ || !compute_.layout) return check(false);
606 cmd.pipeline = compute_pipeline_;
607 cmd.user_data = compute_.data;
608 }
604 check(list_.execute_indirect(cmd)); 609 check(list_.execute_indirect(cmd));
605 } 610 }
606 611
@@ -1261,7 +1266,8 @@ HRESULT create_command_list(D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator
1261 if (!command_allocator || command_allocator->type() != type) return E_INVALIDARG; 1266 if (!command_allocator || command_allocator->type() != type) return E_INVALIDARG;
1262 // A list is created open, so the allocator must be free: E_INVALIDARG as on the PC runtime (D3D-51). 1267 // A list is created open, so the allocator must be free: E_INVALIDARG as on the PC runtime (D3D-51).
1263 if (command_allocator->recording()) return E_INVALIDARG; 1268 if (command_allocator->recording()) return E_INVALIDARG;
1264 if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_BUNDLE) 1269 if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_BUNDLE &&
1270 type != D3D12_COMMAND_LIST_TYPE_COMPUTE && type != D3D12_COMMAND_LIST_TYPE_COPY)
1265 stub("create_command_list(non-direct type)"); 1271 stub("create_command_list(non-direct type)");
1266 auto* object = new GraphicsCommandList(type); // created open, as D3D12 does 1272 auto* object = new GraphicsCommandList(type); // created open, as D3D12 does
1267 object->record_into(command_allocator); 1273 object->record_into(command_allocator);
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index bb2ec934d..a59696c17 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -4080,6 +4080,49 @@ public:
4080 write_image_descriptor(*r, view, destination, false); 4080 write_image_descriptor(*r, view, destination, false);
4081 } 4081 }
4082 4082
4083 // An unordered-access view of a buffer is a V# in the slot (docs section 3.4): the shader loads those four dwords
4084 // through its descriptor table and reaches the bytes by the console VA in them. A structured view (format
4085 // UNKNOWN and a stride) is `stride` and a record count, a raw one (R32_TYPELESS with the RAW flag) is a byte count;
4086 // typed buffer views are not written. A slot left as zeros is a null descriptor.
4087 void write_buffer_uav(ID3D12Resource* resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc,
4088 D3D12_CPU_DESCRIPTOR_HANDLE destination) {
4089 const D3D12_RESOURCE_DESC& rd = Resource::from<Resource>(resource)->desc();
4090 if (!(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) {
4091 log_once("unordered-access view of a buffer created without ALLOW_UNORDERED_ACCESS; flags", int(rd.Flags));
4092 return;
4093 }
4094 if (!desc || desc->ViewDimension != D3D12_UAV_DIMENSION_BUFFER) {
4095 log_once("unordered-access view of a buffer needs a buffer view description; dimension",
4096 desc ? int(desc->ViewDimension) : -1);
4097 return;
4098 }
4099 const D3D12_BUFFER_UAV& view = desc->Buffer;
4100 const bool structured = desc->Format == DXGI_FORMAT_UNKNOWN;
4101 const bool raw = desc->Format == DXGI_FORMAT_R32_TYPELESS && (view.Flags & D3D12_BUFFER_UAV_FLAG_RAW);
4102 if (!structured && !raw) {
4103 log_once("typed buffer unordered-access views not supported; format", int(desc->Format));
4104 return;
4105 }
4106 const UINT64 unit = structured ? view.StructureByteStride : 4;
4107 if (!unit || unit > 0x3fff || view.CounterOffsetInBytes ||
4108 view.FirstElement > rd.Width / unit || (UINT64(view.FirstElement) + view.NumElements) > rd.Width / unit ||
4109 UINT64(view.NumElements) * (structured ? 1 : 4) > ~0u) {
4110 log_once("unordered-access view of a buffer outside the resource or with a bad stride; elements",
4111 int(view.NumElements));
4112 return;
4113 }
4114 const UINT64 va = resource->GetGPUVirtualAddress();
4115 if (!va) return;
4116 leonida::gfx10::Buffer buffer{};
4117 buffer.address = va + view.FirstElement * unit;
4118 buffer.stride = structured ? std::uint32_t(unit) : 0;
4119 buffer.num_records = std::uint32_t(structured ? view.NumElements : UINT64(view.NumElements) * 4);
4120 buffer.oob_select = structured ? leonida::gfx10::OobSelect::structured_with_offset
4121 : leonida::gfx10::OobSelect::raw;
4122 const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer);
4123 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words));
4124 }
4125
4083 // An unordered-access view of a texture is a T# too, of one mip; set 0 also holds it as a storage image. 4126 // An unordered-access view of a texture is a T# too, of one mip; set 0 also holds it as a storage image.
4084 void STDMETHODCALLTYPE CreateUnorderedAccessView(ID3D12Resource* resource, ID3D12Resource* counter, 4127 void STDMETHODCALLTYPE CreateUnorderedAccessView(ID3D12Resource* resource, ID3D12Resource* counter,
4085 const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, 4128 const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc,
@@ -4092,7 +4135,8 @@ public:
4092 if (resource) stub("ID3D12Device::CreateUnorderedAccessView(resource from another device)"); 4135 if (resource) stub("ID3D12Device::CreateUnorderedAccessView(resource from another device)");
4093 return; 4136 return;
4094 } 4137 }
4095 if (!r->image() || counter) return stub("ID3D12Device::CreateUnorderedAccessView(buffer)"); 4138 if (counter) return stub("ID3D12Device::CreateUnorderedAccessView(counter)");
4139 if (!r->image()) return write_buffer_uav(resource, desc, destination);
4096 if (!(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { 4140 if (!(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) {
4097 log_once("unordered-access view of a texture created without ALLOW_UNORDERED_ACCESS; flags", 4141 log_once("unordered-access view of a texture created without ALLOW_UNORDERED_ACCESS; flags",
4098 int(r->desc().Flags)); 4142 int(r->desc().Flags));
@@ -4128,6 +4172,7 @@ public:
4128 return; 4172 return;
4129 } 4173 }
4130 write_image_descriptor(*r, view, destination, true); 4174 write_image_descriptor(*r, view, destination, true);
4175 state_.context->note_storage_image(r->id());
4131 } 4176 }
4132 4177
4133 // A sampler is an S# in the first 16 bytes of the slot; the shader finds the sampler by those four dwords. 4178 // A sampler is an S# in the first 16 bytes of the slot; the shader finds the sampler by those four dwords.
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index 9c74994e1..282863f7c 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -565,6 +565,11 @@ struct ExecuteIndirect {
565 std::uint64_t argument_offset = 0; 565 std::uint64_t argument_offset = 0;
566 ResourceId count_buffer = 0; // 0: fixed max_count; non-zero: vkCmdDraw*IndirectCount 566 ResourceId count_buffer = 0; // 0: fixed max_count; non-zero: vkCmdDraw*IndirectCount
567 std::uint64_t count_offset = 0; 567 std::uint64_t count_offset = 0;
568 // kind == dispatch: the compute pipeline and root arguments in effect, as Dispatch records them, so the dispatches
569 // run that pipeline with those arguments whatever the command buffer had bound. A pipeline of 0 leaves the binding
570 // as it is.
571 std::uintptr_t pipeline = 0;
572 std::array<std::uint32_t, 32> user_data{};
568}; 573};
569 574
570// Triangle geometry descriptor for a BLAS build (ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure). 575// Triangle geometry descriptor for a BLAS build (ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure).
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 814f53549..8f9759c89 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -29,6 +29,7 @@
29#include <map> 29#include <map>
30#include <memory> 30#include <memory>
31#include <mutex> 31#include <mutex>
32#include <unordered_set>
32#include <shared_mutex> 33#include <shared_mutex>
33#include <span> 34#include <span>
34#include <thread> 35#include <thread>
@@ -819,6 +820,15 @@ public:
819 } 820 }
820 } 821 }
821 822
823 // An image that got a storage (unordered-access) view. A shader can write it before any command names it, so the
824 // layer would not know it was used and the first barrier or copy that does would zero-fill it (vulkan_replay.h,
825 // initialize). The next submission therefore moves each such image to GENERAL, the layout its descriptor names,
826 // zero-filled, ahead of its lists. An image already tracked beyond UNDEFINED is left as it is.
827 void note_storage_image(ResourceId id) {
828 std::lock_guard lock(storage_mutex_);
829 storage_pending_.insert(id);
830 }
831
822 void remove_resource(ResourceId id) { 832 void remove_resource(ResourceId id) {
823 VkImage img = VK_NULL_HANDLE; 833 VkImage img = VK_NULL_HANDLE;
824 { 834 {
@@ -1124,6 +1134,14 @@ private:
1124 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 1134 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
1125 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 1135 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
1126 LayoutTracker tracker_; 1136 LayoutTracker tracker_;
1137 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ only
1138 std::unordered_set<ResourceId> storage_pending_;
1139 // The last submission that initialized storage images (its queue's progress semaphore and ticket) and a counter
1140 // that says which one: every other queue's next submission waits for it, so no queue uses such an image before
1141 // the zero-fill that put it in GENERAL has run.
1142 VkSemaphore storage_init_semaphore_ = VK_NULL_HANDLE;
1143 std::uint64_t storage_init_value_ = 0;
1144 std::uint64_t storage_init_version_ = 0;
1127 std::map<std::tuple<VkImage, VkImageAspectFlags, std::uint32_t, std::uint32_t, std::uint32_t, VkFormat>, VkImageView> views_; 1145 std::map<std::tuple<VkImage, VkImageAspectFlags, std::uint32_t, std::uint32_t, std::uint32_t, VkFormat>, VkImageView> views_;
1128 std::function<bool(VkCommandBuffer)> bindless_prepare_; 1146 std::function<bool(VkCommandBuffer)> bindless_prepare_;
1129 std::unique_ptr<Depth24Converter> depth24_; 1147 std::unique_ptr<Depth24Converter> depth24_;
@@ -1439,6 +1457,33 @@ public:
1439 return ReplayResult::unsupported; 1457 return ReplayResult::unsupported;
1440 } 1458 }
1441 auto next_tracker = context_.tracker_; 1459 auto next_tracker = context_.tracker_;
1460 // Images with a UAV view are moved to GENERAL (zeroed) by the first submission that can use a shader on them:
1461 // not a copy queue (its family may not clear images), and one whose lists dispatch or draw.
1462 bool runs_shaders = false;
1463 for (const CommandList* list : lists)
1464 for (const auto& command : list->commands())
1465 runs_shaders |= std::holds_alternative<Dispatch>(command) || std::holds_alternative<Draw>(command) ||
1466 std::holds_alternative<ExecuteIndirect>(command);
1467 std::vector<ResourceId> storage_images;
1468 {
1469 std::lock_guard lock(context_.storage_mutex_);
1470 if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ &&
1471 context_.storage_init_version_ != storage_init_seen_) {
1472 waits_.push_back(context_.storage_init_semaphore_);
1473 wait_values_.push_back(context_.storage_init_value_);
1474 storage_init_seen_ = context_.storage_init_version_;
1475 }
1476 if (kind_ != QueueKind::copy && runs_shaders)
1477 storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end());
1478 if (!storage_images.empty()) context_.storage_pending_.clear();
1479 }
1480 for (const ResourceId id : storage_images) {
1481 const ResourceBinding* image = context_.resolve(id);
1482 if (!image || !image->image) continue;
1483 const VkImageSubresourceRange range{image->aspects, 0, image->mip_levels, 0, image->array_layers};
1484 auto pieces = detail::current(&next_tracker, id, range, VK_IMAGE_LAYOUT_UNDEFINED);
1485 detail::initialize(replay, command_buffer, *image, id, pieces, VK_IMAGE_LAYOUT_GENERAL, &next_tracker);
1486 }
1442 bool wrote_readback = false; 1487 bool wrote_readback = false;
1443 VkPipelineStageFlags2 readback_stages = 0; 1488 VkPipelineStageFlags2 readback_stages = 0;
1444 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists 1489 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists
@@ -1481,6 +1526,17 @@ public:
1481 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; 1526 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS;
1482 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held 1527 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held
1483 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 1528 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
1529 if (!submitted && !storage_images.empty()) { // not initialized after all: try again with the next submission
1530 std::lock_guard lock(context_.storage_mutex_);
1531 context_.storage_pending_.insert(storage_images.begin(), storage_images.end());
1532 }
1533 if (submitted && !storage_images.empty()) {
1534 std::lock_guard lock(context_.storage_mutex_);
1535 context_.storage_init_semaphore_ = progress_;
1536 context_.storage_init_value_ = submitted_;
1537 ++context_.storage_init_version_;
1538 storage_init_seen_ = context_.storage_init_version_;
1539 }
1484 if (submitted) { 1540 if (submitted) {
1485 context_.tracker_ = std::move(next_tracker); 1541 context_.tracker_ = std::move(next_tracker);
1486 slot->predicate = std::move(batch); 1542 slot->predicate = std::move(batch);
@@ -1632,6 +1688,7 @@ private:
1632 std::uint64_t submitted_ = 0; 1688 std::uint64_t submitted_ = 0;
1633 std::vector<CommandSlot> buffers_; 1689 std::vector<CommandSlot> buffers_;
1634 std::unique_ptr<OcclusionResolve> occlusion_resolve_; 1690 std::unique_ptr<OcclusionResolve> occlusion_resolve_;
1691 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for
1635 std::vector<VkSemaphore> waits_; 1692 std::vector<VkSemaphore> waits_;
1636 std::vector<std::uint64_t> wait_values_; 1693 std::vector<std::uint64_t> wait_values_;
1637 std::uint32_t open_labels_ = 0; // queue labels begun and not ended 1694 std::uint32_t open_labels_ = 0; // queue labels begun and not ended
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 0b46198a9..711bd810c 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -2392,6 +2392,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2392 (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect)) 2392 (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect))
2393 return ReplayResult::unsupported; 2393 return ReplayResult::unsupported;
2394 } 2394 }
2395 if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded
2396 if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported;
2397 const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline);
2398 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource;
2399 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported;
2400 p.pipeline = *pipeline;
2401 }
2395 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { 2402 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) {
2396 if (vk.xdxr_check) { 2403 if (vk.xdxr_check) {
2397 if (!vk.xdxr_check(*build)) return ReplayResult::unsupported; 2404 if (!vk.xdxr_check(*build)) return ReplayResult::unsupported;
@@ -3113,6 +3120,18 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3113 } else if (ind->kind == IndirectKind::draw_indexed) { 3120 } else if (ind->kind == IndirectKind::draw_indexed) {
3114 vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride); 3121 vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride);
3115 } else if (ind->kind == IndirectKind::dispatch) { 3122 } else if (ind->kind == IndirectKind::dispatch) {
3123 if (ind->pipeline) {
3124 ShaderUserData data{};
3125 std::copy(ind->user_data.begin(), ind->user_data.end(), data.s);
3126 data.heap_base = vk.heap_base;
3127 data.code_base = p.pipeline.code_base;
3128 vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline);
3129 if (p.pipeline.bindless_set)
3130 vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.layout, 0,
3131 1, &p.pipeline.bindless_set, 0, nullptr);
3132 vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data),
3133 &data);
3134 }
3116 for (std::uint32_t k = 0; k < ind->max_count; ++k) { 3135 for (std::uint32_t k = 0; k < ind->max_count; ++k) {
3117 vk.dispatch_indirect(command_buffer, p.binding.buffer, 3136 vk.dispatch_indirect(command_buffer, p.binding.buffer,
3118 arguments + VkDeviceSize(k) * ind->stride); 3137 arguments + VkDeviceSize(k) * ind->stride);
diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp
new file mode 100644
index 000000000..bd3a555fd
--- /dev/null
+++ b/runtime/test/d3d12_m4_compute_test.cpp
@@ -0,0 +1,395 @@
1// Milestone M4, the synthetic part (docs/d3d12_vulkan.md section 6): a compute workload with the structure a game's asset
2// streaming and compute passes have, through the D3D12 API on the proxy, with compute shaders that are translator output
3// (test/shaders/cs_m4_fill.asm and cs_m4_indirect.asm, hand-written RDNA2).
4// Three queues' worth of work, each its own command list type:
5// COPY queue streams an input buffer: CopyBufferRegion from an UPLOAD buffer into a DEFAULT buffer that was created
6// in COMMON (promoted to COPY_DEST there), then Signal(copy fence, 1).
7// COMPUTE queue Wait(copy fence, 1), then one list: a barrier COMMON -> UNORDERED_ACCESS for the input, a compute root
8// signature (four root constants and a descriptor table of five UAVs: a structured buffer, a raw
9// buffer, an R32_UINT RWTexture2D, the raw input and a raw output), a compute PSO, and Dispatch with
10// four groups. That shader fills the structured buffer and the image from the input and writes the
11// arguments of the next dispatch into the raw buffer. Barriers (a transition of the argument buffer to
12// INDIRECT_ARGUMENT and UAV barriers on the buffer and the image) and ExecuteIndirect with a dispatch
13// command signature runs a second PSO whose group count is that buffer's first word: it reads the
14// structured buffer and the image back and writes the raw output. Everything then goes to COMMON and
15// the queue does Signal(compute fence, 1).
16// COPY queue Wait(compute fence, 1), a COPY list that copies the five results (four buffers and the image through
17// CopyTextureRegion) to a READBACK buffer, Signal(copy fence, 2). The CPU waits for that with
18// SetEventOnCompletion and an event.
19// When the Vulkan family has two queues, the copy and the compute D3D12 queue get their own VkQueue (so the fences are
20// real cross-queue semaphores); with one, they share it. Either way the three batches are submitted in dependency order.
21// Compared with a CPU reference, word by word, error 0: the input after the round trip, the structured buffer, the
22// argument buffer, the image and the indirect dispatch's output (which also shows that exactly the 3 groups the
23// first dispatch asked for ran).
24// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
25#include "vk_test_device.h"
26#include "d3d12_test_shaders.h"
27#include "../shims/d3d12_com.h"
28#include "../shims/d3d12_xs_device.h"
29#include "../src/shader_library.h"
30
31#include <array>
32#include <cstring>
33
34#ifndef LEONIDA_TEST_M4_DIR
35#error "LEONIDA_TEST_M4_DIR must name the folder build.py wrote (spirv/index.json, fssm/cs_*.fssm)"
36#endif
37
38#define EXPECT(condition) do { \
39 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
40} while (0)
41
42using namespace d3d12test;
43using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX
44
45namespace {
46
47std::vector<std::uint8_t> read_file(const std::filesystem::path& path) {
48 std::ifstream in(path, std::ios::binary);
49 return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
50}
51
52constexpr UINT records = 256; // fill: 4 groups of 64
53constexpr UINT second_groups = 3; // the indirect dispatch: 3 groups of 64
54constexpr UINT image_dim = 16; // 16 x 16 R32_UINT, one texel a record
55constexpr UINT seed = 0x00c0ffee, multiplier = 0x01000193;
56// The readback buffer: the structured buffer, the argument buffer's 16 bytes, the second output, the input, the image.
57constexpr UINT64 data_bytes = records * 16, args_bytes = 16, out2_bytes = second_groups * 64 * 8, in_bytes = records * 4;
58constexpr UINT64 offset_data = 0, offset_args = offset_data + data_bytes, offset_out2 = offset_args + args_bytes,
59 offset_in = offset_out2 + out2_bytes;
60constexpr UINT64 offset_image = (offset_in + in_bytes + 511) / 512 * 512;
61constexpr UINT image_pitch = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT;
62constexpr UINT64 readback_bytes = offset_image + UINT64(image_dim) * image_pitch;
63
64std::uint32_t rotr(std::uint32_t v, unsigned n) { return (v >> n) | (v << (32 - n)); }
65std::uint32_t input_word(UINT g) { return (g + 1) * 0x9e3779b1u ^ (g << 7); }
66
67struct Reference {
68 std::vector<std::uint32_t> data, args, in, image, out2;
69};
70Reference reference() {
71 Reference ref;
72 ref.args = {second_groups, 1, 1, 0xc0de0001u};
73 ref.data.resize(records * 4);
74 ref.image.resize(image_dim * image_dim);
75 for (UINT g = 0; g < records; ++g) {
76 const std::uint32_t in = input_word(g);
77 ref.in.push_back(in);
78 ref.data[g * 4 + 0] = in + seed;
79 ref.data[g * 4 + 1] = g * multiplier;
80 ref.data[g * 4 + 2] = in ^ (g << 8);
81 ref.data[g * 4 + 3] = rotr(in, 13);
82 const UINT x = g & 15, y = g >> 4;
83 ref.image[y * image_dim + x] = in * 3 + x * 0x10001u + y;
84 }
85 for (UINT g = 0; g < second_groups * 64; ++g) {
86 const std::uint32_t t = ref.image[g]; // (g & 15, g >> 4) is texel g of the row-major image
87 ref.out2.push_back((ref.data[g * 4 + 0] + t) ^ ref.data[g * 4 + 3]);
88 ref.out2.push_back((ref.data[g * 4 + 2] ^ t) + ref.data[g * 4 + 1]);
89 }
90 return ref;
91}
92
93} // namespace
94
95int main() {
96 vktest::Device d;
97 d.queue_count_wanted = 2; // the copy queue and the compute queue each get a VkQueue where the family has two
98 const auto device_status = d.initialize();
99 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
100 if (device_status != vktest::DeviceStatus::ready) return 1;
101 if (!d.bindless) {
102 std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n");
103 return 77;
104 }
105
106 const std::filesystem::path root_dir = LEONIDA_TEST_M4_DIR;
107 leonida::ShaderLibrary library;
108 EXPECT(library.load((root_dir / "spirv").string()));
109 const auto program = [&](const char* name) { return read_file(root_dir / "fssm" / (std::string(name) + ".fssm")); };
110 const auto fill = program("cs_m4_fill"), indirect = program("cs_m4_indirect");
111 EXPECT(fill.size() >= 0x150 && indirect.size() >= 0x150 && fill != indirect);
112 EXPECT(library.find("cs", leonida::sha256_hex(fill)) && library.find("cs", leonida::sha256_hex(indirect)));
113 const auto fill_container = shader_container(fill), indirect_container = shader_container(indirect);
114
115 const bool distinct_queues = d.queues.size() >= 2;
116 Reference want = reference();
117 std::vector<std::uint8_t> got;
118 {
119 rt::d3d12::VulkanDeviceInfo info{};
120 info.get_instance_proc = d.instance_proc;
121 info.instance = d.instance;
122 info.physical = d.physical;
123 info.device = d.device;
124 info.queue = d.queue;
125 info.queue_family = d.family;
126 if (distinct_queues) info.command_queues = d.queues;
127 info.buffer_device_address = true;
128 info.bindless = d.bindless;
129 info.bindless_partially_bound = d.partially_bound;
130 info.image_view_min_lod = d.image_view_min_lod;
131 info.shader_dir = (root_dir / "spirv").string();
132 ID3D12Device* inner = nullptr;
133 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
134 Ref<ID3D12Device> device;
135 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
136 reinterpret_cast<void**>(&device.p))));
137 rt::d3d12::set_device_outer(inner, device.p);
138 EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE);
139
140 // [0] four 32-bit constants (s0..s3), [1] a table of five UAVs (s[4:5]).
141 D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 5, 0, 0, 0};
142 D3D12_ROOT_PARAMETER params[2] = {};
143 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
144 params[0].Constants = {0, 0, 4};
145 params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
146 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
147 params[1].DescriptorTable = {1, &uav_range};
148 params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
149 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
150 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
151 root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
152 const auto root_blob = serialize_root_signature(root_desc);
153 EXPECT(!root_blob.empty());
154 Ref<ID3D12RootSignature> root;
155 EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
156
157 D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{};
158 pso_desc.pRootSignature = root.p;
159 pso_desc.CS = {fill_container.data(), fill_container.size()};
160 Ref<ID3D12PipelineState> pso_fill, pso_indirect;
161 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_fill.p))));
162 pso_desc.CS = {indirect_container.data(), indirect_container.size()};
163 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_indirect.p))));
164
165 D3D12_INDIRECT_ARGUMENT_DESC argument{};
166 argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
167 D3D12_COMMAND_SIGNATURE_DESC signature_desc{};
168 signature_desc.ByteStride = sizeof(D3D12_DISPATCH_ARGUMENTS);
169 signature_desc.NumArgumentDescs = 1;
170 signature_desc.pArgumentDescs = &argument;
171 Ref<ID3D12CommandSignature> signature;
172 EXPECT(SUCCEEDED(device->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature.p))));
173
174 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
175 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
176 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
177 constexpr auto uav_flag = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
178 constexpr auto uav_state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
179 constexpr auto common = D3D12_RESOURCE_STATE_COMMON;
180 Ref<ID3D12Resource> upload, input, data, args, out2, image, readback;
181 const auto create_buffer = [&](Ref<ID3D12Resource>& out, const D3D12_HEAP_PROPERTIES& heap, UINT64 bytes,
182 D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) {
183 const auto desc = buffer_desc(bytes, flags);
184 return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
185 IID_PPV_ARGS(&out.p)));
186 };
187 EXPECT(create_buffer(upload, upload_heap, in_bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ));
188 EXPECT(create_buffer(input, default_heap, in_bytes, uav_flag, common));
189 EXPECT(create_buffer(data, default_heap, data_bytes, uav_flag, uav_state));
190 EXPECT(create_buffer(args, default_heap, 256, uav_flag, uav_state));
191 EXPECT(create_buffer(out2, default_heap, out2_bytes, uav_flag, uav_state));
192 EXPECT(create_buffer(readback, readback_heap, readback_bytes, D3D12_RESOURCE_FLAG_NONE,
193 D3D12_RESOURCE_STATE_COPY_DEST));
194 D3D12_RESOURCE_DESC image_desc{};
195 image_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
196 image_desc.Width = image_desc.Height = image_dim;
197 image_desc.DepthOrArraySize = 1;
198 image_desc.MipLevels = 1;
199 image_desc.Format = DXGI_FORMAT_R32_UINT;
200 image_desc.SampleDesc.Count = 1;
201 image_desc.Flags = uav_flag;
202 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &image_desc, uav_state,
203 nullptr, IID_PPV_ARGS(&image.p))));
204 {
205 std::uint32_t* mapped = nullptr;
206 EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped))));
207 for (UINT g = 0; g < records; ++g) mapped[g] = input_word(g);
208 upload->Unmap(0, nullptr);
209 }
210
211 // The table: slot 0 structured buffer (stride 16), 1 raw argument buffer, 2 image, 3 raw input, 4 raw output.
212 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5,
213 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
214 Ref<ID3D12DescriptorHeap> heap;
215 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p))));
216 const std::uint64_t cpu = reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 9))(heap.p);
217 const std::uint64_t gpu = reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 10))(heap.p);
218 const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
219 EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step == 32); // the shaders step 32 bytes a slot
220 const auto handle = [&](UINT i) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + std::uint64_t(i) * step)}; };
221 const auto buffer_view = [](DXGI_FORMAT format, UINT count, UINT stride, D3D12_BUFFER_UAV_FLAGS flags) {
222 D3D12_UNORDERED_ACCESS_VIEW_DESC view{};
223 view.Format = format;
224 view.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
225 view.Buffer = {0, count, stride, 0, flags};
226 return view;
227 };
228 auto view = buffer_view(DXGI_FORMAT_UNKNOWN, records, 16, D3D12_BUFFER_UAV_FLAG_NONE);
229 device->CreateUnorderedAccessView(data.p, nullptr, &view, handle(0));
230 view = buffer_view(DXGI_FORMAT_R32_TYPELESS, 4, 0, D3D12_BUFFER_UAV_FLAG_RAW); // the 16 bytes of arguments
231 device->CreateUnorderedAccessView(args.p, nullptr, &view, handle(1));
232 D3D12_UNORDERED_ACCESS_VIEW_DESC image_view{};
233 image_view.Format = DXGI_FORMAT_R32_UINT;
234 image_view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
235 device->CreateUnorderedAccessView(image.p, nullptr, &image_view, handle(2));
236 view = buffer_view(DXGI_FORMAT_R32_TYPELESS, records, 0, D3D12_BUFFER_UAV_FLAG_RAW);
237 device->CreateUnorderedAccessView(input.p, nullptr, &view, handle(3));
238 view = buffer_view(DXGI_FORMAT_R32_TYPELESS, UINT(out2_bytes / 4), 0, D3D12_BUFFER_UAV_FLAG_RAW);
239 device->CreateUnorderedAccessView(out2.p, nullptr, &view, handle(4));
240 // The V# of the structured view and the T# of the image view are what the shader loads from the table.
241 std::uint32_t v_data[4], v_args[4];
242 std::memcpy(v_data, reinterpret_cast<const void*>(handle(0).ptr), sizeof(v_data));
243 std::memcpy(v_args, reinterpret_cast<const void*>(handle(1).ptr), sizeof(v_args));
244 EXPECT(v_data[0] == std::uint32_t(data->GetGPUVirtualAddress()) && (v_data[1] >> 16 & 0x3fff) == 16 &&
245 v_data[2] == records);
246 EXPECT(v_args[0] == std::uint32_t(args->GetGPUVirtualAddress()) && (v_args[1] >> 16 & 0x3fff) == 0 &&
247 v_args[2] == 16);
248
249 D3D12_COMMAND_QUEUE_DESC queue_desc{};
250 Ref<ID3D12CommandQueue> copy_queue, compute_queue;
251 queue_desc.Type = D3D12_COMMAND_LIST_TYPE_COPY;
252 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&copy_queue.p))));
253 queue_desc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE;
254 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&compute_queue.p))));
255 Ref<ID3D12CommandAllocator> stream_alloc, compute_alloc, readback_alloc;
256 Ref<ID3D12GraphicsCommandList> stream_list, compute_list, readback_list;
257 Ref<ID3D12Fence> copy_fence, compute_fence;
258 const auto make_list = [&](D3D12_COMMAND_LIST_TYPE type, Ref<ID3D12CommandAllocator>& alloc,
259 Ref<ID3D12GraphicsCommandList>& list) {
260 return SUCCEEDED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&alloc.p))) &&
261 SUCCEEDED(device->CreateCommandList(0, type, alloc.p, nullptr, IID_PPV_ARGS(&list.p)));
262 };
263 EXPECT(make_list(D3D12_COMMAND_LIST_TYPE_COPY, stream_alloc, stream_list));
264 EXPECT(make_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, compute_alloc, compute_list));
265 EXPECT(make_list(D3D12_COMMAND_LIST_TYPE_COPY, readback_alloc, readback_list));
266 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&copy_fence.p))));
267 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&compute_fence.p))));
268
269 // Copy list 1: stream the input in (the buffer is in COMMON and is promoted to COPY_DEST by the copy). This is the
270 // first submission after the UAV views were written, and a copy queue: it must not initialize the storage image
271 // (the compute queue does, in the submission that dispatches), or the data written later would be at risk.
272 stream_list->CopyBufferRegion(input.p, 0, upload.p, 0, in_bytes);
273 EXPECT(stream_list->Close() == S_OK);
274
275 D3D12_TEXTURE_COPY_LOCATION dst{}, src{};
276 dst.pResource = readback.p;
277 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
278 dst.PlacedFootprint = {offset_image, {DXGI_FORMAT_R32_UINT, image_dim, image_dim, 1, image_pitch}};
279 src.pResource = image.p;
280 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
281
282 // Compute list.
283 ID3D12DescriptorHeap* heaps[] = {heap.p};
284 D3D12_RESOURCE_BARRIER acquire = transition(input.p, common, uav_state);
285 compute_list->ResourceBarrier(1, &acquire);
286 compute_list->SetDescriptorHeaps(1, heaps);
287 compute_list->SetComputeRootSignature(root.p);
288 compute_list->SetPipelineState(pso_fill.p);
289 const std::uint32_t constants[4] = {seed, multiplier, second_groups, 0};
290 compute_list->SetComputeRoot32BitConstants(0, 4, constants, 0);
291 compute_list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu});
292 compute_list->Dispatch(records / 64, 1, 1);
293 D3D12_RESOURCE_BARRIER between[3] = {transition(args.p, uav_state, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT),
294 {}, {}};
295 for (int i : {1, 2}) {
296 between[i].Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
297 between[i].UAV.pResource = i == 1 ? data.p : image.p;
298 }
299 compute_list->ResourceBarrier(3, between);
300 compute_list->SetPipelineState(pso_indirect.p); // the root arguments stay
301 compute_list->ExecuteIndirect(signature.p, 1, args.p, 0, nullptr, 0);
302 D3D12_RESOURCE_BARRIER release[5] = {transition(data.p, uav_state, common),
303 transition(args.p, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, common),
304 transition(out2.p, uav_state, common),
305 transition(input.p, uav_state, common),
306 transition(image.p, uav_state, common)};
307 compute_list->ResourceBarrier(5, release);
308 EXPECT(compute_list->Close() == S_OK);
309
310 // Copy list 2: the results to the readback buffer, once the compute queue is done.
311 readback_list->CopyBufferRegion(readback.p, offset_data, data.p, 0, data_bytes);
312 readback_list->CopyBufferRegion(readback.p, offset_args, args.p, 0, args_bytes);
313 readback_list->CopyBufferRegion(readback.p, offset_out2, out2.p, 0, out2_bytes);
314 readback_list->CopyBufferRegion(readback.p, offset_in, input.p, 0, in_bytes);
315 readback_list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
316 EXPECT(readback_list->Close() == S_OK);
317
318 const auto execute = [&](ID3D12CommandQueue* queue, ID3D12GraphicsCommandList* list) {
319 ID3D12CommandList* lists[] = {list};
320 queue->ExecuteCommandLists(1, lists);
321 return rt::d3d12::last_execute_result(queue) == leonida::ReplayResult::success;
322 };
323 const auto submit_copy = [&] {
324 return execute(copy_queue.p, stream_list.p) && SUCCEEDED(copy_queue->Signal(copy_fence.p, 1));
325 };
326 const auto submit_readback = [&] {
327 return SUCCEEDED(copy_queue->Wait(compute_fence.p, 1)) && execute(copy_queue.p, readback_list.p) &&
328 SUCCEEDED(copy_queue->Signal(copy_fence.p, 2));
329 };
330 const auto submit_compute = [&] {
331 return SUCCEEDED(compute_queue->Wait(copy_fence.p, 1)) && execute(compute_queue.p, compute_list.p) &&
332 SUCCEEDED(compute_queue->Signal(compute_fence.p, 1));
333 };
334 // In dependency order: the layer replays a list at ExecuteCommandLists and tracks every image's layout in that
335 // order, so a list that waits for another queue's signal has to be submitted after the list it waits for
336 // (the Wait-before-Signal order d3d12_queue_wait_test covers, without a resource handed over).
337 EXPECT(submit_copy() && submit_compute() && submit_readback());
338
339 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
340 EXPECT(event != nullptr);
341 EXPECT(SUCCEEDED(copy_fence->SetEventOnCompletion(2, event)));
342 if (WaitForSingleObject(event, 20000) != WAIT_OBJECT_0) {
343 std::fprintf(stderr, "the copy fence never reached 2 (compute fence at %llu)\n",
344 static_cast<unsigned long long>(compute_fence->GetCompletedValue()));
345 return 1;
346 }
347 CloseHandle(event);
348 EXPECT(copy_fence->GetCompletedValue() >= 2 && compute_fence->GetCompletedValue() >= 1);
349
350 void* mapped = nullptr;
351 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
352 got.assign(static_cast<const std::uint8_t*>(mapped), static_cast<const std::uint8_t*>(mapped) + readback_bytes);
353 readback->Unmap(0, nullptr);
354
355 for (auto* r : {&upload, &input, &data, &args, &out2, &image, &readback}) r->reset();
356 stream_list.reset(); compute_list.reset(); readback_list.reset();
357 stream_alloc.reset(); compute_alloc.reset(); readback_alloc.reset();
358 copy_fence.reset(); compute_fence.reset();
359 signature.reset(); pso_fill.reset(); pso_indirect.reset(); root.reset(); heap.reset();
360 copy_queue.reset(); compute_queue.reset();
361 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
362 }
363
364 unsigned mismatches = 0, words = 0;
365 const auto compare = [&](const char* what, UINT64 offset, const std::vector<std::uint32_t>& expected, UINT pitch,
366 UINT row_words) {
367 unsigned bad = 0;
368 for (std::size_t i = 0; i < expected.size(); ++i) {
369 std::uint32_t value = 0;
370 const UINT64 at = offset + (pitch ? (i / row_words) * pitch + (i % row_words) * 4 : i * 4);
371 std::memcpy(&value, got.data() + at, 4);
372 ++words;
373 if (value == expected[i]) continue;
374 ++mismatches;
375 if (bad++ < 4) std::fprintf(stderr, "%s word %zu: got %08x want %08x\n", what, i, value, expected[i]);
376 }
377 if (bad) std::fprintf(stderr, "%s: %u of %zu words differ\n", what, bad, expected.size());
378 };
379 compare("input (copy queue round trip)", offset_in, want.in, 0, 0);
380 compare("structured buffer", offset_data, want.data, 0, 0);
381 compare("dispatch arguments", offset_args, want.args, 0, 0);
382 compare("image", offset_image, want.image, image_pitch, image_dim);
383 compare("indirect dispatch output", offset_out2, want.out2, 0, 0);
384 EXPECT(!mismatches);
385 if (d.validation_errors()) {
386 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
387 return 1;
388 }
389 std::printf("M4: a COPY queue streamed an input buffer in, a COMPUTE queue ran a compute PSO over a UAV table "
390 "(structured buffer, raw buffers, an R32_UINT storage image) and a second dispatch through "
391 "ExecuteIndirect from arguments the first wrote, and a COPY queue behind a cross-queue fence read the "
392 "results back (%s): %u words matched the CPU reference (error 0)\n",
393 distinct_queues ? "two VkQueues" : "one VkQueue", words);
394 return 0;
395}
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index 2aa101e5b..d7e5c0316 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -58,8 +58,8 @@ def asm_mattr(path):
58CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1} 58CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1}
59 59
60 60
61def asm_fssm(path): 61def asm_fssm_fields(path):
62 """The synthetic FSSM program a vs_/ps_ shader's header asks for, or None.""" 62 """(offset, words) of the "fssm-at" and "fssm-data" header comments, (None, []) without them."""
63 at, words = None, [] 63 at, words = None, []
64 for ln in Path(path).read_text(encoding="utf-8").splitlines(): 64 for ln in Path(path).read_text(encoding="utf-8").splitlines():
65 s = ln.strip() 65 s = ln.strip()
@@ -71,11 +71,27 @@ def asm_fssm(path):
71 m = re.match(r";\s*fssm-data:\s*(.*)", s) 71 m = re.match(r";\s*fssm-data:\s*(.*)", s)
72 if m: 72 if m:
73 words += [int(w, 0) for w in m.group(1).split()] 73 words += [int(w, 0) for w in m.group(1).split()]
74 return at, words
75
76
77def asm_fssm(path):
78 """The synthetic FSSM program a vs_/ps_ shader's header asks for, or None."""
79 at, words = asm_fssm_fields(path)
74 if at is None or not words or at < 4 or at % 4: 80 if at is None or not words or at < 4 or at % 4:
75 return None 81 return None
76 return b"FSSM" + bytes(at - 4) + b"".join(struct.pack("<I", w) for w in words) 82 return b"FSSM" + bytes(at - 4) + b"".join(struct.pack("<I", w) for w in words)
77 83
78 84
85def cs_fssm_extra(path):
86 """A compute shader's "fssm-at"/"fssm-data" words (at 0x148 or later, after compute_header's header), or None.
87 Two compute shaders with the same group size and RSRC2 would otherwise share one FSSM hash, which is what the
88 layer finds a PSO's shader by."""
89 at, words = asm_fssm_fields(path)
90 if at is None or not words or at < 0x148 or at % 4:
91 return None
92 return at, b"".join(struct.pack("<I", w) for w in words)
93
94
79def shader_source(name): 95def shader_source(name):
80 return "vs_clip" if name in CLIP_CASES else name 96 return "vs_clip" if name in CLIP_CASES else name
81 97
@@ -113,7 +129,11 @@ def translate_tests(work, names):
113 if program: # where the translator looks for a program to hash, as in the game's work folder 129 if program: # where the translator looks for a program to hash, as in the game's work folder
114 (fssm / (n + ".fssm")).write_bytes(program) 130 (fssm / (n + ".fssm")).write_bytes(program)
115 if n.startswith("cs_"): 131 if n.startswith("cs_"):
116 (fssm / (n + ".fssm")).write_bytes(compute_header(asm_path)) 132 program = bytes(compute_header(asm_path))
133 extra = cs_fssm_extra(asm_path)
134 if extra:
135 program += bytes(extra[0] - len(program)) + extra[1]
136 (fssm / (n + ".fssm")).write_bytes(program)
117 elif n in CLIP_CASES and n != "vs_clip_undeclared": 137 elif n in CLIP_CASES and n != "vs_clip_undeclared":
118 (work / (n + ".dxbc")).write_bytes(clip_container()) 138 (work / (n + ".dxbc")).write_bytes(clip_container())
119 else: 139 else:
@@ -174,7 +194,8 @@ def main():
174 artifact = built / (n + suffix) 194 artifact = built / (n + suffix)
175 artifact.replace(spirv / artifact.name) 195 artifact.replace(spirv / artifact.name)
176 sidecar = work / "fssm" / (n + ".fssm") 196 sidecar = work / "fssm" / (n + ".fssm")
177 if not n.startswith("cs_") and sidecar.is_file(): 197 published = not n.startswith("cs_") or cs_fssm_extra(os.path.join(HERE, n + ".asm"))
198 if published and sidecar.is_file():
178 (out / "fssm").mkdir(exist_ok=True) 199 (out / "fssm").mkdir(exist_ok=True)
179 sidecar.replace(out / "fssm" / sidecar.name) 200 sidecar.replace(out / "fssm" / sidecar.name)
180 index.replace(published_index) 201 index.replace(published_index)
diff --git a/runtime/test/shaders/cs_m4_fill.asm b/runtime/test/shaders/cs_m4_fill.asm
new file mode 100644
index 000000000..1af46dac9
--- /dev/null
+++ b/runtime/test/shaders/cs_m4_fill.asm
@@ -0,0 +1,51 @@
1; group: 64,1,1
2; rsrc2: 0x808c
3; fssm-at: 0x150
4; fssm-data: 0x4c4c4946 0x3d344d5f
5; M4 compute shader 1: fills a structured UAV buffer and a typed UAV image from a raw input buffer, and writes the
6; arguments of the next (indirect) dispatch. Run: d3d12_m4_compute_test (a compute PSO found by the SHA-256 of its
7; synthetic FSSM header, as for the other cs_ shaders).
8; User data, from the root signature: [0] four 32-bit constants, [1] a descriptor table of five UAVs. RSRC2 0x808c =
9; six user SGPRs and TGID_X, so the group index is s6:
10; s0 = seed s1 = multiplier s2 = group count of the indirect dispatch s3 = unused
11; s[4:5] = console VA of the table's first slot. A slot is 32 bytes: a V# in its first 16 bytes or a T# in all 32.
12; slot 0 (+0x00): V#, structured buffer, stride 16, 256 records (written)
13; slot 1 (+0x20): V#, raw buffer, the arguments of the indirect dispatch (written)
14; slot 2 (+0x40): T#, 16x16 R32_UINT image (written)
15; slot 3 (+0x60): V#, raw buffer, 256 input words (read)
16; slot 4 (+0x80): V#, raw buffer, the second shader's output (not used here)
17; g = 64 * group + lane, 0..255: in = input[g]
18; record g = { in + seed, g * mul, in ^ (g << 8), rotr(in, 13) }
19; image(x = g & 15, y = g >> 4) = in * 3 + x * 0x10001 + y
20; g == 0 also writes the arguments { s2, 1, 1, 0xc0de0001 }
21s_load_dwordx4 s[8:11], s[4:5], 0x0
22s_load_dwordx4 s[12:15], s[4:5], 0x20
23s_load_dwordx8 s[16:23], s[4:5], 0x40
24s_load_dwordx4 s[24:27], s[4:5], 0x60
25s_lshl_b32 s7, s6, 6
26s_waitcnt lgkmcnt(0)
27v_add_nc_u32_e32 v1, s7, v0
28v_lshlrev_b32_e32 v2, 2, v1
29buffer_load_dword v3, v2, s[24:27], 0 offen
30s_waitcnt vmcnt(0)
31v_add_nc_u32_e32 v4, s0, v3
32v_mul_lo_u32 v5, v1, s1
33v_lshlrev_b32_e32 v6, 8, v1
34v_xor_b32_e32 v6, v3, v6
35v_alignbit_b32 v7, v3, v3, 13
36buffer_store_dwordx4 v[4:7], v1, s[8:11], 0 idxen
37v_and_b32_e32 v8, 15, v1
38v_lshrrev_b32_e32 v9, 4, v1
39v_mul_u32_u24_e32 v10, 0x10001, v8
40v_mul_lo_u32 v11, v3, 3
41v_add_nc_u32_e32 v10, v10, v11
42v_add_nc_u32_e32 v10, v10, v9
43image_store v10, v[8:9], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
44v_cmpx_eq_u32_e32 0, v1
45v_mov_b32_e32 v12, 0
46v_mov_b32_e32 v13, s2
47v_mov_b32_e32 v14, 1
48v_mov_b32_e32 v15, 1
49v_mov_b32_e32 v16, 0xc0de0001
50buffer_store_dwordx4 v[13:16], v12, s[12:15], 0 offen
51s_endpgm
diff --git a/runtime/test/shaders/cs_m4_indirect.asm b/runtime/test/shaders/cs_m4_indirect.asm
new file mode 100644
index 000000000..8a23596bf
--- /dev/null
+++ b/runtime/test/shaders/cs_m4_indirect.asm
@@ -0,0 +1,28 @@
1; group: 64,1,1
2; rsrc2: 0x808c
3; fssm-at: 0x150
4; fssm-data: 0x44444e49 0x3d344d5f
5; M4 compute shader 2: runs under ExecuteIndirect with the arguments cs_m4_fill wrote ({ groups, 1, 1 }), reads the
6; structured buffer and the image the first dispatch wrote, and writes a raw output buffer. Run:
7; d3d12_m4_compute_test. Same root signature, user data and table as cs_m4_fill (see there):
8; slot 0: structured buffer (read) slot 2: R32_UINT image (read, image_load) slot 4: raw output (written)
9; g = 64 * group + lane; t = image(g & 15, g >> 4); record g = { w0, w1, w2, w3 }
10; out[g] = { (w0 + t) ^ w3, (w2 ^ t) + w1 } at byte offset 8 * g
11s_load_dwordx4 s[8:11], s[4:5], 0x0
12s_load_dwordx8 s[16:23], s[4:5], 0x40
13s_load_dwordx4 s[12:15], s[4:5], 0x80
14s_lshl_b32 s7, s6, 6
15s_waitcnt lgkmcnt(0)
16v_add_nc_u32_e32 v1, s7, v0
17buffer_load_dwordx4 v[4:7], v1, s[8:11], 0 idxen
18v_and_b32_e32 v8, 15, v1
19v_lshrrev_b32_e32 v9, 4, v1
20image_load v10, v[8:9], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
21s_waitcnt vmcnt(0)
22v_add_nc_u32_e32 v11, v4, v10
23v_xor_b32_e32 v11, v11, v7
24v_xor_b32_e32 v12, v6, v10
25v_add_nc_u32_e32 v12, v12, v5
26v_lshlrev_b32_e32 v13, 3, v1
27buffer_store_dwordx2 v[11:12], v13, s[12:15], 0 offen
28s_endpgm
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h
index 6d12ff159..1e54a9487 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -84,6 +84,12 @@ public:
84 VkDevice device = VK_NULL_HANDLE; 84 VkDevice device = VK_NULL_HANDLE;
85 VkQueue queue = VK_NULL_HANDLE; 85 VkQueue queue = VK_NULL_HANDLE;
86 std::uint32_t family = 0; 86 std::uint32_t family = 0;
87 // Set before initialize(): how many queues of `family` to create (fewer if the family has fewer). `queues` holds the
88 // handles; queues[0] == queue. A test that wants distinct VkQueues for its D3D12 queues passes them on as
89 // VulkanDeviceInfo::command_queues when there is more than one.
90 std::uint32_t queue_count_wanted = 1;
91 std::uint32_t family_queue_count = 1; // the family's queueCount, known after the device is chosen
92 std::vector<VkQueue> queues;
87 bool validation = false; 93 bool validation = false;
88 bool bc = false; // textureCompressionBC enabled 94 bool bc = false; // textureCompressionBC enabled
89 VkPhysicalDeviceFeatures enabled{}; // the core features enabled on `device` 95 VkPhysicalDeviceFeatures enabled{}; // the core features enabled on `device`
@@ -286,6 +292,7 @@ public:
286 rank > best_rank) { 292 rank > best_rank) {
287 physical = candidate; 293 physical = candidate;
288 family = i; 294 family = i;
295 family_queue_count = families[i].queueCount;
289 chosen = props; 296 chosen = props;
290 best_rank = rank; 297 best_rank = rank;
291 v13_.choose(candidate13); 298 v13_.choose(candidate13);
@@ -377,11 +384,11 @@ public:
377 enable12.samplerFilterMinmax = sampler_filter_minmax; 384 enable12.samplerFilterMinmax = sampler_filter_minmax;
378 enable12.bufferDeviceAddress = VK_TRUE; 385 enable12.bufferDeviceAddress = VK_TRUE;
379 386
380 const float priority = 1.0f; 387 const std::vector<float> priority(std::max(1u, std::min(queue_count_wanted, family_queue_count)), 1.0f);
381 VkDeviceQueueCreateInfo queue_info{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; 388 VkDeviceQueueCreateInfo queue_info{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
382 queue_info.queueFamilyIndex = family; 389 queue_info.queueFamilyIndex = family;
383 queue_info.queueCount = 1; 390 queue_info.queueCount = std::max(1u, std::min(queue_count_wanted, family_queue_count));
384 queue_info.pQueuePriorities = &priority; 391 queue_info.pQueuePriorities = priority.data();
385 VkPhysicalDeviceFeatures enable{}; 392 VkPhysicalDeviceFeatures enable{};
386 enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available 393 enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available
387 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features) 394 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features)
@@ -487,7 +494,10 @@ public:
487 result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device); 494 result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device);
488 if (result != VK_SUCCESS) return failure("vkCreateDevice", result); 495 if (result != VK_SUCCESS) return failure("vkCreateDevice", result);
489 device_proc = instance_fn<PFN_vkGetDeviceProcAddr>("vkGetDeviceProcAddr"); 496 device_proc = instance_fn<PFN_vkGetDeviceProcAddr>("vkGetDeviceProcAddr");
490 fn<PFN_vkGetDeviceQueue>("vkGetDeviceQueue")(device, family, 0, &queue); 497 queues.resize(queue_info.queueCount);
498 for (std::uint32_t i = 0; i < queue_info.queueCount; ++i)
499 fn<PFN_vkGetDeviceQueue>("vkGetDeviceQueue")(device, family, i, &queues[i]);
500 queue = queues[0];
491 instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(physical, 501 instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(physical,
492 &memory_); 502 &memory_);
493 VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; 503 VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};