Add new linkage types to support a real frontend
[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/Utils/UnifyFunctionExitNodes.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Constants.h"
30 #include "llvm/DerivedTypes.h"
31 #include "llvm/iMemory.h"
32 #include "llvm/Module.h"
33 #include "Graph.h"
34 #include <fstream>
35
36 using std::vector;
37
38 struct ProfilePaths : public FunctionPass {
39   bool runOnFunction(Function &F);
40
41   // Before this pass, make sure that there is only one 
42   // entry and only one exit node for the function in the CFG of the function
43   //
44   void ProfilePaths::getAnalysisUsage(AnalysisUsage &AU) const {
45     AU.addRequired<UnifyFunctionExitNodes>();
46   }
47 };
48
49 static RegisterOpt<ProfilePaths> X("paths", "Profile Paths");
50
51 static Node *findBB(std::vector<Node *> &st, BasicBlock *BB){
52   for(std::vector<Node *>::iterator si=st.begin(); si!=st.end(); ++si){
53     if(((*si)->getElement())==BB){
54       return *si;
55     }
56   }
57   return NULL;
58 }
59
60 //Per function pass for inserting counters and trigger code
61 bool ProfilePaths::runOnFunction(Function &F){
62
63   static int mn = -1;
64
65   if(F.isExternal()) {
66     return false;
67   }
68  
69   //increment counter for instrumented functions. mn is now function#
70   mn++;
71   
72   // Transform the cfg s.t. we have just one exit node
73   BasicBlock *ExitNode = getAnalysis<UnifyFunctionExitNodes>().getExitNode();  
74
75   //iterating over BBs and making graph
76   std::vector<Node *> nodes;
77   std::vector<Edge> edges;
78
79   Node *tmp;
80   Node *exitNode = 0, *startNode = 0;
81
82   // The nodes must be uniquesly identified:
83   // That is, no two nodes must hav same BB*
84   
85   for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE; ++BB) {
86     Node *nd=new Node(BB);
87     nodes.push_back(nd); 
88     if(&*BB == ExitNode)
89       exitNode=nd;
90     if(&*BB==F.begin())
91       startNode=nd;
92   }
93
94   // now do it againto insert edges
95   for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE; ++BB){
96     Node *nd=findBB(nodes, BB);
97     assert(nd && "No node for this edge!");
98
99     for(BasicBlock::succ_iterator s=succ_begin(BB), se=succ_end(BB); 
100         s!=se; ++s){
101       Node *nd2=findBB(nodes,*s);
102       assert(nd2 && "No node for this edge!");
103       Edge ed(nd,nd2,0);
104       edges.push_back(ed);
105     }
106   }
107   
108   Graph g(nodes,edges, startNode, exitNode);
109
110 #ifdef DEBUG_PATH_PROFILES  
111   std::cerr<<"Original graph\n";
112   printGraph(g);
113 #endif
114
115   BasicBlock *fr = &F.front();
116   
117   // The graph is made acyclic: this is done
118   // by removing back edges for now, and adding them later on
119   vector<Edge> be;
120   std::map<Node *, int> nodePriority; //it ranks nodes in depth first order traversal
121   g.getBackEdges(be, nodePriority);
122   
123 #ifdef DEBUG_PATH_PROFILES
124   std::cerr<<"BackEdges-------------\n";
125   for(vector<Edge>::iterator VI=be.begin(); VI!=be.end(); ++VI){
126     printEdge(*VI);
127     cerr<<"\n";
128   }
129   std::cerr<<"------\n";
130 #endif
131
132 #ifdef DEBUG_PATH_PROFILES
133   cerr<<"Backedges:"<<be.size()<<endl;
134 #endif
135   //Now we need to reflect the effect of back edges
136   //This is done by adding dummy edges
137   //If a->b is a back edge
138   //Then we add 2 back edges for it:
139   //1. from root->b (in vector stDummy)
140   //and 2. from a->exit (in vector exDummy)
141   vector<Edge> stDummy;
142   vector<Edge> exDummy;
143   addDummyEdges(stDummy, exDummy, g, be);
144
145 #ifdef DEBUG_PATH_PROFILES
146   std::cerr<<"After adding dummy edges\n";
147   printGraph(g);
148 #endif
149
150   // Now, every edge in the graph is assigned a weight
151   // This weight later adds on to assign path
152   // numbers to different paths in the graph
153   //  All paths for now are acyclic,
154   // since no back edges in the graph now
155   // numPaths is the number of acyclic paths in the graph
156   int numPaths=valueAssignmentToEdges(g, nodePriority, be);
157
158   //if(numPaths<=1) return false;
159
160   if(numPaths<=1 || numPaths >5000) return false;
161   
162 #ifdef DEBUG_PATH_PROFILES  
163   printGraph(g);
164 #endif
165
166   //create instruction allocation r and count
167   //r is the variable that'll act like an accumulator
168   //all along the path, we just add edge values to r
169   //and at the end, r reflects the path number
170   //count is an array: count[x] would store
171   //the number of executions of path numbered x
172
173   Instruction *rVar=new 
174     AllocaInst(Type::IntTy, 
175                ConstantUInt::get(Type::UIntTy,1),"R");
176
177   //Instruction *countVar=new 
178   //AllocaInst(Type::IntTy, 
179   //           ConstantUInt::get(Type::UIntTy, numPaths), "Count");
180
181   //initialize counter array!
182   std::vector<Constant*> arrayInitialize;
183   for(int xi=0; xi<numPaths; xi++)
184     arrayInitialize.push_back(ConstantSInt::get(Type::IntTy, 0));
185
186   const ArrayType *ATy = ArrayType::get(Type::IntTy, numPaths);
187   Constant *initializer =  ConstantArray::get(ATy, arrayInitialize);
188   GlobalVariable *countVar = new GlobalVariable(ATy, false,
189                                                 GlobalValue::InternalLinkage, 
190                                                 initializer, "Count",
191                                                 F.getParent());
192   static GlobalVariable *threshold = NULL;
193   static bool insertedThreshold = false;
194
195   if(!insertedThreshold){
196     threshold = new GlobalVariable(Type::IntTy, false,
197                                    GlobalValue::ExternalLinkage, 0,
198                                    "reopt_threshold");
199
200     F.getParent()->getGlobalList().push_back(threshold);
201     insertedThreshold = true;
202   }
203
204   assert(threshold && "GlobalVariable threshold not defined!");
205
206   // insert initialization code in first (entry) BB
207   // this includes initializing r and count
208   insertInTopBB(&F.getEntryNode(),numPaths, rVar, threshold);
209     
210   //now process the graph: get path numbers,
211   //get increments along different paths,
212   //and assign "increments" and "updates" (to r and count)
213   //"optimally". Finally, insert llvm code along various edges
214   processGraph(g, rVar, countVar, be, stDummy, exDummy, numPaths, mn, 
215                threshold);    
216    
217   return true;  // Always modifies function
218 }