1

I am working with LLVM IR code. I want to create a new store instruction ( Eg: store i32 %add, i32* %temp1, align 4) and I need to insert it after a particular instruction, say after an add instruction. My intention is, the result of an addition operation (some pointer) is stored in %add, I need to keep a copy of the same in a temperory variable say %temp1.

For that, I created a variable named temp1 first (%temp1 = alloca i32, align 4). Now I want to store the result of addition instruction (%add = add nsw i32 %0, %1) i.e., %add to temp1. Then the final store instruction will be something like this: store i32 %add, i32* %temp1, align 4. How to do this?

Any help with some examples?

2 Answers 2

4

For creating %temp1 = alloca i32, align 4 instruction, I used the following statement:

AllocaInst* pa = new AllocaInst(llvm::Type::getInt32Ty(getGlobalContext()), 0, 4,"temp1");

For creating and inserting a new store instruction:

StoreInst *str = new StoreInst(i, pa); // i -> current instruction pointer which represents %add ( source of store instruction ), pa -> destination. i.e., temp1
BB->getInstList().insert(ib, str); // ib -> instruction address before which you want to insert this store instruction
1
  • You can just pass ib to the StorInst constructor as third parameter. All instruction constructors take the insertion point as last parameter: e.g. StoreInst (Value *Val, Value *Ptr, Instruction *InsertBefore) and StoreInst (Value *Val, Value *Ptr, BasicBlock *InsertAtEnd) Jan 14, 2016 at 6:08
1

A couple of notes:

  1. You should be using IRBuilder for creating IR. It's much easier and there are tons of examples to work off of in both the Kaleidoscope tutorial and clang itself.
  2. I'm not sure why you're creating an extra allocation. In general, unless you have an actual local variable to store to a Value is sufficient to hold the result. What are you storing to and why?
  3. If you do need an extra alloca for a local variable then you should create it in the entry block of the function, otherwise you'll be creating a dynamic allocation in the middle of your function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.