Context
C++23 makes many floating point math functions constexpr. Since those math functions’ implementations are quite involved, the path of least resistance is to make the corresponding clang builtins constexpr, and libc++'s cmath can simply call them. Many of the C23 floating point math functions have been implemented in LLVM libc, which are correctly rounded to all rounding modes, and they can used to back floating point math constexpr computations. Moreover, direct use of LLVM libc’s implementations without going through LLVM libc’s build system is proved to be a feasible strategy for sharing runtime implementations with [RFC] Project Hand In Hand (LLVM-libc/libc++ code sharing).
Proposal
We propose to directly use LLVM libc’s floating point math function implementations in APFloat, so that they can be used by clang to make builtin math functions constexpr, enabling C++23 constexpr math functions in libc++.
std::exp(float) → __builtin_expf → APFloat::exp → llvm_libc::shared::expf
Potential Steps
- Refactor LLVM libc floating point math implementations to header-only, exposed them via
libc/shared/math.hheader. - Add
APFloat::func, which will callllvm_libc::shared::funcfor computations. - Update
clang/lib/AST/ExprConstant.cppto enable more builtin math functions, directly call the correspondingAPFloat’s functions. - Update libc++.
- Steps 2-4 can be guarded with
LLVM_INTEGRATE_LIBCflag and the existence oflibcfolder to ease downstream projects. - Example (draft) implementation: [clang] Make __builtin_expf constexpr. by lntue · Pull Request #140841 · llvm/llvm-project · GitHub (the big libc’s refactor commit is NFC and can be ignored)
Further Considerations
- Update
clang/lib/AST/ByteCode/InterpBuiltin.cpp - Update
llvm/lib/Analysis/ConstantFolding.cpp - Replace system libc math usages?