[libc-commits] [libc] [libc][math][docs] Update and move add_math_function.md to docs/dev folder. (PR #240599)

via libc-commits libc-commits at lists.llvm.org
Tue Nov 10 00:48:21 PST 2026


================
@@ -0,0 +1,597 @@
+(add_math_function)=
+
+# Implementing and Adding a Math Function
+
+This guide describes the file layout, implementation conventions, caveats, and
+testing requirements for adding or refactoring math functions in LLVM-libc.
+
+## 1. Math Function Architecture & Layout
+
+Every math function in LLVM-libc separates its **header-only core
+implementation** from its **public C entrypoint** and **shared internal wrapper**
+so the same implementation can be linked into `libm.a`, consumed header-only by
+other LLVM subprojects (`libc++`, offloading runtimes), and tested per
+evaluation variant:
+
+```text
+libc/
+├── include/math.yaml                         # Public C header specification
+├── src/
+│   ├── __support/
+│   │   ├── FPUtil/                           # Generic FP, DoubleDouble, bit utilities
+│   │   └── math/
+│   │       ├── <func>.h                      # Dispatch header (selects *_eval)
+│   │       ├── <func>_double_eval.h          # Double-precision evaluation
+│   │       ├── <func>_float_eval.h           # Single-precision evaluation (optional)
+│   │       ├── <func>_integer_eval.h         # Integer/soft-float evaluation (optional)
+│   │       ├── <func>_utils.h                # Shared family/function tables & helpers
+│   │       ├── <func>_accurate_128.h         # 128-bit fallback pass (optional)
+│   │       └── <func>_accurate_256.h         # 256-bit fallback pass (optional)
+│   └── math/
+│       ├── <func>.h                          # Internal entrypoint declaration
+│       ├── generic/<func>.cpp                # LLVM_LIBC_FUNCTION wrapper
+│       └── <arch>/<func>.cpp                 # Arch-specific override (optional)
+├── shared/
+│   ├── math.h                                # Umbrella header for shared math
+│   └── math/<func>.h                         # Header-only export in shared::
+└── test/
+    ├── shared/shared_math_test.cpp           # Header-only coexistence smoke test
+    └── src/math/
+        ├── smoke/<func>_test.cpp             # MPFR-free smoke tests
+        ├── <func>_test.cpp                   # MPFR unit tests
+        ├── exhaustive/<func>_test.cpp        # Parallel exhaustive / worst-case tests
+        └── performance_testing/<func>_perf.cpp
+```
+
+### Modular `src/__support/math/` Organization
+
+Simple functions with a single implementation (such as basic bit manipulations
+or compact `float16`/`bfloat16` functions) can place their implementation
+directly inside `libc/src/__support/math/<func>.h` under
+`LIBC_NAMESPACE_DECL::math`.
+
+Functions with multiple evaluation strategies, shared family utilities, or
+multi-tier precision passes are split into modular headers:
+
+1. **Dispatch Header (`<func>.h`)**:
+   Selects an evaluation namespace via `LIBC_MATH_<FUNC>_IMPL` based on target
+   hardware features (`LIBC_TARGET_CPU_HAS_FPU_FLOAT`,
+   `LIBC_TARGET_CPU_HAS_FPU_DOUBLE`, `LIBC_TARGET_CPU_HAS_FMA_*`,
+   `LIBC_TARGET_ARCH_IS_GPU`) and `LIBC_MATH_HAS_*` optimization flags. Guard
+   the default selection with `#ifndef LIBC_MATH_<FUNC>_IMPL` and use
+   `LIBC_MATH_IMPL_IS` (from `src/__support/macros/optimization.h`) so external
+   `-DLIBC_MATH_<FUNC>_IMPL=...` overrides only `#include` the selected header:
+
+   ```cpp
+   #ifndef LIBC_MATH_EXPF_IMPL
+   #if defined(LIBC_TARGET_CPU_HAS_FPU_FLOAT) &&                                \
+       defined(LIBC_MATH_HAS_SKIP_ACCURATE_PASS) &&                             \
+       (defined(LIBC_MATH_HAS_SMALL_TABLES) ||                                  \
+        defined(LIBC_MATH_HAS_INTERMEDIATE_COMP_IN_FLOAT))
+   #define LIBC_MATH_EXPF_IMPL float_eval
+   #elif !defined(LIBC_TARGET_CPU_HAS_FPU_DOUBLE) &&                            \
+       defined(LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY) &&                      \
+       defined(LIBC_MATH_HAS_NO_EXCEPT) && defined(LIBC_MATH_HAS_NO_ERRNO)
+   #define LIBC_MATH_EXPF_IMPL integer_eval
+   #else
+   #define LIBC_MATH_EXPF_IMPL double_eval
+   #endif
+   #endif // !LIBC_MATH_EXPF_IMPL
+
+   #if LIBC_MATH_IMPL_IS(LIBC_MATH_EXPF_IMPL, float_eval)
+   #include "src/__support/math/expf_float_eval.h"
+   #elif LIBC_MATH_IMPL_IS(LIBC_MATH_EXPF_IMPL, integer_eval)
+   #include "src/__support/math/expf_integer_eval.h"
+   #elif LIBC_MATH_IMPL_IS(LIBC_MATH_EXPF_IMPL, double_eval)
+   #include "src/__support/math/expf_double_eval.h"
+   #else
+   #error "Unsupported LIBC_MATH_EXPF_IMPL"
+   #endif // LIBC_MATH_IMPL_IS
+
+   namespace LIBC_NAMESPACE_DECL {
+   namespace math {
+
+   using LIBC_MATH_EXPF_IMPL::expf;
+
+   } // namespace math
+   } // namespace LIBC_NAMESPACE_DECL
+
+   #undef LIBC_MATH_EXPF_IMPL
+   ```
+
+2. **Evaluation Variant Headers (`*_{double,float,integer}_eval.h`)**:
+   - `<func>_double_eval.h` (`math::double_eval`): Double-precision evaluation
+     (either standalone for `float` functions or Tier-1 `DoubleDouble` fast path
+     for `double` functions).
+   - `<func>_float_eval.h` (`math::float_eval` or `math::float_eval_cr_rn`):
+     Single-precision evaluation for targets with hardware float FPU when
+     reduced-size or fast math modes are requested.
+   - `<func>_integer_eval.h` (`math::integer_eval` /
+     `math::static_rounding::integer_eval`): Pure integer fixed-point evaluation
+     for soft-float targets and compile-time static rounding modes.
+
+3. **Shared Utilities & Multi-Precision Passes**:
+   - `<func>_utils.h` / `<family>_utils.h` (and mode-specific
+     `<family>_double_utils.h`, `<family>_float_utils.h`,
+     `<family>_integer_utils.h`): Shared lookup tables, polynomial evaluators,
+     subnormal/denormal rounding helpers, and exceptional-case handlers.
+   - `<func>_accurate_128.h` and `<func>_accurate_256.h`: Cold 128-bit and
+     256-bit fixed-point (`Frac64`, `Frac128`, `Frac256`, `DyadicFloat`) passes
+     invoked only when the fast path's Ziv rounding test cannot guarantee
+     correct rounding.
+
+### Math Optimization Flags (`LIBC_CONF_MATH_OPTIMIZATIONS`)
+
+Build configs can set `LIBC_CONF_MATH_OPTIMIZATIONS` (propagated as the bitmask
+macro `LIBC_MATH` in `src/__support/macros/optimization.h`):
+
+| Flag | Derived Macro | Effect |
+| :--- | :--- | :--- |
+| `LIBC_MATH_SKIP_ACCURATE_PASS` | `LIBC_MATH_HAS_SKIP_ACCURATE_PASS` | Skips multi-precision fallback passes and exact-exception tables; targets {math}`< 1` ULP accuracy with compact code size and predictable latency. |
+| `LIBC_MATH_SMALL_TABLES` | `LIBC_MATH_HAS_SMALL_TABLES` | Uses smaller lookup tables (typically paired with `LIBC_MATH_SKIP_ACCURATE_PASS`) and outlines shared helpers via `LIBC_MATH_SMALL_TABLES_INLINE` to minimize `.text` + `.rodata` footprint. |
+| `LIBC_MATH_NO_ERRNO` | `LIBC_MATH_HAS_NO_ERRNO` | Omits `errno` updates (`EDOM`, `ERANGE`), avoiding TLS/PLT calls on cold paths. |
+| `LIBC_MATH_NO_EXCEPT` | `LIBC_MATH_HAS_NO_EXCEPT` | Omits IEEE-754 floating-point exception raising (`FE_INVALID`, `FE_DIVBYZERO`, `FE_OVERFLOW`, `FE_UNDERFLOW`). |
+| `LIBC_MATH_INTERMEDIATE_COMP_IN_FLOAT` | `LIBC_MATH_HAS_INTERMEDIATE_COMP_IN_FLOAT` | Prefers single-precision intermediate arithmetic for `float` functions when hardware float FPU is available. |
+| `LIBC_MATH_ASSUME_ROUND_NEAREST_ONLY` | `LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY` | Assumes round-to-nearest, ties-to-even (`FE_TONEAREST`) without dynamic rounding-mode queries. |
+| `LIBC_MATH_FAST` | *(all of the above except `INTERMEDIATE_COMP_IN_FLOAT`)* | Default embedded/baremetal fast preset combining small tables, no accurate pass, no `errno`/`fenv`, and round-to-nearest. |
+
+---
+
+## 2. Implementation Caveats & Best Practices
+
+### Namespace Hygiene & Avoiding Symbol Collisions
+
+`libc/shared/math.h` includes **every** `src/__support/math/*.h` header into a
+**single translation unit** (verified by `shared_math_test.cpp`), and functions
+such as `pow` transitively include `exp2`, `exp10`, and `exp_utils`. Any
+duplicate constant, struct, or helper name placed directly in a shared
+namespace will cause redefinition errors or silent overload-resolution bugs.
+
+Follow a strict 3-layer namespace convention:
+
+1. **Keep `math::double_eval`, `math::float_eval`, and `math::integer_eval`
+   clean**: Prefer placing only the top-level dispatch targets (`exp`, `pow`,
+   `sinf`, ...) directly inside `*_eval`. Since C math function names are
+   globally unique, entrypoint names never collide.
+2. **Scope private & family-shared symbols in `<func>_internal` or
+   `<family>_internal`**:
+   - Put function-private tables, polynomials, and helpers in `<func>_internal`
+     (e.g., `pow_internal`, `tanf_internal`).
+   - Put family-shared utilities in `<family>_internal` (e.g., `exp_internal`,
+     `sincosf_utils_internal`).
+   - **Never** write `using namespace <foo>_internal;` at header or namespace
+     scope. Place `using namespace` inside function bodies only, and explicitly
+     qualify cross-family helper calls so dependencies remain obvious.
+3. **Promote generic primitives to `fputil::` and keep constants in
+   family `<family>_utils.h` headers**:
+   - Generic floating-point bit masks, DoubleDouble arithmetic, and fixed-point
+     splitting helpers belong in `src/__support/FPUtil/`.
+   - Mathematical constants and lookup tables belong in their owning family's
+     `*_utils.h` header (e.g., `exp_utils.h`, `log_utils.h`, `sincos_utils.h`)
+     rather than a catch-all constants file, using explicit precision/bit-width
+     suffixes (e.g., `LOG_2_HI_12` vs `LOG_2_HI_43`) when multiple splits exist.
+
+### Header Hygiene & Bazel `layering_check` / `parse_headers`
+
+- Every support header must define a unique header guard, `#include`
+  `"src/__support/common.h"` and `"src/__support/macros/config.h"`, and
+  directly `#include` every header whose declarations it uses.
+- Avoid `#include "hdr/stdint_proxy.h"` in `src/__support/math/*.h` when
+  `"src/__support/common.h"` or `"src/__support/FPUtil/FPBits.h"` is already
+  included.
+- Give each `.h` file in `src/__support/math/` its own granular
+  `add_header_library` target in `libc/src/__support/math/CMakeLists.txt` and a
+  matching `libc_support_library` target in
+  `utils/bazel/llvm-project-overlay/libc/BUILD.bazel` listing **exact direct
+  dependencies** (both unconditional and conditional `#include`s). Always verify
+  with Bazel `--features=layering_check --features=parse_headers`.
+
+### Floating-Point Evaluation, Rounding Modes, `errno`, and Cold Paths
+
+- **Split chained floating-point expressions**: Write one floating-point
+  operation per statement with descriptive intermediate variable names. Long
+  chained expressions (`a * b + c * d + e`) invite compiler contraction or
+  reassociation that can invalidate error bounds in `DoubleDouble`, FastTwoSum,
+  or range-reduction arithmetic.
+- **`fputil::multiply_add` vs `fputil::fma`**: Use `fputil::multiply_add(a, b, c)`
+  when FMA is an optimization or guarded by `#ifdef LIBC_TARGET_CPU_HAS_FMA_*`;
+  it compiles to hardware FMA when available and `a * b + c` otherwise. Only
+  call `fputil::fma` when software-emulated FMA is intentionally required on
+  non-FMA targets (which is much slower than a dedicated non-FMA code path).
+- **Keep non-FMA bit masking in FP/SIMD registers**: On targets without FMA,
+  prefer `fputil::fp_and`, `fputil::fp_or`, `fputil::fp_xor`, and
+  `fputil::scale_exp2` (`src/__support/FPUtil/fp_bitwise.h`) over Veltkamp
+  splitting or `cpp::bit_cast<uint64_t>` round-trips between general-purpose and
+  FP registers.
+- **All 4 rounding modes, `errno`, and exceptions**: Unless
+  `LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY` is active, implementations must be
+  correctly rounded in `FE_TONEAREST`, `FE_DOWNWARD`, `FE_UPWARD`, and
+  `FE_TOWARDZERO`, and handle FTZ/DAZ subnormal modes cleanly. Use
+  `fputil::set_overflow<T>`, `fputil::set_underflow<T>`,
+  `fputil::set_errno_if_required`, and `fputil::raise_except_if_required`
+  (`except_value_utils.h` / `FEnvImpl.h`) so `NO_ERRNO` and `NO_EXCEPT` builds
+  compile out side effects automatically.
+- **Outline cold paths without stack spills**: Mark exceptional, subnormal, and
+  multi-precision fallback functions `LIBC_COLD LIBC_NOINLINE LIBC_INLINE`.
+  Return results (or a small 2-field struct) **by value** in registers instead
+  of passing pointers or non-const references to hot-path local variables, which
+  forces stack frame setup and register spills on the fast path.
+- **Compiler compatibility**: Ensure implementations compile warning-free under
+  both Clang and GCC (`>= 12.2`), and keep all lines within 80 columns
+  (`clang-format --dry-run -Werror`).
+
+---
+
+## 3. Step-by-Step Checklist to Add a Math Function
+
+### Step 1: Registration & Public Specification
+
+1. Add the function specification to `libc/include/math.yaml`.
----------------
Sukumarsawant wrote:

Should we add something like this, where it should be for only types with guards available (bf16 can't be added yet)?

https://github.com/llvm/llvm-project/pull/240599


More information about the libc-commits mailing list