Vulkan memory model, ROV interlock, globallycoherent, legacy buffer matrix order

- -fspv-use-vulkan-memory-model: a port of spirv-opt's UpgradeMemoryModel
  (Coherent / Volatile become access flags, Device scope becomes
  QueueFamily); also used when ray tracing reads subgroup built-ins
  below Vulkan 1.3, as dxc does.
- Rasterizer-ordered views: SPIR-V fragment shader interlock around the
  entry; DXIL ROV metadata, properties, RDAT flag and shader flag.
- globallycoherent: SPIR-V Coherent; DXIL metadata, properties, RDAT.
- -fspv-use-legacy-buffer-matrix-order: row-major byte-address matrices.
- -fspv-preserve-interface accepted (zdxc keeps every interface variable).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Peter Li 2026-10-31 17:26:53 -07:00
parent 4e52358128
commit a951eba760
13 changed files with 532 additions and 11 deletions

View File

@ -110,6 +110,9 @@ const Resource = struct {
comparison: bool = false,
/// Structured UAV with a hidden counter (IncrementCounter, Append...).
has_counter: bool = false,
/// `globallycoherent` UAVs and rasterizer-ordered views.
coherent: bool = false,
rov: bool = false,
/// Registers in the range (arrays of resources); maxInt for unsized.
count: u32 = 1,
/// An array element's handle made at its use: a copy of the array's
@ -424,7 +427,7 @@ const Emitter = struct {
else => return e.unsupported("resource type '{s}' is not supported yet", .{r.name}),
};
const class: Resource.Class = if (kind == 13) .cbuffer else if (r.kind.isWritable() or r.kind == .consume_structured_buffer) .uav else .srv;
return .{ .global = 0, .class = class, .kind = kind, .elem = r.elem, .rty = ty, .has_counter = r.kind == .append_structured_buffer or r.kind == .consume_structured_buffer };
return .{ .global = 0, .class = class, .kind = kind, .elem = r.elem, .rty = ty, .has_counter = r.kind == .append_structured_buffer or r.kind == .consume_structured_buffer, .rov = std.mem.startsWith(u8, r.name, "RasterizerOrdered") };
}
// ------------------------------------------------------------------
@ -905,6 +908,7 @@ const Emitter = struct {
}
if (e.t.get(gty) != .resource) return e.unsupported("global '{s}' is not supported yet", .{g.name});
var res = try e.resourceFor(gty);
res.coherent = g.globally_coherent and res.class == .uav;
const class = res.class;
const want: u8 = switch (class) {
.uav => 'u',
@ -1064,6 +1068,8 @@ const Emitter = struct {
fn resourceProperties(e: *Emitter, res: Resource) Error![2]i64 {
var basic: i64 = res.kind;
if (res.class == .uav) basic |= 0x1000;
if (res.rov) basic |= 0x2000;
if (res.coherent) basic |= 0x4000;
if (res.comparison or res.has_counter) basic |= 0x8000;
const extra: i64 = switch (res.kind) {
13 => try e.cbufferSize(res),
@ -4253,12 +4259,15 @@ const Emitter = struct {
if (e.uses_int64) flags |= 1 << 20;
if (e.uses_min_precision) flags |= 1 << 5;
var uavs: u32 = 0;
var rov = false;
for (e.resources.items) |r| {
if (r.view) continue;
if (r.kind == 11 or r.kind == 12) flags |= 1 << 4;
if (r.class == .uav) uavs += @min(r.count, 9);
if (r.rov) rov = true;
}
if (uavs > 8) flags |= 1 << 15;
if (rov) flags |= 1 << 18;
if (e.uses_typed_uav_load) flags |= 1 << 13;
// Resources may not alias (DXIL 1.7+, when UAVs are used).
if (uavs > 0 and e.profile.minor >= 7) flags |= 1 << 33;
@ -4367,7 +4376,7 @@ const Emitter = struct {
try fields.appendSlice(e.arena, &head);
try fields.append(e.arena, try mdI32(dm, r.kind));
if (r.class == .uav) {
try fields.appendSlice(e.arena, &.{ try mdBool(dm, i1t, false), try mdBool(dm, i1t, r.has_counter), try mdBool(dm, i1t, false) });
try fields.appendSlice(e.arena, &.{ try mdBool(dm, i1t, r.coherent), try mdBool(dm, i1t, r.has_counter), try mdBool(dm, i1t, r.rov) });
} else try fields.append(e.arena, try mdI32(dm, 0)); // sample count
const extra: ?module.MdId = switch (r.kind) {
12 => try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, try e.stride(r.elem)) }),
@ -4395,10 +4404,12 @@ const Emitter = struct {
const globals = try e.arena.alloc(?libinfo.GlobalRes, e.dm.globals.items.len);
@memset(globals, null);
var uavs: u32 = 0;
var rov = false;
var raw = false;
for (e.resources.items) |r| {
if (r.view) continue;
if (r.class == .uav) uavs += @min(r.count, 9);
if (r.rov) rov = true;
if ((r.class == .uav or r.class == .srv) and (r.kind == 11 or r.kind == 12)) raw = true;
const lg = r.lib_global orelse continue;
globals[lg] = .{ .uav = r.class == .uav, .typed_multi = r.kind >= 1 and r.kind <= 10 and try e.flatCount(r.elem) > 1 };
@ -4413,6 +4424,7 @@ const Emitter = struct {
flags &= ~@as(u64, libinfo.bit.local);
if (raw) flags |= libinfo.bit.raw_structured;
if (uavs > 8) flags |= 1 << 15;
if (rov) flags |= 1 << 18;
return .{ .infos = infos, .flags = flags };
}
@ -4517,7 +4529,7 @@ const Emitter = struct {
.cbuffer => 2,
.sampler => 3,
};
try b.addResource(.{ .class = rdat_class, .kind = r.kind, .id = r.id, .space = bd.space, .lower = bd.index, .upper = upper, .name = try b.string(e.m.globals.items[r.global].name), .flags = if (r.class == .uav and r.has_counter) 2 else 0 });
try b.addResource(.{ .class = rdat_class, .kind = r.kind, .id = r.id, .space = bd.space, .lower = bd.index, .upper = upper, .name = try b.string(e.m.globals.items[r.global].name), .flags = if (r.class == .uav) @as(u32, @intFromBool(r.coherent)) | @as(u32, @intFromBool(r.has_counter)) << 1 | @as(u32, @intFromBool(r.rov)) << 2 else 0 });
if (r.lib_global) |lg| try res_index.put(e.arena, lg, count);
count += 1;
};

View File

@ -227,7 +227,7 @@ pub fn featureInfo(fl: u64) u64 {
.{ bit.view_id, 0x10000 }, .{ 1 << 24, 0x80000 }, .{ bit.wave, 0x4000 },
.{ bit.typed_uav_load, 0x800 }, .{ bit.resource_heap, 0x2000000 }, .{ bit.sampler_heap, 0x4000000 },
.{ bit.barycentrics, 0x20000 }, .{ bit.extended_command_info, 0x100000000 }, .{ bit.tiled_resources, 0x100 },
.{ 1 << 29, 0x1000000 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 },
.{ 1 << 29, 0x1000000 }, .{ 1 << 18, 0x1000 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 },
.{ bit.advanced_texture_ops, 0x20000000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 },
};
var out: u64 = 0;

View File

@ -258,6 +258,11 @@ pub const VkOptions = struct {
/// -fspv-flatten-resource-arrays: one variable (and binding) per
/// element of an array of resources.
flatten_arrays: bool = false,
/// -fspv-use-legacy-buffer-matrix-order: byte-address buffer matrices
/// are row major (dxc's old, incorrect assumption).
legacy_matrix_order: bool = false,
/// -fspv-use-vulkan-memory-model.
vulkan_memory_model: 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,
@ -318,6 +323,8 @@ pub const Global = struct {
input_attachment: ?u32 = null,
/// [[vk::image_format("...")]]: the SPIR-V ImageFormat.
image_format: ?u32 = null,
/// `globallycoherent` resources.
globally_coherent: bool = false,
ext: SpirvExt = .{},
};

View File

@ -436,7 +436,7 @@ const Lowerer = struct {
};
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;
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 .{} });
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, .globally_coherent = if (v.decl) |d| d.quals.globallycoherent else false, .ext = if (v.decl) |d| try l.spirvExt(d.attrs) else .{} });
const i: u32 = @intCast(l.m.globals.items.len - 1);
try l.globals.put(l.arena, v, i);
return i;

View File

@ -164,6 +164,10 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std
.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,
.fspv_use_legacy_buffer_matrix_order => opts.vk.legacy_matrix_order = true,
.fspv_use_vulkan_memory_model => opts.vk.vulkan_memory_model = true,
// (zdxc never removes interface variables.)
.fspv_preserve_interface => {},
.fvk_invert_y => opts.vk.invert_y = true,
.fvk_use_gl_layout => opts.vk.layout = .gl,
.fvk_use_dx_layout => opts.vk.layout = .dx,

View File

@ -223,7 +223,7 @@ 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, .fvk_invert_y, .fvk_use_dx_position_w, .fvk_use_gl_layout, .fvk_use_dx_layout, .fvk_use_scalar_layout, .fvk_support_nonzero_base_instance, .fvk_support_nonzero_base_vertex, .fspv_entrypoint_name_EQ, .fspv_enable_maximal_reconvergence, .fspv_use_unknown_image_format, .fspv_extension_EQ, .fspv_reflect => .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, .fspv_use_legacy_buffer_matrix_order, .fspv_preserve_interface, .fspv_use_vulkan_memory_model, .fvk_invert_y, .fvk_use_dx_position_w, .fvk_use_gl_layout, .fvk_use_dx_layout, .fvk_use_scalar_layout, .fvk_support_nonzero_base_instance, .fvk_support_nonzero_base_vertex, .fspv_entrypoint_name_EQ, .fspv_enable_maximal_reconvergence, .fspv_use_unknown_image_format, .fspv_extension_EQ, .fspv_reflect => .implemented,
// (Output is the same with or without the unoptimized-IR switch.)
.fcgl => .ignored,
// Diagnostics.
@ -237,7 +237,7 @@ 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, .exports, .export_shaders_only, .default_linkage, .fspv_use_legacy_buffer_matrix_order, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_use_vulkan_memory_model, .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, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_preserve_bindings, .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 },

View File

@ -40,6 +40,8 @@ pub const Op = enum(u16) {
decorate_id = 332,
execution_mode_id = 331,
decorate_string = 5632,
begin_invocation_interlock_ext = 5364,
end_invocation_interlock_ext = 5365,
constant_false = 42,
constant = 43,
constant_composite = 44,

View File

@ -9,6 +9,7 @@ const ir = @import("../ir/ir.zig");
const types = @import("../sema/types.zig");
const texture = @import("../ir/texture.zig");
const op_caps = @import("op_caps.zig");
const memory_model = @import("memory_model.zig");
const builder = @import("builder.zig");
const diag = @import("../diag.zig");
const layout = @import("../ir/layout.zig");
@ -92,6 +93,7 @@ const Capability = enum(u32) {
sampled_image_array_non_uniform_indexing = 5307,
storage_buffer_array_non_uniform_indexing = 5308,
storage_image_array_non_uniform_indexing = 5309,
vulkan_memory_model = 5345,
/// (Inline SPIR-V may use any value.)
_,
};
@ -242,6 +244,9 @@ const Emitter = struct {
iface: std.ArrayList(Id) = .empty,
/// Compute derivatives' execution mode (0: none).
derivative_mode: u32 = 0,
/// Rasterizer-ordered views: the fragment interlock execution
/// mode (0: none).
interlock_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,
@ -577,7 +582,7 @@ const Emitter = struct {
return id;
}
fn constUint(e: *Emitter, v: u64) Error!Id {
pub fn constUint(e: *Emitter, v: u64) Error!Id {
return e.constBits(try e.scalarType(.uint), v, 1);
}
@ -806,9 +811,22 @@ const Emitter = struct {
try e.emitFunction(m.functions.items[v.fi], v.id, v.bindings);
}
// The Vulkan memory model, when asked for or needed (as dxc).
const vulkan_mm = e.vk.vulkan_memory_model or e.capabilities.contains(.vulkan_memory_model);
if (vulkan_mm) {
var tess_control = false;
for (m.entries.items) |en| tess_control = tess_control or en.stage == .hull;
try memory_model.upgrade(e, tess_control);
try e.cap(.vulkan_memory_model);
if (e.spv_minor < 5) {
// (The option implies the extension is allowed.)
if (e.vk.vulkan_memory_model) try e.vk.extensions.append(e.arena, "SPV_KHR_vulkan_memory_model");
try e.extension("SPV_KHR_vulkan_memory_model");
}
}
for (e.capabilities.keys()) |c| try e.b.emit(.capabilities, .capability, &.{@backingInt(c)});
if (e.glsl != 0) try e.b.emitWithString(.ext_inst_imports, .ext_inst_import, &.{e.glsl}, "GLSL.std.450", &.{});
try e.b.emit(.memory_model, .memory_model, &.{ 0, 1 }); // Logical GLSL450
try e.b.emit(.memory_model, .memory_model, &.{ 0, if (vulkan_mm) 3 else 1 }); // Logical Vulkan / GLSL450
for (m.entries.items, 0..) |*entry, k| {
e.setEntry(@intCast(k));
try e.entryPoint(entry);
@ -818,6 +836,36 @@ const Emitter = struct {
}
}
fn usesRov(e: *Emitter) bool {
for (e.m.globals.items) |g| {
var t = g.ty;
while (e.t.get(t) == .array) t = e.t.get(t).array.elem;
if (e.t.get(t) == .resource and std.mem.startsWith(u8, e.t.get(t).resource.name, "RasterizerOrdered")) return true;
}
return false;
}
/// OpBeginInvocationInterlockEXT, ordered per sample when the shader
/// reads SV_SampleIndex, per shading rate region with SV_ShadingRate
/// (the last of them declared), else per pixel.
fn beginInterlock(e: *Emitter) Error!void {
var mode: u32 = 5366; // PixelInterlockOrderedEXT
var capability: u32 = 5378; // FragmentShaderPixelInterlockEXT
for (e.entry.inputs.items) |el| {
if (std.ascii.eqlIgnoreCase(el.semantic, "SV_SampleIndex")) {
mode = 5368; // SampleInterlockOrderedEXT
capability = 5363; // FragmentShaderSampleInterlockEXT
} else if (std.ascii.eqlIgnoreCase(el.semantic, "SV_ShadingRate")) {
mode = 5370; // ShadingRateInterlockOrderedEXT
capability = 5372; // FragmentShaderShadingRateInterlockEXT
}
}
e.st.interlock_mode = mode;
try e.cap(@enumFromInt(capability));
try e.extension("SPV_EXT_fragment_shader_interlock");
try e.b.emit(.functions, .begin_invocation_interlock_ext, &.{});
}
fn recordCall(e: *Emitter, callee: Id) Error!void {
const gop = try e.fn_calls.getOrPut(e.arena, e.cur_fn);
if (!gop.found_existing) gop.value_ptr.* = .empty;
@ -948,6 +996,7 @@ const Emitter = struct {
else => {},
}
if (e.st.derivative_mode != 0) try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, e.st.derivative_mode });
if (e.st.interlock_mode != 0) try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, e.st.interlock_mode });
// vk::ext_execution_mode(...) / ext_execution_mode_id(...).
for (e.st.ext_modes.items) |em| {
var words: std.ArrayList(u32) = .empty;
@ -1005,6 +1054,7 @@ const Emitter = struct {
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
if (g.globally_coherent) try e.b.emit(.annotations, .decorate, &.{ id.*, 23 }); // Coherent
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.*);
}
@ -1019,6 +1069,7 @@ const Emitter = struct {
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
if (g.globally_coherent) try e.b.emit(.annotations, .decorate, &.{ var_id, 23 }); // Coherent
try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{});
try e.userType(var_id, g.ty, g);
if (g.input_attachment) |ia| try e.b.emit(.annotations, .decorate, &.{ var_id, 43, ia }); // InputAttachmentIndex
@ -2384,7 +2435,13 @@ const Emitter = struct {
if (e.mesh_params.contains(.{ callee, @intCast(k) })) continue;
try ops.append(e.arena, e.val(a));
}
// Rasterizer-ordered views: the whole pixel shader is the
// critical section (entered exactly once, as Vulkan
// requires; dxc's optimizer narrows it to the accesses).
const interlock = e.entry.stage == .pixel and c.func == e.entry.func and e.cur_fn == e.func_ids[e.entry.wrapper] and e.usesRov();
if (interlock) try e.beginInterlock();
e.vals[ri] = try e.op1(.function_call, i.ty, ops.items);
if (interlock) try e.b.emit(.functions, .end_invocation_interlock_ext, &.{});
},
.intrinsic => |c| {
if (std.mem.eql(u8, c.name, "SetMeshOutputCounts")) {
@ -3631,7 +3688,7 @@ const Emitter = struct {
/// The scalar type and byte offset of flattened component `k` of a
/// value of `ty` in a byte-address buffer (natural alignment).
fn rawComponent(e: *Emitter, ty: TypeId, k: u32) Error!struct { TypeId, u32 } {
const off = layout.componentOffset(e.arena, e.t, ty, false, k, .dx_packed) catch return e.unsupported("byte-address buffer accesses of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)});
const off = layout.componentOffset(e.arena, e.t, ty, e.vk.legacy_matrix_order, k, .dx_packed) catch return e.unsupported("byte-address buffer accesses of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)});
var cur = ty;
var kk = k;
while (true) switch (e.t.get(cur)) {
@ -3990,7 +4047,12 @@ const Emitter = struct {
5326 => e.entry.stage == .intersection,
else => false,
};
if (changing and e.spv_minor >= 6) try e.b.emit(.annotations, .decorate, &.{ v, 21 }); // Volatile
if (changing) {
try e.b.emit(.annotations, .decorate, &.{ v, 21 }); // Volatile
// Before Vulkan 1.3 Volatile needs the Vulkan memory model
// (which turns the decoration into Volatile loads).
if (e.spv_minor < 6) try e.cap(.vulkan_memory_model);
}
try e.useVar(v);
try e.builtin_inputs.put(e.arena, builtin, v);
return v;

307
src/spirv/memory_model.zig Normal file
View File

@ -0,0 +1,307 @@
//! The Vulkan memory model (-fspv-use-vulkan-memory-model, or modules that
//! need it): a port of spirv-opt's UpgradeMemoryModel pass, which dxc runs
//! on its output. Coherent and Volatile decorations become flags on the
//! loads, stores, image reads / writes and atomics that reach them, and
//! Device scopes become QueueFamily.
const std = @import("std");
const builder = @import("builder.zig");
const op_caps = @import("op_caps.zig");
const Id = builder.Id;
const coherent_dec = 23;
const volatile_dec = 21;
const scope_device = 1;
const scope_workgroup = 2;
const scope_queue_family = 5;
const Attrs = struct { coherent: bool = false, @"volatile": bool = false };
fn Pass(comptime E: type) type {
return struct {
e: E,
a: std.mem.Allocator,
/// Result id -> (section, word offset) of its instruction.
defs: std.AutoHashMapUnmanaged(Id, struct { sec: builder.Section, at: usize }) = .empty,
/// Decorations: (target, member or maxInt, decoration).
decs: std.ArrayList([3]u32) = .empty,
const Self = @This();
fn words(p: *Self, id: Id) ?[]const u32 {
const d = p.defs.get(id) orelse return null;
const s = p.e.b.sections.get(d.sec).items;
return s[d.at..][0 .. s[d.at] >> 16];
}
fn opcode(w: []const u32) u32 {
return w[0] & 0xffff;
}
fn typeOf(p: *Self, id: Id) ?Id {
const w = p.words(id) orelse return null;
const l = op_caps.resultLayout(opcode(w));
return if (l.ty) |t| w[1 + t] else null;
}
/// The storage class of a pointer-typed value.
fn storageOf(p: *Self, id: Id) ?u32 {
const t = p.words(p.typeOf(id) orelse return null) orelse return null;
return if (opcode(t) == 32) t[2] else null;
}
fn constValue(p: *Self, id: Id) ?u32 {
const w = p.words(id) orelse return null;
return if (opcode(w) == 43) w[3] else null;
}
fn hasDec(p: *Self, id: Id, member: u32, dec: u32) bool {
for (p.decs.items) |d| {
if (d[0] != id or d[2] != dec) continue;
if (d[1] == std.math.maxInt(u32) or member == std.math.maxInt(u32) or d[1] == member) return true;
}
return false;
}
/// Coherent / Volatile of a struct member reached through
/// `indices` (innermost last), then of any type below it.
fn checkType(p: *Self, ptr_type: Id, indices: []const Id) Attrs {
var r: Attrs = .{};
var elem = (p.words(ptr_type) orelse return r)[3];
var i = indices.len;
while (i > 0 and !(r.coherent and r.@"volatile")) {
i -= 1;
const w = p.words(elem) orelse return r;
switch (opcode(w)) {
32 => elem = w[3],
30 => {
const k = p.constValue(indices[i]) orelse return r;
r.coherent = r.coherent or p.hasMemberDec(elem, k, coherent_dec);
r.@"volatile" = r.@"volatile" or p.hasMemberDec(elem, k, volatile_dec);
elem = w[2 + k];
},
else => elem = w[2],
}
}
if (!(r.coherent and r.@"volatile")) {
const all = p.checkAllTypes(elem);
r.coherent = r.coherent or all.coherent;
r.@"volatile" = r.@"volatile" or all.@"volatile";
}
return r;
}
fn hasMemberDec(p: *Self, st: Id, member: u32, dec: u32) bool {
for (p.decs.items) |d| if (d[0] == st and d[2] == dec and (d[1] == member or d[1] == std.math.maxInt(u32))) return true;
return false;
}
fn checkAllTypes(p: *Self, ty: Id) Attrs {
var r: Attrs = .{};
var stack: std.ArrayList(Id) = .empty;
var seen: std.AutoHashMapUnmanaged(Id, void) = .empty;
stack.append(p.a, ty) catch return r;
while (stack.pop()) |t| {
if ((seen.getOrPut(p.a, t) catch return r).found_existing) continue;
const w = p.words(t) orelse continue;
switch (opcode(w)) {
30 => {
r.coherent = r.coherent or p.hasMemberDec(t, std.math.maxInt(u32), coherent_dec);
r.@"volatile" = r.@"volatile" or p.hasMemberDec(t, std.math.maxInt(u32), volatile_dec);
if (r.coherent and r.@"volatile") return r;
stack.appendSlice(p.a, w[2..]) catch return r;
},
23, 24, 28, 29 => stack.append(p.a, w[2]) catch return r,
32 => stack.append(p.a, w[3]) catch return r,
else => {},
}
}
return r;
}
fn isPointerLike(p: *Self, id: Id) bool {
const t = p.words(p.typeOf(id) orelse return false) orelse return false;
return switch (opcode(t)) {
25, 27, 32 => true, // image, sampled image, pointer
else => false,
};
}
/// Follows a pointer (or image) back to the variables it comes
/// from.
fn trace(p: *Self, id: Id, indices0: []const Id, visited: *std.AutoHashMapUnmanaged(Id, void)) std.mem.Allocator.Error!Attrs {
if ((try visited.getOrPut(p.a, id)).found_existing) return .{};
const w = p.words(id) orelse return .{};
var indices: std.ArrayList(Id) = .empty;
try indices.appendSlice(p.a, indices0);
switch (opcode(w)) {
59, 55 => { // OpVariable, OpFunctionParameter
var r: Attrs = .{ .coherent = p.hasDec(id, 0, coherent_dec), .@"volatile" = p.hasDec(id, 0, volatile_dec) };
if (!(r.coherent and r.@"volatile")) {
const t = p.checkType(w[1], indices.items);
r.coherent = r.coherent or t.coherent;
r.@"volatile" = r.@"volatile" or t.@"volatile";
}
return r;
},
65, 66 => { // OpAccessChain, OpInBoundsAccessChain
var i = w.len;
while (i > 4) {
i -= 1;
try indices.append(p.a, w[i]);
}
},
67, 70 => { // OpPtrAccessChain, OpInBoundsPtrAccessChain
var i = w.len;
while (i > 5) {
i -= 1;
try indices.append(p.a, w[i]);
}
},
else => {},
}
var r: Attrs = .{};
const l = op_caps.resultLayout(opcode(w));
for (w[1..], 0..) |x, k| {
if ((l.ty != null and k == l.ty.?) or (l.id != null and k == l.id.?)) continue;
if (!p.isPointerLike(x)) continue;
const o = try p.trace(x, indices.items, visited);
r.coherent = r.coherent or o.coherent;
r.@"volatile" = r.@"volatile" or o.@"volatile";
}
return r;
}
fn attributes(p: *Self, ptr: Id) std.mem.Allocator.Error!struct { Attrs, u32 } {
if (p.storageOf(ptr) == 4) return .{ .{ .coherent = true }, scope_workgroup }; // Workgroup
var visited: std.AutoHashMapUnmanaged(Id, void) = .empty;
return .{ try p.trace(ptr, &.{}, &visited), scope_queue_family };
}
};
}
/// Rewrites the module for the Vulkan memory model (the caller emits the
/// capability, extension and memory model instruction).
pub fn upgrade(e: anytype, has_tess_control: bool) !void {
var p: Pass(@TypeOf(e)) = .{ .e = e, .a = e.arena };
for ([_]builder.Section{ .types_globals, .functions }) |sec| {
const s = e.b.sections.get(sec).items;
var at: usize = 0;
while (at < s.len) : (at += s[at] >> 16) {
const l = op_caps.resultLayout(s[at] & 0xffff);
if (l.id) |k| try p.defs.put(p.a, s[at + 1 + k], .{ .sec = sec, .at = at });
}
}
{
const s = e.b.sections.get(.annotations).items;
var at: usize = 0;
while (at < s.len) : (at += s[at] >> 16) switch (s[at] & 0xffff) {
71, 332 => try p.decs.append(p.a, .{ s[at + 1], std.math.maxInt(u32), s[at + 2] }),
72 => try p.decs.append(p.a, .{ s[at + 1], s[at + 2], s[at + 3] }),
else => {},
};
}
// Tessellation control shaders that write outputs: barriers that
// order memory also order output memory.
var writes_output = false;
if (has_tess_control) {
const s = e.b.sections.get(.functions).items;
var at: usize = 0;
while (at < s.len and !writes_output) : (at += s[at] >> 16) {
for (s[at + 1 .. at + (s[at] >> 16)]) |x| if (p.storageOf(x) == 3) {
writes_output = true;
};
}
}
const old = try p.a.dupe(u32, e.b.sections.get(.functions).items);
var out: std.ArrayList(u32) = .empty;
var at: usize = 0;
while (at < old.len) : (at += old[at] >> 16) {
const n = old[at] >> 16;
var w: std.ArrayList(u32) = .empty;
try w.appendSlice(p.a, old[at..][0..n]);
const op = w.items[0] & 0xffff;
const l = op_caps.resultLayout(op);
// Word index of in-operand 0.
const in0: usize = 1 + @as(usize, @intFromBool(l.ty != null)) + @intFromBool(l.id != null);
switch (op) {
61, 62 => { // OpLoad, OpStore
const ptr = w.items[in0];
var at_s = try p.attributes(ptr);
const sc = p.storageOf(ptr);
if (sc == 7 or sc == 6) at_s[0].coherent = false; // Function, Private
try flags(e, &w, in0 + @as(usize, if (op == 61) 1 else 2), at_s[0], op == 61, false, at_s[1]);
},
98, 99, 4290 => { // OpImageRead, OpImageWrite, OpImageSparseRead
const at_s = try p.attributes(w.items[in0]);
try flags(e, &w, in0 + @as(usize, if (op == 99) 3 else 2), at_s[0], op != 99, true, at_s[1]);
},
else => {},
}
if (isAtomic(op)) {
const at_s = try p.attributes(w.items[in0]);
if (at_s[0].@"volatile") {
w.items[in0 + 2] = try e.constUint((p.constValue(w.items[in0 + 2]) orelse 0) | 0x8000);
if (op == 230 or op == 231) w.items[in0 + 3] = try e.constUint((p.constValue(w.items[in0 + 3]) orelse 0) | 0x8000);
}
if (p.constValue(w.items[in0 + 1]) == scope_device) w.items[in0 + 1] = try e.constUint(scope_queue_family);
} else if (op == 224) { // OpControlBarrier
if (p.constValue(w.items[2]) == scope_device) w.items[2] = try e.constUint(scope_queue_family);
if (writes_output) if (p.constValue(w.items[3])) |sem| if (sem & 0x1e != 0) {
w.items[3] = try e.constUint(sem | 0x1000); // OutputMemory
};
} else if (op == 225) { // OpMemoryBarrier
if (p.constValue(w.items[1]) == scope_device) w.items[1] = try e.constUint(scope_queue_family);
}
w.items[0] = (@as(u32, @intCast(w.items.len)) << 16) | op;
try out.appendSlice(p.a, w.items);
}
const fs = e.b.sections.getPtr(.functions);
fs.clearRetainingCapacity();
try fs.appendSlice(e.b.gpa, out.items);
// Coherent and Volatile decorations are gone.
const an = e.b.sections.getPtr(.annotations);
var r: usize = 0;
var wr: usize = 0;
while (r < an.items.len) {
const n = an.items[r] >> 16;
const dec_word: ?u32 = switch (an.items[r] & 0xffff) {
71, 332 => an.items[r + 2],
72 => an.items[r + 3],
else => null,
};
if (dec_word == null or (dec_word.? != coherent_dec and dec_word.? != volatile_dec)) {
std.mem.copyForwards(u32, an.items[wr..][0..n], an.items[r..][0..n]);
wr += n;
}
r += n;
}
an.shrinkRetainingCapacity(wr);
}
fn isAtomic(op: u32) bool {
return switch (op) {
227...242, 318, 319, 5614, 5615, 6035 => true,
else => false,
};
}
/// Memory access (or image operand) flags for a coherent / volatile
/// access at word `k`, then the scope operand.
fn flags(e: anytype, w: *std.ArrayList(u32), k: usize, at: Attrs, visible: bool, image: bool, scope: u32) !void {
if (!at.coherent and !at.@"volatile") return;
var f: u32 = if (k < w.items.len) w.items[k] else 0;
if (at.coherent) {
if (image) {
f |= 0x400 | @as(u32, if (visible) 0x200 else 0x100); // NonPrivateTexel, MakeTexelVisible / Available
} else {
f |= 0x20 | @as(u32, if (visible) 0x10 else 0x8); // NonPrivatePointer, MakePointerVisible / Available
}
}
if (at.@"volatile") f |= if (image) 0x800 else 0x1;
if (k < w.items.len) w.items[k] = f else try w.append(e.arena, f);
if (at.coherent) try w.append(e.arena, try e.constUint(scope));
}

View File

@ -3,6 +3,8 @@
//! SPIRV-Headers' spirv.core.grammar.json in the DXC tree
//! (external/SPIRV-Headers).
const std = @import("std");
const ops = [_][2]u32{
.{ 24, 0 }, // OpTypeMatrix
.{ 29, 1 }, // OpTypeRuntimeArray
@ -1088,3 +1090,70 @@ pub fn need(table: []const Need, value: u32) ?Need {
for (table) |n| if (n.value == value) return n;
return null;
}
/// Opcodes whose first operands are a result type and a result id.
const type_result_ops = [_]u16{
1, 12, 41, 42, 43, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 57,
59, 60, 61, 65, 66, 67, 68, 69, 70, 77, 78, 79, 80, 81, 82, 83,
84, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 100, 101,
102, 103, 104, 105, 106, 107, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
119, 120, 121, 122, 123, 124, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151,
152, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184,
185, 186, 187, 188, 189, 190, 191, 194, 195, 196, 197, 198, 199, 200, 201, 202,
203, 204, 205, 207, 208, 209, 210, 211, 212, 213, 214, 215, 227, 229, 230, 231,
232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 245, 259, 261, 262, 263,
264, 265, 266, 267, 268, 269, 270, 271, 274, 275, 276, 277, 278, 279, 282, 283,
284, 285, 286, 291, 292, 293, 294, 295, 296, 299, 300, 303, 304, 305, 306, 307,
308, 309, 310, 311, 312, 313, 314, 315, 316, 318, 320, 321, 323, 324, 325, 326,
328, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347,
348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363,
364, 365, 366, 400, 401, 402, 403, 4160, 4161, 4162, 4164, 4166, 4181, 4183, 4184, 4195,
4418, 4419, 4420, 4421, 4422, 4423, 4424, 4425, 4427, 4428, 4429, 4430, 4431, 4432, 4433, 4434,
4447, 4450, 4451, 4452, 4453, 4454, 4455, 4457, 4459, 4460, 4461, 4462, 4463, 4477, 4479, 4480,
4481, 4482, 4483, 4497, 4500, 4501, 4502, 4503, 4540, 4541, 4542, 4545, 5000, 5001, 5002, 5003,
5004, 5005, 5006, 5007, 5011, 5012, 5056, 5074, 5078, 5090, 5101, 5110, 5111, 5119, 5126, 5129,
5147, 5148, 5158, 5159, 5252, 5253, 5254, 5255, 5257, 5258, 5265, 5267, 5268, 5269, 5270, 5271,
5272, 5273, 5274, 5275, 5276, 5277, 5278, 5283, 5289, 5292, 5293, 5296, 5300, 5301, 5302, 5307,
5308, 5320, 5322, 5323, 5324, 5325, 5326, 5327, 5328, 5329, 5330, 5331, 5332, 5333, 5334, 5340,
5345, 5346, 5347, 5348, 5349, 5350, 5351, 5352, 5359, 5361, 5362, 5366, 5367, 5369, 5372, 5373,
5374, 5375, 5376, 5377, 5378, 5379, 5381, 5382, 5384, 5390, 5391, 5392, 5393, 5394, 5395, 5396,
5398, 5427, 5428, 5429, 5430, 5431, 5432, 5433, 5434, 5435, 5436, 5437, 5438, 5439, 5571, 5572,
5573, 5574, 5575, 5577, 5580, 5585, 5586, 5587, 5588, 5589, 5590, 5591, 5592, 5593, 5594, 5595,
5596, 5597, 5598, 5600, 5601, 5610, 5611, 5614, 5615, 5631, 5699, 5713, 5714, 5715, 5716, 5717,
5718, 5719, 5720, 5721, 5722, 5723, 5724, 5725, 5726, 5727, 5728, 5729, 5730, 5731, 5732, 5733,
5734, 5735, 5736, 5737, 5738, 5739, 5740, 5741, 5742, 5743, 5744, 5745, 5746, 5747, 5748, 5749,
5750, 5751, 5752, 5753, 5754, 5755, 5756, 5757, 5758, 5759, 5760, 5761, 5762, 5763, 5764, 5765,
5766, 5767, 5768, 5769, 5770, 5771, 5772, 5773, 5774, 5775, 5776, 5777, 5778, 5779, 5780, 5781,
5782, 5783, 5784, 5785, 5786, 5787, 5788, 5789, 5790, 5791, 5792, 5793, 5794, 5795, 5796, 5797,
5798, 5799, 5800, 5801, 5802, 5803, 5804, 5805, 5806, 5807, 5808, 5809, 5810, 5811, 5812, 5813,
5814, 5815, 5816, 5818, 5819, 5840, 5841, 5842, 5843, 5846, 5847, 5848, 5849, 5850, 5851, 5852,
5853, 5854, 5855, 5856, 5857, 5858, 5859, 5860, 5861, 5862, 5863, 5864, 5865, 5866, 5867, 5868,
5869, 5870, 5871, 5872, 5873, 5874, 5875, 5876, 5877, 5878, 5879, 5880, 5881, 5882, 5923, 5924,
5925, 5926, 5927, 5928, 5929, 5930, 5931, 5932, 5933, 5934, 5938, 5949, 6016, 6017, 6018, 6019,
6020, 6021, 6022, 6023, 6024, 6025, 6026, 6027, 6028, 6029, 6030, 6031, 6032, 6035, 6116, 6117,
6145, 6163, 6165, 6237, 6242, 6244, 6251, 6252, 6253, 6254, 6258, 6401, 6402, 6403, 6404, 6405,
6406, 6407, 6408, 6426, 6428, 6529, 6530, 6531, 6916, 6917, 6918,
};
/// Opcodes with a result id but no result type.
const result_ops = [_]u16{
7, 11, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 73, 248, 322, 327, 4163, 4190, 4417, 4456, 4472, 5076,
5103, 5104, 5115, 5281, 5288, 5313, 5341, 5358, 5370, 5371, 5609, 5700, 5701, 5702, 5703, 5704,
5705, 5706, 5707, 5708, 5709, 5710, 5711, 5712, 5911, 5912, 5913, 6086, 6199,
};
/// Where an instruction's result type and result id are (operand
/// indices), if it has them.
pub fn resultLayout(opcode: u32) struct { ty: ?u32, id: ?u32 } {
const o: u16 = @intCast(opcode & 0xffff);
if (std.sort.binarySearch(u16, &type_result_ops, o, order) != null) return .{ .ty = 0, .id = 1 };
if (std.sort.binarySearch(u16, &result_ops, o, order) != null) return .{ .ty = null, .id = 0 };
return .{ .ty = null, .id = null };
}
fn order(a: u16, b: u16) std.math.Order {
return std.math.order(a, b);
}

15
test/dxil/rov.hlsl Normal file
View File

@ -0,0 +1,15 @@
// PROFILE: ps_6_6
// Rasterizer-ordered views and globallycoherent UAVs: resource metadata,
// annotateHandle properties and the ROVs shader flag.
// ZCHECK: Raster Ordered UAVs
// ZCHECK: ResourceProperties { i32 20491, i32 0 }
// ZCHECK: ResourceProperties { i32 12290, i32 1033 }
// ZCHECK: i32 2, i1 false, i1 false, i1 true,
// ZCHECK: i32 11, i1 true, i1 false, i1 false,
globallycoherent RWByteAddressBuffer buffer1 : register(u0);
RasterizerOrderedTexture2D<float4> rov : register(u1);
float4 main(float4 p : SV_Position) : SV_Target {
rov[uint2(p.xy)] += buffer1.Load(0);
return rov[uint2(p.xy)];
}

21
test/spirv/rov.hlsl Normal file
View File

@ -0,0 +1,21 @@
// PROFILE: ps_6_0
// FLAGS: -E main -fspv-use-legacy-buffer-matrix-order
// Rasterizer-ordered views: one fragment interlock critical section
// around the shader; globallycoherent resources are Coherent; legacy
// (row-major) byte-address buffer matrices.
// ZCHECK: OpCapability FragmentShaderPixelInterlockEXT
// ZCHECK: OpExtension "SPV_EXT_fragment_shader_interlock"
// ZCHECK: OpExecutionMode %main PixelInterlockOrderedEXT
// ZCHECK: OpDecorate %buffer1 Coherent
// ZCHECK: OpBeginInvocationInterlockEXT
// ZCHECK: OpEndInvocationInterlockEXT
// ZCHECK: OpIAdd %uint {{.*}} %uint_12
globallycoherent RWByteAddressBuffer buffer1 : register(u0);
RasterizerOrderedTexture2D<float4> rov : register(u1);
ByteAddressBuffer mats : register(t0);
float4 main(float4 p : SV_Position) : SV_Target {
float2x3 m = mats.Load<float2x3>(0);
rov[uint2(p.xy)] += float4(m[1], buffer1.Load(0));
return rov[uint2(p.xy)];
}

View File

@ -0,0 +1,22 @@
// PROFILE: ps_6_0
// FLAGS: -E main -fspv-use-vulkan-memory-model
// ENV: vulkan1.1
// The Vulkan memory model: coherent accesses carry visibility /
// availability flags and a QueueFamily scope instead of Coherent
// decorations, and atomics use QueueFamily for Device scope.
// ZCHECK: OpCapability VulkanMemoryModel
// ZCHECK: OpExtension "SPV_KHR_vulkan_memory_model"
// ZCHECK: OpMemoryModel Logical Vulkan
// ZCHECK: OpLoad %uint {{.*}} MakePointerVisible|NonPrivatePointer %uint_5
// ZCHECK: OpStore {{.*}} MakePointerAvailable|NonPrivatePointer %uint_5
// ZCHECK: OpAtomicIAdd %uint {{.*}} %uint_5 %uint_0
globallycoherent RWByteAddressBuffer buffer1;
globallycoherent RWStructuredBuffer<uint> buffer2;
RWStructuredBuffer<uint> buffer3;
float4 main() : SV_Target {
buffer2[0] = buffer1.Load(0) + buffer3[0];
uint old;
InterlockedAdd(buffer3[1], 1, old);
return old;
}