SubpassInput, vk::image_format and inline SPIR-V

SubpassInput / SubpassInputMS with [[vk::input_attachment_index]] (a
SubpassData image read at (0, 0), with the sample for MS). Explicit
[[vk::image_format]] on storage images and texel buffers, followed from
the variable to every load and element access.

Inline SPIR-V: calls of [[vk::ext_instruction(op[, set])]] functions emit
the instruction (OpExtInst for a set) with [[vk::ext_literal]] and
[[vk::ext_reference]] operands; vk::ext_result_id<T>; ext_capability /
ext_extension on functions, variables and entry points;
ext_builtin_input / ext_builtin_output variables; ext_storage_class;
ext_decorate, ext_decorate_id and ext_decorate_string on variables and
entry parameters; vk::ext_execution_mode(_id). The capabilities and
extensions instructions, builtins, decorations and execution modes need
come from a table generated from the SPIR-V grammar.
This commit is contained in:
Peter Li 2026-10-31 17:08:44 -07:00
parent 3f33ec209b
commit 9e0375fbc5
8 changed files with 1458 additions and 11 deletions

View File

@ -1382,6 +1382,7 @@ const Emitter = struct {
.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],
.spec_constant => return e.unsupported("specialization constants outside SPIR-V", .{}), .spec_constant => return e.unsupported("specialization constants outside SPIR-V", .{}),
.spirv_inst => return e.unsupported("inline SPIR-V outside SPIR-V", .{}),
.ray_incoming => |k| { .ray_incoming => |k| {
// The shader's payload / attribute / parameter argument. // The shader's payload / attribute / parameter argument.
const idx: usize = if (k == .attributes) 1 else 0; const idx: usize = if (k == .attributes) 1 else 0;

View File

@ -131,6 +131,9 @@ pub const Op = union(enum) {
ray_incoming: RayIncoming, ray_incoming: RayIncoming,
/// SPIR-V specialization constant (index into Module.spec_constants). /// SPIR-V specialization constant (index into Module.spec_constants).
spec_constant: u32, spec_constant: u32,
/// Inline SPIR-V (`[[vk::ext_instruction]]` functions): an instruction
/// of `set` (null: core), with the capabilities and extensions it needs.
spirv_inst: *const SpirvInst,
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,
@ -311,6 +314,11 @@ pub const Global = struct {
shader_record: bool = false, shader_record: bool = false,
/// `[[vk::push_constant]]` buffers (SPIR-V PushConstant storage). /// `[[vk::push_constant]]` buffers (SPIR-V PushConstant storage).
push_constant: bool = false, push_constant: bool = false,
/// [[vk::input_attachment_index(n)]] (SubpassInput).
input_attachment: ?u32 = null,
/// [[vk::image_format("...")]]: the SPIR-V ImageFormat.
image_format: ?u32 = null,
ext: SpirvExt = .{},
}; };
pub const Stage = enum { pub const Stage = enum {
@ -355,6 +363,7 @@ pub const SigElement = struct {
vk_location: ?u32 = null, vk_location: ?u32 = null,
vk_index: ?u32 = null, vk_index: ?u32 = null,
vk_builtin: ?[]const u8 = null, vk_builtin: ?[]const u8 = null,
ext_decorations: []const ExtDecoration = &.{},
}; };
pub const Primitive = enum(u8) { point = 1, line = 2, triangle = 3, line_adj = 6, triangle_adj = 7 }; pub const Primitive = enum(u8) { point = 1, line = 2, triangle = 3, line_adj = 6, triangle_adj = 7 };
@ -418,11 +427,43 @@ pub const Entry = struct {
patch_func: ?u32 = null, patch_func: ?u32 = null,
/// `[RootSignature("...")]`: the root signature text. /// `[RootSignature("...")]`: the root signature text.
root_signature: ?[]const u8 = null, root_signature: ?[]const u8 = null,
/// Inline SPIR-V capabilities / extensions of the entry function.
ext: SpirvExt = .{},
/// The wrapper with no parameters that reads `inputs`, calls `func` /// The wrapper with no parameters that reads `inputs`, calls `func`
/// and writes `outputs`. /// and writes `outputs`.
wrapper: u32 = 0, wrapper: u32 = 0,
}; };
/// `[[vk::ext_decorate(...)]]`, `ext_decorate_id`, `ext_decorate_string`.
pub const ExtDecoration = struct {
decoration: u32,
kind: enum { literal, id, string },
/// Literal words, or the constants for `id`.
ints: []const u32 = &.{},
strings: []const []const u8 = &.{},
};
/// Inline SPIR-V attributes of a declaration.
pub const SpirvExt = struct {
decorations: []const ExtDecoration = &.{},
capabilities: []const u32 = &.{},
extensions: []const []const u8 = &.{},
/// `[[vk::ext_builtin_input(n)]]` / `ext_builtin_output(n)`.
builtin: ?u32 = null,
builtin_output: bool = false,
/// `[[vk::ext_storage_class(n)]]`.
storage_class: ?u32 = null,
};
pub const SpirvInst = struct {
opcode: u32,
set: ?[]const u8 = null,
/// Values, pointers (`[[vk::ext_reference]]`) or literal words.
operands: []const union(enum) { value: Ref, literal: u32 },
capabilities: []const u32 = &.{},
extensions: []const []const u8 = &.{},
};
/// A ray tracing state object subobject (DXIL::SubobjectKind values). /// A ray tracing state object subobject (DXIL::SubobjectKind values).
pub const Subobject = struct { pub const Subobject = struct {
name: []const u8, name: []const u8,
@ -625,6 +666,7 @@ fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !vo
.mesh_payload => try w.print("mesh payload", .{}), .mesh_payload => try w.print("mesh payload", .{}),
.ray_incoming => |k| try w.print("ray incoming {s}", .{@tagName(k)}), .ray_incoming => |k| try w.print("ray incoming {s}", .{@tagName(k)}),
.spec_constant => |k| try w.print("spec constant {d}", .{k}), .spec_constant => |k| try w.print("spec constant {d}", .{k}),
.spirv_inst => |x| try w.print("spirv op {d}", .{x.opcode}),
.heap_resource => |h| try w.print("{s}[%{d}]", .{ if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap", h.index.index() }), .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() }), .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 }),

View File

@ -134,6 +134,54 @@ const Lowerer = struct {
try l.buildEntry(f, main, .{ .entry = name, .stage = stage }); try l.buildEntry(f, main, .{ .entry = name, .stage = stage });
} }
/// The inline SPIR-V attributes among `attrs` (SPIR-V only).
fn spirvExt(l: *Lowerer, attrs: []const ast.Attribute) Error!ir.SpirvExt {
if (!l.s.opts.spirv) return .{};
var x: ir.SpirvExt = .{};
var decs: std.ArrayList(ir.ExtDecoration) = .empty;
var caps: std.ArrayList(u32) = .empty;
var exts: std.ArrayList([]const u8) = .empty;
for (attrs) |a| {
const eq = std.mem.eql;
const int = struct {
fn f(ll: *Lowerer, e: *const ast.Expr) ?u32 {
const v = ll.s.evalInt(e) orelse return null;
return @truncate(@as(u64, @bitCast(v)));
}
}.f;
if (eq(u8, a.name, "vk::ext_capability")) {
for (a.args) |arg| if (int(l, arg)) |c| try caps.append(l.arena, c);
} else if (eq(u8, a.name, "vk::ext_extension")) {
for (a.args) |arg| if (arg.kind == .string_lit) try exts.append(l.arena, try stringContents(l.arena, arg.kind.string_lit));
} else if (eq(u8, a.name, "vk::ext_builtin_input") or eq(u8, a.name, "vk::ext_builtin_output")) {
if (a.args.len == 1) x.builtin = int(l, a.args[0]);
x.builtin_output = eq(u8, a.name, "vk::ext_builtin_output");
} else if (eq(u8, a.name, "vk::ext_storage_class")) {
if (a.args.len == 1) x.storage_class = int(l, a.args[0]);
} else if ((eq(u8, a.name, "vk::ext_decorate") or eq(u8, a.name, "vk::ext_decorate_id") or eq(u8, a.name, "vk::ext_decorate_string")) and a.args.len >= 1) {
var d: ir.ExtDecoration = .{ .decoration = int(l, a.args[0]) orelse continue, .kind = if (eq(u8, a.name, "vk::ext_decorate")) .literal else if (eq(u8, a.name, "vk::ext_decorate_id")) .id else .string };
var ints: std.ArrayList(u32) = .empty;
var strs: std.ArrayList([]const u8) = .empty;
var ok = true;
for (a.args[1..]) |arg| {
if (arg.kind == .string_lit) {
try strs.append(l.arena, try stringContents(l.arena, arg.kind.string_lit));
} else if (int(l, arg)) |v| {
try ints.append(l.arena, v);
} else ok = false;
}
if (!ok) continue;
d.ints = ints.items;
d.strings = strs.items;
try decs.append(l.arena, d);
}
}
x.decorations = decs.items;
x.capabilities = caps.items;
x.extensions = exts.items;
return x;
}
/// `[[vk::constant_id(n)]] const T x = v;` (SPIR-V only). /// `[[vk::constant_id(n)]] const T x = v;` (SPIR-V only).
fn isSpecConstant(l: *Lowerer, v: *const Variable) bool { fn isSpecConstant(l: *Lowerer, v: *const Variable) bool {
if (!l.s.opts.spirv or v.storage != .global_uniform) return false; if (!l.s.opts.spirv or v.storage != .global_uniform) return false;
@ -190,7 +238,7 @@ const Lowerer = struct {
.resource => |r| r, .resource => |r| r,
else => null, else => null,
}; };
if (r) |res| if (res.kind == .other) continue; if (r) |res| if (res.kind == .other and !std.mem.startsWith(u8, res.name, "SubpassInput")) continue;
const d = v.decl orelse continue; const d = v.decl orelse continue;
if (isShaderRecord(d.attrs) or hasAttr(d.attrs, "vk::push_constant")) 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 bd = try l.bindingDecl(d.semantics, d.attrs, l.globals.get(v));
@ -388,7 +436,7 @@ const Lowerer = struct {
}; };
const shader_record = if (v.decl) |d| isShaderRecord(d.attrs) else false; const shader_record = if (v.decl) |d| isShaderRecord(d.attrs) else false;
const push_constant = if (v.decl) |d| hasAttr(d.attrs, "vk::push_constant") else false; 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 }); 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, .input_attachment = if (v.decl) |d| l.s.vkAttrInt(d.attrs, "vk::input_attachment_index") else null, .image_format = if (v.decl) |d| imageFormatNamed(semamod.Sema.vkAttrString(d.attrs, "vk::image_format")) else null, .ext = if (v.decl) |d| try l.spirvExt(d.attrs) else .{} });
const i: u32 = @intCast(l.m.globals.items.len - 1); const i: u32 = @intCast(l.m.globals.items.len - 1);
try l.globals.put(l.arena, v, i); try l.globals.put(l.arena, v, i);
return i; return i;
@ -1175,11 +1223,54 @@ const Lowerer = struct {
} }
} }
/// A call of a `[[vk::ext_instruction(opcode[, set])]]` function: the
/// instruction itself (SPIR-V only).
fn spirvInstCall(l: *Lowerer, e: *ast.Expr, f: *const semamod.Function, args: []const *ast.Expr, ret_ty: TypeId) Error!Ref {
if (!l.s.opts.spirv) return l.fail(e, "inline SPIR-V outside SPIR-V");
var inst: ir.SpirvInst = .{ .opcode = 0, .operands = &.{} };
var caps: std.ArrayList(u32) = .empty;
var exts: std.ArrayList([]const u8) = .empty;
for (f.decl.attrs) |a| {
if (std.mem.eql(u8, a.name, "vk::ext_instruction") and a.args.len >= 1) {
inst.opcode = @intCast(l.s.evalInt(a.args[0]) orelse return l.fail(e, "this inline SPIR-V instruction"));
if (a.args.len >= 2 and a.args[1].kind == .string_lit) inst.set = try stringContents(l.arena, a.args[1].kind.string_lit);
}
if (std.mem.eql(u8, a.name, "vk::ext_capability")) for (a.args) |x| {
try caps.append(l.arena, @intCast(l.s.evalInt(x) orelse continue));
};
if (std.mem.eql(u8, a.name, "vk::ext_extension")) for (a.args) |x| if (x.kind == .string_lit) {
try exts.append(l.arena, try stringContents(l.arena, x.kind.string_lit));
};
}
const Operand = @typeInfo(@TypeOf(inst.operands)).pointer.child;
var ops: std.ArrayList(Operand) = .empty;
for (args, 0..) |a, i| {
const pd = if (i < f.decl.params.len) f.decl.params[i] else null;
const pattrs: []const ast.Attribute = if (pd) |x| x.attrs else &.{};
if (hasAttr(pattrs, "vk::ext_literal")) {
const v = l.s.evalInt(a) orelse return l.fail(a, "a non-constant [[vk::ext_literal]] argument");
try ops.append(l.arena, .{ .literal = @truncate(@as(u64, @bitCast(v))) });
} else if (hasAttr(pattrs, "vk::ext_reference")) {
try ops.append(l.arena, .{ .value = try l.lvalue(a) });
} else {
const pt = if (i < f.params.len) f.params[i].type else a.ty;
try ops.append(l.arena, .{ .value = try l.converted(a, pt) });
}
}
inst.operands = ops.items;
inst.capabilities = caps.items;
inst.extensions = exts.items;
const p = try l.arena.create(ir.SpirvInst);
p.* = inst;
return l.b.add(.{ .op = .{ .spirv_inst = p }, .ty = ret_ty });
}
fn call(l: *Lowerer, e: *ast.Expr, callee: *ast.Expr, args: []const *ast.Expr) Error!Ref { fn call(l: *Lowerer, e: *ast.Expr, callee: *ast.Expr, args: []const *ast.Expr) Error!Ref {
const r = l.s.resolution(e) orelse return l.fail(e, "this call"); const r = l.s.resolution(e) orelse return l.fail(e, "this call");
const ret_ty = try l.concrete(e.ty); const ret_ty = try l.concrete(e.ty);
switch (r) { switch (r) {
.function => |f| { .function => |f| {
if (!f.defined and hasAttr(f.decl.attrs, "vk::ext_instruction")) return l.spirvInstCall(e, f, args, ret_ty);
const fi = try l.functionIndex(f); const fi = try l.functionIndex(f);
// Missing trailing arguments take the parameters' defaults. // Missing trailing arguments take the parameters' defaults.
var full = args; var full = args;
@ -1600,6 +1691,7 @@ const Lowerer = struct {
vk_location: ?u32 = null, vk_location: ?u32 = null,
vk_index: ?u32 = null, vk_index: ?u32 = null,
vk_builtin: ?[]const u8 = null, vk_builtin: ?[]const u8 = null,
ext_decorations: []const ir.ExtDecoration = &.{},
/// A field's modifiers, inheriting the enclosing interpolation. /// A field's modifiers, inheriting the enclosing interpolation.
fn field(outer: SigAttrs, fld: Field) SigAttrs { fn field(outer: SigAttrs, fld: Field) SigAttrs {
@ -1615,6 +1707,7 @@ const Lowerer = struct {
r.vk_location = attrs.vk_location; r.vk_location = attrs.vk_location;
r.vk_index = attrs.vk_index; r.vk_index = attrs.vk_index;
r.vk_builtin = attrs.vk_builtin; r.vk_builtin = attrs.vk_builtin;
r.ext_decorations = attrs.ext_decorations;
return r; return r;
} }
@ -1628,6 +1721,7 @@ const Lowerer = struct {
const lit = at.args[0].kind.string_lit; const lit = at.args[0].kind.string_lit;
a.vk_builtin = lit[1 .. lit.len - 1]; a.vk_builtin = lit[1 .. lit.len - 1];
}; };
a.ext_decorations = (l.spirvExt(attrs) catch ir.SpirvExt{}).decorations;
return a; return a;
} }
@ -2008,7 +2102,7 @@ const Lowerer = struct {
fn buildEntry(l: *Lowerer, f: *const semamod.Function, main: u32, opts: Options) Error!void { fn buildEntry(l: *Lowerer, f: *const semamod.Function, main: u32, opts: Options) Error!void {
const inits = try l.staticInits(); const inits = try l.staticInits();
var entry: ir.Entry = .{ .func = main, .name = opts.entry, .stage = opts.stage }; var entry: ir.Entry = .{ .func = main, .name = opts.entry, .stage = opts.stage, .ext = try l.spirvExt(f.decl.attrs) };
entry.outputs = l.early_outputs; entry.outputs = l.early_outputs;
for (f.decl.attrs) |a| { for (f.decl.attrs) |a| {
if (std.ascii.eqlIgnoreCase(a.name, "numthreads") and a.args.len == 3) { if (std.ascii.eqlIgnoreCase(a.name, "numthreads") and a.args.len == 3) {
@ -2223,6 +2317,21 @@ fn packOffset(v: *const Variable) ?u32 {
return null; return null;
} }
/// The SPIR-V ImageFormat a `[[vk::image_format]]` names.
fn imageFormatNamed(name: ?[]const u8) ?u32 {
const n = name orelse return null;
const names = [_][]const u8{
"unknown", "rgba32f", "rgba16f", "r32f", "rgba8", "rgba8snorm", "rg32f", "rg16f",
"r11g11b10f", "r16f", "rgba16", "rgb10a2", "rg16", "rg8", "r16", "r8",
"rgba16snorm", "rg16snorm", "rg8snorm", "r16snorm", "r8snorm", "rgba32i", "rgba16i", "rgba8i",
"r32i", "rg32i", "rg16i", "rg8i", "r16i", "r8i", "rgba32ui", "rgba16ui",
"rgba8ui", "r32ui", "rgb10a2ui", "rg32ui", "rg16ui", "rg8ui", "r16ui", "r8ui",
"r64ui", "r64i",
};
for (names, 0..) |x, k| if (std.ascii.eqlIgnoreCase(x, n)) return @intCast(k);
return null;
}
fn hasAttr(attrs: []const ast.Attribute, name: []const u8) bool { fn hasAttr(attrs: []const ast.Attribute, name: []const u8) bool {
for (attrs) |a| if (std.mem.eql(u8, a.name, name)) return true; for (attrs) |a| if (std.mem.eql(u8, a.name, name)) return true;
return false; return false;

View File

@ -203,6 +203,17 @@ fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
.method => |x| .{ .method = .{ .name = x.name, .res = ctx.map(x.res), .args = try mapRefs(a, x.args, ctx) } }, .method => |x| .{ .method = .{ .name = x.name, .res = ctx.map(x.res), .args = try mapRefs(a, x.args, ctx) } },
.output => |x| .{ .output = .{ .element = x.element, .value = ctx.map(x.value) } }, .output => |x| .{ .output = .{ .element = x.element, .value = ctx.map(x.value) } },
.heap_resource => |h| .{ .heap_resource = .{ .index = ctx.map(h.index), .sampler = h.sampler } }, .heap_resource => |h| .{ .heap_resource = .{ .index = ctx.map(h.index), .sampler = h.sampler } },
.spirv_inst => |x| blk: {
const ops = try a.dupe(@typeInfo(@TypeOf(x.operands)).pointer.child, x.operands);
for (ops) |*o| switch (o.*) {
.value => |*v| v.* = ctx.map(v.*),
.literal => {},
};
const n = try a.create(ir.SpirvInst);
n.* = x.*;
n.operands = ops;
break :blk .{ .spirv_inst = n };
},
.patch_output => |x| .{ .patch_output = .{ .element = x.element, .value = ctx.map(x.value) } }, .patch_output => |x| .{ .patch_output = .{ .element = x.element, .value = ctx.map(x.value) } },
.phi => |ps| blk: { .phi => |ps| blk: {
const out = try a.alloc(@typeInfo(@TypeOf(ps)).pointer.child, ps.len); const out = try a.alloc(@typeInfo(@TypeOf(ps)).pointer.child, ps.len);

View File

@ -1067,6 +1067,8 @@ pub const Sema = struct {
return s.types.intern(.{ .resource = .{ .kind = vn[1], .elem = elem, .name = n } }); return s.types.intern(.{ .resource = .{ .kind = vn[1], .elem = elem, .name = n } });
}; };
// Any other builtin object (RayQuery, node records, vk:: types...). // Any other builtin object (RayQuery, node records, vk:: types...).
// vk::ext_result_id<T>: a T (an inline instruction's result).
if (eql(n, "ext_result_id") and args.len == 1) return try s.typeArg(args[0]) orelse TypeTable.error_type;
if (isOtherBuiltinObject(n)) { if (isOtherBuiltinObject(n)) {
var elem: TypeId = TypeTable.void_type; var elem: TypeId = TypeTable.void_type;
if (eql(n, "RayQuery")) { if (eql(n, "RayQuery")) {
@ -1075,6 +1077,8 @@ pub const Sema = struct {
return s.types.intern(.{ .resource = .{ .kind = .other, .elem = elem, .name = n, .flags = flags, .flags2 = flags2 } }); return s.types.intern(.{ .resource = .{ .kind = .other, .elem = elem, .name = n, .flags = flags, .flags2 = flags2 } });
} }
if (args.len > 0) elem = try s.typeArg(args[0]) orelse TypeTable.void_type; if (args.len > 0) elem = try s.typeArg(args[0]) orelse TypeTable.void_type;
// SubpassInput / SubpassInputMS default to float4.
if (elem == TypeTable.void_type and std.mem.startsWith(u8, n, "SubpassInput")) elem = try s.types.vector(.float, 4);
return s.types.intern(.{ .resource = .{ .kind = .other, .elem = elem, .name = n } }); return s.types.intern(.{ .resource = .{ .kind = .other, .elem = elem, .name = n } });
} }
// The parser already reported unknown type names. // The parser already reported unknown type names.
@ -3592,7 +3596,7 @@ fn methodNamespace(t: types.Type) ?[]const u8 {
.sampled_texture_cube => "VkSampledTextureCUBEMethods", .sampled_texture_cube => "VkSampledTextureCUBEMethods",
.sampled_texture_cube_array => "VkSampledTextureCUBEArrayMethods", .sampled_texture_cube_array => "VkSampledTextureCUBEArrayMethods",
.constant_buffer, .texture_buffer, .raytracing_acceleration_structure => null, .constant_buffer, .texture_buffer, .raytracing_acceleration_structure => null,
.other => if (std.mem.eql(u8, r.name, "RayQuery")) "RayQueryMethods" else null, .other => if (std.mem.eql(u8, r.name, "RayQuery")) "RayQueryMethods" else if (std.mem.eql(u8, r.name, "SubpassInput")) "VkSubpassInputMethods" else if (std.mem.eql(u8, r.name, "SubpassInputMS")) "VkSubpassInputMSMethods" else null,
}, },
else => null, else => null,
}; };

View File

@ -38,6 +38,7 @@ pub const Op = enum(u16) {
spec_constant_false = 49, spec_constant_false = 49,
spec_constant = 50, spec_constant = 50,
decorate_id = 332, decorate_id = 332,
execution_mode_id = 331,
decorate_string = 5632, decorate_string = 5632,
constant_false = 42, constant_false = 42,
constant = 43, constant = 43,
@ -245,6 +246,8 @@ pub const Op = enum(u16) {
end_primitive = 219, end_primitive = 219,
emit_stream_vertex = 220, emit_stream_vertex = 220,
end_stream_primitive = 221, end_stream_primitive = 221,
/// (Inline SPIR-V may use any value.)
_,
}; };
pub const Section = enum { pub const Section = enum {

View File

@ -8,6 +8,7 @@ const Allocator = std.mem.Allocator;
const ir = @import("../ir/ir.zig"); const ir = @import("../ir/ir.zig");
const types = @import("../sema/types.zig"); const types = @import("../sema/types.zig");
const texture = @import("../ir/texture.zig"); const texture = @import("../ir/texture.zig");
const op_caps = @import("op_caps.zig");
const builder = @import("builder.zig"); const builder = @import("builder.zig");
const diag = @import("../diag.zig"); const diag = @import("../diag.zig");
const layout = @import("../ir/layout.zig"); const layout = @import("../ir/layout.zig");
@ -46,6 +47,8 @@ const Capability = enum(u32) {
cull_distance = 33, cull_distance = 33,
draw_parameters = 4427, draw_parameters = 4427,
device_group = 4437, device_group = 4437,
input_attachment = 40,
int64_image_ext = 5016,
multi_view = 4439, multi_view = 4439,
fragment_shading_rate_khr = 4422, fragment_shading_rate_khr = 4422,
stencil_export_ext = 5013, stencil_export_ext = 5013,
@ -89,6 +92,8 @@ const Capability = enum(u32) {
sampled_image_array_non_uniform_indexing = 5307, sampled_image_array_non_uniform_indexing = 5307,
storage_buffer_array_non_uniform_indexing = 5308, storage_buffer_array_non_uniform_indexing = 5308,
storage_image_array_non_uniform_indexing = 5309, storage_image_array_non_uniform_indexing = 5309,
/// (Inline SPIR-V may use any value.)
_,
}; };
/// A Vulkan (or universal) target and the SPIR-V version it implies. /// A Vulkan (or universal) target and the SPIR-V version it implies.
@ -161,6 +166,7 @@ const Emitter = struct {
counter_slots: []?Slot = &.{}, counter_slots: []?Slot = &.{},
used_bindings: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty, used_bindings: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty,
spec_ids: std.AutoHashMapUnmanaged(u32, Id) = .empty, spec_ids: std.AutoHashMapUnmanaged(u32, Id) = .empty,
ext_imports: std.StringHashMapUnmanaged(Id) = .empty,
/// Flattened resource arrays: a variable per element. /// Flattened resource arrays: a variable per element.
flat_vars: std.AutoHashMapUnmanaged(u32, []const Id) = .empty, flat_vars: std.AutoHashMapUnmanaged(u32, []const Id) = .empty,
flat_iface: std.ArrayList(Id) = .empty, flat_iface: std.ArrayList(Id) = .empty,
@ -171,6 +177,10 @@ const Emitter = struct {
sampler_type: Id = 0, sampler_type: Id = 0,
accel_type: Id = 0, accel_type: Id = 0,
ray_query_type: Id = 0, ray_query_type: Id = 0,
/// [[vk::image_format]] of the image type being made.
format_override: ?u32 = null,
/// int2(0, 0), the coordinate of subpass reads.
subpass_coord: Id = 0,
counter_vars: []Id = &.{}, counter_vars: []Id = &.{},
builtin_inputs: std.AutoHashMapUnmanaged(u32, Id) = .empty, builtin_inputs: std.AutoHashMapUnmanaged(u32, Id) = .empty,
/// Per instruction (current function): texel places (`tex[i]`). /// Per instruction (current function): texel places (`tex[i]`).
@ -232,6 +242,9 @@ const Emitter = struct {
iface: std.ArrayList(Id) = .empty, iface: std.ArrayList(Id) = .empty,
/// Compute derivatives' execution mode (0: none). /// Compute derivatives' execution mode (0: none).
derivative_mode: u32 = 0, derivative_mode: u32 = 0,
/// vk::ext_execution_mode(...): mode and operands (ids for
/// ext_execution_mode_id).
ext_modes: std.ArrayList(struct { words: []const u32, id: bool }) = .empty,
/// Mesh shaders: the primitive indices builtin and the payload /// Mesh shaders: the primitive indices builtin and the payload
/// variable (both made on first use); amplification shaders: the /// variable (both made on first use); amplification shaders: the
/// groupshared variable sent by DispatchMesh. /// groupshared variable sent by DispatchMesh.
@ -599,6 +612,93 @@ const Emitter = struct {
} }
} }
/// The storage class `[[vk::ext_builtin_*]]` / `[[vk::ext_storage_class]]`
/// give a global, if any.
fn extStorage(g: ir.Global) ?StorageClass {
if (g.ext.builtin != null) return if (g.ext.builtin_output) .output else .input;
if (g.ext.storage_class) |c| return @enumFromInt(c);
return null;
}
/// Inline SPIR-V decorations, capabilities and extensions of a
/// declaration (decorations on `v` when non-zero).
fn applyExt(e: *Emitter, v: Id, x: ir.SpirvExt) Error!void {
for (x.capabilities) |c| try e.capabilities.put(e.arena, @enumFromInt(c), {});
for (x.extensions) |name| try e.extension(name);
if (v != 0) try e.extDecorate(v, x.decorations);
}
/// What an enumerant used by inline SPIR-V needs (as dxc infers).
fn requireNeed(e: *Emitter, n: ?op_caps.Need) Error!void {
const x = n orelse return;
switch (x.cap) {
// (Not kernel capabilities: Addresses, Linkage, Kernel,
// SubgroupDispatch.)
0, 4, 5, 6, 58 => {},
else => try e.capabilities.put(e.arena, @enumFromInt(x.cap), {}),
}
if (x.ext.len > 0 and x.core > 100 + @as(u32, e.spv_minor)) try e.extension(x.ext);
}
fn extDecorate(e: *Emitter, v: Id, decs: []const ir.ExtDecoration) Error!void {
for (decs) |d| {
if (d.decoration == 11 and d.ints.len > 0) try e.requireNeed(op_caps.need(&op_caps.builtins, d.ints[0])) else try e.requireNeed(op_caps.need(&op_caps.decorations, d.decoration));
}
for (decs) |d| switch (d.kind) {
.literal => {
var words: std.ArrayList(u32) = .empty;
try words.appendSlice(e.arena, &.{ v, d.decoration });
try words.appendSlice(e.arena, d.ints);
try e.b.emit(.annotations, .decorate, words.items);
},
.id => {
var words: std.ArrayList(u32) = .empty;
try words.appendSlice(e.arena, &.{ v, d.decoration });
for (d.ints) |x| try words.append(e.arena, try e.constUint(x));
try e.b.emit(.annotations, .decorate_id, words.items);
},
.string => for (d.strings) |str| try e.b.emitWithString(.annotations, .decorate_string, &.{ v, d.decoration }, str, &.{}),
};
}
/// Inline SPIR-V: the instruction with its operands (OpExtInst for an
/// instruction set).
fn spirvInst(e: *Emitter, x: *const ir.SpirvInst, ty: TypeId) Error!Id {
for (x.capabilities) |c| try e.capabilities.put(e.arena, @enumFromInt(c), {});
for (x.extensions) |name| try e.extension(name);
// The capability the grammar gives the instruction (not ones for
// kernels).
if (x.set == null) if (op_caps.get(x.opcode)) |c| switch (c) {
4, 5, 6 => {},
else => try e.capabilities.put(e.arena, @enumFromInt(c), {}),
};
var words: std.ArrayList(u32) = .empty;
const has_result = ty != TypeTable.void_type or x.set != null;
const id: Id = if (has_result) e.b.newId() else 0;
if (has_result) try words.appendSlice(e.arena, &.{ try e.typeId(ty), id });
if (x.set) |set| try words.appendSlice(e.arena, &.{ try e.extInstImport(set), x.opcode });
for (x.operands) |o| try words.append(e.arena, switch (o) {
.value => |r| e.val(r),
.literal => |w| w,
});
const op: Op = if (x.set != null) .ext_inst else @enumFromInt(@as(u16, @intCast(x.opcode)));
try e.b.emit(.functions, op, words.items);
return id;
}
/// An OpExtInstImport of `name` (made once).
fn extInstImport(e: *Emitter, name: []const u8) Error!Id {
if (std.mem.eql(u8, name, "GLSL.std.450")) {
if (e.glsl == 0) e.glsl = e.b.newId();
return e.glsl;
}
if (e.ext_imports.get(name)) |id| return id;
const id = e.b.newId();
try e.b.emitWithString(.ext_inst_imports, .ext_inst_import, &.{id}, name, &.{});
try e.ext_imports.put(e.arena, name, id);
return id;
}
/// A [[vk::constant_id]] constant: OpSpecConstant* with its SpecId. /// A [[vk::constant_id]] constant: OpSpecConstant* with its SpecId.
fn specConstant(e: *Emitter, k: u32) Error!Id { fn specConstant(e: *Emitter, k: u32) Error!Id {
if (e.spec_ids.get(k)) |id| return id; if (e.spec_ids.get(k)) |id| return id;
@ -665,6 +765,7 @@ const Emitter = struct {
if (m.entries.items.len == 0 and !link) return e.unsupported("libraries without entry points need a universal target environment (-fspv-target-env=universal1.5)", .{}); if (m.entries.items.len == 0 and !link) return e.unsupported("libraries without entry points need a universal target environment (-fspv-target-env=universal1.5)", .{});
if (link) try e.cap(.linkage); if (link) try e.cap(.linkage);
for (m.entries.items) |*entry| { for (m.entries.items) |*entry| {
try e.applyExt(0, entry.ext);
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 (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)", .{}); 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)", .{});
@ -847,6 +948,13 @@ const Emitter = struct {
else => {}, else => {},
} }
if (e.st.derivative_mode != 0) try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, e.st.derivative_mode }); if (e.st.derivative_mode != 0) try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, e.st.derivative_mode });
// vk::ext_execution_mode(...) / ext_execution_mode_id(...).
for (e.st.ext_modes.items) |em| {
var words: std.ArrayList(u32) = .empty;
try words.append(e.arena, wrapper);
try words.appendSlice(e.arena, em.words);
try e.b.emit(.execution_modes, if (em.id) .execution_mode_id else .execution_mode, words.items);
}
} }
fn domainMode(d: ir.Domain) u32 { fn domainMode(d: ir.Domain) u32 {
@ -904,13 +1012,16 @@ const Emitter = struct {
continue; continue;
} }
const var_id = e.b.newId(); const var_id = e.b.newId();
e.format_override = g.image_format;
const p = try e.resourcePointee(g.ty); const p = try e.resourcePointee(g.ty);
e.format_override = null;
try e.b.emit(.types_globals, .variable, &.{ try e.pointerType(p.sc, p.ty), var_id, @backingInt(p.sc) }); try e.b.emit(.types_globals, .variable, &.{ try e.pointerType(p.sc, p.ty), var_id, @backingInt(p.sc) });
const slot = try e.slotOf(@intCast(gi), false); 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, 34, slot.set }); // DescriptorSet
try e.b.emit(.annotations, .decorate, &.{ var_id, 33, slot.binding }); // Binding try e.b.emit(.annotations, .decorate, &.{ var_id, 33, slot.binding }); // Binding
try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{}); try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{});
try e.userType(var_id, g.ty, g); try e.userType(var_id, g.ty, g);
if (g.input_attachment) |ia| try e.b.emit(.annotations, .decorate, &.{ var_id, 43, ia }); // InputAttachmentIndex
e.global_vars[gi] = var_id; e.global_vars[gi] = var_id;
}, },
.cbuffer => { .cbuffer => {
@ -935,15 +1046,23 @@ 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 (e.payload_global == @as(u32, @intCast(gi))) .task_payload_workgroup else if (g.space == .groupshared) .workgroup else .private; const sc: StorageClass = if (extStorage(g)) |x| x else 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) });
try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{}); try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{});
if (g.ext.builtin) |bi| {
try e.b.emit(.annotations, .decorate, &.{ var_id, 11, bi }); // BuiltIn
try e.requireNeed(op_caps.need(&op_caps.builtins, bi));
// Integer pixel shader inputs are flat.
const c = e.t.component(g.ty);
if (!g.ext.builtin_output and c != null and !c.?.isFloat() and e.entry.stage == .pixel) try e.b.emit(.annotations, .decorate, &.{ var_id, 14 }); // Flat
}
e.global_vars[gi] = var_id; e.global_vars[gi] = var_id;
}, },
else => return e.unsupported("global '{s}' is not supported yet", .{g.name}), else => return e.unsupported("global '{s}' is not supported yet", .{g.name}),
} }
if (e.global_vars[gi] != 0) try e.applyExt(e.global_vars[gi], g.ext);
} }
// Descriptor heaps: the next free bindings of set 0 (resources, // Descriptor heaps: the next free bindings of set 0 (resources,
@ -1539,6 +1658,7 @@ const Emitter = struct {
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 }); 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, &.{}); try e.b.emitWithString(.debug_names, .name, &.{var_id}, name, &.{});
try e.userSemantic(var_id, el); try e.userSemantic(var_id, el);
try e.extDecorate(var_id, el.ext_decorations);
iface.* = .{ .var_id = var_id, .ty = vty, .elem_array = bi != null and e.t.get(bi.?.ty) == .array, .builtin = if (bi) |x| x.id else std.math.maxInt(u32) }; iface.* = .{ .var_id = var_id, .ty = vty, .elem_array = bi != null and e.t.get(bi.?.ty) == .array, .builtin = if (bi) |x| x.id else std.math.maxInt(u32) };
try e.useVar(var_id); try e.useVar(var_id);
} }
@ -1898,6 +2018,7 @@ const Emitter = struct {
switch (i.op) { switch (i.op) {
.constant, .param, .local_var => {}, .constant, .param, .local_var => {},
.spec_constant => |k| e.vals[ri] = try e.specConstant(k), .spec_constant => |k| e.vals[ri] = try e.specConstant(k),
.spirv_inst => |x| e.vals[ri] = try e.spirvInst(x, i.ty),
.ray_incoming => |k| e.vals[ri] = try e.rayVar(switch (k) { .ray_incoming => |k| e.vals[ri] = try e.rayVar(switch (k) {
.payload => .incoming_ray_payload_khr, .payload => .incoming_ray_payload_khr,
.attributes => .hit_attribute_khr, .attributes => .hit_attribute_khr,
@ -1905,6 +2026,7 @@ const Emitter = struct {
}, i.ty), }, i.ty),
.global => |g| { .global => |g| {
e.vals[ri] = e.global_vars[g]; e.vals[ri] = e.global_vars[g];
if (extStorage(e.m.globals.items[g])) |sc| if (sc == .input or sc == .output or e.spv_minor >= 4) try e.useVar(e.global_vars[g]);
if (ownStorage(e.m.globals.items[g]) != null) { if (ownStorage(e.m.globals.items[g]) != null) {
// (Interfaces list them from SPIR-V 1.4.) // (Interfaces list them from SPIR-V 1.4.)
if (e.spv_minor >= 4) try e.useVar(e.global_vars[g]); if (e.spv_minor >= 4) try e.useVar(e.global_vars[g]);
@ -2021,7 +2143,7 @@ const Emitter = struct {
const shader_record = own != null; 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.?.buffer)) e.bufferSc() else if (base_pl != null) .uniform else switch (i.ptr) { const sc: StorageClass = if (own) |x| x else if (into_cb) .uniform else if (into_buffer or (base_pl != null and base_pl.?.buffer)) e.bufferSc() else if (base_pl != null) .uniform else switch (i.ptr) {
.function => .function, .function => .function,
.private => .private, .private => if (e.rootGlobal(a.base)) |rg| (extStorage(e.m.globals.items[rg]) orelse .private) else .private,
.groupshared => if (e.payload_global != null and e.rootGlobal(a.base) == e.payload_global) .task_payload_workgroup else .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", .{}),
@ -2686,6 +2808,7 @@ const Emitter = struct {
.sampler => return .{ .sc = .uniform_constant, .ty = try e.samplerType() }, .sampler => return .{ .sc = .uniform_constant, .ty = try e.samplerType() },
.resource => |r| switch (r.kind) { .resource => |r| switch (r.kind) {
.raytracing_acceleration_structure => return .{ .sc = .uniform_constant, .ty = try e.accelType() }, .raytracing_acceleration_structure => return .{ .sc = .uniform_constant, .ty = try e.accelType() },
.other => if (std.mem.startsWith(u8, r.name, "SubpassInput")) return .{ .sc = .uniform_constant, .ty = try e.subpassType(ty) },
.structured_buffer, .rw_structured_buffer, .append_structured_buffer, .consume_structured_buffer, .byte_address_buffer, .rw_byte_address_buffer => return .{ .sc = e.bufferSc(), .ty = try e.bufferBlockType(ty) }, .structured_buffer, .rw_structured_buffer, .append_structured_buffer, .consume_structured_buffer, .byte_address_buffer, .rw_byte_address_buffer => return .{ .sc = e.bufferSc(), .ty = try e.bufferBlockType(ty) },
.constant_buffer => if (e.t.get(r.elem) == .@"struct") return .{ .sc = .uniform, .ty = try e.constantBufferBlock(r.elem) }, .constant_buffer => if (e.t.get(r.elem) == .@"struct") return .{ .sc = .uniform, .ty = try e.constantBufferBlock(r.elem) },
.texture_buffer => if (e.t.get(r.elem) == .@"struct") return .{ .sc = e.bufferSc(), .ty = try e.textureBufferBlock(r.elem) }, .texture_buffer => if (e.t.get(r.elem) == .@"struct") return .{ .sc = e.bufferSc(), .ty = try e.textureBufferBlock(r.elem) },
@ -2770,7 +2893,9 @@ const Emitter = struct {
e.vals[ri] = ids[k]; e.vals[ri] = ids[k];
return; return;
}; };
e.format_override = e.formatFor(a.base);
const p = try e.resourcePointee(ty); const p = try e.resourcePointee(ty);
e.format_override = null;
var ops: std.ArrayList(u32) = .empty; var ops: std.ArrayList(u32) = .empty;
const id = e.b.newId(); const id = e.b.newId();
var nonuniform = false; var nonuniform = false;
@ -2877,6 +3002,20 @@ const Emitter = struct {
}; };
} }
/// SubpassInput[MS]<T>: an image of SubpassData dimension.
fn subpassType(e: *Emitter, ty: TypeId) Error!Id {
const r = e.t.get(ty).resource;
try e.cap(.input_attachment);
const ms: u32 = @intFromBool(std.mem.eql(u8, r.name, "SubpassInputMS"));
const st = try e.scalarType(storageScalar(e.t.component(r.elem).?));
const key: [6]u32 = .{ st, 6, 0, ms, 2, 0 };
if (e.image_types.get(key)) |id| return id;
const id = e.b.newId();
try e.b.emit(.types_globals, .type_image, &.{ id, st, 6, 2, 0, ms, 2, 0 }); // SubpassData, Unknown
try e.image_types.put(e.arena, key, id);
return id;
}
fn accelType(e: *Emitter) Error!Id { fn accelType(e: *Emitter) Error!Id {
if (e.accel_type == 0) { if (e.accel_type == 0) {
e.accel_type = e.b.newId(); e.accel_type = e.b.newId();
@ -2905,6 +3044,20 @@ const Emitter = struct {
/// and the system values as builtins. Null for other names. /// and the system values as builtins. Null for other names.
fn rayIntrinsic(e: *Emitter, name: []const u8, ty: TypeId, args: []const Ref) Error!?Id { fn rayIntrinsic(e: *Emitter, name: []const u8, ty: TypeId, args: []const Ref) Error!?Id {
const eq = std.mem.eql; const eq = std.mem.eql;
if (eq(u8, name, "ext_execution_mode") or eq(u8, name, "ext_execution_mode_id")) {
const id = eq(u8, name, "ext_execution_mode_id");
const words = try e.arena.alloc(u32, args.len);
for (words, args, 0..) |*w, a, k| {
const c = switch (e.f.inst(a).op) {
.constant => |c| c,
else => return e.unsupported("'{s}' with non-constant operands", .{name}),
};
w.* = if (k > 0 and id) try e.constant(e.f.inst(a).ty, c) else @truncate(@as(u64, @bitCast(c.int)));
}
try e.st.ext_modes.append(e.arena, .{ .words = words, .id = id });
if (words.len > 0) try e.requireNeed(op_caps.need(&op_caps.execution_modes, words[0]));
return 0;
}
if (eq(u8, name, "TraceRay") or eq(u8, name, "CallShader")) { if (eq(u8, name, "TraceRay") or eq(u8, name, "CallShader")) {
// Through the payload / callable data variable, copied in and // Through the payload / callable data variable, copied in and
// back out. // back out.
@ -3094,7 +3247,7 @@ const Emitter = struct {
.buffer => 5, .buffer => 5,
}; };
const sampled: u32 = if (sh.rw) 2 else 1; const sampled: u32 = if (sh.rw) 2 else 1;
const format: u32 = if (sh.rw or sh.dim == .buffer) e.imageFormat(elem) else 0; const format: u32 = if (e.format_override) |f| f else if (sh.rw or sh.dim == .buffer) e.imageFormat(elem) else 0;
const key: [6]u32 = .{ st, dim, @intFromBool(sh.array), @intFromBool(sh.ms), sampled, format }; const key: [6]u32 = .{ st, dim, @intFromBool(sh.array), @intFromBool(sh.ms), sampled, format };
if (e.image_types.get(key)) |id| return id; if (e.image_types.get(key)) |id| return id;
switch (sh.dim) { switch (sh.dim) {
@ -3105,7 +3258,11 @@ const Emitter = struct {
} }
if (sh.rw and sh.ms) try e.cap(if (sh.array) .image_ms_array else .storage_image_multisample); if (sh.rw and sh.ms) try e.cap(if (sh.array) .image_ms_array else .storage_image_multisample);
switch (format) { switch (format) {
6, 7, 9, 25, 26, 28, 35, 36, 38 => try e.cap(.storage_image_extended_formats), 6...20, 25...29, 34...39 => try e.cap(.storage_image_extended_formats),
40, 41 => {
try e.cap(.int64_image_ext);
try e.extension("SPV_EXT_shader_image_int64");
},
else => {}, else => {},
} }
const id = e.b.newId(); const id = e.b.newId();
@ -3124,9 +3281,20 @@ const Emitter = struct {
fn imageTypeOf(e: *Emitter, r: Ref) Error!Id { fn imageTypeOf(e: *Emitter, r: Ref) Error!Id {
const rk = e.resourceInfo(r); const rk = e.resourceInfo(r);
e.format_override = e.formatFor(r);
defer e.format_override = null;
return e.imageType(texture.shape(rk.kind).?, rk.elem); return e.imageType(texture.shape(rk.kind).?, rk.elem);
} }
/// The [[vk::image_format]] of the variable image value `r` comes
/// from, if any.
fn formatFor(e: *Emitter, r: Ref) ?u32 {
var x = r;
while (e.f.inst(x).op == .access) x = e.f.inst(x).op.access.base;
const g = e.globalOf(x) orelse return null;
return e.m.globals.items[g].image_format;
}
fn loadImage(e: *Emitter, r: Ref) Error!Id { fn loadImage(e: *Emitter, r: Ref) Error!Id {
if (texture.shape(e.resourceInfo(r).kind)) |sh| if (sh.combined) { if (texture.shape(e.resourceInfo(r).kind)) |sh| if (sh.combined) {
// A combined image sampler: its image. // A combined image sampler: its image.
@ -3167,7 +3335,7 @@ const Emitter = struct {
const img = try e.loadImage(res); const img = try e.loadImage(res);
var v: Id = undefined; var v: Id = undefined;
if (sh.rw) { if (sh.rw) {
if (e.imageFormat(r.elem) == 0) try e.cap(.storage_image_read_without_format); if ((e.formatFor(res) orelse e.imageFormat(r.elem)) == 0) try e.cap(.storage_image_read_without_format);
v = if (sh.ms) v = if (sh.ms)
try e.opRaw(.image_read, try e.vec4Of(s), &.{ img, coord, 0x40, try e.constInt(0) }) try e.opRaw(.image_read, try e.vec4Of(s), &.{ img, coord, 0x40, try e.constInt(0) })
else else
@ -3184,7 +3352,7 @@ const Emitter = struct {
fn imageWrite(e: *Emitter, res: Ref, coord: Id, value: Id) Error!void { fn imageWrite(e: *Emitter, res: Ref, coord: Id, value: Id) Error!void {
const r = e.resourceInfo(res); const r = e.resourceInfo(res);
_ = try e.texelScalar(r.elem); _ = try e.texelScalar(r.elem);
if (e.imageFormat(r.elem) == 0) try e.cap(.storage_image_write_without_format); if ((e.formatFor(res) orelse e.imageFormat(r.elem)) == 0) try e.cap(.storage_image_write_without_format);
const img = try e.loadImage(res); const img = try e.loadImage(res);
try e.b.emit(.functions, .image_write, &.{ img, coord, value }); try e.b.emit(.functions, .image_write, &.{ img, coord, value });
} }
@ -3213,6 +3381,25 @@ const Emitter = struct {
const eq = std.mem.eql; const eq = std.mem.eql;
if (e.t.get(e.f.inst(res).ty) != .resource) return e.unsupported("method '{s}' is not supported yet", .{name}); if (e.t.get(e.f.inst(res).ty) != .resource) return e.unsupported("method '{s}' is not supported yet", .{name});
if (isRayQuery(e.t, e.f.inst(res).ty)) return e.rayQueryMethod(name, res, args, ty); if (isRayQuery(e.t, e.f.inst(res).ty)) return e.rayQueryMethod(name, res, args, ty);
if (e.t.get(e.f.inst(res).ty).resource.kind == .other and std.mem.eql(u8, name, "SubpassLoad")) {
// OpImageRead at (0, 0) (relative to the fragment), with the
// sample for SubpassInputMS.
var it = e.f.inst(res).ty;
while (e.t.get(it) == .array) it = e.t.get(it).array.elem;
const r = e.t.get(it).resource;
const img = try e.opRaw(.load, try e.subpassType(it), &.{e.val(res)});
const v4 = try e.t.vector(e.t.component(r.elem).?, 4);
if (e.subpass_coord == 0) {
e.subpass_coord = e.b.newId();
try e.b.emit(.types_globals, .constant_composite, &.{ try e.typeId(try e.t.vector(.int, 2)), e.subpass_coord, try e.constInt(0), try e.constInt(0) });
}
const coord = e.subpass_coord;
const texel = if (args.len == 1)
try e.op1(.image_read, v4, &.{ img, coord, 0x40, e.val(args[0]) }) // Sample
else
try e.op1(.image_read, v4, &.{ img, coord, 0 });
return e.reshape(texel, v4, ty);
}
const r = e.resourceInfo(res); const r = e.resourceInfo(res);
if (eq(u8, name, "GetDimensions")) { if (eq(u8, name, "GetDimensions")) {
try e.getDimensions(res, r, args); try e.getDimensions(res, r, args);
@ -3322,7 +3509,7 @@ const Emitter = struct {
} }
var ops: std.ArrayList(u32) = .empty; var ops: std.ArrayList(u32) = .empty;
if (call.op == .load) { if (call.op == .load) {
if (sh.rw and e.imageFormat(r.elem) == 0) try e.cap(.storage_image_read_without_format); if (sh.rw and (e.formatFor(res) orelse e.imageFormat(r.elem)) == 0) try e.cap(.storage_image_read_without_format);
try ops.appendSlice(e.arena, &.{ img, coord_id }); try ops.appendSlice(e.arena, &.{ img, coord_id });
if (mask != 0) { if (mask != 0) {
try ops.append(e.arena, mask); try ops.append(e.arena, mask);

1090
src/spirv/op_caps.zig Normal file

File diff suppressed because it is too large Load Diff