all OS functions should be "nothrow @trusted @nogc"

Jacob Carlborg via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 26 23:48:20 PDT 2017


On 2017-07-27 03:14, Steven Schveighoffer wrote:

> I can't see how compilers can take advantage of this one. However, we 
> can take advantage that this UB is almost universally implemented as a 
> hardware segfault that ends the process.

Unfortunately it's not that easy with optimizing compilers for C and C++:

void contains_null_check(int* p)
{
     int dead = *p;

     if (p == 0)
         return;

     *p = 4;
}

If the compiler runs the "Dead Code Elimination" optimization before 
"Redundant Null Check Elimination" then the above code will turn into:


void contains_null_check(int* p)
{
     if (p == 0) // Null check not redundant, and is kept.
         return;

     *p = 4;
}

But if the compiler runs the optimizations in the opposite order we end 
up with this code:


void contains_null_check(int* p)
{
     int dead = *p;

     if (false) // "p" was dereferenced by this point, so it can't be null
         return;

     *p = 4;
}

And then the compiler runs the "Dead Code Elimination" pass and we're 
left with:

void contains_null_check(int* p)
{
     *p = 4;
}

This can change between releases of compilers and between different 
vendors. Introducing an inlining pass will make this even more 
complicated, because the above example might be spread a cross multiple 
functions that have now been inlined.

For reference: 
http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list