techcomp
techcomp

Reputation: 400

Inserting GetElementpointer Instruction in LLVM IR

I am wondering how to insert a GetElementPointer instruction in LLVM IR through LLVM Pass, say suppose I have an array

%arr4 = alloca [100000 x i32], align 4

and Want to insert a gep like

 %arrayidx = getelementptr inbounds [100000 x i32]* %arr, i32 0, i32 %some value

the what will be the sequence of instructions to write as in IRBuilder Class there are so many instructions to create getelementpointer. Which One to use and what will be its parameters. can anyone explain it with example Any help would be appreciated.

Upvotes: 6

Views: 6241

Answers (1)

Brian
Brian

Reputation: 2813

Let's start with the documentation for GetElementPtrInst, since the IRBuilder is providing a wrapper to its constructors. If we want to add this instruction, I usually go direct and call create.

GetElementPtrInst::Create(ptr, IdxList, name, insertpoint)
  • Ptr: This is a Value* that is initial ptr value passed to GetElementPtr (GEP). In your case, %arr.
  • IdxList: This is a list of values that are the sequence of offsets passed to GEP. Your example has 0 and %some value.
  • Name: This is the name in the IR. If you want "%arrayidx", you would provide "arrayidx".
  • insertpoint: Without the IRBuilder, you must specify where to insert the instruction (either before another instruction or at the end of a basic block).

Putting these pieces together, we have the following code sequence:

Value* arr = ...; // This is the instruction producing %arr
Value* someValue = ...; // This is the instruction producing %some value

// We need an array of index values
//   Note - we need a type for constants, so use someValue's type
Value* indexList[2] = {ConstantInt::get(someValue->getType(), 0), someValue};
GetElementPtrInst* gepInst = GetElementPtrInst::Create(arr, ArrayRef<Value*>(indexList, 2), "arrayIdx", <some location to insert>);

Now, you asked about using IRBuilder, which has a very similar function:

IRBuilder::CreateGEP(ptr, idxList, name)

If you want to use the IRBuilder, then you can replace the last line of the code snippet with the similar IRBuilder's call.

Upvotes: 10

Related Questions