[LLVMdev] How to delete a instruction?

lucefe noviceup at gmail.com
Tue Apr 20 22:46:56 PDT 2010

John, thank you for your patience and good suggestion.

I put all the instructions I want to delete into a std::vector,and replace
all the use of the instrutions with an undef value, and then delete the

For your suggestion, I successed. Thank you very much!

Best Regards!

2010/4/21 John Criswell <criswell at uiuc.edu>

>  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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20100421/292792bc/attachment.html>

More information about the llvm-dev mailing list