Addresses of referenced objects in clang 3.5

Hi,

since clang 3.5 code as below is optimized away with -O1, assuming that the address of the object
can never be NULL:

class A { };

int func(A& a)
{
    if (&a)
    {
        return 1;
    }
    return 0;
}

int main()
{
    A &a = *reinterpret_cast<A *>(0);
    return func(a);
}

clang++ -Wall -O1 ptrnull.cpp -o ptrnull

ptrnull.cpp:5:10: warning: reference cannot be bound to dereferenced null pointer
in well-defined C++ code; pointer may be assumed to always convert to true [-Wundefined-bool-conversion]
    if (&a)
    ~~ ^
1 warning generated.

./ptrnull
Return code: 1

This is as described in the release notes.

When changing func() as follows the warning is not shown, but clang still performs
the same optimization. Shouldn't the warning be shown here aswell?

int func(A& a)
{
    A *aptr = &a;
    if (aptr)
    {
        return 1;
    }
    return 0;
}

Is it possible to disable this optimization specifically (without resorting to -O0)
to gradually fix codebases that rely on such checks? I saw that I can use
-fsanitize=null, which helps, but disabling the optimization would still
be the best temporary workaround.

Thanks and Best regards,
Martin

(+Nick who had a hand in implementing this optimization)

I don’t think there’s a flag to control this, no.

Seems like there ought to be some kind of “unreachable” warning on the “return 0;” statement?

–paulr

Seems like there ought to be some kind of "unreachable" warning on the
"return 0;" statement?

Possible - though it's nice not to diagnose something twice in different
ways (to reduce noise, etc). But, yeah - it looks like Clang's CFG analysis
infrastructure hasn't been taught that these idioms are constant
conditions, thus making unreachable code. (also our -Wunreachable-code
warning is still off by default, despite several improvements to the
warning to make it a bit less bad - I haven't re-evaluated it in a while to
see whether it has any major holes left)

- David