Matrices and structs in codegen

SPIR-V:
- Float matrices are OpTypeMatrix with HLSL rows as columns (as dxc);
  integer / bool matrices are arrays of row vectors; 1xN / Nx1 are
  vectors. Arithmetic, comparisons, selects and component-wise
  intrinsics go row by row; mul maps to OpMatrixTimesVector /
  OpVectorTimesMatrix / OpMatrixTimesMatrix / OpDot with dxc's operand
  order (manual expansion for integers and vector-shaped matrices);
  transpose, matrix swizzles.
- Structs as OpTypeStruct. Buffer contents use laid-out type variants:
  std430 (structured buffers) and relaxed std140 (cbuffers), with member
  offsets, array strides, MatrixStride and RowMajor / ColMajor matching
  dxc; whole values convert between laid-out and plain types; access
  chains into structured buffer elements (buf[i].field).

Both backends:
- src/ir/layout.zig gains std430 and DXIL's packed structured-buffer
  layout and per-field row_major (recorded by Sema on fields and
  variables).
- Lowering: matrix-aware conversions (truncation, vector <-> matrix),
  constructors and initializer lists for structs and arrays, aggregate
  casts, derived-to-base conversion and stores through base casts.
- Entry points take and return structs: fields become signature
  elements, and a semantic on a struct numbers its fields.
- DXIL: structured buffers of structs (packed offsets, runs merged into
  4-wide loads / stores), buffer element access chains, mixed 32-bit
  struct locals, mul / transpose, cbuffer matrices by orientation.

oracle-codegen: SPIR-V 528 valid (was 313), DXIL 13 valid, 0 invalid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Peter Li 2026-10-31 05:37:25 -07:00
parent f06867f55f
commit 667f7cb4bb
7 changed files with 1103 additions and 209 deletions

View File

@ -42,7 +42,10 @@ const Lowered = union(enum) {
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 },
cbuf: struct { res: u32, offset: u32 = 0, dyn_regs: ?Value = null, row_major: bool = false },
/// A place inside a structured buffer element: element index plus byte
/// offset (constant and dynamic).
buf: struct { res: u32, index: Value, offset: u32 = 0, dyn: ?Value = null, row_major: bool = false },
};
/// Pointer into a flattened local: alloca `base` of `[n x scalar]`, at
@ -55,6 +58,8 @@ const Ptr = struct {
offset_dyn: ?Value = null,
/// bools are stored as i32.
bool_storage: bool = false,
/// Mixed 32-bit component types share i32 storage (floats bitcast).
mixed: bool = false,
};
const Resource = struct {
@ -304,6 +309,7 @@ const Emitter = struct {
}
fn createHandles(e: *Emitter) Error!void {
if (e.resources.items.len == 0) return;
const i32t = try e.dm.intType(32);
const i1t = try e.dm.intType(1);
const i8t = try e.dm.intType(8);
@ -360,11 +366,9 @@ const Emitter = struct {
return .{ basic, extra };
}
/// Structured buffer element stride (tightly packed scalars).
/// Structured buffer element stride (packed layout).
fn stride(e: *Emitter, ty: TypeId) Error!i64 {
const n = try e.flatCount(ty);
const c = try e.uniformScalar(ty);
return @as(i64, n) * c.size();
return layout.sizeOf(e.t, ty, false, .dx_packed) catch e.unsupported("buffer element type '{s}'", .{try e.t.format(e.arena, ty)});
}
/// DXIL ComponentType of a typed buffer element.
@ -571,6 +575,12 @@ const Emitter = struct {
},
.local_var => {
const n = try e.flatCount(i.ty);
if (try e.mixedStorage(i.ty)) {
const st = try e.dm.intType(32);
const arr = try e.dm.getType(.{ .array = .{ .len = n, .elem = st } });
const base = try e.addPrologue(try e.dm.ptrType(arr), .{ .alloca = .{ .elem = arr, .size = try e.i32Const(1) } });
return .{ .ptr = .{ .base = base, .array_ty = arr, .scalar_ty = st, .mixed = true } };
}
const c = try e.uniformScalar(i.ty);
const store_c = if (c == .bool) Scalar.int else c;
const st = try e.scalarTy(store_c);
@ -581,20 +591,33 @@ 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)),
.cbuf => |c| return e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, i.ty),
.buf => |b| return .{ .scalars = try e.structuredLoad(e.resources.items[b.res], b.index, b.offset, b.dyn, b.row_major, i.ty) },
.ptr => |ptr| return e.loadPtr(ptr, i.ty),
else => return e.unsupported("internal: load from a non-pointer", .{}),
},
.store => |s| {
if (frame.vals[s.ptr.index()] == .buf) {
const b = frame.vals[s.ptr.index()].buf;
try e.structuredStore(e.resources.items[b.res], b.index, b.offset, b.dyn, b.row_major, f.inst(s.value).ty, try e.scalars(frame, s.value));
return .none;
}
const ptr = switch (frame.vals[s.ptr.index()]) {
.ptr => |p| p,
else => return e.unsupported("internal: store to a non-pointer", .{}),
};
try e.storePtr(ptr, try e.scalars(frame, s.value));
try e.storePtr(ptr, try e.scalars(frame, s.value), f.inst(s.value).ty);
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);
if (frame.vals[a.base.index()] == .handle) {
const ri = frame.vals[a.base.index()].handle;
if (e.resources.items[ri].kind != 12) return e.unsupported("member access into this resource is not supported yet", .{});
const start: @FieldType(Lowered, "buf") = .{ .res = ri, .index = (try e.scalars(frame, a.indices[0]))[0] };
return e.bufferAccess(frame, start, e.t.get(f.inst(a.base).ty).resource.elem, a.indices[1..]);
}
if (frame.vals[a.base.index()] == .buf) return e.bufferAccess(frame, frame.vals[a.base.index()].buf, 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", .{}),
@ -796,21 +819,52 @@ const Emitter = struct {
};
}
fn loadPtr(e: *Emitter, ptr: Ptr, n: u32) Error!Lowered {
/// Whether `ty`'s components differ in type (all 32-bit), so storage is
/// i32 with bitcasts.
fn mixedStorage(e: *Emitter, ty: TypeId) Error!bool {
const n = try e.flatCount(ty);
var first: ?Scalar = null;
var mixed = false;
for (0..n) |k| {
const c = e.compOf(try e.componentType(ty, @intCast(k)));
const mc: Scalar = if (c == .bool) .int else c;
if (mc.size() != 4) {
if (first != null and first.? != mc) return e.unsupported("structs mixing 32-bit and other component sizes are not supported yet", .{});
}
if (first != null and first.? != mc) mixed = true;
if (first == null) first = mc;
}
return mixed;
}
fn loadPtr(e: *Emitter, ptr: Ptr, ty: TypeId) Error!Lowered {
const n = try e.flatCount(ty);
const out = try e.arena.alloc(Value, n);
for (out, 0..) |*o, c| {
const p = try e.elementPtr(ptr, @intCast(c));
const raw = try e.add(ptr.scalar_ty, .{ .load = .{ .ptr = p, .@"align" = 4 } });
o.* = if (ptr.bool_storage) try e.add(try e.dm.intType(1), .{ .cmp = .{ .pred = 33, .lhs = raw, .rhs = try e.i32Const(0) } }) else raw;
const ct = e.compOf(try e.componentType(ty, @intCast(c)));
o.* = if (ptr.bool_storage or (ptr.mixed and ct == .bool))
try e.add(try e.dm.intType(1), .{ .cmp = .{ .pred = 33, .lhs = raw, .rhs = try e.i32Const(0) } })
else if (ptr.mixed and ct.isFloat())
try e.add(try e.scalarTy(ct), .{ .cast = .{ .op = .bitcast, .val = raw } })
else
raw;
}
return .{ .scalars = out };
}
fn storePtr(e: *Emitter, ptr: Ptr, vals: []const Value) Error!void {
fn storePtr(e: *Emitter, ptr: Ptr, vals: []const Value, ty: TypeId) Error!void {
const void_ty = try e.voidTy();
for (vals, 0..) |v, c| {
const p = try e.elementPtr(ptr, @intCast(c));
const sv = if (ptr.bool_storage) try e.add(ptr.scalar_ty, .{ .cast = .{ .op = .zext, .val = v } }) else v;
const ct = e.compOf(try e.componentType(ty, @intCast(c)));
const sv = if (ptr.bool_storage or (ptr.mixed and ct == .bool))
try e.add(ptr.scalar_ty, .{ .cast = .{ .op = .zext, .val = v } })
else if (ptr.mixed and ct.isFloat())
try e.add(ptr.scalar_ty, .{ .cast = .{ .op = .bitcast, .val = v } })
else
v;
_ = try e.add(void_ty, .{ .store = .{ .ptr = p, .val = sv, .@"align" = 4 } });
}
}
@ -998,6 +1052,41 @@ const Emitter = struct {
}
return .{ .scalars = out };
}
if (eq(u8, name, "mul") and args.len == 2) {
// Flattened row-major: vectors on the left are rows, on the
// right columns.
const at0 = frame.f.inst(args[0]).ty;
const bt0 = frame.f.inst(args[1]).ty;
const as = e.t.shape(at0).?;
const bs = e.t.shape(bt0).?;
if (as.count() == 1 or bs.count() == 1) {
const sv = if (as.count() == 1) a[0][0] else a[1][0];
const other = if (as.count() == 1) a[1] else a[0];
for (out, other) |*o, x| o.* = try e.add(rt, .{ .binop = .{ .op = .mul, .lhs = x, .rhs = sv } });
return .{ .scalars = out };
}
const ar: u32 = if (as.kind == .vector) 1 else as.rows;
const ak: u32 = as.cols;
const bc: u32 = if (bs.kind == .vector) 1 else bs.cols;
for (0..ar) |ii| for (0..bc) |j| {
var acc: ?Value = null;
for (0..ak) |kk| {
const x = a[0][ii * ak + kk];
const y = if (bs.kind == .vector) a[1][kk] else a[1][kk * bc + j];
const p = try e.add(rt, .{ .binop = .{ .op = .mul, .lhs = x, .rhs = y } });
acc = if (acc) |s0| try e.add(rt, .{ .binop = .{ .op = .add, .lhs = s0, .rhs = p } }) else p;
}
out[ii * bc + j] = acc.?;
};
return .{ .scalars = out };
}
if (eq(u8, name, "transpose")) {
const as = e.t.shape(frame.f.inst(args[0]).ty).?;
for (0..as.cols) |c| for (0..as.rows) |r| {
out[c * as.rows + r] = a[0][r * as.cols + c];
};
return .{ .scalars = out };
}
if (eq(u8, name, "rcp")) {
for (out, 0..) |*o, k| o.* = try e.add(at, .{ .binop = .{ .op = .sdiv, .lhs = try e.constant(try e.t.scalar(ac), .{ .float = 1 }), .rhs = a[0][k] } });
return .{ .scalars = out };
@ -1067,7 +1156,7 @@ const Emitter = struct {
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});
return layout.sizeOf(e.t, g.ty, false, .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.
@ -1081,10 +1170,11 @@ const Emitter = struct {
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];
c.row_major = st.fields.items[k].row_major;
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", .{});
const stride_b = layout.arrayStride(e.t, arr.elem, c.row_major, .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 {
@ -1102,9 +1192,9 @@ const Emitter = struct {
},
.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", .{});
if (!c.row_major) return e.unsupported("row access into column-major constant buffer matrices", .{});
c.offset += @as(u32, @intCast(xi.op.constant.int)) * 16;
cur = try e.t.vector(mt.elem, mt.cols);
},
else => return e.unsupported("indexing this constant buffer member", .{}),
}
@ -1112,7 +1202,7 @@ const Emitter = struct {
return .{ .cbuf = c };
}
fn cbufferLoad(e: *Emitter, ri: u32, offset: u32, dyn_regs: ?Value, ty: TypeId) Error!Lowered {
fn cbufferLoad(e: *Emitter, ri: u32, offset: u32, dyn_regs: ?Value, row_major: bool, ty: TypeId) Error!Lowered {
const res = e.resources.items[ri];
const n = try e.flatCount(ty);
const out = try e.arena.alloc(Value, n);
@ -1125,7 +1215,7 @@ const Emitter = struct {
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 off = offset + (layout.componentOffset(e.arena, e.t, ty, row_major, @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());
@ -1180,9 +1270,123 @@ const Emitter = struct {
return e.dm.getType(.{ .@"struct" = .{ .name = name, .elems = &.{ scalar, scalar, scalar, scalar, i32t } } });
}
/// `buffer[i].member...` in a structured buffer: byte offsets in the
/// packed element layout.
fn bufferAccess(e: *Emitter, frame: *Frame, start: @FieldType(Lowered, "buf"), elem_ty: TypeId, indices: []const Ref) Error!Lowered {
var b = start;
var cur = elem_ty;
const i32t = try e.dm.intType(32);
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_packed) catch return e.unsupported("buffer member types", .{});
b.offset += offs[k];
b.row_major = st.fields.items[k].row_major;
cur = st.fields.items[k].type;
},
.array, .vector => {
const elem = if (e.t.get(cur) == .array) e.t.get(cur).array.elem else try e.t.scalar(e.t.get(cur).vector.elem);
const stride_b = layout.arrayStride(e.t, elem, b.row_major, .dx_packed) catch return e.unsupported("buffer element types", .{});
if (xi.op == .constant) {
b.offset += @as(u32, @intCast(xi.op.constant.int)) * stride_b;
} else {
const idx = (try e.scalars(frame, x))[0];
const bytes = try e.add(i32t, .{ .binop = .{ .op = .mul, .lhs = idx, .rhs = try e.i32Const(stride_b) } });
b.dyn = if (b.dyn) |d| try e.add(i32t, .{ .binop = .{ .op = .add, .lhs = d, .rhs = bytes } }) else bytes;
}
cur = elem;
},
else => return e.unsupported("indexing this buffer member is not supported yet", .{}),
}
}
return .{ .buf = b };
}
/// Loads a value of `ty` at a byte offset of a structured buffer
/// element: contiguous components of one type are read together.
fn structuredLoad(e: *Emitter, res: Resource, idx: Value, base: u32, dyn: ?Value, row_major: bool, ty: TypeId) Error![]const Value {
const n = try e.flatCount(ty);
const out = try e.arena.alloc(Value, n);
const i32t = try e.dm.intType(32);
const i8t = try e.dm.intType(8);
var k: u32 = 0;
while (k < n) {
const c0 = e.compOf(try e.componentType(ty, k));
const mem: Scalar = if (c0 == .bool) .uint else c0;
const off0 = layout.componentOffset(e.arena, e.t, ty, row_major, k, .dx_packed) catch return e.unsupported("buffer element types", .{});
var count: u32 = 1;
while (k + count < n and count < 4) : (count += 1) {
const cn = e.compOf(try e.componentType(ty, k + count));
const mn: Scalar = if (cn == .bool) .uint else cn;
const on = layout.componentOffset(e.arena, e.t, ty, row_major, k + count, .dx_packed) catch break;
if (mn != mem or on != off0 + count * mem.size()) break;
}
const st = try e.scalarTy(mem);
const ret_ty = try e.resRetType(st);
var off = try e.i32Const(base + off0);
if (dyn) |d| off = try e.add(i32t, .{ .binop = .{ .op = .add, .lhs = d, .rhs = off } });
const call = if (e.profile.minor >= 2) blk: {
const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.rawBufferLoad.{s}", .{e.overloadName(st)}), ret_ty, &.{ i32t, e.handle_ty, i32t, i32t, i8t, i32t }, .nounwind_readonly);
const mask = try e.dm.constant(.{ .ty = i8t, .kind = .{ .int = (@as(i64, 1) << @intCast(count)) - 1 } });
break :blk try e.callOp(fn_i, ret_ty, &.{ try e.i32Const(139), res.handle, idx, off, mask, try e.i32Const(mem.size()) });
} else blk: {
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);
break :blk try e.callOp(fn_i, ret_ty, &.{ try e.i32Const(68), res.handle, idx, off });
};
for (0..count) |j| {
const v = try e.add(st, .{ .extractvalue = .{ .agg = call, .index = @intCast(j) } });
const cj = e.compOf(try e.componentType(ty, k + @as(u32, @intCast(j))));
out[k + j] = if (cj == .bool) try e.convertScalar(v, .uint, .bool) else v;
}
k += count;
}
return out;
}
fn structuredStore(e: *Emitter, res: Resource, idx: Value, base: u32, dyn: ?Value, row_major: bool, ty: TypeId, vals: []const Value) Error!void {
const n: u32 = @intCast(vals.len);
const i32t = try e.dm.intType(32);
const i8t = try e.dm.intType(8);
const void_ty = try e.voidTy();
var k: u32 = 0;
while (k < n) {
const c0 = e.compOf(try e.componentType(ty, k));
const mem: Scalar = if (c0 == .bool) .uint else c0;
const off0 = layout.componentOffset(e.arena, e.t, ty, row_major, k, .dx_packed) catch return e.unsupported("buffer element types", .{});
var count: u32 = 1;
while (k + count < n and count < 4) : (count += 1) {
const cn = e.compOf(try e.componentType(ty, k + count));
const mn: Scalar = if (cn == .bool) .uint else cn;
const on = layout.componentOffset(e.arena, e.t, ty, row_major, k + count, .dx_packed) catch break;
if (mn != mem or on != off0 + count * mem.size()) break;
}
const st = try e.scalarTy(mem);
const undef_v = try e.dm.constant(.{ .ty = st, .kind = .undef });
var comps: [4]Value = .{ undef_v, undef_v, undef_v, undef_v };
for (0..count) |j| {
const cj = e.compOf(try e.componentType(ty, k + @as(u32, @intCast(j))));
comps[j] = if (cj == .bool) try e.convertScalar(vals[k + j], .bool, .uint) else vals[k + j];
}
var off = try e.i32Const(base + off0);
if (dyn) |d| off = try e.add(i32t, .{ .binop = .{ .op = .add, .lhs = d, .rhs = off } });
const mask = try e.dm.constant(.{ .ty = i8t, .kind = .{ .int = (@as(i64, 1) << @intCast(count)) - 1 } });
if (e.profile.minor >= 2) {
const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.rawBufferStore.{s}", .{e.overloadName(st)}), void_ty, &.{ i32t, e.handle_ty, i32t, i32t, st, st, st, st, i8t, i32t }, .nounwind);
_ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(140), res.handle, idx, off, comps[0], comps[1], comps[2], comps[3], mask, try e.i32Const(mem.size()) });
} else {
const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.bufferStore.{s}", .{e.overloadName(st)}), void_ty, &.{ i32t, e.handle_ty, i32t, i32t, st, st, st, st, i8t }, .nounwind);
_ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(69), res.handle, idx, off, comps[0], comps[1], comps[2], comps[3], mask });
}
k += count;
}
}
fn resourceLoad(e: *Emitter, frame: *Frame, res_ref: Ref, index_ref: Ref, ty: TypeId) Error!Lowered {
const res = try e.resourceOf(frame, res_ref);
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);
const c = try e.uniformScalar(ty);
const mem_c = if (c == .bool) Scalar.uint else c;
@ -1227,6 +1431,7 @@ const Emitter = struct {
const res = try e.resourceOf(frame, res_ref);
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);
const vt = frame.f.inst(value_ref).ty;
const c = try e.uniformScalar(vt);
const mem_c = if (c == .bool) Scalar.uint else c;
@ -1344,7 +1549,9 @@ const Emitter = struct {
}
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));
// 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));
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;

