Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -1744,8 +1744,19 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all
include PS_NoStripImmutableTable at s11 and VS_TransformD at s12. Their shader inputs establish the
destination dwords. The explicit graphics layouts and ordering for signatures with spills still need
independent root-signature evidence.
**Inline compute layout (integration #984).** Run
`python -I tools/compute_heap_layout_census.py <carve>/disasm` on each compute carve. Of 5,450 indexed compute
entries, 2,959 advertise direct indexing and none of those embeds its root signature. Adding
`--group fspx_compute --dispatch-log <dispatch-log>` joined seven resource-indexing entries to independently
recorded layouts. In all seven, a dynamically indexed resource descriptor used the first SGPR after the explicit
arguments. There were zero mismatches and zero cases without room **among those seven**. For the remaining
2,952 entries the layout is unknown. These are entries across carves, which can contain the same program.
No sampler-indexing entry had a matched layout. Putting the resource heap first when both flags are set, then the
sampler in the next dword, remains a hypothesis. D3D-329's adjacent SGPR examples alone do not establish it.
The runtime snapshots the bound resource and sampler heap pointers in that order after the explicit
arguments for direct and indirect compute dispatches with an inline signature. Set
arguments for direct and indirect compute dispatches with an inline signature. An unbound heap contributes
zero, and rebinding affects later commands. A heap that cannot fit in the inline user data is reported once,
and a signature whose compute arguments spill gets nothing written (logged once). Set
`LEONIDA_COMPUTE_DIRECT_HEAPS=0` to restore the previous compute arguments.
Draws do the same in the graphics layout (`pack_stage(Stage::Pixel)`, from s8, one dword per table): the
resource heap's 32-bit shader VA goes in the dword after the explicit arguments, then the sampler heap's, each
Expand Down
19 changes: 17 additions & 2 deletions runtime/shims/d3d12_com.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1679,10 +1679,26 @@ class GraphicsCommandList final
return !(v && std::string_view(v) == "0");
}

// Direct and indirect dispatches. Putting the resource heap first and the sampler heap next is a hypothesis
// with partial evidence (docs/d3d12_vulkan.md section 3.4, tools/compute_heap_layout_census.py). A heap with no
// inline user-data dword left is reported once per heap kind and the explicit arguments are kept.
std::array<std::uint32_t, rt::rootsig::kMaxUserSgprs> compute_user_data() const {
note_direct_heap_indexing(compute_.layout);
static const bool enabled = direct_heaps_enabled("LEONIDA_COMPUTE_DIRECT_HEAPS");
if (!enabled) return compute_.data;
return with_direct_heaps(compute_, compute_.layout->compute_arguments_end);
const RootArgumentLayout& layout = *compute_.layout;
const bool resource = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED;
const bool sampler = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED;
const std::uint32_t end = layout.compute_arguments_end;
if ((resource || sampler) && end == rt::rootsig::kNoSgpr) {
note_once("compute direct heaps: not supplied, the root arguments spill (no measured slot)");
} else {
if (resource && end >= rt::rootsig::kMaxUserSgprs)
note_once("compute root arguments leave no inline SGPR for the resource heap");
if (sampler && end + (resource ? 1u : 0u) >= rt::rootsig::kMaxUserSgprs)
note_once("compute root arguments leave no inline SGPR for the sampler heap");
}
return with_direct_heaps(compute_, end);
}

// Graphics: vertex, pixel and geometry shaders share one user-data block and the s8 layout, so the heaps after
Expand Down Expand Up @@ -1749,7 +1765,6 @@ class GraphicsCommandList final
std::fputc('\n', stderr);
}
}
note_direct_heap_indexing(compute_.layout);
check(list_.dispatch({compute_pipeline_, compute_user_data(), x, y, z}));
}

