Task 的协程挂起点在 LLVM 中如何生成 continuation?

解读

国内一线 iOS 面试里,Swift Concurrency 已从“加分项”变成“必问项”。
面试官抛出“LLVM 如何生成 continuation”并不是想让你手写 IR,而是考察三层理解:

  1. Swift 前端如何把 await 语法糖降维成 SIL 中的 await_async_continuation/suspend_async 指令;
  2. SIL 如何被 LLVM 后端翻译成“回调+状态机”——也就是 continuation 的实质;
  3. 作为应用开发者,你能否利用这些机制写出零-cost 抽象、同时能在 Instruments 里快速定位“挂起”热点。
    答不出“状态机+尾调用”基本会被判为“只会用 async/await,不懂原理”;答得太深(直接背 LLVM Pass 源码)又容易被认为“偏题”。因此,给出“SIL→LLVM→Runtime”三段式答案最稳妥。

知识点

  1. Swift 编译管线:Parser → AST → SILGen → SIL Optimizer → IRGen → LLVM → Mach-O。
  2. SIL 关键指令:
    • alloc_continuation:在栈上分配 continuation 对象,保存 resume 函数指针与局部变量缓冲区。
    • await_async_continuation:把当前基本块切成两段,前段以 llvm.coro.suspend 结尾,后段生成 llvm.coro.resume 入口。
  3. LLVM Coro 框架:
    • llvm.coro.id:标记这是 Swift 的 continuation,而非 C++20 coroutine。
    • llvm.coro.suspend:生成 __builtin_coro_suspend 调用,返回值决定走 resume、destroy 或 cleanup 路径。
    • llvm.coro.begin/end:分配并初始化 coroutine frame,大小由 SIL 中的 alloc_continuation 推导。
  4. 状态机 lowering:
    • 每个 await 对应一个 switch-case 编号,保存在 coroutine frame 的 __index 字段;
    • resume 函数被 LLVM 做成 available_externally 的 thunk,确保跨模块内联,降低一次挂起 20 ns 量级开销。
  5. Runtime 协作:
    • Swift 的 swift_task_switch 在 resume thunk 里被调用,完成线程切换;
    • 若 continuation 未被 resume,SIL optimizer 会插入 llvm.trap 触发 SIGILL,方便国内审核机扫描“挂起泄漏”。

答案

Swift 编译器在 SIL 层把每个 await 点拆成“挂起基本块”和“恢复基本块”。
SILGen 先插入 alloc_continuation,生成一个结构体,包含:

  • resume 函数指针(类型 @convention(thin) @async (@in T) -> ())
  • 局部变量 spill 区域
  • 状态编号

SIL Optimizer 把 await_async_continuation 标记为 suspend_async,并赋予唯一 ID。
进入 IRGen 阶段,Swift 调用 LLVM 的 Coro 框架:

  1. 为当前函数创建 llvm.coro.id,标记为 Swift async;
  2. 在挂起点生成 llvm.coro.suspend,其返回值被用作 switch 判别式;
  3. 后端 Pass CoroSplit 把函数切成“init”“resume”“destroy”三个子函数;
  4. resume 子函数就是面试官口中的 continuation:它把 coroutine frame 地址当参数,读取 __index,直接跳转到恢复基本块,尾部调用 swift_continuation_resume 回到运行时。

因此,LLVM 并未“新造” continuation,而是利用现有 coroutine intrinsic,把 Swift 的 await 翻译成“状态机+尾调用”,生成的 continuation 是一个轻量级、可跨线程的函数指针,最终在 libswift_Concurrency.dylib 里被 swift_task_switch 消费。

拓展思考

  1. 逆向实战:用 otool -tV 看 .suspension 符号,可定位所有挂起点;结合 atos 就能把 Instruments 的“Swift Task Thread”回溯映射到源码行,国内审核组常用此手段检测“异步锁死”。
  2. 性能调优:continuation 的 frame 大小在 SIL 期就已确定,若局部变量过大,会导致栈爆;可手动 @inline(never) 把大对象拆到堆上,降低 30% 挂起耗时。
  3. 安全合规:Apple 中国要求“用户点击即续”场景必须显式 continuation.resume(returning:),否则会被视为“后台保活”;理解 LLVM 生成的 llvm.trap 路径,可提前在测试阶段捕获泄漏。