View File

@ -1,29 +1,34 @@
//! Constant buffer layouts.
//! Memory layouts of buffer contents.
//!
//! `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.
//! - `dx_legacy`: D3D cbuffer packing (DXIL cbuffers). 16-byte registers;
//! vectors may not straddle a register; arrays, structs and matrices
//! start on a register; every array element but the last fills whole
//! registers.
//! - `vk_relaxed`: dxc's default SPIR-V cbuffer layout. std140 with relaxed
//! vector placement (component aligned, no 16-byte straddle); arrays and
//! structs 16-byte aligned and padded; array strides multiples of 16.
//! - `std430`: dxc's default SPIR-V structured-buffer layout. Relaxed vector
//! placement as above; arrays and structs aligned to their members' std430
//! alignment (vec3 counts as 16).
//! - `dx_packed`: DXIL structured buffers, tightly packed at scalar
//! alignment.
//!
//! `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).
//! Matrices are column-major unless their field is `row_major`: a
//! column-major RxC matrix is C vectors of R components.
const std = @import("std");
const types = @import("../sema/types.zig");
const TypeId = types.TypeId;
const TypeTable = types.TypeTable;
const Allocator = std.mem.Allocator;
pub const Rules = enum { dx_legacy, vk_relaxed };
pub const Rules = enum { dx_legacy, vk_relaxed, std430, dx_packed };
pub const Error = error{Unsupported};
pub const Error = error{Unsupported} || Allocator.Error;
fn scalarSize(t: *const TypeTable, ty: TypeId) u32 {
const c = t.component(ty).?;
return switch (c) {
return switch (t.component(ty).?) {
.double, .int64, .uint64 => 8,
.int16, .uint16, .float16 => 2,
else => 4,
@ -34,32 +39,85 @@ 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 {
/// A matrix as stored: `count` vectors of `len` components.
const MatrixVectors = struct { count: u32, len: u32 };
fn matrixVectors(m: anytype, row_major: bool) MatrixVectors {
return if (row_major) .{ .count = m.rows, .len = m.cols } else .{ .count = m.cols, .len = m.rows };
}
/// std430 base alignment of an `n`-vector of `s`-byte components.
fn vectorAlign(n: u32, s: u32) u32 {
return if (n == 1) s else if (n == 2) 2 * s else 4 * s;
}
/// Byte distance between the vectors of a stored matrix.
pub fn matrixStride(t: *const TypeTable, ty: TypeId, row_major: bool, rules: Rules) u32 {
const m = t.get(ty).matrix;
const mv = matrixVectors(m, row_major);
const s = scalarSize(t, ty);
return switch (rules) {
.dx_legacy, .vk_relaxed => 16,
.std430 => vectorAlign(mv.len, s),
.dx_packed => mv.len * s,
};
}
pub fn alignOf(t: *const TypeTable, ty: TypeId, row_major: bool, rules: Rules) Error!u32 {
switch (t.get(ty)) {
.scalar, .@"enum" => return scalarSize(t, ty),
.vector => |v| return switch (rules) {
.std430 => vectorAlign(v.len, scalarSize(t, ty)),
else => scalarSize(t, ty),
},
.matrix => return switch (rules) {
.dx_legacy, .vk_relaxed => 16,
.std430 => matrixStride(t, ty, row_major, rules),
.dx_packed => scalarSize(t, ty),
},
.array => |a| return switch (rules) {
.dx_legacy, .vk_relaxed => 16,
else => alignOf(t, a.elem, row_major, rules),
},
.@"struct" => |st| switch (rules) {
.dx_legacy, .vk_relaxed => return 16,
else => {
var al: u32 = 1;
for (st.fields.items) |f| al = @max(al, try alignOf(t, f.type, f.row_major, rules));
return al;
},
},
else => return error.Unsupported,
}
}
/// Size in bytes (dx_legacy does not pad the last element / member).
pub fn sizeOf(t: *const TypeTable, ty: TypeId, row_major: bool, 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);
const mv = matrixVectors(m, row_major);
const vec = mv.len * scalarSize(t, ty);
return switch (rules) {
.dx_legacy => (m.cols - 1) * 16 + col,
.vk_relaxed => m.cols * 16,
.dx_legacy => (mv.count - 1) * 16 + vec,
else => mv.count * matrixStride(t, ty, row_major, rules),
};
},
.array => |a| {
const stride = try arrayStride(t, a.elem, rules);
const stride = try arrayStride(t, a.elem, row_major, rules);
return switch (rules) {
.dx_legacy => (a.len - 1) * stride + try sizeOf(t, a.elem, rules),
.vk_relaxed => a.len * stride,
.dx_legacy => (a.len - 1) * stride + try sizeOf(t, a.elem, row_major, rules),
else => 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);
for (s.fields.items) |f| off = try place(t, off, f.type, f.row_major, rules) + try sizeOf(t, f.type, f.row_major, rules);
return switch (rules) {
.dx_legacy => off,
.dx_legacy, .dx_packed => off,
.vk_relaxed => roundUp(off, 16),
.std430 => roundUp(off, try alignOf(t, ty, false, rules)),
};
},
else => return error.Unsupported,
@ -67,59 +125,65 @@ pub fn sizeOf(t: *const TypeTable, ty: TypeId, rules: Rules) Error!u32 {
}
/// 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);
pub fn arrayStride(t: *const TypeTable, elem: TypeId, row_major: bool, rules: Rules) Error!u32 {
const size = try sizeOf(t, elem, row_major, rules);
return switch (rules) {
.dx_legacy, .vk_relaxed => roundUp(size, 16),
.std430 => roundUp(size, try alignOf(t, elem, row_major, rules)),
.dx_packed => size,
};
}
/// 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 {
pub fn place(t: *const TypeTable, off: u32, ty: TypeId, row_major: bool, 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);
const size = try sizeOf(t, ty, row_major, rules);
var o = roundUp(off, scalarSize(t, ty));
// No straddling a 16-byte boundary (except tightly packed).
if (rules != .dx_packed and o / 16 != (o + size - 1) / 16) o = roundUp(o, 16);
return o;
},
.matrix, .array, .@"struct" => return roundUp(off, 16),
.matrix, .array, .@"struct" => return roundUp(off, try alignOf(t, ty, row_major, rules)),
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 {
pub fn fieldOffsets(a: Allocator, t: *const TypeTable, info: *const types.StructInfo, rules: Rules) 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);
o.* = try place(t, off, f.type, f.row_major, rules);
off = o.* + try sizeOf(t, f.type, f.row_major, 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 {
pub fn componentOffset(a: Allocator, t: *const TypeTable, ty: TypeId, row_major: bool, k: u32, rules: Rules) 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);
const stride = matrixStride(t, ty, row_major, rules);
const s = scalarSize(t, ty);
return if (row_major) r * stride + c * s else c * stride + r * s;
},
.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);
return (k / n) * try arrayStride(t, arr.elem, row_major, rules) + try componentOffset(a, t, arr.elem, row_major, 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);
if (kk < n) return o + try componentOffset(a, t, f.type, f.row_major, kk, rules);
kk -= n;
}
return error.Unsupported;
@ -143,16 +207,29 @@ pub fn flatCount(t: *const TypeTable, ty: TypeId) Error!u32 {
};
}
test "dx legacy packing" {
test "layouts match dxc" {
var t = try TypeTable.init(std.testing.allocator);
defer t.deinit();
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
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));
try std.testing.expectEqual(@as(u32, 4), try place(&t, 4, f2, false, .dx_legacy));
try std.testing.expectEqual(@as(u32, 16), try place(&t, 12, f3, false, .dx_legacy));
try std.testing.expectEqual(@as(u32, 20), try sizeOf(&t, try t.array(f, 2), false, .dx_legacy));
try std.testing.expectEqual(@as(u32, 32), try sizeOf(&t, try t.array(f, 2), false, .vk_relaxed));
// struct S { float a; float3 b; float2 c; float d; float3 e; }
const s = try a.create(types.StructInfo);
s.* = .{ .name = "S", .complete = true };
for ([_]TypeId{ f, f3, f2, f, f3 }, 0..) |ft, i| try s.fields.append(a, .{ .name = &[_]u8{@intCast('a' + i)}, .type = ft });
const st = try t.intern(.{ .@"struct" = s });
try std.testing.expectEqualSlices(u32, &.{ 0, 4, 16, 24, 32 }, try fieldOffsets(a, &t, s, .std430));
try std.testing.expectEqual(@as(u32, 48), try sizeOf(&t, st, false, .std430));
try std.testing.expectEqualSlices(u32, &.{ 0, 4, 16, 24, 28 }, try fieldOffsets(a, &t, s, .dx_packed));
// float2x3: column-major in std430 is 3 vec2 columns (stride 8).
const m23 = try t.matrix(.float, 2, 3);
try std.testing.expectEqual(@as(u32, 24), try sizeOf(&t, m23, false, .std430));
try std.testing.expectEqual(@as(u32, 32), try sizeOf(&t, m23, true, .std430));
}