Expand Down
51 changes: 45 additions & 6 deletions runtime/test/d3d12_compute_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -588,15 +588,53 @@ int main() {
list->SetDescriptorHeaps(2, both);
list->SetComputeRootDescriptorTable(2, {gpu + 32});
list->Dispatch(1, 1, 1);
Ref<ID3D12CommandAllocator> bundle_allocator;
Ref<ID3D12GraphicsCommandList> bundle;
EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, IID_PPV_ARGS(&bundle_allocator.p))));
EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, bundle_allocator.p, nullptr,
IID_PPV_ARGS(&bundle.p))));
bundle->Dispatch(1, 1, 1);
EXPECT(SUCCEEDED(bundle->Close()));
list->ExecuteBundle(bundle.p);
list->SetDescriptorHeaps(1, &heap.p);
list->ExecuteIndirect(signature.p, 1, out_a.p, 0, nullptr, 0);
list->SetDescriptorHeaps(1, &sampler.p);
list->ExecuteIndirect(signature.p, 1, out_a.p, 0, nullptr, 0);
// 27 constants starting at s4 leave room for one heap. At 28, s31 is explicit too.
for (UINT count : {27u, 28u}) {
auto constants_param = params[0];
constants_param.Constants.Num32BitValues = count;
auto full_desc = direct_desc;
full_desc.Desc_1_0.NumParameters = 1;
full_desc.Desc_1_0.pParameters = &constants_param;
const auto blob = serialize(full_desc);
Ref<ID3D12RootSignature> full;
EXPECT(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&full.p))));
pipeline_desc.pRootSignature = full.p;
Ref<ID3D12PipelineState> full_pso;
EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pipeline_desc, IID_PPV_ARGS(&full_pso.p))));
list->SetPipelineState(full_pso.p);
list->SetComputeRootSignature(full.p);
list->SetComputeRoot32BitConstant(0, 123, count - 1);
list->SetDescriptorHeaps(2, both);
list->Dispatch(1, 1, 1);
}
EXPECT(SUCCEEDED(list->Close()));
std::vector<leonida::Command> commands;
EXPECT(rt::d3d12::recorded_commands(list.p, commands) && commands.size() == 2);
EXPECT(rt::d3d12::recorded_commands(list.p, commands) && commands.size() == 6);
const auto& before = std::get<leonida::Dispatch>(commands[0]).user_data;
const auto& after = std::get<leonida::ExecuteIndirect>(commands[1]).user_data;
EXPECT(before[8] == gpu + 32 && before[9] == gpu && before[10] == smp);
EXPECT(after[8] == gpu + 32 && after[9] == gpu && after[10] == 0);
const auto& after = std::get<leonida::ExecuteIndirect>(commands[2]).user_data;
char setting[2]{};
const bool enabled = GetEnvironmentVariableA("LEONIDA_COMPUTE_DIRECT_HEAPS", setting, 2) != 1 ||
setting[0] != '0';
EXPECT(before[8] == gpu + 32 && before[9] == (enabled ? gpu : 0) && before[10] == (enabled ? smp : 0));
EXPECT(after[8] == gpu + 32 && after[9] == (enabled ? gpu : 0) && after[10] == 0);
EXPECT(std::get<leonida::Dispatch>(commands[1]).user_data == before);
const auto& sampler_only = std::get<leonida::ExecuteIndirect>(commands[3]).user_data;
EXPECT(sampler_only[9] == 0 && sampler_only[10] == (enabled ? smp : 0));
const auto& one_slot = std::get<leonida::Dispatch>(commands[4]).user_data;
EXPECT(one_slot[30] == 123 && one_slot[31] == (enabled ? gpu : 0));
EXPECT(std::get<leonida::Dispatch>(commands[5]).user_data[31] == 123);
EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr)));
// The shader follows the V# at the heap index in s4. Slot 1 and the unrelated explicit table are null.
D3D12_SHADER_RESOURCE_VIEW_DESC srv{};
Expand Down Expand Up @@ -635,10 +673,11 @@ int main() {
const auto* values = static_cast<const UINT*>(results);
for (UINT i = 0; i < elements; ++i) {
EXPECT(values[i] == 0);
EXPECT(values[elements + i] == table_values[i % 4]);
EXPECT(values[elements + i] == (enabled ? table_values[i % 4] : 0));
}
readback->Unmap(0, nullptr);
std::puts("directly indexed compute heap: 64 buffer reads and 64 null controls matched");
std::puts(enabled ? "directly indexed compute heap: 64 buffer reads and 64 null controls matched"
: "directly indexed compute heap disabled: 128 zero controls matched");
EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr)));
}

