[LLVMdev] Writing a pass that modifies the IR

John Criswell criswell at illinois.edu
Mon Aug 2 07:29:17 PDT 2010


Edmund Grimley-Evans wrote:
> Could some kind soul point me at the documentation, or the appropriate header file, or an example of the best way to write a pass that modifies the IR?
>   

A few places to start:

http://llvm.org/docs/ProgrammersManual.html
http://llvm.org/docs/WritingAnLLVMPass.html
http://llvm.org/doxygen/
http://llvm.org/docs/CommandLine.html

> Suppose, for example, that I wanted to replace every call to the intrinsic i1 with a call to i2 followed by a call to i3: i1(X) -> i3(i2(X))
>
> I'm currently playing around with a class that inherits from FunctionPass and InstVisitor and I can add instructions but I'm not yet able to use the output from the new instruction. I suspect there's a much easier way of doing what I want to do.
>   

First, you should understand what an LLVM Pass is.  I think you more or 
less understand this.

Second, you need to understand the C++ classes that represent and 
manipulate the LLVM IR.  Some of this is documented near the end of the 
Programmer's Manual (the URL for which is given above).  The doxygen 
documentation is invaluable for learning the nuts and bolts of the API; 
there is essentially one class for each kind of object in the LLVM IR, 
and the doxygen documentation provides information on the methods one 
can use on those classes to do what you want.

Now, to answer your specific questions:

1) How do I use the result of an Instruction?

In LLVM IR, an instruction and its result are one and the same.  To use 
an instruction, you just pass a pointer to the object representing the 
instruction.

For example, let us say that I have somehow created an instruction like so:

Instruction * I = AllocaInst::Create (...);

To use the result of the instruction in a pointer for a store 
instruction, I just do the following:

/* V is a Value * and BB is a BasicBlock * that have been defined 
earlier in the code */
Instruction * I = AllocaInst::Create (...);
StoreInst * SI = new StoreInst (V, I, BB);

2) How do I replace the use of one value with another?

In most cases, you use the replaceAllUsesWith() method of Value * (which 
is inherited by Instruction * and a bunch of other classes).  There is 
also some documentation in the Programmer's manual as well.

You may also want to look at the IRBuilder class in doxygen; it is 
apparently the "new" way to create LLVM IR and is less likely to change 
between LLVM releases.

-- John T.

> Edmund
>   




More information about the llvm-dev mailing list