From 0e91e298aa5b7d54f8cf5345ecb88bea9cb98f5c Mon Sep 17 00:00:00 2001 From: Peter Li Date: Sat, 31 Oct 2026 10:00:06 -0700 Subject: [PATCH] Textures and samplers on both backends Texture1D/2D/3D/Cube (and arrays), Texture2DMS, RWTexture*, Buffer and RWBuffer, SamplerState and SamplerComparisonState. Methods: Sample, SampleBias, SampleLevel, SampleGrad, SampleCmp, SampleCmpLevelZero, SampleCmpLevel/Bias/Grad (DXIL 6.7/6.8), Load, operator[] reads and writes, Gather and GatherCmp (per channel, one offset), CalculateLevelOfDetail(Unclamped), GetDimensions (textures and buffers) and, on DXIL, GetSamplePosition. Argument roles come from one shared decoder (src/ir/texture.zig); out parameters of methods go through temporaries. DXIL follows dxc's argument layout (undef padding, zero offsets), resource metadata and properties, replicated typed stores and the typed UAV load flag. SPIR-V follows dxc's image types (unknown depth, inferred formats for typed buffers and RW textures), capabilities and image operands. Also: SPIR-V interpolation decorations on pixel inputs and vertex outputs (as dxc), a crash on array pixel inputs, and a miscompile on both backends where swizzle components lived in a 16-entry static buffer, so a function with more than 16 swizzles could silently read the wrong components. test/spirv/check.sh (part of `zig build oracle`) checks SPIR-V disassembly like test/dxil/check.sh does for DXIL. Not yet: status (sparse feedback) arguments, Gather with four offsets, and texel offsets that need loop unrolling to become constants. Co-Authored-By: Claude Opus 5.5 --- build.zig | 5 + src/dxil/emit.zig | 273 ++++++++++++++++++++++++++++- src/ir/lower.zig | 39 +++-- src/ir/texture.zig | 258 +++++++++++++++++++++++++++ src/root.zig | 2 + src/spirv/builder.zig | 7 + src/spirv/emit.zig | 396 +++++++++++++++++++++++++++++++++++++++++- 7 files changed, 953 insertions(+), 27 deletions(-) create mode 100644 src/ir/texture.zig diff --git a/build.zig b/build.zig index d281c48..03c1aae 100644 --- a/build.zig +++ b/build.zig @@ -78,6 +78,11 @@ pub fn build(b: *std.Build) void { dxil_checks.setCwd(b.path(".")); dxil_checks.has_side_effects = true; oracle_step.dependOn(&dxil_checks.step); + const spirv_checks = b.addSystemCommand(&.{ "sh", "test/spirv/check.sh" }); + spirv_checks.addArtifactArg(exe); + spirv_checks.setCwd(b.path(".")); + spirv_checks.has_side_effects = true; + oracle_step.dependOn(&spirv_checks.step); const oracle_parse_step = b.step("oracle-parse", "Parse every dxc-valid corpus file with zdxc"); const oracle_parse = b.addSystemCommand(&.{ "sh", "test/oracle/parse.sh" }); diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 6f42ea6..21b5a51 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -15,6 +15,7 @@ const container = @import("container.zig"); const hash = @import("hash.zig"); const layout = @import("../ir/layout.zig"); const signature = @import("signature.zig"); +const texture = @import("../ir/texture.zig"); const TypeId = types.TypeId; const TypeTable = types.TypeTable; @@ -71,6 +72,8 @@ const Resource = struct { kind: u32, handle: Value = undefined, elem: TypeId, + /// SamplerComparisonState. + comparison: bool = false, const Class = enum(u8) { srv = 0, uav = 1, cbuffer = 2, sampler = 3 }; }; @@ -110,6 +113,8 @@ const Emitter = struct { /// 16-bit min-precision values cross the signature. uses_min_precision: bool = false, uses_view_id: bool = false, + /// A typed UAV load of more than one component. + uses_typed_uav_load: bool = false, uses_inner_coverage: bool = false, sig_in: []signature.Element = &.{}, @@ -290,6 +295,13 @@ const Emitter = struct { }; for (e.m.globals.items, 0..) |g, gi| { if (g.space != .resource) continue; + if (e.t.get(g.ty) == .sampler) { + if (g.binding.explicit and g.binding.class != 's') return e.unsupported("binding '{s}' to the wrong register class", .{g.name}); + try e.resources.append(e.arena, .{ .global = @intCast(gi), .class = .sampler, .id = counts[3], .kind = 14, .elem = g.ty, .comparison = e.t.get(g.ty).sampler.comparison }); + counts[3] += 1; + try e.resource_of_global.put(e.arena, @intCast(gi), @intCast(e.resources.items.len - 1)); + continue; + } const r = switch (e.t.get(g.ty)) { .resource => |r| r, else => return e.unsupported("global '{s}' is not supported yet", .{g.name}), @@ -298,6 +310,15 @@ const Emitter = struct { .structured_buffer, .rw_structured_buffer => 12, .byte_address_buffer, .rw_byte_address_buffer => 11, .buffer, .rw_buffer => 10, + .texture1d, .rw_texture1d => 1, + .texture2d, .rw_texture2d => 2, + .texture2dms, .rw_texture2dms => 3, + .texture3d, .rw_texture3d => 4, + .texture_cube => 5, + .texture1d_array, .rw_texture1d_array => 6, + .texture2d_array, .rw_texture2d_array => 7, + .texture2dms_array, .rw_texture2dms_array => 8, + .texture_cube_array => 9, else => return e.unsupported("resource type '{s}' is not supported yet", .{r.name}), }; const class: Resource.Class = if (r.kind.isWritable()) .uav else .srv; @@ -375,10 +396,12 @@ 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.comparison) basic |= 0x8000; const extra: i64 = switch (res.kind) { 13 => try e.cbufferSize(res), 12 => try e.stride(res.elem), - 10 => blk: { + 14 => 0, + 1...10 => blk: { const n = try e.flatCount(res.elem); break :blk try e.compType(e.compOf(res.elem)) | (@as(i64, n) << 8); }, @@ -801,7 +824,7 @@ const Emitter = struct { try e.resourceStore(frame, x.res, x.index, x.value); return .none; }, - .method => |x| return e.unsupported("method '{s}' is not supported yet", .{x.name}), + .method => |x| return e.method(frame, x.name, x.res, x.args, i.ty), .input => |k| return e.input(k, i.ty), .output => |o| { try e.output(frame, o.element, o.value); @@ -1479,6 +1502,225 @@ const Emitter = struct { // ------------------------------------------------------------------ // Resources and stage inputs + fn resourceKind(e: *Emitter, res: Resource) types.ResourceKind { + return e.t.get(e.m.globals.items[res.global].ty).resource.kind; + } + + /// The scalar a texture's ResRet carries for elements of `elem`. + fn texelScalar(e: *Emitter, elem: TypeId) Error!Scalar { + const c = e.compOf(elem); + return switch (c) { + .bool => .uint, + .float, .int, .uint => c, + else => e.unsupported("textures of '{s}' are not supported yet", .{try e.t.format(e.arena, elem)}), + }; + } + + /// Components [0, n) of a ResRet, converted to `ty`'s component type. + fn resRetComponents(e: *Emitter, call: Value, st: DType, via: Scalar, ty: TypeId) Error![]const Value { + const n = try e.flatCount(ty); + const out = try e.arena.alloc(Value, n); + for (out, 0..) |*o, k| { + const v = try e.add(st, .{ .extractvalue = .{ .agg = call, .index = @intCast(k) } }); + o.* = try e.convertScalar(v, via, e.compOf(ty)); + } + return out; + } + + /// `n` values from `src` padded with undef to `width`. + fn padded(e: *Emitter, src: []const Value, n: usize, width: usize, ty: DType) Error![]Value { + const out = try e.arena.alloc(Value, width); + const undef = try e.dm.constant(.{ .ty = ty, .kind = .undef }); + for (out, 0..) |*o, k| o.* = if (k < n and k < src.len) src[k] else undef; + return out; + } + + fn textureLoad(e: *Emitter, res: Resource, mip: Value, coords: []const Value, offset: ?[]const Value, ty: TypeId) Error![]const Value { + const via = try e.texelScalar(res.elem); + const st = try e.scalarTy(via); + const ret_ty = try e.resRetType(st); + const i32t = try e.dm.intType(32); + if (res.class == .uav and try e.flatCount(res.elem) > 1) e.uses_typed_uav_load = true; + const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.textureLoad.{s}", .{e.overloadName(st)}), ret_ty, &.{ i32t, e.handle_ty, i32t, i32t, i32t, i32t, i32t, i32t, i32t }, .nounwind_readonly); + const c = try e.padded(coords, coords.len, 3, i32t); + const o = try e.padded(offset orelse &.{}, if (offset) |x| x.len else 0, 3, i32t); + const call = try e.callOp(fn_i, ret_ty, &.{ try e.i32Const(66), res.handle, mip, c[0], c[1], c[2], o[0], o[1], o[2] }); + return e.resRetComponents(call, st, via, ty); + } + + fn textureStore(e: *Emitter, res: Resource, coords: []const Value, vals: []const Value, vty: TypeId) Error!void { + const via = try e.texelScalar(res.elem); + const st = try e.scalarTy(via); + const i32t = try e.dm.intType(32); + const i8t = try e.dm.intType(8); + const void_ty = try e.voidTy(); + const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.textureStore.{s}", .{e.overloadName(st)}), void_ty, &.{ i32t, e.handle_ty, i32t, i32t, i32t, st, st, st, st, i8t }, .nounwind); + const from = e.compOf(vty); + // Typed stores write all four components (replicated, as dxc). + var v: [4]Value = undefined; + for (&v, 0..) |*x, k| x.* = try e.convertScalar(vals[if (k < vals.len) k else 0], from, via); + const c = try e.padded(coords, coords.len, 3, i32t); + const mask = try e.dm.constant(.{ .ty = i8t, .kind = .{ .int = 15 } }); + _ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(67), res.handle, c[0], c[1], c[2], v[0], v[1], v[2], v[3], mask }); + } + + fn method(e: *Emitter, frame: *Frame, name: []const u8, res_ref: Ref, arg_refs: []const Ref, ty: TypeId) Error!Lowered { + const res = try e.resourceOf(frame, res_ref); + const kind = e.resourceKind(res.*); + const eq = std.mem.eql; + const i32t = try e.dm.intType(32); + const f32t = try e.dm.getType(.float); + const undef_i32 = try e.dm.constant(.{ .ty = i32t, .kind = .undef }); + if (eq(u8, name, "GetDimensions")) return e.getDimensions(frame, res.*, kind, arg_refs); + if (res.kind == 10 and eq(u8, name, "Load")) { + if (arg_refs.len > 1) return e.unsupported("Load with a status argument is not supported yet", .{}); + return e.resourceLoad(frame, res_ref, arg_refs[0], ty); + } + if (res.kind == 12 and eq(u8, name, "Load")) return e.resourceLoad(frame, res_ref, arg_refs[0], ty); + const sh = texture.shape(kind) orelse return e.unsupported("method '{s}' is not supported yet", .{name}); + const call = texture.decode(name, sh, arg_refs.len) orelse return e.unsupported("method '{s}' is not supported yet", .{name}); + if (call.status != null) return e.unsupported("texture methods with a status argument are not supported yet", .{}); + if (call.offsets4) return e.unsupported("Gather with four offsets is not supported yet", .{}); + if (call.op.implicitLod() and e.m.entry.?.stage != .pixel) return e.unsupported("'{s}' outside pixel shaders is not supported yet", .{name}); + const arg = struct { + fn f(em: *Emitter, fr: *Frame, refs: []const Ref, idx: ?u8) Error!?[]const Value { + return if (idx) |k| try em.scalars(fr, refs[k]) else null; + } + }.f; + const coord = (try arg(e, frame, arg_refs, call.coord)).?; + const offset = try arg(e, frame, arg_refs, call.offset); + if (offset) |off| for (off) |x| if (x != .constant) { + return e.unsupported("texel offsets that are not constants (they need loop unrolling) are not supported yet", .{}); + }; + if (call.op == .load) { + const coords = coord[0 .. sh.coords() + @intFromBool(sh.array)]; + const mip = if (call.sample_index) |k| (try e.scalars(frame, arg_refs[k]))[0] else if (sh.hasMips()) coord[coord.len - 1] else undef_i32; + return .{ .scalars = try e.textureLoad(res.*, mip, coords, offset, ty) }; + } + if (call.op == .sample_position) { + const pos_ty = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.SamplePos", .elems = &.{ f32t, f32t } } }); + const fn_i = try e.dxOp("dx.op.texture2DMSGetSamplePosition", pos_ty, &.{ i32t, e.handle_ty, i32t }, .nounwind_readonly); + const pos = try e.callOp(fn_i, pos_ty, &.{ try e.i32Const(75), res.handle, (try e.scalars(frame, arg_refs[0]))[0] }); + const out = try e.arena.alloc(Value, 2); + for (out, 0..) |*o, k| o.* = try e.add(f32t, .{ .extractvalue = .{ .agg = pos, .index = @intCast(k) } }); + return .{ .scalars = out }; + } + const smp = try e.resourceOf(frame, arg_refs[call.sampler.?]); + const ncoord = sh.coords() + @intFromBool(sh.array); + if (call.op == .calc_lod or call.op == .calc_lod_unclamped) { + const i1t = try e.dm.intType(1); + const fn_i = try e.dxOp("dx.op.calculateLOD.f32", f32t, &.{ i32t, e.handle_ty, e.handle_ty, f32t, f32t, f32t, i1t }, .nounwind_readonly); + const c = try e.padded(coord, sh.coords(), 3, f32t); + const clamped = try e.dm.constInt(1, @intFromBool(call.op == .calc_lod)); + return e.list(&.{try e.callOp(fn_i, f32t, &.{ try e.i32Const(81), res.handle, smp.handle, c[0], c[1], c[2], clamped })}); + } + const via = if (call.op.isCmp()) Scalar.float else try e.texelScalar(res.elem); + const st = try e.scalarTy(via); + const ret_ty = try e.resRetType(st); + const c = try e.padded(coord, ncoord, 4, f32t); + // Absent offsets are zero (undef for cubes and unused components). + const zero = try e.i32Const(0); + const n_off: usize = if (call.op == .gather or call.op == .gather_cmp) 2 else 3; + const o = try e.arena.alloc(Value, n_off); + for (o, 0..) |*x, k| x.* = if (k >= sh.offsets()) undef_i32 else if (offset) |off| off[k] else zero; + const undef_f = try e.dm.constant(.{ .ty = f32t, .kind = .undef }); + const scalar1 = struct { + fn f(em: *Emitter, fr: *Frame, refs: []const Ref, idx: ?u8, dflt: Value) Error!Value { + return if (idx) |k| (try em.scalars(fr, refs[k]))[0] else dflt; + } + }.f; + const clamp = try scalar1(e, frame, arg_refs, call.clamp, undef_f); + var args: std.ArrayList(Value) = .empty; + var params: std.ArrayList(DType) = .empty; + const Spec = struct { op: i64, fname: []const u8 }; + const spec: Spec = switch (call.op) { + .sample => .{ .op = 60, .fname = "sample" }, + .sample_bias => .{ .op = 61, .fname = "sampleBias" }, + .sample_level => .{ .op = 62, .fname = "sampleLevel" }, + .sample_grad => .{ .op = 63, .fname = "sampleGrad" }, + .sample_cmp => .{ .op = 64, .fname = "sampleCmp" }, + .sample_cmp_level_zero => .{ .op = 65, .fname = "sampleCmpLevelZero" }, + .sample_cmp_level => .{ .op = 224, .fname = "sampleCmpLevel" }, + .sample_cmp_grad => .{ .op = 254, .fname = "sampleCmpGrad" }, + .sample_cmp_bias => .{ .op = 255, .fname = "sampleCmpBias" }, + .gather => .{ .op = 73, .fname = "textureGather" }, + .gather_cmp => .{ .op = 74, .fname = "textureGatherCmp" }, + else => unreachable, + }; + const min_minor: u8 = switch (call.op) { + .sample_cmp_level => 7, + .sample_cmp_grad, .sample_cmp_bias => 8, + else => 0, + }; + if (e.profile.minor < min_minor) return e.unsupported("'{s}' needs shader model 6.{d}", .{ name, min_minor }); + try args.appendSlice(e.arena, &.{ try e.i32Const(spec.op), res.handle, smp.handle }); + try params.appendSlice(e.arena, &.{ i32t, e.handle_ty, e.handle_ty }); + for (c) |x| { + try args.append(e.arena, x); + try params.append(e.arena, f32t); + } + for (o) |x| { + try args.append(e.arena, x); + try params.append(e.arena, i32t); + } + const pushF = struct { + fn f(em: *Emitter, a: *std.ArrayList(Value), p: *std.ArrayList(DType), v: Value) Error!void { + try a.append(em.arena, v); + try p.append(em.arena, try em.dm.getType(.float)); + } + }.f; + if (call.op == .gather or call.op == .gather_cmp) { + try args.append(e.arena, try e.i32Const(call.channel)); + try params.append(e.arena, i32t); + } + if (call.compare) |k| try pushF(e, &args, ¶ms, (try e.scalars(frame, arg_refs[k]))[0]); + if (call.bias) |k| try pushF(e, &args, ¶ms, (try e.scalars(frame, arg_refs[k]))[0]); + if (call.lod) |k| try pushF(e, &args, ¶ms, (try e.scalars(frame, arg_refs[k]))[0]); + if (call.ddx) |k| { + for (try e.padded(try e.scalars(frame, arg_refs[k]), sh.coords(), 3, f32t)) |x| try pushF(e, &args, ¶ms, x); + for (try e.padded(try e.scalars(frame, arg_refs[call.ddy.?]), sh.coords(), 3, f32t)) |x| try pushF(e, &args, ¶ms, x); + } + switch (call.op) { + .sample, .sample_bias, .sample_grad, .sample_cmp, .sample_cmp_bias, .sample_cmp_grad => try pushF(e, &args, ¶ms, clamp), + else => {}, + } + const fname = try std.fmt.allocPrint(e.arena, "dx.op.{s}.{s}", .{ spec.fname, e.overloadName(st) }); + const fn_i = try e.dxOp(fname, ret_ty, params.items, .nounwind_readonly); + const result = try e.callOp(fn_i, ret_ty, args.items); + return .{ .scalars = try e.resRetComponents(result, st, via, ty) }; + } + + fn getDimensions(e: *Emitter, frame: *Frame, res: Resource, kind: types.ResourceKind, arg_refs: []const Ref) Error!Lowered { + const i32t = try e.dm.intType(32); + const dims_ty = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.Dimensions", .elems = &.{ i32t, i32t, i32t, i32t } } }); + const fn_i = try e.dxOp("dx.op.getDimensions", dims_ty, &.{ i32t, e.handle_ty, i32t }, .nounwind_readonly); + const store = struct { + fn f(em: *Emitter, fr: *Frame, ref: Ref, v: Value) Error!void { + const ptr = switch (fr.vals[ref.index()]) { + .ptr => |p| p, + else => return em.unsupported("internal: out argument is not a pointer", .{}), + }; + const ty = fr.f.inst(ref).ty; + try em.storePtr(ptr, &.{try em.convertScalar(v, .int, em.compOf(ty))}, ty); + } + }.f; + const undef_i32 = try e.dm.constant(.{ .ty = i32t, .kind = .undef }); + if (res.kind == 12 or res.kind == 11 or res.kind == 10) { + const dims = try e.callOp(fn_i, dims_ty, &.{ try e.i32Const(72), res.handle, undef_i32 }); + try store(e, frame, arg_refs[0], try e.add(i32t, .{ .extractvalue = .{ .agg = dims, .index = 0 } })); + if (res.kind == 12 and arg_refs.len > 1) try store(e, frame, arg_refs[1], try e.i32Const(try e.stride(res.elem))); + return .none; + } + const sh = texture.shape(kind) orelse return e.unsupported("GetDimensions on this resource is not supported yet", .{}); + const d = texture.getDimensions(sh, arg_refs.len); + const mip = if (d.mip) |k| (try e.scalars(frame, arg_refs[k]))[0] else try e.i32Const(0); + const dims = try e.callOp(fn_i, dims_ty, &.{ try e.i32Const(72), res.handle, mip }); + for (d.outs[0..d.count]) |o| { + try store(e, frame, arg_refs[o.arg], try e.add(i32t, .{ .extractvalue = .{ .agg = dims, .index = o.comp } })); + } + return .none; + } + fn resourceOf(e: *Emitter, frame: *Frame, r: Ref) Error!*Resource { return switch (frame.vals[r.index()]) { .handle => |h| &e.resources.items[h], @@ -1607,6 +1849,13 @@ const Emitter = struct { fn resourceLoad(e: *Emitter, frame: *Frame, res_ref: Ref, index_ref: Ref, ty: TypeId) Error!Lowered { const res = try e.resourceOf(frame, res_ref); + if (res.kind >= 1 and res.kind <= 9) { + const coords = try e.scalars(frame, index_ref); + const sh = texture.shape(e.resourceKind(res.*)).?; + const i32t = try e.dm.intType(32); + const mip = if (sh.hasMips() or sh.ms) try e.i32Const(0) else try e.dm.constant(.{ .ty = i32t, .kind = .undef }); + return .{ .scalars = try e.textureLoad(res.*, mip, coords, null, ty) }; + } const idx = (try e.scalars(frame, index_ref))[0]; if (res.kind == 12) return .{ .scalars = try e.structuredLoad(res.*, idx, 0, null, false, ty) }; const n = try e.flatCount(ty); @@ -1624,6 +1873,7 @@ const Emitter = struct { const chunk = @min(4, n - done); var call: Value = undefined; if (res.kind == 10) { + if (res.class == .uav and try e.flatCount(res.elem) > 1) e.uses_typed_uav_load = true; const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.bufferLoad.{s}", .{e.overloadName(st)}), ret_ty, &.{ i32t, e.handle_ty, i32t, i32t }, .nounwind_readonly); call = try e.callOp(fn_i, ret_ty, &.{ try e.i32Const(68), res.handle, idx, undef_i32 }); } else { @@ -1651,6 +1901,7 @@ const Emitter = struct { fn resourceStore(e: *Emitter, frame: *Frame, res_ref: Ref, index_ref: Ref, value_ref: Ref) Error!void { const res = try e.resourceOf(frame, res_ref); + if (res.kind >= 1 and res.kind <= 9) return e.textureStore(res.*, try e.scalars(frame, index_ref), try e.scalars(frame, value_ref), frame.f.inst(value_ref).ty); const idx = (try e.scalars(frame, index_ref))[0]; const vals = try e.scalars(frame, value_ref); if (res.kind == 12) return e.structuredStore(res.*, idx, 0, null, false, frame.f.inst(value_ref).ty, vals); @@ -1974,6 +2225,7 @@ const Emitter = struct { if (r.class == .uav) uavs += 1; } if (uavs > 8) flags |= 1 << 15; + 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; const stage = e.m.entry.?.stage; @@ -1999,7 +2251,7 @@ const Emitter = struct { const map = [_][2]u64{ .{ 1 << 2, 0x1 }, .{ 1 << 16, 0x4 }, .{ 1 << 15, 0x8 }, .{ 1 << 5, 0x10 }, .{ 1 << 11, 0x200 }, .{ 1 << 10, 0x400 }, .{ 1 << 9, 0x2000 }, .{ 1 << 20, 0x8000 }, - .{ 1 << 21, 0x10000 }, .{ 1 << 24, 0x80000 }, + .{ 1 << 21, 0x10000 }, .{ 1 << 24, 0x80000 }, .{ 1 << 13, 0x800 }, }; var f: u64 = 0; for (map) |m| if (flags & m[0] != 0) { @@ -2041,11 +2293,22 @@ const Emitter = struct { try lists[2].append(e.arena, try dm.mdNode(&.{ try mdI32(dm, r.id), try dm.mdValue(try dm.ptrType(cb_ty), undef_cb), try dm.mdString(""), try mdI32(dm, b.space), try mdI32(dm, b.index), try mdI32(dm, 1), try mdI32(dm, try e.cbufferSize(r)), null })); continue; } + if (r.class == .sampler) { + const name = if (r.comparison) "struct.SamplerComparisonState" else "struct.SamplerState"; + const st = try dm.getType(.{ .@"struct" = .{ .name = name, .elems = &.{try dm.intType(32)} } }); + const undef_s = try dm.constant(.{ .ty = try dm.ptrType(st), .kind = .undef }); + const b = g.binding; + try lists[3].append(e.arena, try dm.mdNode(&.{ try mdI32(dm, r.id), try dm.mdValue(try dm.ptrType(st), undef_s), try dm.mdString(""), try mdI32(dm, b.space), try mdI32(dm, b.index), try mdI32(dm, 1), try mdI32(dm, @intFromBool(r.comparison)), null })); + continue; + } const rt = e.t.get(g.ty).resource; const class_name = try std.fmt.allocPrint(e.arena, "class.{s}<{s}>", .{ rt.name, try e.t.format(e.arena, r.elem) }); // The class type only names the resource; aggregates get a // placeholder element. - const elem_dt = try e.scalarTy(if (r.kind == 11) .uint else if (e.t.shape(r.elem) == null) .int else e.compOf(r.elem)); + var elem_dt = try e.scalarTy(if (r.kind == 11) .uint else if (e.t.shape(r.elem) == null) .int else e.compOf(r.elem)); + // Typed resources carry their component count in the element + // (the validator reads it from here). + if (r.kind >= 1 and r.kind <= 10 and e.t.get(r.elem) == .vector) elem_dt = try dm.getType(.{ .vector = .{ .len = e.t.get(r.elem).vector.len, .elem = elem_dt } }); const class_ty = try dm.getType(.{ .@"struct" = .{ .name = class_name, .elems = &.{elem_dt} } }); const undef_ptr = try dm.constant(.{ .ty = try dm.ptrType(class_ty), .kind = .undef }); const b = g.binding; @@ -2056,7 +2319,7 @@ const Emitter = struct { } 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)) }), - 10 => try dm.mdNode(&.{ try mdI32(dm, 0), try mdI32(dm, try e.compType(e.compOf(r.elem))) }), + 1...10 => try dm.mdNode(&.{ try mdI32(dm, 0), try mdI32(dm, try e.compType(e.compOf(r.elem))) }), else => null, }; try fields.append(e.arena, extra); diff --git a/src/ir/lower.zig b/src/ir/lower.zig index 5188347..55ef327 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -742,7 +742,7 @@ const Lowerer = struct { switch (bt) { .scalar, .vector => { const v = try l.rvalue(base); - const comps = swizzleComponents(name) orelse return l.fail(e, "this swizzle"); + const comps = (try swizzleComponents(l.arena, name)) orelse return l.fail(e, "this swizzle"); const ty = try l.concrete(e.ty); if (bt == .scalar) { if (comps.len == 1) return v; @@ -821,14 +821,28 @@ const Lowerer = struct { switch (r) { .intrinsic => |it| { const name = table.intrinsics[it.index].name; + const spec = table.intrinsics[it.index]; if (it.object) |_| { const obj = callee.kind.member.base; const res = try l.rvalue(obj); + // Out parameters (GetDimensions, ...) are passed as + // pointers to temporaries, copied back afterwards. const vals = try l.arena.alloc(Ref, args.len); - for (args, 0..) |a, i| vals[i] = try l.converted(a, try l.concrete(it.params[i])); - return l.b.add(.{ .op = .{ .method = .{ .name = name, .res = res, .args = vals } }, .ty = ret_ty }); + var any_out = false; + for (args, 0..) |a, i| { + const pt = try l.concrete(it.params[i]); + if (i < spec.params.len and spec.params[i].qual != .in) { + vals[i] = try l.b.add(.{ .op = .local_var, .ty = pt, .ptr = .function }); + any_out = true; + } else vals[i] = try l.converted(a, pt); + } + const result = try l.b.add(.{ .op = .{ .method = .{ .name = name, .res = res, .args = vals } }, .ty = ret_ty }); + if (any_out) for (args, 0..) |a, i| { + if (i >= spec.params.len or spec.params[i].qual == .in) continue; + try l.storeTo(a, try l.convert(try l.b.load(vals[i]), a.ty)); + }; + return result; } - const spec = table.intrinsics[it.index]; const vals = try l.arena.alloc(Ref, args.len); for (args, 0..) |a, i| { if (i < spec.params.len and spec.params[i].qual != .in) { @@ -912,7 +926,7 @@ const Lowerer = struct { return l.storeTo(m.base, whole); } else if (t.get(m.base.ty) == .vector or t.get(m.base.ty) == .scalar) { // Swizzle store: read, replace the named components, write. - const comps = swizzleComponents(m.name) orelse return error.Unsupported; + const comps = (try swizzleComponents(l.arena, m.name)) orelse return error.Unsupported; if (t.get(m.base.ty) == .scalar) return l.storeTo(m.base, value); var whole = try l.rvalue(m.base); const ec = try t.scalar(t.component(m.base.ty).?); @@ -1154,16 +1168,11 @@ fn parseBinding(values: []const []const u8) ir.Binding { } /// `xyzw` / `rgba` swizzle -> component indices. -fn swizzleComponents(name: []const u8) ?[]const u8 { +fn swizzleComponents(a: Allocator, name: []const u8) Allocator.Error!?[]const u8 { if (name.len == 0 or name.len > 4) return null; - const static = struct { - var buf: [16][4]u8 = undefined; - var next: usize = 0; - }; - const out = &static.buf[static.next % 16]; - static.next += 1; - for (name, 0..) |c, i| { - out[i] = switch (c) { + const out = try a.alloc(u8, name.len); + for (name, out) |c, *o| { + o.* = switch (c) { 'x', 'r' => 0, 'y', 'g' => 1, 'z', 'b' => 2, @@ -1171,7 +1180,7 @@ fn swizzleComponents(name: []const u8) ?[]const u8 { else => return null, }; } - return out[0..name.len]; + return out; } /// `_m01_m10` (zero-based) or `_12_21` (one-based) -> row-major component diff --git a/src/ir/texture.zig b/src/ir/texture.zig new file mode 100644 index 0000000..0c022e2 --- /dev/null +++ b/src/ir/texture.zig @@ -0,0 +1,258 @@ +//! Texture and typed-buffer methods, decoded for the backends: which +//! argument plays which role (sampler, coordinate, offset, LOD, ...) in +//! each overload from dxc's intrinsic table. + +const std = @import("std"); +const types = @import("../sema/types.zig"); + +pub const Kind = types.ResourceKind; + +pub const Dim = enum { d1, d2, d3, cube, buffer }; + +pub const Shape = struct { + dim: Dim, + array: bool = false, + ms: bool = false, + rw: bool = false, + + /// Coordinate components, without the array index. + pub fn coords(s: Shape) u8 { + return switch (s.dim) { + .d1, .buffer => 1, + .d2 => 2, + .d3, .cube => 3, + }; + } + + /// Components of a texel offset (none for cubes and buffers). + pub fn offsets(s: Shape) u8 { + return switch (s.dim) { + .d1 => 1, + .d2 => 2, + .d3 => 3, + .cube, .buffer => 0, + }; + } + + /// Whether the resource has mip levels (Load takes one, GetDimensions + /// reports them). + pub fn hasMips(s: Shape) bool { + return !s.rw and !s.ms and s.dim != .buffer; + } +}; + +pub fn shape(kind: Kind) ?Shape { + return switch (kind) { + .buffer => .{ .dim = .buffer }, + .rw_buffer => .{ .dim = .buffer, .rw = true }, + .texture1d => .{ .dim = .d1 }, + .texture1d_array => .{ .dim = .d1, .array = true }, + .texture2d => .{ .dim = .d2 }, + .texture2d_array => .{ .dim = .d2, .array = true }, + .texture2dms => .{ .dim = .d2, .ms = true }, + .texture2dms_array => .{ .dim = .d2, .array = true, .ms = true }, + .texture3d => .{ .dim = .d3 }, + .texture_cube => .{ .dim = .cube }, + .texture_cube_array => .{ .dim = .cube, .array = true }, + .rw_texture1d => .{ .dim = .d1, .rw = true }, + .rw_texture1d_array => .{ .dim = .d1, .array = true, .rw = true }, + .rw_texture2d => .{ .dim = .d2, .rw = true }, + .rw_texture2d_array => .{ .dim = .d2, .array = true, .rw = true }, + .rw_texture2dms => .{ .dim = .d2, .ms = true, .rw = true }, + .rw_texture2dms_array => .{ .dim = .d2, .array = true, .ms = true, .rw = true }, + .rw_texture3d => .{ .dim = .d3, .rw = true }, + else => null, + }; +} + +pub const Op = enum { + sample, + sample_bias, + sample_level, + sample_grad, + sample_cmp, + sample_cmp_level_zero, + sample_cmp_level, + sample_cmp_bias, + sample_cmp_grad, + gather, + gather_cmp, + load, + calc_lod, + calc_lod_unclamped, + sample_position, + + pub fn isCmp(op: Op) bool { + return switch (op) { + .sample_cmp, .sample_cmp_level_zero, .sample_cmp_level, .sample_cmp_bias, .sample_cmp_grad, .gather_cmp => true, + else => false, + }; + } + + /// Needs implicit derivatives (pixel shaders only, for zdxc). + pub fn implicitLod(op: Op) bool { + return switch (op) { + .sample, .sample_bias, .sample_cmp, .sample_cmp_bias, .calc_lod, .calc_lod_unclamped => true, + else => false, + }; + } +}; + +/// Argument positions of one method call (null: absent). +pub const Call = struct { + op: Op, + sampler: ?u8 = null, + coord: u8 = 0, + compare: ?u8 = null, + bias: ?u8 = null, + lod: ?u8 = null, + ddx: ?u8 = null, + ddy: ?u8 = null, + /// One offset, or the first of four (Gather with per-texel offsets). + offset: ?u8 = null, + offsets4: bool = false, + clamp: ?u8 = null, + status: ?u8 = null, + sample_index: ?u8 = null, + /// Gather channel: 0 red ... 3 alpha. + channel: u2 = 0, +}; + +const Sampled = struct { name: []const u8, op: Op, extra: []const Role, has_clamp: bool }; +const Role = enum { compare, bias, lod, ddx, ddy }; + +const sampled = [_]Sampled{ + .{ .name = "Sample", .op = .sample, .extra = &.{}, .has_clamp = true }, + .{ .name = "SampleBias", .op = .sample_bias, .extra = &.{.bias}, .has_clamp = true }, + .{ .name = "SampleLevel", .op = .sample_level, .extra = &.{.lod}, .has_clamp = false }, + .{ .name = "SampleGrad", .op = .sample_grad, .extra = &.{ .ddx, .ddy }, .has_clamp = true }, + .{ .name = "SampleCmp", .op = .sample_cmp, .extra = &.{.compare}, .has_clamp = true }, + .{ .name = "SampleCmpLevelZero", .op = .sample_cmp_level_zero, .extra = &.{.compare}, .has_clamp = false }, + .{ .name = "SampleCmpLevel", .op = .sample_cmp_level, .extra = &.{ .compare, .lod }, .has_clamp = false }, + .{ .name = "SampleCmpBias", .op = .sample_cmp_bias, .extra = &.{ .compare, .bias }, .has_clamp = true }, + .{ .name = "SampleCmpGrad", .op = .sample_cmp_grad, .extra = &.{ .compare, .ddx, .ddy }, .has_clamp = true }, +}; + +/// Decodes `name(args...)` on a resource of shape `s`; null for methods +/// that are not texture operations (GetDimensions is handled apart). +pub fn decode(name: []const u8, s: Shape, nargs: usize) ?Call { + const eq = std.mem.eql; + const n: u8 = @intCast(nargs); + for (sampled) |sm| if (eq(u8, name, sm.name)) { + var c: Call = .{ .op = sm.op, .sampler = 0, .coord = 1 }; + var i: u8 = 2; + for (sm.extra) |r| { + switch (r) { + .compare => c.compare = i, + .bias => c.bias = i, + .lod => c.lod = i, + .ddx => c.ddx = i, + .ddy => c.ddy = i, + } + i += 1; + } + if (i < n and s.offsets() > 0) { + c.offset = i; + i += 1; + } + if (sm.has_clamp and i < n and n - i >= 1) { + // Clamp comes before status; an overload with status has both. + c.clamp = i; + i += 1; + } + if (i < n) c.status = i; + return c; + }; + if (std.mem.startsWith(u8, name, "Gather")) { + var rest = name["Gather".len..]; + var c: Call = .{ .op = .gather, .sampler = 0, .coord = 1 }; + if (std.mem.startsWith(u8, rest, "Cmp")) { + c.op = .gather_cmp; + c.compare = 2; + rest = rest[3..]; + } + if (eq(u8, rest, "Raw")) return null; + c.channel = if (rest.len == 0 or eq(u8, rest, "Red")) 0 else if (eq(u8, rest, "Green")) 1 else if (eq(u8, rest, "Blue")) 2 else if (eq(u8, rest, "Alpha")) 3 else return null; + const first: u8 = if (c.compare != null) 3 else 2; + const left = n - first; + if (left == 1 or left == 2) c.offset = first; + if (left == 4 or left == 5) { + c.offset = first; + c.offsets4 = true; + } + if (left == 2 or left == 5) c.status = n - 1; + return c; + } + if (eq(u8, name, "Load")) { + var c: Call = .{ .op = .load, .coord = 0 }; + var i: u8 = 1; + if (s.ms) { + c.sample_index = 1; + i = 2; + } + if (i < n and s.offsets() > 0 and !s.rw) { + c.offset = i; + i += 1; + } + if (i < n) c.status = i; + return c; + } + if (eq(u8, name, "CalculateLevelOfDetail")) return .{ .op = .calc_lod, .sampler = 0, .coord = 1 }; + if (eq(u8, name, "CalculateLevelOfDetailUnclamped")) return .{ .op = .calc_lod_unclamped, .sampler = 0, .coord = 1 }; + if (eq(u8, name, "GetSamplePosition")) return .{ .op = .sample_position, .sample_index = 0 }; + return null; +} + +/// GetDimensions(...) out parameters, in order, as the components of dxc's +/// `Dimensions` result they receive (0..2: sizes, 3: levels or samples). +pub const Dims = struct { + /// Index of the mip-level argument, if given. + mip: ?u8 = null, + /// (argument index, result component) pairs. + outs: [4]struct { arg: u8, comp: u8 } = undefined, + count: u8 = 0, +}; + +pub fn getDimensions(s: Shape, nargs: usize) Dims { + var d: Dims = .{}; + var first: u8 = 0; + if (s.hasMips() and nargs == @as(usize, s.coords() - @intFromBool(s.dim == .cube)) + @intFromBool(s.array) + 2) { + d.mip = 0; + first = 1; + } + const n: u8 = @intCast(nargs); + var comp: u8 = 0; + var i = first; + while (i < n) : (i += 1) { + // The last of several is levels / samples (component 3), as in + // dxc's TranslateGetDimensions. + const last_special = (d.mip != null or s.ms or s.hasMips()) and i == n - 1 and i > first; + const want_levels = d.mip != null or s.ms; + const c: u8 = if (last_special and want_levels) 3 else comp; + d.outs[d.count] = .{ .arg = i, .comp = c }; + d.count += 1; + comp += 1; + } + return d; +} + +test "decode texture methods" { + const t2: Shape = .{ .dim = .d2 }; + const c = decode("SampleGrad", t2, 6).?; + try std.testing.expectEqual(@as(?u8, 2), c.ddx); + try std.testing.expectEqual(@as(?u8, 4), c.offset); + try std.testing.expectEqual(@as(?u8, 5), c.clamp); + const g = decode("GatherCmpGreen", t2, 7).?; + try std.testing.expect(g.offsets4); + try std.testing.expectEqual(@as(u2, 1), g.channel); + const l = decode("Load", .{ .dim = .d2, .ms = true }, 3).?; + try std.testing.expectEqual(@as(?u8, 1), l.sample_index); + try std.testing.expectEqual(@as(?u8, 2), l.offset); + // GetDimensions(mip, w, h, levels) on Texture2D. + const d = getDimensions(t2, 4); + try std.testing.expectEqual(@as(?u8, 0), d.mip); + try std.testing.expectEqual(@as(u8, 3), d.outs[2].comp); + // GetDimensions(w, h) without a mip level. + const d2 = getDimensions(t2, 2); + try std.testing.expectEqual(@as(u8, 1), d2.outs[1].comp); +} diff --git a/src/root.zig b/src/root.zig index 5fe6141..088a943 100644 --- a/src/root.zig +++ b/src/root.zig @@ -29,6 +29,7 @@ pub const ir = struct { pub const ir = @import("ir/ir.zig"); pub const lower = @import("ir/lower.zig"); pub const layout = @import("ir/layout.zig"); + pub const texture = @import("ir/texture.zig"); }; pub const sema = struct { @@ -48,6 +49,7 @@ test { const std = @import("std"); std.testing.refAllDecls(front); std.testing.refAllDecls(dxil); + std.testing.refAllDecls(ir); _ = @import("sema/types.zig"); _ = @import("sema/sema.zig"); std.testing.refAllDecls(spirv); diff --git a/src/spirv/builder.zig b/src/spirv/builder.zig index 0a81943..2d36517 100644 --- a/src/spirv/builder.zig +++ b/src/spirv/builder.zig @@ -55,15 +55,22 @@ pub const Op = enum(u16) { composite_extract = 81, composite_insert = 82, transpose = 84, + array_length = 68, sampled_image = 86, image_sample_implicit_lod = 87, image_sample_explicit_lod = 88, + image_sample_dref_implicit_lod = 89, + image_sample_dref_explicit_lod = 90, image_fetch = 95, + image_gather = 96, + image_dref_gather = 97, image_read = 98, image_write = 99, image_query_size_lod = 103, image_query_size = 104, + image_query_lod = 105, image_query_levels = 106, + image_query_samples = 107, convert_f_to_u = 109, convert_f_to_s = 110, convert_s_to_f = 111, diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index 32a556d..d95dd4e 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -7,6 +7,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const ir = @import("../ir/ir.zig"); const types = @import("../sema/types.zig"); +const texture = @import("../ir/texture.zig"); const builder = @import("builder.zig"); const diag = @import("../diag.zig"); const layout = @import("../ir/layout.zig"); @@ -24,7 +25,27 @@ pub const Error = Allocator.Error || error{Unsupported}; /// SPIR-V storage classes. const StorageClass = enum(u32) { uniform_constant = 0, input = 1, uniform = 2, output = 3, workgroup = 4, private = 6, function = 7, storage_buffer = 12 }; -const Capability = enum(u32) { shader = 1, float16 = 9, float64 = 10, int64 = 11, int16 = 22, sampled_buffer = 46, image_buffer = 47, storage_image_extended_formats = 49, image_query = 50 }; +const Capability = enum(u32) { + shader = 1, + float16 = 9, + float64 = 10, + int64 = 11, + int16 = 22, + image_gather_extended = 25, + storage_image_multisample = 27, + sample_rate_shading = 35, + min_lod = 42, + sampled1d = 43, + image1d = 44, + sampled_cube_array = 45, + sampled_buffer = 46, + image_buffer = 47, + image_ms_array = 48, + storage_image_extended_formats = 49, + image_query = 50, + storage_image_read_without_format = 55, + storage_image_write_without_format = 56, +}; pub fn emit(gpa: Allocator, m: *const ir.Module, diags: *diag.Diagnostics) Error![]u8 { var arena_state = std.heap.ArenaAllocator.init(gpa); @@ -60,6 +81,12 @@ const Emitter = struct { /// type. global_vars: []Id = &.{}, buffer_elem_ptr: []Id = &.{}, + /// Per global: its image type (textures, typed buffers) or 0. + global_images: []Id = &.{}, + /// 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, + sampler_type: Id = 0, /// Entry inputs / outputs: interface variable and its value type. inputs: []Interface = &.{}, outputs: []Interface = &.{}, @@ -439,6 +466,8 @@ const Emitter = struct { const m = e.m; e.global_vars = try e.arena.alloc(Id, m.globals.items.len); e.buffer_elem_ptr = try e.arena.alloc(Id, m.globals.items.len); + e.global_images = try e.arena.alloc(Id, m.globals.items.len); + @memset(e.global_images, 0); @memset(e.buffer_elem_ptr, 0); // Registers without an explicit binding take the next free one. var used: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty; @@ -447,7 +476,7 @@ const Emitter = struct { for (m.globals.items, 0..) |g, gi| { switch (g.space) { .resource => { - const r = switch (e.t.get(g.ty)) { + const r = if (e.t.get(g.ty) == .sampler) @FieldType(types.Type, "resource"){ .kind = .other, .elem = g.ty, .name = "SamplerState" } else switch (e.t.get(g.ty)) { .resource => |r| r, else => return e.unsupported("global '{s}' of type '{s}' is not supported yet", .{ g.name, try e.t.format(e.arena, g.ty) }), }; @@ -471,7 +500,15 @@ const Emitter = struct { try e.b.emit(.types_globals, .variable, &.{ ptr, var_id, @backingInt(StorageClass.uniform) }); e.buffer_elem_ptr[gi] = try e.pointerType(.uniform, elem); }, - else => return e.unsupported("resource type '{s}' is not supported yet", .{r.name}), + else => if (e.t.get(g.ty) == .sampler) { + const ptr = try e.pointerType(.uniform_constant, try e.samplerType()); + try e.b.emit(.types_globals, .variable, &.{ ptr, var_id, @backingInt(StorageClass.uniform_constant) }); + } else if (texture.shape(r.kind)) |sh| { + const img = try e.imageType(sh, r.elem); + e.global_images[gi] = img; + const ptr = try e.pointerType(.uniform_constant, img); + try e.b.emit(.types_globals, .variable, &.{ ptr, var_id, @backingInt(StorageClass.uniform_constant) }); + } else return e.unsupported("resource type '{s}' is not supported yet", .{r.name}), } var binding = g.binding.index; if (!g.binding.explicit) { @@ -581,9 +618,22 @@ const Emitter = struct { const loc = if (std.ascii.eqlIgnoreCase(el.semantic, "SV_Target")) el.semantic_index else location[dir]; try e.b.emit(.annotations, .decorate, &.{ var_id, 30, loc }); // Location location[dir] = @max(location[dir], loc) + try e.locationCount(ty); - // Integer fragment inputs cannot be interpolated. - if (input and entry.stage == .pixel and !e.t.component(ty).?.isFloat()) { - try e.b.emit(.annotations, .decorate, &.{ var_id, 14 }); // Flat + // Interpolation (as dxc: pixel inputs and vertex + // outputs; integers are always flat). + if ((input and entry.stage == .pixel) or (!input and entry.stage == .vertex)) { + var et = ty; + while (e.t.get(et) == .array) et = e.t.get(et).array.elem; + if (!e.t.component(et).?.isFloat()) { + try e.b.emit(.annotations, .decorate, &.{ var_id, 14 }); // Flat + } else { + if (el.interp.centroid) try e.b.emit(.annotations, .decorate, &.{ var_id, 16 }); // Centroid + if (el.interp.nointerpolation) try e.b.emit(.annotations, .decorate, &.{ var_id, 14 }); // Flat + if (el.interp.noperspective) try e.b.emit(.annotations, .decorate, &.{ var_id, 13 }); // NoPerspective + if (el.interp.sample) { + try e.cap(.sample_rate_shading); + try e.b.emit(.annotations, .decorate, &.{ var_id, 17 }); // Sample + } + } } } const name = try std.fmt.allocPrint(e.arena, "{s}.var.{s}{d}", .{ if (input) "in" else "out", el.semantic, el.semantic_index }); @@ -1045,16 +1095,24 @@ const Emitter = struct { }, .intrinsic => |c| e.vals[ri] = try e.intrinsic(c.name, i.ty, c.args), .res_load => |x| { + if (e.imageGlobal(x.res)) |g| { + e.vals[ri] = try e.imageIndexLoad(g, e.val(x.index), i.ty); + return; + } const ptr = try e.bufferElement(x.res, x.index); const raw = try e.opRaw(.load, try e.layoutTypeId(i.ty, .std430, false), &.{ptr}); e.vals[ri] = try e.fromLayout(raw, i.ty, .std430, false); }, .res_store => |x| { + if (e.imageGlobal(x.res)) |g| { + try e.imageWrite(g, e.val(x.index), e.val(x.value)); + return; + } const ptr = try e.bufferElement(x.res, x.index); const v = try e.toLayout(e.val(x.value), f.inst(x.value).ty, .std430, false); try e.b.emit(.functions, .store, &.{ ptr, v }); }, - .method => |x| return e.unsupported("method '{s}' is not supported yet", .{x.name}), + .method => |x| e.vals[ri] = try e.method(x.name, x.res, x.args, i.ty), .input => |k| { const iface = e.inputs[k]; const loaded = try e.op1(.load, iface.ty, &.{iface.var_id}); @@ -1089,6 +1147,330 @@ const Emitter = struct { return id; } + // ------------------------------------------------------------------ + // Images and samplers + + fn samplerType(e: *Emitter) Error!Id { + if (e.sampler_type == 0) { + e.sampler_type = e.b.newId(); + try e.b.emit(.types_globals, .type_sampler, &.{e.sampler_type}); + } + return e.sampler_type; + } + + fn sampledImageType(e: *Emitter, img: Id) Error!Id { + if (e.sampled_image_types.get(img)) |id| return id; + const id = e.b.newId(); + try e.b.emit(.types_globals, .type_sampled_image, &.{ id, img }); + try e.sampled_image_types.put(e.arena, img, id); + return id; + } + + /// The scalar an image of `elem` texels samples to (bool as uint). + fn texelScalar(e: *Emitter, elem: TypeId) Error!Scalar { + const c = storageScalar(e.t.component(elem) orelse return e.unsupported("textures of '{s}' are not supported yet", .{try e.t.format(e.arena, elem)})); + return switch (c) { + .float, .int, .uint => c, + else => e.unsupported("textures of '{s}' are not supported yet", .{try e.t.format(e.arena, elem)}), + }; + } + + /// dxc's image format for typed buffers and RW textures. + fn imageFormat(e: *Emitter, elem: TypeId) u32 { + const n = e.t.componentCount(elem) orelse return 0; + const c = e.t.component(elem) orelse return 0; + const k: usize = switch (n) { + 1 => 0, + 2 => 1, + 4 => 2, + else => return 0, + }; + const table: [3]u32 = switch (c) { + .float => .{ 3, 6, 1 }, // R32f, Rg32f, Rgba32f + .half, .min16float, .min10float => .{ 9, 7, 2 }, // R16f, Rg16f, Rgba16f + .int => .{ 24, 25, 21 }, // R32i, Rg32i, Rgba32i + .min16int, .min12int => .{ 28, 26, 22 }, // R16i, Rg16i, Rgba16i + .uint => .{ 33, 35, 30 }, // R32ui, Rg32ui, Rgba32ui + .min16uint => .{ 38, 36, 31 }, // R16ui, Rg16ui, Rgba16ui + else => return 0, + }; + return table[k]; + } + + fn imageType(e: *Emitter, sh: texture.Shape, elem: TypeId) Error!Id { + const st = try e.scalarType(try e.texelScalar(elem)); + const dim: u32 = switch (sh.dim) { + .d1 => 0, + .d2 => 1, + .d3 => 2, + .cube => 3, + .buffer => 5, + }; + 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 key: [6]u32 = .{ st, dim, @intFromBool(sh.array), @intFromBool(sh.ms), sampled, format }; + if (e.image_types.get(key)) |id| return id; + switch (sh.dim) { + .d1 => try e.cap(if (sh.rw) .image1d else .sampled1d), + .buffer => try e.cap(if (sh.rw) .image_buffer else .sampled_buffer), + .cube => if (sh.array) try e.cap(.sampled_cube_array), + else => {}, + } + if (sh.rw and sh.ms) try e.cap(if (sh.array) .image_ms_array else .storage_image_multisample); + switch (format) { + 6, 7, 9, 25, 26, 28, 35, 36, 38 => try e.cap(.storage_image_extended_formats), + else => {}, + } + const id = e.b.newId(); + try e.b.emit(.types_globals, .type_image, &.{ id, st, dim, 2, key[2], key[3], sampled, format }); + try e.image_types.put(e.arena, key, id); + return id; + } + + /// The global behind an image value, if it is one. + fn imageGlobal(e: *Emitter, r: Ref) ?u32 { + const g = e.globalOf(r) orelse return null; + return if (e.global_images[g] != 0) g else null; + } + + fn loadImage(e: *Emitter, g: u32) Error!Id { + return e.opRaw(.load, e.global_images[g], &.{e.global_vars[g]}); + } + + fn resourceInfo(e: *Emitter, g: u32) @FieldType(types.Type, "resource") { + return e.t.get(e.m.globals.items[g].ty).resource; + } + + /// The first components of a four-component texel, as `ty`. + fn texelResult(e: *Emitter, v4: Id, s: Scalar, ty: TypeId) Error!Id { + const n = e.t.componentCount(ty) orelse return e.unsupported("texel type '{s}'", .{try e.t.format(e.arena, ty)}); + if (storageScalar(e.t.component(ty).?) != s) return e.unsupported("texel type '{s}'", .{try e.t.format(e.arena, ty)}); + if (n == 4) return v4; + if (n == 1) return e.op1(.composite_extract, ty, &.{ v4, 0 }); + var ops: std.ArrayList(u32) = .empty; + try ops.appendSlice(e.arena, &.{ v4, v4 }); + for (0..n) |k| try ops.append(e.arena, @intCast(k)); + return e.op1(.vector_shuffle, ty, ops.items); + } + + fn vec4Of(e: *Emitter, s: Scalar) Error!Id { + return e.typeId(try e.t.vector(s, 4)); + } + + /// `res[index]` on a texture or typed buffer. + fn imageIndexLoad(e: *Emitter, g: u32, coord: Id, ty: TypeId) Error!Id { + const r = e.resourceInfo(g); + const sh = texture.shape(r.kind).?; + const s = try e.texelScalar(r.elem); + const img = try e.loadImage(g); + var v: Id = undefined; + if (sh.rw) { + if (e.imageFormat(r.elem) == 0) try e.cap(.storage_image_read_without_format); + v = if (sh.ms) + try e.opRaw(.image_read, try e.vec4Of(s), &.{ img, coord, 0x40, try e.constInt(0) }) + else + try e.opRaw(.image_read, try e.vec4Of(s), &.{ img, coord }); + } else if (sh.dim == .buffer) { + v = try e.opRaw(.image_fetch, try e.vec4Of(s), &.{ img, coord }); + } else { + const operand: u32 = if (sh.ms) 0x40 else 0x2; // Sample 0 / Lod 0 + v = try e.opRaw(.image_fetch, try e.vec4Of(s), &.{ img, coord, operand, try e.constUint(0) }); + } + return e.texelResult(v, s, ty); + } + + fn imageWrite(e: *Emitter, g: u32, coord: Id, value: Id) Error!void { + const r = e.resourceInfo(g); + _ = try e.texelScalar(r.elem); + if (e.imageFormat(r.elem) == 0) try e.cap(.storage_image_write_without_format); + const img = try e.loadImage(g); + try e.b.emit(.functions, .image_write, &.{ img, coord, value }); + } + + /// The constant id of an IR value built only from constants, or null. + fn constValue(e: *Emitter, r: Ref) Error!?Id { + const i = e.f.inst(r); + switch (i.op) { + .constant => return e.val(r), + .construct => |xs| { + if (e.t.get(i.ty) != .vector) return null; + var ops: std.ArrayList(u32) = .empty; + const id = e.b.newId(); + try ops.appendSlice(e.arena, &.{ try e.typeId(i.ty), id }); + for (xs) |x| try ops.append(e.arena, (try e.constValue(x)) orelse return null); + try e.b.emit(.types_globals, .constant_composite, ops.items); + return id; + }, + else => return null, + } + } + + fn method(e: *Emitter, name: []const u8, res: Ref, args: []const Ref, ty: TypeId) Error!Id { + const eq = std.mem.eql; + const g = e.globalOf(res) orelse return e.unsupported("resources not tied to a global are not supported yet", .{}); + const gty = e.m.globals.items[g].ty; + if (e.t.get(gty) != .resource) return e.unsupported("method '{s}' is not supported yet", .{name}); + const r = e.resourceInfo(g); + if (eq(u8, name, "GetDimensions")) { + try e.getDimensions(g, r, args); + return 0; + } + if (eq(u8, name, "Load") and (r.kind == .structured_buffer or r.kind == .rw_structured_buffer)) { + const ptr = try e.bufferElement(res, args[0]); + const raw = try e.opRaw(.load, try e.layoutTypeId(ty, .std430, false), &.{ptr}); + return e.fromLayout(raw, ty, .std430, false); + } + const sh = texture.shape(r.kind) orelse return e.unsupported("method '{s}' is not supported yet", .{name}); + const call = texture.decode(name, sh, args.len) orelse return e.unsupported("method '{s}' is not supported yet", .{name}); + if (call.status != null) return e.unsupported("texture methods with a status argument are not supported yet", .{}); + if (call.offsets4) return e.unsupported("Gather with four offsets is not supported yet", .{}); + if (call.op.implicitLod() and e.m.entry.?.stage != .pixel) return e.unsupported("'{s}' outside pixel shaders is not supported yet", .{name}); + const s = try e.texelScalar(r.elem); + const img = try e.loadImage(g); + const coord = e.val(args[call.coord]); + // Image operands, in operand-mask bit order. + var mask: u32 = 0; + var extra: std.ArrayList(u32) = .empty; + if (call.bias) |k| { + mask |= 0x1; + try extra.append(e.arena, e.val(args[k])); + } + if (call.lod) |k| { + mask |= 0x2; + try extra.append(e.arena, e.val(args[k])); + } else if (call.op == .sample_cmp_level_zero) { + mask |= 0x2; + try extra.append(e.arena, try e.constant(try e.t.scalar(.float), .{ .float = 0 })); + } + if (call.ddx) |k| { + mask |= 0x4; + try extra.appendSlice(e.arena, &.{ e.val(args[k]), e.val(args[call.ddy.?]) }); + } + var lod_from_coord: ?Id = null; + var coord_id = coord; + if (call.op == .load and !sh.rw and !sh.ms and sh.dim != .buffer) { + // Load(int3 x): the last component is the mip level. + const n = sh.coords() + @intFromBool(sh.array); + const ct = try e.t.vector(.int, @intCast(n + 1)); + _ = ct; + const it = try e.t.scalar(.int); + lod_from_coord = try e.op1(.composite_extract, it, &.{ coord, n }); + if (n == 1) { + coord_id = try e.op1(.composite_extract, it, &.{ coord, 0 }); + } else { + var ops: std.ArrayList(u32) = .empty; + try ops.appendSlice(e.arena, &.{ coord, coord }); + for (0..n) |k| try ops.append(e.arena, @intCast(k)); + coord_id = try e.op1(.vector_shuffle, try e.t.vector(.int, @intCast(n)), ops.items); + } + mask |= 0x2; + try extra.append(e.arena, lod_from_coord.?); + } + if (call.offset) |k| { + if (try e.constValue(args[k])) |c| { + mask |= 0x8; + try extra.append(e.arena, c); + } else { + if (call.op != .gather and call.op != .gather_cmp) return e.unsupported("texel offsets that are not constants (they need loop unrolling) are not supported yet", .{}); + try e.cap(.image_gather_extended); + mask |= 0x10; + try extra.append(e.arena, e.val(args[k])); + } + } + if (call.sample_index) |k| { + mask |= 0x40; + try extra.append(e.arena, e.val(args[k])); + } + if (call.clamp) |k| { + try e.cap(.min_lod); + mask |= 0x80; + try extra.append(e.arena, e.val(args[k])); + } + var ops: std.ArrayList(u32) = .empty; + if (call.op == .load) { + if (sh.rw and e.imageFormat(r.elem) == 0) try e.cap(.storage_image_read_without_format); + try ops.appendSlice(e.arena, &.{ img, coord_id }); + if (mask != 0) { + try ops.append(e.arena, mask); + try ops.appendSlice(e.arena, extra.items); + } + const v = try e.opRaw(if (sh.rw) .image_read else .image_fetch, try e.vec4Of(s), ops.items); + return e.texelResult(v, s, ty); + } + if (call.op == .sample_position) return e.unsupported("GetSamplePosition is not supported yet", .{}); + const smp = try e.opRaw(.load, try e.samplerType(), &.{e.val(args[call.sampler.?])}); + const si = try e.opRaw(.sampled_image, try e.sampledImageType(e.global_images[g]), &.{ img, smp }); + if (call.op == .calc_lod or call.op == .calc_lod_unclamped) { + try e.cap(.image_query); + const q = try e.opRaw(.image_query_lod, try e.typeId(try e.t.vector(.float, 2)), &.{ si, coord }); + return e.op1(.composite_extract, try e.t.scalar(.float), &.{ q, @intFromBool(call.op == .calc_lod_unclamped) }); + } + try ops.appendSlice(e.arena, &.{ si, coord }); + if (call.compare) |k| try ops.append(e.arena, e.val(args[k])); + if (call.op == .gather) try ops.append(e.arena, try e.constInt(call.channel)); + if (call.op == .gather_cmp and call.channel != 0) return e.unsupported("'{s}' is not supported for SPIR-V", .{name}); + try ops.append(e.arena, mask); + try ops.appendSlice(e.arena, extra.items); + const op: Op = switch (call.op) { + .sample, .sample_bias => .image_sample_implicit_lod, + .sample_level, .sample_grad => .image_sample_explicit_lod, + .sample_cmp, .sample_cmp_bias => .image_sample_dref_implicit_lod, + .sample_cmp_level_zero, .sample_cmp_level, .sample_cmp_grad => .image_sample_dref_explicit_lod, + .gather => .image_gather, + .gather_cmp => .image_dref_gather, + else => unreachable, + }; + if (call.op.isCmp() and call.op != .gather_cmp) return e.opRaw(op, try e.scalarType(s), ops.items); + const v = try e.opRaw(op, try e.vec4Of(s), ops.items); + return e.texelResult(v, s, ty); + } + + fn getDimensions(e: *Emitter, g: u32, r: @FieldType(types.Type, "resource"), args: []const Ref) Error!void { + const uint_ty = try e.t.scalar(.uint); + const store = struct { + fn f(em: *Emitter, arg: Ref, v: Id) Error!void { + const ty = em.f.inst(arg).ty; + const cv = try em.convert(v, try em.t.scalar(.uint), ty); + try em.b.emit(.functions, .store, &.{ em.val(arg), cv }); + } + }.f; + switch (r.kind) { + .structured_buffer, .rw_structured_buffer, .byte_address_buffer, .rw_byte_address_buffer => { + const len = try e.op1(.array_length, uint_ty, &.{ e.global_vars[g], 0 }); + if (r.kind == .byte_address_buffer or r.kind == .rw_byte_address_buffer) { + try store(e, args[0], try e.op1(.i_mul, uint_ty, &.{ len, try e.constUint(4) })); + } else { + try store(e, args[0], len); + if (args.len > 1) { + const stride = layout.arrayStride(e.t, r.elem, false, .std430) catch return e.unsupported("buffer element type", .{}); + try store(e, args[1], try e.constUint(stride)); + } + } + return; + }, + else => {}, + } + const sh = texture.shape(r.kind) orelse return e.unsupported("GetDimensions on this resource is not supported yet", .{}); + try e.cap(.image_query); + const img = try e.loadImage(g); + const d = texture.getDimensions(sh, args.len); + const n: u8 = if (sh.dim == .buffer) 1 else (if (sh.dim == .cube) 2 else sh.coords()) + @intFromBool(sh.array); + const size_ty = if (n == 1) uint_ty else try e.t.vector(.uint, n); + const size = if (sh.hasMips()) + try e.op1(.image_query_size_lod, size_ty, &.{ img, if (d.mip) |k| e.val(args[k]) else try e.constUint(0) }) + else + try e.op1(.image_query_size, size_ty, &.{img}); + for (d.outs[0..d.count]) |o| { + const v = if (o.comp == 3) + try e.op1(if (sh.ms) .image_query_samples else .image_query_levels, uint_ty, &.{img}) + else if (n == 1) + size + else + try e.op1(.composite_extract, uint_ty, &.{ size, o.comp }); + try store(e, args[o.arg], v); + } + } + /// The global a resource value comes from (`load (global g)`). fn globalOf(e: *Emitter, r: Ref) ?u32 { const i = e.f.inst(r);