Expand Down
64 changes: 64 additions & 0 deletions tests/test_compute_heap_layout_census.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""Compute heap layout census on synthetic shader containers, listings and dispatch logs."""
from pathlib import Path
import struct
import sys
import unittest

sys.path.insert(0, str(Path(__file__).resolve().parent))
from test_heap_index_census import Work, SFI0_RES, SFI0_SMP
from test_rootsig_census import container, rts0
import compute_heap_layout_census as c


class ComputeHeapLayout(unittest.TestCase):
def test_compare_programs(self):
work = Work()
self.addCleanup(work.close)
root = Path(work.root)
both = c.RESOURCE | c.SAMPLER

def program(name, res, smp, constants=3, flags=both, used=SFI0_RES | SFI0_SMP, embedded=True):
lines = [(f"s_mov_b32 s20, s{res}", 4), ("s_mov_b32 s21, 0", 4),
("s_load_dwordx8 s[32:39], s[20:21], s4", 8),
(f"s_mov_b32 s20, s{smp}", 4), ("s_load_dwordx4 s[40:43], s[20:21], s4", 8),
("image_sample v[0:3], v[4:5], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D", 8),
("s_endpgm", 4)]
work.add(name, "cs", used, lines, rsrc2=12 << 1)
if embedded:
payload = rts0(params=[("constants", 0, constants)], flags=flags)
(root / (name + ".dxbc")).write_bytes(container([(b"SFI0", struct.pack("<Q", used)), (b"RTS0", payload)]))

program("both", 7, 8)
program("swapped", 8, 7)
program("full", 7, 8, constants=28)
program("sampler_only", 10, 7, flags=c.SAMPLER, used=SFI0_SMP)
program("absent", 7, 8, embedded=False)
program("captured", 7, 8, embedded=False)
program("conflict", 7, 8, embedded=False)
program("other_process", 7, 8, embedded=False)
first, second = root / "first.log", root / "second.log"
layout = "[rt] compute-layout: pso=A flags=c00 bound-heap=0x0 shader-heap=0x0 (s4 type=0 const=3 slots=0)\n"
dispatch = "[rt] compute-input: execute=1 list=0 cmd=0 name=cs/captured pso=A direct groups=1,1,1\n"
first.write_text(layout + dispatch + layout.replace("pso=A", "pso=B") +
dispatch.replace("pso=A", "pso=B").replace("captured", "conflict") +
layout.replace("pso=A", "pso=B").replace("const=3", "const=4"), encoding="utf-8")
second.write_text(dispatch.replace("captured", "other_process"), encoding="utf-8")
counts = c.census(Path(work.disasm), c.captured_layouts([first, second], "cs"))
self.assertEqual((counts["compute"], counts["direct"]), (8, 8))
self.assertEqual((counts["match"], counts["resource matches"], counts["sampler matches"]), (3, 2, 3))
self.assertEqual((counts["mismatch"], counts["no room"], counts["missing layout"],
counts["ambiguous or invalid layout"]), (1, 1, 2, 1))

def test_ambiguous_and_explicit_table_reads(self):
def dynamic(n):
return {"roles": {"V#"}, "offset": ("dynamic", None), "base": f"user s{n}", "ptr": "ptr32"}

layout = (c.RESOURCE, 6, (4,))
self.assertEqual(c.compare(c.RESOURCE, layout, [dynamic(4)]), "inconclusive")
self.assertEqual(c.compare(c.RESOURCE, layout, [dynamic(4), dynamic(6)]), "match")
self.assertEqual(c.compare(c.RESOURCE, layout, [dynamic(6), dynamic(8)]), "inconclusive")
self.assertEqual(c.compare(c.SAMPLER, layout, []), "incompatible flags")


if __name__ == "__main__":
unittest.main()
168 changes: 168 additions & 0 deletions tools/compute_heap_layout_census.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
"""Compare compute heap-base reads with an independently known inline root layout. Print aggregate counts by default.

Usage: python -I tools/compute_heap_layout_census.py <carve>/disasm
[--dispatch-log LOG ... --group GROUP] [--per-program]

