Instruciton replacement

llvm is giving me some assertion errors when trying to replace an
instruction, and I'm not quite sure of what to do. I have the
following snippet of code:

switch((*I)->getOpcode()) {
case Instruction::Malloc:
  {
    AllocaInst *AI;
    AI = new AllocaInst(cast<AllocationInst>(*I)->getAllocatedType(),
      cast<AllocationInst>(*I)->getArraySize());
    (*I)->replaceAllUsesWith(AI);
// (*I)->dropAllReferences();
// (*I)->getParent()->getInstList().erase(*I);
// delete (*I);
// delete(AI);
  }
  break;

running the code will report:

Leaked objects found: after running pass 'move memory objects from the
heap to the stack'
  LLVM Value subclasses leaked: alloca uint ; <uint*>:<badref> [#uses=2]

This is probably because you removed an LLVM value (Instruction,
BasicBlock, etc), but didn't delete it. Please check your code for
memory leaks. Assertion failed: slot != -1 && "Broken bytecode!", file
WriteInst.cpp, line 191
Abort

If I uncomment the (delete(AI)) will report:

While deleting: uint *%
Use still stuck around after Def is destroyed: %reg112 = load uint*
<badref> ; <uint> [#uses=1]
Use still stuck around after Def is destroyed: store uint 37337,
uint* <badref>
Assertion failed: Uses.begin() == Uses.end(), file Value.cpp, line 43
Abort

uncommenting the "dropAllReferences() && delete(*I)" reports:

Assertion failed: Parent == 0 && "Instruction still embedded in basic
block!", file ../../../include/llvm/Instruction.h, line 33
Abort

how can I replace the (*I) instruction with a new AI?

thanks.
nicolas

llvm is giving me some assertion errors when trying to replace an
instruction, and I'm not quite sure of what to do. I have the
following snippet of code:

    AI = new AllocaInst(cast<AllocationInst>(*I)->getAllocatedType(),
      cast<AllocationInst>(*I)->getArraySize());
    (*I)->replaceAllUsesWith(AI);

This is probably because you removed an LLVM value (Instruction,
BasicBlock, etc), but didn't delete it. Please check your code for
memory leaks. Assertion failed: slot != -1 && "Broken bytecode!", file
WriteInst.cpp, line 191 If I uncomment the (delete(AI)) will report:

While deleting: uint *% Use still stuck around after Def is destroyed:
%reg112 = load uint* <badref> ; <uint> [#uses=1] Use still stuck around
after Def is destroyed: store uint 37337, uint* <badref> Assertion
failed: Uses.begin() == Uses.end(), file Value.cpp, line 43 Abort

Actually, the problem is that you are making things point to the new
alloca instruction you created, but you are not inserting the alloca
instruction into the program anywhere. To do this, you can use the extra
argument to the AllocaInst ctor, specifying the instruction that the
alloca should be inserted before.

-Chris