Skip to content

MoonLive on a stack machine: the frame is where values live #166

Closed

Description

@MoonModules

Plan 2026-08-13, closed 2026-09-12, shipped.

Goal

A MoonLive script bounded by memory rather than by register count. The register allocator with spilling that preceded it was textbook-correct on the host and left zero keepable registers on Xtensa (10 registers minus 1 scratch, 5 fixed ABI vregs and 4 reload temps), so every looped script was refused on the ESP32 classic and S3.

Outcome

Every script variable lives in a frame slot; registers hold one expression's temporaries. All four boards (S3, classic ESP32, P4, S31) run scripted layouts and effects with nested loops, plasma and ripples. Measured on Xtensa, grid.mlv went from 212 to 186 bytes and three-deep nesting compiled for the first time; a four-deep layout and a looped effect compile there at all only since call arguments stage through the frame. The three per-ISA lowerers (142, 138 and 150 lines, about 65% identical) became one template over the assembler: 537 lines became 190 shared plus 62 of adapters, and all four boards emit byte-identical exec blocks to the three-file version. The desktop renders a scripted grid with a plasma effect at 76,923 fps. The predicted cost, 20 to 40% on arithmetic-heavy inner loops and close to nothing on host-call-dominated scripts, is recorded against the MoonLive tick and memory numbers.

