Commit a7275ef4

a7275ef4e912Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · +1 added

Description

docs: analyze ↔ codegen IR contract

The split landed in #416 but didn't document the IR file format or the per-ivar contract between spinel_analyze.rb and spinel_codegen.rb. New doc covers:

  • File format (line-oriented, percent-encoded payloads).
  • Tag reference (INT / STR / SA / IA / T / NM / NB / SN / ST).
  • Pipeline contract: what analyze populates in analyze_phase, what codegen consumes in load_analysis_buf, what stays in codegen by design (block-body infer, emit-site-local helpers).
  • Per-ivar contract grouped by category (counters, feature-need flags, live-method tables, top-level methods, classes, constants, modules, FFI, regexp, misc).
  • Per-AST-node records (T cache, NM/NB rewrite ports, SN/ST scope-decl precompute pairs).
  • Loading-order constraints (@nd_count must precede per-node records).
  • Statistics from spinel_codegen.rb's IR (~101K T records, ~370 SN/ST pairs, ~1.5 MB).
  • Gotchas: length-prefixed split, percent-encoding round-trip, the O(N²) buf+= trap that previously blew the heap to 60 GB, block-body-cache-empty-by-design, 4-way fixpoint.
  • A checklist for adding a new ivar.

Refs #416

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
a7275ef4e912
Parent
f762cee91ea6

docs/ANALYZE-IR.mdaddedView file

