https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92712
--- Comment #13 from Jakub Jelinek <jakub at gcc dot gnu.org> --- Ok, so match.pd does the following transformations: A*B+A -> (B+1)*A A*B-A -> (B-1)*A A-A*B -> (1-B)*A A*B+A*C -> (B+C)*A A*B-A*C -> (B-C)*A (ignoring equivalent expressions with commutative + or *). Let's consider for start just the simpler 3 cases. For those, I believe the only cases where these introduce UB when it wasn't before in two's complement world are: A*B+A -> (B+1)*A with A==-1 && B==max A*B+A -> (B+1)*A with A==0 && B==max A*B-A -> (B-1)*A with A==0 && B==min A-A*B -> (1-B)*A with A==-1 && B==-max A-A*B -> (1-B)*A with A==0 && B==min A-A*B -> (1-B)*A with A==0 && B==-max Now, the current match.pd patterns disable this optimization if A might be 0 or -1. So, what we could do is: 1) for the A*B-A case, drop the must not be -1 check 2) add the checks for the ranges of the other operand, say for the first one it is fine if we don't know anything about A (@0) if we know the B (@1) is not maximum. For the last 2, the question is if we can come up with something similar.