[libc-commits] [libc] [llvm] [libc][math] Add tgammabf16 math support for bfloat16. (PR #208689)

Vedant Neve via libc-commits libc-commits at lists.llvm.org
Sat Oct 17 12:49:09 PDT 2026


https://github.com/0bVdnt updated https://github.com/llvm/llvm-project/pull/208689

>From c793f9bf48740199c774f0602be7fe49654d199c Mon Sep 17 00:00:00 2001
From: Vedant Neve <vedantneve13 at gmail.com>
Date: Sun, 18 Oct 2026 00:43:59 +0530
Subject: [PATCH] [libc][math] Add bfloat16 tgamma function (tgammabf16)

Signed-off-by: Vedant Neve <vedantneve13 at gmail.com>
---
 libc/config/baremetal/aarch64/entrypoints.txt |   1 +
 libc/config/baremetal/arm/entrypoints.txt     |   1 +
 libc/config/baremetal/riscv/entrypoints.txt   |   1 +
 libc/config/darwin/aarch64/entrypoints.txt    |   1 +
 libc/config/darwin/x86_64/entrypoints.txt     |   1 +
 libc/config/freebsd/x86_64/entrypoints.txt    |   1 +
 libc/config/gpu/amdgpu/entrypoints.txt        |   1 +
 libc/config/gpu/nvptx/entrypoints.txt         |   1 +
 libc/config/linux/aarch64/entrypoints.txt     |   1 +
 libc/config/linux/arm/entrypoints.txt         |   1 +
 libc/config/linux/riscv/entrypoints.txt       |   1 +
 libc/config/linux/x86_64/entrypoints.txt      |   1 +
 libc/config/windows/entrypoints.txt           |   2 +-
 libc/docs/headers/math/index.rst              |   2 +-
 libc/shared/math.h                            |   1 +
 libc/shared/math/tgammabf16.h                 |  28 ++
 libc/src/__support/math/CMakeLists.txt        |  19 ++
 libc/src/__support/math/tgammabf16.h          | 240 ++++++++++++++++++
 libc/src/math/CMakeLists.txt                  |   1 +
 libc/src/math/generic/CMakeLists.txt          |  12 +
 libc/src/math/generic/tgammabf16.cpp          |  25 ++
 libc/src/math/tgammabf16.h                    |  26 ++
 libc/test/shared/CMakeLists.txt               |   1 +
 libc/test/shared/shared_math_test.cpp         |   3 +
 libc/test/src/math/CMakeLists.txt             |  12 +
 libc/test/src/math/smoke/CMakeLists.txt       |  13 +
 libc/test/src/math/smoke/tgammabf16_test.cpp  |  81 ++++++
 libc/test/src/math/tgammabf16_test.cpp        |  51 ++++
 libc/utils/MPFRWrapper/MPCommon.cpp           |   6 +
 libc/utils/MPFRWrapper/MPCommon.h             |   1 +
 libc/utils/MPFRWrapper/MPFRUtils.cpp          |   2 +
 libc/utils/MPFRWrapper/MPFRUtils.h            |   1 +
 .../llvm-project-overlay/libc/BUILD.bazel     |  26 ++
 .../libc/test/src/math/BUILD.bazel            |   5 +
 .../libc/test/src/math/smoke/BUILD.bazel      |   5 +
 35 files changed, 573 insertions(+), 2 deletions(-)
 create mode 100644 libc/shared/math/tgammabf16.h
 create mode 100644 libc/src/__support/math/tgammabf16.h
 create mode 100644 libc/src/math/generic/tgammabf16.cpp
 create mode 100644 libc/src/math/tgammabf16.h
 create mode 100644 libc/test/src/math/smoke/tgammabf16_test.cpp
 create mode 100644 libc/test/src/math/tgammabf16_test.cpp

diff --git a/libc/config/baremetal/aarch64/entrypoints.txt b/libc/config/baremetal/aarch64/entrypoints.txt
index a85fa19a92fccf..bf639b4624a041 100644
--- a/libc/config/baremetal/aarch64/entrypoints.txt
+++ b/libc/config/baremetal/aarch64/entrypoints.txt
@@ -878,6 +878,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
diff --git a/libc/config/baremetal/arm/entrypoints.txt b/libc/config/baremetal/arm/entrypoints.txt
index 87fdcd04652303..5c7f2e25e82fba 100644
--- a/libc/config/baremetal/arm/entrypoints.txt
+++ b/libc/config/baremetal/arm/entrypoints.txt
@@ -889,6 +889,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
diff --git a/libc/config/baremetal/riscv/entrypoints.txt b/libc/config/baremetal/riscv/entrypoints.txt
index 19397087f3e92c..ff40842b9c31d1 100644
--- a/libc/config/baremetal/riscv/entrypoints.txt
+++ b/libc/config/baremetal/riscv/entrypoints.txt
@@ -881,6 +881,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
diff --git a/libc/config/darwin/aarch64/entrypoints.txt b/libc/config/darwin/aarch64/entrypoints.txt
index 5600b82ad3410b..f8bd68c9638ccc 100644
--- a/libc/config/darwin/aarch64/entrypoints.txt
+++ b/libc/config/darwin/aarch64/entrypoints.txt
@@ -700,6 +700,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
diff --git a/libc/config/darwin/x86_64/entrypoints.txt b/libc/config/darwin/x86_64/entrypoints.txt
index e3fc845d2ed3af..a8af91c4d75cf7 100644
--- a/libc/config/darwin/x86_64/entrypoints.txt
+++ b/libc/config/darwin/x86_64/entrypoints.txt
@@ -336,6 +336,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
diff --git a/libc/config/freebsd/x86_64/entrypoints.txt b/libc/config/freebsd/x86_64/entrypoints.txt
index 8f6c178301c2f2..4520bd971bd0ac 100644
--- a/libc/config/freebsd/x86_64/entrypoints.txt
+++ b/libc/config/freebsd/x86_64/entrypoints.txt
@@ -632,6 +632,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
diff --git a/libc/config/gpu/amdgpu/entrypoints.txt b/libc/config/gpu/amdgpu/entrypoints.txt
index 2eaef608e9a7ac..9695d47d5309c6 100644
--- a/libc/config/gpu/amdgpu/entrypoints.txt
+++ b/libc/config/gpu/amdgpu/entrypoints.txt
@@ -749,6 +749,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
diff --git a/libc/config/gpu/nvptx/entrypoints.txt b/libc/config/gpu/nvptx/entrypoints.txt
index 79d0c733ec3c01..67871639b891d3 100644
--- a/libc/config/gpu/nvptx/entrypoints.txt
+++ b/libc/config/gpu/nvptx/entrypoints.txt
@@ -765,6 +765,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
diff --git a/libc/config/linux/aarch64/entrypoints.txt b/libc/config/linux/aarch64/entrypoints.txt
index b2c8d62a65f4e1..f790cffd955aa4 100644
--- a/libc/config/linux/aarch64/entrypoints.txt
+++ b/libc/config/linux/aarch64/entrypoints.txt
@@ -1113,6 +1113,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
diff --git a/libc/config/linux/arm/entrypoints.txt b/libc/config/linux/arm/entrypoints.txt
index 023d298170c245..d4a8f2c58ef1d4 100644
--- a/libc/config/linux/arm/entrypoints.txt
+++ b/libc/config/linux/arm/entrypoints.txt
@@ -714,6 +714,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
diff --git a/libc/config/linux/riscv/entrypoints.txt b/libc/config/linux/riscv/entrypoints.txt
index 3bdc686c0e4ce4..075a42010e7a89 100644
--- a/libc/config/linux/riscv/entrypoints.txt
+++ b/libc/config/linux/riscv/entrypoints.txt
@@ -1187,6 +1187,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
diff --git a/libc/config/linux/x86_64/entrypoints.txt b/libc/config/linux/x86_64/entrypoints.txt
index 23a588f65d7435..d38e3fff98ebda 100644
--- a/libc/config/linux/x86_64/entrypoints.txt
+++ b/libc/config/linux/x86_64/entrypoints.txt
@@ -1209,6 +1209,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
diff --git a/libc/config/windows/entrypoints.txt b/libc/config/windows/entrypoints.txt
index 1712b2ad26fda4..4ec7cf434ea384 100644
--- a/libc/config/windows/entrypoints.txt
+++ b/libc/config/windows/entrypoints.txt
@@ -426,6 +426,7 @@ list(APPEND TARGET_LIBM_ENTRYPOINTS
   libc.src.math.setpayloadsigbf16
   libc.src.math.sqrtbf16
   libc.src.math.tanbf16
+  libc.src.math.tgammabf16
   libc.src.math.truncbf16
   libc.src.math.totalorderbf16
   libc.src.math.totalordermagbf16
@@ -437,4 +438,3 @@ set(TARGET_LLVMLIBC_ENTRYPOINTS
   ${TARGET_LIBC_ENTRYPOINTS}
   ${TARGET_LIBM_ENTRYPOINTS}
 )
-
diff --git a/libc/docs/headers/math/index.rst b/libc/docs/headers/math/index.rst
index 575c7bd1d1a10a..674091c397a1c6 100644
--- a/libc/docs/headers/math/index.rst
+++ b/libc/docs/headers/math/index.rst
@@ -359,7 +359,7 @@ Higher Math Functions
 +-----------+------------------+-----------------+------------------------+----------------------+------------------------+------------------------+------------------------+----------------------------+
 | tanpi     | |check|          |                 |                        | |check|              |                        |                        | 7.12.4.14              | F.10.1.14                  |
 +-----------+------------------+-----------------+------------------------+----------------------+------------------------+------------------------+------------------------+----------------------------+
-| tgamma    |                  |                 |                        |                      |                        |                        | 7.12.8.4               | F.10.5.4                   |
+| tgamma    |                  |                 |                        |                      |                        | |check|                | 7.12.8.4               | F.10.5.4                   |
 +-----------+------------------+-----------------+------------------------+----------------------+------------------------+------------------------+------------------------+----------------------------+
 
 
diff --git a/libc/shared/math.h b/libc/shared/math.h
index eb72bebcb53bfa..f5eb2d4face1a5 100644
--- a/libc/shared/math.h
+++ b/libc/shared/math.h
@@ -485,6 +485,7 @@
 #include "math/tanhf16.h"
 #include "math/tanpif.h"
 #include "math/tanpif16.h"
+#include "math/tgammabf16.h"
 #include "math/totalorder.h"
 #include "math/totalorderbf16.h"
 #include "math/totalorderf.h"
diff --git a/libc/shared/math/tgammabf16.h b/libc/shared/math/tgammabf16.h
new file mode 100644
index 00000000000000..0d9a38f0072ebd
--- /dev/null
+++ b/libc/shared/math/tgammabf16.h
@@ -0,0 +1,28 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Shared declaration of the bfloat16 tgamma function.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SHARED_MATH_TGAMMABF16_H
+#define LLVM_LIBC_SHARED_MATH_TGAMMABF16_H
+
+#include "src/__support/macros/config.h"
+#include "src/__support/math/tgammabf16.h"
+
+namespace LIBC_NAMESPACE_DECL {
+namespace shared {
+
+using math::tgammabf16;
+
+} // namespace shared
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SHARED_MATH_TGAMMABF16_H
diff --git a/libc/src/__support/math/CMakeLists.txt b/libc/src/__support/math/CMakeLists.txt
index baac96e76d5435..a8e029c091003a 100644
--- a/libc/src/__support/math/CMakeLists.txt
+++ b/libc/src/__support/math/CMakeLists.txt
@@ -5820,6 +5820,25 @@ add_header_library(
     libc.src.__support.FPUtil.bfloat16
 )
 
+add_header_library(
+  tgammabf16
+  HDRS
+    tgammabf16.h
+  DEPENDS
+    libc.hdr.errno_macros
+    libc.hdr.fenv_macros
+    libc.src.__support.FPUtil.bfloat16
+    libc.src.__support.FPUtil.cast
+    libc.src.__support.FPUtil.fenv_impl
+    libc.src.__support.FPUtil.fp_bits
+    libc.src.__support.FPUtil.multiply_add
+    libc.src.__support.FPUtil.polyeval
+    libc.src.__support.macros.config
+    libc.src.__support.macros.optimization
+    libc.src.__support.math.expf
+    libc.src.__support.math.sinpif
+)
+
 add_header_library(
   tanf
   HDRS
diff --git a/libc/src/__support/math/tgammabf16.h b/libc/src/__support/math/tgammabf16.h
new file mode 100644
index 00000000000000..c53906395ca6c9
--- /dev/null
+++ b/libc/src/__support/math/tgammabf16.h
@@ -0,0 +1,240 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Implementation of the bfloat16 tgamma function.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_MATH_TGAMMABF16_H
+#define LLVM_LIBC_SRC___SUPPORT_MATH_TGAMMABF16_H
+
+#include "hdr/errno_macros.h"
+#include "hdr/fenv_macros.h"
+#include "src/__support/FPUtil/FEnvImpl.h"
+#include "src/__support/FPUtil/FPBits.h"
+#include "src/__support/FPUtil/PolyEval.h"
+#include "src/__support/FPUtil/bfloat16.h"
+#include "src/__support/FPUtil/cast.h"
+#include "src/__support/FPUtil/multiply_add.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/optimization.h"
+#include "src/__support/math/expf.h"
+#include "src/__support/math/sinpif.h"
+
+namespace LIBC_NAMESPACE_DECL {
+namespace math {
+
+// Sets ERANGE, raises FE_OVERFLOW, and returns the overflow value
+// (+inf or max_normal) according to the sign and active IEEE 754 rounding mode.
+LIBC_INLINE bfloat16 tgammabf16_overflow(Sign sign) {
+  fputil::set_errno_if_required(ERANGE);
+  fputil::raise_except_if_required(FE_OVERFLOW);
+
+#ifdef LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
+  return fputil::FPBits<bfloat16>::inf(sign).get_val();
+#else
+  switch (fputil::quick_get_round()) {
+  case FE_TONEAREST:
+    return fputil::FPBits<bfloat16>::inf(sign).get_val();
+  case FE_UPWARD:
+    return sign == Sign::POS
+               ? fputil::FPBits<bfloat16>::inf(Sign::POS).get_val()
+               : fputil::FPBits<bfloat16>::max_normal(Sign::NEG).get_val();
+  case FE_DOWNWARD:
+    return sign == Sign::POS
+               ? fputil::FPBits<bfloat16>::max_normal(Sign::POS).get_val()
+               : fputil::FPBits<bfloat16>::inf(Sign::NEG).get_val();
+  case FE_TOWARDZERO:
+    return fputil::FPBits<bfloat16>::max_normal(sign).get_val();
+  default:
+    return fputil::FPBits<bfloat16>::max_normal(sign).get_val();
+  }
+#endif
+}
+
+// This is only called with x in [7.5, 135.5] or with the positive Lanczos
+// coefficient sum. Range reduction into [sqrt(2)/2, sqrt(2)] confines
+// r = (m - 1) / (m + 1) to [-0.172, 0.172], making the degree-13 atanh Taylor
+// series accurate to ~2^-41 (sufficient for bfloat16 requirements).
+LIBC_INLINE double tgammabf16_log(double x) {
+  using DoubleBits = fputil::FPBits<double>;
+  // The hexadecimal literals were generated with Sollya:
+  // > display = hexadecimal;
+  // > round(log(2), D, RN);
+  // > round(sqrt(2), D, RN);
+  constexpr double LOG_2 = 0x1.62e42fefa39efp-1;
+  constexpr double SQRT_2 = 0x1.6a09e667f3bcdp0;
+
+  DoubleBits xbits(x);
+  int exponent =
+      static_cast<int>(xbits.get_biased_exponent()) - DoubleBits::EXP_BIAS;
+  xbits.set_biased_exponent(DoubleBits::EXP_BIAS);
+  double mantissa = xbits.get_val();
+  if (mantissa > SQRT_2) {
+    mantissa *= 0.5;
+    ++exponent;
+  }
+
+  double r = (mantissa - 1.0) / (mantissa + 1.0);
+  double r2 = r * r;
+  // Maclaurin series: log(mantissa) = log((1 + r) / (1 - r)) = 2 * atanh(r)
+  //                                 = 2 * r * (1 + r^2/3 + r^4/5 + ...).
+  // The coefficients 1/(2k + 1) for k = 1..6 were generated with Sollya:
+  // > for k from 1 to 6 do print(round(1 / (2 * k + 1), D, RN));
+  double p = fputil::polyeval(r2, 0x1.5555555555555p-2, 0x1.999999999999ap-3,
+                              0x1.2492492492492p-3, 0x1.c71c71c71c71cp-4,
+                              0x1.745d1745d1746p-4, 0x1.3b13b13b13b14p-4);
+  return fputil::multiply_add(static_cast<double>(exponent), LOG_2,
+                              2.0 * r * fputil::multiply_add(r2, p, 1.0));
+}
+
+LIBC_INLINE bfloat16 tgammabf16(bfloat16 x) {
+  using FPBits = fputil::FPBits<bfloat16>;
+  // The hexadecimal literals were generated with Sollya:
+  // > display = hexadecimal;
+  // > round(pi, D, RN);
+  // > round(log(sqrt(2 * pi)), D, RN);
+  constexpr double PI = 0x1.921fb54442d18p+1;
+  constexpr double LOG_SQRT_2_PI = 0x1.d67f1c864beb5p-1;
+  // Paul Godfrey's exact Lanczos approximation coefficients (g=7, n=9)
+  // Reference: "A note on the computation of the convergent Lanczos complex
+  // Gamma approximation" by Paul Godfrey (2001).
+  // Original:
+  // https://web.archive.org/web/20060915161115/http://my.fit.edu/~gabdo/gamma.txt
+  // Mirror: http://www.mrob.com/pub/ries/lanczos-gamma.html
+  constexpr double LANCZOS_COEFFS[9] = {
+      0x1.ffffffffff950p-1,  0x1.52429b6c30b05p+9,  -0x1.3ac8e8ed4171bp+10,
+      0x1.81a9661d3b4d8p+9,  -0x1.613ae51a32f5dp+7, 0x1.903c27f8b9c81p+3,
+      -0x1.1bcb2992b2855p-3, 0x1.4f0514e4e324fp-17, 0x1.435508f3faeefp-23};
+
+  FPBits xbits(x);
+  uint16_t x_abs = xbits.uintval() & 0x7fffU;
+
+  if (LIBC_UNLIKELY(x_abs >= FPBits::EXP_MASK)) {
+    if (xbits.is_nan()) {
+      if (xbits.is_signaling_nan()) {
+        fputil::raise_except_if_required(FE_INVALID);
+        return FPBits::quiet_nan().get_val();
+      }
+      return x;
+    }
+    if (xbits.is_pos())
+      return x;
+    fputil::set_errno_if_required(EDOM);
+    fputil::raise_except_if_required(FE_INVALID);
+    return FPBits::quiet_nan().get_val();
+  }
+
+  if (LIBC_UNLIKELY(xbits.is_zero())) {
+    fputil::set_errno_if_required(ERANGE);
+    fputil::raise_except_if_required(FE_DIVBYZERO);
+    return FPBits::inf(xbits.sign()).get_val();
+  }
+
+  if (LIBC_UNLIKELY(xbits.is_neg())) {
+    int biased_exp = x_abs >> FPBits::FRACTION_LEN;
+    if (biased_exp >= FPBits::EXP_BIAS) {
+      int e = biased_exp - FPBits::EXP_BIAS;
+      if (e >= FPBits::FRACTION_LEN ||
+          (xbits.get_mantissa() &
+           static_cast<uint16_t>((1U << (FPBits::FRACTION_LEN - e)) - 1U)) ==
+              0U) {
+        fputil::set_errno_if_required(EDOM);
+        fputil::raise_except_if_required(FE_INVALID);
+        return FPBits::quiet_nan().get_val();
+      }
+    }
+  }
+
+  float xf = static_cast<float>(x);
+
+  // Gamma is strictly increasing for x >= 2, and Gamma(35) is finite in
+  // bfloat16 while every larger positive bfloat16 input overflows.
+  if (LIBC_UNLIKELY(xf > 35.0f))
+    return tgammabf16_overflow(Sign::POS);
+
+  // Fast path for exact positive integers
+  if (xf > 0.0f && xf <= 35.0f) {
+    int n = static_cast<int>(xf);
+    if (xf == static_cast<float>(n)) {
+      double res = 1.0;
+      for (int i = 1; i < n; ++i)
+        res *= i;
+      return fputil::cast<bfloat16>(res);
+    }
+  }
+
+  bool reflection = xbits.is_neg();
+  bool divide_by_x = false;
+
+  double xd = static_cast<double>(xf);
+  double x_eval = xd;
+  double res;
+
+  // Fast path for tiny positive inputs to prevent exact-boundary overshoots.
+  // EULER_GAMMA is the Euler-Mascheroni constant. Its correctly rounded
+  // binary64 value was generated with MPFR's mpfr_const_euler.
+  if (LIBC_UNLIKELY(xf > 0.0f && xf < 0x1.0p-8f)) {
+    constexpr double EULER_GAMMA = 0x1.2788cfc6fb619p-1;
+    res = (1.0 / xd) - EULER_GAMMA;
+  } else {
+    if (reflection) {
+      x_eval = 1.0 - xd;
+    } else if (xf < 1.0f) {
+      divide_by_x = true;
+      x_eval = xd + 1.0;
+    }
+
+    double z = x_eval - 1.0;
+    double a = LANCZOS_COEFFS[0];
+    for (int i = 1; i < 9; ++i) {
+      a += LANCZOS_COEFFS[i] / (z + static_cast<double>(i));
+    }
+
+    double t = z + 7.5;
+
+    double log_t = tgammabf16_log(t);
+    double base_term = (LOG_SQRT_2_PI - t) + tgammabf16_log(a);
+    double exp_arg = fputil::multiply_add(z + 0.5, log_t, base_term);
+
+    if (reflection) {
+      double sin_pi_x = static_cast<double>(math::sinpif(xf));
+      if (LIBC_UNLIKELY(sin_pi_x == 0.0)) {
+        fputil::set_errno_if_required(ERANGE);
+        fputil::raise_except_if_required(FE_UNDERFLOW);
+        return FPBits::zero(Sign::POS).get_val();
+      }
+
+      // Gamma(x_eval) can exceed the float range on the reflection path.
+      // Evaluate 1 / Gamma(x_eval) directly instead.
+      res = (PI / sin_pi_x) *
+            static_cast<double>(math::expf(static_cast<float>(-exp_arg)));
+    } else {
+      // Since x <= 35, exp_arg < 88.0, which is within normal float bounds
+      res = static_cast<double>(math::expf(static_cast<float>(exp_arg)));
+      if (divide_by_x)
+        res = res / xd;
+    }
+  }
+
+  double abs_res = res < 0.0 ? -res : res;
+
+  // 0x1.ffp127 is max normal + 0.5 ULP in bfloat16, the exact RTN overflow
+  // threshold
+  if (LIBC_UNLIKELY(abs_res > 0x1.ffp+127)) {
+    return tgammabf16_overflow(res > 0.0 ? Sign::POS : Sign::NEG);
+  }
+
+  return fputil::cast<bfloat16>(res);
+}
+
+} // namespace math
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC___SUPPORT_MATH_TGAMMABF16_H
diff --git a/libc/src/math/CMakeLists.txt b/libc/src/math/CMakeLists.txt
index 4f1dd95a6993da..0e61aa0c8fd605 100644
--- a/libc/src/math/CMakeLists.txt
+++ b/libc/src/math/CMakeLists.txt
@@ -604,6 +604,7 @@ add_math_entrypoint_object(tanpif)
 add_math_entrypoint_object(tanpif16)
 
 add_math_entrypoint_object(tgamma)
+add_math_entrypoint_object(tgammabf16)
 add_math_entrypoint_object(tgammaf)
 add_math_entrypoint_object(lgamma)
 add_math_entrypoint_object(lgamma_r)
diff --git a/libc/src/math/generic/CMakeLists.txt b/libc/src/math/generic/CMakeLists.txt
index 17f586036396f1..afca0fbe761818 100644
--- a/libc/src/math/generic/CMakeLists.txt
+++ b/libc/src/math/generic/CMakeLists.txt
@@ -468,6 +468,18 @@ add_entrypoint_object(
     libc.src.__support.math.tanpif16
 )
 
+add_entrypoint_object(
+  tgammabf16
+  SRCS
+    tgammabf16.cpp
+  HDRS
+    ../tgammabf16.h
+  DEPENDS
+    libc.src.__support.common
+    libc.src.__support.macros.config
+    libc.src.__support.math.tgammabf16
+)
+
 add_entrypoint_object(
   fabs
   SRCS
diff --git a/libc/src/math/generic/tgammabf16.cpp b/libc/src/math/generic/tgammabf16.cpp
new file mode 100644
index 00000000000000..7c68fb0d1d2f61
--- /dev/null
+++ b/libc/src/math/generic/tgammabf16.cpp
@@ -0,0 +1,25 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Implementation of the tgammabf16 function.
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/__support/math/tgammabf16.h"
+#include "src/__support/common.h"
+#include "src/__support/macros/config.h"
+#include "src/math/tgammabf16.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+LLVM_LIBC_FUNCTION(bfloat16, tgammabf16, (bfloat16 x)) {
+  return math::tgammabf16(x);
+}
+
+} // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/src/math/tgammabf16.h b/libc/src/math/tgammabf16.h
new file mode 100644
index 00000000000000..8ca61e36792b07
--- /dev/null
+++ b/libc/src/math/tgammabf16.h
@@ -0,0 +1,26 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Declaration of the bfloat16 tgamma function.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_MATH_TGAMMABF16_H
+#define LLVM_LIBC_SRC_MATH_TGAMMABF16_H
+
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/properties/types.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+bfloat16 tgammabf16(bfloat16 x);
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC_MATH_TGAMMABF16_H
diff --git a/libc/test/shared/CMakeLists.txt b/libc/test/shared/CMakeLists.txt
index 74eda7cdaf065e..663027fd0599a6 100644
--- a/libc/test/shared/CMakeLists.txt
+++ b/libc/test/shared/CMakeLists.txt
@@ -489,6 +489,7 @@ else()
       libc.src.__support.math.tanhf16
       libc.src.__support.math.tanpif
       libc.src.__support.math.tanpif16
+      libc.src.__support.math.tgammabf16
       libc.src.__support.math.trunc
       libc.src.__support.math.truncbf16
       libc.src.__support.math.truncf
diff --git a/libc/test/shared/shared_math_test.cpp b/libc/test/shared/shared_math_test.cpp
index 5b6663fa6494f6..9f5a606bb4c465 100644
--- a/libc/test/shared/shared_math_test.cpp
+++ b/libc/test/shared/shared_math_test.cpp
@@ -809,6 +809,9 @@ TEST(LlvmLibcSharedMathTest, AllBFloat16) {
                                                          bfloat16(0.0)));
   EXPECT_FP_EQ(bfloat16(0.0), setpayloadsigbf16_res);
 
+  EXPECT_FP_EQ(bfloat16(1.0f),
+               LIBC_NAMESPACE::shared::tgammabf16(bfloat16(1.0f)));
+
   EXPECT_FP_EQ(bfloat16(1.0), LIBC_NAMESPACE::shared::exp2bf16(bfloat16(0.0)));
   EXPECT_FP_EQ(bfloat16(1.0), LIBC_NAMESPACE::shared::expbf16(bfloat16(0.0)));
   EXPECT_FP_EQ(bfloat16(0.0), LIBC_NAMESPACE::shared::log_bf16(bfloat16(1.0)));
diff --git a/libc/test/src/math/CMakeLists.txt b/libc/test/src/math/CMakeLists.txt
index 921dbf220eb372..1d17f5c576b435 100644
--- a/libc/test/src/math/CMakeLists.txt
+++ b/libc/test/src/math/CMakeLists.txt
@@ -3438,6 +3438,18 @@ add_fp_unittest(
     libc.src.__support.FPUtil.bfloat16
 )
 
+add_fp_unittest(
+  tgammabf16_test
+  NEED_MPFR
+  SUITE
+    libc-math-unittests
+  SRCS
+    tgammabf16_test.cpp
+  DEPENDS
+    libc.src.math.tgammabf16
+    libc.src.__support.FPUtil.bfloat16
+)
+
 add_fp_unittest(
   dmull_test
   NEED_MPFR
diff --git a/libc/test/src/math/smoke/CMakeLists.txt b/libc/test/src/math/smoke/CMakeLists.txt
index a1f85df34e4c7d..056d08d88b22a0 100644
--- a/libc/test/src/math/smoke/CMakeLists.txt
+++ b/libc/test/src/math/smoke/CMakeLists.txt
@@ -6296,6 +6296,19 @@ add_fp_unittest(
     libc.src.__support.FPUtil.bfloat16
 )
 
+add_fp_unittest(
+  tgammabf16_test
+  SUITE
+    libc-math-smoke-tests
+  SRCS
+    tgammabf16_test.cpp
+  DEPENDS
+    libc.hdr.errno_macros
+    libc.hdr.fenv_macros
+    libc.src.math.tgammabf16
+    libc.src.__support.FPUtil.bfloat16
+)
+
 add_fp_unittest(
   dmull_test
   SUITE
diff --git a/libc/test/src/math/smoke/tgammabf16_test.cpp b/libc/test/src/math/smoke/tgammabf16_test.cpp
new file mode 100644
index 00000000000000..da2e0fa42d2de6
--- /dev/null
+++ b/libc/test/src/math/smoke/tgammabf16_test.cpp
@@ -0,0 +1,81 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Smoke tests for the tgammabf16 function.
+///
+//===----------------------------------------------------------------------===//
+
+#include "hdr/errno_macros.h"
+#include "hdr/fenv_macros.h"
+#include "src/__support/FPUtil/bfloat16.h"
+#include "src/math/tgammabf16.h"
+#include "test/UnitTest/FEnvSafeTest.h"
+#include "test/UnitTest/FPMatcher.h"
+#include "test/UnitTest/Test.h"
+
+class LlvmLibcTgammaBf16Test : public LIBC_NAMESPACE::testing::FEnvSafeTest {
+  DECLARE_SPECIAL_CONSTANTS(bfloat16)
+
+public:
+  void test_special_numbers() {
+    EXPECT_FP_EQ_ALL_ROUNDING(aNaN, LIBC_NAMESPACE::tgammabf16(aNaN));
+    EXPECT_MATH_ERRNO(0);
+
+    EXPECT_FP_EQ_WITH_EXCEPTION(aNaN, LIBC_NAMESPACE::tgammabf16(sNaN),
+                                FE_INVALID);
+    EXPECT_MATH_ERRNO(0);
+
+    EXPECT_FP_EQ_ALL_ROUNDING(inf, LIBC_NAMESPACE::tgammabf16(inf));
+    EXPECT_MATH_ERRNO(0);
+
+    EXPECT_FP_EQ_WITH_EXCEPTION_ALL_ROUNDING(
+        aNaN, LIBC_NAMESPACE::tgammabf16(neg_inf), FE_INVALID);
+    EXPECT_MATH_ERRNO(EDOM);
+
+    EXPECT_FP_EQ_WITH_EXCEPTION_ALL_ROUNDING(
+        inf, LIBC_NAMESPACE::tgammabf16(zero), FE_DIVBYZERO);
+    EXPECT_MATH_ERRNO(ERANGE);
+
+    EXPECT_FP_EQ_WITH_EXCEPTION_ALL_ROUNDING(
+        neg_inf, LIBC_NAMESPACE::tgammabf16(neg_zero), FE_DIVBYZERO);
+    EXPECT_MATH_ERRNO(ERANGE);
+  }
+
+  void test_poles() {
+    EXPECT_FP_EQ_WITH_EXCEPTION_ALL_ROUNDING(
+        aNaN, LIBC_NAMESPACE::tgammabf16(bfloat16(-1.0f)), FE_INVALID);
+    EXPECT_MATH_ERRNO(EDOM);
+
+    EXPECT_FP_EQ_WITH_EXCEPTION_ALL_ROUNDING(
+        aNaN, LIBC_NAMESPACE::tgammabf16(bfloat16(-2.0f)), FE_INVALID);
+    EXPECT_MATH_ERRNO(EDOM);
+  }
+
+  void test_values() {
+    EXPECT_FP_EQ_ALL_ROUNDING(bfloat16(1.0f),
+                              LIBC_NAMESPACE::tgammabf16(bfloat16(1.0f)));
+    EXPECT_FP_EQ_ALL_ROUNDING(bfloat16(1.0f),
+                              LIBC_NAMESPACE::tgammabf16(bfloat16(2.0f)));
+    EXPECT_FP_EQ_ALL_ROUNDING(bfloat16(2.0f),
+                              LIBC_NAMESPACE::tgammabf16(bfloat16(3.0f)));
+    EXPECT_FP_EQ_ALL_ROUNDING(bfloat16(24.0f),
+                              LIBC_NAMESPACE::tgammabf16(bfloat16(5.0f)));
+  }
+
+  void test_boundaries() {
+    EXPECT_FP_EQ_WITH_EXCEPTION(
+        inf, LIBC_NAMESPACE::tgammabf16(bfloat16(36.0f)), FE_OVERFLOW);
+    EXPECT_MATH_ERRNO(ERANGE);
+  }
+};
+
+TEST_F(LlvmLibcTgammaBf16Test, SpecialNumbers) { test_special_numbers(); }
+TEST_F(LlvmLibcTgammaBf16Test, Poles) { test_poles(); }
+TEST_F(LlvmLibcTgammaBf16Test, Values) { test_values(); }
+TEST_F(LlvmLibcTgammaBf16Test, Boundaries) { test_boundaries(); }
diff --git a/libc/test/src/math/tgammabf16_test.cpp b/libc/test/src/math/tgammabf16_test.cpp
new file mode 100644
index 00000000000000..9b92dcd7257b02
--- /dev/null
+++ b/libc/test/src/math/tgammabf16_test.cpp
@@ -0,0 +1,51 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Exhaustive tests for the tgammabf16 function.
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/__support/FPUtil/bfloat16.h"
+#include "src/math/tgammabf16.h"
+#include "test/UnitTest/FPMatcher.h"
+#include "test/UnitTest/Test.h"
+#include "utils/MPFRWrapper/MPFRUtils.h"
+
+using LlvmLibcTgammaBf16Test = LIBC_NAMESPACE::testing::FPTest<bfloat16>;
+
+namespace mpfr = LIBC_NAMESPACE::testing::mpfr;
+
+// Values in (-1, 0) are not integers. At or below -128.0f, bfloat16 has a
+// spacing of at least 1, so every finite value is an exact integer. Since the
+// Gamma function is undefined for negative integers, they are skipped. This
+// check also avoids converting large finite values to int, preventing overflow.
+static bool is_negative_integer(bfloat16 x) {
+  float xf = static_cast<float>(x);
+  if (xf > -1.0f)
+    return false;
+  if (xf <= -128.0f)
+    return true;
+  int n = static_cast<int>(xf);
+  return xf == static_cast<float>(n);
+}
+
+TEST_F(LlvmLibcTgammaBf16Test, Exhaustive) {
+  for (uint32_t v = 0x0000; v < 0x10000; ++v) {
+    bfloat16 x =
+        LIBC_NAMESPACE::fputil::FPBits<bfloat16>(static_cast<uint16_t>(v))
+            .get_val();
+    LIBC_NAMESPACE::fputil::FPBits<bfloat16> bits(x);
+
+    if (bits.is_nan() || bits.is_zero() ||
+        (bits.is_neg() && is_negative_integer(x)))
+      continue;
+    EXPECT_MPFR_MATCH_ALL_ROUNDING(mpfr::Operation::Tgamma, x,
+                                   LIBC_NAMESPACE::tgammabf16(x), 1.0);
+  }
+}
diff --git a/libc/utils/MPFRWrapper/MPCommon.cpp b/libc/utils/MPFRWrapper/MPCommon.cpp
index 2901bed3914160..8c8fa820678352 100644
--- a/libc/utils/MPFRWrapper/MPCommon.cpp
+++ b/libc/utils/MPFRWrapper/MPCommon.cpp
@@ -583,6 +583,12 @@ MPFRNumber MPFRNumber::tanpi() const {
 #endif
 }
 
+MPFRNumber MPFRNumber::tgamma() const {
+  MPFRNumber result(*this);
+  mpfr_gamma(result.value, value, mpfr_rounding);
+  return result;
+}
+
 MPFRNumber MPFRNumber::trunc() const {
   MPFRNumber result(*this);
   mpfr_trunc(result.value, value);
diff --git a/libc/utils/MPFRWrapper/MPCommon.h b/libc/utils/MPFRWrapper/MPCommon.h
index 1deda67da64e6c..1b0f459a3129cf 100644
--- a/libc/utils/MPFRWrapper/MPCommon.h
+++ b/libc/utils/MPFRWrapper/MPCommon.h
@@ -249,6 +249,7 @@ class MPFRNumber {
   MPFRNumber tan() const;
   MPFRNumber tanh() const;
   MPFRNumber tanpi() const;
+  MPFRNumber tgamma() const;
   MPFRNumber trunc() const;
   MPFRNumber fma(const MPFRNumber &b, const MPFRNumber &c);
   MPFRNumber mul(const MPFRNumber &b);
diff --git a/libc/utils/MPFRWrapper/MPFRUtils.cpp b/libc/utils/MPFRWrapper/MPFRUtils.cpp
index 83500cb59de9d8..024792f6e1cc35 100644
--- a/libc/utils/MPFRWrapper/MPFRUtils.cpp
+++ b/libc/utils/MPFRWrapper/MPFRUtils.cpp
@@ -115,6 +115,8 @@ unary_operation(Operation op, InputType input, unsigned int precision,
     return mpfrInput.tanh();
   case Operation::Tanpi:
     return mpfrInput.tanpi();
+  case Operation::Tgamma:
+    return mpfrInput.tgamma();
   case Operation::Trunc:
     return mpfrInput.trunc();
   default:
diff --git a/libc/utils/MPFRWrapper/MPFRUtils.h b/libc/utils/MPFRWrapper/MPFRUtils.h
index 84e59674295f57..55afa336877389 100644
--- a/libc/utils/MPFRWrapper/MPFRUtils.h
+++ b/libc/utils/MPFRWrapper/MPFRUtils.h
@@ -68,6 +68,7 @@ enum class Operation : int {
   Tan,
   Tanh,
   Tanpi,
+  Tgamma,
   Trunc,
   EndUnaryOperationsSingleOutput,
 
diff --git a/utils/bazel/llvm-project-overlay/libc/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/BUILD.bazel
index f2df1ef9466183..9de7bbd8996d73 100644
--- a/utils/bazel/llvm-project-overlay/libc/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/BUILD.bazel
@@ -11527,6 +11527,25 @@ libc_support_library(
     ],
 )
 
+libc_support_library(
+    name = "__support_math_tgammabf16",
+    hdrs = ["src/__support/math/tgammabf16.h"],
+    deps = [
+        ":__support_fputil_bfloat16",
+        ":__support_fputil_cast",
+        ":__support_fputil_fenv_impl",
+        ":__support_fputil_fp_bits",
+        ":__support_fputil_multiply_add",
+        ":__support_fputil_polyeval",
+        ":__support_macros_config",
+        ":__support_macros_optimization",
+        ":__support_math_expf",
+        ":__support_math_sinpif",
+        ":hdr_errno_macros",
+        ":hdr_fenv_macros",
+    ],
+)
+
 libc_support_library(
     name = "__support_math_totalorder",
     hdrs = ["src/__support/math/totalorder.h"],
@@ -15365,6 +15384,13 @@ libc_math_function(
     additional_deps = [":__support_math_tanpif16"],
 )
 
+libc_math_function(
+    name = "tgammabf16",
+    additional_deps = [
+        ":__support_math_tgammabf16",
+    ],
+)
+
 libc_math_function(
     name = "totalorder",
     additional_deps = [
diff --git a/utils/bazel/llvm-project-overlay/libc/test/src/math/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/test/src/math/BUILD.bazel
index 3c6468dfd3b1e9..c1105cd672768f 100644
--- a/utils/bazel/llvm-project-overlay/libc/test/src/math/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/test/src/math/BUILD.bazel
@@ -978,3 +978,8 @@ math_mpfr_test(name = "log10f16")
 math_mpfr_test(name = "log10p1f16")
 
 math_mpfr_test(name = "lgammaf16")
+
+math_mpfr_test(
+    name = "tgammabf16",
+    deps = ["//libc:__support_fputil_bfloat16"],
+)
diff --git a/utils/bazel/llvm-project-overlay/libc/test/src/math/smoke/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/test/src/math/smoke/BUILD.bazel
index b86930825f493d..94e7bafdffbfd3 100644
--- a/utils/bazel/llvm-project-overlay/libc/test/src/math/smoke/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/test/src/math/smoke/BUILD.bazel
@@ -2434,3 +2434,8 @@ math_test(name = "tanf16")
 math_test(name = "tanhf16")
 
 math_test(name = "tanpif16")
+
+math_test(
+    name = "tgammabf16",
+    deps = ["//libc:__support_fputil_bfloat16"],
+)



More information about the libc-commits mailing list