Add mesh and amplification shaders

Output arrays (vertices, primitives, indices) are a pointer space of
their own: stores through it become storeVertexOutput /
storePrimitiveOutput / emitIndices in DXIL and per-attribute output
arrays in SPIR-V (SPV_EXT_mesh_shader, SPIR-V 1.4+). Payloads are
struct-typed memory accessed by GEP in DXIL (getMeshPayload, a
groupshared or local variable for dispatchMesh) and TaskPayloadWorkgroupEXT
storage in SPIR-V. MS/AS state metadata, PSV info and PSG1. PSV now
reports UsesViewID with its (empty) masks.

The codegen oracle passes each test's -fspv-target-env (spirv-val
spells vulkan1.1spirv1.4 as vulkan1.1spv1.4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Peter Li 2026-10-31 12:29:20 -07:00
parent af26ea5e9e
commit 2ff3afc7ef
15 changed files with 804 additions and 29 deletions

View File

@ -53,6 +53,12 @@ const Lowered = union(enum) {
/// A place in a constant buffer: byte offset plus a dynamic register /// A place in a constant buffer: byte offset plus a dynamic register
/// offset. /// offset.
cbuf: struct { res: u32, offset: u32 = 0, dyn_regs: ?Value = null, row_major: bool = false }, cbuf: struct { res: u32, offset: u32 = 0, dyn_regs: ?Value = null, row_major: bool = false },
/// A place in a mesh shader output array: the vertex / primitive index
/// and a flattened component offset within it.
mesh: struct { kind: ir.MeshOutput, index: ?Value = null, offset: u32 = 0, ty: TypeId },
/// Struct-typed memory (mesh payloads): the base pointer, its pointee
/// type, the GEP path so far and the HLSL type there.
typed: struct { base: Value, dty: DType, addr_space: u32, ty: TypeId, path: []const Value = &.{} },
/// A place inside a structured buffer element: element index plus byte /// A place inside a structured buffer element: element index plus byte
/// offset (constant and dynamic). /// offset (constant and dynamic).
buf: struct { res: u32, index: Value, offset: u32 = 0, dyn: ?Value = null, row_major: bool = false }, buf: struct { res: u32, index: Value, offset: u32 = 0, dyn: ?Value = null, row_major: bool = false },
@ -118,6 +124,10 @@ const Emitter = struct {
main_fn: u32 = 0, main_fn: u32 = 0,
/// Hull shaders: the patch constant function. /// Hull shaders: the patch constant function.
pc_fn: ?u32 = null, pc_fn: ?u32 = null,
/// Amplification shaders: the variable sent by DispatchMesh (laid out
/// as a struct, not flattened): a groupshared global or a local.
payload_global: ?u32 = null,
payload_local: ?struct { func: *const ir.Function, inst: u32 } = null,
/// Instructions per block, in creation order, with provisional ids. /// Instructions per block, in creation order, with provisional ids.
blocks: std.ArrayList(std.ArrayList(PInst)) = .empty, blocks: std.ArrayList(std.ArrayList(PInst)) = .empty,
prologue: std.ArrayList(PInst) = .empty, prologue: std.ArrayList(PInst) = .empty,
@ -290,7 +300,7 @@ const Emitter = struct {
const m = e.m; const m = e.m;
const entry = m.entry orelse return e.unsupported("no entry point", .{}); const entry = m.entry orelse return e.unsupported("no entry point", .{});
switch (entry.stage) { switch (entry.stage) {
.compute, .vertex, .pixel, .geometry, .hull, .domain => {}, .compute, .vertex, .pixel, .geometry, .hull, .domain, .mesh, .amplification => {},
else => return e.unsupported("{s} shaders are not supported yet", .{@tagName(entry.stage)}), else => return e.unsupported("{s} shaders are not supported yet", .{@tagName(entry.stage)}),
} }
const void_ty = try e.voidTy(); const void_ty = try e.voidTy();
@ -301,6 +311,7 @@ const Emitter = struct {
try e.collectResources(); try e.collectResources();
try e.buildSignatures(entry); try e.buildSignatures(entry);
if (entry.stage == .amplification) e.findDispatchPayload();
e.cur = try e.newBlock(); e.cur = try e.newBlock();
try e.createHandles(); try e.createHandles();
_ = try e.inlineCall(entry.wrapper, &.{}); _ = try e.inlineCall(entry.wrapper, &.{});
@ -756,7 +767,25 @@ const Emitter = struct {
switch (i.op) { switch (i.op) {
.constant => |c| return e.list(&.{try e.constant(i.ty, c)}), .constant => |c| return e.list(&.{try e.constant(i.ty, c)}),
.param => |p| return frame.params[p], .param => |p| return frame.params[p],
.mesh_output => |k| return .{ .mesh = .{ .kind = k, .ty = i.ty } },
.mesh_payload => {
const dty = try e.memoryType(i.ty);
const ptr_ty = try e.dm.ptrType(dty);
const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.getMeshPayload.{s}", .{e.dm.types.items[dty].@"struct".name}), ptr_ty, &.{try e.dm.intType(32)}, .nounwind_readonly);
const base = try e.callOp(fn_i, ptr_ty, &.{try e.i32Const(170)});
return e.typedLoad(.{ .base = base, .dty = dty, .addr_space = 0, .ty = i.ty }, i.ty);
},
.global => |g| { .global => |g| {
if (e.payload_global == g) {
const gop = try e.private_globals.getOrPut(e.arena, g);
if (!gop.found_existing) {
const dty = try e.memoryType(e.m.globals.items[g].ty);
const gv = try e.dm.addGlobal(e.m.globals.items[g].name, dty, 3);
gop.value_ptr.* = .{ .base = gv, .array_ty = dty, .scalar_ty = dty, .addr_space = 3 };
e.groupshared_bytes += try e.payloadSize(e.m.globals.items[g].ty);
}
return .{ .typed = .{ .base = gop.value_ptr.base, .dty = gop.value_ptr.array_ty, .addr_space = 3, .ty = e.m.globals.items[g].ty } };
}
// Static globals live in the entry function (everything is // Static globals live in the entry function (everything is
// inlined into it). // inlined into it).
if (e.m.globals.items[g].space == .private) { if (e.m.globals.items[g].space == .private) {
@ -783,6 +812,11 @@ const Emitter = struct {
return .{ .handle = ri }; return .{ .handle = ri };
}, },
.local_var => { .local_var => {
if (e.payload_local) |pl| if (pl.func == f and pl.inst == r.index()) {
const dty = try e.memoryType(i.ty);
const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } });
return .{ .typed = .{ .base = base, .dty = dty, .addr_space = 0, .ty = i.ty } };
};
if (isResourceType(e.t, i.ty)) { if (isResourceType(e.t, i.ty)) {
try e.res_locals.append(e.arena, null); try e.res_locals.append(e.arena, null);
return .{ .res_local = @intCast(e.res_locals.items.len - 1) }; return .{ .res_local = @intCast(e.res_locals.items.len - 1) };
@ -802,6 +836,8 @@ const Emitter = struct {
.cbuf => |c| return e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, i.ty), .cbuf => |c| return e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, i.ty),
.buf => |b| return .{ .scalars = try e.structuredLoad(e.resources.items[b.res], b.index, b.offset, b.dyn, b.row_major, i.ty) }, .buf => |b| return .{ .scalars = try e.structuredLoad(e.resources.items[b.res], b.index, b.offset, b.dyn, b.row_major, i.ty) },
.ptr => |ptr| return e.loadPtr(ptr, i.ty), .ptr => |ptr| return e.loadPtr(ptr, i.ty),
.typed => |tp| return e.typedLoad(tp, i.ty),
.mesh => return e.unsupported("reading mesh shader outputs is not supported", .{}),
else => return e.unsupported("internal: load from a non-pointer", .{}), else => return e.unsupported("internal: load from a non-pointer", .{}),
}, },
.store => |s| { .store => |s| {
@ -815,6 +851,14 @@ const Emitter = struct {
slot.* = h; slot.* = h;
return .none; return .none;
} }
if (frame.vals[s.ptr.index()] == .mesh) {
try e.meshStore(frame.vals[s.ptr.index()].mesh, try e.scalars(frame, s.value), f.inst(s.value).ty);
return .none;
}
if (frame.vals[s.ptr.index()] == .typed) {
try e.typedStore(frame.vals[s.ptr.index()].typed, try e.scalars(frame, s.value), f.inst(s.value).ty);
return .none;
}
if (frame.vals[s.ptr.index()] == .buf) { if (frame.vals[s.ptr.index()] == .buf) {
const b = frame.vals[s.ptr.index()].buf; const b = frame.vals[s.ptr.index()].buf;
try e.structuredStore(e.resources.items[b.res], b.index, b.offset, b.dyn, b.row_major, f.inst(s.value).ty, try e.scalars(frame, s.value)); try e.structuredStore(e.resources.items[b.res], b.index, b.offset, b.dyn, b.row_major, f.inst(s.value).ty, try e.scalars(frame, s.value));
@ -828,6 +872,24 @@ const Emitter = struct {
return .none; return .none;
}, },
.access => |a| { .access => |a| {
if (frame.vals[a.base.index()] == .mesh) return e.meshAccess(frame, frame.vals[a.base.index()].mesh, a.indices);
if (frame.vals[a.base.index()] == .typed) {
var tp = frame.vals[a.base.index()].typed;
var path: std.ArrayList(Value) = .empty;
try path.appendSlice(e.arena, tp.path);
for (a.indices) |x| {
try path.append(e.arena, (try e.scalars(frame, x))[0]);
tp.ty = switch (e.t.get(tp.ty)) {
.@"struct" => |st| st.fields.items[@intCast(f.inst(x).op.constant.int)].type,
.array => |arr| arr.elem,
.vector => |v| try e.t.scalar(v.elem),
.matrix => |mt| try e.t.vector(mt.elem, mt.cols),
else => return e.unsupported("indexing this payload member is not supported yet", .{}),
};
}
tp.path = path.items;
return .{ .typed = tp };
}
if (frame.vals[a.base.index()] == .res_array) return e.arrayElement(frame, frame.vals[a.base.index()].res_array, a.indices); if (frame.vals[a.base.index()] == .res_array) return e.arrayElement(frame, frame.vals[a.base.index()].res_array, a.indices);
if (frame.vals[a.base.index()] == .cbuf) return e.cbufferAccess(frame, frame.vals[a.base.index()].cbuf, f.inst(a.base).ty, a.indices); if (frame.vals[a.base.index()] == .cbuf) return e.cbufferAccess(frame, frame.vals[a.base.index()].cbuf, f.inst(a.base).ty, a.indices);
if (frame.vals[a.base.index()] == .handle) { if (frame.vals[a.base.index()] == .handle) {
@ -1197,6 +1259,32 @@ const Emitter = struct {
fn intrinsic(e: *Emitter, frame: *Frame, name: []const u8, ty: TypeId, args: []const Ref) Error!Lowered { fn intrinsic(e: *Emitter, frame: *Frame, name: []const u8, ty: TypeId, args: []const Ref) Error!Lowered {
const eq = std.mem.eql; const eq = std.mem.eql;
if (try e.outIntrinsic(frame, name, ty, args)) |r| return r; if (try e.outIntrinsic(frame, name, ty, args)) |r| return r;
if (eq(u8, name, "DispatchMesh")) {
const tp = switch (frame.vals[args[3].index()]) {
.typed => |x| x,
else => return e.unsupported("DispatchMesh with this payload is not supported yet", .{}),
};
const i32t = try e.dm.intType(32);
// A member of a variable: a pointer to it.
const dty = if (tp.path.len > 0) try e.memoryType(tp.ty) else tp.dty;
if (e.dm.types.items[dty] != .@"struct") return e.unsupported("DispatchMesh payloads must be structs", .{});
const pt = try e.dm.getType(.{ .pointer = .{ .elem = dty, .addr_space = tp.addr_space } });
const ptr = if (tp.path.len == 0) tp.base else blk: {
const idx = try e.arena.alloc(Value, tp.path.len + 1);
idx[0] = try e.i32Const(0);
@memcpy(idx[1..], tp.path);
break :blk try e.add(pt, .{ .gep = .{ .elem = tp.dty, .ptr = tp.base, .indices = idx } });
};
const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.dispatchMesh.{s}", .{e.dm.types.items[dty].@"struct".name}), try e.voidTy(), &.{ i32t, i32t, i32t, i32t, pt }, .nounwind);
_ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(173), (try e.scalars(frame, args[0]))[0], (try e.scalars(frame, args[1]))[0], (try e.scalars(frame, args[2]))[0], ptr });
return .none;
}
if (eq(u8, name, "SetMeshOutputCounts")) {
const i32t = try e.dm.intType(32);
const fn_i = try e.dxOp("dx.op.setMeshOutputCounts", try e.voidTy(), &.{ i32t, i32t, i32t }, .nounwind);
_ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(168), (try e.scalars(frame, args[0]))[0], (try e.scalars(frame, args[1]))[0] });
return .none;
}
for (args) |x| if (frame.vals[x.index()] != .scalars) return e.unsupported("intrinsic '{s}' is not supported yet", .{name}); for (args) |x| if (frame.vals[x.index()] != .scalars) return e.unsupported("intrinsic '{s}' is not supported yet", .{name});
var a: [4][]const Value = undefined; var a: [4][]const Value = undefined;
for (args, 0..) |x, k| a[k] = try e.scalars(frame, x); for (args, 0..) |x, k| a[k] = try e.scalars(frame, x);
@ -2459,6 +2547,7 @@ const Emitter = struct {
.geometry => .{ .gs_v_in, .gs_out, null }, .geometry => .{ .gs_v_in, .gs_out, null },
.hull => .{ .hs_cp_in, .hs_cp_out, .pc_out }, .hull => .{ .hs_cp_in, .hs_cp_out, .pc_out },
.domain => .{ .ds_cp_in, .ds_out, .ds_in }, .domain => .{ .ds_cp_in, .ds_out, .ds_in },
.mesh => .{ null, .ms_out, .ms_p_out },
else => .{ null, null, null }, else => .{ null, null, null },
}; };
e.in_elem = try e.arena.alloc(?u32, entry.inputs.items.len); e.in_elem = try e.arena.alloc(?u32, entry.inputs.items.len);
@ -2540,6 +2629,7 @@ const Emitter = struct {
/// interpolates with perspective. /// interpolates with perspective.
fn interpMode(q: types.Interp, sp: signature.SigPoint, comp: signature.CompType, kind: signature.SemanticKind) signature.InterpMode { fn interpMode(q: types.Interp, sp: signature.SigPoint, comp: signature.CompType, kind: signature.SemanticKind) signature.InterpMode {
if (sp == .vs_in or sp == .ps_out or sp == .gs_in or sp == .pc_out or sp == .ds_in) return .undefined; if (sp == .vs_in or sp == .ps_out or sp == .gs_in or sp == .pc_out or sp == .ds_in) return .undefined;
if (sp == .ms_p_out) return .constant; // per primitive: never interpolated
var m: signature.InterpMode = if (q.nointerpolation) var m: signature.InterpMode = if (q.nointerpolation)
.constant .constant
else if (q.sample) else if (q.sample)
@ -2670,7 +2760,7 @@ const Emitter = struct {
fn inputAt(e: *Emitter, k: u32, ty: TypeId, vertex: ?u32) Error!Lowered { fn inputAt(e: *Emitter, k: u32, ty: TypeId, vertex: ?u32) Error!Lowered {
const entry = e.m.entry.?; const entry = e.m.entry.?;
if (entry.stage == .compute) return e.computeInput(k, ty); if (entry.stage == .compute or entry.stage == .mesh or entry.stage == .amplification) return e.computeInput(k, ty);
const el = entry.inputs.items[k]; const el = entry.inputs.items[k];
const se = if (e.in_elem[k]) |ei| &e.sig_in[ei] else return e.systemValueInput(el.semantic, ty); const se = if (e.in_elem[k]) |ei| &e.sig_in[ei] else return e.systemValueInput(el.semantic, ty);
if (se.interpretation == .shadow) return e.systemValueInput(el.semantic, ty); if (se.interpretation == .shadow) return e.systemValueInput(el.semantic, ty);
@ -2774,6 +2864,210 @@ const Emitter = struct {
return .{ .scalars = out }; return .{ .scalars = out };
} }
/// The groupshared variable an amplification shader passes to
/// DispatchMesh.
fn findDispatchPayload(e: *Emitter) void {
for (e.m.functions.items) |f| for (f.insts.items) |inst| switch (inst.op) {
.intrinsic => |it| if (std.mem.eql(u8, it.name, "DispatchMesh") and it.args.len == 4) {
var x = it.args[3];
while (true) switch (f.inst(x).op) {
.global => |g| {
e.payload_global = g;
return;
},
.local_var => {
e.payload_local = .{ .func = f, .inst = x.index() };
return;
},
.access => |a| x = a.base,
else => break,
};
},
else => {},
};
}
/// The memory type of an HLSL value in struct-typed memory: vectors
/// and matrices (by row) become arrays, bools 32-bit integers.
fn memoryType(e: *Emitter, ty: TypeId) Error!DType {
return switch (e.t.get(ty)) {
.scalar, .@"enum" => e.scalarTy(storageScalar(e.compOf(ty))),
.vector => |v| e.dm.getType(.{ .array = .{ .len = v.len, .elem = try e.scalarTy(storageScalar(e.compOf(ty))) } }),
.matrix => |m| e.dm.getType(.{ .array = .{ .len = m.rows, .elem = try e.dm.getType(.{ .array = .{ .len = m.cols, .elem = try e.scalarTy(storageScalar(e.compOf(ty))) } }) } }),
.array => |a| e.dm.getType(.{ .array = .{ .len = a.len, .elem = try e.memoryType(a.elem) } }),
.@"struct" => |st| blk: {
const elems = try e.arena.alloc(DType, st.fields.items.len);
for (elems, st.fields.items) |*x, fld| x.* = try e.memoryType(fld.type);
break :blk e.dm.getType(.{ .@"struct" = .{ .name = try std.fmt.allocPrint(e.arena, "struct.{s}", .{st.name}), .elems = elems } });
},
else => e.unsupported("payloads of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
};
}
/// The byte size of a payload (its memory type's allocation size).
fn payloadSize(e: *Emitter, ty: TypeId) Error!u32 {
return (try e.memLayout(ty))[0];
}
/// Size and alignment of `ty`'s memory type.
fn memLayout(e: *Emitter, ty: TypeId) Error![2]u32 {
switch (e.t.get(ty)) {
.scalar, .@"enum", .vector, .matrix => {
const sz = storageScalar(e.compOf(ty)).size();
return .{ sz * (e.t.componentCount(ty) orelse 1), sz };
},
.array => |a| {
const el = try e.memLayout(a.elem);
return .{ el[0] * a.len, el[1] };
},
.@"struct" => |st| {
var off: u32 = 0;
var al: u32 = 1;
for (st.fields.items) |fld| {
const fl = try e.memLayout(fld.type);
off = std.mem.alignForward(u32, off, fl[1]) + fl[0];
al = @max(al, fl[1]);
}
return .{ std.mem.alignForward(u32, off, al), al };
},
else => return e.unsupported("payloads of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
}
}
/// GEP paths to the scalars of a value of `ty`, in flattened order.
fn scalarPaths(e: *Emitter, ty: TypeId, prefix: []const Value, out: *std.ArrayList([]const Value)) Error!void {
const sub = struct {
fn f(em: *Emitter, p: []const Value, k: u32) Error![]const Value {
const r = try em.arena.alloc(Value, p.len + 1);
@memcpy(r[0..p.len], p);
r[p.len] = try em.i32Const(k);
return r;
}
}.f;
switch (e.t.get(ty)) {
.scalar, .@"enum" => try out.append(e.arena, prefix),
.vector => |v| for (0..v.len) |k| try out.append(e.arena, try sub(e, prefix, @intCast(k))),
.matrix => |m| for (0..m.rows) |r| {
const rp = try sub(e, prefix, @intCast(r));
for (0..m.cols) |c| try out.append(e.arena, try sub(e, rp, @intCast(c)));
},
.array => |a| for (0..a.len) |k| try e.scalarPaths(a.elem, try sub(e, prefix, @intCast(k)), out),
.@"struct" => |st| for (st.fields.items, 0..) |fld, k| try e.scalarPaths(fld.type, try sub(e, prefix, @intCast(k)), out),
else => return e.unsupported("payloads of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
}
}
fn typedScalarPtr(e: *Emitter, tp: @FieldType(Lowered, "typed"), sub: []const Value, st: DType) Error!Value {
const idx = try e.arena.alloc(Value, 1 + tp.path.len + sub.len);
idx[0] = try e.i32Const(0);
@memcpy(idx[1..][0..tp.path.len], tp.path);
@memcpy(idx[1 + tp.path.len ..], sub);
const pt = try e.dm.getType(.{ .pointer = .{ .elem = st, .addr_space = tp.addr_space } });
return e.add(pt, .{ .gep = .{ .elem = tp.dty, .ptr = tp.base, .indices = idx } });
}
fn typedLoad(e: *Emitter, tp: @FieldType(Lowered, "typed"), ty: TypeId) Error!Lowered {
var paths: std.ArrayList([]const Value) = .empty;
try e.scalarPaths(ty, &.{}, &paths);
const out = try e.arena.alloc(Value, paths.items.len);
for (out, paths.items, 0..) |*o, sub, c| {
const ct = e.compOf(try e.componentType(ty, @intCast(c)));
const st = try e.scalarTy(storageScalar(ct));
const raw = try e.add(st, .{ .load = .{ .ptr = try e.typedScalarPtr(tp, sub, st), .@"align" = 4 } });
o.* = if (ct == .bool) try e.add(try e.dm.intType(1), .{ .cmp = .{ .pred = 33, .lhs = raw, .rhs = try e.i32Const(0) } }) else raw;
}
return .{ .scalars = out };
}
fn typedStore(e: *Emitter, tp: @FieldType(Lowered, "typed"), vals: []const Value, ty: TypeId) Error!void {
var paths: std.ArrayList([]const Value) = .empty;
try e.scalarPaths(ty, &.{}, &paths);
for (vals, paths.items, 0..) |v, sub, c| {
const ct = e.compOf(try e.componentType(ty, @intCast(c)));
const st = try e.scalarTy(storageScalar(ct));
const sv = if (ct == .bool) try e.add(st, .{ .cast = .{ .op = .zext, .val = v } }) else v;
_ = try e.add(try e.voidTy(), .{ .store = .{ .ptr = try e.typedScalarPtr(tp, sub, st), .val = sv, .@"align" = 4 } });
}
}
/// Indexes into a mesh output array: the first index picks the vertex
/// or primitive, the rest a part of it (constant indices only).
fn meshAccess(e: *Emitter, frame: *Frame, start: @FieldType(Lowered, "mesh"), indices: []const Ref) Error!Lowered {
var m = start;
for (indices) |x| {
if (m.index == null) {
m.index = (try e.scalars(frame, x))[0];
m.ty = e.t.get(m.ty).array.elem;
continue;
}
const k: u32 = switch (frame.f.inst(x).op) {
.constant => |c| @intCast(c.int),
else => return e.unsupported("dynamic indexing inside a mesh output is not supported yet", .{}),
};
switch (e.t.get(m.ty)) {
.@"struct" => |st| {
for (st.fields.items[0..k]) |fld| m.offset += try e.flatCount(fld.type);
m.ty = st.fields.items[k].type;
},
.array => |arr| {
m.offset += k * try e.flatCount(arr.elem);
m.ty = arr.elem;
},
.vector => |v| {
m.offset += k;
m.ty = try e.t.scalar(v.elem);
},
.matrix => |mt| {
m.offset += k * mt.cols;
m.ty = try e.t.vector(mt.elem, mt.cols);
},
else => return e.unsupported("indexing this mesh output is not supported yet", .{}),
}
}
return .{ .mesh = m };
}
/// Writes components [offset, offset + n) of a vertex or primitive, or
/// a primitive's indices.
fn meshStore(e: *Emitter, m: @FieldType(Lowered, "mesh"), vals: []const Value, ty: TypeId) Error!void {
const index = m.index orelse return e.unsupported("storing a whole mesh output array is not supported yet", .{});
const i32t = try e.dm.intType(32);
const void_ty = try e.voidTy();
if (m.kind == .indices) {
if (m.offset != 0 or vals.len < 2) return e.unsupported("writing part of a primitive's indices is not supported yet", .{});
const fn_i = try e.dxOp("dx.op.emitIndices", void_ty, &.{ i32t, i32t, i32t, i32t, i32t }, .nounwind);
const v2 = if (vals.len > 2) vals[2] else try e.dm.constant(.{ .ty = i32t, .kind = .undef });
_ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(169), index, vals[0], vals[1], v2 });
return;
}
const entry = e.m.entry.?;
const els = if (m.kind == .vertices) entry.outputs.items else entry.patch_constants.items;
const map = if (m.kind == .vertices) e.out_elem else e.pc_elem;
const sig = if (m.kind == .vertices) e.sig_out else e.sig_pc;
const op: i64 = if (m.kind == .vertices) 171 else 172;
const op_name = if (m.kind == .vertices) "storeVertexOutput" else "storePrimitiveOutput";
for (vals, 0..) |v, c| {
// Which element (leaf) and which of its components.
var flat = m.offset + @as(u32, @intCast(c));
var k: usize = 0;
while (k < els.len) : (k += 1) {
const n = try e.flatCount(els[k].ty);
if (flat < n) break;
flat -= n;
}
if (k == els.len) return e.unsupported("internal: mesh output component out of range", .{});
const el = els[k];
const se = if (map[k]) |ei| &sig[ei] else return e.unsupported("mesh output '{s}' is not supported yet", .{el.semantic});
const via = sigScalar(se.comp);
const vt = try e.scalarTy(via);
const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.{s}.{s}", .{ op_name, e.overloadName(vt) }), void_ty, &.{ i32t, i32t, i32t, try e.dm.intType(8), vt, i32t }, .nounwind);
const rc = try e.sigComponent(el.ty, el.row_major, flat);
const from = e.compOf(try e.componentType(ty, @intCast(c)));
_ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(op), try e.i32Const(se.id), try e.i32Const(rc[0]), try e.dm.constInt(8, rc[1]), try e.convertScalar(v, from, via), index });
se.usage |= @as(u8, 1) << @intCast(rc[1]);
}
}
fn computeInput(e: *Emitter, k: u32, ty: TypeId) Error!Lowered { fn computeInput(e: *Emitter, k: u32, ty: TypeId) Error!Lowered {
const el = e.m.entry.?.inputs.items[k]; const el = e.m.entry.?.inputs.items[k];
const eqi = std.ascii.eqlIgnoreCase; const eqi = std.ascii.eqlIgnoreCase;
@ -2800,7 +3094,7 @@ const Emitter = struct {
for (out) |*o| o.* = try e.convertScalar(v, .uint, e.compOf(ty)); for (out) |*o| o.* = try e.convertScalar(v, .uint, e.compOf(ty));
return .{ .scalars = out }; return .{ .scalars = out };
} }
return e.unsupported("input '{s}' is not supported yet", .{el.semantic}); return e.systemValueInput(el.semantic, ty);
} }
// ------------------------------------------------------------------ // ------------------------------------------------------------------
@ -2946,9 +3240,19 @@ const Emitter = struct {
const i64t = try dm.intType(64); const i64t = try dm.intType(64);
try props.appendSlice(e.arena, &.{ try mdI32(dm, 0), try dm.mdValue(i64t, try dm.constant(.{ .ty = i64t, .kind = .{ .int = @bitCast(flags) } })) }); try props.appendSlice(e.arena, &.{ try mdI32(dm, 0), try dm.mdValue(i64t, try dm.constant(.{ .ty = i64t, .kind = .{ .int = @bitCast(flags) } })) });
} }
if (entry.stage == .compute) {
const threads = try dm.mdNode(&.{ try mdI32(dm, entry.num_threads[0]), try mdI32(dm, entry.num_threads[1]), try mdI32(dm, entry.num_threads[2]) }); const threads = try dm.mdNode(&.{ try mdI32(dm, entry.num_threads[0]), try mdI32(dm, entry.num_threads[1]), try mdI32(dm, entry.num_threads[2]) });
try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads }); if (entry.stage == .compute) try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads });
const payload_size: u32 = if (entry.mesh.payload) |p| try e.payloadSize(p) else 0;
if (entry.stage == .mesh) {
// MS state: thread group, max vertices, max primitives,
// topology, payload size.
const ms = entry.mesh;
const state = try dm.mdNode(&.{ threads, try mdI32(dm, ms.max_vertices), try mdI32(dm, ms.max_primitives), try mdI32(dm, @intFromEnum(ms.topology)), try mdI32(dm, payload_size) });
try props.appendSlice(e.arena, &.{ try mdI32(dm, 9), state });
}
if (entry.stage == .amplification) {
const state = try dm.mdNode(&.{ threads, try mdI32(dm, payload_size) });
try props.appendSlice(e.arena, &.{ try mdI32(dm, 10), state });
} }
if (entry.stage == .geometry) { if (entry.stage == .geometry) {
// GS state: input primitive, max vertex count, stream mask, // GS state: input primitive, max vertex count, stream mask,
@ -3084,24 +3388,37 @@ const Emitter = struct {
} }
std.mem.writeInt(u32, stage_info[8..12], @intFromEnum(entry.tess.domain), .little); std.mem.writeInt(u32, stage_info[8..12], @intFromEnum(entry.tess.domain), .little);
} }
const payload_size: u32 = if (entry.mesh.payload) |p| try e.payloadSize(p) else 0;
if (entry.stage == .mesh) {
std.mem.writeInt(u32, stage_info[0..4], e.groupshared_bytes, .little);
std.mem.writeInt(u32, stage_info[8..12], payload_size, .little);
std.mem.writeInt(u16, stage_info[12..14], @intCast(entry.mesh.max_vertices), .little);
std.mem.writeInt(u16, stage_info[14..16], @intCast(entry.mesh.max_primitives), .little);
}
if (entry.stage == .amplification) std.mem.writeInt(u32, stage_info[0..4], payload_size, .little);
const kind: shader.ShaderKind = switch (entry.stage) { const kind: shader.ShaderKind = switch (entry.stage) {
.vertex => .vertex, .vertex => .vertex,
.pixel => .pixel, .pixel => .pixel,
.geometry => .geometry, .geometry => .geometry,
.hull => .hull, .hull => .hull,
.domain => .domain, .domain => .domain,
.mesh => .mesh,
.amplification => .amplification,
else => .compute, else => .compute,
}; };
const threaded = entry.stage == .compute or entry.stage == .mesh or entry.stage == .amplification;
const psv = try shader.psv(gpa, .{ const psv = try shader.psv(gpa, .{
.kind = kind, .kind = kind,
.entry = entry.name, .entry = entry.name,
.stage_info = stage_info, .stage_info = stage_info,
.num_threads = if (entry.stage == .compute) entry.num_threads else .{ 0, 0, 0 }, .num_threads = if (threaded) entry.num_threads else .{ 0, 0, 0 },
.mesh_topology = if (entry.stage == .mesh) @intFromEnum(entry.mesh.topology) else 0,
.uses_view_id = e.uses_view_id,
.resources = binds.items, .resources = binds.items,
.inputs = e.sig_in, .inputs = e.sig_in,
.outputs = e.sig_out, .outputs = e.sig_out,
.patch_constants = e.sig_pc, .patch_constants = e.sig_pc,
.groupshared_bytes = if (entry.stage == .compute) e.groupshared_bytes else 0, .groupshared_bytes = if (threaded) e.groupshared_bytes else 0,
.max_vertex_count = if (entry.stage == .geometry) @intCast(entry.geometry.max_vertex_count) else 0, .max_vertex_count = if (entry.stage == .geometry) @intCast(entry.geometry.max_vertex_count) else 0,
}); });
defer gpa.free(psv); defer gpa.free(psv);
@ -3120,7 +3437,7 @@ const Emitter = struct {
.{ .fourcc = container.fourcc("ISG1"), .data = isg1 }, .{ .fourcc = container.fourcc("ISG1"), .data = isg1 },
.{ .fourcc = container.fourcc("OSG1"), .data = osg1 }, .{ .fourcc = container.fourcc("OSG1"), .data = osg1 },
}); });
if (entry.stage == .hull or entry.stage == .domain) try parts.append(e.arena, .{ .fourcc = container.fourcc("PSG1"), .data = psg1 }); if (entry.stage == .hull or entry.stage == .domain or entry.stage == .mesh) try parts.append(e.arena, .{ .fourcc = container.fourcc("PSG1"), .data = psg1 });
try parts.appendSlice(e.arena, &.{ try parts.appendSlice(e.arena, &.{
.{ .fourcc = container.fourcc("PSV0"), .data = psv }, .{ .fourcc = container.fourcc("PSV0"), .data = psv },
.{ .fourcc = container.fourcc("DXIL"), .data = dxil_part }, .{ .fourcc = container.fourcc("DXIL"), .data = dxil_part },

View File

@ -148,6 +148,8 @@ pub const PsvInfo = struct {
patch_constants: []const signature.Element = &.{}, patch_constants: []const signature.Element = &.{},
groupshared_bytes: u32 = 0, groupshared_bytes: u32 = 0,
max_vertex_count: u16 = 0, max_vertex_count: u16 = 0,
mesh_topology: u8 = 0,
uses_view_id: bool = false,
}; };
pub fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32, resources: []const ResourceBind) ![]u8 { pub fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32, resources: []const ResourceBind) ![]u8 {
@ -173,8 +175,13 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
// vector counts. // vector counts.
// (The MaxVertexCount union holds SigPatchConstOrPrimVectors for hull // (The MaxVertexCount union holds SigPatchConstOrPrimVectors for hull
// and domain shaders.) // and domain shaders.)
const union16: u16 = if (info.kind == .hull or info.kind == .domain) @intCast(pc_vectors) else info.max_vertex_count; // (Mesh shaders: SigPrimVectors and MeshOutputTopology.)
try buf.appendSlice(gpa, &.{ @backingInt(info.kind), 0, @truncate(union16), @truncate(union16 >> 8) }); const union16: u16 = switch (info.kind) {
.hull, .domain => @intCast(pc_vectors),
.mesh => @as(u16, @intCast(pc_vectors)) | (@as(u16, info.mesh_topology) << 8),
else => info.max_vertex_count,
};
try buf.appendSlice(gpa, &.{ @backingInt(info.kind), @intFromBool(info.uses_view_id), @truncate(union16), @truncate(union16 >> 8) });
try buf.appendSlice(gpa, &.{ @intCast(info.inputs.len), @intCast(info.outputs.len), @intCast(info.patch_constants.len), @intCast(in_vectors) }); try buf.appendSlice(gpa, &.{ @intCast(info.inputs.len), @intCast(info.outputs.len), @intCast(info.patch_constants.len), @intCast(in_vectors) });
for (out_vectors) |v| try buf.append(gpa, @intCast(v)); for (out_vectors) |v| try buf.append(gpa, @intCast(v));
// PSVRuntimeInfo2 // PSVRuntimeInfo2
@ -237,12 +244,21 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
try w(&buf, gpa, 16); // sizeof(PSVSignatureElement0) try w(&buf, gpa, 16); // sizeof(PSVSignatureElement0)
try buf.appendSlice(gpa, records.items); try buf.appendSlice(gpa, records.items);
} }
// Outputs depending on the ViewID (left empty, like the dependency
// tables below).
if (info.uses_view_id) {
for (out_vectors, 0..) |ov, stream| {
if (stream > 0 and info.kind != .geometry) break;
if (ov > 0) try buf.appendNTimes(gpa, 0, ((ov + 7) >> 3) * 4);
}
if ((info.kind == .hull or info.kind == .mesh) and pc_vectors > 0) try buf.appendNTimes(gpa, 0, ((pc_vectors + 7) >> 3) * 4);
}
// Input-to-output dependency table (no ViewID). Left empty: the // Input-to-output dependency table (no ViewID). Left empty: the
// validator only checks it against dx.viewIdState, which zdxc omits. // validator only checks it against dx.viewIdState, which zdxc omits.
// (One per output stream for geometry shaders.) // (One per output stream for geometry shaders.)
for (out_vectors, 0..) |ov, stream| { for (out_vectors, 0..) |ov, stream| {
if (stream > 0 and info.kind != .geometry) break; if (stream > 0 and info.kind != .geometry) break;
if (in_vectors > 0 and ov > 0) try buf.appendNTimes(gpa, 0, tableDwords(in_vectors, ov) * 4); if (info.kind != .mesh and in_vectors > 0 and ov > 0) try buf.appendNTimes(gpa, 0, tableDwords(in_vectors, ov) * 4);
} }
// Inputs to patch constants (hull), patch constants to outputs // Inputs to patch constants (hull), patch constants to outputs
// (domain). // (domain).

View File

@ -38,7 +38,7 @@ pub const BlockId = enum(u32) {
}; };
/// Where a pointer points. /// Where a pointer points.
pub const Space = enum { none, function, private, groupshared, resource, input, output, cbuffer }; pub const Space = enum { none, function, private, groupshared, resource, input, output, cbuffer, mesh };
pub const BinaryOp = enum { pub const BinaryOp = enum {
add, add,
@ -114,6 +114,11 @@ pub const Op = union(enum) {
/// (hull patch constant function), and a hull output control point /// (hull patch constant function), and a hull output control point
/// read back by the patch constant function. /// read back by the patch constant function.
patch_input: u32, patch_input: u32,
/// Mesh shaders: an output array (a pointer in the `mesh` space; stores
/// through it write vertices, primitives or indices), and the payload
/// from the amplification shader.
mesh_output: MeshOutput,
mesh_payload,
patch_output: struct { element: u32, value: Ref }, patch_output: struct { element: u32, value: Ref },
output_vertex: struct { element: u32, vertex: u32 }, output_vertex: struct { element: u32, vertex: u32 },
/// Geometry shaders: emit the vertex written to the outputs of a stream, /// Geometry shaders: emit the vertex written to the outputs of a stream,
@ -197,7 +202,7 @@ pub const Global = struct {
binding: Binding = .{}, binding: Binding = .{},
}; };
pub const Stage = enum { vertex, pixel, geometry, hull, domain, compute, library }; pub const Stage = enum { vertex, pixel, geometry, hull, domain, compute, mesh, amplification, library };
/// One entry-point input or output (a semantic on a parameter, field or /// One entry-point input or output (a semantic on a parameter, field or
/// the return value). /// the return value).
@ -231,6 +236,18 @@ pub const Domain = enum(u8) { isoline = 1, tri = 2, quad = 3 };
pub const Partitioning = enum(u8) { integer = 1, pow2 = 2, fractional_odd = 3, fractional_even = 4 }; pub const Partitioning = enum(u8) { integer = 1, pow2 = 2, fractional_odd = 3, fractional_even = 4 };
pub const OutputTopology = enum(u8) { point = 1, line = 2, triangle_cw = 3, triangle_ccw = 4 }; pub const OutputTopology = enum(u8) { point = 1, line = 2, triangle_cw = 3, triangle_ccw = 4 };
pub const MeshOutput = enum { vertices, primitives, indices };
pub const MeshInfo = struct {
max_vertices: u32 = 0,
max_primitives: u32 = 0,
/// DXIL::MeshOutputTopology.
topology: enum(u8) { line = 1, triangle = 2 } = .triangle,
/// The payload struct (read by a mesh shader, sent by an amplification
/// shader's DispatchMesh).
payload: ?TypeId = null,
};
pub const TessInfo = struct { pub const TessInfo = struct {
domain: Domain = .tri, domain: Domain = .tri,
partitioning: Partitioning = .integer, partitioning: Partitioning = .integer,
@ -250,6 +267,7 @@ pub const Entry = struct {
num_threads: [3]u32 = .{ 1, 1, 1 }, num_threads: [3]u32 = .{ 1, 1, 1 },
geometry: GeometryInfo = .{}, geometry: GeometryInfo = .{},
tess: TessInfo = .{}, tess: TessInfo = .{},
mesh: MeshInfo = .{},
inputs: std.ArrayList(SigElement) = .empty, inputs: std.ArrayList(SigElement) = .empty,
outputs: std.ArrayList(SigElement) = .empty, outputs: std.ArrayList(SigElement) = .empty,
/// Patch constants: written by the hull shader's patch constant /// Patch constants: written by the hull shader's patch constant
@ -422,6 +440,8 @@ fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !vo
.input_vertex => |x| try w.print("input {d} vertex {d}", .{ x.element, x.vertex }), .input_vertex => |x| try w.print("input {d} vertex {d}", .{ x.element, x.vertex }),
.emit => |k| try w.print("emit stream {d}", .{k}), .emit => |k| try w.print("emit stream {d}", .{k}),
.patch_input => |k| try w.print("patch input {d}", .{k}), .patch_input => |k| try w.print("patch input {d}", .{k}),
.mesh_output => |k| try w.print("mesh output {s}", .{@tagName(k)}),
.mesh_payload => try w.print("mesh payload", .{}),
.patch_output => |x| try w.print("patch output {d} = %{d}", .{ x.element, x.value.index() }), .patch_output => |x| try w.print("patch output {d} = %{d}", .{ x.element, x.value.index() }),
.output_vertex => |x| try w.print("output {d} vertex {d}", .{ x.element, x.vertex }), .output_vertex => |x| try w.print("output {d} vertex {d}", .{ x.element, x.vertex }),
.cut => |k| try w.print("cut stream {d}", .{k}), .cut => |k| try w.print("cut stream {d}", .{k}),

View File

@ -74,6 +74,8 @@ const Lowerer = struct {
patch_io: bool = false, patch_io: bool = false,
/// Per-vertex reads come from the hull shader's output control points. /// Per-vertex reads come from the hull shader's output control points.
vertex_from_outputs: bool = false, vertex_from_outputs: bool = false,
/// The payload type an amplification shader dispatches.
mesh_payload: ?TypeId = null,
/// The current method's object pointer. /// The current method's object pointer.
this_ptr: Ref = .none, this_ptr: Ref = .none,
ret_ty: TypeId = TypeTable.void_type, ret_ty: TypeId = TypeTable.void_type,
@ -141,7 +143,9 @@ const Lowerer = struct {
for (f.params, 0..) |p, i| { for (f.params, 0..) |p, i| {
if (l.s.types.get(p.type) == .stream) continue; if (l.s.types.get(p.type) == .stream) continue;
const pty = l.irType(p.type); const pty = l.irType(p.type);
const pv = try l.b.add(.{ .op = .{ .param = ir_index }, .ty = pty, .ptr = if (p.dir != .in) .function else .none }); const mq = if (i < f.decl.params.len) f.decl.params[i].quals else ast.Qualifiers{};
const space: ir.Space = if (mq.vertices or mq.indices or mq.primitives) .mesh else if (p.dir != .in) .function else .none;
const pv = try l.b.add(.{ .op = .{ .param = ir_index }, .ty = pty, .ptr = space });
ir_index += 1; ir_index += 1;
const storage = if (p.dir != .in) pv else blk: { const storage = if (p.dir != .in) pv else blk: {
const local = try l.b.add(.{ .op = .local_var, .ty = pty, .ptr = .function }); const local = try l.b.add(.{ .op = .local_var, .ty = pty, .ptr = .function });
@ -1073,6 +1077,15 @@ const Lowerer = struct {
}; };
return result; return result;
} }
if (std.mem.eql(u8, name, "DispatchMesh") and args.len == 4) {
// The payload goes by reference (a groupshared
// variable).
const vals = try l.arena.alloc(Ref, 4);
for (vals[0..3], args[0..3]) |*v, a| v.* = try l.converted(a, try l.types().scalar(.uint));
vals[3] = try l.lvalue(args[3]);
l.mesh_payload = args[3].ty;
return l.b.add(.{ .op = .{ .intrinsic = .{ .name = name, .args = vals } }, .ty = TypeTable.void_type });
}
// `out` parameters go through temporaries copied back // `out` parameters go through temporaries copied back
// afterwards; `ref` ones (atomic destinations) pass the // afterwards; `ref` ones (atomic destinations) pass the
// storage itself. // storage itself.
@ -1163,6 +1176,22 @@ const Lowerer = struct {
} }
} }
/// Whether `e` designates part of a mesh shader output array.
fn isMeshOutput(l: *Lowerer, e: *const ast.Expr) bool {
var x = e;
while (true) switch (x.kind) {
.member => |m| x = m.base,
.index => |ix| x = ix.base,
.name => {
const r = l.s.resolution(x) orelse return false;
if (r != .variable) return false;
const p = l.vars.get(r.variable) orelse return false;
return l.b.f.inst(p).ptr == .mesh;
},
else => return false,
};
}
/// Pointer to the storage field holding bitfield `bf` of the struct /// Pointer to the storage field holding bitfield `bf` of the struct
/// `ptr` points to. /// `ptr` points to.
fn bitStorage(l: *Lowerer, ptr: Ref, bf: Bitfield) Error!Ref { fn bitStorage(l: *Lowerer, ptr: Ref, bf: Bitfield) Error!Ref {
@ -1253,6 +1282,17 @@ const Lowerer = struct {
// Swizzle store: read, replace the named components, write. // Swizzle store: read, replace the named components, write.
const comps = (try swizzleComponents(l.arena, m.name)) orelse return error.Unsupported; const comps = (try swizzleComponents(l.arena, m.name)) orelse return error.Unsupported;
if (t.get(m.base.ty) == .scalar) return l.storeTo(m.base, value); if (t.get(m.base.ty) == .scalar) return l.storeTo(m.base, value);
if (l.isMeshOutput(m.base)) {
// Outputs cannot be read back: store each component.
const base_ptr = try l.lvalue(m.base);
const ec = try t.scalar(t.component(m.base.ty).?);
for (comps, 0..) |c, i| {
const part = if (comps.len == 1) value else try l.b.add(.{ .op = .{ .extract = .{ .agg = value, .index = @intCast(i) } }, .ty = ec });
const idx = try l.b.constInt(try t.scalar(.uint), c);
try l.b.store(try l.b.add(.{ .op = .{ .access = .{ .base = base_ptr, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = ec, .ptr = .mesh }), part);
}
return;
}
var whole = try l.rvalue(m.base); var whole = try l.rvalue(m.base);
const ec = try t.scalar(t.component(m.base.ty).?); const ec = try t.scalar(t.component(m.base.ty).?);
for (comps, 0..) |c, i| { for (comps, 0..) |c, i| {
@ -1701,6 +1741,12 @@ const Lowerer = struct {
const args = try l.arena.alloc(Ref, f.params.len); const args = try l.arena.alloc(Ref, f.params.len);
const locals = try l.arena.alloc(Ref, f.params.len); const locals = try l.arena.alloc(Ref, f.params.len);
var n_args: usize = 0; var n_args: usize = 0;
if (opts.stage == .mesh) for (f.decl.attrs) |a| {
if (std.ascii.eqlIgnoreCase(a.name, "outputtopology") and a.args.len == 1 and a.args[0].kind == .string_lit) {
if (std.mem.indexOf(u8, a.args[0].kind.string_lit, "line") != null) entry.mesh.topology = .line;
}
};
if (opts.stage == .amplification) entry.mesh.payload = l.mesh_payload;
const tess = opts.stage == .hull or opts.stage == .domain; const tess = opts.stage == .hull or opts.stage == .domain;
if (tess) l.tessAttributes(f, &entry); if (tess) l.tessAttributes(f, &entry);
// Hull shaders: where the control point inputs start. // Hull shaders: where the control point inputs start.
@ -1708,8 +1754,38 @@ const Lowerer = struct {
for (f.decl.params, f.params, 0..) |pd, p, i| { for (f.decl.params, f.params, 0..) |pd, p, i| {
if (l.s.types.get(p.type) == .stream) continue; if (l.s.types.get(p.type) == .stream) continue;
n_args += 1; n_args += 1;
locals[i] = try l.b.add(.{ .op = .local_var, .ty = l.irType(p.type), .ptr = .function });
const q = pd.quals; const q = pd.quals;
if (opts.stage == .mesh and (q.vertices or q.indices or q.primitives) and l.s.types.get(p.type) == .array) {
// Output arrays: stores through them write the outputs.
const arr = l.s.types.get(p.type).array;
const kind: ir.MeshOutput = if (q.vertices) .vertices else if (q.primitives) .primitives else .indices;
switch (kind) {
.vertices => {
entry.mesh.max_vertices = arr.len;
var next: u32 = @intCast(entry.outputs.items.len);
try l.streamOut(&entry.outputs, arr.elem, semanticOf(pd.semantics), paramAttrs(q), null, &next, 0, null, pd.name_loc);
},
.primitives => {
entry.mesh.max_primitives = arr.len;
var next: u32 = @intCast(entry.patch_constants.items.len);
try l.streamOut(&entry.patch_constants, arr.elem, semanticOf(pd.semantics), paramAttrs(q), null, &next, 0, null, pd.name_loc);
},
.indices => {
entry.mesh.max_primitives = arr.len;
if (l.s.types.get(arr.elem) == .vector and l.s.types.get(arr.elem).vector.len == 2) entry.mesh.topology = .line;
},
}
locals[i] = try l.b.add(.{ .op = .{ .mesh_output = kind }, .ty = p.type, .ptr = .mesh });
args[i] = locals[i];
continue;
}
locals[i] = try l.b.add(.{ .op = .local_var, .ty = l.irType(p.type), .ptr = .function });
if (opts.stage == .mesh and q.payload) {
entry.mesh.payload = p.type;
try l.b.store(locals[i], try l.b.add(.{ .op = .mesh_payload, .ty = p.type }));
args[i] = try l.b.load(locals[i]);
continue;
}
if (tess and l.s.types.get(p.type) == .patch) { if (tess and l.s.types.get(p.type) == .patch) {
// Control points: one value per point of the patch. // Control points: one value per point of the patch.
const first: u32 = @intCast(entry.inputs.items.len); const first: u32 = @intCast(entry.inputs.items.len);
@ -1754,11 +1830,17 @@ const Lowerer = struct {
if (f.ret != TypeTable.void_type) try l.entryOutput(&entry, f.ret, semanticOf(f.decl.ret_semantics), paramAttrs(f.decl.quals), ret, f.loc, "return value"); if (f.ret != TypeTable.void_type) try l.entryOutput(&entry, f.ret, semanticOf(f.decl.ret_semantics), paramAttrs(f.decl.quals), ret, f.loc, "return value");
for (f.decl.params, f.params, 0..) |pd, p, i| { for (f.decl.params, f.params, 0..) |pd, p, i| {
if (p.dir == .in or l.s.types.get(p.type) == .stream) continue; if (p.dir == .in or l.s.types.get(p.type) == .stream) continue;
if (l.b.f.inst(locals[i]).ptr == .mesh) continue;
const v = try l.b.load(locals[i]); const v = try l.b.load(locals[i]);
try l.entryOutput(&entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), v, pd.name_loc, pd.name); try l.entryOutput(&entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), v, pd.name_loc, pd.name);
} }
l.b.terminate(.{ .ret = .none }); l.b.terminate(.{ .ret = .none });
entry.wrapper = wrapper; entry.wrapper = wrapper;
if (opts.stage == .mesh) {
// Vertex and primitive outputs are arrays.
for (entry.outputs.items) |*el| el.per_vertex = true;
for (entry.patch_constants.items) |*el| el.per_vertex = true;
}
if (opts.stage == .hull) { if (opts.stage == .hull) {
// Output control points are arrays over the patch. // Output control points are arrays over the patch.
for (entry.outputs.items) |*el| el.per_vertex = true; for (entry.outputs.items) |*el| el.per_vertex = true;

View File

@ -181,7 +181,7 @@ fn mapRefs(a: Allocator, xs: []const Ref, ctx: anytype) Allocator.Error![]const
/// `op` with every operand passed through `ctx.map`. /// `op` with every operand passed through `ctx.map`.
fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op { fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
return switch (op) { return switch (op) {
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex => op, .constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload => op,
.load => |p| .{ .load = ctx.map(p) }, .load => |p| .{ .load = ctx.map(p) },
.store => |x| .{ .store = .{ .ptr = ctx.map(x.ptr), .value = ctx.map(x.value) } }, .store => |x| .{ .store = .{ .ptr = ctx.map(x.ptr), .value = ctx.map(x.value) } },
.access => |x| .{ .access = .{ .base = ctx.map(x.base), .indices = try mapRefs(a, x.indices, ctx) } }, .access => |x| .{ .access = .{ .base = ctx.map(x.base), .indices = try mapRefs(a, x.indices, ctx) } },

View File

@ -266,6 +266,8 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
.hull => .hull, .hull => .hull,
.domain => .domain, .domain => .domain,
.compute => .compute, .compute => .compute,
.mesh => .mesh,
.amplification => .amplification,
else => .library, else => .library,
}; };
module = zdxc.ir.lower.lowerUnit(arena, &sema, .{ .entry = opts.entry, .stage = stage }) catch |e| switch (e) { module = zdxc.ir.lower.lowerUnit(arena, &sema, .{ .entry = opts.entry, .stage = stage }) catch |e| switch (e) {

View File

@ -167,6 +167,8 @@ pub const Op = enum(u16) {
return_value = 254, return_value = 254,
@"unreachable" = 255, @"unreachable" = 255,
group_non_uniform_elect = 333, group_non_uniform_elect = 333,
emit_mesh_tasks_ext = 5294,
set_mesh_outputs_ext = 5295,
group_non_uniform_all = 334, group_non_uniform_all = 334,
group_non_uniform_any = 335, group_non_uniform_any = 335,
group_non_uniform_all_equal = 336, group_non_uniform_all_equal = 336,

View File

@ -23,7 +23,7 @@ const Ref = ir.Ref;
pub const Error = Allocator.Error || error{Unsupported}; pub const Error = Allocator.Error || error{Unsupported};
/// SPIR-V storage classes. /// SPIR-V storage classes.
const StorageClass = enum(u32) { uniform_constant = 0, input = 1, uniform = 2, output = 3, workgroup = 4, private = 6, function = 7, image = 11, storage_buffer = 12 }; const StorageClass = enum(u32) { uniform_constant = 0, input = 1, uniform = 2, output = 3, workgroup = 4, private = 6, function = 7, image = 11, storage_buffer = 12, task_payload_workgroup = 5402 };
const Capability = enum(u32) { const Capability = enum(u32) {
shader = 1, shader = 1,
@ -51,6 +51,7 @@ const Capability = enum(u32) {
storage_image_read_without_format = 55, storage_image_read_without_format = 55,
storage_image_write_without_format = 56, storage_image_write_without_format = 56,
group_non_uniform = 61, group_non_uniform = 61,
mesh_shading_ext = 5283,
group_non_uniform_vote = 62, group_non_uniform_vote = 62,
group_non_uniform_arithmetic = 63, group_non_uniform_arithmetic = 63,
group_non_uniform_ballot = 64, group_non_uniform_ballot = 64,
@ -136,6 +137,17 @@ const Emitter = struct {
inputs: []Interface = &.{}, inputs: []Interface = &.{},
outputs: []Interface = &.{}, outputs: []Interface = &.{},
patches: []Interface = &.{}, patches: []Interface = &.{},
/// Mesh shaders: the primitive indices builtin and the payload
/// variable (both made on first use); amplification shaders: the
/// groupshared variable sent by DispatchMesh.
indices_var: Id = 0,
payload_var: Id = 0,
payload_global: ?u32 = null,
/// Per instruction (current function): places in mesh output arrays.
mesh_places: std.AutoHashMapUnmanaged(u32, MeshPlace) = .empty,
/// Parameters receiving mesh output arrays: not real parameters (the
/// outputs are module variables); by function and parameter index.
mesh_params: std.AutoHashMapUnmanaged(struct { *const ir.Function, u32 }, ir.MeshOutput) = .empty,
interface_ids: std.ArrayList(Id) = .empty, interface_ids: std.ArrayList(Id) = .empty,
// Per function. // Per function.
@ -150,6 +162,7 @@ const Emitter = struct {
tess_level: bool = false, tess_level: bool = false,
}; };
const LayoutKey = struct { TypeId, layout.Rules, bool }; const LayoutKey = struct { TypeId, layout.Rules, bool };
const MeshPlace = struct { kind: ir.MeshOutput, index: Ref = .none, offset: u32 = 0, ty: TypeId };
const PtrLayout = struct { rules: layout.Rules, row_major: bool }; const PtrLayout = struct { rules: layout.Rules, row_major: bool };
fn unsupported(e: *Emitter, comptime fmt: []const u8, args: anytype) Error { fn unsupported(e: *Emitter, comptime fmt: []const u8, args: anytype) Error {
@ -491,6 +504,13 @@ const Emitter = struct {
e.void_id = try e.typeId(TypeTable.void_type); e.void_id = try e.typeId(TypeTable.void_type);
try e.cap(.shader); try e.cap(.shader);
if (entry.stage == .geometry) try e.cap(.geometry); if (entry.stage == .geometry) try e.cap(.geometry);
if (entry.stage == .mesh or entry.stage == .amplification) {
if (e.spv_minor < 4) return e.unsupported("mesh and amplification shaders need SPIR-V 1.4 or later (-fspv-target-env=vulkan1.2 or later)", .{});
try e.cap(.mesh_shading_ext);
try e.extension("SPV_EXT_mesh_shader");
e.payload_global = e.dispatchPayloadGlobal();
try e.findMeshParams();
}
e.func_ids = try e.arena.alloc(Id, m.functions.items.len); e.func_ids = try e.arena.alloc(Id, m.functions.items.len);
for (e.func_ids) |*id| id.* = e.b.newId(); for (e.func_ids) |*id| id.* = e.b.newId();
@ -517,6 +537,8 @@ const Emitter = struct {
.geometry => 3, .geometry => 3,
.pixel => 4, .pixel => 4,
.compute => 5, .compute => 5,
.amplification => 5364, // TaskEXT
.mesh => 5365, // MeshEXT
.library => return e.unsupported("library targets are not supported", .{}), .library => return e.unsupported("library targets are not supported", .{}),
}; };
const wrapper = e.func_ids[entry.wrapper]; const wrapper = e.func_ids[entry.wrapper];
@ -564,6 +586,14 @@ const Emitter = struct {
try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 26, ts.output_control_points }); // OutputVertices try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 26, ts.output_control_points }); // OutputVertices
}, },
.domain => try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, domainMode(entry.tess.domain) }), .domain => try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, domainMode(entry.tess.domain) }),
.amplification => try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 17, entry.num_threads[0], entry.num_threads[1], entry.num_threads[2] }),
.mesh => {
const ms = entry.mesh;
try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 17, entry.num_threads[0], entry.num_threads[1], entry.num_threads[2] });
try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, if (ms.topology == .line) 5269 else 5298 }); // OutputLinesEXT / OutputTrianglesEXT
try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 26, ms.max_vertices }); // OutputVertices
try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 5270, ms.max_primitives }); // OutputPrimitivesEXT
},
.pixel => { .pixel => {
try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 7 }); // OriginUpperLeft try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 7 }); // OriginUpperLeft
for (entry.outputs.items) |o| if (std.ascii.eqlIgnoreCase(o.semantic, "SV_Depth")) { for (entry.outputs.items) |o| if (std.ascii.eqlIgnoreCase(o.semantic, "SV_Depth")) {
@ -630,7 +660,7 @@ const Emitter = struct {
}, },
.groupshared, .private => { .groupshared, .private => {
const ty = try e.typeId(g.ty); const ty = try e.typeId(g.ty);
const sc: StorageClass = if (g.space == .groupshared) .workgroup else .private; const sc: StorageClass = if (e.payload_global == @as(u32, @intCast(gi))) .task_payload_workgroup else if (g.space == .groupshared) .workgroup else .private;
const ptr = try e.pointerType(sc, ty); const ptr = try e.pointerType(sc, ty);
const var_id = e.b.newId(); const var_id = e.b.newId();
try e.b.emit(.types_globals, .variable, &.{ ptr, var_id, @backingInt(sc) }); try e.b.emit(.types_globals, .variable, &.{ ptr, var_id, @backingInt(sc) });
@ -729,7 +759,7 @@ const Emitter = struct {
const eq = std.ascii.eqlIgnoreCase; const eq = std.ascii.eqlIgnoreCase;
// Builtins exist only for some stages and directions; elsewhere a // Builtins exist only for some stages and directions; elsewhere a
// system value is an ordinary located variable (as in dxc). // system value is an ordinary located variable (as in dxc).
if (stage == .compute and input) { if ((stage == .compute or stage == .mesh or stage == .amplification) and input) {
if (eq(n, "SV_DispatchThreadID")) return .{ .id = 28, .ty = uint3 }; // GlobalInvocationId if (eq(n, "SV_DispatchThreadID")) return .{ .id = 28, .ty = uint3 }; // GlobalInvocationId
if (eq(n, "SV_GroupID")) return .{ .id = 26, .ty = uint3 }; // WorkgroupId if (eq(n, "SV_GroupID")) return .{ .id = 26, .ty = uint3 }; // WorkgroupId
if (eq(n, "SV_GroupThreadID")) return .{ .id = 27, .ty = uint3 }; // LocalInvocationId if (eq(n, "SV_GroupThreadID")) return .{ .id = 27, .ty = uint3 }; // LocalInvocationId
@ -749,7 +779,11 @@ const Emitter = struct {
return .{ .id = 7, .ty = uint1 }; // PrimitiveId return .{ .id = 7, .ty = uint1 }; // PrimitiveId
} }
if (input and stage == .geometry and eq(n, "SV_GSInstanceID")) return .{ .id = 8, .ty = uint1 }; // InvocationId if (input and stage == .geometry and eq(n, "SV_GSInstanceID")) return .{ .id = 8, .ty = uint1 }; // InvocationId
if ((!input and stage == .geometry) or (input and stage == .pixel)) { if (stage == .mesh and !input) {
if (eq(n, "SV_CullPrimitive")) return .{ .id = 5299, .ty = try t.scalar(.bool) }; // CullPrimitiveEXT
if (eq(n, "SV_PrimitiveID")) return .{ .id = 7, .ty = uint1 }; // PrimitiveId
}
if ((!input and (stage == .geometry or stage == .mesh)) or (input and stage == .pixel)) {
if (eq(n, "SV_RenderTargetArrayIndex")) { if (eq(n, "SV_RenderTargetArrayIndex")) {
try e.cap(.geometry); try e.cap(.geometry);
return .{ .id = 9, .ty = uint1 }; // Layer return .{ .id = 9, .ty = uint1 }; // Layer
@ -799,6 +833,7 @@ const Emitter = struct {
if (el.per_vertex) ty = try e.t.array(ty, switch (entry.stage) { if (el.per_vertex) ty = try e.t.array(ty, switch (entry.stage) {
.geometry => entry.geometry.input_vertices, .geometry => entry.geometry.input_vertices,
.hull => if (input) entry.tess.input_control_points else entry.tess.output_control_points, .hull => if (input) entry.tess.input_control_points else entry.tess.output_control_points,
.mesh => if (patch) entry.mesh.max_primitives else entry.mesh.max_vertices,
else => entry.tess.input_control_points, else => entry.tess.input_control_points,
}); });
const sc: StorageClass = if (input) .input else .output; const sc: StorageClass = if (input) .input else .output;
@ -811,7 +846,7 @@ const Emitter = struct {
const ptr = try e.pointerType(sc, try e.typeId(ty)); const ptr = try e.pointerType(sc, try e.typeId(ty));
const var_id = e.b.newId(); const var_id = e.b.newId();
try e.b.emit(.types_globals, .variable, &.{ ptr, var_id, @backingInt(sc) }); try e.b.emit(.types_globals, .variable, &.{ ptr, var_id, @backingInt(sc) });
if (patch) try e.b.emit(.annotations, .decorate, &.{ var_id, 15 }); // Patch if (patch) try e.b.emit(.annotations, .decorate, if (entry.stage == .mesh) &.{ var_id, 5271 } else &.{ var_id, 15 }); // PerPrimitiveEXT / Patch
if (bi) |x| { if (bi) |x| {
try e.b.emit(.annotations, .decorate, &.{ var_id, 11, x.id }); // BuiltIn try e.b.emit(.annotations, .decorate, &.{ var_id, 11, x.id }); // BuiltIn
if (input and entry.stage == .pixel and !e.t.component(x.ty).?.isFloat() and e.t.component(x.ty).? != .bool) { if (input and entry.stage == .pixel and !e.t.component(x.ty).?.isFloat() and e.t.component(x.ty).? != .bool) {
@ -905,6 +940,7 @@ const Emitter = struct {
fn emitFunction(e: *Emitter, f: *const ir.Function, fn_id: Id, bindings: []const Id) Error!void { fn emitFunction(e: *Emitter, f: *const ir.Function, fn_id: Id, bindings: []const Id) Error!void {
e.f = f; e.f = f;
e.texel_places = .empty; e.texel_places = .empty;
e.mesh_places = .empty;
e.vals = try e.arena.alloc(Id, f.insts.items.len); e.vals = try e.arena.alloc(Id, f.insts.items.len);
@memset(e.vals, 0); @memset(e.vals, 0);
e.ptr_layouts = try e.arena.alloc(?PtrLayout, f.insts.items.len); e.ptr_layouts = try e.arena.alloc(?PtrLayout, f.insts.items.len);
@ -913,6 +949,7 @@ const Emitter = struct {
var params: std.ArrayList(Id) = .empty; var params: std.ArrayList(Id) = .empty;
for (f.params, 0..) |p, k| { for (f.params, 0..) |p, k| {
if (bindings.len > 0 and bindings[k] != 0) continue; if (bindings.len > 0 and bindings[k] != 0) continue;
if (e.mesh_params.contains(.{ f, @intCast(k) })) continue;
const t = try e.typeId(p.ty); const t = try e.typeId(p.ty);
try params.append(e.arena, if (p.by_ref) try e.pointerType(.function, t) else t); try params.append(e.arena, if (p.by_ref) try e.pointerType(.function, t) else t);
} }
@ -925,6 +962,10 @@ const Emitter = struct {
id.* = bindings[k]; id.* = bindings[k];
continue; continue;
} }
if (e.mesh_params.contains(.{ f, @intCast(k) })) {
id.* = 0;
continue;
}
id.* = e.b.newId(); id.* = e.b.newId();
try e.b.emit(.functions, .function_parameter, &.{ params.items[next], id.* }); try e.b.emit(.functions, .function_parameter, &.{ params.items[next], id.* });
next += 1; next += 1;
@ -938,7 +979,10 @@ const Emitter = struct {
// Constants and parameters first (they may be used in any block). // Constants and parameters first (they may be used in any block).
for (f.insts.items, 0..) |inst, i| switch (inst.op) { for (f.insts.items, 0..) |inst, i| switch (inst.op) {
.constant => |c| e.vals[i] = try e.constant(inst.ty, c), .constant => |c| e.vals[i] = try e.constant(inst.ty, c),
.param => |p| e.vals[i] = param_ids[p], .param => |p| {
e.vals[i] = param_ids[p];
if (e.mesh_params.get(.{ f, p })) |kind| try e.mesh_places.put(e.arena, @intCast(i), .{ .kind = kind, .ty = inst.ty });
},
else => {}, else => {},
}; };
@ -1149,6 +1193,7 @@ const Emitter = struct {
e.vals[ri] = try e.op1(.load, i.ty, &.{e.val(p)}); e.vals[ri] = try e.op1(.load, i.ty, &.{e.val(p)});
}, },
.store => |s| { .store => |s| {
if (e.mesh_places.get(s.ptr.index())) |mp| return e.meshStore(mp, e.val(s.value), f.inst(s.value).ty);
if (e.texel_places.get(s.ptr.index())) |tp| { if (e.texel_places.get(s.ptr.index())) |tp| {
if (tp.comp != .none) return e.unsupported("storing one component of a texel is not supported yet", .{}); if (tp.comp != .none) return e.unsupported("storing one component of a texel is not supported yet", .{});
return e.imageWrite(tp.res, e.val(tp.coord), e.val(s.value)); return e.imageWrite(tp.res, e.val(tp.coord), e.val(s.value));
@ -1185,10 +1230,42 @@ const Emitter = struct {
// Uniform std430 storage. // Uniform std430 storage.
const into_buffer = e.t.get(f.inst(a.base).ty) == .resource; const into_buffer = e.t.get(f.inst(a.base).ty) == .resource;
const base_pl = e.ptr_layouts[a.base.index()]; const base_pl = e.ptr_layouts[a.base.index()];
if (i.ptr == .mesh) {
// Mesh outputs: a place, written component by component.
var mp: MeshPlace = e.mesh_places.get(a.base.index()) orelse .{ .kind = f.inst(a.base).op.mesh_output, .ty = f.inst(a.base).ty };
for (a.indices) |x| {
if (mp.index == .none) {
mp.index = x;
mp.ty = e.t.get(mp.ty).array.elem;
continue;
}
const k: u32 = switch (f.inst(x).op) {
.constant => |c| @intCast(c.int),
else => return e.unsupported("dynamic indexing inside a mesh output is not supported yet", .{}),
};
switch (e.t.get(mp.ty)) {
.@"struct" => |st| {
for (st.fields.items[0..k]) |fld| mp.offset += e.t.componentCount(fld.type).?;
mp.ty = st.fields.items[k].type;
},
.array => |arr| {
mp.offset += k * e.t.componentCount(arr.elem).?;
mp.ty = arr.elem;
},
.vector => |v| {
mp.offset += k;
mp.ty = try e.t.scalar(v.elem);
},
else => return e.unsupported("indexing this mesh output is not supported yet", .{}),
}
}
try e.mesh_places.put(e.arena, ri, mp);
return;
}
const sc: StorageClass = if (into_buffer or (base_pl != null and base_pl.?.rules == .std430)) e.bufferSc() else if (base_pl != null) .uniform else switch (i.ptr) { const sc: StorageClass = if (into_buffer or (base_pl != null and base_pl.?.rules == .std430)) e.bufferSc() else if (base_pl != null) .uniform else switch (i.ptr) {
.function => .function, .function => .function,
.private => .private, .private => .private,
.groupshared => .workgroup, .groupshared => if (e.payload_global != null and e.rootGlobal(a.base) == e.payload_global) .task_payload_workgroup else .workgroup,
.cbuffer, .resource => .uniform, .cbuffer, .resource => .uniform,
else => return e.unsupported("access into this storage is not supported yet", .{}), else => return e.unsupported("access into this storage is not supported yet", .{}),
}; };
@ -1419,10 +1496,26 @@ const Emitter = struct {
return; return;
} }
try ops.append(e.arena, e.func_ids[c.func]); try ops.append(e.arena, e.func_ids[c.func]);
for (c.args) |a| try ops.append(e.arena, e.val(a)); for (c.args, 0..) |a, k| {
if (e.mesh_params.contains(.{ callee, @intCast(k) })) continue;
try ops.append(e.arena, e.val(a));
}
e.vals[ri] = try e.op1(.function_call, i.ty, ops.items); e.vals[ri] = try e.op1(.function_call, i.ty, ops.items);
}, },
.intrinsic => |c| e.vals[ri] = try e.intrinsic(c.name, i.ty, c.args), .intrinsic => |c| {
if (std.mem.eql(u8, c.name, "SetMeshOutputCounts")) {
try e.b.emit(.functions, .set_mesh_outputs_ext, &.{ e.val(c.args[0]), e.val(c.args[1]) });
return;
}
if (std.mem.eql(u8, c.name, "DispatchMesh")) {
if (e.rootGlobal(c.args[3]) == null or f.inst(c.args[3]).op != .global) return e.unsupported("DispatchMesh with this payload is not supported yet", .{});
try e.b.emit(.functions, .emit_mesh_tasks_ext, &.{ e.val(c.args[0]), e.val(c.args[1]), e.val(c.args[2]), e.val(c.args[3]) });
// A terminator: what follows is unreachable.
try e.b.emit(.functions, .label, &.{e.b.newId()});
return;
}
e.vals[ri] = try e.intrinsic(c.name, i.ty, c.args);
},
.res_load => |x| { .res_load => |x| {
if (e.isImage(x.res)) { if (e.isImage(x.res)) {
e.vals[ri] = try e.imageIndexLoad(x.res, e.val(x.index), i.ty); e.vals[ri] = try e.imageIndexLoad(x.res, e.val(x.index), i.ty);
@ -1453,6 +1546,16 @@ const Emitter = struct {
e.vals[ri] = try e.reshape(try e.op1(.load, iface.ty, &.{ptr}), iface.ty, i.ty); e.vals[ri] = try e.reshape(try e.op1(.load, iface.ty, &.{ptr}), iface.ty, i.ty);
}, },
.patch_input => |k| e.vals[ri] = try e.loadInterface(e.patches[k], .input, i.ty), .patch_input => |k| e.vals[ri] = try e.loadInterface(e.patches[k], .input, i.ty),
.mesh_output => try e.mesh_places.put(e.arena, ri, .{ .kind = i.op.mesh_output, .ty = i.ty }),
.mesh_payload => {
if (e.payload_var == 0) {
e.payload_var = e.b.newId();
try e.b.emit(.types_globals, .variable, &.{ try e.pointerType(.task_payload_workgroup, try e.typeId(i.ty)), e.payload_var, @backingInt(StorageClass.task_payload_workgroup) });
try e.b.emitWithString(.debug_names, .name, &.{e.payload_var}, "in.var.payload", &.{});
try e.interface_ids.append(e.arena, e.payload_var);
}
e.vals[ri] = try e.op1(.load, i.ty, &.{e.payload_var});
},
.patch_output => |o| try e.storeInterface(e.patches[o.element], f.inst(o.value).ty, e.val(o.value)), .patch_output => |o| try e.storeInterface(e.patches[o.element], f.inst(o.value).ty, e.val(o.value)),
.output_vertex => |x| { .output_vertex => |x| {
const iface = e.outputs[x.element]; const iface = e.outputs[x.element];
@ -1479,6 +1582,150 @@ const Emitter = struct {
} }
} }
/// Parameters that receive mesh output arrays, through any depth of
/// calls from the entry.
fn findMeshParams(e: *Emitter) Error!void {
var changed = true;
while (changed) {
changed = false;
for (e.m.functions.items) |f| for (f.insts.items) |inst| switch (inst.op) {
.call => |c| for (c.args, 0..) |a, k| {
const kind: ?ir.MeshOutput = switch (f.inst(a).op) {
.mesh_output => |mk| mk,
.param => |p| e.mesh_params.get(.{ f, p }),
else => null,
};
const callee = e.m.functions.items[c.func];
if (kind) |mk| if (!e.mesh_params.contains(.{ callee, @intCast(k) })) {
try e.mesh_params.put(e.arena, .{ callee, @intCast(k) }, mk);
changed = true;
};
},
else => {},
};
}
}
/// The global a pointer derives from, if any.
fn rootGlobal(e: *Emitter, r: Ref) ?u32 {
var x = r;
while (true) switch (e.f.inst(x).op) {
.global => |g| return g,
.access => |a| x = a.base,
else => return null,
};
}
/// The groupshared variable an amplification shader passes to
/// DispatchMesh (its storage becomes the task payload).
fn dispatchPayloadGlobal(e: *Emitter) ?u32 {
for (e.m.functions.items) |f| for (f.insts.items) |inst| switch (inst.op) {
.intrinsic => |it| if (std.mem.eql(u8, it.name, "DispatchMesh") and it.args.len == 4) {
var x = it.args[3];
while (true) switch (f.inst(x).op) {
.global => |g| return g,
.access => |a| x = a.base,
else => break,
};
},
else => {},
};
return null;
}
/// Flattened component `k` of value `v` of type `ty`.
fn flatComponent(e: *Emitter, v: Id, ty: TypeId, k: u32) Error!struct { Id, TypeId } {
switch (e.t.get(ty)) {
.scalar, .@"enum" => return .{ v, ty },
.vector => |vec| {
const st = try e.t.scalar(vec.elem);
return .{ if (vec.len == 1) v else try e.op1(.composite_extract, st, &.{ v, k }), st };
},
.array => |a| {
const n = e.t.componentCount(a.elem).?;
return e.flatComponent(try e.op1(.composite_extract, a.elem, &.{ v, k / n }), a.elem, k % n);
},
.@"struct" => |st| {
var kk = k;
for (st.fields.items, 0..) |fld, fi| {
const n = e.t.componentCount(fld.type).?;
if (kk < n) return e.flatComponent(try e.op1(.composite_extract, fld.type, &.{ v, @intCast(fi) }), fld.type, kk);
kk -= n;
}
return e.unsupported("internal: component out of range", .{});
},
else => return e.unsupported("mesh outputs of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
}
}
/// Writes a vertex / primitive output (component by component, into
/// each attribute's array) or a primitive's indices.
fn meshStore(e: *Emitter, mp: MeshPlace, v: Id, ty: TypeId) Error!void {
if (mp.index == .none) return e.unsupported("storing a whole mesh output array is not supported yet", .{});
const entry = e.m.entry.?;
const index = e.val(mp.index);
if (mp.kind == .indices) {
const lines = entry.mesh.topology == .line;
const vty = try e.t.vector(.uint, if (lines) 2 else 3);
if (e.indices_var == 0) {
e.indices_var = e.b.newId();
try e.b.emit(.types_globals, .variable, &.{ try e.pointerType(.output, try e.typeId(try e.t.array(vty, entry.mesh.max_primitives))), e.indices_var, @backingInt(StorageClass.output) });
try e.b.emit(.annotations, .decorate, &.{ e.indices_var, 11, if (lines) 5295 else 5296 }); // BuiltIn Primitive{Line,Triangle}IndicesEXT
try e.interface_ids.append(e.arena, e.indices_var);
}
if (mp.offset == 0 and e.t.componentCount(ty) == e.t.componentCount(vty)) {
const ptr = try e.opRaw(.access_chain, try e.pointerType(.output, try e.typeId(vty)), &.{ e.indices_var, index });
try e.b.emit(.functions, .store, &.{ ptr, try e.reshape(v, ty, vty) });
return;
}
const ut = try e.t.scalar(.uint);
for (0..e.t.componentCount(ty).?) |c| {
const comp = try e.flatComponent(v, ty, @intCast(c));
const ptr = try e.opRaw(.access_chain, try e.pointerType(.output, try e.typeId(ut)), &.{ e.indices_var, index, try e.constUint(mp.offset + @as(u32, @intCast(c))) });
try e.b.emit(.functions, .store, &.{ ptr, try e.reshape(comp[0], comp[1], ut) });
}
return;
}
const n = e.t.componentCount(ty) orelse return e.unsupported("mesh outputs of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)});
const els = if (mp.kind == .vertices) entry.outputs.items else entry.patch_constants.items;
const ifaces = if (mp.kind == .vertices) e.outputs else e.patches;
for (0..n) |c| {
const comp = try e.flatComponent(v, ty, @intCast(c));
var flat = mp.offset + @as(u32, @intCast(c));
var k: usize = 0;
while (k < els.len) : (k += 1) {
const cnt = e.t.componentCount(els[k].ty).?;
if (flat < cnt) break;
flat -= cnt;
}
if (k == els.len) return e.unsupported("internal: mesh output component out of range", .{});
const iface = ifaces[k];
// Indices into the attribute: [vertex] then within it.
var chain: std.ArrayList(u32) = .empty;
try chain.appendSlice(e.arena, &.{ 0, 0, iface.var_id, index });
var leaf = iface.ty;
switch (e.t.get(leaf)) {
.scalar, .@"enum" => {},
.vector => |vec| {
if (vec.len > 1) try chain.append(e.arena, try e.constUint(flat));
leaf = try e.t.scalar(vec.elem);
},
.array => |a| {
const per = e.t.componentCount(a.elem).?;
try chain.append(e.arena, try e.constUint(flat / per));
if (e.t.get(a.elem) == .vector and per > 1) try chain.append(e.arena, try e.constUint(flat % per));
leaf = try e.t.scalar(e.t.component(a.elem).?);
},
else => return e.unsupported("mesh outputs of type '{s}' are not supported yet", .{try e.t.format(e.arena, leaf)}),
}
const ptr = e.b.newId();
chain.items[0] = try e.pointerType(.output, try e.typeId(leaf));
chain.items[1] = ptr;
try e.b.emit(.functions, .access_chain, chain.items);
try e.b.emit(.functions, .store, &.{ ptr, try e.reshape(comp[0], comp[1], leaf) });
}
}
/// Reads an interface variable as a value of type `ty`. /// Reads an interface variable as a value of type `ty`.
fn loadInterface(e: *Emitter, iface: Interface, sc: StorageClass, ty: TypeId) Error!Id { fn loadInterface(e: *Emitter, iface: Interface, sc: StorageClass, ty: TypeId) Error!Id {
if (!iface.tess_level) return e.reshape(try e.op1(.load, iface.ty, &.{iface.var_id}), iface.ty, ty); if (!iface.tess_level) return e.reshape(try e.op1(.load, iface.ty, &.{iface.var_id}), iface.ty, ty);

View File

@ -0,0 +1,13 @@
// PROFILE: as_6_5
// Amplification shader: a groupshared payload (struct-typed, accessed
// through GEPs) sent with DispatchMesh.
// ZCHECK: call void @dx.op.dispatchMesh.struct.Payload(i32 173
struct Payload { uint base; float scale[2]; uint ids[8]; };
groupshared Payload pl;
[numthreads(8,1,1)]
void main(uint tid : SV_GroupIndex) {
pl.ids[tid] = tid * 2;
if (tid == 0) { pl.base = 7; pl.scale[0] = 1; pl.scale[1] = 2; }
GroupMemoryBarrierWithGroupSync();
DispatchMesh(2, 1, 1, pl);
}

27
test/dxil/mesh.hlsl Normal file
View File

@ -0,0 +1,27 @@
// PROFILE: ms_6_5
// Mesh shader: vertex and primitive outputs written per element, indices,
// partial (swizzled) output writes, the payload.
// ZCHECK: call void @dx.op.setMeshOutputCounts(i32 168
// ZCHECK: call void @dx.op.emitIndices(i32 169
// ZCHECK: call void @dx.op.storePrimitiveOutput.i32(i32 172
// ZCHECK: getMeshPayload
struct V { float4 pos : SV_Position; float2 uv : TEXCOORD0; float c[2] : COLOR; };
struct P { nointerpolation uint id : PRIMID; bool cull : SV_CullPrimitive; };
struct Payload { uint base; float scale[3]; };
[numthreads(4,1,1)]
[outputtopology("triangle")]
void main(out indices uint3 tris[2], out vertices V verts[4], out primitives P prims[2], in payload Payload pl, uint tid : SV_GroupIndex) {
SetMeshOutputCounts(4, 2);
verts[tid].pos = float4(tid, 0, 0, 1) * pl.scale[tid % 3];
verts[tid].uv.y = 1;
verts[tid].uv.x = 0;
verts[tid].c[1] = 2;
verts[tid].c[0] = 3;
if (tid < 2) {
tris[tid] = uint3(0, tid + 1, tid + 2);
P p;
p.id = pl.base + tid;
p.cull = tid == 1;
prims[tid] = p;
}
}

View File

@ -35,7 +35,7 @@ while read -r f; do
crashed=$((crashed + 1)); echo "$f" >> "$TMP/crashed" crashed=$((crashed + 1)); echo "$f" >> "$TMP/crashed"
elif [ $rc = 0 ]; then elif [ $rc = 0 ]; then
if [ "$BACKEND" = spirv ]; then if [ "$BACKEND" = spirv ]; then
env=$(printf '%s\n' "$flags" | sed -n 's/.*-fspv-target-env=\([a-z0-9.]*\).*/\1/p') env=$(printf '%s\n' "$flags" | sed -n 's/.*-fspv-target-env=\([a-z0-9.]*\).*/\1/p'); env=$(printf "%s" "$env" | sed "s/spirv1/spv1/")
"$SPIRV_VAL" --target-env "${env:-vulkan1.0}" --relax-block-layout "$TMP/out" > "$TMP/val" 2>&1 "$SPIRV_VAL" --target-env "${env:-vulkan1.0}" --relax-block-layout "$TMP/out" > "$TMP/val" 2>&1
else else
"$DXV" "$TMP/out" > "$TMP/val" 2>&1 "$DXV" "$TMP/out" > "$TMP/val" 2>&1

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
# Print the dxc/zdxc flags taken from the first RUN line of an HLSL test: # Print the dxc/zdxc flags taken from the first RUN line of an HLSL test:
# -T, -E, -D, -spirv and -enable-16bit-types. Exits 1 if there is no -T. # -T, -E, -D, -spirv, -fspv-target-env and -enable-16bit-types. Exits 1 if
# there is no -T.
run=$(grep -m1 'RUN:' "$1") run=$(grep -m1 'RUN:' "$1")
target=$(printf '%s' "$run" | grep -oE -- '-T *[a-z]+_6_[0-9]+' | head -1 | sed 's/-T *//') target=$(printf '%s' "$run" | grep -oE -- '-T *[a-z]+_6_[0-9]+' | head -1 | sed 's/-T *//')
[ -n "$target" ] || exit 1 [ -n "$target" ] || exit 1
@ -9,4 +10,6 @@ defs=$(printf '%s' "$run" | grep -oE -- '-D *[A-Za-z_][A-Za-z0-9_]*(=[^ ]*)?' |
extra="" extra=""
printf '%s' "$run" | grep -q -- '-spirv' && extra="$extra -spirv" printf '%s' "$run" | grep -q -- '-spirv' && extra="$extra -spirv"
printf '%s' "$run" | grep -q -- '-enable-16bit-types' && extra="$extra -enable-16bit-types" printf '%s' "$run" | grep -q -- '-enable-16bit-types' && extra="$extra -enable-16bit-types"
env=$(printf '%s' "$run" | grep -oE -- '-fspv-target-env=[a-z0-9.]+' | head -1)
[ -n "$env" ] && extra="$extra $env"
echo "-T $target $entry $extra $defs" echo "-T $target $entry $extra $defs"

View File

@ -0,0 +1,16 @@
// PROFILE: as_6_5
// ENV: vulkan1.3
// Amplification shader: the groupshared payload becomes TaskPayloadWorkgroupEXT
// storage, DispatchMesh OpEmitMeshTasksEXT.
// ZCHECK: OpEntryPoint TaskEXT
// ZCHECK: %pl = OpVariable {{.*}} TaskPayloadWorkgroupEXT
// ZCHECK: OpEmitMeshTasksEXT
struct Payload { uint base; float scale[2]; uint ids[8]; };
groupshared Payload pl;
[numthreads(8,1,1)]
void main(uint tid : SV_GroupIndex) {
pl.ids[tid] = tid * 2;
if (tid == 0) { pl.base = 7; pl.scale[0] = 1; pl.scale[1] = 2; }
GroupMemoryBarrierWithGroupSync();
DispatchMesh(2, 1, 1, pl);
}

View File

@ -19,7 +19,7 @@ for f in test/spirv/*.hlsl; do
env=$(sed -n "s|^// ENV: *||p" "$f"); if ! "$ZDXC" -spirv -T "$profile" -fspv-target-env="${env:-vulkan1.0}" "$f" -Fo "$TMP/z.spv" > "$TMP/log" 2>&1; then env=$(sed -n "s|^// ENV: *||p" "$f"); if ! "$ZDXC" -spirv -T "$profile" -fspv-target-env="${env:-vulkan1.0}" "$f" -Fo "$TMP/z.spv" > "$TMP/log" 2>&1; then
fail=$((fail + 1)); echo "FAIL $name: zdxc failed"; head -3 "$TMP/log"; continue fail=$((fail + 1)); echo "FAIL $name: zdxc failed"; head -3 "$TMP/log"; continue
fi fi
if ! "$VAL" --target-env "${env:-vulkan1.0}" --relax-block-layout "$TMP/z.spv" > "$TMP/log" 2>&1; then if ! "$VAL" --target-env "$(printf '%s' "${env:-vulkan1.0}" | sed 's/spirv1/spv1/')" --relax-block-layout "$TMP/z.spv" > "$TMP/log" 2>&1; then
fail=$((fail + 1)); echo "FAIL $name: spirv-val rejected the output"; head -3 "$TMP/log"; continue fail=$((fail + 1)); echo "FAIL $name: spirv-val rejected the output"; head -3 "$TMP/log"; continue
fi fi
"$DIS" "$TMP/z.spv" > "$TMP/z.dis" 2>&1 "$DIS" "$TMP/z.spv" > "$TMP/z.dis" 2>&1

30
test/spirv/mesh.hlsl Normal file
View File

@ -0,0 +1,30 @@
// PROFILE: ms_6_5
// ENV: vulkan1.3
// Mesh shader (SPV_EXT_mesh_shader): per-attribute output arrays,
// triangle indices, per-primitive outputs, the task payload.
// ZCHECK: OpEntryPoint MeshEXT
// ZCHECK: OpSetMeshOutputsEXT
// ZCHECK: BuiltIn PrimitiveTriangleIndicesEXT
// ZCHECK: PerPrimitiveEXT
// ZCHECK: BuiltIn CullPrimitiveEXT
// ZCHECK: TaskPayloadWorkgroupEXT
struct V { float4 pos : SV_Position; float2 uv : TEXCOORD0; float c[2] : COLOR; };
struct P { nointerpolation uint id : PRIMID; bool cull : SV_CullPrimitive; };
struct Payload { uint base; float scale[3]; };
[numthreads(4,1,1)]
[outputtopology("triangle")]
void main(out indices uint3 tris[2], out vertices V verts[4], out primitives P prims[2], in payload Payload pl, uint tid : SV_GroupIndex) {
SetMeshOutputCounts(4, 2);
verts[tid].pos = float4(tid, 0, 0, 1) * pl.scale[tid % 3];
verts[tid].uv.y = 1;
verts[tid].uv.x = 0;
verts[tid].c[1] = 2;
verts[tid].c[0] = 3;
if (tid < 2) {
tris[tid] = uint3(0, tid + 1, tid + 2);
P p;
p.id = pl.base + tid;
p.cull = tid == 1;
prims[tid] = p;
}
}