Undefined behaviors & Clang 3.3

Artur Skawina art.08.09 at gmail.com
Fri Jun 21 05:51:02 PDT 2013


On 06/21/13 10:20, qznc wrote:
> In D an integer overflow is defined, so there is no need to detect anything about it. See Spec:
> 
> "If both operands are of integral types and an overflow or underflow occurs in the computation, wrapping will happen. That is, uint.max + 1 == uint.min and uint.min - 1 == uint.max."
> http://dlang.org/expression.html

Keep in mind that this is not necessarily how real compilers treat it:

   void main() {
     auto a = int.max;
     if (a+1<a.max)
        assert(0);
   }

will not assert when compiled with gdc; you'd have to explicitly disable
that optimization. GCC statically evaluates this kind of checks, by
assuming that signed overflow can't happen - because it's undefined.
But that's not true for D, so, until the compiler is fixed, the
'-fno-strict-overflow' compiler flag has to be used if "spec"-like
behaviour is desired.

Requiring wrapping arithmetic removes some opportunities for optimization,
hence should, ideally, be complemented by more value range awareness in the
language. D doesn't really have the latter, so right now, avoiding the UB
in these cases has a cost. Still, GDC should just be fixed, as having a
subtly different dialect is worse. Right now, incorrect (according to the
"spec") code is silently generated, causing data corruption.

artur


More information about the Digitalmars-d mailing list