001 Iterating Module, Function, and Basicblock with LLVM
Iterating Function, Basicblock, and Instruction with LLVM
As we discussed previous post, LLVM Structure consists of Modules, functions, basicblocks, and instructions. Therefore, we can search for one of them through its super set. For example, if you are looking for an add
instruction, you can find it by investigating BasicBlocks.
Learning Objectives
- Learn how to iterate LLVM structures(Module, Function, BasicBlock, Instruction)
LLVM
Iterating over Functions
Iterating over Basicblocks
llvm/IR/BasicBlock.h
header is deprecated. So you may include Function.h
or Module.h
when you iterate BasicBlocks.
You can iterate BasicBlocks in a function F.
for(BasicBlock &BB: F){
errs() << "Start BB: " << BB.getName() << ' ' << BB.size() << '\n';
}
Iterating over Instructions
You can iterate instructions in a BasicBlocks BB.
for(Instruction &I: BB){
errs() << "Start Inst: " << I << '\n';
}
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
struct YJ00003BB : public FunctionPass{
static char ID;
YJ00003BB() : FunctionPass(ID){}
bool runOnFunction(Function &F) override{
// Function
errs() << "Start Function: " << F.getName() << '\n';
for(BasicBlock &BB: F){
errs() << "Start BB: " << BB.getName() << ' ' << BB.size() << '\n';
for(Instruction & I : BB){
errs() << "Start Inst: " << I << '\n';
}
}
return false;
}
};
}
char YJ00003BB::ID = 0;
static RegisterPass<YJ00003BB> X("BasicBlock", "Print basic block", false, false);
Pass | Type |
---|---|
Writing HelloLLVM Pass | analysis |
Iterating over Module, Function, Basic block | analysis |
Count the number of insts, func calls | analysis |
Insert func call | transformation |
Change Insts (obfuscation) | transformation |
Control flow graph | transformation |
Reference
[1] Andrzej Warzyński. llvm-tutor. github
[2] Adrian Sampson. LLVM for Grad Students. blog
[3] Keshav Pingali. CS 380C: Advanced Topics in Compilers. blog
Enjoy Reading This Article?
Here are some more articles you might like to read next: