From 913c63d81033041bd8ff9fa676412138d2bf8383 Mon Sep 17 00:00:00 2001 From: Peter Li Date: Sat, 31 Oct 2026 12:55:12 -0700 Subject: [PATCH] Add templated byte-address Load/Store Load / Store of any numeric, struct or array type: one access per component at natural-alignment offsets (matrices by row in DXIL, by column in SPIR-V, as dxc). DXIL uses 64-bit raw buffer overloads from SM 6.3 and two words (makeDouble / splitDouble) before; SPIR-V assembles 64-bit values from word pairs and 16-bit ones from halves. DXIL locals and statics whose components have several sizes live in struct-typed memory; 16-bit values set the low-precision shader flag. Test files may give extra compiler flags with // FLAGS:. Co-Authored-By: Claude Opus 5.5 --- src/dxil/emit.zig | 170 +++++++++++++++++++++++-- src/spirv/emit.zig | 141 +++++++++++++++++++- test/dxil/byte_address_templated.hlsl | 20 +++ test/dxil/check.sh | 5 +- test/spirv/byte_address_templated.hlsl | 17 +++ test/spirv/check.sh | 3 +- 6 files changed, 338 insertions(+), 18 deletions(-) create mode 100644 test/dxil/byte_address_templated.hlsl create mode 100644 test/spirv/byte_address_templated.hlsl diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 1033c36..c80fd9f 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -140,6 +140,7 @@ const Emitter = struct { resources: std.ArrayList(Resource) = .empty, resource_of_global: std.AutoHashMapUnmanaged(u32, u32) = .empty, private_globals: std.AutoHashMapUnmanaged(u32, Ptr) = .empty, + private_typed: std.AutoHashMapUnmanaged(u32, @FieldType(Lowered, "typed")) = .empty, res_locals: std.ArrayList(?Lowered) = .empty, /// Indices marked with NonUniformResourceIndex. nonuniform: std.AutoHashMapUnmanaged(Value, void) = .empty, @@ -211,13 +212,19 @@ const Emitter = struct { return switch (s) { .bool => e.dm.intType(1), .int, .uint, .min16int, .min12int, .min16uint, .literal_int, .int8_4packed, .uint8_4packed => e.dm.intType(32), - .int16, .uint16 => e.dm.intType(16), + .int16, .uint16 => blk: { + e.uses_min_precision = true; + break :blk e.dm.intType(16); + }, .int64, .uint64 => blk: { e.uses_int64 = true; break :blk e.dm.intType(64); }, .float, .half, .min16float, .min10float, .literal_float => e.dm.getType(.float), - .float16 => e.dm.getType(.half), + .float16 => blk: { + e.uses_min_precision = true; + break :blk e.dm.getType(.half); + }, .double => blk: { e.uses_double = true; break :blk e.dm.getType(.double); @@ -225,6 +232,11 @@ const Emitter = struct { }; } + /// The scalar a component is kept as in struct-typed memory. + fn memScalar(s: Scalar) Scalar { + return if (s == .bool) .uint else storageScalar(s); + } + fn storageScalar(s: Scalar) Scalar { return switch (s) { .min16int, .min12int, .literal_int, .int8_4packed => .int, @@ -327,6 +339,7 @@ const Emitter = struct { e.prologue = .empty; e.next_id = 0; e.private_globals = .empty; + e.private_typed = .empty; e.nonuniform = .empty; const name = m.functions.items[pw].name; e.pc_fn = try e.dm.addFunction(.{ .name = name[0 .. name.len - ".wrapper".len], .ty = fn_ty, .num_blocks = 1 }); @@ -841,6 +854,16 @@ const Emitter = struct { // Static globals live in the entry function (everything is // inlined into it). if (e.m.globals.items[g].space == .private) { + const gty = e.m.globals.items[g].ty; + if (try e.mixedSizes(gty)) { + const tg = try e.private_typed.getOrPut(e.arena, g); + if (!tg.found_existing) { + const dty = try e.memoryType(gty); + const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } }); + tg.value_ptr.* = .{ .base = base, .dty = dty, .addr_space = 0, .ty = gty }; + } + return .{ .typed = tg.value_ptr.* }; + } const gop = try e.private_globals.getOrPut(e.arena, g); if (!gop.found_existing) gop.value_ptr.* = try e.alloca(e.m.globals.items[g].ty); return .{ .ptr = gop.value_ptr.* }; @@ -873,6 +896,12 @@ const Emitter = struct { try e.res_locals.append(e.arena, null); return .{ .res_local = @intCast(e.res_locals.items.len - 1) }; } + if (try e.mixedSizes(i.ty)) { + // Components of several sizes: a struct-typed alloca. + 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) } }); + return .{ .typed = .{ .base = base, .dty = dty, .addr_space = 0, .ty = i.ty } }; + } return .{ .ptr = try e.alloca(i.ty) }; }, .load => |p| switch (frame.vals[p.index()]) { @@ -1172,6 +1201,20 @@ const Emitter = struct { }; } + /// Whether `ty`'s components are of several sizes (kept in struct-typed + /// memory rather than a flat array). + fn mixedSizes(e: *Emitter, ty: TypeId) Error!bool { + if (e.t.get(ty) != .@"struct" and e.t.get(ty) != .array) return false; + const n = try e.flatCount(ty); + var size: ?u32 = null; + for (0..n) |k| { + const sz = memScalar(e.compOf(try e.componentType(ty, @intCast(k)))).size(); + if (size != null and size.? != sz) return true; + size = sz; + } + return false; + } + /// Whether `ty`'s components differ in type (all 32-bit), so storage is /// i32 with bitcasts. fn mixedStorage(e: *Emitter, ty: TypeId) Error!bool { @@ -2508,6 +2551,7 @@ const Emitter = struct { } const idx = (try e.scalars(frame, index_ref))[0]; if (res.kind == 12) return .{ .scalars = try e.structuredLoad(res.*, idx, 0, null, false, ty) }; + if (res.kind == 11 and !try e.simpleRaw(ty)) return .{ .scalars = try e.rawLoad(res.*, idx, ty) }; const n = try e.flatCount(ty); const c = try e.uniformScalar(ty); const mem_c = if (c == .bool) Scalar.uint else c; @@ -2549,12 +2593,118 @@ const Emitter = struct { return .{ .scalars = out }; } + /// Whether a byte-address Load/Store of `ty` is a single access of up + /// to four 32-bit components. + fn simpleRaw(e: *Emitter, ty: TypeId) Error!bool { + const n = try e.flatCount(ty); + if (n > 4 or e.t.get(ty) == .matrix) return false; + const c = e.uniformScalar(ty) catch return false; + return storageScalar(c).size() == 4; + } + + /// Byte offsets of the components of `ty` in a byte-address buffer + /// (templated Load / Store: natural alignment; dxc's DXIL lays + /// matrices out by row here, its SPIR-V by column). + fn rawOffset(e: *Emitter, ty: TypeId, k: u32) Error!u32 { + return layout.componentOffset(e.arena, e.t, ty, true, k, .dx_packed) catch e.unsupported("byte-address buffer accesses of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}); + } + + /// A templated byte-address Load: one raw load per component. + fn rawLoad(e: *Emitter, res: Resource, base: Value, ty: TypeId) Error![]const Value { + if (e.profile.minor < 2) return e.unsupported("templated loads of '{s}' need shader model 6.2", .{try e.t.format(e.arena, ty)}); + const i32t = try e.dm.intType(32); + const i8t = try e.dm.intType(8); + const undef_i32 = try e.dm.constant(.{ .ty = i32t, .kind = .undef }); + const out = try e.arena.alloc(Value, try e.flatCount(ty)); + for (out, 0..) |*o, k| { + const c = e.compOf(try e.componentType(ty, @intCast(k))); + const mem_c = if (c == .bool) Scalar.uint else storageScalar(c); + const addr = try e.intArith(.add, base, try e.i32Const(try e.rawOffset(ty, @intCast(k)))); + if (mem_c.size() == 8 and e.profile.minor < 3) { + // 64-bit overloads need SM 6.3: two words. + const ut = try e.scalarTy(.uint); + const rt = try e.resRetType(ut); + const fn_i = try e.dxOp("dx.op.rawBufferLoad.i32", rt, &.{ i32t, e.handle_ty, i32t, i32t, i8t, i32t }, .nounwind_readonly); + const call = try e.callOp(fn_i, rt, &.{ try e.i32Const(139), res.handle, addr, undef_i32, try e.dm.constInt(8, 3), try e.i32Const(4) }); + const lo = try e.add(ut, .{ .extractvalue = .{ .agg = call, .index = 0 } }); + const hi = try e.add(ut, .{ .extractvalue = .{ .agg = call, .index = 1 } }); + o.* = try e.joinWords(lo, hi, mem_c); + continue; + } + const st = try e.scalarTy(mem_c); + const ret_ty = try e.resRetType(st); + 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 call = try e.callOp(fn_i, ret_ty, &.{ try e.i32Const(139), res.handle, addr, undef_i32, try e.dm.constInt(8, 1), try e.i32Const(mem_c.size()) }); + const v = try e.add(st, .{ .extractvalue = .{ .agg = call, .index = 0 } }); + o.* = if (c == .bool) try e.convertScalar(v, .uint, .bool) else v; + } + return out; + } + + /// A 64-bit value from its low and high words (makeDouble for + /// doubles). + fn joinWords(e: *Emitter, lo: Value, hi: Value, c: Scalar) Error!Value { + const i32t = try e.dm.intType(32); + if (c == .double) { + const dt = try e.scalarTy(.double); + const fn_i = try e.dxOp("dx.op.makeDouble.f64", dt, &.{ i32t, i32t, i32t }, .nounwind_readnone); + return e.callOp(fn_i, dt, &.{ try e.i32Const(101), lo, hi }); + } + const i64t = try e.scalarTy(c); + const l = try e.add(i64t, .{ .cast = .{ .op = .zext, .val = lo } }); + const h = try e.add(i64t, .{ .cast = .{ .op = .zext, .val = hi } }); + const sh = try e.add(i64t, .{ .binop = .{ .op = .shl, .lhs = h, .rhs = try e.dm.constant(.{ .ty = i64t, .kind = .{ .int = 32 } }) } }); + return e.add(i64t, .{ .binop = .{ .op = .@"or", .lhs = sh, .rhs = l } }); + } + + /// The low and high words of a 64-bit value (splitDouble for doubles). + fn splitWords(e: *Emitter, v: Value, c: Scalar) Error![2]Value { + const i32t = try e.dm.intType(32); + if (c == .double) { + const st = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.splitdouble", .elems = &.{ i32t, i32t } } }); + const fn_i = try e.dxOp("dx.op.splitDouble.f64", st, &.{ i32t, try e.scalarTy(.double) }, .nounwind_readnone); + const r = try e.callOp(fn_i, st, &.{ try e.i32Const(102), v }); + return .{ try e.add(i32t, .{ .extractvalue = .{ .agg = r, .index = 0 } }), try e.add(i32t, .{ .extractvalue = .{ .agg = r, .index = 1 } }) }; + } + const i64t = try e.scalarTy(c); + const lo = try e.add(i32t, .{ .cast = .{ .op = .trunc, .val = v } }); + const sh = try e.add(i64t, .{ .binop = .{ .op = .lshr, .lhs = v, .rhs = try e.dm.constant(.{ .ty = i64t, .kind = .{ .int = 32 } }) } }); + return .{ lo, try e.add(i32t, .{ .cast = .{ .op = .trunc, .val = sh } }) }; + } + + fn rawStore(e: *Emitter, res: Resource, base: Value, ty: TypeId, vals: []const Value) Error!void { + if (e.profile.minor < 2) return e.unsupported("templated stores of '{s}' need shader model 6.2", .{try e.t.format(e.arena, ty)}); + const i32t = try e.dm.intType(32); + const i8t = try e.dm.intType(8); + const void_ty = try e.voidTy(); + const undef_i32 = try e.dm.constant(.{ .ty = i32t, .kind = .undef }); + for (vals, 0..) |v, k| { + const c = e.compOf(try e.componentType(ty, @intCast(k))); + const mem_c = if (c == .bool) Scalar.uint else storageScalar(c); + const addr = try e.intArith(.add, base, try e.i32Const(try e.rawOffset(ty, @intCast(k)))); + if (mem_c.size() == 8 and e.profile.minor < 3) { + const ut = try e.scalarTy(.uint); + const words = try e.splitWords(v, mem_c); + const undef_u = try e.dm.constant(.{ .ty = ut, .kind = .undef }); + const fn_i = try e.dxOp("dx.op.rawBufferStore.i32", void_ty, &.{ i32t, e.handle_ty, i32t, i32t, ut, ut, ut, ut, i8t, i32t }, .nounwind); + _ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(140), res.handle, addr, undef_i32, words[0], words[1], undef_u, undef_u, try e.dm.constInt(8, 3), try e.i32Const(4) }); + continue; + } + const st = try e.scalarTy(mem_c); + const undef_v = try e.dm.constant(.{ .ty = st, .kind = .undef }); + 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); + const sv = if (c == .bool) try e.convertScalar(v, .bool, .uint) else v; + _ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(140), res.handle, addr, undef_i32, sv, undef_v, undef_v, undef_v, try e.dm.constInt(8, 1), try e.i32Const(mem_c.size()) }); + } + } + fn resourceStore(e: *Emitter, frame: *Frame, res_ref: Ref, index_ref: Ref, value_ref: Ref) Error!void { const res = try e.resourceOf(frame, res_ref); if (res.kind >= 1 and res.kind <= 9) return e.textureStore(res.*, try e.scalars(frame, index_ref), try e.scalars(frame, value_ref), frame.f.inst(value_ref).ty); const idx = (try e.scalars(frame, index_ref))[0]; const vals = try e.scalars(frame, value_ref); if (res.kind == 12) return e.structuredStore(res.*, idx, 0, null, false, frame.f.inst(value_ref).ty, vals); + if (res.kind == 11 and !try e.simpleRaw(frame.f.inst(value_ref).ty)) return e.rawStore(res.*, idx, 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; @@ -2944,9 +3094,9 @@ const Emitter = struct { /// and matrices (by row) become arrays, bools 32-bit integers. fn memoryType(e: *Emitter, ty: TypeId) Error!DType { return switch (e.t.get(ty)) { - .scalar, .@"enum" => e.scalarTy(storageScalar(e.compOf(ty))), - .vector => |v| e.dm.getType(.{ .array = .{ .len = v.len, .elem = try e.scalarTy(storageScalar(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(storageScalar(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))) } }), + .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))) } }) } }), .array => |a| e.dm.getType(.{ .array = .{ .len = a.len, .elem = try e.memoryType(a.elem) } }), .@"struct" => |st| blk: { const elems = try e.arena.alloc(DType, st.fields.items.len); @@ -2966,7 +3116,7 @@ const Emitter = struct { fn memLayout(e: *Emitter, ty: TypeId) Error![2]u32 { switch (e.t.get(ty)) { .scalar, .@"enum", .vector, .matrix => { - const sz = storageScalar(e.compOf(ty)).size(); + const sz = memScalar(e.compOf(ty)).size(); return .{ sz * (e.t.componentCount(ty) orelse 1), sz }; }, .array => |a| { @@ -3025,8 +3175,8 @@ const Emitter = struct { const out = try e.arena.alloc(Value, paths.items.len); for (out, paths.items, 0..) |*o, sub, c| { const ct = e.compOf(try e.componentType(ty, @intCast(c))); - const st = try e.scalarTy(storageScalar(ct)); - const raw = try e.add(st, .{ .load = .{ .ptr = try e.typedScalarPtr(tp, sub, st), .@"align" = 4 } }); + 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() } }); o.* = if (ct == .bool) try e.add(try e.dm.intType(1), .{ .cmp = .{ .pred = 33, .lhs = raw, .rhs = try e.i32Const(0) } }) else raw; } return .{ .scalars = out }; @@ -3037,9 +3187,9 @@ const Emitter = struct { try e.scalarPaths(ty, &.{}, &paths); for (vals, paths.items, 0..) |v, sub, c| { const ct = e.compOf(try e.componentType(ty, @intCast(c))); - const st = try e.scalarTy(storageScalar(ct)); + const st = try e.scalarTy(memScalar(ct)); 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" = 4 } }); + _ = try e.add(try e.voidTy(), .{ .store = .{ .ptr = try e.typedScalarPtr(tp, sub, st), .val = sv, .@"align" = memScalar(ct).size() } }); } } diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index a1734f1..6041791 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -1773,6 +1773,7 @@ const Emitter = struct { const st = try e.t.scalar(vec.elem); return .{ if (vec.len == 1) v else try e.op1(.composite_extract, st, &.{ v, k }), st }; }, + .matrix => |m| return .{ try e.elementAt(v, ty, k / m.cols, k % m.cols), try e.t.scalar(m.elem) }, .array => |a| { const n = e.t.componentCount(a.elem).?; return e.flatComponent(try e.op1(.composite_extract, a.elem, &.{ v, k / n }), a.elem, k % n); @@ -1786,7 +1787,7 @@ const Emitter = struct { } return e.unsupported("internal: component out of range", .{}); }, - else => return e.unsupported("mesh outputs of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}), + else => return e.unsupported("values of type '{s}' are not supported here yet", .{try e.t.format(e.arena, ty)}), } } @@ -2339,16 +2340,19 @@ const Emitter = struct { }.f; const off = try e.convert(e.val(args[0]), e.f.inst(args[0]).ty, uint_ty); if (std.mem.startsWith(u8, name, "Load") and args.len == 1) { - const n = e.t.componentCount(ty) orelse return e.unsupported("templated Load is not supported yet", .{}); - if (e.t.component(ty) != .uint) return e.unsupported("templated Load is not supported yet", .{}); + if (e.t.component(ty) != .uint or e.t.get(ty) == .matrix) return e.rawLoad(e.val(res), off, ty); + const n = e.t.componentCount(ty).?; const parts = try e.arena.alloc(Id, n); for (parts, 0..) |*p, k| p.* = try e.op1(.load, uint_ty, &.{try word(e, e.val(res), off, @intCast(k))}); return if (n == 1) parts[0] else e.op1(.composite_construct, ty, parts); } if (std.mem.startsWith(u8, name, "Store") and args.len == 2) { const vty = e.f.inst(args[1]).ty; - const n = e.t.componentCount(vty) orelse return e.unsupported("templated Store is not supported yet", .{}); - if (e.t.component(vty) != .uint) return e.unsupported("templated Store is not supported yet", .{}); + if (e.t.component(vty) != .uint or e.t.get(vty) == .matrix) { + try e.rawStore(e.val(res), off, vty, e.val(args[1])); + return 0; + } + const n = e.t.componentCount(vty).?; for (0..n) |k| { const v = if (n == 1) e.val(args[1]) else try e.op1(.composite_extract, uint_ty, &.{ e.val(args[1]), @intCast(k) }); try e.b.emit(.functions, .store, &.{ try word(e, e.val(res), off, @intCast(k)), v }); @@ -2363,6 +2367,133 @@ const Emitter = struct { return e.unsupported("method '{s}' is not supported yet", .{name}); } + /// Pointer to the 32-bit word holding byte `addr` of a byte-address + /// buffer. + fn rawWord(e: *Emitter, buf: Id, addr: Id) Error!Id { + const ut = try e.t.scalar(.uint); + const idx = try e.op1(.shift_right_logical, ut, &.{ addr, try e.constUint(2) }); + return e.opRaw(.access_chain, try e.pointerType(e.bufferSc(), try e.scalarType(.uint)), &.{ buf, try e.constInt(0), idx }); + } + + /// The scalar type and byte offset of flattened component `k` of a + /// value of `ty` in a byte-address buffer (natural alignment). + fn rawComponent(e: *Emitter, ty: TypeId, k: u32) Error!struct { TypeId, u32 } { + const off = layout.componentOffset(e.arena, e.t, ty, false, k, .dx_packed) catch return e.unsupported("byte-address buffer accesses of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}); + var cur = ty; + var kk = k; + while (true) switch (e.t.get(cur)) { + .scalar, .@"enum" => return .{ cur, off }, + .vector, .matrix => return .{ try e.t.scalar(e.t.component(cur).?), off }, + .array => |a| { + const n = e.t.componentCount(a.elem) orelse return e.unsupported("byte-address buffer accesses of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}); + kk %= n; + cur = a.elem; + }, + .@"struct" => |st| { + for (st.fields.items) |fld| { + const n = e.t.componentCount(fld.type).?; + if (kk < n) { + cur = fld.type; + break; + } + kk -= n; + } + }, + else => return e.unsupported("byte-address buffer accesses of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}), + }; + } + + /// A templated byte-address Load: 32-bit words, combined for 64-bit + /// components and split for 16-bit ones. + fn rawLoad(e: *Emitter, buf: Id, base: Id, ty: TypeId) Error!Id { + const ut = try e.t.scalar(.uint); + const n = e.t.componentCount(ty) orelse return e.unsupported("byte-address buffer accesses of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}); + const comps = try e.arena.alloc(Id, n); + for (comps, 0..) |*c, k| { + const rc = try e.rawComponent(ty, @intCast(k)); + const sc = rc[0]; + const addr = try e.op1(.i_add, ut, &.{ base, try e.constUint(rc[1]) }); + const w0 = try e.op1(.load, ut, &.{try e.rawWord(buf, addr)}); + const comp = storageScalar(e.t.component(sc).?); + c.* = switch (comp.size()) { + 8 => blk: { + const addr1 = try e.op1(.i_add, ut, &.{ addr, try e.constUint(4) }); + const w1 = try e.op1(.load, ut, &.{try e.rawWord(buf, addr1)}); + const pair = try e.op1(.composite_construct, try e.t.vector(.uint, 2), &.{ w0, w1 }); + break :blk try e.op1(.bitcast, sc, &.{pair}); + }, + 2 => blk: { + const shift = try e.op1(.shift_left_logical, ut, &.{ try e.op1(.bitwise_and, ut, &.{ addr, try e.constUint(2) }), try e.constUint(3) }); + const bits = try e.op1(.shift_right_logical, ut, &.{ w0, shift }); + const u16t = try e.t.scalar(.uint16); + const h = try e.op1(.u_convert, u16t, &.{bits}); + break :blk if (comp == .uint16) h else try e.op1(.bitcast, sc, &.{h}); + }, + else => if (comp == .uint) w0 else if (comp == .bool) try e.convert(w0, ut, sc) else try e.op1(.bitcast, sc, &.{w0}), + }; + } + return e.composeFlat(ty, comps); + } + + fn rawStore(e: *Emitter, buf: Id, base: Id, ty: TypeId, v: Id) Error!void { + const ut = try e.t.scalar(.uint); + const n = e.t.componentCount(ty) orelse return e.unsupported("byte-address buffer accesses of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}); + for (0..n) |k| { + const rc = try e.rawComponent(ty, @intCast(k)); + const sc = rc[0]; + const x = (try e.flatComponent(v, ty, @intCast(k)))[0]; + const addr = try e.op1(.i_add, ut, &.{ base, try e.constUint(rc[1]) }); + const comp = storageScalar(e.t.component(sc).?); + switch (comp.size()) { + 8 => { + const pair = try e.op1(.bitcast, try e.t.vector(.uint, 2), &.{x}); + try e.b.emit(.functions, .store, &.{ try e.rawWord(buf, addr), try e.op1(.composite_extract, ut, &.{ pair, 0 }) }); + const addr1 = try e.op1(.i_add, ut, &.{ addr, try e.constUint(4) }); + try e.b.emit(.functions, .store, &.{ try e.rawWord(buf, addr1), try e.op1(.composite_extract, ut, &.{ pair, 1 }) }); + }, + 2 => { + // Replace the half of the word (not atomic, as dxc). + const u16t = try e.t.scalar(.uint16); + const h = if (comp == .uint16) x else try e.op1(.bitcast, u16t, &.{x}); + const wide = try e.op1(.u_convert, ut, &.{h}); + const shift = try e.op1(.shift_left_logical, ut, &.{ try e.op1(.bitwise_and, ut, &.{ addr, try e.constUint(2) }), try e.constUint(3) }); + const ptr = try e.rawWord(buf, addr); + const old = try e.op1(.load, ut, &.{ptr}); + const keep = try e.op1(.bitwise_and, ut, &.{ old, try e.op1(.not_, ut, &.{try e.op1(.shift_left_logical, ut, &.{ try e.constUint(0xFFFF), shift })}) }); + try e.b.emit(.functions, .store, &.{ ptr, try e.op1(.bitwise_or, ut, &.{ keep, try e.op1(.shift_left_logical, ut, &.{ wide, shift }) }) }); + }, + else => { + const w = if (comp == .uint) x else if (comp == .bool) try e.convert(x, sc, ut) else try e.op1(.bitcast, ut, &.{x}); + try e.b.emit(.functions, .store, &.{ try e.rawWord(buf, addr), w }); + }, + } + } + } + + /// A value of `ty` from its flattened scalar components. + fn composeFlat(e: *Emitter, ty: TypeId, comps: []const Id) Error!Id { + switch (e.t.get(ty)) { + .scalar, .@"enum", .vector, .matrix => return e.fromScalars(ty, comps), + .array => |a| { + const n = e.t.componentCount(a.elem).?; + const parts = try e.arena.alloc(Id, a.len); + for (parts, 0..) |*p, k| p.* = try e.composeFlat(a.elem, comps[k * n ..][0..n]); + return e.op1(.composite_construct, ty, parts); + }, + .@"struct" => |st| { + const parts = try e.arena.alloc(Id, st.fields.items.len); + var at: usize = 0; + for (parts, st.fields.items) |*p, fld| { + const n = e.t.componentCount(fld.type).?; + p.* = try e.composeFlat(fld.type, comps[at..][0..n]); + at += n; + } + return e.op1(.composite_construct, ty, parts); + }, + else => return e.unsupported("values of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}), + } + } + fn getDimensions(e: *Emitter, res: Ref, r: @FieldType(types.Type, "resource"), args: []const Ref) Error!void { const uint_ty = try e.t.scalar(.uint); const store = struct { diff --git a/test/dxil/byte_address_templated.hlsl b/test/dxil/byte_address_templated.hlsl new file mode 100644 index 0000000..374b502 --- /dev/null +++ b/test/dxil/byte_address_templated.hlsl @@ -0,0 +1,20 @@ +// PROFILE: cs_6_2 +// FLAGS: -enable-16bit-types +// Templated byte-address Load/Store of structs, matrices (by row in +// DXIL), 16- and 64-bit components (two words before SM 6.3); locals with +// components of several sizes in struct-typed memory. +// ZCHECK: call double @dx.op.makeDouble.f64(i32 101 +// ZCHECK: rawBufferLoad.f16 +struct S { float a; double b; uint16_t c; int2 d; }; +RWByteAddressBuffer buf : register(u0); +[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) { + S s = buf.Load(i * 32); + float3x2 m = buf.Load(64); + half4 h = buf.Load(128); + S arr[2] = buf.Load(256); + s.a += m[1][0] + h.y + arr[1].d.x; + buf.Store(i * 32 + 512, s); + buf.Store(96, m); + buf.Store(136, h); + buf.Store(160, s.b); +} diff --git a/test/dxil/check.sh b/test/dxil/check.sh index 15eb955..00e2edb 100644 --- a/test/dxil/check.sh +++ b/test/dxil/check.sh @@ -25,8 +25,9 @@ sigtables() { for f in test/dxil/*.hlsl; do profile=$(sed -n 's|^// PROFILE: *||p' "$f") + flags=$(sed -n 's|^// FLAGS: *||p' "$f") name=$(basename "$f" .hlsl) - if ! "$ZDXC" -T "$profile" "$f" -Fo "$TMP/z.dxo" > "$TMP/log" 2>&1; then + if ! "$ZDXC" -T "$profile" $flags "$f" -Fo "$TMP/z.dxo" > "$TMP/log" 2>&1; then fail=$((fail + 1)); echo "FAIL $name: zdxc failed"; head -3 "$TMP/log"; continue fi if ! "$DXV" "$TMP/z.dxo" > "$TMP/log" 2>&1; then @@ -34,7 +35,7 @@ for f in test/dxil/*.hlsl; do fi "$DXC" -dumpbin "$TMP/z.dxo" > "$TMP/z.ll" 2>&1 rm -f "$TMP/d.ll" - if ! "$DXC" -T "$profile" "$f" -Fc "$TMP/d.ll" > "$TMP/log" 2>&1; then + if ! "$DXC" -T "$profile" $flags "$f" -Fc "$TMP/d.ll" > "$TMP/log" 2>&1; then fail=$((fail + 1)); echo "FAIL $name: dxc rejects this test"; head -3 "$TMP/log"; continue fi ok=1 diff --git a/test/spirv/byte_address_templated.hlsl b/test/spirv/byte_address_templated.hlsl new file mode 100644 index 0000000..80d0777 --- /dev/null +++ b/test/spirv/byte_address_templated.hlsl @@ -0,0 +1,17 @@ +// PROFILE: cs_6_2 +// FLAGS: -enable-16bit-types +// Templated byte-address Load/Store of structs, matrices (by column in +// SPIR-V), 16- and 64-bit components from 32-bit words. +struct S { float a; double b; uint16_t c; int2 d; }; +RWByteAddressBuffer buf : register(u0); +[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) { + S s = buf.Load(i * 32); + float3x2 m = buf.Load(64); + half4 h = buf.Load(128); + S arr[2] = buf.Load(256); + s.a += m[1][0] + h.y + arr[1].d.x; + buf.Store(i * 32 + 512, s); + buf.Store(96, m); + buf.Store(136, h); + buf.Store(160, s.b); +} diff --git a/test/spirv/check.sh b/test/spirv/check.sh index 6d5e14c..f236e1c 100644 --- a/test/spirv/check.sh +++ b/test/spirv/check.sh @@ -15,8 +15,9 @@ pass=0 fail=0 for f in test/spirv/*.hlsl; do profile=$(sed -n 's|^// PROFILE: *||p' "$f") + flags=$(sed -n 's|^// FLAGS: *||p' "$f") name=$(basename "$f" .hlsl) - env=$(sed -n "s|^// ENV: *||p" "$f"); if ! "$ZDXC" -spirv -T "$profile" -fspv-target-env="${env:-vulkan1.0}" "$f" -Fo "$TMP/z.spv" > "$TMP/log" 2>&1; then + env=$(sed -n "s|^// ENV: *||p" "$f"); if ! "$ZDXC" -spirv -T "$profile" $flags -fspv-target-env="${env:-vulkan1.0}" "$f" -Fo "$TMP/z.spv" > "$TMP/log" 2>&1; then fail=$((fail + 1)); echo "FAIL $name: zdxc failed"; head -3 "$TMP/log"; continue fi if ! "$VAL" --target-env "$(printf '%s' "${env:-vulkan1.0}" | sed 's/spirv1/spv1/')" --relax-block-layout "$TMP/z.spv" > "$TMP/log" 2>&1; then