Fix two toolchain defects found by the M checkpoint
A. Interpreter memory grew with the number of executed steps (one arena, never reclaimed): block and call arguments, frames, frame storage, value copies, place paths, channel buffers and per-step scratch now live in a collectable execution heap. Between instructions, past a threshold, the live state is copied into a fresh heap (sharing preserved) and the old one released. Long-lived state (module, world, authority, task, channel and region tables, the result) stays in the caller's arena. The guarded value of a mutex is a separate cell (no interior pointers). Nothing observable changes: fuel, schedule, PRNG, values, traps and run records are the same. - test: five loop shapes x 100k/1M/4M iterations, measured with the interpreter's own heap counters: live state after a collection does not grow with the iteration count; the heap stays under a fixed bound - conformance --collect-every-step: the second run of every run test collects before every instruction; records must be byte-identical (passes, also with --stress 20) B. A void function whose body ends in an if/if-else/match/block/void call lowered to `ret %` (malformed AIR, reported as E0001): it now lowers to `ret`. Seven fall-through tests (six failed before). Also: files_opened counts reads by relative path and file name; P6A-11 (malformed generated AIR as an internal compiler diagnostic) and Q-023 (ref of a whole array as an argument) recorded.
This commit is contained in:
1 parent
4aa9183e78
commit
222c0c884c
15 files changed
+573
-48
No files matched your search
+10
-2
@@ -526,7 +526,7 @@ const Lowerer = struct {
|
||||
}
|
||||
if (tail) |v| {
|
||||
try l.checkTy(f.body.tail.?.span, v.ty, sig.ret);
|
||||
try l.term(try l.fmt("ret %{s}", .{v.name}), f.body.tail.?.span);
|
||||
try l.term(try l.retText(v), f.body.tail.?.span);
|
||||
} else if (sig.ret == .void) {
|
||||
try l.term("ret", f.body.span);
|
||||
} else return l.fail("E7006", f.body.span, "the function can end without returning a value", &.{.{ .name = "function", .value = f.name }});
|
||||
@@ -561,6 +561,14 @@ const Lowerer = struct {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ret %v`, or `ret` for a void value: a void function whose body ends
|
||||
/// in an `if`, `match`, loop, block or void call falls through with
|
||||
/// nothing to return (spec 15 §4).
|
||||
fn retText(l: *Lowerer, v: Value) Error![]const u8 {
|
||||
if (v.ty == .void) return "ret";
|
||||
return l.fmt("ret %{s}", .{v.name});
|
||||
}
|
||||
|
||||
fn freshName(l: *Lowerer, base: []const u8) Error![]const u8 {
|
||||
while (true) {
|
||||
l.counter += 1;
|
||||
@@ -813,7 +821,7 @@ const Lowerer = struct {
|
||||
try l.checkTy(x.span, v.ty, l.ret);
|
||||
if (l.cur != null) {
|
||||
try l.endScopes(0, s.span);
|
||||
try l.term(try l.fmt("ret %{s}", .{v.name}), s.span);
|
||||
try l.term(try l.retText(v), s.span);
|
||||
}
|
||||
} else {
|
||||
if (l.ret != .void) return l.fail("E7005", s.span, "`return` without a value in a function that returns one", &.{.{ .name = "expected", .value = l.tyText(l.ret) }});
|
||||
|
||||
+310
-41
@@ -5,8 +5,21 @@
|
||||
//! - deterministic: no host time, randomness or address-dependent behavior;
|
||||
//! - traps are values (`Outcome.trapped`), never host panics or unwinding.
|
||||
//!
|
||||
//! Target description: `air64` (spec 09 §9). All memory comes from the arena
|
||||
//! passed to `run` and is released by the caller as a whole.
|
||||
//! Target description: `air64` (spec 09 §9).
|
||||
//!
|
||||
//! Memory: use is bounded by the program's live state, not by the number
|
||||
//! of instructions executed.
|
||||
//! - long-lived state comes from the arena passed to `run` and is released
|
||||
//! by the caller: the module, the world, the authority, task, channel and
|
||||
//! region tables, and the result;
|
||||
//! - execution state lives in a collectable heap: frames, block and call
|
||||
//! arguments, frame storage and heap cells, aggregate and array payloads,
|
||||
//! place paths, channel buffers, per-instruction scratch. Between
|
||||
//! instructions, when the heap has grown past a threshold, the live part
|
||||
//! is copied into a fresh heap (`collect`) and the old one is released.
|
||||
//! Copying preserves sharing, and nothing observable depends on
|
||||
//! addresses, so collection never changes fuel, scheduling, PRNG draws,
|
||||
//! values, traps or the run record.
|
||||
|
||||
const std = @import("std");
|
||||
const air = @import("../air.zig");
|
||||
@@ -55,7 +68,9 @@ pub const Value = union(enum) {
|
||||
mutex: *MutexCell,
|
||||
guard: *MutexCell,
|
||||
|
||||
pub const MutexCell = struct { locked: bool, cell: Cell };
|
||||
/// The guarded value is a separate cell, so a place borrowed through a
|
||||
/// guard points at an ordinary cell.
|
||||
pub const MutexCell = struct { locked: bool, cell: *Cell };
|
||||
|
||||
pub const Aggregate = struct {
|
||||
decl: u32,
|
||||
@@ -124,7 +139,22 @@ pub const Authority = struct {
|
||||
/// A region: its authority and the bytes charged by its current generation.
|
||||
pub const Region = struct { authority: u32, used: u64 };
|
||||
|
||||
const OwnInfo = struct { authority: u32, bytes: u64 };
|
||||
|
||||
/// Execution-heap statistics (`Options.memory`), for tests and tooling.
|
||||
pub const MemoryStats = struct {
|
||||
collections: u64 = 0,
|
||||
/// Largest live execution state after a collection, in heap bytes.
|
||||
peak_live: usize = 0,
|
||||
/// Largest execution heap before a collection, in heap bytes.
|
||||
peak_heap: usize = 0,
|
||||
};
|
||||
|
||||
pub const Options = struct {
|
||||
/// Filled with execution-heap statistics when set.
|
||||
memory: ?*MemoryStats = null,
|
||||
/// Collect before every instruction (tests: a missed root then fails).
|
||||
collect_every_step: bool = false,
|
||||
/// Maximum number of instructions to execute (spec 11 §7.1); null means unlimited.
|
||||
fuel: ?u64 = null,
|
||||
/// Capability grants for the parameters of the entry function.
|
||||
@@ -203,9 +233,79 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
if (!known) return .{ .not_instantiated = .{ .reason = "unknown_parameter", .parameter = g.parameter } };
|
||||
}
|
||||
|
||||
return m.runProgram(idx, args);
|
||||
m.exec_heap.every_step = options.collect_every_step;
|
||||
const outcome = try m.runProgram(idx, args);
|
||||
// The result outlives the execution heap.
|
||||
var result = outcome;
|
||||
if (outcome == .returned) {
|
||||
var tmp: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
|
||||
defer tmp.deinit();
|
||||
var c: Copier = .{ .to = arena, .tmp = tmp.allocator() };
|
||||
result = .{ .returned = try c.value(outcome.returned) };
|
||||
}
|
||||
m.exec_heap.stats.peak_heap = @max(m.exec_heap.stats.peak_heap, m.exec_heap.space.queryCapacity());
|
||||
if (options.memory) |st| st.* = m.exec_heap.stats;
|
||||
m.exec_heap.space.deinit();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Copies values into another heap, preserving sharing: a cell, a mutex or
|
||||
/// a payload reached twice is copied once.
|
||||
const Copier = struct {
|
||||
to: std.mem.Allocator,
|
||||
tmp: std.mem.Allocator,
|
||||
cells: std.AutoHashMapUnmanaged(*Value.Cell, *Value.Cell) = .empty,
|
||||
mutexes: std.AutoHashMapUnmanaged(*Value.MutexCell, *Value.MutexCell) = .empty,
|
||||
payloads: std.AutoHashMapUnmanaged([*]Value, []Value) = .empty,
|
||||
|
||||
fn value(c: *Copier, v: Value) std.mem.Allocator.Error!Value {
|
||||
return switch (v) {
|
||||
.aggregate => |a| .{ .aggregate = .{ .decl = a.decl, .variant = a.variant, .fields = try c.items(a.fields) } },
|
||||
.array => |xs| .{ .array = try c.items(xs) },
|
||||
.local => |cl| .{ .local = try c.cell(cl) },
|
||||
.own => |cl| .{ .own = try c.cell(cl) },
|
||||
.place => |p| .{ .place = try c.place(p) },
|
||||
.slice => |sl| .{ .slice = .{ .place = try c.place(sl.place), .start = sl.start, .len = sl.len } },
|
||||
.mutex => |mc| .{ .mutex = try c.mutex(mc) },
|
||||
.guard => |mc| .{ .guard = try c.mutex(mc) },
|
||||
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver => v,
|
||||
};
|
||||
}
|
||||
|
||||
fn items(c: *Copier, xs: []Value) std.mem.Allocator.Error![]Value {
|
||||
if (xs.len == 0) return &.{};
|
||||
if (c.payloads.get(xs.ptr)) |n| {
|
||||
std.debug.assert(n.len == xs.len);
|
||||
return n;
|
||||
}
|
||||
const out = try c.to.alloc(Value, xs.len);
|
||||
try c.payloads.put(c.tmp, xs.ptr, out);
|
||||
for (xs, out) |x, *o| o.* = try c.value(x);
|
||||
return out;
|
||||
}
|
||||
|
||||
fn cell(c: *Copier, old: *Value.Cell) std.mem.Allocator.Error!*Value.Cell {
|
||||
if (c.cells.get(old)) |n| return n;
|
||||
const n = try c.to.create(Value.Cell);
|
||||
try c.cells.put(c.tmp, old, n);
|
||||
n.* = .{ .value = .void, .ty = old.ty };
|
||||
n.value = try c.value(old.value);
|
||||
return n;
|
||||
}
|
||||
|
||||
fn mutex(c: *Copier, old: *Value.MutexCell) std.mem.Allocator.Error!*Value.MutexCell {
|
||||
if (c.mutexes.get(old)) |n| return n;
|
||||
const n = try c.to.create(Value.MutexCell);
|
||||
try c.mutexes.put(c.tmp, old, n);
|
||||
n.* = .{ .locked = old.locked, .cell = try c.cell(old.cell) };
|
||||
return n;
|
||||
}
|
||||
|
||||
fn place(c: *Copier, p: Value.Place) std.mem.Allocator.Error!Value.Place {
|
||||
return .{ .cell = try c.cell(p.cell), .path = if (p.path.len == 0) &.{} else try c.to.dupe(u32, p.path) };
|
||||
}
|
||||
};
|
||||
|
||||
const TrapKind = enum {
|
||||
explicit,
|
||||
assert,
|
||||
@@ -300,8 +400,19 @@ const Task = struct {
|
||||
delivered: ?struct { arm: u32, value: Value } = null,
|
||||
};
|
||||
|
||||
/// Execution heap: collected between instructions (see the file comment).
|
||||
const Heap = struct {
|
||||
space: std.heap.ArenaAllocator = .init(std.heap.page_allocator),
|
||||
threshold: usize = min_threshold,
|
||||
every_step: bool = false,
|
||||
stats: MemoryStats = .{},
|
||||
|
||||
const min_threshold = 4 << 20;
|
||||
};
|
||||
|
||||
const Machine = struct {
|
||||
arena: std.mem.Allocator,
|
||||
exec_heap: Heap = .{},
|
||||
module: air.Module,
|
||||
fuel: ?u64,
|
||||
tasks: std.ArrayList(Task) = .empty,
|
||||
@@ -335,6 +446,8 @@ const Machine = struct {
|
||||
try m.tasks.append(m.arena, .{});
|
||||
try m.pushFrame(0, fn_index, args);
|
||||
while (true) {
|
||||
// Safe point: between instructions no Zig local holds heap values.
|
||||
if (m.exec_heap.every_step or m.exec_heap.space.queryCapacity() > m.exec_heap.threshold) try m.collect();
|
||||
const t = &m.tasks.items[m.current];
|
||||
if (t.state != .runnable) {
|
||||
if (try m.schedule()) |o| return o;
|
||||
@@ -405,9 +518,58 @@ const Machine = struct {
|
||||
}
|
||||
}
|
||||
|
||||
fn heap(m: *Machine) std.mem.Allocator {
|
||||
return m.exec_heap.space.allocator();
|
||||
}
|
||||
|
||||
/// Copies the live execution state into a fresh heap and releases the
|
||||
/// old one. Roots: every task's frames, result and delivered value; the
|
||||
/// channels' buffered values and offers; the heap cells of live owners.
|
||||
fn collect(m: *Machine) std.mem.Allocator.Error!void {
|
||||
const before = m.exec_heap.space.queryCapacity();
|
||||
var next: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
|
||||
errdefer next.deinit();
|
||||
var tmp: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
|
||||
defer tmp.deinit();
|
||||
var c: Copier = .{ .to = next.allocator(), .tmp = tmp.allocator() };
|
||||
for (m.tasks.items) |*t| {
|
||||
for (t.frames.items) |*fr| fr.vals = try c.items(fr.vals);
|
||||
t.result = try c.value(t.result);
|
||||
if (t.delivered) |*d| d.value = try c.value(d.value);
|
||||
}
|
||||
for (m.channels.items) |*ch| {
|
||||
var buf: std.ArrayList(Value) = .empty;
|
||||
try buf.ensureTotalCapacity(c.to, ch.buf.items.len - ch.head);
|
||||
for (ch.buf.items[ch.head..]) |v| buf.appendAssumeCapacity(try c.value(v));
|
||||
ch.buf = buf;
|
||||
ch.head = 0;
|
||||
var offers: std.ArrayList(Offer) = .empty;
|
||||
try offers.ensureTotalCapacity(c.to, ch.send_offers.items.len);
|
||||
for (ch.send_offers.items) |o| offers.appendAssumeCapacity(.{ .task = o.task, .arm = o.arm, .value = try c.value(o.value) });
|
||||
ch.send_offers = offers;
|
||||
if (ch.recv_offer) |*o| o.value = try c.value(o.value);
|
||||
}
|
||||
var owners: std.AutoHashMapUnmanaged(*Value.Cell, OwnInfo) = .empty;
|
||||
try owners.ensureTotalCapacity(c.to, m.owners.count());
|
||||
var it = m.owners.iterator();
|
||||
while (it.next()) |e| owners.putAssumeCapacityNoClobber(try c.cell(e.key_ptr.*), e.value_ptr.*);
|
||||
m.owners = owners;
|
||||
|
||||
m.exec_heap.space.deinit();
|
||||
m.exec_heap.space = next;
|
||||
const live = m.exec_heap.space.queryCapacity();
|
||||
const st = &m.exec_heap.stats;
|
||||
st.collections += 1;
|
||||
st.peak_heap = @max(st.peak_heap, before);
|
||||
st.peak_live = @max(st.peak_live, live);
|
||||
m.exec_heap.threshold = @max(Heap.min_threshold, 2 * live);
|
||||
}
|
||||
|
||||
fn pushFrame(m: *Machine, task: u32, fn_index: u32, args: []const Value) !void {
|
||||
const f = m.module.functions[fn_index];
|
||||
const vals = try m.arena.alloc(Value, f.values.len);
|
||||
const vals = try m.heap().alloc(Value, f.values.len);
|
||||
// Slots not yet defined are read by `collect`: they start as void.
|
||||
@memset(vals, .void);
|
||||
for (f.params, args) |p, a| vals[p.value] = a;
|
||||
try m.tasks.items[task].frames.append(m.arena, .{ .func = fn_index, .vals = vals, .block = 0, .inst = 0 });
|
||||
}
|
||||
@@ -434,7 +596,7 @@ const Machine = struct {
|
||||
t.state = .runnable;
|
||||
};
|
||||
var runnable: std.ArrayList(u32) = .empty;
|
||||
for (m.tasks.items, 0..) |t, i| if (t.state == .runnable) try runnable.append(m.arena, @intCast(i));
|
||||
for (m.tasks.items, 0..) |t, i| if (t.state == .runnable) try runnable.append(m.heap(), @intCast(i));
|
||||
if (runnable.items.len == 0) {
|
||||
// Global quiescence (spec 11 §8): unfinished tasks, none runnable,
|
||||
// no known future event. Report the oldest waiting task.
|
||||
@@ -663,7 +825,7 @@ const Machine = struct {
|
||||
/// Performs an `ok`-ready send.
|
||||
fn doSend(m: *Machine, id: u32, v: Value) !void {
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity > 0) return c.buf.append(m.arena, try m.deepCopy(v));
|
||||
if (c.capacity > 0) return c.buf.append(m.heap(), try m.deepCopy(v));
|
||||
const o = c.recv_offer.?;
|
||||
m.deliver(o, try m.deepCopy(v));
|
||||
}
|
||||
@@ -782,7 +944,7 @@ const Machine = struct {
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity == 0) try c.send_offers.append(m.arena, .{ .task = self, .arm = 0, .value = v });
|
||||
if (c.capacity == 0) try c.send_offers.append(m.heap(), .{ .task = self, .arm = 0, .value = v });
|
||||
return .{ .wait = .op };
|
||||
},
|
||||
}
|
||||
@@ -819,9 +981,9 @@ const Machine = struct {
|
||||
fn execSelect(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "select")) !Step {
|
||||
const self = m.current;
|
||||
const t = &m.tasks.items[self];
|
||||
const ids = try m.arena.alloc(air.ValueId, x.arms.len);
|
||||
const ids = try m.heap().alloc(air.ValueId, x.arms.len);
|
||||
const vs = air.Op.selectValues(x.arms, ids);
|
||||
const v_vals = try m.arena.alloc(Value, vs.len);
|
||||
const v_vals = try m.heap().alloc(Value, vs.len);
|
||||
for (vs, v_vals) |v, *o| o.* = vals[v];
|
||||
if (t.delivered) |d| {
|
||||
t.delivered = null;
|
||||
@@ -832,7 +994,7 @@ const Machine = struct {
|
||||
for (x.arms, 0..) |arm, i| {
|
||||
const ch = endpointOf(vals[arm.endpoint]);
|
||||
const st = if (arm.value == null) m.recvState(ch) else m.sendState(ch);
|
||||
if (st != .none) try ready_arms.append(m.arena, .{ @intCast(i), st });
|
||||
if (st != .none) try ready_arms.append(m.heap(), .{ @intCast(i), st });
|
||||
}
|
||||
if (ready_arms.items.len == 0) {
|
||||
if (cancelObservable(t)) {
|
||||
@@ -843,7 +1005,7 @@ const Machine = struct {
|
||||
const c = &m.channels.items[endpointOf(vals[arm.endpoint])];
|
||||
if (c.capacity != 0) continue;
|
||||
if (arm.value) |v| {
|
||||
try c.send_offers.append(m.arena, .{ .task = self, .arm = @intCast(i), .value = vals[v] });
|
||||
try c.send_offers.append(m.heap(), .{ .task = self, .arm = @intCast(i), .value = vals[v] });
|
||||
} else c.recv_offer = .{ .task = self, .arm = @intCast(i) };
|
||||
}
|
||||
return .{ .wait = .op };
|
||||
@@ -873,8 +1035,8 @@ const Machine = struct {
|
||||
fn selectOk(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "select"), i: u32, received: Value, vs: []const air.ValueId, v_vals: []const Value) !Step {
|
||||
const arm = x.arms[i];
|
||||
var params: std.ArrayList(Value) = .empty;
|
||||
if (arm.value == null) try params.append(m.arena, received);
|
||||
for (vs, v_vals) |v, val| if (arm.value == null or arm.value.? != v) try params.append(m.arena, val);
|
||||
if (arm.value == null) try params.append(m.heap(), received);
|
||||
for (vs, v_vals) |v, val| if (arm.value == null or arm.value.? != v) try params.append(m.heap(), val);
|
||||
setParams(f, vals, arm.ok, params.items);
|
||||
return .{ .jump_yield = arm.ok };
|
||||
}
|
||||
@@ -882,8 +1044,10 @@ const Machine = struct {
|
||||
fn execMutex(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step {
|
||||
switch (inst.op) {
|
||||
.mutex_make => |v| {
|
||||
const mc = try m.arena.create(Value.MutexCell);
|
||||
mc.* = .{ .locked = false, .cell = .{ .value = try m.deepCopy(vals[v]), .ty = .void } };
|
||||
const mc = try m.heap().create(Value.MutexCell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = try m.deepCopy(vals[v]), .ty = .void };
|
||||
mc.* = .{ .locked = false, .cell = cell };
|
||||
return bind(vals, inst.result, .{ .mutex = mc });
|
||||
},
|
||||
.mutex_take => |v| return bind(vals, inst.result, vals[v].mutex.cell.value),
|
||||
@@ -897,7 +1061,7 @@ const Machine = struct {
|
||||
if (cancelObservable(&m.tasks.items[m.current])) return .{ .jump_yield = x.cancelled };
|
||||
return .{ .wait = .op };
|
||||
},
|
||||
.mutex_borrow => |g| return bind(vals, inst.result, .{ .place = .{ .cell = &vals[g].guard.cell, .path = &.{} } }),
|
||||
.mutex_borrow => |g| return bind(vals, inst.result, .{ .place = .{ .cell = vals[g].guard.cell, .path = &.{} } }),
|
||||
.mutex_unlock => |g| {
|
||||
vals[g].guard.locked = false;
|
||||
return .yield;
|
||||
@@ -932,7 +1096,7 @@ const Machine = struct {
|
||||
}
|
||||
|
||||
fn copyAll(m: *Machine, items: []const Value) std.mem.Allocator.Error![]Value {
|
||||
const out = try m.arena.alloc(Value, items.len);
|
||||
const out = try m.heap().alloc(Value, items.len);
|
||||
for (items, out) |x, *o| o.* = try m.deepCopy(x);
|
||||
return out;
|
||||
}
|
||||
@@ -942,13 +1106,13 @@ const Machine = struct {
|
||||
.int => |it| .{ .int = .{ .ty = it, .bits = 0 } },
|
||||
.bool => .{ .boolean = false },
|
||||
.array => |a| blk: {
|
||||
const items = try m.arena.alloc(Value, a.len);
|
||||
const items = try m.heap().alloc(Value, a.len);
|
||||
for (items) |*x| x.* = try m.zeroValue(a.elem);
|
||||
break :blk .{ .array = items };
|
||||
},
|
||||
.named => |i| blk: {
|
||||
const fields = m.module.types[i].kind.@"struct";
|
||||
const out = try m.arena.alloc(Value, fields.len);
|
||||
const out = try m.heap().alloc(Value, fields.len);
|
||||
for (fields, out) |fd, *o| o.* = try m.zeroValue(fd.ty);
|
||||
break :blk .{ .aggregate = .{ .decl = i, .variant = 0, .fields = out } };
|
||||
},
|
||||
@@ -967,7 +1131,7 @@ const Machine = struct {
|
||||
}
|
||||
|
||||
fn extend(m: *Machine, p: Value.Place, i: u64) !Value.Place {
|
||||
const path = try m.arena.alloc(u32, p.path.len + 1);
|
||||
const path = try m.heap().alloc(u32, p.path.len + 1);
|
||||
@memcpy(path[0..p.path.len], p.path);
|
||||
path[p.path.len] = @intCast(i);
|
||||
return .{ .cell = p.cell, .path = path };
|
||||
@@ -1004,7 +1168,7 @@ const Machine = struct {
|
||||
fn bytesOf(m: *Machine, v: Value) ![]u8 {
|
||||
const s = v.slice;
|
||||
const items = placePtr(s.place).array[s.start..][0..s.len];
|
||||
const out = try m.arena.alloc(u8, items.len);
|
||||
const out = try m.heap().alloc(u8, items.len);
|
||||
for (items, out) |x, *o| o.* = @truncate(x.int.bits);
|
||||
return out;
|
||||
}
|
||||
@@ -1045,7 +1209,7 @@ const Machine = struct {
|
||||
vals[f.blocks[x.err].params[0].value] = .{ .builtin = .{ .which = .cap_error, .variant = r } };
|
||||
return .{ .jump = x.err };
|
||||
}
|
||||
try m.authorities.append(m.arena, .{ .kind = a.kind, .scope = path });
|
||||
try m.authorities.append(m.arena, .{ .kind = a.kind, .scope = try m.arena.dupe(u8, path) });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .cap = @intCast(m.authorities.items.len - 1) };
|
||||
return .{ .jump = x.ok };
|
||||
}
|
||||
@@ -1096,8 +1260,6 @@ const Machine = struct {
|
||||
}
|
||||
|
||||
/// Owner cells remember their charge and authority for `own.free`.
|
||||
const OwnInfo = struct { authority: u32, bytes: u64 };
|
||||
|
||||
fn execAlloc(m: *Machine, f: air.Function, vals: []Value, types_of: anytype, inst: air.Inst) !Step {
|
||||
_ = types_of;
|
||||
switch (inst.op) {
|
||||
@@ -1106,9 +1268,9 @@ const Machine = struct {
|
||||
const bytes = m.valueBytes(vals[x.value]);
|
||||
const a = vals[x.cap].cap;
|
||||
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = try m.deepCopy(v), .ty = .void };
|
||||
try m.owners.put(m.arena, cell, .{ .authority = a, .bytes = bytes.? });
|
||||
try m.owners.put(m.heap(), cell, .{ .authority = a, .bytes = bytes.? });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .own = cell };
|
||||
return .{ .jump = x.ok };
|
||||
},
|
||||
@@ -1117,11 +1279,11 @@ const Machine = struct {
|
||||
const a = vals[x.cap].cap;
|
||||
const bytes = m.arrayBytes(vals[x.value], n);
|
||||
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
|
||||
const items = try m.arena.alloc(Value, n);
|
||||
const items = try m.heap().alloc(Value, n);
|
||||
for (items) |*it| it.* = try m.deepCopy(vals[x.value]);
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = .{ .array = items }, .ty = .void };
|
||||
try m.owners.put(m.arena, cell, .{ .authority = a, .bytes = bytes.? });
|
||||
try m.owners.put(m.heap(), cell, .{ .authority = a, .bytes = bytes.? });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .own = cell };
|
||||
return .{ .jump = x.ok };
|
||||
},
|
||||
@@ -1153,9 +1315,9 @@ const Machine = struct {
|
||||
const bytes = if (n) |count| m.arrayBytes(vals[value], count) else m.valueBytes(vals[value]);
|
||||
if (!m.charge(region.authority, bytes)) return allocFailed(f, vals, t.err);
|
||||
region.used += bytes.?;
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
if (n) |count| {
|
||||
const items = try m.arena.alloc(Value, count);
|
||||
const items = try m.heap().alloc(Value, count);
|
||||
for (items) |*it| it.* = try m.deepCopy(vals[value]);
|
||||
cell.* = .{ .value = .{ .array = items }, .ty = .void };
|
||||
vals[f.blocks[t.ok].params[0].value] = .{ .slice = .{ .place = .{ .cell = cell, .path = &.{} }, .start = 0, .len = count } };
|
||||
@@ -1194,7 +1356,7 @@ const Machine = struct {
|
||||
const now = if (m.host) |*hs| hs.monotonic() else m.steps;
|
||||
return bind(vals, inst.result, .{ .int = .{ .ty = .u64, .bits = now } });
|
||||
} else if (is(name, "random.fill")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const buf = try m.heap().alloc(u8, arg(vals, x, 1).slice.len);
|
||||
if (m.host) |*hs| hs.fill(buf) else m.world.fill(buf);
|
||||
fillSlice(arg(vals, x, 1), buf);
|
||||
return .next;
|
||||
@@ -1203,7 +1365,7 @@ const Machine = struct {
|
||||
const err_stream = is(name, "io.stderr_write");
|
||||
if (m.host) |*hs| failure = hs.writeOut(err_stream, bytes) else try m.world.writeOut(err_stream, bytes);
|
||||
} else if (is(name, "io.stdin_read")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const buf = try m.heap().alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const n: usize = if (m.host) |*hs| switch (hs.readIn(buf)) {
|
||||
.ok => |k| k,
|
||||
.err => |e| blk: {
|
||||
@@ -1222,7 +1384,7 @@ const Machine = struct {
|
||||
.err => |e| failure = e,
|
||||
}
|
||||
} else if (is(name, "fs.read")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const buf = try m.heap().alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const hd = resourceOf(arg(vals, x, 0));
|
||||
const n: usize = if (m.host) |*hs| switch (hs.fileRead(hd, buf)) {
|
||||
.ok => |k| k,
|
||||
@@ -1260,7 +1422,7 @@ const Machine = struct {
|
||||
.err => |e| failure = e,
|
||||
} else result = .{ .resource = m.world.accept(hd) orelse return .{ .wait = .{ .accept = hd } } };
|
||||
} else if (is(name, "net.recv")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const buf = try m.heap().alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const hd = resourceOf(arg(vals, x, 0));
|
||||
const n: usize = if (m.host) |*hs| switch (hs.recv(hd, buf)) {
|
||||
.ok => |k| k,
|
||||
@@ -1292,7 +1454,7 @@ const Machine = struct {
|
||||
fn execMemory(m: *Machine, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
|
||||
switch (inst.op) {
|
||||
.local_alloc => |t| {
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = .void, .ty = t };
|
||||
return bind(vals, inst.result, .{ .local = cell });
|
||||
},
|
||||
@@ -1315,12 +1477,12 @@ const Machine = struct {
|
||||
else => .{ .place = .{ .cell = cell, .path = &.{} } },
|
||||
},
|
||||
.region => |r| blk: {
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = .{ .region = r }, .ty = .void };
|
||||
break :blk .{ .place = .{ .cell = cell, .path = &.{} } };
|
||||
},
|
||||
.resource => |hd| blk: {
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = .{ .resource = hd }, .ty = .void };
|
||||
break :blk .{ .place = .{ .cell = cell, .path = &.{} } };
|
||||
},
|
||||
@@ -1334,7 +1496,7 @@ const Machine = struct {
|
||||
return .next;
|
||||
},
|
||||
.array_splat => |x| {
|
||||
const items = try m.arena.alloc(Value, x.ty.array.len);
|
||||
const items = try m.heap().alloc(Value, x.ty.array.len);
|
||||
for (items) |*it| it.* = try m.deepCopy(vals[x.value]);
|
||||
return bind(vals, inst.result, .{ .array = items });
|
||||
},
|
||||
@@ -1392,7 +1554,7 @@ const Machine = struct {
|
||||
}
|
||||
|
||||
fn gatherMut(m: *Machine, vals: []const Value, ids: []const air.ValueId) ![]Value {
|
||||
const out = try m.arena.alloc(Value, ids.len);
|
||||
const out = try m.heap().alloc(Value, ids.len);
|
||||
for (ids, out) |id, *o| o.* = vals[id];
|
||||
return out;
|
||||
}
|
||||
@@ -1879,3 +2041,110 @@ test "schedule seed: explicit value is used as is, default derives from the prog
|
||||
_ = try run(arena, report.module.?, "main", .{ .world = .{ .seed = 3 }, .output = &out });
|
||||
try std.testing.expectEqual(@as(u64, 3 ^ 0x5343484544554c45), out.schedule.?.seed);
|
||||
}
|
||||
|
||||
// Memory use is bounded by live state, not by the number of instructions
|
||||
// executed. Measured with the interpreter's own heap counters,
|
||||
// not host RSS: for each loop shape, the live execution state after a
|
||||
// collection must not grow with the iteration count, and the heap stays
|
||||
// under a fixed bound.
|
||||
fn memoryOf(comptime body: []const u8, n: u64) !MemoryStats {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
const src = try std.fmt.allocPrint(arena, body, .{n});
|
||||
const report = try check.checkFile(arena, "t.aji", src);
|
||||
if (report.status != .accepted) {
|
||||
for (report.diagnostics) |d| std.debug.print("{s} {s}\n", .{ d.code.id, d.message });
|
||||
return error.NotAccepted;
|
||||
}
|
||||
var stats: MemoryStats = .{};
|
||||
const outcome = try run(arena, report.module.?, "main", .{ .grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = "4096" }}, .memory = &stats });
|
||||
try std.testing.expect(outcome == .returned);
|
||||
return stats;
|
||||
}
|
||||
|
||||
const loop_shapes = [_][]const u8{
|
||||
// scalar state carried in block arguments
|
||||
\\module t
|
||||
\\fn main(heap: cap<mem.alloc>) -> u64
|
||||
\\effects []
|
||||
\\{{
|
||||
\\ var i: u64 = 0;
|
||||
\\ var s: u64 = 0;
|
||||
\\ while i < {d} {{ s = s +% i; i = i + 1; }}
|
||||
\\ s
|
||||
\\}}
|
||||
,
|
||||
// element access through borrows (places and paths)
|
||||
\\module t
|
||||
\\fn main(heap: cap<mem.alloc>) -> u64
|
||||
\\effects []
|
||||
\\{{
|
||||
\\ var a: [u64; 8] = zero;
|
||||
\\ var i: u64 = 0;
|
||||
\\ while i < {d} {{ a[i as! usize % 8] = a[(i as! usize + 1) % 8] +% i; i = i + 1; }}
|
||||
\\ a[0]
|
||||
\\}}
|
||||
,
|
||||
// a call per iteration (frames)
|
||||
\\module t
|
||||
\\fn step(x: u64, b: slice<u64>) -> u64
|
||||
\\effects []
|
||||
\\{{
|
||||
\\ x +% b[x as! usize % 4]
|
||||
\\}}
|
||||
\\fn main(heap: cap<mem.alloc>) -> u64
|
||||
\\effects []
|
||||
\\{{
|
||||
\\ var b: [u64; 4] = [3; 4];
|
||||
\\ var i: u64 = 0;
|
||||
\\ var s: u64 = 0;
|
||||
\\ while i < {d} {{ s = step(s, ref b); i = i + 1; }}
|
||||
\\ s
|
||||
\\}}
|
||||
,
|
||||
// aggregate and array values built and copied every iteration
|
||||
\\module t
|
||||
\\struct P {{ a: u64, b: [u64; 4] }}
|
||||
\\fn main(heap: cap<mem.alloc>) -> u64
|
||||
\\effects []
|
||||
\\{{
|
||||
\\ var p: P = P {{ a: 0, b: [1; 4] }};
|
||||
\\ var i: u64 = 0;
|
||||
\\ while i < {d} {{ p = P {{ a: p.a +% i, b: [i; 4] }}; i = i + 1; }}
|
||||
\\ p.a
|
||||
\\}}
|
||||
,
|
||||
// heap allocation and free every iteration
|
||||
\\module t
|
||||
\\fn main(heap: cap<mem.alloc>) -> u64
|
||||
\\effects [mem.alloc]
|
||||
\\{{
|
||||
\\ var i: u64 = 0;
|
||||
\\ var s: u64 = 0;
|
||||
\\ while i < {d} {{
|
||||
\\ let o = own.new(i, heap) or trap;
|
||||
\\ s = s +% own.take(move o);
|
||||
\\ i = i + 1;
|
||||
\\ }}
|
||||
\\ s
|
||||
\\}}
|
||||
,
|
||||
};
|
||||
|
||||
test "execution memory is bounded by live state, not by the iteration count" {
|
||||
inline for (loop_shapes, 0..) |shape, k| {
|
||||
const small = try memoryOf(shape, 100_000);
|
||||
const mid = try memoryOf(shape, 1_000_000);
|
||||
const large = try memoryOf(shape, 4_000_000);
|
||||
errdefer std.debug.print("shape {d}: live {d}/{d}/{d} heap {d}/{d}/{d} collections {d}/{d}/{d}\n", .{
|
||||
k, small.peak_live, mid.peak_live, large.peak_live, small.peak_heap, mid.peak_heap, large.peak_heap,
|
||||
small.collections, mid.collections, large.collections,
|
||||
});
|
||||
try std.testing.expect(large.collections > 0);
|
||||
// Steady state: the live state of 4M iterations is the live state of 1M.
|
||||
try std.testing.expect(large.peak_live <= mid.peak_live + 64 * 1024);
|
||||
// The heap is bounded by a constant (collection threshold plus one growth step).
|
||||
try std.testing.expect(large.peak_heap <= 3 * Heap.min_threshold);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user