COMPILER PIPELINE

HP 编译器架构The HP Compiler

hpc 以 C++20 实现,后端基于 LLVM,目标为零运行时、静态分派、编译期求值(CTFE)与极致性能。多目标平台:Windows x64 PE / Linux x64 ELF / 裸机 x64。默认优化 -O2hpc is written in C++20 on top of LLVM — zero-runtime, static dispatch, CTFE, peak performance. Multi-target: Windows x64 PE / Linux x64 ELF / bare-metal x64. Default opt -O2.

0

驱动与配置层 DriverDriver

解析命令行,构建模块依赖,默认输出 foo.hp → foo.exe--target 选定平台。Parses the CLI, builds module deps, defaults to foo.hp → foo.exe; --target picks the platform.

1

词法分析 LexerLexical Analysis

中英双语关键字、运算符最长匹配、缩进栈生成 INDENT/DEDENT、字面量 & f-string 预解析。Bilingual keywords, longest-match operators, indentation stack → INDENT/DEDENT, literals & f-string pre-parsing.

2

语法分析 Parser → ASTParsing → AST

递归下降 + Pratt + 缩进驱动;语法糖在解析期展开(|> 管道、推导式、f-string、with、match 常量臂→switch)。Recursive-descent + Pratt + indentation; sugar desugars at parse time (|>, comprehensions, f-string, with, match→switch).

3

语义分析 SemaSemantic Analysis

符号表、类型检查与推断、模块导入、函数重载决议(按形参个数)、unsafe 边界。Symbol tables, type checking & inference, module import, overload resolution, unsafe boundaries.

3b

借用检查 Ownership(NLL)NLL Borrow Check

move 所有权转移 + 借用冲突 + 非词法生命周期(借用者 last-use 后自动失效)。move transfer, borrow conflicts, and NLL — borrows expire after their last use.

4

LLVM IR 生成 CodeGenLLVM IR CodeGen

AST 直接降级为 LLVM IR;内置 CTFE(const fn 编译期求值)、泛型单态化、胖指针/niche、去 CRT 运行时辅助函数、FFI。AST lowers straight to LLVM IR; built-in CTFE, monomorphization, fat pointers, zero-CRT runtime helpers, FFI.

5

目标代码生成 TargetTarget CodeGen

LLVM TargetMachine:ISel、寄存器分配、MC 编码 → .obj--lto 时发射 bitcode。LLVM TargetMachine: ISel, regalloc, MC encoding → .obj; --lto emits bitcode.

6

链接 LinkingLinking

内置 LLD.dll:符号解析、COMDAT 合并、生成 mainCRTStartup,默认去 msvcrt 只链 kernel32。Bundled LLD.dll: symbol resolution, COMDAT merge, mainCRTStartup, no-CRT by default.

命令行参考CLI Reference

基本用法 · 多文件编译
hpc [options] <input.hp>...          # 支持多个输入文件,逐一编译后统一链接
hpc hello.hp                         # 默认输出 hello.hp → hello.exe(同目录)
hpc main.hp util.hp -o app.exe       # 多编译单元链接为一个可执行文件
hpc -c util.hp                       # 仅编译为目标文件(不链接)
优化级别与目标平台
-O0 / -O1 / -O2(默认) / -O3   优化级别(-O2 起启用自动向量化)
-Os / -Oz                    叠加体积约束(基于 O2)
--lto                        链接时优化:发射 bitcode,由 LLD 跨模块内联 / 消死代码
--ffast-math                 不安全浮点优化(opt-in)
--march=<cpu>                 目标 CPU 微架构,如 znver3
--bounds-check | --no-bounds-check   越界检查(默认 -O0/-O1 开,-O2+ 关)