1+# Analyze ↔ Codegen IR
2+
3+The Spinel compiler runs in three stages, each as a separate binary:
4+
5+```
6+.rb ──[spinel_parse]──▶ .ast ──[spinel_analyze]──▶ .ir ──[spinel_codegen]──▶ .c
7+```
8+
9+`spinel_analyze` produces `.ir`; `spinel_codegen` consumes it. This file
10+documents that contract: the file format, every tag, every ivar that
11+crosses the boundary, and the constraints either side relies on.
12+
13+The IR is the only artefact the two binaries share. They do not share
14+heap state, do not share an in-memory `Compiler` instance, and do not
15+re-derive each other's results. If a piece of analysis state is not in
16+the IR, codegen does not have it.
17+
18+## File format
19+
20+Plain UTF-8 text, line-oriented (`\n`-terminated). The first line is the
21+literal version stamp:
22+
23+```
24+SPINEL-IR v1
25+```
26+
27+Every subsequent line is a single record:
28+
29+```
30+<tag> <name-or-nid> [<count>] <payload>
31+```
32+
33+Fields are space-separated. Payload encoding rules below depend on tag.
34+A line is one whole record — newlines never appear inside payload values
35+(they are percent-encoded).
36+
37+### Tags
38+
39+| Tag | Shape | Carries |
40+|------|--------------------------------|--------------------------------------------------------------------------|
41+| `INT`| `INT @ivar <integer>` | scalar integer ivar (counters, feature-need flags) |
42+| `STR`| `STR @ivar <encoded-string>` | scalar string ivar (`@cls_meth_live`, `@cls_cmeth_live`) |
43+| `SA` | `SA @ivar <count> <pipe-strs>`| length-prefixed `Array<String>` (every analysis-derived parallel array) |
44+| `IA` | `IA @ivar <count> <csv-ints>` | length-prefixed `Array<Int>` (body ids, sizes, offsets, flags) |
45+| `T` | `T <nid> <encoded-type>` | per-AST-node inferred type (the cache that lets codegen skip `infer_type`) |
46+| `NM` | `NM <nid> <encoded-name>` | per-AST-node `@nd_name` override (`__sp_ieval_<N>` rewrites) |
47+| `NB` | `NB <nid> <int>` | per-AST-node `@nd_block` override (rewritten ieval call sites) |
48+| `SN` | `SN <nid> <pipe-strs>` | per-scope local-decl names (one entry per scope body) |
49+| `ST` | `ST <nid> <pipe-strs>` | per-scope local-decl types (paired with SN) |
50+
51+`INT`, `STR`, `SA`, `IA` mirror compiler-instance state by ivar name.
52+`T`, `NM`, `NB`, `SN`, `ST` are sparse per-node records — they only emit
53+for nodes whose value differs from the default, so codegen fills the
54+rest with the default at load time.
55+
56+### Encoding
57+
58+Strings (the payload of `STR`, the elements of `SA` / `T` / `NM` / `SN`
59+/ `ST`) are percent-encoded for the four characters that would
60+otherwise collide with the line-and-pipe split:
61+
62+| Char | Encoded |
63+|--------|---------|
64+| space | `%20` |
65+| `\n` | `%0A` |
66+| `\r` | `%0D` |
67+| `\t` | `%09` |
68+| `%` | `%25` |
69+| `\|` | `%7C` |
70+
71+`SA` payloads are `<count> <e1>|<e2>|…|<en>`. The leading `<count>`
72+distinguishes `[]` (count 0, body empty) from `[""]` (count 1, body
73+empty after pipe split) — both serialise to identical bodies, so the
74+loader uses the count to pad with empty strings.
75+
76+`IA` payloads are `<count> <e1>,<e2>,…,<en>`. Same count guarantee.
77+
78+## Pipeline contract
79+
80+### What analyze populates
81+
82+`Compiler#analyze_phase` (spinel_analyze.rb) runs to fixpoint:
83+
84+1. `collect_all` — walks the AST, registers classes, methods, modules,
85+ constants, ivars, FFI declarations.
86+2. `infer_main_call_types` / `infer_function_body_call_types` /
87+ `infer_class_body_call_types` / `infer_ieval_body_call_types` —
88+ per-scope call-site widening.
89+3. `detect_poly_locals`.
90+4. Iterative loop (≤ 4 rounds): `infer_all_returns`,
91+ `infer_*_call_types`, `infer_ivar_types_from_writers`,
92+ `infer_param_array_type_from_body`,
93+ `narrow_param_types_from_body_method_calls`,
94+ `narrow_param_hash_types_from_body_writes`, `detect_poly_params`.
95+ Loop terminates when `inference_signature` (a fingerprint over
96+ return-types, ivar-types, param-types, cmeth-ptypes) is unchanged.
97+5. `fix_nil_ivar_self_refs`, then re-run inference passes.
98+6. `refine_all_module_ivar_types` (uses now-stable param types to
99+ refine module-ivar hash / array specialisation), then re-run.
100+7. `fix_lambda_return_types`.
101+8. `pre_detect_bigint`, `detect_features`.
102+9. `detect_value_types`, `recalc_needs_gc`, `collect_sym_names`,
103+ `scan_toplevel_ivars`, `compute_live_cls_methods`,
104+ `compute_live_instance_methods`.
105+10. Sets `@analysis_frozen = 1`.
106+11. `precompute_all_scope_decls` — walks every method / cmeth / ieval /
107+ main scope, runs the full multi-pass local-decl refinement (used
108+ to be re-derived in `emit_main` and `declare_method_locals`),
109+ stores the result in `@nd_scope_names[bid]` /
110+ `@nd_scope_types[bid]` (pipe-joined per body).
111+12. `annotate_all_node_types` (`walk_and_cache`) — post-order walks
112+ every reachable AST node, calls `infer_type`, fills
113+ `@nd_inferred_type[nid]`. Targets non-block-body nodes (block
114+ iteration scope is iterator-specific and resolved at emit time).
115+
116+After step 12 the compiler dumps state via `dump_analysis_buf`.
117+
118+### What codegen consumes
119+
120+`spinel_codegen.rb`:
121+
122+1. Parses the AST file (same `read_text_ast` as analyze; fresh
123+ `Compiler` instance with empty tables).
124+2. Calls `load_analysis_buf` on the IR to overwrite scalar / array
125+ ivars and per-node caches.
126+3. Calls `generate_code`, which assumes the compiler is in the same
127+ "post-analysis" shape analyze left it in:
128+ - `@cls_is_value_type`, `@needs_gc`, `@sym_names`,
129+ `@toplevel_ivar_*`, `@cls_meth_live`, `@cls_cmeth_live` are
130+ pre-populated. `generate_code` does not re-run
131+ `detect_value_types`, `compute_live_*`, etc.
132+ - `@nd_inferred_type[nid]` is the cache `infer_type` consults
133+ before running the dispatch tree (>99 % hit rate at emit).
134+ - `@nd_scope_names[bid]` / `@nd_scope_types[bid]` are read by
135+ `declare_method_locals`, `emit_main`, and the inline-yield body
136+ emitters in lieu of re-running `scan_locals`.
137+4. Walks AST, emits C, writes to stdout or `out.c`.
138+
139+### What stays in codegen by design
140+
141+Some helpers conceptually belong to analysis but their results are
142+consumed only at emit time, so they stayed in `spinel_codegen.rb`:
143+
144+- `infer_array_elem_type`, `infer_hash_val_type`, `unify_call_types` —
145+ used inside `compile_array_literal_from_ids`, `compile_hash_literal`,
146+ `body_yield_arg_types`. The values they compute are emit-site-local
147+ and are not part of any per-program table.
148+- `cls_meth_is_live`, `cls_cmeth_is_live` — read the pipe-joined
149+ `@cls_meth_live` / `@cls_cmeth_live` strings analyze produced. The
150+ membership-test wrappers stay codegen-side because they are pure
151+ consumers.
152+- Block-iteration scope: `infer_type` for nodes inside a block body
153+ does its own dispatch since the iterator-derived block-param types
154+ (`each` / `map` / `each_with_index` / `each_pair` / `tap` / `scan` /
155+ `Fiber.new` / etc.) are not pre-cached. `walk_and_cache` skips block
156+ bodies for exactly this reason; codegen's own `infer_type` does the
157+ iterator-specific scope push when it traverses into one.
158+ `proc` / `lambda` / `Proc.new` blocks are also intentionally skipped
159+ — their param type is determined by the runtime caller and
160+ `compile_lambda_def` hardcodes `int` for the param.
161+
162+## Per-ivar contract
163+
164+Every ivar listed below is round-tripped through the IR. Codegen has
165+no analysis-side derivers for any of them — if analyze does not write
166+the record, codegen sees the default value (`0`, `""`, `[]`).
167+
168+### Counters / scalars (`INT`)
169+
170+| Ivar | Meaning |
171+|-------------------|-------------------------------------------------------------------------|
172+| `@nd_count` | Total AST node count. Codegen sizes its parallel arrays from this. |
173+| `@root_id` | Root ProgramNode id (entry into AST traversal). |
174+| `@analysis_frozen`| Set to `1` after `analyze_phase` finishes (advisory; codegen ignores). |
175+| `@ieval_counter` | Counter used to mint `__sp_ieval_<N>` synthetic method names. |
176+
177+### Feature-need flags (`INT`, all default `0`)
178+
179+`@needs_gc`, `@needs_system`, `@needs_int_array`, `@needs_float_array`,
180+`@needs_str_array`, `@needs_str_int_hash`, `@needs_str_str_hash`,
181+`@needs_int_str_hash`, `@needs_sym_int_hash`, `@needs_sym_str_hash`,
182+`@needs_sym_intern`, `@needs_setjmp`, `@needs_mutable_str`,
183+`@needs_rb_value`, `@needs_regexp`, `@needs_rand`, `@needs_stringio`,
184+`@needs_lambda`, `@needs_fiber`, `@needs_bigint`, `@needs_poly_array`,
185+`@needs_poly_poly_hash`, `@needs_str_poly_hash`, `@needs_sym_poly_hash`,
186+`@needs_ptr_array`, `@needs_file_io`. Each toggle gates an emit of the
187+corresponding runtime helper block.
188+
189+### Live-method tables (`STR`)
190+
191+| Ivar | Meaning |
192+|--------------------|---------------------------------------------------------------------------|
193+| `@cls_meth_live` | `;`-joined `<ClassName>::<method>` entries for live instance methods. |
194+| `@cls_cmeth_live` | `;`-joined entries for live class methods. Both used by DCE stub emit. |
195+
196+### Top-level methods (`SA` / `IA`)
197+
198+`@meth_names`, `@meth_param_names`, `@meth_param_types`,
199+`@meth_param_empty`, `@meth_return_types`, `@meth_body_ids` (IA),
200+`@meth_has_defaults`, `@meth_rest_index` (IA), `@meth_has_yield` (IA).
201+
202+These are the parallel arrays codegen reads in `emit_toplevel_method`,
203+`compile_no_recv_call_expr`, the bare-call dispatch paths, etc.
204+
205+### Class tables (`SA` / `IA`)
206+
207+`@cls_names`, `@cls_parents`, `@cls_ivar_names`, `@cls_ivar_types`,
208+`@cls_ivar_init_definite`, `@cls_ivar_observed_types`,
209+`@cls_meth_names`, `@cls_meth_params`, `@cls_meth_ptypes`,
210+`@cls_meth_returns`, `@cls_meth_bodies`, `@cls_meth_defaults`,
211+`@cls_meth_ptypes_empty`, `@cls_attr_readers`, `@cls_attr_writers`,
212+`@cls_cmeth_names`, `@cls_cmeth_params`, `@cls_cmeth_ptypes`,
213+`@cls_cmeth_returns`, `@cls_cmeth_bodies`, `@cls_cmeth_defaults`,
214+`@cls_is_value_type` (IA), `@cls_is_sra` (IA), `@cls_meth_has_yield`,
215+`@cls_method_adapters`.
216+
217+The per-class entries inside each `SA` are joined by `;` (between
218+methods of one class) and `|` (between classes). Joining and splitting
219+is consistent with the helper API (`cls_meth_pnames_get`,
220+`cls_meth_ptypes_get`, etc.) on both sides.
221+
222+### Constants / cvars / gvars (`SA` / `IA`)
223+
224+`@const_names`, `@const_types`, `@const_expr_ids` (IA),
225+`@const_scope_names`, `@cvar_names`, `@cvar_types`,
226+`@cvar_init_values`, `@gvar_names`, `@gvar_types`,
227+`@multi_const_inits`.
228+
229+### Modules (`SA` / `IA`)
230+
231+`@module_names`, `@module_body_ids` (IA), `@module_acc_keys`,
232+`@module_acc_consts`.
233+
234+### FFI (`SA` / `IA`)
235+
236+`@ffi_modules`, `@ffi_module_libs`, `@ffi_module_cflags`,
237+`@ffi_func_modules`, `@ffi_func_names`, `@ffi_func_arg_types`,
238+`@ffi_func_ret_types`, `@ffi_func_arg_specs`, `@ffi_func_ret_specs`,
239+`@ffi_buf_modules`, `@ffi_buf_names`, `@ffi_buf_sizes` (IA),
240+`@ffi_reader_modules`, `@ffi_reader_names`, `@ffi_reader_kinds`,
241+`@ffi_reader_offsets` (IA).
242+
243+### Regexp / dyn-regex / local-regex (`SA` / `IA`)
244+
245+`@regexp_patterns`, `@regexp_flags`, `@dyn_regex_node_ids` (IA),
246+`@dyn_regex_flags`, `@local_regex_names`, `@local_regex_idx` (IA).
247+
248+### Misc (`SA` / `IA`)
249+
250+`@open_class_names`, `@method_ref_vars`, `@method_ref_names`,
251+`@galias_new`, `@galias_old`, `@undef_class_idx` (IA), `@undef_method`,
252+`@sym_names`, `@tuple_types`, `@poly_funcs`, `@poly_param_types`,
253+`@ieval_class_idxs` (IA), `@ieval_body_ids` (IA),
254+`@pre_execution_blocks` (IA), `@post_execution_blocks` (IA),
255+`@toplevel_ivar_names`, `@toplevel_ivar_types`,
256+`@lambda_var_ret_names`, `@lambda_var_ret_types`.
257+
258+## Per-AST-node records
259+
260+These records are sparse — a record is emitted only when the value
261+differs from the default, so the count is bounded by the size of the
262+analysis result, not by `@nd_count`.
263+
264+### `T <nid> <type>` — inferred-type cache
265+
266+Filled by `annotate_all_node_types` for every reachable node outside
267+block bodies. Codegen's `infer_type(nid)` checks `@nd_inferred_type[nid]`
268+first; non-empty cache hit returns immediately, otherwise it runs the
269+dispatch tree (still kept in codegen for block-body expressions and
270+the `SuperNode` / `ForwardingSuperNode` arms that need
271+`@current_class_idx` context).
272+
273+### `NM <nid> <name>` — `@nd_name` override
274+
275+Emitted only for `rewrite_instance_eval_calls` rewrites that re-stamp
276+a CallNode's name to `__sp_ieval_<N>`. The matching `NB` record below
277+clears the call's block. Codegen does not re-run the rewrite; the IR
278+ports the result.
279+
280+### `NB <nid> <int>` — `@nd_block` override
281+
282+Emitted alongside `NM` when an ieval call's block was lifted into
283+`@ieval_body_ids` and the AST callsite's block is now `-1`.
284+
285+### `SN <nid> <pipe-names>` and `ST <nid> <pipe-types>` — scope locals
286+
287+One pair per scope body whose local declarations are non-empty. The
288+ids are body-node ids (top-level main, top-level method bodies,
289+instance method bodies, class method bodies, ieval bodies). Codegen
290+calls `declare_method_locals(bid, pnames)` which short-circuits on
291+`@nd_scope_names[bid]` instead of re-running the multi-pass
292+`scan_locals` refinement.
293+
294+The pairing is positional — `SN` element `i` declares the local whose
295+type is `ST` element `i`. Both arrays have the same length.
296+
297+## Loading order
298+
299+`load_analysis_buf` processes records in the order they appear in the
300+file. Order matters in two places:
301+
302+1. `INT @nd_count` must precede any per-node record (`T`, `NM`, `NB`,
303+ `SN`, `ST`). The loader bound-checks `nid < @nd_count` and silently
304+ drops records out of range; with `@nd_count` not yet set, every
305+ per-node record would be dropped. `dump_analysis_buf` emits
306+ `@nd_count` as the first scalar after the version stamp for this
307+ reason.
308+2. Class / method tables (`SA`) load before any `T` record that names
309+ a class or method type (`obj_<C>`, `class`, etc.) — codegen does
310+ not re-validate types at load, so a downstream consumer that calls
311+ `find_class_idx` against an unloaded `@cls_names` would miss. In
312+ practice the dump order keeps the parallel-array tables ahead of
313+ per-node records, so this is not a problem with the current
314+ serialiser, but reordering the SA / IA emit block requires
315+ matching loader awareness.
316+
317+## Statistics
318+
319+For the bootstrap input `spinel_codegen.rb` (~28.9 K Ruby lines, ~123 K
320+AST nodes):
321+
322+| Category | Count | Notes |
323+|------------|---------|------------------------------------------------------------------|
324+| `T` | ~101 K | Per-node inferred-type cache, ~99 % hit rate at emit |
325+| `SN` / `ST`| ~370 each | Scope-body local-decl pairs |
326+| `SA` | ~73 | Analysis-derived parallel arrays |
327+| `INT` | ~30 | Counters + feature-need flags |
328+| `IA` | ~16 | Body-id arrays, flag arrays |
329+| `STR` | ~2 | Live-method tables |
330+| File size | ~1.5 MB | Round-trip fixpoint stable (`gen2.ir == gen3.ir`) |
331+
332+## Gotchas
333+
334+- **Length-prefixed split** is non-negotiable for `SA` / `IA`. The
335+ empty array and the single-empty-element array serialise to the
336+ same body; only the `<count>` distinguishes them. `ir_split_strs_n`
337+ / `ir_split_ints_n` pad up to the recorded count when the body
338+ parses to fewer elements.
339+- **Percent-encoding** must round-trip — the encoder escapes ` `, `\n`,
340+ `\r`, `\t`, `%`, `|`, but downstream consumers may rely on other
341+ characters surviving. Adding new escape rules requires updating both
342+ `ir_escape` (analyze) and `ir_unescape` (codegen).
343+- **Two-string `O(N²)` trap**: the original `dump_analysis_buf`
344+ appended T-records with `buf = buf + line` in a loop; for the ~150 K
345+ T-records in spinel_codegen.rb's self-host, that quadratic
346+ reallocation pattern blew the heap to 60 GB on the spinel-compiled
347+ analyze binary. The current implementation accumulates record
348+ strings into a `StrArray` and joins once at the end. Any new
349+ per-node record loop should follow the same pattern.
350+- **Block-body type cache is empty by design**. Codegen's
351+ `infer_type` is the authoritative path for block-body expressions
352+ because the iterator-derived block-param types are not pre-cached
353+ by `walk_and_cache`. Adding `T` records for block-body nids is not
354+ a no-op — it would override the iterator-specific scope codegen
355+ pushes during traversal.
356+- **Bootstrap fixpoint is 4-way**, not 2-way. `make bootstrap`
357+ verifies both `analyze.rb` and `codegen.rb` round-trip through the
358+ pipeline in both the IR (`analyze.rb: IR fixpoint OK`) and C
359+ (`codegen.rb: C fixpoint OK`) dimensions. A change that affects
360+ either side's deterministic output (record order, string
361+ formatting, default-value handling) breaks the fixpoint and the
362+ bootstrap fails.
363+
364+## Format version
365+
366+`SPINEL-IR v1` is the only version recognised. The loader treats the
367+literal version line as a comment — any other text on the first
368+non-empty line is silently ignored, so a future v2 format that
369+extends the tag set must change the version stamp and matching loader
370+logic together.
371+
372+## Adding a new ivar
373+
374+1. Decide tag: scalar int → `INT`, scalar string → `STR`, array of
375+ strings → `SA`, array of ints → `IA`, per-node attribute → `T` /
376+ `NM` / `NB` / `SN` / `ST`.
377+2. Add the emit line in `dump_analysis_buf`
378+ (spinel_analyze.rb#dump_analysis_buf).
379+3. Add the matching loader arm in `ir_set_int_ivar` /
380+ `ir_set_str_ivar` / `ir_set_sa_ivar` / `ir_set_ia_ivar`
381+ (spinel_codegen.rb).
382+4. Initialise the ivar to its default value in
383+ `Compiler#initialize` on **both** sides — codegen relies on the
384+ ivar existing as a struct field for self-host typing.
385+5. Run `make bootstrap` and verify all four fixpoints
386+ (`analyze.rb: IR fixpoint OK`, `analyze.rb: C fixpoint OK`,
387+ `codegen.rb: IR fixpoint OK`, `codegen.rb: C fixpoint OK`).