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/DataStructure/DSGraphTraits.h"
15 #include "llvm/Function.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/ADT/DepthFirstIterator.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Support/Timer.h"
30 #define COLLAPSE_ARRAYS_AGGRESSIVELY 0
33 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
34 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
35 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
36 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
37 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
38 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
42 #define TIME_REGION(VARNAME, DESC) \
43 NamedRegionTimer VARNAME(DESC)
45 #define TIME_REGION(VARNAME, DESC)
50 /// isForwarding - Return true if this NodeHandle is forwarding to another
52 bool DSNodeHandle::isForwarding() const {
53 return N && N->isForwarding();
56 DSNode *DSNodeHandle::HandleForwarding() const {
57 assert(N->isForwarding() && "Can only be invoked if forwarding!");
59 // Handle node forwarding here!
60 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
61 Offset += N->ForwardNH.getOffset();
63 if (--N->NumReferrers == 0) {
64 // Removing the last referrer to the node, sever the forwarding link
70 if (N->Size <= Offset) {
71 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
77 //===----------------------------------------------------------------------===//
78 // DSNode Implementation
79 //===----------------------------------------------------------------------===//
81 DSNode::DSNode(const Type *T, DSGraph *G)
82 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
83 // Add the type entry if it is specified...
84 if (T) mergeTypeInfo(T, 0);
85 if (G) G->addNode(this);
89 // DSNode copy constructor... do not copy over the referrers list!
90 DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
91 : NumReferrers(0), Size(N.Size), ParentGraph(G),
92 Ty(N.Ty), NodeType(N.NodeType) {
97 Links.resize(N.Links.size()); // Create the appropriate number of null links
102 /// getTargetData - Get the target data object used to construct this node.
104 const TargetData &DSNode::getTargetData() const {
105 return ParentGraph->getTargetData();
108 void DSNode::assertOK() const {
109 assert((Ty != Type::VoidTy ||
110 Ty == Type::VoidTy && (Size == 0 ||
111 (NodeType & DSNode::Array))) &&
114 assert(ParentGraph && "Node has no parent?");
115 const DSScalarMap &SM = ParentGraph->getScalarMap();
116 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
117 assert(SM.count(Globals[i]));
118 assert(SM.find(Globals[i])->second.getNode() == this);
122 /// forwardNode - Mark this node as being obsolete, and all references to it
123 /// should be forwarded to the specified node and offset.
125 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
126 assert(this != To && "Cannot forward a node to itself!");
127 assert(ForwardNH.isNull() && "Already forwarding from this node!");
128 if (To->Size <= 1) Offset = 0;
129 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
130 "Forwarded offset is wrong!");
131 ForwardNH.setTo(To, Offset);
136 // Remove this node from the parent graph's Nodes list.
137 ParentGraph->unlinkNode(this);
141 // addGlobal - Add an entry for a global value to the Globals list. This also
142 // marks the node with the 'G' flag if it does not already have it.
144 void DSNode::addGlobal(GlobalValue *GV) {
145 // Keep the list sorted.
146 std::vector<GlobalValue*>::iterator I =
147 std::lower_bound(Globals.begin(), Globals.end(), GV);
149 if (I == Globals.end() || *I != GV) {
150 Globals.insert(I, GV);
151 NodeType |= GlobalNode;
155 /// foldNodeCompletely - If we determine that this node has some funny
156 /// behavior happening to it that we cannot represent, we fold it down to a
157 /// single, completely pessimistic, node. This node is represented as a
158 /// single byte with a single TypeEntry of "void".
160 void DSNode::foldNodeCompletely() {
161 if (isNodeCompletelyFolded()) return; // If this node is already folded...
165 // If this node has a size that is <= 1, we don't need to create a forwarding
167 if (getSize() <= 1) {
168 NodeType |= DSNode::Array;
171 assert(Links.size() <= 1 && "Size is 1, but has more links?");
174 // Create the node we are going to forward to. This is required because
175 // some referrers may have an offset that is > 0. By forcing them to
176 // forward, the forwarder has the opportunity to correct the offset.
177 DSNode *DestNode = new DSNode(0, ParentGraph);
178 DestNode->NodeType = NodeType|DSNode::Array;
179 DestNode->Ty = Type::VoidTy;
181 DestNode->Globals.swap(Globals);
183 // Start forwarding to the destination node...
184 forwardNode(DestNode, 0);
186 if (!Links.empty()) {
187 DestNode->Links.reserve(1);
189 DSNodeHandle NH(DestNode);
190 DestNode->Links.push_back(Links[0]);
192 // If we have links, merge all of our outgoing links together...
193 for (unsigned i = Links.size()-1; i != 0; --i)
194 NH.getNode()->Links[0].mergeWith(Links[i]);
197 DestNode->Links.resize(1);
202 /// isNodeCompletelyFolded - Return true if this node has been completely
203 /// folded down to something that can never be expanded, effectively losing
204 /// all of the field sensitivity that may be present in the node.
206 bool DSNode::isNodeCompletelyFolded() const {
207 return getSize() == 1 && Ty == Type::VoidTy && isArray();
211 /// TypeElementWalker Class - Used for implementation of physical subtyping...
213 class TypeElementWalker {
218 StackState(const Type *T, unsigned Off = 0)
219 : Ty(T), Offset(Off), Idx(0) {}
222 std::vector<StackState> Stack;
223 const TargetData &TD;
225 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
230 bool isDone() const { return Stack.empty(); }
231 const Type *getCurrentType() const { return Stack.back().Ty; }
232 unsigned getCurrentOffset() const { return Stack.back().Offset; }
234 void StepToNextType() {
235 PopStackAndAdvance();
240 /// PopStackAndAdvance - Pop the current element off of the stack and
241 /// advance the underlying element to the next contained member.
242 void PopStackAndAdvance() {
243 assert(!Stack.empty() && "Cannot pop an empty stack!");
245 while (!Stack.empty()) {
246 StackState &SS = Stack.back();
247 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
249 if (SS.Idx != ST->getNumElements()) {
250 const StructLayout *SL = TD.getStructLayout(ST);
252 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
255 Stack.pop_back(); // At the end of the structure
257 const ArrayType *AT = cast<ArrayType>(SS.Ty);
259 if (SS.Idx != AT->getNumElements()) {
260 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
263 Stack.pop_back(); // At the end of the array
268 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
269 /// on the type stack.
271 if (Stack.empty()) return;
272 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
273 StackState &SS = Stack.back();
274 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
275 if (ST->getNumElements() == 0) {
277 PopStackAndAdvance();
279 // Step into the structure...
280 assert(SS.Idx < ST->getNumElements());
281 const StructLayout *SL = TD.getStructLayout(ST);
282 Stack.push_back(StackState(ST->getElementType(SS.Idx),
283 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
286 const ArrayType *AT = cast<ArrayType>(SS.Ty);
287 if (AT->getNumElements() == 0) {
289 PopStackAndAdvance();
291 // Step into the array...
292 assert(SS.Idx < AT->getNumElements());
293 Stack.push_back(StackState(AT->getElementType(),
295 unsigned(TD.getTypeSize(AT->getElementType()))));
301 } // end anonymous namespace
303 /// ElementTypesAreCompatible - Check to see if the specified types are
304 /// "physically" compatible. If so, return true, else return false. We only
305 /// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
306 /// is true, then we also allow a larger T1.
308 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
309 bool AllowLargerT1, const TargetData &TD){
310 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
312 while (!T1W.isDone() && !T2W.isDone()) {
313 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
316 const Type *T1 = T1W.getCurrentType();
317 const Type *T2 = T2W.getCurrentType();
318 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
321 T1W.StepToNextType();
322 T2W.StepToNextType();
325 return AllowLargerT1 || T1W.isDone();
329 /// mergeTypeInfo - This method merges the specified type into the current node
330 /// at the specified offset. This may update the current node's type record if
331 /// this gives more information to the node, it may do nothing to the node if
332 /// this information is already known, or it may merge the node completely (and
333 /// return true) if the information is incompatible with what is already known.
335 /// This method returns true if the node is completely folded, otherwise false.
337 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
338 bool FoldIfIncompatible) {
339 const TargetData &TD = getTargetData();
340 // Check to make sure the Size member is up-to-date. Size can be one of the
342 // Size = 0, Ty = Void: Nothing is known about this node.
343 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
344 // Size = 1, Ty = Void, Array = 1: The node is collapsed
345 // Otherwise, sizeof(Ty) = Size
347 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
348 (Size == 0 && !Ty->isSized() && !isArray()) ||
349 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
350 (Size == 0 && !Ty->isSized() && !isArray()) ||
351 (TD.getTypeSize(Ty) == Size)) &&
352 "Size member of DSNode doesn't match the type structure!");
353 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
355 if (Offset == 0 && NewTy == Ty)
356 return false; // This should be a common case, handle it efficiently
358 // Return true immediately if the node is completely folded.
359 if (isNodeCompletelyFolded()) return true;
361 // If this is an array type, eliminate the outside arrays because they won't
362 // be used anyway. This greatly reduces the size of large static arrays used
363 // as global variables, for example.
365 bool WillBeArray = false;
366 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
367 // FIXME: we might want to keep small arrays, but must be careful about
368 // things like: [2 x [10000 x int*]]
369 NewTy = AT->getElementType();
373 // Figure out how big the new type we're merging in is...
374 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
376 // Otherwise check to see if we can fold this type into the current node. If
377 // we can't, we fold the node completely, if we can, we potentially update our
380 if (Ty == Type::VoidTy) {
381 // If this is the first type that this node has seen, just accept it without
383 assert(Offset == 0 && !isArray() &&
384 "Cannot have an offset into a void node!");
387 if (WillBeArray) NodeType |= Array;
390 // Calculate the number of outgoing links from this node.
391 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
395 // Handle node expansion case here...
396 if (Offset+NewTySize > Size) {
397 // It is illegal to grow this node if we have treated it as an array of
400 if (FoldIfIncompatible) foldNodeCompletely();
404 if (Offset) { // We could handle this case, but we don't for now...
405 std::cerr << "UNIMP: Trying to merge a growth type into "
406 << "offset != 0: Collapsing!\n";
407 if (FoldIfIncompatible) foldNodeCompletely();
411 // Okay, the situation is nice and simple, we are trying to merge a type in
412 // at offset 0 that is bigger than our current type. Implement this by
413 // switching to the new type and then merge in the smaller one, which should
414 // hit the other code path here. If the other code path decides it's not
415 // ok, it will collapse the node as appropriate.
417 const Type *OldTy = Ty;
420 if (WillBeArray) NodeType |= Array;
423 // Must grow links to be the appropriate size...
424 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
426 // Merge in the old type now... which is guaranteed to be smaller than the
428 return mergeTypeInfo(OldTy, 0);
431 assert(Offset <= Size &&
432 "Cannot merge something into a part of our type that doesn't exist!");
434 // Find the section of Ty that NewTy overlaps with... first we find the
435 // type that starts at offset Offset.
438 const Type *SubType = Ty;
440 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
442 switch (SubType->getTypeID()) {
443 case Type::StructTyID: {
444 const StructType *STy = cast<StructType>(SubType);
445 const StructLayout &SL = *TD.getStructLayout(STy);
447 unsigned i = 0, e = SL.MemberOffsets.size();
448 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
451 // The offset we are looking for must be in the i'th element...
452 SubType = STy->getElementType(i);
453 O += (unsigned)SL.MemberOffsets[i];
456 case Type::ArrayTyID: {
457 SubType = cast<ArrayType>(SubType)->getElementType();
458 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
459 unsigned Remainder = (Offset-O) % ElSize;
460 O = Offset-Remainder;
464 if (FoldIfIncompatible) foldNodeCompletely();
469 assert(O == Offset && "Could not achieve the correct offset!");
471 // If we found our type exactly, early exit
472 if (SubType == NewTy) return false;
474 // Differing function types don't require us to merge. They are not values
476 if (isa<FunctionType>(SubType) &&
477 isa<FunctionType>(NewTy)) return false;
479 unsigned SubTypeSize = SubType->isSized() ?
480 (unsigned)TD.getTypeSize(SubType) : 0;
482 // Ok, we are getting desperate now. Check for physical subtyping, where we
483 // just require each element in the node to be compatible.
484 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
485 SubTypeSize && SubTypeSize < 256 &&
486 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
489 // Okay, so we found the leader type at the offset requested. Search the list
490 // of types that starts at this offset. If SubType is currently an array or
491 // structure, the type desired may actually be the first element of the
494 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
495 while (SubType != NewTy) {
496 const Type *NextSubType = 0;
497 unsigned NextSubTypeSize = 0;
498 unsigned NextPadSize = 0;
499 switch (SubType->getTypeID()) {
500 case Type::StructTyID: {
501 const StructType *STy = cast<StructType>(SubType);
502 const StructLayout &SL = *TD.getStructLayout(STy);
503 if (SL.MemberOffsets.size() > 1)
504 NextPadSize = (unsigned)SL.MemberOffsets[1];
506 NextPadSize = SubTypeSize;
507 NextSubType = STy->getElementType(0);
508 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
511 case Type::ArrayTyID:
512 NextSubType = cast<ArrayType>(SubType)->getElementType();
513 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
514 NextPadSize = NextSubTypeSize;
520 if (NextSubType == 0)
521 break; // In the default case, break out of the loop
523 if (NextPadSize < NewTySize)
524 break; // Don't allow shrinking to a smaller type than NewTySize
525 SubType = NextSubType;
526 SubTypeSize = NextSubTypeSize;
527 PadSize = NextPadSize;
530 // If we found the type exactly, return it...
531 if (SubType == NewTy)
534 // Check to see if we have a compatible, but different type...
535 if (NewTySize == SubTypeSize) {
536 // Check to see if this type is obviously convertible... int -> uint f.e.
537 if (NewTy->isLosslesslyConvertibleTo(SubType))
540 // Check to see if we have a pointer & integer mismatch going on here,
541 // loading a pointer as a long, for example.
543 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
544 NewTy->isInteger() && isa<PointerType>(SubType))
546 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
547 // We are accessing the field, plus some structure padding. Ignore the
548 // structure padding.
553 if (getParentGraph()->getReturnNodes().size())
554 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
555 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
556 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
557 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
559 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
561 if (FoldIfIncompatible) foldNodeCompletely();
567 /// addEdgeTo - Add an edge from the current node to the specified node. This
568 /// can cause merging of nodes in the graph.
570 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
571 if (NH.isNull()) return; // Nothing to do
573 DSNodeHandle &ExistingEdge = getLink(Offset);
574 if (!ExistingEdge.isNull()) {
575 // Merge the two nodes...
576 ExistingEdge.mergeWith(NH);
577 } else { // No merging to perform...
578 setLink(Offset, NH); // Just force a link in there...
583 /// MergeSortedVectors - Efficiently merge a vector into another vector where
584 /// duplicates are not allowed and both are sorted. This assumes that 'T's are
585 /// efficiently copyable and have sane comparison semantics.
587 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
588 const std::vector<GlobalValue*> &Src) {
589 // By far, the most common cases will be the simple ones. In these cases,
590 // avoid having to allocate a temporary vector...
592 if (Src.empty()) { // Nothing to merge in...
594 } else if (Dest.empty()) { // Just copy the result in...
596 } else if (Src.size() == 1) { // Insert a single element...
597 const GlobalValue *V = Src[0];
598 std::vector<GlobalValue*>::iterator I =
599 std::lower_bound(Dest.begin(), Dest.end(), V);
600 if (I == Dest.end() || *I != Src[0]) // If not already contained...
601 Dest.insert(I, Src[0]);
602 } else if (Dest.size() == 1) {
603 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
604 Dest = Src; // Copy over list...
605 std::vector<GlobalValue*>::iterator I =
606 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
607 if (I == Dest.end() || *I != Tmp) // If not already contained...
611 // Make a copy to the side of Dest...
612 std::vector<GlobalValue*> Old(Dest);
614 // Make space for all of the type entries now...
615 Dest.resize(Dest.size()+Src.size());
617 // Merge the two sorted ranges together... into Dest.
618 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
620 // Now erase any duplicate entries that may have accumulated into the
621 // vectors (because they were in both of the input sets)
622 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
626 void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
627 MergeSortedVectors(Globals, RHS);
630 // MergeNodes - Helper function for DSNode::mergeWith().
631 // This function does the hard work of merging two nodes, CurNodeH
632 // and NH after filtering out trivial cases and making sure that
633 // CurNodeH.offset >= NH.offset.
636 // Since merging may cause either node to go away, we must always
637 // use the node-handles to refer to the nodes. These node handles are
638 // automatically updated during merging, so will always provide access
639 // to the correct node after a merge.
641 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
642 assert(CurNodeH.getOffset() >= NH.getOffset() &&
643 "This should have been enforced in the caller.");
644 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
645 "Cannot merge two nodes that are not in the same graph!");
647 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
648 // respect to NH.Offset) is now zero. NOffset is the distance from the base
649 // of our object that N starts from.
651 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
652 unsigned NSize = NH.getNode()->getSize();
654 // If the two nodes are of different size, and the smaller node has the array
655 // bit set, collapse!
656 if (NSize != CurNodeH.getNode()->getSize()) {
657 #if COLLAPSE_ARRAYS_AGGRESSIVELY
658 if (NSize < CurNodeH.getNode()->getSize()) {
659 if (NH.getNode()->isArray())
660 NH.getNode()->foldNodeCompletely();
661 } else if (CurNodeH.getNode()->isArray()) {
662 NH.getNode()->foldNodeCompletely();
667 // Merge the type entries of the two nodes together...
668 if (NH.getNode()->Ty != Type::VoidTy)
669 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
670 assert(!CurNodeH.getNode()->isDeadNode());
672 // If we are merging a node with a completely folded node, then both nodes are
673 // now completely folded.
675 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
676 if (!NH.getNode()->isNodeCompletelyFolded()) {
677 NH.getNode()->foldNodeCompletely();
678 assert(NH.getNode() && NH.getOffset() == 0 &&
679 "folding did not make offset 0?");
680 NOffset = NH.getOffset();
681 NSize = NH.getNode()->getSize();
682 assert(NOffset == 0 && NSize == 1);
684 } else if (NH.getNode()->isNodeCompletelyFolded()) {
685 CurNodeH.getNode()->foldNodeCompletely();
686 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
687 "folding did not make offset 0?");
688 NSize = NH.getNode()->getSize();
689 NOffset = NH.getOffset();
690 assert(NOffset == 0 && NSize == 1);
693 DSNode *N = NH.getNode();
694 if (CurNodeH.getNode() == N || N == 0) return;
695 assert(!CurNodeH.getNode()->isDeadNode());
697 // Merge the NodeType information.
698 CurNodeH.getNode()->NodeType |= N->NodeType;
700 // Start forwarding to the new node!
701 N->forwardNode(CurNodeH.getNode(), NOffset);
702 assert(!CurNodeH.getNode()->isDeadNode());
704 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
706 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
707 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
708 if (Link.getNode()) {
709 // Compute the offset into the current node at which to
710 // merge this link. In the common case, this is a linear
711 // relation to the offset in the original node (with
712 // wrapping), but if the current node gets collapsed due to
713 // recursive merging, we must make sure to merge in all remaining
714 // links at offset zero.
715 unsigned MergeOffset = 0;
716 DSNode *CN = CurNodeH.getNode();
718 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
719 CN->addEdgeTo(MergeOffset, Link);
723 // Now that there are no outgoing edges, all of the Links are dead.
726 // Merge the globals list...
727 if (!N->Globals.empty()) {
728 CurNodeH.getNode()->mergeGlobals(N->Globals);
730 // Delete the globals from the old node...
731 std::vector<GlobalValue*>().swap(N->Globals);
736 /// mergeWith - Merge this node and the specified node, moving all links to and
737 /// from the argument node into the current node, deleting the node argument.
738 /// Offset indicates what offset the specified node is to be merged into the
741 /// The specified node may be a null pointer (in which case, we update it to
742 /// point to this node).
744 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
745 DSNode *N = NH.getNode();
746 if (N == this && NH.getOffset() == Offset)
749 // If the RHS is a null node, make it point to this node!
751 NH.mergeWith(DSNodeHandle(this, Offset));
755 assert(!N->isDeadNode() && !isDeadNode());
756 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
759 // We cannot merge two pieces of the same node together, collapse the node
761 DEBUG(std::cerr << "Attempting to merge two chunks of"
762 << " the same node together!\n");
763 foldNodeCompletely();
767 // If both nodes are not at offset 0, make sure that we are merging the node
768 // at an later offset into the node with the zero offset.
770 if (Offset < NH.getOffset()) {
771 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
773 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
774 // If the offsets are the same, merge the smaller node into the bigger node
775 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
779 // Ok, now we can merge the two nodes. Use a static helper that works with
780 // two node handles, since "this" may get merged away at intermediate steps.
781 DSNodeHandle CurNodeH(this, Offset);
782 DSNodeHandle NHCopy(NH);
783 DSNode::MergeNodes(CurNodeH, NHCopy);
787 //===----------------------------------------------------------------------===//
788 // ReachabilityCloner Implementation
789 //===----------------------------------------------------------------------===//
791 DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
792 if (SrcNH.isNull()) return DSNodeHandle();
793 const DSNode *SN = SrcNH.getNode();
795 DSNodeHandle &NH = NodeMap[SN];
796 if (!NH.isNull()) { // Node already mapped?
797 DSNode *NHN = NH.getNode();
798 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
801 // If SrcNH has globals and the destination graph has one of the same globals,
802 // merge this node with the destination node, which is much more efficient.
803 if (SN->global_begin() != SN->global_end()) {
804 DSScalarMap &DestSM = Dest.getScalarMap();
805 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
807 GlobalValue *GV = *I;
808 DSScalarMap::iterator GI = DestSM.find(GV);
809 if (GI != DestSM.end() && !GI->second.isNull()) {
810 // We found one, use merge instead!
811 merge(GI->second, Src.getNodeForValue(GV));
812 assert(!NH.isNull() && "Didn't merge node!");
813 DSNode *NHN = NH.getNode();
814 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
819 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
820 DN->maskNodeTypes(BitsToKeep);
823 // Next, recursively clone all outgoing links as necessary. Note that
824 // adding these links can cause the node to collapse itself at any time, and
825 // the current node may be merged with arbitrary other nodes. For this
826 // reason, we must always go through NH.
828 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
829 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
830 if (!SrcEdge.isNull()) {
831 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
832 // Compute the offset into the current node at which to
833 // merge this link. In the common case, this is a linear
834 // relation to the offset in the original node (with
835 // wrapping), but if the current node gets collapsed due to
836 // recursive merging, we must make sure to merge in all remaining
837 // links at offset zero.
838 unsigned MergeOffset = 0;
839 DSNode *CN = NH.getNode();
840 if (CN->getSize() != 1)
841 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
842 CN->addEdgeTo(MergeOffset, DestEdge);
846 // If this node contains any globals, make sure they end up in the scalar
847 // map with the correct offset.
848 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
850 GlobalValue *GV = *I;
851 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
852 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
853 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
854 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
855 DestGNH.getOffset()+SrcGNH.getOffset()));
857 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
858 Dest.getInlinedGlobals().insert(GV);
860 NH.getNode()->mergeGlobals(SN->getGlobals());
862 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
865 void ReachabilityCloner::merge(const DSNodeHandle &NH,
866 const DSNodeHandle &SrcNH) {
867 if (SrcNH.isNull()) return; // Noop
869 // If there is no destination node, just clone the source and assign the
870 // destination node to be it.
871 NH.mergeWith(getClonedNH(SrcNH));
875 // Okay, at this point, we know that we have both a destination and a source
876 // node that need to be merged. Check to see if the source node has already
878 const DSNode *SN = SrcNH.getNode();
879 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
880 if (!SCNH.isNull()) { // Node already cloned?
881 DSNode *SCNHN = SCNH.getNode();
882 NH.mergeWith(DSNodeHandle(SCNHN,
883 SCNH.getOffset()+SrcNH.getOffset()));
884 return; // Nothing to do!
887 // Okay, so the source node has not already been cloned. Instead of creating
888 // a new DSNode, only to merge it into the one we already have, try to perform
889 // the merge in-place. The only case we cannot handle here is when the offset
890 // into the existing node is less than the offset into the virtual node we are
891 // merging in. In this case, we have to extend the existing node, which
892 // requires an allocation anyway.
893 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
894 if (NH.getOffset() >= SrcNH.getOffset()) {
895 if (!DN->isNodeCompletelyFolded()) {
896 // Make sure the destination node is folded if the source node is folded.
897 if (SN->isNodeCompletelyFolded()) {
898 DN->foldNodeCompletely();
900 } else if (SN->getSize() != DN->getSize()) {
901 // If the two nodes are of different size, and the smaller node has the
902 // array bit set, collapse!
903 #if COLLAPSE_ARRAYS_AGGRESSIVELY
904 if (SN->getSize() < DN->getSize()) {
906 DN->foldNodeCompletely();
909 } else if (DN->isArray()) {
910 DN->foldNodeCompletely();
916 // Merge the type entries of the two nodes together...
917 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
918 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
923 assert(!DN->isDeadNode());
925 // Merge the NodeType information.
926 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
928 // Before we start merging outgoing links and updating the scalar map, make
929 // sure it is known that this is the representative node for the src node.
930 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
932 // If the source node contains any globals, make sure they end up in the
933 // scalar map with the correct offset.
934 if (SN->global_begin() != SN->global_end()) {
935 // Update the globals in the destination node itself.
936 DN->mergeGlobals(SN->getGlobals());
938 // Update the scalar map for the graph we are merging the source node
940 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
942 GlobalValue *GV = *I;
943 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
944 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
945 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
946 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
947 DestGNH.getOffset()+SrcGNH.getOffset()));
949 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
950 Dest.getInlinedGlobals().insert(GV);
952 NH.getNode()->mergeGlobals(SN->getGlobals());
955 // We cannot handle this case without allocating a temporary node. Fall
956 // back on being simple.
957 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
958 NewDN->maskNodeTypes(BitsToKeep);
960 unsigned NHOffset = NH.getOffset();
961 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
963 assert(NH.getNode() &&
964 (NH.getOffset() > NHOffset ||
965 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
966 "Merging did not adjust the offset!");
968 // Before we start merging outgoing links and updating the scalar map, make
969 // sure it is known that this is the representative node for the src node.
970 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
972 // If the source node contained any globals, make sure to create entries
973 // in the scalar map for them!
974 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
976 GlobalValue *GV = *I;
977 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
978 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
979 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
980 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
981 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
982 DestGNH.getOffset()+SrcGNH.getOffset()));
984 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
985 Dest.getInlinedGlobals().insert(GV);
990 // Next, recursively merge all outgoing links as necessary. Note that
991 // adding these links can cause the destination node to collapse itself at
992 // any time, and the current node may be merged with arbitrary other nodes.
993 // For this reason, we must always go through NH.
995 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
996 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
997 if (!SrcEdge.isNull()) {
998 // Compute the offset into the current node at which to
999 // merge this link. In the common case, this is a linear
1000 // relation to the offset in the original node (with
1001 // wrapping), but if the current node gets collapsed due to
1002 // recursive merging, we must make sure to merge in all remaining
1003 // links at offset zero.
1004 DSNode *CN = SCNH.getNode();
1005 unsigned MergeOffset =
1006 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
1008 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1009 if (!Tmp.isNull()) {
1010 // Perform the recursive merging. Make sure to create a temporary NH,
1011 // because the Link can disappear in the process of recursive merging.
1012 merge(Tmp, SrcEdge);
1014 Tmp.mergeWith(getClonedNH(SrcEdge));
1015 // Merging this could cause all kinds of recursive things to happen,
1016 // culminating in the current node being eliminated. Since this is
1017 // possible, make sure to reaquire the link from 'CN'.
1019 unsigned MergeOffset = 0;
1020 CN = SCNH.getNode();
1021 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1022 CN->getLink(MergeOffset).mergeWith(Tmp);
1028 /// mergeCallSite - Merge the nodes reachable from the specified src call
1029 /// site into the nodes reachable from DestCS.
1030 void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
1031 const DSCallSite &SrcCS) {
1032 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1033 unsigned MinArgs = DestCS.getNumPtrArgs();
1034 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1036 for (unsigned a = 0; a != MinArgs; ++a)
1037 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1041 //===----------------------------------------------------------------------===//
1042 // DSCallSite Implementation
1043 //===----------------------------------------------------------------------===//
1045 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
1046 Function &DSCallSite::getCaller() const {
1047 return *Site.getInstruction()->getParent()->getParent();
1050 void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1051 ReachabilityCloner &RC) {
1052 NH = RC.getClonedNH(Src);
1055 //===----------------------------------------------------------------------===//
1056 // DSGraph Implementation
1057 //===----------------------------------------------------------------------===//
1059 /// getFunctionNames - Return a space separated list of the name of the
1060 /// functions in this graph (if any)
1061 std::string DSGraph::getFunctionNames() const {
1062 switch (getReturnNodes().size()) {
1063 case 0: return "Globals graph";
1064 case 1: return getReturnNodes().begin()->first->getName();
1067 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1068 I != getReturnNodes().end(); ++I)
1069 Return += I->first->getName() + " ";
1070 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1076 DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
1077 PrintAuxCalls = false;
1079 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1082 DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
1083 : GlobalsGraph(0), TD(G.TD) {
1084 PrintAuxCalls = false;
1085 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1088 DSGraph::~DSGraph() {
1089 FunctionCalls.clear();
1090 AuxFunctionCalls.clear();
1091 InlinedGlobals.clear();
1093 ReturnNodes.clear();
1095 // Drop all intra-node references, so that assertions don't fail...
1096 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1097 (*NI)->dropAllReferences();
1099 // Free all of the nodes.
1103 // dump - Allow inspection of graph in a debugger.
1104 void DSGraph::dump() const { print(std::cerr); }
1107 /// remapLinks - Change all of the Links in the current node according to the
1108 /// specified mapping.
1110 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
1111 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1112 if (DSNode *N = Links[i].getNode()) {
1113 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1114 if (ONMI != OldNodeMap.end()) {
1115 DSNode *ONMIN = ONMI->second.getNode();
1116 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1121 /// updateFromGlobalGraph - This function rematerializes global nodes and
1122 /// nodes reachable from them from the globals graph into the current graph.
1123 /// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1124 /// are already up-to-date in the current graph. In practice, in the TD pass,
1125 /// this is likely to be a large fraction of the live global nodes in each
1126 /// function (since most live nodes are likely to have been brought up-to-date
1127 /// in at _some_ caller or callee).
1129 void DSGraph::updateFromGlobalGraph() {
1130 TIME_REGION(X, "updateFromGlobalGraph");
1131 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1133 // Clone the non-up-to-date global nodes into this graph.
1134 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1135 E = getScalarMap().global_end(); I != E; ++I)
1136 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
1137 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
1138 if (It != GlobalsGraph->ScalarMap.end())
1139 RC.merge(getNodeForValue(*I), It->second);
1143 /// addObjectToGraph - This method can be used to add global, stack, and heap
1144 /// objects to the graph. This can be used when updating DSGraphs due to the
1145 /// introduction of new temporary objects. The new object is not pointed to
1146 /// and does not point to any other objects in the graph.
1147 DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1148 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1149 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1150 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
1153 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1155 } else if (MallocInst *MI = dyn_cast<MallocInst>(Ptr)) {
1156 N->setHeapNodeMarker();
1157 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
1158 N->setAllocaNodeMarker();
1160 assert(0 && "Illegal memory object input!");
1166 /// cloneInto - Clone the specified DSGraph into the current graph. The
1167 /// translated ScalarMap for the old function is filled into the OldValMap
1168 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
1170 /// The CloneFlags member controls various aspects of the cloning process.
1172 void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
1173 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1174 unsigned CloneFlags) {
1175 TIME_REGION(X, "cloneInto");
1176 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
1177 assert(&G != this && "Cannot clone graph into itself!");
1179 // Remove alloca or mod/ref bits as specified...
1180 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1181 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1182 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1183 BitsToClear |= DSNode::DEAD; // Clear dead flag...
1185 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1186 assert(!(*I)->isForwarding() &&
1187 "Forward nodes shouldn't be in node list!");
1188 DSNode *New = new DSNode(**I, this);
1189 New->maskNodeTypes(~BitsToClear);
1190 OldNodeMap[*I] = New;
1194 Timer::addPeakMemoryMeasurement();
1197 // Rewrite the links in the new nodes to point into the current graph now.
1198 // Note that we don't loop over the node's list to do this. The problem is
1199 // that remaping links can cause recursive merging to happen, which means
1200 // that node_iterator's can get easily invalidated! Because of this, we
1201 // loop over the OldNodeMap, which contains all of the new nodes as the
1202 // .second element of the map elements. Also note that if we remap a node
1203 // more than once, we won't break anything.
1204 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1206 I->second.getNode()->remapLinks(OldNodeMap);
1208 // Copy the scalar map... merging all of the global nodes...
1209 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
1210 E = G.ScalarMap.end(); I != E; ++I) {
1211 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
1212 DSNodeHandle &H = OldValMap[I->first];
1213 DSNode *MappedNodeN = MappedNode.getNode();
1214 H.mergeWith(DSNodeHandle(MappedNodeN,
1215 I->second.getOffset()+MappedNode.getOffset()));
1217 // If this is a global, add the global to this fn or merge if already exists
1218 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1219 ScalarMap[GV].mergeWith(H);
1220 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1221 InlinedGlobals.insert(GV);
1225 if (!(CloneFlags & DontCloneCallNodes)) {
1226 // Copy the function calls list.
1227 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1228 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
1231 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1232 // Copy the auxiliary function calls list.
1233 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1234 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
1237 // Map the return node pointers over...
1238 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1239 E = G.getReturnNodes().end(); I != E; ++I) {
1240 const DSNodeHandle &Ret = I->second;
1241 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1242 DSNode *MappedRetN = MappedRet.getNode();
1243 OldReturnNodes.insert(std::make_pair(I->first,
1244 DSNodeHandle(MappedRetN,
1245 MappedRet.getOffset()+Ret.getOffset())));
1249 static bool PathExistsToClonedNode(const DSNode *N, ReachabilityCloner &RC) {
1251 for (df_iterator<const DSNode*> I = df_begin(N), E = df_end(N); I != E; ++I)
1252 if (RC.hasClonedNode(*I))
1257 static bool PathExistsToClonedNode(const DSCallSite &CS,
1258 ReachabilityCloner &RC) {
1259 if (PathExistsToClonedNode(CS.getRetVal().getNode(), RC))
1261 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1262 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode(), RC))
1267 /// getFunctionArgumentsForCall - Given a function that is currently in this
1268 /// graph, return the DSNodeHandles that correspond to the pointer-compatible
1269 /// function arguments. The vector is filled in with the return value (or
1270 /// null if it is not pointer compatible), followed by all of the
1271 /// pointer-compatible arguments.
1272 void DSGraph::getFunctionArgumentsForCall(Function *F,
1273 std::vector<DSNodeHandle> &Args) const {
1274 Args.push_back(getReturnNodeFor(*F));
1275 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1276 if (isPointerType(AI->getType())) {
1277 Args.push_back(getNodeForValue(AI));
1278 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1282 /// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1283 /// nodes from G2 into 'this' graph, merging the bindings specified by the
1284 /// call site (in this graph) with the bindings specified by the vector in G2.
1285 /// The two DSGraphs must be different.
1287 void DSGraph::mergeInGraph(const DSCallSite &CS,
1288 std::vector<DSNodeHandle> &Args,
1289 const DSGraph &Graph, unsigned CloneFlags) {
1290 TIME_REGION(X, "mergeInGraph");
1292 // If this is not a recursive call, clone the graph into this graph...
1293 if (&Graph != this) {
1294 // Clone the callee's graph into the current graph, keeping track of where
1295 // scalars in the old graph _used_ to point, and of the new nodes matching
1296 // nodes of the old graph.
1297 ReachabilityCloner RC(*this, Graph, CloneFlags);
1299 // Map the return node pointer over.
1300 if (!CS.getRetVal().isNull())
1301 RC.merge(CS.getRetVal(), Args[0]);
1303 // Map over all of the arguments.
1304 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1305 if (i == Args.size()-1)
1308 // Add the link from the argument scalar to the provided value.
1309 RC.merge(CS.getPtrArg(i), Args[i+1]);
1312 // If requested, copy all of the calls.
1313 if (!(CloneFlags & DontCloneCallNodes)) {
1314 // Copy the function calls list.
1315 for (fc_iterator I = Graph.fc_begin(), E = Graph.fc_end(); I != E; ++I)
1316 FunctionCalls.push_back(DSCallSite(*I, RC));
1319 // If the user has us copying aux calls (the normal case), set up a data
1320 // structure to keep track of which ones we've copied over.
1321 std::set<const DSCallSite*> CopiedAuxCall;
1323 // Clone over all globals that appear in the caller and callee graphs.
1324 hash_set<GlobalVariable*> NonCopiedGlobals;
1325 for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1326 E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1327 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1328 if (ScalarMap.count(GV))
1329 RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
1331 NonCopiedGlobals.insert(GV);
1333 // If the global does not appear in the callers graph we generally don't
1334 // want to copy the node. However, if there is a path from the node global
1335 // node to a node that we did copy in the graph, we *must* copy it to
1336 // maintain the connection information. Every time we decide to include a
1337 // new global, this might make other globals live, so we must iterate
1339 bool MadeChange = true;
1340 while (MadeChange) {
1342 for (hash_set<GlobalVariable*>::iterator I = NonCopiedGlobals.begin();
1343 I != NonCopiedGlobals.end();) {
1344 DSNode *GlobalNode = Graph.getNodeForValue(*I).getNode();
1345 if (RC.hasClonedNode(GlobalNode)) {
1346 // Already cloned it, remove from set.
1347 NonCopiedGlobals.erase(I++);
1349 } else if (PathExistsToClonedNode(GlobalNode, RC)) {
1350 RC.getClonedNH(Graph.getNodeForValue(*I));
1351 NonCopiedGlobals.erase(I++);
1358 // If requested, copy any aux calls that can reach copied nodes.
1359 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1360 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
1361 if (CopiedAuxCall.insert(&*I).second &&
1362 PathExistsToClonedNode(*I, RC)) {
1363 AuxFunctionCalls.push_back(DSCallSite(*I, RC));
1370 // Merge the return value with the return value of the context.
1371 Args[0].mergeWith(CS.getRetVal());
1373 // Resolve all of the function arguments.
1374 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1375 if (i == Args.size()-1)
1378 // Add the link from the argument scalar to the provided value.
1379 Args[i+1].mergeWith(CS.getPtrArg(i));
1386 /// mergeInGraph - The method is used for merging graphs together. If the
1387 /// argument graph is not *this, it makes a clone of the specified graph, then
1388 /// merges the nodes specified in the call site with the formal arguments in the
1391 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1392 const DSGraph &Graph, unsigned CloneFlags) {
1393 // Fastpath for a noop inline.
1394 if (CS.getNumPtrArgs() == 0 && CS.getRetVal().isNull())
1397 // Set up argument bindings.
1398 std::vector<DSNodeHandle> Args;
1399 Graph.getFunctionArgumentsForCall(&F, Args);
1401 mergeInGraph(CS, Args, Graph, CloneFlags);
1404 /// getCallSiteForArguments - Get the arguments and return value bindings for
1405 /// the specified function in the current graph.
1407 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1408 std::vector<DSNodeHandle> Args;
1410 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1411 if (isPointerType(I->getType()))
1412 Args.push_back(getNodeForValue(I));
1414 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1417 /// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1418 /// the context of this graph, return the DSCallSite for it.
1419 DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1420 DSNodeHandle RetVal;
1421 Instruction *I = CS.getInstruction();
1422 if (isPointerType(I->getType()))
1423 RetVal = getNodeForValue(I);
1425 std::vector<DSNodeHandle> Args;
1426 Args.reserve(CS.arg_end()-CS.arg_begin());
1428 // Calculate the arguments vector...
1429 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1430 if (isPointerType((*I)->getType()))
1431 Args.push_back(getNodeForValue(*I));
1433 // Add a new function call entry...
1434 if (Function *F = CS.getCalledFunction())
1435 return DSCallSite(CS, RetVal, F, Args);
1437 return DSCallSite(CS, RetVal,
1438 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1443 // markIncompleteNodes - Mark the specified node as having contents that are not
1444 // known with the current analysis we have performed. Because a node makes all
1445 // of the nodes it can reach incomplete if the node itself is incomplete, we
1446 // must recursively traverse the data structure graph, marking all reachable
1447 // nodes as incomplete.
1449 static void markIncompleteNode(DSNode *N) {
1450 // Stop recursion if no node, or if node already marked...
1451 if (N == 0 || N->isIncomplete()) return;
1453 // Actually mark the node
1454 N->setIncompleteMarker();
1456 // Recursively process children...
1457 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1458 if (DSNode *DSN = I->getNode())
1459 markIncompleteNode(DSN);
1462 static void markIncomplete(DSCallSite &Call) {
1463 // Then the return value is certainly incomplete!
1464 markIncompleteNode(Call.getRetVal().getNode());
1466 // All objects pointed to by function arguments are incomplete!
1467 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1468 markIncompleteNode(Call.getPtrArg(i).getNode());
1471 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1472 // modified by other functions that have not been resolved yet. This marks
1473 // nodes that are reachable through three sources of "unknownness":
1475 // Global Variables, Function Calls, and Incoming Arguments
1477 // For any node that may have unknown components (because something outside the
1478 // scope of current analysis may have modified it), the 'Incomplete' flag is
1479 // added to the NodeType.
1481 void DSGraph::markIncompleteNodes(unsigned Flags) {
1482 // Mark any incoming arguments as incomplete.
1483 if (Flags & DSGraph::MarkFormalArgs)
1484 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1486 Function &F = *FI->first;
1487 if (F.getName() != "main")
1488 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1489 if (isPointerType(I->getType()))
1490 markIncompleteNode(getNodeForValue(I).getNode());
1493 // Mark stuff passed into functions calls as being incomplete.
1494 if (!shouldPrintAuxCalls())
1495 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1496 E = FunctionCalls.end(); I != E; ++I)
1499 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1500 E = AuxFunctionCalls.end(); I != E; ++I)
1503 // Mark all global nodes as incomplete...
1504 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1505 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1506 E = ScalarMap.global_end(); I != E; ++I)
1507 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1508 if (!GV->isConstant() || !GV->hasInitializer())
1509 markIncompleteNode(ScalarMap[GV].getNode());
1512 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1513 if (DSNode *N = Edge.getNode()) // Is there an edge?
1514 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
1515 // No interesting info?
1516 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1517 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1518 Edge.setTo(0, 0); // Kill the edge!
1521 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1522 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1523 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1524 if (Globals[i]->isExternal() && isa<Function>(Globals[i]))
1529 static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
1530 // Remove trivially identical function calls
1531 Calls.sort(); // Sort by callee as primary key!
1533 // Scan the call list cleaning it up as necessary...
1534 DSNode *LastCalleeNode = 0;
1535 Function *LastCalleeFunc = 0;
1536 unsigned NumDuplicateCalls = 0;
1537 bool LastCalleeContainsExternalFunction = false;
1539 unsigned NumDeleted = 0;
1540 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1542 DSCallSite &CS = *I;
1543 std::list<DSCallSite>::iterator OldIt = I++;
1545 // If the Callee is a useless edge, this must be an unreachable call site,
1547 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
1548 CS.getCalleeNode()->isComplete() &&
1549 CS.getCalleeNode()->getGlobals().empty()) { // No useful info?
1551 std::cerr << "WARNING: Useless call site found.\n";
1558 // If the return value or any arguments point to a void node with no
1559 // information at all in it, and the call node is the only node to point
1560 // to it, remove the edge to the node (killing the node).
1562 killIfUselessEdge(CS.getRetVal());
1563 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1564 killIfUselessEdge(CS.getPtrArg(a));
1567 // If this call site calls the same function as the last call site, and if
1568 // the function pointer contains an external function, this node will
1569 // never be resolved. Merge the arguments of the call node because no
1570 // information will be lost.
1572 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1573 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1574 ++NumDuplicateCalls;
1575 if (NumDuplicateCalls == 1) {
1577 LastCalleeContainsExternalFunction =
1578 nodeContainsExternalFunction(LastCalleeNode);
1580 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1583 // It is not clear why, but enabling this code makes DSA really
1584 // sensitive to node forwarding. Basically, with this enabled, DSA
1585 // performs different number of inlinings based on which nodes are
1586 // forwarding or not. This is clearly a problem, so this code is
1587 // disabled until this can be resolved.
1589 if (LastCalleeContainsExternalFunction
1592 // This should be more than enough context sensitivity!
1593 // FIXME: Evaluate how many times this is tripped!
1594 NumDuplicateCalls > 20
1598 std::list<DSCallSite>::iterator PrevIt = OldIt;
1600 PrevIt->mergeWith(CS);
1602 // No need to keep this call anymore.
1609 if (CS.isDirectCall()) {
1610 LastCalleeFunc = CS.getCalleeFunc();
1613 LastCalleeNode = CS.getCalleeNode();
1616 NumDuplicateCalls = 0;
1620 if (I != Calls.end() && CS == *I) {
1627 // Resort now that we simplified things.
1630 // Now that we are in sorted order, eliminate duplicates.
1631 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1634 std::list<DSCallSite>::iterator OldIt = CI++;
1635 if (CI == CE) break;
1637 // If this call site is now the same as the previous one, we can delete it
1639 if (*OldIt == *CI) {
1646 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
1648 // Track the number of call nodes merged away...
1649 NumCallNodesMerged += NumDeleted;
1651 DEBUG(if (NumDeleted)
1652 std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
1656 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1657 // removes all unreachable nodes that are created because they got merged with
1658 // other nodes in the graph. These nodes will all be trivially unreachable, so
1659 // we don't have to perform any non-trivial analysis here.
1661 void DSGraph::removeTriviallyDeadNodes() {
1662 TIME_REGION(X, "removeTriviallyDeadNodes");
1665 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1668 // Loop over all of the nodes in the graph, calling getNode on each field.
1669 // This will cause all nodes to update their forwarding edges, causing
1670 // forwarded nodes to be delete-able.
1671 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
1672 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1674 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1675 N->getLink(l*N->getPointerSize()).getNode();
1679 // NOTE: This code is disabled. Though it should, in theory, allow us to
1680 // remove more nodes down below, the scan of the scalar map is incredibly
1681 // expensive for certain programs (with large SCCs). In the future, if we can
1682 // make the scalar map scan more efficient, then we can reenable this.
1683 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1685 // Likewise, forward any edges from the scalar nodes. While we are at it,
1686 // clean house a bit.
1687 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1688 I->second.getNode();
1693 bool isGlobalsGraph = !GlobalsGraph;
1695 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
1698 // Do not remove *any* global nodes in the globals graph.
1699 // This is a special case because such nodes may not have I, M, R flags set.
1700 if (Node.isGlobalNode() && isGlobalsGraph) {
1705 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
1706 // This is a useless node if it has no mod/ref info (checked above),
1707 // outgoing edges (which it cannot, as it is not modified in this
1708 // context), and it has no incoming edges. If it is a global node it may
1709 // have all of these properties and still have incoming edges, due to the
1710 // scalar map, so we check those now.
1712 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1713 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
1715 // Loop through and make sure all of the globals are referring directly
1717 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1718 DSNode *N = getNodeForValue(Globals[j]).getNode();
1719 assert(N == &Node && "ScalarMap doesn't match globals list!");
1722 // Make sure NumReferrers still agrees, if so, the node is truly dead.
1723 if (Node.getNumReferrers() == Globals.size()) {
1724 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1725 ScalarMap.erase(Globals[j]);
1726 Node.makeNodeDead();
1727 ++NumTrivialGlobalDNE;
1732 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
1733 // This node is dead!
1734 NI = Nodes.erase(NI); // Erase & remove from node list.
1741 removeIdenticalCalls(FunctionCalls);
1742 removeIdenticalCalls(AuxFunctionCalls);
1746 /// markReachableNodes - This method recursively traverses the specified
1747 /// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1748 /// to the set, which allows it to only traverse visited nodes once.
1750 void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
1751 if (this == 0) return;
1752 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1753 if (ReachableNodes.insert(this).second) // Is newly reachable?
1754 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
1756 I->getNode()->markReachableNodes(ReachableNodes);
1759 void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
1760 getRetVal().getNode()->markReachableNodes(Nodes);
1761 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1763 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1764 getPtrArg(i).getNode()->markReachableNodes(Nodes);
1767 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1768 // looking for a node that is marked alive. If an alive node is found, return
1769 // true, otherwise return false. If an alive node is reachable, this node is
1770 // marked as alive...
1772 static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
1773 hash_set<const DSNode*> &Visited,
1774 bool IgnoreGlobals) {
1775 if (N == 0) return false;
1776 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1778 // If this is a global node, it will end up in the globals graph anyway, so we
1779 // don't need to worry about it.
1780 if (IgnoreGlobals && N->isGlobalNode()) return false;
1782 // If we know that this node is alive, return so!
1783 if (Alive.count(N)) return true;
1785 // Otherwise, we don't think the node is alive yet, check for infinite
1787 if (Visited.count(N)) return false; // Found a cycle
1788 Visited.insert(N); // No recursion, insert into Visited...
1790 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1791 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
1792 N->markReachableNodes(Alive);
1798 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1801 static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
1802 hash_set<const DSNode*> &Alive,
1803 hash_set<const DSNode*> &Visited,
1804 bool IgnoreGlobals) {
1805 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1808 if (CS.isIndirectCall() &&
1809 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
1811 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1812 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1818 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1819 // subgraphs that are unreachable. This often occurs because the data
1820 // structure doesn't "escape" into it's caller, and thus should be eliminated
1821 // from the caller's graph entirely. This is only appropriate to use when
1824 void DSGraph::removeDeadNodes(unsigned Flags) {
1825 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
1827 // Reduce the amount of work we have to do... remove dummy nodes left over by
1829 removeTriviallyDeadNodes();
1831 TIME_REGION(X, "removeDeadNodes");
1833 // FIXME: Merge non-trivially identical call nodes...
1835 // Alive - a set that holds all nodes found to be reachable/alive.
1836 hash_set<const DSNode*> Alive;
1837 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1839 // Copy and merge all information about globals to the GlobalsGraph if this is
1840 // not a final pass (where unreachable globals are removed).
1842 // Strip all alloca bits since the current function is only for the BU pass.
1843 // Strip all incomplete bits since they are short-lived properties and they
1844 // will be correctly computed when rematerializing nodes into the functions.
1846 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1847 DSGraph::StripIncompleteBit);
1849 // Mark all nodes reachable by (non-global) scalar nodes as alive...
1850 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
1851 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
1852 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
1853 assert(!I->second.isNull() && "Null global node?");
1854 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
1855 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1857 // Make sure that all globals are cloned over as roots.
1858 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1859 DSGraph::ScalarMapTy::iterator SMI =
1860 GlobalsGraph->getScalarMap().find(I->first);
1861 if (SMI != GlobalsGraph->getScalarMap().end())
1862 GGCloner.merge(SMI->second, I->second);
1864 GGCloner.getClonedNH(I->second);
1868 DSNode *N = I->second.getNode();
1870 // Check to see if this is a worthless node generated for non-pointer
1871 // values, such as integers. Consider an addition of long types: A+B.
1872 // Assuming we can track all uses of the value in this context, and it is
1873 // NOT used as a pointer, we can delete the node. We will be able to
1874 // detect this situation if the node pointed to ONLY has Unknown bit set
1875 // in the node. In this case, the node is not incomplete, does not point
1876 // to any other nodes (no mod/ref bits set), and is therefore
1877 // uninteresting for data structure analysis. If we run across one of
1878 // these, prune the scalar pointing to it.
1880 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1881 ScalarMap.erase(I++);
1884 N->markReachableNodes(Alive);
1890 // The return values are alive as well.
1891 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1893 I->second.getNode()->markReachableNodes(Alive);
1895 // Mark any nodes reachable by primary calls as alive...
1896 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
1897 I->markReachableNodes(Alive);
1900 // Now find globals and aux call nodes that are already live or reach a live
1901 // value (which makes them live in turn), and continue till no more are found.
1904 hash_set<const DSNode*> Visited;
1905 hash_set<const DSCallSite*> AuxFCallsAlive;
1908 // If any global node points to a non-global that is "alive", the global is
1909 // "alive" as well... Remove it from the GlobalNodes list so we only have
1910 // unreachable globals in the list.
1913 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1914 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1915 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1916 Flags & DSGraph::RemoveUnreachableGlobals)) {
1917 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1918 GlobalNodes.pop_back(); // erase efficiently
1922 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1923 // call nodes that get resolved will be difficult to remove from that graph.
1924 // The final unresolved call nodes must be handled specially at the end of
1925 // the BU pass (i.e., in main or other roots of the call graph).
1926 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
1927 if (AuxFCallsAlive.insert(&*CI).second &&
1928 (CI->isIndirectCall()
1929 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
1930 Flags & DSGraph::RemoveUnreachableGlobals))) {
1931 CI->markReachableNodes(Alive);
1936 // Move dead aux function calls to the end of the list
1937 unsigned CurIdx = 0;
1938 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
1939 E = AuxFunctionCalls.end(); CI != E; )
1940 if (AuxFCallsAlive.count(&*CI))
1943 // Copy and merge global nodes and dead aux call nodes into the
1944 // GlobalsGraph, and all nodes reachable from those nodes. Update their
1945 // target pointers using the GGCloner.
1947 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1948 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
1950 AuxFunctionCalls.erase(CI++);
1953 // We are finally done with the GGCloner so we can destroy it.
1956 // At this point, any nodes which are visited, but not alive, are nodes
1957 // which can be removed. Loop over all nodes, eliminating completely
1958 // unreachable nodes.
1960 std::vector<DSNode*> DeadNodes;
1961 DeadNodes.reserve(Nodes.size());
1962 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1964 assert(!N->isForwarding() && "Forwarded node in nodes list?");
1966 if (!Alive.count(N)) {
1968 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
1969 DeadNodes.push_back(N);
1970 N->dropAllReferences();
1975 // Remove all unreachable globals from the ScalarMap.
1976 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1977 // In either case, the dead nodes will not be in the set Alive.
1978 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1979 if (!Alive.count(GlobalNodes[i].second))
1980 ScalarMap.erase(GlobalNodes[i].first);
1982 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
1984 // Delete all dead nodes now since their referrer counts are zero.
1985 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1986 delete DeadNodes[i];
1988 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1991 void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
1992 assert(std::find(N->getGlobals().begin(), N->getGlobals().end(), GV) !=
1993 N->getGlobals().end() && "Global value not in node!");
1996 void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
1997 if (CS.isIndirectCall()) {
1998 AssertNodeInGraph(CS.getCalleeNode());
2000 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2001 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
2002 std::cerr << "WARNING: WIERD CALL SITE FOUND!\n";
2005 AssertNodeInGraph(CS.getRetVal().getNode());
2006 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2007 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2010 void DSGraph::AssertCallNodesInGraph() const {
2011 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2012 AssertCallSiteInGraph(*I);
2014 void DSGraph::AssertAuxCallNodesInGraph() const {
2015 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2016 AssertCallSiteInGraph(*I);
2019 void DSGraph::AssertGraphOK() const {
2020 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2023 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
2024 E = ScalarMap.end(); I != E; ++I) {
2025 assert(!I->second.isNull() && "Null node in scalarmap!");
2026 AssertNodeInGraph(I->second.getNode());
2027 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
2028 assert(I->second.getNode()->isGlobalNode() &&
2029 "Global points to node, but node isn't global?");
2030 AssertNodeContainsGlobal(I->second.getNode(), GV);
2033 AssertCallNodesInGraph();
2034 AssertAuxCallNodesInGraph();
2036 // Check that all pointer arguments to any functions in this graph have
2038 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2039 E = ReturnNodes.end();
2041 Function &F = *RI->first;
2042 for (Function::aiterator AI = F.abegin(); AI != F.aend(); ++AI)
2043 if (isPointerType(AI->getType()))
2044 assert(!getNodeForValue(AI).isNull() &&
2045 "Pointer argument must be in the scalar map!");
2049 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
2050 /// nodes reachable from the two graphs, computing the mapping of nodes from the
2051 /// first to the second graph. This mapping may be many-to-one (i.e. the first
2052 /// graph may have multiple nodes representing one node in the second graph),
2053 /// but it will not work if there is a one-to-many or many-to-many mapping.
2055 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
2056 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2057 bool StrictChecking) {
2058 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2059 if (N1 == 0 || N2 == 0) return;
2061 DSNodeHandle &Entry = NodeMap[N1];
2062 if (!Entry.isNull()) {
2063 // Termination of recursion!
2064 if (StrictChecking) {
2065 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2066 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2067 Entry.getNode()->isNodeCompletelyFolded()) &&
2068 "Inconsistent mapping detected!");
2073 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
2075 // Loop over all of the fields that N1 and N2 have in common, recursively
2076 // mapping the edges together now.
2077 int N2Idx = NH2.getOffset()-NH1.getOffset();
2078 unsigned N2Size = N2->getSize();
2079 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
2080 if (unsigned(N2Idx)+i < N2Size)
2081 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
2083 computeNodeMapping(N1->getLink(i),
2084 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);