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 / seed / ng / IR.md

1169 lines · 82165 bytes Raw Blame History Rendered
1# ΩIR: the Omega next-generation intermediate representation
2
3```text
4Document: seed/ng/IR.md (ΩIR wire version 9, tag omega.ng.ir.v1)
5Status: PROPOSED draft v0.1 (ng-ir lane, Hive NG M0). Witness: seed/ng/ngcheck.om (own reader).
6 Text tools: seed/ng/ngas.om, ngdis.om. Reference interpreter: seed/ng/ngrun.om. Random
7 programs: seed/ng/ngrand.om. In-memory form and the one ng reader/writer: seed/ng/src/ir.om (s14).
8Decisions: Hive NG D1b, D2 + D2b + D2c, D3, D7, D10, D11 (2026-11-07).
9Family: spec/one-layer-format.md (OSC binary IR). Versions 1..8 are untouched by this document.
10Pin: omega-mv 943d955531b9d4d9f70deb41756c0b46441dd5e0, omc sha256 5f90edea…6df.
11```
12
13ΩIR is the one program form inside the `ng` compiler (D1b: one binary built from `seed/ng/src/`
14`ir.om front.om opt.om a64.om gpu.om main.om`): the front end writes it, the passes rewrite it, the
15AArch64 and sm_121 back ends read it. It is typed, in SSA form with block parameters,
16target-neutral, and carries the exact Omega meaning: every trap a program can raise is an explicit
17check op naming its trap code, every host word is an effect op, an ordering token makes trap order
18relative to every observable effect a dataflow edge, and only checked contracts become facts.
19
20## 1. Principles
21
221. **One meaning per byte string, one byte string per unit.** Fixed-width little-endian fields, no
23 padding, every unused field is 0, every enumeration has a closed set of values. A reader refuses
24 anything else; it never repairs, skips or guesses (OSC canonical law, one-layer-format s2).
252. **Arithmetic is total.** No arithmetic or conversion op has undefined behaviour or traps. Traps
26 come only from check ops (`chk.*`), `trap`, and the stack (s7.9). Removing a check can change
27 which value a program computes; it can never make the program's behaviour undefined.
283. **Trap order is dataflow (D2c, D7).** One ordering token threads every check, every effect
29 (store, atomic, host word, call, launch, barrier) and every terminator (s6.4). A check can move
30 only where its token edge lets it; the two legal ways to remove one are s15.
314. **Memory access is covered.** Every memory access op must be dominated by a bounds check or a
32 bounds fact on the same SSA values, and read the token at or after it (s8). The validator
33 enforces this, so an optimizer deletes a check only by putting a fact in its place. The one
34 exception is the run-time pool ops (s7.13), which hold their own bounds test and expose no address.
355. **Facts carry authority only when checked (D2c).** A front-end fact must sit under the runtime
36 check that establishes it; a pass-made fact names the pass whose proof it is (s7.10).
376. **Target facts are not IR.** Calling convention, register classes, clobbers, subgroup width
38 offered, shared memory budget, feature sets: these belong to a target descriptor checked by the
39 backend. The IR states what a kernel *requires* (s6.3), never what a chip *offers*.
407. **Limits are implementation limits with an exit code** (s12), never silent truncation.
41
42## 2. Encoding primitives
43
44`u8 u16 u32 u64`: unsigned little-endian, exactly that many bytes. There are no variable-length
45integers. A *type id*, *value id*, *block id*, *function id* and *global id* are each a `u32`.
46
47## 3. Module
48
49| bytes | field |
50|---|---|
51| 7 | magic `4F 53 43 31 49 52 00` (`OSC1IR\0`, the OSC family) |
52| 1 | version `9` |
53| 16 | domain tag: the 14 bytes `omega.ng.ir.v1` then two `00` |
54| 4 | `ntypes`, then `ntypes` type entries (s4.2) |
55| 4 | `nglobals`, then `nglobals` global entries (s5) |
56| 4 | `nfuncs`, then `nfuncs` function records (s6) |
57
58Nothing follows the last function record. **Identity** = SHA-256 of the whole byte string. ΩIR has
59no name table: names are debug information and are not carried in v1 (a later tag may add a side
60table outside identity, as OSC v6 did).
61
62Version discipline: a ΩIR reader refuses versions 1..8 and any tag other than the exact 16 bytes;
63OSC readers of versions 1..8 refuse version 9 by its version byte. A later ΩIR revision changes the
64tag (`omega.ng.ir.v2`), never the meaning of v1 bytes.
65
66## 4. Types
67
68### 4.1 Built-in scalar types (ids 0..31; no table entry)
69
70| id | type | id | type |
71|---|---|---|---|
72| 0 | void (result only; "no result") | 8 | i32 |
73| 1 | bool | 9 | i64 |
74| 2 | u8 | 13 | f32 (IEEE binary32) |
75| 3 | u16 | 14 | f64 (IEEE binary64) |
76| 4 | u32 | 16 | f16 (IEEE binary16) |
77| 5 | u64 | 17 | bf16 |
78| 6 | i8 | 18 | fp8 e4m3 (OCP FP8, storage and MMA input only) |
79| 7 | i16 | 19 | fp8 e5m2 (storage and MMA input only) |
80| | | 20 | tok, the ordering token (s6.4) |
81
82Ids 0..9, 13, 14 equal the OSC scalar tags (one-layer-format s3.4, s10.3). Ids 10, 11, 12, 15 and
8321..31 are reserved and refused (they carry OSC ref/bytes/cells/GEDIT meanings in other versions).
84*int* below means ids 2..9; *float* means 13, 14, 16, 17; *arith* means int or float; *num* also
85includes the fp8 ids. `tok` is a value type only for token values: it is never a function parameter
86or result, a table type's element, an operand of a non-token op, or a `const`.
87
88### 4.2 Type table (ids 32 + k)
89
90Entry k of the table has id 32 + k. An entry refers only to built-in ids and to entries before it
91(no cycles). Two entries with identical bytes are refused (NONCANONICAL): type equality is id
92equality. Each entry is a kind byte, then its fields:
93
94| kind | name | fields | rules |
95|---|---|---|---|
96| 1 | VEC | `elem u32`, `lanes u32` | elem bool, int or float; lanes 2, 4, 8, 16, 32 or 64; lanes x element bytes <= 64 (bool counts 1 byte) |
97| 2 | ARRAY | `elem u32`, `count u32` | elem num, VEC or STRUCT; count 1..16777216 |
98| 3 | STRUCT | `size u32`, `nfields u32`, per field: `type u32`, `offset u32`, `order u8` | size 1..1073741824; nfields 1..64; field type num, ARRAY or STRUCT; fields strictly ascending by offset, non-overlapping, inside size; order 0 little-endian, 1 big-endian (only meaningful for int/float fields; 0 for ARRAY/STRUCT fields) |
99| 4 | REF | `target u32`, `access u8`, `space u8` | a reference to one memory object of type target (ARRAY or STRUCT); length known from the type |
100| 5 | SLICE | `elem u32`, `access u8`, `space u8` | a reference to a run of elements of type elem (num, VEC or STRUCT) with a run-time length |
101| 6 | FRAG | `role u8`, `m u16`, `n u16`, `k u16`, `elem u32` | an MMA operand tile held by one subgroup (s7.8); role 0 A (m x k), 1 B (k x n), 2 C/D (m x n); m, n, k 1..256; elem num |
102
103`access`: 0 read-only (Omega `view`, `text`), 1 read-write (Omega `edit`, `out`, `fresh`, local arrays).
104`space` (numbers 1..4 from omega-mv#883 E3): 0 HOST (CPU process memory: stack, globals, text),
1051 GLOBAL (device global), 2 SHARED (block-shared), 3 CONSTANT (device constant, access must be 0),
1064 PRIVATE (per-thread device memory). OM-1 cell structs are STRUCTs whose fields sit at multiples
107of 8 bytes; OM-2 `layout`s are STRUCTs with their stated offsets and byte order.
108
109Memory layout of ARRAY and SLICE elements is packed at the element's size (one-layer-format s10.2):
110bool, u8, i8, fp8 1 byte; u16, i16, f16, bf16 2; u32, i32, f32 4; u64, i64, f64 8; VEC lanes x
111element; STRUCT its size. Scalars in memory are little-endian unless a STRUCT field says big.
112
113## 5. Globals
114
115Entry: `type u32` (an ARRAY for classes 0 and 1; a scalar element type for class 2), `class u8`, then for class 1 the initial bytes:
116
117| class | meaning | data |
118|---|---|---|
119| 0 | mutable, zero-filled once per program instance (Omega `global`) | none |
120| 1 | read-only with initial bytes (Omega `text`, constant tables) | exactly the array's byte size |
121
122Global ids are table indices. `gaddr` (s7.5) gives a REF to one; a REF with access 1 to a class 1
123global is refused (TYPE).
124
125**Class 2, run-time pool (s7.13).** `type`
126is not an ARRAY but the *element type id* itself, one of the native pool scalars: u8 u16 u32 u64 i8
127i16 i32 i64 f32 f64 (ids 2..9, 13, 14). Never bool, vectors, structs, ARRAYs, REFs, SLICEs or the
128reduced-precision floats (TYPE). There are no data bytes. The pool starts with zero elements; its
129length only grows (`pool.grow`), and its storage is zero-filled and may move whenever it grows. Because
130the storage can move, no REF or SLICE to it can exist: `gaddr` of a class 2 global is TYPE, no op takes a
131pool as a value, and every access names the global id as an immediate (s7.13). A class byte above 2 is
132NONCANONICAL. Classes 0 and 1 and every existing op are unchanged.
133
134## 6. Functions
135
136### 6.1 Record
137
138| bytes | field |
139|---|---|
140| 1 | `kind`: 0 function, 1 kernel, 2 export (an entry a host calls in function mode) |
141| 1 | `flags`: bit 0 inline hint; bit 1 the callback function (below); other bits 0 |
142| 4 | `nparams` 0..64, then `nparams` param type ids (`u32` each) |
143| 4 | `result` type id (0 = void) |
144| kernel only: 4+4+4 | `tx ty tz`: threads per block on each axis, each 1..4096, product 1..4096 |
145| kernel only: 1 | `subgroup`: 0 any, else the required subgroup width 4, 8, 16, 32, 64 or 128 |
146| 4 | `nblocks` 1..65536, then the blocks |
147
148Block: `nbparams u32` 0..64, `nbparams` param type ids, `nops u32` >= 1, then the ops (s7.1).
149Block 0 (the entry) has no parameters and is never a branch target. Every other block has at least
150one parameter, and its parameter 0 has type `tok` (s6.4); no other parameter is `tok`.
151
152Any function may call any non-kernel function, including itself and later ones. A kernel's result
153is void; a kernel calls no function and no function calls a kernel except through `launch` (s7.7).
154
155**Callback function (flags bit 1).** At most one function of a unit, of kind 0, with exactly six `u64`
156parameters and result `u64`. It is the function library code calls back in a Mach-O program (s7.11, library
157words; `seed/ng/a64/DESIGN.md` s14); to every other consumer it is an ordinary function. Any other kind or
158signature, or a second such function, is FIELD (13) at the function record.
159
160**Program entry (D11).** A unit is a program: exactly one function has kind 2 (export), no
161parameters and result i32. It is the process entry (Omega `fn main to int`), and its result is the
162exit status. Other exports (with parameters or another result) are entries a host calls in
163function mode. A unit with no such function, or with several, is refused ENTRY (exit 30).
164
165### 6.2 Values (SSA)
166
167Every value is defined exactly once. Value ids are implicit, never stored. In each function:
168value 0 is the entry token (type `tok`), values 1 .. nparams are the parameters, then, block by
169block in order, each block's parameters, then each op's definitions in op order. A token op (s6.4)
170defines its new token first and then its result if `ty` != 0; any other op defines one value when
171`ty` != 0 and none otherwise (checks and facts take `ty` as a parameter and define only the token
172or nothing, s7.1). A use names a value id.
173
174- A use in block B at op j is valid when the definition is earlier in B (a parameter of B, or an op
175 before j), or in a block that strictly dominates B, or is value 0 or a function parameter.
176- A use of an id at or past the function's value count, or of a later op in the same block, is
177 USE_BEFORE_DEF; a definition in a non-dominating block is DOMINANCE.
178- Every block must be reachable from block 0 (UNREACHABLE).
179- Values passed to a block's parameters come only from `br` and `cbr` (s7.6); merges are block
180 parameters, there are no phi ops.
181
182### 6.3 Kernels (one form for CPU and GPU)
183
184A kernel describes the work of one thread; a launch runs it over a grid of blocks of `tx*ty*tz`
185threads. The same kernel IR is lowered by `src/a64.om` (threads as loops and NEON lanes) and by
186`src/gpu.om` (threads as sm_121 threads). `subgroup` is what the kernel requires; the target offers its
187own width in its descriptor, and the backend refuses a mismatch (omega-mv#883 E3 s1). Shared
188memory budget, nesting depth, thread maximum and feature set are target-descriptor checks done
189by the backend, not by ngcheck. The race, divergence and sync rules of `docs/omegese/GPU.md`
190(s6, s8 on `c1/chip-fix`) are kernel-checker obligations of the GPU lane (M5); ngcheck checks the
191structural rules of s9.
192
193### 6.4 The ordering token (D2c)
194
195At every point of a block there is exactly one *current token*: value 0 at the start of block 0,
196parameter 0 at the start of any other block. Ops are of three token classes (the `tk` column of
197s7.12):
198
199| class | ops | rule |
200|---|---|---|
201| E effect | every `chk.*`, `store fstore vstore fill atom atomcas mmast alloca sync call launch host`, and the pool ops `pool.grow pool.store pool.read pool.write` | operand 0 is the current token; the op defines a new token, which becomes current |
202| R reader | `load fload vload mmald slice`, and the pool ops `pool.len pool.load` | operand 0 is a token defined in this block at or before the current one, or one that dominates the block (the memory state it reads; s8 bounds which) |
203| T terminator | `br cbr ret retv trap exit` | operand 0 of `br`'s arguments, and operand 0 of the others, is the current token |
204
205All other ops take no token. A token value is used only as operand 0 of an E, R or T op (TOKEN,
206exit 28, otherwise; also when an E or T op names a token that is not current). The token is
207linear for E and T ops: on every path each token is consumed by exactly one E or T op (the one
208right after it on the chain), because only the current token may be consumed and consuming it
209replaces it. So the tokens of a function form one chain along every path, and every check, every
210observable effect and every exit sits at a fixed place on it: a check cannot pass a store, a host
211word, a call, a trap or another check without a rewrite that the validator sees. Reader ops (R)
212read the chain without consuming it, so loads are not linear: an optimizer may give a load an older
213token when it proves no store between the two writes the loaded element, and s8 rule 3 forbids an
214older token than the check that covers it, so a load is never hoisted above its bounds check.
215ngcheck checks the structural rule and s8, not alias proofs.
216
217In the operand lists of s7 the token operand is not repeated: for E and R ops it is the first
218operand on the wire, before the listed ones.
219
220## 7. Ops
221
222### 7.1 Encoding of an op
223
224| bytes | field |
225|---|---|
226| 1 | `op` (s7.2 onward) |
227| 4 | `ty`: the result type id, 0 when the op has no result; for `chk.conv` the destination type (s7.9) |
228| 8 | `imm`, present only when the row has an imm column; 0 when its meaning says unused |
229| 4 | `n`, present only for variadic rows (`br`, `call`, `host`, `launch`) |
230| 4 each | operands: the token (E, R and T ops except `br`), the row's fixed operands, then `n` variadic operands |
231
232Operand kinds: `b` block id (`br` operand 0, `cbr` operands 2 and 3), `f` function id (`call`
233operand 1, `launch` operand 1); every other operand is a value id. Every `ty`, `imm` and operand is
234checked against its row: a value outside the row's types is TYPE. The full row table, with the
235field layout every reader uses, is s7.12.
236
237Terminators are `br cbr ret retv trap exit` (and nothing else). Each block ends with exactly one
238terminator, and no terminator appears before its end (UNTERMINATED).
239
240Notation in the tables: `T` the result type; operand types in parentheses; *same* means the same
241type id as `T`; the token operand is not listed (s6.4).
242
243### 7.2 Constants and selection (1..9)
244
245| op | name | ty | imm | operands | meaning |
246|---|---|---|---|---|---|
247| 1 | `const` | num | bits | - | the value of type T whose bits are imm (canonical form below) |
248| 2 | `select` | any value type | - | c (bool), a, b (same) | a if c else b |
249
250Canonical `const` imm: bool 0 or 1; unsigned ints zero-extended (high bits 0); signed ints
251sign-extended two's complement of the width; f32, f16, bf16, fp8 in the low 16/8/32 bits with the
252rest 0; f64 all 64 bits. Any other imm is NONCANONICAL. Vectors are built with `vsplat`/`vinsert`.
253
254### 7.3 Arithmetic, bitwise, comparison (10..39)
255
256All operate on a scalar or on a VEC (lane by lane); the operands have type T unless stated.
257
258| op | name | types | meaning (total) |
259|---|---|---|---|
260| 10 | `add` | arith | int: modulo 2^w. float: IEEE, round to nearest even |
261| 11 | `sub` | arith | as add |
262| 12 | `mul` | arith | as add |
263| 13 | `div` | arith | int: toward zero; divisor 0 gives 0; signed MIN / -1 gives MIN. float: IEEE |
264| 14 | `rem` | int | sign of the dividend; divisor 0 gives 0; MIN rem -1 gives 0 |
265| 15 | `neg` | arith (1 operand) | int: 0 - a modulo 2^w. float: flip the sign bit only |
266| 16 | `and` | bool, int | bitwise (bool: logical) |
267| 17 | `or` | bool, int | as and |
268| 18 | `xor` | bool, int | as and |
269| 19 | `not` | bool, int (1 operand) | bitwise complement (bool: logical) |
270| 20 | `shl` | int | amount b taken modulo w; bits shifted out are lost |
271| 21 | `shr` | int | amount modulo w; arithmetic for signed, logical for unsigned |
272| 22 | `rotl` | unsigned int | amount modulo w |
273| 23 | `rotr` | unsigned int | amount modulo w |
274| 24 | `min` | arith | int: by signedness. float: IEEE minNum as Omega `fmin` (AArch64 FMINNM): one quiet NaN gives the other operand; a signaling NaN in either operand gives a quiet NaN; two NaNs give a quiet NaN; min(-0, +0) and min(+0, -0) are -0 |
275| 25 | `max` | arith | float: as min, maximum (FMAXNM); max(-0, +0) and max(+0, -0) are +0 |
276| 26 | `fsqrt` | float (1 operand) | IEEE square root, correctly rounded |
277| 27 | `fabs` | float (1 operand) | clear the sign bit |
278| 28 | `fmath` | float (1 operand), imm | transcendental with accuracy class, below |
279| 30..35 | `eq ne lt le gt ge` | operands int, bool (eq, ne only) or float; ty bool, or VEC of bool with the operands' lanes | int by signedness; float IEEE ordered: any NaN gives false except `ne` |
280| 36 | `conv` | ty num; operand num of another type; imm | numeric conversion, below |
281| 37 | `bitcast` | ty and operand of equal bit width | reinterpret bits (one-layer-format s10.2 sets, extended to f16/bf16 with u16/i16 and fp8 with u8/i8) |
282
283Float `min`/`max` (contract correction 2026-11-10, NgIrOracle head 2): the earlier draft rule "a
284NaN operand gives the other" did not match the language. OMEGESE s9.9 defines `fmin`/`fmax` as
285FMINNM/FMAXNM and the seeded compiler measures so: fmin(sNaN, 1.0f32) is the quiet NaN 0x7fc00001;
286fmin(qNaN, 1.0) is 1.0; signed zeros as in the rows above. The quiet NaN's payload is unspecified,
287like every arithmetic NaN. x86-64 back ends: MINSS/MAXSS do not implement this rule (they return
288the second operand for any NaN and do not order signed zeros); they need an explicit NaN and
289zero sequence.
290
291Float arithmetic never contracts separate ops into a fused op; only `fma` is fused. A NaN produced
292by arithmetic may have any quiet-NaN payload; `const`, memory ops, `select`, `bitcast`, `neg` and
293`fabs` preserve every bit (one-layer-format s10.3). f16 and bf16 arithmetic rounds each op to the
294type. fp8 types are refused by every op of this section except `conv` and `bitcast`.
295
296`fmath` imm: bits 0..7 function (0 exp, 1 exp2, 2 log2, 3 inv (1/x), 4 rsq (1/sqrt x), 5 sin,
2976 cos, 7 tanh); bits 8..15 accuracy class (0 CR correctly rounded, 1 ULP(n), 2 FAST target-stated
298bound); bits 16..23 n for ULP (1..255, else 0); bit 24 denormal inputs and outputs may flush to
299zero (0 = kept); other bits 0. The class is what the program requires; a backend that cannot meet
300it refuses (omega-mv#883 E3 s4). Omegese GPU `exp`/`inv`/`root` lower to class FAST with bit 24.
301
302`conv` imm: bits 0..1 rounding for a float destination (0 nearest even, 1 toward zero), bit 2
303saturate to the largest finite value instead of infinity (float destinations only); other bits 0;
304an int destination requires imm 0. Rules (one-layer-format s10.3): int to int keeps the low w bits
305of the source value (sign- or zero-extended first by the source's signedness), so it never traps;
306`chk.conv` (s7.9) gives Omega's trap 5. int to float rounds per imm. float to int truncates toward
307zero and saturates to the destination range; NaN gives 0. float to float rounds per imm. bool is not
308a conv operand or result: compare instead.
309
310### 7.4 Fused multiply-add (46)
311
312| op | name | ty | operands | meaning |
313|---|---|---|---|---|
314| 46 | `fma` | float or VEC of float | a, b, c (same) | a x b + c rounded once (OSC v8 MAD, number kept) |
315
316### 7.5 Memory (42, 43, 47, 48, 50..59)
317
318`r` is a REF or SLICE; `i` an index of type u32 or u64, counted in elements of the target array or
319slice. All accesses are covered (s8). Opcode numbers 42, 43, 47 keep OSC v8's GLOAD, GSTORE and
320ATOM, generalized to every space.
321
322| op | name | ty | imm | operands | meaning |
323|---|---|---|---|---|---|
324| 42 | `load` | element type | - | r, i | element i |
325| 43 | `store` | 0 | - | r (access 1), i, v (element type) | element i = v |
326| 47 | `atom` | element type (u32, i32, u64, i64, f32) | op, scope, order | r (access 1), i, v | atomic read-modify-write; result is the old value |
327| 48 | `atomcas` | element type | scope, order | r (access 1), i, expect, new | if element i == expect then store new; result is the old value |
328| 50 | `alloca` | REF (access 1, space 0 or 4) to ARRAY or STRUCT | - | - | fresh zero-filled storage for this invocation; entry block only |
329| 51 | `fill` | 0 | - | r (access 1, ARRAY or SLICE), v (element) | every element = v |
330| 52 | `gaddr` | REF to the global's type, space 0 | global id | - | the global's storage |
331| 53 | `len` | u64 | - | r (ARRAY REF or SLICE) | element count |
332| 54 | `slice` | SLICE (same elem and space, access <= r's) | - | r, off (u64), n (u64) | elements off .. off+n-1; covered by a `chk.slice` or `fact.slice` on (r, off, n) |
333| 55 | `fload` | the field's scalar type | field index | r (REF to STRUCT) | the field |
334| 56 | `fstore` | 0 | field index | r (access 1), v | the field = v |
335| 57 | `fref` | REF to the field's ARRAY or STRUCT, same access and space | field index | r (REF to STRUCT) | the sub-object |
336| 58 | `vload` | VEC (lanes L of the element type) | - | r, i | elements i .. i+L-1 |
337| 59 | `vstore` | 0 | - | r (access 1), i, v (VEC) | elements i .. i+L-1 = v |
338
339`atom` imm: bits 0..7 op (0 add, 1 min, 2 max, 3 and, 4 or, 5 xor, 6 exch); bits 8..15 scope (0
340subgroup, 1 block, 2 device, 3 system); bits 16..23 order (0 relaxed, 1 acquire-release); others
3410. `atomcas` uses bits 8..23 the same way, bits 0..7 are 0. Integer add wraps; float add rounds to
342nearest even. In a function (not a kernel) the only thread is the caller, so an atomic is its plain
343read-modify-write.
344
345**STRUCT elements are storage-only (v1).** An ARRAY or SLICE may have STRUCT elements (s4.2), and
346`alloca`, `gaddr`, `len` and `slice` take such storage, but no value is ever a STRUCT or an ARRAY
347(value types are scalar, VEC, REF, SLICE or FRAG). So `load`, `store`, `atom`, `atomcas`, `fill`,
348`vload` and `vstore` need a scalar (or, for `load`/`store`, VEC) element and refuse a STRUCT element
349with TYPE at the op, and no op yields a REF to one element. Fields are reached only through a REF to
350the STRUCT itself (`gaddr`, `alloca`, or `fref` of an enclosing STRUCT) with `fload`, `fstore` and
351`fref`; per-record data is laid out as a STRUCT of ARRAY fields: `fref` to the field's ARRAY, then
352`load`/`store` element i under its `chk.bounds`. Omega has no arrays of structs (a struct is one
353`new` object), so the front end needs no other route; an element-reference op is a later
354extension. Fixtures: `r-struct-elem.oir` (TYPE), `k-soa.oir` (accepted).
355
356### 7.6 Control (60..66)
357
358| op | name | ty | imm | operands | meaning |
359|---|---|---|---|---|---|
360| 60 | `br` | 0 | - | b, then n values | jump to b; the n values (n = b's parameter count, same types in order; value 0 of them is the current token) become its parameters (BLOCK_ARITY) |
361| 61 | `cbr` | 0 | - | c (bool), bt, bf | jump to bt if c else bf, passing the current token; bt and bf have exactly one parameter, the token (BLOCK_ARITY) |
362| 62 | `ret` | 0 | - | - | return from a void function or kernel |
363| 63 | `retv` | 0 | - | v (the function's result type) | return v |
364| 64 | `call` | the callee's result | - | f, then n arguments | call f (any non-kernel function; n and types equal f's parameters) |
365| 65 | `trap` | 0 | code 1..14 | - | trap with code (Omega `trap N`, exit 100+code) |
366| 66 | `exit` | 0 | - | v (i32) | end the process with status v (Omega `exit`); functions and exports only |
367
368`trap` in a kernel ends the thread (kernel traps below).
369
370### 7.7 Kernel ops (40, 41, 44, 45, 67)
371
372| op | name | ty | imm | operands | meaning |
373|---|---|---|---|---|---|
374| 40 | `gpu.id` | u32 | which | - | 0 thread.x, 1 block.x, 2 blocks.x, 3 block.y, 4 blocks.y (OSC v8 THREAD, BLOCK, BLOCKS, BATCH, BATCHES), 5 thread.y, 6 thread.z, 7 block.z, 8 blocks.z, 9 lane in subgroup, 10 subgroup index in block |
375| 41 | `shared` | REF (access 1, space 2) to ARRAY | - | - | block-shared storage, zero at kernel start; kernel entry block only |
376| 44 | `sync` | 0 | - | - | block barrier |
377| 45 | `shfl` | u32, i32, f32 (or u64, i64, f64) | mode | v (same), d (u32) | mode 1 DOWN, 2 UP, 3 XOR, 4 IDX (E3 numbers); d must be a `const`: 1..127 for DOWN/UP, 0..127 for XOR/IDX, and below `subgroup` when the kernel declares one. A source lane outside the subgroup gives the caller's own v |
378| 67 | `launch` | 0 | - | f (a kernel), gx, gy, gz (u32), then n arguments | run kernel f on a grid of gx x gy x gz blocks and wait; functions and exports only |
379
380`gpu.id`, `shared`, `sync` and `shfl` appear only in kernels; `launch` and `exit` only outside them
381(EFFECT).
382
383**Kernel traps (D10).** The trap state of a launch is one sticky code. A thread that fails a check or
384reaches `trap` records its code (only its first; later checks of that thread record nothing). When
385the launch ends, if any thread recorded a code, `launch` traps in the caller with the code of the
386trapping thread with the lowest linear id: block linear id first, then thread linear id, that is
387((block.z x blocks.y + block.y) x blocks.x + block.x) x (tx x ty x tz) + (thread.z x ty + thread.y)
388x tx + thread.x. This is the code a sequential lowering that runs threads in linear order reports,
389so `src/a64.om` and `src/gpu.om` agree. Kernel stores and atomics are unordered relative to traps:
390after a trapping launch every location the kernel could write has an unspecified value. Obligation
391on every back end: a trap never strands threads at a barrier. A trapped thread still arrives at
392every `sync` it would reach (one way: it keeps running with its stores and atomics suppressed and
393its loads reading 0, every loop being fuel-bounded; another: the barrier counts it as arrived);
394`src/gpu.om` states which mechanism it uses. Without a trap the launch returns normally and every
395kernel write is visible to the caller after `launch`. Inside a kernel the token orders a thread's
396own checks and effects; it orders nothing between threads (only `sync` and atomics do).
397
398`src/gpu.om` (ng-gpu, PROPOSED, `~/handoffs/hive-ng/gpu/IR-GPU-DRAFT.md`) takes the second way: a
399trapping thread does a device-scope 64-bit unsigned atomic min of `(linear id << 4) | code` into
400one per-launch trap word (initialised to all ones, CPU-visible and uncached) and exits; the host
401reads the word after the launch, so the lowest linear id wins as above. Exited threads release
402barriers (PTX ISA 9.4, `exit`; that `BAR.SYNC` on GB10 does the same is untested until ng-gpu's
403chip check). Its target-descriptor limits: fewer than 2^60 threads per launch, and an encoder with
404a 64-bit atomic min.
405
406### 7.8 Vectors and tiles (100..106)
407
408| op | name | ty | imm | operands | meaning |
409|---|---|---|---|---|---|
410| 100 | `vsplat` | VEC | - | s (element) | every lane = s |
411| 101 | `vextract` | element | lane | v (VEC) | lane `imm` (< lanes) |
412| 102 | `vinsert` | VEC | lane | v (same), s (element) | v with lane `imm` = s |
413| 103 | `vreduce` | element | op | v (VEC) | op 0 add, 1 min, 2 max, 3 and, 4 or, 5 xor. Pairwise order: lanes [0, L/2) combine with [L/2, L) lane by lane, repeated until one lane |
414| 104 | `mmald` | FRAG (role 0, 1 or 2) | layout | r, i, ld (u64), e (u64) | load a tile from r: element (row, col) at i + row x ld + col for layout 0 (row-major), i + col x ld + row for layout 1; positions at or past i + e read as 0 |
415| 105 | `mmast` | 0 | layout | r (access 1), i, ld, e, d (FRAG role 2) | store a tile, positions at or past i + e not written |
416| 106 | `mma` | FRAG role 2 | class | a (role 0), b (role 1), c (role 2) with equal m, n, k | D = A x B + C. class 0: the reference, for each (row, col) c then k = 0 .. K-1 in order, each step one `fma` in D's element type; class 2 FAST: a target-stated bound, never compared bit for bit |
417
418FRAG values are cooperative over one subgroup and appear only in kernels (EFFECT outside). Their
419register layout is the backend's; ΩIR reaches them only through `mmald`, `mmast` and `mma`.
420
421### 7.9 Checks (70..82): the only ops that trap
422
423A check is an E op (s6.4): it reads the current token and defines the next one, and defines no other
424value. Its `imm` is the trap code, which must equal the code in the row (CHECK_CODE); only
425`chk.true` takes any code 1..14. Code 0 is always CHECK_CODE. On failure the program traps with
426that code (exit 100 + code) and no later effect on the token chain happens; on success nothing
427happens. Operands have the type the row names.
428
429| op | name | ty parameter | operands | code | fails when |
430|---|---|---|---|---|---|
431| 70 | `chk.add` | 0 | a, b (int, equal) | 1 | the exact a + b is outside the type |
432| 71 | `chk.sub` | 0 | a, b | 1 | the exact a - b is outside the type |
433| 72 | `chk.mul` | 0 | a, b | 1 | the exact a x b is outside the type |
434| 73 | `chk.neg` | 0 | a | 1 | the exact -a is outside the type |
435| 74 | `chk.divz` | 0 | b (int) | 2 | b = 0 |
436| 75 | `chk.divovf` | 0 | a, b (signed int) | 1 | a = MIN and b = -1 (`div` only; `rem` does not trap) |
437| 76 | `chk.shl` | 0 | a, b (signed int) | 1 | the exact a x 2^b is outside the type (b already in range) |
438| 77 | `chk.shift` | 0 | b (int) | 7 | b < 0 or b >= the width of b's type (Omega rotates: amount and value share a type; an Omega shift whose amount has another integer type reaches it after conv to u64, lt the width, chk.true 7 and conv: seed/ng/front/README.md) |
439| 78 | `chk.conv` | the destination type (int) | v (int or float) | 5 | v (truncated toward zero, if float) is NaN or outside the destination |
440| 79 | `chk.bounds` | 0 | r, i, e (u64) | 3 | i + e > len r (exact, no wrap) or e = 0 |
441| 80 | `chk.slice` | 0 | r, off (u64), n (u64) | 3 | off > len r or n > len r - off |
442| 81 | `chk.fuel` | 0 | k (u64), m (u64) | 4 | k >= m (a loop about to run its (k+1)-th pass with bound m) |
443| 82 | `chk.true` | 0 | c (bool) | any 1..14 | c is false (contracts: 9 requires, 10 ensures, invariant, holds) |
444
445For unsigned operands `chk.add/sub/mul/neg` fail on any wrap; Omega functions wrap unsigned values
446and never emit them, Omegese kernels trap on u32 overflow and do.
447
448`chk.fuel` order: the front end emits a `while` loop the way omc runs it (`seed/omc/omc.om`
4499469-9505, note at 9470-9471): at the loop head the condition is evaluated first; when it is false
450the loop exits without a fuel check; when it is true `chk.fuel 4 k N` runs (k = passes completed),
451then k + 1, then the body. So a loop that runs zero times never traps 4, and a loop whose
452condition is still true after exactly N passes traps 4.
453
454Trap 6 (stack) is not a check op: `call` and `alloca` may trap 6 when the back end's stack is
455exhausted, before any effect of the callee or allocation. NG frames differ in size from omc's, so
456the differential gate compares trap 6 only when both compilers trap 6, and records stack-depth
457cases as BEYOND_OMC (D9).
458
459### 7.10 Facts (90..93): non-executing
460
461A fact has no result, no token and no run-time effect. It states a property that holds whenever
462control reaches it; consumers (passes, back ends) may rely on it. `imm` is the origin. D2c gives a
463fact authority only through a check or a proof:
464
465- **origin 0 (front end):** the fact restates a check. It must be dominated by a check op with the
466 same operands (`fact.true c` by `chk.true k c` for any code k; `fact.inbounds r i e` by
467 `chk.bounds r i e`; `fact.slice r off n` by `chk.slice r off n`; `fact.range v lo hi` by
468 `chk.true` on a value the front end built as `and (ge v lo) (le v hi)`, which ngcheck does not
469 trace, so origin 0 `fact.range` is refused). An unchecked origin 0 fact is FACT (exit 29). This is
470 how an Omega `requires`, `ensures`, `invariant` or `holds` reaches the optimizer: its `chk.true`
471 runs first. A contract the build does not check produces no fact.
472- **origin 1..255 (a pass):** the number of the pass whose proof it is (the pass table is in
473 `src/opt.om`). ngcheck checks typing and placement, not truth; every such pass carries its own
474 translation-validation gate and mutants (D7, D9).
475
476Other origin values are NONCANONICAL.
477
478| op | name | operands | states |
479|---|---|---|---|
480| 90 | `fact.true` | c (bool) | c is true |
481| 91 | `fact.range` | v (int), lo, hi (same type, each defined by `const`, lo <= hi) | lo <= v <= hi |
482| 92 | `fact.inbounds` | r, i, e (u64) | i + e <= len r and e >= 1 |
483| 93 | `fact.slice` | r, off, n (u64) | off <= len r and n <= len r - off |
484
485### 7.11 Effects (110): host words
486
487| op | name | ty | imm | operands | meaning |
488|---|---|---|---|---|---|
489| 110 | `host` | i64, or 0 for class `cpu` | word id | n arguments | the Omega host word with that keyword id; result as OMEGESE s10: a count or minus the Linux errno |
490
491`imm` is the keyword id of the pinned `seed/omc/omc.om` keyword lookup (`read` 53, `write` 54,
492`fclose` 100 through `vfioirq` 232, `execenv` 233, `prlimit` 235 and the scheduler words `cpuset` 236
493through `getprio` 240; `exit`, `const`, `qty`,
494`fma` and the x86efi word `efi` are not host words). The normative
495table is `seed/ng/hostwords.tsv` (columns `id word args class`, 99 rows, extracted from OMEGESE s10,
496`seed/host/MAPPING.md` and the typing code of `seed/omc/omc.om` at the pin); `ngcheck --table`
497prints the table it compiles in and the gate requires those bytes to equal the file. Argument
498letters, one per source argument:
499
500| letter | operands | type |
501|---|---|---|
502| `i` | 1 | i32 |
503| `l` | 1 | i64 |
504| `L` | 1 | u64 |
505| `u` | 1 | u32, defined by a `const` (Omega requires a literal request number) |
506| `r` | 3: A, off, n | A a u8 SLICE or REF to a u8 ARRAY, any access; off, n u64 |
507| `w` | 3: A, off, n | as `r`, access 1 |
508| `S` | 3: A, off, n | `vfioctl` only: as `w`, except as `r` when the preceding `u` request is 15210 (`omc.om` 7610, 7660) |
509
510Every slice is covered by `chk.slice`/`fact.slice` on the same three values (s8). The words of class
511`cpu` (`cpufence`, `cpurelax`) have no result (ty 0); every other word has ty i64. `host` appears
512only in functions and exports (EFFECT). Host effects happen in program order; an optimizer never
513reorders, duplicates or removes a `host` op.
514
515**Reference interpreter host policy.** `ngrun FILE.ir [STEPS] [--scratch NEW-DIR] [-- ARGS...]`
516executes only host words whose effects are deterministic or confined, so a differential test can
517compare stdout and exit status with a native run. `argcnt` and `argread` see FILE.ir as argument 0
518and the ARGS after `--` as arguments 1.., so the count equals that of a native program given the
519same ARGS; `envcnt`/`envread` read ngrun's own environment. `monons`, `realns`,
520`getuid`, `geteuid`, `getgid`, `getegid`, `cpufence` and `cpurelax` execute natively; IR.md
521defines no fixed-value clock mode, so clock results are live and a test may compare only their sign.
522`sleepns 0` executes; a negative interval traps 3 as the native word does; any other interval is
523refused as nondeterministic.
524File words run only with `--scratch`: ngrun creates NEW-DIR (mode 0700; it must not exist), opens it
525with O_DIRECTORY|O_NOFOLLOW and makes it the working directory. A path over 4095 bytes or holding a
526zero byte, and a `renames` or `link` packet that is malformed (count other than 2, a record past the
527end, trailing bytes, an empty record, a zero byte), an empty `stat`, `lstat` or `readlnk` path, and a
528`stat`, `lstat` or `fstat` output under 128 bytes, trap 3 as the native word does, before
529any check below and with or without `--scratch`. Every path must then be one nonempty component (no
530`/`, not `.` or `..`); `renames` and `link` packets must hold exactly two such names. Opens add
531O_NOFOLLOW, and `chdir` opens the name with O_PATH|O_DIRECTORY|O_NOFOLLOW and changes directory with
532`fchdir`, so neither follows a final link. `stat`, `chmod`, `chown`, `truncate` and `faccess`, which
533follow a final link natively, open the name with O_PATH|O_NOFOLLOW, return -40 (ELOOP) when it is a
534link, and otherwise act on `/proc/self/fd/N`, the inode that open found; the kernel's EINVAL checks
535that precede the lookup (`faccess` mode outside 0..7, `truncate` length below 0) come first. So a
536link another process plants in NEW-DIR while ngrun runs is never followed. The interpreted program
537cannot create a link itself (`symlnk` is refused), so a native run and ngrun agree on every result.
538Descriptors are virtual: stdin (0) may be read and stdout/stderr (1, 2) written, and `fclose` may
539close any of the three, as a native program may; every other operation needs a descriptor created by
540an interpreted `fopen` or `memfd`. `memfd` names no path and runs without `--scratch`. A refused word
541prints `ngrun: refused host class C word W at OFFSET` on stderr
542and exits C before any effect. A word refused below whose native form traps 3 on its operands before
543any kernel call traps 3 first, as natively: `waitio` events outside 0..65535, a `peercred` output
544under 12 bytes, a `pollfds` length that is not a multiple of 8 or is over 8192, a `waitpid` output
545under 4 bytes, a `pipefds` output under 8 bytes, and an `execprog`, `execpure`, `execenv` or `symlnk`
546packet that breaks the packed-list rules of OMEGESE s10 (an exec argument packet, that of `execprog`,
547`execpure` or the first of `execenv`, is 2..65536 bytes with count 1..1024, as the pinned omc 564c5835
548lowers it; a `symlnk` packet and the `execenv` environment 2..4096 bytes with count 1..64; records inside
549the packet, no trailing bytes, no zero byte; a nonempty first record for the exec words, exactly two
550nonempty records for `symlnk`, every `execenv` environment record nonempty). The device class (117)
551is refused without this check: its native trap conditions (mapping-table and device-descriptor checks)
552are not mirrored, so a device word with such operands exits 117 where a native run traps 3.
553
554| exit | class | words |
555|---|---|---|
556| 115 | process | fork dupfd waitpid execprog execpure execenv killpid pipefds getpid getppid setsid getpgid setpgid getsid cpuset cpuget setprio getprio |
557| 116 | limits | prlimit |
558| 117 | device | devctl mapnew mapdrop mapread mapwrite devcall uvmctl mapaddr mapget mapset maphold mapbind vfioctl vfiomap vfiomapw eventfd vfioirq libfn libptr libcall |
559| 118 | network | socknew listen accept connect bind recv send waitio sockname sockopt shutdown peercred pollfds sendmsg peername |
560| 119 | outside scratch | any path or descriptor word without `--scratch`, an absolute or multi-component path, `.`/`..`, a descriptor ngrun did not create (including pread/pwrite on 0..2) |
561| 120 | nondeterministic | random, sleepns with a positive interval, cpunow |
562| 121 | unsafe filesystem | symlnk, syncfs, a blocking or shared-wait flock |
563| 122 | unclassified | a host word id with no row here (unreachable for accepted units) |
564| 123 | descriptor table | more than 256 live virtual descriptors |
565
566These exits sit above the trap range 101..114 and below 124 (step limit), 125 (unsupported op) and
567126 (access outside storage). They describe the reference interpreter, not program semantics:
568native code may execute every word.
569
570**Library words (class `lib`, ng only).** `hostwords.tsv` is the table of omc's words and stays that: the gate
571audits it against the pinned omc source. ng's own words have their own table, `seed/ng/hostwords-ng.tsv` (same
572columns, 3 rows), which ngcheck compiles in after the first (`--table` prints the first only). In a unit whose
573first line is `target macos` the front end reads these three more keywords, and gives the function named
574`libback` (six `ulong` parameters, result `ulong`) flags bit 1: with it, `libfn k` for k 2..17 is the address
575of callback entry k - 2, a C function that runs `libback(k - 2, x0, x1, x2, x3, x4)` and returns its result; in every other unit they are ordinary names, as omc reads them (omc refuses `target macos`, error
57625). They are the one gateway from an Omega program to code outside it, and only the Mach-O target has them
577(`@ng a64` refuses each: `a64: unsupported 241`..`243`, exit 5; ngrun refuses them as class 117). Their value is the
578raw 64-bit result, not a count or an errno.
579
580| id | word | value |
581|---|---|---|
582| 241 | `libfn k` | the address of `dlopen` (k = 0) or `dlsym` (k = 1), bound by dyld when the program starts; 0 for any other k |
583| 242 | `libptr A off n` | the address of byte `off` of the writable byte slice (checked like every slice) |
584| 243 | `libcall F A off n` | calls the function at address F with the C calling convention. The slice is the register file, at least 128 bytes: x0..x7 from bytes 0..63 and d0..d7 from bytes 64..127, little-endian. After the call x0 and x1 are written back at 0 and 8, d0..d3 at 64..95, and the value is x0. A slice of fewer than 128 bytes, or F = 0, traps 3 before anything is called |
585
586What the called function does is outside the language: a wrong address, a wrong argument or a function that
587writes through a pointer it was given is not caught. `a64/DESIGN.md` s13 has the lowering.
588
589**Scheduler host words.** The affinity and priority words `cpuset` 236, `cpuget` 237, `cpunow` 238,
590`setprio` 239 and `getprio` 240 are on Radicle main (c106bae0, omc f4fa7951; OMEGESE s10 rows
5911071-1075). Their rows are in `hostwords.tsv` with class `sched` (not `cpu`: each has an i64 result),
592and ngrun refuses them by class: `cpuset`, `cpuget`, `setprio` and `getprio` as 115 process (they read
593or change scheduling state of the process), `cpunow` as 120 nondeterministic (the CPU a thread runs on
594may change between calls).
595
596### 7.12 Row table (the layout every reader uses)
597
598`tk`: token class (s6.4): P none, E effect, R reader, T terminator. `imm`: y when the op carries
599the 8-byte imm. `fix`: fixed operands after the token. `var`: y when a `u32 n` and n more operands
600follow. `ty`: r a result type (nonzero), o optional result (0 = none), p a parameter (no result
601value), 0 always 0.
602
603| op | name | tk | imm | fix | var | ty |
604|---|---|---|---|---|---|---|
605| 1 | `const` | P | y | 0 | - | r |
606| 2 | `select` | P | - | 3 | - | r |
607| 10..14, 16..18, 20..25 | `add sub mul div rem and or xor shl shr rotl rotr min max` | P | - | 2 | - | r |
608| 15, 19, 26, 27 | `neg not fsqrt fabs` | P | - | 1 | - | r |
609| 28 | `fmath` | P | y | 1 | - | r |
610| 30..35 | `eq ne lt le gt ge` | P | - | 2 | - | r |
611| 36 | `conv` | P | y | 1 | - | r |
612| 37 | `bitcast` | P | - | 1 | - | r |
613| 40 | `gpu.id` | P | y | 0 | - | r |
614| 41 | `shared` | P | - | 0 | - | r |
615| 42 | `load` | R | - | 2 | - | r |
616| 43 | `store` | E | - | 3 | - | 0 |
617| 44 | `sync` | E | - | 0 | - | 0 |
618| 45 | `shfl` | P | y | 2 | - | r |
619| 46 | `fma` | P | - | 3 | - | r |
620| 47 | `atom` | E | y | 3 | - | r |
621| 48 | `atomcas` | E | y | 4 | - | r |
622| 50 | `alloca` | E | - | 0 | - | r |
623| 51 | `fill` | E | - | 2 | - | 0 |
624| 52 | `gaddr` | P | y | 0 | - | r |
625| 53 | `len` | P | - | 1 | - | r |
626| 54 | `slice` | R | - | 3 | - | r |
627| 55 | `fload` | R | y | 1 | - | r |
628| 56 | `fstore` | E | y | 2 | - | 0 |
629| 57 | `fref` | P | y | 1 | - | r |
630| 58 | `vload` | R | - | 2 | - | r |
631| 59 | `vstore` | E | - | 3 | - | 0 |
632| 60 | `br` | T | - | 1 | y | 0 |
633| 61 | `cbr` | T | - | 3 | - | 0 |
634| 62 | `ret` | T | - | 0 | - | 0 |
635| 63 | `retv` | T | - | 1 | - | 0 |
636| 64 | `call` | E | - | 1 | y | o |
637| 65 | `trap` | T | y | 0 | - | 0 |
638| 66 | `exit` | T | - | 1 | - | 0 |
639| 67 | `launch` | E | - | 4 | y | 0 |
640| 70, 71, 72, 75, 76, 81 | `chk.add chk.sub chk.mul chk.divovf chk.shl chk.fuel` | E | y | 2 | - | 0 |
641| 73, 74, 77, 82 | `chk.neg chk.divz chk.shift chk.true` | E | y | 1 | - | 0 |
642| 78 | `chk.conv` | E | y | 1 | - | p |
643| 79, 80 | `chk.bounds chk.slice` | E | y | 3 | - | 0 |
644| 90 | `fact.true` | P | y | 1 | - | 0 |
645| 91, 92, 93 | `fact.range fact.inbounds fact.slice` | P | y | 3 | - | 0 |
646| 100 | `vsplat` | P | - | 1 | - | r |
647| 101 | `vextract` | P | y | 1 | - | r |
648| 102 | `vinsert` | P | y | 2 | - | r |
649| 103 | `vreduce` | P | y | 1 | - | r |
650| 104 | `mmald` | R | y | 4 | - | r |
651| 105 | `mmast` | E | y | 5 | - | 0 |
652| 106 | `mma` | P | y | 3 | - | r |
653| 110 | `host` | E | y | 0 | y | o |
654| 111 | `pool.grow` | E | y | 1 | - | r |
655| 112 | `pool.len` | R | y | 0 | - | r |
656| 113 | `pool.load` | R | y | 1 | - | r |
657| 114 | `pool.store` | E | y | 2 | - | 0 |
658| 115, 116 | `pool.read pool.write` | E | y | 3 | - | r |
659
660For the pool rows (111..116) the imm is the pool's global id, written on the wire exactly as the `gaddr`
661imm is (the in-memory form holds the handle, the writer subtracts 1, the reader adds 1; s14).
662
663Every op byte not in the table is UNKNOWN_OP. `shfl`, `mma`, `mmald`, `mmast` and `sync` are
664*convergent*: an optimizer never moves them into or out of a branch, and never duplicates them.
665
666### 7.13 Run-time pool ops (111..116)
667
668Each op names its pool by the global id in `imm` (a class 2 global, s5); none takes a pool, a REF or a
669SLICE as an operand and none returns one. Every op is **self-contained and checked**: the bounds test is
670part of the op, so none needs a `chk.bounds`, `chk.slice` or fact, and none is an access op of s8. The
671current length and base are read from the pool's descriptor *when the op executes*, after every operand
672has been evaluated, so storage that moved while an operand was being computed (a call inside an operand
673that grew the pool) is never used stale. `u64` is type id 5, `i64` type id 9, `i32` type id 8.
674
675| op | name | ty | imm | operands (after the token) | meaning |
676|---|---|---|---|---|---|
677| 111 | `pool.grow` | i64 | pool id | n (u64) | E. Make the pool at least n elements. Result 0: grown, or n <= length (no shrink); new elements are zero, old ones kept. -22: n times the element size is 2^63 bytes or more; the pool is unchanged. -12: the host refused (or, in ngrun, the 16 MiB budget would be exceeded); the pool is unchanged. Advances the token. |
678| 112 | `pool.len` | u64 | pool id | - | R. The current element count. Reads the token, does not advance it. |
679| 113 | `pool.load` | the pool's element type | pool id | i (u64) | R. Element i. Trap 3 (exit 103) if i is at or past the current length. |
680| 114 | `pool.store` | 0 | pool id | i (u64), v (element type) | E. Element i = v. Index and value are both evaluated, then the descriptor is resolved, then the bound is checked; trap 3 (exit 103) before any store when i is at or past the length. Advances the token. |
681| 115 | `pool.read` | i64 | pool id | fd (i32), off (u64), n (u64) | E. Host `read` of n bytes from fd into bytes off .. off+n-1 of the pool. Trap 3 (exit 103) unless off <= length and n <= length - off. Result: the byte count, or minus the Linux errno. Advances the token. |
682| 116 | `pool.write` | i64 | pool id | fd (i32), off (u64), n (u64) | E. As `pool.read`, writing those bytes to fd. |
683
684Rules ngcheck enforces (exit classes of s11, from `ck_tpool` and `ck_place`): the id must name a global
685(REF 24) of class 2 (TYPE 16); `pool.len` has type u64; `pool.grow` type i64 with a u64 operand;
686`pool.load` the element type with a u64 index; `pool.store` a u64 index and an element-typed value;
687`pool.read` and `pool.write` type i64, an i32 descriptor, u64 offset and count, and a *u8* pool (TYPE 16 for
688any other element type). Pool ops are refused in a kernel (EFFECT 22). A `gaddr` of a class 2 global is
689TYPE 16. A class 2 global whose type is not one of the ten native scalars is TYPE 16; a class above 2 is
690NONCANONICAL 13.
691
692Order and meaning of `pool.grow` results, taken from the implementations:
693
694- `-22` when n times the element size exceeds 2^63 - 1 bytes, which is the same as "reaches 2^63 or more"
695 (`ngrun` tests `n > 9223372036854775807 / size`). The pool is unchanged. The a64 path uses omc's helper
696 for this test. The boundary cases are `g8b.om` and `x-pool-widths.om`.
697- `-12` when the host refuses. Under `ngrun` the host is its own 16 MiB budget (s7.13.2).
698
699#### 7.13.1 Text and wire
700
701Text: `global @gN ELEMENT pool` (class 2; ELEMENT is the built-in scalar name, for example `u32`), and for the
702ops the imm prints as `@gN` right after the (optional) result type, as `gaddr` does:
703
704 global @g0 u32 pool
705 %2 %3 = pool.grow i64 @g0 %0 %1
706 %6 = pool.store @g0 %2 %4 %5
707 %7 = pool.load u32 @g0 %6 %4
708
709(See the complete fixture `tests/ir/x-pool.oir`.) `ngas` reads the word `pool` as
710class 2 and takes the ops' imm as `@gN`; `ngdis` prints them back. The wire version byte (9) and the tag are
711not changed by this addition; a reader built before it refuses class 2 (NONCANONICAL) and ops 111..116
712(UNKNOWN_OP).
713
714#### 7.13.2 Back ends and the reference interpreter
715
716- **`ngrun`** (reference interpreter) supports every pool op. Pool storage is kept apart from invocation
717 frames and the interpreted program's `alloca`/global memory, but both draw on **one combined live-storage
718 budget of 16 MiB** (the interpreter's established bound, kept as it was): `pool.grow` returns -12 when the
719 new bytes would not fit beside the storage already in use, leaving every existing pool intact, and a
720 frame allocation that no longer fits beside the pools is the existing exit 106 (trap 6). Growing a pool
721 moves the pools after it; no pool op yields an address, so no IR value can go stale. This 16 MiB is the
722 interpreter's own storage bound, not a rule of the language.
723- **`@ng a64` for Linux AArch64** (`@ng a64`, `@ng a64 split`) lowers every pool op. A pool is a 16-byte
724 descriptor (base, length) in the global area, as omc's slot is. The descriptor is loaded after the operands;
725 `pool.grow` emits an mmap/mremap helper whose instruction words the source copies from omc's `en_help`.
726- **The Mach-O (macOS) target is not supported for pools.** `@ng a64 macho` refuses any pool op explicitly
727 (an `a64: unsupported` line naming the op, exit 5, from `a6_die 5 5 op` in the source), and
728 does not guess an equivalent. It stays refused until a matched Darwin helper exists.
729- **Host only.** Pool ops are refused in kernels (EFFECT), and there is no GPU lowering.
730
731#### 7.13.3 Regression coverage
732
733`gate-ir.om` checks the `x-pool*` run pairs, malformed `r*-pool-*` inputs, byte/text round trips,
734and `o-pool` before and after optimization. Its pool mutants corrupt stored bytes, zero filling, and
735relocation of another pool. `front/gate-front-ir.om` compares the canonical source pool cases and
736`pool-widths-order.om` with omc. `a64/rgate.om` compares both register-save modes and exercises
737native bounds, descriptor-update and float-index mutants. Release receipts must bind the complete
738gate results to their source and compiler identities.
739
740Pool I/O retains the interpreter's host policy (s7.11), including descriptor ownership restrictions.
741A refused pool read/write names host word 53/54 in the existing diagnostic.
742
743## 8. Coverage (the memory safety rule)
744
745An access op A with token operand t is covered by a check or fact op C when
746
7471. C has the operands the table names (same SSA ids), and
7482. C dominates A (earlier in the same block, or in a block that dominates A's block), and
7493. when C is a check, its defined token is t or dominates t on the chain (so A reads memory only
750 after C has run; a fact has no token and needs only 2).
751
752| access | covered by `chk.bounds` or `fact.inbounds` on | with e |
753|---|---|---|
754| `load`, `store`, `atom`, `atomcas` | (r, i, e) | e defined by a `const` >= 1 |
755| `vload`, `vstore` | (r, i, e) | e defined by a `const` >= the lanes |
756| `mmald`, `mmast` | (r, i, e) | e is the op's own e operand |
757| `slice`, each `host` slice | `chk.slice` or `fact.slice` on (r, off, n) | - |
758
759`fload`, `fstore` and `fref` need no coverage: the field lies inside the STRUCT by the type table.
760A REF obtained from `gaddr`, `alloca`, `shared` or `fref` is still covered this way: the check is
761explicit even when the bound is a constant, and a pass replaces a proven check by a fact (s15). An
762uncovered access is UNCHECKED.
763
764The pool ops (s7.13) are the one family outside this table: each carries its own bounds test against the
765pool's current length, so they need no `chk.*` or fact and ngcheck demands none. A pool has no REF, so a
766check on a pool can never be separated from its access by a growth that moves the storage.
767
768## 9. Structural rules ngcheck enforces
769
7701. Every id names an existing object of the right kind: type, global, function, block, value (REF).
7712. Types per row (TYPE); writes need access 1; CONSTANT space is read-only; `tok` only where s4.1
772 allows it.
7733. Block 0 has no parameters (BLOCK_ARITY, at the block's offset) and is not a branch target
774 (REF); other blocks start with one `tok` parameter (BLOCK_ARITY). `alloca` and `shared` only in
775 block 0 (EFFECT).
7764. Every block reachable; SSA dominance (s6.2).
7775. Terminators (s7.1); `br` arity and types; `cbr` targets with exactly the token parameter.
7786. `retv` only in non-void functions with the result type; `ret` only in void ones.
7797. Kernel ops (`gpu.id shared sync shfl mmald mmast mma` and FRAG values) only in kernels; `host`,
780 `exit`, `launch` and `call` only outside them; a kernel's result is void; `launch`'s callee is
781 a kernel and `call`'s is not (EFFECT).
7828. The token chain (TOKEN, s6.4), check codes (CHECK_CODE), coverage (UNCHECKED), facts (FACT).
7839. Canonical fields (NONCANONICAL): reserved bits, `const` imm form, duplicate types, `ty` not 0
784 where the row says 0, flags, `order` of a non-scalar field, enumerations.
78510. Exactly one program entry (ENTRY, s6.1).
786
787## 10. Canonical text form (D3)
788
789`ngdis` prints, and `ngas` reads, exactly one text per unit. Byte-exact round trips are a gate:
790`ngdis(ngas(t)) == t` for every fixture text and `ngas(ngdis(b)) == b` for every assembled binary.
791ngas reads only canonical text: it refuses anything ngdis would not print (no comments, single
792spaces, no trailing spaces, every line ends with one LF, decimal numbers without leading zeros or
793`+`). ngas checks syntax and numbering only; semantic refusals are ngcheck's, so a fixture for any
794semantic class is canonical text. Example:
795
796```
797omegair 1
798type %t32 = vec i32 4
799type %t33 = array u8 64
800type %t34 = struct 16 u64@0:le i32@8:be
801type %t35 = ref edit host %t33
802type %t36 = slice view host u8
803type %t37 = frag a 16 8 16 f16
804type %t38 = array u8 5
805global @g0 %t33 zero
806global @g1 %t38 data 68656c6c6f
807fn @f0 flags 0 %1:i32 %2:i32 -> i32
808block ^0
809%3 = chk.add 1 %0 %1 %2
810%4 = add i32 %1 %2
811retv %3 %4
812end
813kernel @f1 flags 0 threads 256 1 1 subgroup 32 -> void
814block ^0
815%1 = gpu.id u32 0
816ret %0
817end
818export @f2 flags 0 -> i32
819block ^0
820%1 = const i32 0
821retv %0 %1
822end
823```
824
825- Header line `omegair 1`. Then the type table, the globals, the functions, in wire order.
826- Types: built-ins by name (`void bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 f16 bf16 e4m3 e5m2
827 tok`), every other id (table types and unnamed or absent ids alike) as `%tN` with N the type
828 id; a named built-in is never spelled `%tN`. `vec E L`, `array E C`, `struct SIZE` then each
829 field as `TYPE@OFFSET:ORDER` (`le`, `be`), `ref ACCESS SPACE T`, `slice ACCESS SPACE E`,
830 `frag ROLE M N K E`; access `view`/`edit`; space `host global shared constant private`; role `a`
831 `b` `c`. Type line N is `type %tN = ...` with N = 32 + its index.
832- `global @gN TYPE zero` (class 0) or `global @gN TYPE data HEX` (class 1, lowercase hex of every
833 byte). The data length is the byte size of TYPE (a scalar's width; VEC lanes x element; ARRAY
834 count x element; STRUCT its SIZE; 0 for anything else, printed as `data` with no hex).
835- Function line: `fn` (kind 0), `kernel` (kind 1) or `export` (kind 2), `@fN`, `flags N`, kernel
836 `threads X Y Z subgroup S`, each parameter as ` %N:TYPE` (value ids from 1; the entry token %0 is
837 implicit), then ` -> ` and the result type.
838- `block ^N` then each parameter as ` %N:TYPE`.
839- Op line: the defined values, if any, as `%N = ` or `%T %V = ` (token then result), the mnemonic,
840 then `ty` when the row's ty column is r, o or p (`void` for ty 0), then imm when the row has one,
841 then the operands. imm is decimal, except `const` of a scalar type: signed decimal for signed
842 ints (`-0` is not canonical), `true`/`false` for bool, decimal for unsigned, and `0x` with exactly
843 2, 4, 8 or 16 lowercase hex digits of the bits for floats; `const` of a non-scalar `ty` prints
844 the imm in decimal. `gaddr` prints `@gN`. Operands: `%N` values, `^N` blocks, `@fN` functions;
845 a variadic op's `n` is the operand count minus the row's fixed operands.
846- `end` closes the function.
847
848Ids are printed as stored, in range or not, so every semantic refusal has a text fixture. What the
849text cannot spell, `ngdis` refuses with the s11 code and `ngdis: refused class C at OFFSET` on
850stderr: MAGIC, VERSION, TRUNCATED, TRAILING, UNKNOWN_OP, LIMIT (below), IO, and NONCANONICAL for an
851enumeration outside its set (type kind, access, space, field order, frag role, global class,
852function kind), a nonzero `ty` on a row whose ty column is 0, or a `const` imm that is not canonical
853for its scalar type. Its text is complete only on exit 0: a refusal found before 1 MiB of text
854leaves stdout empty, one found later leaves the text already written. `ngas` refuses
855non-canonical text with `ngas: syntax error at line N` and exit 3 (out of order or misnumbered type,
856global, function, block or value ids; the wrong number of defined values for the row and `ty`; a
857fixed-operand count that differs from the row; a `const` outside its type; a global's data length),
858input or output over 16 MiB with exit 23, unreadable input with exit 27.
859
860**Text tool capacities.** Both text tools hold what the text can spell, so their limits are the
861table sizes, not ngcheck's semantic limits: input over 16777216 bytes is LIMIT (ngdis reads one
862byte past the buffer: more input is `ngdis: refused class 23 at 16777216`, a read error class 27 at
863the bytes read); more than 65536 types, globals, functions, blocks in one function, or parameters
864of one function or block is LIMIT, `ngdis: refused class 23 at` the count's offset, checked before
865the entries, and `ngas: limit at line N` (the line of the first item over) with exit 23. The
866parameter limit stays 65536 in the text tools so that ngcheck's 64-parameter LIMIT keeps a text
867fixture.
868
869`seed/ng/tests/ir/` holds the fixtures: canonical text (`NAME.oir`), and the `cases` file that
870`seed/ng/gate-ir.om` runs: text cases with their ngcheck class and offset, ngas syntax refusals,
871byte mutations of assembled fixtures for what text cannot spell (MAGIC, VERSION, TRUNCATED,
872NONCANONICAL, TRAILING, UNKNOWN_OP, counts over s12), each judged by ngcheck and ngdis alike and by
873`ng ir-copy` as s14 states, and inputs the gate generates at the capacities (16777216 bytes and one
874more, 65537 types, globals, functions, blocks and parameters).
875Run pairs
876(`x-NAME.oir` with `x-NAME.om`, the same program in Omega) are the D9 differential of this
877document's semantics: `seed/ng/ngrun.om`, the reference interpreter of s7, runs the ΩIR, omc
878compiles and runs the Omega, and exit status, stdout and stderr must be equal, traps at the exact
879boundaries included (overflow at 2^63, fuel at exactly 1e6 passes, index == len, MIN div -1,
880shift by the width, a conversion one past the range and one at the bottom of it, a signed shift
881left that reaches the minimum). What Omega cannot state (u64 checked add and mul, `chk.bounds` with
882e = 0, wrapping narrow `neg`, the trap 6 depth) the gate checks on ngrun alone (N cases).
883Random programs (`seed/ng/ngrand.om`, the D9 differential source for back ends): `ngrand SEED`
884writes a unit built with `src/ir.om` from a byte tape that SEED fills; every tape gives a unit
885ngcheck accepts (typed SSA, one token chain, checks with their codes, diamonds joined by block
886parameters, counted loops under `chk.fuel`, calls to lower helpers, i64 memory under `chk.bounds`,
887host write), and byte 0 is always the smallest choice, so `ngrand shrink SEED STATUS OUT CMD...`
888minimizes a unit by deleting and zeroing tape bytes while the predicate CMD exits STATUS. The gate
889runs seeds 1..1000 (ngcheck's whole ACCEPT line, `ngas(ngdis(b)) == b`, ngrun ends cleanly), one
890shrink with ngrun as the predicate, and a mutant ngrand that drops one token edge, which ngcheck
891must refuse TOKEN. ngrun has no second oracle on these units: a back end diffing against ngrun is
892the differential, and its disagreements judge both.
893
894**Reference-interpreter float checks.** The supported scalar f32/f64 subset includes bitcast,
895nearest-even and toward-zero conversions (imm 0, 1, 4, 5 for float destinations), and fused
896FMA. Integer destinations still require imm 0: they already truncate toward zero and saturate;
897the former unsupported rounding-mode defect concerned float destinations, not float-to-int.
898Bitcasts retain the entire declared width, including the sign bit and NaN payload. FMA is
899one operation at the declared precision, not a widened or multiply-then-add evaluation.
900
901The IR gate builds `tests/ir/float-oracle.om` with the pinned seeded omc and runs it natively.
902That independent executable emits a unit containing expected raw-bit checks computed with
903native omc bitcasts, conversions and FMA. It links the IR writer, never ngrun. For each float
904width it checks 18 signed special/boundary bit patterns (zeros, infinities, quiet and signaling
905NaNs with payloads, minimum and maximum subnormals, minimum normals and maximum finite values)
906and 1024 deterministic random patterns. It checks float-to-int for all eight integer widths,
90716 probes at each destination's boundaries, integer-to-float in every defined mode at integer
908range and precision boundaries, and f64-to-f32 in every defined mode. The native toward-zero
909f64-to-f32 reference decodes the sign, exponent and significand as integers; it does not use
910ngrun's predecessor-of-nearest algorithm. A separate mutant removes that predecessor step.
911NaN conversions are
912compared by NaN classification; bitcasts and FMA compare raw bits. FMA includes three explicit
913witnesses and the same special/random sweep: two fused-versus-unfused cases and one f32 case
914(`0x3f7ff001 * 0x33800800 + 1`, exactly 1 + 2^-24 + 2^-60) where an f64 FMA narrowed to f32
915double-rounds to `0x3f800000` instead of `0x3f800001`. The oracle exits 3 unless native omc
916reproduces the exact Wolfram-checked bits of all three. The native oracle prints
917its measured check count and finite fused-versus-unfused difference count on stderr.
918`tests/ir/intcv-oracle.om` independently exercises all 16 unsigned-to-signed width pairs at
919eight boundary inputs each (128 native comparisons), including source MAX and MAX-1. Another
920256 native comparisons check f32/f64 `chk.conv` at 16 boundary probes for each integer type,
921using an independent integer decoder of the float sign, exponent and significand rather than
922ngrun's float comparisons. It emits
923the IR before performing the equivalent checked native conversion, so its native exit is the
924expected IR exit (0 or trap 5). The gate compares exit, stdout and stderr. Sign-bit erasure,
925RTZ refusal, unfused f32 and f64 FMA, f32 FMA widened to f64 then narrowed, and the former
926unsigned-to-signed check each have a separately killed interpreter mutant. These are host semantic
927checks, not hardware qualification
928of either NG back end; the integer random-IR generator still has no second independent oracle.
929
930## 11. Refusal classes and ngcheck exit codes
931
932`ngcheck` reads binary ΩIR on stdin. Accept: exit 0 and one stdout line
933`ACCEPT <sha256 hex> fns=N blocks=N ops=N`. Refusal: no stdout, exit code below, and one stderr
934line `ngcheck: <CLASS> at <byte offset>` (offset of the field, op or record at fault, decimal).
935The first fault ends the run. Phase 1 reads the unit front to back and checks every rule that needs
936only the record at hand: header, type table and globals completely (a type-table or global fault
937is reported at its entry's offset), function and block headers, op rows and every count against
938s12 (at the count's offset); then the program entry (ENTRY: at the function count when there is
939none, at the second entry's record otherwise). Phase 2 checks each function in order: terminators
940(UNTERMINATED), branch targets and their arity (REF, BLOCK_ARITY), reachability (UNREACHABLE),
941then each op in block and op order: operand ids, definitions and the token (REF, USE_BEFORE_DEF,
942DOMINANCE, TOKEN), its `ty` against the row, placement (EFFECT), codes and origins (CHECK_CODE,
943NONCANONICAL), typing (TYPE, and BLOCK_ARITY for `br` argument types), then coverage and facts
944(UNCHECKED, FACT). Op faults are reported at the op's offset, block faults at the block's,
945function faults at the function record's.
946
947| exit | class | meaning |
948|---|---|---|
949| 10 | MAGIC | first 7 bytes are not `OSC1IR\0` |
950| 11 | VERSION | version byte is not 9, or the tag is not exact |
951| 12 | TRUNCATED | input ends inside a field |
952| 13 | NONCANONICAL | a reserved bit or unused field nonzero, a duplicate type, a `const` imm not in canonical form, an enumeration outside its set |
953| 14 | TRAILING | bytes after the last function |
954| 15 | UNKNOWN_OP | an op byte with no row |
955| 16 | TYPE | an operand, result or parameter type breaks its row |
956| 17 | USE_BEFORE_DEF | a value used before its definition in the same block, or an id past the function's values |
957| 18 | DOMINANCE | a value used in a block its definition does not dominate |
958| 19 | BLOCK_ARITY | `br` arguments differ from the target's parameters; a `cbr` target with other than the token parameter; a non-entry block without its token parameter; an entry block (block 0) with parameters |
959| 20 | UNTERMINATED | a block without a terminator at its end, or a terminator before its end |
960| 21 | CHECK_CODE | a check without its exact trap code, or `trap`/`chk.true` code outside 1..14 |
961| 22 | EFFECT | an op in a function kind or block that does not allow it (s9 rules 3 and 7), an unknown host word |
962| 23 | LIMIT | a count over s12 |
963| 24 | REF | an id names no object of its kind; a branch to block 0 |
964| 25 | UNCHECKED | a memory access or slice without coverage (s8) |
965| 26 | UNREACHABLE | a block not reachable from block 0 |
966| 27 | IO | standard input could not be read |
967| 28 | TOKEN | a token used outside operand 0 of an E, R or T op, an E or T op not using the current token, a reader using a token after the current one |
968| 29 | FACT | an origin 0 fact without its dominating check (s7.10) |
969| 30 | ENTRY | no program entry, or more than one (s6.1, D11) |
970
971## 12. Limits (implementation limits of the v1 tools)
972
973| item | limit |
974|---|---|
975| input bytes | 16777216 |
976| types | 65536 |
977| struct fields, whole module | 65536 (64 per struct) |
978| globals | 65536 (class-1 data within the input limit) |
979| functions | 65536 |
980| parameters (function, block) | 64 |
981| blocks per function | 65536; whole module 1048576 |
982| ops per function | 1048576; whole module 4194304 |
983| values per function | 2097152 |
984| `call`/`host`/`launch` arguments | 64 |
985
986A count above its limit is LIMIT (exit 23) at the count's offset, checked before reading what it
987counts. ngcheck keeps every number of this table; the text tools use the capacities of s10 (65536 for
988every table, parameters included), which are never below them. `src/ir.om` (ng, ngrun, ngrand) keeps
989them too, but two (no-caps arena, 2026-11-11): its input is region 0 of the arena (`ar_m`, 128 MiB), so
990ng and ngrun read a payload of any size the arena holds (past that, LIMIT at the bytes read, with ng's
991ng-use record), and its globals and their data are arena regions, so ng reads and writes a module of more
992than 65536 globals (ngrun keeps its own 65536-entry address table: more is LIMIT at offset 0). The ΩIR
993builder (front-ir, ngrand, the oracles) refuses a table it would fill with `ng: refused class 23 (IR.md s12
994table full while building)` and exit 23, never an index past it (`ir_lim`).
995
996## 13. Mapping from Omega (for `src/front.om`)
997
998`t` is the current token; each E op makes the next one.
999
1000| Omega | ΩIR |
1001|---|---|
1002| `global P T *` (run-time pool) | a class 2 global of element type T (s5); the front end gives it a private name kind and never a REF |
1003| `len P` | `pool.len` |
1004| `get P i` | the index is evaluated, then `pool.load` (its own bound test, trap 3) |
1005| `put P i v` | index, then value, then `pool.store`; the descriptor is read after both |
1006| `r = enlarge P n` | n (u64) evaluated, then `pool.grow`; its i64 result is r |
1007| `read fd P off n`, `write fd P off n` | `pool.read`, `pool.write` (u8 pools only), no separate `chk.slice` |
1008| signed `add x y` | `t1 = chk.add 1 t x y`, then `add` |
1009| `div a b` signed | `chk.divz 2 b`, `chk.divovf 1 a b`, then `div` |
1010| `rem a b` | `chk.divz 2 b`, `rem` |
1011| `shl a b` signed | `chk.shift 7 b`, `chk.shl 1 a b`, `shl` |
1012| `uchar x` (narrowing) | `chk.conv u8 5 x`, `conv u8 x` |
1013| `get A i` | `chk.bounds 3 A i e1` (e1 a `const u64 1`), then `load` reading the new token |
1014| `while c bound N` | header block with counter k; evaluate c; on true `chk.fuel 4 k N` then the body (the condition before the fuel check, as `omc.om` 9469-9505) |
1015| `requires c` (om2, checked build) | `chk.true 9 c` at entry, then `fact.true 0 c` |
1016| `requires c` (unchecked build) | nothing: no check, no fact (D2c) |
1017| `trap N` | `trap N` |
1018| host word | `chk.slice` on each slice, then `host` |
1019| Omegese GPU `kernel` | kind 1, `gpu.id`, `shared`, `sync`, `shfl`, `fma`, `fmath` FAST |
1020
1021## 14. In-memory ΩIR: `seed/ng/src/ir.om` (D1b)
1022
1023`ir.om` holds ΩIR in global tables and owns the one binary reader and writer of the `ng` binary.
1024Its first code line is `om2` (D11), so the whole `ng` unit is om2: every lane file compiles as
1025part of an om2 unit (`at` is reserved there, error 16).
1026Stages build and read these tables directly; nothing is serialized between stages. Names follow
1027D1b: functions `ir_*`, globals `i_*` (at most 8 bytes). Other lanes read the tables and call the
1028`ir_*` functions; they never write a table directly.
1029
1030**Handles.** Every handle is a `uint`, and 0 means none. Types use their wire type ids (s4).
1031Globals, functions, blocks, ops and values are numbered from 1 in creation order across the whole
1032module. The writer turns handles into wire ids: global g is wire id g-1, function f is f-1, a block
1033is its position in its function's block list, and values are numbered by s6.2 (`ir_num`).
1034
1035**Tables** (index = handle; counters in `i_n`):
1036
1037| table | contents |
1038|---|---|
1039| `i_n` | counters: 0 table types, 1 struct fields, 2 globals, 3 functions, 4 blocks, 5 ops, 6 values, 7 operand slots, 8 global data bytes |
1040| `i_tk i_t1 .. i_t5` | type id -> kind (s4.2, 0 for built-ins) and fields in wire order: VEC elem, lanes; ARRAY elem, count; STRUCT size, nfields, first field; REF target, access, space; SLICE elem, access, space; FRAG role, m, n, k, elem |
1041| `i_xty i_xof i_xor` | struct field -> type, offset, order |
1042| `i_gty i_gcl i_gd0 i_gdat` | global -> type, class, first data byte in the `i_gdat` pool |
1043| `i_fk i_ffl i_frs i_fnp i_ftk i_fp1 i_fb1 i_fbt i_fnb i_ftx i_fty i_ftz i_fsg` | function -> kind, flags, result type, parameter count, entry token value, first parameter value, first and last block, block count, kernel threads x, y, z, subgroup |
1044| `i_bf i_bnx i_bp1 i_bnp i_bo1 i_bot i_bno` | block -> function, next block, first parameter value, parameter count, first and last op, op count |
1045| `i_oop i_oty i_oim i_ona i_oa0 i_ob i_onx i_otk i_ors` | op -> opcode, ty, imm (`ulong`), operand count (token included), first slot in `i_arg`, block, next op, defined token value, defined result value |
1046| `i_arg` | operand slots: value handles, block handles (`br`, `cbr`), function handles (`call`, `launch`) |
1047| `i_vty i_vk i_vo i_vnx i_vno` | value -> type, kind (0 entry token, 1 function parameter, 2 block parameter, 3 op token, 4 op result), owner (function, block or op), next parameter in its list, wire id (after `ir_num`) |
1048
1049**Builder** (each returns the new handle or type id; capacity overrun traps 3 at the table, the
1050front end refuses earlier):
1051
1052| call | effect |
1053|---|---|
1054| `ir_init` | empty module |
1055| `ir_tvec e l`, `ir_tarr e c`, `ir_tref t a s`, `ir_tslc e a s`, `ir_tfrg r m n k e` | the type id, creating it once (equal types are one id) |
1056| `ir_tsb size`, `ir_tsf t off ord`, `ir_tse` | begin a struct, add a field, finish: the type id (deduplicated) |
1057| `ir_glob t cls`, `ir_gbyt g b` | a global; append one data byte to a class-1 global |
1058| `ir_fnew kind flags res` | a function, with its entry token value |
1059| `ir_fpar f t`, `ir_fker f x y z sg` | add a parameter value; set a kernel's threads and subgroup |
1060| `ir_blk f` | append a block; every block after the first gets its `tok` parameter 0 at once |
1061| `ir_bpar b t` | add a block parameter value |
1062| `ir_btok b`, `ir_ftok f` | a block's token parameter; a function's entry token |
1063| `ir_op b op ty imm n` | append an op with n operand slots (token included); defines its token and result values by the row (s7.12) |
1064| `ir_set o k h` | set operand slot k |
1065| `ir_res o`, `ir_otok o`, `ir_arg o k` | the op's result value, defined token, operand k |
1066| `ir_num f` | fill `i_vno` for f by s6.2; returns f's value count |
1067
1068**Reader and writer**: `ir_read off stop` parses `i_in[off..stop)` into empty tables and returns 0
1069or a refusal class of s11, with `ir_badat` the absolute offset in `i_in`. It refuses what it needs
1070to build sound tables (classes 10..15, 23, and REF/USE_BEFORE_DEF/BLOCK_ARITY/UNTERMINATED/TYPE
1071where an id, a count or a global's data size cannot be resolved) and leaves every semantic rule to
1072ngcheck. `ir_wr` writes the tables to `i_out` and returns the byte count. `ir_wr` after `ir_read`
1073reproduces the input bytes exactly for every unit `ir_read` accepts. The gate runs `ng ir-copy` on
1074every fixture unit, every byte mutation and the generated binaries (full, over, types): where
1075ngcheck refuses with a structural class (MAGIC, VERSION, TRUNCATED, TRAILING, UNKNOWN_OP, LIMIT,
1076IO) ng must print the same class and offset with empty stdout, except where that refusal is a LIMIT of
1077s12 that ng's reader no longer has (the input size and the globals count, no-caps arena): there ngcheck
1078keeps its LIMIT and the gate row pins the verdict of this reader (the class of s11 and the offset) for ng
1079(for example `M a-fib 31 1 23 28 13 42`: a globals count of 16777216; the reader resolves a global's type
1080only for class 1, so it reads on to the first class byte outside s5, NONCANONICAL at that record). Otherwise
1081ng must give the bytes back exactly or, where ngcheck refuses, refuse with a class of s11 and empty stdout.
1082In the tables a `gaddr` imm, and the imm of each pool op 111..116 (s7.13), is the global's handle (the writer subtracts 1, the reader adds 1); every other
1083imm is the wire value.
1084
1085Register budget: omc gives a function 16 registers, and each global array read in one expression
1086costs one, and an expression in a loop's or a branch's head holds its registers to the block's end. Keep
1087table reads to two or three per statement (the `ir_*` code shows the pattern); an arena table read is
1088three (`get ar_m add get ar_rb R i`), so a crowded line reads through `ar_w` / `ar_c` / `ar_u`.
1089
1090`main.om` reads the first input line (the mode, at most 63 bytes and its newline) apart, so the
1091payload after it is region 0 of the arena (`ar_rdin`) from offset 0, as large as the arena holds.
1092`@ng ir-copy` reads the ΩIR binary payload and writes it back (reader/writer round trip). A refusal
1093prints `ng: refused class C at OFFSET`, offset in the payload, empty stdout, and exits C: a payload the
1094arena cannot hold is class 23 at the bytes read (then the ng-use record), an unreadable one class 27; an unknown mode is `ng:
1095unknown mode` and exit 2. `@ng opt` reads the payload like `@ng ir-copy`, runs the optimizer of
1096`src/opt.om` (s15.1) and writes the result; `@ng opt-count` runs the same passes and prints one line
1097of counts instead of the unit. Stage lanes add their modes (`@ng dump-ir <stage>` after the front end or
1098a pass, `@ng ingest-ir <stage>` before a back end) beside their code.
1099
1100## 15. What a pass may do to a check (D7)
1101
1102A check is never moved above an earlier effect, an earlier trap or a loop that may run zero times;
1103the token chain makes the first two visible to the validator, and the differential gate with
1104zero-trip mutants guards the third. A pass removes a check in exactly two ways:
1105
11061. **Delete** a check that a dominating fact or check proves cannot fail, replacing it by the fact
1107 (`chk.bounds` by `fact.inbounds` with the pass's origin), so the coverage rule still holds.
11082. **Version** a loop: a guard on the loop entry tests that every index stays in range and the trip
1109 count stays below the fuel bound; the fast copy carries facts in place of the checks, and the
1110 original loop, checks intact, runs when the guard fails.
1111
1112Every pass that does either has mutants that attack trap order and zero-trip hoisting (D9).
1113
1114### 15.1 Loop-invariant code motion, bounds-check elimination and rotation (`src/opt.om`, D16)
1115
1116`src/opt.om` (unit order ir, opt, main; functions `op_*`) rewrites the `ir.om` tables in place,
1117per function:
1118
11191. **Preheaders.** A natural loop is a header h with a back edge u -> h where h dominates u
1120 (Cooper, Harvey and Kennedy dominators over reverse postorder); its blocks reach a latch without
1121 passing h. When h has exactly one predecessor outside the loop and it ends in `br h`, that block
1122 is the preheader; otherwise a new block with h's parameter types, ending in `br h` with them, is
1123 placed before h and every outside predecessor (`br` or `cbr`) branches to it instead. A new block
1124 is added only within the limits of s12 (blocks, ops and values per function and per unit); a loop
1125 that would need one past them keeps none, and LICM leaves that loop alone.
11261a. **PHI.** A block parameter other than the token whose arguments, over every `br` that targets
1127 its block, are one value v or the parameter itself is replaced by v: its uses take v, and it
1128 leaves the block's parameter list and each such `br` its argument (a block with a parameter
1129 past its token is reached only by `br`, s9 rule 5). v dominates the block (s6.2): every block is
1130 reachable (s9 rule 4), and on any path from block 0 the edge that first enters the block comes
1131 from a predecessor the block does not dominate, so that `br` passes v, not the parameter, and v
1132 dominates its end. One parameter per round, to a fixed point. A value an outer loop carries
1133 unchanged through an inner loop's header is such a parameter, so LICM then sees its uses as
1134 invariant. PHI, BCE and LICM repeat in that order while one of them changes something: LICM's
1135 merging can give two `br` arguments one value only after PHI ran (ngrand seed 523 kept a
1136 redundant parameter after one round). Fixture `o-phi` (one parameter stays, one goes); a PHI
1137 that kept a parameter's first argument even where another `br` passes a different one changes
1138 its run (exit 16 for 18).
11392. **BCE** (pass origin 1, item 1 of s15). A `chk.bounds r i e` is replaced in place by
1140 `fact.inbounds 1 r i e` when e is a const >= 1, r is a REF to an ARRAY of count L, and i < X is
1141 known where the check runs with X - 1 + e <= L: i is a const (X = i + 1), or a block on the
1142 check's dominator path has one predecessor, ending in a `cbr` on `lt`/`le`/`gt`/`ge` of i and a
1143 const, so that block runs only after the test proved i < X. A `chk.divz` of a nonzero const is
1144 deleted. Uses of a deleted check's output token take its input token. ngcheck judges the fact's
1145 placement, not its truth (s7.10); the gate's BCE mutant (X - 1 + e <= L + 1) makes the
1146 boundary fixture `o-bce1` (L = 4, i < 5) write past the array, and the run differs.
11473. **LICM**, innermost loop first. An op moves to the end of the preheader when it is class P
1148 (s6.4), defines a value, is not `shared`, is not convergent (`sync`, `shfl`, `mmald`, `mmast`,
1149 `mma`, refused by number: s7.12 forbids moving them into or out of a branch, and the loop body
1150 is the branch of the header's test; the gate's convergent mutant drops `shfl` from that list
1151 and the pinned `o-shfl` row differs), and every
1152 operand is defined outside the loop. P ops
1153 are total (s7.3: division by zero gives 0), so running one on a path where the loop runs zero
1154 times changes nothing. Checks, loads, stores, calls, host words, facts and terminators never
1155 move: they carry the token chain, and that is where coverage (s8) and trap order (above) live.
1156 An op equal to one already in the preheader (op, type, imm, operands) is dropped and its uses
1157 take the earlier value.
11584. **ROT.** When the header ends in `cbr` with one target inside the loop and one outside, and the
1159 one latch ends in `br h`, the header is placed right after the latch. Block order changes no
1160 value (uses are judged by dominance, s6.2); it is the layout a back end emits, so the back
1161 branch falls through into the test and a pass of the loop takes one conditional branch.
1162
1163The gate runs every O/L fixture and every Q seed through `@ng opt`: ngcheck's whole ACCEPT line on
1164the output, the text round trip, ngrun before and after equal, and a second run that finds nothing
1165to move; each O/L line also pins the `@ng opt-count` row of its input (`o-shfl`: a kernel loop whose
1166invariant `shfl` stays put).
1167Its mutants hoist a load past the loop's stores and checks past their guard (both refused
1168by ngcheck: the hoisted op keeps an in-loop token, s6.4), merge preheader ops of different imm
1169(a run differs) and let BCE delete a check one element past its proof (a run differs).