diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index e0cb2a5a3c..3c8f44f6ad 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -42,6 +42,7 @@ struct ComputeTranslation { int state = 0; // 0 not loaded, 1 ready, 2 unavailable x2w_startup::ManifestRetry manifest_retry; // absent and stale manifests can become ready later std::vector uds, srvs, uavs; + UINT heap_srvs = 0; x2w_startup::TranslatedSamplers samplers; // static ones only x2w_startup::ComPtr root; x2w_startup::ComPtr pipeline; @@ -92,7 +93,7 @@ const char* create_compute_pipeline(ComputeTranslation& tr, const void* code, st { // Parameter 0 keeps one constant for a program without entry values: a constants parameter cannot be empty. if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.empty() ? 1 : tr.uds.size()), - static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size())))) + static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size()), tr.heap_srvs))) return "root signature creation failed"; D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; desc.pRootSignature = tr.root.Get(); @@ -203,6 +204,11 @@ const char* load_compute_translation(ComputeTranslation& tr) } else if (std::sscanf(line.c_str(), "srv %u tex2d table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) tr.srvs.push_back({a, b, true}); + else if (std::sscanf(line.c_str(), "resheap %u %u%n", &x, &y, &used) == 2 && whole()) { + if (tr.heap_srvs || !x || x > x2w_startup::max_translated_resheap || y != x2w_startup::translated_resheap_space) + return "a resource heap range outside the supported layout"; + tr.heap_srvs = x; + } // A static sampler, decoded as the draw path does: plain (smp), with the descriptor's LOD clamp (smpl) or a // comparison one (smpc). Not modelled here: the run-time sampler heap table (smpheap). else if (line.rfind("smpheap", 0) == 0) return "a sampler from the sampler heap"; @@ -403,7 +409,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& Wrapper* wrapper; std::uint32_t words[4]; // a buffer's descriptor words as it was bound from, and its stride UINT stride; - } views[40]{}; + }; static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) >= ViewRecord::srv_desc_bytes); static_assert(sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) >= ViewRecord::uav_desc_bytes); const auto type = list->GetType(); @@ -437,6 +443,9 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& if (tr->uds[i].source == ComputeTranslation::root_constant && !pass.compute_constants.is_bound(tr->uds[i].a, tr->uds[i].b, 1)) reason = "an entry value was not set since the compute root"; const std::size_t inputs = reason ? 0 : tr->srvs.size(), count = reason ? 0 : inputs + tr->uavs.size(); + std::vector views(reason ? 0 : count + tr->heap_srvs); + if (!reason && dispatch.signature && tr->heap_srvs) + reason = "translated indirect Dispatch requires fixed-table raw buffers"; for (std::size_t i = 0; i < count && !reason; ++i) { const bool output = i >= inputs; const ComputeTranslation::Slot slot = output ? tr->uavs[i - inputs] : tr->srvs[i]; @@ -480,7 +489,8 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& } // A heap record sits at the 32-bit byte offset the program computes, the index shifted left by 5, in the // title memory of the list's view heap: a literal byte offset, as a table's is. - const u64 entry = slot.heap ? (slot.word_param >= 0 || slot.a >= 0 ? pass.title_view_heap.record(std::uint32_t{index << 5}, 16) : 0) + const u64 entry = slot.heap ? ((slot.word_param >= 0 || slot.a >= 0) && index < pass.title_view_heap_entries + ? pass.title_view_heap.record(std::uint32_t{index << 5}, 16) : 0) : slot.a < 0 || slot.b < 0 ? 0 : pass.compute_tables.table(slot.a).record(static_cast(slot.b), slot.texture ? 32 : 16); const std::size_t entry_bytes = slot.texture ? 32 : 16; if (!entry || !x2w_local::readable(reinterpret_cast(entry), entry_bytes)) { @@ -639,6 +649,25 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& views[i] = {placed.alias, offset, bytes, true}; std::memcpy(views[i].words, words, sizeof(views[i].words)); } + for (UINT r = 0; r < tr->heap_srvs && !reason; ++r) { + std::memset(words, 0, sizeof(words)); + const u64 entry = r < pass.title_view_heap_entries ? pass.title_view_heap.record(u64{r} << 5, 16) : 0; + if (!entry || !x2w_local::readable(reinterpret_cast(entry), 16)) { + reason = "a heap record is outside the list's view heap"; + break; + } + std::memcpy(words, reinterpret_cast(entry), 16); + const IndirectBufferView view = indirect_table_buffer(self, words, false, &reason, 16u << 20); + if (view.resource && view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) + reason = "an input buffer range is not 16-byte aligned in its resource"; + if (reason && !tr->first_refusal) + log("x2w-draw compute %016llx first refused heap record %u, descriptor at 0x%llx", key, r, entry); + for (std::size_t output = inputs; output < count && !reason; ++output) + if (views[output].resource == view.resource) reason = "an output buffer is also an input"; + views[count + r] = {view.resource, view.offset, view.bytes, !view.upload}; + views[count + r].stride = view.stride; + std::memcpy(views[count + r].words, words, sizeof(views[count + r].words)); + } if (dispatch.argument) for (std::size_t i = 0; i < count && !reason; ++i) if (views[i].resource == dispatch.argument) reason = "the indirect argument buffer is also a bound shader resource"; @@ -684,14 +713,14 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); return reason; } - const UINT n = static_cast(count); + const UINT n = static_cast(count + tr->heap_srvs); UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(n))) % draw_heap_size; if (first + n > draw_heap_size) { first = 0; InterlockedExchange(&draw_heap_cursor, static_cast(n)); } D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + std::size_t{first} * draw_heap_increment}; - for (std::size_t i = 0; i < count; ++i, dest.ptr += draw_heap_increment) { + for (std::size_t i = 0; i < n; ++i, dest.ptr += draw_heap_increment) { const View& view = views[i]; if (i < inputs && view.texture) { // A compute list accepts no pixel-shader or depth state in a transition. @@ -701,7 +730,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& view.described ? &view.desc.srv : nullptr, dest); continue; } - if (i < inputs) { + if (i < inputs || i >= count) { if (view.transition) require_state(self, view.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); buffer_view(dest, view.resource, view.offset, static_cast(view.bytes)); continue; diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 7d1901c53a..3d18422106 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -3337,6 +3337,7 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* x2w_startup::SamplerSource source; u64 sampler_wrapper = 0; x2w_startup::ViewTable heap_records; + UINT heap_entries = 0; x2w_startup::ViewHeapSelection view_heaps; if (count && count <= 4 && x2w_local::readable(heaps, std::size_t{count} * sizeof(*heaps))) { AcquireSRWLockShared(¬e_lock); @@ -3346,9 +3347,11 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) view_heaps.note(heap.wrapper, heap.desktop_gpu != 0, heap.logical_count, heap.count); if (heap.wrapper == reinterpret_cast(heaps[i]) && - heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { heap_records = x2w_startup::resolve_view_table(heap.desktop_gpu, heap.title_cpu, heap.logical_count, heap.increment, heap.desktop_gpu); + if (heap_records.address) heap_entries = heap.logical_count; + } if (heap.wrapper == reinterpret_cast(heaps[i]) && heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER && heap.desktop_gpu) { sampler_wrapper = heap.wrapper; @@ -3367,6 +3370,7 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* pass.title_samplers = source; pass.sampler_heap_wrapper = sampler_wrapper; pass.title_view_heap = heap_records; + pass.title_view_heap_entries = heap_entries; } // The table at a title GPU handle, looked up in the title's view heap (the one set by slot 32 when known). diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 33c4f51f30..784b82b58e 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2883,6 +2883,7 @@ struct Pass { x2w_startup::ComputeTables compute_tables; // slot 35, read by a Dispatch handler u64 source_view_heap = 0; x2w_startup::ViewTable title_view_heap; // slot 32: the title memory of the list's view heap (heap records) + UINT title_view_heap_entries = 0; // logical descriptor count of title_view_heap (indices 0..count-1) u64 root_address[16] = {}; // title address of each root descriptor std::uint32_t constants[16][8] = {}; unsigned char constant_words_bound[16] = {}; diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index 21720a3595..8961082c97 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -20,6 +20,8 @@ constexpr UINT translated_sampler_count = D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_ constexpr UINT translated_sampler_space = 1; constexpr UINT translated_sampler_fallback = translated_sampler_count - 1; constexpr UINT title_sampler_stride = sizeof(SamplerWords); +constexpr UINT translated_resheap_space = 2; +constexpr UINT max_translated_resheap = 1024; // comparison: the sampler is read through a SamplerComparisonState (manifest line smpc). SQ_IMG_SAMP_WORD0 bits // 14:12 hold SQ_TEX_DEPTH_COMPARE, which lists NEVER..ALWAYS in the order of D3D12_COMPARISON_FUNC minus one. @@ -115,22 +117,28 @@ inline std::vector decode_statics(const TranslatedSam // views: the SRVs and UAVs of the view table together. inline UINT sampler_root_parameter(UINT views) { return views ? 2u : 1u; } -// Parameter 1, when there are views, is one table: SRVs t0.. first, then UAVs u0.. right after them. +// Parameter 1, when there are views, is one table: SRVs t0.. first, then UAVs u0.., then bounded resheap SRVs (space 2). inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT srvs, - const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 0) + const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 0, + UINT heap_srvs = 0) { D3D12_ROOT_PARAMETER parameters[3]{}; parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; parameters[0].Constants.Num32BitValues = constants; - // A compute program's outputs (u0..) follow its resources in the same table. - const D3D12_DESCRIPTOR_RANGE view_ranges[2]{{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}, - {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, uavs, 0, 0, srvs}}; + // A compute program's outputs (u0..) follow its resources in the same table; bounded heap SRVs follow in space 2. + D3D12_DESCRIPTOR_RANGE view_ranges[3]{}; + UINT range_count = 0; + if (srvs) view_ranges[range_count++] = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}; + if (uavs) view_ranges[range_count++] = {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, uavs, 0, 0, srvs}; + if (heap_srvs) { + view_ranges[range_count++] = { + D3D12_DESCRIPTOR_RANGE_TYPE_SRV, heap_srvs, 0, translated_resheap_space, srvs + uavs}; + } parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - // A range of no descriptors does not serialize: a program without resources starts the table at its outputs. - parameters[1].DescriptorTable = {(srvs ? 1u : 0u) + (uavs ? 1u : 0u), srvs ? view_ranges : view_ranges + 1}; + parameters[1].DescriptorTable = {range_count, view_ranges}; const D3D12_DESCRIPTOR_RANGE sampler_range{ D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, translated_sampler_count, 0, translated_sampler_space, 0}; - UINT count = sampler_root_parameter(srvs + uavs); + UINT count = sampler_root_parameter(srvs + uavs + heap_srvs); if (samplers.heap) { parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; parameters[count].DescriptorTable = {1, &sampler_range}; diff --git a/tests/checks/python-linux/startup_compute_waterfall_heap.txt b/tests/checks/python-linux/startup_compute_waterfall_heap.txt new file mode 100644 index 0000000000..decf1dc693 --- /dev/null +++ b/tests/checks/python-linux/startup_compute_waterfall_heap.txt @@ -0,0 +1 @@ +tests/startup_compute_waterfall_heap_check.py diff --git a/tests/cmake/startup_compute_waterfall_heap.cmake b/tests/cmake/startup_compute_waterfall_heap.cmake new file mode 100644 index 0000000000..a0ac246c9a --- /dev/null +++ b/tests/cmake/startup_compute_waterfall_heap.cmake @@ -0,0 +1,12 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_waterfall_heap_oracle_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_waterfall_heap_check.py" + --oracle "${DXC_EXECUTABLE}" "$" ${adapter}) + set_tests_properties(startup_compute_waterfall_heap_oracle_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_compute_waterfall_heap_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_waterfall_heap_check.py" + --dispatch "$" "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_waterfall_heap_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index 5a23d036a0..8d8eec6926 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -815,3 +815,133 @@ void check_bvh_root_roundtrip(ID3D12Device* device) run_compute(device, false, program); std::puts("normalized_signature=matched_control root_creation=passed pipeline_creation=passed dispatch=passed"); } + +int check_compute_waterfall_oracle(ID3D12Device* device, const char* shader_path) +{ + const auto code = read_compute_shader(shader_path); + ComPtr root; + check(device->CreateRootSignature(0, code.data(), code.size(), IID_PPV_ARGS(&root)), "Create waterfall oracle root"); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.Get(); + pso_desc.CS = {code.data(), code.size()}; + ComPtr pso; + check(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso)), "Create waterfall oracle pipeline"); + + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{}; + heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + heap_desc.NumDescriptors = 4; + heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + ComPtr heap; + check(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), "Create oracle descriptor heap"); + const UINT inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + const auto buf_desc = [](UINT64 size, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = size; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + return d; + }; + const auto write_upload = [](ID3D12Resource* res, const void* data, UINT sz) { + void* mapped = nullptr; + const D3D12_RANGE none{}; + check(res->Map(0, &none, &mapped), "Map upload buffer"); + std::memcpy(mapped, data, sz); + res->Unmap(0, nullptr); + }; + + std::array, 4> sources; + auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + for (UINT rec = 0; rec < 4; ++rec) { + const std::array data{ + 1000u * (rec + 1u), 1000u * (rec + 1u) + 17u, 1000u * (rec + 1u) + 34u, 1000u * (rec + 1u) + 51u}; + sources[rec] = resource(device, buf_desc(16), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + write_upload(sources[rec].Get(), data.data(), 16); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.NumElements = 4; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(sources[rec].Get(), &srv, handle); + handle.ptr += inc; + } + + auto keys_res = resource(device, buf_desc(16), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto init_res = resource(device, buf_desc(16), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto out_res = resource(device, buf_desc(16, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + auto rb_res = resource(device, buf_desc(16), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + constexpr std::array sentinels{0xc001cafeu, 0xc001cafeu, 0xc001cafeu, 0xc001cafeu}; + write_upload(init_res.Get(), sentinels.data(), 16); + + D3D12_COMMAND_QUEUE_DESC qdesc{}; + ComPtr queue; + ComPtr alloc; + ComPtr list; + ComPtr fence; + check(device->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&queue)), "Create oracle queue"); + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc)), "Create oracle alloc"); + check(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.Get(), nullptr, IID_PPV_ARGS(&list)), + "Create oracle list"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "Create oracle fence"); + check(list->Close(), "Close initial list"); + + const std::array, 5> inputs{{{0, 1, 2, 3}, {3, 2, 1, 0}, {2, 1, 2, 3}, {4, 9, 14, 19}, {7, 7, 7, 7}}}; + UINT matches = 0, mismatches = 0; + UINT64 fence_value = 0; + const auto barrier = [&](D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {out_res.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + list->ResourceBarrier(1, &b); + }; + + for (const auto& row : inputs) { + write_upload(keys_res.Get(), row.data(), 16); + for (UINT active = 0; active <= 4; ++active) { + check(alloc->Reset(), "Reset oracle alloc"); + check(list->Reset(alloc.Get(), pso.Get()), "Reset oracle list"); + barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(out_res.Get(), 0, init_res.Get(), 0, 16); + barrier(D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heaps[] = {heap.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(root.Get()); + list->SetComputeRootShaderResourceView(0, keys_res->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(1, heap->GetGPUDescriptorHandleForHeapStart()); + list->SetComputeRootUnorderedAccessView(2, out_res->GetGPUVirtualAddress()); + list->SetComputeRoot32BitConstant(3, active, 0); + list->Dispatch(1, 1, 1); + barrier(D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(rb_res.Get(), 0, out_res.Get(), 0, 16); + barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + check(list->Close(), "Close oracle list"); + ID3D12CommandList* cmd = list.Get(); + queue->ExecuteCommandLists(1, &cmd); + check(queue->Signal(fence.Get(), ++fence_value), "Signal oracle fence"); + while (fence->GetCompletedValue() < fence_value) Sleep(1); + + void* mapped = nullptr; + const D3D12_RANGE range{0, 16}; + const D3D12_RANGE no_writes{}; + check(rb_res->Map(0, &range, &mapped), "Map oracle readback"); + std::array got{}; + std::memcpy(got.data(), mapped, 16); + rb_res->Unmap(0, &no_writes); + + std::array expected{}; + for (UINT lane = 0; lane < 4; ++lane) + expected[lane] = lane < active ? 1000u * ((row[lane] & 3u) + 1u) + 17u * lane : 13u; + if (got == expected) ++matches; + else ++mismatches; + } + } + std::printf("dispatches=25 matches=%u mismatches=%u\n", matches, mismatches); + return 0; +} diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 6597bebcfe..d57366ae69 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -49,6 +49,7 @@ void check_spirv_compare_sampler(ID3D12Device* device, const char* shader_path, const char* reference_path, const char* descriptors = nullptr); void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference = nullptr, bool dpp_case = false, bool sized_views = false, UINT uav_words = 0); +int check_compute_waterfall_oracle(ID3D12Device* device, const char* shader_path); struct ComputeReadbackProgram { Microsoft::WRL::ComPtr signature; Microsoft::WRL::ComPtr pipeline; diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 4520b6bd55..3d53da367c 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1041,6 +1041,12 @@ OperationResult run_bvh_root_roundtrip(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +OperationResult run_compute_waterfall_oracle(const OperationContext& ctx) +{ + check_compute_waterfall_oracle(ctx.device, ctx.argv[3]); + return {OutcomeKind::pass, nullptr}; +} + OperationResult run_bvh_differential(const OperationContext& ctx) { return skip_if_false(check_bvh_differential(ctx.device, false)); @@ -1836,6 +1842,7 @@ const OperationSpec kOperations[] = { {"--mesh-depth-pair-fallback", 7, 7, nullptr, kGateSm60MeshFallback, run_mesh_depth_pair_fallback}, {"--mesh-shadow", 7, 8, validate_mesh_shadow_args, kNoGate, run_mesh_shadow}, {"--bvh-root-roundtrip", 3, 3, nullptr, kNoGate, run_bvh_root_roundtrip}, + {"--compute-waterfall-oracle", 4, 4, nullptr, kNoGate, run_compute_waterfall_oracle}, {"--bvh-differential", 3, 3, nullptr, kNoGate, run_bvh_differential}, {"--bvh-differential-pipeline", 3, 3, nullptr, kNoGate, run_bvh_differential_pipeline}, {"--bvh-hits", 3, 3, nullptr, kGateSm65, run_bvh_hits}, diff --git a/tests/startup_compute_waterfall_heap_check.py b/tests/startup_compute_waterfall_heap_check.py new file mode 100644 index 0000000000..3229de8bd5 --- /dev/null +++ b/tests/startup_compute_waterfall_heap_check.py @@ -0,0 +1,488 @@ +"""Per-lane resource-heap record index inside a compute v_readfirstlane_b32 waterfall loop (#2644 T3). + +usage: + startup_compute_waterfall_heap_check.py [--llvm-mc ] + startup_compute_waterfall_heap_check.py --dxil + startup_compute_waterfall_heap_check.py --oracle + startup_compute_waterfall_heap_check.py --dispatch + +Covers: +1. gfx2hlsl translation and manifest generation for bounded per-lane resource-heap indices in compute + waterfall loops, including both direct heap offsets (s_lshl_b32 + s_load_dwordx4 s[...], s[8:9], sI) + and the adjacent 64-bit pointer-add carry form (s_add_u32 + s_add_u32 0, src_scc / s_addc_u32, with + either in-body s_lshl_b32 or pre-loop v_lshlrev_b32 ..., 5), plus v_min_u32 and v_bfe_u32 bounds. +2. Soundness negative controls: unbounded keys, oversized masks, one-arm diamond bounds, bounded writes under + narrowed EXEC, missing/wrong shift, missing resheap root flag, non-zero high word, broken carry, descriptor + mutation, exit-live scalars, and forbidden store/formatted/idxen uses. +3. Independent DXIL handle metadata assertions via DXC cs_6_0: confirms the resource handle selects SRV space 2 + [0..3] with nonUniformIndex=true, and that stripping NonUniformResourceIndex changes it to false. +4. Four-record GPU oracle (--oracle): reference, static switch, no-marker, and first-active (asserting the + exact 12/25 first-active mismatches that distinguish lane-local selection from a wave-uniform shortcut). +5. End-to-end stand-in Dispatch fixture (--dispatch): translates both the direct-offset and 64-bit carry + waterfall programs via gfx2hlsl.py --pending, dispatches all five oracle key patterns plus active-lane + subsets through d3d12_xs.dll with the debug layer enabled, and verifies a short-range view heap that omits + the highest record (3) refuses cleanly before Dispatch. +""" +import argparse +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) + +import array_atomics_dxil_check as dxil # noqa: E402 +from startup_compute_dispatch_check import dispatch, lines # noqa: E402 +from startup_compute_request_check import DATA, prepare # noqa: E402 +from startup_compute_translate_check import state_a # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 +import startup_gfx2hlsl_heap_record_check as H # noqa: E402 +from startup_gfx2hlsl_compute_check import G, assemble, refused # noqa: E402 + +GROUP = (4, 1, 1) +NO_DATA = bytes(C.WORDS * 4) + +# Bounded four-record waterfall program matching the reference fixture (`bounded-waterfall.s`). +BOUNDED_PREFIX = ( + ('s_mov_b32 s12, s7', '07038cbe'), + ('s_mov_b32 s13, 0', '80038dbe'), + ('s_load_dwordx8 s[40:47], s[12:13], 0x0', '060a0cf4000000fa'), + ('s_waitcnt lgkmcnt(0)', '7fc08cbf'), + ('s_mov_b32 s9, 0', '800389be'), + ('v_lshlrev_b32_e32 v4, 2, v0', '82000834'), + ('buffer_load_dword v5, v4, s[40:43], 0 offen', '001030e004050a80'), + ('s_waitcnt vmcnt(0)', '703f8cbf'), +) +MASK_AND3 = ('v_and_b32_e32 v5, 3, v5', '830a0a36') +INIT_AND_GUARD = ( + ('v_mov_b32_e32 v7, 13', '8d020e7e'), + ('s_mov_b32 s26, exec_lo', '7e039abe'), + ('v_cmpx_gt_u32_e32 s4, v0', '0400a87d'), + ('s_mov_b32 s21, exec_lo', '7e0395be'), +) +HEAD = ('v_readfirstlane_b32 s22, v5', '05052c7e') +COMPARE = ('v_cmpx_eq_i32_e32 s22, v5', '160a247d') +SHIFT5 = ('s_lshl_b32 s23, s22, 5', '1685178f') +HEAP_LOAD = ('s_load_dwordx4 s[28:31], s[8:9], s23', '040708f40000002e') +CARRY_ADD_S23 = ( + ('s_add_u32 s24, s8, s23', '08171880'), + ('s_add_u32 s25, 0, src_scc', '80fd1980'), + ('s_load_dwordx4 s[28:31], s[24:25], 0x0', '0c0708f4000000fa'), +) +CARRY_ADD_S22 = ( + ('s_add_u32 s24, s8, s22', '08161880'), + ('s_add_u32 s25, 0, src_scc', '80fd1980'), + ('s_load_dwordx4 s[28:31], s[24:25], 0x0', '0c0708f4000000fa'), +) +WAIT_LGKM = ('s_waitcnt lgkmcnt(0)', '7fc08cbf') +BODY_LOAD = ('buffer_load_dword v7, v4, s[28:31], 0 offen', '001030e004070780') +WAIT_VM = ('s_waitcnt vmcnt(0)', '703f8cbf') +CLOSE = ('s_andn2_wrexec_b32 s21, s21', '154795be') +RESTORE = ('s_mov_b32 exec_lo, s26', '1a03febe') +FINAL_STORE = ('buffer_store_dword v7, v4, s[44:47], 0 offen', '001070e004070b80') +END = ('s_endpgm', '000081bf') + +ENCODINGS = { + 'v_min_u32_e32 v5, 3, v5': '830a0a26', + 'v_bfe_u32 v5, v5, 0, 2': '050048d505010a02', + 'v_lshlrev_b32_e32 v5, 5, v5': '850a0a34', + 'v_lshlrev_b32_e32 v5, 4, v5': '840a0a34', + 'v_and_b32_e32 v5, 0x7ff, v5': 'ff0a0a36ff070000', + 's_lshl_b32 s22, s22, 5': '1685168f', + 's_lshl_b32 s23, s22, 4': '1684178f', + 's_mov_b32 s24, s23': '170398be', + 's_mov_b32 s24, s22': '160398be', + 's_load_dwordx4 s[28:31], s[8:9], s24': '040708f400000030', + 's_load_dwordx4 s[28:31], s[8:9], s22': '040708f40000002c', + 's_load_dwordx4 s[28:31], s[22:23], 0x0': '0b0708f4000000fa', + 's_addc_u32 s25, s9, 0': '09801982', + 's_mov_b32 s9, 1': '810389be', + 's_cmp_eq_u32 s4, 0': '048006bf', + 's_cbranch_scc0 1': '010084bf', + 's_cbranch_scc0 2': '020084bf', + 's_branch 1': '010082bf', + 's_nop 0': '000080bf', + 's_or_b32 s31, s31, 0': '1f801f88', + 's_mov_b32 s22, 0': '800396be', + 'v_mov_b32_e32 v7, s22': '16020e7e', + 'v_mov_b32_e32 v7, s28': '1c020e7e', + 'buffer_load_dword v7, v4, s[28:31], 0 idxen': '002030e004070780', + 'buffer_load_format_x v7, v4, s[28:31], 0 offen': '001000e004070780', + 'buffer_store_dword v7, v4, s[28:31], 0 offen': '001070e004070780', +} + +BOUNDED_ORACLE_HLSL = """\ +ByteAddressBuffer keys : register(t0); +#if defined(STATIC_SWITCH) +ByteAddressBuffer r0 : register(t1), r1 : register(t2), r2 : register(t3), r3 : register(t4); +#else +ByteAddressBuffer records[4] : register(t1); +#endif +RWByteAddressBuffer result : register(u0); +cbuffer config : register(b0) { uint active; }; + +[RootSignature("SRV(t0), DescriptorTable(SRV(t1, numDescriptors=4)), UAV(u0), RootConstants(num32BitConstants=1,b0)")] +[numthreads(4, 1, 1)] +void main(uint3 tid : SV_GroupThreadID) +{ + uint lane = tid.x; + uint value = 13; + if (lane < active) { +#if defined(FIRST_ACTIVE) + uint index = keys.Load(0) & 3; +#else + uint index = keys.Load(4 * lane) & 3; +#endif +#if defined(STATIC_SWITCH) + switch (index) { + case 0: value = r0.Load(4 * lane); break; + case 1: value = r1.Load(4 * lane); break; + case 2: value = r2.Load(4 * lane); break; + default: value = r3.Load(4 * lane); break; + } +#elif defined(NO_MARKER) + value = records[index].Load(4 * lane); +#else + value = records[NonUniformResourceIndex(index)].Load(4 * lane); +#endif + } + result.Store(4 * lane, value); +} +""" + +ORACLE_ROWS = ((0, 1, 2, 3), (3, 2, 1, 0), (2, 1, 2, 3), (4, 9, 14, 19), (7, 7, 7, 7)) + + +def row_pair(asm): + return (asm, ENCODINGS[asm]) + + +def build_program(*, bound=(MASK_AND3,), init=INIT_AND_GUARD, body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, BODY_LOAD, WAIT_VM), + after_restore=()): + loop = (HEAD, COMPARE, *body, CLOSE) + offset = -(sum(len(bytes.fromhex(code)) for _, code in loop) // 4 + 1) + branch = ('s_cbranch_scc1 %d' % offset, struct.pack('> 5);' in hlsl_pre and 'rh[NonUniformResourceIndex(h0)].Load(a + 0)' in hlsl_pre + assert 'resheap 4 2\n' in man_pre + + # s_addc_u32 high-word carry, v_min_u32, v_bfe_u32, in-place s_lshl_b32, and clobber of s22 after load. + translate(build_program(body=(SHIFT5, ('s_add_u32 s24, s8, s23', '08171880'), row_pair('s_addc_u32 s25, s9, 0'), + ('s_load_dwordx4 s[28:31], s[24:25], 0x0', '0c0708f4000000fa'), + WAIT_LGKM, BODY_LOAD, WAIT_VM))) + translate(build_program(bound=(row_pair('v_min_u32_e32 v5, 3, v5'),))) + hlsl_bfe, man_bfe = translate(build_program(bound=(row_pair('v_bfe_u32 v5, v5, 0, 2'),))) + assert 'resheap 4 2\n' in man_bfe and 'rh[NonUniformResourceIndex(h0)].Load' in hlsl_bfe + hlsl_inp, _ = translate(build_program(body=(row_pair('s_lshl_b32 s22, s22, 5'), + row_pair('s_load_dwordx4 s[28:31], s[8:9], s22'), + WAIT_LGKM, BODY_LOAD, WAIT_VM))) + assert 'h0 = (s22 >> 5);' in hlsl_inp + hlsl_reused, _ = translate(build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, row_pair('s_mov_b32 s22, 0'), + BODY_LOAD, WAIT_VM))) + assert 'h0 = s22;' in hlsl_reused and 'rh[NonUniformResourceIndex(h0)].Load' in hlsl_reused + hlsl_ocpy, _ = translate(build_program(body=(SHIFT5, row_pair('s_mov_b32 s24, s23'), + row_pair('s_load_dwordx4 s[28:31], s[8:9], s24'), + WAIT_LGKM, BODY_LOAD, WAIT_VM))) + assert 'h0 = s22;' in hlsl_ocpy + + # Negative controls: every missing proof or forbidden extension stays refused. + controls = ( + ('unbounded key', build_program(bound=()), 'per-lane descriptor selection requires a proven bound heap range'), + ('oversized mask', build_program(bound=(row_pair('v_and_b32_e32 v5, 0x7ff, v5'),)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('only one diamond arm bounds key', + build_program(bound=(row_pair('s_cmp_eq_u32 s4, 0'), row_pair('s_cbranch_scc0 2'), MASK_AND3, + row_pair('s_branch 1'), row_pair('s_nop 0'))), + 'per-lane descriptor selection requires a proven bound heap range'), + ('bounded after EXEC narrowed without prior bound', + build_program(bound=(), init=(('v_mov_b32_e32 v7, 13', '8d020e7e'), ('s_mov_b32 s26, exec_lo', '7e039abe'), + ('v_cmpx_gt_u32_e32 s4, v0', '0400a87d'), MASK_AND3, + ('s_mov_b32 s21, exec_lo', '7e0395be'))), + 'per-lane descriptor selection requires a proven bound heap range'), + ('missing shift', build_program(body=(row_pair('s_load_dwordx4 s[28:31], s[8:9], s22'), + WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('wrong shift', build_program(body=(row_pair('s_lshl_b32 s23, s22, 4'), HEAP_LOAD, + WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('wrong pre-loop shift', + build_program(bound=(MASK_AND3, row_pair('v_lshlrev_b32_e32 v5, 4, v5')), + body=(*CARRY_ADD_S22, WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('non-resheap base', build_program(body=(row_pair('s_load_dwordx4 s[28:31], s[22:23], 0x0'), + WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('modified descriptor word', build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, + row_pair('s_or_b32 s31, s31, 0'), BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('non-zero resheap high word', + build_program(bound=(row_pair('s_mov_b32 s9, 1'), MASK_AND3)), + 'whose high word is not a constant zero'), + ('missing carry on s_add_u32 pointer add', + build_program(body=(SHIFT5, ('s_add_u32 s24, s8, s23', '08171880'), + ('s_load_dwordx4 s[28:31], s[24:25], 0x0', '0c0708f4000000fa'), + WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('live key at loop exit', + build_program(after_restore=(row_pair('v_mov_b32_e32 v7, s22'),)), 'body scalar is live at the loop exit'), + ('live descriptor word at loop exit', + build_program(after_restore=(row_pair('v_mov_b32_e32 v7, s28'),)), 'body scalar is live at the loop exit'), + ('idxen load through per-lane descriptor', + build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, + row_pair('buffer_load_dword v7, v4, s[28:31], 0 idxen'), WAIT_VM)), + 'has unproved modifiers'), + ('formatted load through per-lane descriptor', + build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, + row_pair('buffer_load_format_x v7, v4, s[28:31], 0 offen'), WAIT_VM)), + 'is not proven lane-local'), + ('store through per-lane descriptor', + build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, + row_pair('buffer_store_dword v7, v4, s[28:31], 0 offen'), WAIT_VM)), + 'is not proven lane-local'), + ) + for label, rows, expected in controls: + try: + refused(expected, lambda: translate(rows)) + except AssertionError as err: + raise AssertionError(f'{label}: {err}') from None + refused('per-lane descriptor selection requires a proven bound heap range', + lambda: translate(build_program(), root=H.root_blob(flags=0))) + + # Check binary reassembly against llvm-mc if provided. + checked_asm = 0 + if llvm_mc: + seen = set() + for asm, hexcode in (*BOUNDED_PREFIX, MASK_AND3, *INIT_AND_GUARD, HEAD, COMPARE, SHIFT5, HEAP_LOAD, + *CARRY_ADD_S23, *CARRY_ADD_S22, WAIT_LGKM, BODY_LOAD, WAIT_VM, CLOSE, RESTORE, + FINAL_STORE, END, *ENCODINGS.items()): + if asm not in seen and 's_cbranch' not in asm and 's_branch' not in asm: + seen.add(asm) + got = assemble(llvm_mc, asm + '\n') + assert got == bytes.fromhex(hexcode), f'{asm}: {got.hex()} != {hexcode}' + checked_asm += 1 + print(f'startup_compute_waterfall_heap: PASS (translator + {len(controls) + 1} refused controls' + + (f' + {checked_asm} llvm-mc encodings' if checked_asm else '') + ')') + + +def check_oracle(dxc, offscreen_check, adapter): + expected_binding = {'space': 0, 'lower': 1, 'size': 4} + with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + hlsl = d / 'bounded.hlsl' + hlsl.write_text(BOUNDED_ORACLE_HLSL, encoding='ascii') + results = {} + variants = ( + ('reference', [], True, ((25, 0),)), + ('static-switch', ['-D', 'STATIC_SWITCH'], None, ((25, 0),)), + ('first-active', ['-D', 'FIRST_ACTIVE'], None, ((13, 12),)), + # On WARP, dropping NonUniformResourceIndex still matches 25/25; on GPUs that scalarize dynamic + # descriptor loads (such as RX 7900 XTX), it reads lane 0 and mismatches 12/25, like first-active. + ('no-marker', ['-D', 'NO_MARKER'], False, ((25, 0), (13, 12))), + ) + for name, defs, want_nu, valid_counts in variants: + cso = d / f'{name}.cso' + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', *defs, '-Fo', cso, hlsl], check=True) + if want_nu is not None: + ir = subprocess.run([dxc, '-dumpbin', cso], check=True, capture_output=True, text=True).stdout + traced = trace_srv_handle(ir, expected_binding=expected_binding) + assert traced['non_uniform'] is want_nu, (name, traced) + res = subprocess.run([offscreen_check, adapter, '--compute-waterfall-oracle', cso], + capture_output=True, text=True) + if res.returncode == 77: + print(res.stdout + res.stderr) + return 77 + assert res.returncode == 0, f'{name} failed:\n{res.stdout}{res.stderr}' + m = re.search(r'dispatches=25 matches=(\d+) mismatches=(\d+)', res.stdout) + assert m, res.stdout + res.stderr + got_m, got_mis = int(m[1]), int(m[2]) + assert (got_m, got_mis) in valid_counts, f'{name}: got {(got_m, got_mis)}' + results[name] = (got_m, got_mis) + print(f"startup_compute_waterfall_heap_oracle ({adapter}): PASS {results}") + return 0 + + +def check_dispatch(consumer, dxc, adapter): + shapes = ( + ('direct', assemble_rows(build_program())), + ('carry64', assemble_rows(build_program(body=(SHIFT5, *CARRY_ADD_S23, WAIT_LGKM, BODY_LOAD, WAIT_VM)))), + ) + for label, program_bytes in shapes: + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(H.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + (directory / 'program').write_bytes(program_bytes) + (directory / 'data').write_bytes(NO_DATA) + (directory / 'state').write_bytes(state_a(GROUP, H.RSRC2)) + untouched = [C.SENTINEL] * C.WORDS + + # 1. Before translation: refused with "no translation", output untouched. + got, result = dispatch(directory, consumer, env, 'dispatch-heap-waterfall') + if result.returncode == 77: + print(result.stdout + result.stderr) + return 77 + assert got == untouched, f'{label}: untranslated dispatch wrote output' + assert len(lines(result, 'Dispatch(1, 1, 1) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + + # 2. Offline translate and validate DXIL nonUniformIndex metadata. + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, + capture_output=True, text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + assert 'resheap 4 2\n' in (cache / f'{key:016x}.txt').read_text(encoding='ascii') + verify_dxil(dxc, (cache / f'{key:016x}.cs.hlsl').read_text(encoding='ascii'), + expected_binding={'space': 2, 'lower': 0, 'size': 4}) + + # 3. Positive readback across the oracle key sets and active lane counts (0, 2, 4). + cases = [(keys, 4) for keys in ORACLE_ROWS] + [((0, 1, 2, 3), 2), ((0, 1, 2, 3), 0)] + for idx, (keys, active) in enumerate(cases): + in_path = directory / f'in-{idx}.bin' + in_words = list(keys) + [0] * (C.WORDS - 4) + in_path.write_bytes(struct.pack(f'<{C.WORDS}I', *in_words)) + case_env = dict(env, X2W_TEST_DISPATCH_IN=str(in_path), X2W_TEST_DISPATCH_ACTIVE=str(active)) + got, result = dispatch(directory, consumer, case_env, 'dispatch-heap-waterfall') + assert len(lines(result, 'Dispatch(1, 1, 1) translated')) == 1 and not lines(result, 'refused'), \ + result.stderr[-3000:] + errors = [ln for ln in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in ln or ' sev=1 ' in ln] + assert not errors, errors[0] + expected = [1000 * ((keys[lane] & 3) + 1) + 17 * lane if lane < active else 13 for lane in range(4)] + untouched[4:] + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, f'{label} case {idx} keys={keys} active={active} word={wrong[0]} got={got[wrong[0]]:08x} expected={expected[wrong[0]]:08x}' + + # 4. Short-range negative control: 3-descriptor heap omits record 3 and must refuse before Dispatch. + in_path = directory / 'in-short.bin' + in_path.write_bytes(struct.pack(f'<{C.WORDS}I', 0, 1, 2, 3, *([0] * (C.WORDS - 4)))) + short_env = dict(env, X2W_TEST_DISPATCH_IN=str(in_path), X2W_TEST_DISPATCH_ACTIVE='4') + got, result = dispatch(directory, consumer, short_env, 'dispatch-heap-waterfall-short') + assert got == untouched, f'{label}: short-range control modified output' + ref = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + want_reason = "a heap record is outside the list's view heap" + assert len(ref) == 1 and want_reason in ref[0], result.stderr[-3000:] + assert len(census) == 3 and census[1].endswith(f'reason "{want_reason}": 1 keys, 1 dispatches'), census + errors = [ln for ln in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in ln or ' sev=1 ' in ln] + assert not errors, errors[0] + print(f'startup_compute_waterfall_heap_dispatch ({adapter}): PASS (direct + carry64 translated, ' + f'DXIL nonUniformIndex verified, all {len(cases)} key/active readbacks matched, short-range control refused)') + return 0 + + +def main(): + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument('--llvm-mc') + parser.add_argument('--dxil') + parser.add_argument('--oracle', nargs=3) + parser.add_argument('--dispatch', nargs=3) + args, unknown = parser.parse_known_args() + if unknown: + sys.exit(__doc__) + if args.dxil: + hlsl, _ = translate(build_program()) + verify_dxil(args.dxil, hlsl, expected_binding={'space': 2, 'lower': 0, 'size': 4}) + print('startup_compute_waterfall_heap_dxil: PASS (nonUniformIndex true with intrinsic, false without)') + return 0 + if args.oracle: + return check_oracle(*args.oracle) + if args.dispatch: + return check_dispatch(*args.dispatch) + check_translator(args.llvm_mc) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 9a89c3dfe1..4749e8893b 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -243,13 +243,15 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin constexpr UINT long_records = 2u << 20, long_frames = 48; const bool shared_uav = mode == "dispatch-read-write-uav"; const bool indirect = mode.rfind("dispatch-indirect-", 0) == 0; + const bool heap_waterfall = mode.rfind("dispatch-heap-waterfall", 0) == 0; const bool pixel = mode.rfind("dispatch-indirect-pixel-", 0) == 0; const bool write_zero = mode == "dispatch-indirect-pixel-zero"; const bool root_srv = mode.rfind("dispatch-root-srv", 0) == 0; const UINT groups = mode == "dispatch-indirect-zero" || write_zero || mode == "dispatch-indirect-pixel-omit" ? 0u : mode == "dispatch-indirect-2" || mode == "dispatch-indirect-pixel-2" ? 2u : 5u; - auto* memory = static_cast(VirtualAlloc(nullptr, long_run ? 0x28000 + long_records * sizeof(UINT) : (indirect || root_srv) ? 0x30000 : 0x20000, - MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + const SIZE_T mem_bytes = heap_waterfall ? 0x60000 : long_run ? 0x28000 + long_records * sizeof(UINT) : + (indirect || root_srv) ? 0x30000 : 0x20000; + auto* memory = static_cast(VirtualAlloc(nullptr, mem_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (!memory) return 70; UINT* const buffers[2] = {memory, memory + 0x10000 / sizeof(UINT)}; UINT* const buffer2 = memory + 0x20000 / sizeof(UINT); @@ -281,6 +283,21 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin const UINT view[4] = {static_cast(address), static_cast(address >> 32) | fields[i][0] << 16, fields[i][1], fields[i][2]}; std::memcpy(descriptors[mode == "dispatch-swapped" ? 1 - i : i], view, sizeof(view)); } + UINT record_descs[4][4]{}; + if (heap_waterfall) { + for (UINT rec = 0; rec < 4; ++rec) { + UINT* const rec_buf = memory + (0x20000 + rec * 0x10000) / sizeof(UINT); + for (UINT i = 0; i < words; ++i) rec_buf[i] = 1000u * (rec + 1u) + 17u * i; + const D3D12_RESOURCE_DESC rdesc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + void* rec_res = nullptr; + if (FAILED(static_cast(invoke(device, 133, word(rec_buf), word(&rdesc), D3D12_RESOURCE_STATE_COMMON, + 0, word(&__uuidof(ID3D12Resource)), word(&rec_res))))) return 71; + const UINT64 address = reinterpret_cast(rec_buf); + const UINT view[4] = {static_cast(address), static_cast(address >> 32) | (4u << 16), words, 0}; + std::memcpy(record_descs[rec], view, sizeof(view)); + } + } const UINT64 between = reinterpret_cast(memory) + (long_run ? 0x28000 : 0x8000); void* placed2 = nullptr; if (root_srv) { @@ -323,10 +340,12 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin descriptors[1][0] += 8; // still inside the buffer: 318 records descriptors[1][2] = words - 2; } + const bool heap_short = mode == "dispatch-heap-waterfall-short"; const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 backing, bytes; - } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, heap_waterfall ? (heap_short ? 3u : 5u) : 4u, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; // dispatch-sampled-compute records the same calls on a compute list and queue. const D3D12_COMMAND_LIST_TYPE list_type = mode == "dispatch-sampled-compute" ? D3D12_COMMAND_LIST_TYPE_COMPUTE : D3D12_COMMAND_LIST_TYPE_DIRECT; @@ -367,12 +386,29 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (change_table_heap && (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&other_heap)))) || !other_heap || other_heap == heap)) return 72; - const bool heap_record = mode.rfind("dispatch-heap", 0) == 0; + const bool heap_record = mode.rfind("dispatch-heap", 0) == 0 && !heap_waterfall; if (heap_record) for (const UINT at : {0u, 32u, 64u}) std::memcpy(reinterpret_cast(cpu + at), descriptors[at != 64], sizeof(descriptors[0])); + if (heap_waterfall) { + if (heap_short) { + std::memcpy(reinterpret_cast(cpu + 32), record_descs[1], sizeof(record_descs[1])); + std::memcpy(reinterpret_cast(cpu + 64), record_descs[2], sizeof(record_descs[2])); + } else { + for (UINT rec = 0; rec < 4; ++rec) + std::memcpy(reinterpret_cast(cpu + rec * 32u), record_descs[rec], sizeof(record_descs[rec])); + std::memcpy(reinterpret_cast(cpu + 128), descriptors, sizeof(descriptors)); + } + } const bool heap_word = mode.rfind("dispatch-heap-word", 0) == 0; - const UINT constants[3] = {0x01234567, 0x9e3779b9, mode == "dispatch-heap-outside" ? 0x07ffffffu : heap_word ? 1u : 2u}; + UINT active_lanes = 4u; + if (heap_waterfall) { + char buf[32]; + const DWORD len = GetEnvironmentVariableA("X2W_TEST_DISPATCH_ACTIVE", buf, sizeof(buf)); + if (len && len < sizeof(buf)) active_lanes = static_cast(std::strtoul(buf, nullptr, 10)); + } + const UINT constants[3] = {heap_waterfall ? active_lanes : 0x01234567u, 0x9e3779b9u, + mode == "dispatch-heap-outside" ? 0x07ffffffu : heap_word ? 1u : 2u}; const UINT graphics[2] = {0xdeadbeef, 0xfeedface}; const auto bind = [&] { invoke(list, 32, 1, word(&heap)); @@ -501,7 +537,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (FAILED(static_cast(invoke(list, 9))) || FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; bind(); } - if (heap_record || root_srv) invoke(list, 39, 0, 1, word(&constants[2]), 2); + if (heap_record || root_srv || heap_waterfall) invoke(list, 39, 0, 1, word(&constants[2]), 2); if (heap_word) { // The index buffer of table byte 96, in this recording's upload memory (list slot 148). Byte 288 + 336 * 1 // holds the index, 2; every other word names record 0 or 1, the output's descriptor. @@ -516,7 +552,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin mode == "dispatch-heap-word-past" ? at : mode == "dispatch-heap-word-placed" ? words * 4 : bytes, 0}; std::memcpy(reinterpret_cast(cpu + 96), view, sizeof(view)); } - invoke(list, 35, 1, table_gpu); + invoke(list, 35, 1, table_gpu + (heap_waterfall && !heap_short ? 128u : 0u)); if (change_table_root) { invoke(list, 33, word(slot67_other_root)); invoke(list, 33, word(slot67_root)); @@ -531,6 +567,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (pixel) record.capture_before_consumer(adapter, device, list); if (indirect) record.execute(list, mode == "dispatch-indirect-multi" ? 2 : 1, mode == "dispatch-indirect-counted", mode == "dispatch-indirect-outside"); + else if (heap_waterfall) invoke(list, 14, 1, 1, 1); else if (mode == "dispatch-reference-2" || mode == "dispatch-reference-5") invoke(list, 14, mode == "dispatch-reference-2" ? 2 : 5, 1, 1); else if (mode != "dispatch-none" && mode != "dispatch-root-srv-none") invoke(list, 14, 3, 2, 2); diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 508f796682..9ed3372a55 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2367,6 +2367,111 @@ def region_walk(lo, hi): return out +RESHEAP_RANGE_SPACE = 2 +RESHEAP_RANGE_MAX = 1024 + + +def _lit_u32(tok): + if re.fullmatch(r'-?(?:0[xX][0-9a-fA-F]+|\d+)', tok) and tok not in FLOATS: + return int(tok, 0) & 0xffffffff + return None + + +def _join_vbound(a, b): + if a is None or b is None or a[0] != b[0]: + return None + return (a[0], max(a[1], b[1])) + + +def vgpr_heap_bounds(ins, succ): + """Forward CFG dataflow: map each instruction index to ({vreg: ('idx' | 'off5', max_idx)}, exec_is_entry). + + A bound enters only while every active lane that can reach a waterfall head executes the bounding write + (proven before any EXEC change, or joined with the prior bound on every path after EXEC changes).""" + if not ins: + return [] + before = [None] * len(ins) + before[0] = ({}, True) + work = [0] + for i in work: + regs, exec_entry = before[i] + _off, _n, name, asm = ins[i] + base, ops, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', base) + nxt_regs = dict(regs) + nxt_exec = exec_entry and not writes_exec(name, ops) + dst_v = set() + for tok in destinations(name, ops): + r = reg_range(tok) + if r and r[0] == 'v': + dst_v.update(range(r[1], r[2] + 1)) + if 'movrel' in name: + nxt_regs.clear() + elif dst_v: + new_val = None + r0 = reg_range(ops[0]) if ops else None + single = r0 and r0[0] == 'v' and r0[1] == r0[2] and r0[1] <= 255 and dst_v == {r0[1]} + if single and not mods: + def src_idx_max(tok): + k = _lit_u32(tok) + if k is not None: + return k + rs = reg_range(tok) + if rs and rs[0] == 'v' and rs[1] == rs[2] and regs.get(rs[1], ('',))[0] == 'idx': + return regs[rs[1]][1] + return None + + if base in ('v_and_b32', 'v_min_u32') and len(ops) == 3: + bounds = [b for b in (src_idx_max(ops[1]), src_idx_max(ops[2])) if b is not None] + if bounds and min(bounds) < RESHEAP_RANGE_MAX: + new_val = ('idx', min(bounds)) + elif base == 'v_bfe_u32' and len(ops) == 4: + width = _lit_u32(ops[3]) + if width is not None and width < 16 and ((1 << width) - 1) < RESHEAP_RANGE_MAX: + new_val = ('idx', (1 << width) - 1) + elif base == 'v_lshrrev_b32' and len(ops) == 3: + shift = _lit_u32(ops[1]) + if shift is not None: + shift &= 31 + rs = reg_range(ops[2]) + if rs and rs[0] == 'v' and rs[1] == rs[2] and regs.get(rs[1], ('',))[0] == 'idx': + new_val = ('idx', regs[rs[1]][1] >> shift) + elif (0xffffffff >> shift) < RESHEAP_RANGE_MAX: + new_val = ('idx', 0xffffffff >> shift) + elif base == 'v_lshlrev_b32' and len(ops) == 3: + shift = _lit_u32(ops[1]) + rs = reg_range(ops[2]) + if (shift is not None and (shift & 31) == 5 and rs and rs[0] == 'v' and rs[1] == rs[2] + and regs.get(rs[1], ('',))[0] == 'idx'): + new_val = ('off5', regs[rs[1]][1]) + elif base == 'v_mov_b32' and len(ops) == 2: + k = _lit_u32(ops[1]) + rs = reg_range(ops[1]) + if k is not None and k < RESHEAP_RANGE_MAX: + new_val = ('idx', k) + elif rs and rs[0] == 'v' and rs[1] == rs[2] and rs[1] in regs: + new_val = regs[rs[1]] + for v in dst_v: + merged = new_val if (single and exec_entry) else (_join_vbound(regs.get(v), new_val) if single else None) + if merged is not None: + nxt_regs[v] = merged + else: + nxt_regs.pop(v, None) + for s in succ[i]: + if before[s] is None: + before[s] = (nxt_regs, nxt_exec) + work.append(s) + else: + old_regs, old_exec = before[s] + m_exec = old_exec and nxt_exec + m_regs = {k: j for k, v in old_regs.items() if k in nxt_regs + for j in (_join_vbound(v, nxt_regs[k]),) if j is not None} + if (m_regs, m_exec) != before[s]: + before[s] = (m_regs, m_exec) + work.append(s) + return before + + def adjacent_address_carries(ins, targets): """Map each candidate low add to its high-word carry read in the same basic block.""" pairs = {} @@ -3145,13 +3250,15 @@ def execz_refusals(self): value = reads | (out - writes) if value != live_in[i]: live_in[i], changed = value, True + vbounds = vgpr_heap_bounds(self.ins, succ) self.waterfall_reads = {} + self.waterfall_heap_bounds = {} for close, target in jumps: head = index.get(target) if (head is not None and head + 3 < close and self.ins[close][2] == 's_cbranch_scc1' and self.ins[head][2] == 'v_readfirstlane_b32' and self.ins[close - 1][2] == 's_andn2_wrexec_b32'): - self.waterfall_reads[target] = self.waterfall_refusal(head, close, effects, live_in, jumps) + self.waterfall_reads[target] = self.waterfall_refusal(head, close, effects, live_in, jumps, vbounds) pre_sub = [EXEC_SUBSET] + [None] * (len(self.ins) - 1) changed = bool(self.ins) while changed: @@ -3343,7 +3450,109 @@ def execz_live_read(self, t, word, halves, effects, succ, quiet, unread): unread[word] = None return None - def waterfall_refusal(self, head, close, effects, live_in, jumps): + def compute_resheap_sgpr(self): + pipe = getattr(self, 'pipe', None) + root = getattr(pipe, 'root', None) + if not root or not (root['flags'] & 0x400): + return None + reg = 4 if getattr(self, 'kind', None) == 'cs' else 8 + for p in root['params']: + reg += 1 if p['type'] == 0 else p['count'] if p['type'] == 1 else 2 + return reg + + def waterfall_heap_check(self, head, close, effects, key, key_vtok, body_writes, numeric_writes, + buffer_descriptors, vbounds): + """Return ('idx' | 'off5', max_idx) when every key-dependent descriptor selection in the waterfall + body reads a resource heap record at a proven bounded per-lane index, else None.""" + if buffer_descriptors & numeric_writes: + return None + resheap_reg = self.compute_resheap_sgpr() + if resheap_reg is None or ('s%d' % resheap_reg) in body_writes or not vbounds: + return None + binfo = vbounds[head] + k_reg = int(key_vtok[1:]) + key_bound = binfo[0].get(k_reg) if binfo else None + if not key_bound: + return None + ins = self.ins + local_idx = {key} if key_bound[0] == 'idx' else set() + local_off5 = {key} if key_bound[0] == 'off5' else set() + local_ptrs = set() + heap_aliases = {'s%d' % resheap_reg} + local_descs = set() + pending_carry = None + for j in range(head + 2, close - 1): + base, ops, mods = parse(ins[j][3]) + base = re.sub(r'_e(32|64)$', '', base) + reads, _writes, may_write = effects[j] + if pending_carry is not None: + carry_d, want_j = pending_carry + pending_carry = None + hi_tok = 's%d' % (carry_d + 1) + carry_ok = (j == want_j and not mods and ( + (base == 's_add_u32' and ops == [hi_tok, '0', 'src_scc']) or + (base == 's_addc_u32' and len(ops) == 3 and ops[0] == hi_tok and ops[2] == '0' + and ops[1] not in body_writes))) + if not carry_ok: + return None + local_ptrs.add(('s%d' % carry_d, hi_tok)) + for w in may_write: + local_idx.discard(w) + local_off5.discard(w) + heap_aliases.discard(w) + local_descs = {tup for tup in local_descs if w not in tup} + continue + idx_hit = (base == 's_lshl_b32' and not mods and len(ops) == 3 and ops[1] in local_idx and ops[2] == '5') + mov_idx = base == 's_mov_b32' and not mods and len(ops) == 2 and ops[1] in local_idx + mov_off5 = base == 's_mov_b32' and not mods and len(ops) == 2 and ops[1] in local_off5 + mov_heap = base == 's_mov_b32' and not mods and len(ops) == 2 and ops[1] in heap_aliases + add_hit = (base == 's_add_u32' and not mods and len(ops) == 3 and ( + (ops[1] in heap_aliases and ops[2] in local_off5) or + (ops[2] in heap_aliases and ops[1] in local_off5))) + load_hit = False + if base == 's_load_dwordx4' and (reads & body_writes): + if mods or len(ops) != 3: + return None + br, dr = reg_range(ops[1]), reg_range(ops[0]) + if not br or br[0] != 's' or br[2] - br[1] != 1 or not dr or dr[0] != 's' or dr[2] - dr[1] != 3: + return None + b_lo, b_hi = 's%d' % br[1], 's%d' % br[2] + off_tok = smem_offset(ops[2]) + if not ((b_lo in heap_aliases and b_hi not in body_writes and off_tok in local_off5) or + ((b_lo, b_hi) in local_ptrs and _lit_u32(off_tok) == 0)): + return None + load_hit = tuple('s%d' % k for k in range(dr[1], dr[2] + 1)) + elif base == 'buffer_load_dword' and (reads & body_writes): + br = reg_range(ops[2]) if len(ops) >= 3 else None + dtup = tuple('s%d' % k for k in range(br[1], br[2] + 1)) if br and br[0] == 's' and br[2] - br[1] == 3 else None + if dtup not in local_descs or any(tok in body_writes and tok not in dtup for tok in scalar_tokens(ops[2])): + return None + for w in may_write: + local_idx.discard(w) + local_off5.discard(w) + heap_aliases.discard(w) + local_ptrs = {pair for pair in local_ptrs if w not in pair} + local_descs = {tup for tup in local_descs if w not in tup} + if idx_hit: + local_off5.add(ops[0]) + elif mov_idx: + local_idx.add(ops[0]) + elif mov_off5: + local_off5.add(ops[0]) + elif mov_heap: + heap_aliases.add(ops[0]) + elif add_hit: + dr = reg_range(ops[0]) + if not dr or dr[0] != 's' or dr[1] != dr[2] or dr[1] >= 105: + return None + pending_carry = (dr[1], j + 1) + elif load_hit: + local_descs.add(load_hit) + if pending_carry is not None: + return None + return key_bound + + def waterfall_refusal(self, head, close, effects, live_in, jumps, vbounds=None): """Return None when the lane can pick its own key at the head of the waterfall. CMPX selects all remaining lanes with the first lane's key. WREXEC removes those lanes, @@ -3391,7 +3600,7 @@ def waterfall_refusal(self, head, close, effects, live_in, jumps): for j in range(head + 2, close - 1): base, ops, mods = parse(ins[j][3]) base = re.sub(r'_e(32|64)$', '', base) - if base not in ('s_add_u32', 's_mov_b32', 's_and_b32', 's_or_b32', 's_lshl_b32', 's_waitcnt', + if base not in ('s_add_u32', 's_addc_u32', 's_mov_b32', 's_and_b32', 's_or_b32', 's_lshl_b32', 's_waitcnt', 'v_mov_b32', 'v_xor_b32', 'v_add_nc_u32', 's_load_dwordx4', 'buffer_load_dword'): return 'body instruction %s is not proven lane-local' % base if mods and not (base == 'buffer_load_dword' and mods == ['offen']): @@ -3412,6 +3621,8 @@ def waterfall_refusal(self, head, close, effects, live_in, jumps): buffer_descriptors.update(scalar_tokens(ops[2])) reads_before_write.update(reads - defined) defined.update(writes) + if base in ('s_add_u32', 's_addc_u32', 's_and_b32', 's_or_b32', 's_lshl_b32'): + defined.add('scc') body_writes.update(may_write) if (reads & keyed) or base == 'buffer_load_dword': keyed.update(may_write) @@ -3422,7 +3633,11 @@ def waterfall_refusal(self, head, close, effects, live_in, jumps): # The data byte offset can use the key. Loading or modifying the resource descriptor # with the key needs a separate proof that the runtime binds the whole range. if descriptor_inputs & body_writes or buffer_descriptors & numeric_writes: - return 'per-lane descriptor selection requires a proven bound heap range' + bound = self.waterfall_heap_check(head, close, effects, key, key_ops[1], body_writes, numeric_writes, + buffer_descriptors, vbounds) + if bound is None: + return 'per-lane descriptor selection requires a proven bound heap range' + self.waterfall_heap_bounds[ins[head][0]] = bound # The close leaves EXEC and SCC zero. The last physical pass's other scalar # values can differ per lane in this model and must be dead on every successor. # A scalar written from loop-invariant inputs only (no read of the key or of a key-dependent scalar, no @@ -3913,6 +4128,10 @@ def translate(self): self.spill_writes = {} # instruction index of a v_writelane_b32 translated in this pass -> (sym, uniform, proven, mask) self.heap_index = {} # SGPR -> what its word is for a resource-heap s_load (see heap_record) self.heap_index_was = {} # the marks the current instruction's destinations held before it + self.per_lane_index = {} # SGPR -> (expr, max_idx) from bounded waterfall v_readfirstlane_b32 + self.per_lane_index_was = {} + self.resheap_low_add = None + self.resheap_index_temps = [] self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) self.defined_uniform_s = set(init_entry_uniform) self.bad_sgprs = set() @@ -3953,6 +4172,7 @@ def translate(self): self.scc_def = None if not falls: self.scc_verified = False + self.resheap_low_add = None self.align4_v.clear() self.align4_s.clear() # Before the first branch target or terminator every path has run exactly the instructions above, so @@ -3961,6 +4181,8 @@ def translate(self): self.past_entry = bool(self.blocks) or 0 in targets if off in targets: self.heap_index.clear() # another path into the join may hold a different word + self.per_lane_index.clear() + self.resheap_low_add = None self.align4_v.clear() self.align4_s.clear() pre_uniform = { @@ -4659,8 +4881,11 @@ def one(self, name, asm): if hasattr(self, 'heap_index'): # unit probes build a Stage without the tracking state # Any write ends a register's mark; the lowering below sets the new one, if any. wrote = scalar_destinations(name, asm) - wrote = set(self.heap_index) if 'any' in wrote else wrote & set(self.heap_index) - self.heap_index_was = {r: self.heap_index.pop(r) for r in wrote} + wrote_h = set(self.heap_index) if 'any' in wrote else wrote & set(self.heap_index) + self.heap_index_was = {r: self.heap_index.pop(r) for r in wrote_h} + pl = getattr(self, 'per_lane_index', {}) + wrote_p = set(pl) if 'any' in wrote else wrote & set(pl) + self.per_lane_index_was = {r: pl.pop(r) for r in wrote_p} try: term = self.lower(base, asm, ops, mods) finally: @@ -5209,6 +5434,8 @@ def _lower(self, base, asm, ops, mods): hi = reg_range(ops[1]) if len(ops) == 3 else None if hasattr(self, 'scc_uniform') and self.tracks_uniformity(): self.scc_uniform = False + if self._complete_resheap_carry(base, ops, mods): + return None if hi and hi[0] == 's' and self.pointer_add(base, ops[0], ops[1:], [self.sym.get(hi[1]), None]): return None raise Unsupported(base) @@ -5651,6 +5878,26 @@ def exec_absorbed_source(self, base, srcs): return i return None + def _complete_resheap_carry(self, base, ops, mods): + if getattr(self, 'resheap_low_add', None) is None: + return False + low_d, expect_pc, per_lane_info = self.resheap_low_add + self.resheap_low_add = None + hi_tok = 's%d' % (low_d + 1) + hi_carry_ok = (self.pc == expect_pc and not mods and ( + (base == 's_add_u32' and ops == [hi_tok, '0', 'src_scc']) or + (base == 's_addc_u32' and len(ops) == 3 and ops[0] == hi_tok and ops[2] == '0' + and reg_range(ops[1]) and reg_range(ops[1])[0] == 's' + and self.sym.get(reg_range(ops[1])[1]) == ('const', 0)))) + if not hi_carry_ok: + return False + self.sym[low_d + 1] = ('ptrhi', ('resheap',), per_lane_info) + getattr(self, 'ptr_open_pairs', set()).discard(low_d) + self.__dict__.setdefault('ptr_addc_pcs', set()).add(self.pc) + self.scc_effect = 'emitted' + self.scc_verified = False + return True + def scalar(self, base, ops, mods=()): # Every SALU form in SCA is dst, src (the two templates below use {0} and {1}); a short list would # index past the end and leave `translator crash in : IndexError` in the census instead of a @@ -5661,6 +5908,8 @@ def scalar(self, base, ops, mods=()): raise Unsupported('s_movk_i32 with %d operands, expected 2' % len(ops)) text, scc = SCA[base] dst = reg_range(ops[0]) + if self._complete_resheap_carry(base, ops, mods): + return None if base == 's_add_u32' and self.address_carry_reader is not None and self.pc == self.address_carry_reader: if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: raise Unsupported('s_add_u32 destination %s' % ops[0]) @@ -5772,6 +6021,24 @@ def src_sym(t): getattr(self, 'mask_high', set()).discard(reg) if self.pointer_add(base, dname, srcs, syms): return None + if (base == 's_add_u32' and not mods and len(srcs) == 2 and dst and dst[0] == 's' + and dst[1] == dst[2] and dst[1] < 105 and hasattr(self, 'heap_index')): + for i in (0, 1): + if syms[i] == ('ptr', ('resheap',)): + off_r = reg_range(srcs[1 - i]) + heap_mark = ({**self.heap_index, **self.heap_index_was}.get(off_r[1]) + if off_r and off_r[0] == 's' and off_r[1] == off_r[2] else None) + if heap_mark and heap_mark[0] == 'per_lane': + ptr_r = reg_range(srcs[i]) + if self.sym.get(ptr_r[1] + 1) != ('const', 0): + raise Unsupported('s_load of a resource heap record through a pointer whose high ' + 'word is not a constant zero') + size = next((n for off, n, _name, _asm in getattr(self, 'ins', ()) if off == self.pc), 0) + self.sym[dst[1]] = ('ptr', ('resheap',), heap_mark) + self.__dict__.setdefault('ptr_open_pairs', set()).add(dst[1]) + self.resheap_low_add = (dst[1], self.pc + size, heap_mark) + self.scc_verified = True + return None if dname == 'm0': if scc: raise Unsupported('scc from descriptor data') @@ -6009,10 +6276,22 @@ def mark_heap_index(self, base, d, srcs, syms): r = reg_range(srcs[0]) if base == 's_lshl_b32' and lit[1:] == [5]: word = {**self.heap_index, **self.heap_index_was}.get(r[1]) if r and r[0] == 's' else None + per_lane = {**getattr(self, 'per_lane_index', {}), **getattr(self, 'per_lane_index_was', {})}.get(r[1]) \ + if r and r[0] == 's' else None if syms[0] and syms[0][0] == 'ud' and self.pipe.uds[syms[0][1]][0] == 'rootconst': self.heap_index[d] = self.pipe.uds[syms[0][1]] elif word and word[0] == 'bufword': self.heap_index[d] = ('buffer',) + word[1:] + elif per_lane is not None: + expr, bound = per_lane + self.heap_index[d] = ('per_lane', ('(s%d >> 5)' % d) if d == r[1] else expr, bound) + elif base == 's_mov_b32' and len(srcs) == 1 and r and r[0] == 's' and r[1] == r[2]: + word = {**self.heap_index, **self.heap_index_was}.get(r[1]) + per_lane = {**getattr(self, 'per_lane_index', {}), **getattr(self, 'per_lane_index_was', {})}.get(r[1]) + if word and word[0] == 'per_lane': + self.heap_index[d] = word + elif per_lane is not None: + self.per_lane_index[d] = ('s%d' % d, per_lane[1]) elif base in ('s_add_u32', 's_add_i32', 's_mul_i32') and len(srcs) == 2: for i in (0, 1): k = lit[1 - i] @@ -6549,6 +6828,14 @@ def op_s_load_dwordx4(self, ops, mods, count=4): p = self.sym.get(base[1]) if not p or p[0] != 'ptr': raise Unsupported('s_load through s%d holding %s' % (base[1], p)) + if len(p) > 2 and p[1] == ('resheap',) and isinstance(p[2], tuple) and p[2][0] == 'per_lane': + if (getattr(self, 'kind', None) != 'cs' or count != 4 or into_vcc or imm is not None + or _lit_u32(smem_offset(ops[2])) != 0): + raise Unsupported('s_load of a resource heap record through %s' % (p,)) + if (base[1] in getattr(self, 'ptr_open_pairs', ()) + or self.sym.get(base[2]) != ('ptrhi', ('resheap',), p[2])): + raise Unsupported('s_load through s%d: its high word is not the matching advanced pair' % base[1]) + return self._capture_resheap_desc(dst, p[2][1], p[2][2]) if len(p) > 2 and not isinstance(p[2], int): # The 'added' mark (an add whose offset is not tracked, as in a program with branches): no byte offset. raise Unsupported('s_load through s%d: the pointer was advanced by an untracked offset' % base[1]) @@ -6627,20 +6914,30 @@ def op_s_load_dwordx4(self, ops, mods, count=4): return self.heap_record(dst, base, token, imm, count) raise Unsupported('s_load with a register offset through %s' % (p[1],)) + def _capture_resheap_desc(self, dst, expr, bound): + if not hasattr(self, 'resheap_index_temps'): + self.resheap_index_temps = [] + temp = 'h%d' % len(self.resheap_index_temps) + self.resheap_index_temps.append(temp) + self.emit('%s = %s;' % (temp, expr)) + source = ('resheap', 'per_lane', temp, bound) + for i in range(4): + self.sym[dst[1] + i] = ('desc', source, 0, i) + def heap_record(self, dst, base, token, imm, count): """s_load_dwordx4 D, , R in a compute program, where R is an index shifted left by 5 with no later write of R and no branch target in between: D is the buffer descriptor in the 32-byte heap record that the index names. The index is a root constant word, or a word an s_buffer_load read from an unmodified table buffer at a literal byte offset or at a root constant word times a literal plus a literal - (the marks, see mark_heap_index, end at a branch target). The manifest names the root constant or where the - word is; the dispatch reads the word and the record. Only these exact forms are modelled.""" + (the marks, see mark_heap_index, end at a branch target), or a bounded per-lane index in a proven waterfall + loop. Only these exact forms are modelled.""" what = 's_load of a resource heap record' r = reg_range(token) index = getattr(self, 'heap_index', {}).get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None if index == ('buffer',): raise Unsupported('%s whose index is read from a buffer other than a table buffer at a dispatch-constant ' 'offset' % what) - if not index or index[0] not in ('rootconst', 'buffer'): + if not index or index[0] not in ('rootconst', 'buffer', 'per_lane'): raise Unsupported('%s whose offset is not a root constant shifted left by 5 since the last branch target' % what) if count != 4: raise Unsupported('%s of %d dwords' % (what, count)) @@ -6648,6 +6945,8 @@ def heap_record(self, dst, base, token, imm, count): raise Unsupported('%s with offset:%#x' % (what, imm)) if self.sym.get(base[2]) != ('const', 0): raise Unsupported('%s through a pointer whose high word is not a constant zero' % what) + if index[0] == 'per_lane': + return self._capture_resheap_desc(dst, index[1], index[2]) source = ('resheap',) + index[1:] if index[0] == 'rootconst' else ('resheap', 'word') + index[1:] for i in range(count): self.sym[dst[1] + i] = ('desc', source, 0, i) @@ -6929,6 +7228,8 @@ def buffer_address(self, ops, mods, *, is_formatted=False): key = self.load_descriptor(ops[2], what, stride0_ok=not idxen, raw_conversion_ok=not idxen) else: key = self.descriptor(ops[2]) + if isinstance(key[0], tuple) and key[0][:2] == ('resheap', 'per_lane') and idxen: + raise Unsupported('indexed load through a per-lane resource heap descriptor') buf = self.pipe.resource(key, 'buf') soffset = None if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): @@ -9018,6 +9319,12 @@ def op_v_readfirstlane_b32(self, ops, mods): if reason: raise Unsupported('compute readfirstlane waterfall: ' + reason) self.set_s(dst[1], self.u(ops[1]), uniform=False) # the selected key varies between lanes + bound = getattr(self, 'waterfall_heap_bounds', {}).get(self.pc) + if bound: + if bound[0] == 'idx': + self.per_lane_index[dst[1]] = ('s%d' % dst[1], bound[1]) + elif bound[0] == 'off5': + self.heap_index[dst[1]] = ('per_lane', '(s%d >> 5)' % dst[1], bound[1]) return if (mods or not dst or dst[0] != 's' or dst[1] != dst[2] or not src or src[0] != 'v' or src[1] != src[2] or not self.proven_uniform_v(src[1])): @@ -10553,6 +10860,8 @@ def declarations(self): lines.append(' uint %s;' % ', '.join('sp%d_%d = 0' % k for k in sorted(self.spill_slots))) if getattr(self, 'uniform_load_temps', None): lines.append(' uint %s;' % ', '.join('%s = 0' % n for n in sorted(self.uniform_load_temps))) + if getattr(self, 'resheap_index_temps', None): + lines.append(' uint %s;' % ', '.join('%s = 0' % n for n in self.resheap_index_temps)) lines.append(' uint vcc = 0, exec = 1, m0 = 0, a = 0, w = 0; bool scc = false; float4 t = 0;') if getattr(self, 'mesh_wave_loads', {}): lines.append(' bool wave_any = false;') @@ -11583,6 +11892,7 @@ def _init_pixel_context(self, root_blob, sampler_heap=None, rtv_formats=(), ps_h self.srv_formats = dict(srv_formats) if isinstance(srv_formats, dict) else dict(enumerate(srv_formats)) self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False + self.resheap_count = 0 self.uses_pack16_rne = False self.uses_bvh = False self.uses_cube_dir = False @@ -11660,6 +11970,13 @@ def ud(self, source): return self.uds.index(source) def resource(self, key, kind): + if isinstance(key[0], tuple) and key[0][:2] == ('resheap', 'per_lane'): + if kind != 'buf': + raise Unsupported('per-lane resource heap descriptor used as %s' % kind) + _tag, _sub, expr, bound = key[0] + if self.resheap_count <= bound: + self.resheap_count = bound + 1 + return 'rh[NonUniformResourceIndex(%s)]' % expr if key in self.stored_images(): raise Unsupported('resource %s is both read and stored to' % (key,)) r = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) @@ -11671,6 +11988,8 @@ def stored_images(self): return self.uavs or {} def uav(self, key, kind): + if isinstance(key[0], tuple) and key[0][:2] == ('resheap', 'per_lane'): + raise Unsupported('store through %s' % (key[0],)) if key in self.resources: raise Unsupported('resource %s is both read and stored to' % (key,)) if self.uavs is None: @@ -11853,6 +12172,8 @@ def common(self): out.extend(BVH_HELPERS) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'bvh': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D', 'texcube': 'TextureCube'}[r['kind']], r['index'], r['index'])) + if getattr(self, 'resheap_count', 0): + out.append('ByteAddressBuffer rh[%d] : register(t0, space%d);' % (self.resheap_count, RESHEAP_RANGE_SPACE)) for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): out.append('%s %s%d : register(u%d);' % ({'tex1d': 'RWTexture1D', 'tex2d': 'RWTexture2D', 'tex2da': 'RWTexture2DArray', 'tex3d': 'RWTexture3D', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) for key, i in self.samplers.items(): @@ -12278,6 +12599,8 @@ def manifest(self): raise Unsupported('stored image through %s' % (source,)) lines.append('uav %d %s table %d %d' % (r['index'], r['kind'], source[1] if len(source) > 1 else 0, off or 0)) lines += self.sampler_lines() + if self.resheap_count: + lines.append('resheap %d %d' % (self.resheap_count, RESHEAP_RANGE_SPACE)) if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) lines.append('params %d' % (max(self.params) + 1 if self.params else 0)) @@ -12317,6 +12640,7 @@ def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals self.vs_fetch, self.packed_position_vgpr, self.rtv_formats = None, None, () self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False + self.resheap_count = 0 self.uses_gather_2d_lod = False self.uses_store_d16_x = False self.uses_bvh = False @@ -12393,6 +12717,8 @@ def manifest(self): else: lines.append('uav %d %s float %s channels 4' % (r['index'], r['kind'], where)) lines += self.sampler_lines() + if self.resheap_count: + lines.append('resheap %d %d' % (self.resheap_count, RESHEAP_RANGE_SPACE)) if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) return '\n'.join(lines) + '\n'