1 //===- TraceBasicBlocks.cpp - Insert basic-block trace instrumentation ----===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass instruments the specified program with calls into a runtime
11 // library that cause it to output a trace of basic blocks as a side effect
12 // of normal execution.
14 //===----------------------------------------------------------------------===//
16 #include "ProfilingUtils.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
22 #include "llvm/Transforms/Instrumentation.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Support/Debug.h"
29 class TraceBasicBlocks : public ModulePass {
30 bool runOnModule(Module &M);
33 RegisterPass<TraceBasicBlocks> X("trace-basic-blocks",
34 "Insert instrumentation for basic block tracing");
37 ModulePass *llvm::createTraceBasicBlockPass()
39 return new TraceBasicBlocks();
42 static void InsertInstrumentationCall (BasicBlock *BB,
43 const std::string FnName,
45 DOUT << "InsertInstrumentationCall (\"" << BB->getName ()
46 << "\", \"" << FnName << "\", " << BBNumber << ")\n";
47 Module &M = *BB->getParent ()->getParent ();
48 Constant *InstrFn = M.getOrInsertFunction (FnName, Type::VoidTy,
49 Type::Int32Ty, (Type *)0);
51 // Insert the call after any alloca or PHI instructions.
52 BasicBlock::iterator InsertPos = BB->begin();
53 while (isa<AllocaInst>(InsertPos) || isa<PHINode>(InsertPos))
56 new CallInst(InstrFn, ConstantInt::get (Type::Int32Ty, BBNumber),
60 bool TraceBasicBlocks::runOnModule(Module &M) {
61 Function *Main = M.getMainFunction();
63 cerr << "WARNING: cannot insert basic-block trace instrumentation"
64 << " into a module with no main function!\n";
65 return false; // No main, no instrumentation!
68 unsigned BBNumber = 0;
69 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
70 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
71 InsertInstrumentationCall (BB, "llvm_trace_basic_block", BBNumber);
75 // Add the initialization call to main.
76 InsertProfilingInitCall(Main, "llvm_start_basic_block_tracing");