blob: 356736289c000ffb3e1d8617bbc7324d58f19d8a [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/BasicBlock.h"
10#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000011#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000012#include "llvm/Target/TargetData.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000013#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000014#include "Support/Statistic.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000015#include <algorithm>
Chris Lattnerfccd06f2002-10-01 22:33:50 +000016#include <set>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017
Chris Lattnere2219762002-07-18 18:22:40 +000018using std::vector;
19
Chris Lattnerfccd06f2002-10-01 22:33:50 +000020// TODO: FIXME
21namespace DataStructureAnalysis {
22 // isPointerType - Return true if this first class type is big enough to hold
23 // a pointer.
24 //
25 bool isPointerType(const Type *Ty);
26 extern TargetData TD;
27}
28using namespace DataStructureAnalysis;
29
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000030//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000031// DSNode Implementation
32//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000033
Chris Lattnerfccd06f2002-10-01 22:33:50 +000034DSNode::DSNode(enum NodeTy NT, const Type *T) : NodeType(NT) {
35 // If this node is big enough to have pointer fields, add space for them now.
Chris Lattner7b7200c2002-10-02 04:57:39 +000036 if (T != Type::VoidTy && !isa<FunctionType>(T)) { // Avoid TargetData assert's
37 MergeMap.resize(TD.getTypeSize(T));
38
39 // Assign unique values to all of the elements of MergeMap
40 if (MergeMap.size() < 128) {
41 // Handle the common case of reasonable size structures...
42 for (unsigned i = 0, e = MergeMap.size(); i != e; ++i)
43 MergeMap[i] = -1-i; // Assign -1, -2, -3, ...
44 } else {
45 // It's possible that we have something really big here. In this case,
46 // divide the object into chunks until it will fit into 128 elements.
47 unsigned Multiple = MergeMap.size()/128;
48
49 // It's probably an array, and probably some power of two in size.
50 // Because of this, find the biggest power of two that is bigger than
51 // multiple to use as our real Multiple.
52 unsigned RealMultiple = 2;
Chris Lattner62d928e2002-10-03 21:06:38 +000053 while (RealMultiple <= Multiple) RealMultiple <<= 1;
Chris Lattner7b7200c2002-10-02 04:57:39 +000054
55 unsigned RealBound = MergeMap.size()/RealMultiple;
56 assert(RealBound <= 128 && "Math didn't work out right");
57
58 // Now go through and assign indexes that are between -1 and -128
59 // inclusive
60 //
61 for (unsigned i = 0, e = MergeMap.size(); i != e; ++i)
62 MergeMap[i] = -1-(i % RealBound); // Assign -1, -2, -3...
63 }
64 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +000065
Chris Lattnera3f85862002-10-18 18:22:46 +000066 TypeEntries.push_back(TypeRec(T, 0));
Chris Lattnerc68c31b2002-07-10 22:38:08 +000067}
68
Chris Lattner0d9bab82002-07-18 00:12:30 +000069// DSNode copy constructor... do not copy over the referrers list!
70DSNode::DSNode(const DSNode &N)
Chris Lattner7b7200c2002-10-02 04:57:39 +000071 : Links(N.Links), MergeMap(N.MergeMap),
Chris Lattnerfccd06f2002-10-01 22:33:50 +000072 TypeEntries(N.TypeEntries), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000073}
74
Chris Lattnerc68c31b2002-07-10 22:38:08 +000075void DSNode::removeReferrer(DSNodeHandle *H) {
76 // Search backwards, because we depopulate the list from the back for
77 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000078 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000079 std::find(Referrers.rbegin(), Referrers.rend(), H);
80 assert(I != Referrers.rend() && "Referrer not pointing to node!");
81 Referrers.erase(I.base()-1);
82}
83
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000084// addGlobal - Add an entry for a global value to the Globals list. This also
85// marks the node with the 'G' flag if it does not already have it.
86//
87void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000088 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000089 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000090 std::lower_bound(Globals.begin(), Globals.end(), GV);
91
92 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000093 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000094 Globals.insert(I, GV);
95 NodeType |= GlobalNode;
96 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000097}
98
99
Chris Lattner7b7200c2002-10-02 04:57:39 +0000100/// setLink - Set the link at the specified offset to the specified
101/// NodeHandle, replacing what was there. It is uncommon to use this method,
102/// instead one of the higher level methods should be used, below.
103///
104void DSNode::setLink(unsigned i, const DSNodeHandle &NH) {
105 // Create a new entry in the Links vector to hold a new element for offset.
106 if (!hasLink(i)) {
107 signed char NewIdx = Links.size();
108 // Check to see if we allocate more than 128 distinct links for this node.
109 // If so, just merge with the last one. This really shouldn't ever happen,
110 // but it should work regardless of whether it does or not.
111 //
112 if (NewIdx >= 0) {
113 Links.push_back(NH); // Allocate space: common case
114 } else { // Wrap around? Too many links?
115 NewIdx--; // Merge with whatever happened last
116 assert(NewIdx > 0 && "Should wrap back around");
117 std::cerr << "\n*** DSNode found that requires more than 128 "
118 << "active links at once!\n\n";
119 }
120
121 signed char OldIdx = MergeMap[i];
122 assert (OldIdx < 0 && "Shouldn't contain link!");
123
124 // Make sure that anything aliasing this field gets updated to point to the
125 // new link field.
126 rewriteMergeMap(OldIdx, NewIdx);
127 assert(MergeMap[i] == NewIdx && "Field not replaced!");
128 } else {
129 Links[MergeMap[i]] = NH;
130 }
131}
132
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000133// addEdgeTo - Add an edge from the current node to the specified node. This
134// can cause merging of nodes in the graph.
135//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000136void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000137 assert(Offset < getSize() && "Offset out of range!");
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000138 if (NH.getNode() == 0) return; // Nothing to do
139
Chris Lattner7b7200c2002-10-02 04:57:39 +0000140 if (DSNodeHandle *ExistingNH = getLink(Offset)) {
141 // Merge the two nodes...
142 ExistingNH->mergeWith(NH);
143 } else { // No merging to perform...
144 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000145 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000146}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000147
Chris Lattner7b7200c2002-10-02 04:57:39 +0000148/// mergeMappedValues - This is the higher level form of rewriteMergeMap. It is
149/// fully capable of merging links together if neccesary as well as simply
150/// rewriting the map entries.
151///
152void DSNode::mergeMappedValues(signed char V1, signed char V2) {
153 assert(V1 != V2 && "Cannot merge two identical mapped values!");
154
155 if (V1 < 0) { // If there is no outgoing link from V1, merge it with V2
156 if (V2 < 0 && V1 > V2)
157 // If both are not linked, merge to the field closer to 0
158 rewriteMergeMap(V2, V1);
159 else
160 rewriteMergeMap(V1, V2);
161 } else if (V2 < 0) { // Is V2 < 0 && V1 >= 0?
162 rewriteMergeMap(V2, V1); // Merge into the one with the link...
163 } else { // Otherwise, links exist at both locations
164 // Merge Links[V1] with Links[V2] so they point to the same place now...
165 Links[V1].mergeWith(Links[V2]);
166
167 // Merge the V2 link into V1 so that we reduce the overall value of the
168 // links are reduced...
169 //
170 if (V2 < V1) std::swap(V1, V2); // Ensure V1 < V2
171 rewriteMergeMap(V2, V1); // After this, V2 is "dead"
172
173 // Change the user of the last link to use V2 instead
174 if ((unsigned)V2 != Links.size()-1) {
175 rewriteMergeMap(Links.size()-1, V2); // Point to V2 instead of last el...
176 // Make sure V2 points the right DSNode
177 Links[V2] = Links.back();
178 }
179
180 // Reduce the number of distinct outgoing links...
181 Links.pop_back();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000182 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000183}
184
185
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000186// MergeSortedVectors - Efficiently merge a vector into another vector where
187// duplicates are not allowed and both are sorted. This assumes that 'T's are
188// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000189//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000190template<typename T>
191void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
192 // By far, the most common cases will be the simple ones. In these cases,
193 // avoid having to allocate a temporary vector...
194 //
195 if (Src.empty()) { // Nothing to merge in...
196 return;
197 } else if (Dest.empty()) { // Just copy the result in...
198 Dest = Src;
199 } else if (Src.size() == 1) { // Insert a single element...
200 const T &V = Src[0];
201 typename vector<T>::iterator I =
202 std::lower_bound(Dest.begin(), Dest.end(), V);
203 if (I == Dest.end() || *I != Src[0]) // If not already contained...
204 Dest.insert(I, Src[0]);
205 } else if (Dest.size() == 1) {
206 T Tmp = Dest[0]; // Save value in temporary...
207 Dest = Src; // Copy over list...
208 typename vector<T>::iterator I =
209 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
210 if (I == Dest.end() || *I != Src[0]) // If not already contained...
211 Dest.insert(I, Src[0]);
212
213 } else {
214 // Make a copy to the side of Dest...
215 vector<T> Old(Dest);
216
217 // Make space for all of the type entries now...
218 Dest.resize(Dest.size()+Src.size());
219
220 // Merge the two sorted ranges together... into Dest.
221 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
222
223 // Now erase any duplicate entries that may have accumulated into the
224 // vectors (because they were in both of the input sets)
225 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
226 }
227}
228
229
230// mergeWith - Merge this node and the specified node, moving all links to and
231// from the argument node into the current node, deleting the node argument.
232// Offset indicates what offset the specified node is to be merged into the
233// current node.
234//
235// The specified node may be a null pointer (in which case, nothing happens).
236//
237void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
238 DSNode *N = NH.getNode();
239 if (N == 0 || (N == this && NH.getOffset() == Offset))
240 return; // Noop
241
242 assert(NH.getNode() != this &&
243 "Cannot merge two portions of the same node yet!");
244
245 // If both nodes are not at offset 0, make sure that we are merging the node
246 // at an later offset into the node with the zero offset.
247 //
248 if (Offset > NH.getOffset()) {
249 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
250 return;
251 }
252
253#if 0
254 std::cerr << "\n\nMerging:\n";
255 N->print(std::cerr, 0);
256 std::cerr << " and:\n";
257 print(std::cerr, 0);
258#endif
259
260 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
261 // respect to NH.Offset) is now zero.
262 //
263 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000264
Chris Lattner7b7200c2002-10-02 04:57:39 +0000265 unsigned NSize = N->getSize();
266 assert(NSize+NOffset <= getSize() &&
267 "Don't know how to merge extend a merged nodes size yet!");
268
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000269 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000270 // Make sure to adjust their offset, not just the node pointer.
271 //
272 while (!N->Referrers.empty()) {
273 DSNodeHandle &Ref = *N->Referrers.back();
274 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
275 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000276
Chris Lattner7b7200c2002-10-02 04:57:39 +0000277 // We must merge fields in this node due to nodes merged in the source node.
278 // In order to handle this we build a map that converts from the source node's
279 // MergeMap values to our MergeMap values. This map is indexed by the
280 // expression: MergeMap[SMM+SourceNodeSize] so we need to allocate at least
281 // 2*SourceNodeSize elements of space for the mapping. We can do this because
282 // we know that there are at most SourceNodeSize outgoing links in the node
283 // (thus that many positive values) and at most SourceNodeSize distinct fields
284 // (thus that many negative values).
285 //
286 std::vector<signed char> MergeMapMap(NSize*2, 127);
287
288 // Loop through the structures, merging them together...
289 for (unsigned i = 0, e = NSize; i != e; ++i) {
290 // Get what this byte of N maps to...
291 signed char NElement = N->MergeMap[i];
292
293 // Get what we map this byte to...
294 signed char Element = MergeMap[i+NOffset];
295 // We use 127 as a sentinal and don't check for it's existence yet...
296 assert(Element != 127 && "MergeMapMap doesn't permit 127 values yet!");
297
298 signed char CurMappedVal = MergeMapMap[NElement+NSize];
299 if (CurMappedVal == 127) { // Haven't seen this NElement yet?
300 MergeMapMap[NElement+NSize] = Element; // Map the two together...
301 } else if (CurMappedVal != Element) {
302 // If we are mapping two different fields together this means that we need
303 // to merge fields in the current node due to merging in the source node.
304 //
305 mergeMappedValues(CurMappedVal, Element);
306 MergeMapMap[NElement+NSize] = MergeMap[i+NOffset];
307 }
308 }
309
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000310 // Make all of the outgoing links of N now be outgoing links of this. This
311 // can cause recursive merging!
312 //
Chris Lattner7b7200c2002-10-02 04:57:39 +0000313 for (unsigned i = 0, e = NSize; i != e; ++i)
314 if (DSNodeHandle *Link = N->getLink(i)) {
315 addEdgeTo(i+NOffset, *Link);
316 N->MergeMap[i] = -1; // Kill outgoing edge
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000317 }
318
319 // Now that there are no outgoing edges, all of the Links are dead.
320 N->Links.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000321
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000322 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000323 NodeType |= N->NodeType;
324 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000325
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000326 // If this merging into node has more than just void nodes in it, merge!
327 assert(!N->TypeEntries.empty() && "TypeEntries is empty for a node?");
Chris Lattnera3f85862002-10-18 18:22:46 +0000328 if (N->TypeEntries.size() != 1 || N->TypeEntries[0].Ty != Type::VoidTy) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000329 // If the current node just has a Void entry in it, remove it.
Chris Lattnera3f85862002-10-18 18:22:46 +0000330 if (TypeEntries.size() == 1 && TypeEntries[0].Ty == Type::VoidTy)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000331 TypeEntries.clear();
332
333 // Adjust all of the type entries we are merging in by the offset... and add
334 // them to the TypeEntries list.
335 //
336 if (NOffset != 0) { // This case is common enough to optimize for
337 // Offset all of the TypeEntries in N with their new offset
338 for (unsigned i = 0, e = N->TypeEntries.size(); i != e; ++i)
Chris Lattnera3f85862002-10-18 18:22:46 +0000339 N->TypeEntries[i].Offset += NOffset;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000340 }
341
342 MergeSortedVectors(TypeEntries, N->TypeEntries);
343
344 N->TypeEntries.clear();
345 }
346
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000347 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000348 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000349 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000350
351 // Delete the globals from the old node...
352 N->Globals.clear();
353 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000354}
355
Vikram S. Adve26b98262002-10-20 21:41:02 +0000356// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
357Function& DSCallSite::getCaller() const {
358 return * callInst->getParent()->getParent();
359}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000360
361template<typename _CopierFunction>
362DSCallSite::DSCallSite(const DSCallSite& FromCall,
363 _CopierFunction nodeCopier)
364 : std::vector<DSNodeHandle>(),
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000365 callInst(&FromCall.getCallInst()) {
366
367 reserve(FromCall.size());
368 for (unsigned j = 0, ej = FromCall.size(); j != ej; ++j)
369 push_back((&nodeCopier == (_CopierFunction*) 0)? DSNodeHandle(FromCall[j])
370 : nodeCopier(&FromCall[j]));
371}
372
373
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000374//===----------------------------------------------------------------------===//
375// DSGraph Implementation
376//===----------------------------------------------------------------------===//
377
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000378DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
379 std::map<const DSNode*, DSNode*> NodeMap;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000380 RetNode = cloneInto(G, ValueMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000381}
382
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000383DSGraph::~DSGraph() {
384 FunctionCalls.clear();
385 ValueMap.clear();
386 RetNode = 0;
387
388#ifndef NDEBUG
389 // Drop all intra-node references, so that assertions don't fail...
390 std::for_each(Nodes.begin(), Nodes.end(),
391 std::mem_fun(&DSNode::dropAllReferences));
392#endif
393
394 // Delete all of the nodes themselves...
395 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
396}
397
Chris Lattner0d9bab82002-07-18 00:12:30 +0000398// dump - Allow inspection of graph in a debugger.
399void DSGraph::dump() const { print(std::cerr); }
400
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000401
Chris Lattnere80fe612002-10-20 20:39:31 +0000402static DSNodeHandle copyHelper(const DSNodeHandle* fromNode,
403 std::map<const DSNode*, DSNode*> *NodeMap) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000404 return DSNodeHandle((*NodeMap)[fromNode->getNode()], fromNode->getOffset());
405}
406
407// Helper function used to clone a function list.
408//
409static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
410 vector<DSCallSite> &toCalls,
411 std::map<const DSNode*, DSNode*> &NodeMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000412 unsigned FC = toCalls.size(); // FirstCall
413 toCalls.reserve(FC+fromCalls.size());
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000414 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
415 toCalls.push_back(DSCallSite(fromCalls[i],
416 std::bind2nd(std::ptr_fun(&copyHelper), &NodeMap)));
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000417}
418
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000419/// remapLinks - Change all of the Links in the current node according to the
420/// specified mapping.
421void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
422 for (unsigned i = 0, e = Links.size(); i != e; ++i)
423 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
424}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000425
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000426
Chris Lattner0d9bab82002-07-18 00:12:30 +0000427// cloneInto - Clone the specified DSGraph into the current graph, returning the
428// Return node of the graph. The translated ValueMap for the old function is
429// filled into the OldValMap member. If StripLocals is set to true, Scalar and
430// Alloca markers are removed from the graph, as the graph is being cloned into
431// a calling function's graph.
432//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000433DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
434 std::map<Value*, DSNodeHandle> &OldValMap,
435 std::map<const DSNode*, DSNode*> &OldNodeMap,
436 bool StripScalars, bool StripAllocas,
437 bool CopyCallers, bool CopyOrigCalls) {
438 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000439
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000440 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000441
442 // Duplicate all of the nodes, populating the node map...
443 Nodes.reserve(FN+G.Nodes.size());
444 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000445 DSNode *Old = G.Nodes[i];
446 DSNode *New = new DSNode(*Old);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000447 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000448 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000449 }
450
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000451 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000452 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000453 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000454
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000455 // Remove local markers as specified
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000456 unsigned char StripBits = (StripScalars ? DSNode::ScalarNode : 0) |
457 (StripAllocas ? DSNode::AllocaNode : 0);
458 if (StripBits)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000459 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000460 Nodes[i]->NodeType &= ~StripBits;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000461
Chris Lattnercf15db32002-10-17 20:09:52 +0000462 // Copy the value map... and merge all of the global nodes...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000463 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
Chris Lattnercf15db32002-10-17 20:09:52 +0000464 E = G.ValueMap.end(); I != E; ++I) {
465 DSNodeHandle &H = OldValMap[I->first];
466 H = DSNodeHandle(OldNodeMap[I->second.getNode()], I->second.getOffset());
467
468 if (isa<GlobalValue>(I->first)) { // Is this a global?
469 std::map<Value*, DSNodeHandle>::iterator GVI = ValueMap.find(I->first);
470 if (GVI != ValueMap.end()) { // Is the global value in this fun already?
471 GVI->second.mergeWith(H);
472 } else {
473 ValueMap[I->first] = H; // Add global pointer to this graph
474 }
475 }
476 }
Chris Lattnere2219762002-07-18 18:22:40 +0000477 // Copy the function calls list...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000478 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000479
Chris Lattnercf15db32002-10-17 20:09:52 +0000480
Chris Lattner0d9bab82002-07-18 00:12:30 +0000481 // Return the returned node pointer...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000482 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000483}
484
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000485#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000486// cloneGlobalInto - Clone the given global node and all its target links
487// (and all their llinks, recursively).
488//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000489DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000490 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
491
492 // If a clone has already been created for GNode, return it.
493 DSNodeHandle& ValMapEntry = ValueMap[GNode->getGlobals()[0]];
494 if (ValMapEntry != 0)
495 return ValMapEntry;
496
497 // Clone the node and update the ValMap.
498 DSNode* NewNode = new DSNode(*GNode);
499 ValMapEntry = NewNode; // j=0 case of loop below!
500 Nodes.push_back(NewNode);
501 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
502 ValueMap[NewNode->getGlobals()[j]] = NewNode;
503
504 // Rewrite the links in the new node to point into the current graph.
505 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
506 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
507
508 return NewNode;
509}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000510#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000511
512
Chris Lattner0d9bab82002-07-18 00:12:30 +0000513// markIncompleteNodes - Mark the specified node as having contents that are not
514// known with the current analysis we have performed. Because a node makes all
515// of the nodes it can reach imcomplete if the node itself is incomplete, we
516// must recursively traverse the data structure graph, marking all reachable
517// nodes as incomplete.
518//
519static void markIncompleteNode(DSNode *N) {
520 // Stop recursion if no node, or if node already marked...
521 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
522
523 // Actually mark the node
524 N->NodeType |= DSNode::Incomplete;
525
526 // Recusively process children...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000527 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
528 if (DSNodeHandle *DSNH = N->getLink(i))
529 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000530}
531
532
533// markIncompleteNodes - Traverse the graph, identifying nodes that may be
534// modified by other functions that have not been resolved yet. This marks
535// nodes that are reachable through three sources of "unknownness":
536//
537// Global Variables, Function Calls, and Incoming Arguments
538//
539// For any node that may have unknown components (because something outside the
540// scope of current analysis may have modified it), the 'Incomplete' flag is
541// added to the NodeType.
542//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000543void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000544 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000545 if (markFormalArgs && Func)
546 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
547 if (isPointerType(I->getType()) && ValueMap.find(I) != ValueMap.end()) {
548 DSNodeHandle &INH = ValueMap[I];
549 if (INH.getNode() && INH.hasLink(0))
550 markIncompleteNode(ValueMap[I].getLink(0)->getNode());
551 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000552
553 // Mark stuff passed into functions calls as being incomplete...
554 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve26b98262002-10-20 21:41:02 +0000555 DSCallSite &Call = FunctionCalls[i];
Chris Lattnere2219762002-07-18 18:22:40 +0000556 // Then the return value is certainly incomplete!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000557 markIncompleteNode(Call.getReturnValueNode().getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000558
559 // The call does not make the function argument incomplete...
560
561 // All arguments to the function call are incomplete though!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000562 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
563 markIncompleteNode(Call.getPtrArgNode(i).getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000564 }
565
Chris Lattner055dc2c2002-07-18 15:54:42 +0000566 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000567 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000568 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000569 DSNode *N = Nodes[i];
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000570 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
571 if (DSNodeHandle *DSNH = N->getLink(i))
572 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000573 }
574}
575
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000576// removeRefsToGlobal - Helper function that removes globals from the
577// ValueMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000578static void removeRefsToGlobal(DSNode* N,
579 std::map<Value*, DSNodeHandle> &ValueMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000580 while (!N->getGlobals().empty()) {
581 GlobalValue *GV = N->getGlobals().back();
582 N->getGlobals().pop_back();
583 ValueMap.erase(GV);
584 }
585}
586
587
Chris Lattner0d9bab82002-07-18 00:12:30 +0000588// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
589// checks to see if there are simple transformations that it can do to make it
590// dead.
591//
592bool DSGraph::isNodeDead(DSNode *N) {
593 // Is it a trivially dead shadow node...
594 if (N->getReferrers().empty() && N->NodeType == 0)
595 return true;
596
597 // Is it a function node or some other trivially unused global?
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000598 if (N->NodeType != 0 &&
599 (N->NodeType & ~DSNode::GlobalNode) == 0 &&
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000600 N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000601 N->getReferrers().size() == N->getGlobals().size()) {
602
Chris Lattnera00397e2002-10-03 21:55:28 +0000603 // Remove the globals from the ValueMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000604 // down to zero.
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000605 removeRefsToGlobal(N, ValueMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000606 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
607 return true;
608 }
609
610 return false;
611}
612
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000613static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000614 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000615 // Remove trivially identical function calls
616 unsigned NumFns = Calls.size();
617 std::sort(Calls.begin(), Calls.end());
618 Calls.erase(std::unique(Calls.begin(), Calls.end()),
619 Calls.end());
620
621 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000622 std::cerr << "Merged " << (NumFns-Calls.size())
623 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000624}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000625
Chris Lattnere2219762002-07-18 18:22:40 +0000626// removeTriviallyDeadNodes - After the graph has been constructed, this method
627// removes all unreachable nodes that are created because they got merged with
628// other nodes in the graph. These nodes will all be trivially unreachable, so
629// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000630//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000631void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000632 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000633 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000634 if (isNodeDead(Nodes[i])) { // This node is dead!
635 delete Nodes[i]; // Free memory...
636 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
637 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000638
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000639 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000640}
641
642
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000643// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000644// stuff to be alive.
645//
646static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000647 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000648
649 Alive.insert(N);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000650 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
651 if (DSNodeHandle *DSNH = N->getLink(i))
652 if (!Alive.count(DSNH->getNode()))
653 markAlive(DSNH->getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000654}
655
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000656static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
657 std::set<DSNode*> &Visiting) {
658 if (N == 0) return false;
659
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000660 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000661 Visiting.insert(N);
662
663 // If any immediate successor is alive, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000664 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
665 if (DSNodeHandle *DSNH = N->getLink(i))
666 if (Alive.count(DSNH->getNode())) {
667 Visiting.erase(N);
668 return true;
669 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000670
671 // Else if any successor reaches a live node, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000672 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
673 if (DSNodeHandle *DSNH = N->getLink(i))
674 if (checkGlobalAlive(DSNH->getNode(), Alive, Visiting)) {
675 Visiting.erase(N); return true;
676 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000677
678 Visiting.erase(N);
679 return false;
680}
681
682
683// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
684// This would be unnecessary if function calls were real nodes! In that case,
685// the simple iterative loop in the first few lines below suffice.
686//
687static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000688 vector<DSCallSite> &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000689 std::set<DSNode*> &Alive,
690 bool FilterCalls) {
691
692 // Iterate, marking globals or cast nodes alive until no new live nodes
693 // are added to Alive
694 std::set<DSNode*> Visiting; // Used to identify cycles
695 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
696 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
697 liveCount = Alive.size();
698 for ( ; I != E; ++I)
699 if (Alive.count(*I) == 0) {
700 Visiting.clear();
701 if (checkGlobalAlive(*I, Alive, Visiting))
702 markAlive(*I, Alive);
703 }
704 }
705
706 // Find function calls with some dead and some live nodes.
707 // Since all call nodes must be live if any one is live, we have to mark
708 // all nodes of the call as live and continue the iteration (via recursion).
709 if (FilterCalls) {
710 bool recurse = false;
711 for (int i = 0, ei = Calls.size(); i < ei; ++i) {
712 bool CallIsDead = true, CallHasDeadArg = false;
713 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000714 bool argIsDead = Calls[i][j].getNode() == 0 ||
715 Alive.count(Calls[i][j].getNode()) == 0;
716 CallHasDeadArg |= (Calls[i][j].getNode() != 0 && argIsDead);
717 CallIsDead &= argIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000718 }
719 if (!CallIsDead && CallHasDeadArg) {
720 // Some node in this call is live and another is dead.
721 // Mark all nodes of call as live and iterate once more.
722 recurse = true;
723 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000724 markAlive(Calls[i][j].getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000725 }
726 }
727 if (recurse)
728 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
729 }
730}
731
732
733// markGlobalsAlive - Mark global nodes and cast nodes alive if they
734// can reach any other live node. Since this can produce new live nodes,
735// we use a simple iterative algorithm.
736//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000737static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000738 bool FilterCalls) {
739 // Add global and cast nodes to a set so we don't walk all nodes every time
740 std::set<DSNode*> GlobalNodes;
741 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000742 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000743 GlobalNodes.insert(G.getNodes()[i]);
744
745 // Add all call nodes to the same set
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000746 vector<DSCallSite> &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000747 if (FilterCalls) {
748 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
749 for (unsigned j = 0, e = Calls[i].size(); j != e; ++j)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000750 if (Calls[i][j].getNode())
751 GlobalNodes.insert(Calls[i][j].getNode());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000752 }
753
754 // Iterate and recurse until no new live node are discovered.
755 // This would be a simple iterative loop if function calls were real nodes!
756 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
757
758 // Free up references to dead globals from the ValueMap
759 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
760 for( ; I != E; ++I)
761 if (Alive.count(*I) == 0)
762 removeRefsToGlobal(*I, G.getValueMap());
763
764 // Delete dead function calls
765 if (FilterCalls)
766 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
767 bool CallIsDead = true;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000768 for (unsigned j = 0, ej = Calls[i].size(); CallIsDead && j != ej; ++j)
769 CallIsDead = Alive.count(Calls[i][j].getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000770 if (CallIsDead)
771 Calls.erase(Calls.begin() + i); // remove the call entirely
772 }
773}
Chris Lattnere2219762002-07-18 18:22:40 +0000774
775// removeDeadNodes - Use a more powerful reachability analysis to eliminate
776// subgraphs that are unreachable. This often occurs because the data
777// structure doesn't "escape" into it's caller, and thus should be eliminated
778// from the caller's graph entirely. This is only appropriate to use when
779// inlining graphs.
780//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000781void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
782 assert((!KeepAllGlobals || KeepCalls) &&
783 "KeepAllGlobals without KeepCalls is meaningless");
784
Chris Lattnere2219762002-07-18 18:22:40 +0000785 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000786 removeTriviallyDeadNodes(KeepAllGlobals);
787
Chris Lattnere2219762002-07-18 18:22:40 +0000788 // FIXME: Merge nontrivially identical call nodes...
789
790 // Alive - a set that holds all nodes found to be reachable/alive.
791 std::set<DSNode*> Alive;
792
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000793 // If KeepCalls, mark all nodes reachable by call nodes as alive...
794 if (KeepCalls)
795 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
796 for (unsigned j = 0, e = FunctionCalls[i].size(); j != e; ++j)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000797 markAlive(FunctionCalls[i][j].getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000798
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000799#if 0
Chris Lattnere2219762002-07-18 18:22:40 +0000800 for (unsigned i = 0, e = OrigFunctionCalls.size(); i != e; ++i)
801 for (unsigned j = 0, e = OrigFunctionCalls[i].size(); j != e; ++j)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000802 markAlive(OrigFunctionCalls[i][j].getNode(), Alive);
803#endif
Chris Lattnere2219762002-07-18 18:22:40 +0000804
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000805 // Mark all nodes reachable by scalar nodes (and global nodes, if
806 // keeping them was specified) as alive...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000807 unsigned char keepBits = DSNode::ScalarNode |
808 (KeepAllGlobals ? DSNode::GlobalNode : 0);
Chris Lattnere2219762002-07-18 18:22:40 +0000809 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000810 if (Nodes[i]->NodeType & keepBits)
Chris Lattnere2219762002-07-18 18:22:40 +0000811 markAlive(Nodes[i], Alive);
812
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000813 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000814 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000815
816 // Mark all globals or cast nodes that can reach a live node as alive.
817 // This also marks all nodes reachable from such nodes as alive.
818 // Of course, if KeepAllGlobals is specified, they would be live already.
819 if (! KeepAllGlobals)
820 markGlobalsAlive(*this, Alive, ! KeepCalls);
821
Chris Lattnere2219762002-07-18 18:22:40 +0000822 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000823 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000824 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
825 for (unsigned i = 0; i != Nodes.size(); ++i)
826 if (!Alive.count(Nodes[i])) {
827 DSNode *N = Nodes[i];
828 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
829 DeadNodes.push_back(N); // Add node to our list of dead nodes
830 N->dropAllReferences(); // Drop all outgoing edges
831 }
832
Chris Lattnere2219762002-07-18 18:22:40 +0000833 // Delete all dead nodes...
834 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
835}
836
837
838
Chris Lattner0d9bab82002-07-18 00:12:30 +0000839// maskNodeTypes - Apply a mask to all of the node types in the graph. This
840// is useful for clearing out markers like Scalar or Incomplete.
841//
842void DSGraph::maskNodeTypes(unsigned char Mask) {
843 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
844 Nodes[i]->NodeType &= Mask;
845}
846
847
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000848#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000849//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000850// GlobalDSGraph Implementation
851//===----------------------------------------------------------------------===//
852
853GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
854}
855
856GlobalDSGraph::~GlobalDSGraph() {
857 assert(Referrers.size() == 0 &&
858 "Deleting global graph while references from other graphs exist");
859}
860
861void GlobalDSGraph::addReference(const DSGraph* referrer) {
862 if (referrer != this)
863 Referrers.insert(referrer);
864}
865
866void GlobalDSGraph::removeReference(const DSGraph* referrer) {
867 if (referrer != this) {
868 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
869 Referrers.erase(referrer);
870 if (Referrers.size() == 0)
871 delete this;
872 }
873}
874
875// Bits used in the next function
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000876static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000877
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000878#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000879// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
880// visible target links (and recursively their such links) into this graph.
881// NodeCache maps the node being cloned to its clone in the Globals graph,
882// in order to track cycles.
883// GlobalsAreFinal is a flag that says whether it is safe to assume that
884// an existing global node is complete. This is important to avoid
885// reinserting all globals when inserting Calls to functions.
886// This is a helper function for cloneGlobals and cloneCalls.
887//
888DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
889 std::map<const DSNode*, DSNode*> &NodeCache,
890 bool GlobalsAreFinal) {
891 if (OldNode == 0) return 0;
892
893 // The caller should check this is an external node. Just more efficient...
894 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
895
896 // If a clone has already been created for OldNode, return it.
897 DSNode*& CacheEntry = NodeCache[OldNode];
898 if (CacheEntry != 0)
899 return CacheEntry;
900
901 // The result value...
902 DSNode* NewNode = 0;
903
904 // If nodes already exist for any of the globals of OldNode,
905 // merge all such nodes together since they are merged in OldNode.
906 // If ValueCacheIsFinal==true, look for an existing node that has
907 // an identical list of globals and return it if it exists.
908 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000909 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
910 if (DSNode *PrevNode = ValueMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000911 if (NewNode == 0) {
912 NewNode = PrevNode; // first existing node found
913 if (GlobalsAreFinal && j == 0)
914 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
915 CacheEntry = NewNode;
916 return NewNode;
917 }
918 }
919 else if (NewNode != PrevNode) { // found another, different from prev
920 // update ValMap *before* merging PrevNode into NewNode
921 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
922 ValueMap[PrevNode->getGlobals()[k]] = NewNode;
923 NewNode->mergeWith(PrevNode);
924 }
925 } else if (NewNode != 0) {
926 ValueMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
927 }
928
929 // If no existing node was found, clone the node and update the ValMap.
930 if (NewNode == 0) {
931 NewNode = new DSNode(*OldNode);
932 Nodes.push_back(NewNode);
933 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
934 NewNode->setLink(j, 0);
935 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
936 ValueMap[NewNode->getGlobals()[j]] = NewNode;
937 }
938 else
939 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
940
941 // Add the entry to NodeCache
942 CacheEntry = NewNode;
943
944 // Rewrite the links in the new node to point into the current graph,
945 // but only for links to external nodes. Set other links to NULL.
946 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
947 DSNode* OldTarget = OldNode->getLink(j);
948 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
949 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
950 if (NewNode->getLink(j))
951 NewNode->getLink(j)->mergeWith(NewLink);
952 else
953 NewNode->setLink(j, NewLink);
954 }
955 }
956
957 // Remove all local markers
958 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
959
960 return NewNode;
961}
962
963
964// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
965// visible target links (and recursively their such links) into this graph.
966//
967void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
968 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000969#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000970 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
971 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
972 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000973 if (CloneCalls)
974 GlobalsGraph->cloneCalls(Graph);
975
976 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000977#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000978}
979
980
981// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
982// links (and recursively their such links) into this graph.
983//
984void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
985 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000986 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000987
988 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
989
990 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000991 DSCallSite& callCopy = FunctionCalls.back();
992 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000993 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000994 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000995 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
996 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
997 : 0);
998 }
999
1000 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001001 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001002}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001003#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001004
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001005#endif