//! Borrow verification for frame storage (spec 08 §11). //! Reports E2101, E2102, E2105, E2106, E2107, E2108. //! //! Borrow definitions have static provenance. Live values must agree at joins. //! Resource relations also follow block arguments; a monotone worklist solves //! them before the diagnostic walk, including later predecessors/backedges. //! Runs after type verification, which prepares nominal properties and value types. const std = @import("std"); const air = @import("../air.zig"); const verifier = @import("../verifier.zig"); const ssa = @import("ssa.zig"); const diag = @import("../diag.zig"); const provenance = @import("provenance.zig"); const Context = verifier.Context; const ValueId = air.ValueId; /// One step of a path from a root (§11.2). const Seg = union(enum) { field: u32, /// One side of a `slice.split`, keyed by the split's left result. split: struct { key: ValueId, side: u1 }, /// An element or sub-range; overlaps every sibling. elem, /// A region allocation, keyed by its `ok` parameter; disjoint from /// every other allocation (spec 03 §20.2). alloc: ValueId, }; const Mode = enum { shared, exclusive }; /// Why a resource is no longer live (spec 06 §6.3). const Dead = enum { none, closed, moved }; const Info = struct { /// Owned borrows are created in this function; lent ones are parameters. owned: bool, mode: Mode, /// A local (`local.alloc` result) or a lent parameter. root: ValueId, path: []const Seg, /// Owned borrow or lent parameter this borrow was derived from. parent: ?ValueId, }; pub fn check(c: *Context) !void { // Signatures first: a borrow return needs `from` (§11.3). for (c.module.functions) |f| { if (f.ret.isBorrow() and f.ret_from == null) { try c.report("E2102", f.span, "a function returning a borrow must name its source with `from`", &.{ .{ .name = "function", .value = .{ .str = f.name } }, }); } } if (c.diags.items.len != 0) return; for (c.module.functions, c.value_types) |f, types| try checkFunction(c, f, types); } const Walker = struct { c: *Context, f: air.Function, types: []const air.Type, info: []?Info, /// Live owned borrows and live owned resources at the current point. live: []bool, /// How a resource stopped being live, for diagnostics. dead: []Dead, facts: provenance.State = .{}, /// First walk records definition/consumption events with relational /// checks disabled. Its diagnostics are discarded, not published. collecting: bool = false, events: ?*std.ArrayList(provenance.Event) = null, block: u32 = 0, index: u32 = 0, span: air.Span = .{ .line = 0, .col = 0 }, fn event(w: *Walker, e: provenance.Event) !void { if (w.collecting) { if (w.events) |out| try out.append(w.c.arena, e); } else try w.facts.apply(w.c.arena, e); } fn name(w: *Walker, v: ValueId) ![]const u8 { return w.c.valueName(w.f, v); } fn report(w: *Walker, code: []const u8, message: []const u8, borrow: ValueId, extra: ?struct { []const u8, ValueId }) !void { return w.reportWithOrigin(code, message, borrow, extra, null); } fn reportWithOrigin(w: *Walker, code: []const u8, message: []const u8, borrow: ValueId, extra: ?struct { []const u8, ValueId }, spawn: ?air.Span) !void { if (extra) |e| { var related: [1]diag.RelatedLocation = undefined; const context: []const diag.RelatedLocation = if ((std.mem.eql(u8, code, "E2101") or std.mem.eql(u8, code, "E2104")) and std.mem.eql(u8, e[0], "conflicts_with")) blk: { const sp = w.f.values[e[1]].span; related[0] = .{ .role = .conflicting_borrow, .value = try w.name(e[1]), .span = .{ .file = w.c.file, .line = sp.line, .col = sp.col } }; break :blk &related; } else if (spawn) |sp| blk: { related[0] = .{ .role = .task_spawn, .value = try w.name(e[1]), .span = .{ .file = w.c.file, .line = sp.line, .col = sp.col } }; break :blk &related; } else &.{}; try w.c.reportRelated(code, w.span, message, &.{ .{ .name = "function", .value = .{ .str = w.f.name } }, .{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } }, .{ .name = "inst", .value = .{ .int = w.index } }, .{ .name = "borrow", .value = .{ .str = try w.name(borrow) } }, .{ .name = e[0], .value = .{ .str = try w.name(e[1]) } }, }, context); } else { try w.c.report(code, w.span, message, &.{ .{ .name = "function", .value = .{ .str = w.f.name } }, .{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } }, .{ .name = "inst", .value = .{ .int = w.index } }, .{ .name = "borrow", .value = .{ .str = try w.name(borrow) } }, }); } } fn isAncestor(w: *Walker, anc: ValueId, of: ValueId) bool { var x: ?ValueId = of; while (x) |v| { if (v == anc) return true; x = if (w.info[v]) |i| i.parent else null; } return false; } /// Checks that `v`, used as a borrow, has not been ended (E2106). fn usable(w: *Walker, v: ValueId) !bool { const i = w.info[v].?; if (!i.owned or w.live[v]) return true; try w.report("E2106", "borrow used after it was ended", v, null); return false; } /// An access to `path` under `root` with `mode`, performed through /// `through` (a borrow whose ancestors do not conflict) or directly on a /// local (`through == null`). Reports the first conflict (E2101). fn access(w: *Walker, root: ValueId, path: []const Seg, mode: Mode, via: ?ValueId, who: ValueId) !void { return w.accessCode(root, path, mode, via, who, "E2101", "conflicting borrow or access"); } fn accessCode(w: *Walker, root: ValueId, path: []const Seg, mode: Mode, via: ?ValueId, who: ValueId, code: []const u8, message: []const u8) !void { for (w.live, 0..) |is_live, cv| { if (!is_live) continue; const ci = w.info[cv] orelse continue; // live resources are not borrows if (ci.root != root) continue; if (via) |t| if (w.isAncestor(@intCast(cv), t)) continue; if (mode == .shared and ci.mode == .shared) continue; if (!overlap(path, ci.path)) continue; try w.report(code, message, who, .{ "conflicts_with", @intCast(cv) }); return; } // Borrows lent to live tasks are accessed concurrently (spec 04 §34). for (w.facts.items.items) |l| { if (l.kind != .loan or !w.live[l.a]) continue; const li = w.info[l.b] orelse continue; if (li.root != root) continue; if (mode == .shared and li.mode == .shared) continue; if (!overlap(path, li.path)) continue; try w.report("E4101", "conflicts with a borrow lent to a live task", who, .{ "task", l.a }); return; } } /// Records a new owned borrow and checks it against live borrows. fn create(w: *Walker, v: ValueId, parent: ?ValueId, root: ValueId, path: []const Seg) !void { const mode: Mode = if (w.types[v].isMutBorrow()) .exclusive else .shared; w.info[v] = .{ .owned = true, .mode = mode, .root = root, .path = path, .parent = parent }; try w.access(root, path, mode, parent, v); w.live[v] = true; } /// Creates a borrow derived from borrow `p` with an extra path step. fn derive(w: *Walker, v: ValueId, p: ValueId, seg: ?Seg) !void { if (!try w.usable(p)) return w.poison(v, p); const pi = w.info[p].?; try w.create(v, p, pi.root, try w.extend(pi.path, seg)); } /// After an error, give `v` provenance so later uses do not cascade. fn poison(w: *Walker, v: ValueId, p: ValueId) void { const pi = w.info[p].?; w.info[v] = .{ .owned = true, .mode = .shared, .root = pi.root, .path = pi.path, .parent = p }; w.live[v] = true; } fn extend(w: *Walker, path: []const Seg, seg: ?Seg) ![]const Seg { const s = seg orelse return path; const out = try w.c.arena.alloc(Seg, path.len + 1); @memcpy(out[0..path.len], path); out[path.len] = s; return out; } /// Read or write through borrow `b` (load, store, slice.copy). fn useThrough(w: *Walker, b: ValueId, mode: Mode) !void { if (!try w.usable(b)) return; const bi = w.info[b].?; try w.access(bi.root, bi.path, mode, b, b); } fn isLocal(w: *Walker, v: ValueId) bool { return w.types[v] == .local; } /// Linear values: resources, owners and regions (spec 06 §6, spec 03 §19–§20). fn isResource(w: *Walker, v: ValueId) bool { return w.c.module.isLinearTypeCached(w.types[v]); } /// A non-consuming use of resource `v` (a borrow of it). fn resourceUsable(w: *Walker, v: ValueId) !bool { if (w.live[v]) return true; switch (w.dead[v]) { .closed => try w.report("E3001", "linear value used after it was closed, freed or destroyed", v, null), .moved => try w.report("E2001", "linear value used after its ownership was transferred", v, null), .none => try w.report("E3001", "linear value used before it is owned", v, null), } return false; } /// Consumes resource `v` by closing or by transfer (spec 06 §6.2). fn consume(w: *Walker, v: ValueId, how: Dead) !void { if (!w.live[v]) { return w.report("E2002", "linear value consumed twice", v, null); } // Consumption is an exclusive access to the whole resource. try w.access(v, &.{}, .exclusive, null, v); w.live[v] = false; w.dead[v] = how; try w.event(.{ .kill = v }); } }; pub fn overlap(a: []const Seg, b: []const Seg) bool { for (a[0..@min(a.len, b.len)], b[0..@min(a.len, b.len)]) |x, y| { switch (x) { .field => |fx| if (y == .field) { if (fx != y.field) return false; continue; }, .split => |sx| if (y == .split and sx.key == y.split.key) { if (sx.side != y.split.side) return false; continue; }, .alloc => |ka| if (y == .alloc) { if (ka != y.alloc) return false; continue; }, .elem => {}, } return true; } return true; // one path is a prefix of the other } const Edge = struct { target: u32, args: []const ValueId }; fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void { if (op.bufferTargets()) |t| { try out.append(arena, .{ .target = t.ok, .args = &.{} }); try out.append(arena, .{ .target = t.err, .args = &.{} }); return; } switch (op) { .br => |t| try out.append(arena, .{ .target = t.block, .args = t.args }), .cbr => |x| { try out.append(arena, .{ .target = x.then.block, .args = x.then.args }); try out.append(arena, .{ .target = x.@"else".block, .args = x.@"else".args }); }, .@"switch" => |x| { for (x.cases) |c| try out.append(arena, .{ .target = c.target.block, .args = c.target.args }); try out.append(arena, .{ .target = x.default.block, .args = x.default.args }); }, inline .enum_switch, .enum_take => |x| { for (x.arms) |a| try out.append(arena, .{ .target = a.block, .args = &.{} }); if (x.default) |d| try out.append(arena, .{ .target = d.block, .args = d.args }); }, .aggregate_unpack => |x| try out.append(arena, .{ .target = x.next, .args = &.{} }), .cap_narrow => |x| { try out.append(arena, .{ .target = x.ok, .args = &.{} }); try out.append(arena, .{ .target = x.err, .args = &.{} }); }, .intrinsic => |x| if (x.ok) |ok| { try out.append(arena, .{ .target = ok, .args = &.{} }); try out.append(arena, .{ .target = x.err.?, .args = &.{} }); }, inline .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => { const t = air.allocTargets(op).?; try out.append(arena, .{ .target = t.ok, .args = &.{} }); try out.append(arena, .{ .target = t.err, .args = &.{} }); }, // Values these terminators consume are consumed on every edge, by // `step`, before propagation; results arrive as block parameters. else => for (try air.waitTargets(op, arena)) |t| try out.append(arena, .{ .target = t.block, .args = &.{} }), } } fn walker(c: *Context, f: air.Function, types: []const air.Type) !Walker { var w: Walker = .{ .c = c, .f = f, .types = types, .info = try c.arena.alloc(?Info, f.values.len), .live = try c.arena.alloc(bool, f.values.len), .dead = try c.arena.alloc(Dead, f.values.len), }; @memset(w.info, null); @memset(w.live, false); @memset(w.dead, .none); for (f.params) |p| { if (p.ty.isBorrow()) w.info[p.value] = .{ .owned = false, .mode = if (p.ty.isMutBorrow()) .exclusive else .shared, .root = p.value, .path = &.{}, .parent = null, }; // Linear parameters were moved in: the function owns them (spec 06 §6.3). if (c.module.isLinearTypeCached(p.ty)) w.live[p.value] = true; } return w; } fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { const dom = try ssa.dominators(c.arena, f); // Most functions have no relational resources and retain the single walk. var relational = false; for (types) |t| switch (t) { .task, .scope, .shield, .guard => { relational = true; break; }, else => {}, }; if (!relational) { var w = try walker(c, f, types); return walkFunction(&w, dom, null, null); } const events = try c.arena.alloc(std.ArrayList(provenance.Event), f.blocks.len); for (events) |*list| list.* = .empty; var collecting = c.*; collecting.diags = .empty; var first = try walker(&collecting, f, types); first.collecting = true; try walkFunction(&first, dom, null, events); const facts = try solveProvenance(c.arena, f, types, dom, events, null); var final = try walker(c, f, types); try walkFunction(&final, dom, facts, null); } fn walkFunction(w: *Walker, dom: ssa.Dominators, facts: ?[]provenance.State, events: ?[]std.ArrayList(provenance.Event)) !void { const c = w.c; const f = w.f; const types = w.types; const entry_state = try c.arena.alloc(?[]bool, f.blocks.len); @memset(entry_state, null); entry_state[0] = try c.arena.dupe(bool, w.live); var reported_join = try c.arena.alloc(bool, f.blocks.len); @memset(reported_join, false); var out: std.ArrayList(Edge) = .empty; for (dom.rpo) |b| { if (events) |lists| w.events = &lists[b]; if (facts) |entries| w.facts = try entries[b].clone(c.arena); @memcpy(w.live, entry_state[b].?); const blk = f.blocks[b]; // Linear block parameters own their argument from here on; the // parameter of a region allocation's `ok` target is a live borrow. for (blk.params) |p| if (c.module.isLinearTypeCached(p.ty) or (p.ty.isBorrow() and w.info[p.value] != null)) { w.live[p.value] = true; w.dead[p.value] = .none; }; w.block = b; for (blk.insts, 0..) |inst, ii| { w.index = @intCast(ii); w.span = inst.span; if (inst.result) |v| if (w.isResource(v)) try w.event(.{ .kill = v }); try step(w, inst); } w.events = null; // Propagate along every edge; branch arguments of resource type are // moved on their own edge only (§11.4, spec 06 §6.2). out.clearRetainingCapacity(); try edges(blk.insts[blk.insts.len - 1].op, &out, c.arena); const base = try c.arena.dupe(bool, w.live); const base_dead = try c.arena.dupe(Dead, w.dead); const base_facts = try w.facts.clone(c.arena); for (out.items) |e| { @memcpy(w.live, base); @memcpy(w.dead, base_dead); w.facts = try base_facts.clone(c.arena); for (e.args) |a| if (c.module.isLinearTypeCached(types[a])) try w.consume(a, .moved); // A linear parameter of the target that is still live on this // edge would be overwritten: that instance leaks. Parameters are // not part of the incoming state; they come alive in the block. for (f.blocks[e.target].params) |p| { if (c.module.isLinearTypeCached(p.ty) and w.live[p.value]) try w.report("E3002", "linear value not consumed before it is redefined", p.value, null); w.live[p.value] = false; } if (entry_state[e.target]) |expected| { if (!std.mem.eql(bool, expected, w.live) and !reported_join[e.target]) { reported_join[e.target] = true; for (expected, w.live, 0..) |a, x, v| if (a != x) { const is_res = c.module.isLinearTypeCached(types[v]); try c.report(if (is_res) "E3002" else "E2105", f.blocks[e.target].span, if (is_res) "resource state differs between edges into this block" else "borrow state differs between edges into this block", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "block", .value = .{ .str = f.blocks[e.target].name } }, .{ .name = if (is_res) "resource" else "borrow", .value = .{ .str = try c.valueName(f, @intCast(v)) } }, }); break; }; } } else entry_state[e.target] = try c.arena.dupe(bool, w.live); if (facts) |entries| { const incoming = try edgeProvenance(c.arena, base_facts, f, types, dom, e); if (!reported_join[e.target]) if (entries[e.target].differentShield(incoming)) |shield| { reported_join[e.target] = true; try c.report("E3002", f.blocks[e.target].span, "shield order differs between edges into this block", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "block", .value = .{ .str = f.blocks[e.target].name } }, .{ .name = "resource", .value = .{ .str = try c.valueName(f, shield) } }, }); }; } } } } /// All linear arguments move simultaneously, including the scope position /// of facts whose task itself is not passed. Old target-parameter instances /// are overwritten; implicit outcome definitions were recorded as events. fn edgeProvenance(arena: std.mem.Allocator, base: provenance.State, f: air.Function, types: []const air.Type, dom: ssa.Dominators, e: Edge) !provenance.State { var out: provenance.State = .{}; for (base.items.items) |old| { var fact = old; fact.a = edgeValue(old.a, f, types, dom, e) orelse continue; fact.b = edgeValue(old.b, f, types, dom, e) orelse continue; _ = try out.add(arena, fact); } return out; } fn edgeValue(v: ValueId, f: air.Function, types: []const air.Type, dom: ssa.Dominators, e: Edge) ?ValueId { for (e.args, 0..) |arg, i| if (arg == v and types[arg].isLinear()) return f.blocks[e.target].params[i].value; // Explicit targets overwrite any older instance of their parameters. if (e.args.len != 0) for (f.blocks[e.target].params) |p| if (p.value == v) return null; return switch (f.values[v].def) { .param => v, .block_param => |d| if (dom.dominates(d.block, e.target)) v else null, .inst => |d| if (dom.dominates(d.block, e.target)) v else null, .none => unreachable, }; } const ProvenanceStats = struct { visits: usize = 0, facts: usize = 0, }; /// A finite monotone lattice of resource relations and loan origins. Events /// depend only on definitions and the collecting live-value transfer. Final /// error recovery may close extra values; checks filter those dead subjects, /// so collecting is conservative. Sparse sets retain insertion order; union /// does not impose a new equality rule on task/guard origins. fn solveProvenance(arena: std.mem.Allocator, f: air.Function, types: []const air.Type, dom: ssa.Dominators, events: []std.ArrayList(provenance.Event), stats: ?*ProvenanceStats) ![]provenance.State { const entries = try arena.alloc(provenance.State, f.blocks.len); for (entries) |*s| s.* = .{}; const visited = try arena.alloc(bool, f.blocks.len); @memset(visited, false); const queued = try arena.alloc(bool, f.blocks.len); @memset(queued, false); var queue: std.ArrayList(u32) = .empty; try queue.append(arena, 0); queued[0] = true; visited[0] = true; var pos: usize = 0; var out: std.ArrayList(Edge) = .empty; while (pos < queue.items.len) : (pos += 1) { const b = queue.items[pos]; if (stats) |s| s.visits += 1; queued[b] = false; var state = try entries[b].clone(arena); for (events[b].items) |event| try state.apply(arena, event); out.clearRetainingCapacity(); const block = f.blocks[b]; try edges(block.insts[block.insts.len - 1].op, &out, arena); for (out.items) |e| { const incoming = try edgeProvenance(arena, state, f, types, dom, e); const changed = try entries[e.target].merge(arena, incoming); if (stats) |s| s.facts += incoming.items.items.len; if ((!visited[e.target] or changed) and !queued[e.target]) { try queue.append(arena, e.target); queued[e.target] = true; } visited[e.target] = true; } } return entries; } fn step(w: *Walker, inst: air.Inst) !void { const f = w.f; switch (inst.op) { .local_store => |x| try w.access(x.local, &.{}, .exclusive, null, x.local), .local_zero => |v| try w.access(v, &.{}, .exclusive, null, v), .local_load => |v| try w.access(v, &.{}, .shared, null, v), .borrow_ref, .borrow_mut => |x| { const r = inst.result.?; if (w.isLocal(x)) { try w.create(r, null, x, &.{}); } else if (w.isResource(x)) { if (!try w.resourceUsable(x)) { w.info[r] = .{ .owned = true, .mode = .shared, .root = x, .path = &.{}, .parent = null }; w.live[r] = true; return; } try w.create(r, null, x, &.{}); } else try w.derive(r, x, null); }, .borrow_field => |x| try w.derive(inst.result.?, x.borrow, .{ .field = x.field }), .borrow_index => |x| try w.derive(inst.result.?, x.borrow, .elem), .buffer_view, .slice_make => |v| try w.derive(inst.result.?, v, null), .slice_sub => |x| try w.derive(inst.result.?, x.slice, .elem), .slice_split => |x| { const l = inst.result.?; try w.derive(l, x.slice, .{ .split = .{ .key = l, .side = 0 } }); try w.derive(inst.result2.?, x.slice, .{ .split = .{ .key = l, .side = 1 } }); }, .slice_len => |v| _ = try w.usable(v), // metadata: no access to elements .load => |v| try w.useThrough(v, .shared), .store => |x| try w.useThrough(x.borrow, .exclusive), .slice_copy => |x| { try w.useThrough(x.src, .shared); try w.useThrough(x.dst, .exclusive); }, .borrow_end => |v| { const i = w.info[v].?; if (!i.owned) return w.report("E2107", "a borrow parameter is lent by the caller and cannot be ended", v, null); if (!w.live[v]) return w.report("E2106", "borrow ended twice", v, null); // Ended even when rejected, so one mistake yields one diagnostic. defer w.live[v] = false; for (w.facts.items.items) |l| if (l.kind == .loan and w.live[l.a] and (l.b == v or w.isAncestor(v, l.b))) { return w.reportWithOrigin("E4302", "borrow ended while it is lent to a live task", v, .{ "task", l.a }, l.spawn); }; for (w.facts.items.items) |g| if (g.kind == .guard and w.live[g.a] and w.isAncestor(v, g.b)) { return w.report("E2102", "mutex borrow ended while a guard locked through it is live", v, .{ "guard", g.a }); }; for (w.live, 0..) |is_live, cv| { if (is_live and w.info[cv] != null and w.info[cv].?.parent == v) { return w.report("E2102", "borrow ended while a borrow derived from it is live", v, .{ "child", @intCast(cv) }); } } }, .call => |x| { try lendArgs(w, x.args); const callee = w.c.module.functions[x.callee]; for (callee.effects) |e| if (std.mem.eql(u8, e, "task.wait") or std.mem.eql(u8, e, "task.spawn")) { try noWaitUnderLock(w, "call of a function that may wait or spawn"); break; }; for (x.args) |a| if (w.isResource(a)) try w.consume(a, .moved); if (callee.ret_from) |p| { // The result borrows from the argument passed for `from` (§11.3). const a = x.args[p]; if (w.types[a].isBorrow() and w.info[a] != null) try w.derive(inst.result.?, a, .elem); } if (inst.result) |r| if (w.isResource(r)) { w.live[r] = true; }; }, inline .struct_make, .enum_make, .array_make => |x| { for (x.args) |v| if (w.isResource(v)) try w.consume(v, .moved); if (inst.result) |r| { if (w.isResource(r)) w.live[r] = true; } }, .struct_get => |x| { if (w.isResource(x.a)) { _ = try w.resourceUsable(x.a); try w.access(x.a, &.{.{ .field = x.field }}, .shared, null, x.a); } }, .aggregate_unpack => |x| { if (w.isResource(x.value)) try w.consume(x.value, .moved); }, .enum_take => |x| { if (w.isResource(x.value)) try w.consume(x.value, .moved); }, .buffer_new => {}, .buffer_len, .buffer_capacity => |v| try w.useThrough(v, .shared), .buffer_reserve => |x| try w.useThrough(x.borrow, .exclusive), .buffer_push => |x| { try w.useThrough(x.borrow, .exclusive); if (w.isResource(x.value)) try w.consume(x.value, .moved); }, .buffer_pop => |x| try w.useThrough(x.value, .exclusive), .buffer_free => |x| try w.consume(x.value, .moved), .own_pack => |x| { if (w.isResource(x.value)) try w.consume(x.value, .moved); }, .value_swap => |x| { try w.useThrough(x.borrow, .exclusive); if (w.isResource(x.value)) try w.consume(x.value, .moved); if (inst.result) |r| { if (w.isResource(r)) w.live[r] = true; } }, .own_free, .own_take => |v| { try w.consume(v, .closed); if (inst.result) |r| { if (w.isResource(r)) w.live[r] = true; } }, .task_scope_begin => w.live[inst.result.?] = true, .task_spawn => |x| { try noWaitUnderLock(w, "task.spawn"); const t = inst.result.?; try w.event(.{ .add = .{ .kind = .scope, .a = t, .b = x.scope } }); for (x.args) |a| { if (w.types[a].isBorrow()) { if (!try w.usable(a)) continue; const ai = w.info[a].?; // The loan must not conflict with live borrows or loans. try w.accessCode(ai.root, ai.path, ai.mode, a, a, "E4101", "lending a borrow that conflicts with a live borrow"); try w.event(.{ .add = .{ .kind = .loan, .a = t, .b = a, .spawn = inst.span } }); } else if (w.isResource(a)) try w.consume(a, .moved); } w.live[t] = true; }, .task_join => |t| { try noWaitUnderLock(w, "task.join"); // Joining ends the task's loans (they are active only while `t` lives). try w.consume(t, .closed); if (inst.result) |r| if (w.isResource(r)) { w.live[r] = true; }; }, .task_cancel => |t| _ = try w.resourceUsable(t), .task_scope_end => |s| { // Copy the selected handles before killing their facts. var children: std.ArrayList(ValueId) = .empty; for (w.facts.items.items) |fact| if (fact.kind == .scope and fact.b == s and w.live[fact.a]) { if (std.mem.indexOfScalar(ValueId, children.items, fact.a) == null) try children.append(w.c.arena, fact.a); }; for (children.items) |v| { try w.report("E4301", "scope ends while a task spawned from it is not joined", v, .{ "scope", s }); w.live[v] = false; // prefer E4301 to E3002 try w.event(.{ .kill = v }); } try w.consume(s, .closed); }, .region_reset => |v| { if (!try w.resourceUsable(v)) return; // Reset invalidates the generation: no reference may be live. try w.accessCode(v, &.{}, .exclusive, null, v, "E2104", "region reset would invalidate a live reference into the region"); }, .region_destroy => |v| { if (w.live[v]) try w.accessCode(v, &.{}, .exclusive, null, v, "E2104", "region destroy would invalidate a live reference into the region"); if (!w.live[v]) return w.report("E2002", "linear value consumed twice", v, null); w.live[v] = false; w.dead[v] = .closed; }, .region_new, .region_array => { const rb = switch (inst.op) { .region_new => |x| x.region, .region_array => |x| x.region, else => unreachable, }; if (!try w.usable(rb)) return; // The allocation is a fresh exclusive child of the shared region // borrow; it comes alive on the `ok` edge (spec 03 §20.2). const ok = air.allocTargets(inst.op).?.ok; const p = w.f.blocks[ok].params[0].value; const ri = w.info[rb].?; w.info[p] = .{ .owned = true, .mode = .exclusive, .root = ri.root, .path = try w.extend(ri.path, .{ .alloc = p }), .parent = rb }; }, .intrinsic => |x| { try lendArgs(w, x.args); // Closing intrinsics consume on both edges, so before propagation. for (x.args, air.authority.intrinsics[x.index].operands) |a, o| if (o == .consumed) try w.consume(a, .closed); }, .ret => |v| try retStep(w, v), .task_join_cancel => |x| { try noWaitUnderLock(w, "task.join.cancel"); const t = x.task; const back = w.f.blocks[x.cancelled].params[0].value; // On `cancelled` the same task comes back: its scope and loans // move to the new handle value (spec 04 §37.3). try w.event(.{ .kill = back }); try w.event(.{ .rename = .{ .from = t, .to = back } }); try w.consume(t, .closed); }, .task_shield_begin => { const r = inst.result.?; for (w.live, 0..) |is_live, v| if (is_live and w.types[v] == .shield) { try w.event(.{ .add = .{ .kind = .inner, .a = r, .b = @intCast(v) } }); }; w.live[r] = true; }, .task_shield_end => |sh| { if (w.live[sh]) for (w.facts.items.items) |fact| if (fact.kind == .inner and fact.b == sh and w.live[fact.a]) { try w.report("E4305", "shield ended while a more inner shield is live", sh, .{ "inner", fact.a }); break; }; try w.consume(sh, .closed); }, .channel_dup => |v| { try lendArgs(w, &.{v}); w.live[inst.result.?] = true; }, .channel_send => |x| { try noWaitUnderLock(w, "channel.send"); try lendArgs(w, &.{x.sender}); if (w.isResource(x.value)) try w.consume(x.value, .moved); }, .channel_recv => |x| { try noWaitUnderLock(w, "channel.recv"); try lendArgs(w, &.{x.receiver}); }, .channel_close_sender => |v| try w.consume(v, .closed), .channel_close_receiver => |x| try w.consume(x.receiver, .closed), .select => |x| { try noWaitUnderLock(w, "select"); // Only one arm runs, so arms may name the same endpoint borrow. for (x.arms, 0..) |arm, i| { const seen = for (x.arms[0..i]) |prev| { if (prev.endpoint == arm.endpoint) break true; } else false; if (!seen) try lendArgs(w, &.{arm.endpoint}); } const buf = try w.c.arena.alloc(ValueId, x.arms.len); for (air.Op.selectValues(x.arms, buf)) |v| if (w.isResource(v)) try w.consume(v, .moved); }, .mutex_make => |v| { if (w.isResource(v)) try w.consume(v, .moved); w.live[inst.result.?] = true; }, .mutex_take => |m| { if (try takeLent(w, m)) return; try w.consume(m, .closed); if (w.isResource(inst.result.?)) w.live[inst.result.?] = true; }, .mutex_lock => |x| { try noWaitUnderLock(w, "mutex.lock"); try lendArgs(w, &.{x.mutex}); const g = w.f.blocks[x.ok].params[0].value; try w.event(.{ .kill = g }); try w.event(.{ .add = .{ .kind = .guard, .a = g, .b = x.mutex } }); }, .mutex_borrow => |g| { const r = inst.result.?; if (!try w.resourceUsable(g)) { w.info[r] = .{ .owned = true, .mode = .exclusive, .root = g, .path = &.{}, .parent = null }; w.live[r] = true; return; } try w.create(r, null, g, &.{}); }, .mutex_unlock => |g| { if (!w.live[g]) return w.report("E2002", "linear value consumed twice", g, null); for (w.live, 0..) |is_live, b| if (is_live and w.info[b] != null and w.info[b].?.root == g) { try w.report("E2102", "guard unlocked while a borrow from it is live", @intCast(b), .{ "guard", g }); break; }; w.live[g] = false; w.dead[g] = .closed; try w.event(.{ .kill = g }); }, // Graphs (spec 03 §22–§24). An access is a child borrow of the // container borrow; a `mut` child is exclusive for the whole island. .island_alloc => |x| try w.useThrough(x.island, .exclusive), .island_root, .frozen_root, .arc_root => |v| _ = try w.usable(v), inline .island_borrow, .frozen_borrow, .arc_borrow => |x| try w.derive(inst.result.?, x.owner, .elem), .island_freeze, .arc_from_frozen => |v| { try w.consume(v, .moved); w.live[inst.result.?] = true; }, .island_destroy, .frozen_release, .arc_release => |v| try w.consume(v, .closed), .arc_clone => |v| { try lendArgs(w, &.{v}); w.live[inst.result.?] = true; }, // Atomics (spec 04 §23, §28): a cell is a linear value; operations go // through a shared borrow of it (interior mutability), `take` consumes // it and needs every borrow ended. .atomic_new => w.live[inst.result.?] = true, .atomic_take => |v| if (!try takeLent(w, v)) try w.consume(v, .closed), .atomic_load => |x| try w.useThrough(x.cell, .shared), inline .atomic_store, .atomic_rmw => |x| try w.useThrough(x.cell, .shared), .atomic_cmpxchg => |x| try w.useThrough(x.cell, .shared), // Values of these instructions are not borrows; any borrow operand // here was already rejected by the type stage. else => {}, } _ = f; } /// Taking a mutex or an atomic cell while a borrow of it is lent to a live /// task races with that task: `E4101` rather than `E2101` (spec 04 §28, §40). fn takeLent(w: *Walker, v: ValueId) !bool { for (w.facts.items.items) |l| if (l.kind == .loan and w.live[l.a] and w.info[l.b] != null and w.info[l.b].?.root == v) { try w.report("E4101", "taken while a borrow of it is lent to a live task", v, .{ "task", l.a }); // Consumed all the same, so the mistake is not reported again as a leak. w.live[v] = false; w.dead[v] = .closed; return true; }; return false; } /// The critical-section rule (spec 04 §41): no operation that may wait or /// spawn while a lock guard is live. fn noWaitUnderLock(w: *Walker, op: []const u8) !void { for (w.live, 0..) |is_live, g| if (is_live and w.types[g] == .guard) { return w.c.report("E4304", w.span, "operation that may wait or spawn while a lock guard is live", &.{ .{ .name = "function", .value = .{ .str = w.f.name } }, .{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } }, .{ .name = "inst", .value = .{ .int = w.index } }, .{ .name = "guard", .value = .{ .str = try w.name(@intCast(g)) } }, .{ .name = "op", .value = .{ .str = op } }, }); }; } /// Borrow arguments of a call or intrinsic are lent for its duration and /// must not alias each other when one is exclusive (§11.2). fn lendArgs(w: *Walker, args: []const ValueId) !void { // Arguments already reported; a conflict involving one of them is the // same mistake and is not reported again. const reported = try w.c.arena.alloc(bool, args.len); @memset(reported, false); for (args, 0..) |a, i| { if (!w.types[a].isBorrow()) continue; if (!try w.usable(a)) continue; const ai = w.info[a].?; // The argument is lent for the call: checked like a use of `a`. const before = w.c.diags.items.len; try w.access(ai.root, ai.path, ai.mode, a, a); if (w.c.diags.items.len != before) { reported[i] = true; continue; } // Arguments must not alias each other if either is exclusive (§11.2). for (args[0..i], 0..) |b, j| { if (reported[j]) continue; if (!w.types[b].isBorrow()) continue; const bi = w.info[b].?; if (bi.root != ai.root) continue; if (ai.mode == .shared and bi.mode == .shared) continue; if (overlap(ai.path, bi.path)) { try w.report("E2101", "call arguments alias and one of them is exclusive", a, .{ "conflicts_with", b }); break; } } } } fn retStep(w: *Walker, value: ?ValueId) !void { const f = w.f; var transferred: ?ValueId = null; if (value) |v| if (w.isResource(v)) try w.consume(v, .moved); if (f.ret_from) |p| { const pv = f.params[p].value; const b = value.?; if (!try w.usable(b)) return; const bi = w.info[b].?; if (bi.root != pv) { if (w.isLocal(bi.root)) { return w.report("E2108", "borrow of frame storage escapes its function", b, .{ "local", bi.root }); } return w.report("E2102", "returned borrow does not derive from the `from` parameter", b, .{ "from", pv }); } transferred = b; } // Only the returned borrow and its owned ancestors may remain live. for (w.live, 0..) |is_live, v| { if (!is_live) continue; if (transferred) |t| if (w.isAncestor(@intCast(v), t)) continue; if (w.isResource(@intCast(v))) { try w.report("E3002", "resource not consumed before return", @intCast(v), null); } else try w.report("E2105", "borrow not ended before return", @intCast(v), null); } } // ---------------------------------------------------------------- tests const h = "module t\nair 0\nlang 0.1\nfeatures [arrays, ownership]\n"; fn fun(comptime sig: []const u8, comptime body: []const u8) []const u8 { return h ++ "fn @f" ++ sig ++ "\neffects []\nentry:\n" ++ body; } const local_x = " %x = local.alloc u8\n local.zero %x\n"; test "exclusive XOR shared" { try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.mut %x\n %b = borrow.ref %x\n borrow.end %b\n borrow.end %a\n ret\n"), &.{"E2101"}); try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n %b = borrow.ref %x\n borrow.end %b\n borrow.end %a\n ret\n"), &.{}); try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n %one = const.u8 1\n local.store %x, %one\n borrow.end %a\n ret\n"), &.{"E2101"}); try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %a = borrow.ref %x\n %v = local.load %x\n borrow.end %a\n ret %v\n"), &.{}); try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %a = borrow.mut %x\n %v = local.load %x\n borrow.end %a\n ret %v\n"), &.{"E2101"}); } test "reborrow freezes the parent" { // Reading through a mut borrow while a shared child is live is fine; // writing is not. try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n %v = load %m\n borrow.end %r\n borrow.end %m\n ret %v\n"), &.{}); try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n %z = const.u8 0\n store %m, %z\n borrow.end %r\n borrow.end %m\n ret\n"), &.{"E2101"}); try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n borrow.end %m\n borrow.end %r\n ret\n"), &.{"E2102"}); } test "fields and split halves are disjoint" { const s = h ++ "type @P = struct { a: u8, b: u8 }\n"; try verifier.expectCodes(s ++ "fn @f() -> void\neffects []\nentry:\n %x = local.alloc @P\n local.zero %x\n %m = borrow.mut %x\n %fa = borrow.field @P.a, %m\n %fb = borrow.field @P.b, %m\n borrow.end %fa\n borrow.end %fb\n borrow.end %m\n ret\n", &.{}); try verifier.expectCodes(s ++ "fn @f() -> void\neffects []\nentry:\n %x = local.alloc @P\n local.zero %x\n %m = borrow.mut %x\n %fa = borrow.field @P.a, %m\n %fb = borrow.field @P.a, %m\n borrow.end %fa\n borrow.end %fb\n borrow.end %m\n ret\n", &.{"E2101"}); const arr = " %x = local.alloc array\n local.zero %x\n %m = borrow.mut %x\n %s = slice.make %m\n %k = const.usize 4\n %l, %r = slice.split %s, %k\n"; const ends = " borrow.end %l\n borrow.end %r\n borrow.end %s\n borrow.end %m\n ret\n"; try verifier.expectCodes(comptime fun("() -> void", arr ++ " %lr = borrow.ref %l\n slice.copy %r, %lr\n borrow.end %lr\n" ++ ends), &.{}); // Two element borrows of the same parent overlap. try verifier.expectCodes(comptime fun("() -> void", arr ++ " %z = const.usize 0\n %e1 = borrow.index %l, %z\n %e2 = borrow.index %l, %z\n borrow.end %e1\n borrow.end %e2\n" ++ ends), &.{"E2101"}); // slice.copy within one slice: source and destination overlap. try verifier.expectCodes(comptime fun("() -> void", arr ++ " %lr = borrow.ref %l\n slice.copy %l, %lr\n borrow.end %lr\n" ++ ends), &.{"E2101"}); } test "path linearity" { try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " %a = borrow.ref %x\n cbr %c, @p(), @q()\np:\n borrow.end %a\n ret\nq:\n borrow.end %a\n ret\n"), &.{}); try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " %a = borrow.ref %x\n cbr %c, @p(), @q()\np:\n borrow.end %a\n ret\nq:\n ret\n"), &.{"E2105"}); try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " %a = borrow.ref %x\n cbr %c, @p(), @q()\np:\n borrow.end %a\n br @j()\nq:\n br @j()\nj:\n ret\n"), &.{ "E2105", "E2105" }); try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n borrow.end %a\n borrow.end %a\n ret\n"), &.{"E2106"}); try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %a = borrow.ref %x\n borrow.end %a\n %v = load %a\n ret %v\n"), &.{"E2106"}); // trap paths carry no obligation. try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n trap\n"), &.{}); } test "loops end their borrows before the back edge" { try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " br @loop()\nloop:\n %a = borrow.ref %x\n borrow.end %a\n cbr %c, @loop(), @out()\nout:\n ret\n"), &.{}); try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " br @loop()\nloop:\n %a = borrow.ref %x\n cbr %c, @loop(), @out()\nout:\n borrow.end %a\n ret\n"), &.{"E2105"}); } test "returning borrows" { try verifier.expectCodes(h ++ "fn @first(%s: slice) -> ref from %s\neffects []\nentry:\n %z = const.usize 0\n %e = borrow.index %s, %z\n ret %e\n", &.{}); try verifier.expectCodes(h ++ "fn @f(%s: slice) -> ref\neffects []\nentry:\n %z = const.usize 0\n %e = borrow.index %s, %z\n ret %e\n", &.{"E2102"}); try verifier.expectCodes(h ++ "fn @f(%p: ref) -> ref from %p\neffects []\nentry:\n" ++ local_x ++ " %b = borrow.ref %x\n ret %b\n", &.{"E2108"}); try verifier.expectCodes(h ++ "fn @f(%p: ref, %q: ref) -> ref from %p\neffects []\nentry:\n %b = borrow.ref %q\n ret %b\n", &.{"E2102"}); try verifier.expectCodes(h ++ "fn @f(%p: ref) -> void\neffects []\nentry:\n borrow.end %p\n ret\n", &.{"E2107"}); } test "call results keep their source alive; mut arguments do not alias" { const first = "fn @first(%s: slice) -> ref from %s\neffects []\nentry:\n %z = const.usize 0\n %e = borrow.index %s, %z\n ret %e\n"; const caller = "fn @f() -> u8\neffects []\nentry:\n %x = local.alloc array\n local.zero %x\n %r = borrow.ref %x\n %s = slice.make %r\n %e = call @first(%s)\n"; try verifier.expectCodes(h ++ caller ++ " %v = load %e\n borrow.end %e\n borrow.end %s\n borrow.end %r\n ret %v\n" ++ first, &.{}); try verifier.expectCodes(h ++ caller ++ " borrow.end %s\n %v = load %e\n borrow.end %e\n borrow.end %r\n ret %v\n" ++ first, &.{"E2102"}); const two = "fn @g(%a: mut, %b: ref) -> void\neffects []\nentry:\n ret\n"; try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n" ++ local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n call @g(%m, %r)\n borrow.end %r\n borrow.end %m\n ret\n" ++ two, &.{"E2101"}); } test "task provenance rotation reaches every header parameter with bounded visits" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); const count = 63; // Below the existing 64-parameter limit. var source: std.Io.Writer.Allocating = .init(a); const out = &source.writer; try out.writeAll("module rotation\nair 0\nlang 0.1\nfeatures [cancellation, effects, ownership, tasks]\nfn @main() -> void\neffects [task.spawn]\nentry:\n %x = local.alloc u8\n local.zero %x\n %r = borrow.ref %x\n %s = task.scope.begin\n %t0 = task.spawn %s, @read(%r)\n"); for (1..count) |i| try out.print(" %t{d} = task.spawn %s, @zero()\n", .{i}); try out.writeAll(" br @head("); for (0..count) |i| try out.print("{s}%t{d}", .{ if (i == 0) "" else ", ", i }); try out.writeAll(")\nhead("); for (0..count) |i| try out.print("{s}%p{d}: task", .{ if (i == 0) "" else ", ", i }); try out.writeAll("):\n br @head("); for (0..count) |i| try out.print("{s}%p{d}", .{ if (i == 0) "" else ", ", (i + 1) % count }); try out.writeAll(")\nfn @read(%p: ref) -> u8\neffects []\nentry:\n %v = load %p\n ret %v\nfn @zero() -> u8\neffects []\nentry:\n %v = const.u8 0\n ret %v\n"); const parsed = try air.parse.parse(a, "rotation.air", source.written()); try std.testing.expectEqual(@as(usize, 0), parsed.diagnostics.len); var c: Context = .{ .arena = a, .file = "rotation.air", .module = parsed.module.? }; try verifier.cfg.check(&c); try ssa.check(&c); try verifier.types.check(&c); try std.testing.expectEqual(@as(usize, 0), c.diags.items.len); const f = c.module.functions[0]; const types = c.value_types[0]; const dom = try ssa.dominators(a, f); const events = try a.alloc(std.ArrayList(provenance.Event), f.blocks.len); for (events) |*e| e.* = .empty; var w = try walker(&c, f, types); w.collecting = true; try walkFunction(&w, dom, null, events); try std.testing.expectEqual(@as(usize, 0), c.diags.items.len); var stats: ProvenanceStats = .{}; const entries = try solveProvenance(a, f, types, dom, events, &stats); var loans: usize = 0; for (entries[1].items.items) |fact| if (fact.kind == .loan) { loans += 1; try std.testing.expectEqual(@as(u32, 12), fact.spawn.line); }; try std.testing.expectEqual(@as(usize, count), loans); try std.testing.expect(stats.visits <= count + 2); try std.testing.expect(stats.facts <= 2 * count * (count + 2)); }