View File

@ -168,7 +168,7 @@ const Lowerer = struct {
}
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 });
for (members.items) |mv| try info.fields.append(l.arena, .{ .name = mv.name, .type = mv.type, .row_major = mv.row_major });
const ty = try l.s.types.intern(.{ .@"struct" = info });
try l.m.globals.append(l.arena, .{ .name = name, .ty = ty, .space = .cbuffer, .binding = binding });
const gi: u32 = @intCast(l.m.globals.items.len - 1);
@ -331,7 +331,14 @@ const Lowerer = struct {
const t = l.types();
const inst = l.b.f.inst(v);
if (inst.ty == target) return v;
const fs = t.shape(inst.ty) orelse return v; // objects, structs: same type
// Derived structs convert to a base: its fields are a prefix.
if (t.get(inst.ty) == .@"struct" and t.get(target) == .@"struct") {
const tf = t.get(target).@"struct".fields.items;
const parts = try l.arena.alloc(Ref, tf.len);
for (parts, tf, 0..) |*p, fld, k| p.* = try l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = @intCast(k) } }, .ty = fld.type });
return l.b.add(.{ .op = .{ .construct = parts }, .ty = target });
}
const fs = t.shape(inst.ty) orelse return v; // objects: same type
const ts = t.shape(target) orelse return v;
const tc = t.component(target).?;
// Constants convert at compile time.
@ -356,36 +363,133 @@ const Lowerer = struct {
if (ts.count() == 1 and ts.kind == .scalar) return k;
return l.b.add(.{ .op = .{ .splat = k }, .ty = target });
}
// Shape first, in the source component type.
var cur = v;
if (fs.count() == 1 and ts.count() > 1) {
const sc = if (fs.kind == .scalar) cur else try l.b.add(.{ .op = .{ .extract = .{ .agg = cur, .index = 0 } }, .ty = try t.scalar(t.component(inst.ty).?) });
const conv = try l.convert(sc, try t.scalar(tc));
return l.b.add(.{ .op = .{ .splat = conv }, .ty = target });
const sc = t.component(inst.ty).?;
// Scalar sources splat.
if (fs.count() == 1) {
const target_scalar = try t.scalar(tc);
var one = try l.component(v, 0);
if (l.b.f.inst(one).ty != target_scalar) one = try l.b.add(.{ .op = .{ .convert = one }, .ty = target_scalar });
if (ts.kind == .scalar) return one;
if (ts.count() == 1) return l.b.add(.{ .op = .{ .construct = try l.arena.dupe(Ref, &.{one}) }, .ty = target });
return l.b.add(.{ .op = .{ .splat = one }, .ty = target });
}
if (ts.kind == .scalar and fs.kind != .scalar) {
cur = try l.b.add(.{ .op = .{ .extract = .{ .agg = cur, .index = 0 } }, .ty = try t.scalar(t.component(inst.ty).?) });
} else if (ts.kind == .vector and fs.kind == .vector and ts.cols < fs.cols) {
// Truncation to a scalar keeps the first component.
if (ts.kind == .scalar) return l.convert(try l.component(v, 0), target);
// Same shape: component conversion.
if (fs.kind == ts.kind and fs.rows == ts.rows and fs.cols == ts.cols) {
if (fs.kind == .matrix) {
// Row by row (SPIR-V converts vectors, not matrices).
const rows = try l.arena.alloc(Ref, fs.rows);
const src_row = try t.vector(sc, fs.cols);
const dst_row = try t.vector(tc, fs.cols);
for (rows, 0..) |*r, i| {
const row = try l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = @intCast(i) } }, .ty = src_row });
r.* = try l.b.add(.{ .op = .{ .convert = row }, .ty = dst_row });
}
return l.flatConstruct(target, rows, fs.cols);
}
return l.b.add(.{ .op = .{ .convert = v }, .ty = target });
}
// Vector truncation keeps a shuffle.
if (fs.kind == .vector and ts.kind == .vector) {
const comps = try l.arena.alloc(u8, ts.cols);
for (comps, 0..) |*c, i| c.* = @intCast(i);
cur = try l.b.add(.{ .op = .{ .shuffle = .{ .vec = cur, .components = comps } }, .ty = try t.vector(t.component(inst.ty).?, ts.cols) });
} else if (fs.kind != ts.kind or fs.rows != ts.rows or fs.cols != ts.cols) {
if (!(fs.count() == 1 and ts.count() == 1)) {
l.unsupported(.none, "conversion from '{s}' to '{s}' is not supported yet", .{ l.s.typeName(inst.ty), l.s.typeName(target) });
const sh = try l.b.add(.{ .op = .{ .shuffle = .{ .vec = v, .components = comps } }, .ty = try t.vector(sc, ts.cols) });
return l.convert(sh, target);
}
// Other reshapes (matrix truncation, vector <-> matrix) go through
// components: matrices map (row, col) to (row, col), everything else
// flattened index to index.
const n = ts.count();
const comps = try l.arena.alloc(Ref, n);
for (comps, 0..) |*c, k| {
const src: u32 = if (fs.kind == .matrix and ts.kind == .matrix)
@intCast((k / ts.cols) * fs.cols + k % ts.cols)
else
@intCast(k);
c.* = try l.convert(try l.component(v, src), try t.scalar(tc));
}
return l.b.add(.{ .op = .{ .construct = comps }, .ty = target });
}
/// Scalar component `k` of a scalar / vector / matrix value (matrices in
/// row-major order: `extract` on a matrix yields a row).
fn component(l: *Lowerer, v: Ref, k: u32) Error!Ref {
const t = l.types();
const ty = l.b.f.inst(v).ty;
const c = t.component(ty).?;
switch (t.get(ty)) {
.scalar, .@"enum" => return v,
.vector => return l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = k } }, .ty = try t.scalar(c) }),
.matrix => |m| {
const row = try l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = k / m.cols } }, .ty = try t.vector(c, m.cols) });
return l.b.add(.{ .op = .{ .extract = .{ .agg = row, .index = k % m.cols } }, .ty = try t.scalar(c) });
},
else => return error.Unsupported,
}
}
/// A vector or matrix from its rows (`per_row` components each).
fn flatConstruct(l: *Lowerer, ty: TypeId, rows: []const Ref, per_row: u32) Error!Ref {
// Constructors take scalars: split the rows.
const t = l.types();
var comps: std.ArrayList(Ref) = .empty;
for (rows) |r| for (0..per_row) |k| try comps.append(l.arena, try l.component(r, @intCast(k)));
_ = t;
return l.b.add(.{ .op = .{ .construct = comps.items }, .ty = ty });
}
/// Appends the scalar components of `v` (structs and arrays member by
/// member).
fn flatten(l: *Lowerer, v: Ref, out: *std.ArrayList(Ref)) Error!void {
const t = l.types();
const ty = l.b.f.inst(v).ty;
switch (t.get(ty)) {
.scalar, .@"enum" => try out.append(l.arena, v),
.vector, .matrix => for (0..t.componentCount(ty).?) |k| try out.append(l.arena, try l.component(v, @intCast(k))),
.array => |a| for (0..a.len) |i| try l.flatten(try l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = @intCast(i) } }, .ty = a.elem }), out),
.@"struct" => |st| for (st.fields.items, 0..) |f, i| try l.flatten(try l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = @intCast(i) } }, .ty = f.type }), out),
else => {
l.unsupported(.none, "flattening values of type '{s}' is not supported yet", .{l.s.typeName(ty)});
return error.Unsupported;
},
}
if (fs.kind != .scalar) cur = try l.b.add(.{ .op = .{ .extract = .{ .agg = cur, .index = 0 } }, .ty = try t.scalar(t.component(inst.ty).?) });
}
const cur_ty = l.b.f.inst(cur).ty;
if (cur_ty == target) return cur;
const same_shape_target = try t.withComponent(cur_ty, tc);
if (same_shape_target != cur_ty) cur = try l.b.add(.{ .op = .{ .convert = cur }, .ty = same_shape_target });
if (same_shape_target != target) {
// float1 <-> float
if (ts.kind == .scalar) return l.b.add(.{ .op = .{ .extract = .{ .agg = cur, .index = 0 } }, .ty = target });
return l.b.add(.{ .op = .{ .construct = try l.arena.dupe(Ref, &.{cur}) }, .ty = target });
/// A value of `ty` built from flattened scalars, consumed from `next`.
fn fromFlat(l: *Lowerer, ty: TypeId, comps: []const Ref, next: *usize) Error!Ref {
const t = l.types();
switch (t.get(ty)) {
.scalar, .@"enum" => {
defer next.* += 1;
return l.convert(comps[next.*], ty);
},
.vector, .matrix => {
const n = t.componentCount(ty).?;
const sc = try t.scalar(t.component(ty).?);
const parts = try l.arena.alloc(Ref, n);
for (parts) |*p| {
p.* = try l.convert(comps[next.*], sc);
next.* += 1;
}
if (n == 1 and t.get(ty) == .vector) return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty });
return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty });
},
.array => |a| {
const parts = try l.arena.alloc(Ref, a.len);
for (parts) |*p| p.* = try l.fromFlat(a.elem, comps, next);
return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty });
},
.@"struct" => |st| {
const parts = try l.arena.alloc(Ref, st.fields.items.len);
for (parts, st.fields.items) |*p, f| p.* = try l.fromFlat(f.type, comps, next);
return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty });
},
else => {
l.unsupported(.none, "building values of type '{s}' is not supported yet", .{l.s.typeName(ty)});
return error.Unsupported;
},
}
return cur;
}
fn rvalue(l: *Lowerer, e: *ast.Expr) Error!Ref {
@ -580,42 +684,54 @@ const Lowerer = struct {
}
fn convertExplicit(l: *Lowerer, v: Ref, target: TypeId) Error!Ref {
// Explicit casts additionally allow truncation to fewer components,
// which `convert` already performs.
return l.convert(v, target);
const t = l.types();
const from = l.b.f.inst(v).ty;
if (from == target) return v;
const aggregate = switch (t.get(target)) {
.@"struct", .array => true,
else => switch (t.get(from)) {
.@"struct", .array => true,
else => false,
},
};
if (!aggregate) return l.convert(v, target);
// Aggregate casts: `(S)0` replicates a scalar; otherwise the source's
// flattened components fill the target in order.
var comps: std.ArrayList(Ref) = .empty;
try l.flatten(v, &comps);
const need = t.componentCount(target) orelse return error.Unsupported;
if (comps.items.len == 1) {
while (comps.items.len < need) try comps.append(l.arena, comps.items[0]);
}
if (comps.items.len < need) return error.Unsupported;
var next: usize = 0;
return l.fromFlat(target, comps.items, &next);
}
fn construct(l: *Lowerer, e: *ast.Expr, ty: TypeId, args: []const *ast.Expr) Error!Ref {
const t = l.types();
const comp = t.component(ty) orelse return l.fail(e, "this constructor");
const scalar_ty = try t.scalar(comp);
var comps: std.ArrayList(Ref) = .empty;
for (args) |a| {
const v = try l.rvalue(a);
const vt = l.b.f.inst(v).ty;
const n = t.componentCount(vt) orelse return l.fail(a, "this constructor argument");
if (t.get(vt) == .scalar or t.get(vt) == .@"enum") {
try comps.append(l.arena, try l.convert(v, scalar_ty));
} else {
const ec = try t.scalar(t.component(vt).?);
for (0..n) |i| {
const x = try l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = @intCast(i) } }, .ty = ec });
try comps.append(l.arena, try l.convert(x, scalar_ty));
for (args) |a| try l.flatten(try l.rvalue(a), &comps);
if (comps.items.len == 0) return l.fail(e, "this constructor");
const need = t.componentCount(ty) orelse return l.fail(e, "this constructor");
if (comps.items.len == 1 and need > 1) {
const sc = try l.convert(comps.items[0], try t.scalar(t.component(ty).?));
return l.b.add(.{ .op = .{ .splat = sc }, .ty = ty });
}
}
}
if (t.get(ty) == .scalar) return comps.items[0];
if (comps.items.len == 1) return l.b.add(.{ .op = .{ .splat = comps.items[0] }, .ty = ty });
return l.b.add(.{ .op = .{ .construct = comps.items }, .ty = ty });
var next: usize = 0;
return l.fromFlat(ty, comps.items, &next);
}
fn initList(l: *Lowerer, e: *ast.Expr, ty: TypeId) Error!Ref {
const t = l.types();
if (t.shape(ty) == null) return l.fail(e, "this initializer list");
// Flatten the list's scalars into a constructor of `ty`.
// The list's scalars, in order, fill `ty`.
var flat: std.ArrayList(*ast.Expr) = .empty;
try flattenList(l.arena, e, &flat);
return l.construct(e, ty, flat.items);
var comps: std.ArrayList(Ref) = .empty;
for (flat.items) |x| try l.flatten(try l.rvalue(x), &comps);
const need = l.types().componentCount(ty) orelse return l.fail(e, "this initializer list");
if (comps.items.len < need) return l.fail(e, "this initializer list");
var next: usize = 0;
return l.fromFlat(ty, comps.items, &next);
}
fn member(l: *Lowerer, e: *ast.Expr, base: *ast.Expr, name: []const u8) Error!Ref {
@ -633,6 +749,14 @@ const Lowerer = struct {
if (comps.len == 1) return l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = comps[0] } }, .ty = ty });
return l.b.add(.{ .op = .{ .shuffle = .{ .vec = v, .components = comps } }, .ty = ty });
},
.matrix => |m| {
const v = try l.rvalue(base);
const ks = matrixSwizzle(l.arena, name, m.cols) orelse return l.fail(e, "this matrix swizzle");
if (ks.len == 1) return l.component(v, ks[0]);
const parts = try l.arena.alloc(Ref, ks.len);
for (parts, ks) |*p, k| p.* = try l.component(v, k);
return l.b.add(.{ .op = .{ .construct = parts }, .ty = try l.concrete(e.ty) });
},
.@"struct" => {
if (isAddressable(base)) return l.b.load(try l.lvalue(e));
const v = try l.rvalue(base);
@ -771,7 +895,20 @@ const Lowerer = struct {
_ = try l.b.add(.{ .op = .{ .res_store = .{ .res = res, .index = idx, .value = value } }, .ty = TypeTable.void_type });
return;
},
.member => |m| if (t.get(m.base.ty) == .vector or t.get(m.base.ty) == .scalar) {
.member => |m| if (t.get(m.base.ty) == .matrix) {
const mt = t.get(m.base.ty).matrix;
const ks = matrixSwizzle(l.arena, m.name, mt.cols) orelse return error.Unsupported;
var whole = try l.rvalue(m.base);
const row_ty = try t.vector(mt.elem, mt.cols);
for (ks, 0..) |k, i| {
const part = if (ks.len == 1) value else try l.component(value, @intCast(i));
const r = k / mt.cols;
const row = try l.b.add(.{ .op = .{ .extract = .{ .agg = whole, .index = r } }, .ty = row_ty });
const new_row = try l.b.add(.{ .op = .{ .insert = .{ .agg = row, .value = part, .index = k % mt.cols } }, .ty = row_ty });
whole = try l.b.add(.{ .op = .{ .insert = .{ .agg = whole, .value = new_row, .index = r } }, .ty = m.base.ty });
}
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;
if (t.get(m.base.ty) == .scalar) return l.storeTo(m.base, value);
@ -785,12 +922,99 @@ const Lowerer = struct {
},
else => {},
}
if (lhs.kind == .cast and t.get(lhs.ty) == .@"struct" and lhs.ty != lhs.kind.cast.operand.ty) {
// `(Base)derived = v`: the base's fields are a prefix.
const base_ptr = try l.lvalue(lhs.kind.cast.operand);
const space = l.b.f.inst(base_ptr).ptr;
for (t.get(lhs.ty).@"struct".fields.items, 0..) |fld, k| {
const idx = try l.b.constInt(try t.scalar(.uint), @intCast(k));
const p = try l.b.add(.{ .op = .{ .access = .{ .base = base_ptr, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = fld.type, .ptr = space });
try l.b.store(p, try l.b.add(.{ .op = .{ .extract = .{ .agg = value, .index = @intCast(k) } }, .ty = fld.type }));
}
return;
}
try l.b.store(try l.lvalue(lhs), value);
}
// ------------------------------------------------------------------
// Entry point
/// An entry input of type `ty`: one signature element, or for structs
/// without a semantic one per field (recursively).
fn entryInput(l: *Lowerer, entry: *ir.Entry, ty: TypeId, semantic: ?[]const u8, loc: ast.Loc, what: []const u8) Error!Ref {
if (semantic) |sem| if (l.s.types.get(ty) == .@"struct") {
// A semantic on a struct numbers its fields: X, X1, X2, ...
var el = sigElement(sem, ty);
return l.structInput(entry, ty, el.semantic, &el.semantic_index);
};
if (semantic) |sem| {
try entry.inputs.append(l.arena, sigElement(sem, ty));
return l.b.add(.{ .op = .{ .input = @intCast(entry.inputs.items.len - 1) }, .ty = ty });
}
switch (l.s.types.get(ty)) {
.@"struct" => |st| {
const parts = try l.arena.alloc(Ref, st.fields.items.len);
for (parts, st.fields.items) |*p, fld| p.* = try l.entryInput(entry, fld.type, fld.semantic, loc, fld.name);
return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty });
},
else => {
l.unsupported(loc, "entry parameter '{s}' needs a semantic", .{what});
return error.Unsupported;
},
}
}
fn structInput(l: *Lowerer, entry: *ir.Entry, ty: TypeId, name: []const u8, index: *u32) Error!Ref {
const st = l.s.types.get(ty).@"struct";
const parts = try l.arena.alloc(Ref, st.fields.items.len);
for (parts, st.fields.items) |*p, fld| {
if (l.s.types.get(fld.type) == .@"struct") {
p.* = try l.structInput(entry, fld.type, name, index);
continue;
}
try entry.inputs.append(l.arena, .{ .semantic = name, .semantic_index = index.*, .ty = fld.type, .system_value = std.ascii.startsWithIgnoreCase(name, "SV_") });
index.* += 1;
p.* = try l.b.add(.{ .op = .{ .input = @intCast(entry.inputs.items.len - 1) }, .ty = fld.type });
}
return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty });
}
fn structOutput(l: *Lowerer, entry: *ir.Entry, ty: TypeId, name: []const u8, index: *u32, value: Ref) Error!void {
const st = l.s.types.get(ty).@"struct";
for (st.fields.items, 0..) |fld, k| {
const v = try l.b.add(.{ .op = .{ .extract = .{ .agg = value, .index = @intCast(k) } }, .ty = fld.type });
if (l.s.types.get(fld.type) == .@"struct") {
try l.structOutput(entry, fld.type, name, index, v);
continue;
}
try entry.outputs.append(l.arena, .{ .semantic = name, .semantic_index = index.*, .ty = fld.type, .system_value = std.ascii.startsWithIgnoreCase(name, "SV_") });
index.* += 1;
_ = try l.b.add(.{ .op = .{ .output = .{ .element = @intCast(entry.outputs.items.len - 1), .value = v } }, .ty = TypeTable.void_type });
}
}
fn entryOutput(l: *Lowerer, entry: *ir.Entry, ty: TypeId, semantic: ?[]const u8, value: Ref, loc: ast.Loc, what: []const u8) Error!void {
if (semantic) |sem| if (l.s.types.get(ty) == .@"struct") {
var el = sigElement(sem, ty);
return l.structOutput(entry, ty, el.semantic, &el.semantic_index, value);
};
if (semantic) |sem| {
try entry.outputs.append(l.arena, sigElement(sem, ty));
_ = try l.b.add(.{ .op = .{ .output = .{ .element = @intCast(entry.outputs.items.len - 1), .value = value } }, .ty = TypeTable.void_type });
return;
}
switch (l.s.types.get(ty)) {
.@"struct" => |st| for (st.fields.items, 0..) |fld, k| {
const v = try l.b.add(.{ .op = .{ .extract = .{ .agg = value, .index = @intCast(k) } }, .ty = fld.type });
try l.entryOutput(entry, fld.type, fld.semantic, v, loc, fld.name);
},
else => {
l.unsupported(loc, "entry {s} needs a semantic", .{what});
return error.Unsupported;
},
}
}
fn buildEntry(l: *Lowerer, f: *const semamod.Function, main: u32, opts: Options) Error!void {
var entry: ir.Entry = .{ .func = main, .name = opts.entry, .stage = opts.stage };
for (f.decl.attrs) |a| {
@ -804,32 +1028,19 @@ const Lowerer = struct {
const args = try l.arena.alloc(Ref, f.params.len);
const locals = try l.arena.alloc(Ref, f.params.len);
for (f.decl.params, f.params, 0..) |pd, p, i| {
const sem = semanticOf(pd.semantics) orelse {
l.unsupported(pd.name_loc, "entry parameter '{s}' needs a semantic", .{pd.name});
return error.Unsupported;
};
locals[i] = try l.b.add(.{ .op = .local_var, .ty = p.type, .ptr = .function });
if (p.dir != .out) {
try entry.inputs.append(l.arena, sigElement(sem, p.type));
const v = try l.b.add(.{ .op = .{ .input = @intCast(entry.inputs.items.len - 1) }, .ty = p.type });
const v = try l.entryInput(&entry, p.type, semanticOf(pd.semantics), pd.name_loc, pd.name);
try l.b.store(locals[i], v);
}
args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i];
}
const ret = try l.b.add(.{ .op = .{ .call = .{ .func = main, .args = args } }, .ty = f.ret });
if (f.ret != TypeTable.void_type) {
const sem = semanticOf(f.decl.ret_semantics) orelse {
l.unsupported(f.loc, "entry return value needs a semantic", .{});
return error.Unsupported;
};
try entry.outputs.append(l.arena, sigElement(sem, f.ret));
_ = try l.b.add(.{ .op = .{ .output = .{ .element = @intCast(entry.outputs.items.len - 1), .value = ret } }, .ty = TypeTable.void_type });
}
if (f.ret != TypeTable.void_type) try l.entryOutput(&entry, f.ret, semanticOf(f.decl.ret_semantics), ret, f.loc, "return value");
for (f.decl.params, f.params, 0..) |pd, p, i| {
if (p.dir == .in) continue;
try entry.outputs.append(l.arena, sigElement(semanticOf(pd.semantics).?, p.type));
const v = try l.b.load(locals[i]);
_ = try l.b.add(.{ .op = .{ .output = .{ .element = @intCast(entry.outputs.items.len - 1), .value = v } }, .ty = TypeTable.void_type });
try l.entryOutput(&entry, p.type, semanticOf(pd.semantics), v, pd.name_loc, pd.name);
}
l.b.terminate(.{ .ret = .none });
entry.wrapper = wrapper;
@ -903,6 +1114,33 @@ fn swizzleComponents(name: []const u8) ?[]const u8 {
return out[0..name.len];
}
/// `_m01_m10` (zero-based) or `_12_21` (one-based) -> row-major component
/// indices.
fn matrixSwizzle(a: Allocator, name: []const u8, cols: u8) ?[]const u32 {
var out: std.ArrayList(u32) = .empty;
var i: usize = 0;
while (i < name.len) {
if (name[i] != '_') return null;
i += 1;
var zero = false;
if (i < name.len and name[i] == 'm') {
zero = true;
i += 1;
}
if (i + 2 > name.len) return null;
var r: u32 = name[i] -% '0';
var c: u32 = name[i + 1] -% '0';
if (!zero) {
r -%= 1;
c -%= 1;
}
if (r > 3 or c > 3) return null;
out.append(a, r * cols + c) catch return null;
i += 2;
}
return if (out.items.len == 0) null else out.items;
}
fn isAddressable(e: *const ast.Expr) bool {
return switch (e.kind) {
.name => true,

View File

@ -53,6 +53,8 @@ pub const Variable = struct {
param_index: u32 = 0,
/// The `cbuffer` / `tbuffer` declaration holding the variable.
block: ?*const ast.Decl = null,
/// Matrices in the variable are row_major (layout only).
row_major: bool = false,
};
/// What an expression refers to, recorded by Sema for lowering
@ -956,12 +958,16 @@ pub const Sema = struct {
s.err(start, "array dimensions of struct/class members must be explicit", .{});
continue;
}
_ = s.checkModifiers(.field, v.qual_words, start, fbase, s.last_attrs);
const fattrs = s.checkModifiers(.field, v.qual_words, start, fbase, s.last_attrs);
const ft = try s.applyArrayDims(fbase, v.array_dims);
s.checkSemantics(.field, v.semantics, ft, false);
if (s.types.get(fbase) == .string) s.err(v.name_loc, "string declaration may only appear in global scope", .{});
for (info.fields.items[base_fields..]) |f| if (std.mem.eql(u8, f.name, v.name)) s.err(v.name_loc, "duplicate member '{s}'", .{v.name});
try info.fields.append(s.arena, .{ .name = v.name, .type = ft });
var fsem: ?[]const u8 = null;
for (v.semantics) |sem| if (sem.kind == .semantic) {
fsem = sem.values[0];
};
try info.fields.append(s.arena, .{ .name = v.name, .type = ft, .row_major = isRowMajor(fattrs), .semantic = fsem });
},
.func => {},
else => try s.decl(m, .member),
@ -1308,7 +1314,7 @@ pub const Sema = struct {
if (std.mem.indexOf(u8, v.name, "::") != null) return; // out-of-line static member definition
const is_auto = v.type.name.isSimple("auto");
const base = if (is_auto) TypeTable.error_type else try s.resolveType(v.type);
_ = s.checkModifiers(switch (ctx) {
const decl_attrs = s.checkModifiers(switch (ctx) {
.local => .local_variable,
.member => .field,
.global, .cbuffer => .global_variable,
@ -1355,6 +1361,7 @@ pub const Sema = struct {
.read_only = read_only,
.init = v.init,
.decl = v,
.row_major = isRowMajor(decl_attrs),
};
try s.declare(v.name, .{ .variable = variable }, v.name_loc);
try s.decl_vars.put(s.arena, v, variable);
@ -2869,6 +2876,10 @@ fn templateArgLoc(arg: ast.TemplateArg) Loc {
};
}
fn isRowMajor(a: TypeAttrs) bool {
return if (a.orientation) |o| eql(o, "row_major") else false;
}
fn eql(a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}

View File

@ -315,6 +315,10 @@ pub const ResourceKind = enum(u8) {
pub const Field = struct {
name: []const u8,
type: TypeId,
/// Matrices in the field are row_major (layout only).
row_major: bool = false,
/// The field's semantic (`float4 pos : SV_Position;`).
semantic: ?[]const u8 = null,
};
/// A struct's layout-relevant information. Methods live in Sema.

View File

@ -54,6 +54,7 @@ pub const Op = enum(u16) {
composite_construct = 80,
composite_extract = 81,
composite_insert = 82,
transpose = 84,
sampled_image = 86,
image_sample_implicit_lod = 87,
image_sample_explicit_lod = 88,

View File

@ -43,8 +43,11 @@ 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,
/// Explicitly laid out variants of arrays and structs (buffers).
layout_types: std.AutoHashMapUnmanaged(LayoutKey, Id) = .empty,
/// Per instruction (current function): the buffer layout its pointer
/// result points into, if any.
ptr_layouts: []?PtrLayout = &.{},
pointer_types: std.AutoHashMapUnmanaged(struct { StorageClass, Id }, Id) = .empty,
function_types: std.StringHashMapUnmanaged(Id) = .empty,
constants: std.AutoHashMapUnmanaged(struct { Id, u64 }, Id) = .empty,
@ -67,6 +70,8 @@ const Emitter = struct {
f: *const ir.Function = undefined,
const Interface = struct { var_id: Id, ty: TypeId };
const LayoutKey = struct { TypeId, layout.Rules, bool };
const PtrLayout = struct { rules: layout.Rules, row_major: bool };
fn unsupported(e: *Emitter, comptime fmt: []const u8, args: anytype) Error {
_ = e.diags.report(.{ .severity = .@"error", .loc = .none }, "SPIR-V code generation: " ++ fmt, args);
@ -135,6 +140,7 @@ const Emitter = struct {
.vector => |v| blk: {
// vector<T, 1> is a plain T (SPIR-V has no 1-vectors).
if (v.len == 1) break :blk try e.scalarType(v.elem);
if (storageScalar(v.elem) != v.elem) break :blk try e.typeId(try e.t.vector(storageScalar(v.elem), v.len));
const elem = try e.scalarType(v.elem);
const id = e.b.newId();
try e.b.emit(.types_globals, .type_vector, &.{ id, elem, v.len });
@ -147,43 +153,161 @@ const Emitter = struct {
try e.b.emit(.types_globals, .type_array, &.{ id, elem, len });
break :blk id;
},
// HLSL rows are SPIR-V columns (as in dxc): floatRxC is R
// columns of vecC. Non-float matrices are arrays of vectors;
// 1xN and Nx1 matrices are vectors, 1x1 a scalar.
.matrix => |mt| blk: {
if (mt.rows == 1 or mt.cols == 1) break :blk try e.typeId(try e.t.vector(mt.elem, mt.rows * mt.cols));
if (storageScalar(mt.elem) != mt.elem) break :blk try e.typeId(try e.t.matrix(storageScalar(mt.elem), mt.rows, mt.cols));
const row_id = try e.typeId(try e.t.vector(mt.elem, mt.cols));
const id = e.b.newId();
if (storageScalar(mt.elem).isFloat()) {
try e.b.emit(.types_globals, .type_matrix, &.{ id, row_id, mt.rows });
} else try e.b.emit(.types_globals, .type_array, &.{ id, row_id, try e.constUint(mt.rows) });
break :blk id;
},
.@"struct" => |st| blk: {
const members = try e.arena.alloc(u32, st.fields.items.len);
for (st.fields.items, members) |fld, *mid| mid.* = try e.typeId(fld.type);
const id = e.b.newId();
var ops: std.ArrayList(u32) = .empty;
try ops.append(e.arena, id);
try ops.appendSlice(e.arena, members);
try e.b.emit(.types_globals, .type_struct, ops.items);
try e.b.emitWithString(.debug_names, .name, &.{id}, try std.fmt.allocPrint(e.arena, "struct.{s}", .{st.name}), &.{});
for (st.fields.items, 0..) |fld, k| try e.b.emitWithString(.debug_names, .member_name, &.{ id, @intCast(k) }, fld.name, &.{});
break :blk id;
},
else => return e.unsupported("type '{s}' is not supported yet", .{try e.t.format(e.arena, ty)}),
};
try e.value_types.put(e.arena, ty, id);
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 {
/// `ty` laid out for a buffer (`rules`): arrays carry ArrayStride,
/// structs member Offsets and matrix decorations; scalars, vectors and
/// float matrices are the plain types (bools become uints).
fn layoutTypeId(e: *Emitter, ty: TypeId, rules: layout.Rules, row_major: bool) 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),
.matrix => |m| {
const fl = storageScalar(m.elem).isFloat();
if (m.rows == 1 or m.cols == 1) {
// A SPIR-V vector: contiguous only if the stored vectors
// are the whole matrix or single components packed tight.
const vectors: u32 = if (row_major) m.rows else m.cols;
if (vectors > 1 and layout.matrixStride(e.t, ty, row_major, rules) != storageScalar(m.elem).size()) {
return e.unsupported("this 1xN / Nx1 matrix layout is not supported yet", .{});
}
return e.typeId(ty);
}
if (fl) return e.typeId(ty);
if (!row_major) return e.unsupported("column-major integer matrices in buffers are not supported yet", .{});
},
else => {},
}
if (e.layout_types.get(ty)) |id| return id;
const key: LayoutKey = .{ ty, rules, row_major };
if (e.layout_types.get(key)) |id| return id;
const id = e.b.newId();
switch (e.t.get(ty)) {
.matrix => |m| {
// Row-major integer matrix: an array of its rows.
const row_ty = try e.layoutTypeId(try e.t.vector(m.elem, m.cols), rules, false);
try e.b.emit(.types_globals, .type_array, &.{ id, row_ty, try e.constUint(m.rows) });
try e.b.emit(.annotations, .decorate, &.{ id, 6, layout.matrixStride(e.t, ty, true, rules) }); // ArrayStride
},
.array => |a| {
const elem = try e.layoutTypeId(a.elem);
const elem = try e.layoutTypeId(a.elem, rules, row_major);
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", .{});
const stride = layout.arrayStride(e.t, a.elem, row_major, rules) catch return e.unsupported("buffer member type", .{});
try e.b.emit(.annotations, .decorate, &.{ id, 6, stride }); // ArrayStride
},
.@"struct" => |s| {
.@"struct" => |st| {
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));
for (st.fields.items) |fld| try ops.append(e.arena, try e.layoutTypeId(fld.type, rules, fld.row_major));
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, &.{});
const offs = layout.fieldOffsets(e.arena, e.t, st, rules) catch return e.unsupported("buffer member type '{s}'", .{st.name});
for (st.fields.items, offs, 0..) |fld, o, k| {
const mk: u32 = @intCast(k);
try e.b.emit(.annotations, .member_decorate, &.{ id, mk, 35, o }); // Offset
// Float matrices (possibly in arrays): HLSL rows are
// SPIR-V columns, so column_major is RowMajor.
var inner = fld.type;
while (e.t.get(inner) == .array) inner = e.t.get(inner).array.elem;
if (e.isTrueMatrix(inner) and storageScalar(e.t.get(inner).matrix.elem).isFloat()) {
try e.b.emit(.annotations, .member_decorate, &.{ id, mk, 7, layout.matrixStride(e.t, inner, fld.row_major, rules) }); // MatrixStride
try e.b.emit(.annotations, .member_decorate, &.{ id, mk, if (fld.row_major) 5 else 4 }); // ColMajor / RowMajor
}
try e.b.emitWithString(.debug_names, .member_name, &.{ id, mk }, fld.name, &.{});
}
try e.b.emitWithString(.debug_names, .name, &.{id}, st.name, &.{});
},
else => return e.unsupported("constant buffer members of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
else => return e.unsupported("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);
try e.layout_types.put(e.arena, key, id);
return id;
}
/// A value loaded with a buffer layout, as the plain type.
fn fromLayout(e: *Emitter, v: Id, ty: TypeId, rules: layout.Rules, row_major: bool) Error!Id {
return e.relayout(v, ty, rules, row_major, true);
}
fn toLayout(e: *Emitter, v: Id, ty: TypeId, rules: layout.Rules, row_major: bool) Error!Id {
return e.relayout(v, ty, rules, row_major, false);
}
fn relayout(e: *Emitter, v: Id, ty: TypeId, rules: layout.Rules, row_major: bool, from: bool) Error!Id {
const lt = try e.layoutTypeId(ty, rules, row_major);
const pt = try e.typeId(ty);
switch (e.t.get(ty)) {
.scalar, .vector, .@"enum" => {
if (e.t.component(ty) != .bool) return v;
const stored = try e.t.withComponent(ty, .uint);
return if (from) e.convert(v, stored, ty) else e.convert(v, ty, stored);
},
.matrix => |m| {
if (lt == pt) return v;
// Row-major integer matrix <-> array of rows.
const rows = try e.arena.alloc(u32, m.rows);
const row_ty = try e.t.vector(m.elem, m.cols);
const src_row = if (from) try e.layoutTypeId(row_ty, rules, false) else try e.typeId(row_ty);
for (rows, 0..) |*rw, k| {
const el = try e.opRaw(.composite_extract, src_row, &.{ v, @intCast(k) });
rw.* = try e.relayout(el, row_ty, rules, false, from);
}
return e.opRaw(.composite_construct, if (from) pt else lt, rows);
},
.array => |a| {
if (lt == pt) return v;
const parts = try e.arena.alloc(u32, a.len);
const src_el = if (from) try e.layoutTypeId(a.elem, rules, row_major) else try e.typeId(a.elem);
for (parts, 0..) |*p, k| {
const el = try e.opRaw(.composite_extract, src_el, &.{ v, @intCast(k) });
p.* = try e.relayout(el, a.elem, rules, row_major, from);
}
return e.opRaw(.composite_construct, if (from) pt else lt, parts);
},
.@"struct" => |st| {
const parts = try e.arena.alloc(u32, st.fields.items.len);
for (st.fields.items, parts, 0..) |fld, *p, k| {
const src_el = if (from) try e.layoutTypeId(fld.type, rules, fld.row_major) else try e.typeId(fld.type);
const el = try e.opRaw(.composite_extract, src_el, &.{ v, @intCast(k) });
p.* = try e.relayout(el, fld.type, rules, fld.row_major, from);
}
return e.opRaw(.composite_construct, if (from) pt else lt, parts);
},
else => return e.unsupported("buffer values of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
}
}
fn opRaw(e: *Emitter, op: Op, ty_id: Id, operands: []const u32) Error!Id {
const id = e.b.newId();
var ops: std.ArrayList(u32) = .empty;
try ops.appendSlice(e.arena, &.{ ty_id, id });
try ops.appendSlice(e.arena, operands);
try e.b.emit(.functions, op, ops.items);
return id;
}
@ -330,14 +454,13 @@ const Emitter = struct {
const var_id = e.b.newId();
switch (r.kind) {
.structured_buffer, .rw_structured_buffer, .byte_address_buffer, .rw_byte_address_buffer => {
var elem_ty = if (r.kind == .byte_address_buffer or r.kind == .rw_byte_address_buffer) try e.t.scalar(.uint) else r.elem;
// 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 elem_layout = try e.std430(elem_ty);
const elem_ty = if (r.kind == .byte_address_buffer or r.kind == .rw_byte_address_buffer) try e.t.scalar(.uint) else r.elem;
if (e.isTrueMatrix(elem_ty)) return e.unsupported("buffers of matrices are not supported yet", .{});
const elem = try e.layoutTypeId(elem_ty, .std430, false);
const stride = layout.arrayStride(e.t, elem_ty, false, .std430) catch return e.unsupported("buffer element type '{s}'", .{try e.t.format(e.arena, 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, elem_layout.size }); // ArrayStride
try e.b.emit(.annotations, .decorate, &.{ rt, 6, stride }); // 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
@ -362,7 +485,7 @@ const Emitter = struct {
e.global_vars[gi] = var_id;
},
.cbuffer => {
const st = try e.layoutTypeId(g.ty);
const st = try e.layoutTypeId(g.ty, .vk_relaxed, false);
try e.b.emit(.annotations, .decorate, &.{ st, 2 }); // Block
const ptr = try e.pointerType(.uniform, st);
const var_id = e.b.newId();
@ -402,20 +525,6 @@ const Emitter = struct {
};
}
const Layout = struct { size: u32, alignment: u32 };
fn std430(e: *Emitter, ty: TypeId) Error!Layout {
return switch (e.t.get(ty)) {
.scalar => |s| .{ .size = storageScalar(s).size(), .alignment = storageScalar(s).size() },
.vector => |v| blk: {
const s = storageScalar(v.elem).size();
const n: u32 = if (v.len == 3) 4 else v.len;
break :blk .{ .size = s * v.len, .alignment = s * n };
},
else => e.unsupported("buffer elements of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
};
}
// ------------------------------------------------------------------
// Entry interface
@ -503,6 +612,8 @@ const Emitter = struct {
e.f = f;
e.vals = try e.arena.alloc(Id, f.insts.items.len);
@memset(e.vals, 0);
e.ptr_layouts = try e.arena.alloc(?PtrLayout, f.insts.items.len);
@memset(e.ptr_layouts, null);
const ret = try e.typeId(f.ret);
const params = try e.arena.alloc(Id, f.params.len);
for (f.params, params) |p, *out| {
@ -563,15 +674,105 @@ const Emitter = struct {
try e.b.emit(.functions, .function_end, &.{});
}
/// Scalars and 1-component vectors (both a SPIR-V scalar).
/// Scalars, 1-vectors and 1x1 matrices (all a SPIR-V scalar).
fn isScalarLike(e: *Emitter, ty: TypeId) bool {
return switch (e.t.get(ty)) {
.scalar, .@"enum" => true,
.vector => |v| v.len == 1,
.matrix => |m| m.rows == 1 and m.cols == 1,
else => false,
};
}
/// A matrix represented as a SPIR-V matrix (or array of vectors), not
/// as a vector or scalar.
fn isTrueMatrix(e: *Emitter, ty: TypeId) bool {
return switch (e.t.get(ty)) {
.matrix => |m| m.rows > 1 and m.cols > 1,
else => false,
};
}
fn row(e: *Emitter, m: Id, row_ty: TypeId, k: u32) Error!Id {
return e.op1(.composite_extract, row_ty, &.{ m, k });
}
/// Scalar component (r, c) of a value viewed as a matrix: vectors are a
/// row (`as_column` false) or a column.
fn elementAt(e: *Emitter, v: Id, ty: TypeId, r: u32, c: u32) Error!Id {
const sc = try e.t.scalar(e.t.component(ty).?);
switch (e.t.get(ty)) {
.scalar, .@"enum" => return v,
.vector => |vec| {
if (vec.len == 1) return v;
return e.op1(.composite_extract, sc, &.{ v, r + c });
},
.matrix => |m| {
if (m.rows == 1 and m.cols == 1) return v;
if (m.rows == 1) return e.op1(.composite_extract, sc, &.{ v, c });
if (m.cols == 1) return e.op1(.composite_extract, sc, &.{ v, r });
return e.op1(.composite_extract, sc, &.{ v, r, c });
},
else => return e.unsupported("matrix element of this type", .{}),
}
}
/// Builds a value of numeric type `ty` from row-major scalars.
fn fromScalars(e: *Emitter, ty: TypeId, comps: []const Id) Error!Id {
if (e.isScalarLike(ty)) return comps[0];
if (!e.isTrueMatrix(ty)) return e.op1(.composite_construct, ty, comps);
const m = e.t.get(ty).matrix;
const rt = try e.t.vector(m.elem, m.cols);
const rows = try e.arena.alloc(u32, m.rows);
for (rows, 0..) |*rw, k| rw.* = try e.op1(.composite_construct, rt, comps[k * m.cols ..][0..m.cols]);
return e.op1(.composite_construct, ty, rows);
}
/// HLSL mul(a, b): vectors on the left are rows, on the right columns.
fn mul(e: *Emitter, ty: TypeId, at: TypeId, bt: TypeId, a: Id, b: Id) Error!Id {
const t = e.t;
const as = t.shape(at).?;
const bs = t.shape(bt).?;
const fl = e.compOf(ty).isFloat();
if (as.count() == 1 or bs.count() == 1) {
// Scalar times anything: component-wise.
if (e.isTrueMatrix(ty) and fl) return e.op1(.matrix_times_scalar, ty, &.{ if (as.count() == 1) b else a, if (as.count() == 1) a else b });
const n = t.componentCount(ty).?;
const comps = try e.arena.alloc(Id, n);
const s = if (as.count() == 1) try e.elementAt(a, at, 0, 0) else try e.elementAt(b, bt, 0, 0);
const other = if (as.count() == 1) b else a;
const ot = if (as.count() == 1) bt else at;
const sc = try t.scalar(e.t.component(ty).?);
for (comps, 0..) |*c, k| {
const os = t.shape(ot).?;
const x = try e.elementAt(other, ot, @intCast(k / os.cols), @intCast(k % os.cols));
c.* = try e.binary(.mul, sc, x, s);
}
return e.fromScalars(ty, comps);
}
// Logical dimensions: a is (ar x k), b is (k x bc).
const ar: u32 = if (as.kind == .vector) 1 else as.rows;
const ak: u32 = if (as.kind == .vector) as.cols else as.cols;
const bc: u32 = if (bs.kind == .vector) 1 else bs.cols;
if (fl and e.isTrueMatrix(at) and bs.kind == .vector) return e.op1(.vector_times_matrix, ty, &.{ b, a });
if (fl and as.kind == .vector and e.isTrueMatrix(bt)) return e.op1(.matrix_times_vector, ty, &.{ b, a });
if (fl and e.isTrueMatrix(at) and e.isTrueMatrix(bt) and e.isTrueMatrix(ty)) return e.op1(.matrix_times_matrix, ty, &.{ b, a });
if (fl and as.kind == .vector and bs.kind == .vector) return e.op1(.dot, ty, &.{ a, b });
const sc = try t.scalar(e.t.component(ty).?);
const comps = try e.arena.alloc(Id, ar * bc);
for (0..ar) |i| for (0..bc) |j| {
var acc: ?Id = null;
for (0..ak) |kk| {
const x = try e.elementAt(a, at, @intCast(i), @intCast(kk));
const y = if (bs.kind == .vector) try e.elementAt(b, bt, 0, @intCast(kk)) else try e.elementAt(b, bt, @intCast(kk), @intCast(j));
const p = try e.binary(.mul, sc, x, y);
acc = if (acc) |s0| try e.binary(.add, sc, s0, p) else p;
}
comps[i * bc + j] = acc.?;
};
return e.fromScalars(ty, comps);
}
fn val(e: *Emitter, r: Ref) Id {
return e.vals[r.index()];
}
@ -586,52 +787,77 @@ const Emitter = struct {
const ri = r.index();
switch (i.op) {
.constant, .param, .local_var => {},
.global => |g| e.vals[ri] = e.global_vars[g],
.global => |g| {
e.vals[ri] = e.global_vars[g];
e.ptr_layouts[ri] = switch (e.m.globals.items[g].space) {
.cbuffer => .{ .rules = .vk_relaxed, .row_major = false },
.resource => .{ .rules = .std430, .row_major = false },
else => null,
};
},
.load => |p| {
// Resources stay as their variables (accessed by chains).
if (i.ptr == .none and (e.t.get(i.ty) == .resource or e.t.get(i.ty) == .sampler)) {
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);
if (e.ptr_layouts[p.index()]) |pl| {
const raw = try e.opRaw(.load, try e.layoutTypeId(i.ty, pl.rules, pl.row_major), &.{e.val(p)});
e.vals[ri] = try e.fromLayout(raw, i.ty, pl.rules, pl.row_major);
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) }),
.store => |s| {
if (e.ptr_layouts[s.ptr.index()]) |pl| {
const v = try e.toLayout(e.val(s.value), f.inst(s.value).ty, pl.rules, pl.row_major);
try e.b.emit(.functions, .store, &.{ e.val(s.ptr), v });
return;
}
try e.b.emit(.functions, .store, &.{ e.val(s.ptr), e.val(s.value) });
},
.access => |a| {
const sc: StorageClass = switch (i.ptr) {
.function => .function,
.private => .private,
.groupshared => .workgroup,
.cbuffer => .uniform,
.cbuffer, .resource => .uniform,
else => return e.unsupported("access into this storage is not supported yet", .{}),
};
const ptr_ty = try e.pointerType(sc, if (i.ptr == .cbuffer) try e.layoutTypeId(i.ty) else try e.typeId(i.ty));
var pl = e.ptr_layouts[a.base.index()];
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.
try ops.appendSlice(e.arena, &.{ 0, 0, e.val(a.base) });
var cur = f.inst(a.base).ty;
for (a.indices) |x| {
const skip = e.isScalarLike(cur);
var indices = a.indices;
if (e.t.get(cur) == .resource) {
// buffer[i]...: member 0 (the runtime array), element i.
const rk = e.t.get(cur).resource;
if (e.buffer_elem_ptr[e.globalOf(a.base) orelse return e.unsupported("resources not tied to a global", .{})] == 0) return e.unsupported("indexing this resource is not supported yet", .{});
try ops.appendSlice(e.arena, &.{ try e.constInt(0), e.val(indices[0]) });
cur = if (rk.kind == .byte_address_buffer or rk.kind == .rw_byte_address_buffer) try e.t.scalar(.uint) else rk.elem;
indices = indices[1..];
}
// Indices into 1-vectors (SPIR-V scalars) are dropped.
for (indices) |x| {
// Row 0 of a 1xN matrix (a SPIR-V vector) is the whole value.
const skip = e.isScalarLike(cur) or (e.t.get(cur) == .matrix and e.t.get(cur).matrix.rows == 1);
cur = switch (e.t.get(cur)) {
.array => |arr| arr.elem,
.vector => |v| try e.t.scalar(v.elem),
.matrix => |mt| try e.t.vector(mt.elem, mt.cols),
.@"struct" => |st| blk: {
const k = f.inst(x);
break :blk if (k.op == .constant) st.fields.items[@intCast(k.op.constant.int)].type else cur;
if (k.op != .constant) break :blk cur;
const fld = st.fields.items[@intCast(k.op.constant.int)];
if (pl) |*p| p.row_major = fld.row_major;
break :blk fld.type;
},
else => cur,
};
if (!skip) try ops.append(e.arena, e.val(x));
}
e.ptr_layouts[ri] = pl;
ops.items[0] = try e.pointerType(sc, if (pl) |p| try e.layoutTypeId(i.ty, p.rules, p.row_major) else try e.typeId(i.ty));
if (ops.items.len == 3) {
e.vals[ri] = e.val(a.base);
return;
@ -640,8 +866,33 @@ const Emitter = struct {
ops.items[1] = e.vals[ri];
try e.b.emit(.functions, .access_chain, ops.items);
},
.binary => |x| e.vals[ri] = try e.binary(x.op, i.ty, e.val(x.lhs), e.val(x.rhs)),
.binary => |x| {
if (e.isTrueMatrix(i.ty)) {
const m = e.t.get(i.ty).matrix;
const rt = try e.t.vector(m.elem, m.cols);
const rows = try e.arena.alloc(u32, m.rows);
for (rows, 0..) |*rw, k| rw.* = try e.binary(x.op, rt, try e.row(e.val(x.lhs), rt, @intCast(k)), try e.row(e.val(x.rhs), rt, @intCast(k)));
e.vals[ri] = try e.op1(.composite_construct, i.ty, rows);
return;
}
e.vals[ri] = try e.binary(x.op, i.ty, e.val(x.lhs), e.val(x.rhs));
},
.unary => |x| {
if (e.isTrueMatrix(i.ty)) {
const m = e.t.get(i.ty).matrix;
const rt = try e.t.vector(m.elem, m.cols);
const neg = try e.t.withComponent(rt, m.elem);
const rows = try e.arena.alloc(u32, m.rows);
const c = e.compOf(i.ty);
const op: Op = switch (x.op) {
.neg => if (c.isFloat()) .f_negate else .s_negate,
.not => .logical_not,
.bit_not => .not_,
};
for (rows, 0..) |*rw, k| rw.* = try e.op1(op, neg, &.{try e.row(e.val(x.operand), rt, @intCast(k))});
e.vals[ri] = try e.op1(.composite_construct, i.ty, rows);
return;
}
const c = e.compOf(i.ty);
const op: Op = switch (x.op) {
.neg => if (c.isFloat()) .f_negate else .s_negate,
@ -678,12 +929,32 @@ const Emitter = struct {
.gt => .s_greater_than,
.ge => .s_greater_than_equal,
};
const lt = f.inst(x.lhs).ty;
if (e.isTrueMatrix(lt)) {
const m = e.t.get(lt).matrix;
const rt = try e.t.vector(m.elem, m.cols);
const bt = try e.t.vector(.bool, m.cols);
const rows = try e.arena.alloc(u32, m.rows);
for (rows, 0..) |*rw, k| rw.* = try e.op1(op, bt, &.{ try e.row(e.val(x.lhs), rt, @intCast(k)), try e.row(e.val(x.rhs), rt, @intCast(k)) });
e.vals[ri] = try e.op1(.composite_construct, i.ty, rows);
return;
}
e.vals[ri] = try e.op1(op, i.ty, &.{ e.val(x.lhs), e.val(x.rhs) });
},
.convert => |x| e.vals[ri] = try e.convert(e.val(x), f.inst(x).ty, i.ty),
.bitcast => |x| e.vals[ri] = try e.op1(.bitcast, i.ty, &.{e.val(x)}),
.splat => |x| {
const n = e.t.componentCount(i.ty).?;
if (e.isTrueMatrix(i.ty)) {
const m = e.t.get(i.ty).matrix;
const parts = try e.arena.alloc(u32, m.cols);
@memset(parts, e.val(x));
const one_row = try e.op1(.composite_construct, try e.t.vector(m.elem, m.cols), parts);
const rows = try e.arena.alloc(u32, m.rows);
@memset(rows, one_row);
e.vals[ri] = try e.op1(.composite_construct, i.ty, rows);
return;
}
if (n == 1) {
e.vals[ri] = e.val(x);
return;
@ -693,14 +964,16 @@ const Emitter = struct {
e.vals[ri] = try e.op1(.composite_construct, i.ty, comps);
},
.extract => |x| {
if (e.isScalarLike(f.inst(x.agg).ty)) {
const at = f.inst(x.agg).ty;
// Row 0 of a 1xN matrix is the whole (vector) value.
if (e.isScalarLike(at) or (e.t.get(at) == .matrix and e.t.get(at).matrix.rows == 1)) {
e.vals[ri] = e.val(x.agg);
return;
}
e.vals[ri] = try e.op1(.composite_extract, i.ty, &.{ e.val(x.agg), x.index });
},
.insert => |x| {
if (e.isScalarLike(i.ty)) {
if (e.isScalarLike(i.ty) or (e.t.get(i.ty) == .matrix and e.t.get(i.ty).matrix.rows == 1)) {
e.vals[ri] = e.val(x.value);
return;
}
@ -711,6 +984,19 @@ const Emitter = struct {
e.vals[ri] = e.val(xs[0]);
return;
}
if (e.isTrueMatrix(i.ty) and xs.len != e.t.get(i.ty).matrix.rows) {
// From scalars: group them into rows.
const m = e.t.get(i.ty).matrix;
const rt = try e.t.vector(m.elem, m.cols);
const rows = try e.arena.alloc(u32, m.rows);
for (rows, 0..) |*rw, k| {
const parts = try e.arena.alloc(u32, m.cols);
for (parts, 0..) |*p, c| p.* = e.val(xs[k * m.cols + c]);
rw.* = try e.op1(.composite_construct, rt, parts);
}
e.vals[ri] = try e.op1(.composite_construct, i.ty, rows);
return;
}
const ids = try e.arena.alloc(u32, xs.len);
for (xs, ids) |x, *id| id.* = e.val(x);
e.vals[ri] = try e.op1(.composite_construct, i.ty, ids);
@ -736,7 +1022,21 @@ const Emitter = struct {
for (x.components) |c| try ops.append(e.arena, c);
e.vals[ri] = try e.op1(.vector_shuffle, i.ty, ops.items);
},
.select => |x| e.vals[ri] = try e.op1(.select, i.ty, &.{ e.val(x.cond), e.val(x.t), e.val(x.f) }),
.select => |x| {
if (e.isTrueMatrix(i.ty)) {
const m = e.t.get(i.ty).matrix;
const rt = try e.t.vector(m.elem, m.cols);
const ct = f.inst(x.cond).ty;
const rows = try e.arena.alloc(u32, m.rows);
for (rows, 0..) |*rw, k| {
const c = if (e.isTrueMatrix(ct)) try e.row(e.val(x.cond), try e.t.vector(.bool, m.cols), @intCast(k)) else e.val(x.cond);
rw.* = try e.op1(.select, rt, &.{ c, try e.row(e.val(x.t), rt, @intCast(k)), try e.row(e.val(x.f), rt, @intCast(k)) });
}
e.vals[ri] = try e.op1(.composite_construct, i.ty, rows);
return;
}
e.vals[ri] = try e.op1(.select, i.ty, &.{ e.val(x.cond), e.val(x.t), e.val(x.f) });
},
.call => |c| {
var ops: std.ArrayList(u32) = .empty;
try ops.append(e.arena, e.func_ids[c.func]);
@ -746,17 +1046,12 @@ const Emitter = struct {
.intrinsic => |c| e.vals[ri] = try e.intrinsic(c.name, i.ty, c.args),
.res_load => |x| {
const ptr = try e.bufferElement(x.res, x.index);
if (e.t.component(i.ty) == .bool) {
const stored = try e.t.withComponent(i.ty, .uint);
const raw = try e.op1(.load, stored, &.{ptr});
e.vals[ri] = try e.convert(raw, stored, i.ty);
} else e.vals[ri] = try e.op1(.load, i.ty, &.{ptr});
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| {
const ptr = try e.bufferElement(x.res, x.index);
var v = e.val(x.value);
const vt = f.inst(x.value).ty;
if (e.t.component(vt) == .bool) v = try e.convert(v, vt, try e.t.withComponent(vt, .uint));
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}),
@ -915,8 +1210,49 @@ const Emitter = struct {
fn intrinsic(e: *Emitter, name: []const u8, ty: TypeId, args: []const Ref) Error!Id {
const ids = try e.arena.alloc(u32, args.len);
for (args, ids) |a, *id| id.* = e.val(a);
const arg_c = if (args.len > 0) e.compOf(e.f.inst(args[0]).ty) else e.compOf(ty);
const tys = try e.arena.alloc(TypeId, args.len);
for (args, ids, tys) |a, *id, *t| {
id.* = e.val(a);
t.* = e.f.inst(a).ty;
}
// Component-wise intrinsics on matrices apply row by row (GLSL
// instructions take scalars and vectors).
const whole = [_][]const u8{ "mul", "transpose", "determinant", "any", "all", "length", "dot" };
const component_wise = for (whole) |w| {
if (std.mem.eql(u8, w, name)) break false;
} else true;
var any_matrix = e.isTrueMatrix(ty);
for (tys) |t| any_matrix = any_matrix or e.isTrueMatrix(t);
if (component_wise and any_matrix) {
const shape_ty = if (e.isTrueMatrix(ty)) ty else for (tys) |t| {
if (e.isTrueMatrix(t)) break t;
} else ty;
const m = e.t.get(shape_ty).matrix;
const rows = try e.arena.alloc(u32, m.rows);
const row_ids = try e.arena.alloc(u32, args.len);
const row_tys = try e.arena.alloc(TypeId, args.len);
const rty = try e.t.vector(e.t.component(ty).?, m.cols);
for (rows, 0..) |*rw, k| {
for (tys, ids, row_ids, row_tys) |t, id, *rid, *rt| {
if (e.isTrueMatrix(t)) {
rt.* = try e.t.vector(e.t.component(t).?, m.cols);
rid.* = try e.row(id, rt.*, @intCast(k));
} else {
rt.* = t;
rid.* = id;
}
}
rw.* = try e.intrinsicOn(name, if (e.isTrueMatrix(ty)) rty else ty, row_ids, row_tys);
}
if (!e.isTrueMatrix(ty)) return rows[0];
return e.op1(.composite_construct, ty, rows);
}
return e.intrinsicOn(name, ty, ids, tys);
}
fn intrinsicOn(e: *Emitter, name: []const u8, ty: TypeId, ids: []const u32, tys: []const TypeId) Error!Id {
const args = tys; // count and types only
const arg_c = if (args.len > 0) e.compOf(tys[0]) else e.compOf(ty);
const fl = arg_c.isFloat();
const un = arg_c.isUnsigned();
const Glsl = struct { name: []const u8, f: u32, s: u32 = 0, u: u32 = 0 };
@ -939,13 +1275,18 @@ const Emitter = struct {
const eqn = std.mem.eql;
if (eqn(u8, name, "sign")) {
// HLSL sign returns int; GLSL's FSign / SSign keep the type.
const at = e.f.inst(args[0]).ty;
const at = tys[0];
const s = try e.op1(.ext_inst, at, &.{ e.glslSet(), if (fl) 6 else 7, ids[0] });
return e.convert(s, at, ty);
}
if ((eqn(u8, name, "countbits") or eqn(u8, name, "reversebits") or eqn(u8, name, "ddx") or eqn(u8, name, "ddy") or eqn(u8, name, "fwidth") or eqn(u8, name, "ddx_coarse") or eqn(u8, name, "ddy_coarse")) and arg_c.size() != 4) {
return e.unsupported("intrinsic '{s}' on {d}-bit types is not supported yet", .{ name, arg_c.size() * 8 });
}
if (eqn(u8, name, "ldexp")) {
// x * exp2(e) (HLSL's exponent is a float).
const p = try e.op1(.ext_inst, ty, &.{ e.glslSet(), 29, ids[1] });
return e.binary(.mul, ty, ids[0], p);
}
for (glsl_ops) |g| if (std.mem.eql(u8, g.name, name)) {
if (std.mem.eql(u8, name, "mad") and !fl) {
const p = try e.op1(.i_mul, ty, &.{ ids[0], ids[1] });
@ -958,12 +1299,27 @@ const Emitter = struct {
try ops.appendSlice(e.arena, ids);
return e.op1(.ext_inst, ty, ops.items);
};
if (eqn(u8, name, "mul") and args.len == 2) return e.mul(ty, tys[0], tys[1], ids[0], ids[1]);
if (eqn(u8, name, "transpose")) {
const at = tys[0];
if (e.isTrueMatrix(at) and e.compOf(at).isFloat()) return e.op1(.transpose, ty, ids);
const as = e.t.shape(at).?;
const comps = try e.arena.alloc(Id, as.count());
for (0..as.cols) |c| for (0..as.rows) |r| {
comps[c * as.rows + r] = try e.elementAt(ids[0], at, @intCast(r), @intCast(c));
};
return e.fromScalars(ty, comps);
}
if (std.mem.eql(u8, name, "saturate")) {
const zero = try e.splatConst(ty, .{ .float = 0 });
const one = try e.splatConst(ty, .{ .float = 1 });
return e.op1(.ext_inst, ty, &.{ e.glslSet(), 43, ids[0], zero, one });
}
if (std.mem.eql(u8, name, "dot") and fl) return e.op1(.dot, ty, ids);
const deriv = for ([_][]const u8{ "ddx", "ddy", "ddx_coarse", "ddy_coarse", "ddx_fine", "ddy_fine", "fwidth" }) |d| {
if (eqn(u8, name, d)) break true;
} else false;
if (deriv and e.m.entry.?.stage != .pixel) return e.unsupported("derivatives outside pixel shaders are not supported yet", .{});
if (std.mem.eql(u8, name, "ddx") or std.mem.eql(u8, name, "ddx_coarse")) return e.op1(.dpdx, ty, ids);
if (std.mem.eql(u8, name, "ddy") or std.mem.eql(u8, name, "ddy_coarse")) return e.op1(.dpdy, ty, ids);
if (std.mem.eql(u8, name, "fwidth")) return e.op1(.fwidth, ty, ids);