D defined behavior

Johan j at j.nl
Mon Apr 27 14:57:09 UTC 2020


On Monday, 27 April 2020 at 14:07:49 UTC, Luís Marques wrote:
> I've lost track. Does D have undefined behavior at all? (e.g. 
> outside @safe code).

Yes, D has UB.

> In any case, I imagine that the D spec (ha!) would dictate that 
> the following code should print 0x10001, although that's not 
> quite clear.
>
> GDC (optimized) prints 0x1.
> LDC2 prints 0x10001, but I suspect only because LLVM doesn't 
> happen to do the same optimization, not because this is handled 
> properly.

I think you mean to ask whether D defines writing to partially 
overlapping objects. Or if it is defined to write a type `int` to 
memory locations that were typed as `char`.

LDC assumes `a` and `b` may alias partially, and therefore `a` 
must be reloaded in the return statement. LDC does not pass 
type-based alias information to the optimizer (TBAA if you are 
interested), which Clang _would_ do; it be nice if someone could 
check me on this: 
https://llvm.org/docs/LangRef.html#pointer-aliasing-rules
Still, Clang does not optimize the code as it probably could, 
same as GCC does. My guess is that GDC inherits the C or C++ 
type-based aliasing rules here.

-Johan



More information about the Digitalmars-d mailing list