1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
3 // This file implements the core data structure functionality.
5 //===----------------------------------------------------------------------===//
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"
20 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
21 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
24 namespace DS { // TODO: FIXME
29 //===----------------------------------------------------------------------===//
30 // DSNode Implementation
31 //===----------------------------------------------------------------------===//
33 DSNode::DSNode(enum NodeTy NT, const Type *T)
34 : Ty(Type::VoidTy), Size(0), NodeType(NT) {
35 // Add the type entry if it is specified...
36 if (T) mergeTypeInfo(T, 0);
39 // DSNode copy constructor... do not copy over the referrers list!
40 DSNode::DSNode(const DSNode &N)
41 : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size),
42 NodeType(N.NodeType) {
45 void DSNode::removeReferrer(DSNodeHandle *H) {
46 // Search backwards, because we depopulate the list from the back for
47 // efficiency (because it's a vector).
48 vector<DSNodeHandle*>::reverse_iterator I =
49 std::find(Referrers.rbegin(), Referrers.rend(), H);
50 assert(I != Referrers.rend() && "Referrer not pointing to node!");
51 Referrers.erase(I.base()-1);
54 // addGlobal - Add an entry for a global value to the Globals list. This also
55 // marks the node with the 'G' flag if it does not already have it.
57 void DSNode::addGlobal(GlobalValue *GV) {
58 // Keep the list sorted.
59 vector<GlobalValue*>::iterator I =
60 std::lower_bound(Globals.begin(), Globals.end(), GV);
62 if (I == Globals.end() || *I != GV) {
63 //assert(GV->getType()->getElementType() == Ty);
64 Globals.insert(I, GV);
65 NodeType |= GlobalNode;
69 /// foldNodeCompletely - If we determine that this node has some funny
70 /// behavior happening to it that we cannot represent, we fold it down to a
71 /// single, completely pessimistic, node. This node is represented as a
72 /// single byte with a single TypeEntry of "void".
74 void DSNode::foldNodeCompletely() {
75 if (isNodeCompletelyFolded()) return;
79 // We are no longer typed at all...
80 Ty = DSTypeRec(Type::VoidTy, true);
83 // Loop over all of our referrers, making them point to our zero bytes of
85 for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
89 // If we have links, merge all of our outgoing links together...
90 for (unsigned i = 1, e = Links.size(); i < e; ++i)
91 Links[0].mergeWith(Links[i]);
95 /// isNodeCompletelyFolded - Return true if this node has been completely
96 /// folded down to something that can never be expanded, effectively losing
97 /// all of the field sensitivity that may be present in the node.
99 bool DSNode::isNodeCompletelyFolded() const {
100 return getSize() == 1 && Ty.Ty == Type::VoidTy && Ty.isArray;
104 /// mergeTypeInfo - This method merges the specified type into the current node
105 /// at the specified offset. This may update the current node's type record if
106 /// this gives more information to the node, it may do nothing to the node if
107 /// this information is already known, or it may merge the node completely (and
108 /// return true) if the information is incompatible with what is already known.
110 /// This method returns true if the node is completely folded, otherwise false.
112 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
113 // Check to make sure the Size member is up-to-date. Size can be one of the
115 // Size = 0, Ty = Void: Nothing is known about this node.
116 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
117 // Size = 1, Ty = Void, Array = 1: The node is collapsed
118 // Otherwise, sizeof(Ty) = Size
120 assert(((Size == 0 && Ty.Ty == Type::VoidTy && !Ty.isArray) ||
121 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
122 (Size == 1 && Ty.Ty == Type::VoidTy && Ty.isArray) ||
123 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
124 (TD.getTypeSize(Ty.Ty) == Size)) &&
125 "Size member of DSNode doesn't match the type structure!");
126 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
128 if (Offset == 0 && NewTy == Ty.Ty)
129 return false; // This should be a common case, handle it efficiently
131 // Return true immediately if the node is completely folded.
132 if (isNodeCompletelyFolded()) return true;
134 // If this is an array type, eliminate the outside arrays because they won't
135 // be used anyway. This greatly reduces the size of large static arrays used
136 // as global variables, for example.
138 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
139 // FIXME: we might want to keep small arrays, but must be careful about
140 // things like: [2 x [10000 x int*]]
141 NewTy = AT->getElementType();
144 // Figure out how big the new type we're merging in is...
145 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
147 // Otherwise check to see if we can fold this type into the current node. If
148 // we can't, we fold the node completely, if we can, we potentially update our
151 if (Ty.Ty == Type::VoidTy) {
152 // If this is the first type that this node has seen, just accept it without
154 assert(Offset == 0 && "Cannot have an offset into a void node!");
155 assert(Ty.isArray == false && "This shouldn't happen!");
159 // Calculate the number of outgoing links from this node.
160 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
164 // Handle node expansion case here...
165 if (Offset+NewTySize > Size) {
166 // It is illegal to grow this node if we have treated it as an array of
169 foldNodeCompletely();
173 if (Offset) { // We could handle this case, but we don't for now...
174 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
175 << "offset != 0: Collapsing!\n");
176 foldNodeCompletely();
180 // Okay, the situation is nice and simple, we are trying to merge a type in
181 // at offset 0 that is bigger than our current type. Implement this by
182 // switching to the new type and then merge in the smaller one, which should
183 // hit the other code path here. If the other code path decides it's not
184 // ok, it will collapse the node as appropriate.
186 const Type *OldTy = Ty.Ty;
190 // Must grow links to be the appropriate size...
191 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
193 // Merge in the old type now... which is guaranteed to be smaller than the
195 return mergeTypeInfo(OldTy, 0);
198 assert(Offset <= Size &&
199 "Cannot merge something into a part of our type that doesn't exist!");
201 // Find the section of Ty.Ty that NewTy overlaps with... first we find the
202 // type that starts at offset Offset.
205 const Type *SubType = Ty.Ty;
207 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
209 switch (SubType->getPrimitiveID()) {
210 case Type::StructTyID: {
211 const StructType *STy = cast<StructType>(SubType);
212 const StructLayout &SL = *TD.getStructLayout(STy);
214 unsigned i = 0, e = SL.MemberOffsets.size();
215 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
218 // The offset we are looking for must be in the i'th element...
219 SubType = STy->getElementTypes()[i];
220 O += SL.MemberOffsets[i];
223 case Type::ArrayTyID: {
224 SubType = cast<ArrayType>(SubType)->getElementType();
225 unsigned ElSize = TD.getTypeSize(SubType);
226 unsigned Remainder = (Offset-O) % ElSize;
227 O = Offset-Remainder;
231 assert(0 && "Unknown type!");
235 assert(O == Offset && "Could not achieve the correct offset!");
237 // If we found our type exactly, early exit
238 if (SubType == NewTy) return false;
240 // Okay, so we found the leader type at the offset requested. Search the list
241 // of types that starts at this offset. If SubType is currently an array or
242 // structure, the type desired may actually be the first element of the
245 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
246 while (SubType != NewTy) {
247 const Type *NextSubType = 0;
248 unsigned NextSubTypeSize;
249 switch (SubType->getPrimitiveID()) {
250 case Type::StructTyID:
251 NextSubType = cast<StructType>(SubType)->getElementTypes()[0];
252 NextSubTypeSize = TD.getTypeSize(SubType);
254 case Type::ArrayTyID:
255 NextSubType = cast<ArrayType>(SubType)->getElementType();
256 NextSubTypeSize = TD.getTypeSize(SubType);
262 if (NextSubType == 0)
263 break; // In the default case, break out of the loop
265 if (NextSubTypeSize < NewTySize)
266 break; // Don't allow shrinking to a smaller type than NewTySize
267 SubType = NextSubType;
268 SubTypeSize = NextSubTypeSize;
271 // If we found the type exactly, return it...
272 if (SubType == NewTy)
275 // Check to see if we have a compatible, but different type...
276 if (NewTySize == SubTypeSize) {
277 // Check to see if this type is obviously convertable... int -> uint f.e.
278 if (NewTy->isLosslesslyConvertableTo(SubType))
281 // Check to see if we have a pointer & integer mismatch going on here,
282 // loading a pointer as a long, for example.
284 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
285 NewTy->isInteger() && isa<PointerType>(SubType))
291 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty.Ty
292 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
293 << "SubType: " << SubType << "\n\n");
295 foldNodeCompletely();
301 // addEdgeTo - Add an edge from the current node to the specified node. This
302 // can cause merging of nodes in the graph.
304 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
305 if (NH.getNode() == 0) return; // Nothing to do
307 DSNodeHandle &ExistingEdge = getLink(Offset);
308 if (ExistingEdge.getNode()) {
309 // Merge the two nodes...
310 ExistingEdge.mergeWith(NH);
311 } else { // No merging to perform...
312 setLink(Offset, NH); // Just force a link in there...
317 // MergeSortedVectors - Efficiently merge a vector into another vector where
318 // duplicates are not allowed and both are sorted. This assumes that 'T's are
319 // efficiently copyable and have sane comparison semantics.
322 void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
323 // By far, the most common cases will be the simple ones. In these cases,
324 // avoid having to allocate a temporary vector...
326 if (Src.empty()) { // Nothing to merge in...
328 } else if (Dest.empty()) { // Just copy the result in...
330 } else if (Src.size() == 1) { // Insert a single element...
332 typename vector<T>::iterator I =
333 std::lower_bound(Dest.begin(), Dest.end(), V);
334 if (I == Dest.end() || *I != Src[0]) // If not already contained...
335 Dest.insert(I, Src[0]);
336 } else if (Dest.size() == 1) {
337 T Tmp = Dest[0]; // Save value in temporary...
338 Dest = Src; // Copy over list...
339 typename vector<T>::iterator I =
340 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
341 if (I == Dest.end() || *I != Src[0]) // If not already contained...
342 Dest.insert(I, Src[0]);
345 // Make a copy to the side of Dest...
348 // Make space for all of the type entries now...
349 Dest.resize(Dest.size()+Src.size());
351 // Merge the two sorted ranges together... into Dest.
352 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
354 // Now erase any duplicate entries that may have accumulated into the
355 // vectors (because they were in both of the input sets)
356 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
361 // mergeWith - Merge this node and the specified node, moving all links to and
362 // from the argument node into the current node, deleting the node argument.
363 // Offset indicates what offset the specified node is to be merged into the
366 // The specified node may be a null pointer (in which case, nothing happens).
368 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
369 DSNode *N = NH.getNode();
370 if (N == 0 || (N == this && NH.getOffset() == Offset))
373 assert((N->NodeType & DSNode::DEAD) == 0);
374 assert((NodeType & DSNode::DEAD) == 0);
375 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
378 // We cannot merge two pieces of the same node together, collapse the node
380 DEBUG(std::cerr << "Attempting to merge two chunks of"
381 << " the same node together!\n");
382 foldNodeCompletely();
386 // Merge the type entries of the two nodes together...
387 if (N->Ty.Ty != Type::VoidTy) {
388 mergeTypeInfo(N->Ty.Ty, Offset);
390 // mergeTypeInfo can cause collapsing, which can cause this node to become
392 if (hasNoReferrers()) return;
394 assert((NodeType & DSNode::DEAD) == 0);
396 // If we are merging a node with a completely folded node, then both nodes are
397 // now completely folded.
399 if (isNodeCompletelyFolded()) {
400 if (!N->isNodeCompletelyFolded()) {
401 N->foldNodeCompletely();
402 if (hasNoReferrers()) return;
404 } else if (N->isNodeCompletelyFolded()) {
405 foldNodeCompletely();
407 if (hasNoReferrers()) return;
410 assert((NodeType & DSNode::DEAD) == 0);
412 if (this == N || N == 0) return;
413 assert((NodeType & DSNode::DEAD) == 0);
415 // If both nodes are not at offset 0, make sure that we are merging the node
416 // at an later offset into the node with the zero offset.
418 if (Offset > NH.getOffset()) {
419 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
421 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
422 // If the offsets are the same, merge the smaller node into the bigger node
423 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
428 std::cerr << "\n\nMerging:\n";
429 N->print(std::cerr, 0);
430 std::cerr << " and:\n";
434 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
435 // respect to NH.Offset) is now zero.
437 unsigned NOffset = NH.getOffset()-Offset;
438 unsigned NSize = N->getSize();
440 assert((NodeType & DSNode::DEAD) == 0);
442 // Remove all edges pointing at N, causing them to point to 'this' instead.
443 // Make sure to adjust their offset, not just the node pointer.
445 while (!N->Referrers.empty()) {
446 DSNodeHandle &Ref = *N->Referrers.back();
447 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
449 assert((NodeType & DSNode::DEAD) == 0);
451 // Make all of the outgoing links of N now be outgoing links of this. This
452 // can cause recursive merging!
454 for (unsigned i = 0; i < NSize; i += DS::PointerSize) {
455 DSNodeHandle &Link = N->getLink(i);
456 if (Link.getNode()) {
457 addEdgeTo((i+NOffset) % getSize(), Link);
459 // It's possible that after adding the new edge that some recursive
460 // merging just occured, causing THIS node to get merged into oblivion.
461 // If that happens, we must not try to merge any more edges into it!
463 if (Size == 0) return;
467 // Now that there are no outgoing edges, all of the Links are dead.
470 N->Ty.Ty = Type::VoidTy;
471 N->Ty.isArray = false;
473 // Merge the node types
474 NodeType |= N->NodeType;
475 N->NodeType = DEAD; // N is now a dead node.
477 // Merge the globals list...
478 if (!N->Globals.empty()) {
479 MergeSortedVectors(Globals, N->Globals);
481 // Delete the globals from the old node...
486 //===----------------------------------------------------------------------===//
487 // DSCallSite Implementation
488 //===----------------------------------------------------------------------===//
490 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
491 Function &DSCallSite::getCaller() const {
492 return *Inst->getParent()->getParent();
496 //===----------------------------------------------------------------------===//
497 // DSGraph Implementation
498 //===----------------------------------------------------------------------===//
500 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
501 std::map<const DSNode*, DSNodeHandle> NodeMap;
502 RetNode = cloneInto(G, ScalarMap, NodeMap);
505 DSGraph::DSGraph(const DSGraph &G,
506 std::map<const DSNode*, DSNodeHandle> &NodeMap)
508 RetNode = cloneInto(G, ScalarMap, NodeMap);
511 DSGraph::~DSGraph() {
512 FunctionCalls.clear();
513 AuxFunctionCalls.clear();
518 // Drop all intra-node references, so that assertions don't fail...
519 std::for_each(Nodes.begin(), Nodes.end(),
520 std::mem_fun(&DSNode::dropAllReferences));
523 // Delete all of the nodes themselves...
524 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
527 // dump - Allow inspection of graph in a debugger.
528 void DSGraph::dump() const { print(std::cerr); }
531 /// remapLinks - Change all of the Links in the current node according to the
532 /// specified mapping.
534 void DSNode::remapLinks(std::map<const DSNode*, DSNodeHandle> &OldNodeMap) {
535 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
536 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
537 Links[i].setNode(H.getNode());
538 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
543 // cloneInto - Clone the specified DSGraph into the current graph, returning the
544 // Return node of the graph. The translated ScalarMap for the old function is
545 // filled into the OldValMap member. If StripAllocas is set to true, Alloca
546 // markers are removed from the graph, as the graph is being cloned into a
547 // calling function's graph.
549 DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
550 std::map<Value*, DSNodeHandle> &OldValMap,
551 std::map<const DSNode*, DSNodeHandle> &OldNodeMap,
552 unsigned CloneFlags) {
553 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
554 assert(&G != this && "Cannot clone graph into itself!");
556 unsigned FN = Nodes.size(); // First new node...
558 // Duplicate all of the nodes, populating the node map...
559 Nodes.reserve(FN+G.Nodes.size());
560 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
561 DSNode *Old = G.Nodes[i];
562 DSNode *New = new DSNode(*Old);
563 New->NodeType &= ~DSNode::DEAD; // Clear dead flag...
564 Nodes.push_back(New);
565 OldNodeMap[Old] = New;
568 // Rewrite the links in the new nodes to point into the current graph now.
569 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
570 Nodes[i]->remapLinks(OldNodeMap);
572 // Remove alloca markers as specified
573 if (CloneFlags & StripAllocaBit)
574 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
575 Nodes[i]->NodeType &= ~DSNode::AllocaNode;
577 // Copy the value map... and merge all of the global nodes...
578 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
579 E = G.ScalarMap.end(); I != E; ++I) {
580 DSNodeHandle &H = OldValMap[I->first];
581 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
582 H.setNode(MappedNode.getNode());
583 H.setOffset(I->second.getOffset()+MappedNode.getOffset());
585 if (isa<GlobalValue>(I->first)) { // Is this a global?
586 std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
587 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
588 GVI->second.mergeWith(H);
590 ScalarMap[I->first] = H; // Add global pointer to this graph
595 if (!(CloneFlags & DontCloneCallNodes)) {
596 // Copy the function calls list...
597 unsigned FC = FunctionCalls.size(); // FirstCall
598 FunctionCalls.reserve(FC+G.FunctionCalls.size());
599 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
600 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
603 if (!(CloneFlags & DontCloneAuxCallNodes)) {
604 // Copy the auxillary function calls list...
605 unsigned FC = AuxFunctionCalls.size(); // FirstCall
606 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
607 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
608 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
611 // Return the returned node pointer...
612 DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
613 return DSNodeHandle(MappedRet.getNode(),
614 MappedRet.getOffset()+G.RetNode.getOffset());
617 /// mergeInGraph - The method is used for merging graphs together. If the
618 /// argument graph is not *this, it makes a clone of the specified graph, then
619 /// merges the nodes specified in the call site with the formal arguments in the
622 void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
623 unsigned CloneFlags) {
624 std::map<Value*, DSNodeHandle> OldValMap;
626 std::map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
628 // If this is not a recursive call, clone the graph into this graph...
629 if (&Graph != this) {
630 // Clone the callee's graph into the current graph, keeping
631 // track of where scalars in the old graph _used_ to point,
632 // and of the new nodes matching nodes of the old graph.
633 std::map<const DSNode*, DSNodeHandle> OldNodeMap;
635 // The clone call may invalidate any of the vectors in the data
636 // structure graph. Strip locals and don't copy the list of callers
637 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
638 ScalarMap = &OldValMap;
640 RetVal = getRetNode();
641 ScalarMap = &getScalarMap();
644 // Merge the return value with the return value of the context...
645 RetVal.mergeWith(CS.getRetVal());
647 // Resolve all of the function arguments...
648 Function &F = Graph.getFunction();
649 Function::aiterator AI = F.abegin();
650 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
651 // Advance the argument iterator to the first pointer argument...
652 while (!isPointerType(AI->getType())) {
656 std::cerr << "Bad call to Function: " << F.getName() << "\n";
658 assert(AI != F.aend() && "# Args provided is not # Args required!");
661 // Add the link from the argument scalar to the provided value
662 DSNodeHandle &NH = (*ScalarMap)[AI];
663 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
664 NH.mergeWith(CS.getPtrArg(i));
669 // cloneGlobalInto - Clone the given global node and all its target links
670 // (and all their llinks, recursively).
672 DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
673 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
675 // If a clone has already been created for GNode, return it.
676 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
677 if (ValMapEntry != 0)
680 // Clone the node and update the ValMap.
681 DSNode* NewNode = new DSNode(*GNode);
682 ValMapEntry = NewNode; // j=0 case of loop below!
683 Nodes.push_back(NewNode);
684 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
685 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
687 // Rewrite the links in the new node to point into the current graph.
688 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
689 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
696 // markIncompleteNodes - Mark the specified node as having contents that are not
697 // known with the current analysis we have performed. Because a node makes all
698 // of the nodes it can reach imcomplete if the node itself is incomplete, we
699 // must recursively traverse the data structure graph, marking all reachable
700 // nodes as incomplete.
702 static void markIncompleteNode(DSNode *N) {
703 // Stop recursion if no node, or if node already marked...
704 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
706 // Actually mark the node
707 N->NodeType |= DSNode::Incomplete;
709 // Recusively process children...
710 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
711 if (DSNode *DSN = N->getLink(i).getNode())
712 markIncompleteNode(DSN);
716 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
717 // modified by other functions that have not been resolved yet. This marks
718 // nodes that are reachable through three sources of "unknownness":
720 // Global Variables, Function Calls, and Incoming Arguments
722 // For any node that may have unknown components (because something outside the
723 // scope of current analysis may have modified it), the 'Incomplete' flag is
724 // added to the NodeType.
726 void DSGraph::markIncompleteNodes(bool markFormalArgs) {
727 // Mark any incoming arguments as incomplete...
728 if (markFormalArgs && Func)
729 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
730 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
731 markIncompleteNode(ScalarMap[I].getNode());
733 // Mark stuff passed into functions calls as being incomplete...
734 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
735 DSCallSite &Call = FunctionCalls[i];
736 // Then the return value is certainly incomplete!
737 markIncompleteNode(Call.getRetVal().getNode());
739 // All objects pointed to by function arguments are incomplete though!
740 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
741 markIncompleteNode(Call.getPtrArg(i).getNode());
744 // Mark all of the nodes pointed to by global nodes as incomplete...
745 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
746 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
747 DSNode *N = Nodes[i];
748 // FIXME: Make more efficient by looking over Links directly
749 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
750 if (DSNode *DSN = N->getLink(i).getNode())
751 markIncompleteNode(DSN);
755 // removeRefsToGlobal - Helper function that removes globals from the
756 // ScalarMap so that the referrer count will go down to zero.
757 static void removeRefsToGlobal(DSNode* N,
758 std::map<Value*, DSNodeHandle> &ScalarMap) {
759 while (!N->getGlobals().empty()) {
760 GlobalValue *GV = N->getGlobals().back();
761 N->getGlobals().pop_back();
767 // isNodeDead - This method checks to see if a node is dead, and if it isn't, it
768 // checks to see if there are simple transformations that it can do to make it
771 bool DSGraph::isNodeDead(DSNode *N) {
772 // Is it a trivially dead shadow node...
773 if (N->getReferrers().empty() &&
774 (N->NodeType == 0 || N->NodeType == DSNode::DEAD))
777 // Is it a function node or some other trivially unused global?
778 if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
779 N->getReferrers().size() == N->getGlobals().size()) {
781 // Remove the globals from the ScalarMap, so that the referrer count will go
783 removeRefsToGlobal(N, ScalarMap);
784 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
791 static void removeIdenticalCalls(vector<DSCallSite> &Calls,
792 const std::string &where) {
793 // Remove trivially identical function calls
794 unsigned NumFns = Calls.size();
795 std::sort(Calls.begin(), Calls.end());
796 Calls.erase(std::unique(Calls.begin(), Calls.end()),
799 // Track the number of call nodes merged away...
800 NumCallNodesMerged += NumFns-Calls.size();
802 DEBUG(if (NumFns != Calls.size())
803 std::cerr << "Merged " << (NumFns-Calls.size())
804 << " call nodes in " << where << "\n";);
807 // removeTriviallyDeadNodes - After the graph has been constructed, this method
808 // removes all unreachable nodes that are created because they got merged with
809 // other nodes in the graph. These nodes will all be trivially unreachable, so
810 // we don't have to perform any non-trivial analysis here.
812 void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
813 for (unsigned i = 0; i != Nodes.size(); ++i)
814 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
815 if (isNodeDead(Nodes[i])) { // This node is dead!
816 delete Nodes[i]; // Free memory...
817 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
820 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
824 // markAlive - Simple graph walker that recursively traverses the graph, marking
825 // stuff to be alive.
827 static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
831 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
832 if (DSNode *DSN = N->getLink(i).getNode())
833 if (!Alive.count(DSN))
834 markAlive(DSN, Alive);
837 static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
838 std::set<DSNode*> &Visiting) {
839 if (N == 0) return false;
841 if (Visiting.count(N)) return false; // terminate recursion on a cycle
844 // If any immediate successor is alive, N is alive
845 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
846 if (DSNode *DSN = N->getLink(i).getNode())
847 if (Alive.count(DSN)) {
852 // Else if any successor reaches a live node, N is alive
853 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
854 if (DSNode *DSN = N->getLink(i).getNode())
855 if (checkGlobalAlive(DSN, Alive, Visiting)) {
856 Visiting.erase(N); return true;
864 // markGlobalsIteration - Recursive helper function for markGlobalsAlive().
865 // This would be unnecessary if function calls were real nodes! In that case,
866 // the simple iterative loop in the first few lines below suffice.
868 static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
869 vector<DSCallSite> &Calls,
870 std::set<DSNode*> &Alive,
873 // Iterate, marking globals or cast nodes alive until no new live nodes
874 // are added to Alive
875 std::set<DSNode*> Visiting; // Used to identify cycles
876 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
877 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
878 liveCount = Alive.size();
880 if (Alive.count(*I) == 0) {
882 if (checkGlobalAlive(*I, Alive, Visiting))
883 markAlive(*I, Alive);
887 // Find function calls with some dead and some live nodes.
888 // Since all call nodes must be live if any one is live, we have to mark
889 // all nodes of the call as live and continue the iteration (via recursion).
891 bool Recurse = false;
892 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
893 bool CallIsDead = true, CallHasDeadArg = false;
894 DSCallSite &CS = Calls[i];
895 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
896 if (DSNode *N = CS.getPtrArg(j).getNode()) {
897 bool ArgIsDead = !Alive.count(N);
898 CallHasDeadArg |= ArgIsDead;
899 CallIsDead &= ArgIsDead;
902 if (DSNode *N = CS.getRetVal().getNode()) {
903 bool RetIsDead = !Alive.count(N);
904 CallHasDeadArg |= RetIsDead;
905 CallIsDead &= RetIsDead;
908 DSNode *N = CS.getCallee().getNode();
909 bool FnIsDead = !Alive.count(N);
910 CallHasDeadArg |= FnIsDead;
911 CallIsDead &= FnIsDead;
913 if (!CallIsDead && CallHasDeadArg) {
914 // Some node in this call is live and another is dead.
915 // Mark all nodes of call as live and iterate once more.
917 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
918 markAlive(CS.getPtrArg(j).getNode(), Alive);
919 markAlive(CS.getRetVal().getNode(), Alive);
920 markAlive(CS.getCallee().getNode(), Alive);
924 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
929 // markGlobalsAlive - Mark global nodes and cast nodes alive if they
930 // can reach any other live node. Since this can produce new live nodes,
931 // we use a simple iterative algorithm.
933 static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
935 // Add global and cast nodes to a set so we don't walk all nodes every time
936 std::set<DSNode*> GlobalNodes;
937 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
938 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
939 GlobalNodes.insert(G.getNodes()[i]);
941 // Add all call nodes to the same set
942 vector<DSCallSite> &Calls = G.getAuxFunctionCalls();
944 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
945 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
946 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
947 GlobalNodes.insert(N);
948 if (DSNode *N = Calls[i].getRetVal().getNode())
949 GlobalNodes.insert(N);
950 if (DSNode *N = Calls[i].getCallee().getNode())
951 GlobalNodes.insert(N);
955 // Iterate and recurse until no new live node are discovered.
956 // This would be a simple iterative loop if function calls were real nodes!
957 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
959 // Free up references to dead globals from the ScalarMap
960 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
962 if (Alive.count(*I) == 0)
963 removeRefsToGlobal(*I, G.getScalarMap());
965 // Delete dead function calls
967 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
968 bool CallIsDead = true;
969 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
970 CallIsDead && j != ej; ++j)
971 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
973 Calls.erase(Calls.begin() + i); // remove the call entirely
977 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
978 // subgraphs that are unreachable. This often occurs because the data
979 // structure doesn't "escape" into it's caller, and thus should be eliminated
980 // from the caller's graph entirely. This is only appropriate to use when
983 void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
984 assert((!KeepAllGlobals || KeepCalls) && // FIXME: This should be an enum!
985 "KeepAllGlobals without KeepCalls is meaningless");
987 // Reduce the amount of work we have to do...
988 removeTriviallyDeadNodes(KeepAllGlobals);
990 // FIXME: Merge nontrivially identical call nodes...
992 // Alive - a set that holds all nodes found to be reachable/alive.
993 std::set<DSNode*> Alive;
995 // If KeepCalls, mark all nodes reachable by call nodes as alive...
997 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
998 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
999 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
1000 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
1001 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
1003 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i) {
1004 for (unsigned j = 0, e = AuxFunctionCalls[i].getNumPtrArgs(); j != e; ++j)
1005 markAlive(AuxFunctionCalls[i].getPtrArg(j).getNode(), Alive);
1006 markAlive(AuxFunctionCalls[i].getRetVal().getNode(), Alive);
1007 markAlive(AuxFunctionCalls[i].getCallee().getNode(), Alive);
1011 // Mark all nodes reachable by scalar nodes as alive...
1012 for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
1013 E = ScalarMap.end(); I != E; ++I)
1014 markAlive(I->second.getNode(), Alive);
1016 // The return value is alive as well...
1017 markAlive(RetNode.getNode(), Alive);
1019 // Mark all globals or cast nodes that can reach a live node as alive.
1020 // This also marks all nodes reachable from such nodes as alive.
1021 // Of course, if KeepAllGlobals is specified, they would be live already.
1023 if (!KeepAllGlobals)
1024 markGlobalsAlive(*this, Alive, !KeepCalls);
1026 // Loop over all unreachable nodes, dropping their references...
1027 vector<DSNode*> DeadNodes;
1028 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
1029 for (unsigned i = 0; i != Nodes.size(); ++i)
1030 if (!Alive.count(Nodes[i])) {
1031 DSNode *N = Nodes[i];
1032 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
1033 DeadNodes.push_back(N); // Add node to our list of dead nodes
1034 N->dropAllReferences(); // Drop all outgoing edges
1037 // Delete all dead nodes...
1038 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
1043 // maskNodeTypes - Apply a mask to all of the node types in the graph. This
1044 // is useful for clearing out markers like Scalar or Incomplete.
1046 void DSGraph::maskNodeTypes(unsigned char Mask) {
1047 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1048 Nodes[i]->NodeType &= Mask;
1053 //===----------------------------------------------------------------------===//
1054 // GlobalDSGraph Implementation
1055 //===----------------------------------------------------------------------===//
1057 GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
1060 GlobalDSGraph::~GlobalDSGraph() {
1061 assert(Referrers.size() == 0 &&
1062 "Deleting global graph while references from other graphs exist");
1065 void GlobalDSGraph::addReference(const DSGraph* referrer) {
1066 if (referrer != this)
1067 Referrers.insert(referrer);
1070 void GlobalDSGraph::removeReference(const DSGraph* referrer) {
1071 if (referrer != this) {
1072 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
1073 Referrers.erase(referrer);
1074 if (Referrers.size() == 0)
1080 // Bits used in the next function
1081 static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1084 // GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1085 // visible target links (and recursively their such links) into this graph.
1086 // NodeCache maps the node being cloned to its clone in the Globals graph,
1087 // in order to track cycles.
1088 // GlobalsAreFinal is a flag that says whether it is safe to assume that
1089 // an existing global node is complete. This is important to avoid
1090 // reinserting all globals when inserting Calls to functions.
1091 // This is a helper function for cloneGlobals and cloneCalls.
1093 DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1094 std::map<const DSNode*, DSNode*> &NodeCache,
1095 bool GlobalsAreFinal) {
1096 if (OldNode == 0) return 0;
1098 // The caller should check this is an external node. Just more efficient...
1099 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1101 // If a clone has already been created for OldNode, return it.
1102 DSNode*& CacheEntry = NodeCache[OldNode];
1103 if (CacheEntry != 0)
1106 // The result value...
1107 DSNode* NewNode = 0;
1109 // If nodes already exist for any of the globals of OldNode,
1110 // merge all such nodes together since they are merged in OldNode.
1111 // If ValueCacheIsFinal==true, look for an existing node that has
1112 // an identical list of globals and return it if it exists.
1114 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
1115 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
1117 NewNode = PrevNode; // first existing node found
1118 if (GlobalsAreFinal && j == 0)
1119 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1120 CacheEntry = NewNode;
1124 else if (NewNode != PrevNode) { // found another, different from prev
1125 // update ValMap *before* merging PrevNode into NewNode
1126 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
1127 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
1128 NewNode->mergeWith(PrevNode);
1130 } else if (NewNode != 0) {
1131 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
1134 // If no existing node was found, clone the node and update the ValMap.
1136 NewNode = new DSNode(*OldNode);
1137 Nodes.push_back(NewNode);
1138 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1139 NewNode->setLink(j, 0);
1140 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
1141 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
1144 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1146 // Add the entry to NodeCache
1147 CacheEntry = NewNode;
1149 // Rewrite the links in the new node to point into the current graph,
1150 // but only for links to external nodes. Set other links to NULL.
1151 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1152 DSNode* OldTarget = OldNode->getLink(j);
1153 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1154 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1155 if (NewNode->getLink(j))
1156 NewNode->getLink(j)->mergeWith(NewLink);
1158 NewNode->setLink(j, NewLink);
1162 // Remove all local markers
1163 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1169 // GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1170 // visible target links (and recursively their such links) into this graph.
1172 void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1173 std::map<const DSNode*, DSNode*> NodeCache;
1175 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1176 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1177 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
1179 GlobalsGraph->cloneCalls(Graph);
1181 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
1186 // GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1187 // links (and recursively their such links) into this graph.
1189 void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1190 std::map<const DSNode*, DSNode*> NodeCache;
1191 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
1193 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1195 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
1196 DSCallSite& callCopy = FunctionCalls.back();
1197 callCopy.reserve(FromCalls[i].size());
1198 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
1200 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1201 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1205 // remove trivially identical function calls
1206 removeIdenticalCalls(FunctionCalls, "Globals Graph");