cd341920a5518384ce5f9d70432ba6efb1298a64
[oota-llvm.git] / lib / Transforms / Instrumentation / ProfilePaths / ProfilePaths.cpp
1 //===-- ProfilePaths.cpp - interface to insert instrumentation ---*- C++ -*--=//
2 //
3 // This inserts intrumentation for counting
4 // execution of paths though a given function
5 // Its implemented as a "Function" Pass, and called using opt
6 //
7 // This pass is implemented by using algorithms similar to 
8 // 1."Efficient Path Profiling": Ball, T. and Larus, J. R., 
9 // Proceedings of Micro-29, Dec 1996, Paris, France.
10 // 2."Efficiently Counting Program events with support for on-line
11 //   "queries": Ball T., ACM Transactions on Programming Languages
12 //   and systems, Sep 1994.
13 //
14 // The algorithms work on a Graph constructed over the nodes
15 // made from Basic Blocks: The transformations then take place on
16 // the constucted graph (implementation in Graph.cpp and GraphAuxillary.cpp)
17 // and finally, appropriate instrumentation is placed over suitable edges.
18 // (code inserted through EdgeCode.cpp).
19 // 
20 // The algorithm inserts code such that every acyclic path in the CFG
21 // of a function is identified through a unique number. the code insertion
22 // is optimal in the sense that its inserted over a minimal set of edges. Also,
23 // the algorithm makes sure than initialization, path increment and counter
24 // update can be collapsed into minimum number of edges.
25 //===----------------------------------------------------------------------===//
26
27 #include "llvm/Transforms/Instrumentation/ProfilePaths.h"
28 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
29 #include "llvm/Support/CFG.h"
30 #include "llvm/Constants.h"
31 #include "llvm/DerivedTypes.h"
32 #include "llvm/iMemory.h"
33 #include "llvm/Transforms/Instrumentation/Graph.h"
34 #include <iostream>
35 #include <fstream>
36
37 using std::vector;
38
39 struct ProfilePaths : public FunctionPass {
40   bool runOnFunction(Function &F);
41
42   // Before this pass, make sure that there is only one 
43   // entry and only one exit node for the function in the CFG of the function
44   //
45   void ProfilePaths::getAnalysisUsage(AnalysisUsage &AU) const {
46     AU.addRequired<UnifyFunctionExitNodes>();
47   }
48 };
49
50 static RegisterOpt<ProfilePaths> X("paths", "Profile Paths");
51
52 // createProfilePathsPass - Create a new pass to add path profiling
53 //
54 Pass *createProfilePathsPass() {
55   return new ProfilePaths();
56 }
57
58
59 static Node *findBB(std::vector<Node *> &st, BasicBlock *BB){
60   for(std::vector<Node *>::iterator si=st.begin(); si!=st.end(); ++si){
61     if(((*si)->getElement())==BB){
62       return *si;
63     }
64   }
65   return NULL;
66 }
67
68 //Per function pass for inserting counters and trigger code
69 bool ProfilePaths::runOnFunction(Function &F){
70
71   static int mn = -1;
72
73   if(F.isExternal()) {
74     return false;
75   }
76  
77   //increment counter for instrumented functions. mn is now function#
78   mn++;
79   
80   // Transform the cfg s.t. we have just one exit node
81   BasicBlock *ExitNode = getAnalysis<UnifyFunctionExitNodes>().getExitNode();  
82
83   //iterating over BBs and making graph
84   std::vector<Node *> nodes;
85   std::vector<Edge> edges;
86
87   Node *tmp;
88   Node *exitNode, *startNode;
89
90   // The nodes must be uniquesly identified:
91   // That is, no two nodes must hav same BB*
92   
93   for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE; ++BB) {
94     Node *nd=new Node(BB);
95     nodes.push_back(nd); 
96     if(&*BB == ExitNode)
97       exitNode=nd;
98     if(&*BB==F.begin())
99       startNode=nd;
100   }
101
102   // now do it againto insert edges
103   for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE; ++BB){
104     Node *nd=findBB(nodes, BB);
105     assert(nd && "No node for this edge!");
106
107     for(BasicBlock::succ_iterator s=succ_begin(BB), se=succ_end(BB); 
108         s!=se; ++s){
109       Node *nd2=findBB(nodes,*s);
110       assert(nd2 && "No node for this edge!");
111       Edge ed(nd,nd2,0);
112       edges.push_back(ed);
113     }
114   }
115   
116   Graph g(nodes,edges, startNode, exitNode);
117
118 #ifdef DEBUG_PATH_PROFILES  
119   std::cerr<<"Original graph\n";
120   printGraph(g);
121 #endif
122
123   BasicBlock *fr = &F.front();
124   
125   // The graph is made acyclic: this is done
126   // by removing back edges for now, and adding them later on
127   vector<Edge> be;
128   std::map<Node *, int> nodePriority; //it ranks nodes in depth first order traversal
129   g.getBackEdges(be, nodePriority);
130   
131 #ifdef DEBUG_PATH_PROFILES
132   std::cerr<<"BackEdges-------------\n";
133   for(vector<Edge>::iterator VI=be.begin(); VI!=be.end(); ++VI){
134     printEdge(*VI);
135     cerr<<"\n";
136   }
137   std::cerr<<"------\n";
138 #endif
139
140 #ifdef DEBUG_PATH_PROFILES
141   cerr<<"Backedges:"<<be.size()<<endl;
142 #endif
143   //Now we need to reflect the effect of back edges
144   //This is done by adding dummy edges
145   //If a->b is a back edge
146   //Then we add 2 back edges for it:
147   //1. from root->b (in vector stDummy)
148   //and 2. from a->exit (in vector exDummy)
149   vector<Edge> stDummy;
150   vector<Edge> exDummy;
151   addDummyEdges(stDummy, exDummy, g, be);
152
153 #ifdef DEBUG_PATH_PROFILES
154   std::cerr<<"After adding dummy edges\n";
155   printGraph(g);
156 #endif
157
158   // Now, every edge in the graph is assigned a weight
159   // This weight later adds on to assign path
160   // numbers to different paths in the graph
161   //  All paths for now are acyclic,
162   // since no back edges in the graph now
163   // numPaths is the number of acyclic paths in the graph
164   int numPaths=valueAssignmentToEdges(g, nodePriority, be);
165
166   if(numPaths<=1 || numPaths >5000) return false;
167   
168 #ifdef DEBUG_PATH_PROFILES  
169   printGraph(g);
170 #endif
171
172   //create instruction allocation r and count
173   //r is the variable that'll act like an accumulator
174   //all along the path, we just add edge values to r
175   //and at the end, r reflects the path number
176   //count is an array: count[x] would store
177   //the number of executions of path numbered x
178
179   Instruction *rVar=new 
180     AllocaInst(Type::IntTy, 
181                ConstantUInt::get(Type::UIntTy,1),"R");
182
183   Instruction *countVar=new 
184     AllocaInst(Type::IntTy, 
185                ConstantUInt::get(Type::UIntTy, numPaths), "Count");
186   
187   // insert initialization code in first (entry) BB
188   // this includes initializing r and count
189   insertInTopBB(&F.getEntryNode(),numPaths, rVar, countVar);
190     
191   //now process the graph: get path numbers,
192   //get increments along different paths,
193   //and assign "increments" and "updates" (to r and count)
194   //"optimally". Finally, insert llvm code along various edges
195   processGraph(g, rVar, countVar, be, stDummy, exDummy, numPaths, mn);    
196    
197   return true;  // Always modifies function
198 }