3 ms·
No, optimizations are allowed to change the ordering or exact implementations, but they cannot change observable behavior unless the behavior depends on undefin
by olliej 8y ago
No, optimizations are allowed to change the ordering or exact implementations, but they cannot change observable behavior unless the behavior depends on undefined (e.g the compiler is the adversary) or unspecified (in which the compiler is required to be self-consistent, e.g parameter evaluation order is (was?) unspecified so a compiler could choose left to right or right to left evaluation, but it must pick one and use that everywhere).
The C abstract machine defines the behavior, and optimization passes aren't allowed to change the behavior.
-ffast-math is the option that allows incorrect semantics (e.g commutative floating point addition), but compilers have a desire to do incorrect things for "performance".
I would hope it is obvious that changing behavior for performance isn't ok, but lets say it was. A compiler could change
y=1.0/fsqrt(x)
from (v. approximate, untested, and written in a text box :D)
movsd xmm0, $(wherever x is)
sqrtsd xmm0
movsd xmm1, $(location of 1.0 constant)
divsd xmm1, xmm0
movsd $(addr of y), xmm1
to something like
movsd xmm0, $(wherever x is)
rsqrtsd xmm0
movsd $(addr of y), xmm0
This would be much much faster, and vastly incorrect (IIRC rsqrt is only 12bits of precision)
Or even more dumb, remove calls to printf, because printf is slow.
A compiler does not have absolute leeway in all things, it is still restricted to ensuring that observable results of the C abstract machine are correct.