overflow semantics + optimization?

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

overflow semantics + optimization?

Joseph Bebel-2
Hi,

While experimenting with LLVM as a gcc-drop-in I noticed some
interesting behavior related to integer overflow. Consider the
following test program:

#include <iostream>
int main() {
  int x = 0;
  for(int i = 0; i < 123456789; i++) {
    x += i;
  }
  std::cout << x << std::endl;
  return 0;
}

Compiled using the latest llvm-g++ (2.1, mac os x universal tarball)
with no optimization, and under all levels of optimization under Apple
GCC 4.0.1 the program correctly outputs "1206807378"

However, when using llvm-g++ under any level of optimization
(-O1/2/3), it outputs instead "-940676270" (which is the above answer
minus 2^31)

Now, is this is proper behavior, undefined behavior, bug, etc? I can't
quite tell, so perhaps someone can clarify? Thanks :)
_______________________________________________
LLVM Developers mailing list
[hidden email]         http://llvm.cs.uiuc.edu
http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev
Reply | Threaded
Open this post in threaded view
|

Re: overflow semantics + optimization?

Chris Lattner
On Nov 13, 2007, at 7:39 PM, Joseph Bebel wrote:

> While experimenting with LLVM as a gcc-drop-in I noticed some
> interesting behavior related to integer overflow. Consider the
> following test program:
>
> #include <iostream>
> int main() {
>  int x = 0;
>  for(int i = 0; i < 123456789; i++) {
>    x += i;
>  }
>  std::cout << x << std::endl;
>  return 0;
> }
>
> Compiled using the latest llvm-g++ (2.1, mac os x universal tarball)
> with no optimization, and under all levels of optimization under Apple
> GCC 4.0.1 the program correctly outputs "1206807378"
>
> However, when using llvm-g++ under any level of optimization
> (-O1/2/3), it outputs instead "-940676270" (which is the above answer
> minus 2^31)
>
> Now, is this is proper behavior, undefined behavior, bug, etc? I can't
> quite tell, so perhaps someone can clarify? Thanks :)

That is almost certainly a bug in LLVM.  While integer overflow is  
undefined for signed int, I suspect you'll see the same bug with llvm  
if you define x and i as "unsigned int" as well.  Please file a  
bugzilla bug, thanks!

-Chris
_______________________________________________
LLVM Developers mailing list
[hidden email]         http://llvm.cs.uiuc.edu
http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev