diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 5fa076e..cd5bb31 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -316,6 +316,10 @@ const Emitter = struct { /// Each HLSL struct's module type (struct types are named, and two /// structs may share a name: `A::In`, `A::In`). struct_types: std.AutoHashMapUnmanaged(TypeId, DType) = .empty, + /// Per type: see structComps, mixedSizes and mixedStorage. + struct_comps: std.AutoHashMapUnmanaged(TypeId, []const TypeId) = .empty, + mixed_sizes: std.AutoHashMapUnmanaged(TypeId, bool) = .empty, + mixed_storage: std.AutoHashMapUnmanaged(TypeId, bool) = .empty, /// Prologue instructions dropped again if unused (resource handles). lib_removable: std.AutoHashMapUnmanaged(u32, void) = .empty, @@ -417,15 +421,25 @@ const Emitter = struct { .vector => |v| v.len, .matrix => |m| @as(u32, m.rows) * m.cols, .array => |a| a.len * try e.flatCount(a.elem), - .@"struct" => |s| blk: { - var n: u32 = 0; - for (s.fields.items) |f| n += try e.flatCount(f.type); - break :blk n; - }, + .@"struct" => @intCast((try e.structComps(ty)).len), else => e.unsupported("values of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}), }; } + /// The scalar type of each flattened component of struct `ty`, worked + /// out once per type. + fn structComps(e: *Emitter, ty: TypeId) Error![]const TypeId { + if (e.struct_comps.get(ty)) |c| return c; + var out: std.ArrayList(TypeId) = .empty; + for (e.t.get(ty).@"struct".fields.items) |f| { + const n = try e.flatCount(f.type); + try out.ensureUnusedCapacity(e.arena, n); + for (0..n) |k| out.appendAssumeCapacity(try e.componentType(f.type, @intCast(k))); + } + try e.struct_comps.put(e.arena, ty, out.items); + return out.items; + } + /// Undefined values for the flattened components of `ty`. fn undefValues(e: *Emitter, ty: TypeId) Error![]const Value { var out: std.ArrayList(Value) = .empty; @@ -1375,6 +1389,11 @@ const Emitter = struct { return if (x == .inst) .{ .inst = mp[x.inst] } else x; } fn vs(a: Allocator, mp: []const u32, xs: []const Value) Allocator.Error![]const Value { + // (Nothing to renumber, as in most getelementptr indices: + // the slice is kept; no pass writes operand slices.) + for (xs) |x| { + if (x == .inst) break; + } else return xs; const out = try a.alloc(Value, xs.len); for (xs, out) |x, *o| o.* = v(mp, x); return out; @@ -1383,8 +1402,8 @@ const Emitter = struct { stats.add(.dxil_lowered, n); try f.insts.ensureUnusedCapacity(e.dm.allocator(), n); const all = [_][]const PInst{e.prologue.items}; - for (all) |items| for (items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap)); - for (e.blocks.items) |blk| for (blk.items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap)); + for (all) |items| for (items) |pi| f.insts.appendAssumeCapacity(try remapInst(e.arena, map, pi.inst, remap)); + for (e.blocks.items) |blk| for (blk.items) |pi| f.insts.appendAssumeCapacity(try remapInst(e.arena, map, pi.inst, remap)); var ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty; var it = e.dyn_ranges.iterator(); while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*); @@ -2752,6 +2771,18 @@ const Emitter = struct { /// 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; + if (e.mixed_sizes.get(ty)) |v| return v; + const v = try e.checkMixedSizes(ty); + try e.mixed_sizes.put(e.arena, ty, v); + return v; + } + + fn checkMixedSizes(e: *Emitter, ty: TypeId) Error!bool { + // (An array's components repeat its element's.) + if (e.t.get(ty) == .array) { + const arr = e.t.get(ty).array; + return arr.len > 0 and try e.mixedSizes(arr.elem); + } const n = try e.flatCount(ty); var size: ?u32 = null; for (0..n) |k| { @@ -2765,6 +2796,17 @@ const Emitter = struct { /// Whether `ty`'s components differ in type (all 32-bit), so storage is /// i32 with bitcasts. fn mixedStorage(e: *Emitter, ty: TypeId) Error!bool { + if (e.mixed_storage.get(ty)) |v| return v; + const v = try e.checkMixedStorage(ty); + try e.mixed_storage.put(e.arena, ty, v); + return v; + } + + fn checkMixedStorage(e: *Emitter, ty: TypeId) Error!bool { + if (e.t.get(ty) == .array) { + const arr = e.t.get(ty).array; + return arr.len > 0 and try e.mixedStorage(arr.elem); + } const n = try e.flatCount(ty); var first: ?Scalar = null; var mixed = false; @@ -3799,14 +3841,10 @@ const Emitter = struct { .scalar, .@"enum", .linalg => return ty, .vector, .matrix => return e.t.scalar(e.t.component(ty).?), .array => |a| return e.componentType(a.elem, k % try e.flatCount(a.elem)), - .@"struct" => |s| { - var kk = k; - for (s.fields.items) |f| { - const n = try e.flatCount(f.type); - if (kk < n) return e.componentType(f.type, kk); - kk -= n; - } - return e.unsupported("struct component", .{}); + .@"struct" => { + const comps = try e.structComps(ty); + if (k >= comps.len) return e.unsupported("struct component", .{}); + return comps[k]; }, else => return e.unsupported("component type", .{}), } diff --git a/src/dxil/module.zig b/src/dxil/module.zig index c107fd2..07a84ee 100644 --- a/src/dxil/module.zig +++ b/src/dxil/module.zig @@ -39,6 +39,36 @@ pub const Type = union(enum) { } }; +/// Hashes what Type.eql compares. +const TypeContext = struct { + pub fn hash(_: TypeContext, t: Type) u64 { + var h: std.hash.Wyhash = .init(@backingInt(t)); + switch (t) { + .void, .label, .metadata, .half, .float, .double => {}, + .int => |w| h.update(std.mem.asBytes(&w)), + .pointer => |p| h.update(std.mem.asBytes(&[2]u32{ p.elem, p.addr_space })), + .function => |f| { + h.update(std.mem.asBytes(&f.ret)); + h.update(std.mem.sliceAsBytes(f.params)); + }, + .@"struct" => |st| h.update(st.name), + .array => |x| { + h.update(std.mem.asBytes(&x.len)); + h.update(std.mem.asBytes(&x.elem)); + }, + .vector => |x| h.update(std.mem.asBytes(&[2]u32{ x.len, x.elem })), + } + return h.final(); + } + + pub fn eql(_: TypeContext, a: Type, b: Type) bool { + return a.eql(b); + } +}; + +const no_type = std.math.maxInt(TypeId); +const no_const = std.math.maxInt(ConstId); + pub const Constant = struct { ty: TypeId, kind: union(enum) { @@ -52,6 +82,29 @@ pub const Constant = struct { }, }; +/// Constants are equal when their type and kind are (aggregates: the same +/// element slice, as std.meta.eql compares slices). +const ConstantContext = struct { + pub fn hash(_: ConstantContext, c: Constant) u64 { + var h: std.hash.Wyhash = .init(c.ty); + h.update(std.mem.asBytes(&@as(u8, @backingInt(c.kind)))); + switch (c.kind) { + .int => |v| h.update(std.mem.asBytes(&v)), + .float_bits => |v| h.update(std.mem.asBytes(&v)), + .undef, .null => {}, + .aggregate => |a| { + h.update(std.mem.asBytes(&@intFromPtr(a.ptr))); + h.update(std.mem.asBytes(&a.len)); + }, + } + return h.final(); + } + + pub fn eql(_: ConstantContext, a: Constant, b: Constant) bool { + return a.ty == b.ty and std.meta.eql(a.kind, b.kind); + } +}; + pub const Linkage = enum(u32) { external = 0, internal = 3 }; /// Attribute group for function declarations (e.g. dx.op functions). @@ -134,8 +187,15 @@ pub const Module = struct { triple: []const u8 = "dxil-ms-dx", datalayout: []const u8 = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64", types: std.ArrayList(Type) = .empty, + /// Index of `types`, for getType to find existing ones. + type_ids: std.HashMapUnmanaged(Type, TypeId, TypeContext, std.hash_map.default_max_load_percentage) = .empty, constants: std.ArrayList(Constant) = .empty, + /// Index of `constants`, for constant() to find existing ones. + constant_ids: std.HashMapUnmanaged(Constant, ConstId, ConstantContext, std.hash_map.default_max_load_percentage) = .empty, functions: std.ArrayList(Function) = .empty, + /// intType's and constInt's results for common arguments. + int_types: [65]TypeId = @splat(no_type), + small_i32: [1024]ConstId = @splat(no_const), globals: std.ArrayList(GlobalVar) = .empty, metadata: std.ArrayList(Metadata) = .empty, named_metadata: std.ArrayList(struct { name: []const u8, nodes: []const MdId }) = .empty, @@ -155,9 +215,7 @@ pub const Module = struct { } pub fn getType(m: *Module, t: Type) !TypeId { - for (m.types.items, 0..) |existing, i| { - if (existing.eql(t)) return @intCast(i); - } + if (m.type_ids.get(t)) |id| return id; const a = m.allocator(); var owned = t; switch (owned) { @@ -168,11 +226,18 @@ pub const Module = struct { }, else => {}, } + const id: TypeId = @intCast(m.types.items.len); + try m.type_ids.ensureUnusedCapacity(a, 1); try m.types.append(a, owned); - return @intCast(m.types.items.len - 1); + m.type_ids.putAssumeCapacity(owned, id); + return id; } pub fn intType(m: *Module, bits: u32) !TypeId { + if (bits < m.int_types.len) { + if (m.int_types[bits] == no_type) m.int_types[bits] = try m.getType(.{ .int = bits }); + return m.int_types[bits]; + } return m.getType(.{ .int = bits }); } @@ -200,14 +265,23 @@ pub const Module = struct { } pub fn constant(m: *Module, c: Constant) !Value { - for (m.constants.items, 0..) |existing, i| { - if (existing.ty == c.ty and std.meta.eql(existing.kind, c.kind)) return .{ .constant = @intCast(i) }; + const gop = try m.constant_ids.getOrPut(m.allocator(), c); + if (!gop.found_existing) { + gop.value_ptr.* = @intCast(m.constants.items.len); + m.constants.append(m.allocator(), c) catch |err| { + m.constant_ids.removeByPtr(gop.key_ptr); + return err; + }; } - try m.constants.append(m.allocator(), c); - return .{ .constant = @intCast(m.constants.items.len - 1) }; + return .{ .constant = gop.value_ptr.* }; } pub fn constInt(m: *Module, bits: u32, v: i64) !Value { + if (bits == 32 and v >= 0 and v < m.small_i32.len) { + const k: usize = @intCast(v); + if (m.small_i32[k] == no_const) m.small_i32[k] = (try m.constant(.{ .ty = try m.intType(32), .kind = .{ .int = v } })).constant; + return .{ .constant = m.small_i32[k] }; + } return m.constant(.{ .ty = try m.intType(bits), .kind = .{ .int = v } }); } diff --git a/src/dxil/unroll.zig b/src/dxil/unroll.zig index 149ffb7..634eceb 100644 --- a/src/dxil/unroll.zig +++ b/src/dxil/unroll.zig @@ -49,18 +49,64 @@ const Cfg = struct { succs: [][]u32, preds: [][]u32, idom: []u32, + /// Each reachable block's interval in a depth-first walk of the + /// dominator tree (`none` for unreachable blocks): `d` dominates `b` + /// when `b`'s interval is inside `d`'s. + dom_pre: []u32, + dom_post: []u32, fn dominates(c: *const Cfg, d: u32, b: u32) bool { - var x = b; - while (true) { - if (x == d) return true; - const p = c.idom[x]; - if (p == none or p == x) return false; - x = p; - } + if (d == b) return true; + if (c.dom_pre[d] == none or c.dom_pre[b] == none) return false; + return c.dom_pre[d] <= c.dom_pre[b] and c.dom_post[b] <= c.dom_post[d]; } }; +/// Numbers the dominator tree's blocks in and out of a depth-first walk. +fn domIntervals(a: Allocator, idom: []const u32) Allocator.Error!struct { []u32, []u32 } { + const nb = idom.len; + // Children lists, packed: block b's are kids[first[b]..first[b + 1]]. + const first = try a.alloc(u32, nb + 1); + @memset(first, 0); + for (idom, 0..) |p, b| if (p != none and p != b) { + first[p + 1] += 1; + }; + for (1..nb + 1) |k| first[k] += first[k - 1]; + const fill = try a.dupe(u32, first[0..nb]); + const kids = try a.alloc(u32, first[nb]); + for (idom, 0..) |p, b| if (p != none and p != b) { + kids[fill[p]] = @intCast(b); + fill[p] += 1; + }; + const pre = try a.alloc(u32, nb); + const post = try a.alloc(u32, nb); + @memset(pre, none); + @memset(post, none); + if (nb == 0) return .{ pre, post }; + var clock: u32 = 0; + // `next` reuses fill: the next child to visit. + @memcpy(fill, first[0..nb]); + var stack: std.ArrayList(u32) = .empty; + try stack.append(a, 0); + pre[0] = clock; + clock += 1; + while (stack.items.len > 0) { + const b = stack.items[stack.items.len - 1]; + if (fill[b] < first[b + 1]) { + const k = kids[fill[b]]; + fill[b] += 1; + pre[k] = clock; + clock += 1; + try stack.append(a, k); + } else { + post[b] = clock; + clock += 1; + _ = stack.pop(); + } + } + return .{ pre, post }; +} + fn isTerminator(inst: Inst) bool { return switch (inst.op) { .ret, .br, .@"switch", .@"unreachable" => true, @@ -165,7 +211,8 @@ fn buildCfg(a: Allocator, f: *const module.Function) Allocator.Error!?Cfg { } } } - return .{ .nb = nb, .block_start = block_start, .succs = succs, .preds = preds, .idom = idom }; + const pre, const post = try domIntervals(a, idom); + return .{ .nb = nb, .block_start = block_start, .succs = succs, .preds = preds, .idom = idom, .dom_pre = pre, .dom_post = post }; } fn constInt(m: *const module.Module, v: Value) ?i64 {