LLVM Programmer's Manual |
Written by Chris Lattner, Dinakar Dhurjati, and Joel Stanley
Introduction |
This document should get you oriented so that you can find your way in the continuously growing source code that makes up the LLVM infrastructure. Note that this manual is not intended to serve as a replacement for reading the source code, so if you think there should be a method in one of these classes to do something, but it's not listed, check the source. Links to the doxygen sources are provided to make this as easy as possible.
The first section of this document describes general information that is useful to know when working in the LLVM infrastructure, and the second describes the Core LLVM classes. In the future this manual will be extended with information describing how to use extension libraries, such as dominator information, CFG traversal routines, and useful utilities like the InstVisitor template.
General Information |
The C++ Standard Template Library |
Here are some useful links:
You are also encouraged to take a look at the LLVM Coding Standards guide which focuses on how to write maintainable code more than where to put your curly braces.
Important and useful LLVM APIs |
The isa<>, cast<> and dyn_cast<> templates |
static bool isLoopInvariant(const Value *V, const Loop *L) { if (isa<Constant>(V) || isa<Argument>(V) || isa<GlobalValue>(V)) return true; // Otherwise, it must be an instruction... return !L->contains(cast<Instruction>(V)->getParent());
Note that you should not use an isa<> test followed by a cast<>, for that use the dyn_cast<> operator.
if (AllocationInst *AI = dyn_cast<AllocationInst>(Val)) { ... }
This form of the if statement effectively combines together a call to isa<> and a call to cast<> into one statement, which is very convenient.
Another common example is:
// Loop over all of the phi nodes in a basic block BasicBlock::iterator BBI = BB->begin(); for (; PHINode *PN = dyn_cast<PHINode>(&*BBI); ++BBI) cerr << *PN;
Note that the dyn_cast<> operator, like C++'s dynamic_cast or Java's instanceof operator, can be abused. In particular you should not use big chained if/then/else blocks to check for lots of different variants of classes. If you find yourself wanting to do this, it is much cleaner and more efficient to use the InstVisitor class to dispatch over the instruction type directly.
The DEBUG() macro & -debug option |
Naturally, because of this, you don't want to delete the debug printouts, but you don't want them to always be noisy. A standard compromise is to comment them out, allowing you to enable them if you need them in the future.
The "Support/Statistic.h" file provides a macro named DEBUG() that is a much nicer solution to this problem. Basically, you can put arbitrary code into the argument of the DEBUG macro, and it is only executed if 'opt' is run with the '-debug' command line argument:
... DEBUG(std::cerr << "I am here!\n"); ...
Then you can run your pass like this:
$ opt < a.bc > /dev/null -mypass <no output> $ opt < a.bc > /dev/null -mypass -debug I am here! $
Using the DEBUG() macro instead of a home brewed solution allows you to now have to create "yet another" command line option for the debug output for your pass. Note that DEBUG() macros are disabled for optimized builds, so they do not cause a performance impact at all (for the same reason, they should also not contain side-effects!).
One additional nice thing about the DEBUG() macro is that you can enable or disable it directly in gdb. Just use "set DebugFlag=0" or "set DebugFlag=1" from the gdb if the program is running. If the program hasn't been started yet, you can always just run it with -debug.
The Statistic template & -stats option |
Often you may run your pass on some big program, and you're interested to see how many times it makes a certain transformation. Although you can do this with hand inspection, or some ad-hoc method, this is a real pain and not very useful for big programs. Using the Statistic template makes it very easy to keep track of this information, and the calculated information is presented in a uniform manner with the rest of the passes being executed.
There are many examples of Statistic users, but this basics of using it are as follows:
static Statistic<> NumXForms("mypassname", "The # of times I did stuff");
The Statistic template can emulate just about any data-type, but if you do not specify a template argument, it defaults to acting like an unsigned int counter (this is usually what you want).
++NumXForms; // I did stuff
That's all you have to do. To get 'opt' to print out the statistics gathered, use the '-stats' option:
$ opt -stats -mypassname < program.bc > /dev/null ... statistic output ...
When running gccas on a C file from the SPEC benchmark suite, it gives a report that looks like this:
7646 bytecodewriter - Number of normal instructions 725 bytecodewriter - Number of oversized instructions 129996 bytecodewriter - Number of bytecode bytes written 2817 raise - Number of insts DCEd or constprop'd 3213 raise - Number of cast-of-self removed 5046 raise - Number of expression trees converted 75 raise - Number of other getelementptr's formed 138 raise - Number of load/store peepholes 42 deadtypeelim - Number of unused typenames removed from symtab 392 funcresolve - Number of varargs functions resolved 27 globaldce - Number of global variables removed 2 adce - Number of basic blocks removed 134 cee - Number of branches revectored 49 cee - Number of setcc instruction eliminated 532 gcse - Number of loads removed 2919 gcse - Number of instructions removed 86 indvars - Number of cannonical indvars added 87 indvars - Number of aux indvars removed 25 instcombine - Number of dead inst eliminate 434 instcombine - Number of insts combined 248 licm - Number of load insts hoisted 1298 licm - Number of insts hoisted to a loop pre-header 3 licm - Number of insts hoisted to multiple loop preds (bad, no loop pre-header) 75 mem2reg - Number of alloca's promoted 1444 cfgsimplify - Number of blocks simplified
Obviously, with so many optimizations, having a unified framework for this stuff is very nice. Making your pass fit well into the framework makes it more maintainable and useful.
Helpful Hints for Common Operations |
Because this is a "how-to" section, you should also read about the main classes that you will be working with. The Core LLVM Class Hierarchy Reference contains details and descriptions of the main classes that you should know about.
Basic Inspection and Traversal Routines |
Because the pattern for iteration is common across many different aspects of the program representation, the standard template library algorithms may be used on them, and it is easier to remember how to iterate. First we show a few common examples of the data structures that need to be traversed. Other data structures are traversed in very similar ways.
// func is a pointer to a Function instance for(Function::iterator i = func->begin(), e = func->end(); i != e; ++i) { // print out the name of the basic block if it has one, and then the // number of instructions that it contains cerr << "Basic block (name=" << i->getName() << ") has " << i->size() << " instructions.\n"; }Note that i can be used as if it were a pointer for the purposes of invoking member functions of the Instruction class. This is because the indirection operator is overloaded for the iterator classes. In the above code, the expression i->size() is exactly equivalent to (*i).size() just like you'd expect.
// blk is a pointer to a BasicBlock instance for(BasicBlock::iterator i = blk->begin(), e = blk->end(); i != e; ++i) // the next statement works since operator<<(ostream&,...) // is overloaded for Instruction& cerr << *i << "\n";However, this isn't really the best way to print out the contents of a BasicBlock! Since the ostream operators are overloaded for virtually anything you'll care about, you could have just invoked the print routine on the basic block itself: cerr << *blk << "\n";.
Note that currently operator<< is implemented for Value*, so it will print out the contents of the pointer, instead of the pointer value you might expect. This is a deprecated interface that will be removed in the future, so it's best not to depend on it. To print out the pointer value for now, you must cast to void*.
#include "llvm/Support/InstIterator.h" ... // Suppose F is a ptr to a function for(inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) cerr << **i << "\n";Easy, isn't it? You can also use InstIterators to fill a worklist with its initial contents. For example, if you wanted to initialize a worklist to contain all instructions in a Function F, all you would need to do is something like:
std::set<Instruction*> worklist; worklist.insert(inst_begin(F), inst_end(F));The STL set worklist would now contain all instructions in the Function pointed to by F.
Instruction& inst = *i; // grab reference to instruction reference Instruction* pinst = &*i; // grab pointer to instruction reference const Instruction& inst = *j;However, the iterators you'll be working with in the LLVM framework are special: they will automatically convert to a ptr-to-instance type whenever they need to. Instead of dereferencing the iterator and then taking the address of the result, you can simply assign the iterator to the proper pointer type and you get the dereference and address-of operation as a result of the assignment (behind the scenes, this is a result of overloading casting mechanisms). Thus the last line of the last example,
Instruction* pinst = &*i;is semantically equivalent to
Instruction* pinst = i;Caveat emptor: The above syntax works only when you're not working with dyn_cast. The template definition of dyn_cast isn't implemented to handle this yet, so you'll still need the following in order for things to work properly:
BasicBlock::iterator bbi = ...; BranchInst* b = dyn_cast<BranchInst>(&*bbi);It's also possible to turn a class pointer into the corresponding iterator. Usually, this conversion is quite inexpensive. The following code snippet illustrates use of the conversion constructors provided by LLVM iterators. By using these, you can explicitly grab the iterator of something without actually obtaining it via iteration over some structure:
void printNextInstruction(Instruction* inst) { BasicBlock::iterator it(inst); ++it; // after this line, it refers to the instruction after *inst. if(it != inst->getParent()->end()) cerr << *it << "\n"; }Of course, this example is strictly pedagogical, because it'd be much better to explicitly grab the next instruction directly from inst.
initialize callCounter to zero for each Function f in the Module for each BasicBlock b in f for each Instruction i in b if(i is a CallInst and calls the given function) increment callCounterAnd the actual code is (remember, since we're writing a FunctionPass, our FunctionPass-derived class simply has to override the runOnFunction method...):
Function* targetFunc = ...; class OurFunctionPass : public FunctionPass { public: OurFunctionPass(): callCounter(0) { } virtual runOnFunction(Function& F) { for(Function::iterator b = F.begin(), be = F.end(); b != be; ++b) { for(BasicBlock::iterator i = b->begin(); ie = b->end(); i != ie; ++i) { if (CallInst* callInst = dyn_cast<CallInst>(&*i)) { // we know we've encountered a call instruction, so we // need to determine if it's a call to the // function pointed to by m_func or not. if(callInst->getCalledFunction() == targetFunc) ++callCounter; } } } private: unsigned callCounter; };
Function* F = ...; for(Value::use_iterator i = F->use_begin(), e = F->use_end(); i != e; ++i) { if(Instruction* Inst = dyn_cast<Instruction>(*i)) { cerr << "F is used in instruction:\n"; cerr << *Inst << "\n"; } }Alternately, it's common to have an instance of the User Class and need to know what Values are used by it. The list of all Values used by a User is known as a use-def chain. Instances of class Instruction are common Users, so we might want to iterate over all of the values that a particular instruction uses (that is, the operands of the particular Instruction):
Instruction* pi = ...; for(User::op_iterator i = pi->op_begin(), e = pi->op_end(); i != e; ++i) { Value* v = *i; ... }
Making simple changes |
Creation of Instructions is straightforward: simply call the constructor for the kind of instruction to instantiate and provide the necessary parameters. For example, an AllocaInst only requires a (const-ptr-to) Type. Thus:
AllocaInst* ai = new AllocaInst(Type::IntTy);will create an AllocaInst instance that represents the allocation of one integer in the current stack frame, at runtime. Each Instruction subclass is likely to have varying default parameters which change the semantics of the instruction, so refer to the doxygen documentation for the subclass of Instruction that you're interested in instantiating.
Naming values
It is very useful to name the values of instructions when you're able to, as this facilitates the debugging of your transformations. If you end up looking at generated LLVM machine code, you definitely want to have logical names associated with the results of instructions! By supplying a value for the Name (default) parameter of the Instruction constructor, you associate a logical name with the result of the instruction's execution at runtime. For example, say that I'm writing a transformation that dynamically allocates space for an integer on the stack, and that integer is going to be used as some kind of index by some other code. To accomplish this, I place an AllocaInst at the first point in the first BasicBlock of some Function, and I'm intending to use it within the same Function. I might do:
AllocaInst* pa = new AllocaInst(Type::IntTy, 0, "indexLoc");where indexLoc is now the logical name of the instruction's execution value, which is a pointer to an integer on the runtime stack.
Inserting instructions
There are essentially two ways to insert an Instruction into an existing sequence of instructions that form a BasicBlock:
Given a BasicBlock* pb, an Instruction* pi within that BasicBlock, and a newly-created instruction we wish to insert before *pi, we do the following:
BasicBlock* pb = ...; Instruction* pi = ...; Instruction* newInst = new Instruction(...); pb->getInstList().insert(pi, newInst); // inserts newInst before pi in pb
Instruction instances that are already in BasicBlocks are implicitly associated with an existing instruction list: the instruction list of the enclosing basic block. Thus, we could have accomplished the same thing as the above code without being given a BasicBlock by doing:
Instruction* pi = ...; Instruction* newInst = new Instruction(...); pi->getParent()->getInstList().insert(pi, newInst);In fact, this sequence of steps occurs so frequently that the Instruction class and Instruction-derived classes provide constructors which take (as a default parameter) a pointer to an Instruction which the newly-created Instruction should precede. That is, Instruction constructors are capable of inserting the newly-created instance into the BasicBlock of a provided instruction, immediately before that instruction. Using an Instruction constructor with a insertBefore (default) parameter, the above code becomes:
Instruction* pi = ...; Instruction* newInst = new Instruction(..., pi);which is much cleaner, especially if you're creating a lot of instructions and adding them to BasicBlocks.
For example:
Instruction *I = .. ; BasicBlock *BB = I->getParent(); BB->getInstList().erase(I);
Replacing individual instructions
Including "llvm/Transforms/Utils/BasicBlockUtils.h " permits use of two very useful replace functions: ReplaceInstWithValue and ReplaceInstWithInst.
This function replaces all uses (within a basic block) of a given instruction with a value, and then removes the original instruction. The following example illustrates the replacement of the result of a particular AllocaInst that allocates memory for a single integer with an null pointer to an integer.
AllocaInst* instToReplace = ...; BasicBlock::iterator ii(instToReplace); ReplaceInstWithValue(instToReplace->getParent()->getInstList(), ii, Constant::getNullValue(PointerType::get(Type::IntTy)));
This function replaces a particular instruction with another instruction. The following example illustrates the replacement of one AllocaInst with another.
AllocaInst* instToReplace = ...; BasicBlock::iterator ii(instToReplace); ReplaceInstWithInst(instToReplace->getParent()->getInstList(), ii, new AllocaInst(Type::IntTy, 0, "ptrToReplacedInt");
Replacing multiple uses of Users and Values
You can use Value::replaceAllUsesWith and User::replaceUsesOfWith to change more than one use at a time. See the doxygen documentation for the Value Class and User Class, respectively, for more information.The Core LLVM Class Hierarchy Reference |
The Value class |
The Value class is the most important class in LLVM Source base. It represents a typed value that may be used (among other things) as an operand to an instruction. There are many different types of Values, such as Constants, Arguments, and even Instructions and Functions are Values.
A particular Value may be used many times in the LLVM representation for a program. For example, an incoming argument to a function (represented with an instance of the Argument class) is "used" by every instruction in the function that references the argument. To keep track of this relationship, the Value class keeps a list of all of the Users that is using it (the User class is a base class for all nodes in the LLVM graph that can refer to Values). This use list is how LLVM represents def-use information in the program, and is accessible through the use_* methods, shown below.
Because LLVM is a typed representation, every LLVM Value is typed, and
this Type is available through the getType()
method. In addition, all LLVM values can be named. The
"name" of the Value is symbolic string printed in the LLVM code:
One important aspect of LLVM is that there is no distinction between an SSA
variable and the operation that produces it. Because of this, any reference to
the value produced by an instruction (or the value available as an incoming
argument, for example) is represented as a direct pointer to the class that
represents this value. Although this may take some getting used to, it
simplifies the representation and makes it easier to manipulate.
%foo = add int 1, 2
The name of this instruction is "foo". NOTE that the name of any value
may be missing (an empty string), so names should ONLY be used for
debugging (making the source code easier to read, debugging printouts), they
should not be used to keep track of values or map between them. For this
purpose, use a std::map of pointers to the Value itself
instead.
These methods are the interface to access the def-use information in LLVM. As with all other iterators in LLVM, the naming conventions follow the conventions defined by the STL.
This method returns the Type of the Value.
This family of methods is used to access and assign a name to a Value, be aware of the precaution above.
This method traverses the use list of a Value changing all Users of the current value to refer to "V" instead. For example, if you detect that an instruction always produces a constant value (for example through constant folding), you can replace all uses of the instruction with the constant like this:
Inst->replaceAllUsesWith(ConstVal);
The User class |
The User class is the common base class of all LLVM nodes that may refer to Values. It exposes a list of "Operands" that are all of the Values that the User is referring to. The User class itself is a subclass of Value.
The operands of a User point directly to the LLVM Value that it refers to. Because LLVM uses Static Single Assignment (SSA) form, there can only be one definition referred to, allowing this direct connection. This connection provides the use-def information in LLVM.
These two methods expose the operands of the User in a convenient form for direct access.
Together, these methods make up the iterator based interface to the operands of a User.
The Instruction class |
The Instruction class is the common base class for all LLVM instructions. It provides only a few methods, but is a very commonly used class. The primary data tracked by the Instruction class itself is the opcode (instruction type) and the parent BasicBlock the Instruction is embedded into. To represent a specific type of instruction, one of many subclasses of Instruction are used.
Because the Instruction class subclasses the User class, its operands can be accessed in the same way as for other Users (with the getOperand()/getNumOperands() and op_begin()/op_end() methods).
An important file for the Instruction class is the llvm/Instruction.def file. This file contains some meta-data about the various different types of instructions in LLVM. It describes the enum values that are used as opcodes (for example Instruction::Add and Instruction::SetLE), as well as the concrete sub-classes of Instruction that implement the instruction (for example BinaryOperator and SetCondInst). Unfortunately, the use of macros in this file confused doxygen, so these enum values don't show up correctly in the doxygen output.
Returns the BasicBlock that this Instruction is embedded into.
Returns true if the instruction has side effects, i.e. it is a call, free, invoke, or store.
Returns the opcode for the Instruction.
Returns another instance of the specified instruction, identical in all ways to the original except that the instruction has no parent (ie it's not embedded into a BasicBlock), and it has no name.
The BasicBlock class |
This class represents a single entry multiple exit section of the code, commonly known as a basic block by the compiler community. The BasicBlock class maintains a list of Instructions, which form the body of the block. Matching the language definition, the last element of this list of instructions is always a terminator instruction (a subclass of the TerminatorInst class).
In addition to tracking the list of instructions that make up the block, the BasicBlock class also keeps track of the Function that it is embedded into.
Note that BasicBlocks themselves are Values, because they are referenced by instructions like branches and can go in the switch tables. BasicBlocks have type label.
The BasicBlock constructor is used to create new basic blocks for insertion into a function. The constructor simply takes a name for the new block, and optionally a Function to insert it into. If the Parent parameter is specified, the new BasicBlock is automatically inserted at the end of the specified Function, if not specified, the BasicBlock must be manually inserted into the Function.
These methods and typedefs are forwarding functions that have the same semantics as the standard library methods of the same names. These methods expose the underlying instruction list of a basic block in a way that is easy to manipulate. To get the full complement of container operations (including operations to update the list), you must use the getInstList() method.
This method is used to get access to the underlying container that actually holds the Instructions. This method must be used when there isn't a forwarding function in the BasicBlock class for the operation that you would like to perform. Because there are no forwarding functions for "updating" operations, you need to use this if you want to update the contents of a BasicBlock.
Returns a pointer to Function the block is embedded into, or a null pointer if it is homeless.
Returns a pointer to the terminator instruction that appears at the end of the BasicBlock. If there is no terminator instruction, or if the last instruction in the block is not a terminator, then a null pointer is returned.
The GlobalValue class |
Global values (GlobalVariables or Functions) are the only LLVM values that are visible in the bodies of all Functions. Because they are visible at global scope, they are also subject to linking with other globals defined in different translation units. To control the linking process, GlobalValues know their linkage rules. Specifically, GlobalValues know whether they have internal or external linkage.
If a GlobalValue has internal linkage (equivalent to being static in C), it is not visible to code outside the current translation unit, and does not participate in linking. If it has external linkage, it is visible to external code, and does participate in linking. In addition to linkage information, GlobalValues keep track of which Module they are currently part of.
Because GlobalValues are memory objects, they are always referred to by their address. As such, the Type of a global is always a pointer to its contents. This is explained in the LLVM Language Reference Manual.
These methods manipulate the linkage characteristics of the GlobalValue.
This returns the Module that the GlobalValue is currently embedded into.
The Function class |
The Function class represents a single procedure in LLVM. It is actually one of the more complex classes in the LLVM heirarchy because it must keep track of a large amount of data. The Function class keeps track of a list of BasicBlocks, a list of formal Arguments, and a SymbolTable.
The list of BasicBlocks is the most commonly used part of Function objects. The list imposes an implicit ordering of the blocks in the function, which indicate how the code will be layed out by the backend. Additionally, the first BasicBlock is the implicit entry node for the Function. It is not legal in LLVM explicitly branch to this initial block. There are no implicit exit nodes, and in fact there may be multiple exit nodes from a single Function. If the BasicBlock list is empty, this indicates that the Function is actually a function declaration: the actual body of the function hasn't been linked in yet.
In addition to a list of BasicBlocks, the Function class also keeps track of the list of formal Arguments that the function receives. This container manages the lifetime of the Argument nodes, just like the BasicBlock list does for the BasicBlocks.
The SymbolTable is a very rarely used LLVM feature that is only used when you have to look up a value by name. Aside from that, the SymbolTable is used internally to make sure that there are not conflicts between the names of Instructions, BasicBlocks, or Arguments in the function body.
Constructor used when you need to create new Functions to add the the program. The constructor must specify the type of the function to create and whether or not it should start out with internal or external linkage.
Return whether or not the Function has a body defined. If the function is "external", it does not have a body, and thus must be resolved by linking with a function defined in a different translation unit.
These are forwarding methods that make it easy to access the contents of a Function object's BasicBlock list.
Returns the list of BasicBlocks. This is neccesary to use when you need to update the list or perform a complex action that doesn't have a forwarding method.
These are forwarding methods that make it easy to access the contents of a Function object's Argument list.
Returns the list of Arguments. This is neccesary to use when you need to update the list or perform a complex action that doesn't have a forwarding method.
Returns the entry BasicBlock for the function. Because the entry block for the function is always the first block, this returns the first block of the Function.
This traverses the Type of the Function and returns the return type of the function, or the FunctionType of the actual function.
Return a pointer to the SymbolTable for this Function.
The GlobalVariable class |
Global variables are represented with the (suprise suprise) GlobalVariable class. Like functions, GlobalVariables are also subclasses of GlobalValue, and as such are always referenced by their address (global values must live in memory, so their "name" refers to their address). Global variables may have an initial value (which must be a Constant), and if they have an initializer, they may be marked as "constant" themselves (indicating that their contents never change at runtime).
Create a new global variable of the specified type. If isConstant is true then the global variable will be marked as unchanging for the program, and if isInternal is true the resultant global variable will have internal linkage. Optionally an initializer and name may be specified for the global variable as well.
Returns true if this is a global variable is known not to be modified at runtime.
Returns true if this GlobalVariable has an intializer.
Returns the intial value for a GlobalVariable. It is not legal to call this method if there is no initializer.
The Module class |
The Module class represents the top level structure present in LLVM programs. An LLVM module is effectively either a translation unit of the original program or a combination of several translation units merged by the linker. The Module class keeps track of a list of Functions, a list of GlobalVariables, and a SymbolTable. Additionally, it contains a few helpful member functions that try to make common operations easy.
These are forwarding methods that make it easy to access the contents of a Module object's Function list.
Returns the list of Functions. This is neccesary to use when you need to update the list or perform a complex action that doesn't have a forwarding method.
These are forwarding methods that make it easy to access the contents of a Module object's GlobalVariable list.
Returns the list of GlobalVariables. This is neccesary to use when you need to update the list or perform a complex action that doesn't have a forwarding method.
Return a reference to the SymbolTable for this Module.
Look up the specified function in the Module SymbolTable. If it does not exist, return null.
Look up the specified function in the Module SymbolTable. If it does not exist, add an external declaration for the function and return it.
If there is at least one entry in the SymbolTable for the specified Type, return it. Otherwise return the empty string.
Insert an entry in the SymbolTable mapping Name to Ty. If there is already an entry for this name, true is returned and the SymbolTable is not modified.
The Constant class and subclasses |
The Type class and Derived Types |
The Argument class |