]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
tree-optimization/121595 - new fabs(a+0.0) -> fabs(a) pattern
authorMatteo Nicoli <matteo.nicoli001@gmail.com>
Fri, 22 Aug 2025 18:42:12 +0000 (20:42 +0200)
committerRichard Biener <rguenther@suse.de>
Thu, 11 Sep 2025 11:19:03 +0000 (13:19 +0200)
With -fno-trapping-math it is safe to optimize fabs(a + 0.0) as
fabs (a).

PR tree-optimization/121595
* match.pd (fabs(a + 0.0) -> fabs (a)): Optimization pattern limited to
the -fno-trapping-math case.

* gcc.dg/fabs-plus-zero-1.c: New testcase.
* gcc.dg/fabs-plus-zero-2.c: Likewise.

Signed-off-by: Matteo Nicoli <matteo.nicoli001@gmail.com>
Reviewed-by: Andrew Pinski <andrew.pinski@oss.qualcomm.com>
gcc/match.pd
gcc/testsuite/gcc.dg/fabs-plus-zero-1.c [new file with mode: 0644]
gcc/testsuite/gcc.dg/fabs-plus-zero-2.c [new file with mode: 0644]

index b1d7a3a1b73f1f55fba2bf06b090188f8a1d7991..f61beb60d27083dccb020e2dbc11817f7a944769 100644 (file)
@@ -2045,6 +2045,15 @@ DEFINE_INT_AND_FLOAT_ROUND_FN (RINT)
  (abs (negate @0))
  (abs @0))
 
+/* fabs(x + 0.0) -> fabs(x), safe even with signed zeros when -fno-trapping-math.
+   With non-default exception handling denormal + 0.0 might trap.
+   Otherwise !HONOR_SNANS would be sufficient here.  */
+(for op (plus minus)
+ (simplify
+  (abs (op @0 real_zerop@1))
+  (if (!flag_trapping_math)
+   (abs @0))))
+
 (simplify
  (absu (negate @0))
  (absu @0))
diff --git a/gcc/testsuite/gcc.dg/fabs-plus-zero-1.c b/gcc/testsuite/gcc.dg/fabs-plus-zero-1.c
new file mode 100644 (file)
index 0000000..c4a5a29
--- /dev/null
@@ -0,0 +1,9 @@
+/* With trapping-math enabled (default behavior), GCC must preserve the +0.0 */
+/* { dg-do compile } */
+/* { dg-options "-O2 -fdump-tree-optimized" } */
+
+double f(double a)
+{
+  return __builtin_fabs(a + 0.0);
+}
+/* { dg-final { scan-tree-dump-times "\\+ 0\\.0" 1 "optimized" } } */
diff --git a/gcc/testsuite/gcc.dg/fabs-plus-zero-2.c b/gcc/testsuite/gcc.dg/fabs-plus-zero-2.c
new file mode 100644 (file)
index 0000000..0bc7934
--- /dev/null
@@ -0,0 +1,10 @@
+/* With -fno-trapping-math it is safe to fold away (+/-)0.0  */
+/* { dg-do compile } */
+/* { dg-options "-O2 -fno-trapping-math -fdump-tree-optimized" } */
+
+double f1(double a) { return __builtin_fabs(a + 0.0); }
+double f2(double a) { return __builtin_fabs(a + -0.0); }
+double f3(double a) { return __builtin_fabs(a - 0.0); }
+double f4(double a) { return __builtin_fabs(a - -0.0); }
+
+/* { dg-final { scan-tree-dump-not "\\+ 0\\.0" "optimized" } } */