[LLVMdev] Problems with getelementptr

Chris Lattner sabre at nondot.org
Mon May 3 12:09:02 PDT 2004


On Mon, 3 May 2004, Anders Alexandersson wrote:

> Hello!
>
> I'm having trouble with pointer traversing. I have a design as follows:
> class -> map -> classFunctions
>
> Starting with a pointer to the class, I want to get a pointer to a
> classFunction via a pointer to the map.

Okay...

> I can't get that function pointer!
>
> How shall I think to get the traversing right (see code below)? Is it
> something with the fact that I am using only pointers in my structs?
>
> Best regards
> Anders
>
> ; My user defined function
> declare int %puts_kernel(sbyte* %string)
>
> ;the map and the class. The class is called "Kernel".
> "myKernelMap" = type {int (sbyte*)*}

Okay, this declares a structure that has a single pointer-to-function
element in it.

> "Kernel" = type {"myKernelMap"*}

This is a single element structure with a pointer to the map.

> ;Allocating...OK
> "myKernelMapInstance" = malloc "myKernelMap"
> %myKernel = malloc "Kernel"

Okay, these are of type %myKernelMap and %Kernel, respectively.

> ;Assigning the map to the class...OK
> "myKernelMapPTR" = getelementptr "Kernel"* %myKernel, long 0, ubyte 0

This gives you a pointer to the '%myKernelMap*' in the Kernel type.

> store "myKernelMap"* "myKernelMapInstance", "myKernelMap"** "myKernelMapPTR"

And this stores the pointer as you would expect.

> ; Try to get pointer to the functionPointer in the map, NOT OK! :-(
> %puts_kernelPTR = getelementptr "Kernel"* %myKernel, long 0, ubyte 0, long 0, ubyte 0

Okay, here you're getting into trouble.  myKernel is of type Kernel, which
doesn't contain a pointer to a function.  In your case, you need to
actually emit a load to get to the structure in question, something like
this:

%t1 = getelementptr "Kernel"* %myKernel, long 0, ubyte 0
%t2 = load "myKernelMap"**
%puts_kernelPTR = getelementptr "myKernelMap"*, long 0, ubyte 0

> store int (sbyte*)* %puts_kernel, int (sbyte*)** %puts_kernelPTR

This should now work.

> ;Want to call the function with a string
> %tmp.11 = load int (sbyte*)** %puts_kernelPTR
> %result = call int %tmp.11(sbyte* %string)

This should also work.

-Chris

-- 
http://llvm.cs.uiuc.edu/
http://www.nondot.org/~sabre/Projects/




More information about the llvm-dev mailing list