#define DEBUG_TYPE "insert-edge-profiling"
#include "ProfilingUtils.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/ADT/Statistic.h"
#include <set>
using namespace llvm;
STATISTIC(NumEdgesInserted, "The # of edges inserted.");
namespace {
class EdgeProfiler : public ModulePass {
bool runOnModule(Module &M);
public:
static char ID; EdgeProfiler() : ModulePass(ID) {
initializeEdgeProfilerPass(*PassRegistry::getPassRegistry());
}
virtual const char *getPassName() const {
return "Edge Profiler";
}
};
}
char EdgeProfiler::ID = 0;
INITIALIZE_PASS(EdgeProfiler, "insert-edge-profiling",
"Insert instrumentation for edge profiling", false, false)
ModulePass *llvm::createEdgeProfilerPass() { return new EdgeProfiler(); }
bool EdgeProfiler::runOnModule(Module &M) {
Function *Main = M.getFunction("main");
if (Main == 0) {
errs() << "WARNING: cannot insert edge profiling into a module"
<< " with no main function!\n";
return false; }
std::set<BasicBlock*> BlocksToInstrument;
unsigned NumEdges = 0;
for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
if (F->isDeclaration()) continue;
++NumEdges;
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
BlocksToInstrument.insert(BB);
NumEdges += BB->getTerminator()->getNumSuccessors();
}
}
const Type *ATy = ArrayType::get(Type::getInt32Ty(M.getContext()), NumEdges);
GlobalVariable *Counters =
new GlobalVariable(M, ATy, false, GlobalValue::InternalLinkage,
Constant::getNullValue(ATy), "EdgeProfCounters");
NumEdgesInserted = NumEdges;
unsigned i = 0;
for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
if (F->isDeclaration()) continue;
IncrementCounterInBlock(&F->getEntryBlock(), i++, Counters);
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
if (BlocksToInstrument.count(BB)) { TerminatorInst *TI = BB->getTerminator();
for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {
SplitCriticalEdge(TI, s, this);
if (TI->getNumSuccessors() == 1) {
IncrementCounterInBlock(BB, i++, Counters, false);
} else {
IncrementCounterInBlock(TI->getSuccessor(s), i++, Counters);
}
}
}
}
InsertProfilingInitCall(Main, "llvm_start_edge_profiling", Counters);
return true;
}