Read the carve index, each compute container's SFI0 and embedded RTS0, and the listing and
launch metadata for comparable programs. An optional integration dispatch log pairs compute-layout
parameter records with compute-input program names by PSO within that log. Use one carve group
per invocation. Entries in different carves need not be unique programs.
"""
import argparse
from collections import Counter, defaultdict
import json
import re
import struct
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import heap_index_census as heap
import shader_meta
import rootsig_census as roots

RESOURCE, SAMPLER = 0x400, 0x800 # D3D12 root-signature flags
PARAM = re.compile(r" \(s(\d+) type=(\d+) const=(\d+) slots=\d+\)")


def captured_layouts(logs, group):
by_name = defaultdict(set)
for path in logs:
# Never join handles across processes, or a reused handle with ambiguous ownership.
names, layouts = defaultdict(set), defaultdict(set)
with path.open(encoding="utf-8", errors="replace") as stream:
for line in stream:
if "[rt] compute-layout:" in line:
match = re.search(r"compute-layout: pso=(\w+) flags=([\da-fA-F]+) .*?shader-heap=\S+(.*)$", line)
if not match:
continue
handle, flags, tail = match.groups()
end, tables = 4, []
valid = not PARAM.sub("", tail).strip()
for slot, kind, count in PARAM.findall(tail):
width = {"0": int(count), "1": 2, "2": 1}.get(kind, 0)
valid &= int(slot) == end and width > 0
if kind == "2":
tables.append(end)
end += width
layouts[handle].add((int(flags, 16), end, tuple(tables)) if valid else None)
elif "compute-input: execute=" in line and " pso=" in line:
m = re.search(r" name=(\S+) pso=(\w+)", line)
if m:
names[m[2]].add(m[1])
for handle, programs in names.items():
for program in programs:
prefix, _, name = program.rpartition("/")
if prefix == group:
by_name[name].update(layouts[handle] if len(programs) == 1 else {None})
return by_name


def embedded_layout(payload):
sig, error = roots.parse_rts0(payload)
if error:
return None
end, tables = 4, []
for p in sig["params"]:
if p["type"] == "table":
tables.append(end)
end += 1
else:
end += p["count"] if p["type"] == "constants" else 2
return sig["flags"], end, tuple(tables)


def compare(kind, layout, loads):
flags, end, tables = layout
if not flags & kind:
return "incompatible flags"
expected = end + (kind == SAMPLER and bool(flags & RESOURCE))
if expected >= 32:
return "no room"
roles = {"V#", "T#"} if kind == RESOURCE else {"S#"}
# Declared tables can use dynamic offsets too. Never use the predicted heap slot
# to choose among multiple remaining candidates.
candidates = set()
for load in loads:
if not roles.intersection(load["roles"]) or load["offset"][0] != "dynamic":
continue
base = re.fullmatch(r"user s(\d+)", load["base"])
if not base or load["ptr"] != "ptr32":
return "inconclusive"
reg = int(base[1])
if reg not in tables:
candidates.add(reg)
if len(candidates) != 1:
return "inconclusive"
return "match" if expected in candidates else "mismatch"


def program_loads(disasm, name):
user = heap.cs_user_count(disasm, name)
launch = disasm.parent / "fspx" / (name + ".json")
if user is None and launch.exists():
user = json.loads(launch.read_bytes()).get("user_sgprs")
listing = disasm / (name + ".s")
if user is not None and listing.is_file():
ir = heap.shader_ir.parse_file(str(listing))
if ir["insns"] and not ir["invalid"]:
try:
return heap.analyse(ir["insns"], "cs", user)
except heap.Skip:
pass
return []


def census(disasm, captured, per_program=False):
result = Counter()
for name, stage in heap.stage_index(disasm).items():
if stage != "cs":
continue
result["compute"] += 1
chunks = roots.parts((disasm.parent / (name + ".dxbc")).read_bytes())
sfi = chunks.get(b"SFI0", b"")
if len(sfi) < 8:
result["missing SFI0"] += 1
continue
bits = struct.unpack_from("<Q", sfi)[0]
used = (RESOURCE if bits & shader_meta.SFI0_RESOURCE_DESCRIPTOR_HEAP_INDEXING else 0) | (
SAMPLER if bits & shader_meta.SFI0_SAMPLER_DESCRIPTOR_HEAP_INDEXING else 0)
if not used:
continue
result["direct"] += 1
result[{RESOURCE: "resource only", SAMPLER: "sampler only", RESOURCE | SAMPLER: "both"}[used]] += 1
layouts = set(captured.get(name, ()))
if b"RTS0" in chunks:
layouts.add(embedded_layout(chunks[b"RTS0"]))
kinds = [kind for kind in (RESOURCE, SAMPLER) if kind & used]
if len(layouts) != 1 or None in layouts:
status = "ambiguous or invalid layout" if layouts else "missing layout"
checks = dict.fromkeys(kinds, status)
else:
loads = program_loads(disasm, name)
checks = {kind: compare(kind, next(iter(layouts)), loads) for kind in kinds}
status = next(s for s in ("incompatible flags", "no room", "mismatch", "inconclusive", "match")
if s in checks.values())
result[status] += 1
for kind, label in ((RESOURCE, "resource"), (SAMPLER, "sampler")):
result[label + " matches"] += checks.get(kind) == "match"
if per_program:
print(f"{name}\tresource={checks.get(RESOURCE, 'unused')}\tsampler={checks.get(SAMPLER, 'unused')}")
return result


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("disasm", type=Path)
parser.add_argument("--dispatch-log", action="append", default=[], type=Path)
parser.add_argument("--group", default="", help="program path prefix in the dispatch log")
parser.add_argument("--per-program", action="store_true", help="also print local program names and each heap result")
args = parser.parse_args()
try:
counts = census(args.disasm, captured_layouts(args.dispatch_log, args.group), args.per_program)
except (OSError, ValueError, KeyError, TypeError) as exc:
parser.exit(2, f"ERROR: {exc}\n")
for key in ("compute", "missing SFI0", "direct", "resource only", "sampler only", "both",
"match", "resource matches", "sampler matches", "mismatch", "no room", "inconclusive", "missing layout",
"ambiguous or invalid layout", "incompatible flags"):
print(f"{key}: {counts[key]}")
Loading