Be a bit more efficient when processing the active and inactive
[oota-llvm.git] / lib / Transforms / Instrumentation / ProfilePaths / InstLoops.cpp
1 //===-- InstLoops.cpp -----------------------------------------------------===//
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 is the first-level instrumentation pass for the Reoptimizer. It
11 // instrument the back-edges of loops by inserting a basic block
12 // containing a call to llvm_first_trigger (the first-level trigger function),
13 // and inserts an initialization call to the main() function.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/Dominators.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Type.h"
23 #include "Support/Debug.h"
24 #include "../ProfilingUtils.h"
25
26 namespace llvm {
27
28 //this is used to color vertices
29 //during DFS
30
31 enum Color{
32   WHITE,
33   GREY,
34   BLACK
35 };
36
37 namespace {
38   typedef std::map<BasicBlock *, BasicBlock *> BBMap;
39   struct InstLoops : public FunctionPass {
40     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41       AU.addRequired<DominatorSet>();
42     }
43   private:
44     Function *inCountMth;
45     DominatorSet *DS;
46     void getBackEdgesVisit(BasicBlock *u,
47                            std::map<BasicBlock *, Color > &color,
48                            std::map<BasicBlock *, int > &d, 
49                            int &time, BBMap &be);
50     void removeRedundant(BBMap &be);
51     void findAndInstrumentBackEdges(Function &F);
52   public:
53     bool doInitialization(Module &M);
54     bool runOnFunction(Function &F);
55   };
56   
57   RegisterOpt<InstLoops> X("instloops", "Instrument backedges for profiling");
58 }
59
60 //helper function to get back edges: it is called by 
61 //the "getBackEdges" function below
62 void InstLoops::getBackEdgesVisit(BasicBlock *u,
63                        std::map<BasicBlock *, Color > &color,
64                        std::map<BasicBlock *, int > &d, 
65                        int &time, BBMap &be) {
66   color[u]=GREY;
67   time++;
68   d[u]=time;
69
70   for(succ_iterator vl = succ_begin(u), 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     // We have a back-edge from BB --> u.
129     DEBUG (std::cerr << "Instrumenting back-edge from " << BB->getName ()
130                      << "-->" << u->getName () << "\n");
131     // Split the back-edge, inserting a new basic block on it, and modify the
132     // source BB's terminator accordingly.
133     BasicBlock *newBB = new BasicBlock("backEdgeInst", u->getParent());
134     BranchInst *ti = cast<BranchInst>(u->getTerminator());
135     unsigned char index = ((ti->getSuccessor(0) == BB) ? 0 : 1);
136
137     assert(ti->getNumSuccessors() > index && "Not enough successors!");
138     ti->setSuccessor(index, newBB);
139         
140     BasicBlock::InstListType &lt = newBB->getInstList();
141     lt.push_back(new CallInst(inCountMth));
142     new BranchInst(BB, newBB);
143       
144     // Now, set the sources of Phi nodes corresponding to the back-edge
145     // in BB to come from the instrumentation block instead.
146     for(BasicBlock::iterator BB2Inst = BB->begin(), BBend = BB->end(); 
147         BB2Inst != BBend; ++BB2Inst) {
148       if (PHINode *phiInst = dyn_cast<PHINode>(BB2Inst)) {
149         int bbIndex = phiInst->getBasicBlockIndex(u);
150         if (bbIndex>=0)
151           phiInst->setIncomingBlock(bbIndex, newBB);
152       }
153     }
154   }
155 }
156
157 bool InstLoops::doInitialization (Module &M) {
158   inCountMth = M.getOrInsertFunction("llvm_first_trigger", Type::VoidTy, 0);
159   return true;  // Module was modified.
160 }
161
162 /// runOnFunction - Entry point for FunctionPass that inserts calls to
163 /// trigger function.
164 ///
165 bool InstLoops::runOnFunction(Function &F){
166   if (F.isExternal ())
167     return false;
168
169   DS = &getAnalysis<DominatorSet> ();
170
171   // Add a call to reoptimizerInitialize() to beginning of function named main.
172   if (F.getName() == "main")
173     InsertProfilingInitCall (&F, "reoptimizerInitialize");
174
175   findAndInstrumentBackEdges(F);
176   return true;  // Function was modified.
177 }
178
179 } // End llvm namespace