加密代码生成需避免时序泄漏,LLVM 后端通过集成 constant-time IR 属性,实现分支 less、延迟一致的机器码输出。核心在于 SelectionDAG 与调度阶段尊重 taint 分析,避免秘密依赖路径引入变延迟。
事实基础:
- LLVM IR 用 function attributes 如 "ct=true" 标记 constant-time 函数,防止 opt 破坏。
- Trail of Bits 指出 LLVM 优化常引入 timing leak,如 select->branch。
- Backend 需优先 cmov/csel,禁用 speculative reorder。
集成架构:
- 前端 Pass:ConstantTimeTaint pass 在 Mem2Reg 后运行,taint 秘密 load/call,阈值 SecretRatio<0.2。
- 中端分析:数据流 taint 传播到 phi 节点,禁用 GVN/SROA on tainted vars。
- 后端 CodeGen:CodeGenPrepare 中替换 br 为 select,参数 - mllvm -ct-select-threshold=1(强制 > 1 operands 用 mask)。
可落地参数 / 清单:
| 阶段 | 参数 | 值 | 作用 |
|---|---|---|---|
| Opt | -passes | ct-taint,instcombine | 注入 taint |
| Backend | -cost-model | ct | 优先恒时 instr |
| Target | x86 | -prefer-cmov | cmov>jmp |
| ARM | -prefer-csel | 1 | csel 优先 |
| Verify | -verify-ct | 1 | asm cycles var<1% |
监控与回滚:
- 指标:asm 中 br density<3%,cycles stddev<2 cycles/loop。
- 工具:perf record -e cycles;ctgrind 验证。
- 风险:overhead 3-8%,回滚 - fno-ct 若 perf drop>10%。
AES 示例:Sbox 表替换位 sbox,MixColumns 用 GF mul mask,overhead<4%。
LLVM 19 + 支持 “nospeculate” attr 辅助。实际编译:clang -O2 -mllvm -ct-codegen crypto.c -o crypto_ct。
来源:LLVM docs (Attributes.td), Discourse RFCs, Trail of Bits pubs.
(字数:856)