blob: 85e9684e02258199a4a6dbbfcd496059eff60fec [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 Lattner92673292002-11-02 00:13:20 +000019namespace DataStructureAnalysis { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000020 // isPointerType - Return true if this first class type is big enough to hold
21 // a pointer.
22 //
23 bool isPointerType(const Type *Ty);
24 extern TargetData TD;
25}
26using namespace DataStructureAnalysis;
27
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 Lattnerfccd06f2002-10-01 22:33:50 +000032DSNode::DSNode(enum NodeTy NT, const Type *T) : NodeType(NT) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000033 // Add the type entry if it is specified...
34 if (T) getTypeRec(T, 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000035}
36
Chris Lattner0d9bab82002-07-18 00:12:30 +000037// DSNode copy constructor... do not copy over the referrers list!
38DSNode::DSNode(const DSNode &N)
Chris Lattner7b7200c2002-10-02 04:57:39 +000039 : Links(N.Links), MergeMap(N.MergeMap),
Chris Lattnerfccd06f2002-10-01 22:33:50 +000040 TypeEntries(N.TypeEntries), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000041}
42
Chris Lattnerc68c31b2002-07-10 22:38:08 +000043void DSNode::removeReferrer(DSNodeHandle *H) {
44 // Search backwards, because we depopulate the list from the back for
45 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000046 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000047 std::find(Referrers.rbegin(), Referrers.rend(), H);
48 assert(I != Referrers.rend() && "Referrer not pointing to node!");
49 Referrers.erase(I.base()-1);
50}
51
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000052// addGlobal - Add an entry for a global value to the Globals list. This also
53// marks the node with the 'G' flag if it does not already have it.
54//
55void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000056 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000057 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000058 std::lower_bound(Globals.begin(), Globals.end(), GV);
59
60 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000061 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000062 Globals.insert(I, GV);
63 NodeType |= GlobalNode;
64 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000065}
66
Chris Lattner8f0a16e2002-10-31 05:45:02 +000067/// foldNodeCompletely - If we determine that this node has some funny
68/// behavior happening to it that we cannot represent, we fold it down to a
69/// single, completely pessimistic, node. This node is represented as a
70/// single byte with a single TypeEntry of "void".
71///
72void DSNode::foldNodeCompletely() {
73 // We are no longer typed at all...
74 TypeEntries.clear();
75 TypeEntries.push_back(DSTypeRec(Type::VoidTy, 0));
76
77 // Loop over all of our referrers, making them point to our one byte of space.
78 for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
79 I != E; ++I)
80 (*I)->setOffset(0);
81
82 // Fold the MergeMap down to a single byte of space...
83 MergeMap.resize(1);
84 MergeMap[0] = -1;
85
86 // If we have links, merge all of our outgoing links together...
87 if (!Links.empty()) {
88 MergeMap[0] = 0; // We now contain an outgoing edge...
89 for (unsigned i = 1, e = Links.size(); i != e; ++i)
90 Links[0].mergeWith(Links[i]);
91 Links.resize(1);
92 }
93}
94
95/// isNodeCompletelyFolded - Return true if this node has been completely
96/// folded down to something that can never be expanded, effectively losing
97/// all of the field sensitivity that may be present in the node.
98///
99bool DSNode::isNodeCompletelyFolded() const {
100 return getSize() == 1 && TypeEntries.size() == 1 &&
101 TypeEntries[0].Ty == Type::VoidTy;
102}
103
104
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000105
Chris Lattner7b7200c2002-10-02 04:57:39 +0000106/// setLink - Set the link at the specified offset to the specified
107/// NodeHandle, replacing what was there. It is uncommon to use this method,
108/// instead one of the higher level methods should be used, below.
109///
110void DSNode::setLink(unsigned i, const DSNodeHandle &NH) {
111 // Create a new entry in the Links vector to hold a new element for offset.
112 if (!hasLink(i)) {
113 signed char NewIdx = Links.size();
114 // Check to see if we allocate more than 128 distinct links for this node.
115 // If so, just merge with the last one. This really shouldn't ever happen,
116 // but it should work regardless of whether it does or not.
117 //
118 if (NewIdx >= 0) {
119 Links.push_back(NH); // Allocate space: common case
120 } else { // Wrap around? Too many links?
121 NewIdx--; // Merge with whatever happened last
122 assert(NewIdx > 0 && "Should wrap back around");
123 std::cerr << "\n*** DSNode found that requires more than 128 "
124 << "active links at once!\n\n";
125 }
126
127 signed char OldIdx = MergeMap[i];
128 assert (OldIdx < 0 && "Shouldn't contain link!");
129
130 // Make sure that anything aliasing this field gets updated to point to the
131 // new link field.
132 rewriteMergeMap(OldIdx, NewIdx);
133 assert(MergeMap[i] == NewIdx && "Field not replaced!");
134 } else {
135 Links[MergeMap[i]] = NH;
136 }
137}
138
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000139// addEdgeTo - Add an edge from the current node to the specified node. This
140// can cause merging of nodes in the graph.
141//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000142void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000143 assert(Offset < getSize() && "Offset out of range!");
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000144 if (NH.getNode() == 0) return; // Nothing to do
145
Chris Lattner7b7200c2002-10-02 04:57:39 +0000146 if (DSNodeHandle *ExistingNH = getLink(Offset)) {
147 // Merge the two nodes...
148 ExistingNH->mergeWith(NH);
149 } else { // No merging to perform...
150 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000151 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000152}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000153
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000154/// getTypeRec - This method returns the specified type record if it exists.
155/// If it does not yet exist, the method checks to see whether or not the
156/// request would result in an untrackable state. If adding it would cause
157/// untrackable state, we foldNodeCompletely the node and return the void
158/// record, otherwise we add an new TypeEntry and return it.
159///
160DSTypeRec &DSNode::getTypeRec(const Type *Ty, unsigned Offset) {
161 // If the node is already collapsed, we can't do anything... bail out early
162 if (isNodeCompletelyFolded()) {
163 assert(TypeEntries.size() == 1 && "Node folded and Entries.size() != 1?");
164 return TypeEntries[0];
165 }
166
167 // First search to see if we already have a record for this...
168 DSTypeRec SearchFor(Ty, Offset);
169
170 std::vector<DSTypeRec>::iterator I;
171 if (TypeEntries.size() < 5) { // Linear search if we have few entries.
172 I = TypeEntries.begin();
173 while (I != TypeEntries.end() && *I < SearchFor)
174 ++I;
175 } else {
176 I = std::lower_bound(TypeEntries.begin(), TypeEntries.end(), SearchFor);
177 }
178
179 // At this point, I either points to the right entry or it points to the entry
180 // we are to insert the new entry in front of...
181 //
182 if (I != TypeEntries.end() && *I == SearchFor)
183 return *I;
184
185 // ASSUME that it's okay to add this type entry.
186 // FIXME: This should check to make sure it's ok.
187
188 // If the data size is different then our current size, try to resize the node
189 unsigned ReqSize = Ty->isSized() ? TD.getTypeSize(Ty) : 0;
190 if (getSize() < ReqSize) {
191 // If we are trying to make it bigger, and we can grow the node, do so.
192 if (growNode(ReqSize)) {
193 assert(isNodeCompletelyFolded() && "Node isn't folded?");
194 return TypeEntries[0];
195 }
196
197 } else if (getSize() > ReqSize) {
198 // If we are trying to make the node smaller, we don't have to do anything.
199
200 }
201
202 return *TypeEntries.insert(I, SearchFor);
203}
204
205/// growNode - Attempt to grow the node to the specified size. This may do one
206/// of three things:
207/// 1. Grow the node, return false
208/// 2. Refuse to grow the node, but maintain a trackable situation, return
209/// false.
210/// 3. Be unable to track if node was that size, so collapse the node and
211/// return true.
212///
213bool DSNode::growNode(unsigned ReqSize) {
214 unsigned OldSize = getSize();
215
216 if (0) {
217 // FIXME: DSNode::growNode() doesn't perform correct safety checks yet!
218
219 foldNodeCompletely();
220 return true;
221 }
222
223 assert(ReqSize > OldSize && "Not growing node!");
224
225 // Resize the merge map to have enough space...
226 MergeMap.resize(ReqSize);
227
228 // Assign unique values to all of the elements of MergeMap
229 if (ReqSize < 128) {
230 // Handle the common case of reasonable size structures...
231 for (unsigned i = OldSize; i != ReqSize; ++i)
232 MergeMap[i] = -1-i; // Assign -1, -2, -3, ...
233 } else {
234 // It's possible that we have something really big here. In this case,
235 // divide the object into chunks until it will fit into 128 elements.
236 unsigned Multiple = ReqSize/128;
237
238 // It's probably an array, and probably some power of two in size.
239 // Because of this, find the biggest power of two that is bigger than
240 // multiple to use as our real Multiple.
241 unsigned RealMultiple = 2;
242 while (RealMultiple <= Multiple) RealMultiple <<= 1;
243
244 unsigned RealBound = ReqSize/RealMultiple;
245 assert(RealBound <= 128 && "Math didn't work out right");
246
247 // Now go through and assign indexes that are between -1 and -128
248 // inclusive
249 //
250 for (unsigned i = OldSize; i != ReqSize; ++i)
251 MergeMap[i] = -1-(i % RealBound); // Assign -1, -2, -3...
252 }
253 return false;
254}
255
Chris Lattner7b7200c2002-10-02 04:57:39 +0000256/// mergeMappedValues - This is the higher level form of rewriteMergeMap. It is
257/// fully capable of merging links together if neccesary as well as simply
258/// rewriting the map entries.
259///
260void DSNode::mergeMappedValues(signed char V1, signed char V2) {
261 assert(V1 != V2 && "Cannot merge two identical mapped values!");
262
263 if (V1 < 0) { // If there is no outgoing link from V1, merge it with V2
264 if (V2 < 0 && V1 > V2)
265 // If both are not linked, merge to the field closer to 0
266 rewriteMergeMap(V2, V1);
267 else
268 rewriteMergeMap(V1, V2);
269 } else if (V2 < 0) { // Is V2 < 0 && V1 >= 0?
270 rewriteMergeMap(V2, V1); // Merge into the one with the link...
271 } else { // Otherwise, links exist at both locations
272 // Merge Links[V1] with Links[V2] so they point to the same place now...
273 Links[V1].mergeWith(Links[V2]);
274
275 // Merge the V2 link into V1 so that we reduce the overall value of the
276 // links are reduced...
277 //
278 if (V2 < V1) std::swap(V1, V2); // Ensure V1 < V2
279 rewriteMergeMap(V2, V1); // After this, V2 is "dead"
280
281 // Change the user of the last link to use V2 instead
282 if ((unsigned)V2 != Links.size()-1) {
283 rewriteMergeMap(Links.size()-1, V2); // Point to V2 instead of last el...
284 // Make sure V2 points the right DSNode
285 Links[V2] = Links.back();
286 }
287
288 // Reduce the number of distinct outgoing links...
289 Links.pop_back();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000290 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000291}
292
293
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000294// MergeSortedVectors - Efficiently merge a vector into another vector where
295// duplicates are not allowed and both are sorted. This assumes that 'T's are
296// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000297//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000298template<typename T>
299void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
300 // By far, the most common cases will be the simple ones. In these cases,
301 // avoid having to allocate a temporary vector...
302 //
303 if (Src.empty()) { // Nothing to merge in...
304 return;
305 } else if (Dest.empty()) { // Just copy the result in...
306 Dest = Src;
307 } else if (Src.size() == 1) { // Insert a single element...
308 const T &V = Src[0];
309 typename vector<T>::iterator I =
310 std::lower_bound(Dest.begin(), Dest.end(), V);
311 if (I == Dest.end() || *I != Src[0]) // If not already contained...
312 Dest.insert(I, Src[0]);
313 } else if (Dest.size() == 1) {
314 T Tmp = Dest[0]; // Save value in temporary...
315 Dest = Src; // Copy over list...
316 typename vector<T>::iterator I =
317 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
318 if (I == Dest.end() || *I != Src[0]) // If not already contained...
319 Dest.insert(I, Src[0]);
320
321 } else {
322 // Make a copy to the side of Dest...
323 vector<T> Old(Dest);
324
325 // Make space for all of the type entries now...
326 Dest.resize(Dest.size()+Src.size());
327
328 // Merge the two sorted ranges together... into Dest.
329 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
330
331 // Now erase any duplicate entries that may have accumulated into the
332 // vectors (because they were in both of the input sets)
333 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
334 }
335}
336
337
338// mergeWith - Merge this node and the specified node, moving all links to and
339// from the argument node into the current node, deleting the node argument.
340// Offset indicates what offset the specified node is to be merged into the
341// current node.
342//
343// The specified node may be a null pointer (in which case, nothing happens).
344//
345void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
346 DSNode *N = NH.getNode();
347 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000348 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000349
Chris Lattner02606632002-11-04 06:48:26 +0000350 if (N == this) {
351 std::cerr << "WARNING: Cannot merge two portions of the same node yet, so we collapse instead!\n";
352 N->foldNodeCompletely();
353 return;
354 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000355
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000356 // If we are merging a node with a completely folded node, then both nodes are
357 // now completely folded.
358 //
359 if (isNodeCompletelyFolded()) {
Chris Lattner02606632002-11-04 06:48:26 +0000360 if (!N->isNodeCompletelyFolded())
361 N->foldNodeCompletely();
362 } else if (N->isNodeCompletelyFolded()) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000363 foldNodeCompletely();
364 Offset = 0;
365 }
Chris Lattner02606632002-11-04 06:48:26 +0000366 N = NH.getNode();
367
368 if (this == N) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000369
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000370 // If both nodes are not at offset 0, make sure that we are merging the node
371 // at an later offset into the node with the zero offset.
372 //
373 if (Offset > NH.getOffset()) {
374 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
375 return;
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000376 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
377 // If the offsets are the same, merge the smaller node into the bigger node
378 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
379 return;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000380 }
381
382#if 0
383 std::cerr << "\n\nMerging:\n";
384 N->print(std::cerr, 0);
385 std::cerr << " and:\n";
386 print(std::cerr, 0);
387#endif
388
389 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
390 // respect to NH.Offset) is now zero.
391 //
392 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000393
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000394 // If our destination node is too small... try to grow it.
395 if (N->getSize()+NOffset > getSize() &&
396 growNode(N->getSize()+NOffset)) {
397 // Catastrophic failure occured and we had to collapse the node. In this
398 // case, collapse the other node as well.
399 N->foldNodeCompletely();
400 NOffset = 0;
401 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000402 unsigned NSize = N->getSize();
Chris Lattner7b7200c2002-10-02 04:57:39 +0000403
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000404 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000405 // Make sure to adjust their offset, not just the node pointer.
406 //
407 while (!N->Referrers.empty()) {
408 DSNodeHandle &Ref = *N->Referrers.back();
409 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
410 }
Chris Lattner02606632002-11-04 06:48:26 +0000411
Chris Lattner7b7200c2002-10-02 04:57:39 +0000412 // We must merge fields in this node due to nodes merged in the source node.
413 // In order to handle this we build a map that converts from the source node's
414 // MergeMap values to our MergeMap values. This map is indexed by the
415 // expression: MergeMap[SMM+SourceNodeSize] so we need to allocate at least
416 // 2*SourceNodeSize elements of space for the mapping. We can do this because
417 // we know that there are at most SourceNodeSize outgoing links in the node
418 // (thus that many positive values) and at most SourceNodeSize distinct fields
419 // (thus that many negative values).
420 //
421 std::vector<signed char> MergeMapMap(NSize*2, 127);
422
423 // Loop through the structures, merging them together...
424 for (unsigned i = 0, e = NSize; i != e; ++i) {
425 // Get what this byte of N maps to...
426 signed char NElement = N->MergeMap[i];
427
428 // Get what we map this byte to...
429 signed char Element = MergeMap[i+NOffset];
430 // We use 127 as a sentinal and don't check for it's existence yet...
431 assert(Element != 127 && "MergeMapMap doesn't permit 127 values yet!");
432
433 signed char CurMappedVal = MergeMapMap[NElement+NSize];
434 if (CurMappedVal == 127) { // Haven't seen this NElement yet?
435 MergeMapMap[NElement+NSize] = Element; // Map the two together...
436 } else if (CurMappedVal != Element) {
437 // If we are mapping two different fields together this means that we need
438 // to merge fields in the current node due to merging in the source node.
439 //
440 mergeMappedValues(CurMappedVal, Element);
441 MergeMapMap[NElement+NSize] = MergeMap[i+NOffset];
442 }
443 }
444
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000445 // Make all of the outgoing links of N now be outgoing links of this. This
446 // can cause recursive merging!
447 //
Chris Lattner7b7200c2002-10-02 04:57:39 +0000448 for (unsigned i = 0, e = NSize; i != e; ++i)
449 if (DSNodeHandle *Link = N->getLink(i)) {
Chris Lattner02606632002-11-04 06:48:26 +0000450 addEdgeTo((i+NOffset) % getSize(), *Link);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000451 N->MergeMap[i] = -1; // Kill outgoing edge
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000452 }
453
454 // Now that there are no outgoing edges, all of the Links are dead.
455 N->Links.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000456
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000457 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000458 NodeType |= N->NodeType;
459 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000460
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000461 // Adjust all of the type entries we are merging in by the offset...
462 //
463 if (NOffset != 0) { // This case is common enough to optimize for
464 // Offset all of the TypeEntries in N with their new offset
465 for (unsigned i = 0, e = N->TypeEntries.size(); i != e; ++i)
466 N->TypeEntries[i].Offset += NOffset;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000467 }
468
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000469 // ... now add them to the TypeEntries list.
470 MergeSortedVectors(TypeEntries, N->TypeEntries);
471 N->TypeEntries.clear(); // N is dead, no type-entries need exist
472
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000473 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000474 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000475 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000476
477 // Delete the globals from the old node...
478 N->Globals.clear();
479 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000480}
481
Chris Lattner9de906c2002-10-20 22:11:44 +0000482//===----------------------------------------------------------------------===//
483// DSCallSite Implementation
484//===----------------------------------------------------------------------===//
485
Vikram S. Adve26b98262002-10-20 21:41:02 +0000486// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000487Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000488 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000489}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000490
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000491
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000492//===----------------------------------------------------------------------===//
493// DSGraph Implementation
494//===----------------------------------------------------------------------===//
495
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000496DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
497 std::map<const DSNode*, DSNode*> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000498 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000499}
500
Chris Lattnereff0da92002-10-21 15:32:34 +0000501DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
502 : Func(G.Func) {
Chris Lattnerc875f022002-11-03 21:27:48 +0000503 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000504}
505
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000506DSGraph::~DSGraph() {
507 FunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000508 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000509 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000510
511#ifndef NDEBUG
512 // Drop all intra-node references, so that assertions don't fail...
513 std::for_each(Nodes.begin(), Nodes.end(),
514 std::mem_fun(&DSNode::dropAllReferences));
515#endif
516
517 // Delete all of the nodes themselves...
518 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
519}
520
Chris Lattner0d9bab82002-07-18 00:12:30 +0000521// dump - Allow inspection of graph in a debugger.
522void DSGraph::dump() const { print(std::cerr); }
523
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000524
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000525// Helper function used to clone a function list.
526//
527static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
528 vector<DSCallSite> &toCalls,
529 std::map<const DSNode*, DSNode*> &NodeMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000530 unsigned FC = toCalls.size(); // FirstCall
531 toCalls.reserve(FC+fromCalls.size());
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000532 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
Chris Lattner99a22842002-10-21 15:04:18 +0000533 toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000534}
535
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000536/// remapLinks - Change all of the Links in the current node according to the
537/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000538///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000539void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
540 for (unsigned i = 0, e = Links.size(); i != e; ++i)
541 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
542}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000543
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000544
Chris Lattner0d9bab82002-07-18 00:12:30 +0000545// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000546// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000547// filled into the OldValMap member. If StripAllocas is set to true, Alloca
548// markers are removed from the graph, as the graph is being cloned into a
549// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000550//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000551DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
552 std::map<Value*, DSNodeHandle> &OldValMap,
553 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattner92673292002-11-02 00:13:20 +0000554 bool StripScalars, // FIXME: Kill StripScalars
555 bool StripAllocas) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000556 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000557
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000558 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000559
560 // Duplicate all of the nodes, populating the node map...
561 Nodes.reserve(FN+G.Nodes.size());
562 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000563 DSNode *Old = G.Nodes[i];
564 DSNode *New = new DSNode(*Old);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000565 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000566 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000567 }
568
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000569 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000570 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000571 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000572
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000573 // Remove local markers as specified
Chris Lattner92673292002-11-02 00:13:20 +0000574 unsigned char StripBits = StripAllocas ? DSNode::AllocaNode : 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000575 if (StripBits)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000576 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000577 Nodes[i]->NodeType &= ~StripBits;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000578
Chris Lattnercf15db32002-10-17 20:09:52 +0000579 // Copy the value map... and merge all of the global nodes...
Chris Lattnerc875f022002-11-03 21:27:48 +0000580 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
581 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000582 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner92673292002-11-02 00:13:20 +0000583 H.setNode(OldNodeMap[I->second.getNode()]);
584 H.setOffset(I->second.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000585
586 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattnerc875f022002-11-03 21:27:48 +0000587 std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
588 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000589 GVI->second.mergeWith(H);
590 } else {
Chris Lattnerc875f022002-11-03 21:27:48 +0000591 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000592 }
593 }
594 }
Chris Lattnere2219762002-07-18 18:22:40 +0000595 // Copy the function calls list...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000596 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000597
Chris Lattnercf15db32002-10-17 20:09:52 +0000598
Chris Lattner0d9bab82002-07-18 00:12:30 +0000599 // Return the returned node pointer...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000600 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000601}
602
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000603#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000604// cloneGlobalInto - Clone the given global node and all its target links
605// (and all their llinks, recursively).
606//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000607DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000608 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
609
610 // If a clone has already been created for GNode, return it.
Chris Lattnerc875f022002-11-03 21:27:48 +0000611 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000612 if (ValMapEntry != 0)
613 return ValMapEntry;
614
615 // Clone the node and update the ValMap.
616 DSNode* NewNode = new DSNode(*GNode);
617 ValMapEntry = NewNode; // j=0 case of loop below!
618 Nodes.push_back(NewNode);
619 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +0000620 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000621
622 // Rewrite the links in the new node to point into the current graph.
623 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
624 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
625
626 return NewNode;
627}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000628#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000629
630
Chris Lattner0d9bab82002-07-18 00:12:30 +0000631// markIncompleteNodes - Mark the specified node as having contents that are not
632// known with the current analysis we have performed. Because a node makes all
633// of the nodes it can reach imcomplete if the node itself is incomplete, we
634// must recursively traverse the data structure graph, marking all reachable
635// nodes as incomplete.
636//
637static void markIncompleteNode(DSNode *N) {
638 // Stop recursion if no node, or if node already marked...
639 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
640
641 // Actually mark the node
642 N->NodeType |= DSNode::Incomplete;
643
644 // Recusively process children...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000645 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
646 if (DSNodeHandle *DSNH = N->getLink(i))
647 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000648}
649
650
651// markIncompleteNodes - Traverse the graph, identifying nodes that may be
652// modified by other functions that have not been resolved yet. This marks
653// nodes that are reachable through three sources of "unknownness":
654//
655// Global Variables, Function Calls, and Incoming Arguments
656//
657// For any node that may have unknown components (because something outside the
658// scope of current analysis may have modified it), the 'Incomplete' flag is
659// added to the NodeType.
660//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000661void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000662 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000663 if (markFormalArgs && Func)
664 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000665 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
666 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000667
668 // Mark stuff passed into functions calls as being incomplete...
669 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve26b98262002-10-20 21:41:02 +0000670 DSCallSite &Call = FunctionCalls[i];
Chris Lattnere2219762002-07-18 18:22:40 +0000671 // Then the return value is certainly incomplete!
Chris Lattner0969c502002-10-21 02:08:03 +0000672 markIncompleteNode(Call.getRetVal().getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000673
Chris Lattner92673292002-11-02 00:13:20 +0000674 // All objects pointed to by function arguments are incomplete though!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000675 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
Chris Lattner0969c502002-10-21 02:08:03 +0000676 markIncompleteNode(Call.getPtrArg(i).getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000677 }
678
Chris Lattner92673292002-11-02 00:13:20 +0000679 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000680 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000681 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000682 DSNode *N = Nodes[i];
Chris Lattner92673292002-11-02 00:13:20 +0000683 // FIXME: Make more efficient by looking over Links directly
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000684 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
685 if (DSNodeHandle *DSNH = N->getLink(i))
686 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000687 }
688}
689
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000690// removeRefsToGlobal - Helper function that removes globals from the
Chris Lattnerc875f022002-11-03 21:27:48 +0000691// ScalarMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000692static void removeRefsToGlobal(DSNode* N,
Chris Lattnerc875f022002-11-03 21:27:48 +0000693 std::map<Value*, DSNodeHandle> &ScalarMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000694 while (!N->getGlobals().empty()) {
695 GlobalValue *GV = N->getGlobals().back();
696 N->getGlobals().pop_back();
Chris Lattnerc875f022002-11-03 21:27:48 +0000697 ScalarMap.erase(GV);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000698 }
699}
700
701
Chris Lattner0d9bab82002-07-18 00:12:30 +0000702// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
703// checks to see if there are simple transformations that it can do to make it
704// dead.
705//
706bool DSGraph::isNodeDead(DSNode *N) {
707 // Is it a trivially dead shadow node...
708 if (N->getReferrers().empty() && N->NodeType == 0)
709 return true;
710
711 // Is it a function node or some other trivially unused global?
Chris Lattner92673292002-11-02 00:13:20 +0000712 if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000713 N->getReferrers().size() == N->getGlobals().size()) {
714
Chris Lattnerc875f022002-11-03 21:27:48 +0000715 // Remove the globals from the ScalarMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000716 // down to zero.
Chris Lattnerc875f022002-11-03 21:27:48 +0000717 removeRefsToGlobal(N, ScalarMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000718 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
719 return true;
720 }
721
722 return false;
723}
724
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000725static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000726 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000727 // Remove trivially identical function calls
728 unsigned NumFns = Calls.size();
729 std::sort(Calls.begin(), Calls.end());
730 Calls.erase(std::unique(Calls.begin(), Calls.end()),
731 Calls.end());
732
733 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000734 std::cerr << "Merged " << (NumFns-Calls.size())
735 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000736}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000737
Chris Lattnere2219762002-07-18 18:22:40 +0000738// removeTriviallyDeadNodes - After the graph has been constructed, this method
739// removes all unreachable nodes that are created because they got merged with
740// other nodes in the graph. These nodes will all be trivially unreachable, so
741// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000742//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000743void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000744 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000745 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000746 if (isNodeDead(Nodes[i])) { // This node is dead!
747 delete Nodes[i]; // Free memory...
748 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
749 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000750
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000751 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000752}
753
754
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000755// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000756// stuff to be alive.
757//
758static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000759 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000760
761 Alive.insert(N);
Chris Lattner92673292002-11-02 00:13:20 +0000762 // FIXME: Make more efficient by looking over Links directly
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000763 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
764 if (DSNodeHandle *DSNH = N->getLink(i))
765 if (!Alive.count(DSNH->getNode()))
766 markAlive(DSNH->getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000767}
768
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000769static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
770 std::set<DSNode*> &Visiting) {
771 if (N == 0) return false;
772
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000773 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000774 Visiting.insert(N);
775
776 // If any immediate successor is alive, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000777 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
778 if (DSNodeHandle *DSNH = N->getLink(i))
779 if (Alive.count(DSNH->getNode())) {
780 Visiting.erase(N);
781 return true;
782 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000783
784 // Else if any successor reaches a live node, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000785 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
786 if (DSNodeHandle *DSNH = N->getLink(i))
787 if (checkGlobalAlive(DSNH->getNode(), Alive, Visiting)) {
788 Visiting.erase(N); return true;
789 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000790
791 Visiting.erase(N);
792 return false;
793}
794
795
796// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
797// This would be unnecessary if function calls were real nodes! In that case,
798// the simple iterative loop in the first few lines below suffice.
799//
800static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000801 vector<DSCallSite> &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000802 std::set<DSNode*> &Alive,
803 bool FilterCalls) {
804
805 // Iterate, marking globals or cast nodes alive until no new live nodes
806 // are added to Alive
807 std::set<DSNode*> Visiting; // Used to identify cycles
Chris Lattner0969c502002-10-21 02:08:03 +0000808 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000809 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
810 liveCount = Alive.size();
811 for ( ; I != E; ++I)
812 if (Alive.count(*I) == 0) {
813 Visiting.clear();
814 if (checkGlobalAlive(*I, Alive, Visiting))
815 markAlive(*I, Alive);
816 }
817 }
818
819 // Find function calls with some dead and some live nodes.
820 // Since all call nodes must be live if any one is live, we have to mark
821 // all nodes of the call as live and continue the iteration (via recursion).
822 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000823 bool Recurse = false;
824 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000825 bool CallIsDead = true, CallHasDeadArg = false;
Chris Lattner0969c502002-10-21 02:08:03 +0000826 DSCallSite &CS = Calls[i];
827 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
828 if (DSNode *N = CS.getPtrArg(j).getNode()) {
829 bool ArgIsDead = !Alive.count(N);
830 CallHasDeadArg |= ArgIsDead;
831 CallIsDead &= ArgIsDead;
832 }
833
834 if (DSNode *N = CS.getRetVal().getNode()) {
835 bool RetIsDead = !Alive.count(N);
836 CallHasDeadArg |= RetIsDead;
837 CallIsDead &= RetIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000838 }
Chris Lattner0969c502002-10-21 02:08:03 +0000839
840 DSNode *N = CS.getCallee().getNode();
841 bool FnIsDead = !Alive.count(N);
842 CallHasDeadArg |= FnIsDead;
843 CallIsDead &= FnIsDead;
844
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000845 if (!CallIsDead && CallHasDeadArg) {
846 // Some node in this call is live and another is dead.
847 // Mark all nodes of call as live and iterate once more.
Chris Lattner0969c502002-10-21 02:08:03 +0000848 Recurse = true;
849 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
850 markAlive(CS.getPtrArg(j).getNode(), Alive);
851 markAlive(CS.getRetVal().getNode(), Alive);
852 markAlive(CS.getCallee().getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000853 }
854 }
Chris Lattner0969c502002-10-21 02:08:03 +0000855 if (Recurse)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000856 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
857 }
858}
859
860
861// markGlobalsAlive - Mark global nodes and cast nodes alive if they
862// can reach any other live node. Since this can produce new live nodes,
863// we use a simple iterative algorithm.
864//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000865static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000866 bool FilterCalls) {
867 // Add global and cast nodes to a set so we don't walk all nodes every time
868 std::set<DSNode*> GlobalNodes;
869 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000870 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000871 GlobalNodes.insert(G.getNodes()[i]);
872
873 // Add all call nodes to the same set
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000874 vector<DSCallSite> &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000875 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000876 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
877 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
878 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
879 GlobalNodes.insert(N);
880 if (DSNode *N = Calls[i].getRetVal().getNode())
881 GlobalNodes.insert(N);
882 if (DSNode *N = Calls[i].getCallee().getNode())
883 GlobalNodes.insert(N);
884 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000885 }
886
887 // Iterate and recurse until no new live node are discovered.
888 // This would be a simple iterative loop if function calls were real nodes!
889 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
890
Chris Lattnerc875f022002-11-03 21:27:48 +0000891 // Free up references to dead globals from the ScalarMap
Chris Lattner92673292002-11-02 00:13:20 +0000892 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000893 for( ; I != E; ++I)
894 if (Alive.count(*I) == 0)
Chris Lattnerc875f022002-11-03 21:27:48 +0000895 removeRefsToGlobal(*I, G.getScalarMap());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000896
897 // Delete dead function calls
898 if (FilterCalls)
899 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
900 bool CallIsDead = true;
Chris Lattner0969c502002-10-21 02:08:03 +0000901 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
902 CallIsDead && j != ej; ++j)
903 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000904 if (CallIsDead)
905 Calls.erase(Calls.begin() + i); // remove the call entirely
906 }
907}
Chris Lattnere2219762002-07-18 18:22:40 +0000908
909// removeDeadNodes - Use a more powerful reachability analysis to eliminate
910// subgraphs that are unreachable. This often occurs because the data
911// structure doesn't "escape" into it's caller, and thus should be eliminated
912// from the caller's graph entirely. This is only appropriate to use when
913// inlining graphs.
914//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000915void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
916 assert((!KeepAllGlobals || KeepCalls) &&
917 "KeepAllGlobals without KeepCalls is meaningless");
918
Chris Lattnere2219762002-07-18 18:22:40 +0000919 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000920 removeTriviallyDeadNodes(KeepAllGlobals);
921
Chris Lattnere2219762002-07-18 18:22:40 +0000922 // FIXME: Merge nontrivially identical call nodes...
923
924 // Alive - a set that holds all nodes found to be reachable/alive.
925 std::set<DSNode*> Alive;
926
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000927 // If KeepCalls, mark all nodes reachable by call nodes as alive...
928 if (KeepCalls)
Chris Lattner0969c502002-10-21 02:08:03 +0000929 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
930 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
931 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
932 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
933 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
934 }
Chris Lattnere2219762002-07-18 18:22:40 +0000935
Chris Lattner92673292002-11-02 00:13:20 +0000936 // Mark all nodes reachable by scalar nodes as alive...
Chris Lattnerc875f022002-11-03 21:27:48 +0000937 for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
938 E = ScalarMap.end(); I != E; ++I)
Chris Lattner92673292002-11-02 00:13:20 +0000939 markAlive(I->second.getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000940
Chris Lattner92673292002-11-02 00:13:20 +0000941#if 0
942 // Marge all nodes reachable by global nodes, as alive. Isn't this covered by
Chris Lattnerc875f022002-11-03 21:27:48 +0000943 // the ScalarMap?
Chris Lattner92673292002-11-02 00:13:20 +0000944 //
945 if (KeepAllGlobals)
946 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
947 if (Nodes[i]->NodeType & DSNode::GlobalNode)
948 markAlive(Nodes[i], Alive);
949#endif
Chris Lattnere2219762002-07-18 18:22:40 +0000950
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000951 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000952 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000953
954 // Mark all globals or cast nodes that can reach a live node as alive.
955 // This also marks all nodes reachable from such nodes as alive.
956 // Of course, if KeepAllGlobals is specified, they would be live already.
Chris Lattner0969c502002-10-21 02:08:03 +0000957 if (!KeepAllGlobals)
Chris Lattner92673292002-11-02 00:13:20 +0000958 markGlobalsAlive(*this, Alive, !KeepCalls);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000959
Chris Lattnere2219762002-07-18 18:22:40 +0000960 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000961 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000962 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
963 for (unsigned i = 0; i != Nodes.size(); ++i)
964 if (!Alive.count(Nodes[i])) {
965 DSNode *N = Nodes[i];
966 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
967 DeadNodes.push_back(N); // Add node to our list of dead nodes
968 N->dropAllReferences(); // Drop all outgoing edges
969 }
970
Chris Lattnere2219762002-07-18 18:22:40 +0000971 // Delete all dead nodes...
972 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
973}
974
975
976
Chris Lattner0d9bab82002-07-18 00:12:30 +0000977// maskNodeTypes - Apply a mask to all of the node types in the graph. This
978// is useful for clearing out markers like Scalar or Incomplete.
979//
980void DSGraph::maskNodeTypes(unsigned char Mask) {
981 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
982 Nodes[i]->NodeType &= Mask;
983}
984
985
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000986#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000987//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000988// GlobalDSGraph Implementation
989//===----------------------------------------------------------------------===//
990
991GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
992}
993
994GlobalDSGraph::~GlobalDSGraph() {
995 assert(Referrers.size() == 0 &&
996 "Deleting global graph while references from other graphs exist");
997}
998
999void GlobalDSGraph::addReference(const DSGraph* referrer) {
1000 if (referrer != this)
1001 Referrers.insert(referrer);
1002}
1003
1004void GlobalDSGraph::removeReference(const DSGraph* referrer) {
1005 if (referrer != this) {
1006 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
1007 Referrers.erase(referrer);
1008 if (Referrers.size() == 0)
1009 delete this;
1010 }
1011}
1012
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001013#if 0
Chris Lattnerd18f3422002-11-03 21:24:04 +00001014// Bits used in the next function
1015static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1016
1017
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001018// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1019// visible target links (and recursively their such links) into this graph.
1020// NodeCache maps the node being cloned to its clone in the Globals graph,
1021// in order to track cycles.
1022// GlobalsAreFinal is a flag that says whether it is safe to assume that
1023// an existing global node is complete. This is important to avoid
1024// reinserting all globals when inserting Calls to functions.
1025// This is a helper function for cloneGlobals and cloneCalls.
1026//
1027DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1028 std::map<const DSNode*, DSNode*> &NodeCache,
1029 bool GlobalsAreFinal) {
1030 if (OldNode == 0) return 0;
1031
1032 // The caller should check this is an external node. Just more efficient...
1033 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1034
1035 // If a clone has already been created for OldNode, return it.
1036 DSNode*& CacheEntry = NodeCache[OldNode];
1037 if (CacheEntry != 0)
1038 return CacheEntry;
1039
1040 // The result value...
1041 DSNode* NewNode = 0;
1042
1043 // If nodes already exist for any of the globals of OldNode,
1044 // merge all such nodes together since they are merged in OldNode.
1045 // If ValueCacheIsFinal==true, look for an existing node that has
1046 // an identical list of globals and return it if it exists.
1047 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001048 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001049 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001050 if (NewNode == 0) {
1051 NewNode = PrevNode; // first existing node found
1052 if (GlobalsAreFinal && j == 0)
1053 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1054 CacheEntry = NewNode;
1055 return NewNode;
1056 }
1057 }
1058 else if (NewNode != PrevNode) { // found another, different from prev
1059 // update ValMap *before* merging PrevNode into NewNode
1060 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
Chris Lattnerc875f022002-11-03 21:27:48 +00001061 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001062 NewNode->mergeWith(PrevNode);
1063 }
1064 } else if (NewNode != 0) {
Chris Lattnerc875f022002-11-03 21:27:48 +00001065 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001066 }
1067
1068 // If no existing node was found, clone the node and update the ValMap.
1069 if (NewNode == 0) {
1070 NewNode = new DSNode(*OldNode);
1071 Nodes.push_back(NewNode);
1072 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1073 NewNode->setLink(j, 0);
1074 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001075 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001076 }
1077 else
1078 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1079
1080 // Add the entry to NodeCache
1081 CacheEntry = NewNode;
1082
1083 // Rewrite the links in the new node to point into the current graph,
1084 // but only for links to external nodes. Set other links to NULL.
1085 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1086 DSNode* OldTarget = OldNode->getLink(j);
1087 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1088 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1089 if (NewNode->getLink(j))
1090 NewNode->getLink(j)->mergeWith(NewLink);
1091 else
1092 NewNode->setLink(j, NewLink);
1093 }
1094 }
1095
1096 // Remove all local markers
1097 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1098
1099 return NewNode;
1100}
1101
1102
1103// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1104// visible target links (and recursively their such links) into this graph.
1105//
1106void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1107 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001108#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001109 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1110 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1111 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001112 if (CloneCalls)
1113 GlobalsGraph->cloneCalls(Graph);
1114
1115 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001116#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001117}
1118
1119
1120// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1121// links (and recursively their such links) into this graph.
1122//
1123void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1124 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001125 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001126
1127 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1128
1129 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001130 DSCallSite& callCopy = FunctionCalls.back();
1131 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001132 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001133 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001134 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1135 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1136 : 0);
1137 }
1138
1139 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001140 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001141}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001142#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001143
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001144#endif