[llvm-branch-commits] [libc] [libc][math][c23] Add log2f16 C23 math function (PR #106084)

via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Mon Aug 26 07:40:07 PDT 2024


https://github.com/overmighty created https://github.com/llvm/llvm-project/pull/106084

Part of #95250.

>From 2f0d352e311301b0853346587cf03d5137b22d76 Mon Sep 17 00:00:00 2001
From: OverMighty <its.overmighty at gmail.com>
Date: Mon, 26 Aug 2024 16:36:19 +0200
Subject: [PATCH] [libc][math][c23] Add log2f16 C23 math function

Part of #95250.
---
 libc/config/gpu/entrypoints.txt           |   1 +
 libc/config/linux/x86_64/entrypoints.txt  |   1 +
 libc/docs/math/index.rst                  |   2 +-
 libc/spec/stdc.td                         |   1 +
 libc/src/math/CMakeLists.txt              |   1 +
 libc/src/math/generic/CMakeLists.txt      |  21 ++++
 libc/src/math/generic/expxf16.h           |  14 +++
 libc/src/math/generic/log2f16.cpp         | 147 ++++++++++++++++++++++
 libc/src/math/log2f16.h                   |  21 ++++
 libc/test/src/math/CMakeLists.txt         |  11 ++
 libc/test/src/math/log2f16_test.cpp       |  40 ++++++
 libc/test/src/math/smoke/CMakeLists.txt   |  12 ++
 libc/test/src/math/smoke/log2f16_test.cpp |  47 +++++++
 13 files changed, 318 insertions(+), 1 deletion(-)
 create mode 100644 libc/src/math/generic/log2f16.cpp
 create mode 100644 libc/src/math/log2f16.h
 create mode 100644 libc/test/src/math/log2f16_test.cpp
 create mode 100644 libc/test/src/math/smoke/log2f16_test.cpp

diff --git a/libc/config/gpu/entrypoints.txt b/libc/config/gpu/entrypoints.txt
index e6a8e381a9212a..279e397287d8e3 100644
--- a/libc/config/gpu/entrypoints.txt
+++ b/libc/config/gpu/entrypoints.txt
@@ -531,6 +531,7 @@ if(LIBC_TYPES_HAS_FLOAT16)
     libc.src.math.llogbf16
     libc.src.math.llrintf16
     libc.src.math.llroundf16
+    libc.src.math.log2f16
     libc.src.math.logbf16
     libc.src.math.logf16
     libc.src.math.lrintf16
diff --git a/libc/config/linux/x86_64/entrypoints.txt b/libc/config/linux/x86_64/entrypoints.txt
index 69944ce3904562..3fd279071ccb1d 100644
--- a/libc/config/linux/x86_64/entrypoints.txt
+++ b/libc/config/linux/x86_64/entrypoints.txt
@@ -642,6 +642,7 @@ if(LIBC_TYPES_HAS_FLOAT16)
     libc.src.math.llogbf16
     libc.src.math.llrintf16
     libc.src.math.llroundf16
+    libc.src.math.log2f16
     libc.src.math.logbf16
     libc.src.math.logf16
     libc.src.math.lrintf16
diff --git a/libc/docs/math/index.rst b/libc/docs/math/index.rst
index e958312b313589..6b30cac1366d6b 100644
--- a/libc/docs/math/index.rst
+++ b/libc/docs/math/index.rst
@@ -314,7 +314,7 @@ Higher Math Functions
 +-----------+------------------+-----------------+------------------------+----------------------+------------------------+------------------------+----------------------------+
 | log1p     | |check|          | |check|         |                        |                      |                        | 7.12.6.14              | F.10.3.14                  |
 +-----------+------------------+-----------------+------------------------+----------------------+------------------------+------------------------+----------------------------+
-| log2      | |check|          | |check|         |                        |                      |                        | 7.12.6.15              | F.10.3.15                  |
+| log2      | |check|          | |check|         |                        | |check|              |                        | 7.12.6.15              | F.10.3.15                  |
 +-----------+------------------+-----------------+------------------------+----------------------+------------------------+------------------------+----------------------------+
 | log2p1    |                  |                 |                        |                      |                        | 7.12.6.16              | F.10.3.16                  |
 +-----------+------------------+-----------------+------------------------+----------------------+------------------------+------------------------+----------------------------+
diff --git a/libc/spec/stdc.td b/libc/spec/stdc.td
index c3115b19349ff4..de4b8f85e94d11 100644
--- a/libc/spec/stdc.td
+++ b/libc/spec/stdc.td
@@ -562,6 +562,7 @@ def StdC : StandardSpec<"stdc"> {
 
           FunctionSpec<"log2", RetValSpec<DoubleType>, [ArgSpec<DoubleType>]>,
           FunctionSpec<"log2f", RetValSpec<FloatType>, [ArgSpec<FloatType>]>,
+          GuardedFunctionSpec<"log2f16", RetValSpec<Float16Type>, [ArgSpec<Float16Type>], "LIBC_TYPES_HAS_FLOAT16">,
 
           FunctionSpec<"log", RetValSpec<DoubleType>, [ArgSpec<DoubleType>]>,
           FunctionSpec<"logf", RetValSpec<FloatType>, [ArgSpec<FloatType>]>,
diff --git a/libc/src/math/CMakeLists.txt b/libc/src/math/CMakeLists.txt
index 47c4ad188ef6df..23c35828b576f4 100644
--- a/libc/src/math/CMakeLists.txt
+++ b/libc/src/math/CMakeLists.txt
@@ -328,6 +328,7 @@ add_math_entrypoint_object(log1pf)
 
 add_math_entrypoint_object(log2)
 add_math_entrypoint_object(log2f)
+add_math_entrypoint_object(log2f16)
 
 add_math_entrypoint_object(log)
 add_math_entrypoint_object(logf)
diff --git a/libc/src/math/generic/CMakeLists.txt b/libc/src/math/generic/CMakeLists.txt
index 6a9d9f02f190f0..0af3d2ad24e0a3 100644
--- a/libc/src/math/generic/CMakeLists.txt
+++ b/libc/src/math/generic/CMakeLists.txt
@@ -2171,6 +2171,27 @@ add_entrypoint_object(
     -O3
 )
 
+add_entrypoint_object(
+  log2f16
+  SRCS
+    log2f16.cpp
+  HDRS
+    ../log2f16.h
+  DEPENDS
+    .expxf16
+    libc.hdr.errno_macros
+    libc.hdr.fenv_macros
+    libc.src.__support.FPUtil.except_value_utils
+    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.optimization
+    libc.src.__support.macros.properties.cpu_features
+  COMPILE_OPTIONS
+    -O3
+)
+
 add_entrypoint_object(
   log
   SRCS
diff --git a/libc/src/math/generic/expxf16.h b/libc/src/math/generic/expxf16.h
index d64bb432811067..ee1db527eec31a 100644
--- a/libc/src/math/generic/expxf16.h
+++ b/libc/src/math/generic/expxf16.h
@@ -300,6 +300,20 @@ constexpr cpp::array<float, 32> LOGF_F = {
     0x1.52a2d2p-1, 0x1.5ad404p-1,
 };
 
+// Generated by Sollya with the following commands:
+//   > display = hexadecimal;
+//   > for i from 0 to 31 do print(round(log2(1 + i * 2^-5), SG, RN));
+constexpr cpp::array<float, 32> LOG2F_F = {
+    0x0p+0f,        0x1.6bad38p-5f, 0x1.663f7p-4f,  0x1.08c588p-3f,
+    0x1.5c01a4p-3f, 0x1.acf5e2p-3f, 0x1.fbc16cp-3f, 0x1.24407ap-2f,
+    0x1.49a784p-2f, 0x1.6e221cp-2f, 0x1.91bba8p-2f, 0x1.b47ecp-2f,
+    0x1.d6753ep-2f, 0x1.f7a856p-2f, 0x1.0c105p-1f,  0x1.1bf312p-1f,
+    0x1.2b8034p-1f, 0x1.3abb4p-1f,  0x1.49a784p-1f, 0x1.584822p-1f,
+    0x1.66a008p-1f, 0x1.74b1fep-1f, 0x1.82809ep-1f, 0x1.900e62p-1f,
+    0x1.9d5dap-1f,  0x1.aa709p-1f,  0x1.b74948p-1f, 0x1.c3e9cap-1f,
+    0x1.d053f6p-1f, 0x1.dc899ap-1f, 0x1.e88c6cp-1f, 0x1.f45e08p-1f,
+};
+
 // Generated by Sollya with the following commands:
 //   > display = hexadecimal;
 //   > for i from 0 to 31 do print(round(1 / (1 + i * 2^-5), SG, RN));
diff --git a/libc/src/math/generic/log2f16.cpp b/libc/src/math/generic/log2f16.cpp
new file mode 100644
index 00000000000000..83319d001114e5
--- /dev/null
+++ b/libc/src/math/generic/log2f16.cpp
@@ -0,0 +1,147 @@
+//===-- Implementation of log2f16 function --------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/math/log2f16.h"
+#include "expxf16.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/except_value_utils.h"
+#include "src/__support/FPUtil/multiply_add.h"
+#include "src/__support/common.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/optimization.h"
+#include "src/__support/macros/properties/cpu_features.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+#ifdef LIBC_TARGET_CPU_HAS_FMA
+static constexpr size_t N_LOG2F16_EXCEPTS = 2;
+#else
+static constexpr size_t N_LOG2F16_EXCEPTS = 9;
+#endif
+
+static constexpr fputil::ExceptValues<float16, N_LOG2F16_EXCEPTS>
+    LOG2F16_EXCEPTS = {{
+#ifndef LIBC_TARGET_CPU_HAS_FMA
+        // x = 0x1.224p-1, log2f16(x) = -0x1.a34p-1 (RZ)
+        {0x3889U, 0xba8dU, 0U, 1U, 0U},
+        // x = 0x1.e34p-1, log2f16(x) = -0x1.558p-4 (RZ)
+        {0x3b8dU, 0xad56U, 0U, 1U, 0U},
+#endif
+        // x = 0x1.e8cp-1, log2f16(x) = -0x1.128p-4 (RZ)
+        {0x3ba3U, 0xac4aU, 0U, 1U, 0U},
+#ifndef LIBC_TARGET_CPU_HAS_FMA
+        // x = 0x1.f98p-1, log2f16(x) = -0x1.2ep-6 (RZ)
+        {0x3be6U, 0xa4b8U, 0U, 1U, 0U},
+        // x = 0x1.facp-1, log2f16(x) = -0x1.e7p-7 (RZ)
+        {0x3bebU, 0xa39cU, 0U, 1U, 1U},
+#endif
+        // x = 0x1.fb4p-1, log2f16(x) = -0x1.b88p-7 (RZ)
+        {0x3bedU, 0xa2e2U, 0U, 1U, 1U},
+#ifndef LIBC_TARGET_CPU_HAS_FMA
+        // x = 0x1.fecp-1, log2f16(x) = -0x1.cep-9 (RZ)
+        {0x3bfbU, 0x9b38U, 0U, 1U, 1U},
+        // x = 0x1.ffcp-1, log2f16(x) = -0x1.714p-11 (RZ)
+        {0x3bffU, 0x91c5U, 0U, 1U, 1U},
+        // x = 0x1.224p+0, log2f16(x) = 0x1.72cp-3 (RZ)
+        {0x3c89U, 0x31cbU, 1U, 0U, 1U},
+#endif
+    }};
+
+LLVM_LIBC_FUNCTION(float16, log2f16, (float16 x)) {
+  using FPBits = fputil::FPBits<float16>;
+  FPBits x_bits(x);
+
+  uint16_t x_u = x_bits.uintval();
+
+  // If x <= 0, or x is 1, or x is +inf, or x is NaN.
+  if (LIBC_UNLIKELY(x_u == 0U || x_u == 0x3c00U || x_u >= 0x7c00U)) {
+    // log2(NaN) = NaN
+    if (x_bits.is_nan()) {
+      if (x_bits.is_signaling_nan()) {
+        fputil::raise_except_if_required(FE_INVALID);
+        return FPBits::quiet_nan().get_val();
+      }
+
+      return x;
+    }
+
+    // log2(+/-0) = −inf
+    if ((x_u & 0x7fffU) == 0U) {
+      fputil::raise_except_if_required(FE_DIVBYZERO);
+      return FPBits::inf(Sign::NEG).get_val();
+    }
+
+    if (x_u == 0x3c00U)
+      return FPBits::zero().get_val();
+
+    // When x < 0.
+    if (x_u > 0x8000U) {
+      fputil::set_errno_if_required(EDOM);
+      fputil::raise_except_if_required(FE_INVALID);
+      return FPBits::quiet_nan().get_val();
+    }
+
+    // log2(+inf) = +inf
+    return FPBits::inf().get_val();
+  }
+
+  if (auto r = LOG2F16_EXCEPTS.lookup(x_u); LIBC_UNLIKELY(r.has_value()))
+    return r.value();
+
+  // To compute log2(x), we perform the following range reduction:
+  //   x = 2^m * 1.mant,
+  //   log2(x) = m + log2(1.mant).
+  // To compute log2(1.mant), let f be the highest 6 bits including the hidden
+  // bit, and d be the difference (1.mant - f), i.e., the remaining 5 bits of
+  // the mantissa, then:
+  //   log2(1.mant) = log2(f) + log2(1.mant / f)
+  //                = log2(f) + log2(1 + d/f)
+  // since d/f is sufficiently small.
+  // We store log2(f) and 1/f in the lookup tables LOG2F_F and ONE_OVER_F
+  // respectively.
+
+  int m = -FPBits::EXP_BIAS;
+
+  // When x is subnormal.
+  if ((x_u & FPBits::EXP_MASK) == 0U) {
+    // Normalize x.
+    x_bits = FPBits(x_bits.get_val() *
+                    static_cast<float16>((1U << FPBits::FRACTION_LEN)));
+    x_u = x_bits.uintval();
+    m -= FPBits::FRACTION_LEN;
+  }
+
+  uint16_t mant = x_bits.get_mantissa();
+  // Leading 10 - 5 = 5 bits of the mantissa.
+  int f = mant >> 5;
+  // Unbiased exponent.
+  m += x_u >> FPBits::FRACTION_LEN;
+
+  // Set bits to 1.mant instead of 2^m * 1.mant.
+  x_bits.set_biased_exponent(FPBits::EXP_BIAS);
+  float mant_f = x_bits.get_val();
+  // v = 1.mant * 1/f - 1 = d/f
+  float v = fputil::multiply_add(mant_f, ONE_OVER_F[f], -1.0f);
+
+  // Degree-3 minimax polynomial generated by Sollya with the following
+  // commands:
+  //   > display = hexadecimal;
+  //   > P = fpminimax(log2(1 + x)/x, 2, [|SG...|], [-2^-5, 2^-5]);
+  //   > x * P;
+  float log2p1_d_over_f =
+      v * fputil::polyeval(v, 0x1.715476p+0f, -0x1.71771ap-1f, 0x1.ecb38ep-2f);
+  // log2(1.mant) = log2(f) + log2(1 + d/f)
+  float log2_1_mant = LOG2F_F[f] + log2p1_d_over_f;
+  return static_cast<float16>(static_cast<float>(m) + log2_1_mant);
+}
+
+} // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/src/math/log2f16.h b/libc/src/math/log2f16.h
new file mode 100644
index 00000000000000..d89f9f398e2a86
--- /dev/null
+++ b/libc/src/math/log2f16.h
@@ -0,0 +1,21 @@
+//===-- Implementation header for log2f16 -----------------------*- C++ -*-===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_MATH_LOG2F16_H
+#define LLVM_LIBC_SRC_MATH_LOG2F16_H
+
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/properties/types.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+float16 log2f16(float16 x);
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC_MATH_LOG2F16_H
diff --git a/libc/test/src/math/CMakeLists.txt b/libc/test/src/math/CMakeLists.txt
index fabc1b51f5b0c8..81dcfe09cd669b 100644
--- a/libc/test/src/math/CMakeLists.txt
+++ b/libc/test/src/math/CMakeLists.txt
@@ -1798,6 +1798,17 @@ add_fp_unittest(
     libc.src.__support.FPUtil.fp_bits
 )
 
+add_fp_unittest(
+  log2f16_test
+  NEED_MPFR
+  SUITE
+    libc-math-unittests
+  SRCS
+    log2f16_test.cpp
+  DEPENDS
+    libc.src.math.log2f16
+)
+
 add_fp_unittest(
  log10_test
  NEED_MPFR
diff --git a/libc/test/src/math/log2f16_test.cpp b/libc/test/src/math/log2f16_test.cpp
new file mode 100644
index 00000000000000..6630ca877d8d19
--- /dev/null
+++ b/libc/test/src/math/log2f16_test.cpp
@@ -0,0 +1,40 @@
+//===-- Exhaustive test for log2f16 ---------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/math/log2f16.h"
+#include "test/UnitTest/FPMatcher.h"
+#include "test/UnitTest/Test.h"
+#include "utils/MPFRWrapper/MPFRUtils.h"
+
+using LlvmLibcLog2f16Test = LIBC_NAMESPACE::testing::FPTest<float16>;
+
+namespace mpfr = LIBC_NAMESPACE::testing::mpfr;
+
+// Range: [0, Inf];
+static constexpr uint16_t POS_START = 0x0000U;
+static constexpr uint16_t POS_STOP = 0x7c00U;
+
+// Range: [-Inf, 0];
+static constexpr uint16_t NEG_START = 0x8000U;
+static constexpr uint16_t NEG_STOP = 0xfc00U;
+
+TEST_F(LlvmLibcLog2f16Test, PositiveRange) {
+  for (uint16_t v = POS_START; v <= POS_STOP; ++v) {
+    float16 x = FPBits(v).get_val();
+    EXPECT_MPFR_MATCH_ALL_ROUNDING(mpfr::Operation::Log2, x,
+                                   LIBC_NAMESPACE::log2f16(x), 0.5);
+  }
+}
+
+TEST_F(LlvmLibcLog2f16Test, NegativeRange) {
+  for (uint16_t v = NEG_START; v <= NEG_STOP; ++v) {
+    float16 x = FPBits(v).get_val();
+    EXPECT_MPFR_MATCH_ALL_ROUNDING(mpfr::Operation::Log2, x,
+                                   LIBC_NAMESPACE::log2f16(x), 0.5);
+  }
+}
diff --git a/libc/test/src/math/smoke/CMakeLists.txt b/libc/test/src/math/smoke/CMakeLists.txt
index f3aa81506ac4ac..3f69210a6155e3 100644
--- a/libc/test/src/math/smoke/CMakeLists.txt
+++ b/libc/test/src/math/smoke/CMakeLists.txt
@@ -3444,6 +3444,18 @@ add_fp_unittest(
     libc.src.__support.FPUtil.fp_bits
 )
 
+add_fp_unittest(
+  log2f16_test
+  SUITE
+    libc-math-smoke-tests
+  SRCS
+    log2f16_test.cpp
+  DEPENDS
+    libc.hdr.fenv_macros
+    libc.src.errno.errno
+    libc.src.math.log2f16
+)
+
 add_fp_unittest(
   log10_test
   SUITE
diff --git a/libc/test/src/math/smoke/log2f16_test.cpp b/libc/test/src/math/smoke/log2f16_test.cpp
new file mode 100644
index 00000000000000..3e0dda69f805d0
--- /dev/null
+++ b/libc/test/src/math/smoke/log2f16_test.cpp
@@ -0,0 +1,47 @@
+//===-- Unittests for log2f16 ---------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "hdr/fenv_macros.h"
+#include "src/errno/libc_errno.h"
+#include "src/math/log2f16.h"
+#include "test/UnitTest/FPMatcher.h"
+#include "test/UnitTest/Test.h"
+
+using LlvmLibcLog2f16Test = LIBC_NAMESPACE::testing::FPTest<float16>;
+
+TEST_F(LlvmLibcLog2f16Test, SpecialNumbers) {
+  LIBC_NAMESPACE::libc_errno = 0;
+
+  EXPECT_FP_EQ_ALL_ROUNDING(aNaN, LIBC_NAMESPACE::log2f16(aNaN));
+  EXPECT_MATH_ERRNO(0);
+
+  EXPECT_FP_EQ_WITH_EXCEPTION(aNaN, LIBC_NAMESPACE::log2f16(sNaN), FE_INVALID);
+  EXPECT_MATH_ERRNO(0);
+
+  EXPECT_FP_EQ_ALL_ROUNDING(inf, LIBC_NAMESPACE::log2f16(inf));
+  EXPECT_MATH_ERRNO(0);
+
+  EXPECT_FP_EQ_ALL_ROUNDING(aNaN, LIBC_NAMESPACE::log2f16(neg_inf));
+  EXPECT_MATH_ERRNO(EDOM);
+
+  EXPECT_FP_EQ_WITH_EXCEPTION_ALL_ROUNDING(
+      neg_inf, LIBC_NAMESPACE::log2f16(zero), FE_DIVBYZERO);
+  EXPECT_MATH_ERRNO(0);
+
+  EXPECT_FP_EQ_WITH_EXCEPTION_ALL_ROUNDING(
+      neg_inf, LIBC_NAMESPACE::log2f16(neg_zero), FE_DIVBYZERO);
+  EXPECT_MATH_ERRNO(0);
+
+  EXPECT_FP_EQ_ALL_ROUNDING(zero,
+                            LIBC_NAMESPACE::log2f16(static_cast<float16>(1.0)));
+  EXPECT_MATH_ERRNO(0);
+
+  EXPECT_FP_EQ_ALL_ROUNDING(
+      aNaN, LIBC_NAMESPACE::log2f16(static_cast<float16>(-1.0)));
+  EXPECT_MATH_ERRNO(EDOM);
+}



More information about the llvm-branch-commits mailing list