aython

Chapter 4 of 1154 min read

Emitting assembly

How a checked tree becomes one assembly function per Python function: stack slots for every value, an explicit call for every ownership transfer, and jumps for control flow and exceptions.

The code generator turns the checked tree into one assembly file. It has no optimiser, no register allocator and no intermediate form: each statement becomes a fixed pattern of instructions, every value lives in an 8-byte stack slot, and every change of ownership is a visible call aython_incref or call aython_decref. That plainness is deliberate. The output is meant to be read, and a pattern simple enough to read is also simple enough to trust. This chapter reads it: the frame, the ownership discipline, branches and loops, calls, exceptions, comprehensions and classes, each shown as the exact assembly the real code generator emits for a corpus program.

The code generator is src/aython/codegen.py. Everything quoted below is produced at site-build time by running it, so the listings are what aython run assembles. If you have not met rdi, rax or [rbp-8] before, x86-64 in fifteen minutes is the background; the object layout behind every pointer here is in Objects in memory. The Assembly reader shows the same output interactively, statement by statement.

The shape of the output #

generate writes the whole file in one pass:

src/aython/codegen.py · generatelines 430–481def generate(tree: ast.Module, variables: list[str], funcs: dict[str, list[str]]) -> str:
    """Emit complete assembly text for a validated program.

    The top-level statements become ``main_main``; each user function
    becomes its own ``fn_<name>`` with params in the lowest slots.

    Args:
        tree: Validated module; every node passed ``frontend`` checks.
        variables: Top-level variable names in first-appearance order.
        funcs: Function table: name to full slot list (params first).

    Returns:
        Full Intel-syntax GAS source defining the entry points.

    Raises:
        CodegenError: If an unexpected node reaches the emitter.
    """
    global _label_seq, _func_params, _func_flexible, _current_fn, _str_pool, _str_seq, _try_depth
    global _try_stack, _except_stack, _exc_base
    global _cls_init, _cls_method_flat, _cls_values
    _label_seq = 0  # branch labels start over for each program
    _str_pool = {}
    _str_seq = 0  # literal pool likewise starts empty
    _try_depth = 0  # no active try at the top of the program
    _try_stack = []  # no enclosing try at the top of the program
    _except_stack = []  # no enclosing handler at the top of the program
    total_nodes = sum(1 for _ in ast.walk(tree))
    _exc_base = SLOTS_PER_NODE * total_nodes + SPARE_SLOTS  # save area starts above statement temps
    _func_params = funcs
    _func_flexible = {name: _is_flexible(tree, name) for name in funcs}
    _cls_init, _cls_method_flat, _cls_values = _class_tables(tree)
    frame = Frame(var_index={name: i for i, name in enumerate(variables)}, nvars=len(variables))
    log.debug("codegen: nvars=%d funcs=%d", frame.nvars, len(funcs))
    lines = _file_header_lines()
    lines += _header_lines("main_main")
    lines += _prologue_lines(frame, _frame_bytes(tree, frame))
    _current_fn = None
    for node in tree.body:
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
            lines += _emit_def_defaults(node, frame)
            continue  # declarations emit as fn_<name> below, not inline
        if isinstance(node, ast.ClassDef):
            lines += _emit_class_defaults(node, frame)
            continue  # methods emit as fn_<Class>__<method> below, not inline
        lines += _emit_stmt(node, frame, 0)
    lines += _epilogue_lines(frame)
    for name in funcs:
        lines += _emit_function(tree, name)
    lines += _defaults_bss_lines(tree)
    lines += _rodata_lines()
    lines += _footer_lines()
    return "\n".join(lines) + "\n"
flowchart TB
  hdr[".intel_syntax noprefix<br/>.text"] --> mm["main_main:<br/>the module's top-level statements"]
  mm --> fns["fn_fib:, fn_Counter__bump:, ...<br/>one per function or method"]
  fns --> bss[".bss: one 8-byte static per default value"]
  bss --> ro[".rodata: pooled string literal bytes"]
  ro --> note[".note.GNU-stack: no executable stack"]
  class mm,fns accent
The sections of one generated file, top to bottom. The runtime's own main calls main_main; every user function is a separate symbol.

main_main holds the module’s top-level statements. It is called by main in runtime.s, which libc’s startup code calls; main sets up the memory arena first and returns 0 after main_main returns:

runtime.s · mainlines 13806–13860.p2align 4  # align entry code
.globl main  # crt calls here, export it
.type main, @function  # mark entry as a function
main:  # libc entry point: rdi = argc, rsi = argv, returns the exit status
    push rbp  # save crt's frame base (entry rsp % 16 == 8, now aligned)
    mov rbp, rsp  # frame base for the program body
    call arena_init  # stash args, mmap the arena (rdi/rsi pass through)
    call main_main  # run the generated program body
    xor eax, eax  # return status 0: success, crt exits the process
    pop rbp  # restore crt's frame base
    ret  # back to crt, which exits the process

# ---- Slice: floats ---------------------------------------------------------------
# A float is a 24-byte header (refcnt/type/f64 payload), allocated from the
# 64 MiB arena with headers recycled through free_float_head (a separate
# 24-byte pool from ints, so the two never mix). Literals box the exact
# double bits; there is no small-value cache (CPython caches no floats).
#
# Promotion: every arithmetic helper below accepts borrowed int/bool/float
# operands (bools count as 1/0, like CPython). int op float and
# float op int both compute in f64 and return a float, exactly like
# CPython: 7 / 2 is 3.5, 7 // 2.0 is 3.0, True + 1.5 is 2.5. The int-only
# fast paths above run first; the float blocks validate the other side is
# numeric (a list or str on either side still aborts TypeError, like
# CPython: [1] * 2.0 and "a" * 2.0 are TypeErrors there too). Floats never
# abort OverflowError: overflow rounds to inf, like CPython (1e308 * 10).
# Zero divisors abort ZeroDivisionError, like CPython (1.0 / 0.0 raises;
# it does NOT produce inf). Comparisons across int/float are exact (no
# double-rounding in the verdict: 2**53+1 > 2.0**53 is True). Printing is
# shortest-round-trip repr via the Ryu port below, matching CPython byte
# for byte on every finite double (plus inf/-inf/nan and signed zero).
# Hashing follows CPython's _Py_HashDouble so int/float/bool keys agree:
# {1: 'a'}[1.0] hits, like CPython.
#
# What is NOT here: int()/float() conversions are refused by the frontend
# (no conversion builtins in the subset), and ** is refused with the other
# power forms. NaN hashing returns 0 (CPython 3.14 uses a pointer hash,
# which is nondeterministic across runs; ours is observable-equivalent
# because nan != nan, so lookups only hit on identical objects, which the
# dict fast path resolves by pointer before hashing).

.section .rodata  # float constants (8-byte aligned doubles)
.p2align 3  # align doubles to 8 bytes for movsd/movq loads
flt_one:  # 1.0 for the floordiv snap adjustment
    .quad 0x3ff0000000000000  # exact bits of 1.0
