remove the second argument to cloneInto
[oota-llvm.git] / lib / Analysis / DataStructure / BottomUpClosure.cpp
1 //===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
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 file implements the BUDataStructures class, which represents the
11 // Bottom-Up Interprocedural closure of the data structure graph over the
12 // program.  This is useful for applications like pool allocation, but **not**
13 // applications like alias analysis.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/DataStructure/DataStructure.h"
18 #include "llvm/Analysis/DataStructure/DSGraph.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Support/Debug.h"
22 using namespace llvm;
23
24 namespace {
25   Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
26   Statistic<> NumBUInlines("budatastructures", "Number of graphs inlined");
27   Statistic<> NumCallEdges("budatastructures", "Number of 'actual' call edges");
28   
29   RegisterAnalysis<BUDataStructures>
30   X("budatastructure", "Bottom-up Data Structure Analysis");
31 }
32
33 // run - Calculate the bottom up data structure graphs for each function in the
34 // program.
35 //
36 bool BUDataStructures::runOnModule(Module &M) {
37   LocalDataStructures &LocalDSA = getAnalysis<LocalDataStructures>();
38   GlobalECs = LocalDSA.getGlobalECs();
39
40   GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph(), GlobalECs);
41   GlobalsGraph->setPrintAuxCalls();
42
43   IndCallGraphMap = new std::map<std::vector<Function*>,
44                            std::pair<DSGraph*, std::vector<DSNodeHandle> > >();
45
46   std::vector<Function*> Stack;
47   hash_map<Function*, unsigned> ValMap;
48   unsigned NextID = 1;
49
50   Function *MainFunc = M.getMainFunction();
51   if (MainFunc)
52     calculateGraphs(MainFunc, Stack, NextID, ValMap);
53
54   // Calculate the graphs for any functions that are unreachable from main...
55   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
56     if (!I->isExternal() && !DSInfo.count(I)) {
57 #ifndef NDEBUG
58       if (MainFunc)
59         std::cerr << "*** Function unreachable from main: "
60                   << I->getName() << "\n";
61 #endif
62       calculateGraphs(I, Stack, NextID, ValMap);     // Calculate all graphs.
63     }
64
65   NumCallEdges += ActualCallees.size();
66
67   // If we computed any temporary indcallgraphs, free them now.
68   for (std::map<std::vector<Function*>,
69          std::pair<DSGraph*, std::vector<DSNodeHandle> > >::iterator I =
70          IndCallGraphMap->begin(), E = IndCallGraphMap->end(); I != E; ++I) {
71     I->second.second.clear();  // Drop arg refs into the graph.
72     delete I->second.first;
73   }
74   delete IndCallGraphMap;
75
76   // At the end of the bottom-up pass, the globals graph becomes complete.
77   // FIXME: This is not the right way to do this, but it is sorta better than
78   // nothing!  In particular, externally visible globals and unresolvable call
79   // nodes at the end of the BU phase should make things that they point to
80   // incomplete in the globals graph.
81   // 
82   GlobalsGraph->removeTriviallyDeadNodes();
83   GlobalsGraph->maskIncompleteMarkers();
84
85   // Merge the globals variables (not the calls) from the globals graph back
86   // into the main function's graph so that the main function contains all of
87   // the information about global pools and GV usage in the program.
88   if (MainFunc && !MainFunc->isExternal()) {
89     DSGraph &MainGraph = getOrCreateGraph(MainFunc);
90     const DSGraph &GG = *MainGraph.getGlobalsGraph();
91     ReachabilityCloner RC(MainGraph, GG, 
92                           DSGraph::DontCloneCallNodes |
93                           DSGraph::DontCloneAuxCallNodes);
94
95     // Clone the global nodes into this graph.
96     for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
97            E = GG.getScalarMap().global_end(); I != E; ++I)
98       if (isa<GlobalVariable>(*I))
99         RC.getClonedNH(GG.getNodeForValue(*I));
100
101     MainGraph.maskIncompleteMarkers();
102     MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs | 
103                                   DSGraph::IgnoreGlobals);
104   }
105
106   return false;
107 }
108
109 DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
110   // Has the graph already been created?
111   DSGraph *&Graph = DSInfo[F];
112   if (Graph) return *Graph;
113
114   // Copy the local version into DSInfo...
115   Graph = new DSGraph(getAnalysis<LocalDataStructures>().getDSGraph(*F),
116                       GlobalECs);
117
118   Graph->setGlobalsGraph(GlobalsGraph);
119   Graph->setPrintAuxCalls();
120
121   // Start with a copy of the original call sites...
122   Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
123   return *Graph;
124 }
125
126 static bool isVAHackFn(const Function *F) {
127   return F->getName() == "printf"  || F->getName() == "sscanf" ||
128     F->getName() == "fprintf" || F->getName() == "open" ||
129     F->getName() == "sprintf" || F->getName() == "fputs" ||
130     F->getName() == "fscanf";
131 }
132
133 static bool isResolvableFunc(const Function* callee) {
134   return !callee->isExternal() || isVAHackFn(callee);
135 }
136
137 static void GetAllCallees(const DSCallSite &CS, 
138                           std::vector<Function*> &Callees) {
139   if (CS.isDirectCall()) {
140     if (isResolvableFunc(CS.getCalleeFunc()))
141       Callees.push_back(CS.getCalleeFunc());
142   } else if (!CS.getCalleeNode()->isIncomplete()) {
143     // Get all callees.
144     unsigned OldSize = Callees.size();
145     CS.getCalleeNode()->addFullFunctionList(Callees);
146     
147     // If any of the callees are unresolvable, remove the whole batch!
148     for (unsigned i = OldSize, e = Callees.size(); i != e; ++i)
149       if (!isResolvableFunc(Callees[i])) {
150         Callees.erase(Callees.begin()+OldSize, Callees.end());
151         return;
152       }
153   }
154 }
155
156
157 /// GetAllAuxCallees - Return a list containing all of the resolvable callees in
158 /// the aux list for the specified graph in the Callees vector.
159 static void GetAllAuxCallees(DSGraph &G, std::vector<Function*> &Callees) {
160   Callees.clear();
161   for (DSGraph::afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
162     GetAllCallees(*I, Callees);
163 }
164
165 unsigned BUDataStructures::calculateGraphs(Function *F,
166                                            std::vector<Function*> &Stack,
167                                            unsigned &NextID, 
168                                      hash_map<Function*, unsigned> &ValMap) {
169   assert(!ValMap.count(F) && "Shouldn't revisit functions!");
170   unsigned Min = NextID++, MyID = Min;
171   ValMap[F] = Min;
172   Stack.push_back(F);
173
174   // FIXME!  This test should be generalized to be any function that we have
175   // already processed, in the case when there isn't a main or there are
176   // unreachable functions!
177   if (F->isExternal()) {   // sprintf, fprintf, sscanf, etc...
178     // No callees!
179     Stack.pop_back();
180     ValMap[F] = ~0;
181     return Min;
182   }
183
184   DSGraph &Graph = getOrCreateGraph(F);
185
186   // Find all callee functions.
187   std::vector<Function*> CalleeFunctions;
188   GetAllAuxCallees(Graph, CalleeFunctions);
189
190   // The edges out of the current node are the call site targets...
191   for (unsigned i = 0, e = CalleeFunctions.size(); i != e; ++i) {
192     Function *Callee = CalleeFunctions[i];
193     unsigned M;
194     // Have we visited the destination function yet?
195     hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
196     if (It == ValMap.end())  // No, visit it now.
197       M = calculateGraphs(Callee, Stack, NextID, ValMap);
198     else                    // Yes, get it's number.
199       M = It->second;
200     if (M < Min) Min = M;
201   }
202
203   assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
204   if (Min != MyID)
205     return Min;         // This is part of a larger SCC!
206
207   // If this is a new SCC, process it now.
208   if (Stack.back() == F) {           // Special case the single "SCC" case here.
209     DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
210                     << F->getName() << "\n");
211     Stack.pop_back();
212     DSGraph &G = getDSGraph(*F);
213     DEBUG(std::cerr << "  [BU] Calculating graph for: " << F->getName()<< "\n");
214     calculateGraph(G);
215     DEBUG(std::cerr << "  [BU] Done inlining: " << F->getName() << " ["
216                     << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
217                     << "]\n");
218
219     if (MaxSCC < 1) MaxSCC = 1;
220
221     // Should we revisit the graph?  Only do it if there are now new resolvable
222     // callees.
223     GetAllAuxCallees(Graph, CalleeFunctions);
224     if (!CalleeFunctions.empty()) {
225       ValMap.erase(F);
226       return calculateGraphs(F, Stack, NextID, ValMap);
227     } else {
228       ValMap[F] = ~0U;
229     }
230     return MyID;
231
232   } else {
233     // SCCFunctions - Keep track of the functions in the current SCC
234     //
235     hash_set<DSGraph*> SCCGraphs;
236
237     Function *NF;
238     std::vector<Function*>::iterator FirstInSCC = Stack.end();
239     DSGraph *SCCGraph = 0;
240     do {
241       NF = *--FirstInSCC;
242       ValMap[NF] = ~0U;
243
244       // Figure out which graph is the largest one, in order to speed things up
245       // a bit in situations where functions in the SCC have widely different
246       // graph sizes.
247       DSGraph &NFGraph = getDSGraph(*NF);
248       SCCGraphs.insert(&NFGraph);
249       // FIXME: If we used a better way of cloning graphs (ie, just splice all
250       // of the nodes into the new graph), this would be completely unneeded!
251       if (!SCCGraph || SCCGraph->getGraphSize() < NFGraph.getGraphSize())
252         SCCGraph = &NFGraph;
253     } while (NF != F);
254
255     std::cerr << "Calculating graph for SCC #: " << MyID << " of size: "
256               << SCCGraphs.size() << "\n";
257
258     // Compute the Max SCC Size...
259     if (MaxSCC < SCCGraphs.size())
260       MaxSCC = SCCGraphs.size();
261
262     // First thing first, collapse all of the DSGraphs into a single graph for
263     // the entire SCC.  We computed the largest graph, so clone all of the other
264     // (smaller) graphs into it.  Discard all of the old graphs.
265     //
266     for (hash_set<DSGraph*>::iterator I = SCCGraphs.begin(),
267            E = SCCGraphs.end(); I != E; ++I) {
268       DSGraph &G = **I;
269       if (&G != SCCGraph) {
270         {
271           DSGraph::NodeMapTy NodeMap;
272           SCCGraph->cloneInto(G, SCCGraph->getReturnNodes(), NodeMap);
273         }
274         // Update the DSInfo map and delete the old graph...
275         for (DSGraph::retnodes_iterator I = G.retnodes_begin(),
276                E = G.retnodes_end(); I != E; ++I)
277           DSInfo[I->first] = SCCGraph;
278         delete &G;
279       }
280     }
281
282     // Clean up the graph before we start inlining a bunch again...
283     SCCGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
284
285     // Now that we have one big happy family, resolve all of the call sites in
286     // the graph...
287     calculateGraph(*SCCGraph);
288     DEBUG(std::cerr << "  [BU] Done inlining SCC  [" << SCCGraph->getGraphSize()
289                     << "+" << SCCGraph->getAuxFunctionCalls().size() << "]\n");
290
291     std::cerr << "DONE with SCC #: " << MyID << "\n";
292
293     // We never have to revisit "SCC" processed functions...
294     
295     // Drop the stuff we don't need from the end of the stack
296     Stack.erase(FirstInSCC, Stack.end());
297     return MyID;
298   }
299
300   return MyID;  // == Min
301 }
302
303
304 // releaseMemory - If the pass pipeline is done with this pass, we can release
305 // our memory... here...
306 //
307 void BUDataStructures::releaseMemory() {
308   for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
309          E = DSInfo.end(); I != E; ++I) {
310     I->second->getReturnNodes().erase(I->first);
311     if (I->second->getReturnNodes().empty())
312       delete I->second;
313   }
314
315   // Empty map so next time memory is released, data structures are not
316   // re-deleted.
317   DSInfo.clear();
318   delete GlobalsGraph;
319   GlobalsGraph = 0;
320 }
321
322 void BUDataStructures::calculateGraph(DSGraph &Graph) {
323   // Move our call site list into TempFCs so that inline call sites go into the
324   // new call site list and doesn't invalidate our iterators!
325   std::list<DSCallSite> TempFCs;
326   std::list<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
327   TempFCs.swap(AuxCallsList);
328
329   DSGraph::ReturnNodesTy &ReturnNodes = Graph.getReturnNodes();
330
331   bool Printed = false;
332   std::vector<Function*> CalledFuncs;
333   while (!TempFCs.empty()) {
334     DSCallSite &CS = *TempFCs.begin();
335
336     CalledFuncs.clear();
337
338     // Fast path for noop calls.  Note that we don't care about merging globals
339     // in the callee with nodes in the caller here.
340     if (CS.getRetVal().isNull() && CS.getNumPtrArgs() == 0) {
341       TempFCs.erase(TempFCs.begin());
342       continue;
343     } else if (CS.isDirectCall() && isVAHackFn(CS.getCalleeFunc())) {
344       TempFCs.erase(TempFCs.begin());
345       continue;
346     }
347
348     GetAllCallees(CS, CalledFuncs);
349
350     if (CalledFuncs.empty()) {
351       // Remember that we could not resolve this yet!
352       AuxCallsList.splice(AuxCallsList.end(), TempFCs, TempFCs.begin());
353       continue;
354     } else {
355       DSGraph *GI;
356       Instruction *TheCall = CS.getCallSite().getInstruction();
357
358       if (CalledFuncs.size() == 1) {
359         Function *Callee = CalledFuncs[0];
360         ActualCallees.insert(std::make_pair(TheCall, Callee));
361
362         // Get the data structure graph for the called function.
363         GI = &getDSGraph(*Callee);  // Graph to inline
364         DEBUG(std::cerr << "    Inlining graph for " << Callee->getName());
365
366         DEBUG(std::cerr << "[" << GI->getGraphSize() << "+"
367               << GI->getAuxFunctionCalls().size() << "] into '"
368               << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
369               << Graph.getAuxFunctionCalls().size() << "]\n");
370         Graph.mergeInGraph(CS, *Callee, *GI,
371                            DSGraph::KeepModRefBits | 
372                            DSGraph::StripAllocaBit|DSGraph::DontCloneCallNodes);
373         ++NumBUInlines;
374       } else {
375         if (!Printed)
376           std::cerr << "In Fns: " << Graph.getFunctionNames() << "\n";
377         std::cerr << "  calls " << CalledFuncs.size()
378                   << " fns from site: " << CS.getCallSite().getInstruction() 
379                   << "  " << *CS.getCallSite().getInstruction();
380         std::cerr << "   Fns =";
381         unsigned NumPrinted = 0;
382
383         for (std::vector<Function*>::iterator I = CalledFuncs.begin(),
384                E = CalledFuncs.end(); I != E; ++I) {
385           if (NumPrinted++ < 8) std::cerr << " " << (*I)->getName();
386
387           // Add the call edges to the call graph.
388           ActualCallees.insert(std::make_pair(TheCall, *I));
389         }
390         std::cerr << "\n";
391
392         // See if we already computed a graph for this set of callees.
393         std::sort(CalledFuncs.begin(), CalledFuncs.end());
394         std::pair<DSGraph*, std::vector<DSNodeHandle> > &IndCallGraph =
395           (*IndCallGraphMap)[CalledFuncs];
396
397         if (IndCallGraph.first == 0) {
398           std::vector<Function*>::iterator I = CalledFuncs.begin(),
399             E = CalledFuncs.end();
400           
401           // Start with a copy of the first graph.
402           GI = IndCallGraph.first = new DSGraph(getDSGraph(**I), GlobalECs);
403           GI->setGlobalsGraph(Graph.getGlobalsGraph());
404           std::vector<DSNodeHandle> &Args = IndCallGraph.second;
405
406           // Get the argument nodes for the first callee.  The return value is
407           // the 0th index in the vector.
408           GI->getFunctionArgumentsForCall(*I, Args);
409
410           // Merge all of the other callees into this graph.
411           for (++I; I != E; ++I) {
412             // If the graph already contains the nodes for the function, don't
413             // bother merging it in again.
414             if (!GI->containsFunction(*I)) {
415               DSGraph::NodeMapTy NodeMap;
416               GI->cloneInto(getDSGraph(**I), GI->getReturnNodes(), NodeMap);
417               ++NumBUInlines;
418             }
419
420             std::vector<DSNodeHandle> NextArgs;
421             GI->getFunctionArgumentsForCall(*I, NextArgs);
422             unsigned i = 0, e = Args.size();
423             for (; i != e; ++i) {
424               if (i == NextArgs.size()) break;
425               Args[i].mergeWith(NextArgs[i]);
426             }
427             for (e = NextArgs.size(); i != e; ++i)
428               Args.push_back(NextArgs[i]);
429           }
430           
431           // Clean up the final graph!
432           GI->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
433         } else {
434           std::cerr << "***\n*** RECYCLED GRAPH ***\n***\n";
435         }
436
437         GI = IndCallGraph.first;
438
439         // Merge the unified graph into this graph now.
440         DEBUG(std::cerr << "    Inlining multi callee graph "
441               << "[" << GI->getGraphSize() << "+"
442               << GI->getAuxFunctionCalls().size() << "] into '"
443               << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
444               << Graph.getAuxFunctionCalls().size() << "]\n");
445
446         Graph.mergeInGraph(CS, IndCallGraph.second, *GI,
447                            DSGraph::KeepModRefBits | 
448                            DSGraph::StripAllocaBit |
449                            DSGraph::DontCloneCallNodes);
450         ++NumBUInlines;
451       }
452     }
453     TempFCs.erase(TempFCs.begin());
454   }
455
456   // Recompute the Incomplete markers
457   Graph.maskIncompleteMarkers();
458   Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
459
460   // Delete dead nodes.  Treat globals that are unreachable but that can
461   // reach live nodes as live.
462   Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
463
464   // When this graph is finalized, clone the globals in the graph into the
465   // globals graph to make sure it has everything, from all graphs.
466   DSScalarMap &MainSM = Graph.getScalarMap();
467   ReachabilityCloner RC(*GlobalsGraph, Graph, DSGraph::StripAllocaBit);
468
469   // Clone everything reachable from globals in the function graph into the
470   // globals graph.
471   for (DSScalarMap::global_iterator I = MainSM.global_begin(),
472          E = MainSM.global_end(); I != E; ++I) 
473     RC.getClonedNH(MainSM[*I]);
474
475   //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
476 }
477
478 static const Function *getFnForValue(const Value *V) {
479   if (const Instruction *I = dyn_cast<Instruction>(V))
480     return I->getParent()->getParent();
481   else if (const Argument *A = dyn_cast<Argument>(V))
482     return A->getParent();
483   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
484     return BB->getParent();
485   return 0;
486 }
487
488 /// deleteValue/copyValue - Interfaces to update the DSGraphs in the program.
489 /// These correspond to the interfaces defined in the AliasAnalysis class.
490 void BUDataStructures::deleteValue(Value *V) {
491   if (const Function *F = getFnForValue(V)) {  // Function local value?
492     // If this is a function local value, just delete it from the scalar map!
493     getDSGraph(*F).getScalarMap().eraseIfExists(V);
494     return;
495   }
496
497   if (Function *F = dyn_cast<Function>(V)) {
498     assert(getDSGraph(*F).getReturnNodes().size() == 1 &&
499            "cannot handle scc's");
500     delete DSInfo[F];
501     DSInfo.erase(F);
502     return;
503   }
504
505   assert(!isa<GlobalVariable>(V) && "Do not know how to delete GV's yet!");
506 }
507
508 void BUDataStructures::copyValue(Value *From, Value *To) {
509   if (From == To) return;
510   if (const Function *F = getFnForValue(From)) {  // Function local value?
511     // If this is a function local value, just delete it from the scalar map!
512     getDSGraph(*F).getScalarMap().copyScalarIfExists(From, To);
513     return;
514   }
515
516   if (Function *FromF = dyn_cast<Function>(From)) {
517     Function *ToF = cast<Function>(To);
518     assert(!DSInfo.count(ToF) && "New Function already exists!");
519     DSGraph *NG = new DSGraph(getDSGraph(*FromF), GlobalECs);
520     DSInfo[ToF] = NG;
521     assert(NG->getReturnNodes().size() == 1 && "Cannot copy SCC's yet!");
522
523     // Change the Function* is the returnnodes map to the ToF.
524     DSNodeHandle Ret = NG->retnodes_begin()->second;
525     NG->getReturnNodes().clear();
526     NG->getReturnNodes()[ToF] = Ret;
527     return;
528   }
529
530   assert(!isa<GlobalVariable>(From) && "Do not know how to copy GV's yet!");
531 }