Skip to content

RFC-018: LLVM AOT Compiler Design ​

⚠️ Implementation status (verified 2026-10-02): This RFC has been moved back to “Draft” in accordance with the RFC-018 status, and implementation has not started—— the repository's Cargo.toml contains no inkwell / llvm / cranelift dependencies, src/backends/ contains only common / interpreter / runtime, and none of the items under “Implementation Strategy” in the main text have been checked off. Scheduling is pending.

References:

Deprecated:

  • Old “bottom-up automatic DAG analysis” model — superseded by RFC-024's spawn block direct-child-expression model
  • @IO/@Pure implicit side-effect inference — superseded by RFC-024's resource type mechanism
  • Arc(T) type mapping — superseded by the ref keyword in RFC-009 v9

Summary ​

This document designs the LLVM AOT (Ahead-of-Time) compiler for the YaoXiang language. The LLVM backend and VM backend (interpreter) share the same compilation frontend, forming the dual-backend architecture defined by RFC-008: the VM is used for development and debugging, while LLVM is used for production releases.

Core responsibilities:

源码 → 前端(共享)→ IR → LLVM Codegen → .o → 链接调度器静态库 → exe

The compiler compiles YaoXiang source code into native machine code, where:

Language featureCompilation strategy
Ordinary codeSequential machine code, zero scheduling overhead
spawn { } blockDirect child expression → task dispatch + synchronous wait (aligned with RFC-024)
native("symbol")LLVM declare external + argument marshalling (aligned with RFC-026)
.drop destructorInsert RAII cleanup code (aligned with RFC-009)
&T / &mut T tokensZero-sized types that disappear after compilation
ref T sharing{ refcount_ptr, data_ptr } fat pointer; the compiler automatically selects Rc/Arc

Relationship to RFC-024: RFC-024 defines the user-facing semantics of spawn blocks (creating tasks from direct child expressions and synchronously blocking until they finish). This document defines how those semantics are compiled into machine code.

Relationship to RFC-026: RFC-026 defines the user-facing syntax for FFI (native(), [0] method bindings, .drop). This document defines how FFI calls generate LLVM IR.


Motivation ​

Why is an LLVM AOT compiler needed? ​

YaoXiang currently has only an interpreter as its execution backend:

ProblemImpact
Performance bottleneckInterpreted execution is 10–100× slower than machine code
Complex deploymentRequires shipping the interpreter and runtime
Production environmentThe interpreter is unsuitable for performance-sensitive scenarios

LLVM in the dual-backend model ​

RFC-008 §6 defines the dual-backend architecture:

                    ┌─────────────────────┐
                    │   编译前端(统一)     │
                    │   Lexer → Parser     │
                    │   → TypeCheck        │
                    │   → spawn 分析       │
                    │   → 逃逸分析          │
                    └──────────┬──────────┘
                               │
                  ┌────────────┴────────────┐
                  ▼                         ▼
      ┌───────────────────┐     ┌───────────────────┐
      │   VM 后端(开发)   │     │  LLVM 后端(生产)  │
      │   IR → 解释执行    │     │  IR → 原生代码      │
      │   步进调试         │     │  链接调度器静态库   │
      │   快速迭代         │     │  输出 .exe         │
      └───────────────────┘     └───────────────────┘

The two backends have exactly the same behavior—the only difference is how they execute. They use the same source code, the same type checking, and the same spawn analysis results.


Proposal ​

1. Compiler architecture ​

The LLVM backend is located at the final stage of the compilation pipeline. It receives IR from the frontend and generates native code:

源码
  → Lexer / Parser(frontend/core/)
  → TypeCheck + spawn 分析(frontend/core/typecheck/)
  → IR 生成(middle/core/ir_gen.rs)
  → LLVM Codegen(backends/llvm/)
      ├── 类型映射:YaoXiang 类型 → LLVM IR 类型
      ├── 函数翻译:IR 指令 → LLVM IR 指令
      ├── spawn 展开:直接子表达式 → 任务函数 + 调度调用
      ├── FFI 展开:native() 调用 → declare + marshalling
      └── 析构插入:作用域结束 → .drop() 调用
  → LLVM 优化 + 目标代码生成
  → 链接运行时静态库 → 可执行文件

2. Compilation flow ​

Phase 1: 前端(与 VM 后端共享)
  - 解析、类型检查、spawn 块分析、逃逸分析
  - 输出:类型标注的 IR

Phase 2: LLVM IR 生成
  - 类型映射、函数声明、指令翻译
  - 输出:LLVM Module

Phase 3: LLVM 优化
  - 标准 LLVM 优化 pipeline(O0/O1/O2/O3)
  - 内联、常量折叠、死代码消除

Phase 4: 目标代码生成
  - LLVM TargetMachine → .o 文件
  - 平台:Linux (ELF)、macOS (Mach-O)、Windows (COFF)

Phase 5: 链接
  - 链接运行时静态库(调度器、分配器)
  - 输出:可执行文件

3. Type mapping ​

3.1 YaoXiang → LLVM IR type mapping ​