flt_half:  # 0.5 for the floordiv snap test (div - floor > 0.5)
    .quad 0x3fe0000000000000  # exact bits of 0.5
flt_sign:  # mask isolating the IEEE-754 sign bit
    .quad 0x8000000000000000  # bit 63 only
flt_nan:  # canonical quiet NaN for inf/nan floordiv/mod results
    .quad 0x7ff8000000000000  # sign 0, all-ones exponent, payload bit 51
flt_2p28:  # 2**28 for the float-hash mantissa fold (CPython processes 28 bits)
    .quad 0x41b0000000000000  # exact bits of 268435456.0
flt_2nm53:  # 2**-53 for subnormal hash normalization (mantissa into [0.5, 1))
    .quad 0x3ca0000000000000  # exact bits of 2**-53

Every emitted line carries a # comment saying what it does and, where ownership moves, whose reference is whose, and every statement other than a def or class starts with a # line N: comment naming its source line. Nothing reads those comments; they are there so the file can be read top to bottom.

One frame, fixed for the whole function #

Every function, main_main included, gets one stack frame, set up once in the prologue and never resized:

tests/mvp/pass_arith.py · emitted · main_main# prologue: single flat frame, rsp stays fixed below
push rbp  # save the caller's frame base on the stack
mov rbp, rsp  # our frame base = current stack top
sub rsp, 2528  # carve all variable + temp slots at once (fixed size)
...
mov [rbp-8], rax  # init x = None (borrowed ref, no incref needed)
mov [rbp-16], rax  # init y = None (borrowed ref, no incref needed)
mov [rbp-24], rax  # init z = None (borrowed ref, no incref needed)
mov [rbp-32], rax  # init w = None (borrowed ref, no incref needed)

The layout is fixed by two functions. Variable slot k (in the order the frontend listed the names) is at [rbp - 8(k+1)]; temporary t is above all the variables:

src/aython/codegen.py · _slotlines 527–537def _slot(frame: Frame, name: str) -> str:
    """Render the memory operand for a variable slot.

    Args:
        frame: Frame layout holding the variable index.
        name: Variable whose slot to address.

    Returns:
        A string like ``[rbp-16]`` addressing the 8-byte slot.
    """
    return f"[rbp-{WORD_SIZE * (frame.var_index[name] + 1)}]"
src/aython/codegen.py · _templines 540–550def _temp(frame: Frame, depth: int) -> str:
    """Render the memory operand for temporary ``depth``.

    Args:
        frame: Frame layout giving the variable area size.
        depth: 0-based temporary index above the variable (and reserved) slots.

    Returns:
        A string like ``[rbp-40]`` addressing the 8-byte temp slot.
    """
    return f"[rbp-{WORD_SIZE * (frame.nvars + frame.reserved + depth + 1)}]"

For pass_arith.py, with variables x, y, z, w:

Address Holds
[rbp-8] variable x
[rbp-16] variable y
[rbp-24] variable z
[rbp-32] variable w
[rbp-40] and up temporaries 0, 1, 2, …

How many temporaries? The code generator does not compute the exact number; it reserves a safe upper bound, 4 slots for every node of the module’s syntax tree, plus 8 spare, plus 64 for saved exception kinds (one per possible try nesting level):

src/aython/codegen.py · _frame_byteslines 484–497def _frame_bytes(tree: ast.Module, frame: Frame) -> int:
    """Compute the fixed frame size for a body of statements.

    Args:
        tree: Module whose nodes size the temp area (a safe upper bound
            shared by main and every function frame).
        frame: Frame layout with variable and reserved slots.

    Returns:
        16-aligned byte count to subtract from ``rsp`` once.
    """
    total_nodes = sum(1 for _ in ast.walk(tree))
    temp_slots = SLOTS_PER_NODE * total_nodes + SPARE_SLOTS + EXC_SAVE_SLOTS
    return _align_up((frame.nvars + frame.reserved + temp_slots) * WORD_SIZE, FRAME_ALIGN)
Program Variables Tree nodes Temporary slots Frame (bytes)
pass_arith.py 4 60 4 × 60 + 8 + 64 = 312 2528
pass_while_sum.py 2 38 4 × 38 + 8 + 64 = 224 1808
pass_fn_fib.py 0 40 4 × 40 + 8 + 64 = 232 1856

The figure in the last column is checked at build time against the sub rsp, N in the emitted main_main. A frame of a few kilobytes for an eight-line program is wasteful, and that is the price of the decision.

Every variable slot starts holding None, a borrowed pointer to the immortal aython_none object. Releasing a slot is therefore always safe, even for a name that was never assigned on the path taken.

Every value is owned by someone #

The rule the whole file follows: runtime helpers borrow their inputs and return a new owned reference. A helper never frees what it is given, and whatever it returns, the caller now owns and must eventually release. The code generator applies the same rule to expressions: evaluating any expression leaves a pointer in rax that the surrounding code owns.

That makes reading a variable cost a call. The slot keeps its own reference, so the expression takes a second one with aython_incref, and releases it when the expression is done. Here is y = x + 1, the second statement of pass_arith.py; the first three instructions after the comment are the read of x:

tests/mvp/pass_arith.py · emitted for line 3# line 3: y = <expr> (release old, compute new, store)
mov rax, [rbp-8]  # rax = x's object (still owned by the slot)
mov rdi, rax  # arg = same pointer (helper borrows it)
call aython_incref  # take our own shared ownership; rax = same pointer
mov [rbp-48], rax  # park owned left operand (calls below would clobber rax)
# int literal: box it (movabs covers the full i64 range; small values hit the cache)
movabs rdi, 1  # arg = raw integer value (not a pointer yet)
call int_new  # rax = new owned int box (refcnt 1)
mov [rbp-56], rax  # park owned right operand
mov rdi, [rbp-48]  # arg1 = left (helper borrows it)
mov rsi, [rbp-56]  # arg2 = right (helper borrows it)
call int_add  # rax = new owned result (or aborts TypeError/OverflowError/...)
mov [rbp-64], rax  # park the result across the cleanup calls
mov rdi, [rbp-48]  # release left operand
call aython_decref  # (single-use temporaries usually freed here)
mov rdi, [rbp-56]  # release right operand
call aython_decref  # (same)
mov rax, [rbp-64]  # rax = owned result for our caller
mov [rbp-40], rax  # park the new owned value where calls cannot clobber it
mov rdi, [rbp-16]  # rdi = old y (borrowed for the call)
call aython_decref  # release old y; may free it right here
mov rax, [rbp-40]  # rax = new value again (survived the call in memory)
mov [rbp-16], rax  # y now owns the new value

And it makes assignment a four-step dance, written once in _emit_assign_name: compute the new value, park it in memory, release the old value, store.

