[LLVMdev] replacing instructions

John Criswell criswell at cs.uiuc.edu
Thu Jan 22 07:25:56 PST 2009


Ralf Karrenberg wrote:
> Hello everyone,
>
> is there any way to replace an instruction inside LLVM that is more
> elegant than creating a new one, replacing uses and deleting the old one
> if I only want to modify the type? It is generally not a big deal, but
> the issue gets really messy if I am in the middle of iterating over uses
> and start deleting some of them...
>   
Yes, the Instruction class has a method for doing this (the method is
technically inherited from the Value class).

Calling the replaceAllUsesWith() method on an Instruction will replace
every use of the old instruction with the new instruction.  As long as
the type generated by the old and new instructions is identical (or
maybe even similar), you shouldn't have any problems.  For example,
replacing an add instruction that adds two i32's with a call instruction
that returns an i32 should be as simple as:

Instruction * OldInst = ... ;
Instruction * NewInst = CallInst::Create (...);
OldInst->replaceAllUsesWith (NewInst);

This sort of code may not work if OldInst and NewInst are not SSA
virtual registers of the same type (for example, if OldInst is a pointer
to an array of i32 and NewInst is a pointer to a structure).  In that
case, not only must the defining instruction be changed, but the
instructions using it must be changed as well.  In that case, you will
need to iterate over the uses of the old instruction and create a new
instruction for each use, making whatever changes to each use are
necessary for your transform to work.

See http://llvm.org/doxygen/classllvm_1_1Value.html for more information
on replaceAllUsesWith().

-- John T.

> I hope I could describe my problem well enough ;)
>
> Regards,
> Ralf
> _______________________________________________
> LLVM Developers mailing list
> LLVMdev at cs.uiuc.edu         http://llvm.cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev
>   




More information about the llvm-dev mailing list