blob: bf487d85d76c5d5b9f03810ef370a70d4487435d [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00002//
Chris Lattnerc68c31b2002-07-10 22:38:08 +00003// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00004//
5//===----------------------------------------------------------------------===//
6
Chris Lattnerfccd06f2002-10-01 22:33:50 +00007#include "llvm/Analysis/DSGraph.h"
8#include "llvm/Function.h"
Vikram S. Adve26b98262002-10-20 21:41:02 +00009#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000011#include "llvm/Target/TargetData.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000012#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000013#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000014#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000015#include <algorithm>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000016
Chris Lattner08db7192002-11-06 06:20:27 +000017namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000018 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
19 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000020};
21
Chris Lattnerb1060432002-11-07 05:20:53 +000022namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000023 extern TargetData TD;
24}
Chris Lattnerb1060432002-11-07 05:20:53 +000025using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000026
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000027//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000028// DSNode Implementation
29//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000030
Chris Lattner08db7192002-11-06 06:20:27 +000031DSNode::DSNode(enum NodeTy NT, const Type *T)
32 : Ty(Type::VoidTy), Size(0), NodeType(NT) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000033 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000034 if (T) mergeTypeInfo(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 Lattner08db7192002-11-06 06:20:27 +000039 : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size),
40 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 Lattnerb3416bc2003-02-01 04:01:21 +000046 std::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 Lattnerb3416bc2003-02-01 04:01:21 +000057 std::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() {
Chris Lattner08db7192002-11-06 06:20:27 +000073 if (isNodeCompletelyFolded()) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +000074
Chris Lattner08db7192002-11-06 06:20:27 +000075 ++NumFolds;
76
77 // We are no longer typed at all...
Chris Lattner18552922002-11-18 21:44:46 +000078 Ty = Type::VoidTy;
79 NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +000080 Size = 1;
81
82 // Loop over all of our referrers, making them point to our zero bytes of
83 // space.
Chris Lattnerb3416bc2003-02-01 04:01:21 +000084 for (std::vector<DSNodeHandle*>::iterator I = Referrers.begin(),
85 E = Referrers.end(); I != E; ++I)
Chris Lattner8f0a16e2002-10-31 05:45:02 +000086 (*I)->setOffset(0);
87
Chris Lattner8f0a16e2002-10-31 05:45:02 +000088 // If we have links, merge all of our outgoing links together...
Chris Lattner08db7192002-11-06 06:20:27 +000089 for (unsigned i = 1, e = Links.size(); i < e; ++i)
90 Links[0].mergeWith(Links[i]);
91 Links.resize(1);
Chris Lattner8f0a16e2002-10-31 05:45:02 +000092}
Chris Lattner076c1f92002-11-07 06:31:54 +000093
Chris Lattner8f0a16e2002-10-31 05:45:02 +000094/// isNodeCompletelyFolded - Return true if this node has been completely
95/// folded down to something that can never be expanded, effectively losing
96/// all of the field sensitivity that may be present in the node.
97///
98bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +000099 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000100}
101
102
Chris Lattner08db7192002-11-06 06:20:27 +0000103/// mergeTypeInfo - This method merges the specified type into the current node
104/// at the specified offset. This may update the current node's type record if
105/// this gives more information to the node, it may do nothing to the node if
106/// this information is already known, or it may merge the node completely (and
107/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000108///
Chris Lattner08db7192002-11-06 06:20:27 +0000109/// This method returns true if the node is completely folded, otherwise false.
110///
111bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
112 // Check to make sure the Size member is up-to-date. Size can be one of the
113 // following:
114 // Size = 0, Ty = Void: Nothing is known about this node.
115 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
116 // Size = 1, Ty = Void, Array = 1: The node is collapsed
117 // Otherwise, sizeof(Ty) = Size
118 //
Chris Lattner18552922002-11-18 21:44:46 +0000119 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
120 (Size == 0 && !Ty->isSized() && !isArray()) ||
121 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
122 (Size == 0 && !Ty->isSized() && !isArray()) ||
123 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000124 "Size member of DSNode doesn't match the type structure!");
125 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000126
Chris Lattner18552922002-11-18 21:44:46 +0000127 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000128 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000129
Chris Lattner08db7192002-11-06 06:20:27 +0000130 // Return true immediately if the node is completely folded.
131 if (isNodeCompletelyFolded()) return true;
132
Chris Lattner23f83dc2002-11-08 22:49:57 +0000133 // If this is an array type, eliminate the outside arrays because they won't
134 // be used anyway. This greatly reduces the size of large static arrays used
135 // as global variables, for example.
136 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000137 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000138 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
139 // FIXME: we might want to keep small arrays, but must be careful about
140 // things like: [2 x [10000 x int*]]
141 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000142 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000143 }
144
Chris Lattner08db7192002-11-06 06:20:27 +0000145 // Figure out how big the new type we're merging in is...
146 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
147
148 // Otherwise check to see if we can fold this type into the current node. If
149 // we can't, we fold the node completely, if we can, we potentially update our
150 // internal state.
151 //
Chris Lattner18552922002-11-18 21:44:46 +0000152 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000153 // If this is the first type that this node has seen, just accept it without
154 // question....
155 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000156 assert(!isArray() && "This shouldn't happen!");
157 Ty = NewTy;
158 NodeType &= ~Array;
159 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000160 Size = NewTySize;
161
162 // Calculate the number of outgoing links from this node.
163 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
164 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000165 }
Chris Lattner08db7192002-11-06 06:20:27 +0000166
167 // Handle node expansion case here...
168 if (Offset+NewTySize > Size) {
169 // It is illegal to grow this node if we have treated it as an array of
170 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000171 if (isArray()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000172 foldNodeCompletely();
173 return true;
174 }
175
176 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner3c87b292002-11-07 01:54:56 +0000177 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
178 << "offset != 0: Collapsing!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000179 foldNodeCompletely();
180 return true;
181 }
182
183 // Okay, the situation is nice and simple, we are trying to merge a type in
184 // at offset 0 that is bigger than our current type. Implement this by
185 // switching to the new type and then merge in the smaller one, which should
186 // hit the other code path here. If the other code path decides it's not
187 // ok, it will collapse the node as appropriate.
188 //
Chris Lattner18552922002-11-18 21:44:46 +0000189 const Type *OldTy = Ty;
190 Ty = NewTy;
191 NodeType &= ~Array;
192 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000193 Size = NewTySize;
194
195 // Must grow links to be the appropriate size...
196 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
197
198 // Merge in the old type now... which is guaranteed to be smaller than the
199 // "current" type.
200 return mergeTypeInfo(OldTy, 0);
201 }
202
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000203 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000204 "Cannot merge something into a part of our type that doesn't exist!");
205
Chris Lattner18552922002-11-18 21:44:46 +0000206 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000207 // type that starts at offset Offset.
208 //
209 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000210 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000211 while (O < Offset) {
212 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
213
214 switch (SubType->getPrimitiveID()) {
215 case Type::StructTyID: {
216 const StructType *STy = cast<StructType>(SubType);
217 const StructLayout &SL = *TD.getStructLayout(STy);
218
219 unsigned i = 0, e = SL.MemberOffsets.size();
220 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
221 /* empty */;
222
223 // The offset we are looking for must be in the i'th element...
224 SubType = STy->getElementTypes()[i];
225 O += SL.MemberOffsets[i];
226 break;
227 }
228 case Type::ArrayTyID: {
229 SubType = cast<ArrayType>(SubType)->getElementType();
230 unsigned ElSize = TD.getTypeSize(SubType);
231 unsigned Remainder = (Offset-O) % ElSize;
232 O = Offset-Remainder;
233 break;
234 }
235 default:
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000236 foldNodeCompletely();
237 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000238 }
239 }
240
241 assert(O == Offset && "Could not achieve the correct offset!");
242
243 // If we found our type exactly, early exit
244 if (SubType == NewTy) return false;
245
246 // Okay, so we found the leader type at the offset requested. Search the list
247 // of types that starts at this offset. If SubType is currently an array or
248 // structure, the type desired may actually be the first element of the
249 // composite type...
250 //
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000251 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
Chris Lattner18552922002-11-18 21:44:46 +0000252 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000253 while (SubType != NewTy) {
254 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000255 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000256 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000257 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000258 case Type::StructTyID: {
259 const StructType *STy = cast<StructType>(SubType);
260 const StructLayout &SL = *TD.getStructLayout(STy);
261 if (SL.MemberOffsets.size() > 1)
262 NextPadSize = SL.MemberOffsets[1];
263 else
264 NextPadSize = SubTypeSize;
265 NextSubType = STy->getElementTypes()[0];
266 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000267 break;
Chris Lattner18552922002-11-18 21:44:46 +0000268 }
Chris Lattner08db7192002-11-06 06:20:27 +0000269 case Type::ArrayTyID:
270 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000271 NextSubTypeSize = TD.getTypeSize(NextSubType);
272 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000273 break;
274 default: ;
275 // fall out
276 }
277
278 if (NextSubType == 0)
279 break; // In the default case, break out of the loop
280
Chris Lattner18552922002-11-18 21:44:46 +0000281 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000282 break; // Don't allow shrinking to a smaller type than NewTySize
283 SubType = NextSubType;
284 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000285 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000286 }
287
288 // If we found the type exactly, return it...
289 if (SubType == NewTy)
290 return false;
291
292 // Check to see if we have a compatible, but different type...
293 if (NewTySize == SubTypeSize) {
294 // Check to see if this type is obviously convertable... int -> uint f.e.
295 if (NewTy->isLosslesslyConvertableTo(SubType))
296 return false;
297
298 // Check to see if we have a pointer & integer mismatch going on here,
299 // loading a pointer as a long, for example.
300 //
301 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
302 NewTy->isInteger() && isa<PointerType>(SubType))
303 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000304 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
305 // We are accessing the field, plus some structure padding. Ignore the
306 // structure padding.
307 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000308 }
309
310
Chris Lattner18552922002-11-18 21:44:46 +0000311 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
Chris Lattner3c87b292002-11-07 01:54:56 +0000312 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
313 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000314
315 foldNodeCompletely();
316 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000317}
318
Chris Lattner08db7192002-11-06 06:20:27 +0000319
320
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000321// addEdgeTo - Add an edge from the current node to the specified node. This
322// can cause merging of nodes in the graph.
323//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000324void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000325 if (NH.getNode() == 0) return; // Nothing to do
326
Chris Lattner08db7192002-11-06 06:20:27 +0000327 DSNodeHandle &ExistingEdge = getLink(Offset);
328 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000329 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000330 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000331 } else { // No merging to perform...
332 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000333 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000334}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000335
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000336
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000337// MergeSortedVectors - Efficiently merge a vector into another vector where
338// duplicates are not allowed and both are sorted. This assumes that 'T's are
339// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000340//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000341static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
342 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000343 // By far, the most common cases will be the simple ones. In these cases,
344 // avoid having to allocate a temporary vector...
345 //
346 if (Src.empty()) { // Nothing to merge in...
347 return;
348 } else if (Dest.empty()) { // Just copy the result in...
349 Dest = Src;
350 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000351 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000352 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000353 std::lower_bound(Dest.begin(), Dest.end(), V);
354 if (I == Dest.end() || *I != Src[0]) // If not already contained...
355 Dest.insert(I, Src[0]);
356 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000357 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000358 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000359 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000360 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
361 if (I == Dest.end() || *I != Tmp) // If not already contained...
362 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000363
364 } else {
365 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000366 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000367
368 // Make space for all of the type entries now...
369 Dest.resize(Dest.size()+Src.size());
370
371 // Merge the two sorted ranges together... into Dest.
372 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
373
374 // Now erase any duplicate entries that may have accumulated into the
375 // vectors (because they were in both of the input sets)
376 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
377 }
378}
379
380
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000381// MergeNodes() - Helper function for DSNode::mergeWith().
382// This function does the hard work of merging two nodes, CurNodeH
383// and NH after filtering out trivial cases and making sure that
384// CurNodeH.offset >= NH.offset.
385//
386// ***WARNING***
387// Since merging may cause either node to go away, we must always
388// use the node-handles to refer to the nodes. These node handles are
389// automatically updated during merging, so will always provide access
390// to the correct node after a merge.
391//
392void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
393 assert(CurNodeH.getOffset() >= NH.getOffset() &&
394 "This should have been enforced in the caller.");
395
396 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
397 // respect to NH.Offset) is now zero. NOffset is the distance from the base
398 // of our object that N starts from.
399 //
400 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
401 unsigned NSize = NH.getNode()->getSize();
402
403 // Merge the type entries of the two nodes together...
404 if (NH.getNode()->Ty != Type::VoidTy) {
405 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
406 }
407 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
408
409 // If we are merging a node with a completely folded node, then both nodes are
410 // now completely folded.
411 //
412 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
413 if (!NH.getNode()->isNodeCompletelyFolded()) {
414 NH.getNode()->foldNodeCompletely();
415 assert(NH.getOffset()==0 && "folding did not make offset 0?");
416 NOffset = NH.getOffset();
417 NSize = NH.getNode()->getSize();
418 assert(NOffset == 0 && NSize == 1);
419 }
420 } else if (NH.getNode()->isNodeCompletelyFolded()) {
421 CurNodeH.getNode()->foldNodeCompletely();
422 assert(CurNodeH.getOffset()==0 && "folding did not make offset 0?");
423 NOffset = NH.getOffset();
424 NSize = NH.getNode()->getSize();
425 assert(NOffset == 0 && NSize == 1);
426 }
427
428 if (CurNodeH.getNode() == NH.getNode() || NH.getNode() == 0) return;
429 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
430
431 // Remove all edges pointing at N, causing them to point to 'this' instead.
432 // Make sure to adjust their offset, not just the node pointer.
433 // Also, be careful to use the DSNode* rather than NH since NH is one of
434 // the referrers and once NH refers to CurNodeH.getNode() this will
435 // become an infinite loop.
436 DSNode* N = NH.getNode();
437 unsigned OldNHOffset = NH.getOffset();
438 while (!N->Referrers.empty()) {
439 DSNodeHandle &Ref = *N->Referrers.back();
440 Ref = DSNodeHandle(CurNodeH.getNode(), NOffset+Ref.getOffset());
441 }
442 NH = DSNodeHandle(N, OldNHOffset); // reset NH to point back to where it was
443
444 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
445
446 // Make all of the outgoing links of *NH now be outgoing links of
447 // this. This can cause recursive merging!
448 //
Chris Lattner6f6fef82003-01-22 22:00:24 +0000449 for (unsigned i = 0; i < NH.getNode()->getSize(); i += DS::PointerSize) {
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000450 DSNodeHandle &Link = NH.getNode()->getLink(i);
451 if (Link.getNode()) {
452 // Compute the offset into the current node at which to
453 // merge this link. In the common case, this is a linear
454 // relation to the offset in the original node (with
455 // wrapping), but if the current node gets collapsed due to
456 // recursive merging, we must make sure to merge in all remaining
457 // links at offset zero.
458 unsigned MergeOffset = 0;
459 if (CurNodeH.getNode()->Size != 1)
460 MergeOffset = (i+NOffset) % CurNodeH.getNode()->getSize();
461 CurNodeH.getNode()->addEdgeTo(MergeOffset, Link);
462 }
463 }
464
465 // Now that there are no outgoing edges, all of the Links are dead.
466 NH.getNode()->Links.clear();
467 NH.getNode()->Size = 0;
468 NH.getNode()->Ty = Type::VoidTy;
469
470 // Merge the node types
471 CurNodeH.getNode()->NodeType |= NH.getNode()->NodeType;
472 NH.getNode()->NodeType = DEAD; // NH is now a dead node.
473
474 // Merge the globals list...
475 if (!NH.getNode()->Globals.empty()) {
476 MergeSortedVectors(CurNodeH.getNode()->Globals, NH.getNode()->Globals);
477
478 // Delete the globals from the old node...
479 NH.getNode()->Globals.clear();
480 }
481}
482
483
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000484// mergeWith - Merge this node and the specified node, moving all links to and
485// from the argument node into the current node, deleting the node argument.
486// Offset indicates what offset the specified node is to be merged into the
487// current node.
488//
489// The specified node may be a null pointer (in which case, nothing happens).
490//
491void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
492 DSNode *N = NH.getNode();
493 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000494 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000495
Chris Lattner679e8e12002-11-08 21:27:12 +0000496 assert((N->NodeType & DSNode::DEAD) == 0);
497 assert((NodeType & DSNode::DEAD) == 0);
498 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
499
Chris Lattner02606632002-11-04 06:48:26 +0000500 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000501 // We cannot merge two pieces of the same node together, collapse the node
502 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000503 DEBUG(std::cerr << "Attempting to merge two chunks of"
504 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000505 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000506 return;
507 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000508
Chris Lattner5190ce82002-11-12 07:20:45 +0000509 // If both nodes are not at offset 0, make sure that we are merging the node
510 // at an later offset into the node with the zero offset.
511 //
512 if (Offset < NH.getOffset()) {
513 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
514 return;
515 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
516 // If the offsets are the same, merge the smaller node into the bigger node
517 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
518 return;
519 }
520
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000521 // Ok, now we can merge the two nodes. Use a static helper that works with
522 // two node handles, since "this" may get merged away at intermediate steps.
523 DSNodeHandle CurNodeH(this, Offset);
524 DSNodeHandle NHCopy(NH);
525 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000526}
527
Chris Lattner9de906c2002-10-20 22:11:44 +0000528//===----------------------------------------------------------------------===//
529// DSCallSite Implementation
530//===----------------------------------------------------------------------===//
531
Vikram S. Adve26b98262002-10-20 21:41:02 +0000532// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000533Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000534 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000535}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000536
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000537
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000538//===----------------------------------------------------------------------===//
539// DSGraph Implementation
540//===----------------------------------------------------------------------===//
541
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000542DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000543 PrintAuxCalls = false;
Chris Lattner41c04f72003-02-01 04:52:08 +0000544 hash_map<const DSNode*, DSNodeHandle> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000545 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000546}
547
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000548DSGraph::DSGraph(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000549 hash_map<const DSNode*, DSNodeHandle> &NodeMap)
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000550 : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000551 PrintAuxCalls = false;
Chris Lattnerc875f022002-11-03 21:27:48 +0000552 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000553}
554
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000555DSGraph::~DSGraph() {
556 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000557 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000558 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000559 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000560
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000561 // Drop all intra-node references, so that assertions don't fail...
562 std::for_each(Nodes.begin(), Nodes.end(),
563 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000564
565 // Delete all of the nodes themselves...
566 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
567}
568
Chris Lattner0d9bab82002-07-18 00:12:30 +0000569// dump - Allow inspection of graph in a debugger.
570void DSGraph::dump() const { print(std::cerr); }
571
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000572
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000573/// remapLinks - Change all of the Links in the current node according to the
574/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000575///
Chris Lattner41c04f72003-02-01 04:52:08 +0000576void DSNode::remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000577 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
578 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
579 Links[i].setNode(H.getNode());
580 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
581 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000582}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000583
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000584
Chris Lattner0d9bab82002-07-18 00:12:30 +0000585// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000586// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000587// filled into the OldValMap member. If StripAllocas is set to true, Alloca
588// markers are removed from the graph, as the graph is being cloned into a
589// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000590//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000591DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000592 hash_map<Value*, DSNodeHandle> &OldValMap,
593 hash_map<const DSNode*, DSNodeHandle> &OldNodeMap,
Chris Lattner679e8e12002-11-08 21:27:12 +0000594 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000595 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000596 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000597
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000598 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000599
600 // Duplicate all of the nodes, populating the node map...
601 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000602
603 // Remove alloca or mod/ref bits as specified...
604 unsigned clearBits = (CloneFlags & StripAllocaBit ? DSNode::AllocaNode : 0)
605 | (CloneFlags & StripModRefBits ? (DSNode::Modified | DSNode::Read) : 0);
606 clearBits |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000607 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000608 DSNode *Old = G.Nodes[i];
609 DSNode *New = new DSNode(*Old);
Chris Lattner1e883692003-02-03 20:08:51 +0000610 New->NodeType &= ~clearBits;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000611 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000612 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000613 }
614
Chris Lattner18552922002-11-18 21:44:46 +0000615#ifndef NDEBUG
616 Timer::addPeakMemoryMeasurement();
617#endif
618
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000619 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000620 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000621 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000622
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000623 // Copy the scalar map... merging all of the global nodes...
Chris Lattner41c04f72003-02-01 04:52:08 +0000624 for (hash_map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000625 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000626 DSNodeHandle &H = OldValMap[I->first];
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000627 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
628 H.setNode(MappedNode.getNode());
629 H.setOffset(I->second.getOffset()+MappedNode.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000630
631 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattner41c04f72003-02-01 04:52:08 +0000632 hash_map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000633 if (GVI != ScalarMap.end()) // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000634 GVI->second.mergeWith(H);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000635 else
Chris Lattnerc875f022002-11-03 21:27:48 +0000636 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000637 }
638 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000639
Chris Lattner679e8e12002-11-08 21:27:12 +0000640 if (!(CloneFlags & DontCloneCallNodes)) {
641 // Copy the function calls list...
642 unsigned FC = FunctionCalls.size(); // FirstCall
643 FunctionCalls.reserve(FC+G.FunctionCalls.size());
644 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
645 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000646 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000647
Chris Lattneracf491f2002-11-08 22:27:09 +0000648 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000649 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000650 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000651 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
652 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
653 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
654 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000655
Chris Lattner0d9bab82002-07-18 00:12:30 +0000656 // Return the returned node pointer...
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000657 DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
658 return DSNodeHandle(MappedRet.getNode(),
659 MappedRet.getOffset()+G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000660}
661
Chris Lattner076c1f92002-11-07 06:31:54 +0000662/// mergeInGraph - The method is used for merging graphs together. If the
663/// argument graph is not *this, it makes a clone of the specified graph, then
664/// merges the nodes specified in the call site with the formal arguments in the
665/// graph.
666///
667void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
Chris Lattner679e8e12002-11-08 21:27:12 +0000668 unsigned CloneFlags) {
Chris Lattner41c04f72003-02-01 04:52:08 +0000669 hash_map<Value*, DSNodeHandle> OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000670 DSNodeHandle RetVal;
Chris Lattner41c04f72003-02-01 04:52:08 +0000671 hash_map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000672
673 // If this is not a recursive call, clone the graph into this graph...
674 if (&Graph != this) {
675 // Clone the callee's graph into the current graph, keeping
676 // track of where scalars in the old graph _used_ to point,
677 // and of the new nodes matching nodes of the old graph.
Chris Lattner41c04f72003-02-01 04:52:08 +0000678 hash_map<const DSNode*, DSNodeHandle> OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000679
680 // The clone call may invalidate any of the vectors in the data
681 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner679e8e12002-11-08 21:27:12 +0000682 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
Chris Lattner076c1f92002-11-07 06:31:54 +0000683 ScalarMap = &OldValMap;
684 } else {
685 RetVal = getRetNode();
686 ScalarMap = &getScalarMap();
687 }
688
689 // Merge the return value with the return value of the context...
690 RetVal.mergeWith(CS.getRetVal());
691
692 // Resolve all of the function arguments...
693 Function &F = Graph.getFunction();
694 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000695
Chris Lattner076c1f92002-11-07 06:31:54 +0000696 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
697 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +0000698 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +0000699 ++AI;
700#ifndef NDEBUG
701 if (AI == F.aend())
702 std::cerr << "Bad call to Function: " << F.getName() << "\n";
703#endif
Chris Lattner076c1f92002-11-07 06:31:54 +0000704 }
Chris Lattner5d274582003-02-06 00:15:08 +0000705 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +0000706
707 // Add the link from the argument scalar to the provided value
708 DSNodeHandle &NH = (*ScalarMap)[AI];
709 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
710 NH.mergeWith(CS.getPtrArg(i));
711 }
712}
713
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000714
Chris Lattner0d9bab82002-07-18 00:12:30 +0000715// markIncompleteNodes - Mark the specified node as having contents that are not
716// known with the current analysis we have performed. Because a node makes all
717// of the nodes it can reach imcomplete if the node itself is incomplete, we
718// must recursively traverse the data structure graph, marking all reachable
719// nodes as incomplete.
720//
721static void markIncompleteNode(DSNode *N) {
722 // Stop recursion if no node, or if node already marked...
723 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
724
725 // Actually mark the node
726 N->NodeType |= DSNode::Incomplete;
727
728 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000729 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
730 if (DSNode *DSN = N->getLink(i).getNode())
731 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000732}
733
Chris Lattnere71ffc22002-11-11 03:36:55 +0000734static void markIncomplete(DSCallSite &Call) {
735 // Then the return value is certainly incomplete!
736 markIncompleteNode(Call.getRetVal().getNode());
737
738 // All objects pointed to by function arguments are incomplete!
739 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
740 markIncompleteNode(Call.getPtrArg(i).getNode());
741}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000742
743// markIncompleteNodes - Traverse the graph, identifying nodes that may be
744// modified by other functions that have not been resolved yet. This marks
745// nodes that are reachable through three sources of "unknownness":
746//
747// Global Variables, Function Calls, and Incoming Arguments
748//
749// For any node that may have unknown components (because something outside the
750// scope of current analysis may have modified it), the 'Incomplete' flag is
751// added to the NodeType.
752//
Chris Lattner394471f2003-01-23 22:05:33 +0000753void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000754 // Mark any incoming arguments as incomplete...
Chris Lattnere77f1452003-02-08 23:08:02 +0000755 if ((Flags & DSGraph::MarkFormalArgs) && Func && Func->getName() != "main")
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000756 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000757 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
758 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000759
760 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +0000761 if (!shouldPrintAuxCalls())
762 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
763 markIncomplete(FunctionCalls[i]);
764 else
765 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
766 markIncomplete(AuxFunctionCalls[i]);
767
Chris Lattner0d9bab82002-07-18 00:12:30 +0000768
Chris Lattner92673292002-11-02 00:13:20 +0000769 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000770 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000771 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000772 DSNode *N = Nodes[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000773 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
774 if (DSNode *DSN = N->getLink(i).getNode())
775 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000776 }
777}
778
Chris Lattneraa8146f2002-11-10 06:59:55 +0000779static inline void killIfUselessEdge(DSNodeHandle &Edge) {
780 if (DSNode *N = Edge.getNode()) // Is there an edge?
781 if (N->getReferrers().size() == 1) // Does it point to a lonely node?
782 if ((N->NodeType & ~DSNode::Incomplete) == 0 && // No interesting info?
Chris Lattner18552922002-11-18 21:44:46 +0000783 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +0000784 Edge.setNode(0); // Kill the edge!
785}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000786
Chris Lattneraa8146f2002-11-10 06:59:55 +0000787static inline bool nodeContainsExternalFunction(const DSNode *N) {
788 const std::vector<GlobalValue*> &Globals = N->getGlobals();
789 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
790 if (Globals[i]->isExternal())
791 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000792 return false;
793}
794
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000795static void removeIdenticalCalls(std::vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000796 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000797 // Remove trivially identical function calls
798 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +0000799 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
800
801 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +0000802 DSNode *LastCalleeNode = 0;
803 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000804 unsigned NumDuplicateCalls = 0;
805 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +0000806 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000807 DSCallSite &CS = Calls[i];
808
Chris Lattnere4258442002-11-11 21:35:38 +0000809 // If the Callee is a useless edge, this must be an unreachable call site,
810 // eliminate it.
Chris Lattner923fc052003-02-05 21:59:58 +0000811 if (CS.isIndirectCall() && CS.getCalleeNode()->getReferrers().size() == 1 &&
812 CS.getCalleeNode()->NodeType == 0) { // No useful info?
813 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +0000814 CS.swap(Calls.back());
815 Calls.pop_back();
816 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000817 } else {
Chris Lattnere4258442002-11-11 21:35:38 +0000818 // If the return value or any arguments point to a void node with no
819 // information at all in it, and the call node is the only node to point
820 // to it, remove the edge to the node (killing the node).
821 //
822 killIfUselessEdge(CS.getRetVal());
823 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
824 killIfUselessEdge(CS.getPtrArg(a));
825
826 // If this call site calls the same function as the last call site, and if
827 // the function pointer contains an external function, this node will
828 // never be resolved. Merge the arguments of the call node because no
829 // information will be lost.
830 //
Chris Lattner923fc052003-02-05 21:59:58 +0000831 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
832 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +0000833 ++NumDuplicateCalls;
834 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +0000835 if (LastCalleeNode)
836 LastCalleeContainsExternalFunction =
837 nodeContainsExternalFunction(LastCalleeNode);
838 else
839 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +0000840 }
841
842 if (LastCalleeContainsExternalFunction ||
843 // This should be more than enough context sensitivity!
844 // FIXME: Evaluate how many times this is tripped!
845 NumDuplicateCalls > 20) {
846 DSCallSite &OCS = Calls[i-1];
847 OCS.mergeWith(CS);
848
849 // The node will now be eliminated as a duplicate!
850 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
851 CS = OCS;
852 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
853 OCS = CS;
854 }
855 } else {
Chris Lattner923fc052003-02-05 21:59:58 +0000856 if (CS.isDirectCall()) {
857 LastCalleeFunc = CS.getCalleeFunc();
858 LastCalleeNode = 0;
859 } else {
860 LastCalleeNode = CS.getCalleeNode();
861 LastCalleeFunc = 0;
862 }
Chris Lattnere4258442002-11-11 21:35:38 +0000863 NumDuplicateCalls = 0;
864 }
Chris Lattneraa8146f2002-11-10 06:59:55 +0000865 }
866 }
867
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000868 Calls.erase(std::unique(Calls.begin(), Calls.end()),
869 Calls.end());
870
Chris Lattner33312f72002-11-08 01:21:07 +0000871 // Track the number of call nodes merged away...
872 NumCallNodesMerged += NumFns-Calls.size();
873
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000874 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000875 std::cerr << "Merged " << (NumFns-Calls.size())
876 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000877}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000878
Chris Lattneraa8146f2002-11-10 06:59:55 +0000879
Chris Lattnere2219762002-07-18 18:22:40 +0000880// removeTriviallyDeadNodes - After the graph has been constructed, this method
881// removes all unreachable nodes that are created because they got merged with
882// other nodes in the graph. These nodes will all be trivially unreachable, so
883// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000884//
Chris Lattnerf40f0a32002-11-09 22:07:02 +0000885void DSGraph::removeTriviallyDeadNodes() {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000886 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattneraa8146f2002-11-10 06:59:55 +0000887 removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
888
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000889 for (unsigned i = 0; i != Nodes.size(); ++i) {
890 DSNode *Node = Nodes[i];
891 if (!(Node->NodeType & ~(DSNode::Composition | DSNode::Array |
Chris Lattner923fc052003-02-05 21:59:58 +0000892 DSNode::DEAD))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000893 // This is a useless node if it has no mod/ref info (checked above),
894 // outgoing edges (which it cannot, as it is not modified in this
895 // context), and it has no incoming edges. If it is a global node it may
896 // have all of these properties and still have incoming edges, due to the
897 // scalar map, so we check those now.
898 //
899 if (Node->getReferrers().size() == Node->getGlobals().size()) {
900 std::vector<GlobalValue*> &Globals = Node->getGlobals();
901 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
902 ScalarMap.erase(Globals[j]);
903 Globals.clear();
904
905 Node->NodeType = DSNode::DEAD;
906 }
907 }
908
909 if ((Node->NodeType & ~DSNode::DEAD) == 0 &&
910 Node->getReferrers().empty()) { // This node is dead!
911 delete Node; // Free memory...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000912 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
913 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000914 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000915}
916
917
Chris Lattner5c7380e2003-01-29 21:10:20 +0000918/// markReachableNodes - This method recursively traverses the specified
919/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
920/// to the set, which allows it to only traverse visited nodes once.
921///
Chris Lattner41c04f72003-02-01 04:52:08 +0000922void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000923 if (this == 0) return;
Chris Lattner41c04f72003-02-01 04:52:08 +0000924 if (ReachableNodes.count(this)) return; // Already marked reachable
925 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +0000926
Chris Lattner5c7380e2003-01-29 21:10:20 +0000927 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
928 getLink(i).getNode()->markReachableNodes(ReachableNodes);
929}
930
Chris Lattner41c04f72003-02-01 04:52:08 +0000931void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000932 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +0000933 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +0000934
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000935 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
936 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +0000937}
938
Chris Lattnera1220af2003-02-01 06:17:02 +0000939// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
940// looking for a node that is marked alive. If an alive node is found, return
941// true, otherwise return false. If an alive node is reachable, this node is
942// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000943//
Chris Lattnera1220af2003-02-01 06:17:02 +0000944static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
945 hash_set<DSNode*> &Visited) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000946 if (N == 0) return false;
947
Chris Lattneraa8146f2002-11-10 06:59:55 +0000948 // If we know that this node is alive, return so!
949 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000950
Chris Lattneraa8146f2002-11-10 06:59:55 +0000951 // Otherwise, we don't think the node is alive yet, check for infinite
952 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +0000953 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +0000954 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000955
Chris Lattner08db7192002-11-06 06:20:27 +0000956 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattnera1220af2003-02-01 06:17:02 +0000957 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
958 N->markReachableNodes(Alive);
959 return true;
960 }
961 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000962}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000963
Chris Lattnera1220af2003-02-01 06:17:02 +0000964// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
965// alive nodes.
966//
Chris Lattner41c04f72003-02-01 04:52:08 +0000967static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
968 hash_set<DSNode*> &Visited) {
Chris Lattner923fc052003-02-05 21:59:58 +0000969 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
970 return true;
971 if (CS.isIndirectCall() &&
972 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +0000973 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000974 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
975 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +0000976 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000977 return false;
978}
979
Chris Lattnere2219762002-07-18 18:22:40 +0000980// removeDeadNodes - Use a more powerful reachability analysis to eliminate
981// subgraphs that are unreachable. This often occurs because the data
982// structure doesn't "escape" into it's caller, and thus should be eliminated
983// from the caller's graph entirely. This is only appropriate to use when
984// inlining graphs.
985//
Chris Lattner394471f2003-01-23 22:05:33 +0000986void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000987 // Reduce the amount of work we have to do... remove dummy nodes left over by
988 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +0000989 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000990
Chris Lattnere2219762002-07-18 18:22:40 +0000991 // FIXME: Merge nontrivially identical call nodes...
992
993 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +0000994 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000995 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000996
Chris Lattneraa8146f2002-11-10 06:59:55 +0000997 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner41c04f72003-02-01 04:52:08 +0000998 for (hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000999 E = ScalarMap.end(); I != E; ++I)
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001000 if (!isa<GlobalValue>(I->first))
Chris Lattner5c7380e2003-01-29 21:10:20 +00001001 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001002 else { // Keep track of global nodes
Chris Lattner394471f2003-01-23 22:05:33 +00001003 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001004 assert(I->second.getNode() && "Null global node?");
1005 }
Chris Lattnere2219762002-07-18 18:22:40 +00001006
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001007 // The return value is alive as well...
Chris Lattner5c7380e2003-01-29 21:10:20 +00001008 RetNode.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001009
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001010 // Mark any nodes reachable by primary calls as alive...
1011 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1012 FunctionCalls[i].markReachableNodes(Alive);
1013
1014 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001015 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001016 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1017 do {
1018 Visited.clear();
1019 // If any global nodes points to a non-global that is "alive", the global is
1020 // "alive" as well... Remov it from the GlobalNodes list so we only have
1021 // unreachable globals in the list.
1022 //
1023 Iterate = false;
1024 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1025 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1026 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1027 GlobalNodes.pop_back(); // Erase efficiently
1028 Iterate = true;
1029 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001030
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001031 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1032 if (!AuxFCallsAlive[i] &&
1033 CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1034 AuxFunctionCalls[i].markReachableNodes(Alive);
1035 AuxFCallsAlive[i] = true;
1036 Iterate = true;
1037 }
1038 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001039
1040 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001041 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001042 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1043 if (AuxFCallsAlive[i])
1044 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001045 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001046 assert(GlobalsGraph && "No globals graph available??");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001047 // Move the unreachable call nodes to the globals graph...
1048 GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1049 AuxFunctionCalls.begin()+CurIdx,
1050 AuxFunctionCalls.end());
1051 }
1052 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001053 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1054 AuxFunctionCalls.end());
1055
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001056 // At this point, any nodes which are visited, but not alive, are nodes which
1057 // should be moved to the globals graph. Loop over all nodes, eliminating
1058 // completely unreachable nodes, and moving visited nodes to the globals graph
1059 //
Chris Lattnere2219762002-07-18 18:22:40 +00001060 for (unsigned i = 0; i != Nodes.size(); ++i)
1061 if (!Alive.count(Nodes[i])) {
1062 DSNode *N = Nodes[i];
Chris Lattner5e7d0e22003-02-01 06:23:33 +00001063 std::swap(Nodes[i--], Nodes.back()); // move node to end of vector
1064 Nodes.pop_back(); // Erase node from alive list.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001065 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && // Not in TD pass
1066 Visited.count(N)) { // Visited but not alive?
1067 GlobalsGraph->Nodes.push_back(N); // Move node to globals graph
1068 } else { // Otherwise, delete the node
1069 assert(((N->NodeType & DSNode::GlobalNode) == 0 ||
1070 (Flags & DSGraph::RemoveUnreachableGlobals))
1071 && "Killing a global?");
1072 while (!N->getReferrers().empty()) // Rewrite referrers
1073 N->getReferrers().back()->setNode(0);
1074 delete N; // Usecount is zero
1075 }
Chris Lattnere2219762002-07-18 18:22:40 +00001076 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001077
1078 // Now that the nodes have either been deleted or moved to the globals graph,
1079 // loop over the scalarmap, updating the entries for globals...
1080 //
1081 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) { // Not in the TD pass?
1082 // In this array we start the remapping, which can cause merging. Because
1083 // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1084 // must always go through the ScalarMap (which contains DSNodeHandles [which
1085 // cannot be invalidated by merging]).
1086 //
1087 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1088 Value *G = GlobalNodes[i].first;
1089 hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(G);
1090 assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1091 assert(I->second.getNode() && "Global not pointing to anything?");
1092 assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1093 GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1094 assert(GlobalsGraph->ScalarMap[G].getNode() &&
1095 "Global not pointing to anything?");
1096 ScalarMap.erase(I);
1097 }
1098
1099 // Merging leaves behind silly nodes, we remove them to avoid polluting the
1100 // globals graph.
1101 GlobalsGraph->removeTriviallyDeadNodes();
1102 } else {
1103 // If we are in the top-down pass, remove all unreachable globals from the
1104 // ScalarMap...
1105 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1106 ScalarMap.erase(GlobalNodes[i].first);
1107 }
1108
1109 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001110}
1111
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001112void DSGraph::AssertGraphOK() const {
1113 for (hash_map<Value*, DSNodeHandle>::const_iterator I = ScalarMap.begin(),
1114 E = ScalarMap.end(); I != E; ++I) {
1115 assert(I->second.getNode() && "Null node in scalarmap!");
1116 AssertNodeInGraph(I->second.getNode());
1117 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1118 assert((I->second.getNode()->NodeType & DSNode::GlobalNode) &&
1119 "Global points to node, but node isn't global?");
1120 AssertNodeContainsGlobal(I->second.getNode(), GV);
1121 }
1122 }
1123 AssertCallNodesInGraph();
1124 AssertAuxCallNodesInGraph();
1125}
1126
1127
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001128#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001129//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001130// GlobalDSGraph Implementation
1131//===----------------------------------------------------------------------===//
1132
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001133#if 0
Chris Lattnerd18f3422002-11-03 21:24:04 +00001134// Bits used in the next function
1135static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1136
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001137// cloneGlobalInto - Clone the given global node and all its target links
1138// (and all their llinks, recursively).
1139//
1140DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
1141 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
1142
1143 // If a clone has already been created for GNode, return it.
1144 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
1145 if (ValMapEntry != 0)
1146 return ValMapEntry;
1147
1148 // Clone the node and update the ValMap.
1149 DSNode* NewNode = new DSNode(*GNode);
1150 ValMapEntry = NewNode; // j=0 case of loop below!
1151 Nodes.push_back(NewNode);
1152 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
1153 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
1154
1155 // Rewrite the links in the new node to point into the current graph.
1156 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
1157 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
1158
1159 return NewNode;
1160}
Chris Lattnerd18f3422002-11-03 21:24:04 +00001161
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001162// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1163// visible target links (and recursively their such links) into this graph.
1164// NodeCache maps the node being cloned to its clone in the Globals graph,
1165// in order to track cycles.
1166// GlobalsAreFinal is a flag that says whether it is safe to assume that
1167// an existing global node is complete. This is important to avoid
1168// reinserting all globals when inserting Calls to functions.
1169// This is a helper function for cloneGlobals and cloneCalls.
1170//
1171DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
Chris Lattner41c04f72003-02-01 04:52:08 +00001172 hash_map<const DSNode*, DSNode*> &NodeCache,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001173 bool GlobalsAreFinal) {
1174 if (OldNode == 0) return 0;
1175
1176 // The caller should check this is an external node. Just more efficient...
1177 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1178
1179 // If a clone has already been created for OldNode, return it.
1180 DSNode*& CacheEntry = NodeCache[OldNode];
1181 if (CacheEntry != 0)
1182 return CacheEntry;
1183
1184 // The result value...
1185 DSNode* NewNode = 0;
1186
1187 // If nodes already exist for any of the globals of OldNode,
1188 // merge all such nodes together since they are merged in OldNode.
1189 // If ValueCacheIsFinal==true, look for an existing node that has
1190 // an identical list of globals and return it if it exists.
1191 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001192 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001193 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001194 if (NewNode == 0) {
1195 NewNode = PrevNode; // first existing node found
1196 if (GlobalsAreFinal && j == 0)
1197 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1198 CacheEntry = NewNode;
1199 return NewNode;
1200 }
1201 }
1202 else if (NewNode != PrevNode) { // found another, different from prev
1203 // update ValMap *before* merging PrevNode into NewNode
1204 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
Chris Lattnerc875f022002-11-03 21:27:48 +00001205 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001206 NewNode->mergeWith(PrevNode);
1207 }
1208 } else if (NewNode != 0) {
Chris Lattnerc875f022002-11-03 21:27:48 +00001209 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001210 }
1211
1212 // If no existing node was found, clone the node and update the ValMap.
1213 if (NewNode == 0) {
1214 NewNode = new DSNode(*OldNode);
1215 Nodes.push_back(NewNode);
1216 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1217 NewNode->setLink(j, 0);
1218 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001219 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001220 }
1221 else
1222 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1223
1224 // Add the entry to NodeCache
1225 CacheEntry = NewNode;
1226
1227 // Rewrite the links in the new node to point into the current graph,
1228 // but only for links to external nodes. Set other links to NULL.
1229 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1230 DSNode* OldTarget = OldNode->getLink(j);
1231 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1232 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1233 if (NewNode->getLink(j))
1234 NewNode->getLink(j)->mergeWith(NewLink);
1235 else
1236 NewNode->setLink(j, NewLink);
1237 }
1238 }
1239
1240 // Remove all local markers
1241 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1242
1243 return NewNode;
1244}
1245
1246
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001247// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1248// links (and recursively their such links) into this graph.
1249//
1250void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
Chris Lattner41c04f72003-02-01 04:52:08 +00001251 hash_map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerb3416bc2003-02-01 04:01:21 +00001252 std::vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001253
1254 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1255
1256 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001257 DSCallSite& callCopy = FunctionCalls.back();
1258 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001259 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001260 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001261 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1262 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1263 : 0);
1264 }
1265
1266 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001267 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001268}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001269#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001270
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001271#endif