From e6a089eb3472af20be2f3a5cd4d7088ddfcacc6c Mon Sep 17 00:00:00 2001 From: peterino2 Date: Tue, 3 Nov 2026 01:03:23 -0800 Subject: [PATCH] stats: time and allocations per compilation stage A caller that wants them points stats.current at a Stats for the thread; zones in compile (options, preprocess, parse, sema, lower, ir_opt, DXIL, SPIR-V) and in DXIL emission (lowering, finish, promote, sccp, unroll, bitcode, container) add their time and the caller's allocation counts, and counters record DXIL instructions lowered and kept. Without a Stats a zone costs one thread-local load. --- src/compile.zig | 18 ++++++++ src/dxil/emit.zig | 11 +++++ src/dxil/promote.zig | 4 ++ src/dxil/sccp.zig | 3 ++ src/dxil/unroll.zig | 3 ++ src/root.zig | 1 + src/stats.zig | 99 ++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 139 insertions(+) create mode 100644 src/stats.zig diff --git a/src/compile.zig b/src/compile.zig index 9fbc17a..259492e 100644 --- a/src/compile.zig +++ b/src/compile.zig @@ -11,6 +11,7 @@ const container = zdxc.dxil.container; const front = zdxc.front; const options = zdxc.options; const FileSystem = front.source.FileSystem; +const stats = zdxc.stats; pub const Request = struct { /// dxc command-line options, without the program name: "-T", "ps_6_0", @@ -371,7 +372,9 @@ fn parseArgs(ctx: *Ctx, arena: std.mem.Allocator, args: []const []const u8) !?Op } fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { + const za = stats.begin(.args); const opts = try parseArgs(ctx, arena, ctx.req.args) orelse return; + za.end(); ctx.result.object_name = opts.output; ctx.result.root_signature_name = opts.rootsig_output; ctx.result.preprocessed_name = opts.pp_output; @@ -445,13 +448,18 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { }); var out: Io.Writer.Allocating = .init(arena); var module: ?zdxc.ir.ir.Module = null; + const zp = stats.begin(.preprocess); const opened = try pp.enterMainFile(input); if (opened) { if (opts.preprocess) { try front.pp_print.print(&pp, &out.writer); + zp.end(); } else { var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp); + zp.end(); + const zparse = stats.begin(.parse); const tu = try parser.parseTranslationUnit(); + zparse.end(); if (opts.dump_ast) try front.ast_dump.dumpUnit(ctx.stdout, tu); if (!opts.parse) { const is_lib = if (profile) |p| p.kind == .library else true; @@ -467,8 +475,10 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { }); // About one resolution per expression: reserve rather // than grow, which leaves every old buffer in the arena. + const zs = stats.begin(.sema); try sema.resolutions.ensureTotalCapacity(arena, parser.toks.len); try sema.checkUnit(tu); + zs.end(); if (!opts.sema and !diags.hasErrors() and profile != null) { const stage: zdxc.ir.ir.Stage = switch (profile.?.kind) { .vertex => .vertex, @@ -481,10 +491,12 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { .amplification => .amplification, else => .library, }; + const zl = stats.begin(.lower); module = zdxc.ir.lower.lowerUnit(arena, &sema, .{ .entry = opts.entry, .stage = stage }) catch |e| switch (e) { error.Unsupported => null, else => |x| return x, }; + zl.end(); if (module) |*mm| { mm.native_16bit = opts.enable_16bit; mm.row_major = opts.row_major; @@ -510,7 +522,11 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { if (opts.parse or opts.sema) return; if (profile == null) return ctx.fail("missing -T ", .{}); if (module) |*m| { + const zo = stats.begin(.ir_opt); try zdxc.ir.opt.run(arena, m); + zo.end(); + const zv = stats.begin(.spirv); + defer if (opts.spirv) zv.end(); if (opts.spirv) { zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) { error.Unsupported => { @@ -546,6 +562,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { if (opts.rootsig_define) |macro| if (m.entries.items.len == 1) { m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed; }; + const zd = stats.begin(.dxil); const dxil_out = zdxc.dxil.emit.emitWithReflection(arena, m, profile.?, &diags, !opts.no_opt and opts.opt_level != .od) catch |err| switch (err) { error.Unsupported => { try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false }); @@ -553,6 +570,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { }, else => |x| return x, }; + zd.end(); try ctx.needOutput(opts); ctx.result.object = dxil_out.object; ctx.result.reflection = dxil_out.reflection; diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 26acd79..5fa076e 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -25,6 +25,7 @@ const reflect = @import("reflect.zig"); const rootsig = @import("rootsig.zig"); const promote = @import("promote.zig"); const unroll = @import("unroll.zig"); +const stats = @import("../stats.zig"); const sccp = @import("sccp.zig"); const opt = @import("../ir/opt.zig"); @@ -511,8 +512,10 @@ const Emitter = struct { try e.buildSignatures(entry); if (entry.stage == .amplification) e.findDispatchPayload(); e.cur = try e.newBlock(); + const zl = stats.begin(.dxil_lower); try e.createHandles(); _ = try e.inlineCall(entry.wrapper, &.{}); + zl.end(); try e.finish(e.main_fn); if (entry.patch_wrapper) |pw| { // The patch constant function is a function of its own. @@ -536,6 +539,7 @@ const Emitter = struct { if (e.optimize) e.inputUsage(); if (e.optimize and e.profile.minor >= 6) try e.dropDeadResources(); + for (e.dm.functions.items) |f| stats.add(.dxil_final, f.insts.items.len); const bitcode = try e.writeModule(entry); defer gpa.free(bitcode); return e.assemble(gpa, entry, bitcode); @@ -1352,6 +1356,7 @@ const Emitter = struct { /// Assigns final instruction indices: prologue first, then blocks in /// creation order. fn finish(e: *Emitter, func: u32) Error!void { + const zf = stats.begin(.dxil_finish); if (e.lib_removable.count() > 0) try e.pruneProlog(); const map = try e.arena.alloc(u32, e.next_id); var n: u32 = 0; @@ -1375,6 +1380,7 @@ const Emitter = struct { return out; } }; + 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)); @@ -1384,6 +1390,7 @@ const Emitter = struct { while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*); e.dyn_ranges.clearRetainingCapacity(); e.array_pool.clearRetainingCapacity(); + zf.end(); if (e.optimize) { try promote.run(e.arena, &e.dm, func, &ranges); // Values only ever one constant (through loops too), and the @@ -6578,6 +6585,8 @@ const Emitter = struct { } fn writeModule(e: *Emitter, entry: ir.Entry) Error![]u8 { + const zone = stats.begin(.bitcode); + defer zone.end(); const dm = &e.dm; const mdI32 = struct { fn f(m: *module.Module, v: i64) !module.MdId { @@ -6648,6 +6657,8 @@ const Emitter = struct { } fn assemble(e: *Emitter, gpa: Allocator, entry: ir.Entry, bitcode: []const u8) Error![]u8 { + const zone = stats.begin(.container); + defer zone.end(); const dxil_part = try shader.programPart(gpa, e.profile, bitcode); defer gpa.free(dxil_part); var binds: std.ArrayList(shader.ResourceBind) = .empty; diff --git a/src/dxil/promote.zig b/src/dxil/promote.zig index 8a255d3..68ea5c4 100644 --- a/src/dxil/promote.zig +++ b/src/dxil/promote.zig @@ -15,6 +15,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const module = @import("module.zig"); +const stats = @import("../stats.zig"); const Value = module.Value; const Inst = module.Inst; @@ -123,6 +124,9 @@ fn isScalar(m: *const module.Module, ty: TypeId) bool { /// `dyn` maps the dynamically indexed getelementptrs into locals to the /// components [lo, hi) they can reach; one missing from it can reach all. pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashMapUnmanaged(u32, [2]u32)) Allocator.Error!void { + const zone = stats.begin(.promote); + stats.add(.promote_runs, 1); + defer zone.end(); const f = &m.functions.items[func]; const insts = f.insts.items; const n: u32 = @intCast(insts.len); diff --git a/src/dxil/sccp.zig b/src/dxil/sccp.zig index b8dbf0c..3b90a55 100644 --- a/src/dxil/sccp.zig +++ b/src/dxil/sccp.zig @@ -12,6 +12,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const module = @import("module.zig"); +const stats = @import("../stats.zig"); const unroll = @import("unroll.zig"); const Value = module.Value; @@ -101,6 +102,8 @@ fn successors(term: Inst) Succs { /// Runs the propagation on `func`; true if it changed anything. pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool { + const zone = stats.begin(.sccp); + defer zone.end(); const f = &m.functions.items[func]; const insts = f.insts.items; const n: u32 = @intCast(insts.len); diff --git a/src/dxil/unroll.zig b/src/dxil/unroll.zig index cc01607..149ffb7 100644 --- a/src/dxil/unroll.zig +++ b/src/dxil/unroll.zig @@ -15,6 +15,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const module = @import("module.zig"); +const stats = @import("../stats.zig"); const promote = @import("promote.zig"); const Value = module.Value; @@ -33,6 +34,8 @@ const max_growth = 65536; /// Unrolls the qualifying loops of `func`, innermost first; true if any. pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool { + const zone = stats.begin(.unroll); + defer zone.end(); var budget: usize = max_growth; var tried: std.AutoHashMapUnmanaged(u32, void) = .empty; var any = false; diff --git a/src/root.zig b/src/root.zig index bf959e3..b2dd0fd 100644 --- a/src/root.zig +++ b/src/root.zig @@ -3,6 +3,7 @@ pub const diag = @import("diag.zig"); pub const options = @import("options.zig"); pub const compile = @import("compile.zig"); +pub const stats = @import("stats.zig"); pub const Diagnostics = diag.Diagnostics; pub const front = struct { diff --git a/src/stats.zig b/src/stats.zig new file mode 100644 index 0000000..ba93d67 --- /dev/null +++ b/src/stats.zig @@ -0,0 +1,99 @@ +//! Time and allocations per compilation stage, for benchmarks. A caller +//! that wants them points `current` at a `Stats` for the thread's +//! compilation; zones anywhere in the compiler then add to it. With no +//! `Stats` (the default) a zone costs one thread-local load. + +const std = @import("std"); + +pub const Stage = enum { + /// Command-line options and setup. + args, + /// Preprocessing and lexing, up to a token array. + preprocess, + parse, + sema, + lower, + ir_opt, + /// DXIL emission, in all (the zones below are inside it). + dxil, + /// Lowering the entry's IR to DXIL instructions (inlining every call). + dxil_lower, + /// Renumbering a function's instructions into its body. + dxil_finish, + promote, + sccp, + unroll, + bitcode, + container, + spirv, + /// Diagnostics rendering and the rest of `compile`. + other, +}; + +pub const count = @typeInfo(Stage).@"enum".field_names.len; + +/// Sizes of the work, to explain the times. +pub const Counter = enum { + /// DXIL instructions lowering produced (before any optimization). + dxil_lowered, + /// DXIL instructions left in the emitted functions. + dxil_final, + /// Times promotion ran. + promote_runs, +}; + +pub const counter_count = @typeInfo(Counter).@"enum".field_names.len; + +/// What the caller's allocator counters read at a point (the caller's +/// `sample` fills it in). +pub const Sample = struct { calls: u64 = 0, bytes: u64 = 0 }; + +pub const Stats = struct { + io: std.Io, + ns: [count]u64 = @splat(0), + /// Allocation calls and bytes requested in each stage. + calls: [count]u64 = @splat(0), + bytes: [count]u64 = @splat(0), + /// Times each zone was entered. + entries: [count]u32 = @splat(0), + counters: [counter_count]u64 = @splat(0), + sample: ?*const fn (ctx: ?*anyopaque) Sample = null, + sample_ctx: ?*anyopaque = null, + + fn read(s: *const Stats) Sample { + return if (s.sample) |f| f(s.sample_ctx) else .{}; + } +}; + +pub threadlocal var current: ?*Stats = null; + +pub const Zone = struct { + stage: Stage, + t0: i96 = 0, + s0: Sample = .{}, + on: bool = false, + + /// Ends the zone, adding its time and allocations to its stage + /// (inclusive of zones nested in it). + pub fn end(z: Zone) void { + if (!z.on) return; + const s = current orelse return; + const t1 = std.Io.Clock.awake.now(s.io).toNanoseconds(); + const s1 = s.read(); + const k = @backingInt(z.stage); + s.ns[k] += @intCast(t1 - z.t0); + s.calls[k] += s1.calls - z.s0.calls; + s.bytes[k] += s1.bytes - z.s0.bytes; + s.entries[k] += 1; + } +}; + +/// Adds `n` to a counter. +pub fn add(c: Counter, n: u64) void { + if (current) |s| s.counters[@backingInt(c)] += n; +} + +pub fn begin(stage: Stage) Zone { + const s = current orelse return .{ .stage = stage }; + return .{ .stage = stage, .t0 = std.Io.Clock.awake.now(s.io).toNanoseconds(), .s0 = s.read(), .on = true }; +}