c++/6914: Wrong outcome of 'double' calculations with -O2
veksler@il.ibm.com
veksler@il.ibm.com
Mon Jun 3 03:26:00 GMT 2002
>Number: 6914
>Category: c++
>Synopsis: -O2 and -O give different results for the same valid FP code
>Confidential: no
>Severity: serious
>Priority: medium
>Responsible: unassigned
>State: open
>Class: wrong-code
>Submitter-Id: net
>Arrival-Date: Mon Jun 03 03:26:00 PDT 2002
>Closed-Date:
>Last-Modified:
>Originator: veksler
>Release: 3.2 20020601 (experimental)
>Organization:
>Environment:
System: Linux lnx12.haifa.ibm.com 2.2.16-22.c4eb #1 SMP Tue Apr 3 09:32:12 IST 2001 i686 unknown
Architecture: i686
host: i686-pc-linux-gnu
build: i686-pc-linux-gnu
target: i686-pc-linux-gnu
configured with: ../gcc/configure --prefix /home2/veksler/gnu2 --enable-languages=c++
>Description:
The following code gives different results with -O2 and -O0.
Now matter how you look at it, the code for -O2 does the wrong thing.
1. It should give the same result as -O0.
2. When two "double" variables "a", "b" get their values from the same
sequence of operations, using the same constants, then even
for double we must get "a == b" ( !(a<b) ).
This is a very old bug. I tested it on RedHat's gcc2.96 (RH7.1),
and on current gcc.
Here is the code:
#include <iostream>
class A
{
public:
virtual double Cost() const { return 3; }
};
int main()
{
int bestPos=-1;
double bestRatio = 0.0;
A* p= new A;
for(int i=0; i!=1000*1000; ++i){
double ratio = 1.0 / p->Cost();
if(ratio > bestRatio){
bestRatio = ratio;
bestPos = i;
}
}
std::cout << "best pos= " << bestPos
<< ", best ratio=" << bestRatio
<< std::endl;
return 0;
}
>How-To-Repeat:
On Linux x86 (Tested on Pentium II and Pentium III):
Simply compile with 'g++ -O2 test.cpp', and run.
In theory it should print "best pos= 0 .....", but
in practice it prints the maximal value of 'i' (minus 1).
I don't supply preprocessor output, because the bug does not
involve the preprocessor, and can be reproduced with no #include
statements.
>Fix:
>Release-Note:
>Audit-Trail:
>Unformatted:
More information about the Gcc-bugs
mailing list