Instruction insertion By Module Pass

Hi,

I need to insert new instruction into every basic block like x=1

or while loop

I tried this code, but it doesn’t work

Type * Int32Type = IntegerType::getInt32Ty(getGlobalContext());
AllocaInst* newInst = new AllocaInst(Int32Type,“flag”, Bb);
Bb->getInstList().push_back(newInst);

the error:
void llvm::SymbolTableListTraits<llvm::Instruction, llvm::BasicBlock>::addNodeToList(ValueSubClass *) [ValueSubClass = llvm::Instruction, ItemParentClass = llvm::BasicBlock]: Assertion `V->getParent() == 0 && “Value already in a container!!”’ failed.

Is there a class I could use to insert while loop in Module Pass?

Thank you in advance

The problem is that you’ve inserted the AllocaInst into the basic block via the AllocaInst constructor (note the Bb at the end of the line with new AllocaInst). You then attempt to insert the AllocaInst into the BasicBlock Bb a second time with the last line. Note that the assertion is telling you that you’re inserting the alloca instruction twice. Remove the last line, and it should fix your problem. – John T.

Thank you for your help

I tried
Instruction* p=&( Bb->front());
Type * Int32Type = IntegerType::getInt32Ty(getGlobalContext());
AllocaInst* newInst = new AllocaInst(Int32Type,“flag”, p);

that works well

but I need to store the value of the variable too.

What’s the method that could be used to store specific value??

Create a store instruction (StoreInst) that stores the desired value into the memory created by the alloca instruction. – John T.