diff --git a/CMakeLists.txt b/CMakeLists.txt index 017d003eea..8021175afc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1954,6 +1954,16 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ "${CMAKE_SOURCE_DIR}/tests/native_compute_clear_check.py" "$" "${DXC_BIN_DIR}") add_test(NAME native_compute_raw_root COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_compute_raw_root_check.py" "$" "${DXC_BIN_DIR}") + foreach(backend IN ITEMS hardware warp) + add_test(NAME native_descriptor_scc_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_descriptor_scc_check.py" "$" + "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_descriptor_scc_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME startup_compute_descriptor_scc_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_descriptor_scc_check.py" runtime "$" + "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(startup_compute_descriptor_scc_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endforeach() add_test(NAME native_direct_container COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" "$" "${DXC_BIN_DIR}") diff --git a/docs/experiments/native-descriptor-stride-scc.md b/docs/experiments/native-descriptor-stride-scc.md new file mode 100644 index 0000000000..7df3ecb032 --- /dev/null +++ b/docs/experiments/native-descriptor-stride-scc.md @@ -0,0 +1,32 @@ +# Buffer-stride condition code in direct compute + +The direct DXIL frontend can carry a guest buffer descriptor symbolically +while calculating SCC from its bound stride. It recognizes a 14-bit stride +extraction from descriptor word 1 and the subsequent unsigned max with 1. The +first sets SCC when the extracted stride is nonzero. The max sets SCC when its +first operand wins strictly, so both operand orders have meaningful tests. + +This applies to fixed, unambiguous buffer SRV slots covered by a declared +descriptor-table range. The compiler adds one stride word per descriptor, +after the regular root constants. Native dispatch and the published manifest +both use the stride from the input view the runtime has already resolved. The +symbolic descriptor fields still carry their slot identity for later buffer +addressing. A dynamic heap or CBV/UAV slot, unproven stride source, and numeric +reads of other symbolic fields retain their refusals. + +The [source-built fixture](../../tests/native_descriptor_scc_check.py) checks +the layout and cache replay, then dispatches with strides of 0, 1, 4 and 16. +The runtime fixture changes guest descriptor fields between runs of the same +shader on the in-process and published paths. It compares the three status +words, the neighboring root constant, and every untouched output word. +The isolated replay also verifies 14-bit extraction and refuses to dispatch +if the stride input is missing. The fixtures use the repository's MIT license. + +```powershell +cmake --build --preset release --target compile_dxil native_store_replay startup_stream_consumer +ctest --preset release --no-tests=error -R '^(native_descriptor_scc|startup_compute_descriptor_scc)_' -V +``` + +The direct shaders require Shader Model 6.6 and 32-lane waves. An available +adapter without wave32 reports a skip. The instruction behavior follows the +[AMD RDNA 2 ISA, revision 1.0](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture). diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index f9a368cb1a..85e9bb2443 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -96,6 +96,9 @@ Bytes encode(const NativeComputeShader &program) { for (const auto &c : program.constants) for (unsigned n : {c.root_parameter, c.first_sgpr, c.count}) word(out, n); + word(out, static_cast(program.stride_srvs.size())); + for (unsigned srv : program.stride_srvs) + word(out, srv); word(out, static_cast(program.samplers.size())); for (const auto &s : program.samplers) { for (auto n : s.words) @@ -144,6 +147,9 @@ NativeComputeShader decode(std::string_view bytes) { throw std::runtime_error("invalid cached constants"); shader.constants.push_back(c); } + n = in.count(32); + for (unsigned j = 0; j < n; ++j) + shader.stride_srvs.push_back(in.count(31)); n = in.count(2048); for (unsigned j = 0; j < n; ++j) { ComputeSampler sampler{}; @@ -729,6 +735,7 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh return std::nullopt; ud_count += block.count; } + ud_count += static_cast(program.stride_srvs.size()); if (ud_count > 32) return std::nullopt; @@ -796,6 +803,12 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh for (const auto &block : program.constants) for (unsigned j = 0; j < block.count; ++j) out << "udsrc " << ud_index++ << " rootconst " << block.root_parameter << ' ' << j << '\n'; + for (unsigned srv : program.stride_srvs) { + if (srv >= srv_count || sorted[srv].kind != ComputeViewKind::raw_vector_srv || + sorted[srv].array_count != 1) + return std::nullopt; + out << "udsrc " << ud_index++ << " stride " << srv << '\n'; + } out << srv_lines.str() << uav_lines.str() << sampler_lines.str(); return out.str(); } diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index a0aef55d07..5b039f7514 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -109,6 +109,8 @@ struct GraphicsLinkage { struct NativeComputeShader { std::vector inputs, outputs; std::vector constants; + // Additional b0 words, after root constants, read from these bound SRVs. + std::vector stride_srvs; std::string hlsl, dxil_ir; std::vector bindings; std::vector samplers; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index d10177eb30..a63eee6ad5 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -32,6 +32,7 @@ struct DirectCompute { bool half_mode_known = true; unsigned mode_bits = 0xf0; std::vector scc_live; + std::map,string> descriptor_strides; unsigned label_number = 0; bool pixel_stage = false; // Straight-line graphics stages keep exact SSA definitions; a missing @@ -256,7 +257,7 @@ struct DirectCompute { initialize_constants(); } void initialize_constants(const GraphicsConstantLayout *linked = nullptr) { - unsigned words = 0; + unsigned words = static_cast(descriptor_strides.size()); for (const auto &block : analysis.result.constants) words += block.count; if (words) { @@ -265,18 +266,21 @@ struct DirectCompute { auto h = ir.handle({2, 0, 13, 0, 0, (words + 3) / 4 * 16}); unsigned pos = 0; std::map vectors; + const auto word_at = [&](unsigned at) { + auto &vec = vectors[at / 4]; + if (vec.empty()) + vec = ir.invoke("%dx.types.CBufRet.i32", "cbufferLoadLegacy.i32", 59, + {{"%dx.types.Handle", h}, {"i32", to_string(at / 4)}}, "nounwind readonly"); + return ir.value("extractvalue %dx.types.CBufRet.i32 " + vec + ", " + to_string(at % 4)); + }; for (const auto &block : analysis.result.constants) { if (linked) pos = linked->offset(block.root_parameter); - for (unsigned j = 0; j < block.count; ++j, ++pos) { - auto &vec = vectors[pos / 4]; - if (vec.empty()) - vec = ir.invoke("%dx.types.CBufRet.i32", "cbufferLoadLegacy.i32", 59, - {{"%dx.types.Handle", h}, {"i32", to_string(pos / 4)}}, "nounwind readonly"); - write(block.first_sgpr + j, - ir.value("extractvalue %dx.types.CBufRet.i32 " + vec + ", " + to_string(pos % 4))); - } + for (unsigned j = 0; j < block.count; ++j, ++pos) + write(block.first_sgpr + j, word_at(pos)); } + for (auto &entry : descriptor_strides) + entry.second = ir.binary("and",word_at(pos++),"16383"); } } // Refuses a GPU-selected heap read that the contract does not cover. raw_buffer is the only class that is translated. @@ -2070,6 +2074,56 @@ struct DirectCompute { } return scc_live[program.at.at(definition.next)]; } + void prepare_descriptor_strides() { + const auto &p = analysis.program; + const auto &layout = analysis.layout; + std::map,size_t> sources; + for (size_t n = 0; n < p.code.size(); ++n) { + if (!p.reached[n]) continue; + const auto &i = p.code[n]; + const auto field = byte_descriptor_field(i,p.before[n],heap_window); + if (!field || (field->type != Symbol::Type::stride && field->type != Symbol::Type::byte_stride) || + field->definition || field->value >= layout.NumParameters || !uses_scc_after(i)) + continue; + const auto ¶meter = layout.pParameters[field->value]; + if (parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE || + parameter.ShaderVisibility != D3D12_SHADER_VISIBILITY_ALL) + continue; + // The runtime provides the stride only for a fixed buffer SRV. + const auto &table = parameter.DescriptorTable; + const auto slot = field->offset / 32; + uint64_t next = 0; + unsigned srvs = 0, other = 0; + for (unsigned j = 0; j < table.NumDescriptorRanges; ++j) { + const auto &range = table.pDescriptorRanges[j]; + const uint64_t start = range.OffsetInDescriptorsFromTableStart == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND + ? next : range.OffsetInDescriptorsFromTableStart; + next = start + range.NumDescriptors; + if (start <= slot && slot < next) { + if (range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV) ++srvs; + else ++other; + } + } + if (srvs == 1 && !other) + sources.try_emplace({field->value,field->offset},n); + } + for (const auto &[source, n] : sources) { + const auto [root, offset] = source; + if (read_write_raw_views.count(source)) continue; + State descriptor; + for (unsigned j=0; j<4; ++j) + descriptor[j] = {Symbol::Type::descriptor,root,offset+4*j}; + analysis.binding(p.code[n],descriptor,0,4,ComputeViewKind::raw_vector_srv,4); + analysis.result.stride_srvs.push_back(analysis.result.bindings.back().shader_register); + descriptor_strides.try_emplace(source); + } + if (!descriptor_strides.empty()) { + size_t words = descriptor_strides.size(); + for (const auto &block : analysis.result.constants) words += block.count; + if (words > 32) + refuse(p.code.front().pc,"descriptor stride metadata exceeds the 32-word compute entry layout"); + } + } string saturated_add(const string &a, const string &b, bool sign) { auto sum = ir.binary("add", a, b); if (!sign) @@ -2335,8 +2389,20 @@ struct DirectCompute { // Its SCC is known for every source descriptor. if (field->type == Symbol::Type::byte_oob) write(128, "1"); - else if (n != "s_mul_i32" && uses_scc_after(i)) - refuse(i.pc, "numeric SCC from a symbolic descriptor field"); + else if (n != "s_mul_i32" && uses_scc_after(i)) { + const auto stride = descriptor_strides.find({field->value,field->offset}); + if (stride == descriptor_strides.end() || field->definition || + (field->type != Symbol::Type::stride && field->type != Symbol::Type::byte_stride)) + refuse(i.pc, "numeric SCC from a symbolic descriptor field"); + string condition; + if (field->type == Symbol::Type::stride) + condition = cmp("ne",stride->second,"0"); + else if (source(i,i.src[0],state).type == Symbol::Type::stride) + condition = cmp("ugt",stride->second,"1"); + else + condition = cmp("ult",stride->second,"1"); + write(128,ir.value("zext i1 " + condition + " to i32")); + } if (graphics_input) write(i.dst, {}); return; } @@ -3590,6 +3656,7 @@ struct DirectCompute { [](const Inst &i) { return i.enc == Encoding::Lds; }); if (uses_lds) ir.globals << "@lds = internal addrspace(3) global [" << lds_words << " x i32] undef, align 4\n"; + prepare_descriptor_strides(); initialize(user, flags, x, y, z); const auto &p = analysis.program; mode_bits = 0xf0; diff --git a/src/native_compute_pipeline.cpp b/src/native_compute_pipeline.cpp index ca74343cfe..f0f51b1299 100644 --- a/src/native_compute_pipeline.cpp +++ b/src/native_compute_pipeline.cpp @@ -49,6 +49,7 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade } pipeline.uav_count = counts[1]; pipeline.constants = std::move(program.constants); + pipeline.stride_srvs = std::move(program.stride_srvs); for (const auto &block : pipeline.constants) pipeline.constant_words += block.count; pipeline.srv_count = counts[0]; @@ -68,7 +69,8 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade D3D12_DESCRIPTOR_RANGE ranges[2]{}; for (const auto &b : pipeline.bindings) pipeline.atomic_views += b.kind == ComputeViewKind::indexed_atomic_uav; - if (unsigned(bool(counts[0])) + unsigned(bool(counts[1])) + pipeline.constant_words + + const auto b0_words = pipeline.constant_words + static_cast(pipeline.stride_srvs.size()); + if (unsigned(bool(counts[0])) + unsigned(bool(counts[1])) + b0_words + 2 * pipeline.atomic_views > D3D12_MAX_ROOT_COST) throw UnsupportedComputeShader("indexed atomic view metadata exceeds root parameter budget"); std::vector params(3 + pipeline.atomic_views); @@ -82,10 +84,10 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; param.DescriptorTable = {1, &ranges[i]}; } - if (pipeline.constant_words) { + if (b0_words) { auto ¶m = params[param_count++]; param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - param.Constants.Num32BitValues = pipeline.constant_words; + param.Constants.Num32BitValues = b0_words; } for (const auto &b : pipeline.bindings) { if (b.kind != ComputeViewKind::indexed_atomic_uav) continue; @@ -113,11 +115,14 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade void NativeComputePipeline::bind(ID3D12GraphicsCommandList *list, ID3D12DescriptorHeap *heap, D3D12_GPU_DESCRIPTOR_HANDLE first, UINT increment, const unsigned *words, - const std::vector &atomic, ID3D12DescriptorHeap *sampler_heap) const { + const std::vector &atomic, ID3D12DescriptorHeap *sampler_heap, + const std::vector &strides) const { if (constant_words && !words) throw std::runtime_error("compute root constants missing"); if (atomic.size() != atomic_views) throw std::runtime_error("indexed atomic view metadata missing"); + if (strides.size() != stride_srvs.size()) + throw std::runtime_error("compute descriptor stride metadata missing"); const bool views = srv_count || uav_count || heap_indexed; if (sampler_heap_indexed) { if (!sampler_heap) @@ -141,7 +146,10 @@ void NativeComputePipeline::bind(ID3D12GraphicsCommandList *list, ID3D12Descript if (uav_count) list->SetComputeRootDescriptorTable(parameter++, first); if (constant_words) - list->SetComputeRoot32BitConstants(parameter++, constant_words, words, 0); + list->SetComputeRoot32BitConstants(parameter, constant_words, words, 0); + if (!strides.empty()) + list->SetComputeRoot32BitConstants(parameter, static_cast(strides.size()), strides.data(), constant_words); + if (constant_words || !strides.empty()) ++parameter; for (const auto &shape : atomic) { const unsigned pair[]{shape.stride, shape.count}; list->SetComputeRoot32BitConstants(parameter++, 2, pair, 0); diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h index c25c9ea0f7..6dc3d8044e 100644 --- a/src/native_compute_pipeline.h +++ b/src/native_compute_pipeline.h @@ -13,6 +13,7 @@ struct NativeComputePipeline { Microsoft::WRL::ComPtr state; std::vector bindings; std::vector constants; + std::vector stride_srvs; unsigned srv_count = 0; unsigned uav_count = 0; unsigned constant_words = 0, atomic_views = 0; @@ -28,7 +29,8 @@ struct NativeComputePipeline { void bind(ID3D12GraphicsCommandList *list, ID3D12DescriptorHeap *heap, D3D12_GPU_DESCRIPTOR_HANDLE first, UINT increment, const unsigned *words = nullptr, - const std::vector &atomic = {}, ID3D12DescriptorHeap *sampler_heap = nullptr) const; + const std::vector &atomic = {}, ID3D12DescriptorHeap *sampler_heap = nullptr, + const std::vector &strides = {}) const; }; NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, ShaderDxilCompiler &compiler, diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index e2a665dbf1..94bddbb902 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -225,6 +225,16 @@ bool translate_compute_natively(ComputeTranslation& tr) for (const auto& block : program.constants) for (unsigned word = 0; word < block.count; ++word) tr.uds.push_back({static_cast(block.root_parameter), static_cast(word)}); + for (unsigned srv : program.stride_srvs) { + const bool present = std::any_of(program.bindings.begin(), program.bindings.end(), [srv](const auto& view) { + return view.kind == x2w::ComputeViewKind::raw_vector_srv && view.shader_register == srv; + }); + if (!present) throw std::runtime_error("descriptor stride source is not a bound SRV"); + ComputeTranslation::Slot slot{}; + slot.a = static_cast(srv); + slot.source = ComputeTranslation::input_stride; + tr.uds.push_back(slot); + } std::sort(program.bindings.begin(), program.bindings.end(), [](const auto& a, const auto& b) { return a.shader_register < b.shader_register; }); for (const auto& view : program.bindings) { diff --git a/tests/native_descriptor_scc_check.py b/tests/native_descriptor_scc_check.py new file mode 100644 index 0000000000..be455d3b26 --- /dev/null +++ b/tests/native_descriptor_scc_check.py @@ -0,0 +1,151 @@ +"""Observe the SCC of a buffer stride extraction and both MAX operand orders.""" + +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove +from startup_compute_dispatch_check import dispatch, lines, prepare_case +from startup_compute_translate_check import state_a +from startup_gfx2hlsl_compute_check import KEY, SENTINEL, TGID_X, TGID_Y, TGID_Z, USER7, WORDS + + +def program(*, runtime=False): + offset = 0 if runtime else 32 + table, constant = (6, 4) if runtime else (4, 5) + words = [sop1(3, 20, table), sop1(3, 21, 128), + 0xf408040a, 0xfa000000 | offset, # input SRV in s[16:19] + 0xf408080a, 0xfa000000 | (offset + 32), # output UAV in s[32:35] + 0xbf8cc07f, + scalar(0x27, 25, 17, 255), 0xe0010, # s_bfe_u32: 14-bit stride + sop1(3, 26, 253), + scalar(9, 27, 25, 129), sop1(3, 28, 253), + scalar(9, 29, 129, 25), sop1(3, 30, 253)] + if runtime: + # Flatten the 3x2x2 Dispatch so each group owns four output words. + words += [scalar(0x26, 8, 8, 131), scalar(0x26, 9, 9, 134), + scalar(0, 6, 7, 8), scalar(0, 6, 6, 9)] + words += [scalar(0x1e, 7, 6, 132), vmove(8, 7), sop1(3, 126, 129)] + for i, reg in enumerate((26, 28, 30, constant)): + words += [vmove(10, reg), 0xe0701000 | (4 * i), 0x80080a08] + return words + [0xbf810000] + + +def main(compile_dxil, replay, sdk, backend): + with TemporaryDirectory() as directory: + work = Path(directory) + dxc = Path(sdk) / "dxc.exe" + source, root = work / "root.hlsl", work / "root.bin" + requests = work / "requests" + requests.mkdir() + # s5 is one root constant and s6 is the X group ID. Exercise b0 with + # the descriptor metadata appended to a regular root constant. + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 6 << 1) + + def root_bytes(srv_count): + source.write_text(f'#define RS "DescriptorTable(SRV(t0,numDescriptors={srv_count}),' + f'UAV(u0,numDescriptors={3 - srv_count},offset={srv_count})),' + 'RootConstants(num32BitConstants=1,b0)"\n', encoding="ascii") + subprocess.run([dxc, "-T", "rootsig_1_1", "-E", "RS", source, "-Fo", root], check=True) + return root.read_bytes() + + marker = write_request(requests, program(), root_bytes(2), sa) + prefix = [compile_dxil, sdk, work / "cache", "gfx1013-direct-cs@0"] + for hit in (0, 1): + published = work / f"published-{hit}" + result = subprocess.run([*prefix, "--requests", requests, published], + capture_output=True, text=True) + assert result.returncode == 0 and f"frontend_cache_hit={hit}" in result.stdout, result.stdout + result.stderr + [manifest] = published.glob("*.txt") + assert manifest.read_text().splitlines() == [ + "x2w-manifest 2", "stage cs", "group 32 1 1", "ud 2", + "udsrc 0 rootconst 1 0", "udsrc 1 stride 0", + "srv 0 buf table 0 32", "uav 0 table 0 64", + ], manifest.read_text() + print("cold and warm manifests both bind the stride of SRV 0 after the root constant") + + negative = work / "negative" + negative.mkdir() + bad = write_request(negative, program(), root_bytes(1), sa) + result = subprocess.run([*prefix, bad, work / "bad.cso"], capture_output=True, text=True) + assert result.returncode and "numeric SCC from a symbolic descriptor field" in result.stderr, result.stderr + print("the same descriptor load from a UAV range is refused") + + mode = "--direct-warp" if backend == "warp" else "--direct" + readback, metadata = work / "readback.bin", work / "stride.txt" + for value in (0, 1, 4, 16, 0x4000, 0x7fff): + metadata.write_text(str(value), encoding="ascii") + result = subprocess.run([replay, sdk, marker, work / "cache", "0", readback, mode, metadata], + capture_output=True, text=True) + if result.returncode == 77: + print(result.stderr.strip()) + return 77 + assert result.returncode == 0, result.stdout + result.stderr + stride = value & 0x3fff + expected = [0x69696969] * 2064 + for group in range(2): + start = 8 + group * 4 + expected[start:start + 4] = [int(stride != 0), int(stride > 1), int(1 > stride), 3] + actual = list(struct.unpack("<2064I", readback.read_bytes())) + assert actual == expected, next((i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b) + print(f"stride word {value}: two groups match {expected[8:12]} and all guards") + result = subprocess.run([replay, sdk, marker, work / "cache", "0", readback, mode], + capture_output=True, text=True) + assert result.returncode == 1 and "compute descriptor stride metadata missing" in result.stderr, result.stderr + print("missing stride metadata is rejected before dispatch") + return 0 + + +def runtime_main(compile_dxil, consumer, sdk, backend): + with TemporaryDirectory() as directory: + work = Path(directory) + cache, env = prepare_case(work, backend) + env.pop("X2W_NATIVE_SHADERS", None) + env.pop("X2W_NATIVE_SHADERS_ONLY", None) + env["X2W_TEST_DISPATCH_FIELDS"] = str(work / "descriptor.bin") + fields = Path(env["X2W_TEST_DISPATCH_FIELDS"]) + fields.write_bytes(struct.pack("<6I", 4, 64, 0, 4, WORDS, 0)) + code = program(runtime=True) + (work / "program").write_bytes(struct.pack(f"<{len(code)}I", *code)) + (work / "state").write_bytes(state_a((32, 1, 1), USER7 | TGID_X | TGID_Y | TGID_Z)) + got, result = dispatch(work, consumer, env, "dispatch-records32", probe=True) + assert got == [SENTINEL] * WORDS and lines(result, "refused: no translation"), result.stderr + [marker] = cache.glob("req_*.c67") + + for route in ("native", "published"): + selected = dict(env) + if route == "native": + selected["X2W_NATIVE_SHADERS"] = sdk + else: + subprocess.run([compile_dxil, sdk, work / "frontend", "gfx1013-direct-cs@0", + "--requests", cache, cache], check=True) + manifest = cache / (marker.stem.removeprefix("req_") + ".txt") + assert "udsrc 2 stride 0\n" in manifest.read_text(), manifest.read_text() + for stride in (0, 1, 4, 16): + fields.write_bytes(struct.pack("<6I", stride, 64, 0, 4, WORDS, 0)) + got, result = dispatch(work, consumer, selected, "dispatch-records32") + if lines(result, "the adapter has no 32-lane waves"): + assert got == [SENTINEL] * WORDS + print("skip: runtime adapter has no wave32") + return 77 + expected = [int(stride != 0), int(stride > 1), int(1 > stride), KEY] * 12 + expected += [SENTINEL] * (WORDS - len(expected)) + assert got == expected, ( + next((i, a, b) for i, (a, b) in enumerate(zip(got, expected)) if a != b), result.stderr[-3000:] + ) + assert bool(lines(result, "translated natively: 3 entry values, 1 inputs, 1 outputs")) == ( + route == "native" + ), result.stderr[-3000:] + assert lines(result, "Dispatch(3, 2, 2) translated") and not lines(result, "refused: "), result.stderr + assert not [line for line in lines(result, "x2w-d3d12-debug ") if " sev=0 " in line or " sev=1 " in line] + print(f"{route}: stride {stride}, 12 groups match {expected[:4]} and all guards") + return 0 + + +if __name__ == "__main__": + if sys.argv[1] == "runtime": + sys.exit(runtime_main(*sys.argv[2:])) + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_store_replay.cpp b/tests/native_store_replay.cpp index 1c2250dae6..43b7af3df3 100644 --- a/tests/native_store_replay.cpp +++ b/tests/native_store_replay.cpp @@ -62,9 +62,9 @@ void report_adapter(ID3D12Device* device) { // A reference directory supplies independently compiled DXIL and its user-data layout. // --direct exercises the same direct DXIL frontend used by the runtime. int wmain(int argc, wchar_t **argv) { - if (argc != 6 && argc != 7) return 2; + if (argc < 6 || argc > 8) return 2; try { - const auto mode = argc == 7 ? std::wstring_view(argv[6]) : std::wstring_view{}; + const auto mode = argc >= 7 ? std::wstring_view(argv[6]) : std::wstring_view{}; const bool warp = mode == L"--direct-warp"; ComPtr adapter; if (warp) { @@ -102,6 +102,7 @@ int wmain(int argc, wchar_t **argv) { fs::path marker=argv[2], dest=argv[5]; const bool null_array = mode == L"--direct-null-srv"; const bool direct = null_array || warp || mode == L"--direct"; + if (argc == 8 && !direct) return 2; if (direct) { D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; @@ -119,6 +120,13 @@ int wmain(int argc, wchar_t **argv) { UINT index=0; for (auto &block:p.constants) for (unsigned j=0;j strides; + if (argc == 8) { + std::ifstream input{fs::path(argv[7])}; + unsigned stride; + while (input >> stride) strides.push_back(stride); + if (!input.eof()) throw std::runtime_error("invalid descriptor stride metadata"); + } UINT roots[64]{}; if (reference) { fs::path base=fs::path(argv[6])/marker.stem().wstring().substr(4); @@ -231,7 +239,8 @@ int wmain(int argc, wchar_t **argv) { if(reference){ ID3D12DescriptorHeap* h=heap.Get();cmd.list->SetDescriptorHeaps(1,&h);cmd.list->SetComputeRootSignature(p.root.Get()); cmd.list->SetComputeRoot32BitConstants(0,64,roots,0); - } else p.bind(cmd.list.Get(),heap.Get(),heap->GetGPUDescriptorHandleForHeapStart(),step,args.data(),atomic); + } else p.bind(cmd.list.Get(),heap.Get(),heap->GetGPUDescriptorHandleForHeapStart(),step,args.data(),atomic, + nullptr,strides); cmd.list->Dispatch(2,1,1); for(auto &w:windows) if(w.write) { transition(cmd.list.Get(),w.resource.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COPY_SOURCE);