From 80a4d05a20dbcf69396ae93b9c996e9a2148f9df Mon Sep 17 00:00:00 2001 From: Reid Spencer Date: Tue, 15 Aug 2006 03:43:31 +0000 Subject: [PATCH] Clarify the first question. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@29692 91177308-0d34-0410-b5e6-96231b3b80d8 --- docs/GetElementPtr.html | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/docs/GetElementPtr.html b/docs/GetElementPtr.html index 99319a49924..98c77af5645 100644 --- a/docs/GetElementPtr.html +++ b/docs/GetElementPtr.html @@ -70,9 +70,21 @@ What is the first index of the GEP instruction?
-

Quick answer: Because its already present.

-

Having understood the previous question, a new - question then arises:

+

Quick answer: The index stepping through the first operand.

+

The confusion with the first index usually arises from thinking about + the GetElementPtr instruction as if it was a C index operator. They aren't the + same. For example, when we write, in "C":

+
+  AType* Foo;
+  ...
+  X = Foo[1];
+

it is natural to think that there is only one index, the constant value + 1. This results from C allowing you to treat pointers and arrays as + equivalent. LLVM doesn't. In this example, Foo is a pointer. That pointer must + be indexed. To arrive at the same address location as the C code, you would + provide the GEP instruction with two indices. The first indexes through the + pointer, the second index the second element of the array.

+

Sometimes this question gets rephrased as:

Why is it okay to index through the first pointer, but subsequent pointers won't be dereferenced?

The answer is simply because memory does not have to be accessed to @@ -194,7 +206,7 @@ %idx = getelementptr { [40 x int]* }* %MyVar, long 0, ubyte 0, long 0, long 17

In this example, we have a global variable, %MyVar that is a pointer to a structure containing a pointer to an array of 40 ints. The - GEP instruction seems to be accessing the 18th integer of of the structure's + GEP instruction seems to be accessing the 18th integer of the structure's array of ints. However, this is actually an illegal GEP instruction. It won't compile. The reason is that the pointer in the structure must be dereferenced in order to index into the array of 40 ints. Since the @@ -213,7 +225,7 @@ ... %idx = getelementptr { [40 x int] }*, long 0, ubyte 0, long 17

then everything works fine. In this case, the structure does not contain a - pointer and the GEP instruction can index through the global variable pointer, + pointer and the GEP instruction can index through the global variable, into the first field of the structure and access the 18th int in the array there.