YaoXiang typeLLVM IR typeDescription
Inti64Default 64-bit signed integer
Int32i32Explicit 32-bit integer, primarily used for FFI
Floatf64Default 64-bit floating-point number
Float32f32Explicit 32-bit floating-point number, primarily used for FFI
Booli1Boolean value
Chari32Unicode code point
String{ i8*, i64 }Pointer + byte length
Void{}Zero-sized empty type
&T—Zero-sized token; disappears after compilation and emits no IR
&mut T—Zero-sized token; disappears after compilation and emits no IR
ref T{ i64*, T* }Fat pointer (reference-count pointer + data pointer)
*TT*Raw pointer
[T; N][N x T]Fixed-length array
List(T){ T*, i64, i64 }Data pointer + length + capacity
StructCorresponding LLVM structFields are laid out in definition order
Tagged enum{ i64, [max_payload_size] }Tag + union with the maximum payload
?T{ i1, T }Has-value flag + data (general representation)
FFI opaque type{ i8* }Wrapped C pointer
Function pointerT (...)*Function pointer type

Zero runtime overhead for &T / &mut T: RFC-009 §2.7 defines tokens that the compiler internally assigns a brand identity (a compile-time unique integer). After monomorphization and inlining, the brand disappears entirely—generated machine code contains no trace of the token.

3.2 FFI parameter type mapping ​

Aligned with RFC-026 §2.2, with an additional LLVM IR column:

C typeYaoXiang typeLLVM IRDescription
intInt32i32
longInt64i64
floatFloat32f32
doubleFloat64f64
charChari32C char → YaoXiang Char (Unicode-compatible)
char*String{ i8*, i64 }marshalling: C string → YaoXiang String
boolBooli1
size_tUinti64
void**Voidi8*
struct T*T (transparent)T*Pass the pointer
typedef struct T TT (opaque){ i8* }Wrap the C pointer

4. IR normalization and instruction translation ​

4.0 IR normalization (stack → registers) ​

The current IR (src/middle/core/ir.rs) contains stack manipulation instructions (Push/Pop/Dup/Swap) designed for the bytecode VM. LLVM IR uses the SSA form and does not accept stack operations.

Processing strategy: Before instruction translation, the LLVM path first passes through a lightweight normalization pass:

Stack instructionNormalization strategy
Push(r)Record stack.push(r); emits no IR
Pop(r)r = stack.pop(); emit load (from the stack slot)
Dupstack.push(stack.top()); emits no IR
SwapSwap the top two stack elements; emits no IR

After normalization, all operands become register/local-variable references, and all stack operations are eliminated. This pass runs as the first step of translator.rs.

Why not eliminate stack instructions at the IR layer? The VM backend requires stack semantics. Normalizing at the LLVM translation entry point preserves the shared IR used by both backends—each backend consumes the same IR according to its own requirements.

Prerequisite: The IR generation stage guarantees stack balance—all control-flow paths reach the same program point with the same stack depth (the bytecode VM backend depends on the same prerequisite; otherwise, bytecode execution would fail). The normalization pass does not check this prerequisite; violations result in undefined behavior in the LLVM backend.

4.1 Instruction translation table ​

The following lists the LLVM IR translation strategy for each variant of the Instruction enum. The instruction names are exactly the same as those in src/middle/core/ir.rs.

Arithmetic instructions:

IR instructionLLVM IRDescription
Add { dst, lhs, rhs }add (integer) / fadd (floating-point)Select integer or floating-point addition based on the type
Sub { dst, lhs, rhs }sub / fsub
Mul { dst, lhs, rhs }mul / fmul
Div { dst, lhs, rhs }sdiv / udiv / fdivSigned/unsigned/floating-point division
Mod { dst, lhs, rhs }srem / uremSigned/unsigned remainder
Neg { dst, src }sub 0, src (integer) / fneg (floating-point)

Upcoming revision to the Mod row (note dated 2026-09-22, with RFC-011b): srem / urem are truncated remainders (the sign follows the dividend), so “remainder” in this row's description is a terminology mix-up. RFC-011b has confirmed that the established semantics of % is mathematical modulo (the result's sign follows the divisor; the language reference precedence table lists “multiply, divide, and modulo” as the first proof), and after this semantics is implemented, this row's mapping must be changed to srem + a sign-correction sequence (or a sdiv+mul+sub composition). The implementation side (the interpreter's checked_rem, constant folding, and bytecode I64_REM) must be updated accordingly.

Bitwise instructions:

IR instructionLLVM IRDescription
And { dst, lhs, rhs }and
Or { dst, lhs, rhs }or
Xor { dst, lhs, rhs }xor
Shl { dst, lhs, rhs }shlLeft shift
Shr { dst, lhs, rhs }lshrLogical right shift
Sar { dst, lhs, rhs }ashrArithmetic right shift

Comparison instructions:

IR instructionLLVM IRDescription
Eq { dst, lhs, rhs }icmp eq / fcmp oeq
Ne { dst, lhs, rhs }icmp ne / fcmp one
Lt { dst, lhs, rhs }icmp slt / fcmp olt
Le { dst, lhs, rhs }icmp sle / fcmp ole
Gt { dst, lhs, rhs }icmp sgt / fcmp ogt
Ge { dst, lhs, rhs }icmp sge / fcmp oge

Control-flow instructions:

IR instructionLLVM IRDescription
Jmp(label)br label %LUnconditional jump
JmpIf(cond, label)br i1 %cond, label %L, label %fallthroughConditional jump
JmpIfNot(cond, label)br i1 %cond, label %fallthrough, label %LConditional non-jump
Ret(Some(v))ret T %vReturn value
Ret(None)ret voidNo return value

Call instructions:

IR instructionLLVM IRDescription
Call { dst, func, args }%r = call T @func(...)Static call
CallVirt { dst, obj, method_name, args }vtable GEP + call (function pointer)Virtual method call, looked up through the vtable
CallDyn { dst, func, args }%r = call T %func(...)Dynamic call (closure/function pointer)
TailCall { func, args }musttail call / tail callTail-call optimization

Memory instructions:

IR instructionLLVM IRDescription
Move { dst, src }—Becomes a register copy after normalization; SSA construction can eliminate most copies
Load { dst, src }%v = load T, T* %src
Store { dst, src }store T %src, T* %dst
Alloc { dst, size }%p = alloca T (stack) / call @malloc (escapes to heap)Escape analysis determines the allocation location
Free(ptr)call @free(%ptr) (heap) / — (stack, automatically reclaimed)
AllocArray { dst, size, elem_size }%p = alloca [N x T] (stack) / call @malloc (heap)

Struct/array access instructions:

IR instructionLLVM IRDescription
LoadField { dst, src, field }%ptr = getelementptr T, T* %src, 0, field + load
StoreField { dst, field, src }%ptr = getelementptr T, T* %dst, 0, field + store
LoadIndex { dst, src, index }%ptr = getelementptr T, T* %src, 0, %index + load
StoreIndex { dst, index, src }%ptr = getelementptr T, T* %dst, 0, %index + store
CreateStruct { dst, type_name, fields }insertvalue chainConstruct the LLVM struct in field order

Type conversion instructions:

IR instructionLLVM IRDescription
Cast { dst, src, target_type }bitcast / trunc / zext / sext / fptrunc / fpext / sitofp / fptosi / inttoptr / ptrtointSelect the appropriate cast instruction based on the source/target type combination
TypeTest(val, type)—Compile-time type test; generates an icmp eq type-tag comparison

Ownership and borrowing instructions:

IR instructionLLVM IRDescription
Borrow { dst, src, mutable }—Zero-sized token; disappears completely after compilation, emitting no IR
Release(val)—Zero-sized token; disappears completely after compilation
Move { dst, src }—Ownership transfer; becomes a register copy after normalization
Drop(val)call void @T.drop(T* %val)Calls the type's destructor (see §7)
ShareRef { dst, src }call %T* @Arc_new(%src) / call %T* @Rc_new(%src)The compiler automatically selects Arc/Rc based on whether the value crosses threads
ArcNew { dst, src }call %T* @Arc_new(%src)Atomic reference count = 1
ArcClone { dst, src }call %T* @Arc_clone(%src)Atomically increments the reference count
ArcDrop(val)call void @Arc_drop(%val)Atomically decrements the count and conditionally releases

Concurrency instructions:

IR instructionLLVM IRDescription
Spawn { closures, plan, result }Expanded into a scheduler call sequenceSee §5; runtime task_spawn + task_wait_all
Yield—Spawn blocks wait synchronously on the AOT path, so yield is unnecessary; ignored

unsafe blocks and raw pointer instructions:

IR instructionLLVM IRDescription
UnsafeBlockStart—Compile-time marker; emits no IR
UnsafeBlockEnd—Compile-time marker; emits no IR
PtrFromRef { dst, src }%p = ptrtoint T* %src to i64 (or copy the pointer directly)
PtrDeref { dst, src }%v = load T, T* %src
PtrStore { dst, src }store T %src, T* %dst
PtrLoad { dst, src }%v = load T, T* %src

String instructions:

IR instructionLLVM IRDescription
StringLength { dst, src }%len = extractvalue { i8*, i64 } %src, 1String is { ptr, len }; the length is in field 1
StringConcat { dst, lhs, rhs }call String @yx_string_concat(%lhs, %rhs)Runtime helper function
StringGetChar { dst, src, index }getelementptr + load i32Includes bounds checking
StringFromInt { dst, src }call String @yx_string_from_int(%src)Runtime helper function
StringFromFloat { dst, src }call String @yx_string_from_f64(%src)Runtime helper function

Closure instructions:

IR instructionLLVM IRDescription
MakeClosure { dst, func: String, env }Allocate a closure struct + populate the function pointer (looked up by function name) and environment{ fn_ptr, env_fields... }
LoadUpvalue { dst, upvalue_idx }%v = extractvalue %env, upvalue_idxRead an upvalue from the closure environment
StoreUpvalue { src, upvalue_idx }%env = insertvalue %env, %src, upvalue_idxWrite an upvalue into the closure environment
CloseUpvalue(val)Copy the upvalue on the stack to the heap

Other instructions:

IR instructionLLVM IRDescription
HeapAlloc { dst, type_id }call i8* @malloc(i64 size) + type-tag writeHeap allocation + type information
NewDict { dst, keys, values }call Dict @yx_dict_new(%keys, %values)Runtime helper function

Note: Push/Pop/Dup/Swap have already been eliminated during the §4.0 normalization stage and do not appear in the translation tables. Borrow/Release are zero-sized compile-time tokens and do not produce any machine code.

5. spawn block code generation ​

Aligned with RFC-024, compiling a spawn block consists of the following steps.

5.1 Semantic review ​

