1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the core data structure functionality.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Analysis/DSGraphTraits.h"
15 #include "llvm/Function.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/iOther.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "Support/CommandLine.h"
22 #include "Support/Debug.h"
23 #include "Support/DepthFirstIterator.h"
24 #include "Support/STLExtras.h"
25 #include "Support/Statistic.h"
26 #include "Support/Timer.h"
31 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
32 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
33 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
34 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
35 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
36 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
40 #define TIME_REGION(VARNAME, DESC) \
41 NamedRegionTimer VARNAME(DESC)
43 #define TIME_REGION(VARNAME, DESC)
48 DSNode *DSNodeHandle::HandleForwarding() const {
49 assert(N->isForwarding() && "Can only be invoked if forwarding!");
51 // Handle node forwarding here!
52 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
53 Offset += N->ForwardNH.getOffset();
55 if (--N->NumReferrers == 0) {
56 // Removing the last referrer to the node, sever the forwarding link
62 if (N->Size <= Offset) {
63 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
69 //===----------------------------------------------------------------------===//
70 // DSNode Implementation
71 //===----------------------------------------------------------------------===//
73 DSNode::DSNode(const Type *T, DSGraph *G)
74 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
75 // Add the type entry if it is specified...
76 if (T) mergeTypeInfo(T, 0);
77 if (G) G->addNode(this);
81 // DSNode copy constructor... do not copy over the referrers list!
82 DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
83 : NumReferrers(0), Size(N.Size), ParentGraph(G),
84 Ty(N.Ty), NodeType(N.NodeType) {
89 Links.resize(N.Links.size()); // Create the appropriate number of null links
94 /// getTargetData - Get the target data object used to construct this node.
96 const TargetData &DSNode::getTargetData() const {
97 return ParentGraph->getTargetData();
100 void DSNode::assertOK() const {
101 assert((Ty != Type::VoidTy ||
102 Ty == Type::VoidTy && (Size == 0 ||
103 (NodeType & DSNode::Array))) &&
106 assert(ParentGraph && "Node has no parent?");
107 const DSScalarMap &SM = ParentGraph->getScalarMap();
108 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
109 assert(SM.count(Globals[i]));
110 assert(SM.find(Globals[i])->second.getNode() == this);
114 /// forwardNode - Mark this node as being obsolete, and all references to it
115 /// should be forwarded to the specified node and offset.
117 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
118 assert(this != To && "Cannot forward a node to itself!");
119 assert(ForwardNH.isNull() && "Already forwarding from this node!");
120 if (To->Size <= 1) Offset = 0;
121 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
122 "Forwarded offset is wrong!");
123 ForwardNH.setNode(To);
124 ForwardNH.setOffset(Offset);
129 // Remove this node from the parent graph's Nodes list.
130 ParentGraph->unlinkNode(this);
134 // addGlobal - Add an entry for a global value to the Globals list. This also
135 // marks the node with the 'G' flag if it does not already have it.
137 void DSNode::addGlobal(GlobalValue *GV) {
138 // Keep the list sorted.
139 std::vector<GlobalValue*>::iterator I =
140 std::lower_bound(Globals.begin(), Globals.end(), GV);
142 if (I == Globals.end() || *I != GV) {
143 //assert(GV->getType()->getElementType() == Ty);
144 Globals.insert(I, GV);
145 NodeType |= GlobalNode;
149 /// foldNodeCompletely - If we determine that this node has some funny
150 /// behavior happening to it that we cannot represent, we fold it down to a
151 /// single, completely pessimistic, node. This node is represented as a
152 /// single byte with a single TypeEntry of "void".
154 void DSNode::foldNodeCompletely() {
155 if (isNodeCompletelyFolded()) return; // If this node is already folded...
159 // If this node has a size that is <= 1, we don't need to create a forwarding
161 if (getSize() <= 1) {
162 NodeType |= DSNode::Array;
165 assert(Links.size() <= 1 && "Size is 1, but has more links?");
168 // Create the node we are going to forward to. This is required because
169 // some referrers may have an offset that is > 0. By forcing them to
170 // forward, the forwarder has the opportunity to correct the offset.
171 DSNode *DestNode = new DSNode(0, ParentGraph);
172 DestNode->NodeType = NodeType|DSNode::Array;
173 DestNode->Ty = Type::VoidTy;
175 DestNode->Globals.swap(Globals);
177 // Start forwarding to the destination node...
178 forwardNode(DestNode, 0);
180 if (!Links.empty()) {
181 DestNode->Links.reserve(1);
183 DSNodeHandle NH(DestNode);
184 DestNode->Links.push_back(Links[0]);
186 // If we have links, merge all of our outgoing links together...
187 for (unsigned i = Links.size()-1; i != 0; --i)
188 NH.getNode()->Links[0].mergeWith(Links[i]);
191 DestNode->Links.resize(1);
196 /// isNodeCompletelyFolded - Return true if this node has been completely
197 /// folded down to something that can never be expanded, effectively losing
198 /// all of the field sensitivity that may be present in the node.
200 bool DSNode::isNodeCompletelyFolded() const {
201 return getSize() == 1 && Ty == Type::VoidTy && isArray();
205 /// TypeElementWalker Class - Used for implementation of physical subtyping...
207 class TypeElementWalker {
212 StackState(const Type *T, unsigned Off = 0)
213 : Ty(T), Offset(Off), Idx(0) {}
216 std::vector<StackState> Stack;
217 const TargetData &TD;
219 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
224 bool isDone() const { return Stack.empty(); }
225 const Type *getCurrentType() const { return Stack.back().Ty; }
226 unsigned getCurrentOffset() const { return Stack.back().Offset; }
228 void StepToNextType() {
229 PopStackAndAdvance();
234 /// PopStackAndAdvance - Pop the current element off of the stack and
235 /// advance the underlying element to the next contained member.
236 void PopStackAndAdvance() {
237 assert(!Stack.empty() && "Cannot pop an empty stack!");
239 while (!Stack.empty()) {
240 StackState &SS = Stack.back();
241 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
243 if (SS.Idx != ST->getNumElements()) {
244 const StructLayout *SL = TD.getStructLayout(ST);
245 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
248 Stack.pop_back(); // At the end of the structure
250 const ArrayType *AT = cast<ArrayType>(SS.Ty);
252 if (SS.Idx != AT->getNumElements()) {
253 SS.Offset += TD.getTypeSize(AT->getElementType());
256 Stack.pop_back(); // At the end of the array
261 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
262 /// on the type stack.
264 if (Stack.empty()) return;
265 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
266 StackState &SS = Stack.back();
267 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
268 if (ST->getNumElements() == 0) {
270 PopStackAndAdvance();
272 // Step into the structure...
273 assert(SS.Idx < ST->getNumElements());
274 const StructLayout *SL = TD.getStructLayout(ST);
275 Stack.push_back(StackState(ST->getElementType(SS.Idx),
276 SS.Offset+SL->MemberOffsets[SS.Idx]));
279 const ArrayType *AT = cast<ArrayType>(SS.Ty);
280 if (AT->getNumElements() == 0) {
282 PopStackAndAdvance();
284 // Step into the array...
285 assert(SS.Idx < AT->getNumElements());
286 Stack.push_back(StackState(AT->getElementType(),
288 TD.getTypeSize(AT->getElementType())));
294 } // end anonymous namespace
296 /// ElementTypesAreCompatible - Check to see if the specified types are
297 /// "physically" compatible. If so, return true, else return false. We only
298 /// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
299 /// is true, then we also allow a larger T1.
301 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
302 bool AllowLargerT1, const TargetData &TD){
303 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
305 while (!T1W.isDone() && !T2W.isDone()) {
306 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
309 const Type *T1 = T1W.getCurrentType();
310 const Type *T2 = T2W.getCurrentType();
311 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
314 T1W.StepToNextType();
315 T2W.StepToNextType();
318 return AllowLargerT1 || T1W.isDone();
322 /// mergeTypeInfo - This method merges the specified type into the current node
323 /// at the specified offset. This may update the current node's type record if
324 /// this gives more information to the node, it may do nothing to the node if
325 /// this information is already known, or it may merge the node completely (and
326 /// return true) if the information is incompatible with what is already known.
328 /// This method returns true if the node is completely folded, otherwise false.
330 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
331 bool FoldIfIncompatible) {
332 const TargetData &TD = getTargetData();
333 // Check to make sure the Size member is up-to-date. Size can be one of the
335 // Size = 0, Ty = Void: Nothing is known about this node.
336 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
337 // Size = 1, Ty = Void, Array = 1: The node is collapsed
338 // Otherwise, sizeof(Ty) = Size
340 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
341 (Size == 0 && !Ty->isSized() && !isArray()) ||
342 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
343 (Size == 0 && !Ty->isSized() && !isArray()) ||
344 (TD.getTypeSize(Ty) == Size)) &&
345 "Size member of DSNode doesn't match the type structure!");
346 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
348 if (Offset == 0 && NewTy == Ty)
349 return false; // This should be a common case, handle it efficiently
351 // Return true immediately if the node is completely folded.
352 if (isNodeCompletelyFolded()) return true;
354 // If this is an array type, eliminate the outside arrays because they won't
355 // be used anyway. This greatly reduces the size of large static arrays used
356 // as global variables, for example.
358 bool WillBeArray = false;
359 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
360 // FIXME: we might want to keep small arrays, but must be careful about
361 // things like: [2 x [10000 x int*]]
362 NewTy = AT->getElementType();
366 // Figure out how big the new type we're merging in is...
367 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
369 // Otherwise check to see if we can fold this type into the current node. If
370 // we can't, we fold the node completely, if we can, we potentially update our
373 if (Ty == Type::VoidTy) {
374 // If this is the first type that this node has seen, just accept it without
376 assert(Offset == 0 && !isArray() &&
377 "Cannot have an offset into a void node!");
380 if (WillBeArray) NodeType |= Array;
383 // Calculate the number of outgoing links from this node.
384 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
388 // Handle node expansion case here...
389 if (Offset+NewTySize > Size) {
390 // It is illegal to grow this node if we have treated it as an array of
393 if (FoldIfIncompatible) foldNodeCompletely();
397 if (Offset) { // We could handle this case, but we don't for now...
398 std::cerr << "UNIMP: Trying to merge a growth type into "
399 << "offset != 0: Collapsing!\n";
400 if (FoldIfIncompatible) foldNodeCompletely();
404 // Okay, the situation is nice and simple, we are trying to merge a type in
405 // at offset 0 that is bigger than our current type. Implement this by
406 // switching to the new type and then merge in the smaller one, which should
407 // hit the other code path here. If the other code path decides it's not
408 // ok, it will collapse the node as appropriate.
410 const Type *OldTy = Ty;
413 if (WillBeArray) NodeType |= Array;
416 // Must grow links to be the appropriate size...
417 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
419 // Merge in the old type now... which is guaranteed to be smaller than the
421 return mergeTypeInfo(OldTy, 0);
424 assert(Offset <= Size &&
425 "Cannot merge something into a part of our type that doesn't exist!");
427 // Find the section of Ty that NewTy overlaps with... first we find the
428 // type that starts at offset Offset.
431 const Type *SubType = Ty;
433 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
435 switch (SubType->getPrimitiveID()) {
436 case Type::StructTyID: {
437 const StructType *STy = cast<StructType>(SubType);
438 const StructLayout &SL = *TD.getStructLayout(STy);
440 unsigned i = 0, e = SL.MemberOffsets.size();
441 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
444 // The offset we are looking for must be in the i'th element...
445 SubType = STy->getElementType(i);
446 O += SL.MemberOffsets[i];
449 case Type::ArrayTyID: {
450 SubType = cast<ArrayType>(SubType)->getElementType();
451 unsigned ElSize = TD.getTypeSize(SubType);
452 unsigned Remainder = (Offset-O) % ElSize;
453 O = Offset-Remainder;
457 if (FoldIfIncompatible) foldNodeCompletely();
462 assert(O == Offset && "Could not achieve the correct offset!");
464 // If we found our type exactly, early exit
465 if (SubType == NewTy) return false;
467 // Differing function types don't require us to merge. They are not values anyway.
468 if (isa<FunctionType>(SubType) &&
469 isa<FunctionType>(NewTy)) return false;
471 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
473 // Ok, we are getting desperate now. Check for physical subtyping, where we
474 // just require each element in the node to be compatible.
475 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
476 SubTypeSize && SubTypeSize < 256 &&
477 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
480 // Okay, so we found the leader type at the offset requested. Search the list
481 // of types that starts at this offset. If SubType is currently an array or
482 // structure, the type desired may actually be the first element of the
485 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
486 while (SubType != NewTy) {
487 const Type *NextSubType = 0;
488 unsigned NextSubTypeSize = 0;
489 unsigned NextPadSize = 0;
490 switch (SubType->getPrimitiveID()) {
491 case Type::StructTyID: {
492 const StructType *STy = cast<StructType>(SubType);
493 const StructLayout &SL = *TD.getStructLayout(STy);
494 if (SL.MemberOffsets.size() > 1)
495 NextPadSize = SL.MemberOffsets[1];
497 NextPadSize = SubTypeSize;
498 NextSubType = STy->getElementType(0);
499 NextSubTypeSize = TD.getTypeSize(NextSubType);
502 case Type::ArrayTyID:
503 NextSubType = cast<ArrayType>(SubType)->getElementType();
504 NextSubTypeSize = TD.getTypeSize(NextSubType);
505 NextPadSize = NextSubTypeSize;
511 if (NextSubType == 0)
512 break; // In the default case, break out of the loop
514 if (NextPadSize < NewTySize)
515 break; // Don't allow shrinking to a smaller type than NewTySize
516 SubType = NextSubType;
517 SubTypeSize = NextSubTypeSize;
518 PadSize = NextPadSize;
521 // If we found the type exactly, return it...
522 if (SubType == NewTy)
525 // Check to see if we have a compatible, but different type...
526 if (NewTySize == SubTypeSize) {
527 // Check to see if this type is obviously convertible... int -> uint f.e.
528 if (NewTy->isLosslesslyConvertibleTo(SubType))
531 // Check to see if we have a pointer & integer mismatch going on here,
532 // loading a pointer as a long, for example.
534 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
535 NewTy->isInteger() && isa<PointerType>(SubType))
537 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
538 // We are accessing the field, plus some structure padding. Ignore the
539 // structure padding.
544 if (getParentGraph()->getReturnNodes().size())
545 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
546 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
547 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
548 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
550 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
552 if (FoldIfIncompatible) foldNodeCompletely();
558 // addEdgeTo - Add an edge from the current node to the specified node. This
559 // can cause merging of nodes in the graph.
561 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
562 if (NH.isNull()) return; // Nothing to do
564 DSNodeHandle &ExistingEdge = getLink(Offset);
565 if (!ExistingEdge.isNull()) {
566 // Merge the two nodes...
567 ExistingEdge.mergeWith(NH);
568 } else { // No merging to perform...
569 setLink(Offset, NH); // Just force a link in there...
574 // MergeSortedVectors - Efficiently merge a vector into another vector where
575 // duplicates are not allowed and both are sorted. This assumes that 'T's are
576 // efficiently copyable and have sane comparison semantics.
578 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
579 const std::vector<GlobalValue*> &Src) {
580 // By far, the most common cases will be the simple ones. In these cases,
581 // avoid having to allocate a temporary vector...
583 if (Src.empty()) { // Nothing to merge in...
585 } else if (Dest.empty()) { // Just copy the result in...
587 } else if (Src.size() == 1) { // Insert a single element...
588 const GlobalValue *V = Src[0];
589 std::vector<GlobalValue*>::iterator I =
590 std::lower_bound(Dest.begin(), Dest.end(), V);
591 if (I == Dest.end() || *I != Src[0]) // If not already contained...
592 Dest.insert(I, Src[0]);
593 } else if (Dest.size() == 1) {
594 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
595 Dest = Src; // Copy over list...
596 std::vector<GlobalValue*>::iterator I =
597 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
598 if (I == Dest.end() || *I != Tmp) // If not already contained...
602 // Make a copy to the side of Dest...
603 std::vector<GlobalValue*> Old(Dest);
605 // Make space for all of the type entries now...
606 Dest.resize(Dest.size()+Src.size());
608 // Merge the two sorted ranges together... into Dest.
609 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
611 // Now erase any duplicate entries that may have accumulated into the
612 // vectors (because they were in both of the input sets)
613 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
617 void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
618 MergeSortedVectors(Globals, RHS);
621 // MergeNodes - Helper function for DSNode::mergeWith().
622 // This function does the hard work of merging two nodes, CurNodeH
623 // and NH after filtering out trivial cases and making sure that
624 // CurNodeH.offset >= NH.offset.
627 // Since merging may cause either node to go away, we must always
628 // use the node-handles to refer to the nodes. These node handles are
629 // automatically updated during merging, so will always provide access
630 // to the correct node after a merge.
632 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
633 assert(CurNodeH.getOffset() >= NH.getOffset() &&
634 "This should have been enforced in the caller.");
635 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
636 "Cannot merge two nodes that are not in the same graph!");
638 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
639 // respect to NH.Offset) is now zero. NOffset is the distance from the base
640 // of our object that N starts from.
642 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
643 unsigned NSize = NH.getNode()->getSize();
645 // If the two nodes are of different size, and the smaller node has the array
646 // bit set, collapse!
647 if (NSize != CurNodeH.getNode()->getSize()) {
648 if (NSize < CurNodeH.getNode()->getSize()) {
649 if (NH.getNode()->isArray())
650 NH.getNode()->foldNodeCompletely();
651 } else if (CurNodeH.getNode()->isArray()) {
652 NH.getNode()->foldNodeCompletely();
656 // Merge the type entries of the two nodes together...
657 if (NH.getNode()->Ty != Type::VoidTy)
658 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
659 assert(!CurNodeH.getNode()->isDeadNode());
661 // If we are merging a node with a completely folded node, then both nodes are
662 // now completely folded.
664 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
665 if (!NH.getNode()->isNodeCompletelyFolded()) {
666 NH.getNode()->foldNodeCompletely();
667 assert(NH.getNode() && NH.getOffset() == 0 &&
668 "folding did not make offset 0?");
669 NOffset = NH.getOffset();
670 NSize = NH.getNode()->getSize();
671 assert(NOffset == 0 && NSize == 1);
673 } else if (NH.getNode()->isNodeCompletelyFolded()) {
674 CurNodeH.getNode()->foldNodeCompletely();
675 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
676 "folding did not make offset 0?");
677 NOffset = NH.getOffset();
678 NSize = NH.getNode()->getSize();
679 assert(NOffset == 0 && NSize == 1);
682 DSNode *N = NH.getNode();
683 if (CurNodeH.getNode() == N || N == 0) return;
684 assert(!CurNodeH.getNode()->isDeadNode());
686 // Merge the NodeType information.
687 CurNodeH.getNode()->NodeType |= N->NodeType;
689 // Start forwarding to the new node!
690 N->forwardNode(CurNodeH.getNode(), NOffset);
691 assert(!CurNodeH.getNode()->isDeadNode());
693 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
695 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
696 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
697 if (Link.getNode()) {
698 // Compute the offset into the current node at which to
699 // merge this link. In the common case, this is a linear
700 // relation to the offset in the original node (with
701 // wrapping), but if the current node gets collapsed due to
702 // recursive merging, we must make sure to merge in all remaining
703 // links at offset zero.
704 unsigned MergeOffset = 0;
705 DSNode *CN = CurNodeH.getNode();
707 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
708 CN->addEdgeTo(MergeOffset, Link);
712 // Now that there are no outgoing edges, all of the Links are dead.
715 // Merge the globals list...
716 if (!N->Globals.empty()) {
717 CurNodeH.getNode()->mergeGlobals(N->Globals);
719 // Delete the globals from the old node...
720 std::vector<GlobalValue*>().swap(N->Globals);
725 // mergeWith - Merge this node and the specified node, moving all links to and
726 // from the argument node into the current node, deleting the node argument.
727 // Offset indicates what offset the specified node is to be merged into the
730 // The specified node may be a null pointer (in which case, we update it to
731 // point to this node).
733 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
734 DSNode *N = NH.getNode();
735 if (N == this && NH.getOffset() == Offset)
738 // If the RHS is a null node, make it point to this node!
740 NH.mergeWith(DSNodeHandle(this, Offset));
744 assert(!N->isDeadNode() && !isDeadNode());
745 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
748 // We cannot merge two pieces of the same node together, collapse the node
750 DEBUG(std::cerr << "Attempting to merge two chunks of"
751 << " the same node together!\n");
752 foldNodeCompletely();
756 // If both nodes are not at offset 0, make sure that we are merging the node
757 // at an later offset into the node with the zero offset.
759 if (Offset < NH.getOffset()) {
760 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
762 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
763 // If the offsets are the same, merge the smaller node into the bigger node
764 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
768 // Ok, now we can merge the two nodes. Use a static helper that works with
769 // two node handles, since "this" may get merged away at intermediate steps.
770 DSNodeHandle CurNodeH(this, Offset);
771 DSNodeHandle NHCopy(NH);
772 DSNode::MergeNodes(CurNodeH, NHCopy);
776 //===----------------------------------------------------------------------===//
777 // ReachabilityCloner Implementation
778 //===----------------------------------------------------------------------===//
780 DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
781 if (SrcNH.isNull()) return DSNodeHandle();
782 const DSNode *SN = SrcNH.getNode();
784 DSNodeHandle &NH = NodeMap[SN];
785 if (!NH.isNull()) // Node already mapped?
786 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
788 // If SrcNH has globals and the destination graph has one of the same globals,
789 // merge this node with the destination node, which is much more efficient.
790 if (SN->global_begin() != SN->global_end()) {
791 DSScalarMap &DestSM = Dest.getScalarMap();
792 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
794 GlobalValue *GV = *I;
795 DSScalarMap::iterator GI = DestSM.find(GV);
796 if (GI != DestSM.end() && !GI->second.isNull()) {
797 // We found one, use merge instead!
798 merge(GI->second, Src.getNodeForValue(GV));
799 assert(!NH.isNull() && "Didn't merge node!");
800 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
805 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
806 DN->maskNodeTypes(BitsToKeep);
809 // Next, recursively clone all outgoing links as necessary. Note that
810 // adding these links can cause the node to collapse itself at any time, and
811 // the current node may be merged with arbitrary other nodes. For this
812 // reason, we must always go through NH.
814 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
815 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
816 if (!SrcEdge.isNull()) {
817 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
818 // Compute the offset into the current node at which to
819 // merge this link. In the common case, this is a linear
820 // relation to the offset in the original node (with
821 // wrapping), but if the current node gets collapsed due to
822 // recursive merging, we must make sure to merge in all remaining
823 // links at offset zero.
824 unsigned MergeOffset = 0;
825 DSNode *CN = NH.getNode();
826 if (CN->getSize() != 1)
827 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()
828 - SrcNH.getOffset()) %CN->getSize();
829 CN->addEdgeTo(MergeOffset, DestEdge);
833 // If this node contains any globals, make sure they end up in the scalar
834 // map with the correct offset.
835 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
837 GlobalValue *GV = *I;
838 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
839 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
840 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
841 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
842 DestGNH.getOffset()+SrcGNH.getOffset()));
844 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
845 Dest.getInlinedGlobals().insert(GV);
847 NH.getNode()->mergeGlobals(SN->getGlobals());
849 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
852 void ReachabilityCloner::merge(const DSNodeHandle &NH,
853 const DSNodeHandle &SrcNH) {
854 if (SrcNH.isNull()) return; // Noop
856 // If there is no destination node, just clone the source and assign the
857 // destination node to be it.
858 NH.mergeWith(getClonedNH(SrcNH));
862 // Okay, at this point, we know that we have both a destination and a source
863 // node that need to be merged. Check to see if the source node has already
865 const DSNode *SN = SrcNH.getNode();
866 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
867 if (!SCNH.isNull()) { // Node already cloned?
868 NH.mergeWith(DSNodeHandle(SCNH.getNode(),
869 SCNH.getOffset()+SrcNH.getOffset()));
871 return; // Nothing to do!
874 // Okay, so the source node has not already been cloned. Instead of creating
875 // a new DSNode, only to merge it into the one we already have, try to perform
876 // the merge in-place. The only case we cannot handle here is when the offset
877 // into the existing node is less than the offset into the virtual node we are
878 // merging in. In this case, we have to extend the existing node, which
879 // requires an allocation anyway.
880 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
881 if (NH.getOffset() >= SrcNH.getOffset()) {
882 if (!DN->isNodeCompletelyFolded()) {
883 // Make sure the destination node is folded if the source node is folded.
884 if (SN->isNodeCompletelyFolded()) {
885 DN->foldNodeCompletely();
887 } else if (SN->getSize() != DN->getSize()) {
888 // If the two nodes are of different size, and the smaller node has the
889 // array bit set, collapse!
890 if (SN->getSize() < DN->getSize()) {
892 DN->foldNodeCompletely();
895 } else if (DN->isArray()) {
896 DN->foldNodeCompletely();
901 // Merge the type entries of the two nodes together...
902 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
903 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
908 assert(!DN->isDeadNode());
910 // Merge the NodeType information.
911 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
913 // Before we start merging outgoing links and updating the scalar map, make
914 // sure it is known that this is the representative node for the src node.
915 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
917 // If the source node contains any globals, make sure they end up in the
918 // scalar map with the correct offset.
919 if (SN->global_begin() != SN->global_end()) {
920 // Update the globals in the destination node itself.
921 DN->mergeGlobals(SN->getGlobals());
923 // Update the scalar map for the graph we are merging the source node
925 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
927 GlobalValue *GV = *I;
928 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
929 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
930 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
931 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
932 DestGNH.getOffset()+SrcGNH.getOffset()));
934 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
935 Dest.getInlinedGlobals().insert(GV);
937 NH.getNode()->mergeGlobals(SN->getGlobals());
940 // We cannot handle this case without allocating a temporary node. Fall
941 // back on being simple.
942 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
943 NewDN->maskNodeTypes(BitsToKeep);
945 unsigned NHOffset = NH.getOffset();
946 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
948 assert(NH.getNode() &&
949 (NH.getOffset() > NHOffset ||
950 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
951 "Merging did not adjust the offset!");
953 // Before we start merging outgoing links and updating the scalar map, make
954 // sure it is known that this is the representative node for the src node.
955 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
957 // If the source node contained any globals, make sure to create entries
958 // in the scalar map for them!
959 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
961 GlobalValue *GV = *I;
962 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
963 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
964 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
965 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
966 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
967 DestGNH.getOffset()+SrcGNH.getOffset()));
969 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
970 Dest.getInlinedGlobals().insert(GV);
975 // Next, recursively merge all outgoing links as necessary. Note that
976 // adding these links can cause the destination node to collapse itself at
977 // any time, and the current node may be merged with arbitrary other nodes.
978 // For this reason, we must always go through NH.
980 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
981 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
982 if (!SrcEdge.isNull()) {
983 // Compute the offset into the current node at which to
984 // merge this link. In the common case, this is a linear
985 // relation to the offset in the original node (with
986 // wrapping), but if the current node gets collapsed due to
987 // recursive merging, we must make sure to merge in all remaining
988 // links at offset zero.
989 DSNode *CN = SCNH.getNode();
990 unsigned MergeOffset =
991 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
993 DSNodeHandle Tmp = CN->getLink(MergeOffset);
995 // Perform the recursive merging. Make sure to create a temporary NH,
996 // because the Link can disappear in the process of recursive merging.
999 Tmp.mergeWith(getClonedNH(SrcEdge));
1000 // Merging this could cause all kinds of recursive things to happen,
1001 // culminating in the current node being eliminated. Since this is
1002 // possible, make sure to reaquire the link from 'CN'.
1004 unsigned MergeOffset = 0;
1005 CN = SCNH.getNode();
1006 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1007 CN->getLink(MergeOffset).mergeWith(Tmp);
1013 /// mergeCallSite - Merge the nodes reachable from the specified src call
1014 /// site into the nodes reachable from DestCS.
1015 void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
1016 const DSCallSite &SrcCS) {
1017 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1018 unsigned MinArgs = DestCS.getNumPtrArgs();
1019 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1021 for (unsigned a = 0; a != MinArgs; ++a)
1022 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1026 //===----------------------------------------------------------------------===//
1027 // DSCallSite Implementation
1028 //===----------------------------------------------------------------------===//
1030 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
1031 Function &DSCallSite::getCaller() const {
1032 return *Site.getInstruction()->getParent()->getParent();
1035 void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1036 ReachabilityCloner &RC) {
1037 NH = RC.getClonedNH(Src);
1040 //===----------------------------------------------------------------------===//
1041 // DSGraph Implementation
1042 //===----------------------------------------------------------------------===//
1044 /// getFunctionNames - Return a space separated list of the name of the
1045 /// functions in this graph (if any)
1046 std::string DSGraph::getFunctionNames() const {
1047 switch (getReturnNodes().size()) {
1048 case 0: return "Globals graph";
1049 case 1: return getReturnNodes().begin()->first->getName();
1052 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1053 I != getReturnNodes().end(); ++I)
1054 Return += I->first->getName() + " ";
1055 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1061 DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
1062 PrintAuxCalls = false;
1064 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1067 DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
1068 : GlobalsGraph(0), TD(G.TD) {
1069 PrintAuxCalls = false;
1070 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1073 DSGraph::~DSGraph() {
1074 FunctionCalls.clear();
1075 AuxFunctionCalls.clear();
1076 InlinedGlobals.clear();
1078 ReturnNodes.clear();
1080 // Drop all intra-node references, so that assertions don't fail...
1081 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1082 (*NI)->dropAllReferences();
1084 // Free all of the nodes.
1088 // dump - Allow inspection of graph in a debugger.
1089 void DSGraph::dump() const { print(std::cerr); }
1092 /// remapLinks - Change all of the Links in the current node according to the
1093 /// specified mapping.
1095 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
1096 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1097 if (DSNode *N = Links[i].getNode()) {
1098 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1099 if (ONMI != OldNodeMap.end()) {
1100 Links[i].setNode(ONMI->second.getNode());
1101 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1106 /// updateFromGlobalGraph - This function rematerializes global nodes and
1107 /// nodes reachable from them from the globals graph into the current graph.
1108 /// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1109 /// are already up-to-date in the current graph. In practice, in the TD pass,
1110 /// this is likely to be a large fraction of the live global nodes in each
1111 /// function (since most live nodes are likely to have been brought up-to-date
1112 /// in at _some_ caller or callee).
1114 void DSGraph::updateFromGlobalGraph() {
1115 TIME_REGION(X, "updateFromGlobalGraph");
1116 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1118 // Clone the non-up-to-date global nodes into this graph.
1119 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1120 E = getScalarMap().global_end(); I != E; ++I)
1121 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
1122 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
1123 if (It != GlobalsGraph->ScalarMap.end())
1124 RC.merge(getNodeForValue(*I), It->second);
1128 /// cloneInto - Clone the specified DSGraph into the current graph. The
1129 /// translated ScalarMap for the old function is filled into the OldValMap
1130 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
1132 /// The CloneFlags member controls various aspects of the cloning process.
1134 void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
1135 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1136 unsigned CloneFlags) {
1137 TIME_REGION(X, "cloneInto");
1138 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
1139 assert(&G != this && "Cannot clone graph into itself!");
1141 // Remove alloca or mod/ref bits as specified...
1142 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1143 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1144 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1145 BitsToClear |= DSNode::DEAD; // Clear dead flag...
1147 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1148 assert(!(*I)->isForwarding() &&
1149 "Forward nodes shouldn't be in node list!");
1150 DSNode *New = new DSNode(**I, this);
1151 New->maskNodeTypes(~BitsToClear);
1152 OldNodeMap[*I] = New;
1156 Timer::addPeakMemoryMeasurement();
1159 // Rewrite the links in the new nodes to point into the current graph now.
1160 // Note that we don't loop over the node's list to do this. The problem is
1161 // that remaping links can cause recursive merging to happen, which means
1162 // that node_iterator's can get easily invalidated! Because of this, we
1163 // loop over the OldNodeMap, which contains all of the new nodes as the
1164 // .second element of the map elements. Also note that if we remap a node
1165 // more than once, we won't break anything.
1166 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1168 I->second.getNode()->remapLinks(OldNodeMap);
1170 // Copy the scalar map... merging all of the global nodes...
1171 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
1172 E = G.ScalarMap.end(); I != E; ++I) {
1173 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
1174 DSNodeHandle &H = OldValMap[I->first];
1175 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1176 I->second.getOffset()+MappedNode.getOffset()));
1178 // If this is a global, add the global to this fn or merge if already exists
1179 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1180 ScalarMap[GV].mergeWith(H);
1181 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1182 InlinedGlobals.insert(GV);
1186 if (!(CloneFlags & DontCloneCallNodes)) {
1187 // Copy the function calls list...
1188 unsigned FC = FunctionCalls.size(); // FirstCall
1189 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1190 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1191 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
1194 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1195 // Copy the auxiliary function calls list...
1196 unsigned FC = AuxFunctionCalls.size(); // FirstCall
1197 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1198 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1199 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1202 // Map the return node pointers over...
1203 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1204 E = G.getReturnNodes().end(); I != E; ++I) {
1205 const DSNodeHandle &Ret = I->second;
1206 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1207 OldReturnNodes.insert(std::make_pair(I->first,
1208 DSNodeHandle(MappedRet.getNode(),
1209 MappedRet.getOffset()+Ret.getOffset())));
1213 static bool PathExistsToClonedNode(const DSNode *N, ReachabilityCloner &RC) {
1215 for (df_iterator<const DSNode*> I = df_begin(N), E = df_end(N); I != E; ++I)
1216 if (RC.hasClonedNode(*I))
1221 static bool PathExistsToClonedNode(const DSCallSite &CS,
1222 ReachabilityCloner &RC) {
1223 if (PathExistsToClonedNode(CS.getRetVal().getNode(), RC))
1225 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1226 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode(), RC))
1231 /// mergeInGraph - The method is used for merging graphs together. If the
1232 /// argument graph is not *this, it makes a clone of the specified graph, then
1233 /// merges the nodes specified in the call site with the formal arguments in the
1236 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1237 const DSGraph &Graph, unsigned CloneFlags) {
1238 TIME_REGION(X, "mergeInGraph");
1240 // Fastpath for a noop inline.
1241 if (CS.getNumPtrArgs() == 0 && CS.getRetVal().isNull())
1244 // If this is not a recursive call, clone the graph into this graph...
1245 if (&Graph != this) {
1246 // Clone the callee's graph into the current graph, keeping track of where
1247 // scalars in the old graph _used_ to point, and of the new nodes matching
1248 // nodes of the old graph.
1249 ReachabilityCloner RC(*this, Graph, CloneFlags);
1251 // Set up argument bindings
1252 Function::aiterator AI = F.abegin();
1253 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1254 // Advance the argument iterator to the first pointer argument...
1255 while (AI != F.aend() && !isPointerType(AI->getType())) {
1257 #ifndef NDEBUG // FIXME: We should merge vararg arguments!
1258 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
1259 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1262 if (AI == F.aend()) break;
1264 // Add the link from the argument scalar to the provided value.
1265 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
1268 // Map the return node pointer over.
1269 if (!CS.getRetVal().isNull())
1270 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1272 // If requested, copy all of the calls.
1273 if (!(CloneFlags & DontCloneCallNodes)) {
1274 // Copy the function calls list...
1275 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1276 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1277 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1280 // If the user has us copying aux calls (the normal case), set up a data
1281 // structure to keep track of which ones we've copied over.
1282 std::vector<bool> CopiedAuxCall;
1283 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1284 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1285 Graph.AuxFunctionCalls.size());
1286 CopiedAuxCall.resize(Graph.AuxFunctionCalls.size());
1289 // Clone over all globals that appear in the caller and callee graphs.
1290 hash_set<GlobalVariable*> NonCopiedGlobals;
1291 for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1292 E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1293 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1294 if (ScalarMap.count(GV))
1295 RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
1297 NonCopiedGlobals.insert(GV);
1299 // If the global does not appear in the callers graph we generally don't
1300 // want to copy the node. However, if there is a path from the node global
1301 // node to a node that we did copy in the graph, we *must* copy it to
1302 // maintain the connection information. Every time we decide to include a
1303 // new global, this might make other globals live, so we must iterate
1305 bool MadeChange = true;
1306 while (MadeChange) {
1308 for (hash_set<GlobalVariable*>::iterator I = NonCopiedGlobals.begin();
1309 I != NonCopiedGlobals.end();) {
1310 DSNode *GlobalNode = Graph.getNodeForValue(*I).getNode();
1311 if (RC.hasClonedNode(GlobalNode)) {
1312 // Already cloned it, remove from set.
1313 NonCopiedGlobals.erase(I++);
1315 } else if (PathExistsToClonedNode(GlobalNode, RC)) {
1316 RC.getClonedNH(Graph.getNodeForValue(*I));
1317 NonCopiedGlobals.erase(I++);
1324 // If requested, copy any aux calls that can reach copied nodes.
1325 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1326 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1327 if (!CopiedAuxCall[i] &&
1328 PathExistsToClonedNode(Graph.AuxFunctionCalls[i], RC)) {
1329 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i],
1331 CopiedAuxCall[i] = true;
1338 DSNodeHandle RetVal = getReturnNodeFor(F);
1340 // Merge the return value with the return value of the context...
1341 RetVal.mergeWith(CS.getRetVal());
1343 // Resolve all of the function arguments...
1344 Function::aiterator AI = F.abegin();
1346 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1347 // Advance the argument iterator to the first pointer argument...
1348 while (AI != F.aend() && !isPointerType(AI->getType())) {
1350 #ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1351 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
1352 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1355 if (AI == F.aend()) break;
1357 // Add the link from the argument scalar to the provided value
1358 DSNodeHandle &NH = getNodeForValue(AI);
1359 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1360 NH.mergeWith(CS.getPtrArg(i));
1365 /// getCallSiteForArguments - Get the arguments and return value bindings for
1366 /// the specified function in the current graph.
1368 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1369 std::vector<DSNodeHandle> Args;
1371 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1372 if (isPointerType(I->getType()))
1373 Args.push_back(getNodeForValue(I));
1375 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1380 // markIncompleteNodes - Mark the specified node as having contents that are not
1381 // known with the current analysis we have performed. Because a node makes all
1382 // of the nodes it can reach incomplete if the node itself is incomplete, we
1383 // must recursively traverse the data structure graph, marking all reachable
1384 // nodes as incomplete.
1386 static void markIncompleteNode(DSNode *N) {
1387 // Stop recursion if no node, or if node already marked...
1388 if (N == 0 || N->isIncomplete()) return;
1390 // Actually mark the node
1391 N->setIncompleteMarker();
1393 // Recursively process children...
1394 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1395 if (DSNode *DSN = N->getLink(i).getNode())
1396 markIncompleteNode(DSN);
1399 static void markIncomplete(DSCallSite &Call) {
1400 // Then the return value is certainly incomplete!
1401 markIncompleteNode(Call.getRetVal().getNode());
1403 // All objects pointed to by function arguments are incomplete!
1404 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1405 markIncompleteNode(Call.getPtrArg(i).getNode());
1408 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1409 // modified by other functions that have not been resolved yet. This marks
1410 // nodes that are reachable through three sources of "unknownness":
1412 // Global Variables, Function Calls, and Incoming Arguments
1414 // For any node that may have unknown components (because something outside the
1415 // scope of current analysis may have modified it), the 'Incomplete' flag is
1416 // added to the NodeType.
1418 void DSGraph::markIncompleteNodes(unsigned Flags) {
1419 // Mark any incoming arguments as incomplete...
1420 if (Flags & DSGraph::MarkFormalArgs)
1421 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1423 Function &F = *FI->first;
1424 if (F.getName() != "main")
1425 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1426 if (isPointerType(I->getType()))
1427 markIncompleteNode(getNodeForValue(I).getNode());
1430 // Mark stuff passed into functions calls as being incomplete...
1431 if (!shouldPrintAuxCalls())
1432 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1433 markIncomplete(FunctionCalls[i]);
1435 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1436 markIncomplete(AuxFunctionCalls[i]);
1439 // Mark all global nodes as incomplete...
1440 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1441 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1442 E = ScalarMap.global_end(); I != E; ++I)
1443 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1444 if (!GV->isConstant() || !GV->hasInitializer())
1445 markIncompleteNode(ScalarMap[GV].getNode());
1448 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1449 if (DSNode *N = Edge.getNode()) // Is there an edge?
1450 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
1451 // No interesting info?
1452 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1453 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1454 Edge.setNode(0); // Kill the edge!
1457 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1458 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1459 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1460 if (Globals[i]->isExternal())
1465 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
1466 // Remove trivially identical function calls
1467 unsigned NumFns = Calls.size();
1468 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1471 // Scan the call list cleaning it up as necessary...
1472 DSNode *LastCalleeNode = 0;
1473 Function *LastCalleeFunc = 0;
1474 unsigned NumDuplicateCalls = 0;
1475 bool LastCalleeContainsExternalFunction = false;
1476 for (unsigned i = 0; i != Calls.size(); ++i) {
1477 DSCallSite &CS = Calls[i];
1479 // If the Callee is a useless edge, this must be an unreachable call site,
1481 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
1482 CS.getCalleeNode()->isComplete() &&
1483 CS.getCalleeNode()->getGlobals().empty()) { // No useful info?
1485 std::cerr << "WARNING: Useless call site found.\n";
1487 CS.swap(Calls.back());
1491 // If the return value or any arguments point to a void node with no
1492 // information at all in it, and the call node is the only node to point
1493 // to it, remove the edge to the node (killing the node).
1495 killIfUselessEdge(CS.getRetVal());
1496 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1497 killIfUselessEdge(CS.getPtrArg(a));
1499 // If this call site calls the same function as the last call site, and if
1500 // the function pointer contains an external function, this node will
1501 // never be resolved. Merge the arguments of the call node because no
1502 // information will be lost.
1504 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1505 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1506 ++NumDuplicateCalls;
1507 if (NumDuplicateCalls == 1) {
1509 LastCalleeContainsExternalFunction =
1510 nodeContainsExternalFunction(LastCalleeNode);
1512 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1515 // It is not clear why, but enabling this code makes DSA really
1516 // sensitive to node forwarding. Basically, with this enabled, DSA
1517 // performs different number of inlinings based on which nodes are
1518 // forwarding or not. This is clearly a problem, so this code is
1519 // disabled until this can be resolved.
1521 if (LastCalleeContainsExternalFunction
1524 // This should be more than enough context sensitivity!
1525 // FIXME: Evaluate how many times this is tripped!
1526 NumDuplicateCalls > 20
1529 DSCallSite &OCS = Calls[i-1];
1532 // The node will now be eliminated as a duplicate!
1533 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1535 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1540 if (CS.isDirectCall()) {
1541 LastCalleeFunc = CS.getCalleeFunc();
1544 LastCalleeNode = CS.getCalleeNode();
1547 NumDuplicateCalls = 0;
1552 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
1554 // Track the number of call nodes merged away...
1555 NumCallNodesMerged += NumFns-Calls.size();
1557 DEBUG(if (NumFns != Calls.size())
1558 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
1562 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1563 // removes all unreachable nodes that are created because they got merged with
1564 // other nodes in the graph. These nodes will all be trivially unreachable, so
1565 // we don't have to perform any non-trivial analysis here.
1567 void DSGraph::removeTriviallyDeadNodes() {
1568 TIME_REGION(X, "removeTriviallyDeadNodes");
1570 // Loop over all of the nodes in the graph, calling getNode on each field.
1571 // This will cause all nodes to update their forwarding edges, causing
1572 // forwarded nodes to be delete-able.
1573 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1575 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1576 N->getLink(l*N->getPointerSize()).getNode();
1579 // NOTE: This code is disabled. Though it should, in theory, allow us to
1580 // remove more nodes down below, the scan of the scalar map is incredibly
1581 // expensive for certain programs (with large SCCs). In the future, if we can
1582 // make the scalar map scan more efficient, then we can reenable this.
1584 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1586 // Likewise, forward any edges from the scalar nodes. While we are at it,
1587 // clean house a bit.
1588 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1589 I->second.getNode();
1594 bool isGlobalsGraph = !GlobalsGraph;
1596 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
1599 // Do not remove *any* global nodes in the globals graph.
1600 // This is a special case because such nodes may not have I, M, R flags set.
1601 if (Node.isGlobalNode() && isGlobalsGraph) {
1606 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
1607 // This is a useless node if it has no mod/ref info (checked above),
1608 // outgoing edges (which it cannot, as it is not modified in this
1609 // context), and it has no incoming edges. If it is a global node it may
1610 // have all of these properties and still have incoming edges, due to the
1611 // scalar map, so we check those now.
1613 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1614 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
1616 // Loop through and make sure all of the globals are referring directly
1618 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1619 DSNode *N = getNodeForValue(Globals[j]).getNode();
1620 assert(N == &Node && "ScalarMap doesn't match globals list!");
1623 // Make sure NumReferrers still agrees, if so, the node is truly dead.
1624 if (Node.getNumReferrers() == Globals.size()) {
1625 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1626 ScalarMap.erase(Globals[j]);
1627 Node.makeNodeDead();
1628 ++NumTrivialGlobalDNE;
1633 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
1634 // This node is dead!
1635 NI = Nodes.erase(NI); // Erase & remove from node list.
1642 removeIdenticalCalls(FunctionCalls);
1643 removeIdenticalCalls(AuxFunctionCalls);
1647 /// markReachableNodes - This method recursively traverses the specified
1648 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1649 /// to the set, which allows it to only traverse visited nodes once.
1651 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
1652 if (this == 0) return;
1653 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1654 if (ReachableNodes.insert(this).second) // Is newly reachable?
1655 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1656 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1659 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
1660 getRetVal().getNode()->markReachableNodes(Nodes);
1661 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1663 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1664 getPtrArg(i).getNode()->markReachableNodes(Nodes);
1667 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1668 // looking for a node that is marked alive. If an alive node is found, return
1669 // true, otherwise return false. If an alive node is reachable, this node is
1670 // marked as alive...
1672 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1673 hash_set<DSNode*> &Visited,
1674 bool IgnoreGlobals) {
1675 if (N == 0) return false;
1676 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1678 // If this is a global node, it will end up in the globals graph anyway, so we
1679 // don't need to worry about it.
1680 if (IgnoreGlobals && N->isGlobalNode()) return false;
1682 // If we know that this node is alive, return so!
1683 if (Alive.count(N)) return true;
1685 // Otherwise, we don't think the node is alive yet, check for infinite
1687 if (Visited.count(N)) return false; // Found a cycle
1688 Visited.insert(N); // No recursion, insert into Visited...
1690 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1691 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1693 N->markReachableNodes(Alive);
1699 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1702 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1703 hash_set<DSNode*> &Visited,
1704 bool IgnoreGlobals) {
1705 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1708 if (CS.isIndirectCall() &&
1709 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
1711 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1712 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1718 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1719 // subgraphs that are unreachable. This often occurs because the data
1720 // structure doesn't "escape" into it's caller, and thus should be eliminated
1721 // from the caller's graph entirely. This is only appropriate to use when
1724 void DSGraph::removeDeadNodes(unsigned Flags) {
1725 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
1727 // Reduce the amount of work we have to do... remove dummy nodes left over by
1729 removeTriviallyDeadNodes();
1731 TIME_REGION(X, "removeDeadNodes");
1733 // FIXME: Merge non-trivially identical call nodes...
1735 // Alive - a set that holds all nodes found to be reachable/alive.
1736 hash_set<DSNode*> Alive;
1737 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1739 // Copy and merge all information about globals to the GlobalsGraph if this is
1740 // not a final pass (where unreachable globals are removed).
1742 // Strip all alloca bits since the current function is only for the BU pass.
1743 // Strip all incomplete bits since they are short-lived properties and they
1744 // will be correctly computed when rematerializing nodes into the functions.
1746 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1747 DSGraph::StripIncompleteBit);
1749 // Mark all nodes reachable by (non-global) scalar nodes as alive...
1750 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
1751 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
1752 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
1753 assert(I->second.getNode() && "Null global node?");
1754 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
1755 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1757 // Make sure that all globals are cloned over as roots.
1758 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1759 DSGraph::ScalarMapTy::iterator SMI =
1760 GlobalsGraph->getScalarMap().find(I->first);
1761 if (SMI != GlobalsGraph->getScalarMap().end())
1762 GGCloner.merge(SMI->second, I->second);
1764 GGCloner.getClonedNH(I->second);
1768 DSNode *N = I->second.getNode();
1770 // Check to see if this is a worthless node generated for non-pointer
1771 // values, such as integers. Consider an addition of long types: A+B.
1772 // Assuming we can track all uses of the value in this context, and it is
1773 // NOT used as a pointer, we can delete the node. We will be able to
1774 // detect this situation if the node pointed to ONLY has Unknown bit set
1775 // in the node. In this case, the node is not incomplete, does not point
1776 // to any other nodes (no mod/ref bits set), and is therefore
1777 // uninteresting for data structure analysis. If we run across one of
1778 // these, prune the scalar pointing to it.
1780 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1781 ScalarMap.erase(I++);
1784 N->markReachableNodes(Alive);
1790 // The return values are alive as well.
1791 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1793 I->second.getNode()->markReachableNodes(Alive);
1795 // Mark any nodes reachable by primary calls as alive...
1796 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1797 FunctionCalls[i].markReachableNodes(Alive);
1800 // Now find globals and aux call nodes that are already live or reach a live
1801 // value (which makes them live in turn), and continue till no more are found.
1804 hash_set<DSNode*> Visited;
1805 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1808 // If any global node points to a non-global that is "alive", the global is
1809 // "alive" as well... Remove it from the GlobalNodes list so we only have
1810 // unreachable globals in the list.
1813 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1814 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1815 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1816 Flags & DSGraph::RemoveUnreachableGlobals)) {
1817 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1818 GlobalNodes.pop_back(); // erase efficiently
1822 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1823 // call nodes that get resolved will be difficult to remove from that graph.
1824 // The final unresolved call nodes must be handled specially at the end of
1825 // the BU pass (i.e., in main or other roots of the call graph).
1826 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1827 if (!AuxFCallsAlive[i] &&
1828 (AuxFunctionCalls[i].isIndirectCall()
1829 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1830 Flags & DSGraph::RemoveUnreachableGlobals))) {
1831 AuxFunctionCalls[i].markReachableNodes(Alive);
1832 AuxFCallsAlive[i] = true;
1837 // Move dead aux function calls to the end of the list
1838 unsigned CurIdx = 0;
1839 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1840 if (AuxFCallsAlive[i])
1841 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1843 // Copy and merge all global nodes and dead aux call nodes into the
1844 // GlobalsGraph, and all nodes reachable from those nodes
1846 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1847 // Copy the unreachable call nodes to the globals graph, updating their
1848 // target pointers using the GGCloner
1849 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1850 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1853 // Crop all the useless ones out...
1854 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1855 AuxFunctionCalls.end());
1857 // We are finally done with the GGCloner so we can destroy it.
1860 // At this point, any nodes which are visited, but not alive, are nodes
1861 // which can be removed. Loop over all nodes, eliminating completely
1862 // unreachable nodes.
1864 std::vector<DSNode*> DeadNodes;
1865 DeadNodes.reserve(Nodes.size());
1866 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1868 assert(!N->isForwarding() && "Forwarded node in nodes list?");
1870 if (!Alive.count(N)) {
1872 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
1873 DeadNodes.push_back(N);
1874 N->dropAllReferences();
1879 // Remove all unreachable globals from the ScalarMap.
1880 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1881 // In either case, the dead nodes will not be in the set Alive.
1882 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1883 if (!Alive.count(GlobalNodes[i].second))
1884 ScalarMap.erase(GlobalNodes[i].first);
1886 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
1888 // Delete all dead nodes now since their referrer counts are zero.
1889 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1890 delete DeadNodes[i];
1892 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1895 void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
1896 if (CS.isIndirectCall()) {
1897 AssertNodeInGraph(CS.getCalleeNode());
1899 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
1900 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
1901 std::cerr << "WARNING: WIERD CALL SITE FOUND!\n";
1904 AssertNodeInGraph(CS.getRetVal().getNode());
1905 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
1906 AssertNodeInGraph(CS.getPtrArg(j).getNode());
1909 void DSGraph::AssertCallNodesInGraph() const {
1910 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1911 AssertCallSiteInGraph(FunctionCalls[i]);
1913 void DSGraph::AssertAuxCallNodesInGraph() const {
1914 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1915 AssertCallSiteInGraph(AuxFunctionCalls[i]);
1918 void DSGraph::AssertGraphOK() const {
1919 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1922 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
1923 E = ScalarMap.end(); I != E; ++I) {
1924 assert(I->second.getNode() && "Null node in scalarmap!");
1925 AssertNodeInGraph(I->second.getNode());
1926 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1927 assert(I->second.getNode()->isGlobalNode() &&
1928 "Global points to node, but node isn't global?");
1929 AssertNodeContainsGlobal(I->second.getNode(), GV);
1932 AssertCallNodesInGraph();
1933 AssertAuxCallNodesInGraph();
1936 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1937 /// nodes reachable from the two graphs, computing the mapping of nodes from
1938 /// the first to the second graph.
1940 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
1941 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1942 bool StrictChecking) {
1943 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1944 if (N1 == 0 || N2 == 0) return;
1946 DSNodeHandle &Entry = NodeMap[N1];
1947 if (Entry.getNode()) {
1948 // Termination of recursion!
1949 assert(!StrictChecking ||
1950 (Entry.getNode() == N2 &&
1951 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
1952 "Inconsistent mapping detected!");
1957 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
1959 // Loop over all of the fields that N1 and N2 have in common, recursively
1960 // mapping the edges together now.
1961 int N2Idx = NH2.getOffset()-NH1.getOffset();
1962 unsigned N2Size = N2->getSize();
1963 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1964 if (unsigned(N2Idx)+i < N2Size)
1965 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1967 computeNodeMapping(N1->getLink(i),
1968 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);