blob: 31ff0a91b2419c1ad69e564b1622f4bc0b8e1def [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 Lattner0d9bab82002-07-18 00:12:30 +000014#include <algorithm>
Chris Lattnerfccd06f2002-10-01 22:33:50 +000015#include <set>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000016
Chris Lattnere2219762002-07-18 18:22:40 +000017using std::vector;
18
Chris Lattner08db7192002-11-06 06:20:27 +000019namespace {
20 Statistic<> NumFolds("dsnode", "Number of nodes completely folded");
21};
22
Chris Lattnerb1060432002-11-07 05:20:53 +000023namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000024 extern TargetData TD;
25}
Chris Lattnerb1060432002-11-07 05:20:53 +000026using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000027
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000028//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000029// DSNode Implementation
30//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000031
Chris Lattner08db7192002-11-06 06:20:27 +000032DSNode::DSNode(enum NodeTy NT, const Type *T)
33 : Ty(Type::VoidTy), Size(0), NodeType(NT) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000034 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000035 if (T) mergeTypeInfo(T, 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000036}
37
Chris Lattner0d9bab82002-07-18 00:12:30 +000038// DSNode copy constructor... do not copy over the referrers list!
39DSNode::DSNode(const DSNode &N)
Chris Lattner08db7192002-11-06 06:20:27 +000040 : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size),
41 NodeType(N.NodeType) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000042}
43
Chris Lattnerc68c31b2002-07-10 22:38:08 +000044void DSNode::removeReferrer(DSNodeHandle *H) {
45 // Search backwards, because we depopulate the list from the back for
46 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000047 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000048 std::find(Referrers.rbegin(), Referrers.rend(), H);
49 assert(I != Referrers.rend() && "Referrer not pointing to node!");
50 Referrers.erase(I.base()-1);
51}
52
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000053// addGlobal - Add an entry for a global value to the Globals list. This also
54// marks the node with the 'G' flag if it does not already have it.
55//
56void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000057 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000058 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000059 std::lower_bound(Globals.begin(), Globals.end(), GV);
60
61 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000062 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000063 Globals.insert(I, GV);
64 NodeType |= GlobalNode;
65 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000066}
67
Chris Lattner8f0a16e2002-10-31 05:45:02 +000068/// foldNodeCompletely - If we determine that this node has some funny
69/// behavior happening to it that we cannot represent, we fold it down to a
70/// single, completely pessimistic, node. This node is represented as a
71/// single byte with a single TypeEntry of "void".
72///
73void DSNode::foldNodeCompletely() {
Chris Lattner08db7192002-11-06 06:20:27 +000074 if (isNodeCompletelyFolded()) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +000075
Chris Lattner08db7192002-11-06 06:20:27 +000076 ++NumFolds;
77
78 // We are no longer typed at all...
79 Ty = DSTypeRec(Type::VoidTy, true);
80 Size = 1;
81
82 // Loop over all of our referrers, making them point to our zero bytes of
83 // space.
Chris Lattner8f0a16e2002-10-31 05:45:02 +000084 for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
85 I != E; ++I)
86 (*I)->setOffset(0);
87
Chris Lattner8f0a16e2002-10-31 05:45:02 +000088 // If we have links, merge all of our outgoing links together...
Chris Lattner08db7192002-11-06 06:20:27 +000089 for (unsigned i = 1, e = Links.size(); i < e; ++i)
90 Links[0].mergeWith(Links[i]);
91 Links.resize(1);
Chris Lattner8f0a16e2002-10-31 05:45:02 +000092}
Chris Lattner076c1f92002-11-07 06:31:54 +000093
Chris Lattner8f0a16e2002-10-31 05:45:02 +000094/// isNodeCompletelyFolded - Return true if this node has been completely
95/// folded down to something that can never be expanded, effectively losing
96/// all of the field sensitivity that may be present in the node.
97///
98bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner08db7192002-11-06 06:20:27 +000099 return getSize() == 1 && Ty.Ty == Type::VoidTy && Ty.isArray;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000100}
101
102
Chris Lattner08db7192002-11-06 06:20:27 +0000103/// mergeTypeInfo - This method merges the specified type into the current node
104/// at the specified offset. This may update the current node's type record if
105/// this gives more information to the node, it may do nothing to the node if
106/// this information is already known, or it may merge the node completely (and
107/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000108///
Chris Lattner08db7192002-11-06 06:20:27 +0000109/// This method returns true if the node is completely folded, otherwise false.
110///
111bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
112 // Check to make sure the Size member is up-to-date. Size can be one of the
113 // following:
114 // Size = 0, Ty = Void: Nothing is known about this node.
115 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
116 // Size = 1, Ty = Void, Array = 1: The node is collapsed
117 // Otherwise, sizeof(Ty) = Size
118 //
119 assert(((Size == 0 && Ty.Ty == Type::VoidTy && !Ty.isArray) ||
120 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
121 (Size == 1 && Ty.Ty == Type::VoidTy && Ty.isArray) ||
122 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
123 (TD.getTypeSize(Ty.Ty) == Size)) &&
124 "Size member of DSNode doesn't match the type structure!");
125 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000126
Chris Lattner08db7192002-11-06 06:20:27 +0000127 if (Offset == 0 && NewTy == Ty.Ty)
128 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000129
Chris Lattner08db7192002-11-06 06:20:27 +0000130 // Return true immediately if the node is completely folded.
131 if (isNodeCompletelyFolded()) return true;
132
133 // Figure out how big the new type we're merging in is...
134 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
135
136 // Otherwise check to see if we can fold this type into the current node. If
137 // we can't, we fold the node completely, if we can, we potentially update our
138 // internal state.
139 //
140 if (Ty.Ty == Type::VoidTy) {
141 // If this is the first type that this node has seen, just accept it without
142 // question....
143 assert(Offset == 0 && "Cannot have an offset into a void node!");
144 assert(Ty.isArray == false && "This shouldn't happen!");
145 Ty.Ty = NewTy;
146 Size = NewTySize;
147
148 // Calculate the number of outgoing links from this node.
149 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
150 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000151 }
Chris Lattner08db7192002-11-06 06:20:27 +0000152
153 // Handle node expansion case here...
154 if (Offset+NewTySize > Size) {
155 // It is illegal to grow this node if we have treated it as an array of
156 // objects...
157 if (Ty.isArray) {
158 foldNodeCompletely();
159 return true;
160 }
161
162 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner3c87b292002-11-07 01:54:56 +0000163 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
164 << "offset != 0: Collapsing!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000165 foldNodeCompletely();
166 return true;
167 }
168
169 // Okay, the situation is nice and simple, we are trying to merge a type in
170 // at offset 0 that is bigger than our current type. Implement this by
171 // switching to the new type and then merge in the smaller one, which should
172 // hit the other code path here. If the other code path decides it's not
173 // ok, it will collapse the node as appropriate.
174 //
175 const Type *OldTy = Ty.Ty;
176 Ty.Ty = NewTy;
177 Size = NewTySize;
178
179 // Must grow links to be the appropriate size...
180 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
181
182 // Merge in the old type now... which is guaranteed to be smaller than the
183 // "current" type.
184 return mergeTypeInfo(OldTy, 0);
185 }
186
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000187 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000188 "Cannot merge something into a part of our type that doesn't exist!");
189
190 // Find the section of Ty.Ty that NewTy overlaps with... first we find the
191 // type that starts at offset Offset.
192 //
193 unsigned O = 0;
194 const Type *SubType = Ty.Ty;
195 while (O < Offset) {
196 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
197
198 switch (SubType->getPrimitiveID()) {
199 case Type::StructTyID: {
200 const StructType *STy = cast<StructType>(SubType);
201 const StructLayout &SL = *TD.getStructLayout(STy);
202
203 unsigned i = 0, e = SL.MemberOffsets.size();
204 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
205 /* empty */;
206
207 // The offset we are looking for must be in the i'th element...
208 SubType = STy->getElementTypes()[i];
209 O += SL.MemberOffsets[i];
210 break;
211 }
212 case Type::ArrayTyID: {
213 SubType = cast<ArrayType>(SubType)->getElementType();
214 unsigned ElSize = TD.getTypeSize(SubType);
215 unsigned Remainder = (Offset-O) % ElSize;
216 O = Offset-Remainder;
217 break;
218 }
219 default:
220 assert(0 && "Unknown type!");
221 }
222 }
223
224 assert(O == Offset && "Could not achieve the correct offset!");
225
226 // If we found our type exactly, early exit
227 if (SubType == NewTy) return false;
228
229 // Okay, so we found the leader type at the offset requested. Search the list
230 // of types that starts at this offset. If SubType is currently an array or
231 // structure, the type desired may actually be the first element of the
232 // composite type...
233 //
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000234 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000235 while (SubType != NewTy) {
236 const Type *NextSubType = 0;
237 unsigned NextSubTypeSize;
238 switch (SubType->getPrimitiveID()) {
239 case Type::StructTyID:
240 NextSubType = cast<StructType>(SubType)->getElementTypes()[0];
241 NextSubTypeSize = TD.getTypeSize(SubType);
242 break;
243 case Type::ArrayTyID:
244 NextSubType = cast<ArrayType>(SubType)->getElementType();
245 NextSubTypeSize = TD.getTypeSize(SubType);
246 break;
247 default: ;
248 // fall out
249 }
250
251 if (NextSubType == 0)
252 break; // In the default case, break out of the loop
253
254 if (NextSubTypeSize < NewTySize)
255 break; // Don't allow shrinking to a smaller type than NewTySize
256 SubType = NextSubType;
257 SubTypeSize = NextSubTypeSize;
258 }
259
260 // If we found the type exactly, return it...
261 if (SubType == NewTy)
262 return false;
263
264 // Check to see if we have a compatible, but different type...
265 if (NewTySize == SubTypeSize) {
266 // Check to see if this type is obviously convertable... int -> uint f.e.
267 if (NewTy->isLosslesslyConvertableTo(SubType))
268 return false;
269
270 // Check to see if we have a pointer & integer mismatch going on here,
271 // loading a pointer as a long, for example.
272 //
273 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
274 NewTy->isInteger() && isa<PointerType>(SubType))
275 return false;
276
277 }
278
279
Chris Lattner3c87b292002-11-07 01:54:56 +0000280 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty.Ty
281 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
282 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000283
284 foldNodeCompletely();
285 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000286}
287
Chris Lattner08db7192002-11-06 06:20:27 +0000288
289
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000290// addEdgeTo - Add an edge from the current node to the specified node. This
291// can cause merging of nodes in the graph.
292//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000293void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000294 if (NH.getNode() == 0) return; // Nothing to do
295
Chris Lattner08db7192002-11-06 06:20:27 +0000296 DSNodeHandle &ExistingEdge = getLink(Offset);
297 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000298 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000299 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000300 } else { // No merging to perform...
301 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000302 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000303}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000304
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000305
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000306// MergeSortedVectors - Efficiently merge a vector into another vector where
307// duplicates are not allowed and both are sorted. This assumes that 'T's are
308// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000309//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000310template<typename T>
311void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
312 // By far, the most common cases will be the simple ones. In these cases,
313 // avoid having to allocate a temporary vector...
314 //
315 if (Src.empty()) { // Nothing to merge in...
316 return;
317 } else if (Dest.empty()) { // Just copy the result in...
318 Dest = Src;
319 } else if (Src.size() == 1) { // Insert a single element...
320 const T &V = Src[0];
321 typename vector<T>::iterator I =
322 std::lower_bound(Dest.begin(), Dest.end(), V);
323 if (I == Dest.end() || *I != Src[0]) // If not already contained...
324 Dest.insert(I, Src[0]);
325 } else if (Dest.size() == 1) {
326 T Tmp = Dest[0]; // Save value in temporary...
327 Dest = Src; // Copy over list...
328 typename vector<T>::iterator I =
329 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
330 if (I == Dest.end() || *I != Src[0]) // If not already contained...
331 Dest.insert(I, Src[0]);
332
333 } else {
334 // Make a copy to the side of Dest...
335 vector<T> Old(Dest);
336
337 // Make space for all of the type entries now...
338 Dest.resize(Dest.size()+Src.size());
339
340 // Merge the two sorted ranges together... into Dest.
341 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
342
343 // Now erase any duplicate entries that may have accumulated into the
344 // vectors (because they were in both of the input sets)
345 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
346 }
347}
348
349
350// mergeWith - Merge this node and the specified node, moving all links to and
351// from the argument node into the current node, deleting the node argument.
352// Offset indicates what offset the specified node is to be merged into the
353// current node.
354//
355// The specified node may be a null pointer (in which case, nothing happens).
356//
357void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
358 DSNode *N = NH.getNode();
359 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000360 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000361
Chris Lattner02606632002-11-04 06:48:26 +0000362 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000363 // We cannot merge two pieces of the same node together, collapse the node
364 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000365 DEBUG(std::cerr << "Attempting to merge two chunks of"
366 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000367 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000368 return;
369 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000370
Chris Lattner08db7192002-11-06 06:20:27 +0000371 // Merge the type entries of the two nodes together...
372 if (N->Ty.Ty != Type::VoidTy)
373 mergeTypeInfo(N->Ty.Ty, Offset);
374
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000375 // If we are merging a node with a completely folded node, then both nodes are
376 // now completely folded.
377 //
378 if (isNodeCompletelyFolded()) {
Chris Lattner02606632002-11-04 06:48:26 +0000379 if (!N->isNodeCompletelyFolded())
380 N->foldNodeCompletely();
381 } else if (N->isNodeCompletelyFolded()) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000382 foldNodeCompletely();
383 Offset = 0;
384 }
Chris Lattner02606632002-11-04 06:48:26 +0000385 N = NH.getNode();
386
Chris Lattner2c0bd012002-11-06 18:01:39 +0000387 if (this == N || N == 0) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000388
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000389 // If both nodes are not at offset 0, make sure that we are merging the node
390 // at an later offset into the node with the zero offset.
391 //
392 if (Offset > NH.getOffset()) {
393 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
394 return;
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000395 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
396 // If the offsets are the same, merge the smaller node into the bigger node
397 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
398 return;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000399 }
400
401#if 0
402 std::cerr << "\n\nMerging:\n";
403 N->print(std::cerr, 0);
404 std::cerr << " and:\n";
405 print(std::cerr, 0);
406#endif
407
408 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
409 // respect to NH.Offset) is now zero.
410 //
411 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000412 unsigned NSize = N->getSize();
Chris Lattner7b7200c2002-10-02 04:57:39 +0000413
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000414 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000415 // Make sure to adjust their offset, not just the node pointer.
416 //
417 while (!N->Referrers.empty()) {
418 DSNodeHandle &Ref = *N->Referrers.back();
419 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
420 }
Chris Lattner59535132002-11-05 00:01:58 +0000421
422 // Make all of the outgoing links of N now be outgoing links of this. This
423 // can cause recursive merging!
424 //
Chris Lattner08db7192002-11-06 06:20:27 +0000425 for (unsigned i = 0; i < NSize; i += DS::PointerSize) {
426 DSNodeHandle &Link = N->getLink(i);
427 if (Link.getNode()) {
428 addEdgeTo((i+NOffset) % getSize(), Link);
Chris Lattner59535132002-11-05 00:01:58 +0000429
Chris Lattner08db7192002-11-06 06:20:27 +0000430 // It's possible that after adding the new edge that some recursive
431 // merging just occured, causing THIS node to get merged into oblivion.
432 // If that happens, we must not try to merge any more edges into it!
Chris Lattner7b7200c2002-10-02 04:57:39 +0000433 //
Chris Lattner08db7192002-11-06 06:20:27 +0000434 if (Size == 0) return;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000435 }
436 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000437
438 // Now that there are no outgoing edges, all of the Links are dead.
439 N->Links.clear();
Chris Lattner08db7192002-11-06 06:20:27 +0000440 N->Size = 0;
441 N->Ty.Ty = Type::VoidTy;
442 N->Ty.isArray = false;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000443
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000444 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000445 NodeType |= N->NodeType;
446 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000447
448 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000449 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000450 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000451
452 // Delete the globals from the old node...
453 N->Globals.clear();
454 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000455}
456
Chris Lattner9de906c2002-10-20 22:11:44 +0000457//===----------------------------------------------------------------------===//
458// DSCallSite Implementation
459//===----------------------------------------------------------------------===//
460
Vikram S. Adve26b98262002-10-20 21:41:02 +0000461// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000462Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000463 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000464}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000465
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000466
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000467//===----------------------------------------------------------------------===//
468// DSGraph Implementation
469//===----------------------------------------------------------------------===//
470
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000471DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
472 std::map<const DSNode*, DSNode*> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000473 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000474}
475
Chris Lattnereff0da92002-10-21 15:32:34 +0000476DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
477 : Func(G.Func) {
Chris Lattnerc875f022002-11-03 21:27:48 +0000478 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000479}
480
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000481DSGraph::~DSGraph() {
482 FunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000483 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000484 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000485
486#ifndef NDEBUG
487 // Drop all intra-node references, so that assertions don't fail...
488 std::for_each(Nodes.begin(), Nodes.end(),
489 std::mem_fun(&DSNode::dropAllReferences));
490#endif
491
492 // Delete all of the nodes themselves...
493 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
494}
495
Chris Lattner0d9bab82002-07-18 00:12:30 +0000496// dump - Allow inspection of graph in a debugger.
497void DSGraph::dump() const { print(std::cerr); }
498
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000499
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000500// Helper function used to clone a function list.
501//
502static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
503 vector<DSCallSite> &toCalls,
504 std::map<const DSNode*, DSNode*> &NodeMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000505 unsigned FC = toCalls.size(); // FirstCall
506 toCalls.reserve(FC+fromCalls.size());
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000507 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
Chris Lattner99a22842002-10-21 15:04:18 +0000508 toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000509}
510
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000511/// remapLinks - Change all of the Links in the current node according to the
512/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000513///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000514void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
515 for (unsigned i = 0, e = Links.size(); i != e; ++i)
516 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
517}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000518
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000519
Chris Lattner0d9bab82002-07-18 00:12:30 +0000520// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000521// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000522// filled into the OldValMap member. If StripAllocas is set to true, Alloca
523// markers are removed from the graph, as the graph is being cloned into a
524// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000525//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000526DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
527 std::map<Value*, DSNodeHandle> &OldValMap,
528 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattner460ea292002-11-07 07:06:20 +0000529 AllocaBit StripAllocas) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000530 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000531
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000532 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000533
534 // Duplicate all of the nodes, populating the node map...
535 Nodes.reserve(FN+G.Nodes.size());
536 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000537 DSNode *Old = G.Nodes[i];
538 DSNode *New = new DSNode(*Old);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000539 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000540 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000541 }
542
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000543 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000544 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000545 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000546
Chris Lattner460ea292002-11-07 07:06:20 +0000547 // Remove alloca markers as specified
548 if (StripAllocas == StripAllocaBit)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000549 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattner460ea292002-11-07 07:06:20 +0000550 Nodes[i]->NodeType &= ~DSNode::AllocaNode;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000551
Chris Lattnercf15db32002-10-17 20:09:52 +0000552 // Copy the value map... and merge all of the global nodes...
Chris Lattnerc875f022002-11-03 21:27:48 +0000553 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
554 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000555 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner92673292002-11-02 00:13:20 +0000556 H.setNode(OldNodeMap[I->second.getNode()]);
557 H.setOffset(I->second.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000558
559 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattnerc875f022002-11-03 21:27:48 +0000560 std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
561 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000562 GVI->second.mergeWith(H);
563 } else {
Chris Lattnerc875f022002-11-03 21:27:48 +0000564 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000565 }
566 }
567 }
Chris Lattnere2219762002-07-18 18:22:40 +0000568 // Copy the function calls list...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000569 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000570
Chris Lattnercf15db32002-10-17 20:09:52 +0000571
Chris Lattner0d9bab82002-07-18 00:12:30 +0000572 // Return the returned node pointer...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000573 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000574}
575
Chris Lattner076c1f92002-11-07 06:31:54 +0000576/// mergeInGraph - The method is used for merging graphs together. If the
577/// argument graph is not *this, it makes a clone of the specified graph, then
578/// merges the nodes specified in the call site with the formal arguments in the
579/// graph.
580///
581void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
Chris Lattner460ea292002-11-07 07:06:20 +0000582 AllocaBit StripAllocas) {
Chris Lattner076c1f92002-11-07 06:31:54 +0000583 std::map<Value*, DSNodeHandle> OldValMap;
584 DSNodeHandle RetVal;
585 std::map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
586
587 // If this is not a recursive call, clone the graph into this graph...
588 if (&Graph != this) {
589 // Clone the callee's graph into the current graph, keeping
590 // track of where scalars in the old graph _used_ to point,
591 // and of the new nodes matching nodes of the old graph.
592 std::map<const DSNode*, DSNode*> OldNodeMap;
593
594 // The clone call may invalidate any of the vectors in the data
595 // structure graph. Strip locals and don't copy the list of callers
596 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, StripAllocas);
597 ScalarMap = &OldValMap;
598 } else {
599 RetVal = getRetNode();
600 ScalarMap = &getScalarMap();
601 }
602
603 // Merge the return value with the return value of the context...
604 RetVal.mergeWith(CS.getRetVal());
605
606 // Resolve all of the function arguments...
607 Function &F = Graph.getFunction();
608 Function::aiterator AI = F.abegin();
609 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
610 // Advance the argument iterator to the first pointer argument...
611 while (!isPointerType(AI->getType())) {
612 ++AI;
613#ifndef NDEBUG
614 if (AI == F.aend())
615 std::cerr << "Bad call to Function: " << F.getName() << "\n";
616#endif
617 assert(AI != F.aend() && "# Args provided is not # Args required!");
618 }
619
620 // Add the link from the argument scalar to the provided value
621 DSNodeHandle &NH = (*ScalarMap)[AI];
622 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
623 NH.mergeWith(CS.getPtrArg(i));
624 }
625}
626
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000627#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000628// cloneGlobalInto - Clone the given global node and all its target links
629// (and all their llinks, recursively).
630//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000631DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000632 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
633
634 // If a clone has already been created for GNode, return it.
Chris Lattnerc875f022002-11-03 21:27:48 +0000635 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000636 if (ValMapEntry != 0)
637 return ValMapEntry;
638
639 // Clone the node and update the ValMap.
640 DSNode* NewNode = new DSNode(*GNode);
641 ValMapEntry = NewNode; // j=0 case of loop below!
642 Nodes.push_back(NewNode);
643 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +0000644 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000645
646 // Rewrite the links in the new node to point into the current graph.
647 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
648 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
649
650 return NewNode;
651}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000652#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000653
654
Chris Lattner0d9bab82002-07-18 00:12:30 +0000655// markIncompleteNodes - Mark the specified node as having contents that are not
656// known with the current analysis we have performed. Because a node makes all
657// of the nodes it can reach imcomplete if the node itself is incomplete, we
658// must recursively traverse the data structure graph, marking all reachable
659// nodes as incomplete.
660//
661static void markIncompleteNode(DSNode *N) {
662 // Stop recursion if no node, or if node already marked...
663 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
664
665 // Actually mark the node
666 N->NodeType |= DSNode::Incomplete;
667
668 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000669 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
670 if (DSNode *DSN = N->getLink(i).getNode())
671 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000672}
673
674
675// markIncompleteNodes - Traverse the graph, identifying nodes that may be
676// modified by other functions that have not been resolved yet. This marks
677// nodes that are reachable through three sources of "unknownness":
678//
679// Global Variables, Function Calls, and Incoming Arguments
680//
681// For any node that may have unknown components (because something outside the
682// scope of current analysis may have modified it), the 'Incomplete' flag is
683// added to the NodeType.
684//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000685void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000686 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000687 if (markFormalArgs && Func)
688 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000689 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
690 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000691
692 // Mark stuff passed into functions calls as being incomplete...
693 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve26b98262002-10-20 21:41:02 +0000694 DSCallSite &Call = FunctionCalls[i];
Chris Lattnere2219762002-07-18 18:22:40 +0000695 // Then the return value is certainly incomplete!
Chris Lattner0969c502002-10-21 02:08:03 +0000696 markIncompleteNode(Call.getRetVal().getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000697
Chris Lattner92673292002-11-02 00:13:20 +0000698 // All objects pointed to by function arguments are incomplete though!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000699 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
Chris Lattner0969c502002-10-21 02:08:03 +0000700 markIncompleteNode(Call.getPtrArg(i).getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000701 }
702
Chris Lattner92673292002-11-02 00:13:20 +0000703 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000704 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000705 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000706 DSNode *N = Nodes[i];
Chris Lattner92673292002-11-02 00:13:20 +0000707 // FIXME: Make more efficient by looking over Links directly
Chris Lattner08db7192002-11-06 06:20:27 +0000708 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
709 if (DSNode *DSN = N->getLink(i).getNode())
710 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000711 }
712}
713
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000714// removeRefsToGlobal - Helper function that removes globals from the
Chris Lattnerc875f022002-11-03 21:27:48 +0000715// ScalarMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000716static void removeRefsToGlobal(DSNode* N,
Chris Lattnerc875f022002-11-03 21:27:48 +0000717 std::map<Value*, DSNodeHandle> &ScalarMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000718 while (!N->getGlobals().empty()) {
719 GlobalValue *GV = N->getGlobals().back();
720 N->getGlobals().pop_back();
Chris Lattnerc875f022002-11-03 21:27:48 +0000721 ScalarMap.erase(GV);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000722 }
723}
724
725
Chris Lattner0d9bab82002-07-18 00:12:30 +0000726// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
727// checks to see if there are simple transformations that it can do to make it
728// dead.
729//
730bool DSGraph::isNodeDead(DSNode *N) {
731 // Is it a trivially dead shadow node...
732 if (N->getReferrers().empty() && N->NodeType == 0)
733 return true;
734
735 // Is it a function node or some other trivially unused global?
Chris Lattner92673292002-11-02 00:13:20 +0000736 if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000737 N->getReferrers().size() == N->getGlobals().size()) {
738
Chris Lattnerc875f022002-11-03 21:27:48 +0000739 // Remove the globals from the ScalarMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000740 // down to zero.
Chris Lattnerc875f022002-11-03 21:27:48 +0000741 removeRefsToGlobal(N, ScalarMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000742 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
743 return true;
744 }
745
746 return false;
747}
748
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000749static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000750 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000751 // Remove trivially identical function calls
752 unsigned NumFns = Calls.size();
753 std::sort(Calls.begin(), Calls.end());
754 Calls.erase(std::unique(Calls.begin(), Calls.end()),
755 Calls.end());
756
757 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000758 std::cerr << "Merged " << (NumFns-Calls.size())
759 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000760}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000761
Chris Lattnere2219762002-07-18 18:22:40 +0000762// removeTriviallyDeadNodes - After the graph has been constructed, this method
763// removes all unreachable nodes that are created because they got merged with
764// other nodes in the graph. These nodes will all be trivially unreachable, so
765// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000766//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000767void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000768 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000769 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000770 if (isNodeDead(Nodes[i])) { // This node is dead!
771 delete Nodes[i]; // Free memory...
772 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
773 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000774
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000775 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000776}
777
778
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000779// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000780// stuff to be alive.
781//
782static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000783 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000784
785 Alive.insert(N);
Chris Lattner08db7192002-11-06 06:20:27 +0000786 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
787 if (DSNode *DSN = N->getLink(i).getNode())
788 if (!Alive.count(DSN))
789 markAlive(DSN, Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000790}
791
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000792static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
793 std::set<DSNode*> &Visiting) {
794 if (N == 0) return false;
795
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000796 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000797 Visiting.insert(N);
798
799 // If any immediate successor is alive, N is alive
Chris Lattner08db7192002-11-06 06:20:27 +0000800 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
801 if (DSNode *DSN = N->getLink(i).getNode())
802 if (Alive.count(DSN)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000803 Visiting.erase(N);
804 return true;
805 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000806
807 // Else if any successor reaches a live node, N is alive
Chris Lattner08db7192002-11-06 06:20:27 +0000808 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
809 if (DSNode *DSN = N->getLink(i).getNode())
810 if (checkGlobalAlive(DSN, Alive, Visiting)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000811 Visiting.erase(N); return true;
812 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000813
814 Visiting.erase(N);
815 return false;
816}
817
818
819// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
820// This would be unnecessary if function calls were real nodes! In that case,
821// the simple iterative loop in the first few lines below suffice.
822//
823static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000824 vector<DSCallSite> &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000825 std::set<DSNode*> &Alive,
826 bool FilterCalls) {
827
828 // Iterate, marking globals or cast nodes alive until no new live nodes
829 // are added to Alive
830 std::set<DSNode*> Visiting; // Used to identify cycles
Chris Lattner0969c502002-10-21 02:08:03 +0000831 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000832 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
833 liveCount = Alive.size();
834 for ( ; I != E; ++I)
835 if (Alive.count(*I) == 0) {
836 Visiting.clear();
837 if (checkGlobalAlive(*I, Alive, Visiting))
838 markAlive(*I, Alive);
839 }
840 }
841
842 // Find function calls with some dead and some live nodes.
843 // Since all call nodes must be live if any one is live, we have to mark
844 // all nodes of the call as live and continue the iteration (via recursion).
845 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000846 bool Recurse = false;
847 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000848 bool CallIsDead = true, CallHasDeadArg = false;
Chris Lattner0969c502002-10-21 02:08:03 +0000849 DSCallSite &CS = Calls[i];
850 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
851 if (DSNode *N = CS.getPtrArg(j).getNode()) {
852 bool ArgIsDead = !Alive.count(N);
853 CallHasDeadArg |= ArgIsDead;
854 CallIsDead &= ArgIsDead;
855 }
856
857 if (DSNode *N = CS.getRetVal().getNode()) {
858 bool RetIsDead = !Alive.count(N);
859 CallHasDeadArg |= RetIsDead;
860 CallIsDead &= RetIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000861 }
Chris Lattner0969c502002-10-21 02:08:03 +0000862
863 DSNode *N = CS.getCallee().getNode();
864 bool FnIsDead = !Alive.count(N);
865 CallHasDeadArg |= FnIsDead;
866 CallIsDead &= FnIsDead;
867
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000868 if (!CallIsDead && CallHasDeadArg) {
869 // Some node in this call is live and another is dead.
870 // Mark all nodes of call as live and iterate once more.
Chris Lattner0969c502002-10-21 02:08:03 +0000871 Recurse = true;
872 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
873 markAlive(CS.getPtrArg(j).getNode(), Alive);
874 markAlive(CS.getRetVal().getNode(), Alive);
875 markAlive(CS.getCallee().getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000876 }
877 }
Chris Lattner0969c502002-10-21 02:08:03 +0000878 if (Recurse)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000879 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
880 }
881}
882
883
884// markGlobalsAlive - Mark global nodes and cast nodes alive if they
885// can reach any other live node. Since this can produce new live nodes,
886// we use a simple iterative algorithm.
887//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000888static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000889 bool FilterCalls) {
890 // Add global and cast nodes to a set so we don't walk all nodes every time
891 std::set<DSNode*> GlobalNodes;
892 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000893 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000894 GlobalNodes.insert(G.getNodes()[i]);
895
896 // Add all call nodes to the same set
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000897 vector<DSCallSite> &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000898 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000899 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
900 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
901 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
902 GlobalNodes.insert(N);
903 if (DSNode *N = Calls[i].getRetVal().getNode())
904 GlobalNodes.insert(N);
905 if (DSNode *N = Calls[i].getCallee().getNode())
906 GlobalNodes.insert(N);
907 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000908 }
909
910 // Iterate and recurse until no new live node are discovered.
911 // This would be a simple iterative loop if function calls were real nodes!
912 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
913
Chris Lattnerc875f022002-11-03 21:27:48 +0000914 // Free up references to dead globals from the ScalarMap
Chris Lattner92673292002-11-02 00:13:20 +0000915 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000916 for( ; I != E; ++I)
917 if (Alive.count(*I) == 0)
Chris Lattnerc875f022002-11-03 21:27:48 +0000918 removeRefsToGlobal(*I, G.getScalarMap());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000919
920 // Delete dead function calls
921 if (FilterCalls)
922 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
923 bool CallIsDead = true;
Chris Lattner0969c502002-10-21 02:08:03 +0000924 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
925 CallIsDead && j != ej; ++j)
926 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000927 if (CallIsDead)
928 Calls.erase(Calls.begin() + i); // remove the call entirely
929 }
930}
Chris Lattnere2219762002-07-18 18:22:40 +0000931
932// removeDeadNodes - Use a more powerful reachability analysis to eliminate
933// subgraphs that are unreachable. This often occurs because the data
934// structure doesn't "escape" into it's caller, and thus should be eliminated
935// from the caller's graph entirely. This is only appropriate to use when
936// inlining graphs.
937//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000938void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
939 assert((!KeepAllGlobals || KeepCalls) &&
940 "KeepAllGlobals without KeepCalls is meaningless");
941
Chris Lattnere2219762002-07-18 18:22:40 +0000942 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000943 removeTriviallyDeadNodes(KeepAllGlobals);
944
Chris Lattnere2219762002-07-18 18:22:40 +0000945 // FIXME: Merge nontrivially identical call nodes...
946
947 // Alive - a set that holds all nodes found to be reachable/alive.
948 std::set<DSNode*> Alive;
949
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000950 // If KeepCalls, mark all nodes reachable by call nodes as alive...
951 if (KeepCalls)
Chris Lattner0969c502002-10-21 02:08:03 +0000952 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
953 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
954 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
955 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
956 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
957 }
Chris Lattnere2219762002-07-18 18:22:40 +0000958
Chris Lattner92673292002-11-02 00:13:20 +0000959 // Mark all nodes reachable by scalar nodes as alive...
Chris Lattnerc875f022002-11-03 21:27:48 +0000960 for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
961 E = ScalarMap.end(); I != E; ++I)
Chris Lattner92673292002-11-02 00:13:20 +0000962 markAlive(I->second.getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000963
Chris Lattner92673292002-11-02 00:13:20 +0000964#if 0
965 // Marge all nodes reachable by global nodes, as alive. Isn't this covered by
Chris Lattnerc875f022002-11-03 21:27:48 +0000966 // the ScalarMap?
Chris Lattner92673292002-11-02 00:13:20 +0000967 //
968 if (KeepAllGlobals)
969 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
970 if (Nodes[i]->NodeType & DSNode::GlobalNode)
971 markAlive(Nodes[i], Alive);
972#endif
Chris Lattnere2219762002-07-18 18:22:40 +0000973
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000974 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000975 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000976
977 // Mark all globals or cast nodes that can reach a live node as alive.
978 // This also marks all nodes reachable from such nodes as alive.
979 // Of course, if KeepAllGlobals is specified, they would be live already.
Chris Lattner0969c502002-10-21 02:08:03 +0000980 if (!KeepAllGlobals)
Chris Lattner92673292002-11-02 00:13:20 +0000981 markGlobalsAlive(*this, Alive, !KeepCalls);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000982
Chris Lattnere2219762002-07-18 18:22:40 +0000983 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000984 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000985 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
986 for (unsigned i = 0; i != Nodes.size(); ++i)
987 if (!Alive.count(Nodes[i])) {
988 DSNode *N = Nodes[i];
989 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
990 DeadNodes.push_back(N); // Add node to our list of dead nodes
991 N->dropAllReferences(); // Drop all outgoing edges
992 }
993
Chris Lattnere2219762002-07-18 18:22:40 +0000994 // Delete all dead nodes...
995 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
996}
997
998
999
Chris Lattner0d9bab82002-07-18 00:12:30 +00001000// maskNodeTypes - Apply a mask to all of the node types in the graph. This
1001// is useful for clearing out markers like Scalar or Incomplete.
1002//
1003void DSGraph::maskNodeTypes(unsigned char Mask) {
1004 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1005 Nodes[i]->NodeType &= Mask;
1006}
1007
1008
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001009#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001010//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001011// GlobalDSGraph Implementation
1012//===----------------------------------------------------------------------===//
1013
1014GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
1015}
1016
1017GlobalDSGraph::~GlobalDSGraph() {
1018 assert(Referrers.size() == 0 &&
1019 "Deleting global graph while references from other graphs exist");
1020}
1021
1022void GlobalDSGraph::addReference(const DSGraph* referrer) {
1023 if (referrer != this)
1024 Referrers.insert(referrer);
1025}
1026
1027void GlobalDSGraph::removeReference(const DSGraph* referrer) {
1028 if (referrer != this) {
1029 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
1030 Referrers.erase(referrer);
1031 if (Referrers.size() == 0)
1032 delete this;
1033 }
1034}
1035
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001036#if 0
Chris Lattnerd18f3422002-11-03 21:24:04 +00001037// Bits used in the next function
1038static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1039
1040
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001041// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1042// visible target links (and recursively their such links) into this graph.
1043// NodeCache maps the node being cloned to its clone in the Globals graph,
1044// in order to track cycles.
1045// GlobalsAreFinal is a flag that says whether it is safe to assume that
1046// an existing global node is complete. This is important to avoid
1047// reinserting all globals when inserting Calls to functions.
1048// This is a helper function for cloneGlobals and cloneCalls.
1049//
1050DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1051 std::map<const DSNode*, DSNode*> &NodeCache,
1052 bool GlobalsAreFinal) {
1053 if (OldNode == 0) return 0;
1054
1055 // The caller should check this is an external node. Just more efficient...
1056 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1057
1058 // If a clone has already been created for OldNode, return it.
1059 DSNode*& CacheEntry = NodeCache[OldNode];
1060 if (CacheEntry != 0)
1061 return CacheEntry;
1062
1063 // The result value...
1064 DSNode* NewNode = 0;
1065
1066 // If nodes already exist for any of the globals of OldNode,
1067 // merge all such nodes together since they are merged in OldNode.
1068 // If ValueCacheIsFinal==true, look for an existing node that has
1069 // an identical list of globals and return it if it exists.
1070 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001071 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001072 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001073 if (NewNode == 0) {
1074 NewNode = PrevNode; // first existing node found
1075 if (GlobalsAreFinal && j == 0)
1076 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1077 CacheEntry = NewNode;
1078 return NewNode;
1079 }
1080 }
1081 else if (NewNode != PrevNode) { // found another, different from prev
1082 // update ValMap *before* merging PrevNode into NewNode
1083 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
Chris Lattnerc875f022002-11-03 21:27:48 +00001084 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001085 NewNode->mergeWith(PrevNode);
1086 }
1087 } else if (NewNode != 0) {
Chris Lattnerc875f022002-11-03 21:27:48 +00001088 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001089 }
1090
1091 // If no existing node was found, clone the node and update the ValMap.
1092 if (NewNode == 0) {
1093 NewNode = new DSNode(*OldNode);
1094 Nodes.push_back(NewNode);
1095 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1096 NewNode->setLink(j, 0);
1097 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001098 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001099 }
1100 else
1101 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1102
1103 // Add the entry to NodeCache
1104 CacheEntry = NewNode;
1105
1106 // Rewrite the links in the new node to point into the current graph,
1107 // but only for links to external nodes. Set other links to NULL.
1108 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1109 DSNode* OldTarget = OldNode->getLink(j);
1110 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1111 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1112 if (NewNode->getLink(j))
1113 NewNode->getLink(j)->mergeWith(NewLink);
1114 else
1115 NewNode->setLink(j, NewLink);
1116 }
1117 }
1118
1119 // Remove all local markers
1120 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1121
1122 return NewNode;
1123}
1124
1125
1126// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1127// visible target links (and recursively their such links) into this graph.
1128//
1129void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1130 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001131#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001132 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1133 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1134 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001135 if (CloneCalls)
1136 GlobalsGraph->cloneCalls(Graph);
1137
1138 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001139#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001140}
1141
1142
1143// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1144// links (and recursively their such links) into this graph.
1145//
1146void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1147 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001148 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001149
1150 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1151
1152 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001153 DSCallSite& callCopy = FunctionCalls.back();
1154 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001155 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001156 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001157 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1158 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1159 : 0);
1160 }
1161
1162 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001163 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001164}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001165#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001166
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001167#endif