blob: 740ece86f522a00c67145509bb34a87a36918edd [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 Lattner92673292002-11-02 00:13:20 +000023namespace DataStructureAnalysis { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000024 // isPointerType - Return true if this first class type is big enough to hold
25 // a pointer.
26 //
27 bool isPointerType(const Type *Ty);
28 extern TargetData TD;
29}
30using namespace DataStructureAnalysis;
31
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000032//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000033// DSNode Implementation
34//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000035
Chris Lattner08db7192002-11-06 06:20:27 +000036DSNode::DSNode(enum NodeTy NT, const Type *T)
37 : Ty(Type::VoidTy), Size(0), NodeType(NT) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000038 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000039 if (T) mergeTypeInfo(T, 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000040}
41
Chris Lattner0d9bab82002-07-18 00:12:30 +000042// DSNode copy constructor... do not copy over the referrers list!
43DSNode::DSNode(const DSNode &N)
Chris Lattner08db7192002-11-06 06:20:27 +000044 : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size),
45 NodeType(N.NodeType) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000046}
47
Chris Lattnerc68c31b2002-07-10 22:38:08 +000048void DSNode::removeReferrer(DSNodeHandle *H) {
49 // Search backwards, because we depopulate the list from the back for
50 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000051 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000052 std::find(Referrers.rbegin(), Referrers.rend(), H);
53 assert(I != Referrers.rend() && "Referrer not pointing to node!");
54 Referrers.erase(I.base()-1);
55}
56
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000057// addGlobal - Add an entry for a global value to the Globals list. This also
58// marks the node with the 'G' flag if it does not already have it.
59//
60void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000061 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000062 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000063 std::lower_bound(Globals.begin(), Globals.end(), GV);
64
65 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000066 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000067 Globals.insert(I, GV);
68 NodeType |= GlobalNode;
69 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000070}
71
Chris Lattner8f0a16e2002-10-31 05:45:02 +000072/// foldNodeCompletely - If we determine that this node has some funny
73/// behavior happening to it that we cannot represent, we fold it down to a
74/// single, completely pessimistic, node. This node is represented as a
75/// single byte with a single TypeEntry of "void".
76///
77void DSNode::foldNodeCompletely() {
Chris Lattner08db7192002-11-06 06:20:27 +000078 if (isNodeCompletelyFolded()) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +000079
Chris Lattner08db7192002-11-06 06:20:27 +000080 ++NumFolds;
81
82 // We are no longer typed at all...
83 Ty = DSTypeRec(Type::VoidTy, true);
84 Size = 1;
85
86 // Loop over all of our referrers, making them point to our zero bytes of
87 // space.
Chris Lattner8f0a16e2002-10-31 05:45:02 +000088 for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
89 I != E; ++I)
90 (*I)->setOffset(0);
91
Chris Lattner8f0a16e2002-10-31 05:45:02 +000092 // If we have links, merge all of our outgoing links together...
Chris Lattner08db7192002-11-06 06:20:27 +000093 for (unsigned i = 1, e = Links.size(); i < e; ++i)
94 Links[0].mergeWith(Links[i]);
95 Links.resize(1);
Chris Lattner8f0a16e2002-10-31 05:45:02 +000096}
Chris Lattner8f0a16e2002-10-31 05:45:02 +000097/// isNodeCompletelyFolded - Return true if this node has been completely
98/// folded down to something that can never be expanded, effectively losing
99/// all of the field sensitivity that may be present in the node.
100///
101bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner08db7192002-11-06 06:20:27 +0000102 return getSize() == 1 && Ty.Ty == Type::VoidTy && Ty.isArray;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000103}
104
105
Chris Lattner08db7192002-11-06 06:20:27 +0000106/// mergeTypeInfo - This method merges the specified type into the current node
107/// at the specified offset. This may update the current node's type record if
108/// this gives more information to the node, it may do nothing to the node if
109/// this information is already known, or it may merge the node completely (and
110/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000111///
Chris Lattner08db7192002-11-06 06:20:27 +0000112/// This method returns true if the node is completely folded, otherwise false.
113///
114bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
115 // Check to make sure the Size member is up-to-date. Size can be one of the
116 // following:
117 // Size = 0, Ty = Void: Nothing is known about this node.
118 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
119 // Size = 1, Ty = Void, Array = 1: The node is collapsed
120 // Otherwise, sizeof(Ty) = Size
121 //
122 assert(((Size == 0 && Ty.Ty == Type::VoidTy && !Ty.isArray) ||
123 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
124 (Size == 1 && Ty.Ty == Type::VoidTy && Ty.isArray) ||
125 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
126 (TD.getTypeSize(Ty.Ty) == Size)) &&
127 "Size member of DSNode doesn't match the type structure!");
128 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000129
Chris Lattner08db7192002-11-06 06:20:27 +0000130 if (Offset == 0 && NewTy == Ty.Ty)
131 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000132
Chris Lattner08db7192002-11-06 06:20:27 +0000133 // Return true immediately if the node is completely folded.
134 if (isNodeCompletelyFolded()) return true;
135
136 // Figure out how big the new type we're merging in is...
137 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
138
139 // Otherwise check to see if we can fold this type into the current node. If
140 // we can't, we fold the node completely, if we can, we potentially update our
141 // internal state.
142 //
143 if (Ty.Ty == Type::VoidTy) {
144 // If this is the first type that this node has seen, just accept it without
145 // question....
146 assert(Offset == 0 && "Cannot have an offset into a void node!");
147 assert(Ty.isArray == false && "This shouldn't happen!");
148 Ty.Ty = NewTy;
149 Size = NewTySize;
150
151 // Calculate the number of outgoing links from this node.
152 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
153 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000154 }
Chris Lattner08db7192002-11-06 06:20:27 +0000155
156 // Handle node expansion case here...
157 if (Offset+NewTySize > Size) {
158 // It is illegal to grow this node if we have treated it as an array of
159 // objects...
160 if (Ty.isArray) {
161 foldNodeCompletely();
162 return true;
163 }
164
165 if (Offset) { // We could handle this case, but we don't for now...
166 std::cerr << "UNIMP: Trying to merge a growth type into offset != 0: "
167 << "Collapsing!\n";
168 foldNodeCompletely();
169 return true;
170 }
171
172 // Okay, the situation is nice and simple, we are trying to merge a type in
173 // at offset 0 that is bigger than our current type. Implement this by
174 // switching to the new type and then merge in the smaller one, which should
175 // hit the other code path here. If the other code path decides it's not
176 // ok, it will collapse the node as appropriate.
177 //
178 const Type *OldTy = Ty.Ty;
179 Ty.Ty = NewTy;
180 Size = NewTySize;
181
182 // Must grow links to be the appropriate size...
183 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
184
185 // Merge in the old type now... which is guaranteed to be smaller than the
186 // "current" type.
187 return mergeTypeInfo(OldTy, 0);
188 }
189
190 assert(Offset < Size &&
191 "Cannot merge something into a part of our type that doesn't exist!");
192
193 // Find the section of Ty.Ty that NewTy overlaps with... first we find the
194 // type that starts at offset Offset.
195 //
196 unsigned O = 0;
197 const Type *SubType = Ty.Ty;
198 while (O < Offset) {
199 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
200
201 switch (SubType->getPrimitiveID()) {
202 case Type::StructTyID: {
203 const StructType *STy = cast<StructType>(SubType);
204 const StructLayout &SL = *TD.getStructLayout(STy);
205
206 unsigned i = 0, e = SL.MemberOffsets.size();
207 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
208 /* empty */;
209
210 // The offset we are looking for must be in the i'th element...
211 SubType = STy->getElementTypes()[i];
212 O += SL.MemberOffsets[i];
213 break;
214 }
215 case Type::ArrayTyID: {
216 SubType = cast<ArrayType>(SubType)->getElementType();
217 unsigned ElSize = TD.getTypeSize(SubType);
218 unsigned Remainder = (Offset-O) % ElSize;
219 O = Offset-Remainder;
220 break;
221 }
222 default:
223 assert(0 && "Unknown type!");
224 }
225 }
226
227 assert(O == Offset && "Could not achieve the correct offset!");
228
229 // If we found our type exactly, early exit
230 if (SubType == NewTy) return false;
231
232 // Okay, so we found the leader type at the offset requested. Search the list
233 // of types that starts at this offset. If SubType is currently an array or
234 // structure, the type desired may actually be the first element of the
235 // composite type...
236 //
237 unsigned SubTypeSize = TD.getTypeSize(SubType);
238 while (SubType != NewTy) {
239 const Type *NextSubType = 0;
240 unsigned NextSubTypeSize;
241 switch (SubType->getPrimitiveID()) {
242 case Type::StructTyID:
243 NextSubType = cast<StructType>(SubType)->getElementTypes()[0];
244 NextSubTypeSize = TD.getTypeSize(SubType);
245 break;
246 case Type::ArrayTyID:
247 NextSubType = cast<ArrayType>(SubType)->getElementType();
248 NextSubTypeSize = TD.getTypeSize(SubType);
249 break;
250 default: ;
251 // fall out
252 }
253
254 if (NextSubType == 0)
255 break; // In the default case, break out of the loop
256
257 if (NextSubTypeSize < NewTySize)
258 break; // Don't allow shrinking to a smaller type than NewTySize
259 SubType = NextSubType;
260 SubTypeSize = NextSubTypeSize;
261 }
262
263 // If we found the type exactly, return it...
264 if (SubType == NewTy)
265 return false;
266
267 // Check to see if we have a compatible, but different type...
268 if (NewTySize == SubTypeSize) {
269 // Check to see if this type is obviously convertable... int -> uint f.e.
270 if (NewTy->isLosslesslyConvertableTo(SubType))
271 return false;
272
273 // Check to see if we have a pointer & integer mismatch going on here,
274 // loading a pointer as a long, for example.
275 //
276 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
277 NewTy->isInteger() && isa<PointerType>(SubType))
278 return false;
279
280 }
281
282
283
284 std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty.Ty
285 << "\n due to:" << NewTy << " @ " << Offset << "!\n";
286 std::cerr << "SubType: " << SubType << "\n\n";
287
288 foldNodeCompletely();
289 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000290}
291
Chris Lattner08db7192002-11-06 06:20:27 +0000292
293
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000294// addEdgeTo - Add an edge from the current node to the specified node. This
295// can cause merging of nodes in the graph.
296//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000297void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000298 if (NH.getNode() == 0) return; // Nothing to do
299
Chris Lattner08db7192002-11-06 06:20:27 +0000300 DSNodeHandle &ExistingEdge = getLink(Offset);
301 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000302 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000303 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000304 } else { // No merging to perform...
305 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000306 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000307}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000308
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000309
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000310// MergeSortedVectors - Efficiently merge a vector into another vector where
311// duplicates are not allowed and both are sorted. This assumes that 'T's are
312// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000313//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000314template<typename T>
315void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
316 // By far, the most common cases will be the simple ones. In these cases,
317 // avoid having to allocate a temporary vector...
318 //
319 if (Src.empty()) { // Nothing to merge in...
320 return;
321 } else if (Dest.empty()) { // Just copy the result in...
322 Dest = Src;
323 } else if (Src.size() == 1) { // Insert a single element...
324 const T &V = Src[0];
325 typename vector<T>::iterator I =
326 std::lower_bound(Dest.begin(), Dest.end(), V);
327 if (I == Dest.end() || *I != Src[0]) // If not already contained...
328 Dest.insert(I, Src[0]);
329 } else if (Dest.size() == 1) {
330 T Tmp = Dest[0]; // Save value in temporary...
331 Dest = Src; // Copy over list...
332 typename vector<T>::iterator I =
333 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
334 if (I == Dest.end() || *I != Src[0]) // If not already contained...
335 Dest.insert(I, Src[0]);
336
337 } else {
338 // Make a copy to the side of Dest...
339 vector<T> Old(Dest);
340
341 // Make space for all of the type entries now...
342 Dest.resize(Dest.size()+Src.size());
343
344 // Merge the two sorted ranges together... into Dest.
345 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
346
347 // Now erase any duplicate entries that may have accumulated into the
348 // vectors (because they were in both of the input sets)
349 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
350 }
351}
352
353
354// mergeWith - Merge this node and the specified node, moving all links to and
355// from the argument node into the current node, deleting the node argument.
356// Offset indicates what offset the specified node is to be merged into the
357// current node.
358//
359// The specified node may be a null pointer (in which case, nothing happens).
360//
361void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
362 DSNode *N = NH.getNode();
363 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000364 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000365
Chris Lattner02606632002-11-04 06:48:26 +0000366 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000367 // We cannot merge two pieces of the same node together, collapse the node
368 // completely.
369 std::cerr << "Attempting to merge two chunks of the same node together!\n";
370 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000371 return;
372 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000373
Chris Lattner08db7192002-11-06 06:20:27 +0000374 // Merge the type entries of the two nodes together...
375 if (N->Ty.Ty != Type::VoidTy)
376 mergeTypeInfo(N->Ty.Ty, Offset);
377
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000378 // If we are merging a node with a completely folded node, then both nodes are
379 // now completely folded.
380 //
381 if (isNodeCompletelyFolded()) {
Chris Lattner02606632002-11-04 06:48:26 +0000382 if (!N->isNodeCompletelyFolded())
383 N->foldNodeCompletely();
384 } else if (N->isNodeCompletelyFolded()) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000385 foldNodeCompletely();
386 Offset = 0;
387 }
Chris Lattner02606632002-11-04 06:48:26 +0000388 N = NH.getNode();
389
Chris Lattner2c0bd012002-11-06 18:01:39 +0000390 if (this == N || N == 0) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000391
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000392 // If both nodes are not at offset 0, make sure that we are merging the node
393 // at an later offset into the node with the zero offset.
394 //
395 if (Offset > NH.getOffset()) {
396 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
397 return;
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000398 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
399 // If the offsets are the same, merge the smaller node into the bigger node
400 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
401 return;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000402 }
403
404#if 0
405 std::cerr << "\n\nMerging:\n";
406 N->print(std::cerr, 0);
407 std::cerr << " and:\n";
408 print(std::cerr, 0);
409#endif
410
411 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
412 // respect to NH.Offset) is now zero.
413 //
414 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000415 unsigned NSize = N->getSize();
Chris Lattner7b7200c2002-10-02 04:57:39 +0000416
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000417 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000418 // Make sure to adjust their offset, not just the node pointer.
419 //
420 while (!N->Referrers.empty()) {
421 DSNodeHandle &Ref = *N->Referrers.back();
422 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
423 }
Chris Lattner59535132002-11-05 00:01:58 +0000424
425 // Make all of the outgoing links of N now be outgoing links of this. This
426 // can cause recursive merging!
427 //
Chris Lattner08db7192002-11-06 06:20:27 +0000428 for (unsigned i = 0; i < NSize; i += DS::PointerSize) {
429 DSNodeHandle &Link = N->getLink(i);
430 if (Link.getNode()) {
431 addEdgeTo((i+NOffset) % getSize(), Link);
Chris Lattner59535132002-11-05 00:01:58 +0000432
Chris Lattner08db7192002-11-06 06:20:27 +0000433 // It's possible that after adding the new edge that some recursive
434 // merging just occured, causing THIS node to get merged into oblivion.
435 // If that happens, we must not try to merge any more edges into it!
Chris Lattner7b7200c2002-10-02 04:57:39 +0000436 //
Chris Lattner08db7192002-11-06 06:20:27 +0000437 if (Size == 0) return;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000438 }
439 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000440
441 // Now that there are no outgoing edges, all of the Links are dead.
442 N->Links.clear();
Chris Lattner08db7192002-11-06 06:20:27 +0000443 N->Size = 0;
444 N->Ty.Ty = Type::VoidTy;
445 N->Ty.isArray = false;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000446
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000447 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000448 NodeType |= N->NodeType;
449 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000450
451 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000452 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000453 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000454
455 // Delete the globals from the old node...
456 N->Globals.clear();
457 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000458}
459
Chris Lattner9de906c2002-10-20 22:11:44 +0000460//===----------------------------------------------------------------------===//
461// DSCallSite Implementation
462//===----------------------------------------------------------------------===//
463
Vikram S. Adve26b98262002-10-20 21:41:02 +0000464// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000465Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000466 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000467}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000468
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000469
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000470//===----------------------------------------------------------------------===//
471// DSGraph Implementation
472//===----------------------------------------------------------------------===//
473
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000474DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
475 std::map<const DSNode*, DSNode*> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000476 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000477}
478
Chris Lattnereff0da92002-10-21 15:32:34 +0000479DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
480 : Func(G.Func) {
Chris Lattnerc875f022002-11-03 21:27:48 +0000481 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000482}
483
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000484DSGraph::~DSGraph() {
485 FunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000486 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000487 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000488
489#ifndef NDEBUG
490 // Drop all intra-node references, so that assertions don't fail...
491 std::for_each(Nodes.begin(), Nodes.end(),
492 std::mem_fun(&DSNode::dropAllReferences));
493#endif
494
495 // Delete all of the nodes themselves...
496 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
497}
498
Chris Lattner0d9bab82002-07-18 00:12:30 +0000499// dump - Allow inspection of graph in a debugger.
500void DSGraph::dump() const { print(std::cerr); }
501
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000502
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000503// Helper function used to clone a function list.
504//
505static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
506 vector<DSCallSite> &toCalls,
507 std::map<const DSNode*, DSNode*> &NodeMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000508 unsigned FC = toCalls.size(); // FirstCall
509 toCalls.reserve(FC+fromCalls.size());
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000510 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
Chris Lattner99a22842002-10-21 15:04:18 +0000511 toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000512}
513
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000514/// remapLinks - Change all of the Links in the current node according to the
515/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000516///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000517void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
518 for (unsigned i = 0, e = Links.size(); i != e; ++i)
519 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
520}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000521
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000522
Chris Lattner0d9bab82002-07-18 00:12:30 +0000523// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000524// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000525// filled into the OldValMap member. If StripAllocas is set to true, Alloca
526// markers are removed from the graph, as the graph is being cloned into a
527// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000528//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000529DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
530 std::map<Value*, DSNodeHandle> &OldValMap,
531 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattner92673292002-11-02 00:13:20 +0000532 bool StripAllocas) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000533 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000534
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000535 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000536
537 // Duplicate all of the nodes, populating the node map...
538 Nodes.reserve(FN+G.Nodes.size());
539 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000540 DSNode *Old = G.Nodes[i];
541 DSNode *New = new DSNode(*Old);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000542 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000543 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000544 }
545
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000546 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000547 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000548 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000549
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000550 // Remove local markers as specified
Chris Lattner92673292002-11-02 00:13:20 +0000551 unsigned char StripBits = StripAllocas ? DSNode::AllocaNode : 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000552 if (StripBits)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000553 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000554 Nodes[i]->NodeType &= ~StripBits;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000555
Chris Lattnercf15db32002-10-17 20:09:52 +0000556 // Copy the value map... and merge all of the global nodes...
Chris Lattnerc875f022002-11-03 21:27:48 +0000557 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
558 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000559 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner92673292002-11-02 00:13:20 +0000560 H.setNode(OldNodeMap[I->second.getNode()]);
561 H.setOffset(I->second.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000562
563 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattnerc875f022002-11-03 21:27:48 +0000564 std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
565 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000566 GVI->second.mergeWith(H);
567 } else {
Chris Lattnerc875f022002-11-03 21:27:48 +0000568 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000569 }
570 }
571 }
Chris Lattnere2219762002-07-18 18:22:40 +0000572 // Copy the function calls list...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000573 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000574
Chris Lattnercf15db32002-10-17 20:09:52 +0000575
Chris Lattner0d9bab82002-07-18 00:12:30 +0000576 // Return the returned node pointer...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000577 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000578}
579
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000580#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000581// cloneGlobalInto - Clone the given global node and all its target links
582// (and all their llinks, recursively).
583//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000584DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000585 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
586
587 // If a clone has already been created for GNode, return it.
Chris Lattnerc875f022002-11-03 21:27:48 +0000588 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000589 if (ValMapEntry != 0)
590 return ValMapEntry;
591
592 // Clone the node and update the ValMap.
593 DSNode* NewNode = new DSNode(*GNode);
594 ValMapEntry = NewNode; // j=0 case of loop below!
595 Nodes.push_back(NewNode);
596 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +0000597 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000598
599 // Rewrite the links in the new node to point into the current graph.
600 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
601 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
602
603 return NewNode;
604}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000605#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000606
607
Chris Lattner0d9bab82002-07-18 00:12:30 +0000608// markIncompleteNodes - Mark the specified node as having contents that are not
609// known with the current analysis we have performed. Because a node makes all
610// of the nodes it can reach imcomplete if the node itself is incomplete, we
611// must recursively traverse the data structure graph, marking all reachable
612// nodes as incomplete.
613//
614static void markIncompleteNode(DSNode *N) {
615 // Stop recursion if no node, or if node already marked...
616 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
617
618 // Actually mark the node
619 N->NodeType |= DSNode::Incomplete;
620
621 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000622 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
623 if (DSNode *DSN = N->getLink(i).getNode())
624 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000625}
626
627
628// markIncompleteNodes - Traverse the graph, identifying nodes that may be
629// modified by other functions that have not been resolved yet. This marks
630// nodes that are reachable through three sources of "unknownness":
631//
632// Global Variables, Function Calls, and Incoming Arguments
633//
634// For any node that may have unknown components (because something outside the
635// scope of current analysis may have modified it), the 'Incomplete' flag is
636// added to the NodeType.
637//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000638void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000639 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000640 if (markFormalArgs && Func)
641 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000642 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
643 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000644
645 // Mark stuff passed into functions calls as being incomplete...
646 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve26b98262002-10-20 21:41:02 +0000647 DSCallSite &Call = FunctionCalls[i];
Chris Lattnere2219762002-07-18 18:22:40 +0000648 // Then the return value is certainly incomplete!
Chris Lattner0969c502002-10-21 02:08:03 +0000649 markIncompleteNode(Call.getRetVal().getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000650
Chris Lattner92673292002-11-02 00:13:20 +0000651 // All objects pointed to by function arguments are incomplete though!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000652 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
Chris Lattner0969c502002-10-21 02:08:03 +0000653 markIncompleteNode(Call.getPtrArg(i).getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000654 }
655
Chris Lattner92673292002-11-02 00:13:20 +0000656 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000657 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000658 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000659 DSNode *N = Nodes[i];
Chris Lattner92673292002-11-02 00:13:20 +0000660 // FIXME: Make more efficient by looking over Links directly
Chris Lattner08db7192002-11-06 06:20:27 +0000661 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
662 if (DSNode *DSN = N->getLink(i).getNode())
663 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000664 }
665}
666
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000667// removeRefsToGlobal - Helper function that removes globals from the
Chris Lattnerc875f022002-11-03 21:27:48 +0000668// ScalarMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000669static void removeRefsToGlobal(DSNode* N,
Chris Lattnerc875f022002-11-03 21:27:48 +0000670 std::map<Value*, DSNodeHandle> &ScalarMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000671 while (!N->getGlobals().empty()) {
672 GlobalValue *GV = N->getGlobals().back();
673 N->getGlobals().pop_back();
Chris Lattnerc875f022002-11-03 21:27:48 +0000674 ScalarMap.erase(GV);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000675 }
676}
677
678
Chris Lattner0d9bab82002-07-18 00:12:30 +0000679// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
680// checks to see if there are simple transformations that it can do to make it
681// dead.
682//
683bool DSGraph::isNodeDead(DSNode *N) {
684 // Is it a trivially dead shadow node...
685 if (N->getReferrers().empty() && N->NodeType == 0)
686 return true;
687
688 // Is it a function node or some other trivially unused global?
Chris Lattner92673292002-11-02 00:13:20 +0000689 if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000690 N->getReferrers().size() == N->getGlobals().size()) {
691
Chris Lattnerc875f022002-11-03 21:27:48 +0000692 // Remove the globals from the ScalarMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000693 // down to zero.
Chris Lattnerc875f022002-11-03 21:27:48 +0000694 removeRefsToGlobal(N, ScalarMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000695 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
696 return true;
697 }
698
699 return false;
700}
701
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000702static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000703 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000704 // Remove trivially identical function calls
705 unsigned NumFns = Calls.size();
706 std::sort(Calls.begin(), Calls.end());
707 Calls.erase(std::unique(Calls.begin(), Calls.end()),
708 Calls.end());
709
710 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000711 std::cerr << "Merged " << (NumFns-Calls.size())
712 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000713}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000714
Chris Lattnere2219762002-07-18 18:22:40 +0000715// removeTriviallyDeadNodes - After the graph has been constructed, this method
716// removes all unreachable nodes that are created because they got merged with
717// other nodes in the graph. These nodes will all be trivially unreachable, so
718// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000719//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000720void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000721 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000722 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000723 if (isNodeDead(Nodes[i])) { // This node is dead!
724 delete Nodes[i]; // Free memory...
725 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
726 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000727
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000728 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000729}
730
731
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000732// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000733// stuff to be alive.
734//
735static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000736 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000737
738 Alive.insert(N);
Chris Lattner08db7192002-11-06 06:20:27 +0000739 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
740 if (DSNode *DSN = N->getLink(i).getNode())
741 if (!Alive.count(DSN))
742 markAlive(DSN, Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000743}
744
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000745static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
746 std::set<DSNode*> &Visiting) {
747 if (N == 0) return false;
748
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000749 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000750 Visiting.insert(N);
751
752 // If any immediate successor is alive, N is alive
Chris Lattner08db7192002-11-06 06:20:27 +0000753 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
754 if (DSNode *DSN = N->getLink(i).getNode())
755 if (Alive.count(DSN)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000756 Visiting.erase(N);
757 return true;
758 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000759
760 // Else if any successor reaches a live node, N is alive
Chris Lattner08db7192002-11-06 06:20:27 +0000761 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
762 if (DSNode *DSN = N->getLink(i).getNode())
763 if (checkGlobalAlive(DSN, Alive, Visiting)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000764 Visiting.erase(N); return true;
765 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000766
767 Visiting.erase(N);
768 return false;
769}
770
771
772// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
773// This would be unnecessary if function calls were real nodes! In that case,
774// the simple iterative loop in the first few lines below suffice.
775//
776static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000777 vector<DSCallSite> &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000778 std::set<DSNode*> &Alive,
779 bool FilterCalls) {
780
781 // Iterate, marking globals or cast nodes alive until no new live nodes
782 // are added to Alive
783 std::set<DSNode*> Visiting; // Used to identify cycles
Chris Lattner0969c502002-10-21 02:08:03 +0000784 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000785 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
786 liveCount = Alive.size();
787 for ( ; I != E; ++I)
788 if (Alive.count(*I) == 0) {
789 Visiting.clear();
790 if (checkGlobalAlive(*I, Alive, Visiting))
791 markAlive(*I, Alive);
792 }
793 }
794
795 // Find function calls with some dead and some live nodes.
796 // Since all call nodes must be live if any one is live, we have to mark
797 // all nodes of the call as live and continue the iteration (via recursion).
798 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000799 bool Recurse = false;
800 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000801 bool CallIsDead = true, CallHasDeadArg = false;
Chris Lattner0969c502002-10-21 02:08:03 +0000802 DSCallSite &CS = Calls[i];
803 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
804 if (DSNode *N = CS.getPtrArg(j).getNode()) {
805 bool ArgIsDead = !Alive.count(N);
806 CallHasDeadArg |= ArgIsDead;
807 CallIsDead &= ArgIsDead;
808 }
809
810 if (DSNode *N = CS.getRetVal().getNode()) {
811 bool RetIsDead = !Alive.count(N);
812 CallHasDeadArg |= RetIsDead;
813 CallIsDead &= RetIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000814 }
Chris Lattner0969c502002-10-21 02:08:03 +0000815
816 DSNode *N = CS.getCallee().getNode();
817 bool FnIsDead = !Alive.count(N);
818 CallHasDeadArg |= FnIsDead;
819 CallIsDead &= FnIsDead;
820
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000821 if (!CallIsDead && CallHasDeadArg) {
822 // Some node in this call is live and another is dead.
823 // Mark all nodes of call as live and iterate once more.
Chris Lattner0969c502002-10-21 02:08:03 +0000824 Recurse = true;
825 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
826 markAlive(CS.getPtrArg(j).getNode(), Alive);
827 markAlive(CS.getRetVal().getNode(), Alive);
828 markAlive(CS.getCallee().getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000829 }
830 }
Chris Lattner0969c502002-10-21 02:08:03 +0000831 if (Recurse)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000832 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
833 }
834}
835
836
837// markGlobalsAlive - Mark global nodes and cast nodes alive if they
838// can reach any other live node. Since this can produce new live nodes,
839// we use a simple iterative algorithm.
840//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000841static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000842 bool FilterCalls) {
843 // Add global and cast nodes to a set so we don't walk all nodes every time
844 std::set<DSNode*> GlobalNodes;
845 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000846 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000847 GlobalNodes.insert(G.getNodes()[i]);
848
849 // Add all call nodes to the same set
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000850 vector<DSCallSite> &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000851 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000852 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
853 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
854 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
855 GlobalNodes.insert(N);
856 if (DSNode *N = Calls[i].getRetVal().getNode())
857 GlobalNodes.insert(N);
858 if (DSNode *N = Calls[i].getCallee().getNode())
859 GlobalNodes.insert(N);
860 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000861 }
862
863 // Iterate and recurse until no new live node are discovered.
864 // This would be a simple iterative loop if function calls were real nodes!
865 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
866
Chris Lattnerc875f022002-11-03 21:27:48 +0000867 // Free up references to dead globals from the ScalarMap
Chris Lattner92673292002-11-02 00:13:20 +0000868 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000869 for( ; I != E; ++I)
870 if (Alive.count(*I) == 0)
Chris Lattnerc875f022002-11-03 21:27:48 +0000871 removeRefsToGlobal(*I, G.getScalarMap());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000872
873 // Delete dead function calls
874 if (FilterCalls)
875 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
876 bool CallIsDead = true;
Chris Lattner0969c502002-10-21 02:08:03 +0000877 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
878 CallIsDead && j != ej; ++j)
879 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000880 if (CallIsDead)
881 Calls.erase(Calls.begin() + i); // remove the call entirely
882 }
883}
Chris Lattnere2219762002-07-18 18:22:40 +0000884
885// removeDeadNodes - Use a more powerful reachability analysis to eliminate
886// subgraphs that are unreachable. This often occurs because the data
887// structure doesn't "escape" into it's caller, and thus should be eliminated
888// from the caller's graph entirely. This is only appropriate to use when
889// inlining graphs.
890//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000891void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
892 assert((!KeepAllGlobals || KeepCalls) &&
893 "KeepAllGlobals without KeepCalls is meaningless");
894
Chris Lattnere2219762002-07-18 18:22:40 +0000895 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000896 removeTriviallyDeadNodes(KeepAllGlobals);
897
Chris Lattnere2219762002-07-18 18:22:40 +0000898 // FIXME: Merge nontrivially identical call nodes...
899
900 // Alive - a set that holds all nodes found to be reachable/alive.
901 std::set<DSNode*> Alive;
902
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000903 // If KeepCalls, mark all nodes reachable by call nodes as alive...
904 if (KeepCalls)
Chris Lattner0969c502002-10-21 02:08:03 +0000905 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
906 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
907 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
908 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
909 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
910 }
Chris Lattnere2219762002-07-18 18:22:40 +0000911
Chris Lattner92673292002-11-02 00:13:20 +0000912 // Mark all nodes reachable by scalar nodes as alive...
Chris Lattnerc875f022002-11-03 21:27:48 +0000913 for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
914 E = ScalarMap.end(); I != E; ++I)
Chris Lattner92673292002-11-02 00:13:20 +0000915 markAlive(I->second.getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000916
Chris Lattner92673292002-11-02 00:13:20 +0000917#if 0
918 // Marge all nodes reachable by global nodes, as alive. Isn't this covered by
Chris Lattnerc875f022002-11-03 21:27:48 +0000919 // the ScalarMap?
Chris Lattner92673292002-11-02 00:13:20 +0000920 //
921 if (KeepAllGlobals)
922 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
923 if (Nodes[i]->NodeType & DSNode::GlobalNode)
924 markAlive(Nodes[i], Alive);
925#endif
Chris Lattnere2219762002-07-18 18:22:40 +0000926
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000927 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000928 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000929
930 // Mark all globals or cast nodes that can reach a live node as alive.
931 // This also marks all nodes reachable from such nodes as alive.
932 // Of course, if KeepAllGlobals is specified, they would be live already.
Chris Lattner0969c502002-10-21 02:08:03 +0000933 if (!KeepAllGlobals)
Chris Lattner92673292002-11-02 00:13:20 +0000934 markGlobalsAlive(*this, Alive, !KeepCalls);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000935
Chris Lattnere2219762002-07-18 18:22:40 +0000936 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000937 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000938 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
939 for (unsigned i = 0; i != Nodes.size(); ++i)
940 if (!Alive.count(Nodes[i])) {
941 DSNode *N = Nodes[i];
942 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
943 DeadNodes.push_back(N); // Add node to our list of dead nodes
944 N->dropAllReferences(); // Drop all outgoing edges
945 }
946
Chris Lattnere2219762002-07-18 18:22:40 +0000947 // Delete all dead nodes...
948 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
949}
950
951
952
Chris Lattner0d9bab82002-07-18 00:12:30 +0000953// maskNodeTypes - Apply a mask to all of the node types in the graph. This
954// is useful for clearing out markers like Scalar or Incomplete.
955//
956void DSGraph::maskNodeTypes(unsigned char Mask) {
957 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
958 Nodes[i]->NodeType &= Mask;
959}
960
961
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000962#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000963//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000964// GlobalDSGraph Implementation
965//===----------------------------------------------------------------------===//
966
967GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
968}
969
970GlobalDSGraph::~GlobalDSGraph() {
971 assert(Referrers.size() == 0 &&
972 "Deleting global graph while references from other graphs exist");
973}
974
975void GlobalDSGraph::addReference(const DSGraph* referrer) {
976 if (referrer != this)
977 Referrers.insert(referrer);
978}
979
980void GlobalDSGraph::removeReference(const DSGraph* referrer) {
981 if (referrer != this) {
982 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
983 Referrers.erase(referrer);
984 if (Referrers.size() == 0)
985 delete this;
986 }
987}
988
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000989#if 0
Chris Lattnerd18f3422002-11-03 21:24:04 +0000990// Bits used in the next function
991static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
992
993
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000994// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
995// visible target links (and recursively their such links) into this graph.
996// NodeCache maps the node being cloned to its clone in the Globals graph,
997// in order to track cycles.
998// GlobalsAreFinal is a flag that says whether it is safe to assume that
999// an existing global node is complete. This is important to avoid
1000// reinserting all globals when inserting Calls to functions.
1001// This is a helper function for cloneGlobals and cloneCalls.
1002//
1003DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1004 std::map<const DSNode*, DSNode*> &NodeCache,
1005 bool GlobalsAreFinal) {
1006 if (OldNode == 0) return 0;
1007
1008 // The caller should check this is an external node. Just more efficient...
1009 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1010
1011 // If a clone has already been created for OldNode, return it.
1012 DSNode*& CacheEntry = NodeCache[OldNode];
1013 if (CacheEntry != 0)
1014 return CacheEntry;
1015
1016 // The result value...
1017 DSNode* NewNode = 0;
1018
1019 // If nodes already exist for any of the globals of OldNode,
1020 // merge all such nodes together since they are merged in OldNode.
1021 // If ValueCacheIsFinal==true, look for an existing node that has
1022 // an identical list of globals and return it if it exists.
1023 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001024 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001025 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001026 if (NewNode == 0) {
1027 NewNode = PrevNode; // first existing node found
1028 if (GlobalsAreFinal && j == 0)
1029 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1030 CacheEntry = NewNode;
1031 return NewNode;
1032 }
1033 }
1034 else if (NewNode != PrevNode) { // found another, different from prev
1035 // update ValMap *before* merging PrevNode into NewNode
1036 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
Chris Lattnerc875f022002-11-03 21:27:48 +00001037 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001038 NewNode->mergeWith(PrevNode);
1039 }
1040 } else if (NewNode != 0) {
Chris Lattnerc875f022002-11-03 21:27:48 +00001041 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001042 }
1043
1044 // If no existing node was found, clone the node and update the ValMap.
1045 if (NewNode == 0) {
1046 NewNode = new DSNode(*OldNode);
1047 Nodes.push_back(NewNode);
1048 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1049 NewNode->setLink(j, 0);
1050 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001051 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001052 }
1053 else
1054 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1055
1056 // Add the entry to NodeCache
1057 CacheEntry = NewNode;
1058
1059 // Rewrite the links in the new node to point into the current graph,
1060 // but only for links to external nodes. Set other links to NULL.
1061 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1062 DSNode* OldTarget = OldNode->getLink(j);
1063 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1064 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1065 if (NewNode->getLink(j))
1066 NewNode->getLink(j)->mergeWith(NewLink);
1067 else
1068 NewNode->setLink(j, NewLink);
1069 }
1070 }
1071
1072 // Remove all local markers
1073 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1074
1075 return NewNode;
1076}
1077
1078
1079// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1080// visible target links (and recursively their such links) into this graph.
1081//
1082void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1083 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001084#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001085 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1086 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1087 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001088 if (CloneCalls)
1089 GlobalsGraph->cloneCalls(Graph);
1090
1091 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001092#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001093}
1094
1095
1096// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1097// links (and recursively their such links) into this graph.
1098//
1099void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1100 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001101 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001102
1103 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1104
1105 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001106 DSCallSite& callCopy = FunctionCalls.back();
1107 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001108 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001109 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001110 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1111 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1112 : 0);
1113 }
1114
1115 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001116 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001117}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001118#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001119
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001120#endif