860b57f7e4fcd7bdde0edc1e62cb6391630deba4
[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 "llvm/Support/Debug.h"
24 #include "llvm/Transforms/Instrumentation.h"
25 #include "../ProfilingUtils.h"
26
27 namespace llvm {
28
29 //this is used to color vertices
30 //during DFS
31
32 enum Color{
33   WHITE,
34   GREY,
35   BLACK
36 };
37
38 namespace {
39   typedef std::map<BasicBlock *, BasicBlock *> BBMap;
40   struct InstLoops : public FunctionPass {
41     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
42       AU.addRequired<DominatorSet>();
43     }
44   private:
45     Function *inCountMth;
46     DominatorSet *DS;
47     void getBackEdgesVisit(BasicBlock *u,
48                            std::map<BasicBlock *, Color > &color,
49                            std::map<BasicBlock *, int > &d,
50                            int &time, BBMap &be);
51     void removeRedundant(BBMap &be);
52     void findAndInstrumentBackEdges(Function &F);
53   public:
54     bool doInitialization(Module &M);
55     bool runOnFunction(Function &F);
56   };
57
58   RegisterOpt<InstLoops> X("instloops", "Instrument backedges for profiling");
59 }
60
61 //helper function to get back edges: it is called by
62 //the "getBackEdges" function below
63 void InstLoops::getBackEdgesVisit(BasicBlock *u,
64                        std::map<BasicBlock *, Color > &color,
65                        std::map<BasicBlock *, int > &d,
66                        int &time, BBMap &be) {
67   color[u]=GREY;
68   time++;
69   d[u]=time;
70
71   for(succ_iterator vl = succ_begin(u), ve = succ_end(u); vl != ve; ++vl){
72     BasicBlock *BB = *vl;
73
74     if(color[BB]!=GREY && color[BB]!=BLACK){
75       getBackEdgesVisit(BB, color, d, time, be);
76     }
77
78     //now checking for d and f vals
79     else if(color[BB]==GREY){
80       //so v is ancestor of u if time of u > time of v
81       if(d[u] >= d[BB]){
82         //u->BB is a backedge
83         be[u] = BB;
84       }
85     }
86   }
87   color[u]=BLACK;//done with visiting the node and its neighbors
88 }
89
90 //look at all BEs, and remove all BEs that are dominated by other BE's in the
91 //set
92 void InstLoops::removeRedundant(BBMap &be) {
93   std::vector<BasicBlock *> toDelete;
94   for(std::map<BasicBlock *, BasicBlock *>::iterator MI = be.begin(),
95         ME = be.end(); MI != ME; ++MI)
96     for(BBMap::iterator MMI = be.begin(), MME = be.end(); MMI != MME; ++MMI)
97       if(DS->properlyDominates(MI->first, MMI->first))
98         toDelete.push_back(MMI->first);
99   // Remove all the back-edges we found from be.
100   for(std::vector<BasicBlock *>::iterator VI = toDelete.begin(),
101         VE = toDelete.end(); VI != VE; ++VI)
102     be.erase(*VI);
103 }
104
105 //getting the backedges in a graph
106 //Its a variation of DFS to get the backedges in the graph
107 //We get back edges by associating a time
108 //and a color with each vertex.
109 //The time of a vertex is the time when it was first visited
110 //The color of a vertex is initially WHITE,
111 //Changes to GREY when it is first visited,
112 //and changes to BLACK when ALL its neighbors
113 //have been visited
114 //So we have a back edge when we meet a successor of
115 //a node with smaller time, and GREY color
116 void InstLoops::findAndInstrumentBackEdges(Function &F){
117   std::map<BasicBlock *, Color > color;
118   std::map<BasicBlock *, int> d;
119   BBMap be;
120   int time=0;
121   getBackEdgesVisit(F.begin(), color, d, time, be);
122
123   removeRedundant(be);
124
125   for(std::map<BasicBlock *, BasicBlock *>::iterator MI = be.begin(),
126         ME = be.end(); MI != ME; ++MI){
127     BasicBlock *u = MI->first;
128     BasicBlock *BB = MI->second;
129     // We have a back-edge from BB --> u.
130     DEBUG (std::cerr << "Instrumenting back-edge from " << BB->getName ()
131                      << "-->" << u->getName () << "\n");
132     // Split the back-edge, inserting a new basic block on it, and modify the
133     // source BB's terminator accordingly.
134     BasicBlock *newBB = new BasicBlock("backEdgeInst", u->getParent());
135     BranchInst *ti = cast<BranchInst>(u->getTerminator());
136     unsigned char index = ((ti->getSuccessor(0) == BB) ? 0 : 1);
137
138     assert(ti->getNumSuccessors() > index && "Not enough successors!");
139     ti->setSuccessor(index, newBB);
140
141     BasicBlock::InstListType &lt = newBB->getInstList();
142     lt.push_back(new CallInst(inCountMth));
143     new BranchInst(BB, newBB);
144
145     // Now, set the sources of Phi nodes corresponding to the back-edge
146     // in BB to come from the instrumentation block instead.
147     for(BasicBlock::iterator BB2Inst = BB->begin(), BBend = BB->end();
148         BB2Inst != BBend; ++BB2Inst) {
149       if (PHINode *phiInst = dyn_cast<PHINode>(BB2Inst)) {
150         int bbIndex = phiInst->getBasicBlockIndex(u);
151         if (bbIndex>=0)
152           phiInst->setIncomingBlock(bbIndex, newBB);
153       }
154     }
155   }
156 }
157
158 bool InstLoops::doInitialization (Module &M) {
159   inCountMth = M.getOrInsertFunction("llvm_first_trigger", Type::VoidTy, 0);
160   return true;  // Module was modified.
161 }
162
163 /// runOnFunction - Entry point for FunctionPass that inserts calls to
164 /// trigger function.
165 ///
166 bool InstLoops::runOnFunction(Function &F){
167   if (F.isExternal ())
168     return false;
169
170   DS = &getAnalysis<DominatorSet> ();
171
172   // Add a call to reoptimizerInitialize() to beginning of function named main.
173   if (F.getName() == "main")
174     InsertProfilingInitCall (&F, "reoptimizerInitialize");
175
176   findAndInstrumentBackEdges(F);
177   return true;  // Function was modified.
178 }
179
180 FunctionPass *createLoopInstrumentationPass () {
181   return new InstLoops();
182 }
183
184 } // End llvm namespace