https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113138
--- Comment #5 from GCC Commits <cvs-commit at gcc dot gnu.org> --- The master branch has been updated by Jeff Law <[email protected]>: https://gcc.gnu.org/g:620481eb9427f0f2cbb76192f5bf009b5a54b2c9 commit r17-7056-g620481eb9427f0f2cbb76192f5bf009b5a54b2c9 Author: Wesley Lewis <[email protected]> Date: Wed Dec 2 22:05:05 2026 -0700 [PATCH] match: Fold x CMP ~x into a sign-bit test [PR113138] A value and it's bitwise complement are mirror images around the middle of the type's range: for signed x, ~x == -x - 1, and for unsigned x of precision p, ~x == 2^p - 1 - x. Comparing x with ~x therefore depends only on the sign-bit of x. x < ~x, x <= ~x -> x < C x > ~x, x >= ~x -> x >= C where C is 0 for signed x and 2^(p-1) for unsigned x. x == ~x is impossible, sinc x + ~x has every bit set, so le/ge fold to the same result as lt/gt. For unsigned x, existing patterns canonicalise the result further to (signed) x >= 0 or (signed) x < 0. bitwise_inverted_equal_p matches the complement on either side, so ~x cmp x is handled too: the result is built from ~x, and the existing ~x cmp C pattern then removes the complement. When the operands are a comparison and it's inverse, the fold is restricted to 1-bit operands, where logical and bitwise negation agree. Only scalar integral types are handled. PR tree-optimization/113138 gcc/ChangeLog: * match.pd (x cmp ~x): New pattern. gcc/testsuite/ChangeLog: * gcc.dg/tree-ssa/pr113138-1.c: New test. * gcc.dg/tree-ssa/pr113138-2.c: New test. * gcc.dg/tree-ssa/pr113138-3.c: New test. * gcc.dg/tree-ssa/pr113138-4.c: New test. * gcc.dg/tree-ssa/pr113138-5.c: New test. Signed-off-by: Wesley Lewis <[email protected]>
