[libc-commits] [libc] [libc][math] Ensure fputil::nextafter is called with correct type args (PR #75009)

Nishant Mittal via libc-commits libc-commits at lists.llvm.org
Sun Dec 10 12:00:15 PST 2023


https://github.com/nishantwrp created https://github.com/llvm/llvm-project/pull/75009

Follow up to https://github.com/llvm/llvm-project/pull/73698#discussion_r1411134482

>From 1d8762599f45b17656b187a440b4bfdf90592309 Mon Sep 17 00:00:00 2001
From: Nishant Mittal <nishantwrp at google.com>
Date: Sun, 10 Dec 2023 19:57:11 +0000
Subject: [PATCH] [libc][math] Ensure fputil::nextafter is called with correct
 type args

---
 libc/src/__support/FPUtil/ManipulationFunctions.h | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

diff --git a/libc/src/__support/FPUtil/ManipulationFunctions.h b/libc/src/__support/FPUtil/ManipulationFunctions.h
index 9d3fd075be4711..08adb074b121fa 100644
--- a/libc/src/__support/FPUtil/ManipulationFunctions.h
+++ b/libc/src/__support/FPUtil/ManipulationFunctions.h
@@ -144,10 +144,11 @@ LIBC_INLINE T ldexp(T x, int exp) {
   return normal;
 }
 
-template <
-    typename T, typename U,
-    cpp::enable_if_t<cpp::is_floating_point_v<T> && cpp::is_floating_point_v<U>,
-                     int> = 0>
+template <typename T, typename U,
+          cpp::enable_if_t<cpp::is_floating_point_v<T> &&
+                               cpp::is_floating_point_v<U> &&
+                               (sizeof(T) <= sizeof(U)),
+                           int> = 0>
 LIBC_INLINE T nextafter(T from, U to) {
   FPBits<T> from_bits(from);
   if (from_bits.is_nan())
@@ -157,6 +158,9 @@ LIBC_INLINE T nextafter(T from, U to) {
   if (to_bits.is_nan())
     return static_cast<T>(to);
 
+  // NOTE: This would work only if `U` has a greater or equal precision than
+  // `T`. Otherwise `from` could loose its precision and the following statement
+  // could incorrectly evaluate to `true`.
   if (static_cast<U>(from) == to)
     return static_cast<T>(to);
 



More information about the libc-commits mailing list