diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 488e0de..a85867e 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -13,6 +13,7 @@ const module = @import("module.zig"); const shader = @import("shader.zig"); const container = @import("container.zig"); const hash = @import("hash.zig"); +const layout = @import("../ir/layout.zig"); const TypeId = types.TypeId; const TypeTable = types.TypeTable; @@ -39,6 +40,9 @@ const Lowered = union(enum) { ptr: Ptr, /// A resource handle (index into Emitter.resources). handle: u32, + /// A place in a constant buffer: byte offset plus a dynamic register + /// offset. + cbuf: struct { res: u32, offset: u32 = 0, dyn_regs: ?Value = null }, }; /// Pointer into a flattened local: alloca `base` of `[n x scalar]`, at @@ -251,6 +255,13 @@ const Emitter = struct { fn collectResources(e: *Emitter) Error!void { var counts = [_]u32{ 0, 0, 0, 0 }; + // Constant buffers: `$Globals` first, then the others in order. + for ([_]bool{ true, false }) |globals_pass| for (e.m.globals.items, 0..) |g, gi| { + if (g.space != .cbuffer or std.mem.eql(u8, g.name, "$Globals") != globals_pass) continue; + try e.resources.append(e.arena, .{ .global = @intCast(gi), .class = .cbuffer, .id = counts[2], .kind = 13, .elem = g.ty }); + counts[2] += 1; + try e.resource_of_global.put(e.arena, @intCast(gi), @intCast(e.resources.items.len - 1)); + }; for (e.m.globals.items, 0..) |g, gi| { if (g.space != .resource) continue; const r = switch (e.t.get(g.ty)) { @@ -338,6 +349,7 @@ const Emitter = struct { var basic: i64 = res.kind; if (res.class == .uav) basic |= 0x1000; const extra: i64 = switch (res.kind) { + 13 => try e.cbufferSize(res), 12 => try e.stride(res.elem), 10 => blk: { const n = try e.flatCount(res.elem); @@ -554,6 +566,7 @@ const Emitter = struct { .param => |p| return frame.params[p], .global => |g| { const ri = e.resource_of_global.get(g) orelse return e.unsupported("global '{s}' is not supported yet", .{e.m.globals.items[g].name}); + if (e.resources.items[ri].class == .cbuffer) return .{ .cbuf = .{ .res = ri } }; return .{ .handle = ri }; }, .local_var => { @@ -568,6 +581,7 @@ const Emitter = struct { }, .load => |p| switch (frame.vals[p.index()]) { .handle => |h| return .{ .handle = h }, + .cbuf => |c| return e.cbufferLoad(c.res, c.offset, c.dyn_regs, i.ty), .ptr => |ptr| return e.loadPtr(ptr, try e.flatCount(i.ty)), else => return e.unsupported("internal: load from a non-pointer", .{}), }, @@ -580,6 +594,7 @@ const Emitter = struct { return .none; }, .access => |a| { + if (frame.vals[a.base.index()] == .cbuf) return e.cbufferAccess(frame, frame.vals[a.base.index()].cbuf, f.inst(a.base).ty, a.indices); var ptr = switch (frame.vals[a.base.index()]) { .ptr => |p| p, else => return e.unsupported("access into this storage is not supported yet", .{}), @@ -1047,6 +1062,108 @@ const Emitter = struct { return acc; } + // ------------------------------------------------------------------ + // Constant buffers + + fn cbufferSize(e: *Emitter, res: Resource) Error!i64 { + const g = e.m.globals.items[res.global]; + return layout.sizeOf(e.t, g.ty, .dx_legacy) catch e.unsupported("constant buffer '{s}' contains types that are not supported yet", .{g.name}); + } + + /// Byte offset of a member / element inside a constant buffer. + fn cbufferAccess(e: *Emitter, frame: *Frame, start: @FieldType(Lowered, "cbuf"), base_ty: TypeId, indices: []const Ref) Error!Lowered { + var c = start; + var cur = base_ty; + for (indices) |x| { + const xi = frame.f.inst(x); + switch (e.t.get(cur)) { + .@"struct" => |st| { + const k: u32 = @intCast(xi.op.constant.int); + const offs = layout.fieldOffsets(e.arena, e.t, st, .dx_legacy) catch return e.unsupported("constant buffer member types", .{}); + c.offset += offs[k]; + cur = st.fields.items[k].type; + }, + .array => |arr| { + const stride_b = layout.arrayStride(e.t, arr.elem, .dx_legacy) catch return e.unsupported("constant buffer array element types", .{}); + if (xi.op == .constant) { + c.offset += @as(u32, @intCast(xi.op.constant.int)) * stride_b; + } else { + const i32t = try e.dm.intType(32); + const idx = (try e.scalars(frame, x))[0]; + const regs = if (stride_b == 16) idx else try e.add(i32t, .{ .binop = .{ .op = .mul, .lhs = idx, .rhs = try e.i32Const(stride_b / 16) } }); + c.dyn_regs = if (c.dyn_regs) |d| try e.add(i32t, .{ .binop = .{ .op = .add, .lhs = d, .rhs = regs } }) else regs; + } + cur = arr.elem; + }, + .vector => |v| { + if (xi.op != .constant) return e.unsupported("dynamic indexing of constant buffer vectors", .{}); + c.offset += @as(u32, @intCast(xi.op.constant.int)) * storageScalar(v.elem).size(); + cur = try e.t.scalar(v.elem); + }, + .matrix => |mt| { + if (xi.op != .constant) return e.unsupported("dynamic indexing of constant buffer matrices", .{}); + // Row r of a column-major matrix: component r of each column. + _ = mt; + return e.unsupported("row access into constant buffer matrices", .{}); + }, + else => return e.unsupported("indexing this constant buffer member", .{}), + } + } + return .{ .cbuf = c }; + } + + fn cbufferLoad(e: *Emitter, ri: u32, offset: u32, dyn_regs: ?Value, ty: TypeId) Error!Lowered { + const res = e.resources.items[ri]; + const n = try e.flatCount(ty); + const out = try e.arena.alloc(Value, n); + const i32t = try e.dm.intType(32); + var cache_reg: ?u32 = null; + var cache_val: Value = undefined; + var cache_c: Scalar = .int; + for (out, 0..) |*o, k| { + const comp_ty = try e.componentType(ty, @intCast(k)); + const c = e.compOf(comp_ty); + const mem_c: Scalar = if (c == .bool) .uint else c; + if (mem_c.size() != 4) return e.unsupported("{d}-bit constant buffer members are not supported yet", .{mem_c.size() * 8}); + const off = offset + (layout.componentOffset(e.arena, e.t, ty, @intCast(k), .dx_legacy) catch return e.unsupported("constant buffer member types", .{})); + const reg = off / 16; + const st = try e.scalarTy(mem_c); + const same_kind = (mem_c.isFloat() == cache_c.isFloat()); + if (cache_reg == null or cache_reg.? != reg or !same_kind) { + const ret_name = try std.fmt.allocPrint(e.arena, "dx.types.CBufRet.{s}", .{e.overloadName(st)}); + const ret_ty = try e.dm.getType(.{ .@"struct" = .{ .name = ret_name, .elems = &.{ st, st, st, st } } }); + const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.cbufferLoadLegacy.{s}", .{e.overloadName(st)}), ret_ty, &.{ i32t, e.handle_ty, i32t }, .nounwind_readonly); + var reg_v = try e.i32Const(reg); + if (dyn_regs) |d| reg_v = try e.add(i32t, .{ .binop = .{ .op = .add, .lhs = d, .rhs = reg_v } }); + cache_val = try e.callOp(fn_i, ret_ty, &.{ try e.i32Const(59), res.handle, reg_v }); + cache_reg = reg; + cache_c = mem_c; + } + const v = try e.add(st, .{ .extractvalue = .{ .agg = cache_val, .index = (off % 16) / 4 } }); + o.* = if (c == .bool) try e.convertScalar(v, .uint, .bool) else v; + } + return .{ .scalars = out }; + } + + /// The scalar type of flattened component `k` of `ty`. + fn componentType(e: *Emitter, ty: TypeId, k: u32) Error!TypeId { + switch (e.t.get(ty)) { + .scalar, .@"enum" => return ty, + .vector, .matrix => return e.t.scalar(e.t.component(ty).?), + .array => |a| return e.componentType(a.elem, k % try e.flatCount(a.elem)), + .@"struct" => |s| { + var kk = k; + for (s.fields.items) |f| { + const n = try e.flatCount(f.type); + if (kk < n) return e.componentType(f.type, kk); + kk -= n; + } + return e.unsupported("struct component", .{}); + }, + else => return e.unsupported("component type", .{}), + } + } + // ------------------------------------------------------------------ // Resources and stage inputs @@ -1217,6 +1334,14 @@ const Emitter = struct { var lists: [4]std.ArrayList(?module.MdId) = .{ .empty, .empty, .empty, .empty }; for (e.resources.items) |r| { const g = e.m.globals.items[r.global]; + if (r.class == .cbuffer) { + const f32t = try dm.getType(.float); + const cb_ty = try dm.getType(.{ .@"struct" = .{ .name = g.name, .elems = &.{f32t} } }); + const undef_cb = try dm.constant(.{ .ty = try dm.ptrType(cb_ty), .kind = .undef }); + const b = g.binding; + 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; + } 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) }); const elem_dt = try e.scalarTy(if (r.kind == 11) .uint else try e.uniformScalar(r.elem)); diff --git a/src/ir/ir.zig b/src/ir/ir.zig index 4f393bc..0a8ab72 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -38,7 +38,7 @@ pub const BlockId = enum(u32) { }; /// Where a pointer points. -pub const Space = enum { none, function, private, groupshared, resource, input, output }; +pub const Space = enum { none, function, private, groupshared, resource, input, output, cbuffer }; pub const BinaryOp = enum { add, diff --git a/src/ir/layout.zig b/src/ir/layout.zig new file mode 100644 index 0000000..d41cd15 --- /dev/null +++ b/src/ir/layout.zig @@ -0,0 +1,158 @@ +//! Constant buffer layouts. +//! +//! `dx_legacy` is D3D's cbuffer packing (DXIL): 16-byte registers; vectors +//! may not straddle a register; arrays, structs and matrices start on a +//! register and every array element but the last fills whole registers. +//! +//! `vk_relaxed` is dxc's default SPIR-V layout for cbuffers: std140 with +//! relaxed vector alignment (component-size aligned unless the vector +//! would straddle a 16-byte boundary); arrays and structs are 16-byte +//! aligned and padded to multiples of 16. +//! +//! Matrices are column-major (dxc's default without -Zpr). + +const std = @import("std"); +const types = @import("../sema/types.zig"); + +const TypeId = types.TypeId; +const TypeTable = types.TypeTable; + +pub const Rules = enum { dx_legacy, vk_relaxed }; + +pub const Error = error{Unsupported}; + +fn scalarSize(t: *const TypeTable, ty: TypeId) u32 { + const c = t.component(ty).?; + return switch (c) { + .double, .int64, .uint64 => 8, + .int16, .uint16, .float16 => 2, + else => 4, + }; +} + +fn roundUp(v: u32, a: u32) u32 { + return (v + a - 1) / a * a; +} + +/// Size in bytes (for dx_legacy, the last element / member is not padded). +pub fn sizeOf(t: *const TypeTable, ty: TypeId, rules: Rules) Error!u32 { + switch (t.get(ty)) { + .scalar, .@"enum" => return scalarSize(t, ty), + .vector => |v| return v.len * scalarSize(t, ty), + .matrix => |m| { + // Column-major: one register per column of `rows` components. + const col = m.rows * scalarSize(t, ty); + return switch (rules) { + .dx_legacy => (m.cols - 1) * 16 + col, + .vk_relaxed => m.cols * 16, + }; + }, + .array => |a| { + const stride = try arrayStride(t, a.elem, rules); + return switch (rules) { + .dx_legacy => (a.len - 1) * stride + try sizeOf(t, a.elem, rules), + .vk_relaxed => a.len * stride, + }; + }, + .@"struct" => |s| { + var off: u32 = 0; + for (s.fields.items) |f| off = try place(t, off, f.type, rules) + try sizeOf(t, f.type, rules); + return switch (rules) { + .dx_legacy => off, + .vk_relaxed => roundUp(off, 16), + }; + }, + else => return error.Unsupported, + } +} + +/// Byte distance between array elements. +pub fn arrayStride(t: *const TypeTable, elem: TypeId, rules: Rules) Error!u32 { + return roundUp(try sizeOf(t, elem, rules), 16); +} + +/// Offset where a member of type `ty` goes when the previous one ended at +/// `off`. +pub fn place(t: *const TypeTable, off: u32, ty: TypeId, rules: Rules) Error!u32 { + switch (t.get(ty)) { + .scalar, .@"enum", .vector => { + const size = try sizeOf(t, ty, rules); + const comp = scalarSize(t, ty); + var o = roundUp(off, comp); + // No straddling a 16-byte register. + if (o / 16 != (o + size - 1) / 16) o = roundUp(o, 16); + return o; + }, + .matrix, .array, .@"struct" => return roundUp(off, 16), + else => return error.Unsupported, + } +} + +/// Offsets of a struct's fields. +pub fn fieldOffsets(a: std.mem.Allocator, t: *const TypeTable, info: *const types.StructInfo, rules: Rules) (Error || std.mem.Allocator.Error)![]u32 { + const out = try a.alloc(u32, info.fields.items.len); + var off: u32 = 0; + for (info.fields.items, out) |f, *o| { + o.* = try place(t, off, f.type, rules); + off = o.* + try sizeOf(t, f.type, rules); + } + return out; +} + +/// Byte offset of flattened component `k` of a value of type `ty` (row-major +/// component order for matrices, as the IR flattens them). +pub fn componentOffset(a: std.mem.Allocator, t: *const TypeTable, ty: TypeId, k: u32, rules: Rules) (Error || std.mem.Allocator.Error)!u32 { + switch (t.get(ty)) { + .scalar, .@"enum" => return 0, + .vector => return k * scalarSize(t, ty), + .matrix => |m| { + const r = k / m.cols; + const c = k % m.cols; + return c * 16 + r * scalarSize(t, ty); + }, + .array => |arr| { + const n = try flatCount(t, arr.elem); + return (k / n) * try arrayStride(t, arr.elem, rules) + try componentOffset(a, t, arr.elem, k % n, rules); + }, + .@"struct" => |s| { + const offs = try fieldOffsets(a, t, s, rules); + var kk = k; + for (s.fields.items, offs) |f, o| { + const n = try flatCount(t, f.type); + if (kk < n) return o + try componentOffset(a, t, f.type, kk, rules); + kk -= n; + } + return error.Unsupported; + }, + else => return error.Unsupported, + } +} + +pub fn flatCount(t: *const TypeTable, ty: TypeId) Error!u32 { + return switch (t.get(ty)) { + .scalar, .@"enum" => 1, + .vector => |v| v.len, + .matrix => |m| @as(u32, m.rows) * m.cols, + .array => |a| a.len * try flatCount(t, a.elem), + .@"struct" => |s| blk: { + var n: u32 = 0; + for (s.fields.items) |f| n += try flatCount(t, f.type); + break :blk n; + }, + else => error.Unsupported, + }; +} + +test "dx legacy packing" { + var t = try TypeTable.init(std.testing.allocator); + defer t.deinit(); + const f = try t.scalar(.float); + const f2 = try t.vector(.float, 2); + const f3 = try t.vector(.float, 3); + const f4a = try t.array(try t.vector(.float, 4), 2); + try std.testing.expectEqual(@as(u32, 4), try place(&t, 4, f2, .dx_legacy)); + try std.testing.expectEqual(@as(u32, 16), try place(&t, 12, f3, .dx_legacy)); + try std.testing.expectEqual(@as(u32, 32), try sizeOf(&t, f4a, .dx_legacy)); + try std.testing.expectEqual(@as(u32, 20), try sizeOf(&t, try t.array(f, 2), .dx_legacy)); + try std.testing.expectEqual(@as(u32, 32), try sizeOf(&t, try t.array(f, 2), .vk_relaxed)); +} diff --git a/src/ir/lower.zig b/src/ir/lower.zig index 73145df..6098f7e 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -49,6 +49,10 @@ const Lowerer = struct { funcs: std.AutoHashMapUnmanaged(*const semamod.Function, u32) = .empty, pending: std.ArrayList(*const semamod.Function) = .empty, globals: std.AutoHashMapUnmanaged(*const Variable, u32) = .empty, + /// cbuffer globals by declaration (0: `$Globals`), and where each + /// member variable lives. + cbuffers: std.AutoHashMapUnmanaged(usize, u32) = .empty, + cbuffer_members: std.AutoHashMapUnmanaged(*const Variable, struct { global: u32, field: u32 }) = .empty, // Per function. b: ir.Builder = undefined, @@ -120,10 +124,7 @@ const Lowerer = struct { const space: ir.Space = switch (v.storage) { .groupshared => .groupshared, .global_static, .constant => if (l.s.types.get(v.type) == .resource or l.s.types.get(v.type) == .sampler) .resource else .private, - .global_uniform, .cbuffer => { - l.unsupported(v.loc, "constant buffer variable '{s}' is not supported yet", .{v.name}); - return error.Unsupported; - }, + .global_uniform, .cbuffer => unreachable, // see cbufferMember else => unreachable, }; var binding: ir.Binding = .{}; @@ -137,6 +138,49 @@ const Lowerer = struct { return i; } + /// The cbuffer global holding `v` (created with all its members on + /// first use, since their layout depends on every member). + fn cbufferMember(l: *Lowerer, v: *const Variable) Error!struct { global: u32, field: u32 } { + if (l.cbuffer_members.get(v)) |m| return .{ .global = m.global, .field = m.field }; + const key: usize = if (v.block) |b| @intFromPtr(b) else 0; + if (l.cbuffers.contains(key)) unreachable; // members are registered with their block + var members: std.ArrayList(*const Variable) = .empty; + var name: []const u8 = "$Globals"; + var binding: ir.Binding = .{}; + if (v.block) |b| { + const cb = b.kind.cbuffer; + if (cb.tbuffer) { + l.unsupported(v.loc, "tbuffer variables are not supported yet", .{}); + return error.Unsupported; + } + name = cb.name; + for (cb.members) |m| if (m.kind == .@"var") { + if (l.s.decl_vars.get(&m.kind.@"var")) |mv| try members.append(l.arena, mv); + }; + for (cb.semantics) |sem| if (sem.kind == .register) { + binding = parseBinding(sem.values); + }; + } else { + for (l.s.uniform_globals.items) |g| { + if (l.s.types.get(g.type) == .resource or l.s.types.get(g.type) == .sampler) continue; + try members.append(l.arena, g); + } + } + const info = try l.arena.create(@import("../sema/types.zig").StructInfo); + info.* = .{ .name = name, .complete = true }; + for (members.items) |mv| try info.fields.append(l.arena, .{ .name = mv.name, .type = mv.type }); + const ty = try l.s.types.intern(.{ .@"struct" = info }); + try l.m.globals.append(l.arena, .{ .name = name, .ty = ty, .space = .cbuffer, .binding = binding }); + const gi: u32 = @intCast(l.m.globals.items.len - 1); + try l.cbuffers.put(l.arena, key, gi); + for (members.items, 0..) |mv, fi| try l.cbuffer_members.put(l.arena, mv, .{ .global = gi, .field = @intCast(fi) }); + const m = l.cbuffer_members.get(v) orelse { + l.unsupported(v.loc, "constant buffer variable '{s}' is not supported yet", .{v.name}); + return error.Unsupported; + }; + return .{ .global = m.global, .field = m.field }; + } + // ------------------------------------------------------------------ // Statements @@ -605,6 +649,25 @@ const Lowerer = struct { switch (r) { .function => |f| { const fi = try l.functionIndex(f); + // Missing trailing arguments take the parameters' defaults. + var full = args; + if (args.len < f.params.len) { + const all = try l.arena.alloc(*ast.Expr, f.params.len); + @memcpy(all[0..args.len], args); + for (all[args.len..], f.decl.params[args.len..]) |*a, pd| { + a.* = pd.init orelse return l.fail(e, "this call"); + } + full = all; + } + return l.userCall(f, fi, full, ret_ty); + }, + else => return l.callOther(e, r, callee, args, ret_ty), + } + } + + fn userCall(l: *Lowerer, f: *const semamod.Function, fi: u32, args: []const *ast.Expr, ret_ty: TypeId) Error!Ref { + { + { const vals = try l.arena.alloc(Ref, args.len); const temps = try l.arena.alloc(Ref, args.len); for (args, f.params, 0..) |a, p, i| { @@ -624,7 +687,12 @@ const Lowerer = struct { try l.storeTo(a, try l.convert(back, a.ty)); } return res; - }, + } + } + } + + fn callOther(l: *Lowerer, e: *ast.Expr, r: semamod.Resolution, callee: *ast.Expr, args: []const *ast.Expr, ret_ty: TypeId) Error!Ref { + switch (r) { .intrinsic => |it| { const name = table.intrinsics[it.index].name; if (it.object) |_| { @@ -659,6 +727,17 @@ const Lowerer = struct { if (l.vars.get(v)) |p| return p; switch (v.storage) { .local, .param, .local_static => return l.fail(e, "this variable"), + .global_uniform, .cbuffer => { + if (l.s.types.get(v.type) == .resource or l.s.types.get(v.type) == .sampler) { + l.unsupported(e.loc, "resource '{s}' declared as a uniform is not supported yet", .{v.name}); + return error.Unsupported; + } + const cm = try l.cbufferMember(v); + const glob = l.m.globals.items[cm.global]; + const base = try l.b.add(.{ .op = .{ .global = cm.global }, .ty = glob.ty, .ptr = .cbuffer }); + const idx = try l.b.constInt(try t.scalar(.uint), cm.field); + return l.b.add(.{ .op = .{ .access = .{ .base = base, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = v.type, .ptr = .cbuffer }); + }, else => {}, } const g = try l.globalIndex(v); diff --git a/src/root.zig b/src/root.zig index 70523b1..ebd0ead 100644 --- a/src/root.zig +++ b/src/root.zig @@ -27,6 +27,7 @@ pub const dxil = struct { 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 sema = struct { diff --git a/src/sema/sema.zig b/src/sema/sema.zig index 1bae720..1efef7e 100644 --- a/src/sema/sema.zig +++ b/src/sema/sema.zig @@ -51,6 +51,8 @@ pub const Variable = struct { decl: ?*const ast.VarDecl = null, /// Position among the function's parameters (storage == .param). param_index: u32 = 0, + /// The `cbuffer` / `tbuffer` declaration holding the variable. + block: ?*const ast.Decl = null, }; /// What an expression refers to, recorded by Sema for lowering @@ -158,6 +160,9 @@ pub const Sema = struct { resolutions: std.ArrayList(Resolution) = .empty, /// Variable of each checked variable declaration (for lowering). decl_vars: std.AutoHashMapUnmanaged(*const ast.VarDecl, *Variable) = .empty, + /// Global uniforms outside cbuffers (dxc's `$Globals`), in order. + uniform_globals: std.ArrayList(*Variable) = .empty, + current_block: ?*const ast.Decl = null, loop_depth: u32 = 0, switch_depth: u32 = 0, intrinsic_db: intrinsics.Db, @@ -778,6 +783,8 @@ pub const Sema = struct { s.err(sem.loc, "user defined constant buffer slots cannot be target specific", .{}); } } + s.current_block = d; + defer s.current_block = null; for (cb.members) |m| try s.decl(m, .cbuffer); if (cb.name.len > 0 and s.scope.syms.get(cb.name) == null) { // The buffer name is not usable as a value; reserve it. @@ -1351,6 +1358,8 @@ pub const Sema = struct { }; try s.declare(v.name, .{ .variable = variable }, v.name_loc); try s.decl_vars.put(s.arena, v, variable); + if (ctx == .cbuffer) variable.block = s.current_block; + if (storage == .global_uniform) try s.uniform_globals.append(s.arena, variable); // Unsized arrays take their size from the initializer. if (v.init) |init_e| if (!is_auto) { if (s.types.get(ty) == .array and s.types.get(ty).array.len == 0 and init_e.kind == .init_list) { diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index 5110419..16f037e 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -9,6 +9,7 @@ const ir = @import("../ir/ir.zig"); const types = @import("../sema/types.zig"); const builder = @import("builder.zig"); const diag = @import("../diag.zig"); +const layout = @import("../ir/layout.zig"); const Builder = builder.Builder; const Id = builder.Id; @@ -42,6 +43,8 @@ const Emitter = struct { diags: *diag.Diagnostics, value_types: std.AutoHashMapUnmanaged(TypeId, Id) = .empty, + /// Explicitly laid out variants of arrays and structs (cbuffers). + layout_types: std.AutoHashMapUnmanaged(TypeId, Id) = .empty, pointer_types: std.AutoHashMapUnmanaged(struct { StorageClass, Id }, Id) = .empty, function_types: std.StringHashMapUnmanaged(Id) = .empty, constants: std.AutoHashMapUnmanaged(struct { Id, u64 }, Id) = .empty, @@ -150,6 +153,40 @@ const Emitter = struct { return id; } + /// `ty` with explicit (cbuffer) layout decorations: array strides and + /// member offsets. Scalars and vectors are the plain types. + fn layoutTypeId(e: *Emitter, ty: TypeId) Error!Id { + switch (e.t.get(ty)) { + // Externally visible storage holds bools as uints. + .scalar, .vector, .@"enum" => return e.typeId(if (e.t.component(ty) == .bool) try e.t.withComponent(ty, .uint) else ty), + else => {}, + } + if (e.layout_types.get(ty)) |id| return id; + const id = e.b.newId(); + switch (e.t.get(ty)) { + .array => |a| { + const elem = try e.layoutTypeId(a.elem); + try e.b.emit(.types_globals, .type_array, &.{ id, elem, try e.constUint(a.len) }); + const stride = layout.arrayStride(e.t, a.elem, .vk_relaxed) catch return e.unsupported("constant buffer member type", .{}); + try e.b.emit(.annotations, .decorate, &.{ id, 6, stride }); // ArrayStride + }, + .@"struct" => |s| { + var ops: std.ArrayList(u32) = .empty; + try ops.append(e.arena, id); + for (s.fields.items) |f| try ops.append(e.arena, try e.layoutTypeId(f.type)); + try e.b.emit(.types_globals, .type_struct, ops.items); + const offs = layout.fieldOffsets(e.arena, e.t, s, .vk_relaxed) catch return e.unsupported("constant buffer member type '{s}'", .{s.name}); + for (s.fields.items, offs, 0..) |f, o, k| { + try e.b.emit(.annotations, .member_decorate, &.{ id, @intCast(k), 35, o }); // Offset + try e.b.emitWithString(.debug_names, .member_name, &.{ id, @intCast(k) }, f.name, &.{}); + } + }, + else => return e.unsupported("constant buffer members of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}), + } + try e.layout_types.put(e.arena, ty, id); + return id; + } + fn pointerType(e: *Emitter, sc: StorageClass, pointee: Id) Error!Id { if (e.pointer_types.get(.{ sc, pointee })) |id| return id; const id = e.b.newId(); @@ -297,10 +334,10 @@ const Emitter = struct { // Buffers hold bools as uints. if (e.t.component(elem_ty) == .bool) elem_ty = try e.t.withComponent(elem_ty, .uint); const elem = try e.typeId(elem_ty); - const layout = try e.std430(elem_ty); + const elem_layout = try e.std430(elem_ty); const rt = e.b.newId(); try e.b.emit(.types_globals, .type_runtime_array, &.{ rt, elem }); - try e.b.emit(.annotations, .decorate, &.{ rt, 6, layout.size }); // ArrayStride + try e.b.emit(.annotations, .decorate, &.{ rt, 6, elem_layout.size }); // ArrayStride const st = e.b.newId(); try e.b.emit(.types_globals, .type_struct, &.{ st, rt }); try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 35, 0 }); // Offset 0 @@ -324,6 +361,24 @@ const Emitter = struct { try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{}); e.global_vars[gi] = var_id; }, + .cbuffer => { + const st = try e.layoutTypeId(g.ty); + try e.b.emit(.annotations, .decorate, &.{ st, 2 }); // Block + const ptr = try e.pointerType(.uniform, st); + const var_id = e.b.newId(); + try e.b.emit(.types_globals, .variable, &.{ ptr, var_id, @backingInt(StorageClass.uniform) }); + var binding = g.binding.index; + if (!g.binding.explicit) { + while (used.contains(.{ g.binding.space, next_free })) next_free += 1; + binding = next_free; + try used.put(e.arena, .{ g.binding.space, binding }, {}); + } + try e.b.emit(.annotations, .decorate, &.{ var_id, 34, g.binding.space }); // DescriptorSet + try e.b.emit(.annotations, .decorate, &.{ var_id, 33, binding }); // Binding + try e.b.emitWithString(.debug_names, .name, &.{st}, try std.fmt.allocPrint(e.arena, "type.{s}", .{g.name}), &.{}); + try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{}); + e.global_vars[gi] = var_id; + }, .groupshared, .private => { const ty = try e.typeId(g.ty); const sc: StorageClass = if (g.space == .groupshared) .workgroup else .private; @@ -538,6 +593,15 @@ const Emitter = struct { e.vals[ri] = e.val(p); return; } + if (f.inst(p).ptr == .cbuffer and e.t.component(i.ty) == .bool and e.t.shape(i.ty) != null) { + const stored = try e.t.withComponent(i.ty, .uint); + const raw = try e.op1(.load, stored, &.{e.val(p)}); + e.vals[ri] = try e.convert(raw, stored, i.ty); + return; + } + if (f.inst(p).ptr == .cbuffer and try e.layoutTypeId(i.ty) != try e.typeId(i.ty)) { + return e.unsupported("loading whole arrays or structs from constant buffers is not supported yet", .{}); + } e.vals[ri] = try e.op1(.load, i.ty, &.{e.val(p)}); }, .store => |s| try e.b.emit(.functions, .store, &.{ e.val(s.ptr), e.val(s.value) }), @@ -546,9 +610,10 @@ const Emitter = struct { .function => .function, .private => .private, .groupshared => .workgroup, + .cbuffer => .uniform, else => return e.unsupported("access into this storage is not supported yet", .{}), }; - const ptr_ty = try e.pointerType(sc, try e.typeId(i.ty)); + const ptr_ty = try e.pointerType(sc, if (i.ptr == .cbuffer) try e.layoutTypeId(i.ty) else try e.typeId(i.ty)); var ops: std.ArrayList(u32) = .empty; try ops.appendSlice(e.arena, &.{ ptr_ty, 0, e.val(a.base) }); // Indices into 1-vectors (SPIR-V scalars) are dropped. diff --git a/test/oracle/codegen.sh b/test/oracle/codegen.sh index ab67752..0050e03 100644 --- a/test/oracle/codegen.sh +++ b/test/oracle/codegen.sh @@ -31,7 +31,7 @@ while read -r f; do # shellcheck disable=SC2086 if "$ZDXC" -fno-color-diagnostics -no-warnings $flags "$f" -Fo "$TMP/out" > "$TMP/log" 2>&1; then if [ "$BACKEND" = spirv ]; then - "$SPIRV_VAL" --target-env vulkan1.0 "$TMP/out" > "$TMP/val" 2>&1 + "$SPIRV_VAL" --target-env vulkan1.0 --relax-block-layout "$TMP/out" > "$TMP/val" 2>&1 else "$DXV" "$TMP/out" > "$TMP/val" 2>&1 fi