[flang-commits] [PATCH] D151272: [flang] Fix SPACING() of very small values

Peter Klausler via Phabricator via flang-commits flang-commits at lists.llvm.org
Tue May 23 17:11:38 PDT 2023


klausler created this revision.
klausler added a reviewer: vdonaldson.
klausler added a project: Flang.
Herald added subscribers: sunshaoce, jdoerfert.
Herald added a project: All.
klausler requested review of this revision.

SPACING() must return TINY() for zero arguments (which we do)
and also for subnormal values smaller than TINY() in absolute value,
which we get wrong.  Fix folding and the runtime.


https://reviews.llvm.org/D151272

Files:
  flang/lib/Evaluate/real.cpp
  flang/runtime/numeric.cpp
  flang/test/Evaluate/fold-spacing.f90


Index: flang/test/Evaluate/fold-spacing.f90
===================================================================
--- flang/test/Evaluate/fold-spacing.f90
+++ flang/test/Evaluate/fold-spacing.f90
@@ -7,6 +7,7 @@
   logical, parameter :: test_4 = spacing(0.) == tiny(0.)
   logical, parameter :: test_5 = spacing(tiny(0.)) == 1.e-45
   logical, parameter :: test_6 = spacing(8388608.) == 1.
+  logical, parameter :: test_7 = spacing(spacing(tiny(.0))) == tiny(0.)
   logical, parameter :: test_11 = rrspacing(3.0) == scale(0.75, 24)
   logical, parameter :: test_12 = rrspacing(-3.0) == scale(0.75, 24)
   logical, parameter :: test_13 = rrspacing(3.0d0) == scale(0.75, 53)
Index: flang/runtime/numeric.cpp
===================================================================
--- flang/runtime/numeric.cpp
+++ flang/runtime/numeric.cpp
@@ -239,8 +239,9 @@
     // subnormal.
     return std::numeric_limits<T>::min(); // 0 -> TINY(x)
   } else {
-    return std::ldexp(
-        static_cast<T>(1.0), std::ilogb(x) + 1 - PREC); // 2**(e-p)
+    T result{
+        std::ldexp(static_cast<T>(1.0), std::ilogb(x) + 1 - PREC)}; // 2**(e-p)
+    return result == 0 ? /*TINY(x)*/ std::numeric_limits<T>::min() : result;
   }
 }
 
Index: flang/lib/Evaluate/real.cpp
===================================================================
--- flang/lib/Evaluate/real.cpp
+++ flang/lib/Evaluate/real.cpp
@@ -745,12 +745,12 @@
     return *this;
   } else if (IsInfinite()) {
     return NotANumber();
-  } else if (IsZero()) {
-    return TINY();
+  } else if (IsZero() || IsSubnormal()) {
+    return TINY(); // mandated by standard
   } else {
     Real result;
     result.Normalize(false, Exponent(), Fraction::MASKR(1));
-    return result;
+    return result.IsZero() ? TINY() : result;
   }
 }
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D151272.524942.patch
Type: text/x-patch
Size: 1785 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/flang-commits/attachments/20230524/60b7c6be/attachment.bin>


More information about the flang-commits mailing list