yaoxiang
(r1, r2) = spawn {
    t1 = fetch("url1"),   // direct child expression → task 1
    t2 = fetch("url2"),   // direct child expression → task 2
    return (t1, t2)       // synchronous wait, assemble the result
}

Rules (RFC-024 §2.1):

  • A spawn block's direct child expressions (top-level, comma-separated statements) create parallel tasks.
  • Expressions nested inside {} are not direct child expressions and do not become independent tasks.
  • The entire spawn block blocks synchronously, waits for all tasks to finish, and then returns.

5.2 Compilation steps ​

Step 1: 识别直接子表达式
  遍历 spawn 块体,收集顶层语句

Step 2: 依赖分析
  对每个直接子表达式,分析它引用了哪些由前面任务产生的变量
  无依赖 → 可立即并行调度
  有依赖 → 排队等待依赖任务完成

Step 3: 资源冲突检测(RFC-024 §2.5)
  检查同一资源类型实例是否被多个任务使用
  同实例冲突 → 标记串行执行顺序

Step 4: 生成任务函数
  每个直接子表达式生成一个独立的 LLVM 函数(闭包)

Step 5: 生成调度代码
  调用运行时 scheduler 的 task_spawn / task_wait

Step 6: 结果组装
  收集所有任务输出,拼装 return 元组

5.3 LLVM IR generation pattern ​

llvm
; spawn block entry
%task_count = 2
%tasks = alloca [2 x %TaskHandle]

; create task 1: fetch("url1")
%task1_fn = @spawn_closure_1
call @runtime_task_spawn(%tasks[0], %task1_fn, ...)

; create task 2: fetch("url2")
%task2_fn = @spawn_closure_2
call @runtime_task_spawn(%tasks[1], %task2_fn, ...)

; synchronously wait for all tasks
call @runtime_task_wait_all(%tasks, %task_count)

; assemble the return value
%r1 = call @runtime_task_result(%tasks[0])
%r2 = call @runtime_task_result(%tasks[1])
ret { %r1, %r2 }

5.4 Dependent tasks ​

yaoxiang
result = spawn {
    data = fetch("url"),       // task 1: no dependencies
    processed = parse(data),   // task 2: depends on task 1's data
    return processed
}

The compiler detects that parse(data) references data produced by task 1 and marks the dependency when generating the scheduling code:

llvm
; task 2 is created with a dependency on task 1
call @runtime_task_spawn_with_dep(%tasks[1], %task2_fn, %tasks[0])
;                                                              ↑
;                                                 depends on task 0 (fetch) completing

5.5 Automatic serialization for resource types ​

The resource types defined by RFC-024 §2.5 (FilePath, HttpUrl, DBUrl, Console, and user-defined resource types) are automatically serialized within a spawn block:

yaoxiang
(a, b) = spawn {
    r1 = db.exec("SELECT ..."),   // uses SqliteDb (a resource type)
    r2 = db.exec("INSERT ...")    // same instance → automatically serialized
}

The compiler detects that the same resource instance is used by two tasks and generates a serialization dependency:

llvm
; task 2 depends on task 1 (automatic serialization for the same resource)
call @runtime_task_spawn_with_dep(%tasks[1], %task2_fn, %tasks[0])

5.6 spawn for data parallelism ​

yaoxiang
results = spawn for item in items {
    process(item)
}

The compiler expands this into N independent tasks (N = the length of items), subject to the maximum concurrency limit.

6. FFI code generation ​

⚠️ Dependency note: The FFI code-generation architecture defined in this section (native("x") → declare external @x → marshalling wrapper function → call) is stable and does not change with RFC-026 syntax changes. The specific parameter marshalling rules table (§6.2) and opaque type layout (§6.3) refer to RFC-026's definitions—if RFC-026's native() syntax or marshalling rules change, only the corresponding mapping tables in this document need to be updated; the architecture layer is unaffected. RFC-026's current status is Under review, and it resides in the same review/ directory as this document.

Acceptance prerequisite: Before this RFC is accepted, the portions of RFC-026 relevant to §6 of this document (native() declaration syntax, parameter marshalling rules, opaque type { i8* } layout, and .drop binding conventions) should first be frozen or accepted alongside RFC-026. Otherwise, the mapping tables in §6.2/§6.3/§7 may become outdated before implementation begins.

Aligned with RFC-026, this section defines the LLVM IR generation strategy for FFI calls.

6.1 native() function declarations ​

yaoxiang
sqlite3_open: (filename: String) -> SqliteDb = native("sqlite3_open")

Compiled into LLVM IR:

llvm
; declare an external C function
declare i8* @sqlite3_open(i8*)

; YaoXiang wrapper function (handles marshalling)
define { i8* } @__yx_sqlite3_open({ i8*, i64 } %filename) {
    ; marshalling: YaoXiang String → C string
    %c_str = extractvalue { i8*, i64 } %filename, 0
    ; call the C function
    %raw = call i8* @sqlite3_open(i8* %c_str)
    ; unmarshalling: C pointer → opaque type
    %result = insertvalue { i8* } undef, i8* %raw, 0
    ret { i8* } %result
}

Key points:

  • native("sqlite3_open") → declare external @sqlite3_open
  • The compiler automatically generates a marshalling wrapper function.
  • The wrapper function's signature uses YaoXiang types and converts internally to C types.

