https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120837

--- Comment #18 from GCC Commits <cvs-commit at gcc dot gnu.org> ---
The master branch has been updated by Jakub Jelinek <ja...@gcc.gnu.org>:

https://gcc.gnu.org/g:e16820d4f7ab1d8a40f70beef722e6f8a4c2392c

commit r16-2000-ge16820d4f7ab1d8a40f70beef722e6f8a4c2392c
Author: Jakub Jelinek <ja...@redhat.com>
Date:   Fri Jul 4 07:50:12 2025 +0200

    c-family: Tweak ptr +- (expr +- cst) FE optimization [PR120837]

    The following testcase is miscompiled with -fsanitize=undefined but we
    introduce UB into the IL even without that flag.

    The optimization ptr +- (expr +- cst) when expr/cst have undefined
    overflow into (ptr +- cst) +- expr is sometimes simply not valid,
    without careful analysis on what ptr points to we don't know if it
    is valid to do (ptr +- cst) pointer arithmetics.
    E.g. on the testcase, ptr points to start of an array (actually
    conditionally one or another) and cst is -1, so ptr - 1 is invalid
    pointer arithmetics, while ptr + (expr - 1) can be valid if expr
    is at runtime always > 1 and smaller than size of the array ptr points
    to + 1.

    Unfortunately, removing this 1992-ish optimization altogether causes
    FAIL: c-c++-common/restrict-2.c  -Wc++-compat   scan-tree-dump-times lim2
"Moving statement" 11
    FAIL: gcc.dg/tree-ssa/copy-headers-5.c scan-tree-dump ch2 "is now do-while
loop"
    FAIL: gcc.dg/tree-ssa/copy-headers-5.c scan-tree-dump-times ch2 "  if " 3
    FAIL: gcc.dg/vect/pr57558-2.c scan-tree-dump vect "vectorized 1 loops"
    FAIL: gcc.dg/vect/pr57558-2.c -flto -ffat-lto-objects  scan-tree-dump vect
"vectorized 1 loops"
    regressions (restrict-2.c also for C++ in all std modes).  I've been
thinking
    about some match.pd optimization for signed integer addition/subtraction of
    constant followed by widening integral conversion followed by
multiplication
    or left shift, but that wouldn't help 32-bit arches.

    So, instead at least for now, the following patch keeps doing the
    optimization, just doesn't perform it in pointer arithmetics.
    pointer_int_sum itself actually adds the multiplication by size_exp,
    so ptr + expr is turned into ptr p+ expr * size_exp,
    so this patch will try to optimize
    ptr + (expr +- cst)
    into
    ptr p+ ((sizetype)expr * size_exp +- (sizetype)cst * size_exp)
    and
    ptr - (expr +- cst)
    into
    ptr p+ -((sizetype)expr * size_exp +- (sizetype)cst * size_exp)

    2025-07-04  Jakub Jelinek  <ja...@redhat.com>

            PR c/120837
            * c-common.cc (pointer_int_sum): Rewrite the intop PLUS_EXPR or
            MINUS_EXPR optimization into extension of both intop operands,
            their separate multiplication and then addition/subtraction
followed
            by rest of pointer_int_sum handling after the multiplication.

            * gcc.dg/ubsan/pr120837.c: New test.

Reply via email to