src/aython/codegen.py · _emit_assign_namelines 753–779def _emit_assign_name(name: str, value: ast.expr, node: ast.stmt, frame: Frame, depth: int) -> list[str]:
    """Emit ``name = value`` with release-old/compute/store ordering.

    The new value is fully computed (and spilled) before the old slot
    is released, so self-assignment ``x = x`` stays alive.

    Args:
        name: Assignment target variable.
        value: Right-hand-side expression, leaving rax owned.
        node: Statement node for the debug comment line number.
        frame: Frame layout for slots and temps.
        depth: Temp base for this statement.

    Returns:
        Assembly lines performing the assignment.
    """
    spill = _temp(frame, depth)
    lines = [f"# line {_line_no(node)}: {name} = <expr> (release old, compute new, store)"]
    lines += _emit_expr(value, frame, depth + OWN_ASSIGN)
    lines += [
        f"mov {spill}, rax  # park the new owned value where calls cannot clobber it",
        f"mov rdi, {_slot(frame, name)}  # rdi = old {name} (borrowed for the call)",
        f"call {RUNTIME_DECREF}  # release old {name}; may free it right here",
        f"mov rax, {spill}  # rax = new value again (survived the call in memory)",
        f"mov {_slot(frame, name)}, rax  # {name} now owns the new value",
    ]
    return lines

The order matters for x = x: the new value is computed (taking its own reference) before the old one is released, so the object cannot be freed in between. Step through x = 6 * 7, the first statement of pass_arith.py, as emitted:

  1. The statement starts. x’s slot [rbp-8] still holds the None the prologue put there. The statement’s spill slot is temporary 0, [rbp-40]; the multiplication will use temporaries 1 to 3.
  2. int_new takes a raw 64-bit integer in rdi and returns an int object in rax. Values from -5 to 256 come from a table of immortal small ints, so no memory is allocated here.
  3. rax is caller-saved: the next call may overwrite it. So the left operand goes to memory, into this level’s first temporary.
  4. The right operand, the same way, into the next temporary.
  5. Both operands go into the argument registers rdi and rsi. int_mul borrows them and returns a new owned result, or aborts OverflowError if the product does not fit in 64 bits.
  6. The result is parked first, because the two releases are calls. Then each operand is released: the expression owned one reference to each and is done with them. (Releasing an immortal small int changes nothing, but the code does not know the values are small.)
  7. The multiplication’s result is back in rax, owned by the assignment now. This is where _emit_binary returns to _emit_assign_name.
  8. Park the new value in the statement’s spill slot, then release the old x. That call may free the old object, and may overwrite rax.
  9. Reload and store. x’s slot now owns the reference the multiplication created. The temporaries are dead: the next statement reuses the same slots.

Nothing in this is clever, and that is what makes it checkable: every owned reference created in the statement is released or stored exactly once, and the judge’s leak probe (in Proving it right) checks that the arena does not grow when the same work is done twice.

Temporaries and the depth discipline #

Each emitter is handed a depth, the first temporary it may use. It takes a fixed number of slots at that depth for its own values, and evaluates its sub-expressions at depth + k, so a nested expression can never overwrite a value its parent has parked. _emit_binary is the clearest case:

src/aython/codegen.py · _emit_binarylines 3444–3477def _emit_binary(helper: str, left: ast.expr, right: ast.expr, frame: Frame, depth: int) -> list[str]:
    """Emit a two-operand helper call with explicit operand cleanup.

    Operands are evaluated to owned temporaries, borrowed by the helper,
    then released; the helper's new owned result ends in rax.

    Args:
        helper: Runtime symbol, e.g. ``int_add`` or ``obj_lt``.
        left: Left operand expression.
        right: Right operand expression.
        frame: Frame layout for slots and temps.
        depth: Three spill slots are used at this level.

    Returns:
        Assembly lines leaving the owned result in rax.
    """
    t_left, t_right, t_result = _temp(frame, depth), _temp(frame, depth + 1), _temp(frame, depth + 2)
    sub = depth + OWN_BINOP
    lines = _emit_expr(left, frame, sub)
    lines.append(f"mov {t_left}, rax  # park owned left operand (calls below would clobber rax)")
    lines += _emit_expr(right, frame, sub)
    lines += [
        f"mov {t_right}, rax  # park owned right operand",
        f"mov rdi, {t_left}  # arg1 = left (helper borrows it)",
        f"mov rsi, {t_right}  # arg2 = right (helper borrows it)",
        f"call {helper}  # rax = new owned result (or aborts TypeError/OverflowError/...)",
        f"mov {t_result}, rax  # park the result across the cleanup calls",
        f"mov rdi, {t_left}  # release left operand",
        f"call {RUNTIME_DECREF}  # (single-use temporaries usually freed here)",
        f"mov rdi, {t_right}  # release right operand",
        f"call {RUNTIME_DECREF}  # (same)",
        f"mov rax, {t_result}  # rax = owned result for our caller",
    ]
    return lines

The number each emitter takes is a named constant. These are all of them, with the emitters that read each (found by walking codegen.py’s own syntax tree at build time):

Constant Slots Used by
OWN_BINOP 3 _emit_binary, _emit_write_file, _emit_append_file
OWN_CMP_CHAIN 3 _emit_compare_chain
OWN_SUBSCRIPT 3 _emit_assign_subscript, _emit_assign_slice_store, _emit_attr_load, _emit_assign_attr, _emit_delete, _emit_delete_slice, _emit_subscript_load, _emit_subscript_slice
OWN_UNARY 1 _emit_unary
OWN_LEN 1 _emit_read_file, _emit_call_expr
OWN_LIST 2 _emit_list, _emit_dict
OWN_TUPLE 2 _emit_tuple
OWN_SET 2 _emit_set
OWN_UNPACK 4 _emit_assign_unpack
OWN_APPEND 2 _emit_call_expr
OWN_METHOD_1 2 no emitter reads it
OWN_METHOD_2 3 no emitter reads it
OWN_METHOD_3 4 no emitter reads it
OWN_METHOD_4 5 no emitter reads it
OWN_ASSIGN 1 _emit_assign_name, _emit_assign_multi, _emit_augassign
OWN_IF_TEST 2 _emit_if, _emit_while

A top-level statement starts at depth 0 and a statement in a block starts at the depth its enclosing statement hands down (a for body starts six slots up, above the loop’s own temporaries). Every statement releases the temporaries it used before it ends, so at every label boundary all temporaries above the enclosing loop’s are dead, and the branches of an if or the passes of a loop reuse the same slots with no bookkeeping. The bound of 4 slots per node rests on the invariant the constant’s own comment states: no emitter level needs more than that many slots per AST node along any root-to-leaf path.

Branches and loops #

if #

An if test may be any expression, not only a comparison, so the code generator normalises truthiness first. aython_not turns any value into the immortal True or False; the branch compares the result with the address of aython_false:

