interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / src / checker2 / c2_check.c

1114 lines · 52769 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* c2_check.c: checker2 acceptance rules over a decoded unit (spec/one-layer-receipts.md section 9).
18 *
19 * Written from docs/osc/OSC-{1,2,3}-DESIGN.md, OSC-EXT-BYTES-DESIGN.md and the osc_ir.h comments
20 * only. Rules, in the order applied:
21 * unit tables -> per-function types -> CFG shape -> per-instruction typing -> calls ->
22 * handle disciplines -> definite assignment -> loop bounds (termination) -> ownership flow ->
23 * mutable-borrow exclusivity.
24 * The ownership flow is a may-analysis. Uses after a release or move are refused when they hold on
25 * every path; an object still held at a return or at an overwrite is refused when it is held on
26 * SOME non-trapping path (omega#465). Drop-flag guarded releases (OSC-3 item 3) are tracked per
27 * value of their flag, so the code oscc emits for them is not refused through that imprecision. */
28#include <stdarg.h>
29#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
32
33#include "c2_ir.h"
34
35static int fail(C2Verdict *v, const char *rule, int func, int insn, const char *fmt, ...)
36{
37 if (v) {
38 v->ok = 0;
39 v->rule = rule;
40 v->func = func;
41 v->insn = insn;
42 va_list ap;
43 va_start(ap, fmt);
44 vsnprintf(v->detail, sizeof v->detail, fmt, ap);
45 va_end(ap);
46 }
47 return -1;
48}
49
50/* ------------------------------------------------------------------ types */
51
52static int is_value(uint8_t s) { return s >= S_BOOL && s <= S_I64; }
53static int is_int(uint8_t s) { return s >= S_U8 && s <= S_I64; }
54static int is_signed(uint8_t s) { return s >= S_I8 && s <= S_I64; }
55static unsigned width(uint8_t s)
56{
57 switch (s) {
58 case S_BOOL: return 1;
59 case S_U8: case S_I8: return 8;
60 case S_U16: case S_I16: return 16;
61 case S_U32: case S_I32: return 32;
62 case S_U64: case S_I64: return 64;
63 default: return 0;
64 }
65}
66static int is_scalar_t(const C2Type *t) { return is_value(t->s); }
67static int is_ref(const C2Type *t) { return t->s == S_REF; }
68static int is_array_ref(const C2Type *t) { return t->s == S_REF && t->sid == 0; }
69static int is_struct_ref(const C2Type *t) { return t->s == S_REF && t->sid != 0; }
70static int is_slice(const C2Type *t) { return t->s == S_BYTES || t->s == S_CELLS; }
71static int is_u64(const C2Type *t) { return t->s == S_U64; }
72static int same_type(const C2Type *a, const C2Type *b)
73{
74 if (a->s != b->s) return 0;
75 if (a->s != S_REF) return 1;
76 return a->kind == b->kind && a->elem == b->elem && a->len == b->len && a->sid == b->sid;
77}
78/* Same object shape (element, length, struct), any reference kind. */
79static int same_shape(const C2Type *a, const C2Type *b)
80{
81 return a->s == S_REF && b->s == S_REF && a->elem == b->elem && a->len == b->len && a->sid == b->sid;
82}
83/* A reference of kind `from` may be bound to a destination of kind `to` (move, borrow, reborrow,
84 * downgrade): own->own|shared|mut, mut->mut|shared, shared->shared. */
85static int bindable(uint8_t to, uint8_t from)
86{
87 if (from == K_OWN) return 1;
88 if (from == K_MUT) return to == K_MUT || to == K_SHARED;
89 if (from == K_SHARED) return to == K_SHARED;
90 return 0;
91}
92/* imm is the canonical 64-bit value of a constant of scalar s */
93static int canonical(uint8_t s, uint64_t imm)
94{
95 unsigned w = width(s);
96 if (s == S_BOOL) return imm <= 1;
97 if (w == 64) return 1;
98 if (!is_signed(s)) return imm < (1ull << w);
99 int64_t x = (int64_t)imm;
100 int64_t lo = -(int64_t)(1ull << (w - 1)), hi = (int64_t)(1ull << (w - 1)) - 1;
101 return x >= lo && x <= hi;
102}
103
104/* ------------------------------------------------------------------ unit tables */
105
106static int check_structs(const C2Unit *u, C2Verdict *v)
107{
108 for (int k = 0; k < u->nstructs; k++) {
109 const C2Struct *s = &u->st[k];
110 for (int j = 0; j < k; j++)
111 if (strcmp(u->st[j].name, s->name) == 0)
112 return fail(v, "C2-STRUCT-NAME", -1, -1, "struct %s defined twice", s->name);
113 unsigned off = 0;
114 for (int f = 0; f < s->nfields; f++) {
115 const C2Field *fd = &s->f[f];
116 for (int g = 0; g < f; g++)
117 if (strcmp(s->f[g].name, fd->name) == 0)
118 return fail(v, "C2-STRUCT-NAME", -1, -1, "field %s.%s twice", s->name, fd->name);
119 if (!is_value(fd->s)) return fail(v, "C2-STRUCT-FIELD-TYPE", -1, -1, "%s.%s", s->name, fd->name);
120 if (fd->alen > C2_MAX_ARRAY)
121 return fail(v, "C2-STRUCT-FIELD-LEN", -1, -1, "%s.%s length %u", s->name, fd->name, fd->alen);
122 if (fd->off != off) /* GUARD:struct-offset */
123 return fail(v, "C2-STRUCT-LAYOUT", -1, -1, "%s.%s offset %u, prefix sum %u", s->name, fd->name, fd->off, off);
124 off += fd->alen ? fd->alen : 1;
125 }
126 if (s->ncells != off || off < 1 || off > C2_MAX_ARRAY) /* GUARD:struct-cells */
127 return fail(v, "C2-STRUCT-LAYOUT", -1, -1, "%s cells %u, fields need %u", s->name, s->ncells, off);
128 }
129 return 0;
130}
131
132static int check_type(const C2Unit *u, const C2Type *t)
133{
134 if (t->s >= S_LIMIT || t->s == S_VOID) return 0;
135 if (t->s != S_REF) return 1;
136 if (t->kind < K_OWN || t->kind > K_MUT) return 0;
137 if (t->elem == S_VOID) { /* struct reference */
138 if (t->sid < 1 || t->sid > u->nstructs) return 0;
139 return t->len == u->st[t->sid - 1].ncells;
140 }
141 return is_value(t->elem) && t->sid == 0 && t->len >= 1 && t->len <= C2_MAX_ARRAY;
142}
143
144/* ------------------------------------------------------------------ per-function context */
145
146#define BSW 8 /* 512 bits: enough for C2_MAX_VREGS (480) and C2_MAX_BLOCKS (512) */
147typedef struct { uint64_t w[BSW]; } Bits;
148static void bset(Bits *b, unsigned i) { b->w[i >> 6] |= 1ull << (i & 63); }
149static int btest(const Bits *b, unsigned i) { return (int)((b->w[i >> 6] >> (i & 63)) & 1); }
150static void ball(Bits *b) { memset(b, 0xff, sizeof *b); }
151static void band(Bits *d, const Bits *s) { for (int i = 0; i < BSW; i++) d->w[i] &= s->w[i]; }
152static int beq(const Bits *a, const Bits *b) { return memcmp(a, b, sizeof *a) == 0; }
153static void bor(Bits *d, const Bits *s) { for (int i = 0; i < BSW; i++) d->w[i] |= s->w[i]; }
154static void bclr(Bits *b, unsigned i) { b->w[i >> 6] &= ~(1ull << (i & 63)); }
155
156typedef struct {
157 const C2Unit *u;
158 const C2Func *f;
159 int fi;
160 C2Verdict *v;
161 int nb;
162 int *blk_of; /* insn -> block */
163 int succ[C2_MAX_BLOCKS][2];
164 int nsucc[C2_MAX_BLOCKS];
165 int reach[C2_MAX_BLOCKS];
166 Bits dom[C2_MAX_BLOCKS];
167 int ndefs[C2_MAX_VREGS];
168 int def_insn[C2_MAX_VREGS]; /* the single definition, or -1 */
169 int quiet; /* ownership fixpoint: apply effects, report nothing */
170} Fx;
171
172static int term(uint8_t op) { return op == C2_BR || op == C2_CBR || op == C2_RET; }
173
174/* uses of an instruction (vregs read); returns count */
175static int uses(const C2Insn *in, int16_t *o)
176{
177 int n = 0;
178 switch (in->op) {
179 case C2_CONST: case C2_TRAP: case C2_BR: case C2_AOPEN: case C2_POPEN: break;
180 case C2_MOV: case C2_CAST: case C2_UN: case C2_ALLOC: case C2_RELEASE: case C2_ADESTROY: case C2_PCLOSE:
181 case C2_CBR: o[n++] = in->a; break;
182 case C2_RET: if (in->a >= 0) o[n++] = in->a; break;
183 case C2_BIN: case C2_CMP: case C2_LOAD: case C2_AALLOC: case C2_HALLOC: case C2_HGEN: case C2_SLOAD:
184 o[n++] = in->a; o[n++] = in->b; break;
185 case C2_STORE: case C2_HFREE: case C2_HLOAD: case C2_SSTORE: o[n++] = in->a; o[n++] = in->b; o[n++] = in->c; break;
186 case C2_HSTORE: o[n++] = in->a; o[n++] = in->b; o[n++] = in->c; o[n++] = in->args[0]; break;
187 case C2_FLOAD: o[n++] = in->a; if (in->b >= 0) o[n++] = in->b; break;
188 case C2_FSTORE: o[n++] = in->a; if (in->b >= 0) o[n++] = in->b; o[n++] = in->c; break;
189 case C2_CALL: for (int k = 0; k < in->nargs; k++) o[n++] = in->args[k]; break;
190 default: break;
191 }
192 return n;
193}
194
195static int defines(const C2Insn *in)
196{
197 switch (in->op) {
198 case C2_CONST: case C2_MOV: case C2_BIN: case C2_UN: case C2_CMP: case C2_CAST: case C2_ALLOC: case C2_LOAD:
199 case C2_FLOAD: case C2_AOPEN: case C2_AALLOC: case C2_POPEN: case C2_HALLOC: case C2_HGEN: case C2_HLOAD:
200 case C2_SLOAD:
201 return in->dst;
202 case C2_CALL: return in->dst; /* -1 for a void call */
203 default: return -1;
204 }
205}
206
207#define F(rule, ...) return fail(x->v, rule, x->fi, (int)ii, __VA_ARGS__)
208
209static const C2Type *T(const Fx *x, int16_t r) { return &x->f->vt[r]; }
210
211static int check_insn(Fx *x, uint32_t ii)
212{
213 const C2Func *f = x->f;
214 const C2Insn *in = &f->in[ii];
215 int nv = f->nvregs;
216 int16_t us[8];
217 int nu = uses(in, us);
218 for (int k = 0; k < nu; k++) {
219 if (us[k] < 0 || us[k] >= nv) F("C2-OPERAND-RANGE", "operand v%d out of range", us[k]); /* GUARD:operand-range */
220 }
221 int d = defines(in);
222 int need_dst = !(in->op == C2_CALL && f->in[ii].dst == -1) && d != -1 ? 1 : 0;
223 if (in->op != C2_CALL && (in->op == C2_CONST || in->op == C2_MOV || in->op == C2_BIN || in->op == C2_UN ||
224 in->op == C2_CMP || in->op == C2_CAST || in->op == C2_ALLOC || in->op == C2_LOAD ||
225 in->op == C2_FLOAD || in->op == C2_AOPEN || in->op == C2_AALLOC || in->op == C2_POPEN ||
226 in->op == C2_HALLOC || in->op == C2_HGEN || in->op == C2_HLOAD || in->op == C2_SLOAD) &&
227 in->dst < 0)
228 F("C2-OPERAND-RANGE", "missing destination");
229 if (need_dst && (d < 0 || d >= nv)) F("C2-OPERAND-RANGE", "destination v%d out of range", d); /* GUARD:dst-range */
230 if (d >= 0 && is_slice(T(x, d))) F("C2-SLICE-WRITE", "slice register v%d redefined", d);
231 if (d >= 0 && d < f->nparams && d > 0 && is_slice(T(x, d - 1)))
232 F("C2-SLICE-WRITE", "slice length register v%d redefined", d);
233
234 const C2Type *td = d >= 0 ? T(x, d) : NULL;
235 const C2Type *ta = in->a >= 0 && in->a < nv ? T(x, in->a) : NULL;
236 const C2Type *tb = in->b >= 0 && in->b < nv ? T(x, in->b) : NULL;
237 const C2Type *tc = in->c >= 0 && in->c < nv ? T(x, in->c) : NULL;
238
239 switch (in->op) {
240 case C2_CONST:
241 if (!is_scalar_t(td)) F("C2-TYPE-CONST", "constant into a non-scalar register");
242 if (!canonical(td->s, in->imm)) F("C2-CONST-CANONICAL", "constant %llu not canonical for its type", (unsigned long long)in->imm); /* GUARD:const-canonical */
243 break;
244 case C2_MOV:
245 if (is_slice(ta) || is_slice(td)) F("C2-SLICE-ESCAPE", "slice copied");
246 if (is_ref(td) || is_ref(ta)) {
247 if (!same_shape(td, ta) || !bindable(td->kind, ta->kind)) F("C2-TYPE-MOV", "reference kinds or shapes do not bind"); /* GUARD:mov-ref */
248 } else {
249 if (!same_type(td, ta) || !is_scalar_t(td)) F("C2-TYPE-MOV", "MOV between different types"); /* GUARD:mov-type */
250 }
251 break;
252 case C2_BIN:
253 if (in->sub < B_ADD || in->sub >= B_LIMIT) F("C2-DECODE-SUBOP", "binary op %u", in->sub);
254 if (in->sub == B_SHL || in->sub == B_SHR) {
255 if (!is_int(td->s) || !same_type(td, ta) || !is_int(tb->s)) F("C2-TYPE-BIN", "shift operand types"); /* GUARD:bin-shift */
256 } else if (in->sub == B_AND || in->sub == B_OR || in->sub == B_XOR) {
257 if (!is_scalar_t(td) || !same_type(td, ta) || !same_type(td, tb)) F("C2-TYPE-BIN", "bitwise operand types");
258 } else {
259 if (!is_int(td->s) || !same_type(td, ta) || !same_type(td, tb)) F("C2-TYPE-BIN", "arithmetic operand types"); /* GUARD:bin-type */
260 }
261 break;
262 case C2_UN:
263 if (in->sub < U_NEG || in->sub >= U_LIMIT) F("C2-DECODE-SUBOP", "unary op %u", in->sub);
264 if (!same_type(td, ta)) F("C2-TYPE-UN", "unary result type differs from operand");
265 if (in->sub == U_LNOT ? td->s != S_BOOL : !is_int(td->s)) F("C2-TYPE-UN", "unary operand type"); /* GUARD:un-type */
266 break;
267 case C2_CMP:
268 if (in->sub < CC_EQ || in->sub >= CC_LIMIT) F("C2-DECODE-SUBOP", "comparison %u", in->sub);
269 if (td->s != S_BOOL || !is_scalar_t(ta) || !same_type(ta, tb)) F("C2-TYPE-CMP", "comparison operand types"); /* GUARD:cmp-type */
270 break;
271 case C2_CAST:
272 if (!is_int(td->s) || !is_int(ta->s)) F("C2-TYPE-CAST", "cast between non-integers (bool casts are refused)"); /* GUARD:cast-type */
273 break;
274 case C2_ALLOC: case C2_AALLOC:
275 if (!is_ref(td) || td->kind != K_OWN) F("C2-TYPE-ALLOC", "allocation into a non-owner"); /* GUARD:alloc-own */
276 if (is_array_ref(td) ? ta->s != td->elem : ta->s != S_U64) F("C2-TYPE-ALLOC", "initial value type"); /* GUARD:alloc-init */
277 if (in->op == C2_AALLOC && !is_u64(tb)) F("C2-TYPE-ALLOC", "arena handle is not u64");
278 break;
279 case C2_RELEASE:
280 if (!is_ref(ta) || ta->kind != K_OWN) F("C2-TYPE-RELEASE", "release of a non-owner"); /* GUARD:release-own */
281 break;
282 case C2_LOAD: case C2_STORE:
283 if (!is_array_ref(ta)) F("C2-TYPE-INDEX", "indexing a non-array"); /* GUARD:index-array */
284 if (!is_int(tb->s)) F("C2-TYPE-INDEX", "index is not an integer");
285 if (in->op == C2_LOAD ? td->s != ta->elem : tc->s != ta->elem) F("C2-TYPE-INDEX", "element type"); /* GUARD:index-elem */
286 if (in->op == C2_STORE && ta->kind == K_SHARED) F("C2-READ-ONLY", "store through a shared borrow"); /* GUARD:store-shared */
287 break;
288 case C2_FLOAD: case C2_FSTORE: {
289 if (!is_struct_ref(ta)) F("C2-TYPE-FIELD", "field access on a non-struct");
290 const C2Struct *s = &x->u->st[ta->sid - 1];
291 if (in->imm >= s->nfields) F("C2-TYPE-FIELD", "field %llu of %s", (unsigned long long)in->imm, s->name); /* GUARD:field-index */
292 const C2Field *fd = &s->f[in->imm];
293 if (fd->alen ? (!tb || !is_int(tb->s)) : in->b != -1) F("C2-TYPE-FIELD", "element index of field %s.%s", s->name, fd->name); /* GUARD:field-elem-index */
294 if (in->op == C2_FLOAD ? td->s != fd->s : tc->s != fd->s) F("C2-TYPE-FIELD", "type of field %s.%s", s->name, fd->name); /* GUARD:field-type */
295 if (in->op == C2_FSTORE && ta->kind == K_SHARED) F("C2-READ-ONLY", "field store through a shared borrow"); /* GUARD:fstore-shared */
296 break;
297 }
298 case C2_AOPEN:
299 if (!is_u64(td)) F("C2-TYPE-HANDLE", "arena handle is not u64");
300 if (in->imm < 1 || in->imm > C2_MAX_ARRAY) F("C2-ARENA-CAPACITY", "arena of %llu cells", (unsigned long long)in->imm); /* GUARD:arena-cap */
301 break;
302 case C2_ADESTROY: case C2_PCLOSE:
303 if (!is_u64(ta)) F("C2-TYPE-HANDLE", "handle is not u64");
304 break;
305 case C2_POPEN:
306 if (!is_u64(td)) F("C2-TYPE-HANDLE", "pool id is not u64");
307 if (!is_value(in->sub)) F("C2-TYPE-POOL", "pool element type %u", in->sub);
308 if (in->nargs < 1 || in->nargs > C2_POOL_SLOTS) F("C2-POOL-CAPACITY", "pool of %u slots", in->nargs); /* GUARD:pool-cap */
309 break;
310 case C2_HALLOC: if (!is_u64(td) || !is_u64(tb) || !is_value(ta->s)) F("C2-TYPE-POOL", "pool alloc operand types"); break;
311 case C2_HGEN: if (!is_u64(td) || !is_u64(ta) || !is_u64(tb)) F("C2-TYPE-POOL", "pool generation operand types"); break;
312 case C2_HFREE: if (!is_u64(ta) || !is_u64(tb) || !is_u64(tc)) F("C2-TYPE-POOL", "pool free operand types"); break;
313 case C2_HLOAD: if (!is_value(td->s) || !is_u64(ta) || !is_u64(tb) || !is_u64(tc)) F("C2-TYPE-POOL", "pool load operand types"); break;
314 case C2_HSTORE:
315 if (in->args[0] < 0 || in->args[0] >= nv) F("C2-OPERAND-RANGE", "pool store value");
316 if (!is_u64(ta) || !is_u64(tb) || !is_u64(tc)) F("C2-TYPE-POOL", "pool store operand types");
317 break;
318 case C2_SLOAD: case C2_SSTORE:
319 if (!is_slice(ta)) F("C2-TYPE-SLICE", "slice access through a non-slice register"); /* GUARD:slice-ptr */
320 if (in->op == C2_SSTORE && ta->s != S_CELLS) F("C2-SLICE-WRITE", "store into a read-only bytes slice"); /* GUARD:slice-bytes-ro */
321 if (!is_int(tb->s)) F("C2-TYPE-SLICE", "slice index is not an integer");
322 if (in->op == C2_SLOAD ? !is_u64(td) : !is_u64(tc)) F("C2-TYPE-SLICE", "slice element is u64");
323 break;
324 case C2_TRAP:
325 if (in->imm < 1 || in->imm > C2_TRAP_MAX) F("C2-TRAP-CODE", "trap code %llu", (unsigned long long)in->imm); /* GUARD:trap-code */
326 break;
327 case C2_BR:
328 if (in->t >= f->nblocks) F("C2-CFG-TARGET", "branch to block %u", in->t); /* GUARD:br-target */
329 break;
330 case C2_CBR:
331 if (in->t >= f->nblocks || in->f >= f->nblocks) F("C2-CFG-TARGET", "branch to block %u/%u", in->t, in->f); /* GUARD:cbr-target */
332 if (ta->s != S_BOOL) F("C2-TYPE-COND", "branch condition is not bool"); /* GUARD:cbr-bool */
333 break;
334 case C2_RET:
335 if (f->ret.s == S_VOID ? in->a != -1 : (in->a < 0 || !same_type(ta, &f->ret))) F("C2-TYPE-RET", "return value type"); /* GUARD:ret-type */
336 break;
337 case C2_CALL: {
338 if (in->callee >= x->fi) F("C2-CALL-ORDER", "call to function %u from function %d (no recursion, no forward calls)", in->callee, x->fi); /* GUARD:call-order */
339 const C2Func *g = &x->u->fn[in->callee];
340 if (in->nargs != g->nparams) F("C2-CALL-ARITY", "%u arguments for %u parameters", in->nargs, g->nparams); /* GUARD:call-arity */
341 if (g->ret.s == S_VOID ? in->dst != -1 : (in->dst < 0 || in->dst >= nv || !same_type(T(x, in->dst), &g->ret)))
342 F("C2-TYPE-CALL", "call result type"); /* GUARD:call-ret */
343 for (int k = 0; k < in->nargs; k++) {
344 const C2Type *pa = T(x, in->args[k]), *pp = &g->vt[k];
345 if (is_ref(pp)) {
346 if (!same_shape(pa, pp) || !bindable(pp->kind, pa->kind)) F("C2-TYPE-CALL", "argument %d does not bind", k); /* GUARD:call-ref */
347 } else if (is_slice(pp)) {
348 if (pa->s != pp->s) F("C2-TYPE-CALL", "slice argument %d type", k);
349 if (k + 1 >= in->nargs || in->args[k + 1] != in->args[k] + 1)
350 F("C2-TYPE-CALL", "slice argument %d is not passed with its own length", k);
351 } else {
352 if (!same_type(pa, pp)) F("C2-TYPE-CALL", "argument %d type", k); /* GUARD:call-scalar */
353 }
354 /* aliasing: the same register twice where either parameter may write or take it */
355 for (int j = 0; j < k; j++) {
356 int alias = in->args[j] == in->args[k] && (is_ref(pp) || pp->s == S_CELLS) &&
357 (pp->kind != K_SHARED || g->vt[j].kind != K_SHARED);
358 if (alias) F("C2-CALL-ALIAS", "register v%d passed twice and written", in->args[k]); /* GUARD:call-alias */
359 }
360 }
361 break;
362 }
363 default: F("C2-DECODE-OPCODE", "opcode %u", in->op);
364 }
365 return 0;
366}
367
368/* ------------------------------------------------------------------ CFG */
369
370static int build_cfg(Fx *x)
371{
372 const C2Func *f = x->f;
373 uint32_t pos = 0;
374 for (int b = 0; b < f->nblocks; b++) {
375 const C2Block *bk = &f->blk[b];
376 if (bk->count < 1 || bk->first != pos || bk->first + bk->count > f->ninsns) /* GUARD:cfg-layout */
377 return fail(x->v, "C2-CFG-LAYOUT", x->fi, -1, "block %d is not the next contiguous range", b);
378 for (uint32_t i = bk->first; i < bk->first + bk->count; i++) {
379 x->blk_of[i] = b;
380 int last = i + 1 == bk->first + bk->count;
381 if (term(f->in[i].op) != last) /* GUARD:cfg-terminator */
382 return fail(x->v, "C2-CFG-TERMINATOR", x->fi, (int)i, last ? "block %d does not end in a terminator" : "terminator inside block %d", b);
383 }
384 pos += bk->count;
385 }
386 if (pos != f->ninsns) return fail(x->v, "C2-CFG-LAYOUT", x->fi, -1, "blocks cover %u of %u instructions", pos, f->ninsns);
387 return 0;
388}
389
390static void link_cfg(Fx *x)
391{
392 const C2Func *f = x->f;
393 for (int b = 0; b < f->nblocks; b++) {
394 const C2Insn *t = &f->in[f->blk[b].first + f->blk[b].count - 1];
395 x->nsucc[b] = 0;
396 if (t->op == C2_BR) x->succ[b][x->nsucc[b]++] = t->t;
397 if (t->op == C2_CBR) {
398 x->succ[b][x->nsucc[b]++] = t->t;
399 if (t->f != t->t) x->succ[b][x->nsucc[b]++] = t->f;
400 }
401 }
402 int stack[C2_MAX_BLOCKS], sp = 0;
403 memset(x->reach, 0, sizeof x->reach);
404 x->reach[0] = 1;
405 stack[sp++] = 0;
406 while (sp) {
407 int b = stack[--sp];
408 for (int k = 0; k < x->nsucc[b]; k++)
409 if (!x->reach[x->succ[b][k]]) { x->reach[x->succ[b][k]] = 1; stack[sp++] = x->succ[b][k]; }
410 }
411 /* dominators over reachable blocks */
412 for (int b = 0; b < f->nblocks; b++) ball(&x->dom[b]);
413 memset(&x->dom[0], 0, sizeof x->dom[0]);
414 bset(&x->dom[0], 0);
415 int changed = 1;
416 while (changed) {
417 changed = 0;
418 for (int b = 1; b < f->nblocks; b++) {
419 if (!x->reach[b]) continue;
420 Bits n;
421 ball(&n);
422 for (int p = 0; p < f->nblocks; p++) {
423 if (!x->reach[p]) continue;
424 for (int k = 0; k < x->nsucc[p]; k++)
425 if (x->succ[p][k] == b) band(&n, &x->dom[p]);
426 }
427 bset(&n, (unsigned)b);
428 if (!beq(&n, &x->dom[b])) { x->dom[b] = n; changed = 1; }
429 }
430 }
431}
432
433static int dominates(const Fx *x, int a, int b) { return btest(&x->dom[b], (unsigned)a); }
434
435/* ------------------------------------------------------------------ disciplines */
436
437static int count_defs(Fx *x)
438{
439 const C2Func *f = x->f;
440 for (int r = 0; r < f->nvregs; r++) { x->ndefs[r] = r < f->nparams ? 1 : 0; x->def_insn[r] = -1; }
441 for (uint32_t i = 0; i < f->ninsns; i++) {
442 int d = defines(&f->in[i]);
443 if (d < 0) continue;
444 x->ndefs[d]++;
445 x->def_insn[d] = x->ndefs[d] == 1 ? (int)i : -1;
446 }
447 return 0;
448}
449
450/* Arena handles and pool ids: defined exactly once, by AOPEN / POPEN, never a parameter, and used
451 * only in their handle positions (OSC-2 section 3.3, OSC-3 item 2). */
452static int check_handles(Fx *x)
453{
454 const C2Func *f = x->f;
455 for (uint32_t i = 0; i < f->ninsns; i++) {
456 const C2Insn *in = &f->in[i];
457 if (in->op != C2_AOPEN && in->op != C2_POPEN) continue;
458 int h = in->dst;
459 if (h < f->nparams || x->ndefs[h] != 1) /* also implied by handle-origin and the leak rule (untagged) */
460 return fail(x->v, "C2-HANDLE-DISCIPLINE", x->fi, (int)i, "handle v%d defined more than once or a parameter", h);
461 for (uint32_t j = 0; j < f->ninsns; j++) {
462 const C2Insn *o = &f->in[j];
463 int16_t us[8];
464 int nu = uses(o, us);
465 for (int k = 0; k < nu; k++) {
466 if (us[k] != h) continue;
467 int ok;
468 if (in->op == C2_AOPEN)
469 ok = (o->op == C2_AALLOC && o->b == h && o->a != h) || (o->op == C2_ADESTROY && o->a == h);
470 else
471 ok = (o->op == C2_PCLOSE && o->a == h) || (o->op == C2_HALLOC && o->b == h && o->a != h) ||
472 ((o->op == C2_HGEN || o->op == C2_HFREE || o->op == C2_HLOAD || o->op == C2_HSTORE) && o->a == h &&
473 o->b != h && o->c != h && o->args[0] != h);
474 if (!ok) /* GUARD:handle-use */
475 return fail(x->v, "C2-HANDLE-DISCIPLINE", x->fi, (int)j, "handle v%d used outside its handle position", h);
476 }
477 }
478 }
479 /* every handle operand is such a handle, and pool element types agree with the pool */
480 for (uint32_t j = 0; j < f->ninsns; j++) {
481 const C2Insn *o = &f->in[j];
482 int h = -1;
483 if (o->op == C2_AALLOC) h = o->b;
484 if (o->op == C2_ADESTROY || o->op == C2_PCLOSE || o->op == C2_HGEN || o->op == C2_HFREE || o->op == C2_HLOAD ||
485 o->op == C2_HSTORE)
486 h = o->a;
487 if (o->op == C2_HALLOC) h = o->b;
488 if (h < 0) continue;
489 int di = x->def_insn[h];
490 uint8_t want = (o->op == C2_AALLOC || o->op == C2_ADESTROY) ? C2_AOPEN : C2_POPEN;
491 if (di < 0 || f->in[di].op != want) /* GUARD:handle-origin */
492 return fail(x->v, "C2-HANDLE-DISCIPLINE", x->fi, (int)j, "v%d is not a handle opened by %s", h, want == C2_AOPEN ? "AOPEN" : "POPEN");
493 uint8_t es = f->in[di].sub;
494 if (o->op == C2_HALLOC && f->vt[o->a].s != es) return fail(x->v, "C2-TYPE-POOL", x->fi, (int)j, "pool value type");
495 if (o->op == C2_HLOAD && f->vt[o->dst].s != es) return fail(x->v, "C2-TYPE-POOL", x->fi, (int)j, "pool value type"); /* GUARD:pool-elem */
496 if (o->op == C2_HSTORE && f->vt[o->args[0]].s != es) return fail(x->v, "C2-TYPE-POOL", x->fi, (int)j, "pool value type");
497 }
498 return 0;
499}
500
501/* ------------------------------------------------------------------ definite assignment */
502
503static int check_defined(Fx *x)
504{
505 const C2Func *f = x->f;
506 static Bits in[C2_MAX_BLOCKS], out[C2_MAX_BLOCKS]; /* not reentrant; checker2 is single-threaded */
507 Bits params;
508 memset(&params, 0, sizeof params);
509 for (int r = 0; r < f->nparams; r++) bset(&params, (unsigned)r);
510 for (int b = 0; b < f->nblocks; b++) ball(&out[b]);
511 int changed = 1;
512 while (changed) {
513 changed = 0;
514 for (int b = 0; b < f->nblocks; b++) {
515 if (!x->reach[b]) continue;
516 Bits cur;
517 if (b == 0) cur = params;
518 else {
519 ball(&cur);
520 for (int p = 0; p < f->nblocks; p++) {
521 if (!x->reach[p]) continue;
522 for (int k = 0; k < x->nsucc[p]; k++)
523 if (x->succ[p][k] == b) band(&cur, &out[p]);
524 }
525 }
526 if (b == 0) {
527 /* the entry block may also be a loop header */
528 for (int p = 0; p < f->nblocks; p++) {
529 if (!x->reach[p]) continue;
530 for (int k = 0; k < x->nsucc[p]; k++)
531 if (x->succ[p][k] == 0) band(&cur, &out[p]);
532 }
533 }
534 in[b] = cur;
535 for (uint32_t i = f->blk[b].first; i < f->blk[b].first + f->blk[b].count; i++) {
536 if (f->in[i].op == C2_TRAP) { ball(&cur); break; } /* a trap ends the path */
537 int d = defines(&f->in[i]);
538 if (d >= 0) bset(&cur, (unsigned)d);
539 }
540 if (!beq(&cur, &out[b])) { out[b] = cur; changed = 1; }
541 }
542 }
543 for (int b = 0; b < f->nblocks; b++) {
544 if (!x->reach[b]) continue;
545 Bits cur = in[b];
546 for (uint32_t i = f->blk[b].first; i < f->blk[b].first + f->blk[b].count; i++) {
547 if (f->in[i].op == C2_TRAP) break;
548 int16_t us[8];
549 int nu = uses(&f->in[i], us);
550 for (int k = 0; k < nu; k++) {
551 if (!btest(&cur, (unsigned)us[k])) /* GUARD:definite-assignment */
552 return fail(x->v, "C2-UNDEFINED-USE", x->fi, (int)i, "v%d may be read before it is written", us[k]);
553 }
554 int d = defines(&f->in[i]);
555 if (d >= 0) bset(&cur, (unsigned)d);
556 }
557 }
558 return 0;
559}
560
561/* ------------------------------------------------------------------ loop bounds */
562
563/* Every loop must be bounded (OSC-1 section 3 "Loops"; OSC-1 section 4 "loops to blocks with an
564 * explicit counter vreg, CMP and CBR on the bound"). checker2 proves it structurally: the CFG is
565 * reducible, and each natural loop L contains a guard block G that dominates every latch of L and
566 * ends in CBR on cond, where
567 * cond is defined once, in G, by CMP c, K with
568 * K defined exactly once in the function, by CONST, |K| <= 1,000,000;
569 * c an integer register whose only definitions inside L are c = BIN ADD c, s with s defined
570 * exactly once in the function by CONST 1, each in a block that dominates every latch of L;
571 * CMP GE with the TRUE successor outside L, or CMP LT with the FALSE successor outside L.
572 * Then every iteration raises c by one and the loop is left once c >= K: at most |K - c0| + 2
573 * iterations per entry (an unsigned counter can wrap at most once, on the first iteration; a
574 * signed one traps on overflow). */
575static int single_const(const Fx *x, int r, uint64_t *val)
576{
577 if (r < 0 || x->ndefs[r] != 1 || x->def_insn[r] < 0) return 0;
578 const C2Insn *d = &x->f->in[x->def_insn[r]];
579 if (d->op != C2_CONST) return 0;
580 *val = d->imm;
581 return 1;
582}
583
584static int loop_guarded(const Fx *x, const int *inloop, const int *latch, int nlatch)
585{
586 const C2Func *f = x->f;
587 for (int g = 0; g < f->nblocks; g++) {
588 if (!inloop[g]) continue;
589 int domall = 1;
590 for (int k = 0; k < nlatch; k++) domall &= dominates(x, g, latch[k]);
591 if (!domall) continue;
592 const C2Insn *t = &f->in[f->blk[g].first + f->blk[g].count - 1];
593 if (t->op != C2_CBR) continue;
594 int ci = x->def_insn[t->a];
595 if (ci < 0 || x->blk_of[ci] != g || f->in[ci].op != C2_CMP) continue;
596 const C2Insn *cmp = &f->in[ci];
597 int exits;
598 if (cmp->sub == CC_GE) exits = !inloop[t->t];
599 else if (cmp->sub == CC_LT) exits = !inloop[t->f];
600 else continue;
601 if (!exits) continue;
602 uint64_t kv, one;
603 if (!single_const(x, cmp->b, &kv)) continue;
604 uint8_t ks = f->vt[cmp->b].s;
605 int64_t ksig = is_signed(ks) ? (int64_t)kv : (kv > 2000000 ? 2000000 : (int64_t)kv);
606 if (ksig > 1000000 || ksig < -1000000) continue;
607 int c = cmp->a;
608 if (!is_int(f->vt[c].s)) continue;
609 int incs = 0, bad = 0;
610 for (uint32_t i = 0; i < f->ninsns && !bad; i++) {
611 if (!inloop[x->blk_of[i]] || defines(&f->in[i]) != c) continue;
612 const C2Insn *d = &f->in[i];
613 int ok = d->op == C2_BIN && d->sub == B_ADD && d->a == c && single_const(x, d->b, &one) && one == 1;
614 for (int k = 0; ok && k < nlatch; k++) ok = dominates(x, x->blk_of[i], latch[k]);
615 if (!ok) bad = 1;
616 else incs++;
617 }
618 if (!bad && incs >= 1) return 1;
619 }
620 return 0;
621}
622
623static int check_loops(Fx *x)
624{
625 const C2Func *f = x->f;
626 /* reducibility: every edge into a block that does not dominate its source must go forward in a
627 * DFS without creating a cycle; equivalently, removing back edges (to a dominator) leaves a DAG. */
628 static int color[C2_MAX_BLOCKS], stk[C2_MAX_BLOCKS], idx[C2_MAX_BLOCKS];
629 memset(color, 0, sizeof color);
630 int sp = 0;
631 stk[sp] = 0; idx[sp] = 0; sp++;
632 color[0] = 1;
633 while (sp) {
634 int b = stk[sp - 1];
635 if (idx[sp - 1] < x->nsucc[b]) {
636 int s = x->succ[b][idx[sp - 1]++];
637 if (color[s] == 1 && !dominates(x, s, b)) /* GUARD:reducible */
638 return fail(x->v, "C2-CFG-IRREDUCIBLE", x->fi, -1, "cycle entered other than through its header (block %d)", s);
639 if (color[s] == 0) { color[s] = 1; stk[sp] = s; idx[sp] = 0; sp++; }
640 } else {
641 color[b] = 2;
642 sp--;
643 }
644 }
645 /* natural loops, one per header (all its back edges together) */
646 for (int h = 0; h < f->nblocks; h++) {
647 if (!x->reach[h]) continue;
648 int latch[C2_MAX_BLOCKS], nlatch = 0;
649 for (int p = 0; p < f->nblocks; p++) {
650 if (!x->reach[p]) continue;
651 for (int k = 0; k < x->nsucc[p]; k++)
652 if (x->succ[p][k] == h && dominates(x, h, p)) latch[nlatch++] = p;
653 }
654 if (!nlatch) continue;
655 static int inloop[C2_MAX_BLOCKS];
656 memset(inloop, 0, sizeof inloop);
657 inloop[h] = 1;
658 int st[C2_MAX_BLOCKS], n = 0;
659 for (int k = 0; k < nlatch; k++)
660 if (!inloop[latch[k]]) { inloop[latch[k]] = 1; st[n++] = latch[k]; }
661 while (n) {
662 int b = st[--n];
663 for (int p = 0; p < f->nblocks; p++) {
664 if (!x->reach[p] || inloop[p]) continue;
665 for (int k = 0; k < x->nsucc[p]; k++)
666 if (x->succ[p][k] == b) { inloop[p] = 1; st[n++] = p; break; }
667 }
668 }
669 if (!loop_guarded(x, inloop, latch, nlatch)) /* GUARD:loop-bound */
670 return fail(x->v, "C2-LOOP-UNBOUNDED", x->fi, (int)f->blk[h].first, "loop at block %d has no counter guard", h);
671 }
672 return 0;
673}
674
675/* ------------------------------------------------------------------ ownership flow */
676
677/* May-states of a reference-owner register: bit 0 not yet holding, bit 1 live, bit 2 dead
678 * (released, moved or its arena destroyed). Handles: bit 0 not opened, bit 1 open, bit 2 closed.
679 * A use, release, move or close is an error only when it excludes "live" on every path; holding an
680 * object at a return, or when the register is written again, is an error when it is possible on
681 * some path (omega#465): every non-trapping path must release, move or close what it holds.
682 *
683 * Drop flags (OSC-3 item 3): a release guarded by a bool register (CBR c -> block starting with
684 * RELEASE r) is correlated with c. The state of such an owner has two components, bits 0-2 for the
685 * paths on which c is 0 and bits 3-5 for those on which c is 1; CONST k into c gathers every path
686 * into component k, any other write of c spreads them over both, and each CBR edge on c keeps only
687 * its own component (an edge that leaves an owner no state is taken by no path and propagates
688 * nothing). An owner without a flag keeps the same state in both components. */
689enum { ST_U = 1, ST_L = 2, ST_D = 4 };
690#define ANY(s) ((uint8_t)(((s) | ((s) >> 3)) & 7))
691
692typedef struct {
693 int arena_obj[C2_MAX_VREGS]; /* defined by AALLOC: its handle register, else -1 */
694 int origin[C2_MAX_VREGS]; /* borrow -> root owner register; -1 none/external; -2 mixed */
695 int flag_of[C2_MAX_VREGS]; /* owner -> bool register guarding its release, else -1 */
696 uint8_t isflag[C2_MAX_VREGS];
697 uint8_t in[C2_MAX_BLOCKS][C2_MAX_VREGS];
698} Own;
699
700static int tracked(const Fx *x, int r)
701{
702 const C2Type *t = &x->f->vt[r];
703 return (t->s == S_REF && t->kind == K_OWN);
704}
705
706/* state v in every component that some path occupies */
707static uint8_t st_set(uint8_t s, uint8_t v) { return (uint8_t)(((s & 7) ? v : 0) | ((s & 070) ? v << 3 : 0)); }
708
709#define OF(rule, ...) do { if (!x->quiet) return fail(x->v, rule, x->fi, (int)i, __VA_ARGS__); } while (0)
710
711static int own_use(const Fx *x, const Own *o, const uint8_t *st, uint32_t i, int r)
712{
713 if (tracked(x, r) && !(ANY(st[r]) & ST_L)) /* GUARD:own-use-dead */
714 OF("C2-OWN-USE-DEAD", "owner v%d used after it was released or moved (every path)", r);
715 int g = o->origin[r];
716 if (g >= 0 && !(ANY(st[g]) & ST_L)) /* GUARD:borrow-outlives */
717 OF("C2-BORROW-OUTLIVES-OWNER", "borrow v%d used after its owner v%d is gone (every path)", r, g);
718 return 0;
719}
720
721static int own_kill(const Fx *x, uint8_t *st, uint32_t i, int r, const char *what)
722{
723 (void)what;
724 if (!(ANY(st[r]) & ST_L)) OF("C2-OWN-USE-DEAD", "owner v%d moved after it was released or moved (every path)", r); /* GUARD:own-move-dead */
725 st[r] = st_set(st[r], ST_D);
726 return 0;
727}
728
729/* An arena object's memory goes back with its arena (ADESTROY), so rebinding one that may still be
730 * live loses nothing; it keeps the every-path rule, as at RET where arena objects are not judged. */
731static int own_birth(const Fx *x, const Own *o, uint8_t *st, uint32_t i, int r)
732{
733 uint8_t s = ANY(st[r]);
734 int heap = o->arena_obj[r] < 0; /* arena objects keep the every-path rule: ADESTROY reclaims them */
735 if ((s & ST_L) && heap) s = ST_L; /* GUARD:overwrite-some-path */
736 if (s == ST_L) /* GUARD:own-overwrite */
737 OF("C2-OWN-LEAK", "owner v%d overwritten while it may still hold an object (on some path)", r);
738 st[r] = st_set(st[r], ST_L);
739 return 0;
740}
741
742static int own_step(const Fx *x, const Own *o, uint8_t *st, uint32_t i)
743{
744 const C2Func *f = x->f;
745 const C2Insn *in = &f->in[i];
746 switch (in->op) {
747 case C2_ALLOC:
748 return own_birth(x, o, st, i, in->dst);
749 case C2_AALLOC:
750 if (!(ANY(st[in->b]) & ST_L)) OF("C2-ARENA-DEAD", "allocation from arena v%d after it was destroyed (every path)", in->b); /* GUARD:arena-alloc-dead */
751 return own_birth(x, o, st, i, in->dst);
752 case C2_RELEASE:
753 if (o->arena_obj[in->a] >= 0) OF("C2-OWN-RELEASE-ARENA", "release of arena object v%d", in->a); /* GUARD:release-arena */
754 if (!(ANY(st[in->a]) & ST_L)) OF("C2-OWN-DOUBLE-RELEASE", "v%d released when it holds nothing (every path)", in->a); /* GUARD:double-release */
755 st[in->a] = st_set(st[in->a], ST_D);
756 return 0;
757 case C2_MOV:
758 if (tracked(x, in->a)) {
759 if (f->vt[in->dst].kind == K_OWN) {
760 if (o->arena_obj[in->a] >= 0 || o->arena_obj[in->dst] >= 0)
761 OF("C2-OWN-ARENA-MOVE", "move involving arena object"); /* GUARD:arena-move */
762 if (own_kill(x, st, i, in->a, "move")) return -1;
763 return own_birth(x, o, st, i, in->dst);
764 }
765 return own_use(x, o, st, i, in->a);
766 }
767 return is_ref(&f->vt[in->a]) ? own_use(x, o, st, i, in->a) : 0;
768 case C2_LOAD: case C2_STORE: case C2_FLOAD: case C2_FSTORE:
769 return own_use(x, o, st, i, in->a);
770 case C2_CALL: {
771 const C2Func *g = &x->u->fn[in->callee];
772 for (int k = 0; k < in->nargs; k++) {
773 int r = in->args[k];
774 if (!is_ref(&f->vt[r])) continue;
775 if (own_use(x, o, st, i, r)) return -1;
776 if (g->vt[k].kind == K_OWN) {
777 if (o->arena_obj[r] >= 0) OF("C2-OWN-ARENA-MOVE", "arena object v%d passed to an own parameter", r);
778 if (own_kill(x, st, i, r, "move into call")) return -1;
779 }
780 }
781 return 0;
782 }
783 case C2_AOPEN: case C2_POPEN:
784 if (ANY(st[in->dst]) & ST_L) OF("C2-HANDLE-REOPEN", "handle v%d reopened while open", in->dst);
785 st[in->dst] = st_set(st[in->dst], ST_L);
786 return 0;
787 case C2_ADESTROY: case C2_PCLOSE:
788 if (!(ANY(st[in->a]) & ST_L)) OF("C2-HANDLE-DOUBLE-CLOSE", "handle v%d closed when not open (every path)", in->a); /* GUARD:double-close */
789 st[in->a] = st_set(st[in->a], ST_D);
790 if (in->op == C2_ADESTROY)
791 for (int r = 0; r < f->nvregs; r++) {
792 if (o->arena_obj[r] != in->a) continue;
793 uint8_t lo = st[r] & 7, hi = (st[r] >> 3) & 7;
794 if (lo && lo != ST_U) lo = ST_D;
795 if (hi && hi != ST_U) hi = ST_D;
796 st[r] = (uint8_t)(lo | hi << 3);
797 }
798 return 0;
799 case C2_HALLOC: case C2_HGEN: case C2_HFREE: case C2_HLOAD: case C2_HSTORE: {
800 int h = in->op == C2_HALLOC ? in->b : in->a;
801 if (!(ANY(st[h]) & ST_L)) OF("C2-HANDLE-DEAD", "pool v%d used when not open (every path)", h); /* GUARD:pool-dead */
802 return 0;
803 }
804 case C2_RET:
805 for (int r = 0; r < f->nvregs; r++) {
806 int handle = x->def_insn[r] >= 0 && (f->in[x->def_insn[r]].op == C2_AOPEN || f->in[x->def_insn[r]].op == C2_POPEN);
807 uint8_t s = ANY(st[r]);
808 if (s & ST_L) s = ST_L; /* GUARD:leak-some-path */
809 if (s == ST_L && (handle || (tracked(x, r) && o->arena_obj[r] < 0))) /* GUARD:leak */
810 OF(handle ? "C2-HANDLE-LEAK" : "C2-OWN-LEAK", "v%d may still %s at return (on some path)", r, handle ? "be open" : "own an object");
811 }
812 return 0;
813 default:
814 return 0;
815 }
816}
817
818/* a write of a drop flag re-sorts the paths of the owners it guards */
819static void own_flag_def(const Fx *x, const Own *o, uint8_t *st, uint32_t i)
820{
821 const C2Insn *in = &x->f->in[i];
822 int c = defines(in);
823 if (c < 0 || !o->isflag[c]) return;
824 for (int r = 0; r < x->f->nvregs; r++) {
825 if (o->flag_of[r] != c) continue;
826 uint8_t s = ANY(st[r]);
827 st[r] = in->op == C2_CONST ? (uint8_t)(in->imm ? s << 3 : s) : (uint8_t)(s | s << 3);
828 }
829}
830
831static int check_ownership(Fx *x)
832{
833 const C2Func *f = x->f;
834 Own *o = malloc(sizeof *o);
835 if (!o) return fail(x->v, "C2-RESOURCE", x->fi, -1, "out of memory");
836 for (int r = 0; r < f->nvregs; r++) { o->arena_obj[r] = -1; o->origin[r] = -1; o->flag_of[r] = -1; o->isflag[r] = 0; }
837 for (uint32_t i = 0; i < f->ninsns; i++) {
838 const C2Insn *in = &f->in[i];
839 if (in->op == C2_AALLOC) o->arena_obj[in->dst] = in->b;
840 }
841 for (uint32_t i = 0; i < f->ninsns; i++) {
842 const C2Insn *in = &f->in[i];
843 if ((in->op == C2_ALLOC && o->arena_obj[in->dst] >= 0) ||
844 (in->op == C2_AALLOC && o->arena_obj[in->dst] != in->b)) {
845 free(o);
846 return fail(x->v, "C2-OWN-ARENA-MOVE", x->fi, (int)i, "register v%d holds both arena and pool objects", in->dst);
847 }
848 }
849 /* drop flags: the condition of a CBR one of whose two targets starts by releasing an owner */
850 for (uint32_t i = 0; i < f->ninsns; i++) {
851 const C2Insn *in = &f->in[i];
852 if (in->op != C2_CBR || in->t == in->f) continue;
853 for (int k = 0; k < 2; k++) {
854 const C2Insn *h = &f->in[f->blk[k ? in->f : in->t].first];
855 if (h->op == C2_RELEASE && tracked(x, h->a) && o->flag_of[h->a] < 0) {
856 o->flag_of[h->a] = in->a;
857 o->isflag[in->a] = 1;
858 }
859 }
860 }
861 /* borrow origins: flow-insensitive, single root owner or unknown */
862 int changed = 1;
863 while (changed) {
864 changed = 0;
865 for (uint32_t i = 0; i < f->ninsns; i++) {
866 const C2Insn *in = &f->in[i];
867 if (in->op != C2_MOV || !is_ref(&f->vt[in->dst]) || f->vt[in->dst].kind == K_OWN) continue;
868 int root = f->vt[in->a].kind == K_OWN ? in->a : o->origin[in->a];
869 int cur = o->origin[in->dst];
870 int nw = cur == -1 && root >= 0 ? root : (cur == root ? cur : -2);
871 if (in->dst < f->nparams) nw = -2;
872 if (nw != cur && cur != -2) { o->origin[in->dst] = nw; changed = 1; }
873 }
874 }
875 for (int r = 0; r < f->nvregs; r++)
876 if (o->origin[r] == -2) o->origin[r] = -1;
877
878 /* Fixpoint of the may-states. In-states only grow (bitwise OR over a finite lattice), so this
879 * terminates. Transfer runs quietly (effects applied, no verdict); a TRAP ends its path, so a
880 * trapping block propagates nothing. Blocks no non-trapping path reaches are not judged. */
881 static int live[C2_MAX_BLOCKS];
882 memset(o->in, 0, sizeof o->in);
883 memset(live, 0, sizeof live);
884 for (int r = 0; r < f->nvregs; r++) o->in[0][r] = (r < f->nparams && tracked(x, r)) ? ST_L | ST_L << 3 : ST_U | ST_U << 3;
885 live[0] = 1;
886 x->quiet = 1;
887 changed = 1;
888 while (changed) {
889 changed = 0;
890 for (int b = 0; b < f->nblocks; b++) {
891 if (!live[b]) continue;
892 uint8_t st[C2_MAX_VREGS];
893 memcpy(st, o->in[b], f->nvregs);
894 int trapped = 0;
895 for (uint32_t i = f->blk[b].first; i < f->blk[b].first + f->blk[b].count && !trapped; i++) {
896 if (f->in[i].op == C2_TRAP) trapped = 1;
897 else { (void)own_step(x, o, st, i); own_flag_def(x, o, st, i); }
898 }
899 if (trapped) continue;
900 const C2Insn *t = &f->in[f->blk[b].first + f->blk[b].count - 1];
901 int c = t->op == C2_CBR && t->t != t->f && o->isflag[t->a] ? t->a : -1;
902 for (int k = 0; k < x->nsucc[b]; k++) {
903 int s = x->succ[b][k];
904 uint8_t keep = 077;
905 if (c >= 0) keep = s == t->t ? 070 : 007; /* GUARD:drop-flag-edge */
906 int taken = 1;
907 for (int r = 0; r < f->nvregs && taken; r++)
908 if (c >= 0 && o->flag_of[r] == c && !(st[r] & keep)) taken = 0;
909 if (!taken) continue;
910 if (!live[s]) { live[s] = 1; changed = 1; }
911 for (int r = 0; r < f->nvregs; r++) {
912 uint8_t m = o->in[s][r] | (c >= 0 && o->flag_of[r] == c ? st[r] & keep : st[r]);
913 if (m != o->in[s][r]) { o->in[s][r] = m; changed = 1; }
914 }
915 }
916 }
917 }
918 x->quiet = 0;
919 /* report the first error */
920 for (int b = 0; b < f->nblocks; b++) {
921 if (!live[b]) continue;
922 uint8_t st[C2_MAX_VREGS];
923 memcpy(st, o->in[b], f->nvregs);
924 for (uint32_t i = f->blk[b].first; i < f->blk[b].first + f->blk[b].count; i++) {
925 if (f->in[i].op == C2_TRAP) break;
926 if (own_step(x, o, st, i)) { free(o); return -1; }
927 own_flag_def(x, o, st, i);
928 }
929 }
930 free(o);
931 return 0;
932}
933
934/* ------------------------------------------------------------------ mutable borrows are exclusive */
935
936/* OSC-1 section 3.1: while a mutable borrow is live, nothing else may reach its object. A mutable
937 * borrow m descends from r when m was bound (MOV) from r, or from a borrow descending from r, and
938 * neither register was written since (forward may-analysis). Reading r -- through a use, a second
939 * borrow, a copy, a call argument or a release -- at an instruction after which such an m is still
940 * live (backward liveness; m not written by that instruction) gives two live paths to one object
941 * and is refused: C2-BORROW-MUT-ALIAS (omega#465). Reading m itself, or a reborrow while its parent
942 * waits, is not such a read. */
943static void live_block(const Fx *x, const Bits *lin, int b, Bits *cur, Bits *after)
944{
945 const C2Func *f = x->f;
946 uint32_t first = f->blk[b].first, end = first + f->blk[b].count;
947 memset(cur, 0, sizeof *cur);
948 for (uint32_t i = first; i < end; i++)
949 if (f->in[i].op == C2_TRAP) end = i; /* a trap ends the path: nothing after it is read */
950 if (end == first + f->blk[b].count)
951 for (int k = 0; k < x->nsucc[b]; k++) bor(cur, &lin[x->succ[b][k]]);
952 for (uint32_t i = end; i-- > first;) {
953 if (after) after[i - first] = *cur;
954 int d = defines(&f->in[i]);
955 if (d >= 0) bclr(cur, (unsigned)d);
956 int16_t us[8];
957 int nu = uses(&f->in[i], us);
958 for (int k = 0; k < nu; k++) bset(cur, (unsigned)us[k]);
959 }
960}
961
962static void alias_def(const Fx *x, const int *mi, int nm, Bits *p, uint32_t i)
963{
964 const C2Insn *in = &x->f->in[i];
965 int d = defines(in);
966 if (d < 0) return;
967 Bits nw;
968 memset(&nw, 0, sizeof nw);
969 if (mi[d] >= 0 && in->op == C2_MOV && is_ref(&x->f->vt[in->a])) {
970 bset(&nw, (unsigned)in->a);
971 if (mi[in->a] >= 0) bor(&nw, &p[mi[in->a]]);
972 }
973 for (int j = 0; j < nm; j++) bclr(&p[j], (unsigned)d);
974 if (mi[d] >= 0) { bclr(&nw, (unsigned)d); p[mi[d]] = nw; }
975}
976
977static int check_mut_alias(Fx *x)
978{
979 const C2Func *f = x->f;
980 int mi[C2_MAX_VREGS], mreg[C2_MAX_VREGS], nm = 0;
981 for (int r = 0; r < f->nvregs; r++) {
982 mi[r] = -1;
983 if (f->vt[r].s == S_REF && f->vt[r].kind == K_MUT) { mi[r] = nm; mreg[nm++] = r; }
984 }
985 if (!nm) return 0;
986 static Bits lin[C2_MAX_BLOCKS];
987 memset(lin, 0, sizeof lin);
988 int changed = 1;
989 while (changed) {
990 changed = 0;
991 for (int b = f->nblocks; b-- > 0;) {
992 if (!x->reach[b]) continue;
993 Bits cur;
994 live_block(x, lin, b, &cur, NULL);
995 if (!beq(&cur, &lin[b])) { lin[b] = cur; changed = 1; }
996 }
997 }
998 Bits *pin = calloc((size_t)f->nblocks * (size_t)nm, sizeof *pin);
999 Bits *p = calloc((size_t)nm, sizeof *p);
1000 Bits *after = calloc(f->ninsns, sizeof *after);
1001 static int seen[C2_MAX_BLOCKS];
1002 int rc = 0;
1003 if (!pin || !p || !after) { rc = fail(x->v, "C2-RESOURCE", x->fi, -1, "out of memory"); goto out; }
1004 memset(seen, 0, sizeof seen);
1005 seen[0] = 1;
1006 changed = 1;
1007 while (changed) {
1008 changed = 0;
1009 for (int b = 0; b < f->nblocks; b++) {
1010 if (!seen[b]) continue;
1011 memcpy(p, &pin[(size_t)b * nm], (size_t)nm * sizeof *p);
1012 int trapped = 0;
1013 for (uint32_t i = f->blk[b].first; i < f->blk[b].first + f->blk[b].count && !trapped; i++) {
1014 if (f->in[i].op == C2_TRAP) trapped = 1;
1015 else alias_def(x, mi, nm, p, i);
1016 }
1017 if (trapped) continue;
1018 for (int k = 0; k < x->nsucc[b]; k++) {
1019 int s = x->succ[b][k];
1020 if (!seen[s]) { seen[s] = 1; changed = 1; }
1021 for (int j = 0; j < nm; j++) {
1022 Bits m = pin[(size_t)s * nm + j];
1023 bor(&m, &p[j]);
1024 if (!beq(&m, &pin[(size_t)s * nm + j])) { pin[(size_t)s * nm + j] = m; changed = 1; }
1025 }
1026 }
1027 }
1028 }
1029 for (int b = 0; b < f->nblocks && !rc; b++) {
1030 if (!seen[b]) continue;
1031 Bits cur;
1032 live_block(x, lin, b, &cur, after);
1033 memcpy(p, &pin[(size_t)b * nm], (size_t)nm * sizeof *p);
1034 for (uint32_t i = f->blk[b].first; i < f->blk[b].first + f->blk[b].count && !rc; i++) {
1035 const C2Insn *in = &f->in[i];
1036 if (in->op == C2_TRAP) break;
1037 int16_t us[8];
1038 int nu = uses(in, us), d = defines(in);
1039 const Bits *la = &after[i - f->blk[b].first];
1040 for (int k = 0; k < nu && !rc; k++) {
1041 int r = us[k];
1042 if (!is_ref(&f->vt[r])) continue;
1043 for (int j = 0; j < nm && !rc; j++) {
1044 int m = mreg[j];
1045 if (m == r || m == d || !btest(la, (unsigned)m)) continue;
1046 int hit = 0;
1047 hit = btest(&p[j], (unsigned)r); /* GUARD:mut-alias */
1048 if (hit)
1049 rc = fail(x->v, "C2-BORROW-MUT-ALIAS", x->fi, (int)i,
1050 "v%d used while mutable borrow v%d taken from it is still live", r, m);
1051 }
1052 }
1053 alias_def(x, mi, nm, p, i);
1054 }
1055 }
1056out:
1057 free(pin);
1058 free(p);
1059 free(after);
1060 return rc;
1061}
1062
1063/* ------------------------------------------------------------------ driver */
1064
1065static int check_func(const C2Unit *u, int fi, C2Verdict *v)
1066{
1067 const C2Func *f = &u->fn[fi];
1068 for (int g = 0; g < fi; g++)
1069 if (strcmp(u->fn[g].name, f->name) == 0) return fail(v, "C2-FUNC-NAME", fi, -1, "function %s defined twice", f->name); /* GUARD:func-name */
1070 if (f->nparams > C2_MAX_PARAMS || f->nparams > f->nvregs) /* GUARD:params */
1071 return fail(v, "C2-FUNC-PARAMS", fi, -1, "%u parameters, %u registers", f->nparams, f->nvregs);
1072 if (!(f->ret.s == S_VOID || is_value(f->ret.s))) /* GUARD:ret-scalar */
1073 return fail(v, "C2-FUNC-RETURN", fi, -1, "function returns a non-scalar");
1074 for (int r = 0; r < f->nvregs; r++) {
1075 const C2Type *t = &f->vt[r];
1076 if (!check_type(u, t)) return fail(v, "C2-TYPE-INVALID", fi, -1, "register v%d has an invalid type", r); /* GUARD:vreg-type */
1077 if (is_slice(t)) {
1078 if (r + 1 >= f->nparams || f->vt[r + 1].s != S_U64) /* GUARD:slice-param */
1079 return fail(v, "C2-SLICE-PARAM", fi, -1, "slice register v%d is not a parameter followed by its u64 length", r);
1080 if (r > 0 && is_slice(&f->vt[r - 1]))
1081 return fail(v, "C2-SLICE-PARAM", fi, -1, "slice v%d sits in the length register of v%d", r, r - 1);
1082 }
1083 }
1084 Fx *x = calloc(1, sizeof *x);
1085 if (!x) return fail(v, "C2-RESOURCE", fi, -1, "out of memory");
1086 x->u = u; x->f = f; x->fi = fi; x->v = v; x->nb = f->nblocks;
1087 x->blk_of = calloc(f->ninsns, sizeof *x->blk_of);
1088 int rc = -1;
1089 if (!x->blk_of) { fail(v, "C2-RESOURCE", fi, -1, "out of memory"); goto out; }
1090 if (build_cfg(x)) goto out;
1091 for (uint32_t i = 0; i < f->ninsns; i++)
1092 if (check_insn(x, i)) goto out;
1093 link_cfg(x);
1094 count_defs(x);
1095 if (check_handles(x)) goto out;
1096 if (check_defined(x)) goto out;
1097 if (check_loops(x)) goto out;
1098 if (check_ownership(x)) goto out;
1099 if (check_mut_alias(x)) goto out;
1100 rc = 0;
1101out:
1102 free(x->blk_of);
1103 free(x);
1104 return rc;
1105}
1106
1107int c2_check_unit(const C2Unit *u, C2Verdict *v)
1108{
1109 if (v) { memset(v, 0, sizeof *v); v->ok = 1; v->func = v->insn = -1; v->rule = "ACCEPT"; }
1110 if (check_structs(u, v)) return -1;
1111 for (int fi = 0; fi < u->nfuncs; fi++)
1112 if (check_func(u, fi, v)) return -1;
1113 return 0;
1114}