Give std::map<BasicBlock *, BasicBlock *> the short name BBMap, because
[oota-llvm.git] / lib / Transforms / Instrumentation / ProfilePaths / InstLoops.cpp
1 //===-- InstLoops.cpp ---------------------------------------- ---*- C++ -*--=//
2 // Pass to instrument loops
3 //
4 // At every backedge, insert a counter for that backedge and a call function
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Reoptimizer/InstLoops.h"
8 #include "llvm/Analysis/Dominators.h"
9 #include "llvm/Support/CFG.h"
10 #include "llvm/Constants.h"
11 #include "llvm/iMemory.h"
12 #include "llvm/GlobalVariable.h"
13 #include "llvm/DerivedTypes.h"
14 #include "llvm/iOther.h"
15 #include "llvm/iOperators.h"
16 #include "llvm/iTerminators.h"
17 #include "llvm/iPHINode.h"
18 #include "llvm/Module.h"
19 #include "llvm/Function.h"
20 #include "llvm/Pass.h"
21
22 //this is used to color vertices
23 //during DFS
24
25 enum Color{
26   WHITE,
27   GREY,
28   BLACK
29 };
30
31 namespace{
32   typedef std::map<BasicBlock *, BasicBlock *> BBMap;
33   struct InstLoops : public FunctionPass {
34     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
35       AU.addRequired<DominatorSet>();
36     }
37   private:
38     DominatorSet *DS;
39     void getBackEdgesVisit(BasicBlock *u,
40                            std::map<BasicBlock *, Color > &color,
41                            std::map<BasicBlock *, int > &d, 
42                            int &time, BBMap &be);
43     void removeRedundant(BBMap &be);
44     void findAndInstrumentBackEdges(Function &F);
45   public:
46     bool runOnFunction(Function &F);
47   };
48   
49   RegisterOpt<InstLoops> X("instloops", "Instrument backedges for profiling");
50 }
51
52 // createInstLoopsPass - Create a new pass to add path profiling
53 //
54 Pass *createInstLoopsPass() {
55   return new InstLoops();
56 }
57
58
59 //helper function to get back edges: it is called by 
60 //the "getBackEdges" function below
61 void InstLoops::getBackEdgesVisit(BasicBlock *u,
62                        std::map<BasicBlock *, Color > &color,
63                        std::map<BasicBlock *, int > &d, 
64                        int &time, BBMap &be) {
65   color[u]=GREY;
66   time++;
67   d[u]=time;
68
69   for(BasicBlock::succ_iterator vl = succ_begin(u), 
70         ve = succ_end(u); vl != ve; ++vl){
71     BasicBlock *BB = *vl;
72
73     if(color[BB]!=GREY && color[BB]!=BLACK){
74       getBackEdgesVisit(BB, color, d, time, be);
75     }
76     
77     //now checking for d and f vals
78     else if(color[BB]==GREY){
79       //so v is ancestor of u if time of u > time of v
80       if(d[u] >= d[BB]){
81         //u->BB is a backedge
82         be[u] = BB;
83       }
84     }
85   }
86   color[u]=BLACK;//done with visiting the node and its neighbors
87 }
88
89 //look at all BEs, and remove all BEs that are dominated by other BE's in the
90 //set
91 void InstLoops::removeRedundant(BBMap &be) {
92   std::vector<BasicBlock *> toDelete;
93   for(std::map<BasicBlock *, BasicBlock *>::iterator MI = be.begin(), 
94         ME = be.end(); MI != ME; ++MI)
95     for(BBMap::iterator MMI = be.begin(), MME = be.end(); MMI != MME; ++MMI)
96       if(DS->properlyDominates(MI->first, MMI->first))
97         toDelete.push_back(MMI->first);
98   // Remove all the back-edges we found from be.
99   for(std::vector<BasicBlock *>::iterator VI = toDelete.begin(), 
100         VE = toDelete.end(); VI != VE; ++VI)
101     be.erase(*VI);
102 }
103
104 //getting the backedges in a graph
105 //Its a variation of DFS to get the backedges in the graph
106 //We get back edges by associating a time
107 //and a color with each vertex.
108 //The time of a vertex is the time when it was first visited
109 //The color of a vertex is initially WHITE,
110 //Changes to GREY when it is first visited,
111 //and changes to BLACK when ALL its neighbors
112 //have been visited
113 //So we have a back edge when we meet a successor of
114 //a node with smaller time, and GREY color
115 void InstLoops::findAndInstrumentBackEdges(Function &F){
116   std::map<BasicBlock *, Color > color;
117   std::map<BasicBlock *, int> d;
118   BBMap be;
119   int time=0;
120   getBackEdgesVisit(F.begin(), color, d, time, be);
121
122   removeRedundant(be);
123
124   for(std::map<BasicBlock *, BasicBlock *>::iterator MI = be.begin(),
125         ME = be.end(); MI != ME; ++MI){
126     BasicBlock *u = MI->first;
127     BasicBlock *BB = MI->second;
128     //std::cerr<<"Edge from: "<<BB->getName()<<"->"<<u->getName()<<"\n";
129     //insert a new basic block: modify terminator accordingly!
130     BasicBlock *newBB = new BasicBlock("", u->getParent());
131     BranchInst *ti = cast<BranchInst>(u->getTerminator());
132     unsigned char index = 1;
133     if(ti->getSuccessor(0) == BB){
134       index = 0;
135     }
136     assert(ti->getNumSuccessors() > index && "Not enough successors!");
137     ti->setSuccessor(index, newBB);
138         
139     BasicBlock::InstListType &lt = newBB->getInstList();
140
141     std::vector<const Type*> inCountArgs;
142     const FunctionType *cFty = FunctionType::get(Type::VoidTy, inCountArgs, 
143                                                  false);
144     Function *inCountMth = 
145       u->getParent()->getParent()->getOrInsertFunction("llvm_first_trigger",
146                                                        cFty);
147         
148     assert(inCountMth && "Initial method could not be inserted!");
149
150     Instruction *call = new CallInst(inCountMth);
151     lt.push_back(call);
152     lt.push_back(new BranchInst(BB));
153       
154     //now iterate over *vl, and set its Phi nodes right
155     for(BasicBlock::iterator BB2Inst = BB->begin(), BBend = BB->end(); 
156         BB2Inst != BBend; ++BB2Inst){
157         
158       if (PHINode *phiInst = dyn_cast<PHINode>(BB2Inst)){
159         int bbIndex = phiInst->getBasicBlockIndex(u);
160         if(bbIndex>=0){
161           phiInst->setIncomingBlock(bbIndex, newBB);
162         }
163       }
164     }
165   }
166 }
167
168 /// Entry point for FunctionPass that inserts calls to trigger function.
169 ///
170 bool InstLoops::runOnFunction(Function &F){
171   DS  = &getAnalysis<DominatorSet>();
172   if(F.isExternal()) {
173     return false;
174   }
175   // Add a call to reoptimizerInitialize() to beginning of function named main.
176   if(F.getName() == "main"){
177     std::vector<const Type*> argTypes;  // Empty formal parameter list.
178     const FunctionType *Fty = FunctionType::get(Type::VoidTy, argTypes, false);
179     Function *initialMeth =
180       F.getParent()->getOrInsertFunction("reoptimizerInitialize", Fty);
181     assert(initialMeth && "Initialize method could not be inserted!");
182     new CallInst(initialMeth, "", F.begin()->begin());  // Insert it.
183   }
184   findAndInstrumentBackEdges(F);
185   return true;  // Function was modified.
186 }