Implement a new mergeInGraph method, which basically factors code out of
[oota-llvm.git] / lib / Analysis / DataStructure / DataStructure.cpp
1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
2 //
3 // This file implements the core data structure functionality.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Analysis/DSGraph.h"
8 #include "llvm/Function.h"
9 #include "llvm/iOther.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/Target/TargetData.h"
12 #include "Support/STLExtras.h"
13 #include "Support/Statistic.h"
14 #include <algorithm>
15 #include <set>
16
17 using std::vector;
18
19 namespace {
20   Statistic<> NumFolds("dsnode", "Number of nodes completely folded");
21 };
22
23 namespace DS {   // TODO: FIXME
24   extern TargetData TD;
25 }
26 using namespace DS;
27
28 //===----------------------------------------------------------------------===//
29 // DSNode Implementation
30 //===----------------------------------------------------------------------===//
31
32 DSNode::DSNode(enum NodeTy NT, const Type *T)
33   : Ty(Type::VoidTy), Size(0), NodeType(NT) {
34   // Add the type entry if it is specified...
35   if (T) mergeTypeInfo(T, 0);
36 }
37
38 // DSNode copy constructor... do not copy over the referrers list!
39 DSNode::DSNode(const DSNode &N)
40   : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size), 
41     NodeType(N.NodeType) {
42 }
43
44 void DSNode::removeReferrer(DSNodeHandle *H) {
45   // Search backwards, because we depopulate the list from the back for
46   // efficiency (because it's a vector).
47   vector<DSNodeHandle*>::reverse_iterator I =
48     std::find(Referrers.rbegin(), Referrers.rend(), H);
49   assert(I != Referrers.rend() && "Referrer not pointing to node!");
50   Referrers.erase(I.base()-1);
51 }
52
53 // addGlobal - Add an entry for a global value to the Globals list.  This also
54 // marks the node with the 'G' flag if it does not already have it.
55 //
56 void DSNode::addGlobal(GlobalValue *GV) {
57   // Keep the list sorted.
58   vector<GlobalValue*>::iterator I =
59     std::lower_bound(Globals.begin(), Globals.end(), GV);
60
61   if (I == Globals.end() || *I != GV) {
62     //assert(GV->getType()->getElementType() == Ty);
63     Globals.insert(I, GV);
64     NodeType |= GlobalNode;
65   }
66 }
67
68 /// foldNodeCompletely - If we determine that this node has some funny
69 /// behavior happening to it that we cannot represent, we fold it down to a
70 /// single, completely pessimistic, node.  This node is represented as a
71 /// single byte with a single TypeEntry of "void".
72 ///
73 void DSNode::foldNodeCompletely() {
74   if (isNodeCompletelyFolded()) return;
75
76   ++NumFolds;
77
78   // We are no longer typed at all...
79   Ty = DSTypeRec(Type::VoidTy, true);
80   Size = 1;
81
82   // Loop over all of our referrers, making them point to our zero bytes of
83   // space.
84   for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
85        I != E; ++I)
86     (*I)->setOffset(0);
87
88   // If we have links, merge all of our outgoing links together...
89   for (unsigned i = 1, e = Links.size(); i < e; ++i)
90     Links[0].mergeWith(Links[i]);
91   Links.resize(1);
92 }
93
94 /// isNodeCompletelyFolded - Return true if this node has been completely
95 /// folded down to something that can never be expanded, effectively losing
96 /// all of the field sensitivity that may be present in the node.
97 ///
98 bool DSNode::isNodeCompletelyFolded() const {
99   return getSize() == 1 && Ty.Ty == Type::VoidTy && Ty.isArray;
100 }
101
102
103 /// mergeTypeInfo - This method merges the specified type into the current node
104 /// at the specified offset.  This may update the current node's type record if
105 /// this gives more information to the node, it may do nothing to the node if
106 /// this information is already known, or it may merge the node completely (and
107 /// return true) if the information is incompatible with what is already known.
108 ///
109 /// This method returns true if the node is completely folded, otherwise false.
110 ///
111 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
112   // Check to make sure the Size member is up-to-date.  Size can be one of the
113   // following:
114   //  Size = 0, Ty = Void: Nothing is known about this node.
115   //  Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
116   //  Size = 1, Ty = Void, Array = 1: The node is collapsed
117   //  Otherwise, sizeof(Ty) = Size
118   //
119   assert(((Size == 0 && Ty.Ty == Type::VoidTy && !Ty.isArray) ||
120           (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
121           (Size == 1 && Ty.Ty == Type::VoidTy && Ty.isArray) ||
122           (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
123           (TD.getTypeSize(Ty.Ty) == Size)) &&
124          "Size member of DSNode doesn't match the type structure!");
125   assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
126
127   if (Offset == 0 && NewTy == Ty.Ty)
128     return false;  // This should be a common case, handle it efficiently
129
130   // Return true immediately if the node is completely folded.
131   if (isNodeCompletelyFolded()) return true;
132
133   // Figure out how big the new type we're merging in is...
134   unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
135
136   // Otherwise check to see if we can fold this type into the current node.  If
137   // we can't, we fold the node completely, if we can, we potentially update our
138   // internal state.
139   //
140   if (Ty.Ty == Type::VoidTy) {
141     // If this is the first type that this node has seen, just accept it without
142     // question....
143     assert(Offset == 0 && "Cannot have an offset into a void node!");
144     assert(Ty.isArray == false && "This shouldn't happen!");
145     Ty.Ty = NewTy;
146     Size = NewTySize;
147
148     // Calculate the number of outgoing links from this node.
149     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
150     return false;
151   }
152
153   // Handle node expansion case here...
154   if (Offset+NewTySize > Size) {
155     // It is illegal to grow this node if we have treated it as an array of
156     // objects...
157     if (Ty.isArray) {
158       foldNodeCompletely();
159       return true;
160     }
161
162     if (Offset) {  // We could handle this case, but we don't for now...
163       DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
164                       << "offset != 0: Collapsing!\n");
165       foldNodeCompletely();
166       return true;
167     }
168
169     // Okay, the situation is nice and simple, we are trying to merge a type in
170     // at offset 0 that is bigger than our current type.  Implement this by
171     // switching to the new type and then merge in the smaller one, which should
172     // hit the other code path here.  If the other code path decides it's not
173     // ok, it will collapse the node as appropriate.
174     //
175     const Type *OldTy = Ty.Ty;
176     Ty.Ty = NewTy;
177     Size = NewTySize;
178
179     // Must grow links to be the appropriate size...
180     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
181
182     // Merge in the old type now... which is guaranteed to be smaller than the
183     // "current" type.
184     return mergeTypeInfo(OldTy, 0);
185   }
186
187   assert(Offset <= Size &&
188          "Cannot merge something into a part of our type that doesn't exist!");
189
190   // Find the section of Ty.Ty that NewTy overlaps with... first we find the
191   // type that starts at offset Offset.
192   //
193   unsigned O = 0;
194   const Type *SubType = Ty.Ty;
195   while (O < Offset) {
196     assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
197
198     switch (SubType->getPrimitiveID()) {
199     case Type::StructTyID: {
200       const StructType *STy = cast<StructType>(SubType);
201       const StructLayout &SL = *TD.getStructLayout(STy);
202
203       unsigned i = 0, e = SL.MemberOffsets.size();
204       for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
205         /* empty */;
206
207       // The offset we are looking for must be in the i'th element...
208       SubType = STy->getElementTypes()[i];
209       O += SL.MemberOffsets[i];
210       break;
211     }
212     case Type::ArrayTyID: {
213       SubType = cast<ArrayType>(SubType)->getElementType();
214       unsigned ElSize = TD.getTypeSize(SubType);
215       unsigned Remainder = (Offset-O) % ElSize;
216       O = Offset-Remainder;
217       break;
218     }
219     default:
220       assert(0 && "Unknown type!");
221     }
222   }
223
224   assert(O == Offset && "Could not achieve the correct offset!");
225
226   // If we found our type exactly, early exit
227   if (SubType == NewTy) return false;
228
229   // Okay, so we found the leader type at the offset requested.  Search the list
230   // of types that starts at this offset.  If SubType is currently an array or
231   // structure, the type desired may actually be the first element of the
232   // composite type...
233   //
234   unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
235   while (SubType != NewTy) {
236     const Type *NextSubType = 0;
237     unsigned NextSubTypeSize;
238     switch (SubType->getPrimitiveID()) {
239     case Type::StructTyID:
240       NextSubType = cast<StructType>(SubType)->getElementTypes()[0];
241       NextSubTypeSize = TD.getTypeSize(SubType);
242       break;
243     case Type::ArrayTyID:
244       NextSubType = cast<ArrayType>(SubType)->getElementType();
245       NextSubTypeSize = TD.getTypeSize(SubType);
246       break;
247     default: ;
248       // fall out 
249     }
250
251     if (NextSubType == 0)
252       break;   // In the default case, break out of the loop
253
254     if (NextSubTypeSize < NewTySize)
255       break;   // Don't allow shrinking to a smaller type than NewTySize
256     SubType = NextSubType;
257     SubTypeSize = NextSubTypeSize;
258   }
259
260   // If we found the type exactly, return it...
261   if (SubType == NewTy)
262     return false;
263
264   // Check to see if we have a compatible, but different type...
265   if (NewTySize == SubTypeSize) {
266     // Check to see if this type is obviously convertable... int -> uint f.e.
267     if (NewTy->isLosslesslyConvertableTo(SubType))
268       return false;
269
270     // Check to see if we have a pointer & integer mismatch going on here,
271     // loading a pointer as a long, for example.
272     //
273     if (SubType->isInteger() && isa<PointerType>(NewTy) ||
274         NewTy->isInteger() && isa<PointerType>(SubType))
275       return false;
276
277   }
278
279
280   DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty.Ty
281                   << "\n due to:" << NewTy << " @ " << Offset << "!\n"
282                   << "SubType: " << SubType << "\n\n");
283
284   foldNodeCompletely();
285   return true;
286 }
287
288
289
290 // addEdgeTo - Add an edge from the current node to the specified node.  This
291 // can cause merging of nodes in the graph.
292 //
293 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
294   if (NH.getNode() == 0) return;       // Nothing to do
295
296   DSNodeHandle &ExistingEdge = getLink(Offset);
297   if (ExistingEdge.getNode()) {
298     // Merge the two nodes...
299     ExistingEdge.mergeWith(NH);
300   } else {                             // No merging to perform...
301     setLink(Offset, NH);               // Just force a link in there...
302   }
303 }
304
305
306 // MergeSortedVectors - Efficiently merge a vector into another vector where
307 // duplicates are not allowed and both are sorted.  This assumes that 'T's are
308 // efficiently copyable and have sane comparison semantics.
309 //
310 template<typename T>
311 void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
312   // By far, the most common cases will be the simple ones.  In these cases,
313   // avoid having to allocate a temporary vector...
314   //
315   if (Src.empty()) {             // Nothing to merge in...
316     return;
317   } else if (Dest.empty()) {     // Just copy the result in...
318     Dest = Src;
319   } else if (Src.size() == 1) {  // Insert a single element...
320     const T &V = Src[0];
321     typename vector<T>::iterator I =
322       std::lower_bound(Dest.begin(), Dest.end(), V);
323     if (I == Dest.end() || *I != Src[0])  // If not already contained...
324       Dest.insert(I, Src[0]);
325   } else if (Dest.size() == 1) {
326     T Tmp = Dest[0];                      // Save value in temporary...
327     Dest = Src;                           // Copy over list...
328     typename vector<T>::iterator I =
329       std::lower_bound(Dest.begin(), Dest.end(),Tmp);
330     if (I == Dest.end() || *I != Src[0])  // If not already contained...
331       Dest.insert(I, Src[0]);
332
333   } else {
334     // Make a copy to the side of Dest...
335     vector<T> Old(Dest);
336     
337     // Make space for all of the type entries now...
338     Dest.resize(Dest.size()+Src.size());
339     
340     // Merge the two sorted ranges together... into Dest.
341     std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
342     
343     // Now erase any duplicate entries that may have accumulated into the 
344     // vectors (because they were in both of the input sets)
345     Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
346   }
347 }
348
349
350 // mergeWith - Merge this node and the specified node, moving all links to and
351 // from the argument node into the current node, deleting the node argument.
352 // Offset indicates what offset the specified node is to be merged into the
353 // current node.
354 //
355 // The specified node may be a null pointer (in which case, nothing happens).
356 //
357 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
358   DSNode *N = NH.getNode();
359   if (N == 0 || (N == this && NH.getOffset() == Offset))
360     return;  // Noop
361
362   if (N == this) {
363     // We cannot merge two pieces of the same node together, collapse the node
364     // completely.
365     DEBUG(std::cerr << "Attempting to merge two chunks of"
366                     << " the same node together!\n");
367     foldNodeCompletely();
368     return;
369   }
370
371   // Merge the type entries of the two nodes together...
372   if (N->Ty.Ty != Type::VoidTy)
373     mergeTypeInfo(N->Ty.Ty, Offset);
374
375   // If we are merging a node with a completely folded node, then both nodes are
376   // now completely folded.
377   //
378   if (isNodeCompletelyFolded()) {
379     if (!N->isNodeCompletelyFolded())
380       N->foldNodeCompletely();
381   } else if (N->isNodeCompletelyFolded()) {
382     foldNodeCompletely();
383     Offset = 0;
384   }
385   N = NH.getNode();
386
387   if (this == N || N == 0) return;
388
389   // If both nodes are not at offset 0, make sure that we are merging the node
390   // at an later offset into the node with the zero offset.
391   //
392   if (Offset > NH.getOffset()) {
393     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
394     return;
395   } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
396     // If the offsets are the same, merge the smaller node into the bigger node
397     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
398     return;
399   }
400
401 #if 0
402   std::cerr << "\n\nMerging:\n";
403   N->print(std::cerr, 0);
404   std::cerr << " and:\n";
405   print(std::cerr, 0);
406 #endif
407
408   // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
409   // respect to NH.Offset) is now zero.
410   //
411   unsigned NOffset = NH.getOffset()-Offset;
412   unsigned NSize = N->getSize();
413
414   // Remove all edges pointing at N, causing them to point to 'this' instead.
415   // Make sure to adjust their offset, not just the node pointer.
416   //
417   while (!N->Referrers.empty()) {
418     DSNodeHandle &Ref = *N->Referrers.back();
419     Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
420   }
421
422   // Make all of the outgoing links of N now be outgoing links of this.  This
423   // can cause recursive merging!
424   //
425   for (unsigned i = 0; i < NSize; i += DS::PointerSize) {
426     DSNodeHandle &Link = N->getLink(i);
427     if (Link.getNode()) {
428       addEdgeTo((i+NOffset) % getSize(), Link);
429
430       // It's possible that after adding the new edge that some recursive
431       // merging just occured, causing THIS node to get merged into oblivion.
432       // If that happens, we must not try to merge any more edges into it!
433       //
434       if (Size == 0) return;
435     }
436   }
437
438   // Now that there are no outgoing edges, all of the Links are dead.
439   N->Links.clear();
440   N->Size = 0;
441   N->Ty.Ty = Type::VoidTy;
442   N->Ty.isArray = false;
443
444   // Merge the node types
445   NodeType |= N->NodeType;
446   N->NodeType = 0;   // N is now a dead node.
447
448   // Merge the globals list...
449   if (!N->Globals.empty()) {
450     MergeSortedVectors(Globals, N->Globals);
451
452     // Delete the globals from the old node...
453     N->Globals.clear();
454   }
455 }
456
457 //===----------------------------------------------------------------------===//
458 // DSCallSite Implementation
459 //===----------------------------------------------------------------------===//
460
461 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
462 Function &DSCallSite::getCaller() const {
463   return *Inst->getParent()->getParent();
464 }
465
466
467 //===----------------------------------------------------------------------===//
468 // DSGraph Implementation
469 //===----------------------------------------------------------------------===//
470
471 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
472   std::map<const DSNode*, DSNode*> NodeMap;
473   RetNode = cloneInto(G, ScalarMap, NodeMap);
474 }
475
476 DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
477   : Func(G.Func) {
478   RetNode = cloneInto(G, ScalarMap, NodeMap);
479 }
480
481 DSGraph::~DSGraph() {
482   FunctionCalls.clear();
483   ScalarMap.clear();
484   RetNode.setNode(0);
485
486 #ifndef NDEBUG
487   // Drop all intra-node references, so that assertions don't fail...
488   std::for_each(Nodes.begin(), Nodes.end(),
489                 std::mem_fun(&DSNode::dropAllReferences));
490 #endif
491
492   // Delete all of the nodes themselves...
493   std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
494 }
495
496 // dump - Allow inspection of graph in a debugger.
497 void DSGraph::dump() const { print(std::cerr); }
498
499
500 // Helper function used to clone a function list.
501 // 
502 static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
503                                   vector<DSCallSite> &toCalls,
504                                   std::map<const DSNode*, DSNode*> &NodeMap) {
505   unsigned FC = toCalls.size();  // FirstCall
506   toCalls.reserve(FC+fromCalls.size());
507   for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
508     toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
509 }
510
511 /// remapLinks - Change all of the Links in the current node according to the
512 /// specified mapping.
513 ///
514 void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
515   for (unsigned i = 0, e = Links.size(); i != e; ++i) 
516     Links[i].setNode(OldNodeMap[Links[i].getNode()]);
517 }
518
519
520 // cloneInto - Clone the specified DSGraph into the current graph, returning the
521 // Return node of the graph.  The translated ScalarMap for the old function is
522 // filled into the OldValMap member.  If StripAllocas is set to true, Alloca
523 // markers are removed from the graph, as the graph is being cloned into a
524 // calling function's graph.
525 //
526 DSNodeHandle DSGraph::cloneInto(const DSGraph &G, 
527                                 std::map<Value*, DSNodeHandle> &OldValMap,
528                                 std::map<const DSNode*, DSNode*> &OldNodeMap,
529                                 bool StripAllocas) {
530   assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
531
532   unsigned FN = Nodes.size();           // First new node...
533
534   // Duplicate all of the nodes, populating the node map...
535   Nodes.reserve(FN+G.Nodes.size());
536   for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
537     DSNode *Old = G.Nodes[i];
538     DSNode *New = new DSNode(*Old);
539     Nodes.push_back(New);
540     OldNodeMap[Old] = New;
541   }
542
543   // Rewrite the links in the new nodes to point into the current graph now.
544   for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
545     Nodes[i]->remapLinks(OldNodeMap);
546
547   // Remove local markers as specified
548   unsigned char StripBits = StripAllocas ? DSNode::AllocaNode : 0;
549   if (StripBits)
550     for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
551       Nodes[i]->NodeType &= ~StripBits;
552
553   // Copy the value map... and merge all of the global nodes...
554   for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
555          E = G.ScalarMap.end(); I != E; ++I) {
556     DSNodeHandle &H = OldValMap[I->first];
557     H.setNode(OldNodeMap[I->second.getNode()]);
558     H.setOffset(I->second.getOffset());
559
560     if (isa<GlobalValue>(I->first)) {  // Is this a global?
561       std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
562       if (GVI != ScalarMap.end()) {   // Is the global value in this fn already?
563         GVI->second.mergeWith(H);
564       } else {
565         ScalarMap[I->first] = H;      // Add global pointer to this graph
566       }
567     }
568   }
569   // Copy the function calls list...
570   CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
571
572
573   // Return the returned node pointer...
574   return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
575 }
576
577 /// mergeInGraph - The method is used for merging graphs together.  If the
578 /// argument graph is not *this, it makes a clone of the specified graph, then
579 /// merges the nodes specified in the call site with the formal arguments in the
580 /// graph.
581 ///
582 void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
583                            bool StripAllocas) {
584   std::map<Value*, DSNodeHandle> OldValMap;
585   DSNodeHandle RetVal;
586   std::map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
587
588   // If this is not a recursive call, clone the graph into this graph...
589   if (&Graph != this) {
590     // Clone the callee's graph into the current graph, keeping
591     // track of where scalars in the old graph _used_ to point,
592     // and of the new nodes matching nodes of the old graph.
593     std::map<const DSNode*, DSNode*> OldNodeMap;
594     
595     // The clone call may invalidate any of the vectors in the data
596     // structure graph.  Strip locals and don't copy the list of callers
597     RetVal = cloneInto(Graph, OldValMap, OldNodeMap, StripAllocas);
598     ScalarMap = &OldValMap;
599   } else {
600     RetVal = getRetNode();
601     ScalarMap = &getScalarMap();
602   }
603
604   // Merge the return value with the return value of the context...
605   RetVal.mergeWith(CS.getRetVal());
606
607   // Resolve all of the function arguments...
608   Function &F = Graph.getFunction();
609   Function::aiterator AI = F.abegin();
610   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
611     // Advance the argument iterator to the first pointer argument...
612     while (!isPointerType(AI->getType())) {
613       ++AI;
614 #ifndef NDEBUG
615       if (AI == F.aend())
616         std::cerr << "Bad call to Function: " << F.getName() << "\n";
617 #endif
618       assert(AI != F.aend() && "# Args provided is not # Args required!");
619     }
620     
621     // Add the link from the argument scalar to the provided value
622     DSNodeHandle &NH = (*ScalarMap)[AI];
623     assert(NH.getNode() && "Pointer argument without scalarmap entry?");
624     NH.mergeWith(CS.getPtrArg(i));
625   }
626 }
627
628 #if 0
629 // cloneGlobalInto - Clone the given global node and all its target links
630 // (and all their llinks, recursively).
631 // 
632 DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
633   if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
634
635   // If a clone has already been created for GNode, return it.
636   DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
637   if (ValMapEntry != 0)
638     return ValMapEntry;
639
640   // Clone the node and update the ValMap.
641   DSNode* NewNode = new DSNode(*GNode);
642   ValMapEntry = NewNode;                // j=0 case of loop below!
643   Nodes.push_back(NewNode);
644   for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
645     ScalarMap[NewNode->getGlobals()[j]] = NewNode;
646
647   // Rewrite the links in the new node to point into the current graph.
648   for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
649     NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
650
651   return NewNode;
652 }
653 #endif
654
655
656 // markIncompleteNodes - Mark the specified node as having contents that are not
657 // known with the current analysis we have performed.  Because a node makes all
658 // of the nodes it can reach imcomplete if the node itself is incomplete, we
659 // must recursively traverse the data structure graph, marking all reachable
660 // nodes as incomplete.
661 //
662 static void markIncompleteNode(DSNode *N) {
663   // Stop recursion if no node, or if node already marked...
664   if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
665
666   // Actually mark the node
667   N->NodeType |= DSNode::Incomplete;
668
669   // Recusively process children...
670   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
671     if (DSNode *DSN = N->getLink(i).getNode())
672       markIncompleteNode(DSN);
673 }
674
675
676 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
677 // modified by other functions that have not been resolved yet.  This marks
678 // nodes that are reachable through three sources of "unknownness":
679 //
680 //  Global Variables, Function Calls, and Incoming Arguments
681 //
682 // For any node that may have unknown components (because something outside the
683 // scope of current analysis may have modified it), the 'Incomplete' flag is
684 // added to the NodeType.
685 //
686 void DSGraph::markIncompleteNodes(bool markFormalArgs) {
687   // Mark any incoming arguments as incomplete...
688   if (markFormalArgs && Func)
689     for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
690       if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
691         markIncompleteNode(ScalarMap[I].getNode());
692
693   // Mark stuff passed into functions calls as being incomplete...
694   for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
695     DSCallSite &Call = FunctionCalls[i];
696     // Then the return value is certainly incomplete!
697     markIncompleteNode(Call.getRetVal().getNode());
698
699     // All objects pointed to by function arguments are incomplete though!
700     for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
701       markIncompleteNode(Call.getPtrArg(i).getNode());
702   }
703
704   // Mark all of the nodes pointed to by global nodes as incomplete...
705   for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
706     if (Nodes[i]->NodeType & DSNode::GlobalNode) {
707       DSNode *N = Nodes[i];
708       // FIXME: Make more efficient by looking over Links directly
709       for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
710         if (DSNode *DSN = N->getLink(i).getNode())
711           markIncompleteNode(DSN);
712     }
713 }
714
715 // removeRefsToGlobal - Helper function that removes globals from the
716 // ScalarMap so that the referrer count will go down to zero.
717 static void removeRefsToGlobal(DSNode* N,
718                                std::map<Value*, DSNodeHandle> &ScalarMap) {
719   while (!N->getGlobals().empty()) {
720     GlobalValue *GV = N->getGlobals().back();
721     N->getGlobals().pop_back();      
722     ScalarMap.erase(GV);
723   }
724 }
725
726
727 // isNodeDead - This method checks to see if a node is dead, and if it isn't, it
728 // checks to see if there are simple transformations that it can do to make it
729 // dead.
730 //
731 bool DSGraph::isNodeDead(DSNode *N) {
732   // Is it a trivially dead shadow node...
733   if (N->getReferrers().empty() && N->NodeType == 0)
734     return true;
735
736   // Is it a function node or some other trivially unused global?
737   if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
738       N->getReferrers().size() == N->getGlobals().size()) {
739
740     // Remove the globals from the ScalarMap, so that the referrer count will go
741     // down to zero.
742     removeRefsToGlobal(N, ScalarMap);
743     assert(N->getReferrers().empty() && "Referrers should all be gone now!");
744     return true;
745   }
746
747   return false;
748 }
749
750 static void removeIdenticalCalls(vector<DSCallSite> &Calls,
751                                  const std::string &where) {
752   // Remove trivially identical function calls
753   unsigned NumFns = Calls.size();
754   std::sort(Calls.begin(), Calls.end());
755   Calls.erase(std::unique(Calls.begin(), Calls.end()),
756               Calls.end());
757
758   DEBUG(if (NumFns != Calls.size())
759           std::cerr << "Merged " << (NumFns-Calls.size())
760                     << " call nodes in " << where << "\n";);
761 }
762
763 // removeTriviallyDeadNodes - After the graph has been constructed, this method
764 // removes all unreachable nodes that are created because they got merged with
765 // other nodes in the graph.  These nodes will all be trivially unreachable, so
766 // we don't have to perform any non-trivial analysis here.
767 //
768 void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
769   for (unsigned i = 0; i != Nodes.size(); ++i)
770     if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
771       if (isNodeDead(Nodes[i])) {               // This node is dead!
772         delete Nodes[i];                        // Free memory...
773         Nodes.erase(Nodes.begin()+i--);         // Remove from node list...
774       }
775
776   removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
777 }
778
779
780 // markAlive - Simple graph walker that recursively traverses the graph, marking
781 // stuff to be alive.
782 //
783 static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
784   if (N == 0) return;
785
786   Alive.insert(N);
787   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
788     if (DSNode *DSN = N->getLink(i).getNode())
789       if (!Alive.count(DSN))
790         markAlive(DSN, Alive);
791 }
792
793 static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
794                              std::set<DSNode*> &Visiting) {
795   if (N == 0) return false;
796
797   if (Visiting.count(N)) return false; // terminate recursion on a cycle
798   Visiting.insert(N);
799
800   // If any immediate successor is alive, N is alive
801   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
802     if (DSNode *DSN = N->getLink(i).getNode())
803       if (Alive.count(DSN)) {
804         Visiting.erase(N);
805         return true;
806       }
807
808   // Else if any successor reaches a live node, N is alive
809   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
810     if (DSNode *DSN = N->getLink(i).getNode())
811       if (checkGlobalAlive(DSN, Alive, Visiting)) {
812         Visiting.erase(N); return true;
813       }
814
815   Visiting.erase(N);
816   return false;
817 }
818
819
820 // markGlobalsIteration - Recursive helper function for markGlobalsAlive().
821 // This would be unnecessary if function calls were real nodes!  In that case,
822 // the simple iterative loop in the first few lines below suffice.
823 // 
824 static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
825                                  vector<DSCallSite> &Calls,
826                                  std::set<DSNode*> &Alive,
827                                  bool FilterCalls) {
828
829   // Iterate, marking globals or cast nodes alive until no new live nodes
830   // are added to Alive
831   std::set<DSNode*> Visiting;           // Used to identify cycles 
832   std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
833   for (size_t liveCount = 0; liveCount < Alive.size(); ) {
834     liveCount = Alive.size();
835     for ( ; I != E; ++I)
836       if (Alive.count(*I) == 0) {
837         Visiting.clear();
838         if (checkGlobalAlive(*I, Alive, Visiting))
839           markAlive(*I, Alive);
840       }
841   }
842
843   // Find function calls with some dead and some live nodes.
844   // Since all call nodes must be live if any one is live, we have to mark
845   // all nodes of the call as live and continue the iteration (via recursion).
846   if (FilterCalls) {
847     bool Recurse = false;
848     for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
849       bool CallIsDead = true, CallHasDeadArg = false;
850       DSCallSite &CS = Calls[i];
851       for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
852         if (DSNode *N = CS.getPtrArg(j).getNode()) {
853           bool ArgIsDead  = !Alive.count(N);
854           CallHasDeadArg |= ArgIsDead;
855           CallIsDead     &= ArgIsDead;
856         }
857
858       if (DSNode *N = CS.getRetVal().getNode()) {
859         bool RetIsDead  = !Alive.count(N);
860         CallHasDeadArg |= RetIsDead;
861         CallIsDead     &= RetIsDead;
862       }
863
864       DSNode *N = CS.getCallee().getNode();
865       bool FnIsDead  = !Alive.count(N);
866       CallHasDeadArg |= FnIsDead;
867       CallIsDead     &= FnIsDead;
868
869       if (!CallIsDead && CallHasDeadArg) {
870         // Some node in this call is live and another is dead.
871         // Mark all nodes of call as live and iterate once more.
872         Recurse = true;
873         for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
874           markAlive(CS.getPtrArg(j).getNode(), Alive);
875         markAlive(CS.getRetVal().getNode(), Alive);
876         markAlive(CS.getCallee().getNode(), Alive);
877       }
878     }
879     if (Recurse)
880       markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
881   }
882 }
883
884
885 // markGlobalsAlive - Mark global nodes and cast nodes alive if they
886 // can reach any other live node.  Since this can produce new live nodes,
887 // we use a simple iterative algorithm.
888 // 
889 static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
890                              bool FilterCalls) {
891   // Add global and cast nodes to a set so we don't walk all nodes every time
892   std::set<DSNode*> GlobalNodes;
893   for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
894     if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
895       GlobalNodes.insert(G.getNodes()[i]);
896
897   // Add all call nodes to the same set
898   vector<DSCallSite> &Calls = G.getFunctionCalls();
899   if (FilterCalls) {
900     for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
901       for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
902         if (DSNode *N = Calls[i].getPtrArg(j).getNode())
903           GlobalNodes.insert(N);
904       if (DSNode *N = Calls[i].getRetVal().getNode())
905         GlobalNodes.insert(N);
906       if (DSNode *N = Calls[i].getCallee().getNode())
907         GlobalNodes.insert(N);
908     }
909   }
910
911   // Iterate and recurse until no new live node are discovered.
912   // This would be a simple iterative loop if function calls were real nodes!
913   markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
914
915   // Free up references to dead globals from the ScalarMap
916   std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
917   for( ; I != E; ++I)
918     if (Alive.count(*I) == 0)
919       removeRefsToGlobal(*I, G.getScalarMap());
920
921   // Delete dead function calls
922   if (FilterCalls)
923     for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
924       bool CallIsDead = true;
925       for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
926            CallIsDead && j != ej; ++j)
927         CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
928       if (CallIsDead)
929         Calls.erase(Calls.begin() + i); // remove the call entirely
930     }
931 }
932
933 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
934 // subgraphs that are unreachable.  This often occurs because the data
935 // structure doesn't "escape" into it's caller, and thus should be eliminated
936 // from the caller's graph entirely.  This is only appropriate to use when
937 // inlining graphs.
938 //
939 void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
940   assert((!KeepAllGlobals || KeepCalls) &&
941          "KeepAllGlobals without KeepCalls is meaningless");
942
943   // Reduce the amount of work we have to do...
944   removeTriviallyDeadNodes(KeepAllGlobals);
945
946   // FIXME: Merge nontrivially identical call nodes...
947
948   // Alive - a set that holds all nodes found to be reachable/alive.
949   std::set<DSNode*> Alive;
950
951   // If KeepCalls, mark all nodes reachable by call nodes as alive...
952   if (KeepCalls)
953     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
954       for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
955         markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
956       markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
957       markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
958     }
959
960   // Mark all nodes reachable by scalar nodes as alive...
961   for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
962          E = ScalarMap.end(); I != E; ++I)
963     markAlive(I->second.getNode(), Alive);
964
965 #if 0
966   // Marge all nodes reachable by global nodes, as alive.  Isn't this covered by
967   // the ScalarMap?
968   //
969   if (KeepAllGlobals)
970     for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
971       if (Nodes[i]->NodeType & DSNode::GlobalNode)
972         markAlive(Nodes[i], Alive);
973 #endif
974
975   // The return value is alive as well...
976   markAlive(RetNode.getNode(), Alive);
977
978   // Mark all globals or cast nodes that can reach a live node as alive.
979   // This also marks all nodes reachable from such nodes as alive.
980   // Of course, if KeepAllGlobals is specified, they would be live already.
981   if (!KeepAllGlobals)
982     markGlobalsAlive(*this, Alive, !KeepCalls);
983
984   // Loop over all unreachable nodes, dropping their references...
985   vector<DSNode*> DeadNodes;
986   DeadNodes.reserve(Nodes.size());     // Only one allocation is allowed.
987   for (unsigned i = 0; i != Nodes.size(); ++i)
988     if (!Alive.count(Nodes[i])) {
989       DSNode *N = Nodes[i];
990       Nodes.erase(Nodes.begin()+i--);  // Erase node from alive list.
991       DeadNodes.push_back(N);          // Add node to our list of dead nodes
992       N->dropAllReferences();          // Drop all outgoing edges
993     }
994   
995   // Delete all dead nodes...
996   std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
997 }
998
999
1000
1001 // maskNodeTypes - Apply a mask to all of the node types in the graph.  This
1002 // is useful for clearing out markers like Scalar or Incomplete.
1003 //
1004 void DSGraph::maskNodeTypes(unsigned char Mask) {
1005   for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1006     Nodes[i]->NodeType &= Mask;
1007 }
1008
1009
1010 #if 0
1011 //===----------------------------------------------------------------------===//
1012 // GlobalDSGraph Implementation
1013 //===----------------------------------------------------------------------===//
1014
1015 GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
1016 }
1017
1018 GlobalDSGraph::~GlobalDSGraph() {
1019   assert(Referrers.size() == 0 &&
1020          "Deleting global graph while references from other graphs exist");
1021 }
1022
1023 void GlobalDSGraph::addReference(const DSGraph* referrer) {
1024   if (referrer != this)
1025     Referrers.insert(referrer);
1026 }
1027
1028 void GlobalDSGraph::removeReference(const DSGraph* referrer) {
1029   if (referrer != this) {
1030     assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
1031     Referrers.erase(referrer);
1032     if (Referrers.size() == 0)
1033       delete this;
1034   }
1035 }
1036
1037 #if 0
1038 // Bits used in the next function
1039 static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1040
1041
1042 // GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1043 // visible target links (and recursively their such links) into this graph.
1044 // NodeCache maps the node being cloned to its clone in the Globals graph,
1045 // in order to track cycles.
1046 // GlobalsAreFinal is a flag that says whether it is safe to assume that
1047 // an existing global node is complete.  This is important to avoid
1048 // reinserting all globals when inserting Calls to functions.
1049 // This is a helper function for cloneGlobals and cloneCalls.
1050 // 
1051 DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1052                                     std::map<const DSNode*, DSNode*> &NodeCache,
1053                                     bool GlobalsAreFinal) {
1054   if (OldNode == 0) return 0;
1055
1056   // The caller should check this is an external node.  Just more  efficient...
1057   assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1058
1059   // If a clone has already been created for OldNode, return it.
1060   DSNode*& CacheEntry = NodeCache[OldNode];
1061   if (CacheEntry != 0)
1062     return CacheEntry;
1063
1064   // The result value...
1065   DSNode* NewNode = 0;
1066
1067   // If nodes already exist for any of the globals of OldNode,
1068   // merge all such nodes together since they are merged in OldNode.
1069   // If ValueCacheIsFinal==true, look for an existing node that has
1070   // an identical list of globals and return it if it exists.
1071   //
1072   for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
1073     if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
1074       if (NewNode == 0) {
1075         NewNode = PrevNode;             // first existing node found
1076         if (GlobalsAreFinal && j == 0)
1077           if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1078             CacheEntry = NewNode;
1079             return NewNode;
1080           }
1081       }
1082       else if (NewNode != PrevNode) {   // found another, different from prev
1083         // update ValMap *before* merging PrevNode into NewNode
1084         for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
1085           ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
1086         NewNode->mergeWith(PrevNode);
1087       }
1088     } else if (NewNode != 0) {
1089       ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
1090     }
1091
1092   // If no existing node was found, clone the node and update the ValMap.
1093   if (NewNode == 0) {
1094     NewNode = new DSNode(*OldNode);
1095     Nodes.push_back(NewNode);
1096     for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1097       NewNode->setLink(j, 0);
1098     for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
1099       ScalarMap[NewNode->getGlobals()[j]] = NewNode;
1100   }
1101   else
1102     NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1103
1104   // Add the entry to NodeCache
1105   CacheEntry = NewNode;
1106
1107   // Rewrite the links in the new node to point into the current graph,
1108   // but only for links to external nodes.  Set other links to NULL.
1109   for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1110     DSNode* OldTarget = OldNode->getLink(j);
1111     if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1112       DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1113       if (NewNode->getLink(j))
1114         NewNode->getLink(j)->mergeWith(NewLink);
1115       else
1116         NewNode->setLink(j, NewLink);
1117     }
1118   }
1119
1120   // Remove all local markers
1121   NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1122
1123   return NewNode;
1124 }
1125
1126
1127 // GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1128 // visible target links (and recursively their such links) into this graph.
1129 // 
1130 void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1131   std::map<const DSNode*, DSNode*> NodeCache;
1132 #if 0
1133   for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1134     if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1135       GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
1136   if (CloneCalls)
1137     GlobalsGraph->cloneCalls(Graph);
1138
1139   GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
1140 #endif
1141 }
1142
1143
1144 // GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1145 // links (and recursively their such links) into this graph.
1146 // 
1147 void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1148   std::map<const DSNode*, DSNode*> NodeCache;
1149   vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
1150
1151   FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1152
1153   for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
1154     DSCallSite& callCopy = FunctionCalls.back();
1155     callCopy.reserve(FromCalls[i].size());
1156     for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
1157       callCopy.push_back
1158         ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1159          ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1160          : 0);
1161   }
1162
1163   // remove trivially identical function calls
1164   removeIdenticalCalls(FunctionCalls, "Globals Graph");
1165 }
1166 #endif
1167
1168 #endif