tests/mvp/pass_if_basic.py · emitted for line 4 (its own lines)# line 4: if <test>: (normalize truthiness, run one branch)
mov rax, [rbp-8]  # rax = x's object (still owned by the slot)
mov rdi, rax  # arg = same pointer (helper borrows it)
call aython_incref  # take our own shared ownership; rax = same pointer
mov [rbp-48], rax  # park owned left operand (calls below would clobber rax)
mov rax, [rbp-16]  # rax = y's object (still owned by the slot)
mov rdi, rax  # arg = same pointer (helper borrows it)
call aython_incref  # take our own shared ownership; rax = same pointer
mov [rbp-56], rax  # park owned right operand
mov rdi, [rbp-48]  # arg1 = left (helper borrows it)
mov rsi, [rbp-56]  # arg2 = right (helper borrows it)
call obj_lt  # rax = new owned result (or aborts TypeError/OverflowError/...)
mov [rbp-64], rax  # park the result across the cleanup calls
mov rdi, [rbp-48]  # release left operand
call aython_decref  # (single-use temporaries usually freed here)
mov rdi, [rbp-56]  # release right operand
call aython_decref  # (same)
mov rax, [rbp-64]  # rax = owned result for our caller
mov [rbp-32], rax  # park the owned test value
mov rdi, [rbp-32]  # arg = test value (helper borrows it)
call aython_not  # rax = immortal (!test): False means truthy
mov [rbp-40], rax  # park the immortal negation (no decref: immortal)
# test value is immortal (comparison or `not`): no decref call
mov rax, [rbp-40]  # reload (!test): calls above clobbered rax AND flags
lea rcx, aython_false[rip]  # rcx = immortal False address
cmp rax, rcx  # !test == False means the test was truthy; the jump reads these flags
je .Lif_then_1  # truthy test runs first; else-branch falls through
...
jmp .Lif_end_1  # else ran; skip the then-branch
.Lif_then_1:  # truthy tests land here
...
.Lif_end_1:  # both paths rejoin; slots agree by construction

The ... lines are where the two branch bodies go (m = x and m = y); the listing keeps only the lines the if statement itself emitted. Three details:

  • The test runs through not. !test == False means the test was truthy. One helper call handles ints, strings, lists, None and everything else, so there is one branch shape for every test.
  • No call between cmp and the jump. A call overwrites the flags register that jne reads, so the negation is parked, the test value released, the negation reloaded, and only then compared. The docstring of _emit_if states this as the one rule the layout obeys.
  • One decref is skipped. A comparison or a not always returns an immortal bool, so releasing the test value would do nothing. _test_yields_immortal recognises those shapes and the emitted comment says so.

Labels are numbered by _next_label, a counter reset per program, so .Lif_then_2 and .Lif_end_2 belong to the same if. Both branches leave every variable in its slot, so nothing needs merging where they rejoin.

while #

A while is the same test at a label, a conditional jump out, the body, and a jump back:

flowchart TB
  top[".Lwhile_top_N:<br/>evaluate test, call aython_not"] --> cmp{"!test == False ?"}
  cmp -- "no: test was falsy" --> done[".Lwhile_end_N:"]
  cmp -- "yes: truthy" --> body["body statements<br/>(each releases its own temps)"]
  body --> back["jmp .Lwhile_top_N"]
  back --> top
  class top,body accent
The labels of a while loop. Every pass starts at .Lwhile_top and reads the current slots; nothing is carried in registers between passes.

Step through the first pass of while i <= 100: in pass_while_sum.py, with total = 0 and i = 1:

  1. Every pass enters here. Nothing is in a register: the test reads i from its slot.
  2. i <= 100 compares a variable with an integer literal, so it takes the raw-bound path: obj_le_imm borrows the slot’s pointer in rdi and takes 100 as a plain number in rsi. No int object is built for 100, and i is not increfed.
  3. aython_not turns the test into False (the test was truthy). The comment line after it records that the test value needs no release: comparisons return immortal bools.
  4. Reload !test, load the address of False, compare. Equal means truthy, so jne (jump if not equal) does not leave the loop.
  5. The two body statements, each the release-compute-store pattern from the stepper above. They reuse the same temporaries as the test, which are dead by now.
  6. Jump back to the top. The next pass sees the updated slots.
  7. After the hundredth pass i is 101, the compare finds !test is True, and jne lands here. The loop holds nothing that needs releasing.

for #

A for loop is a while loop with more state, all in temporaries: the iterable (evaluated once and parked), a raw counter that is a plain machine integer and never an object, a snapshot of the length at entry, and the current index box. This is the skeleton of for i in range(4):, keeping the labels, jumps and helper calls:

tests/mvp/pass_for_range.py · emitted for line 2 (skeleton)# line 2: for i in <iter>: (park iterable, walk 0..len-1)
...
call obj_len  # rax = owned length snapshot for dict/set-change checks
...
.Lfor_top_1:  # every pass re-reads the live length
...
call obj_len  # rax = owned live length
...
je .Lfor_bound_1  # unchanged: skip the change check
...
je .Lfor_abort_1  # dicts abort on resize, like CPython
...
jne .Lfor_bound_1  # neither: live iteration stays correct
.Lfor_abort_1:  # dict/set resized mid-loop
...
jmp abort_runtime  # CPython raises RuntimeError on resize mid-loop
.Lfor_bound_1:  # size ok: test the counter against the length
...
jae .Lfor_end_1  # done: exit with locals and target owned
...
je .Lfor_dict_1  # dict path uses dict_key_at
...
je .Lfor_set_1  # set path uses set_at
...
call obj_getitem  # rax = owned element (lists/strs/ranges)
jmp .Lfor_store_1  # join the shared store
.Lfor_dict_1:  # dict path: positional key lookup
...
call dict_key_at  # rax = owned key at position i
jmp .Lfor_store_1  # join the shared store
.Lfor_set_1:  # set path: positional table lookup
...
call set_at  # rax = owned element at table position i
.Lfor_store_1:  # rax = owned element; the slot already waits as None
...
# line 3: print(...) (one write per value, spaces between, newline after)
...
inc qword ptr [rbp-32]  # advance the raw counter
jmp .Lfor_top_1  # re-read the (possibly grown) length
.Lfor_end_1:  # exhausted: release what the loop held

Every pass calls obj_len again, so a list that grows during the loop is iterated to its new end, exactly as CPython does. A dict or set whose length changed since entry jumps to abort_runtime instead, because CPython raises RuntimeError there. Elements come from obj_getitem for lists, strings, tuples and ranges, and from dict_key_at or set_at by position for dicts and sets; the type tag at offset 8 of the iterable decides which.

break, continue and the else clause of a loop do not exist in the subset; the frontend refuses each by name, so there is no jump to a loop’s end from inside its body.

Calls and the calling convention #

A user function fib becomes the symbol fn_fib, with its own frame and an extra hidden slot for the return value. The call fib(10) in pass_fn_fib.py:

tests/mvp/pass_fn_fib.py · emitted for line 6# line 6: print(...) (one write per value, spaces between, newline after)
# call fib(...) (1 args in registers, count in r10d)
# int literal: box it (movabs covers the full i64 range; small values hit the cache)
movabs rdi, 10  # arg = raw integer value (not a pointer yet)
call int_new  # rax = new owned int box (refcnt 1)
mov [rbp-16], rax  # park owned arg0
mov rdi, [rbp-16]  # arg0 -> register (owned ref travels with it)
mov r10d, 1  # argc for the callee's arity check
call fn_fib  # rax = owned result; args adopted, not borrowed
mov [rbp-8], rax  # park the owned argument across the print call
mov rdi, [rbp-8]  # arg = value to spell out (helper borrows it)
call aython_print_obj  # write the repr bytes to stdout
mov rdi, [rbp-8]  # arg = same value, now to release
call aython_decref  # argument was single-use; usually freed here
call aython_print_newline  # end the line (no args, no result)

The argument is evaluated, parked, then moved into rdi, the first of the System V argument registers rdi, rsi, rdx, rcx, r8, r9. A seventh argument and beyond switch the whole call to pushes on the stack. The argument count goes in r10d, a scratch register no argument uses, and the callee checks it first thing:

tests/mvp/pass_fn_fib.py · emitted · fn_fibfn_fib:  # entry; user args (if any) arrive in the arg registers or on the stack
...
push rbp  # save the caller's frame base on the stack
mov rbp, rsp  # our frame base = current stack top
sub rsp, 1872  # carve all variable + temp slots at once (fixed size)
...
mov [rbp-8], rax  # init n = None (borrowed ref, no incref needed)
cmp r10d, -1  # general mode (pos list + kw dict)?
je .Lgeneral_fn_fib  # yes: bind below, then join the body
...
cmp r10d, 1  # arity check first: CPython raises TypeError here
jne abort_type  # shared runtime stub: one stderr line, exit 1
mov [rbp-8], rdi  # arg0: caller's owned ref, adopted not increfed
jmp .Lbody_fn_fib  # fast path bound: join the body
...
.Lbody_fn_fib:  # both modes join here with params owned

A wrong count jumps to abort_type, which is how fib(1, 2) raises TypeError at run time, as in CPython. Then the callee adopts the argument: it stores rdi into the slot for n without an incref. The reference the caller created when it evaluated 10 now belongs to the callee, which releases it in its epilogue. No reference is copied at the boundary.

sequenceDiagram
  participant M as main_main
  participant F as fn_fib
  M->>M: int_new(10): owns the box
  M->>F: rdi = box, r10d = 1, call fn_fib
  F->>F: cmp r10d, 1 (else abort_type)
  F->>F: [rbp-8] = rdi (adopt: n owns it)
  F->>F: body, result parked in the return slot
  F->>F: epilogue: decref n
  F-->>M: rax = result (owned by the caller now)
  M->>M: print it, then decref it
Who owns the argument and the result across fib(10). Ownership moves with the pointer; neither side increfs at the boundary.

Two calling modes #

That register path is the fast mode. A call with keywords or */** unpacking, or any call to a function with defaults, *args, keyword-only parameters or **kwargs, uses the general mode instead: the caller builds an owned list of positional arguments and an owned dict of keywords, passes them in rdi and rsi, and sets r10d to -1, a value no real count can take. The callee binds parameters from them by name (_emit_general_bind) and adopts both containers. A plain function like fib accepts both modes, which is why fn_fib starts with cmp r10d, -1 and carries a long binding block after its fast path; a flexible one accepts only the general mode. Default values are evaluated once, when the def statement runs, into .bss statics, and increfed into the parameter on each call, so a mutable default is shared across calls as in CPython.

Returning #

Every return parks its value in the return slot and jumps to one shared epilogue, which releases every local and returns the parked value in rax:

tests/mvp/pass_fn_fib.py · emitted · .Lret_fn_fib.Lret_fn_fib:  # every return lands here with the value parked in the return slot
...
mov rdi, [rbp-8]  # release local n
call aython_decref  # (params die here too; ownership was ours)
mov rax, [rbp-16]  # rax = owned return value for the caller
mov rsp, rbp  # drop the whole frame
pop rbp  # restore the caller's frame base
ret  # back to the caller; stack args were already cleaned by them

return n takes a shortcut: instead of increfing n for the return slot and then decref-ing it in the epilogue, it moves the slot’s reference and leaves None behind:

tests/mvp/pass_fn_fib.py · emitted for line 4# line 4: return <expr> (park value, release locals, leave)
mov rax, [rbp-8]  # take over n's owned ref (no incref: ownership moves)
lea rcx, aython_none[rip]  # rcx = immortal None (borrowed, never freed)
mov [rbp-8], rcx  # slot waits as None; its epilogue decref is a no-op
mov [rbp-16], rax  # park the moved value before finally bodies clobber rax
jmp .Lret_fn_fib  # shared epilogue releases locals, returns the parked value

Falling off the end of a function returns None. The machine stack is the only recursion limit: there is no depth counter, so recursion deep enough to exhaust it crashes the process instead of raising RecursionError (the docstring of _emit_function records this as documented, not guarded).

Exceptions as jumps #

There are no exception objects, only a kind number (the table is in the frontend chapter) and a stack of handlers in runtime.s. A try pushes a handler; exc_push records the current rbp, the caller’s rsp and the handler’s address:

runtime.s · exc_pushlines 354–393# ---- try/except machinery: handler stack plus kind-tagged unwind ----------------
# Exception kinds are small integers so generated dispatch is a compare:
# 1 TypeError, 2 IndexError, 3 KeyError, 4 ValueError, 5 RuntimeError,
# 6 ZeroDivisionError, 7 OverflowError, 8 MemoryError, 9 RecursionError,
# 10 FileNotFoundError, 11 NotImplementedError.
# `except Exception` (or bare `except:`) matches every kind, like CPython.
# Unwinding restores the try-entry rbp/rsp and jumps to its handler with
# the kind in exc_kind. Locals and temporaries abandoned mid-expression
# leak by design on the exceptional path (documented): the frame is
# discarded whole, so nothing double-frees, but nothing is released either.
.globl exc_depth  # generated code never touches this directly (helpers do)
.globl exc_kind  # generated handler dispatch reads the in-flight kind
.globl exc_push  # make handler-push visible to generated code
.type exc_push, @function
.globl exc_pop  # make handler-pop visible to generated code
.type exc_pop, @function
.globl exc_raise  # make explicit raise visible to generated code
.type exc_raise, @function
.globl exc_check  # abort_* entries jump here with the kind in eax
.type exc_check, @function
.globl exc_propagate  # handler mismatch jumps here to keep unwinding
.type exc_propagate, @function
exc_push:  # rdi = handler rip: record caller rbp/rsp plus handler
    mov rax, [rip + exc_depth]  # rax = active handler count
    cmp rax, 64  # room for one more?
    jae exc_push_full  # 64 nested trys is a state violation, abort directly
    mov rcx, rbp  # rcx = caller frame base (call preserves rbp)
    lea rdx, [rip + exc_stack_rbp]  # rdx = rbp-slot base (rip+index is illegal)
    mov [rdx + rax*8], rcx  # save rbp at slot depth
    lea rcx, [rsp + 8]  # rcx = caller rsp (skip our return address)
    lea rdx, [rip + exc_stack_rsp]  # rdx = rsp-slot base
    mov [rdx + rax*8], rcx  # save rsp at slot depth
    lea rdx, [rip + exc_stack_rip]  # rdx = rip-slot base
    mov [rdx + rax*8], rdi  # save handler rip at slot depth
    inc qword ptr [rip + exc_depth]  # one more active handler
    ret  # return to the try entry
exc_push_full:  # handler stack overflow: abort without unwinding (no recursion)
    lea rdi, [rip + msg_runtime]  # rdi points to RuntimeError message
    mov rsi, msg_runtime_end - msg_runtime  # rsi gets RuntimeError message length
    jmp abort_msg  # exit directly; routing via exc_check would recurse

A failure in a helper (an operand of the wrong type, a zero divisor, a missing key) jumps to an abort_* stub that loads its kind into eax and jumps to exc_check. With no handler, exc_check prints aython: <Kind> and exits with status 1. With one, it pops the top entry, puts back that entry’s rbp and rsp, which throws away every frame called since the try began, and jumps to the handler with the kind in exc_kind:

runtime.s · abort_typelines 320–322abort_type:  # entry for TypeError abort
    mov eax, 1  # kind 1 = TypeError (see exc kinds below)
    jmp exc_check  # unwind to a handler if any, else exit below
runtime.s · exc_checklines 406–422exc_check:  # rax = kind id: unwind to a handler, or exit when none
    cmp qword ptr [rip + exc_depth], 0  # any active handler?
    je exc_abort_uncaught  # none: exit with the kind's message
    mov [rip + exc_kind], rax  # remember the kind for handler dispatch
    mov qword ptr [rip + eq_depth], 0  # unwinding discards in-flight equality nesting: reset the guard
    mov qword ptr [rip + print_depth], 0  # same for printing: no live nesting survives a handler jump
    mov qword ptr [rip + repr_depth], 0  # same for repr cycle stack: stale identities must never fake a cycle
    mov rcx, [rip + exc_depth]  # rcx = count before popping
    dec rcx  # rcx = index of the top entry
    mov [rip + exc_depth], rcx  # pop it before restoring (reentry-safe)
    lea rdx, [rip + exc_stack_rbp]  # rdx = rbp-slot base (rip+index is illegal)
    mov rbp, [rdx + rcx*8]  # restore the try-entry frame base
    lea rdx, [rip + exc_stack_rsp]  # rdx = rsp-slot base
    mov rsp, [rdx + rcx*8]  # discard frames above the try
    lea rdx, [rip + exc_stack_rip]  # rdx = rip-slot base
    mov rcx, [rdx + rcx*8]  # rcx = handler address
    jmp rcx  # enter the handler with exc_kind set

The generated side of try: return 10 // x except ZeroDivisionError: return -1, from pass_try_fn.py, keeping only the lines the try emitted itself (the ... lines are its body and handler statements):

tests/mvp/pass_try_fn.py · emitted for line 3 (its own lines)# line 3: try: (push handler, run body)
lea rdi, [rip + .Ltry_handler_3]  # handler address for unwinding
call exc_push  # record rbp/rsp/handler (unwind target)
...
call exc_pop  # body ran clean: forget the handler
jmp .Ltry_end_3  # skip the handlers on the normal path
.Ltry_handler_3:  # entered by exc_check with exc_kind set
mov rax, [rip + exc_kind]  # spill the in-flight kind before nested trys overwrite it
mov [rbp-2264], rax  # park it in this try's reserved slot
mov rax, [rip + exc_kind]  # in-flight kind for handler 0
cmp rax, 6  # is it ZeroDivisionError?
je .Ltry_h3_0  # match: run handler 0
jmp exc_propagate  # no handler matched: keep unwinding
.Ltry_h3_0:  # handler 0 body (outer trys still active)
...
jmp .Ltry_end_3  # handler done (+finally): join the normal path
.Ltry_end_3:  # try complete: body or one handler ran (+finally)
flowchart TB
  push["try: call exc_push(.Ltry_handler_N)"] --> body["body: ... call fn_g ... call int_floordiv"]
  body -- "divisor is 0" --> az["abort_zero: eax = 6"]
  az --> chk{"exc_check:<br/>a handler on the stack?"}
  chk -- "no" --> exit["write 'aython: ZeroDivisionError'<br/>exit status 1"]
  chk -- "yes" --> restore["pop it; restore rbp, rsp;<br/>jmp handler, exc_kind = 6"]
  restore --> disp{"handler: compare exc_kind<br/>with each except clause"}
  disp -- "match" --> h["handler body"]
  disp -- "no match" --> prop["exc_propagate:<br/>exc_check again, next handler"]
  body -- "no failure" --> pop["call exc_pop; skip the handlers"]
  class push,restore,disp accent
  class exit bad
How a failure inside a call reaches a handler. Nothing in between runs: the frames of the functions called since exc_push are discarded by restoring rsp.

The rest follows from that mechanism:

  • Matching is by number. except (KeyError, IndexError) is two compares. except RuntimeError also matches RecursionError and NotImplementedError, the only parent-and-child pairs among the supported kinds, and except Exception or a bare except matches everything without a compare.
  • The kind is saved per try. The handler’s first act is to copy exc_kind into a slot reserved for this nesting level, so a nested try inside the handler cannot lose it; a bare raise reloads it from there.
  • finally is emitted more than once: on the normal path, after each handler, and on the unwind path, which then re-raises the saved kind with exc_raise. A return inside a try pops the handler and runs the finally body before jumping to the epilogue.
  • What unwinding skips. Restoring rsp does not run the epilogues of the discarded frames, so their locals and half-evaluated temporaries are never released. The docstring of _emit_try says it directly: such locals “leak by design (the frame is discarded whole)”. The memory stays allocated in the arena; the program’s output is unaffected.

Comprehensions are loops #

A comprehension compiles inline into the enclosing function: an empty result, one for-style loop per for clause, nested, and an insert at the innermost level (list_append, obj_setitem or set_add). Each loop level takes 8 temporaries (iterable, counter, length snapshot, index, two for unpacking, two for the filter), and the element expression evaluates above all of them. This is the skeleton of print([i * 2 for i in [1, 2, 3]]):

tests/mvp/pass_comprehension.py · emitted for line 2 (skeleton)# line 2: print(...) (one write per value, spaces between, newline after)
# line 2: comprehension for i (new list, nested for + filters + append)
call list_new  # rax = new owned empty result
...
call list_new  # rax = new owned empty list (len 0)
...
call list_append  # items[len] = element; len += 1 (returns None)
...
call list_append  # items[len] = element; len += 1 (returns None)
...
call list_append  # items[len] = element; len += 1 (returns None)
...
call obj_len  # rax = owned length snapshot for dict/set-change checks
...
.Lcomp_top_1:  # every pass re-reads the live length
...
call obj_len  # rax = owned live length
...
je .Lcomp_bound_1  # unchanged: skip the change check
...
je .Lcomp_abort_1  # dicts abort on resize, like CPython
...
jne .Lcomp_bound_1  # neither: live iteration stays correct
.Lcomp_abort_1:  # dict/set resized mid-loop
...
.Lcomp_bound_1:  # size ok: test the counter against the length
...
jae .Lcomp_end_1  # done: exit with locals and target owned
...
je .Lcomp_dict_1  # dict path uses dict_key_at
...
je .Lcomp_set_1  # set path uses set_at
...
call obj_getitem  # rax = owned element (lists/strs/ranges)
jmp .Lcomp_store_1  # join the shared store
.Lcomp_dict_1:  # dict path: positional key lookup
...
jmp .Lcomp_store_1  # join the shared store
.Lcomp_set_1:  # set path: positional table lookup
...
.Lcomp_store_1:  # rax = owned element; the slot already waits as None
...
call int_mul  # rax = new owned result (or aborts TypeError/OverflowError/...)
...
call list_append  # result grows by one
...
.Lcomp_cont_1:  # filters or body done here; advance to the next position
...
jmp .Lcomp_top_1  # re-read the (possibly grown) length
.Lcomp_end_1:  # exhausted: release what the loop held

The first list_new is the comprehension’s result. The second, with the three list_append calls after it, builds the display [1, 2, 3] that the loop walks. From the obj_len length snapshot on, it is the loop, with the same live-length check as for, and the list_append near the end is the comprehension’s insert. Because the loop variable is an ordinary slot of the enclosing function, it is still there after the comprehension, holding its last value, where CPython gives a comprehension its own scope. Generator expressions are refused by the frontend (lazy iterator out of scope): there is no object that could hold a paused loop.

Classes and methods #

An instance is a dict. c = Counter() in pass_class_basic.py emits a dict_new, a call to the flattened __init__ with the dict as its first argument, and a check that __init__ returned None:

tests/mvp/pass_class_basic.py · emitted for line 12# line 12: c = <expr> (release old, compute new, store)
# line 12: Counter(...) (fresh instance dict, values, init when defined)
call dict_new  # rax = new owned empty dict: the instance namespace
mov [rbp-32], rax  # park the owned instance
mov rdi, [rbp-32]  # arg = instance (helper borrows it)
call aython_incref  # split ownership: one ref for the call, one for the result
# general call Counter____init__(...): build pos list + kw dict, r10d = -1
call list_new  # rax = fresh empty positional list
mov [rbp-40], rax  # park it across argument evaluation
call dict_new  # rax = fresh empty keyword dict
mov [rbp-48], rax  # park it across argument evaluation
call list_new  # rax = fresh empty list as the duplicate sentinel
mov [rbp-56], rax  # park it (unique pointer: never a real value)
mov rdi, [rbp-40]  # arg1 = pos list (helper borrows it)
mov rsi, [rbp-32]  # arg2 = leading value (helper takes its own incref)
call list_append  # leading operand lands first, like an explicit arg0
mov rdi, [rbp-32]  # release our leading ref
call aython_decref  # (the list keeps its own incref)
mov rdi, [rbp-40]  # arg1 = pos list (adopted by the callee)
mov rsi, [rbp-48]  # arg2 = kw dict (adopted by the callee)
mov r10d, -1  # general mode for the callee's bind prologue
call fn_Counter____init__  # rax = owned result; containers adopted, not borrowed
mov [rbp-64], rax  # park the result: the sentinel release below clobbers rax
mov rdi, [rbp-56]  # release the sentinel (callers keep no refs)
call aython_decref  # (unique: freed here)
mov rax, [rbp-64]  # rax = owned result again for our caller
mov [rbp-40], rax  # park the __init__ result (its temp slot died with the call)
lea rcx, aython_none[rip]  # the only acceptable __init__ answer
cmp rax, rcx  # returned None?
jne abort_type  # no: CPython raises TypeError, like any wrong kind
mov rdi, [rbp-40]  # release the __init__ return (None: a no-op)
call aython_decref  # (the instance survives in memory, not in a temp)
mov rax, [rbp-32]  # rax = owned instance for our caller (surviving ref)
mov [rbp-24], rax  # park the new owned value where calls cannot clobber it
mov rdi, [rbp-8]  # rdi = old c (borrowed for the call)
call aython_decref  # release old c; may free it right here
mov rax, [rbp-24]  # rax = new value again (survived the call in memory)
mov [rbp-8], rax  # c now owns the new value

The dict gets a second reference before the call (split ownership), because the call adopts one: __init__ releases its self when it returns, and the other reference becomes the value of Counter(). Counter() passes no argument for start, which has a default, so this call goes through the general mode. Class-level constants, when a class has any, are stored into the fresh dict before the call, base classes first.

A method call is an ordinary function call with the receiver as the first argument. The name alone decides which function: method names are unique in the program, so c.bump(5) can only be fn_Counter__bump:

tests/mvp/pass_class_basic.py · emitted for line 14# line 14: print(...) (one write per value, spaces between, newline after)
# method call bump(...) resolves to Counter__bump (instance travels as arg0)
# general call Counter__bump(...): build pos list + kw dict, r10d = -1
call list_new  # rax = fresh empty positional list
mov [rbp-32], rax  # park it across argument evaluation
call dict_new  # rax = fresh empty keyword dict
mov [rbp-40], rax  # park it across argument evaluation
call list_new  # rax = fresh empty list as the duplicate sentinel
mov [rbp-48], rax  # park it (unique pointer: never a real value)
mov rax, [rbp-8]  # rax = c's object (still owned by the slot)
mov rdi, rax  # arg = same pointer (helper borrows it)
call aython_incref  # take our own shared ownership; rax = same pointer
mov [rbp-56], rax  # park the owned positional
mov rdi, [rbp-32]  # arg1 = pos list (helper borrows it)
mov rsi, [rbp-56]  # arg2 = value (helper takes its own incref)
call list_append  # list grows by one
mov rdi, [rbp-56]  # release our positional ref
call aython_decref  # (the list keeps its own incref)
# int literal: box it (movabs covers the full i64 range; small values hit the cache)
movabs rdi, 5  # arg = raw integer value (not a pointer yet)
call int_new  # rax = new owned int box (refcnt 1)
mov [rbp-56], rax  # park the owned positional
mov rdi, [rbp-32]  # arg1 = pos list (helper borrows it)
mov rsi, [rbp-56]  # arg2 = value (helper takes its own incref)
call list_append  # list grows by one
mov rdi, [rbp-56]  # release our positional ref
call aython_decref  # (the list keeps its own incref)
mov rdi, [rbp-32]  # arg1 = pos list (adopted by the callee)
mov rsi, [rbp-40]  # arg2 = kw dict (adopted by the callee)
mov r10d, -1  # general mode for the callee's bind prologue
call fn_Counter__bump  # rax = owned result; containers adopted, not borrowed
mov [rbp-56], rax  # park the result: the sentinel release below clobbers rax
mov rdi, [rbp-48]  # release the sentinel (callers keep no refs)
call aython_decref  # (unique: freed here)
mov rax, [rbp-56]  # rax = owned result again for our caller
mov [rbp-24], rax  # park the owned argument across the print call
mov rdi, [rbp-24]  # arg = value to spell out (helper borrows it)
call aython_print_obj  # write the repr bytes to stdout
mov rdi, [rbp-24]  # arg = same value, now to release
call aython_decref  # argument was single-use; usually freed here
call aython_print_newline  # end the line (no args, no result)

Attribute access, self.n, is a dict lookup by the string "n" (_emit_attr_load), which is why a missing attribute aborts KeyError.

Small patterns that save calls #

The code generator does no general optimisation, but a few patterns are emitted in a cheaper form when the saving is provable. Each keeps the result identical to the general form:

Pattern General form Emitted form Where
local < 2 (<, <=, >, >= against an exact int literal) incref the local, box the literal, obj_lt, release both obj_lt_imm borrows the slot and takes the literal as a raw number in rsi _emit_compare_imm
return local incref for the return slot, decref in the epilogue move the reference, leave None in the slot _emit_return
if/while test that is a comparison or not release the test value skip it: the value is an immortal bool _test_yields_immortal
An integer from -5 to 256 allocate a box int_new returns a prebuilt immortal box runtime.s int_new

The literal must be an exact int: True is an int subclass in Python, and the raw-bound helper’s payload compare must match what the boxed helper would do. The runtime side of the same effort, helpers that test for ints before anything else, is in The runtime; what each change was worth, measured on native hardware, is in How fast.

What the code generator does not do #

It does not Consequence Recorded in
Keep values in registers across statements Every value goes through memory; the frame is large _frame_bytes, _emit_binary
Free the locals of frames discarded by an exception Those objects stay allocated until exit _emit_try docstring
Guard recursion depth Very deep recursion crashes instead of raising RecursionError _emit_function docstring
Inline or specialise calls Every call has a frame, an arity check and an epilogue How fast
Collect reference cycles A list containing itself is never freed Objects in memory
Decide which names are assigned on a path A maybe-unassigned name reads None _prologue_lines docstring

Where this lives #

Concept Where
Whole-file emission codegen.generate
Frame layout and size Frame, _slot, _temp, _ret_slot, _frame_bytes, SLOTS_PER_NODE, SPARE_SLOTS, EXC_SAVE_SLOTS
Prologue and epilogue _prologue_lines, _epilogue_lines
Expressions into owned rax _emit_expr, _emit_constant, _emit_binary, OWN_*
Assignment _emit_assign_name, _emit_augassign, _emit_assign_unpack
Branches and loops _emit_if, _emit_while, _emit_for, _test_yields_immortal, _next_label
Calls _emit_user_call, _emit_fast_call, _emit_general_call, _emit_general_bind, REG_ARG_ORDER, GENERAL_ARGC
Functions and returns _emit_function, _emit_return, _emit_def_defaults
Exceptions _emit_try, _emit_raise, EXC_KIND_IDS; exc_push, exc_pop, exc_check, exc_propagate, abort_* in runtime.s
Comprehensions _emit_comprehension, _emit_comp_level, COMP_LEVEL_TEMPS, COMP_BODY_TEMPS
Classes _class_tables, _emit_class_inst, _emit_class_values, _emit_method_user_call, _emit_attr_load
The data on this page docsite/figures/emitter.py, docsite/figures/_spans.py

Check yourself #

Check yourself

  1. In x = 6 * 7, the product is parked in [rbp-40] before the old x is released, then reloaded into rax. Why not keep it in rax?

    1. rax is too small for a pointer
    2. aython_decref is a call, and rax is a caller-saved register the call may overwrite
    3. The assembler does not allow mov [rbp-8], rax after a call
    Answeraython_decref is a call, and rax is a caller-saved register the call may overwrite. Under System V, rax, rcx, rdx, rsi, rdi and r8 to r11 belong to the callee. The code generator never relies on a value surviving a call in a register; it parks every live value in a frame slot first.
  2. A call f(a, b) to a plain two-parameter function. Where does the callee find the number of arguments, and what does it do with a wrong one?

    1. In rcx; it ignores extra arguments
    2. In r10d; cmp r10d, 2 then jne abort_type, which raises TypeError
    3. On the stack above the return address; it returns None
    AnswerIn r10d; cmp r10d, 2 then jne abort_type, which raises TypeError. The count travels in r10d because System V leaves that register free at a call. -1 there instead means general mode: a positional list in rdi and a keyword dict in rsi.
  3. Why does _emit_if park the result of aython_not, release the test value, and reload before the cmp, rather than compare straight after aython_not?

    1. To keep rsp aligned
    2. Because the release is a call, a call overwrites the flags, and no call may sit between the cmp and the jump that reads it
    3. Because aython_not returns its answer in memory
    AnswerBecause the release is a call, a call overwrites the flags, and no call may sit between the cmp and the jump that reads it. The flags register holds the result of the last compare. Any helper call in between would destroy it, so the order is always: park, release, reload, compare, jump.
  4. In fn_fib, how many increfs does return n emit?

    1. One: the return slot needs its own reference
    2. None: the slot’s reference moves to the return slot and the slot is left holding None
    3. Two: one for the caller and one for the epilogue
    AnswerNone: the slot’s reference moves to the return slot and the slot is left holding None. Return-local forwarding. The net effect on the count is the same as incref-then-decref, with two fewer calls; the epilogue’s decref of the now-None slot does nothing.
  5. g(0) divides by zero inside a try in main_main. What happens to fn_g’s local variables?

    1. fn_g’s epilogue runs and releases them before the handler
    2. They are never released: exc_check restores the rsp saved by exc_push, which discards fn_g’s frame without running its epilogue
    3. The handler releases them by walking the stack
    AnswerThey are never released: exc_check restores the rsp saved by exc_push, which discards fn_g’s frame without running its epilogue. Unwinding is two register restores and a jump. Nothing in the discarded frames runs, so what they owned stays allocated; _emit_try documents this as a leak by design. Output is unaffected.