blob: 9403aa26f7517f5bda8ade250b23381732b145da [file] [log] [blame]
Vikram S. Adve39c2a8e2004-06-29 14:20:27 +00001//===- TraceBasicBlocks.cpp - Insert basic-block trace instrumentation ----===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
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.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Module.h"
19#include "llvm/Pass.h"
20#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21#include "llvm/iOther.h"
22#include "llvm/iMemory.h"
23#include "llvm/iPHINode.h"
24#include "ProfilingUtils.h"
25#include "Support/Debug.h"
26#include <set>
27using namespace llvm;
28
29namespace {
30 class TraceBasicBlocks : public Pass {
31 bool run(Module &M);
32 };
33
34 RegisterOpt<TraceBasicBlocks> X("trace-basic-blocks",
35 "Insert instrumentation for basic block tracing");
36}
37
38static void InsertInstrumentationCall (BasicBlock *BB,
39 const std::string FnName,
40 unsigned BBNumber) {
41 DEBUG (std::cerr << "InsertInstrumentationCall (\"" << BB->getName ()
42 << "\", \"" << FnName << "\", " << BBNumber << ")\n");
43 Module &M = *BB->getParent ()->getParent ();
44 Function *InstrFn = M.getOrInsertFunction (FnName, Type::VoidTy,
45 Type::UIntTy, 0);
46 std::vector<Value*> Args (1);
47 Args[0] = ConstantUInt::get (Type::UIntTy, BBNumber);
48
49 // Insert the call after any alloca or PHI instructions...
50 BasicBlock::iterator InsertPos = BB->begin();
51 while (isa<AllocaInst>(InsertPos) || isa<PHINode>(InsertPos))
52 ++InsertPos;
53
54 Instruction *InstrCall = new CallInst (InstrFn, Args, "", InsertPos);
55}
56
57bool TraceBasicBlocks::run(Module &M) {
58 Function *Main = M.getMainFunction();
59 if (Main == 0) {
60 std::cerr << "WARNING: cannot insert basic-block trace instrumentation"
61 << " into a module with no main function!\n";
62 return false; // No main, no instrumentation!
63 }
64
65 unsigned BBNumber = 0;
66 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
67 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
68 InsertInstrumentationCall (BB, "llvm_trace_basic_block", BBNumber);
69 ++BBNumber;
70 }
71
72 // Add the initialization call to main.
73 InsertProfilingInitCall(Main, "llvm_start_basic_block_tracing");
74 return true;
75}
76