hpc --target windows      main.hp    # Windows x64 PE(默认)
hpc --target linux        main.hp    # Linux x64 ELF
hpc --target bare-metal   main.hp    # 裸机:基线 ISA + Static 重定位 + ELF;ptr 访问带 volatile(MMIO)
输出与诊断
-o <file>            指定输出文件
-c                  仅编译,不链接
-S                  输出汇编
-emit-llvm          输出 LLVM IR(.ll)
-tokens             输出词法 Token 流(调试)
-dump-ast           输出 AST 树(调试)
-v / --verbose      冗长输出(各阶段耗时)
--debug             详细调试日志
--version           显示版本信息
-I <dir> / -i <dir>   添加模块搜索路径
--no-console        无控制台模式(GUI 子系统,产物无黑框)
--no-console-cp     跳过代码页设置调用(减体积)
--unbuffered-io     stdout 直写(交互式逐字输出)

目标平台Targets

Windows x64 PE

默认目标。去 msvcrt,仅链 kernel32 等必要系统库,产物体积极小。Default target. Drops msvcrt; links only kernel32 and necessary system libs for tiny binaries.

Linux x64 ELF

原生 ELF。跨模块系统库依赖按全程序取并集聚合,链接宿主平台体系。Native ELF. Cross-module system-library deps are unioned across the program at link time.

Bare-metal x64 ELF

裸机:基线 ISA + Static 重定位;ptr 访问带 volatile 语义(MMIO 安全)。用于内核 / 固件。Bare-metal: baseline ISA + static relocations; ptr loads are volatile for MMIO. For kernels / firmware.

从源码构建Build from Source

CMakeLists.txt
# 基于 LLVM SDK 构建(编译器无独立 config.ini/config.txt)
find_package(LLVM 22 REQUIRED CONFIG)
set(LLVM_ENABLE_LLD ON)
set(CMAKE_CXX_STANDARD 20)

# 构建
cmake -B build -S .
cmake --build build --config Release

# 运行:hpc 从自身目录的 <exe>/bin/stdlib 与 <exe>/stdlib 加载标准库模块,
# 链接用内置 LLD.dll,Windows 默认去 msvcrt
hpc hello.hp

源码模块布局Source Layout

include/hpc/src/ 一一对应: and src/ map 1:1:

mainDriverLexer / TokenParserAST / ASTDumpSema / TypeOwnershipModuleLoaderDiagnostic / DebugCodeGen (+Builtin/Expr/Stmt/Runtime)CodeGenTarget (X8664 Win/Linux/BareMetal)TargetLinkDriver / lld_wrapper

双语诊断Bilingual Diagnostics

错误/警告按 (kind, 位置, en, zh) 四元组给出,统一走 Diagnostic,中英一条消息同时附带。Errors/warnings are emitted as (kind, location, en, zh) tuples through one Diagnostic channel.

优化等级矩阵Optimization Matrix

优化标志Flag优化Opt向量化VectorizeLTO越界检查Bounds目标Goal
-O0关闭offoffoffon快速调试debug
-O1基础basicoffoffon折中balanced
-O2标准standardonoffoff默认(性能/体积平衡)default
-O3激进aggressive开(更激进)on (more)offoff极致速度peak speed
-Os / -Oz标准standardonoffoff体积约束(叠加于 O2)size budget
--lto -O3全部allonLTO (bitcode)off跨模块优化cross-module

极致优化策略Optimization Toolbelt

从语言内建到编译器再到链接期,HP 让每一次优化都可见、可组合。From built-in types to compiler passes to link-time, HP makes every optimization visible and composable.

SIMD 内建向量 vec[T; N]Built-in SIMD vectors

直接映射到 LLVM 向量类型 <N x T>,编译器自动生成 SSE / AVX / AVX-512 / NEON 指令,无需内联汇编。元素必须是标量数值类型,长度必须为 2 的幂。Maps directly to LLVM <N x T>, auto-emitting SSE/AVX/AVX-512/NEON. Elements must be numeric scalars; length must be a power of two.

simd.hp
module { "<std.io>" }

a: vec[f32; 4] = vec[f32;4](1.0, 2.0, 3.0, 4.0)
b: vec[f32; 4] = vec[f32;4](5.0, 6.0, 7.0, 8.0)
c = a * b                    # 逐元素 <5,12,21,32>

