IR and Equivalence Criteria
This document describes L3's IR/SSA structure, validation, and snapshots, as well as how a change proves that it has not broken existing behavior. For type representations, see 02-frontend.md; for layering and stages, see 01-architecture.md.
Structure
src/middle/ir/ir.rs defines:
ModuleIR: function table, module initialization sequence, type table, etc.FunctionIR:name, binding identitydef: Option<DefId>,params,return_type,generic_params,body.FunctionBody:Code { blocks, entry, locals, values, value_slots }—ordinary function body;TypeDecl { body: TypeDeclBody }—type declaration body, retaining only the field table, field types, and type table entries consumed by the IR.
BasicBlock: linear instruction sequence + terminating instruction.Instruction: IR instruction; operands areOperand.Operand:Const(ConstValue)/Value(ValueId)/Local(usize)/Arg(usize)/Global(usize); thevaluesandvalue_slotstables use the sameValueIdindexing.
IR type annotations may only use the resolved subset of MonoType (TypeVar, MetaType, Literal, and ConstExpr must not appear; see 02-frontend).
SSA Discipline
verify (src/middle/ir/verify.rs) checks by pattern:
| Invariant | Description |
|---|---|
| Single definition | Each ValueId is defined only once; Phi does not count as a duplicate ordinary definition |
| Dominance | A definition at a use site must dominate that use site; every predecessor of a Phi must have a corresponding incoming edge |
| Predecessor consistency | The number of incoming edges for a Phi equals the number of predecessors, and they come from the correct basic blocks |
| Jump targets | Branch/jump targets must be existing blocks or labels |
| Slot bounds | Slot numbers must be within the function frame; exceeding the limit is an error rather than a truncation |
| Type consistency | Instruction operands and result types must agree with the MonoType annotations |
| Inner isolation | TypeDecl and code bodies, and closure environment slots and function parameter slots, must not contaminate one another |
Two entry points:
verify_loose: must pass on existing IR; a failure means the IR depends on writing the same slot multiple times, so the defect must be fixed first.verify_ssa: strict SSA mode, requiring single definitions and dominance.
The validator is integrated into CI and covers the entire corpus; new instructions or IR shapes must also be covered by validation.
Snapshots
src/middle/ir/tests/snapshots/ stores normalized IR snapshots. Normalization rules (normalize.rs):
- Strip
Span; - Rename temporary values in order of appearance;
- Relativize global slots;
- Sort predecessors stably.
Snapshots are committed to the repository; updates require manual review of the diff. Snapshots are used only for equivalence criteria C1/C4 and are not runtime inputs.
Lowering Boundaries
- The only construction path from AST → IR is
src/middle/lower/(module_ir.rs/expr//stmt.rs/scope.rs, etc.). Other modules undermiddle/must not construct IR directly from the AST. src/middle/lower/synth.rsis the only place in L3 production code permitted to constructast::Expr/ast::Stmt/ast::Type; the boundary between synthesized and real ASTs is explicit, and implicit callbacks must not bypass it.- Call-expression generation has already been split by responsibility; new branches should be placed in the corresponding phase of
expr/call.rs, rather than piling logic back into a single function. - Type information for local lambda bindings and returned closures is completed once within lowering; downstream stages must not infer closure body types again.
Register Allocation
src/middle/lower/regalloc.rs implements linear-scan allocation:
- The inputs are SSA values and live intervals; the outputs are
value_slotsand frame slots; codegenonly readsvalue_slotsand does not perform allocation itself;- After allocation, the slot limit must be satisfied; if everything does not fit, report
E3014(with the function body span), and do not silently truncate; - Statement-level reclamation has been removed; reclamation is handled uniformly by the allocator and RAII.
Bytecode Format
src/middle/bytecode/file.rs:
VERSION = 5; function records carryupvalue_countandglobals.- The reader validates by version; cross-version compatibility is not a goal.
- No exception table is written:
TRY_BEGIN/TRY_END/THROWare undefined, and the language has no throw/try/catch. - The debug section has an independent version; a missing debug section is treated as empty.
Equivalence Criteria
| Category | Change | Criterion |
|---|---|---|
| C1 | Pure relocation (splitting files, changing directories, extracting submodules) | Zero diff in normalized IR snapshots |
| C2 | Orchestration changes (staging, unified Driver) | Same diagnostic set at each entry point + same corpus behavior |
| C3 | Type-representation convergence | Same diagnostic codes and messages (order may be normalized) |
| C4 | IR shape changes (SSA conversion) | Behavioral equivalence + IR structural invariants |
| C5 | Frontend paradigm changes | AST snapshot + diagnostic code/span + behavior, all three used |
| C6 | Pure deletion | Confirm that there are no references; no equivalence criterion applies |
Criteria are selected according to the layer actually touched by a change, not its size. When a change spans multiple layers, take the union of the applicable criteria.
Three-Layer Criteria
IR static validator (
src/middle/ir/verify.rs)verify_loose: must pass on existing IR, with no exemptions.verify_ssa: strict SSA mode.- Checks: single definitions, dominance,
Phipredecessor consistency, jump targets, slot bounds, type consistency, and inner isolation.
Normalized IR snapshots (
src/middle/ir/tests/snapshots/)- Normalization: strip
Span, rename temporary values in order of appearance, relativize global slots, and sort predecessors. - Snapshots are committed to the repository; updates require manual review of the diff.
- Normalization: strip
End-to-end corpus diff (
tests/baselines/corpus-parity.jsonl)- Compare diagnostic lists, exit codes, stdout, and stderr item by item.
- Covers single-file and multi-file corpora; new corpus cases must be added to the baseline.
Semantic Correction Routing
Equivalence criteria only prove that “behavior remains unchanged.” When behavior needs to be changed, use semantic correction routing; the entry criterion is “whether the old behavior is consistent with the written provisions,” not “whether the compiler previously accepted it.”
A/B/C categories may be corrected along with a change, and all five requirements are indispensable:
- A failing criterion must exist first and must currently genuinely fail.
- Programs that originally complied with the specification must behave identically externally (diagnostic codes, wording, exit codes); paths that originally violated the specification failing or becoming more explicit is the correction itself.
- Correct the affected body text in place in the same commit (the body describes only the current state), and annotate it on the PR's “Error Type” line.
- Regenerate the baseline in the same commit and manually review the diff.
- The commit message and PR must state the RFC/SPEC section number and the minimal counterexample for the behavior.
D/E/F categories—D user-visible semantics, E external contract tables, and F RFC-level design changes—must first go through user adjudication. If the specification is silent or ambiguous, always fall back to D/E/F; “I think it is more correct” is not an entry criterion.
Categorize a change by its primary error type; list incidental behavior changes within the same root cause separately on the PR's “D3 patch determination” line.
Regression Gates
| Gate | Purpose |
|---|---|
verify_loose / verify_ssa | IR structure and SSA invariants |
| Snapshot comparison | Zero drift in IR text |
| Corpus diff | Zero drift in diagnostics/exit codes/stdout/stderr |
| Direct-drive tests | Every mechanism's producer and consumer are exercised through real entry points |
check-obligations.py | Obligation-field delivery matches actual consumption |
Baseline regeneration commands:
UPDATE_SNAPSHOTS=1 cargo test --lib snapshot -- --ignored
cargo run --quiet --example corpus_probe > tests/baselines/corpus-parity.jsonlBaseline changes must be committed in the same commit; what gets reviewed is the diff, not the fact that “the gate is green.”
Two Disciplines
- Criteria before refactoring: establish a failing criterion first, then change the implementation; “green followed by red” cannot distinguish a fix from a regression.
- Do not relax criteria to get a green light: a failing criterion indicates an implementation defect and must be reported truthfully; do not delete tests, add allowlists, or grant exemptions. If it cannot be done, then it cannot be done.
