如何实现运行时符号表达式JIT到Fortran函数
解读
国内超算中心、气象数值模式组、CFD 求解器团队面试时,经常把“运行时把用户输入的符号表达式即时编译成可执行 Fortran 代码并链接到主程序”作为区分“只会写 .f90 文件”与“能把 Fortran 用到极致”的试金石。
核心难点有三:
- Fortran 本身不提供运行时字节码生成接口;
- 国产超算环境(申威、飞腾、x86+DCU)对动态链接、PIC、ABI 有严格限制;
- MPI 并行域内要保证 JIT 产物在多节点间符号地址一致。
面试官期望听到“先 AST→Fortran 源码→内存临时 .f90→调用系统 flang/gfortran 生成 .so→dlopen/dlsym→绑定到 Fortran 抽象接口”的完整闭环,并给出国产平台实测可行的编译选项、ABI 对齐、线程重入、错误回退细节,而不是简单一句“写文件再编译”。
知识点
- 符号表达式解析:逆波兰、递归下降、LLVM/ExprTK 生成 AST。
- Fortran 2003 ISO_C_BINDING:
abstract interface定义 C 兼容函数指针;bind(C)保证符号大小写、下划线、实参传递与 C 侧一致。
- 运行时源码生成模板:
- 预置 pure elemental 模块,占位符
${VARS}、${EXPR}替换; - 自动插入
implicit none与real(real64)防止国产编译器默认 real(4) 陷阱。
- 预置 pure elemental 模块,占位符
- 动态编译与链接:
- 国产 ARM+DCU 平台用 flang-new -fPIC -shared -O3 -march=armv8.4-a+sve -fopenmp-target=amdgcn-amd-amdhsa;
- x86+海光用 gfortran -fPIC -shared -O3 -mavx512f -mcmodel=medium。
- 内存加载:
- POSIX
dlopen(RTLD_NOW|RTLD_LOCAL),禁止RTLD_GLOBAL防止 MPI 符号冲突; dlsym取出 C 指针后立即c_f_procpointer转成 Fortran procedure pointer。
- POSIX
- 错误处理:
- 编译失败回退到 解释求值(AST walker),保证业务不中断;
- 捕获
stderr日志写/tmp/jit_<rank>_<pid>.log,方便国产超算无盘节点调试。
- 并行安全:
- Coarray 或 MPI 场景下,仅 rank 0 负责 JIT 编译,编译完成后把
.so文件广播到所有节点同一路径,避免文件系统不一致; - 使用
dlopen前加MPI_Barrier,保证符号地址全局同步。
- Coarray 或 MPI 场景下,仅 rank 0 负责 JIT 编译,编译完成后把
- 性能调优:
- 对热点表达式做 SCE 展开 与 常量折叠 后再生成 Fortran;
- 开启
-ffast-math前评估国产平台对 IEEE 异常的处理差异。
答案
示范代码(精简可运行,符合国产平台 gfortran 9.3 + glibc 2.31):
module jit_factory
use, intrinsic :: iso_c_binding
implicit none
private
public :: jit_compile, jit_eval
abstract interface
pure function scalar_func(x) bind(C)
import :: c_double
real(c_double), intent(in) :: x
real(c_double) :: scalar_func
end function
end interface
type(c_ptr) :: dl_handle = c_null_ptr
procedure(scalar_func), pointer :: fptr => null()
contains
subroutine jit_compile(expr, ierr)
character(len=*), intent(in) :: expr ! 用户表达式,如 "sin(x)*exp(-x**2)"
integer, intent(out) :: ierr
character(len=:), allocatable :: src, path_so, cmd
integer :: u, stat, rank
character(len=256) :: errmsg
ierr = 0
call mpi_comm_rank(MPI_COMM_WORLD, rank, stat)
! 1. 仅 rank0 生成源码并编译
if (rank == 0) then
src = &
"module jit_kernel"//NL//&
"use, intrinsic :: iso_c_binding"//NL//&
"implicit none"//NL//&
"contains"//NL//&
" pure function kernel(x) bind(C, name='kernel_')"//NL//&
" real(c_double), intent(in) :: x"//NL//&
" real(c_double) :: kernel"//NL//&
" kernel = " // trim(expr) // NL//&
" end function"//NL//&
"end module"
path_so = "/tmp/jit_kernel_"//pid()//".so"
open(newunit=u, file='/tmp/jit_kernel.f90', status='replace')
write(u, '(a)') src; close(u)
cmd = "gfortran -fPIC -shared -O3 -march=native "// &
"-o "//trim(path_so)//" /tmp/jit_kernel.f90 2>&1"
call execute_command_line(cmd, wait=.true., exitstat=stat, cmdmsg=errmsg)
if (stat /= 0) then
ierr = 1
write(*,'(a)') "JIT compile failed: "//trim(errmsg)
end if
end if
! 2. 广播 so 路径与状态
call mpi_bcast(ierr, 1, MPI_INTEGER, 0, MPI_COMM_WORLD, stat)
if (ierr /= 0) return
call mpi_bcast(path_so, len(path_so), MPI_CHARACTER, 0, MPI_COMM_WORLD, stat)
! 3. 所有 rank 加载
dl_handle = dlopen(trim(path_so)//c_null_char, RTLD_NOW)
if (.not. c_associated(dl_handle)) then
ierr = 2; return
end if
block
type(c_funptr) :: cproc
cproc = dlsym(dl_handle, "kernel_"//c_null_char)
if (.not. c_associated(cproc)) then
ierr = 3; return
end if
call c_f_procpointer(cproc, fptr)
end block
end subroutine
pure function jit_eval(x) result(y)
real(c_double), intent(in) :: x
real(c_double) :: y
if (associated(fptr)) then
y = fptr(x)
else
y = ieee_value(0.0_c_double, ieee_quiet_nan)
end if
end function
end module
使用示例:
program demo
use jit_factory
implicit none
integer :: ierr
real(real64) :: x = 1.0_real64, y
call jit_compile("sin(x)*exp(-x**2)", ierr)
if (ierr == 0) then
y = jit_eval(x)
print *, "f(1.0)=", y
end if
end
关键点:
- 源码模板中显式写
bind(C, name='kernel_'),国产编译器不会加下划线二次修饰; - 编译命令带
-fPIC -shared,在神威·太湖之光亦可直接dlopen; - 失败分支
ierr回退到解释器,保证业务连续。
拓展思考
- GPU offload JIT:
在 DCU 平台可把表达式再包一层 OpenACC!$acc routine seq,编译时加-fopenmp-targets=amdgcn-amd-amdhsa,生成.so后同样dlopen,主程序通过!$acc host_data use_device把设备函数指针传进计算核心,实现CPU 端 AST→Fortran→GPU 二进制的全链路 JIT。 - 符号微分与自动伴随:
对气象 4D-Var 应用,可在 AST 层做反向模式自动微分,生成伴随 Fortran 函数,再 JIT 成.so,使用户仅需输入正向表达式即可获得梯度核,无需手写伴随代码。 - 缓存与签名:
生产系统可把表达式 MD5 作为.so文件名,启动时先扫描$JIT_CACHE目录,命中则直接dlopen,避免国产 Lustre 并行文件系统重复编译风暴。 - 安全沙箱:
在提供 Web 前端的服务里,用 systemd-nspawn + overlayfs 把 JIT 编译放在只读容器,防止用户输入"; rm -rf /"注入;同时通过 seccomp-bpf 禁止fork/exec以外的系统调用,满足等保 3 级要求。