0
votes

For example, if I have the following struct

%struct.foo_struct = type { [3 x i32], i16*, i32}

Let's say we have a pointer %struct.foo_struct* %P.

I know I can do %tmp0 = getelementptr inbounds %struct.foo_struct, %struct.foo_struct* %P, i64 0, i32 0, i64 2 to get the third element in the i32 array of the struct (the first element in the struct), but can I do %tmp1 = getelementptr inbounds %struct.foo_struct, %struct.foo_struct* %P, i64 0, i32 1, i64 2 to get the third element in the i16 array of the struct (the second element in the struct), assuming that the i16 array has at least third elements?

I did not find any posts online discussing the difference between these two types, so can I assume they are the same?

2

2 Answers

2
votes

No you cannot, because the second element of the array doesn't have three entries. It has precisely one.

A pointer type is a pointer to something; an instance of it occupies as much memory as a pointer does. An array is n somethings; an instance occupies n times as much memory as that something.

Assuming a 32-bit platform with zero padding:

If you were to bitcast so as to treat that i16* as an array and write to the third or fourth entry, you would overwrite the i32, because the i16* occupies as much memory as a pointer. On a 32-bit platforms a two-entry i16 array is as big as a pointer so the third and fourth entry would overlap the i32, and writing to the fifth entry or later writes beyond the struct's end.

1
votes

You can't. Simple reason being that the GEP instruction never dereferences pointers.

In

%tmp1 = getelementptr inbounds %struct.foo_struct, %struct.foo_struct* %P, i64 0, i32 1, i64 2

i32 1 refers to the i16* pointer, which we can call ptr. Now i64 2 would refer to *(ptr + 2) which is illegal as it effectively tries to dereference ptr, which GEP isn't fond of doing.

If the first element of the struct was of type [3 x i32]*, you'd have the same trouble. See https://godbolt.org/z/ch9hGs and notice how a load instruction is always needed for struct members that are pointers.

Also if you had an i32* pointer and a [n x i32] array, the only real difference is you can always tell the size of the latter, but not the former.