Integer semantic in D, what are the tradeoff ? Do we have numbers ?

Timon Gehr timon.gehr at gmx.ch
Sun Dec 16 16:47:25 PST 2012


On 12/17/2012 01:39 AM, deadalnix wrote:
> On Monday, 17 December 2012 at 00:27:42 UTC, Timon Gehr wrote:
>> On 12/16/2012 11:52 PM, deadalnix wrote:
>>> Following the thread on integer semantic, i wanted to know if some data
>>> are available on the tradeoff we are doing. Let me first explain what
>>> they are.
>>>
>>> In D, integer are guaranteed to loop, ie uint.max + 1 == 0 . In C, the
>>> compiler is allowed to consider that operation do not overflow, which
>>> allow some optimization. See 2 examples bellow :
>>>
>>> if(a < a + 1) { ... }
>>>
>>> On that case, a compiler can decide that the condition is alway true in
>>> C. This may seems like a stupid piece of code, but in fact this is
>>> something that the compiler can do on a regular basis. You have to keep
>>> in mind that the example usually not appears in a way that is as obvious
>>> as this, but after several code transformation (function inlining,
>>> constant propagation, etc . . .).
>>>
>>> Another example is (x + 1) * 2; The compiler may decide to rewrite it as
>>> 2 * x + 2 as this is done in one operation on many CPU, when (x + 1) * 2
>>> is not always possible. Both are equivalent, expect if the integer
>>> overflow.
>>>
>>
>> Even if they do. I claim that 2 * x + 2 = (x + 1) * 2 holds for every
>> int x. The only difference is that one of the two might set the CPU
>> flags whereas the other wont. But flags are not exposed to D code anyway.
>>
>
> Use x * 4 / 2 => x * 2
>

Yup, that works.

>> It is not a very strong case, but the code may accidentally still
>> work. Also, it is much easier to hunt down a bug when it does not
>> disappear when unrelated code changes and is not dependent on
>> optimization or debug flags.
>>
>
> Maybe the compiler should generate a trap in debug mode and go full
> speed in release mode ? Code that accidentally work is not really a
> desirable result (even if i understand that this is arguably better).

If overflow semantics are changed to C's, then checking int overflow 
should be in a separate flag from release.


More information about the Digitalmars-d mailing list