https://gcc.gnu.org/g:79c77e1642030361a17b3c892a00092d8285a3b2
commit r17-2215-g79c77e1642030361a17b3c892a00092d8285a3b2 Author: Pengfei Li <[email protected]> Date: Mon Jul 6 13:11:32 2026 +0000 match.pd: Fold SAD_EXPR with identical inputs Normally, SAD_EXPRs with identical first and second operands are not constructed, since the absolute difference value is zero. However, this can still appear when vectorizing small iteration-count reduction loops with an absolute difference operation. This patch adds a match.pd rule to fold the redundant SAD_EXPR to its accumulator operand. Bootstrapped and tested on aarch64-linux-gnu and x86_64-linux-gnu. gcc/ChangeLog: * match.pd: Simplify SAD(x, x, acc) into acc. gcc/testsuite/ChangeLog: * gcc.target/aarch64/sve/sad_2.c: New test. Diff: --- gcc/match.pd | 7 +++++++ gcc/testsuite/gcc.target/aarch64/sve/sad_2.c | 16 ++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/gcc/match.pd b/gcc/match.pd index a7cec25dbad8..4520a23a026b 100644 --- a/gcc/match.pd +++ b/gcc/match.pd @@ -1229,6 +1229,13 @@ DEFINE_INT_AND_FLOAT_ROUND_FN (RINT) (mult (absu@1 @0) @1) (mult (convert@2 @0) @2)) +#if GIMPLE +/* Simplify SAD(x, x, acc) -> acc since the absolute difference is zero. */ +(simplify + (sad @0 @0 @1) + @1) +#endif + /* cos(copysign(x, y)) -> cos(x). Similarly for cosh. */ (for coss (COS COSH) (for copysigns (COPYSIGN) diff --git a/gcc/testsuite/gcc.target/aarch64/sve/sad_2.c b/gcc/testsuite/gcc.target/aarch64/sve/sad_2.c new file mode 100644 index 000000000000..d46517f10d86 --- /dev/null +++ b/gcc/testsuite/gcc.target/aarch64/sve/sad_2.c @@ -0,0 +1,16 @@ +/* { dg-do compile } */ +/* { dg-options "-O3 -msve-vector-bits=128 -mtune=neoverse-v2" } */ + +#include <stdint.h> + +int foo (uint8_t *pix1, uint8_t *pix2) +{ + int sum = 0; + for (int x = 0; x < 48; x++) + { + sum += __builtin_abs (pix1[x] - pix2[x]); + } + return sum; +} + +/* { dg-final { scan-assembler-times {\tudot\t} 3 } } */
