Bug 34454 - [4.3 regression] Overflow check is optimized away when -O2 is enabled
Bug#: 34454 Product:  gcc Version: 4.3.0
Host:  Target:  Build: 
Status: RESOLVED Severity: normal Priority: P3
Resolution: INVALID Assigned To: unassigned@gcc.gnu.org Reported By: ismail@namtrac.org
Component: middle-end Target Milestone: ---
Summary: [4.3 regression] Overflow check is optimized away when -O2 is enabled
Keywords:  
Opened: 2007-12-13 19:32
Description:   Last confirmed: Opened: 2007-12-13 19:32
Testcase :

#include <sys/types.h>
#include <stdio.h>

void foo(ssize_t x)
{
 if (x >= 0) {
   if (x+x < 0) printf("Overflow\n");
}
}

main()
{
  volatile ssize_t x =2147483647;
  foo(x);
}

When compiled with -O2 it doesn't print Overflow, if you omit -O2 it prints
overflow.
gcc 3.4.6 works fine so this is a regression.

------- Comment #1 From Andrew Pinski 2007-12-13 19:36 -------
This is not a bug, signed overflow is undefined so optimizing away this case is
correct as a positive + positive is always positive.

Use -fwarpv or what ever the strict overflow option is.

------- Comment #2 From Andrew Pinski 2007-12-13 19:37 -------
Or use unsigned types to do the addition.

------- Comment #3 From Ismail "cartman" Donmez 2007-12-13 19:37 -------
FWIW this triggers a crash in Python 2.5, see http://bugs.python.org/issue1608

------- Comment #4 From Ian Lance Taylor 2007-12-13 20:37 -------
Note that this gives a warning with -Wstrict-overflow.

And note that you get the desired behaviour if you compile with
-fno-strict-overflow.

As Pinski says, the code is simply incorrect according to standard C, but you
can use the -Wstrict-overflow and -fno-strict-overflow options to help fix
existing code bases.

------- Comment #5 From Ismail "cartman" Donmez 2007-12-13 20:48 -------
Guido agreed on using -fwrapv hence a patch submitted, thanks for the
diagnosis.