fn dot(a: vec[f32; 4], b: vec[f32; 4]) -> f32 {
    t = a * b
    return t[0] + t[1] + t[2] + t[3]
}

# 标量自动广播(splat)
blend = a * 0.5 + b * 0.5    # 颜色混合(RGBA)

零运行时:vec[T; N] 是纯值类型,栈上分配零堆开销,运算直接映射到 SIMD 指令(如 mulps / vmulpd)。Zero-runtime: vec[T; N] is a pure value type, stack-only, mapping straight to SIMD ops (e.g. mulps, vmulpd).

优化属性注解Optimization Attributes

属性映射到 LLVM 元数据,指导内联、分支与向量化决策。Attributes map to LLVM metadata to steer inlining, branching and vectorization.

attr.hp
module { "<std.io>" }

#[simd]                  # 强制循环自动向量化(映射到 llvm.loop.vectorize)
fn sum_list(a: list[i32]) -> i32 {
    s = 0
    for i in range(a.len()) {
        s = s + a[i]
    }
    return s
}

#[inline(always)]        # 强制内联,忽略成本模型
fn fast(x: i32) -> i32 { return x * 2 }

#[cold]                  # 冷路径:never-inline,移出热路径
fn handle_error() { std.io.print("错误") }

#[likely] / #[unlikely]  # 分支权重,指导基本块布局(if #[likely] cond { ... })

编译期求值与链接期优化CTFE & Link-time

const fn 在编译期求值(CodeGen 内置 CTFE);--lto 让 LLD 跨模块内联与常量传播;PGO 反馈优化列入后续路线图。const fn evaluates at compile time (CTFE inside CodeGen); --lto lets LLD inline & propagate across modules; PGO is on the roadmap.

ctfe.hp + shell
const fn table(idx: i32) -> i32 { return idx * idx + 2 * idx + 1 }
const VAL = table(5)          # 编译期计算为 36

# 链接期优化:LLD 跨模块内联 / 常量传播 / 消死代码
hpc --lto -O3 main.hp
# 路线图:-fprofile-generate / -fprofile-use(PGO 反馈优化)
策略Strategy机制Mechanism预期提升Gain
Pass 策略Pass strategyAggressiveInstCombine · SLP 向量化vectorize · LoopUnrollAndJam5–15%
循环自动向量化Loop auto-vectorize#[simd] + llvm.loop.vectorize 元数据metadata2x–8x
内联与 Hot/Cold SplitInlining & Hot/Cold#[inline(always)] · #[cold]3–10%
常量传播与折叠Const propagationIPSCCP(需 LTOneeds LTO1–5%
全局死代码消除Global DCE#[used] 保留 FFI 导出,其余剔除keeps FFI exports, drops the rest体积 −10–30%size −10–30%
SIMD 内建向量Built-in SIMDvec[T; N] → SSE/AVX/AVX-5124x–16x
分支预测Branch prediction#[likely]/#[unlikely] → branch_weights2–8%
内存对齐Memory alignment#[repr(align(64))] + 字段重排消 paddingfield reorder kills padding10–30%
LTO (--lto)跨模块内联 / DCE / 常量传播cross-module inline / DCE / const-prop5–15%
PGO(路线图roadmapInstrPGO / SamplePGO(分支、内联、布局branches, inline, layout10–20%

里程碑规划Milestones

M0 驱动+词法+诊断Driver+Lex+Diag M1 语法+AST+基础语义Parser+AST+Sema M2 类型检查+AST→LLVM IRTypes+AST→LLVM IR M3 所有权/借用+CTFE+单态化Borrow+CTFE+Mono M4 AST 直译+LLVM 优化Direct lowering+Opt M5 FFI/内联汇编/SIMDFFI/asm/SIMD M6 LTO + 多目标平台multi-target M7 调试/增量编译/PGOdebug/incremental/PGO

亲手编译 HP 源码Compile HP Yourself

下载编译器与示例库,照着教程写出你的第一段 HP 程序。Download the compiler and examples, then write your first HP program following the tutorial.