# Inside the K2 Compiler (https://crow.build/docs/core/compiler)

Crow's runtime performance isn't magic — it's **Kotlin K2 compiler lowering**. You write idiomatic declarative Kotlin; `crow-compiler` eliminates nearly all reactive-graph allocation and closure overhead before R8 even sees your bytecode.

## The Five Lowering Passes [#the-five-lowering-passes]

<Steps>
<Step>
### 1. FIR Static Analysis & Safety Checks (`CR1001`–`CR1003`) [#1-fir-static-analysis--safety-checks-cr1001cr1003]

During Kotlin's Frontend IR phase, Crow checks every `@Ui` body for:
- **`CR1001`**: Bare reactive reads (`Signal`, `Derived`, `Resource`, `Animatable`, live props) inside plain `val` initializers or non-reactive statements.
- **`CR1002`**: Direct writes to reactive state inside a `@Ui` body.
- **`CR1003`**: Storing `@Ui` function types in class fields or constructor parameters.
- **Static vs. live purity**: Deciding deterministically from FIR whether an argument can ever change across incremental builds.
</Step>

<Step>
### 2. `$ui` Scope Threading & Dual-Slot Props [#2-ui-scope-threading--dual-slot-props]

Every `@Ui` function receives an implicit `$ui: UiScope` parameter, and every non-`@Once` parameter gets a paired prop-getter slot (specialized for primitives like `IntProp`, `FloatProp`, `BooleanProp` to avoid boxing). Static call sites pass raw values with `null` getters — zero lambdas, zero bindings.
</Step>

<Step>
### 3. `LocalGraph` Lowering [#3-localgraph-lowering]

Top-level `var x by signal(init)` declarations inside a `@Ui` function are lowered into **fields of a single generated `LocalGraph` subclass** per component instance, with tracking-aware `get$x` / `set$x` accessors (including action staging support). Instead of allocating separate `SignalNode` objects and links, a component with 4 local signals allocates **one** graph object.
</Step>

<Step>
### 4. Modifier Fusion & Binding Fusion [#4-modifier-fusion--binding-fusion]

At inline containers (`Box`, `Row`, `Column`, `Text`), built-in `@IntrinsicModifier` chains fuse directly into sequential field writes on the `LNode` — zero `Modifier` chain objects, zero boxed `Dp`s, zero per-container scope objects (scopes are pooled per tree depth).

When a `@BoundTo` leaf argument (like `Text("$count likes")` or `Modifier.background(if (liked) Red else Gray)`) reads only component-local state at a once-per-instance site, **binding fusion** stores the target node directly in a field of the `LocalGraph` and emits an inline `update(mask)` method. No `BindingNode`, no `Link`, no getter closure.
</Step>

<Step>
### 5. Thunk Tables & Zero-Key `saved()` [#5-thunk-tables--zero-key-saved]

- **Thunk tables**: When a component passes multiple dynamic expressions, Crow groups them into one `when (id)` table closure per value kind instead of one synthetic class per argument — keeping DEX method count flat from 10% to 60% dynamic arguments (**0.79× Compose DEX size** in E2).
- **Zero-key `saved()`**: `var query by saved("")` automatically receives a compiler-synthesized declaration-scoped key, so state survives Android process death without manual string keys.
</Step>
</Steps>

## What the Bytecode Looks Like [#what-the-bytecode-looks-like]

Write this declarative row component:

```kotlin
@Ui
fun FeedRow(title: String, @Once initialLikes: Int) {
    var liked by signal(false)
    var likes by signal(initialLikes)

    Row(Modifier.fillMaxWidth().clickable { likes++ }.padding(16.dp)) {
        Text("$likes likes")
        Box(
            Modifier
                .size(24.dp)
                .background(if (liked) LikedRed else Gray, CircleShape)
                .clickable { liked = !liked },
        )
    }
}
```

After `LocalGraph` lowering + modifier fusion + binding fusion, `crow-compiler` emits the exact shape a hand-optimized imperative engineer would write:

```kotlin
// Conceptual lowered shape generated by crow-compiler (K2 IR)
private class FeedRow$Graph(initialLikes: Int) : LocalGraph() {
    var liked: Boolean = false
    var likes: Int = initialLikes
    lateinit var textNode: TextNode
    lateinit var dotNode: LNode

    override fun update(dirtyMask: Int) {
        if (dirtyMask and MASK_LIKES != 0) textNode.setText("$likes likes")
        if (dirtyMask and MASK_LIKED != 0) dotNode.setBackgroundColor(if (liked) LikedRed else Gray)
    }
}
```

On a Snapdragon 695 phone, the compiler-generated 1,000-row screen matches hand-written imperative Crow UI code in memory (**1,309 KB vs 1,317 KB** Java heap, −2.6 KB in class-histogram heap dumps) and mounts with **0 / 25 GC pauses**.