blob: a186525a402a7809d749eb8c84e28233dbec6d8b [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 Lattner58f98d02003-07-02 04:38:49 +000012#include "llvm/Assembly/Writer.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 Lattner18552922002-11-18 21:44:46 +000015#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000016#include <algorithm>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017
Chris Lattner08db7192002-11-06 06:20:27 +000018namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000019 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
20 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000021};
22
Chris Lattnerb1060432002-11-07 05:20:53 +000023namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000024 extern TargetData TD;
25}
Chris Lattnerb1060432002-11-07 05:20:53 +000026using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000027
Chris Lattner731b2d72003-02-13 19:09:00 +000028DSNode *DSNodeHandle::HandleForwarding() const {
29 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
30
31 // Handle node forwarding here!
32 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
33 Offset += N->ForwardNH.getOffset();
34
35 if (--N->NumReferrers == 0) {
36 // Removing the last referrer to the node, sever the forwarding link
37 N->stopForwarding();
38 }
39
40 N = Next;
41 N->NumReferrers++;
42 if (N->Size <= Offset) {
43 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
44 Offset = 0;
45 }
46 return N;
47}
48
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000049//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000050// DSNode Implementation
51//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000052
Chris Lattnerbd92b732003-06-19 21:15:11 +000053DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000054 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000055 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000056 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000057 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000058}
59
Chris Lattner0d9bab82002-07-18 00:12:30 +000060// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000061DSNode::DSNode(const DSNode &N, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000062 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner58f98d02003-07-02 04:38:49 +000063 Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner72d29a42003-02-11 23:11:51 +000064 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000065}
66
Chris Lattner72d29a42003-02-11 23:11:51 +000067void DSNode::assertOK() const {
68 assert((Ty != Type::VoidTy ||
69 Ty == Type::VoidTy && (Size == 0 ||
70 (NodeType & DSNode::Array))) &&
71 "Node not OK!");
72}
73
74/// forwardNode - Mark this node as being obsolete, and all references to it
75/// should be forwarded to the specified node and offset.
76///
77void DSNode::forwardNode(DSNode *To, unsigned Offset) {
78 assert(this != To && "Cannot forward a node to itself!");
79 assert(ForwardNH.isNull() && "Already forwarding from this node!");
80 if (To->Size <= 1) Offset = 0;
81 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
82 "Forwarded offset is wrong!");
83 ForwardNH.setNode(To);
84 ForwardNH.setOffset(Offset);
85 NodeType = DEAD;
86 Size = 0;
87 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000088}
89
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000090// addGlobal - Add an entry for a global value to the Globals list. This also
91// marks the node with the 'G' flag if it does not already have it.
92//
93void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000094 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +000095 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000096 std::lower_bound(Globals.begin(), Globals.end(), GV);
97
98 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000099 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000100 Globals.insert(I, GV);
101 NodeType |= GlobalNode;
102 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000103}
104
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000105/// foldNodeCompletely - If we determine that this node has some funny
106/// behavior happening to it that we cannot represent, we fold it down to a
107/// single, completely pessimistic, node. This node is represented as a
108/// single byte with a single TypeEntry of "void".
109///
110void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000111 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000112
Chris Lattner08db7192002-11-06 06:20:27 +0000113 ++NumFolds;
114
Chris Lattner72d29a42003-02-11 23:11:51 +0000115 // Create the node we are going to forward to...
Chris Lattner70793862003-07-02 23:57:05 +0000116 DSNode *DestNode = new DSNode(0, ParentGraph);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000117 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000118 DestNode->Ty = Type::VoidTy;
119 DestNode->Size = 1;
120 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000121
Chris Lattner72d29a42003-02-11 23:11:51 +0000122 // Start forwarding to the destination node...
123 forwardNode(DestNode, 0);
124
125 if (Links.size()) {
126 DestNode->Links.push_back(Links[0]);
127 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000128
Chris Lattner72d29a42003-02-11 23:11:51 +0000129 // If we have links, merge all of our outgoing links together...
130 for (unsigned i = Links.size()-1; i != 0; --i)
131 NH.getNode()->Links[0].mergeWith(Links[i]);
132 Links.clear();
133 } else {
134 DestNode->Links.resize(1);
135 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000136}
Chris Lattner076c1f92002-11-07 06:31:54 +0000137
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000138/// isNodeCompletelyFolded - Return true if this node has been completely
139/// folded down to something that can never be expanded, effectively losing
140/// all of the field sensitivity that may be present in the node.
141///
142bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000143 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000144}
145
146
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000147namespace {
148 /// TypeElementWalker Class - Used for implementation of physical subtyping...
149 ///
150 class TypeElementWalker {
151 struct StackState {
152 const Type *Ty;
153 unsigned Offset;
154 unsigned Idx;
155 StackState(const Type *T, unsigned Off = 0)
156 : Ty(T), Offset(Off), Idx(0) {}
157 };
158
159 std::vector<StackState> Stack;
160 public:
161 TypeElementWalker(const Type *T) {
162 Stack.push_back(T);
163 StepToLeaf();
164 }
165
166 bool isDone() const { return Stack.empty(); }
167 const Type *getCurrentType() const { return Stack.back().Ty; }
168 unsigned getCurrentOffset() const { return Stack.back().Offset; }
169
170 void StepToNextType() {
171 PopStackAndAdvance();
172 StepToLeaf();
173 }
174
175 private:
176 /// PopStackAndAdvance - Pop the current element off of the stack and
177 /// advance the underlying element to the next contained member.
178 void PopStackAndAdvance() {
179 assert(!Stack.empty() && "Cannot pop an empty stack!");
180 Stack.pop_back();
181 while (!Stack.empty()) {
182 StackState &SS = Stack.back();
183 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
184 ++SS.Idx;
185 if (SS.Idx != ST->getElementTypes().size()) {
186 const StructLayout *SL = TD.getStructLayout(ST);
187 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
188 return;
189 }
190 Stack.pop_back(); // At the end of the structure
191 } else {
192 const ArrayType *AT = cast<ArrayType>(SS.Ty);
193 ++SS.Idx;
194 if (SS.Idx != AT->getNumElements()) {
195 SS.Offset += TD.getTypeSize(AT->getElementType());
196 return;
197 }
198 Stack.pop_back(); // At the end of the array
199 }
200 }
201 }
202
203 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
204 /// on the type stack.
205 void StepToLeaf() {
206 if (Stack.empty()) return;
207 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
208 StackState &SS = Stack.back();
209 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
210 if (ST->getElementTypes().empty()) {
211 assert(SS.Idx == 0);
212 PopStackAndAdvance();
213 } else {
214 // Step into the structure...
215 assert(SS.Idx < ST->getElementTypes().size());
216 const StructLayout *SL = TD.getStructLayout(ST);
217 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
218 SS.Offset+SL->MemberOffsets[SS.Idx]));
219 }
220 } else {
221 const ArrayType *AT = cast<ArrayType>(SS.Ty);
222 if (AT->getNumElements() == 0) {
223 assert(SS.Idx == 0);
224 PopStackAndAdvance();
225 } else {
226 // Step into the array...
227 assert(SS.Idx < AT->getNumElements());
228 Stack.push_back(StackState(AT->getElementType(),
229 SS.Offset+SS.Idx*
230 TD.getTypeSize(AT->getElementType())));
231 }
232 }
233 }
234 }
235 };
236}
237
238/// ElementTypesAreCompatible - Check to see if the specified types are
239/// "physically" compatible. If so, return true, else return false. We only
240/// have to check the fields in T1: T2 may be larger than T1.
241///
242static bool ElementTypesAreCompatible(const Type *T1, const Type *T2) {
243 TypeElementWalker T1W(T1), T2W(T2);
244
245 while (!T1W.isDone() && !T2W.isDone()) {
246 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
247 return false;
248
249 const Type *T1 = T1W.getCurrentType();
250 const Type *T2 = T2W.getCurrentType();
251 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
252 return false;
253
254 T1W.StepToNextType();
255 T2W.StepToNextType();
256 }
257
258 return T1W.isDone();
259}
260
261
Chris Lattner08db7192002-11-06 06:20:27 +0000262/// mergeTypeInfo - This method merges the specified type into the current node
263/// at the specified offset. This may update the current node's type record if
264/// this gives more information to the node, it may do nothing to the node if
265/// this information is already known, or it may merge the node completely (and
266/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000267///
Chris Lattner08db7192002-11-06 06:20:27 +0000268/// This method returns true if the node is completely folded, otherwise false.
269///
Chris Lattner088b6392003-03-03 17:13:31 +0000270bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
271 bool FoldIfIncompatible) {
Chris Lattner08db7192002-11-06 06:20:27 +0000272 // Check to make sure the Size member is up-to-date. Size can be one of the
273 // following:
274 // Size = 0, Ty = Void: Nothing is known about this node.
275 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
276 // Size = 1, Ty = Void, Array = 1: The node is collapsed
277 // Otherwise, sizeof(Ty) = Size
278 //
Chris Lattner18552922002-11-18 21:44:46 +0000279 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
280 (Size == 0 && !Ty->isSized() && !isArray()) ||
281 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
282 (Size == 0 && !Ty->isSized() && !isArray()) ||
283 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000284 "Size member of DSNode doesn't match the type structure!");
285 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000286
Chris Lattner18552922002-11-18 21:44:46 +0000287 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000288 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000289
Chris Lattner08db7192002-11-06 06:20:27 +0000290 // Return true immediately if the node is completely folded.
291 if (isNodeCompletelyFolded()) return true;
292
Chris Lattner23f83dc2002-11-08 22:49:57 +0000293 // If this is an array type, eliminate the outside arrays because they won't
294 // be used anyway. This greatly reduces the size of large static arrays used
295 // as global variables, for example.
296 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000297 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000298 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
299 // FIXME: we might want to keep small arrays, but must be careful about
300 // things like: [2 x [10000 x int*]]
301 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000302 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000303 }
304
Chris Lattner08db7192002-11-06 06:20:27 +0000305 // Figure out how big the new type we're merging in is...
306 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
307
308 // Otherwise check to see if we can fold this type into the current node. If
309 // we can't, we fold the node completely, if we can, we potentially update our
310 // internal state.
311 //
Chris Lattner18552922002-11-18 21:44:46 +0000312 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000313 // If this is the first type that this node has seen, just accept it without
314 // question....
315 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000316 assert(!isArray() && "This shouldn't happen!");
317 Ty = NewTy;
318 NodeType &= ~Array;
319 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000320 Size = NewTySize;
321
322 // Calculate the number of outgoing links from this node.
323 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
324 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000325 }
Chris Lattner08db7192002-11-06 06:20:27 +0000326
327 // Handle node expansion case here...
328 if (Offset+NewTySize > Size) {
329 // It is illegal to grow this node if we have treated it as an array of
330 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000331 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000332 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000333 return true;
334 }
335
336 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000337 std::cerr << "UNIMP: Trying to merge a growth type into "
338 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000339 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000340 return true;
341 }
342
343 // Okay, the situation is nice and simple, we are trying to merge a type in
344 // at offset 0 that is bigger than our current type. Implement this by
345 // switching to the new type and then merge in the smaller one, which should
346 // hit the other code path here. If the other code path decides it's not
347 // ok, it will collapse the node as appropriate.
348 //
Chris Lattner18552922002-11-18 21:44:46 +0000349 const Type *OldTy = Ty;
350 Ty = NewTy;
351 NodeType &= ~Array;
352 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000353 Size = NewTySize;
354
355 // Must grow links to be the appropriate size...
356 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
357
358 // Merge in the old type now... which is guaranteed to be smaller than the
359 // "current" type.
360 return mergeTypeInfo(OldTy, 0);
361 }
362
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000363 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000364 "Cannot merge something into a part of our type that doesn't exist!");
365
Chris Lattner18552922002-11-18 21:44:46 +0000366 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000367 // type that starts at offset Offset.
368 //
369 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000370 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000371 while (O < Offset) {
372 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
373
374 switch (SubType->getPrimitiveID()) {
375 case Type::StructTyID: {
376 const StructType *STy = cast<StructType>(SubType);
377 const StructLayout &SL = *TD.getStructLayout(STy);
378
379 unsigned i = 0, e = SL.MemberOffsets.size();
380 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
381 /* empty */;
382
383 // The offset we are looking for must be in the i'th element...
384 SubType = STy->getElementTypes()[i];
385 O += SL.MemberOffsets[i];
386 break;
387 }
388 case Type::ArrayTyID: {
389 SubType = cast<ArrayType>(SubType)->getElementType();
390 unsigned ElSize = TD.getTypeSize(SubType);
391 unsigned Remainder = (Offset-O) % ElSize;
392 O = Offset-Remainder;
393 break;
394 }
395 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000396 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000397 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000398 }
399 }
400
401 assert(O == Offset && "Could not achieve the correct offset!");
402
403 // If we found our type exactly, early exit
404 if (SubType == NewTy) return false;
405
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000406 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
407
408 // Ok, we are getting desperate now. Check for physical subtyping, where we
409 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000410 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000411 SubTypeSize && SubTypeSize < 256 &&
412 ElementTypesAreCompatible(NewTy, SubType))
413 return false;
414
Chris Lattner08db7192002-11-06 06:20:27 +0000415 // Okay, so we found the leader type at the offset requested. Search the list
416 // of types that starts at this offset. If SubType is currently an array or
417 // structure, the type desired may actually be the first element of the
418 // composite type...
419 //
Chris Lattner18552922002-11-18 21:44:46 +0000420 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000421 while (SubType != NewTy) {
422 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000423 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000424 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000425 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000426 case Type::StructTyID: {
427 const StructType *STy = cast<StructType>(SubType);
428 const StructLayout &SL = *TD.getStructLayout(STy);
429 if (SL.MemberOffsets.size() > 1)
430 NextPadSize = SL.MemberOffsets[1];
431 else
432 NextPadSize = SubTypeSize;
433 NextSubType = STy->getElementTypes()[0];
434 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000435 break;
Chris Lattner18552922002-11-18 21:44:46 +0000436 }
Chris Lattner08db7192002-11-06 06:20:27 +0000437 case Type::ArrayTyID:
438 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000439 NextSubTypeSize = TD.getTypeSize(NextSubType);
440 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000441 break;
442 default: ;
443 // fall out
444 }
445
446 if (NextSubType == 0)
447 break; // In the default case, break out of the loop
448
Chris Lattner18552922002-11-18 21:44:46 +0000449 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000450 break; // Don't allow shrinking to a smaller type than NewTySize
451 SubType = NextSubType;
452 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000453 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000454 }
455
456 // If we found the type exactly, return it...
457 if (SubType == NewTy)
458 return false;
459
460 // Check to see if we have a compatible, but different type...
461 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000462 // Check to see if this type is obviously convertible... int -> uint f.e.
463 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000464 return false;
465
466 // Check to see if we have a pointer & integer mismatch going on here,
467 // loading a pointer as a long, for example.
468 //
469 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
470 NewTy->isInteger() && isa<PointerType>(SubType))
471 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000472 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
473 // We are accessing the field, plus some structure padding. Ignore the
474 // structure padding.
475 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000476 }
477
Chris Lattner58f98d02003-07-02 04:38:49 +0000478 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000479 if (getParentGraph()->getReturnNodes().size())
480 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000481 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
482 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
483 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
484 << "SubType: ";
485 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000486
Chris Lattner088b6392003-03-03 17:13:31 +0000487 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000488 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000489}
490
Chris Lattner08db7192002-11-06 06:20:27 +0000491
492
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000493// addEdgeTo - Add an edge from the current node to the specified node. This
494// can cause merging of nodes in the graph.
495//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000496void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000497 if (NH.getNode() == 0) return; // Nothing to do
498
Chris Lattner08db7192002-11-06 06:20:27 +0000499 DSNodeHandle &ExistingEdge = getLink(Offset);
500 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000501 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000502 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000503 } else { // No merging to perform...
504 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000505 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000506}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000507
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000508
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000509// MergeSortedVectors - Efficiently merge a vector into another vector where
510// duplicates are not allowed and both are sorted. This assumes that 'T's are
511// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000512//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000513static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
514 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000515 // By far, the most common cases will be the simple ones. In these cases,
516 // avoid having to allocate a temporary vector...
517 //
518 if (Src.empty()) { // Nothing to merge in...
519 return;
520 } else if (Dest.empty()) { // Just copy the result in...
521 Dest = Src;
522 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000523 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000524 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000525 std::lower_bound(Dest.begin(), Dest.end(), V);
526 if (I == Dest.end() || *I != Src[0]) // If not already contained...
527 Dest.insert(I, Src[0]);
528 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000529 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000530 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000531 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000532 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
533 if (I == Dest.end() || *I != Tmp) // If not already contained...
534 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000535
536 } else {
537 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000538 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000539
540 // Make space for all of the type entries now...
541 Dest.resize(Dest.size()+Src.size());
542
543 // Merge the two sorted ranges together... into Dest.
544 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
545
546 // Now erase any duplicate entries that may have accumulated into the
547 // vectors (because they were in both of the input sets)
548 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
549 }
550}
551
552
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000553// MergeNodes() - Helper function for DSNode::mergeWith().
554// This function does the hard work of merging two nodes, CurNodeH
555// and NH after filtering out trivial cases and making sure that
556// CurNodeH.offset >= NH.offset.
557//
558// ***WARNING***
559// Since merging may cause either node to go away, we must always
560// use the node-handles to refer to the nodes. These node handles are
561// automatically updated during merging, so will always provide access
562// to the correct node after a merge.
563//
564void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
565 assert(CurNodeH.getOffset() >= NH.getOffset() &&
566 "This should have been enforced in the caller.");
567
568 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
569 // respect to NH.Offset) is now zero. NOffset is the distance from the base
570 // of our object that N starts from.
571 //
572 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
573 unsigned NSize = NH.getNode()->getSize();
574
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000575 // If the two nodes are of different size, and the smaller node has the array
576 // bit set, collapse!
577 if (NSize != CurNodeH.getNode()->getSize()) {
578 if (NSize < CurNodeH.getNode()->getSize()) {
579 if (NH.getNode()->isArray())
580 NH.getNode()->foldNodeCompletely();
581 } else if (CurNodeH.getNode()->isArray()) {
582 NH.getNode()->foldNodeCompletely();
583 }
584 }
585
586 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000587 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000588 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000589 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000590
591 // If we are merging a node with a completely folded node, then both nodes are
592 // now completely folded.
593 //
594 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
595 if (!NH.getNode()->isNodeCompletelyFolded()) {
596 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000597 assert(NH.getNode() && NH.getOffset() == 0 &&
598 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000599 NOffset = NH.getOffset();
600 NSize = NH.getNode()->getSize();
601 assert(NOffset == 0 && NSize == 1);
602 }
603 } else if (NH.getNode()->isNodeCompletelyFolded()) {
604 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000605 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
606 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000607 NOffset = NH.getOffset();
608 NSize = NH.getNode()->getSize();
609 assert(NOffset == 0 && NSize == 1);
610 }
611
Chris Lattner72d29a42003-02-11 23:11:51 +0000612 DSNode *N = NH.getNode();
613 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000614 assert(!CurNodeH.getNode()->isDeadNode());
615
616 // Merge the NodeType information...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000617 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000618
Chris Lattner72d29a42003-02-11 23:11:51 +0000619 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000620 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000621 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000622
Chris Lattner72d29a42003-02-11 23:11:51 +0000623 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
624 //
625 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
626 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000627 if (Link.getNode()) {
628 // Compute the offset into the current node at which to
629 // merge this link. In the common case, this is a linear
630 // relation to the offset in the original node (with
631 // wrapping), but if the current node gets collapsed due to
632 // recursive merging, we must make sure to merge in all remaining
633 // links at offset zero.
634 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000635 DSNode *CN = CurNodeH.getNode();
636 if (CN->Size != 1)
637 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
638 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000639 }
640 }
641
642 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000643 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000644
645 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000646 if (!N->Globals.empty()) {
647 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000648
649 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000650 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000651 }
652}
653
654
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000655// mergeWith - Merge this node and the specified node, moving all links to and
656// from the argument node into the current node, deleting the node argument.
657// Offset indicates what offset the specified node is to be merged into the
658// current node.
659//
660// The specified node may be a null pointer (in which case, nothing happens).
661//
662void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
663 DSNode *N = NH.getNode();
664 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000665 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000666
Chris Lattnerbd92b732003-06-19 21:15:11 +0000667 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000668 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
669
Chris Lattner02606632002-11-04 06:48:26 +0000670 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000671 // We cannot merge two pieces of the same node together, collapse the node
672 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000673 DEBUG(std::cerr << "Attempting to merge two chunks of"
674 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000675 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000676 return;
677 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000678
Chris Lattner5190ce82002-11-12 07:20:45 +0000679 // If both nodes are not at offset 0, make sure that we are merging the node
680 // at an later offset into the node with the zero offset.
681 //
682 if (Offset < NH.getOffset()) {
683 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
684 return;
685 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
686 // If the offsets are the same, merge the smaller node into the bigger node
687 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
688 return;
689 }
690
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000691 // Ok, now we can merge the two nodes. Use a static helper that works with
692 // two node handles, since "this" may get merged away at intermediate steps.
693 DSNodeHandle CurNodeH(this, Offset);
694 DSNodeHandle NHCopy(NH);
695 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000696}
697
Chris Lattner9de906c2002-10-20 22:11:44 +0000698//===----------------------------------------------------------------------===//
699// DSCallSite Implementation
700//===----------------------------------------------------------------------===//
701
Vikram S. Adve26b98262002-10-20 21:41:02 +0000702// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000703Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000704 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000705}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000706
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000707
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000708//===----------------------------------------------------------------------===//
709// DSGraph Implementation
710//===----------------------------------------------------------------------===//
711
Chris Lattnera9d65662003-06-30 05:57:30 +0000712/// getFunctionNames - Return a space separated list of the name of the
713/// functions in this graph (if any)
714std::string DSGraph::getFunctionNames() const {
715 switch (getReturnNodes().size()) {
716 case 0: return "Globals graph";
717 case 1: return getReturnNodes().begin()->first->getName();
718 default:
719 std::string Return;
720 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
721 I != getReturnNodes().end(); ++I)
722 Return += I->first->getName() + " ";
723 Return.erase(Return.end()-1, Return.end()); // Remove last space character
724 return Return;
725 }
726}
727
728
Chris Lattner5a540632003-06-30 03:15:25 +0000729DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000730 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000731 NodeMapTy NodeMap;
732 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000733}
734
Chris Lattner5a540632003-06-30 03:15:25 +0000735DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
736 : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000737 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000738 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000739}
740
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000741DSGraph::~DSGraph() {
742 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000743 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000744 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +0000745 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000746
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000747 // Drop all intra-node references, so that assertions don't fail...
748 std::for_each(Nodes.begin(), Nodes.end(),
749 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000750
751 // Delete all of the nodes themselves...
752 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
753}
754
Chris Lattner0d9bab82002-07-18 00:12:30 +0000755// dump - Allow inspection of graph in a debugger.
756void DSGraph::dump() const { print(std::cerr); }
757
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000758
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000759/// remapLinks - Change all of the Links in the current node according to the
760/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000761///
Chris Lattner8d327672003-06-30 03:36:09 +0000762void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000763 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
764 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
765 Links[i].setNode(H.getNode());
766 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
767 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000768}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000769
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000770
Chris Lattner5a540632003-06-30 03:15:25 +0000771/// cloneInto - Clone the specified DSGraph into the current graph. The
772/// translated ScalarMap for the old function is filled into the OldValMap
773/// member, and the translated ReturnNodes map is returned into ReturnNodes.
774///
775/// The CloneFlags member controls various aspects of the cloning process.
776///
777void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
778 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
779 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000780 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000781 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000782
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000783 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000784
785 // Duplicate all of the nodes, populating the node map...
786 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000787
788 // Remove alloca or mod/ref bits as specified...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000789 unsigned BitsToClear =((CloneFlags & StripAllocaBit) ? DSNode::AllocaNode : 0)
790 | ((CloneFlags & StripModRefBits) ? (DSNode::Modified | DSNode::Read) : 0);
791 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000792 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000793 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000794 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000795 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000796 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000797 }
798
Chris Lattner18552922002-11-18 21:44:46 +0000799#ifndef NDEBUG
800 Timer::addPeakMemoryMeasurement();
801#endif
802
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000803 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000804 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000805 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000806
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000807 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000808 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000809 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000810 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000811 DSNodeHandle &H = OldValMap[I->first];
812 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
813 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000814
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000815 // If this is a global, add the global to this fn or merge if already exists
Chris Lattner7b1ceaa2003-06-30 05:18:26 +0000816 if (isa<GlobalValue>(I->first))
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000817 ScalarMap[I->first].mergeWith(H);
Chris Lattnercf15db32002-10-17 20:09:52 +0000818 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000819
Chris Lattner679e8e12002-11-08 21:27:12 +0000820 if (!(CloneFlags & DontCloneCallNodes)) {
821 // Copy the function calls list...
822 unsigned FC = FunctionCalls.size(); // FirstCall
823 FunctionCalls.reserve(FC+G.FunctionCalls.size());
824 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
825 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000826 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000827
Chris Lattneracf491f2002-11-08 22:27:09 +0000828 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000829 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000830 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000831 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
832 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
833 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
834 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000835
Chris Lattner5a540632003-06-30 03:15:25 +0000836 // Map the return node pointers over...
837 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
838 E = G.getReturnNodes().end(); I != E; ++I) {
839 const DSNodeHandle &Ret = I->second;
840 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
841 OldReturnNodes.insert(std::make_pair(I->first,
842 DSNodeHandle(MappedRet.getNode(),
843 MappedRet.getOffset()+Ret.getOffset())));
844 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000845}
846
Chris Lattner076c1f92002-11-07 06:31:54 +0000847/// mergeInGraph - The method is used for merging graphs together. If the
848/// argument graph is not *this, it makes a clone of the specified graph, then
849/// merges the nodes specified in the call site with the formal arguments in the
850/// graph.
851///
Chris Lattner9f930552003-06-30 05:27:18 +0000852void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
853 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000854 ScalarMapTy OldValMap, *ScalarMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000855 DSNodeHandle RetVal;
Chris Lattner076c1f92002-11-07 06:31:54 +0000856
857 // If this is not a recursive call, clone the graph into this graph...
858 if (&Graph != this) {
859 // Clone the callee's graph into the current graph, keeping
860 // track of where scalars in the old graph _used_ to point,
861 // and of the new nodes matching nodes of the old graph.
Chris Lattner5a540632003-06-30 03:15:25 +0000862 NodeMapTy OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000863
864 // The clone call may invalidate any of the vectors in the data
865 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner5a540632003-06-30 03:15:25 +0000866 ReturnNodesTy OldRetNodes;
867 cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
Chris Lattner58f98d02003-07-02 04:38:49 +0000868
869 // We need to map the arguments for the function to the cloned nodes old
870 // argument values. Do this now.
Chris Lattner5a540632003-06-30 03:15:25 +0000871 RetVal = OldRetNodes[&F];
Chris Lattner076c1f92002-11-07 06:31:54 +0000872 ScalarMap = &OldValMap;
873 } else {
Chris Lattner5a540632003-06-30 03:15:25 +0000874 RetVal = getReturnNodeFor(F);
Chris Lattner076c1f92002-11-07 06:31:54 +0000875 ScalarMap = &getScalarMap();
876 }
877
878 // Merge the return value with the return value of the context...
879 RetVal.mergeWith(CS.getRetVal());
880
881 // Resolve all of the function arguments...
Chris Lattner076c1f92002-11-07 06:31:54 +0000882 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000883
Chris Lattner076c1f92002-11-07 06:31:54 +0000884 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
885 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +0000886 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +0000887 ++AI;
888#ifndef NDEBUG
889 if (AI == F.aend())
890 std::cerr << "Bad call to Function: " << F.getName() << "\n";
891#endif
Chris Lattner076c1f92002-11-07 06:31:54 +0000892 }
Chris Lattner5d274582003-02-06 00:15:08 +0000893 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +0000894
895 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +0000896 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +0000897 DSNodeHandle &NH = (*ScalarMap)[AI];
898 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
899 NH.mergeWith(CS.getPtrArg(i));
900 }
901}
902
Chris Lattner58f98d02003-07-02 04:38:49 +0000903/// getCallSiteForArguments - Get the arguments and return value bindings for
904/// the specified function in the current graph.
905///
906DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
907 std::vector<DSNodeHandle> Args;
908
909 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
910 if (isPointerType(I->getType()))
911 Args.push_back(getScalarMap().find(I)->second);
912
913 return DSCallSite(*(CallInst*)0, getReturnNodeFor(F), &F, Args);
914}
915
916
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000917
Chris Lattner0d9bab82002-07-18 00:12:30 +0000918// markIncompleteNodes - Mark the specified node as having contents that are not
919// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +0000920// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +0000921// must recursively traverse the data structure graph, marking all reachable
922// nodes as incomplete.
923//
924static void markIncompleteNode(DSNode *N) {
925 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +0000926 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000927
928 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000929 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +0000930
931 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000932 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
933 if (DSNode *DSN = N->getLink(i).getNode())
934 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000935}
936
Chris Lattnere71ffc22002-11-11 03:36:55 +0000937static void markIncomplete(DSCallSite &Call) {
938 // Then the return value is certainly incomplete!
939 markIncompleteNode(Call.getRetVal().getNode());
940
941 // All objects pointed to by function arguments are incomplete!
942 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
943 markIncompleteNode(Call.getPtrArg(i).getNode());
944}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000945
946// markIncompleteNodes - Traverse the graph, identifying nodes that may be
947// modified by other functions that have not been resolved yet. This marks
948// nodes that are reachable through three sources of "unknownness":
949//
950// Global Variables, Function Calls, and Incoming Arguments
951//
952// For any node that may have unknown components (because something outside the
953// scope of current analysis may have modified it), the 'Incomplete' flag is
954// added to the NodeType.
955//
Chris Lattner394471f2003-01-23 22:05:33 +0000956void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000957 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +0000958 if (Flags & DSGraph::MarkFormalArgs)
959 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
960 FI != E; ++FI) {
961 Function &F = *FI->first;
962 if (F.getName() != "main")
963 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
964 if (isPointerType(I->getType()) &&
965 ScalarMap.find(I) != ScalarMap.end())
966 markIncompleteNode(ScalarMap[I].getNode());
967 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000968
969 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +0000970 if (!shouldPrintAuxCalls())
971 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
972 markIncomplete(FunctionCalls[i]);
973 else
974 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
975 markIncomplete(AuxFunctionCalls[i]);
976
Chris Lattner0d9bab82002-07-18 00:12:30 +0000977
Chris Lattner93d7a212003-02-09 18:41:49 +0000978 // Mark all global nodes as incomplete...
979 if ((Flags & DSGraph::IgnoreGlobals) == 0)
980 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +0000981 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +0000982 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000983}
984
Chris Lattneraa8146f2002-11-10 06:59:55 +0000985static inline void killIfUselessEdge(DSNodeHandle &Edge) {
986 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +0000987 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +0000988 // No interesting info?
989 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +0000990 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +0000991 Edge.setNode(0); // Kill the edge!
992}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000993
Chris Lattneraa8146f2002-11-10 06:59:55 +0000994static inline bool nodeContainsExternalFunction(const DSNode *N) {
995 const std::vector<GlobalValue*> &Globals = N->getGlobals();
996 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
997 if (Globals[i]->isExternal())
998 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000999 return false;
1000}
1001
Chris Lattner5a540632003-06-30 03:15:25 +00001002static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Chris Lattner18f07a12003-07-01 16:28:11 +00001003
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001004 // Remove trivially identical function calls
1005 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001006 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1007
1008 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001009 DSNode *LastCalleeNode = 0;
1010 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001011 unsigned NumDuplicateCalls = 0;
1012 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001013 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001014 DSCallSite &CS = Calls[i];
1015
Chris Lattnere4258442002-11-11 21:35:38 +00001016 // If the Callee is a useless edge, this must be an unreachable call site,
1017 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001018 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001019 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001020 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001021 CS.swap(Calls.back());
1022 Calls.pop_back();
1023 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001024 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001025 // If the return value or any arguments point to a void node with no
1026 // information at all in it, and the call node is the only node to point
1027 // to it, remove the edge to the node (killing the node).
1028 //
1029 killIfUselessEdge(CS.getRetVal());
1030 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1031 killIfUselessEdge(CS.getPtrArg(a));
1032
1033 // If this call site calls the same function as the last call site, and if
1034 // the function pointer contains an external function, this node will
1035 // never be resolved. Merge the arguments of the call node because no
1036 // information will be lost.
1037 //
Chris Lattner923fc052003-02-05 21:59:58 +00001038 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1039 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001040 ++NumDuplicateCalls;
1041 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001042 if (LastCalleeNode)
1043 LastCalleeContainsExternalFunction =
1044 nodeContainsExternalFunction(LastCalleeNode);
1045 else
1046 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001047 }
1048
Chris Lattner58f98d02003-07-02 04:38:49 +00001049#if 1
Chris Lattnere4258442002-11-11 21:35:38 +00001050 if (LastCalleeContainsExternalFunction ||
1051 // This should be more than enough context sensitivity!
1052 // FIXME: Evaluate how many times this is tripped!
1053 NumDuplicateCalls > 20) {
1054 DSCallSite &OCS = Calls[i-1];
1055 OCS.mergeWith(CS);
1056
1057 // The node will now be eliminated as a duplicate!
1058 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1059 CS = OCS;
1060 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1061 OCS = CS;
1062 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001063#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001064 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001065 if (CS.isDirectCall()) {
1066 LastCalleeFunc = CS.getCalleeFunc();
1067 LastCalleeNode = 0;
1068 } else {
1069 LastCalleeNode = CS.getCalleeNode();
1070 LastCalleeFunc = 0;
1071 }
Chris Lattnere4258442002-11-11 21:35:38 +00001072 NumDuplicateCalls = 0;
1073 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001074 }
1075 }
1076
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001077 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1078 Calls.end());
1079
Chris Lattner33312f72002-11-08 01:21:07 +00001080 // Track the number of call nodes merged away...
1081 NumCallNodesMerged += NumFns-Calls.size();
1082
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001083 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001084 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001085}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001086
Chris Lattneraa8146f2002-11-10 06:59:55 +00001087
Chris Lattnere2219762002-07-18 18:22:40 +00001088// removeTriviallyDeadNodes - After the graph has been constructed, this method
1089// removes all unreachable nodes that are created because they got merged with
1090// other nodes in the graph. These nodes will all be trivially unreachable, so
1091// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001092//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001093void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner5a540632003-06-30 03:15:25 +00001094 removeIdenticalCalls(FunctionCalls);
1095 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001096
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001097 for (unsigned i = 0; i != Nodes.size(); ++i) {
1098 DSNode *Node = Nodes[i];
Chris Lattner72d50a02003-06-28 21:58:28 +00001099 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001100 // This is a useless node if it has no mod/ref info (checked above),
1101 // outgoing edges (which it cannot, as it is not modified in this
1102 // context), and it has no incoming edges. If it is a global node it may
1103 // have all of these properties and still have incoming edges, due to the
1104 // scalar map, so we check those now.
1105 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001106 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001107 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001108
1109 // Loop through and make sure all of the globals are referring directly
1110 // to the node...
1111 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1112 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1113 assert(N == Node && "ScalarMap doesn't match globals list!");
1114 }
1115
Chris Lattnerbd92b732003-06-19 21:15:11 +00001116 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001117 if (Node->getNumReferrers() == Globals.size()) {
1118 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1119 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001120 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001121 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001122 }
1123 }
1124
Chris Lattnerbd92b732003-06-19 21:15:11 +00001125 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001126 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001127 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001128 Nodes[i--] = Nodes.back();
1129 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001130 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001131 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001132}
1133
1134
Chris Lattner5c7380e2003-01-29 21:10:20 +00001135/// markReachableNodes - This method recursively traverses the specified
1136/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1137/// to the set, which allows it to only traverse visited nodes once.
1138///
Chris Lattner41c04f72003-02-01 04:52:08 +00001139void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001140 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001141 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +00001142 if (ReachableNodes.count(this)) return; // Already marked reachable
1143 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +00001144
Chris Lattner5c7380e2003-01-29 21:10:20 +00001145 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1146 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1147}
1148
Chris Lattner41c04f72003-02-01 04:52:08 +00001149void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001150 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001151 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001152
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001153 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1154 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001155}
1156
Chris Lattnera1220af2003-02-01 06:17:02 +00001157// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1158// looking for a node that is marked alive. If an alive node is found, return
1159// true, otherwise return false. If an alive node is reachable, this node is
1160// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001161//
Chris Lattnera1220af2003-02-01 06:17:02 +00001162static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1163 hash_set<DSNode*> &Visited) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001164 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001165 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001166
Chris Lattneraa8146f2002-11-10 06:59:55 +00001167 // If we know that this node is alive, return so!
1168 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001169
Chris Lattneraa8146f2002-11-10 06:59:55 +00001170 // Otherwise, we don't think the node is alive yet, check for infinite
1171 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001172 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001173 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001174
Chris Lattner08db7192002-11-06 06:20:27 +00001175 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattnera1220af2003-02-01 06:17:02 +00001176 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
1177 N->markReachableNodes(Alive);
1178 return true;
1179 }
1180 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001181}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001182
Chris Lattnera1220af2003-02-01 06:17:02 +00001183// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1184// alive nodes.
1185//
Chris Lattner41c04f72003-02-01 04:52:08 +00001186static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1187 hash_set<DSNode*> &Visited) {
Chris Lattner923fc052003-02-05 21:59:58 +00001188 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
1189 return true;
1190 if (CS.isIndirectCall() &&
1191 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001192 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001193 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1194 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001195 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001196 return false;
1197}
1198
Chris Lattnere2219762002-07-18 18:22:40 +00001199// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1200// subgraphs that are unreachable. This often occurs because the data
1201// structure doesn't "escape" into it's caller, and thus should be eliminated
1202// from the caller's graph entirely. This is only appropriate to use when
1203// inlining graphs.
1204//
Chris Lattner394471f2003-01-23 22:05:33 +00001205void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001206 // Reduce the amount of work we have to do... remove dummy nodes left over by
1207 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001208 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001209
Chris Lattnere2219762002-07-18 18:22:40 +00001210 // FIXME: Merge nontrivially identical call nodes...
1211
1212 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001213 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001214 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001215
Chris Lattneraa8146f2002-11-10 06:59:55 +00001216 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner8d327672003-06-30 03:36:09 +00001217 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001218 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001219 assert(I->second.getNode() && "Null global node?");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001220 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1221 ++I;
1222 } else {
1223 // Check to see if this is a worthless node generated for non-pointer
1224 // values, such as integers. Consider an addition of long types: A+B.
1225 // Assuming we can track all uses of the value in this context, and it is
1226 // NOT used as a pointer, we can delete the node. We will be able to
1227 // detect this situation if the node pointed to ONLY has Unknown bit set
1228 // in the node. In this case, the node is not incomplete, does not point
1229 // to any other nodes (no mod/ref bits set), and is therefore
1230 // uninteresting for data structure analysis. If we run across one of
1231 // these, prune the scalar pointing to it.
1232 //
1233 DSNode *N = I->second.getNode();
Chris Lattnerbd92b732003-06-19 21:15:11 +00001234 if (N->isUnknownNode() && !isa<Argument>(I->first)) {
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001235 ScalarMap.erase(I++);
1236 } else {
1237 I->second.getNode()->markReachableNodes(Alive);
1238 ++I;
1239 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001240 }
Chris Lattnere2219762002-07-18 18:22:40 +00001241
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001242 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001243 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1244 I != E; ++I)
1245 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001246
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001247 // Mark any nodes reachable by primary calls as alive...
1248 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1249 FunctionCalls[i].markReachableNodes(Alive);
1250
1251 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001252 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001253 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1254 do {
1255 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001256 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001257 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001258 // unreachable globals in the list.
1259 //
1260 Iterate = false;
1261 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1262 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1263 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1264 GlobalNodes.pop_back(); // Erase efficiently
1265 Iterate = true;
1266 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001267
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001268 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1269 if (!AuxFCallsAlive[i] &&
1270 CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1271 AuxFunctionCalls[i].markReachableNodes(Alive);
1272 AuxFCallsAlive[i] = true;
1273 Iterate = true;
1274 }
1275 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001276
1277 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001278 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001279 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1280 if (AuxFCallsAlive[i])
1281 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001282 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001283 assert(GlobalsGraph && "No globals graph available??");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001284 // Move the unreachable call nodes to the globals graph...
1285 GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1286 AuxFunctionCalls.begin()+CurIdx,
1287 AuxFunctionCalls.end());
1288 }
1289 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001290 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1291 AuxFunctionCalls.end());
1292
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001293 // At this point, any nodes which are visited, but not alive, are nodes which
1294 // should be moved to the globals graph. Loop over all nodes, eliminating
1295 // completely unreachable nodes, and moving visited nodes to the globals graph
1296 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001297 std::vector<DSNode*> DeadNodes;
1298 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001299 for (unsigned i = 0; i != Nodes.size(); ++i)
1300 if (!Alive.count(Nodes[i])) {
1301 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001302 Nodes[i--] = Nodes.back(); // move node to end of vector
1303 Nodes.pop_back(); // Erase node from alive list.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001304 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && // Not in TD pass
1305 Visited.count(N)) { // Visited but not alive?
1306 GlobalsGraph->Nodes.push_back(N); // Move node to globals graph
Chris Lattner72d29a42003-02-11 23:11:51 +00001307 N->setParentGraph(GlobalsGraph);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001308 } else { // Otherwise, delete the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001309 assert((!N->isGlobalNode() ||
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001310 (Flags & DSGraph::RemoveUnreachableGlobals))
1311 && "Killing a global?");
Chris Lattner72d29a42003-02-11 23:11:51 +00001312 //std::cerr << "[" << i+1 << "/" << DeadNodes.size()
1313 // << "] Node is dead: "; N->dump();
1314 DeadNodes.push_back(N);
1315 N->dropAllReferences();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001316 }
Chris Lattner72d29a42003-02-11 23:11:51 +00001317 } else {
1318 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001319 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001320
1321 // Now that the nodes have either been deleted or moved to the globals graph,
1322 // loop over the scalarmap, updating the entries for globals...
1323 //
1324 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) { // Not in the TD pass?
1325 // In this array we start the remapping, which can cause merging. Because
1326 // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1327 // must always go through the ScalarMap (which contains DSNodeHandles [which
1328 // cannot be invalidated by merging]).
1329 //
1330 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1331 Value *G = GlobalNodes[i].first;
Chris Lattner8d327672003-06-30 03:36:09 +00001332 ScalarMapTy::iterator I = ScalarMap.find(G);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001333 assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1334 assert(I->second.getNode() && "Global not pointing to anything?");
1335 assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1336 GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1337 assert(GlobalsGraph->ScalarMap[G].getNode() &&
1338 "Global not pointing to anything?");
1339 ScalarMap.erase(I);
1340 }
1341
1342 // Merging leaves behind silly nodes, we remove them to avoid polluting the
1343 // globals graph.
Chris Lattner72d29a42003-02-11 23:11:51 +00001344 if (!GlobalNodes.empty())
1345 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001346 } else {
1347 // If we are in the top-down pass, remove all unreachable globals from the
1348 // ScalarMap...
1349 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1350 ScalarMap.erase(GlobalNodes[i].first);
1351 }
1352
Chris Lattner72d29a42003-02-11 23:11:51 +00001353 // Loop over all of the dead nodes now, deleting them since their referrer
1354 // count is zero.
1355 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1356 delete DeadNodes[i];
1357
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001358 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001359}
1360
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001361void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001362 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1363 Nodes[i]->assertOK();
1364 return; // FIXME: remove
Chris Lattner8d327672003-06-30 03:36:09 +00001365 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001366 E = ScalarMap.end(); I != E; ++I) {
1367 assert(I->second.getNode() && "Null node in scalarmap!");
1368 AssertNodeInGraph(I->second.getNode());
1369 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001370 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001371 "Global points to node, but node isn't global?");
1372 AssertNodeContainsGlobal(I->second.getNode(), GV);
1373 }
1374 }
1375 AssertCallNodesInGraph();
1376 AssertAuxCallNodesInGraph();
1377}