[LLVMdev] How to delete a instruction?

John Criswell criswell at uiuc.edu
Tue Apr 20 17:22:18 PDT 2010


lucefe wrote:
> I did a simple test just now, but I alse failed.
>  
> I delete several ordered instructions from end to begin,
> but after deleting the first instruction(the last instruction of F), 
> the program crashed.
> My test code is below (F is a function only containing several 
> sequential instructions):
>  
> for (inst_iterator inst == --inst_end(F); inst != inst_begin(F); --inst) {
> Instruction * i =  &*inst;
> i->eraseFromParent();
> }
>  
>  
> Best Regards!

First, you may be invalidating the iterator i by erasing the value 
inside the loop.  In my code, I almost always iterate through the 
instructions once and record them in a std::vector.  I think loop 
through the std::vector, processing the end element and then remove it 
from the std::vector.  It is less efficient but ensures no nasty 
iterator invalidation errors.

Second, this code does not work correctly on loops.  A basic block could 
branch to itself, meaning that a phi node at the beginning of the basic 
block could use a value computed at the end of itself.

You should do the following:

1) For each instruction to delete, replace its use with an Undef value.  
When this is done for all instructions you want to delete, none of them 
will have any uses.  You should be able to delete them then.

I can provide sample code tomorrow that illustrates how to do this (I'm 
busy writing a short paper tonight).  In the meantime, someone may be 
able to show you an even better way.

-- John T.




More information about the llvm-dev mailing list