Compilers are allowed to make several assumptions that would lead to undefined behaviour (such as assuming addition doesn’t overflow). May they make such an assumption with regards to floating point NaN?
For example:
double a = some_calc();
double b = a;
if( a == b )
do_something();
Can the optimizer remove the conditional statement and assume that it is always true? Or is it bound to the platform floating point rules (IEEE) and forced to do the check in case the value is NaN?
That is, can the compiler optimize based on the assumption that a double does not contain NaN? As the C++ standard doesn’t say a lot about how floating point actually works on the platform, I’m not clear if this is actually fully specified.
Not necessarily, if the implementation uses IEEE 754 floating point numbers,
std::numeric_limits<double>::is_iec559is set to true.If the implementation does use IEEE 754, the result of arithmetic operations must match IEEE floating point rules, but as far as comparison goes, it can be optimised. If the body of
some_calcis available for the analysis by the compiler in the same translation unit (or during link-time code generation) and it can conclude that it never returns NaN (i.e. returns a constant), it can be optimised, as the semantics of the code don’t change.