From 0a2607946f851e4a693d6e44480a71866d6d0920 Mon Sep 17 00:00:00 2001 From: peterino2 Date: Tue, 3 Nov 2026 08:58:02 -0800 Subject: [PATCH] dxil: write only used constants, in order of first use The constants block held every constant ever made, in the order they were first asked for, including those only code that optimization later removed used. Output bytes therefore depended on how much throwaway code lowering made. writeBitcode now drops unused constants and numbers the rest by first use (grouped by type, aggregates after their elements), remapping every reference. - Output: -7% on the hill-climbing set; Unreal shaders up to -59% (ue-vs-2021: 10.2 KB to 4.2 KB). - Cost: about 1.2 ms for the set (bitcode stage +18%, 0.25% of the total). - Validator 1.8: 11,488 Unreal compiles, 0 invalid (10056, a work graph node shader, fails to compile as before). --- src/dxil/module.zig | 184 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 184 insertions(+) diff --git a/src/dxil/module.zig b/src/dxil/module.zig index 2533bd9..835bbf7 100644 --- a/src/dxil/module.zig +++ b/src/dxil/module.zig @@ -297,6 +297,108 @@ pub const Module = struct { return @fromBackingInt(@intCast(m.inst_mds.items.len)); } + /// Drops the constants nothing uses, and numbers the rest in order of + /// first use (functions' instructions, then metadata), grouped by type, + /// with aggregates last, after their elements. The output then depends + /// only on the code that is left, not on code made and removed again or + /// on the order constants were first asked for. + fn pruneConstants(m: *Module) !void { + const a = m.allocator(); + const n = m.constants.items.len; + if (n == 0) return; + const Walk = struct { + m: *Module, + a: Allocator, + seen: []bool, + order: std.ArrayList(ConstId) = .empty, + failed: bool = false, + + fn map(w: *@This(), v: Value) Value { + if (v == .constant) w.visit(v.constant) catch { + w.failed = true; + }; + return v; + } + + fn visit(w: *@This(), c: ConstId) Allocator.Error!void { + if (w.seen[c]) return; + w.seen[c] = true; + switch (w.m.constants.items[c].kind) { + .aggregate => |els| for (els) |el| try w.visit(el), + else => {}, + } + try w.order.append(w.a, c); + } + }; + var walk: Walk = .{ .m = m, .a = a, .seen = try a.alloc(bool, n) }; + @memset(walk.seen, false); + for (m.functions.items) |f| for (f.insts.items) |inst| { + var copy = inst; + // (Reading only: no slice is copied, nothing changes.) + try mapOperands(a, ©, &walk); + }; + for (m.metadata.items) |md| if (md == .value) { + _ = walk.map(md.value.val); + }; + if (walk.failed) return error.OutOfMemory; + + // Types in order of first use; scalars by type (stable), then + // aggregates in walk order (each after its elements). + var rank: std.AutoHashMapUnmanaged(TypeId, u32) = .empty; + const Key = struct { rank: u32, id: ConstId }; + var scalars: std.ArrayList(Key) = .empty; + var aggregates: std.ArrayList(ConstId) = .empty; + for (walk.order.items) |c| { + const k = m.constants.items[c]; + if (k.kind == .aggregate) { + try aggregates.append(a, c); + continue; + } + const gop = try rank.getOrPut(a, k.ty); + if (!gop.found_existing) gop.value_ptr.* = rank.count() - 1; + try scalars.append(a, .{ .rank = gop.value_ptr.*, .id = c }); + } + std.sort.block(Key, scalars.items, {}, struct { + fn lt(_: void, x: Key, y: Key) bool { + return x.rank < y.rank; + } + }.lt); + + const new_id = try a.alloc(ConstId, n); + @memset(new_id, no_const); + var kept: std.ArrayList(Constant) = .empty; + try kept.ensureTotalCapacityPrecise(a, walk.order.items.len); + for (scalars.items) |k| { + new_id[k.id] = @intCast(kept.items.len); + kept.appendAssumeCapacity(m.constants.items[k.id]); + } + for (aggregates.items) |c| { + var k = m.constants.items[c]; + const els = try a.alloc(ConstId, k.kind.aggregate.len); + for (k.kind.aggregate, els) |el, *o| o.* = new_id[el]; + k.kind = .{ .aggregate = els }; + new_id[c] = @intCast(kept.items.len); + kept.appendAssumeCapacity(k); + } + + const Remap = struct { + new_id: []const ConstId, + fn map(r: @This(), v: Value) Value { + return if (v == .constant) .{ .constant = r.new_id[v.constant] } else v; + } + }; + const remap: Remap = .{ .new_id = new_id }; + for (m.functions.items) |*f| for (f.insts.items) |*inst| try mapOperands(a, inst, remap); + for (m.metadata.items) |*md| if (md.* == .value) { + md.value.val = remap.map(md.value.val); + }; + m.constants = kept; + // (Constants made from here on start a new index.) + m.constant_ids = .empty; + for (m.constants.items, 0..) |c, i| try m.constant_ids.put(a, c, @intCast(i)); + m.small_i32 = @splat(no_const); + } + pub fn addFunction(m: *Module, f: Function) !u32 { var owned = f; owned.name = try m.allocator().dupe(u8, f.name); @@ -355,12 +457,94 @@ pub const Module = struct { /// Encode the module as raw LLVM bitcode (starting with 'BC' 0xC0DE). pub fn writeBitcode(m: *Module, gpa: Allocator) ![]u8 { + try m.pruneConstants(); var enc: Encoder = .{ .m = m, .w = .init(gpa) }; defer enc.w.deinit(); return enc.write(); } }; +/// Calls `ctx.map(v) Value` on each value operand of `inst` and stores the +/// results; operand slices whose values change are copied (slices may be +/// shared between instructions). +fn mapOperands(a: Allocator, inst: *Inst, ctx: anytype) !void { + const S = struct { + fn many(al: Allocator, c: anytype, xs: []const Value) ![]const Value { + for (xs, 0..) |x, k| { + if (std.meta.eql(c.map(x), x)) continue; + const out = try al.dupe(Value, xs); + for (out[k..]) |*o| o.* = c.map(o.*); + return out; + } + return xs; + } + }; + switch (inst.op) { + .ret => |*v| if (v.*) |x| { + v.* = ctx.map(x); + }, + .br => |*b| if (b.cond) |c| { + b.cond = ctx.map(c); + }, + .@"switch" => |*sw| { + sw.cond = ctx.map(sw.cond); + const cases = try a.dupe(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases); + for (cases) |*c| c.val = ctx.map(c.val); + sw.cases = cases; + }, + .call => |*c| c.args = try S.many(a, ctx, c.args), + .binop => |*b| { + b.lhs = ctx.map(b.lhs); + b.rhs = ctx.map(b.rhs); + }, + .cast => |*c| c.val = ctx.map(c.val), + .cmp => |*c| { + c.lhs = ctx.map(c.lhs); + c.rhs = ctx.map(c.rhs); + }, + .select => |*x| { + x.cond = ctx.map(x.cond); + x.t = ctx.map(x.t); + x.f = ctx.map(x.f); + }, + .extractvalue => |*x| x.agg = ctx.map(x.agg), + .phi => |*p| { + const ins = try a.dupe(@typeInfo(@TypeOf(p.incoming)).pointer.child, p.incoming); + for (ins) |*in| in.val = ctx.map(in.val); + p.incoming = ins; + }, + .alloca => |*x| x.size = ctx.map(x.size), + .load => |*x| x.ptr = ctx.map(x.ptr), + .store => |*x| { + x.ptr = ctx.map(x.ptr); + x.val = ctx.map(x.val); + }, + .gep => |*x| { + x.ptr = ctx.map(x.ptr); + x.indices = try S.many(a, ctx, x.indices); + }, + .atomicrmw => |*x| { + x.ptr = ctx.map(x.ptr); + x.val = ctx.map(x.val); + }, + .cmpxchg => |*x| { + x.ptr = ctx.map(x.ptr); + x.cmp = ctx.map(x.cmp); + x.new = ctx.map(x.new); + }, + .@"unreachable" => {}, + .extractelement => |*x| { + x.vec = ctx.map(x.vec); + x.index = ctx.map(x.index); + }, + .insertelement => |*x| { + x.vec = ctx.map(x.vec); + x.val = ctx.map(x.val); + x.index = ctx.map(x.index); + }, + } +} + const block_module = 8; const block_paramattr = 9; const block_paramattr_group = 10;