SM 6.10 linear algebra (DXIL)

- __builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use,
  scope)]] as a type; matrices live in locals, statics and structs as
  matrix-typed allocas (as dxc -Od); !dx.targetTypes.
- All 21 dx::__builtin_LinAlg_* builtins lowered to DXIL ops 322-342
  with dxc's overload names (matrix, native vector and scalar operands;
  results stored to the out / ref argument).
- The LinearAlgebra shader flag; PSV0 LinAlgRuntimeInfo (constructions,
  multiplies, outer products, accumulate stores), byte-identical to dxc
  where matrix loads are traceable.
- groupshared parameters alias the caller's variable (they were copied);
  constants forwarded through locals within a block (immediates through
  parameters); enum static consts folded.
- Linear algebra in libraries (RDAT properties) and long vectors are
  reported as not supported yet.
This commit is contained in:
Peter Li 2026-10-31 20:25:57 -07:00
parent 56adacfc4a
commit 77f4fb539c
10 changed files with 612 additions and 21 deletions

View File

@ -18,6 +18,7 @@ const signature = @import("signature.zig");
const texture = @import("../ir/texture.zig"); const texture = @import("../ir/texture.zig");
const mangle = @import("mangle.zig"); const mangle = @import("mangle.zig");
const rdat = @import("rdat.zig"); const rdat = @import("rdat.zig");
const linalg_info = @import("linalg_info.zig");
const libinfo = @import("libinfo.zig"); const libinfo = @import("libinfo.zig");
const rootsig = @import("rootsig.zig"); const rootsig = @import("rootsig.zig");
@ -183,6 +184,9 @@ const Emitter = struct {
uses_tiled_resources: bool = false, uses_tiled_resources: bool = false,
uses_mesh_derivatives: bool = false, uses_mesh_derivatives: bool = false,
uses_ray_query: bool = false, uses_ray_query: bool = false,
/// SM 6.10 matrix types used (`!dx.targetTypes`), in first-use order.
linalg_types: std.ArrayList(struct { ty: TypeId, dty: DType }) = .empty,
uses_linalg: bool = false,
/// RayQuery locals: the query handle (allocated in the prologue on /// RayQuery locals: the query handle (allocated in the prologue on
/// first use, or a copy of another query) and the query type. /// first use, or a copy of another query) and the query type.
rq_locals: std.ArrayList(struct { h: ?Value, ty: TypeId }) = .empty, rq_locals: std.ArrayList(struct { h: ?Value, ty: TypeId }) = .empty,
@ -300,7 +304,8 @@ const Emitter = struct {
/// Number of flattened scalar components of `ty`. /// Number of flattened scalar components of `ty`.
fn flatCount(e: *Emitter, ty: TypeId) Error!u32 { fn flatCount(e: *Emitter, ty: TypeId) Error!u32 {
return switch (e.t.get(ty)) { return switch (e.t.get(ty)) {
.scalar, .@"enum" => 1, // (A matrix handle is one opaque component.)
.scalar, .@"enum", .linalg => 1,
.vector => |v| v.len, .vector => |v| v.len,
.matrix => |m| @as(u32, m.rows) * m.cols, .matrix => |m| @as(u32, m.rows) * m.cols,
.array => |a| a.len * try e.flatCount(a.elem), .array => |a| a.len * try e.flatCount(a.elem),
@ -1434,7 +1439,7 @@ const Emitter = struct {
// inlined into it). // inlined into it).
if (e.m.globals.items[g].space == .private) { if (e.m.globals.items[g].space == .private) {
const gty = e.m.globals.items[g].ty; const gty = e.m.globals.items[g].ty;
if (try e.mixedSizes(gty)) { if (try e.mixedSizes(gty) or e.containsLinAlg(gty)) {
const tg = try e.private_typed.getOrPut(e.arena, g); const tg = try e.private_typed.getOrPut(e.arena, g);
if (!tg.found_existing) { if (!tg.found_existing) {
const dty = try e.memoryType(gty); const dty = try e.memoryType(gty);
@ -1479,8 +1484,9 @@ const Emitter = struct {
try e.res_locals.append(e.arena, null); try e.res_locals.append(e.arena, null);
return .{ .res_local = @intCast(e.res_locals.items.len - 1) }; return .{ .res_local = @intCast(e.res_locals.items.len - 1) };
} }
if (try e.mixedSizes(i.ty)) { if (try e.mixedSizes(i.ty) or e.containsLinAlg(i.ty)) {
// Components of several sizes: a struct-typed alloca. // Components of several sizes (or matrix handles): a
// struct-typed alloca.
const dty = try e.memoryType(i.ty); const dty = try e.memoryType(i.ty);
const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } }); const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } });
return .{ .typed = .{ .base = base, .dty = dty, .addr_space = 0, .ty = i.ty } }; return .{ .typed = .{ .base = base, .dty = dty, .addr_space = 0, .ty = i.ty } };
@ -1875,7 +1881,10 @@ const Emitter = struct {
for (vals, 0..) |v, c| { for (vals, 0..) |v, c| {
if (ptr.offset_dyn == null) { if (ptr.offset_dyn == null) {
const key = .{ ptr.base, ptr.offset_const + @as(u32, @intCast(c)) }; const key = .{ ptr.base, ptr.offset_const + @as(u32, @intCast(c)) };
if (e.status_vals.contains(v)) try e.forwarded.put(e.arena, key, .{ .v = v, .block = e.cur }) else _ = e.forwarded.remove(key); // (Constants too, in locals: ops such as linear algebra
// layouts need immediates passed through parameters.)
const forward = e.status_vals.contains(v) or (v == .constant and ptr.addr_space == 0);
if (forward) try e.forwarded.put(e.arena, key, .{ .v = v, .block = e.cur }) else _ = e.forwarded.remove(key);
} else e.forwarded.clearRetainingCapacity(); } else e.forwarded.clearRetainingCapacity();
const p = try e.elementPtr(ptr, @intCast(c)); const p = try e.elementPtr(ptr, @intCast(c));
const ct = e.compOf(try e.componentType(ty, @intCast(c))); const ct = e.compOf(try e.componentType(ty, @intCast(c)));
@ -1980,6 +1989,7 @@ const Emitter = struct {
const eq = std.mem.eql; const eq = std.mem.eql;
if (try e.rayIntrinsic(frame, name, ty, args)) |r| return r; if (try e.rayIntrinsic(frame, name, ty, args)) |r| return r;
if (try e.outIntrinsic(frame, name, ty, args)) |r| return r; if (try e.outIntrinsic(frame, name, ty, args)) |r| return r;
if (std.mem.startsWith(u8, name, "__builtin_LinAlg_")) return e.linAlg(frame, name[17..], ty, args);
if (eq(u8, name, "DispatchMesh")) { if (eq(u8, name, "DispatchMesh")) {
const tp = switch (frame.vals[args[3].index()]) { const tp = switch (frame.vals[args[3].index()]) {
.typed => |x| x, .typed => |x| x,
@ -2822,7 +2832,7 @@ const Emitter = struct {
/// The scalar type of flattened component `k` of `ty`. /// The scalar type of flattened component `k` of `ty`.
fn componentType(e: *Emitter, ty: TypeId, k: u32) Error!TypeId { fn componentType(e: *Emitter, ty: TypeId, k: u32) Error!TypeId {
switch (e.t.get(ty)) { switch (e.t.get(ty)) {
.scalar, .@"enum" => return ty, .scalar, .@"enum", .linalg => return ty,
.vector, .matrix => return e.t.scalar(e.t.component(ty).?), .vector, .matrix => return e.t.scalar(e.t.component(ty).?),
.array => |a| return e.componentType(a.elem, k % try e.flatCount(a.elem)), .array => |a| return e.componentType(a.elem, k % try e.flatCount(a.elem)),
.@"struct" => |s| { .@"struct" => |s| {
@ -4042,8 +4052,201 @@ const Emitter = struct {
/// The memory type of an HLSL value in struct-typed memory: vectors /// The memory type of an HLSL value in struct-typed memory: vectors
/// and matrices (by row) become arrays, bools 32-bit integers. /// and matrices (by row) become arrays, bools 32-bit integers.
// ------------------------------------------------------------------
// SM 6.10 linear algebra
/// `%dx.types.LinAlgMatrixC<c>M<m>N<n>U<use>S<scope>` = { i8* }.
fn matrixType(e: *Emitter, ty: TypeId) Error!DType {
for (e.linalg_types.items) |x| if (x.ty == ty) return x.dty;
const la = e.t.get(ty).linalg;
const name = try std.fmt.allocPrint(e.arena, "dx.types.LinAlgMatrixC{d}M{d}N{d}U{d}S{d}", .{ la.comp, la.m, la.n, la.use, la.scope });
const dty = try e.dm.getType(.{ .@"struct" = .{ .name = name, .elems = &.{try e.dm.ptrType(try e.dm.intType(8))} } });
try e.linalg_types.append(e.arena, .{ .ty = ty, .dty = dty });
return dty;
}
fn containsLinAlg(e: *Emitter, ty: TypeId) bool {
return switch (e.t.get(ty)) {
.linalg => true,
.array => |a| e.containsLinAlg(a.elem),
.@"struct" => |st| for (st.fields.items) |fld| {
if (e.containsLinAlg(fld.type)) break true;
} else false,
else => false,
};
}
/// The overload suffix of an operand: `mC4M5N4U1S2`, `v4f32`, `f32`.
fn linAlgSuffix(e: *Emitter, ty: TypeId) Error![]const u8 {
return switch (e.t.get(ty)) {
.linalg => |la| std.fmt.allocPrint(e.arena, "mC{d}M{d}N{d}U{d}S{d}", .{ la.comp, la.m, la.n, la.use, la.scope }),
.vector => |v| if (v.len == 1) e.overloadName(try e.scalarTy(e.compOf(ty))) else std.fmt.allocPrint(e.arena, "v{d}{s}", .{ v.len, e.overloadName(try e.scalarTy(e.compOf(ty))) }),
else => e.overloadName(try e.scalarTy(e.compOf(ty))),
};
}
/// An operand of a linear algebra op: a matrix handle, a native vector
/// or a scalar, with its LLVM type.
fn linAlgValue(e: *Emitter, frame: *Frame, r: Ref) Error!struct { Value, DType } {
const ty = frame.f.inst(r).ty;
const vals = try e.scalars(frame, r);
if (e.t.get(ty) == .linalg) return .{ vals[0], try e.matrixType(ty) };
if (e.t.get(ty) == .vector and vals.len > 1) return .{ try e.libJoin(vals, ty), try e.libValueType(ty) };
return .{ vals[0], try e.valueType(vals[0]) };
}
/// Writes an op result (a matrix, vector or scalar) to an `out`
/// argument's storage.
fn linAlgStore(e: *Emitter, frame: *Frame, dst: Ref, v: Value) Error!void {
const ty = frame.f.inst(dst).ty;
const vals = if (e.t.get(ty) == .vector and e.t.get(ty).vector.len > 1) try e.libSplit(v, ty) else try e.arena.dupe(Value, &.{v});
switch (frame.vals[dst.index()]) {
.typed => |tp| try e.typedStore(tp, vals, ty),
.ptr => |p| try e.storePtr(p, vals, ty),
else => return e.unsupported("this destination of a linear algebra result is not supported yet", .{}),
}
}
/// A groupshared array argument: a pointer to its first element.
fn linAlgMemory(e: *Emitter, frame: *Frame, r: Ref) Error!struct { Value, DType, []const u8 } {
const arr = frame.f.inst(r).ty;
if (e.t.get(arr) != .array) return e.unsupported("linear algebra memory that is not a groupshared array", .{});
const elem = e.t.get(arr).array.elem;
if (e.t.get(elem) != .scalar) return e.unsupported("groupshared arrays of type '{s}' for linear algebra are not supported yet", .{try e.t.format(e.arena, arr)});
const p = switch (frame.vals[r.index()]) {
.ptr => |x| x,
else => return e.unsupported("linear algebra memory that is not a groupshared array", .{}),
};
if (p.addr_space != 3 or p.mixed or p.bool_storage) return e.unsupported("linear algebra memory that is not a groupshared array", .{});
const pt = try e.dm.getType(.{ .pointer = .{ .elem = p.scalar_ty, .addr_space = 3 } });
const off = if (p.offset_dyn) |d| d else try e.i32Const(@intCast(p.offset_const));
const ptr = try e.add(pt, .{ .gep = .{ .elem = p.array_ty, .ptr = p.base, .indices = try e.arena.dupe(Value, &.{ try e.i32Const(0), off }) } });
return .{ ptr, pt, e.overloadName(p.scalar_ty) };
}
/// `dx::__builtin_LinAlg_<name>(...)`: DXIL ops 322-342. Results go to
/// the first (`out` / `ref`) argument, or are returned.
fn linAlg(e: *Emitter, frame: *Frame, name: []const u8, ty: TypeId, args: []const Ref) Error!Lowered {
const eq = std.mem.eql;
if (e.profile.minor < 10) return e.unsupported("linear algebra needs shader model 6.10", .{});
e.uses_linalg = true;
const i32t = try e.dm.intType(32);
const Op = struct { code: u32, op: []const u8 };
const table = [_]struct { []const u8, Op }{
.{ "MatrixMatrixMultiplyAccumulate", .{ .code = 322, .op = "linAlgMatrixMultiplyAccumulate" } },
.{ "FillMatrix", .{ .code = 323, .op = "linAlgFillMatrix" } },
.{ "CopyConvertMatrix", .{ .code = 324, .op = "linAlgCopyConvertMatrix" } },
.{ "MatrixLoadFromDescriptor", .{ .code = 325, .op = "linAlgMatrixLoadFromDescriptor" } },
.{ "MatrixLoadFromMemory", .{ .code = 326, .op = "linAlgMatrixLoadFromMemory" } },
.{ "MatrixLength", .{ .code = 327, .op = "linAlgMatrixLength" } },
.{ "MatrixGetCoordinate", .{ .code = 328, .op = "linAlgMatrixGetCoordinate" } },
.{ "MatrixGetElement", .{ .code = 329, .op = "linAlgMatrixGetElement" } },
.{ "MatrixSetElement", .{ .code = 330, .op = "linAlgMatrixSetElement" } },
.{ "MatrixStoreToDescriptor", .{ .code = 331, .op = "linAlgMatrixStoreToDescriptor" } },
.{ "MatrixStoreToMemory", .{ .code = 332, .op = "linAlgMatrixStoreToMemory" } },
.{ "MatrixQueryAccumulatorLayout", .{ .code = 333, .op = "linAlgMatrixQueryAccumulatorLayout" } },
.{ "MatrixMatrixMultiply", .{ .code = 334, .op = "linAlgMatrixMultiply" } },
.{ "MatrixAccumulate", .{ .code = 335, .op = "linAlgMatrixAccumulate" } },
.{ "MatrixVectorMultiply", .{ .code = 336, .op = "linAlgMatVecMul" } },
.{ "MatrixVectorMultiplyAdd", .{ .code = 337, .op = "linAlgMatVecMulAdd" } },
.{ "MatrixAccumulateToDescriptor", .{ .code = 338, .op = "linAlgMatrixAccumulateToDescriptor" } },
.{ "MatrixAccumulateToMemory", .{ .code = 339, .op = "linAlgMatrixAccumulateToMemory" } },
.{ "MatrixOuterProduct", .{ .code = 340, .op = "linAlgMatrixOuterProduct" } },
.{ "Convert", .{ .code = 341, .op = "linAlgConvert" } },
.{ "VectorAccumulateToDescriptor", .{ .code = 342, .op = "linAlgVectorAccumulateToDescriptor" } },
};
const op = for (table) |x| {
if (eq(u8, x[0], name)) break x[1];
} else return e.unsupported("linear algebra builtin '{s}' is not supported yet", .{name});
// Which leading argument receives the result (out / ref), and the
// overload suffixes in dxc's order.
const out_first = switch (op.code) {
322, 323, 324, 325, 326, 329, 330, 334, 335, 336, 337, 340, 341 => true,
else => false,
};
var params: std.ArrayList(DType) = .empty;
var vals: std.ArrayList(Value) = .empty;
var suffix: std.ArrayList(u8) = .empty;
try params.append(e.arena, i32t);
try vals.append(e.arena, try e.i32Const(op.code));
const ret_ty: DType = blk: {
if (out_first) {
const dst_ty = frame.f.inst(args[0]).ty;
try suffix.print(e.arena, ".{s}", .{try e.linAlgSuffix(dst_ty)});
break :blk if (e.t.get(dst_ty) == .linalg) try e.matrixType(dst_ty) else if (e.t.get(dst_ty) == .vector and e.t.get(dst_ty).vector.len > 1) try e.libValueType(dst_ty) else try e.scalarTy(e.compOf(dst_ty));
}
if (ty == TypeTable.void_type) break :blk try e.voidTy();
break :blk if (e.t.get(ty) == .vector) try e.libValueType(ty) else try e.scalarTy(e.compOf(ty));
};
for (args[@intFromBool(out_first)..], @intFromBool(out_first)..) |a, k| {
const aty = frame.f.inst(a).ty;
// The `ref` destination of SetElement / accumulates is not an
// operand (its value is the result).
if (e.t.get(aty) == .array) {
const mem = try e.linAlgMemory(frame, a);
try vals.append(e.arena, mem[0]);
try params.append(e.arena, mem[1]);
try suffix.print(e.arena, ".{s}", .{mem[2]});
continue;
}
if (e.t.get(aty) == .resource) {
try vals.append(e.arena, (try e.resourceOf(frame, a)).handle);
try params.append(e.arena, e.handle_ty);
continue;
}
const v = try e.linAlgValue(frame, a);
try vals.append(e.arena, v[0]);
try params.append(e.arena, v[1]);
const overloaded = e.t.get(aty) == .linalg or (e.t.get(aty) == .vector and e.t.get(aty).vector.len > 1) or
// The filled / set value.
(op.code == 323 and k == 2) or (op.code == 330 and k == 3);
if (overloaded) try suffix.print(e.arena, ".{s}", .{try e.linAlgSuffix(aty)});
}
// GetElement and the vector results name their result first.
const fname = try std.fmt.allocPrint(e.arena, "dx.op.{s}{s}", .{ op.op, suffix.items });
const attrs: module.FnAttrs = switch (op.code) {
327, 328, 329, 333 => .nounwind_readnone,
else => .nounwind,
};
const fn_i = try e.dxOp(fname, ret_ty, params.items, attrs);
const r = try e.callOp(fn_i, ret_ty, vals.items);
if (out_first) {
try e.linAlgStore(frame, args[0], r);
return .none;
}
if (ty == TypeTable.void_type) return .none;
if (e.t.get(ty) == .vector) return .{ .scalars = try e.libSplit(r, ty) };
return .{ .scalars = try e.arena.dupe(Value, &.{r}) };
}
/// What the module does with matrices (PSV0), when it has any.
fn linAlgTables(e: *Emitter) Error!?linalg_info.Tables {
if (!e.uses_linalg) return null;
const mats = try e.arena.alloc(struct { module.TypeId, linalg_info.Matrix }, e.linalg_types.items.len);
for (mats, e.linalg_types.items) |*m, x| {
const la = e.t.get(x.ty).linalg;
m.* = .{ x.dty, .{ .comp = la.comp, .m = la.m, .n = la.n, .use = la.use, .scope = la.scope } };
}
return try linalg_info.collect(e.arena, &e.dm, mats);
}
/// `!dx.targetTypes`: each matrix type with its attributes.
fn targetTypesMd(e: *Emitter) Error!void {
if (e.linalg_types.items.len == 0) return;
const dm = &e.dm;
var nodes: std.ArrayList(module.MdId) = .empty;
for (e.linalg_types.items) |x| {
const la = e.t.get(x.ty).linalg;
const undef = try dm.constant(.{ .ty = x.dty, .kind = .undef });
try nodes.append(e.arena, try dm.mdNode(&.{ try dm.mdValue(x.dty, undef), try dm.mdI32(la.comp), try dm.mdI32(la.m), try dm.mdI32(la.n), try dm.mdI32(la.use), try dm.mdI32(la.scope) }));
}
try dm.addNamedMetadata("dx.targetTypes", nodes.items);
}
fn memoryType(e: *Emitter, ty: TypeId) Error!DType { fn memoryType(e: *Emitter, ty: TypeId) Error!DType {
return switch (e.t.get(ty)) { return switch (e.t.get(ty)) {
.linalg => e.matrixType(ty),
.scalar, .@"enum" => e.scalarTy(memScalar(e.compOf(ty))), .scalar, .@"enum" => e.scalarTy(memScalar(e.compOf(ty))),
.vector => |v| e.dm.getType(.{ .array = .{ .len = v.len, .elem = try e.scalarTy(memScalar(e.compOf(ty))) } }), .vector => |v| e.dm.getType(.{ .array = .{ .len = v.len, .elem = try e.scalarTy(memScalar(e.compOf(ty))) } }),
.matrix => |m| e.dm.getType(.{ .array = .{ .len = m.rows, .elem = try e.dm.getType(.{ .array = .{ .len = m.cols, .elem = try e.scalarTy(memScalar(e.compOf(ty))) } }) } }), .matrix => |m| e.dm.getType(.{ .array = .{ .len = m.rows, .elem = try e.dm.getType(.{ .array = .{ .len = m.cols, .elem = try e.scalarTy(memScalar(e.compOf(ty))) } }) } }),
@ -4065,6 +4268,7 @@ const Emitter = struct {
/// Size and alignment of `ty`'s memory type. /// Size and alignment of `ty`'s memory type.
fn memLayout(e: *Emitter, ty: TypeId) Error![2]u32 { fn memLayout(e: *Emitter, ty: TypeId) Error![2]u32 {
switch (e.t.get(ty)) { switch (e.t.get(ty)) {
.linalg => return .{ 8, 8 },
.scalar, .@"enum", .vector, .matrix => { .scalar, .@"enum", .vector, .matrix => {
const sz = memScalar(e.compOf(ty)).size(); const sz = memScalar(e.compOf(ty)).size();
return .{ sz * (e.t.componentCount(ty) orelse 1), sz }; return .{ sz * (e.t.componentCount(ty) orelse 1), sz };
@ -4098,7 +4302,7 @@ const Emitter = struct {
} }
}.f; }.f;
switch (e.t.get(ty)) { switch (e.t.get(ty)) {
.scalar, .@"enum" => try out.append(e.arena, prefix), .scalar, .@"enum", .linalg => try out.append(e.arena, prefix),
.vector => |v| for (0..v.len) |k| try out.append(e.arena, try sub(e, prefix, @intCast(k))), .vector => |v| for (0..v.len) |k| try out.append(e.arena, try sub(e, prefix, @intCast(k))),
.matrix => |m| for (0..m.rows) |r| { .matrix => |m| for (0..m.rows) |r| {
const rp = try sub(e, prefix, @intCast(r)); const rp = try sub(e, prefix, @intCast(r));
@ -4124,7 +4328,13 @@ const Emitter = struct {
try e.scalarPaths(ty, &.{}, &paths); try e.scalarPaths(ty, &.{}, &paths);
const out = try e.arena.alloc(Value, paths.items.len); const out = try e.arena.alloc(Value, paths.items.len);
for (out, paths.items, 0..) |*o, sub, c| { for (out, paths.items, 0..) |*o, sub, c| {
const ct = e.compOf(try e.componentType(ty, @intCast(c))); const cty = try e.componentType(ty, @intCast(c));
if (e.t.get(cty) == .linalg) {
const mt = try e.matrixType(cty);
o.* = try e.add(mt, .{ .load = .{ .ptr = try e.typedScalarPtr(tp, sub, mt), .@"align" = 0 } });
continue;
}
const ct = e.compOf(cty);
const st = try e.scalarTy(memScalar(ct)); const st = try e.scalarTy(memScalar(ct));
const raw = try e.add(st, .{ .load = .{ .ptr = try e.typedScalarPtr(tp, sub, st), .@"align" = memScalar(ct).size() } }); const raw = try e.add(st, .{ .load = .{ .ptr = try e.typedScalarPtr(tp, sub, st), .@"align" = memScalar(ct).size() } });
o.* = if (ct == .bool) try e.add(try e.dm.intType(1), .{ .cmp = .{ .pred = 33, .lhs = raw, .rhs = try e.i32Const(0) } }) else raw; o.* = if (ct == .bool) try e.add(try e.dm.intType(1), .{ .cmp = .{ .pred = 33, .lhs = raw, .rhs = try e.i32Const(0) } }) else raw;
@ -4136,7 +4346,12 @@ const Emitter = struct {
var paths: std.ArrayList([]const Value) = .empty; var paths: std.ArrayList([]const Value) = .empty;
try e.scalarPaths(ty, &.{}, &paths); try e.scalarPaths(ty, &.{}, &paths);
for (vals, paths.items, 0..) |v, sub, c| { for (vals, paths.items, 0..) |v, sub, c| {
const ct = e.compOf(try e.componentType(ty, @intCast(c))); const cty = try e.componentType(ty, @intCast(c));
if (e.t.get(cty) == .linalg) {
_ = try e.add(try e.voidTy(), .{ .store = .{ .ptr = try e.typedScalarPtr(tp, sub, try e.matrixType(cty)), .val = v, .@"align" = 0 } });
continue;
}
const ct = e.compOf(cty);
const st = try e.scalarTy(memScalar(ct)); const st = try e.scalarTy(memScalar(ct));
const sv = if (ct == .bool) try e.add(st, .{ .cast = .{ .op = .zext, .val = v } }) else v; const sv = if (ct == .bool) try e.add(st, .{ .cast = .{ .op = .zext, .val = v } }) else v;
_ = try e.add(try e.voidTy(), .{ .store = .{ .ptr = try e.typedScalarPtr(tp, sub, st), .val = sv, .@"align" = memScalar(ct).size() } }); _ = try e.add(try e.voidTy(), .{ .store = .{ .ptr = try e.typedScalarPtr(tp, sub, st), .val = sv, .@"align" = memScalar(ct).size() } });
@ -4294,6 +4509,7 @@ const Emitter = struct {
if (e.uses_wave) flags |= 1 << 19; if (e.uses_wave) flags |= 1 << 19;
if (e.uses_inner_coverage) flags |= 1 << 10; if (e.uses_inner_coverage) flags |= 1 << 10;
if (e.uses_ray_query) flags |= 1 << 25; if (e.uses_ray_query) flags |= 1 << 25;
if (e.uses_linalg) flags |= 1 << 41;
// UseNativeLowPrecision: set whenever 16-bit types are native. // UseNativeLowPrecision: set whenever 16-bit types are native.
if (e.native16()) flags |= 1 << 23; if (e.native16()) flags |= 1 << 23;
return flags; return flags;
@ -4433,6 +4649,8 @@ const Emitter = struct {
} }
fn writeLibraryModule(e: *Emitter, funcs: []const LibFunc) Error![]u8 { fn writeLibraryModule(e: *Emitter, funcs: []const LibFunc) Error![]u8 {
// (RDAT's per-function linear algebra properties are not written.)
if (e.uses_linalg) return e.unsupported("linear algebra in libraries is not supported yet", .{});
const dm = &e.dm; const dm = &e.dm;
const mdI32 = struct { const mdI32 = struct {
fn f(m: *module.Module, v: i64) !module.MdId { fn f(m: *module.Module, v: i64) !module.MdId {
@ -4499,6 +4717,7 @@ const Emitter = struct {
try entries.append(e.arena, try dm.mdNode(&.{ try dm.mdValue(try dm.ptrType(fty), .{ .function = lf.func }), try dm.mdString(lf.name), lf.sigs, null, try dm.mdNode(props.items) })); try entries.append(e.arena, try dm.mdNode(&.{ try dm.mdValue(try dm.ptrType(fty), .{ .function = lf.func }), try dm.mdString(lf.name), lf.sigs, null, try dm.mdNode(props.items) }));
} }
try e.targetTypesMd();
try dm.addNamedMetadata("llvm.ident", &.{ident}); try dm.addNamedMetadata("llvm.ident", &.{ident});
try dm.addNamedMetadata("dx.version", &.{version}); try dm.addNamedMetadata("dx.version", &.{version});
try dm.addNamedMetadata("dx.valver", &.{val_ver}); try dm.addNamedMetadata("dx.valver", &.{val_ver});
@ -4689,6 +4908,7 @@ const Emitter = struct {
const fn_ref = try dm.mdValue(try dm.ptrType(main_ty), .{ .function = e.main_fn }); const fn_ref = try dm.mdValue(try dm.ptrType(main_ty), .{ .function = e.main_fn });
const entry_md = try dm.mdNode(&.{ fn_ref, try dm.mdString(entry.name), sigs, resources, props_node }); const entry_md = try dm.mdNode(&.{ fn_ref, try dm.mdString(entry.name), sigs, resources, props_node });
try e.targetTypesMd();
try dm.addNamedMetadata("llvm.ident", &.{ident}); try dm.addNamedMetadata("llvm.ident", &.{ident});
try dm.addNamedMetadata("dx.version", &.{version}); try dm.addNamedMetadata("dx.version", &.{version});
try dm.addNamedMetadata("dx.valver", &.{val_ver}); try dm.addNamedMetadata("dx.valver", &.{val_ver});
@ -4819,6 +5039,7 @@ const Emitter = struct {
.patch_constants = e.sig_pc, .patch_constants = e.sig_pc,
.groupshared_bytes = if (threaded) e.groupshared_bytes else 0, .groupshared_bytes = if (threaded) e.groupshared_bytes else 0,
.max_vertex_count = if (entry.stage == .geometry) @intCast(entry.geometry.max_vertex_count) else 0, .max_vertex_count = if (entry.stage == .geometry) @intCast(entry.geometry.max_vertex_count) else 0,
.linalg = try e.linAlgTables(),
}); });
defer gpa.free(psv); defer gpa.free(psv);
const domain: signature.Domain = if (entry.stage == .hull or entry.stage == .domain) @enumFromInt(@intFromEnum(entry.tess.domain)) else .undefined; const domain: signature.Domain = if (entry.stage == .hull or entry.stage == .domain) @enumFromInt(@intFromEnum(entry.tess.domain)) else .undefined;

View File

@ -50,6 +50,7 @@ pub const bit = struct {
pub const extended_command_info = 1 << 38; pub const extended_command_info = 1 << 38;
pub const uses_derivatives = 1 << 39; pub const uses_derivatives = 1 << 39;
pub const requires_group = 1 << 40; pub const requires_group = 1 << 40;
pub const linear_algebra = 1 << 41;
/// Not part of the module's flags. /// Not part of the module's flags.
pub const local = uses_derivatives | requires_group; pub const local = uses_derivatives | requires_group;
}; };
@ -148,6 +149,7 @@ pub fn analyze(m: *const module.Module, f: *const module.Function, o: Options) I
const args = inst.op.call.args; const args = inst.op.call.args;
if ((code >= 110 and code <= 123) or (code >= 135 and code <= 136) or (code >= 165 and code <= 167) or code == 222 or (code >= 312 and code <= 313)) fl |= bit.wave; if ((code >= 110 and code <= 123) or (code >= 135 and code <= 136) or (code >= 165 and code <= 167) or code == 222 or (code >= 312 and code <= 313)) fl |= bit.wave;
if (code >= 174 and code <= 177) fl |= bit.sampler_feedback; if (code >= 174 and code <= 177) fl |= bit.sampler_feedback;
if (code >= 322 and code <= 342) fl |= bit.linear_algebra;
switch (code) { switch (code) {
71 => check_access = true, 71 => check_access = true,
50 => fl |= bit.msad, 50 => fl |= bit.msad,
@ -227,7 +229,7 @@ pub fn featureInfo(fl: u64) u64 {
.{ bit.view_id, 0x10000 }, .{ 1 << 24, 0x80000 }, .{ bit.wave, 0x4000 }, .{ bit.view_id, 0x10000 }, .{ 1 << 24, 0x80000 }, .{ bit.wave, 0x4000 },
.{ bit.typed_uav_load, 0x800 }, .{ bit.resource_heap, 0x2000000 }, .{ bit.sampler_heap, 0x4000000 }, .{ bit.typed_uav_load, 0x800 }, .{ bit.resource_heap, 0x2000000 }, .{ bit.sampler_heap, 0x4000000 },
.{ bit.barycentrics, 0x20000 }, .{ bit.extended_command_info, 0x100000000 }, .{ bit.tiled_resources, 0x100 }, .{ bit.barycentrics, 0x20000 }, .{ bit.extended_command_info, 0x100000000 }, .{ bit.tiled_resources, 0x100 },
.{ 1 << 29, 0x1000000 }, .{ 1 << 18, 0x1000 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 }, .{ 1 << 29, 0x1000000 }, .{ 1 << 18, 0x1000 }, .{ 1 << 41, 0x200000000 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 },
.{ bit.advanced_texture_ops, 0x20000000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 }, .{ bit.advanced_texture_ops, 0x20000000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 },
}; };
var out: u64 = 0; var out: u64 = 0;

311
src/dxil/linalg_info.zig Normal file
View File

@ -0,0 +1,311 @@
//! The SM 6.10 linear algebra usage the PSV0 part records (and the
//! validator recomputes from the module): matrix constructions, matrix-
//! vector and matrix-matrix multiplies, outer products and accumulating
//! stores. A port of dxc's LinAlgRuntimeInfoCollector.
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
/// A matrix type's attributes (`!dx.targetTypes`).
pub const Matrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 };
pub const Shape = struct { m: u32, n: u32, k: u32 };
/// The serialized tables (PSVLinAlg*0 records) and the shape index runs to
/// put in the semantic index table first.
pub const Tables = struct {
shapes: []const Shape,
/// PSVLinAlgRuntimeInfo0 record bytes, per table in declaration order:
/// constructions, thread mat-vec multiplies, wave multiplies,
/// thread-group multiplies, outer products, accumulate stores.
records: [6][]const u8,
counts: [6]u32,
sizes: [6]u32 = .{ 12, 4, 12, 12, 4, 4 },
semantic_indices: []const u32,
pub fn empty(t: Tables) bool {
if (t.shapes.len > 0) return false;
for (t.counts) |c| if (c > 0) return false;
return true;
}
};
const Key2 = [2]u8;
const Key3 = [3]u8;
const Key4 = [4]u8;
const Info = struct {
constructions: std.AutoArrayHashMapUnmanaged(Key2, std.AutoArrayHashMapUnmanaged(Shape, void)) = .empty,
matvec: std.AutoArrayHashMapUnmanaged(Key3, u8) = .empty,
multiplies: std.AutoArrayHashMapUnmanaged(Key4, std.AutoArrayHashMapUnmanaged(Shape, void)) = .empty,
outer: std.AutoArrayHashMapUnmanaged(Key2, void) = .empty,
accumulate: std.AutoArrayHashMapUnmanaged(u8, u8) = .empty,
};
const transposed: u8 = 1;
const non_mul_optimal: u8 = 2;
/// Collects the usage in every function of `m`; `matrices` maps matrix
/// types to their attributes.
pub fn collect(a: Allocator, m: *const module.Module, matrices: []const struct { module.TypeId, Matrix }) Allocator.Error!Tables {
var info: Info = .{};
const C = struct {
m: *const module.Module,
mats: []const struct { module.TypeId, Matrix },
fn matrix(c: @This(), ty: ?module.TypeId) ?Matrix {
const t = ty orelse return null;
for (c.mats) |x| if (x[0] == t) return x[1];
return null;
}
fn constInt(c: @This(), v: module.Value) ?u32 {
if (v != .constant) return null;
return switch (c.m.constants.items[v.constant].kind) {
.int => |x| @truncate(@as(u64, @bitCast(x))),
else => null,
};
}
/// DXIL::ComponentType of a scalar (or a vector's element).
fn component(c: @This(), ty: module.TypeId, signed: bool) u8 {
const t = switch (c.m.types.items[ty]) {
.vector => |v| c.m.types.items[v.elem],
else => |x| x,
};
return switch (t) {
.half => 8,
.float => 9,
.double => 10,
.int => |w| switch (w) {
8 => if (signed) 19 else 20,
16 => if (signed) 2 else 3,
32 => if (signed) 4 else 5,
64 => if (signed) 6 else 7,
else => 0,
},
else => 0,
};
}
};
const c: C = .{ .m = m, .mats = matrices };
for (m.functions.items) |*f| {
const fty = m.types.items[f.ty].function;
const typeOf = struct {
fn t(mm: *const module.Module, ff: *const module.Function, ft: @FieldType(module.Type, "function"), v: module.Value) ?module.TypeId {
return switch (v) {
.global => |g| mm.globals.items[g].ptr_ty,
.function => null,
.constant => |k| mm.constants.items[k].ty,
.arg => |x| ft.params[x],
.inst => |i| ff.insts.items[i].ty,
};
}
}.t;
for (f.insts.items) |inst| {
if (inst.op != .call) continue;
const call = inst.op.call;
if (!std.mem.startsWith(u8, m.functions.items[call.callee].name, "dx.op.linAlg") or call.args.len == 0) continue;
const op = c.constInt(call.args[0]) orelse continue;
const arg = struct {
fn t(cc: C, ff: *const module.Function, ft: @FieldType(module.Type, "function"), args: []const module.Value, k: usize) ?module.TypeId {
return if (k < args.len) typeOf(cc.m, ff, ft, args[k]) else null;
}
}.t;
switch (op) {
336, 337 => {
const mat = c.matrix(arg(c, f, fty, call.args, 1)) orelse continue;
const signed = (c.constInt(call.args[2]) orelse 0) != 0;
const key: Key3 = .{ c.component(inst.ty, signed), @intCast(mat.comp), @intCast(c.constInt(call.args[4]) orelse 0) };
const gop = try info.matvec.getOrPut(a, key);
if (!gop.found_existing) gop.value_ptr.* = 0;
gop.value_ptr.* |= layoutFlags(c, f, call.args[1]);
},
334, 322 => {
const r = c.matrix(inst.ty) orelse continue;
const ma = c.matrix(arg(c, f, fty, call.args, 1)) orelse continue;
const mb = c.matrix(arg(c, f, fty, call.args, 2)) orelse continue;
const key: Key4 = .{ @intCast(r.scope), @intCast(r.comp), @intCast(ma.comp), @intCast(mb.comp) };
const gop = try info.multiplies.getOrPut(a, key);
if (!gop.found_existing) gop.value_ptr.* = .empty;
try gop.value_ptr.put(a, .{ .m = ma.m, .n = mb.n, .k = ma.n }, {});
},
340 => {
const r = c.matrix(inst.ty) orelse continue;
const signed = (c.constInt(call.args[1]) orelse 0) != 0;
const vt = arg(c, f, fty, call.args, 2) orelse continue;
try info.outer.put(a, .{ @intCast(r.comp), c.component(vt, signed) }, {});
},
338, 339 => {
const mat = c.matrix(arg(c, f, fty, call.args, 1)) orelse continue;
const gop = try info.accumulate.getOrPut(a, @intCast(mat.comp));
if (!gop.found_existing) gop.value_ptr.* = 0;
gop.value_ptr.* |= if (op == 338) 1 else 2;
},
342 => {
const vt = arg(c, f, fty, call.args, 4) orelse continue;
const gop = try info.accumulate.getOrPut(a, c.component(vt, true));
if (!gop.found_existing) gop.value_ptr.* = 0;
gop.value_ptr.* |= 1;
},
else => {
try construction(a, &info, c.matrix(inst.ty));
for (call.args, 0..) |_, k| try construction(a, &info, c.matrix(arg(c, f, fty, call.args, k)));
},
}
}
}
return serialize(a, &info);
}
fn construction(a: Allocator, info: *Info, mat: ?Matrix) Allocator.Error!void {
const x = mat orelse return;
if (x.scope == 0) return; // Thread
const shape: Shape = .{
.m = if (x.use == 1) 0 else x.m,
.n = if (x.use == 0) 0 else x.n,
.k = if (x.use == 2) 0 else if (x.use == 0) x.n else x.m,
};
const gop = try info.constructions.getOrPut(a, .{ @intCast(x.comp), @intCast(x.use) });
if (!gop.found_existing) gop.value_ptr.* = .empty;
try gop.value_ptr.put(a, shape, {});
}
/// How a mat-vec multiply's matrix was loaded (both flags when unknown:
/// zdxc's matrices pass through local variables).
fn layoutFlags(c: anytype, f: *const module.Function, v0: module.Value) u8 {
var v = v0;
var flags: u8 = 0;
var steps: usize = 0;
while (steps < 64) : (steps += 1) {
if (v != .inst) return transposed | non_mul_optimal;
const inst = f.insts.items[v.inst];
if (inst.op != .call) return transposed | non_mul_optimal;
const call = inst.op.call;
const op = if (call.args.len > 0) c.constInt(call.args[0]) else null;
if (op == 324) {
v = call.args[1];
continue;
}
if (op == 325) {
const layout = c.constInt(call.args[4]) orelse return transposed | non_mul_optimal;
if (layout == 3) flags |= transposed else if (layout != 2) flags |= non_mul_optimal;
return flags;
}
return transposed | non_mul_optimal;
}
return transposed | non_mul_optimal;
}
fn lessShape(_: void, x: Shape, y: Shape) bool {
if (x.m != y.m) return x.m < y.m;
if (x.n != y.n) return x.n < y.n;
return x.k < y.k;
}
fn sortedShapes(a: Allocator, set: std.AutoArrayHashMapUnmanaged(Shape, void)) Allocator.Error![]Shape {
const out = try a.dupe(Shape, set.keys());
std.sort.insertion(Shape, out, {}, lessShape);
return out;
}
fn sortedKeys(comptime K: type, a: Allocator, keys: []const K) Allocator.Error![]K {
const out = try a.dupe(K, keys);
std.sort.insertion(K, out, {}, struct {
fn lt(_: void, x: K, y: K) bool {
return std.mem.order(u8, std.mem.asBytes(&x), std.mem.asBytes(&y)) == .lt;
}
}.lt);
return out;
}
const Writer = struct {
a: Allocator,
shapes: std.ArrayList(Shape) = .empty,
indices: std.ArrayList(u32) = .empty,
/// AddLinAlgShapes: shape table indexes, as a run in the semantic
/// index table (shared with an equal earlier run).
fn shapeRun(w: *Writer, shapes: []const Shape) Allocator.Error![2]u32 {
var idx: std.ArrayList(u32) = .empty;
for (shapes) |s| {
const k = for (w.shapes.items, 0..) |x, i| {
if (std.meta.eql(x, s)) break i;
} else blk: {
try w.shapes.append(w.a, s);
break :blk w.shapes.items.len - 1;
};
try idx.append(w.a, @intCast(k));
}
var off: usize = 0;
while (off + idx.items.len <= w.indices.items.len) : (off += 1) {
if (std.mem.eql(u32, w.indices.items[off..][0..idx.items.len], idx.items)) return .{ @intCast(off), @intCast(idx.items.len) };
}
const at: u32 = @intCast(w.indices.items.len);
try w.indices.appendSlice(w.a, idx.items);
return .{ at, @intCast(idx.items.len) };
}
};
fn put32(a: Allocator, out: *std.ArrayList(u8), v: u32) Allocator.Error!void {
var b: [4]u8 = undefined;
std.mem.writeInt(u32, &b, v, .little);
try out.appendSlice(a, &b);
}
fn serialize(a: Allocator, info: *Info) Allocator.Error!Tables {
var w: Writer = .{ .a = a };
var recs: [6]std.ArrayList(u8) = .{ .empty, .empty, .empty, .empty, .empty, .empty };
var counts: [6]u32 = .{ 0, 0, 0, 0, 0, 0 };
// (std::map order: keys sorted.)
for (try sortedKeys(Key2, a, info.constructions.keys())) |k| {
const run = try w.shapeRun(try sortedShapes(a, info.constructions.get(k).?));
try put32(a, &recs[0], run[0]);
try put32(a, &recs[0], run[1]);
try recs[0].appendSlice(a, &.{ k[0], 0, 0, 0 });
counts[0] += 1;
}
for (try sortedKeys(Key3, a, info.matvec.keys())) |k| {
try recs[1].appendSlice(a, &.{ k[0], k[1], k[2], info.matvec.get(k).? });
counts[1] += 1;
}
for (try sortedKeys(Key4, a, info.multiplies.keys())) |k| {
const run = try w.shapeRun(try sortedShapes(a, info.multiplies.get(k).?));
const t: usize = if (k[0] == 1) 2 else 3; // Wave, else ThreadGroup
try put32(a, &recs[t], run[0]);
try put32(a, &recs[t], run[1]);
try recs[t].appendSlice(a, &.{ k[1], k[2], k[3], 0 });
counts[t] += 1;
}
for (try sortedKeys(Key2, a, info.outer.keys())) |k| {
try recs[4].appendSlice(a, &.{ k[0], k[1], 0, 0 });
counts[4] += 1;
}
for (try sortedKeys(u8, a, info.accumulate.keys())) |k| {
try recs[5].appendSlice(a, &.{ k, info.accumulate.get(k).?, 0, 0 });
counts[5] += 1;
}
return .{
.shapes = w.shapes.items,
.records = .{ recs[0].items, recs[1].items, recs[2].items, recs[3].items, recs[4].items, recs[5].items },
.counts = counts,
.semantic_indices = w.indices.items,
};
}
/// The PSV0 LinAlg block: PSVLinAlgRuntimeInfo0, then each non-empty
/// table as its record size and records.
pub fn psvBlock(a: Allocator, t: Tables, out: *std.ArrayList(u8)) Allocator.Error!void {
try put32(a, out, 28); // sizeof(PSVLinAlgRuntimeInfo0)
try put32(a, out, @intCast(t.shapes.len));
for (t.counts) |n| try put32(a, out, n);
if (t.shapes.len > 0) {
try put32(a, out, 12);
for (t.shapes) |s| for ([_]u32{ s.m, s.n, s.k }) |v| try put32(a, out, v);
}
for (t.records, t.counts, t.sizes) |r, n, sz| if (n > 0) {
try put32(a, out, sz);
try out.appendSlice(a, r);
};
}

View File

@ -613,14 +613,14 @@ const Encoder = struct {
.load => |l| { .load => |l| {
try e.pushValueAndType(f, inst_id, l.ptr); try e.pushValueAndType(f, inst_id, l.ptr);
try e.push(inst.ty); try e.push(inst.ty);
try e.push(@as(u64, std.math.log2_int(u32, l.@"align")) + 1); try e.push(if (l.@"align" == 0) 0 else @as(u64, std.math.log2_int(u32, l.@"align")) + 1);
try e.push(0); try e.push(0);
try e.rec(20); try e.rec(20);
}, },
.store => |s| { .store => |s| {
try e.pushValueAndType(f, inst_id, s.ptr); try e.pushValueAndType(f, inst_id, s.ptr);
try e.pushValueAndType(f, inst_id, s.val); try e.pushValueAndType(f, inst_id, s.val);
try e.push(@as(u64, std.math.log2_int(u32, s.@"align")) + 1); try e.push(if (s.@"align" == 0) 0 else @as(u64, std.math.log2_int(u32, s.@"align")) + 1);
try e.push(0); try e.push(0);
try e.rec(44); try e.rec(44);
}, },

View File

@ -2,6 +2,7 @@
//! only covers an empty compute shader; later milestones feed it from the IR. //! only covers an empty compute shader; later milestones feed it from the IR.
const std = @import("std"); const std = @import("std");
const linalg_info = @import("linalg_info.zig");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const Module = @import("module.zig").Module; const Module = @import("module.zig").Module;
const container = @import("container.zig"); const container = @import("container.zig");
@ -150,6 +151,8 @@ pub const PsvInfo = struct {
max_vertex_count: u16 = 0, max_vertex_count: u16 = 0,
mesh_topology: u8 = 0, mesh_topology: u8 = 0,
uses_view_id: bool = false, uses_view_id: bool = false,
/// SM 6.10 linear algebra usage.
linalg: ?linalg_info.Tables = null,
}; };
pub fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32, resources: []const ResourceBind) ![]u8 { pub fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32, resources: []const ResourceBind) ![]u8 {
@ -194,6 +197,9 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
// Semantic index table, with runs shared between elements. // Semantic index table, with runs shared between elements.
var indices: std.ArrayList(u32) = .empty; var indices: std.ArrayList(u32) = .empty;
defer indices.deinit(gpa); defer indices.deinit(gpa);
// (Linear algebra shape runs come first, as in dxc.)
const linalg: ?linalg_info.Tables = if (info.linalg) |t| (if (t.empty()) null else t) else null;
if (linalg) |t| try indices.appendSlice(gpa, t.semantic_indices);
var records: std.ArrayList(u8) = .empty; var records: std.ArrayList(u8) = .empty;
defer records.deinit(gpa); defer records.deinit(gpa);
for ([_][]const signature.Element{ info.inputs, info.outputs, info.patch_constants }) |els| for (els) |e| { for ([_][]const signature.Element{ info.inputs, info.outputs, info.patch_constants }) |els| for (els) |e| {
@ -226,7 +232,7 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
try w(&buf, gpa, entry_off); try w(&buf, gpa, entry_off);
// PSVRuntimeInfo4 // PSVRuntimeInfo4
try w(&buf, gpa, info.groupshared_bytes); // NumBytesGroupSharedMemory try w(&buf, gpa, info.groupshared_bytes); // NumBytesGroupSharedMemory
try w(&buf, gpa, 0); // Flags try w(&buf, gpa, @intFromBool(linalg != null)); // Flags: LinAlgRuntimeInfoPresent
try w(&buf, gpa, @intCast(info.resources.len)); try w(&buf, gpa, @intCast(info.resources.len));
if (info.resources.len > 0) { if (info.resources.len > 0) {
@ -264,6 +270,7 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
// (domain). // (domain).
if (info.kind == .hull and pc_vectors > 0 and in_vectors > 0) try buf.appendNTimes(gpa, 0, tableDwords(in_vectors, pc_vectors) * 4); if (info.kind == .hull and pc_vectors > 0 and in_vectors > 0) try buf.appendNTimes(gpa, 0, tableDwords(in_vectors, pc_vectors) * 4);
if (info.kind == .domain and out_vectors[0] > 0 and pc_vectors > 0) try buf.appendNTimes(gpa, 0, tableDwords(pc_vectors, out_vectors[0]) * 4); if (info.kind == .domain and out_vectors[0] > 0 and pc_vectors > 0) try buf.appendNTimes(gpa, 0, tableDwords(pc_vectors, out_vectors[0]) * 4);
if (linalg) |t| try linalg_info.psvBlock(gpa, t, &buf);
return buf.toOwnedSlice(gpa); return buf.toOwnedSlice(gpa);
} }

View File

@ -184,6 +184,9 @@ pub const Param = struct {
ty: TypeId, ty: TypeId,
/// out / inout: passed as a pointer to caller storage. /// out / inout: passed as a pointer to caller storage.
by_ref: bool, by_ref: bool,
/// `groupshared` parameters: a pointer to the caller's groupshared
/// variable (by_ref too).
groupshared: bool = false,
/// in, out, inout (library function annotations). /// in, out, inout (library function annotations).
dir: enum { in, out, inout } = .in, dir: enum { in, out, inout } = .in,
/// The HLSL type (before patches become arrays), for mangled names. /// The HLSL type (before patches become arrays), for mangled names.

View File

@ -355,7 +355,7 @@ const Lowerer = struct {
for (f.params, 0..) |p, k| { for (f.params, 0..) |p, k| {
if (l.s.types.get(p.type) == .stream) continue; if (l.s.types.get(p.type) == .stream) continue;
const sem = if (k < f.decl.params.len) semanticOf(f.decl.params[k].semantics) else null; const sem = if (k < f.decl.params.len) semanticOf(f.decl.params[k].semantics) else null;
try params.append(l.arena, .{ .name = p.name, .ty = l.irType(p.type), .by_ref = p.dir != .in, .dir = switch (p.dir) { try params.append(l.arena, .{ .name = p.name, .ty = l.irType(p.type), .by_ref = p.dir != .in or p.groupshared, .groupshared = p.groupshared, .dir = switch (p.dir) {
.in => .in, .in => .in,
.out => .out, .out => .out,
.inout => .inout, .inout => .inout,
@ -404,14 +404,14 @@ const Lowerer = struct {
if (l.s.types.get(p.type) == .stream) continue; if (l.s.types.get(p.type) == .stream) continue;
const pty = l.irType(p.type); const pty = l.irType(p.type);
const mq = if (i < f.decl.params.len) f.decl.params[i].quals else ast.Qualifiers{}; const mq = if (i < f.decl.params.len) f.decl.params[i].quals else ast.Qualifiers{};
const space: ir.Space = if (mq.vertices or mq.indices or mq.primitives) .mesh else if (p.dir != .in) .function else .none; const space: ir.Space = if (mq.vertices or mq.indices or mq.primitives) .mesh else if (p.groupshared) .groupshared else if (p.dir != .in) .function else .none;
const pv = try l.b.add(.{ .op = .{ .param = ir_index }, .ty = pty, .ptr = space }); const pv = try l.b.add(.{ .op = .{ .param = ir_index }, .ty = pty, .ptr = space });
ir_index += 1; ir_index += 1;
if (p.dir == .in and isSpirvPointer(&l.s.types, p.type)) { if (p.dir == .in and isSpirvPointer(&l.s.types, p.type)) {
if (i < f.param_vars.len) if (f.param_vars[i]) |v| try l.value_vars.put(l.arena, v, pv); if (i < f.param_vars.len) if (f.param_vars[i]) |v| try l.value_vars.put(l.arena, v, pv);
continue; continue;
} }
const storage = if (p.dir != .in) pv else blk: { const storage = if (p.dir != .in or p.groupshared) pv else blk: {
const local = try l.b.add(.{ .op = .local_var, .ty = pty, .ptr = .function }); const local = try l.b.add(.{ .op = .local_var, .ty = pty, .ptr = .function });
try l.b.store(local, pv); try l.b.store(local, pv);
break :blk local; break :blk local;
@ -942,7 +942,7 @@ const Lowerer = struct {
if (l.value_vars.get(v)) |val| return val; if (l.value_vars.get(v)) |val| return val;
if (l.isSpecConstant(v)) return l.specConstant(v); if (l.isSpecConstant(v)) return l.specConstant(v);
// Integer `static const` scalars are constants. // Integer `static const` scalars are constants.
if (v.storage == .constant and v.init != null and l.s.types.get(v.type) == .scalar and !l.s.types.get(v.type).scalar.isFloat()) { if (v.storage == .constant and v.init != null and isIntConstantType(&l.s.types, v.type)) {
if (l.s.evalVarInt(v)) |val| return l.b.constInt(try l.concrete(e.ty), val); if (l.s.evalVarInt(v)) |val| return l.b.constInt(try l.concrete(e.ty), val);
} }
return l.b.load(try l.lvalue(e)); return l.b.load(try l.lvalue(e));
@ -1214,7 +1214,7 @@ const Lowerer = struct {
// A static member through an object. // A static member through an object.
if (r == .variable) { if (r == .variable) {
const v = r.variable; const v = r.variable;
if (v.storage == .constant and v.init != null and l.s.types.get(v.type) == .scalar and !l.s.types.get(v.type).scalar.isFloat()) { if (v.storage == .constant and v.init != null and isIntConstantType(&l.s.types, v.type)) {
if (l.s.evalVarInt(v)) |val| return l.b.constInt(try l.concrete(e.ty), val); if (l.s.evalVarInt(v)) |val| return l.b.constInt(try l.concrete(e.ty), val);
} }
return l.b.load(try l.variableLvalue(e, v)); return l.b.load(try l.variableLvalue(e, v));
@ -1413,7 +1413,11 @@ const Lowerer = struct {
for (args, f.params, 0..) |a, p, i| { for (args, f.params, 0..) |a, p, i| {
if (l.s.types.get(p.type) == .stream) continue; if (l.s.types.get(p.type) == .stream) continue;
n_vals += 1; n_vals += 1;
if (p.dir == .in) { if (p.groupshared) {
// The caller's groupshared variable itself.
vals[i] = try l.lvalue(a);
temps[i] = .none;
} else if (p.dir == .in) {
vals[i] = try l.converted(a, p.type); vals[i] = try l.converted(a, p.type);
} else { } else {
// Copy-in / copy-out through a temporary. // Copy-in / copy-out through a temporary.
@ -1429,7 +1433,7 @@ const Lowerer = struct {
if (isMethod(f)) try packed_vals.insert(l.arena, 0, object orelse (if (l.this_ptr != .none) l.this_ptr else return error.Unsupported)); if (isMethod(f)) try packed_vals.insert(l.arena, 0, object orelse (if (l.this_ptr != .none) l.this_ptr else return error.Unsupported));
const res = try l.b.add(.{ .op = .{ .call = .{ .func = fi, .args = packed_vals.items } }, .ty = ret_ty }); const res = try l.b.add(.{ .op = .{ .call = .{ .func = fi, .args = packed_vals.items } }, .ty = ret_ty });
for (args, f.params, 0..) |a, p, i| { for (args, f.params, 0..) |a, p, i| {
if (p.dir == .in or l.s.types.get(p.type) == .stream) continue; if (p.dir == .in or p.groupshared or l.s.types.get(p.type) == .stream) continue;
const back = try l.b.load(temps[i]); const back = try l.b.load(temps[i]);
try l.storeTo(a, try l.convert(back, a.ty)); try l.storeTo(a, try l.convert(back, a.ty));
} }
@ -1476,6 +1480,22 @@ const Lowerer = struct {
l.mesh_payload = args[3].ty; l.mesh_payload = args[3].ty;
return l.b.add(.{ .op = .{ .intrinsic = .{ .name = name, .args = vals } }, .ty = TypeTable.void_type }); return l.b.add(.{ .op = .{ .intrinsic = .{ .name = name, .args = vals } }, .ty = TypeTable.void_type });
} }
// SM 6.10 matrices: results go straight to the `out` /
// `ref` argument's storage; groupshared arrays by reference.
if (std.mem.startsWith(u8, name, "__builtin_LinAlg_")) {
const vals = try l.arena.alloc(Ref, args.len);
for (args, 0..) |a, i| {
const q = if (i < spec.params.len) spec.params[i].qual else .in;
const pt = it.params[i];
vals[i] = if (q != .in or l.s.types.get(a.ty) == .array)
try l.lvalue(a)
else if (pt == TypeTable.error_type or l.s.types.get(pt) == .resource)
try l.rvalue(a)
else
try l.converted(a, try l.concrete(pt));
}
return l.b.add(.{ .op = .{ .intrinsic = .{ .name = name, .args = vals } }, .ty = ret_ty });
}
// `out` parameters go through temporaries copied back // `out` parameters go through temporaries copied back
// afterwards; `ref` ones (atomic destinations) pass the // afterwards; `ref` ones (atomic destinations) pass the
// storage itself. // storage itself.
@ -2314,6 +2334,15 @@ pub fn saturatingInt(f: f64) i64 {
/// Non-static member functions take their object as a hidden first /// Non-static member functions take their object as a hidden first
/// parameter. /// parameter.
/// Integer (and enum) `static const` values are folded to constants.
fn isIntConstantType(t: *const TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.scalar => |sc| !sc.isFloat(),
.@"enum" => true,
else => false,
};
}
/// `vk::SpirvOpaqueType<OpTypePointer, ...>` (WorkgroupSpirvPointer). /// `vk::SpirvOpaqueType<OpTypePointer, ...>` (WorkgroupSpirvPointer).
fn isSpirvPointer(t: *const TypeTable, ty: TypeId) bool { fn isSpirvPointer(t: *const TypeTable, ty: TypeId) bool {
return t.get(ty) == .spirv and t.get(ty).spirv.opcode == 32; return t.get(ty) == .spirv and t.get(ty).spirv.opcode == 32;

View File

@ -1210,6 +1210,17 @@ pub const Sema = struct {
}; };
return s.types.intern(.{ .resource = .{ .kind = vn[1], .elem = elem, .name = n } }); return s.types.intern(.{ .resource = .{ .kind = vn[1], .elem = elem, .name = n } });
}; };
// An SM 6.10 matrix handle: its attributes are its type.
if (eql(n, "__builtin_LinAlgMatrix")) {
for (t.attrs) |a| if (eql(a.name, "__LinAlgMatrix_Attributes") and a.args.len == 5) {
var v: [5]u32 = undefined;
for (a.args, &v) |x, *o| o.* = @intCast(s.evalInt(x) orelse {
s.err(x.loc, "expression is not an integral constant expression", .{});
return TypeTable.error_type;
});
return s.types.intern(.{ .linalg = .{ .comp = v[0], .m = v[1], .n = v[2], .use = v[3], .scope = v[4] } });
};
}
// vk::SpirvType<opcode, size, alignment, operands...> and // vk::SpirvType<opcode, size, alignment, operands...> and
// vk::SpirvOpaqueType<opcode, operands...>. // vk::SpirvOpaqueType<opcode, operands...>.
if (s.opts.spirv and (eql(n, "SpirvType") or eql(n, "SpirvOpaqueType"))) return s.inlineSpirvType(t, eql(n, "SpirvType")); if (s.opts.spirv and (eql(n, "SpirvType") or eql(n, "SpirvOpaqueType"))) return s.inlineSpirvType(t, eql(n, "SpirvType"));

View File

@ -467,8 +467,13 @@ pub const Type = union(enum) {
/// `tex.mips` / `tex.sample` and their slices (`tex.mips[level]`). /// `tex.mips` / `tex.sample` and their slices (`tex.mips[level]`).
texture_view: struct { texture: TypeId, kind: enum { mips, mips_slice, sample, sample_slice } }, texture_view: struct { texture: TypeId, kind: enum { mips, mips_slice, sample, sample_slice } },
spirv: *const SpirvTypeInfo, spirv: *const SpirvTypeInfo,
/// `__builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use,
/// scope)]]` (SM 6.10): an opaque matrix handle.
linalg: LinAlgMatrix,
}; };
pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 };
/// Interns types. Ids 0 and 1 are `error` and `void`. /// Interns types. Ids 0 and 1 are `error` and `void`.
pub const TypeTable = struct { pub const TypeTable = struct {
gpa: Allocator, gpa: Allocator,
@ -514,6 +519,7 @@ pub const TypeTable = struct {
.descriptor_heap => |h| .{ .tag = 12, .a = @intFromBool(h.sampler), .b = 0 }, .descriptor_heap => |h| .{ .tag = 12, .a = @intFromBool(h.sampler), .b = 0 },
.dynamic_resource => .{ .tag = 13, .a = 0, .b = 0 }, .dynamic_resource => .{ .tag = 13, .a = 0, .b = 0 },
.texture_view => |v| .{ .tag = 14, .a = v.texture, .b = @backingInt(v.kind) }, .texture_view => |v| .{ .tag = 14, .a = v.texture, .b = @backingInt(v.kind) },
.linalg => |x| .{ .tag = 16, .a = (@as(u64, x.comp) << 32) | x.m, .b = (@as(u64, x.n) << 32) | (@as(u64, x.use) << 16) | x.scope },
.spirv => |x| .{ .tag = 15, .a = (@as(u64, x.opcode) << 32) | x.size, .b = std.hash.Wyhash.hash(x.alignment, std.mem.sliceAsBytes(x.operands)) }, .spirv => |x| .{ .tag = 15, .a = (@as(u64, x.opcode) << 32) | x.size, .b = std.hash.Wyhash.hash(x.alignment, std.mem.sliceAsBytes(x.operands)) },
}; };
} }
@ -703,6 +709,7 @@ pub const TypeTable = struct {
.sample_slice => "sample_slice_type", .sample_slice => "sample_slice_type",
} }), } }),
.spirv => |x| if (x.size == 0) "SpirvOpaqueType" else "SpirvType", .spirv => |x| if (x.size == 0) "SpirvOpaqueType" else "SpirvType",
.linalg => "__builtin_LinAlgMatrix",
}; };
} }
}; };

View File

@ -1942,7 +1942,7 @@ const Emitter = struct {
try e.cap(.variable_pointers); try e.cap(.variable_pointers);
if (e.spv_minor < 3) try e.extension("SPV_KHR_variable_pointers"); if (e.spv_minor < 3) try e.extension("SPV_KHR_variable_pointers");
} }
try params.append(e.arena, if (p.by_ref) try e.pointerType(.function, t) else t); try params.append(e.arena, if (p.by_ref) try e.pointerType(if (p.groupshared) .workgroup else .function, t) else t);
} }
const fn_ty = try e.functionType(ret, params.items); const fn_ty = try e.functionType(ret, params.items);
try e.b.emit(.functions, .function, &.{ ret, fn_id, 0, fn_ty }); try e.b.emit(.functions, .function, &.{ ret, fn_id, 0, fn_ty });