fold-const: do not fold NaN result from non-NaN operands [PR95115]
authorXi Ruoyao <xry111@mengyan1223.wang>
Sun, 30 Jan 2022 17:15:20 +0000 (01:15 +0800)
committerXi Ruoyao <xry111@mengyan1223.wang>
Tue, 1 Feb 2022 10:20:57 +0000 (18:20 +0800)
These operations should raise an invalid operation exception at runtime.
So they should not be folded during compilation unless -fno-trapping-math
is used.

gcc/
PR middle-end/95115
* fold-const.cc (const_binop): Do not fold NaN result from
  non-NaN operands.

gcc/testsuite
* gcc.dg/pr95115.c: New test.

gcc/fold-const.cc
gcc/testsuite/gcc.dg/pr95115.c [new file with mode: 0644]

index b155611..8fc01cd 100644 (file)
@@ -1306,6 +1306,17 @@ const_binop (enum tree_code code, tree arg1, tree arg2)
       real_convert (&result, mode, &value);
 
       /* Don't constant fold this floating point operation if
+        both operands are not NaN but the result is NaN, and
+        flag_trapping_math.  Such operations should raise an
+        invalid operation exception.  */
+      if (flag_trapping_math
+         && MODE_HAS_NANS (mode)
+         && REAL_VALUE_ISNAN (result)
+         && !REAL_VALUE_ISNAN (d1)
+         && !REAL_VALUE_ISNAN (d2))
+       return NULL_TREE;
+
+      /* Don't constant fold this floating point operation if
         the result has overflowed and flag_trapping_math.  */
       if (flag_trapping_math
          && MODE_HAS_INFINITIES (mode)
diff --git a/gcc/testsuite/gcc.dg/pr95115.c b/gcc/testsuite/gcc.dg/pr95115.c
new file mode 100644 (file)
index 0000000..46a95df
--- /dev/null
@@ -0,0 +1,25 @@
+/* { dg-do run } */
+/* { dg-options "-O2 -ftrapping-math" } */
+/* { dg-add-options ieee } */
+/* { dg-require-effective-target fenv_exceptions } */
+
+#include <fenv.h>
+#include <stdlib.h>
+
+double
+x (void)
+{
+  double d = __builtin_inf ();
+  return d / d;
+}
+
+int
+main (void)
+{
+  double r = x ();
+  if (!__builtin_isnan (r))
+       abort ();
+  if (!fetestexcept (FE_INVALID))
+       abort ();
+  exit (0);
+}