6.2 Parameter marshalling ​

DirectionConversion
YaoXiang String → C char*Extract the .ptr field and pass it
YaoXiang Int32 → C intPass directly (i32)
YaoXiang *Void → C void*Pass directly (i8*)
YaoXiang T (transparent) → C struct T*Take the address and pass it
YaoXiang T (opaque) → C struct T*Extract the pointer from { i8* } and pass it

6.3 LLVM layout for opaque types ​

The opaque type defined by RFC-026 §4.1:

yaoxiang
SqliteDb = unsafe {
    SqliteDb: Type = {
        handle: *Void
    }
    return SqliteDb
}

LLVM layout: { i8* } — a struct containing a C pointer.

Layout optimization: When an opaque type has only one handle: *Void field, it can be optimized to use i8* directly (omitting the outer struct). The optimized ABI is exactly identical to a C pointer, with zero marshalling overhead. This optimization is enabled by default and is transparent to users.

6.4 LLVM representation of nullable ?T return values ​

The FFI nullable return value defined by RFC-026 §7.6:

yaoxiang
sqlite3_open: (filename: String) -> ?SqliteDb = native("sqlite3_open")

General LLVM representation: { i1, { i8* } } — has-value flag + data.

Optimization for FFI null pointers: If the T of ?T is an opaque type (internally a pointer), the compiler uses a null pointer = None optimization:

llvm
; optimized LLVM representation: directly use a nullable pointer
define i8* @__yx_sqlite3_open(...) {
    %raw = call i8* @sqlite3_open(...)
    ; null → None, non-null → Some(wrapped as an opaque type)
    ret i8* %raw
}

Caller:

llvm
%raw = call i8* @__yx_sqlite3_open(...)
%is_null = icmp eq i8* %raw, null
br i1 %is_null, label %none_branch, label %some_branch

This optimization makes FFI calls involving ?SqliteDb incur zero additional overhead—it is exactly equivalent to a C null check.

6.5 yx-bindgen integration ​

Binding files automatically generated by yx-bindgen §6 are processed as ordinary YaoXiang source code during compilation. The compiler does not need to know that the code came from bindgen—the handling of native() declarations and unsafe {} type definitions is exactly the same.

7. Destructor code generation ​

Aligned with the RAII semantics in RFC-009 and the .drop conventions in RFC-026 §7.

7.1 .drop binding recognition ​

yaoxiang
SqliteDb.drop = sqlite3_close[0]

The compiler recognizes the .drop binding and marks the destructor function pointer in the type metadata.

7.2 Cleanup insertion at scope exit ​

用户代码:
{
    db = SqliteDb.open("test.db")
    stmt = db.prepare("SELECT ...")
    stmt.step()
    // ← scope ends
}

编译器插入的 cleanup(逆序):
    call @sqlite3_finalize(%stmt)    // stmt.drop()
    call @sqlite3_close(%db)          // db.drop()

Insertion locations:

  • Normal scope exit (})
  • Early return (before return)
  • ? error-propagation path (before ?)
  • Spawn block exit (destructors for variables within the task)

7.3 Move and destructors ​

yaoxiang
db = SqliteDb.open("test.db")
db2 = db                // Move: ownership transfers to db2
// db is now invalid; do not insert a drop for db here
// ← scope ends: insert a drop only for db2

The compiler tracks Move semantics (RFC-009 §1) and inserts destructor calls only at the variable's final holder.

7.4 Destructor failure handling ​

llvm
; debug mode: check the destructor's return value
%ret = call i32 @sqlite3_close(i8* %handle)
%ok = icmp eq i32 %ret, 0
br i1 %ok, label %done, label %panic
panic:
  call @__yx_panic("destructor failed")
  unreachable
done:
  ret void

; release mode: ignore the return value
call i32 @sqlite3_close(i8* %handle)
ret void

8. Compilation artifact structure ​

Compilation artifacts contain the following components (the exact struct definitions will be determined during implementation):

  • Machine code: The LLVM-compiled object file (.o), containing all function translation results
  • spawn metadata: The task function pointers, dependency relationships, and resource-conflict serialization pairs for each spawn block
  • FFI symbol table: References to external C symbols (symbol name + whether it is a weak reference)
  • Entry-point table: The list of entry functions in the executable
  • Type information: Reflection metadata written to the .reflect section and mmaped by the runtime on demand

9. Runtime library ​

Aligned with RFC-008 §6.2, the runtime is linked into the final exe as a static library.

最终 exe 内部结构:

┌────────────────────────────────────────────┐
│  用户代码(原生机器码)                       │
│  ├── 普通函数(顺序执行)                    │
│  ├── spawn 块展开(任务函数 + 调度调用)     │
│  ├── FFI marshalling 包装函数               │
│  └── RAII 析构代码                          │
├────────────────────────────────────────────┤
│  运行时静态库(约 500KB-1MB,取决于平台和功能选择)  │
│  ├── 线程池(num_workers)                  │
│  ├── 事件循环(libuv / io_uring)           │
│  ├── 工作窃取队列(仅 Full Runtime)         │
│  ├── 内存分配器(jemalloc / mimalloc)      │
│  └── 反射元数据(.reflect 段,按需 mmap)    │
│                                              │
│  没有:                                      │
│  ❌ 字节码解释器                             │
│  ❌ JIT 编译器                               │
│  ❌ GC                                      │
│  ❌ 虚拟机                                    │
└────────────────────────────────────────────┘

