Finegrainify namespacification
[oota-llvm.git] / lib / Transforms / Instrumentation / BlockProfiling.cpp
1 //===- BlockProfiling.cpp - Insert counters for block profiling -----------===//
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 counters for basic block or
11 // function profiling.  This is the most basic form of profiling, which can tell
12 // which blocks are hot, but cannot reliably detect hot paths through the CFG.
13 // Block profiling counts the number of times each basic block executes, and
14 // function profiling counts the number of times each function is called.
15 //
16 // Note that this implementation is very naive.  Control equivalent regions of
17 // the CFG should not require duplicate counters, but we do put duplicate
18 // counters in.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Module.h"
26 #include "llvm/Pass.h"
27 using namespace llvm;
28
29 static void insertInitializationCall(Function *MainFn, const char *FnName,
30                                      GlobalValue *Array) {
31   const Type *ArgVTy = PointerType::get(PointerType::get(Type::SByteTy));
32   const Type *UIntPtr = PointerType::get(Type::UIntTy);
33   Module &M = *MainFn->getParent();
34   Function *InitFn = M.getOrInsertFunction(FnName, Type::VoidTy, Type::IntTy,
35                                            ArgVTy, UIntPtr, Type::UIntTy, 0);
36
37   // This could force argc and argv into programs that wouldn't otherwise have
38   // them, but instead we just pass null values in.
39   std::vector<Value*> Args(4);
40   Args[0] = Constant::getNullValue(Type::IntTy);
41   Args[1] = Constant::getNullValue(ArgVTy);
42
43   // Skip over any allocas in the entry block.
44   BasicBlock *Entry = MainFn->begin();
45   BasicBlock::iterator InsertPos = Entry->begin();
46   while (isa<AllocaInst>(InsertPos)) ++InsertPos;
47
48   Function::aiterator AI;
49   switch (MainFn->asize()) {
50   default:
51   case 2:
52     AI = MainFn->abegin(); ++AI;
53     if (AI->getType() != ArgVTy) {
54       Args[1] = new CastInst(AI, ArgVTy, "argv.cast", InsertPos);
55     } else {
56       Args[1] = AI;
57     }
58
59   case 1:
60     AI = MainFn->abegin();
61     if (AI->getType() != Type::IntTy) {
62       Args[0] = new CastInst(AI, Type::IntTy, "argc.cast", InsertPos);
63     } else {
64       Args[0] = AI;
65     }
66     
67   case 0:
68     break;
69   }
70
71   ConstantPointerRef *ArrayCPR = ConstantPointerRef::get(Array);
72   std::vector<Constant*> GEPIndices(2, Constant::getNullValue(Type::LongTy));
73   Args[2] = ConstantExpr::getGetElementPtr(ArrayCPR, GEPIndices);
74   
75   unsigned NumElements =
76     cast<ArrayType>(Array->getType()->getElementType())->getNumElements();
77   Args[3] = ConstantUInt::get(Type::UIntTy, NumElements);
78   
79   new CallInst(InitFn, Args, "", InsertPos);
80 }
81
82 static void IncrementCounterInBlock(BasicBlock *BB, unsigned CounterNum,
83                                     ConstantPointerRef *CounterArray) {
84   // Insert the increment after any alloca or PHI instructions...
85   BasicBlock::iterator InsertPos = BB->begin();
86   while (isa<AllocaInst>(InsertPos) || isa<PHINode>(InsertPos))
87     ++InsertPos;
88
89   // Create the getelementptr constant expression
90   std::vector<Constant*> Indices(2);
91   Indices[0] = Constant::getNullValue(Type::LongTy);
92   Indices[1] = ConstantSInt::get(Type::LongTy, CounterNum);
93   Constant *ElementPtr = ConstantExpr::getGetElementPtr(CounterArray, Indices);
94
95   // Load, increment and store the value back.
96   Value *OldVal = new LoadInst(ElementPtr, "OldFuncCounter", InsertPos);
97   Value *NewVal = BinaryOperator::create(Instruction::Add, OldVal,
98                                          ConstantInt::get(Type::UIntTy, 1),
99                                          "NewFuncCounter", InsertPos);
100   new StoreInst(NewVal, ElementPtr, InsertPos);
101 }
102
103
104 namespace {
105   class FunctionProfiler : public Pass {
106     bool run(Module &M);
107   };
108
109   RegisterOpt<FunctionProfiler> X("insert-function-profiling",
110                                "Insert instrumentation for function profiling");
111 }
112
113 bool FunctionProfiler::run(Module &M) {
114   Function *Main = M.getMainFunction();
115   if (Main == 0) {
116     std::cerr << "WARNING: cannot insert function profiling into a module"
117               << " with no main function!\n";
118     return false;  // No main, no instrumentation!
119   }
120
121   unsigned NumFunctions = 0;
122   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 
123     if (!I->isExternal())
124       ++NumFunctions;
125
126   const Type *ATy = ArrayType::get(Type::UIntTy, NumFunctions);
127   GlobalVariable *Counters =
128     new GlobalVariable(ATy, false, GlobalValue::InternalLinkage,
129                        Constant::getNullValue(ATy), "FuncProfCounters", &M);
130
131   ConstantPointerRef *CounterCPR = ConstantPointerRef::get(Counters);
132
133   // Instrument all of the functions...
134   unsigned i = 0;
135   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 
136     if (!I->isExternal())
137       // Insert counter at the start of the function
138       IncrementCounterInBlock(I->begin(), i++, CounterCPR);
139
140   // Add the initialization call to main.
141   insertInitializationCall(Main, "llvm_start_func_profiling", Counters);
142   return true;
143 }
144
145
146 namespace {
147   class BlockProfiler : public Pass {
148     bool run(Module &M);
149   };
150
151   RegisterOpt<BlockProfiler> Y("insert-block-profiling",
152                                "Insert instrumentation for block profiling");
153 }
154
155 bool BlockProfiler::run(Module &M) {
156   Function *Main = M.getMainFunction();
157   if (Main == 0) {
158     std::cerr << "WARNING: cannot insert block profiling into a module"
159               << " with no main function!\n";
160     return false;  // No main, no instrumentation!
161   }
162
163   unsigned NumBlocks = 0;
164   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 
165     NumBlocks += I->size();
166
167   const Type *ATy = ArrayType::get(Type::UIntTy, NumBlocks);
168   GlobalVariable *Counters =
169     new GlobalVariable(ATy, false, GlobalValue::InternalLinkage,
170                        Constant::getNullValue(ATy), "BlockProfCounters", &M);
171
172   ConstantPointerRef *CounterCPR = ConstantPointerRef::get(Counters);
173
174   // Instrument all of the blocks...
175   unsigned i = 0;
176   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 
177     for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
178       // Insert counter at the start of the block
179       IncrementCounterInBlock(BB, i++, CounterCPR);
180
181   // Add the initialization call to main.
182   insertInitializationCall(Main, "llvm_start_block_profiling", Counters);
183   return true;
184 }
185