Replacing ptrtoint+inttoptr with addrspacecast

Given a ptrtoint followed by inttoptr:

%tmp = ptrtoint i16 addrspace(4)* %a to i32

%b = inttoptr i32 %tmp to i8*

InstCombine will normally collapse them to a bitcast (or no-op, if the src and dst pointer types are the same). But if the pointers are in different address spaces, as shown above, it won’t, due to the following code in Instructions.cpp:

// Cannot simplify if address spaces are different!

if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())

return 0;

Is this correct? Given that the instructions above are effectively casting the pointer between two address spaces, can/should InstCombine replace the code above with an addrspacecast? Is there something in the LLVM language spec that makes it illegal or undesirable?



This would be illegal. This is something resembling a no-op addrspacecast, and would only be valid if the target defined representations of both address spaces is known identical. Addrspacecast can change the representation of the pointer in complex ways which would not happen with the ptrtoint/inttoptr pair.


People have argued that eliminating a ptr -> int -> ptr cast sequence is wrong even if all pointers are in the same address space. Therefore the optimization currently performed by the optimizer is unsafe. See

Additionally there might be additional reasons why replacing ptr -> int -> ptr cast sequence with addrspacecast is wrong. It depends on what the exact semantics of the addrspacecast is.