blob: 5f232e2054d847e3a8caee794898589db001fea7 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00002//
Chris Lattnerc68c31b2002-07-10 22:38:08 +00003// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00004//
5//===----------------------------------------------------------------------===//
6
Chris Lattnerfccd06f2002-10-01 22:33:50 +00007#include "llvm/Analysis/DSGraph.h"
8#include "llvm/Function.h"
Vikram S. Adve26b98262002-10-20 21:41:02 +00009#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000011#include "llvm/Target/TargetData.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000012#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000013#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000014#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000015#include <algorithm>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000016
Chris Lattner08db7192002-11-06 06:20:27 +000017namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000018 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
19 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000020};
21
Chris Lattnerb1060432002-11-07 05:20:53 +000022namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000023 extern TargetData TD;
24}
Chris Lattnerb1060432002-11-07 05:20:53 +000025using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000026
Chris Lattner731b2d72003-02-13 19:09:00 +000027DSNode *DSNodeHandle::HandleForwarding() const {
28 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
29
30 // Handle node forwarding here!
31 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
32 Offset += N->ForwardNH.getOffset();
33
34 if (--N->NumReferrers == 0) {
35 // Removing the last referrer to the node, sever the forwarding link
36 N->stopForwarding();
37 }
38
39 N = Next;
40 N->NumReferrers++;
41 if (N->Size <= Offset) {
42 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
43 Offset = 0;
44 }
45 return N;
46}
47
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000048//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000049// DSNode Implementation
50//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000051
Chris Lattner72d29a42003-02-11 23:11:51 +000052DSNode::DSNode(unsigned NT, const Type *T, DSGraph *G)
53 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(NT) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000054 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000055 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000056 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000057}
58
Chris Lattner0d9bab82002-07-18 00:12:30 +000059// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000060DSNode::DSNode(const DSNode &N, DSGraph *G)
61 : NumReferrers(0), Size(N.Size), ParentGraph(G), Ty(N.Ty),
62 Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
63 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000064}
65
Chris Lattner72d29a42003-02-11 23:11:51 +000066void DSNode::assertOK() const {
67 assert((Ty != Type::VoidTy ||
68 Ty == Type::VoidTy && (Size == 0 ||
69 (NodeType & DSNode::Array))) &&
70 "Node not OK!");
71}
72
73/// forwardNode - Mark this node as being obsolete, and all references to it
74/// should be forwarded to the specified node and offset.
75///
76void DSNode::forwardNode(DSNode *To, unsigned Offset) {
77 assert(this != To && "Cannot forward a node to itself!");
78 assert(ForwardNH.isNull() && "Already forwarding from this node!");
79 if (To->Size <= 1) Offset = 0;
80 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
81 "Forwarded offset is wrong!");
82 ForwardNH.setNode(To);
83 ForwardNH.setOffset(Offset);
84 NodeType = DEAD;
85 Size = 0;
86 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000087}
88
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000089// addGlobal - Add an entry for a global value to the Globals list. This also
90// marks the node with the 'G' flag if it does not already have it.
91//
92void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000093 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +000094 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000095 std::lower_bound(Globals.begin(), Globals.end(), GV);
96
97 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000098 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000099 Globals.insert(I, GV);
100 NodeType |= GlobalNode;
101 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000102}
103
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000104/// foldNodeCompletely - If we determine that this node has some funny
105/// behavior happening to it that we cannot represent, we fold it down to a
106/// single, completely pessimistic, node. This node is represented as a
107/// single byte with a single TypeEntry of "void".
108///
109void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000110 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000111
Chris Lattner08db7192002-11-06 06:20:27 +0000112 ++NumFolds;
113
Chris Lattner72d29a42003-02-11 23:11:51 +0000114 // Create the node we are going to forward to...
115 DSNode *DestNode = new DSNode(NodeType|DSNode::Array, 0, ParentGraph);
116 DestNode->Ty = Type::VoidTy;
117 DestNode->Size = 1;
118 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000119
Chris Lattner72d29a42003-02-11 23:11:51 +0000120 // Start forwarding to the destination node...
121 forwardNode(DestNode, 0);
122
123 if (Links.size()) {
124 DestNode->Links.push_back(Links[0]);
125 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000126
Chris Lattner72d29a42003-02-11 23:11:51 +0000127 // If we have links, merge all of our outgoing links together...
128 for (unsigned i = Links.size()-1; i != 0; --i)
129 NH.getNode()->Links[0].mergeWith(Links[i]);
130 Links.clear();
131 } else {
132 DestNode->Links.resize(1);
133 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000134}
Chris Lattner076c1f92002-11-07 06:31:54 +0000135
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000136/// isNodeCompletelyFolded - Return true if this node has been completely
137/// folded down to something that can never be expanded, effectively losing
138/// all of the field sensitivity that may be present in the node.
139///
140bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000141 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000142}
143
144
Chris Lattner08db7192002-11-06 06:20:27 +0000145/// mergeTypeInfo - This method merges the specified type into the current node
146/// at the specified offset. This may update the current node's type record if
147/// this gives more information to the node, it may do nothing to the node if
148/// this information is already known, or it may merge the node completely (and
149/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000150///
Chris Lattner08db7192002-11-06 06:20:27 +0000151/// This method returns true if the node is completely folded, otherwise false.
152///
Chris Lattner088b6392003-03-03 17:13:31 +0000153bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
154 bool FoldIfIncompatible) {
Chris Lattner08db7192002-11-06 06:20:27 +0000155 // Check to make sure the Size member is up-to-date. Size can be one of the
156 // following:
157 // Size = 0, Ty = Void: Nothing is known about this node.
158 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
159 // Size = 1, Ty = Void, Array = 1: The node is collapsed
160 // Otherwise, sizeof(Ty) = Size
161 //
Chris Lattner18552922002-11-18 21:44:46 +0000162 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
163 (Size == 0 && !Ty->isSized() && !isArray()) ||
164 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
165 (Size == 0 && !Ty->isSized() && !isArray()) ||
166 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000167 "Size member of DSNode doesn't match the type structure!");
168 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000169
Chris Lattner18552922002-11-18 21:44:46 +0000170 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000171 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000172
Chris Lattner08db7192002-11-06 06:20:27 +0000173 // Return true immediately if the node is completely folded.
174 if (isNodeCompletelyFolded()) return true;
175
Chris Lattner23f83dc2002-11-08 22:49:57 +0000176 // If this is an array type, eliminate the outside arrays because they won't
177 // be used anyway. This greatly reduces the size of large static arrays used
178 // as global variables, for example.
179 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000180 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000181 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
182 // FIXME: we might want to keep small arrays, but must be careful about
183 // things like: [2 x [10000 x int*]]
184 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000185 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000186 }
187
Chris Lattner08db7192002-11-06 06:20:27 +0000188 // Figure out how big the new type we're merging in is...
189 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
190
191 // Otherwise check to see if we can fold this type into the current node. If
192 // we can't, we fold the node completely, if we can, we potentially update our
193 // internal state.
194 //
Chris Lattner18552922002-11-18 21:44:46 +0000195 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000196 // If this is the first type that this node has seen, just accept it without
197 // question....
198 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000199 assert(!isArray() && "This shouldn't happen!");
200 Ty = NewTy;
201 NodeType &= ~Array;
202 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000203 Size = NewTySize;
204
205 // Calculate the number of outgoing links from this node.
206 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
207 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000208 }
Chris Lattner08db7192002-11-06 06:20:27 +0000209
210 // Handle node expansion case here...
211 if (Offset+NewTySize > Size) {
212 // It is illegal to grow this node if we have treated it as an array of
213 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000214 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000215 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000216 return true;
217 }
218
219 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner3c87b292002-11-07 01:54:56 +0000220 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
221 << "offset != 0: Collapsing!\n");
Chris Lattner088b6392003-03-03 17:13:31 +0000222 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000223 return true;
224 }
225
226 // Okay, the situation is nice and simple, we are trying to merge a type in
227 // at offset 0 that is bigger than our current type. Implement this by
228 // switching to the new type and then merge in the smaller one, which should
229 // hit the other code path here. If the other code path decides it's not
230 // ok, it will collapse the node as appropriate.
231 //
Chris Lattner18552922002-11-18 21:44:46 +0000232 const Type *OldTy = Ty;
233 Ty = NewTy;
234 NodeType &= ~Array;
235 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000236 Size = NewTySize;
237
238 // Must grow links to be the appropriate size...
239 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
240
241 // Merge in the old type now... which is guaranteed to be smaller than the
242 // "current" type.
243 return mergeTypeInfo(OldTy, 0);
244 }
245
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000246 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000247 "Cannot merge something into a part of our type that doesn't exist!");
248
Chris Lattner18552922002-11-18 21:44:46 +0000249 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000250 // type that starts at offset Offset.
251 //
252 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000253 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000254 while (O < Offset) {
255 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
256
257 switch (SubType->getPrimitiveID()) {
258 case Type::StructTyID: {
259 const StructType *STy = cast<StructType>(SubType);
260 const StructLayout &SL = *TD.getStructLayout(STy);
261
262 unsigned i = 0, e = SL.MemberOffsets.size();
263 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
264 /* empty */;
265
266 // The offset we are looking for must be in the i'th element...
267 SubType = STy->getElementTypes()[i];
268 O += SL.MemberOffsets[i];
269 break;
270 }
271 case Type::ArrayTyID: {
272 SubType = cast<ArrayType>(SubType)->getElementType();
273 unsigned ElSize = TD.getTypeSize(SubType);
274 unsigned Remainder = (Offset-O) % ElSize;
275 O = Offset-Remainder;
276 break;
277 }
278 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000279 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000280 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000281 }
282 }
283
284 assert(O == Offset && "Could not achieve the correct offset!");
285
286 // If we found our type exactly, early exit
287 if (SubType == NewTy) return false;
288
289 // Okay, so we found the leader type at the offset requested. Search the list
290 // of types that starts at this offset. If SubType is currently an array or
291 // structure, the type desired may actually be the first element of the
292 // composite type...
293 //
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000294 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
Chris Lattner18552922002-11-18 21:44:46 +0000295 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000296 while (SubType != NewTy) {
297 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000298 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000299 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000300 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000301 case Type::StructTyID: {
302 const StructType *STy = cast<StructType>(SubType);
303 const StructLayout &SL = *TD.getStructLayout(STy);
304 if (SL.MemberOffsets.size() > 1)
305 NextPadSize = SL.MemberOffsets[1];
306 else
307 NextPadSize = SubTypeSize;
308 NextSubType = STy->getElementTypes()[0];
309 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000310 break;
Chris Lattner18552922002-11-18 21:44:46 +0000311 }
Chris Lattner08db7192002-11-06 06:20:27 +0000312 case Type::ArrayTyID:
313 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000314 NextSubTypeSize = TD.getTypeSize(NextSubType);
315 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000316 break;
317 default: ;
318 // fall out
319 }
320
321 if (NextSubType == 0)
322 break; // In the default case, break out of the loop
323
Chris Lattner18552922002-11-18 21:44:46 +0000324 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000325 break; // Don't allow shrinking to a smaller type than NewTySize
326 SubType = NextSubType;
327 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000328 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000329 }
330
331 // If we found the type exactly, return it...
332 if (SubType == NewTy)
333 return false;
334
335 // Check to see if we have a compatible, but different type...
336 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000337 // Check to see if this type is obviously convertible... int -> uint f.e.
338 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000339 return false;
340
341 // Check to see if we have a pointer & integer mismatch going on here,
342 // loading a pointer as a long, for example.
343 //
344 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
345 NewTy->isInteger() && isa<PointerType>(SubType))
346 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000347 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
348 // We are accessing the field, plus some structure padding. Ignore the
349 // structure padding.
350 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000351 }
352
353
Chris Lattner18552922002-11-18 21:44:46 +0000354 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
Chris Lattner3c87b292002-11-07 01:54:56 +0000355 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
356 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000357
Chris Lattner088b6392003-03-03 17:13:31 +0000358 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000359 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000360}
361
Chris Lattner08db7192002-11-06 06:20:27 +0000362
363
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000364// addEdgeTo - Add an edge from the current node to the specified node. This
365// can cause merging of nodes in the graph.
366//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000367void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000368 if (NH.getNode() == 0) return; // Nothing to do
369
Chris Lattner08db7192002-11-06 06:20:27 +0000370 DSNodeHandle &ExistingEdge = getLink(Offset);
371 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000372 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000373 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000374 } else { // No merging to perform...
375 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000376 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000377}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000378
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000379
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000380// MergeSortedVectors - Efficiently merge a vector into another vector where
381// duplicates are not allowed and both are sorted. This assumes that 'T's are
382// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000383//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000384static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
385 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000386 // By far, the most common cases will be the simple ones. In these cases,
387 // avoid having to allocate a temporary vector...
388 //
389 if (Src.empty()) { // Nothing to merge in...
390 return;
391 } else if (Dest.empty()) { // Just copy the result in...
392 Dest = Src;
393 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000394 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000395 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000396 std::lower_bound(Dest.begin(), Dest.end(), V);
397 if (I == Dest.end() || *I != Src[0]) // If not already contained...
398 Dest.insert(I, Src[0]);
399 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000400 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000401 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000402 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000403 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
404 if (I == Dest.end() || *I != Tmp) // If not already contained...
405 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000406
407 } else {
408 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000409 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000410
411 // Make space for all of the type entries now...
412 Dest.resize(Dest.size()+Src.size());
413
414 // Merge the two sorted ranges together... into Dest.
415 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
416
417 // Now erase any duplicate entries that may have accumulated into the
418 // vectors (because they were in both of the input sets)
419 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
420 }
421}
422
423
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000424// MergeNodes() - Helper function for DSNode::mergeWith().
425// This function does the hard work of merging two nodes, CurNodeH
426// and NH after filtering out trivial cases and making sure that
427// CurNodeH.offset >= NH.offset.
428//
429// ***WARNING***
430// Since merging may cause either node to go away, we must always
431// use the node-handles to refer to the nodes. These node handles are
432// automatically updated during merging, so will always provide access
433// to the correct node after a merge.
434//
435void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
436 assert(CurNodeH.getOffset() >= NH.getOffset() &&
437 "This should have been enforced in the caller.");
438
439 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
440 // respect to NH.Offset) is now zero. NOffset is the distance from the base
441 // of our object that N starts from.
442 //
443 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
444 unsigned NSize = NH.getNode()->getSize();
445
446 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000447 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000448 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000449 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
450
451 // If we are merging a node with a completely folded node, then both nodes are
452 // now completely folded.
453 //
454 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
455 if (!NH.getNode()->isNodeCompletelyFolded()) {
456 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000457 assert(NH.getNode() && NH.getOffset() == 0 &&
458 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000459 NOffset = NH.getOffset();
460 NSize = NH.getNode()->getSize();
461 assert(NOffset == 0 && NSize == 1);
462 }
463 } else if (NH.getNode()->isNodeCompletelyFolded()) {
464 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000465 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
466 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000467 NOffset = NH.getOffset();
468 NSize = NH.getNode()->getSize();
469 assert(NOffset == 0 && NSize == 1);
470 }
471
Chris Lattner72d29a42003-02-11 23:11:51 +0000472 DSNode *N = NH.getNode();
473 if (CurNodeH.getNode() == N || N == 0) return;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000474 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
475
Chris Lattner72d29a42003-02-11 23:11:51 +0000476 // Start forwarding to the new node!
477 CurNodeH.getNode()->NodeType |= N->NodeType;
478 N->forwardNode(CurNodeH.getNode(), NOffset);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000479 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
480
Chris Lattner72d29a42003-02-11 23:11:51 +0000481 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
482 //
483 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
484 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000485 if (Link.getNode()) {
486 // Compute the offset into the current node at which to
487 // merge this link. In the common case, this is a linear
488 // relation to the offset in the original node (with
489 // wrapping), but if the current node gets collapsed due to
490 // recursive merging, we must make sure to merge in all remaining
491 // links at offset zero.
492 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000493 DSNode *CN = CurNodeH.getNode();
494 if (CN->Size != 1)
495 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
496 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000497 }
498 }
499
500 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000501 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000502
503 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000504 if (!N->Globals.empty()) {
505 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000506
507 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000508 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000509 }
510}
511
512
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000513// mergeWith - Merge this node and the specified node, moving all links to and
514// from the argument node into the current node, deleting the node argument.
515// Offset indicates what offset the specified node is to be merged into the
516// current node.
517//
518// The specified node may be a null pointer (in which case, nothing happens).
519//
520void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
521 DSNode *N = NH.getNode();
522 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000523 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000524
Chris Lattner679e8e12002-11-08 21:27:12 +0000525 assert((N->NodeType & DSNode::DEAD) == 0);
526 assert((NodeType & DSNode::DEAD) == 0);
527 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
528
Chris Lattner02606632002-11-04 06:48:26 +0000529 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000530 // We cannot merge two pieces of the same node together, collapse the node
531 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000532 DEBUG(std::cerr << "Attempting to merge two chunks of"
533 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000534 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000535 return;
536 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000537
Chris Lattner5190ce82002-11-12 07:20:45 +0000538 // If both nodes are not at offset 0, make sure that we are merging the node
539 // at an later offset into the node with the zero offset.
540 //
541 if (Offset < NH.getOffset()) {
542 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
543 return;
544 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
545 // If the offsets are the same, merge the smaller node into the bigger node
546 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
547 return;
548 }
549
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000550 // Ok, now we can merge the two nodes. Use a static helper that works with
551 // two node handles, since "this" may get merged away at intermediate steps.
552 DSNodeHandle CurNodeH(this, Offset);
553 DSNodeHandle NHCopy(NH);
554 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000555}
556
Chris Lattner9de906c2002-10-20 22:11:44 +0000557//===----------------------------------------------------------------------===//
558// DSCallSite Implementation
559//===----------------------------------------------------------------------===//
560
Vikram S. Adve26b98262002-10-20 21:41:02 +0000561// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000562Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000563 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000564}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000565
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000566
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000567//===----------------------------------------------------------------------===//
568// DSGraph Implementation
569//===----------------------------------------------------------------------===//
570
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000571DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000572 PrintAuxCalls = false;
Chris Lattner41c04f72003-02-01 04:52:08 +0000573 hash_map<const DSNode*, DSNodeHandle> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000574 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000575}
576
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000577DSGraph::DSGraph(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000578 hash_map<const DSNode*, DSNodeHandle> &NodeMap)
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000579 : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000580 PrintAuxCalls = false;
Chris Lattnerc875f022002-11-03 21:27:48 +0000581 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000582}
583
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000584DSGraph::~DSGraph() {
585 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000586 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000587 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000588 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000589
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000590 // Drop all intra-node references, so that assertions don't fail...
591 std::for_each(Nodes.begin(), Nodes.end(),
592 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000593
594 // Delete all of the nodes themselves...
595 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
596}
597
Chris Lattner0d9bab82002-07-18 00:12:30 +0000598// dump - Allow inspection of graph in a debugger.
599void DSGraph::dump() const { print(std::cerr); }
600
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000601
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000602/// remapLinks - Change all of the Links in the current node according to the
603/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000604///
Chris Lattner41c04f72003-02-01 04:52:08 +0000605void DSNode::remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000606 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
607 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
608 Links[i].setNode(H.getNode());
609 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
610 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000611}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000612
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000613
Chris Lattner0d9bab82002-07-18 00:12:30 +0000614// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000615// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000616// filled into the OldValMap member. If StripAllocas is set to true, Alloca
617// markers are removed from the graph, as the graph is being cloned into a
618// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000619//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000620DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000621 hash_map<Value*, DSNodeHandle> &OldValMap,
622 hash_map<const DSNode*, DSNodeHandle> &OldNodeMap,
Chris Lattner679e8e12002-11-08 21:27:12 +0000623 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000624 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000625 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000626
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000627 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000628
629 // Duplicate all of the nodes, populating the node map...
630 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000631
632 // Remove alloca or mod/ref bits as specified...
633 unsigned clearBits = (CloneFlags & StripAllocaBit ? DSNode::AllocaNode : 0)
634 | (CloneFlags & StripModRefBits ? (DSNode::Modified | DSNode::Read) : 0);
635 clearBits |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000636 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000637 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000638 DSNode *New = new DSNode(*Old, this);
Chris Lattner1e883692003-02-03 20:08:51 +0000639 New->NodeType &= ~clearBits;
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000640 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000641 }
642
Chris Lattner18552922002-11-18 21:44:46 +0000643#ifndef NDEBUG
644 Timer::addPeakMemoryMeasurement();
645#endif
646
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000647 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000648 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000649 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000650
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000651 // Copy the scalar map... merging all of the global nodes...
Chris Lattner41c04f72003-02-01 04:52:08 +0000652 for (hash_map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000653 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000654 DSNodeHandle &H = OldValMap[I->first];
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000655 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000656 H.setOffset(I->second.getOffset()+MappedNode.getOffset());
Chris Lattner72d29a42003-02-11 23:11:51 +0000657 H.setNode(MappedNode.getNode());
Chris Lattnercf15db32002-10-17 20:09:52 +0000658
659 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattner41c04f72003-02-01 04:52:08 +0000660 hash_map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000661 if (GVI != ScalarMap.end()) // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000662 GVI->second.mergeWith(H);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000663 else
Chris Lattnerc875f022002-11-03 21:27:48 +0000664 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000665 }
666 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000667
Chris Lattner679e8e12002-11-08 21:27:12 +0000668 if (!(CloneFlags & DontCloneCallNodes)) {
669 // Copy the function calls list...
670 unsigned FC = FunctionCalls.size(); // FirstCall
671 FunctionCalls.reserve(FC+G.FunctionCalls.size());
672 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
673 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000674 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000675
Chris Lattneracf491f2002-11-08 22:27:09 +0000676 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000677 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000678 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000679 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
680 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
681 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
682 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000683
Chris Lattner0d9bab82002-07-18 00:12:30 +0000684 // Return the returned node pointer...
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000685 DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
686 return DSNodeHandle(MappedRet.getNode(),
687 MappedRet.getOffset()+G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000688}
689
Chris Lattner076c1f92002-11-07 06:31:54 +0000690/// mergeInGraph - The method is used for merging graphs together. If the
691/// argument graph is not *this, it makes a clone of the specified graph, then
692/// merges the nodes specified in the call site with the formal arguments in the
693/// graph.
694///
695void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
Chris Lattner679e8e12002-11-08 21:27:12 +0000696 unsigned CloneFlags) {
Chris Lattner41c04f72003-02-01 04:52:08 +0000697 hash_map<Value*, DSNodeHandle> OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000698 DSNodeHandle RetVal;
Chris Lattner41c04f72003-02-01 04:52:08 +0000699 hash_map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000700
701 // If this is not a recursive call, clone the graph into this graph...
702 if (&Graph != this) {
703 // Clone the callee's graph into the current graph, keeping
704 // track of where scalars in the old graph _used_ to point,
705 // and of the new nodes matching nodes of the old graph.
Chris Lattner41c04f72003-02-01 04:52:08 +0000706 hash_map<const DSNode*, DSNodeHandle> OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000707
708 // The clone call may invalidate any of the vectors in the data
709 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner679e8e12002-11-08 21:27:12 +0000710 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
Chris Lattner076c1f92002-11-07 06:31:54 +0000711 ScalarMap = &OldValMap;
712 } else {
713 RetVal = getRetNode();
714 ScalarMap = &getScalarMap();
715 }
716
717 // Merge the return value with the return value of the context...
718 RetVal.mergeWith(CS.getRetVal());
719
720 // Resolve all of the function arguments...
721 Function &F = Graph.getFunction();
722 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000723
Chris Lattner076c1f92002-11-07 06:31:54 +0000724 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
725 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +0000726 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +0000727 ++AI;
728#ifndef NDEBUG
729 if (AI == F.aend())
730 std::cerr << "Bad call to Function: " << F.getName() << "\n";
731#endif
Chris Lattner076c1f92002-11-07 06:31:54 +0000732 }
Chris Lattner5d274582003-02-06 00:15:08 +0000733 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +0000734
735 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +0000736 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +0000737 DSNodeHandle &NH = (*ScalarMap)[AI];
738 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
739 NH.mergeWith(CS.getPtrArg(i));
740 }
741}
742
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000743
Chris Lattner0d9bab82002-07-18 00:12:30 +0000744// markIncompleteNodes - Mark the specified node as having contents that are not
745// known with the current analysis we have performed. Because a node makes all
746// of the nodes it can reach imcomplete if the node itself is incomplete, we
747// must recursively traverse the data structure graph, marking all reachable
748// nodes as incomplete.
749//
750static void markIncompleteNode(DSNode *N) {
751 // Stop recursion if no node, or if node already marked...
752 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
753
754 // Actually mark the node
755 N->NodeType |= DSNode::Incomplete;
756
757 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000758 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
759 if (DSNode *DSN = N->getLink(i).getNode())
760 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000761}
762
Chris Lattnere71ffc22002-11-11 03:36:55 +0000763static void markIncomplete(DSCallSite &Call) {
764 // Then the return value is certainly incomplete!
765 markIncompleteNode(Call.getRetVal().getNode());
766
767 // All objects pointed to by function arguments are incomplete!
768 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
769 markIncompleteNode(Call.getPtrArg(i).getNode());
770}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000771
772// markIncompleteNodes - Traverse the graph, identifying nodes that may be
773// modified by other functions that have not been resolved yet. This marks
774// nodes that are reachable through three sources of "unknownness":
775//
776// Global Variables, Function Calls, and Incoming Arguments
777//
778// For any node that may have unknown components (because something outside the
779// scope of current analysis may have modified it), the 'Incomplete' flag is
780// added to the NodeType.
781//
Chris Lattner394471f2003-01-23 22:05:33 +0000782void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000783 // Mark any incoming arguments as incomplete...
Chris Lattnere77f1452003-02-08 23:08:02 +0000784 if ((Flags & DSGraph::MarkFormalArgs) && Func && Func->getName() != "main")
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000785 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000786 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
787 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000788
789 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +0000790 if (!shouldPrintAuxCalls())
791 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
792 markIncomplete(FunctionCalls[i]);
793 else
794 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
795 markIncomplete(AuxFunctionCalls[i]);
796
Chris Lattner0d9bab82002-07-18 00:12:30 +0000797
Chris Lattner93d7a212003-02-09 18:41:49 +0000798 // Mark all global nodes as incomplete...
799 if ((Flags & DSGraph::IgnoreGlobals) == 0)
800 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattner98d6f0a2003-02-14 23:27:18 +0000801 if (Nodes[i]->NodeType & DSNode::GlobalNode && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +0000802 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000803}
804
Chris Lattneraa8146f2002-11-10 06:59:55 +0000805static inline void killIfUselessEdge(DSNodeHandle &Edge) {
806 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +0000807 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattneraa8146f2002-11-10 06:59:55 +0000808 if ((N->NodeType & ~DSNode::Incomplete) == 0 && // No interesting info?
Chris Lattner18552922002-11-18 21:44:46 +0000809 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +0000810 Edge.setNode(0); // Kill the edge!
811}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000812
Chris Lattneraa8146f2002-11-10 06:59:55 +0000813static inline bool nodeContainsExternalFunction(const DSNode *N) {
814 const std::vector<GlobalValue*> &Globals = N->getGlobals();
815 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
816 if (Globals[i]->isExternal())
817 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000818 return false;
819}
820
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000821static void removeIdenticalCalls(std::vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000822 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000823 // Remove trivially identical function calls
824 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +0000825 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
826
827 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +0000828 DSNode *LastCalleeNode = 0;
829 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000830 unsigned NumDuplicateCalls = 0;
831 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +0000832 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000833 DSCallSite &CS = Calls[i];
834
Chris Lattnere4258442002-11-11 21:35:38 +0000835 // If the Callee is a useless edge, this must be an unreachable call site,
836 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +0000837 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattner923fc052003-02-05 21:59:58 +0000838 CS.getCalleeNode()->NodeType == 0) { // No useful info?
839 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +0000840 CS.swap(Calls.back());
841 Calls.pop_back();
842 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000843 } else {
Chris Lattnere4258442002-11-11 21:35:38 +0000844 // If the return value or any arguments point to a void node with no
845 // information at all in it, and the call node is the only node to point
846 // to it, remove the edge to the node (killing the node).
847 //
848 killIfUselessEdge(CS.getRetVal());
849 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
850 killIfUselessEdge(CS.getPtrArg(a));
851
852 // If this call site calls the same function as the last call site, and if
853 // the function pointer contains an external function, this node will
854 // never be resolved. Merge the arguments of the call node because no
855 // information will be lost.
856 //
Chris Lattner923fc052003-02-05 21:59:58 +0000857 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
858 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +0000859 ++NumDuplicateCalls;
860 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +0000861 if (LastCalleeNode)
862 LastCalleeContainsExternalFunction =
863 nodeContainsExternalFunction(LastCalleeNode);
864 else
865 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +0000866 }
867
868 if (LastCalleeContainsExternalFunction ||
869 // This should be more than enough context sensitivity!
870 // FIXME: Evaluate how many times this is tripped!
871 NumDuplicateCalls > 20) {
872 DSCallSite &OCS = Calls[i-1];
873 OCS.mergeWith(CS);
874
875 // The node will now be eliminated as a duplicate!
876 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
877 CS = OCS;
878 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
879 OCS = CS;
880 }
881 } else {
Chris Lattner923fc052003-02-05 21:59:58 +0000882 if (CS.isDirectCall()) {
883 LastCalleeFunc = CS.getCalleeFunc();
884 LastCalleeNode = 0;
885 } else {
886 LastCalleeNode = CS.getCalleeNode();
887 LastCalleeFunc = 0;
888 }
Chris Lattnere4258442002-11-11 21:35:38 +0000889 NumDuplicateCalls = 0;
890 }
Chris Lattneraa8146f2002-11-10 06:59:55 +0000891 }
892 }
893
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000894 Calls.erase(std::unique(Calls.begin(), Calls.end()),
895 Calls.end());
896
Chris Lattner33312f72002-11-08 01:21:07 +0000897 // Track the number of call nodes merged away...
898 NumCallNodesMerged += NumFns-Calls.size();
899
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000900 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000901 std::cerr << "Merged " << (NumFns-Calls.size())
902 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000903}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000904
Chris Lattneraa8146f2002-11-10 06:59:55 +0000905
Chris Lattnere2219762002-07-18 18:22:40 +0000906// removeTriviallyDeadNodes - After the graph has been constructed, this method
907// removes all unreachable nodes that are created because they got merged with
908// other nodes in the graph. These nodes will all be trivially unreachable, so
909// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000910//
Chris Lattnerf40f0a32002-11-09 22:07:02 +0000911void DSGraph::removeTriviallyDeadNodes() {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000912 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattneraa8146f2002-11-10 06:59:55 +0000913 removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
914
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000915 for (unsigned i = 0; i != Nodes.size(); ++i) {
916 DSNode *Node = Nodes[i];
917 if (!(Node->NodeType & ~(DSNode::Composition | DSNode::Array |
Chris Lattner923fc052003-02-05 21:59:58 +0000918 DSNode::DEAD))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000919 // This is a useless node if it has no mod/ref info (checked above),
920 // outgoing edges (which it cannot, as it is not modified in this
921 // context), and it has no incoming edges. If it is a global node it may
922 // have all of these properties and still have incoming edges, due to the
923 // scalar map, so we check those now.
924 //
Chris Lattner72d29a42003-02-11 23:11:51 +0000925 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000926 std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +0000927
928 // Loop through and make sure all of the globals are referring directly
929 // to the node...
930 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
931 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
932 assert(N == Node && "ScalarMap doesn't match globals list!");
933 }
934
935 // Make sure numreferrers still agrees, if so, the node is truely dead.
936 if (Node->getNumReferrers() == Globals.size()) {
937 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
938 ScalarMap.erase(Globals[j]);
939
940 Globals.clear();
941 assert(Node->hasNoReferrers() && "Shouldn't have refs now!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000942
Chris Lattner72d29a42003-02-11 23:11:51 +0000943 Node->NodeType = DSNode::DEAD;
944 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000945 }
946 }
947
Chris Lattner2609c072003-02-10 18:18:18 +0000948 if ((Node->NodeType & ~DSNode::DEAD) == 0 && Node->hasNoReferrers()) {
949 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000950 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +0000951 Nodes[i--] = Nodes.back();
952 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000953 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000954 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000955}
956
957
Chris Lattner5c7380e2003-01-29 21:10:20 +0000958/// markReachableNodes - This method recursively traverses the specified
959/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
960/// to the set, which allows it to only traverse visited nodes once.
961///
Chris Lattner41c04f72003-02-01 04:52:08 +0000962void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000963 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +0000964 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +0000965 if (ReachableNodes.count(this)) return; // Already marked reachable
966 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +0000967
Chris Lattner5c7380e2003-01-29 21:10:20 +0000968 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
969 getLink(i).getNode()->markReachableNodes(ReachableNodes);
970}
971
Chris Lattner41c04f72003-02-01 04:52:08 +0000972void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000973 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +0000974 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +0000975
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000976 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
977 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +0000978}
979
Chris Lattnera1220af2003-02-01 06:17:02 +0000980// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
981// looking for a node that is marked alive. If an alive node is found, return
982// true, otherwise return false. If an alive node is reachable, this node is
983// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000984//
Chris Lattnera1220af2003-02-01 06:17:02 +0000985static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
986 hash_set<DSNode*> &Visited) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000987 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +0000988 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000989
Chris Lattneraa8146f2002-11-10 06:59:55 +0000990 // If we know that this node is alive, return so!
991 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000992
Chris Lattneraa8146f2002-11-10 06:59:55 +0000993 // Otherwise, we don't think the node is alive yet, check for infinite
994 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +0000995 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +0000996 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000997
Chris Lattner08db7192002-11-06 06:20:27 +0000998 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattnera1220af2003-02-01 06:17:02 +0000999 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
1000 N->markReachableNodes(Alive);
1001 return true;
1002 }
1003 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001004}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001005
Chris Lattnera1220af2003-02-01 06:17:02 +00001006// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1007// alive nodes.
1008//
Chris Lattner41c04f72003-02-01 04:52:08 +00001009static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1010 hash_set<DSNode*> &Visited) {
Chris Lattner923fc052003-02-05 21:59:58 +00001011 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
1012 return true;
1013 if (CS.isIndirectCall() &&
1014 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001015 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001016 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1017 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001018 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001019 return false;
1020}
1021
Chris Lattnere2219762002-07-18 18:22:40 +00001022// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1023// subgraphs that are unreachable. This often occurs because the data
1024// structure doesn't "escape" into it's caller, and thus should be eliminated
1025// from the caller's graph entirely. This is only appropriate to use when
1026// inlining graphs.
1027//
Chris Lattner394471f2003-01-23 22:05:33 +00001028void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001029 // Reduce the amount of work we have to do... remove dummy nodes left over by
1030 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001031 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001032
Chris Lattnere2219762002-07-18 18:22:40 +00001033 // FIXME: Merge nontrivially identical call nodes...
1034
1035 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001036 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001037 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001038
Chris Lattneraa8146f2002-11-10 06:59:55 +00001039 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner41c04f72003-02-01 04:52:08 +00001040 for (hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001041 E = ScalarMap.end(); I != E; )
1042 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001043 assert(I->second.getNode() && "Null global node?");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001044 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1045 ++I;
1046 } else {
1047 // Check to see if this is a worthless node generated for non-pointer
1048 // values, such as integers. Consider an addition of long types: A+B.
1049 // Assuming we can track all uses of the value in this context, and it is
1050 // NOT used as a pointer, we can delete the node. We will be able to
1051 // detect this situation if the node pointed to ONLY has Unknown bit set
1052 // in the node. In this case, the node is not incomplete, does not point
1053 // to any other nodes (no mod/ref bits set), and is therefore
1054 // uninteresting for data structure analysis. If we run across one of
1055 // these, prune the scalar pointing to it.
1056 //
1057 DSNode *N = I->second.getNode();
1058 if (N->NodeType == DSNode::UnknownNode && !isa<Argument>(I->first)) {
1059 ScalarMap.erase(I++);
1060 } else {
1061 I->second.getNode()->markReachableNodes(Alive);
1062 ++I;
1063 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001064 }
Chris Lattnere2219762002-07-18 18:22:40 +00001065
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001066 // The return value is alive as well...
Chris Lattner5c7380e2003-01-29 21:10:20 +00001067 RetNode.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001068
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001069 // Mark any nodes reachable by primary calls as alive...
1070 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1071 FunctionCalls[i].markReachableNodes(Alive);
1072
1073 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001074 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001075 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1076 do {
1077 Visited.clear();
1078 // If any global nodes points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001079 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001080 // unreachable globals in the list.
1081 //
1082 Iterate = false;
1083 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1084 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1085 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1086 GlobalNodes.pop_back(); // Erase efficiently
1087 Iterate = true;
1088 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001089
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001090 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1091 if (!AuxFCallsAlive[i] &&
1092 CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1093 AuxFunctionCalls[i].markReachableNodes(Alive);
1094 AuxFCallsAlive[i] = true;
1095 Iterate = true;
1096 }
1097 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001098
1099 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001100 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001101 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1102 if (AuxFCallsAlive[i])
1103 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001104 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001105 assert(GlobalsGraph && "No globals graph available??");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001106 // Move the unreachable call nodes to the globals graph...
1107 GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1108 AuxFunctionCalls.begin()+CurIdx,
1109 AuxFunctionCalls.end());
1110 }
1111 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001112 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1113 AuxFunctionCalls.end());
1114
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001115 // At this point, any nodes which are visited, but not alive, are nodes which
1116 // should be moved to the globals graph. Loop over all nodes, eliminating
1117 // completely unreachable nodes, and moving visited nodes to the globals graph
1118 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001119 std::vector<DSNode*> DeadNodes;
1120 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001121 for (unsigned i = 0; i != Nodes.size(); ++i)
1122 if (!Alive.count(Nodes[i])) {
1123 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001124 Nodes[i--] = Nodes.back(); // move node to end of vector
1125 Nodes.pop_back(); // Erase node from alive list.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001126 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && // Not in TD pass
1127 Visited.count(N)) { // Visited but not alive?
1128 GlobalsGraph->Nodes.push_back(N); // Move node to globals graph
Chris Lattner72d29a42003-02-11 23:11:51 +00001129 N->setParentGraph(GlobalsGraph);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001130 } else { // Otherwise, delete the node
1131 assert(((N->NodeType & DSNode::GlobalNode) == 0 ||
1132 (Flags & DSGraph::RemoveUnreachableGlobals))
1133 && "Killing a global?");
Chris Lattner72d29a42003-02-11 23:11:51 +00001134 //std::cerr << "[" << i+1 << "/" << DeadNodes.size()
1135 // << "] Node is dead: "; N->dump();
1136 DeadNodes.push_back(N);
1137 N->dropAllReferences();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001138 }
Chris Lattner72d29a42003-02-11 23:11:51 +00001139 } else {
1140 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001141 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001142
1143 // Now that the nodes have either been deleted or moved to the globals graph,
1144 // loop over the scalarmap, updating the entries for globals...
1145 //
1146 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) { // Not in the TD pass?
1147 // In this array we start the remapping, which can cause merging. Because
1148 // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1149 // must always go through the ScalarMap (which contains DSNodeHandles [which
1150 // cannot be invalidated by merging]).
1151 //
1152 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1153 Value *G = GlobalNodes[i].first;
1154 hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(G);
1155 assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1156 assert(I->second.getNode() && "Global not pointing to anything?");
1157 assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1158 GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1159 assert(GlobalsGraph->ScalarMap[G].getNode() &&
1160 "Global not pointing to anything?");
1161 ScalarMap.erase(I);
1162 }
1163
1164 // Merging leaves behind silly nodes, we remove them to avoid polluting the
1165 // globals graph.
Chris Lattner72d29a42003-02-11 23:11:51 +00001166 if (!GlobalNodes.empty())
1167 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001168 } else {
1169 // If we are in the top-down pass, remove all unreachable globals from the
1170 // ScalarMap...
1171 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1172 ScalarMap.erase(GlobalNodes[i].first);
1173 }
1174
Chris Lattner72d29a42003-02-11 23:11:51 +00001175 // Loop over all of the dead nodes now, deleting them since their referrer
1176 // count is zero.
1177 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1178 delete DeadNodes[i];
1179
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001180 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001181}
1182
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001183void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001184 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1185 Nodes[i]->assertOK();
1186 return; // FIXME: remove
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001187 for (hash_map<Value*, DSNodeHandle>::const_iterator I = ScalarMap.begin(),
1188 E = ScalarMap.end(); I != E; ++I) {
1189 assert(I->second.getNode() && "Null node in scalarmap!");
1190 AssertNodeInGraph(I->second.getNode());
1191 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1192 assert((I->second.getNode()->NodeType & DSNode::GlobalNode) &&
1193 "Global points to node, but node isn't global?");
1194 AssertNodeContainsGlobal(I->second.getNode(), GV);
1195 }
1196 }
1197 AssertCallNodesInGraph();
1198 AssertAuxCallNodesInGraph();
1199}