[libc-commits] [libc] [libc][NFC] Simplify logic in `sqrt` (PR #80426)

via libc-commits libc-commits at lists.llvm.org
Fri Feb 2 04:44:28 PST 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libc

Author: Guillaume Chatelet (gchatelet)

<details>
<summary>Changes</summary>



---
Full diff: https://github.com/llvm/llvm-project/pull/80426.diff


2 Files Affected:

- (modified) libc/src/__support/FPUtil/generic/sqrt.h (+5-11) 
- (modified) libc/src/__support/FPUtil/generic/sqrt_80_bit_long_double.h (+5-11) 


``````````diff
diff --git a/libc/src/__support/FPUtil/generic/sqrt.h b/libc/src/__support/FPUtil/generic/sqrt.h
index 702de3f04a9bf..15ac1d3545e95 100644
--- a/libc/src/__support/FPUtil/generic/sqrt.h
+++ b/libc/src/__support/FPUtil/generic/sqrt.h
@@ -78,20 +78,14 @@ LIBC_INLINE cpp::enable_if_t<cpp::is_floating_point_v<T>, T> sqrt(T x) {
 
     FPBits_t bits(x);
 
-    if (bits.is_inf_or_nan()) {
-      if (bits.is_neg() && (bits.get_mantissa() == 0)) {
-        // sqrt(-Inf) = NaN
-        return FLT_NAN;
-      } else {
-        // sqrt(NaN) = NaN
-        // sqrt(+Inf) = +Inf
-        return x;
-      }
-    } else if (bits.is_zero()) {
+    if (bits == FPBits_t::inf(Sign::POS) || bits.is_zero()) {
+      // sqrt(+Inf) = +Inf
       // sqrt(+0) = +0
       // sqrt(-0) = -0
       return x;
-    } else if (bits.is_neg()) {
+    } else if (bits.is_inf_or_nan() || bits.is_neg()) {
+      // sqrt(-Inf) = NaN
+      // sqrt(NaN) = NaN
       // sqrt( negative numbers ) = NaN
       return FLT_NAN;
     } else {
diff --git a/libc/src/__support/FPUtil/generic/sqrt_80_bit_long_double.h b/libc/src/__support/FPUtil/generic/sqrt_80_bit_long_double.h
index 74a536c04817c..2146019011986 100644
--- a/libc/src/__support/FPUtil/generic/sqrt_80_bit_long_double.h
+++ b/libc/src/__support/FPUtil/generic/sqrt_80_bit_long_double.h
@@ -43,20 +43,14 @@ LIBC_INLINE long double sqrt(long double x) {
 
   LDBits bits(x);
 
-  if (bits.is_inf_or_nan()) {
-    if (bits.is_neg() && (bits.get_mantissa() == 0)) {
-      // sqrt(-Inf) = NaN
-      return LDNAN;
-    } else {
-      // sqrt(NaN) = NaN
-      // sqrt(+Inf) = +Inf
-      return x;
-    }
-  } else if (bits.is_zero()) {
+  if (bits == LDBits::inf(Sign::POS) || bits.is_zero()) {
+    // sqrt(+Inf) = +Inf
     // sqrt(+0) = +0
     // sqrt(-0) = -0
     return x;
-  } else if (bits.is_neg()) {
+  } else if (bits.is_inf_or_nan() || bits.is_neg()) {
+    // sqrt(-Inf) = NaN
+    // sqrt(NaN) = NaN
     // sqrt( negative numbers ) = NaN
     return LDNAN;
   } else {

``````````

</details>


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


More information about the libc-commits mailing list