91b4e203fc2c95ab5b104c181aeb7c0cb511c357
[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   struct InstLoops : public FunctionPass {
33     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
34       AU.addRequired<DominatorSet>();
35     }
36   private:
37     DominatorSet *DS;
38     void getBackEdgesVisit(BasicBlock *u,
39                            std::map<BasicBlock *, Color > &color,
40                            std::map<BasicBlock *, int > &d, 
41                            int &time, Value *threshold, 
42                            std::map<BasicBlock *, BasicBlock *> &be);
43     void removeRedundant(std::map<BasicBlock *, BasicBlock *> &be);
44     void getBackEdges(Function &F, Value *threshold);
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, Value *threshold, 
65                        std::map<BasicBlock *, BasicBlock *> &be) {
66   
67   color[u]=GREY;
68   time++;
69   d[u]=time;
70
71   for(BasicBlock::succ_iterator vl = succ_begin(u), 
72         ve = succ_end(u); vl != ve; ++vl){
73     
74     BasicBlock *BB = *vl;
75
76     if(color[BB]!=GREY && color[BB]!=BLACK){
77       getBackEdgesVisit(BB, color, d, time, threshold, be);
78     }
79     
80     //now checking for d and f vals
81     else if(color[BB]==GREY){
82       //so v is ancestor of u if time of u > time of v
83       if(d[u] >= d[BB]){
84         //u->BB is a backedge
85         be[u] = BB;
86       }
87     }
88   }
89   color[u]=BLACK;//done with visiting the node and its neighbors
90 }
91
92 //look at all BEs, and remove all BEs that are dominated by other BE's in the
93 //set
94 void InstLoops::removeRedundant(std::map<BasicBlock *, BasicBlock *> &be){
95   std::vector<BasicBlock *> toDelete;
96   for(std::map<BasicBlock *, BasicBlock *>::iterator MI = be.begin(), 
97         ME = be.end(); MI != ME; ++MI){
98     //std::cerr<<MI->first->getName()<<"\t->\t"<<MI->second->getName()<<"\n";
99     //std::cerr<<MI->first;
100     //std::cerr<<MI->second;
101     for(std::map<BasicBlock *, BasicBlock *>::iterator MMI = be.begin(), 
102           MME = be.end(); MMI != MME; ++MMI){
103       if(DS->properlyDominates(MI->first, MMI->first)){
104         toDelete.push_back(MMI->first);
105         //std::cerr<<MI->first->getName()<<"\t Dominates\t"<<MMI->first->getName();
106       }
107     }
108   }
109
110   for(std::vector<BasicBlock *>::iterator VI = toDelete.begin(), 
111         VE = toDelete.end(); VI != VE; ++VI){
112     be.erase(*VI);
113   }
114 }
115
116 //getting the backedges in a graph
117 //Its a variation of DFS to get the backedges in the graph
118 //We get back edges by associating a time
119 //and a color with each vertex.
120 //The time of a vertex is the time when it was first visited
121 //The color of a vertex is initially WHITE,
122 //Changes to GREY when it is first visited,
123 //and changes to BLACK when ALL its neighbors
124 //have been visited
125 //So we have a back edge when we meet a successor of
126 //a node with smaller time, and GREY color
127 void InstLoops::getBackEdges(Function &F, Value *threshold){
128   std::map<BasicBlock *, Color > color;
129   std::map<BasicBlock *, int> d;
130   std::map<BasicBlock *, BasicBlock *> be;
131   int time=0;
132   getBackEdgesVisit(F.begin(), color, d, time, threshold, be);
133
134   removeRedundant(be);
135
136   for(std::map<BasicBlock *, BasicBlock *>::iterator MI = be.begin(),
137         ME = be.end(); MI != ME; ++MI){
138     BasicBlock *u = MI->first;
139     BasicBlock *BB = MI->second;
140     //std::cerr<<"Edge from: "<<BB->getName()<<"->"<<u->getName()<<"\n";
141     //insert a new basic block: modify terminator accordingly!
142     BasicBlock *newBB = new BasicBlock("", u->getParent());
143     BranchInst *ti = cast<BranchInst>(u->getTerminator());
144     unsigned char index = 1;
145     if(ti->getSuccessor(0) == BB){
146       index = 0;
147     }
148     assert(ti->getNumSuccessors() > index && "Not enough successors!");
149     ti->setSuccessor(index, newBB);
150         
151     BasicBlock::InstListType &lt = newBB->getInstList();
152
153     std::vector<const Type*> inCountArgs;
154     const FunctionType *cFty = FunctionType::get(Type::VoidTy, inCountArgs, 
155                                                  false);
156     Function *inCountMth = 
157       u->getParent()->getParent()->getOrInsertFunction("llvm_first_trigger",
158                                                        cFty);
159         
160     assert(inCountMth && "Initial method could not be inserted!");
161
162     Instruction *call = new CallInst(inCountMth, "");
163     lt.push_back(call);
164     lt.push_back(new BranchInst(BB));
165       
166     //now iterate over *vl, and set its Phi nodes right
167     for(BasicBlock::iterator BB2Inst = BB->begin(), BBend = BB->end(); 
168         BB2Inst != BBend; ++BB2Inst){
169         
170       if (PHINode *phiInst = dyn_cast<PHINode>(BB2Inst)){
171         int bbIndex = phiInst->getBasicBlockIndex(u);
172         if(bbIndex>=0){
173           phiInst->setIncomingBlock(bbIndex, newBB);
174         }
175       }
176     }
177   }
178 }
179
180 //Per function pass for inserting counters and call function
181 bool InstLoops::runOnFunction(Function &F){
182   
183   static GlobalVariable *threshold = NULL;
184   static bool insertedThreshold = false;
185
186   DS  = &getAnalysis<DominatorSet>();
187
188   if(F.isExternal()) {
189     return false;
190   }
191
192   if(!insertedThreshold){
193     threshold = new GlobalVariable(Type::IntTy, false,  
194                                    GlobalValue::ExternalLinkage, 0,
195                                    "reopt_threshold");
196     
197     F.getParent()->getGlobalList().push_back(threshold);
198     insertedThreshold = true;
199   }
200
201   if(F.getName() == "main"){
202     //intialize threshold
203     std::vector<const Type*> initialize_args;
204     initialize_args.push_back(PointerType::get(Type::IntTy));
205     
206     const FunctionType *Fty = FunctionType::get(Type::VoidTy, initialize_args,
207                                                 false);
208     Function *initialMeth = F.getParent()->getOrInsertFunction("reoptimizerInitialize", Fty);
209     assert(initialMeth && "Initialize method could not be inserted!");
210     
211     std::vector<Value *> trargs;
212     trargs.push_back(threshold);
213   
214     new CallInst(initialMeth, trargs, "", F.begin()->begin());
215   }
216
217   assert(threshold && "GlobalVariable threshold not defined!");
218   
219   getBackEdges(F, threshold);
220   
221   return true;
222 }