[LLVMdev] Pointer sizes, GetElementPtr, and offset sizes

Andrew Lenharth andrewl at lenharth.org
Fri May 2 13:40:51 PDT 2008


I should say what would be a nice instruction for type safety would be
%type x = getcontainerptr %pointer, %type, gep indexes
where %x is the beginning of the structure/array of which %pointer is
the member at the offset that would be calculated by a gep.

%x = alloca [2 x i32*]
%tmp1 = getelementptr [2 x i32*]* %x, i32 0, i32 1
%tmp2 = getcontainerptr i32**  %tmp1, [2 x i32*]*, i32 0, i32 1

then %x == %tmp2

such an instruction would let you backtrack in a structure without
casts and pointer arithmetic.

Andrew

On Fri, May 2, 2008 at 3:29 PM, Andrew Lenharth <andrewl at lenharth.org> wrote:
> On Fri, May 2, 2008 at 1:22 PM, Marc de Kruijf <dekruijf at cs.wisc.edu> wrote:
>
> > The LLVA and LLVM papers motivate the GetElementPtr instruction by arguing
>  > that it abstracts implementation details, in particular pointer size, from
>  > the compiler.  While it does this fine for pointer addresses, it does not
>  > manage it for address offsets.  Consider the following code:
>  >
>  > $ cat test.c
>  > int main() {
>  >     int *x[2];
>  >     int **y = &x[1];
>  >     return (y - x);
>  > }
>
>  Idefine i32 @main() nounwind  {
>
> entry:
>         %x = alloca [2 x i32*]          ; <[2 x i32*]*> [#uses=2]
>         %tmp1 = getelementptr [2 x i32*]* %x, i32 0, i32 1
>   ; <i32**> [#uses=1]
>         %tmp23 = ptrtoint i32** %tmp1 to i32            ; <i32> [#uses=1]
>         %x45 = ptrtoint [2 x i32*]* %x to i32           ; <i32> [#uses=1]
>         %tmp6 = sub i32 %tmp23, %x45            ; <i32> [#uses=1]
>         %size = getelementptr i32** null, i32 1         ; <i32**> [#uses=1]
>         %sizeI = ptrtoint i32** %size to i32            ; <i32> [#uses=1]
>         %tmp7 = ashr i32 %tmp6, %sizeI          ; <i32> [#uses=1]
>         ret i32 %tmp7
>  }
>
>  There, pointer size independent.  The problem you see is you are using
>  a frontend targeting a specific platform, so pointersize is known (see
>  the target datalayout line).
>
>  Andrew
>



More information about the llvm-dev mailing list