Key design: Spawn block task identification and dependency analysis are completed at compile time. At runtime, the system only “creates a task → dispatches it to the thread pool → waits for completion”—the data structures are fixed, and behavior is predictable.

Difference from RFC-008's size estimate: RFC-008 §4 estimates the scheduler at approximately 200–500KB, containing only the core task-scheduling logic. This document's 500KB–1MB estimate additionally includes the memory allocator (jemalloc/mimalloc), event loop (libuv/io_uring), and reflection metadata section. The actual size depends on the platform and feature selection; exact figures will be provided during implementation.

Relationship between the three runtime levels and LLVM (aligned with RFC-008 §1):

RuntimeLLVM AOT behavior
EmbeddedNo spawn support; directly generates sequential machine code
StandardSupports spawn blocks; in-block DAG + single-threaded scheduling (num_workers=1)
FullSupports spawn blocks; in-block DAG + multithreaded scheduling (num_workers>1), with WorkStealing support

Detailed design ​

Module directory structure ​

Aligned with the directory layout in RFC-008 §6. The [! Planned] marker indicates that the file or directory has not yet been created and will be introduced during this RFC's implementation phase.

src/
├── frontend/                          # compilation frontend (shared by all backends)
│   ├── core/
│   │   ├── spawn/                     # spawn module (concurrency analysis shared by the VM and LLVM backends)
│   │   │   ├── mod.rs                 # spawn module entry point
│   │   │   ├── placement.rs           # spawn occurrence placement validity check
│   │   │   └── analysis.rs            # [! Planned] task identification, dependency analysis, resource conflict detection
│   │   └── typecheck/
│   │       └── ...
│
├── middle/
│   ├── core/
│   │   ├── ir.rs                      # IR definition (shared by the VM and LLVM)
│   │   └── ir_gen.rs                  # IR generation
│   └── passes/
│       ├── codegen/
│       │   ├── mod.rs                 # orchestration layer (currently outputs BytecodeFile)
│       │   ├── translator.rs          # IR → bytecode translation (VM backend)
│       │   ├── emitter.rs             # bytecode emission + jump backpatching (VM backend)
│       │   ├── buffer.rs              # constant pool + bytecode buffer (VM backend)
│       │   ├── bytecode.rs            # bytecode format definition + serialization (VM backend)
│       │   ├── flow.rs                # register allocation + label generation + symbol table (VM backend)
│       │   └── operand.rs             # operand resolution (VM backend)
│       ├── lifetime/                  # lifetime/token liveness analysis
│       └── mono/                      # monomorphization
│
├── backends/
│   ├── common/                        # shared values/heap/opcodes
│   ├── interpreter/                   # tree-walking interpreter (VM backend)
│   ├── llvm/                          # [! Planned] LLVM backend code generation (see the file list below)
│   │   ├── mod.rs                     # [! Planned] LLVM backend entry point
│   │   ├── context.rs                 # [! Planned] LLVM context management
│   │   ├── types.rs                   # [! Planned] type mapping (YaoXiang → LLVM IR)
│   │   ├── values.rs                  # [! Planned] value mapping
│   │   ├── func.rs                    # [! Planned] function translation
│   │   ├── spawn.rs                   # [! Planned] spawn block expansion
│   │   ├── ffi.rs                     # [! Planned] FFI call code generation
│   │   └── drop.rs                    # [! Planned] destructor insertion
│   └── runtime/                       # compiled runtime (statically linked into the exe)
│       ├── engine.rs                  # task scheduling engine
│       ├── facade.rs                  # public interface
│       └── task.rs                    # task representation
│
└── util/
    └── diagnostic/                    # error diagnostics (shared)

Key change: Spawn block analysis (task identification, dependency analysis, resource conflict detection) will be implemented in frontend/core/spawn/ (shared by the frontend). The existing frontend/core/typecheck/passes/spawn_placement.rs (spawn placement check) will be moved to frontend/core/spawn/placement.rs; see RFC-024. The LLVM backend only consumes the analysis results and generates the corresponding scheduling code.

Current state: The buffer.rs, emitter.rs, bytecode.rs, flow.rs, and operand.rs files under middle/passes/codegen/ currently serve the VM backend's bytecode generation (CodegenContext::generate() → BytecodeFile). The LLVM backend will be implemented under backends/llvm/, alongside the interpreter backend and runtime—both consume the same ModuleIR input and produce different target formats (bytecode vs. native code).

Platform ABI support ​

PlatformTarget tripleOutput formatDefault FFI calling convention
Linux x86_64x86_64-unknown-linux-gnuELFSystem V AMD64
macOS x86_64x86_64-apple-darwinMach-OSystem V AMD64
macOS ARM64aarch64-apple-darwinMach-OARM64 AAPCS
Windows x86_64x86_64-pc-windows-msvcCOFFMicrosoft x64

FFI calls use the platform's C calling convention by default. Users can override it with options such as native("symbol", cc = "stdcall") (aligned with the future extension in RFC-026).

Floating-point semantic consistency (VM ↔ LLVM) ​

The core promise of the dual-backend architecture is that the VM (development and debugging) and LLVM (production releases) behave identically. Floating-point operations have several potential points of inconsistency between the two execution modes:

