https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128749
Bug ID: 128749
Summary: wrong code with -fwrapv / -fno-strict-overflow: fold
negates the divisor of INT_MIN / (x + 1) and
introduces a trapping INT_MIN / -1
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Keywords: wrong-code
Severity: normal
Priority: P3
Component: middle-end
Assignee: unassigned at gcc dot gnu.org
Reporter: jeffchen006 at gmail dot com
Target Milestone: ---
Target: x86_64-pc-linux-gnu
#include <cstdio>
int x = 0;
int main() {
int r = -5 - (-2147483647 - 1) / (x + 1);
printf("%d\n", r);
}
$ g++ -O0 t.cpp && ./a.out
2147483643
$ g++ -O0 -fwrapv t.cpp && ./a.out
Floating point exception
Same SIGFPE at -O1, -O2, -O3 with -fwrapv, and with -fno-strict-overflow (Linux
kernel flag). Clang -fwrapv gives 2147483643.
Expected 2147483643: x + 1 = 1, INT_MIN / 1 = INT_MIN, -5 - INT_MIN =
2147483643. The program has no overflow at all, so -fwrapv must not change the
result.
-fdump-tree-original with -fwrapv:
int r = -2147483648 / ~x + -5;
A - C / B is folded to A + C / -B, and -(x + 1) to ~x. For x = 0 this is
INT_MIN / -1, which traps on x86.
Cause: negate_expr_p and fold_negate_expr_1 (fold-const.cc), TRUNC_DIV_EXPR:
/* In general we can't negate B in A / B, because if A is INT_MIN and
B is 1, we may turn this into INT_MIN / -1 which is undefined
and actually traps on some architectures. */
if (! ANY_INTEGRAL_TYPE_P (TREE_TYPE (t))
|| TYPE_OVERFLOW_WRAPS (TREE_TYPE (t))
|| ...)
return negate_expr_p (TREE_OPERAND (t, 1));
The comment gives the reason, but TYPE_OVERFLOW_WRAPS still allows negating B.
With -fwrapv INT_MIN / -1 is INT_MIN in theory, but GCC emits a plain idiv
(PR30484), so the fold adds a trap the source never runs. Negating B should not
be allowed for a signed wrapping type unless A is known not to be INT_MIN or B
is known not to be 1. 7.5 is correct; 8.5 and later trap (probably exposed by
the -(X + 1) -> ~X fold).
PR127406 is the same class (a fold creating a trapping INT_MIN / -1) for
another fold, fixed by r17-4415.
gcc -Wall -Wextra gives no warnings. The test needs -fwrapv: the bug is that a
fold ignores it. -fno-strict-aliasing does not change the output.
Possible fix: One possible fix is to not allow negating B in A / B in
negate_expr_p and fold_negate_expr_1 for a signed type with
TYPE_OVERFLOW_WRAPS, unless A is known not to be the minimum value or B is
known not to be 1, which is the case the comment already describes.
gcc version 17.0.0 20261114 (experimental), r17-6275-gfceddda853f,
x86_64-pc-linux-gnu
Configured with: --enable-languages=c,c++ --disable-multilib
--disable-bootstrap --enable-checking=release