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

--- Comment #30 from CVS Commits <cvs-commit at gcc dot gnu.org> ---
The master branch has been updated by Roger Sayle <sa...@gcc.gnu.org>:

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

commit r13-6621-geb1d8df792f990574cbb695b55c92ee2684fc96b
Author: Roger Sayle <ro...@nextmovesoftware.com>
Date:   Sun Mar 12 22:52:41 2023 +0000

    PR middle-end/109031: Fix final value replacement from narrower IVs.

    This patch fixes a P1 regression, a problem with my February 2022 patch
    to improve folding for final value replacement:
    https://gcc.gnu.org/pipermail/gcc-patches/2022-February/590618.html

    The motivation for the original patch is that because we know the number
    of loop iterations can't be negative, final value expressions such as
    (int) ((unsigned int) x + 4294967295) + 1 can be simplified to x,
    as this is effectively ((x - 1) + 1) without overflow.

    The bug/oversight is that using integer_all_onesp to check for the
    implicit tree constant -1 it didn't consider that the inner (unsigned)
    type might be narrower than hthe outer result type.  For the case in the
    PR, (int)((unsigned char)x + 255) + 1 gets simplified to (int)x, but
    when x is originally zero, the correct result should be 256.

    The fix is to check that the inner type's precision (the width of the
    subtraction) is at least as wide as the result type (that of the addition).

    I've also added a test for signed types, but without -fwrapv this
    invokes undefined behaviour, and with -fwrapv it doesn't exhibit the
    problem in the PR.

    2023-03-12  Roger Sayle  <ro...@nextmovesoftware.com>

    gcc/ChangeLog
            PR middle-end/109031
            * tree-chrec.cc (chrec_apply): When folding "{a, +, a} (x-1)",
            ensure that the type of x is as wide or wider than the type of a.

    gcc/testsuite/ChangeLog
            PR middle-end/109031
            * gcc.dg/tree-ssa/pr109031-1.c: New test case.
            * gcc.dg/tree-ssa/pr109031-2.c: Likewise.

Reply via email to