diff --git a/src/BumpArena.zig b/src/BumpArena.zig new file mode 100644 index 0000000..a88f115 --- /dev/null +++ b/src/BumpArena.zig @@ -0,0 +1,193 @@ +//! An arena for one thread: what std.heap.ArenaAllocator does, without the +//! atomic operations that make that one safe to share between threads (an +//! atomic add on every allocation). A compile runs on one thread and +//! allocates millions of times. +//! +//! Memory comes from the child allocator in chunks, each larger than the +//! last; freeing or resizing an allocation works in place only for the +//! most recent one. reset can keep the chunks for the next use. +const BumpArena = @This(); + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const Alignment = std.mem.Alignment; + +child: Allocator, +/// Chunks in use, newest first; allocations bump `end` in the newest. +used: ?*Chunk = null, +/// Chunks a reset kept, for reuse. +spare: ?*Chunk = null, +end: usize = 0, + +const Chunk = struct { + next: ?*Chunk, + /// Bytes after the header. + len: usize, + + fn data(c: *Chunk) [*]u8 { + return @as([*]u8, @ptrCast(c)) + @sizeOf(Chunk); + } +}; + +const chunk_align: Alignment = .@"16"; +const min_chunk = 64 << 10; + +pub fn init(child: Allocator) BumpArena { + return .{ .child = child }; +} + +pub fn deinit(b: *BumpArena) void { + freeList(b.child, b.used); + freeList(b.child, b.spare); + b.* = undefined; +} + +fn freeList(child: Allocator, first: ?*Chunk) void { + var c = first; + while (c) |chunk| { + c = chunk.next; + const bytes: [*]u8 = @ptrCast(chunk); + child.rawFree(bytes[0 .. @sizeOf(Chunk) + chunk.len], chunk_align, @returnAddress()); + } +} + +pub fn allocator(b: *BumpArena) Allocator { + return .{ .ptr = b, .vtable = &vtable }; +} + +const vtable: Allocator.VTable = .{ .alloc = alloc, .resize = resize, .remap = remap, .free = free }; + +/// Total bytes of the chunks held (in use and spare). +pub fn queryCapacity(b: *const BumpArena) usize { + var n: usize = 0; + inline for (.{ b.used, b.spare }) |first| { + var c = first; + while (c) |chunk| : (c = chunk.next) n += chunk.len; + } + return n; +} + +pub const ResetMode = std.heap.ArenaAllocator.ResetMode; + +/// Frees every allocation. `.retain_capacity` keeps the chunks for reuse; +/// `.retain_with_limit` keeps them up to that many bytes (largest first +/// kept); `.free_all` gives them back. +pub fn reset(b: *BumpArena, mode: ResetMode) bool { + const limit: usize = switch (mode) { + .free_all => 0, + .retain_capacity => std.math.maxInt(usize), + .retain_with_limit => |l| l, + }; + // All chunks, then keep the largest that fit under the limit. + var all = b.used; + if (all) |first| { + var last = first; + while (last.next) |nx| last = nx; + last.next = b.spare; + } else all = b.spare; + b.used = null; + b.spare = null; + b.end = 0; + var kept: usize = 0; + var c = all; + while (c) |chunk| { + c = chunk.next; + if (kept + chunk.len <= limit) { + kept += chunk.len; + chunk.next = null; + b.addSpare(chunk); + } else { + const bytes: [*]u8 = @ptrCast(chunk); + b.child.rawFree(bytes[0 .. @sizeOf(Chunk) + chunk.len], chunk_align, @returnAddress()); + } + } + return true; +} + +/// Adds a chunk to the spare list, largest first. +fn addSpare(b: *BumpArena, chunk: *Chunk) void { + var link = &b.spare; + while (link.*) |s| : (link = &s.next) if (s.len < chunk.len) break; + chunk.next = link.*; + link.* = chunk; +} + +fn alloc(ctx: *anyopaque, n: usize, alignment: Alignment, ra: usize) ?[*]u8 { + const b: *BumpArena = @ptrCast(@alignCast(ctx)); + if (b.used) |c| { + const base = c.data(); + const start = alignment.forward(@intFromPtr(base) + b.end) - @intFromPtr(base); + if (start + n <= c.len) { + b.end = start + n; + return base + start; + } + } + return b.allocSlow(n, alignment, ra); +} + +fn allocSlow(b: *BumpArena, n: usize, alignment: Alignment, ra: usize) ?[*]u8 { + const need = n + alignment.toByteUnits(); + // A spare chunk big enough (the largest is first), else a new one half + // again as large as the current. + const chunk: *Chunk = if (b.spare != null and b.spare.?.len >= need) blk: { + const s = b.spare.?; + b.spare = s.next; + break :blk s; + } else blk: { + const grow = if (b.used) |c| c.len + c.len / 2 else 0; + const len = @max(need, grow, min_chunk); + const bytes = b.child.rawAlloc(@sizeOf(Chunk) + len, chunk_align, ra) orelse return null; + const c: *Chunk = @ptrCast(@alignCast(bytes)); + c.len = len; + break :blk c; + }; + chunk.next = b.used; + b.used = chunk; + const base = chunk.data(); + const start = alignment.forward(@intFromPtr(base)) - @intFromPtr(base); + b.end = start + n; + return base + start; +} + +/// Whether `buf` is the newest allocation (the only one that can change +/// in place). +fn isLast(b: *const BumpArena, buf: []u8) bool { + const c = b.used orelse return false; + return buf.ptr + buf.len == c.data() + b.end; +} + +fn resize(ctx: *anyopaque, buf: []u8, _: Alignment, new_len: usize, _: usize) bool { + const b: *BumpArena = @ptrCast(@alignCast(ctx)); + if (!b.isLast(buf)) return new_len <= buf.len; + const c = b.used.?; + const start = @intFromPtr(buf.ptr) - @intFromPtr(c.data()); + if (start + new_len > c.len) return false; + b.end = start + new_len; + return true; +} + +fn remap(ctx: *anyopaque, buf: []u8, alignment: Alignment, new_len: usize, ra: usize) ?[*]u8 { + return if (resize(ctx, buf, alignment, new_len, ra)) buf.ptr else null; +} + +fn free(ctx: *anyopaque, buf: []u8, _: Alignment, _: usize) void { + const b: *BumpArena = @ptrCast(@alignCast(ctx)); + if (b.isLast(buf)) b.end -= buf.len; +} + +test "allocations, growth in place, reset" { + var b: BumpArena = .init(std.testing.allocator); + defer b.deinit(); + const a = b.allocator(); + var list: std.ArrayList(u32) = .empty; + for (0..100_000) |k| try list.append(a, @intCast(k)); + for (list.items, 0..) |x, k| try std.testing.expectEqual(k, x); + const big = try a.alignedAlloc(u8, .@"64", 1 << 20); + try std.testing.expect(std.mem.isAligned(@intFromPtr(big.ptr), 64)); + const cap = b.queryCapacity(); + _ = b.reset(.retain_capacity); + try std.testing.expectEqual(cap, b.queryCapacity()); + _ = try a.alloc(u8, 100); + _ = b.reset(.{ .retain_with_limit = 0 }); + try std.testing.expectEqual(0, b.queryCapacity()); +} diff --git a/src/capi.zig b/src/capi.zig index 0fb2bd8..8262525 100644 --- a/src/capi.zig +++ b/src/capi.zig @@ -2,6 +2,7 @@ //! owns an arena; nothing is global. const std = @import("std"); +const BumpArena = @import("zdxc").BumpArena; const zdxc = @import("zdxc"); const compile = zdxc.compile; const FileSystem = zdxc.front.source.FileSystem; @@ -22,7 +23,7 @@ const CompileInfo = extern struct { const Output = enum(c_int) { object, diagnostics, preprocessed, root_signature, text, _ }; const Result = struct { - arena: std.heap.ArenaAllocator, + arena: BumpArena, status: compile.Status, /// Indexed by `Output`; each NUL-terminated. outputs: [5]?[:0]const u8, @@ -32,7 +33,7 @@ const Result = struct { export fn zdxc_compile(info: ?*const CompileInfo) ?*Result { const i = info orelse return null; if (i.size < @sizeOf(CompileInfo)) return null; - var arena: std.heap.ArenaAllocator = .init(std.heap.smp_allocator); + var arena: BumpArena = .init(std.heap.smp_allocator); const r = compileInto(&arena, i) catch { arena.deinit(); return null; @@ -41,7 +42,7 @@ export fn zdxc_compile(info: ?*const CompileInfo) ?*Result { return r; } -fn compileInto(arena: *std.heap.ArenaAllocator, i: *const CompileInfo) !*Result { +fn compileInto(arena: *BumpArena, i: *const CompileInfo) !*Result { const a = arena.allocator(); const args = try a.alloc([]const u8, i.arg_count); for (args, 0..) |*d, k| d.* = std.mem.span(i.args.?[k] orelse return error.InvalidArgument); diff --git a/src/diag.zig b/src/diag.zig index fecbb39..8990ca8 100644 --- a/src/diag.zig +++ b/src/diag.zig @@ -3,6 +3,7 @@ //! include chains and macro expansion backtraces. const std = @import("std"); +const BumpArena = @import("BumpArena.zig"); const Allocator = std.mem.Allocator; const source = @import("front/source.zig"); const Loc = source.Loc; @@ -56,7 +57,7 @@ pub const Report = struct { }; pub const Diagnostics = struct { - arena: std.heap.ArenaAllocator, + arena: BumpArena, list: std.ArrayList(*Diagnostic) = .empty, error_count: u32 = 0, warning_count: u32 = 0, diff --git a/src/dxcapi.zig b/src/dxcapi.zig index 240d5d2..b068937 100644 --- a/src/dxcapi.zig +++ b/src/dxcapi.zig @@ -14,6 +14,7 @@ //! does (test/dropin in the development repo compares the two). const std = @import("std"); +const BumpArena = @import("zdxc").BumpArena; const builtin = @import("builtin"); const zdxc = @import("zdxc"); const compile = zdxc.compile; @@ -839,7 +840,7 @@ const Compiler = struct { /// gives its blocks back to the OS (smp_allocator maps 64 KiB and up /// directly), and faulting fresh pages in again costs more than the compile /// on many threads. What a thread keeps is capped at `retain_limit`. -threadlocal var thread_arena: ?std.heap.ArenaAllocator = null; +threadlocal var thread_arena: ?BumpArena = null; const retain_limit = 64 << 20; fn run(source: *const Buffer, wargs: []const ?[*:0]const WCHAR, include: ?*anyopaque) error{ OutOfMemory, InvalidArgument }!*Result { diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index d4f2fc6..b532ee4 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -6,6 +6,7 @@ //! signed DXIL container. const std = @import("std"); +const BumpArena = @import("../BumpArena.zig"); const Allocator = std.mem.Allocator; const ir = @import("../ir/ir.zig"); const types = @import("../sema/types.zig"); @@ -52,7 +53,7 @@ pub fn emit(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: pub const Output = struct { object: []u8, reflection: []u8 }; pub fn emitWithReflection(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, optimize: bool) Error!Output { - var arena_state = std.heap.ArenaAllocator.init(gpa); + var arena_state: BumpArena = .init(gpa); defer arena_state.deinit(); var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags, .optimize = optimize }; defer e.dm.deinit(); @@ -6040,7 +6041,7 @@ const Emitter = struct { if (resources) |r| try dm.addNamedMetadata("dx.resources", &.{r}); if (funcs.len > 0) try dm.addNamedMetadata("dx.typeAnnotations", &.{type_annotations}); try dm.addNamedMetadata("dx.entryPoints", entries.items); - return dm.writeBitcode(dm.arena.child_allocator); + return dm.writeBitcode(dm.arena.child); } // ---- Reflection (reflect.zig) ----------------------------------------- @@ -6741,7 +6742,7 @@ const Emitter = struct { try dm.addNamedMetadata("dx.entryPoints", &.{entry_md}); try promote.pruneGlobals(e.arena, dm); _ = try promote.pruneDeclarations(e.arena, dm); - return dm.writeBitcode(dm.arena.child_allocator); + return dm.writeBitcode(dm.arena.child); } /// `!{id, name, comp, kind, !{indices}, interp, rows, cols, row, col, diff --git a/src/dxil/module.zig b/src/dxil/module.zig index 2533bd9..4ad6054 100644 --- a/src/dxil/module.zig +++ b/src/dxil/module.zig @@ -3,6 +3,7 @@ //! unabbreviated records only. const std = @import("std"); +const BumpArena = @import("../BumpArena.zig"); const Allocator = std.mem.Allocator; const bitstream = @import("bitstream.zig"); @@ -187,7 +188,7 @@ pub const Metadata = union(enum) { }; pub const Module = struct { - arena: std.heap.ArenaAllocator, + arena: BumpArena, 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, diff --git a/src/dxil/reflect.zig b/src/dxil/reflect.zig index 7a91751..c656d0e 100644 --- a/src/dxil/reflect.zig +++ b/src/dxil/reflect.zig @@ -8,6 +8,7 @@ //! ZRFL part holding the rest as JSON. const std = @import("std"); +const BumpArena = @import("../BumpArena.zig"); const Allocator = std.mem.Allocator; const container = @import("container.zig"); @@ -194,7 +195,7 @@ test "encode and decode" { }; const blob = try encode(a, r, &.{}); defer a.free(blob); - var arena: std.heap.ArenaAllocator = .init(a); + var arena: BumpArena = .init(a); defer arena.deinit(); const view = try container.parse(arena.allocator(), blob); const back = try decode(arena.allocator(), view.find(part) orelse return error.TestUnexpectedResult); diff --git a/src/dxil/rootsig.zig b/src/dxil/rootsig.zig index 1e7fc1b..31f0f51 100644 --- a/src/dxil/rootsig.zig +++ b/src/dxil/rootsig.zig @@ -18,6 +18,7 @@ //! Self-contained: depends on std only. const std = @import("std"); +const BumpArena = @import("../BumpArena.zig"); const Allocator = std.mem.Allocator; pub const Version = enum(u32) { @@ -66,7 +67,7 @@ pub fn compile(gpa: Allocator, text: []const u8, version: Version, diag: *Diagno } pub fn compileWithOptions(gpa: Allocator, text: []const u8, opts: Options, diag: *Diagnostic) Allocator.Error!?[]u8 { - var arena_state = std.heap.ArenaAllocator.init(gpa); + var arena_state = BumpArena.init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); diff --git a/src/front/parser.zig b/src/front/parser.zig index 5e52e9e..c7e1227 100644 --- a/src/front/parser.zig +++ b/src/front/parser.zig @@ -7,6 +7,7 @@ //! builtin types are recognized by name. const std = @import("std"); +const BumpArena = @import("../BumpArena.zig"); const Allocator = std.mem.Allocator; const ast = @import("ast.zig"); const lexer = @import("lexer.zig"); @@ -2154,7 +2155,7 @@ const TestParse = struct { mfs: source.MemoryFs = .{}, sm: source.SourceManager = undefined, diags: Diagnostics = undefined, - arena: std.heap.ArenaAllocator = undefined, + arena: BumpArena = undefined, out: std.Io.Writer.Allocating = undefined, fn run(t: *TestParse, text: []const u8) ![]const u8 { diff --git a/src/front/preproc.zig b/src/front/preproc.zig index 6675b7d..e3a80f0 100644 --- a/src/front/preproc.zig +++ b/src/front/preproc.zig @@ -4,6 +4,7 @@ //! disabled macro. const std = @import("std"); +const BumpArena = @import("../BumpArena.zig"); const Allocator = std.mem.Allocator; const source = @import("source.zig"); const lexer = @import("lexer.zig"); @@ -1446,7 +1447,7 @@ const TestPP = struct { mfs: source.MemoryFs = .{}, sm: source.SourceManager = undefined, diags: Diagnostics = undefined, - arena: std.heap.ArenaAllocator = undefined, + arena: BumpArena = undefined, pp: Preprocessor = undefined, fn init(t: *TestPP, files: []const [2][]const u8, main: []const u8, opts: Options) !void { diff --git a/src/front/source.zig b/src/front/source.zig index 499e644..3d46fd1 100644 --- a/src/front/source.zig +++ b/src/front/source.zig @@ -1,6 +1,7 @@ //! Source files and locations. const std = @import("std"); +const BumpArena = @import("../BumpArena.zig"); const Allocator = std.mem.Allocator; const scan = @import("scan.zig"); @@ -134,7 +135,7 @@ pub const LineOverride = struct { pub const PresumedLoc = struct { file: []const u8, line: u32 }; pub const SourceManager = struct { - arena: std.heap.ArenaAllocator, + arena: BumpArena, files: std.ArrayList(File) = .empty, fs: FileSystem, /// path -> contents, or null if the path could not be read. diff --git a/src/job.zig b/src/job.zig index dc2bf4e..04b75f1 100644 --- a/src/job.zig +++ b/src/job.zig @@ -28,6 +28,7 @@ //! and fails its job. const std = @import("std"); +const BumpArena = @import("zdxc").BumpArena; const Io = std.Io; const Allocator = std.mem.Allocator; const FileSystem = @import("zdxc").front.source.FileSystem; @@ -238,7 +239,7 @@ const Batch = struct { /// jobs ahead of the compiles. fn read(b: *Batch) void { const gpa = std.heap.smp_allocator; - var arena: std.heap.ArenaAllocator = .init(gpa); + var arena: BumpArena = .init(gpa); defer arena.deinit(); for (b.jobs, b.sources, 0..) |args, *s, i| { while (true) { @@ -303,7 +304,7 @@ const Batch = struct { fn work(b: *Batch) void { const gpa = std.heap.smp_allocator; - var arena: std.heap.ArenaAllocator = .init(gpa); + var arena: BumpArena = .init(gpa); defer arena.deinit(); while (true) { const i = b.next.fetchAdd(1, .monotonic); diff --git a/src/root.zig b/src/root.zig index b2dd0fd..ee9a63c 100644 --- a/src/root.zig +++ b/src/root.zig @@ -4,6 +4,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 BumpArena = @import("BumpArena.zig"); pub const Diagnostics = diag.Diagnostics; pub const front = struct { diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index 68532eb..d250bf1 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -4,6 +4,7 @@ //! (binding = register number, descriptor set = register space). const std = @import("std"); +const BumpArena = @import("../BumpArena.zig"); const Allocator = std.mem.Allocator; const ir = @import("../ir/ir.zig"); const types = @import("../sema/types.zig"); @@ -142,7 +143,7 @@ pub const TargetEnv = struct { }; pub fn emit(gpa: Allocator, m: *const ir.Module, diags: *diag.Diagnostics, env: TargetEnv) Error![]u8 { - var arena_state = std.heap.ArenaAllocator.init(gpa); + var arena_state = BumpArena.init(gpa); defer arena_state.deinit(); var e: Emitter = .{ .arena = arena_state.allocator(), .b = .init(gpa), .m = m, .t = m.types, .diags = diags, .spv_minor = env.minor, .universal = env.universal, .vk = m.vk }; defer e.b.deinit();