Vulkan bindings, locations, push constants and spec constants
SPIR-V descriptor bindings are numbered as dxc numbers them: Sema keeps
global and cbuffer declarations in order, lowering records every
descriptor declaration (used or not), and the backend assigns
[[vk::binding]] / [[vk::counter_binding]] first, then register() with the
-fvk-{b,t,s,u}-shift options, then the rest on the next free bindings in
declaration order (Append / Consume counters right after their buffer,
other counters last). Adds -fvk-bind-register, -fvk-bind-globals,
-auto-binding-space, -fvk-auto-shift-bindings, -fvk-stage-io-order and
-fspv-flatten-resource-arrays (one variable per element where indices
are constant), [[vk::push_constant]] buffers (std430, PushConstant),
[[vk::constant_id]] specialization constants, [[vk::location]] and
[[vk::index]], interface variables named after the semantic as written,
and location counts for 1xN / Nx1 matrices. -fcgl is accepted.
Against dxc on the corpus, bindings and locations now match on all 1234
comparable SPIR-V outputs (865 differed before). The SPIR-V checks now
compare bindings and locations with dxc for every test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
0570274b65
commit
2496fce3c0
|
|
@ -1381,6 +1381,7 @@ const Emitter = struct {
|
|||
switch (i.op) {
|
||||
.constant => |c| return e.list(&.{try e.constant(i.ty, c)}),
|
||||
.param => |p| return frame.params[p],
|
||||
.spec_constant => return e.unsupported("specialization constants outside SPIR-V", .{}),
|
||||
.ray_incoming => |k| {
|
||||
// The shader's payload / attribute / parameter argument.
|
||||
const idx: usize = if (k == .attributes) 1 else 0;
|
||||
|
|
|
|||
|
|
@ -856,9 +856,9 @@ pub const Parser = struct {
|
|||
_ = try p.missingSemi("';' after struct");
|
||||
return;
|
||||
}
|
||||
// `struct S { ... } a, b;`
|
||||
// `struct S { ... } a, b;` (leading attributes apply to them too).
|
||||
const ty = try p.mk(ast.TypeRef, .{ .loc = name_loc, .name = try p.simpleName(name_loc, name.?) });
|
||||
try p.parseDeclaratorsInto(out, &.{}, quals, &.{}, ty, ctx);
|
||||
try p.parseDeclaratorsInto(out, lead_attrs, quals, &.{}, ty, ctx);
|
||||
}
|
||||
|
||||
/// After a struct body without `;`: does the next line look like a new
|
||||
|
|
|
|||
|
|
@ -129,6 +129,8 @@ pub const Op = union(enum) {
|
|||
/// Ray tracing entries: pointer (`ray` space) to the storage of an
|
||||
/// incoming value of the instruction's type.
|
||||
ray_incoming: RayIncoming,
|
||||
/// SPIR-V specialization constant (index into Module.spec_constants).
|
||||
spec_constant: u32,
|
||||
patch_output: struct { element: u32, value: Ref },
|
||||
output_vertex: struct { element: u32, vertex: u32 },
|
||||
/// Geometry shaders: emit the vertex written to the outputs of a stream,
|
||||
|
|
@ -215,6 +217,67 @@ pub const Binding = struct {
|
|||
index: u32 = 0,
|
||||
space: u32 = 0,
|
||||
explicit: bool = false,
|
||||
/// `spaceN` was written.
|
||||
space_given: bool = false,
|
||||
};
|
||||
|
||||
/// Vulkan binding options (-fvk-*-shift, -fvk-bind-globals,
|
||||
/// -auto-binding-space).
|
||||
pub const VkOptions = struct {
|
||||
/// Per register class (b, t, s, u): shifts by set; `all` applies to
|
||||
/// every set without one of its own.
|
||||
shifts: [4]std.ArrayList(struct { shift: u32, set: ?u32 }) = .{ .empty, .empty, .empty, .empty },
|
||||
bind_globals: ?[2]u32 = null,
|
||||
auto_binding_space: u32 = 0,
|
||||
/// -fvk-auto-shift-bindings: implicit bindings start at their class's
|
||||
/// shift too.
|
||||
auto_shift: bool = false,
|
||||
/// -fvk-stage-io-order=alpha: locations by semantic, not declaration.
|
||||
alpha_io_order: bool = false,
|
||||
/// -fspv-flatten-resource-arrays: one variable (and binding) per
|
||||
/// element of an array of resources.
|
||||
flatten_arrays: bool = false,
|
||||
/// -fvk-bind-register: every resource's (set, binding) by register.
|
||||
bind_register: std.ArrayList(struct { class: u8, index: u32, space: u32, binding: u32, set: u32 }) = .empty,
|
||||
|
||||
pub fn shift(o: VkOptions, class: u8, set: u32) u32 {
|
||||
const k: usize = switch (class) {
|
||||
'b' => 0,
|
||||
't' => 1,
|
||||
's' => 2,
|
||||
'u' => 3,
|
||||
else => return 0,
|
||||
};
|
||||
var all: u32 = 0;
|
||||
for (o.shifts[k].items) |x| {
|
||||
if (x.set) |s0| {
|
||||
if (s0 == set) return x.shift;
|
||||
} else all = x.shift;
|
||||
}
|
||||
return all;
|
||||
}
|
||||
};
|
||||
|
||||
/// A descriptor declaration, in declaration order: SPIR-V numbers implicit
|
||||
/// bindings over all of them, used or not (as dxc).
|
||||
pub const BindingDecl = struct {
|
||||
/// The IR global (null: unused; it still takes a binding number).
|
||||
global: ?u32,
|
||||
reg: Binding = .{},
|
||||
/// `register(spaceN)` without a register.
|
||||
space_only: bool = false,
|
||||
/// [[vk::binding(binding, set)]], [[vk::counter_binding(binding)]].
|
||||
vk_binding: ?u32 = null,
|
||||
vk_set: ?u32 = null,
|
||||
vk_counter: ?u32 = null,
|
||||
/// Append / Consume buffers: their counter is numbered right after.
|
||||
acs: bool = false,
|
||||
/// `$Globals`.
|
||||
globals_buffer: bool = false,
|
||||
/// [[vk::combinedImageSampler]]: `s` registers shift like `t` ones.
|
||||
combined: bool = false,
|
||||
/// Resources in the declaration (array elements).
|
||||
count: u32 = 1,
|
||||
};
|
||||
|
||||
pub const Global = struct {
|
||||
|
|
@ -228,6 +291,8 @@ pub const Global = struct {
|
|||
/// `[[vk::shader_record_ext]]` / `[[vk::shader_record_nv]]` buffers
|
||||
/// (SPIR-V ShaderRecordBufferKHR storage).
|
||||
shader_record: bool = false,
|
||||
/// `[[vk::push_constant]]` buffers (SPIR-V PushConstant storage).
|
||||
push_constant: bool = false,
|
||||
};
|
||||
|
||||
pub const Stage = enum {
|
||||
|
|
@ -266,6 +331,11 @@ pub const SigElement = struct {
|
|||
stream: u32 = 0,
|
||||
/// One value per vertex of the input primitive (geometry shaders).
|
||||
per_vertex: bool = false,
|
||||
/// The semantic as written (`TEXCOORD`, `TEXCOORD3`).
|
||||
spelling: ?[]const u8 = null,
|
||||
/// [[vk::location(n)]], [[vk::index(n)]].
|
||||
vk_location: ?u32 = null,
|
||||
vk_index: ?u32 = null,
|
||||
};
|
||||
|
||||
pub const Primitive = enum(u8) { point = 1, line = 2, triangle = 3, line_adj = 6, triangle_adj = 7 };
|
||||
|
|
@ -370,6 +440,11 @@ pub const Module = struct {
|
|||
exports: std.ArrayList(u32) = .empty,
|
||||
/// Libraries: state object subobjects, in declaration order.
|
||||
subobjects: std.ArrayList(Subobject) = .empty,
|
||||
/// [[vk::constant_id(n)]] constants (SPIR-V).
|
||||
spec_constants: std.ArrayList(struct { name: []const u8, ty: TypeId, id: u32, value: Constant }) = .empty,
|
||||
/// Descriptor declarations in declaration order.
|
||||
binding_decls: std.ArrayList(BindingDecl) = .empty,
|
||||
vk: VkOptions = .{},
|
||||
/// -enable-16bit-types: half and 16-bit integers are native types.
|
||||
native_16bit: bool = false,
|
||||
/// Root signatures: version 1.0 or 1.1 (-force-rootsig-ver), and
|
||||
|
|
@ -530,6 +605,7 @@ fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !vo
|
|||
.mesh_output => |k| try w.print("mesh output {s}", .{@tagName(k)}),
|
||||
.mesh_payload => try w.print("mesh payload", .{}),
|
||||
.ray_incoming => |k| try w.print("ray incoming {s}", .{@tagName(k)}),
|
||||
.spec_constant => |k| try w.print("spec constant {d}", .{k}),
|
||||
.heap_resource => |h| try w.print("{s}[%{d}]", .{ if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap", h.index.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 }),
|
||||
|
|
|
|||
154
src/ir/lower.zig
154
src/ir/lower.zig
|
|
@ -55,6 +55,7 @@ pub fn lowerUnit(arena: Allocator, s: *Sema, opts: Options) Error!ir.Module {
|
|||
try l.drain();
|
||||
try l.m.exports.append(l.arena, fi);
|
||||
}
|
||||
try l.bindingDecls();
|
||||
return l.m;
|
||||
}
|
||||
const entry_fn = for (s.all_functions.items) |f| {
|
||||
|
|
@ -64,6 +65,7 @@ pub fn lowerUnit(arena: Allocator, s: *Sema, opts: Options) Error!ir.Module {
|
|||
return error.Unsupported;
|
||||
};
|
||||
try l.lowerEntry(entry_fn, opts.entry, opts.stage);
|
||||
try l.bindingDecls();
|
||||
return l.m;
|
||||
}
|
||||
|
||||
|
|
@ -132,6 +134,96 @@ const Lowerer = struct {
|
|||
try l.buildEntry(f, main, .{ .entry = name, .stage = stage });
|
||||
}
|
||||
|
||||
/// `[[vk::constant_id(n)]] const T x = v;` (SPIR-V only).
|
||||
fn isSpecConstant(l: *Lowerer, v: *const Variable) bool {
|
||||
if (!l.s.opts.spirv or v.storage != .global_uniform) return false;
|
||||
const d = v.decl orelse return false;
|
||||
return hasAttr(d.attrs, "vk::constant_id");
|
||||
}
|
||||
|
||||
fn specConstant(l: *Lowerer, v: *const Variable) Error!Ref {
|
||||
const k: u32 = for (l.m.spec_constants.items, 0..) |sc, i| {
|
||||
if (std.mem.eql(u8, sc.name, v.name)) break @intCast(i);
|
||||
} else blk: {
|
||||
const init_e = v.init orelse {
|
||||
l.unsupported(v.loc, "specialization constant '{s}' without an initializer", .{v.name});
|
||||
return error.Unsupported;
|
||||
};
|
||||
const c = l.s.evalConst(init_e) orelse {
|
||||
l.unsupported(v.loc, "specialization constant '{s}' with this initializer is not supported yet", .{v.name});
|
||||
return error.Unsupported;
|
||||
};
|
||||
const value: ir.Constant = switch (c) {
|
||||
.int => |x| .{ .int = x },
|
||||
.float => |x| .{ .float = x },
|
||||
.bool => |x| .{ .int = @intFromBool(x) },
|
||||
};
|
||||
try l.m.spec_constants.append(l.arena, .{ .name = v.name, .ty = v.type, .id = l.s.vkAttrInt(v.decl.?.attrs, "vk::constant_id") orelse 0, .value = value });
|
||||
break :blk @intCast(l.m.spec_constants.items.len - 1);
|
||||
};
|
||||
return l.b.add(.{ .op = .{ .spec_constant = k }, .ty = v.type });
|
||||
}
|
||||
|
||||
/// `[[vk::push_constant]] struct {...} pc;` (SPIR-V only; dxc's DXIL
|
||||
/// keeps it in `$Globals`).
|
||||
fn isPushConstantStruct(l: *Lowerer, v: *const Variable) bool {
|
||||
if (!l.s.opts.spirv or v.storage != .global_uniform) return false;
|
||||
const d = v.decl orelse return false;
|
||||
return hasAttr(d.attrs, "vk::push_constant") and l.s.types.get(v.type) == .@"struct";
|
||||
}
|
||||
|
||||
/// The module's descriptor declarations in declaration order, each with
|
||||
/// its IR global when used.
|
||||
fn bindingDecls(l: *Lowerer) Error!void {
|
||||
var globals_done = false;
|
||||
for (l.s.global_order.items) |gd| switch (gd) {
|
||||
.variable => |v| {
|
||||
if (!isObject(&l.s.types, v.type)) {
|
||||
if (v.storage != .global_uniform or globals_done or l.isPushConstantStruct(v) or l.isSpecConstant(v)) continue;
|
||||
globals_done = true;
|
||||
try l.m.binding_decls.append(l.arena, .{ .global = l.cbuffers.get(0), .globals_buffer = true });
|
||||
continue;
|
||||
}
|
||||
var et = v.type;
|
||||
while (l.s.types.get(et) == .array) et = l.s.types.get(et).array.elem;
|
||||
const r = switch (l.s.types.get(et)) {
|
||||
.resource => |r| r,
|
||||
else => null,
|
||||
};
|
||||
if (r) |res| if (res.kind == .other) continue;
|
||||
const d = v.decl orelse continue;
|
||||
if (isShaderRecord(d.attrs) or hasAttr(d.attrs, "vk::push_constant")) continue;
|
||||
var bd = try l.bindingDecl(d.semantics, d.attrs, l.globals.get(v));
|
||||
var at = v.type;
|
||||
while (l.s.types.get(at) == .array) : (at = l.s.types.get(at).array.elem) bd.count *= @max(1, l.s.types.get(at).array.len);
|
||||
if (r) |res| bd.acs = res.kind == .append_structured_buffer or res.kind == .consume_structured_buffer;
|
||||
try l.m.binding_decls.append(l.arena, bd);
|
||||
},
|
||||
.cbuffer => |d| {
|
||||
const cb = d.kind.cbuffer;
|
||||
if (isShaderRecord(cb.attrs) or hasAttr(cb.attrs, "vk::push_constant")) continue;
|
||||
try l.m.binding_decls.append(l.arena, try l.bindingDecl(cb.semantics, cb.attrs, l.cbuffers.get(@intFromPtr(d))));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
fn bindingDecl(l: *Lowerer, sems: []const ast.Semantic, attrs: []const ast.Attribute, global: ?u32) Error!ir.BindingDecl {
|
||||
var bd: ir.BindingDecl = .{ .global = global };
|
||||
for (sems) |sem| if (sem.kind == .register) {
|
||||
bd.reg = parseBinding(sem.values);
|
||||
bd.space_only = !bd.reg.explicit;
|
||||
};
|
||||
for (attrs) |a| {
|
||||
if (std.mem.eql(u8, a.name, "vk::binding") and a.args.len >= 1) {
|
||||
bd.vk_binding = @intCast(@max(0, l.s.evalInt(a.args[0]) orelse 0));
|
||||
if (a.args.len >= 2) bd.vk_set = @intCast(@max(0, l.s.evalInt(a.args[1]) orelse 0));
|
||||
}
|
||||
if (std.mem.eql(u8, a.name, "vk::counter_binding") and a.args.len >= 1) bd.vk_counter = @intCast(@max(0, l.s.evalInt(a.args[0]) orelse 0));
|
||||
if (std.mem.eql(u8, a.name, "vk::combinedImageSampler")) bd.combined = true;
|
||||
}
|
||||
return bd;
|
||||
}
|
||||
|
||||
/// The library's subobject declarations (`TriangleHitGroup hg = {...};`).
|
||||
fn subobjects(l: *Lowerer) Error!void {
|
||||
const Kind = ir.Subobject.Kind;
|
||||
|
|
@ -295,7 +387,8 @@ const Lowerer = struct {
|
|||
binding = parseBinding(sem.values);
|
||||
};
|
||||
const shader_record = if (v.decl) |d| isShaderRecord(d.attrs) else false;
|
||||
try l.m.globals.append(l.arena, .{ .name = v.name, .ty = v.type, .space = space, .binding = binding, .shader_record = shader_record });
|
||||
const push_constant = if (v.decl) |d| hasAttr(d.attrs, "vk::push_constant") else false;
|
||||
try l.m.globals.append(l.arena, .{ .name = v.name, .ty = v.type, .space = space, .binding = binding, .shader_record = shader_record, .push_constant = push_constant });
|
||||
const i: u32 = @intCast(l.m.globals.items.len - 1);
|
||||
try l.globals.put(l.arena, v, i);
|
||||
return i;
|
||||
|
|
@ -312,10 +405,12 @@ const Lowerer = struct {
|
|||
var binding: ir.Binding = .{};
|
||||
var is_tbuffer = false;
|
||||
var shader_record = false;
|
||||
var push_constant = false;
|
||||
if (v.block) |b| {
|
||||
const cb = b.kind.cbuffer;
|
||||
is_tbuffer = cb.tbuffer;
|
||||
shader_record = isShaderRecord(cb.attrs);
|
||||
push_constant = hasAttr(cb.attrs, "vk::push_constant");
|
||||
name = cb.name;
|
||||
for (cb.members) |m| if (m.kind == .@"var") {
|
||||
if (l.s.decl_vars.get(&m.kind.@"var")) |mv| try members.append(l.arena, mv);
|
||||
|
|
@ -325,7 +420,7 @@ const Lowerer = struct {
|
|||
};
|
||||
} else {
|
||||
for (l.s.uniform_globals.items) |g| {
|
||||
if (isObject(&l.s.types, g.type)) continue;
|
||||
if (isObject(&l.s.types, g.type) or l.isPushConstantStruct(g) or l.isSpecConstant(g)) continue;
|
||||
try members.append(l.arena, g);
|
||||
}
|
||||
}
|
||||
|
|
@ -333,7 +428,7 @@ const Lowerer = struct {
|
|||
info.* = .{ .name = name, .complete = true };
|
||||
for (members.items) |mv| try info.fields.append(l.arena, .{ .name = mv.name, .type = mv.type, .row_major = mv.row_major });
|
||||
const ty = try l.s.types.intern(.{ .@"struct" = info });
|
||||
try l.m.globals.append(l.arena, .{ .name = name, .ty = ty, .space = .cbuffer, .binding = binding, .tbuffer = is_tbuffer, .shader_record = shader_record });
|
||||
try l.m.globals.append(l.arena, .{ .name = name, .ty = ty, .space = .cbuffer, .binding = binding, .tbuffer = is_tbuffer, .shader_record = shader_record, .push_constant = push_constant });
|
||||
const gi: u32 = @intCast(l.m.globals.items.len - 1);
|
||||
try l.cbuffers.put(l.arena, key, gi);
|
||||
for (members.items, 0..) |mv, fi| try l.cbuffer_members.put(l.arena, mv, .{ .global = gi, .field = @intCast(fi) });
|
||||
|
|
@ -780,6 +875,7 @@ const Lowerer = struct {
|
|||
return l.bitRead(try l.b.load(try l.bitStorage(l.this_ptr, bf)), bf);
|
||||
},
|
||||
.variable => |v| {
|
||||
if (l.isSpecConstant(v)) return l.specConstant(v);
|
||||
// Integer `static const` scalars are constants.
|
||||
if (v.storage == .constant and v.init != null and l.s.types.get(v.type) == .scalar and !l.s.types.get(v.type).scalar.isFloat()) {
|
||||
if (l.s.evalInt(v.init.?)) |val| return l.b.constInt(try l.concrete(e.ty), val);
|
||||
|
|
@ -1303,6 +1399,16 @@ const Lowerer = struct {
|
|||
l.unsupported(e.loc, "resource '{s}' declared as a uniform is not supported yet", .{v.name});
|
||||
return error.Unsupported;
|
||||
}
|
||||
if (l.isPushConstantStruct(v)) {
|
||||
// A buffer of its own (SPIR-V push constants).
|
||||
const g = l.globals.get(v) orelse blk: {
|
||||
try l.m.globals.append(l.arena, .{ .name = v.name, .ty = v.type, .space = .cbuffer, .push_constant = true });
|
||||
const gi: u32 = @intCast(l.m.globals.items.len - 1);
|
||||
try l.globals.put(l.arena, v, gi);
|
||||
break :blk gi;
|
||||
};
|
||||
return l.b.add(.{ .op = .{ .global = g }, .ty = v.type, .ptr = .cbuffer });
|
||||
}
|
||||
const cm = try l.cbufferMember(v);
|
||||
const glob = l.m.globals.items[cm.global];
|
||||
const base = try l.b.add(.{ .op = .{ .global = cm.global }, .ty = glob.ty, .ptr = .cbuffer });
|
||||
|
|
@ -1491,11 +1597,13 @@ const Lowerer = struct {
|
|||
const SigAttrs = struct {
|
||||
interp: Interp = .{},
|
||||
row_major: bool = false,
|
||||
vk_location: ?u32 = null,
|
||||
vk_index: ?u32 = null,
|
||||
|
||||
/// A field's modifiers, inheriting the enclosing interpolation.
|
||||
fn field(outer: SigAttrs, fld: Field) SigAttrs {
|
||||
const own: u8 = @bitCast(fld.interp);
|
||||
return .{ .interp = if (own != 0) fld.interp else outer.interp, .row_major = fld.row_major };
|
||||
return .{ .interp = if (own != 0) fld.interp else outer.interp, .row_major = fld.row_major, .vk_location = fld.vk_location, .vk_index = fld.vk_index };
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -1503,9 +1611,20 @@ const Lowerer = struct {
|
|||
var r = el;
|
||||
r.interp = attrs.interp;
|
||||
r.row_major = attrs.row_major;
|
||||
r.vk_location = attrs.vk_location;
|
||||
r.vk_index = attrs.vk_index;
|
||||
return r;
|
||||
}
|
||||
|
||||
/// A parameter's (or, with the function's attributes, the return
|
||||
/// value's) signature modifiers.
|
||||
fn sigAttrs(l: *Lowerer, q: ast.Qualifiers, attrs: []const ast.Attribute) SigAttrs {
|
||||
var a = paramAttrs(q);
|
||||
a.vk_location = l.s.vkAttrInt(attrs, "vk::location");
|
||||
a.vk_index = l.s.vkAttrInt(attrs, "vk::index");
|
||||
return a;
|
||||
}
|
||||
|
||||
fn addInput(l: *Lowerer, entry: *ir.Entry, el: ir.SigElement) Error!Ref {
|
||||
if (l.patch_io) {
|
||||
try entry.patch_constants.append(l.arena, el);
|
||||
|
|
@ -1794,7 +1913,7 @@ const Lowerer = struct {
|
|||
const points = try l.arena.alloc(Ref, patch.count);
|
||||
for (points, 0..) |*v, k| {
|
||||
var next = first;
|
||||
v.* = try l.vertexIn(entry, patch.elem, semanticOf(pd.semantics), paramAttrs(pd.quals), @intCast(k), register and k == 0, &next, null, pd.name_loc);
|
||||
v.* = try l.vertexIn(entry, patch.elem, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), @intCast(k), register and k == 0, &next, null, pd.name_loc);
|
||||
}
|
||||
try l.b.store(local, try l.b.add(.{ .op = .{ .construct = points }, .ty = l.irType(pty) }));
|
||||
}
|
||||
|
|
@ -1866,7 +1985,7 @@ const Lowerer = struct {
|
|||
args[i] = try l.b.load(locals[i]);
|
||||
continue;
|
||||
}
|
||||
if (p.dir != .out) try l.b.store(locals[i], try l.entryInput(entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), pd.name_loc, pd.name));
|
||||
if (p.dir != .out) try l.b.store(locals[i], try l.entryInput(entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), pd.name_loc, pd.name));
|
||||
args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i];
|
||||
}
|
||||
const ret = try l.b.add(.{ .op = .{ .call = .{ .func = pci, .args = args } }, .ty = pcf.ret });
|
||||
|
|
@ -1875,7 +1994,7 @@ const Lowerer = struct {
|
|||
if (pcf.ret != TypeTable.void_type) try l.entryOutput(entry, pcf.ret, semanticOf(pcf.decl.ret_semantics), paramAttrs(pcf.decl.quals), ret, pcf.loc, "return value");
|
||||
for (pcf.decl.params, pcf.params, 0..) |pd, p, i| {
|
||||
if (p.dir == .in) continue;
|
||||
try l.entryOutput(entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), try l.b.load(locals[i]), pd.name_loc, pd.name);
|
||||
try l.entryOutput(entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), try l.b.load(locals[i]), pd.name_loc, pd.name);
|
||||
}
|
||||
l.b.terminate(.{ .ret = .none });
|
||||
entry.patch_wrapper = wrapper;
|
||||
|
|
@ -1934,12 +2053,12 @@ const Lowerer = struct {
|
|||
.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);
|
||||
try l.streamOut(&entry.outputs, arr.elem, semanticOf(pd.semantics), l.sigAttrs(q, pd.attrs), 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);
|
||||
try l.streamOut(&entry.patch_constants, arr.elem, semanticOf(pd.semantics), l.sigAttrs(q, pd.attrs), null, &next, 0, null, pd.name_loc);
|
||||
},
|
||||
.indices => {
|
||||
entry.mesh.max_primitives = arr.len;
|
||||
|
|
@ -1969,7 +2088,7 @@ const Lowerer = struct {
|
|||
// Everything else a domain shader reads is per patch.
|
||||
l.patch_io = true;
|
||||
defer l.patch_io = false;
|
||||
try l.b.store(locals[i], try l.entryInput(&entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), pd.name_loc, pd.name));
|
||||
try l.b.store(locals[i], try l.entryInput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), pd.name_loc, pd.name));
|
||||
args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i];
|
||||
continue;
|
||||
}
|
||||
|
|
@ -1982,7 +2101,7 @@ const Lowerer = struct {
|
|||
const verts = try l.arena.alloc(Ref, arr.len);
|
||||
for (verts, 0..) |*v, vx| {
|
||||
var next = first;
|
||||
v.* = try l.vertexIn(&entry, arr.elem, semanticOf(pd.semantics), paramAttrs(pd.quals), @intCast(vx), vx == 0, &next, null, pd.name_loc);
|
||||
v.* = try l.vertexIn(&entry, arr.elem, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), @intCast(vx), vx == 0, &next, null, pd.name_loc);
|
||||
}
|
||||
try l.b.store(locals[i], try l.b.add(.{ .op = .{ .construct = verts }, .ty = p.type }));
|
||||
args[i] = try l.b.load(locals[i]);
|
||||
|
|
@ -1998,7 +2117,7 @@ const Lowerer = struct {
|
|||
continue;
|
||||
}
|
||||
if (p.dir != .out) {
|
||||
const v = try l.entryInput(&entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), pd.name_loc, pd.name);
|
||||
const v = try l.entryInput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), pd.name_loc, pd.name);
|
||||
try l.b.store(locals[i], v);
|
||||
}
|
||||
args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i];
|
||||
|
|
@ -2007,7 +2126,7 @@ const Lowerer = struct {
|
|||
for (f.params, 0..) |p, i| if (l.s.types.get(p.type) != .stream) try call_args.append(l.arena, args[i]);
|
||||
std.debug.assert(call_args.items.len == n_args);
|
||||
const ret = try l.b.add(.{ .op = .{ .call = .{ .func = main, .args = call_args.items } }, .ty = f.ret });
|
||||
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), l.sigAttrs(f.decl.quals, f.decl.attrs), ret, f.loc, "return value");
|
||||
for (f.decl.params, f.params, 0..) |pd, p, i| {
|
||||
if (p.dir == .in or l.s.types.get(p.type) == .stream) continue;
|
||||
if (l.b.f.inst(locals[i]).ptr == .mesh) continue;
|
||||
|
|
@ -2016,7 +2135,7 @@ const Lowerer = struct {
|
|||
try l.b.store(ray_srcs[i], v);
|
||||
continue;
|
||||
}
|
||||
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), l.sigAttrs(pd.quals, pd.attrs), v, pd.name_loc, pd.name);
|
||||
}
|
||||
l.b.terminate(.{ .ret = .none });
|
||||
entry.wrapper = wrapper;
|
||||
|
|
@ -2075,6 +2194,11 @@ pub fn stringContents(a: Allocator, lit: []const u8) Allocator.Error![]const u8
|
|||
return out.items;
|
||||
}
|
||||
|
||||
fn hasAttr(attrs: []const ast.Attribute, name: []const u8) bool {
|
||||
for (attrs) |a| if (std.mem.eql(u8, a.name, name)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
fn isShaderRecord(attrs: []const ast.Attribute) bool {
|
||||
for (attrs) |a| {
|
||||
if (std.mem.eql(u8, a.name, "vk::shader_record_ext") or std.mem.eql(u8, a.name, "vk::shader_record_nv")) return true;
|
||||
|
|
@ -2118,6 +2242,7 @@ fn sigElement(semantic: []const u8, ty: TypeId) ir.SigElement {
|
|||
.semantic_index = index,
|
||||
.ty = ty,
|
||||
.system_value = std.ascii.startsWithIgnoreCase(semantic, "SV_"),
|
||||
.spelling = semantic,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -2127,6 +2252,7 @@ fn parseBinding(values: []const []const u8) ir.Binding {
|
|||
for (values) |v| {
|
||||
if (std.mem.startsWith(u8, v, "space")) {
|
||||
b.space = std.fmt.parseInt(u32, v[5..], 10) catch 0;
|
||||
b.space_given = true;
|
||||
} else if (v.len > 0 and std.mem.indexOfScalar(u8, "bcistu", std.ascii.toLower(v[0])) != null) {
|
||||
const end = std.mem.indexOfScalar(u8, v, '[') orelse v.len;
|
||||
b.class = std.ascii.toLower(v[0]);
|
||||
|
|
|
|||
|
|
@ -181,7 +181,7 @@ fn mapRefs(a: Allocator, xs: []const Ref, ctx: anytype) Allocator.Error![]const
|
|||
/// `op` with every operand passed through `ctx.map`.
|
||||
fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
|
||||
return switch (op) {
|
||||
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming => op,
|
||||
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant => op,
|
||||
.load => |p| .{ .load = ctx.map(p) },
|
||||
.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) } },
|
||||
|
|
|
|||
33
src/main.zig
33
src/main.zig
|
|
@ -23,6 +23,7 @@ const Options = struct {
|
|||
strip_rootsig: bool = false,
|
||||
rootsig_define: ?[]const u8 = null,
|
||||
rootsig_output: ?[]const u8 = null,
|
||||
vk: zdxc.ir.ir.VkOptions = .{},
|
||||
defines: std.ArrayList(front.preproc.Define) = .empty,
|
||||
include_dirs: std.ArrayList([]const u8) = .empty,
|
||||
empty: bool = false,
|
||||
|
|
@ -135,6 +136,37 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std
|
|||
.Qstrip_rootsignature => opts.strip_rootsig = true,
|
||||
.rootsig_define => opts.rootsig_define = v,
|
||||
.Frs => opts.rootsig_output = v,
|
||||
.fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift => {
|
||||
const k: usize = switch (id) {
|
||||
.fvk_b_shift => 0,
|
||||
.fvk_t_shift => 1,
|
||||
.fvk_s_shift => 2,
|
||||
else => 3,
|
||||
};
|
||||
const shift = std.fmt.parseInt(u32, a.values[0], 10) catch return cli.fail("invalid {s} shift '{s}'", .{ a.spelling, a.values[0] });
|
||||
const set: ?u32 = if (std.mem.eql(u8, a.values[1], "all")) null else std.fmt.parseInt(u32, a.values[1], 10) catch return cli.fail("invalid {s} space '{s}'", .{ a.spelling, a.values[1] });
|
||||
try opts.vk.shifts[k].append(arena, .{ .shift = shift, .set = set });
|
||||
},
|
||||
.fvk_bind_globals => opts.vk.bind_globals = .{
|
||||
std.fmt.parseInt(u32, a.values[0], 10) catch return cli.fail("invalid -fvk-bind-globals binding number: {s}", .{a.values[0]}),
|
||||
std.fmt.parseInt(u32, a.values[1], 10) catch return cli.fail("invalid -fvk-bind-globals set number: {s}", .{a.values[1]}),
|
||||
},
|
||||
.fvk_bind_register, .vkbr => {
|
||||
const reg = a.values[0];
|
||||
if (reg.len < 2 or std.mem.indexOfScalar(u8, "btsu", reg[0]) == null) return cli.fail("invalid -fvk-bind-register register '{s}'", .{reg});
|
||||
const num = struct {
|
||||
fn f(c: Cli, t: []const u8) !u32 {
|
||||
return std.fmt.parseInt(u32, t, 10) catch c.fail("invalid -fvk-bind-register number '{s}'", .{t});
|
||||
}
|
||||
}.f;
|
||||
try opts.vk.bind_register.append(arena, .{ .class = reg[0], .index = try num(cli, reg[1..]), .space = try num(cli, a.values[1]), .binding = try num(cli, a.values[2]), .set = try num(cli, a.values[3]) });
|
||||
},
|
||||
.auto_binding_space => opts.vk.auto_binding_space = std.fmt.parseInt(u32, v, 10) catch return cli.fail("invalid -auto-binding-space '{s}'", .{v}),
|
||||
.fvk_auto_shift_bindings => opts.vk.auto_shift = true,
|
||||
.fspv_flatten_resource_arrays => opts.vk.flatten_arrays = true,
|
||||
.fvk_stage_io_order_EQ => {
|
||||
if (std.mem.eql(u8, v, "alpha")) opts.vk.alpha_io_order = true else if (!std.mem.eql(u8, v, "decl")) return cli.fail("unknown -fvk-stage-io-order '{s}'", .{v});
|
||||
},
|
||||
._SLASH_WX => opts.warnings_as_errors = true,
|
||||
.no_warnings => opts.no_warnings = true,
|
||||
.W_Joined => {
|
||||
|
|
@ -296,6 +328,7 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
|
|||
};
|
||||
if (module) |*mm| {
|
||||
mm.native_16bit = opts.enable_16bit;
|
||||
mm.vk = opts.vk;
|
||||
mm.strip_rootsig = opts.strip_rootsig;
|
||||
if (opts.rootsig_ver) |rv| {
|
||||
if (std.mem.eql(u8, rv, "rootsig_1_0")) mm.rootsig_version = .v1_0 else if (!std.mem.eql(u8, rv, "rootsig_1_1")) return cli.fail("unknown root signature version '{s}'", .{rv});
|
||||
|
|
|
|||
|
|
@ -223,6 +223,9 @@ pub fn support(id: Id) Support {
|
|||
// Core compilation.
|
||||
.target_profile, .entrypoint, .Fo, .D, .I, .P, .Fi, .hlsl_version, .spirv, .enable_16bit_types, .fspv_target_env_EQ => .implemented,
|
||||
.Frs, .Qstrip_rootsignature, .force_rootsig_ver, .force_rootsig_ver_, .rootsig_define => .implemented,
|
||||
.auto_binding_space, .fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift, .fvk_bind_globals, .fvk_bind_register, .vkbr, .fvk_auto_shift_bindings, .fvk_stage_io_order_EQ, .fspv_flatten_resource_arrays => .implemented,
|
||||
// (Output is the same with or without the unoptimized-IR switch.)
|
||||
.fcgl => .ignored,
|
||||
// Diagnostics.
|
||||
._SLASH_WX, .no_warnings, .W_Joined, .Wno_vk_ignored_features, .Wno_vk_emulated_features => .implemented,
|
||||
.fdiagnostics_format_EQ, .ferror_limit_EQ, .fdiagnostics_color, .fdiagnostics_color_EQ => .implemented,
|
||||
|
|
@ -234,13 +237,13 @@ pub fn support(id: Id) Support {
|
|||
.VD, .validator_version => .implemented,
|
||||
|
||||
// Accepted for build-script compatibility; no effect yet.
|
||||
.Zpr, .Zpc, .Gis, .Gfa, .Gfp, .Ges, .Gec, .denorm, .all_resources_bound, .all_resources_bound_, .res_may_alias, .res_may_alias_, .pack_optimized, .pack_optimized_, .pack_prefix_stable, .pack_prefix_stable_, .ffinite_math_only, .fno_finite_math_only, .flegacy_macro_expansion, .flegacy_resource_reservation, .no_legacy_cbuf_layout, .not_use_legacy_cbuf_load_, .enable_payload_qualifiers, .disable_payload_qualifiers, .enable_lifetime_markers, .disable_lifetime_markers, .force_zero_store_lifetimes, .ignore_line_directives, .Qunused_arguments, .fdiagnostics_show_option, .fno_diagnostics_show_option, .fdiagnostics_show_category_EQ, ._vi, .verbose, .v, .encoding, .Wall, .Wdeprecated, ._all_warnings, .Fh, .Vn, .Fsh, .Fre, .Zss, .Zsb, .Qstrip_reflect, .Qstrip_debug, .Qstrip_priv, .Qkeep_reflect_in_dxil, .Qstrip_reflect_from_dxil, .auto_binding_space, .exports, .export_shaders_only, .default_linkage, .fvk_stage_io_order_EQ, .fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift, .fvk_bind_globals, .fvk_bind_register, .vkbr, .fvk_invert_y, .fvk_use_dx_position_w, .fvk_support_nonzero_base_instance, .fvk_support_nonzero_base_vertex, .fvk_use_gl_layout, .fvk_use_dx_layout, .fvk_use_scalar_layout, .fspv_use_legacy_buffer_matrix_order, .fspv_reflect, .fspv_extension_EQ, .fspv_flatten_resource_arrays, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_entrypoint_name_EQ, .fspv_enable_maximal_reconvergence, .fspv_use_vulkan_memory_model, .fspv_use_unknown_image_format, .fvk_auto_shift_bindings, .fspv_preserve_bindings, .fspv_preserve_interface, .Oconfig => .ignored,
|
||||
.Zpr, .Zpc, .Gis, .Gfa, .Gfp, .Ges, .Gec, .denorm, .all_resources_bound, .all_resources_bound_, .res_may_alias, .res_may_alias_, .pack_optimized, .pack_optimized_, .pack_prefix_stable, .pack_prefix_stable_, .ffinite_math_only, .fno_finite_math_only, .flegacy_macro_expansion, .flegacy_resource_reservation, .no_legacy_cbuf_layout, .not_use_legacy_cbuf_load_, .enable_payload_qualifiers, .disable_payload_qualifiers, .enable_lifetime_markers, .disable_lifetime_markers, .force_zero_store_lifetimes, .ignore_line_directives, .Qunused_arguments, .fdiagnostics_show_option, .fno_diagnostics_show_option, .fdiagnostics_show_category_EQ, ._vi, .verbose, .v, .encoding, .Wall, .Wdeprecated, ._all_warnings, .Fh, .Vn, .Fsh, .Fre, .Zss, .Zsb, .Qstrip_reflect, .Qstrip_debug, .Qstrip_priv, .Qkeep_reflect_in_dxil, .Qstrip_reflect_from_dxil, .exports, .export_shaders_only, .default_linkage, .fvk_invert_y, .fvk_use_dx_position_w, .fvk_support_nonzero_base_instance, .fvk_support_nonzero_base_vertex, .fvk_use_gl_layout, .fvk_use_dx_layout, .fvk_use_scalar_layout, .fspv_use_legacy_buffer_matrix_order, .fspv_reflect, .fspv_extension_EQ, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_entrypoint_name_EQ, .fspv_enable_maximal_reconvergence, .fspv_use_vulkan_memory_model, .fspv_use_unknown_image_format, .fspv_preserve_bindings, .fspv_preserve_interface, .Oconfig => .ignored,
|
||||
|
||||
// Dropped by design (see the zdxc plan).
|
||||
._SLASH_Zi, .Zs, .Fd, .Qembed_debug, .Qsource_in_debug_module, .Qpdb_in_private, .fspv_debug_EQ => .{ .unsupported = dropped_debug },
|
||||
.Fc, .Cc, .Ni, .No, .Lx, .dumpbin => .{ .unsupported = dropped_disasm },
|
||||
.recompile, .link, .ast_dump, .verify, .metal, .external_lib, .external_fn, .setprivate, .getprivate, .setrootsignature, .extractrootsignature, .verifyrootsignature, .rw_unchanged, .rw_skip_function_body, .rw_skip_static, .rw_global_extern_by_default, .rw_keep_user_macro, .rw_extract_entry_uniforms, .rw_remove_unused_globals, .rw_remove_unused_functions, .rw_line_directive, .rw_decl_global_cb, .import_binding_table, .binding_table_define, .ftime_report, .ftime_trace, .ftime_trace_EQ, .ftime_trace_granularity_EQ => .{ .unsupported = dropped_tooling },
|
||||
.Odump, .fcgl, .print_before_all, .print_before, .print_after_all, .print_after, .opt_disable, .opt_enable, .opt_select, .memdep_block_scan_limit, .fdisable_loc_tracking, .fnew_inlining_behavior, .preserve_intermediate_values, .skip_serialization, .d_Flag, .d_Joined, .ignore_opt_semdefs, .ignore_semdef, .override_semdef, .precise_output, .disable_exception_handling, .fspv_print_all, .fspv_max_id => .{ .unsupported = dropped_internal },
|
||||
.Odump, .print_before_all, .print_before, .print_after_all, .print_after, .opt_disable, .opt_enable, .opt_select, .memdep_block_scan_limit, .fdisable_loc_tracking, .fnew_inlining_behavior, .preserve_intermediate_values, .skip_serialization, .d_Flag, .d_Joined, .ignore_opt_semdefs, .ignore_semdef, .override_semdef, .precise_output, .disable_exception_handling, .fspv_print_all, .fspv_max_id => .{ .unsupported = dropped_internal },
|
||||
|
||||
else => .{ .unsupported = not_yet },
|
||||
};
|
||||
|
|
|
|||
|
|
@ -59,6 +59,9 @@ pub const Variable = struct {
|
|||
row_major: bool = false,
|
||||
};
|
||||
|
||||
/// A global variable or a cbuffer / tbuffer block.
|
||||
pub const GlobalDecl = union(enum) { variable: *Variable, cbuffer: *const ast.Decl };
|
||||
|
||||
/// What an expression refers to, recorded by Sema for lowering
|
||||
/// (`Expr.info` is an index into `Sema.resolutions` plus one).
|
||||
pub const Resolution = union(enum) {
|
||||
|
|
@ -185,6 +188,9 @@ pub const Sema = struct {
|
|||
/// `static` (and `static const`) globals and static members, in
|
||||
/// declaration order.
|
||||
static_globals: std.ArrayList(*Variable) = .empty,
|
||||
/// Global variables and cbuffer / tbuffer declarations in declaration
|
||||
/// order (SPIR-V numbers implicit bindings in this order).
|
||||
global_order: std.ArrayList(GlobalDecl) = .empty,
|
||||
current_block: ?*const ast.Decl = null,
|
||||
loop_depth: u32 = 0,
|
||||
switch_depth: u32 = 0,
|
||||
|
|
@ -1075,6 +1081,15 @@ pub const Sema = struct {
|
|||
return TypeTable.error_type;
|
||||
}
|
||||
|
||||
/// The constant argument of attribute `name` (`[[vk::location(2)]]`).
|
||||
pub fn vkAttrInt(s: *Sema, attrs: []const ast.Attribute, name: []const u8) ?u32 {
|
||||
for (attrs) |a| if (std.mem.eql(u8, a.name, name) and a.args.len >= 1) {
|
||||
const v = s.evalInt(a.args[0]) orelse return null;
|
||||
return if (v < 0) null else @intCast(v);
|
||||
};
|
||||
return null;
|
||||
}
|
||||
|
||||
fn arrayLen(s: *Sema, dim: ?*ast.Expr) Allocator.Error!u32 {
|
||||
const e = dim orelse return 0;
|
||||
_ = try s.expr(e);
|
||||
|
|
@ -1280,6 +1295,7 @@ pub const Sema = struct {
|
|||
s.err(sem.loc, "user defined constant buffer slots cannot be target specific", .{});
|
||||
}
|
||||
}
|
||||
if (s.instance_depth == 0) try s.global_order.append(s.arena, .{ .cbuffer = d });
|
||||
s.current_block = d;
|
||||
defer s.current_block = null;
|
||||
for (cb.members) |m| try s.decl(m, .cbuffer);
|
||||
|
|
@ -1469,7 +1485,7 @@ pub const Sema = struct {
|
|||
for (v.semantics) |sem| if (sem.kind == .semantic) {
|
||||
fsem = sem.values[0];
|
||||
};
|
||||
try info.fields.append(s.arena, .{ .name = v.name, .type = ft, .row_major = isRowMajor(fattrs), .semantic = fsem, .interp = interpOf(v.quals) });
|
||||
try info.fields.append(s.arena, .{ .name = v.name, .type = ft, .row_major = isRowMajor(fattrs), .semantic = fsem, .interp = interpOf(v.quals), .vk_location = s.vkAttrInt(v.attrs, "vk::location"), .vk_index = s.vkAttrInt(v.attrs, "vk::index"), .vk_offset = s.vkAttrInt(v.attrs, "vk::offset") });
|
||||
},
|
||||
.func => {},
|
||||
else => try s.decl(m, .member),
|
||||
|
|
@ -1871,6 +1887,7 @@ pub const Sema = struct {
|
|||
try s.decl_vars.put(s.arena, v, variable);
|
||||
if (ctx == .cbuffer) variable.block = s.current_block;
|
||||
if (storage == .global_uniform) try s.uniform_globals.append(s.arena, variable);
|
||||
if (storage == .global_uniform or (storage == .global_static and !q.static and ctx == .global)) try s.global_order.append(s.arena, .{ .variable = variable });
|
||||
if (storage == .global_static or storage == .constant or storage == .local_static) try s.static_globals.append(s.arena, variable);
|
||||
// Unsized arrays take their size from the initializer.
|
||||
if (v.init) |init_e| if (!is_auto) {
|
||||
|
|
|
|||
|
|
@ -342,6 +342,10 @@ pub const Field = struct {
|
|||
interp: Interp = .{},
|
||||
/// Hidden storage for consecutive bitfields (see StructInfo.bitfields).
|
||||
bits: bool = false,
|
||||
/// [[vk::location(n)]], [[vk::index(n)]], [[vk::offset(n)]].
|
||||
vk_location: ?u32 = null,
|
||||
vk_index: ?u32 = null,
|
||||
vk_offset: ?u32 = null,
|
||||
};
|
||||
|
||||
/// A bitfield member: `width` bits at `offset` in storage field `storage`.
|
||||
|
|
|
|||
|
|
@ -34,6 +34,9 @@ pub const Op = enum(u16) {
|
|||
type_pointer = 32,
|
||||
type_function = 33,
|
||||
constant_true = 41,
|
||||
spec_constant_true = 48,
|
||||
spec_constant_false = 49,
|
||||
spec_constant = 50,
|
||||
constant_false = 42,
|
||||
constant = 43,
|
||||
constant_composite = 44,
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ pub const Error = Allocator.Error || error{Unsupported};
|
|||
/// Marks a binding that is a recipe (see Emitter.resourceBinding).
|
||||
const recipe_tag: u32 = 0x8000_0000;
|
||||
|
||||
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, callable_data_khr = 5328, incoming_callable_data_khr = 5329, ray_payload_khr = 5338, hit_attribute_khr = 5339, incoming_ray_payload_khr = 5342, shader_record_buffer_khr = 5343 };
|
||||
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, callable_data_khr = 5328, incoming_callable_data_khr = 5329, ray_payload_khr = 5338, hit_attribute_khr = 5339, incoming_ray_payload_khr = 5342, shader_record_buffer_khr = 5343, push_constant = 9 };
|
||||
|
||||
const Capability = enum(u32) {
|
||||
shader = 1,
|
||||
|
|
@ -110,7 +110,7 @@ pub const TargetEnv = struct {
|
|||
pub fn emit(gpa: Allocator, m: *const ir.Module, diags: *diag.Diagnostics, env: TargetEnv) Error![]u8 {
|
||||
var arena_state = std.heap.ArenaAllocator.init(gpa);
|
||||
defer arena_state.deinit();
|
||||
var e: Emitter = .{ .arena = arena_state.allocator(), .b = .init(gpa), .m = m, .t = m.types, .diags = diags, .spv_minor = env.minor, .universal = env.universal };
|
||||
var e: Emitter = .{ .arena = arena_state.allocator(), .b = .init(gpa), .m = m, .t = m.types, .diags = diags, .spv_minor = env.minor, .universal = env.universal, .vk = m.vk };
|
||||
defer e.b.deinit();
|
||||
try e.module();
|
||||
return e.b.finish(0x00010000 | (@as(u32, env.minor) << 8));
|
||||
|
|
@ -154,6 +154,16 @@ const Emitter = struct {
|
|||
/// on the heap's binding.
|
||||
heap_vars: std.AutoHashMapUnmanaged(struct { bool, Id }, Id) = .empty,
|
||||
heap_bindings: [2]u32 = .{ 0, 0 },
|
||||
/// Descriptor bindings by global (and of their counters); bindings
|
||||
/// taken, by (set, binding).
|
||||
slots: []?Slot = &.{},
|
||||
counter_slots: []?Slot = &.{},
|
||||
used_bindings: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty,
|
||||
spec_ids: std.AutoHashMapUnmanaged(u32, Id) = .empty,
|
||||
/// Flattened resource arrays: a variable per element.
|
||||
flat_vars: std.AutoHashMapUnmanaged(u32, []const Id) = .empty,
|
||||
flat_iface: std.ArrayList(Id) = .empty,
|
||||
vk: ir.VkOptions = .{},
|
||||
/// Image types by (sampled type, dim, arrayed, ms, sampled, format).
|
||||
image_types: std.AutoHashMapUnmanaged([6]u32, Id) = .empty,
|
||||
sampled_image_types: std.AutoHashMapUnmanaged(Id, Id) = .empty,
|
||||
|
|
@ -575,6 +585,33 @@ const Emitter = struct {
|
|||
}
|
||||
}
|
||||
|
||||
/// A [[vk::constant_id]] constant: OpSpecConstant* with its SpecId.
|
||||
fn specConstant(e: *Emitter, k: u32) Error!Id {
|
||||
if (e.spec_ids.get(k)) |id| return id;
|
||||
const sc = e.m.spec_constants.items[k];
|
||||
const s = storageScalar(e.t.component(sc.ty).?);
|
||||
const ty_id = try e.scalarType(s);
|
||||
const id = e.b.newId();
|
||||
if (s == .bool) {
|
||||
try e.b.emit(.types_globals, if (intOf(sc.value) != 0) .spec_constant_true else .spec_constant_false, &.{ ty_id, id });
|
||||
} else {
|
||||
const bits: u64 = switch (s) {
|
||||
.float => @as(u32, @bitCast(@as(f32, @floatCast(floatOf(sc.value))))),
|
||||
.double => @bitCast(floatOf(sc.value)),
|
||||
.float16 => @as(u16, @bitCast(@as(f16, @floatCast(floatOf(sc.value))))),
|
||||
.int64, .uint64 => @bitCast(intOf(sc.value)),
|
||||
else => @as(u32, @truncate(@as(u64, @bitCast(intOf(sc.value))))),
|
||||
};
|
||||
if (s.size() == 8) {
|
||||
try e.b.emit(.types_globals, .spec_constant, &.{ ty_id, id, @truncate(bits), @truncate(bits >> 32) });
|
||||
} else try e.b.emit(.types_globals, .spec_constant, &.{ ty_id, id, @truncate(bits) });
|
||||
}
|
||||
try e.b.emit(.annotations, .decorate, &.{ id, 1, sc.id }); // SpecId
|
||||
try e.b.emitWithString(.debug_names, .name, &.{id}, sc.name, &.{});
|
||||
try e.spec_ids.put(e.arena, k, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
fn floatOf(c: ir.Constant) f64 {
|
||||
return switch (c) {
|
||||
.int => |i| @floatFromInt(i),
|
||||
|
|
@ -704,8 +741,9 @@ const Emitter = struct {
|
|||
}
|
||||
if (e.spv_minor >= 4) {
|
||||
// (Shader record buffers only where used: at most one each.)
|
||||
for (e.global_vars, e.m.globals.items) |v, g| if (v != 0 and !g.shader_record) try out.put(e.arena, v, {});
|
||||
for (e.global_vars, e.m.globals.items) |v, g| if (v != 0 and !g.shader_record and !g.push_constant) try out.put(e.arena, v, {});
|
||||
for (e.counter_vars) |v| if (v != 0) try out.put(e.arena, v, {});
|
||||
for (e.flat_iface.items) |v| try out.put(e.arena, v, {});
|
||||
}
|
||||
return out.keys();
|
||||
}
|
||||
|
|
@ -804,21 +842,20 @@ const Emitter = struct {
|
|||
const m = e.m;
|
||||
e.global_vars = try e.arena.alloc(Id, m.globals.items.len);
|
||||
|
||||
// Registers without an explicit binding take the next free one.
|
||||
var used: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty;
|
||||
for (m.globals.items) |g| if (g.binding.explicit) try used.put(e.arena, .{ g.binding.space, g.binding.index }, {});
|
||||
var next_free: u32 = 0;
|
||||
try e.findCounterGlobals();
|
||||
try e.assignBindings();
|
||||
for (m.globals.items, 0..) |g, gi| {
|
||||
switch (g.space) {
|
||||
.resource, .cbuffer => if (g.shader_record) {
|
||||
// Shader record buffers: std430, no descriptor.
|
||||
.resource, .cbuffer => if (ownStorage(g)) |sc| {
|
||||
// Shader record buffers and push constants: std430, no
|
||||
// descriptor.
|
||||
const st = e.t.get(if (g.space == .resource) e.t.get(g.ty).resource.elem else g.ty);
|
||||
if (st != .@"struct") return e.unsupported("this shader record buffer is not supported yet", .{});
|
||||
if (st != .@"struct") return e.unsupported("this buffer is not supported yet", .{});
|
||||
const block = e.b.newId();
|
||||
try e.layoutStruct(block, st.@"struct", .std430, try std.fmt.allocPrint(e.arena, "type.ShaderRecord.{s}", .{g.name}));
|
||||
try e.layoutStruct(block, st.@"struct", .std430, try std.fmt.allocPrint(e.arena, "type.{s}.{s}", .{ if (sc == .push_constant) "PushConstant" else "ShaderRecord", g.name }));
|
||||
try e.b.emit(.annotations, .decorate, &.{ block, 2 }); // Block
|
||||
const var_id = e.b.newId();
|
||||
try e.b.emit(.types_globals, .variable, &.{ try e.pointerType(.shader_record_buffer_khr, block), var_id, @backingInt(StorageClass.shader_record_buffer_khr) });
|
||||
try e.b.emit(.types_globals, .variable, &.{ try e.pointerType(sc, block), var_id, @backingInt(sc) });
|
||||
try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{});
|
||||
e.global_vars[gi] = var_id;
|
||||
continue;
|
||||
|
|
@ -827,17 +864,32 @@ const Emitter = struct {
|
|||
}
|
||||
switch (g.space) {
|
||||
.resource => {
|
||||
if (e.vk.flatten_arrays and e.t.get(g.ty) == .array and e.constantlyIndexed(@intCast(gi))) {
|
||||
// One variable per element, on consecutive bindings.
|
||||
var et = g.ty;
|
||||
var n: u32 = 1;
|
||||
while (e.t.get(et) == .array) : (et = e.t.get(et).array.elem) n *= e.t.get(et).array.len;
|
||||
if (n == 0) return e.unsupported("flattening unsized resource arrays is not supported", .{});
|
||||
const p = try e.resourcePointee(et);
|
||||
const slot = try e.slotOf(@intCast(gi), false);
|
||||
const ids = try e.arena.alloc(Id, n);
|
||||
for (ids, 0..) |*id, k| {
|
||||
id.* = e.b.newId();
|
||||
try e.b.emit(.types_globals, .variable, &.{ try e.pointerType(p.sc, p.ty), id.*, @backingInt(p.sc) });
|
||||
try e.b.emit(.annotations, .decorate, &.{ id.*, 34, slot.set }); // DescriptorSet
|
||||
try e.b.emit(.annotations, .decorate, &.{ id.*, 33, slot.binding + @as(u32, @intCast(k)) }); // Binding
|
||||
try e.b.emitWithString(.debug_names, .name, &.{id.*}, try std.fmt.allocPrint(e.arena, "{s}[{d}]", .{ g.name, k }), &.{});
|
||||
if (e.spv_minor >= 4) try e.flat_iface.append(e.arena, id.*);
|
||||
}
|
||||
try e.flat_vars.put(e.arena, @intCast(gi), ids);
|
||||
continue;
|
||||
}
|
||||
const var_id = e.b.newId();
|
||||
const p = try e.resourcePointee(g.ty);
|
||||
try e.b.emit(.types_globals, .variable, &.{ try e.pointerType(p.sc, p.ty), var_id, @backingInt(p.sc) });
|
||||
var binding = g.binding.index;
|
||||
if (!g.binding.explicit) {
|
||||
while (used.contains(.{ g.binding.space, next_free })) next_free += 1;
|
||||
binding = next_free;
|
||||
try used.put(e.arena, .{ g.binding.space, binding }, {});
|
||||
}
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 34, g.binding.space }); // DescriptorSet
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 33, binding }); // Binding
|
||||
const slot = try e.slotOf(@intCast(gi), false);
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 34, slot.set }); // DescriptorSet
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 33, slot.binding }); // Binding
|
||||
try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{});
|
||||
e.global_vars[gi] = var_id;
|
||||
},
|
||||
|
|
@ -852,14 +904,9 @@ const Emitter = struct {
|
|||
const ptr = try e.pointerType(sc, st);
|
||||
const var_id = e.b.newId();
|
||||
try e.b.emit(.types_globals, .variable, &.{ ptr, var_id, @backingInt(sc) });
|
||||
var binding = g.binding.index;
|
||||
if (!g.binding.explicit) {
|
||||
while (used.contains(.{ g.binding.space, next_free })) next_free += 1;
|
||||
binding = next_free;
|
||||
try used.put(e.arena, .{ g.binding.space, binding }, {});
|
||||
}
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 34, g.binding.space }); // DescriptorSet
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 33, binding }); // Binding
|
||||
const slot = try e.slotOf(@intCast(gi), false);
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 34, slot.set }); // DescriptorSet
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 33, slot.binding }); // Binding
|
||||
try e.b.emitWithString(.debug_names, .name, &.{st}, try std.fmt.allocPrint(e.arena, "type.{s}", .{g.name}), &.{});
|
||||
try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{});
|
||||
e.global_vars[gi] = var_id;
|
||||
|
|
@ -888,14 +935,11 @@ const Emitter = struct {
|
|||
if (hit) break true;
|
||||
} else false;
|
||||
if (!used_heap) continue;
|
||||
while (used.contains(.{ 0, next_free })) next_free += 1;
|
||||
try used.put(e.arena, .{ 0, next_free }, {});
|
||||
e.heap_bindings[@intFromBool(sampler)] = next_free;
|
||||
e.heap_bindings[@intFromBool(sampler)] = try e.nextBinding(0);
|
||||
}
|
||||
|
||||
// Hidden counters (as dxc): a `{ int }` buffer per structured buffer
|
||||
// that uses one, on the next free binding of its set.
|
||||
try e.findCounterGlobals();
|
||||
// that uses one.
|
||||
e.counter_vars = try e.arena.alloc(Id, m.globals.items.len);
|
||||
@memset(e.counter_vars, 0);
|
||||
for (m.globals.items, 0..) |g, gi| {
|
||||
|
|
@ -925,15 +969,187 @@ const Emitter = struct {
|
|||
}
|
||||
const var_id = e.b.newId();
|
||||
try e.b.emit(.types_globals, .variable, &.{ try e.pointerType(e.bufferSc(), cty), var_id, @backingInt(e.bufferSc()) });
|
||||
while (used.contains(.{ g.binding.space, next_free })) next_free += 1;
|
||||
try used.put(e.arena, .{ g.binding.space, next_free }, {});
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 34, g.binding.space }); // DescriptorSet
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 33, next_free }); // Binding
|
||||
const slot = try e.slotOf(@intCast(gi), true);
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 34, slot.set }); // DescriptorSet
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 33, slot.binding }); // Binding
|
||||
try e.b.emitWithString(.debug_names, .name, &.{var_id}, try std.fmt.allocPrint(e.arena, "counter.var.{s}", .{g.name}), &.{});
|
||||
e.counter_vars[gi] = var_id;
|
||||
}
|
||||
}
|
||||
|
||||
const Slot = struct { set: u32, binding: u32 };
|
||||
|
||||
/// Descriptor set and binding of every resource and counter, as dxc
|
||||
/// numbers them: [[vk::binding]] (and [[vk::counter_binding]]) first,
|
||||
/// then `register()` with the shift options, then the rest in
|
||||
/// declaration order on the next free bindings (Append / Consume
|
||||
/// counters right after their buffer, other counters at the end).
|
||||
fn assignBindings(e: *Emitter) Error!void {
|
||||
const m = e.m;
|
||||
e.slots = try e.arena.alloc(?Slot, m.globals.items.len);
|
||||
e.counter_slots = try e.arena.alloc(?Slot, m.globals.items.len);
|
||||
@memset(e.slots, null);
|
||||
@memset(e.counter_slots, null);
|
||||
const Var = struct {
|
||||
bd: ir.BindingDecl,
|
||||
counter: bool,
|
||||
/// Bindings taken (array elements, when flattened).
|
||||
fn n(v: @This(), flatten: bool) u32 {
|
||||
return if (flatten and !v.counter) v.bd.count else 1;
|
||||
}
|
||||
};
|
||||
var vars: std.ArrayList(Var) = .empty;
|
||||
var declared: std.AutoHashMapUnmanaged(u32, void) = .empty;
|
||||
for (m.binding_decls.items) |bd| {
|
||||
try vars.append(e.arena, .{ .bd = bd, .counter = false });
|
||||
if (bd.acs) try vars.append(e.arena, .{ .bd = bd, .counter = true });
|
||||
if (bd.global) |g| try declared.put(e.arena, g, {});
|
||||
}
|
||||
// Resources with no declaration of their own (none in practice),
|
||||
// and counters of RW structured buffers, in the order first used.
|
||||
for (m.globals.items, 0..) |g, gi| {
|
||||
if (g.space != .resource and g.space != .cbuffer) continue;
|
||||
if (g.shader_record or g.push_constant or declared.contains(@intCast(gi))) continue;
|
||||
try vars.append(e.arena, .{ .bd = .{ .global = @intCast(gi), .reg = g.binding }, .counter = false });
|
||||
}
|
||||
for (m.globals.items, 0..) |_, gi| {
|
||||
if (!e.needsCounter(@intCast(gi))) continue;
|
||||
const acs = for (m.binding_decls.items) |bd| {
|
||||
if (bd.global == @as(u32, @intCast(gi))) break bd.acs;
|
||||
} else false;
|
||||
if (acs) continue;
|
||||
const bd = for (m.binding_decls.items) |bd| {
|
||||
if (bd.global == @as(u32, @intCast(gi))) break bd;
|
||||
} else ir.BindingDecl{ .global = @intCast(gi), .reg = m.globals.items[gi].binding };
|
||||
try vars.append(e.arena, .{ .bd = bd, .counter = true });
|
||||
}
|
||||
const record = struct {
|
||||
fn f(em: *Emitter, v: Var, slot: Slot) void {
|
||||
const g = v.bd.global orelse return;
|
||||
if (v.counter) em.counter_slots[g] = slot else em.slots[g] = slot;
|
||||
}
|
||||
}.f;
|
||||
const default_set = e.vk.auto_binding_space;
|
||||
if (e.vk.bind_register.items.len > 0) {
|
||||
// Every resource bound by its register.
|
||||
for (vars.items) |v| {
|
||||
if (v.counter) return e.unsupported("-fvk-bind-register for RW/Append/Consume StructuredBuffer unimplemented", .{});
|
||||
if (v.bd.reg.explicit) {
|
||||
const space = if (v.bd.reg.space_given) v.bd.reg.space else default_set;
|
||||
const hit = for (e.vk.bind_register.items) |br| {
|
||||
if (br.class == v.bd.reg.class and br.index == v.bd.reg.index and br.space == space) break br;
|
||||
} else return e.unsupported("missing -fvk-bind-register for resource", .{});
|
||||
record(e, v, .{ .set = hit.set, .binding = hit.binding });
|
||||
} else if (v.bd.globals_buffer) {
|
||||
const bg = e.vk.bind_globals orelse return e.unsupported("-fvk-bind-register requires Globals buffer to be bound with -fvk-bind-globals", .{});
|
||||
record(e, v, .{ .set = bg[1], .binding = bg[0] });
|
||||
} else return e.unsupported("-fvk-bind-register requires register annotations on all resources", .{});
|
||||
}
|
||||
return;
|
||||
}
|
||||
const regSet = struct {
|
||||
fn f(bd: ir.BindingDecl, dflt: u32) u32 {
|
||||
if (bd.vk_set) |s0| return s0;
|
||||
if (bd.vk_binding != null) return dflt;
|
||||
if (bd.reg.explicit or bd.space_only) return if (bd.reg.space_given) bd.reg.space else dflt;
|
||||
return dflt;
|
||||
}
|
||||
}.f;
|
||||
// [[vk::binding]] / [[vk::counter_binding]].
|
||||
for (vars.items) |v| {
|
||||
if (v.counter) {
|
||||
const b = v.bd.vk_counter orelse continue;
|
||||
const set = regSet(v.bd, default_set);
|
||||
try e.useBindings(set, b, 1);
|
||||
record(e, v, .{ .set = set, .binding = b });
|
||||
} else if (v.bd.vk_binding) |b| {
|
||||
const set = v.bd.vk_set orelse default_set;
|
||||
try e.useBindings(set, b, v.n(e.vk.flatten_arrays));
|
||||
record(e, v, .{ .set = set, .binding = b });
|
||||
}
|
||||
}
|
||||
// register(), shifted.
|
||||
for (vars.items) |v| {
|
||||
if (v.counter or v.bd.vk_binding != null or !v.bd.reg.explicit) continue;
|
||||
const set = if (v.bd.reg.space_given) v.bd.reg.space else default_set;
|
||||
const class: u8 = if (v.bd.reg.class == 's' and v.bd.combined) 't' else v.bd.reg.class;
|
||||
const b = v.bd.reg.index + e.vk.shift(class, set);
|
||||
try e.useBindings(set, b, v.n(e.vk.flatten_arrays));
|
||||
record(e, v, .{ .set = set, .binding = b });
|
||||
}
|
||||
// The rest, in order.
|
||||
for (vars.items) |v| {
|
||||
if (v.counter) {
|
||||
if (v.bd.vk_counter != null) continue;
|
||||
const set = regSet(v.bd, default_set);
|
||||
record(e, v, .{ .set = set, .binding = try e.nextBindingFrom(set, if (e.vk.auto_shift) e.vk.shift('u', set) else 0) });
|
||||
} else if (v.bd.vk_binding == null and !v.bd.reg.explicit) {
|
||||
if (v.bd.globals_buffer and e.vk.bind_globals != null) {
|
||||
const bg = e.vk.bind_globals.?;
|
||||
record(e, v, .{ .set = bg[1], .binding = bg[0] });
|
||||
continue;
|
||||
}
|
||||
const set = if (v.bd.space_only and v.bd.reg.space_given) v.bd.reg.space else default_set;
|
||||
const shift = if (e.vk.auto_shift) e.vk.shift(e.implicitClass(v.bd), set) else 0;
|
||||
record(e, v, .{ .set = set, .binding = try e.nextBindings(set, shift, v.n(e.vk.flatten_arrays)) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn useBinding(e: *Emitter, set: u32, binding: u32) Error!void {
|
||||
try e.used_bindings.put(e.arena, .{ set, binding }, {});
|
||||
}
|
||||
|
||||
fn useBindings(e: *Emitter, set: u32, binding: u32, n: u32) Error!void {
|
||||
for (0..n) |k| try e.useBinding(set, binding + @as(u32, @intCast(k)));
|
||||
}
|
||||
|
||||
/// The first `n` consecutive free bindings from `start`.
|
||||
fn nextBindings(e: *Emitter, set: u32, start: u32, n: u32) Error!u32 {
|
||||
var b = start;
|
||||
while (true) : (b += 1) {
|
||||
const free = for (0..n) |k| {
|
||||
if (e.used_bindings.contains(.{ set, b + @as(u32, @intCast(k)) })) break false;
|
||||
} else true;
|
||||
if (free) break;
|
||||
}
|
||||
try e.useBindings(set, b, n);
|
||||
return b;
|
||||
}
|
||||
|
||||
fn nextBinding(e: *Emitter, set: u32) Error!u32 {
|
||||
return e.nextBindingFrom(set, 0);
|
||||
}
|
||||
|
||||
fn nextBindingFrom(e: *Emitter, set: u32, start: u32) Error!u32 {
|
||||
var b: u32 = start;
|
||||
while (e.used_bindings.contains(.{ set, b })) b += 1;
|
||||
try e.useBinding(set, b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// The register class a resource without one would have.
|
||||
fn implicitClass(e: *Emitter, bd: ir.BindingDecl) u8 {
|
||||
if (bd.globals_buffer) return 'b';
|
||||
const g = bd.global orelse return 't';
|
||||
const glob = e.m.globals.items[g];
|
||||
if (glob.space == .cbuffer) return if (glob.tbuffer) 't' else 'b';
|
||||
var t = glob.ty;
|
||||
while (e.t.get(t) == .array) t = e.t.get(t).array.elem;
|
||||
return switch (e.t.get(t)) {
|
||||
.sampler => 's',
|
||||
.resource => |r| if (r.kind == .constant_buffer) 'b' else if (r.kind.isWritable() or r.kind == .append_structured_buffer or r.kind == .consume_structured_buffer) 'u' else 't',
|
||||
else => 't',
|
||||
};
|
||||
}
|
||||
|
||||
/// The binding of global `gi` (or of its counter).
|
||||
fn slotOf(e: *Emitter, gi: u32, counter: bool) Error!Slot {
|
||||
const s0 = if (counter) e.counter_slots[gi] else e.slots[gi];
|
||||
if (s0) |x| return x;
|
||||
return .{ .set = 0, .binding = try e.nextBinding(0) };
|
||||
}
|
||||
|
||||
/// Append/Consume buffers, and structured buffers whose counter is
|
||||
/// incremented or decremented somewhere.
|
||||
fn needsCounter(e: *Emitter, gi: u32) bool {
|
||||
|
|
@ -1169,7 +1385,7 @@ const Emitter = struct {
|
|||
e.st.patches = try e.arena.alloc(Interface, entry.patch_constants.items.len);
|
||||
if (entry.stage == .hull or entry.stage == .domain) try e.cap(.tessellation);
|
||||
// Variables needing a Location, assigned once all exist.
|
||||
const Located = struct { var_id: Id, key: []const u8, count: u32, input: bool, target: ?u32 };
|
||||
const Located = struct { var_id: Id, key: []const u8, count: u32, input: bool, target: ?u32, loc: ?u32 = null, index: ?u32 = null };
|
||||
var located: std.ArrayList(Located) = .empty;
|
||||
const lists = [_][]const ir.SigElement{ entry.inputs.items, entry.outputs.items, entry.patch_constants.items };
|
||||
const ifaces = [_][]Interface{ e.st.inputs, e.st.outputs, e.st.patches };
|
||||
|
|
@ -1247,7 +1463,7 @@ const Emitter = struct {
|
|||
} else {
|
||||
const key = if (el.semantic_index > 0) try std.fmt.allocPrint(e.arena, "{s}{d}", .{ el.semantic, el.semantic_index }) else el.semantic;
|
||||
const target: ?u32 = if (std.ascii.eqlIgnoreCase(el.semantic, "SV_Target")) el.semantic_index else null;
|
||||
try located.append(e.arena, .{ .var_id = var_id, .key = key, .count = try e.locationCount(vty), .input = input, .target = target });
|
||||
try located.append(e.arena, .{ .var_id = var_id, .key = key, .count = try e.locationCount(vty), .input = input, .target = target, .loc = el.vk_location, .index = el.vk_index });
|
||||
// Interpolation (as dxc: pixel inputs and vertex
|
||||
// outputs; integers are always flat).
|
||||
if ((input and entry.stage == .pixel) or (!input and entry.stage == .vertex)) {
|
||||
|
|
@ -1270,7 +1486,8 @@ const Emitter = struct {
|
|||
try e.cap(.geometry_streams);
|
||||
try e.b.emit(.annotations, .decorate, &.{ var_id, 29, el.stream }); // Stream
|
||||
}
|
||||
const name = try std.fmt.allocPrint(e.arena, "{s}.var.{s}{d}", .{ if (input) "in" else "out", el.semantic, el.semantic_index });
|
||||
// (Named after the semantic as written, as dxc.)
|
||||
const name = if (el.spelling) |sp| try std.fmt.allocPrint(e.arena, "{s}.var.{s}", .{ if (input) "in" else "out", sp }) else try std.fmt.allocPrint(e.arena, "{s}.var.{s}{d}", .{ if (input) "in" else "out", el.semantic, el.semantic_index });
|
||||
try e.b.emitWithString(.debug_names, .name, &.{var_id}, name, &.{});
|
||||
iface.* = .{ .var_id = var_id, .ty = vty, .elem_array = bi != null and e.t.get(bi.?.ty) == .array };
|
||||
try e.useVar(var_id);
|
||||
|
|
@ -1282,17 +1499,22 @@ const Emitter = struct {
|
|||
for ([_]bool{ true, false }) |input| {
|
||||
var vars: std.ArrayList(Located) = .empty;
|
||||
for (located.items) |x| if (x.input == input) try vars.append(e.arena, x);
|
||||
if ((!input and entry.stage == .hull) or (input and entry.stage == .domain)) {
|
||||
if (e.vk.alpha_io_order or (!input and entry.stage == .hull) or (input and entry.stage == .domain)) {
|
||||
std.sort.insertion(Located, vars.items, {}, struct {
|
||||
fn lt(_: void, a: Located, b: Located) bool {
|
||||
return std.mem.order(u8, a.key, b.key) == .lt;
|
||||
}
|
||||
}.lt);
|
||||
}
|
||||
// [[vk::location]] on one needs it on all.
|
||||
var explicit: usize = 0;
|
||||
for (vars.items) |x| explicit += @intFromBool(x.loc != null);
|
||||
if (explicit != 0 and explicit != vars.items.len) return e.unsupported("partial explicit stage {s} location assignment via vk::location(X) unsupported", .{if (input) "input" else "output"});
|
||||
var next: u32 = 0;
|
||||
for (vars.items) |x| {
|
||||
const loc = x.target orelse next;
|
||||
const loc = x.loc orelse x.target orelse next;
|
||||
try e.b.emit(.annotations, .decorate, &.{ x.var_id, 30, loc }); // Location
|
||||
if (x.index) |ix| try e.b.emit(.annotations, .decorate, &.{ x.var_id, 32, ix }); // Index
|
||||
next = @max(next, loc) + x.count;
|
||||
}
|
||||
}
|
||||
|
|
@ -1303,7 +1525,8 @@ const Emitter = struct {
|
|||
fn locationCount(e: *Emitter, ty: TypeId) Error!u32 {
|
||||
return switch (e.t.get(ty)) {
|
||||
.array => |a| a.len * try e.locationCount(a.elem),
|
||||
.matrix => |m| m.rows * (if (m.elem.size() == 8 and m.cols > 2) @as(u32, 2) else 1),
|
||||
// (1xN and Nx1 matrices are vectors.)
|
||||
.matrix => |m| if (m.rows == 1 or m.cols == 1) (if (m.elem.size() == 8 and m.rows * m.cols > 2) @as(u32, 2) else 1) else m.rows * (if (m.elem.size() == 8 and m.cols > 2) @as(u32, 2) else 1),
|
||||
.vector => |v| if (v.elem.size() == 8 and v.len > 2) 2 else 1,
|
||||
else => 1,
|
||||
};
|
||||
|
|
@ -1624,6 +1847,7 @@ const Emitter = struct {
|
|||
const ri = r.index();
|
||||
switch (i.op) {
|
||||
.constant, .param, .local_var => {},
|
||||
.spec_constant => |k| e.vals[ri] = try e.specConstant(k),
|
||||
.ray_incoming => |k| e.vals[ri] = try e.rayVar(switch (k) {
|
||||
.payload => .incoming_ray_payload_khr,
|
||||
.attributes => .hit_attribute_khr,
|
||||
|
|
@ -1631,8 +1855,9 @@ const Emitter = struct {
|
|||
}, i.ty),
|
||||
.global => |g| {
|
||||
e.vals[ri] = e.global_vars[g];
|
||||
if (e.m.globals.items[g].shader_record) {
|
||||
try e.useVar(e.global_vars[g]);
|
||||
if (ownStorage(e.m.globals.items[g]) != null) {
|
||||
// (Interfaces list them from SPIR-V 1.4.)
|
||||
if (e.spv_minor >= 4) try e.useVar(e.global_vars[g]);
|
||||
e.ptr_layouts[ri] = .{ .rules = .std430, .row_major = false };
|
||||
return;
|
||||
}
|
||||
|
|
@ -1742,8 +1967,9 @@ const Emitter = struct {
|
|||
try e.mesh_places.put(e.arena, ri, mp);
|
||||
return;
|
||||
}
|
||||
const shader_record = e.inShaderRecord(a.base);
|
||||
const sc: StorageClass = if (shader_record) .shader_record_buffer_khr else if (into_cb) .uniform else 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 own = e.ownBuffer(a.base);
|
||||
const shader_record = own != null;
|
||||
const sc: StorageClass = if (own) |x| x else if (into_cb) .uniform else 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,
|
||||
.private => .private,
|
||||
.groupshared => if (e.payload_global != null and e.rootGlobal(a.base) == e.payload_global) .task_payload_workgroup else .workgroup,
|
||||
|
|
@ -2419,7 +2645,43 @@ const Emitter = struct {
|
|||
|
||||
/// `array[i]...` into an array of resources: an access chain to the
|
||||
/// element (or sub-array) variable.
|
||||
/// Whether every access to resource array `gi` uses constant indices
|
||||
/// (and nothing else uses the array itself).
|
||||
fn constantlyIndexed(e: *Emitter, gi: u32) bool {
|
||||
for (e.m.functions.items) |f| {
|
||||
for (f.insts.items, 0..) |inst, k| {
|
||||
if (inst.op != .global or inst.op.global != gi) continue;
|
||||
for (f.insts.items) |user| switch (user.op) {
|
||||
.access => |a| if (a.base.index() == k) {
|
||||
for (a.indices) |x| if (f.inst(x).op != .constant) return false;
|
||||
},
|
||||
.call => |c| for (c.args) |x| if (x.index() == k) return false,
|
||||
.store => |st| if (st.value.index() == k) return false,
|
||||
else => {},
|
||||
};
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
fn resourceArrayAccess(e: *Emitter, ri: usize, a: @FieldType(ir.Op, "access"), ty: TypeId) Error!void {
|
||||
if (e.f.inst(a.base).op == .global) if (e.flat_vars.get(e.f.inst(a.base).op.global)) |ids| {
|
||||
// A flattened array: the element's own variable.
|
||||
var at = e.f.inst(a.base).ty;
|
||||
var k: u32 = 0;
|
||||
for (a.indices) |x| {
|
||||
const len = e.t.get(at).array.len;
|
||||
const c = switch (e.f.inst(x).op) {
|
||||
.constant => |c| c.int,
|
||||
else => return e.unsupported("dynamic indices into flattened resource arrays are not supported", .{}),
|
||||
};
|
||||
k = k * len + @as(u32, @intCast(c));
|
||||
at = e.t.get(at).array.elem;
|
||||
}
|
||||
if (e.t.get(at) == .array) return e.unsupported("sub-arrays of flattened resource arrays are not supported", .{});
|
||||
e.vals[ri] = ids[k];
|
||||
return;
|
||||
};
|
||||
const p = try e.resourcePointee(ty);
|
||||
var ops: std.ArrayList(u32) = .empty;
|
||||
const id = e.b.newId();
|
||||
|
|
@ -3189,16 +3451,24 @@ const Emitter = struct {
|
|||
}
|
||||
|
||||
/// The global a resource value comes from (`load (global g)`).
|
||||
/// Whether pointer / resource `r` reaches into a shader record buffer.
|
||||
fn inShaderRecord(e: *Emitter, r: Ref) bool {
|
||||
/// The storage class of shader record buffers and push constants.
|
||||
fn ownStorage(g: ir.Global) ?StorageClass {
|
||||
if (g.shader_record) return .shader_record_buffer_khr;
|
||||
if (g.push_constant) return .push_constant;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The storage of the shader record buffer / push constants pointer /
|
||||
/// resource `r` reaches into, if any.
|
||||
fn ownBuffer(e: *Emitter, r: Ref) ?StorageClass {
|
||||
var x = r;
|
||||
while (e.f.inst(x).op == .access) x = e.f.inst(x).op.access.base;
|
||||
if (e.f.inst(x).op == .global) return e.m.globals.items[e.f.inst(x).op.global].shader_record;
|
||||
if (e.f.inst(x).op == .global) return ownStorage(e.m.globals.items[e.f.inst(x).op.global]);
|
||||
// ConstantBuffer<T> values (through locals and parameters).
|
||||
const t = e.t.get(e.f.inst(x).ty);
|
||||
if (t != .resource or t.resource.kind != .constant_buffer) return false;
|
||||
const g = e.globalOf(x) orelse return false;
|
||||
return e.m.globals.items[g].shader_record;
|
||||
if (t != .resource or t.resource.kind != .constant_buffer) return null;
|
||||
const g = e.globalOf(x) orelse return null;
|
||||
return ownStorage(e.m.globals.items[g]);
|
||||
}
|
||||
|
||||
fn globalOf(e: *Emitter, r: Ref) ?u32 {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
#!/bin/sh
|
||||
# SPIR-V output checks beyond validation: every test/spirv/*.hlsl must pass
|
||||
# spirv-val, and every `// ZCHECK: text` line must appear in zdxc's
|
||||
# disassembly (`{{.*}}` matches anything).
|
||||
# disassembly (`{{.*}}` matches anything), and descriptor bindings and
|
||||
# interface locations must match dxc's.
|
||||
#
|
||||
# Usage: test/spirv/check.sh <path-to-zdxc>
|
||||
set -u
|
||||
|
|
@ -9,6 +10,7 @@ ZDXC=$1
|
|||
DXC_BUILD=${DXC_BUILD:-../build}
|
||||
VAL=$DXC_BUILD/oracle-spirv-tools/tools/spirv-val
|
||||
DIS=$DXC_BUILD/oracle-spirv-tools/tools/spirv-dis
|
||||
DXC=$DXC_BUILD/bin/dxc
|
||||
TMP=$(mktemp -d)
|
||||
trap 'rm -rf "$TMP"' EXIT
|
||||
pass=0
|
||||
|
|
@ -25,6 +27,13 @@ for f in test/spirv/*.hlsl; do
|
|||
fi
|
||||
"$DIS" "$TMP/z.spv" > "$TMP/z.dis" 2>&1
|
||||
ok=1
|
||||
# Bindings and locations must match dxc's (when dxc compiles the test).
|
||||
if "$DXC" -spirv -T "$profile" $flags -fspv-target-env="${env:-vulkan1.0}" "$f" -Fo "$TMP/d.spv" > /dev/null 2>&1; then
|
||||
"$DIS" "$TMP/d.spv" > "$TMP/d.dis" 2>&1
|
||||
if ! python3 test/spirv/compare_bindings.py "$TMP/d.dis" "$TMP/z.dis" > "$TMP/bind" 2>&1; then
|
||||
ok=0; echo "FAIL $name: bindings / locations differ from dxc"; head -5 "$TMP/bind"
|
||||
fi
|
||||
fi
|
||||
sed -n 's|^// ZCHECK: *||p' "$f" > "$TMP/checks"
|
||||
while IFS= read -r pat; do
|
||||
re=$(printf '%s\n' "$pat" | sed -e 's/[][\.*^$()+?|{}]/\\&/g' -e 's/\\{\\{\\\.\\\*\\}\\}/.*/g')
|
||||
|
|
|
|||
|
|
@ -0,0 +1,31 @@
|
|||
"""Exits non-zero if the descriptor bindings and interface locations of two
|
||||
SPIR-V disassemblies differ (variables present in both, keyed by name).
|
||||
Usage: compare_bindings.py <expected.dis> <actual.dis>"""
|
||||
import re, sys
|
||||
def parse(path):
|
||||
names = {}; decs = {}; sc = {}
|
||||
for line in open(path):
|
||||
m = re.match(r'\s*OpName (%\S+) "(.*)"', line)
|
||||
if m: names[m.group(1)] = m.group(2); continue
|
||||
m = re.match(r'\s*OpDecorate (%\S+) (DescriptorSet|Binding|Location|Component|Index|BuiltIn|InputAttachmentIndex|SpecId) (\S+)', line)
|
||||
if m: decs.setdefault(m.group(1), {})[m.group(2)] = m.group(3); continue
|
||||
m = re.match(r'\s*(%\S+) = OpVariable %\S+ (\S+)', line)
|
||||
if m: sc[m.group(1)] = m.group(2)
|
||||
out = {}
|
||||
for v, s in sc.items():
|
||||
if s in ('Function', 'Private', 'Workgroup'): continue
|
||||
n = names.get(v, None)
|
||||
if n is None:
|
||||
bi = decs.get(v, {}).get('BuiltIn')
|
||||
if not bi: continue
|
||||
n = 'builtin.' + bi + '.' + s
|
||||
pass
|
||||
d = dict(decs.get(v, {})); d['sc'] = s
|
||||
out.setdefault(n, []).append(tuple(sorted(d.items())))
|
||||
return out
|
||||
a = parse(sys.argv[1]); b = parse(sys.argv[2])
|
||||
bad = []
|
||||
for n in sorted(set(a) & set(b)):
|
||||
if sorted(a.get(n, [])) != sorted(b.get(n, [])): bad.append('%s: dxc %s zdxc %s' % (n, a.get(n), b.get(n)))
|
||||
print('\n'.join(bad))
|
||||
sys.exit(1 if bad else 0)
|
||||
|
|
@ -2,8 +2,8 @@
|
|||
// Domain shader: TessCoord, tess levels and patch inputs; locations of
|
||||
// control points and patch constants ordered by semantic, as dxc.
|
||||
// ZCHECK: BuiltIn TessCoord
|
||||
// ZCHECK: OpDecorate %in_var_EXTRA0 Location 0
|
||||
// ZCHECK: OpDecorate %in_var_PATCHID0 Location 1
|
||||
// ZCHECK: OpDecorate %in_var_EXTRA Location 0
|
||||
// ZCHECK: OpDecorate %in_var_PATCHID Location 1
|
||||
struct HSOut { float4 pos : POSITION; float2 uv : TEXCOORD0; };
|
||||
struct PC {
|
||||
float edges[4] : SV_TessFactor;
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
// ZCHECK: OpExecutionMode %main VertexOrderCcw
|
||||
// ZCHECK: OpControlBarrier %uint_2 %uint_4 %uint_0
|
||||
// ZCHECK: BuiltIn TessLevelOuter
|
||||
// ZCHECK: OpDecorate %out_var_EXTRA0 Location 0
|
||||
// ZCHECK: OpDecorate %out_var_EXTRA Location 0
|
||||
struct VSOut { float4 pos : POSITION; float2 uv : TEXCOORD0; };
|
||||
struct HSOut { float4 pos : POSITION; float2 uv : TEXCOORD0; };
|
||||
struct PC {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,41 @@
|
|||
// PROFILE: ps_6_0
|
||||
// FLAGS: -E main -fvk-t-shift 10 0 -fvk-s-shift 20 all -fvk-bind-globals 7 2
|
||||
// Vulkan bindings, numbered as dxc numbers them: [[vk::binding]] and
|
||||
// [[vk::counter_binding]] first, then registers (shifted), then the rest
|
||||
// in declaration order (used or not), Append / Consume counters right
|
||||
// after their buffer. Also push constants, explicit locations / indices
|
||||
// and specialization constants.
|
||||
// ZCHECK: OpDecorate %tex DescriptorSet 0
|
||||
// ZCHECK: OpDecorate %tex Binding 13
|
||||
// ZCHECK: OpDecorate %samp Binding 21
|
||||
// ZCHECK: OpDecorate %explicit_ DescriptorSet 3
|
||||
// ZCHECK: OpDecorate %_Globals{{.*}} DescriptorSet 2
|
||||
// ZCHECK: OpDecorate %_Globals{{.*}} Binding 7
|
||||
// ZCHECK: OpDecorate %counter_var_consumed Binding 6
|
||||
// ZCHECK: OpDecorate %out_var_SV_Target1 Index 1
|
||||
// ZCHECK: OpDecorate %in_var_COLOR Location 4
|
||||
// ZCHECK: OpDecorate %spec SpecId 3
|
||||
// ZCHECK: OpSpecConstant %int 5
|
||||
// ZCHECK: OpVariable %_ptr_PushConstant_type_PushConstant_pc PushConstant
|
||||
Texture2D<float4> tex : register(t3);
|
||||
SamplerState samp : register(s1);
|
||||
[[vk::binding(4, 3)]] Texture2D<float4> explicit_;
|
||||
Texture2D<float4> unused;
|
||||
[[vk::counter_binding(6)]] ConsumeStructuredBuffer<float4> consumed;
|
||||
StructuredBuffer<float> later;
|
||||
float4 tint;
|
||||
[[vk::constant_id(3)]] const int spec = 5;
|
||||
struct PC { float4 scale; };
|
||||
[[vk::push_constant]] PC pc;
|
||||
|
||||
struct Out {
|
||||
[[vk::location(0)]] float4 a : SV_Target0;
|
||||
[[vk::location(0), vk::index(1)]] float4 b : SV_Target1;
|
||||
};
|
||||
|
||||
Out main([[vk::location(4)]] float2 uv : COLOR) {
|
||||
Out o;
|
||||
o.a = tex.Sample(samp, uv) * tint * pc.scale + explicit_.Sample(samp, uv) + consumed.Consume() + later[spec];
|
||||
o.b = o.a;
|
||||
return o;
|
||||
}
|
||||
Loading…
Reference in New Issue