[LLVMdev] Indexing backwards through a structure

Jay Foad jay.foad at gmail.com
Tue Aug 24 04:35:00 PDT 2010

Hi David,

On 23 August 2010 15:02, David Given <dg at cowlark.com> wrote:
> Given a structure like this (using C syntax rather than LLVM because I'm
> still not fluent with LLVM assembly):
> struct Object
> {
>  int i1;
>  int i2;
>  int i3;
> };
> Then, if I have an int* pointer which I know is pointing to the i3
> element, what's the best way of recovering a pointer to the structure as
> a whole?
> My fallback option is to cast the pointer to an int64, use getelementptr
> to determine the offset of the i3 element, subtract, cast back to a
> pointer, etc. However this feels very clunky to me and I'd like a
> cleaner way of doing it.

Casting the pointer to "i8 *" and then using getelementptr with a
single index, to add a (negative) number of bytes to the pointer, is
probably a bit cleaner.

As for how you calculate the number to subtract, you can either try to
implement offsetof() as a complicated ConstantExpr using
getelementptr, or you can just know that the value is 8. Most front
ends know what the target data layout is, so they can just use a

As a general suggestion, try writing the code in C and seeing what
llvm-gcc or clang turns it into.

> life←{ ↑1 ⍵∨.^3 4=+/,¯1 0 1∘.⊖¯1 0 1∘.⌽⊂⍵ }



More information about the llvm-dev mailing list