Kern
On this page

Smallest-first plan: Kern on microcontrollers

Status (updated on top of fd2afa7; all numbers below directly measured from the repo scripts):

  • O0–O2 done: register-local allocation, value-flow/branch optimization, peepholes, O2 inlining + -Os, and kern size ELF32/ELF64/Mach-O reporting (e07de68, cd22f0f).
  • M0 done (48eb6db): 32-bit target profiles (thumbv7m-none, thumbv7em-none, riscv32imc-none, riscv32imac-none), targets/*.target + kern.target, --board, i32/u32/usize, E170–E179 capability/MMIO-window/recursion/wide diagnostics (41 checks in tests/embedded/caps/check.py).
  • M1 done: external toolchain Cortex-M3 probe (scripts/mcu-probe.sh); native direct encoders now handle MCU ELF32 output without external tools.
  • M2 partial: C-side runtime probes (scripts/mcu/runtime-probe.sh, scripts/mcu/runtime-probe-rv32.sh) and compiler-emitted .data/.bss/trap/SysTick runtime exist; full compiler-side 32-bit structs/arenas/stack-proof/heap lowering is separate.
  • M3 done (e95bf26): volatile MMIO (read{8,16,32}/write{8,16,32}), [T; N] arrays & .data/.bss statics, interrupt fn, nestable critical, fence(), raise(), SysTick clock_ms/clock_ns/sleep_ms, and source-located _kern_trap_hook.
  • M4 done (e07de68, scripts/mcu-size.sh): Thumb-2 MCU size budgets passing across all 17 fixtures in bench/size_mcu_budgets.json — e.g. empty 124 B flash (0 B .data/.bss), hello 155 B flash, mmio_hello 292 B flash, blinky 412 B flash, fib 572 B flash, sieve 928 B flash (4096 B .bss), systick_sleep 1312 B flash (8 B .bss), irq_critical 1344 B flash (24 B .bss).
  • M5 done (scripts/mcu-native.sh, scripts/mcu-rv32-native.sh): direct Thumb-2 (EM_ARM) and RV32IMAC/RV32IMC (EM_RISCV) encoders + ELF32 writers build zero-external-tool binaries with byte-identical rebuilds and zero <unknown> instructions in llvm-objdump -d. Observed RV32IMAC QEMU virt sizes: empty 148 B .text, hello 224 B .text / 39 B .rodata, blinky 440 B .text / 74 B .rodata, fib 652 B .text / 148 B .rodata, sieve 1096 B .text / 108 B .rodata / 4096 B .bss, mmio 924 B .text / 235 B .rodata, critical+fence 496 B .text / 386 B .rodata / 4 B .bss.
  • M6 not started: design only (M6-TASKS.md).
  • M7 done (scripts/mcu-boards.sh): parameterized @ kern:memory flash/RAM maps across Thumb-2 and RV32 (elf32), thumbv7em-none routing, RV32 critical/fence lowering, CI mcu job wiring, and all 5 board profiles verified with kern size (and QEMU execution for qemu-mps2-an385 + qemu-sifive-e):
    • stm32f103 (examples/mcu/stm32f103_blinky): 799 B flash / 12 B RAM (64 KiB / 20 KiB budget, e_entry = 0x8000041)
    • stm32f407 (examples/mcu/stm32f407_uart): 690 B flash / 4 B RAM (1 MiB / 192 KiB budget, e_entry = 0x8000041)
    • qemu-mps2-an385 (examples/mcu/mps2_irq_demo): 1266 B flash / 8 B RAM (4 MiB / 4 MiB budget, e_entry = 0x45, QEMU exit 0)
    • esp32c3 (examples/mcu/esp32c3_blinky): 1156 B flash / 4 B RAM (4 MiB / 400 KiB budget, e_entry = 0x42000000)
    • qemu-sifive-e (profile + QEMU XIP probe): 958 B flash / 4 B RAM (4 MiB / 16 KiB budget, e_entry = 0x20000000; live 0x20400000 XIP UART0 boot on qemu-system-riscv32 -M sifive_e)

Design law: every feature is designed as if it must run on a microcontroller with a few tens of kilobytes of RAM, a few hundred kilobytes of flash and no operating system. Hosted features are opt-in capabilities, never assumptions.

This is not only an embedded port. It is a filter applied to the whole language and runtime.

0. Priority

MCU usefulness first; concurrency later.

  1. O0 — self-hosted register-local parity. Evidence: build/kern-stage0 asm examples/sieve.kn keeps locals in x19+; build/kern asm examples/sieve.kn spills every local to [sp,#…]. compiler/src/backend/state.kn:150 allocates every local a frame offset and never assigns a register. This is a parity bug before it is an optimisation, and it is the first task.
  2. O1 — optimizer core on hosted targets: peephole, permanent register residency for address-free locals, redundant bounds/overflow-check elimination, dead-code and constant folding, -Os.
  3. O2 — size mode, size report and CI budgets.
  4. M0-M3 — 32-bit model, external toolchain + QEMU, freestanding runtime, MMIO/interrupts.
  5. M4 — apply O1/O2 to the 32-bit backend and enforce MCU size budgets.
  6. M5-M6 — direct encoders, then cooperative tasks on MCU.
  7. Concurrency C0+ — only after MCU usefulness ships.

1. The ten rules

  1. Bounded by construction. Every operation has a static bound on stack, code and memory. No hidden heap allocation, no unbounded queue, no background thread, no lazy initialisation.
  2. Static memory is the default. .data/.bss, caller-provided buffers and arenas. alloc is an opt-in capability that requires a declared heap; on a bare-metal target the default heap is zero bytes.
  3. No hidden startup. No constructors, no runtime initialisation beyond copying .data, zeroing .bss and setting the stack. The reset vector calls main.
  4. Zero-cost abstraction. Generics are monomorphised, interfaces are static, there are no vtables. Runtime helpers are emitted only when used (already true: arena, I/O, system, image code are flags).
  5. Errors are values. !, fail and try only; no unwinding, no exceptions. A trap is a few instructions to a board hook (UART, semihosting or halt).
  6. Deterministic. No GC, no async runtime, no scheduler unless tasks are used. Interrupts are the only asynchronous events, and they are declared.
  7. 32-bit first. On MCU targets the pointer and usize are 32 bits, slots are 4 bytes, and slices are (ptr32, len32). i64/u64 remain available but are not the default.
  8. Capabilities, not platforms. Files, processes, clocks, threads and heap are declared capabilities. A bare-metal target rejects a program that uses one it did not grant (new diagnostics E170-E179).
  9. Size is a gate. Each example and each feature has a flash/RAM budget. A regression fails CI, the same way a test failure does.
  10. Every feature ships a none test. No feature is done until it runs under QEMU with no OS and no libc.

These rules already fit Kern's foundations: no GC, no exceptions, explicit ownership, arenas, checked arithmetic, direct writers, per-feature runtime. The gaps are 32-bit codegen, a freestanding runtime, MMIO/interrupts and size optimisation.

2. What must change in the language

AreaTodaySmallest-first change
Word/pointer size64-bit only (SPEC.md)Target word size; usize is 32 bits on MCU; slice length is usize
Integer typesi64, u64, u8Add i32/u32; keep 64-bit as opt-in; checked 32-bit arithmetic
Fixed arraysonly alloc[T](n)stack arrays [T; N] and static BUF: [T; N]
MMIOnonevolatile read/write builtins with compile-time addresses
Interruptsnoneinterrupt fn handlers and a vector table declared per board
RecursionallowedMCU profile forbids recursion (or enforces a stack budget); hard rule
Heapalloc = mmapmemory provider: OS heap when hosted, static arena or none when bare metal
Files/processesalways availablecompile-time capabilities; absent on none targets
Floatsabsentstays absent (soft-float is opt-in later)
Panic/trap outputstderrboard hook: semihosting, UART or halt

Stage0 thumbv7m-none lowers 64-bit +, - and ordering with the low word in r0 and the high word in r1; multiplication, division and 64-bit parameters or return values stay rejected with E091.

Open decision: usize as a new type, or make u64 the word type and emulate it on 32-bit. The first is more work but is the only version that meets the size and speed goals.

3. Targets

TargetCoreWhy
QEMU mps2-an385Cortex-M3bring-up and CI without hardware
QEMU netduinoplus2Cortex-M4FFPU-less profile initially
QEMU sifive_e / virtRV32IMACRISC-V bring-up
STM32F103Cortex-M3, 64 KiB flash / 20 KiB RAMthe smallest real board
STM32F407Cortex-M4F, 1 MiB / 192 KiBcommon hobby board
ESP32-C3RV32IMC, 400 KiB SRAMWi-Fi part with a tractable ISA
ESP32-S3Xtensa LX7later; needs the Espressif toolchain or a new backend

Xtensa is deliberately last: upstream LLVM has no Xtensa backend, so it depends on a vendor toolchain or a large encoder project. RISC-V C3 gives an ESP32-class target without that dependency.

4. Phases

The optimizer runs first, on the hosted targets, because it is also the foundation for MCU size and the fastest way to validate O0-O2. The 32-bit work follows; M4 then applies the same optimizer to MCU code.

PhaseDeliverableAcceptance
O0Self-hosted register-local parity with stage0build/kern asm examples/sieve.kn uses x19+ like stage0; full suite and self-host proof pass
O1Peephole, register residency, redundant check elimination, DCE/folding, -Ossieve benchmark improves; size drops; no behaviour change
O2Size report and per-example budgets on hosted targetskern size prints flash/RAM class; budgets enforced in CI
M032-bit target model, usize, i32/u32, 4-byte slots, capability diagnosticskern check rejects files/processes on --target thumbv7em-none with E170
M1External-toolchain build (clang/LLD + linker script) and QEMU runnerhello and blinky run under QEMU with semihosting exit
M2Freestanding runtime: vectors, reset, .data/.bss, trap hook, SysTick, static arena, no heaptests/embedded/ pass on QEMU for M3 and RV32
M3Fixed arrays, static buffers, MMIO builtins, interrupt fn, critical sectionsGPIO/UART interrupt example on QEMU; no dynamic allocation
M4Apply O1/O2 to the 32-bit backend and enforce MCU size budgetsflash/RAM budgets pass; code size within 1.5x of C -Os on the corpus
M5Direct Thumb-2 and RV32 encoders + ELF writer (no external tools)byte-identical rebuilds; kern --no-cc build on QEMU
M6Cooperative tasks on MCU: static stack pool, no heap, interrupts as preemptionconcurrency tests under QEMU within RAM budget
M7Board support: STM32F103/F407, ESP32-C3; QEMU CI; size reportCI green on QEMU, size table published

M1 uses an external toolchain on purpose: it validates the language and runtime semantics before the much larger direct-encoder work. The hosted targets keep the no-external-tools guarantee; only the embedded profile starts with clang/LLD.

5. Runtime and memory layout

flash:  .vectors | .text | .rodata | .data (load image)
ram:    .data | .bss | heap (optional) | static task stacks | main stack
  • No heap by default. alloc links only when the board declares a heap. The first allocator is a first-fit free list over a static byte array; the desktop mmap allocator stays for hosted targets.
  • Arenas are the preferred structure: a fixed buffer plus arena_new, typed handles, no fragmentation.
  • Stacks: main stack size is a linker symbol; each task stack comes from a static pool. The compiler reports per-function stack use and the maximum call chain. Recursion is rejected in the MCU profile.
  • Traps call one board hook (kern_trap_hook); the default writes to semihosting/UART and halts.
  • Time is SysTick-based clock_ns; sleep_ms yields to the scheduler or enters a low-power wait.
  • Atomics: single-core MCUs use interrupt masking (critical { ... }), not lock-prefixed atomics.

6. Capability model

A project declares what the target grants:

// kern.target (sketch)
target = "thumbv7em-none"
memory = { flash = 64K, ram = 20K, heap = 0, stack = 2K }
capabilities = [gpio, uart, systick]

The checker rejects every builtin outside the granted set with a source-located error. This replaces the current "everything is available on every target" assumption and keeps a typo from pulling in read_file or spawn_process on a board that cannot support it.

7. Size and speed budgets

The following MCU budgets are targets for the future 32-bit backend and are not yet measured or checked in CI:

ProgramFlash budgetRAM budget
empty main512 B256 B
hello over UART2 KiB1 KiB
blinky + SysTick3 KiB1 KiB
arenas + handles demo6 KiB2 KiB
cooperative tasks (2 tasks, 2 channels)10 KiB4 KiB

Hosted size baseline

Measured on macOS arm64 at commit 5a62fca with python3 bench/size.py --stage0 build/kern-stage0. These hosted executable file sizes are a baseline, not a gate or a proxy for MCU flash/RAM usage. Both compilers were built with .cip/build-kern.sh. Sizes are bytes:

ProgramSelf-hosted fileSelf-hosted textSelf-hosted dataStage0 fileStage0 textStage0 data
empty main3681679953363390489280
wc37040995433633952158180
sieve373601104633634016179980
calc559522460333634720750380

The file size includes headers, padding and other metadata. On macOS, text is the sum of sections in __TEXT, data is the sum in __DATA*, including zero-fill sections; reserved segments such as __PAGEZERO are excluded. On Linux, GNU size -A text covers .text* and .rodata*; data covers .data*, .bss*, .sdata*, .sbss*, .tdata* and .tbss*, including zero-fill. Other sections are excluded. These platform-specific totals are not directly comparable. Missing or unsupported size output is shown as - (JSON null). The empty program disables its empty-body and formatting rules; the examples retain their own rules. No blinky example exists yet.

Compile speed matters less than size here, but the 32-bit backend should keep the current ~5k lines/s class of throughput on a laptop.

8. Testing

  • tests/embedded/ — one folder per board profile, with expect files for flash/RAM and semihosting output.
  • tests/run_embedded.sh — builds each case, runs QEMU, checks exit code and size, prints one PASS line.
  • CI job embedded (not queue-safe on hosted runners unless QEMU is installed): M3 and RV32 only at first.
  • A size report in build/embedded-size.json, committed as a baseline; a >5% growth fails.
  • Optional hardware-in-the-loop job for one STM32 and one ESP32-C3 later.

9. Risks

  1. 32-bit backend is invasive. Slots, ABI, slices, checked arithmetic and usize touch every phase.
  2. No libc on Linux. The current Linux runtime is already raw syscalls; the MCU runtime must avoid both libc and syscalls, using only memory-mapped registers and inline assembly.
  3. Xtensa. Deferred until RISC-V C3 works; do not block the plan on it.
  4. Size without an optimiser. The current codegen is deliberately naive (2.4x C -O0 on sieve). M4 is therefore on the critical path for MCU usefulness.
  5. Toolchain drift. M1 depends on clang/LLD; pin versions and keep the direct encoder as the endgame.
  6. Recursion ban may be too strict for some algorithms; provide an explicit opt-out with a stack budget.

10. Relation to the concurrency plan

CONCURRENCY.md already assumes the smallest-first rules: single-threaded v1, bounded channels, fixed stacks, cooperative cancellation, no hidden heap. On MCU:

  • task stacks come from a static pool, not mmap;
  • channel buffers come from the scope's static arena;
  • sleep_ms waits on SysTick;
  • interrupts are the only preemption; the loop poll stays for cooperative fairness;
  • Shared/Atomic use interrupt masking, not lock-prefixed instructions.

Source: EMBEDDED.md in the repository.