
louise
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
ADR 0003: Effect handler lowering in the C backend
Status: Accepted — 2026-10-08, reviewed and accepted by the project owner (issue #2), including Revision 1.
Context
Algebraic effects need some way to reach the nearest handler and, for some operations, to capture and resume the rest of the computation.
The native backend emits C, which has no delimited continuations. The design has to work together with:
- Perceus (ADR 0002),
- actor fibers (ADR 0004),
- a possible future wasm/JS client target, which has no fibers.
Decision
Lowering is chosen per operation kind, which is known statically from the effect declaration:
| Op kind | Semantics | Native lowering in v0 |
|---|---|---|
fn | tail-resumptive: the clause's result is the op's result | Evidence passing. The op is a direct call to the clause found in the evidence vector. |
final ctl | never resumes (exceptions, early exit) | Yield-bubbling unwind to the handler's marker (runtime ABI). |
ctl | captures a one-shot resumption | Interpreter only in v0. Codegen rejects it with a diagnostic. |
Rules:
- Evidence scope. A
fnclause runs with the evidence vector of the place where its handler was installed. Otherwise a clause that performs its own effect would find itself and loop.maskskips the innermost handler of a label. - Yield checks live in Core. They are inserted explicitly in Core, as
let x = f(..); if yielding(ctx) { return }, before Perceus runs. Perceus then computes the drops on the unwind path like on any other path, so codegen never redoes liveness analysis. - Where yield checks go: after every call except to a callee proven never to yield.
- Correction to the v0 plan: the plan, following the architecture review, would skip checks for callees with closed rows and no
ctl/final ctleffect. - That is insufficient, because panics and exit signals use the same unwinding and can cross any frame. The M0 spike made this explicit.
- "Never yields" means: no
TL_ENTER, no operation that can panic, and only calls to never-yield functions. In practice that is small leaf functions. - Cost: one predicted branch per call.
- Correction to the v0 plan: the plan, following the architecture review, would skip checks for callees with closed rows and no
- Op values are owned. Operation arguments and resume values are always passed owned. A borrowed argument could be freed by unwinding while the clause still uses it.
- No user
finallyin v0. Unwinding runs only drops; it never runs user code that could perform operations. (v1:defercleanups run while unwinding, limited to effects that cannot unwind or suspend; ADR 0016, proposed.)
Planned v1 path for general ctl: extend yield-bubbling into Koka-style continuation capture. Each frame that sees yielding = CTL appends its continuation (a closure over its live locals) before returning. The same scheme works on wasm and JS. Fiber-based capture remains an alternative for native code only.
Consequences
- The v0 demo needs only
fnops (logging, DB mocks),final ctl(errors), panics and kills, and all of these are covered natively. - Generators and async-style handlers run in the interpreter but not natively until v1. Users get a clear error instead of a miscompile.
- Every non-leaf call carries a yield check. This is the price of having unwinding without a C++/DWARF unwinder and with exact drops.
Alternatives considered
- A fiber per handler for
ctl(OCaml 5 style). Captures cheaply, but with corosensei's asymmetric coroutines, preemption inside a nested fiber returns to the parent handler rather than to the scheduler. It also needs a separate wasm story. Deferred. setjmp/longjmpor forced unwinding with__attribute__((cleanup)). Zero cost on the happy path, but it runs drops at scope end instead of last use, fights Perceus's ownership tracking, and is undefined behaviour across Rust frames.- A full CPS transform. Simple semantics, but it allocates on every effectful call and makes debugging the generated C painful.
Revision 1 — 2026-10-09: native ctl, zero-overhead unwinding, guaranteed tail calls
Status: Accepted — 2026-10-08, with the rest of this ADR (issue #2). Decided by the project owner. This supersedes "general ctl is interpreter-only in v0", rule 3 (a yield check after every non-leaf call), and the tail-call rule.
ctl operations compile natively in v0: stack switching with one-shot continuations
This follows Lexa (Ma et al., OOPSLA 2024), OCaml 5 and WasmFX.
Handlers on fibers: a
handlefor an effect that hasctloperations runs its body on a fiber taken from a per-thread pool. Fibers have large, lazily committed stacks with a guard page; C stacks cannot move.Operations: performing a
ctloperation switches to the handler's stack, andresumeswitches back. A continuation is the suspended fiber, so it is one-shot and needs no copying.A continuation that is never resumed is resumed once in cancel mode, which unwinds it (see below), so Perceus stays exact.
Unchanged paths:
fnoperations remain direct calls through the evidence vector;final ctluses the unwinding below.
Programs that do not use
ctlpay nothing.The context switch: the runtime's own symmetric switch, a few dozen lines of assembly for x86_64 and aarch64. It replaces corosensei, and is shared with actor scheduling (ADR 0004).
Unwinding is zero-overhead and table-driven
This follows the zero-overhead principle and mechanism of Ma et al., Zero-Overhead Lexical Effect Handlers (OOPSLA 2025).
Normal paths carry nothing: no flag checks after calls, and no extra arguments.
The data: the compiler emits per-call-site metadata keyed by return address, recording which owned values must be released if the stack is unwound through that call.
At raise time, for a panic, an exit signal or a
final ctloperation, a runtime stack walker visits frames from the raise point and runs their cleanups. It stops at:- the handler frame, recorded (stack address and resume point) when the handler was installed: a cost per
handle, not per call; - or the actor's root.
- the handler frame, recorded (stack address and resume point) when the handler was installed: a cost per
In the C backend, the call-site tables are the platform unwind tables. The compiler emits C compiled with
-fexceptions, marks owned locals with__attribute__((cleanup)), and sets moved values to null.- The runtime walks the tables with
_Unwind_ForcedUnwindand a stop function that recognizes the target frame. - The runtime is entered through
extern "C-unwind", so unwinding through it is defined.
- The runtime walks the tables with
The trade-off, measured in the paper: raising becomes more expensive (a stack walk), while code that does not raise runs faster. Panics and exit signals are rare by nature.
- For
final ctleffects that are raised frequently, an effect can opt into the previous early-return (bubbling) strategy, as Zero Lexa does per effect. - The default and the opt-in syntax are settled with the M5 benchmarks.
- For
Handlers are lexically scoped since ADR 0010, the setting Zero Lexa was designed for:
- every operation names its handler's capability, so there is no handler search;
fnoperations are direct calls through the capability;final ctlunwinds to a statically known frame.
Rule 1 above ("evidence scope") becomes: clauses run in the environment of the place where the handler was installed.
maskis not needed.
Tail calls are guaranteed
Rule: every call in tail position runs in constant stack, whether the callee is known, mutually recursive, or a closure. This is part of the semantics, not an optimization.
- Self tail calls become loops.
- Every other tail call is emitted with
musttail.musttailrequires the caller's and callee's C signatures to match, so all generated functions share one signature:- the context, then 6 value arguments (passed in registers);
- unused slots are never read;
- further arguments go through an area in the context.
- Toolchain: clang ≥ 13 or GCC ≥ 15.
louise buildrejects older C compilers instead of silently losing the guarantee. - Interactions:
- Reference counting: nothing remains to release after a tail call. Perceus releases before it, and borrowed parameters passed on are first given an owned copy.
- Unwinding: there are no unwinding metadata at tail calls.
- Preemption: the reduction check stays in the callee's entry.
- Handlers: calls inside a
handlebody are not in tail position for the enclosing function, because the handler frame remains. These are Koka's semantics.
- Tail recursion modulo cons (Leijen & Lorenzen, POPL 2023) is a Core transformation.
[f(x), ..map(rest, f)]writes into a hole of an already-allocated cell and becomes a real tail call, somap,filterandappendrun in constant stack. It benefits both the interpreter and the native backend.Note (2026-10-13, issue #154): until then this was planned, not implemented: these functions recursed. ADR 0039 implements it, with its scope (self-recursive functions, one hole field per function).
- Tests: native runs of
tests/runuse a deliberately small stack (ulimit -s).Note (2026-10-13, issue #149):
ulimit -scan't do it, since programs run on their own fiber stacks. A program marked//@ small-stackruns withLOUISE_STACK_KIB=256natively and a 10,000-frame limit in the interpreter (ADR 0037).
Revision 2 — 2026-10-09: unwinding by yield checks in the C backend (proposed)
Status: Accepted by the project owner on 2026-10-12; needs engineering review (#44). It reverses one point of Revision 1 for the C backend. This was found while implementing M5 part 2.
The conflict: two Revision 1 decisions cannot both hold in C.
- Zero-overhead unwinding. It needs code that runs only when unwinding through a frame (landing pads). C has no such construct. The closest,
__attribute__((cleanup)), runs on every scope exit. - Guaranteed tail calls. These need
musttail, which clang and GCC refuse while any cleanup is in scope. Every local holding a reference would be in scope at every tail call.
Keeping tail calls guaranteed is the language-level promise (ADR 0001, Revision 1). So the C backend uses the ABI v0 mechanism the M0 spike validated: yield checks.
- After each call that may unwind, generated code tests
ctx->yielding. If it is set, the code drops exactly the references the frame holds at that point and returns. - Perceus knows those references, so unwinding is exact and leaves 0 live blocks.
musttailcalls need no check: the caller holds nothing after them.
Calls that may unwind:
- calls to generated functions and closures;
- operations;
- the externs that can panic: integer arithmetic and
panic.
Other externs never unwind. A later "never unwinds" analysis can drop checks after calls to leaf functions.
What remains of Revision 1:
- the per-effect choice and
final ctlsemantics; - unwinding to a handler known statically (ADR 0010: the capability carries the handler's marker).
Zero-overhead table-driven unwinding stays the goal of a future LLVM backend, where landing pads and musttail coexist.
Cost: one load, compare and predicted branch after calls that may unwind. ADR 0003 measured this as acceptable in v0, and the spike validated it.
Implementation status (M5 part 3):
ctlhandlers run natively as designed above: a fiber per handler, one-shotresume, and a never-resumed body cancelled by unwinding.- Fibers are corosensei coroutines for now. Requests between nested handler fibers are forwarded like in the interpreter, and preemption inside a fiber is forwarded up to the actor's stack.
- Replacing corosensei with the runtime's own symmetric switch is needed only when actors move between threads (M6).
Implementation note — 2026-10-09: calls that never unwind (issue #61). Status: Accepted by the project owner on 2026-10-12; needs engineering review (#44). Revision 2 left "a later 'never unwinds' analysis". It is done, conservatively, in louise_codegen_c/src/unwind.rs:
- A function never unwinds when nothing in it can panic or park (no extern of the panicking list, no
blockingextern, nopanic, no operation other thanstd/ref's, no handler or region), it calls no closure, and it only calls functions that never unwind, or constant dictionaries. Such functions are found from the leaves of the call graph up, so a recursive function (a loop) never qualifies. - Calls of such a function have no yield check, and the function has no preemption point at its entry: it runs a bounded amount of code, and its callers keep theirs. Exit signals are still delivered at the next preemption point.
- Drops were already assumed not to unwind (a dropped value runs no user code); this is unchanged.
- Measured (on the v1 chain, where
Intaddition, subtraction and multiplication no longer panic, ADR 0014): inhttp_demo's C, 93 of 368 yield checks and 44 of 135 preemption points go. Ontests/bench,dictruns 4% fewer cycles, the others within ±2%: specialised evidence (ADR 0013) had already removed most small calls. - Consequence: preemption happens at slightly different calls than in the interpreter (ADR 0013, Consequences).