[flang-commits] [flang] [flang] Fix folding of NEAREST(TINY(1.), -1.) (PR #76590)

Peter Klausler via flang-commits flang-commits at lists.llvm.org
Tue Jan 2 07:52:39 PST 2024


https://github.com/klausler updated https://github.com/llvm/llvm-project/pull/76590

>From c4c69b1a4905fbe49430d8221ea3179f32767724 Mon Sep 17 00:00:00 2001
From: Peter Klausler <pklausler at nvidia.com>
Date: Fri, 29 Dec 2023 14:14:55 -0800
Subject: [PATCH] [flang] Fix folding of NEAREST(TINY(1.),-1.)

The code to fold NEAREST would return a value that's too large
when transitioning from a normal number to a subnormal.

Fixes llvm-test-suite/Fortran/gfortran/regression/nearest_1.f90.
---
 flang/lib/Evaluate/real.cpp          | 2 +-
 flang/test/Evaluate/fold-nearest.f90 | 2 ++
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/flang/lib/Evaluate/real.cpp b/flang/lib/Evaluate/real.cpp
index 4fecaa1a131f81d..cb8be98bb6f40fc 100644
--- a/flang/lib/Evaluate/real.cpp
+++ b/flang/lib/Evaluate/real.cpp
@@ -350,7 +350,7 @@ ValueWithRealFlags<Real<W, P>> Real<W, P>::NEAREST(bool upward) const {
         isNegative = !isNegative;
       } else {
         auto sub1{fraction.SubtractSigned(one)};
-        if (sub1.overflow) {
+        if (sub1.overflow && expo > 1) {
           nearest = Fraction{0}.NOT();
           --expo;
         } else {
diff --git a/flang/test/Evaluate/fold-nearest.f90 b/flang/test/Evaluate/fold-nearest.f90
index 99af303128411cf..bd8b020c392ac39 100644
--- a/flang/test/Evaluate/fold-nearest.f90
+++ b/flang/test/Evaluate/fold-nearest.f90
@@ -26,6 +26,8 @@ module m1
   logical, parameter :: test_14 = nearest(0., negZero) == -minSubnormal
   !WARN: warning: NEAREST: S argument is zero
   logical, parameter :: test_15 = nearest(negZero, 0.) == minSubnormal
+  logical, parameter :: test_16 = nearest(tiny(1.),-1.) == 1.1754942E-38
+  logical, parameter :: test_17 = nearest(tiny(1.),1.) == 1.1754945E-38
 end module
 
 module m2



More information about the flang-commits mailing list