[LLVMdev] Constant folding inttoptr i32 0 to null pointer?

Daniel Berlin dberlin at dberlin.org
Tue Jun 9 13:21:54 PDT 2015


On Tue, Jun 9, 2015 at 11:34 AM, Benyei, Guy <guy.benyei at intel.com> wrote:
> Thanks David,
>
> It turns out, that the address space I was using was not 0, and yet the
> pointer was constant folded to null.
>

The lang ref is not entirely clear on whether 0 is always equal to the
null pointer. It (at least to me) implies it is:
"
Any memory access must be done through a pointer value associated with
an address range of the memory access, otherwise the behavior is
undefined. Pointer values are associated with address ranges according
to the following rules:
...

A pointer value is associated with the addresses associated with any
value it is based on.
A null pointer in the default address-space is associated with no address.
An integer constant other than zero or a pointer value returned from a
function not defined within LLVM may be associated with address ranges
allocated through mechanisms other than those provided by LLVM. Such
ranges shall not overlap with any ranges of addresses allocated by
mechanisms provided by LLVM.
....

A pointer value formed by an inttoptr is based on all pointer values
that contribute (directly or indirectly) to the computation of the
pointer’s value.

"
(Fun lawyering: This, and the remaining clauses, do not ever define
the behavior of a null pointer constant in the non-default address
space, which means it's behavior is undefined by the first sentence. I
know this is not what is intended, so this should probably be cleaned
up)

Anyway, the above to me implies the inttoptr of the integer constant
zero is the null pointer, because if it isn't, it's a pretty striking
omission to cover everything *but* the integer constant zero ;).

As such, folding it to null should be correct, and not cause wrong
behavior for your program.

As David says, the question of whether it can be dereferenced or not
is separate, specifically to allow the null pointer in non-default
address spaces to do different things.

Do you have a case where it does something wrong?

>
> The contant folder doesn’t seem to check for address space, it simply checks
> if the integer in question is zero, and folds the inttoptr to null:
>
>

I believe this is correct by the above.




More information about the llvm-dev mailing list