ScenarioRiskStrategy
NaN propagationThe VM and LLVM may handle NaN sign bits and payloads differentlyThe compiler normalizes the NaN representation at the IR level; NaN comparisons consistently use fcmp uno
Rounding modeLLVM defaults to round-to-nearest-even, while the VM depends on the host CPUNon-default rounding modes are not exposed; the VM and LLVM both use RTNE
Division by zeroIEEE 754 defines ±Inf, but some platforms may trapDebug mode checks for division by zero and reports a diagnostic; release mode follows IEEE 754
-0.0 vs +0.0Comparison operations may not be equivalentUse IEEE 754 rules consistently: +0.0 == -0.0
Denormal numbersSome platforms use flush-to-zeroLLVM does not enable the denormal-fp-math attribute and preserves full IEEE 754 semantics

Testing strategy: Implement a cross-backend floating-point consistency test suite—the same YaoXiang source is executed by the VM and LLVM backends, and their outputs are compared value by value. This test suite is a mandatory CI gate.


Trade-offs ​

Advantages ​

  1. Performance: AOT compilation is 10–100× faster than interpreted execution
  2. Unified frontend: The VM and LLVM share the same frontend and behave identically
  3. Zero scheduling overhead: Ordinary code directly generates sequential machine code, with no DAG overhead outside spawn blocks
  4. Static linking: No external runtime dependency; a single exe is sufficient for deployment
  5. Zero GC: RAII provides deterministic destruction with no pauses
  6. Zero-overhead FFI: ?T null-pointer optimization and opaque-type layout optimization make FFI calls equivalent in cost to C
  7. Compile-time analysis: Spawn block task identification and dependency analysis are completed at compile time; the runtime only executes

Disadvantages ​

  1. LLVM integration complexity: Requires an in-depth understanding of the inkwell API and LLVM IR
  2. Compilation time: AOT compilation is slower than interpretation (a one-time cost)
  3. Debugging experience: Debugging native code requires DWARF/PDB symbol support (the compiler must generate debug information)
  4. Incremental compilation: Incremental compilation of large projects requires additional design
  5. Floating-point semantic consistency: The VM and LLVM may differ in boundary behavior such as NaN propagation, rounding mode, and division by zero; normalization strategies are required to ensure consistent behavior across both backends (see §10)
RFCConsistency
RFC-024 spawn block concurrency model✅ spawn block direct child expression → task dispatch
RFC-008 runtime architecture✅ dual backend + scheduler static library + module directory structure
RFC-009 ownership model v9✅ &T/&mut T tokens (zero-sized), ref T (fat pointer), ?T (Option)
RFC-026 FFI core mechanism✅ native() → declare + marshalling, .drop → RAII cleanup

Alternatives ​

AlternativeDescriptionWhy it was not selected
Interpreter onlyNo AOTInsufficient performance
Pure static compilation (no runtime)Do not link the schedulerSpawn blocks require runtime task scheduling
Cranelift backendFaster compilation speedRuntime performance is inferior to LLVM; retained as a possible future backend
Link against LLVM's external runtimeUse LLVM's built-in runtimeIntroduces an unnecessary dependency

Implementation strategy ​

Phase division ​

Phase 1: Basic framework ​

  • [ ] Add the inkwell dependency
  • [ ] Implement LLVM context initialization (context.rs)
  • [ ] Implement basic type mapping (types.rs)

Phase 2: Function translation ​

  • [ ] Implement function declaration translation (func.rs)
  • [ ] Implement basic instruction translation (arithmetic, control flow, calls) (translator.rs)
  • [ ] Implement value mapping (values.rs)

Phase 3: Ownership type translation ​

  • [ ] Implement &T/&mut T tokens (zero-sized and absent after compilation)
  • [ ] Implement ref T (fat pointer { i64*, T* })
  • [ ] Implement ?T ({ i1, T } tagged union)
  • [ ] Implement List(T) ({ T*, i64, i64 })
  • [ ] Implement Move semantics tracking (used to determine destructor insertion)

Phase 4: spawn block code generation ​

  • [ ] Consume the analysis results from spawn_placement.rs
  • [ ] Direct child expression → task function generation
  • [ ] Dependent task scheduling code generation
  • [ ] Resource conflict serialization
  • [ ] spawn for expansion

Phase 5: FFI code generation ​

  • [ ] native() → declare external (ffi.rs)
  • [ ] Parameter marshalling / return-value unmarshalling
  • [ ] Opaque type layout (including the single-field optimization)
  • [ ] ?T null-pointer optimization (FFI-specific)

Phase 6: Destructor code generation ​

  • [ ] .drop binding recognition
  • [ ] Cleanup insertion at scope exit (in reverse order) (drop.rs)
  • [ ] Cleanup on early-return paths
  • [ ] Cleanup on ? error-propagation paths

Phase 7: Runtime library linking ​

  • [ ] Implement runtime functions such as runtime_task_spawn / runtime_task_wait_all
  • [ ] Link the runtime static library
  • [ ] End-to-end integration tests

Dependencies ​

  • RFC-024 (spawn block concurrency) → input for Phase 4
  • RFC-009 v9 (ownership) → input for Phases 3 and 6
  • RFC-008 (runtime architecture) → input for Phase 7
  • RFC-026 (FFI mechanism) → input for Phase 5

