From: Chris Lattner
// 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";
}
// 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
std::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 @@ -645,7 +645,7 @@ href="/doxygen/InstIterator_8h-source.html">llvm/Support/InstIterator.h and then instantiate InstIterators explicitly in your code. Here's a small example that shows how to dump all instructions in a function to the standard error stream:
-
#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";
#include "llvm/Support/InstIterator.h"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 @@ -693,7 +693,7 @@ 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: -
...
// Suppose F is a ptr to a function
for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
std::cerr << *i << "\n";
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";
}
void printNextInstruction(Instruction* inst) {@@ -768,7 +768,7 @@ particular function foo. Finding all of the instructions that use foo is as simple as iterating over the def-use chain of F: -
BasicBlock::iterator it(inst);
++it; // after this line, it refers to the instruction after *inst.
if (it != inst->getParent()->end()) std::cerr << *it << "\n";
}
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";
}
}
Function* F = ...;
for (Value::use_iterator i = F->use_begin(), e = F->use_end(); i != e; ++i) {
if (Instruction *Inst = dyn_cast<Instruction>(*i)) {
std::cerr << "F is used in instruction:\n";
std::cerr << *Inst << "\n";
}
}
Alternately, it's common to have an instance of the User Class and need to know what