On Wed, Sep 9, 2026 at 11:12 AM <[email protected]> wrote:
>
> From: Ezra Sitorus <[email protected]>
>
> Add a new pattern to split up negative product pattern to make it easier
> to match in further negative dot product matcher.
>
> A previous attempt went like this:
> (a*b - c*d) + acc -> a*b + (acc + (-b * c))
> but this caused an infinite simplification loop during bootstrap build.
>
> gcc/ChangeLog:
> * match.pd: Add new pattern.
>
> gcc/testsuite/ChangeLog:
> * gcc.dg/tree-ssa/neg-dot-prod-1.c: Add new test.
> ---
> gcc/match.pd | 8 ++++++++
> .../gcc.dg/tree-ssa/neg-dot-prod-1.c | 19 +++++++++++++++++++
> 2 files changed, 27 insertions(+)
> create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/neg-dot-prod-1.c
>
> diff --git a/gcc/match.pd b/gcc/match.pd
> index 032f29dcbc25..185b4b7c6089 100644
> --- a/gcc/match.pd
> +++ b/gcc/match.pd
> @@ -13407,3 +13407,11 @@ and,
> (if (INTEGRAL_TYPE_P (type))
> (with { tree itype = TREE_TYPE (@2); }
> (convert (minus @2 (convert:itype @1))))))
> +
> +(simplify
> + (plus:c (minus (mult:s @0 @1) (mult:s @2 @3)) @4)
> + (if (INTEGRAL_TYPE_P (type)
> + && !TYPE_OVERFLOW_TRAPS (type)
> + && !TYPE_OVERFLOW_SANITIZED (type)
> + && !TYPE_SATURATING (type))
> + (minus (plus @4 (mult @0 @1)) (mult @2 @3))))
Why not reuse the 2 mults? Since they are the same?
In fact why isn't this handled by the reassociation?
I think your current match pattern can introduce some undefined behavior.
(a*b - c*d) + acc -> (acc + a*b) - c*d
say a*b is INT_MIN, c*d is INT_MIN and acc is -1.
Before we would have (INT_MIN - INT_MIN) + -1 which is well defined
and has no overflow involved.
But with your pattern we would get `(INT_MIN + -1) - INT_MIN` which
is undefined as `(INT_MIN + -1)` has an overflow (underflow?).
Even a*b being INT_MAX and c*d being INT_MAX and acc being 1 would
have an overflow with your pattern.
> diff --git a/gcc/testsuite/gcc.dg/tree-ssa/neg-dot-prod-1.c
> b/gcc/testsuite/gcc.dg/tree-ssa/neg-dot-prod-1.c
> new file mode 100644
> index 000000000000..289312ddafc7
> --- /dev/null
> +++ b/gcc/testsuite/gcc.dg/tree-ssa/neg-dot-prod-1.c
> @@ -0,0 +1,19 @@
> +/* { dg-do compile } */
> +/* { dg-options "-O1 -fdump-tree-gimple" } */
> +
> +int
> +f1 (int acc, int a, int b, int c, int d)
> +{
> + return acc + (a * b - c * d);
> +}
> +
> +int
> +f2 (int acc, int a, int b, int c, int d)
> +{
> + return (a * b - c * d) + acc;
> +}
> +
> +/* The pattern in match.pd should convert the above to
> + (acc + a*b) - c*d */
> +/* { dg-final { scan-tree-dump
> + "_[0-9]+ = acc(_[0-9]+)? \\+ _[0-9]+;" 2 "gimple" } } */
> --
> 2.53.0
>