Lazy Task Creation (1990)[^1] ​

AttributeDescription
InstitutionMIT
AuthorsJames R. Larus, Robert H. Halstead Jr.
CoreLazily create subtasks and create them on demand
Reference valueTheoretical foundation for on-demand scheduling of tasks within spawn blocks

Core idea: Rather than creating tasks immediately, defer task creation until the parent task needs a child task's value. This addresses the performance overhead of fine-grained parallel tasks[^1]. YaoXiang's spawn block scheduling draws on this idea—tasks are identified at compile time, but dispatched to the thread pool on demand at runtime.

Lazy Scheduling (2014)[^2] ​

AttributeDescription
InstitutionUniversity of Maryland
AuthorsTzannes, Caragea
CoreAdaptive runtime scheduling with no additional state
Reference valueReference for the Full Runtime WorkStealing scheduler design

SISAL language[^3] ​

AttributeDescription
InstitutionLawrence Livermore National Laboratory (LLNL)
CoreSingle-assignment language, dataflow graph, implicit parallelism
Reference valueDemonstrates the feasibility of the dataflow model in industrial applications

Key distinction: SISAL's parallelism is implicit—the language uses single-assignment semantics, and the compiler automatically analyzes the whole program's data-dependency graph to determine parallelism. YaoXiang's parallelism is explicit—users mark parallel regions with spawn {} blocks, and the compiler analyzes dependencies only within spawn blocks. This avoids the complexity of whole-program analysis while preserving user control over parallel behavior.

Mul-T parallel Scheme[^4] ​

AttributeDescription
InstitutionMIT
CoreFuture construction, Lazy Task Creation implementation
Reference valueA concrete implementation reference

Comparison summary ​

TechnologyLazy creationParallel markerAnalysis scopeOwnership
Lazy Task Creation[^1]✅ImplicitWhole programN/A
Lazy Scheduling[^2]✅ImplicitWhole programN/A
SISAL[^3]✅Implicit (single assignment)Whole programN/A
Mul-T[^4]✅Explicit (future)Call siteN/A
YaoXiang✅Explicit (spawn blocks)Within spawn blocks✅ (Move + tokens + ref)

YaoXiang's innovation: It elevates the parallel marker from “each function call” (future) to a “structured block” (spawn). Users write ordinary code and place a spawn block wherever they need parallelism. Analysis is constrained to the spawn block, resulting in efficient compilation and controllable behavior.


Appendix ​

Appendix A: Comparison with Rust async ​

FeatureRust asyncYaoXiang LLVM AOT
Compilation artifactState machine + machine codeMachine code + spawn task metadata
RuntimetokioStatically linked scheduler (approximately 500KB–1MB)
Concurrency markerasync/await keywordsspawn { } block
Task creationState machine generated at compile timeIdentify direct child expressions at compile time → task functions
Function coloringasync contagionNo function coloring
Synchronization.awaitSpawn blocks automatically block synchronously
Memory managementGC (runtime)RAII (deterministic)
Sharing mechanismArc::new() + manual Weakref keyword (compiler automatically selects Rc/Arc)

Appendix B: Design decision record ​

DecisionDecisionDate
Adopt LLVM AOTDirect Codegen without excessive abstraction2026-02-15
Concurrency model alignmentAlign with RFC-024's spawn block direct-child-expression model2026-06-10
DAG analysis scopeWithin spawn blocks only; does not cross spawn blocks (aligned with RFC-024)2026-06-05
Ownership model alignmentAlign with RFC-009 v9: &T/&mut T tokens + the ref keyword2026-06-10
Dual-backend modelVM (development) + LLVM (production), aligned with RFC-0082026-05-11
Scheduler formStatically linked into the exe, approximately 500KB–1MB (depending on platform and features), with no GC2026-05-11
FFI code generationIntegrate RFC-026: native() declare + marshalling2026-06-10
Destructors.drop → RAII cleanup insertion, aligned with RFC-026 §72026-06-10
Side-effect handlingRemove @IO/@Pure inference and use RFC-024 resource types instead2026-06-10
Reflection metadataCompile into the exe's .reflect section and load on demand via mmap2026-05-11
Paper citationsRetain Lazy Task Creation and others while clarifying YaoXiang's distinction2026-02-16

References ​

[^1]: Larus, J. R., & Halstead, R. H. (1990). Lazy Task Creation: A Technique for Increasing the Granularity of Parallel Programs. MIT.

[^2]: Tzannes, A., & Caragea, G. (2014). Lazy Scheduling: A Runtime Adaptive Scheduler for Declarative Parallelism. University of Maryland.

[^3]: Feo, J. T., et al. (1990). A report on the SISAL language project. Lawrence Livermore National Laboratory.

[^4]: Mohr, E., et al. (1991). Mul-T: A high-performance parallel lisp. MIT.


Lifecycle and disposition ​

StatusLocationDescription
Draftdocs/design/rfc/Author's draft, awaiting submission for review
Under reviewdocs/design/rfc/review/Open community discussion and feedback
Accepteddocs/design/rfc/accepted/Becomes an official design document
Rejecteddocs/design/rfc/Retained in the RFC directory

Current status: Accepted — aligned with RFC-024's spawn block concurrency model, RFC-009 v9's ownership model, and RFC-026's FFI mechanism