From ab27e3ddd934aa5aae966289820db5be03a65af1 Mon Sep 17 00:00:00 2001 From: Peterino2 Date: Mon, 2 Nov 2026 07:09:50 +0000 Subject: [PATCH] SPIR-V: inline calls in the IR dxc's SPIR-V gets its calls inlined by legalization; zdxc emitted every function and left inlining to the driver, with 10361 calls across the Hyperion engine's Glide shaders. ir/inline.zig now inlines bottom-up before emission: - The calling block is split at the call: it branches to a copy of the callee, and the rest of the block (terminator and merge included) moves to a continuation block. Parameters become the arguments. - A callee with one return outside every construct branches from it to the continuation. Returns inside selections or switches become breaks out of a loop that runs once around the callee, the return value going through a local. - Callees that return from inside a loop, [noinline] ones, ones with RayQuery or by-reference resource parameters, and ones returning a resource from several places stay functions (resource arguments then still get specializations). - Functions nothing reaches any more are marked dead and not emitted. Only modules with vertex, pixel and compute entry points and no rasterizer-ordered views for now (the emitter treats the others' functions specially). -Od and the new -zdxc-no-opt skip it; -zdxc-ir prints the IR after the SPIR-V passes. On Glide: 37 calls left; the SPIR-V grows (517k to 838k instructions, callee bodies copied, one-trip loops) until promotion to SSA values removes the locals; compile time 597 to 765 ms. The driver's own statistics barely move, except one compute shader passing float4[28] arrays by value, whose copies now take more scratch. Co-Authored-By: Claude Opus 5.5 --- src/compile.zig | 18 ++- src/ir/inline.zig | 382 +++++++++++++++++++++++++++++++++++++++++++++ src/ir/ir.zig | 2 + src/options.zig | 2 + src/root.zig | 1 + src/spirv/emit.zig | 3 +- 6 files changed, 403 insertions(+), 5 deletions(-) create mode 100644 src/ir/inline.zig diff --git a/src/compile.zig b/src/compile.zig index 4ffad96..2298e21 100644 --- a/src/compile.zig +++ b/src/compile.zig @@ -187,6 +187,8 @@ const Options = struct { dump_ast: bool = false, sema: bool = false, dump_ir: bool = false, + /// -zdxc-no-opt: no SPIR-V IR optimizations. + no_opt: bool = false, /// -O0..-O3 / -Od (default -O3, as in dxc). opt_level: enum { od, o0, o1, o2, o3 } = .o3, /// Accepted options with no effect yet, reported once each. @@ -219,6 +221,7 @@ fn parseArgs(ctx: *Ctx, arena: std.mem.Allocator, args: []const []const u8) !?Op }, .zdxc_sema => opts.sema = true, .zdxc_ir => opts.dump_ir = true, + .zdxc_no_opt => opts.no_opt = true, .job => opts.job = a.value(), .fcolor_diagnostics => opts.color = true, .fno_color_diagnostics => opts.color = false, @@ -493,10 +496,6 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { if (profile == null) return ctx.fail("missing -T ", .{}); if (module) |*m| { try zdxc.ir.opt.run(arena, m); - if (opts.dump_ir) { - try zdxc.ir.ir.dump(m, ctx.stdout); - return; - } if (opts.spirv) { zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) { error.Unsupported => { @@ -505,6 +504,17 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { }, else => |x| return x, }; + // Legalization and cleanup dxc's SPIR-V gets from its + // optimizer (skipped for -Od). + if (!opts.no_opt and opts.opt_level != .od) { + try zdxc.ir.inline_calls.run(m); + } + } + if (opts.dump_ir) { + try zdxc.ir.ir.dump(m, ctx.stdout); + return; + } + if (opts.spirv) { const bytes = zdxc.spirv.emit.emit(arena, m, &diags, zdxc.spirv.emit.TargetEnv.parse(opts.target_env) orelse return ctx.fail("unknown SPIR-V target environment '{s}'", .{opts.target_env})) catch |err| switch (err) { error.Unsupported => { try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false }); diff --git a/src/ir/inline.zig b/src/ir/inline.zig new file mode 100644 index 0000000..caa14da --- /dev/null +++ b/src/ir/inline.zig @@ -0,0 +1,382 @@ +//! Inlining for SPIR-V: calls are replaced by copies of their callees, as +//! dxc's legalization does, so drivers get one function per entry point +//! (and later passes see across call boundaries). +//! +//! Callees are inlined bottom-up. The calling block is split at the call: +//! it branches to the copy of the callee's entry, and the rest of the block +//! (with its terminator and merge) moves to a continuation block. A callee +//! with one return outside every construct branches from it to the +//! continuation. Returns inside selections first become breaks out of a +//! loop that runs once (the callee wrapped in it), with the return value in +//! a local; the loop's merge block is where the callee returns, once. +//! Returns inside loops would need a break per loop level: those callees +//! stay functions. +//! +//! Functions no root reaches any more are marked dead (and not emitted). + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const ir = @import("ir.zig"); +const types = @import("../sema/types.zig"); +const opt = @import("opt.zig"); + +const Ref = ir.Ref; +const BlockId = ir.BlockId; +const TypeTable = types.TypeTable; + +pub const Error = Allocator.Error; + +/// Whether the module is one the pass handles: graphics and compute entry +/// points only (the emitter treats hull, mesh, geometry and ray tracing +/// functions specially), and no rasterizer-ordered views (the pixel +/// shader's call of its entry function is the interlocked region). +fn eligible(m: *const ir.Module) bool { + if (m.entries.items.len == 0) return false; + for (m.entries.items) |e| switch (e.stage) { + .vertex, .pixel, .compute => {}, + else => return false, + }; + for (m.globals.items) |g| { + var t = g.ty; + while (m.types.get(t) == .array) t = m.types.get(t).array.elem; + if (m.types.get(t) == .resource and std.mem.startsWith(u8, m.types.get(t).resource.name, "RasterizerOrdered")) return false; + } + return true; +} + +pub fn run(m: *ir.Module) Error!void { + if (!eligible(m)) return; + const a = m.arena; + const n = m.functions.items.len; + // Callees first: post-order over the call graph from every function. + const state = try a.alloc(u8, n); // 0 new, 1 in progress, 2 done + @memset(state, 0); + var order: std.ArrayList(u32) = .empty; + for (0..n) |fi| try postOrder(a, m, @intCast(fi), state, &order); + const shapes = try a.alloc(?Shape, n); + @memset(shapes, null); + for (order.items) |fi| { + try inlineCalls(m, m.functions.items[fi], shapes); + shapes[fi] = try shapeOf(a, m, m.functions.items[fi]); + } + try markDead(m); +} + +fn postOrder(a: Allocator, m: *const ir.Module, fi: u32, state: []u8, out: *std.ArrayList(u32)) Error!void { + if (state[fi] != 0) return; + state[fi] = 1; + const f = m.functions.items[fi]; + for (f.insts.items) |inst| if (inst.op == .call) try postOrder(a, m, inst.op.call.func, state, out); + state[fi] = 2; + try out.append(a, fi); +} + +/// How a function returns, for inlining it. +const Shape = union(enum) { + /// Not inlinable. + keep, + /// One return, outside every construct: that block. + single: u32, + /// Returns inside selections (or several): wrap in a one-trip loop. + wrap, +}; + +fn shapeOf(a: Allocator, m: *const ir.Module, f: *const ir.Function) Error!Shape { + if (f.no_inline) return .keep; + for (f.params) |p| { + if (isRayQuery(m.types, p.ty)) return .keep; + if (p.by_ref and isResource(m.types, p.ty)) return .keep; + } + const nb = f.blocks.items.len; + // The innermost construct (header block) around each block, from a + // structured walk: a header's merge is at the header's level, its other + // successors are inside; exits to an enclosing merge or continue are + // not followed (their header places those blocks). + const root = std.math.maxInt(u32); + const ctx = try a.alloc(u32, nb); + const seen = try a.alloc(bool, nb); + const parent = try a.alloc(u32, nb); + @memset(seen, false); + @memset(parent, root); + var stack: std.ArrayList(struct { b: u32, c: u32 }) = .empty; + try stack.append(a, .{ .b = 0, .c = root }); + while (stack.pop()) |it| { + if (seen[it.b]) continue; + seen[it.b] = true; + ctx[it.b] = it.c; + const blk = f.blocks.items[it.b]; + var inner = it.c; + switch (blk.merge) { + .none => {}, + .selection => |mb| { + try stack.append(a, .{ .b = mb.index(), .c = it.c }); + parent[it.b] = it.c; + inner = it.b; + }, + .loop => |l| { + try stack.append(a, .{ .b = l.merge.index(), .c = it.c }); + try stack.append(a, .{ .b = l.@"continue".index(), .c = it.b }); + parent[it.b] = it.c; + inner = it.b; + }, + } + for (try successors(a, blk.term)) |s| { + if (s == .none) continue; + if (isExit(f, inner, parent, s.index())) continue; + try stack.append(a, .{ .b = s.index(), .c = inner }); + } + } + var rets: u32 = 0; + var ret_block: u32 = 0; + var nested = false; + for (f.blocks.items, 0..) |blk, bi| { + if (!seen[bi] or blk.term != .ret) continue; + rets += 1; + ret_block = @intCast(bi); + // Inside a loop: not inlinable. + var c = ctx[bi]; + while (c != root) : (c = parent[c]) { + if (f.blocks.items[c].merge == .loop) return .keep; + } + if (ctx[bi] != root) nested = true; + } + if (rets == 0) return .keep; // (never returns: leave it alone) + if (rets == 1 and !nested) return .{ .single = ret_block }; + // A resource returned through a local would be a resource local + // assigned in several places. + if (isResource(m.types, f.ret)) return .keep; + return .wrap; +} + +/// Whether `s`, a successor of a block whose innermost construct is headed +/// by `inner`, is that construct's (or an enclosing one's) merge or +/// continue target. +fn isExit(f: *const ir.Function, inner: u32, parent: []const u32, s: u32) bool { + var c = inner; + while (c != std.math.maxInt(u32)) : (c = parent[c]) { + switch (f.blocks.items[c].merge) { + .none => {}, + .selection => |mb| if (mb.index() == s) return true, + .loop => |l| if (l.merge.index() == s or l.@"continue".index() == s) return true, + } + } + return false; +} + +fn successors(a: Allocator, term: ir.Terminator) Error![]const BlockId { + return switch (term) { + .br => |b| try a.dupe(BlockId, &.{b}), + .cond_br => |c| try a.dupe(BlockId, &.{ c.then, c.@"else" }), + .@"switch" => |sw| blk: { + const out = try a.alloc(BlockId, sw.cases.len + 1); + out[0] = sw.default; + for (sw.cases, out[1..]) |c, *o| o.* = c.block; + break :blk out; + }, + else => &.{}, + }; +} + +fn isRayQuery(t: *TypeTable, ty: types.TypeId) bool { + return switch (t.get(ty)) { + .resource => |r| r.kind == .other and std.mem.eql(u8, r.name, "RayQuery"), + else => false, + }; +} + +fn isResource(t: *TypeTable, ty: types.TypeId) bool { + return switch (t.get(ty)) { + .resource => !isRayQuery(t, ty), + .sampler => true, + .array => |x| isResource(t, x.elem), + else => false, + }; +} + +fn newBlock(a: Allocator, f: *ir.Function, blk: ir.Block) Error!u32 { + try f.blocks.append(a, blk); + return @intCast(f.blocks.items.len - 1); +} + +fn newInst(a: Allocator, f: *ir.Function, inst: ir.Inst) Error!Ref { + try f.insts.append(a, inst); + return @fromBackingInt(@intCast(f.insts.items.len - 1)); +} + +/// Inlines every call in `f` whose callee has an inlinable shape. +fn inlineCalls(m: *ir.Module, f: *ir.Function, shapes: []const ?Shape) Error!void { + const a = m.arena; + // Call results, replaced by the callees' return values at the end. + var results: std.AutoHashMapUnmanaged(u32, Ref) = .empty; + var bi: usize = 0; + while (bi < f.blocks.items.len) : (bi += 1) { + var pos: usize = 0; + while (pos < f.blocks.items[bi].insts.items.len) : (pos += 1) { + const r = f.blocks.items[bi].insts.items[pos]; + const call = switch (f.inst(r).op) { + .call => |c| c, + else => continue, + }; + const shape = shapes[call.func] orelse continue; + if (shape == .keep) continue; + // A loop header keeps its instructions (its back edges target it). + if (f.blocks.items[bi].merge == .loop) continue; + const callee = m.functions.items[call.func]; + const value = try inlineOne(a, f, @intCast(bi), pos, call.args, callee, shape); + try results.put(a, r.index(), value); + // The rest of the block moved to the continuation block, which + // is later in the block list. + break; + } + } + if (results.count() == 0) return; + const Map = struct { + res: *const std.AutoHashMapUnmanaged(u32, Ref), + pub fn map(c: @This(), x: Ref) Ref { + var y = x; + while (y != .none) { + y = c.res.get(y.index()) orelse return y; + } + return y; + } + }; + const mp = Map{ .res = &results }; + for (f.blocks.items) |*blk| { + for (blk.insts.items) |r| f.insts.items[r.index()].op = try opt.mapOp(a, f.inst(r).op, mp); + blk.term = mapTerm(blk.term, mp); + } +} + +fn mapTerm(term: ir.Terminator, mp: anytype) ir.Terminator { + return switch (term) { + .ret => |v| .{ .ret = mp.map(v) }, + .cond_br => |c| .{ .cond_br = .{ .cond = mp.map(c.cond), .then = c.then, .@"else" = c.@"else" } }, + .@"switch" => |s| .{ .@"switch" = .{ .value = mp.map(s.value), .default = s.default, .cases = s.cases } }, + else => term, + }; +} + +/// Inlines `callee(args)`, the instruction at `pos` of block `bi` of `f`. +/// Returns the value the call produced (`.none` for void). +fn inlineOne(a: Allocator, f: *ir.Function, bi: u32, pos: usize, args: []const Ref, callee: *const ir.Function, shape: Shape) Error!Ref { + // Continuation: the instructions after the call, the terminator and + // the merge. + const cont = try newBlock(a, f, .{}); + { + const blk = &f.blocks.items[bi]; + try f.blocks.items[cont].insts.appendSlice(a, blk.insts.items[pos + 1 ..]); + f.blocks.items[cont].term = blk.term; + f.blocks.items[cont].merge = blk.merge; + blk.insts.shrinkRetainingCapacity(pos); + blk.merge = .none; + } + + // Copies of the callee's blocks and instructions (parameters become + // the arguments). + const bmap = try a.alloc(u32, callee.blocks.items.len); + for (bmap) |*b| b.* = try newBlock(a, f, .{}); + const imap = try a.alloc(Ref, callee.insts.items.len); + for (callee.insts.items, imap) |inst, *x| { + x.* = switch (inst.op) { + .param => |p| args[p], + else => try newInst(a, f, inst), + }; + } + const Map = struct { + imap: []const Ref, + pub fn map(c: @This(), x: Ref) Ref { + return if (x == .none) x else c.imap[x.index()]; + } + }; + const mp = Map{ .imap = imap }; + for (callee.insts.items, 0..) |inst, k| { + if (inst.op == .param) continue; + f.insts.items[imap[k].index()].op = try opt.mapOp(a, inst.op, mp); + } + const B = struct { + fn map(bm: []const u32, b: BlockId) BlockId { + return if (b == .none) b else @fromBackingInt(@intCast(bm[b.index()])); + } + }; + + // Wrapping: header -> (callee entry) ... -> exit; an unreachable + // continue block; the return value in a local. + var exit: u32 = cont; + var ret_var: Ref = .none; + var result: Ref = .none; + var entry_target: u32 = bmap[0]; + if (shape == .wrap) { + exit = try newBlock(a, f, .{}); + const header = try newBlock(a, f, .{}); + const latch = try newBlock(a, f, .{ .term = .{ .br = @fromBackingInt(@intCast(header)) } }); + f.blocks.items[header].merge = .{ .loop = .{ .merge = @fromBackingInt(@intCast(exit)), .@"continue" = @fromBackingInt(@intCast(latch)), .unroll = .auto } }; + f.blocks.items[header].term = .{ .br = @fromBackingInt(@intCast(bmap[0])) }; + entry_target = header; + if (callee.ret != TypeTable.void_type) { + ret_var = try newInst(a, f, .{ .op = .local_var, .ty = callee.ret, .ptr = .function }); + result = try newInst(a, f, .{ .op = .{ .load = ret_var }, .ty = callee.ret }); + try f.blocks.items[exit].insts.append(a, result); + } + f.blocks.items[exit].term = .{ .br = @fromBackingInt(@intCast(cont)) }; + } + + for (callee.blocks.items, 0..) |src, k| { + var insts: std.ArrayList(Ref) = .empty; + for (src.insts.items) |r| { + if (callee.inst(r).op == .param) continue; + try insts.append(a, imap[r.index()]); + } + var term: ir.Terminator = switch (src.term) { + .ret => |v| blk: { + if (shape == .wrap) { + if (ret_var != .none and v != .none) { + const st = try newInst(a, f, .{ .op = .{ .store = .{ .ptr = ret_var, .value = mp.map(v) } }, .ty = TypeTable.void_type }); + try insts.append(a, st); + } + break :blk .{ .br = @fromBackingInt(@intCast(exit)) }; + } + if (v != .none) result = mp.map(v); + break :blk .{ .br = @fromBackingInt(@intCast(cont)) }; + }, + .br => |b| .{ .br = B.map(bmap, b) }, + .cond_br => |c| .{ .cond_br = .{ .cond = mp.map(c.cond), .then = B.map(bmap, c.then), .@"else" = B.map(bmap, c.@"else") } }, + .@"switch" => |sw| blk: { + const cases = try a.alloc(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases.len); + for (sw.cases, cases) |c, *o| o.* = .{ .value = c.value, .block = B.map(bmap, c.block) }; + break :blk .{ .@"switch" = .{ .value = mp.map(sw.value), .default = B.map(bmap, sw.default), .cases = cases } }; + }, + else => src.term, + }; + _ = &term; + const merge: ir.Merge = switch (src.merge) { + .none => .none, + .selection => |mb| .{ .selection = B.map(bmap, mb) }, + .loop => |l| .{ .loop = .{ .merge = B.map(bmap, l.merge), .@"continue" = B.map(bmap, l.@"continue"), .unroll = l.unroll } }, + }; + f.blocks.items[bmap[k]] = .{ .insts = insts, .term = term, .merge = merge }; + } + f.blocks.items[bi].term = .{ .br = @fromBackingInt(@intCast(entry_target)) }; + return result; +} + +/// Marks functions no root (entry wrappers and patch wrappers, exports) +/// reaches through calls as dead. +fn markDead(m: *ir.Module) Error!void { + const a = m.arena; + const n = m.functions.items.len; + const live = try a.alloc(bool, n); + @memset(live, false); + var stack: std.ArrayList(u32) = .empty; + for (m.entries.items) |e| { + try stack.append(a, e.wrapper); + if (e.patch_wrapper) |p| try stack.append(a, p); + } + try stack.appendSlice(a, m.exports.items); + while (stack.pop()) |fi| { + if (live[fi]) continue; + live[fi] = true; + const f = m.functions.items[fi]; + for (f.blocks.items) |blk| for (blk.insts.items) |r| if (f.inst(r).op == .call) try stack.append(a, f.inst(r).op.call.func); + } + for (m.functions.items, live) |f, l| f.dead = !l; +} diff --git a/src/ir/ir.zig b/src/ir/ir.zig index ac27764..7ca434f 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -208,6 +208,8 @@ pub const Function = struct { /// `[noinline]` (plain functions, not methods or template instances): /// libraries keep it a function of its own. no_inline: bool = false, + /// Nothing calls it any more (inlined everywhere): not emitted. + dead: bool = false, insts: std.ArrayList(Inst) = .empty, blocks: std.ArrayList(Block) = .empty, diff --git a/src/options.zig b/src/options.zig index e91fdde..a8abd9c 100644 --- a/src/options.zig +++ b/src/options.zig @@ -29,6 +29,7 @@ pub const Extra = enum { zdxc_ast, zdxc_sema, zdxc_ir, + zdxc_no_opt, job, fcolor_diagnostics, fno_color_diagnostics, @@ -42,6 +43,7 @@ const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const .{ .id = .zdxc_ast, .spelling = "zdxc-ast", .help = "Preprocess, parse and dump the syntax tree (development)" }, .{ .id = .zdxc_sema, .spelling = "zdxc-sema", .help = "Run the front end through semantic analysis only (development)" }, .{ .id = .zdxc_ir, .spelling = "zdxc-ir", .help = "Print the lowered IR instead of compiling (development)" }, + .{ .id = .zdxc_no_opt, .spelling = "zdxc-no-opt", .help = "Skip the SPIR-V IR optimizations: inlining, promotion to SSA values (development)" }, .{ .id = .job, .spelling = "-job=", .kind = .joined, .meta = "", .help = "Compile every shader a JSON job file lists, in one process, on all cores (see docs/batch.md)" }, .{ .id = .fcolor_diagnostics, .spelling = "fcolor-diagnostics", .help = "Always use colors in diagnostics" }, .{ .id = .fno_color_diagnostics, .spelling = "fno-color-diagnostics", .help = "Never use colors in diagnostics" }, diff --git a/src/root.zig b/src/root.zig index efd87d2..a708ff6 100644 --- a/src/root.zig +++ b/src/root.zig @@ -35,6 +35,7 @@ pub const ir = struct { pub const texture = @import("ir/texture.zig"); pub const opt = @import("ir/opt.zig"); pub const split_resources = @import("ir/split_resources.zig"); + pub const inline_calls = @import("ir/inline.zig"); }; pub const sema = struct { diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index f2829cb..2d09458 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -945,6 +945,7 @@ const Emitter = struct { } for (m.functions.items, e.func_ids) |f, id| { + if (f.dead) continue; e.setEntry(f.entry); if (!e.hasResourceParams(f)) try e.emitFunction(f, id, &.{}); } @@ -984,7 +985,7 @@ const Emitter = struct { try e.entryPoint(entry); } for (m.functions.items, e.func_ids) |f, id| { - if (!e.hasResourceParams(f)) try e.b.emitWithString(.debug_names, .name, &.{id}, f.name, &.{}); + if (!f.dead and !e.hasResourceParams(f)) try e.b.emitWithString(.debug_names, .name, &.{id}, f.name, &.{}); } }