Make error messages more useful than jsut an abort
[oota-llvm.git] / lib / Analysis / DataStructure / BottomUpClosure.cpp
1 //===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
2 //
3 // This file implements the BUDataStructures class, which represents the
4 // Bottom-Up Interprocedural closure of the data structure graph over the
5 // program.  This is useful for applications like pool allocation, but **not**
6 // applications like alias analysis.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Analysis/DataStructure.h"
11 #include "llvm/Analysis/DSGraph.h"
12 #include "llvm/Module.h"
13 #include "Support/Statistic.h"
14 #include "Support/hash_map"
15
16 namespace {
17   Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
18   
19   RegisterAnalysis<BUDataStructures>
20   X("budatastructure", "Bottom-up Data Structure Analysis Closure");
21 }
22
23 using namespace DS;
24
25 static bool isVAHackFn(const Function *F) {
26   return F->getName() == "printf"  || F->getName() == "sscanf" ||
27          F->getName() == "fprintf" || F->getName() == "open" ||
28          F->getName() == "sprintf" || F->getName() == "fputs" ||
29          F->getName() == "fscanf";
30 }
31
32 // isCompleteNode - Return true if we know all of the targets of this node, and
33 // if the call sites are not external.
34 //
35 static inline bool isCompleteNode(DSNode *N) {
36   if (N->NodeType & DSNode::Incomplete) return false;
37   const std::vector<GlobalValue*> &Callees = N->getGlobals();
38   for (unsigned i = 0, e = Callees.size(); i != e; ++i)
39     if (Callees[i]->isExternal())
40       if (!isVAHackFn(cast<Function>(Callees[i])))
41         return false;  // External function found...
42   return true;  // otherwise ok
43 }
44
45 struct CallSiteIterator {
46   // FCs are the edges out of the current node are the call site targets...
47   std::vector<DSCallSite> *FCs;
48   unsigned CallSite;
49   unsigned CallSiteEntry;
50
51   CallSiteIterator(std::vector<DSCallSite> &CS) : FCs(&CS) {
52     CallSite = 0; CallSiteEntry = 0;
53     advanceToValidCallee();
54   }
55
56   // End iterator ctor...
57   CallSiteIterator(std::vector<DSCallSite> &CS, bool) : FCs(&CS) {
58     CallSite = FCs->size(); CallSiteEntry = 0;
59   }
60
61   void advanceToValidCallee() {
62     while (CallSite < FCs->size()) {
63       if ((*FCs)[CallSite].isDirectCall()) {
64         if (CallSiteEntry == 0 &&        // direct call only has one target...
65             (!(*FCs)[CallSite].getCalleeFunc()->isExternal() ||
66              isVAHackFn((*FCs)[CallSite].getCalleeFunc()))) // If not external
67           return;
68       } else {
69         DSNode *CalleeNode = (*FCs)[CallSite].getCalleeNode();
70         if (CallSiteEntry || isCompleteNode(CalleeNode)) {
71           const std::vector<GlobalValue*> &Callees = CalleeNode->getGlobals();
72           
73           if (CallSiteEntry < Callees.size())
74             return;
75         }
76       }
77       CallSiteEntry = 0;
78       ++CallSite;
79     }
80   }
81 public:
82   static CallSiteIterator begin(DSGraph &G) { return G.getAuxFunctionCalls(); }
83   static CallSiteIterator end(DSGraph &G) {
84     return CallSiteIterator(G.getAuxFunctionCalls(), true);
85   }
86   static CallSiteIterator begin(std::vector<DSCallSite> &CSs) { return CSs; }
87   static CallSiteIterator end(std::vector<DSCallSite> &CSs) {
88     return CallSiteIterator(CSs, true);
89   }
90   bool operator==(const CallSiteIterator &CSI) const {
91     return CallSite == CSI.CallSite && CallSiteEntry == CSI.CallSiteEntry;
92   }
93   bool operator!=(const CallSiteIterator &CSI) const { return !operator==(CSI);}
94
95   unsigned getCallSiteIdx() const { return CallSite; }
96   DSCallSite &getCallSite() const { return (*FCs)[CallSite]; }
97
98   Function *operator*() const {
99     if ((*FCs)[CallSite].isDirectCall()) {
100       return (*FCs)[CallSite].getCalleeFunc();
101     } else {
102       DSNode *Node = (*FCs)[CallSite].getCalleeNode();
103       return cast<Function>(Node->getGlobals()[CallSiteEntry]);
104     }
105   }
106
107   CallSiteIterator& operator++() {                // Preincrement
108     ++CallSiteEntry;
109     advanceToValidCallee();
110     return *this;
111   }
112   CallSiteIterator operator++(int) { // Postincrement
113     CallSiteIterator tmp = *this; ++*this; return tmp; 
114   }
115 };
116
117
118
119 // run - Calculate the bottom up data structure graphs for each function in the
120 // program.
121 //
122 bool BUDataStructures::run(Module &M) {
123   GlobalsGraph = new DSGraph();
124   GlobalsGraph->setPrintAuxCalls();
125
126   Function *MainFunc = M.getMainFunction();
127   if (MainFunc)
128     calculateReachableGraphs(MainFunc);
129
130   // Calculate the graphs for any functions that are unreachable from main...
131   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
132     if (!I->isExternal() && DSInfo.find(I) == DSInfo.end()) {
133 #ifndef NDEBUG
134       if (MainFunc)
135         std::cerr << "*** Function unreachable from main: "
136                   << I->getName() << "\n";
137 #endif
138       calculateReachableGraphs(I);    // Calculate all graphs...
139     }
140   return false;
141 }
142
143 void BUDataStructures::calculateReachableGraphs(Function *F) {
144   std::vector<Function*> Stack;
145   hash_map<Function*, unsigned> ValMap;
146   unsigned NextID = 1;
147   calculateGraphs(F, Stack, NextID, ValMap);
148 }
149
150 DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
151   // Has the graph already been created?
152   DSGraph *&Graph = DSInfo[F];
153   if (Graph) return *Graph;
154
155   // Copy the local version into DSInfo...
156   Graph = new DSGraph(getAnalysis<LocalDataStructures>().getDSGraph(*F));
157
158   Graph->setGlobalsGraph(GlobalsGraph);
159   Graph->setPrintAuxCalls();
160
161   // Start with a copy of the original call sites...
162   Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
163   return *Graph;
164 }
165
166 unsigned BUDataStructures::calculateGraphs(Function *F,
167                                            std::vector<Function*> &Stack,
168                                            unsigned &NextID, 
169                                      hash_map<Function*, unsigned> &ValMap) {
170   assert(ValMap.find(F) == ValMap.end() && "Shouldn't revisit functions!");
171   unsigned Min = NextID++, MyID = Min;
172   ValMap[F] = Min;
173   Stack.push_back(F);
174
175   if (F->isExternal()) {   // sprintf, fprintf, sscanf, etc...
176     // No callees!
177     Stack.pop_back();
178     ValMap[F] = ~0;
179     return Min;
180   }
181
182   DSGraph &Graph = getOrCreateGraph(F);
183
184   // The edges out of the current node are the call site targets...
185   for (CallSiteIterator I = CallSiteIterator::begin(Graph),
186          E = CallSiteIterator::end(Graph); I != E; ++I) {
187     Function *Callee = *I;
188     unsigned M;
189     // Have we visited the destination function yet?
190     hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
191     if (It == ValMap.end())  // No, visit it now.
192       M = calculateGraphs(Callee, Stack, NextID, ValMap);
193     else                    // Yes, get it's number.
194       M = It->second;
195     if (M < Min) Min = M;
196   }
197
198   assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
199   if (Min != MyID)
200     return Min;         // This is part of a larger SCC!
201
202   // If this is a new SCC, process it now.
203   if (Stack.back() == F) {           // Special case the single "SCC" case here.
204     DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
205                     << F->getName() << "\n");
206     Stack.pop_back();
207     DSGraph &G = calculateGraph(*F);
208
209     if (MaxSCC < 1) MaxSCC = 1;
210
211     // Should we revisit the graph?
212     if (CallSiteIterator::begin(G) != CallSiteIterator::end(G)) {
213       ValMap.erase(F);
214       return calculateGraphs(F, Stack, NextID, ValMap);
215     } else {
216       ValMap[F] = ~0U;
217     }
218     return MyID;
219
220   } else {
221     // SCCFunctions - Keep track of the functions in the current SCC
222     //
223     hash_set<Function*> SCCFunctions;
224
225     Function *NF;
226     std::vector<Function*>::iterator FirstInSCC = Stack.end();
227     do {
228       NF = *--FirstInSCC;
229       ValMap[NF] = ~0U;
230       SCCFunctions.insert(NF);
231     } while (NF != F);
232
233     std::cerr << "Identified SCC #: " << MyID << " of size: "
234               << (Stack.end()-FirstInSCC) << "\n";
235
236     // Compute the Max SCC Size...
237     if (MaxSCC < unsigned(Stack.end()-FirstInSCC))
238       MaxSCC = Stack.end()-FirstInSCC;
239
240     std::vector<Function*>::iterator I = Stack.end();
241     do {
242       --I;
243 #ifndef NDEBUG
244       /*DEBUG*/(std::cerr << "  Fn #" << (Stack.end()-I) << "/"
245             << (Stack.end()-FirstInSCC) << " in SCC: "
246             << (*I)->getName());
247       DSGraph &G = getDSGraph(**I);
248       std::cerr << " [" << G.getGraphSize() << "+"
249                 << G.getAuxFunctionCalls().size() << "] ";
250 #endif
251
252       // Eliminate all call sites in the SCC that are not to functions that are
253       // in the SCC.
254       inlineNonSCCGraphs(**I, SCCFunctions);
255
256 #ifndef NDEBUG
257       std::cerr << "after Non-SCC's [" << G.getGraphSize() << "+"
258                 << G.getAuxFunctionCalls().size() << "]\n";
259 #endif
260     } while (I != FirstInSCC);
261
262     I = Stack.end();
263     do {
264       --I;
265 #ifndef NDEBUG
266       /*DEBUG*/(std::cerr << "  Fn #" << (Stack.end()-I) << "/"
267             << (Stack.end()-FirstInSCC) << " in SCC: "
268             << (*I)->getName());
269       DSGraph &G = getDSGraph(**I);
270       std::cerr << " [" << G.getGraphSize() << "+"
271                 << G.getAuxFunctionCalls().size() << "] ";
272 #endif
273       // Inline all graphs into the SCC nodes...
274       calculateSCCGraph(**I, SCCFunctions);
275
276 #ifndef NDEBUG
277       std::cerr << "after [" << G.getGraphSize() << "+"
278                 << G.getAuxFunctionCalls().size() << "]\n";
279 #endif
280     } while (I != FirstInSCC);
281
282
283     std::cerr << "DONE with SCC #: " << MyID << "\n";
284
285     // We never have to revisit "SCC" processed functions...
286     
287     // Drop the stuff we don't need from the end of the stack
288     Stack.erase(FirstInSCC, Stack.end());
289     return MyID;
290   }
291
292   return MyID;  // == Min
293 }
294
295
296 // releaseMemory - If the pass pipeline is done with this pass, we can release
297 // our memory... here...
298 //
299 void BUDataStructures::releaseMemory() {
300   for (hash_map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
301          E = DSInfo.end(); I != E; ++I)
302     delete I->second;
303
304   // Empty map so next time memory is released, data structures are not
305   // re-deleted.
306   DSInfo.clear();
307   delete GlobalsGraph;
308   GlobalsGraph = 0;
309 }
310
311 DSGraph &BUDataStructures::calculateGraph(Function &F) {
312   DSGraph &Graph = getDSGraph(F);
313   DEBUG(std::cerr << "  [BU] Calculating graph for: " << F.getName() << "\n");
314
315   // Move our call site list into TempFCs so that inline call sites go into the
316   // new call site list and doesn't invalidate our iterators!
317   std::vector<DSCallSite> TempFCs;
318   std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
319   TempFCs.swap(AuxCallsList);
320
321   // Loop over all of the resolvable call sites
322   unsigned LastCallSiteIdx = ~0U;
323   for (CallSiteIterator I = CallSiteIterator::begin(TempFCs),
324          E = CallSiteIterator::end(TempFCs); I != E; ++I) {
325     // If we skipped over any call sites, they must be unresolvable, copy them
326     // to the real call site list.
327     LastCallSiteIdx++;
328     for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
329       AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
330     LastCallSiteIdx = I.getCallSiteIdx();
331     
332     // Resolve the current call...
333     Function *Callee = *I;
334     DSCallSite &CS = I.getCallSite();
335
336     if (Callee->isExternal()) {
337       // Ignore this case, simple varargs functions we cannot stub out!
338     } else if (Callee == &F) {
339       // Self recursion... simply link up the formal arguments with the
340       // actual arguments...
341       DEBUG(std::cerr << "    Self Inlining: " << F.getName() << "\n");
342
343       // Handle self recursion by resolving the arguments and return value
344       Graph.mergeInGraph(CS, Graph, 0);
345
346     } else {
347       // Get the data structure graph for the called function.
348       //
349       DSGraph &GI = getDSGraph(*Callee);  // Graph to inline
350       
351       DEBUG(std::cerr << "    Inlining graph for " << Callee->getName()
352             << "[" << GI.getGraphSize() << "+"
353             << GI.getAuxFunctionCalls().size() << "] into: " << F.getName()
354             << "[" << Graph.getGraphSize() << "+"
355             << Graph.getAuxFunctionCalls().size() << "]\n");
356 #if 0
357       Graph.writeGraphToFile(std::cerr, "bu_" + F.getName() + "_before_" +
358                              Callee->getName());
359 #endif
360       
361       // Handle self recursion by resolving the arguments and return value
362       Graph.mergeInGraph(CS, GI,
363                          DSGraph::KeepModRefBits | 
364                          DSGraph::StripAllocaBit | DSGraph::DontCloneCallNodes);
365
366 #if 0
367       Graph.writeGraphToFile(std::cerr, "bu_" + F.getName() + "_after_" +
368                              Callee->getName());
369 #endif
370     }
371   }
372
373   // Make sure to catch any leftover unresolvable calls...
374   for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
375     AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
376
377   TempFCs.clear();
378
379   // Recompute the Incomplete markers.  If there are any function calls left
380   // now that are complete, we must loop!
381   Graph.maskIncompleteMarkers();
382   Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
383   // FIXME: materialize nodes from the globals graph as neccesary...
384   Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
385
386   DEBUG(std::cerr << "  [BU] Done inlining: " << F.getName() << " ["
387         << Graph.getGraphSize() << "+" << Graph.getAuxFunctionCalls().size()
388         << "]\n");
389
390   //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
391
392   return Graph;
393 }
394
395
396 // inlineNonSCCGraphs - This method is almost like the other two calculate graph
397 // methods.  This one is used to inline function graphs (from functions outside
398 // of the SCC) into functions in the SCC.  It is not supposed to touch functions
399 // IN the SCC at all.
400 //
401 DSGraph &BUDataStructures::inlineNonSCCGraphs(Function &F,
402                                              hash_set<Function*> &SCCFunctions){
403   DSGraph &Graph = getDSGraph(F);
404   DEBUG(std::cerr << "  [BU] Inlining Non-SCC graphs for: "
405                   << F.getName() << "\n");
406
407   // Move our call site list into TempFCs so that inline call sites go into the
408   // new call site list and doesn't invalidate our iterators!
409   std::vector<DSCallSite> TempFCs;
410   std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
411   TempFCs.swap(AuxCallsList);
412
413   // Loop over all of the resolvable call sites
414   unsigned LastCallSiteIdx = ~0U;
415   for (CallSiteIterator I = CallSiteIterator::begin(TempFCs),
416          E = CallSiteIterator::end(TempFCs); I != E; ++I) {
417     // If we skipped over any call sites, they must be unresolvable, copy them
418     // to the real call site list.
419     LastCallSiteIdx++;
420     for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
421       AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
422     LastCallSiteIdx = I.getCallSiteIdx();
423     
424     // Resolve the current call...
425     Function *Callee = *I;
426     DSCallSite &CS = I.getCallSite();
427
428     if (Callee->isExternal()) {
429       // Ignore this case, simple varargs functions we cannot stub out!
430     } else if (SCCFunctions.count(Callee)) {
431       // Calling a function in the SCC, ignore it for now!
432       DEBUG(std::cerr << "    SCC CallSite for: " << Callee->getName() << "\n");
433       AuxCallsList.push_back(CS);
434     } else {
435       // Get the data structure graph for the called function.
436       //
437       DSGraph &GI = getDSGraph(*Callee);  // Graph to inline
438
439       DEBUG(std::cerr << "    Inlining graph for " << Callee->getName()
440             << "[" << GI.getGraphSize() << "+"
441             << GI.getAuxFunctionCalls().size() << "] into: " << F.getName()
442             << "[" << Graph.getGraphSize() << "+"
443             << Graph.getAuxFunctionCalls().size() << "]\n");
444
445       // Handle self recursion by resolving the arguments and return value
446       Graph.mergeInGraph(CS, GI,
447                          DSGraph::KeepModRefBits | DSGraph::StripAllocaBit |
448                          DSGraph::DontCloneCallNodes);
449     }
450   }
451
452   // Make sure to catch any leftover unresolvable calls...
453   for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
454     AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
455
456   TempFCs.clear();
457
458   // Recompute the Incomplete markers.  If there are any function calls left
459   // now that are complete, we must loop!
460   Graph.maskIncompleteMarkers();
461   Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
462   Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
463
464   DEBUG(std::cerr << "  [BU] Done Non-SCC inlining: " << F.getName() << " ["
465         << Graph.getGraphSize() << "+" << Graph.getAuxFunctionCalls().size()
466         << "]\n");
467   //Graph.writeGraphToFile(std::cerr, "nscc_" + F.getName());
468   return Graph;
469 }
470
471
472 DSGraph &BUDataStructures::calculateSCCGraph(Function &F,
473                                              hash_set<Function*> &SCCFunctions){
474   DSGraph &Graph = getDSGraph(F);
475   DEBUG(std::cerr << "  [BU] Calculating SCC graph for: " << F.getName()<<"\n");
476
477   std::vector<DSCallSite> UnresolvableCalls;
478   hash_map<Function*, DSCallSite> SCCCallSiteMap;
479   std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
480
481   while (1) {  // Loop until we run out of resolvable call sites!
482     // Move our call site list into TempFCs so that inline call sites go into
483     // the new call site list and doesn't invalidate our iterators!
484     std::vector<DSCallSite> TempFCs;
485     TempFCs.swap(AuxCallsList);
486
487     // Loop over all of the resolvable call sites
488     unsigned LastCallSiteIdx = ~0U;
489     CallSiteIterator I = CallSiteIterator::begin(TempFCs),
490       E = CallSiteIterator::end(TempFCs);
491     if (I == E) {
492       TempFCs.swap(AuxCallsList);
493       break;  // Done when no resolvable call sites exist
494     }
495
496     for (; I != E; ++I) {
497       // If we skipped over any call sites, they must be unresolvable, copy them
498       // to the unresolvable site list.
499       LastCallSiteIdx++;
500       for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
501         UnresolvableCalls.push_back(TempFCs[LastCallSiteIdx]);
502       LastCallSiteIdx = I.getCallSiteIdx();
503       
504       // Resolve the current call...
505       Function *Callee = *I;
506       DSCallSite &CS = I.getCallSite();
507       
508       if (Callee->isExternal()) {
509         // Ignore this case, simple varargs functions we cannot stub out!
510       } else if (Callee == &F) {
511         // Self recursion... simply link up the formal arguments with the
512         // actual arguments...
513         DEBUG(std::cerr << "    Self Inlining: " << F.getName() << "\n");
514         
515         // Handle self recursion by resolving the arguments and return value
516         Graph.mergeInGraph(CS, Graph, 0);
517       } else if (SCCCallSiteMap.count(Callee)) {
518         // We have already seen a call site in the SCC for this function, just
519         // merge the two call sites together and we are done.
520         SCCCallSiteMap.find(Callee)->second.mergeWith(CS);
521       } else {
522         // Get the data structure graph for the called function.
523         //
524         DSGraph &GI = getDSGraph(*Callee);  // Graph to inline
525         DEBUG(std::cerr << "    Inlining graph for " << Callee->getName()
526               << "[" << GI.getGraphSize() << "+"
527               << GI.getAuxFunctionCalls().size() << "] into: " << F.getName()
528               << "[" << Graph.getGraphSize() << "+"
529               << Graph.getAuxFunctionCalls().size() << "]\n");
530         
531         // Handle self recursion by resolving the arguments and return value
532         Graph.mergeInGraph(CS, GI,
533                            DSGraph::KeepModRefBits | DSGraph::StripAllocaBit |
534                            DSGraph::DontCloneCallNodes);
535
536         if (SCCFunctions.count(Callee))
537           SCCCallSiteMap.insert(std::make_pair(Callee, CS));
538       }
539     }
540     
541     // Make sure to catch any leftover unresolvable calls...
542     for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
543       UnresolvableCalls.push_back(TempFCs[LastCallSiteIdx]);
544   }
545
546   // Reset the SCCCallSiteMap...
547   SCCCallSiteMap.clear();
548
549   AuxCallsList.insert(AuxCallsList.end(), UnresolvableCalls.begin(),
550                       UnresolvableCalls.end());
551   UnresolvableCalls.clear();
552
553
554   // Recompute the Incomplete markers.  If there are any function calls left
555   // now that are complete, we must loop!
556   Graph.maskIncompleteMarkers();
557   Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
558
559   // FIXME: materialize nodes from the globals graph as neccesary...
560
561   Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
562
563   DEBUG(std::cerr << "  [BU] Done inlining: " << F.getName() << " ["
564         << Graph.getGraphSize() << "+" << Graph.getAuxFunctionCalls().size()
565         << "]\n");
566   //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
567   return Graph;
568 }