https://gcc.gnu.org/g:aa4aafbad5235fd302c39e1d8b7cb9cdea11c67c
commit r16-3802-gaa4aafbad5235fd302c39e1d8b7cb9cdea11c67c Author: Matteo Nicoli <matteo.nicoli...@gmail.com> Date: Fri Aug 22 20:42:12 2025 +0200 tree-optimization/121595 - new fabs(a+0.0) -> fabs(a) pattern 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.nicoli...@gmail.com> Reviewed-by: Andrew Pinski <andrew.pin...@oss.qualcomm.com> Diff: --- gcc/match.pd | 9 +++++++++ gcc/testsuite/gcc.dg/fabs-plus-zero-1.c | 9 +++++++++ gcc/testsuite/gcc.dg/fabs-plus-zero-2.c | 10 ++++++++++ 3 files changed, 28 insertions(+) diff --git a/gcc/match.pd b/gcc/match.pd index b1d7a3a1b73f..f61beb60d270 100644 --- a/gcc/match.pd +++ b/gcc/match.pd @@ -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 index 000000000000..c4a5a298334e --- /dev/null +++ b/gcc/testsuite/gcc.dg/fabs-plus-zero-1.c @@ -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 index 000000000000..0bc7934353d0 --- /dev/null +++ b/gcc/testsuite/gcc.dg/fabs-plus-zero-2.c @@ -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" } } */