Decisions

  • A stack machine, not a better allocator. Register allocation makes every language feature interact with the allocator (loop-extended intervals, live-range merges at joins, a save-set per call site, arguments bounded by spare vregs, recursion impossible in a fixed slot file). In the stack model each is the same recursive mechanism: nesting is nesting, a call pushes args, each activation gets its own frame. It is also the shape prior art on this chip settles on. A design whose margin is zero on the platform it exists to serve is the wrong design, however correct its algorithm.
  • One lowering per construct, not one per target. A new target is a new assembler (encodings plus ABI constants), never a new IR walk; where an ISA genuinely differs, the difference is a named hook on the assembler surface. The host backend's cmp and branchIf became private, since a flags pair cannot be shared with a backend that has none; it gained movReg, branchGeU and branchNe and adopted the devices' FillElems. The two device lowerings had differed by two identifier tokens, and the host one by free choices rather than ISA facts.
  • The host arguments go to the frame too (buf, nLights, cpl, t, ctrls). They were read-only yet held five registers permanently, on Xtensa five of the six the windowed ABI leaves a calling routine. Parked at entry and reloaded where read. This belongs in core: it is the same "the frame is where values live" rule, and per-backend copies would be three copies of one policy.
  • Unlimited call arguments by passing a pointer to the argument slots, not by widening HostCallFn and the three call() sequences. The Xtensa call sequence had produced three separate defects, so it stays untouched; HostCallFn takes (const uintptr_t* args, uint32_t argc, const uint8_t* arena) and arity is bounded by frame slots (kMaxCallArgs = kMaxLocals). Not the arena: its bytes are uint8 and its offset an 8-bit immediate, so it cannot carry a 32-bit argument. A seven-argument line() became an ordinary builtin.
  • One system-variable table for every role, and a modifier's per-light coordinate renamed xPos/yPos/zPos. The three tables were different vocabularies, not nested ones, so a name meant one thing in one role and was reserved in another; disasm.py, compiling against the widest table, refused the shipped grid.mlv because it used x/y as loop counters. width/height/depth now mean the grid's dimensions in every script: a layout defines them, an effect and a modifier read them. The three role accessors remain as aliases. No MIGRATING entry: MoonLive had not launched, so an entry would describe an upgrade path no user could take.
  • Clean first, speed decisions made deliberately. No speculative fast paths, no register pinning, no innermost-counter caching. Register optimization in full is out of scope, including whether any fixed ABI vreg stays in a register; that is reopened against measurements, as an addon over a correct baseline. This inverts the failure from "refuse to compile" to "compile, possibly slower".
  • Which limits are physics and which are choices. kRegCount (Xtensa 10, RISC-V 14, host 14) and kArenaBytes 255 (the l8ui/lbu immediate is one byte) are hardware. kMaxLocals/kMaxSpillSlots 16 (243 reachable on Xtensa, 512 on RISC-V), kMaxVRegs 32, kIrLabels 16 and kMaxCtrls 8 are chosen and raisable with a reason. kMaxLocals and kMaxSpillSlots index one frame and must move together; spillToBudget refuses a compile when they mismatch. None is raised speculatively: once variables live in the frame, kMaxLocals is the real ceiling and is set from a measurement.
  • Verification before the rework. Five wrong theories about emitted Xtensa code in one session, each falsified only by the device, because no test executed Xtensa code. So first: golden-byte tests over the shipped scripts, a structural checker (branch targets on instruction boundaries inside the program, frame offsets inside the entry frame, no register outside the backend's map), and the squeezed-budget behavioral tests kept. The device backends compile and run on the development machine through a lower seam on compileSource, two per-ISA test TUs sharing one body.
  • Dropped: deleting the allocator. Its precondition never came true: registers still hold expression temporaries, so a complex enough expression on Xtensa's ten still spills, and all three lowerings call spillToBudget. Its test suite is the only way the register algorithm is tested at all, since only the host backend executes in tests. It earns its place.
  • Superseded: one shared base for the three bindings. The code's objection: the bindings derive from three sibling bases, so a shared MoonLiveBase : MoonModule gives each binding two MoonModule subobjects unless MoonModule becomes a virtual base, and a CRTP mixin trades duplication for friend plumbing; the duplication is about 25 lines, and compiledHash_ means two different things (a presence flag in the layout, a change detector in the modifier). The product's objection, the decisive one: a script should look like the compiled module it stands in for, with named entry points, so a binding compiles, discovers which entry points exist and calls the right one. That is a dispatch table, not a class hierarchy, and it cannot be designed before the entry points exist. Replaced by MoonLive scripts are classes #167.
  • Xtensa: the diagnosis was half right. The windowed ABI (call8 rotates the window by eight; a8..a15 are clobbered) explained three earlier defects, and the planned fix was to restrict the vreg map to a2..a7 rather than use call4, which would constrain host builtins we do not own. The map stayed at ten: call() already saved a8..a11 around the call. The real defect was frame layout: the window-overflow handler spills a frame's a4..a7 into the frame's own top 32 bytes, the emitter reserved 16, so the parked arena pointer sat in hardware-owned memory and any interrupt during a host call destroyed it. Spatial, not temporal, and invisible to every encoding check. Register numbering had been derived independently in four places, which register-and-slot-contract.md now writes down.

Where it lives

What Home
The one IR walk, a template over the assembler src/core/moonlive/moonlive_lower.h
Who owns register numbers and frame slots src/core/moonlive/register-and-slot-contract.md
The spiller that stays, and its squeezed-budget tests src/core/moonlive/MoonLiveSpill.h
The compiler and per-ISA backend shape MoonLive architecture, a native-codegen compiler
The register-window frame bug lessons
Tick, exec block and flash cost performance.md, MoonLive
Per-ISA codegen tests and the structural checker test/unit/core/unit_moonlive_codegen_xtensa.cpp, moonlive_structural.h
Emitted code on the host moondeck/moonlive/disasm.py

Steps

  • Emitted-code tests against current behavior: two per-ISA test TUs sharing one body, 11 tests
  • A frame slot per script variable; a read reloads into a temp that dies at once
  • Registers become expression temporaries; call arguments staged through the frame, one holding a register at a time
  • The host arguments parked in the frame at entry, in core
  • Unlimited call arguments through a pointer to the argument slots
  • The three lowerers collapsed into one template over the assembler
  • Delete the allocator: dropped, spilling is still reachable and its tests are the register algorithm's only coverage
  • One system-variable table for every role; xPos/yPos/zPos on a modifier; the shipped scripts and tests moved
  • One shared base for the three bindings: superseded by the dispatch-table shape of MoonLive scripts are classes #167
  • Bench on S3, classic ESP32, P4 and S31: scripted layout and effect, nested loops, plasma and ripples
  • Measured with collect_kpi.py, recorded in performance.md

Shipped in

Still open

  • Whether to promote anything into registers, and which, including whether any fixed ABI vreg earns one: decided against measurements, after a correct baseline.
  • A scripted driver as the fourth role, the test of the successor's dispatch step: backlog/moonlive.

Activity

  1. added
    plan
    on Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    plan

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions