docs

You are reading the docs for v0.1.2. Nabi 0.1.2 is no longer supported. Latest release: v0.1.3 →

#8.10. Lowering: coroutines and generics

On this page

This section defines coroutine lowering for generators, async and streams, and monomorphization lowering for generics and const generics.

#8.10.1. State machines

Coroutines are lowered to compiler-built state machines.

  1. HIR: yield / async / async yield blocks are lifted into body functions, like closures. An expression that creates the frame remains in place of the block.
  2. MIR: the body function is turned into a resume function. Each suspend point gets a state number, and locals live across that point are moved into frame fields.
  3. The frame type is (i32 state, locals..) and has a ScanTable. Frames are created through the ordinary allocation path (8.9.9).
  4. The entry of the resume function dispatches on state: a chain of two-way branches comparing it with each state number (8.9.3).

#8.10.2. Generator (yield fn)

nabi
yield fn count_up_to(n: i32) -> i32 {
    let i = 0;
    while i < n {
        yield i;
        i = i + 1;
    }
}

The conceptual resume function (next) is:

next(frame) -> i32 | none:
    switch frame.state:
      0: frame.i = 0; goto loop
      1: frame.i = frame.i + 1; goto loop
      2: return none
    loop:
      if frame.i < frame.n:
          frame.state = 1
          return frame.i          // yield i
      frame.state = 2
      return none

count_up_to(n) allocates the frame and returns a wrapper (GenIter<i32>) with state = 0.

#8.10.3. Async (async fn)

nabi
async fn fetch() -> Data {
    let r = await op1();
    process(r)
}
poll(frame, cx) -> Poll<Data>:
    switch frame.state:
      0: frame.fut = op1(); frame.state = 1; goto await1
      1: goto await1
    await1:
      match frame.fut.poll(cx):
        Pending  => return Pending
        Ready(r) => frame.state = 2; return Ready(process(r))

await stores the target future in the frame and polls it. If Pending, it returns Pending, leaving the state in place, and the next poll continues from the same point.

#8.10.4. Stream (async yield fn)

Streams combine the two. The state numbers of a single frame count yield points and await points together. poll_next returns Ready(value) at a yield, Pending on a Pending await, and Ready(none) at the end.

#8.10.5. Frame allocation

A frame is allocated on every coroutine call. There is no dedicated elision for a coroutine run to completion by its caller; a frame that never escapes may be removed like any allocation (7.2.12).

#8.10.6. Generic monomorphization

Monomorphization of generics generates a separate instance for each type tuple at call sites.

nabi
fn id<T>(x: T) -> T { x }

let a = id(42i32);     // id<i32>
let b = id(3.14f64);   // id<f64>

After monomorphization, the program has one function per instance.

fn id<i32>(x: i32, tls) -> i32:
    return x

fn id<f64>(x: f64, tls) -> f64:
    return x

fn main(tls):
    a = call id<i32>(42, tls)
    b = call id<f64>(3.14, tls)

A separate function is created for each concrete type tuple (id<i32> stands for its mangled symbol, below).

#When monomorphization happens

Monomorphization proceeds as follows.

nabi-hir -> specialize(hir, type_tuple) -> nabi-mir -> machine code

In AOT mode, all call sites are collected and then specialize runs in bulk. In JIT mode, specialize runs at the first call and the result is cached (see Execution engines and user surface). Both modes share the same specialize mechanism.

#Symbol naming

The symbol mangling rule used by the compilation pipeline is:

_Y<pkg_hash_8>_<path>_<name>_<typehash_16>

The package is the hash, so a function at the package root has an empty <path>: id<i32> becomes something like _Y3f8a1c2b__id_a7c91d8e44b2f190 (illustrative), and this symbol is the name of the function in the object. A non-generic item has an empty <typehash> (_Y3f8a1c2b__main_). A literal _ in an identifier is escaped as _0 (9.5).

#8.10.7. const generic monomorphization

An example of const generics:

nabi
fn dot<T: Num, const N: usize>(a: [T; N], b: [T; N]) -> T { ... }

let r = dot([1.0, 2.0, 3.0], [4.0, 5.0, 6.0]);  // T=f64, N=3

This is monomorphized to the following.

fn dot<f64, 3>(a: [f64; 3], b: [f64; 3], tls) -> f64:
    ; ... a loop of 3 iterations

Because const N=3 is a compile-time constant, the loop bound and the array sizes are constants in the instance: the optimizer folds what depends on them.

#8.10.8. Generic trait dispatch

nabi
fn process<T: Describe>(x: T) -> str {
    x.describe()
}

The concrete type T is determined at the call site, so for T = Point the lowering is:

fn process<Point>(x: (f64, f64), tls) -> (ptr, usize):
    ; call Point's Describe::describe directly
    r = call Point.describe(x, tls)
    return r

Point is passed as its value struct (8.8.3), str as its (ptr, usize) pair (8.8.1). There are no indirect calls through a vtable; everything is a direct function call. Combined with the trait-as-type ban, this model guarantees zero vtable cost.

#8.10.9. Branch dispatch on sum types

Matching on sum types is lowered to tag tests, a chain of two-way branches (8.9.3).

nabi
let v: i32 | str = ...;
match v {
    n: i32 => use_int(n),
    s: str => use_str(s),
}

i32 | str is (i32, [u64; 2]) on a 64-bit target: tag 0 is i32, tag 1 is str, and the payload is two words because str is the two-word pair holding a GC reference (8.8.6). As blocks:

bb0:
    if v.0 == 0 then bb_use_int else bb_test_str
bb_test_str:
    if v.0 == 1 then bb_use_str else bb_unreachable

bb_use_int:
    n = v.1 as i32                 ; the payload read as i32
    call use_int(n, tls)
    goto bb_end

bb_use_str:
    s = v.1 as str                 ; the payload read as the (ptr, usize) pair
    call use_str(s, tls)
    goto bb_end

bb_end:
    ...

The match is exhaustive, so bb_unreachable is never reached. Tag checks and branches are all static code.

#8.10.10. Trait-bound dispatch of trait methods

nabi
fn add_all<T: Add<T, Output = T>>(items: List<T>) -> T {
    let r: T = ...;
    for x in items {
        r = r.add(x);
    }
    r
}

After monomorphization, a separate function is created for each T at each call site. For T = i32, r.add(x) resolves to a direct call to i32's Add::add, which can also be inlined.

#8.10.11. Summary

The compiler lowers coroutines itself into state machines (8.10.1). Generic lowering generates separate code for each concrete type through monomorphization and uses no vtables.

These two mechanisms are the most complex lowerings in this ABI block; the rest, Lowering: data types and expressions and Lowering: control flow and GC integration, are close to direct mappings onto machine operations.

This concludes chapter 8 (runtime ABI / lowering / code generation).

Found a mistake? Edit this page on GitHub. Last updated